-
Notifications
You must be signed in to change notification settings - Fork 2k
/
acl.go
1636 lines (1375 loc) · 47.4 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
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package structs
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"regexp"
"strconv"
"time"
"github.com/hashicorp/go-bexpr"
"github.com/hashicorp/go-multierror"
"github.com/hashicorp/go-set"
lru "github.com/hashicorp/golang-lru/v2"
"github.com/hashicorp/nomad/helper"
"github.com/hashicorp/nomad/helper/pointer"
"github.com/hashicorp/nomad/helper/uuid"
"github.com/hashicorp/nomad/lib/lang"
"golang.org/x/crypto/blake2b"
"golang.org/x/exp/slices"
"oss.indeed.com/go/libtime"
)
const (
// ACLUpsertPoliciesRPCMethod is the RPC method for batch creating or
// modifying ACL policies.
//
// Args: ACLPolicyUpsertRequest
// Reply: GenericResponse
ACLUpsertPoliciesRPCMethod = "ACL.UpsertPolicies"
// ACLUpsertTokensRPCMethod is the RPC method for batch creating or
// modifying ACL tokens.
//
// Args: ACLTokenUpsertRequest
// Reply: ACLTokenUpsertResponse
ACLUpsertTokensRPCMethod = "ACL.UpsertTokens"
// ACLDeleteTokensRPCMethod is the RPC method for batch deleting ACL
// tokens.
//
// Args: ACLTokenDeleteRequest
// Reply: GenericResponse
ACLDeleteTokensRPCMethod = "ACL.DeleteTokens"
// ACLUpsertRolesRPCMethod is the RPC method for batch creating or
// modifying ACL roles.
//
// Args: ACLRolesUpsertRequest
// Reply: ACLRolesUpsertResponse
ACLUpsertRolesRPCMethod = "ACL.UpsertRoles"
// ACLDeleteRolesByIDRPCMethod the RPC method for batch deleting ACL
// roles by their ID.
//
// Args: ACLRolesDeleteByIDRequest
// Reply: ACLRolesDeleteByIDResponse
ACLDeleteRolesByIDRPCMethod = "ACL.DeleteRolesByID"
// ACLListRolesRPCMethod is the RPC method for listing ACL roles.
//
// Args: ACLRolesListRequest
// Reply: ACLRolesListResponse
ACLListRolesRPCMethod = "ACL.ListRoles"
// ACLGetRolesByIDRPCMethod is the RPC method for detailing a number of ACL
// roles using their ID. This is an internal only RPC endpoint and used by
// the ACL Role replication process.
//
// Args: ACLRolesByIDRequest
// Reply: ACLRolesByIDResponse
ACLGetRolesByIDRPCMethod = "ACL.GetRolesByID"
// ACLGetRoleByIDRPCMethod is the RPC method for detailing an individual
// ACL role using its ID.
//
// Args: ACLRoleByIDRequest
// Reply: ACLRoleByIDResponse
ACLGetRoleByIDRPCMethod = "ACL.GetRoleByID"
// ACLGetRoleByNameRPCMethod is the RPC method for detailing an individual
// ACL role using its name.
//
// Args: ACLRoleByNameRequest
// Reply: ACLRoleByNameResponse
ACLGetRoleByNameRPCMethod = "ACL.GetRoleByName"
// ACLUpsertAuthMethodsRPCMethod is the RPC method for batch creating or
// modifying auth methods.
//
// Args: ACLAuthMethodsUpsertRequest
// Reply: ACLAuthMethodUpsertResponse
ACLUpsertAuthMethodsRPCMethod = "ACL.UpsertAuthMethods"
// ACLDeleteAuthMethodsRPCMethod is the RPC method for batch deleting auth
// methods.
//
// Args: ACLAuthMethodDeleteRequest
// Reply: ACLAuthMethodDeleteResponse
ACLDeleteAuthMethodsRPCMethod = "ACL.DeleteAuthMethods"
// ACLListAuthMethodsRPCMethod is the RPC method for listing auth methods.
//
// Args: ACLAuthMethodListRequest
// Reply: ACLAuthMethodListResponse
ACLListAuthMethodsRPCMethod = "ACL.ListAuthMethods"
// ACLGetAuthMethodRPCMethod is the RPC method for detailing an individual
// auth method using its name.
//
// Args: ACLAuthMethodGetRequest
// Reply: ACLAuthMethodGetResponse
ACLGetAuthMethodRPCMethod = "ACL.GetAuthMethod"
// ACLGetAuthMethodsRPCMethod is the RPC method for getting multiple auth
// methods using their names.
//
// Args: ACLAuthMethodsGetRequest
// Reply: ACLAuthMethodsGetResponse
ACLGetAuthMethodsRPCMethod = "ACL.GetAuthMethods"
// ACLUpsertBindingRulesRPCMethod is the RPC method for batch creating or
// modifying binding rules.
//
// Args: ACLBindingRulesUpsertRequest
// Reply: ACLBindingRulesUpsertResponse
ACLUpsertBindingRulesRPCMethod = "ACL.UpsertBindingRules"
// ACLDeleteBindingRulesRPCMethod is the RPC method for batch deleting
// binding rules.
//
// Args: ACLBindingRulesDeleteRequest
// Reply: ACLBindingRulesDeleteResponse
ACLDeleteBindingRulesRPCMethod = "ACL.DeleteBindingRules"
// ACLListBindingRulesRPCMethod is the RPC method listing binding rules.
//
// Args: ACLBindingRulesListRequest
// Reply: ACLBindingRulesListResponse
ACLListBindingRulesRPCMethod = "ACL.ListBindingRules"
// ACLGetBindingRulesRPCMethod is the RPC method for getting multiple
// binding rules using their IDs.
//
// Args: ACLBindingRulesRequest
// Reply: ACLBindingRulesResponse
ACLGetBindingRulesRPCMethod = "ACL.GetBindingRules"
// ACLGetBindingRuleRPCMethod is the RPC method for detailing an individual
// binding rule using its ID.
//
// Args: ACLBindingRuleRequest
// Reply: ACLBindingRuleResponse
ACLGetBindingRuleRPCMethod = "ACL.GetBindingRule"
// ACLOIDCAuthURLRPCMethod is the RPC method for starting the OIDC login
// workflow. It generates the OIDC provider URL which will be used for user
// authentication.
//
// Args: ACLOIDCAuthURLRequest
// Reply: ACLOIDCAuthURLResponse
ACLOIDCAuthURLRPCMethod = "ACL.OIDCAuthURL"
// ACLOIDCCompleteAuthRPCMethod is the RPC method for completing the OIDC
// login workflow. It exchanges the OIDC provider token for a Nomad ACL
// token with roles as defined within the remote provider.
//
// Args: ACLOIDCCompleteAuthRequest
// Reply: ACLOIDCCompleteAuthResponse
ACLOIDCCompleteAuthRPCMethod = "ACL.OIDCCompleteAuth"
// ACLLoginRPCMethod is the RPC method for performing a non-OIDC login
// workflow. It exchanges the provided token for a Nomad ACL token with
// roles as defined within the remote provider.
//
// Args: ACLLoginRequest
// Reply: ACLLoginResponse
ACLLoginRPCMethod = "ACL.Login"
)
const (
// ACLMaxExpiredBatchSize is the maximum number of expired ACL tokens that
// will be garbage collected in a single trigger. This number helps limit
// the replication pressure due to expired token deletion. If there are a
// large number of expired tokens pending garbage collection, this value is
// a potential limiting factor.
ACLMaxExpiredBatchSize = 4096
// maxACLRoleDescriptionLength limits an ACL roles description length.
maxACLRoleDescriptionLength = 256
// maxACLBindingRuleDescriptionLength limits an ACL binding rules
// description length and should be used to validate the object.
maxACLBindingRuleDescriptionLength = 256
// ACLAuthMethodTokenLocalityLocal is the ACLAuthMethod.TokenLocality that
// will generate ACL tokens which can only be used on the local cluster the
// request was made.
ACLAuthMethodTokenLocalityLocal = "local"
// ACLAuthMethodTokenLocalityGlobal is the ACLAuthMethod.TokenLocality that
// will generate ACL tokens which can be used on all federated clusters.
ACLAuthMethodTokenLocalityGlobal = "global"
// ACLAuthMethodTypeOIDC the ACLAuthMethod.Type and represents an
// auth-method which uses the OIDC protocol.
ACLAuthMethodTypeOIDC = "OIDC"
// ACLAuthMethodTypeJWT the ACLAuthMethod.Type and represents an auth-method
// which uses the JWT type.
ACLAuthMethodTypeJWT = "JWT"
)
var (
// ValidACLRoleName is used to validate an ACL role name.
ValidACLRoleName = regexp.MustCompile("^[a-zA-Z0-9-]{1,128}$")
// ValidACLAuthMethod is used to validate an ACL auth method name.
ValidACLAuthMethod = regexp.MustCompile("^[a-zA-Z0-9-]{1,128}$")
// ValitACLAuthMethodTypes lists supported auth method types.
ValidACLAuthMethodTypes = []string{ACLAuthMethodTypeOIDC, ACLAuthMethodTypeJWT}
)
type ACLCacheEntry[T any] lang.Pair[T, time.Time]
func (e ACLCacheEntry[T]) Age() time.Duration {
return time.Since(e.Second)
}
func (e ACLCacheEntry[T]) Get() T {
return e.First
}
// An ACLCache caches ACL tokens by their policy content.
type ACLCache[T any] struct {
*lru.TwoQueueCache[string, ACLCacheEntry[T]]
clock libtime.Clock
}
func (c *ACLCache[T]) Add(key string, item T) {
c.AddAtTime(key, item, c.clock.Now())
}
func (c *ACLCache[T]) AddAtTime(key string, item T, now time.Time) {
c.TwoQueueCache.Add(key, ACLCacheEntry[T]{
First: item,
Second: now,
})
}
func NewACLCache[T any](size int) *ACLCache[T] {
c, err := lru.New2Q[string, ACLCacheEntry[T]](size)
if err != nil {
panic(err) // not possible
}
return &ACLCache[T]{
TwoQueueCache: c,
clock: libtime.SystemClock(),
}
}
// ACLTokenRoleLink is used to link an ACL token to an ACL role. The ACL token
// can therefore inherit all the ACL policy permissions that the ACL role
// contains.
type ACLTokenRoleLink struct {
// ID is the ACLRole.ID UUID. This field is immutable and represents the
// absolute truth for the link.
ID string
// Name is the human friendly identifier for the ACL role and is a
// convenience field for operators. This field is always resolved to the
// ID and discarded before the token is stored in state. This is because
// operators can change the name of an ACL role.
Name string
}
// Canonicalize performs basic canonicalization on the ACL token object. It is
// important for callers to understand certain fields such as AccessorID are
// set if it is empty, so copies should be taken if needed before calling this
// function.
func (a *ACLToken) Canonicalize() {
// If the accessor ID is empty, it means this is creation of a new token,
// therefore we need to generate base information.
if a.AccessorID == "" {
a.AccessorID = uuid.Generate()
a.SecretID = uuid.Generate()
a.CreateTime = time.Now().UTC()
// If the user has not set the expiration time, but has provided a TTL, we
// calculate and populate the former filed.
if a.ExpirationTime == nil && a.ExpirationTTL != 0 {
a.ExpirationTime = pointer.Of(a.CreateTime.Add(a.ExpirationTTL))
}
}
}
// Validate is used to check a token for reasonableness
func (a *ACLToken) Validate(minTTL, maxTTL time.Duration, existing *ACLToken) error {
var mErr multierror.Error
// The human friendly name of an ACL token cannot exceed 256 characters.
if len(a.Name) > maxTokenNameLength {
mErr.Errors = append(mErr.Errors, errors.New("token name too long"))
}
// The type of an ACL token must be set. An ACL token of type client must
// have associated policies or roles, whereas a management token cannot be
// associated with policies.
switch a.Type {
case ACLClientToken:
if len(a.Policies) == 0 && len(a.Roles) == 0 {
mErr.Errors = append(mErr.Errors, errors.New("client token missing policies or roles"))
}
case ACLManagementToken:
if len(a.Policies) != 0 || len(a.Roles) != 0 {
mErr.Errors = append(mErr.Errors, errors.New("management token cannot be associated with policies or roles"))
}
default:
mErr.Errors = append(mErr.Errors, errors.New("token type must be client or management"))
}
// There are different validation rules depending on whether the ACL token
// is being created or updated.
switch existing {
case nil:
if a.ExpirationTTL < 0 {
mErr.Errors = append(mErr.Errors,
fmt.Errorf("token expiration TTL '%s' should not be negative", a.ExpirationTTL))
}
if a.ExpirationTime != nil && !a.ExpirationTime.IsZero() {
if a.CreateTime.After(*a.ExpirationTime) {
mErr.Errors = append(mErr.Errors, errors.New("expiration time cannot be before create time"))
}
// Create a time duration which details the time-til-expiry, so we can
// check this against the regions max and min values.
expiresIn := a.ExpirationTime.Sub(a.CreateTime)
if expiresIn > maxTTL {
mErr.Errors = append(mErr.Errors,
fmt.Errorf("expiration time cannot be more than %s in the future (was %s)",
maxTTL, expiresIn))
} else if expiresIn < minTTL {
mErr.Errors = append(mErr.Errors,
fmt.Errorf("expiration time cannot be less than %s in the future (was %s)",
minTTL, expiresIn))
}
}
default:
if existing.Global != a.Global {
mErr.Errors = append(mErr.Errors, errors.New("cannot toggle global mode"))
}
if existing.ExpirationTTL != a.ExpirationTTL {
mErr.Errors = append(mErr.Errors, errors.New("cannot update expiration TTL"))
}
if existing.ExpirationTime != a.ExpirationTime {
mErr.Errors = append(mErr.Errors, errors.New("cannot update expiration time"))
}
}
return mErr.ErrorOrNil()
}
// HasExpirationTime checks whether the ACL token has an expiration time value
// set.
func (a *ACLToken) HasExpirationTime() bool {
if a == nil || a.ExpirationTime == nil {
return false
}
return !a.ExpirationTime.IsZero()
}
// IsExpired compares the ACLToken.ExpirationTime against the passed t to
// identify whether the token is considered expired. The function can be called
// without checking whether the ACL token has an expiry time.
func (a *ACLToken) IsExpired(t time.Time) bool {
// Check the token has an expiration time before potentially modifying the
// supplied time. This allows us to avoid extra work, if it isn't needed.
if !a.HasExpirationTime() {
return false
}
// Check and ensure the time location is set to UTC. This is vital for
// consistency with multi-region global tokens.
if t.Location() != time.UTC {
t = t.UTC()
}
return a.ExpirationTime.Before(t) || t.IsZero()
}
// HasRoles checks if a given set of role IDs are assigned to the ACL token. It
// does not account for management tokens, therefore it is the responsibility
// of the caller to perform this check, if required.
func (a *ACLToken) HasRoles(roleIDs []string) bool {
// Generate a set of role IDs that the token is assigned.
roleSet := set.FromFunc(a.Roles, func(roleLink *ACLTokenRoleLink) string { return roleLink.ID })
// Iterate the role IDs within the request and check whether these are
// present within the token assignment.
for _, roleID := range roleIDs {
if !roleSet.Contains(roleID) {
return false
}
}
return true
}
// MarshalJSON implements the json.Marshaler interface and allows
// ACLToken.ExpirationTTL to be marshaled correctly.
func (a *ACLToken) MarshalJSON() ([]byte, error) {
type Alias ACLToken
exported := &struct {
ExpirationTTL string
*Alias
}{
ExpirationTTL: a.ExpirationTTL.String(),
Alias: (*Alias)(a),
}
if a.ExpirationTTL == 0 {
exported.ExpirationTTL = ""
}
return json.Marshal(exported)
}
// UnmarshalJSON implements the json.Unmarshaler interface and allows
// ACLToken.ExpirationTTL to be unmarshalled correctly.
func (a *ACLToken) UnmarshalJSON(data []byte) (err error) {
type Alias ACLToken
aux := &struct {
ExpirationTTL interface{}
Hash string
*Alias
}{
Alias: (*Alias)(a),
}
if err = json.Unmarshal(data, &aux); err != nil {
return err
}
if aux.ExpirationTTL != nil {
switch v := aux.ExpirationTTL.(type) {
case string:
if v != "" {
if a.ExpirationTTL, err = time.ParseDuration(v); err != nil {
return err
}
}
case float64:
a.ExpirationTTL = time.Duration(v)
}
}
if aux.Hash != "" {
a.Hash = []byte(aux.Hash)
}
return nil
}
// ACLRole is an abstraction for the ACL system which allows the grouping of
// ACL policies into a single object. ACL tokens can be created and linked to
// a role; the token then inherits all the permissions granted by the policies.
type ACLRole struct {
// ID is an internally generated UUID for this role and is controlled by
// Nomad.
ID string
// Name is unique across the entire set of federated clusters and is
// supplied by the operator on role creation. The name can be modified by
// updating the role and including the Nomad generated ID. This update will
// not affect tokens created and linked to this role. This is a required
// field.
Name string
// Description is a human-readable, operator set description that can
// provide additional context about the role. This is an operational field.
Description string
// Policies is an array of ACL policy links. Although currently policies
// can only be linked using their name, in the future we will want to add
// IDs also and thus allow operators to specify either a name, an ID, or
// both.
Policies []*ACLRolePolicyLink
// Hash is the hashed value of the role and is generated using all fields
// above this point.
Hash []byte
CreateIndex uint64
ModifyIndex uint64
}
// ACLRolePolicyLink is used to link a policy to an ACL role. We use a struct
// rather than a list of strings as in the future we will want to add IDs to
// policies and then link via these.
type ACLRolePolicyLink struct {
// Name is the ACLPolicy.Name value which will be linked to the ACL role.
Name string
}
// SetHash is used to compute and set the hash of the ACL role. This should be
// called every and each time a user specified field on the role is changed
// before updating the Nomad state store.
func (a *ACLRole) SetHash() []byte {
// Initialize a 256bit Blake2 hash (32 bytes).
hash, err := blake2b.New256(nil)
if err != nil {
panic(err)
}
// Write all the user set fields.
_, _ = hash.Write([]byte(a.Name))
_, _ = hash.Write([]byte(a.Description))
for _, policyLink := range a.Policies {
_, _ = hash.Write([]byte(policyLink.Name))
}
// Finalize the hash.
hashVal := hash.Sum(nil)
// Set and return the hash.
a.Hash = hashVal
return hashVal
}
// Validate ensure the ACL role contains valid information which meets Nomad's
// internal requirements. This does not include any state calls, such as
// ensuring the linked policies exist.
func (a *ACLRole) Validate() error {
var mErr multierror.Error
if !ValidACLRoleName.MatchString(a.Name) {
mErr.Errors = append(mErr.Errors, fmt.Errorf("invalid name '%s'", a.Name))
}
if len(a.Description) > maxACLRoleDescriptionLength {
mErr.Errors = append(mErr.Errors, fmt.Errorf("description longer than %d", maxACLRoleDescriptionLength))
}
if len(a.Policies) < 1 {
mErr.Errors = append(mErr.Errors, errors.New("at least one policy should be specified"))
}
return mErr.ErrorOrNil()
}
// Canonicalize performs basic canonicalization on the ACL role object. It is
// important for callers to understand certain fields such as ID are set if it
// is empty, so copies should be taken if needed before calling this function.
func (a *ACLRole) Canonicalize() {
if a.ID == "" {
a.ID = uuid.Generate()
}
}
// Equal performs an equality check on the two service registrations. It
// handles nil objects.
func (a *ACLRole) Equal(o *ACLRole) bool {
if a == nil || o == nil {
return a == o
}
if len(a.Hash) == 0 {
a.SetHash()
}
if len(o.Hash) == 0 {
o.SetHash()
}
return bytes.Equal(a.Hash, o.Hash)
}
// Copy creates a deep copy of the ACL role. This copy can then be safely
// modified. It handles nil objects.
func (a *ACLRole) Copy() *ACLRole {
if a == nil {
return nil
}
c := new(ACLRole)
*c = *a
c.Policies = slices.Clone(a.Policies)
c.Hash = slices.Clone(a.Hash)
return c
}
// Stub converts the ACLRole object into a ACLRoleListStub object.
func (a *ACLRole) Stub() *ACLRoleListStub {
return &ACLRoleListStub{
ID: a.ID,
Name: a.Name,
Description: a.Description,
Policies: a.Policies,
Hash: a.Hash,
CreateIndex: a.CreateIndex,
ModifyIndex: a.ModifyIndex,
}
}
// ACLRoleListStub is the stub object returned when performing a listing of ACL
// roles. While it might not currently be different to the full response
// object, it allows us to future-proof the RPC in the event the ACLRole object
// grows over time.
type ACLRoleListStub struct {
// ID is an internally generated UUID for this role and is controlled by
// Nomad.
ID string
// Name is unique across the entire set of federated clusters and is
// supplied by the operator on role creation. The name can be modified by
// updating the role and including the Nomad generated ID. This update will
// not affect tokens created and linked to this role. This is a required
// field.
Name string
// Description is a human-readable, operator set description that can
// provide additional context about the role. This is an operational field.
Description string
// Policies is an array of ACL policy links. Although currently policies
// can only be linked using their name, in the future we will want to add
// IDs also and thus allow operators to specify either a name, an ID, or
// both.
Policies []*ACLRolePolicyLink
// Hash is the hashed value of the role and is generated using all fields
// above this point.
Hash []byte
CreateIndex uint64
ModifyIndex uint64
}
// ACLRolesUpsertRequest is the request object used to upsert one or more ACL
// roles.
type ACLRolesUpsertRequest struct {
ACLRoles []*ACLRole
// AllowMissingPolicies skips the ACL Role policy link verification and is
// used by the replication process. The replication cannot ensure policies
// are present before ACL Roles are replicated.
AllowMissingPolicies bool
WriteRequest
}
// ACLRolesUpsertResponse is the response object when one or more ACL roles
// have been successfully upserted into state.
type ACLRolesUpsertResponse struct {
ACLRoles []*ACLRole
WriteMeta
}
// ACLRolesDeleteByIDRequest is the request object to delete one or more ACL
// roles using the role ID.
type ACLRolesDeleteByIDRequest struct {
ACLRoleIDs []string
WriteRequest
}
// ACLRolesDeleteByIDResponse is the response object when performing a deletion
// of one or more ACL roles using the role ID.
type ACLRolesDeleteByIDResponse struct {
WriteMeta
}
// ACLRolesListRequest is the request object when performing ACL role listings.
type ACLRolesListRequest struct {
QueryOptions
}
// ACLRolesListResponse is the response object when performing ACL role
// listings.
type ACLRolesListResponse struct {
ACLRoles []*ACLRoleListStub
QueryMeta
}
// ACLRolesByIDRequest is the request object when performing a lookup of
// multiple roles by the ID.
type ACLRolesByIDRequest struct {
ACLRoleIDs []string
QueryOptions
}
// ACLRolesByIDResponse is the response object when performing a lookup of
// multiple roles by their IDs.
type ACLRolesByIDResponse struct {
ACLRoles map[string]*ACLRole
QueryMeta
}
// ACLRoleByIDRequest is the request object to perform a lookup of an ACL
// role using a specific ID.
type ACLRoleByIDRequest struct {
RoleID string
QueryOptions
}
// ACLRoleByIDResponse is the response object when performing a lookup of an
// ACL role matching a specific ID.
type ACLRoleByIDResponse struct {
ACLRole *ACLRole
QueryMeta
}
// ACLRoleByNameRequest is the request object to perform a lookup of an ACL
// role using a specific name.
type ACLRoleByNameRequest struct {
RoleName string
QueryOptions
}
// ACLRoleByNameResponse is the response object when performing a lookup of an
// ACL role matching a specific name.
type ACLRoleByNameResponse struct {
ACLRole *ACLRole
QueryMeta
}
// ACLAuthMethod is used to capture the properties of an authentication method
// used for single sing-on
type ACLAuthMethod struct {
Name string
Type string
TokenLocality string // is the token valid locally or globally?
MaxTokenTTL time.Duration
Default bool
Config *ACLAuthMethodConfig
Hash []byte
CreateTime time.Time
ModifyTime time.Time
CreateIndex uint64
ModifyIndex uint64
}
// SetHash is used to compute and set the hash of the ACL auth method. This
// should be called every and each time a user specified field on the method is
// changed before updating the Nomad state store.
func (a *ACLAuthMethod) SetHash() []byte {
// Initialize a 256bit Blake2 hash (32 bytes).
hash, err := blake2b.New256(nil)
if err != nil {
panic(err)
}
_, _ = hash.Write([]byte(a.Name))
_, _ = hash.Write([]byte(a.Type))
_, _ = hash.Write([]byte(a.TokenLocality))
_, _ = hash.Write([]byte(a.MaxTokenTTL.String()))
_, _ = hash.Write([]byte(strconv.FormatBool(a.Default)))
if a.Config != nil {
_, _ = hash.Write([]byte(a.Config.OIDCDiscoveryURL))
_, _ = hash.Write([]byte(a.Config.OIDCClientID))
_, _ = hash.Write([]byte(a.Config.OIDCClientSecret))
for _, ba := range a.Config.BoundAudiences {
_, _ = hash.Write([]byte(ba))
}
for _, uri := range a.Config.AllowedRedirectURIs {
_, _ = hash.Write([]byte(uri))
}
for _, pem := range a.Config.DiscoveryCaPem {
_, _ = hash.Write([]byte(pem))
}
for _, sa := range a.Config.SigningAlgs {
_, _ = hash.Write([]byte(sa))
}
for k, v := range a.Config.ClaimMappings {
_, _ = hash.Write([]byte(k))
_, _ = hash.Write([]byte(v))
}
for k, v := range a.Config.ListClaimMappings {
_, _ = hash.Write([]byte(k))
_, _ = hash.Write([]byte(v))
}
}
// Finalize the hash.
hashVal := hash.Sum(nil)
// Set and return the hash.
a.Hash = hashVal
return hashVal
}
// MarshalJSON implements the json.Marshaler interface and allows
// ACLAuthMethod.MaxTokenTTL to be marshaled correctly.
func (a *ACLAuthMethod) MarshalJSON() ([]byte, error) {
type Alias ACLAuthMethod
exported := &struct {
MaxTokenTTL string
*Alias
}{
MaxTokenTTL: a.MaxTokenTTL.String(),
Alias: (*Alias)(a),
}
if a.MaxTokenTTL == 0 {
exported.MaxTokenTTL = ""
}
return json.Marshal(exported)
}
// UnmarshalJSON implements the json.Unmarshaler interface and allows
// ACLAuthMethod.MaxTokenTTL to be unmarshalled correctly.
func (a *ACLAuthMethod) UnmarshalJSON(data []byte) (err error) {
type Alias ACLAuthMethod
aux := &struct {
MaxTokenTTL interface{}
*Alias
}{
Alias: (*Alias)(a),
}
if err = json.Unmarshal(data, &aux); err != nil {
return err
}
if aux.MaxTokenTTL != nil {
switch v := aux.MaxTokenTTL.(type) {
case string:
if a.MaxTokenTTL, err = time.ParseDuration(v); err != nil {
return err
}
case float64:
a.MaxTokenTTL = time.Duration(v)
}
}
return nil
}
func (a *ACLAuthMethod) Stub() *ACLAuthMethodStub {
return &ACLAuthMethodStub{
Name: a.Name,
Type: a.Type,
Default: a.Default,
Hash: a.Hash,
CreateIndex: a.CreateIndex,
ModifyIndex: a.ModifyIndex,
}
}
func (a *ACLAuthMethod) Equal(other *ACLAuthMethod) bool {
if a == nil || other == nil {
return a == other
}
if len(a.Hash) == 0 {
a.SetHash()
}
if len(other.Hash) == 0 {
other.SetHash()
}
return bytes.Equal(a.Hash, other.Hash)
}
// Copy creates a deep copy of the ACL auth method. This copy can then be safely
// modified. It handles nil objects.
func (a *ACLAuthMethod) Copy() *ACLAuthMethod {
if a == nil {
return nil
}
c := new(ACLAuthMethod)
*c = *a
c.Hash = slices.Clone(a.Hash)
c.Config = a.Config.Copy()
return c
}
// Canonicalize performs basic canonicalization on the ACL auth method object.
func (a *ACLAuthMethod) Canonicalize() {
t := time.Now().UTC()
if a.CreateTime.IsZero() {
a.CreateTime = t
}
a.ModifyTime = t
}
// Merge merges auth method a with method b. It sets all required empty fields
// of method a to corresponding values of method b, except for "default" and
// "name."
func (a *ACLAuthMethod) Merge(b *ACLAuthMethod) {
if b != nil {
a.Type = helper.Merge(a.Type, b.Type)
a.TokenLocality = helper.Merge(a.TokenLocality, b.TokenLocality)
a.MaxTokenTTL = helper.Merge(a.MaxTokenTTL, b.MaxTokenTTL)
a.Config = helper.Merge(a.Config, b.Config)
}
}
// Validate returns an error is the ACLAuthMethod is invalid.
//
// TODO revisit possible other validity conditions in the future
func (a *ACLAuthMethod) Validate(minTTL, maxTTL time.Duration) error {
var mErr multierror.Error
if !ValidACLAuthMethod.MatchString(a.Name) {
mErr.Errors = append(mErr.Errors, fmt.Errorf("invalid name '%s'", a.Name))
}
if !slices.Contains([]string{"local", "global"}, a.TokenLocality) {
mErr.Errors = append(
mErr.Errors, fmt.Errorf("invalid token locality '%s'", a.TokenLocality))
}
if !slices.Contains(ValidACLAuthMethodTypes, a.Type) {
mErr.Errors = append(
mErr.Errors, fmt.Errorf("invalid token type '%s'", a.Type))
}
if minTTL > a.MaxTokenTTL || a.MaxTokenTTL > maxTTL {
mErr.Errors = append(mErr.Errors, fmt.Errorf(
"invalid MaxTokenTTL value '%s' (should be between %s and %s)",
a.MaxTokenTTL.String(), minTTL.String(), maxTTL.String()))
}
return mErr.ErrorOrNil()
}
// TokenLocalityIsGlobal returns whether the auth method creates global ACL
// tokens or not.
func (a *ACLAuthMethod) TokenLocalityIsGlobal() bool { return a.TokenLocality == "global" }
// ACLAuthMethodConfig is used to store configuration of an auth method
type ACLAuthMethodConfig struct {
// A list of PEM-encoded public keys to use to authenticate signatures
// locally
JWTValidationPubKeys []string
// JSON Web Key Sets url for authenticating signatures
JWKSURL string
// The OIDC Discovery URL, without any .well-known component (base path)
OIDCDiscoveryURL string
// The OAuth Client ID configured with the OIDC provider
OIDCClientID string
// The OAuth Client Secret configured with the OIDC provider
OIDCClientSecret string
// List of OIDC scopes
OIDCScopes []string
// List of auth claims that are valid for login
BoundAudiences []string
// The value against which to match the iss claim in a JWT
BoundIssuer []string
// A list of allowed values for redirect_uri
AllowedRedirectURIs []string
// PEM encoded CA certs for use by the TLS client used to talk with the
// OIDC Discovery URL.
DiscoveryCaPem []string
// PEM encoded CA cert for use by the TLS client used to talk with the JWKS
// URL
JWKSCACert string
// A list of supported signing algorithms
SigningAlgs []string
// Duration in seconds of leeway when validating expiration of a token to
// account for clock skew
ExpirationLeeway time.Duration
// Duration in seconds of leeway when validating not before values of a
// token to account for clock skew.
NotBeforeLeeway time.Duration
// Duration in seconds of leeway when validating all claims to account for
// clock skew.
ClockSkewLeeway time.Duration
// Mappings of claims (key) that will be copied to a metadata field