Skip to content

Commit

Permalink
fix kyverno#1585 issue; validate on DELETE the oldResource
Browse files Browse the repository at this point in the history
Signed-off-by: Max Goncharenko <kacejot@fex.net>
  • Loading branch information
kacejot committed Mar 15, 2021
1 parent 10c714d commit 17699e4
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
10 changes: 10 additions & 0 deletions pkg/engine/variables/vars.go
Expand Up @@ -94,6 +94,16 @@ func subValR(log logr.Logger, ctx context.EvalInterface, valuePattern string, pa
variable := strings.ReplaceAll(v, "{{", "")
variable = strings.ReplaceAll(variable, "}}", "")
variable = strings.TrimSpace(variable)

var substitutedVar interface{}
if operation, err := ctx.Query("request.operation"); err != nil {
return nil, fmt.Errorf("failed to resolve %v at path %s", variable, path)
} else {
if operation == "DELETE" {
variable = strings.ReplaceAll(variable, "request.object", "request.oldObject")
}
}

substitutedVar, err := ctx.Query(variable)
if err != nil {
switch err.(type) {
Expand Down
45 changes: 45 additions & 0 deletions pkg/engine/variables/vars_test.go
Expand Up @@ -2,6 +2,7 @@ package variables

import (
"encoding/json"
"fmt"
"testing"

"github.com/kyverno/kyverno/pkg/engine/context"
Expand Down Expand Up @@ -131,6 +132,50 @@ func Test_subVars_failed(t *testing.T) {
}
}

func Test_ReplacingPathWhenDeleting(t *testing.T) {
patternRaw := []byte(`"{{request.object.metadata.annotations.target}}"`)

var resourceRaw = []byte(`
{
"request": {
"operation": "DELETE",
"object": {
"metadata": {
"name": "curr",
"namespace": "ns",
"annotations": {
"target": "foo"
}
}
},
"oldObject": {
"metadata": {
"name": "old",
"annotations": {
"target": "bar"
}
}
}
}
}
`)

var pattern interface{}
var err error
err = json.Unmarshal(patternRaw, &pattern)
if err != nil {
t.Error(err)
}
ctx := context.NewContext()
err = ctx.AddJSON(resourceRaw)
assert.NilError(t, err)

pattern, err = SubstituteVars(log.Log, ctx, pattern)
assert.NilError(t, err)

assert.Equal(t, fmt.Sprintf("%v", pattern), "bar")
}

var resourceRaw = []byte(`
{
"metadata": {
Expand Down

0 comments on commit 17699e4

Please sign in to comment.