forked from hashicorp/vault
-
Notifications
You must be signed in to change notification settings - Fork 0
/
identity_store_oidc.go
2094 lines (1776 loc) · 57.6 KB
/
identity_store_oidc.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 (c) HashiCorp, Inc.
// SPDX-License-Identifier: BUSL-1.1
package vault
import (
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/rsa"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"math"
mathrand "math/rand"
"net/url"
"sort"
"strings"
"time"
"github.com/go-jose/go-jose/v3"
"github.com/go-jose/go-jose/v3/jwt"
"github.com/hashicorp/go-hclog"
"github.com/hashicorp/go-secure-stdlib/base62"
"github.com/hashicorp/go-secure-stdlib/strutil"
"github.com/hashicorp/go-uuid"
"github.com/hashicorp/vault/helper/identity"
"github.com/hashicorp/vault/helper/namespace"
"github.com/hashicorp/vault/sdk/framework"
"github.com/hashicorp/vault/sdk/helper/consts"
"github.com/hashicorp/vault/sdk/helper/identitytpl"
"github.com/hashicorp/vault/sdk/logical"
"github.com/patrickmn/go-cache"
"golang.org/x/crypto/ed25519"
)
type oidcConfig struct {
Issuer string `json:"issuer"`
// effectiveIssuer is a calculated field and will be either Issuer (if
// that's set) or the Vault instance's api_addr.
effectiveIssuer string
}
type expireableKey struct {
KeyID string `json:"key_id"`
ExpireAt time.Time `json:"expire_at"`
}
type namedKey struct {
name string
Algorithm string `json:"signing_algorithm"`
VerificationTTL time.Duration `json:"verification_ttl"`
RotationPeriod time.Duration `json:"rotation_period"`
KeyRing []*expireableKey `json:"key_ring"`
SigningKey *jose.JSONWebKey `json:"signing_key"`
NextSigningKey *jose.JSONWebKey `json:"next_signing_key"`
NextRotation time.Time `json:"next_rotation"`
AllowedClientIDs []string `json:"allowed_client_ids"`
}
type role struct {
TokenTTL time.Duration `json:"token_ttl"`
Key string `json:"key"`
Template string `json:"template"`
ClientID string `json:"client_id"`
}
// idToken contains the required OIDC fields.
//
// Templated claims will be merged into the final output. Those claims may
// include top-level keys, but those keys may not overwrite any of the
// required OIDC fields.
type idToken struct {
Issuer string `json:"iss"` // api_addr or custom Issuer
Namespace string `json:"namespace"` // Namespace of issuer
Subject string `json:"sub"` // Entity ID
Audience string `json:"aud"` // Role or client ID will be used here.
Expiry int64 `json:"exp"` // Expiration, as determined by the role or client.
IssuedAt int64 `json:"iat"` // Time of token creation
Nonce string `json:"nonce"` // Nonce given in OIDC authentication requests
AuthTime int64 `json:"auth_time"` // AuthTime given in OIDC authentication requests
AccessTokenHash string `json:"at_hash"` // Access token hash value
CodeHash string `json:"c_hash"` // Authorization code hash value
}
// discovery contains a subset of the required elements of OIDC discovery needed
// for JWT verification libraries to use the .well-known endpoint.
//
// https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata
type discovery struct {
Issuer string `json:"issuer"`
Keys string `json:"jwks_uri"`
ResponseTypes []string `json:"response_types_supported"`
Subjects []string `json:"subject_types_supported"`
IDTokenAlgs []string `json:"id_token_signing_alg_values_supported"`
}
// oidcCache is a thin wrapper around go-cache to partition by namespace
type oidcCache struct {
c *cache.Cache
}
var errNilNamespace = errors.New("nil namespace in oidc cache request")
const (
issuerPath = "identity/oidc"
oidcTokensPrefix = "oidc_tokens/"
oidcConfigStorageKey = oidcTokensPrefix + "config/"
namedKeyConfigPath = oidcTokensPrefix + "named_keys/"
publicKeysConfigPath = oidcTokensPrefix + "public_keys/"
roleConfigPath = oidcTokensPrefix + "roles/"
)
var (
reservedClaims = []string{
"iat", "aud", "exp", "iss",
"sub", "namespace", "nonce",
"auth_time", "at_hash", "c_hash",
}
supportedAlgs = []string{
string(jose.RS256),
string(jose.RS384),
string(jose.RS512),
string(jose.ES256),
string(jose.ES384),
string(jose.ES512),
string(jose.EdDSA),
}
)
// pseudo-namespace for cache items that don't belong to any real namespace.
var noNamespace = &namespace.Namespace{ID: "__NO_NAMESPACE"}
func oidcPaths(i *IdentityStore) []*framework.Path {
return []*framework.Path{
{
Pattern: "oidc/config/?$",
DisplayAttrs: &framework.DisplayAttributes{
OperationPrefix: "oidc",
},
Fields: map[string]*framework.FieldSchema{
"issuer": {
Type: framework.TypeString,
Description: "Issuer URL to be used in the iss claim of the token. If not set, Vault's app_addr will be used.",
},
},
Operations: map[logical.Operation]framework.OperationHandler{
logical.ReadOperation: &framework.PathOperation{
Callback: i.pathOIDCReadConfig,
DisplayAttrs: &framework.DisplayAttributes{
OperationSuffix: "configuration",
},
},
logical.UpdateOperation: &framework.PathOperation{
Callback: i.pathOIDCUpdateConfig,
DisplayAttrs: &framework.DisplayAttributes{
OperationVerb: "configure",
},
},
},
HelpSynopsis: "OIDC configuration",
HelpDescription: "Update OIDC configuration in the identity backend",
},
{
Pattern: "oidc/key/" + framework.GenericNameRegex("name"),
DisplayAttrs: &framework.DisplayAttributes{
OperationPrefix: "oidc",
OperationSuffix: "key",
},
Fields: map[string]*framework.FieldSchema{
"name": {
Type: framework.TypeString,
Description: "Name of the key",
},
"rotation_period": {
Type: framework.TypeDurationSecond,
Description: "How often to generate a new keypair.",
Default: "24h",
},
"verification_ttl": {
Type: framework.TypeDurationSecond,
Description: "Controls how long the public portion of a key will be available for verification after being rotated.",
Default: "24h",
},
"algorithm": {
Type: framework.TypeString,
Description: "Signing algorithm to use. This will default to RS256.",
Default: "RS256",
},
"allowed_client_ids": {
Type: framework.TypeCommaStringSlice,
Description: "Comma separated string or array of role client ids allowed to use this key for signing. If empty no roles are allowed. If \"*\" all roles are allowed.",
},
},
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.CreateOperation: i.pathOIDCCreateUpdateKey,
logical.UpdateOperation: i.pathOIDCCreateUpdateKey,
logical.ReadOperation: i.pathOIDCReadKey,
logical.DeleteOperation: i.pathOIDCDeleteKey,
},
ExistenceCheck: i.pathOIDCKeyExistenceCheck,
HelpSynopsis: "CRUD operations for OIDC keys.",
HelpDescription: "Create, Read, Update, and Delete OIDC named keys.",
},
{
Pattern: "oidc/key/" + framework.GenericNameRegex("name") + "/rotate/?$",
DisplayAttrs: &framework.DisplayAttributes{
OperationPrefix: "oidc",
OperationVerb: "rotate",
OperationSuffix: "key",
},
Fields: map[string]*framework.FieldSchema{
"name": {
Type: framework.TypeString,
Description: "Name of the key",
},
"verification_ttl": {
Type: framework.TypeDurationSecond,
Description: "Controls how long the public portion of a key will be available for verification after being rotated. Setting verification_ttl here will override the verification_ttl set on the key.",
},
},
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.UpdateOperation: i.pathOIDCRotateKey,
},
HelpSynopsis: "Rotate a named OIDC key.",
HelpDescription: "Manually rotate a named OIDC key. Rotating a named key will cause a new underlying signing key to be generated. The public portion of the underlying rotated signing key will continue to live for the verification_ttl duration.",
},
{
Pattern: "oidc/key/?$",
DisplayAttrs: &framework.DisplayAttributes{
OperationPrefix: "oidc",
OperationSuffix: "keys",
},
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.ListOperation: i.pathOIDCListKey,
},
HelpSynopsis: "List OIDC keys",
HelpDescription: "List all named OIDC keys",
},
{
Pattern: "oidc/\\.well-known/openid-configuration/?$",
DisplayAttrs: &framework.DisplayAttributes{
OperationPrefix: "oidc",
OperationSuffix: "open-id-configuration",
},
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.ReadOperation: i.pathOIDCDiscovery,
},
HelpSynopsis: "Query OIDC configurations",
HelpDescription: "Query this path to retrieve the configured OIDC Issuer and Keys endpoints, response types, subject types, and signing algorithms used by the OIDC backend.",
},
{
Pattern: "oidc/\\.well-known/keys/?$",
DisplayAttrs: &framework.DisplayAttributes{
OperationPrefix: "oidc",
OperationSuffix: "public-keys",
},
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.ReadOperation: i.pathOIDCReadPublicKeys,
},
HelpSynopsis: "Retrieve public keys",
HelpDescription: "Query this path to retrieve the public portion of keys used to sign OIDC tokens. Clients can use this to validate the authenticity of the OIDC token claims.",
},
{
Pattern: "oidc/token/" + framework.GenericNameRegex("name"),
DisplayAttrs: &framework.DisplayAttributes{
OperationPrefix: "oidc",
OperationVerb: "generate",
OperationSuffix: "token",
},
Fields: map[string]*framework.FieldSchema{
"name": {
Type: framework.TypeString,
Description: "Name of the role",
},
},
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.ReadOperation: i.pathOIDCGenerateToken,
},
HelpSynopsis: "Generate an OIDC token",
HelpDescription: "Generate an OIDC token against a configured role. The vault token used to call this path must have a corresponding entity.",
},
{
Pattern: "oidc/role/" + framework.GenericNameRegex("name"),
DisplayAttrs: &framework.DisplayAttributes{
OperationPrefix: "oidc",
OperationSuffix: "role",
},
Fields: map[string]*framework.FieldSchema{
"name": {
Type: framework.TypeString,
Description: "Name of the role",
},
"key": {
Type: framework.TypeString,
Description: "The OIDC key to use for generating tokens. The specified key must already exist.",
Required: true,
},
"template": {
Type: framework.TypeString,
Description: "The template string to use for generating tokens. This may be in string-ified JSON or base64 format.",
},
"ttl": {
Type: framework.TypeDurationSecond,
Description: "TTL of the tokens generated against the role.",
Default: "24h",
},
"client_id": {
Type: framework.TypeString,
Description: "Optional client_id",
},
},
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.UpdateOperation: i.pathOIDCCreateUpdateRole,
logical.CreateOperation: i.pathOIDCCreateUpdateRole,
logical.ReadOperation: i.pathOIDCReadRole,
logical.DeleteOperation: i.pathOIDCDeleteRole,
},
ExistenceCheck: i.pathOIDCRoleExistenceCheck,
HelpSynopsis: "CRUD operations on OIDC Roles",
HelpDescription: "Create, Read, Update, and Delete OIDC Roles. OIDC tokens are generated against roles which can be configured to determine how OIDC tokens are generated.",
},
{
Pattern: "oidc/role/?$",
DisplayAttrs: &framework.DisplayAttributes{
OperationPrefix: "oidc",
OperationSuffix: "roles",
},
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.ListOperation: i.pathOIDCListRole,
},
HelpSynopsis: "List configured OIDC roles",
HelpDescription: "List all configured OIDC roles in the identity backend.",
},
{
Pattern: "oidc/introspect/?$",
DisplayAttrs: &framework.DisplayAttributes{
OperationPrefix: "oidc",
OperationVerb: "introspect",
},
Fields: map[string]*framework.FieldSchema{
"token": {
Type: framework.TypeString,
Description: "Token to verify",
},
"client_id": {
Type: framework.TypeString,
Description: "Optional client_id to verify",
},
},
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.UpdateOperation: i.pathOIDCIntrospect,
},
HelpSynopsis: "Verify the authenticity of an OIDC token",
HelpDescription: "Use this path to verify the authenticity of an OIDC token and whether the associated entity is active and enabled.",
},
}
}
func (i *IdentityStore) pathOIDCReadConfig(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
c, err := i.getOIDCConfig(ctx, req.Storage)
if err != nil {
return nil, err
}
if c == nil {
return nil, nil
}
resp := &logical.Response{
Data: map[string]interface{}{
"issuer": c.Issuer,
},
}
if i.redirectAddr == "" && c.Issuer == "" {
resp.AddWarning(`Both "issuer" and Vault's "api_addr" are empty. ` +
`The issuer claim in generated tokens will not be network reachable.`)
}
return resp, nil
}
func (i *IdentityStore) pathOIDCUpdateConfig(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
var resp *logical.Response
ns, err := namespace.FromContext(ctx)
if err != nil {
return nil, err
}
issuerRaw, ok := d.GetOk("issuer")
if !ok {
return nil, nil
}
issuer := issuerRaw.(string)
if issuer != "" {
// verify that issuer is the correct format:
// - http or https
// - host name
// - optional port
// - nothing more
valid := false
if u, err := url.Parse(issuer); err == nil {
u2 := url.URL{
Scheme: u.Scheme,
Host: u.Host,
}
valid = (*u == u2) &&
(u.Scheme == "http" || u.Scheme == "https") &&
u.Host != ""
}
if !valid {
return logical.ErrorResponse(
"invalid issuer, which must include only a scheme, host, " +
"and optional port (e.g. https://example.com:8200)"), nil
}
resp = &logical.Response{
Warnings: []string{`If "issuer" is set explicitly, all tokens must be ` +
`validated against that address, including those issued by secondary ` +
`clusters. Setting issuer to "" will restore the default behavior of ` +
`using the cluster's api_addr as the issuer.`},
}
}
c := oidcConfig{
Issuer: issuer,
}
entry, err := logical.StorageEntryJSON(oidcConfigStorageKey, c)
if err != nil {
return nil, err
}
if err := req.Storage.Put(ctx, entry); err != nil {
return nil, err
}
if err := i.oidcCache.Flush(ns); err != nil {
return nil, err
}
return resp, nil
}
func (i *IdentityStore) getOIDCConfig(ctx context.Context, s logical.Storage) (*oidcConfig, error) {
ns, err := namespace.FromContext(ctx)
if err != nil {
return nil, err
}
v, ok, err := i.oidcCache.Get(ns, "config")
if err != nil {
return nil, err
}
if ok {
return v.(*oidcConfig), nil
}
var c oidcConfig
entry, err := s.Get(ctx, oidcConfigStorageKey)
if err != nil {
return nil, err
}
if entry != nil {
if err := entry.DecodeJSON(&c); err != nil {
return nil, err
}
}
c.effectiveIssuer = c.Issuer
if c.effectiveIssuer == "" {
c.effectiveIssuer = i.redirectAddr
}
c.effectiveIssuer += "/v1/" + ns.Path + issuerPath
if err := i.oidcCache.SetDefault(ns, "config", &c); err != nil {
return nil, err
}
return &c, nil
}
// handleOIDCCreateKey is used to create a new named key or update an existing one
func (i *IdentityStore) pathOIDCCreateUpdateKey(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
ns, err := namespace.FromContext(ctx)
if err != nil {
return nil, err
}
name := d.Get("name").(string)
i.oidcLock.Lock()
defer i.oidcLock.Unlock()
var key namedKey
if req.Operation == logical.UpdateOperation {
entry, err := req.Storage.Get(ctx, namedKeyConfigPath+name)
if err != nil {
return nil, err
}
if entry != nil {
if err := entry.DecodeJSON(&key); err != nil {
return nil, err
}
}
}
if rotationPeriodRaw, ok := d.GetOk("rotation_period"); ok {
key.RotationPeriod = time.Duration(rotationPeriodRaw.(int)) * time.Second
} else if req.Operation == logical.CreateOperation {
key.RotationPeriod = time.Duration(d.Get("rotation_period").(int)) * time.Second
}
if key.RotationPeriod < 1*time.Minute {
return logical.ErrorResponse("rotation_period must be at least one minute"), nil
}
if verificationTTLRaw, ok := d.GetOk("verification_ttl"); ok {
key.VerificationTTL = time.Duration(verificationTTLRaw.(int)) * time.Second
} else if req.Operation == logical.CreateOperation {
key.VerificationTTL = time.Duration(d.Get("verification_ttl").(int)) * time.Second
}
if key.VerificationTTL > 10*key.RotationPeriod {
return logical.ErrorResponse("verification_ttl cannot be longer than 10x rotation_period"), nil
}
if req.Operation == logical.UpdateOperation {
// ensure any roles referencing this key do not already have a token_ttl
// greater than the key's verification_ttl
roles, err := i.rolesReferencingTargetKeyName(ctx, req, name)
if err != nil {
return nil, err
}
for _, role := range roles {
if role.TokenTTL > key.VerificationTTL {
errorMessage := fmt.Sprintf(
"unable to update key %q because it is currently referenced by one or more roles with a token ttl greater than %d seconds",
name,
key.VerificationTTL/time.Second,
)
return logical.ErrorResponse(errorMessage), nil
}
}
// ensure any clients referencing this key do not already have a id_token_ttl
// greater than the key's verification_ttl
clients, err := i.clientsReferencingTargetKeyName(ctx, req, name)
if err != nil {
return nil, err
}
for _, client := range clients {
if client.IDTokenTTL > key.VerificationTTL {
errorMessage := fmt.Sprintf(
"unable to update key %q because it is currently referenced by one or more clients with an id_token_ttl greater than %d seconds",
name,
key.VerificationTTL/time.Second,
)
return logical.ErrorResponse(errorMessage), nil
}
}
}
if allowedClientIDsRaw, ok := d.GetOk("allowed_client_ids"); ok {
key.AllowedClientIDs = allowedClientIDsRaw.([]string)
} else if req.Operation == logical.CreateOperation {
key.AllowedClientIDs = d.Get("allowed_client_ids").([]string)
}
prevAlgorithm := key.Algorithm
if algorithm, ok := d.GetOk("algorithm"); ok {
key.Algorithm = algorithm.(string)
} else if req.Operation == logical.CreateOperation {
key.Algorithm = d.Get("algorithm").(string)
}
if !strutil.StrListContains(supportedAlgs, key.Algorithm) {
return logical.ErrorResponse("unknown signing algorithm %q", key.Algorithm), nil
}
now := time.Now()
// Update next rotation time if it is unset or now earlier than previously set.
nextRotation := now.Add(key.RotationPeriod)
if key.NextRotation.IsZero() || nextRotation.Before(key.NextRotation) {
key.NextRotation = nextRotation
}
// generate current and next keys if creating a new key or changing algorithms
if key.Algorithm != prevAlgorithm {
err = key.generateAndSetKey(ctx, i.Logger(), req.Storage)
if err != nil {
return nil, err
}
err = key.generateAndSetNextKey(ctx, i.Logger(), req.Storage)
if err != nil {
return nil, err
}
}
if err := i.oidcCache.Flush(ns); err != nil {
return nil, err
}
// store named key
entry, err := logical.StorageEntryJSON(namedKeyConfigPath+name, key)
if err != nil {
return nil, err
}
if err := req.Storage.Put(ctx, entry); err != nil {
return nil, err
}
return nil, nil
}
// handleOIDCReadKey is used to read an existing key
func (i *IdentityStore) pathOIDCReadKey(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
name := d.Get("name").(string)
i.oidcLock.RLock()
defer i.oidcLock.RUnlock()
entry, err := req.Storage.Get(ctx, namedKeyConfigPath+name)
if err != nil {
return nil, err
}
if entry == nil {
return nil, nil
}
var storedNamedKey namedKey
if err := entry.DecodeJSON(&storedNamedKey); err != nil {
return nil, err
}
return &logical.Response{
Data: map[string]interface{}{
"rotation_period": int64(storedNamedKey.RotationPeriod.Seconds()),
"verification_ttl": int64(storedNamedKey.VerificationTTL.Seconds()),
"algorithm": storedNamedKey.Algorithm,
"allowed_client_ids": storedNamedKey.AllowedClientIDs,
},
}, nil
}
// keyIDsByName will return a slice of key IDs for the given key name
func (i *IdentityStore) keyIDsByName(ctx context.Context, s logical.Storage, name string) ([]string, error) {
var keyIDs []string
entry, err := s.Get(ctx, namedKeyConfigPath+name)
if err != nil {
return keyIDs, err
}
if entry == nil {
return keyIDs, nil
}
var key namedKey
if err := entry.DecodeJSON(&key); err != nil {
return keyIDs, err
}
for _, k := range key.KeyRing {
keyIDs = append(keyIDs, k.KeyID)
}
return keyIDs, nil
}
// rolesReferencingTargetKeyName returns a map of role names to roles
// referencing targetKeyName.
//
// Note: this is not threadsafe. It is to be called with Lock already held.
func (i *IdentityStore) rolesReferencingTargetKeyName(ctx context.Context, req *logical.Request, targetKeyName string) (map[string]role, error) {
roleNames, err := req.Storage.List(ctx, roleConfigPath)
if err != nil {
return nil, err
}
var tempRole role
roles := make(map[string]role)
for _, roleName := range roleNames {
entry, err := req.Storage.Get(ctx, roleConfigPath+roleName)
if err != nil {
return nil, err
}
if entry != nil {
if err := entry.DecodeJSON(&tempRole); err != nil {
return nil, err
}
if tempRole.Key == targetKeyName {
roles[roleName] = tempRole
}
}
}
return roles, nil
}
// roleNamesReferencingTargetKeyName returns a slice of strings of role
// names referencing targetKeyName.
//
// Note: this is not threadsafe. It is to be called with Lock already held.
func (i *IdentityStore) roleNamesReferencingTargetKeyName(ctx context.Context, req *logical.Request, targetKeyName string) ([]string, error) {
roles, err := i.rolesReferencingTargetKeyName(ctx, req, targetKeyName)
if err != nil {
return nil, err
}
var names []string
for key := range roles {
names = append(names, key)
}
sort.Strings(names)
return names, nil
}
// handleOIDCDeleteKey is used to delete a key
func (i *IdentityStore) pathOIDCDeleteKey(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
ns, err := namespace.FromContext(ctx)
if err != nil {
return nil, err
}
targetKeyName := d.Get("name").(string)
if targetKeyName == defaultKeyName {
return logical.ErrorResponse("deletion of key %q not allowed",
defaultKeyName), nil
}
i.oidcLock.Lock()
roleNames, err := i.roleNamesReferencingTargetKeyName(ctx, req, targetKeyName)
if err != nil {
i.oidcLock.Unlock()
return nil, err
}
if len(roleNames) > 0 {
errorMessage := fmt.Sprintf("unable to delete key %q because it is currently referenced by these roles: %s",
targetKeyName, strings.Join(roleNames, ", "))
i.oidcLock.Unlock()
return logical.ErrorResponse(errorMessage), logical.ErrInvalidRequest
}
clientNames, err := i.clientNamesReferencingTargetKeyName(ctx, req, targetKeyName)
if err != nil {
i.oidcLock.Unlock()
return nil, err
}
if len(clientNames) > 0 {
errorMessage := fmt.Sprintf("unable to delete key %q because it is currently referenced by these clients: %s",
targetKeyName, strings.Join(clientNames, ", "))
i.oidcLock.Unlock()
return logical.ErrorResponse(errorMessage), logical.ErrInvalidRequest
}
// key can safely be deleted now
err = req.Storage.Delete(ctx, namedKeyConfigPath+targetKeyName)
if err != nil {
i.oidcLock.Unlock()
return nil, err
}
i.oidcLock.Unlock()
_, err = i.expireOIDCPublicKeys(ctx, req.Storage)
if err != nil {
return nil, err
}
if err := i.oidcCache.Flush(ns); err != nil {
return nil, err
}
return nil, nil
}
// handleOIDCListKey is used to list named keys
func (i *IdentityStore) pathOIDCListKey(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
i.oidcLock.RLock()
defer i.oidcLock.RUnlock()
keys, err := req.Storage.List(ctx, namedKeyConfigPath)
if err != nil {
return nil, err
}
return logical.ListResponse(keys), nil
}
// pathOIDCRotateKey is used to manually trigger a rotation on the named key
func (i *IdentityStore) pathOIDCRotateKey(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
ns, err := namespace.FromContext(ctx)
if err != nil {
return nil, err
}
name := d.Get("name").(string)
i.oidcLock.Lock()
defer i.oidcLock.Unlock()
// load the named key and perform a rotation
entry, err := req.Storage.Get(ctx, namedKeyConfigPath+name)
if err != nil {
return nil, err
}
if entry == nil {
return logical.ErrorResponse("no named key found at %q", name), logical.ErrInvalidRequest
}
var storedNamedKey namedKey
if err := entry.DecodeJSON(&storedNamedKey); err != nil {
return nil, err
}
storedNamedKey.name = name
// call rotate with an appropriate overrideTTL where < 0 means no override
verificationTTLOverride := -1 * time.Second
if ttlRaw, ok := d.GetOk("verification_ttl"); ok {
verificationTTLOverride = time.Duration(ttlRaw.(int)) * time.Second
}
if err := storedNamedKey.rotate(ctx, i.Logger(), req.Storage, verificationTTLOverride); err != nil {
return nil, err
}
if err := i.oidcCache.Flush(ns); err != nil {
return nil, err
}
return nil, nil
}
func (i *IdentityStore) pathOIDCKeyExistenceCheck(ctx context.Context, req *logical.Request, d *framework.FieldData) (bool, error) {
name := d.Get("name").(string)
i.oidcLock.RLock()
defer i.oidcLock.RUnlock()
entry, err := req.Storage.Get(ctx, namedKeyConfigPath+name)
if err != nil {
return false, err
}
return entry != nil, nil
}
// handleOIDCGenerateSignToken generates and signs an OIDC token
func (i *IdentityStore) pathOIDCGenerateToken(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
ns, err := namespace.FromContext(ctx)
if err != nil {
return nil, err
}
roleName := d.Get("name").(string)
role, err := i.getOIDCRole(ctx, req.Storage, roleName)
if err != nil {
return nil, err
}
if role == nil {
return logical.ErrorResponse("role %q not found", roleName), nil
}
key, err := i.getNamedKey(ctx, req.Storage, role.Key)
if err != nil {
return nil, err
}
if key == nil {
return logical.ErrorResponse("key %q not found", role.Key), nil
}
// Validate that the role is allowed to sign with its key (the key could have been updated)
if !strutil.StrListContains(key.AllowedClientIDs, "*") && !strutil.StrListContains(key.AllowedClientIDs, role.ClientID) {
return logical.ErrorResponse("the key %q does not list the client ID of the role %q as an allowed client ID", role.Key, roleName), nil
}
// generate an OIDC token from entity data
if req.EntityID == "" {
return logical.ErrorResponse("no entity associated with the request's token"), nil
}
config, err := i.getOIDCConfig(ctx, req.Storage)
if err != nil {
return nil, err
}
retResp := &logical.Response{}
expiry := role.TokenTTL
if expiry > key.VerificationTTL {
expiry = key.VerificationTTL
retResp.AddWarning(fmt.Sprintf("a role's token ttl cannot be longer "+
"than the verification_ttl of the key it references, setting token ttl to %d", expiry))
}
now := time.Now()
idToken := idToken{
Issuer: config.effectiveIssuer,
Namespace: ns.ID,
Subject: req.EntityID,
Audience: role.ClientID,
Expiry: now.Add(expiry).Unix(),
IssuedAt: now.Unix(),
}
e, err := i.MemDBEntityByID(req.EntityID, true)
if err != nil {
return nil, err
}
if e == nil {
return nil, fmt.Errorf("error loading entity ID %q", req.EntityID)
}
groups, inheritedGroups, err := i.groupsByEntityID(e.ID)
if err != nil {
return nil, err
}
groups = append(groups, inheritedGroups...)
// Parse and integrate the populated template. Structural errors with the template _should_
// be caught during configuration. Error found during runtime will be logged, but they will
// not block generation of the basic ID token. They should not be returned to the requester.
_, populatedTemplate, err := identitytpl.PopulateString(identitytpl.PopulateStringInput{
Mode: identitytpl.JSONTemplating,
String: role.Template,
Entity: identity.ToSDKEntity(e),
Groups: identity.ToSDKGroups(groups),
NamespaceID: ns.ID,
})
if err != nil {
i.Logger().Warn("error populating OIDC token template", "template", role.Template, "error", err)
}
payload, err := idToken.generatePayload(i.Logger(), populatedTemplate)
if err != nil {
i.Logger().Warn("error populating OIDC token template", "error", err)
}
signedIdToken, err := key.signPayload(payload)
if err != nil {
return nil, fmt.Errorf("error signing OIDC token: %w", err)
}
retResp.Data = map[string]interface{}{
"token": signedIdToken,
"client_id": role.ClientID,
"ttl": int64(role.TokenTTL.Seconds()),
}
return retResp, nil
}
func (i *IdentityStore) getNamedKey(ctx context.Context, s logical.Storage, name string) (*namedKey, error) {
ns, err := namespace.FromContext(ctx)
if err != nil {
return nil, err
}
// Attempt to get the key from the cache
keyRaw, found, err := i.oidcCache.Get(ns, "namedKeys/"+name)
if err != nil {
return nil, err
}
if key, ok := keyRaw.(*namedKey); ok && found {
return key, nil
}
// Fall back to reading the key from storage
entry, err := s.Get(ctx, namedKeyConfigPath+name)
if err != nil {
return nil, err
}
if entry == nil {
return nil, nil