-
Notifications
You must be signed in to change notification settings - Fork 4.4k
/
acl.go
1909 lines (1547 loc) · 52 KB
/
acl.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 state
import (
"encoding/binary"
"fmt"
"time"
memdb "github.com/hashicorp/go-memdb"
"github.com/hashicorp/consul/agent/structs"
pbacl "github.com/hashicorp/consul/proto/pbacl"
)
type TokenPoliciesIndex struct {
}
func (s *TokenPoliciesIndex) FromObject(obj interface{}) (bool, [][]byte, error) {
token, ok := obj.(*structs.ACLToken)
if !ok {
return false, nil, fmt.Errorf("object is not an ACLToken")
}
links := token.Policies
numLinks := len(links)
if numLinks == 0 {
return false, nil, nil
}
vals := make([][]byte, 0, numLinks)
for _, link := range links {
vals = append(vals, []byte(link.ID+"\x00"))
}
return true, vals, nil
}
func (s *TokenPoliciesIndex) FromArgs(args ...interface{}) ([]byte, error) {
if len(args) != 1 {
return nil, fmt.Errorf("must provide only a single argument")
}
arg, ok := args[0].(string)
if !ok {
return nil, fmt.Errorf("argument must be a string: %#v", args[0])
}
// Add the null character as a terminator
arg += "\x00"
return []byte(arg), nil
}
func (s *TokenPoliciesIndex) PrefixFromArgs(args ...interface{}) ([]byte, error) {
val, err := s.FromArgs(args...)
if err != nil {
return nil, err
}
// Strip the null terminator, the rest is a prefix
n := len(val)
if n > 0 {
return val[:n-1], nil
}
return val, nil
}
type TokenRolesIndex struct {
}
func (s *TokenRolesIndex) FromObject(obj interface{}) (bool, [][]byte, error) {
token, ok := obj.(*structs.ACLToken)
if !ok {
return false, nil, fmt.Errorf("object is not an ACLToken")
}
links := token.Roles
numLinks := len(links)
if numLinks == 0 {
return false, nil, nil
}
vals := make([][]byte, 0, numLinks)
for _, link := range links {
vals = append(vals, []byte(link.ID+"\x00"))
}
return true, vals, nil
}
func (s *TokenRolesIndex) FromArgs(args ...interface{}) ([]byte, error) {
if len(args) != 1 {
return nil, fmt.Errorf("must provide only a single argument")
}
arg, ok := args[0].(string)
if !ok {
return nil, fmt.Errorf("argument must be a string: %#v", args[0])
}
// Add the null character as a terminator
arg += "\x00"
return []byte(arg), nil
}
func (s *TokenRolesIndex) PrefixFromArgs(args ...interface{}) ([]byte, error) {
val, err := s.FromArgs(args...)
if err != nil {
return nil, err
}
// Strip the null terminator, the rest is a prefix
n := len(val)
if n > 0 {
return val[:n-1], nil
}
return val, nil
}
type RolePoliciesIndex struct {
}
func (s *RolePoliciesIndex) FromObject(obj interface{}) (bool, [][]byte, error) {
role, ok := obj.(*structs.ACLRole)
if !ok {
return false, nil, fmt.Errorf("object is not an ACLRole")
}
links := role.Policies
numLinks := len(links)
if numLinks == 0 {
return false, nil, nil
}
vals := make([][]byte, 0, numLinks)
for _, link := range links {
vals = append(vals, []byte(link.ID+"\x00"))
}
return true, vals, nil
}
func (s *RolePoliciesIndex) FromArgs(args ...interface{}) ([]byte, error) {
if len(args) != 1 {
return nil, fmt.Errorf("must provide only a single argument")
}
arg, ok := args[0].(string)
if !ok {
return nil, fmt.Errorf("argument must be a string: %#v", args[0])
}
// Add the null character as a terminator
arg += "\x00"
return []byte(arg), nil
}
func (s *RolePoliciesIndex) PrefixFromArgs(args ...interface{}) ([]byte, error) {
val, err := s.FromArgs(args...)
if err != nil {
return nil, err
}
// Strip the null terminator, the rest is a prefix
n := len(val)
if n > 0 {
return val[:n-1], nil
}
return val, nil
}
type TokenExpirationIndex struct {
LocalFilter bool
}
func (s *TokenExpirationIndex) encodeTime(t time.Time) []byte {
val := t.Unix()
buf := make([]byte, 8)
binary.BigEndian.PutUint64(buf, uint64(val))
return buf
}
func (s *TokenExpirationIndex) FromObject(obj interface{}) (bool, []byte, error) {
token, ok := obj.(*structs.ACLToken)
if !ok {
return false, nil, fmt.Errorf("object is not an ACLToken")
}
if s.LocalFilter != token.Local {
return false, nil, nil
}
if !token.HasExpirationTime() {
return false, nil, nil
}
if token.ExpirationTime.Unix() < 0 {
return false, nil, fmt.Errorf("token expiration time cannot be before the unix epoch: %s", token.ExpirationTime)
}
buf := s.encodeTime(*token.ExpirationTime)
return true, buf, nil
}
func (s *TokenExpirationIndex) FromArgs(args ...interface{}) ([]byte, error) {
if len(args) != 1 {
return nil, fmt.Errorf("must provide only a single argument")
}
arg, ok := args[0].(time.Time)
if !ok {
return nil, fmt.Errorf("argument must be a time.Time: %#v", args[0])
}
if arg.Unix() < 0 {
return nil, fmt.Errorf("argument must be a time.Time after the unix epoch: %s", args[0])
}
buf := s.encodeTime(arg)
return buf, nil
}
func init() {
registerSchema(tokensTableSchema)
registerSchema(policiesTableSchema)
registerSchema(rolesTableSchema)
registerSchema(bindingRulesTableSchema)
registerSchema(authMethodsTableSchema)
}
// ACLTokens is used when saving a snapshot
func (s *Snapshot) ACLTokens() (memdb.ResultIterator, error) {
iter, err := s.tx.Get("acl-tokens", "id")
if err != nil {
return nil, err
}
return iter, nil
}
// ACLToken is used when restoring from a snapshot. For general inserts, use ACL.
func (s *Restore) ACLToken(token *structs.ACLToken) error {
return aclTokenInsert(s.tx, token)
}
// ACLPolicies is used when saving a snapshot
func (s *Snapshot) ACLPolicies() (memdb.ResultIterator, error) {
iter, err := s.tx.Get("acl-policies", "id")
if err != nil {
return nil, err
}
return iter, nil
}
func (s *Restore) ACLPolicy(policy *structs.ACLPolicy) error {
return aclPolicyInsert(s.tx, policy)
}
// ACLRoles is used when saving a snapshot
func (s *Snapshot) ACLRoles() (memdb.ResultIterator, error) {
iter, err := s.tx.Get("acl-roles", "id")
if err != nil {
return nil, err
}
return iter, nil
}
func (s *Restore) ACLRole(role *structs.ACLRole) error {
return aclRoleInsert(s.tx, role)
}
// ACLBindingRules is used when saving a snapshot
func (s *Snapshot) ACLBindingRules() (memdb.ResultIterator, error) {
iter, err := s.tx.Get("acl-binding-rules", "id")
if err != nil {
return nil, err
}
return iter, nil
}
func (s *Restore) ACLBindingRule(rule *structs.ACLBindingRule) error {
return aclBindingRuleInsert(s.tx, rule)
}
// ACLAuthMethods is used when saving a snapshot
func (s *Snapshot) ACLAuthMethods() (memdb.ResultIterator, error) {
iter, err := s.tx.Get("acl-auth-methods", "id")
if err != nil {
return nil, err
}
return iter, nil
}
func (s *Restore) ACLAuthMethod(method *structs.ACLAuthMethod) error {
return aclAuthMethodInsert(s.tx, method)
}
// ACLBootstrap is used to perform a one-time ACL bootstrap operation on a
// cluster to get the first management token.
func (s *Store) ACLBootstrap(idx, resetIndex uint64, token *structs.ACLToken, legacy bool) error {
tx := s.db.WriteTxn(idx)
defer tx.Abort()
// We must have initialized before this will ever be possible.
existing, err := tx.First("index", "id", "acl-token-bootstrap")
if err != nil {
return fmt.Errorf("bootstrap check failed: %v", err)
}
if existing != nil {
if resetIndex == 0 {
return structs.ACLBootstrapNotAllowedErr
} else if resetIndex != existing.(*IndexEntry).Value {
return structs.ACLBootstrapInvalidResetIndexErr
}
}
if err := aclTokenSetTxn(tx, idx, token, ACLTokenSetOptions{Legacy: legacy}); err != nil {
return fmt.Errorf("failed inserting bootstrap token: %v", err)
}
if err := tx.Insert("index", &IndexEntry{"acl-token-bootstrap", idx}); err != nil {
return fmt.Errorf("failed to mark ACL bootstrapping as complete: %v", err)
}
return tx.Commit()
}
// CanBootstrapACLToken checks if bootstrapping is possible and returns the reset index
func (s *Store) CanBootstrapACLToken() (bool, uint64, error) {
tx := s.db.Txn(false)
// Lookup the bootstrap sentinel
out, err := tx.First("index", "id", "acl-token-bootstrap")
if err != nil {
return false, 0, err
}
// No entry, we haven't bootstrapped yet
if out == nil {
return true, 0, nil
}
// Return the reset index if we've already bootstrapped
return false, out.(*IndexEntry).Value, nil
}
// resolveACLLinks is used to populate the links Name given its ID as the object is inserted
// into the Store. This will modify the links in place and should not be performed on data
// already inserted into the store without copying first. This is an optimization so that when
// the link is read back out of the Store, we hopefully will not have to copy the object being retrieved
// to update the name. Unlike the older functions to operate specifically on role or policy links
// this function does not itself handle the case where the id cannot be found. Instead the
// getName function should handle that and return an error if necessary
func resolveACLLinks(tx ReadTxn, links []pbacl.ACLLink, getName func(ReadTxn, string) (string, error)) (int, error) {
var numValid int
for linkIndex, link := range links {
if link.ID != "" {
name, err := getName(tx, link.ID)
if err != nil {
return 0, err
}
// the name doesn't matter here
if name != "" {
links[linkIndex].Name = name
numValid++
}
} else {
return 0, fmt.Errorf("Encountered an ACL resource linked by Name in the state store")
}
}
return numValid, nil
}
// fixupACLLinks is used to ensure data returned by read operations have the most up to date name
// associated with the ID of the link. Ideally this will be a no-op if the names are already correct
// however if a linked resource was renamed it might be stale. This function will treat the incoming
// links with copy-on-write semantics and its output will indicate whether any modifications were made.
func fixupACLLinks(tx ReadTxn, original []pbacl.ACLLink, getName func(ReadTxn, string) (string, error)) ([]pbacl.ACLLink, bool, error) {
owned := false
links := original
cloneLinks := func(l []pbacl.ACLLink, copyNumLinks int) []pbacl.ACLLink {
clone := make([]pbacl.ACLLink, copyNumLinks)
copy(clone, l[:copyNumLinks])
return clone
}
for linkIndex, link := range original {
name, err := getName(tx, link.ID)
if err != nil {
return nil, false, err
}
if name == "" {
if !owned {
// clone the original as we cannot modify anything stored in memdb
links = cloneLinks(original, linkIndex)
owned = true
}
// if already owned then we just don't append it.
} else if name != link.Name {
if !owned {
links = cloneLinks(original, linkIndex)
owned = true
}
// append the corrected link
links = append(links, pbacl.ACLLink{ID: link.ID, Name: name})
} else if owned {
links = append(links, link)
}
}
return links, owned, nil
}
func resolveTokenPolicyLinks(tx *txn, token *structs.ACLToken, allowMissing bool) (int, error) {
var numValid int
for linkIndex, link := range token.Policies {
if link.ID != "" {
policy, err := getPolicyWithTxn(tx, nil, link.ID, aclPolicyGetByID, &token.EnterpriseMeta)
if err != nil {
return 0, err
}
if policy != nil {
// the name doesn't matter here
token.Policies[linkIndex].Name = policy.Name
numValid++
} else if !allowMissing {
return 0, fmt.Errorf("No such policy with ID: %s", link.ID)
}
} else {
return 0, fmt.Errorf("Encountered a Token with policies linked by Name in the state store")
}
}
return numValid, nil
}
// fixupTokenPolicyLinks is to be used when retrieving tokens from memdb. The policy links could have gotten
// stale when a linked policy was deleted or renamed. This will correct them and generate a newly allocated
// token only when fixes are needed. If the policy links are still accurate then we just return the original
// token.
func fixupTokenPolicyLinks(tx ReadTxn, original *structs.ACLToken) (*structs.ACLToken, error) {
owned := false
token := original
cloneToken := func(t *structs.ACLToken, copyNumLinks int) *structs.ACLToken {
clone := *t
clone.Policies = make([]structs.ACLTokenPolicyLink, copyNumLinks)
copy(clone.Policies, t.Policies[:copyNumLinks])
return &clone
}
for linkIndex, link := range original.Policies {
if link.ID == "" {
return nil, fmt.Errorf("Detected corrupted token within the state store - missing policy link ID")
}
policy, err := getPolicyWithTxn(tx, nil, link.ID, aclPolicyGetByID, &token.EnterpriseMeta)
if err != nil {
return nil, err
}
if policy == nil {
if !owned {
// clone the token as we cannot touch the original
token = cloneToken(original, linkIndex)
owned = true
}
// if already owned then we just don't append it.
} else if policy.Name != link.Name {
if !owned {
token = cloneToken(original, linkIndex)
owned = true
}
// append the corrected policy
token.Policies = append(token.Policies, structs.ACLTokenPolicyLink{ID: link.ID, Name: policy.Name})
} else if owned {
token.Policies = append(token.Policies, link)
}
}
return token, nil
}
func resolveTokenRoleLinks(tx *txn, token *structs.ACLToken, allowMissing bool) (int, error) {
var numValid int
for linkIndex, link := range token.Roles {
if link.ID != "" {
role, err := getRoleWithTxn(tx, nil, link.ID, aclRoleGetByID, &token.EnterpriseMeta)
if err != nil {
return 0, err
}
if role != nil {
// the name doesn't matter here
token.Roles[linkIndex].Name = role.Name
numValid++
} else if !allowMissing {
return 0, fmt.Errorf("No such role with ID: %s", link.ID)
}
} else {
return 0, fmt.Errorf("Encountered a Token with roles linked by Name in the state store")
}
}
return numValid, nil
}
// fixupTokenRoleLinks is to be used when retrieving tokens from memdb. The role links could have gotten
// stale when a linked role was deleted or renamed. This will correct them and generate a newly allocated
// token only when fixes are needed. If the role links are still accurate then we just return the original
// token.
func fixupTokenRoleLinks(tx ReadTxn, original *structs.ACLToken) (*structs.ACLToken, error) {
owned := false
token := original
cloneToken := func(t *structs.ACLToken, copyNumLinks int) *structs.ACLToken {
clone := *t
clone.Roles = make([]structs.ACLTokenRoleLink, copyNumLinks)
copy(clone.Roles, t.Roles[:copyNumLinks])
return &clone
}
for linkIndex, link := range original.Roles {
if link.ID == "" {
return nil, fmt.Errorf("Detected corrupted token within the state store - missing role link ID")
}
role, err := getRoleWithTxn(tx, nil, link.ID, aclRoleGetByID, &original.EnterpriseMeta)
if err != nil {
return nil, err
}
if role == nil {
if !owned {
// clone the token as we cannot touch the original
token = cloneToken(original, linkIndex)
owned = true
}
// if already owned then we just don't append it.
} else if role.Name != link.Name {
if !owned {
token = cloneToken(original, linkIndex)
owned = true
}
// append the corrected policy
token.Roles = append(token.Roles, structs.ACLTokenRoleLink{ID: link.ID, Name: role.Name})
} else if owned {
token.Roles = append(token.Roles, link)
}
}
return token, nil
}
func resolveRolePolicyLinks(tx *txn, role *structs.ACLRole, allowMissing bool) error {
for linkIndex, link := range role.Policies {
if link.ID != "" {
policy, err := getPolicyWithTxn(tx, nil, link.ID, aclPolicyGetByID, &role.EnterpriseMeta)
if err != nil {
return err
}
if policy != nil {
// the name doesn't matter here
role.Policies[linkIndex].Name = policy.Name
} else if !allowMissing {
return fmt.Errorf("No such policy with ID: %s", link.ID)
}
} else {
return fmt.Errorf("Encountered a Role with policies linked by Name in the state store")
}
}
return nil
}
// fixupRolePolicyLinks is to be used when retrieving roles from memdb. The policy links could have gotten
// stale when a linked policy was deleted or renamed. This will correct them and generate a newly allocated
// role only when fixes are needed. If the policy links are still accurate then we just return the original
// role.
func fixupRolePolicyLinks(tx ReadTxn, original *structs.ACLRole) (*structs.ACLRole, error) {
owned := false
role := original
cloneRole := func(t *structs.ACLRole, copyNumLinks int) *structs.ACLRole {
clone := *t
clone.Policies = make([]structs.ACLRolePolicyLink, copyNumLinks)
copy(clone.Policies, t.Policies[:copyNumLinks])
return &clone
}
for linkIndex, link := range original.Policies {
if link.ID == "" {
return nil, fmt.Errorf("Detected corrupted role within the state store - missing policy link ID")
}
policy, err := getPolicyWithTxn(tx, nil, link.ID, aclPolicyGetByID, &original.EnterpriseMeta)
if err != nil {
return nil, err
}
if policy == nil {
if !owned {
// clone the token as we cannot touch the original
role = cloneRole(original, linkIndex)
owned = true
}
// if already owned then we just don't append it.
} else if policy.Name != link.Name {
if !owned {
role = cloneRole(original, linkIndex)
owned = true
}
// append the corrected policy
role.Policies = append(role.Policies, structs.ACLRolePolicyLink{ID: link.ID, Name: policy.Name})
} else if owned {
role.Policies = append(role.Policies, link)
}
}
return role, nil
}
// ACLTokenSet is used to insert an ACL rule into the state store.
func (s *Store) ACLTokenSet(idx uint64, token *structs.ACLToken, legacy bool) error {
tx := s.db.WriteTxn(idx)
defer tx.Abort()
// Call set on the ACL
if err := aclTokenSetTxn(tx, idx, token, ACLTokenSetOptions{Legacy: legacy}); err != nil {
return err
}
return tx.Commit()
}
type ACLTokenSetOptions struct {
CAS bool
AllowMissingPolicyAndRoleIDs bool
ProhibitUnprivileged bool
Legacy bool
FromReplication bool
}
func (s *Store) ACLTokenBatchSet(idx uint64, tokens structs.ACLTokens, opts ACLTokenSetOptions) error {
if opts.Legacy {
return fmt.Errorf("failed inserting acl token: cannot use this endpoint to persist legacy tokens")
}
tx := s.db.WriteTxn(idx)
defer tx.Abort()
for _, token := range tokens {
if err := aclTokenSetTxn(tx, idx, token, opts); err != nil {
return err
}
}
return tx.Commit()
}
// aclTokenSetTxn is the inner method used to insert an ACL token with the
// proper indexes into the state store.
func aclTokenSetTxn(tx *txn, idx uint64, token *structs.ACLToken, opts ACLTokenSetOptions) error {
// Check that the ID is set
if token.SecretID == "" {
return ErrMissingACLTokenSecret
}
if !opts.Legacy && token.AccessorID == "" {
return ErrMissingACLTokenAccessor
}
if opts.FromReplication && token.Local {
return fmt.Errorf("Cannot replicate local tokens")
}
// DEPRECATED (ACL-Legacy-Compat)
if token.Rules != "" {
// When we update a legacy acl token we may have to correct old HCL to
// prevent the propagation of older syntax into the state store and
// into in-memory representations.
correctedRules := structs.SanitizeLegacyACLTokenRules(token.Rules)
if correctedRules != "" {
token.Rules = correctedRules
}
}
// Check for an existing ACL
// DEPRECATED (ACL-Legacy-Compat) - transition to using accessor index instead of secret once v1 compat is removed
_, existing, err := aclTokenGetFromIndex(tx, token.SecretID, "id", nil)
if err != nil {
return fmt.Errorf("failed token lookup: %s", err)
}
var original *structs.ACLToken
if existing != nil {
original = existing.(*structs.ACLToken)
}
if opts.CAS {
// set-if-unset case
if token.ModifyIndex == 0 && original != nil {
return nil
}
// token already deleted
if token.ModifyIndex != 0 && original == nil {
return nil
}
// check for other modifications
if token.ModifyIndex != 0 && token.ModifyIndex != original.ModifyIndex {
return nil
}
}
if opts.Legacy && original != nil {
if original.UsesNonLegacyFields() {
return fmt.Errorf("failed inserting acl token: cannot use legacy endpoint to modify a non-legacy token")
}
token.AccessorID = original.AccessorID
}
if err := aclTokenUpsertValidateEnterprise(tx, token, original); err != nil {
return err
}
var numValidPolicies int
if numValidPolicies, err = resolveTokenPolicyLinks(tx, token, opts.AllowMissingPolicyAndRoleIDs); err != nil {
return err
}
var numValidRoles int
if numValidRoles, err = resolveTokenRoleLinks(tx, token, opts.AllowMissingPolicyAndRoleIDs); err != nil {
return err
}
if token.AuthMethod != "" && !opts.FromReplication {
method, err := getAuthMethodWithTxn(tx, nil, token.AuthMethod, token.ACLAuthMethodEnterpriseMeta.ToEnterpriseMeta())
if err != nil {
return err
} else if method == nil {
return fmt.Errorf("No such auth method with Name: %s", token.AuthMethod)
}
}
for _, svcid := range token.ServiceIdentities {
if svcid.ServiceName == "" {
return fmt.Errorf("Encountered a Token with an empty service identity name in the state store")
}
}
for _, nodeid := range token.NodeIdentities {
if nodeid.NodeName == "" {
return fmt.Errorf("Encountered a Token with an empty node identity name in the state store")
}
if nodeid.Datacenter == "" {
return fmt.Errorf("Encountered a Token with an empty node identity datacenter in the state store")
}
}
if opts.ProhibitUnprivileged {
if numValidRoles == 0 && numValidPolicies == 0 && len(token.ServiceIdentities) == 0 && len(token.NodeIdentities) == 0 {
return ErrTokenHasNoPrivileges
}
}
// Set the indexes
if original != nil {
if original.AccessorID != "" && token.AccessorID != original.AccessorID {
return fmt.Errorf("The ACL Token AccessorID field is immutable")
}
if token.SecretID != original.SecretID {
return fmt.Errorf("The ACL Token SecretID field is immutable")
}
token.CreateIndex = original.CreateIndex
token.ModifyIndex = idx
} else {
token.CreateIndex = idx
token.ModifyIndex = idx
}
// ensure that a hash is set
token.SetHash(false)
return aclTokenInsert(tx, token)
}
// ACLTokenGetBySecret is used to look up an existing ACL token by its SecretID.
func (s *Store) ACLTokenGetBySecret(ws memdb.WatchSet, secret string, entMeta *structs.EnterpriseMeta) (uint64, *structs.ACLToken, error) {
return s.aclTokenGet(ws, secret, "id", entMeta)
}
// ACLTokenGetByAccessor is used to look up an existing ACL token by its AccessorID.
func (s *Store) ACLTokenGetByAccessor(ws memdb.WatchSet, accessor string, entMeta *structs.EnterpriseMeta) (uint64, *structs.ACLToken, error) {
return s.aclTokenGet(ws, accessor, "accessor", entMeta)
}
// aclTokenGet looks up a token using one of the indexes provided
func (s *Store) aclTokenGet(ws memdb.WatchSet, value, index string, entMeta *structs.EnterpriseMeta) (uint64, *structs.ACLToken, error) {
tx := s.db.Txn(false)
defer tx.Abort()
token, err := aclTokenGetTxn(tx, ws, value, index, entMeta)
if err != nil {
return 0, nil, err
}
idx := aclTokenMaxIndex(tx, token, entMeta)
return idx, token, nil
}
func (s *Store) ACLTokenBatchGet(ws memdb.WatchSet, accessors []string) (uint64, structs.ACLTokens, error) {
tx := s.db.Txn(false)
defer tx.Abort()
tokens := make(structs.ACLTokens, 0)
for _, accessor := range accessors {
token, err := aclTokenGetTxn(tx, ws, accessor, "accessor", nil)
if err != nil {
return 0, nil, fmt.Errorf("failed acl token lookup: %v", err)
}
// token == nil is valid and will indic
if token != nil {
tokens = append(tokens, token)
}
}
idx := maxIndexTxn(tx, "acl-tokens")
return idx, tokens, nil
}
func aclTokenGetTxn(tx ReadTxn, ws memdb.WatchSet, value, index string, entMeta *structs.EnterpriseMeta) (*structs.ACLToken, error) {
watchCh, rawToken, err := aclTokenGetFromIndex(tx, value, index, entMeta)
if err != nil {
return nil, fmt.Errorf("failed acl token lookup: %v", err)
}
ws.Add(watchCh)
if rawToken != nil {
token := rawToken.(*structs.ACLToken)
token, err := fixupTokenPolicyLinks(tx, token)
if err != nil {
return nil, err
}
token, err = fixupTokenRoleLinks(tx, token)
if err != nil {
return nil, err
}
return token, nil
}
return nil, nil
}
// ACLTokenList is used to list out all of the ACLs in the state store.
func (s *Store) ACLTokenList(ws memdb.WatchSet, local, global bool, policy, role, methodName string, methodMeta, entMeta *structs.EnterpriseMeta) (uint64, structs.ACLTokens, error) {
tx := s.db.Txn(false)
defer tx.Abort()
var iter memdb.ResultIterator
var err error
// Note global == local works when both are true or false. It is not valid to set both
// to false but for defaulted structs (zero values for both) we want it to list out
// all tokens so our checks just ensure that global == local
needLocalityFilter := false
if policy == "" && role == "" && methodName == "" {
if global == local {
iter, err = aclTokenListAll(tx, entMeta)
} else if global {
iter, err = aclTokenListGlobal(tx, entMeta)
} else {
iter, err = aclTokenListLocal(tx, entMeta)
}
} else if policy != "" && role == "" && methodName == "" {
iter, err = aclTokenListByPolicy(tx, policy, entMeta)
needLocalityFilter = true
} else if policy == "" && role != "" && methodName == "" {
iter, err = aclTokenListByRole(tx, role, entMeta)
needLocalityFilter = true
} else if policy == "" && role == "" && methodName != "" {
iter, err = aclTokenListByAuthMethod(tx, methodName, methodMeta, entMeta)
needLocalityFilter = true
} else {
return 0, nil, fmt.Errorf("can only filter by one of policy, role, or methodName at a time")
}
if err != nil {
return 0, nil, fmt.Errorf("failed acl token lookup: %v", err)
}
if needLocalityFilter && global != local {
iter = memdb.NewFilterIterator(iter, func(raw interface{}) bool {
token, ok := raw.(*structs.ACLToken)
if !ok {
return true
}
if global && !token.Local {
return false
} else if local && token.Local {
return false
}
return true
})
}
ws.Add(iter.WatchCh())
var result structs.ACLTokens
for raw := iter.Next(); raw != nil; raw = iter.Next() {
token := raw.(*structs.ACLToken)
token, err := fixupTokenPolicyLinks(tx, token)
if err != nil {
return 0, nil, err
}
token, err = fixupTokenRoleLinks(tx, token)
if err != nil {
return 0, nil, err
}
result = append(result, token)
}
// Get the table index.
idx := aclTokenMaxIndex(tx, nil, entMeta)
return idx, result, nil
}
func (s *Store) ACLTokenListUpgradeable(max int) (structs.ACLTokens, <-chan struct{}, error) {
tx := s.db.Txn(false)
defer tx.Abort()
iter, err := tx.Get("acl-tokens", "needs-upgrade", true)
if err != nil {
return nil, nil, fmt.Errorf("failed acl token listing: %v", err)
}
var tokens structs.ACLTokens
i := 0
for token := iter.Next(); token != nil; token = iter.Next() {
tokens = append(tokens, token.(*structs.ACLToken))
i += 1
if i >= max {
return tokens, nil, nil
}
}
return tokens, iter.WatchCh(), nil
}
func (s *Store) ACLTokenMinExpirationTime(local bool) (time.Time, error) {
tx := s.db.Txn(false)
defer tx.Abort()
item, err := tx.First("acl-tokens", s.expiresIndexName(local))
if err != nil {
return time.Time{}, fmt.Errorf("failed acl token listing: %v", err)
}
if item == nil {
return time.Time{}, nil
}
token := item.(*structs.ACLToken)
return *token.ExpirationTime, nil
}
// ACLTokenListExpires lists tokens that are expired as of the provided time.
// The returned set will be no larger than the max value provided.
func (s *Store) ACLTokenListExpired(local bool, asOf time.Time, max int) (structs.ACLTokens, <-chan struct{}, error) {
tx := s.db.Txn(false)
defer tx.Abort()
iter, err := tx.Get("acl-tokens", s.expiresIndexName(local))
if err != nil {
return nil, nil, fmt.Errorf("failed acl token listing: %v", err)
}
var (
tokens structs.ACLTokens
i int
)