-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathstrategy_oauth_test.go
More file actions
1139 lines (989 loc) · 47.6 KB
/
strategy_oauth_test.go
File metadata and controls
1139 lines (989 loc) · 47.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright © 2022 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package consent_test
import (
"bytes"
"context"
"crypto/sha256"
"encoding/json"
"fmt"
"net/http"
"net/http/cookiejar"
"net/url"
"regexp"
"testing"
"time"
"golang.org/x/exp/slices"
"golang.org/x/oauth2"
"github.com/ory/x/pointerx"
"github.com/tidwall/gjson"
"github.com/pborman/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/ory/hydra/v2/internal/testhelpers"
"github.com/ory/x/contextx"
"github.com/ory/fosite"
"github.com/ory/x/urlx"
"github.com/ory/x/uuidx"
hydra "github.com/ory/hydra-client-go/v2"
"github.com/ory/hydra/v2/client"
"github.com/ory/hydra/v2/driver/config"
)
func TestStrategyLoginConsentNext(t *testing.T) {
ctx := context.Background()
reg := testhelpers.NewMockedRegistry(t, &contextx.Default{})
reg.Config().MustSet(ctx, config.KeyAccessTokenStrategy, "opaque")
reg.Config().MustSet(ctx, config.KeyConsentRequestMaxAge, time.Hour)
reg.Config().MustSet(ctx, config.KeyConsentRequestMaxAge, time.Hour)
reg.Config().MustSet(ctx, config.KeyScopeStrategy, "exact")
reg.Config().MustSet(ctx, config.KeySubjectTypesSupported, []string{"pairwise", "public"})
reg.Config().MustSet(ctx, config.KeySubjectIdentifierAlgorithmSalt, "76d5d2bf-747f-4592-9fbd-d2b895a54b3a")
publicTS, adminTS := testhelpers.NewOAuth2Server(ctx, t, reg)
adminClient := hydra.NewAPIClient(hydra.NewConfiguration())
adminClient.GetConfig().Servers = hydra.ServerConfigurations{{URL: adminTS.URL}}
oauth2Config := func(t *testing.T, c *client.Client) *oauth2.Config {
return &oauth2.Config{
ClientID: c.GetID(),
ClientSecret: c.Secret,
Endpoint: oauth2.Endpoint{
AuthURL: publicTS.URL + "/oauth2/auth",
TokenURL: publicTS.URL + "/oauth2/token",
AuthStyle: oauth2.AuthStyleInHeader,
},
RedirectURL: c.RedirectURIs[0],
}
}
acceptLoginHandler := func(t *testing.T, subject string, payload *hydra.AcceptOAuth2LoginRequest) http.HandlerFunc {
return checkAndAcceptLoginHandler(t, adminClient, subject, func(*testing.T, *hydra.OAuth2LoginRequest, error) hydra.AcceptOAuth2LoginRequest {
if payload == nil {
return hydra.AcceptOAuth2LoginRequest{}
}
return *payload
})
}
acceptConsentHandler := func(t *testing.T, payload *hydra.AcceptOAuth2ConsentRequest) http.HandlerFunc {
return checkAndAcceptConsentHandler(t, adminClient, func(*testing.T, *hydra.OAuth2ConsentRequest, error) hydra.AcceptOAuth2ConsentRequest {
if payload == nil {
return hydra.AcceptOAuth2ConsentRequest{}
}
return *payload
})
}
createClientWithRedir := func(t *testing.T, redir string) *client.Client {
c := &client.Client{RedirectURIs: []string{redir}}
return createClient(t, reg, c)
}
createDefaultClient := func(t *testing.T) *client.Client {
return createClientWithRedir(t, testhelpers.NewCallbackURL(t, "callback", testhelpers.HTTPServerNotImplementedHandler))
}
makeRequestAndExpectCode := func(t *testing.T, hc *http.Client, c *client.Client, values url.Values) string {
_, res := makeOAuth2Request(t, reg, hc, c, values)
assert.EqualValues(t, http.StatusNotImplemented, res.StatusCode)
code := res.Request.URL.Query().Get("code")
assert.NotEmpty(t, code)
return code
}
makeRequestAndExpectError := func(t *testing.T, hc *http.Client, c *client.Client, values url.Values, errContains string) {
_, res := makeOAuth2Request(t, reg, hc, c, values)
assert.EqualValues(t, http.StatusNotImplemented, res.StatusCode)
assert.Empty(t, res.Request.URL.Query().Get("code"))
assert.Contains(t, res.Request.URL.Query().Get("error_description"), errContains, "%v", res.Request.URL.Query())
}
t.Run("case=should fail because a login verifier was given that doesn't exist in the store", func(t *testing.T) {
testhelpers.NewLoginConsentUI(t, reg.Config(), testhelpers.HTTPServerNoExpectedCallHandler(t), testhelpers.HTTPServerNoExpectedCallHandler(t))
c := createDefaultClient(t)
hc := testhelpers.NewEmptyJarClient(t)
makeRequestAndExpectError(
t, hc, c, url.Values{"login_verifier": {"does-not-exist"}},
"The resource owner or authorization server denied the request. The login verifier is invalid",
)
})
t.Run("case=should fail because a non-existing consent verifier was given", func(t *testing.T) {
// Covers:
// - This should fail because consent verifier was set but does not exist
// - This should fail because a consent verifier was given but no login verifier
testhelpers.NewLoginConsentUI(t, reg.Config(), testhelpers.HTTPServerNoExpectedCallHandler(t), testhelpers.HTTPServerNoExpectedCallHandler(t))
c := createDefaultClient(t)
hc := testhelpers.NewEmptyJarClient(t)
makeRequestAndExpectError(
t, hc, c, url.Values{"consent_verifier": {"does-not-exist"}},
"The consent verifier has already been used, has not been granted, or is invalid.",
)
})
t.Run("case=should fail because the request was redirected but the login endpoint doesn't do anything (like redirecting back)", func(t *testing.T) {
testhelpers.NewLoginConsentUI(t, reg.Config(), testhelpers.HTTPServerNotImplementedHandler, testhelpers.HTTPServerNoExpectedCallHandler(t))
c := createClientWithRedir(t, testhelpers.NewCallbackURL(t, "callback", testhelpers.HTTPServerNoExpectedCallHandler(t)))
_, res := makeOAuth2Request(t, reg, nil, c, url.Values{})
assert.EqualValues(t, http.StatusNotImplemented, res.StatusCode)
assert.NotEmpty(t, res.Request.URL.Query().Get("login_challenge"), "%s", res.Request.URL)
})
t.Run("case=should fail because the request was redirected but consent endpoint doesn't do anything (like redirecting back)", func(t *testing.T) {
// "This should fail because consent endpoints idles after login was granted - but consent endpoint should be called because cookie jar exists"
testhelpers.NewLoginConsentUI(t, reg.Config(), acceptLoginHandler(t, "aeneas-rekkas", nil), testhelpers.HTTPServerNotImplementedHandler)
c := createClientWithRedir(t, testhelpers.NewCallbackURL(t, "callback", testhelpers.HTTPServerNoExpectedCallHandler(t)))
_, res := makeOAuth2Request(t, reg, nil, c, url.Values{})
assert.EqualValues(t, http.StatusNotImplemented, res.StatusCode)
assert.NotEmpty(t, res.Request.URL.Query().Get("consent_challenge"), "%s", res.Request.URL)
})
t.Run("case=should fail because the request was redirected but the login endpoint rejected the request", func(t *testing.T) {
testhelpers.NewLoginConsentUI(t, reg.Config(), func(w http.ResponseWriter, r *http.Request) {
vr, _, err := adminClient.OAuth2API.RejectOAuth2LoginRequest(context.Background()).
LoginChallenge(r.URL.Query().Get("login_challenge")).
RejectOAuth2Request(hydra.RejectOAuth2Request{
Error: pointerx.String(fosite.ErrInteractionRequired.ErrorField),
ErrorDescription: pointerx.String("expect-reject-login"),
StatusCode: pointerx.Int64(int64(fosite.ErrInteractionRequired.CodeField)),
}).Execute()
require.NoError(t, err)
assert.NotEmpty(t, vr.RedirectTo)
http.Redirect(w, r, vr.RedirectTo, http.StatusFound)
}, testhelpers.HTTPServerNoExpectedCallHandler(t))
c := createDefaultClient(t)
makeRequestAndExpectError(t, nil, c, url.Values{}, "expect-reject-login")
})
t.Run("case=should fail because no cookie jar invalid csrf", func(t *testing.T) {
c := createDefaultClient(t)
testhelpers.NewLoginConsentUI(t, reg.Config(), acceptLoginHandler(t, "aeneas-rekkas", nil),
testhelpers.HTTPServerNoExpectedCallHandler(t))
hc := new(http.Client)
hc.Jar = DropCookieJar(regexp.MustCompile("ory_hydra_.*_csrf_.*"))
makeRequestAndExpectError(t, hc, c, url.Values{}, "No CSRF value available in the session cookie.")
})
t.Run("case=should fail because consent endpoints denies the request after login was granted", func(t *testing.T) {
c := createDefaultClient(t)
testhelpers.NewLoginConsentUI(t, reg.Config(),
acceptLoginHandler(t, "aeneas-rekkas", nil),
func(w http.ResponseWriter, r *http.Request) {
vr, _, err := adminClient.OAuth2API.RejectOAuth2ConsentRequest(context.Background()).
ConsentChallenge(r.URL.Query().Get("consent_challenge")).
RejectOAuth2Request(hydra.RejectOAuth2Request{
Error: pointerx.String(fosite.ErrInteractionRequired.ErrorField),
ErrorDescription: pointerx.String("expect-reject-consent"),
StatusCode: pointerx.Int64(int64(fosite.ErrInteractionRequired.CodeField))}).Execute()
require.NoError(t, err)
require.NotEmpty(t, vr.RedirectTo)
http.Redirect(w, r, vr.RedirectTo, http.StatusFound)
})
makeRequestAndExpectError(t, nil, c, url.Values{}, "expect-reject-consent")
})
t.Run("suite=double-submit", func(t *testing.T) {
ctx := context.Background()
c := createDefaultClient(t)
hc := testhelpers.NewEmptyJarClient(t)
var loginChallenge, consentChallenge string
testhelpers.NewLoginConsentUI(t, reg.Config(),
func(w http.ResponseWriter, r *http.Request) {
loginChallenge = r.URL.Query().Get("login_challenge")
res, _, err := adminClient.OAuth2API.GetOAuth2LoginRequest(ctx).
LoginChallenge(loginChallenge).
Execute()
require.NoError(t, err)
require.Equal(t, loginChallenge, res.Challenge)
v, _, err := adminClient.OAuth2API.AcceptOAuth2LoginRequest(ctx).
LoginChallenge(loginChallenge).
AcceptOAuth2LoginRequest(hydra.AcceptOAuth2LoginRequest{Subject: "aeneas-rekkas"}).
Execute()
require.NoError(t, err)
require.NotEmpty(t, v.RedirectTo)
http.Redirect(w, r, v.RedirectTo, http.StatusFound)
},
func(w http.ResponseWriter, r *http.Request) {
consentChallenge = r.URL.Query().Get("consent_challenge")
res, _, err := adminClient.OAuth2API.GetOAuth2ConsentRequest(ctx).
ConsentChallenge(consentChallenge).
Execute()
require.NoError(t, err)
require.Equal(t, consentChallenge, res.Challenge)
v, _, err := adminClient.OAuth2API.AcceptOAuth2ConsentRequest(ctx).
ConsentChallenge(consentChallenge).
AcceptOAuth2ConsentRequest(hydra.AcceptOAuth2ConsentRequest{}).
Execute()
require.NoError(t, err)
require.NotEmpty(t, v.RedirectTo)
http.Redirect(w, r, v.RedirectTo, http.StatusFound)
})
makeRequestAndExpectCode(t, hc, c, url.Values{})
t.Run("case=double-submit login verifier", func(t *testing.T) {
v, _, err := adminClient.OAuth2API.AcceptOAuth2LoginRequest(ctx).
LoginChallenge(loginChallenge).
AcceptOAuth2LoginRequest(hydra.AcceptOAuth2LoginRequest{Subject: "aeneas-rekkas"}).
Execute()
require.NoError(t, err)
res, err := hc.Get(v.RedirectTo)
require.NoError(t, err)
q := res.Request.URL.Query()
assert.Equal(t,
"The resource owner or authorization server denied the request. The consent verifier has already been used.",
q.Get("error_description"), q)
})
t.Run("case=double-submit consent verifier", func(t *testing.T) {
v, _, err := adminClient.OAuth2API.AcceptOAuth2ConsentRequest(ctx).
ConsentChallenge(consentChallenge).
AcceptOAuth2ConsentRequest(hydra.AcceptOAuth2ConsentRequest{}).
Execute()
require.NoError(t, err)
res, err := hc.Get(v.RedirectTo)
require.NoError(t, err)
q := res.Request.URL.Query()
assert.Equal(t,
"The resource owner or authorization server denied the request. The consent verifier has already been used.",
q.Get("error_description"), q)
})
})
t.Run("case=should pass and set acr values properly", func(t *testing.T) {
c := createDefaultClient(t)
testhelpers.NewLoginConsentUI(t, reg.Config(),
acceptLoginHandler(t, "aeneas-rekkas", nil),
acceptConsentHandler(t, nil))
makeRequestAndExpectCode(t, nil, c, url.Values{})
})
t.Run("case=should pass if both login and consent are granted and check remember flows as well as various payloads", func(t *testing.T) {
// Covers old test cases:
// - This should pass because login and consent have been granted, this time we remember the decision
// - This should pass because login and consent have been granted, this time we remember the decision#2
// - This should pass because login and consent have been granted, this time we remember the decision#3
// - This should pass because login was remembered and session id should be set and session context should also work
// - This should pass and confirm previous authentication and consent because it is a authorization_code
subject := "aeneas-rekkas"
c := createDefaultClient(t)
now := 1723546027 // Unix timestamps must round-trip through Hydra without converting to floats or similar
testhelpers.NewLoginConsentUI(t, reg.Config(),
acceptLoginHandler(t, subject, &hydra.AcceptOAuth2LoginRequest{
Remember: pointerx.Bool(true),
}),
acceptConsentHandler(t, &hydra.AcceptOAuth2ConsentRequest{
Remember: pointerx.Bool(true),
GrantScope: []string{"openid"},
Session: &hydra.AcceptOAuth2ConsentRequestSession{
AccessToken: map[string]interface{}{
"foo": "bar",
"ts1": now,
},
IdToken: map[string]interface{}{
"bar": "baz",
"ts2": now,
},
},
}))
hc := testhelpers.NewEmptyJarClient(t)
conf := oauth2Config(t, c)
var sid string
var run = func(t *testing.T) {
code := makeRequestAndExpectCode(t, hc, c, url.Values{"redirect_uri": {c.RedirectURIs[0]},
"scope": {"openid"}})
token, err := conf.Exchange(context.Background(), code)
require.NoError(t, err)
claims := testhelpers.IntrospectToken(t, conf, token.AccessToken, adminTS)
assert.Equalf(t, `"bar"`, claims.Get("ext.foo").Raw, "%s", claims.Raw) // Raw rather than .Int() or .Value() to verify the exact JSON payload
assert.Equalf(t, "1723546027", claims.Get("ext.ts1").Raw, "%s", claims.Raw) // must round-trip as integer
idClaims := testhelpers.DecodeIDToken(t, token)
assert.Equalf(t, `"baz"`, idClaims.Get("bar").Raw, "%s", idClaims.Raw) // Raw rather than .Int() or .Value() to verify the exact JSON payload
assert.Equalf(t, "1723546027", idClaims.Get("ts2").Raw, "%s", idClaims.Raw) // must round-trip as integer
sid = idClaims.Get("sid").String()
assert.NotEmpty(t, sid)
}
t.Run("perform first flow", run)
t.Run("perform follow up flows and check if session values are set", func(t *testing.T) {
testhelpers.NewLoginConsentUI(t, reg.Config(),
checkAndAcceptLoginHandler(t, adminClient, subject, func(t *testing.T, res *hydra.OAuth2LoginRequest, err error) hydra.AcceptOAuth2LoginRequest {
require.NoError(t, err)
assert.True(t, res.Skip)
assert.Equal(t, sid, *res.SessionId)
assert.Equal(t, subject, res.Subject)
assert.Empty(t, pointerx.StringR(res.Client.ClientSecret))
return hydra.AcceptOAuth2LoginRequest{
Subject: subject,
Context: map[string]interface{}{"xyz": "abc"},
}
}),
checkAndAcceptConsentHandler(t, adminClient, func(t *testing.T, req *hydra.OAuth2ConsentRequest, err error) hydra.AcceptOAuth2ConsentRequest {
require.NoError(t, err)
assert.True(t, *req.Skip)
assert.Equal(t, sid, *req.LoginSessionId)
assert.Equal(t, subject, *req.Subject)
assert.Empty(t, pointerx.StringR(req.Client.ClientSecret))
assert.Equal(t, map[string]interface{}{"xyz": "abc"}, req.Context)
return hydra.AcceptOAuth2ConsentRequest{
Remember: pointerx.Bool(true),
GrantScope: []string{"openid"},
Session: &hydra.AcceptOAuth2ConsentRequestSession{
AccessToken: map[string]interface{}{
"foo": "bar",
"ts1": now,
},
IdToken: map[string]interface{}{
"bar": "baz",
"ts2": now,
},
},
}
}))
for k := 0; k < 3; k++ {
t.Run(fmt.Sprintf("case=%d", k), run)
}
})
})
t.Run("case=should set client specific csrf cookie names", func(t *testing.T) {
subject := "subject-1"
consentRequestMaxAge := reg.Config().ConsentRequestMaxAge(ctx).Seconds()
c := createDefaultClient(t)
testhelpers.NewLoginConsentUI(t, reg.Config(),
acceptLoginHandler(t, subject, &hydra.AcceptOAuth2LoginRequest{
Remember: pointerx.Bool(true),
}),
acceptConsentHandler(t, &hydra.AcceptOAuth2ConsentRequest{
Remember: pointerx.Bool(true),
GrantScope: []string{"openid"},
Session: &hydra.AcceptOAuth2ConsentRequestSession{
AccessToken: map[string]interface{}{"foo": "bar"},
IdToken: map[string]interface{}{"bar": "baz"},
},
}))
testhelpers.NewLoginConsentUI(t, reg.Config(),
checkAndAcceptLoginHandler(t, adminClient, subject, func(t *testing.T, res *hydra.OAuth2LoginRequest, err error) hydra.AcceptOAuth2LoginRequest {
require.NoError(t, err)
assert.Empty(t, res.Subject)
assert.Empty(t, pointerx.StringR(res.Client.ClientSecret))
return hydra.AcceptOAuth2LoginRequest{
Subject: subject,
Context: map[string]interface{}{"foo": "bar"},
}
}),
checkAndAcceptConsentHandler(t, adminClient, func(t *testing.T, res *hydra.OAuth2ConsentRequest, err error) hydra.AcceptOAuth2ConsentRequest {
require.NoError(t, err)
assert.Equal(t, subject, *res.Subject)
assert.Empty(t, pointerx.StringR(res.Client.ClientSecret))
return hydra.AcceptOAuth2ConsentRequest{
Remember: pointerx.Bool(true),
GrantScope: []string{"openid"},
Session: &hydra.AcceptOAuth2ConsentRequestSession{
AccessToken: map[string]interface{}{"foo": "bar"},
IdToken: map[string]interface{}{"bar": "baz"},
},
}
}))
hc := &http.Client{
Jar: testhelpers.NewEmptyCookieJar(t),
Transport: &http.Transport{},
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
_, oauthRes := makeOAuth2Request(t, reg, hc, c, url.Values{"redirect_uri": {c.RedirectURIs[0]}, "scope": {"openid"}})
assert.EqualValues(t, http.StatusFound, oauthRes.StatusCode)
loginChallengeRedirect, err := oauthRes.Location()
require.NoError(t, err)
defer oauthRes.Body.Close()
foundLoginCookie := slices.ContainsFunc(oauthRes.Header.Values("set-cookie"), func(sc string) bool {
ok, err := regexp.MatchString(fmt.Sprintf("ory_hydra_login_csrf_dev_%s=.*Max-Age=%.0f;.*", c.CookieSuffix(), consentRequestMaxAge), sc)
require.NoError(t, err)
return ok
})
require.True(t, foundLoginCookie, "client-specific login cookie with max age set")
loginChallengeRes, err := hc.Get(loginChallengeRedirect.String())
require.NoError(t, err)
defer loginChallengeRes.Body.Close()
loginVerifierRedirect, err := loginChallengeRes.Location()
require.NoError(t, err)
loginVerifierRes, err := hc.Get(loginVerifierRedirect.String())
require.NoError(t, err)
defer loginVerifierRes.Body.Close()
foundConsentCookie := slices.ContainsFunc(loginVerifierRes.Header.Values("set-cookie"), func(sc string) bool {
ok, err := regexp.MatchString(fmt.Sprintf("ory_hydra_consent_csrf_dev_%s=.*Max-Age=%.0f;.*", c.CookieSuffix(), consentRequestMaxAge), sc)
require.NoError(t, err)
return ok
})
require.True(t, foundConsentCookie, "client-specific consent cookie with max age set")
})
t.Run("case=should pass if both login and consent are granted and check remember flows with refresh session cookie", func(t *testing.T) {
subject := "subject-1"
c := createDefaultClient(t)
testhelpers.NewLoginConsentUI(t, reg.Config(),
acceptLoginHandler(t, subject, &hydra.AcceptOAuth2LoginRequest{
Remember: pointerx.Bool(true),
}),
acceptConsentHandler(t, &hydra.AcceptOAuth2ConsentRequest{
Remember: pointerx.Bool(true),
GrantScope: []string{"openid"},
Session: &hydra.AcceptOAuth2ConsentRequestSession{
AccessToken: map[string]interface{}{"foo": "bar"},
IdToken: map[string]interface{}{"bar": "baz"},
},
}))
hc := testhelpers.NewEmptyJarClient(t)
followUpHandler := func(extendSessionLifespan bool) {
rememberFor := int64(12345)
testhelpers.NewLoginConsentUI(t, reg.Config(),
checkAndAcceptLoginHandler(t, adminClient, subject, func(t *testing.T, res *hydra.OAuth2LoginRequest, err error) hydra.AcceptOAuth2LoginRequest {
require.NoError(t, err)
assert.True(t, res.Skip)
assert.Equal(t, subject, res.Subject)
assert.Empty(t, res.Client.ClientSecret)
return hydra.AcceptOAuth2LoginRequest{
Subject: subject,
Remember: pointerx.Bool(true),
RememberFor: pointerx.Int64(rememberFor),
ExtendSessionLifespan: pointerx.Bool(extendSessionLifespan),
Context: map[string]interface{}{"foo": "bar"},
}
}),
checkAndAcceptConsentHandler(t, adminClient, func(t *testing.T, res *hydra.OAuth2ConsentRequest, err error) hydra.AcceptOAuth2ConsentRequest {
require.NoError(t, err)
assert.True(t, *res.Skip)
assert.Equal(t, subject, res.Subject)
assert.Empty(t, res.Client.ClientSecret)
return hydra.AcceptOAuth2ConsentRequest{
Remember: pointerx.Bool(true),
GrantScope: []string{"openid"},
Session: &hydra.AcceptOAuth2ConsentRequestSession{
AccessToken: map[string]interface{}{"foo": "bar"},
IdToken: map[string]interface{}{"bar": "baz"},
},
}
}))
hc := &http.Client{
Jar: hc.Jar,
Transport: &http.Transport{},
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
_, oauthRes := makeOAuth2Request(t, reg, hc, c, url.Values{"redirect_uri": {c.RedirectURIs[0]}, "scope": {"openid"}})
assert.EqualValues(t, http.StatusFound, oauthRes.StatusCode)
loginChallengeRedirect, err := oauthRes.Location()
require.NoError(t, err)
defer oauthRes.Body.Close()
loginChallengeRes, err := hc.Get(loginChallengeRedirect.String())
require.NoError(t, err)
defer loginChallengeRes.Body.Close()
loginVerifierRedirect, err := loginChallengeRes.Location()
require.NoError(t, err)
loginVerifierRes, err := hc.Get(loginVerifierRedirect.String())
require.NoError(t, err)
defer loginVerifierRes.Body.Close()
setCookieHeader := loginVerifierRes.Header.Get("set-cookie")
assert.NotNil(t, setCookieHeader)
if extendSessionLifespan {
assert.Regexp(t, fmt.Sprintf("ory_hydra_session_dev=.*; Path=/; Expires=.*Max-Age=%d; HttpOnly; SameSite=Lax", rememberFor), setCookieHeader)
} else {
assert.NotContains(t, setCookieHeader, "ory_hydra_session_dev")
}
}
t.Run("perform first flow", func(t *testing.T) {
makeRequestAndExpectCode(t, hc, c, url.Values{"redirect_uri": {c.RedirectURIs[0]},
"scope": {"openid"}})
})
t.Run("perform follow up flow with extend_session_lifespan=false", func(t *testing.T) {
followUpHandler(false)
})
t.Run("perform follow up flow with extend_session_lifespan=true", func(t *testing.T) {
followUpHandler(true)
})
})
t.Run("case=should set session cookie with correct configuration", func(t *testing.T) {
cookiePath := "/foo"
reg.Config().MustSet(ctx, config.KeyCookieSessionPath, cookiePath)
defer reg.Config().MustSet(ctx, config.KeyCookieSessionPath, "/")
subject := "subject-1"
c := createDefaultClient(t)
testhelpers.NewLoginConsentUI(t, reg.Config(),
acceptLoginHandler(t, subject, &hydra.AcceptOAuth2LoginRequest{
Remember: pointerx.Bool(true),
}),
acceptConsentHandler(t, &hydra.AcceptOAuth2ConsentRequest{
Remember: pointerx.Bool(true),
GrantScope: []string{"openid"},
Session: &hydra.AcceptOAuth2ConsentRequestSession{
AccessToken: map[string]interface{}{"foo": "bar"},
IdToken: map[string]interface{}{"bar": "baz"},
},
}))
testhelpers.NewLoginConsentUI(t, reg.Config(),
checkAndAcceptLoginHandler(t, adminClient, subject, func(t *testing.T, res *hydra.OAuth2LoginRequest, err error) hydra.AcceptOAuth2LoginRequest {
require.NoError(t, err)
assert.Empty(t, res.Subject)
assert.Empty(t, pointerx.StringR(res.Client.ClientSecret))
return hydra.AcceptOAuth2LoginRequest{
Subject: subject,
Context: map[string]interface{}{"foo": "bar"},
}
}),
checkAndAcceptConsentHandler(t, adminClient, func(t *testing.T, res *hydra.OAuth2ConsentRequest, err error) hydra.AcceptOAuth2ConsentRequest {
require.NoError(t, err)
assert.Equal(t, subject, *res.Subject)
assert.Empty(t, pointerx.StringR(res.Client.ClientSecret))
return hydra.AcceptOAuth2ConsentRequest{
Remember: pointerx.Bool(true),
GrantScope: []string{"openid"},
Session: &hydra.AcceptOAuth2ConsentRequestSession{
AccessToken: map[string]interface{}{"foo": "bar"},
IdToken: map[string]interface{}{"bar": "baz"},
},
}
}))
hc := &http.Client{
Jar: testhelpers.NewEmptyCookieJar(t),
Transport: &http.Transport{},
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
_, oauthRes := makeOAuth2Request(t, reg, hc, c, url.Values{"redirect_uri": {c.RedirectURIs[0]}, "scope": {"openid"}})
assert.EqualValues(t, http.StatusFound, oauthRes.StatusCode)
loginChallengeRedirect, err := oauthRes.Location()
require.NoError(t, err)
defer oauthRes.Body.Close()
loginChallengeRes, err := hc.Get(loginChallengeRedirect.String())
require.NoError(t, err)
defer loginChallengeRes.Body.Close()
loginVerifierRedirect, err := loginChallengeRes.Location()
require.NoError(t, err)
loginVerifierRes, err := hc.Get(loginVerifierRedirect.String())
require.NoError(t, err)
defer loginVerifierRes.Body.Close()
setCookieHeader := loginVerifierRes.Header.Get("set-cookie")
assert.NotNil(t, setCookieHeader)
assert.Regexp(t, fmt.Sprintf("ory_hydra_session_dev=.*; Path=%s; Expires=.*; Max-Age=0; HttpOnly; SameSite=Lax", cookiePath), setCookieHeader)
})
t.Run("case=should pass and check if login context is set properly", func(t *testing.T) {
// This should pass because login was remembered and session id should be set and session context should also work
subject := "aeneas-rekkas"
c := createDefaultClient(t)
testhelpers.NewLoginConsentUI(t, reg.Config(),
acceptLoginHandler(t, subject, &hydra.AcceptOAuth2LoginRequest{
Subject: subject,
Context: map[string]interface{}{"fooz": "barz"},
}),
checkAndAcceptConsentHandler(t, adminClient, func(t *testing.T, res *hydra.OAuth2ConsentRequest, err error) hydra.AcceptOAuth2ConsentRequest {
require.NoError(t, err)
assert.Equal(t, map[string]interface{}{"fooz": "barz"}, res.Context)
assert.Equal(t, subject, *res.Subject)
return hydra.AcceptOAuth2ConsentRequest{
Remember: pointerx.Bool(true),
GrantScope: []string{"openid"},
Session: &hydra.AcceptOAuth2ConsentRequestSession{
AccessToken: map[string]interface{}{"foo": "bar"},
IdToken: map[string]interface{}{"bar": "baz"},
},
}
}))
hc := testhelpers.NewEmptyJarClient(t)
makeRequestAndExpectCode(t, hc, c, url.Values{"redirect_uri": {c.RedirectURIs[0]}})
})
t.Run("case=perform flows with a public client", func(t *testing.T) {
// This test covers old cases:
// - This should fail because prompt=none, client is public, and redirection scheme is not HTTPS but a custom scheme and a custom domain
// - This should fail because prompt=none, client is public, and redirection scheme is not HTTPS but a custom scheme
// - This should pass because prompt=none, client is public, redirection scheme is HTTP and host is localhost
c := &client.Client{ID: uuidx.NewV4().String(), TokenEndpointAuthMethod: "none",
RedirectURIs: []string{
testhelpers.NewCallbackURL(t, "callback", testhelpers.HTTPServerNotImplementedHandler),
"custom://redirection-scheme/path",
"custom://localhost/path",
}}
require.NoError(t, reg.ClientManager().CreateClient(context.Background(), c))
subject := "aeneas-rekkas"
testhelpers.NewLoginConsentUI(t, reg.Config(),
acceptLoginHandler(t, subject, &hydra.AcceptOAuth2LoginRequest{Remember: pointerx.Bool(true), RememberFor: pointerx.Int64(0)}),
acceptConsentHandler(t, &hydra.AcceptOAuth2ConsentRequest{Remember: pointerx.Bool(true), RememberFor: pointerx.Int64(0)}))
hc := testhelpers.NewEmptyJarClient(t)
// set up initial session
makeRequestAndExpectCode(t, hc, c, url.Values{"redirect_uri": {c.RedirectURIs[0]}})
// By not waiting here we ensure that there are no race conditions when it comes to authenticated_at and
// requested_at time comparisons:
//
// time.Sleep(time.Second)
t.Run("followup=should pass when prompt=none, redirection scheme is HTTP and host is localhost", func(t *testing.T) {
makeRequestAndExpectCode(t, hc, c, url.Values{"redirect_uri": {c.RedirectURIs[0]}, "prompt": {"none"}})
})
t.Run("followup=should pass when prompt=none, redirection scheme is HTTP and host is a custom scheme", func(t *testing.T) {
for _, redir := range c.RedirectURIs[1:] {
t.Run("redir=should pass because prompt=none, client is public, and redirection is "+redir, func(t *testing.T) {
_, err := hc.Get(urlx.CopyWithQuery(reg.Config().OAuth2AuthURL(ctx), url.Values{
"response_type": {"code"},
"state": {uuid.New()},
"redirect_uri": {redir},
"client_id": {c.GetID()},
"prompt": {"none"},
}).String())
require.Error(t, err)
assert.Contains(t, err.Error(), redir)
// https://tools.ietf.org/html/rfc6749
//
// As stated in Section 10.2 of OAuth 2.0 [RFC6749], the authorization
// server SHOULD NOT process authorization requests automatically
// without user consent or interaction, except when the identity of the
// client can be assured. This includes the case where the user has
// previously approved an authorization request for a given client id --
// unless the identity of the client can be proven, the request SHOULD
// be processed as if no previous request had been approved.
//
// Measures such as claimed "https" scheme redirects MAY be accepted by
// authorization servers as identity proof. Some operating systems may
// offer alternative platform-specific identity features that MAY be
assert.Contains(t, err.Error(), "error=consent_required")
})
}
})
})
t.Run("case=should retry the authorization with prompt=login if subject in login challenge does not match subject from previous session", func(t *testing.T) {
// Previously: This should fail at login screen because subject from accept does not match subject from session
c := createDefaultClient(t)
testhelpers.NewLoginConsentUI(t, reg.Config(),
acceptLoginHandler(t, "aeneas-rekkas", &hydra.AcceptOAuth2LoginRequest{Remember: pointerx.Bool(true)}),
acceptConsentHandler(t, nil))
// Init session
hc := testhelpers.NewEmptyJarClient(t)
makeRequestAndExpectCode(t, hc, c, url.Values{})
testhelpers.NewLoginConsentUI(t, reg.Config(),
func(w http.ResponseWriter, r *http.Request) {
res, _, err := adminClient.OAuth2API.AcceptOAuth2LoginRequest(context.Background()).
LoginChallenge(r.URL.Query().Get("login_challenge")).
AcceptOAuth2LoginRequest(hydra.AcceptOAuth2LoginRequest{
Subject: "not-aeneas-rekkas",
}).Execute()
require.NoError(t, err)
redirectURL, err := url.Parse(res.RedirectTo)
require.NoError(t, err)
assert.Equal(t, "login", redirectURL.Query().Get("prompt"))
w.WriteHeader(http.StatusBadRequest)
},
testhelpers.HTTPServerNoExpectedCallHandler(t))
_, res := makeOAuth2Request(t, reg, hc, c, url.Values{})
assert.EqualValues(t, http.StatusBadRequest, res.StatusCode)
assert.Empty(t, res.Request.URL.Query().Get("code"))
})
t.Run("case=should require re-authentication when parameters mandate it", func(t *testing.T) {
// Covers:
// - should pass and require re-authentication although session is set (because prompt=login)
// - should pass and require re-authentication although session is set (because max_age=1)
subject := "aeneas-rekkas"
c := createDefaultClient(t)
resetUI := func(t *testing.T) {
testhelpers.NewLoginConsentUI(t, reg.Config(),
checkAndAcceptLoginHandler(t, adminClient, subject, func(t *testing.T, res *hydra.OAuth2LoginRequest, err error) hydra.AcceptOAuth2LoginRequest {
require.NoError(t, err)
assert.False(t, res.Skip) // Skip should always be false here
return hydra.AcceptOAuth2LoginRequest{
Remember: pointerx.Bool(true),
}
}),
acceptConsentHandler(t, &hydra.AcceptOAuth2ConsentRequest{
Remember: pointerx.Bool(true),
}))
}
resetUI(t)
// Init session
hc := testhelpers.NewEmptyJarClient(t)
makeRequestAndExpectCode(t, hc, c, url.Values{})
for k, values := range []url.Values{
{"prompt": {"login"}},
{"max_age": {"1"}},
{"max_age": {"0"}},
} {
t.Run("values="+values.Encode(), func(t *testing.T) {
if k == 1 {
// If this is the max_age case we need to wait for max age to pass.
time.Sleep(time.Second)
}
resetUI(t)
makeRequestAndExpectCode(t, hc, c, values)
})
}
})
t.Run("case=should fail because max_age=1 but prompt=none", func(t *testing.T) {
subject := "aeneas-rekkas"
c := createDefaultClient(t)
testhelpers.NewLoginConsentUI(t, reg.Config(), acceptLoginHandler(t, subject, &hydra.AcceptOAuth2LoginRequest{Remember: pointerx.Bool(true)}),
acceptConsentHandler(t, &hydra.AcceptOAuth2ConsentRequest{Remember: pointerx.Bool(true)}))
hc := testhelpers.NewEmptyJarClient(t)
makeRequestAndExpectCode(t, hc, c, url.Values{})
time.Sleep(time.Second)
makeRequestAndExpectError(t, hc, c, url.Values{"max_age": {"1"}, "prompt": {"none"}},
"prompt is set to 'none' and authentication time reached 'max_age'")
})
t.Run("case=should fail because prompt is none but no auth session exists", func(t *testing.T) {
c := createDefaultClient(t)
testhelpers.NewLoginConsentUI(t, reg.Config(), acceptLoginHandler(t, "aeneas-rekkas", &hydra.AcceptOAuth2LoginRequest{Remember: pointerx.Bool(true)}),
acceptConsentHandler(t, &hydra.AcceptOAuth2ConsentRequest{Remember: pointerx.Bool(true)}))
makeRequestAndExpectError(t, nil, c, url.Values{"prompt": {"none"}},
"Prompt 'none' was requested, but no existing login session was found")
})
t.Run("case=should fail because prompt is none and consent is missing a permission which requires re-authorization of the app", func(t *testing.T) {
c := createDefaultClient(t)
testhelpers.NewLoginConsentUI(t, reg.Config(), acceptLoginHandler(t, "aeneas-rekkas", &hydra.AcceptOAuth2LoginRequest{Remember: pointerx.Bool(true)}),
acceptConsentHandler(t, &hydra.AcceptOAuth2ConsentRequest{Remember: pointerx.Bool(true)}))
// Init cookie
hc := testhelpers.NewEmptyJarClient(t)
makeRequestAndExpectCode(t, hc, c, url.Values{})
// Make request with additional scope and prompt none, which fails
makeRequestAndExpectError(t, hc, c, url.Values{"prompt": {"none"}, "scope": {"openid"}, "redirect_uri": {c.RedirectURIs[0]}},
"Prompt 'none' was requested, but no previous consent was found")
})
t.Run("case=pass and properly require authentication as well as authorization because prompt is set to login and consent although previous session exists", func(t *testing.T) {
subject := "aeneas-rekkas"
c := createDefaultClient(t)
testhelpers.NewLoginConsentUI(t, reg.Config(),
checkAndAcceptLoginHandler(t, adminClient, subject, func(t *testing.T, res *hydra.OAuth2LoginRequest, err error) hydra.AcceptOAuth2LoginRequest {
require.NoError(t, err)
assert.False(t, res.Skip) // Skip should always be false here because prompt has login
return hydra.AcceptOAuth2LoginRequest{Remember: pointerx.Bool(true)}
}),
checkAndAcceptConsentHandler(t, adminClient, func(t *testing.T, res *hydra.OAuth2ConsentRequest, err error) hydra.AcceptOAuth2ConsentRequest {
require.NoError(t, err)
assert.False(t, *res.Skip) // Skip should always be false here because prompt has consent
return hydra.AcceptOAuth2ConsentRequest{
Remember: pointerx.Bool(true),
}
}))
// Init cookie
hc := testhelpers.NewEmptyJarClient(t)
makeRequestAndExpectCode(t, hc, c, url.Values{})
// Rerun with login and consent set
makeRequestAndExpectCode(t, hc, c, url.Values{"prompt": {"login consent"}})
})
t.Run("case=should fail because id_token_hint does not match value from accepted login request", func(t *testing.T) {
// Covers former tests:
// - This should pass and require authentication because id_token_hint does not match subject from session
// - This should fail because id_token_hint does not match authentication session and prompt is none
// - This should fail because the user from the ID token does not match the user from the accept login request
subject := "aeneas-rekkas"
notSubject := "not-aeneas-rekkas"
c := createDefaultClient(t)
testhelpers.NewLoginConsentUI(t, reg.Config(),
acceptLoginHandler(t, subject, &hydra.AcceptOAuth2LoginRequest{Remember: pointerx.Bool(true)}),
acceptConsentHandler(t, &hydra.AcceptOAuth2ConsentRequest{Remember: pointerx.Bool(true)}))
// Init cookie
hc := testhelpers.NewEmptyJarClient(t)
makeRequestAndExpectCode(t, hc, c, url.Values{})
for _, values := range []url.Values{
{"prompt": {"none"}, "id_token_hint": {testhelpers.NewIDToken(t, reg, notSubject)}},
{"id_token_hint": {testhelpers.NewIDToken(t, reg, notSubject)}},
} {
t.Run(fmt.Sprintf("values=%v", values), func(t *testing.T) {
testhelpers.NewLoginConsentUI(t, reg.Config(),
checkAndAcceptLoginHandler(t, adminClient, subject, func(t *testing.T, res *hydra.OAuth2LoginRequest, err error) hydra.AcceptOAuth2LoginRequest {
var b bytes.Buffer
require.NoError(t, json.NewEncoder(&b).Encode(res))
assert.EqualValues(t, notSubject, gjson.GetBytes(b.Bytes(), "oidc_context.id_token_hint_claims.sub"), b.String())
return hydra.AcceptOAuth2LoginRequest{Remember: pointerx.Bool(true)}
}),
acceptConsentHandler(t, &hydra.AcceptOAuth2ConsentRequest{Remember: pointerx.Bool(true)}))
makeRequestAndExpectError(t, hc, c, values,
"Request failed because subject claim from id_token_hint does not match subject from authentication session")
})
}
})
t.Run("case=should pass and require authentication because id_token_hint does match subject from session", func(t *testing.T) {
subject := "aeneas-rekkas"
c := createDefaultClient(t)
testhelpers.NewLoginConsentUI(t, reg.Config(),
acceptLoginHandler(t, subject, &hydra.AcceptOAuth2LoginRequest{Remember: pointerx.Bool(true)}),
acceptConsentHandler(t, &hydra.AcceptOAuth2ConsentRequest{Remember: pointerx.Bool(true)}))
makeRequestAndExpectCode(t, nil, c, url.Values{"id_token_hint": {testhelpers.NewIDToken(t, reg, subject)}})
t.Run("case=should pass even though id_token_hint is expired", func(t *testing.T) {
// Formerly: should pass as regularly even though id_token_hint is expired
makeRequestAndExpectCode(t, nil, c, url.Values{
"id_token_hint": {testhelpers.NewIDTokenWithExpiry(t, reg, subject, -time.Hour)}})
})
})
t.Run("suite=pairwise auth", func(t *testing.T) {
// Covers former tests:
// - This should pass as regularly and create a new session with pairwise subject set by hydra
// - This should pass as regularly and create a new session with pairwise subject and also with the ID token set
c := createClient(t, reg, &client.Client{
SubjectType: "pairwise",
SectorIdentifierURI: "foo",
RedirectURIs: []string{testhelpers.NewCallbackURL(t, "callback", testhelpers.HTTPServerNotImplementedHandler)},
})
subject := "auth-user"
hash := fmt.Sprintf("%x",
sha256.Sum256([]byte(c.SectorIdentifierURI+subject+reg.Config().SubjectIdentifierAlgorithmSalt(ctx))))
testhelpers.NewLoginConsentUI(t, reg.Config(),
acceptLoginHandler(t, subject, &hydra.AcceptOAuth2LoginRequest{Remember: pointerx.Bool(true)}),
acceptConsentHandler(t, &hydra.AcceptOAuth2ConsentRequest{Remember: pointerx.Bool(true), GrantScope: []string{"openid"}}))
for _, tc := range []struct {
d string
values url.Values
}{
{
d: "check all the sub claims",
values: url.Values{"scope": {"openid"}, "redirect_uri": {c.RedirectURIs[0]}},
},
{
d: "works with id_token_hint",
values: url.Values{"scope": {"openid"}, "redirect_uri": {c.RedirectURIs[0]}, "id_token_hint": {testhelpers.NewIDToken(t, reg, hash)}},
},
} {
t.Run("case="+tc.d, func(t *testing.T) {
code := makeRequestAndExpectCode(t, nil, c, tc.values)
conf := oauth2Config(t, c)
token, err := conf.Exchange(context.Background(), code)
require.NoError(t, err)
// OpenID data must be obfuscated
idClaims := testhelpers.DecodeIDToken(t, token)
assert.EqualValues(t, hash, idClaims.Get("sub").String())
uiClaims := testhelpers.Userinfo(t, token, publicTS)
assert.EqualValues(t, hash, uiClaims.Get("sub").String())
// Access token data must not be obfuscated
atClaims := testhelpers.IntrospectToken(t, conf, token.AccessToken, adminTS)
assert.EqualValues(t, subject, atClaims.Get("sub").String())
})
}
})
t.Run("suite=pairwise auth with forced identifier", func(t *testing.T) {
// Covers:
// - This should pass as regularly and create a new session with pairwise subject set login request
// - This should pass as regularly and create a new session with pairwise subject set on login request and also with the ID token set
c := createClient(t, reg, &client.Client{
SubjectType: "pairwise",
SectorIdentifierURI: "foo",
RedirectURIs: []string{testhelpers.NewCallbackURL(t, "callback", testhelpers.HTTPServerNotImplementedHandler)},
})
subject := "aeneas-rekkas"
obfuscated := "obfuscated-friedrich-kaiser"
testhelpers.NewLoginConsentUI(t, reg.Config(),
acceptLoginHandler(t, subject, &hydra.AcceptOAuth2LoginRequest{
ForceSubjectIdentifier: &obfuscated,
}),
acceptConsentHandler(t, &hydra.AcceptOAuth2ConsentRequest{GrantScope: []string{"openid"}}))
code := makeRequestAndExpectCode(t, nil, c, url.Values{"redirect_uri": {c.RedirectURIs[0]}})
conf := oauth2Config(t, c)
token, err := conf.Exchange(context.Background(), code)
require.NoError(t, err)
// OpenID data must be obfuscated
idClaims := testhelpers.DecodeIDToken(t, token)
assert.EqualValues(t, obfuscated, idClaims.Get("sub").String())
uiClaims := testhelpers.Userinfo(t, token, publicTS)
assert.EqualValues(t, obfuscated, uiClaims.Get("sub").String())
// Access token data must not be obfuscated
atClaims := testhelpers.IntrospectToken(t, conf, token.AccessToken, adminTS)
assert.EqualValues(t, subject, atClaims.Get("sub").String())
})
t.Run("suite=properly clean up session cookies", func(t *testing.T) {
t.Skip("This test is skipped because we forcibly set remember to true always when skip is also true for a better user experience.")
subject := "aeneas-rekkas"
c := createDefaultClient(t)
testhelpers.NewLoginConsentUI(t, reg.Config(),