forked from ory/fosite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
config_default.go
508 lines (407 loc) · 19.7 KB
/
config_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
/*
* 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 2015-2018 Aeneas Rekkas <[email protected]>
* @license Apache-2.0
*
*/
package fosite
import (
"context"
"hash"
"html/template"
"net/url"
"time"
"github.com/hashicorp/go-retryablehttp"
"github.com/ory/fosite/token/jwt"
"github.com/ory/fosite/i18n"
)
const (
defaultPARPrefix = "urn:ietf:params:oauth:request_uri:"
defaultPARContextLifetime = 5 * time.Minute
)
var (
_ AuthorizeCodeLifespanProvider = (*Config)(nil)
_ RefreshTokenLifespanProvider = (*Config)(nil)
_ AccessTokenLifespanProvider = (*Config)(nil)
_ ScopeStrategyProvider = (*Config)(nil)
_ AudienceStrategyProvider = (*Config)(nil)
_ RedirectSecureCheckerProvider = (*Config)(nil)
_ RefreshTokenScopesProvider = (*Config)(nil)
_ DisableRefreshTokenValidationProvider = (*Config)(nil)
_ AccessTokenIssuerProvider = (*Config)(nil)
_ JWTScopeFieldProvider = (*Config)(nil)
_ AllowedPromptsProvider = (*Config)(nil)
_ OmitRedirectScopeParamProvider = (*Config)(nil)
_ MinParameterEntropyProvider = (*Config)(nil)
_ SanitationAllowedProvider = (*Config)(nil)
_ EnforcePKCEForPublicClientsProvider = (*Config)(nil)
_ EnablePKCEPlainChallengeMethodProvider = (*Config)(nil)
_ EnforcePKCEProvider = (*Config)(nil)
_ GrantTypeJWTBearerCanSkipClientAuthProvider = (*Config)(nil)
_ GrantTypeJWTBearerIDOptionalProvider = (*Config)(nil)
_ GrantTypeJWTBearerIssuedDateOptionalProvider = (*Config)(nil)
_ GetJWTMaxDurationProvider = (*Config)(nil)
_ IDTokenLifespanProvider = (*Config)(nil)
_ IDTokenIssuerProvider = (*Config)(nil)
_ JWKSFetcherStrategyProvider = (*Config)(nil)
_ ClientAuthenticationStrategyProvider = (*Config)(nil)
_ SendDebugMessagesToClientsProvider = (*Config)(nil)
_ ResponseModeHandlerExtensionProvider = (*Config)(nil)
_ MessageCatalogProvider = (*Config)(nil)
_ FormPostHTMLTemplateProvider = (*Config)(nil)
_ TokenURLProvider = (*Config)(nil)
_ GetSecretsHashingProvider = (*Config)(nil)
_ HTTPClientProvider = (*Config)(nil)
_ HMACHashingProvider = (*Config)(nil)
_ AuthorizeEndpointHandlersProvider = (*Config)(nil)
_ TokenEndpointHandlersProvider = (*Config)(nil)
_ TokenIntrospectionHandlersProvider = (*Config)(nil)
_ RevocationHandlersProvider = (*Config)(nil)
_ PushedAuthorizeRequestHandlersProvider = (*Config)(nil)
_ PushedAuthorizeRequestConfigProvider = (*Config)(nil)
)
type Config struct {
// AccessTokenLifespan sets how long an access token is going to be valid. Defaults to one hour.
AccessTokenLifespan time.Duration
// RefreshTokenLifespan sets how long a refresh token is going to be valid. Defaults to 30 days. Set to -1 for
// refresh tokens that never expire.
RefreshTokenLifespan time.Duration
// AuthorizeCodeLifespan sets how long an authorize code is going to be valid. Defaults to fifteen minutes.
AuthorizeCodeLifespan time.Duration
// IDTokenLifespan sets the default id token lifetime. Defaults to one hour.
IDTokenLifespan time.Duration
// IDTokenIssuer sets the default issuer of the ID Token.
IDTokenIssuer string
// HashCost sets the cost of the password hashing cost. Defaults to 12.
HashCost int
// DisableRefreshTokenValidation sets the introspection endpoint to disable refresh token validation.
DisableRefreshTokenValidation bool
// SendDebugMessagesToClients if set to true, includes error debug messages in response payloads. Be aware that sensitive
// data may be exposed, depending on your implementation of Fosite. Such sensitive data might include database error
// codes or other information. Proceed with caution!
SendDebugMessagesToClients bool
// ScopeStrategy sets the scope strategy that should be supported, for example fosite.WildcardScopeStrategy.
ScopeStrategy ScopeStrategy
// AudienceMatchingStrategy sets the audience matching strategy that should be supported, defaults to fosite.DefaultsAudienceMatchingStrategy.
AudienceMatchingStrategy AudienceMatchingStrategy
// EnforcePKCE, if set to true, requires clients to perform authorize code flows with PKCE. Defaults to false.
EnforcePKCE bool
// EnforcePKCEForPublicClients requires only public clients to use PKCE with the authorize code flow. Defaults to false.
EnforcePKCEForPublicClients bool
// EnablePKCEPlainChallengeMethod sets whether or not to allow the plain challenge method (S256 should be used whenever possible, plain is really discouraged). Defaults to false.
EnablePKCEPlainChallengeMethod bool
// AllowedPromptValues sets which OpenID Connect prompt values the server supports. Defaults to []string{"login", "none", "consent", "select_account"}.
AllowedPromptValues []string
// TokenURL is the the URL of the Authorization Server's Token Endpoint. If the authorization server is intended
// to be compatible with the private_key_jwt client authentication method (see http://openid.net/specs/openid-connect-core-1_0.html#CodeFlowAuth),
// this value MUST be set.
TokenURL string
// JWKSFetcherStrategy is responsible for fetching JSON Web Keys from remote URLs. This is required when the private_key_jwt
// client authentication method is used. Defaults to fosite.DefaultJWKSFetcherStrategy.
JWKSFetcherStrategy JWKSFetcherStrategy
// TokenEntropy indicates the entropy of the random string, used as the "message" part of the HMAC token.
// Defaults to 32.
TokenEntropy int
// RedirectSecureChecker is a function that returns true if the provided URL can be securely used as a redirect URL.
RedirectSecureChecker func(context.Context, *url.URL) bool
// RefreshTokenScopes defines which OAuth scopes will be given refresh tokens during the authorization code grant exchange. This defaults to "offline" and "offline_access". When set to an empty array, all exchanges will be given refresh tokens.
RefreshTokenScopes []string
// MinParameterEntropy controls the minimum size of state and nonce parameters. Defaults to fosite.MinParameterEntropy.
MinParameterEntropy int
// UseLegacyErrorFormat controls whether the legacy error format (with `error_debug`, `error_hint`, ...)
// should be used or not.
UseLegacyErrorFormat bool
// GrantTypeJWTBearerCanSkipClientAuth indicates, if client authentication can be skipped, when using jwt as assertion.
GrantTypeJWTBearerCanSkipClientAuth bool
// GrantTypeJWTBearerIDOptional indicates, if jti (JWT ID) claim required or not in JWT.
GrantTypeJWTBearerIDOptional bool
// GrantTypeJWTBearerIssuedDateOptional indicates, if "iat" (issued at) claim required or not in JWT.
GrantTypeJWTBearerIssuedDateOptional bool
// GrantTypeJWTBearerMaxDuration sets the maximum time after JWT issued date, during which the JWT is considered valid.
GrantTypeJWTBearerMaxDuration time.Duration
// ClientAuthenticationStrategy indicates the Strategy to authenticate client requests
ClientAuthenticationStrategy ClientAuthenticationStrategy
// ResponseModeHandlerExtension provides a handler for custom response modes
ResponseModeHandlerExtension ResponseModeHandler
// MessageCatalog is the message bundle used for i18n
MessageCatalog i18n.MessageCatalog
// FormPostHTMLTemplate sets html template for rendering the authorization response when the request has response_mode=form_post.
FormPostHTMLTemplate *template.Template
// OmitRedirectScopeParam indicates whether the "scope" parameter should be omitted from the redirect URL.
OmitRedirectScopeParam bool
// SanitationWhiteList is a whitelist of form values that are required by the token endpoint. These values
// are safe for storage in a database (cleartext).
SanitationWhiteList []string
// JWTScopeClaimKey defines the claim key to be used to set the scope in. Valid fields are "scope" or "scp" or both.
JWTScopeClaimKey jwt.JWTScopeFieldEnum
// AccessTokenIssuer is the issuer to be used when generating access tokens.
AccessTokenIssuer string
// ClientSecretsHasher is the hasher used to hash OAuth2 Client Secrets.
ClientSecretsHasher Hasher
// HTTPClient is the HTTP client to use for requests.
HTTPClient *retryablehttp.Client
// AuthorizeEndpointHandlers is a list of handlers that are called before the authorization endpoint is served.
AuthorizeEndpointHandlers AuthorizeEndpointHandlers
// TokenEndpointHandlers is a list of handlers that are called before the token endpoint is served.
TokenEndpointHandlers TokenEndpointHandlers
// TokenIntrospectionHandlers is a list of handlers that are called before the token introspection endpoint is served.
TokenIntrospectionHandlers TokenIntrospectionHandlers
// RevocationHandlers is a list of handlers that are called before the revocation endpoint is served.
RevocationHandlers RevocationHandlers
// PushedAuthorizeEndpointHandlers is a list of handlers that are called before the PAR endpoint is served.
PushedAuthorizeEndpointHandlers PushedAuthorizeEndpointHandlers
// GlobalSecret is the global secret used to sign and verify signatures.
GlobalSecret []byte
// RotatedGlobalSecrets is a list of global secrets that are used to verify signatures.
RotatedGlobalSecrets [][]byte
// HMACHasher is the hasher used to generate HMAC signatures.
HMACHasher func() hash.Hash
// PushedAuthorizeRequestURIPrefix is the URI prefix for the PAR request_uri.
// This is defaulted to 'urn:ietf:params:oauth:request_uri:'.
PushedAuthorizeRequestURIPrefix string
// PushedAuthorizeContextLifespan is the lifespan of the PAR context
PushedAuthorizeContextLifespan time.Duration
// IsPushedAuthorizeEnforced enforces pushed authorization request for /authorize
IsPushedAuthorizeEnforced bool
}
func (c *Config) GetGlobalSecret(ctx context.Context) []byte {
return c.GlobalSecret
}
func (c *Config) GetUseLegacyErrorFormat(ctx context.Context) bool {
return c.UseLegacyErrorFormat
}
func (c *Config) GetRotatedGlobalSecrets(ctx context.Context) [][]byte {
return c.RotatedGlobalSecrets
}
func (c *Config) GetHMACHasher(ctx context.Context) func() hash.Hash {
return c.HMACHasher
}
func (c *Config) GetAuthorizeEndpointHandlers(ctx context.Context) AuthorizeEndpointHandlers {
return c.AuthorizeEndpointHandlers
}
func (c *Config) GetTokenEndpointHandlers(ctx context.Context) TokenEndpointHandlers {
return c.TokenEndpointHandlers
}
func (c *Config) GetTokenIntrospectionHandlers(ctx context.Context) TokenIntrospectionHandlers {
return c.TokenIntrospectionHandlers
}
func (c *Config) GetRevocationHandlers(ctx context.Context) RevocationHandlers {
return c.RevocationHandlers
}
func (c *Config) GetHTTPClient(ctx context.Context) *retryablehttp.Client {
if c.HTTPClient == nil {
return retryablehttp.NewClient()
}
return c.HTTPClient
}
func (c *Config) GetSecretsHasher(ctx context.Context) Hasher {
if c.ClientSecretsHasher == nil {
c.ClientSecretsHasher = &BCrypt{Config: c}
}
return c.ClientSecretsHasher
}
func (c *Config) GetTokenURL(ctx context.Context) string {
return c.TokenURL
}
func (c *Config) GetFormPostHTMLTemplate(ctx context.Context) *template.Template {
return c.FormPostHTMLTemplate
}
func (c *Config) GetMessageCatalog(ctx context.Context) i18n.MessageCatalog {
return c.MessageCatalog
}
func (c *Config) GetResponseModeHandlerExtension(ctx context.Context) ResponseModeHandler {
return c.ResponseModeHandlerExtension
}
func (c *Config) GetSendDebugMessagesToClients(ctx context.Context) bool {
return c.SendDebugMessagesToClients
}
func (c *Config) GetIDTokenIssuer(ctx context.Context) string {
return c.IDTokenIssuer
}
// GetGrantTypeJWTBearerIssuedDateOptional returns the GrantTypeJWTBearerIssuedDateOptional field.
func (c *Config) GetGrantTypeJWTBearerIssuedDateOptional(ctx context.Context) bool {
return c.GrantTypeJWTBearerIssuedDateOptional
}
// GetGrantTypeJWTBearerIDOptional returns the GrantTypeJWTBearerIDOptional field.
func (c *Config) GetGrantTypeJWTBearerIDOptional(ctx context.Context) bool {
return c.GrantTypeJWTBearerIDOptional
}
// GetGrantTypeJWTBearerCanSkipClientAuth returns the GrantTypeJWTBearerCanSkipClientAuth field.
func (c *Config) GetGrantTypeJWTBearerCanSkipClientAuth(ctx context.Context) bool {
return c.GrantTypeJWTBearerCanSkipClientAuth
}
// GetEnforcePKCE If set to true, public clients must use PKCE.
func (c *Config) GetEnforcePKCE(ctx context.Context) bool {
return c.EnforcePKCE
}
// GetEnablePKCEPlainChallengeMethod returns whether or not to allow the plain challenge method (S256 should be used whenever possible, plain is really discouraged).
func (c *Config) GetEnablePKCEPlainChallengeMethod(ctx context.Context) bool {
return c.EnablePKCEPlainChallengeMethod
}
// GetEnforcePKCEForPublicClients returns the value of EnforcePKCEForPublicClients.
func (c *Config) GetEnforcePKCEForPublicClients(ctx context.Context) bool {
return c.EnforcePKCEForPublicClients
}
// GetSanitationWhiteList returns a list of allowed form values that are required by the token endpoint. These values
// are safe for storage in a database (cleartext).
func (c *Config) GetSanitationWhiteList(ctx context.Context) []string {
return c.SanitationWhiteList
}
func (c *Config) GetOmitRedirectScopeParam(ctx context.Context) bool {
return c.OmitRedirectScopeParam
}
func (c *Config) GetAccessTokenIssuer(ctx context.Context) string {
return c.AccessTokenIssuer
}
func (c *Config) GetJWTScopeField(ctx context.Context) jwt.JWTScopeFieldEnum {
return c.JWTScopeClaimKey
}
func (c *Config) GetAllowedPrompts(_ context.Context) []string {
return c.AllowedPromptValues
}
// GetScopeStrategy returns the scope strategy to be used. Defaults to glob scope strategy.
func (c *Config) GetScopeStrategy(_ context.Context) ScopeStrategy {
if c.ScopeStrategy == nil {
c.ScopeStrategy = WildcardScopeStrategy
}
return c.ScopeStrategy
}
// GetAudienceStrategy returns the scope strategy to be used. Defaults to glob scope strategy.
func (c *Config) GetAudienceStrategy(_ context.Context) AudienceMatchingStrategy {
if c.AudienceMatchingStrategy == nil {
c.AudienceMatchingStrategy = DefaultAudienceMatchingStrategy
}
return c.AudienceMatchingStrategy
}
// GetAuthorizeCodeLifespan returns how long an authorize code should be valid. Defaults to one fifteen minutes.
func (c *Config) GetAuthorizeCodeLifespan(_ context.Context) time.Duration {
if c.AuthorizeCodeLifespan == 0 {
return time.Minute * 15
}
return c.AuthorizeCodeLifespan
}
// GeIDTokenLifespan returns how long an id token should be valid. Defaults to one hour.
func (c *Config) GetIDTokenLifespan(_ context.Context) time.Duration {
if c.IDTokenLifespan == 0 {
return time.Hour
}
return c.IDTokenLifespan
}
// GetAccessTokenLifespan returns how long an access token should be valid. Defaults to one hour.
func (c *Config) GetAccessTokenLifespan(_ context.Context) time.Duration {
if c.AccessTokenLifespan == 0 {
return time.Hour
}
return c.AccessTokenLifespan
}
// GetRefreshTokenLifespan sets how long a refresh token is going to be valid. Defaults to 30 days. Set to -1 for
// refresh tokens that never expire.
func (c *Config) GetRefreshTokenLifespan(_ context.Context) time.Duration {
if c.RefreshTokenLifespan == 0 {
return time.Hour * 24 * 30
}
return c.RefreshTokenLifespan
}
// GetHashCost returns the bcrypt cost factor. Defaults to 12.
func (c *Config) GetBCryptCost(_ context.Context) int {
if c.HashCost == 0 {
return DefaultBCryptWorkFactor
}
return c.HashCost
}
// GetJWKSFetcherStrategy returns the JWKSFetcherStrategy.
func (c *Config) GetJWKSFetcherStrategy(_ context.Context) JWKSFetcherStrategy {
if c.JWKSFetcherStrategy == nil {
c.JWKSFetcherStrategy = NewDefaultJWKSFetcherStrategy()
}
return c.JWKSFetcherStrategy
}
// GetTokenEntropy returns the entropy of the "message" part of a HMAC Token. Defaults to 32.
func (c *Config) GetTokenEntropy(_ context.Context) int {
if c.TokenEntropy == 0 {
return 32
}
return c.TokenEntropy
}
// GetRedirectSecureChecker returns the checker to check if redirect URI is secure. Defaults to fosite.IsRedirectURISecure.
func (c *Config) GetRedirectSecureChecker(_ context.Context) func(context.Context, *url.URL) bool {
if c.RedirectSecureChecker == nil {
return IsRedirectURISecure
}
return c.RedirectSecureChecker
}
// GetRefreshTokenScopes returns which scopes will provide refresh tokens.
func (c *Config) GetRefreshTokenScopes(_ context.Context) []string {
if c.RefreshTokenScopes == nil {
return []string{"offline", "offline_access"}
}
return c.RefreshTokenScopes
}
// GetMinParameterEntropy returns MinParameterEntropy if set. Defaults to fosite.MinParameterEntropy.
func (c *Config) GetMinParameterEntropy(_ context.Context) int {
if c.MinParameterEntropy == 0 {
return MinParameterEntropy
} else {
return c.MinParameterEntropy
}
}
// GetJWTMaxDuration specified the maximum amount of allowed `exp` time for a JWT. It compares
// the time with the JWT's `exp` time if the JWT time is larger, will cause the JWT to be invalid.
//
// Defaults to a day.
func (c *Config) GetJWTMaxDuration(_ context.Context) time.Duration {
if c.GrantTypeJWTBearerMaxDuration == 0 {
return time.Hour * 24
}
return c.GrantTypeJWTBearerMaxDuration
}
// GetClientAuthenticationStrategy returns the configured client authentication strategy.
// Defaults to nil.
// Note that on a nil strategy `fosite.Fosite` fallbacks to its default client authentication strategy
// `fosite.Fosite.DefaultClientAuthenticationStrategy`
func (c *Config) GetClientAuthenticationStrategy(_ context.Context) ClientAuthenticationStrategy {
return c.ClientAuthenticationStrategy
}
// GetDisableRefreshTokenValidation returns whether to disable the validation of the refresh token.
func (c *Config) GetDisableRefreshTokenValidation(_ context.Context) bool {
return c.DisableRefreshTokenValidation
}
// GetPushedAuthorizeEndpointHandlers returns the handlers.
func (c *Config) GetPushedAuthorizeEndpointHandlers(ctx context.Context) PushedAuthorizeEndpointHandlers {
return c.PushedAuthorizeEndpointHandlers
}
// GetPushedAuthorizeRequestURIPrefix is the request URI prefix. This is
// usually 'urn:ietf:params:oauth:request_uri:'.
func (c *Config) GetPushedAuthorizeRequestURIPrefix(ctx context.Context) string {
if c.PushedAuthorizeRequestURIPrefix == "" {
return defaultPARPrefix
}
return c.PushedAuthorizeRequestURIPrefix
}
// GetPushedAuthorizeContextLifespan is the lifespan of the short-lived PAR context.
func (c *Config) GetPushedAuthorizeContextLifespan(ctx context.Context) time.Duration {
if c.PushedAuthorizeContextLifespan <= 0 {
return defaultPARContextLifetime
}
return c.PushedAuthorizeContextLifespan
}
// EnforcePushedAuthorize indicates if PAR is enforced. In this mode, a client
// cannot pass authorize parameters at the 'authorize' endpoint. The 'authorize' endpoint
// must contain the PAR request_uri.
func (c *Config) EnforcePushedAuthorize(ctx context.Context) bool {
return c.IsPushedAuthorizeEnforced
}