diff --git a/cmd/fleet-manager/synthetic.go b/cmd/fleet-manager/synthetic.go index ffcf86d2..d6bb8cfe 100644 --- a/cmd/fleet-manager/synthetic.go +++ b/cmd/fleet-manager/synthetic.go @@ -28,10 +28,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 @@ -96,8 +92,8 @@ func syntheticCustody(ctx context.Context, scheme *runtime.Scheme, providerConfi } coordinator := &custody.Coordinator{Client: coordinatorClient, Registry: registry, Sites: sites, Config: custody.Config{Namespace: namespace, Principals: principals}} log := ctrl.Log.WithName("custody") - cleaning := func(context.Context, string) (string, error) { return custody.SpecDigest(syntheticCleaningPolicy) } - projector := &capacity.Projector{Reader: projectorClient, Writer: projectorClient, Namespace: namespace, Cleaning: cleaning} + + projector := &capacity.Projector{Reader: projectorClient, Writer: projectorClient, Namespace: namespace, Cleaning: capacity.Policies(projectorClient, namespace)} loop := &delivery.Loop{Client: coordinatorClient, Coordinator: coordinator, Namespace: namespace, Capacity: projector, Courier: &delivery.Courier{Client: coordinatorClient, Registry: registry, Coordinator: coordinator, Sites: sites, Namespace: namespace}, OnError: func(err error) { log.Info("coordinator pass incomplete", "error", err.Error()) }} @@ -105,8 +101,7 @@ 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) }, - Capacity: &capacity.Projector{Reader: provider, Namespace: namespace, Cleaning: cleaning}, + Capacity: &capacity.Projector{Reader: provider, Namespace: namespace, Cleaning: capacity.Policies(provider, namespace)}, // The synthetic site enrolls one boot NIC and one disk per Device. BootInterface: "primary", TargetDisks: []string{"disk-0"}, Sites: sites, diff --git a/cmd/fleet-registration/main.go b/cmd/fleet-registration/main.go index 56c374a9..96dc479b 100644 --- a/cmd/fleet-registration/main.go +++ b/cmd/fleet-registration/main.go @@ -25,7 +25,7 @@ import ( ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" - "go.datum.net/fleet/internal/capacity" + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" "go.datum.net/fleet/internal/custody/creatorwebhook" "go.datum.net/fleet/internal/powerwebhook" ) @@ -57,7 +57,7 @@ func run(ctx context.Context, configFile, providers, powerWriter, cert, key, cli return err } scheme := runtime.NewScheme() - for _, add := range []func(*runtime.Scheme) error{clientgoscheme.AddToScheme, inventory.AddToScheme, metal.AddToScheme, resourcemanager.AddToScheme} { + for _, add := range []func(*runtime.Scheme) error{clientgoscheme.AddToScheme, inventory.AddToScheme, ops.AddToScheme, metal.AddToScheme, resourcemanager.AddToScheme} { if err := add(scheme); err != nil { return err } @@ -79,9 +79,6 @@ func run(ctx context.Context, configFile, providers, powerWriter, cert, key, cli } handler := registration.NewHandler(config.AuthorityID, projects, root, template, scheme) handler.Projectors = projectors - // No cleaning policy resolver exists yet: the cleaning policy owner - // provides it. Until then no registered capacity can be enabled. - handler.Cleaning = capacity.Unresolved tlsConfig, err := webhookTLS(clientCA, clients) if err != nil { return err diff --git a/cmd/fleet-standalone-smoke/main.go b/cmd/fleet-standalone-smoke/main.go index 8e5c1db5..9c13d1aa 100644 --- a/cmd/fleet-standalone-smoke/main.go +++ b/cmd/fleet-standalone-smoke/main.go @@ -35,9 +35,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,13 +78,12 @@ func main() { must(err) releaseCreator, err := allocation.Creator(ctx, releaseConfig) must(err) - offers := &capacity.Projector{Reader: provider, Namespace: options.ProviderNamespace, Cleaning: fixtureResolver} + offers := &capacity.Projector{Reader: provider, Namespace: options.ProviderNamespace, Cleaning: capacity.Policies(provider, options.ProviderNamespace)} allocator := &allocation.Allocator{ Provider: provider, ProviderCreator: providerCreator, Releaser: releaseClient, ReleaseCreator: releaseCreator, Custody: &custody.Coordinator{Client: coordinatorClient, Registry: registry, Config: custody.Config{Namespace: options.ProviderNamespace, Principals: principals()}}, Namespace: options.ProviderNamespace, - Cleaning: fixtureCleaning, Capacity: offers, // The fixture Device's boot NIC and the simulator's one enrolled disk. BootInterface: "primary", TargetDisks: []string{"disk-0"}, @@ -144,7 +140,7 @@ func coordinate(ctx context.Context, config *rest.Config, registry *custody.Regi } coordinator := &custody.Coordinator{Client: api, Registry: registry, Sites: sites, Config: custody.Config{Namespace: namespace, Principals: principals()}} logger := slog.New(slog.NewJSONHandler(os.Stderr, nil)) - projector := &capacity.Projector{Reader: projectorClient, Writer: projectorClient, Namespace: namespace, Cleaning: fixtureResolver} + projector := &capacity.Projector{Reader: projectorClient, Writer: projectorClient, Namespace: namespace, Cleaning: capacity.Policies(projectorClient, namespace)} loop := &delivery.Loop{Client: api, Coordinator: coordinator, Namespace: namespace, Capacity: projector, Courier: &delivery.Courier{Client: api, Registry: registry, Coordinator: coordinator, Sites: sites, Namespace: namespace}, OnError: func(err error) { logger.Info("coordinator pass incomplete", "error", err.Error()) }} logger.Info("custody coordinator running", "namespace", namespace, "site", siteName) @@ -177,26 +173,10 @@ func staff(ctx context.Context, config *rest.Config, author, approver, operator return out, nil } -// fixtureResolver is the projector's view of the fixture cleaning policy. -func fixtureResolver(_ context.Context, name string) (string, error) { - digest, err := fixtureCleaning(name) - if err != nil { - return "", capacity.ErrUnresolved - } - return digest, nil -} - 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 8b0e3082..ee0c9b84 100644 --- a/config/README.md +++ b/config/README.md @@ -71,15 +71,16 @@ 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, -recovery operator and power 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, 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 coordinator: the production manager has no provider, so -nothing creates custody operations there. See [device custody](../docs/development/device-custody.md#cutover-increment-c). +operation kinds, `CleaningPolicy`, their ProtectedResources, the coordinator, +requester, viewer, recovery operator, power 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 +coordinator: the production manager has no provider, so nothing creates +custody operations there. See [device custody](../docs/development/device-custody.md#cutover-increment-c). `config/base/bmc-discovery` runs read-only BMC discovery for one Milo project in a cluster that can reach the BMC network: one replica, no leader election, diff --git a/config/base/crd/metal.datumapis.com.yaml b/config/base/crd/metal.datumapis.com.yaml index e4c805c2..aa6844b7 100644 --- a/config/base/crd/metal.datumapis.com.yaml +++ b/config/base/crd/metal.datumapis.com.yaml @@ -375,7 +375,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: @@ -449,7 +449,69 @@ spec: required: [name] properties: name: {type: string, minLength: 1} - cleaningPolicyDigest: {type: string, pattern: '^sha256:[a-f0-9]{64}$'} + cleaningPolicy: + type: object + required: [name, generation, digest, spec] + properties: + name: {type: string, minLength: 1, maxLength: 253} + generation: {type: integer, format: int64, minimum: 1} + 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, pattern: '^([0-9]+(\.[0-9]+)?(ns|us|µs|μs|ms|s|m|h))+$'} + 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 61baf224..7c18f767 100644 --- a/config/components/device-operations/crds/fleet.datumapis.com.yaml +++ b/config/components/device-operations/crds/fleet.datumapis.com.yaml @@ -826,9 +826,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 + generation: + type: integer + format: int64 + minimum: 1 + digest: + type: string + pattern: ^sha256:[0-9a-f]{64}$ + required: + - name + - generation + - digest targetDisks: type: array minItems: 1 @@ -882,7 +897,7 @@ spec: - deviceRef - authority - step - - cleaningPolicyDigest + - policy - targetDisks x-kubernetes-validations: - rule: self == oldSelf @@ -2043,3 +2058,97 @@ spec: x-kubernetes-validations: - rule: self.metadata.name.startsWith(self.spec.planRef.name + '-') && size(self.metadata.name) == size(self.spec.planRef.name) + 17 message: an approval's name is its plan's name and a suffix derived from the plan's UID +--- +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, pattern: '^([0-9]+(\.[0-9]+)?(ns|us|µs|μs|ms|s|m|h))+$'} + 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 8f868515..b2471c04 100644 --- a/config/components/device-operations/protected-resources/kustomization.yaml +++ b/config/components/device-operations/protected-resources/kustomization.yaml @@ -6,6 +6,7 @@ resources: - devicewipe.yaml - devicepoweroperation.yaml - devicerecovery.yaml + - cleaningpolicy.yaml - devicecommissioning.yaml - devicecommissioningplan.yaml - devicecommissioningplanapproval.yaml diff --git a/config/components/device-operations/roles/capacity-projector.yaml b/config/components/device-operations/roles/capacity-projector.yaml index 4cbe39fb..964cc023 100644 --- a/config/components/device-operations/roles/capacity-projector.yaml +++ b/config/components/device-operations/roles/capacity-projector.yaml @@ -27,3 +27,4 @@ spec: - fleet.datumapis.com/devicecommissioningplanapprovals.get - fleet.datumapis.com/devicecommissioningplanapprovals.list - fleet.datumapis.com/devicecommissioningplanapprovals.watch + - fleet.datumapis.com/cleaningpolicies.get 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 0c78eeeb..9653241e 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 and the commissioning evidence it evaluates capacity from. + kubernetes.io/description: The Fleet provider for Metal. Creates DeviceInstallations from Installations, and pins cleaning policies, and reads custody and the commissioning evidence it evaluates capacity from. spec: launchStage: Alpha includedPermissions: @@ -15,6 +15,7 @@ spec: - fleet.datumapis.com/devicecustodies.get - fleet.datumapis.com/devicecustodies.list - fleet.datumapis.com/devicecustodies.watch + - fleet.datumapis.com/cleaningpolicies.get - fleet.datumapis.com/devices.get - fleet.datumapis.com/devices.list - fleet.datumapis.com/devices.watch diff --git a/config/components/device-operations/roles/kustomization.yaml b/config/components/device-operations/roles/kustomization.yaml index 75a3be27..3f974f77 100644 --- a/config/components/device-operations/roles/kustomization.yaml +++ b/config/components/device-operations/roles/kustomization.yaml @@ -6,6 +6,7 @@ resources: - recovery-operator.yaml - installation-requester.yaml - wipe-requester.yaml + - cleaning-policy-admin.yaml - device-commissioning-operator.yaml - device-commissioning-plan-author.yaml - device-commissioning-plan-approver.yaml diff --git a/config/components/device-operations/roles/viewer.yaml b/config/components/device-operations/roles/viewer.yaml index 0be137c2..ba168a7b 100644 --- a/config/components/device-operations/roles/viewer.yaml +++ b/config/components/device-operations/roles/viewer.yaml @@ -23,6 +23,9 @@ 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 - fleet.datumapis.com/devicecommissionings.get - fleet.datumapis.com/devicecommissionings.list - fleet.datumapis.com/devicecommissionings.watch diff --git a/config/components/device-operations/webhook.yaml b/config/components/device-operations/webhook.yaml index 04c2f8d6..b32721d7 100644 --- a/config/components/device-operations/webhook.yaml +++ b/config/components/device-operations/webhook.yaml @@ -24,3 +24,19 @@ webhooks: # policy; TestPackagedResourcesMatch keeps them in step. resources: [deviceinstallations, devicewipes, devicepoweroperations, devicerecoveries, devicecommissionings, devicecommissioningplans, devicecommissioningplanapprovals] 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] + resources: [cleaningpolicies] + scope: Namespaced 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/config/standalone/fixtures.yaml b/config/standalone/fixtures.yaml index 5489f150..b17311da 100644 --- a/config/standalone/fixtures.yaml +++ b/config/standalone/fixtures.yaml @@ -32,6 +32,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 f7a4b957..91696bfe 100644 --- a/config/standalone/rbac.yaml +++ b/config/standalone/rbac.yaml @@ -43,6 +43,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] @@ -234,6 +237,9 @@ apiVersion: rbac.authorization.k8s.io/v1 kind: Role metadata: {name: fleet-capacity-projector, namespace: fleet-provider} rules: + - apiGroups: [fleet.datumapis.com] + resources: [cleaningpolicies] + verbs: [get] - apiGroups: [metal.datumapis.com] resources: [machinecapacities] verbs: [get, list] diff --git a/docs/development/README.md b/docs/development/README.md index 4f212500..80e45df0 100644 --- a/docs/development/README.md +++ b/docs/development/README.md @@ -498,6 +498,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 b6d72074..6025e90a 100644 --- a/docs/development/device-custody.md +++ b/docs/development/device-custody.md @@ -183,10 +183,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, the pinned cleaning policy - 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 @@ -773,10 +774,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).** Settled by commissioning: see [Capacity status](#capacity-status). @@ -819,6 +817,44 @@ 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`, 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, 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 + 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 +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 @@ -1092,9 +1128,9 @@ inputs, and nothing else writes them. name is derived from the plan's UID, so evidence under a plan recreated with the same name and content proves nothing (`PlanChanged`). - **Cleaning policy.** The projector takes a resolver that returns a digest, - `ErrUnresolved`, or another error, which makes `Available` `Unknown`. Every - mode supplies a fixture resolver for its one fixture policy. No production - resolver exists yet; it belongs to the cleaning policy owner. + `ErrUnresolved`, or another error, which makes `Available` `Unknown`. Standalone, synthetic staging and the multi-plane lab read and validate the + named CleaningPolicy in the provider namespace. The allocator re-reads it + before pinning its exact content. - **Simulated commissioning.** The simulator site runs a `DeviceCommissioning` worker that inspects the hardware and firmware its enrollment records for the Device. Its burn-in sends nothing and takes no time: it journals one diff --git a/docs/development/inventory-capacity-registration.md b/docs/development/inventory-capacity-registration.md index ed213b26..d2a011ec 100644 --- a/docs/development/inventory-capacity-registration.md +++ b/docs/development/inventory-capacity-registration.md @@ -595,7 +595,7 @@ Environment-owned inputs, none of which this repository supplies: 1. Keep the existing `fleet-manager-config` authority and discovery paths. Supply `fleet-registration-milo-kubeconfig` (Project reads) and `fleet-registration-project-kubeconfig` (Device and capacity get/list - across the complete provider scope, and SubjectAccessReview create). It + across the complete provider scope, CleaningPolicy get, and SubjectAccessReview create). It needs no public writes, allocation permissions or provider credentials. 2. Supply `fleet-registration-tls` with `tls.crt`, `tls.key` and a dedicated `client-ca.crt`. Configure Milo's admission webhook client with an @@ -702,12 +702,10 @@ or while the capacity is `Disabled`. It is frozen while the capacity is capacity being disabled first. **The cleaning policy.** The webhook resolves the policy name through a -resolver that returns a digest, `ErrUnresolved`, or another error. Fleet owns -the production cleaning-policy resolver. It is built on the cleaning policy -pinned at allocation ([#183](https://github.com/datum-cloud/fleet/pull/183), -[#193](https://github.com/datum-cloud/fleet/pull/193)) and lands with the -cleaning stack. Until then the webhook uses one that resolves nothing, so no -registered capacity can be enabled in production. +resolver that returns a digest, `ErrUnresolved`, or another error. The webhook reads the named CleaningPolicy with its provider-project client in the +capacity namespace and validates the spec. Missing or invalid policy denies enablement; +a failed read is not evidence of a usable policy. The allocator separately pins the +policy it reads at allocation time. ### The duplicate race diff --git a/docs/operations/multiplane.md b/docs/operations/multiplane.md index 26f2551e..3c34c74e 100644 --- a/docs/operations/multiplane.md +++ b/docs/operations/multiplane.md @@ -645,7 +645,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/hack/multiplane/milo.py b/hack/multiplane/milo.py index cd03188f..6e8849c8 100755 --- a/hack/multiplane/milo.py +++ b/hack/multiplane/milo.py @@ -183,6 +183,7 @@ def write(obj): 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','devicecommissionings','devicecommissioningplans','devicecommissioningplanapprovals'],'verbs':['get','list','watch']}] + rules.append({'apiGroups':['fleet.datumapis.com'],'resources':['cleaningpolicies'],'verbs':['get']}) # Synchronized lab DHCP claims boot addresses from IPAM, which asks this # API to authorize each request. Each requester claims and releases its # own boot addresses, and reads allocations to confirm a release; the @@ -200,7 +201,7 @@ def write(obj): {'apiGroups':['metal.datumapis.com'],'resources':['machineallocations'],'verbs':['get','list','watch']}]+([{'apiGroups':['ipam.miloapis.com'],'resources':['ipclaims'],'verbs':['get']}] if with_ipam else []), 'release':[{'apiGroups':['fleet.datumapis.com'],'resources':['devicewipes'],'verbs':['get','create']}]+([claims,allocations,{'apiGroups':['fleet.datumapis.com'],'resources':['devicecustodies'],'verbs':['get']}] if with_ipam else []), # The capacity projector is the only writer of capacity status. - 'projector':[{'apiGroups':['metal.datumapis.com'],'resources':['machinecapacities'],'verbs':['get','list','watch']},{'apiGroups':['metal.datumapis.com'],'resources':['machinecapacities/status'],'verbs':['get','update']}, + 'projector':[{'apiGroups':['fleet.datumapis.com'],'resources':['cleaningpolicies'],'verbs':['get']},{'apiGroups':['metal.datumapis.com'],'resources':['machinecapacities'],'verbs':['get','list','watch']},{'apiGroups':['metal.datumapis.com'],'resources':['machinecapacities/status'],'verbs':['get','update']}, {'apiGroups':['fleet.datumapis.com'],'resources':['devices','devicecustodies','devicecommissionings','devicecommissioningplans','devicecommissioningplanapprovals'],'verbs':['get','list','watch']}], # Three people commission a server: one writes the plan, another approves # it, and an operator commissions the Device. diff --git a/internal/allocation/allocator.go b/internal/allocation/allocator.go index 34d3ab3f..2f1c95e3 100644 --- a/internal/allocation/allocator.go +++ b/internal/allocation/allocator.go @@ -33,6 +33,7 @@ import ( fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" "go.datum.net/fleet/internal/bootaddress" "go.datum.net/fleet/internal/capacity" + "go.datum.net/fleet/internal/cleaning" "go.datum.net/fleet/internal/custody" "go.datum.net/fleet/internal/tenancy" ) @@ -52,6 +53,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 = capacity.ErrUnresolved // ErrBootClaimsFull means the allocation's boot claim record is full: // no new boot claim is made until earlier ones are verified released. ErrBootClaimsFull = errors.New("the allocation's boot claims are not yet verified released, so no new boot claim is made") @@ -110,10 +114,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) - // Offers evaluates, from live inputs, whether a capacity may be offered and // the hardware its latest passed commissioning inspected. The capacity // projector implements it. The allocator never reads capacity conditions, so @@ -146,7 +146,6 @@ type Allocator struct { // in it too. Namespace string Quota Quota - Cleaning CleaningPolicies // Capacity decides which capacity may be offered. Capacity Offers // BootInterface and TargetDisks are pinned on each allocation. @@ -260,6 +259,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 { @@ -274,11 +274,21 @@ func (a *Allocator) Allocate(ctx context.Context, request Request) (*fleetv1.Mac continue } candidate, device, hardware, 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 } tried[candidate.Name] = true - allocation, err = a.newAllocation(request, candidate, device, hardware, claim) + allocation, err = a.newAllocation(ctx, request, candidate, device, hardware, claim) + if errors.Is(err, ErrCleaningUncovered) { + // Capacity without a usable cleaning policy is not eligible. + // Nothing was claimed; try the next candidate, and report why + // if none is left. + uncovered = err + continue + } if err != nil { return nil, err } @@ -402,6 +412,7 @@ func (a *Allocator) candidate(ctx context.Context, request Request, tried map[st offer = passes.Pass() } var failed error + var uncovered error for index := range capacities.Items { capacity := &capacities.Items[index] if tried[capacity.Name] || capacity.Spec.AllocationPolicy != "Enabled" || !capacity.DeletionTimestamp.IsZero() || !selector.Matches(labels.Set(capacity.Labels)) { @@ -434,6 +445,10 @@ func (a *Allocator) candidate(ctx context.Context, request Request, tried map[st continue } offered, hardware, err := offer(ctx, capacity) + if errors.Is(err, ErrCleaningUncovered) { + uncovered = fmt.Errorf("capacity %s: %w", capacity.Name, err) + continue + } if err != nil { failed = errors.Join(failed, fmt.Errorf("capacity %s: %w", capacity.Name, err)) continue @@ -446,6 +461,9 @@ func (a *Allocator) candidate(ctx context.Context, request Request, tried map[st if failed != nil { return nil, nil, fleetv1.Hardware{}, failed } + if uncovered != nil { + return nil, nil, fleetv1.Hardware{}, fmt.Errorf("%w; skipped: %w", ErrInsufficientCapacity, uncovered) + } return nil, nil, fleetv1.Hardware{}, ErrInsufficientCapacity } @@ -457,13 +475,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, hardware fleetv1.Hardware, 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, hardware fleetv1.Hardware, 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 { @@ -488,11 +503,11 @@ func (a *Allocator) newAllocation(request Request, capacity *fleetv1.MachineCapa CPU: request.Profile.Spec.CPU, Memory: request.Profile.Spec.Memory, }, - Hardware: hardware, - Authority: request.Authority, - CleaningPolicyDigest: digest, - BootInterface: a.BootInterface, - TargetDisks: slices.Clone(a.TargetDisks), + Hardware: hardware, + Authority: request.Authority, + CleaningPolicy: policy, + BootInterface: a.BootInterface, + TargetDisks: slices.Clone(a.TargetDisks), }, } if claim != "" { @@ -816,3 +831,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, Generation: policy.Generation, Digest: digest}, Spec: policy.Spec}, nil +} diff --git a/internal/allocation/capacity_test.go b/internal/allocation/capacity_test.go index 98aeec47..2bd76cec 100644 --- a/internal/allocation/capacity_test.go +++ b/internal/allocation/capacity_test.go @@ -168,7 +168,7 @@ func TestAnAllocationOnDisabledCapacityIsWithdrawn(t *testing.T) { e := startEnv(t) device := e.server(1) capacity := e.capacity(device.Name) - stale, err := e.allocator.newAllocation(e.request(1), capacity, device, fleetv1.Hardware{}, "") + stale, err := e.allocator.newAllocation(e.ctx, e.request(1), capacity, device, fleetv1.Hardware{}, "") if err != nil { t.Fatal(err) } @@ -195,7 +195,7 @@ func TestARecreatedDeviceIsNotClaimed(t *testing.T) { e := startEnv(t) device := e.server(1) capacity := e.capacity(device.Name) - stale, err := e.allocator.newAllocation(e.request(1), capacity, device, fleetv1.Hardware{}, "") + stale, err := e.allocator.newAllocation(e.ctx, e.request(1), capacity, device, fleetv1.Hardware{}, "") if err != nil { t.Fatal(err) } @@ -375,7 +375,7 @@ func TestDisablingAfterTheLastCheckDoesNotStopTheClaim(t *testing.T) { e := startEnv(t) device := e.server(1) capacity := e.capacity(device.Name) - allocation, err := e.allocator.newAllocation(e.request(1), capacity, device, fleetv1.Hardware{}, "") + allocation, err := e.allocator.newAllocation(e.ctx, e.request(1), capacity, device, fleetv1.Hardware{}, "") if err != nil { t.Fatal(err) } diff --git a/internal/allocation/cleaning_test.go b/internal/allocation/cleaning_test.go new file mode 100644 index 00000000..4599e351 --- /dev/null +++ b/internal/allocation/cleaning_test.go @@ -0,0 +1,147 @@ +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.Generation != policy.Generation || pinned.Generation < 1 || 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) || !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) + } + if holder := e.custody(device.Name).Spec.Holder.Type; holder != ops.HolderNone { + t.Fatalf("holder = %s, want None", holder) + } + }) + } +} + +// 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/allocation/flow_test.go b/internal/allocation/flow_test.go index f50804d9..1108a920 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, fleetv1.Hardware{}, "") + stale, err := e.allocator.newAllocation(context.Background(), e.request(2), e.capacity(taken.Name), taken, fleetv1.Hardware{}, "") if err != nil { t.Fatal(err) } diff --git a/internal/allocation/harness_test.go b/internal/allocation/harness_test.go index 540b4f34..3be9a220 100644 --- a/internal/allocation/harness_test.go +++ b/internal/allocation/harness_test.go @@ -36,14 +36,14 @@ import ( ) const ( - namespace = "fleet-provider" - providerUser = "system:serviceaccount:fleet-system:metal-provider" - releaseUser = "system:serviceaccount:fleet-system:release-controller" - siteName = "site-example-a" - siteToken = "synthetic-site-token" - keyDigest = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - imageRef = "debian-12@sha256:9f4ad8d8b8a6f6fc64d2cf2c7e70b9184b74f089adf8c36d84f4fcb99892f3cb" - policyDigest = "sha256:0c2b77e1d9a4000000000000000000000000000000000000000000000000cafe" + fixtureDigest = "sha256:0c2b77e1d9a4000000000000000000000000000000000000000000000000cafe" + namespace = "fleet-provider" + providerUser = "system:serviceaccount:fleet-system:metal-provider" + releaseUser = "system:serviceaccount:fleet-system:release-controller" + siteName = "site-example-a" + siteToken = "synthetic-site-token" + keyDigest = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + imageRef = "debian-12@sha256:9f4ad8d8b8a6f6fc64d2cf2c7e70b9184b74f089adf8c36d84f4fcb99892f3cb" ) func uid(n int) string { return fmt.Sprintf("00000000-0000-4000-8000-%012d", n) } @@ -134,14 +134,13 @@ func startEnvWith(t *testing.T, crds ...*apiextensionsv1.CustomResourceDefinitio coordinator := &custody.Coordinator{Client: admin, Registry: registry, Sites: sites, Config: custody.Config{Namespace: namespace, Principals: custody.Principals{ custody.CreatorMetalProvider: {{Username: providerUser}}, custody.CreatorReleaseController: {{Username: releaseUser}}, }}} - e.projector = &capacity.Projector{Reader: admin, Writer: admin, Namespace: namespace, Cleaning: capacity.Fixed(map[string]string{"example-cleaning": policyDigest})} + e.projector = &capacity.Projector{Reader: admin, Writer: admin, Namespace: namespace, Cleaning: capacity.Policies(admin, namespace)} e.loop = &delivery.Loop{Client: admin, Coordinator: coordinator, Namespace: namespace, Capacity: e.projector, Courier: &delivery.Courier{Client: admin, Registry: registry, Coordinator: coordinator, Sites: sites, Namespace: namespace}} e.allocator = &Allocator{ 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 }, Capacity: e.projector, BootInterface: "primary", TargetDisks: []string{"disk-0"}, Sites: sites, @@ -154,7 +153,7 @@ func startEnvWith(t *testing.T, crds ...*apiextensionsv1.CustomResourceDefinitio Content: ops.CommissioningPlanContent{ Inspection: ops.CommissioningInspection{CPU: ops.InspectionCPU{Architecture: "amd64", Cores: 2}, Memory: ops.InspectionValue{Capacity: "2Gi"}, Disks: ops.InspectionDisks{Count: 1, MinCapacity: "2Gi"}, Interfaces: ops.InspectionCount{Count: 1}}, - BurnIn: ops.CommissioningBurnIn{Image: ops.ImageInput{Name: "burn-in", Digest: policyDigest}, Duration: metav1.Duration{Duration: time.Minute}}, + BurnIn: ops.CommissioningBurnIn{Image: ops.ImageInput{Name: "burn-in", Digest: fixtureDigest}, Duration: metav1.Duration{Duration: time.Minute}}, }, EvidenceLifetime: metav1.Duration{Duration: 24 * time.Hour}, }} @@ -166,6 +165,7 @@ func startEnvWith(t *testing.T, crds ...*apiextensionsv1.CustomResourceDefinitio e.create(approval) 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 @@ -281,3 +281,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 077c8cf4..9cac76c3 100644 --- a/internal/allocation/release.go +++ b/internal/allocation/release.go @@ -345,11 +345,11 @@ 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), - BootInterface: allocation.Spec.BootInterface, + OperationEnvelope: a.envelope(allocation, a.ReleaseCreator), + Step: reference.Step, + Policy: allocation.Spec.CleaningPolicy.CleaningPolicyReference, + TargetDisks: slices.Clone(allocation.Spec.TargetDisks), + BootInterface: allocation.Spec.BootInterface, }, } // An existing wipe keeps the boot address it was created with, which may diff --git a/internal/allocation/release_test.go b/internal/allocation/release_test.go index b08bd082..4cc89e04 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, fleetv1.Hardware{}, "fleet-machine-601") + orphan, err := e.allocator.newAllocation(context.Background(), e.request(1), e.capacity(device.Name), device, fleetv1.Hardware{}, "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..68c1c08b --- /dev/null +++ b/internal/api/operations/v1alpha1/cleaning.go @@ -0,0 +1,139 @@ +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 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"` + Generation int64 `json:"generation"` + 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 39401e5a..e8c5b7aa 100644 --- a/internal/api/operations/v1alpha1/config_test.go +++ b/internal/api/operations/v1alpha1/config_test.go @@ -73,7 +73,7 @@ func loadCRDs(t *testing.T) map[string]*extensionsv1.CustomResourceDefinition { func TestCRDContract(t *testing.T) { crds := loadCRDs(t) - if len(crds) != 1+len(operationKinds)+len(planKinds) || crds["DeviceCustody"] == nil { + if len(crds) != 2+len(operationKinds)+len(planKinds) || crds["DeviceCustody"] == nil || crds["CleaningPolicy"] == nil { t.Fatalf("got %d CRDs, want DeviceCustody, the operation kinds and the plan kinds", len(crds)) } for kind, crd := range crds { @@ -90,6 +90,11 @@ func TestCRDContract(t *testing.T) { if version.Subresources != nil || len(properties["status"].Properties) != 0 { t.Fatal("DeviceCustody has no status") } + } else if kind == "CleaningPolicy" { + spec := properties["spec"] + if version.Subresources != nil || len(properties["status"].Properties) != 0 || len(spec.XValidations) != 1 || spec.XValidations[0].Rule != "self == oldSelf" { + t.Fatal("CleaningPolicy requires an immutable spec and no status") + } } else if slices.Contains(planKinds, kind) { spec := properties["spec"] if version.Subresources != nil || len(properties["status"].Properties) != 0 || !slices.Contains(spec.Required, "creator") { @@ -230,7 +235,8 @@ 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+"devicepoweroperations", read...), p(group+"devicerecoveries", read...), + "fleet.datumapis.com-cleaning-policy-admin": p(group+"cleaningpolicies", "create", "get", "list", "watch", "delete"), + "fleet.datumapis.com-device-operations-viewer": slices.Concat(p(group+"cleaningpolicies", read...), p(group+"devicecustodies", read...), p(group+"deviceinstallations", read...), p(group+"devicewipes", read...), p(group+"devicepoweroperations", read...), p(group+"devicerecoveries", read...), p(group+"devicecommissionings", read...), p(group+"devicecommissioningplans", read...), p(group+"devicecommissioningplanapprovals", read...)), "fleet.datumapis.com-device-commissioning-operator": p(group+"devicecommissionings", "create"), "fleet.datumapis.com-device-commissioning-plan-author": p(group+"devicecommissioningplans", "create", "delete"), @@ -238,9 +244,9 @@ func TestRolesKeepOneWriterAndKeepStaffFromCustomerSecrets(t *testing.T) { "fleet.datumapis.com-device-power-operator": p(group+"devicepoweroperations", "create"), "fleet.datumapis.com-device-power-requester": slices.Concat(p(group+"devicepoweroperations", "create", "get", "list", "watch"), p(group+"devicecustodies", 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+"cleaningpolicies", "get"), p(group+"deviceinstallations", "create", "get", "list", "watch"), p(group+"devicecustodies", read...), p(group+"devices", read...), p(group+"devicecommissionings", read...), p(group+"devicecommissioningplans", read...), p(group+"devicecommissioningplanapprovals", read...)), - "fleet.datumapis.com-capacity-projector": slices.Concat(p("metal.datumapis.com/machinecapacities", "get", "list", "watch", "updateStatus"), p(group+"devices", read...), p(group+"devicecustodies", read...), + "fleet.datumapis.com-capacity-projector": slices.Concat(p(group+"cleaningpolicies", "get"), p("metal.datumapis.com/machinecapacities", "get", "list", "watch", "updateStatus"), p(group+"devices", read...), p(group+"devicecustodies", read...), p(group+"devicecommissionings", read...), p(group+"devicecommissioningplans", read...), p(group+"devicecommissioningplanapprovals", read...)), "fleet.datumapis.com-device-wipe-requester": slices.Concat(p(group+"devicewipes", "create", "get", "list", "watch"), p(group+"devicecustodies", read...)), } @@ -551,3 +557,24 @@ func TestBootAddressRolesAreOptIn(t *testing.T) { t.Fatal(err) } } + +// 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/api/operations/v1alpha1/types.go b/internal/api/operations/v1alpha1/types.go index ed8da18a..d7d1efab 100644 --- a/internal/api/operations/v1alpha1/types.go +++ b/internal/api/operations/v1alpha1/types.go @@ -19,7 +19,7 @@ import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" - fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/api" ) var GroupVersion = schema.GroupVersion{Group: "fleet.datumapis.com", Version: "v1alpha1"} @@ -397,7 +397,7 @@ type BootNetworkInput struct { // and its only name. Admission picks its check by the group and kind. // The claim's incarnation is pinned by that name, its labels, and its // creation no later than the operation's; no UID is held in spec. - AddressClaim fleetv1.TypedReference `json:"addressClaim"` + AddressClaim api.TypedReference `json:"addressClaim"` // Address is the bound host address, without a prefix length. Address string `json:"address"` } @@ -450,10 +450,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"` // BootInterface names the Device interface the wipe network-boots. // Admission requires it; the schema leaves it optional so wipes stored // before it existed stay valid. @@ -572,7 +571,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{}) if err := addPower(s); err != nil { return err } diff --git a/internal/api/reference.go b/internal/api/reference.go new file mode 100644 index 00000000..cb73122d --- /dev/null +++ b/internal/api/reference.go @@ -0,0 +1,10 @@ +package api + +// TypedReference names an object by API group, kind and name, with no UID, +// in the shape of Milo's ResourceClaim consumerRef. An empty APIGroup is the +// core group. +type TypedReference struct { + APIGroup string `json:"apiGroup"` + Kind string `json:"kind"` + Name string `json:"name"` +} diff --git a/internal/api/v1alpha1/types.go b/internal/api/v1alpha1/types.go index 03fe31b4..22b9a751 100644 --- a/internal/api/v1alpha1/types.go +++ b/internal/api/v1alpha1/types.go @@ -2,6 +2,9 @@ package v1alpha1 import ( "encoding/json" + "go.datum.net/fleet/internal/api" + + 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" @@ -371,9 +374,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"` @@ -390,14 +393,7 @@ const ( LabelDeviceUID = "fleet.datumapis.com/device-uid" ) -// TypedReference names an object by API group, kind and name, with no UID, -// in the shape of Milo's ResourceClaim consumerRef. An empty APIGroup is the -// core group. -type TypedReference struct { - APIGroup string `json:"apiGroup"` - Kind string `json:"kind"` - Name string `json:"name"` -} +type TypedReference = api.TypedReference // AllocatedMachineReference names the Machine within its consumer. The // incarnation is in the allocation's name and labels. diff --git a/internal/capacity/projector.go b/internal/capacity/projector.go index c4aa62ba..a3784935 100644 --- a/internal/capacity/projector.go +++ b/internal/capacity/projector.go @@ -19,6 +19,7 @@ import ( inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" ops "go.datum.net/fleet/internal/api/operations/v1alpha1" metal "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/cleaning" "go.datum.net/fleet/internal/custody" apiequality "k8s.io/apimachinery/pkg/api/equality" apierrors "k8s.io/apimachinery/pkg/api/errors" @@ -39,6 +40,25 @@ var ErrUnresolved = errors.New("the cleaning policy does not resolve") // current digest. The cleaning policy owner provides it. type CleaningResolver func(ctx context.Context, name string) (string, error) +func Policies(reader client.Reader, namespace string) CleaningResolver { + return func(ctx context.Context, name string) (string, error) { + if name == "" { + return "", ErrUnresolved + } + policy := &ops.CleaningPolicy{} + if err := reader.Get(ctx, client.ObjectKey{Namespace: namespace, Name: name}, policy); err != nil { + if apierrors.IsNotFound(err) { + return "", ErrUnresolved + } + return "", err + } + if err := cleaning.Validate(policy.Spec); err != nil { + return "", fmt.Errorf("%w: %v", ErrUnresolved, err) + } + return cleaning.Digest(policy.Spec) + } +} + // Unresolved is the resolver to use until the cleaning policy owner provides // one: no name resolves, so no capacity is Available. func Unresolved(context.Context, string) (string, error) { return "", ErrUnresolved } @@ -274,6 +294,9 @@ func (p *Projector) Offer(ctx context.Context, capacity *metal.MachineCapacity) if err != nil { return false, metal.Hardware{}, err } + if available := apiMeta.FindStatusCondition(projection.Conditions, custody.ConditionAvailable); available != nil && available.Reason == "CleaningPolicyUnresolved" { + return false, metal.Hardware{}, fmt.Errorf("%w: %s", ErrUnresolved, capacity.Spec.CleaningPolicyRef.Name) + } return projection.Available(), hardware(projection.Hardware), nil } diff --git a/internal/cleaning/envtest_test.go b/internal/cleaning/envtest_test.go new file mode 100644 index 00000000..288fb021 --- /dev/null +++ b/internal/cleaning/envtest_test.go @@ -0,0 +1,113 @@ +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" + 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" + 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) + } + // The schema refuses a time bound that is not a duration, so no stored + // policy fails to decode. + 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 { + 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/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) + } +} 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..4ed7a1c3 --- /dev/null +++ b/internal/cleaning/webhook.go @@ -0,0 +1,38 @@ +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 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 { + 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..6bbcb695 --- /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}, + {"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}, + {"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 8d65e797..0fc0d61f 100644 --- a/internal/coordination/transport_test.go +++ b/internal/coordination/transport_test.go @@ -117,7 +117,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", 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 c2f6af04..88450467 100644 --- a/internal/custody/admission_test.go +++ b/internal/custody/admission_test.go @@ -99,7 +99,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"}, BootInterface: "primary"}} + 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"}, BootInterface: "primary"}} e.create(wipe) e.settle(device.Name) for _, operation := range []ops.Operation{spoof, service, named, wipe} { @@ -361,7 +361,7 @@ func TestAdmissionPreconditions(t *testing.T) { } wipeFence := e.custody(releasing.Name).Spec.Fence wipe := &ops.DeviceWipe{ObjectMeta: metav1.ObjectMeta{Name: WipeName("alloc-net-wipe", 1), Namespace: "default"}, Spec: ops.DeviceWipeSpec{ - OperationEnvelope: envelope(releasing, releaseUser, allocated("alloc-net-wipe")), Step: 1, CleaningPolicyDigest: policyDigest, TargetDisks: []string{"disk-0"}, BootInterface: "absent", + OperationEnvelope: envelope(releasing, releaseUser, allocated("alloc-net-wipe")), Step: 1, Policy: ops.CleaningPolicyReference{Name: "tenant-reuse-v1", Generation: 1, Digest: policyDigest}, TargetDisks: []string{"disk-0"}, BootInterface: "absent", }} e.create(wipe) e.settle(releasing.Name) diff --git a/internal/custody/creatorwebhook/envtest_test.go b/internal/custody/creatorwebhook/envtest_test.go index 6bcc6aa7..eda4d2b6 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/creatorwebhook/packaged_test.go b/internal/custody/creatorwebhook/packaged_test.go index 39cc4634..59436f42 100644 --- a/internal/custody/creatorwebhook/packaged_test.go +++ b/internal/custody/creatorwebhook/packaged_test.go @@ -30,6 +30,9 @@ func TestPackagedResourcesMatch(t *testing.T) { } var registered []string for _, webhook := range webhooks.Webhooks { + if webhook.Name != "creator.operations.fleet.datumapis.com" { + continue + } for _, rule := range webhook.Rules { registered = append(registered, rule.Resources...) } diff --git a/internal/custody/creatorwebhook/resources_test.go b/internal/custody/creatorwebhook/resources_test.go index 93860eea..2be9674a 100644 --- a/internal/custody/creatorwebhook/resources_test.go +++ b/internal/custody/creatorwebhook/resources_test.go @@ -21,7 +21,7 @@ var governed = []string{ } // TestEveryOperationKindIsGoverned requires the webhook's resource list to -// name every kind the custody CRDs define except DeviceCustody, so a new kind +// name every kind except DeviceCustody and CleaningPolicy, so a new kind // cannot ship with an unchecked creator. TestPackagedResourcesMatch keeps the // packaged webhook and standalone's policy in step with the list. func TestEveryOperationKindIsGoverned(t *testing.T) { @@ -32,7 +32,7 @@ func TestEveryOperationKindIsGoverned(t *testing.T) { if err := yaml.Unmarshal(document, &crd); err != nil { t.Fatal(err) } - if crd.Spec.Names.Kind != "DeviceCustody" { + if crd.Spec.Names.Kind != "DeviceCustody" && crd.Spec.Names.Kind != "CleaningPolicy" { kinds = append(kinds, crd.Spec.Names.Plural) } } diff --git a/internal/custody/harness_test.go b/internal/custody/harness_test.go index ff77e192..ed5f2ccc 100644 --- a/internal/custody/harness_test.go +++ b/internal/custody/harness_test.go @@ -369,7 +369,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"}, BootInterface: "primary", + OperationEnvelope: envelope(device, releaseUser, allocated(allocation)), Step: step, Policy: ops.CleaningPolicyReference{Name: "tenant-reuse-v1", Generation: 1, Digest: policyDigest}, TargetDisks: []string{"disk-0"}, BootInterface: "primary", }} e.create(operation) return operation @@ -399,7 +399,7 @@ func (e *env) ipClaim(name, operation, kind, phase, address string) *unstructure 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"}, BootInterface: "primary", + OperationEnvelope: envelope(device, releaseUser, allocated(allocation)), Step: step, Policy: ops.CleaningPolicyReference{Name: "tenant-reuse-v1", Generation: 1, Digest: policyDigest}, TargetDisks: []string{"disk-0"}, BootInterface: "primary", }} e.create(operation) return operation @@ -469,10 +469,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", 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}}}, + }}, + BootInterface: "primary", + TargetDisks: []string{"disk-0"}, }} e.create(allocation) if phase != "" { diff --git a/internal/manager/customer_power_envtest_test.go b/internal/manager/customer_power_envtest_test.go index 669c28ed..70df3f2d 100644 --- a/internal/manager/customer_power_envtest_test.go +++ b/internal/manager/customer_power_envtest_test.go @@ -130,10 +130,15 @@ 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, Sites: sites, Namespace: namespace, - Cleaning: func(string) (string, error) { return policyDigest, nil }, + BootInterface: "primary", TargetDisks: []string{"disk-0"}, Capacity: fixtureOffers{}, } + e.create(&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}}}, + }}) 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.profile = &fleetv1.MachineProfile{ObjectMeta: metav1.ObjectMeta{Name: "profile-example"}, Spec: fleetv1.MachineProfileSpec{CPU: fleetv1.CPURequirement{Architecture: "amd64", Cores: 2}, Memory: fleetv1.MemoryRequirement{Capacity: "2Gi"}}} diff --git a/internal/multiplane/runner.go b/internal/multiplane/runner.go index 19895ba2..71a3a90d 100644 --- a/internal/multiplane/runner.go +++ b/internal/multiplane/runner.go @@ -207,7 +207,7 @@ func Coordinate(ctx context.Context, c Config, o CoordinatorOptions, onError fun if err != nil { return err } - projector := &capacity.Projector{Reader: projectorAPI, Writer: projectorAPI, Namespace: DeviceNamespace, Cleaning: cleaningResolver} + projector := &capacity.Projector{Reader: projectorAPI, Writer: projectorAPI, Namespace: DeviceNamespace, Cleaning: capacity.Policies(projectorAPI, DeviceNamespace)} loop := &delivery.Loop{Client: api, Coordinator: coord, Namespace: DeviceNamespace, OnError: onError, Capacity: projector, Courier: &delivery.Courier{Client: api, Registry: registry, Coordinator: coord, Sites: sites, Namespace: DeviceNamespace}} go fixture.Run(ctx, discovery, c.Enrollment, 30*time.Second, func(err error) { onError(fmt.Errorf("fixture discovery: %w", err)) }) @@ -257,13 +257,7 @@ 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(localCleaningPolicy) - }, - Capacity: &capacity.Projector{Reader: r.Provider.API, Namespace: DeviceNamespace, Cleaning: cleaningResolver}, + Capacity: &capacity.Projector{Reader: r.Provider.API, Namespace: DeviceNamespace, Cleaning: capacity.Policies(r.Provider.API, DeviceNamespace)}, BootInterface: "primary", TargetDisks: []string{"disk-0"}, Sites: sites, } @@ -276,18 +270,6 @@ func New(ctx context.Context, c Config) (*Runner, error) { return r, nil } -// localCleaningPolicy is the fixture cleaning policy record. The cleaning -// policy owner's resolution contract does not exist yet, so the run resolves -// this one name itself. -const localCleaningPolicy = `{"method":"overwrite","disks":"all"}` - -func cleaningResolver(_ context.Context, name string) (string, error) { - if name != "local-cleaning" { - return "", capacity.ErrUnresolved - } - return custody.SpecDigest(localCleaningPolicy) -} - func condition(kind string, status metav1.ConditionStatus, generation int64, reason string) metav1.Condition { return metav1.Condition{Type: kind, Status: status, ObservedGeneration: generation, Reason: reason, Message: "Local multi-plane acceptance; synthetic IAM, quota, catalog and networkless fixtures", LastTransitionTime: metav1.Now()} } diff --git a/internal/multiplane/seed.go b/internal/multiplane/seed.go index 142a314a..4d7bd387 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 } @@ -160,3 +163,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/admission.go b/internal/registration/admission.go index f9e31127..62d4aeba 100644 --- a/internal/registration/admission.go +++ b/internal/registration/admission.go @@ -75,8 +75,8 @@ type Handler struct { // resource and object name. Authorize func(ctx context.Context, project Project, actor authenticationv1.UserInfo, verb, group, resource, name string) error // Cleaning resolves a cleaning policy name to its digest. It returns - // capacity.ErrUnresolved for a name that does not resolve. Nil resolves - // nothing, so no registered capacity can be enabled. + // capacity.ErrUnresolved for a name that does not resolve. Nil reads the + // policy in the request’s provider project and namespace. Cleaning capacity.CleaningResolver // Projectors are the usernames of the capacity projector, the only // identity that may write the status of registered capacity. @@ -264,7 +264,7 @@ func (handler *Handler) evaluateUpdate(ctx context.Context, name string, request } resolve := handler.Cleaning if resolve == nil { - resolve = capacity.Unresolved + resolve = capacity.Policies(project.Client, request.Namespace) } if next.Spec.CleaningPolicyRef.Name == "" { return errors.New("capacity cannot leave Disabled without a cleaning policy") diff --git a/internal/registration/envtest_test.go b/internal/registration/envtest_test.go index da77370f..915742c0 100644 --- a/internal/registration/envtest_test.go +++ b/internal/registration/envtest_test.go @@ -5,6 +5,7 @@ import ( "context" "encoding/pem" "errors" + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" "io" "net/http/httptest" "os" @@ -46,7 +47,7 @@ func startAPI(t *testing.T) *liveAPI { if os.Getenv("KUBEBUILDER_ASSETS") == "" { t.Skip("KUBEBUILDER_ASSETS required") } - environment := &envtest.Environment{CRDDirectoryPaths: []string{filepath.Join("..", "..", "config", "base", "crd"), filepath.Join("..", "..", "config", "components", "inventory", "crds")}, ErrorIfCRDPathMissing: true} + environment := &envtest.Environment{CRDDirectoryPaths: []string{filepath.Join("..", "..", "config", "base", "crd"), filepath.Join("..", "..", "config", "components", "inventory", "crds"), filepath.Join("..", "..", "config", "components", "device-operations", "crds")}, ErrorIfCRDPathMissing: true} config, err := environment.Start() if err != nil { t.Fatal(err) @@ -57,7 +58,7 @@ func startAPI(t *testing.T) *liveAPI { } }) scheme := runtime.NewScheme() - for _, add := range []func(*runtime.Scheme) error{corev1.AddToScheme, rbacv1.AddToScheme, inventory.AddToScheme, metal.AddToScheme, admissionregistrationv1.AddToScheme, authorizationv1.AddToScheme} { + for _, add := range []func(*runtime.Scheme) error{corev1.AddToScheme, rbacv1.AddToScheme, inventory.AddToScheme, ops.AddToScheme, metal.AddToScheme, admissionregistrationv1.AddToScheme, authorizationv1.AddToScheme} { if err := add(scheme); err != nil { t.Fatal(err) } diff --git a/internal/registration/stage2_envtest_test.go b/internal/registration/stage2_envtest_test.go index 3d2269a7..518b4d73 100644 --- a/internal/registration/stage2_envtest_test.go +++ b/internal/registration/stage2_envtest_test.go @@ -2,11 +2,13 @@ package registration import ( "context" + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" "testing" + "time" inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" metal "go.datum.net/fleet/internal/api/v1alpha1" - "go.datum.net/fleet/internal/capacity" + "go.datum.net/fleet/internal/cleaning" "go.datum.net/fleet/internal/controller" rbacv1 "k8s.io/api/rbac/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" @@ -23,9 +25,17 @@ const stageTwoPolicyDigest = "sha256:0c2b77e1d9a40000000000000000000000000000000 func TestStageTwoEnablesRegisteredCapacity(t *testing.T) { api := startAPI(t) ctx := context.Background() + policy := &ops.CleaningPolicy{ObjectMeta: metav1.ObjectMeta{Name: "tenant-reuse", Namespace: InventoryNamespace}, Spec: ops.CleaningPolicySpec{Assurance: ops.AssuranceClear, Rules: []ops.CleaningRule{{Name: "nvme", 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}}}}} + if err := api.admin.Create(ctx, policy); err != nil { + t.Fatal(err) + } + digest, err := cleaning.Digest(policy.Spec) + if err != nil { + t.Fatal(err) + } api.installHandler(&Handler{Projects: []string{"datum-cloud"}, Resolve: func(context.Context, string) (Project, error) { return Project{Identity: controller.ProjectIdentity{AuthorityID: "milo", RouteName: "datum-cloud", UID: "project-1"}, Client: api.admin}, nil - }, Authorize: Authorize, Cleaning: capacity.Fixed(map[string]string{"tenant-reuse": stageTwoPolicyDigest}), Projectors: []string{"capacity-projector"}}) + }, Authorize: Authorize, Projectors: []string{"capacity-projector"}}) operator := api.actor("operator", "system:masters") projector := api.actor("capacity-projector", "system:masters") register := func(device *inventory.Device) *metal.MachineCapacity { @@ -125,8 +135,8 @@ func TestStageTwoEnablesRegisteredCapacity(t *testing.T) { DeviceRef: metal.AllocatedDeviceReference{Name: device.Name}, Accepted: metal.AcceptedContract{MachineClassRef: metal.ContentReference{Name: "class", Generation: 1, Digest: stageTwoPolicyDigest}, MachineProfileRef: metal.ContentReference{Name: "profile", Generation: 1, Digest: stageTwoPolicyDigest}, CPU: metal.CPURequirement{Architecture: "amd64", Cores: 2}, Memory: metal.MemoryRequirement{Capacity: "2Gi"}}, - Authority: metal.AllocationAuthority{Principal: "fixture", Decision: "fixture"}, - CleaningPolicyDigest: stageTwoPolicyDigest, BootInterface: "primary", TargetDisks: []string{"disk-0"}, + Authority: metal.AllocationAuthority{Principal: "fixture", Decision: "fixture"}, + CleaningPolicy: ops.PinnedCleaningPolicy{CleaningPolicyReference: ops.CleaningPolicyReference{Name: policy.Name, Generation: policy.Generation, Digest: digest}, Spec: policy.Spec}, BootInterface: "primary", TargetDisks: []string{"disk-0"}, }} if err := api.admin.Create(ctx, allocation); err != nil { t.Fatal(err) diff --git a/internal/registration/transport.go b/internal/registration/transport.go index 3f01ab50..dcb58b53 100644 --- a/internal/registration/transport.go +++ b/internal/registration/transport.go @@ -5,6 +5,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/webhook/admission" + "go.datum.net/fleet/internal/cleaning" "go.datum.net/fleet/internal/custody/creatorwebhook" "go.datum.net/fleet/internal/machineadmission" "go.datum.net/fleet/internal/powerwebhook" @@ -22,6 +23,7 @@ func (handler *Handler) Transport(creator *creatorwebhook.Handler, power *powerw mux.Handle(powerwebhook.Path, &admission.Webhook{Handler: power}) mux.Handle(machineadmission.MutatePath, &admission.Webhook{Handler: machineadmission.Mutator{}}) mux.Handle(machineadmission.ValidatePath, &admission.Webhook{Handler: machineadmission.Validator{}}) + 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/dhcp_test.go b/internal/site/redfishwork/dhcp_test.go index 66304836..3b03ec05 100644 --- a/internal/site/redfishwork/dhcp_test.go +++ b/internal/site/redfishwork/dhcp_test.go @@ -139,7 +139,7 @@ func TestAStaticSiteStoresNoReservation(t *testing.T) { if result, err := r.Run(context.Background(), assignment(l, "DeviceInstallation", "op-static-install", 1, installSpec())); err != nil || result.Phase != ops.PhaseSucceeded { t.Fatalf("install: %+v, %v", result, err) } - wipe := ops.DeviceWipeSpec{Step: 1, CleaningPolicyDigest: "sha256:" + strings.Repeat("b", 64), TargetDisks: []string{"disk-0"}, BootInterface: "primary"} + wipe := ops.DeviceWipeSpec{Step: 1, Policy: ops.CleaningPolicyReference{Name: "tenant-reuse-v1", Generation: 1, Digest: "sha256:" + strings.Repeat("b", 64)}, TargetDisks: []string{"disk-0"}, BootInterface: "primary"} if result, err := r.Run(context.Background(), assignment(l, "DeviceWipe", "op-static-wipe", 2, wipe)); err != nil || result.Phase != ops.PhaseSucceeded { t.Fatalf("wipe: %+v, %v", result, err) } @@ -170,7 +170,7 @@ func TestABootAddressMustFitTheSiteDHCP(t *testing.T) { m := newLab(t) s := runner(t, m) synced(s) - wipe := ops.DeviceWipeSpec{Step: 1, CleaningPolicyDigest: "sha256:" + strings.Repeat("b", 64), TargetDisks: []string{"disk-0"}, BootInterface: "primary"} + wipe := ops.DeviceWipeSpec{Step: 1, Policy: ops.CleaningPolicyReference{Name: "tenant-reuse-v1", Generation: 1, Digest: "sha256:" + strings.Repeat("b", 64)}, TargetDisks: []string{"disk-0"}, BootInterface: "primary"} result, _ = s.Run(context.Background(), assignment(m, "DeviceWipe", "op-no-address", 1, wipe)) if result.Phase != ops.PhaseFailed || result.Reason != custody.ReasonBootNetworkRequired || m.onCount() != 0 { t.Fatalf("synced site without an address: %+v", result) diff --git a/internal/site/redfishwork/kinds_test.go b/internal/site/redfishwork/kinds_test.go index 252f8f44..dff7a00d 100644 --- a/internal/site/redfishwork/kinds_test.go +++ b/internal/site/redfishwork/kinds_test.go @@ -397,7 +397,7 @@ func TestNetworkBootNeedsNoWorkerIdentity(t *testing.T) { if result, err := r.Run(context.Background(), assignment(l, "DeviceInstallation", "op-nb-identity", 1, installSpec())); err != nil || result.Phase != ops.PhaseSucceeded { t.Fatalf("install = %+v, %v", result, err) } - spec := ops.DeviceWipeSpec{Step: 1, CleaningPolicyDigest: "sha256:" + strings.Repeat("b", 64), TargetDisks: []string{"disk-0"}, BootInterface: "primary"} + spec := ops.DeviceWipeSpec{Step: 1, Policy: ops.CleaningPolicyReference{Name: "tenant-reuse-v1", Generation: 1, Digest: "sha256:" + strings.Repeat("b", 64)}, TargetDisks: []string{"disk-0"}, BootInterface: "primary"} if result, err := r.Run(context.Background(), assignment(l, "DeviceWipe", "op-wipe-identity", 2, spec)); err != nil || result.Phase != ops.PhaseSucceeded { t.Fatalf("wipe = %+v, %v", result, err) } @@ -406,7 +406,7 @@ func TestNetworkBootNeedsNoWorkerIdentity(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"}, BootInterface: "primary"} + spec := ops.DeviceWipeSpec{Step: 1, Policy: ops.CleaningPolicyReference{Name: "tenant-reuse-v1", Generation: 1, Digest: "sha256:" + strings.Repeat("b", 64)}, TargetDisks: []string{"disk-0"}, BootInterface: "primary"} 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 876f0d28..16d51c80 100644 --- a/internal/site/simwork/kinds.go +++ b/internal/site/simwork/kinds.go @@ -175,7 +175,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 @@ -214,6 +214,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 1e88f1ba..bcf77e1c 100644 --- a/internal/site/vmwork/kinds.go +++ b/internal/site/vmwork/kinds.go @@ -443,7 +443,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 @@ -547,5 +547,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 5f6f4af0..e8dffb34 100644 --- a/internal/site/vmwork/kinds_test.go +++ b/internal/site/vmwork/kinds_test.go @@ -215,7 +215,7 @@ func installSpec() ops.DeviceInstallationSpec { } func wipeSpec() ops.DeviceWipeSpec { - return ops.DeviceWipeSpec{OperationEnvelope: envelope(), Step: 1, CleaningPolicyDigest: "sha256:" + key, TargetDisks: []string{"disk-0"}, BootInterface: "primary"} + return ops.DeviceWipeSpec{OperationEnvelope: envelope(), Step: 1, Policy: ops.CleaningPolicyReference{Name: "tenant-reuse-v1", Generation: 1, Digest: "sha256:" + key}, TargetDisks: []string{"disk-0"}, BootInterface: "primary"} } // TestInstallThenWipe installs directly, proves each phase by its receipt, diff --git a/internal/staging/harness_test.go b/internal/staging/harness_test.go index 587b43ef..e82bc19a 100644 --- a/internal/staging/harness_test.go +++ b/internal/staging/harness_test.go @@ -35,12 +35,12 @@ import ( ) const ( + fixtureDigest = "sha256:0c2b77e1d9a4000000000000000000000000000000000000000000000000cafe" providerNamespace = "fleet-provider" providerUser = "system:serviceaccount:fleet-system:metal-provider" 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" @@ -129,14 +129,13 @@ func startStack(t *testing.T) *stack { coordinator := &custody.Coordinator{Client: admin, Registry: registry, Sites: sites, Config: custody.Config{Namespace: providerNamespace, Principals: custody.Principals{ custody.CreatorMetalProvider: {{Username: providerUser}}, custody.CreatorReleaseController: {{Username: releaseUser}}, }}} - s.projector = &capacity.Projector{Reader: admin, Writer: admin, Namespace: providerNamespace, Cleaning: capacity.Fixed(map[string]string{"example-cleaning": policyDigest})} + s.projector = &capacity.Projector{Reader: admin, Writer: admin, Namespace: providerNamespace, Cleaning: capacity.Policies(admin, providerNamespace)} s.loop = &delivery.Loop{Client: admin, Coordinator: coordinator, Namespace: providerNamespace, Capacity: s.projector, Courier: &delivery.Courier{Client: admin, Registry: registry, Coordinator: coordinator, Sites: sites, Namespace: providerNamespace}} s.allocator = &allocation.Allocator{ 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 }, Capacity: s.projector, BootInterface: "primary", TargetDisks: []string{"disk-0"}, Sites: sites, @@ -148,7 +147,7 @@ func startStack(t *testing.T) *stack { Content: ops.CommissioningPlanContent{ Inspection: ops.CommissioningInspection{CPU: ops.InspectionCPU{Architecture: "amd64", Cores: 24}, Memory: ops.InspectionValue{Capacity: "128Gi"}, Disks: ops.InspectionDisks{Count: 1, MinCapacity: "100Gi"}, Interfaces: ops.InspectionCount{Count: 1}}, - BurnIn: ops.CommissioningBurnIn{Image: ops.ImageInput{Name: "burn-in", Digest: policyDigest}, Duration: metav1.Duration{Duration: time.Minute}}, + BurnIn: ops.CommissioningBurnIn{Image: ops.ImageInput{Name: "burn-in", Digest: fixtureDigest}, Duration: metav1.Duration{Duration: time.Minute}}, }, EvidenceLifetime: metav1.Duration{Duration: 24 * time.Hour}, }} @@ -162,6 +161,7 @@ func startStack(t *testing.T) *stack { 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 @@ -283,3 +283,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}}}, + }} +}