From d770d6680b53d6519d08f301c08b75b1f64931d2 Mon Sep 17 00:00:00 2001 From: Shuting Zhao Date: Mon, 22 Feb 2021 17:22:23 -0800 Subject: [PATCH] add request.namespace in the background process Signed-off-by: Shuting Zhao --- pkg/engine/context/context.go | 24 ++++++++++++++++++++++++ pkg/policy/apply.go | 7 ++++++- pkg/policy/background.go | 2 +- 3 files changed, 31 insertions(+), 2 deletions(-) diff --git a/pkg/engine/context/context.go b/pkg/engine/context/context.go index e9320ac7ee..c0a5846c67 100644 --- a/pkg/engine/context/context.go +++ b/pkg/engine/context/context.go @@ -28,6 +28,9 @@ type Interface interface { // AddServiceAccount merges ServiceAccount types AddServiceAccount(userName string) error + // AddNamespace merges resource json under request.namespace + AddNamespace(namespace string) error + EvalInterface } @@ -190,6 +193,27 @@ func (ctx *Context) AddServiceAccount(userName string) error { return nil } +// AddNamespace merges resource json under request.namespace +func (ctx *Context) AddNamespace(namespace string) error { + modifiedResource := struct { + Request interface{} `json:"request"` + }{ + Request: struct { + Namespace string `json:"namespace"` + }{ + Namespace: namespace, + }, + } + + objRaw, err := json.Marshal(modifiedResource) + if err != nil { + ctx.log.Error(err, "failed to marshal the resource") + return err + } + + return ctx.AddJSON(objRaw) +} + // Checkpoint creates a copy of the internal state. // Prior checkpoints will be overridden. func (ctx *Context) Checkpoint() { diff --git a/pkg/policy/apply.go b/pkg/policy/apply.go index d74c650bdb..71f59cd75b 100644 --- a/pkg/policy/apply.go +++ b/pkg/policy/apply.go @@ -42,7 +42,12 @@ func applyPolicy(policy kyverno.ClusterPolicy, resource unstructured.Unstructure ctx := context.NewContext() err = ctx.AddResource(transformResource(resource)) if err != nil { - logger.Error(err, "enable to add transform resource to ctx") + logger.Error(err, "failed to add transform resource to ctx") + } + + err = ctx.AddNamespace(resource.GetNamespace()) + if err != nil { + logger.Error(err, "failed to add namespace to ctx") } engineResponseMutation, err = mutation(policy, resource, logger, resCache, ctx, namespaceLabels) diff --git a/pkg/policy/background.go b/pkg/policy/background.go index da00b17e0f..ffe108e8e2 100644 --- a/pkg/policy/background.go +++ b/pkg/policy/background.go @@ -21,7 +21,7 @@ func ContainsVariablesOtherThanObject(policy kyverno.ClusterPolicy) error { return fmt.Errorf("invalid variable used at path: spec/rules[%d]/exclude/%s", idx, path) } - filterVars := []string{"request.object"} + filterVars := []string{"request.object", "request.namespace"} ctx := context.NewContext(filterVars...) for contextIdx, contextEntry := range rule.Context {