From 39bbe7615324a8c85b5556ad845316f022e37358 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 25 Nov 2026 10:31:52 -0600 Subject: [PATCH 1/2] feat(custody): Deliver bootstrap data through a sealed store Installs refused bootstrap data because nothing could hold it. The Fleet provider now reads a customer's bootstrap Secret, seals it with a random salt into an immutable SealedPayload in the provider project, and creates a DeviceInstallation that carries only the payload's name and salted digest. A retry after admission returns the operation and seals nothing new. The coordinator checks the payload at admission and fails the operation with BootstrapUnavailable, sending nothing, if it is missing or altered. Each pass it deletes payloads whose operation ended, that their operation does not name, or that wait for an operation under an allocation that is no longer Active. The courier delivers the payload beside the assignment, the site takes the reference from the admitted inputs, checks the payload again before anything is sent, and deletes it when the operation ends or a newer fence passes it. Install evidence must name the digest of the data handed to the server. Only the coordinator role reads the sealed store, and a test walks every Milo role the repository ships to prove it. The simulator site carries bootstrap data end to end. Federation and the local VM and Redfish sites refuse it until the lab increment. Co-Authored-By: Claude Opus 5.5 --- cmd/fleet-simulator/main.go | 2 +- .../device-operations/crds/kustomization.yaml | 2 +- .../crds/sealedpayloads.yaml | 41 ++++ .../protected-resources/kustomization.yaml | 1 + .../protected-resources/sealedpayload.yaml | 15 ++ .../device-operations/roles/coordinator.yaml | 7 + .../roles/installation-requester.yaml | 2 + config/standalone/fixtures.yaml | 14 ++ config/standalone/rbac.yaml | 14 ++ docs/development/README.md | 16 +- docs/development/device-custody.md | 21 +- docs/development/machine-images.md | 49 +++- docs/operations/site-execution.md | 5 +- hack/multiplane/milo.py | 7 +- hack/standalone-smoke.sh | 29 ++- internal/allocation/allocator.go | 80 ++++++- internal/allocation/bootstrap_test.go | 130 +++++++++++ internal/allocation/harness_test.go | 2 +- internal/allocation/install_test.go | 113 ++++++++++ .../api/operations/v1alpha1/config_test.go | 88 +++++++- internal/api/operations/v1alpha1/types.go | 40 +++- internal/coordination/transport.go | 9 +- internal/coordination/transport_test.go | 6 +- internal/custody/admission_test.go | 52 ++++- internal/custody/bootstrap_evidence_test.go | 37 +++ internal/custody/extension_test.go | 2 +- internal/custody/kinds.go | 35 ++- internal/delivery/delivery.go | 36 ++- internal/sealed/sealed.go | 213 ++++++++++++++++++ internal/sealed/sealed_test.go | 187 +++++++++++++++ internal/site/payload.go | 159 +++++++++++++ internal/site/payload_test.go | 107 +++++++++ internal/site/redfishwork/kinds.go | 2 +- internal/site/runner.go | 29 ++- internal/site/simwork/kinds.go | 22 +- internal/site/siteapi/api_test.go | 6 +- internal/site/siteapi/client.go | 4 +- internal/site/siteapi/server.go | 34 ++- internal/site/store.go | 24 ++ internal/site/vmwork/kinds.go | 2 +- internal/standalone/runner.go | 12 +- 41 files changed, 1566 insertions(+), 90 deletions(-) create mode 100644 config/components/device-operations/crds/sealedpayloads.yaml create mode 100644 config/components/device-operations/protected-resources/sealedpayload.yaml create mode 100644 internal/allocation/bootstrap_test.go create mode 100644 internal/allocation/install_test.go create mode 100644 internal/custody/bootstrap_evidence_test.go create mode 100644 internal/sealed/sealed.go create mode 100644 internal/sealed/sealed_test.go create mode 100644 internal/site/payload.go create mode 100644 internal/site/payload_test.go diff --git a/cmd/fleet-simulator/main.go b/cmd/fleet-simulator/main.go index c9baa2d0..33af3df2 100644 --- a/cmd/fleet-simulator/main.go +++ b/cmd/fleet-simulator/main.go @@ -73,7 +73,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{}}} + Kinds: map[string]site.Kind{"DeviceInstallation": simwork.Installation{}, "DeviceWipe": simwork.Wipe{}}, Payloads: site.StorePayloads{Store: store}} dispatcher := &siteapi.Dispatcher{Runner: runner, Context: ctx, Logger: logger} server := newServer(address, siteapi.Handler(dispatcher, store, results, func() (string, error) { return readToken(tokenPath) }), logger) if discover { 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..92bd293c --- /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 64 KiB of bootstrap data and its encoding, base64. + data: {type: string, format: byte, minLength: 1, maxLength: 100000} diff --git a/config/components/device-operations/protected-resources/kustomization.yaml b/config/components/device-operations/protected-resources/kustomization.yaml index 7b5e6674..b98f74c4 100644 --- a/config/components/device-operations/protected-resources/kustomization.yaml +++ b/config/components/device-operations/protected-resources/kustomization.yaml @@ -5,3 +5,4 @@ resources: - deviceinstallation.yaml - devicewipe.yaml - devicerecovery.yaml + - sealedpayload.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 facbdbdd..871de7d2 100644 --- a/config/components/device-operations/roles/coordinator.yaml +++ b/config/components/device-operations/roles/coordinator.yaml @@ -41,3 +41,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 1131652a..ebf85a09 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 1163e077..7cb6e0cb 100644 --- a/config/standalone/fixtures.yaml +++ b/config/standalone/fixtures.yaml @@ -40,6 +40,7 @@ spec: version: "12" architecture: amd64 firmwareModes: [UEFI] + bootstrapFormats: [NoCloud] digest: "sha256:9f4ad8d8b8a6f6fc64d2cf2c7e70b9184b74f089adf8c36d84f4fcb99892f3cb" availability: Available --- @@ -80,6 +81,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 edf6eb46..030b9505 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] verbs: [get] @@ -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] @@ -162,6 +172,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 70afc8ff..021a5dfd 100644 --- a/docs/development/README.md +++ b/docs/development/README.md @@ -42,7 +42,8 @@ smoke verifies it. The end-to-end failure scenarios (Increment D) are proposed. **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 @@ -530,7 +531,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 @@ -785,13 +786,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 9e7cd13d..43d1cb1b 100644 --- a/docs/development/device-custody.md +++ b/docs/development/device-custody.md @@ -236,7 +236,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, Network and Address close at once. @@ -374,7 +374,8 @@ event. - The capacity projector stays unwired (O1), so the synthetic fixtures still write `Prepared`, `Healthy` and `Available`. -- 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. ## Implementation decisions @@ -620,10 +621,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 @@ -773,8 +774,8 @@ These need a decision before the increment that depends on them. - **O1: the interim source of `Prepared` and `Healthy`.** Still open after C. The projector stays unwired, so the synthetic fixtures write `Prepared`, `Healthy` and `Available` themselves. -- **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). - **A second person for `DeviceRecovery`.** Not required yet. A person accepted this for now, and it stays open for a later decision. - **Synthetic staging needs its records imported again, and two new @@ -884,7 +885,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` | @@ -919,7 +920,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 d7577699..cb5af846 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. Federation and the local VM and Redfish sites refuse bootstrap data. | | 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 @@ -68,6 +68,45 @@ 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, at most 64 KiB. Admission refuses + any other type or key 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, 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` and nothing + is sent. +- **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 a newer fence passes the assignment, and when a newer assignment for + the Device arrives. 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 @@ -78,3 +117,11 @@ 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. The coordinator does not deliver such an + assignment over federation, and those sites refuse one with + `BootstrapUnsupported`. +- 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 134e3035..9c6b9e56 100644 --- a/docs/operations/site-execution.md +++ b/docs/operations/site-execution.md @@ -322,8 +322,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 the +coordinator does not deliver an assignment 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 5858a60c..c3145090 100755 --- a/hack/multiplane/milo.py +++ b/hack/multiplane/milo.py @@ -79,7 +79,7 @@ def wait(fn,seconds,what): 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 @@ -89,12 +89,13 @@ def wait(fn,seconds,what): # The Metal provider records allocations and creates installations; it # reads custody and Devices only to skip taken capacity. 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':['deviceinstallations'],'verbs':['get','list','watch','create']},{'apiGroups':['fleet.datumapis.com'],'resources':['devices','devicecustodies'],'verbs':['get','list','watch']}] + {'apiGroups':['fleet.datumapis.com'],'resources':['deviceinstallations'],'verbs':['get','list','watch','create']},{'apiGroups':['fleet.datumapis.com'],'resources':['sealedpayloads'],'verbs':['create']},{'apiGroups':['fleet.datumapis.com'],'resources':['devices','devicecustodies'],'verbs':['get','list','watch']}] components={ 'coordinator':[{'apiGroups':['fleet.datumapis.com'],'resources':['devices'],'verbs':['get','list','watch']},{'apiGroups':['fleet.datumapis.com'],'resources':['devicecustodies'],'verbs':['get','list','watch','create','update','delete']}, {'apiGroups':['fleet.datumapis.com'],'resources':['deviceinstallations','devicewipes','devicerecoveries'],'verbs':['get','list','watch','delete']}, {'apiGroups':['fleet.datumapis.com'],'resources':['deviceinstallations/status','devicewipes/status','devicerecoveries/status'],'verbs':['get','update']}, - {'apiGroups':['metal.datumapis.com'],'resources':['machineallocations'],'verbs':['get','list','watch']}], + {'apiGroups':['metal.datumapis.com'],'resources':['machineallocations'],'verbs':['get','list','watch']}, + {'apiGroups':['fleet.datumapis.com'],'resources':['sealedpayloads'],'verbs':['get','list','watch','delete']}], 'release':[{'apiGroups':['fleet.datumapis.com'],'resources':['devicewipes'],'verbs':['get','create']}], 'discovery':[{'apiGroups':['fleet.datumapis.com'],'resources':['devices'],'verbs':['get','list']},{'apiGroups':['fleet.datumapis.com'],'resources':['devices/status'],'verbs':['get','update']}]} for who,component in components.items(): diff --git a/hack/standalone-smoke.sh b/hack/standalone-smoke.sh index dfdd281b..4abbf80f 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 devicerecoveries; do +for crd in devices devicecustodies deviceinstallations devicewipes devicerecoveries 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 @@ -132,6 +132,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 @@ -143,7 +160,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 devicerecoveries machineallocations; do + for resource in devicecustodies deviceinstallations devicewipes devicerecoveries 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 @@ -163,6 +180,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 e3864df3..67bffad8 100644 --- a/internal/allocation/allocator.go +++ b/internal/allocation/allocator.go @@ -32,6 +32,7 @@ import ( fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" "go.datum.net/fleet/internal/catalog" "go.datum.net/fleet/internal/custody" + "go.datum.net/fleet/internal/sealed" "go.datum.net/fleet/internal/tenancy" ) @@ -47,8 +48,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") ) @@ -348,6 +349,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 @@ -364,8 +369,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)) { @@ -378,10 +383,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)}, @@ -389,7 +395,69 @@ func (a *Allocator) Install(ctx context.Context, allocation *fleetv1.MachineAllo TargetDisks: slices.Clone(allocation.Spec.TargetDisks), }, } - return operation, a.createOnce(ctx, a.Provider, operation, &ops.DeviceInstallation{}) + // Admission is final once the operation exists: a retry returns it and + // never reads or seals the bootstrap data again, but only if it is this + // request's operation. + existing := &ops.DeviceInstallation{} + if err := a.Provider.Get(ctx, client.ObjectKeyFromObject(operation), existing); err == nil { + return sameInstallation(operation, request.Bootstrap != nil, existing) + } else if !apierrors.IsNotFound(err) { + return nil, err + } + 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 } func (a *Allocator) envelope(allocation *fleetv1.MachineAllocation, creator ops.Creator) ops.OperationEnvelope { 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 9825b7a4..5040dfe4 100644 --- a/internal/allocation/harness_test.go +++ b/internal/allocation/harness_test.go @@ -104,7 +104,7 @@ func startEnv(t *testing.T) *env { 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{}}, Poll: 20 * time.Millisecond} + Kinds: map[string]site.Kind{"DeviceInstallation": simwork.Installation{}, "DeviceWipe": simwork.Wipe{}}, Payloads: site.StorePayloads{Store: e.store}, Poll: 20 * time.Millisecond} dispatcher := &siteapi.Dispatcher{Runner: runner, Context: ctx} server := httptest.NewServer(siteapi.Handler(dispatcher, e.store, runner.Results, func() (string, error) { return siteToken, nil })) t.Cleanup(func() { cancel(); server.Close(); dispatcher.Wait() }) diff --git a/internal/allocation/install_test.go b/internal/allocation/install_test.go new file mode 100644 index 00000000..39ab220c --- /dev/null +++ b/internal/allocation/install_test.go @@ -0,0 +1,113 @@ +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" + + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/sealed" +) + +// 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 := 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: fake.NewClientBuilder().WithScheme(scheme).Build(), Namespace: "default"} + 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 := fake.NewClientBuilder().WithScheme(scheme).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"} + 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 815171f7..bd80034b 100644 --- a/internal/api/operations/v1alpha1/config_test.go +++ b/internal/api/operations/v1alpha1/config_test.go @@ -60,7 +60,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 } @@ -69,8 +69,8 @@ func loadCRDs(t *testing.T) map[string]*extensionsv1.CustomResourceDefinition { func TestCRDContract(t *testing.T) { crds := loadCRDs(t) - if len(crds) != 4 || crds["DeviceCustody"] == nil { - t.Fatalf("got %d CRDs, want DeviceCustody and three operation kinds", len(crds)) + if len(crds) != 5 || crds["DeviceCustody"] == nil || crds["SealedPayload"] == nil { + t.Fatalf("got %d CRDs, want DeviceCustody, three operation kinds and SealedPayload", len(crds)) } for kind, crd := range crds { version := crd.Spec.Versions[0] @@ -81,7 +81,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") @@ -190,10 +196,10 @@ func TestRolesKeepOneWriterAndKeepStaffFromCustomerSecrets(t *testing.T) { want := map[string][]string{ "fleet.datumapis.com-device-operations-viewer": slices.Concat(p(group+"devicecustodies", read...), p(group+"deviceinstallations", read...), p(group+"devicewipes", read...), p(group+"devicerecoveries", read...)), "fleet.datumapis.com-device-recovery-operator": slices.Concat(p(group+"devicerecoveries", "create"), p("metal.datumapis.com/machineallocations", read...)), - "fleet.datumapis.com-device-installation-requester": slices.Concat(p(group+"deviceinstallations", "create", "get", "list", "watch"), p(group+"devicecustodies", read...)), + "fleet.datumapis.com-device-installation-requester": slices.Concat(p(group+"deviceinstallations", "create", "get", "list", "watch"), p(group+"devicecustodies", read...), p(group+"sealedpayloads", "create")), "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+"devicecustodies", "get", "list", "watch", "create", "update", "delete"), p(group+"devices", read...), p("metal.datumapis.com/machineallocations", read...), p("metal.datumapis.com/machinecapacities", read...), p(group+"sealedpayloads", "get", "list", "watch", "delete")) for _, plural := range []string{"deviceinstallations", "devicewipes", "devicerecoveries"} { coordinator = slices.Concat(coordinator, p(group+plural, "get", "list", "watch", "delete", "updateStatus"), []string{group + plural + "/status.update"}) } @@ -227,8 +233,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) } } @@ -306,3 +317,64 @@ func TestPhases(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) + } +} diff --git a/internal/api/operations/v1alpha1/types.go b/internal/api/operations/v1alpha1/types.go index 80523ecf..1466fbea 100644 --- a/internal/api/operations/v1alpha1/types.go +++ b/internal/api/operations/v1alpha1/types.go @@ -314,15 +314,49 @@ type ImageInput 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. @@ -462,7 +496,7 @@ type DeviceRecoveryList struct { } func addKnown(s *runtime.Scheme) error { - s.AddKnownTypes(GroupVersion, &DeviceCustody{}, &DeviceCustodyList{}, &DeviceInstallation{}, &DeviceInstallationList{}, &DeviceWipe{}, &DeviceWipeList{}, &DeviceRecovery{}, &DeviceRecoveryList{}) + s.AddKnownTypes(GroupVersion, &DeviceCustody{}, &DeviceCustodyList{}, &DeviceInstallation{}, &DeviceInstallationList{}, &DeviceWipe{}, &DeviceWipeList{}, &DeviceRecovery{}, &DeviceRecoveryList{}, &SealedPayload{}, &SealedPayloadList{}) metav1.AddToGroupVersion(s, GroupVersion) return nil } @@ -477,6 +511,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 07f9eb5c..0e4a6fd6 100644 --- a/internal/coordination/transport.go +++ b/internal/coordination/transport.go @@ -184,7 +184,14 @@ 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. +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 056b35f7..faa62982 100644 --- a/internal/coordination/transport_test.go +++ b/internal/coordination/transport_test.go @@ -150,16 +150,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() diff --git a/internal/custody/admission_test.go b/internal/custody/admission_test.go index 827721dc..2e998822 100644 --- a/internal/custody/admission_test.go +++ b/internal/custody/admission_test.go @@ -8,6 +8,7 @@ import ( inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + "go.datum.net/fleet/internal/sealed" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/controller-runtime/pkg/client" ) @@ -245,27 +246,56 @@ 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"}, + }} + } + 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"}, - }} - 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"}, - }} + // 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, "") }) t.Run("a staff operation not admitted within five minutes expires", 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/extension_test.go b/internal/custody/extension_test.go index bae82818..5fb878ec 100644 --- a/internal/custody/extension_test.go +++ b/internal/custody/extension_test.go @@ -250,7 +250,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/kinds.go b/internal/custody/kinds.go index 2d48a0a3..cbd487ec 100644 --- a/internal/custody/kinds.go +++ b/internal/custody/kinds.go @@ -10,6 +10,7 @@ import ( "time" ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + "go.datum.net/fleet/internal/sealed" "sigs.k8s.io/controller-runtime/pkg/client" ) @@ -28,6 +29,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" @@ -103,11 +109,19 @@ func DeviceInstallationKind() Kind { Deadline: InstallationDeadline, Effectful: true, BootInterface: func(operation ops.Operation) string { return operation.(*ops.DeviceInstallation).Spec.BootInterface }, - Check: func(_ context.Context, admission *Admission) *Refusal { + 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 { + payload := &ops.SealedPayload{} + if err := admission.Reader.Get(ctx, client.ObjectKey{Namespace: installation.Namespace, Name: reference.Ref}, payload); err != nil { + 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") + } } for _, iface := range admission.Device.Spec.Interfaces { if iface.Name == installation.Spec.BootInterface && iface.MACAddress != "" { @@ -117,8 +131,17 @@ func DeviceInstallationKind() Kind { return refuse(ReasonBootInterfaceUnknown, "the Device records no interface %q with a MAC address", installation.Spec.BootInterface) }, Settles: []SettleRule{{Held: "DeviceInstallation"}}, - Reasons: append([]Reason{{Name: ReasonBootstrapUnsupported, RaisedBy: RaisedByBoth}, {Name: ReasonBootInterfaceUnknown, RaisedBy: RaisedByCoordinator}, {Name: ReasonImageIncompatible, RaisedBy: RaisedByWorker}}, workerReasons...), - Evidence: StrictEvidence(evidenceLimit, func(_ ops.Operation, evidence *ops.InstallationEvidence) error { + Reasons: append([]Reason{{Name: ReasonBootstrapUnavailable, RaisedBy: RaisedByCoordinator}, {Name: ReasonBootstrapUnsupported, RaisedBy: RaisedByWorker}, {Name: ReasonBootInterfaceUnknown, RaisedBy: RaisedByCoordinator}, {Name: ReasonImageIncompatible, RaisedBy: RaisedByWorker}}, workerReasons...), + 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/delivery/delivery.go b/internal/delivery/delivery.go index 7b72dfa8..d1e628a0 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) @@ -138,19 +140,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 { @@ -236,6 +261,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 time.Since(l.lastSweep) > time.Hour { if _, err := l.Coordinator.SweepRetention(ctx); err != nil { failed = errors.Join(failed, err) diff --git a/internal/sealed/sealed.go b/internal/sealed/sealed.go new file mode 100644 index 00000000..3c7227bb --- /dev/null +++ b/internal/sealed/sealed.go @@ -0,0 +1,213 @@ +// 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" + + 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. +const MaxBytes = 64 << 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") + } + 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") + } + 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 + } + 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..56bad9f9 --- /dev/null +++ b/internal/sealed/sealed_test.go @@ -0,0 +1,187 @@ +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) + } +} diff --git a/internal/site/payload.go b/internal/site/payload.go new file mode 100644 index 00000000..f1e6ca63 --- /dev/null +++ b/internal/site/payload.go @@ -0,0 +1,159 @@ +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 +} + +// 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(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(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..384435d1 --- /dev/null +++ b/internal/site/payload_test.go @@ -0,0 +1,107 @@ +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") + } +} diff --git a/internal/site/redfishwork/kinds.go b/internal/site/redfishwork/kinds.go index 8769e8ff..979f65a0 100644 --- a/internal/site/redfishwork/kinds.go +++ b/internal/site/redfishwork/kinds.go @@ -122,7 +122,7 @@ func (k Installation) Check(_ context.Context, work *site.Work) *custody.Refusal 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 d8eba1c3..fa8fdcde 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 @@ -310,6 +313,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 } @@ -471,6 +485,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 545f12be..c6654b4c 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"` } const serverRecords = "simulator" @@ -88,9 +94,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"} - } return checkDisks(work, spec.TargetDisks) } @@ -99,6 +102,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{ { @@ -108,12 +119,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 }, }, { @@ -146,6 +157,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 090a18ec..3dfcf689 100644 --- a/internal/site/siteapi/api_test.go +++ b/internal/site/siteapi/api_test.go @@ -88,7 +88,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) } } @@ -111,7 +111,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() @@ -127,7 +127,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 f9e3f53f..0efef5ce 100644 --- a/internal/site/siteapi/client.go +++ b/internal/site/siteapi/client.go @@ -72,8 +72,8 @@ 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) +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/server.go b/internal/site/siteapi/server.go index 39393a30..e9b05286 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"` @@ -92,11 +98,31 @@ type FenceReport struct { func Handler(dispatcher *Dispatcher, store *site.Store, results *site.Results, token func() (string, error)) http.Handler { mux := http.NewServeMux() 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 @@ -154,7 +180,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 9cad0c07..0de27a3c 100644 --- a/internal/site/store.go +++ b/internal/site/store.go @@ -364,6 +364,30 @@ func (s *Store) GetRecord(device, collection, name string, into any) (bool, erro return true, json.Unmarshal(data, into) } +// DeleteRecord removes a kind's record. It is idempotent. +func (s *Store) DeleteRecord(device, collection, name string) error { + if !validRecordName(collection) || !validRecordName(name) { + return errors.New("site: invalid record name") + } + err := os.Remove(filepath.Join(s.deviceDir(device), collection, name+".json")) + if err != nil && !os.IsNotExist(err) { + return err + } + return syncPath(filepath.Join(s.deviceDir(device), collection)) +} + +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 e7f670c3..69c318f2 100644 --- a/internal/site/vmwork/kinds.go +++ b/internal/site/vmwork/kinds.go @@ -147,7 +147,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 spec.Image.Name+"@"+spec.Image.Digest != k.Image { return &custody.Refusal{Reason: custody.ReasonTargetUnsupported, Message: "the site installs only its verified local image"} diff --git a/internal/standalone/runner.go b/internal/standalone/runner.go index 241f7bf3..75e356bd 100644 --- a/internal/standalone/runner.go +++ b/internal/standalone/runner.go @@ -25,6 +25,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 ( @@ -179,8 +180,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)) From 82aaca1ecbf7681a428fade8f8f84832e1140d52 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 25 Nov 2026 10:47:01 -0600 Subject: [PATCH 2/2] fix(custody): Leave no bootstrap copy behind and refuse what cannot arrive A payload whose worker never ran stayed on the site disk after a recovery raised the fence. The site now removes every payload below a Device's fence whenever it raises one, and forgetting an answered result removes its payload. Bootstrap data must be UTF-8 and fit in 96 KiB once encoded, so a site always receives exactly what the customer stored. Admission refuses bootstrap data for a Device whose sites cannot receive payloads, so a federated install fails at once instead of holding the server until its deadline. Add tests for the courier, the site API payload path, the hub refusal, recovery pruning, and the new limits, and correct the status page. Co-Authored-By: Claude Opus 5.5 --- .../crds/sealedpayloads.yaml | 4 +- docs/development/machine-images.md | 30 +++-- docs/operations/site-execution.md | 4 +- internal/coordination/transport.go | 2 + internal/coordination/transport_test.go | 21 ++++ internal/custody/admission_test.go | 19 +++ internal/custody/coordinator.go | 10 +- internal/custody/harness_test.go | 11 +- internal/custody/kinds.go | 7 +- internal/custody/registry.go | 5 +- internal/delivery/delivery.go | 23 +++- internal/delivery/delivery_test.go | 91 ++++++++++++++ internal/sealed/sealed.go | 21 +++- internal/sealed/sealed_test.go | 18 +++ internal/site/payload.go | 8 +- internal/site/payload_test.go | 55 +++++++++ internal/site/runner.go | 7 ++ internal/site/siteapi/client.go | 4 + internal/site/siteapi/payload_test.go | 111 ++++++++++++++++++ internal/site/siteapi/server.go | 6 + 20 files changed, 431 insertions(+), 26 deletions(-) create mode 100644 internal/site/siteapi/payload_test.go diff --git a/config/components/device-operations/crds/sealedpayloads.yaml b/config/components/device-operations/crds/sealedpayloads.yaml index 92bd293c..b5cff7d3 100644 --- a/config/components/device-operations/crds/sealedpayloads.yaml +++ b/config/components/device-operations/crds/sealedpayloads.yaml @@ -37,5 +37,5 @@ spec: digest: {type: string, pattern: '^sha256:[0-9a-f]{64}$'} # 32 random bytes, base64. salt: {type: string, format: byte, minLength: 44, maxLength: 44} - # At most 64 KiB of bootstrap data and its encoding, base64. - data: {type: string, format: byte, minLength: 1, maxLength: 100000} + # At most 96 KiB of encoded bootstrap data, base64. + data: {type: string, format: byte, minLength: 1, maxLength: 131072} diff --git a/docs/development/machine-images.md b/docs/development/machine-images.md index cb5af846..41853f80 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`, 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. Federation and the local VM and Redfish sites refuse bootstrap data. | +| 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 @@ -71,8 +71,9 @@ proposal's API names are provisional. Each piece below is marked ## What increment 2 adds - **Bootstrap Secret.** A Secret of type `metal.datumapis.com/bootstrap` with - `userData`, `sshAuthorizedKeys`, or both, at most 64 KiB. Admission refuses - any other type or key with `BootstrapInvalid`, and a missing or unreadable + `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, @@ -83,10 +84,13 @@ proposal's API names are provisional. Each piece below is marked 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, 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` and nothing - is sent. +- **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`. @@ -95,9 +99,10 @@ proposal's API names are provisional. Each piece below is marked 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 a newer fence passes the assignment, and when a newer assignment for - the Device arrives. A worker stopped from outside keeps it for its - replacement. + 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 @@ -118,9 +123,8 @@ proposal's API names are provisional. Each piece below is marked 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. The coordinator does not deliver such an - assignment over federation, and those sites refuse one with - `BootstrapUnsupported`. + 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 diff --git a/docs/operations/site-execution.md b/docs/operations/site-execution.md index 9c6b9e56..504f60d4 100644 --- a/docs/operations/site-execution.md +++ b/docs/operations/site-execution.md @@ -323,8 +323,8 @@ objects. This sequence is proposed only. A handoff carries one assignment: the Device, the operation, the fence, the admitted snapshot and the exact inputs. It holds no credential and no -bootstrap payload. Federation does not yet carry bootstrap payloads, so the -coordinator does not deliver an assignment that names one. A Redfish worker reads each Device's own +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/internal/coordination/transport.go b/internal/coordination/transport.go index 0e4a6fd6..ef6db5ab 100644 --- a/internal/coordination/transport.go +++ b/internal/coordination/transport.go @@ -186,6 +186,8 @@ func (h *Hub) ensure(ctx context.Context, name, role string, spec Spec) (*unstru // 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 { diff --git a/internal/coordination/transport_test.go b/internal/coordination/transport_test.go index faa62982..8acf7726 100644 --- a/internal/coordination/transport_test.go +++ b/internal/coordination/transport_test.go @@ -3,11 +3,14 @@ package coordination import ( "context" "encoding/json" + "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" @@ -293,3 +296,21 @@ 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") + } +} diff --git a/internal/custody/admission_test.go b/internal/custody/admission_test.go index 2e998822..3bd430de 100644 --- a/internal/custody/admission_test.go +++ b/internal/custody/admission_test.go @@ -296,6 +296,25 @@ func TestAdmissionPreconditions(t *testing.T) { 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 staff operation not admitted within five minutes expires", func(t *testing.T) { diff --git a/internal/custody/coordinator.go b/internal/custody/coordinator.go index 35d2f548..12b07fcd 100644 --- a/internal/custody/coordinator.go +++ b/internal/custody/coordinator.go @@ -31,6 +31,14 @@ type Sites interface { Fence(ctx context.Context, site string, device *inventory.Device) (SiteFence, 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 @@ -792,7 +800,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} // Rule 7, the kind's own checks, runs before the shared identity and // key checks, so a kind's more specific reason, such as a system UUID // that is not recorded, is the one reported. diff --git a/internal/custody/harness_test.go b/internal/custody/harness_test.go index 8b01531a..0ad66d04 100644 --- a/internal/custody/harness_test.go +++ b/internal/custody/harness_test.go @@ -70,10 +70,19 @@ 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 +} + +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 cbd487ec..f5a5be85 100644 --- a/internal/custody/kinds.go +++ b/internal/custody/kinds.go @@ -115,8 +115,13 @@ func DeviceInstallationKind() Kind { // 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 { @@ -131,7 +136,7 @@ func DeviceInstallationKind() Kind { return refuse(ReasonBootInterfaceUnknown, "the Device records no interface %q with a MAC address", installation.Spec.BootInterface) }, Settles: []SettleRule{{Held: "DeviceInstallation"}}, - Reasons: append([]Reason{{Name: ReasonBootstrapUnavailable, RaisedBy: RaisedByCoordinator}, {Name: ReasonBootstrapUnsupported, RaisedBy: RaisedByWorker}, {Name: ReasonBootInterfaceUnknown, RaisedBy: RaisedByCoordinator}, {Name: ReasonImageIncompatible, RaisedBy: RaisedByWorker}}, workerReasons...), + Reasons: append([]Reason{{Name: ReasonBootstrapUnavailable, RaisedBy: RaisedByCoordinator}, {Name: ReasonBootstrapUnsupported, RaisedBy: RaisedByBoth}, {Name: ReasonBootInterfaceUnknown, RaisedBy: RaisedByCoordinator}, {Name: ReasonImageIncompatible, RaisedBy: RaisedByWorker}}, workerReasons...), 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. diff --git a/internal/custody/registry.go b/internal/custody/registry.go index f45a9f96..960973f0 100644 --- a/internal/custody/registry.go +++ b/internal/custody/registry.go @@ -153,8 +153,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 d1e628a0..e020004d 100644 --- a/internal/delivery/delivery.go +++ b/internal/delivery/delivery.go @@ -46,7 +46,10 @@ type Sites struct { Devices map[string][]string } -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 @@ -58,6 +61,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 { 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 index 3c7227bb..53fc426c 100644 --- a/internal/sealed/sealed.go +++ b/internal/sealed/sealed.go @@ -20,6 +20,7 @@ import ( "errors" "fmt" "slices" + "unicode/utf8" corev1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" @@ -39,8 +40,13 @@ const ( KeySSHAuthorizedKeys = "sshAuthorizedKeys" ) -// MaxBytes bounds the bootstrap data. -const MaxBytes = 64 << 10 +// 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 ( @@ -80,6 +86,11 @@ func Validate(secret *corev1.Secret) (Payload, error) { 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])} @@ -89,6 +100,9 @@ func Validate(secret *corev1.Secret) (Payload, error) { 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 } @@ -114,6 +128,9 @@ func Seal(payload Payload, operation, allocation, namespace string) (*ops.Sealed 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 diff --git a/internal/sealed/sealed_test.go b/internal/sealed/sealed_test.go index 56bad9f9..ffd7f4b4 100644 --- a/internal/sealed/sealed_test.go +++ b/internal/sealed/sealed_test.go @@ -185,3 +185,21 @@ func TestSweepDeletesOnlyWhatNothingNeeds(t *testing.T) { 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 index f1e6ca63..a010feb2 100644 --- a/internal/site/payload.go +++ b/internal/site/payload.go @@ -29,6 +29,10 @@ type Payloads interface { 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, @@ -117,7 +121,7 @@ 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(assignment.Device); err != nil { + 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}) @@ -133,7 +137,7 @@ func (s StorePayloads) Get(_ context.Context, assignment Assignment) (*Payload, } // Prune deletes the Device's payloads below its stored fence. -func (s StorePayloads) Prune(device string) error { +func (s StorePayloads) Prune(_ context.Context, device string) error { fence, _, err := s.Store.Peek(device) if err != nil { return err diff --git a/internal/site/payload_test.go b/internal/site/payload_test.go index 384435d1..16198e42 100644 --- a/internal/site/payload_test.go +++ b/internal/site/payload_test.go @@ -105,3 +105,58 @@ func TestPayloadsAreStoredOnlyForTheirAssignmentAndPruned(t *testing.T) { 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/runner.go b/internal/site/runner.go index fa8fdcde..6ba461bb 100644 --- a/internal/site/runner.go +++ b/internal/site/runner.go @@ -278,6 +278,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 { diff --git a/internal/site/siteapi/client.go b/internal/site/siteapi/client.go index 0efef5ce..c0f3c95e 100644 --- a/internal/site/siteapi/client.go +++ b/internal/site/siteapi/client.go @@ -72,6 +72,10 @@ func (c *Client) do(ctx context.Context, method, path string, body, into any) er return decoder.Decode(into) } +// 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) } diff --git a/internal/site/siteapi/payload_test.go b/internal/site/siteapi/payload_test.go new file mode 100644 index 00000000..b0957616 --- /dev/null +++ b/internal/site/siteapi/payload_test.go @@ -0,0 +1,111 @@ +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/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, 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 e9b05286..b0b4ec4f 100644 --- a/internal/site/siteapi/server.go +++ b/internal/site/siteapi/server.go @@ -158,6 +158,12 @@ func Handler(dispatcher *Dispatcher, store *site.Store, results *site.Results, t 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) })