From f51bad24e90bbf8c1f6af78ed9d5531010947107 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 25 Nov 2026 14:32:28 -0600 Subject: [PATCH 1/7] feat(coordination): Carry bootstrap payloads to the cell as their own kind Federation refused bootstrap data. The hub now writes each payload as a MachineAllocationPayload beside its handoff, before the handoff that names it, and deletes it when the coordinator answers the result, which removes the cell's copy. A worker that runs before the payload arrives sends nothing, stores no result, and is retried. The payload is its own kind, not a Secret. Karmada's member identity watches every propagated kind cluster-wide, and the lab BMC's credentials are Secrets, so a Secret transport would have exposed them. On this kind, the member identity, kro and the worker each hold only what they need: kro holds get to grant each worker get on its one payload, and holds no escalate or bind. The worker identity policy admits only the per-operation Role and binding shapes, on create and update, and a new policy refuses any cluster-wide RBAC kro writes. A test against a real API server runs each refused shape as kro and shows it is admitted once the one rule it tests is removed. The harness probes the same shapes on the live cell. Also add the NoCloud seed archive a network boot will load. Co-Authored-By: Claude Opus 5.5 --- cmd/fleet-multiplane/main.go | 3 + .../cell-federation/federation.yaml | 4 +- config/multiplane/coordination/crd.yaml | 41 ++ config/multiplane/karmada-api/hub-rbac.yaml | 5 + .../multiplane/karmada-members/members.yaml | 7 + config/site/base/kro.yaml | 48 ++- config/site/graph/rgd.yaml | 8 +- config/site/redfish/base/kustomization.yaml | 16 +- hack/multiplane/k8s_evidence.py | 11 +- hack/multiplane/test-harness.sh | 7 +- hack/multiplane/test-k8s-evidence.py | 4 +- hack/multiplane/verify-rbac.py | 55 ++- internal/coordination/cell.go | 66 +++ internal/coordination/transport.go | 88 +++- internal/coordination/transport_test.go | 144 ++++++- internal/site/seed.go | 82 ++++ internal/site/seed_test.go | 45 ++ internal/sitepolicy/policy_test.go | 383 ++++++++++++++++++ 18 files changed, 972 insertions(+), 45 deletions(-) create mode 100644 internal/site/seed.go create mode 100644 internal/site/seed_test.go create mode 100644 internal/sitepolicy/policy_test.go diff --git a/cmd/fleet-multiplane/main.go b/cmd/fleet-multiplane/main.go index ad806389..1f93fe43 100644 --- a/cmd/fleet-multiplane/main.go +++ b/cmd/fleet-multiplane/main.go @@ -113,6 +113,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 9ed82ed9..872dccc6 100644 --- a/config/multiplane/coordination/crd.yaml +++ b/config/multiplane/coordination/crd.yaml @@ -44,6 +44,47 @@ spec: # The Device's BMC credential Secret at the site, derived from # the Device; the assignment's worker may get only it. credential: {type: string, pattern: '^bmc-[a-f0-9]{20}$'} + # 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..641b5f54 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. It lists none. + - apiGroups: [coordination.fleet.datumapis.com] + resources: [machineallocationpayloads] + verbs: [get, 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..a11d39ea 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 @@ -158,11 +165,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 +188,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 fd996eab..39998632 100644 --- a/config/site/graph/rgd.yaml +++ b/config/site/graph/rgd.yaml @@ -92,7 +92,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: @@ -122,6 +124,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 e1697134..b876a2f9 100644 --- a/config/site/redfish/base/kustomization.yaml +++ b/config/site/redfish/base/kustomization.yaml @@ -34,7 +34,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] @@ -46,7 +46,13 @@ patches: (has(object.rules) && 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}$')))) : - (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, or get on one named BMC credential + (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 diff --git a/hack/multiplane/k8s_evidence.py b/hack/multiplane/k8s_evidence.py index 2d1c024a..5aad48ba 100644 --- a/hack/multiplane/k8s_evidence.py +++ b/hack/multiplane/k8s_evidence.py @@ -117,7 +117,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'), @@ -127,7 +129,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 244f8f04..27ce9116 100755 --- a/hack/multiplane/test-harness.sh +++ b/hack/multiplane/test-harness.sh @@ -250,8 +250,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 702327b0..50694224 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': []}) @@ -69,7 +71,7 @@ def emit(v): print(json.dumps(v)); sys.exit(0) if kind == 'pv': emit({'metadata': {'uid': 'pv-uid'}, 'spec': {'persistentVolumeReclaimPolicy': 'Retain'}}) if kind == 'machine': emit(world['machines'][config.split('/')[-2]]) -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 == 'machineallocationhandoff': emit({'metadata': {'name': name}, 'spec': {}, 'status': world.get('statuses', {}).get(name)}) sys.exit(1) diff --git a/hack/multiplane/verify-rbac.py b/hack/multiplane/verify-rbac.py index 6998a8b8..00040319 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' if redfish: @@ -64,7 +67,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)] if redfish else []) bad=[' '.join(a) for a in allowed if not can(*a)]+['denied '+' '.join(a) for a in denied if can(*a)] if bad:raise SystemExit('kro RBAC is not the narrowed grant: '+'; '.join(bad)) @@ -81,7 +86,11 @@ def job(**change): (c if k in ('image','securityContext','env','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}, @@ -90,7 +99,19 @@ 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),'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 @@ -123,10 +144,36 @@ 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'} +outside_grant={'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. +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'})}} + 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/internal/coordination/cell.go b/internal/coordination/cell.go index 8409bc54..274c7c10 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" @@ -49,6 +51,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) || spec.Credential != site.CredentialSecretName(assignment.Device) { 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 } @@ -67,10 +78,65 @@ func (c *Cell) Work(ctx context.Context, name string, runner *site.Runner) error 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 + } + if payload, err := runner.Payloads.Get(ctx, assignment); err != nil || 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 + } + encoded, _, _ := unstructured.NestedString(object.Object, "spec", "payload") + data, err := base64.StdEncoding.DecodeString(encoded) + if err != nil { + return nil, err + } + var payload site.Payload + if err := json.Unmarshal(data, &payload); err != nil { + return nil, err + } + return &payload, nil +} + +func (HandoffPayloads) Delete(context.Context, site.Assignment) error { return nil } + +func (HandoffPayloads) Prune(context.Context, string) error { return nil } + // Publish writes the observation of one handoff: the Device's stored fences // and, for an assignment, its stored result. It deletes the site's copy of a // result the coordinator answered. diff --git a/internal/coordination/transport.go b/internal/coordination/transport.go index ef6db5ab..8912f4f2 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" @@ -61,6 +66,11 @@ type Spec struct { // site, derived from the Device. The site grants the assignment's worker // get on exactly that Secret. A report handoff has none. Credential string `json:"credential,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. @@ -101,6 +111,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] } @@ -184,24 +205,64 @@ 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") +// CarriesPayloads is true: the hub delivers a payload as its own object +// beside the handoff. +func (h *Hub) CarriesPayloads() bool { return true } +// 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 { - return ErrBootstrapUnsupported + spec := Spec{Cell: h.Cell, Device: assignment.Device, Credential: site.CredentialSecretName(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), Credential: site.CredentialSecretName(assignment.Device)}) + spec.AssignmentJSON = string(data) + _, err = h.ensure(ctx, AssignmentName(assignment), RoleAssignment, spec) return err } +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 @@ -266,9 +327,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 8acf7726..905b3d49 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" @@ -33,7 +35,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 +77,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 { @@ -297,20 +333,104 @@ 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 +} + +// 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) } - if _, ok := any(f.hub).(interface{ CarriesPayloads() bool }); ok { - t.Fatal("the hub claims to carry payloads") +} + +// 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 Secret": {Cell: cellName, Device: device, AssignmentJSON: string(data), Credential: site.CredentialSecretName(device), Payload: "bmc-0123456789abcdef0123"}, + "no Secret": {Cell: cellName, Device: device, AssignmentJSON: string(data), Credential: site.CredentialSecretName(device)}, + } { + 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) + } + }) } } diff --git a/internal/site/seed.go b/internal/site/seed.go new file mode 100644 index 00000000..68bcc7de --- /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, and the +// installed system's first boot reads it. +const SeedDirectory = "fleet-bootstrap" + +// BootstrapMarker starts the console line in which the installed system, +// on its first disk boot, reports the digest of the bootstrap data it +// found: "FLEET-BOOTSTRAP::sha256:". The guest recomputes it +// from the salt and data on its own disk, so the line proves receipt +// without printing the data or an unsalted hash of it. +const BootstrapMarker = "FLEET-BOOTSTRAP:" + +// BootstrapLine is the console line a guest 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 guest +// 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/sitepolicy/policy_test.go b/internal/sitepolicy/policy_test.go new file mode 100644 index 00000000..2a53ba42 --- /dev/null +++ b/internal/sitepolicy/policy_test.go @@ -0,0 +1,383 @@ +// 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) + } + 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 the validation whose message starts with prefix by one +// that always passes, and returns a function that restores the policy. +func (e *env) weaken(name, prefix string) func() { + e.t.Helper() + policy := e.policy(name) + original := policy.DeepCopy() + validations, _, _ := unstructured.NestedSlice(policy.Object, "spec", "validations") + found := false + for index, validation := range validations { + rule := validation.(map[string]any) + if strings.HasPrefix(fmt.Sprint(rule["message"]), prefix) { + rule["expression"], found = "true", true + validations[index] = rule + } + } + if !found { + e.t.Fatalf("%s has no validation %q", name, prefix) + } + _ = 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) + original.SetResourceVersion(current.GetResourceVersion()) + if err := e.admin.Update(e.ctx, original); 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"]}` + roleRuleText = "a worker Role may grant only" + bindingRule = "a worker RoleBinding may bind only" + clusterRBACMsg = "kro may not write cluster-wide RBAC" +) + +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"}` +) + +type probe struct { + name string + send func(context.Context, client.Client) error + // policy and rule name the one validation that must refuse the probe. + policy, rule 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) + } + restore := e.weaken(p.policy, p.rule) + defer restore() + if got := e.outcome(p.send, "admitted"); got != "admitted" { + t.Fatalf("without %q: %s, want admitted; the probe does not test that rule", p.rule, 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{ + {"a Role without its payload rule", dryRun(role(t, coordination, ownHandoff)), identity, roleRuleText}, + {"a Role reading another operation's payload", dryRun(role(t, coordination, ownHandoff, otherPayload)), identity, roleRuleText}, + {"a Role reading every payload", dryRun(role(t, coordination, ownHandoff, anyPayload)), identity, roleRuleText}, + {"a Role with a third rule", dryRun(role(t, coordination, ownHandoff, ownPayload, ownHandoff)), identity, roleRuleText}, + }) + // 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, bindingRule}, + {"a binding to another operation's worker", dryRun(binding(t, coordination, otherWorker)), identity, bindingRule}, + {"a binding to kro as a user", dryRun(binding(t, coordination, kroUser)), identity, bindingRule}, + {"a binding to every ServiceAccount", dryRun(binding(t, coordination, everyone)), identity, bindingRule}, + {"a binding to its worker and kro", dryRun(binding(t, coordination, worker, kroAccount)), identity, bindingRule}, + }) + + // 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, roleRuleText}, + {"widening the Role to another payload", widen(ownHandoff, otherPayload), identity, roleRuleText}, + }) + + // 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", clusterRBACMsg}, + {"a ClusterRoleBinding, with a grant", dryRun(clusterBinding), "fleet-site-kro-cluster-rbac", clusterRBACMsg}, + }) +} + +// 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, roleRuleText}, + {"a credential Role naming another Secret", dryRun(role(t, credentials, strings.Replace(ownCredential, "bmc-0123456789abcdef0123", "fleet-site-bmc-credentials", 1))), identity, roleRuleText}, + {"a worker Role reading every payload", dryRun(role(t, coordination, ownHandoff, anyPayload)), identity, roleRuleText}, + }) + if got := e.outcome(dryRun(role(t, credentials, anyCredential)), "rbac"); got != "policy" && got != "rbac" { + t.Errorf("a credential Role reading every Secret: %s", got) + } +} From 6542181c6f1ee279721b0e3703aa4d8d175d3ab1 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 25 Nov 2026 14:51:23 -0600 Subject: [PATCH 2/7] feat(site): Hand bootstrap data to the guest and prove it arrived The local VM and Redfish workers refused bootstrap data. The worker now renders the verified payload as a NoCloud seed archive on the operation's boot admission. The boot service serves it as a second initrd only while the admission is open, and the admission drops it when it closes. The installer copies it to the disk, and on its first disk boot the installed system prints the salted digest of what it found. The worker requires exactly that line before it reports success, and the evidence carries the digest. A direct kernel boot refuses bootstrap data. Consumer A's multi-plane install carries synthetic bootstrap data, and the evidence checks the guest's report and that no payload copy remains. The hub now deletes every payload no delivered operation needs after each complete coordinator pass, so a payload of an operation that ended without a collected result does not outlive it. A worker retries only while its payload is missing, and refuses one that does not decode. kro's Job policy refuses environment from Secrets and any program but the site worker for its own handoff. The policy test weakens the exact clauses each refused shape names, including binding a worker to kro's own Role, and waits for the policies to take effect before counting an admission. Co-Authored-By: Claude Opus 5.5 --- config/multiplane/karmada-api/hub-rbac.yaml | 4 +- config/site/base/kro.yaml | 13 ++ docs/development/README.md | 10 +- docs/development/device-custody.md | 4 +- docs/development/machine-images.md | 45 ++++- docs/operations/redfish-lab.md | 6 +- docs/operations/site-execution.md | 5 +- hack/local-vm/boot | 7 + hack/local-vm/init | 10 ++ hack/multiplane/evidence.py | 53 +++++- hack/multiplane/milo.py | 8 +- hack/multiplane/verify-rbac.py | 20 ++- internal/coordination/cell.go | 12 +- internal/coordination/transport.go | 26 +++ internal/coordination/transport_test.go | 94 ++++++++++ internal/delivery/delivery.go | 42 +++++ internal/delivery/delivery_test.go | 26 +++ internal/multiplane/runner.go | 12 +- internal/multiplane/seed.go | 18 +- internal/site/redfishwork/boot.go | 15 +- internal/site/redfishwork/kinds.go | 53 +++++- internal/site/redfishwork/kinds_test.go | 82 ++++++++- internal/site/vmwork/boot.go | 25 ++- internal/site/vmwork/kinds.go | 47 ++++- internal/site/vmwork/kinds_test.go | 149 +++++++++++++++ internal/sitepolicy/policy_test.go | 190 +++++++++++++++----- 26 files changed, 875 insertions(+), 101 deletions(-) diff --git a/config/multiplane/karmada-api/hub-rbac.yaml b/config/multiplane/karmada-api/hub-rbac.yaml index 641b5f54..10f9732d 100644 --- a/config/multiplane/karmada-api/hub-rbac.yaml +++ b/config/multiplane/karmada-api/hub-rbac.yaml @@ -12,10 +12,10 @@ rules: # 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. It lists none. + # and deletes it once the result is answered or the operation ends. - apiGroups: [coordination.fleet.datumapis.com] resources: [machineallocationpayloads] - verbs: [get, create, delete] + verbs: [get, list, create, delete] --- apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding diff --git a/config/site/base/kro.yaml b/config/site/base/kro.yaml index a11d39ea..c75e6984 100644 --- a/config/site/base/kro.yaml +++ b/config/site/base/kro.yaml @@ -127,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 diff --git a/docs/development/README.md b/docs/development/README.md index 021a5dfd..0a5e7132 100644 --- a/docs/development/README.md +++ b/docs/development/README.md @@ -41,9 +41,10 @@ smoke verifies it. The end-to-end failure scenarios (Increment D) are proposed. [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 sealed bootstrap store and its +delivery through federation to the local VM and Redfish guests are +**implemented**; the multi-plane runs that prove the guest receives the data +are pending. 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 @@ -793,7 +794,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 43d1cb1b..ccf346d9 100644 --- a/docs/development/device-custody.md +++ b/docs/development/device-custody.md @@ -374,7 +374,7 @@ event. - The capacity projector stays unwired (O1), so the synthetic fixtures still write `Prepared`, `Healthy` and `Available`. -- Bootstrap data reaches only the simulator site. See +- Bootstrap data reaches every site through its sealed store. See [OS images and bootstrap data](machine-images.md). - `DeviceRecovery` needs no second person. @@ -920,7 +920,7 @@ Increment B's site tests run with `go test -race ./internal/site/...`: | One worker per assignment, final results, shutdown at each stage, an older worker that does not stop, a fence raised between journal and send | `TestARedeliveryWhileTheSameOperationRunsStoresNothing`, `TestACopyWaitingForTheLockReturnsTheStoredResult`, `TestAStoredResultSurvivesARedelivery`, `TestAWorkerStoppedFromOutsideStoresNoResult`, `TestAShutdownWhileWaitingForTheRunLockStoresNothing`, `TestAShutdownDuringTheChecksStoresNothing`, `TestANewerAssignmentThatCannotStopTheOlderWorkerSendsNothing`, `TestALostLockWithJournaledStepsIsUnknown`, `TestAFenceRaisedBetweenJournalAndSendStopsTheStep` | | Per-Device credentials, the fence report | `TestSecretCredentialsUseThePerDeviceContract`, `TestReportGivesTheCoordinatorSeenAndStoppedFences` | | Step payloads, the start-by window, identity separate from capabilities, a resumed worker reporting unknown | `TestAStepPayloadIsJournaledAndReadBack`, `TestALateStartIsStaleAndSendsNothing`, `TestIdentityIsSeparateFromInstallCapabilities`, `TestAResumedWorkerThatCannotReachTheBMCReportsUnknown` | -| Install and wipe against a simulated BMC, one power-on per phase after an interruption in either phase, the power-off bound, fenced boot admission, bootstrap refused 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 installed system reports, bootstrap refused without a payload | `TestAWorkerInterruptedInTheDiskPhaseResumes`, `TestAServerThatNeverPowersOffEndsTheStep`, `TestInstallationRunsBothPhasesWithOneOnEach`, `TestWipeChecksTheEnrolledDisk`, `TestAnInterruptedWorkerResumesWithoutASecondOn`, `TestOnlyTheCurrentFenceHasAnOpenBootAdmission`, `TestBootstrapDataReachesTheInstalledSystemOverRedfish`, `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 41853f80..f920b894 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: lab delivery | Federation carries a payload to the cell, the local VM and Redfish boot services hand it to the installer, and the installed system reports it | **Implemented**, verified by unit tests and tests against a real API server. The local VM and Redfish multi-plane runs are pending. | ## What increment 1 adds @@ -112,6 +112,39 @@ proposal's API names are provisional. Each piece below is marked ships, resolves inheritance, and fails if any other role can read it or holds a wildcard. +## What increment 3 adds + +- **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, and the admission + drops it when it closes. The installer copies it to the disk, puts the user + data where NoCloud reads it and the keys in the default user's + `authorized_keys`. On its first disk boot the installed system prints the + salted digest of what it found, and the worker requires exactly that line + before it reports success. A direct kernel boot, which has one initrd, + refuses bootstrap data. + ## Not implemented yet - The validating webhook that rejects image writes from anyone but the @@ -122,10 +155,10 @@ proposal's API names are provisional. Each piece below is marked - Artifact mirroring by digest from a provider registry. Each lab site holds one pinned image and serves only that one. - Firmware mode from BMC discovery. Lab fixtures write it on the capacity. -- Federation delivery of bootstrap payloads to a cell, and handing them to a - local VM or Redfish server. Admission refuses such an operation with - `BootstrapUnsupported` before the Device's fence moves. - The Milo check that the Installation's creator can read the bootstrap Secret. The lab compositions read it with their own identity. -- Encryption at rest for `SealedPayload` and an audit policy that omits its - bodies. +- 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. +- HTTPS for the boot service. The lab serves the seed over HTTP on its + isolated provisioning bridge. diff --git a/docs/operations/redfish-lab.md b/docs/operations/redfish-lab.md index 3e990f8e..017650e8 100644 --- a/docs/operations/redfish-lab.md +++ b/docs/operations/redfish-lab.md @@ -393,9 +393,11 @@ 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 installed system must report by its + salted digest, and bootstrap data refused when the site holds no payload (`TestInstallationRunsBothPhasesWithOneOnEach`, `TestWipeChecksTheEnrolledDisk`, - `TestBootstrapIsRefusedAtTheSiteToo`); + `TestBootstrapDataReachesTheInstalledSystemOverRedfish`, + `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 504f60d4..685f05ce 100644 --- a/docs/operations/site-execution.md +++ b/docs/operations/site-execution.md @@ -323,8 +323,9 @@ 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 carries an operation's payload as its own +`MachineAllocationPayload` beside the handoff, and the worker may get only +its own. 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/boot b/hack/local-vm/boot index b40c21ec..c9bf333b 100644 --- a/hack/local-vm/boot +++ b/hack/local-vm/boot @@ -4,6 +4,13 @@ mount -t proc proc /proc 2>/dev/null || true exec >/dev/ttyS0 2>&1 # Only the disk-root boot emits completion; installer completion is insufficient. if grep -Eq '^/dev/vda1 / ext4 ' /proc/mounts && test -s /fleet-receipt; then + # Report the bootstrap data this system found on its own disk, by the + # salted digest only, and only if the installer put it where the image + # reads it. + if test -s /fleet-bootstrap/data && cmp -s /fleet-bootstrap/authorized_keys /root/.ssh/authorized_keys && + cmp -s /fleet-bootstrap/user-data /var/lib/cloud/seed/nocloud/user-data; then + printf 'FLEET-BOOTSTRAP:%s:sha256:%s\n' "$(cat /fleet-receipt)" "$(cat /fleet-bootstrap/salt /fleet-bootstrap/data | sha256sum | cut -d' ' -f1)" + fi printf 'FLEET-DISK-BOOT:%s\n' "$(cat /fleet-receipt)" fi sync diff --git a/hack/local-vm/init b/hack/local-vm/init index a4303d6b..28087f20 100644 --- a/hack/local-vm/init +++ b/hack/local-vm/init @@ -45,6 +45,16 @@ mount --bind /dev /target/dev mount --bind /proc /target/proc mount --bind /sys /target/sys printf '%s\n' "$receipt" > /target/fleet-receipt +# Bootstrap data arrives as a second initrd under /fleet-bootstrap, which the +# copy above already put on the disk. Install it where the image reads it on +# first boot: the NoCloud seed, and the default user's SSH keys. +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 /target/fleet-bootstrap + 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-*) diff --git a/hack/multiplane/evidence.py b/hack/multiplane/evidence.py index 318f0767..7e390407 100755 --- a/hack/multiplane/evidence.py +++ b/hack/multiplane/evidence.py @@ -166,6 +166,30 @@ def custody_evidence(store, ops, provider, a, b): return record +def bootstrap_line(provider, o, receipt): + """The console line the installed system must print for an install's + bootstrap data, or None. The operation's evidence must name the same + salted digest the guest reports.""" + p = provider[o['operation']] + digest = (p['spec'].get('bootstrap') or {}).get('digest') + if not digest: + return None + if ((p.get('status') or {}).get('evidence') or {}).get('bootstrap') != digest: + fail('%s succeeded without evidence of its bootstrap data' % p['metadata']['name']) + return 'FLEET-BOOTSTRAP:%s:%s' % (receipt, digest) + + +def bootstrap_gone(): + """No copy of a payload remains once the lifecycle ends: not in the + provider's sealed store, and not at the cell, which federation clears + when the hub deletes its copy.""" + config = s / 'provider' / 'bootstrap-project.json' + sealed = json.loads(out('kubectl', '--kubeconfig', str(config), '--request-timeout=30s', '-n', 'fleet-provider', 'get', 'sealedpayloads', '-o', 'json'))['items'] + delivered = kget('-n', 'fleet-coordination', 'get', 'machineallocationpayloads')['items'] + if sealed or delivered: + fail('bootstrap payload copies remain: %d sealed, %d at the cell' % (len(sealed), len(delivered))) + + def boot_record(raw, collection, name): p = raw / 'site' / 'devices' / harness.device_dir().rsplit('/', 1)[1] / collection / (name + '.json') return json.loads(p.read_text()) if p.exists() else {} @@ -183,7 +207,7 @@ def libvirt_provider(): installs = [o for o in ops if o['kind'] == 'DeviceInstallation'] wipes = [o for o in ops if o['kind'] == 'DeviceWipe'] - receipts, starts = [], {} + receipts, starts, bootstrapped = [], {}, [] for o in installs: uid = o['operation'] directory = raw / 'vm' / harness.key(harness.DEVICE) / harness.key(uid) @@ -192,9 +216,16 @@ def libvirt_provider(): fail('boot admission not closed at the install fence') log = raw / 'boot-evidence' / harness.key(uid) / 'boot-delivery.log' written = log.read_text() if log.exists() else '' - for name in ('boot.ipxe', 'kernel', 'installer.gz'): + seeded = bootstrap_line(provider, o, boot['receipt']) + for name in ('boot.ipxe', 'kernel', 'installer.gz') + (('seed.cpio',) if seeded else ()): if not any('write-complete ' + name + ' bytes=' in line for line in written.splitlines()): fail('missing completed broker write for ' + name) + if seeded: + disk_log = directory / 'disk.log' + lines = [line.strip() for line in disk_log.read_text(errors='replace').splitlines()] if disk_log.exists() else [] + if lines.count(seeded) != 1 or sum(1 for l in lines if l.startswith('FLEET-BOOTSTRAP:')) != 1: + fail('the installed system did not report exactly the admitted bootstrap data') + bootstrapped.append(uid) for filename, marker in (('installer.log', 'FLEET-INSTALLED:'), ('disk.log', 'FLEET-DISK-BOOT:')): p = directory / filename lines = [line.strip() for line in p.read_text(errors='replace').splitlines()] if p.exists() else [] @@ -219,6 +250,10 @@ def libvirt_provider(): starts[uid] = {'qemuStarts': len(blocks), 'networkInstallerStarts': len(network), 'diskOnlyStarts': len(disk_only)} if len(blocks) != 2 or len(network) != 1 or len(disk_only) != 1 or blocks.index(network[0]) != 0: fail('expected exactly one network installer start followed by one disk-only start, got %s' % starts[uid]) + # Consumer A's install carries bootstrap data; the guest proved it. + if len(bootstrapped) != 1 or bootstrapped[0] != ops[0]['operation']: + fail('expected consumer A\'s install, and only it, to report bootstrap data; got %s' % bootstrapped) + bootstrap_gone() # The release wipes deleted every installation disk of the Device. if list((raw / 'vm').rglob('disk.raw')): fail('a wiped Device still has an installation disk') @@ -252,12 +287,16 @@ def redfish_provider(): if a['systemID'] != 'System-1' or a['console'] != 'target-a.log': fail('the allocated Device is not enrolled as lab target A') console = [l.strip() for l in (raw / 'lab-console' / 'target-a.log').read_text(errors='replace').splitlines()] - expected, receipts = [], [] + expected, receipts, bootstrapped = [], [], [] for o in ops: boot = boot_record(raw, 'boot', o['operation']) if not boot.get('closed') or boot.get('phase') or boot.get('fence') != o['fence'] or boot.get('mac') != a['mac'].lower(): fail('an operation did not keep a closed boot admission for target A at its fence') - want = ['FLEET-INSTALLED:' + boot['receipt'], 'FLEET-DISK-BOOT:' + boot['receipt']] if o['kind'] == 'DeviceInstallation' else ['FLEET-WIPED:%s:%d' % (boot['receipt'], a['diskBytes'])] + seeded = bootstrap_line(provider, o, boot['receipt']) if o['kind'] == 'DeviceInstallation' else None + if seeded: + bootstrapped.append(o['operation']) + # The installed system prints its bootstrap report just before its disk receipt. + want = (['FLEET-INSTALLED:' + boot['receipt']] + ([seeded] if seeded else []) + ['FLEET-DISK-BOOT:' + boot['receipt']]) if o['kind'] == 'DeviceInstallation' else ['FLEET-WIPED:%s:%d' % (boot['receipt'], a['diskBytes'])] for line in want: if console.count(line) != 1: fail('expected exactly one exact console receipt %s for %s' % (line.split(':')[0], o['kind'])) @@ -266,11 +305,15 @@ def redfish_provider(): 'receipts': [line.split(':')[0] for line in want], 'receiptSHA256': hashlib.sha256(boot['receipt'].encode()).hexdigest()}) log = raw / 'boot-evidence' / harness.key(o['operation']) / 'boot-delivery.log' written = log.read_text() if log.exists() else '' - for name in ('boot.ipxe', 'kernel', 'installer.gz'): + for name in ('boot.ipxe', 'kernel', 'installer.gz') + (('seed.cpio',) if seeded else ()): if 'write-complete ' + name + ' bytes=' not in written: fail('missing completed boot delivery of %s for %s' % (name, o['kind'])) if expected != sorted(expected) or sum(1 for l in console if l.startswith('FLEET-')) != len(expected): fail('console receipts are out of order or include another operation') + # Consumer A's install carries bootstrap data, consumer B's does not. + if len(bootstrapped) != 1 or bootstrapped[0] != ops[0]['operation']: + fail('expected consumer A\'s install, and only it, to report bootstrap data; got %s' % bootstrapped) + bootstrap_gone() if sum(1 for l in console if l.startswith('+ sfdisk /dev/vda')) != 2: fail('the installer partitioned the target disk other than once per install') qemu = (raw / 'libvirt-qemu' / 'fleet-lab-target-a.log').read_text(errors='replace') diff --git a/hack/multiplane/milo.py b/hack/multiplane/milo.py index c3145090..0cdb9554 100755 --- a/hack/multiplane/milo.py +++ b/hack/multiplane/milo.py @@ -106,6 +106,12 @@ def wait(fn,seconds,what): apply(d/'bootstrap.json',{'apiVersion':'rbac.authorization.k8s.io/v1','kind':'ClusterRoleBinding','metadata':{'name':'fleet-management'},'roleRef':{'apiGroup':'rbac.authorization.k8s.io','kind':'ClusterRole','name':'fleet-management'},'subjects':[{'kind':'User','name':'management'}]}) if role!='provider': apply(d/'bootstrap.json',{'apiVersion':'v1','kind':'Namespace','metadata':{'name':'default'}}) - apply(d/'bootstrap.json',{'apiVersion':'rbac.authorization.k8s.io/v1','kind':'Role','metadata':{'name':'customer','namespace':'default'},'rules':[{'apiGroups':['metal.datumapis.com'],'resources':['machines','installations'],'verbs':['get','list','watch','create','delete']}]}) + apply(d/'bootstrap.json',{'apiVersion':'rbac.authorization.k8s.io/v1','kind':'Role','metadata':{'name':'customer','namespace':'default'},'rules':[{'apiGroups':['metal.datumapis.com'],'resources':['machines','installations'],'verbs':['get','list','watch','create','delete']}, + # The customer stores its own bootstrap data. + {'apiGroups':[''],'resources':['secrets'],'verbs':['get','create','delete']}]}) + # The Metal provider reads only the one bootstrap Secret consumer A's + # Installation names, standing in for the creator's authority. + apply(d/'bootstrap.json',{'apiVersion':'rbac.authorization.k8s.io/v1','kind':'Role','metadata':{'name':'fleet-bootstrap-reader','namespace':'default'},'rules':[{'apiGroups':[''],'resources':['secrets'],'resourceNames':['debian-pxe-bootstrap'],'verbs':['get']}]}) + apply(d/'bootstrap.json',{'apiVersion':'rbac.authorization.k8s.io/v1','kind':'RoleBinding','metadata':{'name':'fleet-bootstrap-reader','namespace':'default'},'roleRef':{'apiGroup':'rbac.authorization.k8s.io','kind':'Role','name':'fleet-bootstrap-reader'},'subjects':[{'kind':'User','name':'management'}]}) apply(d/'bootstrap.json',{'apiVersion':'rbac.authorization.k8s.io/v1','kind':'RoleBinding','metadata':{'name':'customer','namespace':'default'},'roleRef':{'apiGroup':'rbac.authorization.k8s.io','kind':'Role','name':'customer'},'subjects':[{'kind':'User','name':'customer'}]}) print(role+': Flux-managed Milo project API ready (static-token RBAC test seam)',flush=True) diff --git a/hack/multiplane/verify-rbac.py b/hack/multiplane/verify-rbac.py index 00040319..d47d08aa 100755 --- a/hack/multiplane/verify-rbac.py +++ b/hack/multiplane/verify-rbac.py @@ -79,11 +79,11 @@ 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']}, @@ -99,7 +99,13 @@ 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']),own[1]]), + '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'])]), @@ -150,6 +156,8 @@ def job(**change): 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]) @@ -165,7 +173,11 @@ def job(**change): '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 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)) diff --git a/internal/coordination/cell.go b/internal/coordination/cell.go index 274c7c10..cf0a0ac2 100644 --- a/internal/coordination/cell.go +++ b/internal/coordination/cell.go @@ -84,7 +84,11 @@ func (c *Cell) Work(ctx context.Context, name string, runner *site.Runner) error if runner.Payloads == nil { return ErrNotDelivered } - if payload, err := runner.Payloads.Get(ctx, assignment); err != nil || payload == nil { + payload, err := runner.Payloads.Get(ctx, assignment) + if err != nil { + return err + } + if payload == nil { return ErrPayloadPending } } @@ -121,14 +125,16 @@ func (s HandoffPayloads) Get(ctx context.Context, assignment site.Assignment) (* 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, err + return nil, ErrNotDelivered } var payload site.Payload if err := json.Unmarshal(data, &payload); err != nil { - return nil, err + return nil, ErrNotDelivered } return &payload, nil } diff --git a/internal/coordination/transport.go b/internal/coordination/transport.go index 8912f4f2..1795eac8 100644 --- a/internal/coordination/transport.go +++ b/internal/coordination/transport.go @@ -232,6 +232,32 @@ func (h *Hub) Deliver(ctx context.Context, assignment site.Assignment, payload * 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) } diff --git a/internal/coordination/transport_test.go b/internal/coordination/transport_test.go index 905b3d49..361d9558 100644 --- a/internal/coordination/transport_test.go +++ b/internal/coordination/transport_test.go @@ -434,3 +434,97 @@ func TestACellRefusesAHandoffNamingAnotherPayload(t *testing.T) { }) } } + +// 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{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 } diff --git a/internal/delivery/delivery.go b/internal/delivery/delivery.go index e020004d..2ccf4df3 100644 --- a/internal/delivery/delivery.go +++ b/internal/delivery/delivery.go @@ -61,6 +61,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 { @@ -128,6 +135,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 @@ -165,6 +177,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 @@ -197,6 +212,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 { @@ -270,18 +306,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/multiplane/runner.go b/internal/multiplane/runner.go index 673d7f9e..ec9d0e5f 100644 --- a/internal/multiplane/runner.go +++ b/internal/multiplane/runner.go @@ -35,6 +35,7 @@ import ( "go.datum.net/fleet/internal/custody" "go.datum.net/fleet/internal/delivery" "go.datum.net/fleet/internal/manager" + "go.datum.net/fleet/internal/sealed" "go.datum.net/fleet/internal/site/fixture" "go.datum.net/fleet/internal/tenancy" ) @@ -417,8 +418,17 @@ func (r *Runner) installation(ctx context.Context, index int) (*request, *fleet. if err == nil { image, err = ImageCatalog(r.Provider.API).Resolve(ctx, consumer, &install) } + var bootstrap *sealed.Payload + if ref := install.Spec.BootstrapConfigRef; err == nil && ref != nil { + // The management identity reads only this named Secret, standing + // in for the Installation creator's authority. + var payload sealed.Payload + if payload, err = sealed.Read(ctx, q.project.API, install.Namespace, ref.Name); err == nil { + bootstrap = &payload + } + } if err == nil { - operation, err = r.Allocator.Install(ctx, current, allocation.Installation{Installation: &install, Current: previous, Image: image}) + operation, err = r.Allocator.Install(ctx, current, allocation.Installation{Installation: &install, Current: previous, Image: image, Bootstrap: bootstrap}) } if refusal := (*catalog.Refusal)(nil); errors.As(err, &refusal) { accepted := condition("Accepted", metav1.ConditionFalse, install.Generation, refusal.Reason) diff --git a/internal/multiplane/seed.go b/internal/multiplane/seed.go index 719ab5c1..86590bbc 100644 --- a/internal/multiplane/seed.go +++ b/internal/multiplane/seed.go @@ -18,9 +18,13 @@ import ( inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" fleet "go.datum.net/fleet/internal/api/v1alpha1" "go.datum.net/fleet/internal/manager" + "go.datum.net/fleet/internal/sealed" "go.datum.net/fleet/internal/tenancy" ) +// BootstrapSecret is consumer A's bootstrap Secret. +const BootstrapSecret = "debian-pxe-bootstrap" + // Seed uses bootstrap only for provider facts and publication: the profile, // class and capacity, and one Device for each enrolled Device. Requests use // distinct customer credentials, and a watch starts before each create. @@ -73,7 +77,7 @@ func Seed(ctx context.Context, c Config) error { return errors.New("the cell image is not name@digest") } image := &fleet.MachineImage{ObjectMeta: metav1.ObjectMeta{Name: imageName, Namespace: DeviceNamespace}, Spec: fleet.MachineImageSpec{ - Definition: &fleet.ImageDefinition{Family: "fleet-local-linux", Version: "1", Architecture: "amd64", FirmwareModes: []string{fleet.FirmwareBIOS}, Digest: imageDigest}, + Definition: &fleet.ImageDefinition{Family: "fleet-local-linux", Version: "1", Architecture: "amd64", FirmwareModes: []string{fleet.FirmwareBIOS}, BootstrapFormats: []string{fleet.BootstrapNoCloud}, Digest: imageDigest}, Availability: fleet.ImageAvailable, }} if err := ensure(ctx, provider, image); err != nil { @@ -147,6 +151,18 @@ func Seed(ctx context.Context, c Config) error { return err } installation := &fleet.Installation{ObjectMeta: metav1.ObjectMeta{Name: "debian-pxe", Namespace: Namespace}, Spec: fleet.InstallationSpec{MachineRef: fleet.MachineReference{Name: machine.Name}, ExpectedPredecessor: fleet.InstallationPredecessor{Type: "None"}, ImageRef: fleet.LocalReference{Name: imageName}}} + // Consumer A stores synthetic bootstrap data in its own project, as + // the customer, and its first install names it. + if name == "consumer-a" { + secret := &core.Secret{ObjectMeta: metav1.ObjectMeta{Name: BootstrapSecret, Namespace: Namespace}, Type: sealed.SecretType, StringData: map[string]string{ + sealed.KeyUserData: "#cloud-config\nhostname: synthetic-example\n", + sealed.KeySSHAuthorizedKeys: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAISyntheticExampleOnly synthetic@example.com\n", + }} + if err := ensure(ctx, user, secret); err != nil { + return err + } + installation.Spec.BootstrapConfigRef = &fleet.LocalReference{Name: BootstrapSecret} + } if err := ensure(ctx, user, installation); err != nil { return err } diff --git a/internal/site/redfishwork/boot.go b/internal/site/redfishwork/boot.go index 06af2582..270dfb34 100644 --- a/internal/site/redfishwork/boot.go +++ b/internal/site/redfishwork/boot.go @@ -111,7 +111,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" || len(found.Seed) == 0)) { deny() return } @@ -122,7 +122,16 @@ func (b BootServer) Handler() http.Handler { var size int64 if name == "boot.ipxe" { base := b.Origin + "/" + Key(boot.Operation) + "/" + boot.Token - data = []byte(fmt.Sprintf("#!ipxe\nkernel %s/kernel console=ttyS0 rdinit=/init fleet.receipt=%s fleet.mode=%s\ninitrd %s/installer.gz\nboot\n", base, boot.Receipt, boot.Mode, base)) + seed := "" + if 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\ninitrd %s/installer.gz\n%sboot\n", base, boot.Receipt, boot.Mode, 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. @@ -233,7 +242,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 979f65a0..6092341f 100644 --- a/internal/site/redfishwork/kinds.go +++ b/internal/site/redfishwork/kinds.go @@ -121,9 +121,6 @@ func (k Installation) Check(_ context.Context, work *site.Work) *custody.Refusal 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"} - } // Firmware settings can change after allocation: read the mode the // server boots in now. if mode := conn(work).System.BootMode; mode == "" || !contains(spec.Image.FirmwareModes, mode) { @@ -186,7 +183,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.Bootstrap = payload.Digest + } + return evidence, nil } func (k Wipe) Run(ctx context.Context, work *site.Work) (any, error) { @@ -219,6 +220,9 @@ 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" @@ -241,6 +245,11 @@ func (c Config) boot(ctx context.Context, work *site.Work, mode string) (Boot, e } _, _, _, window := c.durations() boot = Boot{Operation: work.Key(), Fence: work.Fence, Mode: mode, MAC: strings.ToLower(conn(work).Target.MAC), 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 + } + } return boot, store.PutRecord(work.Device, work.Fence, bootRecords, work.Key(), boot) } @@ -303,7 +312,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 + boot.Phase, boot.Closed, boot.Seed = "", true, nil if err := c.saveBoot(work, boot); err != nil { return nil, err } @@ -399,7 +408,12 @@ 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) + return c.verifyDelivery(work, len(boot.Seed) > 0) + } + // The installed system proves it found exactly the + // admitted bootstrap data on its own disk. + if ph.name == "disk" && work.Bootstrap() != nil { + return c.verifyBootstrap(work, boot) } return nil } @@ -473,9 +487,32 @@ 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 installed +// system reports the admitted bootstrap data's salted digest. +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 installed system did not report the admitted bootstrap data") + } + 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 d7d3580a..6cf4977d 100644 --- a/internal/site/redfishwork/kinds_test.go +++ b/internal/site/redfishwork/kinds_test.go @@ -54,6 +54,11 @@ type lab struct { bootRoot string store *site.Store operation string + // bootstrap, given the receipt, is the extra line the installed + // system prints on its disk boot. + bootstrap func(receipt string) string + // seeded records whether the network boot's script loaded the seed. + seeded bool } func newLab(t *testing.T) *lab { @@ -142,10 +147,16 @@ 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 case target == "Hdd": line = "FLEET-DISK-BOOT:" + boot.Receipt + if l.bootstrap != nil { + line = l.bootstrap(boot.Receipt) + "\n" + line + } } file, err := os.OpenFile(l.console, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600) if err == nil { @@ -161,7 +172,11 @@ func (l *lab) deliver() { dir := BootDirectory(l.bootRoot, l.operation) os.MkdirAll(dir, 0o700) log := "t 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 { + names = append(names, "seed.cpio") + } + for _, name := range names { log += "t write-complete " + name + " bytes=1\n" } os.WriteFile(filepath.Join(dir, "boot-delivery.log"), []byte(log), 0o600) @@ -271,14 +286,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) + } } } @@ -378,3 +398,55 @@ func TestAServerThatNeverPowersOffEndsTheStep(t *testing.T) { t.Fatalf("result = %+v, %d power-ons after %s", result, l.onCount(), time.Since(started)) } } + +// TestBootstrapDataReachesTheInstalledSystemOverRedfish: the network boot +// loads the seed, and the install succeeds only if the installed system +// reports the admitted data's salted digest. +func TestBootstrapDataReachesTheInstalledSystemOverRedfish(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} + for name, test := range map[string]struct { + line func(receipt string) string + ok bool + }{ + "the admitted data": {func(receipt string) string { return site.BootstrapLine(receipt, payload.Digest) }, true}, + "other data": {func(receipt string) string { return site.BootstrapLine(receipt, "sha256:"+strings.Repeat("0", 64)) }, false}, + "no bootstrap line": {func(string) string { return "booted" }, false}, + } { + 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 + 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.Bootstrap != payload.Digest) { + t.Fatalf("result = %+v, evidence %+v", result, evidence) + } + }) + } +} diff --git a/internal/site/vmwork/boot.go b/internal/site/vmwork/boot.go index 7fa178f1..227909cf 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\ninitrd %s/installer.gz\nboot\n", base, boot.Receipt, base)) + seed := "" + if 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\ninitrd %s/installer.gz\n%sboot\n", base, boot.Receipt, 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 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. @@ -235,7 +252,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/kinds.go b/internal/site/vmwork/kinds.go index 69c318f2..6a7e6ded 100644 --- a/internal/site/vmwork/kinds.go +++ b/internal/site/vmwork/kinds.go @@ -146,8 +146,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 { + return &custody.Refusal{Reason: custody.ReasonBootstrapUnsupported, Message: "this site hands bootstrap data to the server only on a network boot"} } if spec.Image.Name+"@"+spec.Image.Digest != k.Image { return &custody.Refusal{Reason: custody.ReasonTargetUnsupported, Message: "the site installs only its verified local image"} @@ -170,8 +172,14 @@ 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"` } +// 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 @@ -190,6 +198,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())} + 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) } @@ -255,7 +268,7 @@ func (k Installation) Run(ctx context.Context, work *site.Work) (any, error) { // leaves it open for its replacement to resume. fail := func(err error) error { if stage == "installer" && k.PXE && boot.Open && ctx.Err() == nil { - boot.Open, boot.Closed = false, true + closeBoot(&boot) _ = k.save(work, boot) } return err @@ -284,10 +297,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 } @@ -297,6 +310,9 @@ func (k Installation) Run(ctx context.Context, work *site.Work) (any, error) { } record(stage) } + if payload := work.Bootstrap(); payload != nil { + evidence.Bootstrap = payload.Digest + } return evidence, nil } @@ -363,6 +379,15 @@ 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 installed system prints for the +// admitted bootstrap data, 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" +} + // waitReceipt waits for the guest to stop with exactly this phase's receipt. func (k Installation) waitReceipt(ctx context.Context, work *site.Work, boot Boot, stage string) error { marker := "FLEET-INSTALLED:" @@ -380,15 +405,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 installed system proves it found exactly the admitted + // bootstrap data on its own disk, by its salted digest. + if stage == "disk" && work.Bootstrap() != nil && bootstrapped != 1 { + return errors.New("the installed system did not report the admitted bootstrap data") + } 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 68fe5676..4e45bae5 100644 --- a/internal/site/vmwork/kinds_test.go +++ b/internal/site/vmwork/kinds_test.go @@ -1,8 +1,12 @@ package vmwork import ( + "bytes" "context" + "crypto/sha256" + "encoding/hex" "encoding/json" + "io" "net/http" "net/http/httptest" "os" @@ -35,6 +39,12 @@ type hypervisor struct { hold bool // noReceipt makes the guest print no receipt. noReceipt bool + // bootstrap, given the receipt, is the extra line the installed + // system prints on its disk boot. + 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 } var receiptArg = regexp.MustCompile(`fleet.receipt=([0-9a-f]{64})`) @@ -56,6 +66,8 @@ func (h *hypervisor) run(_ context.Context, _ string, args ...string) (string, e receipt := "" if match := receiptArg.FindStringSubmatch(xml); 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")) @@ -64,6 +76,9 @@ func (h *hypervisor) run(_ context.Context, _ string, args ...string) (string, e } } console := "booting\n" + marker + receipt + "\n" + if marker == "FLEET-DISK-BOOT:" && h.bootstrap != nil { + console = "booting\n" + h.bootstrap(receipt) + "\n" + marker + receipt + "\n" + } if h.noReceipt { console = "booting\n" } @@ -74,6 +89,8 @@ func (h *hypervisor) run(_ context.Context, _ string, args ...string) (string, e if !h.hold { delete(h.running, name) } + case "net-dhcp-leases": + return guestMAC + " 192.168.77.2/24", nil case "list": var names []string for name := range h.running { @@ -289,3 +306,135 @@ func TestAFailedNetworkBootClosesItsAdmission(t *testing.T) { t.Fatalf("admission after the failure = %+v, %v, %v", boot, found, err) } } + +// 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 +} + +// TestBootstrapDataReachesTheInstalledSystem: a network install loads the +// seed as a second initrd, the installed system reports the salted digest +// of the data it found, and the evidence names it. A guest that reports +// other data, or none, does not succeed, and the seed is dropped either way. +func TestBootstrapDataReachesTheInstalledSystem(t *testing.T) { + for name, test := range map[string]struct { + line func(receipt, digest string) string + ok bool + }{ + "the admitted data": {func(receipt, digest string) string { return site.BootstrapLine(receipt, digest) }, true}, + "other data": {func(receipt, _ string) string { return site.BootstrapLine(receipt, "sha256:"+strings.Repeat("0", 64)) }, false}, + "no bootstrap 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 { + t.Fatalf("result = %+v", result) + } + return + } + var evidence ops.InstallationEvidence + if result.Phase != ops.PhaseSucceeded || json.Unmarshal(result.Evidence, &evidence) != nil || evidence.Bootstrap != 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) + } + closeBoot(&boot) + 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) + } +} diff --git a/internal/sitepolicy/policy_test.go b/internal/sitepolicy/policy_test.go index 2a53ba42..136e203c 100644 --- a/internal/sitepolicy/policy_test.go +++ b/internal/sitepolicy/policy_test.go @@ -127,6 +127,14 @@ func start(t *testing.T, base string) *env { 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 } @@ -160,23 +168,28 @@ func (e *env) policy(name string) *unstructured.Unstructured { return policy } -// weaken replaces the validation whose message starts with prefix by one -// that always passes, and returns a function that restores the policy. -func (e *env) weaken(name, prefix string) func() { +// 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 := false + found := 0 for index, validation := range validations { rule := validation.(map[string]any) - if strings.HasPrefix(fmt.Sprint(rule["message"]), prefix) { - rule["expression"], found = "true", true + 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 { - e.t.Fatalf("%s has no validation %q", name, prefix) + 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 { @@ -184,8 +197,10 @@ func (e *env) weaken(name, prefix string) func() { } return func() { current := e.policy(name) - original.SetResourceVersion(current.GetResourceVersion()) - if err := e.admin.Update(e.ctx, original); err != nil { + 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) } } @@ -227,17 +242,44 @@ func role(t *testing.T, namespace string, rules ...string) *unstructured.Unstruc } 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"]}` - roleRuleText = "a worker Role may grant only" - bindingRule = "a worker RoleBinding may bind only" - clusterRBACMsg = "kro may not write cluster-wide RBAC" + 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" + 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)) @@ -249,13 +291,24 @@ const ( 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 rule name the one validation that must refuse the probe. - policy, rule string + // 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 @@ -266,10 +319,17 @@ func (e *env) check(probes []probe) { if got := e.outcome(p.send, "policy"); got != "policy" { t.Fatalf("as rendered: %s, want refused by policy", got) } - restore := e.weaken(p.policy, p.rule) - defer restore() + 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 that rule", p.rule, got) + t.Fatalf("without %q: %s, want admitted; the probe does not test those clauses", p.clauses, got) } }) } @@ -294,10 +354,12 @@ func TestKroCanCreateOnlyPerOperationRBAC(t *testing.T) { // 1. Role shape. Each Role is within kro's own grant, so only the // policy can refuse it. e.check([]probe{ - {"a Role without its payload rule", dryRun(role(t, coordination, ownHandoff)), identity, roleRuleText}, - {"a Role reading another operation's payload", dryRun(role(t, coordination, ownHandoff, otherPayload)), identity, roleRuleText}, - {"a Role reading every payload", dryRun(role(t, coordination, ownHandoff, anyPayload)), identity, roleRuleText}, - {"a Role with a third rule", dryRun(role(t, coordination, ownHandoff, ownPayload, ownHandoff)), identity, roleRuleText}, + // 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{ @@ -318,11 +380,15 @@ func TestKroCanCreateOnlyPerOperationRBAC(t *testing.T) { t.Fatalf("the worker binding: %s", got) } e.check([]probe{ - {"a binding to kro's own ServiceAccount", dryRun(binding(t, coordination, kroAccount)), identity, bindingRule}, - {"a binding to another operation's worker", dryRun(binding(t, coordination, otherWorker)), identity, bindingRule}, - {"a binding to kro as a user", dryRun(binding(t, coordination, kroUser)), identity, bindingRule}, - {"a binding to every ServiceAccount", dryRun(binding(t, coordination, everyone)), identity, bindingRule}, - {"a binding to its worker and kro", dryRun(binding(t, coordination, worker, kroAccount)), identity, bindingRule}, + {"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. @@ -338,8 +404,8 @@ func TestKroCanCreateOnlyPerOperationRBAC(t *testing.T) { } } e.check([]probe{ - {"widening the Role to every payload", widen(ownHandoff, anyPayload), identity, roleRuleText}, - {"widening the Role to another payload", widen(ownHandoff, otherPayload), identity, roleRuleText}, + {"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; @@ -356,8 +422,49 @@ func TestKroCanCreateOnlyPerOperationRBAC(t *testing.T) { 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", clusterRBACMsg}, - {"a ClusterRoleBinding, with a grant", dryRun(clusterBinding), "fleet-site-kro-cluster-rbac", clusterRBACMsg}, + {"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}}, }) } @@ -373,9 +480,12 @@ func TestRedfishCredentialRolesAreOneGetOnOneSecret(t *testing.T) { t.Fatalf("the worker Role: %s", got) } e.check([]probe{ - {"a credential Role with a second rule", dryRun(role(t, credentials, ownCredential, ownCredential)), identity, roleRuleText}, - {"a credential Role naming another Secret", dryRun(role(t, credentials, strings.Replace(ownCredential, "bmc-0123456789abcdef0123", "fleet-site-bmc-credentials", 1))), identity, roleRuleText}, - {"a worker Role reading every payload", dryRun(role(t, coordination, ownHandoff, anyPayload)), identity, roleRuleText}, + {"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) From f3688627d87b84c2ff5911cd8fb14a058b0a517a Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 25 Nov 2026 15:05:47 -0600 Subject: [PATCH 3/7] fix(site): Drop the boot seed however an install ends The bootstrap seed stayed in a boot admission whenever an install did not reach a clean close: a failure before the admission opened, an expired admission, or an error out of the Redfish wait. Kinds that keep payload copies in their own site records now scrub them when the operation's result is stored, and whenever the site raises the Device's fence, so a superseded install's seed goes too. Test that a failed and an expired install drop the seed, that a recovery fence drops a superseded one, that each coordinator pass keeps exactly the delivered operations' payloads and a failed pass sweeps nothing, and that every hub delete carries the listed UID. Co-Authored-By: Claude Opus 5.5 --- docs/development/machine-images.md | 6 ++- internal/allocation/bootstrap_test.go | 24 ++++++++++ internal/allocation/harness_test.go | 47 ++++++++++++++++++- internal/coordination/transport_test.go | 31 +++++++++++++ internal/site/payload.go | 24 +++++++++- internal/site/redfishwork/kinds.go | 22 +++++++++ internal/site/redfishwork/kinds_test.go | 35 ++++++++++++++ internal/site/runner.go | 3 ++ internal/site/store.go | 18 ++++++++ internal/site/vmwork/kinds.go | 22 +++++++++ internal/site/vmwork/kinds_test.go | 61 +++++++++++++++++++++++++ 11 files changed, 289 insertions(+), 4 deletions(-) diff --git a/docs/development/machine-images.md b/docs/development/machine-images.md index f920b894..a2d8a649 100644 --- a/docs/development/machine-images.md +++ b/docs/development/machine-images.md @@ -137,8 +137,10 @@ proposal's API names are provisional. Each piece below is marked 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, and the admission - drops it when it closes. The installer copies it to the disk, puts the user + 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 it to the disk, puts the user data where NoCloud reads it and the keys in the default user's `authorized_keys`. On its first disk boot the installed system prints the salted digest of what it found, and the worker requires exactly that line diff --git a/internal/allocation/bootstrap_test.go b/internal/allocation/bootstrap_test.go index c540f139..668e32ca 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) @@ -106,6 +125,11 @@ func TestBootstrapReachesTheServerAndEveryCopyIsDeleted(t *testing.T) { // 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 5040dfe4..13a54fa2 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" @@ -55,6 +57,7 @@ type env struct { loop *delivery.Loop store *site.Store enrollment fixture.Enrollment + site *sweepingSite class *fleetv1.MachineClass profile *fleetv1.MachineProfile } @@ -116,7 +119,8 @@ func startEnv(t *testing.T) *env { 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}}, }}} @@ -238,3 +242,44 @@ func (e *env) release(allocation *fleetv1.MachineAllocation, owner Machine) { return released }) } + +// 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) +} diff --git a/internal/coordination/transport_test.go b/internal/coordination/transport_test.go index 361d9558..ff5d576e 100644 --- a/internal/coordination/transport_test.go +++ b/internal/coordination/transport_test.go @@ -19,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" @@ -528,3 +529,33 @@ func (p failingPayloads) Get(context.Context, site.Assignment) (*site.Payload, e } 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 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/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/kinds.go b/internal/site/redfishwork/kinds.go index 6092341f..c6c1e0e4 100644 --- a/internal/site/redfishwork/kinds.go +++ b/internal/site/redfishwork/kinds.go @@ -227,6 +227,28 @@ type Boot struct { 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) { diff --git a/internal/site/redfishwork/kinds_test.go b/internal/site/redfishwork/kinds_test.go index 6cf4977d..5176cefe 100644 --- a/internal/site/redfishwork/kinds_test.go +++ b/internal/site/redfishwork/kinds_test.go @@ -450,3 +450,38 @@ func TestBootstrapDataReachesTheInstalledSystemOverRedfish(t *testing.T) { }) } } + +// 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 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) + } +} diff --git a/internal/site/runner.go b/internal/site/runner.go index 6ba461bb..b91fd753 100644 --- a/internal/site/runner.go +++ b/internal/site/runner.go @@ -285,6 +285,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/store.go b/internal/site/store.go index 0de27a3c..764068e1 100644 --- a/internal/site/store.go +++ b/internal/site/store.go @@ -349,6 +349,24 @@ func (s *Store) PutRecord(device string, fence int64, collection, name string, v }) } +// 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) + }) +} + // GetRecord reads a kind's record. It returns false if there is none. func (s *Store) GetRecord(device, collection, name string, into any) (bool, error) { if !validRecordName(collection) || !validRecordName(name) { diff --git a/internal/site/vmwork/kinds.go b/internal/site/vmwork/kinds.go index 6a7e6ded..b378a121 100644 --- a/internal/site/vmwork/kinds.go +++ b/internal/site/vmwork/kinds.go @@ -177,6 +177,28 @@ type Boot struct { Seed []byte `json:"seed,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 } diff --git a/internal/site/vmwork/kinds_test.go b/internal/site/vmwork/kinds_test.go index 4e45bae5..1014adc7 100644 --- a/internal/site/vmwork/kinds_test.go +++ b/internal/site/vmwork/kinds_test.go @@ -6,6 +6,7 @@ import ( "crypto/sha256" "encoding/hex" "encoding/json" + "errors" "io" "net/http" "net/http/httptest" @@ -45,6 +46,8 @@ type hypervisor struct { // 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 } var receiptArg = regexp.MustCompile(`fleet.receipt=([0-9a-f]{64})`) @@ -89,6 +92,10 @@ func (h *hypervisor) run(_ context.Context, _ string, args ...string) (string, e if !h.hold { delete(h.running, name) } + case "net-create": + if h.failNetwork { + return "", errors.New("net-create failed") + } case "net-dhcp-leases": return guestMAC + " 192.168.77.2/24", nil case "list": @@ -438,3 +445,57 @@ func TestTheBootServerServesTheSeedOnlyWhileOpen(t *testing.T) { 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)) + } + }) +} From 5b5cad75d5e95f4b41051c4b260ae271e4dbb8c0 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 25 Nov 2026 15:17:05 -0600 Subject: [PATCH 4/7] test(site): Cover the Redfish seed scrub on a fence raise Add the Redfish counterpart of the local VM test: a recovery that only raises the fence drops the seed a superseded install left behind. Rewrap the status page's guest paragraph. Co-Authored-By: Claude Opus 5.5 --- docs/development/machine-images.md | 12 ++++++------ internal/site/redfishwork/kinds_test.go | 24 ++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 6 deletions(-) diff --git a/docs/development/machine-images.md b/docs/development/machine-images.md index a2d8a649..640a5abf 100644 --- a/docs/development/machine-images.md +++ b/docs/development/machine-images.md @@ -140,12 +140,12 @@ proposal's API names are provisional. Each piece below is marked 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 it to the disk, puts the user - data where NoCloud reads it and the keys in the default user's - `authorized_keys`. On its first disk boot the installed system prints the - salted digest of what it found, and the worker requires exactly that line - before it reports success. A direct kernel boot, which has one initrd, - refuses bootstrap data. + failed, expired or superseded install leaves it behind. The installer copies + it to the disk, puts the user data where NoCloud reads it and the keys in + the default user's `authorized_keys`. On its first disk boot the installed + system prints the salted digest of what it found, and the worker requires + exactly that line before it reports success. A direct kernel boot, which has + one initrd, refuses bootstrap data. ## Not implemented yet diff --git a/internal/site/redfishwork/kinds_test.go b/internal/site/redfishwork/kinds_test.go index 5176cefe..5fb16c30 100644 --- a/internal/site/redfishwork/kinds_test.go +++ b/internal/site/redfishwork/kinds_test.go @@ -485,3 +485,27 @@ func TestAFailedRedfishInstallDropsItsSeed(t *testing.T) { 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) + } +} From 8d1b126bf0edffbf3c706595c12672ccaf518483 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 25 Nov 2026 15:56:24 -0600 Subject: [PATCH 5/7] feat(site): Verify bootstrap data in the installer, not the guest Install success depended on the installed OS printing the salted digest of its bootstrap data on first boot, but Fleet does not own the guest OS. The installer now reads the seed back from the target disk past the page cache, checks that the NoCloud user data and the authorized keys match it, and prints the salted digest before its own receipt. The worker requires exactly the admitted digest from the installer before it lets the disk boot run, and the evidence records it as installerVerifiedBootstrap. A wrong, truncated or missing report fails the install before the disk boot. The installed system no longer prints anything about bootstrap data. Co-Authored-By: Claude Opus 5.5 --- docs/development/README.md | 5 +-- docs/development/device-custody.md | 2 +- docs/development/machine-images.md | 23 ++++++------ docs/operations/redfish-lab.md | 7 ++-- hack/local-vm/boot | 7 ---- hack/local-vm/init | 12 +++++++ hack/multiplane/evidence.py | 22 ++++++------ internal/allocation/bootstrap_test.go | 2 +- internal/api/operations/v1alpha1/types.go | 8 ++--- internal/custody/bootstrap_evidence_test.go | 6 ++-- internal/custody/kinds.go | 8 ++--- internal/site/redfishwork/kinds.go | 19 +++++----- internal/site/redfishwork/kinds_test.go | 28 ++++++++------- internal/site/simwork/kinds.go | 2 +- internal/site/vmwork/kinds.go | 15 ++++---- internal/site/vmwork/kinds_test.go | 40 +++++++++++++-------- 16 files changed, 117 insertions(+), 89 deletions(-) diff --git a/docs/development/README.md b/docs/development/README.md index 0a5e7132..27dcbdc0 100644 --- a/docs/development/README.md +++ b/docs/development/README.md @@ -43,8 +43,9 @@ smoke verifies it. The end-to-end failure scenarios (Increment D) are proposed. admission resolves through a publication record and checks against the server's architecture and firmware mode. The sealed bootstrap store and its delivery through federation to the local VM and Redfish guests are -**implemented**; the multi-plane runs that prove the guest receives the data -are pending. +**implemented**: the installer verifies the data on the target disk before +the install succeeds. The multi-plane runs that prove it in the lab are +pending. 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 diff --git a/docs/development/device-custody.md b/docs/development/device-custody.md index ccf346d9..1df572e4 100644 --- a/docs/development/device-custody.md +++ b/docs/development/device-custody.md @@ -920,7 +920,7 @@ Increment B's site tests run with `go test -race ./internal/site/...`: | One worker per assignment, final results, shutdown at each stage, an older worker that does not stop, a fence raised between journal and send | `TestARedeliveryWhileTheSameOperationRunsStoresNothing`, `TestACopyWaitingForTheLockReturnsTheStoredResult`, `TestAStoredResultSurvivesARedelivery`, `TestAWorkerStoppedFromOutsideStoresNoResult`, `TestAShutdownWhileWaitingForTheRunLockStoresNothing`, `TestAShutdownDuringTheChecksStoresNothing`, `TestANewerAssignmentThatCannotStopTheOlderWorkerSendsNothing`, `TestALostLockWithJournaledStepsIsUnknown`, `TestAFenceRaisedBetweenJournalAndSendStopsTheStep` | | Per-Device credentials, the fence report | `TestSecretCredentialsUseThePerDeviceContract`, `TestReportGivesTheCoordinatorSeenAndStoppedFences` | | Step payloads, the start-by window, identity separate from capabilities, a resumed worker reporting unknown | `TestAStepPayloadIsJournaledAndReadBack`, `TestALateStartIsStaleAndSendsNothing`, `TestIdentityIsSeparateFromInstallCapabilities`, `TestAResumedWorkerThatCannotReachTheBMCReportsUnknown` | -| Install and wipe against a simulated BMC, one power-on per phase after an interruption in either phase, the power-off bound, fenced boot admission, bootstrap data the installed system reports, bootstrap refused without a payload | `TestAWorkerInterruptedInTheDiskPhaseResumes`, `TestAServerThatNeverPowersOffEndsTheStep`, `TestInstallationRunsBothPhasesWithOneOnEach`, `TestWipeChecksTheEnrolledDisk`, `TestAnInterruptedWorkerResumesWithoutASecondOn`, `TestOnlyTheCurrentFenceHasAnOpenBootAdmission`, `TestBootstrapDataReachesTheInstalledSystemOverRedfish`, `TestBootstrapWithoutAPayloadSendsNothing` | +| 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 640a5abf..116c5273 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 delivery | Federation carries a payload to the cell, the local VM and Redfish boot services hand it to the installer, and the installed system reports it | **Implemented**, verified by unit tests and tests against a real API server. The local VM and Redfish multi-plane runs are pending. | +| 3: lab delivery | Federation carries a payload to the cell, the local VM and Redfish boot services hand it to the installer, and the installer verifies it on the target disk | **Implemented**, verified by unit tests and tests against a real API server. The local VM and Redfish multi-plane runs are pending. | ## What increment 1 adds @@ -103,10 +103,11 @@ 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 @@ -141,11 +142,13 @@ proposal's API names are provisional. Each piece below is marked 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 - it to the disk, puts the user data where NoCloud reads it and the keys in - the default user's `authorized_keys`. On its first disk boot the installed - system prints the salted digest of what it found, and the worker requires - exactly that line before it reports success. A direct kernel boot, which has - one initrd, refuses bootstrap data. + 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. Fleet does not own the installed OS, so + success never depends on what the installed OS prints. A direct kernel boot, + which has one initrd, refuses bootstrap data. ## Not implemented yet diff --git a/docs/operations/redfish-lab.md b/docs/operations/redfish-lab.md index 017650e8..5476382d 100644 --- a/docs/operations/redfish-lab.md +++ b/docs/operations/redfish-lab.md @@ -393,10 +393,11 @@ 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, bootstrap data the installed system must report by its - salted digest, and bootstrap data refused when the site holds no payload + 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`, - `TestBootstrapDataReachesTheInstalledSystemOverRedfish`, + `TestTheInstallerVerifiesBootstrapDataOverRedfish`, `TestBootstrapWithoutAPayloadSendsNothing`); - a worker interrupted in either phase that resumes without a second power-on (`TestAnInterruptedWorkerResumesWithoutASecondOn`, diff --git a/hack/local-vm/boot b/hack/local-vm/boot index c9bf333b..b40c21ec 100644 --- a/hack/local-vm/boot +++ b/hack/local-vm/boot @@ -4,13 +4,6 @@ mount -t proc proc /proc 2>/dev/null || true exec >/dev/ttyS0 2>&1 # Only the disk-root boot emits completion; installer completion is insufficient. if grep -Eq '^/dev/vda1 / ext4 ' /proc/mounts && test -s /fleet-receipt; then - # Report the bootstrap data this system found on its own disk, by the - # salted digest only, and only if the installer put it where the image - # reads it. - if test -s /fleet-bootstrap/data && cmp -s /fleet-bootstrap/authorized_keys /root/.ssh/authorized_keys && - cmp -s /fleet-bootstrap/user-data /var/lib/cloud/seed/nocloud/user-data; then - printf 'FLEET-BOOTSTRAP:%s:sha256:%s\n' "$(cat /fleet-receipt)" "$(cat /fleet-bootstrap/salt /fleet-bootstrap/data | sha256sum | cut -d' ' -f1)" - fi printf 'FLEET-DISK-BOOT:%s\n' "$(cat /fleet-receipt)" fi sync diff --git a/hack/local-vm/init b/hack/local-vm/init index 28087f20..dd352c38 100644 --- a/hack/local-vm/init +++ b/hack/local-vm/init @@ -66,5 +66,17 @@ menuentry Fleet { } CFG sync +# 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 /target/fleet-bootstrap/user-data /target/var/lib/cloud/seed/nocloud/user-data + cmp -s /target/fleet-bootstrap/meta-data /target/var/lib/cloud/seed/nocloud/meta-data + cmp -s /target/fleet-bootstrap/authorized_keys /target/root/.ssh/authorized_keys + digest=$(cat /target/fleet-bootstrap/salt /target/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/evidence.py b/hack/multiplane/evidence.py index 7e390407..488674c9 100755 --- a/hack/multiplane/evidence.py +++ b/hack/multiplane/evidence.py @@ -167,15 +167,15 @@ def custody_evidence(store, ops, provider, a, b): def bootstrap_line(provider, o, receipt): - """The console line the installed system must print for an install's - bootstrap data, or None. The operation's evidence must name the same - salted digest the guest reports.""" + """The console line the installer must print after it reads an install's + bootstrap data back from the target disk, or None. The operation's + evidence must record the same salted digest as installer-verified.""" p = provider[o['operation']] digest = (p['spec'].get('bootstrap') or {}).get('digest') if not digest: return None - if ((p.get('status') or {}).get('evidence') or {}).get('bootstrap') != digest: - fail('%s succeeded without evidence of its bootstrap data' % p['metadata']['name']) + if ((p.get('status') or {}).get('evidence') or {}).get('installerVerifiedBootstrap') != digest: + fail('%s succeeded without the installer verifying its bootstrap data' % p['metadata']['name']) return 'FLEET-BOOTSTRAP:%s:%s' % (receipt, digest) @@ -221,10 +221,10 @@ def libvirt_provider(): if not any('write-complete ' + name + ' bytes=' in line for line in written.splitlines()): fail('missing completed broker write for ' + name) if seeded: - disk_log = directory / 'disk.log' - lines = [line.strip() for line in disk_log.read_text(errors='replace').splitlines()] if disk_log.exists() else [] + installer_log = directory / 'installer.log' + lines = [line.strip() for line in installer_log.read_text(errors='replace').splitlines()] if installer_log.exists() else [] if lines.count(seeded) != 1 or sum(1 for l in lines if l.startswith('FLEET-BOOTSTRAP:')) != 1: - fail('the installed system did not report exactly the admitted bootstrap data') + fail('the installer did not verify exactly the admitted bootstrap data on disk') bootstrapped.append(uid) for filename, marker in (('installer.log', 'FLEET-INSTALLED:'), ('disk.log', 'FLEET-DISK-BOOT:')): p = directory / filename @@ -250,7 +250,7 @@ def libvirt_provider(): starts[uid] = {'qemuStarts': len(blocks), 'networkInstallerStarts': len(network), 'diskOnlyStarts': len(disk_only)} if len(blocks) != 2 or len(network) != 1 or len(disk_only) != 1 or blocks.index(network[0]) != 0: fail('expected exactly one network installer start followed by one disk-only start, got %s' % starts[uid]) - # Consumer A's install carries bootstrap data; the guest proved it. + # Consumer A's install carries bootstrap data; the installer verified it. if len(bootstrapped) != 1 or bootstrapped[0] != ops[0]['operation']: fail('expected consumer A\'s install, and only it, to report bootstrap data; got %s' % bootstrapped) bootstrap_gone() @@ -295,8 +295,8 @@ def redfish_provider(): seeded = bootstrap_line(provider, o, boot['receipt']) if o['kind'] == 'DeviceInstallation' else None if seeded: bootstrapped.append(o['operation']) - # The installed system prints its bootstrap report just before its disk receipt. - want = (['FLEET-INSTALLED:' + boot['receipt']] + ([seeded] if seeded else []) + ['FLEET-DISK-BOOT:' + boot['receipt']]) if o['kind'] == 'DeviceInstallation' else ['FLEET-WIPED:%s:%d' % (boot['receipt'], a['diskBytes'])] + # The installer prints its bootstrap check just before its own receipt. + want = (([seeded] if seeded else []) + ['FLEET-INSTALLED:' + boot['receipt'], 'FLEET-DISK-BOOT:' + boot['receipt']]) if o['kind'] == 'DeviceInstallation' else ['FLEET-WIPED:%s:%d' % (boot['receipt'], a['diskBytes'])] for line in want: if console.count(line) != 1: fail('expected exactly one exact console receipt %s for %s' % (line.split(':')[0], o['kind'])) diff --git a/internal/allocation/bootstrap_test.go b/internal/allocation/bootstrap_test.go index 668e32ca..193b2d8f 100644 --- a/internal/allocation/bootstrap_test.go +++ b/internal/allocation/bootstrap_test.go @@ -119,7 +119,7 @@ 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 diff --git a/internal/api/operations/v1alpha1/types.go b/internal/api/operations/v1alpha1/types.go index 1466fbea..61a406af 100644 --- a/internal/api/operations/v1alpha1/types.go +++ b/internal/api/operations/v1alpha1/types.go @@ -353,10 +353,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/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 f5a5be85..8c3236da 100644 --- a/internal/custody/kinds.go +++ b/internal/custody/kinds.go @@ -138,14 +138,14 @@ func DeviceInstallationKind() Kind { Settles: []SettleRule{{Held: "DeviceInstallation"}}, Reasons: append([]Reason{{Name: ReasonBootstrapUnavailable, RaisedBy: RaisedByCoordinator}, {Name: ReasonBootstrapUnsupported, RaisedBy: RaisedByBoth}, {Name: ReasonBootInterfaceUnknown, RaisedBy: RaisedByCoordinator}, {Name: ReasonImageIncompatible, RaisedBy: RaisedByWorker}}, workerReasons...), Evidence: StrictEvidence(evidenceLimit, func(operation ops.Operation, evidence *ops.InstallationEvidence) error { - // A success must prove the server was handed exactly the admitted - // bootstrap data, and nothing when there was none. + // 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/site/redfishwork/kinds.go b/internal/site/redfishwork/kinds.go index c6c1e0e4..b91f8d2f 100644 --- a/internal/site/redfishwork/kinds.go +++ b/internal/site/redfishwork/kinds.go @@ -185,7 +185,7 @@ func (k Installation) Run(ctx context.Context, work *site.Work) (any, error) { } evidence := ops.InstallationEvidence{Steps: steps} if payload := work.Bootstrap(); payload != nil { - evidence.Bootstrap = payload.Digest + evidence.InstallerVerifiedBootstrap = payload.Digest } return evidence, nil } @@ -430,11 +430,13 @@ 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, len(boot.Seed) > 0) + if err := c.verifyDelivery(work, len(boot.Seed) > 0); err != nil { + return err + } } - // The installed system proves it found exactly the - // admitted bootstrap data on its own disk. - if ph.name == "disk" && work.Bootstrap() != nil { + // 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 @@ -509,8 +511,9 @@ func (c Config) deliveries(work *site.Work) map[string]bool { return done } -// verifyBootstrap requires exactly one console line in which the installed -// system reports the admitted bootstrap data's salted digest. +// 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 { @@ -523,7 +526,7 @@ func (c Config) verifyBootstrap(work *site.Work, boot Boot) error { } } if n != 1 { - return errors.New("the installed system did not report the admitted bootstrap data") + return errors.New("the installer did not verify the admitted bootstrap data on disk") } return nil } diff --git a/internal/site/redfishwork/kinds_test.go b/internal/site/redfishwork/kinds_test.go index 5fb16c30..57f944eb 100644 --- a/internal/site/redfishwork/kinds_test.go +++ b/internal/site/redfishwork/kinds_test.go @@ -54,8 +54,8 @@ type lab struct { bootRoot string store *site.Store operation string - // bootstrap, given the receipt, is the extra line the installed - // system prints on its disk boot. + // 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 @@ -152,11 +152,11 @@ func (l *lab) boot(target string) { l.mu.Unlock() l.deliver() line = "FLEET-INSTALLED:" + boot.Receipt - case target == "Hdd": - line = "FLEET-DISK-BOOT:" + boot.Receipt if l.bootstrap != nil { line = l.bootstrap(boot.Receipt) + "\n" + line } + case target == "Hdd": + line = "FLEET-DISK-BOOT:" + boot.Receipt } file, err := os.OpenFile(l.console, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600) if err == nil { @@ -399,10 +399,11 @@ func TestAServerThatNeverPowersOffEndsTheStep(t *testing.T) { } } -// TestBootstrapDataReachesTheInstalledSystemOverRedfish: the network boot -// loads the seed, and the install succeeds only if the installed system -// reports the admitted data's salted digest. -func TestBootstrapDataReachesTheInstalledSystemOverRedfish(t *testing.T) { +// 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() @@ -413,9 +414,9 @@ func TestBootstrapDataReachesTheInstalledSystemOverRedfish(t *testing.T) { line func(receipt string) string ok bool }{ - "the admitted data": {func(receipt string) string { return site.BootstrapLine(receipt, payload.Digest) }, true}, - "other data": {func(receipt string) string { return site.BootstrapLine(receipt, "sha256:"+strings.Repeat("0", 64)) }, false}, - "no bootstrap line": {func(string) string { return "booted" }, false}, + "the admitted seed": {func(receipt string) string { return site.BootstrapLine(receipt, payload.Digest) }, true}, + "a wrong seed read back": {func(receipt string) string { return site.BootstrapLine(receipt, "sha256:"+strings.Repeat("0", 64)) }, false}, + "no verification line": {func(string) string { return "booted" }, false}, } { t.Run(name, func(t *testing.T) { l := newLab(t) @@ -444,9 +445,12 @@ func TestBootstrapDataReachesTheInstalledSystemOverRedfish(t *testing.T) { } var evidence ops.InstallationEvidence _ = json.Unmarshal(result.Evidence, &evidence) - if succeeded := result.Phase == ops.PhaseSucceeded; succeeded != test.ok || (test.ok && evidence.Bootstrap != payload.Digest) { + 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()) + } }) } } diff --git a/internal/site/simwork/kinds.go b/internal/site/simwork/kinds.go index c6654b4c..4fb9e154 100644 --- a/internal/site/simwork/kinds.go +++ b/internal/site/simwork/kinds.go @@ -157,7 +157,7 @@ func (Installation) Run(ctx context.Context, work *site.Work) (any, error) { if server.Booted != spec.Image.Digest { return nil, &custody.Refusal{Reason: site.ReasonStep, Message: "the simulated server did not boot the installed image"} } - evidence.Bootstrap = server.Bootstrap + evidence.InstallerVerifiedBootstrap = server.Bootstrap return evidence, nil } diff --git a/internal/site/vmwork/kinds.go b/internal/site/vmwork/kinds.go index b378a121..ec10af94 100644 --- a/internal/site/vmwork/kinds.go +++ b/internal/site/vmwork/kinds.go @@ -333,7 +333,7 @@ func (k Installation) Run(ctx context.Context, work *site.Work) (any, error) { record(stage) } if payload := work.Bootstrap(); payload != nil { - evidence.Bootstrap = payload.Digest + evidence.InstallerVerifiedBootstrap = payload.Digest } return evidence, nil } @@ -401,8 +401,9 @@ 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 installed system prints for the -// admitted bootstrap data, or a line no guest prints when there is none. +// 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) @@ -439,10 +440,10 @@ func (k Installation) waitReceipt(ctx context.Context, work *site.Work, boot Boo if count != 1 { return errors.New("the guest stopped without exactly one boot receipt") } - // The installed system proves it found exactly the admitted - // bootstrap data on its own disk, by its salted digest. - if stage == "disk" && work.Bootstrap() != nil && bootstrapped != 1 { - return errors.New("the installed system did not report the admitted bootstrap data") + // 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 { diff --git a/internal/site/vmwork/kinds_test.go b/internal/site/vmwork/kinds_test.go index 1014adc7..d49e5f27 100644 --- a/internal/site/vmwork/kinds_test.go +++ b/internal/site/vmwork/kinds_test.go @@ -40,8 +40,8 @@ type hypervisor struct { hold bool // noReceipt makes the guest print no receipt. noReceipt bool - // bootstrap, given the receipt, is the extra line the installed - // system prints on its disk boot. + // 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. @@ -79,7 +79,7 @@ func (h *hypervisor) run(_ context.Context, _ string, args ...string) (string, e } } console := "booting\n" + marker + receipt + "\n" - if marker == "FLEET-DISK-BOOT:" && h.bootstrap != nil { + if marker == "FLEET-INSTALLED:" && h.bootstrap != nil { console = "booting\n" + h.bootstrap(receipt) + "\n" + marker + receipt + "\n" } if h.noReceipt { @@ -348,19 +348,29 @@ func (r *rig) sealedInstall(uid string, fence int64) (site.Assignment, site.Payl return assignment, payload } -// TestBootstrapDataReachesTheInstalledSystem: a network install loads the -// seed as a second initrd, the installed system reports the salted digest -// of the data it found, and the evidence names it. A guest that reports -// other data, or none, does not succeed, and the seed is dropped either way. -func TestBootstrapDataReachesTheInstalledSystem(t *testing.T) { +// 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 data": {func(receipt, digest string) string { return site.BootstrapLine(receipt, digest) }, true}, - "other data": {func(receipt, _ string) string { return site.BootstrapLine(receipt, "sha256:"+strings.Repeat("0", 64)) }, false}, - "no bootstrap line": {func(string, string) string { return "" }, false}, - "another receipt": {func(_, digest string) string { return site.BootstrapLine(strings.Repeat("e", 64), digest) }, false}, + "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) @@ -383,13 +393,13 @@ func TestBootstrapDataReachesTheInstalledSystem(t *testing.T) { 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 { - t.Fatalf("result = %+v", result) + 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.Bootstrap != payload.Digest { + if result.Phase != ops.PhaseSucceeded || json.Unmarshal(result.Evidence, &evidence) != nil || evidence.InstallerVerifiedBootstrap != payload.Digest { t.Fatalf("result = %+v, evidence %+v", result, evidence) } }) From f59b9e97cb7b7aab36d0bb9e7caa7ea390eac65a Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 25 Nov 2026 16:04:46 -0600 Subject: [PATCH 6/7] fix(site): Check the installer-verified digest in the smoke The standalone smoke still read the renamed evidence field. Cover a Redfish line for another receipt and a seed the boot never fetched, and drop the guest wording from the seed comments. Co-Authored-By: Claude Opus 5.5 --- hack/standalone-smoke.sh | 4 ++-- internal/site/redfishwork/kinds_test.go | 20 ++++++++++++++------ internal/site/seed.go | 16 ++++++++-------- 3 files changed, 24 insertions(+), 16 deletions(-) diff --git a/hack/standalone-smoke.sh b/hack/standalone-smoke.sh index 4abbf80f..faded30b 100755 --- a/hack/standalone-smoke.sh +++ b/hack/standalone-smoke.sh @@ -133,14 +133,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/site/redfishwork/kinds_test.go b/internal/site/redfishwork/kinds_test.go index 57f944eb..cb040d4d 100644 --- a/internal/site/redfishwork/kinds_test.go +++ b/internal/site/redfishwork/kinds_test.go @@ -59,6 +59,9 @@ type lab struct { 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 } func newLab(t *testing.T) *lab { @@ -173,7 +176,7 @@ func (l *lab) deliver() { os.MkdirAll(dir, 0o700) log := "t admitted boot.ipxe bytes=1\n" names := []string{"boot.ipxe", "kernel", "installer.gz"} - if l.seeded { + if l.seeded && !l.unfetchedSeed { names = append(names, "seed.cpio") } for _, name := range names { @@ -410,19 +413,24 @@ func TestTheInstallerVerifiesBootstrapDataOverRedfish(t *testing.T) { 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 - ok bool + line func(receipt string) string + unfetched bool + ok bool }{ - "the admitted seed": {func(receipt string) string { return site.BootstrapLine(receipt, payload.Digest) }, true}, - "a wrong seed read back": {func(receipt string) string { return site.BootstrapLine(receipt, "sha256:"+strings.Repeat("0", 64)) }, false}, - "no verification line": {func(string) string { return "booted" }, false}, + "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) diff --git a/internal/site/seed.go b/internal/site/seed.go index 68bcc7de..352b62e5 100644 --- a/internal/site/seed.go +++ b/internal/site/seed.go @@ -9,24 +9,24 @@ import ( ) // SeedDirectory is where the seed archive puts a payload in the installer's -// root filesystem. The installer copies it to the target disk, and the -// installed system's first boot reads it. +// root filesystem. The installer copies it to the target disk. const SeedDirectory = "fleet-bootstrap" -// BootstrapMarker starts the console line in which the installed system, -// on its first disk boot, reports the digest of the bootstrap data it -// found: "FLEET-BOOTSTRAP::sha256:". The guest recomputes it -// from the salt and data on its own disk, so the line proves receipt +// 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 a guest prints for a receipt and digest. +// 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 guest +// 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) { From c714ee14be59ed4f80938db0aba00aecf15ff27e Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 25 Nov 2026 16:15:56 -0600 Subject: [PATCH 7/7] test(lab): Check that the booted guest finds its bootstrap data Install success stays installer-verified. On its first disk boot, the lab guest now checks that the user data and keys are where NoCloud and SSH read them and prints the salted digest on a separate line, which no worker reads. The multi-plane evidence requires that line for consumer A's install in both the local VM and Redfish modes. Co-Authored-By: Claude Opus 5.5 --- docs/development/machine-images.md | 6 ++++++ hack/local-vm/boot | 8 ++++++++ hack/multiplane/evidence.py | 17 +++++++++++++++-- 3 files changed, 29 insertions(+), 2 deletions(-) diff --git a/docs/development/machine-images.md b/docs/development/machine-images.md index 116c5273..7a081645 100644 --- a/docs/development/machine-images.md +++ b/docs/development/machine-images.md @@ -149,6 +149,12 @@ proposal's API names are provisional. Each piece below is marked missing report fails the install. Fleet does not own the installed OS, so success never depends on what the installed OS prints. A direct kernel boot, which has one initrd, refuses bootstrap data. +- **Lab first-boot evidence.** On its first disk boot, the lab guest checks + that the user data and keys sit where NoCloud and SSH read them and prints + the salted digest on a separate line. The multi-plane evidence requires that + line for consumer A's install; no worker reads it. The lab guest has no + cloud-init, so this proves the booted system found the data in place, not + that a datasource consumed it. ## Not implemented yet diff --git a/hack/local-vm/boot b/hack/local-vm/boot index b40c21ec..7f1d2970 100644 --- a/hack/local-vm/boot +++ b/hack/local-vm/boot @@ -4,6 +4,14 @@ mount -t proc proc /proc 2>/dev/null || true exec >/dev/ttyS0 2>&1 # Only the disk-root boot emits completion; installer completion is insufficient. if grep -Eq '^/dev/vda1 / ext4 ' /proc/mounts && test -s /fleet-receipt; then + # Lab evidence only, never a worker check: the booted system finds the + # bootstrap data where its NoCloud datasource and SSH read it, and reports + # the salted digest. This lab guest has no cloud-init. + if test -s /fleet-bootstrap/data && cmp -s /fleet-bootstrap/user-data /var/lib/cloud/seed/nocloud/user-data && + cmp -s /fleet-bootstrap/meta-data /var/lib/cloud/seed/nocloud/meta-data && + cmp -s /fleet-bootstrap/authorized_keys /root/.ssh/authorized_keys; then + printf 'FLEET-GUEST-BOOTSTRAP:%s:sha256:%s\n' "$(cat /fleet-receipt)" "$(cat /fleet-bootstrap/salt /fleet-bootstrap/data | sha256sum | cut -d' ' -f1)" + fi printf 'FLEET-DISK-BOOT:%s\n' "$(cat /fleet-receipt)" fi sync diff --git a/hack/multiplane/evidence.py b/hack/multiplane/evidence.py index 488674c9..a001b04d 100755 --- a/hack/multiplane/evidence.py +++ b/hack/multiplane/evidence.py @@ -179,6 +179,12 @@ def bootstrap_line(provider, o, receipt): return 'FLEET-BOOTSTRAP:%s:%s' % (receipt, digest) +def guest_line(installer_line): + """The line the lab guest prints on first boot for the same receipt and + digest. It is lab evidence, never a condition of the install's success.""" + return 'FLEET-GUEST-' + installer_line[len('FLEET-'):] + + def bootstrap_gone(): """No copy of a payload remains once the lifecycle ends: not in the provider's sealed store, and not at the cell, which federation clears @@ -225,6 +231,12 @@ def libvirt_provider(): lines = [line.strip() for line in installer_log.read_text(errors='replace').splitlines()] if installer_log.exists() else [] if lines.count(seeded) != 1 or sum(1 for l in lines if l.startswith('FLEET-BOOTSTRAP:')) != 1: fail('the installer did not verify exactly the admitted bootstrap data on disk') + # Lab evidence only: the booted guest found the same data where + # it reads it. The worker never waits for this line. + disk_log = directory / 'disk.log' + lines = [line.strip() for line in disk_log.read_text(errors='replace').splitlines()] if disk_log.exists() else [] + if lines.count(guest_line(seeded)) != 1 or sum(1 for l in lines if l.startswith('FLEET-GUEST-BOOTSTRAP:')) != 1: + fail('the booted guest did not find exactly the admitted bootstrap data on first boot') bootstrapped.append(uid) for filename, marker in (('installer.log', 'FLEET-INSTALLED:'), ('disk.log', 'FLEET-DISK-BOOT:')): p = directory / filename @@ -295,8 +307,9 @@ def redfish_provider(): seeded = bootstrap_line(provider, o, boot['receipt']) if o['kind'] == 'DeviceInstallation' else None if seeded: bootstrapped.append(o['operation']) - # The installer prints its bootstrap check just before its own receipt. - want = (([seeded] if seeded else []) + ['FLEET-INSTALLED:' + boot['receipt'], 'FLEET-DISK-BOOT:' + boot['receipt']]) if o['kind'] == 'DeviceInstallation' else ['FLEET-WIPED:%s:%d' % (boot['receipt'], a['diskBytes'])] + # The installer prints its bootstrap check just before its own receipt, + # and the lab guest its first-boot report just before the disk receipt. + want = (([seeded] if seeded else []) + ['FLEET-INSTALLED:' + boot['receipt']] + ([guest_line(seeded)] if seeded else []) + ['FLEET-DISK-BOOT:' + boot['receipt']]) if o['kind'] == 'DeviceInstallation' else ['FLEET-WIPED:%s:%d' % (boot['receipt'], a['diskBytes'])] for line in want: if console.count(line) != 1: fail('expected exactly one exact console receipt %s for %s' % (line.split(':')[0], o['kind']))