-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathplugin.go
1911 lines (1589 loc) · 58.5 KB
/
plugin.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 Contributors to the Open Cluster Management project
package internal
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"reflect"
"sort"
"strings"
"time"
yaml "gopkg.in/yaml.v3"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/util/validation"
"open-cluster-management.io/policy-generator-plugin/internal/types"
)
const (
configPolicyKind = "ConfigurationPolicy"
policyAPIGroup = "policy.open-cluster-management.io"
policyAPIVersion = policyAPIGroup + "/v1"
policyKind = "Policy"
policySetAPIVersion = policyAPIGroup + "/v1beta1"
policySetKind = "PolicySet"
placementBindingAPIVersion = policyAPIGroup + "/v1"
placementBindingKind = "PlacementBinding"
placementRuleAPIVersion = "apps.open-cluster-management.io/v1"
placementRuleKind = "PlacementRule"
placementAPIVersion = "cluster.open-cluster-management.io/v1beta1"
placementKind = "Placement"
maxObjectNameLength = 63
dnsReference = "https://kubernetes.io/docs/concepts/overview/working-with-objects/names/" +
"#dns-subdomain-names"
severityAnnotation = "policy.open-cluster-management.io/severity"
)
// Plugin is used to store the PolicyGenerator configuration and the methods to generate the
// desired policies.
type Plugin struct {
APIVersion string `json:"apiVersion,omitempty" yaml:"apiVersion,omitempty"`
Kind string `json:"kind,omitempty" yaml:"kind,omitempty"`
Metadata struct {
Name string `json:"name,omitempty" yaml:"name,omitempty"`
} `json:"metadata,omitempty" yaml:"metadata,omitempty"`
PlacementBindingDefaults struct {
Name string `json:"name,omitempty" yaml:"name,omitempty"`
} `json:"placementBindingDefaults,omitempty" yaml:"placementBindingDefaults,omitempty"`
PolicyDefaults types.PolicyDefaults `json:"policyDefaults,omitempty" yaml:"policyDefaults,omitempty"`
PolicySetDefaults types.PolicySetDefaults `json:"policySetDefaults,omitempty" yaml:"policySetDefaults,omitempty"`
Policies []types.PolicyConfig `json:"policies" yaml:"policies"`
PolicySets []types.PolicySetConfig `json:"policySets" yaml:"policySets"`
// A set of all placement names that have been processed or generated
allPlcs map[string]bool
// The base of the directory tree to restrict all manifest files to be within
baseDirectory string
// This is a mapping of cluster/label selectors formatted as the return value of getCsKey to
// placement names. This is used to find common cluster/label selectors that can be consolidated
// to a single placement.
csToPlc map[string]string
outputBuffer bytes.Buffer
// Track placement kind (we only expect to have one kind)
usingPlR bool
// A set of processed placements from external placements (either Placement.PlacementRulePath or
// Placement.PlacementPath)
processedPlcs map[string]bool
// Track previous policy name for use if policies are being ordered
previousPolicyName string
}
var defaults = types.PolicyDefaults{
PolicyOptions: types.PolicyOptions{
Categories: []string{"CM Configuration Management"},
Controls: []string{"CM-2 Baseline Configuration"},
Standards: []string{"NIST SP 800-53"},
},
ConfigurationPolicyOptions: types.ConfigurationPolicyOptions{
ComplianceType: "musthave",
RemediationAction: "inform",
Severity: "low",
},
}
// Config validates the input PolicyGenerator configuration, applies any missing defaults, and
// configures the Policy object.
func (p *Plugin) Config(config []byte, baseDirectory string) error {
dec := yaml.NewDecoder(bytes.NewReader(config))
dec.KnownFields(true) // emit an error on unknown fields in the input
err := dec.Decode(p)
const errTemplate = "the PolicyGenerator configuration file is invalid: %w"
if err != nil {
return fmt.Errorf(errTemplate, addFieldNotFoundHelp(err))
}
var unmarshaledConfig map[string]interface{}
err = yaml.Unmarshal(config, &unmarshaledConfig)
if err != nil {
return fmt.Errorf(errTemplate, err)
}
p.applyDefaults(unmarshaledConfig)
baseDirectory, err = filepath.EvalSymlinks(baseDirectory)
if err != nil {
return fmt.Errorf("failed to evaluate symlinks for the base directory: %w", err)
}
p.baseDirectory = baseDirectory
return p.assertValidConfig()
}
// Generate generates the policies, placements, and placement bindings and returns them as
// a single YAML file as a byte array. An error is returned if they cannot be created.
func (p *Plugin) Generate() ([]byte, error) {
// Set the default empty values to the fields that track state
p.allPlcs = map[string]bool{}
p.csToPlc = map[string]string{}
p.outputBuffer = bytes.Buffer{}
p.processedPlcs = map[string]bool{}
for i := range p.Policies {
err := p.createPolicy(&p.Policies[i])
if err != nil {
return nil, err
}
}
for i := range p.PolicySets {
err := p.createPolicySet(&p.PolicySets[i])
if err != nil {
return nil, err
}
}
// Keep track of which placement maps to which policy and policySet. This will be used to determine
// how many placement bindings are required since one binding per placement is required.
// plcNameToPolicyAndSetIdxs[plcName]["policy"] stores the index of policy
// plcNameToPolicyAndSetIdxs[plcName]["policyset"] stores the index of policyset
plcNameToPolicyAndSetIdxs := map[string]map[string][]int{}
for i := range p.Policies {
// only generate placement when GeneratePlacementWhenInSet equals to true, GeneratePlacement is true,
// or policy is not part of any policy sets
if p.Policies[i].GeneratePlacementWhenInSet ||
(p.Policies[i].GeneratePolicyPlacement && len(p.Policies[i].PolicySets) == 0) {
plcName, err := p.createPolicyPlacement(p.Policies[i].Placement, p.Policies[i].Name)
if err != nil {
return nil, err
}
if plcNameToPolicyAndSetIdxs[plcName] == nil {
plcNameToPolicyAndSetIdxs[plcName] = map[string][]int{}
}
plcNameToPolicyAndSetIdxs[plcName]["policy"] = append(plcNameToPolicyAndSetIdxs[plcName]["policy"], i)
}
}
for i := range p.PolicySets {
// only generate placement when GeneratePolicySetPlacement equals to true
if p.PolicySets[i].GeneratePolicySetPlacement {
plcName, err := p.createPolicySetPlacement(p.PolicySets[i].Placement, p.PolicySets[i].Name)
if err != nil {
return nil, err
}
if plcNameToPolicyAndSetIdxs[plcName] == nil {
plcNameToPolicyAndSetIdxs[plcName] = map[string][]int{}
}
plcNameToPolicyAndSetIdxs[plcName]["policyset"] = append(plcNameToPolicyAndSetIdxs[plcName]["policyset"], i)
}
}
// Sort the keys of plcNameToPolicyseetsIdxs so that the policy bindings are generated in a
// consistent order.
plcNames := make([]string, len(plcNameToPolicyAndSetIdxs))
i := 0
for k := range plcNameToPolicyAndSetIdxs {
plcNames[i] = k
i++
}
sort.Strings(plcNames)
plcBindingCount := 0
for _, plcName := range plcNames {
// Determine which policies and policy sets to be included in the placement binding.
policyConfs := []*types.PolicyConfig{}
for _, i := range plcNameToPolicyAndSetIdxs[plcName]["policy"] {
policyConfs = append(policyConfs, &p.Policies[i])
}
policySetConfs := []*types.PolicySetConfig{}
for _, i := range plcNameToPolicyAndSetIdxs[plcName]["policyset"] {
policySetConfs = append(policySetConfs, &p.PolicySets[i])
}
// If there is more than one policy associated with a placement but no default binding name
// specified, throw an error
if (len(policyConfs) > 1 || len(policySetConfs) > 1) && p.PlacementBindingDefaults.Name == "" {
return nil, fmt.Errorf(
"placementBindingDefaults.name must be set but is empty (multiple policies or policy sets were found "+
"for the PlacementBinding to placement %s)",
plcName,
)
}
var bindingName string
existMultiple := false
// If there is only one policy or one policy set, use the policy or policy set name if there is no default
// binding name specified
if len(policyConfs) == 1 && len(policySetConfs) == 0 {
bindingName = "binding-" + policyConfs[0].Name
} else if len(policyConfs) == 0 && len(policySetConfs) == 0 {
bindingName = "binding-" + policySetConfs[0].Name
} else {
existMultiple = true
}
// If there are multiple policies or policy sets, use the default placement binding name
// but append a number to it so it's a unique name.
if p.PlacementBindingDefaults.Name != "" && existMultiple {
plcBindingCount++
if plcBindingCount == 1 {
bindingName = p.PlacementBindingDefaults.Name
} else {
bindingName = fmt.Sprintf("%s%d", p.PlacementBindingDefaults.Name, plcBindingCount)
}
}
err := p.createPlacementBinding(bindingName, plcName, policyConfs, policySetConfs)
if err != nil {
return nil, fmt.Errorf("failed to create a placement binding: %w", err)
}
}
return p.outputBuffer.Bytes(), nil
}
func getPolicyDefaultBool(config map[string]interface{}, key string) (value bool, set bool) {
return getDefaultBool(config, "policyDefaults", key)
}
func getPolicySetDefaultBool(config map[string]interface{}, key string) (value bool, set bool) {
return getDefaultBool(config, "policySetDefaults", key)
}
func getDefaultBool(config map[string]interface{}, defaultKey string, key string) (value bool, set bool) {
defaults, ok := config[defaultKey].(map[string]interface{})
if ok {
value, set = defaults[key].(bool)
return
}
return false, false
}
func getPolicyBool(
config map[string]interface{}, policyIndex int, key string,
) (value bool, set bool) {
policy := getPolicy(config, policyIndex)
if policy == nil {
return false, false
}
value, set = policy[key].(bool)
return
}
func getPolicySetBool(
config map[string]interface{}, policySetIndex int, key string,
) (value bool, set bool) {
policySet := getPolicySet(config, policySetIndex)
if policySet == nil {
return false, false
}
value, set = policySet[key].(bool)
return
}
func getArrayObject(config map[string]interface{}, key string, idx int) map[string]interface{} {
array, ok := config[key].([]interface{})
if !ok {
return nil
}
if len(array)-1 < idx {
return nil
}
object, ok := array[idx].(map[string]interface{})
if !ok {
return nil
}
return object
}
// getPolicy will return a policy at the specified index in the Policy Generator configuration YAML.
func getPolicy(config map[string]interface{}, policyIndex int) map[string]interface{} {
return getArrayObject(config, "policies", policyIndex)
}
// getPolicySet will return a policy at the specified index in the Policy Generator configuration YAML.
func getPolicySet(config map[string]interface{}, policySetIndex int) map[string]interface{} {
return getArrayObject(config, "policySets", policySetIndex)
}
func isComplianceConfigSet(config map[string]interface{}, policyIndex int, field, complianceType string) bool {
policy := getPolicy(config, policyIndex)
if policy == nil {
return false
}
evaluationInterval, ok := policy[field].(map[string]interface{})
if !ok {
return false
}
_, set := evaluationInterval[complianceType].(string)
return set
}
// isEvaluationIntervalSet will return if the evaluation interval is set for the specified policy in the Policy
// Generator configuration YAML.
func isEvaluationIntervalSet(config map[string]interface{}, policyIndex int, complianceType string) bool {
return isComplianceConfigSet(config, policyIndex, "evaluationInterval", complianceType)
}
// isCustomMessageSet will return if the custom message is set for the specified policy in the Policy
// Generator configuration YAML.
func isCustomMessageSet(config map[string]interface{}, policyIndex int, complianceType string) bool {
return isComplianceConfigSet(config, policyIndex, "customMessage", complianceType)
}
func isComplianceConfigSetManifest(
config map[string]interface{}, policyIndex int, manifestIndex int, field, complianceType string,
) bool {
policy := getPolicy(config, policyIndex)
if policy == nil {
return false
}
manifests, ok := policy["manifests"].([]interface{})
if !ok {
return false
}
if len(manifests)-1 < manifestIndex {
return false
}
manifest, ok := manifests[manifestIndex].(map[string]interface{})
if !ok {
return false
}
fieldValue, ok := manifest[field].(map[string]interface{})
if !ok {
return false
}
_, set := fieldValue[complianceType].(string)
return set
}
// isEvaluationIntervalSetManifest will return whether the evaluation interval of the specified manifest
// of the specified policy is set in the Policy Generator configuration YAML.
func isEvaluationIntervalSetManifest(
config map[string]interface{}, policyIndex int, manifestIndex int, complianceType string,
) bool {
return isComplianceConfigSetManifest(config, policyIndex, manifestIndex, "evaluationInterval", complianceType)
}
// isCustomMessageSetManifest will return whether the compliance message of the specified manifest
// of the specified policy is set in the Policy Generator configuration YAML.
func isCustomMessageSetManifest(
config map[string]interface{}, policyIndex int, manifestIndex int, complianceType string,
) bool {
return isComplianceConfigSetManifest(config, policyIndex, manifestIndex, "customMessage", complianceType)
}
func isPolicyFieldSet(config map[string]interface{}, policyIndex int, field string) bool {
policy := getPolicy(config, policyIndex)
if policy == nil {
return false
}
_, set := policy[field]
return set
}
func isManifestFieldSet(config map[string]interface{}, policyIdx, manifestIdx int, field string) bool {
policy := getPolicy(config, policyIdx)
if policy == nil {
return false
}
manifests, ok := policy["manifests"].([]interface{})
if !ok {
return false
}
if len(manifests)-1 < manifestIdx {
return false
}
manifest, ok := manifests[manifestIdx].(map[string]interface{})
if !ok {
return false
}
_, set := manifest[field]
return set
}
// applyDefaults applies any missing defaults under Policy.PlacementBindingDefaults,
// Policy.PolicyDefaults and PolicySets. It then applies the defaults and user provided
// defaults on each policy and policyset entry if they are not overridden by the user. The
// input unmarshaledConfig is used in situations where it is necessary to know if an explicit
// false is provided rather than rely on the default Go value on the Plugin struct.
func (p *Plugin) applyDefaults(unmarshaledConfig map[string]interface{}) {
if len(p.Policies) == 0 {
return
}
// Set defaults to the defaults that aren't overridden
if p.PolicyDefaults.Categories == nil {
p.PolicyDefaults.Categories = defaults.Categories
}
if p.PolicyDefaults.ComplianceType == "" {
p.PolicyDefaults.ComplianceType = defaults.ComplianceType
}
if p.PolicyDefaults.Controls == nil {
p.PolicyDefaults.Controls = defaults.Controls
}
cpmValue, setCPM := getPolicyDefaultBool(unmarshaledConfig, "copyPolicyMetadata")
if setCPM {
p.PolicyDefaults.CopyPolicyMetadata = cpmValue
} else {
p.PolicyDefaults.CopyPolicyMetadata = true
}
// Policy expanders default to true unless explicitly set in the config.
// Gatekeeper policy expander policyDefault
igvValue, setIgv := getPolicyDefaultBool(unmarshaledConfig, "informGatekeeperPolicies")
if setIgv {
p.PolicyDefaults.InformGatekeeperPolicies = igvValue
} else {
p.PolicyDefaults.InformGatekeeperPolicies = true
}
// Kyverno policy expander policyDefault
ikvValue, setIkv := getPolicyDefaultBool(unmarshaledConfig, "informKyvernoPolicies")
if setIkv {
p.PolicyDefaults.InformKyvernoPolicies = ikvValue
} else {
p.PolicyDefaults.InformKyvernoPolicies = true
}
consolidatedValue, setConsolidated := getPolicyDefaultBool(unmarshaledConfig, "consolidateManifests")
if setConsolidated {
p.PolicyDefaults.ConsolidateManifests = consolidatedValue
} else if p.PolicyDefaults.OrderManifests {
p.PolicyDefaults.ConsolidateManifests = false
} else {
p.PolicyDefaults.ConsolidateManifests = true
}
if p.PolicyDefaults.RemediationAction == "" {
p.PolicyDefaults.RemediationAction = defaults.RemediationAction
}
if p.PolicyDefaults.Severity == "" {
p.PolicyDefaults.Severity = defaults.Severity
}
if p.PolicyDefaults.Standards == nil {
p.PolicyDefaults.Standards = defaults.Standards
}
// GeneratePolicyPlacement defaults to true unless explicitly set in the config.
gppValue, setGpp := getPolicyDefaultBool(unmarshaledConfig, "generatePolicyPlacement")
if setGpp {
p.PolicyDefaults.GeneratePolicyPlacement = gppValue
} else {
p.PolicyDefaults.GeneratePolicyPlacement = true
}
// Generate temporary sets to later merge the policy sets declared in p.Policies[*] and p.PolicySets
plcsetToPlc := make(map[string]map[string]bool)
plcToPlcset := make(map[string]map[string]bool)
for _, plcset := range p.PolicySets {
if plcsetToPlc[plcset.Name] == nil {
plcsetToPlc[plcset.Name] = make(map[string]bool)
}
for _, plc := range plcset.Policies {
plcsetToPlc[plcset.Name][plc] = true
if plcToPlcset[plc] == nil {
plcToPlcset[plc] = make(map[string]bool)
}
plcToPlcset[plc][plcset.Name] = true
}
}
applyDefaultDependencyFields(p.PolicyDefaults.Dependencies, p.PolicyDefaults.Namespace)
applyDefaultDependencyFields(p.PolicyDefaults.ExtraDependencies, p.PolicyDefaults.Namespace)
for i := range p.Policies {
policy := &p.Policies[i]
if policy.PolicyAnnotations == nil {
annotations := map[string]string{}
for k, v := range p.PolicyDefaults.PolicyAnnotations {
annotations[k] = v
}
policy.PolicyAnnotations = annotations
}
if policy.PolicyLabels == nil {
labels := map[string]string{}
for k, v := range p.PolicyDefaults.PolicyLabels {
labels[k] = v
}
policy.PolicyLabels = labels
}
if policy.Categories == nil {
policy.Categories = p.PolicyDefaults.Categories
}
if policy.ConfigurationPolicyAnnotations == nil {
annotations := map[string]string{}
for k, v := range p.PolicyDefaults.ConfigurationPolicyAnnotations {
annotations[k] = v
}
policy.ConfigurationPolicyAnnotations = annotations
}
cpmValue, setCpm := getPolicyBool(unmarshaledConfig, i, "copyPolicyMetadata")
if setCpm {
policy.CopyPolicyMetadata = cpmValue
} else {
policy.CopyPolicyMetadata = p.PolicyDefaults.CopyPolicyMetadata
}
if policy.Standards == nil {
policy.Standards = p.PolicyDefaults.Standards
}
if policy.Controls == nil {
policy.Controls = p.PolicyDefaults.Controls
}
if policy.Description == "" {
policy.Description = p.PolicyDefaults.Description
}
if policy.RecreateOption == "" {
policy.RecreateOption = p.PolicyDefaults.RecreateOption
}
if policy.RecordDiff == "" {
policy.RecordDiff = p.PolicyDefaults.RecordDiff
}
if policy.ComplianceType == "" {
policy.ComplianceType = p.PolicyDefaults.ComplianceType
}
if policy.MetadataComplianceType == "" {
policy.MetadataComplianceType = p.PolicyDefaults.MetadataComplianceType
}
if policy.GatekeeperEnforcementAction == "" {
policy.GatekeeperEnforcementAction = p.PolicyDefaults.GatekeeperEnforcementAction
}
// Only use the policyDefault evaluationInterval value when it's not explicitly set on the policy.
if policy.EvaluationInterval.Compliant == "" {
set := isEvaluationIntervalSet(unmarshaledConfig, i, "compliant")
if !set {
policy.EvaluationInterval.Compliant = p.PolicyDefaults.EvaluationInterval.Compliant
}
}
if policy.EvaluationInterval.NonCompliant == "" {
set := isEvaluationIntervalSet(unmarshaledConfig, i, "noncompliant")
if !set {
policy.EvaluationInterval.NonCompliant = p.PolicyDefaults.EvaluationInterval.NonCompliant
}
}
// Only use the policyDefault customMessage value when it's not explicitly set on the policy.
if policy.CustomMessage.Compliant == "" {
set := isCustomMessageSet(unmarshaledConfig, i, "compliant")
if !set {
policy.CustomMessage.Compliant = p.PolicyDefaults.CustomMessage.Compliant
}
}
if policy.CustomMessage.NonCompliant == "" {
set := isCustomMessageSet(unmarshaledConfig, i, "noncompliant")
if !set {
policy.CustomMessage.NonCompliant = p.PolicyDefaults.CustomMessage.NonCompliant
}
}
if policy.PruneObjectBehavior == "" {
policy.PruneObjectBehavior = p.PolicyDefaults.PruneObjectBehavior
}
if policy.PolicySets == nil {
policy.PolicySets = p.PolicyDefaults.PolicySets
}
// GeneratePolicyPlacement defaults to true unless explicitly set in the config.
gppValue, setGpp := getPolicyBool(unmarshaledConfig, i, "generatePolicyPlacement")
if setGpp {
policy.GeneratePolicyPlacement = gppValue
} else {
policy.GeneratePolicyPlacement = p.PolicyDefaults.GeneratePolicyPlacement
}
// GeneratePlacementWhenInSet defaults to false unless explicitly set in the config.
gpsetValue, setGpset := getPolicyBool(unmarshaledConfig, i, "generatePlacementWhenInSet")
if setGpset {
policy.GeneratePlacementWhenInSet = gpsetValue
} else {
policy.GeneratePlacementWhenInSet = p.PolicyDefaults.GeneratePlacementWhenInSet
}
// Policy expanders default to the policy default unless explicitly set.
// Gatekeeper policy expander policy override
igvValue, setIgv := getPolicyBool(unmarshaledConfig, i, "informGatekeeperPolicies")
if setIgv {
policy.InformGatekeeperPolicies = igvValue
} else {
policy.InformGatekeeperPolicies = p.PolicyDefaults.InformGatekeeperPolicies
}
// Kyverno policy expander policy override
ikvValue, setIkv := getPolicyBool(unmarshaledConfig, i, "informKyvernoPolicies")
if setIkv {
policy.InformKyvernoPolicies = ikvValue
} else {
policy.InformKyvernoPolicies = p.PolicyDefaults.InformKyvernoPolicies
}
if !isPolicyFieldSet(unmarshaledConfig, i, "orderManifests") {
policy.OrderManifests = p.PolicyDefaults.OrderManifests
}
consolidatedValue, setConsolidated := getPolicyBool(unmarshaledConfig, i, "consolidateManifests")
if setConsolidated {
policy.ConsolidateManifests = consolidatedValue
} else if policy.OrderManifests {
policy.ConsolidateManifests = false
} else {
policy.ConsolidateManifests = p.PolicyDefaults.ConsolidateManifests
}
disabledValue, setDisabled := getPolicyBool(unmarshaledConfig, i, "disabled")
if setDisabled {
policy.Disabled = disabledValue
} else {
policy.Disabled = p.PolicyDefaults.Disabled
}
ignorePending, ignorePendingIsSet := getPolicyBool(unmarshaledConfig, i, "ignorePending")
if ignorePendingIsSet {
policy.IgnorePending = ignorePending
} else {
policy.IgnorePending = p.PolicyDefaults.IgnorePending
}
if isPolicyFieldSet(unmarshaledConfig, i, "dependencies") {
applyDefaultDependencyFields(policy.Dependencies, p.PolicyDefaults.Namespace)
} else {
policy.Dependencies = p.PolicyDefaults.Dependencies
}
if isPolicyFieldSet(unmarshaledConfig, i, "extraDependencies") {
applyDefaultDependencyFields(policy.ExtraDependencies, p.PolicyDefaults.Namespace)
} else {
policy.ExtraDependencies = p.PolicyDefaults.ExtraDependencies
}
applyDefaultPlacementFields(&policy.Placement, p.PolicyDefaults.Placement)
// Only use defaults when the namespaceSelector is not set on the policy
nsSelector := policy.NamespaceSelector
defNsSelector := p.PolicyDefaults.NamespaceSelector
if nsSelector.Exclude == nil && nsSelector.Include == nil &&
nsSelector.MatchLabels == nil && nsSelector.MatchExpressions == nil {
policy.NamespaceSelector = defNsSelector
}
if policy.RemediationAction == "" {
policy.RemediationAction = p.PolicyDefaults.RemediationAction
}
if policy.Severity == "" {
policy.Severity = p.PolicyDefaults.Severity
}
if policy.HubTemplateOptions.ServiceAccountName == "" {
policy.HubTemplateOptions.ServiceAccountName = p.PolicyDefaults.HubTemplateOptions.ServiceAccountName
}
for j := range policy.Manifests {
manifest := &policy.Manifests[j]
// Only use the policy's ConfigurationPolicyOptions values when they're not explicitly set in
// the manifest.
if manifest.ComplianceType == "" {
manifest.ComplianceType = policy.ComplianceType
}
if manifest.MetadataComplianceType == "" {
manifest.MetadataComplianceType = policy.MetadataComplianceType
}
if manifest.EvaluationInterval.Compliant == "" {
set := isEvaluationIntervalSetManifest(unmarshaledConfig, i, j, "compliant")
if !set {
manifest.EvaluationInterval.Compliant = policy.EvaluationInterval.Compliant
}
}
if manifest.EvaluationInterval.NonCompliant == "" {
set := isEvaluationIntervalSetManifest(unmarshaledConfig, i, j, "noncompliant")
if !set {
manifest.EvaluationInterval.NonCompliant = policy.EvaluationInterval.NonCompliant
}
}
if manifest.CustomMessage.Compliant == "" {
set := isCustomMessageSetManifest(unmarshaledConfig, i, j, "compliant")
if !set {
manifest.CustomMessage.Compliant = policy.CustomMessage.Compliant
}
}
if manifest.CustomMessage.NonCompliant == "" {
set := isCustomMessageSetManifest(unmarshaledConfig, i, j, "noncompliant")
if !set {
manifest.CustomMessage.NonCompliant = policy.CustomMessage.NonCompliant
}
}
selector := manifest.NamespaceSelector
if selector.Exclude == nil && selector.Include == nil &&
selector.MatchLabels == nil && selector.MatchExpressions == nil {
manifest.NamespaceSelector = policy.NamespaceSelector
}
if manifest.RemediationAction == "" && policy.RemediationAction != "" {
manifest.RemediationAction = policy.RemediationAction
}
if manifest.PruneObjectBehavior == "" && policy.PruneObjectBehavior != "" {
manifest.PruneObjectBehavior = policy.PruneObjectBehavior
}
if manifest.Severity == "" && policy.Severity != "" {
manifest.Severity = policy.Severity
}
if manifest.RecreateOption == "" {
manifest.RecreateOption = policy.RecreateOption
}
if manifest.RecordDiff == "" {
manifest.RecordDiff = policy.RecordDiff
}
if manifest.GatekeeperEnforcementAction == "" {
manifest.GatekeeperEnforcementAction = policy.GatekeeperEnforcementAction
}
if isManifestFieldSet(unmarshaledConfig, i, j, "extraDependencies") {
applyDefaultDependencyFields(manifest.ExtraDependencies, p.PolicyDefaults.Namespace)
} else {
manifest.ExtraDependencies = policy.ExtraDependencies
}
if !isManifestFieldSet(unmarshaledConfig, i, j, "ignorePending") {
manifest.IgnorePending = policy.IgnorePending
}
}
for _, plcsetInPlc := range policy.PolicySets {
if _, ok := plcsetToPlc[plcsetInPlc]; !ok {
newPlcset := types.PolicySetConfig{
Name: plcsetInPlc,
}
p.PolicySets = append(p.PolicySets, newPlcset)
plcsetToPlc[plcsetInPlc] = make(map[string]bool)
}
if plcToPlcset[policy.Name] == nil {
plcToPlcset[policy.Name] = make(map[string]bool)
}
plcToPlcset[policy.Name][plcsetInPlc] = true
plcsetToPlc[plcsetInPlc][policy.Name] = true
}
policy.PolicySets = make([]string, 0, len(plcToPlcset[policy.Name]))
for plcset := range plcToPlcset[policy.Name] {
policy.PolicySets = append(policy.PolicySets, plcset)
}
}
gpspValue, setGpsp := getPolicySetDefaultBool(unmarshaledConfig, "generatePolicySetPlacement")
if setGpsp {
p.PolicySetDefaults.GeneratePolicySetPlacement = gpspValue
} else {
p.PolicySetDefaults.GeneratePolicySetPlacement = true
}
// Sync up the declared policy sets in p.Policies[*]
for i := range p.PolicySets {
plcset := &p.PolicySets[i]
plcset.Policies = make([]string, 0, len(plcsetToPlc[plcset.Name]))
for plc := range plcsetToPlc[plcset.Name] {
plcset.Policies = append(plcset.Policies, plc)
}
// GeneratePolicySetPlacement defaults to true unless explicitly set in the config.
gpspValue, setGpsp := getPolicySetBool(unmarshaledConfig, i, "generatePolicySetPlacement")
if setGpsp {
plcset.GeneratePolicySetPlacement = gpspValue
} else {
plcset.GeneratePolicySetPlacement = p.PolicySetDefaults.GeneratePolicySetPlacement
}
applyDefaultPlacementFields(&plcset.Placement, p.PolicySetDefaults.Placement)
// Sort alphabetically to make it deterministic
sort.Strings(plcset.Policies)
}
}
func applyDefaultDependencyFields(deps []types.PolicyDependency, namespace string) {
for i, dep := range deps {
if dep.Kind == "" {
deps[i].Kind = policyKind
}
if dep.APIVersion == "" {
deps[i].APIVersion = policyAPIVersion
}
if dep.Namespace == "" && deps[i].Kind == policyKind {
deps[i].Namespace = namespace
}
if dep.Compliance == "" {
deps[i].Compliance = "Compliant"
}
}
}
// applyDefaultPlacementFields is a helper for applyDefaults that handles default Placement configuration
func applyDefaultPlacementFields(placement *types.PlacementConfig, defaultPlacement types.PlacementConfig) {
// Determine whether defaults are set for placement
plcDefaultSet := len(defaultPlacement.LabelSelector) != 0 ||
defaultPlacement.PlacementPath != "" ||
defaultPlacement.PlacementName != ""
plrDefaultSet := len(defaultPlacement.ClusterSelectors) != 0 ||
len(defaultPlacement.ClusterSelector) != 0 ||
defaultPlacement.PlacementRulePath != "" ||
defaultPlacement.PlacementRuleName != ""
policyPlcUnset := len(placement.LabelSelector) == 0 &&
placement.PlacementPath == "" &&
placement.PlacementName == ""
policyPlrUnset := len(placement.ClusterSelectors) == 0 &&
len(placement.ClusterSelector) == 0 &&
placement.PlacementRulePath == "" &&
placement.PlacementRuleName == ""
// If both cluster label selectors and placement path/name aren't set, then use the defaults with a
// priority on placement path followed by placement name.
if policyPlcUnset && plcDefaultSet {
if !policyPlrUnset {
return
} else if defaultPlacement.PlacementPath != "" {
placement.PlacementPath = defaultPlacement.PlacementPath
} else if defaultPlacement.PlacementName != "" {
placement.PlacementName = defaultPlacement.PlacementName
} else if len(defaultPlacement.LabelSelector) > 0 {
placement.LabelSelector = defaultPlacement.LabelSelector
}
} else if policyPlrUnset && plrDefaultSet {
// Else if both cluster selectors and placement rule path/name aren't set, then use the defaults with a
// priority on placement rule path followed by placement rule name.
if !policyPlcUnset {
return
} else if defaultPlacement.PlacementRulePath != "" {
placement.PlacementRulePath = defaultPlacement.PlacementRulePath
} else if defaultPlacement.PlacementRuleName != "" {
placement.PlacementRuleName = defaultPlacement.PlacementRuleName
} else if len(defaultPlacement.ClusterSelectors) > 0 {
placement.ClusterSelectors = defaultPlacement.ClusterSelectors
} else if len(defaultPlacement.ClusterSelector) > 0 {
placement.ClusterSelector = defaultPlacement.ClusterSelector
}
}
}
// assertValidConfig verifies that the user provided configuration has all the
// required fields. Note that this should be run only after applyDefaults is run.
func (p *Plugin) assertValidConfig() error {
if p.PolicyDefaults.Namespace == "" {
return errors.New("policyDefaults.namespace is empty but it must be set")
}
// Validate default policy placement settings
err := p.assertValidPlacement(p.PolicyDefaults.Placement, "policyDefaults", nil)
if err != nil {
return err
}
// validate placement binding names are DNS compliant
if p.PlacementBindingDefaults.Name != "" &&
len(validation.IsDNS1123Subdomain(p.PlacementBindingDefaults.Name)) > 0 {
return fmt.Errorf(
"PlacementBindingDefaults.Name `%s` is not DNS compliant. See %s",
p.PlacementBindingDefaults.Name,
dnsReference,
)
}
if len(p.Policies) == 0 {
return errors.New("policies is empty but it must be set")
}
if p.PolicyDefaults.OrderPolicies && len(p.PolicyDefaults.Dependencies) != 0 {
return errors.New("policyDefaults must specify only one of dependencies or orderPolicies")
}
for i, dep := range p.PolicyDefaults.Dependencies {
if dep.Name == "" {
return fmt.Errorf("dependency name must be set in policyDefaults dependency %v", i)
}
}
if p.PolicyDefaults.OrderManifests && p.PolicyDefaults.ConsolidateManifests {
return errors.New("policyDefaults may not specify both consolidateManifests and orderManifests")
}
if len(p.PolicyDefaults.ExtraDependencies) > 0 && p.PolicyDefaults.OrderManifests {
return errors.New("policyDefaults may not specify both extraDependencies and orderManifests")
}
for i, dep := range p.PolicyDefaults.ExtraDependencies {
if dep.Name == "" {
return fmt.Errorf("extraDependency name must be set in policyDefaults extraDependency %v", i)
}
}
seenPlc := map[string]bool{}
plCount := struct {
plc int