diff --git a/cmd/fleet-simulator/main.go b/cmd/fleet-simulator/main.go index 017cdc87..7fd0a1f7 100644 --- a/cmd/fleet-simulator/main.go +++ b/cmd/fleet-simulator/main.go @@ -74,7 +74,7 @@ func main() { defer stop() results := site.NewResults(store) runner := &site.Runner{Site: siteName, Store: store, Results: results, Access: fixture.Access{Enrollment: enrollment}, - Kinds: map[string]site.Kind{"DeviceInstallation": simwork.Installation{}, "DeviceWipe": simwork.Wipe{}, "DeviceCommissioning": simwork.Commissioning{}}} + Kinds: map[string]site.Kind{"DeviceInstallation": simwork.Installation{}, "DeviceWipe": simwork.Wipe{}, "DeviceCommissioning": simwork.Commissioning{}}, Payloads: site.StorePayloads{Store: store}} runner.Kinds["DevicePowerOperation"] = simwork.Power{} dispatcher := &siteapi.Dispatcher{Runner: runner, Context: ctx, Logger: logger} // The simulator's installs and wipes are simulated, so its declaration diff --git a/config/components/device-operations/crds/kustomization.yaml b/config/components/device-operations/crds/kustomization.yaml index 1f890b4c..24d03271 100644 --- a/config/components/device-operations/crds/kustomization.yaml +++ b/config/components/device-operations/crds/kustomization.yaml @@ -1,3 +1,3 @@ apiVersion: kustomize.config.k8s.io/v1beta1 kind: Kustomization -resources: [fleet.datumapis.com.yaml] +resources: [fleet.datumapis.com.yaml, sealedpayloads.yaml] diff --git a/config/components/device-operations/crds/sealedpayloads.yaml b/config/components/device-operations/crds/sealedpayloads.yaml new file mode 100644 index 00000000..b5cff7d3 --- /dev/null +++ b/config/components/device-operations/crds/sealedpayloads.yaml @@ -0,0 +1,41 @@ +# The sealed store for customer bootstrap data (#184). A dedicated kind, not a +# Secret, because Milo grants permissions per kind or per object, never per +# namespace: only roles that name this kind can read it. +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: sealedpayloads.fleet.datumapis.com + annotations: + discovery.miloapis.com/parent-contexts: Project +spec: + group: fleet.datumapis.com + names: + kind: SealedPayload + listKind: SealedPayloadList + plural: sealedpayloads + singular: sealedpayload + scope: Namespaced + versions: + - name: v1alpha1 + served: true + storage: true + schema: + openAPIV3Schema: + type: object + properties: + apiVersion: {type: string} + kind: {type: string} + metadata: {type: object} + spec: + type: object + x-kubernetes-validations: + - {rule: 'self == oldSelf', message: a sealed payload never changes} + required: [operationName, allocationName, digest, salt, data] + properties: + operationName: {type: string, minLength: 1, maxLength: 253} + allocationName: {type: string, minLength: 1, maxLength: 253} + digest: {type: string, pattern: '^sha256:[0-9a-f]{64}$'} + # 32 random bytes, base64. + salt: {type: string, format: byte, minLength: 44, maxLength: 44} + # At most 96 KiB of encoded bootstrap data, base64. + data: {type: string, format: byte, minLength: 1, maxLength: 131072} diff --git a/config/components/device-operations/protected-resources/kustomization.yaml b/config/components/device-operations/protected-resources/kustomization.yaml index b2471c04..34698aae 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 + - sealedpayload.yaml - cleaningpolicy.yaml - devicecommissioning.yaml - devicecommissioningplan.yaml diff --git a/config/components/device-operations/protected-resources/sealedpayload.yaml b/config/components/device-operations/protected-resources/sealedpayload.yaml new file mode 100644 index 00000000..e3ec9a3b --- /dev/null +++ b/config/components/device-operations/protected-resources/sealedpayload.yaml @@ -0,0 +1,15 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: fleet.datumapis.com-sealedpayload +spec: + serviceRef: + name: fleet.datumapis.com + kind: SealedPayload + plural: sealedpayloads + singular: sealedpayload + # The spec never changes, so there is no update or patch. + permissions: [list, get, watch, create, delete] + parentResources: + - apiGroup: resourcemanager.miloapis.com + kind: Project diff --git a/config/components/device-operations/roles/coordinator.yaml b/config/components/device-operations/roles/coordinator.yaml index 2773486d..287bb943 100644 --- a/config/components/device-operations/roles/coordinator.yaml +++ b/config/components/device-operations/roles/coordinator.yaml @@ -59,3 +59,10 @@ spec: - metal.datumapis.com/machinecapacities.get - metal.datumapis.com/machinecapacities.list - metal.datumapis.com/machinecapacities.watch + # The coordinator checks each payload at admission, the federation + # courier in it delivers payloads to sites, and it deletes them. No + # other role can read the sealed store. + - fleet.datumapis.com/sealedpayloads.get + - fleet.datumapis.com/sealedpayloads.list + - fleet.datumapis.com/sealedpayloads.watch + - fleet.datumapis.com/sealedpayloads.delete diff --git a/config/components/device-operations/roles/installation-requester.yaml b/config/components/device-operations/roles/installation-requester.yaml index 9653241e..ed620e56 100644 --- a/config/components/device-operations/roles/installation-requester.yaml +++ b/config/components/device-operations/roles/installation-requester.yaml @@ -9,6 +9,8 @@ spec: launchStage: Alpha includedPermissions: - fleet.datumapis.com/deviceinstallations.create + # It copies bootstrap data into the sealed store and never reads it back. + - fleet.datumapis.com/sealedpayloads.create - fleet.datumapis.com/deviceinstallations.get - fleet.datumapis.com/deviceinstallations.list - fleet.datumapis.com/deviceinstallations.watch diff --git a/config/standalone/fixtures.yaml b/config/standalone/fixtures.yaml index f3aea79f..0b81dcf3 100644 --- a/config/standalone/fixtures.yaml +++ b/config/standalone/fixtures.yaml @@ -43,6 +43,7 @@ spec: version: "12" architecture: amd64 firmwareModes: [UEFI] + bootstrapFormats: [NoCloud] digest: "sha256:9f4ad8d8b8a6f6fc64d2cf2c7e70b9184b74f089adf8c36d84f4fcb99892f3cb" availability: Available --- @@ -97,6 +98,19 @@ spec: machineRef: {name: allocation} expectedPredecessor: {type: None} imageRef: {name: debian-12} + bootstrapConfigRef: {name: debian-12-bootstrap} +--- +# The consumer's bootstrap data, in its own namespace. Synthetic values only. +apiVersion: v1 +kind: Secret +metadata: {name: debian-12-bootstrap, namespace: fleet-project-a} +type: metal.datumapis.com/bootstrap +stringData: + userData: | + #cloud-config + hostname: synthetic-example + sshAuthorizedKeys: | + ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAISyntheticExampleOnly synthetic@example.com --- apiVersion: metal.datumapis.com/v1alpha1 kind: Installation diff --git a/config/standalone/rbac.yaml b/config/standalone/rbac.yaml index b367c918..df78f2c3 100644 --- a/config/standalone/rbac.yaml +++ b/config/standalone/rbac.yaml @@ -58,6 +58,10 @@ rules: - apiGroups: [metal.datumapis.com] resources: [machineimagepublications] verbs: [get, create, delete] + # It copies bootstrap data into the sealed store and never reads it back. + - apiGroups: [fleet.datumapis.com] + resources: [sealedpayloads] + verbs: [create] - apiGroups: [fleet.datumapis.com] resources: [devices, devicecustodies, devicecommissionings, devicecommissioningplans, devicecommissioningplanapprovals] verbs: [get, list] @@ -73,6 +77,12 @@ apiVersion: rbac.authorization.k8s.io/v1 kind: Role metadata: {name: fleet-synthetic-consumer-writer, namespace: fleet-project-a} rules: + # The Installation's bootstrap Secret. The fixture stands in for reading it + # under the Installation creator's authority. + - apiGroups: [""] + resources: [secrets] + resourceNames: [debian-12-bootstrap] + verbs: [get] # The publisher's copy of the provider image. - apiGroups: [metal.datumapis.com] resources: [machineimages] @@ -165,6 +175,10 @@ rules: - apiGroups: [metal.datumapis.com] resources: [machineallocations] verbs: [get, list, watch] + # The only reader of the sealed store: it checks, delivers and deletes. + - apiGroups: [fleet.datumapis.com] + resources: [sealedpayloads] + verbs: [get, list, watch, delete] --- apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding diff --git a/docs/development/README.md b/docs/development/README.md index ce0c2c9c..fd0e5234 100644 --- a/docs/development/README.md +++ b/docs/development/README.md @@ -45,7 +45,8 @@ is implemented on the same custody, and nothing creates power operations yet. **implemented**: a provider-published, digest-pinned `MachineImage` that admission resolves through a publication record and checks against the server's architecture and firmware mode. The sealed bootstrap store is -proposed. +**implemented** through the simulator site; federation and the lab sites do +not carry bootstrap data yet. The opt-in [multi-plane acceptance harness](../operations/multiplane.md) composes the [local VM site](../operations/local-vm.md) with native Milo project APIs, the @@ -546,7 +547,7 @@ allocator selects again. An `Active` allocation that lost custody is not repaire Installation admission creates a `DeviceInstallation` named from the allocation and the Installation UID. The Installation's predecessor must be the Machine's -current installation, and a bootstrap reference is refused. Response-loss +current installation, and bootstrap data goes through the sealed store. Response-loss recovery is an exact lookup by name, not a second effect. Release moves the holder to `Release`, closes the gates, wipes the Device, deletes the quota claim, and only then returns the Device to `None`. The allocation, installations and @@ -814,13 +815,14 @@ acceptance inventory. fence, consumer-project deletion recovery, or provider-project purge guard. Production cross-project allocation therefore fails closed, and the quota claim has no end-to-end run. -- `LocalDigestImageResolver` is test-only. Production image authority, - namespace authorization, catalog lifetime identity, and digest resolution are - not implemented. +- Image resolution uses a fixture authorizer; the Milo image-use check is not + implemented. See [OS images and bootstrap data](machine-images.md). - No container image or Kubernetes deployment is delivered in this increment. - There is no mTLS workload identity, target-level authorization, or production site credential protocol. -- The capacity projector is unwired (O1) and bootstrap is refused (O10); see - [Device custody](device-custody.md#points-for-a-person). +- The capacity projector is unwired (O1); see + [Device custody](device-custody.md#points-for-a-person). Bootstrap data + reaches only the simulator site; see [OS images and bootstrap + data](machine-images.md). - The site store is intended for a single site process per Device. Replication, migration, backup, and upgrade/downgrade compatibility are not implemented. diff --git a/docs/development/device-custody.md b/docs/development/device-custody.md index 3545fd8f..1a6ff1a8 100644 --- a/docs/development/device-custody.md +++ b/docs/development/device-custody.md @@ -242,7 +242,7 @@ update). A retry finds the same allocation by its name. - **Installation.** The `DeviceInstallation` is named from the allocation and the Installation UID, which its `fleet.datumapis.com/installation-uid` label records. Its predecessor must be the Machine's current installation. - A bootstrap reference is refused. + Bootstrap data goes through the [sealed store](machine-images.md). - **Release.** The allocation's holder moves to `Release` with all six gates open. Then: - Access closes at once. @@ -452,7 +452,8 @@ a Machine status, update or patch permission. ### Unchanged and still open -- Bootstrap stays refused (O10). +- Bootstrap data reaches only the simulator site. See + [OS images and bootstrap data](machine-images.md). - `DeviceRecovery` needs no second person. ## Failure scenarios (Increment D) @@ -756,10 +757,10 @@ remains. a person](#points-for-a-person). - Staff roles may read MachineAllocations, because nothing secret is on them. Only the recovery operator role grants that read today. -- Bootstrap stays refused. A `DeviceInstallation` that names a bootstrap - reference ends `Failed` with `BootstrapUnsupported`. No role can read a - Secret, a sealed store, or a bootstrap payload, and a test checks the role - definitions. +- Bootstrap data lives in the [sealed store](machine-images.md). Only the + coordinator role can read it, the installation requester can only create + it, and no role reads a Secret or a bootstrap payload. A test walks every + role the repository ships to check this. ### Other decisions @@ -1190,8 +1191,8 @@ These need a decision before the increment that depends on them. - **Who approves commissioning plans.** No team holds the plan approver role in any deployed environment yet, so no plan qualifies there. The roles keep the author and the approver apart by username. -- **O10: the sealed store for bootstrap payloads.** Bootstrap stays refused in - every increment until a store is chosen. +- **O10: the sealed store for bootstrap payloads.** Chosen and implemented as + `SealedPayload`; see [OS images and bootstrap data](machine-images.md). - **Machine status writes by consumers in Milo.** Milo's authorizer, with subresource authorization off, checks a status write against `update` and `patch`, which the consumer and claimant roles hold. The power webhook refuses @@ -1440,7 +1441,7 @@ a real API server: | Area | Tests | | --- | --- | -| Every admission precondition, names, kind checks, bootstrap refusal, staff expiry | `TestAdmissionPreconditions` | +| Every admission precondition, names, kind checks, the sealed bootstrap payload check, staff expiry | `TestAdmissionPreconditions` | | Every holder transition, pending order, supersede, cancellation on holder change, stale fences, results, deadlines | `TestLifecycle`, `TestImportedDeviceGetsUnverifiedCustodyAndSendsNothing` | | Holds and settlement through the test-only kind, install and wipe holds, `Retry`, `Retire`, retention | `TestRecovery` | | Rebuild from each source, each conflict, `Resolve`, custody deleted and restored | `TestRebuild` | @@ -1482,7 +1483,7 @@ Increment B's site tests run with `go test -race ./internal/site/...`: | One worker per assignment, final results, shutdown at each stage, an older worker that does not stop, a fence raised between journal and send | `TestARedeliveryWhileTheSameOperationRunsStoresNothing`, `TestACopyWaitingForTheLockReturnsTheStoredResult`, `TestAStoredResultSurvivesARedelivery`, `TestAWorkerStoppedFromOutsideStoresNoResult`, `TestAShutdownWhileWaitingForTheRunLockStoresNothing`, `TestAShutdownDuringTheChecksStoresNothing`, `TestANewerAssignmentThatCannotStopTheOlderWorkerSendsNothing`, `TestALostLockWithJournaledStepsIsUnknown`, `TestAFenceRaisedBetweenJournalAndSendStopsTheStep` | | Per-Device credentials, the fence report | `TestSecretCredentialsUseThePerDeviceContract`, `TestReportGivesTheCoordinatorSeenAndStoppedFences` | | Step payloads, the start-by window, identity separate from capabilities, a resumed worker reporting unknown | `TestAStepPayloadIsJournaledAndReadBack`, `TestALateStartIsStaleAndSendsNothing`, `TestIdentityIsSeparateFromInstallCapabilities`, `TestAResumedWorkerThatCannotReachTheBMCReportsUnknown` | -| Install and wipe against a simulated BMC, one power-on per phase after an interruption in either phase, the power-off bound, fenced boot admission, bootstrap refused | `TestAWorkerInterruptedInTheDiskPhaseResumes`, `TestAServerThatNeverPowersOffEndsTheStep`, `TestInstallationRunsBothPhasesWithOneOnEach`, `TestWipeChecksTheEnrolledDisk`, `TestAnInterruptedWorkerResumesWithoutASecondOn`, `TestOnlyTheCurrentFenceHasAnOpenBootAdmission`, `TestBootstrapIsRefusedAtTheSiteToo` | +| Install and wipe against a simulated BMC, one power-on per phase after an interruption in either phase, the power-off bound, fenced boot admission, bootstrap refused by a site that cannot hand it on | `TestAWorkerInterruptedInTheDiskPhaseResumes`, `TestAServerThatNeverPowersOffEndsTheStep`, `TestInstallationRunsBothPhasesWithOneOnEach`, `TestWipeChecksTheEnrolledDisk`, `TestAnInterruptedWorkerResumesWithoutASecondOn`, `TestOnlyTheCurrentFenceHasAnOpenBootAdmission`, `TestBootstrapIsRefusedAtTheSiteToo` | Increment C's tests run with `task test:envtest`, and the smoke runs with `task standalone:test`: diff --git a/docs/development/machine-images.md b/docs/development/machine-images.md index 30bb47ef..7285ef96 100644 --- a/docs/development/machine-images.md +++ b/docs/development/machine-images.md @@ -13,7 +13,7 @@ proposal's API names are provisional. Each piece below is marked | Increment | What it covers | Status | | --- | --- | --- | | 1: image catalog | `MachineImage` and `MachineImagePublication` kinds, publication, admission-time resolution to a pinned digest, architecture and firmware mode checks, the worker's firmware mode check, and IAM | **Implemented and verified.** The CRD rules are checked with the API server's own schema validator, resolution and publication with a fake API server, and installs of a resolved image against a real API server and in the standalone smoke. The multi-plane runs are not yet verified. | -| 2: sealed bootstrap store | `SealedPayload`, delivery to the operation's worker, deletion | **Proposed** | +| 2: sealed bootstrap store | `SealedPayload`, the coordinator's check and sweep, delivery to the operation's worker, deletion at the site, IAM | **Implemented and verified** through the simulator site, by unit tests, tests against a real API server, and the standalone smoke. Admission refuses bootstrap data for a Device served through federation, which the local VM and Redfish labs use. | | 3: lab proof | A chosen image with bootstrap data installs in the local VM and Redfish labs, and the guest reports the data it received | **Proposed** | ## What increment 1 adds @@ -70,6 +70,50 @@ proposal's API names are provisional. Each piece below is marked publisher roles write images, only the publisher writes records, and only the publisher and the Fleet provider read records. +## What increment 2 adds + +- **Bootstrap Secret.** A Secret of type `metal.datumapis.com/bootstrap` with + `userData`, `sshAuthorizedKeys`, or both, as UTF-8 text, at most 64 KiB and + at most 96 KiB once encoded, so a site always receives it whole. Admission + refuses anything else with `BootstrapInvalid`, and a missing or unreadable + Secret with `BootstrapNotFound`. +- **Sealed store.** `SealedPayload` in `fleet.datumapis.com`, in the provider + project. Its spec never changes. It holds a random 32-byte salt and the data, + and its digest covers both. Its name derives from the operation name and the + digest. +- **Admission.** If the DeviceInstallation already exists, admission returns + it and reads nothing. Otherwise the Fleet provider seals the data, creates + the payload, then creates the operation, which carries only the payload's + name and digest. Of two concurrent admissions, one operation wins and the + other's payload is swept. +- **Coordinator check.** At the custody update, every site serving the Device + must be able to receive payloads, or the operation fails with + `BootstrapUnsupported`. The payload must exist under the derived name, name + the operation, and match a digest recomputed from its salt and data, or the + operation fails with `BootstrapUnavailable`. Either way nothing is sent. The + coordinator reads through to the API server, and a failed read refuses, as + in every kind check. +- **Sweep.** Each coordinator pass deletes, with a UID precondition, every + payload whose operation ended, whose operation names another payload, or + that has no operation and an allocation that is not `Active`. +- **Delivery.** The courier reads the payload, checks it again, and sends it to + the site beside the assignment. The site takes the payload reference from + the admitted inputs, not from the transport, stores the payload only if it + matches, and the runner checks it again before anything is sent. +- **Site deletion.** The site deletes the payload when the result is stored, + when the coordinator answers the result, and whenever it raises the Device's + fence, for a newer operation or a recovery, which removes every payload + below it, including one whose worker never ran. A worker stopped from + outside keeps it for its replacement. +- **Evidence.** A successful install's evidence names the digest of the data + the worker handed to the server, recomputed from what it handed. Custody + accepts a success only if that equals the admitted digest, and only if it is + empty when there was no bootstrap data. +- **IAM.** Only the coordinator role reads `SealedPayload`; the installation + requester may only create it. A test walks every Milo role the repository + ships, resolves inheritance, and fails if any other role can read it or holds + a wildcard. + ## Not implemented yet - The validating webhook that rejects image writes from anyone but the @@ -80,3 +124,10 @@ proposal's API names are provisional. Each piece below is marked - Artifact mirroring by digest from a provider registry. Each lab site holds one pinned image and serves only that one. - Firmware mode from BMC discovery. Lab fixtures write it on the capacity. +- Federation delivery of bootstrap payloads to a cell, and handing them to a + local VM or Redfish server. Admission refuses such an operation with + `BootstrapUnsupported` before the Device's fence moves. +- The Milo check that the Installation's creator can read the bootstrap + Secret. The lab compositions read it with their own identity. +- Encryption at rest for `SealedPayload` and an audit policy that omits its + bodies. diff --git a/docs/operations/site-execution.md b/docs/operations/site-execution.md index 741cce32..0ad92ea3 100644 --- a/docs/operations/site-execution.md +++ b/docs/operations/site-execution.md @@ -324,8 +324,9 @@ objects. This sequence is proposed only. ## Secrets A handoff carries one assignment: the Device, the operation, the fence, the -admitted snapshot and the exact inputs. It holds no credential. A bootstrap -payload is refused, so none is carried. A Redfish worker reads each Device's own +admitted snapshot and the exact inputs. It holds no credential and no +bootstrap payload. Federation does not yet carry bootstrap payloads, so +admission refuses an operation that names one. A Redfish worker reads each Device's own BMC credential Secret in the site's cluster, never from a handoff. Cell readers of handoffs are: diff --git a/hack/multiplane/milo.py b/hack/multiplane/milo.py index aba55ca1..9c0ed4ca 100755 --- a/hack/multiplane/milo.py +++ b/hack/multiplane/milo.py @@ -170,7 +170,7 @@ def write(obj): apply(config,{'apiVersion':'v1','kind':'Namespace','metadata':{'name':ns}}) rules=[{'apiGroups':[''],'resources':['namespaces'],'verbs':['get']},{'apiGroups':['metal.datumapis.com'],'resources':['machineclasses','machineprofiles','machinecapacities','machines','installations','machineimages'],'verbs':['get','list','watch']}] if role=='provider': - for crds in ('config/components/inventory/crds/fleet.datumapis.com.yaml','config/components/device-operations/crds/fleet.datumapis.com.yaml'): + for crds in ('config/components/inventory/crds/fleet.datumapis.com.yaml','config/components/device-operations/crds/fleet.datumapis.com.yaml','config/components/device-operations/crds/sealedpayloads.yaml'): kubectl(config,'apply','-f',crds,stdout=subprocess.DEVNULL) kubectl(config,'wait','--for=condition=Established','crd','--all','--timeout=90s',stdout=subprocess.DEVNULL) # The CRD rule check writes its synthetic objects here, away from the @@ -181,6 +181,7 @@ def write(obj): # evaluates capacity from custody and commissioning evidence, and never # writes capacity status. rules+=[{'apiGroups':['metal.datumapis.com'],'resources':['machineallocations'],'verbs':['get','list','watch','create','delete']},{'apiGroups':['metal.datumapis.com'],'resources':['machineallocations/status'],'verbs':['get','update']},{'apiGroups':['metal.datumapis.com'],'resources':['machineimagepublications'],'verbs':['get']}, + {'apiGroups':['fleet.datumapis.com'],'resources':['sealedpayloads'],'verbs':['create']}, {'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']}) @@ -194,7 +195,7 @@ def write(obj): # The coordinator rules mirror config/components/device-operations/roles/ # coordinator.yaml: it lists and settles every registered operation kind. components={ - 'coordinator':[{'apiGroups':['fleet.datumapis.com'],'resources':['devices'],'verbs':['get','list','watch']},{'apiGroups':['fleet.datumapis.com'],'resources':['devicecustodies'],'verbs':['get','list','watch','create','update','delete']}, + 'coordinator':[{'apiGroups':['fleet.datumapis.com'],'resources':['sealedpayloads'],'verbs':['get','list','watch','delete']},{'apiGroups':['fleet.datumapis.com'],'resources':['devices'],'verbs':['get','list','watch']},{'apiGroups':['fleet.datumapis.com'],'resources':['devicecustodies'],'verbs':['get','list','watch','create','update','delete']}, {'apiGroups':['fleet.datumapis.com'],'resources':['deviceinstallations','devicewipes','devicepoweroperations','devicerecoveries','devicecommissionings'],'verbs':['get','list','watch','delete']}, {'apiGroups':['fleet.datumapis.com'],'resources':['deviceinstallations/status','devicewipes/status','devicepoweroperations/status','devicerecoveries/status','devicecommissionings/status'],'verbs':['get','update']}, {'apiGroups':['fleet.datumapis.com'],'resources':['devicecommissioningplans','devicecommissioningplanapprovals'],'verbs':['get','list','watch']}, diff --git a/hack/standalone-smoke.sh b/hack/standalone-smoke.sh index e33bb658..57546bce 100755 --- a/hack/standalone-smoke.sh +++ b/hack/standalone-smoke.sh @@ -52,7 +52,7 @@ for crd in installations machineallocations machinecapacities machineclasses mac exit 1 fi done -for crd in devices devicecustodies deviceinstallations devicewipes devicepoweroperations devicerecoveries devicecommissionings devicecommissioningplans devicecommissioningplanapprovals; do +for crd in devices devicecustodies deviceinstallations devicewipes devicepoweroperations devicerecoveries devicecommissionings devicecommissioningplans devicecommissioningplanapprovals sealedpayloads; do if kubectl --context "$context" get crd "$crd.fleet.datumapis.com" >/dev/null 2>&1; then echo "fixed Fleet CRD $crd already exists; use a fresh dedicated kind cluster" >&2 exit 1 @@ -156,6 +156,23 @@ run_phase install fleet-smoke-install-recovery-run kubectl --context "$context" -n fleet-project-a get installations,machines test "$(kubectl --context "$context" -n fleet-project-a get installation debian-12 -o jsonpath='{.status.phase}')" = "Ready" test "$(kubectl --context "$context" -n fleet-project-a get machine allocation -o jsonpath='{.status.currentInstallationRef.name}')" = "debian-12" +# The install resolved the published image to its pinned digest, and the +# simulated server was handed exactly the admitted bootstrap data: its +# evidence names the operation's salted digest. +test "$(kubectl --context "$context" -n fleet-project-a get installation debian-12 -o jsonpath='{.status.resolvedImage.digest}')" = "$(kubectl --context "$context" -n fleet-provider get machineimage debian-12 -o jsonpath='{.spec.definition.digest}')" +bootstrap_op=$(kubectl --context "$context" -n fleet-provider get deviceinstallations -o jsonpath='{range .items[?(@.spec.bootstrap)]}{.metadata.name}{"\n"}{end}') +test "$(printf '%s\n' "$bootstrap_op" | grep -c .)" = "1" +bootstrap_digest=$(kubectl --context "$context" -n fleet-provider get deviceinstallation "$bootstrap_op" -o jsonpath='{.spec.bootstrap.digest}') +test -n "$bootstrap_digest" +test "$(kubectl --context "$context" -n fleet-provider get deviceinstallation "$bootstrap_op" -o jsonpath='{.status.evidence.bootstrap}')" = "$bootstrap_digest" +# The coordinator deletes the sealed copy once the operation ended. +payloads=1 +for _ in $(seq 1 60); do + payloads=$(kubectl --context "$context" -n fleet-provider get sealedpayloads -o name | grep -c . || true) + [ "$payloads" = "0" ] && break + sleep 1 +done +test "$payloads" = "0" run_phase reinstall fleet-smoke-reinstall-run kubectl --context "$context" -n fleet-system rollout restart statefulset/fleet-simulator @@ -167,7 +184,7 @@ test "$(kubectl --context "$context" -n fleet-project-b get machine allocation - for project in fleet-project-a fleet-project-b; do subject="system:serviceaccount:$project:default" - for resource in devicecustodies deviceinstallations devicewipes devicepoweroperations devicerecoveries devicecommissionings devicecommissioningplans devicecommissioningplanapprovals machineallocations; do + for resource in devicecustodies deviceinstallations devicewipes devicepoweroperations devicerecoveries devicecommissionings devicecommissioningplans devicecommissioningplanapprovals machineallocations sealedpayloads; do for verb in get list watch create update patch delete; do if [ "$(kubectl --context "$context" auth can-i "$verb" "$resource" --as="$subject" -n fleet-provider)" != "no" ]; then echo "$subject unexpectedly has $verb access to $resource" >&2 @@ -187,6 +204,14 @@ provider_subject=system:serviceaccount:fleet-system:fleet-standalone-smoke test "$(kubectl --context "$context" auth can-i update devicecustodies --as="$provider_subject" -n fleet-provider)" = "no" test "$(kubectl --context "$context" auth can-i create devicewipes --as="$provider_subject" -n fleet-provider)" = "no" test "$(kubectl --context "$context" auth can-i create deviceinstallations --as=system:serviceaccount:fleet-system:fleet-release-controller -n fleet-provider)" = "no" +# Only the coordinator reads the sealed store. The Metal provider may only +# create a payload, and the release controller may do nothing with one. +for verb in get list watch; do + test "$(kubectl --context "$context" auth can-i "$verb" sealedpayloads --as="$provider_subject" -n fleet-provider)" = "no" + test "$(kubectl --context "$context" auth can-i "$verb" sealedpayloads --as=system:serviceaccount:fleet-system:fleet-release-controller -n fleet-provider)" = "no" + test "$(kubectl --context "$context" auth can-i "$verb" sealedpayloads --as=system:serviceaccount:fleet-system:fleet-custody-coordinator -n fleet-provider)" = "yes" +done +test "$(kubectl --context "$context" auth can-i create sealedpayloads --as="$provider_subject" -n fleet-provider)" = "yes" smoke_subject=system:serviceaccount:fleet-system:fleet-standalone-smoke test "$(kubectl --context "$context" auth can-i get machine/other-machine --as="$smoke_subject" -n fleet-provider)" = "no" test "$(kubectl --context "$context" auth can-i update machineclass/standard-metal --as="$smoke_subject")" = "no" diff --git a/internal/allocation/allocator.go b/internal/allocation/allocator.go index 1b2e27f5..ef7ea54d 100644 --- a/internal/allocation/allocator.go +++ b/internal/allocation/allocator.go @@ -36,6 +36,7 @@ import ( "go.datum.net/fleet/internal/catalog" "go.datum.net/fleet/internal/cleaning" "go.datum.net/fleet/internal/custody" + "go.datum.net/fleet/internal/sealed" "go.datum.net/fleet/internal/tenancy" ) @@ -51,8 +52,8 @@ var ( ErrCustodyLost = errors.New("the allocation no longer holds its Device") // ErrPredecessor means an Installation does not follow the current one. ErrPredecessor = errors.New("the installation does not name the current installation as its predecessor") - // ErrUnsupported means a request Fleet does not implement, such as a - // bootstrap payload. + // ErrUnsupported means a request Fleet cannot act on, such as an + // Installation whose image or bootstrap data the caller did not resolve. ErrUnsupported = errors.New("unsupported request") // ErrCleaningUncovered means the capacity names no CleaningPolicy, or // one that does not exist or is not valid. @@ -528,6 +529,10 @@ func (a *Allocator) setPhase(ctx context.Context, allocation *fleetv1.MachineAll // Installation is one Installation an allocation's Machine requested. type Installation struct { + // Bootstrap is the bootstrap data the caller read, under the + // Installation creator's authority, from its bootstrap Secret. It is + // set exactly when the Installation names one. + Bootstrap *sealed.Payload Installation *fleetv1.Installation // Current is the Machine's current installation, or empty. Current string @@ -544,8 +549,8 @@ func (a *Allocator) Install(ctx context.Context, allocation *fleetv1.MachineAllo if allocation.Status.Phase != fleetv1.AllocationActive { return nil, ErrReleased } - if installation.Spec.BootstrapConfigRef != nil { - return nil, fmt.Errorf("%w: bootstrap payloads need the sealed store, which is not implemented", ErrUnsupported) + if (installation.Spec.BootstrapConfigRef != nil) != (request.Bootstrap != nil) { + return nil, fmt.Errorf("%w: the bootstrap data is not read", ErrUnsupported) } predecessor := installation.Spec.ExpectedPredecessor if (request.Current == "" && predecessor.Type != "None") || (request.Current != "" && (predecessor.Type != "Installation" || predecessor.Name != request.Current)) { @@ -558,10 +563,11 @@ func (a *Allocator) Install(ctx context.Context, allocation *fleetv1.MachineAllo if err := catalog.Compatible(image.Definition, allocation.Spec.Hardware, installation.Spec.BootstrapConfigRef != nil); err != nil { return nil, err } + name := custody.InstallationName(allocation.Name, string(installation.UID)) labels := operationLabels(allocation) labels[ops.LabelInstallationUID] = string(installation.UID) operation := &ops.DeviceInstallation{ - ObjectMeta: metav1.ObjectMeta{Name: custody.InstallationName(allocation.Name, string(installation.UID)), Namespace: a.Namespace, Labels: labels}, + ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: a.Namespace, Labels: labels}, Spec: ops.DeviceInstallationSpec{ OperationEnvelope: a.envelope(allocation, a.ProviderCreator), Image: ops.ImageInput{Name: image.Name, Digest: image.Definition.Digest, FirmwareModes: slices.Clone(image.Definition.FirmwareModes)}, @@ -575,7 +581,7 @@ func (a *Allocator) Install(ctx context.Context, allocation *fleetv1.MachineAllo if err := a.Provider.Get(ctx, client.ObjectKeyFromObject(operation), existing); err == nil { operation.Spec.BootNetwork = existing.Spec.BootNetwork operation.Spec.Delivery = existing.Spec.Delivery - return operation, matchExisting(operation, existing) + return sameInstallation(operation, request.Bootstrap != nil, existing) } else if !apierrors.IsNotFound(err) { return nil, err } @@ -602,7 +608,60 @@ func (a *Allocator) Install(ctx context.Context, allocation *fleetv1.MachineAllo } } operation.Spec.Delivery = delivery - return operation, a.createOnce(ctx, a.Provider, operation, &ops.DeviceInstallation{}) + if request.Bootstrap != nil { + // The payload is written before the operation that names it. A + // payload left by a crash is named by no operation, and the + // coordinator's sweep deletes it. + payload, err := sealed.Seal(*request.Bootstrap, name, allocation.Name, a.Namespace) + if err != nil { + return nil, err + } + if err := a.Provider.Create(ctx, payload); err != nil { + return nil, err + } + operation.Spec.Bootstrap = &ops.SealedInput{Ref: payload.Name, Digest: payload.Spec.Digest} + } + if err := a.Provider.Create(ctx, operation); apierrors.IsAlreadyExists(err) { + // A concurrent admission won. Its payload is the admitted one, and + // the sweep deletes this one. + if err := a.Provider.Get(ctx, client.ObjectKeyFromObject(operation), existing); err != nil { + return nil, err + } + return sameInstallation(operation, request.Bootstrap != nil, existing) + } else if err != nil { + return nil, err + } + return operation, nil +} + +// sameInstallation returns an existing installation only if it is the one +// this request would create: the same spec and the same incarnation labels, +// so one for another Device or Installation incarnation is a conflict. Each +// seal has a fresh salt, so of the sealed reference only its presence is +// compared. +func sameInstallation(want *ops.DeviceInstallation, bootstrap bool, existing *ops.DeviceInstallation) (*ops.DeviceInstallation, error) { + if (existing.Spec.Bootstrap != nil) != bootstrap { + return nil, fmt.Errorf("%w: %s exists with other bootstrap data", ErrConflict, want.Name) + } + mine, theirs := *want, *existing + mine.Spec.Bootstrap, theirs.Spec.Bootstrap = nil, nil + wantDigest, err := specDigest(&mine) + if err != nil { + return nil, err + } + gotDigest, err := specDigest(&theirs) + if err != nil { + return nil, err + } + if wantDigest != gotDigest { + return nil, fmt.Errorf("%w: %s exists with other inputs", ErrConflict, want.Name) + } + for key, value := range want.Labels { + if existing.Labels[key] != value { + return nil, fmt.Errorf("%w: %s exists for another %s", ErrConflict, want.Name, key) + } + } + return existing, nil } // installClaims and wipeClaims are each requester's boot address source, diff --git a/internal/allocation/bootstrap_test.go b/internal/allocation/bootstrap_test.go new file mode 100644 index 00000000..c540f139 --- /dev/null +++ b/internal/allocation/bootstrap_test.go @@ -0,0 +1,130 @@ +package allocation + +import ( + "encoding/json" + "sync" + "testing" + + "sigs.k8s.io/controller-runtime/pkg/client" + + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/custody" + "go.datum.net/fleet/internal/sealed" + "go.datum.net/fleet/internal/site" + "go.datum.net/fleet/internal/site/simwork" +) + +// TestBootstrapReachesTheServerAndEveryCopyIsDeleted installs with bootstrap +// data through custody and the simulator site. The operation carries only a +// reference and a digest, the server is handed exactly the sealed data, and +// once the operation ends no copy remains in the provider project or at the +// site. A payload a crash left behind, and the loser of a concurrent +// admission, are swept too. +func TestBootstrapReachesTheServerAndEveryCopyIsDeleted(t *testing.T) { + e := startEnv(t) + device := e.server(1) + allocation, err := e.allocator.Allocate(e.ctx, e.request(1)) + if err != nil { + t.Fatal(err) + } + installation := e.installation(1, "debian-12", "") + installation.Spec.BootstrapConfigRef = &fleetv1.LocalReference{Name: "example-bootstrap"} + payload := sealed.Payload{UserData: "#cloud-config\nhostname: example\n", SSHAuthorizedKeys: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIExampleOnly example@example.com\n"} + withBootstrap := image() + withBootstrap.Definition.BootstrapFormats = []string{fleetv1.BootstrapNoCloud} + + // Bootstrap data for an image that takes none is refused before + // anything is written. + if _, err := e.allocator.Install(e.ctx, allocation, Installation{Installation: installation, Image: image(), Bootstrap: &payload}); err == nil { + t.Fatal("an image without a bootstrap format accepted bootstrap data") + } + e.requirePayloads(0) + + // A crash between the sealed write and the operation leaves a payload + // that no operation names. + name := custody.InstallationName(allocation.Name, string(installation.UID)) + orphan, err := sealed.Seal(payload, name, allocation.Name, namespace) + if err != nil { + t.Fatal(err) + } + e.create(orphan) + + // Two concurrent admissions of the same Installation: one operation. + var wg sync.WaitGroup + operations := make([]*ops.DeviceInstallation, 2) + for i := range operations { + wg.Add(1) + go func() { + defer wg.Done() + var err error + operations[i], err = e.allocator.Install(e.ctx, allocation, Installation{Installation: installation, Image: withBootstrap, Bootstrap: &payload}) + if err != nil { + t.Error(err) + } + }() + } + wg.Wait() + if t.Failed() { + t.FailNow() + } + operation := operations[0] + if operations[1].UID != operation.UID || operation.Spec.Bootstrap == nil { + t.Fatalf("operations = %v, %v", operations[0].Spec.Bootstrap, operations[1].Spec.Bootstrap) + } + reference := *operation.Spec.Bootstrap + if reference.Ref == orphan.Name { + t.Fatal("the operation names the payload a crash left behind") + } + // Admission is final once the operation exists: a retry after the + // customer edited the Secret returns the admitted operation and seals + // nothing new. + before := e.payloads() + edited := sealed.Payload{UserData: "#cloud-config\nhostname: edited\n"} + again, err := e.allocator.Install(e.ctx, allocation, Installation{Installation: installation, Image: withBootstrap, Bootstrap: &edited}) + if err != nil || again.UID != operation.UID || *again.Spec.Bootstrap != reference || e.payloads() != before { + t.Fatalf("retry = %v, %v; payloads %d, before %d", again.Spec.Bootstrap, err, e.payloads(), before) + } + + e.until("the installation succeeds", func() bool { + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(operation), operation); err != nil { + t.Fatal(err) + } + if operation.Status.Phase.Ended() && operation.Status.Phase != ops.PhaseSucceeded { + t.Fatalf("installation ended %s: %s", operation.Status.Phase, operation.Status.Message) + } + return operation.Status.Phase == ops.PhaseSucceeded + }) + server, err := simwork.ReadServer(e.store, namespace+"/"+device.Name) + if err != nil || server.Bootstrap != reference.Digest { + t.Fatalf("the server was handed %q, want %q: %v", server.Bootstrap, reference.Digest, err) + } + var evidence ops.InstallationEvidence + if err := json.Unmarshal(operation.Status.Evidence.Raw, &evidence); err != nil || evidence.Bootstrap != reference.Digest { + t.Fatalf("evidence = %+v, %v", evidence, err) + } + // The ended operation's payload, the orphan and the concurrent loser are + // deleted, and the site kept no copy. + e.until("no sealed payload remains", func() bool { return e.payloads() == 0 }) + if records, err := e.store.Records("payload"); err != nil || len(records) != 0 { + t.Fatalf("site payloads = %d, %v", len(records), err) + } + if got, _ := (site.StorePayloads{Store: e.store}).Get(e.ctx, site.Assignment{Device: namespace + "/" + device.Name, Operation: ops.OperationReference{Kind: "DeviceInstallation", Name: operation.Name}, Fence: operation.Status.Admission.Fence}); got != nil { + t.Fatal("the site still holds the payload") + } +} + +func (e *env) payloads() int { + var list ops.SealedPayloadList + if err := e.admin.List(e.ctx, &list, client.InNamespace(namespace)); err != nil { + e.t.Fatal(err) + } + return len(list.Items) +} + +func (e *env) requirePayloads(want int) { + e.t.Helper() + if got := e.payloads(); got != want { + e.t.Fatalf("sealed payloads = %d, want %d", got, want) + } +} diff --git a/internal/allocation/harness_test.go b/internal/allocation/harness_test.go index 9f7162c8..4064fae6 100644 --- a/internal/allocation/harness_test.go +++ b/internal/allocation/harness_test.go @@ -119,7 +119,7 @@ func startEnvWith(t *testing.T, crds ...*apiextensionsv1.CustomResourceDefinitio t.Fatal(err) } runner := &site.Runner{Site: siteName, Store: e.store, Results: site.NewResults(e.store), Access: fixture.Access{Enrollment: e.enrollment}, - Kinds: map[string]site.Kind{"DeviceInstallation": simwork.Installation{}, "DeviceWipe": simwork.Wipe{}, "DeviceCommissioning": simwork.Commissioning{}}, Poll: 20 * time.Millisecond} + Kinds: map[string]site.Kind{"DeviceInstallation": simwork.Installation{}, "DeviceWipe": simwork.Wipe{}, "DeviceCommissioning": simwork.Commissioning{}}, Payloads: site.StorePayloads{Store: e.store}, Poll: 20 * time.Millisecond} e.runner = runner dispatcher := &siteapi.Dispatcher{Runner: runner, Context: ctx} server := httptest.NewServer(siteapi.Handler(dispatcher, e.store, runner.Results, custody.NetworkBootOnly, func() (string, error) { return siteToken, nil })) diff --git a/internal/allocation/install_test.go b/internal/allocation/install_test.go new file mode 100644 index 00000000..ca988789 --- /dev/null +++ b/internal/allocation/install_test.go @@ -0,0 +1,127 @@ +package allocation + +import ( + "context" + "errors" + "testing" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/client/interceptor" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/custody" + "go.datum.net/fleet/internal/sealed" +) + +type installTestSite struct{ offering } + +func (installTestSite) Serving(*inventory.Device) []string { return []string{"test-site"} } + +// TestAnInstallationNameHeldByAnotherOperationIsAConflict: Install returns +// an operation that already holds the Installation's name only if it is +// this request's. One for another Device incarnation, or one that disagrees +// on whether bootstrap data was admitted, is a conflict, whether Install +// finds it first or loses the create race to it. +func TestAnInstallationNameHeldByAnotherOperationIsAConflict(t *testing.T) { + scheme := runtime.NewScheme() + if err := inventory.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + sites := installTestSite{offering{methods: custody.NetworkBootOnly}} + meta := metav1.ObjectMeta{Name: "server-example-001", Namespace: "default"} + provider := func() *fake.ClientBuilder { + return fake.NewClientBuilder().WithScheme(scheme).WithObjects(&inventory.Device{ObjectMeta: meta}, &ops.DeviceCustody{ObjectMeta: meta}) + } + if err := ops.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + allocation := &fleetv1.MachineAllocation{ + ObjectMeta: metav1.ObjectMeta{Name: "alloc-example", Labels: map[string]string{fleetv1.LabelDeviceUID: "device-1"}}, + Spec: fleetv1.MachineAllocationSpec{ + DeviceRef: fleetv1.AllocatedDeviceReference{Name: "server-example-001"}, + Hardware: fleetv1.Hardware{CPU: fleetv1.HardwareCPU{Architecture: "amd64"}, Firmware: &fleetv1.HardwareFirmware{BootMode: fleetv1.FirmwareUEFI}}, + BootInterface: "primary", + TargetDisks: []string{"disk-0"}, + }, + Status: fleetv1.MachineAllocationStatus{Phase: fleetv1.AllocationActive}, + } + request := func(bootstrap bool) Installation { + installation := &fleetv1.Installation{ObjectMeta: metav1.ObjectMeta{Name: "example-os", Namespace: "default", UID: "installation-1"}, Spec: fleetv1.InstallationSpec{ExpectedPredecessor: fleetv1.InstallationPredecessor{Type: "None"}}} + resolved := image() + resolved.Definition.BootstrapFormats = []string{fleetv1.BootstrapNoCloud} + r := Installation{Installation: installation, Image: resolved} + if bootstrap { + installation.Spec.BootstrapConfigRef = &fleetv1.LocalReference{Name: "example-bootstrap"} + r.Bootstrap = &sealed.Payload{SSHAuthorizedKeys: "ssh-ed25519 AAAAExampleOnly"} + } + return r + } + // admitted is the operation Install writes for a request into an empty + // provider project. + admitted := func(bootstrap bool) *ops.DeviceInstallation { + a := &Allocator{Provider: provider().Build(), Namespace: "default", Sites: sites} + operation, err := a.Install(context.Background(), allocation, request(bootstrap)) + if err != nil { + t.Fatal(err) + } + operation.ResourceVersion = "" + return operation + } + for name, test := range map[string]struct { + change func(*ops.DeviceInstallation) + held bool + bootstrap bool + ok bool + }{ + "this request's operation": {change: func(*ops.DeviceInstallation) {}, ok: true}, + "this request's operation with bootstrap": {held: true, bootstrap: true, change: func(*ops.DeviceInstallation) {}, ok: true}, + "another Device incarnation": {change: func(o *ops.DeviceInstallation) { o.Labels[ops.LabelDeviceUID] = "device-0" }}, + "another Installation incarnation": {change: func(o *ops.DeviceInstallation) { o.Labels[ops.LabelInstallationUID] = "installation-0" }}, + "other inputs": {change: func(o *ops.DeviceInstallation) { o.Spec.TargetDisks = []string{"disk-1"} }}, + "bootstrap data the request does not have": {held: true, change: func(*ops.DeviceInstallation) {}}, + "no bootstrap data where the request has": {bootstrap: true, change: func(*ops.DeviceInstallation) {}}, + } { + for _, race := range []bool{false, true} { + label := name + ", found first" + if race { + label = name + ", after a lost create race" + } + t.Run(label, func(t *testing.T) { + existing := admitted(test.held) + test.change(existing) + // A lost race: the first read finds nothing, and the + // create then meets the other admission's operation. + hidden := race + c := provider().WithObjects(existing).WithInterceptorFuncs(interceptor.Funcs{ + Get: func(ctx context.Context, c client.WithWatch, key client.ObjectKey, object client.Object, opts ...client.GetOption) error { + if _, ok := object.(*ops.DeviceInstallation); ok && hidden { + hidden = false + return apierrors.NewNotFound(ops.GroupVersion.WithResource("deviceinstallations").GroupResource(), key.Name) + } + return c.Get(ctx, key, object, opts...) + }, + }).Build() + a := &Allocator{Provider: c, Namespace: "default", Sites: sites} + operation, err := a.Install(context.Background(), allocation, request(test.bootstrap)) + if test.ok { + if err != nil || operation == nil || operation.Name != existing.Name { + t.Fatalf("operation = %v, %v", operation, err) + } + return + } + if !errors.Is(err, ErrConflict) || operation != nil { + t.Fatalf("operation = %v, err = %v; want a conflict", operation, err) + } + if hidden { + t.Fatal("the race was not exercised") + } + }) + } + } +} diff --git a/internal/api/operations/v1alpha1/config_test.go b/internal/api/operations/v1alpha1/config_test.go index e8c5b7aa..677fefbd 100644 --- a/internal/api/operations/v1alpha1/config_test.go +++ b/internal/api/operations/v1alpha1/config_test.go @@ -64,7 +64,7 @@ func decodeDir[T any](t *testing.T, dir string) []T { func loadCRDs(t *testing.T) map[string]*extensionsv1.CustomResourceDefinition { t.Helper() out := map[string]*extensionsv1.CustomResourceDefinition{} - for _, crd := range decodeAll[extensionsv1.CustomResourceDefinition](t, filepath.Join(componentRoot, "crds", "fleet.datumapis.com.yaml")) { + for _, crd := range decodeDir[extensionsv1.CustomResourceDefinition](t, filepath.Join(componentRoot, "crds")) { copied := crd out[crd.Spec.Names.Kind] = &copied } @@ -73,8 +73,8 @@ func loadCRDs(t *testing.T) map[string]*extensionsv1.CustomResourceDefinition { func TestCRDContract(t *testing.T) { crds := loadCRDs(t) - 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)) + if len(crds) != 3+len(operationKinds)+len(planKinds) || crds["DeviceCustody"] == nil || crds["CleaningPolicy"] == nil || crds["SealedPayload"] == nil { + t.Fatalf("got %d CRDs, want DeviceCustody, CleaningPolicy, SealedPayload, the operation kinds and the plan kinds", len(crds)) } for kind, crd := range crds { version := crd.Spec.Versions[0] @@ -85,7 +85,13 @@ func TestCRDContract(t *testing.T) { t.Fatalf("%s must be served only in Milo project control planes", kind) } properties := version.Schema.OpenAPIV3Schema.Properties - if kind == "DeviceCustody" { + if kind == "SealedPayload" { + // The sealed store has no status, and its spec never changes. + spec := properties["spec"] + if version.Subresources != nil || len(spec.XValidations) == 0 || spec.XValidations[0].Rule != "self == oldSelf" { + t.Fatal("SealedPayload must be immutable and have no status") + } + } else if kind == "DeviceCustody" { // Custody keeps its fields in spec, like a Lease. if version.Subresources != nil || len(properties["status"].Properties) != 0 { t.Fatal("DeviceCustody has no status") @@ -244,13 +250,13 @@ 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+"cleaningpolicies", "get"), 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+"sealedpayloads", "create"), 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(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...)), } - coordinator := slices.Concat(p(group+"devicecustodies", "get", "list", "watch", "create", "update", "delete"), p(group+"devices", read...), p("metal.datumapis.com/machineallocations", read...), p("metal.datumapis.com/machinecapacities", read...)) + coordinator := slices.Concat(p(group+"sealedpayloads", "get", "list", "watch", "delete"), p(group+"devicecustodies", "get", "list", "watch", "create", "update", "delete"), p(group+"devices", read...), p("metal.datumapis.com/machineallocations", read...), p("metal.datumapis.com/machinecapacities", read...)) for _, plural := range []string{"deviceinstallations", "devicewipes", "devicepoweroperations", "devicerecoveries", "devicecommissionings"} { coordinator = slices.Concat(coordinator, p(group+plural, "get", "list", "watch", "delete", "updateStatus"), []string{group + plural + "/status.update"}) } @@ -289,8 +295,13 @@ func TestRolesKeepOneWriterAndKeepStaffFromCustomerSecrets(t *testing.T) { if name != "fleet.datumapis.com-device-coordinator" && (strings.Contains(permission, "/status.") || strings.HasSuffix(permission, ".updateStatus") || (resource == "devicecustodies" && !slices.Contains(read, verb))) { t.Fatalf("%s writes custody or status: %s", name, permission) } - // No role reads a sealed store, a Secret or a bootstrap payload. - if strings.Contains(permission, "secret") || strings.Contains(permission, "sealed") || strings.Contains(permission, "bootstrap") { + // No role but the coordinator reads the sealed store, and no role + // reads a Secret or a bootstrap payload. The Metal provider may + // only create a sealed payload. + if strings.Contains(permission, "secret") || strings.Contains(permission, "bootstrap") { + t.Fatalf("%s grants %s", name, permission) + } + if resource == "sealedpayloads" && name != "fleet.datumapis.com-device-coordinator" && !(name == "fleet.datumapis.com-device-installation-requester" && verb == "create") { t.Fatalf("%s grants %s", name, permission) } } @@ -558,6 +569,67 @@ func TestBootAddressRolesAreOptIn(t *testing.T) { } } +// TestNoStaffRoleReadsTheSealedStore walks every Milo role the repository +// ships, in every component, and resolves inherited roles. Only the +// coordinator may get, list or watch a SealedPayload, and no role holds a +// wildcard that would reach it. +func TestNoStaffRoleReadsTheSealedStore(t *testing.T) { + roles := map[string]role{} + err := filepath.WalkDir(configRoot, func(path string, entry fs.DirEntry, err error) error { + if err != nil || entry.IsDir() || filepath.Ext(path) != ".yaml" || filepath.Base(path) == "kustomization.yaml" { + return err + } + data, err := os.ReadFile(path) + if err != nil || !strings.Contains(string(data), "kind: Role") || !strings.Contains(string(data), "iam.miloapis.com") { + return err + } + for _, r := range decodeAll[role](t, path) { + if r.Metadata.Name != "" && len(r.Spec.Included)+len(r.Spec.Inherited) > 0 { + roles[r.Metadata.Name] = r + } + } + return nil + }) + if err != nil { + t.Fatal(err) + } + if len(roles) < 10 { + t.Fatalf("found only %d Milo roles; the walk is not reading the config", len(roles)) + } + var resolve func(name string, seen map[string]bool) []string + resolve = func(name string, seen map[string]bool) []string { + if seen[name] { + return nil + } + seen[name] = true + out := slices.Clone(roles[name].Spec.Included) + for _, parent := range roles[name].Spec.Inherited { + out = append(out, resolve(parent.Name, seen)...) + } + return out + } + readers := 0 + for name := range roles { + for _, permission := range resolve(name, map[string]bool{}) { + if strings.Contains(permission, "*") { + t.Errorf("%s holds the wildcard %s", name, permission) + } + verb, ok := strings.CutPrefix(permission, GroupVersion.Group+"/sealedpayloads.") + if !ok || verb == "create" && name == "fleet.datumapis.com-device-installation-requester" { + continue + } + if name != "fleet.datumapis.com-device-coordinator" { + t.Errorf("%s holds %s", name, permission) + } else if slices.Contains([]string{"get", "list", "watch"}, verb) { + readers++ + } + } + } + if readers != 3 { + t.Fatalf("the coordinator holds %d of get, list and watch on the sealed store", readers) + } +} + // 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. diff --git a/internal/api/operations/v1alpha1/types.go b/internal/api/operations/v1alpha1/types.go index d304e313..40a38759 100644 --- a/internal/api/operations/v1alpha1/types.go +++ b/internal/api/operations/v1alpha1/types.go @@ -422,15 +422,49 @@ type DownloadInput struct { } // SealedInput is an opaque reference into the sealed store and the digest of -// what it holds. Operations never carry the payload. +// what it holds. Operations never carry the payload. Ref names a +// SealedPayload in the operation's namespace. type SealedInput struct { Ref string `json:"ref"` Digest string `json:"digest"` } +// SealedPayload is the sealed store: one copy of a customer's bootstrap +// data for one operation, in the provider project. Only the coordinator, +// which includes the federation courier, can read it; the Fleet provider +// for Metal can only create it. Its spec never changes. +type SealedPayload struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + Spec SealedPayloadSpec `json:"spec"` +} + +type SealedPayloadList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []SealedPayload `json:"items"` +} + +type SealedPayloadSpec struct { + // OperationName and AllocationName are the operation the payload is + // for, and its allocation. The sweep reads them. + OperationName string `json:"operationName"` + AllocationName string `json:"allocationName"` + // Digest covers Salt and Data, so a reader of the operation cannot + // confirm a guessed value against it. + Digest string `json:"digest"` + Salt []byte `json:"salt"` + // Data is the bootstrap data, exactly as the customer stored it. + Data []byte `json:"data"` +} + // InstallationEvidence is the result evidence of a DeviceInstallation. type InstallationEvidence struct { Steps []StepEvidence `json:"steps,omitempty"` + // Bootstrap is the digest of the bootstrap data the worker handed to + // the server, recomputed from what it handed. It is the operation's + // salted digest, never a hash of the data alone. + Bootstrap string `json:"bootstrap,omitempty"` } // StepEvidence records one journaled step. It never carries a BMC response. @@ -574,7 +608,7 @@ type DeviceRecoveryList struct { } func addKnown(s *runtime.Scheme) error { - s.AddKnownTypes(GroupVersion, &DeviceCustody{}, &DeviceCustodyList{}, &DeviceInstallation{}, &DeviceInstallationList{}, &DeviceWipe{}, &DeviceWipeList{}, &DeviceRecovery{}, &DeviceRecoveryList{}, &CleaningPolicy{}, &CleaningPolicyList{}) + s.AddKnownTypes(GroupVersion, &DeviceCustody{}, &DeviceCustodyList{}, &DeviceInstallation{}, &DeviceInstallationList{}, &DeviceWipe{}, &DeviceWipeList{}, &DeviceRecovery{}, &DeviceRecoveryList{}, &CleaningPolicy{}, &CleaningPolicyList{}, &SealedPayload{}, &SealedPayloadList{}) if err := addPower(s); err != nil { return err } @@ -592,6 +626,8 @@ func (in *DeviceWipe) DeepCopyObject() runtime.Object { return deepC func (in *DeviceWipeList) DeepCopyObject() runtime.Object { return deepCopy(in) } func (in *DeviceRecovery) DeepCopyObject() runtime.Object { return deepCopy(in) } func (in *DeviceRecoveryList) DeepCopyObject() runtime.Object { return deepCopy(in) } +func (in *SealedPayload) DeepCopyObject() runtime.Object { return deepCopy(in) } +func (in *SealedPayloadList) DeepCopyObject() runtime.Object { return deepCopy(in) } // DeepCopy returns a copy of custody. func (in *DeviceCustody) DeepCopy() *DeviceCustody { return deepCopy(in) } diff --git a/internal/coordination/transport.go b/internal/coordination/transport.go index cf5479a5..93f7ef23 100644 --- a/internal/coordination/transport.go +++ b/internal/coordination/transport.go @@ -191,7 +191,16 @@ func (h *Hub) ensure(ctx context.Context, name, role string, spec Spec) (*unstru return object, nil } -func (h *Hub) Deliver(ctx context.Context, assignment site.Assignment) error { +// ErrBootstrapUnsupported means the federation transport does not yet +// carry bootstrap payloads to a cell. The assignment is not delivered. +// Admission refuses such an operation first, because Hub does not report +// that it carries payloads. +var ErrBootstrapUnsupported = errors.New("coordination: federation does not carry bootstrap payloads yet") + +func (h *Hub) Deliver(ctx context.Context, assignment site.Assignment, payload *site.Payload) error { + if payload != nil || assignment.Sealed() != nil { + return ErrBootstrapUnsupported + } data, err := json.Marshal(assignment) if err != nil { return err diff --git a/internal/coordination/transport_test.go b/internal/coordination/transport_test.go index 0fc0d61f..e2519e81 100644 --- a/internal/coordination/transport_test.go +++ b/internal/coordination/transport_test.go @@ -6,9 +6,11 @@ import ( "errors" "fmt" "os" + "strings" "testing" "time" + 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" @@ -151,16 +153,16 @@ func TestAssignmentRoundTrip(t *testing.T) { t.Fatalf("report = %+v %v %v", report, reported, err) } assignment := f.wipe(3, "00000000-0000-4000-8000-000000000101") - if err := f.hub.Deliver(f.ctx, assignment); err != nil { + if err := f.hub.Deliver(f.ctx, assignment, nil); err != nil { t.Fatal(err) } // Delivery is idempotent; other contents under the same name conflict. - if err := f.hub.Deliver(f.ctx, assignment); err != nil { + if err := f.hub.Deliver(f.ctx, assignment, nil); err != nil { t.Fatal(err) } changed := assignment changed.Deadline = changed.Deadline.Add(time.Second) - if err := f.hub.Deliver(f.ctx, changed); err != ErrConflict { + if err := f.hub.Deliver(f.ctx, changed, nil); err != ErrConflict { t.Fatalf("changed delivery err = %v", err) } f.fed.sync() @@ -295,6 +297,24 @@ func TestTheCellRunsOnlyItsOwnAssignments(t *testing.T) { } } +// TestTheHubRefusesABootstrapPayload: federation does not carry payloads +// yet, so the hub writes no handoff for an assignment that names one, and +// it does not report that it carries them, so admission refuses first. +func TestTheHubRefusesABootstrapPayload(t *testing.T) { + f := newFixture(t) + assignment := f.wipe(3, "00000000-0000-4000-8000-000000000111") + assignment.Inputs = json.RawMessage(`{"bootstrap":{"ref":"sealed-example","digest":"sha256:` + strings.Repeat("a", 64) + `"}}`) + if err := f.hub.Deliver(f.ctx, assignment, nil); !errors.Is(err, ErrBootstrapUnsupported) { + t.Fatalf("err = %v", err) + } + if _, err := f.hub.api().Get(f.ctx, AssignmentName(assignment), metav1.GetOptions{}); !apierrors.IsNotFound(err) { + t.Fatalf("a handoff was written: %v", err) + } + if _, ok := any(f.hub).(interface{ CarriesPayloads() bool }); ok { + t.Fatal("the hub claims to carry payloads") + } +} + // TestTheHubReadsTheSiteDeliveryDeclaration reads the declaration the // site's observer publishes on the report handoff, follows its changes, and // counts a missing, unreadable or stale one as no declaration. diff --git a/internal/custody/admission_test.go b/internal/custody/admission_test.go index 88450467..caeedda9 100644 --- a/internal/custody/admission_test.go +++ b/internal/custody/admission_test.go @@ -12,6 +12,7 @@ import ( ops "go.datum.net/fleet/internal/api/operations/v1alpha1" fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" "go.datum.net/fleet/internal/bootaddress" + "go.datum.net/fleet/internal/sealed" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" @@ -261,27 +262,75 @@ func TestAdmissionPreconditions(t *testing.T) { e.requireUntouched(device.Name, fence) }) - t.Run("bootstrap stays refused", func(t *testing.T) { + t.Run("bootstrap needs its sealed payload", func(t *testing.T) { e := e.sub(t) + installation := func(device *inventory.Device, allocation, request string, bootstrap *ops.SealedInput, bootInterface string) *ops.DeviceInstallation { + return &ops.DeviceInstallation{ObjectMeta: metav1.ObjectMeta{Name: InstallationName(allocation, request), Namespace: "default", Labels: map[string]string{ops.LabelInstallationUID: request}}, Spec: ops.DeviceInstallationSpec{ + OperationEnvelope: envelope(device, providerUser, allocated(allocation)), + Image: ops.ImageInput{Name: "debian-12", Digest: imageDigest}, Bootstrap: bootstrap, BootInterface: bootInterface, TargetDisks: []string{"disk-0"}, Delivery: ops.DeliveryInput{Method: ops.DeliveryNetworkBoot}, + }} + } + seal := func(operation, allocation string) *ops.SealedPayload { + payload, err := sealed.Seal(sealed.Payload{SSHAuthorizedKeys: "ssh-ed25519 AAAAExampleOnly"}, operation, allocation, "default") + if err != nil { + t.Fatal(err) + } + return payload + } device := fresh() if err := e.coord.Claim(e.ctx, device.Name, device.UID, "alloc-boot"); err != nil { t.Fatal(err) } fence := e.custody(device.Name).Spec.Fence - operation := &ops.DeviceInstallation{ObjectMeta: metav1.ObjectMeta{Name: InstallationName("alloc-boot", "request-1"), Namespace: "default", Labels: map[string]string{ops.LabelInstallationUID: "request-1"}}, Spec: ops.DeviceInstallationSpec{ - OperationEnvelope: envelope(device, providerUser, allocated("alloc-boot")), - Image: ops.ImageInput{Name: "debian-12", Digest: imageDigest}, Bootstrap: &ops.SealedInput{Ref: "sealed-example", Digest: imageDigest}, BootInterface: "primary", TargetDisks: []string{"disk-0"}, Delivery: ops.DeliveryInput{Method: ops.DeliveryNetworkBoot}, - }} - e.create(operation) - missing := &ops.DeviceInstallation{ObjectMeta: metav1.ObjectMeta{Name: InstallationName("alloc-boot", "request-2"), Namespace: "default", Labels: map[string]string{ops.LabelInstallationUID: "request-2"}}, Spec: ops.DeviceInstallationSpec{ - OperationEnvelope: envelope(device, providerUser, allocated("alloc-boot")), - Image: ops.ImageInput{Name: "debian-12", Digest: imageDigest}, BootInterface: "absent", TargetDisks: []string{"disk-0"}, Delivery: ops.DeliveryInput{Method: ops.DeliveryNetworkBoot}, - }} + // A reference to a payload that was never written. + absent := installation(device, "alloc-boot", "request-1", &ops.SealedInput{Ref: sealed.Name(InstallationName("alloc-boot", "request-1"), imageDigest), Digest: imageDigest}, "primary") + e.create(absent) + // A payload whose contents changed after its digest was taken. + tamperedName := InstallationName("alloc-boot", "request-2") + tampered := seal(tamperedName, "alloc-boot") + reference := &ops.SealedInput{Ref: tampered.Name, Digest: tampered.Spec.Digest} + tampered.Spec.Data = []byte(`{"sshAuthorizedKeys":"ssh-ed25519 AAAAOther"}`) + e.create(tampered) + e.create(installation(device, "alloc-boot", "request-2", reference, "primary")) + missing := installation(device, "alloc-boot", "request-3", nil, "absent") e.create(missing) e.settle(device.Name) - e.requirePhase(operation, ops.PhaseFailed, ReasonBootstrapUnsupported) + e.requirePhase(absent, ops.PhaseFailed, ReasonBootstrapUnavailable) + e.requirePhase(installation(device, "alloc-boot", "request-2", nil, ""), ops.PhaseFailed, ReasonBootstrapUnavailable) e.requirePhase(missing, ops.PhaseFailed, ReasonBootInterfaceUnknown) e.requireUntouched(device.Name, fence) + + // The payload it names, unchanged, is admitted. + other := fresh() + if err := e.coord.Claim(e.ctx, other.Name, other.UID, "alloc-good"); err != nil { + t.Fatal(err) + } + goodName := InstallationName("alloc-good", "request-1") + good := seal(goodName, "alloc-good") + e.create(good) + admitted := installation(other, "alloc-good", "request-1", &ops.SealedInput{Ref: good.Name, Digest: good.Spec.Digest}, "primary") + e.create(admitted) + e.settle(other.Name) + e.requirePhase(admitted, ops.PhaseAdmitted, "") + + // A Device served by a site that cannot receive bootstrap data is + // refused at admission, before its fence moves, even with a good + // payload. + federated := fresh() + e.sites.mu.Lock() + e.sites.noPayloads[federated.Name] = true + e.sites.mu.Unlock() + if err := e.coord.Claim(e.ctx, federated.Name, federated.UID, "alloc-fed"); err != nil { + t.Fatal(err) + } + fedFence := e.custody(federated.Name).Spec.Fence + fedPayload := seal(InstallationName("alloc-fed", "request-1"), "alloc-fed") + e.create(fedPayload) + refused := installation(federated, "alloc-fed", "request-1", &ops.SealedInput{Ref: fedPayload.Name, Digest: fedPayload.Spec.Digest}, "primary") + e.create(refused) + e.settle(federated.Name) + e.requirePhase(refused, ops.PhaseFailed, ReasonBootstrapUnsupported) + e.requireUntouched(federated.Name, fedFence) }) t.Run("a boot address must still be bound to its claim", func(t *testing.T) { diff --git a/internal/custody/bootstrap_evidence_test.go b/internal/custody/bootstrap_evidence_test.go new file mode 100644 index 00000000..d7317e23 --- /dev/null +++ b/internal/custody/bootstrap_evidence_test.go @@ -0,0 +1,37 @@ +package custody + +import ( + "strings" + "testing" + + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" +) + +// TestInstallEvidenceMustProveTheAdmittedBootstrap: a success is accepted +// only if its evidence names exactly the admitted bootstrap digest, and +// names none when the operation has no bootstrap data. +func TestInstallEvidenceMustProveTheAdmittedBootstrap(t *testing.T) { + evidence := DeviceInstallationKind().Evidence + digest := "sha256:" + strings.Repeat("ab", 32) + with := &ops.DeviceInstallation{Spec: ops.DeviceInstallationSpec{Bootstrap: &ops.SealedInput{Ref: "sealed-example", Digest: digest}}} + without := &ops.DeviceInstallation{} + for _, test := range []struct { + name string + operation *ops.DeviceInstallation + evidence string + ok bool + }{ + {"the admitted digest", with, `{"steps":[{"name":"disk","completedAt":"2026-11-25T00:00:00Z"}],"bootstrap":"` + digest + `"}`, true}, + {"no bootstrap proof", with, `{"steps":[{"name":"disk","completedAt":"2026-11-25T00:00:00Z"}]}`, false}, + {"another digest", with, `{"bootstrap":"sha256:` + strings.Repeat("cd", 32) + `"}`, false}, + {"none admitted, none handed", without, `{"steps":[{"name":"disk","completedAt":"2026-11-25T00:00:00Z"}]}`, true}, + {"none admitted, some handed", without, `{"bootstrap":"` + digest + `"}`, false}, + } { + t.Run(test.name, func(t *testing.T) { + _, err := evidence(test.operation, []byte(test.evidence)) + if test.ok != (err == nil) { + t.Fatalf("err = %v", err) + } + }) + } +} diff --git a/internal/custody/coordinator.go b/internal/custody/coordinator.go index 4c0e7aec..b0e0713f 100644 --- a/internal/custody/coordinator.go +++ b/internal/custody/coordinator.go @@ -36,6 +36,14 @@ type Sites interface { DeliveryMethods(ctx context.Context, site string, device *inventory.Device) ([]OfferedMethod, bool, error) } +// PayloadCarriers is implemented by Sites that can tell whether every site +// serving a Device can receive bootstrap payloads. Admission refuses an +// operation with bootstrap data for a Device one of them cannot serve, so +// it never holds the Device only to fail at its deadline. +type PayloadCarriers interface { + CarriesPayloads(device *inventory.Device) bool +} + // SiteFence is one site's fence report for one Device. type SiteFence struct { // Seen is the highest fence the site has stored. Admission and rebuild @@ -812,7 +820,7 @@ func (c *Coordinator) decide(ctx context.Context, kind *Kind, operation ops.Oper } return fail(ReasonOperationInProgress, "another operation is running, and staff operations never wait") } - admission := &Admission{Operation: operation, Custody: custody.DeepCopy(), Device: device, Row: row, Registry: c.Registry, Reader: c.Client, Now: now, DiscoveryInterval: cfg.DiscoveryInterval} + admission := &Admission{Operation: operation, Custody: custody.DeepCopy(), Device: device, Row: row, Registry: c.Registry, Reader: c.Client, Sites: c.Sites, Now: now, DiscoveryInterval: cfg.DiscoveryInterval} // A declaration that cannot be read counts as not current: a check that // needs it waits instead of deciding. if offers, known, err := Offered(ctx, c.Sites, device); err == nil { diff --git a/internal/custody/extension_test.go b/internal/custody/extension_test.go index 631c1408..76baab40 100644 --- a/internal/custody/extension_test.go +++ b/internal/custody/extension_test.go @@ -355,7 +355,7 @@ func TestRegistryValidatesDeclaredReasons(t *testing.T) { } } registry := testRegistry(t) - if !registry.Declared("DeviceInstallation", ReasonBootstrapUnsupported, RaisedByWorker) || !registry.Declared("DeviceInstallation", ReasonBootInterfaceUnknown, RaisedByCoordinator) || registry.Declared("DeviceInstallation", ReasonBootInterfaceUnknown, RaisedByWorker) { + if !registry.Declared("DeviceInstallation", ReasonBootstrapUnsupported, RaisedByWorker) || !registry.Declared("DeviceInstallation", ReasonBootstrapUnavailable, RaisedByCoordinator) || !registry.Declared("DeviceInstallation", ReasonBootInterfaceUnknown, RaisedByCoordinator) || registry.Declared("DeviceInstallation", ReasonBootInterfaceUnknown, RaisedByWorker) { t.Fatal("declared sources are not kept") } // A kind may settle no hold itself. diff --git a/internal/custody/harness_test.go b/internal/custody/harness_test.go index ed5f2ccc..d01370a0 100644 --- a/internal/custody/harness_test.go +++ b/internal/custody/harness_test.go @@ -72,6 +72,9 @@ type fakeSites struct { // place of its stopped fence, as a site whose older worker has not yet // stopped would report. seen map[string]int64 + // noPayloads names Devices a site serves that cannot receive bootstrap + // payloads, as a federated cell cannot yet. + noPayloads map[string]bool // methods, when set, replaces the site's declared delivery methods, // which default to network boot then virtual media. methods []OfferedMethod @@ -91,8 +94,14 @@ func (s *fakeSites) DeliveryMethods(context.Context, string, *inventory.Device) return []OfferedMethod{{Method: ops.DeliveryNetworkBoot}, {Method: ops.DeliveryVirtualMedia, Addresses: ops.AddressesDataNetwork, MediaService: "https://192.0.2.10:8443"}}, true, nil } +func (s *fakeSites) CarriesPayloads(device *inventory.Device) bool { + s.mu.Lock() + defer s.mu.Unlock() + return !s.noPayloads[device.Name] +} + func newFakeSites() *fakeSites { - return &fakeSites{serving: map[string][]string{}, fences: map[string]int64{}, seen: map[string]int64{}} + return &fakeSites{serving: map[string][]string{}, fences: map[string]int64{}, seen: map[string]int64{}, noPayloads: map[string]bool{}} } func (s *fakeSites) Serving(device *inventory.Device) []string { diff --git a/internal/custody/kinds.go b/internal/custody/kinds.go index 86b9774f..af44ac5a 100644 --- a/internal/custody/kinds.go +++ b/internal/custody/kinds.go @@ -9,6 +9,7 @@ import ( "strconv" "time" + "go.datum.net/fleet/internal/sealed" "sigs.k8s.io/controller-runtime/pkg/client" ops "go.datum.net/fleet/internal/api/operations/v1alpha1" @@ -30,6 +31,11 @@ const ( // Kind-specific refusal reasons. const ( + // ReasonBootstrapUnavailable: the sealed payload an installation names + // is missing or does not match it. + ReasonBootstrapUnavailable = "BootstrapUnavailable" + // ReasonBootstrapUnsupported: the site cannot yet hand bootstrap data + // to the server. ReasonBootstrapUnsupported = "BootstrapUnsupported" ReasonBootInterfaceUnknown = "BootInterfaceUnknown" ReasonHoldMismatch = "HoldMismatch" @@ -178,9 +184,22 @@ func DeviceInstallationKind() Kind { BootInterface: func(operation ops.Operation) string { return operation.(*ops.DeviceInstallation).Spec.BootInterface }, Check: func(ctx context.Context, admission *Admission) *Refusal { installation := admission.Operation.(*ops.DeviceInstallation) - // Bootstrap stays refused until the sealed store exists. - if installation.Spec.Bootstrap != nil { - return refuse(ReasonBootstrapUnsupported, "bootstrap payloads need the sealed store, which is not implemented") + // The sealed payload must exist and match at this custody update. + // The sweep never deletes the payload of an operation that has + // not ended, so it stays until the site has it. + if reference := installation.Spec.Bootstrap; reference != nil { + if carriers, ok := admission.Sites.(PayloadCarriers); ok && !carriers.CarriesPayloads(admission.Device) { + return refuse(ReasonBootstrapUnsupported, "a site serving the Device cannot receive bootstrap data") + } + payload := &ops.SealedPayload{} + if err := admission.Reader.Get(ctx, client.ObjectKey{Namespace: installation.Namespace, Name: reference.Ref}, payload); err != nil { + // Like every kind check, a read that fails refuses: the + // operation ends Failed and nothing is sent. + return refuse(ReasonBootstrapUnavailable, "the sealed bootstrap payload cannot be read") + } + if sealed.Verify(payload, installation.Name, *reference) != nil { + return refuse(ReasonBootstrapUnavailable, "the sealed bootstrap payload does not match the operation") + } } if refusal := checkDelivery(admission, &installation.Spec); refusal != nil { return refusal @@ -197,8 +216,17 @@ func DeviceInstallationKind() Kind { return map[string]string{ExtraDeliveryMethod: string(admission.Operation.(*ops.DeviceInstallation).Spec.Delivery.Method)} }, Settles: []SettleRule{{Held: "DeviceInstallation"}}, - Reasons: append(append(append([]Reason{{Name: ReasonImageIncompatible, RaisedBy: RaisedByWorker}, {Name: ReasonBootstrapUnsupported, RaisedBy: RaisedByBoth}}, networkBootReasons...), workerReasons...), deliveryReasons...), - Evidence: StrictEvidence(evidenceLimit, func(_ ops.Operation, evidence *ops.InstallationEvidence) error { + Reasons: append(append(append([]Reason{{Name: ReasonBootstrapUnavailable, RaisedBy: RaisedByCoordinator}, {Name: ReasonImageIncompatible, RaisedBy: RaisedByWorker}, {Name: ReasonBootstrapUnsupported, RaisedBy: RaisedByBoth}}, networkBootReasons...), workerReasons...), deliveryReasons...), + Evidence: StrictEvidence(evidenceLimit, func(operation ops.Operation, evidence *ops.InstallationEvidence) error { + // A success must prove the server was handed exactly the admitted + // bootstrap data, and nothing when there was none. + want := "" + if reference := operation.(*ops.DeviceInstallation).Spec.Bootstrap; reference != nil { + want = reference.Digest + } + if evidence.Bootstrap != want { + return errors.New("the evidence does not prove the admitted bootstrap data was handed to the server") + } return validateSteps(evidence.Steps) }), } diff --git a/internal/custody/registry.go b/internal/custody/registry.go index d8eaabb5..85eccb20 100644 --- a/internal/custody/registry.go +++ b/internal/custody/registry.go @@ -180,8 +180,11 @@ type Admission struct { Device *inventory.Device Row Rule Registry *Registry - // Reader reads the provider project. A check must not write. + // Reader reads the provider project. A check must not write. It reads + // through to the API server, so a missing object is missing now. Reader client.Reader + // Sites are the sites the coordinator delivers to. + Sites Sites // Now is the coordinator's injected clock, read once per decision. Now time.Time // DiscoveryInterval is how often BMC discovery reads each BMC. diff --git a/internal/delivery/delivery.go b/internal/delivery/delivery.go index bc256675..4a5a7e2b 100644 --- a/internal/delivery/delivery.go +++ b/internal/delivery/delivery.go @@ -19,13 +19,15 @@ import ( inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" ops "go.datum.net/fleet/internal/api/operations/v1alpha1" "go.datum.net/fleet/internal/custody" + "go.datum.net/fleet/internal/sealed" "go.datum.net/fleet/internal/site" ) // Site is the coordinator's view of one remote site. type Site interface { - // Deliver hands the site one assignment. It is idempotent. - Deliver(ctx context.Context, assignment site.Assignment) error + // Deliver hands the site one assignment and, beside it, the bootstrap + // payload its inputs name, if any. It is idempotent. + Deliver(ctx context.Context, assignment site.Assignment, payload *site.Payload) error // Fence returns the site's fence report for a "/" // Device, and false if the site has not reported one. Fence(ctx context.Context, device string) (custody.SiteFence, bool, error) @@ -58,7 +60,10 @@ func (s *Sites) DeliveryMethods(ctx context.Context, name string, device *invent return remote.DeliveryMethods(ctx, device.Namespace+"/"+device.Name) } -var _ custody.Sites = (*Sites)(nil) +var ( + _ custody.Sites = (*Sites)(nil) + _ custody.PayloadCarriers = (*Sites)(nil) +) func (s *Sites) Serving(device *inventory.Device) []string { var out []string @@ -70,6 +75,24 @@ func (s *Sites) Serving(device *inventory.Device) []string { return out } +// PayloadSite is implemented by a site that reports whether it can receive +// bootstrap payloads. A site that does not implement it cannot. +type PayloadSite interface { + CarriesPayloads() bool +} + +// CarriesPayloads reports whether every site serving the Device can +// receive bootstrap payloads. A Device no site serves carries none. +func (s *Sites) CarriesPayloads(device *inventory.Device) bool { + serving := s.Serving(device) + for _, name := range serving { + if site, ok := s.Sites[name].(PayloadSite); !ok || !site.CarriesPayloads() { + return false + } + } + return len(serving) > 0 +} + func (s *Sites) Fence(ctx context.Context, name string, device *inventory.Device) (custody.SiteFence, bool, error) { remote, ok := s.Sites[name] if !ok { @@ -152,19 +175,42 @@ func (c *Courier) Deliver(ctx context.Context, name string) error { if err != nil { return err } + payload, err := c.payload(ctx, assignment) + if err != nil { + return err + } device := &inventory.Device{} if err := c.Client.Get(ctx, client.ObjectKey{Namespace: c.Namespace, Name: name}, device); err != nil { return err } var failed error for _, serving := range c.Sites.Serving(device) { - if err := c.Sites.Sites[serving].Deliver(ctx, assignment); err != nil { + if err := c.Sites.Sites[serving].Deliver(ctx, assignment, payload); err != nil { failed = errors.Join(failed, fmt.Errorf("deliver to %s: %w", serving, err)) } } return failed } +// payload reads the sealed payload the assignment's inputs name, and +// checks it again. The courier is part of the coordinator, the only reader +// of the sealed store. +func (c *Courier) payload(ctx context.Context, assignment site.Assignment) (*site.Payload, error) { + reference := assignment.Sealed() + if reference == nil { + return nil, nil + } + sealed := &ops.SealedPayload{} + if err := c.Client.Get(ctx, client.ObjectKey{Namespace: c.Namespace, Name: reference.Ref}, sealed); err != nil { + return nil, fmt.Errorf("delivery: the sealed payload: %w", err) + } + payload := &site.Payload{Ref: sealed.Name, Digest: sealed.Spec.Digest, Salt: sealed.Spec.Salt, Data: sealed.Spec.Data} + if sealed.Spec.OperationName != assignment.Operation.Name || !payload.Matches(reference) { + return nil, errors.New("delivery: the sealed payload does not match the operation") + } + return payload, nil +} + // Collect reports every site's held results to the coordinator, and tells // the site to forget each one the coordinator accepted or rejected as stale. func (c *Courier) Collect(ctx context.Context) error { @@ -256,6 +302,11 @@ func (l *Loop) Pass(ctx context.Context) error { if err := l.Courier.Collect(ctx); err != nil { failed = errors.Join(failed, err) } + // Results were copied to operation status above, so a payload whose + // operation ended is deleted in the same pass. + if _, err := sealed.Sweep(ctx, l.Coordinator.Client, l.Namespace); err != nil { + failed = errors.Join(failed, err) + } if l.Capacity != nil { if err := l.Capacity.ProjectAll(ctx); err != nil { failed = errors.Join(failed, fmt.Errorf("capacity: %w", err)) diff --git a/internal/delivery/delivery_test.go b/internal/delivery/delivery_test.go index ead64345..6d0e1a79 100644 --- a/internal/delivery/delivery_test.go +++ b/internal/delivery/delivery_test.go @@ -1,13 +1,104 @@ package delivery import ( + "context" + "encoding/json" + "fmt" "testing" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + "go.datum.net/fleet/internal/custody" + "go.datum.net/fleet/internal/sealed" + "go.datum.net/fleet/internal/site" ) +const operationName = "alloc-example-install-1" + +func courier(t *testing.T, objects ...client.Object) *Courier { + t.Helper() + scheme := runtime.NewScheme() + if err := ops.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + return &Courier{Client: fake.NewClientBuilder().WithScheme(scheme).WithObjects(objects...).Build(), Namespace: "default"} +} + +func sealedFor(t *testing.T, operation string) *ops.SealedPayload { + t.Helper() + payload, err := sealed.Seal(sealed.Payload{SSHAuthorizedKeys: "ssh-ed25519 AAAAExampleOnly"}, operation, "alloc-example", "default") + if err != nil { + t.Fatal(err) + } + return payload +} + +func assignmentNaming(payload *ops.SealedPayload) site.Assignment { + inputs := json.RawMessage(fmt.Sprintf(`{"bootstrap":{"ref":%q,"digest":%q}}`, payload.Name, payload.Spec.Digest)) + return site.Assignment{Operation: ops.OperationReference{Kind: "DeviceInstallation", Name: operationName}, Inputs: inputs} +} + +// TestTheCourierDeliversOnlyTheAdmittedPayload reads the payload the +// admitted inputs name, checks it again, and refuses a missing, altered or +// foreign one rather than deliver it. +func TestTheCourierDeliversOnlyTheAdmittedPayload(t *testing.T) { + ctx := context.Background() + good := sealedFor(t, operationName) + if payload, err := courier(t, good).payload(ctx, assignmentNaming(good)); err != nil || payload == nil || payload.Digest != good.Spec.Digest { + t.Fatalf("payload = %+v, %v", payload, err) + } + if payload, err := courier(t).payload(ctx, site.Assignment{Inputs: json.RawMessage(`{}`)}); err != nil || payload != nil { + t.Fatalf("no bootstrap: %+v, %v", payload, err) + } + altered := sealedFor(t, operationName) + reference := assignmentNaming(altered) + altered.Spec.Data = []byte(`{"userData":"other"}`) + foreign := sealedFor(t, "alloc-other-install-1") + for name, test := range map[string]struct { + courier *Courier + assignment site.Assignment + }{ + "missing": {courier(t), assignmentNaming(good)}, + "altered": {courier(t, altered), reference}, + "another operation's": {courier(t, foreign), assignmentNaming(foreign)}, + } { + if payload, err := test.courier.payload(ctx, test.assignment); err == nil || payload != nil { + t.Errorf("%s payload delivered: %+v", name, payload) + } + } +} + +type siteWith struct { + Site + carries bool +} + +func (s siteWith) CarriesPayloads() bool { return s.carries } + +func TestADeviceCarriesPayloadsOnlyIfEverySiteServingItDoes(t *testing.T) { + device := &inventory.Device{ObjectMeta: metav1.ObjectMeta{Name: "server-example-001"}} + for name, test := range map[string]struct { + sites map[string]Site + want bool + }{ + "every site carries": {map[string]Site{"a": siteWith{carries: true}, "b": siteWith{carries: true}}, true}, + "one site does not": {map[string]Site{"a": siteWith{carries: true}, "b": siteWith{carries: false}}, false}, + "a site that cannot tell": {map[string]Site{"a": siteWith{carries: true}, "b": nil}, false}, + "no site serves it": {map[string]Site{}, false}, + } { + sites := &Sites{Sites: test.sites, Devices: map[string][]string{device.Name: {"a", "b"}}} + if got := sites.CarriesPayloads(device); got != test.want { + t.Errorf("%s: %v", name, got) + } + } + var _ custody.PayloadCarriers = (*Sites)(nil) +} + // TestOnlyTheAdmittedOperationIsDelivered never builds an assignment from // an operation that does not carry the fence custody admitted it at, so a // same-name operation created later is never delivered as the admitted one. diff --git a/internal/sealed/sealed.go b/internal/sealed/sealed.go new file mode 100644 index 00000000..53fc426c --- /dev/null +++ b/internal/sealed/sealed.go @@ -0,0 +1,230 @@ +// Package sealed is the sealed store for customer bootstrap data. The Fleet +// provider for Metal reads a customer's bootstrap Secret, validates it, and +// copies it into one SealedPayload per operation. The operation carries only +// the payload's name and digest. The coordinator checks the payload at +// admission and deletes it once nothing needs it; the federation courier +// delivers it to the operation's site. +// +// The digest covers a random salt and the data, so a staff member who can +// read the operation cannot confirm a guessed SSH key against it. +package sealed + +import ( + "bytes" + "context" + "crypto/rand" + "crypto/sha256" + "crypto/subtle" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "slices" + "unicode/utf8" + + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + "sigs.k8s.io/controller-runtime/pkg/client" + + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/catalog" +) + +// SecretType is the type of a customer's bootstrap Secret. +const SecretType corev1.SecretType = "metal.datumapis.com/bootstrap" + +// The bootstrap Secret's keys. +const ( + KeyUserData = "userData" + KeySSHAuthorizedKeys = "sshAuthorizedKeys" +) + +// MaxBytes bounds the bootstrap data, and MaxEncodedBytes its encoded form, +// which JSON escaping can make larger. A site receives the encoded form in +// base64 inside a request of at most 256 KiB. +const ( + MaxBytes = 64 << 10 + MaxEncodedBytes = 96 << 10 +) + +// Refusal reasons an Installation reports as Accepted=False. +const ( + ReasonBootstrapNotFound = "BootstrapNotFound" + ReasonBootstrapInvalid = "BootstrapInvalid" +) + +// Payload is a customer's bootstrap data, exactly as stored. +type Payload struct { + UserData string `json:"userData,omitempty"` + SSHAuthorizedKeys string `json:"sshAuthorizedKeys,omitempty"` +} + +// Read reads and validates the named bootstrap Secret in the +// Installation's namespace. The reader must act for the Installation's +// creator: the caller decides who may read the Secret. +func Read(ctx context.Context, reader client.Reader, namespace, name string) (Payload, error) { + secret := &corev1.Secret{} + if err := reader.Get(ctx, client.ObjectKey{Namespace: namespace, Name: name}, secret); apierrors.IsNotFound(err) || apierrors.IsForbidden(err) { + return Payload{}, &catalog.Refusal{Reason: ReasonBootstrapNotFound, Message: fmt.Sprintf("no readable bootstrap Secret %q in this namespace", name)} + } else if err != nil { + return Payload{}, err + } + return Validate(secret) +} + +// Validate checks a bootstrap Secret's type, keys and size. +func Validate(secret *corev1.Secret) (Payload, error) { + invalid := func(message string) (Payload, error) { + return Payload{}, &catalog.Refusal{Reason: ReasonBootstrapInvalid, Message: message} + } + if secret.Type != SecretType { + return invalid("the bootstrap Secret's type must be " + string(SecretType)) + } + size := 0 + for key, value := range secret.Data { + if key != KeyUserData && key != KeySSHAuthorizedKeys { + return invalid("the bootstrap Secret may hold only userData and sshAuthorizedKeys") + } + // Bootstrap data is text. Encoding would rewrite invalid UTF-8, + // and the server would not get exactly what was stored. + if !utf8.Valid(value) { + return invalid("the bootstrap Secret's values must be UTF-8 text") + } + size += len(value) + } + payload := Payload{UserData: string(secret.Data[KeyUserData]), SSHAuthorizedKeys: string(secret.Data[KeySSHAuthorizedKeys])} + if payload == (Payload{}) { + return invalid("the bootstrap Secret holds no userData or sshAuthorizedKeys") + } + if size > MaxBytes { + return invalid("the bootstrap Secret holds more than 64 KiB") + } + if encoded, err := json.Marshal(payload); err != nil || len(encoded) > MaxEncodedBytes { + return invalid("the bootstrap Secret holds too many characters that need escaping") + } + return payload, nil +} + +// Digest is the digest of a salt and the encoded data. +func Digest(salt, data []byte) string { + hash := sha256.New() + hash.Write(salt) + hash.Write(data) + return "sha256:" + hex.EncodeToString(hash.Sum(nil)) +} + +// Name is the only name a payload may have: its operation and its digest. +// A retry that reads changed data writes a new name, never new contents +// under an old one. +func Name(operation, digest string) string { + sum := sha256.Sum256([]byte(operation + "/" + digest)) + return "sealed-" + hex.EncodeToString(sum[:])[:20] +} + +// Seal encodes a payload with a new random salt for one operation. +func Seal(payload Payload, operation, allocation, namespace string) (*ops.SealedPayload, error) { + data, err := json.Marshal(payload) + if err != nil { + return nil, err + } + if len(data) > MaxEncodedBytes { + return nil, errors.New("sealed: the bootstrap data is too large to deliver") + } + salt := make([]byte, 32) + if _, err := rand.Read(salt); err != nil { + return nil, err + } + digest := Digest(salt, data) + object := &ops.SealedPayload{Spec: ops.SealedPayloadSpec{OperationName: operation, AllocationName: allocation, Digest: digest, Salt: salt, Data: data}} + object.Name, object.Namespace = Name(operation, digest), namespace + return object, nil +} + +// ErrMismatch means a payload is not the one an operation names. +var ErrMismatch = errors.New("sealed: the payload does not match its operation") + +// Verify checks that a payload is the one the operation's reference names: +// its name, its operation, and a digest recomputed from its contents. +func Verify(payload *ops.SealedPayload, operation string, reference ops.SealedInput) error { + spec := payload.Spec + if payload.Name != reference.Ref || payload.Name != Name(operation, reference.Digest) || spec.OperationName != operation || spec.Digest != reference.Digest || len(spec.Salt) != 32 { + return ErrMismatch + } + if subtle.ConstantTimeCompare([]byte(Digest(spec.Salt, spec.Data)), []byte(reference.Digest)) != 1 { + return ErrMismatch + } + return nil +} + +// Decode returns the payload's data. It refuses bytes that do not decode +// to exactly a bootstrap payload. +func Decode(data []byte) (Payload, error) { + var payload Payload + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.DisallowUnknownFields() + if err := decoder.Decode(&payload); err != nil || payload == (Payload{}) { + return Payload{}, ErrMismatch + } + return payload, nil +} + +// Ended reports whether an operation phase is one whose payload is no +// longer needed: no path delivers an ended operation again. +func Ended(phase ops.Phase) bool { + return slices.Contains([]ops.Phase{ops.PhaseSucceeded, ops.PhaseFailed, ops.PhaseCancelled, ops.PhaseOutcomeUnknown}, phase) +} + +// Sweep deletes every payload in the namespace that nothing can need +// again: one whose operation has ended, one whose operation names another +// payload, and one with no operation whose allocation is no longer Active. +// An allocation that is not Active cannot admit an install, so the last +// rule never removes a payload admission still needs. Each delete carries +// the payload's UID as a precondition. +func Sweep(ctx context.Context, api client.Client, namespace string) (int, error) { + var payloads ops.SealedPayloadList + if err := api.List(ctx, &payloads, client.InNamespace(namespace)); err != nil { + return 0, err + } + deleted := 0 + var failed error + for index := range payloads.Items { + payload := &payloads.Items[index] + remove, err := unneeded(ctx, api, payload) + if err != nil { + failed = errors.Join(failed, err) + continue + } + if !remove { + continue + } + uid := payload.UID + if err := api.Delete(ctx, payload, client.Preconditions{UID: &uid}); err != nil && !apierrors.IsNotFound(err) { + failed = errors.Join(failed, err) + continue + } + deleted++ + } + return deleted, failed +} + +func unneeded(ctx context.Context, api client.Client, payload *ops.SealedPayload) (bool, error) { + operation := &ops.DeviceInstallation{} + err := api.Get(ctx, client.ObjectKey{Namespace: payload.Namespace, Name: payload.Spec.OperationName}, operation) + if err == nil { + named := operation.Spec.Bootstrap != nil && operation.Spec.Bootstrap.Ref == payload.Name + return !named || Ended(operation.Status.Phase), nil + } + if !apierrors.IsNotFound(err) { + return false, err + } + allocation := &fleetv1.MachineAllocation{} + err = api.Get(ctx, client.ObjectKey{Namespace: payload.Namespace, Name: payload.Spec.AllocationName}, allocation) + if apierrors.IsNotFound(err) { + return true, nil + } + if err != nil { + return false, err + } + return allocation.Status.Phase != fleetv1.AllocationActive, nil +} diff --git a/internal/sealed/sealed_test.go b/internal/sealed/sealed_test.go new file mode 100644 index 00000000..ffd7f4b4 --- /dev/null +++ b/internal/sealed/sealed_test.go @@ -0,0 +1,205 @@ +package sealed + +import ( + "context" + "errors" + "strings" + "testing" + + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/types" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/catalog" +) + +func reason(t *testing.T, err error) string { + t.Helper() + var refusal *catalog.Refusal + if !errors.As(err, &refusal) { + t.Fatalf("err = %v, want a refusal", err) + } + return refusal.Reason +} + +func TestValidateAcceptsOnlyABootstrapSecret(t *testing.T) { + secret := func(kind corev1.SecretType, data map[string]string) *corev1.Secret { + s := &corev1.Secret{Type: kind, Data: map[string][]byte{}} + for k, v := range data { + s.Data[k] = []byte(v) + } + return s + } + for _, test := range []struct { + name string + secret *corev1.Secret + ok bool + }{ + {"user data", secret(SecretType, map[string]string{KeyUserData: "#cloud-config\n"}), true}, + {"keys", secret(SecretType, map[string]string{KeySSHAuthorizedKeys: "ssh-ed25519 AAAAExampleOnly"}), true}, + {"another type", secret(corev1.SecretTypeOpaque, map[string]string{KeyUserData: "#cloud-config\n"}), false}, + {"no keys", secret(SecretType, nil), false}, + {"an unknown key", secret(SecretType, map[string]string{KeyUserData: "x", "password": "x"}), false}, + {"over 64 KiB", secret(SecretType, map[string]string{KeyUserData: strings.Repeat("x", MaxBytes), KeySSHAuthorizedKeys: "x"}), false}, + } { + t.Run(test.name, func(t *testing.T) { + _, err := Validate(test.secret) + if test.ok != (err == nil) { + t.Fatalf("err = %v", err) + } + if err != nil && reason(t, err) != ReasonBootstrapInvalid { + t.Fatalf("reason = %v", err) + } + }) + } +} + +func TestReadRefusesAMissingSecret(t *testing.T) { + reader := fake.NewClientBuilder().Build() + if _, err := Read(context.Background(), reader, "default", "absent"); reason(t, err) != ReasonBootstrapNotFound { + t.Fatalf("err = %v", err) + } +} + +// TestVerifyRefusesEveryAlteredPayload: a payload must be the one the +// operation names, under its derived name, with a digest recomputed from its +// salt and data. +func TestVerifyRefusesEveryAlteredPayload(t *testing.T) { + payload, err := Seal(Payload{SSHAuthorizedKeys: "ssh-ed25519 AAAAExampleOnly"}, "alloc-1-install-1", "alloc-1", "default") + if err != nil { + t.Fatal(err) + } + reference := ops.SealedInput{Ref: payload.Name, Digest: payload.Spec.Digest} + if err := Verify(payload, "alloc-1-install-1", reference); err != nil { + t.Fatal(err) + } + for name, change := range map[string]func(*ops.SealedPayload, *ops.SealedInput, *string){ + "other data": func(p *ops.SealedPayload, _ *ops.SealedInput, _ *string) { p.Spec.Data = []byte(`{"userData":"x"}`) }, + "other salt": func(p *ops.SealedPayload, _ *ops.SealedInput, _ *string) { p.Spec.Salt[0] ^= 1 }, + "other operation": func(_ *ops.SealedPayload, _ *ops.SealedInput, operation *string) { *operation = "alloc-1-install-2" }, + "other name": func(p *ops.SealedPayload, r *ops.SealedInput, _ *string) { + p.Name, r.Ref = "sealed-other", "sealed-other" + }, + "other digest": func(_ *ops.SealedPayload, r *ops.SealedInput, _ *string) { + r.Digest = "sha256:" + strings.Repeat("0", 64) + }, + } { + t.Run(name, func(t *testing.T) { + copy := payload.DeepCopyObject().(*ops.SealedPayload) + ref, operation := reference, "alloc-1-install-1" + change(copy, &ref, &operation) + if err := Verify(copy, operation, ref); !errors.Is(err, ErrMismatch) { + t.Fatalf("err = %v", err) + } + }) + } + // Each seal has a new salt, so equal data never shares a digest. + again, _ := Seal(Payload{SSHAuthorizedKeys: "ssh-ed25519 AAAAExampleOnly"}, "alloc-1-install-1", "alloc-1", "default") + if again.Spec.Digest == payload.Spec.Digest || again.Name == payload.Name { + t.Fatal("two seals of the same data share a digest") + } +} + +// TestSweepDeletesOnlyWhatNothingNeeds covers each rule: a payload whose +// operation ended, one its operation does not name, and one with no +// operation whose allocation is not Active are deleted. The payload of a +// running operation, and one waiting for its operation under an Active +// allocation, are kept. +func TestSweepDeletesOnlyWhatNothingNeeds(t *testing.T) { + scheme := runtime.NewScheme() + for _, add := range []func(*runtime.Scheme) error{ops.AddToScheme, fleetv1.AddToScheme} { + if err := add(scheme); err != nil { + t.Fatal(err) + } + } + api := fake.NewClientBuilder().WithScheme(scheme).Build() + ctx := context.Background() + create := func(object client.Object) { + t.Helper() + if err := api.Create(ctx, object); err != nil { + t.Fatal(err) + } + } + allocation := func(name, phase string) { + a := &fleetv1.MachineAllocation{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: "default"}, Status: fleetv1.MachineAllocationStatus{Phase: phase}} + create(a) + } + seal := func(operation, allocation string) *ops.SealedPayload { + p, err := Seal(Payload{UserData: "#cloud-config\n"}, operation, allocation, "default") + if err != nil { + t.Fatal(err) + } + p.UID = types.UID("uid-" + p.Name) + create(p) + return p + } + operation := func(name string, payload *ops.SealedPayload, phase ops.Phase) { + o := &ops.DeviceInstallation{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: "default"}, Status: ops.OperationStatus{Phase: phase}} + if payload != nil { + o.Spec.Bootstrap = &ops.SealedInput{Ref: payload.Name, Digest: payload.Spec.Digest} + } + create(o) + } + allocation("alloc-active", fleetv1.AllocationActive) + allocation("alloc-released", fleetv1.AllocationReleased) + + running := seal("op-running", "alloc-active") + operation("op-running", running, ops.PhaseDispatched) + ended := seal("op-ended", "alloc-active") + operation("op-ended", ended, ops.PhaseOutcomeUnknown) + loser := seal("op-named", "alloc-active") + winner := seal("op-named", "alloc-active") + operation("op-named", winner, ops.PhaseAdmitted) + waiting := seal("op-not-yet-created", "alloc-active") + released := seal("op-never-created", "alloc-released") + gone := seal("op-never-created-2", "alloc-deleted") + + deleted, err := Sweep(ctx, api, "default") + if err != nil { + t.Fatal(err) + } + kept := map[string]bool{} + var list ops.SealedPayloadList + if err := api.List(ctx, &list); err != nil { + t.Fatal(err) + } + for _, p := range list.Items { + kept[p.Name] = true + } + for _, p := range []*ops.SealedPayload{running, winner, waiting} { + if !kept[p.Name] { + t.Errorf("%s was deleted", p.Spec.OperationName) + } + } + for _, p := range []*ops.SealedPayload{ended, loser, released, gone} { + if kept[p.Name] { + t.Errorf("%s (%s) was kept", p.Name, p.Spec.OperationName) + } + } + if deleted != 4 { + t.Fatalf("deleted %d", deleted) + } +} + +func TestValidateRefusesDataThatWouldNotArriveExactly(t *testing.T) { + for name, value := range map[string]string{ + "invalid UTF-8": "#cloud-config\n\xff\xfe", + "too large once escaped": strings.Repeat("\x01", MaxBytes), + "escaping right at the cap": strings.Repeat("\"", MaxEncodedBytes/2+1), + } { + t.Run(name, func(t *testing.T) { + secret := &corev1.Secret{Type: SecretType, Data: map[string][]byte{KeyUserData: []byte(value)}} + if _, err := Validate(secret); reason(t, err) != ReasonBootstrapInvalid { + t.Fatalf("err = %v", err) + } + }) + } + if _, err := Seal(Payload{UserData: strings.Repeat("\x01", MaxBytes)}, "op", "alloc", "default"); err == nil { + t.Fatal("Seal accepted data too large to deliver") + } +} diff --git a/internal/site/payload.go b/internal/site/payload.go new file mode 100644 index 00000000..a010feb2 --- /dev/null +++ b/internal/site/payload.go @@ -0,0 +1,163 @@ +package site + +import ( + "context" + "crypto/sha256" + "crypto/subtle" + "encoding/hex" + "encoding/json" + "errors" + + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + "go.datum.net/fleet/internal/custody" +) + +// Payload is an operation's sealed bootstrap data, delivered to the site +// beside its assignment and never inside it. Only that operation's worker +// reads it, and the site deletes it when the operation ends. +type Payload struct { + Ref string `json:"ref"` + Digest string `json:"digest"` + Salt []byte `json:"salt"` + Data []byte `json:"data"` +} + +// Payloads is where a site keeps delivered payloads. A Kubernetes site +// keeps each in its own Secret, which only that operation's worker may get. +type Payloads interface { + // Get returns the assignment's payload, or nil if none was delivered. + Get(ctx context.Context, assignment Assignment) (*Payload, error) + // Delete removes the assignment's payload. It is idempotent. + Delete(ctx context.Context, assignment Assignment) error + // Prune removes every payload of the Device delivered below its stored + // fence. The site calls it whenever it raises a fence, so a superseded + // operation whose worker never ran leaves no payload behind. + Prune(ctx context.Context, device string) error +} + +// Sealed returns the sealed reference in an assignment's admitted inputs, +// or nil. The reference is read from the inputs, whose digest the +// coordinator admitted, so a transport cannot substitute another payload. +func (a Assignment) Sealed() *ops.SealedInput { + var inputs struct { + Bootstrap *ops.SealedInput `json:"bootstrap"` + } + if json.Unmarshal(a.Inputs, &inputs) != nil { + return nil + } + return inputs.Bootstrap +} + +// Matches reports whether a payload is the one a reference names: the +// same name, and a digest recomputed from its salt and data. +func (p *Payload) Matches(reference *ops.SealedInput) bool { + if p == nil || reference == nil || p.Ref != reference.Ref || p.Digest != reference.Digest || len(p.Salt) != 32 { + return false + } + hash := sha256.New() + hash.Write(p.Salt) + hash.Write(p.Data) + return subtle.ConstantTimeCompare([]byte("sha256:"+hex.EncodeToString(hash.Sum(nil))), []byte(reference.Digest)) == 1 +} + +// Bootstrap returns the operation's verified bootstrap data, or nil if it +// has none. +func (w *Work) Bootstrap() *Payload { return w.payload } + +// ReasonBootstrapUnsupported is refused by a site that cannot receive or +// hand on bootstrap data. +const ReasonBootstrapUnsupported = custody.ReasonBootstrapUnsupported + +// payload reads and verifies the assignment's payload before anything is +// sent. A missing or altered payload refuses the operation. +func (r *Runner) payload(ctx context.Context, assignment Assignment) (*Payload, *custody.Refusal) { + reference := assignment.Sealed() + if reference == nil { + return nil, nil + } + if r.Payloads == nil { + return nil, &custody.Refusal{Reason: ReasonBootstrapUnsupported, Message: "this site cannot receive bootstrap data"} + } + payload, err := r.Payloads.Get(ctx, assignment) + if err != nil || payload == nil { + return nil, &custody.Refusal{Reason: ReasonInputMismatch, Message: "the bootstrap payload was not delivered"} + } + if !payload.Matches(reference) { + return nil, &custody.Refusal{Reason: ReasonInputMismatch, Message: "the bootstrap payload does not match the admitted digest"} + } + return payload, nil +} + +// dropPayload deletes the assignment's payload once nothing can need it. +func (r *Runner) dropPayload(ctx context.Context, assignment Assignment) { + if r.Payloads != nil && assignment.Sealed() != nil { + _ = r.Payloads.Delete(context.WithoutCancel(ctx), assignment) + } +} + +const payloadRecords = "payload" + +// StorePayloads keeps delivered payloads in the site store, one record per +// operation, for a site that receives them over its own API. +type StorePayloads struct{ Store *Store } + +func payloadKey(assignment Assignment) string { + sum := sha256.Sum256([]byte(assignment.Key())) + return hex.EncodeToString(sum[:])[:32] +} + +// storedPayload is a payload with the fence of the assignment it came +// with, so a newer fence can remove it. +type storedPayload struct { + Fence int64 `json:"fence"` + Payload Payload `json:"payload"` +} + +// Put stores a delivered payload. It refuses one that does not match the +// assignment's admitted reference, and one below the Device's stored fence. +// It deletes every payload of the Device below the stored fence first, so +// a superseded operation that never ran leaves none behind. +func (s StorePayloads) Put(assignment Assignment, payload Payload) error { + if !payload.Matches(assignment.Sealed()) { + return errors.New("site: the payload does not match the assignment") + } + if err := s.Prune(context.Background(), assignment.Device); err != nil { + return err + } + return s.Store.PutRecord(assignment.Device, assignment.Fence, payloadRecords, payloadKey(assignment), storedPayload{Fence: assignment.Fence, Payload: payload}) +} + +func (s StorePayloads) Get(_ context.Context, assignment Assignment) (*Payload, error) { + var stored storedPayload + found, err := s.Store.GetRecord(assignment.Device, payloadRecords, payloadKey(assignment), &stored) + if err != nil || !found || stored.Fence != assignment.Fence { + return nil, err + } + return &stored.Payload, nil +} + +// Prune deletes the Device's payloads below its stored fence. +func (s StorePayloads) Prune(_ context.Context, device string) error { + fence, _, err := s.Store.Peek(device) + if err != nil { + return err + } + records, err := s.Store.Records(payloadRecords) + if err != nil { + return err + } + for _, record := range records { + var stored storedPayload + if record.Device != device || json.Unmarshal(record.Data, &stored) == nil && stored.Fence >= fence { + continue + } + if err := s.Store.DeleteRecord(device, payloadRecords, record.Name); err != nil { + return err + } + } + return nil +} + +func (s StorePayloads) Delete(_ context.Context, assignment Assignment) error { + return s.Store.DeleteRecord(assignment.Device, payloadRecords, payloadKey(assignment)) +} diff --git a/internal/site/payload_test.go b/internal/site/payload_test.go new file mode 100644 index 00000000..16198e42 --- /dev/null +++ b/internal/site/payload_test.go @@ -0,0 +1,162 @@ +package site + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "testing" + + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" +) + +// sealedAssignment returns a payload and an assignment whose admitted inputs +// name it. +func (f *fixture) sealedAssignment(fence int64, uid string) (Assignment, Payload) { + salt := make([]byte, 32) + data := []byte(`{"userData":"#cloud-config\n"}`) + hash := sha256.New() + hash.Write(salt) + hash.Write(data) + payload := Payload{Ref: "sealed-" + uid, Digest: "sha256:" + hex.EncodeToString(hash.Sum(nil)), Salt: salt, Data: data} + assignment := f.assignment(fence, uid) + assignment.Inputs = json.RawMessage(fmt.Sprintf(`{"image":"debian-12","bootstrap":{"ref":%q,"digest":%q}}`, payload.Ref, payload.Digest)) + sum := sha256.Sum256(assignment.Inputs) + assignment.InputDigest = "sha256:" + hex.EncodeToString(sum[:]) + return assignment, payload +} + +// TestABootstrapPayloadIsCheckedThenDeleted: the worker sees the verified +// payload, and the site deletes it once the result is stored. +func TestABootstrapPayloadIsCheckedThenDeleted(t *testing.T) { + f := newFixture(t, testUUID) + payloads := StorePayloads{Store: f.runner.Store} + f.runner.Payloads = payloads + assignment, payload := f.sealedAssignment(1, "op-sealed") + if err := payloads.Put(assignment, payload); err != nil { + t.Fatal(err) + } + var seen *Payload + f.kind.check = func(work *Work) { seen = work.Bootstrap() } + result, err := f.runner.Run(context.Background(), assignment) + if err != nil || result.Phase != ops.PhaseSucceeded || seen == nil || seen.Digest != payload.Digest { + t.Fatalf("result = %+v, %v; worker saw %v", result, err, seen) + } + if got, err := payloads.Get(context.Background(), assignment); err != nil || got != nil { + t.Fatalf("the site kept the payload: %v, %v", got, err) + } +} + +// TestABadOrMissingPayloadSendsNothing refuses before any BMC write. +func TestABadOrMissingPayloadSendsNothing(t *testing.T) { + for name, deliver := range map[string]func(*fixture, Assignment, Payload) *Runner{ + "not delivered": func(f *fixture, _ Assignment, _ Payload) *Runner { + f.runner.Payloads = StorePayloads{Store: f.runner.Store} + return f.runner + }, + "altered after sealing": func(f *fixture, a Assignment, p Payload) *Runner { + f.runner.Payloads = StorePayloads{Store: f.runner.Store} + p.Data = []byte(`{"userData":"other"}`) + _ = f.runner.Store.PutRecord(a.Device, a.Fence, payloadRecords, payloadKey(a), storedPayload{Fence: a.Fence, Payload: p}) + return f.runner + }, + "a site that cannot receive bootstrap data": func(f *fixture, _ Assignment, _ Payload) *Runner { + f.runner.Payloads = nil + return f.runner + }, + } { + t.Run(name, func(t *testing.T) { + f := newFixture(t, testUUID) + assignment, payload := f.sealedAssignment(1, "op-bad") + result, err := deliver(f, assignment, payload).Run(context.Background(), assignment) + if err != nil || result.Phase != ops.PhaseFailed || f.kind.runs.Load() != 0 || f.bmc.count(notGet) != 0 { + t.Fatalf("result = %+v, %v; runs %d, writes %d", result, err, f.kind.runs.Load(), f.bmc.count(notGet)) + } + }) + } +} + +// TestPayloadsAreStoredOnlyForTheirAssignmentAndPruned: the site stores a +// payload only for the assignment whose inputs name it, and a newer fence +// removes a superseded operation's payload. +func TestPayloadsAreStoredOnlyForTheirAssignmentAndPruned(t *testing.T) { + f := newFixture(t, testUUID) + payloads := StorePayloads{Store: f.runner.Store} + first, payload := f.sealedAssignment(1, "op-first") + other, _ := f.sealedAssignment(1, "op-other") + if err := payloads.Put(other, payload); err == nil { + t.Fatal("a payload was stored for an assignment that does not name it") + } + if err := payloads.Put(first, payload); err != nil { + t.Fatal(err) + } + second, next := f.sealedAssignment(2, "op-second") + if err := f.runner.Store.Raise(second.Device, 2); err != nil { + t.Fatal(err) + } + if err := payloads.Put(second, next); err != nil { + t.Fatal(err) + } + if got, _ := payloads.Get(context.Background(), first); got != nil { + t.Fatal("a superseded operation's payload remains") + } + if got, _ := payloads.Get(context.Background(), second); got == nil { + t.Fatal("the current payload was pruned") + } +} + +// TestARecoveryFencePrunesAPayloadWhoseWorkerNeverRan: an install's payload +// is stored but its worker never starts; a recovery raises the fence, and +// the site deletes the payload at once. +func TestARecoveryFencePrunesAPayloadWhoseWorkerNeverRan(t *testing.T) { + f := newFixture(t, testUUID) + payloads := StorePayloads{Store: f.runner.Store} + f.runner.Payloads = payloads + install, payload := f.sealedAssignment(1, "op-never-ran") + if err := payloads.Put(install, payload); err != nil { + t.Fatal(err) + } + recovery := f.assignment(2, "op-recovery") + recovery.Operation.Kind = "DeviceRecovery" + if err := f.runner.Fence(context.Background(), recovery); err != nil { + t.Fatal(err) + } + if records, err := f.runner.Store.Records(payloadRecords); err != nil || len(records) != 0 { + t.Fatalf("payloads after the recovery fence = %d, %v", len(records), err) + } +} + +// TestAPayloadIsKeyedByItsOperationAndFence deletes one admission's payload +// and keeps another's that differs only in fence, operation name or kind, +// so an answered or superseded admission never drops a live one. +func TestAPayloadIsKeyedByItsOperationAndFence(t *testing.T) { + for name, other := range map[string]func(Assignment) Assignment{ + "a later fence": func(a Assignment) Assignment { a.Fence = 2; return a }, + "another name": func(a Assignment) Assignment { a.Operation.Name += "-other"; return a }, + "another kind": func(a Assignment) Assignment { a.Operation.Kind = "DeviceOtherInstallation"; return a }, + "a later fence, kind": func(a Assignment) Assignment { a.Fence, a.Operation.Kind = 2, "DeviceOtherInstallation"; return a }, + } { + t.Run(name, func(t *testing.T) { + f := newFixture(t, testUUID) + payloads := StorePayloads{Store: f.runner.Store} + gone, payload := f.sealedAssignment(1, "op-keyed") + kept := other(gone) + if err := payloads.Put(gone, payload); err != nil { + t.Fatal(err) + } + if err := f.runner.Store.Raise(kept.Device, kept.Fence); err != nil { + t.Fatal(err) + } + if err := payloads.Put(kept, payload); err != nil { + t.Fatal(err) + } + if err := payloads.Delete(context.Background(), gone); err != nil { + t.Fatal(err) + } + if got, err := payloads.Get(context.Background(), kept); err != nil || got == nil { + t.Fatalf("deleting another admission's payload dropped this one: %v, %v", got, err) + } + }) + } +} diff --git a/internal/site/redfishwork/kinds.go b/internal/site/redfishwork/kinds.go index 9bd9bb61..4d899490 100644 --- a/internal/site/redfishwork/kinds.go +++ b/internal/site/redfishwork/kinds.go @@ -150,7 +150,7 @@ func (k Installation) Check(ctx context.Context, work *site.Work) *custody.Refus return &custody.Refusal{Reason: ReasonInputs, Message: "the admitted inputs are not a DeviceInstallation spec"} } if spec.Bootstrap != nil { - return &custody.Refusal{Reason: custody.ReasonBootstrapUnsupported, Message: "bootstrap payloads need the sealed store, which is not implemented"} + return &custody.Refusal{Reason: custody.ReasonBootstrapUnsupported, Message: "this site cannot yet hand bootstrap data to the server"} } // Firmware settings can change after allocation: read the mode the // server boots in now. diff --git a/internal/site/runner.go b/internal/site/runner.go index 8b91f5dc..baab613a 100644 --- a/internal/site/runner.go +++ b/internal/site/runner.go @@ -17,9 +17,9 @@ import ( // Assignment is the handoff payload: one admitted operation, its fence and // deadline, the Device snapshot the coordinator captured at admission, and -// the exact inputs. Bootstrap, when it is supported, arrives as a sealed -// reference and digest, never as a payload. It replaces the request JSON of -// the old handoff in Increment C. +// the exact inputs. Bootstrap data is never in the assignment: the inputs +// carry its sealed reference and digest, and the payload arrives beside the +// assignment. type Assignment struct { // Device is "/" in the provider project. Device string `json:"device"` @@ -31,8 +31,7 @@ type Assignment struct { InputDigest string `json:"inputDigest"` // Inputs is the operation's spec exactly as admitted. Its SHA-256 is // InputDigest. - Inputs json.RawMessage `json:"inputs"` - Sealed *ops.SealedInput `json:"sealed,omitempty"` + Inputs json.RawMessage `json:"inputs"` } const maxInputs = 16 << 10 @@ -86,6 +85,7 @@ type Work struct { Connection any store *Store sent bool + payload *Payload } // Kind is the site worker contract for one operation kind. @@ -231,6 +231,9 @@ type Runner struct { // VM and simulator executors add their own in Increment C. Access Access Kinds map[string]Kind + // Payloads holds delivered bootstrap payloads. A site without it + // refuses any operation that carries bootstrap data. + Payloads Payloads // Poll is how often a worker checks for a newer fence and for the run // lock. It defaults to one second. Poll time.Duration @@ -278,6 +281,13 @@ func (r *Runner) acquire(ctx context.Context, assignment Assignment) (*runLock, if err := r.Store.Raise(assignment.Device, assignment.Fence); err != nil { return nil, err } + // Nothing below the new fence may run, so no payload below it is read + // again: a recovery or a newer operation removes them. + if r.Payloads != nil { + if err := r.Payloads.Prune(ctx, assignment.Device); err != nil { + return nil, err + } + } ctx, cancel := context.WithDeadline(ctx, assignment.Deadline) defer cancel() for { @@ -313,6 +323,17 @@ var ErrAlreadyRunning = errors.New("site: another worker runs this assignment") // ErrStaleFence, and stores nothing, for an assignment below the Device's // stored fence. func (r *Runner) Run(ctx context.Context, assignment Assignment) (custody.SiteResult, error) { + result, err := r.run(ctx, assignment) + // Once a result is stored, or a newer fence passed the assignment, no + // worker reads the payload again. A worker stopped from outside keeps it + // for its replacement. + if err == nil || errors.Is(err, ErrStaleFence) { + r.dropPayload(ctx, assignment) + } + return result, err +} + +func (r *Runner) run(ctx context.Context, assignment Assignment) (custody.SiteResult, error) { if err := assignment.Validate(); err != nil { return custody.SiteResult{}, err } @@ -502,6 +523,11 @@ func (r *Runner) prepare(ctx context.Context, work *Work) *custody.Refusal { if sum := sha256.Sum256(assignment.Inputs); "sha256:"+hex.EncodeToString(sum[:]) != assignment.InputDigest { return &custody.Refusal{Reason: ReasonInputMismatch, Message: "the inputs do not match the admitted digest"} } + payload, refusal := r.payload(ctx, assignment) + if refusal != nil { + return refusal + } + work.payload = payload connection, refusal := r.Access.Prepare(ctx, assignment) if refusal != nil { return refusal diff --git a/internal/site/simwork/kinds.go b/internal/site/simwork/kinds.go index 16d51c80..4a4c51d5 100644 --- a/internal/site/simwork/kinds.go +++ b/internal/site/simwork/kinds.go @@ -8,6 +8,8 @@ package simwork import ( "context" + "crypto/sha256" + "encoding/hex" "encoding/json" "slices" @@ -25,6 +27,10 @@ type Server struct { Image string `json:"image,omitempty"` // Booted is the digest the server last booted from disk. Booted string `json:"booted,omitempty"` + // Bootstrap is the salted digest of the bootstrap data written with the + // image, recomputed from what was written, as the guest would read it + // on first boot. The data itself is not kept. + Bootstrap string `json:"bootstrap,omitempty"` // Power is On or Off; empty is Off. Power string `json:"power,omitempty"` // LastReset is when the server last came out of a reset. @@ -106,9 +112,6 @@ func (Installation) Check(_ context.Context, work *site.Work) *custody.Refusal { if refusal != nil { return refusal } - if spec.Bootstrap != nil { - return &custody.Refusal{Reason: custody.ReasonBootstrapUnsupported, Message: "bootstrap payloads need the sealed store, which is not implemented"} - } if refusal := custody.OnlyNetworkBoot(spec.Delivery); refusal != nil { return refusal } @@ -123,6 +126,14 @@ func (Installation) Run(ctx context.Context, work *site.Work) (any, error) { if refusal != nil { return nil, refusal } + // The framework verified the payload against the admitted digest. + bootstrap := "" + if payload := work.Bootstrap(); payload != nil { + hash := sha256.New() + hash.Write(payload.Salt) + hash.Write(payload.Data) + bootstrap = "sha256:" + hex.EncodeToString(hash.Sum(nil)) + } var evidence ops.InstallationEvidence steps := []site.Step{ { @@ -132,12 +143,12 @@ func (Installation) Run(ctx context.Context, work *site.Work) (any, error) { if err != nil { return err } - server.Image, server.Booted = spec.Image.Digest, "" + server.Image, server.Booted, server.Bootstrap = spec.Image.Digest, "", bootstrap return write(work, server) }, Observe: func(context.Context, json.RawMessage) (bool, error) { server, err := read(work) - return server.Image == spec.Image.Digest, err + return server.Image == spec.Image.Digest && server.Bootstrap == bootstrap, err }, }, { @@ -170,6 +181,7 @@ func (Installation) Run(ctx context.Context, work *site.Work) (any, error) { if server.Booted != spec.Image.Digest { return nil, &custody.Refusal{Reason: site.ReasonStep, Message: "the simulated server did not boot the installed image"} } + evidence.Bootstrap = server.Bootstrap return evidence, nil } diff --git a/internal/site/siteapi/api_test.go b/internal/site/siteapi/api_test.go index f9807055..8c350f9a 100644 --- a/internal/site/siteapi/api_test.go +++ b/internal/site/siteapi/api_test.go @@ -96,7 +96,7 @@ func TestTheSiteAPI(t *testing.T) { } a := assignment(t) for range 3 { - if err := remote.Deliver(ctx, a); err != nil { + if err := remote.Deliver(ctx, a, nil); err != nil { t.Fatal(err) } } @@ -119,7 +119,7 @@ func TestTheSiteAPI(t *testing.T) { t.Fatalf("fence = %+v, %v, %v", report, reported, err) } // A redelivery after the result is stored returns it and runs nothing. - if err := remote.Deliver(ctx, a); err != nil { + if err := remote.Deliver(ctx, a, nil); err != nil { t.Fatal(err) } dispatcher.Wait() @@ -135,7 +135,7 @@ func TestTheSiteAPI(t *testing.T) { // An invalid assignment is refused before anything runs. bad := a bad.Fence = 0 - if err := remote.Deliver(ctx, bad); err == nil { + if err := remote.Deliver(ctx, bad, nil); err == nil { t.Fatal("an invalid assignment was accepted") } } diff --git a/internal/site/siteapi/client.go b/internal/site/siteapi/client.go index 50a52946..aad05346 100644 --- a/internal/site/siteapi/client.go +++ b/internal/site/siteapi/client.go @@ -72,8 +72,12 @@ func (c *Client) do(ctx context.Context, method, path string, body, into any) er return decoder.Decode(into) } -func (c *Client) Deliver(ctx context.Context, assignment site.Assignment) error { - return c.do(ctx, http.MethodPut, "/v1/assignments", assignment, nil) +// CarriesPayloads is true: the site API receives a payload beside its +// assignment. +func (c *Client) CarriesPayloads() bool { return true } + +func (c *Client) Deliver(ctx context.Context, assignment site.Assignment, payload *site.Payload) error { + return c.do(ctx, http.MethodPut, "/v1/assignments", Delivery{Assignment: assignment, Payload: payload}, nil) } func (c *Client) Fence(ctx context.Context, device string) (custody.SiteFence, bool, error) { diff --git a/internal/site/siteapi/payload_test.go b/internal/site/siteapi/payload_test.go new file mode 100644 index 00000000..a7ba265c --- /dev/null +++ b/internal/site/siteapi/payload_test.go @@ -0,0 +1,112 @@ +package siteapi + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "net/http/httptest" + "os" + "testing" + "time" + + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + "go.datum.net/fleet/internal/custody" + "go.datum.net/fleet/internal/site" +) + +// seenPayload records the payload the worker saw. +type seenPayload struct { + counting + seen chan *site.Payload +} + +func (k *seenPayload) Run(ctx context.Context, work *site.Work) (any, error) { + k.seen <- work.Bootstrap() + return k.counting.Run(ctx, work) +} + +func sealedAssignment(t *testing.T, uid string, fence int64) (site.Assignment, site.Payload) { + salt := make([]byte, 32) + data := []byte(`{"userData":"#cloud-config\n"}`) + hash := sha256.New() + hash.Write(salt) + hash.Write(data) + payload := site.Payload{Ref: "sealed-" + uid[len(uid)-4:], Digest: "sha256:" + hex.EncodeToString(hash.Sum(nil)), Salt: salt, Data: data} + a := assignment(t) + a.Operation.Name, a.Fence = a.Operation.Name+"-"+uid, fence + a.Inputs = json.RawMessage(fmt.Sprintf(`{"bootstrap":{"ref":%q,"digest":%q}}`, payload.Ref, payload.Digest)) + sum := sha256.Sum256(a.Inputs) + a.InputDigest = "sha256:" + hex.EncodeToString(sum[:]) + return a, payload +} + +// TestTheSiteAPICarriesAPayloadBesideItsAssignment stores a payload only +// when it matches the admitted inputs, hands it to the worker, and keeps no +// copy once the result is stored and answered. +func TestTheSiteAPICarriesAPayloadBesideItsAssignment(t *testing.T) { + dir := t.TempDir() + if err := os.Chmod(dir, 0o700); err != nil { + t.Fatal(err) + } + store, err := site.OpenStore(dir, nil) + if err != nil { + t.Fatal(err) + } + kind := &seenPayload{seen: make(chan *site.Payload, 4)} + results := site.NewResults(store) + runner := &site.Runner{Site: "site-example-a", Store: store, Results: results, Access: access{}, Kinds: map[string]site.Kind{"DeviceTestKind": kind}, Payloads: site.StorePayloads{Store: store}, Poll: 10 * time.Millisecond} + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + dispatcher := &Dispatcher{Runner: runner, Context: ctx} + server := httptest.NewServer(Handler(dispatcher, store, results, custody.NetworkBootOnly, func() (string, error) { return token, nil })) + defer server.Close() + remote, err := NewClient(server.URL, func() (string, error) { return token, nil }, server.Client()) + if err != nil { + t.Fatal(err) + } + a, payload := sealedAssignment(t, "00000000-0000-4000-8000-000000000501", 2) + + // A payload the inputs do not name, or none when they name one, is + // refused and nothing runs. + altered := payload + altered.Data = []byte(`{"userData":"other"}`) + for name, p := range map[string]*site.Payload{"altered": &altered, "missing": nil} { + if err := remote.Deliver(ctx, a, p); err == nil { + t.Fatalf("%s payload accepted", name) + } + } + plain := assignment(t) + if err := remote.Deliver(ctx, plain, &payload); err == nil { + t.Fatal("a payload for an assignment that names none was accepted") + } + dispatcher.Wait() + if kind.runs.Load() != 0 { + t.Fatalf("runs = %d", kind.runs.Load()) + } + + if err := remote.Deliver(ctx, a, &payload); err != nil { + t.Fatal(err) + } + if seen := <-kind.seen; seen == nil || seen.Digest != payload.Digest { + t.Fatalf("the worker saw %v", seen) + } + dispatcher.Wait() + held, err := remote.Results(ctx) + if err != nil || len(held) != 1 || held[0].Result.Phase != ops.PhaseSucceeded { + t.Fatalf("results = %+v, %v", held, err) + } + // A late redelivery can store the payload again after the worker + // deleted its copy, while the dispatcher still counts it running. + // Answering the result deletes it. + if err := (site.StorePayloads{Store: store}).Put(a, payload); err != nil { + t.Fatal(err) + } + if err := remote.Forget(ctx, held[0]); err != nil { + t.Fatal(err) + } + if records, err := store.Records("payload"); err != nil || len(records) != 0 { + t.Fatalf("payloads after the answer = %d, %v", len(records), err) + } +} diff --git a/internal/site/siteapi/server.go b/internal/site/siteapi/server.go index 2a7d0797..44023993 100644 --- a/internal/site/siteapi/server.go +++ b/internal/site/siteapi/server.go @@ -82,6 +82,12 @@ func (d *Dispatcher) Dispatch(assignment site.Assignment) error { // Wait returns once every worker stopped. func (d *Dispatcher) Wait() { d.wg.Wait() } +// Delivery is one assignment and, beside it, its bootstrap payload. +type Delivery struct { + Assignment site.Assignment `json:"assignment"` + Payload *site.Payload `json:"payload,omitempty"` +} + // FenceReport is the site's fence report for one Device. type FenceReport struct { Seen int64 `json:"seen"` @@ -98,11 +104,31 @@ func Handler(dispatcher *Dispatcher, store *site.Store, results *site.Results, m }{methods}) }) mux.HandleFunc("PUT /v1/assignments", func(w http.ResponseWriter, r *http.Request) { - var assignment site.Assignment - if err := decode(r, &assignment); err != nil { + var delivery Delivery + if err := decode(r, &delivery); err != nil { http.Error(w, "the assignment could not be decoded", http.StatusBadRequest) return } + assignment := delivery.Assignment + if err := assignment.Validate(); err != nil { + http.Error(w, "the assignment is invalid", http.StatusBadRequest) + return + } + // The payload is stored before the worker starts, and only if it is + // the one the admitted inputs name. + if (delivery.Payload != nil) != (assignment.Sealed() != nil) { + http.Error(w, "the payload does not match the assignment", http.StatusBadRequest) + return + } + if delivery.Payload != nil { + if err := (site.StorePayloads{Store: store}).Put(assignment, *delivery.Payload); errors.Is(err, site.ErrStaleFence) { + w.WriteHeader(http.StatusAccepted) + return + } else if err != nil { + http.Error(w, "the payload was refused", http.StatusBadRequest) + return + } + } if err := dispatcher.Dispatch(assignment); err != nil { http.Error(w, "the assignment is invalid", http.StatusBadRequest) return @@ -138,6 +164,12 @@ func Handler(dispatcher *Dispatcher, store *site.Store, results *site.Results, m http.Error(w, "the result could not be deleted", http.StatusInternalServerError) return } + // An answered operation never runs again, so a payload a late + // redelivery stored is not needed either. + if err := (site.StorePayloads{Store: store}).Delete(r.Context(), site.Assignment{Device: stored.Device, Operation: stored.Result.Operation, Fence: stored.Result.Fence}); err != nil { + http.Error(w, "the payload could not be deleted", http.StatusInternalServerError) + return + } w.WriteHeader(http.StatusNoContent) }) mux.HandleFunc("GET /readyz", func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) }) @@ -160,7 +192,9 @@ func bearer(token func() (string, error), next http.Handler) http.Handler { }) } -const maxBody = 64 << 10 +// maxBody bounds a request: an assignment's 16 KiB of inputs and a 64 KiB +// bootstrap payload, both base64 or JSON encoded. +const maxBody = 256 << 10 func decode(r *http.Request, into any) error { decoder := json.NewDecoder(io.LimitReader(r.Body, maxBody)) diff --git a/internal/site/store.go b/internal/site/store.go index 83b448d5..387ed2c7 100644 --- a/internal/site/store.go +++ b/internal/site/store.go @@ -365,7 +365,10 @@ func (s *Store) DeleteRecord(device, collection, name string) error { if os.IsNotExist(err) { return false, nil } - return false, err + if err != nil { + return false, err + } + return false, syncPath(filepath.Join(s.deviceDir(device), collection)) }) } @@ -384,6 +387,18 @@ func (s *Store) GetRecord(device, collection, name string, into any) (bool, erro return true, json.Unmarshal(data, into) } +func syncPath(dir string) error { + file, err := os.Open(dir) + if os.IsNotExist(err) { + return nil + } + if err != nil { + return err + } + defer file.Close() + return file.Sync() +} + func validRecordName(name string) bool { if name == "" || len(name) > 128 { return false diff --git a/internal/site/vmwork/kinds.go b/internal/site/vmwork/kinds.go index 645cc6cc..b44cc160 100644 --- a/internal/site/vmwork/kinds.go +++ b/internal/site/vmwork/kinds.go @@ -157,7 +157,7 @@ func (k Installation) Check(_ context.Context, work *site.Work) *custody.Refusal return refusal } if spec.Bootstrap != nil { - return &custody.Refusal{Reason: custody.ReasonBootstrapUnsupported, Message: "bootstrap payloads need the sealed store, which is not implemented"} + return &custody.Refusal{Reason: custody.ReasonBootstrapUnsupported, Message: "this site cannot yet hand bootstrap data to the server"} } if refusal := custody.OnlyNetworkBoot(spec.Delivery); refusal != nil { return refusal diff --git a/internal/standalone/runner.go b/internal/standalone/runner.go index 50b95763..dd37b92a 100644 --- a/internal/standalone/runner.go +++ b/internal/standalone/runner.go @@ -27,6 +27,7 @@ import ( "go.datum.net/fleet/internal/custody" "go.datum.net/fleet/internal/manager" "go.datum.net/fleet/internal/tenancy" + "go.datum.net/fleet/internal/sealed" ) const ( @@ -200,8 +201,17 @@ func (r Runner) install(ctx context.Context, installationName string) error { return err } image, err := r.catalog().Resolve(ctx, r.consumerOf(first), &installation) + var bootstrap *sealed.Payload + if ref := installation.Spec.BootstrapConfigRef; err == nil && ref != nil { + // The fixture reads the Secret with its own identity, standing in + // for the Installation creator's authority. + var payload sealed.Payload + if payload, err = sealed.Read(ctx, r.Client, installation.Namespace, ref.Name); err == nil { + bootstrap = &payload + } + } if err == nil { - operation, err = r.Allocator.Install(ctx, current, allocation.Installation{Installation: &installation, Current: previous, Image: image}) + operation, err = r.Allocator.Install(ctx, current, allocation.Installation{Installation: &installation, Current: previous, Image: image, Bootstrap: bootstrap}) } if refusal := (*catalog.Refusal)(nil); errors.As(err, &refusal) { apiMeta.SetStatusCondition(&installation.Status.Conditions, condition("Accepted", metav1.ConditionFalse, installation.Generation, refusal.Reason, refusal.Message))