|
| 1 | +/* |
| 2 | +Copyright 2026 The Cozystack Authors. |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +package application |
| 18 | + |
| 19 | +import ( |
| 20 | + "context" |
| 21 | + "slices" |
| 22 | + "strings" |
| 23 | + "testing" |
| 24 | + |
| 25 | + admissionregistrationv1 "k8s.io/api/admissionregistration/v1" |
| 26 | + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" |
| 27 | + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" |
| 28 | + "k8s.io/apimachinery/pkg/labels" |
| 29 | + "k8s.io/apimachinery/pkg/runtime" |
| 30 | + "k8s.io/apimachinery/pkg/runtime/schema" |
| 31 | + "k8s.io/apiserver/pkg/admission" |
| 32 | + "k8s.io/apiserver/pkg/admission/plugin/policy/validating" |
| 33 | + celconfig "k8s.io/apiserver/pkg/apis/cel" |
| 34 | + "k8s.io/apiserver/pkg/authentication/user" |
| 35 | +) |
| 36 | + |
| 37 | +const tenantNamespaceDeletePolicyPath = "../../../../packages/system/cozystack-basics/templates/tenant-namespace-delete-policy.yaml" |
| 38 | + |
| 39 | +func TestTenantNamespaceDeletePolicy_Binding(t *testing.T) { |
| 40 | + policy, binding := loadPolicy(t, tenantNamespaceDeletePolicyPath) |
| 41 | + |
| 42 | + if binding.Spec.PolicyName != policy.Name { |
| 43 | + t.Errorf("binding names policy %q, want %q", binding.Spec.PolicyName, policy.Name) |
| 44 | + } |
| 45 | + if !slices.Equal(binding.Spec.ValidationActions, []admissionregistrationv1.ValidationAction{admissionregistrationv1.Deny}) { |
| 46 | + t.Errorf("binding validationActions = %v, want [Deny]", binding.Spec.ValidationActions) |
| 47 | + } |
| 48 | + if policy.Spec.FailurePolicy == nil || *policy.Spec.FailurePolicy != admissionregistrationv1.Fail { |
| 49 | + t.Errorf("failurePolicy must be Fail") |
| 50 | + } |
| 51 | + |
| 52 | + rules := policy.Spec.MatchConstraints.ResourceRules |
| 53 | + if len(rules) != 1 { |
| 54 | + t.Fatalf("want one resource rule, got %d", len(rules)) |
| 55 | + } |
| 56 | + rule := rules[0] |
| 57 | + if !slices.Equal(rule.APIGroups, []string{""}) || !slices.Equal(rule.APIVersions, []string{"v1"}) { |
| 58 | + t.Errorf("rule must match core v1 only, got apiGroups %v apiVersions %v", rule.APIGroups, rule.APIVersions) |
| 59 | + } |
| 60 | + if !slices.Equal(rule.Operations, []admissionregistrationv1.OperationType{admissionregistrationv1.Delete}) { |
| 61 | + t.Errorf("operations = %v, want [DELETE]", rule.Operations) |
| 62 | + } |
| 63 | + if !slices.Equal(rule.Resources, []string{"namespaces"}) { |
| 64 | + t.Errorf("resources = %v, want [namespaces]", rule.Resources) |
| 65 | + } |
| 66 | + |
| 67 | + if binding.Spec.MatchResources == nil || binding.Spec.MatchResources.ObjectSelector == nil { |
| 68 | + t.Fatal("binding must select namespaces by label") |
| 69 | + } |
| 70 | + selector, err := metav1.LabelSelectorAsSelector(binding.Spec.MatchResources.ObjectSelector) |
| 71 | + if err != nil { |
| 72 | + t.Fatalf("binding objectSelector: %v", err) |
| 73 | + } |
| 74 | + selected := []struct { |
| 75 | + name string |
| 76 | + labels labels.Set |
| 77 | + want bool |
| 78 | + }{ |
| 79 | + {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}, |
| 80 | + {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}, |
| 81 | + {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"}}, |
| 82 | + {name: "namespace named tenant-* without tenant labels", labels: labels.Set{"namespace.cozystack.io/host": "case-probe.example.org"}}, |
| 83 | + {name: "unlabelled namespace", labels: labels.Set{}}, |
| 84 | + } |
| 85 | + for _, tc := range selected { |
| 86 | + if got := selector.Matches(tc.labels); got != tc.want { |
| 87 | + t.Errorf("%s: selected = %v, want %v", tc.name, got, tc.want) |
| 88 | + } |
| 89 | + } |
| 90 | +} |
| 91 | + |
| 92 | +func TestTenantNamespaceDeletePolicy_Decisions(t *testing.T) { |
| 93 | + policy, _ := loadPolicy(t, tenantNamespaceDeletePolicyPath) |
| 94 | + validator := compilePolicy(t, policy) |
| 95 | + |
| 96 | + fluxGroups := []string{"system:serviceaccounts", "system:serviceaccounts:cozy-fluxcd", "system:authenticated"} |
| 97 | + kubeSystemGroups := []string{"system:serviceaccounts", "system:serviceaccounts:kube-system", "system:authenticated"} |
| 98 | + adminGroups := []string{"system:masters", "system:authenticated"} |
| 99 | + |
| 100 | + cases := []struct { |
| 101 | + name string |
| 102 | + namespace string |
| 103 | + user string |
| 104 | + groups []string |
| 105 | + denied bool |
| 106 | + tenant string |
| 107 | + parent string |
| 108 | + }{ |
| 109 | + {name: "helm-controller uninstalling a Tenant", namespace: "tenant-foo", user: "system:serviceaccount:cozy-fluxcd:flux", groups: fluxGroups}, |
| 110 | + {name: "helm-controller uninstalling a nested Tenant", namespace: "tenant-foo-bar", user: "system:serviceaccount:cozy-fluxcd:flux", groups: fluxGroups}, |
| 111 | + {name: "garbage collector following a deleted parent namespace", namespace: "tenant-foo-bar", user: "system:serviceaccount:kube-system:generic-garbage-collector", groups: kubeSystemGroups}, |
| 112 | + {name: "cluster admin deleting a tenant namespace", namespace: "tenant-foo", user: "admin", groups: adminGroups, denied: true, tenant: "foo", parent: "tenant-root"}, |
| 113 | + {name: "cluster admin deleting a nested tenant namespace", namespace: "tenant-foo-bar", user: "admin", groups: adminGroups, denied: true, tenant: "bar", parent: "tenant-foo"}, |
| 114 | + {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"}, |
| 115 | + {name: "cluster admin deleting a labelled namespace without a dash", namespace: "standalone", user: "admin", groups: adminGroups, denied: true, tenant: "standalone", parent: "tenant-root"}, |
| 116 | + {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"}, |
| 117 | + {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"}, |
| 118 | + {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"}, |
| 119 | + {name: "user without groups", namespace: "tenant-foo", user: "no-groups", denied: true, tenant: "foo", parent: "tenant-root"}, |
| 120 | + } |
| 121 | + |
| 122 | + gvk := schema.GroupVersionKind{Version: "v1", Kind: "Namespace"} |
| 123 | + gvr := schema.GroupVersionResource{Version: "v1", Resource: "namespaces"} |
| 124 | + for _, tc := range cases { |
| 125 | + t.Run(tc.name, func(t *testing.T) { |
| 126 | + oldObj := &unstructured.Unstructured{Object: map[string]any{ |
| 127 | + "apiVersion": "v1", |
| 128 | + "kind": "Namespace", |
| 129 | + "metadata": map[string]any{ |
| 130 | + "name": tc.namespace, |
| 131 | + "labels": map[string]any{"tenant.cozystack.io/tenant-root": ""}, |
| 132 | + }, |
| 133 | + }} |
| 134 | + var newObj runtime.Object |
| 135 | + attrs := admission.NewAttributesRecord(newObj, oldObj, gvk, tc.namespace, tc.namespace, gvr, "", admission.Delete, &metav1.DeleteOptions{}, false, &user.DefaultInfo{Name: tc.user, Groups: tc.groups}) |
| 136 | + versioned := &admission.VersionedAttributes{Attributes: attrs, VersionedObject: admission.NewLazyObject(newObj), VersionedOldObject: admission.NewLazyObject(oldObj), VersionedKind: gvk} |
| 137 | + |
| 138 | + result := validator.Validate(context.Background(), gvr, versioned, nil, nil, celconfig.RuntimeCELCostBudget, nil) |
| 139 | + var denials []validating.PolicyDecision |
| 140 | + for _, d := range result.Decisions { |
| 141 | + if d.Evaluation == validating.EvalError { |
| 142 | + t.Fatalf("evaluation error: %s", d.Message) |
| 143 | + } |
| 144 | + if d.Action == validating.ActionDeny { |
| 145 | + denials = append(denials, d) |
| 146 | + } |
| 147 | + } |
| 148 | + if got := len(denials) > 0; got != tc.denied { |
| 149 | + t.Fatalf("denied = %v, want %v (decisions %+v)", got, tc.denied, result.Decisions) |
| 150 | + } |
| 151 | + for _, d := range denials { |
| 152 | + for _, want := range []string{ |
| 153 | + "kubectl delete tenants.apps.cozystack.io " + tc.tenant + " --namespace " + tc.parent + ".", |
| 154 | + "kubectl label namespace " + tc.namespace + " tenant.cozystack.io/tenant-root-", |
| 155 | + } { |
| 156 | + if !strings.Contains(d.Message, want) { |
| 157 | + t.Errorf("denial message must carry %q, got %q", want, d.Message) |
| 158 | + } |
| 159 | + } |
| 160 | + } |
| 161 | + }) |
| 162 | + } |
| 163 | +} |
0 commit comments