-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
strategy_default.go
1180 lines (998 loc) · 41.6 KB
/
strategy_default.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
// Copyright © 2022 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package consent
import (
"context"
stderrs "errors"
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/gorilla/sessions"
"github.com/hashicorp/go-retryablehttp"
"github.com/pborman/uuid"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"go.opentelemetry.io/otel/trace"
"github.com/ory/hydra/v2/flow"
"github.com/ory/hydra/v2/oauth2/flowctx"
"github.com/ory/fosite"
"github.com/ory/fosite/handler/openid"
"github.com/ory/fosite/token/jwt"
"github.com/ory/hydra/v2/client"
"github.com/ory/hydra/v2/driver/config"
"github.com/ory/hydra/v2/x"
"github.com/ory/x/errorsx"
"github.com/ory/x/mapx"
"github.com/ory/x/otelx"
"github.com/ory/x/sqlcon"
"github.com/ory/x/sqlxx"
"github.com/ory/x/stringslice"
"github.com/ory/x/stringsx"
"github.com/ory/x/urlx"
)
const (
CookieAuthenticationSIDName = "sid"
)
type DefaultStrategy struct {
c *config.DefaultProvider
r InternalRegistry
}
func NewStrategy(
r InternalRegistry,
c *config.DefaultProvider,
) *DefaultStrategy {
return &DefaultStrategy{
c: c,
r: r,
}
}
var ErrAbortOAuth2Request = stderrs.New("the OAuth 2.0 Authorization request must be aborted")
var ErrNoPreviousConsentFound = stderrs.New("no previous OAuth 2.0 Consent could be found for this access request")
var ErrNoAuthenticationSessionFound = stderrs.New("no previous login session was found")
var ErrHintDoesNotMatchAuthentication = stderrs.New("subject from hint does not match subject from session")
func (s *DefaultStrategy) matchesValueFromSession(ctx context.Context, c fosite.Client, hintSubject string, sessionSubject string) error {
obfuscatedUserID, err := s.ObfuscateSubjectIdentifier(ctx, c, sessionSubject, "")
if err != nil {
return err
}
var forcedObfuscatedUserID string
if s, err := s.r.ConsentManager().GetForcedObfuscatedLoginSession(ctx, c.GetID(), hintSubject); errors.Is(err, x.ErrNotFound) {
// do nothing
} else if err != nil {
return err
} else {
forcedObfuscatedUserID = s.SubjectObfuscated
}
if hintSubject != sessionSubject && hintSubject != obfuscatedUserID && hintSubject != forcedObfuscatedUserID {
return ErrHintDoesNotMatchAuthentication
}
return nil
}
func (s *DefaultStrategy) authenticationSession(ctx context.Context, _ http.ResponseWriter, r *http.Request) (*flow.LoginSession, error) {
store, err := s.r.CookieStore(ctx)
if err != nil {
return nil, err
}
// We try to open the session cookie. If it does not exist (indicated by the error), we must authenticate the user.
cookie, err := store.Get(r, s.c.SessionCookieName(ctx))
if err != nil {
s.r.Logger().
WithRequest(r).
WithError(err).Debug("User logout skipped because cookie store returned an error.")
return nil, errorsx.WithStack(ErrNoAuthenticationSessionFound)
}
sessionID := mapx.GetStringDefault(cookie.Values, CookieAuthenticationSIDName, "")
if sessionID == "" {
s.r.Logger().
WithRequest(r).
Debug("User logout skipped because cookie exists but session value is empty.")
return nil, errorsx.WithStack(ErrNoAuthenticationSessionFound)
}
session, err := s.r.ConsentManager().GetRememberedLoginSession(r.Context(), nil, sessionID)
if errors.Is(err, x.ErrNotFound) {
s.r.Logger().WithRequest(r).WithError(err).
Debug("User logout skipped because cookie exists and session value exist but are not remembered any more.")
return nil, errorsx.WithStack(ErrNoAuthenticationSessionFound)
} else if err != nil {
return nil, err
}
return session, nil
}
func (s *DefaultStrategy) requestAuthentication(ctx context.Context, w http.ResponseWriter, r *http.Request, ar fosite.AuthorizeRequester) (err error) {
ctx, span := trace.SpanFromContext(ctx).TracerProvider().Tracer("").Start(ctx, "DefaultStrategy.requestAuthentication")
defer otelx.End(span, &err)
prompt := stringsx.Splitx(ar.GetRequestForm().Get("prompt"), " ")
if stringslice.Has(prompt, "login") {
return s.forwardAuthenticationRequest(ctx, w, r, ar, "", time.Time{}, nil)
}
session, err := s.authenticationSession(ctx, w, r)
if errors.Is(err, ErrNoAuthenticationSessionFound) {
return s.forwardAuthenticationRequest(ctx, w, r, ar, "", time.Time{}, nil)
} else if err != nil {
return err
}
maxAge := int64(-1)
if ma := ar.GetRequestForm().Get("max_age"); len(ma) > 0 {
var err error
maxAge, err = strconv.ParseInt(ma, 10, 64)
if err != nil {
return err
}
}
if maxAge > -1 && time.Time(session.AuthenticatedAt).UTC().Add(time.Second*time.Duration(maxAge)).Before(time.Now().UTC()) {
if stringslice.Has(prompt, "none") {
return errorsx.WithStack(fosite.ErrLoginRequired.WithHint("Request failed because prompt is set to 'none' and authentication time reached 'max_age'."))
}
return s.forwardAuthenticationRequest(ctx, w, r, ar, "", time.Time{}, nil)
}
idTokenHint := ar.GetRequestForm().Get("id_token_hint")
if idTokenHint == "" {
return s.forwardAuthenticationRequest(ctx, w, r, ar, session.Subject, time.Time(session.AuthenticatedAt), session)
}
hintSub, err := s.getSubjectFromIDTokenHint(r.Context(), idTokenHint)
if err != nil {
return err
}
if err := s.matchesValueFromSession(r.Context(), ar.GetClient(), hintSub, session.Subject); errors.Is(err, ErrHintDoesNotMatchAuthentication) {
return errorsx.WithStack(fosite.ErrLoginRequired.WithHint("Request failed because subject claim from id_token_hint does not match subject from authentication session."))
}
return s.forwardAuthenticationRequest(ctx, w, r, ar, session.Subject, time.Time(session.AuthenticatedAt), session)
}
func (s *DefaultStrategy) getIDTokenHintClaims(ctx context.Context, idTokenHint string) (jwt.MapClaims, error) {
token, err := s.r.OpenIDJWTStrategy().Decode(ctx, idTokenHint)
if ve := new(jwt.ValidationError); errors.As(err, &ve) && ve.Errors == jwt.ValidationErrorExpired {
// Expired is ok
} else if err != nil {
return nil, errorsx.WithStack(fosite.ErrInvalidRequest.WithHint(err.Error()))
}
return token.Claims, nil
}
func (s *DefaultStrategy) getSubjectFromIDTokenHint(ctx context.Context, idTokenHint string) (string, error) {
claims, err := s.getIDTokenHintClaims(ctx, idTokenHint)
if err != nil {
return "", err
}
sub, _ := claims["sub"].(string)
if sub == "" {
return "", errorsx.WithStack(fosite.ErrInvalidRequest.WithHint("Failed to validate OpenID Connect request because provided id token from id_token_hint does not have a subject."))
}
return sub, nil
}
func (s *DefaultStrategy) forwardAuthenticationRequest(ctx context.Context, w http.ResponseWriter, r *http.Request, ar fosite.AuthorizeRequester, subject string, authenticatedAt time.Time, session *flow.LoginSession) error {
if (subject != "" && authenticatedAt.IsZero()) || (subject == "" && !authenticatedAt.IsZero()) {
return errorsx.WithStack(fosite.ErrServerError.WithHint("Consent strategy returned a non-empty subject with an empty auth date, or an empty subject with a non-empty auth date."))
}
skip := false
if subject != "" {
skip = true
}
// Let's validate that prompt is actually not "none" if we can't skip authentication
prompt := stringsx.Splitx(ar.GetRequestForm().Get("prompt"), " ")
if stringslice.Has(prompt, "none") && !skip {
return errorsx.WithStack(fosite.ErrLoginRequired.WithHint(`Prompt 'none' was requested, but no existing login session was found.`))
}
// Set up csrf/challenge/verifier values
verifier := strings.Replace(uuid.New(), "-", "", -1)
challenge := strings.Replace(uuid.New(), "-", "", -1)
csrf := strings.Replace(uuid.New(), "-", "", -1)
// Generate the request URL
iu := s.c.OAuth2AuthURL(ctx)
iu.RawQuery = r.URL.RawQuery
var idTokenHintClaims jwt.MapClaims
if idTokenHint := ar.GetRequestForm().Get("id_token_hint"); len(idTokenHint) > 0 {
claims, err := s.getIDTokenHintClaims(r.Context(), idTokenHint)
if err != nil {
return err
}
idTokenHintClaims = claims
}
sessionID := uuid.New()
if session != nil {
sessionID = session.ID
}
// Set the session
cl := sanitizeClientFromRequest(ar)
loginRequest := &flow.LoginRequest{
ID: challenge,
Verifier: verifier,
CSRF: csrf,
Skip: skip,
RequestedScope: []string(ar.GetRequestedScopes()),
RequestedAudience: []string(ar.GetRequestedAudience()),
Subject: subject,
Client: cl,
RequestURL: iu.String(),
AuthenticatedAt: sqlxx.NullTime(authenticatedAt),
RequestedAt: time.Now().Truncate(time.Second).UTC(),
SessionID: sqlxx.NullString(sessionID),
OpenIDConnectContext: &flow.OAuth2ConsentRequestOpenIDConnectContext{
IDTokenHintClaims: idTokenHintClaims,
ACRValues: stringsx.Splitx(ar.GetRequestForm().Get("acr_values"), " "),
UILocales: stringsx.Splitx(ar.GetRequestForm().Get("ui_locales"), " "),
Display: ar.GetRequestForm().Get("display"),
LoginHint: ar.GetRequestForm().Get("login_hint"),
},
}
f, err := s.r.ConsentManager().CreateLoginRequest(
ctx,
loginRequest,
)
if err != nil {
return errorsx.WithStack(err)
}
store, err := s.r.CookieStore(ctx)
if err != nil {
return err
}
clientSpecificCookieNameLoginCSRF := fmt.Sprintf("%s_%s", s.r.Config().CookieNameLoginCSRF(ctx), cl.CookieSuffix())
if err := createCsrfSession(w, r, s.r.Config(), store, clientSpecificCookieNameLoginCSRF, csrf, s.c.ConsentRequestMaxAge(ctx)); err != nil {
return errorsx.WithStack(err)
}
encodedFlow, err := f.ToLoginChallenge(ctx, s.r)
if err != nil {
return err
}
var baseURL *url.URL
if stringslice.Has(prompt, "registration") {
baseURL = s.c.RegistrationURL(ctx)
} else {
baseURL = s.c.LoginURL(ctx)
}
http.Redirect(w, r, urlx.SetQuery(baseURL, url.Values{"login_challenge": {encodedFlow}}).String(), http.StatusFound)
// generate the verifier
return errorsx.WithStack(ErrAbortOAuth2Request)
}
func (s *DefaultStrategy) revokeAuthenticationSession(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
store, err := s.r.CookieStore(ctx)
if err != nil {
return err
}
sid, err := s.revokeAuthenticationCookie(w, r, store)
if err != nil {
return err
}
if sid == "" {
return nil
}
_, err = s.r.ConsentManager().DeleteLoginSession(r.Context(), sid)
return err
}
func (s *DefaultStrategy) revokeAuthenticationCookie(w http.ResponseWriter, r *http.Request, ss sessions.Store) (string, error) {
ctx := r.Context()
cookie, _ := ss.Get(r, s.c.SessionCookieName(ctx))
sid, _ := mapx.GetString(cookie.Values, CookieAuthenticationSIDName)
cookie.Values[CookieAuthenticationSIDName] = ""
cookie.Options.HttpOnly = true
cookie.Options.Path = s.c.SessionCookiePath(ctx)
cookie.Options.SameSite = s.c.CookieSameSiteMode(ctx)
cookie.Options.Secure = s.c.CookieSecure(ctx)
cookie.Options.Domain = s.c.CookieDomain(ctx)
cookie.Options.MaxAge = -1
if err := cookie.Save(r, w); err != nil {
return "", errorsx.WithStack(err)
}
return sid, nil
}
func (s *DefaultStrategy) verifyAuthentication(
ctx context.Context,
w http.ResponseWriter,
r *http.Request,
req fosite.AuthorizeRequester,
verifier string,
) (_ *flow.Flow, err error) {
ctx, span := trace.SpanFromContext(ctx).TracerProvider().Tracer("").Start(ctx, "DefaultStrategy.verifyAuthentication")
defer otelx.End(span, &err)
// We decode the flow from the cookie again because VerifyAndInvalidateLoginRequest does not return the flow
f, err := flowctx.Decode[flow.Flow](ctx, s.r.FlowCipher(), verifier, flowctx.AsLoginVerifier)
if err != nil {
return nil, errorsx.WithStack(fosite.ErrAccessDenied.WithHint("The login verifier is invalid."))
}
session, err := s.r.ConsentManager().VerifyAndInvalidateLoginRequest(ctx, verifier)
if errors.Is(err, sqlcon.ErrNoRows) {
return nil, errorsx.WithStack(fosite.ErrAccessDenied.WithHint("The login verifier has already been used, has not been granted, or is invalid."))
} else if err != nil {
return nil, err
}
if session.HasError() {
session.Error.SetDefaults(flow.LoginRequestDeniedErrorName)
return nil, errorsx.WithStack(session.Error.ToRFCError())
}
if session.RequestedAt.Add(s.c.ConsentRequestMaxAge(ctx)).Before(time.Now()) {
return nil, errorsx.WithStack(fosite.ErrRequestUnauthorized.WithHint("The login request has expired. Please try again."))
}
store, err := s.r.CookieStore(ctx)
if err != nil {
return nil, err
}
clientSpecificCookieNameLoginCSRF := fmt.Sprintf("%s_%s", s.r.Config().CookieNameLoginCSRF(ctx), session.LoginRequest.Client.CookieSuffix())
if err := validateCsrfSession(r, s.r.Config(), store, clientSpecificCookieNameLoginCSRF, session.LoginRequest.CSRF); err != nil {
return nil, err
}
if session.LoginRequest.Skip && !session.Remember {
return nil, errorsx.WithStack(fosite.ErrServerError.WithHint("The login request was previously remembered and can only be forgotten using the reject feature."))
}
if session.LoginRequest.Skip && session.Subject != session.LoginRequest.Subject {
// Revoke the session because there's clearly a mix up wrt the subject that's being authenticated
if err := s.revokeAuthenticationSession(ctx, w, r); err != nil {
return nil, err
}
return nil, errorsx.WithStack(fosite.ErrServerError.WithHint("The login request is marked as remember, but the subject from the login confirmation does not match the original subject from the cookie."))
}
subjectIdentifier, err := s.ObfuscateSubjectIdentifier(ctx, req.GetClient(), session.Subject, session.ForceSubjectIdentifier)
if err != nil {
return nil, err
}
sessionID := session.LoginRequest.SessionID.String()
if err := s.r.OpenIDConnectRequestValidator().ValidatePrompt(ctx, &fosite.AuthorizeRequest{
ResponseTypes: req.GetResponseTypes(),
RedirectURI: req.GetRedirectURI(),
State: req.GetState(),
// HandledResponseTypes, this can be safely ignored because it's not being used by validation
Request: fosite.Request{
ID: req.GetID(),
RequestedAt: req.GetRequestedAt(),
Client: req.GetClient(),
RequestedAudience: req.GetRequestedAudience(),
GrantedAudience: req.GetGrantedAudience(),
RequestedScope: req.GetRequestedScopes(),
GrantedScope: req.GetGrantedScopes(),
Form: req.GetRequestForm(),
Session: &openid.DefaultSession{
Claims: &jwt.IDTokenClaims{
Subject: subjectIdentifier,
IssuedAt: time.Now().UTC(), // doesn't matter
ExpiresAt: time.Now().Add(time.Hour).UTC(), // doesn't matter
AuthTime: time.Time(session.AuthenticatedAt),
RequestedAt: session.RequestedAt,
},
Headers: &jwt.Headers{},
Subject: session.Subject,
},
},
}); errors.Is(err, fosite.ErrLoginRequired) {
// This indicates that something went wrong with checking the subject id - let's destroy the session to be safe
if err := s.revokeAuthenticationSession(ctx, w, r); err != nil {
return nil, err
}
return nil, err
} else if err != nil {
return nil, err
}
if session.ForceSubjectIdentifier != "" {
if err := s.r.ConsentManager().CreateForcedObfuscatedLoginSession(r.Context(), &ForcedObfuscatedLoginSession{
Subject: session.Subject,
ClientID: req.GetClient().GetID(),
SubjectObfuscated: session.ForceSubjectIdentifier,
}); err != nil {
return nil, err
}
}
if !session.LoginRequest.Skip {
if time.Time(session.AuthenticatedAt).IsZero() {
return nil, errorsx.WithStack(fosite.ErrServerError.WithHint(
"Expected the handled login request to contain a valid authenticated_at value but it was zero. " +
"This is a bug which should be reported to https://github.com/ory/hydra."))
}
if err := s.r.ConsentManager().ConfirmLoginSession(ctx, &flow.LoginSession{
ID: sessionID,
AuthenticatedAt: session.AuthenticatedAt,
Subject: session.Subject,
IdentityProviderSessionID: sqlxx.NullString(session.IdentityProviderSessionID),
Remember: session.Remember,
}); err != nil {
if errors.Is(err, sqlcon.ErrUniqueViolation) {
return nil, errorsx.WithStack(fosite.ErrAccessDenied.WithHint("The login verifier has already been used."))
}
return nil, err
}
}
if !session.Remember && !session.LoginRequest.Skip {
// If the session should not be remembered (and we're actually not skipping), than the user clearly don't
// wants us to store a cookie. So let's bust the authentication session (if one exists).
if err := s.revokeAuthenticationSession(ctx, w, r); err != nil {
return nil, err
}
}
if !session.Remember || session.LoginRequest.Skip && !session.ExtendSessionLifespan {
// If the user doesn't want to remember the session, we do not store a cookie.
// If login was skipped, it means an authentication cookie was present and
// we don't want to touch it (in order to preserve its original expiry date)
return f, nil
}
// Not a skipped login and the user asked to remember its session, store a cookie
cookie, _ := store.Get(r, s.c.SessionCookieName(ctx))
cookie.Values[CookieAuthenticationSIDName] = sessionID
if session.RememberFor >= 0 {
cookie.Options.MaxAge = session.RememberFor
}
cookie.Options.HttpOnly = true
cookie.Options.Path = s.c.SessionCookiePath(ctx)
cookie.Options.SameSite = s.c.CookieSameSiteMode(ctx)
cookie.Options.Secure = s.c.CookieSecure(ctx)
if err := cookie.Save(r, w); err != nil {
return nil, errorsx.WithStack(err)
}
s.r.Logger().WithRequest(r).
WithFields(logrus.Fields{
"cookie_name": s.c.SessionCookieName(ctx),
"cookie_http_only": true,
"cookie_same_site": s.c.CookieSameSiteMode(ctx),
"cookie_secure": s.c.CookieSecure(ctx),
}).Debug("Authentication session cookie was set.")
return f, nil
}
func (s *DefaultStrategy) requestConsent(
ctx context.Context,
w http.ResponseWriter,
r *http.Request,
ar fosite.AuthorizeRequester,
f *flow.Flow,
) (err error) {
ctx, span := trace.SpanFromContext(ctx).TracerProvider().Tracer("").Start(ctx, "DefaultStrategy.requestConsent")
defer otelx.End(span, &err)
prompt := stringsx.Splitx(ar.GetRequestForm().Get("prompt"), " ")
if stringslice.Has(prompt, "consent") {
return s.forwardConsentRequest(ctx, w, r, ar, f, nil)
}
// 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
// accepted, as appropriate.
if ar.GetClient().IsPublic() {
// The OpenID Connect Test Tool fails if this returns `consent_required` when `prompt=none` is used.
// According to the quote above, it should be ok to allow https to skip consent.
//
// This is tracked as issue: https://github.com/ory/hydra/issues/866
// This is also tracked as upstream issue: https://github.com/openid-certification/oidctest/issues/97
if !(ar.GetRedirectURI().Scheme == "https" || (fosite.IsLocalhost(ar.GetRedirectURI()) && ar.GetRedirectURI().Scheme == "http")) {
return s.forwardConsentRequest(ctx, w, r, ar, f, nil)
}
}
// This breaks OIDC Conformity Tests and is probably a bit paranoid.
//
// if ar.GetResponseTypes().Has("token") {
// // We're probably requesting the implicit or hybrid flow in which case we MUST authenticate and authorize the request
// return s.forwardConsentRequest(w, r, ar, authenticationSession, nil)
// }
consentSessions, err := s.r.ConsentManager().FindGrantedAndRememberedConsentRequests(ctx, ar.GetClient().GetID(), f.Subject)
if errors.Is(err, ErrNoPreviousConsentFound) {
return s.forwardConsentRequest(ctx, w, r, ar, f, nil)
} else if err != nil {
return err
}
if found := matchScopes(s.r.Config().GetScopeStrategy(ctx), consentSessions, ar.GetRequestedScopes()); found != nil {
return s.forwardConsentRequest(ctx, w, r, ar, f, found)
}
return s.forwardConsentRequest(ctx, w, r, ar, f, nil)
}
func (s *DefaultStrategy) forwardConsentRequest(
ctx context.Context,
w http.ResponseWriter,
r *http.Request,
ar fosite.AuthorizeRequester,
f *flow.Flow,
previousConsent *flow.AcceptOAuth2ConsentRequest,
) error {
as := f.GetHandledLoginRequest()
skip := false
if previousConsent != nil {
skip = true
}
prompt := stringsx.Splitx(ar.GetRequestForm().Get("prompt"), " ")
if stringslice.Has(prompt, "none") && !skip {
return errorsx.WithStack(fosite.ErrConsentRequired.WithHint(`Prompt 'none' was requested, but no previous consent was found.`))
}
// Set up csrf/challenge/verifier values
verifier := strings.Replace(uuid.New(), "-", "", -1)
challenge := strings.Replace(uuid.New(), "-", "", -1)
csrf := strings.Replace(uuid.New(), "-", "", -1)
cl := sanitizeClientFromRequest(ar)
consentRequest := &flow.OAuth2ConsentRequest{
ID: challenge,
ACR: as.ACR,
AMR: as.AMR,
Verifier: verifier,
CSRF: csrf,
Skip: skip,
RequestedScope: []string(ar.GetRequestedScopes()),
RequestedAudience: []string(ar.GetRequestedAudience()),
Subject: as.Subject,
Client: cl,
RequestURL: as.LoginRequest.RequestURL,
AuthenticatedAt: as.AuthenticatedAt,
RequestedAt: as.RequestedAt,
ForceSubjectIdentifier: as.ForceSubjectIdentifier,
OpenIDConnectContext: as.LoginRequest.OpenIDConnectContext,
LoginSessionID: as.LoginRequest.SessionID,
LoginChallenge: sqlxx.NullString(as.LoginRequest.ID),
Context: as.Context,
}
err := s.r.ConsentManager().CreateConsentRequest(ctx, f, consentRequest)
if err != nil {
return errorsx.WithStack(err)
}
consentChallenge, err := f.ToConsentChallenge(ctx, s.r)
if err != nil {
return err
}
store, err := s.r.CookieStore(ctx)
if err != nil {
return err
}
if f.Client.GetID() != cl.GetID() {
return errorsx.WithStack(fosite.ErrInvalidClient.WithHint("The flow client id does not match the authorize request client id."))
}
clientSpecificCookieNameConsentCSRF := fmt.Sprintf("%s_%s", s.r.Config().CookieNameConsentCSRF(ctx), cl.CookieSuffix())
if err := createCsrfSession(w, r, s.r.Config(), store, clientSpecificCookieNameConsentCSRF, csrf, s.c.ConsentRequestMaxAge(ctx)); err != nil {
return errorsx.WithStack(err)
}
http.Redirect(
w, r,
urlx.SetQuery(s.c.ConsentURL(ctx), url.Values{"consent_challenge": {consentChallenge}}).String(),
http.StatusFound,
)
// generate the verifier
return errorsx.WithStack(ErrAbortOAuth2Request)
}
func (s *DefaultStrategy) verifyConsent(ctx context.Context, _ http.ResponseWriter, r *http.Request, verifier string) (_ *flow.AcceptOAuth2ConsentRequest, _ *flow.Flow, err error) {
ctx, span := trace.SpanFromContext(ctx).TracerProvider().Tracer("").Start(ctx, "DefaultStrategy.verifyConsent")
defer otelx.End(span, &err)
// We decode the flow here once again because VerifyAndInvalidateConsentRequest does not return the flow
f, err := flowctx.Decode[flow.Flow](ctx, s.r.FlowCipher(), verifier, flowctx.AsConsentVerifier)
if err != nil {
return nil, nil, errorsx.WithStack(fosite.ErrAccessDenied.WithHint("The consent verifier has already been used, has not been granted, or is invalid."))
}
if f.Client.GetID() != r.URL.Query().Get("client_id") {
return nil, nil, errorsx.WithStack(fosite.ErrInvalidClient.WithHint("The flow client id does not match the authorize request client id."))
}
session, err := s.r.ConsentManager().VerifyAndInvalidateConsentRequest(ctx, verifier)
if errors.Is(err, sqlcon.ErrUniqueViolation) {
return nil, nil, errorsx.WithStack(fosite.ErrAccessDenied.WithHint("The consent verifier has already been used."))
} else if errors.Is(err, sqlcon.ErrNoRows) {
return nil, nil, errorsx.WithStack(fosite.ErrAccessDenied.WithHint("The consent verifier has already been used, has not been granted, or is invalid."))
} else if err != nil {
return nil, nil, err
}
if session.RequestedAt.Add(s.c.ConsentRequestMaxAge(ctx)).Before(time.Now()) {
return nil, nil, errorsx.WithStack(fosite.ErrRequestUnauthorized.WithHint("The consent request has expired, please try again."))
}
if session.HasError() {
session.Error.SetDefaults(flow.ConsentRequestDeniedErrorName)
return nil, nil, errorsx.WithStack(session.Error.ToRFCError())
}
if time.Time(session.ConsentRequest.AuthenticatedAt).IsZero() {
return nil, nil, errorsx.WithStack(fosite.ErrServerError.WithHint("The authenticatedAt value was not set."))
}
store, err := s.r.CookieStore(ctx)
if err != nil {
return nil, nil, err
}
clientSpecificCookieNameConsentCSRF := fmt.Sprintf("%s_%s", s.r.Config().CookieNameConsentCSRF(ctx), session.ConsentRequest.Client.CookieSuffix())
if err := validateCsrfSession(r, s.r.Config(), store, clientSpecificCookieNameConsentCSRF, session.ConsentRequest.CSRF); err != nil {
return nil, nil, err
}
if session.Session == nil {
session.Session = flow.NewConsentRequestSessionData()
}
if session.Session.AccessToken == nil {
session.Session.AccessToken = map[string]interface{}{}
}
if session.Session.IDToken == nil {
session.Session.IDToken = map[string]interface{}{}
}
session.AuthenticatedAt = session.ConsentRequest.AuthenticatedAt
return session, f, nil
}
func (s *DefaultStrategy) generateFrontChannelLogoutURLs(ctx context.Context, subject, sid string) ([]string, error) {
clients, err := s.r.ConsentManager().ListUserAuthenticatedClientsWithFrontChannelLogout(ctx, subject, sid)
if err != nil {
return nil, err
}
var urls []string
for _, c := range clients {
u, err := url.Parse(c.FrontChannelLogoutURI)
if err != nil {
return nil, errorsx.WithStack(fosite.ErrServerError.WithHintf("Unable to parse frontchannel_logout_uri because %s.", c.FrontChannelLogoutURI).WithDebug(err.Error()))
}
urls = append(urls, urlx.SetQuery(u, url.Values{
"iss": {s.c.IssuerURL(ctx).String()},
"sid": {sid},
}).String())
}
return urls, nil
}
func (s *DefaultStrategy) executeBackChannelLogout(r *http.Request, subject, sid string) error {
ctx := r.Context()
clients, err := s.r.ConsentManager().ListUserAuthenticatedClientsWithBackChannelLogout(ctx, subject, sid)
if err != nil {
return err
}
openIDKeyID, err := s.r.OpenIDJWTStrategy().GetPublicKeyID(ctx)
if err != nil {
return err
}
type task struct {
url string
token string
clientID string
}
var tasks []task
for _, c := range clients {
// Getting the forced obfuscated login session is tricky because the user id could be obfuscated with a new
// ID every time the algorithm is used. Thus, we would only get the most recent version. It therefore makes
// sense to just use the sid.
//
// s.r.ConsentManager().GetForcedObfuscatedLoginSession(context.Background(), subject, <missing>)
// sub := s.obfuscateSubjectIdentifier(c, subject, )
t, _, err := s.r.OpenIDJWTStrategy().Generate(ctx, jwt.MapClaims{
"iss": s.c.IssuerURL(ctx).String(),
"aud": []string{c.ID},
"iat": time.Now().UTC().Unix(),
"jti": uuid.New(),
"events": map[string]struct{}{"http://schemas.openid.net/event/backchannel-logout": {}},
"sid": sid,
}, &jwt.Headers{
Extra: map[string]interface{}{"kid": openIDKeyID},
})
if err != nil {
return err
}
tasks = append(tasks, task{url: c.BackChannelLogoutURI, clientID: c.GetID(), token: t})
}
span := trace.SpanFromContext(ctx)
cl := s.r.HTTPClient(ctx)
execute := func(t task) {
log := s.r.Logger().WithRequest(r).
WithField("client_id", t.clientID).
WithField("backchannel_logout_url", t.url)
body := url.Values{"logout_token": {t.token}}.Encode()
req, err := retryablehttp.NewRequestWithContext(trace.ContextWithSpan(context.Background(), span), "POST", t.url, []byte(body))
if err != nil {
log.WithError(err).Error("Unable to construct OpenID Connect Back-Channel Logout Request")
return
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
res, err := cl.Do(req)
if err != nil {
log.WithError(err).Error("Unable to execute OpenID Connect Back-Channel Logout Request")
return
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
log.WithError(errors.Errorf("expected HTTP status code %d but got %d", http.StatusOK, res.StatusCode)).
Error("Unable to execute OpenID Connect Back-Channel Logout Request")
return
} else {
log.Info("Back-Channel Logout Request")
}
}
for _, t := range tasks {
go execute(t)
}
return nil
}
func (s *DefaultStrategy) issueLogoutVerifier(ctx context.Context, w http.ResponseWriter, r *http.Request) (*flow.LogoutResult, error) {
// There are two types of log out flows:
//
// - RP initiated logout
// - OP initiated logout
// Per default, we're redirecting to the global redirect URL. This is assuming that we're not an RP-initiated
// logout flow.
redir := s.c.LogoutRedirectURL(ctx).String()
if err := r.ParseForm(); err != nil {
return nil, errorsx.WithStack(fosite.ErrInvalidRequest.
WithHintf("Logout failed because the '%s' request could not be parsed.", r.Method),
)
}
hint := r.Form.Get("id_token_hint")
state := r.Form.Get("state")
requestedRedir := r.Form.Get("post_logout_redirect_uri")
if len(hint) == 0 {
// hint is not set, so this is an OP initiated logout
if len(state) > 0 {
// state can only be set if it's an RP-initiated logout flow. If not, we should throw an error.
return nil, errorsx.WithStack(fosite.ErrInvalidRequest.WithHint("Logout failed because query parameter state is set but id_token_hint is missing."))
}
if len(requestedRedir) > 0 {
// post_logout_redirect_uri can only be set if it's an RP-initiated logout flow. If not, we should throw an error.
return nil, errorsx.WithStack(fosite.ErrInvalidRequest.WithHint("Logout failed because query parameter post_logout_redirect_uri is set but id_token_hint is missing."))
}
session, err := s.authenticationSession(ctx, w, r)
if errors.Is(err, ErrNoAuthenticationSessionFound) {
// OP initiated log out but no session was found. Since we can not identify the user we can not call
// any RPs.
s.r.AuditLogger().
WithRequest(r).
Info("User logout skipped because no authentication session exists.")
http.Redirect(w, r, redir, http.StatusFound)
return nil, errorsx.WithStack(ErrAbortOAuth2Request)
} else if err != nil {
return nil, err
}
challenge := uuid.New()
if err := s.r.ConsentManager().CreateLogoutRequest(r.Context(), &flow.LogoutRequest{
RequestURL: r.URL.String(),
ID: challenge,
Subject: session.Subject,
SessionID: session.ID,
Verifier: uuid.New(),
RPInitiated: false,
// PostLogoutRedirectURI is set to the value from config.Provider().LogoutRedirectURL()
PostLogoutRedirectURI: redir,
}); err != nil {
return nil, err
}
s.r.AuditLogger().
WithRequest(r).
Info("User logout requires user confirmation, redirecting to Logout UI.")
http.Redirect(w, r, urlx.SetQuery(s.c.LogoutURL(ctx), url.Values{"logout_challenge": {challenge}}).String(), http.StatusFound)
return nil, errorsx.WithStack(ErrAbortOAuth2Request)
}
claims, err := s.getIDTokenHintClaims(r.Context(), hint)
if err != nil {
return nil, err
}
mksi := mapx.KeyStringToInterface(claims)
if !claims.VerifyIssuer(s.c.IssuerURL(ctx).String(), true) {
return nil, errorsx.WithStack(fosite.ErrInvalidRequest.
WithHintf(
`Logout failed because issuer claim value '%s' from query parameter id_token_hint does not match with issuer value from configuration '%s'.`,
mapx.GetStringDefault(mksi, "iss", ""),
s.c.IssuerURL(ctx).String(),
),
)
}
now := time.Now().UTC().Unix()
if !claims.VerifyIssuedAt(now, true) {
return nil, errorsx.WithStack(fosite.ErrInvalidRequest.
WithHintf(
`Logout failed because iat claim value '%.0f' from query parameter id_token_hint is before now ('%d').`,
mapx.GetFloat64Default(mksi, "iat", float64(0)),
now,
),
)
}
hintSid := mapx.GetStringDefault(mksi, "sid", "")
if len(hintSid) == 0 {
return nil, errorsx.WithStack(fosite.ErrInvalidRequest.WithHint("Logout failed because query parameter id_token_hint is missing sid claim."))
}
// It doesn't really make sense to use the subject value from the ID Token because it might be obfuscated.
if hintSub := mapx.GetStringDefault(mksi, "sub", ""); len(hintSub) == 0 {
return nil, errorsx.WithStack(fosite.ErrInvalidRequest.WithHint("Logout failed because query parameter id_token_hint is missing sub claim."))
}
// Let's find the client by cycling through the audiences. Typically, we only have one audience
var cl *client.Client
for _, aud := range mapx.GetStringSliceDefault(
mksi,
"aud",
[]string{
mapx.GetStringDefault(mksi, "aud", ""),
},
) {
c, err := s.r.ClientManager().GetConcreteClient(r.Context(), aud)
if errors.Is(err, x.ErrNotFound) {
continue
} else if err != nil {
return nil, err
}
cl = c
break
}
if cl == nil {
return nil, errorsx.WithStack(fosite.ErrInvalidRequest.
WithHint("Logout failed because none of the listed audiences is a registered OAuth 2.0 Client."))
}
if len(requestedRedir) > 0 {
var f *url.URL
for _, w := range cl.PostLogoutRedirectURIs {
if w == requestedRedir {
u, err := url.Parse(w)
if err != nil {
return nil, errorsx.WithStack(fosite.ErrServerError.WithHintf("Unable to parse post_logout_redirect_uri '%s'.", w).WithDebug(err.Error()))
}
f = u
}
}
if f == nil {
return nil, errorsx.WithStack(fosite.ErrInvalidRequest.
WithHint("Logout failed because query parameter post_logout_redirect_uri is not a whitelisted as a post_logout_redirect_uri for the client."),
)
}
params := url.Values{}
if state != "" {
params.Add("state", state)
}
redir = urlx.SetQuery(f, params).String()
}
// We do not really want to verify if the user (from id token hint) has a session here because it doesn't really matter.
// Instead, we'll check this when we're actually revoking the cookie!
session, err := s.r.ConsentManager().GetRememberedLoginSession(r.Context(), nil, hintSid)
if errors.Is(err, x.ErrNotFound) {
// Such a session does not exist - maybe it has already been revoked? In any case, we can't do much except
// leaning back and redirecting back.
http.Redirect(w, r, redir, http.StatusFound)
return nil, errorsx.WithStack(ErrAbortOAuth2Request)
} else if err != nil {
return nil, err
}
challenge := uuid.New()
if err := s.r.ConsentManager().CreateLogoutRequest(r.Context(), &flow.LogoutRequest{
RequestURL: r.URL.String(),
ID: challenge,
SessionID: hintSid,
Subject: session.Subject,
Verifier: uuid.New(),
Client: cl,
RPInitiated: true,
// PostLogoutRedirectURI is set to the value from config.Provider().LogoutRedirectURL()
PostLogoutRedirectURI: redir,
}); err != nil {
return nil, err
}
http.Redirect(w, r, urlx.SetQuery(s.c.LogoutURL(ctx), url.Values{"logout_challenge": {challenge}}).String(), http.StatusFound)
return nil, errorsx.WithStack(ErrAbortOAuth2Request)
}
func (s *DefaultStrategy) performBackChannelLogoutAndDeleteSession(r *http.Request, subject string, sid string) error {
ctx := r.Context()
if err := s.executeBackChannelLogout(r, subject, sid); err != nil {