-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathexternalauth_test.go
More file actions
2659 lines (2337 loc) · 89.4 KB
/
Copy pathexternalauth_test.go
File metadata and controls
2659 lines (2337 loc) · 89.4 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"
"database/sql"
"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/lib/pq"
"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/dbgen"
"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/externalauth/gitprovider"
"github.com/coder/coder/v2/coderd/promoauth"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/testutil"
)
func TestConfigGitMemoizesProvider(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitShort)
const etag = `"config-git-memo-etag"`
var conditionalRequests atomic.Int64
srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if inm := r.Header.Get("If-None-Match"); inm != "" {
conditionalRequests.Add(1)
assert.Equal(t, etag, inm)
w.Header().Set("ETag", etag)
w.WriteHeader(http.StatusNotModified)
return
}
w.Header().Set("Content-Type", "application/json")
w.Header().Set("ETag", etag)
_, _ = w.Write([]byte(`[]`))
}))
defer srv.Close()
cfg := &externalauth.Config{
Type: string(codersdk.EnhancedExternalAuthProviderGitHub),
APIBaseURL: srv.URL + "/api/v3",
HTTPClient: srv.Client(),
}
gp1, err := cfg.Git()
require.NoError(t, err)
require.NotNil(t, gp1)
branch := gitprovider.BranchRef{Owner: "owner", Repo: "repo", Branch: "feat"}
// Cold poll: populates the provider's ETag cache.
_, err = gp1.ResolveBranchPullRequest(ctx, "test-token", branch)
require.NoError(t, err)
// Re-resolve the provider, as the worker does on every poll.
gp2, err := cfg.Git()
require.NoError(t, err)
require.NotNil(t, gp2)
assert.Same(t, gp1, gp2, "Git must return the same provider instance so its ETag cache survives across calls")
_, err = gp2.ResolveBranchPullRequest(ctx, "test-token", branch)
require.NoError(t, err)
assert.Equal(t, int64(1), conditionalRequests.Load(), "second poll should have revalidated with If-None-Match using the cache from the first poll")
}
func TestConfigGitRetriesOnConstructorError(t *testing.T) {
t.Parallel()
cfg := &externalauth.Config{
Type: string(codersdk.EnhancedExternalAuthProviderGitLab),
APIBaseURL: "://invalid",
}
_, err1 := cfg.Git()
require.Error(t, err1)
_, err2 := cfg.Git()
require.Error(t, err2)
// A memoized error would be the same instance; a retried
// construction produces a fresh error each call.
require.NotErrorIs(t, err2, err1, "construction errors must be retried, not memoized")
}
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
// Should abort before entering the group.
cfg.RefreshGroup = nil
},
ExternalAuthLinkOpts: func(link *database.ExternalAuthLink) {
link.OAuthExpiry = expired
},
})
mDB := mockDB(t)
// There should be no database calls since we return early.
ctx := oidc.ClientContext(testutil.Context(t, testutil.WaitLong), fake.HTTPClient(nil))
_, err := config.RefreshToken(ctx, mDB, link)
require.Error(t, err)
require.True(t, externalauth.IsInvalidTokenError(err))
require.Contains(t, err.Error(), "token expired and refreshing is disabled")
})
// 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
},
})
mDB := mockDB(t)
ctx := oidc.ClientContext(testutil.Context(t, testutil.WaitLong), fake.HTTPClient(nil))
// Zero time used
link.OAuthExpiry = time.Time{}
// Since the token is not expired, no refresh lease will be acquired and
// it will only be validated.
_, err := config.RefreshToken(ctx, mDB, 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),
}
link := database.ExternalAuthLink{
OAuthExpiry: expired,
}
mDB := mockDB(t, withLease(link))
ctx := testutil.Context(t, testutil.WaitLong)
_, err := config.RefreshToken(ctx, mDB, link)
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()
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) {
},
})
mDB := mockDB(t,
withLease(link),
withUpdatePassthrough())
ctx := oidc.ClientContext(testutil.Context(t, testutil.WaitLong), 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 external 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
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
},
ExternalAuthLinkOpts: func(link *database.ExternalAuthLink) {
link.OAuthExpiry = expired
},
})
// Allow acquiring and releasing the lease for all the temporary error
// attempts, the bad refresh token attempt, and then finally the last
// attempt with no refresh token set.
mDB := mockDB(t,
withLease(link),
withLease(link),
withLease(link),
withLease(link))
ctx := oidc.ClientContext(testutil.Context(t, testutil.WaitLong), fake.HTTPClient(nil))
// 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)
}
// The final attempt will be a permanent error and we should see the
// database update with the error. Need to extract it from the mock call
// like this rather than use the returned link from RefreshToken as it does
// not return the updated link in the error case.
mDB.EXPECT().UpdateExternalAuthLink(gomock.Any(), gomock.Any()).
DoAndReturn(func(_ context.Context, p database.UpdateExternalAuthLinkParams) (database.ExternalAuthLink, error) {
link = database.ExternalAuthLink{
ProviderID: p.ProviderID,
UserID: p.UserID,
OAuthAccessToken: p.OAuthAccessToken,
// This should be zeroed out.
OAuthRefreshToken: p.OAuthRefreshToken,
OAuthExpiry: p.OAuthExpiry,
OauthRefreshFailureReason: p.OauthRefreshFailureReason,
}
return link, nil
}).Times(1)
refreshErr = &oauth2.RetrieveError{ // github error
Response: &http.Response{
StatusCode: http.StatusOK,
},
ErrorCode: "bad_refresh_token",
}
zeroedLink, err := config.RefreshToken(ctx, mDB, link)
require.Error(t, err)
totalRefreshes++
require.True(t, externalauth.IsInvalidTokenError(err))
require.Equal(t, refreshCount, totalRefreshes)
// Although the fully updated link with the error is not returned, it does
// zero out the token.
require.Empty(t, zeroedLink.OAuthRefreshToken)
// Databasae link should have a reason and no refresh token.
require.NotEmpty(t, link.OauthRefreshFailureReason)
require.Empty(t, link.OAuthRefreshToken)
// Once more, this time with the zeroed-out refresh token due to the bad
// refresh error.
withLease(link)(mDB)
// When the refresh token is empty, no api calls should be made
_, err = config.RefreshToken(ctx, mDB, link)
require.Error(t, err)
require.True(t, externalauth.IsInvalidTokenError(err))
require.Equal(t, refreshCount, totalRefreshes)
// It should return the original cached error, not "no refresh token".
require.ErrorContains(t, err, "a long while ago")
require.ErrorContains(t, err, "bad_refresh_token")
})
// 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,
ExternalAuthLinkOpts: func(link *database.ExternalAuthLink) {
link.OAuthExpiry = expired
},
})
ctx := oidc.ClientContext(testutil.Context(t, testutil.WaitLong), fake.HTTPClient(nil))
oldAccessToken := link.OAuthAccessToken
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()
db, _ := dbtestutil.NewDB(t)
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
},
ExternalAuthLinkOpts: func(link *database.ExternalAuthLink) {
link.OAuthExpiry = expired
},
DB: db,
})
ctx := oidc.ClientContext(testutil.Context(t, testutil.WaitLong), fake.HTTPClient(nil))
_, err := config.RefreshToken(ctx, db, 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()
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}
// Only one call should try to acquire and release a lease and only one call
// should update the link.
mDB := mockDB(t,
withLease(link),
withUpdatePassthrough())
// 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, refreshedToken.AccessToken, results[i].OAuthAccessToken)
require.Equal(t, refreshedToken.RefreshToken, results[i].OAuthRefreshToken)
}
// 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 that group.
//
// This request would fail with `bad_refresh_token` for providers that have
// single-use refresh tokens. It should instead re-read the token from the
// database 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()
fake, config, link := setupOauth2Test(t, testConfig{
FakeIDPOpts: []oidctest.FakeIDPOpt{
oidctest.WithRefresh(func(_ string) error {
return xerrors.New("should not reach this")
}),
},
ExternalAuthLinkOpts: func(link *database.ExternalAuthLink) {
link.OAuthExpiry = expired
},
})
ctx := oidc.ClientContext(testutil.Context(t, testutil.WaitLong), fake.HTTPClient(nil))
winnerLink := link
winnerLink.OAuthRefreshToken = "winner-refresh-token"
winnerLink.OAuthAccessToken = "winner-access-token"
// Simulate that another caller updated the link.
// UpdateExternalAuthLinkRefreshToken should NOT be called because trying to
// get the lease detected the nearly-concurrent refresh. It should instead
// return the winning token.
mDB := mockDB(t, withLease(winnerLink))
result, err := config.RefreshToken(ctx, mDB, link)
require.NoError(t, err, "loser should succeed using the winner's token")
require.Equal(t, winnerLink.OAuthAccessToken, result.OAuthAccessToken)
require.Equal(t, winnerLink.OAuthRefreshToken, 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
}
}
}
return xerrors.New("should not reach this")
}),
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,
ExternalAuthLinkOpts: func(link *database.ExternalAuthLink) {
link.OAuthExpiry = expired
},
})
oldAccessToken := link.OAuthAccessToken
oldRefreshToken := link.OAuthRefreshToken
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(ctx, 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())
})
t.Run("LeaseAcquisitionError", func(t *testing.T) {
t.Parallel()
fake, config, link := setupOauth2Test(t, testConfig{
FakeIDPOpts: []oidctest.FakeIDPOpt{
oidctest.WithRefresh(func(_ string) error {
return nil
}),
},
ExternalAuthOpt: func(cfg *externalauth.Config) {},
ExternalAuthLinkOpts: func(link *database.ExternalAuthLink) {
link.OAuthExpiry = expired
},
})
mDB := mockDB(t, withLeaseErrors(link, xerrors.New("acquire error"), nil))
ctx := oidc.ClientContext(testutil.Context(t, testutil.WaitLong), fake.HTTPClient(nil))
_, err := config.RefreshToken(ctx, mDB, link)
require.Error(t, err)
require.ErrorContains(t, err, "acquire error")
})
t.Run("ReturnsReleaseError", func(t *testing.T) {
t.Parallel()
fake, config, link := setupOauth2Test(t, testConfig{
FakeIDPOpts: []oidctest.FakeIDPOpt{
oidctest.WithRefresh(func(_ string) error {
return nil
}),
},
ExternalAuthOpt: func(cfg *externalauth.Config) {},
ExternalAuthLinkOpts: func(link *database.ExternalAuthLink) {
link.OAuthExpiry = expired
},
})
mDB := mockDB(t,
withLeaseErrors(link, nil, xerrors.New("release error")),
withUpdatePassthrough())
// Although the refresh was successful, an error is still returned due to
// the release having failed.
ctx := oidc.ClientContext(testutil.Context(t, testutil.WaitLong), fake.HTTPClient(nil))
refreshed, err := config.RefreshToken(ctx, mDB, link)
require.Error(t, err)
require.ErrorContains(t, err, "release error")
require.NotEqual(t, link.OAuthAccessToken, refreshed.OAuthAccessToken)
require.NotEqual(t, link.OAuthRefreshToken, refreshed.OAuthRefreshToken)
})
t.Run("ReturnsCombinedWithReleaseError", func(t *testing.T) {
t.Parallel()
fake, config, link := setupOauth2Test(t, testConfig{
FakeIDPOpts: []oidctest.FakeIDPOpt{
oidctest.WithRefresh(func(_ string) error {
return nil
}),
},
ExternalAuthOpt: func(cfg *externalauth.Config) {},
ExternalAuthLinkOpts: func(link *database.ExternalAuthLink) {
link.OAuthExpiry = expired
},
})
mDB := mockDB(t,
withLeaseErrors(link, nil, xerrors.New("release error")),
withUpdateError(xerrors.New("update error")))
// Both the release and update errors should be returned.
ctx := oidc.ClientContext(testutil.Context(t, testutil.WaitLong), fake.HTTPClient(nil))
_, err := config.RefreshToken(ctx, mDB, link)
require.Error(t, err)
require.ErrorContains(t, err, "release error")
require.ErrorContains(t, err, "update error")
})
// ValidateFailure tests if the token is no longer valid with a 401 response.
t.Run("ValidateFailure", func(t *testing.T) {
t.Parallel()
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(testutil.Context(t, testutil.WaitLong), fake.HTTPClient(nil))
link.OAuthExpiry = expired
mDB := mockDB(t,
withLease(link),
withUpdatePassthrough())
_, 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()
},
ExternalAuthLinkOpts: func(link *database.ExternalAuthLink) {
// Unlimited lifetime, this is what GitHub returns tokens as.
link.OAuthExpiry = time.Time{}
},
})
// Since the token is not expired, no lock or refresh lease will be acquired
// and it will only be validated.
mDB := mockDB(t)
ctx := oidc.ClientContext(testutil.Context(t, testutil.WaitLong), fake.HTTPClient(nil))
_, err := config.RefreshToken(ctx, mDB, 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()
},
})
// Since the token is not expired, no lock or refresh lease will be acquired
// and it will only be validated.
mDB := mockDB(t)
ctx := oidc.ClientContext(testutil.Context(t, testutil.WaitLong), fake.HTTPClient(nil))
_, err := config.RefreshToken(ctx, mDB, 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,
ExternalAuthLinkOpts: func(link *database.ExternalAuthLink) {
link.OAuthExpiry = expired
},
})
ctx := oidc.ClientContext(testutil.Context(t, testutil.WaitLong), fake.HTTPClient(nil))
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(ctx, 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,
ExternalAuthLinkOpts: func(link *database.ExternalAuthLink) {
link.OAuthExpiry = expired
},
})
ctx := oidc.ClientContext(testutil.Context(t, testutil.WaitLong), fake.HTTPClient(nil))
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,
ExternalAuthLinkOpts: func(link *database.ExternalAuthLink) {
link.OAuthExpiry = expired
},
})
ctx := oidc.ClientContext(testutil.Context(t, testutil.WaitLong), fake.HTTPClient(nil))
oldAccessToken := link.OAuthAccessToken
oldRefreshToken := link.OAuthRefreshToken
// 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(ctx, 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")