-
-
Notifications
You must be signed in to change notification settings - Fork 367
/
memory.go
504 lines (422 loc) · 15.8 KB
/
memory.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
// Copyright © 2024 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package storage
import (
"context"
"errors"
"sync"
"time"
"github.com/go-jose/go-jose/v3"
"github.com/google/uuid"
"github.com/ory/fosite"
"github.com/ory/fosite/internal"
)
type MemoryUserRelation struct {
Username string
Password string
}
type IssuerPublicKeys struct {
Issuer string
KeysBySub map[string]SubjectPublicKeys
}
type SubjectPublicKeys struct {
Subject string
Keys map[string]PublicKeyScopes
}
type PublicKeyScopes struct {
Key *jose.JSONWebKey
Scopes []string
}
type MemoryStore struct {
Clients map[string]fosite.Client
AuthorizeCodes map[string]StoreAuthorizeCode
IDSessions map[string]fosite.Requester
AccessTokens map[string]fosite.Requester
RefreshTokens map[string]StoreRefreshToken
PKCES map[string]fosite.Requester
Users map[string]MemoryUserRelation
BlacklistedJTIs map[string]time.Time
// In-memory request ID to token signatures
AccessTokenRequestIDs map[string]string
RefreshTokenRequestIDs map[string]string
// Public keys to check signature in auth grant jwt assertion.
IssuerPublicKeys map[string]IssuerPublicKeys
PARSessions map[string]fosite.AuthorizeRequester
clientsMutex sync.RWMutex
authorizeCodesMutex sync.RWMutex
idSessionsMutex sync.RWMutex
accessTokensMutex sync.RWMutex
refreshTokensMutex sync.RWMutex
pkcesMutex sync.RWMutex
usersMutex sync.RWMutex
blacklistedJTIsMutex sync.RWMutex
accessTokenRequestIDsMutex sync.RWMutex
refreshTokenRequestIDsMutex sync.RWMutex
issuerPublicKeysMutex sync.RWMutex
parSessionsMutex sync.RWMutex
}
func NewMemoryStore() *MemoryStore {
return &MemoryStore{
Clients: make(map[string]fosite.Client),
AuthorizeCodes: make(map[string]StoreAuthorizeCode),
IDSessions: make(map[string]fosite.Requester),
AccessTokens: make(map[string]fosite.Requester),
RefreshTokens: make(map[string]StoreRefreshToken),
PKCES: make(map[string]fosite.Requester),
Users: make(map[string]MemoryUserRelation),
AccessTokenRequestIDs: make(map[string]string),
RefreshTokenRequestIDs: make(map[string]string),
BlacklistedJTIs: make(map[string]time.Time),
IssuerPublicKeys: make(map[string]IssuerPublicKeys),
PARSessions: make(map[string]fosite.AuthorizeRequester),
}
}
type StoreAuthorizeCode struct {
active bool
fosite.Requester
}
type StoreRefreshToken struct {
active bool
accessTokenSignature string
fosite.Requester
}
func NewExampleStore() *MemoryStore {
return &MemoryStore{
IDSessions: make(map[string]fosite.Requester),
Clients: map[string]fosite.Client{
"my-client": &fosite.DefaultClient{
ID: "my-client",
Secret: []byte(`$2a$10$IxMdI6d.LIRZPpSfEwNoeu4rY3FhDREsxFJXikcgdRRAStxUlsuEO`), // = "foobar"
RotatedSecrets: [][]byte{[]byte(`$2y$10$X51gLxUQJ.hGw1epgHTE5u0bt64xM0COU7K9iAp.OFg8p2pUd.1zC `)}, // = "foobaz",
RedirectURIs: []string{"http://localhost:3846/callback"},
ResponseTypes: []string{"id_token", "code", "token", "id_token token", "code id_token", "code token", "code id_token token"},
GrantTypes: []string{"implicit", "refresh_token", "authorization_code", "password", "client_credentials"},
Scopes: []string{"fosite", "openid", "photos", "offline"},
},
"custom-lifespan-client": &fosite.DefaultClientWithCustomTokenLifespans{
DefaultClient: &fosite.DefaultClient{
ID: "custom-lifespan-client",
Secret: []byte(`$2a$10$IxMdI6d.LIRZPpSfEwNoeu4rY3FhDREsxFJXikcgdRRAStxUlsuEO`), // = "foobar"
RotatedSecrets: [][]byte{[]byte(`$2y$10$X51gLxUQJ.hGw1epgHTE5u0bt64xM0COU7K9iAp.OFg8p2pUd.1zC `)}, // = "foobaz",
RedirectURIs: []string{"http://localhost:3846/callback"},
ResponseTypes: []string{"id_token", "code", "token", "id_token token", "code id_token", "code token", "code id_token token"},
GrantTypes: []string{"implicit", "refresh_token", "authorization_code", "password", "client_credentials"},
Scopes: []string{"fosite", "openid", "photos", "offline"},
},
TokenLifespans: &internal.TestLifespans,
},
"encoded:client": &fosite.DefaultClient{
ID: "encoded:client",
Secret: []byte(`$2a$10$A7M8b65dSSKGHF0H2sNkn.9Z0hT8U1Nv6OWPV3teUUaczXkVkxuDS`), // = "encoded&password"
RotatedSecrets: nil,
RedirectURIs: []string{"http://localhost:3846/callback"},
ResponseTypes: []string{"id_token", "code", "token", "id_token token", "code id_token", "code token", "code id_token token"},
GrantTypes: []string{"implicit", "refresh_token", "authorization_code", "password", "client_credentials"},
Scopes: []string{"fosite", "openid", "photos", "offline"},
},
},
Users: map[string]MemoryUserRelation{
"peter": {
// This store simply checks for equality, a real storage implementation would obviously use
// a hashing algorithm for encrypting the user password.
Username: "peter",
Password: "secret",
},
},
AuthorizeCodes: map[string]StoreAuthorizeCode{},
AccessTokens: map[string]fosite.Requester{},
RefreshTokens: map[string]StoreRefreshToken{},
PKCES: map[string]fosite.Requester{},
AccessTokenRequestIDs: map[string]string{},
RefreshTokenRequestIDs: map[string]string{},
IssuerPublicKeys: map[string]IssuerPublicKeys{},
PARSessions: map[string]fosite.AuthorizeRequester{},
}
}
func (s *MemoryStore) CreateOpenIDConnectSession(_ context.Context, authorizeCode string, requester fosite.Requester) error {
s.idSessionsMutex.Lock()
defer s.idSessionsMutex.Unlock()
s.IDSessions[authorizeCode] = requester
return nil
}
func (s *MemoryStore) GetOpenIDConnectSession(_ context.Context, authorizeCode string, requester fosite.Requester) (fosite.Requester, error) {
s.idSessionsMutex.RLock()
defer s.idSessionsMutex.RUnlock()
cl, ok := s.IDSessions[authorizeCode]
if !ok {
return nil, fosite.ErrNotFound
}
return cl, nil
}
func (s *MemoryStore) DeleteOpenIDConnectSession(_ context.Context, authorizeCode string) error {
s.idSessionsMutex.Lock()
defer s.idSessionsMutex.Unlock()
delete(s.IDSessions, authorizeCode)
return nil
}
func (s *MemoryStore) GetClient(_ context.Context, id string) (fosite.Client, error) {
s.clientsMutex.RLock()
defer s.clientsMutex.RUnlock()
cl, ok := s.Clients[id]
if !ok {
return nil, fosite.ErrNotFound
}
return cl, nil
}
func (s *MemoryStore) SetTokenLifespans(clientID string, lifespans *fosite.ClientLifespanConfig) error {
if client, ok := s.Clients[clientID]; ok {
if clc, ok := client.(*fosite.DefaultClientWithCustomTokenLifespans); ok {
clc.SetTokenLifespans(lifespans)
return nil
}
return fosite.ErrorToRFC6749Error(errors.New("failed to set token lifespans due to failed client type assertion"))
}
return fosite.ErrNotFound
}
func (s *MemoryStore) ClientAssertionJWTValid(_ context.Context, jti string) error {
s.blacklistedJTIsMutex.RLock()
defer s.blacklistedJTIsMutex.RUnlock()
if exp, exists := s.BlacklistedJTIs[jti]; exists && exp.After(time.Now()) {
return fosite.ErrJTIKnown
}
return nil
}
func (s *MemoryStore) SetClientAssertionJWT(_ context.Context, jti string, exp time.Time) error {
s.blacklistedJTIsMutex.Lock()
defer s.blacklistedJTIsMutex.Unlock()
// delete expired jtis
for j, e := range s.BlacklistedJTIs {
if e.Before(time.Now()) {
delete(s.BlacklistedJTIs, j)
}
}
if _, exists := s.BlacklistedJTIs[jti]; exists {
return fosite.ErrJTIKnown
}
s.BlacklistedJTIs[jti] = exp
return nil
}
func (s *MemoryStore) CreateAuthorizeCodeSession(_ context.Context, code string, req fosite.Requester) error {
s.authorizeCodesMutex.Lock()
defer s.authorizeCodesMutex.Unlock()
s.AuthorizeCodes[code] = StoreAuthorizeCode{active: true, Requester: req}
return nil
}
func (s *MemoryStore) GetAuthorizeCodeSession(_ context.Context, code string, _ fosite.Session) (fosite.Requester, error) {
s.authorizeCodesMutex.RLock()
defer s.authorizeCodesMutex.RUnlock()
rel, ok := s.AuthorizeCodes[code]
if !ok {
return nil, fosite.ErrNotFound
}
if !rel.active {
return rel, fosite.ErrInvalidatedAuthorizeCode
}
return rel.Requester, nil
}
func (s *MemoryStore) InvalidateAuthorizeCodeSession(ctx context.Context, code string) error {
s.authorizeCodesMutex.Lock()
defer s.authorizeCodesMutex.Unlock()
rel, ok := s.AuthorizeCodes[code]
if !ok {
return fosite.ErrNotFound
}
rel.active = false
s.AuthorizeCodes[code] = rel
return nil
}
func (s *MemoryStore) CreatePKCERequestSession(_ context.Context, code string, req fosite.Requester) error {
s.pkcesMutex.Lock()
defer s.pkcesMutex.Unlock()
s.PKCES[code] = req
return nil
}
func (s *MemoryStore) GetPKCERequestSession(_ context.Context, code string, _ fosite.Session) (fosite.Requester, error) {
s.pkcesMutex.RLock()
defer s.pkcesMutex.RUnlock()
rel, ok := s.PKCES[code]
if !ok {
return nil, fosite.ErrNotFound
}
return rel, nil
}
func (s *MemoryStore) DeletePKCERequestSession(_ context.Context, code string) error {
s.pkcesMutex.Lock()
defer s.pkcesMutex.Unlock()
delete(s.PKCES, code)
return nil
}
func (s *MemoryStore) CreateAccessTokenSession(_ context.Context, signature string, req fosite.Requester) error {
// We first lock accessTokenRequestIDsMutex and then accessTokensMutex because this is the same order
// locking happens in RevokeAccessToken and using the same order prevents deadlocks.
s.accessTokenRequestIDsMutex.Lock()
defer s.accessTokenRequestIDsMutex.Unlock()
s.accessTokensMutex.Lock()
defer s.accessTokensMutex.Unlock()
s.AccessTokens[signature] = req
s.AccessTokenRequestIDs[req.GetID()] = signature
return nil
}
func (s *MemoryStore) GetAccessTokenSession(_ context.Context, signature string, _ fosite.Session) (fosite.Requester, error) {
s.accessTokensMutex.RLock()
defer s.accessTokensMutex.RUnlock()
rel, ok := s.AccessTokens[signature]
if !ok {
return nil, fosite.ErrNotFound
}
return rel, nil
}
func (s *MemoryStore) DeleteAccessTokenSession(_ context.Context, signature string) error {
s.accessTokensMutex.Lock()
defer s.accessTokensMutex.Unlock()
delete(s.AccessTokens, signature)
return nil
}
func (s *MemoryStore) CreateRefreshTokenSession(_ context.Context, signature, accessTokenSignature string, req fosite.Requester) error {
// We first lock refreshTokenRequestIDsMutex and then refreshTokensMutex because this is the same order
// locking happens in RevokeRefreshToken and using the same order prevents deadlocks.
s.refreshTokenRequestIDsMutex.Lock()
defer s.refreshTokenRequestIDsMutex.Unlock()
s.refreshTokensMutex.Lock()
defer s.refreshTokensMutex.Unlock()
s.RefreshTokens[signature] = StoreRefreshToken{active: true, Requester: req, accessTokenSignature: accessTokenSignature}
s.RefreshTokenRequestIDs[req.GetID()] = signature
return nil
}
func (s *MemoryStore) GetRefreshTokenSession(_ context.Context, signature string, _ fosite.Session) (fosite.Requester, error) {
s.refreshTokensMutex.RLock()
defer s.refreshTokensMutex.RUnlock()
rel, ok := s.RefreshTokens[signature]
if !ok {
return nil, fosite.ErrNotFound
}
if !rel.active {
return rel, fosite.ErrInactiveToken
}
return rel, nil
}
func (s *MemoryStore) DeleteRefreshTokenSession(_ context.Context, signature string) error {
s.refreshTokensMutex.Lock()
defer s.refreshTokensMutex.Unlock()
delete(s.RefreshTokens, signature)
return nil
}
func (s *MemoryStore) Authenticate(_ context.Context, name string, secret string) (subject string, err error) {
s.usersMutex.RLock()
defer s.usersMutex.RUnlock()
rel, ok := s.Users[name]
if !ok {
return "", fosite.ErrNotFound
}
if rel.Password != secret {
return "", fosite.ErrNotFound.WithDebug("Invalid credentials")
}
return uuid.New().String(), nil
}
func (s *MemoryStore) RevokeRefreshToken(ctx context.Context, requestID string) error {
s.refreshTokenRequestIDsMutex.Lock()
defer s.refreshTokenRequestIDsMutex.Unlock()
if signature, exists := s.RefreshTokenRequestIDs[requestID]; exists {
rel, ok := s.RefreshTokens[signature]
if !ok {
return fosite.ErrNotFound
}
rel.active = false
s.RefreshTokens[signature] = rel
}
return nil
}
func (s *MemoryStore) RevokeAccessToken(ctx context.Context, requestID string) error {
s.accessTokenRequestIDsMutex.RLock()
defer s.accessTokenRequestIDsMutex.RUnlock()
if signature, exists := s.AccessTokenRequestIDs[requestID]; exists {
if err := s.DeleteAccessTokenSession(ctx, signature); err != nil {
return err
}
}
return nil
}
func (s *MemoryStore) GetPublicKey(ctx context.Context, issuer string, subject string, keyId string) (*jose.JSONWebKey, error) {
s.issuerPublicKeysMutex.RLock()
defer s.issuerPublicKeysMutex.RUnlock()
if issuerKeys, ok := s.IssuerPublicKeys[issuer]; ok {
if subKeys, ok := issuerKeys.KeysBySub[subject]; ok {
if keyScopes, ok := subKeys.Keys[keyId]; ok {
return keyScopes.Key, nil
}
}
}
return nil, fosite.ErrNotFound
}
func (s *MemoryStore) GetPublicKeys(ctx context.Context, issuer string, subject string) (*jose.JSONWebKeySet, error) {
s.issuerPublicKeysMutex.RLock()
defer s.issuerPublicKeysMutex.RUnlock()
if issuerKeys, ok := s.IssuerPublicKeys[issuer]; ok {
if subKeys, ok := issuerKeys.KeysBySub[subject]; ok {
if len(subKeys.Keys) == 0 {
return nil, fosite.ErrNotFound
}
keys := make([]jose.JSONWebKey, 0, len(subKeys.Keys))
for _, keyScopes := range subKeys.Keys {
keys = append(keys, *keyScopes.Key)
}
return &jose.JSONWebKeySet{Keys: keys}, nil
}
}
return nil, fosite.ErrNotFound
}
func (s *MemoryStore) GetPublicKeyScopes(ctx context.Context, issuer string, subject string, keyId string) ([]string, error) {
s.issuerPublicKeysMutex.RLock()
defer s.issuerPublicKeysMutex.RUnlock()
if issuerKeys, ok := s.IssuerPublicKeys[issuer]; ok {
if subKeys, ok := issuerKeys.KeysBySub[subject]; ok {
if keyScopes, ok := subKeys.Keys[keyId]; ok {
return keyScopes.Scopes, nil
}
}
}
return nil, fosite.ErrNotFound
}
func (s *MemoryStore) IsJWTUsed(ctx context.Context, jti string) (bool, error) {
err := s.ClientAssertionJWTValid(ctx, jti)
if err != nil {
return true, nil
}
return false, nil
}
func (s *MemoryStore) MarkJWTUsedForTime(ctx context.Context, jti string, exp time.Time) error {
return s.SetClientAssertionJWT(ctx, jti, exp)
}
// CreatePARSession stores the pushed authorization request context. The requestURI is used to derive the key.
func (s *MemoryStore) CreatePARSession(ctx context.Context, requestURI string, request fosite.AuthorizeRequester) error {
s.parSessionsMutex.Lock()
defer s.parSessionsMutex.Unlock()
s.PARSessions[requestURI] = request
return nil
}
// GetPARSession gets the push authorization request context. If the request is nil, a new request object
// is created. Otherwise, the same object is updated.
func (s *MemoryStore) GetPARSession(ctx context.Context, requestURI string) (fosite.AuthorizeRequester, error) {
s.parSessionsMutex.RLock()
defer s.parSessionsMutex.RUnlock()
r, ok := s.PARSessions[requestURI]
if !ok {
return nil, fosite.ErrNotFound
}
return r, nil
}
// DeletePARSession deletes the context.
func (s *MemoryStore) DeletePARSession(ctx context.Context, requestURI string) (err error) {
s.parSessionsMutex.Lock()
defer s.parSessionsMutex.Unlock()
delete(s.PARSessions, requestURI)
return nil
}
func (s *MemoryStore) RotateRefreshToken(ctx context.Context, requestID string, refreshTokenSignature string) (err error) {
// Graceful token rotation can be implemented here but it's beyond the scope of this example. Check
// the Ory Hydra implementation for reference.
if err := s.RevokeRefreshToken(ctx, requestID); err != nil {
return err
}
return s.RevokeAccessToken(ctx, requestID)
}