fix(cozystack-basics): refuse a direct delete of a tenant namespace (#5011)

## What this PR does

Fixes #5002. A DELETE of a tenant namespace is refused unless it comes
from the identities that remove it on the normal path, and the denial
says to delete the Tenant instead.

The new ValidatingAdmissionPolicy in cozystack-basics matches DELETE of
core namespaces, and its binding selects namespaces labelled
`tenant.cozystack.io/tenant-root`. The tenant chart puts that label on
every tenant namespace below tenant-root (`tenant.ancestorTenantLabels`,
and migration 49 backfilled older ones). tenant-root itself has no such
label and stays with `cozystack-no-delete-guardrail`. The `tenant-*`
probe namespaces of the e2e suites carry only
`namespace.cozystack.io/host` and are not selected either.

Two groups pass. `system:serviceaccounts:cozy-fluxcd`, because
helm-controller and its shards run as `flux` there, and a Tenant
uninstall is helm-controller deleting the namespace after the pre-delete
hook. `system:serviceaccounts:kube-system`, for the garbage collector
following the ownerReference of a child namespace once its parent is
gone. The namespace controller never sends a DELETE for a namespace, it
updates `finalize`, so it is not affected
(`pkg/controller/namespace/deletion` and
`pkg/registry/core/namespace/storage` at v1.33.12 and v1.34.1).
`system:masters` is not exempt, the same as with the no-delete
guardrail.

This is the denial kube-apiserver 1.35 returns.

```
namespaces "tenant-foo" is forbidden: ValidatingAdmissionPolicy 'cozystack-tenant-namespace-delete-policy' with binding 'cozystack-tenant-namespace-delete-policy' denied request: Namespace tenant-foo belongs to the Tenant foo in tenant-root. Delete the Tenant instead with kubectl delete tenants.apps.cozystack.io foo --namespace tenant-root. Deleting the namespace directly can remove the tenant etcd before the Kubernetes clusters that use it and leave the namespace stuck in Terminating. If the Tenant is already gone, remove the label first with kubectl label namespace tenant-foo tenant.cozystack.io/tenant-root-
```

There are a few limits.

- The bypass is removing the label, like with the guardrail. That also
takes the namespace out of the tenant-root egress policy and the
dashboard tree, which only matters for a namespace that is about to go.
- Migration 49 labelled every `tenant-*` namespace that existed when it
ran, so a non-tenant namespace with such a name is refused too and needs
the same label removal.
- Because the garbage collector is exempt, a parent namespace whose
label was removed and that is deleted with foreground propagation still
cascades into its children directly.
- A DELETE of a namespace that is already Terminating is answered before
admission, so the policy does not see it. It changes nothing either.
- A cluster that made helm-controller impersonate another account
(`--default-service-account`, or `spec.serviceAccountName` on Tenant
HelmReleases) would need that account allowed. Cozystack sets neither.
- It does not change how Kamaji cleans up once the order is broken,
which is the second idea in #5002.

The helper rename in `external_tls_policy_test.go` (`loadPolicy(t,
path)` and `compilePolicy`) is byte for byte the one in #2622, so the
two merge in either order.

Checked locally.

- `go test ./pkg/registry/apps/application/ -run
'TestTenantNamespaceDeletePolicy|TestDatabaseExternalTLSPolicy' -count=1
-v` passes 4 tests, the new `TestTenantNamespaceDeletePolicy_Decisions`
with 11 cases. `go test ./pkg/registry/... ./pkg/config/...
./pkg/cmd/server/...` passes in all 11 packages that have tests.
- `helm unittest` in `packages/system/cozystack-basics` with
helm-unittest 1.1.2 in docker passes 12 suites and 70 tests, against 11
and 66 on main. The new tests on main without the template fail, both Go
tests and 4 helm tests in 2 suites.
- 12 mutations of the template each fail a test. They exempt
`system:masters`, drop either exempt group, select on the no-delete
label, add UPDATE, always name tenant-root as the parent, drop the
capability gate, label tenant-root, switch to Warn, switch failurePolicy
to Ignore, drop the bypass from the message and drop the objectSelector.
- The rendered policy, the guardrail and namespaces rendered from the
tenant chart were applied to kube-apiserver v1.33.0, v1.35.0 and v1.36.2
from setup-envtest, 16 checks on each. Real and dry-run deletes by a
cluster admin, by an OIDC user bound to cluster-admin and by a
cozy-system and a tenant ServiceAccount are refused with 403. The flux
and garbage collector identities get their delete accepted. tenant-root
gets the guardrail's denial, and with the guardrail binding removed a
dry-run delete of it goes through, so this policy does not select it. A
`tenant-*` namespace without the label and a tenant namespace after its
label is removed are accepted for deletion. With this binding removed, a
dry-run delete by the cluster admin goes through. That harness is not
part of the PR.
- `hack/bats-no-negated-assert.bats`, `hack/bats-no-exit-trap.bats`,
`hack/bats-runner-coverage.bats`, `hack/helmrelease-readiness.bats` and
`hack/route-hostname-policy-version-coverage.bats` pass under
`hack/cozytest.sh`.

The new e2e case in `hack/e2e-install-cozystack.bats` creates an empty
Tenant, checks that a server dry-run delete of its namespace is refused
with the message, deletes the Tenant and waits for the namespace to go.
It was not run here, there is no Cozystack cluster at hand. Its kubectl
steps were run against the envtest apiserver 1.35, the selector and
field selector read, the refused dry-run with the exact strings it greps
for, and `kubectl wait --for=delete` on a namespace that is gone. The
Chainsaw suites that delete Tenants, the gateway inheritance ones among
them, go through the uninstall path as well.

The release-1.6 backport is #5012.

### Screenshots

Not a UI change.

### Downstream repositories

- [x] No downstream repository is affected by this change
- [ ] [cozystack/website](https://github.com/cozystack/website) -
follow-up:
- [ ]
[cozystack/terraform-provider-cozystack](https://github.com/cozystack/terraform-provider-cozystack)
- follow-up:
- [ ]
[cozystack/ansible-cozystack](https://github.com/cozystack/ansible-cozystack)
- follow-up:
- [ ] [cozystack/ccp](https://github.com/cozystack/ccp) - follow-up:
- [ ] [cozystack/talm](https://github.com/cozystack/talm) - follow-up:
- [ ] [cozystack/cozyhr](https://github.com/cozystack/cozyhr) -
follow-up:
- [ ] [cozystack/cozy-proxy](https://github.com/cozystack/cozy-proxy) -
follow-up:
- [ ]
[cozystack/cozystack-telemetry-server](https://github.com/cozystack/cozystack-telemetry-server)
- follow-up:
- [ ]
[cozystack/external-apps-example](https://github.com/cozystack/external-apps-example)
- follow-up:
- [ ] [cozystack/examples](https://github.com/cozystack/examples) -
follow-up:
- [ ] [cozystack/community](https://github.com/cozystack/community) -
follow-up:

The trigger map was walked against the diff. It adds a policy and tests
to cozystack-basics and an e2e case, and no entry covers that. The
website docs do not tell users to delete a tenant namespace directly,
and terraform-provider-cozystack deletes Tenants through the apps API.

### Release note

```release-note
fix(cozystack-basics): refuse a direct DELETE of a tenant namespace unless it comes from helm-controller or the garbage collector, and point to deleting the Tenant instead, so a tenant namespace deleted by hand no longer gets stuck Terminating on Kamaji finalizers
```
This commit is contained in:
Aleksei Sviridkin authored and GitHub committed 2026-11-13 18:25:04 +03:00
commit 29e8522f4b
7 files changed
+331 -11

No files matched your search

+37
View File
@@ -561,3 +561,40 @@ data:
version: "${version}"
EOF
}
@test "Tenant namespace delete policy refuses a direct delete and keeps the Tenant uninstall" {
if ! kubectl api-resources --api-group=admissionregistration.k8s.io \
2>/dev/null | grep -qw validatingadmissionpolicies; then
skip "ValidatingAdmissionPolicy API not available on this cluster"
fi
kubectl get validatingadmissionpolicy cozystack-tenant-namespace-delete-policy
kubectl get validatingadmissionpolicybinding cozystack-tenant-namespace-delete-policy
kubectl apply -f - <<EOF
apiVersion: apps.cozystack.io/v1alpha1
kind: Tenant
metadata:
name: deleteprobe
namespace: tenant-root
spec: {}
EOF
timeout 60 sh -ec 'until kubectl get hr/tenant-deleteprobe -n tenant-root >/dev/null 2>&1; do sleep 2; done'
kubectl wait hr/tenant-deleteprobe -n tenant-root --timeout=1m --for=condition=ready
local selected output rc still_there
selected=$(kubectl get namespaces --selector tenant.cozystack.io/tenant-root --field-selector metadata.name=tenant-deleteprobe -o name)
[ "$selected" = "namespace/tenant-deleteprobe" ]
output=$(kubectl delete namespace tenant-deleteprobe --dry-run=server 2>&1) && rc=0 || rc=$?
echo "kubectl delete exit=$rc, output=$output"
[ "$rc" -ne 0 ]
echo "$output" | grep -qF "ValidatingAdmissionPolicy 'cozystack-tenant-namespace-delete-policy'"
echo "$output" | grep -qF 'kubectl delete tenants.apps.cozystack.io deleteprobe --namespace tenant-root.'
kubectl delete tenants.apps.cozystack.io deleteprobe -n tenant-root --timeout=5m
kubectl wait namespace/tenant-deleteprobe --for=delete --timeout=5m
if ! still_there=$(kubectl get namespace tenant-deleteprobe --ignore-not-found -o name); then
echo "FAIL: reading the tenant-deleteprobe namespace did not answer"; false
fi
if [ -n "$still_there" ]; then echo "FAIL: deleting the Tenant must remove its namespace"; false; fi
}
@@ -0,0 +1,59 @@
{{- if .Capabilities.APIVersions.Has "admissionregistration.k8s.io/v1/ValidatingAdmissionPolicy" }}
---
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicy
metadata:
name: cozystack-tenant-namespace-delete-policy
labels:
internal.cozystack.io/managed-by-cozystack: ""
spec:
failurePolicy: Fail
matchConstraints:
resourceRules:
- apiGroups: [""]
apiVersions: ["v1"]
operations: ["DELETE"]
resources: ["namespaces"]
variables:
- name: platformCaller
expression: >-
has(request.userInfo.groups) && request.userInfo.groups.exists(g,
g == "system:serviceaccounts:cozy-fluxcd" ||
g == "system:serviceaccounts:kube-system")
- name: name
expression: oldObject.metadata.name
- name: cut
expression: variables.name.lastIndexOf("-")
- name: tenant
expression: variables.name.substring(variables.cut + 1)
- name: parentNamespace
expression: >-
variables.cut > 0 && variables.name.substring(0, variables.cut) != "tenant"
? variables.name.substring(0, variables.cut)
: "tenant-root"
validations:
- expression: variables.platformCaller
messageExpression: >-
"Namespace " + variables.name + " belongs to the Tenant " + variables.tenant +
" in " + variables.parentNamespace + ". Delete the Tenant instead with kubectl delete tenants.apps.cozystack.io " +
variables.tenant + " --namespace " + variables.parentNamespace +
". Deleting the namespace directly can remove the tenant etcd before the Kubernetes clusters that use it and leave the namespace stuck in Terminating." +
" If the Tenant is already gone, remove the label first with kubectl label namespace " + variables.name +
" tenant.cozystack.io/tenant-root-"
reason: Forbidden
---
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicyBinding
metadata:
name: cozystack-tenant-namespace-delete-policy
labels:
internal.cozystack.io/managed-by-cozystack: ""
spec:
policyName: cozystack-tenant-namespace-delete-policy
validationActions: [Deny]
matchResources:
objectSelector:
matchExpressions:
- key: tenant.cozystack.io/tenant-root
operator: Exists
{{- end }}
@@ -1,5 +1,6 @@
suite: cozystack-basics VAP policies are gated on the ValidatingAdmissionPolicy API
templates:
- templates/tenant-namespace-delete-policy.yaml
- templates/route-hostname-policy.yaml
- templates/gateway-hostname-policy.yaml
- templates/ingress-hostname-policy.yaml
@@ -20,6 +21,9 @@ capabilities:
tests:
- it: none of the VAP policies render when the API is unavailable
asserts:
- hasDocuments:
count: 0
template: templates/tenant-namespace-delete-policy.yaml
- hasDocuments:
count: 0
template: templates/route-hostname-policy.yaml
@@ -0,0 +1,51 @@
suite: tenant namespace delete policy renders with its binding
templates:
- templates/tenant-namespace-delete-policy.yaml
release:
name: cozystack-basics
namespace: cozy-system
capabilities:
apiVersions:
- admissionregistration.k8s.io/v1/ValidatingAdmissionPolicy
tests:
- it: renders the policy and a Deny binding to it
asserts:
- hasDocuments:
count: 2
- documentIndex: 0
equal:
path: kind
value: ValidatingAdmissionPolicy
- documentIndex: 0
equal:
path: metadata.name
value: cozystack-tenant-namespace-delete-policy
- documentIndex: 1
equal:
path: spec.policyName
value: cozystack-tenant-namespace-delete-policy
- documentIndex: 1
equal:
path: spec.validationActions
value: [Deny]
- it: matches only DELETE of core namespaces
asserts:
- documentIndex: 0
equal:
path: spec.matchConstraints.resourceRules
value:
- apiGroups: [""]
apiVersions: ["v1"]
operations: ["DELETE"]
resources: ["namespaces"]
- it: binds to the namespaces the tenant chart labels as descendants of tenant-root
asserts:
- documentIndex: 1
equal:
path: spec.matchResources.objectSelector
value:
matchExpressions:
- key: tenant.cozystack.io/tenant-root
operator: Exists
@@ -79,3 +79,9 @@ tests:
equal:
path: spec.chartRef.name
value: cozystack-tenant-application-default-tenant
- it: tenant-root namespace carries no tenant.cozystack.io/tenant-root label, which the tenant namespace delete policy selects on
asserts:
- documentIndex: 0
notExists:
path: metadata.labels["tenant.cozystack.io/tenant-root"]
@@ -41,14 +41,14 @@ import (
// expressions a cluster actually receives rather than a copy of them.
const externalTLSPolicyPath = "../../../../packages/system/cozystack-basics/templates/database-external-tls-policy.yaml"
// loadExternalTLSPolicy returns the policy and its binding from the chart
// template. The template's only directives are the capability guard lines
// around the manifests; any other directive would mean the test is no longer
// looking at what renders, so it fails instead of guessing.
func loadExternalTLSPolicy(t *testing.T) (*admissionregistrationv1.ValidatingAdmissionPolicy, *admissionregistrationv1.ValidatingAdmissionPolicyBinding) {
// loadPolicy returns the policy and its binding from a chart template. The
// template's only directives are the capability guard lines around the
// manifests; any other directive would mean the test is no longer looking at
// what renders, so it fails instead of guessing.
func loadPolicy(t *testing.T, path string) (*admissionregistrationv1.ValidatingAdmissionPolicy, *admissionregistrationv1.ValidatingAdmissionPolicyBinding) {
t.Helper()
raw, err := os.ReadFile(externalTLSPolicyPath)
raw, err := os.ReadFile(path)
if err != nil {
t.Fatalf("read policy template: %v", err)
}
@@ -92,11 +92,11 @@ func loadExternalTLSPolicy(t *testing.T) (*admissionregistrationv1.ValidatingAdm
return policy, binding
}
// compileExternalTLSPolicy mirrors compilePolicy in
// compilePolicy mirrors compilePolicy in
// k8s.io/apiserver/pkg/admission/plugin/policy/validating, which is
// unexported: the same composition environment, the same variable, match
// condition, validation and message compilers.
func compileExternalTLSPolicy(t *testing.T, policy *admissionregistrationv1.ValidatingAdmissionPolicy) validating.Validator {
func compilePolicy(t *testing.T, policy *admissionregistrationv1.ValidatingAdmissionPolicy) validating.Validator {
t.Helper()
compiler, err := plugincel.NewCompositedCompiler(environment.MustBaseEnvSet(environment.DefaultCompatibilityVersion()))
@@ -139,7 +139,7 @@ func compileExternalTLSPolicy(t *testing.T, policy *admissionregistrationv1.Vali
}
func TestDatabaseExternalTLSPolicy_Binding(t *testing.T) {
policy, binding := loadExternalTLSPolicy(t)
policy, binding := loadPolicy(t, externalTLSPolicyPath)
if binding.Spec.PolicyName != policy.Name {
t.Errorf("binding names policy %q, want %q", binding.Spec.PolicyName, policy.Name)
@@ -171,8 +171,8 @@ func TestDatabaseExternalTLSPolicy_Binding(t *testing.T) {
}
func TestDatabaseExternalTLSPolicy_Decisions(t *testing.T) {
policy, _ := loadExternalTLSPolicy(t)
validator := compileExternalTLSPolicy(t, policy)
policy, _ := loadPolicy(t, externalTLSPolicyPath)
validator := compilePolicy(t, policy)
tlsOn := map[string]any{"enabled": true}
tlsOff := map[string]any{"enabled": false}
@@ -0,0 +1,163 @@
/*
Copyright 2026 The Cozystack Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package application
import (
"context"
"slices"
"strings"
"testing"
admissionregistrationv1 "k8s.io/api/admissionregistration/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apiserver/pkg/admission"
"k8s.io/apiserver/pkg/admission/plugin/policy/validating"
celconfig "k8s.io/apiserver/pkg/apis/cel"
"k8s.io/apiserver/pkg/authentication/user"
)
const tenantNamespaceDeletePolicyPath = "../../../../packages/system/cozystack-basics/templates/tenant-namespace-delete-policy.yaml"
func TestTenantNamespaceDeletePolicy_Binding(t *testing.T) {
policy, binding := loadPolicy(t, tenantNamespaceDeletePolicyPath)
if binding.Spec.PolicyName != policy.Name {
t.Errorf("binding names policy %q, want %q", binding.Spec.PolicyName, policy.Name)
}
if !slices.Equal(binding.Spec.ValidationActions, []admissionregistrationv1.ValidationAction{admissionregistrationv1.Deny}) {
t.Errorf("binding validationActions = %v, want [Deny]", binding.Spec.ValidationActions)
}
if policy.Spec.FailurePolicy == nil || *policy.Spec.FailurePolicy != admissionregistrationv1.Fail {
t.Errorf("failurePolicy must be Fail")
}
rules := policy.Spec.MatchConstraints.ResourceRules
if len(rules) != 1 {
t.Fatalf("want one resource rule, got %d", len(rules))
}
rule := rules[0]
if !slices.Equal(rule.APIGroups, []string{""}) || !slices.Equal(rule.APIVersions, []string{"v1"}) {
t.Errorf("rule must match core v1 only, got apiGroups %v apiVersions %v", rule.APIGroups, rule.APIVersions)
}
if !slices.Equal(rule.Operations, []admissionregistrationv1.OperationType{admissionregistrationv1.Delete}) {
t.Errorf("operations = %v, want [DELETE]", rule.Operations)
}
if !slices.Equal(rule.Resources, []string{"namespaces"}) {
t.Errorf("resources = %v, want [namespaces]", rule.Resources)
}
if binding.Spec.MatchResources == nil || binding.Spec.MatchResources.ObjectSelector == nil {
t.Fatal("binding must select namespaces by label")
}
selector, err := metav1.LabelSelectorAsSelector(binding.Spec.MatchResources.ObjectSelector)
if err != nil {
t.Fatalf("binding objectSelector: %v", err)
}
selected := []struct {
name string
labels labels.Set
want bool
}{
{name: "tenant namespace under tenant-root", labels: labels.Set{"tenant.cozystack.io/tenant-root": "", "tenant.cozystack.io/tenant-foo": "", "namespace.cozystack.io/host": "foo.example.org"}, want: true},
{name: "nested tenant namespace", labels: labels.Set{"tenant.cozystack.io/tenant-root": "", "tenant.cozystack.io/tenant-foo": "", "tenant.cozystack.io/tenant-foo-bar": ""}, want: true},
{name: "tenant-root namespace", labels: labels.Set{"platform.cozystack.io/no-delete": "true", "namespace.cozystack.io/host": "example.org", "namespace.cozystack.io/gateway": "tenant-root"}},
{name: "namespace named tenant-* without tenant labels", labels: labels.Set{"namespace.cozystack.io/host": "case-probe.example.org"}},
{name: "unlabelled namespace", labels: labels.Set{}},
}
for _, tc := range selected {
if got := selector.Matches(tc.labels); got != tc.want {
t.Errorf("%s: selected = %v, want %v", tc.name, got, tc.want)
}
}
}
func TestTenantNamespaceDeletePolicy_Decisions(t *testing.T) {
policy, _ := loadPolicy(t, tenantNamespaceDeletePolicyPath)
validator := compilePolicy(t, policy)
fluxGroups := []string{"system:serviceaccounts", "system:serviceaccounts:cozy-fluxcd", "system:authenticated"}
kubeSystemGroups := []string{"system:serviceaccounts", "system:serviceaccounts:kube-system", "system:authenticated"}
adminGroups := []string{"system:masters", "system:authenticated"}
cases := []struct {
name string
namespace string
user string
groups []string
denied bool
tenant string
parent string
}{
{name: "helm-controller uninstalling a Tenant", namespace: "tenant-foo", user: "system:serviceaccount:cozy-fluxcd:flux", groups: fluxGroups},
{name: "helm-controller uninstalling a nested Tenant", namespace: "tenant-foo-bar", user: "system:serviceaccount:cozy-fluxcd:flux", groups: fluxGroups},
{name: "garbage collector following a deleted parent namespace", namespace: "tenant-foo-bar", user: "system:serviceaccount:kube-system:generic-garbage-collector", groups: kubeSystemGroups},
{name: "cluster admin deleting a tenant namespace", namespace: "tenant-foo", user: "admin", groups: adminGroups, denied: true, tenant: "foo", parent: "tenant-root"},
{name: "cluster admin deleting a nested tenant namespace", namespace: "tenant-foo-bar", user: "admin", groups: adminGroups, denied: true, tenant: "bar", parent: "tenant-foo"},
{name: "cluster admin deleting a third-level tenant namespace", namespace: "tenant-foo-bar-baz", user: "admin", groups: adminGroups, denied: true, tenant: "baz", parent: "tenant-foo-bar"},
{name: "cluster admin deleting a labelled namespace without a dash", namespace: "standalone", user: "admin", groups: adminGroups, denied: true, tenant: "standalone", parent: "tenant-root"},
{name: "OIDC user bound to cluster-admin", namespace: "tenant-foo", user: "cluster-admin-user", groups: []string{"cozystack-cluster-admin", "system:authenticated"}, denied: true, tenant: "foo", parent: "tenant-root"},
{name: "cozy-system service account", namespace: "tenant-foo", user: "system:serviceaccount:cozy-system:cozystack-api", groups: []string{"system:serviceaccounts", "system:serviceaccounts:cozy-system", "system:authenticated"}, denied: true, tenant: "foo", parent: "tenant-root"},
{name: "tenant service account", namespace: "tenant-foo-bar", user: "system:serviceaccount:tenant-foo:default", groups: []string{"system:serviceaccounts", "system:serviceaccounts:tenant-foo", "system:authenticated"}, denied: true, tenant: "bar", parent: "tenant-foo"},
{name: "user without groups", namespace: "tenant-foo", user: "no-groups", denied: true, tenant: "foo", parent: "tenant-root"},
}
gvk := schema.GroupVersionKind{Version: "v1", Kind: "Namespace"}
gvr := schema.GroupVersionResource{Version: "v1", Resource: "namespaces"}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
oldObj := &unstructured.Unstructured{Object: map[string]any{
"apiVersion": "v1",
"kind": "Namespace",
"metadata": map[string]any{
"name": tc.namespace,
"labels": map[string]any{"tenant.cozystack.io/tenant-root": ""},
},
}}
var newObj runtime.Object
attrs := admission.NewAttributesRecord(newObj, oldObj, gvk, tc.namespace, tc.namespace, gvr, "", admission.Delete, &metav1.DeleteOptions{}, false, &user.DefaultInfo{Name: tc.user, Groups: tc.groups})
versioned := &admission.VersionedAttributes{Attributes: attrs, VersionedObject: admission.NewLazyObject(newObj), VersionedOldObject: admission.NewLazyObject(oldObj), VersionedKind: gvk}
result := validator.Validate(context.Background(), gvr, versioned, nil, nil, celconfig.RuntimeCELCostBudget, nil)
var denials []validating.PolicyDecision
for _, d := range result.Decisions {
if d.Evaluation == validating.EvalError {
t.Fatalf("evaluation error: %s", d.Message)
}
if d.Action == validating.ActionDeny {
denials = append(denials, d)
}
}
if got := len(denials) > 0; got != tc.denied {
t.Fatalf("denied = %v, want %v (decisions %+v)", got, tc.denied, result.Decisions)
}
for _, d := range denials {
for _, want := range []string{
"kubectl delete tenants.apps.cozystack.io " + tc.tenant + " --namespace " + tc.parent + ".",
"kubectl label namespace " + tc.namespace + " tenant.cozystack.io/tenant-root-",
} {
if !strings.Contains(d.Message, want) {
t.Errorf("denial message must carry %q, got %q", want, d.Message)
}
}
}
})
}
}