diff --git a/config/components/device-deletion-protection/kustomization.yaml b/config/components/device-deletion-protection/kustomization.yaml new file mode 100644 index 00000000..fcc694dd --- /dev/null +++ b/config/components/device-deletion-protection/kustomization.yaml @@ -0,0 +1,8 @@ +# Reusable and opt-in: no root in this repository includes it. A deploying +# repository that must keep in-service Devices adds it to the root it applies +# to the Milo control plane, where Devices are admitted. See +# docs/operations/physical-inventory.md#device-deletion-protection. +apiVersion: kustomize.config.k8s.io/v1alpha1 +kind: Component +resources: + - policy.yaml diff --git a/config/components/device-deletion-protection/policy.yaml b/config/components/device-deletion-protection/policy.yaml new file mode 100644 index 00000000..62031225 --- /dev/null +++ b/config/components/device-deletion-protection/policy.yaml @@ -0,0 +1,75 @@ +# A Device is deleted only after it is Retired, so a Device in service stays +# visible to duplicate-hardware checks. Retire a Device by moving +# spec.lifecycle to Decommissioning and then Retired; the CRD rejects every +# other path to Retired, and Retired is terminal. +# +# Three exceptions admit a DELETE: +# +# 1. The Device's namespace is being deleted +# (namespaceObject.metadata.deletionTimestamp is set). Deleting a namespace +# is the privileged escape hatch: it lets the namespace controller finish +# and takes its Devices with it. +# 2. The Device is Retired. +# 3. The request's username is listed, exactly, in the cleanupUsernames key of +# the binding's parameter ConfigMap. This lets a project cleanup controller +# drain Devices in place, which namespace deletion cannot do for `default`. +# Entries are separated by commas or newlines and trimmed; empty entries +# and an empty username never match. Groups, prefixes and wildcards are not +# consulted. +# +# Exception 3 is a stopgap. Milo's project cleanup deletes namespaced +# resources before it marks any namespace for deletion, and it never deletes +# `default`, so exception 1 cannot cover project teardown today. Milo should +# mark every namespace it purges, `default` included, before deleting its +# contents. This policy can then rely on that namespace signal and drop the +# subject exemption. +# +# The binding below has no paramRef, so params is null and exception 3 is off. +# A deploying repository turns it on by adding the ConfigMap and patching the +# binding with a paramRef that sets parameterNotFoundAction: Deny; a missing +# ConfigMap then denies every Device DELETE. The API server runs admission once +# per object for deletecollection, garbage collection and namespace cleanup, so +# each of those paths is held to the same rule. A missing namespace object or +# an evaluation error denies the request (failurePolicy: Fail). +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicy +metadata: + name: fleet-device-deletion-protection +spec: + failurePolicy: Fail + paramKind: + apiVersion: v1 + kind: ConfigMap + matchConstraints: + matchPolicy: Equivalent + resourceRules: + - apiGroups: [fleet.datumapis.com] + apiVersions: ['*'] + operations: [DELETE] + resources: [devices] + validations: + - expression: >- + (namespaceObject != null && has(namespaceObject.metadata) && + has(namespaceObject.metadata.deletionTimestamp)) || + (oldObject != null && has(oldObject.spec) && has(oldObject.spec.lifecycle) && + oldObject.spec.lifecycle == 'Retired') || + (params != null && has(params.data) && 'cleanupUsernames' in params.data && + request.userInfo.username != '' && + params.data.cleanupUsernames.replace('\n', ',').split(',').exists(entry, + entry.trim() != '' && entry.trim() == request.userInfo.username)) + reason: Forbidden + message: >- + A Device can be deleted only when it is Retired, when its namespace is + being deleted, or by a configured cleanup identity. Move the Device to + Decommissioning, then Retired, first; its identity must stay visible to + duplicate-hardware checks while it is in service. +--- +# No paramRef: params is null and only the namespace and Retired exceptions +# apply. See docs/operations/physical-inventory.md#cleanup-identity. +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicyBinding +metadata: + name: fleet-device-deletion-protection +spec: + policyName: fleet-device-deletion-protection + validationActions: [Deny] diff --git a/docs/operations/physical-inventory.md b/docs/operations/physical-inventory.md index c734df68..e56e59ea 100644 --- a/docs/operations/physical-inventory.md +++ b/docs/operations/physical-inventory.md @@ -138,7 +138,7 @@ is registered; the kinds are provider-internal, not a catalog offering. | Interface names are unique; MACs are lowercase and colon-separated, appear at most once per Device, and are either mapped to an interface or listed in `unmappedMACAddresses`, not both | Both | Malformed or ambiguous facts are rejected. | | The system UUID is in lowercase canonical form | Device | One spelling per identity. | | `bmc.endpoint` is an `https` host and optional port, with no credentials, path, query, or fragment | Device | Every inventory viewer can read it, so nothing secret can live in it. | -| `lifecycle` is `Active` (default), `Decommissioning` or `Retired`; `Active` and `Decommissioning` move between each other, only `Decommissioning` moves to `Retired`, and `Retired` is terminal | Device | Retirement is deliberate and one-way. Nothing reads the lifecycle yet. | +| `lifecycle` is `Active` (default), `Decommissioning` or `Retired`; `Active` and `Decommissioning` move between each other, only `Decommissioning` moves to `Retired`, and `Retired` is terminal | Device | Retirement is deliberate and one-way. Only the opt-in [Device deletion protection](#device-deletion-protection) reads the lifecycle. | | `status` is a separate subresource that declares no fields | All nine | Reserved for future collectors and verifiers to report drift and mismatch. Status never carries identity, and nothing writes it yet. | The CRDs cannot check that `claimRef` names an existing DeviceClaim, because @@ -343,6 +343,71 @@ that names the same claim. Leave the old Device in place and move its `spec.lifecycle` from `Active` to `Decommissioning`, then to `Retired`. Retired is terminal. +## Device deletion protection + +The `device-deletion-protection` component under `config/components` is a +ValidatingAdmissionPolicy and binding that keep an in-service Device from +being deleted, so its identity stays visible to duplicate-hardware checks. It +is opt-in: no root in this repository includes it. A deploying repository that +must keep in-service Devices adds it to the root it applies to the control +plane where Devices are admitted. + +A `DELETE` of a Device is admitted only when: + +1. the Device's namespace is being deleted; +2. the Device is `Retired`; or +3. the request's username is listed exactly in a configured cleanup identity. + This is off as shipped; see [Cleanup identity](#cleanup-identity). + +Every other delete is denied with `Forbidden`, and the message says to move +the Device to `Decommissioning`, then `Retired`, first. The policy fails +closed: an evaluation error or a missing namespace object denies the request. +Cluster administrators are held to the same rule. + +- **Collection deletes and garbage collection.** The API server admits each + object individually, so a collection delete that reaches a Device that is + not `Retired` leaves it in place. Retired Devices reached first may already + be gone, so repeat the delete per Device. A denied Device gets no deletion + timestamp, so its finalizers never run. +- **Namespace deletion is the escape hatch.** Once a namespace is marked for + deletion, its Devices can be deleted whatever their lifecycle, and their + identities leave the duplicate check. The policy observes the mark shortly + after it is set. +- **Project deletion.** Milo's project cleanup deletes the contents of every + namespace, `default` included, before it marks any namespace for deletion, + and it never deletes `default`. The namespace exception therefore does not + cover project teardown, and a denied delete stops the cleanup. Either + retire every Device first or configure the cleanup identity. +- **Validation.** `hack/validate-overlay-isolation.sh` renders the component on + its own and fails unless it is exactly this policy. It also fails if any + other root in this repository renders a Device deletion policy, or if the + inventory component exists without this one. + +### Cleanup identity + +The cleanup identity is a stopgap. Milo should mark every namespace it purges, +`default` included, before deleting its contents. The policy can then rely on +the namespace signal and drop the identity exemption. + +The binding ships without a `paramRef`, so the third exception is off. A +deploying repository turns it on by: + +1. Adding a ConfigMap with a `cleanupUsernames` key listing usernames, one per + line or separated by commas. Entries are trimmed and empty entries are + ignored. Matching is exact and case-sensitive; groups, prefixes and + wildcards never match, and an empty username never matches. List only the + identity that runs project cleanup. +2. Patching the binding with a `paramRef` that names the ConfigMap, sets its + `namespace` explicitly, and sets `parameterNotFoundAction: Deny`. + +A missing ConfigMap then denies every Device `DELETE`, including Retired +Devices and deletes in a deleting namespace, so teardown stops until the +ConfigMap exists. The API server reports this as `422 Invalid` rather than +`403`. Never set `parameterNotFoundAction: Allow`: a missing ConfigMap would +skip the policy and admit every delete. Anyone who can impersonate a listed +username, or who can write the ConfigMap or the binding, is outside the +guarantee; restrict them as tightly as the cleanup controller itself. + ## Relationship to the inventory proposal The names and writers match #63: diff --git a/hack/overlay-isolation-validator.go b/hack/overlay-isolation-validator.go index 8d1ea9f6..79e111f0 100644 --- a/hack/overlay-isolation-validator.go +++ b/hack/overlay-isolation-validator.go @@ -26,6 +26,29 @@ const ( marker = "fleet.datumapis.com/standalone-only" localProjectStandIn = "fleet.datumapis.com/local-project-stand-in" sharedNamespace = "fleet.datumapis.com/shared-with-standalone" + + // Device deletion protection is a reusable component that deploying + // repositories opt into. No root in this repository may render it, and the + // component rendered alone must be the exact fail-closed policy. + deletionProtection = "fleet-device-deletion-protection" + deletionProtectionComponent = "components/device-deletion-protection" + // inventoryComponent defines the Device CRD. A config tree that has it + // must also ship the deletion protection component. + inventoryComponent = "components/inventory" + + // deletionProtectionExpression is the only admitted rule: a Device DELETE + // passes when its namespace is being deleted, it is Retired, or the + // request's username is listed exactly in the parameter ConfigMap's + // cleanupUsernames. It is compared with whitespace normalized, so wildcard, + // prefix, group-based or null-params-allows-all variants are rejected. + deletionProtectionExpression = `(namespaceObject != null && has(namespaceObject.metadata) && +has(namespaceObject.metadata.deletionTimestamp)) || +(oldObject != null && has(oldObject.spec) && has(oldObject.spec.lifecycle) && +oldObject.spec.lifecycle == 'Retired') || +(params != null && has(params.data) && 'cleanupUsernames' in params.data && +request.userInfo.username != '' && +params.data.cleanupUsernames.replace('\n', ',').split(',').exists(entry, +entry.trim() != '' && entry.trim() == request.userInfo.username))` ) type kustomization struct { @@ -78,13 +101,22 @@ func main() { } } v.indexStandalone(standaloneObjects) + if err := checkDeletionProtection("standalone", standaloneObjects, false); err != nil { + fatalf("render %s: %v", standaloneRoot, err) + } + componentPresent := false + if _, err := os.Stat(filepath.Join(configRoot, filepath.FromSlash(deletionProtectionComponent))); err == nil { + componentPresent = true + } else if _, err := os.Stat(filepath.Join(configRoot, filepath.FromSlash(inventoryComponent))); err == nil { + fatalf("%s defines Devices, so %s must exist for deploying repositories to opt into", inventoryComponent, deletionProtectionComponent) + } entries, err := discover(configRoot) check(err) if len(entries) == 0 { fatalf("no Kustomize entry points found below %s", configRoot) } - checked := 0 + checked, componentChecked := 0, false for _, entry := range entries { root := filepath.Dir(entry) if v.definitionRoot(root) { @@ -103,10 +135,21 @@ func main() { fatalf("render %s: %v", root, err) } } + relative, err := filepath.Rel(configRoot, root) + check(err) + relative = filepath.ToSlash(relative) + required := relative == deletionProtectionComponent + componentChecked = componentChecked || required + if err := checkDeletionProtection(relative, objects, required); err != nil { + fatalf("render %s: %v", root, err) + } } if checked == 0 { fatalf("no non-standalone Kustomize entry point was validated") } + if componentPresent && !componentChecked { + fatalf("%s was not rendered on its own", deletionProtectionComponent) + } } func (v *validator) definitionRoot(path string) bool { @@ -260,6 +303,133 @@ func (v *validator) checkObject(object *unstructured.Unstructured) error { return nil } +// checkDeletionProtection requires the exact Device DELETE policy and its +// binding when the component is rendered alone, and forbids either object in +// every other root: deploying repositories opt in, this repository does not. +func checkDeletionProtection(root string, objects []*unstructured.Unstructured, required bool) error { + var policy, binding *unstructured.Unstructured + for _, object := range objects { + if object.GetAPIVersion() != "admissionregistration.k8s.io/v1" { + continue + } + switch object.GetKind() { + case "ValidatingAdmissionPolicy": + if object.GetName() == deletionProtection || policyMatchesDeviceDelete(object) { + policy = object + } + case "ValidatingAdmissionPolicyBinding": + if name, _, _ := unstructured.NestedString(object.Object, "spec", "policyName"); object.GetName() == deletionProtection || name == deletionProtection { + binding = object + } + } + } + if !required { + if policy != nil || binding != nil { + return fmt.Errorf("%s renders Device deletion protection; no root in this repository may include %s, deploying repositories opt in", root, deletionProtectionComponent) + } + return nil + } + if policy == nil || binding == nil { + return fmt.Errorf("%s must render the Device deletion policy and its binding", root) + } + failurePolicy, _, _ := unstructured.NestedString(policy.Object, "spec", "failurePolicy") + validations, _, _ := unstructured.NestedSlice(policy.Object, "spec", "validations") + spec := policy.Object["spec"].(map[string]any) + _, hasConditions := spec["matchConditions"] + _, hasVariables := spec["variables"] + if policy.GetName() != deletionProtection || failurePolicy != "Fail" || !policyMatchesDeviceDelete(policy) || !unscopedConstraints(policy) || hasConditions || hasVariables || len(validations) != 1 { + return fmt.Errorf("%s: Device deletion policy must fail closed, match DELETE on devices and have no exemptions", root) + } + if !configMapParamKind(spec["paramKind"]) { + return fmt.Errorf("%s: Device deletion policy paramKind must be exactly core/v1 ConfigMap", root) + } + if expression, _, _ := unstructured.NestedString(validations[0].(map[string]any), "expression"); strings.Join(strings.Fields(expression), " ") != strings.Join(strings.Fields(deletionProtectionExpression), " ") { + return fmt.Errorf("%s: Device deletion policy must allow DELETE only for a Retired Device, a deleting namespace or an exactly listed cleanup username", root) + } + actions, _, _ := unstructured.NestedStringSlice(binding.Object, "spec", "validationActions") + _, hasMatch := binding.Object["spec"].(map[string]any)["matchResources"] + if len(actions) != 1 || actions[0] != "Deny" || hasMatch { + return fmt.Errorf("%s: Device deletion binding must Deny in every namespace", root) + } + // The component ships the cleanup identity off. A deploying repository + // adds the paramRef, with parameterNotFoundAction: Deny, alongside its own + // ConfigMap; a paramRef here, and above all one that Allows a missing + // parameter (which skips the policy), is rejected. + if _, hasParamRef := binding.Object["spec"].(map[string]any)["paramRef"]; hasParamRef { + return fmt.Errorf("%s: Device deletion binding must not set paramRef; deploying repositories enable the cleanup identity", root) + } + return nil +} + +// configMapParamKind reports whether a policy paramKind is exactly core/v1 +// ConfigMap, the only parameter the cleanup identity reads. +func configMapParamKind(value any) bool { + paramKind, ok := value.(map[string]any) + return ok && len(paramKind) == 2 && paramKind["apiVersion"] == "v1" && paramKind["kind"] == "ConfigMap" +} + +func policyMatchesDeviceDelete(policy *unstructured.Unstructured) bool { + rules, _, _ := unstructured.NestedSlice(policy.Object, "spec", "matchConstraints", "resourceRules") + for _, raw := range rules { + rule, ok := raw.(map[string]any) + if !ok { + continue + } + groups, resources, operations := stringsFrom(rule["apiGroups"]), stringsFrom(rule["resources"]), stringsFrom(rule["operations"]) + if (contains(groups, "fleet.datumapis.com") || contains(groups, "*")) && (contains(resources, "devices") || contains(resources, "*")) && (contains(operations, "DELETE") || contains(operations, "*")) { + return true + } + } + return false +} + +// unscopedConstraints reports whether the policy's match constraints apply to +// every namespace and object, with no exclusions or name restrictions. +func unscopedConstraints(policy *unstructured.Unstructured) bool { + constraints, _, _ := unstructured.NestedMap(policy.Object, "spec", "matchConstraints") + for _, key := range []string{"namespaceSelector", "objectSelector", "excludeResourceRules"} { + if value, found := constraints[key]; found && !emptyValue(value) { + return false + } + } + rules, _, _ := unstructured.NestedSlice(policy.Object, "spec", "matchConstraints", "resourceRules") + for _, raw := range rules { + rule, ok := raw.(map[string]any) + if !ok { + return false + } + if names, found := rule["resourceNames"]; found && !emptyValue(names) { + return false + } + if scope, found := rule["scope"]; found && scope != "*" && scope != "Namespaced" { + return false + } + } + return true +} + +func emptyValue(value any) bool { + switch typed := value.(type) { + case nil: + return true + case map[string]any: + return len(typed) == 0 + case []any: + return len(typed) == 0 + default: + return false + } +} + +func contains(values []string, value string) bool { + for _, candidate := range values { + if candidate == value { + return true + } + } + return false +} + func isCoreNamespace(object *unstructured.Unstructured) bool { return object.GetAPIVersion() == "v1" && object.GetKind() == "Namespace" } diff --git a/hack/test-overlay-isolation.sh b/hack/test-overlay-isolation.sh index e8564d36..ee163d01 100755 --- a/hack/test-overlay-isolation.sh +++ b/hack/test-overlay-isolation.sh @@ -417,4 +417,98 @@ EOF expect_failure "intentional Kustomize build failure" "missing.yaml" rm -rf "$fixture_root/config/overlays/broken" +# Device deletion protection is a reusable component that deploying +# repositories opt into. No root in this repository may render it, and the +# component rendered alone must be the exact fail-closed policy. +component="$fixture_root/config/components/device-deletion-protection" +policy="$repo_root/config/components/device-deletion-protection/policy.yaml" +mkdir -p "$fixture_root/config/components/inventory" +cat >"$fixture_root/config/components/inventory/kustomization.yaml" <<'EOF' +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: [../../base/safe] +EOF +expect_failure "Device inventory without the deletion component" "must exist for deploying repositories to opt into" +mkdir -p "$component" +cp "$repo_root/config/components/device-deletion-protection/kustomization.yaml" "$policy" "$component/" +"$repo_root/hack/validate-overlay-isolation.sh" "$fixture_root/config" "$fixture_root/config/standalone" + +mkdir -p "$fixture_root/config/milo-production" +cat >"$fixture_root/config/milo-production/kustomization.yaml" <<'EOF' +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: [../base/safe] +components: [../components/device-deletion-protection] +EOF +expect_failure "fleet root including the deletion component" "milo-production renders Device deletion protection" +rm -rf "$fixture_root/config/milo-production" +mkdir -p "$fixture_root/config/overlays/synthetic-with-protection" +cat >"$fixture_root/config/overlays/synthetic-with-protection/kustomization.yaml" <<'EOF' +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: [../../base/safe] +components: [../../components/device-deletion-protection] +EOF +expect_failure "nested fleet root including the deletion component" "renders Device deletion protection" +rm -rf "$fixture_root/config/overlays/synthetic-with-protection" +mkdir -p "$fixture_root/config/overlays/renamed-protection" +sed 's/name: fleet-device-deletion-protection/name: renamed-device-guard/; s/policyName: fleet-device-deletion-protection/policyName: renamed-device-guard/' "$policy" >"$fixture_root/config/overlays/renamed-protection/policy.yaml" +cat >"$fixture_root/config/overlays/renamed-protection/kustomization.yaml" <<'EOF' +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: [policy.yaml] +EOF +expect_failure "renamed Device deletion policy copied into a fleet root" "renders Device deletion protection" +rm -rf "$fixture_root/config/overlays/renamed-protection" + +# Each weakening below is rendered through the component itself. +weakened() { + description=$1 + expected=$2 + shift 2 + sed "$@" "$policy" >"$component/policy.yaml" + if cmp -s "$policy" "$component/policy.yaml"; then + echo "$description fixture did not change the policy" >&2 + exit 1 + fi + expect_failure "$description" "$expected" + cp "$policy" "$component/policy.yaml" +} +weakened "renamed Device deletion policy" "components/device-deletion-protection: Device deletion policy must fail closed" -e '1,/kind: ValidatingAdmissionPolicyBinding/s/name: fleet-device-deletion-protection/name: renamed-device-guard/' +weakened "renamed Device deletion policy and binding" "components/device-deletion-protection must render the Device deletion policy and its binding" -e 's/name: fleet-device-deletion-protection/name: renamed-device-guard/' -e 's/policyName: fleet-device-deletion-protection/policyName: renamed-device-guard/' +weakened "audit-only Device deletion binding" "must Deny in every namespace" -e 's/validationActions: \[Deny\]/validationActions: [Audit]/' +weakened "warn-only Device deletion binding" "must Deny in every namespace" -e 's/validationActions: \[Deny\]/validationActions: [Warn]/' +weakened "fail-open Device deletion policy" "must fail closed" -e 's/failurePolicy: Fail/failurePolicy: Ignore/' +weakened "always-true Device deletion expression" "allow DELETE only for a Retired Device, a deleting namespace or an exactly listed cleanup username" -e "s/oldObject.spec.lifecycle == 'Retired')/oldObject.spec.lifecycle == 'Retired') || true/" +weakened "Decommissioning Device deletion allowed" "allow DELETE only for a Retired Device, a deleting namespace or an exactly listed cleanup username" -e "s/== 'Retired')/!= 'Active')/" +weakened "namespace-scoped Device deletion policy" "must fail closed" -e 's/ matchPolicy: Equivalent/ matchPolicy: Equivalent\ + namespaceSelector: {matchLabels: {protected: "true"}}/' +weakened "subject exemption in Device deletion policy" "must fail closed" -e 's/^ validations:/ matchConditions:\ + - name: not-admin\ + expression: "request.userInfo.username != '\''admin'\''"\ + validations:/' + +# The cleanup identity clause admits only an exactly listed, non-empty +# username from a ConfigMap parameter, and the component ships it off. +allowed="allow DELETE only for a Retired Device, a deleting namespace or an exactly listed cleanup username" +weakened "always-true cleanup identity clause" "$allowed" -e "s/entry.trim() != '' && entry.trim() == request.userInfo.username/true/" +weakened "wildcard cleanup username" "$allowed" -e "s/entry.trim() == request.userInfo.username/(entry.trim() == '*' || entry.trim() == request.userInfo.username)/" +weakened "prefix cleanup username" "$allowed" -e "s/entry.trim() == request.userInfo.username/request.userInfo.username.startsWith(entry.trim())/" +weakened "group-based cleanup exemption" "$allowed" -e "s/entry.trim() == request.userInfo.username))/entry.trim() == request.userInfo.username)) ||\\ + (params != null \&\& request.userInfo.groups.exists(group, group in params.data.cleanupUsernames.split(',')))/" +weakened "absent params allowing every Device deletion" "$allowed" -e "s/(params != null && has(params.data)/(params == null || has(params.data)/" +weakened "empty username matching an empty entry" "$allowed" -e "s/entry.trim() != '' && entry.trim() == request.userInfo.username/entry.trim() == request.userInfo.username/" -e "/request.userInfo.username != '' &&\$/d" +weakened "Secret paramKind" "paramKind must be exactly core/v1 ConfigMap" -e 's/^ kind: ConfigMap$/ kind: Secret/' +weakened "missing paramKind" "paramKind must be exactly core/v1 ConfigMap" -e '/^ paramKind:$/d' -e '/^ apiVersion: v1$/d' -e '/^ kind: ConfigMap$/d' +weakened "Allow parameterNotFoundAction in the component" "must not set paramRef" -e 's/^ validationActions: \[Deny\]/ validationActions: [Deny]\ + paramRef:\ + name: synthetic-device-cleanup\ + namespace: synthetic-device-cleanup\ + parameterNotFoundAction: Allow/' +weakened "cleanup identity enabled in the component" "must not set paramRef" -e 's/^ validationActions: \[Deny\]/ validationActions: [Deny]\ + paramRef:\ + name: synthetic-device-cleanup\ + namespace: synthetic-device-cleanup\ + parameterNotFoundAction: Deny/' + "$repo_root/hack/validate-overlay-isolation.sh" "$fixture_root/config" "$fixture_root/config/standalone" diff --git a/internal/api/inventory/v1alpha1/deletion_envtest_test.go b/internal/api/inventory/v1alpha1/deletion_envtest_test.go new file mode 100644 index 00000000..7a7ed113 --- /dev/null +++ b/internal/api/inventory/v1alpha1/deletion_envtest_test.go @@ -0,0 +1,387 @@ +package v1alpha1 + +import ( + "context" + "fmt" + "strings" + "testing" + + admissionregistrationv1 "k8s.io/api/admissionregistration/v1" + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/controller-runtime/pkg/client" +) + +const ( + deletionDenied = "A Device can be deleted only when it is Retired, when its namespace is being deleted, or by a configured cleanup identity" + // Synthetic identities. The policy compares usernames only, so each actor + // also holds system:masters to pass RBAC and prove groups do not matter. + syntheticCleanupUser = "synthetic-cleanup" + syntheticPurgeUser = "system:synthetic-purger" + cleanupConfig = "synthetic-device-cleanup" + missingParamsDenied = "no params found for policy binding with `Deny` parameterNotFoundAction" +) + +func (api *liveAPI) namespace(name string) *corev1.Namespace { + api.t.Helper() + namespace := &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: name}} + if err := api.admin.Create(context.Background(), namespace); err != nil { + api.t.Fatal(err) + } + return namespace +} + +// TestDeviceLifecycleTransitionsAgainstLiveAPI runs the CRD transition rules +// in a real API server. +func TestDeviceLifecycleTransitionsAgainstLiveAPI(t *testing.T) { + api := startAPI(t) + device := api.device("lifecycle", "default", "lifecycle-serial", "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaa1") + if device.Spec.Lifecycle != DeviceActive { + t.Fatalf("created Device lifecycle = %q, want the Active default", device.Spec.Lifecycle) + } + rejected := func(to DeviceLifecycle, message string) { + t.Helper() + if err := api.updateLifecycle(device, to); !apierrors.IsInvalid(err) || !strings.Contains(err.Error(), message) { + t.Fatalf("transition to %s: %v", to, err) + } + } + rejected(DeviceRetired, "move an Active Device to Decommissioning before Retired") + api.setLifecycle(device, DeviceDecommissioning) + api.setLifecycle(device, DeviceActive) + api.setLifecycle(device, DeviceDecommissioning) + api.setLifecycle(device, DeviceRetired) + rejected(DeviceActive, "Retired is terminal") + rejected(DeviceDecommissioning, "Retired is terminal") + rejected("", "Retired is terminal") + api.setLifecycle(device, DeviceRetired) +} + +// TestDeviceDeletionProtection applies the component's manifests as a +// deploying repository that opts in would, and checks every deletion path. +func TestDeviceDeletionProtection(t *testing.T) { + api := startAPI(t) + ctx := context.Background() + active := api.device("active", "default", "active-serial", "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbb1") + decommissioning := api.device("decommissioning", "default", "decommissioning-serial", "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbb2") + api.setLifecycle(decommissioning, DeviceDecommissioning) + retired := api.device("retired", "default", "retired-serial", "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbb3") + api.retire(retired) + + api.namespace("mixed") + mixed := map[string]DeviceLifecycle{"mixed-active": DeviceActive, "mixed-decommissioning": DeviceDecommissioning, "mixed-retired-a": DeviceRetired, "mixed-retired-b": DeviceRetired} + mixedDevices := map[string]*Device{} + suffix := 0 + for name, lifecycle := range mixed { + suffix++ + device := api.device(name, "mixed", name+"-serial", fmt.Sprintf("cccccccc-cccc-4ccc-8ccc-%012d", suffix)) + switch lifecycle { + case DeviceDecommissioning: + api.setLifecycle(device, lifecycle) + case DeviceRetired: + api.retire(device) + } + mixedDevices[name] = device + } + + teardown := api.namespace("teardown") + teardownActive := api.device("teardown-active", "teardown", "teardown-active-serial", "dddddddd-dddd-4ddd-8ddd-ddddddddddd1") + teardownDecommissioning := api.device("teardown-decommissioning", "teardown", "teardown-decommissioning-serial", "dddddddd-dddd-4ddd-8ddd-ddddddddddd2") + api.setLifecycle(teardownDecommissioning, DeviceDecommissioning) + + api.installDeletionProtection(active) + operator := api.actor("operator", "system:masters") + + t.Run("Active and Decommissioning Devices cannot be deleted by any caller", func(t *testing.T) { + for _, device := range []*Device{active, decommissioning} { + for _, caller := range []client.Client{api.admin, operator} { + if err := caller.Delete(ctx, device); !apierrors.IsForbidden(err) || !strings.Contains(err.Error(), deletionDenied) || !strings.Contains(err.Error(), "Decommissioning, then Retired") { + t.Fatalf("deleting %s: %v", device.Name, err) + } + } + if !api.exists(device) { + t.Fatalf("%s removed despite deletion protection", device.Name) + } + } + }) + t.Run("without a paramRef the cleanup username is not exempt", func(t *testing.T) { + // The shipped binding has no paramRef, so params is null. A null + // params must evaluate, not error: the denial carries the policy's + // own message, and the Retired subtest below is admitted. + cleanup := api.actor(syntheticCleanupUser, "system:masters") + if err := cleanup.Delete(ctx, active); !apierrors.IsForbidden(err) || !strings.Contains(err.Error(), deletionDenied) { + t.Fatalf("cleanup username deleting an Active Device without a paramRef: %v", err) + } + if !api.exists(active) { + t.Fatal("Active Device removed without a paramRef") + } + }) + t.Run("a Retired Device can be deleted", func(t *testing.T) { + if err := operator.Delete(ctx, retired); err != nil { + t.Fatalf("deleting a Retired Device: %v", err) + } + if api.exists(retired) { + t.Fatal("Retired Device survived deletion") + } + }) + t.Run("deletecollection denies the Devices that are not Retired", func(t *testing.T) { + if err := api.admin.DeleteAllOf(ctx, &Device{}, client.InNamespace("mixed")); !apierrors.IsForbidden(err) || !strings.Contains(err.Error(), deletionDenied) { + t.Fatalf("deletecollection over mixed Devices: %v", err) + } + // The API server stops a collection delete at its first denial, so + // each Retired Device is either already gone or deletable now. + for name, lifecycle := range mixed { + device := mixedDevices[name] + err := api.admin.Delete(ctx, device) + switch { + case lifecycle == DeviceRetired && err != nil && !apierrors.IsNotFound(err): + t.Fatalf("deleting Retired %s after deletecollection: %v", name, err) + case lifecycle != DeviceRetired && (!apierrors.IsForbidden(err) || !api.exists(device)): + t.Fatalf("%s (%s) is not protected after deletecollection: %v", name, lifecycle, err) + case lifecycle == DeviceRetired && api.exists(device): + t.Fatalf("Retired %s survived", name) + } + } + }) + t.Run("deleting the namespace lets its Devices be deleted", func(t *testing.T) { + if err := api.admin.Delete(ctx, teardownActive); !apierrors.IsForbidden(err) { + t.Fatalf("Device deletion before namespace deletion: %v", err) + } + if err := api.admin.Delete(ctx, teardown); err != nil { + t.Fatal(err) + } + if !api.exists(teardown) || teardown.DeletionTimestamp.IsZero() { + t.Fatal("namespace is not marked for deletion") + } + // The policy reads namespaceObject from the API server's namespace + // cache, which observes the deletion mark shortly after it is set. + api.eventually("namespace deletion mark", func() bool { + return api.admin.Delete(ctx, teardownActive, client.DryRunAll) == nil + }) + // envtest runs no namespace controller. Issue the content deletions + // the controller would: deletecollection, then per item. + if err := api.admin.DeleteAllOf(ctx, &Device{}, client.InNamespace("teardown")); err != nil { + t.Fatalf("namespace cleanup deletecollection: %v", err) + } + for _, device := range []*Device{teardownActive, teardownDecommissioning} { + if err := api.admin.Delete(ctx, device); err != nil && !apierrors.IsNotFound(err) { + t.Fatalf("namespace cleanup of %s: %v", device.Name, err) + } + if api.exists(device) { + t.Fatalf("%s survived namespace cleanup", device.Name) + } + } + }) + t.Run("Devices in other namespaces stay protected", func(t *testing.T) { + if err := api.admin.Delete(ctx, active); !apierrors.IsForbidden(err) || !api.exists(active) { + t.Fatalf("Active Device outside the deleting namespace: %v", err) + } + }) +} + +// setParamRef does what a deploying repository does to turn on the cleanup +// identity: it points the binding at a ConfigMap in a fixed namespace with +// parameterNotFoundAction: Deny. The ConfigMap is created separately, so a +// test can also point the binding at one that does not exist. +func (api *liveAPI) setParamRef(name string) { + api.t.Helper() + ctx := context.Background() + binding := &admissionregistrationv1.ValidatingAdmissionPolicyBinding{} + if err := api.admin.Get(ctx, client.ObjectKey{Name: "fleet-device-deletion-protection"}, binding); err != nil { + api.t.Fatal(err) + } + deny := admissionregistrationv1.DenyAction + binding.Spec.ParamRef = &admissionregistrationv1.ParamRef{Name: name, Namespace: cleanupConfig, ParameterNotFoundAction: &deny} + if err := api.admin.Update(ctx, binding); err != nil { + api.t.Fatal(err) + } +} + +// missingParams reports whether err is the API server's denial for a binding +// whose parameter is missing under parameterNotFoundAction: Deny. +func missingParams(err error) bool { + return apierrors.IsInvalid(err) && strings.Contains(err.Error(), missingParamsDenied) +} + +func requireDeletionDenied(t *testing.T, err error, message string) { + t.Helper() + if !apierrors.IsForbidden(err) || !strings.Contains(err.Error(), message) { + t.Fatalf("expected a Device deletion denial containing %q, got %v", message, err) + } +} + +// TestDeviceDeletionCleanupIdentity enables the cleanup identity as a +// deploying repository would and checks who it admits, that the other two +// exceptions still hold, that it lets a Milo-style purge drain `default`, and +// that a missing ConfigMap fails closed. +func TestDeviceDeletionCleanupIdentity(t *testing.T) { + api := startAPI(t) + ctx := context.Background() + suffix := 0 + lifecycled := func(name, namespace string, lifecycle DeviceLifecycle) *Device { + suffix++ + device := api.device(name, namespace, fmt.Sprintf("%s-serial-%d", name, suffix), fmt.Sprintf("eeeeeeee-eeee-4eee-8eee-%012d", suffix)) + switch lifecycle { + case DeviceDecommissioning: + api.setLifecycle(device, lifecycle) + case DeviceRetired: + api.retire(device) + } + return device + } + active := lifecycled("cleanup-active", "default", DeviceActive) + decommissioning := lifecycled("cleanup-decommissioning", "default", DeviceDecommissioning) + guarded := lifecycled("guarded-active", "default", DeviceActive) + retired := lifecycled("cleanup-retired", "default", DeviceRetired) + api.namespace("collection") + collection := []*Device{ + lifecycled("collection-active", "collection", DeviceActive), + lifecycled("collection-decommissioning", "collection", DeviceDecommissioning), + lifecycled("collection-retired", "collection", DeviceRetired), + } + api.namespace("workloads") + purged := []*Device{ + lifecycled("purge-default-active", "default", DeviceActive), + lifecycled("purge-default-decommissioning", "default", DeviceDecommissioning), + lifecycled("purge-default-retired", "default", DeviceRetired), + lifecycled("purge-workloads-active", "workloads", DeviceActive), + lifecycled("purge-workloads-decommissioning", "workloads", DeviceDecommissioning), + lifecycled("purge-workloads-retired", "workloads", DeviceRetired), + } + teardown := api.namespace("teardown") + teardownFirst := lifecycled("teardown-first", "teardown", DeviceActive) + teardownSecond := lifecycled("teardown-second", "teardown", DeviceActive) + + api.installDeletionProtection(guarded) + cleanup := api.actor(syntheticCleanupUser, "system:masters") + purger := api.actor(syntheticPurgeUser, "system:masters") + operator := api.actor("synthetic-operator", "system:masters") + + t.Run("without a paramRef the cleanup username is denied", func(t *testing.T) { + requireDeletionDenied(t, cleanup.Delete(ctx, active), deletionDenied) + if !api.exists(active) { + t.Fatal("Active Device removed without a paramRef") + } + }) + + // Entries are padded and separated by commas, newlines and CRLF, with + // blank entries in between. Only exact, trimmed names match. + api.namespace(cleanupConfig) + config := &corev1.ConfigMap{ObjectMeta: metav1.ObjectMeta{Name: cleanupConfig, Namespace: cleanupConfig}, Data: map[string]string{"cleanupUsernames": " " + syntheticCleanupUser + " ,\n\n , \r\n" + syntheticPurgeUser + "\r\n,"}} + if err := api.admin.Create(ctx, config); err != nil { + t.Fatal(err) + } + api.setParamRef(cleanupConfig) + api.eventually("cleanup identity", func() bool { + return cleanup.Delete(ctx, guarded, client.DryRunAll) == nil + }) + + t.Run("the listed username deletes Active and Decommissioning Devices", func(t *testing.T) { + for _, device := range []*Device{active, decommissioning} { + if err := cleanup.Delete(ctx, device); err != nil { + t.Fatalf("cleanup identity deleting %s: %v", device.Name, err) + } + if api.exists(device) { + t.Fatalf("%s survived the cleanup identity's delete", device.Name) + } + } + }) + t.Run("the listed username deletes a mixed collection", func(t *testing.T) { + if err := cleanup.DeleteAllOf(ctx, &Device{}, client.InNamespace("collection")); err != nil { + t.Fatalf("cleanup identity deletecollection: %v", err) + } + for _, device := range collection { + if api.exists(device) { + t.Fatalf("%s survived the cleanup identity's deletecollection", device.Name) + } + } + }) + t.Run("other usernames stay denied", func(t *testing.T) { + callers := map[string]client.Client{ + "admin": api.admin, + "unlisted": operator, + "prefix": api.actor("synthetic-clean", "system:masters"), + "superset": api.actor(syntheticCleanupUser+"-extra", "system:masters"), + "embedded": api.actor("x"+syntheticCleanupUser, "system:masters"), + "case": api.actor("Synthetic-Cleanup", "system:masters"), + "listed name as a group": api.actor("synthetic-grouped", "system:masters", syntheticCleanupUser), + "suffix of a listed name": api.actor("synthetic-purger", "system:masters"), + } + for name, caller := range callers { + if err := caller.Delete(ctx, guarded); !apierrors.IsForbidden(err) || !strings.Contains(err.Error(), deletionDenied) { + t.Fatalf("%s deleting an Active Device: %v", name, err) + } + } + if !api.exists(guarded) { + t.Fatal("Active Device removed by an unlisted caller") + } + }) + t.Run("the Retired exception still holds", func(t *testing.T) { + if err := operator.Delete(ctx, retired); err != nil { + t.Fatalf("unlisted caller deleting a Retired Device: %v", err) + } + }) + t.Run("the deleting-namespace exception still holds", func(t *testing.T) { + requireDeletionDenied(t, operator.Delete(ctx, teardownFirst), deletionDenied) + if err := api.admin.Delete(ctx, teardown); err != nil { + t.Fatal(err) + } + api.eventually("namespace deletion mark", func() bool { + return operator.Delete(ctx, teardownFirst, client.DryRunAll) == nil + }) + if err := operator.Delete(ctx, teardownFirst); err != nil { + t.Fatalf("unlisted caller deleting a Device in a deleting namespace: %v", err) + } + // teardownSecond stays behind for the fail-closed check below. + }) + t.Run("a Milo-style purge drains default and other namespaces", func(t *testing.T) { + // Milo v0.36.9 project purge issues DeleteCollection per namespace, + // `default` included, before any namespace is marked for deletion. + for _, namespace := range []string{"default", "workloads"} { + if err := purger.DeleteAllOf(ctx, &Device{}, client.InNamespace(namespace)); err != nil { + t.Fatalf("purge deletecollection in %s: %v", namespace, err) + } + } + for _, device := range append(purged, guarded) { + if api.exists(device) { + t.Fatalf("%s survived the purge", device.Name) + } + } + }) + + // Fail closed: a paramRef to a ConfigMap that does not exist, under + // parameterNotFoundAction: Deny, denies every Device DELETE, including a + // Retired Device, the listed username and a deleting namespace. The API + // server reports this binding configuration error as 422 Invalid, not as + // the policy's 403 Forbidden. + failClosedRetired := lifecycled("fail-closed-retired", "default", DeviceRetired) + failClosedActive := lifecycled("fail-closed-active", "default", DeviceActive) + api.setParamRef("absent-" + cleanupConfig) + api.eventually("missing parameter denial", func() bool { + return missingParams(operator.Delete(ctx, failClosedRetired, client.DryRunAll)) + }) + t.Run("a missing ConfigMap denies every delete", func(t *testing.T) { + attempts := []struct { + name string + attempt func() error + }{ + {"Retired by an unlisted caller", func() error { return operator.Delete(ctx, failClosedRetired) }}, + {"Retired by the cleanup user", func() error { return cleanup.Delete(ctx, failClosedRetired) }}, + {"Active by the cleanup user", func() error { return cleanup.Delete(ctx, failClosedActive) }}, + {"Device in a deleting namespace", func() error { return api.admin.Delete(ctx, teardownSecond) }}, + {"purge deletecollection", func() error { + return purger.DeleteAllOf(ctx, &Device{}, client.InNamespace("default")) + }}, + } + for _, test := range attempts { + if err := test.attempt(); !missingParams(err) { + t.Fatalf("%s: %v", test.name, err) + } + } + for _, device := range []*Device{failClosedRetired, failClosedActive, teardownSecond} { + if !api.exists(device) { + t.Fatalf("%s removed while the parameter is missing", device.Name) + } + } + }) +} diff --git a/internal/api/inventory/v1alpha1/deletion_policy_test.go b/internal/api/inventory/v1alpha1/deletion_policy_test.go new file mode 100644 index 00000000..cf6fd1f1 --- /dev/null +++ b/internal/api/inventory/v1alpha1/deletion_policy_test.go @@ -0,0 +1,140 @@ +package v1alpha1 + +import ( + "bytes" + "context" + "errors" + "io" + "os" + "path/filepath" + "testing" + + admissionv1 "k8s.io/api/admission/v1" + admissionregistrationv1 "k8s.io/api/admissionregistration/v1" + authenticationv1 "k8s.io/api/authentication/v1" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + utilyaml "k8s.io/apimachinery/pkg/util/yaml" + "k8s.io/apiserver/pkg/admission" + plugincel "k8s.io/apiserver/pkg/admission/plugin/cel" + "k8s.io/apiserver/pkg/admission/plugin/policy/validating" + celconfig "k8s.io/apiserver/pkg/apis/cel" + "k8s.io/apiserver/pkg/authentication/user" + "k8s.io/apiserver/pkg/cel/environment" +) + +// deletionPolicy reads the component's ValidatingAdmissionPolicy. +func deletionPolicy(t *testing.T) *admissionregistrationv1.ValidatingAdmissionPolicy { + t.Helper() + data, err := os.ReadFile(filepath.Join(configRoot, "components", "device-deletion-protection", "policy.yaml")) + if err != nil { + t.Fatal(err) + } + decoder := utilyaml.NewYAMLOrJSONDecoder(bytes.NewReader(data), 4096) + for { + var policy admissionregistrationv1.ValidatingAdmissionPolicy + err := decoder.Decode(&policy) + if errors.Is(err, io.EOF) { + t.Fatal("component has no ValidatingAdmissionPolicy") + } + if err != nil { + t.Fatal(err) + } + if policy.Kind == "ValidatingAdmissionPolicy" { + return &policy + } + } +} + +type deletionInput struct { + username string + groups []string + lifecycle string + namespaceDeleted bool + params *corev1.ConfigMap +} + +// TestDeletionPolicyCleanupIdentityOffline evaluates the policy's expression +// with the API server's admission CEL compiler, for inputs envtest cannot +// produce, such as an empty username. +func TestDeletionPolicyCleanupIdentityOffline(t *testing.T) { + policy := deletionPolicy(t) + if policy.Spec.ParamKind == nil || policy.Spec.ParamKind.APIVersion != "v1" || policy.Spec.ParamKind.Kind != "ConfigMap" { + t.Fatalf("paramKind = %+v, want core/v1 ConfigMap", policy.Spec.ParamKind) + } + if len(policy.Spec.Validations) != 1 { + t.Fatalf("validations = %d, want 1", len(policy.Spec.Validations)) + } + compiler := plugincel.NewConditionCompiler(environment.MustBaseEnvSet(environment.DefaultCompatibilityVersion())) + evaluator := compiler.CompileCondition([]plugincel.ExpressionAccessor{&validating.ValidationCondition{Expression: policy.Spec.Validations[0].Expression}}, plugincel.OptionalVariableDeclarations{HasParams: true}, environment.StoredExpressions) + + listed := func(value string) *corev1.ConfigMap { + return &corev1.ConfigMap{ObjectMeta: metav1.ObjectMeta{Name: "synthetic-device-cleanup", Namespace: "synthetic-device-cleanup"}, Data: map[string]string{"cleanupUsernames": value}} + } + list := listed(" synthetic-cleanup ,\n\n , \r\nsystem:synthetic-purger\r\n,") + for _, test := range []struct { + name string + input deletionInput + want bool + }{ + {"no params: listed name is not exempt", deletionInput{username: "synthetic-cleanup", lifecycle: "Active"}, false}, + {"no params: Retired is deletable", deletionInput{username: "synthetic-operator", lifecycle: "Retired"}, true}, + {"no params: deleting namespace", deletionInput{username: "synthetic-operator", lifecycle: "Active", namespaceDeleted: true}, true}, + {"listed name with padding", deletionInput{username: "synthetic-cleanup", lifecycle: "Active", params: list}, true}, + {"listed name after CRLF and blank entries", deletionInput{username: "system:synthetic-purger", lifecycle: "Decommissioning", params: list}, true}, + {"unlisted name", deletionInput{username: "synthetic-operator", lifecycle: "Active", params: list}, false}, + {"prefix of a listed name", deletionInput{username: "synthetic-clean", lifecycle: "Active", params: list}, false}, + {"superset of a listed name", deletionInput{username: "synthetic-cleanup-extra", lifecycle: "Active", params: list}, false}, + {"listed name embedded", deletionInput{username: "xsynthetic-cleanup", lifecycle: "Active", params: list}, false}, + {"case differs", deletionInput{username: "Synthetic-Cleanup", lifecycle: "Active", params: list}, false}, + {"listed name as a group only", deletionInput{username: "synthetic-operator", groups: []string{"synthetic-cleanup"}, lifecycle: "Active", params: list}, false}, + {"empty username against empty entries", deletionInput{username: "", lifecycle: "Active", params: listed(",\n , \n")}, false}, + {"empty username against an empty value", deletionInput{username: "", lifecycle: "Active", params: listed("")}, false}, + {"wildcard entry is literal", deletionInput{username: "synthetic-operator", lifecycle: "Active", params: listed("*")}, false}, + {"ConfigMap without the key", deletionInput{username: "synthetic-cleanup", lifecycle: "Active", params: &corev1.ConfigMap{Data: map[string]string{"other": "synthetic-cleanup"}}}, false}, + {"ConfigMap without data", deletionInput{username: "synthetic-cleanup", lifecycle: "Active", params: &corev1.ConfigMap{}}, false}, + {"params set: Retired still deletable", deletionInput{username: "synthetic-operator", lifecycle: "Retired", params: list}, true}, + {"params set: deleting namespace still deletable", deletionInput{username: "synthetic-operator", lifecycle: "Active", namespaceDeleted: true, params: list}, true}, + } { + t.Run(test.name, func(t *testing.T) { + if got := evaluateDeletion(t, evaluator, test.input); got != test.want { + t.Fatalf("admitted = %v, want %v", got, test.want) + } + }) + } +} + +func evaluateDeletion(t *testing.T, evaluator plugincel.ConditionEvaluator, input deletionInput) bool { + t.Helper() + gvk := schema.GroupVersionKind{Group: "fleet.datumapis.com", Version: "v1alpha1", Kind: "Device"} + gvr := schema.GroupVersionResource{Group: "fleet.datumapis.com", Version: "v1alpha1", Resource: "devices"} + old := &unstructured.Unstructured{Object: map[string]any{"apiVersion": gvk.GroupVersion().String(), "kind": gvk.Kind, "metadata": map[string]any{"name": "synthetic-device", "namespace": "default"}, "spec": map[string]any{"lifecycle": input.lifecycle}}} + caller := &user.DefaultInfo{Name: input.username, Groups: input.groups} + attributes := admission.NewAttributesRecord(nil, old, gvk, "default", "synthetic-device", gvr, "", admission.Delete, &metav1.DeleteOptions{}, false, caller) + versioned := &admission.VersionedAttributes{Attributes: attributes, VersionedOldObject: admission.NewLazyObject(old), VersionedKind: gvk} + request := &admissionv1.AdmissionRequest{Kind: metav1.GroupVersionKind(gvk), Resource: metav1.GroupVersionResource(gvr), Name: "synthetic-device", Namespace: "default", Operation: admissionv1.Delete, UserInfo: authenticationv1.UserInfo{Username: input.username, Groups: input.groups}} + namespace := &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "default"}} + if input.namespaceDeleted { + now := metav1.Now() + namespace.DeletionTimestamp = &now + } + var params runtime.Object + if input.params != nil { + params = input.params + } + results, _, err := evaluator.ForInput(context.Background(), versioned, request, plugincel.OptionalVariableBindings{VersionedParams: params}, namespace, celconfig.RuntimeCELCostBudget) + if err != nil { + t.Fatal(err) + } + if len(results) != 1 || results[0].Error != nil { + t.Fatalf("evaluation failed: %+v", results) + } + admitted, ok := results[0].EvalResult.Value().(bool) + if !ok { + t.Fatalf("expression returned %v, want a bool", results[0].EvalResult) + } + return admitted +} diff --git a/internal/api/inventory/v1alpha1/live_api_test.go b/internal/api/inventory/v1alpha1/live_api_test.go new file mode 100644 index 00000000..51afa2a7 --- /dev/null +++ b/internal/api/inventory/v1alpha1/live_api_test.go @@ -0,0 +1,151 @@ +package v1alpha1 + +import ( + "bytes" + "context" + "errors" + "io" + "os" + "path/filepath" + "testing" + "time" + + admissionregistrationv1 "k8s.io/api/admissionregistration/v1" + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime" + utilyaml "k8s.io/apimachinery/pkg/util/yaml" + "k8s.io/client-go/rest" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/envtest" +) + +// liveAPI is a disposable API server with the inventory CRDs installed, for +// tests that need admission policies or impersonated callers. +type liveAPI struct { + t *testing.T + config *rest.Config + scheme *runtime.Scheme + admin client.Client +} + +func startAPI(t *testing.T) *liveAPI { + t.Helper() + if os.Getenv("KUBEBUILDER_ASSETS") == "" { + t.Skip("KUBEBUILDER_ASSETS required for disposable API validation") + } + environment := &envtest.Environment{CRDDirectoryPaths: []string{filepath.Join(inventoryRoot, "crds")}, ErrorIfCRDPathMissing: true} + config, err := environment.Start() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if err := environment.Stop(); err != nil { + t.Error(err) + } + }) + scheme := runtime.NewScheme() + for _, add := range []func(*runtime.Scheme) error{AddToScheme, corev1.AddToScheme, admissionregistrationv1.AddToScheme} { + if err := add(scheme); err != nil { + t.Fatal(err) + } + } + admin, err := client.New(config, client.Options{Scheme: scheme}) + if err != nil { + t.Fatal(err) + } + return &liveAPI{t: t, config: config, scheme: scheme, admin: admin} +} + +// actor impersonates a caller with the given username and groups. +func (api *liveAPI) actor(name string, groups ...string) client.Client { + api.t.Helper() + config := rest.CopyConfig(api.config) + config.Impersonate = rest.ImpersonationConfig{UserName: name, UID: name + "-uid", Groups: groups} + actor, err := client.New(config, client.Options{Scheme: api.scheme}) + if err != nil { + api.t.Fatal(err) + } + return actor +} + +func (api *liveAPI) device(name, namespace, serial, uuid string) *Device { + api.t.Helper() + device := &Device{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: namespace}, Spec: DeviceSpec{ClaimRef: LocalReference{Name: "installation"}, Identity: DeviceIdentity{Model: "test", Serial: serial, SystemUUID: uuid}}} + if err := api.admin.Create(context.Background(), device); err != nil { + api.t.Fatal(err) + } + return device +} + +func (api *liveAPI) updateLifecycle(device *Device, lifecycle DeviceLifecycle) error { + api.t.Helper() + if err := api.admin.Get(context.Background(), client.ObjectKeyFromObject(device), device); err != nil { + api.t.Fatal(err) + } + device.Spec.Lifecycle = lifecycle + return api.admin.Update(context.Background(), device) +} + +func (api *liveAPI) setLifecycle(device *Device, lifecycle DeviceLifecycle) { + api.t.Helper() + if err := api.updateLifecycle(device, lifecycle); err != nil { + api.t.Fatal(err) + } +} + +// retire takes a Device through the only allowed path to Retired. +func (api *liveAPI) retire(device *Device) { + api.t.Helper() + api.setLifecycle(device, DeviceDecommissioning) + api.setLifecycle(device, DeviceRetired) +} + +// installDeletionProtection applies the optional component's manifests as a +// deploying repository that opts in would. +func (api *liveAPI) installDeletionProtection(probe *Device) { + api.t.Helper() + data, err := os.ReadFile(filepath.Join(configRoot, "components", "device-deletion-protection", "policy.yaml")) + if err != nil { + api.t.Fatal(err) + } + decoder := utilyaml.NewYAMLOrJSONDecoder(bytes.NewReader(data), 4096) + for { + var object unstructured.Unstructured + err := decoder.Decode(&object.Object) + if errors.Is(err, io.EOF) { + break + } + if err != nil { + api.t.Fatal(err) + } + if err := api.admin.Create(context.Background(), &object); err != nil { + api.t.Fatal(err) + } + } + api.eventually("Device deletion policy", func() bool { + return apierrors.IsForbidden(api.admin.Delete(context.Background(), probe, client.DryRunAll)) + }) +} + +func (api *liveAPI) eventually(what string, condition func() bool) { + api.t.Helper() + deadline := time.Now().Add(15 * time.Second) + for !condition() { + if time.Now().After(deadline) { + api.t.Fatalf("%s did not engage", what) + } + time.Sleep(50 * time.Millisecond) + } +} + +func (api *liveAPI) exists(object client.Object) bool { + api.t.Helper() + err := api.admin.Get(context.Background(), client.ObjectKeyFromObject(object), object) + if err != nil && !apierrors.IsNotFound(err) { + api.t.Fatal(err) + } + return err == nil +}