Skip to content

Commit

Permalink
add request.namespace in the background process
Browse files Browse the repository at this point in the history
Signed-off-by: Shuting Zhao <shutting06@gmail.com>
  • Loading branch information
realshuting committed Feb 23, 2021
1 parent 17c72c1 commit d770d66
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 2 deletions.
24 changes: 24 additions & 0 deletions pkg/engine/context/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand Down Expand Up @@ -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() {
Expand Down
7 changes: 6 additions & 1 deletion pkg/policy/apply.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion pkg/policy/background.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down

0 comments on commit d770d66

Please sign in to comment.