-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathexternalauth_test.go
More file actions
2143 lines (1885 loc) · 72.6 KB
/
Copy pathexternalauth_test.go
File metadata and controls
2143 lines (1885 loc) · 72.6 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 externalauth_test
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/url"
"runtime/debug"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/coreos/go-oidc/v3/oidc"
"github.com/golang-jwt/jwt/v4"
"github.com/google/uuid"
"github.com/prometheus/client_golang/prometheus"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.uber.org/mock/gomock"
"golang.org/x/oauth2"
"golang.org/x/sync/errgroup"
"golang.org/x/sync/singleflight"
"golang.org/x/xerrors"
"cdr.dev/slog/v3"
"cdr.dev/slog/v3/sloggers/slogjson"
"github.com/coder/coder/v2/coderd"
"github.com/coder/coder/v2/coderd/coderdtest/oidctest"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/database/dbmock"
"github.com/coder/coder/v2/coderd/database/dbtestutil"
"github.com/coder/coder/v2/coderd/database/dbtime"
"github.com/coder/coder/v2/coderd/externalauth"
"github.com/coder/coder/v2/coderd/promoauth"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/testutil"
)
func TestRefreshToken(t *testing.T) {
t.Parallel()
expired := time.Now().Add(time.Hour * -1)
t.Run("NoRefreshExpired", func(t *testing.T) {
t.Parallel()
fake, config, link := setupOauth2Test(t, testConfig{
FakeIDPOpts: []oidctest.FakeIDPOpt{
oidctest.WithRefresh(func(_ string) error {
t.Error("refresh on the IDP was called, but NoRefresh was set")
return xerrors.New("should not be called")
}),
// The IDP should not be contacted since the token is expired. An expired
// token with 'NoRefresh' should early abort.
oidctest.WithDynamicUserInfo(func(_ string) (jwt.MapClaims, error) {
t.Error("token was validated, but it was expired and this should never have happened.")
return nil, xerrors.New("should not be called")
}),
},
ExternalAuthOpt: func(cfg *externalauth.Config) {
cfg.NoRefresh = true
},
})
ctx := oidc.ClientContext(context.Background(), fake.HTTPClient(nil))
// Expire the link
link.OAuthExpiry = expired
_, err := config.RefreshToken(ctx, nil, link)
require.Error(t, err)
require.True(t, externalauth.IsInvalidTokenError(err))
require.Contains(t, err.Error(), "refreshing is either disabled or refreshing failed")
})
// NoRefreshNoExpiry tests that an oauth token without an expiry is always valid.
// The "validate url" should be hit, but the refresh endpoint should not.
t.Run("NoRefreshNoExpiry", func(t *testing.T) {
t.Parallel()
validated := false
fake, config, link := setupOauth2Test(t, testConfig{
FakeIDPOpts: []oidctest.FakeIDPOpt{
oidctest.WithRefresh(func(_ string) error {
t.Error("refresh on the IDP was called, but NoRefresh was set")
return xerrors.New("should not be called")
}),
oidctest.WithDynamicUserInfo(func(_ string) (jwt.MapClaims, error) {
validated = true
return jwt.MapClaims{}, nil
}),
},
ExternalAuthOpt: func(cfg *externalauth.Config) {
cfg.NoRefresh = true
},
})
ctx := oidc.ClientContext(context.Background(), fake.HTTPClient(nil))
// Zero time used
link.OAuthExpiry = time.Time{}
_, err := config.RefreshToken(ctx, nil, link)
require.NoError(t, err)
require.True(t, validated, "token should have been validated")
})
t.Run("FalseIfTokenSourceFails", func(t *testing.T) {
t.Parallel()
config := &externalauth.Config{
InstrumentedOAuth2Config: &testutil.OAuth2Config{
TokenSourceFunc: func() (*oauth2.Token, error) {
return nil, xerrors.New("failure")
},
},
RefreshGroup: new(singleflight.Group),
}
_, err := config.RefreshToken(context.Background(), nil, database.ExternalAuthLink{
OAuthExpiry: expired,
})
require.Error(t, err)
require.True(t, externalauth.IsInvalidTokenError(err))
require.Contains(t, err.Error(), "failure")
})
t.Run("ValidateServerError", func(t *testing.T) {
t.Parallel()
ctrl := gomock.NewController(t)
mDB := dbmock.NewMockStore(ctrl)
mDB.EXPECT().UpdateExternalAuthLink(gomock.Any(), gomock.Any()).
Return(database.ExternalAuthLink{}, nil).AnyTimes()
const staticError = "static error"
validated := false
fake, config, link := setupOauth2Test(t, testConfig{
FakeIDPOpts: []oidctest.FakeIDPOpt{
oidctest.WithDynamicUserInfo(func(_ string) (jwt.MapClaims, error) {
validated = true
return jwt.MapClaims{}, xerrors.New(staticError)
}),
},
ExternalAuthOpt: func(cfg *externalauth.Config) {
},
})
ctx := oidc.ClientContext(context.Background(), fake.HTTPClient(nil))
link.OAuthExpiry = expired
_, err := config.RefreshToken(ctx, mDB, link)
require.ErrorContains(t, err, staticError)
// Unsure if this should be the correct behavior. It's an invalid token because
// 'ValidateToken()' failed with a runtime error. This was the previous behavior,
// so not going to change it.
require.False(t, externalauth.IsInvalidTokenError(err))
require.True(t, validated, "token should have been attempted to be validated")
})
// RefreshRetries tests that refresh token retry behavior works as expected.
// If a refresh token fails because the token itself is invalid, no more
// refresh attempts should ever happen. An invalid refresh token does
// not magically become valid at some point in the future.
//
// Internal retries are disabled in this subtest via a negative
// RefreshRetryTimeout so each RefreshToken call results in exactly one
// IDP refresh attempt. The RefreshTokenWithBackoff subtest covers the
// retry-with-backoff path.
t.Run("RefreshRetries", func(t *testing.T) {
t.Parallel()
var refreshErr *oauth2.RetrieveError
ctrl := gomock.NewController(t)
mDB := dbmock.NewMockStore(ctrl)
refreshCount := 0
fake, config, link := setupOauth2Test(t, testConfig{
FakeIDPOpts: []oidctest.FakeIDPOpt{
oidctest.WithRefresh(func(_ string) error {
refreshCount++
return refreshErr
}),
// The IDP should not be contacted since the token is expired and
// refresh attempts will fail.
oidctest.WithDynamicUserInfo(func(_ string) (jwt.MapClaims, error) {
t.Error("token was validated, but it was expired and this should never have happened.")
return nil, xerrors.New("should not be called")
}),
},
ExternalAuthOpt: func(cfg *externalauth.Config) {
// Negative timeout disables retries (1 IDP call per RefreshToken).
// A tiny positive timeout is unreliable on coarse-clock platforms
// (Windows).
cfg.RefreshRetryTimeout = -1
},
})
ctx := oidc.ClientContext(context.Background(), fake.HTTPClient(nil))
// Expire the link
link.OAuthExpiry = expired
// Make the failure a server internal error. Not related to the token
// This should be retried since this error is temporary.
refreshErr = &oauth2.RetrieveError{
Response: &http.Response{
StatusCode: http.StatusInternalServerError,
},
ErrorCode: "internal_error",
}
totalRefreshes := 0
for i := 0; i < 3; i++ {
// Each loop will hit the temporary error and retry.
_, err := config.RefreshToken(ctx, mDB, link)
require.Error(t, err)
totalRefreshes++
require.True(t, externalauth.IsInvalidTokenError(err))
require.Equal(t, refreshCount, totalRefreshes)
}
// Try again with a bad refresh token error. This will invalidate the
// refresh token, and not retry again. Expect DB calls to check for
// concurrent refresh (GetExternalAuthLink) and then remove the refresh token.
mDB.EXPECT().GetExternalAuthLink(gomock.Any(), gomock.Any()).Return(link, nil).Times(1)
mDB.EXPECT().UpdateExternalAuthLinkRefreshToken(gomock.Any(), gomock.Any()).Return(nil).Times(1)
refreshErr = &oauth2.RetrieveError{ // github error
Response: &http.Response{
StatusCode: http.StatusOK,
},
ErrorCode: "bad_refresh_token",
}
_, err := config.RefreshToken(ctx, mDB, link)
require.Error(t, err)
totalRefreshes++
require.True(t, externalauth.IsInvalidTokenError(err))
require.Equal(t, refreshCount, totalRefreshes)
// When the refresh token is empty, no api calls should be made
link.OAuthRefreshToken = "" // mock'd db, so manually set the token to ''
_, err = config.RefreshToken(ctx, mDB, link)
require.Error(t, err)
require.True(t, externalauth.IsInvalidTokenError(err))
require.Equal(t, refreshCount, totalRefreshes)
})
// RefreshTokenWithBackoff tests that refreshes which fail with transient
// errors (HTTP 5xx, 429, network errors) are retried with exponential
// backoff so a temporary upstream glitch does not force users to
// re-authenticate. After enough successful retries, RefreshToken should
// return a valid token without surfacing the transient error.
t.Run("RefreshTokenWithBackoff", func(t *testing.T) {
t.Parallel()
db, _ := dbtestutil.NewDB(t)
const failuresBeforeSuccess = 3
var refreshCalls atomic.Int64
fake, config, link := setupOauth2Test(t, testConfig{
FakeIDPOpts: []oidctest.FakeIDPOpt{
oidctest.WithRefresh(func(_ string) error {
// Fail the first N attempts with a transient 5xx, then succeed.
if refreshCalls.Add(1) <= failuresBeforeSuccess {
return &oauth2.RetrieveError{
Response: &http.Response{StatusCode: http.StatusInternalServerError},
ErrorCode: "server_error",
}
}
return nil
}),
},
ExternalAuthOpt: func(cfg *externalauth.Config) {
cfg.Type = codersdk.EnhancedExternalAuthProviderGitHub.String()
// Tight backoffs keep the test fast.
cfg.RefreshRetryInitialBackoff = time.Millisecond
cfg.RefreshRetryMaxBackoff = 5 * time.Millisecond
cfg.RefreshRetryTimeout = 5 * time.Second
},
DB: db,
})
ctx := oidc.ClientContext(context.Background(), fake.HTTPClient(nil))
oldAccessToken := link.OAuthAccessToken
link.OAuthExpiry = expired
updated, err := config.RefreshToken(ctx, db, link)
require.NoError(t, err, "transient errors should be retried until success")
require.Equal(t, int64(failuresBeforeSuccess+1), refreshCalls.Load(),
"refresh should have been retried until the IDP returned success")
require.NotEqual(t, oldAccessToken, updated.OAuthAccessToken,
"a new access token should have been issued")
})
// RefreshTokenBackoffPermanentError verifies that errors classified as
// permanent by isFailedRefresh (e.g. "bad_refresh_token") are not
// retried. Retrying a permanent failure wastes the refresh quota and,
// on providers with single-use refresh tokens, can mask a legitimate
// concurrent winner with repeated "bad_refresh_token" responses.
t.Run("RefreshTokenBackoffPermanentError", func(t *testing.T) {
t.Parallel()
ctrl := gomock.NewController(t)
mDB := dbmock.NewMockStore(ctrl)
var refreshCalls atomic.Int64
fake, config, link := setupOauth2Test(t, testConfig{
FakeIDPOpts: []oidctest.FakeIDPOpt{
oidctest.WithRefresh(func(_ string) error {
refreshCalls.Add(1)
return &oauth2.RetrieveError{
Response: &http.Response{StatusCode: http.StatusOK},
ErrorCode: "bad_refresh_token",
}
}),
},
ExternalAuthOpt: func(cfg *externalauth.Config) {
cfg.Type = codersdk.EnhancedExternalAuthProviderGitHub.String()
// Generous backoff: a regression that incorrectly retried
// would re-run the failing refresh many times and the test
// would fail on the call-count assertion below.
cfg.RefreshRetryInitialBackoff = time.Millisecond
cfg.RefreshRetryMaxBackoff = 5 * time.Millisecond
cfg.RefreshRetryTimeout = time.Second
},
})
// The race-detection re-read returns the same refresh token so it
// does not look like a concurrent winner. The cached-failure write
// then proceeds. Each runs exactly once for a single refresh attempt.
mDB.EXPECT().GetExternalAuthLink(gomock.Any(), gomock.Any()).
Return(link, nil).Times(1)
mDB.EXPECT().UpdateExternalAuthLinkRefreshToken(gomock.Any(), gomock.Any()).
Return(nil).Times(1)
ctx := oidc.ClientContext(context.Background(), fake.HTTPClient(nil))
link.OAuthExpiry = expired
_, err := config.RefreshToken(ctx, mDB, link)
require.Error(t, err)
require.True(t, externalauth.IsInvalidTokenError(err))
require.Equal(t, int64(1), refreshCalls.Load(),
"permanent failures should not be retried")
})
// ConcurrentRefreshGroup tests that when requests try to refresh a token
// while another request is pending, they wait on the first caller and share
// the result instead of all attempting to perform the refresh.
t.Run("ConcurrentRefreshGroup", func(t *testing.T) {
t.Parallel()
ctrl := gomock.NewController(t)
mDB := dbmock.NewMockStore(ctrl)
parallelRequests := 5
ch := make(chan string)
refreshedToken := &oauth2.Token{
AccessToken: "winner-access-token",
RefreshToken: "winner-refresh-token",
Expiry: time.Now().Add(time.Hour),
}
var refreshCalls atomic.Int64
config := &externalauth.Config{
InstrumentedOAuth2Config: &testutil.OAuth2Config{
// The first call to refresh will succeed and all others will fail. The
// first will wait for all callers to join the group before returning.
TokenSourceFunc: func() (*oauth2.Token, error) {
if refreshCalls.Add(1) == 1 {
// Wait for all the other calls to be subscribed, to prevent
// the test from flaking.
subscribed := 1
for {
<-ch
subscribed++
if subscribed >= parallelRequests {
return refreshedToken, nil
}
}
}
return nil, xerrors.New("bad_refresh_token")
},
},
RefreshGroup: &group{
notify: ch,
},
}
link := database.ExternalAuthLink{OAuthExpiry: expired}
refreshedLink := database.ExternalAuthLink{
OAuthAccessToken: refreshedToken.AccessToken,
OAuthRefreshToken: refreshedToken.RefreshToken,
OAuthExpiry: refreshedToken.Expiry,
}
// The single winning call will update the link.
mDB.EXPECT().UpdateExternalAuthLink(gomock.Any(), gomock.Cond(func(params database.UpdateExternalAuthLinkParams) bool {
return params.ProviderID == link.ProviderID && params.UserID == link.UserID
})).Return(refreshedLink, nil).Times(1)
// When we fire off all requests in parallel...
ctx := testutil.Context(t, testutil.WaitLong)
var eg errgroup.Group
results := make([]database.ExternalAuthLink, parallelRequests)
for i := range parallelRequests {
eg.Go(func() error {
result, err := config.RefreshToken(ctx, mDB, link)
results[i] = result
return err
})
}
// No call should error.
err := eg.Wait()
require.NoError(t, err)
// All calls should have picked up the winning token.
for i := range parallelRequests {
require.Equal(t, refreshedLink, results[i])
}
// Only one refresh call should have actually been made.
require.Equal(t, int64(1), refreshCalls.Load())
})
// ConcurrentRefreshRace tests what happens a request reads the refresh token
// from the database, then another request finishes and updates the token and
// releases the refresh group lock before this request can join.
//
// This request will then fail with `bad_refresh_token` for providers that
// have single-use refresh tokens. It should re-read the token from the
// database after making this failed request to check whether the token was
// updated by another request and returns that rather than incorrectly
// recording in the database that the request failed.
t.Run("ConcurrentRefreshRace", func(t *testing.T) {
t.Parallel()
ctrl := gomock.NewController(t)
mDB := dbmock.NewMockStore(ctrl)
fake, config, link := setupOauth2Test(t, testConfig{
FakeIDPOpts: []oidctest.FakeIDPOpt{
oidctest.WithRefresh(func(_ string) error {
return &oauth2.RetrieveError{
Response: &http.Response{
StatusCode: http.StatusOK,
},
ErrorCode: "bad_refresh_token",
}
}),
},
ExternalAuthOpt: func(cfg *externalauth.Config) {},
})
ctx := oidc.ClientContext(context.Background(), fake.HTTPClient(nil))
link.OAuthExpiry = time.Now().Add(time.Hour * -1)
// Simulate a concurrent winner: when the loser re-reads the
// DB, the refresh token has changed (the winner stored a new
// one). The loser should return the updated link instead of
// caching the failure.
winnerLink := link
winnerLink.OAuthRefreshToken = "winner-refresh-token"
winnerLink.OAuthAccessToken = "winner-access-token"
mDB.EXPECT().GetExternalAuthLink(gomock.Any(), database.GetExternalAuthLinkParams{
ProviderID: link.ProviderID,
UserID: link.UserID,
}).Return(winnerLink, nil).Times(1)
// UpdateExternalAuthLinkRefreshToken should NOT be called
// because the re-read detected the concurrent refresh.
result, err := config.RefreshToken(ctx, mDB, link)
require.NoError(t, err, "loser should succeed using the winner's token")
require.Equal(t, "winner-access-token", result.OAuthAccessToken)
require.Equal(t, "winner-refresh-token", result.OAuthRefreshToken)
})
// ConcurrentContextCancel tests that if one request is canceled, it does not
// cancel other requests waiting on it.
t.Run("ConcurrentContextCanceled", func(t *testing.T) {
t.Parallel()
db, _ := dbtestutil.NewDB(t)
parallelRequests := 5
ch := make(chan string)
var refreshCalls atomic.Int64
ctx := testutil.Context(t, testutil.WaitLong)
cancelOnRefresh, cancel := context.WithCancel(ctx)
defer cancel()
// Use to know when the first call has started the group, so we know which
// context we can cancel.
listening := make(chan struct{})
fake, config, link := setupOauth2Test(t, testConfig{
FakeIDPOpts: []oidctest.FakeIDPOpt{
oidctest.WithRefresh(func(_ string) error {
if refreshCalls.Add(1) == 1 {
close(listening)
// Wait for all the other calls to be subscribed, to prevent
// the test from flaking.
subscribed := 1
for {
<-ch
subscribed++
if subscribed >= parallelRequests {
// Cancel the parent context after refresh succeeds
// but before the DB save and validation.
cancel()
return nil
}
}
}
// Should never reach here.
return xerrors.New("bad_refresh_token")
}),
oidctest.WithDynamicUserInfo(func(_ string) (jwt.MapClaims, error) {
return jwt.MapClaims{}, nil
}),
},
ExternalAuthOpt: func(cfg *externalauth.Config) {
cfg.Type = codersdk.EnhancedExternalAuthProviderGitHub.String()
cfg.RefreshGroup = &group{notify: ch}
},
DB: db,
})
oldAccessToken := link.OAuthAccessToken
oldRefreshToken := link.OAuthRefreshToken
link.OAuthExpiry = expired
var wg sync.WaitGroup
// Start the first call with the cancelable context.
wg.Add(1)
go func() {
defer wg.Done()
ctx := oidc.ClientContext(cancelOnRefresh, fake.HTTPClient(nil))
_, err := config.RefreshToken(ctx, db, link)
assert.ErrorIs(t, err, context.Canceled)
}()
// Wait for it to start the group, to make sure the callback above is
// canceling the right context (if we fire them all at once, any one of them
// could start the group).
<-listening
// Now we can fire off the remaining requests.
for range parallelRequests - 1 {
wg.Add(1)
go func() {
defer wg.Done()
ctx := oidc.ClientContext(ctx, fake.HTTPClient(nil))
result, err := config.RefreshToken(ctx, db, link)
assert.NoError(t, err)
assert.NotEqual(t, oldAccessToken, result.OAuthAccessToken)
assert.NotEqual(t, oldRefreshToken, result.OAuthRefreshToken)
}()
}
wg.Wait()
// DB link should have been updated.
dbLink, err := db.GetExternalAuthLink(context.Background(), database.GetExternalAuthLinkParams{
ProviderID: link.ProviderID,
UserID: link.UserID,
})
require.NoError(t, err)
require.NotEqual(t, oldAccessToken, dbLink.OAuthAccessToken,
"DB should have the new access token despite context cancellation")
require.NotEqual(t, oldRefreshToken, dbLink.OAuthRefreshToken,
"DB should have the new refresh token despite context cancellation")
// Only one refresh call should have actually been made.
require.Equal(t, int64(1), refreshCalls.Load())
})
// ValidateFailure tests if the token is no longer valid with a 401 response.
t.Run("ValidateFailure", func(t *testing.T) {
t.Parallel()
ctrl := gomock.NewController(t)
mDB := dbmock.NewMockStore(ctrl)
mDB.EXPECT().UpdateExternalAuthLink(gomock.Any(), gomock.Any()).
Return(database.ExternalAuthLink{}, nil).AnyTimes()
const staticError = "static error"
validated := false
fake, config, link := setupOauth2Test(t, testConfig{
FakeIDPOpts: []oidctest.FakeIDPOpt{
oidctest.WithDynamicUserInfo(func(_ string) (jwt.MapClaims, error) {
validated = true
return jwt.MapClaims{}, oidctest.StatusError(http.StatusUnauthorized, xerrors.New(staticError))
}),
},
ExternalAuthOpt: func(cfg *externalauth.Config) {
},
})
ctx := oidc.ClientContext(context.Background(), fake.HTTPClient(nil))
link.OAuthExpiry = expired
_, err := config.RefreshToken(ctx, mDB, link)
require.ErrorContains(t, err, "token failed to validate")
require.True(t, externalauth.IsInvalidTokenError(err))
require.True(t, validated, "token should have been attempted to be validated")
})
t.Run("ValidateRetryGitHub", func(t *testing.T) {
t.Parallel()
const staticError = "static error"
validateCalls := 0
fake, config, link := setupOauth2Test(t, testConfig{
FakeIDPOpts: []oidctest.FakeIDPOpt{
oidctest.WithRefresh(func(_ string) error {
t.Error("refresh on the IDP was called, but the token is not expired")
return xerrors.New("should not be called")
}),
oidctest.WithDynamicUserInfo(func(_ string) (jwt.MapClaims, error) {
validateCalls++
// Make the first call return a 401, subsequent calls should return a 200.
if validateCalls > 1 {
return jwt.MapClaims{}, nil
}
return jwt.MapClaims{}, oidctest.StatusError(http.StatusUnauthorized, xerrors.New(staticError))
}),
},
ExternalAuthOpt: func(cfg *externalauth.Config) {
cfg.Type = codersdk.EnhancedExternalAuthProviderGitHub.String()
},
})
ctx := oidc.ClientContext(context.Background(), fake.HTTPClient(nil))
// Unlimited lifetime, this is what GitHub returns tokens as
link.OAuthExpiry = time.Time{}
_, err := config.RefreshToken(ctx, nil, link)
require.NoError(t, err)
require.Equal(t, 2, validateCalls, "token should have been attempted to be validated more than once")
})
t.Run("ValidateNoUpdate", func(t *testing.T) {
t.Parallel()
validateCalls := 0
fake, config, link := setupOauth2Test(t, testConfig{
FakeIDPOpts: []oidctest.FakeIDPOpt{
oidctest.WithRefresh(func(_ string) error {
t.Error("refresh on the IDP was called, but the token is not expired")
return xerrors.New("should not be called")
}),
oidctest.WithDynamicUserInfo(func(_ string) (jwt.MapClaims, error) {
validateCalls++
return jwt.MapClaims{}, nil
}),
},
ExternalAuthOpt: func(cfg *externalauth.Config) {
cfg.Type = codersdk.EnhancedExternalAuthProviderGitHub.String()
},
})
ctx := oidc.ClientContext(context.Background(), fake.HTTPClient(nil))
_, err := config.RefreshToken(ctx, nil, link)
require.NoError(t, err)
require.Equal(t, 1, validateCalls, "token is validated")
})
// A token update comes from a refresh.
t.Run("Updates", func(t *testing.T) {
t.Parallel()
db, _ := dbtestutil.NewDB(t)
validateCalls := 0
refreshCalls := 0
fake, config, link := setupOauth2Test(t, testConfig{
FakeIDPOpts: []oidctest.FakeIDPOpt{
oidctest.WithRefresh(func(_ string) error {
refreshCalls++
return nil
}),
oidctest.WithDynamicUserInfo(func(_ string) (jwt.MapClaims, error) {
validateCalls++
return jwt.MapClaims{}, nil
}),
},
ExternalAuthOpt: func(cfg *externalauth.Config) {
cfg.Type = codersdk.EnhancedExternalAuthProviderGitHub.String()
},
DB: db,
})
ctx := oidc.ClientContext(context.Background(), fake.HTTPClient(nil))
// Force a refresh
link.OAuthExpiry = expired
updated, err := config.RefreshToken(ctx, db, link)
require.NoError(t, err)
require.Equal(t, 1, validateCalls, "token is validated")
require.Equal(t, 1, refreshCalls, "token is refreshed")
require.NotEqualf(t, link.OAuthAccessToken, updated.OAuthAccessToken, "token is updated")
dbLink, err := db.GetExternalAuthLink(context.Background(), database.GetExternalAuthLinkParams{
ProviderID: link.ProviderID,
UserID: link.UserID,
})
require.NoError(t, err)
require.Equal(t, updated.OAuthAccessToken, dbLink.OAuthAccessToken, "token is updated in the DB")
})
t.Run("WithExtra", func(t *testing.T) {
t.Parallel()
db, _ := dbtestutil.NewDB(t)
fake, config, link := setupOauth2Test(t, testConfig{
FakeIDPOpts: []oidctest.FakeIDPOpt{
oidctest.WithMutateToken(func(token map[string]interface{}) {
token["authed_user"] = map[string]interface{}{
"access_token": token["access_token"],
}
}),
},
ExternalAuthOpt: func(cfg *externalauth.Config) {
cfg.Type = codersdk.EnhancedExternalAuthProviderSlack.String()
cfg.ExtraTokenKeys = []string{"authed_user"}
cfg.ValidateURL = ""
},
DB: db,
})
ctx := oidc.ClientContext(context.Background(), fake.HTTPClient(nil))
// Force a refresh
link.OAuthExpiry = expired
updated, err := config.RefreshToken(ctx, db, link)
require.NoError(t, err)
require.True(t, updated.OAuthExtra.Valid)
extra := map[string]interface{}{}
require.NoError(t, json.Unmarshal(updated.OAuthExtra.RawMessage, &extra))
mapping, ok := extra["authed_user"].(map[string]interface{})
require.True(t, ok)
require.Equal(t, updated.OAuthAccessToken, mapping["access_token"])
})
// SaveBeforeValidate tests that a successfully refreshed token is
// persisted to the DB even when post-refresh validation fails. This
// prevents the data-loss scenario where GitHub rotates the refresh
// token on use but the new token is silently discarded because a
// rate-limited validation endpoint returns 403.
t.Run("SaveBeforeValidate", func(t *testing.T) {
t.Parallel()
db, _ := dbtestutil.NewDB(t)
// simulateRateLimit controls whether the validate endpoint
// returns 403 (true) or 200 (false).
var simulateRateLimit atomic.Bool
simulateRateLimit.Store(true)
var refreshCalls atomic.Int64
fake, config, link := setupOauth2Test(t, testConfig{
FakeIDPOpts: []oidctest.FakeIDPOpt{
oidctest.WithRefresh(func(_ string) error {
refreshCalls.Add(1)
return nil
}),
oidctest.WithDynamicUserInfo(func(_ string) (jwt.MapClaims, error) {
if simulateRateLimit.Load() {
return jwt.MapClaims{}, oidctest.StatusError(http.StatusForbidden, xerrors.New("rate limit exceeded"))
}
return jwt.MapClaims{}, nil
}),
},
ExternalAuthOpt: func(cfg *externalauth.Config) {
cfg.Type = codersdk.EnhancedExternalAuthProviderGitHub.String()
},
DB: db,
})
ctx := oidc.ClientContext(context.Background(), fake.HTTPClient(nil))
oldAccessToken := link.OAuthAccessToken
oldRefreshToken := link.OAuthRefreshToken
// Expire the token to force a refresh.
link.OAuthExpiry = expired
// First call: refresh succeeds, validation fails (403).
_, err := config.RefreshToken(ctx, db, link)
require.Error(t, err, "expected error because validation returned 403")
require.True(t, externalauth.IsInvalidTokenError(err))
require.Equal(t, int64(1), refreshCalls.Load(), "IDP refresh should have been called exactly once")
// Critical assertion: the DB must contain the NEW tokens from the
// successful refresh, not the old (now-stale) ones.
dbLink, err := db.GetExternalAuthLink(context.Background(), database.GetExternalAuthLinkParams{
ProviderID: link.ProviderID,
UserID: link.UserID,
})
require.NoError(t, err)
require.NotEqual(t, oldAccessToken, dbLink.OAuthAccessToken,
"DB should have the new access token from the successful refresh")
require.NotEqual(t, oldRefreshToken, dbLink.OAuthRefreshToken,
"DB should have the new refresh token (old one was rotated by the IDP)")
// Second call: uses the saved token from DB, no re-refresh.
// The saved token has a future expiry, so TokenSource should return
// it without contacting the IDP. Validation should succeed now.
simulateRateLimit.Store(false)
updated, err := config.RefreshToken(ctx, db, dbLink)
require.NoError(t, err, "second call should succeed because rate limit lifted")
require.Equal(t, int64(1), refreshCalls.Load(),
"IDP refresh should NOT have been called again; the saved token is not expired")
require.Equal(t, dbLink.OAuthAccessToken, updated.OAuthAccessToken,
"returned token should match what was saved in the DB")
})
// SaveBeforeValidate_ContextCanceled verifies the early DB save
// uses a detached context. The parent context is canceled inside
// the refresh hook (after TokenSource.Token() but before the DB
// write), and the test asserts the new token is still persisted.
t.Run("SaveBeforeValidate_ContextCanceled", func(t *testing.T) {
t.Parallel()
db, _ := dbtestutil.NewDB(t)
var refreshCalls atomic.Int64
cancelOnRefresh, cancel := context.WithCancel(context.Background())
defer cancel()
fake, config, link := setupOauth2Test(t, testConfig{
FakeIDPOpts: []oidctest.FakeIDPOpt{
oidctest.WithRefresh(func(_ string) error {
refreshCalls.Add(1)
// Cancel the parent context after refresh succeeds
// but before the DB save and validation.
cancel()
return nil
}),
oidctest.WithDynamicUserInfo(func(_ string) (jwt.MapClaims, error) {
return jwt.MapClaims{}, nil
}),
},
ExternalAuthOpt: func(cfg *externalauth.Config) {
cfg.Type = codersdk.EnhancedExternalAuthProviderGitHub.String()
},
DB: db,
})
ctx := oidc.ClientContext(cancelOnRefresh, fake.HTTPClient(nil))
oldAccessToken := link.OAuthAccessToken
oldRefreshToken := link.OAuthRefreshToken
link.OAuthExpiry = expired
_, err := config.RefreshToken(ctx, db, link)
require.ErrorIs(t, err, context.Canceled)
require.Equal(t, int64(1), refreshCalls.Load())
require.Eventually(t, func() bool {
dbLink, err := db.GetExternalAuthLink(context.Background(), database.GetExternalAuthLinkParams{
ProviderID: link.ProviderID,
UserID: link.UserID,
})
if err != nil {
return false
}
return err == nil &&
dbLink.OAuthAccessToken != oldAccessToken &&
dbLink.OAuthRefreshToken != oldRefreshToken
}, testutil.WaitShort, testutil.IntervalFast, "never saw refresh token db updated")
})
// SaveBeforeValidate_RateLimited tests the full path: refresh
// succeeds, early save persists the token, validation returns
// rate-limited optimistic true, and RefreshToken returns success
// with no InvalidTokenError. Uses httptest.NewServer for the
// validate endpoint to set rate-limit headers that the FakeIDP's
// WithDynamicUserInfo hook cannot control.
t.Run("SaveBeforeValidate_RateLimited", func(t *testing.T) {
t.Parallel()
db, _ := dbtestutil.NewDB(t)
var refreshCalls atomic.Int64
// rateLimitValidate returns 403 with rate-limit headers.
rateLimitValidate := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("X-RateLimit-Remaining", "0")
w.Header().Set("X-RateLimit-Limit", "5000")
w.WriteHeader(http.StatusForbidden)
}))
t.Cleanup(rateLimitValidate.Close)
fake, config, link := setupOauth2Test(t, testConfig{
FakeIDPOpts: []oidctest.FakeIDPOpt{
oidctest.WithRefresh(func(_ string) error {
refreshCalls.Add(1)
return nil
}),
},
ExternalAuthOpt: func(cfg *externalauth.Config) {
cfg.Type = codersdk.EnhancedExternalAuthProviderGitHub.String()
cfg.ValidateURL = rateLimitValidate.URL
},
DB: db,
})
// Use a real HTTP transport for non-IDP requests so the
// validate request can reach the httptest server.
ctx := oidc.ClientContext(context.Background(), fake.HTTPClient(&http.Client{
Transport: http.DefaultTransport,
}))
oldAccessToken := link.OAuthAccessToken
oldRefreshToken := link.OAuthRefreshToken
// Expire the token to force a refresh.
link.OAuthExpiry = expired
// RefreshToken should succeed: the IDP refresh works, the
// early save persists the token, and ValidateToken returns
// (true, nil, nil) because the 403 has rate-limit headers.
updated, err := config.RefreshToken(ctx, db, link)
require.NoError(t, err, "RefreshToken should succeed when validation is rate-limited")
require.Equal(t, int64(1), refreshCalls.Load(), "IDP refresh should have been called")
require.NotEqual(t, oldAccessToken, updated.OAuthAccessToken,
"returned token should be the new one from the refresh")
// Verify the DB has the new token.
dbLink, err := db.GetExternalAuthLink(context.Background(), database.GetExternalAuthLinkParams{
ProviderID: link.ProviderID,
UserID: link.UserID,
})
require.NoError(t, err)
require.Equal(t, updated.OAuthAccessToken, dbLink.OAuthAccessToken,
"DB should have the refreshed access token")
require.NotEqual(t, oldRefreshToken, dbLink.OAuthRefreshToken,
"DB should have the new refresh token (old one was rotated by the IDP)")
})
// SaveBeforeValidate_DBError tests that when the early DB save
// fails after a successful IDP refresh, the error is surfaced
// as a non-InvalidTokenError. This is a degraded state (token
// issued by IDP but not persisted), and callers should see a
// real error, not a "please re-authenticate" prompt.
t.Run("SaveBeforeValidate_DBError", func(t *testing.T) {
t.Parallel()
ctrl := gomock.NewController(t)
mDB := dbmock.NewMockStore(ctrl)
fake, config, link := setupOauth2Test(t, testConfig{
FakeIDPOpts: []oidctest.FakeIDPOpt{
oidctest.WithRefresh(func(_ string) error {
return nil
}),
},
ExternalAuthOpt: func(cfg *externalauth.Config) {
cfg.Type = codersdk.EnhancedExternalAuthProviderGitHub.String()
},
})
ctx := oidc.ClientContext(context.Background(), fake.HTTPClient(nil))
link.OAuthExpiry = expired
mDB.EXPECT().
UpdateExternalAuthLink(gomock.Any(), gomock.Any()).
Return(database.ExternalAuthLink{}, xerrors.New("db connection lost"))
_, err := config.RefreshToken(ctx, mDB, link)
require.Error(t, err)
require.Contains(t, err.Error(), "persist refreshed token")
require.False(t, externalauth.IsInvalidTokenError(err),
"DB errors should not be treated as invalid token")
})
// OptimisticLockPreventsStaleOverwrite verifies that the
// UpdateExternalAuthLinkRefreshToken WHERE clause prevents a
// stale caller from overwriting a valid refresh token saved
// by a concurrent winner.
t.Run("OptimisticLockPreventsStaleOverwrite", func(t *testing.T) {
t.Parallel()
db, _ := dbtestutil.NewDB(t)
fake, config, link := setupOauth2Test(t, testConfig{
FakeIDPOpts: []oidctest.FakeIDPOpt{
oidctest.WithRefresh(func(_ string) error {
return nil
}),
oidctest.WithDynamicUserInfo(func(_ string) (jwt.MapClaims, error) {
return jwt.MapClaims{}, nil
}),
},
ExternalAuthOpt: func(cfg *externalauth.Config) {
cfg.Type = codersdk.EnhancedExternalAuthProviderGitHub.String()
},
DB: db,