Merge pull request #115973 from jpbetz/enforcement-actions

KEP-3488: Implement Enforcement Actions and Audit Annotations
This commit is contained in:
Kubernetes Prow Robot 2023-03-06 21:56:37 -08:00 committed by GitHub
commit 04675428bb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
45 changed files with 3023 additions and 305 deletions

View File

@ -348,6 +348,24 @@
},
"type": "object"
},
"io.k8s.api.admissionregistration.v1alpha1.AuditAnnotation": {
"description": "AuditAnnotation describes how to produce an audit annotation for an API request.",
"properties": {
"key": {
"description": "key specifies the audit annotation key. The audit annotation keys of a ValidatingAdmissionPolicy must be unique. The key must be a qualified name ([A-Za-z0-9][-A-Za-z0-9_.]*) no more than 63 bytes in length.\n\nThe key is combined with the resource name of the ValidatingAdmissionPolicy to construct an audit annotation key: \"{ValidatingAdmissionPolicy name}/{key}\".\n\nIf an admission webhook uses the same resource name as this ValidatingAdmissionPolicy and the same audit annotation key, the annotation key will be identical. In this case, the first annotation written with the key will be included in the audit event and all subsequent annotations with the same key will be discarded.\n\nRequired.",
"type": "string"
},
"valueExpression": {
"description": "valueExpression represents the expression which is evaluated by CEL to produce an audit annotation value. The expression must evaluate to either a string or null value. If the expression evaluates to a string, the audit annotation is included with the string value. If the expression evaluates to null or empty string the audit annotation will be omitted. The valueExpression may be no longer than 5kb in length. If the result of the valueExpression is more than 10kb in length, it will be truncated to 10kb.\n\nIf multiple ValidatingAdmissionPolicyBinding resources match an API request, then the valueExpression will be evaluated for each binding. All unique values produced by the valueExpressions will be joined together in a comma-separated list.\n\nRequired.",
"type": "string"
}
},
"required": [
"key",
"valueExpression"
],
"type": "object"
},
"io.k8s.api.admissionregistration.v1alpha1.MatchResources": {
"description": "MatchResources decides whether to run the admission control policy on an object based on whether it meets the match criteria. The exclude rules take precedence over include rules (if a resource matches both, it is excluded)",
"properties": {
@ -568,6 +586,14 @@
"policyName": {
"description": "PolicyName references a ValidatingAdmissionPolicy name which the ValidatingAdmissionPolicyBinding binds to. If the referenced resource does not exist, this binding is considered invalid and will be ignored Required.",
"type": "string"
},
"validationActions": {
"description": "validationActions declares how Validations of the referenced ValidatingAdmissionPolicy are enforced. If a validation evaluates to false it is always enforced according to these actions.\n\nFailures defined by the ValidatingAdmissionPolicy's FailurePolicy are enforced according to these actions only if the FailurePolicy is set to Fail, otherwise the failures are ignored. This includes compilation errors, runtime errors and misconfigurations of the policy.\n\nvalidationActions is declared as a set of action values. Order does not matter. validationActions may not contain duplicates of the same action.\n\nThe supported actions values are:\n\n\"Deny\" specifies that a validation failure results in a denied request.\n\n\"Warn\" specifies that a validation failure is reported to the request client in HTTP Warning headers, with a warning code of 299. Warnings can be sent both for allowed or denied admission responses.\n\n\"Audit\" specifies that a validation failure is included in the published audit event for the request. The audit event will contain a `validation.policy.admission.k8s.io/validation_failure` audit annotation with a value containing the details of the validation failures, formatted as a JSON list of objects, each with the following fields: - message: The validation failure message string - policy: The resource name of the ValidatingAdmissionPolicy - binding: The resource name of the ValidatingAdmissionPolicyBinding - expressionIndex: The index of the failed validations in the ValidatingAdmissionPolicy - validationActions: The enforcement actions enacted for the validation failure Example audit annotation: `\"validation.policy.admission.k8s.io/validation_failure\": \"[{\"message\": \"Invalid value\", {\"policy\": \"policy.example.com\", {\"binding\": \"policybinding.example.com\", {\"expressionIndex\": \"1\", {\"validationActions\": [\"Audit\"]}]\"`\n\nClients should expect to handle additional values by ignoring any values not recognized.\n\n\"Deny\" and \"Warn\" may not be used together since this combination needlessly duplicates the validation failure both in the API response body and the HTTP warning headers.\n\nRequired.",
"items": {
"type": "string"
},
"type": "array",
"x-kubernetes-list-type": "set"
}
},
"type": "object"
@ -607,8 +633,16 @@
"io.k8s.api.admissionregistration.v1alpha1.ValidatingAdmissionPolicySpec": {
"description": "ValidatingAdmissionPolicySpec is the specification of the desired behavior of the AdmissionPolicy.",
"properties": {
"auditAnnotations": {
"description": "auditAnnotations contains CEL expressions which are used to produce audit annotations for the audit event of the API request. validations and auditAnnotations may not both be empty; a least one of validations or auditAnnotations is required.",
"items": {
"$ref": "#/definitions/io.k8s.api.admissionregistration.v1alpha1.AuditAnnotation"
},
"type": "array",
"x-kubernetes-list-type": "atomic"
},
"failurePolicy": {
"description": "FailurePolicy defines how to handle failures for the admission policy. Failures can occur from invalid or mis-configured policy definitions or bindings. A policy is invalid if spec.paramKind refers to a non-existent Kind. A binding is invalid if spec.paramRef.name refers to a non-existent resource. Allowed values are Ignore or Fail. Defaults to Fail.",
"description": "failurePolicy defines how to handle failures for the admission policy. Failures can occur from CEL expression parse errors, type check errors, runtime errors and invalid or mis-configured policy definitions or bindings.\n\nA policy is invalid if spec.paramKind refers to a non-existent Kind. A binding is invalid if spec.paramRef.name refers to a non-existent resource.\n\nfailurePolicy does not define how validations that evaluate to false are handled.\n\nWhen failurePolicy is set to Fail, ValidatingAdmissionPolicyBinding validationActions define how failures are enforced.\n\nAllowed values are Ignore or Fail. Defaults to Fail.",
"type": "string"
},
"matchConstraints": {
@ -620,7 +654,7 @@
"description": "ParamKind specifies the kind of resources used to parameterize this policy. If absent, there are no parameters for this policy and the param CEL variable will not be provided to validation expressions. If ParamKind refers to a non-existent kind, this policy definition is mis-configured and the FailurePolicy is applied. If paramKind is specified but paramRef is unset in ValidatingAdmissionPolicyBinding, the params variable will be null."
},
"validations": {
"description": "Validations contain CEL expressions which is used to apply the validation. A minimum of one validation is required for a policy definition. Required.",
"description": "Validations contain CEL expressions which is used to apply the validation. Validations and AuditAnnotations may not both be empty; a minimum of one Validations or AuditAnnotations is required.",
"items": {
"$ref": "#/definitions/io.k8s.api.admissionregistration.v1alpha1.Validation"
},
@ -628,16 +662,13 @@
"x-kubernetes-list-type": "atomic"
}
},
"required": [
"validations"
],
"type": "object"
},
"io.k8s.api.admissionregistration.v1alpha1.Validation": {
"description": "Validation specifies the CEL expression which is used to apply the validation.",
"properties": {
"expression": {
"description": "Expression represents the expression which will be evaluated by CEL. ref: https://github.com/google/cel-spec CEL expressions have access to the contents of the Admission request/response, organized into CEL variables as well as some other useful variables:\n\n- 'object' - The object from the incoming request. The value is null for DELETE requests. - 'oldObject' - The existing object. The value is null for CREATE requests. - 'request' - Attributes of the admission request([ref](/pkg/apis/admission/types.go#AdmissionRequest)). - 'params' - Parameter resource referred to by the policy binding being evaluated. Only populated if the policy has a ParamKind. - 'authorizer' - A CEL Authorizer. May be used to perform authorization checks for the principal (user or service account) of the request.\n See https://pkg.go.dev/k8s.io/apiserver/pkg/cel/library#Authz\n- 'authorizer.requestResource' - A CEL ResourceCheck constructed from the 'authorizer' and configured with the\n request resource.\n\nThe `apiVersion`, `kind`, `metadata.name` and `metadata.generateName` are always accessible from the root of the object. No other metadata properties are accessible.\n\nOnly property names of the form `[a-zA-Z_.-/][a-zA-Z0-9_.-/]*` are accessible. Accessible property names are escaped according to the following rules when accessed in the expression: - '__' escapes to '__underscores__' - '.' escapes to '__dot__' - '-' escapes to '__dash__' - '/' escapes to '__slash__' - Property names that exactly match a CEL RESERVED keyword escape to '__{keyword}__'. The keywords are:\n\t \"true\", \"false\", \"null\", \"in\", \"as\", \"break\", \"const\", \"continue\", \"else\", \"for\", \"function\", \"if\",\n\t \"import\", \"let\", \"loop\", \"package\", \"namespace\", \"return\".\nExamples:\n - Expression accessing a property named \"namespace\": {\"Expression\": \"object.__namespace__ > 0\"}\n - Expression accessing a property named \"x-prop\": {\"Expression\": \"object.x__dash__prop > 0\"}\n - Expression accessing a property named \"redact__d\": {\"Expression\": \"object.redact__underscores__d > 0\"}\n\nEquality on arrays with list type of 'set' or 'map' ignores element order, i.e. [1, 2] == [2, 1]. Concatenation on arrays with x-kubernetes-list-type use the semantics of the list type:\n - 'set': `X + Y` performs a union where the array positions of all elements in `X` are preserved and\n non-intersecting elements in `Y` are appended, retaining their partial order.\n - 'map': `X + Y` performs a merge where the array positions of all keys in `X` are preserved but the values\n are overwritten by values in `Y` when the key sets of `X` and `Y` intersect. Elements in `Y` with\n non-intersecting keys are appended, retaining their partial order.\nRequired.",
"description": "Expression represents the expression which will be evaluated by CEL. ref: https://github.com/google/cel-spec CEL expressions have access to the contents of the API request/response, organized into CEL variables as well as some other useful variables:\n\n- 'object' - The object from the incoming request. The value is null for DELETE requests. - 'oldObject' - The existing object. The value is null for CREATE requests. - 'request' - Attributes of the API request([ref](/pkg/apis/admission/types.go#AdmissionRequest)). - 'params' - Parameter resource referred to by the policy binding being evaluated. Only populated if the policy has a ParamKind. - 'authorizer' - A CEL Authorizer. May be used to perform authorization checks for the principal (user or service account) of the request.\n See https://pkg.go.dev/k8s.io/apiserver/pkg/cel/library#Authz\n- 'authorizer.requestResource' - A CEL ResourceCheck constructed from the 'authorizer' and configured with the\n request resource.\n\nThe `apiVersion`, `kind`, `metadata.name` and `metadata.generateName` are always accessible from the root of the object. No other metadata properties are accessible.\n\nOnly property names of the form `[a-zA-Z_.-/][a-zA-Z0-9_.-/]*` are accessible. Accessible property names are escaped according to the following rules when accessed in the expression: - '__' escapes to '__underscores__' - '.' escapes to '__dot__' - '-' escapes to '__dash__' - '/' escapes to '__slash__' - Property names that exactly match a CEL RESERVED keyword escape to '__{keyword}__'. The keywords are:\n\t \"true\", \"false\", \"null\", \"in\", \"as\", \"break\", \"const\", \"continue\", \"else\", \"for\", \"function\", \"if\",\n\t \"import\", \"let\", \"loop\", \"package\", \"namespace\", \"return\".\nExamples:\n - Expression accessing a property named \"namespace\": {\"Expression\": \"object.__namespace__ > 0\"}\n - Expression accessing a property named \"x-prop\": {\"Expression\": \"object.x__dash__prop > 0\"}\n - Expression accessing a property named \"redact__d\": {\"Expression\": \"object.redact__underscores__d > 0\"}\n\nEquality on arrays with list type of 'set' or 'map' ignores element order, i.e. [1, 2] == [2, 1]. Concatenation on arrays with x-kubernetes-list-type use the semantics of the list type:\n - 'set': `X + Y` performs a union where the array positions of all elements in `X` are preserved and\n non-intersecting elements in `Y` are appended, retaining their partial order.\n - 'map': `X + Y` performs a merge where the array positions of all keys in `X` are preserved but the values\n are overwritten by values in `Y` when the key sets of `X` and `Y` intersect. Elements in `Y` with\n non-intersecting keys are appended, retaining their partial order.\nRequired.",
"type": "string"
},
"message": {

View File

@ -1,6 +1,26 @@
{
"components": {
"schemas": {
"io.k8s.api.admissionregistration.v1alpha1.AuditAnnotation": {
"description": "AuditAnnotation describes how to produce an audit annotation for an API request.",
"properties": {
"key": {
"default": "",
"description": "key specifies the audit annotation key. The audit annotation keys of a ValidatingAdmissionPolicy must be unique. The key must be a qualified name ([A-Za-z0-9][-A-Za-z0-9_.]*) no more than 63 bytes in length.\n\nThe key is combined with the resource name of the ValidatingAdmissionPolicy to construct an audit annotation key: \"{ValidatingAdmissionPolicy name}/{key}\".\n\nIf an admission webhook uses the same resource name as this ValidatingAdmissionPolicy and the same audit annotation key, the annotation key will be identical. In this case, the first annotation written with the key will be included in the audit event and all subsequent annotations with the same key will be discarded.\n\nRequired.",
"type": "string"
},
"valueExpression": {
"default": "",
"description": "valueExpression represents the expression which is evaluated by CEL to produce an audit annotation value. The expression must evaluate to either a string or null value. If the expression evaluates to a string, the audit annotation is included with the string value. If the expression evaluates to null or empty string the audit annotation will be omitted. The valueExpression may be no longer than 5kb in length. If the result of the valueExpression is more than 10kb in length, it will be truncated to 10kb.\n\nIf multiple ValidatingAdmissionPolicyBinding resources match an API request, then the valueExpression will be evaluated for each binding. All unique values produced by the valueExpressions will be joined together in a comma-separated list.\n\nRequired.",
"type": "string"
}
},
"required": [
"key",
"valueExpression"
],
"type": "object"
},
"io.k8s.api.admissionregistration.v1alpha1.MatchResources": {
"description": "MatchResources decides whether to run the admission control policy on an object based on whether it meets the match criteria. The exclude rules take precedence over include rules (if a resource matches both, it is excluded)",
"properties": {
@ -282,6 +302,15 @@
"policyName": {
"description": "PolicyName references a ValidatingAdmissionPolicy name which the ValidatingAdmissionPolicyBinding binds to. If the referenced resource does not exist, this binding is considered invalid and will be ignored Required.",
"type": "string"
},
"validationActions": {
"description": "validationActions declares how Validations of the referenced ValidatingAdmissionPolicy are enforced. If a validation evaluates to false it is always enforced according to these actions.\n\nFailures defined by the ValidatingAdmissionPolicy's FailurePolicy are enforced according to these actions only if the FailurePolicy is set to Fail, otherwise the failures are ignored. This includes compilation errors, runtime errors and misconfigurations of the policy.\n\nvalidationActions is declared as a set of action values. Order does not matter. validationActions may not contain duplicates of the same action.\n\nThe supported actions values are:\n\n\"Deny\" specifies that a validation failure results in a denied request.\n\n\"Warn\" specifies that a validation failure is reported to the request client in HTTP Warning headers, with a warning code of 299. Warnings can be sent both for allowed or denied admission responses.\n\n\"Audit\" specifies that a validation failure is included in the published audit event for the request. The audit event will contain a `validation.policy.admission.k8s.io/validation_failure` audit annotation with a value containing the details of the validation failures, formatted as a JSON list of objects, each with the following fields: - message: The validation failure message string - policy: The resource name of the ValidatingAdmissionPolicy - binding: The resource name of the ValidatingAdmissionPolicyBinding - expressionIndex: The index of the failed validations in the ValidatingAdmissionPolicy - validationActions: The enforcement actions enacted for the validation failure Example audit annotation: `\"validation.policy.admission.k8s.io/validation_failure\": \"[{\"message\": \"Invalid value\", {\"policy\": \"policy.example.com\", {\"binding\": \"policybinding.example.com\", {\"expressionIndex\": \"1\", {\"validationActions\": [\"Audit\"]}]\"`\n\nClients should expect to handle additional values by ignoring any values not recognized.\n\n\"Deny\" and \"Warn\" may not be used together since this combination needlessly duplicates the validation failure both in the API response body and the HTTP warning headers.\n\nRequired.",
"items": {
"default": "",
"type": "string"
},
"type": "array",
"x-kubernetes-list-type": "set"
}
},
"type": "object"
@ -331,8 +360,21 @@
"io.k8s.api.admissionregistration.v1alpha1.ValidatingAdmissionPolicySpec": {
"description": "ValidatingAdmissionPolicySpec is the specification of the desired behavior of the AdmissionPolicy.",
"properties": {
"auditAnnotations": {
"description": "auditAnnotations contains CEL expressions which are used to produce audit annotations for the audit event of the API request. validations and auditAnnotations may not both be empty; a least one of validations or auditAnnotations is required.",
"items": {
"allOf": [
{
"$ref": "#/components/schemas/io.k8s.api.admissionregistration.v1alpha1.AuditAnnotation"
}
],
"default": {}
},
"type": "array",
"x-kubernetes-list-type": "atomic"
},
"failurePolicy": {
"description": "FailurePolicy defines how to handle failures for the admission policy. Failures can occur from invalid or mis-configured policy definitions or bindings. A policy is invalid if spec.paramKind refers to a non-existent Kind. A binding is invalid if spec.paramRef.name refers to a non-existent resource. Allowed values are Ignore or Fail. Defaults to Fail.",
"description": "failurePolicy defines how to handle failures for the admission policy. Failures can occur from CEL expression parse errors, type check errors, runtime errors and invalid or mis-configured policy definitions or bindings.\n\nA policy is invalid if spec.paramKind refers to a non-existent Kind. A binding is invalid if spec.paramRef.name refers to a non-existent resource.\n\nfailurePolicy does not define how validations that evaluate to false are handled.\n\nWhen failurePolicy is set to Fail, ValidatingAdmissionPolicyBinding validationActions define how failures are enforced.\n\nAllowed values are Ignore or Fail. Defaults to Fail.",
"type": "string"
},
"matchConstraints": {
@ -352,7 +394,7 @@
"description": "ParamKind specifies the kind of resources used to parameterize this policy. If absent, there are no parameters for this policy and the param CEL variable will not be provided to validation expressions. If ParamKind refers to a non-existent kind, this policy definition is mis-configured and the FailurePolicy is applied. If paramKind is specified but paramRef is unset in ValidatingAdmissionPolicyBinding, the params variable will be null."
},
"validations": {
"description": "Validations contain CEL expressions which is used to apply the validation. A minimum of one validation is required for a policy definition. Required.",
"description": "Validations contain CEL expressions which is used to apply the validation. Validations and AuditAnnotations may not both be empty; a minimum of one Validations or AuditAnnotations is required.",
"items": {
"allOf": [
{
@ -365,9 +407,6 @@
"x-kubernetes-list-type": "atomic"
}
},
"required": [
"validations"
],
"type": "object"
},
"io.k8s.api.admissionregistration.v1alpha1.Validation": {
@ -375,7 +414,7 @@
"properties": {
"expression": {
"default": "",
"description": "Expression represents the expression which will be evaluated by CEL. ref: https://github.com/google/cel-spec CEL expressions have access to the contents of the Admission request/response, organized into CEL variables as well as some other useful variables:\n\n- 'object' - The object from the incoming request. The value is null for DELETE requests. - 'oldObject' - The existing object. The value is null for CREATE requests. - 'request' - Attributes of the admission request([ref](/pkg/apis/admission/types.go#AdmissionRequest)). - 'params' - Parameter resource referred to by the policy binding being evaluated. Only populated if the policy has a ParamKind. - 'authorizer' - A CEL Authorizer. May be used to perform authorization checks for the principal (user or service account) of the request.\n See https://pkg.go.dev/k8s.io/apiserver/pkg/cel/library#Authz\n- 'authorizer.requestResource' - A CEL ResourceCheck constructed from the 'authorizer' and configured with the\n request resource.\n\nThe `apiVersion`, `kind`, `metadata.name` and `metadata.generateName` are always accessible from the root of the object. No other metadata properties are accessible.\n\nOnly property names of the form `[a-zA-Z_.-/][a-zA-Z0-9_.-/]*` are accessible. Accessible property names are escaped according to the following rules when accessed in the expression: - '__' escapes to '__underscores__' - '.' escapes to '__dot__' - '-' escapes to '__dash__' - '/' escapes to '__slash__' - Property names that exactly match a CEL RESERVED keyword escape to '__{keyword}__'. The keywords are:\n\t \"true\", \"false\", \"null\", \"in\", \"as\", \"break\", \"const\", \"continue\", \"else\", \"for\", \"function\", \"if\",\n\t \"import\", \"let\", \"loop\", \"package\", \"namespace\", \"return\".\nExamples:\n - Expression accessing a property named \"namespace\": {\"Expression\": \"object.__namespace__ > 0\"}\n - Expression accessing a property named \"x-prop\": {\"Expression\": \"object.x__dash__prop > 0\"}\n - Expression accessing a property named \"redact__d\": {\"Expression\": \"object.redact__underscores__d > 0\"}\n\nEquality on arrays with list type of 'set' or 'map' ignores element order, i.e. [1, 2] == [2, 1]. Concatenation on arrays with x-kubernetes-list-type use the semantics of the list type:\n - 'set': `X + Y` performs a union where the array positions of all elements in `X` are preserved and\n non-intersecting elements in `Y` are appended, retaining their partial order.\n - 'map': `X + Y` performs a merge where the array positions of all keys in `X` are preserved but the values\n are overwritten by values in `Y` when the key sets of `X` and `Y` intersect. Elements in `Y` with\n non-intersecting keys are appended, retaining their partial order.\nRequired.",
"description": "Expression represents the expression which will be evaluated by CEL. ref: https://github.com/google/cel-spec CEL expressions have access to the contents of the API request/response, organized into CEL variables as well as some other useful variables:\n\n- 'object' - The object from the incoming request. The value is null for DELETE requests. - 'oldObject' - The existing object. The value is null for CREATE requests. - 'request' - Attributes of the API request([ref](/pkg/apis/admission/types.go#AdmissionRequest)). - 'params' - Parameter resource referred to by the policy binding being evaluated. Only populated if the policy has a ParamKind. - 'authorizer' - A CEL Authorizer. May be used to perform authorization checks for the principal (user or service account) of the request.\n See https://pkg.go.dev/k8s.io/apiserver/pkg/cel/library#Authz\n- 'authorizer.requestResource' - A CEL ResourceCheck constructed from the 'authorizer' and configured with the\n request resource.\n\nThe `apiVersion`, `kind`, `metadata.name` and `metadata.generateName` are always accessible from the root of the object. No other metadata properties are accessible.\n\nOnly property names of the form `[a-zA-Z_.-/][a-zA-Z0-9_.-/]*` are accessible. Accessible property names are escaped according to the following rules when accessed in the expression: - '__' escapes to '__underscores__' - '.' escapes to '__dot__' - '-' escapes to '__dash__' - '/' escapes to '__slash__' - Property names that exactly match a CEL RESERVED keyword escape to '__{keyword}__'. The keywords are:\n\t \"true\", \"false\", \"null\", \"in\", \"as\", \"break\", \"const\", \"continue\", \"else\", \"for\", \"function\", \"if\",\n\t \"import\", \"let\", \"loop\", \"package\", \"namespace\", \"return\".\nExamples:\n - Expression accessing a property named \"namespace\": {\"Expression\": \"object.__namespace__ > 0\"}\n - Expression accessing a property named \"x-prop\": {\"Expression\": \"object.x__dash__prop > 0\"}\n - Expression accessing a property named \"redact__d\": {\"Expression\": \"object.redact__underscores__d > 0\"}\n\nEquality on arrays with list type of 'set' or 'map' ignores element order, i.e. [1, 2] == [2, 1]. Concatenation on arrays with x-kubernetes-list-type use the semantics of the list type:\n - 'set': `X + Y` performs a union where the array positions of all elements in `X` are preserved and\n non-intersecting elements in `Y` are appended, retaining their partial order.\n - 'map': `X + Y` performs a merge where the array positions of all keys in `X` are preserved but the values\n are overwritten by values in `Y` when the key sets of `X` and `Y` intersect. Elements in `Y` with\n non-intersecting keys are appended, retaining their partial order.\nRequired.",
"type": "string"
},
"message": {

View File

@ -20,6 +20,7 @@ import (
fuzz "github.com/google/gofuzz"
runtimeserializer "k8s.io/apimachinery/pkg/runtime/serializer"
"k8s.io/kubernetes/pkg/apis/admissionregistration"
)
@ -84,6 +85,12 @@ var Funcs = func(codecs runtimeserializer.CodecFactory) []interface{} {
obj.FailurePolicy = &p
}
},
func(obj *admissionregistration.ValidatingAdmissionPolicyBindingSpec, c fuzz.Continue) {
c.FuzzNoCustom(obj) // fuzz self without calling this function again
if obj.ValidationActions == nil {
obj.ValidationActions = []admissionregistration.ValidationAction{admissionregistration.Deny}
}
},
func(obj *admissionregistration.MatchResources, c fuzz.Continue) {
c.FuzzNoCustom(obj) // fuzz self without calling this function again
if obj.MatchPolicy == nil {

View File

@ -154,18 +154,35 @@ type ValidatingAdmissionPolicySpec struct {
// Required.
MatchConstraints *MatchResources
// Validations contain CEL expressions which is used to apply the validation.
// A minimum of one validation is required for a policy definition.
// Required.
// validations contain CEL expressions which are used to validate admission requests.
// validations and auditAnnotations may not both be empty; a minimum of one validations or auditAnnotations is
// required.
// +optional
Validations []Validation
// FailurePolicy defines how to handle failures for the admission policy.
// Failures can occur from invalid or mis-configured policy definitions or bindings.
// failurePolicy defines how to handle failures for the admission policy. Failures can
// occur from CEL expression parse errors, type check errors, runtime errors and invalid
// or mis-configured policy definitions or bindings.
//
// A policy is invalid if spec.paramKind refers to a non-existent Kind.
// A binding is invalid if spec.paramRef.name refers to a non-existent resource.
//
// failurePolicy does not define how validations that evaluate to false are handled.
//
// When failurePolicy is set to Fail, ValidatingAdmissionPolicyBinding validationActions
// define how failures are enforced.
//
// Allowed values are Ignore or Fail. Defaults to Fail.
// +optional
FailurePolicy *FailurePolicyType
// auditAnnotations contains CEL expressions which are used to produce audit
// annotations for the audit event of the API request.
// validations and auditAnnotations may not both be empty; a least one of validations or auditAnnotations is
// required.
// A maximum of 20 auditAnnotation are allowed per ValidatingAdmissionPolicy.
// +optional
AuditAnnotations []AuditAnnotation
}
// ParamKind is a tuple of Group Kind and Version.
@ -184,12 +201,12 @@ type ParamKind struct {
type Validation struct {
// Expression represents the expression which will be evaluated by CEL.
// ref: https://github.com/google/cel-spec
// CEL expressions have access to the contents of the Admission request/response, organized into CEL variables as well as some other useful variables:
// CEL expressions have access to the contents of the API request/response, organized into CEL variables as well as some other useful variables:
//
// - 'object' - The object from the incoming request. The value is null for DELETE requests.
// - 'oldObject' - The existing object. The value is null for CREATE requests.
// - 'request' - Attributes of the admission request([ref](/pkg/apis/admission/types.go#AdmissionRequest)).
// - 'params' - Parameter resource referred to by the policy binding being evaluated. Only populated if the policy has a ParamKind.
//'object' - The object from the incoming request. The value is null for DELETE requests.
//'oldObject' - The existing object. The value is null for CREATE requests.
//'request' - Attributes of the API request([ref](/pkg/apis/admission/types.go#AdmissionRequest)).
//'params' - Parameter resource referred to by the policy binding being evaluated. Only populated if the policy has a ParamKind.
// - 'authorizer' - A CEL Authorizer. May be used to perform authorization checks for the principal (user or service account) of the request.
// See https://pkg.go.dev/k8s.io/apiserver/pkg/cel/library#Authz
// - 'authorizer.requestResource' - A CEL ResourceCheck constructed from the 'authorizer' and configured with the
@ -241,6 +258,43 @@ type Validation struct {
Reason *metav1.StatusReason
}
// AuditAnnotation describes how to produce an audit annotation for an API request.
type AuditAnnotation struct {
// key specifies the audit annotation key. The audit annotation keys of
// a ValidatingAdmissionPolicy must be unique. The key must be a qualified
// name ([A-Za-z0-9][-A-Za-z0-9_.]*) no more than 63 bytes in length.
//
// The key is combined with the resource name of the
// ValidatingAdmissionPolicy to construct an audit annotation key:
// "{ValidatingAdmissionPolicy name}/{key}".
//
// If an admission webhook uses the same resource name as this ValidatingAdmissionPolicy
// and the same audit annotation key, the annotation key will be identical.
// In this case, the first annotation written with the key will be included
// in the audit event and all subsequent annotations with the same key
// will be discarded.
//
// Required.
Key string
// valueExpression represents the expression which is evaluated by CEL to
// produce an audit annotation value. The expression must evaluate to either
// a string or null value. If the expression evaluates to a string, the
// audit annotation is included with the string value. If the expression
// evaluates to null or empty string the audit annotation will be omitted.
// The valueExpression may be no longer than 5kb in length.
// If the result of the valueExpression is more than 10kb in length, it
// will be truncated to 10kb.
//
// If multiple ValidatingAdmissionPolicyBinding resources match an
// API request, then the valueExpression will be evaluated for
// each binding. All unique values produced by the valueExpressions
// will be joined together in a comma-separated list.
//
// Required.
ValueExpression string
}
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// ValidatingAdmissionPolicyBinding binds the ValidatingAdmissionPolicy with paramerized resources.
@ -287,6 +341,47 @@ type ValidatingAdmissionPolicyBindingSpec struct {
// Note that this is differs from ValidatingAdmissionPolicy matchConstraints, where resourceRules are required.
// +optional
MatchResources *MatchResources
// validationActions declares how Validations of the referenced ValidatingAdmissionPolicy are enforced.
// If a validation evaluates to false it is always enforced according to these actions.
//
// Failures defined by the ValidatingAdmissionPolicy's FailurePolicy are enforced according
// to these actions only if the FailurePolicy is set to Fail, otherwise the failures are
// ignored. This includes compilation errors, runtime errors and misconfigurations of the policy.
//
// validationActions is declared as a set of action values. Order does
// not matter. validationActions may not contain duplicates of the same action.
//
// The supported actions values are:
//
// "Deny" specifies that a validation failure results in a denied request.
//
// "Warn" specifies that a validation failure is reported to the request client
// in HTTP Warning headers, with a warning code of 299. Warnings can be sent
// both for allowed or denied admission responses.
//
// "Audit" specifies that a validation failure is included in the published
// audit event for the request. The audit event will contain a
// `validation.policy.admission.k8s.io/validation_failure` audit annotation
// with a value containing the details of the validation failures, formatted as
// a JSON list of objects, each with the following fields:
// - message: The validation failure message string
// - policy: The resource name of the ValidatingAdmissionPolicy
// - binding: The resource name of the ValidatingAdmissionPolicyBinding
// - expressionIndex: The index of the failed validations in the ValidatingAdmissionPolicy
// - validationActions: The enforcement actions enacted for the validation failure
// Example audit annotation:
// `"validation.policy.admission.k8s.io/validation_failure": "[{\"message\": \"Invalid value\", {\"policy\": \"policy.example.com\", {\"binding\": \"policybinding.example.com\", {\"expressionIndex\": \"1\", {\"validationActions\": [\"Audit\"]}]"`
//
// Clients should expect to handle additional values by ignoring
// any values not recognized.
//
// "Deny" and "Warn" may not be used together since this combination
// needlessly duplicates the validation failure both in the
// API response body and the HTTP warning headers.
//
// Required.
ValidationActions []ValidationAction
}
// ParamRef references a parameter resource
@ -387,6 +482,23 @@ type MatchResources struct {
MatchPolicy *MatchPolicyType
}
// ValidationAction specifies a policy enforcement action.
type ValidationAction string
const (
// Deny specifies that a validation failure results in a denied request.
Deny ValidationAction = "Deny"
// Warn specifies that a validation failure is reported to the request client
// in HTTP Warning headers, with a warning code of 299. Warnings can be sent
// both for allowed or denied admission responses.
Warn ValidationAction = "Warn"
// Audit specifies that a validation failure is included in the published
// audit event for the request. The audit event will contain a
// `validation.policy.admission.k8s.io/validation_failure` audit annotation
// with a value containing the details of the validation failure.
Audit ValidationAction = "Audit"
)
// NamedRuleWithOperations is a tuple of Operations and Resources with ResourceNames.
type NamedRuleWithOperations struct {
// ResourceNames is an optional white list of names that the rule applies to. An empty set means that everything is allowed.

View File

@ -39,6 +39,16 @@ func init() {
// RegisterConversions adds conversion functions to the given scheme.
// Public to allow building arbitrary schemes.
func RegisterConversions(s *runtime.Scheme) error {
if err := s.AddGeneratedConversionFunc((*v1alpha1.AuditAnnotation)(nil), (*admissionregistration.AuditAnnotation)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v1alpha1_AuditAnnotation_To_admissionregistration_AuditAnnotation(a.(*v1alpha1.AuditAnnotation), b.(*admissionregistration.AuditAnnotation), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*admissionregistration.AuditAnnotation)(nil), (*v1alpha1.AuditAnnotation)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_admissionregistration_AuditAnnotation_To_v1alpha1_AuditAnnotation(a.(*admissionregistration.AuditAnnotation), b.(*v1alpha1.AuditAnnotation), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*v1alpha1.MatchResources)(nil), (*admissionregistration.MatchResources)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v1alpha1_MatchResources_To_admissionregistration_MatchResources(a.(*v1alpha1.MatchResources), b.(*admissionregistration.MatchResources), scope)
}); err != nil {
@ -152,6 +162,28 @@ func RegisterConversions(s *runtime.Scheme) error {
return nil
}
func autoConvert_v1alpha1_AuditAnnotation_To_admissionregistration_AuditAnnotation(in *v1alpha1.AuditAnnotation, out *admissionregistration.AuditAnnotation, s conversion.Scope) error {
out.Key = in.Key
out.ValueExpression = in.ValueExpression
return nil
}
// Convert_v1alpha1_AuditAnnotation_To_admissionregistration_AuditAnnotation is an autogenerated conversion function.
func Convert_v1alpha1_AuditAnnotation_To_admissionregistration_AuditAnnotation(in *v1alpha1.AuditAnnotation, out *admissionregistration.AuditAnnotation, s conversion.Scope) error {
return autoConvert_v1alpha1_AuditAnnotation_To_admissionregistration_AuditAnnotation(in, out, s)
}
func autoConvert_admissionregistration_AuditAnnotation_To_v1alpha1_AuditAnnotation(in *admissionregistration.AuditAnnotation, out *v1alpha1.AuditAnnotation, s conversion.Scope) error {
out.Key = in.Key
out.ValueExpression = in.ValueExpression
return nil
}
// Convert_admissionregistration_AuditAnnotation_To_v1alpha1_AuditAnnotation is an autogenerated conversion function.
func Convert_admissionregistration_AuditAnnotation_To_v1alpha1_AuditAnnotation(in *admissionregistration.AuditAnnotation, out *v1alpha1.AuditAnnotation, s conversion.Scope) error {
return autoConvert_admissionregistration_AuditAnnotation_To_v1alpha1_AuditAnnotation(in, out, s)
}
func autoConvert_v1alpha1_MatchResources_To_admissionregistration_MatchResources(in *v1alpha1.MatchResources, out *admissionregistration.MatchResources, s conversion.Scope) error {
out.NamespaceSelector = (*v1.LabelSelector)(unsafe.Pointer(in.NamespaceSelector))
out.ObjectSelector = (*v1.LabelSelector)(unsafe.Pointer(in.ObjectSelector))
@ -396,6 +428,7 @@ func autoConvert_v1alpha1_ValidatingAdmissionPolicyBindingSpec_To_admissionregis
} else {
out.MatchResources = nil
}
out.ValidationActions = *(*[]admissionregistration.ValidationAction)(unsafe.Pointer(&in.ValidationActions))
return nil
}
@ -416,6 +449,7 @@ func autoConvert_admissionregistration_ValidatingAdmissionPolicyBindingSpec_To_v
} else {
out.MatchResources = nil
}
out.ValidationActions = *(*[]v1alpha1.ValidationAction)(unsafe.Pointer(&in.ValidationActions))
return nil
}
@ -479,6 +513,7 @@ func autoConvert_v1alpha1_ValidatingAdmissionPolicySpec_To_admissionregistration
}
out.Validations = *(*[]admissionregistration.Validation)(unsafe.Pointer(&in.Validations))
out.FailurePolicy = (*admissionregistration.FailurePolicyType)(unsafe.Pointer(in.FailurePolicy))
out.AuditAnnotations = *(*[]admissionregistration.AuditAnnotation)(unsafe.Pointer(&in.AuditAnnotations))
return nil
}
@ -500,6 +535,7 @@ func autoConvert_admissionregistration_ValidatingAdmissionPolicySpec_To_v1alpha1
}
out.Validations = *(*[]v1alpha1.Validation)(unsafe.Pointer(&in.Validations))
out.FailurePolicy = (*v1alpha1.FailurePolicyType)(unsafe.Pointer(in.FailurePolicy))
out.AuditAnnotations = *(*[]v1alpha1.AuditAnnotation)(unsafe.Pointer(&in.AuditAnnotations))
return nil
}

View File

@ -37,6 +37,7 @@ import (
"k8s.io/kubernetes/pkg/apis/admissionregistration"
admissionregistrationv1 "k8s.io/kubernetes/pkg/apis/admissionregistration/v1"
admissionregistrationv1beta1 "k8s.io/kubernetes/pkg/apis/admissionregistration/v1beta1"
apivalidation "k8s.io/kubernetes/pkg/apis/core/validation"
)
func hasWildcard(slice []string) bool {
@ -583,6 +584,14 @@ func ValidateMutatingWebhookConfigurationUpdate(newC, oldC *admissionregistratio
})
}
const (
maxAuditAnnotations = 20
// use a 5kb limit the CEL expression, note that this is less than the length limit
// for the audit annotation value limit (10kb) since an expressions that concatenates
// strings will often produce a longer value than the expression
maxAuditAnnotationValueExpressionLength = 5 * 1024
)
// ValidateValidatingAdmissionPolicy validates a ValidatingAdmissionPolicy before creation.
func ValidateValidatingAdmissionPolicy(p *admissionregistration.ValidatingAdmissionPolicy) field.ErrorList {
return validateValidatingAdmissionPolicy(p)
@ -590,11 +599,11 @@ func ValidateValidatingAdmissionPolicy(p *admissionregistration.ValidatingAdmiss
func validateValidatingAdmissionPolicy(p *admissionregistration.ValidatingAdmissionPolicy) field.ErrorList {
allErrors := genericvalidation.ValidateObjectMeta(&p.ObjectMeta, false, genericvalidation.NameIsDNSSubdomain, field.NewPath("metadata"))
allErrors = append(allErrors, validateValidatingAdmissionPolicySpec(&p.Spec, field.NewPath("spec"))...)
allErrors = append(allErrors, validateValidatingAdmissionPolicySpec(p.ObjectMeta, &p.Spec, field.NewPath("spec"))...)
return allErrors
}
func validateValidatingAdmissionPolicySpec(spec *admissionregistration.ValidatingAdmissionPolicySpec, fldPath *field.Path) field.ErrorList {
func validateValidatingAdmissionPolicySpec(meta metav1.ObjectMeta, spec *admissionregistration.ValidatingAdmissionPolicySpec, fldPath *field.Path) field.ErrorList {
var allErrors field.ErrorList
if spec.FailurePolicy == nil {
allErrors = append(allErrors, field.Required(fldPath.Child("failurePolicy"), ""))
@ -613,14 +622,27 @@ func validateValidatingAdmissionPolicySpec(spec *admissionregistration.Validatin
allErrors = append(allErrors, field.Required(fldPath.Child("matchConstraints", "resourceRules"), ""))
}
}
if len(spec.Validations) == 0 {
allErrors = append(allErrors, field.Required(fldPath.Child("validations"), ""))
if len(spec.Validations) == 0 && len(spec.AuditAnnotations) == 0 {
allErrors = append(allErrors, field.Required(fldPath.Child("validations"), "validations or auditAnnotations must contain at least one item"))
allErrors = append(allErrors, field.Required(fldPath.Child("auditAnnotations"), "validations or auditAnnotations must contain at least one item"))
} else {
for i, validation := range spec.Validations {
allErrors = append(allErrors, validateValidation(&validation, spec.ParamKind, fldPath.Child("validations").Index(i))...)
}
if spec.AuditAnnotations != nil {
keys := sets.NewString()
if len(spec.AuditAnnotations) > maxAuditAnnotations {
allErrors = append(allErrors, field.Invalid(fldPath.Child("auditAnnotations"), spec.AuditAnnotations, fmt.Sprintf("must not have more than %d auditAnnotations", maxAuditAnnotations)))
}
for i, auditAnnotation := range spec.AuditAnnotations {
allErrors = append(allErrors, validateAuditAnnotation(meta, &auditAnnotation, spec.ParamKind, fldPath.Child("auditAnnotations").Index(i))...)
if keys.Has(auditAnnotation.Key) {
allErrors = append(allErrors, field.Duplicate(fldPath.Child("auditAnnotations").Index(i).Child("key"), auditAnnotation.Key))
}
keys.Insert(auditAnnotation.Key)
}
}
}
return allErrors
}
@ -712,6 +734,33 @@ func validateMatchResources(mc *admissionregistration.MatchResources, fldPath *f
return allErrors
}
var validValidationActions = sets.NewString(
string(admissionregistration.Deny),
string(admissionregistration.Warn),
string(admissionregistration.Audit),
)
func validateValidationActions(va []admissionregistration.ValidationAction, fldPath *field.Path) field.ErrorList {
var allErrors field.ErrorList
actions := sets.NewString()
for i, action := range va {
if !validValidationActions.Has(string(action)) {
allErrors = append(allErrors, field.NotSupported(fldPath.Index(i), action, validValidationActions.List()))
}
if actions.Has(string(action)) {
allErrors = append(allErrors, field.Duplicate(fldPath.Index(i), action))
}
actions.Insert(string(action))
}
if actions.Has(string(admissionregistration.Deny)) && actions.Has(string(admissionregistration.Warn)) {
allErrors = append(allErrors, field.Invalid(fldPath, va, "must not contain both Deny and Warn (repeating the same validation failure information in the API response and headers serves no purpose)"))
}
if len(actions) == 0 {
allErrors = append(allErrors, field.Required(fldPath, "at least one validation action is required"))
}
return allErrors
}
func validateNamedRuleWithOperations(n *admissionregistration.NamedRuleWithOperations, fldPath *field.Path) field.ErrorList {
var allErrors field.ErrorList
resourceNames := sets.NewString()
@ -767,6 +816,38 @@ func validateValidation(v *admissionregistration.Validation, paramKind *admissio
return allErrors
}
func validateAuditAnnotation(meta metav1.ObjectMeta, v *admissionregistration.AuditAnnotation, paramKind *admissionregistration.ParamKind, fldPath *field.Path) field.ErrorList {
var allErrors field.ErrorList
if len(meta.GetName()) != 0 {
name := meta.GetName()
allErrors = append(allErrors, apivalidation.ValidateQualifiedName(name+"/"+v.Key, fldPath.Child("key"))...)
} else {
allErrors = append(allErrors, field.Invalid(fldPath.Child("key"), v.Key, "requires metadata.name be non-empty"))
}
trimmedValueExpression := strings.TrimSpace(v.ValueExpression)
if len(trimmedValueExpression) == 0 {
allErrors = append(allErrors, field.Required(fldPath.Child("valueExpression"), "valueExpression is not specified"))
} else if len(trimmedValueExpression) > maxAuditAnnotationValueExpressionLength {
allErrors = append(allErrors, field.Required(fldPath.Child("valueExpression"), fmt.Sprintf("must not exceed %d bytes in length", maxAuditAnnotationValueExpressionLength)))
} else {
result := plugincel.CompileCELExpression(&validatingadmissionpolicy.AuditAnnotationCondition{
ValueExpression: trimmedValueExpression,
}, plugincel.OptionalVariableDeclarations{HasParams: paramKind != nil, HasAuthorizer: true}, celconfig.PerCallLimit)
if result.Error != nil {
switch result.Error.Type {
case cel.ErrorTypeRequired:
allErrors = append(allErrors, field.Required(fldPath.Child("valueExpression"), result.Error.Detail))
case cel.ErrorTypeInvalid:
allErrors = append(allErrors, field.Invalid(fldPath.Child("valueExpression"), v.ValueExpression, result.Error.Detail))
default:
allErrors = append(allErrors, field.InternalError(fldPath.Child("valueExpression"), result.Error))
}
}
}
return allErrors
}
var newlineMatcher = regexp.MustCompile(`[\n\r]+`) // valid newline chars in CEL grammar
func hasNewlines(s string) bool {
return newlineMatcher.MatchString(s)
@ -796,6 +877,7 @@ func validateValidatingAdmissionPolicyBindingSpec(spec *admissionregistration.Va
}
allErrors = append(allErrors, validateParamRef(spec.ParamRef, fldPath.Child("paramRef"))...)
allErrors = append(allErrors, validateMatchResources(spec.MatchResources, fldPath.Child("matchResouces"))...)
allErrors = append(allErrors, validateValidationActions(spec.ValidationActions, fldPath.Child("validationActions"))...)
return allErrors
}

View File

@ -21,6 +21,7 @@ import (
"testing"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/kubernetes/pkg/apis/admissionregistration"
)
@ -1999,7 +2000,7 @@ func TestValidateValidatingAdmissionPolicy(t *testing.T) {
Spec: admissionregistration.ValidatingAdmissionPolicySpec{},
},
expectedError: `spec.validations: Required value`,
expectedError: `spec.validations: Required value: validations or auditAnnotations must contain at least one item`,
},
{
name: "Invalid Validations Reason",
@ -2565,6 +2566,112 @@ func TestValidateValidatingAdmissionPolicy(t *testing.T) {
},
expectedError: `spec.validations[0].expression: Invalid value: "object.x in [1, 2, ": compilation failed: ERROR: <input>:1:19: Syntax error: missing ']' at '<EOF>`,
},
{
name: "invalid auditAnnotations key due to key name",
config: &admissionregistration.ValidatingAdmissionPolicy{
ObjectMeta: metav1.ObjectMeta{
Name: "config",
},
Spec: admissionregistration.ValidatingAdmissionPolicySpec{
AuditAnnotations: []admissionregistration.AuditAnnotation{
{
Key: "@",
ValueExpression: "value",
},
},
},
},
expectedError: `spec.auditAnnotations[0].key: Invalid value: "config/@": name part must consist of alphanumeric characters`,
},
{
name: "auditAnnotations keys must be unique",
config: &admissionregistration.ValidatingAdmissionPolicy{
ObjectMeta: metav1.ObjectMeta{
Name: "config",
},
Spec: admissionregistration.ValidatingAdmissionPolicySpec{
AuditAnnotations: []admissionregistration.AuditAnnotation{
{
Key: "a",
ValueExpression: "'1'",
},
{
Key: "a",
ValueExpression: "'2'",
},
},
},
},
expectedError: `spec.auditAnnotations[1].key: Duplicate value: "a"`,
},
{
name: "invalid auditAnnotations key due to metadata.name",
config: &admissionregistration.ValidatingAdmissionPolicy{
ObjectMeta: metav1.ObjectMeta{
Name: "nope!",
},
Spec: admissionregistration.ValidatingAdmissionPolicySpec{
AuditAnnotations: []admissionregistration.AuditAnnotation{
{
Key: "key",
ValueExpression: "'value'",
},
},
},
},
expectedError: `spec.auditAnnotations[0].key: Invalid value: "nope!/key": prefix part a lowercase RFC 1123 subdomain`,
},
{
name: "invalid auditAnnotations key due to length",
config: &admissionregistration.ValidatingAdmissionPolicy{
ObjectMeta: metav1.ObjectMeta{
Name: "this-is-a-long-name-for-a-admission-policy-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
},
Spec: admissionregistration.ValidatingAdmissionPolicySpec{
AuditAnnotations: []admissionregistration.AuditAnnotation{
{
Key: "this-is-a-long-name-for-an-audit-annotation-key-xxxxxxxxxxxxxxxxxxxxxxxxxx",
ValueExpression: "'value'",
},
},
},
},
expectedError: `spec.auditAnnotations[0].key: Invalid value`,
},
{
name: "invalid auditAnnotations valueExpression type",
config: &admissionregistration.ValidatingAdmissionPolicy{
ObjectMeta: metav1.ObjectMeta{
Name: "config",
},
Spec: admissionregistration.ValidatingAdmissionPolicySpec{
AuditAnnotations: []admissionregistration.AuditAnnotation{
{
Key: "something",
ValueExpression: "true",
},
},
},
},
expectedError: `spec.auditAnnotations[0].valueExpression: Invalid value: "true": must evaluate to one of [string null_type]`,
},
{
name: "invalid auditAnnotations valueExpression",
config: &admissionregistration.ValidatingAdmissionPolicy{
ObjectMeta: metav1.ObjectMeta{
Name: "config",
},
Spec: admissionregistration.ValidatingAdmissionPolicySpec{
AuditAnnotations: []admissionregistration.AuditAnnotation{
{
Key: "something",
ValueExpression: "object.x in [1, 2, ",
},
},
},
},
expectedError: `spec.auditAnnotations[0].valueExpression: Invalid value: "object.x in [1, 2, ": compilation failed: ERROR: <input>:1:19: Syntax error: missing ']' at '<EOF>`,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
@ -2580,7 +2687,6 @@ func TestValidateValidatingAdmissionPolicy(t *testing.T) {
}
}
})
}
}
@ -2709,6 +2815,7 @@ func TestValidateValidatingAdmissionPolicyUpdate(t *testing.T) {
Spec: admissionregistration.ValidatingAdmissionPolicySpec{},
},
},
// TODO: CustomAuditAnnotations: string valueExpression with {oldObject} is allowed
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
@ -2902,6 +3009,7 @@ func TestValidateValidatingAdmissionPolicyBinding(t *testing.T) {
ParamRef: &admissionregistration.ParamRef{
Name: "xyzlimit-scale-setting.example.com",
},
ValidationActions: []admissionregistration.ValidationAction{admissionregistration.Deny},
MatchResources: &admissionregistration.MatchResources{
ResourceRules: []admissionregistration.NamedRuleWithOperations{
{
@ -2931,6 +3039,7 @@ func TestValidateValidatingAdmissionPolicyBinding(t *testing.T) {
ParamRef: &admissionregistration.ParamRef{
Name: "xyzlimit-scale-setting.example.com",
},
ValidationActions: []admissionregistration.ValidationAction{admissionregistration.Deny},
MatchResources: &admissionregistration.MatchResources{
NamespaceSelector: &metav1.LabelSelector{
MatchLabels: map[string]string{"a": "b"},
@ -2969,6 +3078,7 @@ func TestValidateValidatingAdmissionPolicyBinding(t *testing.T) {
ParamRef: &admissionregistration.ParamRef{
Name: "xyzlimit-scale-setting.example.com",
},
ValidationActions: []admissionregistration.ValidationAction{admissionregistration.Deny},
MatchResources: &admissionregistration.MatchResources{
ResourceRules: []admissionregistration.NamedRuleWithOperations{
{
@ -2998,6 +3108,7 @@ func TestValidateValidatingAdmissionPolicyBinding(t *testing.T) {
ParamRef: &admissionregistration.ParamRef{
Name: "xyzlimit-scale-setting.example.com",
},
ValidationActions: []admissionregistration.ValidationAction{admissionregistration.Deny},
MatchResources: &admissionregistration.MatchResources{
ResourceRules: []admissionregistration.NamedRuleWithOperations{
{
@ -3027,6 +3138,7 @@ func TestValidateValidatingAdmissionPolicyBinding(t *testing.T) {
ParamRef: &admissionregistration.ParamRef{
Name: "xyzlimit-scale-setting.example.com",
},
ValidationActions: []admissionregistration.ValidationAction{admissionregistration.Deny},
MatchResources: &admissionregistration.MatchResources{
NamespaceSelector: &metav1.LabelSelector{
MatchLabels: map[string]string{"a": "b"},
@ -3065,6 +3177,7 @@ func TestValidateValidatingAdmissionPolicyBinding(t *testing.T) {
ParamRef: &admissionregistration.ParamRef{
Name: "xyzlimit-scale-setting.example.com",
},
ValidationActions: []admissionregistration.ValidationAction{admissionregistration.Deny},
MatchResources: &admissionregistration.MatchResources{
ResourceRules: []admissionregistration.NamedRuleWithOperations{
{
@ -3094,6 +3207,7 @@ func TestValidateValidatingAdmissionPolicyBinding(t *testing.T) {
ParamRef: &admissionregistration.ParamRef{
Name: "xyzlimit-scale-setting.example.com",
},
ValidationActions: []admissionregistration.ValidationAction{admissionregistration.Deny},
MatchResources: &admissionregistration.MatchResources{
ResourceRules: []admissionregistration.NamedRuleWithOperations{
{
@ -3112,6 +3226,38 @@ func TestValidateValidatingAdmissionPolicyBinding(t *testing.T) {
},
expectedError: `spec.matchResouces.resourceRules[0].resources: Invalid value: []string{"*/*", "a"}: if '*/*' is present, must not specify other resources`,
},
{
name: "validationActions must be unique",
config: &admissionregistration.ValidatingAdmissionPolicyBinding{
ObjectMeta: metav1.ObjectMeta{
Name: "config",
},
Spec: admissionregistration.ValidatingAdmissionPolicyBindingSpec{
PolicyName: "xyzlimit-scale.example.com",
ParamRef: &admissionregistration.ParamRef{
Name: "xyzlimit-scale-setting.example.com",
},
ValidationActions: []admissionregistration.ValidationAction{admissionregistration.Deny, admissionregistration.Deny},
},
},
expectedError: `spec.validationActions[1]: Duplicate value: "Deny"`,
},
{
name: "validationActions must contain supported values",
config: &admissionregistration.ValidatingAdmissionPolicyBinding{
ObjectMeta: metav1.ObjectMeta{
Name: "config",
},
Spec: admissionregistration.ValidatingAdmissionPolicyBindingSpec{
PolicyName: "xyzlimit-scale.example.com",
ParamRef: &admissionregistration.ParamRef{
Name: "xyzlimit-scale-setting.example.com",
},
ValidationActions: []admissionregistration.ValidationAction{admissionregistration.ValidationAction("illegal")},
},
},
expectedError: `Unsupported value: "illegal": supported values: "Audit", "Deny", "Warn"`,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
@ -3149,6 +3295,7 @@ func TestValidateValidatingAdmissionPolicyBindingUpdate(t *testing.T) {
ParamRef: &admissionregistration.ParamRef{
Name: "xyzlimit-scale-setting.example.com",
},
ValidationActions: []admissionregistration.ValidationAction{admissionregistration.Deny},
MatchResources: &admissionregistration.MatchResources{
NamespaceSelector: &metav1.LabelSelector{
MatchLabels: map[string]string{"a": "b"},
@ -3184,6 +3331,7 @@ func TestValidateValidatingAdmissionPolicyBindingUpdate(t *testing.T) {
ParamRef: &admissionregistration.ParamRef{
Name: "xyzlimit-scale-setting.example.com",
},
ValidationActions: []admissionregistration.ValidationAction{admissionregistration.Deny},
MatchResources: &admissionregistration.MatchResources{
NamespaceSelector: &metav1.LabelSelector{
MatchLabels: map[string]string{"a": "b"},
@ -3222,6 +3370,7 @@ func TestValidateValidatingAdmissionPolicyBindingUpdate(t *testing.T) {
ParamRef: &admissionregistration.ParamRef{
Name: "xyzlimit-scale-setting.example.com",
},
ValidationActions: []admissionregistration.ValidationAction{admissionregistration.Deny},
MatchResources: &admissionregistration.MatchResources{
NamespaceSelector: &metav1.LabelSelector{
MatchLabels: map[string]string{"a": "b"},

View File

@ -26,6 +26,22 @@ import (
runtime "k8s.io/apimachinery/pkg/runtime"
)
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *AuditAnnotation) DeepCopyInto(out *AuditAnnotation) {
*out = *in
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AuditAnnotation.
func (in *AuditAnnotation) DeepCopy() *AuditAnnotation {
if in == nil {
return nil
}
out := new(AuditAnnotation)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *MatchResources) DeepCopyInto(out *MatchResources) {
*out = *in
@ -434,6 +450,11 @@ func (in *ValidatingAdmissionPolicyBindingSpec) DeepCopyInto(out *ValidatingAdmi
*out = new(MatchResources)
(*in).DeepCopyInto(*out)
}
if in.ValidationActions != nil {
in, out := &in.ValidationActions, &out.ValidationActions
*out = make([]ValidationAction, len(*in))
copy(*out, *in)
}
return
}
@ -505,6 +526,11 @@ func (in *ValidatingAdmissionPolicySpec) DeepCopyInto(out *ValidatingAdmissionPo
*out = new(FailurePolicyType)
**out = **in
}
if in.AuditAnnotations != nil {
in, out := &in.AuditAnnotations, &out.AuditAnnotations
*out = make([]AuditAnnotation, len(*in))
copy(*out, *in)
}
return
}

View File

@ -45,6 +45,7 @@ func GetOpenAPIDefinitions(ref common.ReferenceCallback) map[string]common.OpenA
"k8s.io/api/admissionregistration/v1.ValidatingWebhookConfiguration": schema_k8sio_api_admissionregistration_v1_ValidatingWebhookConfiguration(ref),
"k8s.io/api/admissionregistration/v1.ValidatingWebhookConfigurationList": schema_k8sio_api_admissionregistration_v1_ValidatingWebhookConfigurationList(ref),
"k8s.io/api/admissionregistration/v1.WebhookClientConfig": schema_k8sio_api_admissionregistration_v1_WebhookClientConfig(ref),
"k8s.io/api/admissionregistration/v1alpha1.AuditAnnotation": schema_k8sio_api_admissionregistration_v1alpha1_AuditAnnotation(ref),
"k8s.io/api/admissionregistration/v1alpha1.MatchResources": schema_k8sio_api_admissionregistration_v1alpha1_MatchResources(ref),
"k8s.io/api/admissionregistration/v1alpha1.NamedRuleWithOperations": schema_k8sio_api_admissionregistration_v1alpha1_NamedRuleWithOperations(ref),
"k8s.io/api/admissionregistration/v1alpha1.ParamKind": schema_k8sio_api_admissionregistration_v1alpha1_ParamKind(ref),
@ -1856,6 +1857,36 @@ func schema_k8sio_api_admissionregistration_v1_WebhookClientConfig(ref common.Re
}
}
func schema_k8sio_api_admissionregistration_v1alpha1_AuditAnnotation(ref common.ReferenceCallback) common.OpenAPIDefinition {
return common.OpenAPIDefinition{
Schema: spec.Schema{
SchemaProps: spec.SchemaProps{
Description: "AuditAnnotation describes how to produce an audit annotation for an API request.",
Type: []string{"object"},
Properties: map[string]spec.Schema{
"key": {
SchemaProps: spec.SchemaProps{
Description: "key specifies the audit annotation key. The audit annotation keys of a ValidatingAdmissionPolicy must be unique. The key must be a qualified name ([A-Za-z0-9][-A-Za-z0-9_.]*) no more than 63 bytes in length.\n\nThe key is combined with the resource name of the ValidatingAdmissionPolicy to construct an audit annotation key: \"{ValidatingAdmissionPolicy name}/{key}\".\n\nIf an admission webhook uses the same resource name as this ValidatingAdmissionPolicy and the same audit annotation key, the annotation key will be identical. In this case, the first annotation written with the key will be included in the audit event and all subsequent annotations with the same key will be discarded.\n\nRequired.",
Default: "",
Type: []string{"string"},
Format: "",
},
},
"valueExpression": {
SchemaProps: spec.SchemaProps{
Description: "valueExpression represents the expression which is evaluated by CEL to produce an audit annotation value. The expression must evaluate to either a string or null value. If the expression evaluates to a string, the audit annotation is included with the string value. If the expression evaluates to null or empty string the audit annotation will be omitted. The valueExpression may be no longer than 5kb in length. If the result of the valueExpression is more than 10kb in length, it will be truncated to 10kb.\n\nIf multiple ValidatingAdmissionPolicyBinding resources match an API request, then the valueExpression will be evaluated for each binding. All unique values produced by the valueExpressions will be joined together in a comma-separated list.\n\nRequired.",
Default: "",
Type: []string{"string"},
Format: "",
},
},
},
Required: []string{"key", "valueExpression"},
},
},
}
}
func schema_k8sio_api_admissionregistration_v1alpha1_MatchResources(ref common.ReferenceCallback) common.OpenAPIDefinition {
return common.OpenAPIDefinition{
Schema: spec.Schema{
@ -2285,6 +2316,26 @@ func schema_k8sio_api_admissionregistration_v1alpha1_ValidatingAdmissionPolicyBi
Ref: ref("k8s.io/api/admissionregistration/v1alpha1.MatchResources"),
},
},
"validationActions": {
VendorExtensible: spec.VendorExtensible{
Extensions: spec.Extensions{
"x-kubernetes-list-type": "set",
},
},
SchemaProps: spec.SchemaProps{
Description: "validationActions declares how Validations of the referenced ValidatingAdmissionPolicy are enforced. If a validation evaluates to false it is always enforced according to these actions.\n\nFailures defined by the ValidatingAdmissionPolicy's FailurePolicy are enforced according to these actions only if the FailurePolicy is set to Fail, otherwise the failures are ignored. This includes compilation errors, runtime errors and misconfigurations of the policy.\n\nvalidationActions is declared as a set of action values. Order does not matter. validationActions may not contain duplicates of the same action.\n\nThe supported actions values are:\n\n\"Deny\" specifies that a validation failure results in a denied request.\n\n\"Warn\" specifies that a validation failure is reported to the request client in HTTP Warning headers, with a warning code of 299. Warnings can be sent both for allowed or denied admission responses.\n\n\"Audit\" specifies that a validation failure is included in the published audit event for the request. The audit event will contain a `validation.policy.admission.k8s.io/validation_failure` audit annotation with a value containing the details of the validation failures, formatted as a JSON list of objects, each with the following fields: - message: The validation failure message string - policy: The resource name of the ValidatingAdmissionPolicy - binding: The resource name of the ValidatingAdmissionPolicyBinding - expressionIndex: The index of the failed validations in the ValidatingAdmissionPolicy - validationActions: The enforcement actions enacted for the validation failure Example audit annotation: `\"validation.policy.admission.k8s.io/validation_failure\": \"[{\"message\": \"Invalid value\", {\"policy\": \"policy.example.com\", {\"binding\": \"policybinding.example.com\", {\"expressionIndex\": \"1\", {\"validationActions\": [\"Audit\"]}]\"`\n\nClients should expect to handle additional values by ignoring any values not recognized.\n\n\"Deny\" and \"Warn\" may not be used together since this combination needlessly duplicates the validation failure both in the API response body and the HTTP warning headers.\n\nRequired.",
Type: []string{"array"},
Items: &spec.SchemaOrArray{
Schema: &spec.Schema{
SchemaProps: spec.SchemaProps{
Default: "",
Type: []string{"string"},
Format: "",
},
},
},
},
},
},
},
},
@ -2369,7 +2420,7 @@ func schema_k8sio_api_admissionregistration_v1alpha1_ValidatingAdmissionPolicySp
},
},
SchemaProps: spec.SchemaProps{
Description: "Validations contain CEL expressions which is used to apply the validation. A minimum of one validation is required for a policy definition. Required.",
Description: "Validations contain CEL expressions which is used to apply the validation. Validations and AuditAnnotations may not both be empty; a minimum of one Validations or AuditAnnotations is required.",
Type: []string{"array"},
Items: &spec.SchemaOrArray{
Schema: &spec.Schema{
@ -2383,18 +2434,36 @@ func schema_k8sio_api_admissionregistration_v1alpha1_ValidatingAdmissionPolicySp
},
"failurePolicy": {
SchemaProps: spec.SchemaProps{
Description: "FailurePolicy defines how to handle failures for the admission policy. Failures can occur from invalid or mis-configured policy definitions or bindings. A policy is invalid if spec.paramKind refers to a non-existent Kind. A binding is invalid if spec.paramRef.name refers to a non-existent resource. Allowed values are Ignore or Fail. Defaults to Fail.\n\nPossible enum values:\n - `\"Fail\"` means that an error calling the webhook causes the admission to fail.\n - `\"Ignore\"` means that an error calling the webhook is ignored.",
Description: "failurePolicy defines how to handle failures for the admission policy. Failures can occur from CEL expression parse errors, type check errors, runtime errors and invalid or mis-configured policy definitions or bindings.\n\nA policy is invalid if spec.paramKind refers to a non-existent Kind. A binding is invalid if spec.paramRef.name refers to a non-existent resource.\n\nfailurePolicy does not define how validations that evaluate to false are handled.\n\nWhen failurePolicy is set to Fail, ValidatingAdmissionPolicyBinding validationActions define how failures are enforced.\n\nAllowed values are Ignore or Fail. Defaults to Fail.\n\nPossible enum values:\n - `\"Fail\"` means that an error calling the webhook causes the admission to fail.\n - `\"Ignore\"` means that an error calling the webhook is ignored.",
Type: []string{"string"},
Format: "",
Enum: []interface{}{"Fail", "Ignore"},
},
},
"auditAnnotations": {
VendorExtensible: spec.VendorExtensible{
Extensions: spec.Extensions{
"x-kubernetes-list-type": "atomic",
},
},
SchemaProps: spec.SchemaProps{
Description: "auditAnnotations contains CEL expressions which are used to produce audit annotations for the audit event of the API request. validations and auditAnnotations may not both be empty; a least one of validations or auditAnnotations is required.",
Type: []string{"array"},
Items: &spec.SchemaOrArray{
Schema: &spec.Schema{
SchemaProps: spec.SchemaProps{
Default: map[string]interface{}{},
Ref: ref("k8s.io/api/admissionregistration/v1alpha1.AuditAnnotation"),
},
},
},
},
},
},
Required: []string{"validations"},
},
},
Dependencies: []string{
"k8s.io/api/admissionregistration/v1alpha1.MatchResources", "k8s.io/api/admissionregistration/v1alpha1.ParamKind", "k8s.io/api/admissionregistration/v1alpha1.Validation"},
"k8s.io/api/admissionregistration/v1alpha1.AuditAnnotation", "k8s.io/api/admissionregistration/v1alpha1.MatchResources", "k8s.io/api/admissionregistration/v1alpha1.ParamKind", "k8s.io/api/admissionregistration/v1alpha1.Validation"},
}
}
@ -2407,7 +2476,7 @@ func schema_k8sio_api_admissionregistration_v1alpha1_Validation(ref common.Refer
Properties: map[string]spec.Schema{
"expression": {
SchemaProps: spec.SchemaProps{
Description: "Expression represents the expression which will be evaluated by CEL. ref: https://github.com/google/cel-spec CEL expressions have access to the contents of the Admission request/response, organized into CEL variables as well as some other useful variables:\n\n- 'object' - The object from the incoming request. The value is null for DELETE requests. - 'oldObject' - The existing object. The value is null for CREATE requests. - 'request' - Attributes of the admission request([ref](/pkg/apis/admission/types.go#AdmissionRequest)). - 'params' - Parameter resource referred to by the policy binding being evaluated. Only populated if the policy has a ParamKind. - 'authorizer' - A CEL Authorizer. May be used to perform authorization checks for the principal (user or service account) of the request.\n See https://pkg.go.dev/k8s.io/apiserver/pkg/cel/library#Authz\n- 'authorizer.requestResource' - A CEL ResourceCheck constructed from the 'authorizer' and configured with the\n request resource.\n\nThe `apiVersion`, `kind`, `metadata.name` and `metadata.generateName` are always accessible from the root of the object. No other metadata properties are accessible.\n\nOnly property names of the form `[a-zA-Z_.-/][a-zA-Z0-9_.-/]*` are accessible. Accessible property names are escaped according to the following rules when accessed in the expression: - '__' escapes to '__underscores__' - '.' escapes to '__dot__' - '-' escapes to '__dash__' - '/' escapes to '__slash__' - Property names that exactly match a CEL RESERVED keyword escape to '__{keyword}__'. The keywords are:\n\t \"true\", \"false\", \"null\", \"in\", \"as\", \"break\", \"const\", \"continue\", \"else\", \"for\", \"function\", \"if\",\n\t \"import\", \"let\", \"loop\", \"package\", \"namespace\", \"return\".\nExamples:\n - Expression accessing a property named \"namespace\": {\"Expression\": \"object.__namespace__ > 0\"}\n - Expression accessing a property named \"x-prop\": {\"Expression\": \"object.x__dash__prop > 0\"}\n - Expression accessing a property named \"redact__d\": {\"Expression\": \"object.redact__underscores__d > 0\"}\n\nEquality on arrays with list type of 'set' or 'map' ignores element order, i.e. [1, 2] == [2, 1]. Concatenation on arrays with x-kubernetes-list-type use the semantics of the list type:\n - 'set': `X + Y` performs a union where the array positions of all elements in `X` are preserved and\n non-intersecting elements in `Y` are appended, retaining their partial order.\n - 'map': `X + Y` performs a merge where the array positions of all keys in `X` are preserved but the values\n are overwritten by values in `Y` when the key sets of `X` and `Y` intersect. Elements in `Y` with\n non-intersecting keys are appended, retaining their partial order.\nRequired.",
Description: "Expression represents the expression which will be evaluated by CEL. ref: https://github.com/google/cel-spec CEL expressions have access to the contents of the API request/response, organized into CEL variables as well as some other useful variables:\n\n- 'object' - The object from the incoming request. The value is null for DELETE requests. - 'oldObject' - The existing object. The value is null for CREATE requests. - 'request' - Attributes of the API request([ref](/pkg/apis/admission/types.go#AdmissionRequest)). - 'params' - Parameter resource referred to by the policy binding being evaluated. Only populated if the policy has a ParamKind. - 'authorizer' - A CEL Authorizer. May be used to perform authorization checks for the principal (user or service account) of the request.\n See https://pkg.go.dev/k8s.io/apiserver/pkg/cel/library#Authz\n- 'authorizer.requestResource' - A CEL ResourceCheck constructed from the 'authorizer' and configured with the\n request resource.\n\nThe `apiVersion`, `kind`, `metadata.name` and `metadata.generateName` are always accessible from the root of the object. No other metadata properties are accessible.\n\nOnly property names of the form `[a-zA-Z_.-/][a-zA-Z0-9_.-/]*` are accessible. Accessible property names are escaped according to the following rules when accessed in the expression: - '__' escapes to '__underscores__' - '.' escapes to '__dot__' - '-' escapes to '__dash__' - '/' escapes to '__slash__' - Property names that exactly match a CEL RESERVED keyword escape to '__{keyword}__'. The keywords are:\n\t \"true\", \"false\", \"null\", \"in\", \"as\", \"break\", \"const\", \"continue\", \"else\", \"for\", \"function\", \"if\",\n\t \"import\", \"let\", \"loop\", \"package\", \"namespace\", \"return\".\nExamples:\n - Expression accessing a property named \"namespace\": {\"Expression\": \"object.__namespace__ > 0\"}\n - Expression accessing a property named \"x-prop\": {\"Expression\": \"object.x__dash__prop > 0\"}\n - Expression accessing a property named \"redact__d\": {\"Expression\": \"object.redact__underscores__d > 0\"}\n\nEquality on arrays with list type of 'set' or 'map' ignores element order, i.e. [1, 2] == [2, 1]. Concatenation on arrays with x-kubernetes-list-type use the semantics of the list type:\n - 'set': `X + Y` performs a union where the array positions of all elements in `X` are preserved and\n non-intersecting elements in `Y` are appended, retaining their partial order.\n - 'map': `X + Y` performs a merge where the array positions of all keys in `X` are preserved but the values\n are overwritten by values in `Y` when the key sets of `X` and `Y` intersect. Elements in `Y` with\n non-intersecting keys are appended, retaining their partial order.\nRequired.",
Default: "",
Type: []string{"string"},
Format: "",

View File

@ -27,6 +27,7 @@ import (
"k8s.io/apiserver/pkg/registry/generic"
genericregistrytest "k8s.io/apiserver/pkg/registry/generic/testing"
etcd3testing "k8s.io/apiserver/pkg/storage/etcd3/testing"
"k8s.io/kubernetes/pkg/apis/admissionregistration"
"k8s.io/kubernetes/pkg/registry/admissionregistration/resolver"
"k8s.io/kubernetes/pkg/registry/registrytest"
@ -127,6 +128,7 @@ func validPolicyBinding() *admissionregistration.ValidatingAdmissionPolicyBindin
ParamRef: &admissionregistration.ParamRef{
Name: "param-test",
},
ValidationActions: []admissionregistration.ValidationAction{admissionregistration.Deny},
MatchResources: &admissionregistration.MatchResources{
MatchPolicy: func() *admissionregistration.MatchPolicyType {
r := admissionregistration.MatchPolicyType("Exact")
@ -166,7 +168,8 @@ func newPolicyBinding(name string) *admissionregistration.ValidatingAdmissionPol
ParamRef: &admissionregistration.ParamRef{
Name: "param-test",
},
MatchResources: &admissionregistration.MatchResources{},
ValidationActions: []admissionregistration.ValidationAction{admissionregistration.Deny},
MatchResources: &admissionregistration.MatchResources{},
},
}
}

View File

@ -21,6 +21,7 @@ import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
genericapirequest "k8s.io/apiserver/pkg/endpoints/request"
"k8s.io/kubernetes/pkg/apis/admissionregistration"
)
@ -59,6 +60,7 @@ func validPolicyBinding() *admissionregistration.ValidatingAdmissionPolicyBindin
ParamRef: &admissionregistration.ParamRef{
Name: "replica-limit-test.example.com",
},
ValidationActions: []admissionregistration.ValidationAction{admissionregistration.Deny},
},
}
}

View File

@ -45,10 +45,38 @@ var _ = math.Inf
// proto package needs to be updated.
const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package
func (m *AuditAnnotation) Reset() { *m = AuditAnnotation{} }
func (*AuditAnnotation) ProtoMessage() {}
func (*AuditAnnotation) Descriptor() ([]byte, []int) {
return fileDescriptor_c3be8d256e3ae3cf, []int{0}
}
func (m *AuditAnnotation) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *AuditAnnotation) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
func (m *AuditAnnotation) XXX_Merge(src proto.Message) {
xxx_messageInfo_AuditAnnotation.Merge(m, src)
}
func (m *AuditAnnotation) XXX_Size() int {
return m.Size()
}
func (m *AuditAnnotation) XXX_DiscardUnknown() {
xxx_messageInfo_AuditAnnotation.DiscardUnknown(m)
}
var xxx_messageInfo_AuditAnnotation proto.InternalMessageInfo
func (m *MatchResources) Reset() { *m = MatchResources{} }
func (*MatchResources) ProtoMessage() {}
func (*MatchResources) Descriptor() ([]byte, []int) {
return fileDescriptor_c3be8d256e3ae3cf, []int{0}
return fileDescriptor_c3be8d256e3ae3cf, []int{1}
}
func (m *MatchResources) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
@ -76,7 +104,7 @@ var xxx_messageInfo_MatchResources proto.InternalMessageInfo
func (m *NamedRuleWithOperations) Reset() { *m = NamedRuleWithOperations{} }
func (*NamedRuleWithOperations) ProtoMessage() {}
func (*NamedRuleWithOperations) Descriptor() ([]byte, []int) {
return fileDescriptor_c3be8d256e3ae3cf, []int{1}
return fileDescriptor_c3be8d256e3ae3cf, []int{2}
}
func (m *NamedRuleWithOperations) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
@ -104,7 +132,7 @@ var xxx_messageInfo_NamedRuleWithOperations proto.InternalMessageInfo
func (m *ParamKind) Reset() { *m = ParamKind{} }
func (*ParamKind) ProtoMessage() {}
func (*ParamKind) Descriptor() ([]byte, []int) {
return fileDescriptor_c3be8d256e3ae3cf, []int{2}
return fileDescriptor_c3be8d256e3ae3cf, []int{3}
}
func (m *ParamKind) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
@ -132,7 +160,7 @@ var xxx_messageInfo_ParamKind proto.InternalMessageInfo
func (m *ParamRef) Reset() { *m = ParamRef{} }
func (*ParamRef) ProtoMessage() {}
func (*ParamRef) Descriptor() ([]byte, []int) {
return fileDescriptor_c3be8d256e3ae3cf, []int{3}
return fileDescriptor_c3be8d256e3ae3cf, []int{4}
}
func (m *ParamRef) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
@ -160,7 +188,7 @@ var xxx_messageInfo_ParamRef proto.InternalMessageInfo
func (m *ValidatingAdmissionPolicy) Reset() { *m = ValidatingAdmissionPolicy{} }
func (*ValidatingAdmissionPolicy) ProtoMessage() {}
func (*ValidatingAdmissionPolicy) Descriptor() ([]byte, []int) {
return fileDescriptor_c3be8d256e3ae3cf, []int{4}
return fileDescriptor_c3be8d256e3ae3cf, []int{5}
}
func (m *ValidatingAdmissionPolicy) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
@ -188,7 +216,7 @@ var xxx_messageInfo_ValidatingAdmissionPolicy proto.InternalMessageInfo
func (m *ValidatingAdmissionPolicyBinding) Reset() { *m = ValidatingAdmissionPolicyBinding{} }
func (*ValidatingAdmissionPolicyBinding) ProtoMessage() {}
func (*ValidatingAdmissionPolicyBinding) Descriptor() ([]byte, []int) {
return fileDescriptor_c3be8d256e3ae3cf, []int{5}
return fileDescriptor_c3be8d256e3ae3cf, []int{6}
}
func (m *ValidatingAdmissionPolicyBinding) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
@ -216,7 +244,7 @@ var xxx_messageInfo_ValidatingAdmissionPolicyBinding proto.InternalMessageInfo
func (m *ValidatingAdmissionPolicyBindingList) Reset() { *m = ValidatingAdmissionPolicyBindingList{} }
func (*ValidatingAdmissionPolicyBindingList) ProtoMessage() {}
func (*ValidatingAdmissionPolicyBindingList) Descriptor() ([]byte, []int) {
return fileDescriptor_c3be8d256e3ae3cf, []int{6}
return fileDescriptor_c3be8d256e3ae3cf, []int{7}
}
func (m *ValidatingAdmissionPolicyBindingList) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
@ -244,7 +272,7 @@ var xxx_messageInfo_ValidatingAdmissionPolicyBindingList proto.InternalMessageIn
func (m *ValidatingAdmissionPolicyBindingSpec) Reset() { *m = ValidatingAdmissionPolicyBindingSpec{} }
func (*ValidatingAdmissionPolicyBindingSpec) ProtoMessage() {}
func (*ValidatingAdmissionPolicyBindingSpec) Descriptor() ([]byte, []int) {
return fileDescriptor_c3be8d256e3ae3cf, []int{7}
return fileDescriptor_c3be8d256e3ae3cf, []int{8}
}
func (m *ValidatingAdmissionPolicyBindingSpec) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
@ -272,7 +300,7 @@ var xxx_messageInfo_ValidatingAdmissionPolicyBindingSpec proto.InternalMessageIn
func (m *ValidatingAdmissionPolicyList) Reset() { *m = ValidatingAdmissionPolicyList{} }
func (*ValidatingAdmissionPolicyList) ProtoMessage() {}
func (*ValidatingAdmissionPolicyList) Descriptor() ([]byte, []int) {
return fileDescriptor_c3be8d256e3ae3cf, []int{8}
return fileDescriptor_c3be8d256e3ae3cf, []int{9}
}
func (m *ValidatingAdmissionPolicyList) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
@ -300,7 +328,7 @@ var xxx_messageInfo_ValidatingAdmissionPolicyList proto.InternalMessageInfo
func (m *ValidatingAdmissionPolicySpec) Reset() { *m = ValidatingAdmissionPolicySpec{} }
func (*ValidatingAdmissionPolicySpec) ProtoMessage() {}
func (*ValidatingAdmissionPolicySpec) Descriptor() ([]byte, []int) {
return fileDescriptor_c3be8d256e3ae3cf, []int{9}
return fileDescriptor_c3be8d256e3ae3cf, []int{10}
}
func (m *ValidatingAdmissionPolicySpec) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
@ -328,7 +356,7 @@ var xxx_messageInfo_ValidatingAdmissionPolicySpec proto.InternalMessageInfo
func (m *Validation) Reset() { *m = Validation{} }
func (*Validation) ProtoMessage() {}
func (*Validation) Descriptor() ([]byte, []int) {
return fileDescriptor_c3be8d256e3ae3cf, []int{10}
return fileDescriptor_c3be8d256e3ae3cf, []int{11}
}
func (m *Validation) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
@ -354,6 +382,7 @@ func (m *Validation) XXX_DiscardUnknown() {
var xxx_messageInfo_Validation proto.InternalMessageInfo
func init() {
proto.RegisterType((*AuditAnnotation)(nil), "k8s.io.api.admissionregistration.v1alpha1.AuditAnnotation")
proto.RegisterType((*MatchResources)(nil), "k8s.io.api.admissionregistration.v1alpha1.MatchResources")
proto.RegisterType((*NamedRuleWithOperations)(nil), "k8s.io.api.admissionregistration.v1alpha1.NamedRuleWithOperations")
proto.RegisterType((*ParamKind)(nil), "k8s.io.api.admissionregistration.v1alpha1.ParamKind")
@ -372,73 +401,113 @@ func init() {
}
var fileDescriptor_c3be8d256e3ae3cf = []byte{
// 1054 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xbc, 0x57, 0xcd, 0x6e, 0x1c, 0x45,
0x10, 0xf6, 0xc4, 0x9b, 0xc4, 0xdb, 0x1b, 0x3b, 0x76, 0xe3, 0x88, 0xc5, 0x82, 0xdd, 0xd5, 0x2a,
0x42, 0xf6, 0x81, 0x19, 0xec, 0x04, 0x02, 0x27, 0x94, 0x21, 0x41, 0x44, 0xb1, 0x63, 0xab, 0x8d,
0x12, 0x09, 0x11, 0x89, 0xf6, 0x4c, 0x7b, 0xb6, 0xb3, 0x3b, 0x3f, 0x4c, 0xf7, 0x58, 0xb6, 0x38,
0x80, 0xc4, 0x0b, 0x70, 0xe0, 0x41, 0x38, 0x71, 0xe1, 0x05, 0x7c, 0xcc, 0xd1, 0x5c, 0x46, 0x78,
0xb8, 0xc0, 0x0b, 0x80, 0xe4, 0x13, 0xea, 0x9e, 0x9e, 0xbf, 0xfd, 0xc1, 0xeb, 0x60, 0xe5, 0xb6,
0x5d, 0x3f, 0xdf, 0x57, 0x55, 0x5d, 0x35, 0xd5, 0x0b, 0x50, 0xff, 0x23, 0xa6, 0x53, 0xdf, 0xe8,
0x47, 0x7b, 0x24, 0xf4, 0x08, 0x27, 0xcc, 0x38, 0x20, 0x9e, 0xed, 0x87, 0x86, 0x52, 0xe0, 0x80,
0x1a, 0xd8, 0x76, 0x29, 0x63, 0xd4, 0xf7, 0x42, 0xe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, 0x5b, 0x27, 0x67, 0xf5, 0x99, 0x57, 0x67, 0xf5, 0x99, 0xd3, 0xb3, 0xfa, 0xcc, 0xcb, 0xb0,
0xae, 0x9d, 0x84, 0x75, 0xed, 0x55, 0x58, 0xd7, 0x4e, 0xc3, 0xba, 0xf6, 0x7b, 0x58, 0xd7, 0x7e,
0xfa, 0xa3, 0x3e, 0xf3, 0xd5, 0xca, 0xd4, 0x7f, 0x26, 0xff, 0x0d, 0x00, 0x00, 0xff, 0xff, 0x05,
0xb2, 0x6f, 0x65, 0x91, 0x0e, 0x00, 0x00,
}
func (m *AuditAnnotation) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *AuditAnnotation) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *AuditAnnotation) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
i -= len(m.ValueExpression)
copy(dAtA[i:], m.ValueExpression)
i = encodeVarintGenerated(dAtA, i, uint64(len(m.ValueExpression)))
i--
dAtA[i] = 0x12
i -= len(m.Key)
copy(dAtA[i:], m.Key)
i = encodeVarintGenerated(dAtA, i, uint64(len(m.Key)))
i--
dAtA[i] = 0xa
return len(dAtA) - i, nil
}
func (m *MatchResources) Marshal() (dAtA []byte, err error) {
@ -784,6 +853,15 @@ func (m *ValidatingAdmissionPolicyBindingSpec) MarshalToSizedBuffer(dAtA []byte)
_ = i
var l int
_ = l
if len(m.ValidationActions) > 0 {
for iNdEx := len(m.ValidationActions) - 1; iNdEx >= 0; iNdEx-- {
i -= len(m.ValidationActions[iNdEx])
copy(dAtA[i:], m.ValidationActions[iNdEx])
i = encodeVarintGenerated(dAtA, i, uint64(len(m.ValidationActions[iNdEx])))
i--
dAtA[i] = 0x22
}
}
if m.MatchResources != nil {
{
size, err := m.MatchResources.MarshalToSizedBuffer(dAtA[:i])
@ -883,6 +961,20 @@ func (m *ValidatingAdmissionPolicySpec) MarshalToSizedBuffer(dAtA []byte) (int,
_ = i
var l int
_ = l
if len(m.AuditAnnotations) > 0 {
for iNdEx := len(m.AuditAnnotations) - 1; iNdEx >= 0; iNdEx-- {
{
size, err := m.AuditAnnotations[iNdEx].MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintGenerated(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x2a
}
}
if m.FailurePolicy != nil {
i -= len(*m.FailurePolicy)
copy(dAtA[i:], *m.FailurePolicy)
@ -982,6 +1074,19 @@ func encodeVarintGenerated(dAtA []byte, offset int, v uint64) int {
dAtA[offset] = uint8(v)
return base
}
func (m *AuditAnnotation) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.Key)
n += 1 + l + sovGenerated(uint64(l))
l = len(m.ValueExpression)
n += 1 + l + sovGenerated(uint64(l))
return n
}
func (m *MatchResources) Size() (n int) {
if m == nil {
return 0
@ -1117,6 +1222,12 @@ func (m *ValidatingAdmissionPolicyBindingSpec) Size() (n int) {
l = m.MatchResources.Size()
n += 1 + l + sovGenerated(uint64(l))
}
if len(m.ValidationActions) > 0 {
for _, s := range m.ValidationActions {
l = len(s)
n += 1 + l + sovGenerated(uint64(l))
}
}
return n
}
@ -1161,6 +1272,12 @@ func (m *ValidatingAdmissionPolicySpec) Size() (n int) {
l = len(*m.FailurePolicy)
n += 1 + l + sovGenerated(uint64(l))
}
if len(m.AuditAnnotations) > 0 {
for _, e := range m.AuditAnnotations {
l = e.Size()
n += 1 + l + sovGenerated(uint64(l))
}
}
return n
}
@ -1187,6 +1304,17 @@ func sovGenerated(x uint64) (n int) {
func sozGenerated(x uint64) (n int) {
return sovGenerated(uint64((x << 1) ^ uint64((int64(x) >> 63))))
}
func (this *AuditAnnotation) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&AuditAnnotation{`,
`Key:` + fmt.Sprintf("%v", this.Key) + `,`,
`ValueExpression:` + fmt.Sprintf("%v", this.ValueExpression) + `,`,
`}`,
}, "")
return s
}
func (this *MatchResources) String() string {
if this == nil {
return "nil"
@ -1290,6 +1418,7 @@ func (this *ValidatingAdmissionPolicyBindingSpec) String() string {
`PolicyName:` + fmt.Sprintf("%v", this.PolicyName) + `,`,
`ParamRef:` + strings.Replace(this.ParamRef.String(), "ParamRef", "ParamRef", 1) + `,`,
`MatchResources:` + strings.Replace(this.MatchResources.String(), "MatchResources", "MatchResources", 1) + `,`,
`ValidationActions:` + fmt.Sprintf("%v", this.ValidationActions) + `,`,
`}`,
}, "")
return s
@ -1319,11 +1448,17 @@ func (this *ValidatingAdmissionPolicySpec) String() string {
repeatedStringForValidations += strings.Replace(strings.Replace(f.String(), "Validation", "Validation", 1), `&`, ``, 1) + ","
}
repeatedStringForValidations += "}"
repeatedStringForAuditAnnotations := "[]AuditAnnotation{"
for _, f := range this.AuditAnnotations {
repeatedStringForAuditAnnotations += strings.Replace(strings.Replace(f.String(), "AuditAnnotation", "AuditAnnotation", 1), `&`, ``, 1) + ","
}
repeatedStringForAuditAnnotations += "}"
s := strings.Join([]string{`&ValidatingAdmissionPolicySpec{`,
`ParamKind:` + strings.Replace(this.ParamKind.String(), "ParamKind", "ParamKind", 1) + `,`,
`MatchConstraints:` + strings.Replace(this.MatchConstraints.String(), "MatchResources", "MatchResources", 1) + `,`,
`Validations:` + repeatedStringForValidations + `,`,
`FailurePolicy:` + valueToStringGenerated(this.FailurePolicy) + `,`,
`AuditAnnotations:` + repeatedStringForAuditAnnotations + `,`,
`}`,
}, "")
return s
@ -1348,6 +1483,120 @@ func valueToStringGenerated(v interface{}) string {
pv := reflect.Indirect(rv).Interface()
return fmt.Sprintf("*%v", pv)
}
func (m *AuditAnnotation) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowGenerated
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: AuditAnnotation: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: AuditAnnotation: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Key", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowGenerated
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthGenerated
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthGenerated
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Key = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field ValueExpression", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowGenerated
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthGenerated
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthGenerated
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.ValueExpression = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipGenerated(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthGenerated
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *MatchResources) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
@ -2396,6 +2645,38 @@ func (m *ValidatingAdmissionPolicyBindingSpec) Unmarshal(dAtA []byte) error {
return err
}
iNdEx = postIndex
case 4:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field ValidationActions", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowGenerated
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthGenerated
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthGenerated
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.ValidationActions = append(m.ValidationActions, ValidationAction(dAtA[iNdEx:postIndex]))
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipGenerated(dAtA[iNdEx:])
@ -2702,6 +2983,40 @@ func (m *ValidatingAdmissionPolicySpec) Unmarshal(dAtA []byte) error {
s := FailurePolicyType(dAtA[iNdEx:postIndex])
m.FailurePolicy = &s
iNdEx = postIndex
case 5:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field AuditAnnotations", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowGenerated
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthGenerated
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthGenerated
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.AuditAnnotations = append(m.AuditAnnotations, AuditAnnotation{})
if err := m.AuditAnnotations[len(m.AuditAnnotations)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipGenerated(dAtA[iNdEx:])

View File

@ -29,6 +29,43 @@ import "k8s.io/apimachinery/pkg/runtime/schema/generated.proto";
// Package-wide variables from generator "generated".
option go_package = "k8s.io/api/admissionregistration/v1alpha1";
// AuditAnnotation describes how to produce an audit annotation for an API request.
message AuditAnnotation {
// key specifies the audit annotation key. The audit annotation keys of
// a ValidatingAdmissionPolicy must be unique. The key must be a qualified
// name ([A-Za-z0-9][-A-Za-z0-9_.]*) no more than 63 bytes in length.
//
// The key is combined with the resource name of the
// ValidatingAdmissionPolicy to construct an audit annotation key:
// "{ValidatingAdmissionPolicy name}/{key}".
//
// If an admission webhook uses the same resource name as this ValidatingAdmissionPolicy
// and the same audit annotation key, the annotation key will be identical.
// In this case, the first annotation written with the key will be included
// in the audit event and all subsequent annotations with the same key
// will be discarded.
//
// Required.
optional string key = 1;
// valueExpression represents the expression which is evaluated by CEL to
// produce an audit annotation value. The expression must evaluate to either
// a string or null value. If the expression evaluates to a string, the
// audit annotation is included with the string value. If the expression
// evaluates to null or empty string the audit annotation will be omitted.
// The valueExpression may be no longer than 5kb in length.
// If the result of the valueExpression is more than 10kb in length, it
// will be truncated to 10kb.
//
// If multiple ValidatingAdmissionPolicyBinding resources match an
// API request, then the valueExpression will be evaluated for
// each binding. All unique values produced by the valueExpressions
// will be joined together in a comma-separated list.
//
// Required.
optional string valueExpression = 2;
}
// MatchResources decides whether to run the admission control policy on an object based
// on whether it meets the match criteria.
// The exclude rules take precedence over include rules (if a resource matches both, it is excluded)
@ -213,6 +250,48 @@ message ValidatingAdmissionPolicyBindingSpec {
// Note that this is differs from ValidatingAdmissionPolicy matchConstraints, where resourceRules are required.
// +optional
optional MatchResources matchResources = 3;
// validationActions declares how Validations of the referenced ValidatingAdmissionPolicy are enforced.
// If a validation evaluates to false it is always enforced according to these actions.
//
// Failures defined by the ValidatingAdmissionPolicy's FailurePolicy are enforced according
// to these actions only if the FailurePolicy is set to Fail, otherwise the failures are
// ignored. This includes compilation errors, runtime errors and misconfigurations of the policy.
//
// validationActions is declared as a set of action values. Order does
// not matter. validationActions may not contain duplicates of the same action.
//
// The supported actions values are:
//
// "Deny" specifies that a validation failure results in a denied request.
//
// "Warn" specifies that a validation failure is reported to the request client
// in HTTP Warning headers, with a warning code of 299. Warnings can be sent
// both for allowed or denied admission responses.
//
// "Audit" specifies that a validation failure is included in the published
// audit event for the request. The audit event will contain a
// `validation.policy.admission.k8s.io/validation_failure` audit annotation
// with a value containing the details of the validation failures, formatted as
// a JSON list of objects, each with the following fields:
// - message: The validation failure message string
// - policy: The resource name of the ValidatingAdmissionPolicy
// - binding: The resource name of the ValidatingAdmissionPolicyBinding
// - expressionIndex: The index of the failed validations in the ValidatingAdmissionPolicy
// - validationActions: The enforcement actions enacted for the validation failure
// Example audit annotation:
// `"validation.policy.admission.k8s.io/validation_failure": "[{\"message\": \"Invalid value\", {\"policy\": \"policy.example.com\", {\"binding\": \"policybinding.example.com\", {\"expressionIndex\": \"1\", {\"validationActions\": [\"Audit\"]}]"`
//
// Clients should expect to handle additional values by ignoring
// any values not recognized.
//
// "Deny" and "Warn" may not be used together since this combination
// needlessly duplicates the validation failure both in the
// API response body and the HTTP warning headers.
//
// Required.
// +listType=set
repeated string validationActions = 4;
}
// ValidatingAdmissionPolicyList is a list of ValidatingAdmissionPolicy.
@ -243,29 +322,46 @@ message ValidatingAdmissionPolicySpec {
optional MatchResources matchConstraints = 2;
// Validations contain CEL expressions which is used to apply the validation.
// A minimum of one validation is required for a policy definition.
// Validations and AuditAnnotations may not both be empty; a minimum of one Validations or AuditAnnotations is
// required.
// +listType=atomic
// Required.
// +optional
repeated Validation validations = 3;
// FailurePolicy defines how to handle failures for the admission policy.
// Failures can occur from invalid or mis-configured policy definitions or bindings.
// failurePolicy defines how to handle failures for the admission policy. Failures can
// occur from CEL expression parse errors, type check errors, runtime errors and invalid
// or mis-configured policy definitions or bindings.
//
// A policy is invalid if spec.paramKind refers to a non-existent Kind.
// A binding is invalid if spec.paramRef.name refers to a non-existent resource.
//
// failurePolicy does not define how validations that evaluate to false are handled.
//
// When failurePolicy is set to Fail, ValidatingAdmissionPolicyBinding validationActions
// define how failures are enforced.
//
// Allowed values are Ignore or Fail. Defaults to Fail.
// +optional
optional string failurePolicy = 4;
// auditAnnotations contains CEL expressions which are used to produce audit
// annotations for the audit event of the API request.
// validations and auditAnnotations may not both be empty; a least one of validations or auditAnnotations is
// required.
// +listType=atomic
// +optional
repeated AuditAnnotation auditAnnotations = 5;
}
// Validation specifies the CEL expression which is used to apply the validation.
message Validation {
// Expression represents the expression which will be evaluated by CEL.
// ref: https://github.com/google/cel-spec
// CEL expressions have access to the contents of the Admission request/response, organized into CEL variables as well as some other useful variables:
// CEL expressions have access to the contents of the API request/response, organized into CEL variables as well as some other useful variables:
//
// - 'object' - The object from the incoming request. The value is null for DELETE requests.
// - 'oldObject' - The existing object. The value is null for CREATE requests.
// - 'request' - Attributes of the admission request([ref](/pkg/apis/admission/types.go#AdmissionRequest)).
// - 'request' - Attributes of the API request([ref](/pkg/apis/admission/types.go#AdmissionRequest)).
// - 'params' - Parameter resource referred to by the policy binding being evaluated. Only populated if the policy has a ParamKind.
// - 'authorizer' - A CEL Authorizer. May be used to perform authorization checks for the principal (user or service account) of the request.
// See https://pkg.go.dev/k8s.io/apiserver/pkg/cel/library#Authz

View File

@ -107,18 +107,35 @@ type ValidatingAdmissionPolicySpec struct {
MatchConstraints *MatchResources `json:"matchConstraints,omitempty" protobuf:"bytes,2,rep,name=matchConstraints"`
// Validations contain CEL expressions which is used to apply the validation.
// A minimum of one validation is required for a policy definition.
// Validations and AuditAnnotations may not both be empty; a minimum of one Validations or AuditAnnotations is
// required.
// +listType=atomic
// Required.
Validations []Validation `json:"validations" protobuf:"bytes,3,rep,name=validations"`
// +optional
Validations []Validation `json:"validations,omitempty" protobuf:"bytes,3,rep,name=validations"`
// FailurePolicy defines how to handle failures for the admission policy.
// Failures can occur from invalid or mis-configured policy definitions or bindings.
// failurePolicy defines how to handle failures for the admission policy. Failures can
// occur from CEL expression parse errors, type check errors, runtime errors and invalid
// or mis-configured policy definitions or bindings.
//
// A policy is invalid if spec.paramKind refers to a non-existent Kind.
// A binding is invalid if spec.paramRef.name refers to a non-existent resource.
//
// failurePolicy does not define how validations that evaluate to false are handled.
//
// When failurePolicy is set to Fail, ValidatingAdmissionPolicyBinding validationActions
// define how failures are enforced.
//
// Allowed values are Ignore or Fail. Defaults to Fail.
// +optional
FailurePolicy *FailurePolicyType `json:"failurePolicy,omitempty" protobuf:"bytes,4,opt,name=failurePolicy,casttype=FailurePolicyType"`
// auditAnnotations contains CEL expressions which are used to produce audit
// annotations for the audit event of the API request.
// validations and auditAnnotations may not both be empty; a least one of validations or auditAnnotations is
// required.
// +listType=atomic
// +optional
AuditAnnotations []AuditAnnotation `json:"auditAnnotations,omitempty" protobuf:"bytes,5,rep,name=auditAnnotations"`
}
// ParamKind is a tuple of Group Kind and Version.
@ -138,11 +155,11 @@ type ParamKind struct {
type Validation struct {
// Expression represents the expression which will be evaluated by CEL.
// ref: https://github.com/google/cel-spec
// CEL expressions have access to the contents of the Admission request/response, organized into CEL variables as well as some other useful variables:
// CEL expressions have access to the contents of the API request/response, organized into CEL variables as well as some other useful variables:
//
// - 'object' - The object from the incoming request. The value is null for DELETE requests.
// - 'oldObject' - The existing object. The value is null for CREATE requests.
// - 'request' - Attributes of the admission request([ref](/pkg/apis/admission/types.go#AdmissionRequest)).
// - 'request' - Attributes of the API request([ref](/pkg/apis/admission/types.go#AdmissionRequest)).
// - 'params' - Parameter resource referred to by the policy binding being evaluated. Only populated if the policy has a ParamKind.
// - 'authorizer' - A CEL Authorizer. May be used to perform authorization checks for the principal (user or service account) of the request.
// See https://pkg.go.dev/k8s.io/apiserver/pkg/cel/library#Authz
@ -194,6 +211,43 @@ type Validation struct {
Reason *metav1.StatusReason `json:"reason,omitempty" protobuf:"bytes,3,opt,name=reason"`
}
// AuditAnnotation describes how to produce an audit annotation for an API request.
type AuditAnnotation struct {
// key specifies the audit annotation key. The audit annotation keys of
// a ValidatingAdmissionPolicy must be unique. The key must be a qualified
// name ([A-Za-z0-9][-A-Za-z0-9_.]*) no more than 63 bytes in length.
//
// The key is combined with the resource name of the
// ValidatingAdmissionPolicy to construct an audit annotation key:
// "{ValidatingAdmissionPolicy name}/{key}".
//
// If an admission webhook uses the same resource name as this ValidatingAdmissionPolicy
// and the same audit annotation key, the annotation key will be identical.
// In this case, the first annotation written with the key will be included
// in the audit event and all subsequent annotations with the same key
// will be discarded.
//
// Required.
Key string `json:"key" protobuf:"bytes,1,opt,name=key"`
// valueExpression represents the expression which is evaluated by CEL to
// produce an audit annotation value. The expression must evaluate to either
// a string or null value. If the expression evaluates to a string, the
// audit annotation is included with the string value. If the expression
// evaluates to null or empty string the audit annotation will be omitted.
// The valueExpression may be no longer than 5kb in length.
// If the result of the valueExpression is more than 10kb in length, it
// will be truncated to 10kb.
//
// If multiple ValidatingAdmissionPolicyBinding resources match an
// API request, then the valueExpression will be evaluated for
// each binding. All unique values produced by the valueExpressions
// will be joined together in a comma-separated list.
//
// Required.
ValueExpression string `json:"valueExpression" protobuf:"bytes,2,opt,name=valueExpression"`
}
// +genclient
// +genclient:nonNamespaced
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
@ -244,6 +298,48 @@ type ValidatingAdmissionPolicyBindingSpec struct {
// Note that this is differs from ValidatingAdmissionPolicy matchConstraints, where resourceRules are required.
// +optional
MatchResources *MatchResources `json:"matchResources,omitempty" protobuf:"bytes,3,rep,name=matchResources"`
// validationActions declares how Validations of the referenced ValidatingAdmissionPolicy are enforced.
// If a validation evaluates to false it is always enforced according to these actions.
//
// Failures defined by the ValidatingAdmissionPolicy's FailurePolicy are enforced according
// to these actions only if the FailurePolicy is set to Fail, otherwise the failures are
// ignored. This includes compilation errors, runtime errors and misconfigurations of the policy.
//
// validationActions is declared as a set of action values. Order does
// not matter. validationActions may not contain duplicates of the same action.
//
// The supported actions values are:
//
// "Deny" specifies that a validation failure results in a denied request.
//
// "Warn" specifies that a validation failure is reported to the request client
// in HTTP Warning headers, with a warning code of 299. Warnings can be sent
// both for allowed or denied admission responses.
//
// "Audit" specifies that a validation failure is included in the published
// audit event for the request. The audit event will contain a
// `validation.policy.admission.k8s.io/validation_failure` audit annotation
// with a value containing the details of the validation failures, formatted as
// a JSON list of objects, each with the following fields:
// - message: The validation failure message string
// - policy: The resource name of the ValidatingAdmissionPolicy
// - binding: The resource name of the ValidatingAdmissionPolicyBinding
// - expressionIndex: The index of the failed validations in the ValidatingAdmissionPolicy
// - validationActions: The enforcement actions enacted for the validation failure
// Example audit annotation:
// `"validation.policy.admission.k8s.io/validation_failure": "[{\"message\": \"Invalid value\", {\"policy\": \"policy.example.com\", {\"binding\": \"policybinding.example.com\", {\"expressionIndex\": \"1\", {\"validationActions\": [\"Audit\"]}]"`
//
// Clients should expect to handle additional values by ignoring
// any values not recognized.
//
// "Deny" and "Warn" may not be used together since this combination
// needlessly duplicates the validation failure both in the
// API response body and the HTTP warning headers.
//
// Required.
// +listType=set
ValidationActions []ValidationAction `json:"validationActions,omitempty" protobuf:"bytes,4,rep,name=validationActions"`
}
// ParamRef references a parameter resource
@ -348,6 +444,24 @@ type MatchResources struct {
MatchPolicy *MatchPolicyType `json:"matchPolicy,omitempty" protobuf:"bytes,7,opt,name=matchPolicy,casttype=MatchPolicyType"`
}
// ValidationAction specifies a policy enforcement action.
// +enum
type ValidationAction string
const (
// Deny specifies that a validation failure results in a denied request.
Deny ValidationAction = "Deny"
// Warn specifies that a validation failure is reported to the request client
// in HTTP Warning headers, with a warning code of 299. Warnings can be sent
// both for allowed or denied admission responses.
Warn ValidationAction = "Warn"
// Audit specifies that a validation failure is included in the published
// audit event for the request. The audit event will contain a
// `validation.policy.admission.k8s.io/validation_failure` audit annotation
// with a value containing the details of the validation failure.
Audit ValidationAction = "Audit"
)
// NamedRuleWithOperations is a tuple of Operations and Resources with ResourceNames.
// +structType=atomic
type NamedRuleWithOperations struct {

View File

@ -27,6 +27,16 @@ package v1alpha1
// Those methods can be generated by using hack/update-codegen.sh
// AUTO-GENERATED FUNCTIONS START HERE. DO NOT EDIT.
var map_AuditAnnotation = map[string]string{
"": "AuditAnnotation describes how to produce an audit annotation for an API request.",
"key": "key specifies the audit annotation key. The audit annotation keys of a ValidatingAdmissionPolicy must be unique. The key must be a qualified name ([A-Za-z0-9][-A-Za-z0-9_.]*) no more than 63 bytes in length.\n\nThe key is combined with the resource name of the ValidatingAdmissionPolicy to construct an audit annotation key: \"{ValidatingAdmissionPolicy name}/{key}\".\n\nIf an admission webhook uses the same resource name as this ValidatingAdmissionPolicy and the same audit annotation key, the annotation key will be identical. In this case, the first annotation written with the key will be included in the audit event and all subsequent annotations with the same key will be discarded.\n\nRequired.",
"valueExpression": "valueExpression represents the expression which is evaluated by CEL to produce an audit annotation value. The expression must evaluate to either a string or null value. If the expression evaluates to a string, the audit annotation is included with the string value. If the expression evaluates to null or empty string the audit annotation will be omitted. The valueExpression may be no longer than 5kb in length. If the result of the valueExpression is more than 10kb in length, it will be truncated to 10kb.\n\nIf multiple ValidatingAdmissionPolicyBinding resources match an API request, then the valueExpression will be evaluated for each binding. All unique values produced by the valueExpressions will be joined together in a comma-separated list.\n\nRequired.",
}
func (AuditAnnotation) SwaggerDoc() map[string]string {
return map_AuditAnnotation
}
var map_MatchResources = map[string]string{
"": "MatchResources decides whether to run the admission control policy on an object based on whether it meets the match criteria. The exclude rules take precedence over include rules (if a resource matches both, it is excluded)",
"namespaceSelector": "NamespaceSelector decides whether to run the admission control policy on an object based on whether the namespace for that object matches the selector. If the object itself is a namespace, the matching is performed on object.metadata.labels. If the object is another cluster scoped resource, it never skips the policy.\n\nFor example, to run the webhook on any objects whose namespace is not associated with \"runlevel\" of \"0\" or \"1\"; you will set the selector as follows: \"namespaceSelector\": {\n \"matchExpressions\": [\n {\n \"key\": \"runlevel\",\n \"operator\": \"NotIn\",\n \"values\": [\n \"0\",\n \"1\"\n ]\n }\n ]\n}\n\nIf instead you want to only run the policy on any objects whose namespace is associated with the \"environment\" of \"prod\" or \"staging\"; you will set the selector as follows: \"namespaceSelector\": {\n \"matchExpressions\": [\n {\n \"key\": \"environment\",\n \"operator\": \"In\",\n \"values\": [\n \"prod\",\n \"staging\"\n ]\n }\n ]\n}\n\nSee https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/ for more examples of label selectors.\n\nDefault to the empty LabelSelector, which matches everything.",
@ -100,10 +110,11 @@ func (ValidatingAdmissionPolicyBindingList) SwaggerDoc() map[string]string {
}
var map_ValidatingAdmissionPolicyBindingSpec = map[string]string{
"": "ValidatingAdmissionPolicyBindingSpec is the specification of the ValidatingAdmissionPolicyBinding.",
"policyName": "PolicyName references a ValidatingAdmissionPolicy name which the ValidatingAdmissionPolicyBinding binds to. If the referenced resource does not exist, this binding is considered invalid and will be ignored Required.",
"paramRef": "ParamRef specifies the parameter resource used to configure the admission control policy. It should point to a resource of the type specified in ParamKind of the bound ValidatingAdmissionPolicy. If the policy specifies a ParamKind and the resource referred to by ParamRef does not exist, this binding is considered mis-configured and the FailurePolicy of the ValidatingAdmissionPolicy applied.",
"matchResources": "MatchResources declares what resources match this binding and will be validated by it. Note that this is intersected with the policy's matchConstraints, so only requests that are matched by the policy can be selected by this. If this is unset, all resources matched by the policy are validated by this binding When resourceRules is unset, it does not constrain resource matching. If a resource is matched by the other fields of this object, it will be validated. Note that this is differs from ValidatingAdmissionPolicy matchConstraints, where resourceRules are required.",
"": "ValidatingAdmissionPolicyBindingSpec is the specification of the ValidatingAdmissionPolicyBinding.",
"policyName": "PolicyName references a ValidatingAdmissionPolicy name which the ValidatingAdmissionPolicyBinding binds to. If the referenced resource does not exist, this binding is considered invalid and will be ignored Required.",
"paramRef": "ParamRef specifies the parameter resource used to configure the admission control policy. It should point to a resource of the type specified in ParamKind of the bound ValidatingAdmissionPolicy. If the policy specifies a ParamKind and the resource referred to by ParamRef does not exist, this binding is considered mis-configured and the FailurePolicy of the ValidatingAdmissionPolicy applied.",
"matchResources": "MatchResources declares what resources match this binding and will be validated by it. Note that this is intersected with the policy's matchConstraints, so only requests that are matched by the policy can be selected by this. If this is unset, all resources matched by the policy are validated by this binding When resourceRules is unset, it does not constrain resource matching. If a resource is matched by the other fields of this object, it will be validated. Note that this is differs from ValidatingAdmissionPolicy matchConstraints, where resourceRules are required.",
"validationActions": "validationActions declares how Validations of the referenced ValidatingAdmissionPolicy are enforced. If a validation evaluates to false it is always enforced according to these actions.\n\nFailures defined by the ValidatingAdmissionPolicy's FailurePolicy are enforced according to these actions only if the FailurePolicy is set to Fail, otherwise the failures are ignored. This includes compilation errors, runtime errors and misconfigurations of the policy.\n\nvalidationActions is declared as a set of action values. Order does not matter. validationActions may not contain duplicates of the same action.\n\nThe supported actions values are:\n\n\"Deny\" specifies that a validation failure results in a denied request.\n\n\"Warn\" specifies that a validation failure is reported to the request client in HTTP Warning headers, with a warning code of 299. Warnings can be sent both for allowed or denied admission responses.\n\n\"Audit\" specifies that a validation failure is included in the published audit event for the request. The audit event will contain a `validation.policy.admission.k8s.io/validation_failure` audit annotation with a value containing the details of the validation failures, formatted as a JSON list of objects, each with the following fields: - message: The validation failure message string - policy: The resource name of the ValidatingAdmissionPolicy - binding: The resource name of the ValidatingAdmissionPolicyBinding - expressionIndex: The index of the failed validations in the ValidatingAdmissionPolicy - validationActions: The enforcement actions enacted for the validation failure Example audit annotation: `\"validation.policy.admission.k8s.io/validation_failure\": \"[{\"message\": \"Invalid value\", {\"policy\": \"policy.example.com\", {\"binding\": \"policybinding.example.com\", {\"expressionIndex\": \"1\", {\"validationActions\": [\"Audit\"]}]\"`\n\nClients should expect to handle additional values by ignoring any values not recognized.\n\n\"Deny\" and \"Warn\" may not be used together since this combination needlessly duplicates the validation failure both in the API response body and the HTTP warning headers.\n\nRequired.",
}
func (ValidatingAdmissionPolicyBindingSpec) SwaggerDoc() map[string]string {
@ -124,8 +135,9 @@ var map_ValidatingAdmissionPolicySpec = map[string]string{
"": "ValidatingAdmissionPolicySpec is the specification of the desired behavior of the AdmissionPolicy.",
"paramKind": "ParamKind specifies the kind of resources used to parameterize this policy. If absent, there are no parameters for this policy and the param CEL variable will not be provided to validation expressions. If ParamKind refers to a non-existent kind, this policy definition is mis-configured and the FailurePolicy is applied. If paramKind is specified but paramRef is unset in ValidatingAdmissionPolicyBinding, the params variable will be null.",
"matchConstraints": "MatchConstraints specifies what resources this policy is designed to validate. The AdmissionPolicy cares about a request if it matches _all_ Constraints. However, in order to prevent clusters from being put into an unstable state that cannot be recovered from via the API ValidatingAdmissionPolicy cannot match ValidatingAdmissionPolicy and ValidatingAdmissionPolicyBinding. Required.",
"validations": "Validations contain CEL expressions which is used to apply the validation. A minimum of one validation is required for a policy definition. Required.",
"failurePolicy": "FailurePolicy defines how to handle failures for the admission policy. Failures can occur from invalid or mis-configured policy definitions or bindings. A policy is invalid if spec.paramKind refers to a non-existent Kind. A binding is invalid if spec.paramRef.name refers to a non-existent resource. Allowed values are Ignore or Fail. Defaults to Fail.",
"validations": "Validations contain CEL expressions which is used to apply the validation. Validations and AuditAnnotations may not both be empty; a minimum of one Validations or AuditAnnotations is required.",
"failurePolicy": "failurePolicy defines how to handle failures for the admission policy. Failures can occur from CEL expression parse errors, type check errors, runtime errors and invalid or mis-configured policy definitions or bindings.\n\nA policy is invalid if spec.paramKind refers to a non-existent Kind. A binding is invalid if spec.paramRef.name refers to a non-existent resource.\n\nfailurePolicy does not define how validations that evaluate to false are handled.\n\nWhen failurePolicy is set to Fail, ValidatingAdmissionPolicyBinding validationActions define how failures are enforced.\n\nAllowed values are Ignore or Fail. Defaults to Fail.",
"auditAnnotations": "auditAnnotations contains CEL expressions which are used to produce audit annotations for the audit event of the API request. validations and auditAnnotations may not both be empty; a least one of validations or auditAnnotations is required.",
}
func (ValidatingAdmissionPolicySpec) SwaggerDoc() map[string]string {
@ -134,7 +146,7 @@ func (ValidatingAdmissionPolicySpec) SwaggerDoc() map[string]string {
var map_Validation = map[string]string{
"": "Validation specifies the CEL expression which is used to apply the validation.",
"expression": "Expression represents the expression which will be evaluated by CEL. ref: https://github.com/google/cel-spec CEL expressions have access to the contents of the Admission request/response, organized into CEL variables as well as some other useful variables:\n\n- 'object' - The object from the incoming request. The value is null for DELETE requests. - 'oldObject' - The existing object. The value is null for CREATE requests. - 'request' - Attributes of the admission request([ref](/pkg/apis/admission/types.go#AdmissionRequest)). - 'params' - Parameter resource referred to by the policy binding being evaluated. Only populated if the policy has a ParamKind. - 'authorizer' - A CEL Authorizer. May be used to perform authorization checks for the principal (user or service account) of the request.\n See https://pkg.go.dev/k8s.io/apiserver/pkg/cel/library#Authz\n- 'authorizer.requestResource' - A CEL ResourceCheck constructed from the 'authorizer' and configured with the\n request resource.\n\nThe `apiVersion`, `kind`, `metadata.name` and `metadata.generateName` are always accessible from the root of the object. No other metadata properties are accessible.\n\nOnly property names of the form `[a-zA-Z_.-/][a-zA-Z0-9_.-/]*` are accessible. Accessible property names are escaped according to the following rules when accessed in the expression: - '__' escapes to '__underscores__' - '.' escapes to '__dot__' - '-' escapes to '__dash__' - '/' escapes to '__slash__' - Property names that exactly match a CEL RESERVED keyword escape to '__{keyword}__'. The keywords are:\n\t \"true\", \"false\", \"null\", \"in\", \"as\", \"break\", \"const\", \"continue\", \"else\", \"for\", \"function\", \"if\",\n\t \"import\", \"let\", \"loop\", \"package\", \"namespace\", \"return\".\nExamples:\n - Expression accessing a property named \"namespace\": {\"Expression\": \"object.__namespace__ > 0\"}\n - Expression accessing a property named \"x-prop\": {\"Expression\": \"object.x__dash__prop > 0\"}\n - Expression accessing a property named \"redact__d\": {\"Expression\": \"object.redact__underscores__d > 0\"}\n\nEquality on arrays with list type of 'set' or 'map' ignores element order, i.e. [1, 2] == [2, 1]. Concatenation on arrays with x-kubernetes-list-type use the semantics of the list type:\n - 'set': `X + Y` performs a union where the array positions of all elements in `X` are preserved and\n non-intersecting elements in `Y` are appended, retaining their partial order.\n - 'map': `X + Y` performs a merge where the array positions of all keys in `X` are preserved but the values\n are overwritten by values in `Y` when the key sets of `X` and `Y` intersect. Elements in `Y` with\n non-intersecting keys are appended, retaining their partial order.\nRequired.",
"expression": "Expression represents the expression which will be evaluated by CEL. ref: https://github.com/google/cel-spec CEL expressions have access to the contents of the API request/response, organized into CEL variables as well as some other useful variables:\n\n- 'object' - The object from the incoming request. The value is null for DELETE requests. - 'oldObject' - The existing object. The value is null for CREATE requests. - 'request' - Attributes of the API request([ref](/pkg/apis/admission/types.go#AdmissionRequest)). - 'params' - Parameter resource referred to by the policy binding being evaluated. Only populated if the policy has a ParamKind. - 'authorizer' - A CEL Authorizer. May be used to perform authorization checks for the principal (user or service account) of the request.\n See https://pkg.go.dev/k8s.io/apiserver/pkg/cel/library#Authz\n- 'authorizer.requestResource' - A CEL ResourceCheck constructed from the 'authorizer' and configured with the\n request resource.\n\nThe `apiVersion`, `kind`, `metadata.name` and `metadata.generateName` are always accessible from the root of the object. No other metadata properties are accessible.\n\nOnly property names of the form `[a-zA-Z_.-/][a-zA-Z0-9_.-/]*` are accessible. Accessible property names are escaped according to the following rules when accessed in the expression: - '__' escapes to '__underscores__' - '.' escapes to '__dot__' - '-' escapes to '__dash__' - '/' escapes to '__slash__' - Property names that exactly match a CEL RESERVED keyword escape to '__{keyword}__'. The keywords are:\n\t \"true\", \"false\", \"null\", \"in\", \"as\", \"break\", \"const\", \"continue\", \"else\", \"for\", \"function\", \"if\",\n\t \"import\", \"let\", \"loop\", \"package\", \"namespace\", \"return\".\nExamples:\n - Expression accessing a property named \"namespace\": {\"Expression\": \"object.__namespace__ > 0\"}\n - Expression accessing a property named \"x-prop\": {\"Expression\": \"object.x__dash__prop > 0\"}\n - Expression accessing a property named \"redact__d\": {\"Expression\": \"object.redact__underscores__d > 0\"}\n\nEquality on arrays with list type of 'set' or 'map' ignores element order, i.e. [1, 2] == [2, 1]. Concatenation on arrays with x-kubernetes-list-type use the semantics of the list type:\n - 'set': `X + Y` performs a union where the array positions of all elements in `X` are preserved and\n non-intersecting elements in `Y` are appended, retaining their partial order.\n - 'map': `X + Y` performs a merge where the array positions of all keys in `X` are preserved but the values\n are overwritten by values in `Y` when the key sets of `X` and `Y` intersect. Elements in `Y` with\n non-intersecting keys are appended, retaining their partial order.\nRequired.",
"message": "Message represents the message displayed when validation fails. The message is required if the Expression contains line breaks. The message must not contain line breaks. If unset, the message is \"failed rule: {Rule}\". e.g. \"must be a URL with the host matching spec.host\" If the Expression contains line breaks. Message is required. The message must not contain line breaks. If unset, the message is \"failed Expression: {Expression}\".",
"reason": "Reason represents a machine-readable description of why this validation failed. If this is the first validation in the list to fail, this reason, as well as the corresponding HTTP response code, are used in the HTTP response to the client. The currently supported reasons are: \"Unauthorized\", \"Forbidden\", \"Invalid\", \"RequestEntityTooLarge\". If not set, StatusReasonInvalid is used in the response to the client.",
}

View File

@ -26,6 +26,22 @@ import (
runtime "k8s.io/apimachinery/pkg/runtime"
)
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *AuditAnnotation) DeepCopyInto(out *AuditAnnotation) {
*out = *in
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AuditAnnotation.
func (in *AuditAnnotation) DeepCopy() *AuditAnnotation {
if in == nil {
return nil
}
out := new(AuditAnnotation)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *MatchResources) DeepCopyInto(out *MatchResources) {
*out = *in
@ -225,6 +241,11 @@ func (in *ValidatingAdmissionPolicyBindingSpec) DeepCopyInto(out *ValidatingAdmi
*out = new(MatchResources)
(*in).DeepCopyInto(*out)
}
if in.ValidationActions != nil {
in, out := &in.ValidationActions, &out.ValidationActions
*out = make([]ValidationAction, len(*in))
copy(*out, *in)
}
return
}
@ -296,6 +317,11 @@ func (in *ValidatingAdmissionPolicySpec) DeepCopyInto(out *ValidatingAdmissionPo
*out = new(FailurePolicyType)
**out = **in
}
if in.AuditAnnotations != nil {
in, out := &in.AuditAnnotations, &out.AuditAnnotations
*out = make([]AuditAnnotation, len(*in))
copy(*out, *in)
}
return
}

View File

@ -126,6 +126,12 @@
"reason": "reasonValue"
}
],
"failurePolicy": "failurePolicyValue"
"failurePolicy": "failurePolicyValue",
"auditAnnotations": [
{
"key": "keyValue",
"valueExpression": "valueExpressionValue"
}
]
}
}

View File

@ -33,6 +33,9 @@ metadata:
selfLink: selfLinkValue
uid: uidValue
spec:
auditAnnotations:
- key: keyValue
valueExpression: valueExpressionValue
failurePolicy: failurePolicyValue
matchConstraints:
excludeResourceRules:

View File

@ -119,6 +119,9 @@
}
],
"matchPolicy": "matchPolicyValue"
}
},
"validationActions": [
"validationActionsValue"
]
}
}

View File

@ -79,3 +79,5 @@ spec:
name: nameValue
namespace: namespaceValue
policyName: policyNameValue
validationActions:
- validationActionsValue

View File

@ -0,0 +1,131 @@
{
"kind": "ValidatingAdmissionPolicy",
"apiVersion": "admissionregistration.k8s.io/v1alpha1",
"metadata": {
"name": "nameValue",
"generateName": "generateNameValue",
"namespace": "namespaceValue",
"selfLink": "selfLinkValue",
"uid": "uidValue",
"resourceVersion": "resourceVersionValue",
"generation": 7,
"creationTimestamp": "2008-01-01T01:01:01Z",
"deletionTimestamp": "2009-01-01T01:01:01Z",
"deletionGracePeriodSeconds": 10,
"labels": {
"labelsKey": "labelsValue"
},
"annotations": {
"annotationsKey": "annotationsValue"
},
"ownerReferences": [
{
"apiVersion": "apiVersionValue",
"kind": "kindValue",
"name": "nameValue",
"uid": "uidValue",
"controller": true,
"blockOwnerDeletion": true
}
],
"finalizers": [
"finalizersValue"
],
"managedFields": [
{
"manager": "managerValue",
"operation": "operationValue",
"apiVersion": "apiVersionValue",
"time": "2004-01-01T01:01:01Z",
"fieldsType": "fieldsTypeValue",
"fieldsV1": {},
"subresource": "subresourceValue"
}
]
},
"spec": {
"paramKind": {
"apiVersion": "apiVersionValue",
"kind": "kindValue"
},
"matchConstraints": {
"namespaceSelector": {
"matchLabels": {
"matchLabelsKey": "matchLabelsValue"
},
"matchExpressions": [
{
"key": "keyValue",
"operator": "operatorValue",
"values": [
"valuesValue"
]
}
]
},
"objectSelector": {
"matchLabels": {
"matchLabelsKey": "matchLabelsValue"
},
"matchExpressions": [
{
"key": "keyValue",
"operator": "operatorValue",
"values": [
"valuesValue"
]
}
]
},
"resourceRules": [
{
"resourceNames": [
"resourceNamesValue"
],
"operations": [
"operationsValue"
],
"apiGroups": [
"apiGroupsValue"
],
"apiVersions": [
"apiVersionsValue"
],
"resources": [
"resourcesValue"
],
"scope": "scopeValue"
}
],
"excludeResourceRules": [
{
"resourceNames": [
"resourceNamesValue"
],
"operations": [
"operationsValue"
],
"apiGroups": [
"apiGroupsValue"
],
"apiVersions": [
"apiVersionsValue"
],
"resources": [
"resourcesValue"
],
"scope": "scopeValue"
}
],
"matchPolicy": "matchPolicyValue"
},
"validations": [
{
"expression": "expressionValue",
"message": "messageValue",
"reason": "reasonValue"
}
],
"failurePolicy": "failurePolicyValue"
}
}

View File

@ -0,0 +1,85 @@
apiVersion: admissionregistration.k8s.io/v1alpha1
kind: ValidatingAdmissionPolicy
metadata:
annotations:
annotationsKey: annotationsValue
creationTimestamp: "2008-01-01T01:01:01Z"
deletionGracePeriodSeconds: 10
deletionTimestamp: "2009-01-01T01:01:01Z"
finalizers:
- finalizersValue
generateName: generateNameValue
generation: 7
labels:
labelsKey: labelsValue
managedFields:
- apiVersion: apiVersionValue
fieldsType: fieldsTypeValue
fieldsV1: {}
manager: managerValue
operation: operationValue
subresource: subresourceValue
time: "2004-01-01T01:01:01Z"
name: nameValue
namespace: namespaceValue
ownerReferences:
- apiVersion: apiVersionValue
blockOwnerDeletion: true
controller: true
kind: kindValue
name: nameValue
uid: uidValue
resourceVersion: resourceVersionValue
selfLink: selfLinkValue
uid: uidValue
spec:
failurePolicy: failurePolicyValue
matchConstraints:
excludeResourceRules:
- apiGroups:
- apiGroupsValue
apiVersions:
- apiVersionsValue
operations:
- operationsValue
resourceNames:
- resourceNamesValue
resources:
- resourcesValue
scope: scopeValue
matchPolicy: matchPolicyValue
namespaceSelector:
matchExpressions:
- key: keyValue
operator: operatorValue
values:
- valuesValue
matchLabels:
matchLabelsKey: matchLabelsValue
objectSelector:
matchExpressions:
- key: keyValue
operator: operatorValue
values:
- valuesValue
matchLabels:
matchLabelsKey: matchLabelsValue
resourceRules:
- apiGroups:
- apiGroupsValue
apiVersions:
- apiVersionsValue
operations:
- operationsValue
resourceNames:
- resourceNamesValue
resources:
- resourcesValue
scope: scopeValue
paramKind:
apiVersion: apiVersionValue
kind: kindValue
validations:
- expression: expressionValue
message: messageValue
reason: reasonValue

View File

@ -109,3 +109,15 @@ func (m *ValidatingAdmissionPolicyMetrics) ObserveRejection(ctx context.Context,
m.policyCheck.WithContext(ctx).WithLabelValues(policy, binding, "deny", state).Inc()
m.policyLatency.WithContext(ctx).WithLabelValues(policy, binding, "deny", state).Observe(elapsed.Seconds())
}
// ObserveAudit observes a policy validation audit annotation was published for a validation failure.
func (m *ValidatingAdmissionPolicyMetrics) ObserveAudit(ctx context.Context, elapsed time.Duration, policy, binding, state string) {
m.policyCheck.WithContext(ctx).WithLabelValues(policy, binding, "audit", state).Inc()
m.policyLatency.WithContext(ctx).WithLabelValues(policy, binding, "audit", state).Observe(elapsed.Seconds())
}
// ObserveWarn observes a policy validation warning was published for a validation failure.
func (m *ValidatingAdmissionPolicyMetrics) ObserveWarn(ctx context.Context, elapsed time.Duration, policy, binding, state string) {
m.policyCheck.WithContext(ctx).WithLabelValues(policy, binding, "warn", state).Inc()
m.policyLatency.WithContext(ctx).WithLabelValues(policy, binding, "warn", state).Observe(elapsed.Seconds())
}

View File

@ -223,11 +223,26 @@ func CompileCELExpression(expressionAccessor ExpressionAccessor, optionalVars Op
ExpressionAccessor: expressionAccessor,
}
}
if ast.OutputType() != cel.BoolType {
found := false
returnTypes := expressionAccessor.ReturnTypes()
for _, returnType := range returnTypes {
if ast.OutputType() == returnType {
found = true
break
}
}
if !found {
var reason string
if len(returnTypes) == 1 {
reason = fmt.Sprintf("must evaluate to %v", returnTypes[0].String())
} else {
reason = fmt.Sprintf("must evaluate to one of %v", returnTypes)
}
return CompilationResult{
Error: &apiservercel.Error{
Type: apiservercel.ErrorTypeInvalid,
Detail: "cel expression must evaluate to a bool",
Detail: reason,
},
ExpressionAccessor: expressionAccessor,
}

View File

@ -20,6 +20,8 @@ import (
"strings"
"testing"
celgo "github.com/google/cel-go/cel"
celconfig "k8s.io/apiserver/pkg/apis/cel"
)
@ -120,34 +122,79 @@ func TestCompileValidatingPolicyExpression(t *testing.T) {
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
for _, expr := range tc.expressions {
result := CompileCELExpression(&fakeExpressionAccessor{
expr,
}, OptionalVariableDeclarations{HasParams: tc.hasParams, HasAuthorizer: true}, celconfig.PerCallLimit)
if result.Error != nil {
t.Errorf("Unexpected error: %v", result.Error)
}
t.Run(expr, func(t *testing.T) {
t.Run("expression", func(t *testing.T) {
result := CompileCELExpression(&fakeValidationCondition{
Expression: expr,
}, OptionalVariableDeclarations{HasParams: tc.hasParams, HasAuthorizer: tc.hasAuthorizer}, celconfig.PerCallLimit)
if result.Error != nil {
t.Errorf("Unexpected error: %v", result.Error)
}
})
t.Run("auditAnnotation.valueExpression", func(t *testing.T) {
// Test audit annotation compilation by casting the result to a string
result := CompileCELExpression(&fakeAuditAnnotationCondition{
ValueExpression: "string(" + expr + ")",
}, OptionalVariableDeclarations{HasParams: tc.hasParams, HasAuthorizer: tc.hasAuthorizer}, celconfig.PerCallLimit)
if result.Error != nil {
t.Errorf("Unexpected error: %v", result.Error)
}
})
})
}
for expr, expectErr := range tc.errorExpressions {
result := CompileCELExpression(&fakeExpressionAccessor{
expr,
}, OptionalVariableDeclarations{HasParams: tc.hasParams, HasAuthorizer: tc.hasAuthorizer}, celconfig.PerCallLimit)
if result.Error == nil {
t.Errorf("Expected expression '%s' to contain '%v' but got no error", expr, expectErr)
continue
}
if !strings.Contains(result.Error.Error(), expectErr) {
t.Errorf("Expected compilation '%s' error to contain '%v' but got: %v", expr, expectErr, result.Error)
}
continue
t.Run(expr, func(t *testing.T) {
t.Run("expression", func(t *testing.T) {
result := CompileCELExpression(&fakeValidationCondition{
Expression: expr,
}, OptionalVariableDeclarations{HasParams: tc.hasParams, HasAuthorizer: tc.hasAuthorizer}, celconfig.PerCallLimit)
if result.Error == nil {
t.Errorf("Expected expression '%s' to contain '%v' but got no error", expr, expectErr)
return
}
if !strings.Contains(result.Error.Error(), expectErr) {
t.Errorf("Expected validation '%s' error to contain '%v' but got: %v", expr, expectErr, result.Error)
}
})
t.Run("auditAnnotation.valueExpression", func(t *testing.T) {
// Test audit annotation compilation by casting the result to a string
result := CompileCELExpression(&fakeAuditAnnotationCondition{
ValueExpression: "string(" + expr + ")",
}, OptionalVariableDeclarations{HasParams: tc.hasParams, HasAuthorizer: tc.hasAuthorizer}, celconfig.PerCallLimit)
if result.Error == nil {
t.Errorf("Expected expression '%s' to contain '%v' but got no error", expr, expectErr)
return
}
if !strings.Contains(result.Error.Error(), expectErr) {
t.Errorf("Expected validation '%s' error to contain '%v' but got: %v", expr, expectErr, result.Error)
}
})
})
}
})
}
}
type fakeExpressionAccessor struct {
expression string
type fakeValidationCondition struct {
Expression string
}
func (f *fakeExpressionAccessor) GetExpression() string {
return f.expression
func (v *fakeValidationCondition) GetExpression() string {
return v.Expression
}
func (v *fakeValidationCondition) ReturnTypes() []*celgo.Type {
return []*celgo.Type{celgo.BoolType}
}
type fakeAuditAnnotationCondition struct {
ValueExpression string
}
func (v *fakeAuditAnnotationCondition) GetExpression() string {
return v.ValueExpression
}
func (v *fakeAuditAnnotationCondition) ReturnTypes() []*celgo.Type {
return []*celgo.Type{celgo.StringType, celgo.NullType}
}

View File

@ -75,11 +75,7 @@ func (a *evaluationActivation) Parent() interpreter.Activation {
}
// Compile compiles the cel expressions defined in the ExpressionAccessors into a Filter
// perCallLimit was added for testing purpose only. Callers should always use const PerCallLimit from k8s.io/apiserver/pkg/apis/cel/config.go as input.
func (c *filterCompiler) Compile(expressionAccessors []ExpressionAccessor, options OptionalVariableDeclarations, perCallLimit uint64) Filter {
if len(expressionAccessors) == 0 {
return nil
}
compilationResults := make([]CompilationResult, len(expressionAccessors))
for i, expressionAccessor := range expressionAccessors {
compilationResults[i] = CompileCELExpression(expressionAccessor, options, perCallLimit)

View File

@ -24,14 +24,10 @@ import (
"strings"
"testing"
celgo "github.com/google/cel-go/cel"
celtypes "github.com/google/cel-go/common/types"
"github.com/stretchr/testify/require"
celconfig "k8s.io/apiserver/pkg/apis/cel"
"k8s.io/apiserver/pkg/authentication/user"
"k8s.io/apiserver/pkg/authorization/authorizer"
apiservercel "k8s.io/apiserver/pkg/cel"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
@ -39,6 +35,10 @@ import (
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apiserver/pkg/admission"
"k8s.io/apiserver/pkg/admission/plugin/webhook/generic"
celconfig "k8s.io/apiserver/pkg/apis/cel"
"k8s.io/apiserver/pkg/authentication/user"
"k8s.io/apiserver/pkg/authorization/authorizer"
apiservercel "k8s.io/apiserver/pkg/cel"
)
type condition struct {
@ -49,6 +49,10 @@ func (c *condition) GetExpression() string {
return c.Expression
}
func (v *condition) ReturnTypes() []*celgo.Type {
return []*celgo.Type{celgo.BoolType}
}
func TestCompile(t *testing.T) {
cases := []struct {
name string

View File

@ -19,6 +19,7 @@ package cel
import (
"time"
"github.com/google/cel-go/cel"
"github.com/google/cel-go/common/types/ref"
v1 "k8s.io/api/admission/v1"
@ -31,6 +32,7 @@ var _ ExpressionAccessor = &MatchCondition{}
type ExpressionAccessor interface {
GetExpression() string
ReturnTypes() []*cel.Type
}
// EvaluationResult contains the minimal required fields and metadata of a cel evaluation
@ -50,6 +52,10 @@ func (v *MatchCondition) GetExpression() string {
return v.Expression
}
func (v *MatchCondition) ReturnTypes() []*cel.Type {
return []*cel.Type{cel.BoolType}
}
// OptionalVariableDeclarations declares which optional CEL variables
// are declared for an expression.
type OptionalVariableDeclarations struct {
@ -83,6 +89,7 @@ type OptionalVariableBindings struct {
// Filter contains a function to evaluate compiled CEL-typed values
// It expects the inbound object to already have been converted to the version expected
// by the underlying CEL code (which is indicated by the match criteria of a policy definition).
// versionedParams may be nil.
type Filter interface {
// ForInput converts compiled CEL-typed values into evaluated CEL-typed values
// runtimeCELCostBudget was added for testing purpose only. Callers should always use const RuntimeCELCostBudget from k8s.io/apiserver/pkg/apis/cel/config.go as input.

View File

@ -19,11 +19,13 @@ package validatingadmissionpolicy
import (
"context"
"fmt"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
celgo "github.com/google/cel-go/cel"
"github.com/stretchr/testify/require"
"k8s.io/klog/v2"
@ -38,14 +40,18 @@ import (
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
utiljson "k8s.io/apimachinery/pkg/util/json"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/apiserver/pkg/admission"
"k8s.io/apiserver/pkg/admission/initializer"
"k8s.io/apiserver/pkg/admission/plugin/cel"
"k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/internal/generic"
whgeneric "k8s.io/apiserver/pkg/admission/plugin/webhook/generic"
auditinternal "k8s.io/apiserver/pkg/apis/audit"
"k8s.io/apiserver/pkg/authorization/authorizer"
"k8s.io/apiserver/pkg/features"
"k8s.io/apiserver/pkg/warning"
dynamicfake "k8s.io/client-go/dynamic/fake"
"k8s.io/client-go/informers"
"k8s.io/client-go/kubernetes/fake"
@ -144,6 +150,7 @@ var (
Name: fakeParams.GetName(),
Namespace: fakeParams.GetNamespace(),
},
ValidationActions: []v1alpha1.ValidationAction{v1alpha1.Deny},
},
}
denyBindingWithNoParamRef *v1alpha1.ValidatingAdmissionPolicyBinding = &v1alpha1.ValidatingAdmissionPolicyBinding{
@ -152,7 +159,39 @@ var (
ResourceVersion: "1",
},
Spec: v1alpha1.ValidatingAdmissionPolicyBindingSpec{
PolicyName: denyPolicy.Name,
PolicyName: denyPolicy.Name,
ValidationActions: []v1alpha1.ValidationAction{v1alpha1.Deny},
},
}
denyBindingWithAudit = &v1alpha1.ValidatingAdmissionPolicyBinding{
ObjectMeta: metav1.ObjectMeta{
Name: "denybinding.example.com",
ResourceVersion: "1",
},
Spec: v1alpha1.ValidatingAdmissionPolicyBindingSpec{
PolicyName: denyPolicy.Name,
ValidationActions: []v1alpha1.ValidationAction{v1alpha1.Audit},
},
}
denyBindingWithWarn = &v1alpha1.ValidatingAdmissionPolicyBinding{
ObjectMeta: metav1.ObjectMeta{
Name: "denybinding.example.com",
ResourceVersion: "1",
},
Spec: v1alpha1.ValidatingAdmissionPolicyBindingSpec{
PolicyName: denyPolicy.Name,
ValidationActions: []v1alpha1.ValidationAction{v1alpha1.Warn},
},
}
denyBindingWithAll = &v1alpha1.ValidatingAdmissionPolicyBinding{
ObjectMeta: metav1.ObjectMeta{
Name: "denybinding.example.com",
ResourceVersion: "1",
},
Spec: v1alpha1.ValidatingAdmissionPolicyBindingSpec{
PolicyName: denyPolicy.Name,
ValidationActions: []v1alpha1.ValidationAction{v1alpha1.Deny, v1alpha1.Warn, v1alpha1.Audit},
},
}
)
@ -174,12 +213,13 @@ func (f *fakeCompiler) Compile(
options cel.OptionalVariableDeclarations,
perCallLimit uint64,
) cel.Filter {
key := expressions[0].GetExpression()
if fun, ok := f.CompileFuncs[key]; ok {
return fun(expressions, options)
if len(expressions) > 0 {
key := expressions[0].GetExpression()
if fun, ok := f.CompileFuncs[key]; ok {
return fun(expressions, options)
}
}
return nil
return &fakeFilter{}
}
func (f *fakeCompiler) RegisterDefinition(definition *v1alpha1.ValidatingAdmissionPolicy, compileFunc func([]cel.ExpressionAccessor, cel.OptionalVariableDeclarations) cel.Filter) {
@ -203,6 +243,10 @@ func (f *fakeEvalRequest) GetExpression() string {
return ""
}
func (f *fakeEvalRequest) ReturnTypes() []*celgo.Type {
return []*celgo.Type{celgo.BoolType}
}
var _ cel.Filter = &fakeFilter{}
type fakeFilter struct {
@ -220,22 +264,28 @@ func (f *fakeFilter) CompilationErrors() []error {
var _ Validator = &fakeValidator{}
type fakeValidator struct {
*fakeFilter
ValidateFunc func(versionedAttr *whgeneric.VersionedAttributes, versionedParams runtime.Object, runtimeCELCostBudget int64) []PolicyDecision
validationFilter, auditAnnotationFilter *fakeFilter
ValidateFunc func(versionedAttr *whgeneric.VersionedAttributes, versionedParams runtime.Object, runtimeCELCostBudget int64) ValidateResult
}
func (f *fakeValidator) RegisterDefinition(definition *v1alpha1.ValidatingAdmissionPolicy, validateFunc func(versionedAttr *whgeneric.VersionedAttributes, versionedParams runtime.Object, runtimeCELCostBudget int64) []PolicyDecision) {
func (f *fakeValidator) RegisterDefinition(definition *v1alpha1.ValidatingAdmissionPolicy, validateFunc func(versionedAttr *whgeneric.VersionedAttributes, versionedParams runtime.Object, runtimeCELCostBudget int64) ValidateResult) {
//Key must be something that we can decipher from the inputs to Validate so using message which will be on the validationCondition object of evalResult
validateKey := definition.Spec.Validations[0].Expression
var key string
if len(definition.Spec.Validations) > 0 {
key = definition.Spec.Validations[0].Expression
} else {
key = definition.Spec.AuditAnnotations[0].Key
}
if validatorMap == nil {
validatorMap = make(map[string]*fakeValidator)
}
f.ValidateFunc = validateFunc
validatorMap[validateKey] = f
validatorMap[key] = f
}
func (f *fakeValidator) Validate(versionedAttr *whgeneric.VersionedAttributes, versionedParams runtime.Object, runtimeCELCostBudget int64) []PolicyDecision {
func (f *fakeValidator) Validate(versionedAttr *whgeneric.VersionedAttributes, versionedParams runtime.Object, runtimeCELCostBudget int64) ValidateResult {
return f.ValidateFunc(versionedAttr, versionedParams, runtimeCELCostBudget)
}
@ -369,10 +419,11 @@ func setupTestCommon(t *testing.T, compiler cel.FilterCompiler, matcher Matcher,
// Override compiler used by controller for tests
controller = handler.evaluator.(*celAdmissionController)
controller.policyController.filterCompiler = compiler
controller.policyController.newValidator = func(filter cel.Filter, fail *admissionRegistrationv1.FailurePolicyType, authorizer authorizer.Authorizer) Validator {
f := filter.(*fakeFilter)
controller.policyController.newValidator = func(validationFilter, auditAnnotationFilter cel.Filter, fail *admissionRegistrationv1.FailurePolicyType, authorizer authorizer.Authorizer) Validator {
f := validationFilter.(*fakeFilter)
v := validatorMap[f.keyId]
v.fakeFilter = f
v.validationFilter = f
v.auditAnnotationFilter = auditAnnotationFilter.(*fakeFilter)
return v
}
controller.policyController.matcher = matcher
@ -596,7 +647,7 @@ func waitForReconcileDeletion(ctx context.Context, controller *celAdmissionContr
func attributeRecord(
old, new runtime.Object,
operation admission.Operation,
) admission.Attributes {
) *FakeAttributes {
if old == nil && new == nil {
panic("both `old` and `new` may not be nil")
}
@ -622,19 +673,21 @@ func attributeRecord(
panic(err)
}
return admission.NewAttributesRecord(
new,
old,
gvk,
accessor.GetNamespace(),
accessor.GetName(),
mapping.Resource,
"",
operation,
nil,
false,
nil,
)
return &FakeAttributes{
Attributes: admission.NewAttributesRecord(
new,
old,
gvk,
accessor.GetNamespace(),
accessor.GetName(),
mapping.Resource,
"",
operation,
nil,
false,
nil,
),
}
}
func ptrTo[T any](obj T) *T {
@ -716,11 +769,13 @@ func TestBasicPolicyDefinitionFailure(t *testing.T) {
}
})
validator.RegisterDefinition(denyPolicy, func(versionedAttr *whgeneric.VersionedAttributes, versionedParams runtime.Object, runtimeCELCostBudget int64) []PolicyDecision {
return []PolicyDecision{
{
Action: ActionDeny,
Message: "Denied",
validator.RegisterDefinition(denyPolicy, func(versionedAttr *whgeneric.VersionedAttributes, versionedParams runtime.Object, runtimeCELCostBudget int64) ValidateResult {
return ValidateResult{
Decisions: []PolicyDecision{
{
Action: ActionDeny,
Message: "Denied",
},
},
}
})
@ -737,14 +792,22 @@ func TestBasicPolicyDefinitionFailure(t *testing.T) {
testContext, controller,
fakeParams, denyBinding, denyPolicy))
warningRecorder := newWarningRecorder()
warnCtx := warning.WithWarningRecorder(testContext, warningRecorder)
attr := attributeRecord(nil, fakeParams, admission.Create)
err := handler.Validate(
testContext,
warnCtx,
// Object is irrelevant/unchecked for this test. Just test that
// the evaluator is executed, and returns a denial
attributeRecord(nil, fakeParams, admission.Create),
attr,
&admission.RuntimeObjectInterfaces{},
)
require.Equal(t, 0, warningRecorder.len())
annotations := attr.GetAnnotations(auditinternal.LevelMetadata)
require.Equal(t, 0, len(annotations))
require.ErrorContains(t, err, `Denied`)
}
@ -776,11 +839,13 @@ func TestDefinitionDoesntMatch(t *testing.T) {
}
})
validator.RegisterDefinition(denyPolicy, func(versionedAttr *whgeneric.VersionedAttributes, versionedParams runtime.Object, runtimeCELCostBudget int64) []PolicyDecision {
return []PolicyDecision{
{
Action: ActionDeny,
Message: "Denied",
validator.RegisterDefinition(denyPolicy, func(versionedAttr *whgeneric.VersionedAttributes, versionedParams runtime.Object, runtimeCELCostBudget int64) ValidateResult {
return ValidateResult{
Decisions: []PolicyDecision{
{
Action: ActionDeny,
Message: "Denied",
},
},
}
})
@ -887,11 +952,13 @@ func TestReconfigureBinding(t *testing.T) {
}
})
validator.RegisterDefinition(denyPolicy, func(versionedAttr *whgeneric.VersionedAttributes, versionedParams runtime.Object, runtimeCELCostBudget int64) []PolicyDecision {
return []PolicyDecision{
{
Action: ActionDeny,
Message: "Denied",
validator.RegisterDefinition(denyPolicy, func(versionedAttr *whgeneric.VersionedAttributes, versionedParams runtime.Object, runtimeCELCostBudget int64) ValidateResult {
return ValidateResult{
Decisions: []PolicyDecision{
{
Action: ActionDeny,
Message: "Denied",
},
},
}
})
@ -907,6 +974,7 @@ func TestReconfigureBinding(t *testing.T) {
Name: fakeParams2.GetName(),
Namespace: fakeParams2.GetNamespace(),
},
ValidationActions: []v1alpha1.ValidationAction{v1alpha1.Deny},
},
}
@ -994,11 +1062,13 @@ func TestRemoveDefinition(t *testing.T) {
}
})
validator.RegisterDefinition(denyPolicy, func(versionedAttr *whgeneric.VersionedAttributes, versionedParams runtime.Object, runtimeCELCostBudget int64) []PolicyDecision {
return []PolicyDecision{
{
Action: ActionDeny,
Message: "Denied",
validator.RegisterDefinition(denyPolicy, func(versionedAttr *whgeneric.VersionedAttributes, versionedParams runtime.Object, runtimeCELCostBudget int64) ValidateResult {
return ValidateResult{
Decisions: []PolicyDecision{
{
Action: ActionDeny,
Message: "Denied",
},
},
}
})
@ -1061,11 +1131,13 @@ func TestRemoveBinding(t *testing.T) {
}
})
validator.RegisterDefinition(denyPolicy, func(versionedAttr *whgeneric.VersionedAttributes, versionedParams runtime.Object, runtimeCELCostBudget int64) []PolicyDecision {
return []PolicyDecision{
{
Action: ActionDeny,
Message: "Denied",
validator.RegisterDefinition(denyPolicy, func(versionedAttr *whgeneric.VersionedAttributes, versionedParams runtime.Object, runtimeCELCostBudget int64) ValidateResult {
return ValidateResult{
Decisions: []PolicyDecision{
{
Action: ActionDeny,
Message: "Denied",
},
},
}
})
@ -1169,11 +1241,13 @@ func TestInvalidParamSourceInstanceName(t *testing.T) {
}
})
validator.RegisterDefinition(denyPolicy, func(versionedAttr *whgeneric.VersionedAttributes, versionedParams runtime.Object, runtimeCELCostBudget int64) []PolicyDecision {
return []PolicyDecision{
{
Action: ActionDeny,
Message: "Denied",
validator.RegisterDefinition(denyPolicy, func(versionedAttr *whgeneric.VersionedAttributes, versionedParams runtime.Object, runtimeCELCostBudget int64) ValidateResult {
return ValidateResult{
Decisions: []PolicyDecision{
{
Action: ActionDeny,
Message: "Denied",
},
},
}
})
@ -1235,11 +1309,13 @@ func TestEmptyParamSource(t *testing.T) {
}
})
validator.RegisterDefinition(denyPolicy, func(versionedAttr *whgeneric.VersionedAttributes, versionedParams runtime.Object, runtimeCELCostBudget int64) []PolicyDecision {
return []PolicyDecision{
{
Action: ActionDeny,
Message: "Denied",
validator.RegisterDefinition(denyPolicy, func(versionedAttr *whgeneric.VersionedAttributes, versionedParams runtime.Object, runtimeCELCostBudget int64) ValidateResult {
return ValidateResult{
Decisions: []PolicyDecision{
{
Action: ActionDeny,
Message: "Denied",
},
},
}
})
@ -1335,11 +1411,13 @@ func TestMultiplePoliciesSharedParamType(t *testing.T) {
}
})
validator1.RegisterDefinition(&policy1, func(versionedAttr *whgeneric.VersionedAttributes, versionedParams runtime.Object, runtimeCELCostBudget int64) []PolicyDecision {
validator1.RegisterDefinition(&policy1, func(versionedAttr *whgeneric.VersionedAttributes, versionedParams runtime.Object, runtimeCELCostBudget int64) ValidateResult {
evaluations1.Add(1)
return []PolicyDecision{
{
Action: ActionAdmit,
return ValidateResult{
Decisions: []PolicyDecision{
{
Action: ActionAdmit,
},
},
}
})
@ -1352,12 +1430,14 @@ func TestMultiplePoliciesSharedParamType(t *testing.T) {
}
})
validator2.RegisterDefinition(&policy2, func(versionedAttr *whgeneric.VersionedAttributes, versionedParams runtime.Object, runtimeCELCostBudget int64) []PolicyDecision {
validator2.RegisterDefinition(&policy2, func(versionedAttr *whgeneric.VersionedAttributes, versionedParams runtime.Object, runtimeCELCostBudget int64) ValidateResult {
evaluations2.Add(1)
return []PolicyDecision{
{
Action: ActionDeny,
Message: "Policy2Denied",
return ValidateResult{
Decisions: []PolicyDecision{
{
Action: ActionDeny,
Message: "Policy2Denied",
},
},
}
})
@ -1460,20 +1540,24 @@ func TestNativeTypeParam(t *testing.T) {
}
})
validator.RegisterDefinition(&nativeTypeParamPolicy, func(versionedAttr *whgeneric.VersionedAttributes, versionedParams runtime.Object, runtimeCELCostBudget int64) []PolicyDecision {
validator.RegisterDefinition(&nativeTypeParamPolicy, func(versionedAttr *whgeneric.VersionedAttributes, versionedParams runtime.Object, runtimeCELCostBudget int64) ValidateResult {
evaluations.Add(1)
if _, ok := versionedParams.(*v1.ConfigMap); ok {
return []PolicyDecision{
{
Action: ActionDeny,
Message: "correct type",
return ValidateResult{
Decisions: []PolicyDecision{
{
Action: ActionDeny,
Message: "correct type",
},
},
}
}
return []PolicyDecision{
{
Action: ActionDeny,
Message: "Incorrect param type",
return ValidateResult{
Decisions: []PolicyDecision{
{
Action: ActionDeny,
Message: "Incorrect param type",
},
},
}
})
@ -1516,6 +1600,366 @@ func TestNativeTypeParam(t *testing.T) {
require.EqualValues(t, 1, evaluations.Load())
}
func TestAuditValidationAction(t *testing.T) {
testContext, testContextCancel := context.WithCancel(context.Background())
defer testContextCancel()
compiler := &fakeCompiler{}
validator := &fakeValidator{}
matcher := &fakeMatcher{
DefaultMatch: true,
}
handler, _, tracker, controller := setupFakeTest(t, compiler, matcher)
// Push some fake
noParamSourcePolicy := *denyPolicy
noParamSourcePolicy.Spec.ParamKind = nil
compiler.RegisterDefinition(denyPolicy, func([]cel.ExpressionAccessor, cel.OptionalVariableDeclarations) cel.Filter {
return &fakeFilter{
keyId: denyPolicy.Spec.Validations[0].Expression,
}
})
validator.RegisterDefinition(denyPolicy, func(versionedAttr *whgeneric.VersionedAttributes, versionedParams runtime.Object, runtimeCELCostBudget int64) ValidateResult {
return ValidateResult{
Decisions: []PolicyDecision{
{
Action: ActionDeny,
Message: "I'm sorry Dave",
},
},
}
})
require.NoError(t, tracker.Create(definitionsGVR, &noParamSourcePolicy, noParamSourcePolicy.Namespace))
require.NoError(t, tracker.Create(bindingsGVR, denyBindingWithAudit, denyBindingWithAudit.Namespace))
// Wait for controller to reconcile given objects
require.NoError(t,
waitForReconcile(
testContext, controller,
denyBindingWithAudit, &noParamSourcePolicy))
attr := attributeRecord(nil, fakeParams, admission.Create)
warningRecorder := newWarningRecorder()
warnCtx := warning.WithWarningRecorder(testContext, warningRecorder)
err := handler.Validate(
warnCtx,
attr,
&admission.RuntimeObjectInterfaces{},
)
require.Equal(t, 0, warningRecorder.len())
annotations := attr.GetAnnotations(auditinternal.LevelMetadata)
require.Equal(t, 1, len(annotations))
valueJson, ok := annotations["validation.policy.admission.k8s.io/validation_failure"]
require.True(t, ok)
var value []validationFailureValue
jsonErr := utiljson.Unmarshal([]byte(valueJson), &value)
require.NoError(t, jsonErr)
expected := []validationFailureValue{{
ExpressionIndex: 0,
Message: "I'm sorry Dave",
ValidationActions: []v1alpha1.ValidationAction{v1alpha1.Audit},
Binding: "denybinding.example.com",
Policy: noParamSourcePolicy.Name,
}}
require.Equal(t, expected, value)
require.NoError(t, err)
}
func TestWarnValidationAction(t *testing.T) {
testContext, testContextCancel := context.WithCancel(context.Background())
defer testContextCancel()
compiler := &fakeCompiler{}
validator := &fakeValidator{}
matcher := &fakeMatcher{
DefaultMatch: true,
}
handler, _, tracker, controller := setupFakeTest(t, compiler, matcher)
// Push some fake
noParamSourcePolicy := *denyPolicy
noParamSourcePolicy.Spec.ParamKind = nil
compiler.RegisterDefinition(denyPolicy, func([]cel.ExpressionAccessor, cel.OptionalVariableDeclarations) cel.Filter {
return &fakeFilter{
keyId: denyPolicy.Spec.Validations[0].Expression,
}
})
validator.RegisterDefinition(denyPolicy, func(versionedAttr *whgeneric.VersionedAttributes, versionedParams runtime.Object, runtimeCELCostBudget int64) ValidateResult {
return ValidateResult{
Decisions: []PolicyDecision{
{
Action: ActionDeny,
Message: "I'm sorry Dave",
},
},
}
})
require.NoError(t, tracker.Create(definitionsGVR, &noParamSourcePolicy, noParamSourcePolicy.Namespace))
require.NoError(t, tracker.Create(bindingsGVR, denyBindingWithWarn, denyBindingWithWarn.Namespace))
// Wait for controller to reconcile given objects
require.NoError(t,
waitForReconcile(
testContext, controller,
denyBindingWithWarn, &noParamSourcePolicy))
attr := attributeRecord(nil, fakeParams, admission.Create)
warningRecorder := newWarningRecorder()
warnCtx := warning.WithWarningRecorder(testContext, warningRecorder)
err := handler.Validate(
warnCtx,
attr,
&admission.RuntimeObjectInterfaces{},
)
require.Equal(t, 1, warningRecorder.len())
require.True(t, warningRecorder.hasWarning("Validation failed for ValidatingAdmissionPolicy 'denypolicy.example.com' with binding 'denybinding.example.com': I'm sorry Dave"))
annotations := attr.GetAnnotations(auditinternal.LevelMetadata)
require.Equal(t, 0, len(annotations))
require.NoError(t, err)
}
func TestAllValidationActions(t *testing.T) {
testContext, testContextCancel := context.WithCancel(context.Background())
defer testContextCancel()
compiler := &fakeCompiler{}
validator := &fakeValidator{}
matcher := &fakeMatcher{
DefaultMatch: true,
}
handler, _, tracker, controller := setupFakeTest(t, compiler, matcher)
// Push some fake
noParamSourcePolicy := *denyPolicy
noParamSourcePolicy.Spec.ParamKind = nil
compiler.RegisterDefinition(denyPolicy, func([]cel.ExpressionAccessor, cel.OptionalVariableDeclarations) cel.Filter {
return &fakeFilter{
keyId: denyPolicy.Spec.Validations[0].Expression,
}
})
validator.RegisterDefinition(denyPolicy, func(versionedAttr *whgeneric.VersionedAttributes, versionedParams runtime.Object, runtimeCELCostBudget int64) ValidateResult {
return ValidateResult{
Decisions: []PolicyDecision{
{
Action: ActionDeny,
Message: "I'm sorry Dave",
},
},
}
})
require.NoError(t, tracker.Create(definitionsGVR, &noParamSourcePolicy, noParamSourcePolicy.Namespace))
require.NoError(t, tracker.Create(bindingsGVR, denyBindingWithAll, denyBindingWithAll.Namespace))
// Wait for controller to reconcile given objects
require.NoError(t,
waitForReconcile(
testContext, controller,
denyBindingWithAll, &noParamSourcePolicy))
attr := attributeRecord(nil, fakeParams, admission.Create)
warningRecorder := newWarningRecorder()
warnCtx := warning.WithWarningRecorder(testContext, warningRecorder)
err := handler.Validate(
warnCtx,
attr,
&admission.RuntimeObjectInterfaces{},
)
require.Equal(t, 1, warningRecorder.len())
require.True(t, warningRecorder.hasWarning("Validation failed for ValidatingAdmissionPolicy 'denypolicy.example.com' with binding 'denybinding.example.com': I'm sorry Dave"))
annotations := attr.GetAnnotations(auditinternal.LevelMetadata)
require.Equal(t, 1, len(annotations))
valueJson, ok := annotations["validation.policy.admission.k8s.io/validation_failure"]
require.True(t, ok)
var value []validationFailureValue
jsonErr := utiljson.Unmarshal([]byte(valueJson), &value)
require.NoError(t, jsonErr)
expected := []validationFailureValue{{
ExpressionIndex: 0,
Message: "I'm sorry Dave",
ValidationActions: []v1alpha1.ValidationAction{v1alpha1.Deny, v1alpha1.Warn, v1alpha1.Audit},
Binding: "denybinding.example.com",
Policy: noParamSourcePolicy.Name,
}}
require.Equal(t, expected, value)
require.ErrorContains(t, err, "I'm sorry Dave")
}
func TestAuditAnnotations(t *testing.T) {
testContext, testContextCancel := context.WithCancel(context.Background())
defer testContextCancel()
compiler := &fakeCompiler{}
validator := &fakeValidator{}
matcher := &fakeMatcher{
DefaultMatch: true,
}
handler, paramsTracker, tracker, controller := setupFakeTest(t, compiler, matcher)
// Push some fake
policy := *denyPolicy
compiler.RegisterDefinition(denyPolicy, func([]cel.ExpressionAccessor, cel.OptionalVariableDeclarations) cel.Filter {
return &fakeFilter{
keyId: denyPolicy.Spec.Validations[0].Expression,
}
})
validator.RegisterDefinition(denyPolicy, func(versionedAttr *whgeneric.VersionedAttributes, versionedParams runtime.Object, runtimeCELCostBudget int64) ValidateResult {
o, err := meta.Accessor(versionedParams)
if err != nil {
t.Fatal(err)
}
exampleValue := "normal-value"
if o.GetName() == "replicas-test2.example.com" {
exampleValue = "special-value"
}
return ValidateResult{
AuditAnnotations: []PolicyAuditAnnotation{
{
Key: "example-key",
Value: exampleValue,
Action: AuditAnnotationActionPublish,
},
{
Key: "excluded-key",
Value: "excluded-value",
Action: AuditAnnotationActionExclude,
},
{
Key: "error-key",
Action: AuditAnnotationActionError,
Error: "example error",
},
},
}
})
fakeParams2 := fakeParams.DeepCopy()
fakeParams2.SetName("replicas-test2.example.com")
denyBinding2 := denyBinding.DeepCopy()
denyBinding2.SetName("denybinding2.example.com")
denyBinding2.Spec.ParamRef.Name = fakeParams2.GetName()
fakeParams3 := fakeParams.DeepCopy()
fakeParams3.SetName("replicas-test3.example.com")
denyBinding3 := denyBinding.DeepCopy()
denyBinding3.SetName("denybinding3.example.com")
denyBinding3.Spec.ParamRef.Name = fakeParams3.GetName()
require.NoError(t, paramsTracker.Add(fakeParams))
require.NoError(t, paramsTracker.Add(fakeParams2))
require.NoError(t, paramsTracker.Add(fakeParams3))
require.NoError(t, tracker.Create(definitionsGVR, &policy, policy.Namespace))
require.NoError(t, tracker.Create(bindingsGVR, denyBinding, denyBinding.Namespace))
require.NoError(t, tracker.Create(bindingsGVR, denyBinding2, denyBinding2.Namespace))
require.NoError(t, tracker.Create(bindingsGVR, denyBinding3, denyBinding3.Namespace))
// Wait for controller to reconcile given objects
require.NoError(t,
waitForReconcile(
testContext, controller,
denyBinding, denyBinding2, denyBinding3, denyPolicy, fakeParams, fakeParams2, fakeParams3))
attr := attributeRecord(nil, fakeParams, admission.Create)
err := handler.Validate(
testContext,
attr,
&admission.RuntimeObjectInterfaces{},
)
annotations := attr.GetAnnotations(auditinternal.LevelMetadata)
require.Equal(t, 1, len(annotations))
value := annotations[policy.Name+"/example-key"]
parts := strings.Split(value, ", ")
require.Equal(t, 2, len(parts))
require.Contains(t, parts, "normal-value", "special-value")
require.ErrorContains(t, err, "example error")
}
// FakeAttributes decorates admission.Attributes. It's used to trace the added annotations.
type FakeAttributes struct {
admission.Attributes
annotations map[string]string
mutex sync.Mutex
}
// AddAnnotation adds an annotation key value pair to FakeAttributes
func (f *FakeAttributes) AddAnnotation(k, v string) error {
return f.AddAnnotationWithLevel(k, v, auditinternal.LevelMetadata)
}
// AddAnnotationWithLevel adds an annotation key value pair to FakeAttributes
func (f *FakeAttributes) AddAnnotationWithLevel(k, v string, _ auditinternal.Level) error {
f.mutex.Lock()
defer f.mutex.Unlock()
if err := f.Attributes.AddAnnotation(k, v); err != nil {
return err
}
if f.annotations == nil {
f.annotations = make(map[string]string)
}
f.annotations[k] = v
return nil
}
// GetAnnotations reads annotations from FakeAttributes
func (f *FakeAttributes) GetAnnotations(_ auditinternal.Level) map[string]string {
f.mutex.Lock()
defer f.mutex.Unlock()
annotations := make(map[string]string, len(f.annotations))
for k, v := range f.annotations {
annotations[k] = v
}
return annotations
}
type warningRecorder struct {
sync.Mutex
warnings sets.Set[string]
}
func newWarningRecorder() *warningRecorder {
return &warningRecorder{warnings: sets.New[string]()}
}
func (r *warningRecorder) AddWarning(_, text string) {
r.Lock()
defer r.Unlock()
r.warnings.Insert(text)
return
}
func (r *warningRecorder) hasWarning(text string) bool {
r.Lock()
defer r.Unlock()
return r.warnings.Has(text)
}
func (r *warningRecorder) len() int {
r.Lock()
defer r.Unlock()
return len(r.warnings)
}
type fakeAuthorizer struct{}
func (f fakeAuthorizer) Authorize(ctx context.Context, a authorizer.Attributes) (authorizer.Decision, string, error) {

View File

@ -20,16 +20,19 @@ import (
"context"
"errors"
"fmt"
celconfig "k8s.io/apiserver/pkg/apis/cel"
"strings"
"sync"
"sync/atomic"
"time"
"k8s.io/klog/v2"
"k8s.io/api/admissionregistration/v1alpha1"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
utiljson "k8s.io/apimachinery/pkg/util/json"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apimachinery/pkg/util/wait"
@ -39,7 +42,9 @@ import (
"k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/internal/generic"
"k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/matching"
whgeneric "k8s.io/apiserver/pkg/admission/plugin/webhook/generic"
celconfig "k8s.io/apiserver/pkg/apis/cel"
"k8s.io/apiserver/pkg/authorization/authorizer"
"k8s.io/apiserver/pkg/warning"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/informers"
"k8s.io/client-go/kubernetes"
@ -169,6 +174,8 @@ func (c *celAdmissionController) Run(stopCh <-chan struct{}) {
wg.Wait()
}
const maxAuditAnnotationValueLength = 10 * 1024
func (c *celAdmissionController) Validate(
ctx context.Context,
a admission.Attributes,
@ -239,6 +246,7 @@ func (c *celAdmissionController) Validate(
continue
}
auditAnnotationCollector := newAuditAnnotationCollector()
for _, bindingInfo := range definitionInfo.bindings {
// If the key is inside dependentBindings, there is guaranteed to
// be a bindingInfo for it
@ -321,27 +329,72 @@ func (c *celAdmissionController) Validate(
versionedAttr = va
}
decisions := bindingInfo.validator.Validate(versionedAttr, param, celconfig.RuntimeCELCostBudget)
validationResult := bindingInfo.validator.Validate(versionedAttr, param, celconfig.RuntimeCELCostBudget)
if err != nil {
// runtime error. Apply failure policy
wrappedError := fmt.Errorf("failed to evaluate CEL expression: %w", err)
addConfigError(wrappedError, definition, binding)
continue
}
for _, decision := range decisions {
for i, decision := range validationResult.Decisions {
switch decision.Action {
case ActionAdmit:
if decision.Evaluation == EvalError {
celmetrics.Metrics.ObserveAdmissionWithError(ctx, decision.Elapsed, definition.Name, binding.Name, "active")
}
case ActionDeny:
deniedDecisions = append(deniedDecisions, policyDecisionWithMetadata{
Definition: definition,
Binding: binding,
PolicyDecision: decision,
})
celmetrics.Metrics.ObserveRejection(ctx, decision.Elapsed, definition.Name, binding.Name, "active")
for _, action := range binding.Spec.ValidationActions {
switch action {
case v1alpha1.Deny:
deniedDecisions = append(deniedDecisions, policyDecisionWithMetadata{
Definition: definition,
Binding: binding,
PolicyDecision: decision,
})
celmetrics.Metrics.ObserveRejection(ctx, decision.Elapsed, definition.Name, binding.Name, "active")
case v1alpha1.Audit:
c.publishValidationFailureAnnotation(binding, i, decision, versionedAttr)
celmetrics.Metrics.ObserveAudit(ctx, decision.Elapsed, definition.Name, binding.Name, "active")
case v1alpha1.Warn:
warning.AddWarning(ctx, "", fmt.Sprintf("Validation failed for ValidatingAdmissionPolicy '%s' with binding '%s': %s", definition.Name, binding.Name, decision.Message))
celmetrics.Metrics.ObserveWarn(ctx, decision.Elapsed, definition.Name, binding.Name, "active")
}
}
default:
return fmt.Errorf("unrecognized evaluation decision '%s' for ValidatingAdmissionPolicyBinding '%s' with ValidatingAdmissionPolicy '%s'",
decision.Action, binding.Name, definition.Name)
}
}
for _, auditAnnotation := range validationResult.AuditAnnotations {
switch auditAnnotation.Action {
case AuditAnnotationActionPublish:
value := auditAnnotation.Value
if len(auditAnnotation.Value) > maxAuditAnnotationValueLength {
value = value[:maxAuditAnnotationValueLength]
}
auditAnnotationCollector.add(auditAnnotation.Key, value)
case AuditAnnotationActionError:
// When failurePolicy=fail, audit annotation errors result in deny
deniedDecisions = append(deniedDecisions, policyDecisionWithMetadata{
Definition: definition,
Binding: binding,
PolicyDecision: PolicyDecision{
Action: ActionDeny,
Evaluation: EvalError,
Message: auditAnnotation.Error,
Elapsed: auditAnnotation.Elapsed,
},
})
celmetrics.Metrics.ObserveRejection(ctx, auditAnnotation.Elapsed, definition.Name, binding.Name, "active")
case AuditAnnotationActionExclude: // skip it
default:
return fmt.Errorf("unsupported AuditAnnotation Action: %s", auditAnnotation.Action)
}
}
}
auditAnnotationCollector.publish(definition.Name, a)
}
if len(deniedDecisions) > 0 {
@ -366,6 +419,25 @@ func (c *celAdmissionController) Validate(
return nil
}
func (c *celAdmissionController) publishValidationFailureAnnotation(binding *v1alpha1.ValidatingAdmissionPolicyBinding, expressionIndex int, decision PolicyDecision, attributes admission.Attributes) {
key := "validation.policy.admission.k8s.io/validation_failure"
// Marshal to a list of failures since, in the future, we may need to support multiple failures
valueJson, err := utiljson.Marshal([]validationFailureValue{{
ExpressionIndex: expressionIndex,
Message: decision.Message,
ValidationActions: binding.Spec.ValidationActions,
Binding: binding.Name,
Policy: binding.Spec.PolicyName,
}})
if err != nil {
klog.Warningf("Failed to set admission audit annotation %s for ValidatingAdmissionPolicy %s and ValidatingAdmissionPolicyBinding %s: %v", key, binding.Spec.PolicyName, binding.Name, err)
}
value := string(valueJson)
if err := attributes.AddAnnotation(key, value); err != nil {
klog.Warningf("Failed to set admission audit annotation %s to %s for ValidatingAdmissionPolicy %s and ValidatingAdmissionPolicyBinding %s: %v", key, value, binding.Spec.PolicyName, binding.Name, err)
}
}
func (c *celAdmissionController) HasSynced() bool {
return c.policyController.HasSynced() && c.definitions.Load() != nil
}
@ -377,3 +449,48 @@ func (c *celAdmissionController) ValidateInitialization() error {
func (c *celAdmissionController) refreshPolicies() {
c.definitions.Store(c.policyController.latestPolicyData())
}
// validationFailureValue defines the JSON format of a "validation.policy.admission.k8s.io/validation_failure" audit
// annotation value.
type validationFailureValue struct {
Message string `json:"message"`
Policy string `json:"policy"`
Binding string `json:"binding"`
ExpressionIndex int `json:"expressionIndex"`
ValidationActions []v1alpha1.ValidationAction `json:"validationActions"`
}
type auditAnnotationCollector struct {
annotations map[string][]string
}
func newAuditAnnotationCollector() auditAnnotationCollector {
return auditAnnotationCollector{annotations: map[string][]string{}}
}
func (a auditAnnotationCollector) add(key, value string) {
// If multiple bindings produces the exact same key and value for an audit annotation,
// ignore the duplicates.
for _, v := range a.annotations[key] {
if v == value {
return
}
}
a.annotations[key] = append(a.annotations[key], value)
}
func (a auditAnnotationCollector) publish(policyName string, attributes admission.Attributes) {
for key, bindingAnnotations := range a.annotations {
var value string
if len(bindingAnnotations) == 1 {
value = bindingAnnotations[0]
} else {
// Multiple distinct values can exist when binding params are used in the valueExpression of an auditAnnotation.
// When this happens, the values are concatenated into a comma-separated list.
value = strings.Join(bindingAnnotations, ", ")
}
if err := attributes.AddAnnotation(policyName+"/"+key, value); err != nil {
klog.Warningf("Failed to set admission audit annotation %s to %s for ValidatingAdmissionPolicy %s: %v", key, value, policyName, err)
}
}
}

View File

@ -92,7 +92,7 @@ type policyController struct {
authz authorizer.Authorizer
}
type newValidator func(cel.Filter, *v1.FailurePolicyType, authorizer.Authorizer) Validator
type newValidator func(validationFilter cel.Filter, auditAnnotationFilter cel.Filter, failurePolicy *v1.FailurePolicyType, authorizer authorizer.Authorizer) Validator
func newPolicyController(
restMapper meta.RESTMapper,
@ -461,6 +461,7 @@ func (c *policyController) latestPolicyData() []policyData {
optionalVars := cel.OptionalVariableDeclarations{HasParams: hasParam, HasAuthorizer: true}
bindingInfo.validator = c.newValidator(
c.filterCompiler.Compile(convertv1alpha1Validations(definitionInfo.lastReconciledValue.Spec.Validations), optionalVars, celconfig.PerCallLimit),
c.filterCompiler.Compile(convertv1alpha1AuditAnnotations(definitionInfo.lastReconciledValue.Spec.AuditAnnotations), optionalVars, celconfig.PerCallLimit),
convertv1alpha1FailurePolicyTypeTov1FailurePolicyType(definitionInfo.lastReconciledValue.Spec.FailurePolicy),
c.authz,
)
@ -513,6 +514,18 @@ func convertv1alpha1Validations(inputValidations []v1alpha1.Validation) []cel.Ex
return celExpressionAccessor
}
func convertv1alpha1AuditAnnotations(inputValidations []v1alpha1.AuditAnnotation) []cel.ExpressionAccessor {
celExpressionAccessor := make([]cel.ExpressionAccessor, len(inputValidations))
for i, validation := range inputValidations {
validation := AuditAnnotationCondition{
Key: validation.Key,
ValueExpression: validation.ValueExpression,
}
celExpressionAccessor[i] = &validation
}
return celExpressionAccessor
}
func getNamespaceName(namespace, name string) namespacedName {
return namespacedName{
namespace: namespace,

View File

@ -17,6 +17,8 @@ limitations under the License.
package validatingadmissionpolicy
import (
celgo "github.com/google/cel-go/cel"
"k8s.io/api/admissionregistration/v1alpha1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
@ -39,6 +41,24 @@ func (v *ValidationCondition) GetExpression() string {
return v.Expression
}
func (v *ValidationCondition) ReturnTypes() []*celgo.Type {
return []*celgo.Type{celgo.BoolType}
}
// AuditAnnotationCondition contains the inputs needed to compile, evaluate and publish a cel audit annotation
type AuditAnnotationCondition struct {
Key string
ValueExpression string
}
func (v *AuditAnnotationCondition) GetExpression() string {
return v.ValueExpression
}
func (v *AuditAnnotationCondition) ReturnTypes() []*celgo.Type {
return []*celgo.Type{celgo.StringType, celgo.NullType}
}
// Matcher is used for matching ValidatingAdmissionPolicy and ValidatingAdmissionPolicyBinding to attributes
type Matcher interface {
admission.InitializationValidator
@ -52,9 +72,17 @@ type Matcher interface {
BindingMatches(a admission.Attributes, o admission.ObjectInterfaces, definition *v1alpha1.ValidatingAdmissionPolicyBinding) (bool, error)
}
// ValidateResult defines the result of a Validator.Validate operation.
type ValidateResult struct {
// Decisions specifies the outcome of the validation as well as the details about the decision.
Decisions []PolicyDecision
// AuditAnnotations specifies the audit annotations that should be recorded for the validation.
AuditAnnotations []PolicyAuditAnnotation
}
// Validator is contains logic for converting ValidationEvaluation to PolicyDecisions
type Validator interface {
// Validate is used to take cel evaluations and convert into decisions
// runtimeCELCostBudget was added for testing purpose only. Callers should always use const RuntimeCELCostBudget from k8s.io/apiserver/pkg/apis/cel/config.go as input.
Validate(versionedAttr *generic.VersionedAttributes, versionedParams runtime.Object, runtimeCELCostBudget int64) []PolicyDecision
Validate(versionedAttr *generic.VersionedAttributes, versionedParams runtime.Object, runtimeCELCostBudget int64) ValidateResult
}

View File

@ -47,6 +47,29 @@ type PolicyDecision struct {
Elapsed time.Duration
}
type PolicyAuditAnnotationAction string
const (
// AuditAnnotationActionPublish indicates that the audit annotation should be
// published with the audit event.
AuditAnnotationActionPublish PolicyAuditAnnotationAction = "publish"
// AuditAnnotationActionError indicates that the valueExpression resulted
// in an error.
AuditAnnotationActionError PolicyAuditAnnotationAction = "error"
// AuditAnnotationActionExclude indicates that the audit annotation should be excluded
// because the valueExpression evaluated to null, or because FailurePolicy is Ignore
// and the expression failed with a parse error, type check error, or runtime error.
AuditAnnotationActionExclude PolicyAuditAnnotationAction = "exclude"
)
type PolicyAuditAnnotation struct {
Key string
Value string
Elapsed time.Duration
Action PolicyAuditAnnotationAction
Error string
}
func reasonToCode(r metav1.StatusReason) int32 {
switch r {
case metav1.StatusReasonForbidden:

View File

@ -21,6 +21,7 @@ import (
"strings"
celtypes "github.com/google/cel-go/common/types"
"k8s.io/klog/v2"
v1 "k8s.io/api/admissionregistration/v1"
@ -33,16 +34,18 @@ import (
// validator implements the Validator interface
type validator struct {
filter cel.Filter
failPolicy *v1.FailurePolicyType
authorizer authorizer.Authorizer
validationFilter cel.Filter
auditAnnotationFilter cel.Filter
failPolicy *v1.FailurePolicyType
authorizer authorizer.Authorizer
}
func NewValidator(filter cel.Filter, failPolicy *v1.FailurePolicyType, authorizer authorizer.Authorizer) Validator {
func NewValidator(validationFilter, auditAnnotationFilter cel.Filter, failPolicy *v1.FailurePolicyType, authorizer authorizer.Authorizer) Validator {
return &validator{
filter: filter,
failPolicy: failPolicy,
authorizer: authorizer,
validationFilter: validationFilter,
auditAnnotationFilter: auditAnnotationFilter,
failPolicy: failPolicy,
authorizer: authorizer,
}
}
@ -53,9 +56,16 @@ func policyDecisionActionForError(f v1.FailurePolicyType) PolicyDecisionAction {
return ActionDeny
}
func auditAnnotationEvaluationForError(f v1.FailurePolicyType) PolicyAuditAnnotationAction {
if f == v1.Ignore {
return AuditAnnotationActionExclude
}
return AuditAnnotationActionError
}
// Validate takes a list of Evaluation and a failure policy and converts them into actionable PolicyDecisions
// runtimeCELCostBudget was added for testing purpose only. Callers should always use const RuntimeCELCostBudget from k8s.io/apiserver/pkg/apis/cel/config.go as input.
func (v *validator) Validate(versionedAttr *generic.VersionedAttributes, versionedParams runtime.Object, runtimeCELCostBudget int64) []PolicyDecision {
func (v *validator) Validate(versionedAttr *generic.VersionedAttributes, versionedParams runtime.Object, runtimeCELCostBudget int64) ValidateResult {
var f v1.FailurePolicyType
if v.failPolicy == nil {
f = v1.Fail
@ -64,13 +74,15 @@ func (v *validator) Validate(versionedAttr *generic.VersionedAttributes, version
}
optionalVars := cel.OptionalVariableBindings{VersionedParams: versionedParams, Authorizer: v.authorizer}
evalResults, err := v.filter.ForInput(versionedAttr, cel.CreateAdmissionRequest(versionedAttr.Attributes), optionalVars, runtimeCELCostBudget)
evalResults, err := v.validationFilter.ForInput(versionedAttr, cel.CreateAdmissionRequest(versionedAttr.Attributes), optionalVars, runtimeCELCostBudget)
if err != nil {
return []PolicyDecision{
{
Action: policyDecisionActionForError(f),
Evaluation: EvalError,
Message: err.Error(),
return ValidateResult{
Decisions: []PolicyDecision{
{
Action: policyDecisionActionForError(f),
Evaluation: EvalError,
Message: err.Error(),
},
},
}
}
@ -104,11 +116,60 @@ func (v *validator) Validate(versionedAttr *generic.VersionedAttributes, version
} else {
decision.Message = fmt.Sprintf("failed expression: %v", strings.TrimSpace(validation.Expression))
}
} else {
decision.Action = ActionAdmit
decision.Evaluation = EvalAdmit
}
}
return decisions
options := cel.OptionalVariableBindings{VersionedParams: versionedParams}
auditAnnotationEvalResults, err := v.auditAnnotationFilter.ForInput(versionedAttr, cel.CreateAdmissionRequest(versionedAttr.Attributes), options, runtimeCELCostBudget)
if err != nil {
return ValidateResult{
Decisions: []PolicyDecision{
{
Action: policyDecisionActionForError(f),
Evaluation: EvalError,
Message: err.Error(),
},
},
}
}
auditAnnotationResults := make([]PolicyAuditAnnotation, len(auditAnnotationEvalResults))
for i, evalResult := range auditAnnotationEvalResults {
var auditAnnotationResult = &auditAnnotationResults[i]
// TODO: move this to generics
validation, ok := evalResult.ExpressionAccessor.(*AuditAnnotationCondition)
if !ok {
klog.Error("Invalid type conversion to AuditAnnotationCondition")
auditAnnotationResult.Action = auditAnnotationEvaluationForError(f)
auditAnnotationResult.Error = fmt.Sprintf("Invalid type sent to validator, expected AuditAnnotationCondition but got %T", evalResult.ExpressionAccessor)
continue
}
auditAnnotationResult.Key = validation.Key
if evalResult.Error != nil {
auditAnnotationResult.Action = auditAnnotationEvaluationForError(f)
auditAnnotationResult.Error = evalResult.Error.Error()
} else {
switch evalResult.EvalResult.Type() {
case celtypes.StringType:
value := strings.TrimSpace(evalResult.EvalResult.Value().(string))
if len(value) == 0 {
auditAnnotationResult.Action = AuditAnnotationActionExclude
} else {
auditAnnotationResult.Action = AuditAnnotationActionPublish
auditAnnotationResult.Value = value
}
case celtypes.NullType:
auditAnnotationResult.Action = AuditAnnotationActionExclude
default:
auditAnnotationResult.Action = AuditAnnotationActionError
auditAnnotationResult.Error = fmt.Sprintf("valueExpression '%v' resulted in unsupported return type: %v. "+
"Return type must be either string or null.", validation.ValueExpression, evalResult.EvalResult.Type())
}
}
}
return ValidateResult{Decisions: decisions, AuditAnnotations: auditAnnotationResults}
}

View File

@ -18,6 +18,7 @@ package validatingadmissionpolicy
import (
"errors"
"fmt"
"strings"
"testing"
@ -64,11 +65,13 @@ func TestValidate(t *testing.T) {
fakeVersionedAttr, _ := generic.NewVersionedAttributes(fakeAttr, schema.GroupVersionKind{}, nil)
cases := []struct {
name string
failPolicy *v1.FailurePolicyType
evaluations []cel.EvaluationResult
policyDecision []PolicyDecision
throwError bool
name string
failPolicy *v1.FailurePolicyType
evaluations []cel.EvaluationResult
auditEvaluations []cel.EvaluationResult
policyDecision []PolicyDecision
auditAnnotations []PolicyAuditAnnotation
throwError bool
}{
{
name: "test pass",
@ -455,30 +458,161 @@ func TestValidate(t *testing.T) {
failPolicy: &fail,
throwError: true,
},
{
name: "test empty validations with non-empty audit annotations",
auditEvaluations: []cel.EvaluationResult{
{
EvalResult: celtypes.String("string value"),
ExpressionAccessor: &AuditAnnotationCondition{
ValueExpression: "'string value'",
},
},
},
failPolicy: &fail,
auditAnnotations: []PolicyAuditAnnotation{
{
Action: AuditAnnotationActionPublish,
Value: "string value",
},
},
},
{
name: "test non-empty validations with non-empty audit annotations",
evaluations: []cel.EvaluationResult{
{
EvalResult: celtypes.True,
ExpressionAccessor: &ValidationCondition{
Reason: &forbiddenReason,
Expression: "this.expression == unit.test",
Message: "test1",
},
},
},
auditEvaluations: []cel.EvaluationResult{
{
EvalResult: celtypes.String("string value"),
ExpressionAccessor: &AuditAnnotationCondition{
ValueExpression: "'string value'",
},
},
},
policyDecision: []PolicyDecision{
{
Action: ActionAdmit,
},
},
auditAnnotations: []PolicyAuditAnnotation{
{
Action: AuditAnnotationActionPublish,
Value: "string value",
},
},
failPolicy: &fail,
},
{
name: "test audit annotations with null return",
auditEvaluations: []cel.EvaluationResult{
{
EvalResult: celtypes.NullValue,
ExpressionAccessor: &AuditAnnotationCondition{
ValueExpression: "null",
},
},
{
EvalResult: celtypes.String("string value"),
ExpressionAccessor: &AuditAnnotationCondition{
ValueExpression: "'string value'",
},
},
},
auditAnnotations: []PolicyAuditAnnotation{
{
Action: AuditAnnotationActionExclude,
},
{
Action: AuditAnnotationActionPublish,
Value: "string value",
},
},
failPolicy: &fail,
},
{
name: "test audit annotations with failPolicy=fail",
auditEvaluations: []cel.EvaluationResult{
{
Error: fmt.Errorf("valueExpression ''this is not valid CEL' resulted in error: <nil>"),
ExpressionAccessor: &AuditAnnotationCondition{
ValueExpression: "'this is not valid CEL",
},
},
},
auditAnnotations: []PolicyAuditAnnotation{
{
Action: AuditAnnotationActionError,
Error: "valueExpression ''this is not valid CEL' resulted in error: <nil>",
},
},
failPolicy: &fail,
},
{
name: "test audit annotations with failPolicy=ignore",
auditEvaluations: []cel.EvaluationResult{
{
Error: fmt.Errorf("valueExpression ''this is not valid CEL' resulted in error: <nil>"),
ExpressionAccessor: &AuditAnnotationCondition{
ValueExpression: "'this is not valid CEL",
},
},
},
auditAnnotations: []PolicyAuditAnnotation{
{
Action: AuditAnnotationActionExclude, // TODO: is this right?
Error: "valueExpression ''this is not valid CEL' resulted in error: <nil>",
},
},
failPolicy: &ignore,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
v := validator{
failPolicy: tc.failPolicy,
filter: &fakeCelFilter{
validationFilter: &fakeCelFilter{
evaluations: tc.evaluations,
throwError: tc.throwError,
},
auditAnnotationFilter: &fakeCelFilter{
evaluations: tc.auditEvaluations,
throwError: tc.throwError,
},
}
validateResult := v.Validate(fakeVersionedAttr, nil, celconfig.RuntimeCELCostBudget)
policyResults := v.Validate(fakeVersionedAttr, nil, celconfig.RuntimeCELCostBudget)
require.Equal(t, len(policyResults), len(tc.policyDecision))
require.Equal(t, len(validateResult.Decisions), len(tc.policyDecision))
for i, policyDecision := range tc.policyDecision {
if policyDecision.Action != policyResults[i].Action {
t.Errorf("Expected policy decision kind '%v' but got '%v'", policyDecision.Action, policyResults[i].Action)
if policyDecision.Action != validateResult.Decisions[i].Action {
t.Errorf("Expected policy decision kind '%v' but got '%v'", policyDecision.Action, validateResult.Decisions[i].Action)
}
if !strings.Contains(policyResults[i].Message, policyDecision.Message) {
t.Errorf("Expected policy decision message contains '%v' but got '%v'", policyDecision.Message, policyResults[i].Message)
if !strings.Contains(validateResult.Decisions[i].Message, policyDecision.Message) {
t.Errorf("Expected policy decision message contains '%v' but got '%v'", policyDecision.Message, validateResult.Decisions[i].Message)
}
if policyDecision.Reason != policyResults[i].Reason {
t.Errorf("Expected policy decision reason '%v' but got '%v'", policyDecision.Reason, policyResults[i].Reason)
if policyDecision.Reason != validateResult.Decisions[i].Reason {
t.Errorf("Expected policy decision reason '%v' but got '%v'", policyDecision.Reason, validateResult.Decisions[i].Reason)
}
}
require.Equal(t, len(tc.auditEvaluations), len(validateResult.AuditAnnotations))
for i, auditAnnotation := range tc.auditAnnotations {
actual := validateResult.AuditAnnotations[i]
if auditAnnotation.Action != actual.Action {
t.Errorf("Expected policy audit annotation action '%v' but got '%v'", auditAnnotation.Action, actual.Action)
}
if auditAnnotation.Error != actual.Error {
t.Errorf("Expected audit annotation error '%v' but got '%v'", auditAnnotation.Error, actual.Error)
}
if auditAnnotation.Value != actual.Value {
t.Errorf("Expected policy audit annotation value '%v' but got '%v'", auditAnnotation.Value, actual.Value)
}
}
})

View File

@ -0,0 +1,48 @@
/*
Copyright The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by applyconfiguration-gen. DO NOT EDIT.
package v1alpha1
// AuditAnnotationApplyConfiguration represents an declarative configuration of the AuditAnnotation type for use
// with apply.
type AuditAnnotationApplyConfiguration struct {
Key *string `json:"key,omitempty"`
ValueExpression *string `json:"valueExpression,omitempty"`
}
// AuditAnnotationApplyConfiguration constructs an declarative configuration of the AuditAnnotation type for use with
// apply.
func AuditAnnotation() *AuditAnnotationApplyConfiguration {
return &AuditAnnotationApplyConfiguration{}
}
// WithKey sets the Key field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the Key field is set to the value of the last call.
func (b *AuditAnnotationApplyConfiguration) WithKey(value string) *AuditAnnotationApplyConfiguration {
b.Key = &value
return b
}
// WithValueExpression sets the ValueExpression field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the ValueExpression field is set to the value of the last call.
func (b *AuditAnnotationApplyConfiguration) WithValueExpression(value string) *AuditAnnotationApplyConfiguration {
b.ValueExpression = &value
return b
}

View File

@ -18,12 +18,17 @@ limitations under the License.
package v1alpha1
import (
admissionregistrationv1alpha1 "k8s.io/api/admissionregistration/v1alpha1"
)
// ValidatingAdmissionPolicyBindingSpecApplyConfiguration represents an declarative configuration of the ValidatingAdmissionPolicyBindingSpec type for use
// with apply.
type ValidatingAdmissionPolicyBindingSpecApplyConfiguration struct {
PolicyName *string `json:"policyName,omitempty"`
ParamRef *ParamRefApplyConfiguration `json:"paramRef,omitempty"`
MatchResources *MatchResourcesApplyConfiguration `json:"matchResources,omitempty"`
PolicyName *string `json:"policyName,omitempty"`
ParamRef *ParamRefApplyConfiguration `json:"paramRef,omitempty"`
MatchResources *MatchResourcesApplyConfiguration `json:"matchResources,omitempty"`
ValidationActions []admissionregistrationv1alpha1.ValidationAction `json:"validationActions,omitempty"`
}
// ValidatingAdmissionPolicyBindingSpecApplyConfiguration constructs an declarative configuration of the ValidatingAdmissionPolicyBindingSpec type for use with
@ -55,3 +60,13 @@ func (b *ValidatingAdmissionPolicyBindingSpecApplyConfiguration) WithMatchResour
b.MatchResources = value
return b
}
// WithValidationActions adds the given value to the ValidationActions field in the declarative configuration
// and returns the receiver, so that objects can be build by chaining "With" function invocations.
// If called multiple times, values provided by each call will be appended to the ValidationActions field.
func (b *ValidatingAdmissionPolicyBindingSpecApplyConfiguration) WithValidationActions(values ...admissionregistrationv1alpha1.ValidationAction) *ValidatingAdmissionPolicyBindingSpecApplyConfiguration {
for i := range values {
b.ValidationActions = append(b.ValidationActions, values[i])
}
return b
}

View File

@ -29,6 +29,7 @@ type ValidatingAdmissionPolicySpecApplyConfiguration struct {
MatchConstraints *MatchResourcesApplyConfiguration `json:"matchConstraints,omitempty"`
Validations []ValidationApplyConfiguration `json:"validations,omitempty"`
FailurePolicy *admissionregistrationv1alpha1.FailurePolicyType `json:"failurePolicy,omitempty"`
AuditAnnotations []AuditAnnotationApplyConfiguration `json:"auditAnnotations,omitempty"`
}
// ValidatingAdmissionPolicySpecApplyConfiguration constructs an declarative configuration of the ValidatingAdmissionPolicySpec type for use with
@ -73,3 +74,16 @@ func (b *ValidatingAdmissionPolicySpecApplyConfiguration) WithFailurePolicy(valu
b.FailurePolicy = &value
return b
}
// WithAuditAnnotations adds the given value to the AuditAnnotations field in the declarative configuration
// and returns the receiver, so that objects can be build by chaining "With" function invocations.
// If called multiple times, values provided by each call will be appended to the AuditAnnotations field.
func (b *ValidatingAdmissionPolicySpecApplyConfiguration) WithAuditAnnotations(values ...*AuditAnnotationApplyConfiguration) *ValidatingAdmissionPolicySpecApplyConfiguration {
for i := range values {
if values[i] == nil {
panic("nil value passed to WithAuditAnnotations")
}
b.AuditAnnotations = append(b.AuditAnnotations, *values[i])
}
return b
}

View File

@ -225,6 +225,17 @@ var schemaYAML = typed.YAMLObject(`types:
- name: url
type:
scalar: string
- name: io.k8s.api.admissionregistration.v1alpha1.AuditAnnotation
map:
fields:
- name: key
type:
scalar: string
default: ""
- name: valueExpression
type:
scalar: string
default: ""
- name: io.k8s.api.admissionregistration.v1alpha1.MatchResources
map:
fields:
@ -353,9 +364,21 @@ var schemaYAML = typed.YAMLObject(`types:
- name: policyName
type:
scalar: string
- name: validationActions
type:
list:
elementType:
scalar: string
elementRelationship: associative
- name: io.k8s.api.admissionregistration.v1alpha1.ValidatingAdmissionPolicySpec
map:
fields:
- name: auditAnnotations
type:
list:
elementType:
namedType: io.k8s.api.admissionregistration.v1alpha1.AuditAnnotation
elementRelationship: atomic
- name: failurePolicy
type:
scalar: string

View File

@ -139,6 +139,8 @@ func ForKind(kind schema.GroupVersionKind) interface{} {
return &admissionregistrationv1.WebhookClientConfigApplyConfiguration{}
// Group=admissionregistration.k8s.io, Version=v1alpha1
case v1alpha1.SchemeGroupVersion.WithKind("AuditAnnotation"):
return &admissionregistrationv1alpha1.AuditAnnotationApplyConfiguration{}
case v1alpha1.SchemeGroupVersion.WithKind("MatchResources"):
return &admissionregistrationv1alpha1.MatchResourcesApplyConfiguration{}
case v1alpha1.SchemeGroupVersion.WithKind("NamedRuleWithOperations"):

View File

@ -18,13 +18,19 @@ package cel
import (
"context"
"fmt"
"os"
"strconv"
"strings"
"sync"
"testing"
"time"
apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
apiextensionsclientset "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset"
"k8s.io/apiextensions-apiserver/test/integration/fixtures"
auditinternal "k8s.io/apiserver/pkg/apis/audit"
auditv1 "k8s.io/apiserver/pkg/apis/audit/v1"
genericfeatures "k8s.io/apiserver/pkg/features"
utilfeature "k8s.io/apiserver/pkg/util/feature"
"k8s.io/client-go/rest"
@ -34,11 +40,13 @@ import (
"k8s.io/kubernetes/test/integration/authutil"
"k8s.io/kubernetes/test/integration/etcd"
"k8s.io/kubernetes/test/integration/framework"
"k8s.io/kubernetes/test/utils"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/dynamic"
clientset "k8s.io/client-go/kubernetes"
@ -252,10 +260,10 @@ func Test_ValidateNamespace_NoParams(t *testing.T) {
err: "",
},
}
for _, testcase := range testcases {
t.Run(testcase.name, func(t *testing.T) {
defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, genericfeatures.ValidatingAdmissionPolicy, true)()
server, err := apiservertesting.StartTestServer(t, nil, []string{
"--enable-admission-plugins", "ValidatingAdmissionPolicy",
}, framework.SharedEtcd())
@ -285,6 +293,190 @@ func Test_ValidateNamespace_NoParams(t *testing.T) {
})
}
}
func Test_ValidateAnnotationsAndWarnings(t *testing.T) {
testcases := []struct {
name string
policy *admissionregistrationv1alpha1.ValidatingAdmissionPolicy
policyBinding *admissionregistrationv1alpha1.ValidatingAdmissionPolicyBinding
object *v1.ConfigMap
err string
failureReason metav1.StatusReason
auditAnnotations map[string]string
warnings sets.Set[string]
}{
{
name: "with audit annotations",
policy: withAuditAnnotations([]admissionregistrationv1alpha1.AuditAnnotation{
{
Key: "example-key",
ValueExpression: "'object name: ' + object.metadata.name",
},
{
Key: "exclude-key",
ValueExpression: "null",
},
}, withParams(configParamKind(), withFailurePolicy(admissionregistrationv1alpha1.Fail, withConfigMapMatch(makePolicy("validate-audit-annotations"))))),
policyBinding: makeBinding("validate-audit-annotations-binding", "validate-audit-annotations", ""),
object: &v1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: "test1-k8s",
},
},
err: "",
auditAnnotations: map[string]string{
"validate-audit-annotations/example-key": `object name: test1-k8s`,
},
},
{
name: "with audit annotations with invalid expression",
policy: withAuditAnnotations([]admissionregistrationv1alpha1.AuditAnnotation{
{
Key: "example-key",
ValueExpression: "string(params.metadata.name)", // runtime error, params is null
},
}, withParams(configParamKind(), withFailurePolicy(admissionregistrationv1alpha1.Fail, withConfigMapMatch(makePolicy("validate-audit-annotations-invalid"))))),
policyBinding: makeBinding("validate-audit-annotations-invalid-binding", "validate-audit-annotations-invalid", ""),
object: &v1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: "test2-k8s",
},
},
err: "configmaps \"test2-k8s\" is forbidden: ValidatingAdmissionPolicy 'validate-audit-annotations-invalid' with binding 'validate-audit-annotations-invalid-binding' denied request: expression 'string(params.metadata.name)' resulted in error: no such key: metadata",
failureReason: metav1.StatusReasonInvalid,
},
{
name: "with audit annotations with invalid expression and ignore failure policy",
policy: withAuditAnnotations([]admissionregistrationv1alpha1.AuditAnnotation{
{
Key: "example-key",
ValueExpression: "string(params.metadata.name)", // runtime error, params is null
},
}, withParams(configParamKind(), withFailurePolicy(admissionregistrationv1alpha1.Ignore, withConfigMapMatch(makePolicy("validate-audit-annotations-invalid-ignore"))))),
policyBinding: makeBinding("validate-audit-annotations-invalid-ignore-binding", "validate-audit-annotations-invalid-ignore", ""),
object: &v1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: "test3-k8s",
},
},
err: "",
},
{
name: "with warn validationActions",
policy: withValidations([]admissionregistrationv1alpha1.Validation{
{
Expression: "object.metadata.name.endsWith('k8s')",
},
}, withParams(configParamKind(), withFailurePolicy(admissionregistrationv1alpha1.Fail, withConfigMapMatch(makePolicy("validate-actions-warn"))))),
policyBinding: withValidationActions([]admissionregistrationv1alpha1.ValidationAction{admissionregistrationv1alpha1.Warn}, makeBinding("validate-actions-warn-binding", "validate-actions-warn", "")),
object: &v1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: "test4-nope",
},
},
warnings: sets.New("Validation failed for ValidatingAdmissionPolicy 'validate-actions-warn' with binding 'validate-actions-warn-binding': failed expression: object.metadata.name.endsWith('k8s')"),
},
{
name: "with audit validationActions",
policy: withValidations([]admissionregistrationv1alpha1.Validation{
{
Expression: "object.metadata.name.endsWith('k8s')",
},
}, withParams(configParamKind(), withFailurePolicy(admissionregistrationv1alpha1.Fail, withConfigMapMatch(makePolicy("validate-actions-audit"))))),
policyBinding: withValidationActions([]admissionregistrationv1alpha1.ValidationAction{admissionregistrationv1alpha1.Deny, admissionregistrationv1alpha1.Audit}, makeBinding("validate-actions-audit-binding", "validate-actions-audit", "")),
object: &v1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: "test5-nope",
},
},
err: "configmaps \"test5-nope\" is forbidden: ValidatingAdmissionPolicy 'validate-actions-audit' with binding 'validate-actions-audit-binding' denied request: failed expression: object.metadata.name.endsWith('k8s')",
failureReason: metav1.StatusReasonInvalid,
auditAnnotations: map[string]string{
"validation.policy.admission.k8s.io/validation_failure": `[{"message":"failed expression: object.metadata.name.endsWith('k8s')","policy":"validate-actions-audit","binding":"validate-actions-audit-binding","expressionIndex":1,"validationActions":["Deny","Audit"]}]`,
},
},
}
defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, genericfeatures.ValidatingAdmissionPolicy, true)()
// prepare audit policy file
policyFile, err := os.CreateTemp("", "audit-policy.yaml")
if err != nil {
t.Fatalf("Failed to create audit policy file: %v", err)
}
defer os.Remove(policyFile.Name())
if _, err := policyFile.Write([]byte(auditPolicy)); err != nil {
t.Fatalf("Failed to write audit policy file: %v", err)
}
if err := policyFile.Close(); err != nil {
t.Fatalf("Failed to close audit policy file: %v", err)
}
// prepare audit log file
logFile, err := os.CreateTemp("", "audit.log")
if err != nil {
t.Fatalf("Failed to create audit log file: %v", err)
}
defer os.Remove(logFile.Name())
server, err := apiservertesting.StartTestServer(t, nil, []string{
"--enable-admission-plugins", "ValidatingAdmissionPolicy",
"--audit-policy-file", policyFile.Name(),
"--audit-log-version", "audit.k8s.io/v1",
"--audit-log-mode", "blocking",
"--audit-log-path", logFile.Name(),
}, framework.SharedEtcd())
if err != nil {
t.Fatal(err)
}
defer server.TearDownFn()
config := server.ClientConfig
warnHandler := newWarningHandler()
config.WarningHandler = warnHandler
config.Impersonate.UserName = testReinvocationClientUsername
client, err := clientset.NewForConfig(config)
if err != nil {
t.Fatal(err)
}
for i, testcase := range testcases {
t.Run(testcase.name, func(t *testing.T) {
testCaseID := strconv.Itoa(i)
ns := "auditannotations-" + testCaseID
_, err = client.CoreV1().Namespaces().Create(context.TODO(), &v1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: ns}}, metav1.CreateOptions{})
if err != nil {
t.Fatal(err)
}
policy := withWaitReadyConstraintAndExpression(testcase.policy)
if _, err := client.AdmissionregistrationV1alpha1().ValidatingAdmissionPolicies().Create(context.TODO(), policy, metav1.CreateOptions{}); err != nil {
t.Fatal(err)
}
if err := createAndWaitReadyNamespacedWithWarnHandler(t, client, withMatchNamespace(testcase.policyBinding, ns), nil, ns, warnHandler); err != nil {
t.Fatal(err)
}
warnHandler.reset()
testcase.object.Namespace = ns
_, err = client.CoreV1().ConfigMaps(ns).Create(context.TODO(), testcase.object, metav1.CreateOptions{})
code := int32(201)
if testcase.err != "" {
code = 422
}
auditAnnotationFilter := func(key, val string) bool {
_, ok := testcase.auditAnnotations[key]
return ok
}
checkExpectedError(t, err, testcase.err)
checkFailureReason(t, err, testcase.failureReason)
checkExpectedWarnings(t, warnHandler, testcase.warnings)
checkAuditEvents(t, logFile, expectedAuditEvents(testcase.auditAnnotations, ns, code), auditAnnotationFilter)
})
}
}
// Test_ValidateNamespace_WithConfigMapParams tests a ValidatingAdmissionPolicy that validates creation of a Namespace,
// using ConfigMap as a param reference.
@ -2254,14 +2446,22 @@ func withWaitReadyConstraintAndExpression(policy *admissionregistrationv1alpha1.
}
func createAndWaitReady(t *testing.T, client *clientset.Clientset, binding *admissionregistrationv1alpha1.ValidatingAdmissionPolicyBinding, matchLabels map[string]string) error {
marker := &v1.Endpoints{ObjectMeta: metav1.ObjectMeta{Name: "test-marker", Namespace: "default", Labels: matchLabels}}
return createAndWaitReadyNamespaced(t, client, binding, matchLabels, "default")
}
func createAndWaitReadyNamespaced(t *testing.T, client *clientset.Clientset, binding *admissionregistrationv1alpha1.ValidatingAdmissionPolicyBinding, matchLabels map[string]string, ns string) error {
return createAndWaitReadyNamespacedWithWarnHandler(t, client, binding, matchLabels, ns, newWarningHandler())
}
func createAndWaitReadyNamespacedWithWarnHandler(t *testing.T, client *clientset.Clientset, binding *admissionregistrationv1alpha1.ValidatingAdmissionPolicyBinding, matchLabels map[string]string, ns string, handler *warningHandler) error {
marker := &v1.Endpoints{ObjectMeta: metav1.ObjectMeta{Name: "test-marker", Namespace: ns, Labels: matchLabels}}
defer func() {
err := client.CoreV1().Endpoints("default").Delete(context.TODO(), marker.Name, metav1.DeleteOptions{})
err := client.CoreV1().Endpoints(ns).Delete(context.TODO(), marker.Name, metav1.DeleteOptions{})
if err != nil {
t.Logf("error deleting marker: %v", err)
}
}()
marker, err := client.CoreV1().Endpoints("default").Create(context.TODO(), marker, metav1.CreateOptions{})
marker, err := client.CoreV1().Endpoints(ns).Create(context.TODO(), marker, metav1.CreateOptions{})
if err != nil {
return err
}
@ -2272,7 +2472,11 @@ func createAndWaitReady(t *testing.T, client *clientset.Clientset, binding *admi
}
if waitErr := wait.PollImmediate(time.Millisecond*5, wait.ForeverTestTimeout, func() (bool, error) {
_, err := client.CoreV1().Endpoints("default").Patch(context.TODO(), marker.Name, types.JSONPatchType, []byte("[]"), metav1.PatchOptions{})
handler.reset()
_, err := client.CoreV1().Endpoints(ns).Patch(context.TODO(), marker.Name, types.JSONPatchType, []byte("[]"), metav1.PatchOptions{})
if handler.hasObservedMarker() {
return true, nil
}
if err != nil && strings.Contains(err.Error(), "marker denied; policy is ready") {
return true, nil
} else if err != nil && strings.Contains(err.Error(), "not yet synced to use for admission") {
@ -2285,9 +2489,26 @@ func createAndWaitReady(t *testing.T, client *clientset.Clientset, binding *admi
}); waitErr != nil {
return waitErr
}
t.Logf("Marker ready: %v", marker)
handler.reset()
return nil
}
func withMatchNamespace(binding *admissionregistrationv1alpha1.ValidatingAdmissionPolicyBinding, ns string) *admissionregistrationv1alpha1.ValidatingAdmissionPolicyBinding {
binding.Spec.MatchResources = &admissionregistrationv1alpha1.MatchResources{
NamespaceSelector: &metav1.LabelSelector{
MatchExpressions: []metav1.LabelSelectorRequirement{
{
Key: "kubernetes.io/metadata.name",
Operator: metav1.LabelSelectorOpIn,
Values: []string{ns},
},
},
},
}
return binding
}
func makePolicy(name string) *admissionregistrationv1alpha1.ValidatingAdmissionPolicy {
return &admissionregistrationv1alpha1.ValidatingAdmissionPolicy{
ObjectMeta: metav1.ObjectMeta{Name: name},
@ -2395,6 +2616,11 @@ func withValidations(validations []admissionregistrationv1alpha1.Validation, pol
return policy
}
func withAuditAnnotations(auditAnnotations []admissionregistrationv1alpha1.AuditAnnotation, policy *admissionregistrationv1alpha1.ValidatingAdmissionPolicy) *admissionregistrationv1alpha1.ValidatingAdmissionPolicy {
policy.Spec.AuditAnnotations = auditAnnotations
return policy
}
func makeBinding(name, policyName, paramName string) *admissionregistrationv1alpha1.ValidatingAdmissionPolicyBinding {
var paramRef *admissionregistrationv1alpha1.ParamRef
if paramName != "" {
@ -2406,12 +2632,18 @@ func makeBinding(name, policyName, paramName string) *admissionregistrationv1alp
return &admissionregistrationv1alpha1.ValidatingAdmissionPolicyBinding{
ObjectMeta: metav1.ObjectMeta{Name: name},
Spec: admissionregistrationv1alpha1.ValidatingAdmissionPolicyBindingSpec{
PolicyName: policyName,
ParamRef: paramRef,
PolicyName: policyName,
ParamRef: paramRef,
ValidationActions: []admissionregistrationv1alpha1.ValidationAction{admissionregistrationv1alpha1.Deny},
},
}
}
func withValidationActions(validationActions []admissionregistrationv1alpha1.ValidationAction, binding *admissionregistrationv1alpha1.ValidatingAdmissionPolicyBinding) *admissionregistrationv1alpha1.ValidatingAdmissionPolicyBinding {
binding.Spec.ValidationActions = validationActions
return binding
}
func withBindingExistsLabels(labels []string, policy *admissionregistrationv1alpha1.ValidatingAdmissionPolicy, binding *admissionregistrationv1alpha1.ValidatingAdmissionPolicyBinding) *admissionregistrationv1alpha1.ValidatingAdmissionPolicyBinding {
if policy != nil {
// shallow copy
@ -2468,6 +2700,36 @@ func checkFailureReason(t *testing.T, err error, expectedReason metav1.StatusRea
}
}
func checkExpectedWarnings(t *testing.T, recordedWarnings *warningHandler, expectedWarnings sets.Set[string]) {
if !recordedWarnings.equals(expectedWarnings) {
t.Errorf("Expected warnings '%v' but got '%v", expectedWarnings, recordedWarnings)
}
}
func checkAuditEvents(t *testing.T, logFile *os.File, auditEvents []utils.AuditEvent, filter utils.AuditAnnotationsFilter) {
stream, err := os.OpenFile(logFile.Name(), os.O_RDWR, 0600)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
defer stream.Close()
if auditEvents != nil {
missing, err := utils.CheckAuditLinesFiltered(stream, auditEvents, auditv1.SchemeGroupVersion, filter)
if err != nil {
t.Errorf("unexpected error checking audit lines: %v", err)
}
if len(missing.MissingEvents) > 0 {
t.Errorf("failed to get expected events -- missing: %s", missing)
}
}
if err := stream.Truncate(0); err != nil {
t.Errorf("unexpected error truncate file: %v", err)
}
if _, err := stream.Seek(0, 0); err != nil {
t.Errorf("unexpected error reset offset: %v", err)
}
}
func withCRDParamKind(kind, crdGroup, crdVersion string) *admissionregistrationv1alpha1.ParamKind {
return &admissionregistrationv1alpha1.ParamKind{
APIVersion: crdGroup + "/" + crdVersion,
@ -2544,3 +2806,82 @@ func versionedCustomResourceDefinition() *apiextensionsv1.CustomResourceDefiniti
},
}
}
type warningHandler struct {
lock sync.Mutex
warnings sets.Set[string]
observedMarker bool
}
func newWarningHandler() *warningHandler {
return &warningHandler{warnings: sets.New[string]()}
}
func (w *warningHandler) reset() {
w.lock.Lock()
defer w.lock.Unlock()
w.warnings = sets.New[string]()
w.observedMarker = false
}
func (w *warningHandler) equals(s sets.Set[string]) bool {
w.lock.Lock()
defer w.lock.Unlock()
return w.warnings.Equal(s)
}
func (w *warningHandler) hasObservedMarker() bool {
w.lock.Lock()
defer w.lock.Unlock()
return w.observedMarker
}
func (w *warningHandler) HandleWarningHeader(code int, _ string, message string) {
if strings.HasSuffix(message, "marker denied; policy is ready") {
func() {
w.lock.Lock()
defer w.lock.Unlock()
w.observedMarker = true
}()
}
if code != 299 || len(message) == 0 {
return
}
w.lock.Lock()
defer w.lock.Unlock()
w.warnings.Insert(message)
}
func expectedAuditEvents(auditAnnotations map[string]string, ns string, code int32) []utils.AuditEvent {
return []utils.AuditEvent{
{
Level: auditinternal.LevelRequest,
Stage: auditinternal.StageResponseComplete,
RequestURI: fmt.Sprintf("/api/v1/namespaces/%s/configmaps", ns),
Verb: "create",
Code: code,
User: "system:apiserver",
ImpersonatedUser: testReinvocationClientUsername,
ImpersonatedGroups: "system:authenticated",
Resource: "configmaps",
Namespace: ns,
AuthorizeDecision: "allow",
RequestObject: true,
ResponseObject: false,
CustomAuditAnnotations: auditAnnotations,
},
}
}
const (
testReinvocationClientUsername = "webhook-reinvocation-integration-client"
auditPolicy = `
apiVersion: audit.k8s.io/v1
kind: Policy
rules:
- level: Request
resources:
- group: "" # core
resources: ["configmaps"]
`
)

View File

@ -21,6 +21,7 @@ import (
"k8s.io/apiextensions-apiserver/test/integration/fixtures"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/kubernetes/test/utils/image"
)
@ -388,7 +389,7 @@ func GetEtcdStorageDataForNamespace(namespace string) map[schema.GroupVersionRes
ExpectedEtcdPath: "/registry/validatingadmissionpolicies/vap1",
},
gvr("admissionregistration.k8s.io", "v1alpha1", "validatingadmissionpolicybindings"): {
Stub: `{"metadata":{"name":"pb1","creationTimestamp":null},"spec":{"policyName":"replicalimit-policy.example.com","paramRef":{"name":"replica-limit-test.example.com"}}}`,
Stub: `{"metadata":{"name":"pb1","creationTimestamp":null},"spec":{"policyName":"replicalimit-policy.example.com","paramRef":{"name":"replica-limit-test.example.com"},"validationActions":["Deny"]}}`,
ExpectedEtcdPath: "/registry/validatingadmissionpolicybindings/pb1",
},
// --

View File

@ -53,8 +53,13 @@ type AuditEvent struct {
// not reference these maps after calling the Check functions.
AdmissionWebhookMutationAnnotations map[string]string
AdmissionWebhookPatchAnnotations map[string]string
// Only populated when a filter is provided to testEventFromInternalFiltered
CustomAuditAnnotations map[string]string
}
type AuditAnnotationsFilter func(key, val string) bool
// MissingEventsReport provides an analysis if any events are missing
type MissingEventsReport struct {
FirstEventChecked *auditinternal.Event
@ -78,6 +83,13 @@ func (m *MissingEventsReport) String() string {
// CheckAuditLines searches the audit log for the expected audit lines.
func CheckAuditLines(stream io.Reader, expected []AuditEvent, version schema.GroupVersion) (missingReport *MissingEventsReport, err error) {
return CheckAuditLinesFiltered(stream, expected, version, nil)
}
// CheckAuditLinesFiltered searches the audit log for the expected audit lines, customAnnotationsFilter
// controls which audit annotations are added to AuditEvent.CustomAuditAnnotations.
// If the customAnnotationsFilter is nil, AuditEvent.CustomAuditAnnotations will be empty.
func CheckAuditLinesFiltered(stream io.Reader, expected []AuditEvent, version schema.GroupVersion, customAnnotationsFilter AuditAnnotationsFilter) (missingReport *MissingEventsReport, err error) {
expectations := newAuditEventTracker(expected)
scanner := bufio.NewScanner(stream)
@ -100,7 +112,7 @@ func CheckAuditLines(stream io.Reader, expected []AuditEvent, version schema.Gro
}
missingReport.LastEventChecked = e
event, err := testEventFromInternal(e)
event, err := testEventFromInternalFiltered(e, customAnnotationsFilter)
if err != nil {
return missingReport, err
}
@ -162,6 +174,13 @@ func CheckForDuplicates(el auditinternal.EventList) (auditinternal.EventList, er
// testEventFromInternal takes an internal audit event and returns a test event
func testEventFromInternal(e *auditinternal.Event) (AuditEvent, error) {
return testEventFromInternalFiltered(e, nil)
}
// testEventFromInternalFiltered takes an internal audit event and returns a test event, customAnnotationsFilter
// controls which audit annotations are added to AuditEvent.CustomAuditAnnotations.
// If the customAnnotationsFilter is nil, AuditEvent.CustomAuditAnnotations will be empty.
func testEventFromInternalFiltered(e *auditinternal.Event, customAnnotationsFilter AuditAnnotationsFilter) (AuditEvent, error) {
event := AuditEvent{
Level: e.Level,
Stage: e.Stage,
@ -199,6 +218,11 @@ func testEventFromInternal(e *auditinternal.Event) (AuditEvent, error) {
event.AdmissionWebhookMutationAnnotations = map[string]string{}
}
event.AdmissionWebhookMutationAnnotations[k] = v
} else if customAnnotationsFilter != nil && customAnnotationsFilter(k, v) {
if event.CustomAuditAnnotations == nil {
event.CustomAuditAnnotations = map[string]string{}
}
event.CustomAuditAnnotations[k] = v
}
}
return event, nil