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

feat: move GetRules() at the policy level (#3420)

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

Co-authored-by: shuting <shuting@nirmata.com>
This commit is contained in:
Charles-Edouard Brétéché 2022-03-18 16:18:32 +01:00 committed by GitHub
parent 30261b5235
commit 0c8e8c1212
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
33 changed files with 78 additions and 67 deletions

View file

@ -30,6 +30,11 @@ type ClusterPolicy struct {
Status PolicyStatus `json:"status,omitempty" yaml:"status,omitempty"` Status PolicyStatus `json:"status,omitempty" yaml:"status,omitempty"`
} }
// GetRules returns the policy rules
func (p *ClusterPolicy) GetRules() []Rule {
return p.Spec.GetRules()
}
// HasAutoGenAnnotation checks if a policy has auto-gen annotation // HasAutoGenAnnotation checks if a policy has auto-gen annotation
func (p *ClusterPolicy) HasAutoGenAnnotation() bool { func (p *ClusterPolicy) HasAutoGenAnnotation() bool {
annotations := p.GetAnnotations() annotations := p.GetAnnotations()

View file

@ -31,6 +31,11 @@ type Policy struct {
Status PolicyStatus `json:"status,omitempty" yaml:"status,omitempty"` Status PolicyStatus `json:"status,omitempty" yaml:"status,omitempty"`
} }
// GetRules returns the policy rules
func (p *Policy) GetRules() []Rule {
return p.Spec.GetRules()
}
// HasAutoGenAnnotation checks if a policy has auto-gen annotation // HasAutoGenAnnotation checks if a policy has auto-gen annotation
func (p *Policy) HasAutoGenAnnotation() bool { func (p *Policy) HasAutoGenAnnotation() bool {
annotations := p.GetAnnotations() annotations := p.GetAnnotations()

View file

@ -88,7 +88,7 @@ func Test_Validate_RuleType_MultipleRule(t *testing.T) {
var policy *ClusterPolicy var policy *ClusterPolicy
err := json.Unmarshal(rawPolicy, &policy) err := json.Unmarshal(rawPolicy, &policy)
assert.NilError(t, err) assert.NilError(t, err)
for _, rule := range policy.Spec.GetRules() { for _, rule := range policy.GetRules() {
path := field.NewPath("dummy") path := field.NewPath("dummy")
errs := rule.Validate(path) errs := rule.Validate(path)
assert.Assert(t, len(errs) != 0) assert.Assert(t, len(errs) != 0)
@ -143,7 +143,7 @@ func Test_Validate_RuleType_SingleRule(t *testing.T) {
var policy *ClusterPolicy var policy *ClusterPolicy
err := json.Unmarshal(rawPolicy, &policy) err := json.Unmarshal(rawPolicy, &policy)
assert.NilError(t, err) assert.NilError(t, err)
for _, rule := range policy.Spec.GetRules() { for _, rule := range policy.GetRules() {
path := field.NewPath("dummy") path := field.NewPath("dummy")
errs := rule.Validate(path) errs := rule.Validate(path)
assert.Assert(t, len(errs) == 0) assert.Assert(t, len(errs) == 0)

View file

@ -48,6 +48,7 @@ type Spec struct {
WebhookTimeoutSeconds *int32 `json:"webhookTimeoutSeconds,omitempty" yaml:"webhookTimeoutSeconds,omitempty"` WebhookTimeoutSeconds *int32 `json:"webhookTimeoutSeconds,omitempty" yaml:"webhookTimeoutSeconds,omitempty"`
} }
// GetRules returns the spec rules
func (s *Spec) GetRules() []Rule { func (s *Spec) GetRules() []Rule {
return s.Rules return s.Rules
} }

View file

@ -30,7 +30,7 @@ const (
// - otherwise it returns all pod controllers // - otherwise it returns all pod controllers
func CanAutoGen(spec *kyverno.Spec, log logr.Logger) (applyAutoGen bool, controllers string) { func CanAutoGen(spec *kyverno.Spec, log logr.Logger) (applyAutoGen bool, controllers string) {
var needAutogen bool var needAutogen bool
rules := spec.GetRules() rules := spec.Rules
for _, rule := range rules { for _, rule := range rules {
match := rule.MatchResources match := rule.MatchResources
exclude := rule.ExcludeResources exclude := rule.ExcludeResources
@ -166,7 +166,7 @@ func GetControllers(meta metav1.ObjectMeta, spec *kyverno.Spec, log logr.Logger)
// GenerateRulePatches generates rule for podControllers based on scenario A and C // 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) { func GenerateRulePatches(spec *kyverno.Spec, controllers string, log logr.Logger) (rulePatches [][]byte, errs []error) {
rules := spec.GetRules() rules := spec.Rules
insertIdx := len(rules) insertIdx := len(rules)
ruleMap := createRuleMap(rules) ruleMap := createRuleMap(rules)

View file

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

View file

@ -94,7 +94,7 @@ func AddCloneLabel(client *dclient.Client, pInformer kyvernoinformer.ClusterPoli
} }
for _, policy := range policies { for _, policy := range policies {
for _, rule := range policy.Spec.GetRules() { for _, rule := range policy.GetRules() {
if rule.HasGenerate() { if rule.HasGenerate() {
clone := rule.Generation.Clone clone := rule.Generation.Clone
if clone.Name != "" { 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()) "namespace", resource.GetNamespace(), "name", resource.GetName())
patchedResource := resource patchedResource := resource
for _, rule := range policy.Spec.GetRules() { for _, rule := range policy.GetRules() {
if !rule.HasMutate() { if !rule.HasMutate() {
continue continue
} }

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -141,7 +141,7 @@ func (c *Controller) deletePolicy(obj interface{}) {
// clean up the GR // clean up the GR
// Get the corresponding GR // Get the corresponding GR
// get the list of GR for the current Policy version // get the list of GR for the current Policy version
rules := p.Spec.GetRules() rules := p.GetRules()
generatePolicyWithClone := pkgCommon.ProcessDeletePolicyForCloneGenerateRule(rules, c.client, p.GetName(), logger) 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 // 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) ruleNameToProcessingTime := make(map[string]time.Duration)
for _, rule := range policy.Spec.GetRules() { for _, rule := range policy.GetRules() {
var err error var err error
if !rule.HasGenerate() { if !rule.HasGenerate() {
continue continue

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -138,7 +138,7 @@ func (o *Controller) ValidateResource(patchedResource unstructured.Unstructured,
// ValidatePolicyMutation ... // ValidatePolicyMutation ...
func (o *Controller) ValidatePolicyMutation(policy v1.ClusterPolicy) error { func (o *Controller) ValidatePolicyMutation(policy v1.ClusterPolicy) error {
var kindToRules = make(map[string][]v1.Rule) var kindToRules = make(map[string][]v1.Rule)
for _, rule := range policy.Spec.GetRules() { for _, rule := range policy.GetRules() {
if rule.HasMutate() { if rule.HasMutate() {
for _, kind := range rule.MatchResources.Kinds { for _, kind := range rule.MatchResources.Kinds {
kindToRules[kind] = append(kindToRules[common.GetFormatedKind(kind)], rule) kindToRules[kind] = append(kindToRules[common.GetFormatedKind(kind)], rule)

View file

@ -19,7 +19,7 @@ func containsUserVariables(policy *kyverno.ClusterPolicy, vars [][]string) error
return fmt.Errorf("variable %s is not allowed", s[0]) return fmt.Errorf("variable %s is not allowed", s[0])
} }
} }
rules := policy.Spec.GetRules() rules := policy.GetRules()
for idx := range rules { for idx := range rules {
if err := hasUserMatchExclude(idx, &rules[idx]); err != nil { if err := hasUserMatchExclude(idx, &rules[idx]); err != nil {
return err 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 // Parse through all the resources drops the cache after configured rebuild time
pc.rm.Drop() pc.rm.Drop()
for _, rule := range policy.Spec.GetRules() { for _, rule := range policy.GetRules() {
if !rule.HasValidate() && !rule.HasVerifyImages() { if !rule.HasValidate() && !rule.HasVerifyImages() {
continue continue
} }

View file

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

View file

@ -127,7 +127,7 @@ func Validate(policy *kyverno.ClusterPolicy, client *dclient.Client, mock bool,
clusterResources = append(clusterResources, k) clusterResources = append(clusterResources, k)
} }
} }
rules := policy.Spec.GetRules() rules := policy.GetRules()
rulesPath := specPath.Child("rules") rulesPath := specPath.Child("rules")
for i, rule := range rules { for i, rule := range rules {
rulePath := rulesPath.Index(i) rulePath := rulesPath.Index(i)
@ -385,7 +385,7 @@ func ValidateVariables(p *kyverno.ClusterPolicy, backgroundMode bool) error {
// hasInvalidVariables - checks for unexpected variables in the policy // hasInvalidVariables - checks for unexpected variables in the policy
func hasInvalidVariables(policy *kyverno.ClusterPolicy, background bool) error { func hasInvalidVariables(policy *kyverno.ClusterPolicy, background bool) error {
for _, r := range policy.Spec.GetRules() { for _, r := range policy.GetRules() {
ruleCopy := r.DeepCopy() ruleCopy := r.DeepCopy()
if err := ruleForbiddenSectionsHaveVariables(ruleCopy); err != nil { if err := ruleForbiddenSectionsHaveVariables(ruleCopy); err != nil {

View file

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

View file

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

View file

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

View file

@ -31,7 +31,7 @@ func JoinPatches(patches [][]byte) []byte {
// TODO This needs to be removed. A simpler way to encode and decode Policy is needed. // TODO This needs to be removed. A simpler way to encode and decode Policy is needed.
func MarshalPolicy(policy v1.ClusterPolicy) []byte { func MarshalPolicy(policy v1.ClusterPolicy) []byte {
var rules []interface{} var rules []interface{}
policyRules := policy.Spec.GetRules() policyRules := policy.GetRules()
rulesRaw, _ := json.Marshal(policyRules) rulesRaw, _ := json.Marshal(policyRules)
_ = json.Unmarshal(rulesRaw, &rules) _ = json.Unmarshal(rulesRaw, &rules)
for i, r := range rules { for i, r := range rules {

View file

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

View file

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

View file

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