1
0
Fork 0
mirror of https://github.com/kyverno/kyverno.git synced 2024-12-14 11:57:48 +00:00

refactor: introduce rules getters and setters (#3350)

Signed-off-by: Charles-Edouard Brétéché <charled.breteche@gmail.com>

Co-authored-by: shuting <shuting@nirmata.com>
Co-authored-by: Prateek Pandey <prateekpandey14@gmail.com>
This commit is contained in:
Charles-Edouard Brétéché 2022-03-09 16:28:31 +01:00 committed by GitHub
parent ea977b259c
commit ce5f648f30
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
32 changed files with 101 additions and 89 deletions

View file

@ -81,6 +81,14 @@ type Spec struct {
WebhookTimeoutSeconds *int32 `json:"webhookTimeoutSeconds,omitempty" yaml:"webhookTimeoutSeconds,omitempty"`
}
func (base *Spec) GetRules() []Rule {
return base.Rules
}
func (base *Spec) SetRules(rules []Rule) {
base.Rules = rules
}
// Rule defines a validation, mutation, or generation control for matching resources.
// Each rules contains a match declaration to select resources, and an optional exclude
// declaration to specify which resources to exclude.

View file

@ -42,7 +42,7 @@ func (p *ClusterPolicy) HasAutoGenAnnotation() bool {
// HasMutateOrValidateOrGenerate checks for rule types
func (p *ClusterPolicy) HasMutateOrValidateOrGenerate() bool {
for _, rule := range p.Spec.Rules {
for _, rule := range p.Spec.GetRules() {
if rule.HasMutate() || rule.HasValidate() || rule.HasGenerate() {
return true
}
@ -52,7 +52,7 @@ func (p *ClusterPolicy) HasMutateOrValidateOrGenerate() bool {
// HasMutate checks for mutate rule types
func (p *ClusterPolicy) HasMutate() bool {
for _, rule := range p.Spec.Rules {
for _, rule := range p.Spec.GetRules() {
if rule.HasMutate() {
return true
}
@ -63,7 +63,7 @@ func (p *ClusterPolicy) HasMutate() bool {
// HasValidate checks for validate rule types
func (p *ClusterPolicy) HasValidate() bool {
for _, rule := range p.Spec.Rules {
for _, rule := range p.Spec.GetRules() {
if rule.HasValidate() {
return true
}
@ -74,7 +74,7 @@ func (p *ClusterPolicy) HasValidate() bool {
// HasGenerate checks for generate rule types
func (p *ClusterPolicy) HasGenerate() bool {
for _, rule := range p.Spec.Rules {
for _, rule := range p.Spec.GetRules() {
if rule.HasGenerate() {
return true
}
@ -85,7 +85,7 @@ func (p *ClusterPolicy) HasGenerate() bool {
// HasVerifyImages checks for image verification rule types
func (p *ClusterPolicy) HasVerifyImages() bool {
for _, rule := range p.Spec.Rules {
for _, rule := range p.Spec.GetRules() {
if rule.HasVerifyImages() {
return true
}

View file

@ -27,7 +27,8 @@ const (
// - otherwise it returns all pod controllers
func CanAutoGen(spec *kyverno.Spec, log logr.Logger) (applyAutoGen bool, controllers string) {
var needAutogen bool
for _, rule := range spec.Rules {
rules := spec.GetRules()
for _, rule := range rules {
match := rule.MatchResources
exclude := rule.ExcludeResources
@ -115,15 +116,16 @@ func CanAutoGen(spec *kyverno.Spec, log logr.Logger) (applyAutoGen bool, control
// GenerateRulePatches generates rule for podControllers based on scenario A and C
func GenerateRulePatches(spec *kyverno.Spec, controllers string, log logr.Logger) (rulePatches [][]byte, errs []error) {
insertIdx := len(spec.Rules)
rules := spec.GetRules()
insertIdx := len(rules)
ruleMap := createRuleMap(spec.Rules)
ruleMap := createRuleMap(rules)
var ruleIndex = make(map[string]int)
for index, rule := range spec.Rules {
for index, rule := range rules {
ruleIndex[rule.Name] = index
}
for _, rule := range spec.Rules {
for _, rule := range rules {
patchPostion := insertIdx
convertToPatches := func(genRule kyvernoRule, patchPostion int) []byte {
operation := "add"

View file

@ -120,7 +120,7 @@ func Test_Any(t *testing.T) {
}
policy := policies[0]
policy.Spec.Rules[0].MatchResources.Any = kyverno.ResourceFilters{
policy.Spec.GetRules()[0].MatchResources.Any = kyverno.ResourceFilters{
{
ResourceDescription: kyverno.ResourceDescription{
Kinds: []string{"Pod"},
@ -158,7 +158,7 @@ func Test_All(t *testing.T) {
}
policy := policies[0]
policy.Spec.Rules[0].MatchResources.All = kyverno.ResourceFilters{
policy.Spec.GetRules()[0].MatchResources.All = kyverno.ResourceFilters{
{
ResourceDescription: kyverno.ResourceDescription{
Kinds: []string{"Pod"},
@ -196,7 +196,7 @@ func Test_Exclude(t *testing.T) {
}
policy := policies[0]
policy.Spec.Rules[0].ExcludeResources.Namespaces = []string{"fake-namespce"}
policy.Spec.GetRules()[0].ExcludeResources.Namespaces = []string{"fake-namespce"}
rulePatches, errs := GenerateRulePatches(&policy.Spec, PodControllers, log.Log)
if len(errs) != 0 {
@ -260,7 +260,7 @@ func Test_ForEachPod(t *testing.T) {
}
policy := policies[0]
policy.Spec.Rules[0].ExcludeResources.Namespaces = []string{"fake-namespce"}
policy.Spec.GetRules()[0].ExcludeResources.Namespaces = []string{"fake-namespce"}
rulePatches, errs := GenerateRulePatches(&policy.Spec, PodControllers, log.Log)
if len(errs) != 0 {
@ -299,10 +299,10 @@ func Test_CronJob_hasExclude(t *testing.T) {
kyverno.PodControllersAnnotation: controllers,
})
rule := policy.Spec.Rules[0].DeepCopy()
rule := policy.Spec.GetRules()[0].DeepCopy()
rule.ExcludeResources.Kinds = []string{"Pod"}
rule.ExcludeResources.Namespaces = []string{"test"}
policy.Spec.Rules[0] = *rule
policy.Spec.GetRules()[0] = *rule
rulePatches, errs := GenerateRulePatches(&policy.Spec, controllers, log.Log)
if len(errs) != 0 {
@ -389,7 +389,7 @@ func Test_Deny(t *testing.T) {
}
policy := policies[0]
policy.Spec.Rules[0].MatchResources.Any = kyverno.ResourceFilters{
policy.Spec.GetRules()[0].MatchResources.Any = kyverno.ResourceFilters{
{
ResourceDescription: kyverno.ResourceDescription{
Kinds: []string{"Pod"},

View file

@ -94,7 +94,7 @@ func AddCloneLabel(client *dclient.Client, pInformer kyvernoinformer.ClusterPoli
}
for _, policy := range policies {
for _, rule := range policy.Spec.Rules {
for _, rule := range policy.Spec.GetRules() {
if rule.HasGenerate() {
clone := rule.Generation.Clone
if clone.Name != "" {

View file

@ -19,7 +19,7 @@ func ForceMutate(ctx *context.Context, policy kyverno.ClusterPolicy, resource un
"namespace", resource.GetNamespace(), "name", resource.GetName())
patchedResource := resource
for _, rule := range policy.Spec.Rules {
for _, rule := range policy.Spec.GetRules() {
if !rule.HasMutate() {
continue
}

View file

@ -48,7 +48,7 @@ func filterRules(policyContext *PolicyContext, startTime time.Time) *response.En
return resp
}
for _, rule := range policyContext.Policy.Spec.Rules {
for _, rule := range policyContext.Policy.Spec.GetRules() {
if ruleResp := filterRule(rule, policyContext); ruleResp != nil {
resp.PolicyResponse.Rules = append(resp.PolicyResponse.Rules, *ruleResp)
}

View file

@ -48,8 +48,9 @@ func VerifyAndPatchImages(policyContext *PolicyContext) (resp *response.EngineRe
}
}
for i := range policyContext.Policy.Spec.Rules {
rule := &policyContext.Policy.Spec.Rules[i]
rules := policyContext.Policy.Spec.GetRules()
for i := range rules {
rule := &rules[i]
if len(rule.VerifyImages) == 0 {
continue
}

View file

@ -242,7 +242,7 @@ func Test_PolicyDeserilize(t *testing.T) {
err := json.Unmarshal(rawPolicy, &policy)
assert.NilError(t, err)
overlayPatches := policy.Spec.Rules[0].Mutation.GetPatchStrategicMerge()
overlayPatches := policy.Spec.GetRules()[0].Mutation.GetPatchStrategicMerge()
patchString, err := json.Marshal(overlayPatches)
assert.NilError(t, err)

View file

@ -39,7 +39,7 @@ func Mutate(policyContext *PolicyContext) (resp *response.EngineResponse) {
var err error
for _, rule := range policy.Spec.Rules {
for _, rule := range policy.Spec.GetRules() {
if !rule.HasMutate() {
continue
}

View file

@ -897,7 +897,7 @@ func TestMatchesResourceDescription(t *testing.T) {
}
resource, _ := utils.ConvertToUnstructured(tc.Resource)
for _, rule := range policy.Spec.Rules {
for _, rule := range policy.Spec.GetRules() {
err := MatchesResourceDescription(*resource, rule, tc.AdmissionInfo, []string{}, nil, "")
if err != nil {
if !tc.areErrorsExpected {

View file

@ -87,8 +87,9 @@ func validateResource(log logr.Logger, ctx *PolicyContext) *response.EngineRespo
ctx.JSONContext.Checkpoint()
defer ctx.JSONContext.Restore()
for i := range ctx.Policy.Spec.Rules {
rule := &ctx.Policy.Spec.Rules[i]
rules := ctx.Policy.Spec.GetRules()
for i := range rules {
rule := &rules[i]
if !rule.HasValidate() {
continue
}

View file

@ -141,7 +141,7 @@ func (c *Controller) deletePolicy(obj interface{}) {
// clean up the GR
// Get the corresponding GR
// get the list of GR for the current Policy version
rules := p.Spec.Rules
rules := p.Spec.GetRules()
generatePolicyWithClone := pkgCommon.ProcessDeletePolicyForCloneGenerateRule(rules, c.client, p.GetName(), logger)

View file

@ -259,7 +259,7 @@ func (c *Controller) applyGeneratePolicy(log logr.Logger, policyContext *engine.
// To manage existing resources, we compare the creation time for the default resource to be generated and policy creation time
ruleNameToProcessingTime := make(map[string]time.Duration)
for _, rule := range policy.Spec.Rules {
for _, rule := range policy.Spec.GetRules() {
var err error
if !rule.HasGenerate() {
continue

View file

@ -258,7 +258,7 @@ func (c *Controller) updatePolicy(old, cur interface{}) {
}
var policyHasGenerate bool
for _, rule := range curP.Spec.Rules {
for _, rule := range curP.Spec.GetRules() {
if rule.HasGenerate() {
policyHasGenerate = true
}

View file

@ -471,7 +471,7 @@ func ApplyPolicyOnResource(policy *v1.ClusterPolicy, resource *unstructured.Unst
policyWithNamespaceSelector := false
OuterLoop:
for _, p := range policy.Spec.Rules {
for _, p := range policy.Spec.GetRules() {
if p.MatchResources.ResourceDescription.NamespaceSelector != nil ||
p.ExcludeResources.ResourceDescription.NamespaceSelector != nil {
policyWithNamespaceSelector = true
@ -573,7 +573,7 @@ OuterLoop:
}
var policyHasValidate bool
for _, rule := range policy.Spec.Rules {
for _, rule := range policy.Spec.GetRules() {
if rule.HasValidate() {
policyHasValidate = true
}
@ -591,7 +591,7 @@ OuterLoop:
}
var policyHasGenerate bool
for _, rule := range policy.Spec.Rules {
for _, rule := range policy.Spec.GetRules() {
if rule.HasGenerate() {
policyHasGenerate = true
}
@ -748,7 +748,7 @@ func GetResourceAccordingToResourcePath(fs billy.Filesystem, resourcePaths []str
func ProcessValidateEngineResponse(policy *v1.ClusterPolicy, validateResponse *response.EngineResponse, resPath string, rc *ResultCounts, policyReport bool) policyreport.Info {
var violatedRules []v1.ViolatedRule
printCount := 0
for _, policyRule := range policy.Spec.Rules {
for _, policyRule := range policy.Spec.GetRules() {
ruleFoundInEngineResponse := false
if !policyRule.HasValidate() {
continue
@ -829,7 +829,7 @@ func buildPVInfo(er *response.EngineResponse, violatedRules []v1.ViolatedRule) p
func processGenerateEngineResponse(policy *v1.ClusterPolicy, generateResponse *response.EngineResponse, resPath string, rc *ResultCounts) {
printCount := 0
for _, policyRule := range policy.Spec.Rules {
for _, policyRule := range policy.Spec.GetRules() {
ruleFoundInEngineResponse := false
for i, genResponseRule := range generateResponse.PolicyResponse.Rules {
if policyRule.Name == genResponseRule.Name {
@ -857,7 +857,7 @@ func SetInStoreContext(mutatedPolicies []*v1.ClusterPolicy, variables map[string
storePolicies := make([]store.Policy, 0)
for _, policy := range mutatedPolicies {
storeRules := make([]store.Rule, 0)
for _, rule := range policy.Spec.Rules {
for _, rule := range policy.Spec.GetRules() {
contextVal := make(map[string]string)
if len(rule.Context) != 0 {
for _, contextVar := range rule.Context {
@ -889,7 +889,7 @@ func SetInStoreContext(mutatedPolicies []*v1.ClusterPolicy, variables map[string
func processMutateEngineResponse(policy *v1.ClusterPolicy, mutateResponse *response.EngineResponse, resPath string, rc *ResultCounts, mutateLogPath string, stdin bool, mutateLogPathIsDir bool, resourceName string, printPatchResource bool) error {
var policyHasMutate bool
for _, rule := range policy.Spec.Rules {
for _, rule := range policy.Spec.GetRules() {
if rule.HasMutate() {
policyHasMutate = true
}
@ -900,7 +900,7 @@ func processMutateEngineResponse(policy *v1.ClusterPolicy, mutateResponse *respo
printCount := 0
printMutatedRes := false
for _, policyRule := range policy.Spec.Rules {
for _, policyRule := range policy.Spec.GetRules() {
ruleFoundInEngineResponse := false
for i, mutateResponseRule := range mutateResponse.PolicyResponse.Rules {
if policyRule.Name == mutateResponseRule.Name {
@ -999,7 +999,7 @@ func CheckVariableForPolicy(valuesMap map[string]map[string]Resource, globalValM
func GetKindsFromPolicy(policy *v1.ClusterPolicy) map[string]struct{} {
var kindOnwhichPolicyIsApplied = make(map[string]struct{})
for _, rule := range policy.Spec.Rules {
for _, rule := range policy.Spec.GetRules() {
for _, kind := range rule.MatchResources.ResourceDescription.Kinds {
kindOnwhichPolicyIsApplied[kind] = struct{}{}
}

View file

@ -31,7 +31,7 @@ func GetResources(policies []*v1.ClusterPolicy, resourcePaths []string, dClient
var resourceTypes []string
for _, policy := range policies {
for _, rule := range policy.Spec.Rules {
for _, rule := range policy.Spec.GetRules() {
resourceTypesInRule := getKindsFromPolicy(rule)
for resourceKind := range resourceTypesInRule {
resourceTypesMap[resourceKind] = true
@ -120,7 +120,7 @@ func GetResourcesWithTest(fs billy.Filesystem, policies []*v1.ClusterPolicy, res
var resourceTypesMap = make(map[string]bool)
var resourceTypes []string
for _, policy := range policies {
for _, rule := range policy.Spec.Rules {
for _, rule := range policy.Spec.GetRules() {
for _, kind := range rule.MatchResources.Kinds {
resourceTypesMap[kind] = true
}

View file

@ -786,7 +786,7 @@ func applyPoliciesFromPath(fs billy.Filesystem, policyBytes []byte, isGit bool,
for _, p := range filteredPolicies {
var filteredRules = []v1.Rule{}
for _, rule := range p.Spec.Rules {
for _, rule := range p.Spec.GetRules() {
for _, res := range values.Results {
if rule.Name == res.Rule {
filteredRules = append(filteredRules, rule)
@ -794,7 +794,7 @@ func applyPoliciesFromPath(fs billy.Filesystem, policyBytes []byte, isGit bool,
}
}
}
p.Spec.Rules = filteredRules
p.Spec.SetRules(filteredRules)
}
policies = filteredPolicies

View file

@ -73,7 +73,7 @@ func (pc PromConfig) AddPolicy(policy interface{}) error {
policyName := inputPolicy.ObjectMeta.Name
ready := inputPolicy.Status.Ready
// registering the metrics on a per-rule basis
for _, rule := range inputPolicy.Spec.Rules {
for _, rule := range inputPolicy.Spec.GetRules() {
ruleName := rule.Name
ruleType := metrics.ParseRuleType(rule)
@ -93,7 +93,7 @@ func (pc PromConfig) AddPolicy(policy interface{}) error {
policyName := inputPolicy.ObjectMeta.Name
ready := inputPolicy.Status.Ready
// registering the metrics on a per-rule basis
for _, rule := range inputPolicy.Spec.Rules {
for _, rule := range inputPolicy.Spec.GetRules() {
ruleName := rule.Name
ruleType := metrics.ParseRuleType(rule)
@ -110,7 +110,7 @@ func (pc PromConfig) AddPolicy(policy interface{}) error {
func (pc PromConfig) RemovePolicy(policy interface{}) error {
switch inputPolicy := policy.(type) {
case *kyverno.ClusterPolicy:
for _, rule := range inputPolicy.Spec.Rules {
for _, rule := range inputPolicy.Spec.GetRules() {
policyValidationMode, err := metrics.ParsePolicyValidationMode(inputPolicy.Spec.ValidationFailureAction)
if err != nil {
return err
@ -129,7 +129,7 @@ func (pc PromConfig) RemovePolicy(policy interface{}) error {
}
return nil
case *kyverno.Policy:
for _, rule := range inputPolicy.Spec.Rules {
for _, rule := range inputPolicy.Spec.GetRules() {
policyValidationMode, err := metrics.ParsePolicyValidationMode(inputPolicy.Spec.ValidationFailureAction)
if err != nil {
return err

View file

@ -138,7 +138,7 @@ func (o *Controller) ValidateResource(patchedResource unstructured.Unstructured,
// ValidatePolicyMutation ...
func (o *Controller) ValidatePolicyMutation(policy v1.ClusterPolicy) error {
var kindToRules = make(map[string][]v1.Rule)
for _, rule := range policy.Spec.Rules {
for _, rule := range policy.Spec.GetRules() {
if rule.HasMutate() {
for _, kind := range rule.MatchResources.Kinds {
kindToRules[kind] = append(kindToRules[common.GetFormatedKind(kind)], rule)
@ -148,7 +148,7 @@ func (o *Controller) ValidatePolicyMutation(policy v1.ClusterPolicy) error {
for kind, rules := range kindToRules {
newPolicy := *policy.DeepCopy()
newPolicy.Spec.Rules = rules
newPolicy.Spec.SetRules(rules)
k := o.gvkToDefinitionName.GetKind(kind)
resource, _ := o.generateEmptyResource(o.definitions.GetSchema(k)).(map[string]interface{})
if resource == nil || len(resource) == 0 {

View file

@ -19,9 +19,9 @@ func containsUserVariables(policy *kyverno.ClusterPolicy, vars [][]string) error
return fmt.Errorf("variable %s is not allowed", s[0])
}
}
for idx := range policy.Spec.Rules {
if err := hasUserMatchExclude(idx, &policy.Spec.Rules[idx]); err != nil {
rules := policy.Spec.GetRules()
for idx := range rules {
if err := hasUserMatchExclude(idx, &rules[idx]); err != nil {
return err
}
}

View file

@ -23,7 +23,7 @@ func (pc *PolicyController) processExistingResources(policy *kyverno.ClusterPoli
// Parse through all the resources drops the cache after configured rebuild time
pc.rm.Drop()
for _, rule := range policy.Spec.Rules {
for _, rule := range policy.Spec.GetRules() {
if !rule.HasValidate() && !rule.HasVerifyImages() {
continue
}

View file

@ -269,7 +269,7 @@ func (pc *PolicyController) deletePolicy(obj interface{}) {
// we process policies that are not set of background processing
// as we need to clean up GRs when a policy is deleted
// skip generate policies with clone
rules := p.Spec.Rules
rules := p.Spec.GetRules()
generatePolicyWithClone := pkgCommon.ProcessDeletePolicyForCloneGenerateRule(rules, pc.client, p.GetName(), logger)
@ -375,11 +375,11 @@ func (pc *PolicyController) deleteNsPolicy(obj interface{}) {
func (pc *PolicyController) enqueueRCRDeletedRule(old, cur *kyverno.ClusterPolicy) {
curRule := make(map[string]bool)
for _, rule := range cur.Spec.Rules {
for _, rule := range cur.Spec.GetRules() {
curRule[rule.Name] = true
}
for _, rule := range old.Spec.Rules {
for _, rule := range old.Spec.GetRules() {
if !curRule[rule.Name] {
pc.prGenerator.Add(policyreport.Info{
PolicyName: cur.GetName(),
@ -564,7 +564,7 @@ func missingAutoGenRules(policy *kyverno.ClusterPolicy, log logr.Logger) bool {
var podRuleName []string
ruleCount := 1
if canApplyAutoGen, _ := autogen.CanAutoGen(&policy.Spec, log); canApplyAutoGen {
for _, rule := range policy.Spec.Rules {
for _, rule := range policy.Spec.GetRules() {
podRuleName = append(podRuleName, rule.Name)
}
}
@ -591,7 +591,7 @@ func missingAutoGenRules(policy *kyverno.ClusterPolicy, log logr.Logger) bool {
}
}
if len(policy.Spec.Rules) != (ruleCount * len(podRuleName)) {
if len(policy.Spec.GetRules()) != (ruleCount * len(podRuleName)) {
return true
}
}

View file

@ -128,8 +128,8 @@ func Validate(policy *kyverno.ClusterPolicy, client *dclient.Client, mock bool,
clusterResources = append(clusterResources, k)
}
}
for i, rule := range policy.Spec.Rules {
rules := policy.Spec.GetRules()
for i, rule := range rules {
//check for forward slash
if err := validateJSONPatchPathForForwardSlash(rule.Mutation.PatchesJSON6902); err != nil {
return fmt.Errorf("path must begin with a forward slash: spec.rules[%d]: %s", i, err)
@ -173,7 +173,7 @@ func Validate(policy *kyverno.ClusterPolicy, client *dclient.Client, mock bool,
// - Mutate
// - Validate
// - Generate
if err := validateActions(i, &policy.Spec.Rules[i], client, mock); err != nil {
if err := validateActions(i, &rules[i], client, mock); err != nil {
return err
}
@ -373,7 +373,7 @@ func ValidateVariables(p *kyverno.ClusterPolicy, backgroundMode bool) error {
// hasInvalidVariables - checks for unexpected variables in the policy
func hasInvalidVariables(policy *kyverno.ClusterPolicy, background bool) error {
for _, r := range policy.Spec.Rules {
for _, r := range policy.Spec.GetRules() {
ruleCopy := r.DeepCopy()
if err := ruleForbiddenSectionsHaveVariables(ruleCopy); err != nil {
@ -1074,7 +1074,7 @@ func validateConditionValuesKeyRequestOperation(c kyverno.Condition) (string, er
func validateUniqueRuleName(p kyverno.ClusterPolicy) (string, error) {
var ruleNames []string
for i, rule := range p.Spec.Rules {
for i, rule := range p.Spec.GetRules() {
if utils.ContainsString(ruleNames, rule.Name) {
return fmt.Sprintf("rule[%d]", i), fmt.Errorf(`duplicate rule name: '%s'`, rule.Name)
}

View file

@ -85,7 +85,7 @@ func Test_Validate_RuleType_EmptyRule(t *testing.T) {
err := json.Unmarshal(rawPolicy, &policy)
assert.NilError(t, err)
for _, rule := range policy.Spec.Rules {
for _, rule := range policy.Spec.GetRules() {
err := validateRuleType(rule)
assert.Assert(t, err != nil)
}
@ -160,7 +160,7 @@ func Test_Validate_RuleType_MultipleRule(t *testing.T) {
err := json.Unmarshal(rawPolicy, &policy)
assert.NilError(t, err)
for _, rule := range policy.Spec.Rules {
for _, rule := range policy.Spec.GetRules() {
err := validateRuleType(rule)
assert.Assert(t, err != nil)
}
@ -215,7 +215,7 @@ func Test_Validate_RuleType_SingleRule(t *testing.T) {
err := json.Unmarshal(rawPolicy, &policy)
assert.NilError(t, err)
for _, rule := range policy.Spec.Rules {
for _, rule := range policy.Spec.GetRules() {
err := validateRuleType(rule)
assert.NilError(t, err)
}

View file

@ -124,7 +124,7 @@ func (m *pMap) add(policy *kyverno.ClusterPolicy) {
pName = pSpace + "/" + pName
}
for _, rule := range policy.Spec.Rules {
for _, rule := range policy.Spec.GetRules() {
if len(rule.MatchResources.Any) > 0 {
for _, rmr := range rule.MatchResources.Any {
@ -230,8 +230,7 @@ func (m *pMap) remove(policy *kyverno.ClusterPolicy) {
pName = pSpace + "/" + pName
}
for _, rule := range policy.Spec.Rules {
for _, rule := range policy.Spec.GetRules() {
if len(rule.MatchResources.Any) > 0 {
for _, rmr := range rule.MatchResources.Any {
removeCacheHelper(rmr, m, pName)

View file

@ -49,7 +49,7 @@ func Test_All(t *testing.T) {
policy := newPolicy(t)
//add
pCache.Add(policy)
for _, rule := range policy.Spec.Rules {
for _, rule := range policy.Spec.GetRules() {
for _, kind := range rule.MatchResources.Kinds {
// get
@ -82,7 +82,7 @@ func Test_Add_Duplicate_Policy(t *testing.T) {
pCache.Add(policy)
pCache.Add(policy)
pCache.Add(policy)
for _, rule := range policy.Spec.Rules {
for _, rule := range policy.Spec.GetRules() {
for _, kind := range rule.MatchResources.Kinds {
mutate := pCache.get(Mutate, kind, "")
@ -111,7 +111,7 @@ func Test_Add_Validate_Audit(t *testing.T) {
policy.Spec.ValidationFailureAction = "audit"
pCache.Add(policy)
pCache.Add(policy)
for _, rule := range policy.Spec.Rules {
for _, rule := range policy.Spec.GetRules() {
for _, kind := range rule.MatchResources.Kinds {
validateEnforce := pCache.get(ValidateEnforce, kind, "")
@ -930,7 +930,7 @@ func Test_Ns_All(t *testing.T) {
//add
pCache.Add(policy)
nspace := policy.GetNamespace()
for _, rule := range policy.Spec.Rules {
for _, rule := range policy.Spec.GetRules() {
for _, kind := range rule.MatchResources.Kinds {
// get
@ -963,7 +963,7 @@ func Test_Ns_Add_Duplicate_Policy(t *testing.T) {
pCache.Add(policy)
pCache.Add(policy)
nspace := policy.GetNamespace()
for _, rule := range policy.Spec.Rules {
for _, rule := range policy.Spec.GetRules() {
for _, kind := range rule.MatchResources.Kinds {
mutate := pCache.get(Mutate, kind, nspace)
@ -992,7 +992,7 @@ func Test_Ns_Add_Validate_Audit(t *testing.T) {
policy.Spec.ValidationFailureAction = "audit"
pCache.Add(policy)
pCache.Add(policy)
for _, rule := range policy.Spec.Rules {
for _, rule := range policy.Spec.GetRules() {
for _, kind := range rule.MatchResources.Kinds {
validateEnforce := pCache.get(ValidateEnforce, kind, nspace)
@ -1031,7 +1031,7 @@ func Test_GVk_Cache(t *testing.T) {
policy := newGVKPolicy(t)
//add
pCache.Add(policy)
for _, rule := range policy.Spec.Rules {
for _, rule := range policy.Spec.GetRules() {
for _, kind := range rule.MatchResources.Kinds {
generate := pCache.get(Generate, kind, "")
@ -1065,7 +1065,7 @@ func Test_Add_Validate_Enforce(t *testing.T) {
nspace := policy.GetNamespace()
//add
pCache.Add(policy)
for _, rule := range policy.Spec.Rules {
for _, rule := range policy.Spec.GetRules() {
for _, kind := range rule.MatchResources.Kinds {
validateEnforce := pCache.get(ValidateEnforce, kind, nspace)
if len(validateEnforce) != 1 {
@ -1100,7 +1100,7 @@ func Test_Mutate_Policy(t *testing.T) {
pCache.Add(policy)
pCache.Add(policy)
pCache.Add(policy)
for _, rule := range policy.Spec.Rules {
for _, rule := range policy.Spec.GetRules() {
for _, kind := range rule.MatchResources.Kinds {
// get
@ -1117,7 +1117,7 @@ func Test_Generate_Policy(t *testing.T) {
policy := newgenratePolicy(t)
//add
pCache.Add(policy)
for _, rule := range policy.Spec.Rules {
for _, rule := range policy.Spec.GetRules() {
for _, kind := range rule.MatchResources.Kinds {
// get

View file

@ -65,7 +65,7 @@ func GenerateJSONPatchesForDefaults(policy *kyverno.ClusterPolicy, log logr.Logg
func checkForGVKFormatPatch(policy *kyverno.ClusterPolicy, log logr.Logger) (patches [][]byte, errs []error) {
patches = make([][]byte, 0)
for i, rule := range policy.Spec.Rules {
for i, rule := range policy.Spec.GetRules() {
patchByte, err := convertGVKForKinds(fmt.Sprintf("/spec/rules/%s/match/resources/kinds", strconv.Itoa(i)), rule.MatchResources.Kinds, log)
if err == nil && patchByte != nil {
patches = append(patches, patchByte)

View file

@ -31,18 +31,19 @@ func JoinPatches(patches [][]byte) []byte {
// TODO This needs to be removed. A simpler way to encode and decode Policy is needed.
func MarshalPolicy(policy v1.ClusterPolicy) []byte {
var rules []interface{}
rulesRaw, _ := json.Marshal(policy.Spec.Rules)
policyRules := policy.Spec.GetRules()
rulesRaw, _ := json.Marshal(policyRules)
_ = json.Unmarshal(rulesRaw, &rules)
for i, r := range rules {
rule, _ := r.(map[string]interface{})
if reflect.DeepEqual(policy.Spec.Rules[i].Mutation, v1.Mutation{}) {
if reflect.DeepEqual(policyRules[i].Mutation, v1.Mutation{}) {
delete(rule, "mutate")
}
if reflect.DeepEqual(policy.Spec.Rules[i].Validation, v1.Validation{}) {
if reflect.DeepEqual(policyRules[i].Validation, v1.Validation{}) {
delete(rule, "validate")
}
if reflect.DeepEqual(policy.Spec.Rules[i].Generation, v1.Generation{}) {
if reflect.DeepEqual(policyRules[i].Generation, v1.Generation{}) {
delete(rule, "generate")
}

View file

@ -692,7 +692,7 @@ func (m *webhookConfigManager) updateStatus(policy *kyverno.ClusterPolicy, statu
// mergeWebhook merges the matching kinds of the policy to webhook.rule
func (m *webhookConfigManager) mergeWebhook(dst *webhook, policy *kyverno.ClusterPolicy, updateValidate bool) {
matchedGVK := make([]string, 0)
for _, rule := range policy.Spec.Rules {
for _, rule := range policy.Spec.GetRules() {
// matching kinds in generate policies need to be added to both webhook
if rule.HasGenerate() {
matchedGVK = append(matchedGVK, rule.MatchKinds()...)
@ -803,7 +803,7 @@ func webhookKey(webhookKind, failurePolicy string) string {
func hasWildcard(policy interface{}) bool {
if p, ok := policy.(*kyverno.ClusterPolicy); ok {
for _, rule := range p.Spec.Rules {
for _, rule := range p.Spec.GetRules() {
if kinds := rule.MatchKinds(); utils.ContainsString(kinds, "*") {
return true
}
@ -811,7 +811,7 @@ func hasWildcard(policy interface{}) bool {
}
if p, ok := policy.(*kyverno.Policy); ok {
for _, rule := range p.Spec.Rules {
for _, rule := range p.Spec.GetRules() {
if kinds := rule.MatchKinds(); utils.ContainsString(kinds, "*") {
return true
}

View file

@ -143,7 +143,7 @@ func processResourceWithPatches(patch []byte, resource []byte, log logr.Logger)
func containsRBACInfo(policies ...[]*kyverno.ClusterPolicy) bool {
for _, policySlice := range policies {
for _, policy := range policySlice {
for _, rule := range policy.Spec.Rules {
for _, rule := range policy.Spec.GetRules() {
if checkForRBACInfo(rule) {
return true
}

View file

@ -234,7 +234,7 @@ func (ws *WebhookServer) handleUpdateGenerateTargetResource(request *v1beta1.Adm
return
}
for _, rule := range policy.Spec.Rules {
for _, rule := range policy.Spec.GetRules() {
if rule.Generation.Kind == targetSourceKind && rule.Generation.Name == targetSourceName {
updatedRule, err := getGeneratedByResource(newRes, resLabels, ws.client, rule, logger)
if err != nil {