1
0
Fork 0
mirror of https://github.com/kyverno/kyverno.git synced 2025-03-31 03:45:17 +00:00

refactor: make use of policy interface (#3499)

- refactor: make use of policy interface

Signed-off-by: Charles-Edouard Brétéché <charled.breteche@gmail.com>
This commit is contained in:
Charles-Edouard Brétéché 2022-03-30 15:04:30 +02:00 committed by GitHub
parent 1fce53f49d
commit 83343697b9
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
28 changed files with 125 additions and 125 deletions

View file

@ -14,13 +14,14 @@ import (
// ForceMutate does not check any conditions, it simply mutates the given resource
// It is used to validate mutation logic, and for tests.
func ForceMutate(ctx *context.Context, policy kyverno.ClusterPolicy, resource unstructured.Unstructured) (unstructured.Unstructured, error) {
logger := log.Log.WithName("EngineForceMutate").WithValues("policy", policy.Name, "kind", resource.GetKind(),
func ForceMutate(ctx *context.Context, policy kyverno.PolicyInterface, resource unstructured.Unstructured) (unstructured.Unstructured, error) {
logger := log.Log.WithName("EngineForceMutate").WithValues("policy", policy.GetName(), "kind", resource.GetKind(),
"namespace", resource.GetNamespace(), "name", resource.GetName())
patchedResource := resource
// TODO: if we apply autogen, tests will fail
for _, rule := range policy.Spec.Rules {
spec := policy.GetSpec()
for _, rule := range spec.Rules {
if !rule.HasMutate() {
continue
}

View file

@ -103,7 +103,7 @@ func Test_ForceMutateSubstituteVars(t *testing.T) {
err = ctx.AddResource(rawResource)
assert.NilError(t, err)
mutatedResource, err := ForceMutate(ctx, policy, *resourceUnstructured)
mutatedResource, err := ForceMutate(ctx, &policy, *resourceUnstructured)
assert.NilError(t, err)
assert.DeepEqual(t, expectedResource, mutatedResource.UnstructuredContent())
@ -208,7 +208,7 @@ func Test_ForceMutateSubstituteVarsWithPatchesJson6902(t *testing.T) {
err = ctx.AddResource(rawResource)
assert.NilError(t, err)
mutatedResource, err := ForceMutate(ctx, policy, *resourceUnstructured)
mutatedResource, err := ForceMutate(ctx, &policy, *resourceUnstructured)
assert.NilError(t, err)
assert.DeepEqual(t, expectedResource.UnstructuredContent(), mutatedResource.UnstructuredContent())
@ -294,7 +294,7 @@ func Test_ForceMutateSubstituteVarsWithPatchStrategicMerge(t *testing.T) {
err = ctx.AddResource(rawResource)
assert.NilError(t, err)
mutatedResource, err := ForceMutate(ctx, policy, *resourceUnstructured)
mutatedResource, err := ForceMutate(ctx, &policy, *resourceUnstructured)
assert.NilError(t, err)
assert.DeepEqual(t, expectedResource, mutatedResource.UnstructuredContent())

View file

@ -61,7 +61,7 @@ func filterGenerateRules(policyContext *PolicyContext, policyNameKey string, sta
return resp
}
for _, rule := range autogen.ComputeRules(&policyContext.Policy) {
for _, rule := range autogen.ComputeRules(policyContext.Policy) {
if ruleResp := filterRule(rule, policyContext); ruleResp != nil {
resp.PolicyResponse.Rules = append(resp.PolicyResponse.Rules, *ruleResp)
}
@ -98,7 +98,7 @@ func filterRules(policyContext *PolicyContext, startTime time.Time) *response.En
return resp
}
for _, rule := range autogen.ComputeRules(&policyContext.Policy) {
for _, rule := range autogen.ComputeRules(policyContext.Policy) {
if ruleResp := filterRule(rule, policyContext); ruleResp != nil {
resp.PolicyResponse.Rules = append(resp.PolicyResponse.Rules, *ruleResp)
}
@ -123,7 +123,7 @@ func filterRule(rule kyverno.Rule, policyContext *PolicyContext) *response.RuleR
excludeGroupRole := policyContext.ExcludeGroupRole
namespaceLabels := policyContext.NamespaceLabels
logger := log.Log.WithName("Generate").WithValues("policy", policy.Name,
logger := log.Log.WithName("Generate").WithValues("policy", policy.GetName(),
"kind", newResource.GetKind(), "namespace", newResource.GetNamespace(), "name", newResource.GetName())
if err = MatchesResourceDescription(newResource, rule, admissionInfo, excludeGroupRole, namespaceLabels, ""); err != nil {

View file

@ -29,7 +29,7 @@ func VerifyAndPatchImages(policyContext *PolicyContext) (resp *response.EngineRe
policy := policyContext.Policy
patchedResource := policyContext.NewResource
logger := log.Log.WithName("EngineVerifyImages").WithValues("policy", policy.Name,
logger := log.Log.WithName("EngineVerifyImages").WithValues("policy", policy.GetName(),
"kind", patchedResource.GetKind(), "namespace", patchedResource.GetNamespace(), "name", patchedResource.GetName())
startTime := time.Now()
@ -49,7 +49,7 @@ func VerifyAndPatchImages(policyContext *PolicyContext) (resp *response.EngineRe
}
}
rules := autogen.ComputeRules(&policyContext.Policy)
rules := autogen.ComputeRules(policyContext.Policy)
for i := range rules {
rule := &rules[i]
if len(rule.VerifyImages) == 0 {

View file

@ -170,7 +170,7 @@ func buildContext(t *testing.T, policy, resource string) *PolicyContext {
}
policyContext := &PolicyContext{
Policy: cpol,
Policy: &cpol,
JSONContext: ctx,
NewResource: *resourceUnstructured}

View file

@ -22,7 +22,7 @@ func LoadContext(logger logr.Logger, contextEntries []kyverno.ContextEntry, ctx
return nil
}
policyName := ctx.Policy.Name
policyName := ctx.Policy.GetName()
if store.GetMock() {
if store.GetRegistryAccess() {
for _, entry := range contextEntries {

View file

@ -25,7 +25,7 @@ func Mutate(policyContext *PolicyContext) (resp *response.EngineResponse) {
ctx := policyContext.JSONContext
var skippedRules []string
logger := log.Log.WithName("EngineMutate").WithValues("policy", policy.Name, "kind", patchedResource.GetKind(),
logger := log.Log.WithName("EngineMutate").WithValues("policy", policy.GetName(), "kind", patchedResource.GetKind(),
"namespace", patchedResource.GetNamespace(), "skippedRules", patchedResource.GetName())
logger.V(4).Info("start policy processing", "startTime", startTime)
@ -38,7 +38,7 @@ func Mutate(policyContext *PolicyContext) (resp *response.EngineResponse) {
var err error
for _, rule := range autogen.ComputeRules(&policy) {
for _, rule := range autogen.ComputeRules(policy) {
if !rule.HasMutate() {
continue
}
@ -49,7 +49,7 @@ func Mutate(policyContext *PolicyContext) (resp *response.EngineResponse) {
excludeResource = policyContext.ExcludeGroupRole
}
if err = MatchesResourceDescription(patchedResource, rule, policyContext.AdmissionInfo, excludeResource, policyContext.NamespaceLabels, policyContext.Policy.Namespace); err != nil {
if err = MatchesResourceDescription(patchedResource, rule, policyContext.AdmissionInfo, excludeResource, policyContext.NamespaceLabels, policyContext.Policy.GetNamespace()); err != nil {
logger.V(4).Info("rule not matched", "reason", err.Error())
skippedRules = append(skippedRules, rule.Name)
continue
@ -259,7 +259,7 @@ func buildSuccessMessage(r unstructured.Unstructured) string {
return fmt.Sprintf("mutated %s/%s in namespace %s", r.GetKind(), r.GetName(), r.GetNamespace())
}
func startMutateResultResponse(resp *response.EngineResponse, policy kyverno.ClusterPolicy, resource unstructured.Unstructured) {
func startMutateResultResponse(resp *response.EngineResponse, policy kyverno.PolicyInterface, resource unstructured.Unstructured) {
if resp == nil {
return
}

View file

@ -86,7 +86,7 @@ func Test_VariableSubstitutionPatchStrategicMerge(t *testing.T) {
t.Error(err)
}
policyContext := &PolicyContext{
Policy: policy,
Policy: &policy,
JSONContext: ctx,
NewResource: *resourceUnstructured}
er := Mutate(policyContext)
@ -159,7 +159,7 @@ func Test_variableSubstitutionPathNotExist(t *testing.T) {
assert.NilError(t, err)
policyContext := &PolicyContext{
Policy: policy,
Policy: &policy,
JSONContext: ctx,
NewResource: *resourceUnstructured}
er := Mutate(policyContext)
@ -254,7 +254,7 @@ func Test_variableSubstitutionCLI(t *testing.T) {
assert.NilError(t, err)
policyContext := &PolicyContext{
Policy: policy,
Policy: &policy,
JSONContext: ctx,
NewResource: *resourceUnstructured,
}
@ -357,7 +357,7 @@ func Test_chained_rules(t *testing.T) {
assert.NilError(t, err)
policyContext := &PolicyContext{
Policy: policy,
Policy: &policy,
JSONContext: ctx,
NewResource: *resource,
}
@ -451,7 +451,7 @@ func Test_precondition(t *testing.T) {
assert.NilError(t, err)
policyContext := &PolicyContext{
Policy: policy,
Policy: &policy,
JSONContext: ctx,
NewResource: *resourceUnstructured,
}
@ -548,7 +548,7 @@ func Test_nonZeroIndexNumberPatchesJson6902(t *testing.T) {
assert.NilError(t, err)
policyContext := &PolicyContext{
Policy: policy,
Policy: &policy,
JSONContext: ctx,
NewResource: *resourceUnstructured,
}
@ -636,7 +636,7 @@ func Test_foreach(t *testing.T) {
assert.NilError(t, err)
policyContext := &PolicyContext{
Policy: policy,
Policy: &policy,
JSONContext: ctx,
NewResource: *resource,
}
@ -743,7 +743,7 @@ func Test_foreach_element_mutation(t *testing.T) {
assert.NilError(t, err)
policyContext := &PolicyContext{
Policy: policy,
Policy: &policy,
JSONContext: ctx,
NewResource: *resource,
}
@ -869,7 +869,7 @@ func Test_Container_InitContainer_foreach(t *testing.T) {
assert.NilError(t, err)
policyContext := &PolicyContext{
Policy: policy,
Policy: &policy,
JSONContext: ctx,
NewResource: *resource,
}
@ -996,7 +996,7 @@ func Test_foreach_order_mutation_(t *testing.T) {
assert.NilError(t, err)
policyContext := &PolicyContext{
Policy: policy,
Policy: &policy,
JSONContext: ctx,
NewResource: *resource,
}

View file

@ -9,9 +9,8 @@ import (
// PolicyContext contains the contexts for engine to process
type PolicyContext struct {
// Policy is the policy to be processed
Policy kyverno.ClusterPolicy
Policy kyverno.PolicyInterface
// NewResource is the resource to be processed
NewResource unstructured.Unstructured

View file

@ -14,7 +14,7 @@ type EngineResponse struct {
PatchedResource unstructured.Unstructured
// Original policy
Policy *kyverno.ClusterPolicy
Policy kyverno.PolicyInterface
// Policy Response
PolicyResponse PolicyResponse

View file

@ -427,7 +427,7 @@ func excludeResource(podControllers string, resource unstructured.Unstructured)
// ManagedPodResource returns true:
// - if the policy has auto-gen annotation && resource == Pod
// - if the auto-gen contains cronJob && resource == Job
func ManagedPodResource(policy kyverno.ClusterPolicy, resource unstructured.Unstructured) bool {
func ManagedPodResource(policy kyverno.PolicyInterface, resource unstructured.Unstructured) bool {
podControllers, ok := policy.GetAnnotations()[kyverno.PodControllersAnnotation]
if !ok || strings.ToLower(podControllers) == "none" {
return false

View file

@ -1445,7 +1445,7 @@ func TestManagedPodResource(t *testing.T) {
assert.Assert(t, err == nil, "Test %d/%s invalid policy raw: %v", i+1, tc.name, err)
resource, _ := utils.ConvertToUnstructured(tc.resource)
res := ManagedPodResource(policy, *resource)
res := ManagedPodResource(&policy, *resource)
assert.Equal(t, res, tc.expectedResult, "test %d/%s failed, expect %v, got %v", i+1, tc.name, tc.expectedResult, res)
}
}

View file

@ -40,7 +40,7 @@ func Validate(policyContext *PolicyContext) (resp *response.EngineResponse) {
}
func buildLogger(ctx *PolicyContext) logr.Logger {
logger := log.Log.WithName("EngineValidate").WithValues("policy", ctx.Policy.Name)
logger := log.Log.WithName("EngineValidate").WithValues("policy", ctx.Policy.GetName())
if reflect.DeepEqual(ctx.NewResource, unstructured.Unstructured{}) {
logger = logger.WithValues("kind", ctx.OldResource.GetKind(), "namespace", ctx.OldResource.GetNamespace(), "name", ctx.OldResource.GetName())
} else {
@ -65,16 +65,16 @@ func buildResponse(ctx *PolicyContext, resp *response.EngineResponse, startTime
resp.PatchedResource = resource
}
resp.Policy = &ctx.Policy
resp.Policy = ctx.Policy
resp.PolicyResponse.Policy.Name = ctx.Policy.GetName()
resp.PolicyResponse.Policy.Namespace = ctx.Policy.GetNamespace()
resp.PolicyResponse.Resource.Name = resp.PatchedResource.GetName()
resp.PolicyResponse.Resource.Namespace = resp.PatchedResource.GetNamespace()
resp.PolicyResponse.Resource.Kind = resp.PatchedResource.GetKind()
resp.PolicyResponse.Resource.APIVersion = resp.PatchedResource.GetAPIVersion()
resp.PolicyResponse.ValidationFailureAction = ctx.Policy.Spec.ValidationFailureAction
resp.PolicyResponse.ValidationFailureAction = ctx.Policy.GetSpec().ValidationFailureAction
for _, v := range ctx.Policy.Spec.ValidationFailureActionOverrides {
for _, v := range ctx.Policy.GetSpec().ValidationFailureActionOverrides {
resp.PolicyResponse.ValidationFailureActionOverrides = append(resp.PolicyResponse.ValidationFailureActionOverrides, response.ValidationFailureActionOverride{Action: v.Action, Namespaces: v.Namespaces})
}
@ -88,7 +88,7 @@ func validateResource(log logr.Logger, ctx *PolicyContext) *response.EngineRespo
ctx.JSONContext.Checkpoint()
defer ctx.JSONContext.Restore()
rules := autogen.ComputeRules(&ctx.Policy)
rules := autogen.ComputeRules(ctx.Policy)
for i := range rules {
rule := &rules[i]
if !rule.HasValidate() {

View file

@ -131,7 +131,7 @@ func TestValidate_image_tag_fail(t *testing.T) {
"validation error: imagePullPolicy 'Always' required with tag 'latest'. Rule validate-latest failed at path /spec/containers/0/imagePullPolicy/",
}
er := Validate(&PolicyContext{Policy: policy, NewResource: *resourceUnstructured, JSONContext: context.NewContext()})
er := Validate(&PolicyContext{Policy: &policy, NewResource: *resourceUnstructured, JSONContext: context.NewContext()})
for index, r := range er.PolicyResponse.Rules {
assert.Equal(t, r.Message, msgs[index])
}
@ -231,7 +231,7 @@ func TestValidate_image_tag_pass(t *testing.T) {
"validation rule 'validate-tag' passed.",
"validation rule 'validate-latest' passed.",
}
er := Validate(&PolicyContext{Policy: policy, NewResource: *resourceUnstructured, JSONContext: context.NewContext()})
er := Validate(&PolicyContext{Policy: &policy, NewResource: *resourceUnstructured, JSONContext: context.NewContext()})
for index, r := range er.PolicyResponse.Rules {
assert.Equal(t, r.Message, msgs[index])
}
@ -305,7 +305,7 @@ func TestValidate_Fail_anyPattern(t *testing.T) {
resourceUnstructured, err := utils.ConvertToUnstructured(rawResource)
assert.NilError(t, err)
er := Validate(&PolicyContext{Policy: policy, NewResource: *resourceUnstructured, JSONContext: context.NewContext()})
er := Validate(&PolicyContext{Policy: &policy, NewResource: *resourceUnstructured, JSONContext: context.NewContext()})
assert.Assert(t, !er.IsSuccessful())
msgs := []string{"validation error: A namespace is required. Rule check-default-namespace[0] failed at path /metadata/namespace/. Rule check-default-namespace[1] failed at path /metadata/namespace/."}
@ -388,7 +388,7 @@ func TestValidate_host_network_port(t *testing.T) {
resourceUnstructured, err := utils.ConvertToUnstructured(rawResource)
assert.NilError(t, err)
er := Validate(&PolicyContext{Policy: policy, NewResource: *resourceUnstructured, JSONContext: context.NewContext()})
er := Validate(&PolicyContext{Policy: &policy, NewResource: *resourceUnstructured, JSONContext: context.NewContext()})
msgs := []string{"validation error: Host network and port are not allowed. Rule validate-host-network-port failed at path /spec/containers/0/ports/0/hostPort/"}
for index, r := range er.PolicyResponse.Rules {
@ -478,7 +478,7 @@ func TestValidate_anchor_arraymap_pass(t *testing.T) {
resourceUnstructured, err := utils.ConvertToUnstructured(rawResource)
assert.NilError(t, err)
er := Validate(&PolicyContext{Policy: policy, NewResource: *resourceUnstructured, JSONContext: context.NewContext()})
er := Validate(&PolicyContext{Policy: &policy, NewResource: *resourceUnstructured, JSONContext: context.NewContext()})
msgs := []string{"validation rule 'validate-host-path' passed."}
for index, r := range er.PolicyResponse.Rules {
@ -566,7 +566,7 @@ func TestValidate_anchor_arraymap_fail(t *testing.T) {
assert.NilError(t, err)
resourceUnstructured, err := utils.ConvertToUnstructured(rawResource)
assert.NilError(t, err)
er := Validate(&PolicyContext{Policy: policy, NewResource: *resourceUnstructured, JSONContext: context.NewContext()})
er := Validate(&PolicyContext{Policy: &policy, NewResource: *resourceUnstructured, JSONContext: context.NewContext()})
msgs := []string{"validation error: Host path '/var/lib/' is not allowed. Rule validate-host-path failed at path /spec/volumes/0/hostPath/path/"}
for index, r := range er.PolicyResponse.Rules {
@ -636,7 +636,7 @@ func TestValidate_anchor_map_notfound(t *testing.T) {
resourceUnstructured, err := utils.ConvertToUnstructured(rawResource)
assert.NilError(t, err)
er := Validate(&PolicyContext{Policy: policy, NewResource: *resourceUnstructured, JSONContext: context.NewContext()})
er := Validate(&PolicyContext{Policy: &policy, NewResource: *resourceUnstructured, JSONContext: context.NewContext()})
msgs := []string{"validation rule 'pod rule 2' passed."}
for index, r := range er.PolicyResponse.Rules {
@ -709,7 +709,7 @@ func TestValidate_anchor_map_found_valid(t *testing.T) {
resourceUnstructured, err := utils.ConvertToUnstructured(rawResource)
assert.NilError(t, err)
er := Validate(&PolicyContext{Policy: policy, NewResource: *resourceUnstructured, JSONContext: context.NewContext()})
er := Validate(&PolicyContext{Policy: &policy, NewResource: *resourceUnstructured, JSONContext: context.NewContext()})
msgs := []string{"validation rule 'pod rule 2' passed."}
for index, r := range er.PolicyResponse.Rules {
@ -783,7 +783,7 @@ func TestValidate_inequality_List_Processing(t *testing.T) {
resourceUnstructured, err := utils.ConvertToUnstructured(rawResource)
assert.NilError(t, err)
er := Validate(&PolicyContext{Policy: policy, NewResource: *resourceUnstructured, JSONContext: context.NewContext()})
er := Validate(&PolicyContext{Policy: &policy, NewResource: *resourceUnstructured, JSONContext: context.NewContext()})
msgs := []string{"validation rule 'pod rule 2' passed."}
for index, r := range er.PolicyResponse.Rules {
@ -863,7 +863,7 @@ func TestValidate_inequality_List_ProcessingBrackets(t *testing.T) {
resourceUnstructured, err := utils.ConvertToUnstructured(rawResource)
assert.NilError(t, err)
er := Validate(&PolicyContext{Policy: policy, NewResource: *resourceUnstructured, JSONContext: context.NewContext()})
er := Validate(&PolicyContext{Policy: &policy, NewResource: *resourceUnstructured, JSONContext: context.NewContext()})
msgs := []string{"validation rule 'pod rule 2' passed."}
for index, r := range er.PolicyResponse.Rules {
@ -937,7 +937,7 @@ func TestValidate_anchor_map_found_invalid(t *testing.T) {
resourceUnstructured, err := utils.ConvertToUnstructured(rawResource)
assert.NilError(t, err)
er := Validate(&PolicyContext{Policy: policy, NewResource: *resourceUnstructured, JSONContext: context.NewContext()})
er := Validate(&PolicyContext{Policy: &policy, NewResource: *resourceUnstructured, JSONContext: context.NewContext()})
msgs := []string{"validation error: pod: validate run as non root user. Rule pod rule 2 failed at path /spec/securityContext/runAsNonRoot/"}
for index, r := range er.PolicyResponse.Rules {
@ -1012,7 +1012,7 @@ func TestValidate_AnchorList_pass(t *testing.T) {
resourceUnstructured, err := utils.ConvertToUnstructured(rawResource)
assert.NilError(t, err)
er := Validate(&PolicyContext{Policy: policy, NewResource: *resourceUnstructured, JSONContext: context.NewContext()})
er := Validate(&PolicyContext{Policy: &policy, NewResource: *resourceUnstructured, JSONContext: context.NewContext()})
msgs := []string{"validation rule 'pod image rule' passed."}
for index, r := range er.PolicyResponse.Rules {
@ -1087,7 +1087,7 @@ func TestValidate_AnchorList_fail(t *testing.T) {
resourceUnstructured, err := utils.ConvertToUnstructured(rawResource)
assert.NilError(t, err)
er := Validate(&PolicyContext{Policy: policy, NewResource: *resourceUnstructured, JSONContext: context.NewContext()})
er := Validate(&PolicyContext{Policy: &policy, NewResource: *resourceUnstructured, JSONContext: context.NewContext()})
assert.Assert(t, !er.IsSuccessful())
}
@ -1157,7 +1157,7 @@ func TestValidate_existenceAnchor_fail(t *testing.T) {
resourceUnstructured, err := utils.ConvertToUnstructured(rawResource)
assert.NilError(t, err)
er := Validate(&PolicyContext{Policy: policy, NewResource: *resourceUnstructured, JSONContext: context.NewContext()})
er := Validate(&PolicyContext{Policy: &policy, NewResource: *resourceUnstructured, JSONContext: context.NewContext()})
assert.Assert(t, !er.IsSuccessful())
}
@ -1227,7 +1227,7 @@ func TestValidate_existenceAnchor_pass(t *testing.T) {
resourceUnstructured, err := utils.ConvertToUnstructured(rawResource)
assert.NilError(t, err)
er := Validate(&PolicyContext{Policy: policy, NewResource: *resourceUnstructured, JSONContext: context.NewContext()})
er := Validate(&PolicyContext{Policy: &policy, NewResource: *resourceUnstructured, JSONContext: context.NewContext()})
msgs := []string{"validation rule 'pod image rule' passed."}
for index, r := range er.PolicyResponse.Rules {
@ -1315,7 +1315,7 @@ func TestValidate_negationAnchor_deny(t *testing.T) {
resourceUnstructured, err := utils.ConvertToUnstructured(rawResource)
assert.NilError(t, err)
er := Validate(&PolicyContext{Policy: policy, NewResource: *resourceUnstructured, JSONContext: context.NewContext()})
er := Validate(&PolicyContext{Policy: &policy, NewResource: *resourceUnstructured, JSONContext: context.NewContext()})
msgs := []string{"validation error: Host path is not allowed. Rule validate-host-path failed at path /spec/volumes/0/hostPath/"}
for index, r := range er.PolicyResponse.Rules {
@ -1402,7 +1402,7 @@ func TestValidate_negationAnchor_pass(t *testing.T) {
resourceUnstructured, err := utils.ConvertToUnstructured(rawResource)
assert.NilError(t, err)
er := Validate(&PolicyContext{Policy: policy, NewResource: *resourceUnstructured, JSONContext: context.NewContext()})
er := Validate(&PolicyContext{Policy: &policy, NewResource: *resourceUnstructured, JSONContext: context.NewContext()})
msgs := []string{"validation rule 'validate-host-path' passed."}
for index, r := range er.PolicyResponse.Rules {
@ -1475,7 +1475,7 @@ func Test_VariableSubstitutionPathNotExistInPattern(t *testing.T) {
assert.NilError(t, err)
policyContext := &PolicyContext{
Policy: policy,
Policy: &policy,
JSONContext: ctx,
NewResource: *resourceUnstructured}
er := Validate(policyContext)
@ -1568,7 +1568,7 @@ func Test_VariableSubstitutionPathNotExistInAnyPattern_OnePatternStatisfiesButSu
assert.NilError(t, err)
policyContext := &PolicyContext{
Policy: policy,
Policy: &policy,
JSONContext: ctx,
NewResource: *resourceUnstructured}
er := Validate(policyContext)
@ -1629,7 +1629,7 @@ func Test_VariableSubstitution_NotOperatorWithStringVariable(t *testing.T) {
assert.NilError(t, err)
policyContext := &PolicyContext{
Policy: policy,
Policy: &policy,
JSONContext: ctx,
NewResource: *resourceUnstructured}
er := Validate(policyContext)
@ -1720,7 +1720,7 @@ func Test_VariableSubstitutionPathNotExistInAnyPattern_AllPathNotPresent(t *test
assert.NilError(t, err)
policyContext := &PolicyContext{
Policy: policy,
Policy: &policy,
JSONContext: ctx,
NewResource: *resourceUnstructured}
er := Validate(policyContext)
@ -1813,7 +1813,7 @@ func Test_VariableSubstitutionPathNotExistInAnyPattern_AllPathPresent_NonePatter
assert.NilError(t, err)
policyContext := &PolicyContext{
Policy: policy,
Policy: &policy,
JSONContext: ctx,
NewResource: *resourceUnstructured}
er := Validate(policyContext)
@ -1918,7 +1918,7 @@ func Test_VariableSubstitutionValidate_VariablesInMessageAreResolved(t *testing.
assert.NilError(t, err)
policyContext := &PolicyContext{
Policy: policy,
Policy: &policy,
JSONContext: ctx,
NewResource: *resourceUnstructured}
er := Validate(policyContext)
@ -1971,7 +1971,7 @@ func Test_Flux_Kustomization_PathNotPresent(t *testing.T) {
assert.NilError(t, err)
policyContext := &PolicyContext{
Policy: policy,
Policy: &policy,
JSONContext: ctx,
NewResource: *resourceUnstructured}
er := Validate(policyContext)
@ -2138,7 +2138,7 @@ func executeTest(t *testing.T, err error, test testCase) {
}
pc := &PolicyContext{
Policy: policy,
Policy: &policy,
NewResource: newR,
OldResource: oldR,
AdmissionInfo: userInfo,
@ -2244,7 +2244,7 @@ func TestValidate_context_variable_substitution_CLI(t *testing.T) {
msgs := []string{
"restrict pod counts to be no more than 10 on node minikube",
}
er := Validate(&PolicyContext{Policy: policy, NewResource: *resourceUnstructured, JSONContext: context.NewContext()})
er := Validate(&PolicyContext{Policy: &policy, NewResource: *resourceUnstructured, JSONContext: context.NewContext()})
for index, r := range er.PolicyResponse.Rules {
assert.Equal(t, r.Message, msgs[index])
}
@ -2333,7 +2333,7 @@ func Test_EmptyStringInDenyCondition(t *testing.T) {
resourceUnstructured, err := utils.ConvertToUnstructured(resourceRaw)
assert.NilError(t, err)
er := Validate(&PolicyContext{Policy: policy, NewResource: *resourceUnstructured, JSONContext: ctx})
er := Validate(&PolicyContext{Policy: &policy, NewResource: *resourceUnstructured, JSONContext: ctx})
assert.Assert(t, !er.IsSuccessful())
}
@ -2422,7 +2422,7 @@ func Test_StringInDenyCondition(t *testing.T) {
resourceUnstructured, err := utils.ConvertToUnstructured(resourceRaw)
assert.NilError(t, err)
er := Validate(&PolicyContext{Policy: policy, NewResource: *resourceUnstructured, JSONContext: ctx})
er := Validate(&PolicyContext{Policy: &policy, NewResource: *resourceUnstructured, JSONContext: ctx})
assert.Assert(t, er.IsSuccessful())
}
@ -3006,7 +3006,7 @@ func testForEach(t *testing.T, policyraw []byte, resourceRaw []byte, msg string,
assert.NilError(t, err)
policyContext := &PolicyContext{
Policy: policy,
Policy: &policy,
JSONContext: ctx,
NewResource: *resourceUnstructured}
er := Validate(policyContext)
@ -3070,7 +3070,7 @@ func Test_delete_ignore_pattern(t *testing.T) {
assert.NilError(t, err)
policyContextCreate := &PolicyContext{
Policy: policy,
Policy: &policy,
JSONContext: ctx,
NewResource: *resourceUnstructured}
engineResponseCreate := Validate(policyContextCreate)
@ -3078,7 +3078,7 @@ func Test_delete_ignore_pattern(t *testing.T) {
assert.Equal(t, engineResponseCreate.PolicyResponse.Rules[0].Status, response.RuleStatusFail)
policyContextDelete := &PolicyContext{
Policy: policy,
Policy: &policy,
JSONContext: ctx,
OldResource: *resourceUnstructured}
engineResponseDelete := Validate(policyContextDelete)

View file

@ -194,7 +194,7 @@ func (c *Controller) applyGenerate(resource unstructured.Unstructured, gr kyvern
}
policyContext := &engine.PolicyContext{
NewResource: resource,
Policy: policy,
Policy: &policy,
AdmissionInfo: gr.Spec.Context.UserRequestInfo,
ExcludeGroupRole: c.Config.GetExcludeGroupRole(),
ExcludeResourceFunc: c.Config.ToFilter,
@ -287,7 +287,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 autogen.ComputeRules(&policy) {
for _, rule := range autogen.ComputeRules(policy) {
var err error
if !rule.HasGenerate() {
continue
@ -321,9 +321,9 @@ func (c *Controller) applyGeneratePolicy(log logr.Logger, policyContext *engine.
}
if !processExisting {
genResource, err = applyRule(log, c.client, rule, resource, jsonContext, policy.Name, gr)
genResource, err = applyRule(log, c.client, rule, resource, jsonContext, policy.GetName(), gr)
if err != nil {
log.Error(err, "failed to apply generate rule", "policy", policy.Name,
log.Error(err, "failed to apply generate rule", "policy", policy.GetName(),
"rule", rule.Name, "resource", resource.GetName(), "suggestion", "users need to grant Kyverno's service account additional privileges")
return nil, processExisting, err
}

View file

@ -553,7 +553,7 @@ OuterLoop:
if err := context.MutateResourceWithImageInfo(resourceRaw, ctx); err != nil {
log.Log.Error(err, "failed to add image variables to context")
}
mutateResponse := engine.Mutate(&engine.PolicyContext{Policy: *policy, NewResource: *updated_resource, JSONContext: ctx, NamespaceLabels: namespaceLabels})
mutateResponse := engine.Mutate(&engine.PolicyContext{Policy: policy, NewResource: *updated_resource, JSONContext: ctx, NamespaceLabels: namespaceLabels})
if mutateResponse != nil {
engineResponses = append(engineResponses, mutateResponse)
}
@ -583,7 +583,7 @@ OuterLoop:
var info policyreport.Info
var validateResponse *response.EngineResponse
if policyHasValidate {
policyCtx := &engine.PolicyContext{Policy: *policy, NewResource: mutateResponse.PatchedResource, JSONContext: ctx, NamespaceLabels: namespaceLabels}
policyCtx := &engine.PolicyContext{Policy: policy, NewResource: mutateResponse.PatchedResource, JSONContext: ctx, NamespaceLabels: namespaceLabels}
validateResponse = engine.Validate(policyCtx)
info = ProcessValidateEngineResponse(policy, validateResponse, resPath, rc, policyReport)
}
@ -601,7 +601,7 @@ OuterLoop:
if policyHasGenerate {
policyContext := &engine.PolicyContext{
NewResource: *resource,
Policy: *policy,
Policy: policy,
ExcludeGroupRole: []string{},
ExcludeResourceFunc: func(s1, s2, s3 string) bool {
return false

View file

@ -58,14 +58,14 @@ func (pc PromConfig) registerPolicyExecutionDurationMetric(
//policy - policy related data
//engineResponse - resource and rule related data
func (pc PromConfig) ProcessEngineResponse(policy kyverno.ClusterPolicy, engineResponse response.EngineResponse, executionCause metrics.RuleExecutionCause, generateRuleLatencyType string, resourceRequestOperation metrics.ResourceRequestOperation) error {
func (pc PromConfig) ProcessEngineResponse(policy kyverno.PolicyInterface, engineResponse response.EngineResponse, executionCause metrics.RuleExecutionCause, generateRuleLatencyType string, resourceRequestOperation metrics.ResourceRequestOperation) error {
policyValidationMode, err := metrics.ParsePolicyValidationMode(policy.Spec.ValidationFailureAction)
policyValidationMode, err := metrics.ParsePolicyValidationMode(policy.GetSpec().ValidationFailureAction)
if err != nil {
return err
}
policyType := metrics.Namespaced
policyBackgroundMode := metrics.ParsePolicyBackgroundMode(policy.Spec.Background)
policyBackgroundMode := metrics.ParsePolicyBackgroundMode(policy.GetSpec().Background)
policyNamespace := policy.GetNamespace()
if policyNamespace == "" {
policyNamespace = "-"

View file

@ -52,13 +52,13 @@ func (pc PromConfig) registerPolicyResultsMetric(
//policy - policy related data
//engineResponse - resource and rule related data
func (pc PromConfig) ProcessEngineResponse(policy kyverno.ClusterPolicy, engineResponse response.EngineResponse, executionCause metrics.RuleExecutionCause, resourceRequestOperation metrics.ResourceRequestOperation) error {
policyValidationMode, err := metrics.ParsePolicyValidationMode(policy.Spec.ValidationFailureAction)
func (pc PromConfig) ProcessEngineResponse(policy kyverno.PolicyInterface, engineResponse response.EngineResponse, executionCause metrics.RuleExecutionCause, resourceRequestOperation metrics.ResourceRequestOperation) error {
policyValidationMode, err := metrics.ParsePolicyValidationMode(policy.GetSpec().ValidationFailureAction)
if err != nil {
return err
}
policyType := metrics.Namespaced
policyBackgroundMode := metrics.ParsePolicyBackgroundMode(policy.Spec.Background)
policyBackgroundMode := metrics.ParsePolicyBackgroundMode(policy.GetSpec().Background)
policyNamespace := policy.GetNamespace()
if policyNamespace == "" {
policyNamespace = "-"

View file

@ -160,7 +160,7 @@ func (o *Controller) ValidatePolicyMutation(policy v1.ClusterPolicy) error {
newResource := unstructured.Unstructured{Object: resource}
newResource.SetKind(kind)
patchedResource, err := engine.ForceMutate(nil, newPolicy, newResource)
patchedResource, err := engine.ForceMutate(nil, &newPolicy, newResource)
if err != nil {
return err
}

View file

@ -59,7 +59,7 @@ func applyPolicy(policy kyverno.ClusterPolicy, resource unstructured.Unstructure
}
policyCtx := &engine.PolicyContext{
Policy: policy,
Policy: &policy,
NewResource: resource,
ExcludeGroupRole: excludeGroupRole,
JSONContext: ctx,
@ -76,7 +76,7 @@ func applyPolicy(policy kyverno.ClusterPolicy, resource unstructured.Unstructure
func mutation(policy kyverno.ClusterPolicy, resource unstructured.Unstructured, log logr.Logger, jsonContext *context.Context, namespaceLabels map[string]string) (*response.EngineResponse, error) {
policyContext := &engine.PolicyContext{
Policy: policy,
Policy: &policy,
NewResource: resource,
JSONContext: jsonContext,
NamespaceLabels: namespaceLabels,

View file

@ -51,9 +51,9 @@ func (pc *PolicyController) applyAndReportPerNamespace(policy *kyverno.ClusterPo
if !*metricAlreadyRegistered && len(engineResponses) > 0 {
for _, engineResponse := range engineResponses {
// registering the kyverno_policy_results_total metric concurrently
go pc.registerPolicyResultsMetricValidation(logger, *policy, *engineResponse)
go pc.registerPolicyResultsMetricValidation(logger, policy, *engineResponse)
// registering the kyverno_policy_execution_duration_seconds metric concurrently
go pc.registerPolicyExecutionDurationMetricValidate(logger, *policy, *engineResponse)
go pc.registerPolicyExecutionDurationMetricValidate(logger, policy, *engineResponse)
}
*metricAlreadyRegistered = true
}
@ -61,15 +61,15 @@ func (pc *PolicyController) applyAndReportPerNamespace(policy *kyverno.ClusterPo
pc.report(engineResponses, logger)
}
func (pc *PolicyController) registerPolicyResultsMetricValidation(logger logr.Logger, policy kyverno.ClusterPolicy, engineResponse response.EngineResponse) {
func (pc *PolicyController) registerPolicyResultsMetricValidation(logger logr.Logger, policy kyverno.PolicyInterface, engineResponse response.EngineResponse) {
if err := policyResults.ParsePromConfig(*pc.promConfig).ProcessEngineResponse(policy, engineResponse, metrics.BackgroundScan, metrics.ResourceCreated); err != nil {
logger.Error(err, "error occurred while registering kyverno_policy_results_total metrics for the above policy", "name", policy.Name)
logger.Error(err, "error occurred while registering kyverno_policy_results_total metrics for the above policy", "name", policy.GetName())
}
}
func (pc *PolicyController) registerPolicyExecutionDurationMetricValidate(logger logr.Logger, policy kyverno.ClusterPolicy, engineResponse response.EngineResponse) {
func (pc *PolicyController) registerPolicyExecutionDurationMetricValidate(logger logr.Logger, policy kyverno.PolicyInterface, engineResponse response.EngineResponse) {
if err := policyExecutionDuration.ParsePromConfig(*pc.promConfig).ProcessEngineResponse(policy, engineResponse, metrics.BackgroundScan, "", metrics.ResourceCreated); err != nil {
logger.Error(err, "error occurred while registering kyverno_policy_execution_duration_seconds metrics for the above policy", "name", policy.Name)
logger.Error(err, "error occurred while registering kyverno_policy_execution_duration_seconds metrics for the above policy", "name", policy.GetName())
}
}
@ -92,7 +92,7 @@ func (pc *PolicyController) applyPolicy(policy *kyverno.ClusterPolicy, resource
// excludeAutoGenResources filter out the pods / jobs with ownerReference
func excludeAutoGenResources(policy kyverno.ClusterPolicy, resourceMap map[string]unstructured.Unstructured, log logr.Logger) {
for uid, r := range resourceMap {
if engine.ManagedPodResource(policy, r) {
if engine.ManagedPodResource(&policy, r) {
log.V(4).Info("exclude resource", "namespace", r.GetNamespace(), "kind", r.GetKind(), "name", r.GetName())
delete(resourceMap, uid)
}

View file

@ -67,7 +67,7 @@ func GeneratePRsFromEngineResponse(ers []*response.EngineResponse, log logr.Logg
continue
}
if er.Policy != nil && engine.ManagedPodResource(*er.Policy, er.PatchedResource) {
if er.Policy != nil && engine.ManagedPodResource(er.Policy, er.PatchedResource) {
continue
}

View file

@ -143,7 +143,7 @@ func runTestCase(t *testing.T, tc TestCase) bool {
}
ctx := &engine.PolicyContext{
Policy: *policy,
Policy: policy,
NewResource: *resource,
ExcludeGroupRole: []string{},
JSONContext: context.NewContext(),
@ -160,7 +160,7 @@ func runTestCase(t *testing.T, tc TestCase) bool {
}
ctx = &engine.PolicyContext{
Policy: *policy,
Policy: policy,
NewResource: *resource,
ExcludeGroupRole: []string{},
JSONContext: context.NewContext(),
@ -182,7 +182,7 @@ func runTestCase(t *testing.T, tc TestCase) bool {
} else {
policyContext := &engine.PolicyContext{
NewResource: *resource,
Policy: *policy,
Policy: policy,
Client: client,
ExcludeGroupRole: []string{},
ExcludeResourceFunc: func(s1, s2, s3 string) bool {

View file

@ -80,7 +80,7 @@ func (ws *WebhookServer) handleGenerate(
for _, policy := range policies {
var rules []response.RuleResponse
policyContext.Policy = *policy
policyContext.Policy = policy
if request.Kind.Kind != "Namespace" && request.Namespace != "" {
policyContext.NamespaceLabels = common.GetNamespaceSelectorsFromNamespaceLister(request.Kind.Kind, request.Namespace, ws.nsLister, logger)
}
@ -100,10 +100,10 @@ func (ws *WebhookServer) handleGenerate(
}
// registering the kyverno_policy_results_total metric concurrently
go ws.registerPolicyResultsMetricGeneration(logger, string(request.Operation), *policy, *engineResponse)
go ws.registerPolicyResultsMetricGeneration(logger, string(request.Operation), policy, *engineResponse)
// registering the kyverno_policy_execution_duration_seconds metric concurrently
go ws.registerPolicyExecutionDurationMetricGenerate(logger, string(request.Operation), *policy, *engineResponse)
go ws.registerPolicyExecutionDurationMetricGenerate(logger, string(request.Operation), policy, *engineResponse)
}
// Adds Generate Request to a channel(queue size 1000) to generators
@ -127,23 +127,23 @@ func (ws *WebhookServer) handleGenerate(
*generateEngineResponsesSenderForAdmissionRequestsCountMetric <- engineResponses
}
func (ws *WebhookServer) registerPolicyResultsMetricGeneration(logger logr.Logger, resourceRequestOperation string, policy kyverno.ClusterPolicy, engineResponse response.EngineResponse) {
func (ws *WebhookServer) registerPolicyResultsMetricGeneration(logger logr.Logger, resourceRequestOperation string, policy kyverno.PolicyInterface, engineResponse response.EngineResponse) {
resourceRequestOperationPromAlias, err := policyResults.ParseResourceRequestOperation(resourceRequestOperation)
if err != nil {
logger.Error(err, "error occurred while registering kyverno_policy_results_total metrics for the above policy", "name", policy.Name)
logger.Error(err, "error occurred while registering kyverno_policy_results_total metrics for the above policy", "name", policy.GetName())
}
if err := policyResults.ParsePromConfig(*ws.promConfig).ProcessEngineResponse(policy, engineResponse, metrics.AdmissionRequest, resourceRequestOperationPromAlias); err != nil {
logger.Error(err, "error occurred while registering kyverno_policy_results_total metrics for the above policy", "name", policy.Name)
logger.Error(err, "error occurred while registering kyverno_policy_results_total metrics for the above policy", "name", policy.GetName())
}
}
func (ws *WebhookServer) registerPolicyExecutionDurationMetricGenerate(logger logr.Logger, resourceRequestOperation string, policy kyverno.ClusterPolicy, engineResponse response.EngineResponse) {
func (ws *WebhookServer) registerPolicyExecutionDurationMetricGenerate(logger logr.Logger, resourceRequestOperation string, policy kyverno.PolicyInterface, engineResponse response.EngineResponse) {
resourceRequestOperationPromAlias, err := policyExecutionDuration.ParseResourceRequestOperation(resourceRequestOperation)
if err != nil {
logger.Error(err, "error occurred while registering kyverno_policy_execution_duration_seconds metrics for the above policy", "name", policy.Name)
logger.Error(err, "error occurred while registering kyverno_policy_execution_duration_seconds metrics for the above policy", "name", policy.GetName())
}
if err := policyExecutionDuration.ParsePromConfig(*ws.promConfig).ProcessEngineResponse(policy, engineResponse, metrics.AdmissionRequest, "", resourceRequestOperationPromAlias); err != nil {
logger.Error(err, "error occurred while registering kyverno_policy_execution_duration_seconds metrics for the above policy", "name", policy.Name)
logger.Error(err, "error occurred while registering kyverno_policy_execution_duration_seconds metrics for the above policy", "name", policy.GetName())
}
}

View file

@ -79,7 +79,7 @@ func (ws *WebhookServer) handleMutation(
}
logger.V(3).Info("applying policy mutate rules", "policy", policy.Name)
policyContext.Policy = *policy
policyContext.Policy = policy
engineResponse, policyPatches, err := ws.applyMutation(request, policyContext, logger)
if err != nil {
// TODO report errors in engineResponse and record in metrics
@ -99,10 +99,10 @@ func (ws *WebhookServer) handleMutation(
engineResponses = append(engineResponses, engineResponse)
// registering the kyverno_policy_results_total metric concurrently
go ws.registerPolicyResultsMetricMutation(logger, string(request.Operation), *policy, *engineResponse)
go ws.registerPolicyResultsMetricMutation(logger, string(request.Operation), policy, *engineResponse)
// registering the kyverno_policy_execution_duration_seconds metric concurrently
go ws.registerPolicyExecutionDurationMetricMutate(logger, string(request.Operation), *policy, *engineResponse)
go ws.registerPolicyExecutionDurationMetricMutate(logger, string(request.Operation), policy, *engineResponse)
}
// generate annotations
@ -147,35 +147,35 @@ func (ws *WebhookServer) applyMutation(request *v1beta1.AdmissionRequest, policy
policyPatches := engineResponse.GetPatches()
if !engineResponse.IsSuccessful() && len(engineResponse.GetFailedRules()) > 0 {
return nil, nil, fmt.Errorf("failed to apply policy %s rules %v", policyContext.Policy.Name, engineResponse.GetFailedRules())
return nil, nil, fmt.Errorf("failed to apply policy %s rules %v", policyContext.Policy.GetName(), engineResponse.GetFailedRules())
}
if engineResponse.PatchedResource.GetKind() != "*" {
err := ws.openAPIController.ValidateResource(*engineResponse.PatchedResource.DeepCopy(), engineResponse.PatchedResource.GetAPIVersion(), engineResponse.PatchedResource.GetKind())
if err != nil {
return nil, nil, errors.Wrapf(err, "failed to validate resource mutated by policy %s", policyContext.Policy.Name)
return nil, nil, errors.Wrapf(err, "failed to validate resource mutated by policy %s", policyContext.Policy.GetName())
}
}
return engineResponse, policyPatches, nil
}
func (ws *WebhookServer) registerPolicyResultsMetricMutation(logger logr.Logger, resourceRequestOperation string, policy kyverno.ClusterPolicy, engineResponse response.EngineResponse) {
func (ws *WebhookServer) registerPolicyResultsMetricMutation(logger logr.Logger, resourceRequestOperation string, policy kyverno.PolicyInterface, engineResponse response.EngineResponse) {
resourceRequestOperationPromAlias, err := policyResults.ParseResourceRequestOperation(resourceRequestOperation)
if err != nil {
logger.Error(err, "error occurred while registering kyverno_policy_results_total metrics for the above policy", "name", policy.Name)
logger.Error(err, "error occurred while registering kyverno_policy_results_total metrics for the above policy", "name", policy.GetName())
}
if err := policyResults.ParsePromConfig(*ws.promConfig).ProcessEngineResponse(policy, engineResponse, metrics.AdmissionRequest, resourceRequestOperationPromAlias); err != nil {
logger.Error(err, "error occurred while registering kyverno_policy_results_total metrics for the above policy", "name", policy.Name)
logger.Error(err, "error occurred while registering kyverno_policy_results_total metrics for the above policy", "name", policy.GetName())
}
}
func (ws *WebhookServer) registerPolicyExecutionDurationMetricMutate(logger logr.Logger, resourceRequestOperation string, policy kyverno.ClusterPolicy, engineResponse response.EngineResponse) {
func (ws *WebhookServer) registerPolicyExecutionDurationMetricMutate(logger logr.Logger, resourceRequestOperation string, policy kyverno.PolicyInterface, engineResponse response.EngineResponse) {
resourceRequestOperationPromAlias, err := policyExecutionDuration.ParseResourceRequestOperation(resourceRequestOperation)
if err != nil {
logger.Error(err, "error occurred while registering kyverno_policy_execution_duration_seconds metrics for the above policy", "name", policy.Name)
logger.Error(err, "error occurred while registering kyverno_policy_execution_duration_seconds metrics for the above policy", "name", policy.GetName())
}
if err := policyExecutionDuration.ParsePromConfig(*ws.promConfig).ProcessEngineResponse(policy, engineResponse, metrics.AdmissionRequest, "", resourceRequestOperationPromAlias); err != nil {
logger.Error(err, "error occurred while registering kyverno_policy_execution_duration_seconds metrics for the above policy", "name", policy.Name)
logger.Error(err, "error occurred while registering kyverno_policy_execution_duration_seconds metrics for the above policy", "name", policy.GetName())
}
}

View file

@ -59,7 +59,7 @@ func (v *validationHandler) handleValidation(
var engineResponses []*response.EngineResponse
for _, policy := range policies {
logger.V(3).Info("evaluating policy", "policy", policy.Name)
policyContext.Policy = *policy
policyContext.Policy = policy
policyContext.NamespaceLabels = namespaceLabels
engineResponse := engine.Validate(policyContext)
if reflect.DeepEqual(engineResponse, response.EngineResponse{}) {
@ -116,7 +116,7 @@ func (v *validationHandler) handleValidation(
if request.Operation == v1beta1.Delete {
managed := true
for _, er := range engineResponses {
if er.Policy != nil && !engine.ManagedPodResource(*er.Policy, er.PatchedResource) {
if er.Policy != nil && !engine.ManagedPodResource(er.Policy, er.PatchedResource) {
managed = false
break
}
@ -150,23 +150,23 @@ func getResourceName(request *v1beta1.AdmissionRequest) string {
return resourceName
}
func registerPolicyResultsMetricValidation(promConfig *metrics.PromConfig, logger logr.Logger, requestOperation string, policy v1.ClusterPolicy, engineResponse response.EngineResponse) {
func registerPolicyResultsMetricValidation(promConfig *metrics.PromConfig, logger logr.Logger, requestOperation string, policy v1.PolicyInterface, engineResponse response.EngineResponse) {
resourceRequestOperationPromAlias, err := policyResults.ParseResourceRequestOperation(requestOperation)
if err != nil {
logger.Error(err, "error occurred while registering kyverno_policy_results_total metrics for the above policy", "name", policy.Name)
logger.Error(err, "error occurred while registering kyverno_policy_results_total metrics for the above policy", "name", policy.GetName())
}
if err := policyResults.ParsePromConfig(*promConfig).ProcessEngineResponse(policy, engineResponse, metrics.AdmissionRequest, resourceRequestOperationPromAlias); err != nil {
logger.Error(err, "error occurred while registering kyverno_policy_results_total metrics for the above policy", "name", policy.Name)
logger.Error(err, "error occurred while registering kyverno_policy_results_total metrics for the above policy", "name", policy.GetName())
}
}
func registerPolicyExecutionDurationMetricValidate(promConfig *metrics.PromConfig, logger logr.Logger, requestOperation string, policy v1.ClusterPolicy, engineResponse response.EngineResponse) {
func registerPolicyExecutionDurationMetricValidate(promConfig *metrics.PromConfig, logger logr.Logger, requestOperation string, policy v1.PolicyInterface, engineResponse response.EngineResponse) {
resourceRequestOperationPromAlias, err := policyExecutionDuration.ParseResourceRequestOperation(requestOperation)
if err != nil {
logger.Error(err, "error occurred while registering kyverno_policy_execution_duration_seconds metrics for the above policy", "name", policy.Name)
logger.Error(err, "error occurred while registering kyverno_policy_execution_duration_seconds metrics for the above policy", "name", policy.GetName())
}
if err := policyExecutionDuration.ParsePromConfig(*promConfig).ProcessEngineResponse(policy, engineResponse, metrics.AdmissionRequest, "", resourceRequestOperationPromAlias); err != nil {
logger.Error(err, "error occurred while registering kyverno_policy_execution_duration_seconds metrics for the above policy", "name", policy.Name)
logger.Error(err, "error occurred while registering kyverno_policy_execution_duration_seconds metrics for the above policy", "name", policy.GetName())
}
}

View file

@ -529,7 +529,7 @@ func TestValidate_failure_action_overrides(t *testing.T) {
"validation error: The label 'app' is required. Rule check-label-app failed at path /metadata/labels/",
}
er := engine.Validate(&engine.PolicyContext{Policy: policy, NewResource: *resourceUnstructured, JSONContext: context.NewContext()})
er := engine.Validate(&engine.PolicyContext{Policy: &policy, NewResource: *resourceUnstructured, JSONContext: context.NewContext()})
if tc.blocked {
for index, r := range er.PolicyResponse.Rules {
assert.Equal(t, r.Message, msgs[index])

View file

@ -36,7 +36,7 @@ func (ws *WebhookServer) handleVerifyImages(request *v1beta1.AdmissionRequest,
var engineResponses []*response.EngineResponse
var patches [][]byte
for _, p := range policies {
policyContext.Policy = *p
policyContext.Policy = p
resp := engine.VerifyAndPatchImages(policyContext)
engineResponses = append(engineResponses, resp)
patches = append(patches, resp.GetPatches()...)