-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
path_role.go
2347 lines (2046 loc) · 78.1 KB
/
path_role.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 approle
import (
"context"
"fmt"
"strings"
"time"
"github.com/fatih/structs"
"github.com/hashicorp/errwrap"
"github.com/hashicorp/go-uuid"
"github.com/hashicorp/vault/helper/cidrutil"
"github.com/hashicorp/vault/helper/consts"
"github.com/hashicorp/vault/helper/locksutil"
"github.com/hashicorp/vault/helper/policyutil"
"github.com/hashicorp/vault/helper/strutil"
"github.com/hashicorp/vault/logical"
"github.com/hashicorp/vault/logical/framework"
)
// roleStorageEntry stores all the options that are set on an role
type roleStorageEntry struct {
// UUID that uniquely represents this role. This serves as a credential
// to perform login using this role.
RoleID string `json:"role_id" structs:"role_id" mapstructure:"role_id"`
// UUID that serves as the HMAC key for the hashing the 'secret_id's
// of the role
HMACKey string `json:"hmac_key" structs:"hmac_key" mapstructure:"hmac_key"`
// Policies that are to be required by the token to access this role
Policies []string `json:"policies" structs:"policies" mapstructure:"policies"`
// Number of times the SecretID generated against this role can be
// used to perform login operation
SecretIDNumUses int `json:"secret_id_num_uses" structs:"secret_id_num_uses" mapstructure:"secret_id_num_uses"`
// Duration (less than the backend mount's max TTL) after which a
// SecretID generated against the role will expire
SecretIDTTL time.Duration `json:"secret_id_ttl" structs:"secret_id_ttl" mapstructure:"secret_id_ttl"`
// TokenNumUses defines the number of allowed uses of the token issued
TokenNumUses int `json:"token_num_uses" mapstructure:"token_num_uses" structs:"token_num_uses"`
// Duration before which an issued token must be renewed
TokenTTL time.Duration `json:"token_ttl" structs:"token_ttl" mapstructure:"token_ttl"`
// Duration after which an issued token should not be allowed to be renewed
TokenMaxTTL time.Duration `json:"token_max_ttl" structs:"token_max_ttl" mapstructure:"token_max_ttl"`
// A constraint, if set, requires 'secret_id' credential to be presented during login
BindSecretID bool `json:"bind_secret_id" structs:"bind_secret_id" mapstructure:"bind_secret_id"`
// A constraint, if set, specifies the CIDR blocks from which logins should be allowed
BoundCIDRListOld string `json:"bound_cidr_list,omitempty"`
// A constraint, if set, specifies the CIDR blocks from which logins should be allowed
BoundCIDRList []string `json:"bound_cidr_list_list" structs:"bound_cidr_list" mapstructure:"bound_cidr_list"`
// Period, if set, indicates that the token generated using this role
// should never expire. The token should be renewed within the duration
// specified by this value. The renewal duration will be fixed if the
// value is not modified on the role. If the `Period` in the role is modified,
// a token will pick up the new value during its next renewal.
Period time.Duration `json:"period" mapstructure:"period" structs:"period"`
// LowerCaseRoleName enforces the lower casing of role names for all the
// roles that get created since this field was introduced.
LowerCaseRoleName bool `json:"lower_case_role_name" mapstructure:"lower_case_role_name" structs:"lower_case_role_name"`
// SecretIDPrefix is the storage prefix for persisting secret IDs. This
// differs based on whether the secret IDs are cluster local or not.
SecretIDPrefix string `json:"secret_id_prefix" mapstructure:"secret_id_prefix" structs:"secret_id_prefix"`
}
// roleIDStorageEntry represents the reverse mapping from RoleID to Role
type roleIDStorageEntry struct {
Name string `json:"name" structs:"name" mapstructure:"name"`
}
// rolePaths creates all the paths that are used to register and manage an role.
//
// Paths returned:
// role/ - For listing all the registered roles
// role/<role_name> - For registering an role
// role/<role_name>/policies - For updating the param
// role/<role_name>/secret-id-num-uses - For updating the param
// role/<role_name>/secret-id-ttl - For updating the param
// role/<role_name>/token-ttl - For updating the param
// role/<role_name>/token-max-ttl - For updating the param
// role/<role_name>/token-num-uses - For updating the param
// role/<role_name>/bind-secret-id - For updating the param
// role/<role_name>/bound-cidr-list - For updating the param
// role/<role_name>/period - For updating the param
// role/<role_name>/role-id - For fetching the role_id of an role
// role/<role_name>/secret-id - For issuing a secret_id against an role, also to list the secret_id_accessors
// role/<role_name>/custom-secret-id - For assigning a custom SecretID against an role
// role/<role_name>/secret-id/lookup - For reading the properties of a secret_id
// role/<role_name>/secret-id/destroy - For deleting a secret_id
// role/<role_name>/secret-id-accessor/lookup - For reading secret_id using accessor
// role/<role_name>/secret-id-accessor/destroy - For deleting secret_id using accessor
func rolePaths(b *backend) []*framework.Path {
return []*framework.Path{
&framework.Path{
Pattern: "role/?",
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.ListOperation: b.pathRoleList,
},
HelpSynopsis: strings.TrimSpace(roleHelp["role-list"][0]),
HelpDescription: strings.TrimSpace(roleHelp["role-list"][1]),
},
&framework.Path{
Pattern: "role/" + framework.GenericNameRegex("role_name"),
Fields: map[string]*framework.FieldSchema{
"role_name": &framework.FieldSchema{
Type: framework.TypeString,
Description: "Name of the role.",
},
"bind_secret_id": &framework.FieldSchema{
Type: framework.TypeBool,
Default: true,
Description: "Impose secret_id to be presented when logging in using this role. Defaults to 'true'.",
},
"bound_cidr_list": &framework.FieldSchema{
Type: framework.TypeCommaStringSlice,
Description: `Comma separated string or list of CIDR blocks. If set, specifies the blocks of
IP addresses which can perform the login operation.`,
},
"policies": &framework.FieldSchema{
Type: framework.TypeCommaStringSlice,
Default: "default",
Description: "Comma separated list of policies on the role.",
},
"secret_id_num_uses": &framework.FieldSchema{
Type: framework.TypeInt,
Description: `Number of times a SecretID can access the role, after which the SecretID
will expire. Defaults to 0 meaning that the the secret_id is of unlimited use.`,
},
"secret_id_ttl": &framework.FieldSchema{
Type: framework.TypeDurationSecond,
Description: `Duration in seconds after which the issued SecretID should expire. Defaults
to 0, meaning no expiration.`,
},
"token_num_uses": &framework.FieldSchema{
Type: framework.TypeInt,
Description: `Number of times issued tokens can be used`,
},
"token_ttl": &framework.FieldSchema{
Type: framework.TypeDurationSecond,
Description: `Duration in seconds after which the issued token should expire. Defaults
to 0, in which case the value will fall back to the system/mount defaults.`,
},
"token_max_ttl": &framework.FieldSchema{
Type: framework.TypeDurationSecond,
Description: `Duration in seconds after which the issued token should not be allowed to
be renewed. Defaults to 0, in which case the value will fall back to the system/mount defaults.`,
},
"period": &framework.FieldSchema{
Type: framework.TypeDurationSecond,
Default: 0,
Description: `If set, indicates that the token generated using this role
should never expire. The token should be renewed within the
duration specified by this value. At each renewal, the token's
TTL will be set to the value of this parameter.`,
},
"role_id": &framework.FieldSchema{
Type: framework.TypeString,
Description: "Identifier of the role. Defaults to a UUID.",
},
"local_secret_ids": &framework.FieldSchema{
Type: framework.TypeBool,
Description: `If set, the secret IDs generated using this role will be cluster local. This
can only be set during role creation and once set, it can't be reset later.`,
},
},
ExistenceCheck: b.pathRoleExistenceCheck,
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.CreateOperation: b.pathRoleCreateUpdate,
logical.UpdateOperation: b.pathRoleCreateUpdate,
logical.ReadOperation: b.pathRoleRead,
logical.DeleteOperation: b.pathRoleDelete,
},
HelpSynopsis: strings.TrimSpace(roleHelp["role"][0]),
HelpDescription: strings.TrimSpace(roleHelp["role"][1]),
},
&framework.Path{
Pattern: "role/" + framework.GenericNameRegex("role_name") + "/local-secret-ids$",
Fields: map[string]*framework.FieldSchema{
"role_name": &framework.FieldSchema{
Type: framework.TypeString,
Description: "Name of the role.",
},
},
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.ReadOperation: b.pathRoleLocalSecretIDsRead,
},
HelpSynopsis: strings.TrimSpace(roleHelp["role-local-secret-ids"][0]),
HelpDescription: strings.TrimSpace(roleHelp["role-local-secret-ids"][1]),
},
&framework.Path{
Pattern: "role/" + framework.GenericNameRegex("role_name") + "/policies$",
Fields: map[string]*framework.FieldSchema{
"role_name": &framework.FieldSchema{
Type: framework.TypeString,
Description: "Name of the role.",
},
"policies": &framework.FieldSchema{
Type: framework.TypeCommaStringSlice,
Default: "default",
Description: "Comma separated list of policies on the role.",
},
},
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.UpdateOperation: b.pathRolePoliciesUpdate,
logical.ReadOperation: b.pathRolePoliciesRead,
logical.DeleteOperation: b.pathRolePoliciesDelete,
},
HelpSynopsis: strings.TrimSpace(roleHelp["role-policies"][0]),
HelpDescription: strings.TrimSpace(roleHelp["role-policies"][1]),
},
&framework.Path{
Pattern: "role/" + framework.GenericNameRegex("role_name") + "/bound-cidr-list$",
Fields: map[string]*framework.FieldSchema{
"role_name": &framework.FieldSchema{
Type: framework.TypeString,
Description: "Name of the role.",
},
"bound_cidr_list": &framework.FieldSchema{
Type: framework.TypeCommaStringSlice,
Description: `Comma separated string or list of CIDR blocks. If set, specifies the blocks of
IP addresses which can perform the login operation.`,
},
},
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.UpdateOperation: b.pathRoleBoundCIDRListUpdate,
logical.ReadOperation: b.pathRoleBoundCIDRListRead,
logical.DeleteOperation: b.pathRoleBoundCIDRListDelete,
},
HelpSynopsis: strings.TrimSpace(roleHelp["role-bound-cidr-list"][0]),
HelpDescription: strings.TrimSpace(roleHelp["role-bound-cidr-list"][1]),
},
&framework.Path{
Pattern: "role/" + framework.GenericNameRegex("role_name") + "/bind-secret-id$",
Fields: map[string]*framework.FieldSchema{
"role_name": &framework.FieldSchema{
Type: framework.TypeString,
Description: "Name of the role.",
},
"bind_secret_id": &framework.FieldSchema{
Type: framework.TypeBool,
Default: true,
Description: "Impose secret_id to be presented when logging in using this role.",
},
},
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.UpdateOperation: b.pathRoleBindSecretIDUpdate,
logical.ReadOperation: b.pathRoleBindSecretIDRead,
logical.DeleteOperation: b.pathRoleBindSecretIDDelete,
},
HelpSynopsis: strings.TrimSpace(roleHelp["role-bind-secret-id"][0]),
HelpDescription: strings.TrimSpace(roleHelp["role-bind-secret-id"][1]),
},
&framework.Path{
Pattern: "role/" + framework.GenericNameRegex("role_name") + "/secret-id-num-uses$",
Fields: map[string]*framework.FieldSchema{
"role_name": &framework.FieldSchema{
Type: framework.TypeString,
Description: "Name of the role.",
},
"secret_id_num_uses": &framework.FieldSchema{
Type: framework.TypeInt,
Description: "Number of times a SecretID can access the role, after which the SecretID will expire.",
},
},
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.UpdateOperation: b.pathRoleSecretIDNumUsesUpdate,
logical.ReadOperation: b.pathRoleSecretIDNumUsesRead,
logical.DeleteOperation: b.pathRoleSecretIDNumUsesDelete,
},
HelpSynopsis: strings.TrimSpace(roleHelp["role-secret-id-num-uses"][0]),
HelpDescription: strings.TrimSpace(roleHelp["role-secret-id-num-uses"][1]),
},
&framework.Path{
Pattern: "role/" + framework.GenericNameRegex("role_name") + "/secret-id-ttl$",
Fields: map[string]*framework.FieldSchema{
"role_name": &framework.FieldSchema{
Type: framework.TypeString,
Description: "Name of the role.",
},
"secret_id_ttl": &framework.FieldSchema{
Type: framework.TypeDurationSecond,
Description: `Duration in seconds after which the issued SecretID should expire. Defaults
to 0, meaning no expiration.`,
},
},
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.UpdateOperation: b.pathRoleSecretIDTTLUpdate,
logical.ReadOperation: b.pathRoleSecretIDTTLRead,
logical.DeleteOperation: b.pathRoleSecretIDTTLDelete,
},
HelpSynopsis: strings.TrimSpace(roleHelp["role-secret-id-ttl"][0]),
HelpDescription: strings.TrimSpace(roleHelp["role-secret-id-ttl"][1]),
},
&framework.Path{
Pattern: "role/" + framework.GenericNameRegex("role_name") + "/period$",
Fields: map[string]*framework.FieldSchema{
"role_name": &framework.FieldSchema{
Type: framework.TypeString,
Description: "Name of the role.",
},
"period": &framework.FieldSchema{
Type: framework.TypeDurationSecond,
Default: 0,
Description: `If set, indicates that the token generated using this role
should never expire. The token should be renewed within the
duration specified by this value. At each renewal, the token's
TTL will be set to the value of this parameter.`,
},
},
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.UpdateOperation: b.pathRolePeriodUpdate,
logical.ReadOperation: b.pathRolePeriodRead,
logical.DeleteOperation: b.pathRolePeriodDelete,
},
HelpSynopsis: strings.TrimSpace(roleHelp["role-period"][0]),
HelpDescription: strings.TrimSpace(roleHelp["role-period"][1]),
},
&framework.Path{
Pattern: "role/" + framework.GenericNameRegex("role_name") + "/token-num-uses$",
Fields: map[string]*framework.FieldSchema{
"role_name": &framework.FieldSchema{
Type: framework.TypeString,
Description: "Name of the role.",
},
"token_num_uses": &framework.FieldSchema{
Type: framework.TypeInt,
Description: `Number of times issued tokens can be used`,
},
},
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.UpdateOperation: b.pathRoleTokenNumUsesUpdate,
logical.ReadOperation: b.pathRoleTokenNumUsesRead,
logical.DeleteOperation: b.pathRoleTokenNumUsesDelete,
},
HelpSynopsis: strings.TrimSpace(roleHelp["role-token-num-uses"][0]),
HelpDescription: strings.TrimSpace(roleHelp["role-token-num-uses"][1]),
},
&framework.Path{
Pattern: "role/" + framework.GenericNameRegex("role_name") + "/token-ttl$",
Fields: map[string]*framework.FieldSchema{
"role_name": &framework.FieldSchema{
Type: framework.TypeString,
Description: "Name of the role.",
},
"token_ttl": &framework.FieldSchema{
Type: framework.TypeDurationSecond,
Description: `Duration in seconds after which the issued token should expire. Defaults
to 0, in which case the value will fall back to the system/mount defaults.`,
},
},
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.UpdateOperation: b.pathRoleTokenTTLUpdate,
logical.ReadOperation: b.pathRoleTokenTTLRead,
logical.DeleteOperation: b.pathRoleTokenTTLDelete,
},
HelpSynopsis: strings.TrimSpace(roleHelp["role-token-ttl"][0]),
HelpDescription: strings.TrimSpace(roleHelp["role-token-ttl"][1]),
},
&framework.Path{
Pattern: "role/" + framework.GenericNameRegex("role_name") + "/token-max-ttl$",
Fields: map[string]*framework.FieldSchema{
"role_name": &framework.FieldSchema{
Type: framework.TypeString,
Description: "Name of the role.",
},
"token_max_ttl": &framework.FieldSchema{
Type: framework.TypeDurationSecond,
Description: `Duration in seconds after which the issued token should not be allowed to
be renewed. Defaults to 0, in which case the value will fall back to the system/mount defaults.`,
},
},
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.UpdateOperation: b.pathRoleTokenMaxTTLUpdate,
logical.ReadOperation: b.pathRoleTokenMaxTTLRead,
logical.DeleteOperation: b.pathRoleTokenMaxTTLDelete,
},
HelpSynopsis: strings.TrimSpace(roleHelp["role-token-max-ttl"][0]),
HelpDescription: strings.TrimSpace(roleHelp["role-token-max-ttl"][1]),
},
&framework.Path{
Pattern: "role/" + framework.GenericNameRegex("role_name") + "/role-id$",
Fields: map[string]*framework.FieldSchema{
"role_name": &framework.FieldSchema{
Type: framework.TypeString,
Description: "Name of the role.",
},
"role_id": &framework.FieldSchema{
Type: framework.TypeString,
Description: "Identifier of the role. Defaults to a UUID.",
},
},
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.ReadOperation: b.pathRoleRoleIDRead,
logical.UpdateOperation: b.pathRoleRoleIDUpdate,
},
HelpSynopsis: strings.TrimSpace(roleHelp["role-id"][0]),
HelpDescription: strings.TrimSpace(roleHelp["role-id"][1]),
},
&framework.Path{
Pattern: "role/" + framework.GenericNameRegex("role_name") + "/secret-id/?$",
Fields: map[string]*framework.FieldSchema{
"role_name": &framework.FieldSchema{
Type: framework.TypeString,
Description: "Name of the role.",
},
"metadata": &framework.FieldSchema{
Type: framework.TypeString,
Description: `Metadata to be tied to the SecretID. This should be a JSON
formatted string containing the metadata in key value pairs.`,
},
"cidr_list": &framework.FieldSchema{
Type: framework.TypeCommaStringSlice,
Description: `Comma separated string or list of CIDR blocks enforcing secret IDs to be used from
specific set of IP addresses. If 'bound_cidr_list' is set on the role, then the
list of CIDR blocks listed here should be a subset of the CIDR blocks listed on
the role.`,
},
},
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.UpdateOperation: b.pathRoleSecretIDUpdate,
logical.ListOperation: b.pathRoleSecretIDList,
},
HelpSynopsis: strings.TrimSpace(roleHelp["role-secret-id"][0]),
HelpDescription: strings.TrimSpace(roleHelp["role-secret-id"][1]),
},
&framework.Path{
Pattern: "role/" + framework.GenericNameRegex("role_name") + "/secret-id/lookup/?$",
Fields: map[string]*framework.FieldSchema{
"role_name": &framework.FieldSchema{
Type: framework.TypeString,
Description: "Name of the role.",
},
"secret_id": &framework.FieldSchema{
Type: framework.TypeString,
Description: "SecretID attached to the role.",
},
},
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.UpdateOperation: b.pathRoleSecretIDLookupUpdate,
},
HelpSynopsis: strings.TrimSpace(roleHelp["role-secret-id-lookup"][0]),
HelpDescription: strings.TrimSpace(roleHelp["role-secret-id-lookup"][1]),
},
&framework.Path{
Pattern: "role/" + framework.GenericNameRegex("role_name") + "/secret-id/destroy/?$",
Fields: map[string]*framework.FieldSchema{
"role_name": &framework.FieldSchema{
Type: framework.TypeString,
Description: "Name of the role.",
},
"secret_id": &framework.FieldSchema{
Type: framework.TypeString,
Description: "SecretID attached to the role.",
},
},
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.UpdateOperation: b.pathRoleSecretIDDestroyUpdateDelete,
logical.DeleteOperation: b.pathRoleSecretIDDestroyUpdateDelete,
},
HelpSynopsis: strings.TrimSpace(roleHelp["role-secret-id-destroy"][0]),
HelpDescription: strings.TrimSpace(roleHelp["role-secret-id-destroy"][1]),
},
&framework.Path{
Pattern: "role/" + framework.GenericNameRegex("role_name") + "/secret-id-accessor/lookup/?$",
Fields: map[string]*framework.FieldSchema{
"role_name": &framework.FieldSchema{
Type: framework.TypeString,
Description: "Name of the role.",
},
"secret_id_accessor": &framework.FieldSchema{
Type: framework.TypeString,
Description: "Accessor of the SecretID",
},
},
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.UpdateOperation: b.pathRoleSecretIDAccessorLookupUpdate,
},
HelpSynopsis: strings.TrimSpace(roleHelp["role-secret-id-accessor"][0]),
HelpDescription: strings.TrimSpace(roleHelp["role-secret-id-accessor"][1]),
},
&framework.Path{
Pattern: "role/" + framework.GenericNameRegex("role_name") + "/secret-id-accessor/destroy/?$",
Fields: map[string]*framework.FieldSchema{
"role_name": &framework.FieldSchema{
Type: framework.TypeString,
Description: "Name of the role.",
},
"secret_id_accessor": &framework.FieldSchema{
Type: framework.TypeString,
Description: "Accessor of the SecretID",
},
},
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.UpdateOperation: b.pathRoleSecretIDAccessorDestroyUpdateDelete,
logical.DeleteOperation: b.pathRoleSecretIDAccessorDestroyUpdateDelete,
},
HelpSynopsis: strings.TrimSpace(roleHelp["role-secret-id-accessor"][0]),
HelpDescription: strings.TrimSpace(roleHelp["role-secret-id-accessor"][1]),
},
&framework.Path{
Pattern: "role/" + framework.GenericNameRegex("role_name") + "/custom-secret-id$",
Fields: map[string]*framework.FieldSchema{
"role_name": &framework.FieldSchema{
Type: framework.TypeString,
Description: "Name of the role.",
},
"secret_id": &framework.FieldSchema{
Type: framework.TypeString,
Description: "SecretID to be attached to the role.",
},
"metadata": &framework.FieldSchema{
Type: framework.TypeString,
Description: `Metadata to be tied to the SecretID. This should be a JSON
formatted string containing metadata in key value pairs.`,
},
"cidr_list": &framework.FieldSchema{
Type: framework.TypeCommaStringSlice,
Description: `Comma separated string or list of CIDR blocks enforcing secret IDs to be used from
specific set of IP addresses. If 'bound_cidr_list' is set on the role, then the
list of CIDR blocks listed here should be a subset of the CIDR blocks listed on
the role.`,
},
},
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.UpdateOperation: b.pathRoleCustomSecretIDUpdate,
},
HelpSynopsis: strings.TrimSpace(roleHelp["role-custom-secret-id"][0]),
HelpDescription: strings.TrimSpace(roleHelp["role-custom-secret-id"][1]),
},
}
}
// pathRoleExistenceCheck returns whether the role with the given name exists or not.
func (b *backend) pathRoleExistenceCheck(ctx context.Context, req *logical.Request, data *framework.FieldData) (bool, error) {
roleName := data.Get("role_name").(string)
if roleName == "" {
return false, fmt.Errorf("missing role_name")
}
lock := b.roleLock(roleName)
lock.RLock()
defer lock.RUnlock()
role, err := b.roleEntry(ctx, req.Storage, strings.ToLower(roleName))
if err != nil {
return false, err
}
return role != nil, nil
}
// pathRoleList is used to list all the Roles registered with the backend.
func (b *backend) pathRoleList(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
lock := b.roleLock("")
lock.RLock()
defer lock.RUnlock()
roles, err := req.Storage.List(ctx, "role/")
if err != nil {
return nil, err
}
return logical.ListResponse(roles), nil
}
// pathRoleSecretIDList is used to list all the 'secret_id_accessor's issued against the role.
func (b *backend) pathRoleSecretIDList(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
roleName := data.Get("role_name").(string)
if roleName == "" {
return logical.ErrorResponse("missing role_name"), nil
}
lock := b.roleLock(roleName)
lock.RLock()
defer lock.RUnlock()
// Get the role entry
role, err := b.roleEntry(ctx, req.Storage, strings.ToLower(roleName))
if err != nil {
return nil, err
}
if role == nil {
return logical.ErrorResponse(fmt.Sprintf("role %q does not exist", roleName)), nil
}
if role.LowerCaseRoleName {
roleName = strings.ToLower(roleName)
}
// Guard the list operation with an outer lock
b.secretIDListingLock.RLock()
defer b.secretIDListingLock.RUnlock()
roleNameHMAC, err := createHMAC(role.HMACKey, roleName)
if err != nil {
return nil, errwrap.Wrapf("failed to create HMAC of role_name: {{err}}", err)
}
// Listing works one level at a time. Get the first level of data
// which could then be used to get the actual SecretID storage entries.
secretIDHMACs, err := req.Storage.List(ctx, fmt.Sprintf("%s%s/", role.SecretIDPrefix, roleNameHMAC))
if err != nil {
return nil, err
}
var listItems []string
for _, secretIDHMAC := range secretIDHMACs {
// For sanity
if secretIDHMAC == "" {
continue
}
// Prepare the full index of the SecretIDs.
entryIndex := fmt.Sprintf("%s%s/%s", role.SecretIDPrefix, roleNameHMAC, secretIDHMAC)
// SecretID locks are not indexed by SecretIDs itself.
// This is because SecretIDs are not stored in plaintext
// form anywhere in the backend, and hence accessing its
// corresponding lock many times using SecretIDs is not
// possible. Also, indexing it everywhere using secretIDHMACs
// makes listing operation easier.
secretIDLock := b.secretIDLock(secretIDHMAC)
secretIDLock.RLock()
result := secretIDStorageEntry{}
if entry, err := req.Storage.Get(ctx, entryIndex); err != nil {
secretIDLock.RUnlock()
return nil, err
} else if entry == nil {
secretIDLock.RUnlock()
return nil, fmt.Errorf("storage entry for SecretID is present but no content found at the index")
} else if err := entry.DecodeJSON(&result); err != nil {
secretIDLock.RUnlock()
return nil, err
}
listItems = append(listItems, result.SecretIDAccessor)
secretIDLock.RUnlock()
}
return logical.ListResponse(listItems), nil
}
// validateRoleConstraints checks if the role has at least one constraint
// enabled.
func validateRoleConstraints(role *roleStorageEntry) error {
if role == nil {
return fmt.Errorf("nil role")
}
// At least one constraint should be enabled on the role
switch {
case role.BindSecretID:
case len(role.BoundCIDRList) != 0:
default:
return fmt.Errorf("at least one constraint should be enabled on the role")
}
return nil
}
// setRoleEntry persists the role and creates an index from roleID to role
// name.
func (b *backend) setRoleEntry(ctx context.Context, s logical.Storage, roleName string, role *roleStorageEntry, previousRoleID string) error {
if roleName == "" {
return fmt.Errorf("missing role name")
}
if role == nil {
return fmt.Errorf("nil role")
}
// Check if role constraints are properly set
if err := validateRoleConstraints(role); err != nil {
return err
}
// Create a storage entry for the role
entry, err := logical.StorageEntryJSON("role/"+strings.ToLower(roleName), role)
if err != nil {
return err
}
if entry == nil {
return fmt.Errorf("failed to create storage entry for role %q", roleName)
}
// Check if the index from the role_id to role already exists
roleIDIndex, err := b.roleIDEntry(ctx, s, role.RoleID)
if err != nil {
return errwrap.Wrapf("failed to read role_id index: {{err}}", err)
}
// If the entry exists, make sure that it belongs to the current role
if roleIDIndex != nil && roleIDIndex.Name != roleName {
return fmt.Errorf("role_id already in use")
}
// When role_id is getting updated, delete the old index before
// a new one is created
if previousRoleID != "" && previousRoleID != role.RoleID {
if err = b.roleIDEntryDelete(ctx, s, previousRoleID); err != nil {
return fmt.Errorf("failed to delete previous role ID index")
}
}
// Save the role entry only after all the validations
if err = s.Put(ctx, entry); err != nil {
return err
}
// If previousRoleID is still intact, don't create another one
if previousRoleID != "" && previousRoleID == role.RoleID {
return nil
}
// Create a storage entry for reverse mapping of RoleID to role.
// Note that secondary index is created when the roleLock is held.
return b.setRoleIDEntry(ctx, s, role.RoleID, &roleIDStorageEntry{
Name: roleName,
})
}
// roleEntry reads the role from storage
func (b *backend) roleEntry(ctx context.Context, s logical.Storage, roleName string) (*roleStorageEntry, error) {
if roleName == "" {
return nil, fmt.Errorf("missing role_name")
}
var role roleStorageEntry
if entry, err := s.Get(ctx, "role/"+strings.ToLower(roleName)); err != nil {
return nil, err
} else if entry == nil {
return nil, nil
} else if err := entry.DecodeJSON(&role); err != nil {
return nil, err
}
needsUpgrade := false
if role.BoundCIDRListOld != "" {
role.BoundCIDRList = strings.Split(role.BoundCIDRListOld, ",")
role.BoundCIDRListOld = ""
needsUpgrade = true
}
if role.SecretIDPrefix == "" {
role.SecretIDPrefix = secretIDPrefix
needsUpgrade = true
}
if needsUpgrade && (b.System().LocalMount() || !b.System().ReplicationState().HasState(consts.ReplicationPerformanceSecondary)) {
entry, err := logical.StorageEntryJSON("role/"+strings.ToLower(roleName), &role)
if err != nil {
return nil, err
}
if err := s.Put(ctx, entry); err != nil {
// Only perform upgrades on replication primary
if !strings.Contains(err.Error(), logical.ErrReadOnly.Error()) {
return nil, err
}
}
}
return &role, nil
}
// pathRoleCreateUpdate registers a new role with the backend or updates the options
// of an existing role
func (b *backend) pathRoleCreateUpdate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
roleName := data.Get("role_name").(string)
if roleName == "" {
return logical.ErrorResponse("missing role_name"), nil
}
lock := b.roleLock(roleName)
lock.Lock()
defer lock.Unlock()
// Check if the role already exists
role, err := b.roleEntry(ctx, req.Storage, roleName)
if err != nil {
return nil, err
}
// Create a new entry object if this is a CreateOperation
if role == nil && req.Operation == logical.CreateOperation {
hmacKey, err := uuid.GenerateUUID()
if err != nil {
return nil, errwrap.Wrapf("failed to create role_id: {{err}}", err)
}
role = &roleStorageEntry{
HMACKey: hmacKey,
LowerCaseRoleName: true,
}
} else if role == nil {
return logical.ErrorResponse(fmt.Sprintf("role name %q doesn't exist", roleName)), nil
}
localSecretIDsRaw, ok := data.GetOk("local_secret_ids")
if ok {
switch {
case req.Operation == logical.CreateOperation:
localSecretIDs := localSecretIDsRaw.(bool)
if localSecretIDs {
role.SecretIDPrefix = secretIDLocalPrefix
}
default:
return logical.ErrorResponse("local_secret_ids can only be modified during role creation"), nil
}
}
previousRoleID := role.RoleID
if roleIDRaw, ok := data.GetOk("role_id"); ok {
role.RoleID = roleIDRaw.(string)
} else if req.Operation == logical.CreateOperation {
roleID, err := uuid.GenerateUUID()
if err != nil {
return nil, errwrap.Wrapf("failed to generate role_id: {{err}}", err)
}
role.RoleID = roleID
}
if role.RoleID == "" {
return logical.ErrorResponse("invalid role_id supplied, or failed to generate a role_id"), nil
}
if bindSecretIDRaw, ok := data.GetOk("bind_secret_id"); ok {
role.BindSecretID = bindSecretIDRaw.(bool)
} else if req.Operation == logical.CreateOperation {
role.BindSecretID = data.Get("bind_secret_id").(bool)
}
if boundCIDRListRaw, ok := data.GetOk("bound_cidr_list"); ok {
role.BoundCIDRList = boundCIDRListRaw.([]string)
} else if req.Operation == logical.CreateOperation {
role.BoundCIDRList = data.Get("bound_cidr_list").([]string)
}
if len(role.BoundCIDRList) != 0 {
valid, err := cidrutil.ValidateCIDRListSlice(role.BoundCIDRList)
if err != nil {
return nil, errwrap.Wrapf("failed to validate CIDR blocks: {{err}}", err)
}
if !valid {
return logical.ErrorResponse("invalid CIDR blocks"), nil
}
}
if policiesRaw, ok := data.GetOk("policies"); ok {
role.Policies = policyutil.ParsePolicies(policiesRaw)
} else if req.Operation == logical.CreateOperation {
role.Policies = policyutil.ParsePolicies(data.Get("policies"))
}
periodRaw, ok := data.GetOk("period")
if ok {
role.Period = time.Second * time.Duration(periodRaw.(int))
} else if req.Operation == logical.CreateOperation {
role.Period = time.Second * time.Duration(data.Get("period").(int))
}
if role.Period > b.System().MaxLeaseTTL() {
return logical.ErrorResponse(fmt.Sprintf("period of %q is greater than the backend's maximum lease TTL of %q", role.Period.String(), b.System().MaxLeaseTTL().String())), nil
}
if secretIDNumUsesRaw, ok := data.GetOk("secret_id_num_uses"); ok {
role.SecretIDNumUses = secretIDNumUsesRaw.(int)
} else if req.Operation == logical.CreateOperation {
role.SecretIDNumUses = data.Get("secret_id_num_uses").(int)
}
if role.SecretIDNumUses < 0 {
return logical.ErrorResponse("secret_id_num_uses cannot be negative"), nil
}
if secretIDTTLRaw, ok := data.GetOk("secret_id_ttl"); ok {
role.SecretIDTTL = time.Second * time.Duration(secretIDTTLRaw.(int))
} else if req.Operation == logical.CreateOperation {
role.SecretIDTTL = time.Second * time.Duration(data.Get("secret_id_ttl").(int))
}
if tokenNumUsesRaw, ok := data.GetOk("token_num_uses"); ok {
role.TokenNumUses = tokenNumUsesRaw.(int)
} else if req.Operation == logical.CreateOperation {
role.TokenNumUses = data.Get("token_num_uses").(int)
}
if role.TokenNumUses < 0 {
return logical.ErrorResponse("token_num_uses cannot be negative"), nil
}
if tokenTTLRaw, ok := data.GetOk("token_ttl"); ok {
role.TokenTTL = time.Second * time.Duration(tokenTTLRaw.(int))
} else if req.Operation == logical.CreateOperation {
role.TokenTTL = time.Second * time.Duration(data.Get("token_ttl").(int))
}
if tokenMaxTTLRaw, ok := data.GetOk("token_max_ttl"); ok {
role.TokenMaxTTL = time.Second * time.Duration(tokenMaxTTLRaw.(int))
} else if req.Operation == logical.CreateOperation {
role.TokenMaxTTL = time.Second * time.Duration(data.Get("token_max_ttl").(int))
}
// Check that the TokenTTL value provided is less than the TokenMaxTTL.
// Sanitizing the TTL and MaxTTL is not required now and can be performed
// at credential issue time.
if role.TokenMaxTTL > time.Duration(0) && role.TokenTTL > role.TokenMaxTTL {
return logical.ErrorResponse("token_ttl should not be greater than token_max_ttl"), nil
}
var resp *logical.Response
if role.TokenMaxTTL > b.System().MaxLeaseTTL() {
resp = &logical.Response{}
resp.AddWarning("token_max_ttl is greater than the backend mount's maximum TTL value; issued tokens' max TTL value will be truncated")
}
// Store the entry.
return resp, b.setRoleEntry(ctx, req.Storage, roleName, role, previousRoleID)
}
// pathRoleRead grabs a read lock and reads the options set on the role from the storage
func (b *backend) pathRoleRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
roleName := data.Get("role_name").(string)
if roleName == "" {
return logical.ErrorResponse("missing role_name"), nil
}
lock := b.roleLock(roleName)
lock.RLock()
lockRelease := lock.RUnlock
role, err := b.roleEntry(ctx, req.Storage, strings.ToLower(roleName))
if err != nil {
lockRelease()
return nil, err
}
if role == nil {
lockRelease()
return nil, nil
}
respData := map[string]interface{}{
"bind_secret_id": role.BindSecretID,
"bound_cidr_list": role.BoundCIDRList,
"period": role.Period / time.Second,
"policies": role.Policies,
"secret_id_num_uses": role.SecretIDNumUses,
"secret_id_ttl": role.SecretIDTTL / time.Second,
"token_max_ttl": role.TokenMaxTTL / time.Second,
"token_num_uses": role.TokenNumUses,
"token_ttl": role.TokenTTL / time.Second,
"local_secret_ids": false,
}
if role.SecretIDPrefix == secretIDLocalPrefix {
respData["local_secret_ids"] = true
}
resp := &logical.Response{
Data: respData,
}
if err := validateRoleConstraints(role); err != nil {
resp.AddWarning("Role does not have any constraints set on it. Updates to this role will require a constraint to be set")
}
// For sanity, verify that the index still exists. If the index is missing,
// add one and return a warning so it can be reported.
roleIDIndex, err := b.roleIDEntry(ctx, req.Storage, role.RoleID)
if err != nil {
lockRelease()
return nil, err
}
if roleIDIndex == nil {
// Switch to a write lock
lock.RUnlock()
lock.Lock()
lockRelease = lock.Unlock
// Check again if the index is missing
roleIDIndex, err = b.roleIDEntry(ctx, req.Storage, role.RoleID)
if err != nil {
lockRelease()
return nil, err
}
if roleIDIndex == nil {
// Create a new index
err = b.setRoleIDEntry(ctx, req.Storage, role.RoleID, &roleIDStorageEntry{
Name: roleName,
})