forked from grantzvolsky/hydra
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstrategy_default.go
522 lines (447 loc) · 19 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
/*
* Copyright © 2015-2018 Aeneas Rekkas <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @author Aeneas Rekkas <[email protected]>
* @Copyright 2017-2018 Aeneas Rekkas <[email protected]>
* @license Apache-2.0
*/
package consent
import (
"net/http"
"net/url"
"strconv"
"strings"
"time"
jwtgo "github.com/dgrijalva/jwt-go"
"github.com/gorilla/sessions"
"github.com/ory/fosite"
"github.com/ory/fosite/handler/openid"
"github.com/ory/fosite/token/jwt"
"github.com/ory/go-convenience/mapx"
"github.com/ory/go-convenience/stringslice"
"github.com/ory/go-convenience/stringsx"
"github.com/ory/go-convenience/urlx"
"github.com/ory/hydra/pkg"
"github.com/ory/sqlcon"
"github.com/pborman/uuid"
"github.com/pkg/errors"
)
const (
cookieAuthenticationName = "oauth2_authentication_session"
cookieAuthenticationSIDName = "sid"
cookieAuthenticationCSRFName = "oauth2_authentication_csrf"
cookieConsentCSRFName = "oauth2_consent_csrf"
)
type DefaultStrategy struct {
AuthenticationURL string
ConsentURL string
IssuerURL string
OAuth2AuthURL string
M Manager
CookieStore sessions.Store
ScopeStrategy fosite.ScopeStrategy
RunsHTTPS bool
RequestMaxAge time.Duration
JWTStrategy jwt.JWTStrategy
OpenIDConnectRequestValidator *openid.OpenIDConnectRequestValidator
}
func NewStrategy(
authenticationURL string,
consentURL string,
issuerURL string,
oAuth2AuthURL string,
m Manager,
cookieStore sessions.Store,
scopeStrategy fosite.ScopeStrategy,
runsHTTPS bool,
requestMaxAge time.Duration,
jwtStrategy jwt.JWTStrategy,
openIDConnectRequestValidator *openid.OpenIDConnectRequestValidator,
) *DefaultStrategy {
return &DefaultStrategy{
AuthenticationURL: authenticationURL,
ConsentURL: consentURL,
IssuerURL: issuerURL,
OAuth2AuthURL: oAuth2AuthURL,
M: m,
CookieStore: cookieStore,
ScopeStrategy: scopeStrategy,
RunsHTTPS: runsHTTPS,
RequestMaxAge: requestMaxAge,
JWTStrategy: jwtStrategy,
OpenIDConnectRequestValidator: openIDConnectRequestValidator,
}
}
var ErrAbortOAuth2Request = errors.New("The OAuth 2.0 Authorization request must be aborted")
var errNoPreviousConsentFound = errors.New("No previous OAuth 2.0 Consent could be found for this access request")
func (s *DefaultStrategy) requestAuthentication(w http.ResponseWriter, r *http.Request, ar fosite.AuthorizeRequester) error {
prompt := stringsx.Splitx(ar.GetRequestForm().Get("prompt"), " ")
if stringslice.Has(prompt, "login") {
return s.forwardAuthenticationRequest(w, r, ar, "", time.Time{})
}
// We try to open the session cookie. If it does not exist (indicated by the error), we must authenticate the user.
cookie, err := s.CookieStore.Get(r, cookieAuthenticationName)
if err != nil {
//id.L.WithError(err).Debug("No OAuth2 authentication session was found, performing consent authentication flow")
return s.forwardAuthenticationRequest(w, r, ar, "", time.Time{})
}
sessionID := mapx.GetStringDefault(cookie.Values, cookieAuthenticationSIDName, "")
if sessionID == "" {
return s.forwardAuthenticationRequest(w, r, ar, "", time.Time{})
}
session, err := s.M.GetAuthenticationSession(sessionID)
if errors.Cause(err) == sqlcon.ErrNoRows {
return s.forwardAuthenticationRequest(w, r, ar, "", time.Time{})
} else if err != nil {
return err
}
maxAge := int64(0)
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 > 0 && session.AuthenticatedAt.UTC().Add(time.Second*time.Duration(maxAge)).Before(time.Now().UTC()) {
if stringslice.Has(prompt, "none") {
return errors.WithStack(fosite.ErrLoginRequired.WithDebug("Request failed because prompt is set to \"none\" and authentication time reached max_age"))
}
return s.forwardAuthenticationRequest(w, r, ar, "", time.Time{})
}
idTokenHint := ar.GetRequestForm().Get("id_token_hint")
if idTokenHint == "" {
return s.forwardAuthenticationRequest(w, r, ar, session.Subject, session.AuthenticatedAt)
}
token, err := s.JWTStrategy.Decode(idTokenHint)
if err != nil {
return err
}
if hintClaims, ok := token.Claims.(jwtgo.MapClaims); !ok {
return errors.WithStack(fosite.ErrInvalidRequest.WithDebug("Failed to validate OpenID Connect request as decoding id token from id_token_hint to *jwt.StandardClaims failed"))
} else if hintSub, _ := hintClaims["sub"].(string); hintSub == "" {
return errors.WithStack(fosite.ErrInvalidRequest.WithDebug("Failed to validate OpenID Connect request because provided id token from id_token_hint does not have a subject"))
} else if hintSub != session.Subject {
return errors.WithStack(fosite.ErrLoginRequired.WithDebug("Request failed because subject claim from id_token_hint does not match subject from authentication session"))
} else {
return s.forwardAuthenticationRequest(w, r, ar, session.Subject, session.AuthenticatedAt)
}
}
func (s *DefaultStrategy) forwardAuthenticationRequest(w http.ResponseWriter, r *http.Request, ar fosite.AuthorizeRequester, subject string, authenticatedAt time.Time) error {
if (subject != "" && authenticatedAt.IsZero()) || (subject == "" && !authenticatedAt.IsZero()) {
return errors.WithStack(fosite.ErrServerError.WithDebug("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'id 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 errors.WithStack(fosite.ErrLoginRequired.WithDebug(`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, err := url.Parse(s.IssuerURL)
if err != nil {
return errors.WithStack(err)
}
iu = urlx.AppendPaths(iu, s.OAuth2AuthURL)
iu.RawQuery = r.URL.RawQuery
var idTokenHintClaims jwtgo.MapClaims
if idTokenHint := ar.GetRequestForm().Get("id_token_hint"); len(idTokenHint) > 0 {
if token, err := s.JWTStrategy.Decode(idTokenHint); err == nil {
if hintClaims, ok := token.Claims.(jwtgo.MapClaims); ok {
idTokenHintClaims = hintClaims
}
}
}
// Set the session
if err := s.M.CreateAuthenticationRequest(
&AuthenticationRequest{
Challenge: challenge,
Verifier: verifier,
CSRF: csrf,
Skip: skip,
RequestedScope: []string(ar.GetRequestedScopes()),
Subject: subject,
Client: sanitizeClientFromRequest(ar),
RequestURL: iu.String(),
AuthenticatedAt: authenticatedAt,
RequestedAt: time.Now().UTC(),
OpenIDConnectContext: &OpenIDConnectContext{
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"),
},
},
); err != nil {
return errors.WithStack(err)
}
if err := createCsrfSession(w, r, s.CookieStore, cookieAuthenticationCSRFName, csrf, s.RunsHTTPS); err != nil {
return errors.WithStack(err)
}
au, err := url.Parse(s.AuthenticationURL)
if err != nil {
return errors.WithStack(err)
}
q := au.Query()
q.Set("login_challenge", challenge)
au.RawQuery = q.Encode()
http.Redirect(w, r, au.String(), http.StatusFound)
// generate the verifier
return errors.WithStack(ErrAbortOAuth2Request)
}
func (s *DefaultStrategy) revokeAuthenticationSession(w http.ResponseWriter, r *http.Request) error {
cookie, _ := s.CookieStore.Get(r, cookieAuthenticationName)
sid, _ := mapx.GetString(cookie.Values, cookieAuthenticationSIDName)
cookie.Options.MaxAge = -1
cookie.Values[cookieAuthenticationSIDName] = ""
if err := cookie.Save(r, w); err != nil {
return errors.WithStack(err)
}
if sid == "" {
return nil
}
return s.M.DeleteAuthenticationSession(sid)
}
func (s *DefaultStrategy) verifyAuthentication(w http.ResponseWriter, r *http.Request, req fosite.AuthorizeRequester, verifier string) (*HandledAuthenticationRequest, error) {
session, err := s.M.VerifyAndInvalidateAuthenticationRequest(verifier)
if errors.Cause(err) == pkg.ErrNotFound {
return nil, errors.WithStack(fosite.ErrAccessDenied.WithDebug("The login verifier has already been used, has not been granted, or is invalid."))
} else if err != nil {
return nil, err
}
if session.Error != nil {
return nil, errors.WithStack(session.Error.toRFCError())
}
if session.RequestedAt.Add(s.RequestMaxAge).Before(time.Now()) {
return nil, errors.WithStack(fosite.ErrRequestUnauthorized.WithDebug("The login request has expired, please try again."))
}
if err := validateCsrfSession(r, s.CookieStore, cookieAuthenticationCSRFName, session.AuthenticationRequest.CSRF); err != nil {
return nil, err
}
if session.AuthenticationRequest.Skip && session.Remember {
return nil, errors.WithStack(fosite.ErrServerError.WithDebug("The login request is marked as remember, but is also marked as skipped - only one of the values can be true."))
}
if session.AuthenticationRequest.Skip && session.Subject != session.AuthenticationRequest.Subject {
// Revoke the session because there's clearly a mix up wrt the subject that's being authenticated
if err := s.revokeAuthenticationSession(w, r); err != nil {
return nil, err
}
return nil, errors.WithStack(fosite.ErrServerError.WithDebug("The login request is marked as remember, but the subject from the login confirmation does not match the original subject from the cookie."))
}
if err := s.OpenIDConnectRequestValidator.ValidatePrompt(&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(),
Scopes: req.GetRequestedScopes(),
GrantedScopes: req.GetGrantedScopes(),
Form: req.GetRequestForm(),
Session: &openid.DefaultSession{
Claims: &jwt.IDTokenClaims{
Subject: session.Subject,
IssuedAt: time.Now().UTC(), // doesn't matter
ExpiresAt: time.Now().Add(time.Hour).UTC(), // doesn't matter
AuthTime: session.AuthenticatedAt,
RequestedAt: session.RequestedAt,
},
Headers: &jwt.Headers{},
Subject: session.Subject,
},
},
}); errors.Cause(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(w, r); err != nil {
return nil, err
}
return nil, err
} else if err != nil {
return nil, err
}
if !session.Remember {
if !session.AuthenticationRequest.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(w, r); err != nil {
return nil, err
}
}
return session, nil
}
cookie, _ := s.CookieStore.Get(r, cookieAuthenticationName)
sid := uuid.New()
if err := s.M.CreateAuthenticationSession(&AuthenticationSession{
ID: sid,
Subject: session.Subject,
AuthenticatedAt: session.AuthenticatedAt,
}); err != nil {
return nil, err
}
cookie.Values[cookieAuthenticationSIDName] = sid
if session.RememberFor > 0 {
cookie.Options.MaxAge = session.RememberFor
}
cookie.Options.HttpOnly = true
if s.RunsHTTPS {
cookie.Options.Secure = true
}
if err := cookie.Save(r, w); err != nil {
return nil, errors.WithStack(err)
}
return session, nil
}
func (s *DefaultStrategy) requestConsent(w http.ResponseWriter, r *http.Request, ar fosite.AuthorizeRequester, authenticationSession *HandledAuthenticationRequest) error {
prompt := stringsx.Splitx(ar.GetRequestForm().Get("prompt"), " ")
if stringslice.Has(prompt, "consent") {
return s.forwardConsentRequest(w, r, ar, authenticationSession, 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" {
return s.forwardConsentRequest(w, r, ar, authenticationSession, 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.M.FindPreviouslyGrantedConsentRequests(ar.GetClient().GetID(), authenticationSession.Subject)
if errors.Cause(err) == errNoPreviousConsentFound {
return s.forwardConsentRequest(w, r, ar, authenticationSession, nil)
} else if err != nil {
return err
}
if found := matchScopes(s.ScopeStrategy, consentSessions, ar.GetRequestedScopes()); found != nil {
return s.forwardConsentRequest(w, r, ar, authenticationSession, found)
}
return s.forwardConsentRequest(w, r, ar, authenticationSession, nil)
}
func (s *DefaultStrategy) forwardConsentRequest(w http.ResponseWriter, r *http.Request, ar fosite.AuthorizeRequester, as *HandledAuthenticationRequest, cs *HandledConsentRequest) error {
skip := false
if cs != nil {
skip = true
}
prompt := stringsx.Splitx(ar.GetRequestForm().Get("prompt"), " ")
if stringslice.Has(prompt, "none") && !skip {
return errors.WithStack(fosite.ErrConsentRequired.WithDebug(`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)
if err := s.M.CreateConsentRequest(
&ConsentRequest{
Challenge: challenge,
Verifier: verifier,
CSRF: csrf,
Skip: skip,
RequestedScope: []string(ar.GetRequestedScopes()),
Subject: as.Subject,
Client: sanitizeClientFromRequest(ar),
RequestURL: as.AuthenticationRequest.RequestURL,
AuthenticatedAt: as.AuthenticatedAt,
RequestedAt: as.RequestedAt,
OpenIDConnectContext: as.AuthenticationRequest.OpenIDConnectContext,
},
); err != nil {
return errors.WithStack(err)
}
cu, err := url.Parse(s.ConsentURL)
if err != nil {
return errors.WithStack(err)
}
if err := createCsrfSession(w, r, s.CookieStore, cookieConsentCSRFName, csrf, s.RunsHTTPS); err != nil {
return errors.WithStack(err)
}
q := cu.Query()
q.Set("consent_challenge", challenge)
cu.RawQuery = q.Encode()
http.Redirect(w, r, cu.String(), http.StatusFound)
// generate the verifier
return errors.WithStack(ErrAbortOAuth2Request)
}
func (s *DefaultStrategy) verifyConsent(w http.ResponseWriter, r *http.Request, req fosite.AuthorizeRequester, verifier string) (*HandledConsentRequest, error) {
session, err := s.M.VerifyAndInvalidateConsentRequest(verifier)
if errors.Cause(err) == pkg.ErrNotFound {
return nil, errors.WithStack(fosite.ErrAccessDenied.WithDebug("The consent verifier has already been used, has not been granted, or is invalid."))
} else if err != nil {
return nil, err
}
if session.RequestedAt.Add(s.RequestMaxAge).Before(time.Now()) {
return nil, errors.WithStack(fosite.ErrRequestUnauthorized.WithDebug("The consent request has expired, please try again."))
}
if session.Error != nil {
return nil, errors.WithStack(session.Error.toRFCError())
}
if session.ConsentRequest.AuthenticatedAt.IsZero() {
return nil, errors.WithStack(fosite.ErrServerError.WithDebug("The authenticatedAt value was not set."))
}
if err := validateCsrfSession(r, s.CookieStore, cookieConsentCSRFName, session.ConsentRequest.CSRF); err != nil {
return nil, err
}
session.AuthenticatedAt = session.ConsentRequest.AuthenticatedAt
return session, nil
}
func (s *DefaultStrategy) HandleOAuth2AuthorizationRequest(w http.ResponseWriter, r *http.Request, req fosite.AuthorizeRequester) (*HandledConsentRequest, error) {
authenticationVerifier := strings.TrimSpace(req.GetRequestForm().Get("login_verifier"))
consentVerifier := strings.TrimSpace(req.GetRequestForm().Get("consent_verifier"))
if authenticationVerifier == "" && consentVerifier == "" {
// ok, we need to process this request and redirect to auth endpoint
return nil, s.requestAuthentication(w, r, req)
} else if authenticationVerifier != "" {
authSession, err := s.verifyAuthentication(w, r, req, authenticationVerifier)
if err != nil {
return nil, err
}
// ok, we need to process this request and redirect to auth endpoint
return nil, s.requestConsent(w, r, req, authSession)
}
consentSession, err := s.verifyConsent(w, r, req, consentVerifier)
if err != nil {
return nil, err
}
return consentSession, nil
}