1
0
Fork 0
mirror of https://github.com/kyverno/kyverno.git synced 2025-03-28 10:28:36 +00:00

fix: evaluate namespaceObject for Kyverno policies in the CLI (#9977)

Signed-off-by: Mariam Fahmy <mariam.fahmy@nirmata.com>
This commit is contained in:
Mariam Fahmy 2024-04-19 18:55:41 +08:00 committed by GitHub
parent e91b80a600
commit ea64529e63
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 95 additions and 6 deletions

View file

@ -130,12 +130,20 @@ func (h validateCELHandler) Process(
if gvk.Kind == "Namespace" && gvk.Version == "v1" && gvk.Group == "" {
namespaceName = ""
}
if namespaceName != "" && h.client != nil {
namespace, err = h.client.GetNamespace(ctx, namespaceName, metav1.GetOptions{})
if err != nil {
return resource, handlers.WithResponses(
engineapi.RuleError(rule.Name, engineapi.Validation, "Error getting the resource's namespace", err),
)
if namespaceName != "" {
if h.client != nil {
namespace, err = h.client.GetNamespace(ctx, namespaceName, metav1.GetOptions{})
if err != nil {
return resource, handlers.WithResponses(
engineapi.RuleError(rule.Name, engineapi.Validation, "Error getting the resource's namespace", err),
)
}
} else {
namespace = &corev1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Name: namespaceName,
},
}
}
}

View file

@ -0,0 +1,21 @@
apiVersion: cli.kyverno.io/v1alpha1
kind: Test
metadata:
name: kyverno-test.yaml
policies:
- policy.yaml
resources:
- resources.yaml
results:
- kind: Deployment
policy: disallow-default-namespace
resources:
- bad-deployment
result: fail
rule: validate-deployment-namespace
- kind: Deployment
policy: disallow-default-namespace
resources:
- good-deployment
result: pass
rule: validate-deployment-namespace

View file

@ -0,0 +1,19 @@
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: disallow-default-namespace
spec:
validationFailureAction: Audit
background: true
rules:
- name: validate-deployment-namespace
match:
any:
- resources:
kinds:
- Deployment
validate:
cel:
expressions:
- expression: "namespaceObject.metadata.name != 'default'"
message: "Using 'default' namespace is not allowed for deployments."

View file

@ -0,0 +1,41 @@
apiVersion: apps/v1
kind: Deployment
metadata:
name: bad-deployment
namespace: default
labels:
app: busybox
spec:
replicas: 2
selector:
matchLabels:
app: busybox
template:
metadata:
labels:
app: busybox
spec:
containers:
- name: busybox
image: busybox:latest
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: good-deployment
namespace: staging
labels:
app: busybox
spec:
replicas: 2
selector:
matchLabels:
app: busybox
template:
metadata:
labels:
app: busybox
spec:
containers:
- name: busybox
image: busybox:latest