Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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
75 changes: 75 additions & 0 deletions config/components/device-deletion-protection/policy.yaml
Original file line number Diff line number Diff line change
@@ -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]
67 changes: 66 additions & 1 deletion docs/operations/physical-inventory.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down
172 changes: 171 additions & 1 deletion hack/overlay-isolation-validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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) {
Expand All @@ -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 {
Expand Down Expand Up @@ -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"
}
Expand Down
Loading
Loading