|
| 1 | +package auth |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "errors" |
| 6 | + "fmt" |
| 7 | + "io" |
| 8 | + "net/http" |
| 9 | + "net/http/httptest" |
| 10 | + "strings" |
| 11 | + "sync/atomic" |
| 12 | + "testing" |
| 13 | + "time" |
| 14 | + |
| 15 | + "github.com/cipherstash/stack/languages/golang/internal/guest" |
| 16 | + "github.com/tetratelabs/wazero/api" |
| 17 | +) |
| 18 | + |
| 19 | +// A profile serves every strategy, and through them every encrypt client, |
| 20 | +// in a process: a request cancelled while its token is fetched must fail |
| 21 | +// on its own and leave the profile open for the next. |
| 22 | + |
| 23 | +// tokenServer answers the access-key exchange, holding each request until |
| 24 | +// the client gives up while hold is set. |
| 25 | +func tokenServer(t *testing.T, hold *atomic.Bool) *httptest.Server { |
| 26 | + t.Helper() |
| 27 | + var jwt string |
| 28 | + // A request the client never cancels is let go at the end, so a |
| 29 | + // failure reports itself rather than hanging the server's Close. |
| 30 | + done := make(chan struct{}) |
| 31 | + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 32 | + if hold.Load() { |
| 33 | + // The server notices a client that hung up only once the body |
| 34 | + // is read. |
| 35 | + _, _ = io.Copy(io.Discard, r.Body) |
| 36 | + select { |
| 37 | + case <-r.Context().Done(): |
| 38 | + case <-done: |
| 39 | + t.Error("a held request was never cancelled") |
| 40 | + } |
| 41 | + return |
| 42 | + } |
| 43 | + fmt.Fprintf(w, `{"accessToken":%q,"expiry":%d}`, jwt, time.Now().Add(time.Hour).Unix()) |
| 44 | + })) |
| 45 | + t.Cleanup(server.Close) |
| 46 | + t.Cleanup(func() { close(done) }) |
| 47 | + jwt = testJWT(t, server.URL) |
| 48 | + return server |
| 49 | +} |
| 50 | + |
| 51 | +func TestATokenFetchCancelledFailsOnlyItself(t *testing.T) { |
| 52 | + guestOrSkip(t) |
| 53 | + var hold atomic.Bool |
| 54 | + server := tokenServer(t, &hold) |
| 55 | + profile, err := Open(context.Background(), t.TempDir()) |
| 56 | + if err != nil { |
| 57 | + t.Fatal(err) |
| 58 | + } |
| 59 | + defer profile.Close() |
| 60 | + strategy, err := profile.AccessKey(context.Background(), testCRN, "CSAKtestKeyId.testKeySecret", WithBaseURL(server.URL)) |
| 61 | + if err != nil { |
| 62 | + t.Fatal(err) |
| 63 | + } |
| 64 | + defer strategy.Close() |
| 65 | + |
| 66 | + hold.Store(true) |
| 67 | + ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) |
| 68 | + defer cancel() |
| 69 | + if _, err := strategy.Token(ctx); !errors.Is(err, context.DeadlineExceeded) { |
| 70 | + t.Fatalf("cancelled Token: %v, want the deadline", err) |
| 71 | + } |
| 72 | + if profile.root.closed || profile.root.inst.module.IsClosed() { |
| 73 | + t.Fatal("the profile was closed") |
| 74 | + } |
| 75 | + hold.Store(false) |
| 76 | + if token, err := strategy.Token(context.Background()); err != nil || token == "" { |
| 77 | + t.Fatalf("the next Token: %q, %v", token, err) |
| 78 | + } |
| 79 | +} |
| 80 | + |
| 81 | +// A refresh runs on after its caller gives up, so the guest call under it |
| 82 | +// can succeed after the caller's context ended. It still fails with the |
| 83 | +// context's error; what the refresh brought is kept for the next call. |
| 84 | +func TestARefreshThatSucceedsAfterItsContextEndsFailsWithIt(t *testing.T) { |
| 85 | + guestOrSkip(t) |
| 86 | + dir, _ := expiredDeviceProfile(t) |
| 87 | + ctx, cancel := context.WithCancel(context.Background()) |
| 88 | + defer cancel() |
| 89 | + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 90 | + _, _ = io.Copy(io.Discard, r.Body) |
| 91 | + cancel() |
| 92 | + fmt.Fprint(w, `{"access_token":"fresh","token_type":"Bearer","expires_in":3600,"refresh_token":"refresh-2"}`) |
| 93 | + })) |
| 94 | + t.Cleanup(server.Close) |
| 95 | + profile, err := Open(context.Background(), dir) |
| 96 | + if err != nil { |
| 97 | + t.Fatal(err) |
| 98 | + } |
| 99 | + defer profile.Close() |
| 100 | + ws, err := profile.WorkspaceStore(context.Background(), wsA) |
| 101 | + if err != nil { |
| 102 | + t.Fatal(err) |
| 103 | + } |
| 104 | + strategy, err := ws.DeviceSession(context.Background(), WithBaseURL(server.URL)) |
| 105 | + if err != nil { |
| 106 | + t.Fatal(err) |
| 107 | + } |
| 108 | + defer strategy.Close() |
| 109 | + |
| 110 | + out, err := strategy.store.callArgs(withRefresh(ctx), func(i *instance) api.Function { return i.authRefresh }, guest.BufArg([]byte(strategy.handle))) |
| 111 | + if !errors.Is(err, context.Canceled) || out != nil { |
| 112 | + t.Fatalf("refresh: %q, %v, want no token and context.Canceled", out, err) |
| 113 | + } |
| 114 | + if token, err := strategy.Token(context.Background()); err != nil || token != "fresh" { |
| 115 | + t.Fatalf("the next Token: %q, %v, want the refreshed token", token, err) |
| 116 | + } |
| 117 | +} |
| 118 | + |
| 119 | +func TestATokenRequestWhoseContextEndsInTheQueueNeverReachesTheGuest(t *testing.T) { |
| 120 | + guestOrSkip(t) |
| 121 | + var hold atomic.Bool |
| 122 | + server := tokenServer(t, &hold) |
| 123 | + profile, err := Open(context.Background(), t.TempDir()) |
| 124 | + if err != nil { |
| 125 | + t.Fatal(err) |
| 126 | + } |
| 127 | + defer profile.Close() |
| 128 | + strategy, err := profile.AccessKey(context.Background(), testCRN, "CSAKtestKeyId.testKeySecret", WithBaseURL(server.URL)) |
| 129 | + if err != nil { |
| 130 | + t.Fatal(err) |
| 131 | + } |
| 132 | + defer strategy.Close() |
| 133 | + |
| 134 | + for name, lock := range map[string]interface { |
| 135 | + Acquire(context.Context) error |
| 136 | + Unlock() |
| 137 | + }{"the strategy's": &strategy.mu, "the profile's": &profile.root.mu} { |
| 138 | + t.Run(name, func(t *testing.T) { |
| 139 | + if err := lock.Acquire(context.Background()); err != nil { |
| 140 | + t.Fatal(err) |
| 141 | + } |
| 142 | + released := make(chan struct{}) |
| 143 | + time.AfterFunc(200*time.Millisecond, func() { lock.Unlock(); close(released) }) |
| 144 | + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond) |
| 145 | + defer cancel() |
| 146 | + if _, err := strategy.Token(ctx); !errors.Is(err, context.DeadlineExceeded) { |
| 147 | + t.Fatalf("queued Token: %v, want the deadline", err) |
| 148 | + } |
| 149 | + <-released |
| 150 | + }) |
| 151 | + } |
| 152 | + if token, err := strategy.Token(context.Background()); err != nil || token == "" { |
| 153 | + t.Fatalf("the next Token: %q, %v", token, err) |
| 154 | + } |
| 155 | +} |
| 156 | + |
| 157 | +// The backstop: a call still running long after its caller gave up closes |
| 158 | +// the profile, and says so. |
| 159 | +func TestATokenFetchThatRunsOnAfterItsContextEndsClosesTheProfile(t *testing.T) { |
| 160 | + guestOrSkip(t) |
| 161 | + profile, err := Open(context.Background(), t.TempDir(), WithRoundTripper(roundTripFunc(func(*http.Request) (*http.Response, error) { |
| 162 | + // A RoundTripper that ignores the request's context. |
| 163 | + time.Sleep(300 * time.Millisecond) |
| 164 | + return nil, errors.New("too late") |
| 165 | + }))) |
| 166 | + if err != nil { |
| 167 | + t.Fatal(err) |
| 168 | + } |
| 169 | + defer profile.Close() |
| 170 | + strategy, err := profile.AccessKey(context.Background(), testCRN, "CSAKtestKeyId.testKeySecret", WithBaseURL("https://cts.example.com")) |
| 171 | + if err != nil { |
| 172 | + t.Fatal(err) |
| 173 | + } |
| 174 | + defer strategy.Close() |
| 175 | + profile.root.stuck = 20 * time.Millisecond |
| 176 | + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond) |
| 177 | + defer cancel() |
| 178 | + if _, err := strategy.Token(ctx); err == nil || !strings.Contains(err.Error(), "the profile is closed") { |
| 179 | + t.Fatalf("stuck Token: %v, want the profile closed", err) |
| 180 | + } |
| 181 | + if _, err := strategy.Token(context.Background()); !errors.Is(err, ErrState) { |
| 182 | + t.Fatalf("a Token after the close: %v, want ErrState", err) |
| 183 | + } |
| 184 | +} |
0 commit comments