forked from openshift/osin
-
Notifications
You must be signed in to change notification settings - Fork 3
/
access.go
618 lines (526 loc) · 18 KB
/
access.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
package osin
import (
"context"
"crypto/sha256"
"encoding/base64"
"errors"
"net/http"
"strings"
"time"
)
// AccessRequestType is the type for OAuth param `grant_type`
type AccessRequestType string
const (
AUTHORIZATION_CODE AccessRequestType = "authorization_code"
REFRESH_TOKEN AccessRequestType = "refresh_token"
PASSWORD AccessRequestType = "password"
CLIENT_CREDENTIALS AccessRequestType = "client_credentials"
ASSERTION AccessRequestType = "assertion"
IMPLICIT AccessRequestType = "__implicit"
EXTENSION AccessRequestType = "extension"
)
// AccessRequest is a request for access tokens
type AccessRequest struct {
Type AccessRequestType
Code string
Client Client
AuthorizeData *AuthorizeData
AccessData *AccessData
// Force finish to use this access data, to allow access data reuse
ForceAccessData *AccessData
RedirectUri string
Scope string
Username string
Password string
AssertionType string
Assertion string
Extension interface{}
// Set if request is authorized
Authorized bool
// Token expiration in seconds. Change if different from default
Expiration int32
// Set if a refresh token should be generated
GenerateRefresh bool
// Data to be passed to storage. Not used by the library.
UserData interface{}
// HttpRequest *http.Request for special use
HttpRequest *http.Request
// Optional code_verifier as described in rfc7636
CodeVerifier string
}
// AccessData represents an access grant (tokens, expiration, client, etc)
type AccessData struct {
// Client information
Client Client
// Authorize data, for authorization code
AuthorizeData *AuthorizeData
// Previous access data, for refresh token
AccessData *AccessData
// Access token
AccessToken string
// Refresh Token. Can be blank
RefreshToken string
// Token expiration in seconds
ExpiresIn int32
// Requested scope
Scope string
// Redirect Uri from request
RedirectUri string
// Date created
CreatedAt time.Time
// Data to be passed to storage. Not used by the library.
UserData interface{}
// ID Identifier for user token
UserID int64
}
// IsExpired returns true if access expired
func (d *AccessData) IsExpired() bool {
return d.IsExpiredAt(time.Now())
}
// IsExpiredAt returns true if access expires at time 't'
func (d *AccessData) IsExpiredAt(t time.Time) bool {
return d.ExpireAt().Before(t)
}
// ExpireAt returns the expiration date
func (d *AccessData) ExpireAt() time.Time {
return d.CreatedAt.Add(time.Duration(d.ExpiresIn) * time.Second)
}
// AccessTokenGen generates access tokens
type AccessTokenGen interface {
GenerateAccessToken(data *AccessData, generaterefresh bool) (accesstoken string, refreshtoken string, err error)
}
// HandleAccessRequest is the http.HandlerFunc for handling access token requests
func (s *Server) HandleAccessRequest(w *Response, r *http.Request) *AccessRequest {
// Only allow GET or POST
if r.Method == "GET" {
if !s.Config.AllowGetAccessRequest {
s.setErrorAndLog(w, E_INVALID_REQUEST, errors.New("Request must be POST"), "access_request=%s", "GET request not allowed")
return nil
}
} else if r.Method != "POST" {
s.setErrorAndLog(w, E_INVALID_REQUEST, errors.New("Request must be POST"), "access_request=%s", "request must be POST")
return nil
}
err := r.ParseForm()
if err != nil {
s.setErrorAndLog(w, E_INVALID_REQUEST, err, "access_request=%s", "parsing error")
return nil
}
grantType := AccessRequestType(r.Form.Get("grant_type"))
if s.Config.AllowedAccessTypes.Exists(grantType) {
switch grantType {
case AUTHORIZATION_CODE:
return s.handleAuthorizationCodeRequest(w, r)
case REFRESH_TOKEN:
return s.handleRefreshTokenRequest(w, r)
case PASSWORD:
return s.handlePasswordRequest(w, r)
case CLIENT_CREDENTIALS:
return s.handleClientCredentialsRequest(w, r)
case ASSERTION:
return s.handleAssertionRequest(w, r)
case EXTENSION:
return s.handleExtensionRequest(w, r)
}
}
s.setErrorAndLog(w, E_UNSUPPORTED_GRANT_TYPE, nil, "access_request=%s", "unknown grant type")
return nil
}
func (s *Server) handleAuthorizationCodeRequest(w *Response, r *http.Request) *AccessRequest {
// get client authentication
ctx := r.Context()
auth := s.getClientAuth(w, r, s.Config.AllowClientSecretInParams)
if auth == nil {
return nil
}
// generate access token
ret := &AccessRequest{
Type: AUTHORIZATION_CODE,
Code: r.Form.Get("code"),
CodeVerifier: r.Form.Get("code_verifier"),
RedirectUri: r.Form.Get("redirect_uri"),
GenerateRefresh: true,
Expiration: s.Config.AccessExpiration,
HttpRequest: r,
}
// "code" is required
if ret.Code == "" {
s.setErrorAndLog(w, E_INVALID_GRANT, nil, "auth_code_request=%s", "code is required")
return nil
}
// must have a valid client
if ret.Client = s.getClient(ctx, auth, w.Storage, w); ret.Client == nil {
return nil
}
// must be a valid authorization code
var err error
ret.AuthorizeData, err = w.Storage.LoadAuthorize(ctx, ret.Code)
if err != nil {
s.setErrorAndLog(w, E_INVALID_GRANT, err, "auth_code_request=%s", "error loading authorize data")
return nil
}
if ret.AuthorizeData == nil {
s.setErrorAndLog(w, E_UNAUTHORIZED_CLIENT, nil, "auth_code_request=%s", "authorization data is nil")
return nil
}
if ret.AuthorizeData.Client == nil {
s.setErrorAndLog(w, E_UNAUTHORIZED_CLIENT, nil, "auth_code_request=%s", "authorization client is nil")
return nil
}
if ret.AuthorizeData.Client.GetRedirectUri() == "" {
s.setErrorAndLog(w, E_UNAUTHORIZED_CLIENT, nil, "auth_code_request=%s", "client redirect uri is empty")
return nil
}
if ret.AuthorizeData.IsExpiredAt(s.Now()) {
s.setErrorAndLog(w, E_INVALID_GRANT, nil, "auth_code_request=%s", "authorization data is expired")
return nil
}
// code must be from the client
if ret.AuthorizeData.Client.GetId() != ret.Client.GetId() {
s.setErrorAndLog(w, E_INVALID_GRANT, nil, "auth_code_request=%s", "client code does not match")
return nil
}
// check redirect uri
if ret.RedirectUri == "" {
ret.RedirectUri = FirstUri(ret.Client.GetRedirectUri(), s.Config.RedirectUriSeparator)
}
if err = ValidateUriList(ret.Client.GetRedirectUri(), ret.RedirectUri, s.Config.RedirectUriSeparator); err != nil {
s.setErrorAndLog(w, E_INVALID_REQUEST, err, "auth_code_request=%s", "error validating client redirect")
return nil
}
if ret.AuthorizeData.RedirectUri != ret.RedirectUri {
s.setErrorAndLog(w, E_INVALID_REQUEST, errors.New("Redirect uri is different"), "auth_code_request=%s", "client redirect does not match authorization data")
return nil
}
// Verify PKCE, if present in the authorization data
if len(ret.AuthorizeData.CodeChallenge) > 0 {
// https://tools.ietf.org/html/rfc7636#section-4.1
if matched := pkceMatcher.MatchString(ret.CodeVerifier); !matched {
s.setErrorAndLog(w, E_INVALID_REQUEST, errors.New("code_verifier has invalid format"),
"auth_code_request=%s", "pkce code challenge verifier does not match")
return nil
}
// https: //tools.ietf.org/html/rfc7636#section-4.6
codeVerifier := ""
switch ret.AuthorizeData.CodeChallengeMethod {
case "", PKCE_PLAIN:
codeVerifier = ret.CodeVerifier
case PKCE_S256:
hash := sha256.Sum256([]byte(ret.CodeVerifier))
codeVerifier = base64.RawURLEncoding.EncodeToString(hash[:])
default:
s.setErrorAndLog(w, E_INVALID_REQUEST, nil,
"auth_code_request=%s", "pkce transform algorithm not supported (rfc7636)")
return nil
}
// This is hacky way to fix android webview sending hashed codeVerifier value.
// We compare stored codeChallenge to both plain and hashed codeVerifier.
if codeVerifier != ret.AuthorizeData.CodeChallenge && ret.CodeVerifier != ret.AuthorizeData.CodeChallenge {
s.setErrorAndLog(w, E_INVALID_GRANT, errors.New("code_verifier failed comparison with code_challenge"),
"auth_code_request=%s request:%s saved_challenge:%s", "pkce code verifier does not match challenge", ret.CodeVerifier, ret.AuthorizeData.CodeChallenge)
return nil
}
}
// set rest of data
ret.Scope = ret.AuthorizeData.Scope
ret.UserData = ret.AuthorizeData.UserData
return ret
}
func extraScopes(access_scopes, refresh_scopes string) bool {
access_scopes_list := strings.Split(access_scopes, " ")
refresh_scopes_list := strings.Split(refresh_scopes, " ")
access_map := make(map[string]int)
for _, scope := range access_scopes_list {
if scope == "" {
continue
}
access_map[scope] = 1
}
for _, scope := range refresh_scopes_list {
if scope == "" {
continue
}
if _, ok := access_map[scope]; !ok {
return true
}
}
return false
}
func (s *Server) handleRefreshTokenRequest(w *Response, r *http.Request) *AccessRequest {
// get client authentication
ctx := r.Context()
auth := s.getClientAuth(w, r, s.Config.AllowClientSecretInParams)
if auth == nil {
return nil
}
// generate access token
ret := &AccessRequest{
Type: REFRESH_TOKEN,
Code: r.Form.Get("refresh_token"),
Scope: r.Form.Get("scope"),
GenerateRefresh: true,
Expiration: s.Config.AccessExpiration,
HttpRequest: r,
}
// "refresh_token" is required
if ret.Code == "" {
s.setErrorAndLog(w, E_INVALID_GRANT, nil, "refresh_token=%s", "refresh_token is required")
return nil
}
// must have a valid client
if ret.Client = s.getClient(ctx, auth, w.Storage, w); ret.Client == nil {
return nil
}
// must be a valid refresh code
var err error
ret.AccessData, err = w.Storage.LoadRefresh(ctx, ret.Code)
if err != nil {
s.setErrorAndLog(w, E_INVALID_GRANT, err, "refresh_token=%s", "error loading access data")
return nil
}
if ret.AccessData == nil {
s.setErrorAndLog(w, E_UNAUTHORIZED_CLIENT, nil, "refresh_token=%s", "access data is nil")
return nil
}
if ret.AccessData.Client == nil {
s.setErrorAndLog(w, E_UNAUTHORIZED_CLIENT, nil, "refresh_token=%s", "access data client is nil")
return nil
}
if ret.AccessData.Client.GetRedirectUri() == "" {
s.setErrorAndLog(w, E_UNAUTHORIZED_CLIENT, nil, "refresh_token=%s", "access data client redirect uri is empty")
return nil
}
// client must be the same as the previous token
if ret.AccessData.Client.GetId() != ret.Client.GetId() {
s.setErrorAndLog(w, E_INVALID_CLIENT, errors.New("Client id must be the same from previous token"), "refresh_token=%s, current=%v, previous=%v", "client mismatch", ret.Client.GetId(), ret.AccessData.Client.GetId())
return nil
}
// set rest of data
ret.RedirectUri = ret.AccessData.RedirectUri
ret.UserData = ret.AccessData.UserData
if ret.Scope == "" {
ret.Scope = ret.AccessData.Scope
}
if extraScopes(ret.AccessData.Scope, ret.Scope) {
msg := "the requested scope must not include any scope not originally granted by the resource owner"
s.setErrorAndLog(w, E_ACCESS_DENIED, errors.New(msg), "refresh_token=%s", msg)
return nil
}
return ret
}
func (s *Server) handlePasswordRequest(w *Response, r *http.Request) *AccessRequest {
// get client authentication
ctx := r.Context()
auth := s.getClientAuth(w, r, s.Config.AllowClientSecretInParams)
if auth == nil {
return nil
}
// generate access token
ret := &AccessRequest{
Type: PASSWORD,
Username: r.Form.Get("username"),
Password: r.Form.Get("password"),
Scope: r.Form.Get("scope"),
GenerateRefresh: true,
Expiration: s.Config.AccessExpiration,
HttpRequest: r,
}
// "username" and "password" is required
if ret.Username == "" || ret.Password == "" {
s.setErrorAndLog(w, E_INVALID_GRANT, nil, "handle_password=%s", "username and pass required")
return nil
}
// must have a valid client
if ret.Client = s.getClient(ctx, auth, w.Storage, w); ret.Client == nil {
return nil
}
// set redirect uri
ret.RedirectUri = FirstUri(ret.Client.GetRedirectUri(), s.Config.RedirectUriSeparator)
return ret
}
func (s *Server) handleClientCredentialsRequest(w *Response, r *http.Request) *AccessRequest {
// get client authentication
ctx := r.Context()
auth := s.getClientAuth(w, r, s.Config.AllowClientSecretInParams)
if auth == nil {
return nil
}
// generate access token
ret := &AccessRequest{
Type: CLIENT_CREDENTIALS,
Scope: r.Form.Get("scope"),
GenerateRefresh: false,
Expiration: s.Config.AccessExpiration,
HttpRequest: r,
}
// must have a valid client
client := s.getClient(ctx, auth, w.Storage, w)
if client == nil {
return nil
}
if client.IsExternal() && client.GetAppName() == "OPENAPI" {
ret.Scope = "OPENAPI"
}
ret.Client = client
// set redirect uri
ret.RedirectUri = FirstUri(ret.Client.GetRedirectUri(), s.Config.RedirectUriSeparator)
return ret
}
func (s *Server) handleAssertionRequest(w *Response, r *http.Request) *AccessRequest {
// get client authentication
ctx := r.Context()
auth := s.getClientAuth(w, r, s.Config.AllowClientSecretInParams)
if auth == nil {
return nil
}
// generate access token
ret := &AccessRequest{
Type: ASSERTION,
Scope: r.Form.Get("scope"),
AssertionType: r.Form.Get("assertion_type"),
Assertion: r.Form.Get("assertion"),
GenerateRefresh: false, // assertion should NOT generate a refresh token, per the RFC
Expiration: s.Config.AccessExpiration,
HttpRequest: r,
}
// "assertion_type" and "assertion" is required
if ret.AssertionType == "" || ret.Assertion == "" {
s.setErrorAndLog(w, E_INVALID_GRANT, nil, "handle_assertion_request=%s", "assertion and assertion_type required")
return nil
}
// must have a valid client
if ret.Client = s.getClient(ctx, auth, w.Storage, w); ret.Client == nil {
return nil
}
// set redirect uri
ret.RedirectUri = FirstUri(ret.Client.GetRedirectUri(), s.Config.RedirectUriSeparator)
return ret
}
func (s *Server) handleExtensionRequest(w *Response, r *http.Request) *AccessRequest {
// get client authentication
ctx := r.Context()
auth := s.getClientAuth(w, r, s.Config.AllowClientSecretInParams)
if auth == nil {
return nil
}
// generate access token
if s.Config.ExtensionHandler == nil {
return nil
}
ret := s.Config.ExtensionHandler(s, w, r)
// "assertion_type" and "assertion" is required
if ret.Extension == nil {
w.SetError(E_INVALID_GRANT, "")
return nil
}
// must have a valid client
if ret.Client = s.getClient(ctx, auth, w.Storage, w); ret.Client == nil {
return nil
}
// set redirect uri
ret.RedirectUri = FirstUri(ret.Client.GetRedirectUri(), s.Config.RedirectUriSeparator)
return ret
}
func (s *Server) FinishAccessRequest(w *Response, r *http.Request, ar *AccessRequest) {
// don't process if is already an error
ctx := r.Context()
if w.IsError {
return
}
redirectUri := r.Form.Get("redirect_uri")
// Get redirect uri from AccessRequest if it's there (e.g., refresh token request)
if ar.RedirectUri != "" {
redirectUri = ar.RedirectUri
}
if ar.Authorized {
var ret *AccessData
var err error
if ar.ForceAccessData == nil {
// generate access token
ret = &AccessData{
Client: ar.Client,
AuthorizeData: ar.AuthorizeData,
AccessData: ar.AccessData,
RedirectUri: redirectUri,
CreatedAt: s.Now(),
ExpiresIn: ar.Expiration,
UserData: ar.UserData,
Scope: ar.Scope,
}
// generate access token
ret.AccessToken, ret.RefreshToken, err = s.AccessTokenGen.GenerateAccessToken(ret, ar.GenerateRefresh)
if err != nil {
s.setErrorAndLog(w, E_SERVER_ERROR, err, "finish_access_request=%s", "error generating token")
return
}
} else {
ret = ar.ForceAccessData
}
// save access token
if err = w.Storage.SaveAccess(ctx, ret); err != nil {
s.setErrorAndLog(w, E_SERVER_ERROR, err, "finish_access_request=%s", "error saving access token")
return
}
// remove authorization token
if ret.AuthorizeData != nil {
w.Storage.RemoveAuthorize(ctx, ret.AuthorizeData.Code)
}
// remove previous access token
if ret.AccessData != nil && !s.Config.RetainTokenAfterRefresh {
if ret.AccessData.RefreshToken != "" {
w.Storage.RemoveRefresh(ctx, ret.AccessData.RefreshToken)
}
w.Storage.RemoveAccess(ctx, ret.AccessData.AccessToken)
}
// output data
w.Output["access_token"] = ret.AccessToken
w.Output["token_type"] = s.Config.TokenType
w.Output["expires_in"] = ret.ExpiresIn
if ret.RefreshToken != "" {
w.Output["refresh_token"] = ret.RefreshToken
}
if ret.Scope != "" {
w.Output["scope"] = ret.Scope
}
} else {
s.setErrorAndLog(w, E_ACCESS_DENIED, nil, "finish_access_request=%s", "authorization failed")
}
}
// Helper Functions
// getClient looks up and authenticates the basic auth using the given
// storage. Sets an error on the response if auth fails or a server error occurs.
func (s Server) getClient(ctx context.Context, auth *BasicAuth, storage Storage, w *Response) Client {
client, err := storage.GetClient(ctx, auth.Username)
if err == ErrNotFound {
s.setErrorAndLog(w, E_UNAUTHORIZED_CLIENT, nil, "get_client=%s", "not found")
return nil
}
if err != nil {
s.setErrorAndLog(w, E_SERVER_ERROR, err, "get_client=%s", "error finding client")
return nil
}
if client == nil {
s.setErrorAndLog(w, E_UNAUTHORIZED_CLIENT, nil, "get_client=%s", "client is nil")
return nil
}
if !CheckClientSecret(client, auth.Password) {
s.setErrorAndLog(w, E_UNAUTHORIZED_CLIENT, nil, "get_client=%s, client_id=%v", "client check failed", client.GetId())
return nil
}
if client.GetRedirectUri() == "" {
s.setErrorAndLog(w, E_UNAUTHORIZED_CLIENT, nil, "get_client=%s", "client redirect uri is empty")
return nil
}
return client
}
// setErrorAndLog sets the response error and internal error (if non-nil) and logs them along with the provided debug format string and arguments.
func (s Server) setErrorAndLog(w *Response, responseError string, internalError error, debugFormat string, debugArgs ...interface{}) {
format := "error=%v, internal_error=%#v " + debugFormat
w.InternalError = internalError
w.SetError(responseError, "")
if internalError != nil {
if internalError.Error() != ErrorIgnore.Error() {
s.Logger.Printf(format, append([]interface{}{responseError, internalError}, debugArgs...)...)
}
}
}