forked from hashicorp/consul
-
Notifications
You must be signed in to change notification settings - Fork 0
/
config_entry_intentions.go
1010 lines (845 loc) · 26.9 KB
/
config_entry_intentions.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 (
"fmt"
"sort"
"strings"
"time"
"github.com/hernad/consul/lib/stringslice"
"github.com/hashicorp/go-multierror"
"github.com/hernad/consul/acl"
)
type ServiceIntentionsConfigEntry struct {
Kind string
Name string // formerly DestinationName
Sources []*SourceIntention
JWT *IntentionJWTRequirement `json:",omitempty"`
Meta map[string]string `json:",omitempty"` // formerly Intention.Meta
acl.EnterpriseMeta `hcl:",squash" mapstructure:",squash"` // formerly DestinationNS
RaftIndex
}
var _ UpdatableConfigEntry = (*ServiceIntentionsConfigEntry)(nil)
func (e *ServiceIntentionsConfigEntry) GetKind() string {
return ServiceIntentions
}
func (e *ServiceIntentionsConfigEntry) GetName() string {
if e == nil {
return ""
}
return e.Name
}
func (e *ServiceIntentionsConfigEntry) GetMeta() map[string]string {
if e == nil {
return nil
}
return e.Meta
}
func (e *ServiceIntentionsConfigEntry) Clone() *ServiceIntentionsConfigEntry {
e2 := *e
e2.Meta = cloneStringStringMap(e.Meta)
e2.Sources = make([]*SourceIntention, len(e.Sources))
for i, src := range e.Sources {
e2.Sources[i] = src.Clone()
}
if e.JWT != nil {
e2.JWT = e.JWT.Clone()
}
return &e2
}
func (e *ServiceIntentionsConfigEntry) DestinationServiceName() ServiceName {
return NewServiceName(e.Name, &e.EnterpriseMeta)
}
func (e *ServiceIntentionsConfigEntry) UpdateSourceByLegacyID(legacyID string, update *SourceIntention) bool {
for i, src := range e.Sources {
if src.LegacyID == legacyID {
e.Sources[i] = update
return true
}
}
return false
}
func (e *ServiceIntentionsConfigEntry) UpsertSourceByName(sn ServiceName, upsert *SourceIntention) {
for i, src := range e.Sources {
if src.SourceServiceName() == sn {
e.Sources[i] = upsert
return
}
}
e.Sources = append(e.Sources, upsert)
}
func (e *ServiceIntentionsConfigEntry) DeleteSourceByLegacyID(legacyID string) bool {
for i, src := range e.Sources {
if src.LegacyID == legacyID {
// Delete slice element: https://github.com/golang/go/wiki/SliceTricks#delete
// a = append(a[:i], a[i+1:]...)
e.Sources = append(e.Sources[:i], e.Sources[i+1:]...)
if len(e.Sources) == 0 {
e.Sources = nil
}
return true
}
}
return false
}
func (e *ServiceIntentionsConfigEntry) DeleteSourceByName(sn ServiceName) bool {
for i, src := range e.Sources {
if src.SourceServiceName() == sn {
// Delete slice element: https://github.com/golang/go/wiki/SliceTricks#delete
// a = append(a[:i], a[i+1:]...)
e.Sources = append(e.Sources[:i], e.Sources[i+1:]...)
if len(e.Sources) == 0 {
e.Sources = nil
}
return true
}
}
return false
}
func (e *ServiceIntentionsConfigEntry) ToIntention(src *SourceIntention) *Intention {
meta := e.Meta
if src.LegacyID != "" {
meta = src.LegacyMeta
}
ixn := &Intention{
ID: src.LegacyID,
Description: src.Description,
SourcePeer: src.Peer,
SourceSamenessGroup: src.SamenessGroup,
SourcePartition: src.PartitionOrEmpty(),
SourceNS: src.NamespaceOrDefault(),
SourceName: src.Name,
SourceType: src.Type,
JWT: e.JWT,
Action: src.Action,
Permissions: src.Permissions,
Meta: meta,
Precedence: src.Precedence,
DestinationPartition: e.PartitionOrEmpty(),
DestinationNS: e.NamespaceOrDefault(),
DestinationName: e.Name,
RaftIndex: e.RaftIndex,
}
if src.LegacyCreateTime != nil {
ixn.CreatedAt = *src.LegacyCreateTime
}
if src.LegacyUpdateTime != nil {
ixn.UpdatedAt = *src.LegacyUpdateTime
}
if src.LegacyID != "" {
// Ensure that pre-1.9.0 secondaries can still replicate legacy
// intentions via the APIs. These require the Hash field to be
// populated.
//
//nolint:staticcheck
ixn.SetHash()
}
return ixn
}
func (e *ServiceIntentionsConfigEntry) LegacyIDFieldsAreAllEmpty() bool {
for _, src := range e.Sources {
if src.LegacyID != "" {
return false
}
}
return true
}
func (e *ServiceIntentionsConfigEntry) LegacyIDFieldsAreAllSet() bool {
for _, src := range e.Sources {
if src.LegacyID == "" {
return false
}
}
return true
}
func (e *ServiceIntentionsConfigEntry) ToIntentions() Intentions {
out := make(Intentions, 0, len(e.Sources))
for _, src := range e.Sources {
out = append(out, e.ToIntention(src))
}
return out
}
type SourceIntention struct {
// Name is the name of the source service. This can be a wildcard "*", but
// only the full value can be a wildcard. Partial wildcards are not
// allowed.
//
// The source may also be a non-Consul service, as specified by SourceType.
//
// formerly Intention.SourceName
Name string
// Action is whether this is an allowlist or denylist intention.
//
// formerly Intention.Action
//
// NOTE: this is mutually exclusive with the Permissions field.
Action IntentionAction `json:",omitempty"`
// Permissions is the list of additional L7 attributes that extend the
// intention definition.
//
// Permissions are interpreted in the order represented in the slice. In
// default-deny mode, deny permissions are logically subtracted from all
// following allow permissions. Multiple allow permissions are then ORed
// together.
//
// For example:
// ["deny /v2/admin", "allow /v2/*", "allow GET /healthz"]
//
// Is logically interpreted as:
// allow: [
// "(/v2/*) AND NOT (/v2/admin)",
// "(GET /healthz) AND NOT (/v2/admin)"
// ]
Permissions []*IntentionPermission `json:",omitempty"`
// Precedence is the order that the intention will be applied, with
// larger numbers being applied first. This is a read-only field, on
// any intention update it is updated.
//
// Note we will technically decode this over the wire during a write, but
// we always recompute it on save.
//
// formerly Intention.Precedence
Precedence int
// LegacyID is manipulated just by the bridging code
// used as part of backwards compatibility.
//
// formerly Intention.ID
LegacyID string `json:",omitempty" alias:"legacy_id"`
// Type is the type of the value for the source.
//
// formerly Intention.SourceType
Type IntentionSourceType
// Description is a human-friendly description of this intention.
// It is opaque to Consul and is only stored and transferred in API
// requests.
//
// formerly Intention.Description
Description string `json:",omitempty"`
// LegacyMeta is arbitrary metadata associated with the intention. This is
// opaque to Consul but is served in API responses.
//
// formerly Intention.Meta
LegacyMeta map[string]string `json:",omitempty" alias:"legacy_meta"`
// LegacyCreateTime is formerly Intention.CreatedAt
LegacyCreateTime *time.Time `json:",omitempty" alias:"legacy_create_time"`
// LegacyUpdateTime is formerly Intention.UpdatedAt
LegacyUpdateTime *time.Time `json:",omitempty" alias:"legacy_update_time"`
// Things like L7 rules or Sentinel rules could go here later.
// formerly Intention.SourceNS
acl.EnterpriseMeta `hcl:",squash" mapstructure:",squash"`
// Peer is the name of the remote peer of the source service, if applicable.
Peer string `json:",omitempty"`
// SamenessGroup is the name of the sameness group, if applicable.
SamenessGroup string `json:",omitempty" alias:"sameness_group"`
}
type IntentionJWTRequirement struct {
// Providers is a list of providers to consider when verifying a JWT.
Providers []*IntentionJWTProvider `json:",omitempty"`
}
func (e *IntentionJWTRequirement) Clone() *IntentionJWTRequirement {
e2 := *e
e2.Providers = make([]*IntentionJWTProvider, len(e.Providers))
for i, src := range e.Providers {
e2.Providers[i] = src.Clone()
}
return &e2
}
func (p *IntentionJWTProvider) Validate() error {
if p.Name == "" {
return fmt.Errorf("JWT provider name is required")
}
return nil
}
func (e *IntentionJWTRequirement) Validate() error {
var result error
for _, provider := range e.Providers {
if err := provider.Validate(); err != nil {
result = multierror.Append(result, err)
}
}
return result
}
type IntentionJWTProvider struct {
// Name is the name of the JWT provider. There MUST be a corresponding
// "jwt-provider" config entry with this name.
Name string `json:",omitempty"`
// VerifyClaims is a list of additional claims to verify in a JWT's payload.
VerifyClaims []*IntentionJWTClaimVerification `json:",omitempty" alias:"verify_claims"`
}
func (e *IntentionJWTProvider) Clone() *IntentionJWTProvider {
e2 := *e
e2.VerifyClaims = make([]*IntentionJWTClaimVerification, len(e.VerifyClaims))
for i, src := range e.VerifyClaims {
e2.VerifyClaims[i] = src.Clone()
}
return &e2
}
type IntentionJWTClaimVerification struct {
// Path is the path to the claim in the token JSON.
Path []string `json:",omitempty"`
// Value is the expected value at the given path:
// - If the type at the path is a list then we verify
// that this value is contained in the list.
//
// - If the type at the path is a string then we verify
// that this value matches.
Value string `json:",omitempty"`
}
func (e *IntentionJWTClaimVerification) Clone() *IntentionJWTClaimVerification {
e2 := *e
e2.Path = stringslice.CloneStringSlice(e.Path)
return &e2
}
type IntentionPermission struct {
Action IntentionAction // required: allow|deny
HTTP *IntentionHTTPPermission `json:",omitempty"`
// If we have non-http match criteria for other protocols
// in the future (gRPC, redis, etc) they can go here.
// Support for edge-decoded JWTs would likely be configured
// in a new top level section here.
// If we ever add Sentinel support, this is one place we may
// wish to add it.
JWT *IntentionJWTRequirement `json:",omitempty"`
}
func (p *IntentionPermission) Clone() *IntentionPermission {
p2 := *p
if p.HTTP != nil {
p2.HTTP = p.HTTP.Clone()
}
if p.JWT != nil {
p2.JWT = p.JWT.Clone()
}
return &p2
}
func (p *IntentionPermission) Validate() error {
var result error
if p.JWT != nil {
result = p.JWT.Validate()
}
return result
}
type IntentionHTTPPermission struct {
// PathExact, PathPrefix, and PathRegex are mutually exclusive.
PathExact string `json:",omitempty" alias:"path_exact"`
PathPrefix string `json:",omitempty" alias:"path_prefix"`
PathRegex string `json:",omitempty" alias:"path_regex"`
Header []IntentionHTTPHeaderPermission `json:",omitempty"`
Methods []string `json:",omitempty"`
}
func (p *IntentionHTTPPermission) Clone() *IntentionHTTPPermission {
p2 := *p
if len(p.Header) > 0 {
p2.Header = make([]IntentionHTTPHeaderPermission, 0, len(p.Header))
for _, hdr := range p.Header {
p2.Header = append(p2.Header, hdr)
}
}
p2.Methods = stringslice.CloneStringSlice(p.Methods)
return &p2
}
type IntentionHTTPHeaderPermission struct {
Name string
Present bool `json:",omitempty"`
Exact string `json:",omitempty"`
Prefix string `json:",omitempty"`
Suffix string `json:",omitempty"`
Regex string `json:",omitempty"`
Invert bool `json:",omitempty"`
}
func cloneStringStringMap(m map[string]string) map[string]string {
if m == nil {
return nil
}
m2 := make(map[string]string)
for k, v := range m {
m2[k] = v
}
return m2
}
func (x *SourceIntention) SourceServiceName() ServiceName {
return NewServiceName(x.Name, &x.EnterpriseMeta)
}
func (x *SourceIntention) Clone() *SourceIntention {
x2 := *x
x2.LegacyMeta = cloneStringStringMap(x.LegacyMeta)
if len(x.Permissions) > 0 {
x2.Permissions = make([]*IntentionPermission, 0, len(x.Permissions))
for _, perm := range x.Permissions {
x2.Permissions = append(x2.Permissions, perm.Clone())
}
}
return &x2
}
func (e *ServiceIntentionsConfigEntry) UpdateOver(rawPrev ConfigEntry) error {
if rawPrev == nil {
return nil
}
prev, ok := rawPrev.(*ServiceIntentionsConfigEntry)
if !ok {
return fmt.Errorf("previous config entry is not of type %T: %T", e, rawPrev)
}
var (
prevSourceByName = make(map[PeeredServiceName]*SourceIntention)
prevSourceByLegacyID = make(map[string]*SourceIntention)
)
for _, src := range prev.Sources {
prevSourceByName[PeeredServiceName{Peer: src.Peer, ServiceName: src.SourceServiceName()}] = src
if src.LegacyID != "" {
prevSourceByLegacyID[src.LegacyID] = src
}
}
for i, src := range e.Sources {
if src.LegacyID == "" {
continue
}
// Check that the LegacyID fields are handled correctly during updates.
if prevSrc, ok := prevSourceByName[PeeredServiceName{Peer: src.Peer, ServiceName: src.SourceServiceName()}]; ok {
if prevSrc.LegacyID == "" {
return fmt.Errorf("Sources[%d].LegacyID: cannot set this field", i)
} else if src.LegacyID != prevSrc.LegacyID {
return fmt.Errorf("Sources[%d].LegacyID: cannot set this field to a different value", i)
}
}
// Now ensure legacy timestamps carry over properly. We always retain the LegacyCreateTime.
if prevSrc, ok := prevSourceByLegacyID[src.LegacyID]; ok {
if prevSrc.LegacyCreateTime != nil {
// NOTE: we don't want to share the memory here
src.LegacyCreateTime = timePointer(*prevSrc.LegacyCreateTime)
}
}
}
return nil
}
func (e *ServiceIntentionsConfigEntry) Normalize() error {
return e.normalize(false)
}
func (e *ServiceIntentionsConfigEntry) LegacyNormalize() error {
return e.normalize(true)
}
func (e *ServiceIntentionsConfigEntry) normalize(legacyWrite bool) error {
if e == nil {
return fmt.Errorf("config entry is nil")
}
// NOTE: this function must be deterministic so that the raft log doesn't
// diverge. This means no ID assignments or time.Now() usage!
e.Kind = ServiceIntentions
e.EnterpriseMeta.Normalize()
for _, src := range e.Sources {
// Default source type
if src.Type == "" {
src.Type = IntentionSourceConsul
}
// Normalize the source's namespace and partition.
// If the source is not peered, it inherits the destination's
// EnterpriseMeta.
if src.Peer != "" || src.SamenessGroup != "" {
// If the source is peered or a sameness group, normalize the namespace only,
// since they are mutually exclusive with partition.
src.EnterpriseMeta.NormalizeNamespace()
} else {
src.EnterpriseMeta.MergeNoWildcard(&e.EnterpriseMeta)
src.EnterpriseMeta.Normalize()
}
// Compute the precedence only AFTER normalizing namespaces since the
// namespaces are factored into the calculation.
src.Precedence = computeIntentionPrecedence(e, src)
if legacyWrite {
// We always force meta to be non-nil so that it's an empty map. This
// makes it easy for API responses to not nil-check this everywhere.
if src.LegacyMeta == nil {
src.LegacyMeta = make(map[string]string)
}
} else {
// Legacy fields are cleared, except LegacyMeta which we leave
// populated so that we can later fail the write in Validate() and
// give the user a warning about possible data loss.
src.LegacyID = ""
src.LegacyCreateTime = nil
src.LegacyUpdateTime = nil
}
for _, perm := range src.Permissions {
if perm.HTTP == nil {
continue
}
for j := 0; j < len(perm.HTTP.Methods); j++ {
perm.HTTP.Methods[j] = strings.ToUpper(perm.HTTP.Methods[j])
}
}
}
// The source intentions closer to the head of the list have higher
// precedence. i.e. index 0 has the highest precedence.
sort.SliceStable(e.Sources, func(i, j int) bool {
return e.Sources[i].Precedence > e.Sources[j].Precedence
})
return nil
}
func timePointer(t time.Time) *time.Time {
if t.IsZero() {
return nil
}
return &t
}
// NOTE: this assumes that the namespaces have been fully normalized.
func computeIntentionPrecedence(entry *ServiceIntentionsConfigEntry, src *SourceIntention) int {
// Max maintains the maximum value that the precedence can be depending
// on the number of exact values in the destination.
var max int
switch intentionCountExact(entry.Name, &entry.EnterpriseMeta) {
case 2:
max = 9
case 1:
max = 6
case 0:
max = 3
default:
// This shouldn't be possible, just set it to zero
return 0
}
// Given the maximum, the exact value is determined based on the
// number of source exact values.
countSrc := intentionCountExact(src.Name, &src.EnterpriseMeta)
return max - (2 - countSrc)
}
// intentionCountExact counts the number of exact values (not wildcards) in
// the given namespace and name.
func intentionCountExact(name string, entMeta *acl.EnterpriseMeta) int {
ns := entMeta.NamespaceOrDefault()
// If NS is wildcard, pair must be */* since an exact service cannot follow a wildcard NS
// */* is allowed, but */foo is not
if ns == WildcardSpecifier {
return 0
}
// only the namespace must be exact, since the */* case already returned.
if name == WildcardSpecifier {
return 1
}
return 2
}
func (e *ServiceIntentionsConfigEntry) Validate() error {
return e.validate(false)
}
func (e *ServiceIntentionsConfigEntry) LegacyValidate() error {
return e.validate(true)
}
func (e *ServiceIntentionsConfigEntry) HasWildcardDestination() bool {
dstNS := e.EnterpriseMeta.NamespaceOrDefault()
return dstNS == WildcardSpecifier || e.Name == WildcardSpecifier
}
func (e *ServiceIntentionsConfigEntry) HasAnyPermissions() bool {
for _, src := range e.Sources {
if len(src.Permissions) > 0 {
return true
}
}
return false
}
func (e *ServiceIntentionsConfigEntry) validate(legacyWrite bool) error {
if e.Name == "" {
return fmt.Errorf("Name is required")
}
if err := validateIntentionWildcards(e.Name, &e.EnterpriseMeta, "", ""); err != nil {
return err
}
destIsWild := e.HasWildcardDestination()
if e.JWT != nil {
if err := e.JWT.Validate(); err != nil {
return err
}
}
if legacyWrite {
if len(e.Meta) > 0 {
return fmt.Errorf("Meta must be omitted for legacy intention writes")
}
} else {
if err := validateConfigEntryMeta(e.Meta); err != nil {
return err
}
}
if len(e.Sources) == 0 {
return fmt.Errorf("At least one source is required")
}
type qualifiedServiceName struct {
ServiceName ServiceName
Peer string
SamenessGroup string
}
seenSources := make(map[qualifiedServiceName]struct{})
for i, src := range e.Sources {
if src.Name == "" {
return fmt.Errorf("Sources[%d].Name is required", i)
}
if err := src.validateSamenessGroup(); err != nil {
return fmt.Errorf("Sources[%d].SamenessGroup: %v ", i, err)
}
if err := validateIntentionWildcards(src.Name, &src.EnterpriseMeta, src.Peer, src.SamenessGroup); err != nil {
return fmt.Errorf("Sources[%d].%v", i, err)
}
if err := validateSourceIntentionEnterpriseMeta(&src.EnterpriseMeta, &e.EnterpriseMeta); err != nil {
return fmt.Errorf("Sources[%d].%v", i, err)
}
if src.Peer != "" && src.PartitionOrEmpty() != "" {
return fmt.Errorf("Sources[%d].Peer: cannot set Peer and Partition at the same time.", i)
}
if src.SamenessGroup != "" && src.PartitionOrEmpty() != "" {
return fmt.Errorf("Sources[%d].SamenessGroup: cannot set SamenessGroup and Partition at the same time", i)
}
if src.SamenessGroup != "" && src.Peer != "" {
return fmt.Errorf("Sources[%d].SamenessGroup: cannot set SamenessGroup and Peer at the same time", i)
}
// Length of opaque values
if len(src.Description) > metaValueMaxLength {
return fmt.Errorf(
"Sources[%d].Description exceeds maximum length %d", i, metaValueMaxLength)
}
if legacyWrite {
if src.Peer != "" {
return fmt.Errorf("Sources[%d].Peer cannot be set by legacy intentions", i)
}
if src.SamenessGroup != "" {
return fmt.Errorf("Sources[%d].SamenessGroup cannot be set by legacy intentions", i)
}
if len(src.LegacyMeta) > metaMaxKeyPairs {
return fmt.Errorf(
"Sources[%d].Meta exceeds maximum element count %d", i, metaMaxKeyPairs)
}
for k, v := range src.LegacyMeta {
if len(k) > metaKeyMaxLength {
return fmt.Errorf(
"Sources[%d].Meta key %q exceeds maximum length %d",
i, k, metaKeyMaxLength,
)
}
if len(v) > metaValueMaxLength {
return fmt.Errorf(
"Sources[%d].Meta value for key %q exceeds maximum length %d",
i, k, metaValueMaxLength,
)
}
}
if src.LegacyCreateTime == nil {
return fmt.Errorf("Sources[%d].LegacyCreateTime must be set", i)
}
if src.LegacyUpdateTime == nil {
return fmt.Errorf("Sources[%d].LegacyUpdateTime must be set", i)
}
} else {
if len(src.LegacyMeta) > 0 {
return fmt.Errorf("Sources[%d].LegacyMeta must be omitted", i)
}
src.LegacyMeta = nil // ensure it's completely unset
if src.LegacyCreateTime != nil {
return fmt.Errorf("Sources[%d].LegacyCreateTime must be omitted", i)
}
if src.LegacyUpdateTime != nil {
return fmt.Errorf("Sources[%d].LegacyUpdateTime must be omitted", i)
}
}
if legacyWrite {
if src.LegacyID == "" {
return fmt.Errorf("Sources[%d].LegacyID must be set", i)
}
} else {
if src.LegacyID != "" {
return fmt.Errorf("Sources[%d].LegacyID must be omitted", i)
}
}
if legacyWrite || len(src.Permissions) == 0 {
switch src.Action {
case IntentionActionAllow, IntentionActionDeny:
default:
return fmt.Errorf("Sources[%d].Action must be set to 'allow' or 'deny'", i)
}
}
if len(src.Permissions) > 0 && src.Action != "" {
return fmt.Errorf("Sources[%d].Action must be omitted if Permissions are specified", i)
}
if destIsWild && len(src.Permissions) > 0 {
return fmt.Errorf("Sources[%d].Permissions cannot be specified on intentions with wildcarded destinations", i)
}
switch src.Type {
case IntentionSourceConsul:
default:
return fmt.Errorf("Sources[%d].Type must be set to 'consul'", i)
}
for j, perm := range src.Permissions {
switch perm.Action {
case IntentionActionAllow, IntentionActionDeny:
default:
return fmt.Errorf("Sources[%d].Permissions[%d].Action must be set to 'allow' or 'deny'", i, j)
}
errorPrefix := "Sources[%d].Permissions[%d].HTTP"
if perm.HTTP == nil {
return fmt.Errorf(errorPrefix+" is required", i, j)
}
pathParts := 0
if perm.HTTP.PathExact != "" {
pathParts++
if !strings.HasPrefix(perm.HTTP.PathExact, "/") {
return fmt.Errorf(
errorPrefix+".PathExact doesn't start with '/': %q",
i, j, perm.HTTP.PathExact,
)
}
}
if perm.HTTP.PathPrefix != "" {
pathParts++
if !strings.HasPrefix(perm.HTTP.PathPrefix, "/") {
return fmt.Errorf(
errorPrefix+".PathPrefix doesn't start with '/': %q",
i, j, perm.HTTP.PathPrefix,
)
}
}
if perm.HTTP.PathRegex != "" {
pathParts++
}
if pathParts > 1 {
return fmt.Errorf(
errorPrefix+" should only contain at most one of PathExact, PathPrefix, or PathRegex",
i, j,
)
}
permParts := pathParts
for k, hdr := range perm.HTTP.Header {
if hdr.Name == "" {
return fmt.Errorf(errorPrefix+".Header[%d] missing required Name field", i, j, k)
}
hdrParts := 0
if hdr.Present {
hdrParts++
}
if hdr.Exact != "" {
hdrParts++
}
if hdr.Regex != "" {
hdrParts++
}
if hdr.Prefix != "" {
hdrParts++
}
if hdr.Suffix != "" {
hdrParts++
}
if hdrParts != 1 {
return fmt.Errorf(errorPrefix+".Header[%d] should only contain one of Present, Exact, Prefix, Suffix, or Regex", i, j, k)
}
permParts++
}
if len(perm.HTTP.Methods) > 0 {
found := make(map[string]struct{})
for _, m := range perm.HTTP.Methods {
if !isValidHTTPMethod(m) {
return fmt.Errorf(errorPrefix+".Methods contains an invalid method %q", i, j, m)
}
if _, ok := found[m]; ok {
return fmt.Errorf(errorPrefix+".Methods contains %q more than once", i, j, m)
}
found[m] = struct{}{}
}
permParts++
}
if permParts == 0 {
return fmt.Errorf(errorPrefix+" should not be empty", i, j)
}
if err := perm.Validate(); err != nil {
return err
}
}
qsn := qualifiedServiceName{Peer: src.Peer, SamenessGroup: src.SamenessGroup, ServiceName: src.SourceServiceName()}
if _, exists := seenSources[qsn]; exists {
if qsn.Peer != "" {
return fmt.Errorf("Sources[%d] defines peer(%q) %q more than once", i, qsn.Peer, qsn.ServiceName.String())
} else if qsn.SamenessGroup != "" {
return fmt.Errorf("Sources[%d] defines sameness-group(%q) %q more than once", i, qsn.SamenessGroup, qsn.ServiceName.String())
} else {
return fmt.Errorf("Sources[%d] defines %q more than once", i, qsn.ServiceName.String())
}
}
seenSources[qsn] = struct{}{}
}
return nil
}
// Wildcard usage verification
func validateIntentionWildcards(name string, entMeta *acl.EnterpriseMeta, peerName, samenessGroup string) error {
ns := entMeta.NamespaceOrDefault()
if ns != WildcardSpecifier {
if strings.Contains(ns, WildcardSpecifier) {
return fmt.Errorf("Namespace: wildcard character '*' cannot be used with partial values")
}
}
if name != WildcardSpecifier {
if strings.Contains(name, WildcardSpecifier) {
return fmt.Errorf("Name: wildcard character '*' cannot be used with partial values")
}
if ns == WildcardSpecifier {
return fmt.Errorf("Name: exact value cannot follow wildcard namespace")
}
}
if strings.Contains(entMeta.PartitionOrDefault(), WildcardSpecifier) {
return fmt.Errorf("Partition: cannot use wildcard '*' in partition")
}
if strings.Contains(peerName, WildcardSpecifier) {
return fmt.Errorf("Peer: cannot use wildcard '*' in peer")
}
if strings.Contains(samenessGroup, WildcardSpecifier) {
return fmt.Errorf("SamenessGroup: cannot use wildcard '*' in sameness group")
}
return nil
}
func (e *ServiceIntentionsConfigEntry) GetRaftIndex() *RaftIndex {
if e == nil {
return &RaftIndex{}
}
return &e.RaftIndex
}
func (e *ServiceIntentionsConfigEntry) GetEnterpriseMeta() *acl.EnterpriseMeta {
if e == nil {
return nil
}
return &e.EnterpriseMeta
}
func (e *ServiceIntentionsConfigEntry) CanRead(authz acl.Authorizer) error {
var authzContext acl.AuthorizerContext
e.FillAuthzContext(&authzContext)
return authz.ToAllowAuthorizer().IntentionReadAllowed(e.GetName(), &authzContext)
}
func (e *ServiceIntentionsConfigEntry) CanWrite(authz acl.Authorizer) error {
var authzContext acl.AuthorizerContext
e.FillAuthzContext(&authzContext)
return authz.ToAllowAuthorizer().IntentionWriteAllowed(e.GetName(), &authzContext)
}
func MigrateIntentions(ixns Intentions) []*ServiceIntentionsConfigEntry {
if len(ixns) == 0 {
return nil
}
collated := make(map[ServiceName]*ServiceIntentionsConfigEntry)
for _, ixn := range ixns {
thisEntry := ixn.ToConfigEntry(true)
sn := thisEntry.DestinationServiceName()
if entry, ok := collated[sn]; ok {
entry.Sources = append(entry.Sources, thisEntry.Sources...)
} else {
collated[sn] = thisEntry
}
}
out := make([]*ServiceIntentionsConfigEntry, 0, len(collated))
for _, entry := range collated {
out = append(out, entry)
}
sort.Slice(out, func(i, j int) bool {
a := out[i]
b := out[j]
if a.PartitionOrDefault() < b.PartitionOrDefault() {
return true
} else if a.PartitionOrDefault() > b.PartitionOrDefault() {
return false
}