diff --git a/cmd/fleet-multiplane/main.go b/cmd/fleet-multiplane/main.go index 48c272f1..d3b678ba 100644 --- a/cmd/fleet-multiplane/main.go +++ b/cmd/fleet-multiplane/main.go @@ -184,6 +184,9 @@ func run() error { if err != nil { return err } + // The worker may get only its own assignment's payload object, which + // federation delivers beside the handoff. + runner.Payloads = coordination.HandoffPayloads{API: api, Namespace: coordinationNamespace, Cell: *cell} err = cellView.Work(ctx, *handoff, runner) fmt.Fprintf(os.Stderr, "site-worker: handoff %s: %s\n", *handoff, classify(err)) switch { diff --git a/config/multiplane/cell-federation/federation.yaml b/config/multiplane/cell-federation/federation.yaml index f704aa17..6b54d1cc 100644 --- a/config/multiplane/cell-federation/federation.yaml +++ b/config/multiplane/cell-federation/federation.yaml @@ -11,7 +11,7 @@ kind: Role metadata: {name: fleet-federation, namespace: fleet-coordination} rules: - apiGroups: [coordination.fleet.datumapis.com] - resources: [machineallocationhandoffs] + resources: [machineallocationhandoffs, machineallocationpayloads] verbs: [get, list, watch, create, update, patch, delete] - apiGroups: [""] resources: [events] @@ -30,7 +30,7 @@ kind: ClusterRole metadata: {name: fleet-federation-discovery} rules: - apiGroups: [coordination.fleet.datumapis.com] - resources: [machineallocationhandoffs] + resources: [machineallocationhandoffs, machineallocationpayloads] verbs: [get, list, watch] - apiGroups: [""] resources: [nodes, pods, namespaces] diff --git a/config/multiplane/coordination/crd.yaml b/config/multiplane/coordination/crd.yaml index bd0e3234..5c1947af 100644 --- a/config/multiplane/coordination/crd.yaml +++ b/config/multiplane/coordination/crd.yaml @@ -41,6 +41,47 @@ spec: type: string minLength: 1 maxLength: 65536 + # The assignment's MachineAllocationPayload, derived from the + # handoff; the assignment's worker may get only it. + payload: {type: string, pattern: '^op-[a-f0-9]{40}-payload$'} status: type: object x-kubernetes-preserve-unknown-fields: true +--- +# An assignment's bootstrap payload, beside its handoff and never inside it. +# A dedicated kind, not a Secret: RBAC on it reaches only payloads, so the +# federation member, kro and each worker need no Secret permission, and no +# BMC credential is exposed to grant one. +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: machineallocationpayloads.coordination.fleet.datumapis.com + annotations: + kustomize.toolkit.fluxcd.io/prune: disabled +spec: + group: coordination.fleet.datumapis.com + scope: Namespaced + names: + plural: machineallocationpayloads + singular: machineallocationpayload + kind: MachineAllocationPayload + versions: + - name: v1alpha1 + served: true + storage: true + schema: + openAPIV3Schema: + type: object + required: [spec] + properties: + spec: + type: object + required: [cell, payload] + x-kubernetes-validations: + - rule: self == oldSelf + message: A payload is immutable + properties: + cell: {type: string, minLength: 1, maxLength: 63} + # The site payload JSON: reference, salted digest, salt and + # data, base64. At most 96 KiB of encoded data. + payload: {type: string, format: byte, minLength: 1, maxLength: 262144} diff --git a/config/multiplane/karmada-api/hub-rbac.yaml b/config/multiplane/karmada-api/hub-rbac.yaml index 17fb5d66..10f9732d 100644 --- a/config/multiplane/karmada-api/hub-rbac.yaml +++ b/config/multiplane/karmada-api/hub-rbac.yaml @@ -11,6 +11,11 @@ rules: resources: [machineallocationhandoffs] # patch marks a handoff's result answered; the spec stays immutable. verbs: [get, list, watch, create, patch] + # The courier writes each assignment's payload, checks an existing one, + # and deletes it once the result is answered or the operation ends. + - apiGroups: [coordination.fleet.datumapis.com] + resources: [machineallocationpayloads] + verbs: [get, list, create, delete] --- apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding diff --git a/config/multiplane/karmada-members/members.yaml b/config/multiplane/karmada-members/members.yaml index c77d1ed1..663e5f12 100644 --- a/config/multiplane/karmada-members/members.yaml +++ b/config/multiplane/karmada-members/members.yaml @@ -28,6 +28,13 @@ spec: labelSelector: matchLabels: coordination.fleet.datumapis.com/cell: "${FLEET_CELL}" + # An assignment's bootstrap payload travels beside its handoff. Deleting + # it on the hub deletes the cell's copy. + - apiVersion: coordination.fleet.datumapis.com/v1alpha1 + kind: MachineAllocationPayload + labelSelector: + matchLabels: + coordination.fleet.datumapis.com/cell: "${FLEET_CELL}" placement: clusterAffinity: clusterNames: diff --git a/config/site/base/kro.yaml b/config/site/base/kro.yaml index a6d759d7..c75e6984 100644 --- a/config/site/base/kro.yaml +++ b/config/site/base/kro.yaml @@ -7,7 +7,11 @@ # Jobs and ServiceAccounts in fleet-site, Roles and RoleBindings in # fleet-coordination. kro holds no Deployment, Service, volume, ConfigMap or # Secret write and no handoff spec or status write. To create a per-operation -# Role granting get on one handoff, kro itself must hold that get permission. +# Role granting get on one handoff and on its one payload, kro itself must +# hold get on both kinds, and it holds nothing more on payloads: no list, +# watch or write, and no escalate or bind. The worker identity policy admits +# only the per-operation Role and binding shapes, and the cluster RBAC policy +# refuses every cluster-wide Role or binding kro writes. apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: @@ -59,6 +63,9 @@ rules: - apiGroups: [rbac.authorization.k8s.io] resources: [roles, rolebindings] verbs: [create, update, patch, delete] + - apiGroups: [coordination.fleet.datumapis.com] + resources: [machineallocationpayloads] + verbs: [get] --- apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding @@ -120,6 +127,19 @@ spec: !has(variables.pod.volumes) || variables.pod.volumes.all(v, (has(v.persistentVolumeClaim) && v.persistentVolumeClaim.claimName == 'fleet-site-state') || has(v.emptyDir)) message: a worker Job may mount only the site journal claim and emptyDir + # The kubelet resolves Secret references for a Pod whatever its + # ServiceAccount may read, so a worker takes environment only from + # literal values and the site enrollment. + - expression: >- + variables.pod.containers.all(c, !has(c.envFrom) && (!has(c.env) || c.env.all(e, !has(e.valueFrom) || + (has(e.valueFrom.configMapKeyRef) && e.valueFrom.configMapKeyRef.name == 'fleet-site-enrollment' && + !has(e.valueFrom.secretKeyRef) && !has(e.valueFrom.fieldRef) && !has(e.valueFrom.resourceFieldRef))))) + message: a worker Job may take environment only from literal values and the site enrollment + - expression: >- + variables.pod.containers.all(c, !has(c.args) && has(c.command) && size(c.command) == 6 && + c.command[0] == 'fleet-multiplane' && c.command[1] == 'site-worker' && + c.command[2] == '--handoff' && c.command[3] == variables.handoff && c.command[4] == '--cell') + message: a worker Job must run only the site worker for its own handoff --- apiVersion: admissionregistration.k8s.io/v1 kind: ValidatingAdmissionPolicyBinding @@ -158,11 +178,16 @@ spec: - expression: "variables.kind != 'serviceaccounts' || request.namespace == 'fleet-site'" message: worker ServiceAccounts live in fleet-site - expression: >- - variables.kind != 'roles' || (has(object.rules) && size(object.rules) == 1 && - object.rules.all(r, r.apiGroups == ['coordination.fleet.datumapis.com'] && - r.resources == ['machineallocationhandoffs'] && r.verbs == ['get'] && - has(r.resourceNames) && r.resourceNames == [variables.handoff])) - message: a worker Role may grant only get on its own handoff + variables.kind != 'roles' || (has(object.rules) && size(object.rules) == 2 && + object.rules[0].apiGroups == ['coordination.fleet.datumapis.com'] && + object.rules[0].resources == ['machineallocationhandoffs'] && object.rules[0].verbs == ['get'] && + has(object.rules[0].resourceNames) && object.rules[0].resourceNames == [variables.handoff] && + !has(object.rules[0].nonResourceURLs) && + object.rules[1].apiGroups == ['coordination.fleet.datumapis.com'] && + object.rules[1].resources == ['machineallocationpayloads'] && object.rules[1].verbs == ['get'] && + has(object.rules[1].resourceNames) && object.rules[1].resourceNames == [variables.handoff + '-payload'] && + !has(object.rules[1].nonResourceURLs)) + message: a worker Role may grant only get on its own handoff and on its own payload - expression: >- variables.kind != 'rolebindings' || (object.roleRef.kind == 'Role' && object.roleRef.name == object.metadata.name && has(object.subjects) && size(object.subjects) == 1 && @@ -176,3 +201,27 @@ metadata: {name: fleet-site-kro-worker-identity} spec: policyName: fleet-site-kro-worker-identity validationActions: [Deny] +--- +# kro holds no cluster-wide RBAC write, and this refuses one anyway: a graph +# revision must never create or change a ClusterRole or ClusterRoleBinding. +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicy +metadata: {name: fleet-site-kro-cluster-rbac} +spec: + failurePolicy: Fail + matchConstraints: + resourceRules: + - {apiGroups: [rbac.authorization.k8s.io], apiVersions: ["*"], resources: [clusterroles, clusterrolebindings], operations: [CREATE, UPDATE, DELETE]} + matchConditions: + - name: kro-controller + expression: "request.userInfo.username == 'system:serviceaccount:kro-system:kro'" + validations: + - expression: "false" + message: kro may not write cluster-wide RBAC +--- +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicyBinding +metadata: {name: fleet-site-kro-cluster-rbac} +spec: + policyName: fleet-site-kro-cluster-rbac + validationActions: [Deny] diff --git a/config/site/graph/rgd.yaml b/config/site/graph/rgd.yaml index 39932d62..f02a2f8a 100644 --- a/config/site/graph/rgd.yaml +++ b/config/site/graph/rgd.yaml @@ -97,7 +97,9 @@ spec: operator: In values: [assignment] # Per-operation identity and policy: each worker may read exactly its own - # handoff and nothing else. It has no status, list or Secret permission. + # handoff and its own payload, which exists only for an operation with + # bootstrap data, and nothing else. It has no status, list or Secret + # permission. # The fleet-site-kro-worker-identity admission policy enforces this shape. - id: workerAccounts includeWhen: @@ -127,6 +129,10 @@ spec: resources: [machineallocationhandoffs] resourceNames: ["${handoff.metadata.name}"] verbs: [get] + - apiGroups: [coordination.fleet.datumapis.com] + resources: [machineallocationpayloads] + resourceNames: ["${handoff.metadata.name + '-payload'}"] + verbs: [get] - id: workerBindings includeWhen: - ${schema.spec.dispatch} diff --git a/config/site/redfish/base/kustomization.yaml b/config/site/redfish/base/kustomization.yaml index 790d4883..9a26f23b 100644 --- a/config/site/redfish/base/kustomization.yaml +++ b/config/site/redfish/base/kustomization.yaml @@ -36,7 +36,7 @@ patches: patch: |- - op: test path: /spec/validations/2/message - value: a worker Role may grant only get on its own handoff + value: a worker Role may grant only get on its own handoff and on its own payload - op: replace path: /spec/matchConstraints/namespaceSelector/matchExpressions/0/values value: [fleet-site, fleet-coordination, fleet-site-credentials, fleet-site-worker-identity] @@ -51,7 +51,13 @@ patches: request.namespace == 'fleet-site-worker-identity' ? (has(object.rules) && size(object.rules) == 1 && object.rules.all(r, r.apiGroups == [''] && r.resources == ['secrets'] && r.verbs == ['get'] && has(r.resourceNames) && r.resourceNames == ['fleet-site-worker-media'])) : - (has(object.rules) && size(object.rules) == 1 && object.rules.all(r, r.apiGroups == ['coordination.fleet.datumapis.com'] && - r.resources == ['machineallocationhandoffs'] && r.verbs == ['get'] && - has(r.resourceNames) && r.resourceNames == [variables.handoff]))) - message: a worker Role may grant only get on its own handoff, get on one named BMC credential, or get on the site worker identity + (has(object.rules) && size(object.rules) == 2 && + object.rules[0].apiGroups == ['coordination.fleet.datumapis.com'] && + object.rules[0].resources == ['machineallocationhandoffs'] && object.rules[0].verbs == ['get'] && + has(object.rules[0].resourceNames) && object.rules[0].resourceNames == [variables.handoff] && + !has(object.rules[0].nonResourceURLs) && + object.rules[1].apiGroups == ['coordination.fleet.datumapis.com'] && + object.rules[1].resources == ['machineallocationpayloads'] && object.rules[1].verbs == ['get'] && + has(object.rules[1].resourceNames) && object.rules[1].resourceNames == [variables.handoff + '-payload'] && + !has(object.rules[1].nonResourceURLs))) + message: a worker Role may grant only get on its own handoff and on its own payload, or get on one named BMC credential or the site worker identity diff --git a/docs/development/README.md b/docs/development/README.md index fd0e5234..b89afc37 100644 --- a/docs/development/README.md +++ b/docs/development/README.md @@ -44,9 +44,8 @@ is implemented on the same custody, and nothing creates power operations yet. [OS images and bootstrap data](machine-images.md) has its image catalog **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 -**implemented** through the simulator site; federation and the lab sites do -not carry bootstrap data yet. +server's architecture and firmware mode. The simulator uses the sealed bootstrap store. Federation and guest seed +delivery are exercised only by isolated tests, not enabled in deployments. 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 @@ -822,7 +821,6 @@ acceptance inventory. site credential protocol. - 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). + delivery is described in [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 1a6ff1a8..2210da9c 100644 --- a/docs/development/device-custody.md +++ b/docs/development/device-custody.md @@ -452,7 +452,7 @@ a Machine status, update or patch permission. ### Unchanged and still open -- Bootstrap data reaches only the simulator site. See +- Only isolated tests deliver bootstrap data to federated network-boot workers. See [OS images and bootstrap data](machine-images.md). - `DeviceRecovery` needs no second person. @@ -1483,7 +1483,7 @@ Increment B's site tests run with `go test -race ./internal/site/...`: | One worker per assignment, final results, shutdown at each stage, an older worker that does not stop, a fence raised between journal and send | `TestARedeliveryWhileTheSameOperationRunsStoresNothing`, `TestACopyWaitingForTheLockReturnsTheStoredResult`, `TestAStoredResultSurvivesARedelivery`, `TestAWorkerStoppedFromOutsideStoresNoResult`, `TestAShutdownWhileWaitingForTheRunLockStoresNothing`, `TestAShutdownDuringTheChecksStoresNothing`, `TestANewerAssignmentThatCannotStopTheOlderWorkerSendsNothing`, `TestALostLockWithJournaledStepsIsUnknown`, `TestAFenceRaisedBetweenJournalAndSendStopsTheStep` | | Per-Device credentials, the fence report | `TestSecretCredentialsUseThePerDeviceContract`, `TestReportGivesTheCoordinatorSeenAndStoppedFences` | | Step payloads, the start-by window, identity separate from capabilities, a resumed worker reporting unknown | `TestAStepPayloadIsJournaledAndReadBack`, `TestALateStartIsStaleAndSendsNothing`, `TestIdentityIsSeparateFromInstallCapabilities`, `TestAResumedWorkerThatCannotReachTheBMCReportsUnknown` | -| Install and wipe against a simulated BMC, one power-on per phase after an interruption in either phase, the power-off bound, fenced boot admission, bootstrap refused by a site that cannot hand it on | `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 data the installer verifies on disk, bootstrap refused without a payload | `TestAWorkerInterruptedInTheDiskPhaseResumes`, `TestAServerThatNeverPowersOffEndsTheStep`, `TestInstallationRunsBothPhasesWithOneOnEach`, `TestWipeChecksTheEnrolledDisk`, `TestAnInterruptedWorkerResumesWithoutASecondOn`, `TestOnlyTheCurrentFenceHasAnOpenBootAdmission`, `TestTheInstallerVerifiesBootstrapDataOverRedfish`, `TestBootstrapWithoutAPayloadSendsNothing` | 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 7285ef96..619baf8f 100644 --- a/docs/development/machine-images.md +++ b/docs/development/machine-images.md @@ -14,7 +14,7 @@ proposal's API names are provisional. Each piece below is marked | --- | --- | --- | | 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. 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** | +| 3: federation and network-boot seed prototype | Per-operation payload transport, worker authorization, installer readback and scrubbing | **Test-only.** No runtime flag, deployment or acceptance fixture enables customer seed delivery. | ## What increment 1 adds @@ -105,15 +105,55 @@ proposal's API names are provisional. Each piece below is marked fence, for a newer operation or a recovery, which removes every payload below it, including one whose worker never ran. A worker stopped from outside keeps it for its replacement. -- **Evidence.** A successful install's evidence names the digest of the data - the worker handed to the server, recomputed from what it handed. Custody - accepts a success only if that equals the admitted digest, and only if it is - empty when there was no bootstrap data. +- **Evidence.** A successful install's evidence records, as installer-verified, + the salted digest of the bootstrap data on the target disk: the simulator + recomputes it from what it wrote, and a lab installer from what it read + back. Custody accepts a success only if it 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. +## What increment 3 adds + +These contracts are exercised with synthetic fixtures in package tests only. Ordinary hubs refuse before writing a payload or handoff; cells and HTTP boot services independently refuse a seed. Neither the lab harness nor staging enables this path. + +- **Federation.** The hub writes each payload as a `MachineAllocationPayload` + beside its handoff, before the handoff that names it. It is its own kind, + not a Secret, because Karmada's member identity watches every kind it + propagates across the whole cell, and the lab BMC's credentials are + Secrets. A worker that runs before the payload arrives sends nothing, + stores no result, and is retried; a payload it cannot read is an error, + and one that does not decode refuses the handoff. +- **Deletion.** The hub deletes a payload when the coordinator answers its + result, and after every complete coordinator pass it deletes each payload + whose operation is no longer delivered: ended, cancelled, superseded, or + never given a handoff. Deleting the hub's copy deletes the cell's. +- **Site RBAC.** Each worker may get its own handoff and its own payload, by + name. kro, which creates every worker, holds only get on payloads, so it + can grant that without escalate or bind; it can already run a worker as + any operation's identity, so this grants it nothing new. Admission policies + admit only the per-operation Role and RoleBinding shapes on create and + update, refuse every cluster-wide RBAC write by kro, and admit only Jobs + that run the site worker for their own handoff and take environment from + literals and the site enrollment. A test against a real API server runs + each refused shape as kro and shows that it is admitted once the clauses it + names are removed. +- **Guest.** The worker renders the verified payload as a NoCloud seed archive + and attaches it to the operation's boot admission. The boot service serves + it as a second initrd only while the admission is open. The site drops the + seed when the admission closes, when the operation's result is stored + however it ended, and when a newer fence for the Device is raised, so no + failed, expired or superseded install leaves it behind. The installer copies + the seed to the target disk, puts the user data where NoCloud reads it and + the keys in the default user's `authorized_keys`, reads it all back from the + disk past the page cache, and reports the salted digest. The worker requires + exactly that digest before it lets the disk boot run; a wrong, truncated or + missing report fails the install. This installer readback is a test assertion, not production installation success. A direct kernel boot, + which has one initrd, refuses bootstrap data. +- **Transport and success.** The #227 virtual-media path requires certificate-verified HTTPS and an authenticated first-boot report from the installed OS. Installer readback or console output is not that proof. Customer bootstrap via virtual media is refused. Only the installed NoCloud files and authorized keys belong on the disk; the network installer keeps its raw JSON and salt in the initramfs. + ## Not implemented yet - The validating webhook that rejects image writes from anyone but the @@ -124,10 +164,9 @@ proposal's API names are provisional. Each piece below is marked - Artifact mirroring by digest from a provider registry. Each lab site holds one pinned image and serves only that one. - Firmware mode from BMC discovery. Lab fixtures write it on the capacity. -- Federation delivery of bootstrap payloads to a cell, and handing them to a - local VM or Redfish server. Admission refuses such an operation with - `BootstrapUnsupported` before the Device's fence moves. - The Milo check that the Installation's creator can read the bootstrap Secret. The lab compositions read it with their own identity. -- Encryption at rest for `SealedPayload` and an audit policy that omits its - bodies. +- Encryption at rest for `SealedPayload` and `MachineAllocationPayload`, on + the provider project, the federation hub and its Work objects, and the + cell, and an audit policy that omits their bodies. +- Verified transport for a customer network-boot seed. HTTP seed serving stays disabled outside package tests. diff --git a/docs/operations/redfish-lab.md b/docs/operations/redfish-lab.md index 10ba2e1e..b486d878 100644 --- a/docs/operations/redfish-lab.md +++ b/docs/operations/redfish-lab.md @@ -595,7 +595,7 @@ a CI runner's KVM guests. Each held installation waits out both windows. | Central media service | Real windows, fences from custody, media, report endpoint, transfer records and a background sweep that drops config media no window can serve. The sweep skips and counts a window file it cannot read, and goes on. In the lab it runs on the workstation beside the coordinator, on loopback, which lab Pods reach through the runtime's host gateway. Guests reach it through the report relay. | | Worker authentication | Real. Each site worker presents a client certificate from the site workers' CA. The certificate is its own Secret, `fleet-site-worker-media`, one per site worker identity, in the `fleet-site-worker-identity` namespace. Each worker gets exactly that Secret through a per-operation Role, and BMC credential Secrets hold only BMC credentials. Only virtual media reads it: network boot installs and wipes neither read nor need it. The service refuses every window operation from a client with no certificate, or one that is not the worker for that Device's site. | | BMC | Real Redfish VirtualMedia on the lab emulator: two CD devices, insert over verified HTTPS, eject, readback, one-time boot from CD. As a BMC does, the lab BMC accepts an insert at once and then fetches the medium, so a slow fetch never outlasts the worker's request. A power-on during a fetch answers at once and starts the target once its media are fetched. A medium the BMC cannot fetch stays inserted but is never attached, so the target boots without it and sends no report. | -| First-boot report | Real. The installed lab OS posts it over HTTPS. Bootstrap data is always empty because the sealed store is not on this branch; admission still refuses bootstrap data. | +| First-boot report | Real. The installed lab OS posts it over HTTPS. The customer bootstrap field is refused for virtual media; the sealed simulator store does not change this transport or success criterion. | | Installer downloads | Admission refuses any download that is not pinned by digest. The config medium lists the pinned downloads, and the first-boot report names each download by the digest the installer fetched. The worker refuses a report whose downloads are not exactly the recorded ones. The lab installer fetches nothing; it reports what its config medium lists. | | Report source | Real. Each virtual media installation records the Machine's address, which IPAM bound to the operation's own claim. The media service takes the report only from that address, and only inside the site's report ranges; a report from another address in the ranges is refused and recorded, token or not. The path from lab guests to the workstation rewrites their addresses, so guests post to a relay on the lab bridge, which names each guest's address to the service's relay listener in a PROXY protocol header. The service trusts that header only from its configured relays. The installed OS adds its IPAM address beside its DHCP lease and reports from it. The lab proves the service's check, not the network's binding: its relay set is all of loopback, because every lab Pod arrives there, so any lab Pod could name any source and only the report token stops it. Guests cannot reach the relay listener, but on the shared lab bridge a guest can take any lab address, as the stray-source fault does. A real site network, where only the relay or load balancer reaches the relay listener and the data network serves only the Machine its address, still needs verifying. | | BMCs that do not verify HTTPS | Stubbed. Staff record `fleet.datumapis.com/virtual-media-tls: Unverified`, and admission refuses virtual media for that server. The fallback that mounts only the public medium and fetches bootstrap data with a single-use token is not implemented. | @@ -640,9 +640,12 @@ receipts. The site framework's tests in `internal/site` run against TLS stubs. Together they cover: - an install with both phases and one power-on each, a wipe that checks the - enrolled disk, and a bootstrap reference refused at the site + enrolled disk, bootstrap data the installer must verify on the target disk + by its salted digest before the disk boot, and bootstrap data refused when + the site holds no payload (`TestInstallationRunsBothPhasesWithOneOnEach`, `TestWipeChecksTheEnrolledDisk`, - `TestBootstrapIsRefusedAtTheSiteToo`); + `TestTheInstallerVerifiesBootstrapDataOverRedfish`, + `TestBootstrapWithoutAPayloadSendsNothing`); - a worker interrupted in either phase that resumes without a second power-on (`TestAnInterruptedWorkerResumesWithoutASecondOn`, `TestAWorkerInterruptedInTheDiskPhaseResumes`); diff --git a/docs/operations/site-execution.md b/docs/operations/site-execution.md index 0ad92ea3..cb6e5ef9 100644 --- a/docs/operations/site-execution.md +++ b/docs/operations/site-execution.md @@ -325,8 +325,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 -admission refuses an operation that names one. A Redfish worker reads each Device's own +bootstrap payload. Federation refuses bootstrap in every deployment. In tests +a separate `MachineAllocationPayload` is readable only by its assigned worker and infrastructure identities. See [OS images and bootstrap data](../development/machine-images.md). 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/local-vm/init b/hack/local-vm/init index 3fccbdca..09a7767e 100644 --- a/hack/local-vm/init +++ b/hack/local-vm/init @@ -111,7 +111,7 @@ fi printf 'label: dos\n, , L, *\n' | sfdisk /dev/vda # One line, in one write, once the disk is partitioned: the shell trace above # reaches the console in pieces the kernel's own messages can split. -printf 'FLEET-PARTITIONED:%s\n' "$receipt" +[ "$delivery" = media ] || printf 'FLEET-PARTITIONED:%s\n' "$receipt" mkfs.ext4 -F /dev/vda1 mkdir -p /target mount /dev/vda1 /target @@ -134,6 +134,14 @@ if [ "$delivery" = media ]; then else printf '%s\n' "$receipt" > /target/fleet-receipt fi +# Only the NoCloud files and authorized keys go on disk, not the raw seed. +if [ -d /fleet-bootstrap ]; then + mkdir -p /target/var/lib/cloud/seed/nocloud /target/root/.ssh + cp /fleet-bootstrap/user-data /fleet-bootstrap/meta-data /target/var/lib/cloud/seed/nocloud/ + cp /fleet-bootstrap/authorized_keys /target/root/.ssh/authorized_keys + chmod 700 /target/root/.ssh + chmod 600 /target/root/.ssh/authorized_keys +fi chroot /target grub-install --target=i386-pc /dev/vda kernel=$(basename /boot/vmlinuz-*) initrd=$(basename /boot/initrd.img-*) @@ -164,5 +172,17 @@ if [ "$delivery" = media ]; then echo 'fleet: virtual media installer finished' /bin/busybox poweroff -f fi +# Read the installed seed back from the disk, past the page cache, and report +# its salted digest. The worker requires exactly the admitted digest; the +# installed OS is not asked to prove anything. A copy that differs from the +# seed on disk stops the install before its receipt. +if [ -d /fleet-bootstrap ]; then + echo 3 > /proc/sys/vm/drop_caches + cmp -s /fleet-bootstrap/user-data /target/var/lib/cloud/seed/nocloud/user-data + cmp -s /fleet-bootstrap/meta-data /target/var/lib/cloud/seed/nocloud/meta-data + cmp -s /fleet-bootstrap/authorized_keys /target/root/.ssh/authorized_keys + digest=$(cat /fleet-bootstrap/salt /fleet-bootstrap/data | sha256sum | cut -d' ' -f1) + printf 'FLEET-BOOTSTRAP:%s:sha256:%s\n' "$receipt" "$digest" +fi printf 'FLEET-INSTALLED:%s\n' "$receipt" /bin/busybox poweroff -f diff --git a/hack/multiplane/k8s_evidence.py b/hack/multiplane/k8s_evidence.py index 7e33ae1f..7c8926ed 100644 --- a/hack/multiplane/k8s_evidence.py +++ b/hack/multiplane/k8s_evidence.py @@ -119,7 +119,9 @@ def worker_rbac(state, name): for args in (('-n', NS, 'get', 'machineallocationhandoff', 'op-other-operation'), ('-n', NS, 'get', 'machineallocationhandoffs'), ('-n', NS, 'patch', 'machineallocationhandoff', name, '--subresource=status', '--type=merge', '-p', '{"status":{}}'), ('-n', NS, 'patch', 'machineallocationhandoff', name, '--type=merge', '-p', '{"spec":{"cell":"other"}}'), - ('-n', NS, 'get', 'secrets'), ('-n', SITE, 'get', 'secrets'), ('-n', SITE, 'create', 'configmap', 'forbidden', '--from-literal=x=y'), ('-n', SITE, 'get', 'jobs'), + ('-n', NS, 'get', 'secrets'), ('-n', NS, 'get', 'machineallocationpayloads'), + ('-n', NS, 'get', 'machineallocationpayload', 'op-other-operation-payload'), + ('-n', NS, 'delete', 'machineallocationpayload', name + '-payload'), ('-n', SITE, 'get', 'secrets'), ('-n', SITE, 'create', 'configmap', 'forbidden', '--from-literal=x=y'), ('-n', SITE, 'get', 'jobs'), # Another Device's credential, and listing or watching them, are # denied in both modes. ('-n', CREDENTIALS, 'get', 'secret', credential_name(OTHER_DEVICE)), ('-n', CREDENTIALS, 'get', 'secrets'), @@ -129,7 +131,12 @@ def worker_rbac(state, name): if r.returncode == 0 or 'forbidden' not in r.stderr.lower(): raise SystemExit('worker credential allowed: ' + ' '.join(args[:4]) + ' ' + r.stderr[:200]) denied.append(args[1] + ' ' + ' '.join(args[2:4]) + (' (status)' if '--subresource=status' in args else '')) - record = {'observedAt': now(), 'serviceAccount': 'w-' + name, 'ownHandoffReadable': True, 'forbidden': denied} + # The worker may get exactly its own payload, which exists only for an + # operation with bootstrap data. + mine = kubectl(state, 'auth', 'can-i', 'get', 'machineallocationpayload/' + name + '-payload', '-n', NS, check=False, config='worker-kubeconfig.json') + if mine.stdout.strip() != 'yes': + raise SystemExit('worker cannot get its own payload: ' + (mine.stdout + mine.stderr)[:200]) + record = {'observedAt': now(), 'serviceAccount': 'w-' + name, 'ownHandoffReadable': True, 'ownPayloadReadable': True, 'forbidden': denied} role = get(state, '-n', NS, 'get', 'role', 'w-' + name) record.update(roleRules=role['rules'], roleCreatedBy=role['metadata'].get('labels', {}).get('kro.run/node-id')) if REDFISH: diff --git a/hack/multiplane/test-harness.sh b/hack/multiplane/test-harness.sh index fba84830..6eb21507 100755 --- a/hack/multiplane/test-harness.sh +++ b/hack/multiplane/test-harness.sh @@ -490,8 +490,11 @@ with tempfile.TemporaryDirectory() as tmp: check('kro writes only worker kinds in their namespaces', sorted(roles) == sorted(write_roles) and all( all(k in roles[n] for k in kinds) and not any(x in roles[n] for x in ('deployments', 'services', 'persistentvolumeclaims', 'configmaps', 'secrets')) for n, kinds in write_roles.items()), str(sorted(roles))) - check('kro writes are shape-checked by admission', kro_rbac.count('kind: ValidatingAdmissionPolicy\n') == 2 and kro_rbac.count('kind: ValidatingAdmissionPolicyBinding\n') == 2 - and kro_rbac.count("request.userInfo.username == 'system:serviceaccount:kro-system:kro'") == 2 and 'parameterNotFoundAction: Deny' in kro_rbac) + check('kro writes are shape-checked by admission', kro_rbac.count('kind: ValidatingAdmissionPolicy\n') == 3 and kro_rbac.count('kind: ValidatingAdmissionPolicyBinding\n') == 3 + and kro_rbac.count("request.userInfo.username == 'system:serviceaccount:kro-system:kro'") == 3 and 'parameterNotFoundAction: Deny' in kro_rbac) + check('kro may not write cluster-wide RBAC', 'name: fleet-site-kro-cluster-rbac' in kro_rbac and 'resources: [clusterroles, clusterrolebindings], operations: [CREATE, UPDATE, DELETE]' in kro_rbac) + kro_rules = '\n'.join(line for line in kro_rbac.splitlines() if not line.lstrip().startswith('#')) + check('kro holds no escalate or bind', 'escalate' not in kro_rules and not re.search(r'verbs: \[[^]]*\bbind\b', kro_rules)) kro = (root / 'config/multiplane/kro/kro.yaml').read_text() check('unused chart ConfigMap grant removed, failing closed', 'postRenderers:' in kro and 'op: test' in kro and 'resources: [configmaps]' in kro and 'op: remove' in kro) check('kro version pinned consistently', 'tag: v0.9.4@sha256:' in kro and "'version': 'v0.9.4'" in evidence and 'digest: sha256:4e8de4d3' in kro) diff --git a/hack/multiplane/test-k8s-evidence.py b/hack/multiplane/test-k8s-evidence.py index d599e979..385fca16 100644 --- a/hack/multiplane/test-k8s-evidence.py +++ b/hack/multiplane/test-k8s-evidence.py @@ -36,6 +36,8 @@ def emit(v): print(json.dumps(v)); sys.exit(0) if config.endswith('worker-kubeconfig.json'): if args[-3:] == ['get', 'machineallocationhandoff', world['handoff']] or args[-5:-2] == ['get', 'machineallocationhandoff', world['handoff']]: print('machineallocationhandoff/' + world['handoff']); sys.exit(0) + if args[:2] == ['auth', 'can-i'] and args[3] == 'machineallocationpayload/' + world['handoff'] + '-payload': + print('yes'); sys.exit(0) print('Error from server (Forbidden): denied', file=sys.stderr); sys.exit(1) if args[:3] == ['config', 'view', '--raw']: emit({'clusters': [{'cluster': {}}], 'contexts': [{'context': {}}], 'users': []}) @@ -74,7 +76,7 @@ def emit(v): print(json.dumps(v)); sys.exit(0) emit(world['machines'][config.split('/')[-2]]) if kind == 'role' and ns() == 'fleet-site-credentials' and name not in world.get('credentialRoles', []): print('NotFound', file=sys.stderr); sys.exit(1) -if kind == 'role': emit({'metadata': {'labels': {'kro.run/node-id': 'workerRoles'}}, 'rules': [{'resourceNames': [world['handoff']], 'verbs': ['get']}]}) +if kind == 'role': emit({'metadata': {'labels': {'kro.run/node-id': 'workerRoles'}}, 'rules': [{'resourceNames': [world['handoff']], 'verbs': ['get']}, {'resourceNames': [world['handoff'] + '-payload'], 'verbs': ['get']}]}) if kind == 'machineallocationhandoffs': emit({'items': world['handoffs']}) if kind == 'roles': emit({'items': world.get('roles', [])}) if kind == 'machineallocationhandoff' and name not in [h['metadata']['name'] for h in world['handoffs']] + world.get('created', []) + [world['handoff']]: diff --git a/hack/multiplane/verify-rbac.py b/hack/multiplane/verify-rbac.py index 149dc175..6807e772 100755 --- a/hack/multiplane/verify-rbac.py +++ b/hack/multiplane/verify-rbac.py @@ -54,7 +54,10 @@ def can(*args): r=call(s/'cell-admin.yaml','auth','can-i',*args,'--as',kro) if r.stdout.strip() not in ('yes','no'):raise SystemExit('auth can-i failed: '+r.stderr[:200]) return r.stdout.strip()=='yes' +p='machineallocationpayloads.coordination.fleet.datumapis.com' allowed=[('create','jobs','-n',site),('create','serviceaccounts','-n',site),('create','roles','-n',ns),('create','rolebindings','-n',ns), + # kro grants each worker get on its one payload, so it holds get and nothing more on payloads. + ('get',p,'-n',ns), ('list','deployments','-A'),('list','services','-A'),('watch',h,'-A'),('get','persistentvolumeclaims','-n',site)] redfish=os.environ.get('FLEET_SITE_PROVIDER')=='redfish';creds_ns='fleet-site-credentials';ident_ns='fleet-site-worker-identity' if redfish: @@ -66,7 +69,9 @@ def can(*args): denied=[('create','deployments','-n',site),('patch','deployments','-n',site),('create','services','-n',site),('delete','services','-n',site), ('delete','persistentvolumeclaims','-n',site),('patch','configmaps','-n',site),('create','jobs','-n','default'),('create','jobs','-n','kube-system'), ('create','roles','-n',site),('create','rolebindings','-n','kube-system'),('create','clusterroles'),('get','secrets','-n',site), - ('patch',h,'-n',ns),('update',h,'--subresource=status','-n',ns),('delete','validatingadmissionpolicies')]+( + ('patch',h,'-n',ns),('update',h,'--subresource=status','-n',ns),('delete','validatingadmissionpolicies'), + ('list',p,'-n',ns),('watch',p,'-n',ns),('create',p,'-n',ns),('delete',p,'-n',ns),('get','secrets','-n',ns), + ('escalate','roles','-n',ns),('bind','roles','-n',ns),('create','clusterrolebindings'),('escalate','clusterroles'),('bind','clusterroles')]+( [('list','secrets','-n',creds_ns),('create','secrets','-n',creds_ns),('watch','secrets','-n',creds_ns), ('list','secrets','-n',ident_ns),('create','secrets','-n',ident_ns),('watch','secrets','-n',ident_ns)] if redfish else []) bad=[' '.join(a) for a in allowed if not can(*a)]+['denied '+' '.join(a) for a in denied if can(*a)] @@ -77,14 +82,18 @@ def can(*args): retained={' '.join(a):can(*a) for a in retained} image=json.loads((s/'gitops-environment.json').read_text())['siteImage'] def job(**change): - c={'name':'worker','image':image,'command':['fleet-multiplane','site-worker'],'securityContext':{'runAsUser':0,'allowPrivilegeEscalation':False,'readOnlyRootFilesystem':True,'capabilities':{'drop':['ALL']}}} + c={'name':'worker','image':image,'command':['fleet-multiplane','site-worker','--handoff','op-admission-probe','--cell','probe'],'securityContext':{'runAsUser':0,'allowPrivilegeEscalation':False,'readOnlyRootFilesystem':True,'capabilities':{'drop':['ALL']}}} if redfish:c['env']=[{'name':'FLEET_SITE_PROVIDER','value':'redfish'}] spec={'restartPolicy':'Never','serviceAccountName':'w-op-admission-probe','containers':[c],'volumes':[{'name':'state','persistentVolumeClaim':{'claimName':'fleet-site-state'}},{'name':'tmp','emptyDir':{}}]} for k,v in change.items(): - (c if k in ('image','securityContext','env','volumeMounts') else spec)[k]=v + (c if k in ('image','securityContext','env','envFrom','command','args','volumeMounts') else spec)[k]=v return {'apiVersion':'batch/v1','kind':'Job','metadata':{'name':'w-op-admission-probe','namespace':site,'labels':{'fleet.datumapis.com/handoff':'op-admission-probe'}},'spec':{'template':{'spec':spec}}} role=lambda rules,namespace=ns:{'apiVersion':'rbac.authorization.k8s.io/v1','kind':'Role','metadata':{'name':'w-op-admission-probe','namespace':namespace},'rules':rules} -own=[{'apiGroups':['coordination.fleet.datumapis.com'],'resources':['machineallocationhandoffs'],'resourceNames':['op-admission-probe'],'verbs':['get']}] +own=[{'apiGroups':['coordination.fleet.datumapis.com'],'resources':['machineallocationhandoffs'],'resourceNames':['op-admission-probe'],'verbs':['get']}, + {'apiGroups':['coordination.fleet.datumapis.com'],'resources':['machineallocationpayloads'],'resourceNames':['op-admission-probe-payload'],'verbs':['get']}] +# A binding of the per-operation Role itself, so only its subject is wrong. +subject=lambda *s:{'apiVersion':'rbac.authorization.k8s.io/v1','kind':'RoleBinding','metadata':{'name':'w-op-admission-probe','namespace':ns}, + 'subjects':list(s),'roleRef':{'apiGroup':'rbac.authorization.k8s.io','kind':'Role','name':'w-op-admission-probe'}} # RBAC resolves a binding's Role before admission runs, so the probe binds an # existing Role that kro fully holds; a dry run cannot create w- first. binding=lambda name,sa,ref,namespace=ns:{'apiVersion':'rbac.authorization.k8s.io/v1','kind':'RoleBinding','metadata':{'name':name,'namespace':namespace}, @@ -93,7 +102,25 @@ def job(**change): cases={'admitted':{'worker Job':job(),'worker Role':role(own),'worker ServiceAccount':sa('w-op-admission-probe')}, 'denied':{'Job as the observer':job(serviceAccountName='fleet-site-observer'),'privileged Job':job(securityContext={'privileged':True,'allowPrivilegeEscalation':True}), 'Job from another image':job(image='registry.k8s.io/pause:3.10'),'Job with a hostPath volume':job(volumes=[{'name':'host','hostPath':{'path':'/'}}]), - 'Job on the host network':job(hostNetwork=True),'Role listing every handoff':role([dict(own[0],resourceNames=[],verbs=['get','list'])]), + 'Job on the host network':job(hostNetwork=True), + # The kubelet resolves these whatever the worker may read, so the policy refuses them. + 'Job taking environment from a Secret':job(envFrom=[{'secretRef':{'name':'fleet-site-bmc-credentials'}}]), + 'Job reading a Secret key':job(env=[{'name':'X','valueFrom':{'secretKeyRef':{'name':'fleet-site-bmc-credentials','key':'password'}}}]), + 'Job running another command':job(command=['sh','-c','true']), + 'Job for another handoff':job(command=['fleet-multiplane','site-worker','--handoff','op-other-operation','--cell','probe']), + 'Job with arguments':job(args=['--extra']),'Role listing every handoff':role([dict(own[0],resourceNames=[],verbs=['get','list']),own[1]]), + # Each shape is within kro's own grant, so only the policy can refuse it. + 'worker Role without its payload rule':role([own[0]]), + 'worker Role reading another operation\'s payload':role([own[0],dict(own[1],resourceNames=['op-other-operation-payload'])]), + 'worker Role reading every payload by an empty name list':role([own[0],dict(own[1],resourceNames=[])]), + 'worker Role with a third rule':role(own+[own[0]]), + # Outside kro's own grant, so RBAC refuses these before admission; the + # cluster RBAC policy refuses the cluster-wide ones too. + 'Role listing payloads':role([own[0],dict(own[1],verbs=['get','list'])]), + 'Role reading Secrets':role([own[0],{'apiGroups':[''],'resources':['secrets'],'verbs':['get']}]), + 'ClusterRole':{'apiVersion':'rbac.authorization.k8s.io/v1','kind':'ClusterRole','metadata':{'name':'w-op-admission-probe'},'rules':own}, + 'ClusterRoleBinding to kro':{'apiVersion':'rbac.authorization.k8s.io/v1','kind':'ClusterRoleBinding','metadata':{'name':'w-op-admission-probe'}, + 'subjects':[{'kind':'ServiceAccount','name':'kro','namespace':'kro-system'}],'roleRef':{'apiGroup':'rbac.authorization.k8s.io','kind':'ClusterRole','name':'fleet-site-kro'}}, 'RoleBinding to another Role, for the observer':binding('w-op-admission-probe','fleet-site-observer','fleet-site-kro-worker-rbac'),'ServiceAccount outside the worker set':sa('fleet-site-probe')}} if redfish: # Redfish workers have no hypervisor path: the libvirt socket, the lab disks @@ -131,10 +158,42 @@ def job(**change): # A credential Role that lists Secrets is outside kro's own grant: kro holds # only get there, so RBAC escalation refuses it before admission. Every other # shape is within kro's grant and must be refused by the policies. -outside_grant={'credential Role listing Secrets','identity Role listing Secrets'} +outside_grant={'identity Role listing Secrets','credential Role listing Secrets','Role listing payloads','Role reading Secrets','ClusterRole','ClusterRoleBinding to kro'} wrong=[n for n,v in record['admission'].items() if not v['admitted'] and v['deniedBy']!=('RBAC' if n in outside_grant else 'ValidatingAdmissionPolicy')] if wrong: raise SystemExit('a shape was refused by the wrong layer (%s): %s'%(', '.join(wrong),record['admission'])) +# With a real per-operation Role in place, kro may bind it only to that +# operation's worker, and cannot widen it later: updates pass the same policy. +# A probe Role left by an interrupted run is removed first. +call(s/'cell-admin.yaml','-n',ns,'delete','role','w-op-admission-probe','--ignore-not-found') +probe=role(own) +r=call(s/'cell-admin.yaml','create','--as',kro,'-f','-',input=json.dumps(probe)) +if r.returncode:raise SystemExit('kro could not create the widening probe Role: '+r.stderr[:300]) +try: + for name,rules in {'widened to every payload':[own[0],dict(own[1],resourceNames=[])],'widened to another operation':[own[0],dict(own[1],resourceNames=['op-other-operation-payload'])]}.items(): + r=call(s/'cell-admin.yaml','-n',ns,'patch','role','w-op-admission-probe','--as',kro,'--dry-run=server','--type=merge','-p',json.dumps({'rules':rules})) + if r.returncode==0 or 'ValidatingAdmissionPolicy' not in r.stderr: + raise SystemExit('kro widened its Role (%s): %s'%(name,(r.stdout+r.stderr)[:300])) + record['admission']['Role '+name]={'expected':'denied','admitted':False,'deniedBy':'ValidatingAdmissionPolicy'} + worker={'kind':'ServiceAccount','name':'w-op-admission-probe','namespace':site} + bindings={'admitted':{'RoleBinding to the operation\'s worker':subject(worker)}, + 'denied':{'RoleBinding to kro\'s own ServiceAccount':subject({'kind':'ServiceAccount','name':'kro','namespace':'kro-system'}), + 'RoleBinding to another operation\'s worker':subject(dict(worker,name='w-op-other-operation')), + 'RoleBinding to a user':subject({'kind':'User','apiGroup':'rbac.authorization.k8s.io','name':kro}), + 'RoleBinding to a group':subject({'kind':'Group','apiGroup':'rbac.authorization.k8s.io','name':'system:serviceaccounts'}), + 'RoleBinding to its worker and kro':subject(worker,{'kind':'ServiceAccount','name':'kro','namespace':'kro-system'}), + 'RoleBinding to a worker name in another namespace':subject(dict(worker,namespace='kro-system')), + # kro holds every permission of its own Role, so only the policy's + # own-Role rule refuses binding a worker to it. + 'RoleBinding of a worker to kro\'s own Role':dict(subject(worker),roleRef={'apiGroup':'rbac.authorization.k8s.io','kind':'Role','name':'fleet-site-kro-worker-rbac'})}} + for outcome,objs in bindings.items(): + for name,obj in objs.items(): + r=call(s/'cell-admin.yaml','create','--dry-run=server','--as',kro,'-f','-',input=json.dumps(obj)) + if (r.returncode==0)!=(outcome=='admitted') or (r.returncode and 'ValidatingAdmissionPolicy' not in r.stderr): + raise SystemExit('kro binding %s: %s'%(name,(r.stdout+r.stderr)[:300])) + record['admission'][name]={'expected':outcome,'admitted':r.returncode==0,'deniedBy':None if r.returncode==0 else 'ValidatingAdmissionPolicy'} +finally: + call(s/'cell-admin.yaml','-n',ns,'delete','role','w-op-admission-probe','--ignore-not-found') (s/'evidence'/'kro-rbac.json').write_text(json.dumps(record,indent=2,sort_keys=True)+'\n') print('Verified kro RBAC and admission confine it to per-operation objects: %d allowed, %d denied verbs; %d shapes admitted, %d denied by policy'%( len(allowed),len(denied),len(cases['admitted']),len(cases['denied']))) diff --git a/hack/standalone-smoke.sh b/hack/standalone-smoke.sh index 57546bce..256258f1 100755 --- a/hack/standalone-smoke.sh +++ b/hack/standalone-smoke.sh @@ -157,14 +157,14 @@ 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 +# simulated installer verified 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" +test "$(kubectl --context "$context" -n fleet-provider get deviceinstallation "$bootstrap_op" -o jsonpath='{.status.evidence.installerVerifiedBootstrap}')" = "$bootstrap_digest" # The coordinator deletes the sealed copy once the operation ended. payloads=1 for _ in $(seq 1 60); do diff --git a/internal/allocation/bootstrap_test.go b/internal/allocation/bootstrap_test.go index c540f139..193b2d8f 100644 --- a/internal/allocation/bootstrap_test.go +++ b/internal/allocation/bootstrap_test.go @@ -2,6 +2,7 @@ package allocation import ( "encoding/json" + "slices" "sync" "testing" @@ -86,6 +87,24 @@ func TestBootstrapReachesTheServerAndEveryCopyIsDeleted(t *testing.T) { t.Fatalf("retry = %v, %v; payloads %d, before %d", again.Spec.Bootstrap, err, e.payloads(), before) } + // A pass that delivers the active operation tells the site to keep its + // payload. A pass that fails to deliver any Device sweeps nothing. + _ = e.loop.Pass(e.ctx) + if kept, _ := e.site.lastSweep(); !slices.Contains(kept, operation.Name) { + t.Fatalf("the active operation's payload was not kept: %v", kept) + } + e.site.mu.Lock() + e.site.failDeliver = true + e.site.mu.Unlock() + _, sweeps := e.site.lastSweep() + _ = e.loop.Pass(e.ctx) + if _, after := e.site.lastSweep(); after != sweeps { + t.Fatal("a pass that failed to deliver swept payloads") + } + e.site.mu.Lock() + e.site.failDeliver = false + e.site.mu.Unlock() + e.until("the installation succeeds", func() bool { if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(operation), operation); err != nil { t.Fatal(err) @@ -100,12 +119,17 @@ func TestBootstrapReachesTheServerAndEveryCopyIsDeleted(t *testing.T) { 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 { + if err := json.Unmarshal(operation.Status.Evidence.Raw, &evidence); err != nil || evidence.InstallerVerifiedBootstrap != 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 }) + // Once the operation ended, the site is told to keep nothing for it. + _ = e.loop.Pass(e.ctx) + if kept, _ := e.site.lastSweep(); slices.Contains(kept, operation.Name) { + t.Fatalf("an ended operation's payload was kept: %v", kept) + } if records, err := e.store.Records("payload"); err != nil || len(records) != 0 { t.Fatalf("site payloads = %d, %v", len(records), err) } diff --git a/internal/allocation/harness_test.go b/internal/allocation/harness_test.go index 4064fae6..8b2db52b 100644 --- a/internal/allocation/harness_test.go +++ b/internal/allocation/harness_test.go @@ -2,10 +2,12 @@ package allocation import ( "context" + "errors" "fmt" "net/http/httptest" "os" "path/filepath" + "sync" "testing" "time" @@ -61,6 +63,7 @@ type env struct { store *site.Store runner *site.Runner enrollment fixture.Enrollment + site *sweepingSite class *fleetv1.MachineClass profile *fleetv1.MachineProfile projector *capacity.Projector @@ -132,7 +135,8 @@ func startEnvWith(t *testing.T, crds ...*apiextensionsv1.CustomResourceDefinitio if err != nil { t.Fatal(err) } - sites := &delivery.Sites{Sites: map[string]delivery.Site{siteName: remote}, Devices: map[string][]string{}} + e.site = &sweepingSite{Client: remote} + sites := &delivery.Sites{Sites: map[string]delivery.Site{siteName: e.site}, Devices: map[string][]string{}} coordinator := &custody.Coordinator{Client: admin, Registry: registry, Sites: sites, Config: custody.Config{Namespace: namespace, Principals: custody.Principals{ custody.CreatorMetalProvider: {{Username: providerUser}}, custody.CreatorReleaseController: {{Username: releaseUser}}, }}} @@ -289,6 +293,47 @@ func (e *env) release(allocation *fleetv1.MachineAllocation, owner Machine) { }) } +// sweepingSite is the simulator site's API, also keeping payloads the way +// the federation hub does, so a test sees what each coordinator pass tells +// a site to keep. failDeliver makes every delivery fail. +type sweepingSite struct { + *siteapi.Client + mu sync.Mutex + sweeps [][]string + failDeliver bool +} + +func (s *sweepingSite) Deliver(ctx context.Context, assignment site.Assignment, payload *site.Payload) error { + s.mu.Lock() + fail := s.failDeliver + s.mu.Unlock() + if fail { + return errors.New("delivery failed") + } + return s.Client.Deliver(ctx, assignment, payload) +} + +func (s *sweepingSite) SweepPayloads(_ context.Context, keep []site.Assignment) error { + s.mu.Lock() + defer s.mu.Unlock() + var names []string + for _, assignment := range keep { + names = append(names, assignment.Operation.Name) + } + s.sweeps = append(s.sweeps, names) + return nil +} + +// lastSweep returns the names the last sweep kept, and how many sweeps ran. +func (s *sweepingSite) lastSweep() ([]string, int) { + s.mu.Lock() + defer s.mu.Unlock() + if len(s.sweeps) == 0 { + return nil, 0 + } + return s.sweeps[len(s.sweeps)-1], len(s.sweeps) +} + // examplePolicy is the CleaningPolicy every fixture capacity names. func examplePolicy(namespace string) *ops.CleaningPolicy { return &ops.CleaningPolicy{ObjectMeta: metav1.ObjectMeta{Name: "example-cleaning", Namespace: namespace}, Spec: ops.CleaningPolicySpec{ diff --git a/internal/api/operations/v1alpha1/types.go b/internal/api/operations/v1alpha1/types.go index 40a38759..3723578c 100644 --- a/internal/api/operations/v1alpha1/types.go +++ b/internal/api/operations/v1alpha1/types.go @@ -461,10 +461,10 @@ type SealedPayloadSpec struct { // 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"` + // InstallerVerifiedBootstrap is the salted digest of the bootstrap data + // the installer read back from the target disk, never a hash of the data + // alone. Success rests on the installer's check, not on the installed OS. + InstallerVerifiedBootstrap string `json:"installerVerifiedBootstrap,omitempty"` } // StepEvidence records one journaled step. It never carries a BMC response. diff --git a/internal/coordination/cell.go b/internal/coordination/cell.go index 3ff14242..c4aabbec 100644 --- a/internal/coordination/cell.go +++ b/internal/coordination/cell.go @@ -2,10 +2,12 @@ package coordination import ( "context" + "encoding/base64" "encoding/json" "errors" "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/client-go/dynamic" @@ -23,6 +25,8 @@ var ErrNotDelivered = errors.New("coordination: the handoff is not an assignment // read only its own handoff; the observer is the only writer of handoff // status, and reports only what the site store holds. type Cell struct { + fixtureSeeds bool // Enabled only by in-package tests; never configurable by a deployment. + API dynamic.Interface Namespace string Name string @@ -53,6 +57,15 @@ func (c *Cell) assignment(object *unstructured.Unstructured) (site.Assignment, S if err := json.Unmarshal([]byte(spec.AssignmentJSON), &assignment); err != nil || assignment.Device != spec.Device || object.GetName() != AssignmentName(assignment) { return site.Assignment{}, spec, ErrNotDelivered } + // The handoff names a payload object exactly when the admitted inputs + // name a payload, and only under its derived name. + want := "" + if assignment.Sealed() != nil { + want = PayloadName(assignment) + } + if spec.Payload != want { + return site.Assignment{}, spec, ErrNotDelivered + } return assignment, spec, nil } @@ -68,13 +81,77 @@ func (c *Cell) Work(ctx context.Context, name string, runner *site.Runner) error if err != nil { return err } + if !c.fixtureSeeds && assignment.Sealed() != nil { + return ErrBootstrapUnsupported + } if assignment.Operation.Kind == "DeviceRecovery" { return runner.Fence(ctx, assignment) } + // Federation can deliver the handoff before the payload object. The + // worker exits to be retried, and stores no result, until it arrives. + if assignment.Sealed() != nil { + if runner.Payloads == nil { + return ErrNotDelivered + } + payload, err := runner.Payloads.Get(ctx, assignment) + if err != nil { + return err + } + if payload == nil { + return ErrPayloadPending + } + } _, err = runner.Run(ctx, assignment) return err } +// ErrPayloadPending means the assignment's payload object has not reached +// the cell yet. The worker sends nothing and is retried. +var ErrPayloadPending = errors.New("coordination: the bootstrap payload has not reached the cell") + +// HandoffPayloads reads an assignment's payload from the one +// MachineAllocationPayload federation delivered for it. The worker may get +// exactly that object, and may list, watch, change or delete none. The cell +// keeps the payload only until the coordinator answers the result: the hub +// then deletes its object, and federation deletes the cell's copy. So +// Delete and Prune have nothing a worker can do. +type HandoffPayloads struct { + API dynamic.Interface + Namespace string + Cell string +} + +var _ site.Payloads = HandoffPayloads{} + +func (s HandoffPayloads) Get(ctx context.Context, assignment site.Assignment) (*site.Payload, error) { + object, err := s.API.Resource(PayloadResource).Namespace(s.Namespace).Get(ctx, PayloadName(assignment), metav1.GetOptions{}) + if apierrors.IsNotFound(err) { + return nil, nil + } + if err != nil { + return nil, err + } + if cell, _, _ := unstructured.NestedString(object.Object, "spec", "cell"); cell != s.Cell || object.GetLabels()[CellLabel] != s.Cell || object.GetLabels()[RoleLabel] != RolePayload { + return nil, ErrNotDelivered + } + // A payload that does not decode was not delivered by the hub; the + // worker refuses the handoff rather than retry it. + encoded, _, _ := unstructured.NestedString(object.Object, "spec", "payload") + data, err := base64.StdEncoding.DecodeString(encoded) + if err != nil { + return nil, ErrNotDelivered + } + var payload site.Payload + if err := json.Unmarshal(data, &payload); err != nil { + return nil, ErrNotDelivered + } + return &payload, nil +} + +func (HandoffPayloads) Delete(context.Context, site.Assignment) error { return nil } + +func (HandoffPayloads) Prune(context.Context, string) error { return nil } + // declaration reads the delivery declaration for one pass, or nil. func (c *Cell) declaration() (*DeliveryDeclaration, error) { if c.Delivery == nil { diff --git a/internal/coordination/transport.go b/internal/coordination/transport.go index 93f7ef23..6e58a633 100644 --- a/internal/coordination/transport.go +++ b/internal/coordination/transport.go @@ -9,6 +9,7 @@ package coordination import ( "context" "crypto/sha256" + "encoding/base64" "encoding/hex" "encoding/json" "errors" @@ -36,6 +37,10 @@ const ( RoleLabel = "coordination.fleet.datumapis.com/role" RoleAssignment = "assignment" RoleReport = "report" + // RolePayload labels the MachineAllocationPayload that carries an + // assignment's bootstrap payload to its cell, beside the handoff and + // never inside it. + RolePayload = "payload" // AnsweredLabel marks an assignment whose result the coordinator // answered. The cell then deletes its copy of the result. AnsweredLabel = "coordination.fleet.datumapis.com/answered" @@ -57,6 +62,11 @@ type Spec struct { // AssignmentJSON is the exact assignment, as a string so an API server // cannot reorder it. A report handoff has none. AssignmentJSON string `json:"assignmentJSON,omitempty"` + // Payload is the name of the MachineAllocationPayload that carries the + // assignment's bootstrap payload, set exactly when the admitted inputs + // name one. The site grants the assignment's worker get on exactly that + // object. + Payload string `json:"payload,omitempty"` } // FenceReport is the cell's stored fences for the Device. @@ -108,6 +118,17 @@ func AssignmentName(assignment site.Assignment) string { return "op-" + digest(assignment.Device + "/" + assignment.Key())[:40] } +// PayloadName is the only name the object carrying an assignment's +// bootstrap payload may have. +func PayloadName(assignment site.Assignment) string { return AssignmentName(assignment) + "-payload" } + +// PayloadResource carries bootstrap payloads. It is its own kind, not a +// Secret, so permission on it reaches nothing else. +var PayloadResource = schema.GroupVersionResource{Group: Resource.Group, Version: Resource.Version, Resource: "machineallocationpayloads"} + +// PayloadKind is the kind of PayloadResource. +const PayloadKind = "MachineAllocationPayload" + // ReportName is the only name a Device's report handoff may have. func ReportName(device string) string { return "fence-" + digest(device)[:40] } @@ -157,6 +178,8 @@ func newObject(namespace, name, role string, spec Spec) *unstructured.Unstructur // delivery.Site. It writes handoffs and their answered label; it never // writes status. type Hub struct { + fixtureSeeds bool // Enabled only by in-package tests; never configurable by a deployment. + API dynamic.Interface Namespace string Cell string @@ -191,24 +214,93 @@ func (h *Hub) ensure(ctx context.Context, name, role string, spec Spec) (*unstru return object, nil } -// 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") +var ErrBootstrapUnsupported = errors.New("coordination: federated bootstrap delivery is disabled") + +func (h *Hub) CarriesPayloads() bool { return h.fixtureSeeds } +// Deliver writes the payload object, if the assignment's admitted inputs +// name one, and then the handoff that names it, so a cell never sees a +// handoff whose payload was never written. func (h *Hub) Deliver(ctx context.Context, assignment site.Assignment, payload *site.Payload) error { - if payload != nil || assignment.Sealed() != nil { + if !h.CarriesPayloads() && (payload != nil || assignment.Sealed() != nil) { return ErrBootstrapUnsupported } + spec := Spec{Cell: h.Cell, Device: assignment.Device} + if (payload != nil) != (assignment.Sealed() != nil) || (payload != nil && !payload.Matches(assignment.Sealed())) { + return ErrConflict + } + if payload != nil { + spec.Payload = PayloadName(assignment) + if err := h.ensurePayload(ctx, spec.Payload, *payload); err != nil { + return err + } + } data, err := json.Marshal(assignment) if err != nil { return err } - _, err = h.ensure(ctx, AssignmentName(assignment), RoleAssignment, Spec{Cell: h.Cell, Device: assignment.Device, AssignmentJSON: string(data)}) + spec.AssignmentJSON = string(data) + _, err = h.ensure(ctx, AssignmentName(assignment), RoleAssignment, spec) return err } +// SweepPayloads deletes every payload object of this cell that is not for +// one of the assignments to keep. Deleting the hub's copy deletes the +// cell's. A payload deleted just before its handoff is written is written +// again by the next delivery, and the worker waits for it. +func (h *Hub) SweepPayloads(ctx context.Context, keep []site.Assignment) error { + names := map[string]bool{} + for _, assignment := range keep { + names[PayloadName(assignment)] = true + } + list, err := h.payloads().List(ctx, metav1.ListOptions{LabelSelector: CellLabel + "=" + h.Cell + "," + RoleLabel + "=" + RolePayload}) + if err != nil { + return err + } + var failed error + for _, object := range list.Items { + if names[object.GetName()] { + continue + } + uid := object.GetUID() + if err := h.payloads().Delete(ctx, object.GetName(), metav1.DeleteOptions{Preconditions: &metav1.Preconditions{UID: &uid}}); err != nil && !apierrors.IsNotFound(err) { + failed = errors.Join(failed, err) + } + } + return failed +} + +func (h *Hub) payloads() dynamic.ResourceInterface { + return h.API.Resource(PayloadResource).Namespace(h.Namespace) +} + +// ensurePayload creates the payload object, or requires the existing one to +// hold the same payload. +func (h *Hub) ensurePayload(ctx context.Context, name string, payload site.Payload) error { + data, err := json.Marshal(payload) + if err != nil { + return err + } + object := &unstructured.Unstructured{Object: map[string]any{ + "apiVersion": PayloadResource.GroupVersion().String(), "kind": PayloadKind, + "metadata": map[string]any{"name": name, "namespace": h.Namespace, "labels": map[string]any{CellLabel: h.Cell, RoleLabel: RolePayload}}, + "spec": map[string]any{"cell": h.Cell, "payload": base64.StdEncoding.EncodeToString(data)}, + }} + existing, err := h.payloads().Create(ctx, object, metav1.CreateOptions{}) + if apierrors.IsAlreadyExists(err) { + existing, err = h.payloads().Get(ctx, name, metav1.GetOptions{}) + } + if err != nil { + return err + } + stored, _, _ := unstructured.NestedString(existing.Object, "spec", "payload") + cell, _, _ := unstructured.NestedString(existing.Object, "spec", "cell") + if stored != base64.StdEncoding.EncodeToString(data) || cell != h.Cell || existing.GetLabels()[CellLabel] != h.Cell || existing.GetLabels()[RoleLabel] != RolePayload { + return ErrConflict + } + return nil +} + // reflected returns the one valid observation of this cell. func (h *Hub) reflected(object *unstructured.Unstructured) (Spec, Observation, error) { var status HubStatus @@ -292,9 +384,16 @@ func namespaceOf(device string) string { return "" } -// Forget marks the assignment answered, so the cell deletes its copy. +// Forget deletes the assignment's payload object, which removes the cell's +// copy too, and then marks the assignment answered, so the cell deletes its +// copy of the result. A crash between the two deletes the Secret again on +// the retry. func (h *Hub) Forget(ctx context.Context, stored site.Stored) error { - name := AssignmentName(site.Assignment{Device: stored.Device, Operation: stored.Result.Operation, Fence: stored.Result.Fence}) + assignment := site.Assignment{Device: stored.Device, Operation: stored.Result.Operation, Fence: stored.Result.Fence} + name := AssignmentName(assignment) + if err := h.payloads().Delete(ctx, PayloadName(assignment), metav1.DeleteOptions{}); err != nil && !apierrors.IsNotFound(err) { + return err + } patch := []byte(`{"metadata":{"labels":{"` + AnsweredLabel + `":"true"}}}`) _, err := h.api().Patch(ctx, name, types.MergePatchType, patch, metav1.PatchOptions{}) if apierrors.IsNotFound(err) { diff --git a/internal/coordination/transport_test.go b/internal/coordination/transport_test.go index e2519e81..d1778153 100644 --- a/internal/coordination/transport_test.go +++ b/internal/coordination/transport_test.go @@ -2,6 +2,8 @@ package coordination import ( "context" + "crypto/sha256" + "encoding/hex" "encoding/json" "errors" "fmt" @@ -17,6 +19,7 @@ import ( k8sschema "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/client-go/dynamic" "k8s.io/client-go/dynamic/fake" + k8stesting "k8s.io/client-go/testing" ops "go.datum.net/fleet/internal/api/operations/v1alpha1" "go.datum.net/fleet/internal/custody" @@ -33,7 +36,7 @@ const ( ) func client() dynamic.Interface { - return fake.NewSimpleDynamicClientWithCustomListKinds(runtime.NewScheme(), map[k8sschema.GroupVersionResource]string{Resource: Kind + "List"}) + return fake.NewSimpleDynamicClientWithCustomListKinds(runtime.NewScheme(), map[k8sschema.GroupVersionResource]string{Resource: Kind + "List", PayloadResource: PayloadKind + "List"}) } // federation copies hub handoffs to the cell and aggregates cell status @@ -75,6 +78,40 @@ func (f federation) sync() { } } +// syncPayloads mirrors the hub's payload objects to the cell, creating +// those it lacks and deleting those the hub deleted, as Karmada's +// propagation does. +func (f federation) syncPayloads() { + f.t.Helper() + ctx := context.Background() + hub, cell := f.hub.Resource(PayloadResource).Namespace(namespace), f.cell.Resource(PayloadResource).Namespace(namespace) + list, err := hub.List(ctx, metav1.ListOptions{LabelSelector: RoleLabel + "=" + RolePayload + "," + CellLabel + "=" + f.clusterFor}) + if err != nil { + f.t.Fatal(err) + } + keep := map[string]bool{} + for index := range list.Items { + object := list.Items[index] + keep[object.GetName()] = true + if _, err := cell.Get(ctx, object.GetName(), metav1.GetOptions{}); err == nil { + continue + } + copied := &unstructured.Unstructured{Object: map[string]any{"apiVersion": object.GetAPIVersion(), "kind": PayloadKind, "metadata": map[string]any{"name": object.GetName(), "namespace": namespace, "labels": toAny(object.GetLabels())}, "spec": object.Object["spec"]}} + if _, err := cell.Create(ctx, copied, metav1.CreateOptions{}); err != nil { + f.t.Fatal(err) + } + } + existing, err := cell.List(ctx, metav1.ListOptions{}) + if err != nil { + f.t.Fatal(err) + } + for _, object := range existing.Items { + if !keep[object.GetName()] { + _ = cell.Delete(ctx, object.GetName(), metav1.DeleteOptions{}) + } + } +} + func toAny(labels map[string]string) map[string]any { out := map[string]any{} for key, value := range labels { @@ -110,8 +147,8 @@ func newFixture(t *testing.T) *rig { results := site.NewResults(store) return &rig{ t: t, ctx: context.Background(), store: store, results: results, snapshot: snapshot, - hub: &Hub{API: hubAPI, Namespace: namespace, Cell: cellName, MaxAge: time.Minute}, - cell: &Cell{API: cellAPI, Namespace: namespace, Name: cellName}, + hub: &Hub{fixtureSeeds: true, API: hubAPI, Namespace: namespace, Cell: cellName, MaxAge: time.Minute}, + cell: &Cell{fixtureSeeds: true, API: cellAPI, Namespace: namespace, Name: cellName}, fed: federation{t: t, hub: hubAPI, cell: cellAPI, clusterFor: cellName}, runner: &site.Runner{Site: cellName, Store: store, Results: results, Access: fixture.Access{Enrollment: enrollment}, Kinds: map[string]site.Kind{"DeviceWipe": simwork.Wipe{}}, Poll: 10 * time.Millisecond}, } @@ -297,21 +334,247 @@ 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) { +// sealedWipe is a wipe assignment whose admitted inputs name a sealed +// payload, and the payload. +func (f *rig) sealedWipe(fence int64, uid string) (site.Assignment, site.Payload) { + assignment := f.wipe(fence, uid) + salt := make([]byte, 32) + data := []byte(`{"userData":"#cloud-config\n"}`) + hash := sha256.New() + hash.Write(salt) + hash.Write(data) + payload := site.Payload{Ref: "sealed-example", Digest: "sha256:" + hex.EncodeToString(hash.Sum(nil)), Salt: salt, Data: data} + var inputs map[string]any + _ = json.Unmarshal(assignment.Inputs, &inputs) + inputs["bootstrap"] = map[string]string{"ref": payload.Ref, "digest": payload.Digest} + assignment.Inputs, _ = json.Marshal(inputs) + sum := sha256.Sum256(assignment.Inputs) + assignment.InputDigest = "sha256:" + hex.EncodeToString(sum[:]) + return assignment, payload +} + +func TestFederationRefusesSeedsBeforeAnyWrite(t *testing.T) { + fixture := newFixture(t) + assignment, payload := fixture.sealedWipe(2, "00000000-0000-4000-8000-000000000121") + hub := &Hub{API: fixture.fed.hub, Namespace: namespace, Cell: cellName} + if hub.CarriesPayloads() { + t.Fatal("ordinary federation advertises seed transport") + } + for _, candidate := range []*site.Payload{nil, &payload} { + if err := hub.Deliver(fixture.ctx, assignment, candidate); !errors.Is(err, ErrBootstrapUnsupported) { + t.Fatalf("deliver: %v", err) + } + } + if len(fixture.fed.hub.(*fake.FakeDynamicClient).Actions()) != 0 { + t.Fatal("refusal touched the hub API") + } +} + +// TestFederationCarriesAPayloadBesideItsHandoff: the hub writes the payload +// object before the handoff that names it; a worker that runs before the +// object reaches the cell stores nothing and is retried; the worker reads +// it; and answering the result deletes the hub's copy and so the cell's. +func TestFederationCarriesAPayloadBesideItsHandoff(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) { + payloads := HandoffPayloads{API: f.cell.API, Namespace: namespace, Cell: cellName} + f.runner.Payloads = payloads + assignment, payload := f.sealedWipe(3, "00000000-0000-4000-8000-000000000121") + if err := f.hub.Deliver(f.ctx, assignment, nil); !errors.Is(err, ErrConflict) { + t.Fatalf("an assignment naming a payload was delivered without it: %v", err) + } + altered := payload + altered.Data = []byte(`{"userData":"other"}`) + if err := f.hub.Deliver(f.ctx, assignment, &altered); !errors.Is(err, ErrConflict) { + t.Fatalf("an altered payload was delivered: %v", err) + } + if err := f.hub.Deliver(f.ctx, assignment, &payload); err != nil { + t.Fatal(err) + } + if err := f.hub.Deliver(f.ctx, assignment, &payload); err != nil { + t.Fatalf("redelivery: %v", err) + } + handoff, err := f.hub.api().Get(f.ctx, AssignmentName(assignment), metav1.GetOptions{}) + if err != nil { + t.Fatal(err) + } + if spec, _ := decode(handoff, nil); spec.Payload != PayloadName(assignment) || strings.Contains(spec.AssignmentJSON, string(payload.Data)) { + t.Fatalf("handoff spec = %+v", spec) + } + // The handoff arrives first: the worker sends nothing and stores + // nothing. + f.fed.sync() + if err := f.cell.Work(f.ctx, AssignmentName(assignment), f.runner); !errors.Is(err, ErrPayloadPending) { 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 _, found, _ := f.results.Get(device, assignment.Operation, assignment.Fence); found { + t.Fatal("a result was stored without the payload") + } + f.fed.syncPayloads() + if err := f.cell.Work(f.ctx, AssignmentName(assignment), f.runner); err != nil { + t.Fatal(err) + } + f.observe() + f.fed.sync() + held, err := f.hub.Results(f.ctx) + if err != nil || len(held) != 1 { + t.Fatalf("results = %+v, %v", held, err) + } + if err := f.hub.Forget(f.ctx, held[0]); err != nil { + t.Fatal(err) + } + if _, err := f.hub.payloads().Get(f.ctx, PayloadName(assignment), metav1.GetOptions{}); !apierrors.IsNotFound(err) { + t.Fatalf("the hub kept the payload: %v", err) + } + f.fed.syncPayloads() + if got, err := payloads.Get(f.ctx, assignment); err != nil || got != nil { + t.Fatalf("the cell kept its copy: %v, %v", got, err) + } +} + +// TestACellRefusesAHandoffNamingAnotherPayload: the worker would be granted +// get on whatever payload the handoff names. +func TestACellRefusesAHandoffNamingAnotherPayload(t *testing.T) { + f := newFixture(t) + assignment, _ := f.sealedWipe(3, "00000000-0000-4000-8000-000000000131") + data, _ := json.Marshal(assignment) + for name, spec := range map[string]Spec{ + "another operation": {Cell: cellName, Device: device, AssignmentJSON: string(data), Payload: PayloadName(f.wipe(4, "00000000-0000-4000-8000-000000000132"))}, + "another object": {Cell: cellName, Device: device, AssignmentJSON: string(data), Payload: "bmc-0123456789abcdef0123"}, + "no payload": {Cell: cellName, Device: device, AssignmentJSON: string(data)}, + } { + t.Run(name, func(t *testing.T) { + f := newFixture(t) + if _, err := f.cell.api().Create(f.ctx, newObject(namespace, AssignmentName(assignment), RoleAssignment, spec), metav1.CreateOptions{}); err != nil { + t.Fatal(err) + } + if err := f.cell.Work(f.ctx, AssignmentName(assignment), f.runner); !errors.Is(err, ErrNotDelivered) { + t.Fatalf("err = %v", err) + } + }) + } +} + +// TestTheHubSweepsPayloadsNoOperationNeeds deletes every payload of its +// cell not in the keep set: an operation that ended without an answered +// result, or a payload written before a crash left it without a handoff. +// It keeps the payloads still needed and touches no other cell's. +func TestTheHubSweepsPayloadsNoOperationNeeds(t *testing.T) { + f := newFixture(t) + kept, keptPayload := f.sealedWipe(3, "00000000-0000-4000-8000-000000000141") + ended, endedPayload := f.sealedWipe(4, "00000000-0000-4000-8000-000000000142") + for _, pair := range []struct { + a site.Assignment + p site.Payload + }{{kept, keptPayload}, {ended, endedPayload}} { + if err := f.hub.Deliver(f.ctx, pair.a, &pair.p); err != nil { + t.Fatal(err) + } + } + other := &Hub{fixtureSeeds: true, API: f.hub.API, Namespace: namespace, Cell: "cell-example-b", MaxAge: time.Minute} + foreign, foreignPayload := f.sealedWipe(5, "00000000-0000-4000-8000-000000000143") + if err := other.Deliver(f.ctx, foreign, &foreignPayload); err != nil { + t.Fatal(err) + } + if err := f.hub.SweepPayloads(f.ctx, []site.Assignment{kept}); err != nil { + t.Fatal(err) + } + exists := func(a site.Assignment) bool { + _, err := f.hub.payloads().Get(f.ctx, PayloadName(a), metav1.GetOptions{}) + return err == nil + } + if !exists(kept) || exists(ended) || !exists(foreign) { + t.Fatalf("kept %v, ended %v, other cell %v", exists(kept), exists(ended), exists(foreign)) + } + // The next delivery writes a swept payload again, so a sweep racing a + // delivery leaves the worker waiting, not failed. + if err := f.hub.Deliver(f.ctx, ended, &endedPayload); err != nil || !exists(ended) { + t.Fatalf("redelivery after a sweep: %v", err) + } +} + +// TestOnlyAMissingPayloadIsPending: a worker retries only while the payload +// has not arrived. A read it may not make is an error, and a payload that +// does not decode, or names another cell, refuses the handoff. +func TestOnlyAMissingPayloadIsPending(t *testing.T) { + assignment, payload := newFixture(t).sealedWipe(3, "00000000-0000-4000-8000-000000000151") + cases := map[string]struct { + mutate func(f *rig) + want error + }{ + "a payload that does not decode": {func(f *rig) { + object, _ := f.cell.API.Resource(PayloadResource).Namespace(namespace).Get(f.ctx, PayloadName(assignment), metav1.GetOptions{}) + _ = unstructured.SetNestedField(object.Object, "not base64!", "spec", "payload") + _, _ = f.cell.API.Resource(PayloadResource).Namespace(namespace).Update(f.ctx, object, metav1.UpdateOptions{}) + }, ErrNotDelivered}, + "a payload for another cell": {func(f *rig) { + object, _ := f.cell.API.Resource(PayloadResource).Namespace(namespace).Get(f.ctx, PayloadName(assignment), metav1.GetOptions{}) + _ = unstructured.SetNestedField(object.Object, "cell-example-b", "spec", "cell") + _, _ = f.cell.API.Resource(PayloadResource).Namespace(namespace).Update(f.ctx, object, metav1.UpdateOptions{}) + }, ErrNotDelivered}, + } + for name, test := range cases { + t.Run(name, func(t *testing.T) { + f := newFixture(t) + f.runner.Payloads = HandoffPayloads{API: f.cell.API, Namespace: namespace, Cell: cellName} + if err := f.hub.Deliver(f.ctx, assignment, &payload); err != nil { + t.Fatal(err) + } + f.fed.sync() + f.fed.syncPayloads() + test.mutate(f) + if err := f.cell.Work(f.ctx, AssignmentName(assignment), f.runner); !errors.Is(err, test.want) { + t.Fatalf("err = %v, want %v", err, test.want) + } + }) + } + t.Run("a read the worker may not make", func(t *testing.T) { + f := newFixture(t) + f.runner.Payloads = failingPayloads{errors.New("forbidden")} + if err := f.hub.Deliver(f.ctx, assignment, &payload); err != nil { + t.Fatal(err) + } + f.fed.sync() + if err := f.cell.Work(f.ctx, AssignmentName(assignment), f.runner); err == nil || errors.Is(err, ErrPayloadPending) { + t.Fatalf("err = %v, want the read error", err) + } + }) +} + +type failingPayloads struct{ err error } + +func (p failingPayloads) Get(context.Context, site.Assignment) (*site.Payload, error) { + return nil, p.err +} +func (failingPayloads) Delete(context.Context, site.Assignment) error { return nil } +func (failingPayloads) Prune(context.Context, string) error { return nil } + +// TestASweepDeletesOnlyThePayloadItListed: each delete carries the UID the +// sweep listed, so a payload replaced since the list is never removed. +func TestASweepDeletesOnlyThePayloadItListed(t *testing.T) { + f := newFixture(t) + ended, payload := f.sealedWipe(4, "00000000-0000-4000-8000-000000000161") + if err := f.hub.Deliver(f.ctx, ended, &payload); err != nil { + t.Fatal(err) + } + listed, err := f.hub.payloads().Get(f.ctx, PayloadName(ended), metav1.GetOptions{}) + if err != nil { + t.Fatal(err) + } + // The fake API server assigns no UIDs; this one does. + listed.SetUID("payload-uid-1") + if listed, err = f.hub.payloads().Update(f.ctx, listed, metav1.UpdateOptions{}); err != nil || listed.GetUID() == "" { + t.Fatalf("set UID: %v", err) + } + var preconditions []*metav1.Preconditions + f.hub.API.(*fake.FakeDynamicClient).PrependReactor("delete", "machineallocationpayloads", func(action k8stesting.Action) (bool, runtime.Object, error) { + preconditions = append(preconditions, action.(k8stesting.DeleteActionImpl).GetDeleteOptions().Preconditions) + return false, nil, nil + }) + if err := f.hub.SweepPayloads(f.ctx, nil); err != nil { + t.Fatal(err) } - if _, ok := any(f.hub).(interface{ CarriesPayloads() bool }); ok { - t.Fatal("the hub claims to carry payloads") + if len(preconditions) != 1 || preconditions[0] == nil || preconditions[0].UID == nil || *preconditions[0].UID != listed.GetUID() { + t.Fatalf("delete preconditions = %+v, want the listed UID %s", preconditions, listed.GetUID()) } } diff --git a/internal/custody/bootstrap_evidence_test.go b/internal/custody/bootstrap_evidence_test.go index d7317e23..7322a411 100644 --- a/internal/custody/bootstrap_evidence_test.go +++ b/internal/custody/bootstrap_evidence_test.go @@ -21,11 +21,11 @@ func TestInstallEvidenceMustProveTheAdmittedBootstrap(t *testing.T) { evidence string ok bool }{ - {"the admitted digest", with, `{"steps":[{"name":"disk","completedAt":"2026-11-25T00:00:00Z"}],"bootstrap":"` + digest + `"}`, true}, + {"the admitted digest", with, `{"steps":[{"name":"disk","completedAt":"2026-11-25T00:00:00Z"}],"installerVerifiedBootstrap":"` + 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}, + {"another digest", with, `{"installerVerifiedBootstrap":"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}, + {"none admitted, some handed", without, `{"installerVerifiedBootstrap":"` + digest + `"}`, false}, } { t.Run(test.name, func(t *testing.T) { _, err := evidence(test.operation, []byte(test.evidence)) diff --git a/internal/custody/kinds.go b/internal/custody/kinds.go index af44ac5a..a0737ed8 100644 --- a/internal/custody/kinds.go +++ b/internal/custody/kinds.go @@ -188,6 +188,9 @@ 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 installation.Spec.Delivery.Method == ops.DeliveryVirtualMedia { + return refuse(ReasonBootstrapUnsupported, "virtual media cannot deliver the admitted customer seed") + } if carriers, ok := admission.Sites.(PayloadCarriers); ok && !carriers.CarriesPayloads(admission.Device) { return refuse(ReasonBootstrapUnsupported, "a site serving the Device cannot receive bootstrap data") } @@ -218,14 +221,14 @@ func DeviceInstallationKind() Kind { Settles: []SettleRule{{Held: "DeviceInstallation"}}, Reasons: append(append(append([]Reason{{Name: ReasonBootstrapUnavailable, RaisedBy: RaisedByCoordinator}, {Name: ReasonImageIncompatible, RaisedBy: RaisedByWorker}, {Name: ReasonBootstrapUnsupported, RaisedBy: RaisedByBoth}}, networkBootReasons...), workerReasons...), deliveryReasons...), Evidence: StrictEvidence(evidenceLimit, func(operation ops.Operation, evidence *ops.InstallationEvidence) error { - // A success must prove the server was handed exactly the admitted - // bootstrap data, and nothing when there was none. + // A success must prove the installer verified exactly the admitted + // bootstrap data on the target disk, 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") + if evidence.InstallerVerifiedBootstrap != want { + return errors.New("the evidence does not prove the installer verified the admitted bootstrap data on disk") } return validateSteps(evidence.Steps) }), diff --git a/internal/delivery/delivery.go b/internal/delivery/delivery.go index 4a5a7e2b..fc1427ec 100644 --- a/internal/delivery/delivery.go +++ b/internal/delivery/delivery.go @@ -75,6 +75,13 @@ func (s *Sites) Serving(device *inventory.Device) []string { return out } +// PayloadSweeper is implemented by a site that keeps delivered payloads +// itself, such as the federation hub. SweepPayloads deletes every payload +// it holds that is not for one of the assignments to keep. +type PayloadSweeper interface { + SweepPayloads(ctx context.Context, keep []site.Assignment) error +} + // 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 { @@ -142,6 +149,11 @@ type Courier struct { Coordinator *custody.Coordinator Sites *Sites Namespace string + // delivered are this pass's delivered assignments that carry a + // payload, and complete says every Device was reconciled and delivered + // without error, so the rest of the sites' payloads are not needed. + delivered []site.Assignment + complete bool } // Deliver sends a Device's active operation to every site serving it, once @@ -179,6 +191,9 @@ func (c *Courier) Deliver(ctx context.Context, name string) error { if err != nil { return err } + if payload != nil { + c.delivered = append(c.delivered, assignment) + } device := &inventory.Device{} if err := c.Client.Get(ctx, client.ObjectKey{Namespace: c.Namespace, Name: name}, device); err != nil { return err @@ -211,6 +226,27 @@ func (c *Courier) payload(ctx context.Context, assignment site.Assignment) (*sit return payload, nil } +// SweepPayloads tells every site that keeps payloads which assignments +// still need one: the active operations delivered in this pass. It does +// nothing after a pass that failed to reconcile or deliver any Device, so +// a payload an active operation needs is never deleted. A payload whose +// operation ended, was cancelled or superseded, or never got a handoff, is +// deleted, whether or not its result was collected. +func (c *Courier) SweepPayloads(ctx context.Context) error { + if !c.complete { + return nil + } + var failed error + for name, remote := range c.Sites.Sites { + if sweeper, ok := remote.(PayloadSweeper); ok { + if err := sweeper.SweepPayloads(ctx, c.delivered); err != nil { + failed = errors.Join(failed, fmt.Errorf("sweep payloads at %s: %w", name, err)) + } + } + } + return failed +} + // 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 { @@ -290,18 +326,24 @@ func (l *Loop) Pass(ctx context.Context) error { } slices.Sort(sorted) var failed error + l.Courier.delivered, l.Courier.complete = nil, true for _, name := range sorted { if err := l.Settle(ctx, name); err != nil { failed = errors.Join(failed, fmt.Errorf("%s: %w", name, err)) + l.Courier.complete = false continue } if err := l.Courier.Deliver(ctx, name); err != nil { failed = errors.Join(failed, fmt.Errorf("%s: %w", name, err)) + l.Courier.complete = false } } if err := l.Courier.Collect(ctx); err != nil { failed = errors.Join(failed, err) } + if err := l.Courier.SweepPayloads(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 { diff --git a/internal/delivery/delivery_test.go b/internal/delivery/delivery_test.go index 6d0e1a79..18598c0c 100644 --- a/internal/delivery/delivery_test.go +++ b/internal/delivery/delivery_test.go @@ -99,6 +99,32 @@ func TestADeviceCarriesPayloadsOnlyIfEverySiteServingItDoes(t *testing.T) { var _ custody.PayloadCarriers = (*Sites)(nil) } +type sweeping struct { + siteWith + kept *[][]site.Assignment +} + +func (s sweeping) SweepPayloads(_ context.Context, keep []site.Assignment) error { + *s.kept = append(*s.kept, keep) + return nil +} + +// TestPayloadsAreSweptOnlyAfterACompletePass never tells a site to drop +// payloads after a pass that could not reconcile or deliver every Device, +// because it would drop one an active operation needs. +func TestPayloadsAreSweptOnlyAfterACompletePass(t *testing.T) { + var kept [][]site.Assignment + delivered := []site.Assignment{{Operation: ops.OperationReference{Kind: "DeviceInstallation", Name: "op-active"}}} + c := &Courier{Sites: &Sites{Sites: map[string]Site{"a": sweeping{kept: &kept}}}, delivered: delivered} + if err := c.SweepPayloads(context.Background()); err != nil || len(kept) != 0 { + t.Fatalf("swept after an incomplete pass: %v, %v", kept, err) + } + c.complete = true + if err := c.SweepPayloads(context.Background()); err != nil || len(kept) != 1 || len(kept[0]) != 1 || kept[0][0].Operation.Name != "op-active" { + t.Fatalf("kept = %v, %v", kept, err) + } +} + // 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/site/payload.go b/internal/site/payload.go index a010feb2..abdf4e15 100644 --- a/internal/site/payload.go +++ b/internal/site/payload.go @@ -88,11 +88,33 @@ func (r *Runner) payload(ctx context.Context, assignment Assignment) (*Payload, return payload, nil } -// dropPayload deletes the assignment's payload once nothing can need it. +// Scrubber is implemented by a kind that keeps copies of a payload in its +// own site records, such as a boot admission's seed. Scrub removes every +// such copy for the Device's operations below the fence. The site calls it +// when an assignment's result is stored or it is passed, with the fence +// just above it, and whenever it raises the Device's fence. +type Scrubber interface { + Scrub(store *Store, device string, below int64) error +} + +// dropPayload deletes the assignment's payload, and every kind's copy of +// it, 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) } + r.scrub(assignment.Device, assignment.Fence+1) +} + +// scrub asks every kind to remove its payload copies below the fence. +func (r *Runner) scrub(device string, below int64) error { + var failed error + for _, kind := range r.Kinds { + if scrubber, ok := kind.(Scrubber); ok { + failed = errors.Join(failed, scrubber.Scrub(r.Store, device, below)) + } + } + return failed } const payloadRecords = "payload" diff --git a/internal/site/redfishwork/boot.go b/internal/site/redfishwork/boot.go index cd48d73c..145c7b3d 100644 --- a/internal/site/redfishwork/boot.go +++ b/internal/site/redfishwork/boot.go @@ -27,6 +27,8 @@ const chainScript = "#!ipxe\nchain %s/pxe/${net0/mac:hexhyp}/boot.ipxe\n" // BootServer serves network boots from the site store's admissions. type BootServer struct { + fixtureSeeds bool // Enabled only by in-package tests; never configurable by a deployment. + Store *site.Store // Origin is the boot server's URL as firmware reaches it. Origin string @@ -110,7 +112,7 @@ func (b BootServer) Handler() http.Handler { boot, name = found, "boot.ipxe" } else { found, open := b.open(parts[1], parts[2]) - if !open || (parts[3] != "kernel" && parts[3] != "installer.gz") { + if !open || (parts[3] != "kernel" && parts[3] != "installer.gz" && (parts[3] != "seed.cpio" || !b.fixtureSeeds || len(found.Seed) == 0)) { deny() return } @@ -125,7 +127,16 @@ func (b BootServer) Handler() http.Handler { if boot.DurationSeconds > 0 { args = " fleet.duration=" + strconv.FormatInt(boot.DurationSeconds, 10) } - data = []byte(fmt.Sprintf("#!ipxe\nkernel %s/kernel console=ttyS0 rdinit=/init fleet.receipt=%s fleet.mode=%s%s\ninitrd %s/installer.gz\nboot\n", base, boot.Receipt, boot.Mode, args, base)) + seed := "" + if b.fixtureSeeds && len(boot.Seed) > 0 { + seed = "initrd " + base + "/seed.cpio\n" + } + data = []byte(fmt.Sprintf("#!ipxe\nkernel %s/kernel console=ttyS0 rdinit=/init fleet.receipt=%s fleet.mode=%s%s\ninitrd %s/installer.gz\n%sboot\n", base, boot.Receipt, boot.Mode, args, base, seed)) + size = int64(len(data)) + } else if name == "seed.cpio" { + // The operation's bootstrap seed, only while its admission is + // open; it is never written to the delivery evidence. + data = boot.Seed size = int64(len(data)) } else { // Hash the pinned artifact, then serve the same open file. @@ -229,7 +240,7 @@ func (b BootServer) CheckClosedBoot(origin string, extraMACs []string) (string, return "", fmt.Errorf("a boot admission is not closed") } base := origin + "/" + Key(boot.Operation) + "/" + boot.Token - for _, url := range []string{origin + "/pxe/" + strings.ReplaceAll(boot.MAC, ":", "-") + "/boot.ipxe", base + "/kernel", base + "/installer.gz", base + "/disk.raw", base + "/boot.ipxe"} { + for _, url := range []string{origin + "/pxe/" + strings.ReplaceAll(boot.MAC, ":", "-") + "/boot.ipxe", base + "/kernel", base + "/installer.gz", base + "/seed.cpio", base + "/disk.raw", base + "/boot.ipxe"} { if err := probe(url); err != nil { return "", err } diff --git a/internal/site/redfishwork/kinds.go b/internal/site/redfishwork/kinds.go index 4d899490..c53bf9a3 100644 --- a/internal/site/redfishwork/kinds.go +++ b/internal/site/redfishwork/kinds.go @@ -54,6 +54,8 @@ var ( // Config is what both kinds read at the site. type Config struct { + fixtureSeeds bool // Enabled only by in-package tests; never configurable by a deployment. + // ConsoleRoot holds each target's serial console capture. ConsoleRoot string // BootRoot holds the boot server's per-operation delivery evidence. @@ -149,8 +151,8 @@ func (k Installation) Check(ctx context.Context, work *site.Work) *custody.Refus if err := json.Unmarshal(work.Inputs, &spec); err != nil { 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: "this site cannot yet hand bootstrap data to the server"} + if spec.Bootstrap != nil && !k.fixtureSeeds { + return &custody.Refusal{Reason: custody.ReasonBootstrapUnsupported, Message: "federated customer seeds are disabled"} } // Firmware settings can change after allocation: read the mode the // server boots in now. @@ -204,6 +206,9 @@ func (m networkBoot) install(ctx context.Context, work *site.Work, _ ops.DeviceI type virtualMedia struct{ Config } func (m virtualMedia) check(ctx context.Context, work *site.Work, spec ops.DeviceInstallationSpec) *custody.Refusal { + if spec.Bootstrap != nil { + return &custody.Refusal{Reason: custody.ReasonBootstrapUnsupported, Message: "virtual media cannot deliver the admitted customer seed"} + } return m.checkMedia(ctx, work, spec) } @@ -321,7 +326,11 @@ func (k Installation) Run(ctx context.Context, work *site.Work) (any, error) { if err != nil { return nil, err } - return ops.InstallationEvidence{Steps: steps}, nil + evidence := ops.InstallationEvidence{Steps: steps} + if payload := work.Bootstrap(); payload != nil { + evidence.InstallerVerifiedBootstrap = payload.Digest + } + return evidence, nil } func (k Wipe) Run(ctx context.Context, work *site.Work) (any, error) { @@ -365,10 +374,35 @@ type Boot struct { // Phase is the network-booting phase, set while it may boot. Phase string `json:"phase,omitempty"` Closed bool `json:"closed,omitempty"` + // Seed is the operation's bootstrap seed archive, served only while the + // admission is open and dropped when it closes. + Seed []byte `json:"seed,omitempty"` } const bootRecords = "boot" +var _ site.Scrubber = Installation{} + +// Scrub drops the seed from every boot admission of the Device below the +// fence, however its install ended. +func (Installation) Scrub(store *site.Store, device string, below int64) error { + records, err := store.Records(bootRecords) + if err != nil { + return err + } + for _, record := range records { + var boot Boot + if record.Device != device || json.Unmarshal(record.Data, &boot) != nil || boot.Fence >= below || len(boot.Seed) == 0 { + continue + } + boot.Seed = nil + if err := store.RewriteRecord(device, bootRecords, record.Name, boot); err != nil { + return err + } + } + return nil +} + // boot reads the operation's boot admission, creating it once. The receipt is // fixed before any boot, so a replay waits for the same receipt. func (c Config) boot(ctx context.Context, work *site.Work, mode string) (Boot, error) { @@ -388,6 +422,11 @@ func (c Config) boot(ctx context.Context, work *site.Work, mode string) (Boot, e _, _, _, window := c.durations() mac, _ := bootnet.NormalizeMAC(work.Snapshot.BootMACAddress) boot = Boot{Operation: work.Key(), Fence: work.Fence, Mode: mode, MAC: mac, Address: bootAddress(work), Receipt: hex.EncodeToString(receipt), Token: hex.EncodeToString(token), Created: c.now().UTC(), Expires: c.now().Add(window).UTC()} + if payload := work.Bootstrap(); payload != nil && mode == "install" { + if boot.Seed, err = site.SeedArchive(payload, "fleet-"+Key(work.Key())); err != nil { + return boot, err + } + } if boot.Address != "" { // Publishing the reservation is an effect: from here on the // operation can no longer end Failed, so its boot address is kept @@ -399,6 +438,8 @@ func (c Config) boot(ctx context.Context, work *site.Work, mode string) (Boot, e return boot, store.PutRecord(work.Device, work.Fence, bootRecords, work.Key(), boot) } +func closeBoot(boot *Boot) { boot.Phase, boot.Closed, boot.Seed = "", true, nil } + func (c Config) saveBoot(work *site.Work, boot Boot) error { return work.Store().PutRecord(work.Device, work.Fence, bootRecords, work.Key(), boot) } @@ -414,7 +455,7 @@ func (c Config) run(ctx context.Context, work *site.Work, phases []phase) ([]ops // stopped from outside leaves it open for its replacement. defer func() { if mode != "" && site.DeadlinePassed(ctx) && !boot.Closed { - boot.Phase, boot.Closed = "", true + closeBoot(&boot) _ = c.saveBoot(work, boot) } }() @@ -471,7 +512,7 @@ func (c Config) run(ctx context.Context, work *site.Work, phases []phase) ([]ops return nil, err } if ph.mode != "" { - boot.Phase, boot.Closed = "", true + closeBoot(&boot) if err := c.saveBoot(work, boot); err != nil { return nil, err } @@ -574,7 +615,14 @@ func (c Config) complete(ctx context.Context, work *site.Work, boot Boot, ph pha if power.State == "Off" { if seen == 1 { if ph.mode != "" { - return c.verifyDelivery(work) + if err := c.verifyDelivery(work, len(boot.Seed) > 0); err != nil { + return err + } + } + // The installer read the seed back from the target disk + // and reported its salted digest. + if ph.name == "installer" && work.Bootstrap() != nil { + return c.verifyBootstrap(work, boot) } return nil } @@ -652,9 +700,33 @@ func (c Config) deliveries(work *site.Work) map[string]bool { return done } -func (c Config) verifyDelivery(work *site.Work) error { +// verifyBootstrap requires exactly one console line in which the installer +// reports the salted digest of the bootstrap data it read back from the +// target disk. +func (c Config) verifyBootstrap(work *site.Work, boot Boot) error { + data, err := os.ReadFile(filepath.Join(c.ConsoleRoot, filepath.Base(conn(work).Target.Console))) + if err != nil { + return err + } + want, n := site.BootstrapLine(boot.Receipt, work.Bootstrap().Digest), 0 + for _, line := range strings.Split(string(data), "\n") { + if strings.TrimSpace(line) == want { + n++ + } + } + if n != 1 { + return errors.New("the installer did not verify the admitted bootstrap data on disk") + } + return nil +} + +func (c Config) verifyDelivery(work *site.Work, seed bool) error { done := c.deliveries(work) - for _, name := range []string{"boot.ipxe", "kernel", "installer.gz"} { + names := []string{"boot.ipxe", "kernel", "installer.gz"} + if seed { + names = append(names, "seed.cpio") + } + for _, name := range names { if !done["write-complete "+name] { return fmt.Errorf("missing network delivery: %s", name) } diff --git a/internal/site/redfishwork/kinds_test.go b/internal/site/redfishwork/kinds_test.go index 42266060..6fb0e5ee 100644 --- a/internal/site/redfishwork/kinds_test.go +++ b/internal/site/redfishwork/kinds_test.go @@ -55,6 +55,14 @@ type lab struct { bootRoot string store *site.Store operation string + // bootstrap, given the receipt, is the extra line the installer prints + // after it reads the seed back from the target disk. + bootstrap func(receipt string) string + // seeded records whether the network boot's script loaded the seed. + seeded bool + // unfetchedSeed leaves the seed out of the boot service's delivery log, + // as when the installer never fetched it. + unfetchedSeed bool // silent keeps the server running with no console receipt. silent bool // Commissioning: the serial and firmware the BMC reports, a component @@ -238,8 +246,14 @@ func (l *lab) boot(target string) { l.deliver() line = fmt.Sprintf("FLEET-WIPED:%s:%d", boot.Receipt, diskBytes) case target == "Pxe": + l.mu.Lock() + l.seeded = len(boot.Seed) > 0 + l.mu.Unlock() l.deliver() line = "FLEET-INSTALLED:" + boot.Receipt + if l.bootstrap != nil { + line = l.bootstrap(boot.Receipt) + "\n" + line + } case target == "Hdd": line = "FLEET-DISK-BOOT:" + boot.Receipt } @@ -311,7 +325,11 @@ func (l *lab) deliver() { at := time.Now().Add(l.skew).UTC().Format(time.RFC3339) l.mu.Unlock() log := at + " admitted boot.ipxe bytes=1\n" - for _, name := range []string{"boot.ipxe", "kernel", "installer.gz"} { + names := []string{"boot.ipxe", "kernel", "installer.gz"} + if l.seeded && !l.unfetchedSeed { + names = append(names, "seed.cpio") + } + for _, name := range names { log += at + " write-complete " + name + " bytes=1\n" } os.WriteFile(filepath.Join(dir, "boot-delivery.log"), []byte(log), 0o600) @@ -340,7 +358,7 @@ func runner(t *testing.T, l *lab) *site.Runner { t.Fatal(err) } l.store = store - config := Config{ConsoleRoot: filepath.Dir(l.console), BootRoot: l.bootRoot, Poll: 10 * time.Millisecond, OffGrace: 2 * time.Second} + config := Config{fixtureSeeds: true, ConsoleRoot: filepath.Dir(l.console), BootRoot: l.bootRoot, Poll: 10 * time.Millisecond, OffGrace: 2 * time.Second} return &site.Runner{ Site: "site-example-a", Store: store, Results: site.NewResults(store), Access: site.RedfishAccess{Credentials: credentials{pin: l.pin()}, @@ -439,14 +457,19 @@ func TestWipeChecksTheEnrolledDisk(t *testing.T) { } } -func TestBootstrapIsRefusedAtTheSiteToo(t *testing.T) { +// TestBootstrapWithoutAPayloadSendsNothing: an install whose inputs name a +// payload the site does not hold is refused before any power change. +func TestBootstrapWithoutAPayloadSendsNothing(t *testing.T) { l := newLab(t) r := runner(t, l) spec := installSpec() spec.Bootstrap = &ops.SealedInput{Ref: "sealed-example", Digest: "sha256:" + strings.Repeat("c", 64)} - result, _ := r.Run(context.Background(), assignment(l, "DeviceInstallation", "op-bootstrap", 1, spec)) - if result.Phase != ops.PhaseFailed || l.onCount() != 0 { - t.Fatalf("result = %+v", result) + for name, payloads := range map[string]site.Payloads{"a site that cannot receive payloads": nil, "a payload never delivered": site.StorePayloads{Store: r.Store}} { + r.Payloads = payloads + result, _ := r.Run(context.Background(), assignment(l, "DeviceInstallation", "op-bootstrap-"+strings.ReplaceAll(name, " ", "-"), 1, spec)) + if result.Phase != ops.PhaseFailed || l.onCount() != 0 { + t.Fatalf("%s: result = %+v", name, result) + } } } @@ -565,3 +588,148 @@ func TestAServerThatNeverPowersOffEndsTheStep(t *testing.T) { t.Fatalf("result = %+v, %d power-ons after %s", result, l.onCount(), time.Since(started)) } } + +// TestTheInstallerVerifiesBootstrapDataOverRedfish: the network boot loads +// the seed, and the install succeeds only if the installer reports the +// admitted data's salted digest after reading it back from the disk. A +// failed check stops before the disk boot. +func TestTheInstallerVerifiesBootstrapDataOverRedfish(t *testing.T) { + salt := make([]byte, 32) + data := []byte(`{"sshAuthorizedKeys":"ssh-ed25519 AAAAExampleOnly\n"}`) + hash := sha256.New() + hash.Write(salt) + hash.Write(data) + payload := site.Payload{Ref: "sealed-example", Digest: "sha256:" + hex.EncodeToString(hash.Sum(nil)), Salt: salt, Data: data} + admitted := func(receipt string) string { return site.BootstrapLine(receipt, payload.Digest) } + for name, test := range map[string]struct { + line func(receipt string) string + unfetched bool + ok bool + }{ + "the admitted seed": {line: admitted, ok: true}, + "a wrong seed read back": {line: func(receipt string) string { return site.BootstrapLine(receipt, "sha256:"+strings.Repeat("0", 64)) }}, + "no verification line": {line: func(string) string { return "booted" }}, + "another receipt": {line: func(string) string { return site.BootstrapLine(strings.Repeat("e", 64), payload.Digest) }}, + "a seed never fetched": {line: admitted, unfetched: true}, + } { + t.Run(name, func(t *testing.T) { + l := newLab(t) + r := runner(t, l) + r.Payloads = site.StorePayloads{Store: r.Store} + l.bootstrap = test.line + l.unfetchedSeed = test.unfetched + spec := installSpec() + spec.Bootstrap = &ops.SealedInput{Ref: payload.Ref, Digest: payload.Digest} + a := assignment(l, "DeviceInstallation", "op-seed", 1, spec) + if err := r.Store.Raise(device, 1); err != nil { + t.Fatal(err) + } + if err := r.Payloads.(site.StorePayloads).Put(a, payload); err != nil { + t.Fatal(err) + } + result, err := r.Run(context.Background(), a) + if err != nil { + t.Fatal(err) + } + if !l.seeded { + t.Fatal("the network boot did not load the seed") + } + var boot Boot + if found, err := r.Store.GetRecord(device, bootRecords, a.Key(), &boot); err != nil || !found || len(boot.Seed) != 0 { + t.Fatalf("the admission kept its seed: %d bytes, %v, %v", len(boot.Seed), found, err) + } + var evidence ops.InstallationEvidence + _ = json.Unmarshal(result.Evidence, &evidence) + if succeeded := result.Phase == ops.PhaseSucceeded; succeeded != test.ok || (test.ok && evidence.InstallerVerifiedBootstrap != payload.Digest) { + t.Fatalf("result = %+v, evidence %+v", result, evidence) + } + if !test.ok && l.onCount() != 1 { + t.Fatalf("a failed check powered the server on %d times; it must stop before the disk boot", l.onCount()) + } + }) + } +} + +// TestAFailedRedfishInstallDropsItsSeed: an admission that expires before +// the network boot ends the install without a clean close, and the site +// still drops the seed it held. +func TestOrdinaryBootServerRefusesSeedBeforeClose(t *testing.T) { + lab := newLab(t) + store := runner(t, lab).Store + boot := Boot{Operation: uuid, Fence: 1, Phase: "installer", Expires: time.Now().Add(time.Minute), Token: strings.Repeat("c", 64), Seed: []byte("synthetic")} + if err := store.Raise(device, 1); err != nil { + t.Fatal(err) + } + if err := store.PutRecord(device, 1, bootRecords, boot.Operation, boot); err != nil { + t.Fatal(err) + } + server := BootServer{Store: store} + if _, open := server.open(Key(boot.Operation), boot.Token); !open { + t.Fatal("test admission is not open") + } + response := httptest.NewRecorder() + server.Handler().ServeHTTP(response, httptest.NewRequest("GET", "/"+Key(boot.Operation)+"/"+boot.Token+"/seed.cpio", nil)) + if response.Code != http.StatusForbidden { + t.Fatalf("ordinary seed request: %d", response.Code) + } + closeBoot(&boot) + if len(boot.Seed) != 0 { + t.Fatal("closed admission retained seed bytes") + } +} + +func TestAFailedRedfishInstallDropsItsSeed(t *testing.T) { + l := newLab(t) + r := runner(t, l) + installation := r.Kinds["DeviceInstallation"].(Installation) + installation.BootWindow = time.Nanosecond + r.Kinds["DeviceInstallation"] = installation + r.Payloads = site.StorePayloads{Store: r.Store} + salt := make([]byte, 32) + data := []byte(`{"userData":"#cloud-config\n"}`) + hash := sha256.New() + hash.Write(salt) + hash.Write(data) + payload := site.Payload{Ref: "sealed-example", Digest: "sha256:" + hex.EncodeToString(hash.Sum(nil)), Salt: salt, Data: data} + spec := installSpec() + spec.Bootstrap = &ops.SealedInput{Ref: payload.Ref, Digest: payload.Digest} + a := assignment(l, "DeviceInstallation", "op-expired", 1, spec) + if err := r.Store.Raise(device, 1); err != nil { + t.Fatal(err) + } + if err := r.Payloads.(site.StorePayloads).Put(a, payload); err != nil { + t.Fatal(err) + } + result, err := r.Run(context.Background(), a) + if err != nil || result.Phase == ops.PhaseSucceeded { + t.Fatalf("result = %+v, %v", result, err) + } + var boot Boot + if found, err := r.Store.GetRecord(device, bootRecords, a.Key(), &boot); err != nil || !found || len(boot.Seed) != 0 { + t.Fatalf("the site kept %d bytes of seed: %v, %v", len(boot.Seed), found, err) + } +} + +// TestANewerFenceDropsASupersededSeed: a recovery only raises the fence, +// and the site drops the seed a superseded install left in its boot +// admission. +func TestANewerFenceDropsASupersededSeed(t *testing.T) { + l := newLab(t) + r := runner(t, l) + uid := "op-superseded" + if err := r.Store.Raise(device, 1); err != nil { + t.Fatal(err) + } + boot := Boot{Operation: uid, Fence: 1, Mode: "install", MAC: mac, Receipt: strings.Repeat("d", 64), Token: strings.Repeat("c", 64), Expires: time.Now().Add(time.Minute), Seed: []byte("seed-bytes")} + if err := r.Store.PutRecord(device, 1, bootRecords, uid, boot); err != nil { + t.Fatal(err) + } + recovery := assignment(l, "DeviceRecovery", "op-recovery", 2, installSpec()) + if err := r.Fence(context.Background(), recovery); err != nil { + t.Fatal(err) + } + var after Boot + if found, err := r.Store.GetRecord(device, bootRecords, uid, &after); err != nil || !found || len(after.Seed) != 0 { + t.Fatalf("a superseded admission kept %d bytes of seed: %v, %v", len(after.Seed), found, err) + } +} diff --git a/internal/site/runner.go b/internal/site/runner.go index baab613a..9d5c0a3a 100644 --- a/internal/site/runner.go +++ b/internal/site/runner.go @@ -288,6 +288,9 @@ func (r *Runner) acquire(ctx context.Context, assignment Assignment) (*runLock, return nil, err } } + if err := r.scrub(assignment.Device, assignment.Fence); err != nil { + return nil, err + } ctx, cancel := context.WithDeadline(ctx, assignment.Deadline) defer cancel() for { diff --git a/internal/site/seed.go b/internal/site/seed.go new file mode 100644 index 00000000..352b62e5 --- /dev/null +++ b/internal/site/seed.go @@ -0,0 +1,82 @@ +package site + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "strings" +) + +// SeedDirectory is where the seed archive puts a payload in the installer's +// root filesystem. The installer copies it to the target disk. +const SeedDirectory = "fleet-bootstrap" + +// BootstrapMarker starts the console line in which the installer, after it +// writes the seed to the target disk, reports the digest of what it reads +// back: "FLEET-BOOTSTRAP::sha256:". It recomputes the digest +// from the salt and data on the target disk, so the line proves the write +// without printing the data or an unsalted hash of it. +const BootstrapMarker = "FLEET-BOOTSTRAP:" + +// BootstrapLine is the console line the installer prints for a receipt and +// digest. +func BootstrapLine(receipt, digest string) string { + return BootstrapMarker + receipt + ":" + digest +} + +// SeedArchive renders a verified payload as the newc cpio archive a network +// boot loads as a second initrd. It holds the salt and data the installer +// digests, and the NoCloud user-data, meta-data and authorized keys the +// installed system reads. Every file is readable by root only. +func SeedArchive(payload *Payload, instanceID string) ([]byte, error) { + if payload == nil || instanceID == "" || strings.ContainsAny(instanceID, "\n:") { + return nil, errors.New("site: a seed needs a payload and an instance ID") + } + var values struct { + UserData string `json:"userData"` + SSHAuthorizedKeys string `json:"sshAuthorizedKeys"` + } + if err := json.Unmarshal(payload.Data, &values); err != nil { + return nil, err + } + var archive bytes.Buffer + files := []struct { + name string + mode uint32 + data []byte + }{ + {SeedDirectory, 0o040700, nil}, + {SeedDirectory + "/salt", 0o100600, payload.Salt}, + {SeedDirectory + "/data", 0o100600, payload.Data}, + {SeedDirectory + "/user-data", 0o100600, []byte(values.UserData)}, + {SeedDirectory + "/meta-data", 0o100600, []byte("instance-id: " + instanceID + "\n")}, + {SeedDirectory + "/authorized_keys", 0o100600, []byte(values.SSHAuthorizedKeys)}, + } + for index, file := range files { + writeEntry(&archive, uint32(index+1), file.mode, file.name, file.data) + } + writeEntry(&archive, 0, 0, "TRAILER!!!", nil) + return archive.Bytes(), nil +} + +// writeEntry writes one newc cpio entry, padding the header and name, and +// the data, to four bytes. +func writeEntry(out *bytes.Buffer, inode, mode uint32, name string, data []byte) { + nlink := uint32(1) + if mode&0o040000 != 0 { + nlink = 2 + } + fmt.Fprintf(out, "070701%08X%08X%08X%08X%08X%08X%08X%08X%08X%08X%08X%08X%08X", inode, mode, 0, 0, nlink, 0, len(data), 0, 0, 0, 0, len(name)+1, 0) + out.WriteString(name) + out.WriteByte(0) + pad(out) + out.Write(data) + pad(out) +} + +func pad(out *bytes.Buffer) { + for out.Len()%4 != 0 { + out.WriteByte(0) + } +} diff --git a/internal/site/seed_test.go b/internal/site/seed_test.go new file mode 100644 index 00000000..c8986cb5 --- /dev/null +++ b/internal/site/seed_test.go @@ -0,0 +1,45 @@ +package site + +import ( + "bytes" + "os" + "os/exec" + "path/filepath" + "testing" +) + +// TestASeedArchiveUnpacksToThePayload unpacks the archive with the +// system's cpio: the files a guest reads hold exactly the payload. +func TestASeedArchiveUnpacksToThePayload(t *testing.T) { + payload := &Payload{Salt: bytes.Repeat([]byte{7}, 32), Data: []byte(`{"userData":"#cloud-config\nhostname: example\n","sshAuthorizedKeys":"ssh-ed25519 AAAAExampleOnly\n"}`)} + archive, err := SeedArchive(payload, "fleet-0123") + if err != nil { + t.Fatal(err) + } + if len(archive)%4 != 0 || !bytes.Contains(archive, []byte("TRAILER!!!")) { + t.Fatal("the archive is not a padded newc archive") + } + cpio, err := exec.LookPath("cpio") + if err != nil { + t.Fatal("cpio is required to check the archive") + } + dir := t.TempDir() + command := exec.Command(cpio, "-id", "--quiet") + command.Dir, command.Stdin = dir, bytes.NewReader(archive) + if output, err := command.CombinedOutput(); err != nil { + t.Fatalf("cpio: %v: %s", err, output) + } + for name, want := range map[string]string{ + "salt": string(payload.Salt), "data": string(payload.Data), + "user-data": "#cloud-config\nhostname: example\n", "meta-data": "instance-id: fleet-0123\n", + "authorized_keys": "ssh-ed25519 AAAAExampleOnly\n", + } { + got, err := os.ReadFile(filepath.Join(dir, SeedDirectory, name)) + if err != nil || string(got) != want { + t.Errorf("%s = %q, %v", name, got, err) + } + } + if _, err := SeedArchive(payload, "bad\nid"); err == nil { + t.Fatal("an instance ID with a newline was accepted") + } +} diff --git a/internal/site/simwork/kinds.go b/internal/site/simwork/kinds.go index 4a4c51d5..e7963523 100644 --- a/internal/site/simwork/kinds.go +++ b/internal/site/simwork/kinds.go @@ -181,7 +181,7 @@ func (Installation) Run(ctx context.Context, work *site.Work) (any, error) { if server.Booted != spec.Image.Digest { return nil, &custody.Refusal{Reason: site.ReasonStep, Message: "the simulated server did not boot the installed image"} } - evidence.Bootstrap = server.Bootstrap + evidence.InstallerVerifiedBootstrap = server.Bootstrap return evidence, nil } diff --git a/internal/site/store.go b/internal/site/store.go index 387ed2c7..b6465f4c 100644 --- a/internal/site/store.go +++ b/internal/site/store.go @@ -452,3 +452,21 @@ func (s *Store) Records(collection string) ([]Record, error) { } return out, nil } + +// RewriteRecord replaces a kind's existing record whatever the stored fence, +// so a newer fence can remove secret material from a superseded one. It +// writes nothing if there is no record. +func (s *Store) RewriteRecord(device, collection, name string, value any) error { + if !validRecordName(collection) || !validRecordName(name) { + return errors.New("site: invalid record name") + } + return s.locked(device, func(*deviceState) (bool, error) { + dir := filepath.Join(s.deviceDir(device), collection) + if _, err := os.Stat(filepath.Join(dir, name+".json")); os.IsNotExist(err) { + return false, nil + } else if err != nil { + return false, err + } + return false, writeAtomic(dir, name+".json", value) + }) +} diff --git a/internal/site/vmwork/boot.go b/internal/site/vmwork/boot.go index d07c77e5..5cd9b672 100644 --- a/internal/site/vmwork/boot.go +++ b/internal/site/vmwork/boot.go @@ -65,7 +65,7 @@ func (c Config) stopNetwork(ctx context.Context) error { // verifyNetworkBoot requires the boot server's completed deliveries and the // firmware's DHCP lease. -func (k Installation) verifyNetworkBoot(ctx context.Context, work *site.Work) error { +func (k Installation) verifyNetworkBoot(ctx context.Context, work *site.Work, seed bool) error { data, err := os.ReadFile(filepath.Join(k.BootRoot, Key(work.Key()), "boot-delivery.log")) if err != nil { return err @@ -80,7 +80,11 @@ func (k Installation) verifyNetworkBoot(ctx context.Context, work *site.Work) er completed[fields[2]] = true } } - for _, name := range []string{"boot.ipxe", "kernel", "installer.gz"} { + names := []string{"boot.ipxe", "kernel", "installer.gz"} + if seed { + names = append(names, "seed.cpio") + } + for _, name := range names { if !completed[name] { return fmt.Errorf("missing network delivery: %s", name) } @@ -139,7 +143,20 @@ func (c Config) BootHandler(store *site.Store) http.Handler { switch name { case "boot.ipxe": base := c.origin() + "/" + parts[1] + "/" + boot.Token - data = []byte(fmt.Sprintf("#!ipxe\nkernel %s/kernel console=ttyS0 rdinit=/init fleet.receipt=%s%s\ninitrd %s/installer.gz\nboot\n", base, boot.Receipt, modeArgs(boot), base)) + seed := "" + if c.fixtureSeeds && len(boot.Seed) > 0 { + seed = "initrd " + base + "/seed.cpio\n" + } + data = []byte(fmt.Sprintf("#!ipxe\nkernel %s/kernel console=ttyS0 rdinit=/init fleet.receipt=%s%s\ninitrd %s/installer.gz\n%sboot\n", base, boot.Receipt, modeArgs(boot), base, seed)) + size = int64(len(data)) + case "seed.cpio": + // The operation's bootstrap seed, only while its admission is + // open; it is never written to the delivery evidence. + if !c.fixtureSeeds || len(boot.Seed) == 0 { + deny() + return + } + data = boot.Seed size = int64(len(data)) case "kernel", "installer.gz": // Hash the pinned artifact, then serve the same open file. @@ -228,7 +245,7 @@ func (c Config) CheckClosedBoot(store *site.Store, origin string) (string, error return "", fmt.Errorf("a boot admission is not closed") } base := origin + "/" + record.Name + "/" + boot.Token - for _, url := range []string{base + "/boot.ipxe", base + "/kernel", base + "/installer.gz", base + "/disk.raw", origin + "/kernel", origin + "/unknown/unknown/boot.ipxe"} { + for _, url := range []string{base + "/boot.ipxe", base + "/kernel", base + "/installer.gz", base + "/seed.cpio", base + "/disk.raw", origin + "/kernel", origin + "/unknown/unknown/boot.ipxe"} { response, err := client.Get(url) if err != nil { return "", fmt.Errorf("the boot denial probe is unavailable") diff --git a/internal/site/vmwork/commissioning.go b/internal/site/vmwork/commissioning.go index 6fa01bb3..56ed6b34 100644 --- a/internal/site/vmwork/commissioning.go +++ b/internal/site/vmwork/commissioning.go @@ -204,7 +204,7 @@ func (k Commissioning) burnIn(ctx context.Context, work *site.Work, duration tim if err := k.waitBurnIn(ctx, work, boot); err != nil { return "", fail(err) } - if err := install.verifyNetworkBoot(ctx, work); err != nil { + if err := install.verifyNetworkBoot(ctx, work, false); err != nil { return "", fail(err) } boot.Open, boot.Closed = false, true diff --git a/internal/site/vmwork/kinds.go b/internal/site/vmwork/kinds.go index b44cc160..7609ef72 100644 --- a/internal/site/vmwork/kinds.go +++ b/internal/site/vmwork/kinds.go @@ -38,6 +38,8 @@ const guestMAC = "52:54:00:77:00:02" // Config is one local VM site. type Config struct { + fixtureSeeds bool // Enabled only by in-package tests; never configurable by a deployment. + // Artifacts holds the installer kernel, initrd and their SHA256SUMS. Artifacts string // Image is the only image the site installs: the artifact manifest's @@ -156,8 +158,10 @@ func (k 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: "this site cannot yet hand bootstrap data to the server"} + // Bootstrap data reaches the guest only as a second initrd of a network + // boot; a direct kernel boot has one initrd. + if spec.Bootstrap != nil && (!k.PXE || !k.fixtureSeeds) { + return &custody.Refusal{Reason: custody.ReasonBootstrapUnsupported, Message: "this site hands bootstrap data to the server only on a network boot"} } if refusal := custody.OnlyNetworkBoot(spec.Delivery); refusal != nil { return refusal @@ -186,6 +190,9 @@ type Boot struct { Expires time.Time `json:"expires"` Open bool `json:"open,omitempty"` Closed bool `json:"closed,omitempty"` + // Seed is the operation's bootstrap seed archive, served only while the + // admission is open and dropped when it closes. + Seed []byte `json:"seed,omitempty"` // Accelerator is the one the installation runs under, fixed before any // boot, so a replacement worker never resumes it under another. Accelerator string `json:"accelerator"` @@ -195,6 +202,31 @@ type Boot struct { DurationSeconds int64 `json:"durationSeconds,omitempty"` } +var _ site.Scrubber = Installation{} + +// Scrub drops the seed from every boot admission of the Device below the +// fence, however its install ended. +func (Installation) Scrub(store *site.Store, device string, below int64) error { + records, err := store.Records(bootRecords) + if err != nil { + return err + } + for _, record := range records { + var boot Boot + if record.Device != device || json.Unmarshal(record.Data, &boot) != nil || boot.Fence >= below || len(boot.Seed) == 0 { + continue + } + boot.Seed = nil + if err := store.RewriteRecord(device, bootRecords, record.Name, boot); err != nil { + return err + } + } + return nil +} + +// closeBoot closes an admission and drops its seed. +func closeBoot(boot *Boot) { boot.Open, boot.Closed, boot.Seed = false, true, nil } + const bootRecords = "vmboot" // boot reads the installation's boot admission, creating it once. The @@ -213,6 +245,11 @@ func (k Installation) boot(work *site.Work) (Boot, error) { return boot, err } boot = Boot{Operation: work.Key(), Fence: work.Fence, Receipt: hex.EncodeToString(receipt), Token: hex.EncodeToString(token), Expires: k.now().Add(k.window()), Accelerator: k.Accelerator} + if payload := work.Bootstrap(); payload != nil { + if boot.Seed, err = site.SeedArchive(payload, "fleet-"+Key(work.Key())); err != nil { + return boot, err + } + } return boot, k.save(work, boot) } @@ -282,7 +319,7 @@ func (k Installation) Run(ctx context.Context, work *site.Work) (any, error) { // outside leaves it open for its replacement to resume. fail := func(err error) error { if stage == "installer" && k.PXE && boot.Open && (ctx.Err() == nil || site.DeadlinePassed(ctx)) { - boot.Open, boot.Closed = false, true + closeBoot(&boot) _ = k.save(work, boot) } return err @@ -311,10 +348,10 @@ func (k Installation) Run(ctx context.Context, work *site.Work) (any, error) { return nil, fail(err) } if stage == "installer" && k.PXE { - if err := k.verifyNetworkBoot(ctx, work); err != nil { + if err := k.verifyNetworkBoot(ctx, work, len(boot.Seed) > 0); err != nil { return nil, fail(err) } - boot.Open, boot.Closed = false, true + closeBoot(&boot) if err := k.save(work, boot); err != nil { return nil, err } @@ -324,6 +361,9 @@ func (k Installation) Run(ctx context.Context, work *site.Work) (any, error) { } record(stage) } + if payload := work.Bootstrap(); payload != nil { + evidence.InstallerVerifiedBootstrap = payload.Digest + } return evidence, nil } @@ -390,6 +430,16 @@ func (k Installation) domainXML(work *site.Work, boot Boot, stage string) string return fmt.Sprintf(`%s20482hvm%sdestroydestroydestroy%s/usr/bin/qemu-system-x86_64`, domainType, domain(work.Key()), bootXML, nic, dir, dir, stage) } +// bootstrapLine is the console line the installer prints after it reads the +// admitted bootstrap data back from the target disk, or a line no guest +// prints when there is none. +func bootstrapLine(work *site.Work, boot Boot) string { + if payload := work.Bootstrap(); payload != nil { + return site.BootstrapLine(boot.Receipt, payload.Digest) + } + return "\x00" +} + // modeArgs is the kernel arguments that select the boot image's mode. func modeArgs(boot Boot) string { if boot.Mode == "" { @@ -415,15 +465,23 @@ func (k Installation) waitReceipt(ctx context.Context, work *site.Work, boot Boo if err != nil { return err } - count := 0 + count, bootstrapped := 0, 0 for _, line := range strings.Split(string(data), "\n") { - if strings.TrimSpace(line) == marker+boot.Receipt { + switch strings.TrimSpace(line) { + case marker + boot.Receipt: count++ + case bootstrapLine(work, boot): + bootstrapped++ } } if count != 1 { return errors.New("the guest stopped without exactly one boot receipt") } + // The installer read the seed back from the target disk and + // reported its salted digest; the installed OS is not asked. + if stage == "installer" && work.Bootstrap() != nil && bootstrapped != 1 { + return errors.New("the installer did not verify the admitted bootstrap data on disk") + } file, err := os.OpenFile(log, os.O_RDWR, 0) if err != nil { return err diff --git a/internal/site/vmwork/kinds_test.go b/internal/site/vmwork/kinds_test.go index 3ecc514a..d330311f 100644 --- a/internal/site/vmwork/kinds_test.go +++ b/internal/site/vmwork/kinds_test.go @@ -1,9 +1,13 @@ package vmwork import ( + "bytes" "context" + "crypto/sha256" + "encoding/hex" "encoding/json" "errors" + "io" "net/http" "net/http/httptest" "os" @@ -36,6 +40,14 @@ type hypervisor struct { hold bool // noReceipt makes the guest print no receipt. noReceipt bool + // bootstrap, given the receipt, is the extra line the installer prints + // after it reads the seed back from the target disk. + bootstrap func(receipt string) string + // networkReceipt is the receipt a network boot's script carries, as the + // boot server reads it from the open admission. + networkReceipt func() string + // failNetwork makes creating the provisioning network fail. + failNetwork bool // stuck makes destroy leave the domain running. stuck bool // exited makes destroy fail because the guest exited first. @@ -109,6 +121,8 @@ func (h *hypervisor) run(_ context.Context, _ string, args ...string) (string, e marker, receipt = "FLEET-BURNIN:", match[1]+":"+result } else if match != nil { marker, receipt = "FLEET-INSTALLED:", match[1] + } else if strings.Contains(xml, "") && h.networkReceipt != nil { + marker, receipt = "FLEET-INSTALLED:", h.networkReceipt() } else { // The disk boot prints the receipt the installer wrote. installed, _ := os.ReadFile(filepath.Join(filepath.Dir(log), "installer.log")) @@ -117,6 +131,9 @@ func (h *hypervisor) run(_ context.Context, _ string, args ...string) (string, e } } console := "booting\n" + marker + receipt + "\n" + if marker == "FLEET-INSTALLED:" && h.bootstrap != nil { + console = "booting\n" + h.bootstrap(receipt) + "\n" + marker + receipt + "\n" + } if h.noReceipt { console = "booting\n" } @@ -135,6 +152,10 @@ func (h *hypervisor) run(_ context.Context, _ string, args ...string) (string, e if !h.hold && !scripted { delete(h.running, name) } + case "net-create": + if h.failNetwork { + return "", errors.New("net-create failed") + } case "destroy": if h.exited { delete(h.running, args[1]) @@ -190,7 +211,7 @@ func newRig(t *testing.T) *rig { t.Fatal(err) } vm := &hypervisor{running: map[string]string{}} - config := Config{Artifacts: filepath.Join(root, "artifacts"), Image: image, Disks: filepath.Join(root, "disks"), BootRoot: filepath.Join(root, "boot"), Command: vm.run} + config := Config{fixtureSeeds: true, Artifacts: filepath.Join(root, "artifacts"), Image: image, Disks: filepath.Join(root, "disks"), BootRoot: filepath.Join(root, "boot"), Command: vm.run} enrollment := fixture.Enrollment{device: {BMCEndpoint: "https://[2001:db8::1]", SystemUUID: "00000000-0000-4000-8000-000000000001", BootMACAddress: "02:00:00:00:00:01", BMCPublicKeySHA256: key, Disks: []string{"disk-0"}}} runner := &site.Runner{Site: "site-example-a", Store: store, Results: site.NewResults(store), Access: fixture.Access{Enrollment: enrollment}, Kinds: map[string]site.Kind{"DeviceInstallation": Installation{config}, "DeviceWipe": Wipe{config}}, Poll: 10 * time.Millisecond} @@ -421,6 +442,212 @@ func TestAFailedNetworkBootClosesItsAdmission(t *testing.T) { } } +// sealedInstall is an install whose admitted inputs name a sealed payload, +// with the payload stored at the site as the site API stores it. +func (r *rig) sealedInstall(uid string, fence int64) (site.Assignment, site.Payload) { + r.t.Helper() + salt := bytes.Repeat([]byte{9}, 32) + data := []byte(`{"userData":"#cloud-config\n","sshAuthorizedKeys":"ssh-ed25519 AAAAExampleOnly\n"}`) + hash := sha256.New() + hash.Write(salt) + hash.Write(data) + payload := site.Payload{Ref: "sealed-example", Digest: "sha256:" + hex.EncodeToString(hash.Sum(nil)), Salt: salt, Data: data} + spec := installSpec() + spec.Bootstrap = &ops.SealedInput{Ref: payload.Ref, Digest: payload.Digest} + assignment := r.assignment("DeviceInstallation", uid, fence, spec) + if err := r.store.Raise(device, fence); err != nil { + r.t.Fatal(err) + } + if err := (site.StorePayloads{Store: r.store}).Put(assignment, payload); err != nil { + r.t.Fatal(err) + } + // The boot server's delivery evidence for every network boot file. + dir := filepath.Join(r.config.BootRoot, Key(assignment.Key())) + if err := os.MkdirAll(dir, 0o700); err != nil { + r.t.Fatal(err) + } + evidence := "" + for _, name := range []string{"boot.ipxe", "kernel", "installer.gz", "seed.cpio"} { + evidence += "2026-11-25T00:00:00Z write-complete " + name + " bytes=1\n" + } + if err := os.WriteFile(filepath.Join(dir, "boot-delivery.log"), []byte(evidence), 0o600); err != nil { + r.t.Fatal(err) + } + return assignment, payload +} + +// TestTheInstallerVerifiesBootstrapDataOnDisk: a network install loads the +// seed as a second initrd, the installer reads it back from the target disk +// and reports its salted digest, and the evidence records it as +// installer-verified. An installer that reads back a wrong or truncated +// seed, or reports nothing, fails the install before the disk boot, and the +// seed is dropped either way. The installed OS is not asked to prove +// anything. +func TestTheInstallerVerifiesBootstrapDataOnDisk(t *testing.T) { + truncated := func(receipt, _ string) string { + hash := sha256.New() + hash.Write(bytes.Repeat([]byte{9}, 32)) + hash.Write([]byte(`{"userData":"#cloud-config\n"`)) + return site.BootstrapLine(receipt, "sha256:"+hex.EncodeToString(hash.Sum(nil))) + } + for name, test := range map[string]struct { + line func(receipt, digest string) string + ok bool + }{ + "the admitted seed": {func(receipt, digest string) string { return site.BootstrapLine(receipt, digest) }, true}, + "a wrong seed read back": {func(receipt, _ string) string { return site.BootstrapLine(receipt, "sha256:"+strings.Repeat("0", 64)) }, false}, + "a truncated seed": {truncated, false}, + "no verification line": {func(string, string) string { return "" }, false}, + "another receipt": {func(_, digest string) string { return site.BootstrapLine(strings.Repeat("e", 64), digest) }, false}, + } { + t.Run(name, func(t *testing.T) { + r := newRig(t) + r.config.PXE = true + r.runner.Kinds["DeviceInstallation"] = Installation{r.config} + r.runner.Payloads = site.StorePayloads{Store: r.store} + assignment, payload := r.sealedInstall("00000000-0000-4000-8000-000000000211", 2) + r.vm.bootstrap = func(receipt string) string { return test.line(receipt, payload.Digest) } + r.vm.networkReceipt = func() string { + var boot Boot + _, _ = r.store.GetRecord(device, bootRecords, Key(assignment.Key()), &boot) + return boot.Receipt + } + result, err := r.runner.Run(context.Background(), assignment) + if err != nil { + t.Fatal(err) + } + var boot Boot + if found, err := r.store.GetRecord(device, bootRecords, Key(assignment.Key()), &boot); err != nil || !found || boot.Open || len(boot.Seed) != 0 { + t.Fatalf("admission after the install = open %v, seed %d bytes, %v, %v", boot.Open, len(boot.Seed), found, err) + } + if !test.ok { + if result.Phase == ops.PhaseSucceeded || r.vm.creates != 1 { + t.Fatalf("result = %+v after %d boots; a failed check must stop before the disk boot", result, r.vm.creates) + } + return + } + var evidence ops.InstallationEvidence + if result.Phase != ops.PhaseSucceeded || json.Unmarshal(result.Evidence, &evidence) != nil || evidence.InstallerVerifiedBootstrap != payload.Digest { + t.Fatalf("result = %+v, evidence %+v", result, evidence) + } + }) + } +} + +// TestADirectBootRefusesBootstrapData: a direct kernel boot has one initrd, +// so it cannot hand the seed to the guest, and sends nothing. +func TestADirectBootRefusesBootstrapData(t *testing.T) { + r := newRig(t) + r.runner.Payloads = site.StorePayloads{Store: r.store} + assignment, _ := r.sealedInstall("00000000-0000-4000-8000-000000000212", 2) + result, err := r.runner.Run(context.Background(), assignment) + if err != nil || result.Phase != ops.PhaseFailed || result.Reason != custody.ReasonBootstrapUnsupported || r.vm.creates != 0 { + t.Fatalf("result = %+v, %v, %d boots", result, err, r.vm.creates) + } +} + +// TestTheBootServerServesTheSeedOnlyWhileOpen: the script loads the seed as +// a second initrd, and the seed is served only under the open admission. +func TestTheBootServerServesTheSeedOnlyWhileOpen(t *testing.T) { + r := newRig(t) + if err := r.store.Raise(device, 4); err != nil { + t.Fatal(err) + } + token := strings.Repeat("c", 64) + boot := Boot{Operation: "00000000-0000-4000-8000-000000000213", Fence: 4, Receipt: strings.Repeat("d", 64), Token: token, Expires: time.Now().Add(time.Minute), Open: true, Seed: []byte("seed-bytes")} + if err := r.store.PutRecord(device, 4, bootRecords, Key(boot.Operation), boot); err != nil { + t.Fatal(err) + } + server := httptest.NewServer(r.config.BootHandler(r.store)) + defer server.Close() + get := func(name string) (int, string) { + response, err := http.Get(server.URL + "/" + Key(boot.Operation) + "/" + token + "/" + name) + if err != nil { + t.Fatal(err) + } + defer response.Body.Close() + body, _ := io.ReadAll(response.Body) + return response.StatusCode, string(body) + } + if code, script := get("boot.ipxe"); code != http.StatusOK || !strings.Contains(script, "/seed.cpio\n") { + t.Fatalf("script = %d %q", code, script) + } + if code, body := get("seed.cpio"); code != http.StatusOK || body != "seed-bytes" { + t.Fatalf("seed = %d %q", code, body) + } + ordinary := r.config + ordinary.fixtureSeeds = false + response := httptest.NewRecorder() + ordinary.BootHandler(r.store).ServeHTTP(response, httptest.NewRequest("GET", "/"+Key(boot.Operation)+"/"+token+"/seed.cpio", nil)) + if response.Code != http.StatusForbidden { + t.Fatalf("ordinary seed request: %d", response.Code) + } + closeBoot(&boot) + if len(boot.Seed) != 0 { + t.Fatal("closed admission retained seed bytes") + } + if err := r.store.PutRecord(device, 4, bootRecords, Key(boot.Operation), boot); err != nil { + t.Fatal(err) + } + if code, _ := get("seed.cpio"); code != http.StatusForbidden { + t.Fatalf("seed after close = %d", code) + } +} + +// TestEveryEndDropsTheSeed: a seed is customer data in the site store, so +// an install that fails before its network boot opens, or whose admission +// expires, drops it as surely as a clean close does, and a newer fence +// drops a superseded operation's. +func TestEveryEndDropsTheSeed(t *testing.T) { + seed := func(r *rig, uid string) []byte { + var boot Boot + if _, err := r.store.GetRecord(device, bootRecords, Key(uid), &boot); err != nil { + t.Fatal(err) + } + return boot.Seed + } + for name, setup := range map[string]func(*rig){ + "a failure before the admission opens": func(r *rig) { r.vm.failNetwork = true }, + "an admission that expires": func(r *rig) { r.config.BootWindow = time.Nanosecond }, + } { + t.Run(name, func(t *testing.T) { + r := newRig(t) + r.config.PXE = true + setup(r) + r.runner.Kinds["DeviceInstallation"] = Installation{r.config} + r.runner.Payloads = site.StorePayloads{Store: r.store} + uid := "00000000-0000-4000-8000-000000000221" + assignment, _ := r.sealedInstall(uid, 2) + result, err := r.runner.Run(context.Background(), assignment) + if err != nil || result.Phase == ops.PhaseSucceeded { + t.Fatalf("result = %+v, %v", result, err) + } + if got := seed(r, uid); len(got) != 0 { + t.Fatalf("the site kept %d bytes of seed after the install ended", len(got)) + } + }) + } + t.Run("a newer fence", func(t *testing.T) { + r := newRig(t) + uid := "00000000-0000-4000-8000-000000000222" + boot := Boot{Operation: uid, Fence: 2, Receipt: strings.Repeat("d", 64), Token: strings.Repeat("c", 64), Expires: time.Now().Add(time.Minute), Seed: []byte("seed-bytes")} + if err := r.store.Raise(device, 2); err != nil { + t.Fatal(err) + } + if err := r.store.PutRecord(device, 2, bootRecords, Key(uid), boot); err != nil { + t.Fatal(err) + } + // A recovery only raises the fence; nothing of its own ends. + recovery := r.assignment("DeviceRecovery", "00000000-0000-4000-8000-000000000223", 3, wipeSpec()) + if err := r.runner.Fence(context.Background(), recovery); err != nil { + t.Fatal(err) + } + if got := seed(r, uid); len(got) != 0 { + t.Fatalf("a superseded admission kept %d bytes of seed", len(got)) + } + }) +} + // TestAnInstallationResumesOnlyUnderItsBoundAccelerator starts an install // under TCG; a replacement worker configured for KVM boots nothing, and its // journaled boot admission still names TCG. diff --git a/internal/sitepolicy/policy_test.go b/internal/sitepolicy/policy_test.go new file mode 100644 index 00000000..8e6b9d12 --- /dev/null +++ b/internal/sitepolicy/policy_test.go @@ -0,0 +1,493 @@ +// Package sitepolicy tests the site's admission policies and kro's RBAC +// against a real API server. kro creates every per-operation Role and +// RoleBinding at a site, so these policies, not kro, decide what a worker +// may read. Each case also runs with the one policy rule it tests removed, +// and must then be admitted: a probe that passes without its rule proves +// nothing. +package sitepolicy + +import ( + "bytes" + "context" + "fmt" + "io" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/go-logr/logr" + apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/util/yaml" + "k8s.io/client-go/rest" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/envtest" + ctrllog "sigs.k8s.io/controller-runtime/pkg/log" +) + +const ( + kro = "system:serviceaccount:kro-system:kro" + coordination = "fleet-coordination" + credentials = "fleet-site-credentials" + handoff = "op-" + "0123456789abcdef0123456789abcdef01234567" +) + +var root = filepath.Join("..", "..") + +// render builds a kustomization with the kustomize binary CI installs. +func render(t *testing.T, dir string) []*unstructured.Unstructured { + t.Helper() + path, err := exec.LookPath("kustomize") + if err != nil { + t.Fatal("kustomize is required: the policies are tested as rendered") + } + output, err := exec.Command(path, "build", filepath.Join(root, dir)).Output() + if err != nil { + t.Fatalf("kustomize build %s: %v", dir, err) + } + return decode(t, output) +} + +func decode(t *testing.T, data []byte) []*unstructured.Unstructured { + t.Helper() + decoder := yaml.NewYAMLOrJSONDecoder(bytes.NewReader(data), 4096) + var out []*unstructured.Unstructured + for { + object := &unstructured.Unstructured{} + if err := decoder.Decode(&object.Object); err == io.EOF { + return out + } else if err != nil { + t.Fatal(err) + } + if len(object.Object) != 0 { + out = append(out, object) + } + } +} + +func object(t *testing.T, text string) *unstructured.Unstructured { + t.Helper() + objects := decode(t, []byte(text)) + if len(objects) != 1 { + t.Fatalf("want one object in %s", text) + } + return objects[0] +} + +type env struct { + t *testing.T + ctx context.Context + admin client.Client + kro client.Client +} + +// start runs an API server with the coordination CRDs and one rendered site +// base, and binds kro's cluster role as the kro chart's aggregation does. +func start(t *testing.T, base string) *env { + t.Helper() + if os.Getenv("KUBEBUILDER_ASSETS") == "" { + t.Skip("KUBEBUILDER_ASSETS required") + } + ctrllog.SetLogger(logr.Discard()) + environment := &envtest.Environment{CRDDirectoryPaths: []string{filepath.Join(root, "config", "multiplane", "coordination", "crd.yaml")}, ErrorIfCRDPathMissing: true} + config, err := environment.Start() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = environment.Stop() }) + scheme := runtime.NewScheme() + admin, err := client.New(config, client.Options{Scheme: scheme}) + if err != nil { + t.Fatal(err) + } + impersonated := rest.CopyConfig(config) + impersonated.Impersonate = rest.ImpersonationConfig{UserName: kro, Groups: []string{"system:serviceaccounts", "system:serviceaccounts:kro-system", "system:authenticated"}} + kroClient, err := client.New(impersonated, client.Options{Scheme: scheme}) + if err != nil { + t.Fatal(err) + } + e := &env{t: t, ctx: context.Background(), admin: admin, kro: kroClient} + for _, namespace := range []string{"kro-system", "flux-system", coordination, credentials} { + e.apply(object(t, fmt.Sprintf(`{"apiVersion":"v1","kind":"Namespace","metadata":{"name":%q}}`, namespace))) + } + for _, rendered := range render(t, base) { + if rendered.GetKind() == "StorageClass" || rendered.GetKind() == "PersistentVolumeClaim" { + continue + } + e.apply(rendered) + } + e.apply(object(t, `{"apiVersion":"rbac.authorization.k8s.io/v1","kind":"ClusterRoleBinding","metadata":{"name":"kro-aggregated"}, + "subjects":[{"kind":"ServiceAccount","name":"kro","namespace":"kro-system"}], + "roleRef":{"apiGroup":"rbac.authorization.k8s.io","kind":"ClusterRole","name":"fleet-site-kro"}}`)) + // RBAC is the API server's authorizer here, as on a site. + if err := e.kro.Create(e.ctx, object(t, `{"apiVersion":"v1","kind":"ConfigMap","metadata":{"name":"probe","namespace":"kube-system"}}`)); !apierrors.IsForbidden(err) { + t.Fatalf("the API server does not authorize kro by RBAC: %v", err) + } + // The Job policy reads the site image from its parameter. + e.apply(object(t, `{"apiVersion":"v1","kind":"ConfigMap","metadata":{"name":"fleet-site-worker-policy","namespace":"fleet-site"},"data":{"image":"site-image"}}`)) + // A new policy admits everything until it is compiled; nothing counts + // as admitted until a known-refused request is refused by the policy. + control := dryRun(object(t, fmt.Sprintf(`{"apiVersion":"rbac.authorization.k8s.io/v1","kind":"Role","metadata":{"name":"w-%s","namespace":%q},"rules":[]}`, handoff, coordination))) + if got := e.outcome(control, "policy"); got != "policy" { + t.Fatalf("the policies never took effect: %s", got) + } + return e +} + +func (e *env) apply(object *unstructured.Unstructured) { + e.t.Helper() + object = object.DeepCopy() + if err := e.admin.Create(e.ctx, object); apierrors.IsAlreadyExists(err) { + existing := object.DeepCopy() + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(object), existing); err != nil { + e.t.Fatal(err) + } + object.SetResourceVersion(existing.GetResourceVersion()) + err = e.admin.Update(e.ctx, object) + if err != nil { + e.t.Fatal(err) + } + } else if err != nil { + e.t.Fatalf("apply %s %s: %v", object.GetKind(), object.GetName(), err) + } +} + +// policy returns a live policy, for a case to weaken one rule. +func (e *env) policy(name string) *unstructured.Unstructured { + e.t.Helper() + policy := &unstructured.Unstructured{} + policy.SetAPIVersion("admissionregistration.k8s.io/v1") + policy.SetKind("ValidatingAdmissionPolicy") + if err := e.admin.Get(e.ctx, client.ObjectKey{Name: name}, policy); err != nil { + e.t.Fatal(err) + } + return policy +} + +// weaken replaces one clause, an exact substring of exactly one +// validation's expression, by true, and returns a function that restores +// the policy. Weakening a single clause, not a whole validation, shows that +// this clause is what refuses the probe. +func (e *env) weaken(name, clause string) func() { + e.t.Helper() + policy := e.policy(name) + original := policy.DeepCopy() + original.SetResourceVersion("") + validations, _, _ := unstructured.NestedSlice(policy.Object, "spec", "validations") + found := 0 + for index, validation := range validations { + rule := validation.(map[string]any) + expression := fmt.Sprint(rule["expression"]) + if n := strings.Count(expression, clause); n > 0 { + found += n + rule["expression"] = strings.ReplaceAll(expression, clause, "true") + validations[index] = rule + } + } + if found != 1 { + e.t.Fatalf("%s has %d copies of the clause %q, want exactly one", name, found, clause) + } + _ = unstructured.SetNestedSlice(policy.Object, validations, "spec", "validations") + if err := e.admin.Update(e.ctx, policy); err != nil { + e.t.Fatal(err) + } + return func() { + current := e.policy(name) + restored := current.DeepCopy() + spec, _, _ := unstructured.NestedMap(original.Object, "spec") + restored.Object["spec"] = spec + if err := e.admin.Update(e.ctx, restored); err != nil { + e.t.Fatal(err) + } + } +} + +// outcome sends a request as kro, retrying while a just-changed policy has +// not yet taken effect, and reports whether it was admitted and which layer +// refused it. +func (e *env) outcome(send func(context.Context, client.Client) error, want string) string { + e.t.Helper() + got := "" + for deadline := time.Now().Add(20 * time.Second); time.Now().Before(deadline); time.Sleep(200 * time.Millisecond) { + err := send(e.ctx, e.kro) + switch { + case err == nil: + got = "admitted" + case strings.Contains(err.Error(), "ValidatingAdmissionPolicy"): + got = "policy" + case apierrors.IsForbidden(err): + got = "rbac" + default: + got = "error: " + err.Error() + } + if got == want { + return got + } + } + return got +} + +func dryRun(object *unstructured.Unstructured) func(context.Context, client.Client) error { + return func(ctx context.Context, c client.Client) error { + return c.Create(ctx, object.DeepCopy(), client.DryRunAll) + } +} + +func role(t *testing.T, namespace string, rules ...string) *unstructured.Unstructured { + return object(t, fmt.Sprintf(`{"apiVersion":"rbac.authorization.k8s.io/v1","kind":"Role","metadata":{"name":"w-%s","namespace":%q},"rules":[%s]}`, handoff, namespace, strings.Join(rules, ","))) +} + +const ( + ownHandoff = `{"apiGroups":["coordination.fleet.datumapis.com"],"resources":["machineallocationhandoffs"],"resourceNames":["` + handoff + `"],"verbs":["get"]}` + ownPayload = `{"apiGroups":["coordination.fleet.datumapis.com"],"resources":["machineallocationpayloads"],"resourceNames":["` + handoff + `-payload"],"verbs":["get"]}` + otherPayload = `{"apiGroups":["coordination.fleet.datumapis.com"],"resources":["machineallocationpayloads"],"resourceNames":["op-other-payload"],"verbs":["get"]}` + anyPayload = `{"apiGroups":["coordination.fleet.datumapis.com"],"resources":["machineallocationpayloads"],"verbs":["get"]}` + ownCredential = `{"apiGroups":[""],"resources":["secrets"],"resourceNames":["bmc-0123456789abcdef0123"],"verbs":["get"]}` + anyCredential = `{"apiGroups":[""],"resources":["secrets"],"verbs":["get"]}` + // Clauses of the rendered policies, each refusing one probe. + sizeClause = "size(object.rules) == 2" + payloadNameClause = "object.rules[1].resourceNames == [variables.handoff + '-payload']" + roleRefKindClause = "object.roleRef.kind == 'Role'" + ownRoleClause = "object.roleRef.name == object.metadata.name" + oneSubjectClause = "size(object.subjects) == 1" + subjectKindClause = "object.subjects[0].kind == 'ServiceAccount'" + subjectNameClause = "object.subjects[0].name == object.metadata.name" + subjectSpaceClause = "object.subjects[0].namespace == 'fleet-site'" + clusterRBACClause = "false" + envClause = "!has(c.envFrom)" + secretKeyClause = "!has(e.valueFrom.secretKeyRef)" + commandClause = "c.command[0] == 'fleet-multiplane'" + ownHandoffClause = "c.command[3] == variables.handoff" + argsClause = "!has(c.args)" + credentialSize = "size(object.rules) == 1 && object.rules.all(r, r.apiGroups == [''] && r.resources == ['secrets'] && r.verbs == ['get'] && has(r.resourceNames) && size(r.resourceNames) == 1 && r.resourceNames.all(n, n.matches('^bmc-[a-f0-9]{20}$')))" + payloadNamedClause = "has(object.rules[1].resourceNames)" +) + +// payloadRuleClauses are every clause about a worker Role's second rule. +var payloadRuleClauses = []string{ + "object.rules[1].apiGroups == ['coordination.fleet.datumapis.com']", + "object.rules[1].resources == ['machineallocationpayloads']", + "object.rules[1].verbs == ['get']", + payloadNamedClause, + payloadNameClause, + "!has(object.rules[1].nonResourceURLs)", +} + +// credentialName is the Redfish credential Role's Secret name clause. +const credentialName = "n.matches('^bmc-[a-f0-9]{20}$')" + +func binding(t *testing.T, namespace string, subjects ...string) *unstructured.Unstructured { + return object(t, fmt.Sprintf(`{"apiVersion":"rbac.authorization.k8s.io/v1","kind":"RoleBinding","metadata":{"name":"w-%s","namespace":%q},"subjects":[%s], + "roleRef":{"apiGroup":"rbac.authorization.k8s.io","kind":"Role","name":"w-%s"}}`, handoff, namespace, strings.Join(subjects, ","), handoff)) +} + +const ( + worker = `{"kind":"ServiceAccount","name":"w-` + handoff + `","namespace":"fleet-site"}` + otherWorker = `{"kind":"ServiceAccount","name":"w-op-other","namespace":"fleet-site"}` + kroAccount = `{"kind":"ServiceAccount","name":"kro","namespace":"kro-system"}` + kroUser = `{"kind":"User","apiGroup":"rbac.authorization.k8s.io","name":"` + kro + `"}` + everyone = `{"kind":"Group","apiGroup":"rbac.authorization.k8s.io","name":"system:serviceaccounts"}` + // workerElsewhere has the worker's name in kro's namespace. + workerElsewhere = `{"kind":"ServiceAccount","name":"w-` + handoff + `","namespace":"kro-system"}` +) + +// bindingTo binds the subjects to the named Role. +func bindingTo(t *testing.T, namespace, role string, subjects ...string) *unstructured.Unstructured { + return object(t, fmt.Sprintf(`{"apiVersion":"rbac.authorization.k8s.io/v1","kind":"RoleBinding","metadata":{"name":"w-%s","namespace":%q},"subjects":[%s], + "roleRef":{"apiGroup":"rbac.authorization.k8s.io","kind":"Role","name":%q}}`, handoff, namespace, strings.Join(subjects, ","), role)) +} + +type probe struct { + name string + send func(context.Context, client.Client) error + // policy and clauses name the clauses that refuse the probe. Several + // clauses are named only where each alone refuses it, or where one + // cannot be evaluated without the other. + policy string + clauses []string +} + +// check runs each probe: refused by the named rule as rendered, and +// admitted once that rule alone is removed. +func (e *env) check(probes []probe) { + for _, p := range probes { + e.t.Run(p.name, func(t *testing.T) { + if got := e.outcome(p.send, "policy"); got != "policy" { + t.Fatalf("as rendered: %s, want refused by policy", got) + } + var restores []func() + for _, clause := range p.clauses { + restores = append(restores, e.weaken(p.policy, clause)) + } + defer func() { + for i := len(restores) - 1; i >= 0; i-- { + restores[i]() + } + }() + if got := e.outcome(p.send, "admitted"); got != "admitted" { + t.Fatalf("without %q: %s, want admitted; the probe does not test those clauses", p.clauses, got) + } + }) + } +} + +// TestKroCanCreateOnlyPerOperationRBAC covers the four bounds on kro's RBAC +// writes at a site: Role shape, binding subject, no cluster-wide RBAC, and +// no widening of an existing Role. +func TestKroCanCreateOnlyPerOperationRBAC(t *testing.T) { + e := start(t, filepath.Join("config", "site", "base")) + identity := "fleet-site-kro-worker-identity" + + // The per-operation shapes are admitted. + for name, admitted := range map[string]*unstructured.Unstructured{ + "the worker Role": role(t, coordination, ownHandoff, ownPayload), + } { + if got := e.outcome(dryRun(admitted), "admitted"); got != "admitted" { + t.Fatalf("%s: %s", name, got) + } + } + + // 1. Role shape. Each Role is within kro's own grant, so only the + // policy can refuse it. + e.check([]probe{ + // Without a second rule, no clause about it can be evaluated, so all + // of them and the rule count refuse it together. + {"a Role without its payload rule", dryRun(role(t, coordination, ownHandoff)), identity, append([]string{sizeClause}, payloadRuleClauses...)}, + {"a Role reading another operation's payload", dryRun(role(t, coordination, ownHandoff, otherPayload)), identity, []string{payloadNameClause}}, + {"a Role reading every payload", dryRun(role(t, coordination, ownHandoff, anyPayload)), identity, []string{payloadNamedClause, payloadNameClause}}, + {"a Role with a third rule", dryRun(role(t, coordination, ownHandoff, ownPayload, ownHandoff)), identity, []string{sizeClause}}, + }) + // Shapes outside kro's own grant are refused by RBAC before admission. + for name, outside := range map[string]*unstructured.Unstructured{ + "a Role reading Secrets": role(t, coordination, ownHandoff, anyCredential), + "a Role listing payloads": role(t, coordination, ownHandoff, strings.Replace(ownPayload, `"verbs":["get"]`, `"verbs":["get","list"]`, 1)), + } { + if got := e.outcome(dryRun(outside), "rbac"); got != "rbac" { + t.Errorf("%s: %s, want refused by RBAC", name, got) + } + } + + // 2. Binding subject. The per-operation Role exists, so RBAC resolves + // it and only the subject is wrong. + if err := e.kro.Create(e.ctx, role(t, coordination, ownHandoff, ownPayload)); err != nil { + t.Fatal(err) + } + if got := e.outcome(dryRun(binding(t, coordination, worker)), "admitted"); got != "admitted" { + t.Fatalf("the worker binding: %s", got) + } + e.check([]probe{ + {"a binding to kro's own ServiceAccount", dryRun(binding(t, coordination, kroAccount)), identity, []string{subjectNameClause, subjectSpaceClause}}, + {"a binding to another operation's worker", dryRun(binding(t, coordination, otherWorker)), identity, []string{subjectNameClause}}, + {"a binding to a worker name in another namespace", dryRun(binding(t, coordination, workerElsewhere)), identity, []string{subjectSpaceClause}}, + {"a binding to kro as a user", dryRun(binding(t, coordination, kroUser)), identity, []string{subjectKindClause, subjectNameClause, subjectSpaceClause}}, + {"a binding to every ServiceAccount", dryRun(binding(t, coordination, everyone)), identity, []string{subjectKindClause, subjectNameClause, subjectSpaceClause}}, + {"a binding to its worker and kro", dryRun(binding(t, coordination, worker, kroAccount)), identity, []string{oneSubjectClause}}, + // kro holds every permission of its own Role, so RBAC admits binding + // a worker to it, and only the own-Role clause refuses it. + {"a binding of the worker to kro's own Role", dryRun(bindingTo(t, coordination, "fleet-site-kro-worker-rbac", worker)), identity, []string{ownRoleClause}}, + }) + + // 4. No widening: an update of kro's own Role passes the same rule. + widen := func(rules ...string) func(context.Context, client.Client) error { + return func(ctx context.Context, c client.Client) error { + current := role(t, coordination) + if err := c.Get(ctx, client.ObjectKeyFromObject(current), current); err != nil { + return err + } + updated := role(t, coordination, rules...) + updated.SetResourceVersion(current.GetResourceVersion()) + return c.Update(ctx, updated, client.DryRunAll) + } + } + e.check([]probe{ + {"widening the Role to every payload", widen(ownHandoff, anyPayload), identity, []string{payloadNamedClause, payloadNameClause}}, + {"widening the Role to another payload", widen(ownHandoff, otherPayload), identity, []string{payloadNameClause}}, + }) + + // 3. No cluster-wide RBAC. kro holds no such grant, so RBAC refuses it; + // the policy refuses it too, which a temporary grant shows. + clusterRole := object(t, `{"apiVersion":"rbac.authorization.k8s.io/v1","kind":"ClusterRole","metadata":{"name":"w-probe"},"rules":[`+anyCredential+`]}`) + clusterBinding := object(t, `{"apiVersion":"rbac.authorization.k8s.io/v1","kind":"ClusterRoleBinding","metadata":{"name":"w-probe"},"subjects":[`+kroAccount+`],"roleRef":{"apiGroup":"rbac.authorization.k8s.io","kind":"ClusterRole","name":"view"}}`) + for name, cluster := range map[string]*unstructured.Unstructured{"a ClusterRole": clusterRole, "a ClusterRoleBinding to kro": clusterBinding} { + if got := e.outcome(dryRun(cluster), "rbac"); got != "rbac" { + t.Errorf("%s: %s, want refused by RBAC", name, got) + } + } + e.apply(object(t, `{"apiVersion":"rbac.authorization.k8s.io/v1","kind":"ClusterRole","metadata":{"name":"probe-cluster-rbac"}, + "rules":[{"apiGroups":["rbac.authorization.k8s.io"],"resources":["clusterroles","clusterrolebindings"],"verbs":["create","escalate","bind"]},{"apiGroups":[""],"resources":["secrets"],"verbs":["get"]}]}`)) + e.apply(object(t, `{"apiVersion":"rbac.authorization.k8s.io/v1","kind":"ClusterRoleBinding","metadata":{"name":"probe-cluster-rbac"}, + "subjects":[`+kroAccount+`],"roleRef":{"apiGroup":"rbac.authorization.k8s.io","kind":"ClusterRole","name":"probe-cluster-rbac"}}`)) + e.check([]probe{ + {"a ClusterRole, with a grant", dryRun(clusterRole), "fleet-site-kro-cluster-rbac", []string{clusterRBACClause}}, + {"a ClusterRoleBinding, with a grant", dryRun(clusterBinding), "fleet-site-kro-cluster-rbac", []string{clusterRBACClause}}, + }) +} + +// job is a worker Job for the handoff, as the graph renders it, with one +// change applied to its container. +func job(t *testing.T, change string) *unstructured.Unstructured { + container := `"name":"worker","image":"site-image","command":["fleet-multiplane","site-worker","--handoff","` + handoff + `","--cell","cell-example"], + "env":[{"name":"FLEET_SITE_ENROLLMENT","valueFrom":{"configMapKeyRef":{"name":"fleet-site-enrollment","key":"enrollment.json"}}}], + "securityContext":{"allowPrivilegeEscalation":false,"capabilities":{"drop":["ALL"]}}` + if change != "" { + container = change + } + return object(t, `{"apiVersion":"batch/v1","kind":"Job","metadata":{"name":"w-`+handoff+`","namespace":"fleet-site","labels":{"fleet.datumapis.com/handoff":"`+handoff+`"}}, + "spec":{"template":{"spec":{"restartPolicy":"Never","serviceAccountName":"w-`+handoff+`","containers":[{`+container+`}]}}}}`) +} + +// TestKroJobsReadNoSecretAndRunOnlyTheWorker: the kubelet resolves a Pod's +// Secret references whatever its ServiceAccount may read, so a Job kro +// writes takes environment only from literals and the site enrollment, and +// runs only the site worker for its own handoff. +func TestKroJobsReadNoSecretAndRunOnlyTheWorker(t *testing.T) { + e := start(t, filepath.Join("config", "site", "base")) + jobs := "fleet-site-kro-worker-jobs" + safe := `"securityContext":{"allowPrivilegeEscalation":false,"capabilities":{"drop":["ALL"]}}` + command := func(args ...string) string { + quoted := make([]string, len(args)) + for i, a := range args { + quoted[i] = fmt.Sprintf("%q", a) + } + return `"name":"worker","image":"site-image","command":[` + strings.Join(quoted, ",") + `],` + safe + } + if got := e.outcome(dryRun(job(t, "")), "admitted"); got != "admitted" { + t.Fatalf("the worker Job: %s", got) + } + e.check([]probe{ + {"a Job taking environment from a Secret", dryRun(job(t, command("fleet-multiplane", "site-worker", "--handoff", handoff, "--cell", "c")+`,"envFrom":[{"secretRef":{"name":"fleet-site-bmc-credentials"}}]`)), jobs, []string{envClause}}, + {"a Job reading one Secret key", dryRun(job(t, command("fleet-multiplane", "site-worker", "--handoff", handoff, "--cell", "c")+`,"env":[{"name":"X","valueFrom":{"secretKeyRef":{"name":"fleet-site-bmc-credentials","key":"password"}}}]`)), jobs, + []string{"has(e.valueFrom.configMapKeyRef) && e.valueFrom.configMapKeyRef.name == 'fleet-site-enrollment'", secretKeyClause}}, + {"a Job running another program", dryRun(job(t, command("sh", "site-worker", "--handoff", handoff, "--cell", "c"))), jobs, []string{commandClause}}, + {"a Job for another handoff", dryRun(job(t, command("fleet-multiplane", "site-worker", "--handoff", "op-other", "--cell", "c"))), jobs, []string{ownHandoffClause}}, + {"a Job with arguments", dryRun(job(t, command("fleet-multiplane", "site-worker", "--handoff", handoff, "--cell", "c")+`,"args":["--extra"]`)), jobs, []string{argsClause}}, + }) +} + +// TestRedfishCredentialRolesAreOneGetOnOneSecret covers the Redfish site's +// credential Roles: only get on one named BMC credential Secret. +func TestRedfishCredentialRolesAreOneGetOnOneSecret(t *testing.T) { + e := start(t, filepath.Join("config", "site", "redfish", "base")) + identity := "fleet-site-kro-worker-identity" + if got := e.outcome(dryRun(role(t, credentials, ownCredential)), "admitted"); got != "admitted" { + t.Fatalf("the credential Role: %s", got) + } + if got := e.outcome(dryRun(role(t, coordination, ownHandoff, ownPayload)), "admitted"); got != "admitted" { + t.Fatalf("the worker Role: %s", got) + } + e.check([]probe{ + {"a credential Role with a second rule", dryRun(role(t, credentials, ownCredential, ownCredential)), identity, []string{credentialSize}}, + {"a credential Role naming another Secret", dryRun(role(t, credentials, strings.Replace(ownCredential, "bmc-0123456789abcdef0123", "fleet-site-bmc-credentials", 1))), identity, []string{credentialName}}, + {"a worker Role reading every payload", dryRun(role(t, coordination, ownHandoff, anyPayload)), identity, []string{payloadNamedClause, payloadNameClause}}, + // kro holds get on every BMC credential to grant one, so only the + // own-Role clause refuses binding a worker to kro's Role. + {"a binding of the worker to kro's credential Role", dryRun(bindingTo(t, credentials, "fleet-site-kro-worker-credentials", worker)), identity, []string{ownRoleClause}}, + }) + if got := e.outcome(dryRun(role(t, credentials, anyCredential)), "rbac"); got != "policy" && got != "rbac" { + t.Errorf("a credential Role reading every Secret: %s", got) + } +}