Skip to content

Commit

Permalink
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge branch 'release-1.12' into cherry-pick-10382
Browse files Browse the repository at this point in the history
MariamFahmy98 authored Jul 4, 2024
2 parents 580139b + b5946eb commit 32cd548
Showing 8 changed files with 133 additions and 58 deletions.
9 changes: 8 additions & 1 deletion .github/workflows/conformance.yaml
Original file line number Diff line number Diff line change
@@ -964,6 +964,13 @@ jobs:
name: kubectl-kyverno
- name: Install chainsaw
uses: kyverno/action-install-chainsaw@3bf0752f44d348d859fefa022f113bda6a24a1ae # v0.1.7
# create cluster
- name: Create kind cluster
uses: helm/kind-action@0025e74a8c7512023d06dc019c617aa3cf561fde # v1.10.0
with:
node_image: kindest/node:v1.30.0
cluster_name: kind
config: ./scripts/config/kind/default.yaml
- name: Install Kyverno CLI
shell: bash
run: |
@@ -977,7 +984,7 @@ jobs:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -e
cd ./test/conformance/chainsaw && chainsaw test --include-test-regex '^chainsaw$/${{ matrix.tests }}' --no-cluster
cd ./test/conformance/chainsaw && chainsaw test --include-test-regex '^chainsaw$/${{ matrix.tests }}'
- name: Fix test files
shell: bash
run: |
8 changes: 8 additions & 0 deletions cmd/cli/kubectl-kyverno/processor/policy_processor.go
Original file line number Diff line number Diff line change
@@ -254,6 +254,14 @@ func (p *PolicyProcessor) makePolicyContext(
return nil, fmt.Errorf("failed to update old resource in json context (%w)", err)
}
}
if p.Client != nil && len(namespaceLabels) == 0 && resource.GetKind() != "Namespace" {
ns, err := p.Client.GetResource(context.TODO(), "v1", "Namespace", "", resource.GetNamespace())
if err != nil {
log.Log.Error(err, "failed to get the resource's namespace")
return nil, fmt.Errorf("failed to get the resource's namespace (%w)", err)
}
namespaceLabels = ns.GetLabels()
}
policyContext = policyContext.
WithPolicy(policy).
WithNamespaceLabels(namespaceLabels).
60 changes: 3 additions & 57 deletions pkg/controllers/cleanup/controller.go
Original file line number Diff line number Diff line change
@@ -90,7 +90,7 @@ func NewController(
enqueueFunc := func(logger logr.Logger, operation, kind string) controllerutils.EnqueueFuncT[kyvernov2alpha1.CleanupPolicyInterface] {
logger = logger.WithValues("kind", kind, "operation", operation)
return func(obj kyvernov2alpha1.CleanupPolicyInterface) error {
logger = logger.WithValues("name", obj.GetName())
logger := logger.WithValues("name", obj.GetName())
if obj.GetNamespace() != "" {
logger = logger.WithValues("namespace", obj.GetNamespace())
}
@@ -280,62 +280,8 @@ func (c *controller) cleanup(ctx context.Context, logger logr.Logger, policy kyv
errs = append(errs, err)
continue
}
if spec.ExcludeResources != nil {
excluded := match.CheckMatchesResources(
resource,
*spec.ExcludeResources,
nsLabels,
// TODO(eddycharly): we don't have user info here, we should check that
// we don't have user conditions in the policy rule
kyvernov1beta1.RequestInfo{},
resource.GroupVersionKind(),
"",
)
if excluded == nil {
debug.Info("resource/exclude matched")
continue
} else {
debug.Info("resource/exclude didn't match", "result", excluded)
}
}
// check conditions
if spec.Conditions != nil {
enginectx.Reset()
if err := enginectx.SetTargetResource(resource.Object); err != nil {
debug.Error(err, "failed to add resource in context")
errs = append(errs, err)
continue
}
if err := enginectx.AddNamespace(resource.GetNamespace()); err != nil {
debug.Error(err, "failed to add namespace in context")
errs = append(errs, err)
continue
}
if err := enginectx.AddImageInfos(&resource, c.configuration); err != nil {
debug.Error(err, "failed to add image infos in context")
errs = append(errs, err)
continue
}
passed, err := conditions.CheckAnyAllConditions(logger, enginectx, *spec.Conditions)
if err != nil {
debug.Error(err, "failed to check condition")
errs = append(errs, err)
continue
}
if !passed {
debug.Info("conditions did not pass")
continue
}
}
var labels []attribute.KeyValue
labels = append(labels, commonLabels...)
labels = append(labels, attribute.String("resource_namespace", namespace))
logger.WithValues("name", name, "namespace", namespace).Info("resource matched, it will be deleted...")
if err := c.client.DeleteResource(ctx, resource.GetAPIVersion(), resource.GetKind(), namespace, name, false); err != nil {
if c.metrics.cleanupFailuresTotal != nil {
c.metrics.cleanupFailuresTotal.Add(ctx, 1, metric.WithAttributes(labels...))
}
debug.Error(err, "failed to delete resource")
if err := enginectx.AddNamespace(resource.GetNamespace()); err != nil {
debug.Error(err, "failed to add namespace in context")
errs = append(errs, err)
continue
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
## Description

This test makes sure that Kyverno CLI apply works as expected when an exception matches a pod with a namespace selector in case of cluster mode. (i.e. `--cluster` flag is set)

## Steps

1. - Create a namespace `ns-1`
1. - Label the namespace `ns-1` with `kyverno.tess.io/mutateresource=false`
1. - Create a pod `test-pod` in namespace `ns-1`
1. - Create a policy that requires pod to run as non-root user.
1. - Create an exception that matches any pod whose ns selector is `kyverno.tess.io/mutateresource=false`
1. - Use `kyverno apply` command to apply the policy and the exception in a cluster mode. It is expected to have a `skip` as a result.

## Reference Issue(s)

https://github.com/kyverno/kyverno/issues/10260
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
apiVersion: chainsaw.kyverno.io/v1alpha1
kind: Test
metadata:
creationTimestamp: null
name: apply-exception-with-ns-selector
spec:
steps:
- name: step-01
try:
- script:
content: kubectl create ns ns-1
- name: step-02
try:
- script:
content: kubectl label ns ns-1 kyverno.tess.io/mutateresource=false
- name: step-03
try:
- script:
content: kubectl apply -f pod.yaml
- name: step-04
try:
- script:
content: kyverno apply policy.yaml --exception exception.yaml --cluster --namespace ns-1
check:
($stdout): |-
Applying 3 policy rule(s) to 1 resource(s) with 1 exception(s)...
pass: 0, fail: 0, warn: 0, error: 0, skip: 1
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
apiVersion: kyverno.io/v2beta1
kind: PolicyException
metadata:
name: exception
spec:
background: false
exceptions:
- policyName: require-run-as-non-root-user
ruleNames:
- run-as-non-root-user
match:
any:
- resources:
namespaceSelector:
matchExpressions:
- key: kyverno.tess.io/mutateresource
operator: In
values:
- "false"
kinds:
- Pod
operations:
- UPDATE
- CREATE
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
apiVersion: v1
kind: Pod
metadata:
name: test-pod
namespace: ns-1
spec:
containers:
- name: nginx
image: nginx:latest
# Grant necessary permissions using SecurityContext (optional)
securityContext:
runAsUser: 0
resources:
limits:
cpu: "1"
memory: "1Gi"
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: require-run-as-non-root-user
spec:
validationFailureAction: Enforce
background: true
rules:
- name: run-as-non-root-user
match:
any:
- resources:
kinds:
- Pod
validate:
message: >-
Running the container as root user is not allowed.
pattern:
spec:
=(securityContext):
=(runAsUser): ">0"
=(ephemeralContainers):
- =(securityContext):
=(runAsUser): ">0"
=(initContainers):
- =(securityContext):
=(runAsUser): ">0"
containers:
- =(securityContext):
=(runAsUser): ">0"

0 comments on commit 32cd548

Please sign in to comment.