-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtoken_cmd_test.go
More file actions
441 lines (417 loc) · 11.8 KB
/
token_cmd_test.go
File metadata and controls
441 lines (417 loc) · 11.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
package main
import (
"bytes"
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
retry "github.com/appleboy/go-httpretry"
"github.com/go-authgate/sdk-go/credstore"
"github.com/go-authgate/sdk-go/oauth"
)
func TestRunTokenDelete(t *testing.T) {
tests := []struct {
name string
setup func(credstore.Store[credstore.Token])
wantCode int
checkOut func(t *testing.T, out string)
checkErr func(t *testing.T, errOut string)
postCheck func(t *testing.T, store credstore.Store[credstore.Token])
}{
{
name: "token exists delete succeeds",
setup: func(s credstore.Store[credstore.Token]) {
if err := s.Save("test-id", credstore.Token{
AccessToken: "my-access-token",
ExpiresAt: time.Now().Add(time.Hour),
ClientID: "test-id",
}); err != nil {
t.Fatalf("setup: failed to save token: %v", err)
}
},
wantCode: 0,
checkOut: func(t *testing.T, out string) {
if !strings.Contains(out, "deleted") {
t.Errorf("expected 'deleted' in stdout, got: %q", out)
}
},
},
{
name: "no token stored",
setup: func(s credstore.Store[credstore.Token]) {},
wantCode: 1,
checkErr: func(t *testing.T, errOut string) {
if !strings.Contains(errOut, "no stored token") {
t.Errorf("expected 'no stored token' in stderr, got: %q", errOut)
}
},
},
{
name: "delete then load returns not found",
setup: func(s credstore.Store[credstore.Token]) {
if err := s.Save("test-id", credstore.Token{
AccessToken: "my-access-token",
ExpiresAt: time.Now().Add(time.Hour),
ClientID: "test-id",
}); err != nil {
t.Fatalf("setup: failed to save token: %v", err)
}
},
wantCode: 0,
postCheck: func(t *testing.T, store credstore.Store[credstore.Token]) {
_, err := store.Load("test-id")
if !errors.Is(err, credstore.ErrNotFound) {
t.Errorf("expected ErrNotFound after delete, got: %v", err)
}
},
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
store := credstore.NewTokenFileStore(
filepath.Join(t.TempDir(), "tokens.json"),
)
tc.setup(store)
cfg := &AppConfig{ClientID: "test-id", Store: store}
var stdout, stderr bytes.Buffer
code := runTokenDelete(
context.Background(), cfg, true, &stdout, &stderr,
)
if code != tc.wantCode {
t.Errorf("exit code: got %d, want %d", code, tc.wantCode)
}
if tc.checkOut != nil {
tc.checkOut(t, stdout.String())
}
if tc.checkErr != nil {
tc.checkErr(t, stderr.String())
}
if tc.postCheck != nil {
tc.postCheck(t, store)
}
})
}
}
func TestRunTokenDelete_ServerRevocation(t *testing.T) {
t.Run("successful revocation and local delete", func(t *testing.T) {
type revokeCall struct {
token string
tokenTypeHint string
}
var revokeCalls []revokeCall
var mu sync.Mutex
srv := httptest.NewServer(
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, "bad form", http.StatusBadRequest)
return
}
mu.Lock()
revokeCalls = append(revokeCalls, revokeCall{
token: r.FormValue("token"),
tokenTypeHint: r.FormValue("token_type_hint"),
})
mu.Unlock()
w.WriteHeader(http.StatusOK)
}),
)
defer srv.Close()
rc, err := retry.NewClient()
if err != nil {
t.Fatal(err)
}
store := credstore.NewTokenFileStore(
filepath.Join(t.TempDir(), "tokens.json"),
)
if err := store.Save("test-id", credstore.Token{
AccessToken: "access-123",
RefreshToken: "refresh-456",
ExpiresAt: time.Now().Add(time.Hour),
ClientID: "test-id",
}); err != nil {
t.Fatal(err)
}
cfg := &AppConfig{
ClientID: "test-id",
ServerURL: srv.URL,
Endpoints: oauth.Endpoints{RevocationURL: srv.URL + "/oauth/revoke"},
RevocationTimeout: defaultRevocationTimeout,
RetryClient: rc,
Store: store,
}
var stdout, stderr bytes.Buffer
code := runTokenDelete(
context.Background(), cfg, false, &stdout, &stderr,
)
if code != 0 {
t.Fatalf("exit code: got %d, want 0; stderr: %s", code, stderr.String())
}
if !strings.Contains(stdout.String(), "revoked on server") {
t.Errorf("expected 'revoked on server' in stdout, got: %q", stdout.String())
}
if !strings.Contains(stdout.String(), "deleted") {
t.Errorf("expected 'deleted' in stdout, got: %q", stdout.String())
}
mu.Lock()
defer mu.Unlock()
if len(revokeCalls) != 2 {
t.Fatalf("expected 2 revoke calls, got %d", len(revokeCalls))
}
// Revocations run concurrently, so order is non-deterministic.
// Build a map from token to its type hint for assertion.
hintByToken := make(map[string]string, len(revokeCalls))
for _, c := range revokeCalls {
hintByToken[c.token] = c.tokenTypeHint
}
if hint, ok := hintByToken["refresh-456"]; !ok {
t.Errorf("expected refresh token to be revoked, got %v", revokeCalls)
} else if hint != "refresh_token" {
t.Errorf("refresh token_type_hint: got %q, want %q", hint, "refresh_token")
}
if hint, ok := hintByToken["access-123"]; !ok {
t.Errorf("expected access token to be revoked, got %v", revokeCalls)
} else if hint != "access_token" {
t.Errorf("access token_type_hint: got %q, want %q", hint, "access_token")
}
})
t.Run("server error graceful degradation", func(t *testing.T) {
srv := httptest.NewServer(
http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
}),
)
defer srv.Close()
rc, err := retry.NewClient()
if err != nil {
t.Fatal(err)
}
store := credstore.NewTokenFileStore(
filepath.Join(t.TempDir(), "tokens.json"),
)
if err := store.Save("test-id", credstore.Token{
AccessToken: "access-123",
ExpiresAt: time.Now().Add(time.Hour),
ClientID: "test-id",
}); err != nil {
t.Fatal(err)
}
cfg := &AppConfig{
ClientID: "test-id",
ServerURL: srv.URL,
Endpoints: oauth.Endpoints{RevocationURL: srv.URL + "/oauth/revoke"},
RevocationTimeout: defaultRevocationTimeout,
RetryClient: rc,
Store: store,
}
var stdout, stderr bytes.Buffer
code := runTokenDelete(
context.Background(), cfg, false, &stdout, &stderr,
)
if code != 0 {
t.Fatalf("exit code: got %d, want 0", code)
}
if !strings.Contains(stderr.String(), "Warning") {
t.Errorf("expected warning in stderr, got: %q", stderr.String())
}
if !strings.Contains(stdout.String(), "deleted") {
t.Errorf("token should still be deleted locally, got: %q", stdout.String())
}
})
t.Run("local-only skips server call", func(t *testing.T) {
var serverCalled atomic.Bool
srv := httptest.NewServer(
http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
serverCalled.Store(true)
w.WriteHeader(http.StatusOK)
}),
)
defer srv.Close()
rc, err := retry.NewClient()
if err != nil {
t.Fatal(err)
}
store := credstore.NewTokenFileStore(
filepath.Join(t.TempDir(), "tokens.json"),
)
if err := store.Save("test-id", credstore.Token{
AccessToken: "access-123",
ExpiresAt: time.Now().Add(time.Hour),
ClientID: "test-id",
}); err != nil {
t.Fatal(err)
}
cfg := &AppConfig{
ClientID: "test-id",
Endpoints: oauth.Endpoints{RevocationURL: srv.URL + "/oauth/revoke"},
RevocationTimeout: defaultRevocationTimeout,
RetryClient: rc,
Store: store,
}
var stdout, stderr bytes.Buffer
code := runTokenDelete(
context.Background(), cfg, true, &stdout, &stderr,
)
if code != 0 {
t.Fatalf("exit code: got %d, want 0", code)
}
if serverCalled.Load() {
t.Error("server should not have been called with --local-only")
}
})
t.Run("only access token no refresh token", func(t *testing.T) {
var (
callCount int
gotToken string
gotTokenTypeHint string
mu sync.Mutex
)
srv := httptest.NewServer(
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, "bad form", http.StatusBadRequest)
return
}
mu.Lock()
callCount++
gotToken = r.FormValue("token")
gotTokenTypeHint = r.FormValue("token_type_hint")
mu.Unlock()
w.WriteHeader(http.StatusOK)
}),
)
defer srv.Close()
rc, err := retry.NewClient()
if err != nil {
t.Fatal(err)
}
store := credstore.NewTokenFileStore(
filepath.Join(t.TempDir(), "tokens.json"),
)
if err := store.Save("test-id", credstore.Token{
AccessToken: "access-only",
ExpiresAt: time.Now().Add(time.Hour),
ClientID: "test-id",
}); err != nil {
t.Fatal(err)
}
cfg := &AppConfig{
ClientID: "test-id",
ServerURL: srv.URL,
Endpoints: oauth.Endpoints{RevocationURL: srv.URL + "/oauth/revoke"},
RevocationTimeout: defaultRevocationTimeout,
RetryClient: rc,
Store: store,
}
var stdout, stderr bytes.Buffer
code := runTokenDelete(
context.Background(), cfg, false, &stdout, &stderr,
)
if code != 0 {
t.Fatalf("exit code: got %d, want 0", code)
}
mu.Lock()
defer mu.Unlock()
if callCount != 1 {
t.Fatalf("expected 1 revoke call (access only), got %d", callCount)
}
if gotToken != "access-only" {
t.Errorf("token: got %q, want %q", gotToken, "access-only")
}
if gotTokenTypeHint != "access_token" {
t.Errorf("token_type_hint: got %q, want %q", gotTokenTypeHint, "access_token")
}
})
}
func TestRunTokenGet(t *testing.T) {
tests := []struct {
name string
setup func(credstore.Store[credstore.Token])
jsonOut bool
wantCode int
checkOut func(t *testing.T, out string)
checkErr func(t *testing.T, errOut string)
}{
{
name: "token found plain output",
setup: func(s credstore.Store[credstore.Token]) {
if err := s.Save("test-id", credstore.Token{
AccessToken: "my-access-token",
ExpiresAt: time.Now().Add(time.Hour),
ClientID: "test-id",
}); err != nil {
t.Fatalf("setup: failed to save token: %v", err)
}
},
jsonOut: false,
wantCode: 0,
checkOut: func(t *testing.T, out string) {
if out != "my-access-token\n" {
t.Errorf("got %q, want %q", out, "my-access-token\n")
}
},
},
{
name: "token found json output",
setup: func(s credstore.Store[credstore.Token]) {
if err := s.Save("test-id", credstore.Token{
AccessToken: "my-access-token",
ExpiresAt: time.Now().Add(time.Hour),
ClientID: "test-id",
}); err != nil {
t.Fatalf("setup: failed to save token: %v", err)
}
},
jsonOut: true,
wantCode: 0,
checkOut: func(t *testing.T, out string) {
var result tokenGetOutput
if err := json.Unmarshal([]byte(out), &result); err != nil {
t.Fatalf("invalid JSON: %v", err)
}
if result.AccessToken != "my-access-token" {
t.Errorf("access_token: got %q", result.AccessToken)
}
if result.Expired {
t.Error("expected expired=false")
}
},
},
{
name: "no token stored",
setup: func(s credstore.Store[credstore.Token]) {},
jsonOut: false,
wantCode: 1,
checkErr: func(t *testing.T, errOut string) {
if !strings.Contains(errOut, "no stored token") {
t.Errorf("expected 'no stored token' in stderr, got: %q", errOut)
}
},
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
store := credstore.NewTokenFileStore(
filepath.Join(t.TempDir(), "tokens.json"),
)
tc.setup(store)
var stdout, stderr bytes.Buffer
code := runTokenGet(store, "test-id", tc.jsonOut, &stdout, &stderr)
if code != tc.wantCode {
t.Errorf("exit code: got %d, want %d", code, tc.wantCode)
}
if tc.checkOut != nil {
tc.checkOut(t, stdout.String())
}
if tc.checkErr != nil {
tc.checkErr(t, stderr.String())
}
})
}
}