-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain_test.go
More file actions
661 lines (594 loc) · 16.5 KB
/
main_test.go
File metadata and controls
661 lines (594 loc) · 16.5 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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
package main
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
retry "github.com/appleboy/go-httpretry"
"github.com/go-authgate/device-cli/tui"
"github.com/go-authgate/sdk-go/credstore"
)
func init() {
// Set default values for tests (don't call initConfig to avoid flag parsing)
if serverURL == "" {
serverURL = "http://localhost:8080"
}
if clientID == "" {
clientID = "test-client"
}
if tokenFile == "" {
tokenFile = ".authgate-tokens.json" //nolint:gosec // token file path is not a credential
}
// Initialize tokenStore for tests
if tokenStore == nil {
tokenStore = credstore.NewTokenFileStore(tokenFile)
}
// Initialize retryClient for tests
if retryClient == nil {
var err error
retryClient, err = retry.NewClient()
if err != nil {
panic(fmt.Sprintf("failed to create retry client: %v", err))
}
}
}
func TestSaveTokens_ConcurrentWrites(t *testing.T) {
tempDir := t.TempDir()
tokenFile = filepath.Join(tempDir, "tokens.json")
store := credstore.NewTokenFileStore(tokenFile)
const goroutines = 10
var wg sync.WaitGroup
wg.Add(goroutines)
for i := range goroutines {
go func(id int) {
defer wg.Done()
cID := fmt.Sprintf("client-%d", id)
storage := credstore.Token{
AccessToken: fmt.Sprintf("access-token-%d", id),
RefreshToken: fmt.Sprintf("refresh-token-%d", id),
TokenType: "Bearer",
ExpiresAt: time.Now().Add(1 * time.Hour),
ClientID: cID,
}
if err := store.Save(cID, storage); err != nil {
t.Errorf("Goroutine %d: Failed to save tokens: %v", id, err)
}
}(i)
}
wg.Wait()
// Verify all tokens were saved
for i := range goroutines {
cID := fmt.Sprintf("client-%d", i)
loaded, err := store.Load(cID)
if err != nil {
t.Errorf("Load(%s) error = %v", cID, err)
continue
}
expectedAccessToken := fmt.Sprintf("access-token-%d", i)
if loaded.AccessToken != expectedAccessToken {
t.Errorf(
"Client %s: Expected access token %s, got %s",
cID,
expectedAccessToken,
loaded.AccessToken,
)
}
}
// Verify no lock files remain
lockPath := tokenFile + ".lock"
if _, err := os.Stat(lockPath); !os.IsNotExist(err) {
t.Errorf("Lock file still exists after all saves completed")
}
}
func TestSaveTokens_PreservesOtherClients(t *testing.T) {
tempDir := t.TempDir()
tokenFile = filepath.Join(tempDir, "tokens.json")
store := credstore.NewTokenFileStore(tokenFile)
// Save first client
clientID = "client-1"
storage1 := credstore.Token{
AccessToken: "token-1",
RefreshToken: "refresh-1",
TokenType: "Bearer",
ExpiresAt: time.Now().Add(1 * time.Hour),
ClientID: "client-1",
}
if err := store.Save("client-1", storage1); err != nil {
t.Fatalf("Failed to save first client: %v", err)
}
// Save second client (should preserve first)
clientID = "client-2"
storage2 := credstore.Token{
AccessToken: "token-2",
RefreshToken: "refresh-2",
TokenType: "Bearer",
ExpiresAt: time.Now().Add(1 * time.Hour),
ClientID: "client-2",
}
if err := store.Save("client-2", storage2); err != nil {
t.Fatalf("Failed to save second client: %v", err)
}
// Load and verify both exist
loaded1, err := store.Load("client-1")
if err != nil {
t.Fatalf("Load(client-1) error = %v", err)
}
if loaded1.AccessToken != "token-1" {
t.Errorf("Client 1 token was not preserved")
}
loaded2, err := store.Load("client-2")
if err != nil {
t.Fatalf("Load(client-2) error = %v", err)
}
if loaded2.AccessToken != "token-2" {
t.Errorf("Client 2 token was not saved correctly")
}
}
func BenchmarkSaveTokens_SingleClient(b *testing.B) {
tempDir := b.TempDir()
tokenFile = filepath.Join(tempDir, "tokens.json")
store := credstore.NewTokenFileStore(tokenFile)
clientID = "bench-client"
storage := credstore.Token{
AccessToken: "access-token",
RefreshToken: "refresh-token",
TokenType: "Bearer",
ExpiresAt: time.Now().Add(1 * time.Hour),
ClientID: clientID,
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
if err := store.Save(clientID, storage); err != nil {
b.Fatalf("Failed to save tokens: %v", err)
}
}
}
func BenchmarkSaveTokens_ParallelWrites(b *testing.B) {
tempDir := b.TempDir()
tokenFile = filepath.Join(tempDir, "tokens.json")
store := credstore.NewTokenFileStore(tokenFile)
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
id := 0
for pb.Next() {
cID := fmt.Sprintf("client-%d", id)
storage := credstore.Token{
AccessToken: fmt.Sprintf("access-token-%d", id),
RefreshToken: fmt.Sprintf("refresh-token-%d", id),
TokenType: "Bearer",
ExpiresAt: time.Now().Add(1 * time.Hour),
ClientID: cID,
}
if err := store.Save(cID, storage); err != nil {
b.Fatalf("Failed to save tokens: %v", err)
}
id++
}
})
}
func TestValidateTokenResponse(t *testing.T) {
tests := []struct {
name string
accessToken string
tokenType string
expiresIn int
wantErr bool
errContains string
}{
{
name: "valid token response",
accessToken: "valid-access-token-123456",
tokenType: "Bearer",
expiresIn: 3600,
wantErr: false,
},
{
name: "valid token with empty type (optional field)",
accessToken: "valid-access-token-123456",
tokenType: "",
expiresIn: 3600,
wantErr: false,
},
{
name: "empty access token",
accessToken: "",
tokenType: "Bearer",
expiresIn: 3600,
wantErr: true,
errContains: "access_token is empty",
},
{
name: "access token too short",
accessToken: "short",
tokenType: "Bearer",
expiresIn: 3600,
wantErr: true,
errContains: "access_token is too short",
},
{
name: "zero expires_in",
accessToken: "valid-access-token-123456",
tokenType: "Bearer",
expiresIn: 0,
wantErr: true,
errContains: "expires_in must be positive",
},
{
name: "negative expires_in",
accessToken: "valid-access-token-123456",
tokenType: "Bearer",
expiresIn: -3600,
wantErr: true,
errContains: "expires_in must be positive",
},
{
name: "invalid token type",
accessToken: "valid-access-token-123456",
tokenType: "Basic",
expiresIn: 3600,
wantErr: true,
errContains: "unexpected token_type",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := validateTokenResponse(tt.accessToken, tt.tokenType, tt.expiresIn)
if tt.wantErr {
if err == nil {
t.Errorf("validateTokenResponse() expected error but got nil")
return
}
if tt.errContains != "" && !strings.Contains(err.Error(), tt.errContains) {
t.Errorf(
"validateTokenResponse() error = %v, want error containing %q",
err,
tt.errContains,
)
}
} else if err != nil {
t.Errorf("validateTokenResponse() unexpected error = %v", err)
}
})
}
}
func TestRefreshAccessToken_RotationMode(t *testing.T) {
// Save original values
origServerURL := serverURL
origClientID := clientID
origTokenFile := tokenFile
origTokenStore := tokenStore
// Restore after test
defer func() {
serverURL = origServerURL
clientID = origClientID
tokenFile = origTokenFile
tokenStore = origTokenStore
}()
tempDir := t.TempDir()
tokenFile = filepath.Join(tempDir, "tokens.json")
tokenStore = credstore.NewTokenFileStore(tokenFile)
clientID = "test-client-rotation"
tests := []struct {
name string
oldRefreshToken string
responseRefreshToken string // Empty string means server doesn't return refresh_token
expectedRefreshToken string
description string
}{
{
name: "rotation mode - server returns new refresh token",
oldRefreshToken: "old-refresh-token",
responseRefreshToken: "new-refresh-token",
expectedRefreshToken: "new-refresh-token",
description: "Should use new refresh token from server",
},
{
name: "fixed mode - server doesn't return refresh token",
oldRefreshToken: "old-refresh-token",
responseRefreshToken: "",
expectedRefreshToken: "old-refresh-token",
description: "Should preserve old refresh token",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Create mock server
server := httptest.NewServer(
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/oauth/token" {
http.NotFound(w, r)
return
}
// Parse form to verify grant_type
if err := r.ParseForm(); err != nil {
http.Error(w, "Invalid form", http.StatusBadRequest)
return
}
grantType := r.FormValue("grant_type")
if grantType != "refresh_token" {
http.Error(w, "Invalid grant_type", http.StatusBadRequest)
return
}
// Build response
response := map[string]any{
"access_token": "new-access-token",
"token_type": "Bearer",
"expires_in": 3600,
}
// Only include refresh_token if not empty (simulates rotation vs fixed mode)
if tt.responseRefreshToken != "" {
response["refresh_token"] = tt.responseRefreshToken
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(response)
}),
)
defer server.Close()
// Update serverURL to point to mock server
serverURL = server.URL
// Call refreshAccessToken
storage, err := refreshAccessToken(
context.Background(),
tt.oldRefreshToken,
tui.NoopDisplayer{},
)
if err != nil {
t.Fatalf("refreshAccessToken() error = %v", err)
}
// Verify access token
if storage.AccessToken != "new-access-token" {
t.Errorf(
"AccessToken = %v, want %v",
storage.AccessToken,
"new-access-token",
)
}
// Verify refresh token (this is the key test)
if storage.RefreshToken != tt.expectedRefreshToken {
t.Errorf(
"%s: RefreshToken = %v, want %v",
tt.description,
storage.RefreshToken,
tt.expectedRefreshToken,
)
}
// Verify token was saved to file
savedToken, loadErr := tokenStore.Load(clientID)
if loadErr != nil {
t.Fatalf("Token not found in file for client %s: %v", clientID, loadErr)
}
if savedToken.RefreshToken != tt.expectedRefreshToken {
t.Errorf(
"Saved RefreshToken = %v, want %v",
savedToken.RefreshToken,
tt.expectedRefreshToken,
)
}
})
}
}
func TestRefreshAccessToken_ValidationErrors(t *testing.T) {
// Save original values
origServerURL := serverURL
origClientID := clientID
origTokenFile := tokenFile
origTokenStore := tokenStore
// Restore after test
defer func() {
serverURL = origServerURL
clientID = origClientID
tokenFile = origTokenFile
tokenStore = origTokenStore
}()
tempDir := t.TempDir()
tokenFile = filepath.Join(tempDir, "tokens.json")
tokenStore = credstore.NewTokenFileStore(tokenFile)
clientID = "test-client-validation"
tests := []struct {
name string
responseBody map[string]any
wantErr bool
errContains string
}{
{
name: "invalid - empty access token",
responseBody: map[string]any{
"access_token": "",
"token_type": "Bearer",
"expires_in": 3600,
},
wantErr: true,
errContains: "access_token is empty",
},
{
name: "invalid - access token too short",
responseBody: map[string]any{
"access_token": "short",
"token_type": "Bearer",
"expires_in": 3600,
},
wantErr: true,
errContains: "access_token is too short",
},
{
name: "invalid - zero expires_in",
responseBody: map[string]any{
"access_token": "valid-token-123456",
"token_type": "Bearer",
"expires_in": 0,
},
wantErr: true,
errContains: "expires_in must be positive",
},
{
name: "invalid - wrong token type",
responseBody: map[string]any{
"access_token": "valid-token-123456",
"token_type": "Basic",
"expires_in": 3600,
},
wantErr: true,
errContains: "unexpected token_type",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Create mock server
server := httptest.NewServer(
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(tt.responseBody)
}),
)
defer server.Close()
// Update serverURL to point to mock server
serverURL = server.URL
// Call refreshAccessToken
_, err := refreshAccessToken(
context.Background(),
"test-refresh-token",
tui.NoopDisplayer{},
)
if tt.wantErr {
if err == nil {
t.Errorf("refreshAccessToken() expected error but got nil")
return
}
if tt.errContains != "" && !strings.Contains(err.Error(), tt.errContains) {
t.Errorf(
"refreshAccessToken() error = %v, want error containing %q",
err,
tt.errContains,
)
}
} else if err != nil {
t.Errorf("refreshAccessToken() unexpected error = %v", err)
}
})
}
}
func TestRequestDeviceCode_WithRetry(t *testing.T) {
// Save original values
origServerURL := serverURL
origClientID := clientID
defer func() {
serverURL = origServerURL
clientID = origClientID
}()
clientID = "test-client"
var attemptCount atomic.Int32
var testServer *httptest.Server
testServer = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
count := attemptCount.Add(1)
if count < 2 {
// Fail first attempt
w.WriteHeader(http.StatusInternalServerError)
return
}
// Succeed on second attempt
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_ = json.NewEncoder(w).Encode(map[string]any{
"device_code": "test-device-code",
"user_code": "TEST-CODE",
"verification_uri": testServer.URL + "/device",
"verification_uri_complete": testServer.URL + "/device?user_code=TEST-CODE",
"expires_in": 600,
"interval": 5,
})
}))
defer testServer.Close()
serverURL = testServer.URL
ctx := context.Background()
resp, err := requestDeviceCode(ctx)
if err != nil {
t.Fatalf("requestDeviceCode() error = %v", err)
}
if resp.DeviceCode != "test-device-code" {
t.Errorf("Expected device_code 'test-device-code', got %s", resp.DeviceCode)
}
finalCount := attemptCount.Load()
if finalCount != 2 {
t.Errorf("Expected 2 attempts (1 retry), got %d", finalCount)
}
}
func TestReadResponseBody_ExactlyAtLimit(t *testing.T) {
data := make([]byte, maxResponseBodySize)
body, err := readResponseBody(bytes.NewReader(data))
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(body) != int(maxResponseBodySize) {
t.Errorf("expected %d bytes, got %d", maxResponseBodySize, len(body))
}
}
func TestReadResponseBody_ExceedsLimit(t *testing.T) {
data := make([]byte, maxResponseBodySize+1)
_, err := readResponseBody(bytes.NewReader(data))
if !errors.Is(err, errResponseTooLarge) {
t.Errorf("expected errResponseTooLarge, got %v", err)
}
}
func TestReadResponseBody_SmallBody(t *testing.T) {
expected := "hello world"
body, err := readResponseBody(strings.NewReader(expected))
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if string(body) != expected {
t.Errorf("expected %q, got %q", expected, string(body))
}
}
func TestReadResponseBody_EmptyBody(t *testing.T) {
body, err := readResponseBody(strings.NewReader(""))
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(body) != 0 {
t.Errorf("expected empty body, got %d bytes", len(body))
}
}
func TestRequestDeviceCode_OversizedResponse(t *testing.T) {
// Server that returns a response larger than maxResponseBodySize
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
// Write more than maxResponseBodySize
data := make([]byte, maxResponseBodySize+100)
for i := range data {
data[i] = 'a'
}
_, _ = w.Write(data)
}))
defer server.Close()
oldServerURL := serverURL
serverURL = server.URL
defer func() { serverURL = oldServerURL }()
oldClient := retryClient
newClient, err := retry.NewBackgroundClient(
retry.WithHTTPClient(server.Client()),
)
if err != nil {
t.Fatalf("failed to create retry client: %v", err)
}
retryClient = newClient
defer func() { retryClient = oldClient }()
ctx := context.Background()
_, err = requestDeviceCode(ctx)
if err == nil {
t.Fatal("expected error for oversized response, got nil")
}
if !errors.Is(err, errResponseTooLarge) {
t.Errorf("expected errResponseTooLarge in error chain, got: %v", err)
}
}