From a8a036e2b9bbb72f54bde519a2662820f0dab853 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 25 Nov 2026 09:56:24 -0600 Subject: [PATCH 1/5] feat(cleaning): Add CleaningPolicy and pin it at allocation Add the CleaningPolicy kind proposed in #183, with an immutable spec, its IAM resources and a webhook that rejects methods below a policy's assurance. The allocator copies the capacity's policy and digest into each MachineAllocation and skips capacity whose policy is missing or invalid. Each release DeviceWipe names the pinned policy. Co-Authored-By: Claude Opus 5.5 --- cmd/fleet-manager/synthetic.go | 5 - cmd/fleet-standalone-smoke/main.go | 11 - config/README.md | 9 +- config/base/crd/metal.datumapis.com.yaml | 66 +++++- .../crds/fleet.datumapis.com.yaml | 117 +++++++++- .../protected-resources/cleaningpolicy.yaml | 16 ++ .../protected-resources/kustomization.yaml | 1 + .../roles/cleaning-policy-admin.yaml | 15 ++ .../roles/installation-requester.yaml | 3 +- .../roles/kustomization.yaml | 1 + .../device-operations/roles/viewer.yaml | 3 + .../components/device-operations/webhook.yaml | 16 ++ config/standalone/fixtures.yaml | 16 ++ config/standalone/rbac.yaml | 3 + docs/development/device-custody.md | 42 +++- docs/operations/multiplane.md | 2 +- internal/allocation/allocator.go | 59 ++++-- internal/allocation/cleaning_test.go | 102 +++++++++ internal/allocation/flow_test.go | 3 +- internal/allocation/harness_test.go | 12 +- internal/allocation/release.go | 8 +- internal/allocation/release_test.go | 2 +- internal/api/operations/v1alpha1/cleaning.go | 137 ++++++++++++ .../api/operations/v1alpha1/config_test.go | 24 ++- internal/api/operations/v1alpha1/types.go | 9 +- internal/api/v1alpha1/types.go | 8 +- internal/cleaning/envtest_test.go | 89 ++++++++ internal/cleaning/policy.go | 199 ++++++++++++++++++ internal/cleaning/policy_test.go | 131 ++++++++++++ internal/cleaning/webhook.go | 36 ++++ internal/cleaning/webhook_test.go | 51 +++++ internal/coordination/transport_test.go | 2 +- internal/custody/admission_test.go | 2 +- .../custody/creatorwebhook/envtest_test.go | 10 +- internal/custody/harness_test.go | 16 +- internal/multiplane/runner.go | 6 - internal/multiplane/seed.go | 19 +- internal/registration/transport.go | 5 +- internal/site/redfishwork/kinds_test.go | 2 +- internal/site/simwork/kinds.go | 4 +- internal/site/vmwork/kinds.go | 4 +- internal/site/vmwork/kinds_test.go | 2 +- internal/staging/harness_test.go | 12 +- 43 files changed, 1181 insertions(+), 99 deletions(-) create mode 100644 config/components/device-operations/protected-resources/cleaningpolicy.yaml create mode 100644 config/components/device-operations/roles/cleaning-policy-admin.yaml create mode 100644 internal/allocation/cleaning_test.go create mode 100644 internal/api/operations/v1alpha1/cleaning.go create mode 100644 internal/cleaning/envtest_test.go create mode 100644 internal/cleaning/policy.go create mode 100644 internal/cleaning/policy_test.go create mode 100644 internal/cleaning/webhook.go create mode 100644 internal/cleaning/webhook_test.go diff --git a/cmd/fleet-manager/synthetic.go b/cmd/fleet-manager/synthetic.go index 3ad35ccd..e10c0845 100644 --- a/cmd/fleet-manager/synthetic.go +++ b/cmd/fleet-manager/synthetic.go @@ -25,10 +25,6 @@ import ( // syntheticSite is the synthetic provider: the simulator site. const syntheticSite = "synthetic-provider" -// syntheticCleaningPolicy is the fixture cleaning policy record every -// synthetic capacity names. Its digest is what each allocation pins. -const syntheticCleaningPolicy = `{"method":"overwrite","disks":"all"}` - // syntheticCustody builds the allocator, the custody coordinator loop and // fixture discovery for synthetic staging. The manager's own identity is the // Metal provider; the coordinator and the release controller authenticate @@ -89,7 +85,6 @@ func syntheticCustody(ctx context.Context, scheme *runtime.Scheme, providerConfi Provider: provider, ProviderCreator: providerCreator, Releaser: releaseClient, ReleaseCreator: releaseCreator, Custody: coordinator, Namespace: namespace, - Cleaning: func(string) (string, error) { return custody.SpecDigest(syntheticCleaningPolicy) }, // The synthetic site enrolls one boot NIC and one disk per Device. BootInterface: "primary", TargetDisks: []string{"disk-0"}, } diff --git a/cmd/fleet-standalone-smoke/main.go b/cmd/fleet-standalone-smoke/main.go index b4546881..ba1515b9 100644 --- a/cmd/fleet-standalone-smoke/main.go +++ b/cmd/fleet-standalone-smoke/main.go @@ -34,9 +34,6 @@ import ( const ( providerPrincipal = "system:serviceaccount:fleet-system:fleet-standalone-smoke" releasePrincipal = "system:serviceaccount:fleet-system:fleet-release-controller" - // cleaningPolicy is the fixture's cleaning policy record. Its digest is - // what each allocation pins. - cleaningPolicy = `{"name":"synthetic-tenant-reuse-v1","method":"overwrite","disks":"all"}` ) func main() { @@ -81,7 +78,6 @@ func main() { Releaser: releaseClient, ReleaseCreator: releaseCreator, Custody: &custody.Coordinator{Client: coordinatorClient, Registry: registry, Config: custody.Config{Namespace: options.ProviderNamespace, Principals: principals()}}, Namespace: options.ProviderNamespace, - Cleaning: fixtureCleaning, // The fixture Device's boot NIC and the simulator's one enrolled disk. BootInterface: "primary", TargetDisks: []string{"disk-0"}, } @@ -121,13 +117,6 @@ func principals() custody.Principals { return custody.Principals{custody.CreatorMetalProvider: {{Username: providerPrincipal}}, custody.CreatorReleaseController: {{Username: releasePrincipal}}} } -func fixtureCleaning(name string) (string, error) { - if name != "synthetic-tenant-reuse-v1" { - return "", fmt.Errorf("no fixture cleaning policy %q", name) - } - return custody.SpecDigest(cleaningPolicy) -} - func newClient(config *rest.Config) (client.Client, error) { scheme := runtime.NewScheme() for _, add := range []func(*runtime.Scheme) error{clientgoscheme.AddToScheme, fleetv1.AddToScheme, inventory.AddToScheme, ops.AddToScheme} { diff --git a/config/README.md b/config/README.md index b1cb911b..e909f765 100644 --- a/config/README.md +++ b/config/README.md @@ -63,10 +63,11 @@ legacy management-cluster install and will be removed. See [Planning and registering physical devices](../docs/operations/physical-inventory.md). `config/components/device-operations` registers `DeviceCustody`, the Device -operation kinds, their ProtectedResources, the coordinator, requester, viewer -and recovery operator roles, and the creator webhook. `config/milo` includes all -of it, and the `fleet-registration` server serves the webhook at -`/validate-operation-creator`. `config/milo-synthetic` includes the kinds, +operation kinds, `CleaningPolicy`, their ProtectedResources, the coordinator, +requester, viewer, recovery operator and cleaning policy admin roles, and the +creator and cleaning policy webhooks. `config/milo` includes all of it, and the +`fleet-registration` server serves the webhooks at +`/validate-operation-creator` and `/validate-cleaning-policy`. `config/milo-synthetic` includes the kinds, ProtectedResources and roles without the webhook, because it installs no registration webhook. `config/standalone` includes only the CRDs and enforces the creator rule with a ValidatingAdmissionPolicy. Including the kinds installs no diff --git a/config/base/crd/metal.datumapis.com.yaml b/config/base/crd/metal.datumapis.com.yaml index 481cb14b..ef63f080 100644 --- a/config/base/crd/metal.datumapis.com.yaml +++ b/config/base/crd/metal.datumapis.com.yaml @@ -364,7 +364,7 @@ spec: metadata: {type: object} spec: type: object - required: [consumerRef, machineRef, machineCapacityRef, deviceRef, accepted, hardware, authority, cleaningPolicyDigest, bootInterface, targetDisks] + required: [consumerRef, machineRef, machineCapacityRef, deviceRef, accepted, hardware, authority, cleaningPolicy, bootInterface, targetDisks] x-kubernetes-validations: - {rule: 'self == oldSelf', message: MachineAllocation identity and endpoints are immutable} properties: @@ -438,7 +438,69 @@ spec: required: [name] properties: name: {type: string, minLength: 1} - cleaningPolicyDigest: {type: string, pattern: '^sha256:[a-f0-9]{64}$'} + cleaningPolicy: + type: object + required: [name, uid, digest, spec] + properties: + name: {type: string, minLength: 1, maxLength: 253} + uid: {type: string, minLength: 1, maxLength: 64} + digest: {type: string, pattern: '^sha256:[a-f0-9]{64}$'} + spec: + type: object + required: [assurance, rules] + properties: + assurance: {type: string, enum: [Clear, Purge]} + rules: + type: array + minItems: 1 + maxItems: 16 + x-kubernetes-list-type: map + x-kubernetes-list-map-keys: [name] + items: + type: object + required: [name, match, methods, verify, timePerTiB] + properties: + name: {type: string, minLength: 1, maxLength: 63} + match: + type: object + required: [protocol, mediaType] + properties: + protocol: {type: string, enum: [NVMe, SATA, SAS]} + mediaType: {type: string, enum: [SSD, HDD]} + methods: + type: array + minItems: 1 + maxItems: 6 + x-kubernetes-list-type: set + items: {type: string, enum: [CryptographicErase, BlockErase, SanitizeOverwrite, Format, SecureErase, Overwrite]} + verify: + type: object + required: [mode] + properties: + mode: {type: string, enum: [Full, Canary]} + samples: {type: integer, format: int32, minimum: 0, maximum: 1024} + timePerTiB: {type: string, minLength: 1, maxLength: 32} + qualified: + type: array + maxItems: 32 + items: + type: object + required: [model, firmware, methods] + properties: + model: {type: string, minLength: 1, maxLength: 128} + firmware: + type: array + minItems: 1 + maxItems: 16 + x-kubernetes-list-type: set + items: {type: string, minLength: 1, maxLength: 64} + methods: + type: array + minItems: 1 + maxItems: 6 + x-kubernetes-list-type: set + items: {type: string, enum: [CryptographicErase, BlockErase, SanitizeOverwrite, Format, SecureErase, Overwrite]} + alwaysEncrypts: {type: boolean} bootInterface: {type: string, minLength: 1, maxLength: 63} targetDisks: type: array diff --git a/config/components/device-operations/crds/fleet.datumapis.com.yaml b/config/components/device-operations/crds/fleet.datumapis.com.yaml index 42fc7e92..c5870657 100644 --- a/config/components/device-operations/crds/fleet.datumapis.com.yaml +++ b/config/components/device-operations/crds/fleet.datumapis.com.yaml @@ -705,9 +705,24 @@ spec: type: integer format: int32 minimum: 1 - cleaningPolicyDigest: - type: string - pattern: ^sha256:[0-9a-f]{64}$ + policy: + type: object + properties: + name: + type: string + minLength: 1 + maxLength: 253 + uid: + type: string + minLength: 1 + maxLength: 64 + digest: + type: string + pattern: ^sha256:[0-9a-f]{64}$ + required: + - name + - uid + - digest targetDisks: type: array minItems: 1 @@ -722,7 +737,7 @@ spec: - deviceRef - authority - step - - cleaningPolicyDigest + - policy - targetDisks x-kubernetes-validations: - rule: self == oldSelf @@ -1077,3 +1092,97 @@ spec: message: operation phases move forward only, and an ended phase is final required: - spec +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: cleaningpolicies.fleet.datumapis.com + annotations: + discovery.miloapis.com/parent-contexts: Project +spec: + group: fleet.datumapis.com + names: + kind: CleaningPolicy + listKind: CleaningPolicyList + plural: cleaningpolicies + singular: cleaningpolicy + scope: Namespaced + versions: + - name: v1alpha1 + served: true + storage: true + additionalPrinterColumns: + - name: Assurance + type: string + jsonPath: .spec.assurance + schema: + openAPIV3Schema: + type: object + properties: + apiVersion: + type: string + kind: + type: string + metadata: + type: object + spec: + type: object + required: [assurance, rules] + properties: + assurance: {type: string, enum: [Clear, Purge]} + rules: + type: array + minItems: 1 + maxItems: 16 + x-kubernetes-list-type: map + x-kubernetes-list-map-keys: [name] + items: + type: object + required: [name, match, methods, verify, timePerTiB] + properties: + name: {type: string, minLength: 1, maxLength: 63} + match: + type: object + required: [protocol, mediaType] + properties: + protocol: {type: string, enum: [NVMe, SATA, SAS]} + mediaType: {type: string, enum: [SSD, HDD]} + methods: + type: array + minItems: 1 + maxItems: 6 + x-kubernetes-list-type: set + items: {type: string, enum: [CryptographicErase, BlockErase, SanitizeOverwrite, Format, SecureErase, Overwrite]} + verify: + type: object + required: [mode] + properties: + mode: {type: string, enum: [Full, Canary]} + samples: {type: integer, format: int32, minimum: 0, maximum: 1024} + timePerTiB: {type: string, minLength: 1, maxLength: 32} + qualified: + type: array + maxItems: 32 + items: + type: object + required: [model, firmware, methods] + properties: + model: {type: string, minLength: 1, maxLength: 128} + firmware: + type: array + minItems: 1 + maxItems: 16 + x-kubernetes-list-type: set + items: {type: string, minLength: 1, maxLength: 64} + methods: + type: array + minItems: 1 + maxItems: 6 + x-kubernetes-list-type: set + items: {type: string, enum: [CryptographicErase, BlockErase, SanitizeOverwrite, Format, SecureErase, Overwrite]} + alwaysEncrypts: {type: boolean} + x-kubernetes-validations: + - rule: self == oldSelf + message: a CleaningPolicy spec is immutable; create a new policy instead + required: + - spec diff --git a/config/components/device-operations/protected-resources/cleaningpolicy.yaml b/config/components/device-operations/protected-resources/cleaningpolicy.yaml new file mode 100644 index 00000000..6ccd1417 --- /dev/null +++ b/config/components/device-operations/protected-resources/cleaningpolicy.yaml @@ -0,0 +1,16 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: fleet.datumapis.com-cleaningpolicy +spec: + serviceRef: + name: fleet.datumapis.com + kind: CleaningPolicy + plural: cleaningpolicies + singular: cleaningpolicy + # The spec is immutable, so no role needs update or patch. A changed + # policy is a new policy. + permissions: [list, get, watch, create, update, patch, delete] + parentResources: + - apiGroup: resourcemanager.miloapis.com + kind: Project diff --git a/config/components/device-operations/protected-resources/kustomization.yaml b/config/components/device-operations/protected-resources/kustomization.yaml index 7b5e6674..38c39957 100644 --- a/config/components/device-operations/protected-resources/kustomization.yaml +++ b/config/components/device-operations/protected-resources/kustomization.yaml @@ -5,3 +5,4 @@ resources: - deviceinstallation.yaml - devicewipe.yaml - devicerecovery.yaml + - cleaningpolicy.yaml diff --git a/config/components/device-operations/roles/cleaning-policy-admin.yaml b/config/components/device-operations/roles/cleaning-policy-admin.yaml new file mode 100644 index 00000000..ec48a121 --- /dev/null +++ b/config/components/device-operations/roles/cleaning-policy-admin.yaml @@ -0,0 +1,15 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: Role +metadata: + name: fleet.datumapis.com-cleaning-policy-admin + annotations: + kubernetes.io/display-name: Fleet Cleaning Policy Admin + kubernetes.io/description: Provider operators. Create and delete CleaningPolicies, which say how Fleet cleans a server between customers. A policy cannot be changed after creation. +spec: + launchStage: Alpha + includedPermissions: + - fleet.datumapis.com/cleaningpolicies.create + - fleet.datumapis.com/cleaningpolicies.get + - fleet.datumapis.com/cleaningpolicies.list + - fleet.datumapis.com/cleaningpolicies.watch + - fleet.datumapis.com/cleaningpolicies.delete diff --git a/config/components/device-operations/roles/installation-requester.yaml b/config/components/device-operations/roles/installation-requester.yaml index 1131652a..1bb0c5f6 100644 --- a/config/components/device-operations/roles/installation-requester.yaml +++ b/config/components/device-operations/roles/installation-requester.yaml @@ -4,7 +4,7 @@ metadata: name: fleet.datumapis.com-device-installation-requester annotations: kubernetes.io/display-name: Fleet Device Installation Requester - kubernetes.io/description: The Fleet provider for Metal. Creates DeviceInstallations from Installations and reads custody. + kubernetes.io/description: The Fleet provider for Metal. Creates DeviceInstallations from Installations, reads custody, and reads the CleaningPolicy each allocation pins. spec: launchStage: Alpha includedPermissions: @@ -15,3 +15,4 @@ spec: - fleet.datumapis.com/devicecustodies.get - fleet.datumapis.com/devicecustodies.list - fleet.datumapis.com/devicecustodies.watch + - fleet.datumapis.com/cleaningpolicies.get diff --git a/config/components/device-operations/roles/kustomization.yaml b/config/components/device-operations/roles/kustomization.yaml index 0deb9bd5..3117a656 100644 --- a/config/components/device-operations/roles/kustomization.yaml +++ b/config/components/device-operations/roles/kustomization.yaml @@ -6,3 +6,4 @@ resources: - recovery-operator.yaml - installation-requester.yaml - wipe-requester.yaml + - cleaning-policy-admin.yaml diff --git a/config/components/device-operations/roles/viewer.yaml b/config/components/device-operations/roles/viewer.yaml index 7a1e5100..b2b5dbb0 100644 --- a/config/components/device-operations/roles/viewer.yaml +++ b/config/components/device-operations/roles/viewer.yaml @@ -20,3 +20,6 @@ spec: - fleet.datumapis.com/devicerecoveries.get - fleet.datumapis.com/devicerecoveries.list - fleet.datumapis.com/devicerecoveries.watch + - fleet.datumapis.com/cleaningpolicies.get + - fleet.datumapis.com/cleaningpolicies.list + - fleet.datumapis.com/cleaningpolicies.watch diff --git a/config/components/device-operations/webhook.yaml b/config/components/device-operations/webhook.yaml index 3958a845..8e6a43e4 100644 --- a/config/components/device-operations/webhook.yaml +++ b/config/components/device-operations/webhook.yaml @@ -22,3 +22,19 @@ webhooks: operations: [CREATE, UPDATE] resources: [deviceinstallations, devicewipes, devicerecoveries] scope: Namespaced + # Rejects a CleaningPolicy whose methods cannot reach its assurance, or + # that does not fit its drives. The CRD keeps the spec immutable. + - name: cleaningpolicies.fleet.datumapis.com + admissionReviewVersions: [v1] + failurePolicy: Fail + matchPolicy: Equivalent + sideEffects: None + timeoutSeconds: 10 + clientConfig: + url: https://fleet-registration.fleet-system.svc:9443/validate-cleaning-policy + rules: + - apiGroups: [fleet.datumapis.com] + apiVersions: [v1alpha1] + operations: [CREATE, UPDATE] + resources: [cleaningpolicies] + scope: Namespaced diff --git a/config/standalone/fixtures.yaml b/config/standalone/fixtures.yaml index d4f0d938..73a3938b 100644 --- a/config/standalone/fixtures.yaml +++ b/config/standalone/fixtures.yaml @@ -29,6 +29,22 @@ spec: bmc: {endpoint: "https://[2001:db8::21]"} interfaces: [{name: primary, macAddress: "02:00:00:00:00:21"}] --- +# The synthetic site overwrites its one disk and reads it back, so the +# fixture policy claims only Clear. +apiVersion: fleet.datumapis.com/v1alpha1 +kind: CleaningPolicy +metadata: + name: synthetic-tenant-reuse-v1 + namespace: fleet-provider +spec: + assurance: Clear + rules: + - name: nvme-ssd + match: {protocol: NVMe, mediaType: SSD} + methods: [Overwrite] + verify: {mode: Full} + timePerTiB: 1h +--- apiVersion: metal.datumapis.com/v1alpha1 kind: MachineCapacity metadata: diff --git a/config/standalone/rbac.yaml b/config/standalone/rbac.yaml index 3c5e477b..4e8baf66 100644 --- a/config/standalone/rbac.yaml +++ b/config/standalone/rbac.yaml @@ -46,6 +46,9 @@ rules: - apiGroups: [metal.datumapis.com] resources: [machineallocations/status] verbs: [get, update] + - apiGroups: [fleet.datumapis.com] + resources: [cleaningpolicies] + verbs: [get] - apiGroups: [fleet.datumapis.com] resources: [deviceinstallations] verbs: [get, list, create] diff --git a/docs/development/device-custody.md b/docs/development/device-custody.md index 9e7cd13d..22e2d356 100644 --- a/docs/development/device-custody.md +++ b/docs/development/device-custody.md @@ -180,8 +180,8 @@ provider project, and only the Metal provider writes it. - **Spec (immutable).** The consumer as a typed reference, the Machine by namespace and name, the capacity, the Device by name, the accepted class and profile pinned by generation and spec digest, the CPU and memory, the hardware snapshot, the - admission authority, an optional quota claim, the pinned cleaning policy - digest, the boot interface and the target disks. + admission authority, an optional quota claim, a copy of the capacity's + `CleaningPolicy` with its name, UID and digest, the boot interface and the target disks. - **Labels.** `fleet.datumapis.com/machine-uid`, `fleet.datumapis.com/consumer-uid` and `fleet.datumapis.com/device-uid` record the incarnations the allocation was @@ -638,10 +638,7 @@ remains. - **Boot interface (O12).** `bootInterface` resolves by name against the Device's interfaces, and the snapshot records its MAC. Target disks stay a site-local enrollment fact that the worker checks (Increment B). -- **Cleaning policy (O11).** `DeviceWipe` requires the digest of the cleaning - policy record pinned at allocation. A resolver maps the capacity's cleaning - policy reference to that digest when the allocator creates the allocation. The - standalone, staging and multi-plane modes supply a fixture resolver. +- **Cleaning policy (O11).** See [Cleaning policies](#cleaning-policies). - **Capacity (O1).** The projector stays a pure function. `Prepared` needs a succeeded commissioning under the current plan, `Healthy` needs current commissioning and discovery evidence, and `Available` also needs `Verified` @@ -687,6 +684,39 @@ an object UID: `..`, with the name replaced by its digest if the key would exceed the site store's 128-character limit. A same-name operation admitted later has a higher fence and so another key. +### Cleaning policies + +This section records how Fleet implements the [cleaning +proposal](https://github.com/datum-cloud/fleet/pull/183) (#183). The first +increment is **implemented and verified** with unit tests and tests against a +real API server. The rest of #183 is **proposed**. + +- **Kind.** `CleaningPolicy` in `fleet.datumapis.com`, served only in provider + project control planes, with its ProtectedResource and a + `cleaning-policy-admin` role that can create and delete but not update. The + viewer role reads policies, and the Metal provider role can get one. The CRD + keeps the spec immutable. +- **Validation.** `internal/cleaning` rejects a policy whose methods cannot + reach its assurance, that applies a method to the wrong protocol, that uses a + check a method does not allow, or that qualifies `CryptographicErase` for a + model that does not always encrypt. The `fleet-registration` server serves it + as a webhook at `/validate-cleaning-policy` in `config/milo`. The synthetic + Milo root and the standalone cluster have no such webhook. +- **Pinning.** The allocator reads the capacity's policy, validates it again, + and copies its name, UID, SHA-256 digest and spec into the MachineAllocation. + Capacity whose policy is missing or invalid is skipped, and nothing is + claimed. Each release `DeviceWipe` names the pinned policy, so release does + not need the policy to exist. +- **Fixtures.** The standalone fixtures and the multi-plane seed create a + `Clear` policy that overwrites and reads back, the only method the sites run. + Synthetic staging has no fixture: an operator must create the policy that its + capacity names before that capacity can be allocated. + +Not implemented yet: drive inventory from Redfish and commissioning, the media +manifest and pinned drive names, the per-drive plan in `DeviceWipe`, the +in-band methods and their evidence, the evidence check and its reasons, and +`DisposeDrive`. Until then, every site still wipes its one enrolled disk. + ### Cutover decisions Each decision was made while building Increment C. Each is open for review by a diff --git a/docs/operations/multiplane.md b/docs/operations/multiplane.md index 7bcdfe81..29672e99 100644 --- a/docs/operations/multiplane.md +++ b/docs/operations/multiplane.md @@ -465,7 +465,7 @@ cell RoleBinding, verify denial, and restore that exact binding. These tests establish Kubernetes RBAC behavior, not caller-preserving production Milo IAM. The local runner's catalog, publication, hardware observations, source-use -admission and fixture cleaning policy are explicit synthetic fixtures, and no +admission and `Clear` cleaning policy are explicit synthetic fixtures, and no quota system serves the run. The MachineAllocation, custody and operation records are durable before effects. Networking is deliberately empty; no NSO/IPAM/routing implementation is substituted. Adoption and production service readiness are never diff --git a/internal/allocation/allocator.go b/internal/allocation/allocator.go index 9285255d..3a8ae630 100644 --- a/internal/allocation/allocator.go +++ b/internal/allocation/allocator.go @@ -30,6 +30,7 @@ import ( inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" ops "go.datum.net/fleet/internal/api/operations/v1alpha1" fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/cleaning" "go.datum.net/fleet/internal/custody" "go.datum.net/fleet/internal/tenancy" ) @@ -49,6 +50,9 @@ var ( // ErrUnsupported means a request Fleet does not implement, such as a // bootstrap payload. ErrUnsupported = errors.New("unsupported request") + // ErrCleaningUncovered means the capacity names no CleaningPolicy, or + // one that does not exist or is not valid. + ErrCleaningUncovered = errors.New("no usable cleaning policy covers the capacity") ) // Machine names one Machine incarnation in one consumer incarnation. @@ -100,10 +104,6 @@ type Quota interface { Release(ctx context.Context, machine Machine) error } -// CleaningPolicies resolves a MachineCapacity's cleaning policy reference -// to the digest of the policy record pinned at allocation. -type CleaningPolicies func(name string) (string, error) - // Request is one Machine's allocation request, already admitted. type Request struct { Machine Machine @@ -128,7 +128,6 @@ type Allocator struct { // in it too. Namespace string Quota Quota - Cleaning CleaningPolicies // BootInterface and TargetDisks are pinned on each allocation. BootInterface string TargetDisks []string @@ -195,7 +194,12 @@ func (a *Allocator) Allocate(ctx context.Context, request Request) (*fleetv1.Mac return nil, err } tried[candidate.Name] = true - allocation, err = a.newAllocation(request, candidate, device, claim) + allocation, err = a.newAllocation(ctx, request, candidate, device, claim) + if errors.Is(err, ErrCleaningUncovered) { + // Capacity without a usable cleaning policy is not eligible. + // Nothing was claimed; try the next candidate. + continue + } if err != nil { return nil, err } @@ -292,13 +296,10 @@ func Free(state *ops.DeviceCustody, device *inventory.Device) bool { spec.RecoveryHold == nil && spec.ActiveOperation == nil && inventory.LifecycleOf(device) == inventory.DeviceActive } -func (a *Allocator) newAllocation(request Request, capacity *fleetv1.MachineCapacity, device *inventory.Device, claim string) (*fleetv1.MachineAllocation, error) { - if a.Cleaning == nil { - return nil, errors.New("allocation: no cleaning policy resolver") - } - digest, err := a.Cleaning(capacity.Spec.CleaningPolicyRef.Name) +func (a *Allocator) newAllocation(ctx context.Context, request Request, capacity *fleetv1.MachineCapacity, device *inventory.Device, claim string) (*fleetv1.MachineAllocation, error) { + policy, err := a.pinCleaning(ctx, capacity) if err != nil { - return nil, fmt.Errorf("resolve cleaning policy: %w", err) + return nil, err } classDigest, err := custody.SpecDigest(request.Class.Spec) if err != nil { @@ -323,11 +324,11 @@ func (a *Allocator) newAllocation(request Request, capacity *fleetv1.MachineCapa CPU: request.Profile.Spec.CPU, Memory: request.Profile.Spec.Memory, }, - Hardware: capacity.Status.Hardware, - Authority: request.Authority, - CleaningPolicyDigest: digest, - BootInterface: a.BootInterface, - TargetDisks: slices.Clone(a.TargetDisks), + Hardware: capacity.Status.Hardware, + Authority: request.Authority, + CleaningPolicy: policy, + BootInterface: a.BootInterface, + TargetDisks: slices.Clone(a.TargetDisks), }, } if claim != "" { @@ -456,3 +457,27 @@ func specDigest(operation ops.Operation) (string, error) { sum := sha256.Sum256(object.Spec) return hex.EncodeToString(sum[:]), nil } + +// pinCleaning copies the capacity's CleaningPolicy for the allocation to +// keep. A policy that is missing or invalid refuses the allocation. +func (a *Allocator) pinCleaning(ctx context.Context, capacity *fleetv1.MachineCapacity) (ops.PinnedCleaningPolicy, error) { + name := capacity.Spec.CleaningPolicyRef.Name + if name == "" { + return ops.PinnedCleaningPolicy{}, fmt.Errorf("%w: capacity %s names no cleaning policy", ErrCleaningUncovered, capacity.Name) + } + policy := &ops.CleaningPolicy{} + if err := a.Provider.Get(ctx, client.ObjectKey{Namespace: capacity.Namespace, Name: name}, policy); err != nil { + if apierrors.IsNotFound(err) { + return ops.PinnedCleaningPolicy{}, fmt.Errorf("%w: cleaning policy %s does not exist", ErrCleaningUncovered, name) + } + return ops.PinnedCleaningPolicy{}, err + } + if err := cleaning.Validate(policy.Spec); err != nil { + return ops.PinnedCleaningPolicy{}, fmt.Errorf("%w: cleaning policy %s: %v", ErrCleaningUncovered, name, err) + } + digest, err := cleaning.Digest(policy.Spec) + if err != nil { + return ops.PinnedCleaningPolicy{}, err + } + return ops.PinnedCleaningPolicy{CleaningPolicyReference: ops.CleaningPolicyReference{Name: policy.Name, UID: string(policy.UID), Digest: digest}, Spec: policy.Spec}, nil +} diff --git a/internal/allocation/cleaning_test.go b/internal/allocation/cleaning_test.go new file mode 100644 index 00000000..bcf1e4ab --- /dev/null +++ b/internal/allocation/cleaning_test.go @@ -0,0 +1,102 @@ +package allocation + +import ( + "errors" + "testing" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + "sigs.k8s.io/controller-runtime/pkg/client" + + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + "go.datum.net/fleet/internal/cleaning" + "go.datum.net/fleet/internal/custody" +) + +func (e *env) policy() *ops.CleaningPolicy { + e.t.Helper() + policy := &ops.CleaningPolicy{} + if err := e.admin.Get(e.ctx, client.ObjectKey{Namespace: namespace, Name: "example-cleaning"}, policy); err != nil { + e.t.Fatal(err) + } + return policy +} + +// TestAllocationPinsItsCleaningPolicy pins a copy of the capacity's policy +// and its digest, keeps it when the policy is deleted, and wipes under it. +func TestAllocationPinsItsCleaningPolicy(t *testing.T) { + e := startEnv(t) + e.server(1) + policy := e.policy() + + allocation, err := e.allocator.Allocate(e.ctx, e.request(1)) + if err != nil { + t.Fatal(err) + } + digest, err := cleaning.Digest(policy.Spec) + if err != nil { + t.Fatal(err) + } + pinned := allocation.Spec.CleaningPolicy + if pinned.Name != policy.Name || pinned.UID != string(policy.UID) || pinned.Digest != digest || pinned.Spec.Rules[0].Name != "nvme-ssd" { + t.Fatalf("pinned = %+v", pinned) + } + + // The spec cannot change, so a pinned digest always names what a + // provider can still read. + changed := policy.DeepCopyObject().(*ops.CleaningPolicy) + changed.Spec.Assurance = ops.AssurancePurge + if err := e.admin.Update(e.ctx, changed); !apierrors.IsInvalid(err) { + t.Fatalf("updating a policy spec = %v, want Invalid", err) + } + + // Release does not need the policy to exist. + if err := e.admin.Delete(e.ctx, policy); err != nil { + t.Fatal(err) + } + e.release(allocation, machine(1)) + wipe := &ops.DeviceWipe{} + if err := e.admin.Get(e.ctx, client.ObjectKey{Namespace: namespace, Name: custody.WipeName(allocation.Name, 1)}, wipe); err != nil { + t.Fatal(err) + } + if wipe.Spec.Policy != pinned.CleaningPolicyReference { + t.Fatalf("wipe policy = %+v, want %+v", wipe.Spec.Policy, pinned.CleaningPolicyReference) + } +} + +// TestCapacityWithoutAUsableCleaningPolicyIsNotAllocated skips capacity +// whose policy is missing or invalid, and claims nothing. +func TestCapacityWithoutAUsableCleaningPolicyIsNotAllocated(t *testing.T) { + cases := map[string]func(e *env){ + "missing policy": func(e *env) { + if err := e.admin.Delete(e.ctx, e.policy()); err != nil { + e.t.Fatal(err) + } + }, + "invalid policy": func(e *env) { + if err := e.admin.Delete(e.ctx, e.policy()); err != nil { + e.t.Fatal(err) + } + // The CRD admits it; only the webhook, absent here, would refuse + // Overwrite with Canary. The allocator checks again at pin time. + invalid := examplePolicy(namespace) + invalid.Spec.Rules[0].Verify = ops.VerifySpec{Mode: ops.VerifyCanary, Samples: 64} + e.create(invalid) + }, + } + for name, setup := range cases { + t.Run(name, func(t *testing.T) { + e := startEnv(t) + device := e.server(1) + setup(e) + if _, err := e.allocator.Allocate(e.ctx, e.request(1)); !errors.Is(err, ErrInsufficientCapacity) { + t.Fatalf("allocate = %v, want ErrInsufficientCapacity", err) + } + if found, err := e.allocator.Get(e.ctx, machine(1)); err != nil || found != nil { + t.Fatalf("allocation = %v, %v", found, err) + } + if holder := e.custody(device.Name).Spec.Holder.Type; holder != ops.HolderNone { + t.Fatalf("holder = %s, want None", holder) + } + }) + } +} diff --git a/internal/allocation/flow_test.go b/internal/allocation/flow_test.go index bd2815ec..c3cf34d2 100644 --- a/internal/allocation/flow_test.go +++ b/internal/allocation/flow_test.go @@ -1,6 +1,7 @@ package allocation import ( + "context" "errors" "sync" "testing" @@ -161,7 +162,7 @@ func TestAnAllocationThatLostItsDeviceIsReplaced(t *testing.T) { } // A crash left the second Machine's allocation naming the taken Device, // before it claimed custody. - stale, err := e.allocator.newAllocation(e.request(2), e.capacity(taken.Name), taken, "") + stale, err := e.allocator.newAllocation(context.Background(), e.request(2), e.capacity(taken.Name), taken, "") if err != nil { t.Fatal(err) } diff --git a/internal/allocation/harness_test.go b/internal/allocation/harness_test.go index 0079bf7e..b64a23f5 100644 --- a/internal/allocation/harness_test.go +++ b/internal/allocation/harness_test.go @@ -38,7 +38,6 @@ const ( siteToken = "synthetic-site-token" keyDigest = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" imageRef = "debian-12@sha256:9f4ad8d8b8a6f6fc64d2cf2c7e70b9184b74f089adf8c36d84f4fcb99892f3cb" - policyDigest = "sha256:0c2b77e1d9a4000000000000000000000000000000000000000000000000cafe" ) func uid(n int) string { return fmt.Sprintf("00000000-0000-4000-8000-%012d", n) } @@ -124,11 +123,11 @@ func startEnv(t *testing.T) *env { Provider: admin, ProviderCreator: ops.Creator{Username: providerUser, UID: uid(801)}, Releaser: admin, ReleaseCreator: ops.Creator{Username: releaseUser, UID: uid(802)}, Custody: coordinator, Namespace: namespace, - Cleaning: func(string) (string, error) { return policyDigest, nil }, BootInterface: "primary", TargetDisks: []string{"disk-0"}, } e.class = &fleetv1.MachineClass{ObjectMeta: metav1.ObjectMeta{Name: "class-example"}, Spec: fleetv1.MachineClassSpec{ProfilePolicy: &fleetv1.ProfilePolicy{AllowedProfiles: []fleetv1.LocalReference{{Name: "profile-example"}}}, Capacity: &fleetv1.CapacityPolicy{MachineCapacities: fleetv1.MachineSelector{Namespace: namespace, Selector: metav1.LabelSelector{MatchLabels: map[string]string{"pool": "example"}}}}}} e.create(e.class) + e.create(examplePolicy(namespace)) e.profile = &fleetv1.MachineProfile{ObjectMeta: metav1.ObjectMeta{Name: "profile-example"}, Spec: fleetv1.MachineProfileSpec{CPU: fleetv1.CPURequirement{Architecture: "amd64", Cores: 2}, Memory: fleetv1.MemoryRequirement{Capacity: "2Gi"}}} e.create(e.profile) return e @@ -231,3 +230,12 @@ func (e *env) release(allocation *fleetv1.MachineAllocation, owner Machine) { return released }) } + +// examplePolicy is the CleaningPolicy every fixture capacity names. +func examplePolicy(namespace string) *ops.CleaningPolicy { + return &ops.CleaningPolicy{ObjectMeta: metav1.ObjectMeta{Name: "example-cleaning", Namespace: namespace}, Spec: ops.CleaningPolicySpec{ + Assurance: ops.AssuranceClear, + Rules: []ops.CleaningRule{{Name: "nvme-ssd", Match: ops.DriveMatch{Protocol: ops.ProtocolNVMe, MediaType: ops.MediaSSD}, + Methods: []ops.CleaningMethod{ops.MethodOverwrite}, Verify: ops.VerifySpec{Mode: ops.VerifyFull}, TimePerTiB: metav1.Duration{Duration: time.Hour}}}, + }} +} diff --git a/internal/allocation/release.go b/internal/allocation/release.go index 7b60b25f..34e66039 100644 --- a/internal/allocation/release.go +++ b/internal/allocation/release.go @@ -178,10 +178,10 @@ func (a *Allocator) wipe(ctx context.Context, allocation *fleetv1.MachineAllocat wipe := &ops.DeviceWipe{ ObjectMeta: metav1.ObjectMeta{Name: reference.Name, Namespace: a.Namespace, Labels: operationLabels(allocation)}, Spec: ops.DeviceWipeSpec{ - OperationEnvelope: a.envelope(allocation, a.ReleaseCreator), - Step: reference.Step, - CleaningPolicyDigest: allocation.Spec.CleaningPolicyDigest, - TargetDisks: slices.Clone(allocation.Spec.TargetDisks), + OperationEnvelope: a.envelope(allocation, a.ReleaseCreator), + Step: reference.Step, + Policy: allocation.Spec.CleaningPolicy.CleaningPolicyReference, + TargetDisks: slices.Clone(allocation.Spec.TargetDisks), }, } return a.createOnce(ctx, a.Releaser, wipe, &ops.DeviceWipe{}) diff --git a/internal/allocation/release_test.go b/internal/allocation/release_test.go index 018fee80..04d32fc1 100644 --- a/internal/allocation/release_test.go +++ b/internal/allocation/release_test.go @@ -72,7 +72,7 @@ func TestAnAllocationThatNeverHeldItsDeviceIsReleased(t *testing.T) { if _, err := q.Acquire(e.ctx, machine(1)); err != nil { t.Fatal(err) } - orphan, err := e.allocator.newAllocation(e.request(1), e.capacity(device.Name), device, "fleet-machine-601") + orphan, err := e.allocator.newAllocation(context.Background(), e.request(1), e.capacity(device.Name), device, "fleet-machine-601") if err != nil { t.Fatal(err) } diff --git a/internal/api/operations/v1alpha1/cleaning.go b/internal/api/operations/v1alpha1/cleaning.go new file mode 100644 index 00000000..c210ae03 --- /dev/null +++ b/internal/api/operations/v1alpha1/cleaning.go @@ -0,0 +1,137 @@ +package v1alpha1 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" +) + +// CleaningPolicy says how Fleet cleans each drive of a server before another +// customer can use it, what each step must prove, and what assurance the +// policy claims, as proposed in datum-cloud/fleet#183. Provider operators +// own it. Its spec is immutable: a changed policy is a new policy, and every +// allocation keeps the copy it pinned. +type CleaningPolicy struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + Spec CleaningPolicySpec `json:"spec"` +} + +// Assurance is how thoroughly a method removes data, in the NIST SP 800-88 +// and IEEE 2883 sense. Fleet makes no certification claim. +type Assurance string + +const ( + AssuranceClear Assurance = "Clear" + AssurancePurge Assurance = "Purge" +) + +// Reaches reports whether a meets the required assurance. +func (a Assurance) Reaches(required Assurance) bool { + return a == AssurancePurge || (a == AssuranceClear && required == AssuranceClear) +} + +type DriveProtocol string + +const ( + ProtocolNVMe DriveProtocol = "NVMe" + ProtocolSATA DriveProtocol = "SATA" + ProtocolSAS DriveProtocol = "SAS" +) + +type MediaType string + +const ( + MediaSSD MediaType = "SSD" + MediaHDD MediaType = "HDD" +) + +// CleaningMethod is one way to erase a drive. Its assurance is fixed. +type CleaningMethod string + +const ( + MethodCryptographicErase CleaningMethod = "CryptographicErase" + MethodBlockErase CleaningMethod = "BlockErase" + MethodSanitizeOverwrite CleaningMethod = "SanitizeOverwrite" + MethodFormat CleaningMethod = "Format" + MethodSecureErase CleaningMethod = "SecureErase" + MethodOverwrite CleaningMethod = "Overwrite" +) + +type VerifyMode string + +const ( + // VerifyFull reads every block back and compares it with the pattern. + VerifyFull VerifyMode = "Full" + // VerifyCanary writes random markers to sampled ranges before the erase + // and requires that none remain after it. + VerifyCanary VerifyMode = "Canary" +) + +type CleaningPolicySpec struct { + // Assurance is what every drive must reach. + Assurance Assurance `json:"assurance"` + // Rules are matched in order. The first rule that matches a drive applies. + Rules []CleaningRule `json:"rules"` + // Qualified lists the drive models and firmware that passed hardware + // qualification, and the methods each passed. A Purge method runs on a + // drive only when its model, firmware and that method are listed. + Qualified []QualifiedModel `json:"qualified,omitempty"` +} + +type CleaningRule struct { + Name string `json:"name"` + Match DriveMatch `json:"match"` + // Methods are tried in order. Fleet plans only the methods qualified for + // the drive. + Methods []CleaningMethod `json:"methods"` + Verify VerifySpec `json:"verify"` + // TimePerTiB bounds how long each method may take per TiB of capacity. + // The wipe's deadline is derived from it. + TimePerTiB metav1.Duration `json:"timePerTiB"` +} + +// DriveMatch selects drives by protocol and media type. +type DriveMatch struct { + Protocol DriveProtocol `json:"protocol"` + MediaType MediaType `json:"mediaType"` +} + +// QualifiedModel is one drive model's hardware qualification. +type QualifiedModel struct { + Model string `json:"model"` + Firmware []string `json:"firmware"` + Methods []CleaningMethod `json:"methods"` + // AlwaysEncrypts says the model encrypts all user data and cannot turn + // encryption off. CryptographicErase needs it. + AlwaysEncrypts bool `json:"alwaysEncrypts,omitempty"` +} + +type VerifySpec struct { + Mode VerifyMode `json:"mode"` + // Samples is the number of canary ranges. Canary only. + Samples int32 `json:"samples,omitempty"` +} + +// CleaningPolicyReference names one CleaningPolicy incarnation and the digest +// of its spec. +type CleaningPolicyReference struct { + Name string `json:"name"` + UID string `json:"uid"` + Digest string `json:"digest"` +} + +// PinnedCleaningPolicy is the copy of a CleaningPolicy an allocation keeps, +// so its release does not depend on the policy still existing. +type PinnedCleaningPolicy struct { + CleaningPolicyReference `json:",inline"` + Spec CleaningPolicySpec `json:"spec"` +} + +type CleaningPolicyList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []CleaningPolicy `json:"items"` +} + +func (in *CleaningPolicy) DeepCopyObject() runtime.Object { return deepCopy(in) } +func (in *CleaningPolicyList) DeepCopyObject() runtime.Object { return deepCopy(in) } diff --git a/internal/api/operations/v1alpha1/config_test.go b/internal/api/operations/v1alpha1/config_test.go index 815171f7..a74dbded 100644 --- a/internal/api/operations/v1alpha1/config_test.go +++ b/internal/api/operations/v1alpha1/config_test.go @@ -69,8 +69,8 @@ func loadCRDs(t *testing.T) map[string]*extensionsv1.CustomResourceDefinition { func TestCRDContract(t *testing.T) { crds := loadCRDs(t) - if len(crds) != 4 || crds["DeviceCustody"] == nil { - t.Fatalf("got %d CRDs, want DeviceCustody and three operation kinds", len(crds)) + if len(crds) != 5 || crds["DeviceCustody"] == nil || crds["CleaningPolicy"] == nil { + t.Fatalf("got %d CRDs, want DeviceCustody, CleaningPolicy and three operation kinds", len(crds)) } for kind, crd := range crds { version := crd.Spec.Versions[0] @@ -81,12 +81,23 @@ func TestCRDContract(t *testing.T) { t.Fatalf("%s must be served only in Milo project control planes", kind) } properties := version.Schema.OpenAPIV3Schema.Properties - if kind == "DeviceCustody" { + switch kind { + case "DeviceCustody": // Custody keeps its fields in spec, like a Lease. if version.Subresources != nil || len(properties["status"].Properties) != 0 { t.Fatal("DeviceCustody has no status") } - } else { + case "CleaningPolicy": + // A policy is provider-written configuration with no status, and + // its spec never changes after create. + spec := properties["spec"] + if version.Subresources != nil || len(properties["status"].Properties) != 0 { + t.Fatal("CleaningPolicy has no status") + } + if len(spec.XValidations) != 1 || spec.XValidations[0].Rule != "self == oldSelf" { + t.Fatal("CleaningPolicy spec must be immutable") + } + default: if version.Subresources == nil || version.Subresources.Status == nil { t.Fatalf("%s status must be a subresource, written only by the coordinator", kind) } @@ -188,9 +199,10 @@ func TestRolesKeepOneWriterAndKeepStaffFromCustomerSecrets(t *testing.T) { group := GroupVersion.Group + "/" read := []string{"get", "list", "watch"} want := map[string][]string{ - "fleet.datumapis.com-device-operations-viewer": slices.Concat(p(group+"devicecustodies", read...), p(group+"deviceinstallations", read...), p(group+"devicewipes", read...), p(group+"devicerecoveries", read...)), + "fleet.datumapis.com-device-operations-viewer": slices.Concat(p(group+"devicecustodies", read...), p(group+"deviceinstallations", read...), p(group+"devicewipes", read...), p(group+"devicerecoveries", read...), p(group+"cleaningpolicies", read...)), "fleet.datumapis.com-device-recovery-operator": slices.Concat(p(group+"devicerecoveries", "create"), p("metal.datumapis.com/machineallocations", read...)), - "fleet.datumapis.com-device-installation-requester": slices.Concat(p(group+"deviceinstallations", "create", "get", "list", "watch"), p(group+"devicecustodies", read...)), + "fleet.datumapis.com-device-installation-requester": slices.Concat(p(group+"deviceinstallations", "create", "get", "list", "watch"), p(group+"devicecustodies", read...), p(group+"cleaningpolicies", "get")), + "fleet.datumapis.com-cleaning-policy-admin": p(group+"cleaningpolicies", "create", "get", "list", "watch", "delete"), "fleet.datumapis.com-device-wipe-requester": slices.Concat(p(group+"devicewipes", "create", "get", "list", "watch"), p(group+"devicecustodies", read...)), } coordinator := slices.Concat(p(group+"devicecustodies", "get", "list", "watch", "create", "update", "delete"), p(group+"devices", read...), p("metal.datumapis.com/machineallocations", read...), p("metal.datumapis.com/machinecapacities", read...)) diff --git a/internal/api/operations/v1alpha1/types.go b/internal/api/operations/v1alpha1/types.go index 40190461..003a56c0 100644 --- a/internal/api/operations/v1alpha1/types.go +++ b/internal/api/operations/v1alpha1/types.go @@ -342,10 +342,9 @@ type DeviceWipeSpec struct { // Step numbers the wipes of one release, from 1. The name is derived // from it. Step int32 `json:"step"` - // CleaningPolicyDigest is the digest of the cleaning policy record - // pinned at allocation. - CleaningPolicyDigest string `json:"cleaningPolicyDigest"` - TargetDisks []string `json:"targetDisks"` + // Policy is the cleaning policy pinned at allocation. + Policy CleaningPolicyReference `json:"policy"` + TargetDisks []string `json:"targetDisks"` } // WipeEvidence is the result evidence of a DeviceWipe. @@ -459,7 +458,7 @@ type DeviceRecoveryList struct { } func addKnown(s *runtime.Scheme) error { - s.AddKnownTypes(GroupVersion, &DeviceCustody{}, &DeviceCustodyList{}, &DeviceInstallation{}, &DeviceInstallationList{}, &DeviceWipe{}, &DeviceWipeList{}, &DeviceRecovery{}, &DeviceRecoveryList{}) + s.AddKnownTypes(GroupVersion, &DeviceCustody{}, &DeviceCustodyList{}, &DeviceInstallation{}, &DeviceInstallationList{}, &DeviceWipe{}, &DeviceWipeList{}, &DeviceRecovery{}, &DeviceRecoveryList{}, &CleaningPolicy{}, &CleaningPolicyList{}) metav1.AddToGroupVersion(s, GroupVersion) return nil } diff --git a/internal/api/v1alpha1/types.go b/internal/api/v1alpha1/types.go index ac4bc000..30d84603 100644 --- a/internal/api/v1alpha1/types.go +++ b/internal/api/v1alpha1/types.go @@ -2,6 +2,8 @@ package v1alpha1 import ( "encoding/json" + + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" @@ -361,9 +363,9 @@ type MachineAllocationSpec struct { // allocation, in the Machine's namespace. It is absent where no quota // system serves the consumer. QuotaClaimRef *LocalReference `json:"quotaClaimRef,omitempty"` - // CleaningPolicyDigest pins the cleaning policy record the release - // wipes under. - CleaningPolicyDigest string `json:"cleaningPolicyDigest"` + // CleaningPolicy is the copy of the capacity's cleaning policy the + // release wipes under. It is pinned at allocation. + CleaningPolicy ops.PinnedCleaningPolicy `json:"cleaningPolicy"` // BootInterface and TargetDisks are what installations and wipes for // this allocation use. BootInterface string `json:"bootInterface"` diff --git a/internal/cleaning/envtest_test.go b/internal/cleaning/envtest_test.go new file mode 100644 index 00000000..c5a18ed2 --- /dev/null +++ b/internal/cleaning/envtest_test.go @@ -0,0 +1,89 @@ +package cleaning + +import ( + "context" + "encoding/pem" + "net/http/httptest" + "os" + "path/filepath" + "slices" + "strings" + "testing" + + "github.com/go-logr/logr" + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + admissionregistrationv1 "k8s.io/api/admissionregistration/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/envtest" + ctrllog "sigs.k8s.io/controller-runtime/pkg/log" + "sigs.k8s.io/controller-runtime/pkg/webhook/admission" + "sigs.k8s.io/yaml" +) + +// TestPolicyAgainstAPIServer installs the packaged CRD and webhook and +// checks that an invalid policy is refused and a valid one is immutable. +func TestPolicyAgainstAPIServer(t *testing.T) { + if os.Getenv("KUBEBUILDER_ASSETS") == "" { + t.Skip("KUBEBUILDER_ASSETS required") + } + ctrllog.SetLogger(logr.Discard()) + root := filepath.Join("..", "..") + environment := &envtest.Environment{CRDDirectoryPaths: []string{filepath.Join(root, "config", "components", "device-operations", "crds")}, ErrorIfCRDPathMissing: true} + config, err := environment.Start() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = environment.Stop() }) + scheme := runtime.NewScheme() + for _, add := range []func(*runtime.Scheme) error{ops.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) + } + server := httptest.NewTLSServer(&admission.Webhook{Handler: Webhook{}}) + t.Cleanup(server.Close) + data, err := os.ReadFile(filepath.Join(root, "config", "components", "device-operations", "webhook.yaml")) + if err != nil { + t.Fatal(err) + } + webhooks := &admissionregistrationv1.ValidatingWebhookConfiguration{} + if err := yaml.UnmarshalStrict(data, webhooks); err != nil { + t.Fatal(err) + } + webhooks.Webhooks = slices.DeleteFunc(webhooks.Webhooks, func(webhook admissionregistrationv1.ValidatingWebhook) bool { + return !strings.HasSuffix(*webhook.ClientConfig.URL, WebhookPath) + }) + if len(webhooks.Webhooks) != 1 { + t.Fatalf("the packaged configuration must have one webhook that calls %s", WebhookPath) + } + url := server.URL + WebhookPath + webhooks.Webhooks[0].ClientConfig = admissionregistrationv1.WebhookClientConfig{URL: &url, CABundle: pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: server.Certificate().Raw})} + if err := admin.Create(context.Background(), webhooks); err != nil { + t.Fatal(err) + } + ctx := context.Background() + policy := func(name string, spec ops.CleaningPolicySpec) *ops.CleaningPolicy { + return &ops.CleaningPolicy{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: "default"}, Spec: spec} + } + + fallback := purgePolicy() + fallback.Rules[0].Methods = append(fallback.Rules[0].Methods, ops.MethodOverwrite) + if err := admin.Create(ctx, policy("fallback", fallback)); !apierrors.IsForbidden(err) || !strings.Contains(err.Error(), "below the policy's Purge") { + t.Fatalf("a fallback below the assurance = %v, want the webhook to refuse it", err) + } + valid := policy("valid", purgePolicy()) + if err := admin.Create(ctx, valid); err != nil { + t.Fatal(err) + } + valid.Spec.Assurance = ops.AssuranceClear + if err := admin.Update(ctx, valid); !apierrors.IsInvalid(err) { + t.Fatalf("changing a policy spec = %v, want Invalid", err) + } +} diff --git a/internal/cleaning/policy.go b/internal/cleaning/policy.go new file mode 100644 index 00000000..fae2545c --- /dev/null +++ b/internal/cleaning/policy.go @@ -0,0 +1,199 @@ +// Package cleaning validates CleaningPolicies and matches them to drives, as +// proposed in datum-cloud/fleet#183. It is pure: it reads no API and sends +// nothing to a server. +package cleaning + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "slices" + + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" +) + +// Bounds keep a policy, and every allocation that copies it, small. +const ( + MaxRules = 16 + MaxMethods = 5 + MaxModels = 32 + MaxFirmware = 16 + MinSamples = 16 + MaxSamples = 1024 + DefaultSamples = 64 +) + +// method is what Fleet knows about one cleaning method: the assurance it can +// reach, the protocols it applies to, and the checks it may use. +type method struct { + assurance ops.Assurance + protocols []ops.DriveProtocol + verify []ops.VerifyMode +} + +var methods = map[ops.CleaningMethod]method{ + ops.MethodCryptographicErase: {ops.AssurancePurge, []ops.DriveProtocol{ops.ProtocolNVMe, ops.ProtocolSATA, ops.ProtocolSAS}, []ops.VerifyMode{ops.VerifyCanary}}, + ops.MethodBlockErase: {ops.AssurancePurge, []ops.DriveProtocol{ops.ProtocolNVMe, ops.ProtocolSATA, ops.ProtocolSAS}, []ops.VerifyMode{ops.VerifyCanary, ops.VerifyFull}}, + ops.MethodSanitizeOverwrite: {ops.AssurancePurge, []ops.DriveProtocol{ops.ProtocolNVMe, ops.ProtocolSATA, ops.ProtocolSAS}, []ops.VerifyMode{ops.VerifyCanary, ops.VerifyFull}}, + ops.MethodFormat: {ops.AssuranceClear, []ops.DriveProtocol{ops.ProtocolNVMe, ops.ProtocolSAS}, []ops.VerifyMode{ops.VerifyCanary, ops.VerifyFull}}, + ops.MethodSecureErase: {ops.AssuranceClear, []ops.DriveProtocol{ops.ProtocolSATA}, []ops.VerifyMode{ops.VerifyCanary, ops.VerifyFull}}, + ops.MethodOverwrite: {ops.AssuranceClear, []ops.DriveProtocol{ops.ProtocolNVMe, ops.ProtocolSATA, ops.ProtocolSAS}, []ops.VerifyMode{ops.VerifyFull}}, +} + +// AssuranceOf returns the assurance a method can reach, or "" for an unknown +// method. +func AssuranceOf(m ops.CleaningMethod) ops.Assurance { return methods[m].assurance } + +// Digest is the policy digest allocations pin: the SHA-256 of the canonical +// spec, computed the way custody digests operation inputs. +func Digest(spec ops.CleaningPolicySpec) (string, error) { + data, err := json.Marshal(spec) + if err != nil { + return "", err + } + sum := sha256.Sum256(data) + return "sha256:" + hex.EncodeToString(sum[:]), nil +} + +// Validate reports every reason the spec is not a usable policy. A rule may +// list only methods that reach the policy's assurance, so a fallback never +// lowers it. +func Validate(spec ops.CleaningPolicySpec) error { + var errs []error + if spec.Assurance != ops.AssuranceClear && spec.Assurance != ops.AssurancePurge { + errs = append(errs, fmt.Errorf("assurance %q is not Clear or Purge", spec.Assurance)) + } + if len(spec.Rules) == 0 || len(spec.Rules) > MaxRules { + errs = append(errs, fmt.Errorf("a policy has 1 to %d rules", MaxRules)) + } + names := map[string]bool{} + for i, rule := range spec.Rules { + at := fmt.Sprintf("rule %d (%s)", i, rule.Name) + if rule.Name == "" || len(rule.Name) > 63 { + errs = append(errs, fmt.Errorf("%s: a rule name is 1 to 63 characters", at)) + } + if names[rule.Name] { + errs = append(errs, fmt.Errorf("%s: rule names are unique", at)) + } + names[rule.Name] = true + errs = append(errs, validateMatch(at, rule.Match)...) + if rule.TimePerTiB.Duration <= 0 { + errs = append(errs, fmt.Errorf("%s: timePerTiB is positive", at)) + } + if len(rule.Methods) == 0 || len(rule.Methods) > MaxMethods { + errs = append(errs, fmt.Errorf("%s: a rule lists 1 to %d methods", at, MaxMethods)) + } + seen := map[ops.CleaningMethod]bool{} + for _, m := range rule.Methods { + known, ok := methods[m] + switch { + case !ok: + errs = append(errs, fmt.Errorf("%s: unknown method %q", at, m)) + continue + case seen[m]: + errs = append(errs, fmt.Errorf("%s: method %s is listed twice", at, m)) + case !slices.Contains(known.protocols, rule.Match.Protocol): + errs = append(errs, fmt.Errorf("%s: method %s does not apply to %s", at, m, rule.Match.Protocol)) + case !known.assurance.Reaches(spec.Assurance): + errs = append(errs, fmt.Errorf("%s: method %s reaches only %s, below the policy's %s", at, m, known.assurance, spec.Assurance)) + case !slices.Contains(known.verify, rule.Verify.Mode): + errs = append(errs, fmt.Errorf("%s: method %s cannot use %s verification", at, m, rule.Verify.Mode)) + } + seen[m] = true + } + switch rule.Verify.Mode { + case ops.VerifyFull: + if rule.Verify.Samples != 0 { + errs = append(errs, fmt.Errorf("%s: samples apply only to Canary verification", at)) + } + case ops.VerifyCanary: + if rule.Verify.Samples < MinSamples || rule.Verify.Samples > MaxSamples { + errs = append(errs, fmt.Errorf("%s: Canary verification takes %d to %d samples", at, MinSamples, MaxSamples)) + } + default: + errs = append(errs, fmt.Errorf("%s: verification mode %q is not Full or Canary", at, rule.Verify.Mode)) + } + } + errs = append(errs, validateQualified(spec.Qualified)...) + return errors.Join(errs...) +} + +func validateQualified(qualified []ops.QualifiedModel) []error { + var errs []error + if len(qualified) > MaxModels { + errs = append(errs, fmt.Errorf("a policy qualifies at most %d models", MaxModels)) + } + for i, model := range qualified { + at := fmt.Sprintf("qualified %d (%s)", i, model.Model) + if model.Model == "" || len(model.Firmware) == 0 || len(model.Firmware) > MaxFirmware { + errs = append(errs, fmt.Errorf("%s: a qualification names the model and 1 to %d firmware versions", at, MaxFirmware)) + } + if len(model.Methods) == 0 || len(model.Methods) > len(methods) { + errs = append(errs, fmt.Errorf("%s: a qualification lists the methods that passed", at)) + } + for _, m := range model.Methods { + if _, ok := methods[m]; !ok { + errs = append(errs, fmt.Errorf("%s: unknown method %q", at, m)) + } + if m == ops.MethodCryptographicErase && !model.AlwaysEncrypts { + errs = append(errs, fmt.Errorf("%s: CryptographicErase needs a model that always encrypts", at)) + } + } + } + return errs +} + +func validateMatch(at string, match ops.DriveMatch) []error { + var errs []error + if !slices.Contains([]ops.DriveProtocol{ops.ProtocolNVMe, ops.ProtocolSATA, ops.ProtocolSAS}, match.Protocol) { + errs = append(errs, fmt.Errorf("%s: protocol %q is not NVMe, SATA or SAS", at, match.Protocol)) + } + if match.MediaType != ops.MediaSSD && match.MediaType != ops.MediaHDD { + errs = append(errs, fmt.Errorf("%s: media type %q is not SSD or HDD", at, match.MediaType)) + } + return errs +} + +// Drive is what Fleet knows about one drive when it matches a policy. +type Drive struct { + Protocol ops.DriveProtocol + MediaType ops.MediaType + Model string + Firmware string +} + +// Match returns the first rule that matches the drive, or nil when none +// does. +func Match(spec ops.CleaningPolicySpec, drive Drive) *ops.CleaningRule { + for i, rule := range spec.Rules { + if rule.Match.Protocol == drive.Protocol && rule.Match.MediaType == drive.MediaType { + return &spec.Rules[i] + } + } + return nil +} + +// Methods returns the rule's methods Fleet may plan for the drive, in order: +// every Clear method, and each Purge method the policy qualifies for the +// drive's model and firmware. +func Methods(spec ops.CleaningPolicySpec, rule ops.CleaningRule, drive Drive) []ops.CleaningMethod { + var planned []ops.CleaningMethod + for _, m := range rule.Methods { + if AssuranceOf(m) != ops.AssurancePurge || qualified(spec, drive, m) { + planned = append(planned, m) + } + } + return planned +} + +func qualified(spec ops.CleaningPolicySpec, drive Drive, m ops.CleaningMethod) bool { + for _, model := range spec.Qualified { + if model.Model == drive.Model && slices.Contains(model.Firmware, drive.Firmware) && slices.Contains(model.Methods, m) && + (m != ops.MethodCryptographicErase || model.AlwaysEncrypts) { + return true + } + } + return false +} diff --git a/internal/cleaning/policy_test.go b/internal/cleaning/policy_test.go new file mode 100644 index 00000000..1bb31e7d --- /dev/null +++ b/internal/cleaning/policy_test.go @@ -0,0 +1,131 @@ +package cleaning + +import ( + "slices" + "strings" + "testing" + "time" + + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +var hour = metav1.Duration{Duration: time.Hour} + +func purgePolicy() ops.CleaningPolicySpec { + return ops.CleaningPolicySpec{ + Assurance: ops.AssurancePurge, + Rules: []ops.CleaningRule{{ + Name: "nvme-qualified", + Match: ops.DriveMatch{Protocol: ops.ProtocolNVMe, MediaType: ops.MediaSSD}, + Methods: []ops.CleaningMethod{ops.MethodCryptographicErase, ops.MethodBlockErase}, + Verify: ops.VerifySpec{Mode: ops.VerifyCanary, Samples: 64}, + TimePerTiB: metav1.Duration{Duration: 10 * time.Minute}, + }}, + Qualified: []ops.QualifiedModel{{Model: "EXAMPLE-NVME-3840", Firmware: []string{"EX1.2", "EX1.3"}, Methods: []ops.CleaningMethod{ops.MethodCryptographicErase, ops.MethodBlockErase}, AlwaysEncrypts: true}}, + } +} + +func clearPolicy() ops.CleaningPolicySpec { + return ops.CleaningPolicySpec{ + Assurance: ops.AssuranceClear, + Rules: []ops.CleaningRule{ + {Name: "nvme", Match: ops.DriveMatch{Protocol: ops.ProtocolNVMe, MediaType: ops.MediaSSD}, Methods: []ops.CleaningMethod{ops.MethodFormat, ops.MethodOverwrite}, Verify: ops.VerifySpec{Mode: ops.VerifyFull}, TimePerTiB: hour}, + {Name: "any-sata", Match: ops.DriveMatch{Protocol: ops.ProtocolSATA, MediaType: ops.MediaHDD}, Methods: []ops.CleaningMethod{ops.MethodOverwrite}, Verify: ops.VerifySpec{Mode: ops.VerifyFull}, TimePerTiB: hour}, + }, + } +} + +func TestValidateAcceptsPolicies(t *testing.T) { + for name, spec := range map[string]ops.CleaningPolicySpec{"purge": purgePolicy(), "clear": clearPolicy()} { + if err := Validate(spec); err != nil { + t.Errorf("%s: %v", name, err) + } + } +} + +func TestValidateRejects(t *testing.T) { + cases := map[string]struct { + mutate func(*ops.CleaningPolicySpec) + want string + }{ + "fallback below assurance": {func(s *ops.CleaningPolicySpec) { + s.Rules[0].Methods = append(s.Rules[0].Methods, ops.MethodOverwrite) + }, "below the policy's Purge"}, + "crypto erase without always-on encryption": {func(s *ops.CleaningPolicySpec) { s.Qualified[0].AlwaysEncrypts = false }, "always encrypts"}, + "no time bound": {func(s *ops.CleaningPolicySpec) { s.Rules[0].TimePerTiB = metav1.Duration{} }, "timePerTiB"}, + "method for another protocol": {func(s *ops.CleaningPolicySpec) { + s.Assurance = ops.AssuranceClear + s.Rules[0].Methods = []ops.CleaningMethod{ops.MethodSecureErase} + }, "does not apply to NVMe"}, + "overwrite without full verify": {func(s *ops.CleaningPolicySpec) { + s.Assurance = ops.AssuranceClear + s.Rules[0].Methods = []ops.CleaningMethod{ops.MethodOverwrite} + }, "cannot use Canary"}, + "duplicate method": {func(s *ops.CleaningPolicySpec) { + s.Rules[0].Methods = []ops.CleaningMethod{ops.MethodBlockErase, ops.MethodBlockErase} + }, "listed twice"}, + "unknown method": {func(s *ops.CleaningPolicySpec) { s.Rules[0].Methods = []ops.CleaningMethod{"Shred"} }, "unknown method"}, + "too few samples": {func(s *ops.CleaningPolicySpec) { s.Rules[0].Verify.Samples = 1 }, "samples"}, + "no rules": {func(s *ops.CleaningPolicySpec) { s.Rules = nil }, "1 to 16 rules"}, + "bad assurance": {func(s *ops.CleaningPolicySpec) { s.Assurance = "Destroy" }, "not Clear or Purge"}, + "duplicate rule": {func(s *ops.CleaningPolicySpec) { s.Rules = append(s.Rules, s.Rules[0]) }, "unique"}, + "model no firmware": {func(s *ops.CleaningPolicySpec) { s.Qualified[0].Firmware = nil }, "firmware"}, + } + for name, tc := range cases { + spec := purgePolicy() + tc.mutate(&spec) + err := Validate(spec) + if err == nil || !strings.Contains(err.Error(), tc.want) { + t.Errorf("%s: got %v, want an error containing %q", name, err, tc.want) + } + } +} + +func TestMatchAndQualifiedMethods(t *testing.T) { + spec := purgePolicy() + rule := Match(spec, Drive{ops.ProtocolNVMe, ops.MediaSSD, "EXAMPLE-NVME-3840", "EX1.3"}) + if rule == nil || rule.Name != "nvme-qualified" { + t.Fatalf("matching rule: got %v", rule) + } + if rule := Match(spec, Drive{ops.ProtocolSATA, ops.MediaSSD, "EXAMPLE-NVME-3840", "EX1.3"}); rule != nil { + t.Fatalf("another protocol matched %s", rule.Name) + } + cases := []struct { + name string + drive Drive + edit func(*ops.CleaningPolicySpec) + want []ops.CleaningMethod + }{ + {"qualified", Drive{ops.ProtocolNVMe, ops.MediaSSD, "EXAMPLE-NVME-3840", "EX1.3"}, nil, []ops.CleaningMethod{ops.MethodCryptographicErase, ops.MethodBlockErase}}, + {"unqualified firmware", Drive{ops.ProtocolNVMe, ops.MediaSSD, "EXAMPLE-NVME-3840", "EX0.9"}, nil, nil}, + {"unqualified model", Drive{ops.ProtocolNVMe, ops.MediaSSD, "OTHER", "EX1.3"}, nil, nil}, + {"method not qualified", Drive{ops.ProtocolNVMe, ops.MediaSSD, "EXAMPLE-NVME-3840", "EX1.3"}, + func(s *ops.CleaningPolicySpec) { s.Qualified[0].Methods = []ops.CleaningMethod{ops.MethodBlockErase} }, []ops.CleaningMethod{ops.MethodBlockErase}}, + {"crypto erase without always-on encryption", Drive{ops.ProtocolNVMe, ops.MediaSSD, "EXAMPLE-NVME-3840", "EX1.3"}, + func(s *ops.CleaningPolicySpec) { s.Qualified[0].AlwaysEncrypts = false }, []ops.CleaningMethod{ops.MethodBlockErase}}, + } + for _, tc := range cases { + spec := purgePolicy() + if tc.edit != nil { + tc.edit(&spec) + } + if got := Methods(spec, spec.Rules[0], tc.drive); !slices.Equal(got, tc.want) { + t.Errorf("%s: got %v, want %v", tc.name, got, tc.want) + } + } + clear := clearPolicy() + if got := Methods(clear, clear.Rules[0], Drive{ops.ProtocolNVMe, ops.MediaSSD, "any", "any"}); len(got) != 2 { + t.Errorf("Clear methods need no qualification: got %v", got) + } +} + +func TestDigestChangesWithSpec(t *testing.T) { + a, _ := Digest(purgePolicy()) + changed := purgePolicy() + changed.Rules[0].Verify.Samples = 65 + b, _ := Digest(changed) + if a == b || !strings.HasPrefix(a, "sha256:") || len(a) != 71 { + t.Fatalf("digests %s and %s", a, b) + } +} diff --git a/internal/cleaning/webhook.go b/internal/cleaning/webhook.go new file mode 100644 index 00000000..8c9e04a7 --- /dev/null +++ b/internal/cleaning/webhook.go @@ -0,0 +1,36 @@ +package cleaning + +import ( + "bytes" + "context" + "encoding/json" + + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + admissionv1 "k8s.io/api/admission/v1" + "sigs.k8s.io/controller-runtime/pkg/webhook/admission" +) + +// WebhookPath is where the policy webhook is served. +const WebhookPath = "/validate-cleaning-policy" + +// Webhook rejects a CleaningPolicy that Validate rejects. The CRD keeps the +// spec immutable; this checks what a schema cannot, such as a fallback method +// below the policy's assurance. It reads nothing and keeps no state. +type Webhook struct{} + +func (Webhook) Handle(_ context.Context, request admission.Request) admission.Response { + if request.Resource.Group != ops.GroupVersion.Group || request.Resource.Resource != "cleaningpolicies" || request.SubResource != "" || + (request.Operation != admissionv1.Create && request.Operation != admissionv1.Update) { + return admission.Denied("unsupported cleaning policy admission request") + } + var policy ops.CleaningPolicy + decoder := json.NewDecoder(bytes.NewReader(request.Object.Raw)) + decoder.DisallowUnknownFields() + if err := decoder.Decode(&policy); err != nil { + return admission.Denied("the cleaning policy could not be decoded: " + err.Error()) + } + if err := Validate(policy.Spec); err != nil { + return admission.Denied(err.Error()) + } + return admission.Allowed("the cleaning policy is valid") +} diff --git a/internal/cleaning/webhook_test.go b/internal/cleaning/webhook_test.go new file mode 100644 index 00000000..cdd65889 --- /dev/null +++ b/internal/cleaning/webhook_test.go @@ -0,0 +1,51 @@ +package cleaning + +import ( + "context" + "encoding/json" + "testing" + + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + admissionv1 "k8s.io/api/admission/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "sigs.k8s.io/controller-runtime/pkg/webhook/admission" +) + +func review(t *testing.T, operation admissionv1.Operation, resource string, object any) admission.Request { + t.Helper() + raw, err := json.Marshal(object) + if err != nil { + t.Fatal(err) + } + return admission.Request{AdmissionRequest: admissionv1.AdmissionRequest{ + Operation: operation, + Resource: metav1.GroupVersionResource{Group: ops.GroupVersion.Group, Version: ops.GroupVersion.Version, Resource: resource}, + Object: runtime.RawExtension{Raw: raw}, + }} +} + +func TestWebhook(t *testing.T) { + valid := &ops.CleaningPolicy{TypeMeta: metav1.TypeMeta{APIVersion: ops.GroupVersion.String(), Kind: "CleaningPolicy"}, ObjectMeta: metav1.ObjectMeta{Name: "p", Namespace: "default"}, Spec: purgePolicy()} + fallback := valid.DeepCopyObject().(*ops.CleaningPolicy) + fallback.Spec.Rules[0].Methods = append(fallback.Spec.Rules[0].Methods, ops.MethodOverwrite) + unknown := map[string]any{"apiVersion": ops.GroupVersion.String(), "kind": "CleaningPolicy", "metadata": map[string]any{"name": "p"}, + "spec": map[string]any{"assurance": "Clear", "rules": []any{}, "extra": true}} + cases := []struct { + name string + request admission.Request + allowed bool + }{ + {"valid create", review(t, admissionv1.Create, "cleaningpolicies", valid), true}, + {"valid update", review(t, admissionv1.Update, "cleaningpolicies", valid), true}, + {"fallback below assurance", review(t, admissionv1.Create, "cleaningpolicies", fallback), false}, + {"unknown field", review(t, admissionv1.Create, "cleaningpolicies", unknown), false}, + {"another resource", review(t, admissionv1.Create, "devicewipes", valid), false}, + {"delete", review(t, admissionv1.Delete, "cleaningpolicies", valid), false}, + } + for _, tc := range cases { + if got := (Webhook{}).Handle(context.Background(), tc.request); got.Allowed != tc.allowed { + t.Errorf("%s: allowed = %v, want %v (%v)", tc.name, got.Allowed, tc.allowed, got.Result) + } + } +} diff --git a/internal/coordination/transport_test.go b/internal/coordination/transport_test.go index 056b35f7..084e2955 100644 --- a/internal/coordination/transport_test.go +++ b/internal/coordination/transport_test.go @@ -116,7 +116,7 @@ func newFixture(t *testing.T) *rig { func (f *rig) wipe(fence int64, uid string) site.Assignment { spec := ops.DeviceWipeSpec{OperationEnvelope: ops.OperationEnvelope{Creator: ops.Creator{Username: "release", UID: "u"}, DeviceRef: ops.DeviceReference{Name: "server-example-001"}, Authority: ops.Authority{AllocationRef: &ops.LocalReference{Name: "alloc-example"}}}, - Step: 1, CleaningPolicyDigest: "sha256:" + keyDigest, TargetDisks: []string{"disk-0"}} + Step: 1, Policy: ops.CleaningPolicyReference{Name: "tenant-reuse-v1", UID: "policy-uid", Digest: "sha256:" + keyDigest}, TargetDisks: []string{"disk-0"}} inputs, _ := json.Marshal(spec) digest, _ := custody.SpecDigest(spec) now := time.Now().UTC() diff --git a/internal/custody/admission_test.go b/internal/custody/admission_test.go index 827721dc..4ecb20a5 100644 --- a/internal/custody/admission_test.go +++ b/internal/custody/admission_test.go @@ -83,7 +83,7 @@ func TestAdmissionPreconditions(t *testing.T) { named := &DeviceTestStaffOperation{ObjectMeta: metav1.ObjectMeta{GenerateName: "named-", Namespace: "default"}, Spec: testSpec{OperationEnvelope: envelope(device, staffUser, allocated("alloc-x")), Input: "a"}} e.create(named) // Staff cannot create the release kind either. - wipe := &ops.DeviceWipe{ObjectMeta: metav1.ObjectMeta{Name: WipeName("alloc-x", 1), Namespace: "default"}, Spec: ops.DeviceWipeSpec{OperationEnvelope: envelope(device, staffUser, allocated("alloc-x")), Step: 1, CleaningPolicyDigest: policyDigest, TargetDisks: []string{"disk-0"}}} + wipe := &ops.DeviceWipe{ObjectMeta: metav1.ObjectMeta{Name: WipeName("alloc-x", 1), Namespace: "default"}, Spec: ops.DeviceWipeSpec{OperationEnvelope: envelope(device, staffUser, allocated("alloc-x")), Step: 1, Policy: ops.CleaningPolicyReference{Name: "tenant-reuse-v1", UID: "policy-uid", Digest: policyDigest}, TargetDisks: []string{"disk-0"}}} e.create(wipe) e.settle(device.Name) for _, operation := range []ops.Operation{spoof, service, named, wipe} { diff --git a/internal/custody/creatorwebhook/envtest_test.go b/internal/custody/creatorwebhook/envtest_test.go index c9a6f08d..caade287 100644 --- a/internal/custody/creatorwebhook/envtest_test.go +++ b/internal/custody/creatorwebhook/envtest_test.go @@ -6,6 +6,7 @@ import ( "net/http/httptest" "os" "path/filepath" + "slices" "strings" "testing" "time" @@ -60,8 +61,13 @@ func TestCreatorAgainstAPIServer(t *testing.T) { if err := yaml.UnmarshalStrict(data, webhooks); err != nil { t.Fatal(err) } - if len(webhooks.Webhooks) != 1 || !strings.HasSuffix(*webhooks.Webhooks[0].ClientConfig.URL, Path) { - t.Fatalf("the packaged webhook must call %s", Path) + // The configuration also carries the cleaning policy webhook; this test + // installs only the creator webhook. + webhooks.Webhooks = slices.DeleteFunc(webhooks.Webhooks, func(webhook admissionregistrationv1.ValidatingWebhook) bool { + return !strings.HasSuffix(*webhook.ClientConfig.URL, Path) + }) + if len(webhooks.Webhooks) != 1 { + t.Fatalf("the packaged configuration must have one webhook that calls %s", Path) } url := server.URL + Path for index := range webhooks.Webhooks { diff --git a/internal/custody/harness_test.go b/internal/custody/harness_test.go index 8b01531a..57649e44 100644 --- a/internal/custody/harness_test.go +++ b/internal/custody/harness_test.go @@ -349,7 +349,7 @@ func (e *env) installation(device *inventory.Device, allocation, request string) func (e *env) wipe(device *inventory.Device, allocation string, step int32) *ops.DeviceWipe { e.t.Helper() operation := &ops.DeviceWipe{ObjectMeta: metav1.ObjectMeta{Name: WipeName(allocation, step), Namespace: "default"}, Spec: ops.DeviceWipeSpec{ - OperationEnvelope: envelope(device, releaseUser, allocated(allocation)), Step: step, CleaningPolicyDigest: policyDigest, TargetDisks: []string{"disk-0"}, + OperationEnvelope: envelope(device, releaseUser, allocated(allocation)), Step: step, Policy: ops.CleaningPolicyReference{Name: "tenant-reuse-v1", UID: "policy-uid", Digest: policyDigest}, TargetDisks: []string{"disk-0"}, }} e.create(operation) return operation @@ -359,7 +359,7 @@ func (e *env) wipe(device *inventory.Device, allocation string, step int32) *ops func (e *env) namedWipe(device *inventory.Device, allocation, name string, step int32) *ops.DeviceWipe { e.t.Helper() operation := &ops.DeviceWipe{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: "default"}, Spec: ops.DeviceWipeSpec{ - OperationEnvelope: envelope(device, releaseUser, allocated(allocation)), Step: step, CleaningPolicyDigest: policyDigest, TargetDisks: []string{"disk-0"}, + OperationEnvelope: envelope(device, releaseUser, allocated(allocation)), Step: step, Policy: ops.CleaningPolicyReference{Name: "tenant-reuse-v1", UID: "policy-uid", Digest: policyDigest}, TargetDisks: []string{"disk-0"}, }} e.create(operation) return operation @@ -429,10 +429,14 @@ func (e *env) allocation(device *inventory.Device, name, phase string) *metal.Ma DeviceRef: metal.AllocatedDeviceReference{Name: device.Name}, Accepted: metal.AcceptedContract{MachineClassRef: metal.ContentReference{Name: "class-example", Generation: 1, Digest: policyDigest}, MachineProfileRef: metal.ContentReference{Name: "profile-example", Generation: 1, Digest: policyDigest}, CPU: metal.CPURequirement{Architecture: "amd64", Cores: 2}, Memory: metal.MemoryRequirement{Capacity: "2Gi"}}, - Authority: metal.AllocationAuthority{Principal: "fixture", Decision: "fixture-" + name}, - CleaningPolicyDigest: policyDigest, - BootInterface: "primary", - TargetDisks: []string{"disk-0"}, + Authority: metal.AllocationAuthority{Principal: "fixture", Decision: "fixture-" + name}, + CleaningPolicy: ops.PinnedCleaningPolicy{CleaningPolicyReference: ops.CleaningPolicyReference{Name: "tenant-reuse-v1", UID: "policy-uid", Digest: policyDigest}, Spec: ops.CleaningPolicySpec{ + Assurance: ops.AssuranceClear, + Rules: []ops.CleaningRule{{Name: "nvme-ssd", Match: ops.DriveMatch{Protocol: ops.ProtocolNVMe, MediaType: ops.MediaSSD}, + Methods: []ops.CleaningMethod{ops.MethodOverwrite}, Verify: ops.VerifySpec{Mode: ops.VerifyFull}, TimePerTiB: metav1.Duration{Duration: time.Hour}}}, + }}, + BootInterface: "primary", + TargetDisks: []string{"disk-0"}, }} e.create(allocation) if phase != "" { diff --git a/internal/multiplane/runner.go b/internal/multiplane/runner.go index f69aaffa..be4613ca 100644 --- a/internal/multiplane/runner.go +++ b/internal/multiplane/runner.go @@ -223,12 +223,6 @@ func New(ctx context.Context, c Config) (*Runner, error) { Provider: r.Provider.API, ProviderCreator: providerCreator, Releaser: releaser, ReleaseCreator: releaseCreator, Custody: coord, Namespace: DeviceNamespace, - Cleaning: func(name string) (string, error) { - if name != "local-cleaning" { - return "", fmt.Errorf("no fixture cleaning policy %q", name) - } - return custody.SpecDigest(`{"method":"overwrite","disks":"all"}`) - }, BootInterface: "primary", TargetDisks: []string{"disk-0"}, } return r, nil diff --git a/internal/multiplane/seed.go b/internal/multiplane/seed.go index 216a8284..673e5fc9 100644 --- a/internal/multiplane/seed.go +++ b/internal/multiplane/seed.go @@ -8,6 +8,7 @@ import ( "path/filepath" "sort" "strings" + "time" core "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -16,6 +17,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" fleet "go.datum.net/fleet/internal/api/v1alpha1" "go.datum.net/fleet/internal/manager" "go.datum.net/fleet/internal/tenancy" @@ -30,6 +32,7 @@ func Seed(ctx context.Context, c Config) error { var profile fleet.MachineProfile var class fleet.MachineClass var capacity fleet.MachineCapacity + policy := LabCleaningPolicy() if err := json.Unmarshal([]byte(`{"metadata":{"name":"local-profile"},"spec":{"cpu":{"architecture":"amd64","cores":2},"memory":{"capacity":"2Gi"}}}`), &profile); err != nil { return err } @@ -47,7 +50,7 @@ func Seed(ctx context.Context, c Config) error { if err != nil { return err } - for _, obj := range append([]client.Object{&profile, &class, &capacity}, devices...) { + for _, obj := range append([]client.Object{&profile, &class, policy, &capacity}, devices...) { if err := ensure(ctx, provider, obj); err != nil { return err } @@ -168,3 +171,17 @@ func enrolledDevices(c Config) ([]client.Object, error) { } return out, nil } + +// LabCleaningPolicy is the lab's CleaningPolicy: Clear, by overwriting every +// block and reading it back, the only method the lab proves. +func LabCleaningPolicy() *ops.CleaningPolicy { + hour := metav1.Duration{Duration: time.Hour} + rule := func(protocol ops.DriveProtocol, media ops.MediaType) ops.CleaningRule { + return ops.CleaningRule{Name: strings.ToLower(string(protocol) + "-" + string(media)), Match: ops.DriveMatch{Protocol: protocol, MediaType: media}, + Methods: []ops.CleaningMethod{ops.MethodOverwrite}, Verify: ops.VerifySpec{Mode: ops.VerifyFull}, TimePerTiB: hour} + } + return &ops.CleaningPolicy{ObjectMeta: metav1.ObjectMeta{Name: "local-cleaning", Namespace: DeviceNamespace}, Spec: ops.CleaningPolicySpec{ + Assurance: ops.AssuranceClear, + Rules: []ops.CleaningRule{rule(ops.ProtocolNVMe, ops.MediaSSD), rule(ops.ProtocolSATA, ops.MediaSSD), rule(ops.ProtocolSATA, ops.MediaHDD)}, + }} +} diff --git a/internal/registration/transport.go b/internal/registration/transport.go index db0ecb6a..0ea52c68 100644 --- a/internal/registration/transport.go +++ b/internal/registration/transport.go @@ -5,17 +5,20 @@ import ( "sigs.k8s.io/controller-runtime/pkg/webhook/admission" + "go.datum.net/fleet/internal/cleaning" "go.datum.net/fleet/internal/custody/creatorwebhook" ) // Transport serves the validating webhooks and a transport probe. All sit // behind the same mutually authenticated TLS listener. The operation creator // webhook shares this server: it has the same caller, the same transport -// and the same provider scope, and it keeps no state. +// and the same provider scope, and it keeps no state. So does the cleaning +// policy webhook. func (handler *Handler) Transport(creator *creatorwebhook.Handler) http.Handler { mux := http.NewServeMux() mux.Handle("/validate-registration", &admission.Webhook{Handler: handler}) mux.Handle(creatorwebhook.Path, &admission.Webhook{Handler: creator}) + mux.Handle(cleaning.WebhookPath, &admission.Webhook{Handler: cleaning.Webhook{}}) mux.HandleFunc("/transportz", func(writer http.ResponseWriter, _ *http.Request) { writer.WriteHeader(http.StatusNoContent) }) diff --git a/internal/site/redfishwork/kinds_test.go b/internal/site/redfishwork/kinds_test.go index 264ecbc5..13373d9e 100644 --- a/internal/site/redfishwork/kinds_test.go +++ b/internal/site/redfishwork/kinds_test.go @@ -238,7 +238,7 @@ func TestInstallationRunsBothPhasesWithOneOnEach(t *testing.T) { func TestWipeChecksTheEnrolledDisk(t *testing.T) { l := newLab(t) r := runner(t, l) - spec := ops.DeviceWipeSpec{Step: 1, CleaningPolicyDigest: "sha256:" + strings.Repeat("b", 64), TargetDisks: []string{"disk-0"}} + spec := ops.DeviceWipeSpec{Step: 1, Policy: ops.CleaningPolicyReference{Name: "tenant-reuse-v1", UID: "policy-uid", Digest: "sha256:" + strings.Repeat("b", 64)}, TargetDisks: []string{"disk-0"}} result, err := r.Run(context.Background(), assignment(l, "DeviceWipe", "op-wipe", 1, spec)) if err != nil { t.Fatal(err) diff --git a/internal/site/simwork/kinds.go b/internal/site/simwork/kinds.go index 545f12be..b7c34ef8 100644 --- a/internal/site/simwork/kinds.go +++ b/internal/site/simwork/kinds.go @@ -151,7 +151,7 @@ func (Installation) Run(ctx context.Context, work *site.Work) (any, error) { func wipeSpec(work *site.Work) (ops.DeviceWipeSpec, *custody.Refusal) { var spec ops.DeviceWipeSpec - if err := json.Unmarshal(work.Inputs, &spec); err != nil || spec.CleaningPolicyDigest == "" { + if err := json.Unmarshal(work.Inputs, &spec); err != nil || spec.Policy.Digest == "" { return spec, &custody.Refusal{Reason: custody.ReasonInputsUnreadable, Message: "the admitted inputs are not a DeviceWipe spec"} } return spec, nil @@ -187,6 +187,6 @@ func (Wipe) Run(ctx context.Context, work *site.Work) (any, error) { return ops.WipeEvidence{ Steps: []ops.StepEvidence{{Name: step.Name, CompletedAt: metav1.NewTime(at.UTC())}}, WipedDisks: slices.Clone(spec.TargetDisks), - PolicyDigest: spec.CleaningPolicyDigest, + PolicyDigest: spec.Policy.Digest, }, nil } diff --git a/internal/site/vmwork/kinds.go b/internal/site/vmwork/kinds.go index 7b2a4ede..46f93b1a 100644 --- a/internal/site/vmwork/kinds.go +++ b/internal/site/vmwork/kinds.go @@ -407,7 +407,7 @@ func (k Installation) waitReceipt(ctx context.Context, work *site.Work, boot Boo func (k Installation) wipeSpec(work *site.Work) (ops.DeviceWipeSpec, *custody.Refusal) { var spec ops.DeviceWipeSpec - if err := json.Unmarshal(work.Inputs, &spec); err != nil || spec.CleaningPolicyDigest == "" { + if err := json.Unmarshal(work.Inputs, &spec); err != nil || spec.Policy.Digest == "" { return spec, &custody.Refusal{Reason: custody.ReasonInputsUnreadable, Message: "the admitted inputs are not a DeviceWipe spec"} } return spec, nil @@ -473,5 +473,5 @@ func (k Wipe) Run(ctx context.Context, work *site.Work) (any, error) { return nil, &custody.Refusal{Reason: site.ReasonStep, Message: "a disk remained after the wipe"} } at, _ := work.JournaledAt(step.Name) - return ops.WipeEvidence{Steps: []ops.StepEvidence{{Name: step.Name, CompletedAt: metav1.NewTime(at.UTC())}}, WipedDisks: spec.TargetDisks, PolicyDigest: spec.CleaningPolicyDigest}, nil + return ops.WipeEvidence{Steps: []ops.StepEvidence{{Name: step.Name, CompletedAt: metav1.NewTime(at.UTC())}}, WipedDisks: spec.TargetDisks, PolicyDigest: spec.Policy.Digest}, nil } diff --git a/internal/site/vmwork/kinds_test.go b/internal/site/vmwork/kinds_test.go index ce683991..a8539eb2 100644 --- a/internal/site/vmwork/kinds_test.go +++ b/internal/site/vmwork/kinds_test.go @@ -129,7 +129,7 @@ func installSpec() ops.DeviceInstallationSpec { } func wipeSpec() ops.DeviceWipeSpec { - return ops.DeviceWipeSpec{OperationEnvelope: envelope(), Step: 1, CleaningPolicyDigest: "sha256:" + key, TargetDisks: []string{"disk-0"}} + return ops.DeviceWipeSpec{OperationEnvelope: envelope(), Step: 1, Policy: ops.CleaningPolicyReference{Name: "tenant-reuse-v1", UID: "policy-uid", Digest: "sha256:" + key}, TargetDisks: []string{"disk-0"}} } // TestInstallThenWipe installs directly, proves each phase by its receipt, diff --git a/internal/staging/harness_test.go b/internal/staging/harness_test.go index 63816c5b..f3c7eaec 100644 --- a/internal/staging/harness_test.go +++ b/internal/staging/harness_test.go @@ -38,7 +38,6 @@ const ( releaseUser = "system:serviceaccount:fleet-system:release-controller" siteName = "site-example-a" siteToken = "synthetic-site-token" - policyDigest = "sha256:0c2b77e1d9a4000000000000000000000000000000000000000000000000cafe" locationName = "us-central-1" className = "central-metal" profileName = "general-purpose-24c-128g" @@ -131,13 +130,13 @@ func startStack(t *testing.T) *stack { Provider: admin, ProviderCreator: ops.Creator{Username: providerUser, UID: uid(801)}, Releaser: admin, ReleaseCreator: ops.Creator{Username: releaseUser, UID: uid(802)}, Custody: coordinator, Namespace: providerNamespace, - Cleaning: func(string) (string, error) { return policyDigest, nil }, BootInterface: "primary", TargetDisks: []string{"disk-0"}, } s.servers = enrollment s.sites = sites s.class = &fleetv1.MachineClass{ObjectMeta: metav1.ObjectMeta{Name: className}, Spec: fleetv1.MachineClassSpec{ProfilePolicy: &fleetv1.ProfilePolicy{AllowedProfiles: []fleetv1.LocalReference{{Name: profileName}}}, Access: &fleetv1.AccessPolicy{}, Capacity: &fleetv1.CapacityPolicy{MachineCapacities: fleetv1.MachineSelector{Namespace: providerNamespace, Selector: metav1.LabelSelector{MatchLabels: map[string]string{"pool": "example"}}}}}} s.create(s.class) + s.create(examplePolicy(providerNamespace)) s.profile = &fleetv1.MachineProfile{ObjectMeta: metav1.ObjectMeta{Name: profileName}, Spec: fleetv1.MachineProfileSpec{CPU: fleetv1.CPURequirement{Architecture: "amd64", Cores: 24}, Memory: fleetv1.MemoryRequirement{Capacity: "128Gi"}}} s.create(s.profile) return s @@ -252,3 +251,12 @@ func drive(t *testing.T, ctx context.Context, handler manager.Handler, project c func machineIdentity(project controller.ProjectIdentity, claim *fleetv1.Machine) allocation.Machine { return allocation.MachineOf(manager.ProjectConsumer(project, nil), claim) } + +// examplePolicy is the CleaningPolicy every fixture capacity names. +func examplePolicy(namespace string) *ops.CleaningPolicy { + return &ops.CleaningPolicy{ObjectMeta: metav1.ObjectMeta{Name: "example-cleaning", Namespace: namespace}, Spec: ops.CleaningPolicySpec{ + Assurance: ops.AssuranceClear, + Rules: []ops.CleaningRule{{Name: "nvme-ssd", Match: ops.DriveMatch{Protocol: ops.ProtocolNVMe, MediaType: ops.MediaSSD}, + Methods: []ops.CleaningMethod{ops.MethodOverwrite}, Verify: ops.VerifySpec{Mode: ops.VerifyFull}, TimePerTiB: metav1.Duration{Duration: time.Hour}}}, + }} +} From 4b9152df1165c1d88e427a4054e3e7c5103a6cd2 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 25 Nov 2026 10:05:52 -0600 Subject: [PATCH 2/5] fix(cleaning): Let the lab provider read policies and name skips Grant the multi-plane Metal provider get on CleaningPolicies, require timePerTiB to be a duration so every stored policy decodes, report the skipped policy when no capacity is left, and validate policies only on create, since the spec cannot change. Co-Authored-By: Claude Opus 5.5 --- config/base/crd/metal.datumapis.com.yaml | 2 +- .../device-operations/crds/fleet.datumapis.com.yaml | 2 +- config/components/device-operations/webhook.yaml | 2 +- docs/development/device-custody.md | 5 +++-- hack/multiplane/milo.py | 6 ++++-- internal/allocation/allocator.go | 8 +++++++- internal/allocation/cleaning_test.go | 4 ++-- internal/cleaning/envtest_test.go | 10 ++++++++++ internal/cleaning/webhook.go | 10 ++++++---- internal/cleaning/webhook_test.go | 2 +- 10 files changed, 36 insertions(+), 15 deletions(-) diff --git a/config/base/crd/metal.datumapis.com.yaml b/config/base/crd/metal.datumapis.com.yaml index ef63f080..87a7b27f 100644 --- a/config/base/crd/metal.datumapis.com.yaml +++ b/config/base/crd/metal.datumapis.com.yaml @@ -479,7 +479,7 @@ spec: properties: mode: {type: string, enum: [Full, Canary]} samples: {type: integer, format: int32, minimum: 0, maximum: 1024} - timePerTiB: {type: string, minLength: 1, maxLength: 32} + timePerTiB: {type: string, minLength: 1, maxLength: 32, pattern: '^([0-9]+(\\.[0-9]+)?(ns|us|µs|ms|s|m|h))+$'} qualified: type: array maxItems: 32 diff --git a/config/components/device-operations/crds/fleet.datumapis.com.yaml b/config/components/device-operations/crds/fleet.datumapis.com.yaml index c5870657..4d9791a6 100644 --- a/config/components/device-operations/crds/fleet.datumapis.com.yaml +++ b/config/components/device-operations/crds/fleet.datumapis.com.yaml @@ -1159,7 +1159,7 @@ spec: properties: mode: {type: string, enum: [Full, Canary]} samples: {type: integer, format: int32, minimum: 0, maximum: 1024} - timePerTiB: {type: string, minLength: 1, maxLength: 32} + timePerTiB: {type: string, minLength: 1, maxLength: 32, pattern: '^([0-9]+(\\.[0-9]+)?(ns|us|µs|ms|s|m|h))+$'} qualified: type: array maxItems: 32 diff --git a/config/components/device-operations/webhook.yaml b/config/components/device-operations/webhook.yaml index 8e6a43e4..07e5aefc 100644 --- a/config/components/device-operations/webhook.yaml +++ b/config/components/device-operations/webhook.yaml @@ -35,6 +35,6 @@ webhooks: rules: - apiGroups: [fleet.datumapis.com] apiVersions: [v1alpha1] - operations: [CREATE, UPDATE] + operations: [CREATE] resources: [cleaningpolicies] scope: Namespaced diff --git a/docs/development/device-custody.md b/docs/development/device-custody.md index 22e2d356..57f4aaf4 100644 --- a/docs/development/device-custody.md +++ b/docs/development/device-custody.md @@ -700,12 +700,13 @@ real API server. The rest of #183 is **proposed**. reach its assurance, that applies a method to the wrong protocol, that uses a check a method does not allow, or that qualifies `CryptographicErase` for a model that does not always encrypt. The `fleet-registration` server serves it - as a webhook at `/validate-cleaning-policy` in `config/milo`. The synthetic + as a webhook at `/validate-cleaning-policy` in `config/milo`, for creates + only, because the spec cannot change. The synthetic Milo root and the standalone cluster have no such webhook. - **Pinning.** The allocator reads the capacity's policy, validates it again, and copies its name, UID, SHA-256 digest and spec into the MachineAllocation. Capacity whose policy is missing or invalid is skipped, and nothing is - claimed. Each release `DeviceWipe` names the pinned policy, so release does + claimed. If no capacity is left, the error names the skipped policy. Each release `DeviceWipe` names the pinned policy, so release does not need the policy to exist. - **Fixtures.** The standalone fixtures and the multi-plane seed create a `Clear` policy that overwrites and reads back, the only method the sites run. diff --git a/hack/multiplane/milo.py b/hack/multiplane/milo.py index 5e5ee1c2..32262685 100755 --- a/hack/multiplane/milo.py +++ b/hack/multiplane/milo.py @@ -87,9 +87,11 @@ def wait(fn,seconds,what): # the namespace is never deleted. apply(config,{'apiVersion':'v1','kind':'Namespace','metadata':{'name':'fleet-rules'}}) # The Metal provider records allocations and creates installations; it - # reads custody and Devices only to skip taken capacity. + # reads custody and Devices only to skip taken capacity, and gets the + # CleaningPolicy each allocation pins. rules+=[{'apiGroups':['metal.datumapis.com'],'resources':['machineallocations'],'verbs':['get','list','watch','create','delete']},{'apiGroups':['metal.datumapis.com'],'resources':['machineallocations/status'],'verbs':['get','update']}, - {'apiGroups':['fleet.datumapis.com'],'resources':['deviceinstallations'],'verbs':['get','list','watch','create']},{'apiGroups':['fleet.datumapis.com'],'resources':['devices','devicecustodies'],'verbs':['get','list','watch']}] + {'apiGroups':['fleet.datumapis.com'],'resources':['deviceinstallations'],'verbs':['get','list','watch','create']},{'apiGroups':['fleet.datumapis.com'],'resources':['devices','devicecustodies'],'verbs':['get','list','watch']}, + {'apiGroups':['fleet.datumapis.com'],'resources':['cleaningpolicies'],'verbs':['get']}] components={ 'coordinator':[{'apiGroups':['fleet.datumapis.com'],'resources':['devices'],'verbs':['get','list','watch']},{'apiGroups':['fleet.datumapis.com'],'resources':['devicecustodies'],'verbs':['get','list','watch','create','update','delete']}, {'apiGroups':['fleet.datumapis.com'],'resources':['deviceinstallations','devicewipes','devicerecoveries'],'verbs':['get','list','watch','delete']}, diff --git a/internal/allocation/allocator.go b/internal/allocation/allocator.go index 3a8ae630..aadbf314 100644 --- a/internal/allocation/allocator.go +++ b/internal/allocation/allocator.go @@ -176,6 +176,7 @@ func (a *Allocator) Allocate(ctx context.Context, request Request) (*fleetv1.Mac } } tried := map[string]bool{} + var uncovered error for { allocation, err := a.Get(ctx, request.Machine) if err != nil { @@ -190,6 +191,9 @@ func (a *Allocator) Allocate(ctx context.Context, request Request) (*fleetv1.Mac continue } candidate, device, err := a.candidate(ctx, request, tried) + if errors.Is(err, ErrInsufficientCapacity) && uncovered != nil { + return nil, fmt.Errorf("%w; skipped: %w", err, uncovered) + } if err != nil { return nil, err } @@ -197,7 +201,9 @@ func (a *Allocator) Allocate(ctx context.Context, request Request) (*fleetv1.Mac allocation, err = a.newAllocation(ctx, request, candidate, device, claim) if errors.Is(err, ErrCleaningUncovered) { // Capacity without a usable cleaning policy is not eligible. - // Nothing was claimed; try the next candidate. + // Nothing was claimed; try the next candidate, and report why + // if none is left. + uncovered = err continue } if err != nil { diff --git a/internal/allocation/cleaning_test.go b/internal/allocation/cleaning_test.go index bcf1e4ab..edca1643 100644 --- a/internal/allocation/cleaning_test.go +++ b/internal/allocation/cleaning_test.go @@ -88,8 +88,8 @@ func TestCapacityWithoutAUsableCleaningPolicyIsNotAllocated(t *testing.T) { e := startEnv(t) device := e.server(1) setup(e) - if _, err := e.allocator.Allocate(e.ctx, e.request(1)); !errors.Is(err, ErrInsufficientCapacity) { - t.Fatalf("allocate = %v, want ErrInsufficientCapacity", err) + if _, err := e.allocator.Allocate(e.ctx, e.request(1)); !errors.Is(err, ErrInsufficientCapacity) || !errors.Is(err, ErrCleaningUncovered) { + t.Fatalf("allocate = %v, want ErrInsufficientCapacity that says the cleaning policy was not usable", err) } if found, err := e.allocator.Get(e.ctx, machine(1)); err != nil || found != nil { t.Fatalf("allocation = %v, %v", found, err) diff --git a/internal/cleaning/envtest_test.go b/internal/cleaning/envtest_test.go index c5a18ed2..3ddf1d59 100644 --- a/internal/cleaning/envtest_test.go +++ b/internal/cleaning/envtest_test.go @@ -15,6 +15,7 @@ import ( admissionregistrationv1 "k8s.io/api/admissionregistration/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" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/envtest" @@ -78,6 +79,15 @@ func TestPolicyAgainstAPIServer(t *testing.T) { if err := admin.Create(ctx, policy("fallback", fallback)); !apierrors.IsForbidden(err) || !strings.Contains(err.Error(), "below the policy's Purge") { t.Fatalf("a fallback below the assurance = %v, want the webhook to refuse it", err) } + // The schema refuses a time bound that is not a duration, so no stored + // policy fails to decode. + malformed := &unstructured.Unstructured{Object: map[string]any{"apiVersion": ops.GroupVersion.String(), "kind": "CleaningPolicy", + "metadata": map[string]any{"name": "malformed", "namespace": "default"}, + "spec": map[string]any{"assurance": "Clear", "rules": []any{map[string]any{"name": "r", "match": map[string]any{"protocol": "NVMe", "mediaType": "SSD"}, + "methods": []any{"Overwrite"}, "verify": map[string]any{"mode": "Full"}, "timePerTiB": "abc"}}}}} + if err := admin.Create(ctx, malformed); !apierrors.IsInvalid(err) { + t.Fatalf("a time bound that is not a duration = %v, want Invalid", err) + } valid := policy("valid", purgePolicy()) if err := admin.Create(ctx, valid); err != nil { t.Fatal(err) diff --git a/internal/cleaning/webhook.go b/internal/cleaning/webhook.go index 8c9e04a7..4ed7a1c3 100644 --- a/internal/cleaning/webhook.go +++ b/internal/cleaning/webhook.go @@ -13,14 +13,16 @@ import ( // WebhookPath is where the policy webhook is served. const WebhookPath = "/validate-cleaning-policy" -// Webhook rejects a CleaningPolicy that Validate rejects. The CRD keeps the -// spec immutable; this checks what a schema cannot, such as a fallback method -// below the policy's assurance. It reads nothing and keeps no state. +// Webhook rejects a new CleaningPolicy that Validate rejects. It checks what a +// schema cannot, such as a fallback method below the policy's assurance. It +// sees only creates: the CRD keeps the spec immutable, so an update can only +// change metadata, and a stricter Validate later must not block that. It +// reads nothing and keeps no state. type Webhook struct{} func (Webhook) Handle(_ context.Context, request admission.Request) admission.Response { if request.Resource.Group != ops.GroupVersion.Group || request.Resource.Resource != "cleaningpolicies" || request.SubResource != "" || - (request.Operation != admissionv1.Create && request.Operation != admissionv1.Update) { + request.Operation != admissionv1.Create { return admission.Denied("unsupported cleaning policy admission request") } var policy ops.CleaningPolicy diff --git a/internal/cleaning/webhook_test.go b/internal/cleaning/webhook_test.go index cdd65889..6bbcb695 100644 --- a/internal/cleaning/webhook_test.go +++ b/internal/cleaning/webhook_test.go @@ -37,7 +37,7 @@ func TestWebhook(t *testing.T) { allowed bool }{ {"valid create", review(t, admissionv1.Create, "cleaningpolicies", valid), true}, - {"valid update", review(t, admissionv1.Update, "cleaningpolicies", valid), true}, + {"update", review(t, admissionv1.Update, "cleaningpolicies", valid), false}, {"fallback below assurance", review(t, admissionv1.Create, "cleaningpolicies", fallback), false}, {"unknown field", review(t, admissionv1.Create, "cleaningpolicies", unknown), false}, {"another resource", review(t, admissionv1.Create, "devicewipes", valid), false}, From 762ad3bd2dce613edd99cb869f78251250a96168 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 25 Nov 2026 10:10:34 -0600 Subject: [PATCH 3/5] fix(cleaning): Match Go durations in the timePerTiB pattern The pattern escaped its decimal point twice, so it rejected 1.5h and accepted malformed values. Test accepted and refused bounds against the API server, and keep the allocation's pinned schema equal to the policy's. Co-Authored-By: Claude Opus 5.5 --- config/base/crd/metal.datumapis.com.yaml | 2 +- .../crds/fleet.datumapis.com.yaml | 2 +- docs/development/device-custody.md | 9 ++++--- .../api/operations/v1alpha1/config_test.go | 22 ++++++++++++++++ internal/cleaning/envtest_test.go | 26 ++++++++++++++----- 5 files changed, 49 insertions(+), 12 deletions(-) diff --git a/config/base/crd/metal.datumapis.com.yaml b/config/base/crd/metal.datumapis.com.yaml index 87a7b27f..b08463d4 100644 --- a/config/base/crd/metal.datumapis.com.yaml +++ b/config/base/crd/metal.datumapis.com.yaml @@ -479,7 +479,7 @@ spec: properties: mode: {type: string, enum: [Full, Canary]} samples: {type: integer, format: int32, minimum: 0, maximum: 1024} - timePerTiB: {type: string, minLength: 1, maxLength: 32, pattern: '^([0-9]+(\\.[0-9]+)?(ns|us|µs|ms|s|m|h))+$'} + timePerTiB: {type: string, minLength: 1, maxLength: 32, pattern: '^([0-9]+(\.[0-9]+)?(ns|us|µs|μs|ms|s|m|h))+$'} qualified: type: array maxItems: 32 diff --git a/config/components/device-operations/crds/fleet.datumapis.com.yaml b/config/components/device-operations/crds/fleet.datumapis.com.yaml index 4d9791a6..27977e3b 100644 --- a/config/components/device-operations/crds/fleet.datumapis.com.yaml +++ b/config/components/device-operations/crds/fleet.datumapis.com.yaml @@ -1159,7 +1159,7 @@ spec: properties: mode: {type: string, enum: [Full, Canary]} samples: {type: integer, format: int32, minimum: 0, maximum: 1024} - timePerTiB: {type: string, minLength: 1, maxLength: 32, pattern: '^([0-9]+(\\.[0-9]+)?(ns|us|µs|ms|s|m|h))+$'} + timePerTiB: {type: string, minLength: 1, maxLength: 32, pattern: '^([0-9]+(\.[0-9]+)?(ns|us|µs|μs|ms|s|m|h))+$'} qualified: type: array maxItems: 32 diff --git a/docs/development/device-custody.md b/docs/development/device-custody.md index 57f4aaf4..9eb9442c 100644 --- a/docs/development/device-custody.md +++ b/docs/development/device-custody.md @@ -701,13 +701,14 @@ real API server. The rest of #183 is **proposed**. check a method does not allow, or that qualifies `CryptographicErase` for a model that does not always encrypt. The `fleet-registration` server serves it as a webhook at `/validate-cleaning-policy` in `config/milo`, for creates - only, because the spec cannot change. The synthetic - Milo root and the standalone cluster have no such webhook. + only, because the spec cannot change. The synthetic Milo root and the + standalone cluster have no such webhook. - **Pinning.** The allocator reads the capacity's policy, validates it again, and copies its name, UID, SHA-256 digest and spec into the MachineAllocation. Capacity whose policy is missing or invalid is skipped, and nothing is - claimed. If no capacity is left, the error names the skipped policy. Each release `DeviceWipe` names the pinned policy, so release does - not need the policy to exist. + claimed. If no capacity is left, the error names the skipped policy. Each + release `DeviceWipe` names the pinned policy, so release does not need the + policy to exist. - **Fixtures.** The standalone fixtures and the multi-plane seed create a `Clear` policy that overwrites and reads back, the only method the sites run. Synthetic staging has no fixture: an operator must create the policy that its diff --git a/internal/api/operations/v1alpha1/config_test.go b/internal/api/operations/v1alpha1/config_test.go index a74dbded..c0bc451b 100644 --- a/internal/api/operations/v1alpha1/config_test.go +++ b/internal/api/operations/v1alpha1/config_test.go @@ -7,6 +7,7 @@ import ( "io/fs" "os" "path/filepath" + "reflect" "slices" "strings" "testing" @@ -318,3 +319,24 @@ func TestPhases(t *testing.T) { } } } + +// TestPinnedPolicySchemaMatchesThePolicy keeps the MachineAllocation's copy of +// a CleaningPolicy spec as strict as the policy itself, so every policy the +// allocator pins can be stored. +func TestPinnedPolicySchemaMatchesThePolicy(t *testing.T) { + policy := loadCRDs(t)["CleaningPolicy"].Spec.Versions[0].Schema.OpenAPIV3Schema.Properties["spec"] + var pinned *extensionsv1.JSONSchemaProps + for _, crd := range decodeAll[extensionsv1.CustomResourceDefinition](t, filepath.Join(configRoot, "base", "crd", "metal.datumapis.com.yaml")) { + if crd.Spec.Names.Kind == "MachineAllocation" { + copied := crd.Spec.Versions[0].Schema.OpenAPIV3Schema.Properties["spec"].Properties["cleaningPolicy"].Properties["spec"] + pinned = &copied + } + } + if pinned == nil { + t.Fatal("MachineAllocation has no cleaningPolicy.spec") + } + policy.XValidations = nil + if !reflect.DeepEqual(policy, *pinned) { + t.Fatal("MachineAllocation.spec.cleaningPolicy.spec differs from the CleaningPolicy spec schema") + } +} diff --git a/internal/cleaning/envtest_test.go b/internal/cleaning/envtest_test.go index 3ddf1d59..288fb021 100644 --- a/internal/cleaning/envtest_test.go +++ b/internal/cleaning/envtest_test.go @@ -3,12 +3,14 @@ package cleaning import ( "context" "encoding/pem" + "fmt" "net/http/httptest" "os" "path/filepath" "slices" "strings" "testing" + "time" "github.com/go-logr/logr" ops "go.datum.net/fleet/internal/api/operations/v1alpha1" @@ -81,12 +83,24 @@ func TestPolicyAgainstAPIServer(t *testing.T) { } // The schema refuses a time bound that is not a duration, so no stored // policy fails to decode. - malformed := &unstructured.Unstructured{Object: map[string]any{"apiVersion": ops.GroupVersion.String(), "kind": "CleaningPolicy", - "metadata": map[string]any{"name": "malformed", "namespace": "default"}, - "spec": map[string]any{"assurance": "Clear", "rules": []any{map[string]any{"name": "r", "match": map[string]any{"protocol": "NVMe", "mediaType": "SSD"}, - "methods": []any{"Overwrite"}, "verify": map[string]any{"mode": "Full"}, "timePerTiB": "abc"}}}}} - if err := admin.Create(ctx, malformed); !apierrors.IsInvalid(err) { - t.Fatalf("a time bound that is not a duration = %v, want Invalid", err) + raw := func(name, bound string) *unstructured.Unstructured { + return &unstructured.Unstructured{Object: map[string]any{"apiVersion": ops.GroupVersion.String(), "kind": "CleaningPolicy", + "metadata": map[string]any{"name": name, "namespace": "default"}, + "spec": map[string]any{"assurance": "Clear", "rules": []any{map[string]any{"name": "r", "match": map[string]any{"protocol": "NVMe", "mediaType": "SSD"}, + "methods": []any{"Overwrite"}, "verify": map[string]any{"mode": "Full"}, "timePerTiB": bound}}}}} + } + for i, bound := range []string{"1h", "1.5h", "1h30m", "0.5µs", "90s"} { + if _, err := time.ParseDuration(bound); err != nil { + t.Fatal(err) + } + if err := admin.Create(ctx, raw(fmt.Sprintf("bound-%d", i), bound)); err != nil { + t.Fatalf("time bound %q = %v, want accepted", bound, err) + } + } + for i, bound := range []string{"abc", `1\x5h`, "1", "-1h", "1h "} { + if err := admin.Create(ctx, raw(fmt.Sprintf("malformed-%d", i), bound)); !apierrors.IsInvalid(err) { + t.Fatalf("time bound %q = %v, want Invalid", bound, err) + } } valid := policy("valid", purgePolicy()) if err := admin.Create(ctx, valid); err != nil { From 31cea81b55ec6aeb0e67e16c30b7f341ac3917fa Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 25 Nov 2026 11:12:41 -0600 Subject: [PATCH 4/5] feat(cleaning): Ship a staging cleaning policy for operators Synthetic staging names a cleaning policy that nothing creates, and the manager must not write policies. Ship the fixture policy operators apply to the provider project, and test that every shipped policy is valid. Co-Authored-By: Claude Opus 5.5 --- .../provider-project/cleaning-policy.yaml | 18 +++++++ docs/development/README.md | 3 ++ docs/development/device-custody.md | 5 +- internal/cleaning/fixtures_test.go | 47 +++++++++++++++++++ 4 files changed, 71 insertions(+), 2 deletions(-) create mode 100644 config/overlays/synthetic-staging/provider-project/cleaning-policy.yaml create mode 100644 internal/cleaning/fixtures_test.go diff --git a/config/overlays/synthetic-staging/provider-project/cleaning-policy.yaml b/config/overlays/synthetic-staging/provider-project/cleaning-policy.yaml new file mode 100644 index 00000000..74ca5404 --- /dev/null +++ b/config/overlays/synthetic-staging/provider-project/cleaning-policy.yaml @@ -0,0 +1,18 @@ +# Operators apply this to the synthetic provider project, in the Device +# namespace (--synthetic-device-namespace). It is not part of the overlay, +# which renders into the management cluster. Synthetic staging allocates no +# capacity until the policy its capacity names exists. The synthetic site +# overwrites its one disk and reads it back, so the policy claims only Clear. +apiVersion: fleet.datumapis.com/v1alpha1 +kind: CleaningPolicy +metadata: + name: synthetic-tenant-reuse-v1 + namespace: default +spec: + assurance: Clear + rules: + - name: nvme-ssd + match: {protocol: NVMe, mediaType: SSD} + methods: [Overwrite] + verify: {mode: Full} + timePerTiB: 1h diff --git a/docs/development/README.md b/docs/development/README.md index faf64def..da679ebc 100644 --- a/docs/development/README.md +++ b/docs/development/README.md @@ -485,6 +485,9 @@ store persistence is covered by local tests. This remains synthetic API validation, not production provider qualification. The overlay needs imported records and two new credentials; see the [deployment and migration contract](../../config/README.md#moving-from-the-secret-backed-staging). +Operators also apply the [fixture cleaning +policy](../../config/overlays/synthetic-staging/provider-project/cleaning-policy.yaml) +to the provider project. No capacity is allocated until it exists. `config/overlays/management-plane` now packages the manager Deployment so its diff --git a/docs/development/device-custody.md b/docs/development/device-custody.md index 9eb9442c..6c30e9f1 100644 --- a/docs/development/device-custody.md +++ b/docs/development/device-custody.md @@ -711,8 +711,9 @@ real API server. The rest of #183 is **proposed**. policy to exist. - **Fixtures.** The standalone fixtures and the multi-plane seed create a `Clear` policy that overwrites and reads back, the only method the sites run. - Synthetic staging has no fixture: an operator must create the policy that its - capacity names before that capacity can be allocated. + Synthetic staging ships a fixture policy that operators apply to the + provider project, because the manager writes no policies. No capacity is + allocated until it exists. Not implemented yet: drive inventory from Redfish and commissioning, the media manifest and pinned drive names, the per-drive plan in `DeviceWipe`, the diff --git a/internal/cleaning/fixtures_test.go b/internal/cleaning/fixtures_test.go new file mode 100644 index 00000000..e5150075 --- /dev/null +++ b/internal/cleaning/fixtures_test.go @@ -0,0 +1,47 @@ +package cleaning + +import ( + "bytes" + "io" + "os" + "path/filepath" + "testing" + + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + "k8s.io/apimachinery/pkg/util/yaml" +) + +// TestShippedPoliciesAreValid keeps every packaged fixture policy one the +// allocator will pin. +func TestShippedPoliciesAreValid(t *testing.T) { + root := filepath.Join("..", "..", "config") + found := 0 + for _, path := range []string{ + filepath.Join(root, "standalone", "fixtures.yaml"), + filepath.Join(root, "overlays", "synthetic-staging", "provider-project", "cleaning-policy.yaml"), + } { + data, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + decoder := yaml.NewYAMLOrJSONDecoder(bytes.NewReader(data), 4096) + for { + var policy ops.CleaningPolicy + if err := decoder.Decode(&policy); err == io.EOF { + break + } else if err != nil { + t.Fatal(err) + } + if policy.Kind != "CleaningPolicy" { + continue + } + found++ + if err := Validate(policy.Spec); err != nil { + t.Errorf("%s %s: %v", path, policy.Name, err) + } + } + } + if found != 2 { + t.Fatalf("found %d fixture policies, want 2", found) + } +} From fee8ebb5c4684cf5caf2be5294f7039a33ff6bbd Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 25 Nov 2026 16:08:22 -0600 Subject: [PATCH 5/5] fix(cleaning): Pin cleaning policies by generation and digest, not UID No resource spec may hold an object UID. The allocation's pinned policy and each DeviceWipe's policy reference now carry the policy's name, generation and digest. The allocation keeps its own copy, so a policy recreated under the same name changes no existing pin; a test recreates one with other content and checks that release still wipes under the original pin. Co-Authored-By: Claude Opus 5.5 --- config/base/crd/metal.datumapis.com.yaml | 4 +- .../crds/fleet.datumapis.com.yaml | 10 ++-- docs/development/device-custody.md | 21 +++++---- internal/allocation/allocator.go | 2 +- internal/allocation/cleaning_test.go | 47 ++++++++++++++++++- internal/api/operations/v1alpha1/cleaning.go | 12 +++-- internal/coordination/transport_test.go | 2 +- internal/custody/admission_test.go | 2 +- internal/custody/harness_test.go | 6 +-- internal/site/redfishwork/kinds_test.go | 2 +- internal/site/vmwork/kinds_test.go | 2 +- 11 files changed, 80 insertions(+), 30 deletions(-) diff --git a/config/base/crd/metal.datumapis.com.yaml b/config/base/crd/metal.datumapis.com.yaml index b08463d4..88f9e645 100644 --- a/config/base/crd/metal.datumapis.com.yaml +++ b/config/base/crd/metal.datumapis.com.yaml @@ -440,10 +440,10 @@ spec: name: {type: string, minLength: 1} cleaningPolicy: type: object - required: [name, uid, digest, spec] + required: [name, generation, digest, spec] properties: name: {type: string, minLength: 1, maxLength: 253} - uid: {type: string, minLength: 1, maxLength: 64} + generation: {type: integer, format: int64, minimum: 1} digest: {type: string, pattern: '^sha256:[a-f0-9]{64}$'} spec: type: object diff --git a/config/components/device-operations/crds/fleet.datumapis.com.yaml b/config/components/device-operations/crds/fleet.datumapis.com.yaml index 27977e3b..126b3ddf 100644 --- a/config/components/device-operations/crds/fleet.datumapis.com.yaml +++ b/config/components/device-operations/crds/fleet.datumapis.com.yaml @@ -712,16 +712,16 @@ spec: type: string minLength: 1 maxLength: 253 - uid: - type: string - minLength: 1 - maxLength: 64 + generation: + type: integer + format: int64 + minimum: 1 digest: type: string pattern: ^sha256:[0-9a-f]{64}$ required: - name - - uid + - generation - digest targetDisks: type: array diff --git a/docs/development/device-custody.md b/docs/development/device-custody.md index 6c30e9f1..b94fd699 100644 --- a/docs/development/device-custody.md +++ b/docs/development/device-custody.md @@ -178,10 +178,11 @@ A `MachineAllocation` holds the allocation's private facts (O8). It lives in the provider project, and only the Metal provider writes it. - **Spec (immutable).** The consumer as a typed reference, the Machine by - namespace and name, the capacity, the Device by name, the accepted class and profile pinned by - generation and spec digest, the CPU and memory, the hardware snapshot, the - admission authority, an optional quota claim, a copy of the capacity's - `CleaningPolicy` with its name, UID and digest, the boot interface and the target disks. + namespace and name, the capacity, the Device by name, the accepted class + and profile pinned by generation and spec digest, the CPU and memory, the + hardware snapshot, the admission authority, an optional quota claim, a copy + of the capacity's `CleaningPolicy` with its name, generation and digest, the + boot interface and the target disks. - **Labels.** `fleet.datumapis.com/machine-uid`, `fleet.datumapis.com/consumer-uid` and `fleet.datumapis.com/device-uid` record the incarnations the allocation was @@ -704,11 +705,13 @@ real API server. The rest of #183 is **proposed**. only, because the spec cannot change. The synthetic Milo root and the standalone cluster have no such webhook. - **Pinning.** The allocator reads the capacity's policy, validates it again, - and copies its name, UID, SHA-256 digest and spec into the MachineAllocation. - Capacity whose policy is missing or invalid is skipped, and nothing is - claimed. If no capacity is left, the error names the skipped policy. Each - release `DeviceWipe` names the pinned policy, so release does not need the - policy to exist. + and copies its name, generation, SHA-256 digest and spec into the + MachineAllocation. No spec holds the policy's UID: the copy and its digest + pin the content, so a policy deleted and recreated under the same name, even + at the same generation, changes no existing pin. Capacity whose policy is + missing or invalid is skipped, and nothing is claimed. If no capacity is + left, the error names the skipped policy. Each release `DeviceWipe` names + the pinned policy, so release does not need the policy to exist. - **Fixtures.** The standalone fixtures and the multi-plane seed create a `Clear` policy that overwrites and reads back, the only method the sites run. Synthetic staging ships a fixture policy that operators apply to the diff --git a/internal/allocation/allocator.go b/internal/allocation/allocator.go index aadbf314..20896853 100644 --- a/internal/allocation/allocator.go +++ b/internal/allocation/allocator.go @@ -485,5 +485,5 @@ func (a *Allocator) pinCleaning(ctx context.Context, capacity *fleetv1.MachineCa if err != nil { return ops.PinnedCleaningPolicy{}, err } - return ops.PinnedCleaningPolicy{CleaningPolicyReference: ops.CleaningPolicyReference{Name: policy.Name, UID: string(policy.UID), Digest: digest}, Spec: policy.Spec}, nil + return ops.PinnedCleaningPolicy{CleaningPolicyReference: ops.CleaningPolicyReference{Name: policy.Name, Generation: policy.Generation, Digest: digest}, Spec: policy.Spec}, nil } diff --git a/internal/allocation/cleaning_test.go b/internal/allocation/cleaning_test.go index edca1643..4599e351 100644 --- a/internal/allocation/cleaning_test.go +++ b/internal/allocation/cleaning_test.go @@ -37,7 +37,7 @@ func TestAllocationPinsItsCleaningPolicy(t *testing.T) { t.Fatal(err) } pinned := allocation.Spec.CleaningPolicy - if pinned.Name != policy.Name || pinned.UID != string(policy.UID) || pinned.Digest != digest || pinned.Spec.Rules[0].Name != "nvme-ssd" { + if pinned.Name != policy.Name || pinned.Generation != policy.Generation || pinned.Generation < 1 || pinned.Digest != digest || pinned.Spec.Rules[0].Name != "nvme-ssd" { t.Fatalf("pinned = %+v", pinned) } @@ -100,3 +100,48 @@ func TestCapacityWithoutAUsableCleaningPolicyIsNotAllocated(t *testing.T) { }) } } + +// TestARecreatedPolicyChangesNoPin recreates a policy under the same name +// with other content. The allocation keeps the copy and digest it pinned, its +// release wipes under that pin, and a new allocation pins the new content. +func TestARecreatedPolicyChangesNoPin(t *testing.T) { + e := startEnv(t) + e.server(1) + e.server(2) + first, err := e.allocator.Allocate(e.ctx, e.request(1)) + if err != nil { + t.Fatal(err) + } + original := first.Spec.CleaningPolicy + if err := e.admin.Delete(e.ctx, e.policy()); err != nil { + t.Fatal(err) + } + recreated := examplePolicy(namespace) + recreated.Spec.Rules[0].TimePerTiB.Duration *= 2 + e.create(recreated) + second, err := e.allocator.Allocate(e.ctx, e.request(2)) + if err != nil { + t.Fatal(err) + } + newDigest, err := cleaning.Digest(recreated.Spec) + if err != nil { + t.Fatal(err) + } + if second.Spec.CleaningPolicy.Name != original.Name || second.Spec.CleaningPolicy.Digest != newDigest || second.Spec.CleaningPolicy.Digest == original.Digest { + t.Fatalf("a new allocation must pin the recreated content: %+v", second.Spec.CleaningPolicy.CleaningPolicyReference) + } + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(first), first); err != nil { + t.Fatal(err) + } + if first.Spec.CleaningPolicy.CleaningPolicyReference != original.CleaningPolicyReference || first.Spec.CleaningPolicy.Spec.Rules[0].TimePerTiB != original.Spec.Rules[0].TimePerTiB { + t.Fatalf("the first allocation's pin changed: %+v", first.Spec.CleaningPolicy) + } + e.release(first, machine(1)) + wipe := &ops.DeviceWipe{} + if err := e.admin.Get(e.ctx, client.ObjectKey{Namespace: namespace, Name: custody.WipeName(first.Name, 1)}, wipe); err != nil { + t.Fatal(err) + } + if wipe.Spec.Policy != original.CleaningPolicyReference { + t.Fatalf("the release must wipe under the original pin: %+v, want %+v", wipe.Spec.Policy, original.CleaningPolicyReference) + } +} diff --git a/internal/api/operations/v1alpha1/cleaning.go b/internal/api/operations/v1alpha1/cleaning.go index c210ae03..68c1c08b 100644 --- a/internal/api/operations/v1alpha1/cleaning.go +++ b/internal/api/operations/v1alpha1/cleaning.go @@ -112,12 +112,14 @@ type VerifySpec struct { Samples int32 `json:"samples,omitempty"` } -// CleaningPolicyReference names one CleaningPolicy incarnation and the digest -// of its spec. +// CleaningPolicyReference pins a CleaningPolicy's content: its name, the +// generation the allocator read, and the digest of that spec. A policy +// recreated under the same name changes no pin, because every pin keeps its +// own copy and digest. type CleaningPolicyReference struct { - Name string `json:"name"` - UID string `json:"uid"` - Digest string `json:"digest"` + Name string `json:"name"` + Generation int64 `json:"generation"` + Digest string `json:"digest"` } // PinnedCleaningPolicy is the copy of a CleaningPolicy an allocation keeps, diff --git a/internal/coordination/transport_test.go b/internal/coordination/transport_test.go index 084e2955..98da74b8 100644 --- a/internal/coordination/transport_test.go +++ b/internal/coordination/transport_test.go @@ -116,7 +116,7 @@ func newFixture(t *testing.T) *rig { func (f *rig) wipe(fence int64, uid string) site.Assignment { spec := ops.DeviceWipeSpec{OperationEnvelope: ops.OperationEnvelope{Creator: ops.Creator{Username: "release", UID: "u"}, DeviceRef: ops.DeviceReference{Name: "server-example-001"}, Authority: ops.Authority{AllocationRef: &ops.LocalReference{Name: "alloc-example"}}}, - Step: 1, Policy: ops.CleaningPolicyReference{Name: "tenant-reuse-v1", UID: "policy-uid", Digest: "sha256:" + keyDigest}, TargetDisks: []string{"disk-0"}} + Step: 1, Policy: ops.CleaningPolicyReference{Name: "tenant-reuse-v1", Generation: 1, Digest: "sha256:" + keyDigest}, TargetDisks: []string{"disk-0"}} inputs, _ := json.Marshal(spec) digest, _ := custody.SpecDigest(spec) now := time.Now().UTC() diff --git a/internal/custody/admission_test.go b/internal/custody/admission_test.go index 4ecb20a5..411df7a1 100644 --- a/internal/custody/admission_test.go +++ b/internal/custody/admission_test.go @@ -83,7 +83,7 @@ func TestAdmissionPreconditions(t *testing.T) { named := &DeviceTestStaffOperation{ObjectMeta: metav1.ObjectMeta{GenerateName: "named-", Namespace: "default"}, Spec: testSpec{OperationEnvelope: envelope(device, staffUser, allocated("alloc-x")), Input: "a"}} e.create(named) // Staff cannot create the release kind either. - wipe := &ops.DeviceWipe{ObjectMeta: metav1.ObjectMeta{Name: WipeName("alloc-x", 1), Namespace: "default"}, Spec: ops.DeviceWipeSpec{OperationEnvelope: envelope(device, staffUser, allocated("alloc-x")), Step: 1, Policy: ops.CleaningPolicyReference{Name: "tenant-reuse-v1", UID: "policy-uid", Digest: policyDigest}, TargetDisks: []string{"disk-0"}}} + wipe := &ops.DeviceWipe{ObjectMeta: metav1.ObjectMeta{Name: WipeName("alloc-x", 1), Namespace: "default"}, Spec: ops.DeviceWipeSpec{OperationEnvelope: envelope(device, staffUser, allocated("alloc-x")), Step: 1, Policy: ops.CleaningPolicyReference{Name: "tenant-reuse-v1", Generation: 1, Digest: policyDigest}, TargetDisks: []string{"disk-0"}}} e.create(wipe) e.settle(device.Name) for _, operation := range []ops.Operation{spoof, service, named, wipe} { diff --git a/internal/custody/harness_test.go b/internal/custody/harness_test.go index 57649e44..c9bb40fe 100644 --- a/internal/custody/harness_test.go +++ b/internal/custody/harness_test.go @@ -349,7 +349,7 @@ func (e *env) installation(device *inventory.Device, allocation, request string) func (e *env) wipe(device *inventory.Device, allocation string, step int32) *ops.DeviceWipe { e.t.Helper() operation := &ops.DeviceWipe{ObjectMeta: metav1.ObjectMeta{Name: WipeName(allocation, step), Namespace: "default"}, Spec: ops.DeviceWipeSpec{ - OperationEnvelope: envelope(device, releaseUser, allocated(allocation)), Step: step, Policy: ops.CleaningPolicyReference{Name: "tenant-reuse-v1", UID: "policy-uid", Digest: policyDigest}, TargetDisks: []string{"disk-0"}, + OperationEnvelope: envelope(device, releaseUser, allocated(allocation)), Step: step, Policy: ops.CleaningPolicyReference{Name: "tenant-reuse-v1", Generation: 1, Digest: policyDigest}, TargetDisks: []string{"disk-0"}, }} e.create(operation) return operation @@ -359,7 +359,7 @@ func (e *env) wipe(device *inventory.Device, allocation string, step int32) *ops func (e *env) namedWipe(device *inventory.Device, allocation, name string, step int32) *ops.DeviceWipe { e.t.Helper() operation := &ops.DeviceWipe{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: "default"}, Spec: ops.DeviceWipeSpec{ - OperationEnvelope: envelope(device, releaseUser, allocated(allocation)), Step: step, Policy: ops.CleaningPolicyReference{Name: "tenant-reuse-v1", UID: "policy-uid", Digest: policyDigest}, TargetDisks: []string{"disk-0"}, + OperationEnvelope: envelope(device, releaseUser, allocated(allocation)), Step: step, Policy: ops.CleaningPolicyReference{Name: "tenant-reuse-v1", Generation: 1, Digest: policyDigest}, TargetDisks: []string{"disk-0"}, }} e.create(operation) return operation @@ -430,7 +430,7 @@ func (e *env) allocation(device *inventory.Device, name, phase string) *metal.Ma Accepted: metal.AcceptedContract{MachineClassRef: metal.ContentReference{Name: "class-example", Generation: 1, Digest: policyDigest}, MachineProfileRef: metal.ContentReference{Name: "profile-example", Generation: 1, Digest: policyDigest}, CPU: metal.CPURequirement{Architecture: "amd64", Cores: 2}, Memory: metal.MemoryRequirement{Capacity: "2Gi"}}, Authority: metal.AllocationAuthority{Principal: "fixture", Decision: "fixture-" + name}, - CleaningPolicy: ops.PinnedCleaningPolicy{CleaningPolicyReference: ops.CleaningPolicyReference{Name: "tenant-reuse-v1", UID: "policy-uid", Digest: policyDigest}, Spec: ops.CleaningPolicySpec{ + CleaningPolicy: ops.PinnedCleaningPolicy{CleaningPolicyReference: ops.CleaningPolicyReference{Name: "tenant-reuse-v1", Generation: 1, Digest: policyDigest}, Spec: ops.CleaningPolicySpec{ Assurance: ops.AssuranceClear, Rules: []ops.CleaningRule{{Name: "nvme-ssd", Match: ops.DriveMatch{Protocol: ops.ProtocolNVMe, MediaType: ops.MediaSSD}, Methods: []ops.CleaningMethod{ops.MethodOverwrite}, Verify: ops.VerifySpec{Mode: ops.VerifyFull}, TimePerTiB: metav1.Duration{Duration: time.Hour}}}, diff --git a/internal/site/redfishwork/kinds_test.go b/internal/site/redfishwork/kinds_test.go index 13373d9e..3468761b 100644 --- a/internal/site/redfishwork/kinds_test.go +++ b/internal/site/redfishwork/kinds_test.go @@ -238,7 +238,7 @@ func TestInstallationRunsBothPhasesWithOneOnEach(t *testing.T) { func TestWipeChecksTheEnrolledDisk(t *testing.T) { l := newLab(t) r := runner(t, l) - spec := ops.DeviceWipeSpec{Step: 1, Policy: ops.CleaningPolicyReference{Name: "tenant-reuse-v1", UID: "policy-uid", Digest: "sha256:" + strings.Repeat("b", 64)}, TargetDisks: []string{"disk-0"}} + spec := ops.DeviceWipeSpec{Step: 1, Policy: ops.CleaningPolicyReference{Name: "tenant-reuse-v1", Generation: 1, Digest: "sha256:" + strings.Repeat("b", 64)}, TargetDisks: []string{"disk-0"}} result, err := r.Run(context.Background(), assignment(l, "DeviceWipe", "op-wipe", 1, spec)) if err != nil { t.Fatal(err) diff --git a/internal/site/vmwork/kinds_test.go b/internal/site/vmwork/kinds_test.go index a8539eb2..c9895264 100644 --- a/internal/site/vmwork/kinds_test.go +++ b/internal/site/vmwork/kinds_test.go @@ -129,7 +129,7 @@ func installSpec() ops.DeviceInstallationSpec { } func wipeSpec() ops.DeviceWipeSpec { - return ops.DeviceWipeSpec{OperationEnvelope: envelope(), Step: 1, Policy: ops.CleaningPolicyReference{Name: "tenant-reuse-v1", UID: "policy-uid", Digest: "sha256:" + key}, TargetDisks: []string{"disk-0"}} + return ops.DeviceWipeSpec{OperationEnvelope: envelope(), Step: 1, Policy: ops.CleaningPolicyReference{Name: "tenant-reuse-v1", Generation: 1, Digest: "sha256:" + key}, TargetDisks: []string{"disk-0"}} } // TestInstallThenWipe installs directly, proves each phase by its receipt,