-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoauth_test.go
More file actions
1319 lines (1112 loc) · 36.2 KB
/
oauth_test.go
File metadata and controls
1319 lines (1112 loc) · 36.2 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
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"context"
"crypto/sha256"
"encoding/base64"
"errors"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
"golang.org/x/oauth2"
)
// Test Helper Functions
func testSiteConfig() SiteConfig {
return SiteConfig{
ClientID: "test_client_id",
ClientSecret: "test_client_secret",
AuthURL: "https://example.com/auth",
TokenURL: "https://example.com/token",
}
}
// =============================================================================
// Category 1: Basic Tests (No external dependencies)
// =============================================================================
func TestNewOAuth_Success(t *testing.T) {
t.Parallel()
tmpDir := t.TempDir()
tokenPath := filepath.Join(tmpDir, "token.json")
config := testSiteConfig()
oauth, err := NewOAuth(config, "http://localhost:18080/callback", "test", []oauth2.AuthCodeOption{}, tokenPath)
if err != nil {
t.Fatalf("NewOAuth() error = %v", err)
}
if oauth == nil {
t.Fatal("NewOAuth() returned nil")
}
if oauth.Config.ClientID != config.ClientID {
t.Errorf("ClientID = %v, want %v", oauth.Config.ClientID, config.ClientID)
}
if oauth.siteName != "test" {
t.Errorf("siteName = %v, want %v", oauth.siteName, "test")
}
if oauth.tokenFilePath != tokenPath {
t.Errorf("tokenFilePath = %v, want %v", oauth.tokenFilePath, tokenPath)
}
if len(oauth.state) == 0 {
t.Error("state is empty")
}
}
func TestNewOAuth_RelativePathRejected(t *testing.T) {
t.Parallel()
tests := []struct {
name string
tokenPath string
expectError bool
description string
}{
{"Relative path", "token.json", true, "relative path should be rejected"},
{"Relative path with dir", "./config/token.json", true, "relative path should be rejected"},
{"Absolute path", t.TempDir() + "/token.json", false, "absolute path should be accepted"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
config := testSiteConfig()
_, err := NewOAuth(config, "http://localhost/callback", "test", []oauth2.AuthCodeOption{}, tt.tokenPath)
if (err != nil) != tt.expectError {
t.Errorf("NewOAuth() error = %v, expectError %v (%s)", err, tt.expectError, tt.description)
}
if err != nil && tt.expectError {
if !strings.Contains(err.Error(), "path must be absolute") {
t.Errorf("error message should contain 'path must be absolute', got: %v", err)
}
}
})
}
}
func TestNeedInit_NoToken(t *testing.T) {
t.Parallel()
tmpDir := t.TempDir()
tokenPath := filepath.Join(tmpDir, "token.json")
config := testSiteConfig()
oauth, err := NewOAuth(config, "http://localhost/callback", "test", []oauth2.AuthCodeOption{}, tokenPath)
if err != nil {
t.Fatalf("NewOAuth() error = %v", err)
}
if !oauth.NeedInit() {
t.Error("NeedInit() should return true when token is nil")
}
}
func TestNeedInit_HasToken(t *testing.T) {
t.Parallel()
tmpDir := t.TempDir()
tokenPath := filepath.Join(tmpDir, "token.json")
// Pre-create token file
token := &oauth2.Token{
AccessToken: "test_token",
TokenType: "Bearer",
Expiry: time.Now().Add(time.Hour),
}
tf := &TokenFile{Tokens: map[string]*oauth2.Token{"test": token}}
if err := writeTokenFile(tokenPath, tf); err != nil {
t.Fatalf("setup: writeTokenFile() error = %v", err)
}
config := testSiteConfig()
oauth, err := NewOAuth(config, "http://localhost/callback", "test", []oauth2.AuthCodeOption{}, tokenPath)
if err != nil {
t.Fatalf("NewOAuth() error = %v", err)
}
if oauth.NeedInit() {
t.Error("NeedInit() should return false when token exists")
}
}
func TestStateParameterGeneration(t *testing.T) {
t.Parallel()
tmpDir := t.TempDir()
oauth1, err := NewOAuth(testSiteConfig(), "http://localhost/callback", "test1", []oauth2.AuthCodeOption{}, tmpDir+"/token1.json")
if err != nil {
t.Fatalf("NewOAuth() error = %v", err)
}
oauth2, err := NewOAuth(testSiteConfig(), "http://localhost/callback", "test2", []oauth2.AuthCodeOption{}, tmpDir+"/token2.json")
if err != nil {
t.Fatalf("NewOAuth() error = %v", err)
}
// State should be 32 characters (from randHTTPParamString(32))
if len(oauth1.state) != 32 {
t.Errorf("state length = %v, want 32", len(oauth1.state))
}
if len(oauth2.state) != 32 {
t.Errorf("state length = %v, want 32", len(oauth2.state))
}
// Each OAuth instance should have different state
if oauth1.state == oauth2.state {
t.Error("states should be different for different OAuth instances")
}
}
func TestGetAuthURL_IncludesState(t *testing.T) {
t.Parallel()
tmpDir := t.TempDir()
tokenPath := filepath.Join(tmpDir, "token.json")
config := testSiteConfig()
oauth, err := NewOAuth(config, "http://localhost/callback", "test", []oauth2.AuthCodeOption{}, tokenPath)
if err != nil {
t.Fatalf("NewOAuth() error = %v", err)
}
authURL := oauth.GetAuthURL()
// Parse URL to verify state parameter
parsedURL, err := url.Parse(authURL)
if err != nil {
t.Fatalf("failed to parse auth URL: %v", err)
}
state := parsedURL.Query().Get("state")
if state == "" {
t.Error("auth URL should contain state parameter")
}
if state != oauth.state {
t.Errorf("state in URL = %v, want %v", state, oauth.state)
}
}
func TestCreateDirIfNotExists(t *testing.T) {
t.Parallel()
tests := []struct {
name string
setupPath func(t *testing.T) string
expectError bool
description string
}{
{
"Directory doesn't exist",
func(t *testing.T) string {
return t.TempDir() + "/newdir/token.json"
},
false,
"should create directory",
},
{
"Directory exists",
func(t *testing.T) string {
return filepath.Join(t.TempDir(), "token.json")
},
false,
"should no-op",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
path := tt.setupPath(t)
err := createDirIfNotExists(path)
if (err != nil) != tt.expectError {
t.Errorf("createDirIfNotExists() error = %v, expectError %v (%s)", err, tt.expectError, tt.description)
}
if !tt.expectError {
// Verify directory was created
dir := filepath.Dir(path)
if _, err := os.Stat(dir); os.IsNotExist(err) {
t.Errorf("directory was not created: %s", dir)
}
}
})
}
}
// =============================================================================
// Category 2: Token File Operations Tests
// =============================================================================
func TestTokenFileReadWrite(t *testing.T) {
t.Parallel()
tmpDir := t.TempDir()
tokenPath := filepath.Join(tmpDir, "token.json")
// Write token
token := &oauth2.Token{
AccessToken: "test_token",
TokenType: "Bearer",
Expiry: time.Now().Add(time.Hour),
}
tf := &TokenFile{Tokens: map[string]*oauth2.Token{"test": token}}
err := writeTokenFile(tokenPath, tf)
if err != nil {
t.Fatalf("writeTokenFile() error = %v", err)
}
// Read back
tf2, err := readTokenFile(tokenPath)
if err != nil {
t.Fatalf("readTokenFile() error = %v", err)
}
// Verify
if tf2.Tokens["test"].AccessToken != "test_token" {
t.Errorf("token = %v, want %v", tf2.Tokens["test"].AccessToken, "test_token")
}
}
func TestMissingTokenFile(t *testing.T) {
t.Parallel()
tmpDir := t.TempDir()
tokenPath := filepath.Join(tmpDir, "nonexistent.json")
tf, err := readTokenFile(tokenPath)
if err != nil {
t.Errorf("readTokenFile() error = %v, want nil", err)
}
if tf == nil {
t.Error("readTokenFile() should return empty TokenFile, not nil")
return
}
if len(tf.Tokens) != 0 {
t.Errorf("TokenFile should be empty, got %d tokens", len(tf.Tokens))
}
}
func TestInvalidTokenFileJSON(t *testing.T) {
t.Parallel()
tmpDir := t.TempDir()
tokenPath := filepath.Join(tmpDir, "invalid.json")
// Write invalid JSON
if err := os.WriteFile(tokenPath, []byte("{invalid json}"), 0o600); err != nil {
t.Fatalf("setup: WriteFile() error = %v", err)
}
_, err := readTokenFile(tokenPath)
if err == nil {
t.Error("readTokenFile() should return error for invalid JSON")
}
}
func TestAtomicWritePreventsCorruption(t *testing.T) {
t.Parallel()
tmpDir := t.TempDir()
tokenPath := filepath.Join(tmpDir, "token.json")
// Write first token
token1 := &oauth2.Token{AccessToken: "token1"}
tf1 := &TokenFile{Tokens: map[string]*oauth2.Token{"test": token1}}
if err := writeTokenFile(tokenPath, tf1); err != nil {
t.Fatalf("writeTokenFile() error = %v", err)
}
// Verify first token exists
tfRead, err := readTokenFile(tokenPath)
if err != nil {
t.Fatalf("readTokenFile() error = %v", err)
}
if tfRead.Tokens["test"].AccessToken != "token1" {
t.Errorf("token = %v, want token1", tfRead.Tokens["test"].AccessToken)
}
// Write second token (should use atomic write)
token2 := &oauth2.Token{AccessToken: "token2"}
tf2 := &TokenFile{Tokens: map[string]*oauth2.Token{"test": token2}}
if err := writeTokenFile(tokenPath, tf2); err != nil {
t.Fatalf("writeTokenFile() error = %v", err)
}
// Verify second token replaced first
tfRead2, err := readTokenFile(tokenPath)
if err != nil {
t.Fatalf("readTokenFile() error = %v", err)
}
if tfRead2.Tokens["test"].AccessToken != "token2" {
t.Errorf("token = %v, want token2", tfRead2.Tokens["test"].AccessToken)
}
// Verify no temp files left
files, err := os.ReadDir(tmpDir)
if err != nil {
t.Fatalf("ReadDir() error = %v", err)
}
for _, f := range files {
if strings.HasSuffix(f.Name(), ".tmp") {
t.Errorf("temp file should be cleaned up, found: %s", f.Name())
}
}
}
// =============================================================================
// Category 3: PKCE Configuration Tests
// =============================================================================
func TestMyAnimeListPKCE_PlainMethod(t *testing.T) {
t.Parallel()
tests := []struct {
name string
wantMethod string
description string
}{
{"Plain PKCE method", "plain", "MAL requires plain method"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tmpDir := t.TempDir()
tokenPath := filepath.Join(tmpDir, "token.json")
// Simulate MyAnimeList PKCE options
verifier := oauth2.GenerateVerifier()
config := testSiteConfig()
oauth, err := NewOAuth(
config,
"http://localhost:18080/callback",
"myanimelist",
[]oauth2.AuthCodeOption{
oauth2.SetAuthURLParam("code_challenge", verifier),
oauth2.SetAuthURLParam("code_challenge_method", "plain"),
oauth2.VerifierOption(verifier),
},
tokenPath,
)
if err != nil {
t.Fatalf("NewOAuth() error = %v", err)
}
authURL := oauth.GetAuthURL()
parsedURL, err := url.Parse(authURL)
if err != nil {
t.Fatalf("failed to parse auth URL: %v", err)
}
query := parsedURL.Query()
method := query.Get("code_challenge_method")
challenge := query.Get("code_challenge")
if method != tt.wantMethod {
t.Errorf("code_challenge_method = %v, want %v (%s)", method, tt.wantMethod, tt.description)
}
// For plain method, challenge should equal verifier
if challenge != verifier {
t.Errorf("code_challenge = %v, want %v (plain method should have challenge=verifier)", challenge, verifier)
}
})
}
}
func TestAnilistPKCE_S256Method(t *testing.T) {
t.Parallel()
tmpDir := t.TempDir()
tokenPath := filepath.Join(tmpDir, "token.json")
// Simulate AniList PKCE options
verifier := oauth2.GenerateVerifier()
config := testSiteConfig()
oauth, err := NewOAuth(
config,
"http://localhost:18080/callback",
"anilist",
[]oauth2.AuthCodeOption{
oauth2.AccessTypeOffline,
oauth2.S256ChallengeOption(verifier),
oauth2.VerifierOption(verifier),
},
tokenPath,
)
if err != nil {
t.Fatalf("NewOAuth() error = %v", err)
}
authURL := oauth.GetAuthURL()
parsedURL, err := url.Parse(authURL)
if err != nil {
t.Fatalf("failed to parse auth URL: %v", err)
}
query := parsedURL.Query()
method := query.Get("code_challenge_method")
challenge := query.Get("code_challenge")
accessType := query.Get("access_type")
// Verify S256 method
if method != "S256" {
t.Errorf("code_challenge_method = %v, want S256", method)
}
// Verify challenge is SHA256 hash of verifier
hash := sha256.Sum256([]byte(verifier))
expectedChallenge := base64.RawURLEncoding.EncodeToString(hash[:])
if challenge != expectedChallenge {
t.Errorf("code_challenge = %v, want %v (SHA256 of verifier)", challenge, expectedChallenge)
}
// Verify AccessTypeOffline
if accessType != "offline" {
t.Errorf("access_type = %v, want offline", accessType)
}
}
func TestGetAuthURL_IncludesPKCEOptions(t *testing.T) {
t.Parallel()
tmpDir := t.TempDir()
tokenPath := filepath.Join(tmpDir, "token.json")
verifier := oauth2.GenerateVerifier()
config := testSiteConfig()
oauth, err := NewOAuth(
config,
"http://localhost/callback",
"test",
[]oauth2.AuthCodeOption{
oauth2.SetAuthURLParam("code_challenge", verifier),
oauth2.SetAuthURLParam("code_challenge_method", "plain"),
},
tokenPath,
)
if err != nil {
t.Fatalf("NewOAuth() error = %v", err)
}
authURL := oauth.GetAuthURL()
parsedURL, err := url.Parse(authURL)
if err != nil {
t.Fatalf("failed to parse auth URL: %v", err)
}
query := parsedURL.Query()
challenge := query.Get("code_challenge")
if challenge == "" {
t.Error("auth URL should contain code_challenge parameter")
}
method := query.Get("code_challenge_method")
if method == "" {
t.Error("auth URL should contain code_challenge_method parameter")
}
}
// =============================================================================
// Category 4: CSRF State Validation Tests (with httptest)
// =============================================================================
func TestStateValidation_MissingState(t *testing.T) {
t.Parallel()
tmpDir := t.TempDir()
tokenPath := filepath.Join(tmpDir, "token.json")
config := testSiteConfig()
oauth, err := NewOAuth(config, "http://localhost:18080/callback", "test", []oauth2.AuthCodeOption{}, tokenPath)
if err != nil {
t.Fatalf("NewOAuth() error = %v", err)
}
// Create request without state parameter
req := httptest.NewRequest(http.MethodGet, "/callback?code=test_code", nil)
w := httptest.NewRecorder()
// Call the callback handler (extracted from startServer)
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, cancel := context.WithTimeout(t.Context(), 5*time.Second)
defer cancel()
state := r.URL.Query().Get("state")
if state == "" {
http.Error(w, "State parameter missing", http.StatusBadRequest)
return
}
oauth.stateMu.RLock()
expectedState := oauth.state
oauth.stateMu.RUnlock()
if state != expectedState {
http.Error(w, "Invalid state parameter", http.StatusBadRequest)
return
}
})
handler.ServeHTTP(w, req)
resp := w.Result()
if err := resp.Body.Close(); err != nil {
t.Logf("Warning: failed to close response body: %v", err)
}
if resp.StatusCode != http.StatusBadRequest {
t.Errorf("status code = %v, want %v", resp.StatusCode, http.StatusBadRequest)
}
}
func TestStateValidation_MismatchedState(t *testing.T) {
t.Parallel()
tmpDir := t.TempDir()
tokenPath := filepath.Join(tmpDir, "token.json")
config := testSiteConfig()
oauth, err := NewOAuth(config, "http://localhost:18080/callback", "test", []oauth2.AuthCodeOption{}, tokenPath)
if err != nil {
t.Fatalf("NewOAuth() error = %v", err)
}
// Create request with wrong state
req := httptest.NewRequest(http.MethodGet, "/callback?code=test_code&state=wrong_state", nil)
w := httptest.NewRecorder()
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, cancel := context.WithTimeout(t.Context(), 5*time.Second)
defer cancel()
state := r.URL.Query().Get("state")
if state == "" {
http.Error(w, "State parameter missing", http.StatusBadRequest)
return
}
oauth.stateMu.RLock()
expectedState := oauth.state
oauth.stateMu.RUnlock()
if state != expectedState {
http.Error(w, "Invalid state parameter", http.StatusBadRequest)
return
}
})
handler.ServeHTTP(w, req)
resp := w.Result()
if err := resp.Body.Close(); err != nil {
t.Logf("Warning: failed to close response body: %v", err)
}
if resp.StatusCode != http.StatusBadRequest {
t.Errorf("status code = %v, want %v", resp.StatusCode, http.StatusBadRequest)
}
}
func TestStateValidation_ValidState(t *testing.T) {
t.Parallel()
tmpDir := t.TempDir()
tokenPath := filepath.Join(tmpDir, "token.json")
config := testSiteConfig()
oauth, err := NewOAuth(config, "http://localhost:18080/callback", "test", []oauth2.AuthCodeOption{}, tokenPath)
if err != nil {
t.Fatalf("NewOAuth() error = %v", err)
}
// Create request with correct state
req := httptest.NewRequest(http.MethodGet, "/callback?code=test_code&state="+oauth.state, nil)
w := httptest.NewRecorder()
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, cancel := context.WithTimeout(t.Context(), 5*time.Second)
defer cancel()
state := r.URL.Query().Get("state")
if state == "" {
http.Error(w, "State parameter missing", http.StatusBadRequest)
return
}
oauth.stateMu.RLock()
expectedState := oauth.state
oauth.stateMu.RUnlock()
if state != expectedState {
http.Error(w, "Invalid state parameter", http.StatusBadRequest)
return
}
// State is valid, would continue to token exchange
w.WriteHeader(http.StatusOK)
})
handler.ServeHTTP(w, req)
resp := w.Result()
if err := resp.Body.Close(); err != nil {
t.Logf("Warning: failed to close response body: %v", err)
}
if resp.StatusCode != http.StatusOK {
t.Errorf("status code = %v, want %v", resp.StatusCode, http.StatusOK)
}
}
// =============================================================================
// Category 5: Context Cancellation Tests
// =============================================================================
func TestTokenWithContext_RespectsContext(t *testing.T) {
t.Parallel()
tmpDir := t.TempDir()
tokenPath := filepath.Join(tmpDir, "token.json")
config := testSiteConfig()
oauth, err := NewOAuth(config, "http://localhost/callback", "test", []oauth2.AuthCodeOption{}, tokenPath)
if err != nil {
t.Fatalf("NewOAuth() error = %v", err)
}
ctx, cancel := context.WithCancel(t.Context())
cancel() // Cancel immediately
// TokenWithContext should fail due to cancelled context
_, err = oauth.TokenWithContext(ctx)
if err == nil {
t.Error("TokenWithContext() should return error when context is cancelled")
}
// The error might be from context cancellation or token refresh
// Either way, there should be an error
if err == nil {
t.Error("expected error due to context cancellation")
}
}
func TestToken_DeprecatedUsesBackgroundContext(t *testing.T) {
t.Parallel()
tmpDir := t.TempDir()
tokenPath := filepath.Join(tmpDir, "token.json")
config := testSiteConfig()
oauth, err := NewOAuth(config, "http://localhost/callback", "test", []oauth2.AuthCodeOption{}, tokenPath)
if err != nil {
t.Fatalf("NewOAuth() error = %v", err)
}
// Token() is deprecated but should still work (uses background context)
// It will fail because there's no actual token, but it shouldn't panic
_, err = oauth.Token()
// We expect an error since there's no valid token to refresh
if err == nil {
t.Log("Token() returned nil error (this is expected if there's a valid token)")
}
}
func TestTokenSource_ContextAware(t *testing.T) {
t.Parallel()
tmpDir := t.TempDir()
tokenPath := filepath.Join(tmpDir, "token.json")
config := testSiteConfig()
oauth, err := NewOAuth(config, "http://localhost/callback", "test", []oauth2.AuthCodeOption{}, tokenPath)
if err != nil {
t.Fatalf("NewOAuth() error = %v", err)
}
ctx := t.Context()
ts := oauth.TokenSource(ctx)
if ts == nil {
t.Error("TokenSource() should return a non-nil TokenSource")
}
// Verify it's the context-aware wrapper
if _, ok := ts.(*contextAwareTokenSource); !ok {
t.Errorf("TokenSource() should return *contextAwareTokenSource, got %T", ts)
}
}
// =============================================================================
// Category 6: Thread Safety Tests (run with -race flag)
// =============================================================================
func TestConcurrentTokenAccess(t *testing.T) {
tmpDir := t.TempDir()
tokenPath := filepath.Join(tmpDir, "token.json")
config := testSiteConfig()
oauth, err := NewOAuth(config, "http://localhost/callback", "test", []oauth2.AuthCodeOption{}, tokenPath)
if err != nil {
t.Fatalf("NewOAuth() error = %v", err)
}
// Spawn 100 goroutines reading token state
var wg sync.WaitGroup
iterations := 100
for range iterations {
wg.Go(func() {
_ = oauth.NeedInit() // Concurrent read
})
}
wg.Wait()
// Run with: go test -race
// This test should not report any race conditions
}
func TestConcurrentStateAccess(t *testing.T) {
tmpDir := t.TempDir()
tokenPath := filepath.Join(tmpDir, "token.json")
config := testSiteConfig()
oauth, err := NewOAuth(config, "http://localhost/callback", "test", []oauth2.AuthCodeOption{}, tokenPath)
if err != nil {
t.Fatalf("NewOAuth() error = %v", err)
}
// Spawn 100 goroutines getting auth URL (reads state)
var wg sync.WaitGroup
iterations := 100
for range iterations {
wg.Go(func() {
_ = oauth.GetAuthURL() // Concurrent read of state
})
}
wg.Wait()
// Run with: go test -race
// This test should not report any race conditions
}
func TestConcurrentTokenAndStateAccess(t *testing.T) {
tmpDir := t.TempDir()
tokenPath := filepath.Join(tmpDir, "token.json")
config := testSiteConfig()
oauth, err := NewOAuth(config, "http://localhost/callback", "test", []oauth2.AuthCodeOption{}, tokenPath)
if err != nil {
t.Fatalf("NewOAuth() error = %v", err)
}
// Spawn multiple goroutines accessing both token and state
var wg sync.WaitGroup
iterations := 50
for range iterations {
wg.Add(2)
go func() {
defer wg.Done()
_ = oauth.NeedInit()
}()
go func() {
defer wg.Done()
_ = oauth.GetAuthURL()
}()
}
wg.Wait()
// Run with: go test -race
// This test should not report any race conditions
}
// =============================================================================
// Category 7: Mock OAuth Server Tests
// =============================================================================
func setupMockOAuthServer(t *testing.T) (*httptest.Server, *oauth2.Config) {
mux := http.NewServeMux()
mux.HandleFunc("/token", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/x-www-form-urlencoded")
if _, err := w.Write([]byte("access_token=mocktoken&token_type=bearer&expires_in=3600")); err != nil {
http.Error(w, "failed to write response", http.StatusInternalServerError)
}
})
server := httptest.NewServer(mux)
config := &oauth2.Config{
ClientID: "test_id",
ClientSecret: "test_secret",
RedirectURL: "http://localhost/callback",
Endpoint: oauth2.Endpoint{
AuthURL: server.URL + "/auth",
TokenURL: server.URL + "/token",
},
}
t.Cleanup(func() { server.Close() })
return server, config
}
func TestExchangeToken_WithMockServer(t *testing.T) {
t.Parallel()
tmpDir := t.TempDir()
tokenPath := filepath.Join(tmpDir, "token.json")
_, mockConfig := setupMockOAuthServer(t)
// Create OAuth with mock config
oauth := &OAuth{
Config: mockConfig,
siteName: "test",
authCodeOptions: []oauth2.AuthCodeOption{},
tokenFilePath: tokenPath,
state: "test_state",
}
// Exchange token (will use mock server)
ctx := t.Context()
err := oauth.ExchangeToken(ctx, "test_code")
if err != nil {
t.Logf("ExchangeToken() error = %v (this is expected if mock server doesn't handle full OAuth flow)", err)
}
// Verify token was saved if exchange succeeded
if !oauth.NeedInit() {
t.Log("Token was successfully exchanged and saved")
}
}
// =============================================================================
// Round-trip Integration Test
// =============================================================================
func TestOAuth_RoundTrip(t *testing.T) {
t.Parallel()
tmpDir := t.TempDir()
tokenPath := filepath.Join(tmpDir, "token.json")
// Create OAuth
config := testSiteConfig()
oauth, err := NewOAuth(config, "http://localhost:18080/callback", "test", []oauth2.AuthCodeOption{}, tokenPath)
if err != nil {
t.Fatalf("NewOAuth() error = %v", err)
}
// Verify initial state
if !oauth.NeedInit() {
t.Error("NeedInit() should return true initially")
}
// Generate auth URL
authURL := oauth.GetAuthURL()
if authURL == "" {
t.Error("GetAuthURL() should return non-empty URL")
}
// Verify state in URL
parsedURL, err := url.Parse(authURL)
if err != nil {
t.Fatalf("failed to parse auth URL: %v", err)
}
state := parsedURL.Query().Get("state")
if state != oauth.state {
t.Errorf("state in URL = %v, want %v", state, oauth.state)
}
}
// =============================================================================
// Category 8: CLI-Related OAuth Tests
// =============================================================================
func TestIsTokenValid_NoToken(t *testing.T) {
t.Parallel()
tmpDir := t.TempDir()
tokenPath := filepath.Join(tmpDir, "token.json")
config := testSiteConfig()
oauth, err := NewOAuth(config, "http://localhost/callback", "test", []oauth2.AuthCodeOption{}, tokenPath)
if err != nil {
t.Fatalf("NewOAuth() error = %v", err)
}
if oauth.IsTokenValid() {
t.Error("IsTokenValid() should return false when token is nil")
}
}
func TestIsTokenValid_ValidToken(t *testing.T) {
t.Parallel()
tmpDir := t.TempDir()
tokenPath := filepath.Join(tmpDir, "token.json")
// Pre-create token file with valid token
token := &oauth2.Token{
AccessToken: "test_token",
TokenType: "Bearer",
Expiry: time.Now().Add(time.Hour),
}
tf := &TokenFile{Tokens: map[string]*oauth2.Token{"test": token}}
if err := writeTokenFile(tokenPath, tf); err != nil {
t.Fatalf("setup: writeTokenFile() error = %v", err)
}
config := testSiteConfig()
oauth, err := NewOAuth(config, "http://localhost/callback", "test", []oauth2.AuthCodeOption{}, tokenPath)
if err != nil {
t.Fatalf("NewOAuth() error = %v", err)
}
if !oauth.IsTokenValid() {
t.Error("IsTokenValid() should return true for valid token")
}
}
func TestIsTokenValid_ExpiredToken(t *testing.T) {
t.Parallel()
tmpDir := t.TempDir()
tokenPath := filepath.Join(tmpDir, "token.json")
// Pre-create token file with expired token
token := &oauth2.Token{
AccessToken: "test_token",
TokenType: "Bearer",
Expiry: time.Now().Add(-time.Hour),
}
tf := &TokenFile{Tokens: map[string]*oauth2.Token{"test": token}}
if err := writeTokenFile(tokenPath, tf); err != nil {
t.Fatalf("setup: writeTokenFile() error = %v", err)
}
config := testSiteConfig()
oauth, err := NewOAuth(config, "http://localhost/callback", "test", []oauth2.AuthCodeOption{}, tokenPath)
if err != nil {
t.Fatalf("NewOAuth() error = %v", err)
}
if oauth.IsTokenValid() {
t.Error("IsTokenValid() should return false for expired token")
}
}
func TestIsTokenValid_ZeroExpiry(t *testing.T) {
t.Parallel()
tmpDir := t.TempDir()
tokenPath := filepath.Join(tmpDir, "token.json")
// Token with zero expiry is considered always valid
token := &oauth2.Token{
AccessToken: "test_token",
TokenType: "Bearer",
Expiry: time.Time{},
}
tf := &TokenFile{Tokens: map[string]*oauth2.Token{"test": token}}