1
0
Fork 0
mirror of https://github.com/kyverno/kyverno.git synced 2024-12-15 17:51:20 +00:00
kyverno/pkg/policy/on_update_policy_test.go
shuting b4f2b63f53
Load mutate.targets via dclient (#3797)
* Load mutate.targets via dclient

Signed-off-by: ShutingZhao <shuting@nirmata.com>

* Do not fail on namespace cleanup for e2e generate

Signed-off-by: ShutingZhao <shuting@nirmata.com>

* Fix wildcard name listing for a certain namespace

Signed-off-by: ShutingZhao <shuting@nirmata.com>

* Rename onPolicyUpdate to mutateExistingOnPolicyUpdate

Signed-off-by: ShutingZhao <shuting@nirmata.com>

* Enable "mutateExistingOnPolicyUpdate" on policy events

Signed-off-by: ShutingZhao <shuting@nirmata.com>

Co-authored-by: Prateek Pandey <prateek.pandey@nirmata.com>
2022-05-06 05:46:36 +00:00

109 lines
2.2 KiB
Go

package policy
import (
"encoding/json"
"testing"
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
"gotest.tools/assert"
)
func Test_valid_onUpdatePolicyPolicy(t *testing.T) {
rawPolicy := []byte(`{
"apiVersion": "kyverno.io/v1",
"kind": "ClusterPolicy",
"metadata": {
"name": "test-gen",
"annotations": {
"policies.kyverno.io/category": "Best Practices"
}
},
"spec": {
"rules": [
{
"match": {
"resources": {
"kinds": [
"Namespace"
]
}
},
"name": "test-gen",
"preconditions": {
"all": [
{
"key": "{{request.object.metadata.name}}",
"operator": "NotEquals",
"value": ""
}
]
},
"validate": {
"message": "The only label that may be removed or changed is breakglass.",
"deny": {
"conditions": {
"any": [
{
"key": "{{ request.object.metadata.labels | merge(@, {breakglass:null}) }}",
"operator": "NotEquals",
"value": "{{ request.oldObject.metadata.labels | merge(@, {breakglass:null}) }}"
}
]
}
}
}
}
]
}
}`)
var policy kyverno.ClusterPolicy
err := json.Unmarshal(rawPolicy, &policy)
assert.NilError(t, err)
err = ValidateOnPolicyUpdate(&policy, true)
assert.NilError(t, err)
}
func Test_invalid_onUpdatePolicyPolicy(t *testing.T) {
rawPolicy := []byte(`{
"apiVersion": "kyverno.io/v1",
"kind": "ClusterPolicy",
"metadata": {
"name": "who-created-this"
},
"spec": {
"rules": [
{
"name": "who-created-this",
"match": {
"any": [
{
"resources": {
"kinds": [
"Pod"
]
}
}
]
},
"mutate": {
"patchStrategicMerge": {
"metadata": {
"labels": {
"created-by": "{{request.userInfo.username}}"
}
}
}
}
}
]
}
}`)
var policy kyverno.ClusterPolicy
err := json.Unmarshal(rawPolicy, &policy)
assert.NilError(t, err)
err = ValidateOnPolicyUpdate(&policy, true)
assert.ErrorContains(t, err, "only select variables are allowed in on policy update. Set spec.mutateExistingOnPolicyUpdate=false to disable update policy mode for this policy rule: variable \"{{request.userInfo.username}} is not allowed ")
}