-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathserver_test.go
1818 lines (1635 loc) · 54.2 KB
/
server_test.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 server
import (
"context"
"crypto/rsa"
"crypto/x509"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"net/http/httputil"
"net/url"
"path"
"reflect"
"sort"
"strings"
"testing"
"time"
gosundheit "github.com/AppsFlyer/go-sundheit"
"github.com/coreos/go-oidc/v3/oidc"
"github.com/go-jose/go-jose/v4"
"github.com/kylelemons/godebug/pretty"
"github.com/prometheus/client_golang/prometheus"
"github.com/stretchr/testify/require"
"golang.org/x/crypto/bcrypt"
"golang.org/x/oauth2"
"github.com/dexidp/dex/connector"
"github.com/dexidp/dex/connector/mock"
"github.com/dexidp/dex/storage"
"github.com/dexidp/dex/storage/memory"
)
func mustLoad(s string) *rsa.PrivateKey {
block, _ := pem.Decode([]byte(s))
if block == nil {
panic("no pem data found")
}
key, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
panic(err)
}
return key
}
var testKey = mustLoad(`-----BEGIN RSA PRIVATE KEY-----
MIIEogIBAAKCAQEArmoiX5G36MKPiVGS1sicruEaGRrbhPbIKOf97aGGQRjXVngo
Knwd2L4T9CRyABgQm3tLHHcT5crODoy46wX2g9onTZWViWWuhJ5wxXNmUbCAPWHb
j9SunW53WuLYZ/IJLNZt5XYCAFPjAakWp8uMuuDwWo5EyFaw85X3FSMhVmmaYDd0
cn+1H4+NS/52wX7tWmyvGUNJ8lzjFAnnOtBJByvkyIC7HDphkLQV4j//sMNY1mPX
HbsYgFv2J/LIJtkjdYO2UoDhZG3Gvj16fMy2JE2owA8IX4/s+XAmA2PiTfd0J5b4
drAKEcdDl83G6L3depEkTkfvp0ZLsh9xupAvIwIDAQABAoIBABKGgWonPyKA7+AF
AxS/MC0/CZebC6/+ylnV8lm4K1tkuRKdJp8EmeL4pYPsDxPFepYZLWwzlbB1rxdK
iSWld36fwEb0WXLDkxrQ/Wdrj3Wjyqs6ZqjLTVS5dAH6UEQSKDlT+U5DD4lbX6RA
goCGFUeQNtdXfyTMWHU2+4yKM7NKzUpczFky+0d10Mg0ANj3/4IILdr3hqkmMSI9
1TB9ksWBXJxt3nGxAjzSFihQFUlc231cey/HhYbvAX5fN0xhLxOk88adDcdXE7br
3Ser1q6XaaFQSMj4oi1+h3RAT9MUjJ6johEqjw0PbEZtOqXvA1x5vfFdei6SqgKn
Am3BspkCgYEA2lIiKEkT/Je6ZH4Omhv9atbGoBdETAstL3FnNQjkyVau9f6bxQkl
4/sz985JpaiasORQBiTGY8JDT/hXjROkut91agi2Vafhr29L/mto7KZglfDsT4b2
9z/EZH8wHw7eYhvdoBbMbqNDSI8RrGa4mpLpuN+E0wsFTzSZEL+QMQUCgYEAzIQh
xnreQvDAhNradMqLmxRpayn1ORaPReD4/off+mi7hZRLKtP0iNgEVEWHJ6HEqqi1
r38XAc8ap/lfOVMar2MLyCFOhYspdHZ+TGLZfr8gg/Fzeq9IRGKYadmIKVwjMeyH
REPqg1tyrvMOE0HI5oqkko8JTDJ0OyVC0Vc6+AcCgYAqCzkywugLc/jcU35iZVOH
WLdFq1Vmw5w/D7rNdtoAgCYPj6nV5y4Z2o2mgl6ifXbU7BMRK9Hc8lNeOjg6HfdS
WahV9DmRA1SuIWPkKjE5qczd81i+9AHpmakrpWbSBF4FTNKAewOBpwVVGuBPcDTK
59IE3V7J+cxa9YkotYuCNQKBgCwGla7AbHBEm2z+H+DcaUktD7R+B8gOTzFfyLoi
Tdj+CsAquDO0BQQgXG43uWySql+CifoJhc5h4v8d853HggsXa0XdxaWB256yk2Wm
MePTCRDePVm/ufLetqiyp1kf+IOaw1Oyux0j5oA62mDS3Iikd+EE4Z+BjPvefY/L
E2qpAoGAZo5Wwwk7q8b1n9n/ACh4LpE+QgbFdlJxlfFLJCKstl37atzS8UewOSZj
FDWV28nTP9sqbtsmU8Tem2jzMvZ7C/Q0AuDoKELFUpux8shm8wfIhyaPnXUGZoAZ
Np4vUwMSYV5mopESLWOg3loBxKyLGFtgGKVCjGiQvy6zISQ4fQo=
-----END RSA PRIVATE KEY-----`)
var logger = slog.New(slog.NewTextHandler(io.Discard, &slog.HandlerOptions{}))
func newTestServer(ctx context.Context, t *testing.T, updateConfig func(c *Config)) (*httptest.Server, *Server) {
var server *Server
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
server.ServeHTTP(w, r)
}))
config := Config{
Issuer: s.URL,
Storage: memory.New(logger),
Web: WebConfig{
Dir: "../web",
},
Logger: logger,
PrometheusRegistry: prometheus.NewRegistry(),
HealthChecker: gosundheit.New(),
SkipApprovalScreen: true, // Don't prompt for approval, just immediately redirect with code.
AllowedGrantTypes: []string{ // all implemented types
grantTypeDeviceCode,
grantTypeAuthorizationCode,
grantTypeRefreshToken,
grantTypeTokenExchange,
grantTypeImplicit,
grantTypePassword,
},
}
if updateConfig != nil {
updateConfig(&config)
}
s.URL = config.Issuer
connector := storage.Connector{
ID: "mock",
Type: "mockCallback",
Name: "Mock",
ResourceVersion: "1",
}
if err := config.Storage.CreateConnector(ctx, connector); err != nil {
t.Fatalf("create connector: %v", err)
}
var err error
if server, err = newServer(ctx, config, staticRotationStrategy(testKey)); err != nil {
t.Fatal(err)
}
// Default rotation policy
if server.refreshTokenPolicy == nil {
server.refreshTokenPolicy, err = NewRefreshTokenPolicy(logger, false, "", "", "")
if err != nil {
t.Fatalf("failed to prepare rotation policy: %v", err)
}
server.refreshTokenPolicy.now = config.Now
}
return s, server
}
func newTestServerMultipleConnectors(ctx context.Context, t *testing.T, updateConfig func(c *Config)) (*httptest.Server, *Server) {
var server *Server
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
server.ServeHTTP(w, r)
}))
config := Config{
Issuer: s.URL,
Storage: memory.New(logger),
Web: WebConfig{
Dir: "../web",
},
Logger: logger,
PrometheusRegistry: prometheus.NewRegistry(),
}
if updateConfig != nil {
updateConfig(&config)
}
s.URL = config.Issuer
connector := storage.Connector{
ID: "mock",
Type: "mockCallback",
Name: "Mock",
ResourceVersion: "1",
}
connector2 := storage.Connector{
ID: "mock2",
Type: "mockCallback",
Name: "Mock",
ResourceVersion: "1",
}
if err := config.Storage.CreateConnector(ctx, connector); err != nil {
t.Fatalf("create connector: %v", err)
}
if err := config.Storage.CreateConnector(ctx, connector2); err != nil {
t.Fatalf("create connector: %v", err)
}
var err error
if server, err = newServer(ctx, config, staticRotationStrategy(testKey)); err != nil {
t.Fatal(err)
}
server.skipApproval = true // Don't prompt for approval, just immediately redirect with code.
return s, server
}
func TestNewTestServer(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
newTestServer(ctx, t, nil)
}
func TestDiscovery(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
httpServer, _ := newTestServer(ctx, t, func(c *Config) {
c.Issuer += "/non-root-path"
})
defer httpServer.Close()
p, err := oidc.NewProvider(ctx, httpServer.URL)
if err != nil {
t.Fatalf("failed to get provider: %v", err)
}
var got map[string]*json.RawMessage
if err := p.Claims(&got); err != nil {
t.Fatalf("failed to decode claims: %v", err)
}
required := []string{
"issuer",
"authorization_endpoint",
"token_endpoint",
"jwks_uri",
"userinfo_endpoint",
}
for _, field := range required {
if _, ok := got[field]; !ok {
t.Errorf("server discovery is missing required field %q", field)
}
}
}
type oauth2Tests struct {
clientID string
tests []test
}
type test struct {
name string
// If specified these set of scopes will be used during the test case.
scopes []string
// handleToken provides the OAuth2 token response for the integration test.
handleToken func(context.Context, *oidc.Provider, *oauth2.Config, *oauth2.Token, *mock.Callback) error
// extra parameters to pass when requesting auth_code
authCodeOptions []oauth2.AuthCodeOption
// extra parameters to pass when retrieving id token
retrieveTokenOptions []oauth2.AuthCodeOption
// define an error response, when the test expects an error on the auth endpoint
authError *OAuth2ErrorResponse
// define an error response, when the test expects an error on the token endpoint
tokenError ErrorResponse
}
// Defines an expected error by HTTP Status Code and
// the OAuth2 error int the response json
type ErrorResponse struct {
Error string
StatusCode int
}
// https://tools.ietf.org/html/rfc6749#section-5.2
type OAuth2ErrorResponse struct {
Error string `json:"error"`
ErrorDescription string `json:"error_description"`
ErrorURI string `json:"error_uri"`
}
func makeOAuth2Tests(clientID string, clientSecret string, now func() time.Time) oauth2Tests {
requestedScopes := []string{oidc.ScopeOpenID, "email", "profile", "groups", "offline_access"}
// Used later when configuring test servers to set how long id_tokens will be valid for.
//
// The actual value of 30s is completely arbitrary. We just need to set a value
// so tests can compute the expected "expires_in" field.
idTokensValidFor := time.Second * 30
oidcConfig := &oidc.Config{SkipClientIDCheck: true}
basicIDTokenVerify := func(ctx context.Context, p *oidc.Provider, config *oauth2.Config, token *oauth2.Token, conn *mock.Callback) error {
idToken, ok := token.Extra("id_token").(string)
if !ok {
return fmt.Errorf("no id token found")
}
if _, err := p.Verifier(oidcConfig).Verify(ctx, idToken); err != nil {
return fmt.Errorf("failed to verify id token: %v", err)
}
return nil
}
return oauth2Tests{
clientID: clientID,
tests: []test{
{
name: "verify ID Token",
handleToken: func(ctx context.Context, p *oidc.Provider, config *oauth2.Config, token *oauth2.Token, conn *mock.Callback) error {
idToken, ok := token.Extra("id_token").(string)
if !ok {
return fmt.Errorf("no id token found")
}
if _, err := p.Verifier(oidcConfig).Verify(ctx, idToken); err != nil {
return fmt.Errorf("failed to verify id token: %v", err)
}
return nil
},
},
{
name: "fetch userinfo",
handleToken: func(ctx context.Context, p *oidc.Provider, config *oauth2.Config, token *oauth2.Token, conn *mock.Callback) error {
ui, err := p.UserInfo(ctx, config.TokenSource(ctx, token))
if err != nil {
return fmt.Errorf("failed to fetch userinfo: %v", err)
}
if conn.Identity.Email != ui.Email {
return fmt.Errorf("expected email to be %v, got %v", conn.Identity.Email, ui.Email)
}
return nil
},
},
{
name: "verify id token and oauth2 token expiry",
handleToken: func(ctx context.Context, p *oidc.Provider, config *oauth2.Config, token *oauth2.Token, conn *mock.Callback) error {
expectedExpiry := now().Add(idTokensValidFor)
timeEq := func(t1, t2 time.Time, within time.Duration) bool {
return t1.Sub(t2) < within
}
// TODO: This is a flaky test. We need something better (eg. clockwork).
if !timeEq(token.Expiry, expectedExpiry, 2*time.Second) {
return fmt.Errorf("expected expired_in to be %s, got %s", expectedExpiry, token.Expiry)
}
rawIDToken, ok := token.Extra("id_token").(string)
if !ok {
return fmt.Errorf("no id token found")
}
idToken, err := p.Verifier(oidcConfig).Verify(ctx, rawIDToken)
if err != nil {
return fmt.Errorf("failed to verify id token: %v", err)
}
if !timeEq(idToken.Expiry, expectedExpiry, time.Second) {
return fmt.Errorf("expected id token expiry to be %s, got %s", expectedExpiry, token.Expiry)
}
return nil
},
},
{
name: "verify at_hash",
handleToken: func(ctx context.Context, p *oidc.Provider, config *oauth2.Config, token *oauth2.Token, conn *mock.Callback) error {
rawIDToken, ok := token.Extra("id_token").(string)
if !ok {
return fmt.Errorf("no id token found")
}
idToken, err := p.Verifier(oidcConfig).Verify(ctx, rawIDToken)
if err != nil {
return fmt.Errorf("failed to verify id token: %v", err)
}
var claims struct {
AtHash string `json:"at_hash"`
}
if err := idToken.Claims(&claims); err != nil {
return fmt.Errorf("failed to decode raw claims: %v", err)
}
if claims.AtHash == "" {
return errors.New("no at_hash value in id_token")
}
wantAtHash, err := accessTokenHash(jose.RS256, token.AccessToken)
if err != nil {
return fmt.Errorf("computed expected at hash: %v", err)
}
if wantAtHash != claims.AtHash {
return fmt.Errorf("expected at_hash=%q got=%q", wantAtHash, claims.AtHash)
}
return nil
},
},
{
name: "refresh token",
handleToken: func(ctx context.Context, p *oidc.Provider, config *oauth2.Config, token *oauth2.Token, conn *mock.Callback) error {
// have to use time.Now because the OAuth2 package uses it.
token.Expiry = time.Now().Add(time.Second * -10)
if token.Valid() {
return errors.New("token shouldn't be valid")
}
newToken, err := config.TokenSource(ctx, token).Token()
if err != nil {
return fmt.Errorf("failed to refresh token: %v", err)
}
if token.RefreshToken == newToken.RefreshToken {
return fmt.Errorf("old refresh token was the same as the new token %q", token.RefreshToken)
}
if _, err := config.TokenSource(ctx, token).Token(); err == nil {
return errors.New("was able to redeem the same refresh token twice")
}
return nil
},
},
{
name: "refresh with explicit scopes",
handleToken: func(ctx context.Context, p *oidc.Provider, config *oauth2.Config, token *oauth2.Token, conn *mock.Callback) error {
v := url.Values{}
v.Add("client_id", clientID)
v.Add("client_secret", clientSecret)
v.Add("grant_type", "refresh_token")
v.Add("refresh_token", token.RefreshToken)
v.Add("scope", strings.Join(requestedScopes, " "))
resp, err := http.PostForm(p.Endpoint().TokenURL, v)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
dump, err := httputil.DumpResponse(resp, true)
if err != nil {
panic(err)
}
return fmt.Errorf("unexpected response: %s", dump)
}
if resp.Header.Get("Cache-Control") != "no-store" {
return fmt.Errorf("cache-control header doesn't included in token response")
}
if resp.Header.Get("Pragma") != "no-cache" {
return fmt.Errorf("pragma header doesn't included in token response")
}
return nil
},
},
{
name: "refresh with extra spaces",
handleToken: func(ctx context.Context, p *oidc.Provider, config *oauth2.Config, token *oauth2.Token, conn *mock.Callback) error {
v := url.Values{}
v.Add("client_id", clientID)
v.Add("client_secret", clientSecret)
v.Add("grant_type", "refresh_token")
v.Add("refresh_token", token.RefreshToken)
// go-oidc adds an additional space before scopes when refreshing.
// Since we support that client we choose to be more relaxed about
// scope parsing, disregarding extra whitespace.
v.Add("scope", " "+strings.Join(requestedScopes, " "))
resp, err := http.PostForm(p.Endpoint().TokenURL, v)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
dump, err := httputil.DumpResponse(resp, true)
if err != nil {
panic(err)
}
return fmt.Errorf("unexpected response: %s", dump)
}
if resp.Header.Get("Cache-Control") != "no-store" {
return fmt.Errorf("cache-control header doesn't included in token response")
}
if resp.Header.Get("Pragma") != "no-cache" {
return fmt.Errorf("pragma header doesn't included in token response")
}
return nil
},
},
{
name: "refresh with unauthorized scopes",
scopes: []string{"openid", "email"},
handleToken: func(ctx context.Context, p *oidc.Provider, config *oauth2.Config, token *oauth2.Token, conn *mock.Callback) error {
v := url.Values{}
v.Add("client_id", clientID)
v.Add("client_secret", clientSecret)
v.Add("grant_type", "refresh_token")
v.Add("refresh_token", token.RefreshToken)
// Request a scope that wasn't requested initially.
v.Add("scope", "oidc email profile")
resp, err := http.PostForm(p.Endpoint().TokenURL, v)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusOK {
dump, err := httputil.DumpResponse(resp, true)
if err != nil {
panic(err)
}
return fmt.Errorf("unexpected response: %s", dump)
}
return nil
},
},
{
name: "refresh with different client id",
scopes: []string{"openid", "email"},
handleToken: func(ctx context.Context, p *oidc.Provider, config *oauth2.Config, token *oauth2.Token, conn *mock.Callback) error {
v := url.Values{}
v.Add("client_id", clientID)
v.Add("client_secret", clientSecret)
v.Add("grant_type", "refresh_token")
v.Add("refresh_token", "existedrefrestoken")
v.Add("scope", "oidc email")
resp, err := http.PostForm(p.Endpoint().TokenURL, v)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusBadRequest {
return fmt.Errorf("expected status code %d, got %d", http.StatusBadRequest, resp.StatusCode)
}
var respErr struct {
Error string `json:"error"`
Description string `json:"error_description"`
}
if err = json.NewDecoder(resp.Body).Decode(&respErr); err != nil {
return fmt.Errorf("cannot decode token response: %v", err)
}
if respErr.Error != errInvalidGrant {
return fmt.Errorf("expected error %q, got %q", errInvalidGrant, respErr.Error)
}
expectedMsg := "Refresh token is invalid or has already been claimed by another client."
if respErr.Description != expectedMsg {
return fmt.Errorf("expected error description %q, got %q", expectedMsg, respErr.Description)
}
return nil
},
},
{
// This test ensures that the connector.RefreshConnector interface is being
// used when clients request a refresh token.
name: "refresh with identity changes",
handleToken: func(ctx context.Context, p *oidc.Provider, config *oauth2.Config, token *oauth2.Token, conn *mock.Callback) error {
// have to use time.Now because the OAuth2 package uses it.
token.Expiry = time.Now().Add(time.Second * -10)
if token.Valid() {
return errors.New("token shouldn't be valid")
}
ident := connector.Identity{
UserID: "fooid",
Username: "foo",
Email: "[email protected]",
EmailVerified: true,
Groups: []string{"foo", "bar"},
}
conn.Identity = ident
type claims struct {
Username string `json:"name"`
Email string `json:"email"`
EmailVerified bool `json:"email_verified"`
Groups []string `json:"groups"`
}
want := claims{ident.Username, ident.Email, ident.EmailVerified, ident.Groups}
newToken, err := config.TokenSource(ctx, token).Token()
if err != nil {
return fmt.Errorf("failed to refresh token: %v", err)
}
rawIDToken, ok := newToken.Extra("id_token").(string)
if !ok {
return fmt.Errorf("no id_token in refreshed token")
}
idToken, err := p.Verifier(oidcConfig).Verify(ctx, rawIDToken)
if err != nil {
return fmt.Errorf("failed to verify id token: %v", err)
}
var got claims
if err := idToken.Claims(&got); err != nil {
return fmt.Errorf("failed to unmarshal claims: %v", err)
}
if diff := pretty.Compare(want, got); diff != "" {
return fmt.Errorf("got identity != want identity: %s", diff)
}
return nil
},
},
{
name: "unsupported grant type",
retrieveTokenOptions: []oauth2.AuthCodeOption{
oauth2.SetAuthURLParam("grant_type", "unsupported"),
},
handleToken: basicIDTokenVerify,
tokenError: ErrorResponse{
Error: errUnsupportedGrantType,
StatusCode: http.StatusBadRequest,
},
},
{
// This test ensures that PKCE work in "plain" mode (no code_challenge_method specified)
name: "PKCE with plain",
authCodeOptions: []oauth2.AuthCodeOption{
oauth2.SetAuthURLParam("code_challenge", "challenge123"),
},
retrieveTokenOptions: []oauth2.AuthCodeOption{
oauth2.SetAuthURLParam("code_verifier", "challenge123"),
},
handleToken: basicIDTokenVerify,
},
{
// This test ensures that PKCE works in "S256" mode
name: "PKCE with S256",
authCodeOptions: []oauth2.AuthCodeOption{
oauth2.SetAuthURLParam("code_challenge", "lyyl-X4a69qrqgEfUL8wodWic3Be9ZZ5eovBgIKKi-w"),
oauth2.SetAuthURLParam("code_challenge_method", "S256"),
},
retrieveTokenOptions: []oauth2.AuthCodeOption{
oauth2.SetAuthURLParam("code_verifier", "challenge123"),
},
handleToken: basicIDTokenVerify,
},
{
// This test ensures that PKCE does fail with wrong code_verifier in "plain" mode
name: "PKCE with plain and wrong code_verifier",
authCodeOptions: []oauth2.AuthCodeOption{
oauth2.SetAuthURLParam("code_challenge", "challenge123"),
},
retrieveTokenOptions: []oauth2.AuthCodeOption{
oauth2.SetAuthURLParam("code_verifier", "challenge124"),
},
handleToken: basicIDTokenVerify,
tokenError: ErrorResponse{
Error: errInvalidGrant,
StatusCode: http.StatusBadRequest,
},
},
{
// This test ensures that PKCE fail with wrong code_verifier in "S256" mode
name: "PKCE with S256 and wrong code_verifier",
authCodeOptions: []oauth2.AuthCodeOption{
oauth2.SetAuthURLParam("code_challenge", "lyyl-X4a69qrqgEfUL8wodWic3Be9ZZ5eovBgIKKi-w"),
oauth2.SetAuthURLParam("code_challenge_method", "S256"),
},
retrieveTokenOptions: []oauth2.AuthCodeOption{
oauth2.SetAuthURLParam("code_verifier", "challenge124"),
},
handleToken: basicIDTokenVerify,
tokenError: ErrorResponse{
Error: errInvalidGrant,
StatusCode: http.StatusBadRequest,
},
},
{
// Ensure that, when PKCE flow started on /auth
// we stay in PKCE flow on /token
name: "PKCE flow expected on /token",
authCodeOptions: []oauth2.AuthCodeOption{
oauth2.SetAuthURLParam("code_challenge", "lyyl-X4a69qrqgEfUL8wodWic3Be9ZZ5eovBgIKKi-w"),
oauth2.SetAuthURLParam("code_challenge_method", "S256"),
},
retrieveTokenOptions: []oauth2.AuthCodeOption{
// No PKCE call on /token
},
handleToken: basicIDTokenVerify,
tokenError: ErrorResponse{
Error: errInvalidGrant,
StatusCode: http.StatusBadRequest,
},
},
{
// Ensure that when no PKCE flow was started on /auth
// we cannot switch to PKCE on /token
name: "No PKCE flow started on /auth",
authCodeOptions: []oauth2.AuthCodeOption{
// No PKCE call on /auth
},
retrieveTokenOptions: []oauth2.AuthCodeOption{
oauth2.SetAuthURLParam("code_verifier", "challenge123"),
},
handleToken: basicIDTokenVerify,
tokenError: ErrorResponse{
Error: errInvalidRequest,
StatusCode: http.StatusBadRequest,
},
},
{
// Make sure that, when we start with "S256" on /auth, we cannot downgrade to "plain" on /token
name: "PKCE with S256 and try to downgrade to plain",
authCodeOptions: []oauth2.AuthCodeOption{
oauth2.SetAuthURLParam("code_challenge", "lyyl-X4a69qrqgEfUL8wodWic3Be9ZZ5eovBgIKKi-w"),
oauth2.SetAuthURLParam("code_challenge_method", "S256"),
},
retrieveTokenOptions: []oauth2.AuthCodeOption{
oauth2.SetAuthURLParam("code_verifier", "lyyl-X4a69qrqgEfUL8wodWic3Be9ZZ5eovBgIKKi-w"),
oauth2.SetAuthURLParam("code_challenge_method", "plain"),
},
handleToken: basicIDTokenVerify,
tokenError: ErrorResponse{
Error: errInvalidGrant,
StatusCode: http.StatusBadRequest,
},
},
{
name: "Request parameter in authorization query",
authCodeOptions: []oauth2.AuthCodeOption{
oauth2.SetAuthURLParam("request", "anything"),
},
authError: &OAuth2ErrorResponse{
Error: errRequestNotSupported,
ErrorDescription: "Server does not support request parameter.",
},
handleToken: func(ctx context.Context, p *oidc.Provider, config *oauth2.Config, token *oauth2.Token, conn *mock.Callback) error {
return nil
},
},
},
}
}
// TestOAuth2CodeFlow runs integration tests against a test server. The tests stand up a server
// which requires no interaction to login, logs in through a test client, then passes the client
// and returned token to the test.
func TestOAuth2CodeFlow(t *testing.T) {
clientID := "testclient"
clientSecret := "testclientsecret"
requestedScopes := []string{oidc.ScopeOpenID, "email", "profile", "groups", "offline_access"}
t0 := time.Now()
// Always have the time function used by the server return the same time so
// we can predict expected values of "expires_in" fields exactly.
now := func() time.Time { return t0 }
// Used later when configuring test servers to set how long id_tokens will be valid for.
//
// The actual value of 30s is completely arbitrary. We just need to set a value
// so tests can compute the expected "expires_in" field.
idTokensValidFor := time.Second * 30
// Connector used by the tests.
var conn *mock.Callback
tests := makeOAuth2Tests(clientID, clientSecret, now)
for _, tc := range tests.tests {
t.Run(tc.name, func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Setup a dex server.
httpServer, s := newTestServer(ctx, t, func(c *Config) {
c.Issuer += "/non-root-path"
c.Now = now
c.IDTokensValidFor = idTokensValidFor
})
defer httpServer.Close()
mockConn := s.connectors["mock"]
conn = mockConn.Connector.(*mock.Callback)
// Query server's provider metadata.
p, err := oidc.NewProvider(ctx, httpServer.URL)
if err != nil {
t.Fatalf("failed to get provider: %v", err)
}
var (
// If the OAuth2 client didn't get a response, we need
// to print the requests the user saw.
gotCode bool
reqDump, respDump []byte // Auth step, not token.
state = "a_state"
)
defer func() {
if !gotCode && tc.authError == nil {
t.Errorf("never got a code in callback\n%s\n%s", reqDump, respDump)
}
}()
// Setup OAuth2 client.
var oauth2Config *oauth2.Config
oauth2Client := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/callback" {
// User is visiting app first time. Redirect to dex.
http.Redirect(w, r, oauth2Config.AuthCodeURL(state, tc.authCodeOptions...), http.StatusSeeOther)
return
}
// User is at '/callback' so they were just redirected _from_ dex.
q := r.URL.Query()
// Did dex return an error?
if errType := q.Get("error"); errType != "" {
description := q.Get("error_description")
if tc.authError == nil {
if description != "" {
t.Errorf("got error from server %s: %s", errType, description)
} else {
t.Errorf("got error from server %s", errType)
}
w.WriteHeader(http.StatusInternalServerError)
return
}
require.Equal(t, *tc.authError, OAuth2ErrorResponse{Error: errType, ErrorDescription: description})
return
}
// Grab code, exchange for token.
if code := q.Get("code"); code != "" {
gotCode = true
token, err := oauth2Config.Exchange(ctx, code, tc.retrieveTokenOptions...)
if tc.tokenError.StatusCode != 0 {
checkErrorResponse(err, t, tc)
return
}
if err != nil {
t.Errorf("failed to exchange code for token: %v", err)
return
}
err = tc.handleToken(ctx, p, oauth2Config, token, conn)
if err != nil {
t.Errorf("%s: %v", tc.name, err)
}
return
}
// Ensure state matches.
if gotState := q.Get("state"); gotState != state {
t.Errorf("state did not match, want=%q got=%q", state, gotState)
}
w.WriteHeader(http.StatusOK)
}))
defer oauth2Client.Close()
// Register the client above with dex.
redirectURL := oauth2Client.URL + "/callback"
client := storage.Client{
ID: clientID,
Secret: clientSecret,
RedirectURIs: []string{redirectURL},
}
if err := s.storage.CreateClient(ctx, client); err != nil {
t.Fatalf("failed to create client: %v", err)
}
if err := s.storage.CreateRefresh(ctx, storage.RefreshToken{
ID: "existedrefrestoken",
ClientID: "unexcistedclientid",
}); err != nil {
t.Fatalf("failed to create existed refresh token: %v", err)
}
// Create the OAuth2 config.
oauth2Config = &oauth2.Config{
ClientID: client.ID,
ClientSecret: client.Secret,
Endpoint: p.Endpoint(),
Scopes: requestedScopes,
RedirectURL: redirectURL,
}
if len(tc.scopes) != 0 {
oauth2Config.Scopes = tc.scopes
}
// Login!
//
// 1. First request to client, redirects to dex.
// 2. Dex "logs in" the user, redirects to client with "code".
// 3. Client exchanges "code" for "token" (id_token, refresh_token, etc.).
// 4. Test is run with OAuth2 token response.
//
resp, err := http.Get(oauth2Client.URL + "/login")
if err != nil {
t.Fatalf("get failed: %v", err)
}
defer resp.Body.Close()
if reqDump, err = httputil.DumpRequest(resp.Request, false); err != nil {
t.Fatal(err)
}
if respDump, err = httputil.DumpResponse(resp, true); err != nil {
t.Fatal(err)
}
tokens, err := s.storage.ListRefreshTokens(ctx)
if err != nil {
t.Fatalf("failed to get existed refresh token: %v", err)
}
for _, token := range tokens {
if /* token was updated */ token.ObsoleteToken != "" && token.ConnectorData != nil {
t.Fatalf("token connectorData with id %q field is not nil: %s", token.ID, token.ConnectorData)
}
}
})
}
}
func TestOAuth2ImplicitFlow(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
httpServer, s := newTestServer(ctx, t, func(c *Config) {
// Enable support for the implicit flow.
c.SupportedResponseTypes = []string{"code", "token", "id_token"}
})
defer httpServer.Close()
p, err := oidc.NewProvider(ctx, httpServer.URL)
if err != nil {
t.Fatalf("failed to get provider: %v", err)
}
var (
reqDump, respDump []byte
gotIDToken bool
state = "a_state"
nonce = "a_nonce"
)
defer func() {
if !gotIDToken {
t.Errorf("never got a id token in fragment\n%s\n%s", reqDump, respDump)
}
}()
var oauth2Config *oauth2.Config
oauth2Server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/callback" {
q := r.URL.Query()
if errType := q.Get("error"); errType != "" {
if desc := q.Get("error_description"); desc != "" {
t.Errorf("got error from server %s: %s", errType, desc)
} else {
t.Errorf("got error from server %s", errType)
}
w.WriteHeader(http.StatusInternalServerError)
return
}
// Fragment is checked by the client since net/http servers don't preserve URL fragments.
// E.g.
//
// r.URL.Fragment
//
// Will always be empty.
w.WriteHeader(http.StatusOK)
return
}
u := oauth2Config.AuthCodeURL(state, oauth2.SetAuthURLParam("response_type", "id_token token"), oidc.Nonce(nonce))
http.Redirect(w, r, u, http.StatusSeeOther)
}))
defer oauth2Server.Close()
redirectURL := oauth2Server.URL + "/callback"
client := storage.Client{
ID: "testclient",
Secret: "testclientsecret",
RedirectURIs: []string{redirectURL},
}
if err := s.storage.CreateClient(ctx, client); err != nil {
t.Fatalf("failed to create client: %v", err)
}
idTokenVerifier := p.Verifier(&oidc.Config{
ClientID: client.ID,
})
oauth2Config = &oauth2.Config{
ClientID: client.ID,
ClientSecret: client.Secret,
Endpoint: p.Endpoint(),
Scopes: []string{oidc.ScopeOpenID, "profile", "email", "offline_access"},
RedirectURL: redirectURL,
}
checkIDToken := func(u *url.URL) error {
if u.Fragment == "" {
return fmt.Errorf("url has no fragment: %s", u)
}
v, err := url.ParseQuery(u.Fragment)
if err != nil {
return fmt.Errorf("failed to parse fragment: %v", err)
}
rawIDToken := v.Get("id_token")
if rawIDToken == "" {
return errors.New("no id_token in fragment")
}
idToken, err := idTokenVerifier.Verify(ctx, rawIDToken)
if err != nil {
return fmt.Errorf("failed to verify id_token: %v", err)
}
if idToken.Nonce != nonce {
return fmt.Errorf("failed to verify id_token: nonce was %v, but want %v", idToken.Nonce, nonce)
}
return nil
}
httpClient := &http.Client{
// net/http servers don't preserve URL fragments when passing the request to
// handlers. The only way to get at that values is to check the redirect on
// the client side.
CheckRedirect: func(req *http.Request, via []*http.Request) error {
if len(via) > 10 {
return errors.New("too many redirects")
}
// If we're being redirected back to the client server, inspect the URL fragment