diff --git a/api/kyverno/v1/spec_types.go b/api/kyverno/v1/spec_types.go index f215a82eaae8..e89dec66425f 100644 --- a/api/kyverno/v1/spec_types.go +++ b/api/kyverno/v1/spec_types.go @@ -48,10 +48,10 @@ type Spec struct { // ValidationFailureAction defines if a validation policy rule violation should block // the admission review request (enforce), or allow (audit) the admission review request // and report an error in a policy report. Optional. - // Allowed values are audit or enforce. The default value is "audit". + // Allowed values are audit or enforce. + // The default value is "" which means policy will be executed in background-only mode. // +optional - // +kubebuilder:validation:Enum=audit;enforce - // +kubebuilder:default=audit + // +kubebuilder:validation:Enum=audit;enforce;"" ValidationFailureAction ValidationFailureAction `json:"validationFailureAction,omitempty" yaml:"validationFailureAction,omitempty"` // ValidationFailureActionOverrides is a Cluster Policy attribute that specifies ValidationFailureAction diff --git a/api/kyverno/v2beta1/spec_types.go b/api/kyverno/v2beta1/spec_types.go index 10e6538be358..c8f4e7c89e99 100644 --- a/api/kyverno/v2beta1/spec_types.go +++ b/api/kyverno/v2beta1/spec_types.go @@ -30,10 +30,10 @@ type Spec struct { // ValidationFailureAction defines if a validation policy rule violation should block // the admission review request (enforce), or allow (audit) the admission review request // and report an error in a policy report. Optional. - // Allowed values are audit or enforce. The default value is "audit". + // Allowed values are audit or enforce. + // The default value is "" which means policy will be executed in background-only mode. // +optional - // +kubebuilder:validation:Enum=audit;enforce - // +kubebuilder:default=audit + // +kubebuilder:validation:Enum=audit;enforce;"" ValidationFailureAction kyvernov1.ValidationFailureAction `json:"validationFailureAction,omitempty" yaml:"validationFailureAction,omitempty"` // ValidationFailureActionOverrides is a Cluster Policy attribute that specifies ValidationFailureAction diff --git a/charts/kyverno/templates/crds.yaml b/charts/kyverno/templates/crds.yaml index f3b554c8e2b3..82d3471a16ea 100644 --- a/charts/kyverno/templates/crds.yaml +++ b/charts/kyverno/templates/crds.yaml @@ -2811,11 +2811,11 @@ spec: description: SchemaValidation skips policy validation checks. Optional. The default value is set to "true", it must be set to "false" to disable the validation checks. type: boolean validationFailureAction: - default: audit - description: ValidationFailureAction defines if a validation policy rule violation should block the admission review request (enforce), or allow (audit) the admission review request and report an error in a policy report. Optional. Allowed values are audit or enforce. The default value is "audit". + description: ValidationFailureAction defines if a validation policy rule violation should block the admission review request (enforce), or allow (audit) the admission review request and report an error in a policy report. Optional. Allowed values are audit or enforce. The default value is "" which means policy will be executed in background-only mode. enum: - audit - enforce + - "" type: string validationFailureActionOverrides: description: ValidationFailureActionOverrides is a Cluster Policy attribute that specifies ValidationFailureAction namespace-wise. It overrides ValidationFailureAction for the specified namespaces. @@ -6294,11 +6294,11 @@ spec: description: SchemaValidation skips policy validation checks. Optional. The default value is set to "true", it must be set to "false" to disable the validation checks. type: boolean validationFailureAction: - default: audit - description: ValidationFailureAction defines if a validation policy rule violation should block the admission review request (enforce), or allow (audit) the admission review request and report an error in a policy report. Optional. Allowed values are audit or enforce. The default value is "audit". + description: ValidationFailureAction defines if a validation policy rule violation should block the admission review request (enforce), or allow (audit) the admission review request and report an error in a policy report. Optional. Allowed values are audit or enforce. The default value is "" which means policy will be executed in background-only mode. enum: - audit - enforce + - "" type: string validationFailureActionOverrides: description: ValidationFailureActionOverrides is a Cluster Policy attribute that specifies ValidationFailureAction namespace-wise. It overrides ValidationFailureAction for the specified namespaces. @@ -10401,11 +10401,11 @@ spec: description: SchemaValidation skips policy validation checks. Optional. The default value is set to "true", it must be set to "false" to disable the validation checks. type: boolean validationFailureAction: - default: audit - description: ValidationFailureAction defines if a validation policy rule violation should block the admission review request (enforce), or allow (audit) the admission review request and report an error in a policy report. Optional. Allowed values are audit or enforce. The default value is "audit". + description: ValidationFailureAction defines if a validation policy rule violation should block the admission review request (enforce), or allow (audit) the admission review request and report an error in a policy report. Optional. Allowed values are audit or enforce. The default value is "" which means policy will be executed in background-only mode. enum: - audit - enforce + - "" type: string validationFailureActionOverrides: description: ValidationFailureActionOverrides is a Cluster Policy attribute that specifies ValidationFailureAction namespace-wise. It overrides ValidationFailureAction for the specified namespaces. @@ -13884,11 +13884,11 @@ spec: description: SchemaValidation skips policy validation checks. Optional. The default value is set to "true", it must be set to "false" to disable the validation checks. type: boolean validationFailureAction: - default: audit - description: ValidationFailureAction defines if a validation policy rule violation should block the admission review request (enforce), or allow (audit) the admission review request and report an error in a policy report. Optional. Allowed values are audit or enforce. The default value is "audit". + description: ValidationFailureAction defines if a validation policy rule violation should block the admission review request (enforce), or allow (audit) the admission review request and report an error in a policy report. Optional. Allowed values are audit or enforce. The default value is "" which means policy will be executed in background-only mode. enum: - audit - enforce + - "" type: string validationFailureActionOverrides: description: ValidationFailureActionOverrides is a Cluster Policy attribute that specifies ValidationFailureAction namespace-wise. It overrides ValidationFailureAction for the specified namespaces. diff --git a/config/crds/kyverno.io_clusterpolicies.yaml b/config/crds/kyverno.io_clusterpolicies.yaml index 49a3910bc4b7..52304ac23fc9 100644 --- a/config/crds/kyverno.io_clusterpolicies.yaml +++ b/config/crds/kyverno.io_clusterpolicies.yaml @@ -2867,15 +2867,16 @@ spec: disable the validation checks. type: boolean validationFailureAction: - default: audit description: ValidationFailureAction defines if a validation policy rule violation should block the admission review request (enforce), or allow (audit) the admission review request and report an error in a policy report. Optional. Allowed values are audit or enforce. - The default value is "audit". + The default value is "" which means policy will be executed in background-only + mode. enum: - audit - enforce + - "" type: string validationFailureActionOverrides: description: ValidationFailureActionOverrides is a Cluster Policy @@ -8449,15 +8450,16 @@ spec: disable the validation checks. type: boolean validationFailureAction: - default: audit description: ValidationFailureAction defines if a validation policy rule violation should block the admission review request (enforce), or allow (audit) the admission review request and report an error in a policy report. Optional. Allowed values are audit or enforce. - The default value is "audit". + The default value is "" which means policy will be executed in background-only + mode. enum: - audit - enforce + - "" type: string validationFailureActionOverrides: description: ValidationFailureActionOverrides is a Cluster Policy diff --git a/config/crds/kyverno.io_policies.yaml b/config/crds/kyverno.io_policies.yaml index 87c05ffd0c80..0ac8289f160d 100644 --- a/config/crds/kyverno.io_policies.yaml +++ b/config/crds/kyverno.io_policies.yaml @@ -2868,15 +2868,16 @@ spec: disable the validation checks. type: boolean validationFailureAction: - default: audit description: ValidationFailureAction defines if a validation policy rule violation should block the admission review request (enforce), or allow (audit) the admission review request and report an error in a policy report. Optional. Allowed values are audit or enforce. - The default value is "audit". + The default value is "" which means policy will be executed in background-only + mode. enum: - audit - enforce + - "" type: string validationFailureActionOverrides: description: ValidationFailureActionOverrides is a Cluster Policy @@ -8452,15 +8453,16 @@ spec: disable the validation checks. type: boolean validationFailureAction: - default: audit description: ValidationFailureAction defines if a validation policy rule violation should block the admission review request (enforce), or allow (audit) the admission review request and report an error in a policy report. Optional. Allowed values are audit or enforce. - The default value is "audit". + The default value is "" which means policy will be executed in background-only + mode. enum: - audit - enforce + - "" type: string validationFailureActionOverrides: description: ValidationFailureActionOverrides is a Cluster Policy diff --git a/config/install.yaml b/config/install.yaml index 1019c0d5d0d5..cc4d477dc895 100644 --- a/config/install.yaml +++ b/config/install.yaml @@ -4189,15 +4189,16 @@ spec: disable the validation checks. type: boolean validationFailureAction: - default: audit description: ValidationFailureAction defines if a validation policy rule violation should block the admission review request (enforce), or allow (audit) the admission review request and report an error in a policy report. Optional. Allowed values are audit or enforce. - The default value is "audit". + The default value is "" which means policy will be executed in background-only + mode. enum: - audit - enforce + - "" type: string validationFailureActionOverrides: description: ValidationFailureActionOverrides is a Cluster Policy @@ -9771,15 +9772,16 @@ spec: disable the validation checks. type: boolean validationFailureAction: - default: audit description: ValidationFailureAction defines if a validation policy rule violation should block the admission review request (enforce), or allow (audit) the admission review request and report an error in a policy report. Optional. Allowed values are audit or enforce. - The default value is "audit". + The default value is "" which means policy will be executed in background-only + mode. enum: - audit - enforce + - "" type: string validationFailureActionOverrides: description: ValidationFailureActionOverrides is a Cluster Policy @@ -16210,15 +16212,16 @@ spec: disable the validation checks. type: boolean validationFailureAction: - default: audit description: ValidationFailureAction defines if a validation policy rule violation should block the admission review request (enforce), or allow (audit) the admission review request and report an error in a policy report. Optional. Allowed values are audit or enforce. - The default value is "audit". + The default value is "" which means policy will be executed in background-only + mode. enum: - audit - enforce + - "" type: string validationFailureActionOverrides: description: ValidationFailureActionOverrides is a Cluster Policy @@ -21794,15 +21797,16 @@ spec: disable the validation checks. type: boolean validationFailureAction: - default: audit description: ValidationFailureAction defines if a validation policy rule violation should block the admission review request (enforce), or allow (audit) the admission review request and report an error in a policy report. Optional. Allowed values are audit or enforce. - The default value is "audit". + The default value is "" which means policy will be executed in background-only + mode. enum: - audit - enforce + - "" type: string validationFailureActionOverrides: description: ValidationFailureActionOverrides is a Cluster Policy diff --git a/config/install_debug.yaml b/config/install_debug.yaml index 2e5b788140ee..5db6699f6c4b 100644 --- a/config/install_debug.yaml +++ b/config/install_debug.yaml @@ -4183,15 +4183,16 @@ spec: disable the validation checks. type: boolean validationFailureAction: - default: audit description: ValidationFailureAction defines if a validation policy rule violation should block the admission review request (enforce), or allow (audit) the admission review request and report an error in a policy report. Optional. Allowed values are audit or enforce. - The default value is "audit". + The default value is "" which means policy will be executed in background-only + mode. enum: - audit - enforce + - "" type: string validationFailureActionOverrides: description: ValidationFailureActionOverrides is a Cluster Policy @@ -9765,15 +9766,16 @@ spec: disable the validation checks. type: boolean validationFailureAction: - default: audit description: ValidationFailureAction defines if a validation policy rule violation should block the admission review request (enforce), or allow (audit) the admission review request and report an error in a policy report. Optional. Allowed values are audit or enforce. - The default value is "audit". + The default value is "" which means policy will be executed in background-only + mode. enum: - audit - enforce + - "" type: string validationFailureActionOverrides: description: ValidationFailureActionOverrides is a Cluster Policy @@ -16201,15 +16203,16 @@ spec: disable the validation checks. type: boolean validationFailureAction: - default: audit description: ValidationFailureAction defines if a validation policy rule violation should block the admission review request (enforce), or allow (audit) the admission review request and report an error in a policy report. Optional. Allowed values are audit or enforce. - The default value is "audit". + The default value is "" which means policy will be executed in background-only + mode. enum: - audit - enforce + - "" type: string validationFailureActionOverrides: description: ValidationFailureActionOverrides is a Cluster Policy @@ -21785,15 +21788,16 @@ spec: disable the validation checks. type: boolean validationFailureAction: - default: audit description: ValidationFailureAction defines if a validation policy rule violation should block the admission review request (enforce), or allow (audit) the admission review request and report an error in a policy report. Optional. Allowed values are audit or enforce. - The default value is "audit". + The default value is "" which means policy will be executed in background-only + mode. enum: - audit - enforce + - "" type: string validationFailureActionOverrides: description: ValidationFailureActionOverrides is a Cluster Policy diff --git a/docs/user/crd/index.html b/docs/user/crd/index.html index 79e951e4c10d..48db048e8f04 100644 --- a/docs/user/crd/index.html +++ b/docs/user/crd/index.html @@ -164,7 +164,8 @@

ClusterPolicy

ValidationFailureAction defines if a validation policy rule violation should block the admission review request (enforce), or allow (audit) the admission review request and report an error in a policy report. Optional. -Allowed values are audit or enforce. The default value is “audit”.

+Allowed values are audit or enforce. +The default value is “” which means policy will be executed in background-only mode.

@@ -505,7 +506,8 @@

Policy

ValidationFailureAction defines if a validation policy rule violation should block the admission review request (enforce), or allow (audit) the admission review request and report an error in a policy report. Optional. -Allowed values are audit or enforce. The default value is “audit”.

+Allowed values are audit or enforce. +The default value is “” which means policy will be executed in background-only mode.

@@ -3356,7 +3358,8 @@

Spec

ValidationFailureAction defines if a validation policy rule violation should block the admission review request (enforce), or allow (audit) the admission review request and report an error in a policy report. Optional. -Allowed values are audit or enforce. The default value is “audit”.

+Allowed values are audit or enforce. +The default value is “” which means policy will be executed in background-only mode.

@@ -4973,7 +4976,8 @@

ClusterPolicy

ValidationFailureAction defines if a validation policy rule violation should block the admission review request (enforce), or allow (audit) the admission review request and report an error in a policy report. Optional. -Allowed values are audit or enforce. The default value is “audit”.

+Allowed values are audit or enforce. +The default value is “” which means policy will be executed in background-only mode.

@@ -5198,7 +5202,8 @@

Policy

ValidationFailureAction defines if a validation policy rule violation should block the admission review request (enforce), or allow (audit) the admission review request and report an error in a policy report. Optional. -Allowed values are audit or enforce. The default value is “audit”.

+Allowed values are audit or enforce. +The default value is “” which means policy will be executed in background-only mode.

@@ -6025,7 +6030,8 @@

Spec

ValidationFailureAction defines if a validation policy rule violation should block the admission review request (enforce), or allow (audit) the admission review request and report an error in a policy report. Optional. -Allowed values are audit or enforce. The default value is “audit”.

+Allowed values are audit or enforce. +The default value is “” which means policy will be executed in background-only mode.

diff --git a/pkg/client/clientset/versioned/fake/register.go b/pkg/client/clientset/versioned/fake/register.go index cf3c1a08f422..a93604b6d11a 100644 --- a/pkg/client/clientset/versioned/fake/register.go +++ b/pkg/client/clientset/versioned/fake/register.go @@ -43,14 +43,14 @@ var localSchemeBuilder = runtime.SchemeBuilder{ // AddToScheme adds all types of this clientset into the given scheme. This allows composition // of clientsets, like in: // -// import ( -// "k8s.io/client-go/kubernetes" -// clientsetscheme "k8s.io/client-go/kubernetes/scheme" -// aggregatorclientsetscheme "k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset/scheme" -// ) +// import ( +// "k8s.io/client-go/kubernetes" +// clientsetscheme "k8s.io/client-go/kubernetes/scheme" +// aggregatorclientsetscheme "k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset/scheme" +// ) // -// kclientset, _ := kubernetes.NewForConfig(c) -// _ = aggregatorclientsetscheme.AddToScheme(clientsetscheme.Scheme) +// kclientset, _ := kubernetes.NewForConfig(c) +// _ = aggregatorclientsetscheme.AddToScheme(clientsetscheme.Scheme) // // After this, RawExtensions in Kubernetes types will serialize kube-aggregator types // correctly. diff --git a/pkg/client/clientset/versioned/scheme/register.go b/pkg/client/clientset/versioned/scheme/register.go index 776190e3523e..9fbeaa98f0d3 100644 --- a/pkg/client/clientset/versioned/scheme/register.go +++ b/pkg/client/clientset/versioned/scheme/register.go @@ -43,14 +43,14 @@ var localSchemeBuilder = runtime.SchemeBuilder{ // AddToScheme adds all types of this clientset into the given scheme. This allows composition // of clientsets, like in: // -// import ( -// "k8s.io/client-go/kubernetes" -// clientsetscheme "k8s.io/client-go/kubernetes/scheme" -// aggregatorclientsetscheme "k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset/scheme" -// ) +// import ( +// "k8s.io/client-go/kubernetes" +// clientsetscheme "k8s.io/client-go/kubernetes/scheme" +// aggregatorclientsetscheme "k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset/scheme" +// ) // -// kclientset, _ := kubernetes.NewForConfig(c) -// _ = aggregatorclientsetscheme.AddToScheme(clientsetscheme.Scheme) +// kclientset, _ := kubernetes.NewForConfig(c) +// _ = aggregatorclientsetscheme.AddToScheme(clientsetscheme.Scheme) // // After this, RawExtensions in Kubernetes types will serialize kube-aggregator types // correctly. diff --git a/pkg/policy/validate.go b/pkg/policy/validate.go index a14f771ddf4b..1ac8a4360565 100644 --- a/pkg/policy/validate.go +++ b/pkg/policy/validate.go @@ -109,12 +109,31 @@ func validateJSONPatch(patch string, ruleIdx int) error { return nil } +func validateBackgroundOnlyMode(policy kyvernov1.PolicyInterface) error { + validate := policy.GetSpec().ValidationFailureAction + background := policy.GetSpec().BackgroundProcessingEnabled() + if !background { + for _, rule := range policy.GetSpec().Rules { + if validate == "" && (rule.HasValidate() || rule.HasVerifyImages()) { + return fmt.Errorf("%s", "Invalid policy. When background is false ValidationFailureAction must be set to either audit or enforce") + } + } + } + return nil +} + // Validate checks the policy and rules declarations for required configurations func Validate(policy kyvernov1.PolicyInterface, client dclient.Interface, mock bool, openApiManager openapi.Manager) (*admissionv1.AdmissionResponse, error) { namespaced := policy.IsNamespaced() spec := policy.GetSpec() background := spec.BackgroundProcessingEnabled() onPolicyUpdate := spec.GetMutateExistingOnPolicyUpdate() + + err := validateBackgroundOnlyMode(policy) + if err != nil { + return nil, err + } + if !mock { openapicontroller.NewController(client, openApiManager).CheckSync(context.TODO()) } @@ -122,7 +141,7 @@ func Validate(policy kyvernov1.PolicyInterface, client dclient.Interface, mock b var errs field.ErrorList specPath := field.NewPath("spec") - err := ValidateVariables(policy, background) + err = ValidateVariables(policy, background) if err != nil { return nil, err } diff --git a/pkg/policy/validate_test.go b/pkg/policy/validate_test.go index e5587e2ebe88..015f1bddb4e9 100644 --- a/pkg/policy/validate_test.go +++ b/pkg/policy/validate_test.go @@ -2061,3 +2061,62 @@ func Test_ValidateNamespace(t *testing.T) { }) } } + +func Test_Validate_BackgroundOnlyMode_Policy(t *testing.T) { + invalidBackgroundModePolicy := `{ + "apiVersion": "kyverno.io/v1", + "kind": "ClusterPolicy", + "metadata": { + "name": "check-label-app" + }, + "spec": { + "background": false, + "validationFailureAction": "", + "rules": [ + { + "name": "check-label-app", + "match": { + "resources": { + "kinds": [ + "Pod" + ] + } + }, + "validate": { + "message": "The label 'app' is required.", + "pattern": { + "metadata": { + "labels": { + "app": "?*" + } + } + } + } + } + ] + } + } + ` + var inValidPolicy *kyverno.ClusterPolicy + err := json.Unmarshal([]byte(invalidBackgroundModePolicy), &inValidPolicy) + assert.NilError(t, err) + openApiManager, _ := openapi.NewManager() + // vlidate invalid policy + _, err = Validate(inValidPolicy, nil, true, openApiManager) + assert.Error(t, err, "Invalid policy. When background is false ValidationFailureAction must be set to either audit or enforce") + validPolicy := inValidPolicy.DeepCopy() + // validate background-only mode policy + background := true + validPolicy.Spec.Background = &background + _, err = Validate(validPolicy, nil, true, openApiManager) + assert.NilError(t, err) + // validate background mode policy + validPolicy.Spec.ValidationFailureAction = kyverno.Audit + _, err = Validate(validPolicy, nil, true, openApiManager) + assert.NilError(t, err) + // validate non background mode policy + background = false + validPolicy.Spec.Background = &background + _, err = Validate(validPolicy, nil, true, openApiManager) + assert.NilError(t, err) +} diff --git a/pkg/webhooks/resource/handlers.go b/pkg/webhooks/resource/handlers.go index daf7970d9d6c..b0068ebc444b 100644 --- a/pkg/webhooks/resource/handlers.go +++ b/pkg/webhooks/resource/handlers.go @@ -101,10 +101,10 @@ func (h *handlers) Validate(logger logr.Logger, request *admissionv1.AdmissionRe logger.V(4).Info("received an admission request in validating webhook") // timestamp at which this admission request got triggered - policies := filterPolicies(failurePolicy, h.pCache.GetPolicies(policycache.ValidateEnforce, kind, request.Namespace)...) - mutatePolicies := filterPolicies(failurePolicy, h.pCache.GetPolicies(policycache.Mutate, kind, request.Namespace)...) - generatePolicies := filterPolicies(failurePolicy, h.pCache.GetPolicies(policycache.Generate, kind, request.Namespace)...) - imageVerifyValidatePolicies := filterPolicies(failurePolicy, h.pCache.GetPolicies(policycache.VerifyImagesValidate, kind, request.Namespace)...) + policies := filterPolicies(failurePolicy, true, h.pCache.GetPolicies(policycache.ValidateEnforce, kind, request.Namespace)...) + mutatePolicies := filterPolicies(failurePolicy, false, h.pCache.GetPolicies(policycache.Mutate, kind, request.Namespace)...) + generatePolicies := filterPolicies(failurePolicy, false, h.pCache.GetPolicies(policycache.Generate, kind, request.Namespace)...) + imageVerifyValidatePolicies := filterPolicies(failurePolicy, true, h.pCache.GetPolicies(policycache.VerifyImagesValidate, kind, request.Namespace)...) policies = append(policies, imageVerifyValidatePolicies...) if len(policies) == 0 && len(mutatePolicies) == 0 && len(generatePolicies) == 0 { @@ -157,8 +157,8 @@ func (h *handlers) Mutate(logger logr.Logger, request *admissionv1.AdmissionRequ kind := request.Kind.Kind logger = logger.WithValues("kind", kind) logger.V(4).Info("received an admission request in mutating webhook") - mutatePolicies := filterPolicies(failurePolicy, h.pCache.GetPolicies(policycache.Mutate, kind, request.Namespace)...) - verifyImagesPolicies := filterPolicies(failurePolicy, h.pCache.GetPolicies(policycache.VerifyImagesMutate, kind, request.Namespace)...) + mutatePolicies := filterPolicies(failurePolicy, false, h.pCache.GetPolicies(policycache.Mutate, kind, request.Namespace)...) + verifyImagesPolicies := filterPolicies(failurePolicy, true, h.pCache.GetPolicies(policycache.VerifyImagesMutate, kind, request.Namespace)...) if len(mutatePolicies) == 0 && len(verifyImagesPolicies) == 0 { logger.V(4).Info("no policies matched mutate admission request") return admissionutils.ResponseSuccess() @@ -227,9 +227,13 @@ func (h *handlers) handleDelete(logger logr.Logger, request *admissionv1.Admissi } } -func filterPolicies(failurePolicy string, policies ...kyvernov1.PolicyInterface) []kyvernov1.PolicyInterface { +func filterPolicies(failurePolicy string, filterBackgroundOnlyPolicies bool, policies ...kyvernov1.PolicyInterface) []kyvernov1.PolicyInterface { var results []kyvernov1.PolicyInterface for _, policy := range policies { + // exlude background-only policies + if filterBackgroundOnlyPolicies && policy.BackgroundProcessingEnabled() && policy.GetSpec().ValidationFailureAction == "" { + continue + } if failurePolicy == "fail" { if policy.GetSpec().GetFailurePolicy() == kyvernov1.Fail { results = append(results, policy) diff --git a/pkg/webhooks/resource/handlers_test.go b/pkg/webhooks/resource/handlers_test.go index dc6330dadcdc..65c8016652e3 100644 --- a/pkg/webhooks/resource/handlers_test.go +++ b/pkg/webhooks/resource/handlers_test.go @@ -419,3 +419,56 @@ func makeKey(policy kyverno.PolicyInterface) string { return namespace + "/" + name } + +func Test_Filter_BackgroundOnly_Policies(t *testing.T) { + tests := []struct { + policy kyverno.ClusterPolicy + result int + filterBackgroundOnlyPolicies bool + background bool + ValidationFailureAction kyverno.ValidationFailureAction + }{ + { // background only mode + do filter + ValidationFailureAction: "", + filterBackgroundOnlyPolicies: true, + background: true, + result: 0, + }, + { // background only mode + no filter + ValidationFailureAction: "", + filterBackgroundOnlyPolicies: false, + background: true, + result: 1, + }, + { // background mode + Audit mode + do filter + ValidationFailureAction: kyverno.Audit, + filterBackgroundOnlyPolicies: true, + background: true, + result: 1, + }, + { // background mode + Audit mode + no filter + ValidationFailureAction: kyverno.Audit, + result: 1, + filterBackgroundOnlyPolicies: false, + background: true, + }, + { // no background mode + Audit mode + do filter + ValidationFailureAction: kyverno.Audit, + result: 1, + filterBackgroundOnlyPolicies: true, + background: false, + }, + { // no background mode + Audit mode + no filter + ValidationFailureAction: kyverno.Audit, + result: 1, + filterBackgroundOnlyPolicies: false, + background: false, + }, + } + for _, test := range tests { + test.policy.Spec.ValidationFailureAction = test.ValidationFailureAction + test.policy.Spec.Background = &test.background + result := filterPolicies("", test.filterBackgroundOnlyPolicies, &test.policy) + assert.Equal(t, len(result), test.result) + } +}