/
acl_endpoint.go
2580 lines (2115 loc) · 74.3 KB
/
acl_endpoint.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 consul
import (
"context"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"time"
"github.com/armon/go-metrics"
"github.com/armon/go-metrics/prometheus"
"github.com/hashicorp/go-bexpr"
"github.com/hashicorp/go-hclog"
memdb "github.com/hashicorp/go-memdb"
uuid "github.com/hashicorp/go-uuid"
"github.com/hashicorp/consul/acl"
"github.com/hashicorp/consul/agent/consul/authmethod"
"github.com/hashicorp/consul/agent/consul/state"
"github.com/hashicorp/consul/agent/structs"
"github.com/hashicorp/consul/lib"
"github.com/hashicorp/consul/lib/template"
)
const (
// aclBootstrapReset is the file name to create in the data dir. It's only contents
// should be the reset index
aclBootstrapReset = "acl-bootstrap-reset"
)
var ACLEndpointSummaries = []prometheus.SummaryDefinition{
{
Name: []string{"acl", "token", "clone"},
Help: "",
},
{
Name: []string{"acl", "token", "upsert"},
Help: "",
},
{
Name: []string{"acl", "token", "delete"},
Help: "",
},
{
Name: []string{"acl", "policy", "upsert"},
Help: "",
},
{
Name: []string{"acl", "policy", "delete"},
Help: "",
},
{
Name: []string{"acl", "policy", "delete"},
Help: "",
},
{
Name: []string{"acl", "role", "upsert"},
Help: "",
},
{
Name: []string{"acl", "role", "delete"},
Help: "",
},
{
Name: []string{"acl", "bindingrule", "upsert"},
Help: "",
},
{
Name: []string{"acl", "bindingrule", "delete"},
Help: "",
},
{
Name: []string{"acl", "authmethod", "upsert"},
Help: "",
},
{
Name: []string{"acl", "authmethod", "delete"},
Help: "",
},
{
Name: []string{"acl", "login"},
Help: "",
},
{
Name: []string{"acl", "login"},
Help: "",
},
{
Name: []string{"acl", "logout"},
Help: "",
},
{
Name: []string{"acl", "logout"},
Help: "",
},
}
// Regex for matching
var (
validPolicyName = regexp.MustCompile(`^[A-Za-z0-9\-_]{1,128}$`)
validServiceIdentityName = regexp.MustCompile(`^[a-z0-9]([a-z0-9\-_]*[a-z0-9])?$`)
serviceIdentityNameMaxLength = 256
validNodeIdentityName = regexp.MustCompile(`^[a-z0-9]([a-z0-9\-_]*[a-z0-9])?$`)
nodeIdentityNameMaxLength = 256
validRoleName = regexp.MustCompile(`^[A-Za-z0-9\-_]{1,256}$`)
validAuthMethod = regexp.MustCompile(`^[A-Za-z0-9\-_]{1,128}$`)
)
// ACL endpoint is used to manipulate ACLs
type ACL struct {
srv *Server
logger hclog.Logger
}
// fileBootstrapResetIndex retrieves the reset index specified by the administrator from
// the file on disk.
//
// Q: What is the bootstrap reset index?
// A: If you happen to lose acess to all tokens capable of ACL management you need a way
// to get back into your system. This allows an admin to write the current
// bootstrap "index" into a special file on disk to override the mechanism preventing
// a second token bootstrap. The index will be retrieved by a API call to /v1/acl/bootstrap
// When already bootstrapped this API will return the reset index necessary within
// the error response. Once set in the file, the bootstrap API can be used again to
// get a new token.
//
// Q: Why is the reset index not in the config?
// A: We want to be able to remove the reset index once we have used it. This prevents
// accidentally allowing bootstrapping yet again after a snapshot restore.
//
func (a *ACL) fileBootstrapResetIndex() uint64 {
// Determine the file path to check
path := filepath.Join(a.srv.config.DataDir, aclBootstrapReset)
// Read the file
raw, err := ioutil.ReadFile(path)
if err != nil {
if !os.IsNotExist(err) {
a.logger.Error("bootstrap: failed to read path",
"path", path,
"error", err,
)
}
return 0
}
// Attempt to parse the file
var resetIdx uint64
if _, err := fmt.Sscanf(string(raw), "%d", &resetIdx); err != nil {
a.logger.Error("failed to parse bootstrap reset index path", "path", path, "error", err)
return 0
}
// Return the reset index
a.logger.Debug("parsed bootstrap reset index path", "path", path, "reset_index", resetIdx)
return resetIdx
}
func (a *ACL) removeBootstrapResetFile() {
if err := os.Remove(filepath.Join(a.srv.config.DataDir, aclBootstrapReset)); err != nil {
a.logger.Warn("failed to remove bootstrap file", "error", err)
}
}
func (a *ACL) aclPreCheck() error {
if !a.srv.config.ACLsEnabled {
return acl.ErrDisabled
}
if a.srv.UseLegacyACLs() {
return fmt.Errorf("The ACL system is currently in legacy mode.")
}
return nil
}
// Bootstrap is used to perform a one-time ACL bootstrap operation on
// a cluster to get the first management token.
func (a *ACL) BootstrapTokens(args *structs.DCSpecificRequest, reply *structs.ACLToken) error {
if err := a.aclPreCheck(); err != nil {
return err
}
if done, err := a.srv.ForwardRPC("ACL.BootstrapTokens", args, reply); done {
return err
}
if err := a.srv.aclBootstrapAllowed(); err != nil {
return err
}
// Verify we are allowed to serve this request
if !a.srv.InACLDatacenter() {
return acl.ErrDisabled
}
// By doing some pre-checks we can head off later bootstrap attempts
// without having to run them through Raft, which should curb abuse.
state := a.srv.fsm.State()
allowed, resetIdx, err := state.CanBootstrapACLToken()
if err != nil {
return err
}
var specifiedIndex uint64 = 0
if !allowed {
// Check if there is a reset index specified
specifiedIndex = a.fileBootstrapResetIndex()
if specifiedIndex == 0 {
return fmt.Errorf("ACL bootstrap no longer allowed (reset index: %d)", resetIdx)
} else if specifiedIndex != resetIdx {
return fmt.Errorf("Invalid bootstrap reset index (specified %d, reset index: %d)", specifiedIndex, resetIdx)
}
}
// remove the bootstrap override file now that we have the index from it and it was valid.
// whether bootstrapping works or not is irrelevant as we really don't want this file hanging around
// in case a snapshot restore is done. In that case we don't want to accidentally allow re-bootstrapping
// just because the file was unchanged.
a.removeBootstrapResetFile()
accessor, err := lib.GenerateUUID(a.srv.checkTokenUUID)
if err != nil {
return err
}
secret, err := lib.GenerateUUID(a.srv.checkTokenUUID)
if err != nil {
return err
}
req := structs.ACLTokenBootstrapRequest{
Token: structs.ACLToken{
AccessorID: accessor,
SecretID: secret,
Description: "Bootstrap Token (Global Management)",
Policies: []structs.ACLTokenPolicyLink{
{
ID: structs.ACLPolicyGlobalManagementID,
},
},
CreateTime: time.Now(),
Local: false,
// DEPRECATED (ACL-Legacy-Compat) - This is used so that the bootstrap token is still visible via the v1 acl APIs
Type: structs.ACLTokenTypeManagement,
EnterpriseMeta: *structs.DefaultEnterpriseMeta(),
},
ResetIndex: specifiedIndex,
}
req.Token.SetHash(true)
_, err = a.srv.raftApply(structs.ACLBootstrapRequestType, &req)
if err != nil {
return err
}
if _, token, err := state.ACLTokenGetByAccessor(nil, accessor, structs.DefaultEnterpriseMeta()); err == nil {
*reply = *token
}
a.logger.Info("ACL bootstrap completed")
return nil
}
func (a *ACL) TokenRead(args *structs.ACLTokenGetRequest, reply *structs.ACLTokenResponse) error {
if err := a.aclPreCheck(); err != nil {
return err
}
if err := a.srv.validateEnterpriseRequest(&args.EnterpriseMeta, false); err != nil {
return err
}
// clients will not know whether the server has local token store. In the case
// where it doesn't we will transparently forward requests.
if !a.srv.LocalTokensEnabled() {
args.Datacenter = a.srv.config.ACLDatacenter
}
if done, err := a.srv.ForwardRPC("ACL.TokenRead", args, reply); done {
return err
}
var authz acl.Authorizer
if args.TokenIDType == structs.ACLTokenAccessor {
var err error
var authzContext acl.AuthorizerContext
// Only ACLRead privileges are required to list tokens
// However if you do not have ACLWrite as well the token
// secrets will be redacted
if authz, err = a.srv.ResolveTokenAndDefaultMeta(args.Token, &args.EnterpriseMeta, &authzContext); err != nil {
return err
} else if authz == nil || authz.ACLRead(&authzContext) != acl.Allow {
return acl.ErrPermissionDenied
}
}
return a.srv.blockingQuery(&args.QueryOptions, &reply.QueryMeta,
func(ws memdb.WatchSet, state *state.Store) error {
var index uint64
var token *structs.ACLToken
var err error
if args.TokenIDType == structs.ACLTokenAccessor {
index, token, err = state.ACLTokenGetByAccessor(ws, args.TokenID, &args.EnterpriseMeta)
if token != nil {
a.srv.filterACLWithAuthorizer(authz, &token)
// token secret was redacted
if token.SecretID == redactedToken {
reply.Redacted = true
}
}
} else {
index, token, err = state.ACLTokenGetBySecret(ws, args.TokenID, nil)
// no extra validation is needed here. If you have the secret ID you can read it.
}
if token != nil && token.IsExpired(time.Now()) {
token = nil
}
if err != nil {
return err
}
reply.Index, reply.Token = index, token
reply.SourceDatacenter = args.Datacenter
return nil
})
}
func (a *ACL) TokenClone(args *structs.ACLTokenSetRequest, reply *structs.ACLToken) error {
if err := a.aclPreCheck(); err != nil {
return err
}
if err := a.srv.validateEnterpriseRequest(&args.ACLToken.EnterpriseMeta, true); err != nil {
return err
}
// clients will not know whether the server has local token store. In the case
// where it doesn't we will transparently forward requests.
if !a.srv.LocalTokensEnabled() {
args.Datacenter = a.srv.config.ACLDatacenter
}
if done, err := a.srv.ForwardRPC("ACL.TokenClone", args, reply); done {
return err
}
defer metrics.MeasureSince([]string{"acl", "token", "clone"}, time.Now())
var authzContext acl.AuthorizerContext
authz, err := a.srv.ResolveTokenAndDefaultMeta(args.Token, &args.ACLToken.EnterpriseMeta, &authzContext)
if err != nil {
return err
} else if authz == nil || authz.ACLWrite(&authzContext) != acl.Allow {
return acl.ErrPermissionDenied
}
_, token, err := a.srv.fsm.State().ACLTokenGetByAccessor(nil, args.ACLToken.AccessorID, &args.ACLToken.EnterpriseMeta)
if err != nil {
return err
} else if token == nil || token.IsExpired(time.Now()) {
return acl.ErrNotFound
} else if !a.srv.InACLDatacenter() && !token.Local {
// global token writes must be forwarded to the primary DC
args.Datacenter = a.srv.config.ACLDatacenter
return a.srv.forwardDC("ACL.TokenClone", a.srv.config.ACLDatacenter, args, reply)
}
if token.AuthMethod != "" {
return fmt.Errorf("Cannot clone a token created from an auth method")
}
if token.Rules != "" {
return fmt.Errorf("Cannot clone a legacy ACL with this endpoint")
}
cloneReq := structs.ACLTokenSetRequest{
Datacenter: args.Datacenter,
ACLToken: structs.ACLToken{
Policies: token.Policies,
Roles: token.Roles,
ServiceIdentities: token.ServiceIdentities,
NodeIdentities: token.NodeIdentities,
Local: token.Local,
Description: token.Description,
ExpirationTime: token.ExpirationTime,
EnterpriseMeta: args.ACLToken.EnterpriseMeta,
},
WriteRequest: args.WriteRequest,
}
if args.ACLToken.Description != "" {
cloneReq.ACLToken.Description = args.ACLToken.Description
}
return a.tokenSetInternal(&cloneReq, reply, false)
}
func (a *ACL) TokenSet(args *structs.ACLTokenSetRequest, reply *structs.ACLToken) error {
if err := a.aclPreCheck(); err != nil {
return err
}
if err := a.srv.validateEnterpriseRequest(&args.ACLToken.EnterpriseMeta, true); err != nil {
return err
}
// Global token creation/modification always goes to the ACL DC
if !args.ACLToken.Local {
args.Datacenter = a.srv.config.ACLDatacenter
} else if !a.srv.LocalTokensEnabled() {
return fmt.Errorf("Local tokens are disabled")
}
if done, err := a.srv.ForwardRPC("ACL.TokenSet", args, reply); done {
return err
}
defer metrics.MeasureSince([]string{"acl", "token", "upsert"}, time.Now())
// Verify token is permitted to modify ACLs
var authzContext acl.AuthorizerContext
if authz, err := a.srv.ResolveTokenAndDefaultMeta(args.Token, &args.ACLToken.EnterpriseMeta, &authzContext); err != nil {
return err
} else if authz == nil || authz.ACLWrite(&authzContext) != acl.Allow {
return acl.ErrPermissionDenied
}
return a.tokenSetInternal(args, reply, false)
}
func (a *ACL) tokenSetInternal(args *structs.ACLTokenSetRequest, reply *structs.ACLToken, fromLogin bool) error {
token := &args.ACLToken
if !a.srv.LocalTokensEnabled() {
// local token operations
return fmt.Errorf("Cannot upsert tokens within this datacenter")
} else if !a.srv.InACLDatacenter() && !token.Local {
return fmt.Errorf("Cannot upsert global tokens within this datacenter")
}
state := a.srv.fsm.State()
var accessorMatch *structs.ACLToken
var secretMatch *structs.ACLToken
var err error
if token.AccessorID != "" {
_, accessorMatch, err = state.ACLTokenGetByAccessor(nil, token.AccessorID, nil)
if err != nil {
return fmt.Errorf("Failed acl token lookup by accessor: %v", err)
}
}
if token.SecretID != "" {
_, secretMatch, err = state.ACLTokenGetBySecret(nil, token.SecretID, nil)
if err != nil {
return fmt.Errorf("Failed acl token lookup by secret: %v", err)
}
}
if token.AccessorID == "" || args.Create {
// Token Create
// Generate the AccessorID if not specified
if token.AccessorID == "" {
token.AccessorID, err = lib.GenerateUUID(a.srv.checkTokenUUID)
if err != nil {
return err
}
} else if _, err := uuid.ParseUUID(token.AccessorID); err != nil {
return fmt.Errorf("Invalid Token: AccessorID is not a valid UUID")
} else if accessorMatch != nil {
return fmt.Errorf("Invalid Token: AccessorID is already in use")
} else if _, match, err := state.ACLTokenGetBySecret(nil, token.AccessorID, nil); err != nil || match != nil {
if err != nil {
return fmt.Errorf("Failed to lookup the acl token: %v", err)
}
return fmt.Errorf("Invalid Token: AccessorID is already in use")
} else if structs.ACLIDReserved(token.AccessorID) {
return fmt.Errorf("Invalid Token: UUIDs with the prefix %q are reserved", structs.ACLReservedPrefix)
}
// Generate the SecretID if not specified
if token.SecretID == "" {
token.SecretID, err = lib.GenerateUUID(a.srv.checkTokenUUID)
if err != nil {
return err
}
} else if _, err := uuid.ParseUUID(token.SecretID); err != nil {
return fmt.Errorf("Invalid Token: SecretID is not a valid UUID")
} else if secretMatch != nil {
return fmt.Errorf("Invalid Token: SecretID is already in use")
} else if _, match, err := state.ACLTokenGetByAccessor(nil, token.SecretID, nil); err != nil || match != nil {
if err != nil {
return fmt.Errorf("Failed to lookup the acl token: %v", err)
}
return fmt.Errorf("Invalid Token: SecretID is already in use")
} else if structs.ACLIDReserved(token.SecretID) {
return fmt.Errorf("Invalid Token: UUIDs with the prefix %q are reserved", structs.ACLReservedPrefix)
}
token.CreateTime = time.Now()
if fromLogin {
if token.AuthMethod == "" {
return fmt.Errorf("AuthMethod field is required during Login")
}
} else {
if token.AuthMethod != "" {
return fmt.Errorf("AuthMethod field is disallowed outside of Login")
}
}
// Ensure an ExpirationTTL is valid if provided.
if token.ExpirationTTL != 0 {
if token.ExpirationTTL < 0 {
return fmt.Errorf("Token Expiration TTL '%s' should be > 0", token.ExpirationTTL)
}
if token.HasExpirationTime() {
return fmt.Errorf("Token Expiration TTL and Expiration Time cannot both be set")
}
token.ExpirationTime = timePointer(token.CreateTime.Add(token.ExpirationTTL))
token.ExpirationTTL = 0
}
if token.HasExpirationTime() {
if token.CreateTime.After(*token.ExpirationTime) {
return fmt.Errorf("ExpirationTime cannot be before CreateTime")
}
expiresIn := token.ExpirationTime.Sub(token.CreateTime)
if expiresIn > a.srv.config.ACLTokenMaxExpirationTTL {
return fmt.Errorf("ExpirationTime cannot be more than %s in the future (was %s)",
a.srv.config.ACLTokenMaxExpirationTTL, expiresIn)
} else if expiresIn < a.srv.config.ACLTokenMinExpirationTTL {
return fmt.Errorf("ExpirationTime cannot be less than %s in the future (was %s)",
a.srv.config.ACLTokenMinExpirationTTL, expiresIn)
}
}
} else {
// Token Update
if _, err := uuid.ParseUUID(token.AccessorID); err != nil {
return fmt.Errorf("AccessorID is not a valid UUID")
}
// DEPRECATED (ACL-Legacy-Compat) - maybe get rid of this in the future
// and instead do a ParseUUID check. New tokens will not have
// secrets generated by users but rather they will always be UUIDs.
// However if users just continue the upgrade cycle they may still
// have tokens using secrets that are not UUIDS
// The RootAuthorizer checks that the SecretID is not "allow", "deny"
// or "manage" as a precaution against something accidentally using
// one of these root policies by setting the secret to it.
if acl.RootAuthorizer(token.SecretID) != nil {
return acl.PermissionDeniedError{Cause: "Cannot modify root ACL"}
}
// Verify the token exists
if accessorMatch == nil || accessorMatch.IsExpired(time.Now()) {
return fmt.Errorf("Cannot find token %q", token.AccessorID)
}
if token.SecretID == "" {
token.SecretID = accessorMatch.SecretID
} else if accessorMatch.SecretID != token.SecretID {
return fmt.Errorf("Changing a tokens SecretID is not permitted")
}
// Cannot toggle the "Global" mode
if token.Local != accessorMatch.Local {
return fmt.Errorf("cannot toggle local mode of %s", token.AccessorID)
}
if token.AuthMethod == "" {
token.AuthMethod = accessorMatch.AuthMethod
} else if token.AuthMethod != accessorMatch.AuthMethod {
return fmt.Errorf("Cannot change AuthMethod of %s", token.AccessorID)
}
if token.ExpirationTTL != 0 {
return fmt.Errorf("Cannot change expiration time of %s", token.AccessorID)
}
if !token.HasExpirationTime() {
token.ExpirationTime = accessorMatch.ExpirationTime
} else if !accessorMatch.HasExpirationTime() {
return fmt.Errorf("Cannot change expiration time of %s", token.AccessorID)
} else if !token.ExpirationTime.Equal(*accessorMatch.ExpirationTime) {
return fmt.Errorf("Cannot change expiration time of %s", token.AccessorID)
}
token.CreateTime = accessorMatch.CreateTime
}
policyIDs := make(map[string]struct{})
var policies []structs.ACLTokenPolicyLink
// Validate all the policy names and convert them to policy IDs
for _, link := range token.Policies {
if link.ID == "" {
_, policy, err := state.ACLPolicyGetByName(nil, link.Name, &token.EnterpriseMeta)
if err != nil {
return fmt.Errorf("Error looking up policy for name %q: %v", link.Name, err)
}
if policy == nil {
return fmt.Errorf("No such ACL policy with name %q", link.Name)
}
link.ID = policy.ID
} else {
_, policy, err := state.ACLPolicyGetByID(nil, link.ID, &token.EnterpriseMeta)
if err != nil {
return fmt.Errorf("Error looking up policy for id %q: %v", link.ID, err)
}
if policy == nil {
return fmt.Errorf("No such ACL policy with ID %q", link.ID)
}
}
// Do not store the policy name within raft/memdb as the policy could be renamed in the future.
link.Name = ""
// dedup policy links by id
if _, ok := policyIDs[link.ID]; !ok {
policies = append(policies, link)
policyIDs[link.ID] = struct{}{}
}
}
token.Policies = policies
roleIDs := make(map[string]struct{})
var roles []structs.ACLTokenRoleLink
// Validate all the role names and convert them to role IDs.
for _, link := range token.Roles {
if link.ID == "" {
_, role, err := state.ACLRoleGetByName(nil, link.Name, &token.EnterpriseMeta)
if err != nil {
return fmt.Errorf("Error looking up role for name %q: %v", link.Name, err)
}
if role == nil {
return fmt.Errorf("No such ACL role with name %q", link.Name)
}
link.ID = role.ID
} else {
_, role, err := state.ACLRoleGetByID(nil, link.ID, &token.EnterpriseMeta)
if err != nil {
return fmt.Errorf("Error looking up role for id %q: %v", link.ID, err)
}
if role == nil {
return fmt.Errorf("No such ACL role with ID %q", link.ID)
}
}
// Do not store the role name within raft/memdb as the role could be renamed in the future.
link.Name = ""
// dedup role links by id
if _, ok := roleIDs[link.ID]; !ok {
roles = append(roles, link)
roleIDs[link.ID] = struct{}{}
}
}
token.Roles = roles
for _, svcid := range token.ServiceIdentities {
if svcid.ServiceName == "" {
return fmt.Errorf("Service identity is missing the service name field on this token")
}
if token.Local && len(svcid.Datacenters) > 0 {
return fmt.Errorf("Service identity %q cannot specify a list of datacenters on a local token", svcid.ServiceName)
}
if !isValidServiceIdentityName(svcid.ServiceName) {
return fmt.Errorf("Service identity %q has an invalid name. Only alphanumeric characters, '-' and '_' are allowed", svcid.ServiceName)
}
}
token.ServiceIdentities = dedupeServiceIdentities(token.ServiceIdentities)
for _, nodeid := range token.NodeIdentities {
if nodeid.NodeName == "" {
return fmt.Errorf("Node identity is missing the node name field on this token")
}
if nodeid.Datacenter == "" {
return fmt.Errorf("Node identity is missing the datacenter field on this token")
}
if !isValidNodeIdentityName(nodeid.NodeName) {
return fmt.Errorf("Node identity has an invalid name. Only alphanumeric characters, '-' and '_' are allowed")
}
}
token.NodeIdentities = dedupeNodeIdentities(token.NodeIdentities)
if token.Rules != "" {
return fmt.Errorf("Rules cannot be specified for this token")
}
if token.Type != "" {
return fmt.Errorf("Type cannot be specified for this token")
}
token.SetHash(true)
// validate the enterprise meta
err = state.ACLTokenUpsertValidateEnterprise(token, accessorMatch)
if err != nil {
return err
}
req := &structs.ACLTokenBatchSetRequest{
Tokens: structs.ACLTokens{token},
CAS: false,
}
if fromLogin {
// Logins may attempt to link to roles that do not exist. These
// may be persisted, but don't allow tokens to be created that
// have no privileges (i.e. role links that point nowhere).
req.AllowMissingLinks = true
req.ProhibitUnprivileged = true
}
_, err = a.srv.raftApply(structs.ACLTokenSetRequestType, req)
if err != nil {
return fmt.Errorf("Failed to apply token write request: %v", err)
}
// Purge the identity from the cache to prevent using the previous definition of the identity
a.srv.acls.cache.RemoveIdentity(tokenSecretCacheID(token.SecretID))
// Don't check expiration times here as it doesn't really matter.
if _, updatedToken, err := a.srv.fsm.State().ACLTokenGetByAccessor(nil, token.AccessorID, nil); err == nil && updatedToken != nil {
*reply = *updatedToken
} else {
return fmt.Errorf("Failed to retrieve the token after insertion")
}
return nil
}
func validateBindingRuleBindName(bindType, bindName string, availableFields []string) (bool, error) {
if bindType == "" || bindName == "" {
return false, nil
}
fakeVarMap := make(map[string]string)
for _, v := range availableFields {
fakeVarMap[v] = "fake"
}
_, valid, err := computeBindingRuleBindName(bindType, bindName, fakeVarMap)
if err != nil {
return false, err
}
return valid, nil
}
// computeBindingRuleBindName processes the HIL for the provided bind type+name
// using the projected variables.
//
// - If the HIL is invalid ("", false, AN_ERROR) is returned.
// - If the computed name is not valid for the type ("INVALID_NAME", false, nil) is returned.
// - If the computed name is valid for the type ("VALID_NAME", true, nil) is returned.
func computeBindingRuleBindName(bindType, bindName string, projectedVars map[string]string) (string, bool, error) {
bindName, err := template.InterpolateHIL(bindName, projectedVars, true)
if err != nil {
return "", false, err
}
valid := false
switch bindType {
case structs.BindingRuleBindTypeService:
valid = isValidServiceIdentityName(bindName)
case structs.BindingRuleBindTypeNode:
valid = isValidNodeIdentityName(bindName)
case structs.BindingRuleBindTypeRole:
valid = validRoleName.MatchString(bindName)
default:
return "", false, fmt.Errorf("unknown binding rule bind type: %s", bindType)
}
return bindName, valid, nil
}
// isValidServiceIdentityName returns true if the provided name can be used as
// an ACLServiceIdentity ServiceName. This is more restrictive than standard
// catalog registration, which basically takes the view that "everything is
// valid".
func isValidServiceIdentityName(name string) bool {
if len(name) < 1 || len(name) > serviceIdentityNameMaxLength {
return false
}
return validServiceIdentityName.MatchString(name)
}
// isValidNodeIdentityName returns true if the provided name can be used as
// an ACLNodeIdentity NodeName. This is more restrictive than standard
// catalog registration, which basically takes the view that "everything is
// valid".
func isValidNodeIdentityName(name string) bool {
if len(name) < 1 || len(name) > nodeIdentityNameMaxLength {
return false
}
return validNodeIdentityName.MatchString(name)
}
func (a *ACL) TokenDelete(args *structs.ACLTokenDeleteRequest, reply *string) error {
if err := a.aclPreCheck(); err != nil {
return err
}
if err := a.srv.validateEnterpriseRequest(&args.EnterpriseMeta, true); err != nil {
return err
}
if !a.srv.LocalTokensEnabled() {
args.Datacenter = a.srv.config.ACLDatacenter
}
if done, err := a.srv.ForwardRPC("ACL.TokenDelete", args, reply); done {
return err
}
defer metrics.MeasureSince([]string{"acl", "token", "delete"}, time.Now())
// Verify token is permitted to modify ACLs
var authzContext acl.AuthorizerContext
if authz, err := a.srv.ResolveTokenAndDefaultMeta(args.Token, &args.EnterpriseMeta, &authzContext); err != nil {
return err
} else if authz == nil || authz.ACLWrite(&authzContext) != acl.Allow {
return acl.ErrPermissionDenied
}
if _, err := uuid.ParseUUID(args.TokenID); err != nil {
return fmt.Errorf("Accessor ID is missing or an invalid UUID")
}
if args.TokenID == structs.ACLTokenAnonymousID {
return fmt.Errorf("Delete operation not permitted on the anonymous token")
}
// grab the token here so we can invalidate our cache later on
_, token, err := a.srv.fsm.State().ACLTokenGetByAccessor(nil, args.TokenID, &args.EnterpriseMeta)
if err != nil {
return err
}
if token != nil {
if args.Token == token.SecretID {
return fmt.Errorf("Deletion of the request's authorization token is not permitted")
}
// No need to check expiration time because it's being deleted.
// token found in secondary DC but its not local so it must be deleted in the primary
if !a.srv.InACLDatacenter() && !token.Local {
args.Datacenter = a.srv.config.ACLDatacenter
return a.srv.forwardDC("ACL.TokenDelete", a.srv.config.ACLDatacenter, args, reply)
}
} else if !a.srv.InACLDatacenter() {
// token not found in secondary DC - attempt to delete within the primary
args.Datacenter = a.srv.config.ACLDatacenter
return a.srv.forwardDC("ACL.TokenDelete", a.srv.config.ACLDatacenter, args, reply)
} else {
// in Primary Datacenter but the token does not exist - return early as there is nothing to do.
return nil
}
req := &structs.ACLTokenBatchDeleteRequest{
TokenIDs: []string{args.TokenID},
}
_, err = a.srv.raftApply(structs.ACLTokenDeleteRequestType, req)
if err != nil {
return fmt.Errorf("Failed to apply token delete request: %v", err)
}
// Purge the identity from the cache to prevent using the previous definition of the identity
a.srv.acls.cache.RemoveIdentity(tokenSecretCacheID(token.SecretID))
if reply != nil {
*reply = token.AccessorID
}
return nil
}
func (a *ACL) TokenList(args *structs.ACLTokenListRequest, reply *structs.ACLTokenListResponse) error {
if err := a.aclPreCheck(); err != nil {
return err
}
if err := a.srv.validateEnterpriseRequest(&args.EnterpriseMeta, false); err != nil {
return err
}
if !a.srv.LocalTokensEnabled() {
if args.Datacenter != a.srv.config.ACLDatacenter {
args.Datacenter = a.srv.config.ACLDatacenter
args.IncludeLocal = false
args.IncludeGlobal = true
}
args.Datacenter = a.srv.config.ACLDatacenter
}
if done, err := a.srv.ForwardRPC("ACL.TokenList", args, reply); done {
return err
}
var authzContext acl.AuthorizerContext
var requestMeta structs.EnterpriseMeta
authz, err := a.srv.ResolveTokenAndDefaultMeta(args.Token, &requestMeta, &authzContext)
if err != nil {
return err
}
// merge the token default meta into the requests meta
args.EnterpriseMeta.Merge(&requestMeta)
args.EnterpriseMeta.FillAuthzContext(&authzContext)
if authz == nil || authz.ACLRead(&authzContext) != acl.Allow {
return acl.ErrPermissionDenied
}
var methodMeta *structs.EnterpriseMeta
if args.AuthMethod != "" {
methodMeta = args.ACLAuthMethodEnterpriseMeta.ToEnterpriseMeta()
// attempt to merge in the overall meta, wildcards will not be merged
methodMeta.MergeNoWildcard(&args.EnterpriseMeta)
// in the event that the meta above didn't merge due to being a wildcard
// we ensure that proper token based meta inference occurs
methodMeta.Merge(&requestMeta)
}
return a.srv.blockingQuery(&args.QueryOptions, &reply.QueryMeta,
func(ws memdb.WatchSet, state *state.Store) error {
index, tokens, err := state.ACLTokenList(ws, args.IncludeLocal, args.IncludeGlobal, args.Policy, args.Role, args.AuthMethod, methodMeta, &args.EnterpriseMeta)
if err != nil {
return err
}
now := time.Now()
stubs := make([]*structs.ACLTokenListStub, 0, len(tokens))
for _, token := range tokens {
if token.IsExpired(now) {
continue
}
stubs = append(stubs, token.Stub())
}
// filter down to just the tokens that the requester has permissions to read
if err := a.srv.filterACLWithAuthorizer(authz, &stubs); err != nil {
return err
}
reply.Index, reply.Tokens = index, stubs
return nil
})
}
func (a *ACL) TokenBatchRead(args *structs.ACLTokenBatchGetRequest, reply *structs.ACLTokenBatchResponse) error {
if err := a.aclPreCheck(); err != nil {
return err
}
if !a.srv.LocalTokensEnabled() {
args.Datacenter = a.srv.config.ACLDatacenter
}
if done, err := a.srv.ForwardRPC("ACL.TokenBatchRead", args, reply); done {
return err
}
authz, err := a.srv.ResolveToken(args.Token)
if err != nil {
return err
} else if authz == nil {
return acl.ErrPermissionDenied
}
return a.srv.blockingQuery(&args.QueryOptions, &reply.QueryMeta,
func(ws memdb.WatchSet, state *state.Store) error {
index, tokens, err := state.ACLTokenBatchGet(ws, args.AccessorIDs)
if err != nil {
return err
}
// This RPC is used for replication, so don't filter out expired tokens here.
// Filter the tokens down to just what we have permission to see - also redact
// secrets based on allowed permissions. We could just call filterACLWithAuthorizer
// on the whole token list but then it would require another pass through the token
// list to determine if any secrets were redacted. Its a small amount of code to