-
Notifications
You must be signed in to change notification settings - Fork 4.1k
/
identity_store_oidc_provider.go
2489 lines (2179 loc) · 78.2 KB
/
identity_store_oidc_provider.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
package vault
import (
"context"
"crypto/sha256"
"crypto/sha512"
"crypto/subtle"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"hash"
"net/http"
"net/url"
"sort"
"strings"
"time"
"github.com/hashicorp/go-memdb"
"github.com/hashicorp/go-secure-stdlib/base62"
"github.com/hashicorp/go-secure-stdlib/strutil"
"github.com/hashicorp/vault/helper/identity"
"github.com/hashicorp/vault/helper/namespace"
"github.com/hashicorp/vault/sdk/framework"
"github.com/hashicorp/vault/sdk/helper/identitytpl"
"github.com/hashicorp/vault/sdk/logical"
"gopkg.in/square/go-jose.v2"
)
const (
// OIDC-related constants
openIDScope = "openid"
scopesDelimiter = " "
accessTokenScopesMeta = "scopes"
accessTokenClientIDMeta = "client_id"
clientIDLength = 32
clientSecretLength = 64
clientSecretPrefix = "hvo_secret_"
// Storage path constants
oidcProviderPrefix = "oidc_provider/"
assignmentPath = oidcProviderPrefix + "assignment/"
scopePath = oidcProviderPrefix + "scope/"
clientPath = oidcProviderPrefix + "client/"
providerPath = oidcProviderPrefix + "provider/"
// Error constants used in the Authorization Endpoint. See details at
// https://openid.net/specs/openid-connect-core-1_0.html#AuthError.
ErrAuthUnsupportedResponseType = "unsupported_response_type"
ErrAuthInvalidRequest = "invalid_request"
ErrAuthAccessDenied = "access_denied"
ErrAuthUnauthorizedClient = "unauthorized_client"
ErrAuthServerError = "server_error"
ErrAuthRequestNotSupported = "request_not_supported"
ErrAuthRequestURINotSupported = "request_uri_not_supported"
// Error constants used in the Token Endpoint. See details at
// https://openid.net/specs/openid-connect-core-1_0.html#TokenErrorResponse
ErrTokenInvalidRequest = "invalid_request"
ErrTokenInvalidClient = "invalid_client"
ErrTokenInvalidGrant = "invalid_grant"
ErrTokenUnsupportedGrantType = "unsupported_grant_type"
ErrTokenServerError = "server_error"
// Error constants used in the UserInfo Endpoint. See details at
// https://openid.net/specs/openid-connect-core-1_0.html#UserInfoError
ErrUserInfoServerError = "server_error"
ErrUserInfoInvalidRequest = "invalid_request"
ErrUserInfoInvalidToken = "invalid_token"
ErrUserInfoAccessDenied = "access_denied"
// The following errors are used by the UI for specific behavior of
// the OIDC specification. Any changes to their values must come with
// a corresponding change in the UI code.
ErrAuthInvalidClientID = "invalid_client_id"
ErrAuthInvalidRedirectURI = "invalid_redirect_uri"
ErrAuthMaxAgeReAuthenticate = "max_age_violation"
)
type assignment struct {
GroupIDs []string `json:"group_ids"`
EntityIDs []string `json:"entity_ids"`
}
type scope struct {
Template string `json:"template"`
Description string `json:"description"`
}
type client struct {
// Used for indexing in memdb
Name string `json:"name"`
NamespaceID string `json:"namespace_id"`
// User-supplied parameters
RedirectURIs []string `json:"redirect_uris"`
Assignments []string `json:"assignments"`
Key string `json:"key"`
IDTokenTTL time.Duration `json:"id_token_ttl"`
AccessTokenTTL time.Duration `json:"access_token_ttl"`
// Generated values that are used in OIDC endpoints
ClientID string `json:"client_id"`
ClientSecret string `json:"client_secret"`
}
type provider struct {
Issuer string `json:"issuer"`
AllowedClientIDs []string `json:"allowed_client_ids"`
ScopesSupported []string `json:"scopes_supported"`
// effectiveIssuer is a calculated field and will be either Issuer (if
// that's set) or the Vault instance's api_addr.
effectiveIssuer string
}
type providerDiscovery struct {
Issuer string `json:"issuer"`
Keys string `json:"jwks_uri"`
AuthorizationEndpoint string `json:"authorization_endpoint"`
TokenEndpoint string `json:"token_endpoint"`
UserinfoEndpoint string `json:"userinfo_endpoint"`
RequestURIParameter bool `json:"request_uri_parameter_supported"`
IDTokenAlgs []string `json:"id_token_signing_alg_values_supported"`
ResponseTypes []string `json:"response_types_supported"`
Scopes []string `json:"scopes_supported"`
Subjects []string `json:"subject_types_supported"`
GrantTypes []string `json:"grant_types_supported"`
AuthMethods []string `json:"token_endpoint_auth_methods_supported"`
}
type authCodeCacheEntry struct {
clientID string
entityID string
redirectURI string
nonce string
scopes []string
authTime time.Time
}
func oidcProviderPaths(i *IdentityStore) []*framework.Path {
return []*framework.Path{
{
Pattern: "oidc/assignment/" + framework.GenericNameRegex("name"),
Fields: map[string]*framework.FieldSchema{
"name": {
Type: framework.TypeString,
Description: "Name of the assignment",
},
"entity_ids": {
Type: framework.TypeCommaStringSlice,
Description: "Comma separated string or array of identity entity IDs",
},
"group_ids": {
Type: framework.TypeCommaStringSlice,
Description: "Comma separated string or array of identity group IDs",
},
},
Operations: map[logical.Operation]framework.OperationHandler{
logical.UpdateOperation: &framework.PathOperation{
Callback: i.pathOIDCCreateUpdateAssignment,
},
logical.CreateOperation: &framework.PathOperation{
Callback: i.pathOIDCCreateUpdateAssignment,
},
logical.ReadOperation: &framework.PathOperation{
Callback: i.pathOIDCReadAssignment,
},
logical.DeleteOperation: &framework.PathOperation{
Callback: i.pathOIDCDeleteAssignment,
},
},
ExistenceCheck: i.pathOIDCAssignmentExistenceCheck,
HelpSynopsis: "CRUD operations for OIDC assignments.",
HelpDescription: "Create, Read, Update, and Delete OIDC assignments.",
},
{
Pattern: "oidc/assignment/?$",
Operations: map[logical.Operation]framework.OperationHandler{
logical.ListOperation: &framework.PathOperation{
Callback: i.pathOIDCListAssignment,
},
},
HelpSynopsis: "List OIDC assignments",
HelpDescription: "List all configured OIDC assignments in the identity backend.",
},
{
Pattern: "oidc/scope/" + framework.GenericNameRegex("name"),
Fields: map[string]*framework.FieldSchema{
"name": {
Type: framework.TypeString,
Description: "Name of the scope",
},
"template": {
Type: framework.TypeString,
Description: "The template string to use for the scope. This may be in string-ified JSON or base64 format.",
},
"description": {
Type: framework.TypeString,
Description: "The description of the scope",
},
},
Operations: map[logical.Operation]framework.OperationHandler{
logical.UpdateOperation: &framework.PathOperation{
Callback: i.pathOIDCCreateUpdateScope,
},
logical.CreateOperation: &framework.PathOperation{
Callback: i.pathOIDCCreateUpdateScope,
},
logical.ReadOperation: &framework.PathOperation{
Callback: i.pathOIDCReadScope,
},
logical.DeleteOperation: &framework.PathOperation{
Callback: i.pathOIDCDeleteScope,
},
},
ExistenceCheck: i.pathOIDCScopeExistenceCheck,
HelpSynopsis: "CRUD operations for OIDC scopes.",
HelpDescription: "Create, Read, Update, and Delete OIDC scopes.",
},
{
Pattern: "oidc/scope/?$",
Operations: map[logical.Operation]framework.OperationHandler{
logical.ListOperation: &framework.PathOperation{
Callback: i.pathOIDCListScope,
},
},
HelpSynopsis: "List OIDC scopes",
HelpDescription: "List all configured OIDC scopes in the identity backend.",
},
{
Pattern: "oidc/client/" + framework.GenericNameRegex("name"),
Fields: map[string]*framework.FieldSchema{
"name": {
Type: framework.TypeString,
Description: "Name of the client.",
},
"redirect_uris": {
Type: framework.TypeCommaStringSlice,
Description: "Comma separated string or array of redirect URIs used by the client. One of these values must exactly match the redirect_uri parameter value used in each authentication request.",
},
"assignments": {
Type: framework.TypeCommaStringSlice,
Description: "Comma separated string or array of assignment resources.",
},
"key": {
Type: framework.TypeString,
Description: "A reference to a named key resource. Cannot be modified after creation.",
Required: true,
},
"id_token_ttl": {
Type: framework.TypeDurationSecond,
Description: "The time-to-live for ID tokens obtained by the client.",
Default: "24h",
},
"access_token_ttl": {
Type: framework.TypeDurationSecond,
Description: "The time-to-live for access tokens obtained by the client.",
Default: "24h",
},
},
Operations: map[logical.Operation]framework.OperationHandler{
logical.UpdateOperation: &framework.PathOperation{
Callback: i.pathOIDCCreateUpdateClient,
},
logical.CreateOperation: &framework.PathOperation{
Callback: i.pathOIDCCreateUpdateClient,
},
logical.ReadOperation: &framework.PathOperation{
Callback: i.pathOIDCReadClient,
},
logical.DeleteOperation: &framework.PathOperation{
Callback: i.pathOIDCDeleteClient,
},
},
ExistenceCheck: i.pathOIDCClientExistenceCheck,
HelpSynopsis: "CRUD operations for OIDC clients.",
HelpDescription: "Create, Read, Update, and Delete OIDC clients.",
},
{
Pattern: "oidc/client/?$",
Operations: map[logical.Operation]framework.OperationHandler{
logical.ListOperation: &framework.PathOperation{
Callback: i.pathOIDCListClient,
},
},
HelpSynopsis: "List OIDC clients",
HelpDescription: "List all configured OIDC clients in the identity backend.",
},
{
Pattern: "oidc/provider/" + framework.GenericNameRegex("name"),
Fields: map[string]*framework.FieldSchema{
"name": {
Type: framework.TypeString,
Description: "Name of the provider",
},
"issuer": {
Type: framework.TypeString,
Description: "Specifies what will be used for the iss claim of ID tokens.",
},
"allowed_client_ids": {
Type: framework.TypeCommaStringSlice,
Description: "The client IDs that are permitted to use the provider",
},
"scopes_supported": {
Type: framework.TypeCommaStringSlice,
Description: "The scopes supported for requesting on the provider",
},
},
Operations: map[logical.Operation]framework.OperationHandler{
logical.UpdateOperation: &framework.PathOperation{
Callback: i.pathOIDCCreateUpdateProvider,
},
logical.CreateOperation: &framework.PathOperation{
Callback: i.pathOIDCCreateUpdateProvider,
},
logical.ReadOperation: &framework.PathOperation{
Callback: i.pathOIDCReadProvider,
},
logical.DeleteOperation: &framework.PathOperation{
Callback: i.pathOIDCDeleteProvider,
},
},
ExistenceCheck: i.pathOIDCProviderExistenceCheck,
HelpSynopsis: "CRUD operations for OIDC providers.",
HelpDescription: "Create, Read, Update, and Delete OIDC named providers.",
},
{
Pattern: "oidc/provider/?$",
Operations: map[logical.Operation]framework.OperationHandler{
logical.ListOperation: &framework.PathOperation{
Callback: i.pathOIDCListProvider,
},
},
HelpSynopsis: "List OIDC providers",
HelpDescription: "List all configured OIDC providers in the identity backend.",
},
{
Pattern: "oidc/provider/" + framework.GenericNameRegex("name") + "/.well-known/openid-configuration",
Fields: map[string]*framework.FieldSchema{
"name": {
Type: framework.TypeString,
Description: "Name of the provider",
},
},
Operations: map[logical.Operation]framework.OperationHandler{
logical.ReadOperation: &framework.PathOperation{
Callback: i.pathOIDCProviderDiscovery,
},
},
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/provider/" + framework.GenericNameRegex("name") + "/.well-known/keys",
Fields: map[string]*framework.FieldSchema{
"name": {
Type: framework.TypeString,
Description: "Name of the provider",
},
},
Operations: map[logical.Operation]framework.OperationHandler{
logical.ReadOperation: &framework.PathOperation{
Callback: i.pathOIDCReadProviderPublicKeys,
},
},
HelpSynopsis: "Retrieve public keys",
HelpDescription: "Returns the public portion of keys for a named OIDC provider. Clients can use them to validate the authenticity of an ID token.",
},
{
Pattern: "oidc/provider/" + framework.GenericNameRegex("name") + "/authorize",
Fields: map[string]*framework.FieldSchema{
"name": {
Type: framework.TypeString,
Description: "Name of the provider",
},
"client_id": {
Type: framework.TypeString,
Description: "The ID of the requesting client.",
Required: true,
},
"scope": {
Type: framework.TypeString,
Description: "A space-delimited, case-sensitive list of scopes to be requested. The 'openid' scope is required.",
Required: true,
},
"redirect_uri": {
Type: framework.TypeString,
Description: "The redirection URI to which the response will be sent.",
Required: true,
},
"response_type": {
Type: framework.TypeString,
Description: "The OIDC authentication flow to be used. The following response types are supported: 'code'",
Required: true,
},
"state": {
Type: framework.TypeString,
Description: "The value used to maintain state between the authentication request and client.",
Required: true,
},
"nonce": {
Type: framework.TypeString,
Description: "The value that will be returned in the ID token nonce claim after a token exchange.",
Required: true,
},
"max_age": {
Type: framework.TypeInt,
Description: "The allowable elapsed time in seconds since the last time the end-user was actively authenticated.",
},
},
Operations: map[logical.Operation]framework.OperationHandler{
logical.ReadOperation: &framework.PathOperation{
Callback: i.pathOIDCAuthorize,
ForwardPerformanceStandby: true,
ForwardPerformanceSecondary: false,
},
logical.UpdateOperation: &framework.PathOperation{
Callback: i.pathOIDCAuthorize,
ForwardPerformanceStandby: true,
ForwardPerformanceSecondary: false,
},
},
HelpSynopsis: "Provides the OIDC Authorization Endpoint.",
HelpDescription: "The OIDC Authorization Endpoint performs authentication and authorization by using request parameters defined by OpenID Connect (OIDC).",
},
{
Pattern: "oidc/provider/" + framework.GenericNameRegex("name") + "/token",
Fields: map[string]*framework.FieldSchema{
"name": {
Type: framework.TypeString,
Description: "Name of the provider",
},
"code": {
Type: framework.TypeString,
Description: "The authorization code received from the provider's authorization endpoint.",
Required: true,
},
"grant_type": {
Type: framework.TypeString,
Description: "The authorization grant type. The following grant types are supported: 'authorization_code'.",
Required: true,
},
"redirect_uri": {
Type: framework.TypeString,
Description: "The callback location where the authentication response was sent.",
Required: true,
},
// The client_id and client_secret are provided to the token endpoint via
// the client_secret_basic authentication method, which uses the HTTP Basic
// authentication scheme. See the OIDC spec for details at:
// https://openid.net/specs/openid-connect-core-1_0.html#ClientAuthentication
},
Operations: map[logical.Operation]framework.OperationHandler{
logical.UpdateOperation: &framework.PathOperation{
Callback: i.pathOIDCToken,
ForwardPerformanceStandby: true,
ForwardPerformanceSecondary: false,
},
},
HelpSynopsis: "Provides the OIDC Token Endpoint.",
HelpDescription: "The OIDC Token Endpoint allows a client to exchange its Authorization Grant for an Access Token and ID Token.",
},
{
Pattern: "oidc/provider/" + framework.GenericNameRegex("name") + "/userinfo",
Fields: map[string]*framework.FieldSchema{
"name": {
Type: framework.TypeString,
Description: "Name of the provider",
},
},
Operations: map[logical.Operation]framework.OperationHandler{
logical.ReadOperation: &framework.PathOperation{
Callback: i.pathOIDCUserInfo,
},
logical.UpdateOperation: &framework.PathOperation{
Callback: i.pathOIDCUserInfo,
},
},
HelpSynopsis: "Provides the OIDC UserInfo Endpoint.",
HelpDescription: "The OIDC UserInfo Endpoint returns claims about the authenticated end-user.",
},
}
}
// clientsReferencingTargetAssignmentName returns a map of client names to
// clients referencing targetAssignmentName.
func (i *IdentityStore) clientsReferencingTargetAssignmentName(ctx context.Context, req *logical.Request, targetAssignmentName string) (map[string]client, error) {
clientNames, err := req.Storage.List(ctx, clientPath)
if err != nil {
return nil, err
}
var tempClient client
clients := make(map[string]client)
for _, clientName := range clientNames {
entry, err := req.Storage.Get(ctx, clientPath+clientName)
if err != nil {
return nil, err
}
if entry != nil {
if err := entry.DecodeJSON(&tempClient); err != nil {
return nil, err
}
for _, a := range tempClient.Assignments {
if a == targetAssignmentName {
clients[clientName] = tempClient
}
}
}
}
return clients, nil
}
// clientNamesReferencingTargetAssignmentName returns a slice of strings of client
// names referencing targetAssignmentName.
func (i *IdentityStore) clientNamesReferencingTargetAssignmentName(ctx context.Context, req *logical.Request, targetAssignmentName string) ([]string, error) {
clients, err := i.clientsReferencingTargetAssignmentName(ctx, req, targetAssignmentName)
if err != nil {
return nil, err
}
var names []string
for client := range clients {
names = append(names, client)
}
sort.Strings(names)
return names, nil
}
// clientsReferencingTargetKeyName returns a map of client names to
// clients referencing targetKeyName.
func (i *IdentityStore) clientsReferencingTargetKeyName(ctx context.Context, req *logical.Request, targetKeyName string) (map[string]client, error) {
clientNames, err := req.Storage.List(ctx, clientPath)
if err != nil {
return nil, err
}
var tempClient client
clients := make(map[string]client)
for _, clientName := range clientNames {
entry, err := req.Storage.Get(ctx, clientPath+clientName)
if err != nil {
return nil, err
}
if entry != nil {
if err := entry.DecodeJSON(&tempClient); err != nil {
return nil, err
}
if tempClient.Key == targetKeyName {
clients[clientName] = tempClient
}
}
}
return clients, nil
}
// clientNamesReferencingTargetKeyName returns a slice of strings of client
// names referencing targetKeyName.
func (i *IdentityStore) clientNamesReferencingTargetKeyName(ctx context.Context, req *logical.Request, targetKeyName string) ([]string, error) {
clients, err := i.clientsReferencingTargetKeyName(ctx, req, targetKeyName)
if err != nil {
return nil, err
}
var names []string
for client := range clients {
names = append(names, client)
}
sort.Strings(names)
return names, nil
}
// providersReferencingTargetScopeName returns a list of provider names referencing targetScopeName.
// Not threadsafe. To be called with lock already held.
func (i *IdentityStore) providersReferencingTargetScopeName(ctx context.Context, req *logical.Request, targetScopeName string) ([]string, error) {
providerNames, err := req.Storage.List(ctx, providerPath)
if err != nil {
return nil, err
}
var tempProvider provider
var providers []string
for _, providerName := range providerNames {
entry, err := req.Storage.Get(ctx, providerPath+providerName)
if err != nil {
return nil, err
}
if entry != nil {
if err := entry.DecodeJSON(&tempProvider); err != nil {
return nil, err
}
for _, a := range tempProvider.ScopesSupported {
if a == targetScopeName {
providers = append(providers, providerName)
}
}
}
}
return providers, nil
}
// pathOIDCCreateUpdateAssignment is used to create a new assignment or update an existing one
func (i *IdentityStore) pathOIDCCreateUpdateAssignment(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
name := d.Get("name").(string)
var assignment assignment
if req.Operation == logical.UpdateOperation {
entry, err := req.Storage.Get(ctx, assignmentPath+name)
if err != nil {
return nil, err
}
if entry != nil {
if err := entry.DecodeJSON(&assignment); err != nil {
return nil, err
}
}
}
if entitiesRaw, ok := d.GetOk("entity_ids"); ok {
assignment.EntityIDs = entitiesRaw.([]string)
} else if req.Operation == logical.CreateOperation {
assignment.EntityIDs = d.Get("entity_ids").([]string)
}
if groupsRaw, ok := d.GetOk("group_ids"); ok {
assignment.GroupIDs = groupsRaw.([]string)
} else if req.Operation == logical.CreateOperation {
assignment.GroupIDs = d.Get("group_ids").([]string)
}
// remove duplicates and lowercase entities and groups
assignment.EntityIDs = strutil.RemoveDuplicates(assignment.EntityIDs, true)
assignment.GroupIDs = strutil.RemoveDuplicates(assignment.GroupIDs, true)
// store assignment
entry, err := logical.StorageEntryJSON(assignmentPath+name, assignment)
if err != nil {
return nil, err
}
if err := req.Storage.Put(ctx, entry); err != nil {
return nil, err
}
return nil, nil
}
// pathOIDCListAssignment is used to list assignments
func (i *IdentityStore) pathOIDCListAssignment(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
assignments, err := req.Storage.List(ctx, assignmentPath)
if err != nil {
return nil, err
}
return logical.ListResponse(assignments), nil
}
// pathOIDCReadAssignment is used to read an existing assignment
func (i *IdentityStore) pathOIDCReadAssignment(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
name := d.Get("name").(string)
assignment, err := i.getOIDCAssignment(ctx, req.Storage, name)
if err != nil {
return nil, err
}
if assignment == nil {
return nil, nil
}
return &logical.Response{
Data: map[string]interface{}{
"group_ids": assignment.GroupIDs,
"entity_ids": assignment.EntityIDs,
},
}, nil
}
func (i *IdentityStore) getOIDCAssignment(ctx context.Context, s logical.Storage, name string) (*assignment, error) {
entry, err := s.Get(ctx, assignmentPath+name)
if err != nil {
return nil, err
}
if entry == nil {
return nil, nil
}
var assignment assignment
if err := entry.DecodeJSON(&assignment); err != nil {
return nil, err
}
return &assignment, nil
}
// pathOIDCDeleteAssignment is used to delete an assignment
func (i *IdentityStore) pathOIDCDeleteAssignment(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
name := d.Get("name").(string)
clientNames, err := i.clientNamesReferencingTargetAssignmentName(ctx, req, name)
if err != nil {
return nil, err
}
if len(clientNames) > 0 {
errorMessage := fmt.Sprintf("unable to delete assignment %q because it is currently referenced by these clients: %s",
name, strings.Join(clientNames, ", "))
return logical.ErrorResponse(errorMessage), logical.ErrInvalidRequest
}
err = req.Storage.Delete(ctx, assignmentPath+name)
if err != nil {
return nil, err
}
return nil, nil
}
func (i *IdentityStore) pathOIDCAssignmentExistenceCheck(ctx context.Context, req *logical.Request, d *framework.FieldData) (bool, error) {
name := d.Get("name").(string)
entry, err := req.Storage.Get(ctx, assignmentPath+name)
if err != nil {
return false, err
}
return entry != nil, nil
}
// pathOIDCCreateUpdateScope is used to create a new scope or update an existing one
func (i *IdentityStore) pathOIDCCreateUpdateScope(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
name := d.Get("name").(string)
if name == openIDScope {
return logical.ErrorResponse("the %q scope name is reserved", openIDScope), nil
}
var scope scope
if req.Operation == logical.UpdateOperation {
entry, err := req.Storage.Get(ctx, scopePath+name)
if err != nil {
return nil, err
}
if entry != nil {
if err := entry.DecodeJSON(&scope); err != nil {
return nil, err
}
}
}
if descriptionRaw, ok := d.GetOk("description"); ok {
scope.Description = descriptionRaw.(string)
} else if req.Operation == logical.CreateOperation {
scope.Description = d.Get("description").(string)
}
if templateRaw, ok := d.GetOk("template"); ok {
scope.Template = templateRaw.(string)
} else if req.Operation == logical.CreateOperation {
scope.Template = d.Get("template").(string)
}
// Attempt to decode as base64 and use that if it works
if decoded, err := base64.StdEncoding.DecodeString(scope.Template); err == nil {
scope.Template = string(decoded)
}
// Validate that template can be parsed and results in valid JSON
if scope.Template != "" {
_, populatedTemplate, err := identitytpl.PopulateString(identitytpl.PopulateStringInput{
Mode: identitytpl.JSONTemplating,
String: scope.Template,
Entity: new(logical.Entity),
Groups: make([]*logical.Group, 0),
})
if err != nil {
return logical.ErrorResponse("error parsing template: %s", err.Error()), nil
}
var tmp map[string]interface{}
if err := json.Unmarshal([]byte(populatedTemplate), &tmp); err != nil {
return logical.ErrorResponse("error parsing template JSON: %s", err.Error()), nil
}
for key := range tmp {
if strutil.StrListContains(requiredClaims, key) {
return logical.ErrorResponse(`top level key %q not allowed. Restricted keys: %s`,
key, strings.Join(requiredClaims, ", ")), nil
}
}
}
// store scope
entry, err := logical.StorageEntryJSON(scopePath+name, scope)
if err != nil {
return nil, err
}
if err := req.Storage.Put(ctx, entry); err != nil {
return nil, err
}
return nil, nil
}
// pathOIDCListScope is used to list scopes
func (i *IdentityStore) pathOIDCListScope(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
scopes, err := req.Storage.List(ctx, scopePath)
if err != nil {
return nil, err
}
return logical.ListResponse(scopes), nil
}
// pathOIDCReadScope is used to read an existing scope
func (i *IdentityStore) pathOIDCReadScope(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
name := d.Get("name").(string)
scope, err := i.getOIDCScope(ctx, req.Storage, name)
if err != nil {
return nil, err
}
if scope == nil {
return nil, nil
}
return &logical.Response{
Data: map[string]interface{}{
"template": scope.Template,
"description": scope.Description,
},
}, nil
}
func (i *IdentityStore) getOIDCScope(ctx context.Context, s logical.Storage, name string) (*scope, error) {
entry, err := s.Get(ctx, scopePath+name)
if err != nil {
return nil, err
}
if entry == nil {
return nil, nil
}
var scope scope
if err := entry.DecodeJSON(&scope); err != nil {
return nil, err
}
return &scope, nil
}
// pathOIDCDeleteScope is used to delete an scope
func (i *IdentityStore) pathOIDCDeleteScope(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
name := d.Get("name").(string)
targetScopeName := d.Get("name").(string)
providerNames, err := i.providersReferencingTargetScopeName(ctx, req, targetScopeName)
if err != nil {
return nil, err
}
if len(providerNames) > 0 {
errorMessage := fmt.Sprintf("unable to delete scope %q because it is currently referenced by these providers: %s",
targetScopeName, strings.Join(providerNames, ", "))
return logical.ErrorResponse(errorMessage), logical.ErrInvalidRequest
}
err = req.Storage.Delete(ctx, scopePath+name)
if err != nil {
return nil, err
}
return nil, nil
}
func (i *IdentityStore) pathOIDCScopeExistenceCheck(ctx context.Context, req *logical.Request, d *framework.FieldData) (bool, error) {
name := d.Get("name").(string)
entry, err := req.Storage.Get(ctx, scopePath+name)
if err != nil {
return false, err
}
return entry != nil, nil
}
// pathOIDCCreateUpdateClient is used to create a new client or update an existing one
func (i *IdentityStore) pathOIDCCreateUpdateClient(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
name := d.Get("name").(string)
ns, err := namespace.FromContext(ctx)
if err != nil {
return nil, err
}
client := client{
Name: name,
NamespaceID: ns.ID,
}
if req.Operation == logical.UpdateOperation {
entry, err := req.Storage.Get(ctx, clientPath+name)
if err != nil {
return nil, err
}
if entry != nil {
if err := entry.DecodeJSON(&client); err != nil {
return nil, err
}
}
}
if redirectURIsRaw, ok := d.GetOk("redirect_uris"); ok {
client.RedirectURIs = redirectURIsRaw.([]string)
} else if req.Operation == logical.CreateOperation {
client.RedirectURIs = d.Get("redirect_uris").([]string)
}
if assignmentsRaw, ok := d.GetOk("assignments"); ok {
client.Assignments = assignmentsRaw.([]string)
} else if req.Operation == logical.CreateOperation {
client.Assignments = d.Get("assignments").([]string)
}
// remove duplicate assignments and redirect URIs
client.Assignments = strutil.RemoveDuplicates(client.Assignments, false)
client.RedirectURIs = strutil.RemoveDuplicates(client.RedirectURIs, false)
// enforce assignment existence
for _, assignment := range client.Assignments {
entry, err := req.Storage.Get(ctx, assignmentPath+assignment)
if err != nil {
return nil, err
}
if entry == nil {
return logical.ErrorResponse("assignment %q does not exist", assignment), nil
}
}
if keyRaw, ok := d.GetOk("key"); ok {
key := keyRaw.(string)
if req.Operation == logical.UpdateOperation && client.Key != key {
return logical.ErrorResponse("key modification is not allowed"), nil
}
client.Key = key
} else if req.Operation == logical.CreateOperation {
client.Key = d.Get("key").(string)
}
if client.Key == "" {
return logical.ErrorResponse("the key parameter is required"), nil
}
var key namedKey
// enforce key existence on client creation
entry, err := req.Storage.Get(ctx, namedKeyConfigPath+client.Key)
if err != nil {
return nil, err
}
if entry == nil {
return logical.ErrorResponse("key %q does not exist", client.Key), nil
}
if err := entry.DecodeJSON(&key); err != nil {
return nil, err
}
if idTokenTTLRaw, ok := d.GetOk("id_token_ttl"); ok {
client.IDTokenTTL = time.Duration(idTokenTTLRaw.(int)) * time.Second
} else if req.Operation == logical.CreateOperation {
client.IDTokenTTL = time.Duration(d.Get("id_token_ttl").(int)) * time.Second
}
if client.IDTokenTTL > key.VerificationTTL {
return logical.ErrorResponse("a client's id_token_ttl cannot be greater than the verification_ttl of the key it references"), nil
}
if accessTokenTTLRaw, ok := d.GetOk("access_token_ttl"); ok {
client.AccessTokenTTL = time.Duration(accessTokenTTLRaw.(int)) * time.Second
} else if req.Operation == logical.CreateOperation {
client.AccessTokenTTL = time.Duration(d.Get("access_token_ttl").(int)) * time.Second
}
if client.ClientID == "" {
// generate client_id
clientID, err := base62.Random(clientIDLength)
if err != nil {
return nil, err
}
client.ClientID = clientID
}
if client.ClientSecret == "" {
// generate client_secret
clientSecret, err := base62.Random(clientSecretLength)
if err != nil {
return nil, err
}
client.ClientSecret = clientSecretPrefix + clientSecret
}
// invalidate the cached client in memdb
if err := i.memDBDeleteClientByName(ctx, name); err != nil {