-
Notifications
You must be signed in to change notification settings - Fork 586
/
idp.go
1442 lines (1264 loc) · 44.3 KB
/
idp.go
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 oidctest
import (
"context"
"crypto"
"crypto/rsa"
"crypto/x509"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"io"
"math/rand"
"mime"
"net"
"net/http"
"net/http/cookiejar"
"net/http/httptest"
"net/http/httputil"
"net/url"
"strconv"
"strings"
"testing"
"time"
"github.com/coreos/go-oidc/v3/oidc"
"github.com/go-chi/chi/v5"
"github.com/go-jose/go-jose/v3"
"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"
"golang.org/x/oauth2"
"golang.org/x/xerrors"
"cdr.dev/slog"
"cdr.dev/slog/sloggers/slogtest"
"github.com/coder/coder/v2/coderd"
"github.com/coder/coder/v2/coderd/externalauth"
"github.com/coder/coder/v2/coderd/httpapi"
"github.com/coder/coder/v2/coderd/promoauth"
"github.com/coder/coder/v2/coderd/util/syncmap"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/testutil"
)
type token struct {
issued time.Time
email string
exp time.Time
}
type deviceFlow struct {
// userInput is the expected input to authenticate the device flow.
userInput string
exp time.Time
granted bool
}
// FakeIDP is a functional OIDC provider.
// It only supports 1 OIDC client.
type FakeIDP struct {
issuer string
issuerURL *url.URL
key *rsa.PrivateKey
provider ProviderJSON
handler http.Handler
cfg *oauth2.Config
// callbackPath allows changing where the callback path to coderd is expected.
// This only affects using the Login helper functions.
callbackPath string
// clientID to be used by coderd
clientID string
clientSecret string
// externalProviderID is optional to match the provider in coderd for
// redirectURLs.
externalProviderID string
logger slog.Logger
// externalAuthValidate will be called when the user tries to validate their
// external auth. The fake IDP will reject any invalid tokens, so this just
// controls the response payload after a successfully authed token.
externalAuthValidate func(email string, rw http.ResponseWriter, r *http.Request)
// These maps are used to control the state of the IDP.
// That is the various access tokens, refresh tokens, states, etc.
codeToStateMap *syncmap.Map[string, string]
// Token -> Email
accessTokens *syncmap.Map[string, token]
// Refresh Token -> Email
refreshTokensUsed *syncmap.Map[string, bool]
refreshTokens *syncmap.Map[string, string]
stateToIDTokenClaims *syncmap.Map[string, jwt.MapClaims]
refreshIDTokenClaims *syncmap.Map[string, jwt.MapClaims]
// Device flow
deviceCode *syncmap.Map[string, deviceFlow]
// hooks
// hookValidRedirectURL can be used to reject a redirect url from the
// IDP -> Application. Almost all IDPs have the concept of
// "Authorized Redirect URLs". This can be used to emulate that.
hookValidRedirectURL func(redirectURL string) error
hookUserInfo func(email string) (jwt.MapClaims, error)
// defaultIDClaims is if a new client connects and we didn't preset
// some claims.
defaultIDClaims jwt.MapClaims
hookMutateToken func(token map[string]interface{})
fakeCoderd func(req *http.Request) (*http.Response, error)
hookOnRefresh func(email string) error
// Custom authentication for the client. This is useful if you want
// to test something like PKI auth vs a client_secret.
hookAuthenticateClient func(t testing.TB, req *http.Request) (url.Values, error)
serve bool
// optional middlewares
middlewares chi.Middlewares
defaultExpire time.Duration
}
func StatusError(code int, err error) error {
return statusHookError{
Err: err,
HTTPStatusCode: code,
}
}
// statusHookError allows a hook to change the returned http status code.
type statusHookError struct {
Err error
HTTPStatusCode int
}
func (s statusHookError) Error() string {
if s.Err == nil {
return ""
}
return s.Err.Error()
}
type FakeIDPOpt func(idp *FakeIDP)
func WithAuthorizedRedirectURL(hook func(redirectURL string) error) func(*FakeIDP) {
return func(f *FakeIDP) {
f.hookValidRedirectURL = hook
}
}
func WithMiddlewares(mws ...func(http.Handler) http.Handler) func(*FakeIDP) {
return func(f *FakeIDP) {
f.middlewares = append(f.middlewares, mws...)
}
}
// WithRefresh is called when a refresh token is used. The email is
// the email of the user that is being refreshed assuming the claims are correct.
func WithRefresh(hook func(email string) error) func(*FakeIDP) {
return func(f *FakeIDP) {
f.hookOnRefresh = hook
}
}
func WithDefaultExpire(d time.Duration) func(*FakeIDP) {
return func(f *FakeIDP) {
f.defaultExpire = d
}
}
func WithCallbackPath(path string) func(*FakeIDP) {
return func(f *FakeIDP) {
f.callbackPath = path
}
}
func WithStaticCredentials(id, secret string) func(*FakeIDP) {
return func(f *FakeIDP) {
if id != "" {
f.clientID = id
}
if secret != "" {
f.clientSecret = secret
}
}
}
// WithExtra returns extra fields that be accessed on the returned Oauth Token.
// These extra fields can override the default fields (id_token, access_token, etc).
func WithMutateToken(mutateToken func(token map[string]interface{})) func(*FakeIDP) {
return func(f *FakeIDP) {
f.hookMutateToken = mutateToken
}
}
func WithCustomClientAuth(hook func(t testing.TB, req *http.Request) (url.Values, error)) func(*FakeIDP) {
return func(f *FakeIDP) {
f.hookAuthenticateClient = hook
}
}
// WithLogging is optional, but will log some HTTP calls made to the IDP.
func WithLogging(t testing.TB, options *slogtest.Options) func(*FakeIDP) {
return func(f *FakeIDP) {
f.logger = slogtest.Make(t, options)
}
}
func WithLogger(logger slog.Logger) func(*FakeIDP) {
return func(f *FakeIDP) {
f.logger = logger
}
}
// WithStaticUserInfo is optional, but will return the same user info for
// every user on the /userinfo endpoint.
func WithStaticUserInfo(info jwt.MapClaims) func(*FakeIDP) {
return func(f *FakeIDP) {
f.hookUserInfo = func(_ string) (jwt.MapClaims, error) {
return info, nil
}
}
}
func WithDefaultIDClaims(claims jwt.MapClaims) func(*FakeIDP) {
return func(f *FakeIDP) {
f.defaultIDClaims = claims
}
}
func WithDynamicUserInfo(userInfoFunc func(email string) (jwt.MapClaims, error)) func(*FakeIDP) {
return func(f *FakeIDP) {
f.hookUserInfo = userInfoFunc
}
}
// WithServing makes the IDP run an actual http server.
func WithServing() func(*FakeIDP) {
return func(f *FakeIDP) {
f.serve = true
}
}
func WithIssuer(issuer string) func(*FakeIDP) {
return func(f *FakeIDP) {
f.issuer = issuer
}
}
type With429Arguments struct {
AllPaths bool
TokenPath bool
AuthorizePath bool
KeysPath bool
UserInfoPath bool
DeviceAuth bool
DeviceVerify bool
}
// With429 will emulate a 429 response for the selected paths.
func With429(params With429Arguments) func(*FakeIDP) {
return func(f *FakeIDP) {
f.middlewares = append(f.middlewares, func(next http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
if params.AllPaths {
http.Error(rw, "429, being manually blocked (all)", http.StatusTooManyRequests)
return
}
if params.TokenPath && strings.Contains(r.URL.Path, tokenPath) {
http.Error(rw, "429, being manually blocked (token)", http.StatusTooManyRequests)
return
}
if params.AuthorizePath && strings.Contains(r.URL.Path, authorizePath) {
http.Error(rw, "429, being manually blocked (authorize)", http.StatusTooManyRequests)
return
}
if params.KeysPath && strings.Contains(r.URL.Path, keysPath) {
http.Error(rw, "429, being manually blocked (keys)", http.StatusTooManyRequests)
return
}
if params.UserInfoPath && strings.Contains(r.URL.Path, userInfoPath) {
http.Error(rw, "429, being manually blocked (userinfo)", http.StatusTooManyRequests)
return
}
if params.DeviceAuth && strings.Contains(r.URL.Path, deviceAuth) {
http.Error(rw, "429, being manually blocked (device-auth)", http.StatusTooManyRequests)
return
}
if params.DeviceVerify && strings.Contains(r.URL.Path, deviceVerify) {
http.Error(rw, "429, being manually blocked (device-verify)", http.StatusTooManyRequests)
return
}
next.ServeHTTP(rw, r)
})
})
}
}
const (
// nolint:gosec // It thinks this is a secret lol
tokenPath = "/oauth2/token"
authorizePath = "/oauth2/authorize"
keysPath = "/oauth2/keys"
userInfoPath = "/oauth2/userinfo"
deviceAuth = "/login/device/code"
deviceVerify = "/login/device"
)
func NewFakeIDP(t testing.TB, opts ...FakeIDPOpt) *FakeIDP {
t.Helper()
block, _ := pem.Decode([]byte(testRSAPrivateKey))
pkey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
require.NoError(t, err)
idp := &FakeIDP{
key: pkey,
clientID: uuid.NewString(),
clientSecret: uuid.NewString(),
logger: slog.Make(),
codeToStateMap: syncmap.New[string, string](),
accessTokens: syncmap.New[string, token](),
refreshTokens: syncmap.New[string, string](),
refreshTokensUsed: syncmap.New[string, bool](),
stateToIDTokenClaims: syncmap.New[string, jwt.MapClaims](),
refreshIDTokenClaims: syncmap.New[string, jwt.MapClaims](),
deviceCode: syncmap.New[string, deviceFlow](),
hookOnRefresh: func(_ string) error { return nil },
hookUserInfo: func(email string) (jwt.MapClaims, error) { return jwt.MapClaims{}, nil },
hookValidRedirectURL: func(redirectURL string) error { return nil },
defaultExpire: time.Minute * 5,
}
for _, opt := range opts {
opt(idp)
}
if idp.issuer == "" {
idp.issuer = "https://coder.com"
}
idp.handler = idp.httpHandler(t)
idp.updateIssuerURL(t, idp.issuer)
if idp.serve {
idp.realServer(t)
}
return idp
}
func (f *FakeIDP) WellknownConfig() ProviderJSON {
return f.provider
}
func (f *FakeIDP) IssuerURL() *url.URL {
return f.issuerURL
}
func (f *FakeIDP) updateIssuerURL(t testing.TB, issuer string) {
t.Helper()
u, err := url.Parse(issuer)
require.NoError(t, err, "invalid issuer URL")
f.issuer = issuer
f.issuerURL = u
// ProviderJSON is the JSON representation of the OpenID Connect provider
// These are all the urls that the IDP will respond to.
f.provider = ProviderJSON{
Issuer: issuer,
AuthURL: u.ResolveReference(&url.URL{Path: authorizePath}).String(),
TokenURL: u.ResolveReference(&url.URL{Path: tokenPath}).String(),
JWKSURL: u.ResolveReference(&url.URL{Path: keysPath}).String(),
UserInfoURL: u.ResolveReference(&url.URL{Path: userInfoPath}).String(),
DeviceCodeURL: u.ResolveReference(&url.URL{Path: deviceAuth}).String(),
Algorithms: []string{
"RS256",
},
ExternalAuthURL: u.ResolveReference(&url.URL{Path: "/external-auth-validate/user"}).String(),
}
}
// realServer turns the FakeIDP into a real http server.
func (f *FakeIDP) realServer(t testing.TB) *httptest.Server {
t.Helper()
srvURL := "localhost:0"
issURL, err := url.Parse(f.issuer)
if err == nil {
if issURL.Hostname() == "localhost" || issURL.Hostname() == "127.0.0.1" {
srvURL = issURL.Host
}
}
l, err := net.Listen("tcp", srvURL)
require.NoError(t, err, "failed to create listener")
ctx, cancel := context.WithCancel(context.Background())
srv := &httptest.Server{
Listener: l,
Config: &http.Server{Handler: f.handler, ReadHeaderTimeout: time.Second * 5},
}
srv.Config.BaseContext = func(_ net.Listener) context.Context {
return ctx
}
srv.Start()
t.Cleanup(srv.CloseClientConnections)
t.Cleanup(srv.Close)
t.Cleanup(cancel)
f.updateIssuerURL(t, srv.URL)
return srv
}
// GenerateAuthenticatedToken skips all oauth2 flows, and just generates a
// valid token for some given claims.
func (f *FakeIDP) GenerateAuthenticatedToken(claims jwt.MapClaims) (*oauth2.Token, error) {
state := uuid.NewString()
f.stateToIDTokenClaims.Store(state, claims)
code := f.newCode(state)
return f.cfg.Exchange(oidc.ClientContext(context.Background(), f.HTTPClient(nil)), code)
}
// Login does the full OIDC flow starting at the "LoginButton".
// The client argument is just to get the URL of the Coder instance.
//
// The client passed in is just to get the url of the Coder instance.
// The actual client that is used is 100% unauthenticated and fresh.
func (f *FakeIDP) Login(t testing.TB, client *codersdk.Client, idTokenClaims jwt.MapClaims, opts ...func(r *http.Request)) (*codersdk.Client, *http.Response) {
t.Helper()
client, resp := f.AttemptLogin(t, client, idTokenClaims, opts...)
if resp.StatusCode != http.StatusOK {
data, err := httputil.DumpResponse(resp, true)
if err == nil {
t.Logf("Attempt Login response payload\n%s", string(data))
}
}
require.Equal(t, http.StatusOK, resp.StatusCode, "client failed to login")
return client, resp
}
func (f *FakeIDP) AttemptLogin(t testing.TB, client *codersdk.Client, idTokenClaims jwt.MapClaims, opts ...func(r *http.Request)) (*codersdk.Client, *http.Response) {
t.Helper()
var err error
cli := f.HTTPClient(client.HTTPClient)
shallowCpyCli := *cli
if shallowCpyCli.Jar == nil {
shallowCpyCli.Jar, err = cookiejar.New(nil)
require.NoError(t, err, "failed to create cookie jar")
}
unauthenticated := codersdk.New(client.URL)
unauthenticated.HTTPClient = &shallowCpyCli
return f.LoginWithClient(t, unauthenticated, idTokenClaims, opts...)
}
// LoginWithClient reuses the context of the passed in client. This means the same
// cookies will be used. This should be an unauthenticated client in most cases.
//
// This is a niche case, but it is needed for testing ConvertLoginType.
func (f *FakeIDP) LoginWithClient(t testing.TB, client *codersdk.Client, idTokenClaims jwt.MapClaims, opts ...func(r *http.Request)) (*codersdk.Client, *http.Response) {
t.Helper()
path := "/api/v2/users/oidc/callback"
if f.callbackPath != "" {
path = f.callbackPath
}
coderOauthURL, err := client.URL.Parse(path)
require.NoError(t, err)
f.SetRedirect(t, coderOauthURL.String())
cli := f.HTTPClient(client.HTTPClient)
cli.CheckRedirect = func(req *http.Request, via []*http.Request) error {
// Store the idTokenClaims to the specific state request. This ties
// the claims 1:1 with a given authentication flow.
state := req.URL.Query().Get("state")
f.stateToIDTokenClaims.Store(state, idTokenClaims)
return nil
}
req, err := http.NewRequestWithContext(context.Background(), "GET", coderOauthURL.String(), nil)
require.NoError(t, err)
if cli.Jar == nil {
cli.Jar, err = cookiejar.New(nil)
require.NoError(t, err, "failed to create cookie jar")
}
for _, opt := range opts {
opt(req)
}
res, err := cli.Do(req)
require.NoError(t, err)
// If the coder session token exists, return the new authed client!
var user *codersdk.Client
cookies := cli.Jar.Cookies(client.URL)
for _, cookie := range cookies {
if cookie.Name == codersdk.SessionTokenCookie {
user = codersdk.New(client.URL)
user.SetSessionToken(cookie.Value)
}
}
t.Cleanup(func() {
if res.Body != nil {
_ = res.Body.Close()
}
})
return user, res
}
// ExternalLogin does the oauth2 flow for external auth providers. This requires
// an authenticated coder client.
func (f *FakeIDP) ExternalLogin(t testing.TB, client *codersdk.Client, opts ...func(r *http.Request)) {
coderOauthURL, err := client.URL.Parse(fmt.Sprintf("/external-auth/%s/callback", f.externalProviderID))
require.NoError(t, err)
f.SetRedirect(t, coderOauthURL.String())
cli := f.HTTPClient(client.HTTPClient)
cli.CheckRedirect = func(req *http.Request, via []*http.Request) error {
// Store the idTokenClaims to the specific state request. This ties
// the claims 1:1 with a given authentication flow.
state := req.URL.Query().Get("state")
f.stateToIDTokenClaims.Store(state, jwt.MapClaims{})
return nil
}
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
req, err := http.NewRequestWithContext(ctx, "GET", coderOauthURL.String(), nil)
require.NoError(t, err)
// External auth flow requires the user be authenticated.
headerName := client.SessionTokenHeader
if headerName == "" {
headerName = codersdk.SessionTokenHeader
}
req.Header.Set(headerName, client.SessionToken())
if cli.Jar == nil {
cli.Jar, err = cookiejar.New(nil)
require.NoError(t, err, "failed to create cookie jar")
}
for _, opt := range opts {
opt(req)
}
res, err := cli.Do(req)
require.NoError(t, err)
require.Equal(t, http.StatusOK, res.StatusCode, "client failed to login")
_ = res.Body.Close()
}
// DeviceLogin does the oauth2 device flow for external auth providers.
func (*FakeIDP) DeviceLogin(t testing.TB, client *codersdk.Client, externalAuthID string) {
// First we need to initiate the device flow. This will have Coder hit the
// fake IDP and get a device code.
device, err := client.ExternalAuthDeviceByID(context.Background(), externalAuthID)
require.NoError(t, err)
// Now the user needs to go to the fake IDP page and click "allow" and enter
// the device code input. For our purposes, we just send an http request to
// the verification url. No additional user input is needed.
ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitShort)
defer cancel()
resp, err := client.Request(ctx, http.MethodPost, device.VerificationURI, nil)
require.NoError(t, err)
defer resp.Body.Close()
// Now we need to exchange the device code for an access token. We do this
// in this method because it is the user that does the polling for the device
// auth flow, not the backend.
err = client.ExternalAuthDeviceExchange(context.Background(), externalAuthID, codersdk.ExternalAuthDeviceExchange{
DeviceCode: device.DeviceCode,
})
require.NoError(t, err)
}
// CreateAuthCode emulates a user clicking "allow" on the IDP page. When doing
// unit tests, it's easier to skip this step sometimes. It does make an actual
// request to the IDP, so it should be equivalent to doing this "manually" with
// actual requests.
func (f *FakeIDP) CreateAuthCode(t testing.TB, state string) string {
// We need to store some claims, because this is also an OIDC provider, and
// it expects some claims to be present.
f.stateToIDTokenClaims.Store(state, jwt.MapClaims{})
code, err := OAuth2GetCode(f.cfg.AuthCodeURL(state), func(req *http.Request) (*http.Response, error) {
rw := httptest.NewRecorder()
f.handler.ServeHTTP(rw, req)
resp := rw.Result()
return resp, nil
})
require.NoError(t, err, "failed to get auth code")
return code
}
// OIDCCallback will emulate the IDP redirecting back to the Coder callback.
// This is helpful if no Coderd exists because the IDP needs to redirect to
// something.
// Essentially this is used to fake the Coderd side of the exchange.
// The flow starts at the user hitting the OIDC login page.
func (f *FakeIDP) OIDCCallback(t testing.TB, state string, idTokenClaims jwt.MapClaims) *http.Response {
t.Helper()
if f.serve {
panic("cannot use OIDCCallback with WithServing. This is only for the in memory usage")
}
f.stateToIDTokenClaims.Store(state, idTokenClaims)
cli := f.HTTPClient(nil)
u := f.cfg.AuthCodeURL(state)
req, err := http.NewRequest("GET", u, nil)
require.NoError(t, err)
resp, err := cli.Do(req.WithContext(context.Background()))
require.NoError(t, err)
t.Cleanup(func() {
if resp.Body != nil {
_ = resp.Body.Close()
}
})
return resp
}
// ProviderJSON is the .well-known/configuration JSON
type ProviderJSON struct {
Issuer string `json:"issuer"`
AuthURL string `json:"authorization_endpoint"`
TokenURL string `json:"token_endpoint"`
JWKSURL string `json:"jwks_uri"`
UserInfoURL string `json:"userinfo_endpoint"`
DeviceCodeURL string `json:"device_authorization_endpoint"`
Algorithms []string `json:"id_token_signing_alg_values_supported"`
// This is custom
ExternalAuthURL string `json:"external_auth_url"`
}
// newCode enforces the code exchanged is actually a valid code
// created by the IDP.
func (f *FakeIDP) newCode(state string) string {
code := uuid.NewString()
f.codeToStateMap.Store(code, state)
return code
}
// newToken enforces the access token exchanged is actually a valid access token
// created by the IDP.
func (f *FakeIDP) newToken(email string, expires time.Time) string {
accessToken := uuid.NewString()
f.accessTokens.Store(accessToken, token{
issued: time.Now(),
email: email,
exp: expires,
})
return accessToken
}
func (f *FakeIDP) newRefreshTokens(email string) string {
refreshToken := uuid.NewString()
f.refreshTokens.Store(refreshToken, email)
return refreshToken
}
// authenticateBearerTokenRequest enforces the access token is valid.
func (f *FakeIDP) authenticateBearerTokenRequest(t testing.TB, req *http.Request) (string, error) {
t.Helper()
auth := req.Header.Get("Authorization")
token := strings.TrimPrefix(auth, "Bearer ")
authToken, ok := f.accessTokens.Load(token)
if !ok {
return "", xerrors.New("invalid access token")
}
if !authToken.exp.IsZero() && authToken.exp.Before(time.Now()) {
return "", xerrors.New("access token expired")
}
return token, nil
}
// authenticateOIDCClientRequest enforces the client_id and client_secret are valid.
func (f *FakeIDP) authenticateOIDCClientRequest(t testing.TB, req *http.Request) (url.Values, error) {
t.Helper()
if f.hookAuthenticateClient != nil {
return f.hookAuthenticateClient(t, req)
}
data, err := io.ReadAll(req.Body)
if !assert.NoError(t, err, "read token request body") {
return nil, xerrors.Errorf("authenticate request, read body: %w", err)
}
values, err := url.ParseQuery(string(data))
if !assert.NoError(t, err, "parse token request values") {
return nil, xerrors.New("invalid token request")
}
if !assert.Equal(t, f.clientID, values.Get("client_id"), "client_id mismatch") {
return nil, xerrors.New("client_id mismatch")
}
if !assert.Equal(t, f.clientSecret, values.Get("client_secret"), "client_secret mismatch") {
return nil, xerrors.New("client_secret mismatch")
}
return values, nil
}
// encodeClaims is a helper func to convert claims to a valid JWT.
func (f *FakeIDP) encodeClaims(t testing.TB, claims jwt.MapClaims) string {
t.Helper()
if _, ok := claims["exp"]; !ok {
claims["exp"] = time.Now().Add(time.Hour).UnixMilli()
}
if _, ok := claims["aud"]; !ok {
claims["aud"] = f.clientID
}
if _, ok := claims["iss"]; !ok {
claims["iss"] = f.issuer
}
signed, err := jwt.NewWithClaims(jwt.SigningMethodRS256, claims).SignedString(f.key)
require.NoError(t, err)
return signed
}
// httpHandler is the IDP http server.
func (f *FakeIDP) httpHandler(t testing.TB) http.Handler {
t.Helper()
mux := chi.NewMux()
mux.Use(f.middlewares...)
// This endpoint is required to initialize the OIDC provider.
// It is used to get the OIDC configuration.
mux.Get("/.well-known/openid-configuration", func(rw http.ResponseWriter, r *http.Request) {
f.logger.Info(r.Context(), "http OIDC config", slog.F("url", r.URL.String()))
_ = json.NewEncoder(rw).Encode(f.provider)
})
// Authorize is called when the user is redirected to the IDP to login.
// This is the browser hitting the IDP and the user logging into Google or
// w/e and clicking "Allow". They will be redirected back to the redirect
// when this is done.
mux.Handle(authorizePath, http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
f.logger.Info(r.Context(), "http call authorize", slog.F("url", r.URL.String()))
clientID := r.URL.Query().Get("client_id")
if !assert.Equal(t, f.clientID, clientID, "unexpected client_id") {
http.Error(rw, "invalid client_id", http.StatusBadRequest)
return
}
redirectURI := r.URL.Query().Get("redirect_uri")
state := r.URL.Query().Get("state")
scope := r.URL.Query().Get("scope")
assert.NotEmpty(t, scope, "scope is empty")
responseType := r.URL.Query().Get("response_type")
switch responseType {
case "code":
case "token":
t.Errorf("response_type %q not supported", responseType)
http.Error(rw, "invalid response_type", http.StatusBadRequest)
return
default:
t.Errorf("unexpected response_type %q", responseType)
http.Error(rw, "invalid response_type", http.StatusBadRequest)
return
}
err := f.hookValidRedirectURL(redirectURI)
if err != nil {
t.Errorf("not authorized redirect_uri by custom hook %q: %s", redirectURI, err.Error())
http.Error(rw, fmt.Sprintf("invalid redirect_uri: %s", err.Error()), httpErrorCode(http.StatusBadRequest, err))
return
}
ru, err := url.Parse(redirectURI)
if err != nil {
t.Errorf("invalid redirect_uri %q: %s", redirectURI, err.Error())
http.Error(rw, fmt.Sprintf("invalid redirect_uri: %s", err.Error()), http.StatusBadRequest)
return
}
q := ru.Query()
q.Set("state", state)
q.Set("code", f.newCode(state))
ru.RawQuery = q.Encode()
http.Redirect(rw, r, ru.String(), http.StatusTemporaryRedirect)
}))
mux.Handle(tokenPath, http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
var values url.Values
var err error
if r.URL.Query().Get("grant_type") == "urn:ietf:params:oauth:grant-type:device_code" {
values = r.URL.Query()
} else {
values, err = f.authenticateOIDCClientRequest(t, r)
}
f.logger.Info(r.Context(), "http idp call token",
slog.F("url", r.URL.String()),
slog.F("valid", err == nil),
slog.F("grant_type", values.Get("grant_type")),
slog.F("values", values.Encode()),
)
if err != nil {
http.Error(rw, fmt.Sprintf("invalid token request: %s", err.Error()), httpErrorCode(http.StatusBadRequest, err))
return
}
getEmail := func(claims jwt.MapClaims) string {
email, ok := claims["email"]
if !ok {
return "unknown"
}
emailStr, ok := email.(string)
if !ok {
return "wrong-type"
}
return emailStr
}
var claims jwt.MapClaims
switch values.Get("grant_type") {
case "authorization_code":
code := values.Get("code")
if !assert.NotEmpty(t, code, "code is empty") {
http.Error(rw, "invalid code", http.StatusBadRequest)
return
}
stateStr, ok := f.codeToStateMap.Load(code)
if !assert.True(t, ok, "invalid code") {
http.Error(rw, "invalid code", http.StatusBadRequest)
return
}
// Always invalidate the code after it is used.
f.codeToStateMap.Delete(code)
idTokenClaims, ok := f.getClaims(f.stateToIDTokenClaims, stateStr)
if !ok {
t.Errorf("missing id token claims")
http.Error(rw, "missing id token claims", http.StatusBadRequest)
return
}
claims = idTokenClaims
case "refresh_token":
refreshToken := values.Get("refresh_token")
if !assert.NotEmpty(t, refreshToken, "refresh_token is empty") {
http.Error(rw, "invalid refresh_token", http.StatusBadRequest)
return
}
_, ok := f.refreshTokens.Load(refreshToken)
if !assert.True(t, ok, "invalid refresh_token") {
http.Error(rw, "invalid refresh_token", http.StatusBadRequest)
return
}
idTokenClaims, ok := f.getClaims(f.refreshIDTokenClaims, refreshToken)
if !ok {
t.Errorf("missing id token claims in refresh")
http.Error(rw, "missing id token claims in refresh", http.StatusBadRequest)
return
}
claims = idTokenClaims
err := f.hookOnRefresh(getEmail(claims))
if err != nil {
http.Error(rw, fmt.Sprintf("refresh hook blocked refresh: %s", err.Error()), httpErrorCode(http.StatusBadRequest, err))
return
}
f.refreshTokensUsed.Store(refreshToken, true)
// Always invalidate the refresh token after it is used.
f.refreshTokens.Delete(refreshToken)
case "urn:ietf:params:oauth:grant-type:device_code":
// Device flow
var resp externalauth.ExchangeDeviceCodeResponse
deviceCode := values.Get("device_code")
if deviceCode == "" {
resp.Error = "invalid_request"
resp.ErrorDescription = "missing device_code"
httpapi.Write(r.Context(), rw, http.StatusBadRequest, resp)
return
}
deviceFlow, ok := f.deviceCode.Load(deviceCode)
if !ok {
resp.Error = "invalid_request"
resp.ErrorDescription = "device_code provided not found"
httpapi.Write(r.Context(), rw, http.StatusBadRequest, resp)
return
}
if !deviceFlow.granted {
// Status code ok with the error as pending.
resp.Error = "authorization_pending"
resp.ErrorDescription = ""
httpapi.Write(r.Context(), rw, http.StatusOK, resp)
return
}
// Would be nice to get an actual email here.
claims = jwt.MapClaims{
"email": "unknown-dev-auth",
}
default:
t.Errorf("unexpected grant_type %q", values.Get("grant_type"))
http.Error(rw, "invalid grant_type", http.StatusBadRequest)
return
}
exp := time.Now().Add(f.defaultExpire)
claims["exp"] = exp.UnixMilli()
email := getEmail(claims)
refreshToken := f.newRefreshTokens(email)
token := map[string]interface{}{
"access_token": f.newToken(email, exp),
"refresh_token": refreshToken,
"token_type": "Bearer",
"expires_in": int64((f.defaultExpire).Seconds()),
"id_token": f.encodeClaims(t, claims),
}
if f.hookMutateToken != nil {
f.hookMutateToken(token)
}
// Store the claims for the next refresh
f.refreshIDTokenClaims.Store(refreshToken, claims)
mediaType, _, _ := mime.ParseMediaType(r.Header.Get("Accept"))
if mediaType == "application/x-www-form-urlencoded" {
// This val encode might not work for some data structures.
// It's good enough for now...
rw.Header().Set("Content-Type", "application/x-www-form-urlencoded")
vals := url.Values{}
for k, v := range token {
vals.Set(k, fmt.Sprintf("%v", v))
}
_, _ = rw.Write([]byte(vals.Encode()))
return
}
// Default to json since the oauth2 package doesn't use Accept headers.
if mediaType == "application/json" || mediaType == "" {
rw.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(rw).Encode(token)
return
}
// If we get something we don't support, throw an error.
httpapi.Write(r.Context(), rw, http.StatusBadRequest, codersdk.Response{
Message: "'Accept' header contains unsupported media type",
Detail: fmt.Sprintf("Found %q", mediaType),
})
}))
validateMW := func(rw http.ResponseWriter, r *http.Request) (email string, ok bool) {
token, err := f.authenticateBearerTokenRequest(t, r)
if err != nil {
http.Error(rw, fmt.Sprintf("invalid user info request: %s", err.Error()), http.StatusUnauthorized)
return "", false
}
authToken, ok := f.accessTokens.Load(token)
if !ok {
t.Errorf("access token user for user_info has no email to indicate which user")
http.Error(rw, "invalid access token, missing user info", http.StatusUnauthorized)
return "", false
}
if !authToken.exp.IsZero() && authToken.exp.Before(time.Now()) {
http.Error(rw, "auth token expired", http.StatusUnauthorized)
return "", false
}
return authToken.email, true
}
mux.Handle(userInfoPath, http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
email, ok := validateMW(rw, r)
f.logger.Info(r.Context(), "http userinfo endpoint",
slog.F("valid", ok),
slog.F("email", email),
)
if !ok {
return
}
claims, err := f.hookUserInfo(email)