From 00111b784b8f2dc87942119e6cf6135eed196bfa Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 25 Nov 2026 18:43:46 -0600 Subject: [PATCH 1/2] feat(metal): Resolve Installation images through a published catalog Installations named an image as name@sha256 and only a test parser read it. The provider now defines immutable MachineImages by digest and publishes them into consumer tenants. A published copy names its publisher with a typed publisherRef plus the image's name, and a protected publication record names the consumer with a typed consumerRef. A tenant is a Milo Project, or a Namespace in standalone mode; every other kind is refused, and Publish writes nothing for one. No spec holds an object UID. The record's name derives from the consumer tenant, copy and provider image UIDs, and its spec holds names and the digest. Admission reads the copy and the provider image, looks up the record under the derived name, and refuses a missing record, so a recreated tenant, copy or provider image is refused. Republishing a recreated image writes its own record. Admission also refuses a withdrawn image and checks architecture and firmware mode against the allocation's hardware. The DeviceInstallation keeps the digest and the image's firmware modes, and each install worker reads the server's firmware mode again before it sends anything. Customer roles may only read and use images, and the publisher may delete stale records. The standalone and multi-plane compositions publish their one image and resolve it with a fixture authorizer. Co-Authored-By: Claude Opus 5.5 --- config/base/crd/metal.datumapis.com.yaml | 136 ++++++ .../crds/fleet.datumapis.com.yaml | 8 + .../protected-resources/kustomization.yaml | 2 + .../iam/protected-resources/machineimage.yaml | 14 + .../machineimagepublication.yaml | 14 + config/components/iam/roles/claimant.yaml | 1 + config/components/iam/roles/consumer.yaml | 1 + config/components/iam/roles/controller.yaml | 4 + config/components/iam/roles/provider.yaml | 8 + config/components/iam/roles/publisher.yaml | 12 + config/components/iam/roles/viewer.yaml | 3 + config/standalone/fixtures.yaml | 18 +- config/standalone/rbac.yaml | 21 + docs/development/README.md | 6 + docs/development/machine-images.md | 80 ++++ hack/multiplane/milo.py | 4 +- internal/allocation/allocator.go | 25 +- internal/allocation/flow_test.go | 22 +- internal/allocation/harness_test.go | 13 +- internal/allocation/incarnation_test.go | 4 +- internal/api/operations/v1alpha1/types.go | 3 + internal/api/v1alpha1/crd_test.go | 4 +- internal/api/v1alpha1/crd_validation_test.go | 102 +++++ internal/api/v1alpha1/iam_test.go | 99 +++++ internal/api/v1alpha1/types.go | 129 +++++- internal/api/v1alpha1/types_test.go | 2 + internal/catalog/catalog.go | 234 ++++++++++ internal/catalog/catalog_test.go | 415 ++++++++++++++++++ internal/custody/kinds.go | 5 +- internal/multiplane/runner.go | 28 +- internal/multiplane/seed.go | 28 +- internal/redfish/client.go | 9 + internal/redfish/client_test.go | 17 + internal/site/redfishwork/kinds.go | 5 + internal/site/redfishwork/kinds_test.go | 19 +- internal/site/vmwork/kinds.go | 5 + internal/site/vmwork/kinds_test.go | 14 +- internal/standalone/runner.go | 42 +- 38 files changed, 1510 insertions(+), 46 deletions(-) create mode 100644 config/components/iam/protected-resources/machineimage.yaml create mode 100644 config/components/iam/protected-resources/machineimagepublication.yaml create mode 100644 docs/development/machine-images.md create mode 100644 internal/api/v1alpha1/iam_test.go create mode 100644 internal/catalog/catalog.go create mode 100644 internal/catalog/catalog_test.go diff --git a/config/base/crd/metal.datumapis.com.yaml b/config/base/crd/metal.datumapis.com.yaml index 481cb14b..bfb7b332 100644 --- a/config/base/crd/metal.datumapis.com.yaml +++ b/config/base/crd/metal.datumapis.com.yaml @@ -509,7 +509,143 @@ spec: type: object properties: phase: {type: string} + resolvedImage: + type: object + required: [name, digest] + properties: + name: {type: string, minLength: 1} + digest: {type: string, pattern: '^sha256:[a-f0-9]{64}$'} completedAt: {type: string, format: date-time} conditions: type: array items: {type: object, x-kubernetes-preserve-unknown-fields: true} +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: machineimages.metal.datumapis.com + annotations: + discovery.miloapis.com/parent-contexts: Project +spec: + group: metal.datumapis.com + names: {kind: MachineImage, listKind: MachineImageList, plural: machineimages, singular: machineimage, shortNames: [mimg]} + scope: Namespaced + versions: + - name: v1alpha1 + served: true + storage: true + subresources: {status: {}} + additionalPrinterColumns: + - {name: Availability, type: string, jsonPath: .spec.availability} + schema: + openAPIV3Schema: + type: object + properties: + apiVersion: {type: string} + kind: {type: string} + metadata: {type: object} + spec: + type: object + x-kubernetes-validations: + - rule: >- + (has(self.definition) && !has(self.source) && has(self.availability)) || + (!has(self.definition) && has(self.source) && !has(self.availability)) + message: an image is either a provider definition with an availability or a published source reference + - rule: >- + has(self.definition) == has(oldSelf.definition) && + (!has(self.definition) || self.definition == oldSelf.definition) && + (!has(self.source) || self.source == oldSelf.source) + message: an image's definition and source are immutable + properties: + definition: + type: object + required: [family, version, architecture, firmwareModes, digest] + properties: + family: {type: string, minLength: 1, maxLength: 63} + version: {type: string, minLength: 1, maxLength: 63} + architecture: {type: string, minLength: 1, maxLength: 63} + firmwareModes: + type: array + minItems: 1 + maxItems: 2 + x-kubernetes-list-type: set + items: {type: string, enum: [UEFI, BIOS]} + bootstrapFormats: + type: array + maxItems: 1 + x-kubernetes-list-type: set + items: {type: string, enum: [NoCloud]} + digest: {type: string, pattern: '^sha256:[a-f0-9]{64}$'} + source: + type: object + required: [publisherRef, name] + properties: + publisherRef: + type: object + required: [kind, name] + x-kubernetes-validations: + - rule: '(self.kind == "Project" && has(self.apiGroup) && self.apiGroup == "resourcemanager.miloapis.com") || (self.kind == "Namespace" && (!has(self.apiGroup) || self.apiGroup == ""))' + message: a publisher is a Milo Project or a standalone Namespace + properties: + apiGroup: {type: string} + kind: {type: string, minLength: 1} + name: {type: string, minLength: 1} + name: {type: string, minLength: 1} + availability: {type: string, enum: [Available, Withdrawn]} + status: + type: object + properties: + resolved: {type: object, x-kubernetes-preserve-unknown-fields: true} + conditions: + type: array + items: {type: object, x-kubernetes-preserve-unknown-fields: true} +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: machineimagepublications.metal.datumapis.com + annotations: + discovery.miloapis.com/parent-contexts: Project +spec: + group: metal.datumapis.com + names: {kind: MachineImagePublication, listKind: MachineImagePublicationList, plural: machineimagepublications, singular: machineimagepublication} + scope: Namespaced + versions: + - name: v1alpha1 + served: true + storage: true + schema: + openAPIV3Schema: + type: object + properties: + apiVersion: {type: string} + kind: {type: string} + metadata: {type: object} + spec: + type: object + x-kubernetes-validations: + - {rule: 'self == oldSelf', message: a publication record is immutable} + required: [consumerRef, image, source, digest] + properties: + consumerRef: + type: object + required: [kind, name] + x-kubernetes-validations: + - rule: '(self.kind == "Project" && has(self.apiGroup) && self.apiGroup == "resourcemanager.miloapis.com") || (self.kind == "Namespace" && (!has(self.apiGroup) || self.apiGroup == ""))' + message: a consumer is a Milo Project or a standalone Namespace + properties: + apiGroup: {type: string} + kind: {type: string, minLength: 1} + name: {type: string, minLength: 1} + image: + type: object + required: [namespace, name] + properties: + namespace: {type: string, minLength: 1} + name: {type: string, minLength: 1} + source: + type: object + required: [name] + properties: + name: {type: string, minLength: 1} + digest: {type: string, pattern: '^sha256:[a-f0-9]{64}$'} diff --git a/config/components/device-operations/crds/fleet.datumapis.com.yaml b/config/components/device-operations/crds/fleet.datumapis.com.yaml index 42fc7e92..334ee7d8 100644 --- a/config/components/device-operations/crds/fleet.datumapis.com.yaml +++ b/config/components/device-operations/crds/fleet.datumapis.com.yaml @@ -488,6 +488,14 @@ spec: digest: type: string pattern: ^sha256:[0-9a-f]{64}$ + firmwareModes: + type: array + maxItems: 2 + items: + type: string + enum: + - UEFI + - BIOS required: - name - digest diff --git a/config/components/iam/protected-resources/kustomization.yaml b/config/components/iam/protected-resources/kustomization.yaml index 1fe1bed8..48436f24 100644 --- a/config/components/iam/protected-resources/kustomization.yaml +++ b/config/components/iam/protected-resources/kustomization.yaml @@ -7,3 +7,5 @@ resources: - machinecapacity.yaml - machineallocation.yaml - installation.yaml + - machineimage.yaml + - machineimagepublication.yaml diff --git a/config/components/iam/protected-resources/machineimage.yaml b/config/components/iam/protected-resources/machineimage.yaml new file mode 100644 index 00000000..96105793 --- /dev/null +++ b/config/components/iam/protected-resources/machineimage.yaml @@ -0,0 +1,14 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: metal.datumapis.com-machineimage +spec: + serviceRef: + name: metal.datumapis.com + kind: MachineImage + plural: machineimages + singular: machineimage + permissions: [list, get, watch, create, update, patch, delete, updateStatus, use] + parentResources: + - apiGroup: resourcemanager.miloapis.com + kind: Project diff --git a/config/components/iam/protected-resources/machineimagepublication.yaml b/config/components/iam/protected-resources/machineimagepublication.yaml new file mode 100644 index 00000000..44a4f67e --- /dev/null +++ b/config/components/iam/protected-resources/machineimagepublication.yaml @@ -0,0 +1,14 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: metal.datumapis.com-machineimagepublication +spec: + serviceRef: + name: metal.datumapis.com + kind: MachineImagePublication + plural: machineimagepublications + singular: machineimagepublication + permissions: [list, get, watch, create, delete] + parentResources: + - apiGroup: resourcemanager.miloapis.com + kind: Project diff --git a/config/components/iam/roles/claimant.yaml b/config/components/iam/roles/claimant.yaml index 4bfa49d4..ee55173f 100644 --- a/config/components/iam/roles/claimant.yaml +++ b/config/components/iam/roles/claimant.yaml @@ -12,6 +12,7 @@ spec: includedPermissions: - metal.datumapis.com/machineclasses.use - metal.datumapis.com/machineprofiles.use + - metal.datumapis.com/machineimages.use - metal.datumapis.com/machines.create - metal.datumapis.com/machines.update - metal.datumapis.com/machines.patch diff --git a/config/components/iam/roles/consumer.yaml b/config/components/iam/roles/consumer.yaml index 79d4a471..eadb061f 100644 --- a/config/components/iam/roles/consumer.yaml +++ b/config/components/iam/roles/consumer.yaml @@ -15,6 +15,7 @@ spec: - metal.datumapis.com/machineprofiles.patch - metal.datumapis.com/machineprofiles.delete - metal.datumapis.com/machineprofiles.use + - metal.datumapis.com/machineimages.use - metal.datumapis.com/machines.create - metal.datumapis.com/machines.update - metal.datumapis.com/machines.patch diff --git a/config/components/iam/roles/controller.yaml b/config/components/iam/roles/controller.yaml index 5739cf1b..6c165b82 100644 --- a/config/components/iam/roles/controller.yaml +++ b/config/components/iam/roles/controller.yaml @@ -26,3 +26,7 @@ spec: - metal.datumapis.com/machineallocations.patch - metal.datumapis.com/machineallocations.updateStatus - metal.datumapis.com/installations.updateStatus + # Admission resolves an image through its publication record. + - metal.datumapis.com/machineimagepublications.list + - metal.datumapis.com/machineimagepublications.get + - metal.datumapis.com/machineimagepublications.watch diff --git a/config/components/iam/roles/provider.yaml b/config/components/iam/roles/provider.yaml index d0517411..7566d8b0 100644 --- a/config/components/iam/roles/provider.yaml +++ b/config/components/iam/roles/provider.yaml @@ -24,6 +24,14 @@ spec: - metal.datumapis.com/machineprofiles.patch - metal.datumapis.com/machineprofiles.delete - metal.datumapis.com/machineprofiles.use + - metal.datumapis.com/machineimages.list + - metal.datumapis.com/machineimages.get + - metal.datumapis.com/machineimages.watch + - metal.datumapis.com/machineimages.create + - metal.datumapis.com/machineimages.update + - metal.datumapis.com/machineimages.patch + - metal.datumapis.com/machineimages.delete + - metal.datumapis.com/machineimages.use - metal.datumapis.com/machinecapacities.list - metal.datumapis.com/machinecapacities.get - metal.datumapis.com/machinecapacities.watch diff --git a/config/components/iam/roles/publisher.yaml b/config/components/iam/roles/publisher.yaml index 97793bbe..f3c31d52 100644 --- a/config/components/iam/roles/publisher.yaml +++ b/config/components/iam/roles/publisher.yaml @@ -20,3 +20,15 @@ spec: - metal.datumapis.com/machineprofiles.patch - metal.datumapis.com/machineprofiles.delete - metal.datumapis.com/machineprofiles.updateStatus + # Publishing an image writes the consumer copy and the provider's + # publication record. Unpublishing deletes both, which is also how a + # publication is repaired after its copy or source is recreated. + # Customers hold no write on either kind. + - metal.datumapis.com/machineimages.create + - metal.datumapis.com/machineimages.update + - metal.datumapis.com/machineimages.patch + - metal.datumapis.com/machineimages.delete + - metal.datumapis.com/machineimages.updateStatus + - metal.datumapis.com/machineimagepublications.get + - metal.datumapis.com/machineimagepublications.create + - metal.datumapis.com/machineimagepublications.delete diff --git a/config/components/iam/roles/viewer.yaml b/config/components/iam/roles/viewer.yaml index 2899e220..a76afba6 100644 --- a/config/components/iam/roles/viewer.yaml +++ b/config/components/iam/roles/viewer.yaml @@ -20,3 +20,6 @@ spec: - metal.datumapis.com/installations.list - metal.datumapis.com/installations.get - metal.datumapis.com/installations.watch + - metal.datumapis.com/machineimages.list + - metal.datumapis.com/machineimages.get + - metal.datumapis.com/machineimages.watch diff --git a/config/standalone/fixtures.yaml b/config/standalone/fixtures.yaml index d4f0d938..1163e077 100644 --- a/config/standalone/fixtures.yaml +++ b/config/standalone/fixtures.yaml @@ -29,6 +29,20 @@ spec: bmc: {endpoint: "https://[2001:db8::21]"} interfaces: [{name: primary, macAddress: "02:00:00:00:00:21"}] --- +# The provider's one image release. The allocate phase publishes it into the +# first consumer namespace, which stands in for a consumer project. +apiVersion: metal.datumapis.com/v1alpha1 +kind: MachineImage +metadata: {name: debian-12, namespace: fleet-provider} +spec: + definition: + family: debian + version: "12" + architecture: amd64 + firmwareModes: [UEFI] + digest: "sha256:9f4ad8d8b8a6f6fc64d2cf2c7e70b9184b74f089adf8c36d84f4fcb99892f3cb" + availability: Available +--- apiVersion: metal.datumapis.com/v1alpha1 kind: MachineCapacity metadata: @@ -65,7 +79,7 @@ metadata: {name: debian-12, namespace: fleet-project-a} spec: machineRef: {name: allocation} expectedPredecessor: {type: None} - imageRef: {name: "debian-12@sha256:9f4ad8d8b8a6f6fc64d2cf2c7e70b9184b74f089adf8c36d84f4fcb99892f3cb"} + imageRef: {name: debian-12} --- apiVersion: metal.datumapis.com/v1alpha1 kind: Installation @@ -73,4 +87,4 @@ metadata: {name: debian-12-reinstall, namespace: fleet-project-a} spec: machineRef: {name: allocation} expectedPredecessor: {type: Installation, name: debian-12} - imageRef: {name: "debian-12@sha256:9f4ad8d8b8a6f6fc64d2cf2c7e70b9184b74f089adf8c36d84f4fcb99892f3cb"} + imageRef: {name: debian-12} diff --git a/config/standalone/rbac.yaml b/config/standalone/rbac.yaml index 3c5e477b..edf6eb46 100644 --- a/config/standalone/rbac.yaml +++ b/config/standalone/rbac.yaml @@ -49,6 +49,15 @@ rules: - apiGroups: [fleet.datumapis.com] resources: [deviceinstallations] verbs: [get, list, create] + # As the provider's publisher, it reads the image it publishes and records + # each publication; as the provider, it resolves images through them. + - apiGroups: [metal.datumapis.com] + resources: [machineimages] + resourceNames: [debian-12] + verbs: [get] + - apiGroups: [metal.datumapis.com] + resources: [machineimagepublications] + verbs: [get, create, delete] - apiGroups: [fleet.datumapis.com] resources: [devices, devicecustodies] verbs: [get] @@ -64,6 +73,18 @@ apiVersion: rbac.authorization.k8s.io/v1 kind: Role metadata: {name: fleet-synthetic-consumer-writer, namespace: fleet-project-a} rules: + # The publisher's copy of the provider image. + - apiGroups: [metal.datumapis.com] + resources: [machineimages] + verbs: [create] + - apiGroups: [metal.datumapis.com] + resources: [machineimages] + resourceNames: [debian-12] + verbs: [get] + - apiGroups: [metal.datumapis.com] + resources: [machineimages/status] + resourceNames: [debian-12] + verbs: [get, update] - apiGroups: [metal.datumapis.com] resources: [machines] resourceNames: [allocation] diff --git a/docs/development/README.md b/docs/development/README.md index faf64def..70afc8ff 100644 --- a/docs/development/README.md +++ b/docs/development/README.md @@ -38,6 +38,12 @@ Secret-backed coordinator, its private records and the old executors are deleted and an allocation's private facts live on its MachineAllocation. The standalone 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 +proposed. + 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 custody coordinator, and actual Karmada delivery. On the selected cell the site diff --git a/docs/development/machine-images.md b/docs/development/machine-images.md new file mode 100644 index 00000000..d7577699 --- /dev/null +++ b/docs/development/machine-images.md @@ -0,0 +1,80 @@ +# OS images and bootstrap data + +[Documentation overview](../README.md) ยท [Implementation status](README.md) + +This page records how Fleet implements the [OS images and bootstrap data +proposal](https://github.com/datum-cloud/fleet/pull/184) (#184). The +proposal's API names are provisional. Each piece below is marked +**implemented and verified**, **implemented in lab compositions only**, or +**proposed**. + +## Status + +| Increment | What it covers | Status | +| --- | --- | --- | +| 1: image catalog | `MachineImage` and `MachineImagePublication` kinds, publication, admission-time resolution to a pinned digest, architecture and firmware mode checks, the worker's firmware mode check, and IAM | **Implemented and verified.** The CRD rules are checked with the API server's own schema validator, resolution and publication with a fake API server, and installs of a resolved image against a real API server and in the standalone smoke. The multi-plane runs are not yet verified. | +| 2: sealed bootstrap store | `SealedPayload`, delivery to the operation's worker, deletion | **Proposed** | +| 3: lab proof | A chosen image with bootstrap data installs in the local VM and Redfish labs, and the guest reports the data it received | **Proposed** | + +## What increment 1 adds + +- **Kinds.** `MachineImage` holds either a provider `definition` or a published + `source`: a `publisherRef` and the image's name there. CEL makes the + definition and the source immutable and lets the provider change only + `availability`. `MachineImagePublication` is the immutable record, in the + provider project, of one consumer copy published from one provider image + incarnation and digest. Its `consumerRef` names the consumer tenant. Its + name derives from the tenant reference and UID, the copy's namespace, name + and UID, and the provider image's name and UID. Its spec holds only names + and the digest, never a UID. +- **Tenant references.** `publisherRef` and `consumerRef` are typed + `{apiGroup, kind, name}` references with names only. A Milo `Project` is + the tenant in multi-plane mode, and a `Namespace` in standalone mode, where + the provider namespace is the publisher. The CRD rules and the catalog + refuse every other kind, and the catalog writes nothing for one. The + catalog takes its consumer from the shared tenancy resolver, with the + reference, incarnation and API client together, and uses the same typed + reference and source shape as MachineClass. +- **Publication.** The publisher writes the consumer copy, then the record. + Until the record exists the copy entitles nothing, so a crash between the + writes fails closed and a retry completes it. +- **Resolution.** Admission reads the consumer copy and the provider image, + derives the record's name from their incarnations and the consumer + tenant's, and refuses unless that record exists and matches the names and + the provider image's digest. A recreated tenant, copy or provider image + finds no record and is refused. The digest comes from the record, never from + the copy's status. The provider definition is immutable, so the digest pins + its content; `availability` is read live. A Fleet deployment serves one + publisher, which also holds every allocation, so a copy must name that + publisher. +- **Republishing.** A record never changes. If a copy or its source is + recreated, publishing it again writes a new record under its own name. The + old record entitles nothing, and the publisher may delete it. +- **Compatibility.** The allocation's hardware snapshot records the server's + firmware mode. Admission refuses an image whose architecture differs, whose + firmware modes do not include the server's, or which takes no bootstrap data + when the Installation has some. An unknown firmware mode installs nothing. +- **Retention.** The DeviceInstallation keeps the image name, digest and + firmware modes, so later catalog changes never change an admitted install. + The Installation reports `status.resolvedImage`. +- **Worker check.** The Redfish worker reads the system's + `BootSourceOverrideMode` and refuses with `ImageIncompatible` before sending + anything if the image does not list it. Redfish defines that property as the + mode of the next override boot, which is the boot the installer uses. A BMC + that does not report it installs nothing. The Redfish lab reports `Legacy`. + Physical BMCs are not qualified. The local VM worker refuses any image that + does not list BIOS, which its guests boot. +- **IAM.** Customer roles may only read and use images. Only the provider and + publisher roles write images, only the publisher writes records, and only + the publisher and the Fleet provider read records. + +## Not implemented yet + +- The validating webhook that rejects image writes from anyone but the + publisher, and definitions outside provider projects. IAM alone keeps + customers from writing images today. +- A Milo IAM image-use check. The standalone and multi-plane compositions use a + fixture authorizer that allows every creator. +- 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. diff --git a/hack/multiplane/milo.py b/hack/multiplane/milo.py index 5e5ee1c2..5858a60c 100755 --- a/hack/multiplane/milo.py +++ b/hack/multiplane/milo.py @@ -77,7 +77,7 @@ def wait(fn,seconds,what): kubectl(config,'wait','--for=condition=Established','crd','--all','--timeout=90s',stdout=subprocess.DEVNULL) ns='fleet-provider' if role=='provider' else 'default' apply(config,{'apiVersion':'v1','kind':'Namespace','metadata':{'name':ns}}) - rules=[{'apiGroups':[''],'resources':['namespaces'],'verbs':['get']},{'apiGroups':['metal.datumapis.com'],'resources':['machineclasses','machineprofiles','machinecapacities','machines','installations'],'verbs':['get','list','watch']}] + rules=[{'apiGroups':[''],'resources':['namespaces'],'verbs':['get']},{'apiGroups':['metal.datumapis.com'],'resources':['machineclasses','machineprofiles','machinecapacities','machines','installations','machineimages'],'verbs':['get','list','watch']}] if role=='provider': for crds in ('config/components/inventory/crds/fleet.datumapis.com.yaml','config/components/device-operations/crds/fleet.datumapis.com.yaml'): kubectl(config,'apply','-f',crds,stdout=subprocess.DEVNULL) @@ -88,7 +88,7 @@ def wait(fn,seconds,what): apply(config,{'apiVersion':'v1','kind':'Namespace','metadata':{'name':'fleet-rules'}}) # The Metal provider records allocations and creates installations; it # reads custody and Devices only to skip taken capacity. - rules+=[{'apiGroups':['metal.datumapis.com'],'resources':['machineallocations'],'verbs':['get','list','watch','create','delete']},{'apiGroups':['metal.datumapis.com'],'resources':['machineallocations/status'],'verbs':['get','update']}, + rules+=[{'apiGroups':['metal.datumapis.com'],'resources':['machineallocations'],'verbs':['get','list','watch','create','delete']},{'apiGroups':['metal.datumapis.com'],'resources':['machineallocations/status'],'verbs':['get','update']},{'apiGroups':['metal.datumapis.com'],'resources':['machineimagepublications'],'verbs':['get']}, {'apiGroups':['fleet.datumapis.com'],'resources':['deviceinstallations'],'verbs':['get','list','watch','create']},{'apiGroups':['fleet.datumapis.com'],'resources':['devices','devicecustodies'],'verbs':['get','list','watch']}] components={ 'coordinator':[{'apiGroups':['fleet.datumapis.com'],'resources':['devices'],'verbs':['get','list','watch']},{'apiGroups':['fleet.datumapis.com'],'resources':['devicecustodies'],'verbs':['get','list','watch','create','update','delete']}, diff --git a/internal/allocation/allocator.go b/internal/allocation/allocator.go index 9285255d..e3864df3 100644 --- a/internal/allocation/allocator.go +++ b/internal/allocation/allocator.go @@ -30,6 +30,7 @@ import ( inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" ops "go.datum.net/fleet/internal/api/operations/v1alpha1" fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/catalog" "go.datum.net/fleet/internal/custody" "go.datum.net/fleet/internal/tenancy" ) @@ -350,17 +351,10 @@ type Installation struct { Installation *fleetv1.Installation // Current is the Machine's current installation, or empty. Current string -} - -// ParseImage splits an image reference into its name and digest. Fleet -// installs only images pinned by digest. -func ParseImage(reference string) (ops.ImageInput, error) { - name, digest, ok := strings.Cut(reference, "@") - hexDigest, sha := strings.CutPrefix(digest, "sha256:") - if !ok || name == "" || !sha || len(hexDigest) != 64 || strings.Trim(hexDigest, "0123456789abcdef") != "" { - return ops.ImageInput{}, fmt.Errorf("%w: the image must be name@sha256:<64 hex>", ErrUnsupported) - } - return ops.ImageInput{Name: name, Digest: digest}, nil + // Image is the provider image the catalog resolved for the + // Installation. Install checks it against the allocation's hardware + // and retains its digest on the operation. + Image catalog.Image } // Install creates the DeviceInstallation for an Installation. It is @@ -377,8 +371,11 @@ func (a *Allocator) Install(ctx context.Context, allocation *fleetv1.MachineAllo if (request.Current == "" && predecessor.Type != "None") || (request.Current != "" && (predecessor.Type != "Installation" || predecessor.Name != request.Current)) { return nil, ErrPredecessor } - image, err := ParseImage(installation.Spec.ImageRef.Name) - if err != nil { + image := request.Image + if image.Name == "" || image.Definition.Digest == "" { + return nil, fmt.Errorf("%w: the image is not resolved", ErrUnsupported) + } + if err := catalog.Compatible(image.Definition, allocation.Spec.Hardware, installation.Spec.BootstrapConfigRef != nil); err != nil { return nil, err } labels := operationLabels(allocation) @@ -387,7 +384,7 @@ func (a *Allocator) Install(ctx context.Context, allocation *fleetv1.MachineAllo ObjectMeta: metav1.ObjectMeta{Name: custody.InstallationName(allocation.Name, string(installation.UID)), Namespace: a.Namespace, Labels: labels}, Spec: ops.DeviceInstallationSpec{ OperationEnvelope: a.envelope(allocation, a.ProviderCreator), - Image: image, + Image: ops.ImageInput{Name: image.Name, Digest: image.Definition.Digest, FirmwareModes: slices.Clone(image.Definition.FirmwareModes)}, BootInterface: allocation.Spec.BootInterface, TargetDisks: slices.Clone(allocation.Spec.TargetDisks), }, diff --git a/internal/allocation/flow_test.go b/internal/allocation/flow_test.go index bd2815ec..b0a03eb8 100644 --- a/internal/allocation/flow_test.go +++ b/internal/allocation/flow_test.go @@ -2,6 +2,7 @@ package allocation import ( "errors" + "strings" "sync" "testing" @@ -10,6 +11,7 @@ import ( ops "go.datum.net/fleet/internal/api/operations/v1alpha1" fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/catalog" "go.datum.net/fleet/internal/custody" "go.datum.net/fleet/internal/site/simwork" ) @@ -50,7 +52,7 @@ func TestAllocateInstallReleaseReuse(t *testing.T) { install := func(allocation *fleetv1.MachineAllocation, installation *fleetv1.Installation, current string) *ops.DeviceInstallation { t.Helper() - operation, err := e.allocator.Install(e.ctx, allocation, Installation{Installation: installation, Current: current}) + operation, err := e.allocator.Install(e.ctx, allocation, Installation{Installation: installation, Current: current, Image: image()}) if err != nil { t.Fatal(err) } @@ -74,9 +76,25 @@ func TestAllocateInstallReleaseReuse(t *testing.T) { t.Fatalf("server = %+v, %v", server, err) } // A reinstall must name the current installation. - if _, err := e.allocator.Install(e.ctx, first, Installation{Installation: e.installation(2, "debian-12-reinstall", "elsewhere"), Current: "debian-12"}); !errors.Is(err, ErrPredecessor) { + if _, err := e.allocator.Install(e.ctx, first, Installation{Installation: e.installation(2, "debian-12-reinstall", "elsewhere"), Current: "debian-12", Image: image()}); !errors.Is(err, ErrPredecessor) { t.Fatalf("stale predecessor err = %v", err) } + // The operation retains the resolved digest and the image's firmware + // modes for the worker's check. + if initial.Spec.Image.Digest != imageDigest || initial.Spec.Image.Name != imageName || len(initial.Spec.Image.FirmwareModes) != 1 { + t.Fatalf("image input = %+v", initial.Spec.Image) + } + // An image that does not match the allocated hardware is refused + // before any operation exists. + incompatible := image() + incompatible.Definition.Architecture = "arm64" + refused := e.installation(3, "arm-image", "debian-12") + if _, err := e.allocator.Install(e.ctx, first, Installation{Installation: refused, Current: "debian-12", Image: incompatible}); err == nil || !strings.Contains(err.Error(), catalog.ReasonImageIncompatible) { + t.Fatalf("incompatible image err = %v", err) + } + if err := e.admin.Get(e.ctx, client.ObjectKey{Namespace: namespace, Name: custody.InstallationName(first.Name, string(refused.UID))}, &ops.DeviceInstallation{}); !apierrors.IsNotFound(err) { + t.Fatalf("a refused image created an operation: %v", err) + } reinstall := install(first, e.installation(2, "debian-12-reinstall", "debian-12"), "debian-12") if reinstall.Status.Fence <= initial.Status.Fence { t.Fatalf("reinstall fence %d, initial %d", reinstall.Status.Fence, initial.Status.Fence) diff --git a/internal/allocation/harness_test.go b/internal/allocation/harness_test.go index 0079bf7e..9825b7a4 100644 --- a/internal/allocation/harness_test.go +++ b/internal/allocation/harness_test.go @@ -21,6 +21,7 @@ import ( inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" ops "go.datum.net/fleet/internal/api/operations/v1alpha1" fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/catalog" "go.datum.net/fleet/internal/custody" "go.datum.net/fleet/internal/delivery" "go.datum.net/fleet/internal/site" @@ -37,7 +38,8 @@ const ( siteName = "site-example-a" siteToken = "synthetic-site-token" keyDigest = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - imageRef = "debian-12@sha256:9f4ad8d8b8a6f6fc64d2cf2c7e70b9184b74f089adf8c36d84f4fcb99892f3cb" + imageName = "debian-12" + imageDigest = "sha256:9f4ad8d8b8a6f6fc64d2cf2c7e70b9184b74f089adf8c36d84f4fcb99892f3cb" policyDigest = "sha256:0c2b77e1d9a4000000000000000000000000000000000000000000000000cafe" ) @@ -160,7 +162,7 @@ func (e *env) server(n int) *inventory.Device { capacity := &fleetv1.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: "capacity-" + name, Namespace: namespace, Labels: map[string]string{"pool": "example"}}, Spec: fleetv1.MachineCapacitySpec{DeviceRef: fleetv1.LocalReference{Name: name}, AllocationPolicy: "Enabled", CleaningPolicyRef: fleetv1.LocalReference{Name: "example-cleaning"}, ReclaimPolicy: "Retain"}} e.create(capacity) - capacity.Status.Hardware = fleetv1.Hardware{CPU: fleetv1.HardwareCPU{Architecture: "amd64", Cores: 2}, Memory: fleetv1.HardwareMemory{Capacity: "2Gi"}} + capacity.Status.Hardware = fleetv1.Hardware{CPU: fleetv1.HardwareCPU{Architecture: "amd64", Cores: 2}, Firmware: &fleetv1.HardwareFirmware{BootMode: fleetv1.FirmwareUEFI}, Memory: fleetv1.HardwareMemory{Capacity: "2Gi"}} for _, kind := range []string{"Prepared", "Healthy", "Available"} { capacity.Status.Conditions = append(capacity.Status.Conditions, metav1.Condition{Type: kind, Status: metav1.ConditionTrue, Reason: "Fixture", ObservedGeneration: capacity.Generation, LastTransitionTime: metav1.Now()}) } @@ -210,13 +212,18 @@ func (e *env) request(n int) Request { func (e *env) installation(n int, name, predecessor string) *fleetv1.Installation { installation := &fleetv1.Installation{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: "default", UID: types.UID(uid(700 + n))}, - Spec: fleetv1.InstallationSpec{MachineRef: fleetv1.MachineReference{Name: "allocation"}, ImageRef: fleetv1.LocalReference{Name: imageRef}, ExpectedPredecessor: fleetv1.InstallationPredecessor{Type: "None"}}} + Spec: fleetv1.InstallationSpec{MachineRef: fleetv1.MachineReference{Name: "allocation"}, ImageRef: fleetv1.LocalReference{Name: imageName}, ExpectedPredecessor: fleetv1.InstallationPredecessor{Type: "None"}}} if predecessor != "" { installation.Spec.ExpectedPredecessor = fleetv1.InstallationPredecessor{Type: "Installation", Name: predecessor} } return installation } +// image is the catalog's resolution of the fixture image. +func image() catalog.Image { + return catalog.Image{Name: imageName, Definition: fleetv1.ImageDefinition{Family: "debian", Version: "12", Architecture: "amd64", FirmwareModes: []string{fleetv1.FirmwareUEFI}, Digest: imageDigest}} +} + // release repeats Release while the coordinator runs, until it is Released. func (e *env) release(allocation *fleetv1.MachineAllocation, owner Machine) { e.t.Helper() diff --git a/internal/allocation/incarnation_test.go b/internal/allocation/incarnation_test.go index 2f968b53..2118e2f5 100644 --- a/internal/allocation/incarnation_test.go +++ b/internal/allocation/incarnation_test.go @@ -67,7 +67,7 @@ func TestAnOperationForAnotherDeviceIncarnationIsAConflict(t *testing.T) { t.Fatal(err) } installation := e.installation(1, "first", "") - operation, err := e.allocator.Install(e.ctx, allocation, Installation{Installation: installation}) + operation, err := e.allocator.Install(e.ctx, allocation, Installation{Installation: installation, Image: image()}) if err != nil { t.Fatal(err) } @@ -79,7 +79,7 @@ func TestAnOperationForAnotherDeviceIncarnationIsAConflict(t *testing.T) { if err := e.admin.Update(e.ctx, stored); err != nil { t.Fatal(err) } - if _, err := e.allocator.Install(e.ctx, allocation, Installation{Installation: installation}); !errors.Is(err, ErrConflict) { + if _, err := e.allocator.Install(e.ctx, allocation, Installation{Installation: installation, Image: image()}); !errors.Is(err, ErrConflict) { t.Fatalf("an operation recorded for another Device incarnation: %v", err) } if stored.Spec.DeviceRef.Name != device.Name { diff --git a/internal/api/operations/v1alpha1/types.go b/internal/api/operations/v1alpha1/types.go index 40190461..80523ecf 100644 --- a/internal/api/operations/v1alpha1/types.go +++ b/internal/api/operations/v1alpha1/types.go @@ -308,6 +308,9 @@ type DeviceInstallationSpec struct { type ImageInput struct { Name string `json:"name"` Digest string `json:"digest"` + // FirmwareModes are the image's firmware modes. The worker reads the + // server's mode again before it sends anything. + FirmwareModes []string `json:"firmwareModes,omitempty"` } // SealedInput is an opaque reference into the sealed store and the digest of diff --git a/internal/api/v1alpha1/crd_test.go b/internal/api/v1alpha1/crd_test.go index 22bcbad4..64eec737 100644 --- a/internal/api/v1alpha1/crd_test.go +++ b/internal/api/v1alpha1/crd_test.go @@ -40,8 +40,8 @@ func TestAllocationCRDContract(t *testing.T) { if GroupVersion.Group != "metal.datumapis.com" || GroupVersion.Version != "v1alpha1" { t.Fatalf("unexpected public API identity: %s", GroupVersion) } - if len(crds) != 6 { - t.Fatalf("got %d allocation CRDs, want 6", len(crds)) + if len(crds) != 8 { + t.Fatalf("got %d allocation CRDs, want 8", len(crds)) } for _, crd := range crds { if crd.Spec.Group != GroupVersion.Group || crd.Name != crd.Spec.Names.Plural+"."+GroupVersion.Group { diff --git a/internal/api/v1alpha1/crd_validation_test.go b/internal/api/v1alpha1/crd_validation_test.go index 3f2cabde..c04b146d 100644 --- a/internal/api/v1alpha1/crd_validation_test.go +++ b/internal/api/v1alpha1/crd_validation_test.go @@ -192,3 +192,105 @@ func TestMachinePrinterColumnsShowRequestedHardware(t *testing.T) { } } } + +// TestMachineImageDefinitionAndSourceNeverChange proves the catalog is +// immutable: a provider may only withdraw a definition, and a published +// copy can never be pointed at another source. +func TestMachineImageDefinitionAndSourceNeverChange(t *testing.T) { + crd := loadCRDs(t)["machineimages.metal.datumapis.com"] + digest := "sha256:" + strings.Repeat("ab", 32) + definition := func(version, availability string) map[string]any { + return map[string]any{"apiVersion": "metal.datumapis.com/v1alpha1", "kind": "MachineImage", "metadata": map[string]any{"name": "example-linux", "namespace": "default"}, "spec": map[string]any{ + "definition": map[string]any{"family": "example-linux", "version": version, "architecture": "amd64", "firmwareModes": []any{"UEFI"}, "bootstrapFormats": []any{"NoCloud"}, "digest": digest}, + "availability": availability, + }} + } + publisher := func(group, kind, name string) map[string]any { + return map[string]any{"apiVersion": "metal.datumapis.com/v1alpha1", "kind": "MachineImage", "metadata": map[string]any{"name": "example-linux", "namespace": "default"}, "spec": map[string]any{ + "source": map[string]any{"publisherRef": map[string]any{"apiGroup": group, "kind": kind, "name": name}, "name": "example-linux"}, + }} + } + source := func(project string) map[string]any { + return publisher("resourcemanager.miloapis.com", "Project", project) + } + both := definition("1.2", "Available") + both["spec"].(map[string]any)["source"] = source("provider-example")["spec"].(map[string]any)["source"] + bareProject := publisher("resourcemanager.miloapis.com", "Project", "provider-example") + bareProject["spec"].(map[string]any)["source"] = map[string]any{"project": "provider-example", "name": "example-linux"} + noAvailability := definition("1.2", "Available") + delete(noAvailability["spec"].(map[string]any), "availability") + copyWithAvailability := source("provider-example") + copyWithAvailability["spec"].(map[string]any)["availability"] = "Available" + copyWithDefinition := source("provider-example") + copyWithDefinition["spec"].(map[string]any)["definition"] = definition("1.2", "Available")["spec"].(map[string]any)["definition"] + copyBecomesDefinition := source("provider-example") + delete(copyBecomesDefinition["spec"].(map[string]any), "source") + copyBecomesDefinition["spec"].(map[string]any)["definition"] = copyWithDefinition["spec"].(map[string]any)["definition"] + copyBecomesDefinition["spec"].(map[string]any)["availability"] = "Available" + badDigest := definition("1.2", "Available") + badDigest["spec"].(map[string]any)["definition"].(map[string]any)["digest"] = "sha256:short" + for _, test := range []struct { + name string + object, old map[string]any + allowed bool + }{ + {"a definition", definition("1.2", "Available"), nil, true}, + {"a published copy", source("provider-example"), nil, true}, + {"both a definition and a source", both, nil, false}, + {"a definition without an availability", noAvailability, nil, false}, + {"a digest that is not sha256", badDigest, nil, false}, + {"a published copy with an availability", copyWithAvailability, nil, false}, + {"adding an availability to a published copy", copyWithAvailability, source("provider-example"), false}, + {"adding a definition to a published copy", copyWithDefinition, source("provider-example"), false}, + {"turning a published copy into a definition", copyBecomesDefinition, source("provider-example"), false}, + {"withdrawing a definition", definition("1.2", "Withdrawn"), definition("1.2", "Available"), true}, + // A provider may make a withdrawn release available again. + {"restoring a withdrawn definition", definition("1.2", "Available"), definition("1.2", "Withdrawn"), true}, + {"changing a definition", definition("1.3", "Available"), definition("1.2", "Available"), false}, + {"turning a definition into a copy", source("provider-example"), definition("1.2", "Available"), false}, + {"repointing a published copy", source("provider-other"), source("provider-example"), false}, + {"a standalone copy published from a Namespace", publisher("", "Namespace", "fleet-provider"), nil, true}, + {"a publisher of another kind", publisher("resourcemanager.miloapis.com", "Organization", "provider-example"), nil, false}, + {"a Project publisher in the core group", publisher("", "Project", "provider-example"), nil, false}, + {"a Namespace publisher in another group", publisher("resourcemanager.miloapis.com", "Namespace", "fleet-provider"), nil, false}, + {"a publisher without a name", publisher("resourcemanager.miloapis.com", "Project", ""), nil, false}, + {"a bare project field", bareProject, nil, false}, + } { + t.Run(test.name, func(t *testing.T) { + if errs := validateObject(t, crd, test.object, test.old); (len(errs) == 0) != test.allowed { + t.Fatalf("allowed = %v, errors: %v", len(errs) == 0, errs) + } + }) + } +} + +// TestPublicationRecordsReferenceASupportedTenant: a publication record's +// consumer is a typed reference to a Milo Project or a Namespace. +func TestPublicationRecordsReferenceASupportedTenant(t *testing.T) { + crd := loadCRDs(t)["machineimagepublications.metal.datumapis.com"] + record := func(group, kind string) map[string]any { + return map[string]any{"apiVersion": "metal.datumapis.com/v1alpha1", "kind": "MachineImagePublication", "metadata": map[string]any{"name": "imgpub-example", "namespace": "fleet-provider"}, "spec": map[string]any{ + "consumerRef": map[string]any{"apiGroup": group, "kind": kind, "name": "consumer-example"}, + "image": map[string]any{"namespace": "default", "name": "example-linux"}, + "source": map[string]any{"name": "example-linux"}, + "digest": "sha256:" + strings.Repeat("ab", 32), + }} + } + for _, test := range []struct { + name string + group, kind string + allowed bool + }{ + {"a Milo Project", "resourcemanager.miloapis.com", "Project", true}, + {"a standalone Namespace", "", "Namespace", true}, + {"another kind", "resourcemanager.miloapis.com", "Organization", false}, + {"a Project in the core group", "", "Project", false}, + {"a Namespace in another group", "resourcemanager.miloapis.com", "Namespace", false}, + } { + t.Run(test.name, func(t *testing.T) { + if errs := validateObject(t, crd, record(test.group, test.kind), nil); (len(errs) == 0) != test.allowed { + t.Fatalf("allowed = %v, errors: %v", len(errs) == 0, errs) + } + }) + } +} diff --git a/internal/api/v1alpha1/iam_test.go b/internal/api/v1alpha1/iam_test.go new file mode 100644 index 00000000..4575134e --- /dev/null +++ b/internal/api/v1alpha1/iam_test.go @@ -0,0 +1,99 @@ +package v1alpha1 + +import ( + "bytes" + "io" + "os" + "path/filepath" + "slices" + "strings" + "testing" + + "k8s.io/apimachinery/pkg/util/yaml" +) + +type iamRole struct { + Metadata struct{ Name string } `json:"metadata"` + Spec struct { + Inherited []struct{ Name string } `json:"inheritedRoles"` + Included []string `json:"includedPermissions"` + } `json:"spec"` +} + +// roles reads every Metal IAM role and resolves inherited permissions. +func roles(t *testing.T) map[string][]string { + t.Helper() + files, err := filepath.Glob(filepath.Join("..", "..", "..", "config", "components", "iam", "roles", "*.yaml")) + if err != nil { + t.Fatal(err) + } + raw := map[string]iamRole{} + for _, file := range files { + if filepath.Base(file) == "kustomization.yaml" { + continue + } + data, err := os.ReadFile(file) + if err != nil { + t.Fatal(err) + } + decoder := yaml.NewYAMLOrJSONDecoder(bytes.NewReader(data), 4096) + for { + var r iamRole + if err := decoder.Decode(&r); err == io.EOF { + break + } else if err != nil { + t.Fatal(err) + } + raw[r.Metadata.Name] = r + } + } + var resolve func(name string, seen map[string]bool) []string + resolve = func(name string, seen map[string]bool) []string { + if seen[name] { + return nil + } + seen[name] = true + r, ok := raw[name] + if !ok { + t.Fatalf("role %s is inherited but not defined", name) + } + out := slices.Clone(r.Spec.Included) + for _, parent := range r.Spec.Inherited { + out = append(out, resolve(parent.Name, seen)...) + } + return out + } + out := map[string][]string{} + for name := range raw { + out[name] = resolve(name, map[string]bool{}) + } + return out +} + +// TestCustomersCannotWriteImagesOrReadPublications proves the catalog's +// entitlement cannot be forged through IAM: no customer role writes a +// MachineImage or touches a publication record, and a claimant may use a +// published image. +func TestCustomersCannotWriteImagesOrReadPublications(t *testing.T) { + all := roles(t) + for _, name := range []string{"metal.datumapis.com-viewer", "metal.datumapis.com-claimant", "metal.datumapis.com-consumer"} { + permissions, ok := all[name] + if !ok { + t.Fatalf("role %s is missing", name) + } + for _, permission := range permissions { + if strings.HasPrefix(permission, "metal.datumapis.com/machineimagepublications.") { + t.Errorf("%s holds %s", name, permission) + } + if verb, ok := strings.CutPrefix(permission, "metal.datumapis.com/machineimages."); ok && !slices.Contains([]string{"list", "get", "watch", "use"}, verb) { + t.Errorf("%s holds %s", name, permission) + } + } + } + if !slices.Contains(all["metal.datumapis.com-claimant"], "metal.datumapis.com/machineimages.use") { + t.Error("a claimant cannot use a published image") + } + if !slices.Contains(all["metal.datumapis.com-controller"], "metal.datumapis.com/machineimagepublications.get") { + t.Error("the Fleet provider cannot read publication records") + } +} diff --git a/internal/api/v1alpha1/types.go b/internal/api/v1alpha1/types.go index ac4bc000..23dc81b2 100644 --- a/internal/api/v1alpha1/types.go +++ b/internal/api/v1alpha1/types.go @@ -143,7 +143,10 @@ type MachineProfileList struct { } type Hardware struct { - CPU HardwareCPU `json:"cpu,omitempty"` + CPU HardwareCPU `json:"cpu,omitempty"` + // Firmware is the server's boot firmware. An image installs only on a + // server whose firmware mode it lists; an unknown mode installs none. + Firmware *HardwareFirmware `json:"firmware,omitempty"` Memory HardwareMemory `json:"memory,omitempty"` GPUs []HardwareGPU `json:"gpus,omitempty"` Disks []HardwareDisk `json:"disks,omitempty"` @@ -156,6 +159,16 @@ type HardwareCPU struct { Cores int64 `json:"cores,omitempty"` Threads int64 `json:"threads,omitempty"` } + +// Firmware boot modes. +const ( + FirmwareUEFI = "UEFI" + FirmwareBIOS = "BIOS" +) + +type HardwareFirmware struct { + BootMode string `json:"bootMode,omitempty"` +} type HardwareMemory struct { Capacity string `json:"capacity,omitempty"` } @@ -333,9 +346,94 @@ type InstallationSpec struct { BootstrapConfigRef *LocalReference `json:"bootstrapConfigRef,omitempty"` } type InstallationStatus struct { - Phase string `json:"phase,omitempty"` - CompletedAt *metav1.Time `json:"completedAt,omitempty"` - Conditions []metav1.Condition `json:"conditions,omitempty"` + Phase string `json:"phase,omitempty"` + // ResolvedImage is the provider image and digest Fleet admitted. + ResolvedImage *ResolvedImage `json:"resolvedImage,omitempty"` + CompletedAt *metav1.Time `json:"completedAt,omitempty"` + Conditions []metav1.Condition `json:"conditions,omitempty"` +} + +type ResolvedImage struct { + Name string `json:"name"` + Digest string `json:"digest"` +} + +// MachineImage is one OS image release. In the provider project it holds a +// definition: what the image is and the digest of its artifact manifest. In a +// consumer project it names its provider source; only the provider's +// publisher writes it there. The definition and the source never change. +type MachineImage struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + Spec MachineImageSpec `json:"spec"` + Status MachineImageStatus `json:"status,omitempty"` +} +type MachineImageList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []MachineImage `json:"items"` +} + +// Image availability. A withdrawn image admits no new installation. +const ( + ImageAvailable = "Available" + ImageWithdrawn = "Withdrawn" +) + +type MachineImageSpec struct { + Definition *ImageDefinition `json:"definition,omitempty"` + Source *SourceReference `json:"source,omitempty"` + // Availability is set only on a definition, and is its only mutable + // field. + Availability string `json:"availability,omitempty"` +} + +// Bootstrap formats an image can read on first boot. +const BootstrapNoCloud = "NoCloud" + +type ImageDefinition struct { + Family string `json:"family"` + Version string `json:"version"` + Architecture string `json:"architecture"` + FirmwareModes []string `json:"firmwareModes"` + BootstrapFormats []string `json:"bootstrapFormats,omitempty"` + // Digest is the digest of the image's artifact manifest. + Digest string `json:"digest"` +} +type MachineImageStatus struct { + // Resolved is the provider definition, for display. Admission reads + // the publication record, never this. + Resolved *ImageDefinition `json:"resolved,omitempty"` + Conditions []metav1.Condition `json:"conditions,omitempty"` +} + +// MachineImagePublication is a protected record in the provider project +// that one consumer MachineImage was published from one provider +// MachineImage incarnation. Its name derives from the consumer project, +// copy and provider image UIDs, so a recreated object finds no record and +// is not the published one. Admission resolves the digest from it. +type MachineImagePublication struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + Spec MachineImagePublicationSpec `json:"spec"` +} +type MachineImagePublicationList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []MachineImagePublication `json:"items"` +} +type MachineImagePublicationSpec struct { + ConsumerRef TypedReference `json:"consumerRef"` + Image PublishedImage `json:"image"` + Source LocalReference `json:"source"` + Digest string `json:"digest"` +} + +// PublishedImage names the consumer MachineImage. The record's name pins +// its incarnation and its tenant's. +type PublishedImage struct { + Namespace string `json:"namespace"` + Name string `json:"name"` } // MachineAllocation is a protected, service-owned record in the provider @@ -472,7 +570,7 @@ type InstallationList struct { } func addKnown(s *runtime.Scheme) error { - s.AddKnownTypes(GroupVersion, &MachineClass{}, &MachineClassList{}, &MachineProfile{}, &MachineProfileList{}, &MachineCapacity{}, &MachineCapacityList{}, &Machine{}, &MachineList{}, &MachineAllocation{}, &MachineAllocationList{}, &Installation{}, &InstallationList{}) + s.AddKnownTypes(GroupVersion, &MachineClass{}, &MachineClassList{}, &MachineProfile{}, &MachineProfileList{}, &MachineCapacity{}, &MachineCapacityList{}, &Machine{}, &MachineList{}, &MachineAllocation{}, &MachineAllocationList{}, &Installation{}, &InstallationList{}, &MachineImage{}, &MachineImageList{}, &MachineImagePublication{}, &MachineImagePublicationList{}) metav1.AddToGroupVersion(s, GroupVersion) return nil } @@ -541,3 +639,24 @@ func (in *InstallationList) DeepCopyObject() runtime.Object { } func deepCopy[T any](in *T, out *T) { b, _ := json.Marshal(in); _ = json.Unmarshal(b, out) } + +func (in *MachineImage) DeepCopyObject() runtime.Object { + out := new(MachineImage) + deepCopy(in, out) + return out +} +func (in *MachineImageList) DeepCopyObject() runtime.Object { + out := new(MachineImageList) + deepCopy(in, out) + return out +} +func (in *MachineImagePublication) DeepCopyObject() runtime.Object { + out := new(MachineImagePublication) + deepCopy(in, out) + return out +} +func (in *MachineImagePublicationList) DeepCopyObject() runtime.Object { + out := new(MachineImagePublicationList) + deepCopy(in, out) + return out +} diff --git a/internal/api/v1alpha1/types_test.go b/internal/api/v1alpha1/types_test.go index 0d10fe84..e987780b 100644 --- a/internal/api/v1alpha1/types_test.go +++ b/internal/api/v1alpha1/types_test.go @@ -20,6 +20,8 @@ func TestAddToSchemeRegistersPublicKinds(t *testing.T) { "Machine", "MachineList", "MachineAllocation", "MachineAllocationList", "Installation", "InstallationList", + "MachineImage", "MachineImageList", + "MachineImagePublication", "MachineImagePublicationList", } { gvk := GroupVersion.WithKind(kind) if _, err := scheme.New(gvk); err != nil { diff --git a/internal/catalog/catalog.go b/internal/catalog/catalog.go new file mode 100644 index 00000000..68b840da --- /dev/null +++ b/internal/catalog/catalog.go @@ -0,0 +1,234 @@ +// Package catalog is the Metal image catalog: the provider publishes +// immutable MachineImages by digest, publication copies one into a consumer +// project with a protected record in the provider project, and admission +// resolves an Installation's image through that record to the exact digest. +// +// Resolution never reads the consumer copy's status, and never trusts an +// object only by name: the record's name derives from the consumer tenant, +// copy and provider image UIDs, and its spec pins the digest, so an object +// deleted and recreated under the same name finds no record. A tenant is a +// Milo Project, or a Namespace in standalone mode; any other kind is +// refused. +package catalog + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "slices" + "strings" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + apiMeta "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/controller-runtime/pkg/client" + + fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/tenancy" +) + +// Refusal reasons an Installation reports as Accepted=False. +const ( + ReasonImageNotFound = "ImageNotFound" + ReasonImageNotEntitled = "ImageNotEntitled" + ReasonImageWithdrawn = "ImageWithdrawn" + ReasonImageIncompatible = "ImageIncompatible" + ReasonAuthorizationUnavailable = "AuthorizationUnavailable" +) + +// Refusal is an admission refusal. Nothing was copied or created for it. +type Refusal struct { + Reason string + Message string +} + +func (r *Refusal) Error() string { return r.Reason + ": " + r.Message } + +func refuse(reason, format string, args ...any) *Refusal { + return &Refusal{Reason: reason, Message: fmt.Sprintf(format, args...)} +} + +// ErrAuthorizationUnavailable is what an Authorizer returns when it could +// not decide. Admission treats it as unknown, never as permission. +var ErrAuthorizationUnavailable = errors.New("authorization unavailable") + +// ErrConflict means a publication already exists with other contents. +var ErrConflict = errors.New("catalog: the publication exists with other contents") + +// Authorizer decides whether the principal that created the Installation +// may use both images: the consumer copy and its provider source. It +// returns nil to allow, ErrAuthorizationUnavailable when it cannot decide, +// and any other error to deny. +type Authorizer func(ctx context.Context, installation *fleetv1.Installation, consumer, provider *fleetv1.MachineImage) error + +// Image is a resolved provider image and its definition. +type Image struct { + Name string + Definition fleetv1.ImageDefinition +} + +// Catalog reads the provider project's images and publication records. +type Catalog struct { + // Provider reads the provider project. It must read through to the API + // server. + Provider client.Reader + // Publisher is the provider's tenant. A consumer copy must name it. + Publisher fleetv1.TypedReference + // Namespace holds the provider's images and publication records. + Namespace string + Authorize Authorizer +} + +// PublicationName is the only name a publication record may have. It +// derives from the consumer tenant incarnation, the consumer copy's +// namespace, name and UID, and the provider image's name and UID, so a +// record entitles only the incarnations it was written for. +func PublicationName(consumer tenancy.Consumer, local, source *fleetv1.MachineImage) string { + sum := sha256.Sum256([]byte(strings.Join([]string{consumer.Ref.APIGroup, consumer.Ref.Kind, consumer.Ref.Name, string(consumer.UID), local.Namespace, local.Name, string(local.UID), source.Name, string(source.UID)}, "\x00"))) + return "imgpub-" + hex.EncodeToString(sum[:])[:32] +} + +// Resolve resolves an Installation's image to the provider incarnation and +// digest its publication record pins, and checks entitlement and use +// permission. It returns a *Refusal for every reason the request is refused. +func (c *Catalog) Resolve(ctx context.Context, consumer tenancy.Consumer, installation *fleetv1.Installation) (Image, error) { + if consumer.Client == nil { + return Image{}, errors.New("catalog: the consumer has no API client") + } + local := &fleetv1.MachineImage{} + if err := consumer.Client.Get(ctx, client.ObjectKey{Namespace: installation.Namespace, Name: installation.Spec.ImageRef.Name}, local); apierrors.IsNotFound(err) { + return Image{}, refuse(ReasonImageNotFound, "no MachineImage %q in this namespace", installation.Spec.ImageRef.Name) + } else if err != nil { + return Image{}, err + } + notEntitled := refuse(ReasonImageNotEntitled, "MachineImage %q is not published to this project", local.Name) + if tenancy.Supported(consumer.Ref) != nil || tenancy.Supported(c.Publisher) != nil { + return Image{}, refuse(ReasonImageNotEntitled, "a tenant must be a Milo Project or, in standalone mode, a Namespace") + } + if local.Spec.Source == nil || local.Spec.Source.PublisherRef != c.Publisher { + return Image{}, notEntitled + } + source := &fleetv1.MachineImage{} + if err := c.Provider.Get(ctx, client.ObjectKey{Namespace: c.Namespace, Name: local.Spec.Source.Name}, source); apierrors.IsNotFound(err) { + return Image{}, notEntitled + } else if err != nil { + return Image{}, err + } + if local.UID == "" || source.UID == "" || consumer.UID == "" { + return Image{}, notEntitled + } + record := &fleetv1.MachineImagePublication{} + if err := c.Provider.Get(ctx, client.ObjectKey{Namespace: c.Namespace, Name: PublicationName(consumer, local, source)}, record); apierrors.IsNotFound(err) { + return Image{}, notEntitled + } else if err != nil { + return Image{}, err + } + if record.Spec != publication(consumer, local, source) { + return Image{}, notEntitled + } + if source.Spec.Availability != fleetv1.ImageAvailable { + return Image{}, refuse(ReasonImageWithdrawn, "MachineImage %q is withdrawn", local.Name) + } + if c.Authorize == nil { + return Image{}, refuse(ReasonAuthorizationUnavailable, "no image authorizer is configured") + } + if err := c.Authorize(ctx, installation, local, source); errors.Is(err, ErrAuthorizationUnavailable) { + return Image{}, refuse(ReasonAuthorizationUnavailable, "the image-use check could not complete") + } else if err != nil { + return Image{}, refuse(ReasonImageNotEntitled, "the creator may not use MachineImage %q", local.Name) + } + return Image{Name: source.Name, Definition: *source.Spec.Definition}, nil +} + +// publication is the record a copy and its provider image would have. It +// returns no spec a record can hold for a source without a definition. +func publication(consumer tenancy.Consumer, local, source *fleetv1.MachineImage) fleetv1.MachineImagePublicationSpec { + spec := fleetv1.MachineImagePublicationSpec{ + ConsumerRef: consumer.Ref, + Image: fleetv1.PublishedImage{Namespace: local.Namespace, Name: local.Name}, + Source: fleetv1.LocalReference{Name: source.Name}, + } + if source.Spec.Definition != nil { + spec.Digest = source.Spec.Definition.Digest + } + return spec +} + +// Compatible checks an image against an allocation's hardware: the +// architecture must be equal, the server's firmware mode must be known and +// listed, and bootstrap data needs a bootstrap format. +func Compatible(definition fleetv1.ImageDefinition, hardware fleetv1.Hardware, bootstrap bool) error { + if definition.Architecture != hardware.CPU.Architecture { + return refuse(ReasonImageIncompatible, "the image is %s and the server is %s", definition.Architecture, hardware.CPU.Architecture) + } + if hardware.Firmware == nil || !slices.Contains(definition.FirmwareModes, hardware.Firmware.BootMode) { + return refuse(ReasonImageIncompatible, "the server's firmware mode is unknown or not one the image boots in") + } + if bootstrap && len(definition.BootstrapFormats) == 0 { + return refuse(ReasonImageIncompatible, "the image takes no bootstrap data") + } + return nil +} + +// Publish publishes a provider image into a consumer project under the +// same name: the consumer copy first, then the record that entitles it. +// Until the record exists the copy entitles nothing, so a crash between +// the writes fails closed and a retry completes it. Publish is the +// publisher's action; it is idempotent and refuses to change an existing +// publication. +func (c *Catalog) Publish(ctx context.Context, provider client.Client, consumer tenancy.Consumer, namespace, name string) error { + if err := tenancy.Supported(consumer.Ref); err != nil { + return fmt.Errorf("catalog: consumer: %w", err) + } + if err := tenancy.Supported(c.Publisher); err != nil { + return fmt.Errorf("catalog: publisher: %w", err) + } + if consumer.Client == nil { + return errors.New("catalog: the consumer has no API client") + } + consumerAPI := consumer.Client + source := &fleetv1.MachineImage{} + if err := provider.Get(ctx, client.ObjectKey{Namespace: c.Namespace, Name: name}, source); err != nil { + return err + } + if source.Spec.Definition == nil { + return fmt.Errorf("catalog: %s is not a provider definition", name) + } + local := &fleetv1.MachineImage{ObjectMeta: metav1.ObjectMeta{Namespace: namespace, Name: name}, Spec: fleetv1.MachineImageSpec{Source: &fleetv1.SourceReference{PublisherRef: c.Publisher, Name: name}}} + if err := consumerAPI.Create(ctx, local); apierrors.IsAlreadyExists(err) { + if err := consumerAPI.Get(ctx, client.ObjectKeyFromObject(local), local); err != nil { + return err + } + if local.Spec.Source == nil || *local.Spec.Source != (fleetv1.SourceReference{PublisherRef: c.Publisher, Name: name}) { + return fmt.Errorf("%w: %s/%s names another source", ErrConflict, namespace, name) + } + } else if err != nil { + return err + } + if local.UID == "" || source.UID == "" || consumer.UID == "" { + return errors.New("catalog: a publication name binds object UIDs, and one is empty") + } + want := publication(consumer, local, source) + record := &fleetv1.MachineImagePublication{ObjectMeta: metav1.ObjectMeta{Namespace: c.Namespace, Name: PublicationName(consumer, local, source)}, Spec: want} + if err := provider.Create(ctx, record); apierrors.IsAlreadyExists(err) { + if err := provider.Get(ctx, client.ObjectKeyFromObject(record), record); err != nil { + return err + } + if record.Spec != want { + return fmt.Errorf("%w: %s", ErrConflict, record.Name) + } + } else if err != nil { + return err + } + definition := *source.Spec.Definition + local.Status.Resolved = &definition + status := metav1.ConditionTrue + reason := "Published" + if source.Spec.Availability != fleetv1.ImageAvailable { + status, reason = metav1.ConditionFalse, "Withdrawn" + } + apiMeta.SetStatusCondition(&local.Status.Conditions, metav1.Condition{Type: "Available", Status: status, Reason: reason, ObservedGeneration: local.Generation}) + return consumerAPI.Status().Update(ctx, local) +} diff --git a/internal/catalog/catalog_test.go b/internal/catalog/catalog_test.go new file mode 100644 index 00000000..b7ce2362 --- /dev/null +++ b/internal/catalog/catalog_test.go @@ -0,0 +1,415 @@ +package catalog + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "strings" + "testing" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/types" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/client/interceptor" + + fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/tenancy" +) + +const ( + providerProject = "provider-example" + providerNS = "fleet-provider" + imageName = "example-linux-1-2" +) + +var ( + digest = "sha256:" + strings.Repeat("4f", 32) + consumer = tenancy.Consumer{Ref: tenancy.Project("consumer-example"), UID: "00000000-0000-4000-8000-000000000501"} +) + +type fixture struct { + ctx context.Context + provider client.Client + consumer client.Client + catalog *Catalog + allowed error + // failRecord makes the next publication record create fail, as a + // crash between Publish's two writes would. + failRecord bool + uids int +} + +func newFixture(t *testing.T) *fixture { + t.Helper() + scheme := runtime.NewScheme() + if err := fleetv1.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + f := &fixture{ctx: context.Background()} + // The fake API server assigns no UIDs; this one does, as a real one + // would, so publication binds real incarnations. + create := func(ctx context.Context, c client.WithWatch, object client.Object, opts ...client.CreateOption) error { + if _, ok := object.(*fleetv1.MachineImagePublication); ok && f.failRecord { + f.failRecord = false + return errors.New("lost response") + } + if object.GetUID() == "" { + f.uids++ + object.SetUID(types.UID(fmt.Sprintf("uid-%d", f.uids))) + } + return c.Create(ctx, object, opts...) + } + f.provider = fake.NewClientBuilder().WithScheme(scheme).WithStatusSubresource(&fleetv1.MachineImage{}).WithInterceptorFuncs(interceptor.Funcs{Create: create}).Build() + f.consumer = fake.NewClientBuilder().WithScheme(scheme).WithStatusSubresource(&fleetv1.MachineImage{}).WithInterceptorFuncs(interceptor.Funcs{Create: create}).Build() + f.catalog = &Catalog{Provider: f.provider, Publisher: tenancy.Project(providerProject), Namespace: providerNS, Authorize: func(context.Context, *fleetv1.Installation, *fleetv1.MachineImage, *fleetv1.MachineImage) error { + return f.allowed + }} + f.define(imageName, digest, fleetv1.ImageAvailable) + if err := f.catalog.Publish(f.ctx, f.provider, f.with(consumer), "default", imageName); err != nil { + t.Fatal(err) + } + return f +} + +// with is a consumer whose API is the fixture's consumer cluster. +func (f *fixture) with(consumer tenancy.Consumer) tenancy.Consumer { + consumer.Client = f.consumer + return consumer +} + +func (f *fixture) define(name, digest, availability string) *fleetv1.MachineImage { + image := &fleetv1.MachineImage{ObjectMeta: metav1.ObjectMeta{Namespace: providerNS, Name: name, UID: types.UID("uid-" + name + "-" + digest[len(digest)-4:])}, Spec: fleetv1.MachineImageSpec{ + Definition: &fleetv1.ImageDefinition{Family: "example-linux", Version: "1.2", Architecture: "amd64", FirmwareModes: []string{fleetv1.FirmwareUEFI}, BootstrapFormats: []string{fleetv1.BootstrapNoCloud}, Digest: digest}, + Availability: availability, + }} + if err := f.provider.Create(f.ctx, image); err != nil { + panic(err) + } + return image +} + +// editCopy changes the published copy's source in place, keeping its UID. +// The API server's CEL rules forbid this; resolution must not rely on them. +func (f *fixture) editCopy(change func(*fleetv1.SourceReference)) { + local := &fleetv1.MachineImage{} + _ = f.consumer.Get(f.ctx, client.ObjectKey{Namespace: "default", Name: imageName}, local) + change(local.Spec.Source) + _ = f.consumer.Update(f.ctx, local) +} + +func installation(image string) *fleetv1.Installation { + return &fleetv1.Installation{ObjectMeta: metav1.ObjectMeta{Namespace: "default", Name: "example-os-1"}, Spec: fleetv1.InstallationSpec{ImageRef: fleetv1.LocalReference{Name: image}}} +} + +func reason(t *testing.T, err error) string { + t.Helper() + var refusal *Refusal + if !errors.As(err, &refusal) { + t.Fatalf("err = %v, want a refusal", err) + } + return refusal.Reason +} + +func TestResolvePinsThePublishedIncarnationAndDigest(t *testing.T) { + f := newFixture(t) + image, err := f.catalog.Resolve(f.ctx, f.with(consumer), installation(imageName)) + if err != nil { + t.Fatal(err) + } + if image.Name != imageName || image.Definition.Digest != digest { + t.Fatalf("image = %+v", image) + } + local := &fleetv1.MachineImage{} + if err := f.consumer.Get(f.ctx, client.ObjectKey{Namespace: "default", Name: imageName}, local); err != nil { + t.Fatal(err) + } + if local.Status.Resolved == nil || local.Status.Resolved.Digest != digest { + t.Fatalf("published status = %+v", local.Status) + } +} + +// TestResolveRefusesEveryUnentitledImage covers each way a project can +// name an image it is not entitled to, and each refusal reason. +func TestResolveRefusesEveryUnentitledImage(t *testing.T) { + for _, test := range []struct { + name string + change func(*fixture) + image string + reason string + }{ + {"no such image", nil, "missing", ReasonImageNotFound}, + {"a customer-written definition", func(f *fixture) { + own := &fleetv1.MachineImage{ObjectMeta: metav1.ObjectMeta{Namespace: "default", Name: "own"}, Spec: fleetv1.MachineImageSpec{Definition: &fleetv1.ImageDefinition{Architecture: "amd64", Digest: digest}, Availability: fleetv1.ImageAvailable}} + _ = f.consumer.Create(f.ctx, own) + }, "own", ReasonImageNotEntitled}, + {"a copy naming another provider", func(f *fixture) { + other := &fleetv1.MachineImage{ObjectMeta: metav1.ObjectMeta{Namespace: "default", Name: "foreign"}, Spec: fleetv1.MachineImageSpec{Source: &fleetv1.SourceReference{PublisherRef: tenancy.Project("provider-other"), Name: imageName}}} + _ = f.consumer.Create(f.ctx, other) + }, "foreign", ReasonImageNotEntitled}, + {"a copy with no publication record", func(f *fixture) { + copy := &fleetv1.MachineImage{ObjectMeta: metav1.ObjectMeta{Namespace: "default", Name: "unpublished"}, Spec: fleetv1.MachineImageSpec{Source: &fleetv1.SourceReference{PublisherRef: tenancy.Project(providerProject), Name: imageName}}} + _ = f.consumer.Create(f.ctx, copy) + }, "unpublished", ReasonImageNotEntitled}, + {"a copy recreated after publication", func(f *fixture) { + local := &fleetv1.MachineImage{} + _ = f.consumer.Get(f.ctx, client.ObjectKey{Namespace: "default", Name: imageName}, local) + _ = f.consumer.Delete(f.ctx, local) + _ = f.consumer.Create(f.ctx, &fleetv1.MachineImage{ObjectMeta: metav1.ObjectMeta{Namespace: "default", Name: imageName, UID: "recreated"}, Spec: local.Spec}) + }, imageName, ReasonImageNotEntitled}, + {"a provider image recreated under the same name", func(f *fixture) { + _ = f.provider.Delete(f.ctx, &fleetv1.MachineImage{ObjectMeta: metav1.ObjectMeta{Namespace: providerNS, Name: imageName}}) + f.define(imageName, "sha256:"+strings.Repeat("9e", 32), fleetv1.ImageAvailable) + }, imageName, ReasonImageNotEntitled}, + {"a provider image recreated with the same digest", func(f *fixture) { + _ = f.provider.Delete(f.ctx, &fleetv1.MachineImage{ObjectMeta: metav1.ObjectMeta{Namespace: providerNS, Name: imageName}}) + image := f.define(imageName, digest, fleetv1.ImageAvailable) + _ = f.provider.Delete(f.ctx, image) + image.ResourceVersion, image.UID = "", "uid-recreated" + _ = f.provider.Create(f.ctx, image) + }, imageName, ReasonImageNotEntitled}, + {"a published copy edited to name the publisher by another kind", func(f *fixture) { + f.editCopy(func(source *fleetv1.SourceReference) { source.PublisherRef = tenancy.Namespace(providerProject) }) + }, imageName, ReasonImageNotEntitled}, + {"a published copy edited to name another provider", func(f *fixture) { + f.editCopy(func(source *fleetv1.SourceReference) { source.PublisherRef.Name = "provider-other" }) + }, imageName, ReasonImageNotEntitled}, + {"a published copy edited to name another image", func(f *fixture) { + f.define("other-image", digest, fleetv1.ImageAvailable) + f.editCopy(func(source *fleetv1.SourceReference) { source.Name = "other-image" }) + }, imageName, ReasonImageNotEntitled}, + {"a provider image whose digest changed in place", func(f *fixture) { + source := &fleetv1.MachineImage{} + _ = f.provider.Get(f.ctx, client.ObjectKey{Namespace: providerNS, Name: imageName}, source) + source.Spec.Definition.Digest = "sha256:" + strings.Repeat("9e", 32) + _ = f.provider.Update(f.ctx, source) + }, imageName, ReasonImageNotEntitled}, + {"a deleted provider image", func(f *fixture) { + _ = f.provider.Delete(f.ctx, &fleetv1.MachineImage{ObjectMeta: metav1.ObjectMeta{Namespace: providerNS, Name: imageName}}) + }, imageName, ReasonImageNotEntitled}, + {"a withdrawn image", func(f *fixture) { + source := &fleetv1.MachineImage{} + _ = f.provider.Get(f.ctx, client.ObjectKey{Namespace: providerNS, Name: imageName}, source) + source.Spec.Availability = fleetv1.ImageWithdrawn + _ = f.provider.Update(f.ctx, source) + }, imageName, ReasonImageWithdrawn}, + {"a creator without use permission", func(f *fixture) { f.allowed = errors.New("denied") }, imageName, ReasonImageNotEntitled}, + {"an unavailable authorizer", func(f *fixture) { f.allowed = ErrAuthorizationUnavailable }, imageName, ReasonAuthorizationUnavailable}, + {"no authorizer", func(f *fixture) { f.catalog.Authorize = nil }, imageName, ReasonAuthorizationUnavailable}, + } { + t.Run(test.name, func(t *testing.T) { + f := newFixture(t) + if test.change != nil { + test.change(f) + } + _, err := f.catalog.Resolve(f.ctx, f.with(consumer), installation(test.image)) + if got := reason(t, err); got != test.reason { + t.Fatalf("reason = %s, want %s", got, test.reason) + } + }) + } +} + +// TestAnotherProjectCannotUseThePublication proves the record binds the +// consumer project incarnation: a project of the same name with another +// UID, holding an identical copy, is not entitled. +func TestAnotherProjectCannotUseThePublication(t *testing.T) { + f := newFixture(t) + other := tenancy.Consumer{Ref: consumer.Ref, UID: "00000000-0000-4000-8000-000000000999"} + if _, err := f.catalog.Resolve(f.ctx, f.with(other), installation(imageName)); reason(t, err) != ReasonImageNotEntitled { + t.Fatalf("err = %v", err) + } +} + +func TestPublishIsIdempotentAndRefusesAnotherSource(t *testing.T) { + f := newFixture(t) + if err := f.catalog.Publish(f.ctx, f.provider, f.with(consumer), "default", imageName); err != nil { + t.Fatalf("republish: %v", err) + } + f.define("other-image", digest, fleetv1.ImageAvailable) + conflict := &fleetv1.MachineImage{ObjectMeta: metav1.ObjectMeta{Namespace: "default", Name: "other-image"}, Spec: fleetv1.MachineImageSpec{Source: &fleetv1.SourceReference{PublisherRef: tenancy.Project("provider-other"), Name: "other-image"}}} + if err := f.consumer.Create(f.ctx, conflict); err != nil { + t.Fatal(err) + } + if err := f.catalog.Publish(f.ctx, f.provider, f.with(consumer), "default", "other-image"); !errors.Is(err, ErrConflict) { + t.Fatalf("err = %v, want a conflict", err) + } +} + +// TestACrashBetweenPublishWritesFailsClosed loses the record write after +// the copy exists: the copy entitles nothing, and a retry completes it. +func TestACrashBetweenPublishWritesFailsClosed(t *testing.T) { + f := newFixture(t) + f.define("next-image", digest, fleetv1.ImageAvailable) + f.failRecord = true + if err := f.catalog.Publish(f.ctx, f.provider, f.with(consumer), "default", "next-image"); err == nil { + t.Fatal("the lost record write was not reported") + } + if _, err := f.catalog.Resolve(f.ctx, f.with(consumer), installation("next-image")); reason(t, err) != ReasonImageNotEntitled { + t.Fatalf("a copy without its record resolved: %v", err) + } + if err := f.catalog.Publish(f.ctx, f.provider, f.with(consumer), "default", "next-image"); err != nil { + t.Fatalf("retry: %v", err) + } + if _, err := f.catalog.Resolve(f.ctx, f.with(consumer), installation("next-image")); err != nil { + t.Fatalf("resolve after the retry: %v", err) + } +} + +// TestRepublishingARecreatedProviderImageWritesANewRecord: a provider +// image recreated under the same name is refused until it is published +// again, and publishing it writes a record of its own instead of taking +// over the first. The first record never entitles the new incarnation. +func TestRepublishingARecreatedProviderImageWritesANewRecord(t *testing.T) { + f := newFixture(t) + before := &fleetv1.MachineImagePublicationList{} + if err := f.provider.List(f.ctx, before); err != nil || len(before.Items) != 1 { + t.Fatalf("records = %d, %v", len(before.Items), err) + } + _ = f.provider.Delete(f.ctx, &fleetv1.MachineImage{ObjectMeta: metav1.ObjectMeta{Namespace: providerNS, Name: imageName}}) + image := f.define(imageName, digest, fleetv1.ImageAvailable) + _ = f.provider.Delete(f.ctx, image) + image.ResourceVersion, image.UID = "", "uid-recreated" + if err := f.provider.Create(f.ctx, image); err != nil { + t.Fatal(err) + } + if _, err := f.catalog.Resolve(f.ctx, f.with(consumer), installation(imageName)); reason(t, err) != ReasonImageNotEntitled { + t.Fatalf("the recreated image resolved before it was published: %v", err) + } + if err := f.catalog.Publish(f.ctx, f.provider, f.with(consumer), "default", imageName); err != nil { + t.Fatalf("republish: %v", err) + } + if _, err := f.catalog.Resolve(f.ctx, f.with(consumer), installation(imageName)); err != nil { + t.Fatalf("resolve after republishing: %v", err) + } + after := &fleetv1.MachineImagePublicationList{} + if err := f.provider.List(f.ctx, after); err != nil || len(after.Items) != 2 { + t.Fatalf("records = %d, %v; republishing must not rewrite the first", len(after.Items), err) + } + for _, record := range after.Items { + if record.Name == before.Items[0].Name && record.Spec != before.Items[0].Spec { + t.Fatalf("the first record changed: %+v", record.Spec) + } + } +} + +// TestNoPublicationSpecHoldsAUID: incarnations are pinned by the record's +// name, never by a UID in its spec. +func TestNoPublicationSpecHoldsAUID(t *testing.T) { + f := newFixture(t) + records := &fleetv1.MachineImagePublicationList{} + if err := f.provider.List(f.ctx, records); err != nil || len(records.Items) != 1 { + t.Fatalf("records = %d, %v", len(records.Items), err) + } + spec, _ := json.Marshal(records.Items[0].Spec) + for _, uid := range []string{string(consumer.UID), "uid-", "\"uid\"", "UID", "\"project\""} { + if strings.Contains(string(spec), uid) { + t.Fatalf("spec %s holds %q", spec, uid) + } + } +} + +func TestCompatibleChecksArchitectureFirmwareAndBootstrap(t *testing.T) { + definition := fleetv1.ImageDefinition{Architecture: "amd64", FirmwareModes: []string{fleetv1.FirmwareUEFI}, BootstrapFormats: []string{fleetv1.BootstrapNoCloud}} + noBootstrap := definition + noBootstrap.BootstrapFormats = nil + hardware := func(arch, mode string) fleetv1.Hardware { + h := fleetv1.Hardware{CPU: fleetv1.HardwareCPU{Architecture: arch}} + if mode != "" { + h.Firmware = &fleetv1.HardwareFirmware{BootMode: mode} + } + return h + } + for _, test := range []struct { + name string + definition fleetv1.ImageDefinition + hardware fleetv1.Hardware + bootstrap bool + ok bool + }{ + {"matching", definition, hardware("amd64", fleetv1.FirmwareUEFI), true, true}, + {"another architecture", definition, hardware("arm64", fleetv1.FirmwareUEFI), false, false}, + {"another firmware mode", definition, hardware("amd64", fleetv1.FirmwareBIOS), false, false}, + {"an unknown firmware mode", definition, hardware("amd64", ""), false, false}, + {"bootstrap data for an image without a format", noBootstrap, hardware("amd64", fleetv1.FirmwareUEFI), true, false}, + {"no bootstrap data for an image without a format", noBootstrap, hardware("amd64", fleetv1.FirmwareUEFI), false, true}, + } { + t.Run(test.name, func(t *testing.T) { + err := Compatible(test.definition, test.hardware, test.bootstrap) + if test.ok != (err == nil) { + t.Fatalf("err = %v", err) + } + if err != nil && reason(t, err) != ReasonImageIncompatible { + t.Fatalf("reason = %v", err) + } + }) + } +} + +// unsupported are tenant references of kinds Fleet does not support. +var unsupported = map[string]fleetv1.TypedReference{ + "another kind": {APIGroup: "resourcemanager.miloapis.com", Kind: "Organization", Name: "consumer-example"}, + "a Project in the core group": {Kind: tenancy.ProjectKind, Name: "consumer-example"}, + "a Namespace in another group": {APIGroup: "resourcemanager.miloapis.com", Kind: tenancy.NamespaceKind, Name: "consumer-example"}, + "no name": {APIGroup: "resourcemanager.miloapis.com", Kind: tenancy.ProjectKind}, +} + +// TestPublishRefusesAnUnsupportedTenant writes nothing for a consumer or a +// publisher of an unsupported kind. +func TestPublishRefusesAnUnsupportedTenant(t *testing.T) { + for name, ref := range unsupported { + for _, role := range []string{"consumer", "publisher"} { + t.Run(name+" as "+role, func(t *testing.T) { + f := newFixture(t) + f.define("next-image", digest, fleetv1.ImageAvailable) + who := tenancy.Consumer{Ref: ref, UID: consumer.UID} + if role == "publisher" { + who, f.catalog.Publisher = consumer, ref + } + if err := f.catalog.Publish(f.ctx, f.provider, f.with(who), "default", "next-image"); err == nil { + t.Fatal("published to an unsupported tenant") + } + records := &fleetv1.MachineImagePublicationList{} + copies := &fleetv1.MachineImageList{} + _ = f.provider.List(f.ctx, records) + _ = f.consumer.List(f.ctx, copies) + if len(records.Items) != 1 || len(copies.Items) != 1 { + t.Fatalf("records = %d, copies = %d; want only the fixture's", len(records.Items), len(copies.Items)) + } + }) + } + } +} + +// TestResolveRefusesAnUnsupportedTenant refuses a consumer of an +// unsupported kind even when a matching copy and record exist, as they +// would if something other than Publish wrote them. +func TestResolveRefusesAnUnsupportedTenant(t *testing.T) { + for name, ref := range unsupported { + t.Run(name, func(t *testing.T) { + f := newFixture(t) + who := tenancy.Consumer{Ref: ref, UID: consumer.UID} + local := &fleetv1.MachineImage{} + source := &fleetv1.MachineImage{} + _ = f.consumer.Get(f.ctx, client.ObjectKey{Namespace: "default", Name: imageName}, local) + _ = f.provider.Get(f.ctx, client.ObjectKey{Namespace: providerNS, Name: imageName}, source) + record := &fleetv1.MachineImagePublication{ObjectMeta: metav1.ObjectMeta{Namespace: providerNS, Name: PublicationName(who, local, source)}, Spec: publication(who, local, source)} + if err := f.provider.Create(f.ctx, record); err != nil { + t.Fatal(err) + } + if _, err := f.catalog.Resolve(f.ctx, f.with(who), installation(imageName)); reason(t, err) != ReasonImageNotEntitled { + t.Fatalf("err = %v", err) + } + }) + } + t.Run("an unsupported publisher", func(t *testing.T) { + f := newFixture(t) + f.catalog.Publisher = unsupported["another kind"] + f.editCopy(func(source *fleetv1.SourceReference) { source.PublisherRef = f.catalog.Publisher }) + if _, err := f.catalog.Resolve(f.ctx, f.with(consumer), installation(imageName)); reason(t, err) != ReasonImageNotEntitled { + t.Fatalf("err = %v", err) + } + }) +} diff --git a/internal/custody/kinds.go b/internal/custody/kinds.go index 19ab1a19..2d48a0a3 100644 --- a/internal/custody/kinds.go +++ b/internal/custody/kinds.go @@ -40,6 +40,9 @@ const ( ReasonTargetUnsupported = "TargetUnsupported" ReasonTargetDisks = "TargetDisksUnknown" ReasonInputsUnreadable = "InputsUnreadable" + // ReasonImageIncompatible is raised by an install worker that reads the + // server's firmware mode and finds the image does not list it. + ReasonImageIncompatible = "ImageIncompatible" ) // workerReasons are the reasons every site's install and wipe workers @@ -114,7 +117,7 @@ func DeviceInstallationKind() Kind { return refuse(ReasonBootInterfaceUnknown, "the Device records no interface %q with a MAC address", installation.Spec.BootInterface) }, Settles: []SettleRule{{Held: "DeviceInstallation"}}, - Reasons: append([]Reason{{Name: ReasonBootstrapUnsupported, RaisedBy: RaisedByBoth}, {Name: ReasonBootInterfaceUnknown, RaisedBy: RaisedByCoordinator}}, workerReasons...), + Reasons: append([]Reason{{Name: ReasonBootstrapUnsupported, RaisedBy: RaisedByBoth}, {Name: ReasonBootInterfaceUnknown, RaisedBy: RaisedByCoordinator}, {Name: ReasonImageIncompatible, RaisedBy: RaisedByWorker}}, workerReasons...), Evidence: StrictEvidence(evidenceLimit, func(_ ops.Operation, evidence *ops.InstallationEvidence) error { return validateSteps(evidence.Steps) }), diff --git a/internal/multiplane/runner.go b/internal/multiplane/runner.go index f69aaffa..673d7f9e 100644 --- a/internal/multiplane/runner.go +++ b/internal/multiplane/runner.go @@ -29,6 +29,7 @@ import ( inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" ops "go.datum.net/fleet/internal/api/operations/v1alpha1" fleet "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/catalog" "go.datum.net/fleet/internal/controller" "go.datum.net/fleet/internal/coordination" "go.datum.net/fleet/internal/custody" @@ -378,6 +379,14 @@ func (r *Runner) projectPower(ctx context.Context, q *request) error { return manager.ProjectPower(ctx, q.project.API, r.Provider.API, DeviceNamespace, q.alloc.Machine) } +// ImageCatalog is the provider's image catalog in the provider project. Its +// authorizer is the fixture's: every creator may use a published image. +// This composition has no Milo IAM image-use check. +func ImageCatalog(provider client.Reader) *catalog.Catalog { + return &catalog.Catalog{Provider: provider, Publisher: tenancy.Project("provider"), Namespace: DeviceNamespace, + Authorize: func(context.Context, *fleet.Installation, *fleet.MachineImage, *fleet.MachineImage) error { return nil }} +} + // installation creates the consumer's DeviceInstallation once and returns // it with the allocation. func (r *Runner) installation(ctx context.Context, index int) (*request, *fleet.MachineAllocation, *fleet.Installation, *ops.DeviceInstallation, error) { @@ -403,7 +412,23 @@ func (r *Runner) installation(ctx context.Context, index int) (*request, *fleet. if ref := q.machine.Status.CurrentInstallationRef; ref != nil { previous = ref.Name } - if operation, err = r.Allocator.Install(ctx, current, allocation.Installation{Installation: &install, Current: previous}); err != nil { + consumer, err := r.Resolve(ctx, tenancy.Project(q.project.Identity.RouteName)) + var image catalog.Image + if err == nil { + image, err = ImageCatalog(r.Provider.API).Resolve(ctx, consumer, &install) + } + if err == nil { + operation, err = r.Allocator.Install(ctx, current, allocation.Installation{Installation: &install, Current: previous, Image: image}) + } + if refusal := (*catalog.Refusal)(nil); errors.As(err, &refusal) { + accepted := condition("Accepted", metav1.ConditionFalse, install.Generation, refusal.Reason) + accepted.Message = refusal.Message + meta.SetStatusCondition(&install.Status.Conditions, accepted) + if serr := q.project.API.Status().Update(ctx, &install); serr != nil { + return nil, nil, nil, nil, serr + } + } + if err != nil { return nil, nil, nil, nil, err } } else if err != nil { @@ -452,6 +477,7 @@ func (r *Runner) InstallIndex(ctx context.Context, index int) error { return fmt.Errorf("%w: the installation is %s", errPending, phase) } install.Status.Phase = "Ready" + install.Status.ResolvedImage = &fleet.ResolvedImage{Name: operation.Spec.Image.Name, Digest: operation.Spec.Image.Digest} install.Status.Conditions = []metav1.Condition{condition("Ready", metav1.ConditionTrue, install.Generation, "LocalPXEVerifiedViaKarmada")} if err := q.project.API.Status().Update(ctx, install); err != nil { return err diff --git a/internal/multiplane/seed.go b/internal/multiplane/seed.go index 216a8284..719ab5c1 100644 --- a/internal/multiplane/seed.go +++ b/internal/multiplane/seed.go @@ -58,13 +58,27 @@ func Seed(ctx context.Context, c Config) error { } // The capacity projector is not wired, so the fixture writes Prepared, // Healthy and Available. Custody decides which Machine gets the Device. - capacity.Status.Hardware = fleet.Hardware{CPU: fleet.HardwareCPU{Architecture: "amd64", Cores: 2}, Memory: fleet.HardwareMemory{Capacity: "2Gi"}} + // Local guests and the Redfish lab VMs boot SeaBIOS. + capacity.Status.Hardware = fleet.Hardware{CPU: fleet.HardwareCPU{Architecture: "amd64", Cores: 2}, Firmware: &fleet.HardwareFirmware{BootMode: fleet.FirmwareBIOS}, Memory: fleet.HardwareMemory{Capacity: "2Gi"}} for _, kind := range []string{"Available", "Prepared", "Healthy"} { capacity.Status.Conditions = append(capacity.Status.Conditions, condition(kind, metav1.ConditionTrue, capacity.Generation, "SyntheticHardwareObservation")) } if err := provider.Status().Update(ctx, &capacity); err != nil { return err } + // The provider defines the one image the cell holds: the pinned + // installer manifest's digest. + imageName, imageDigest, ok := strings.Cut(c.Image, "@") + if !ok { + 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}, + Availability: fleet.ImageAvailable, + }} + if err := ensure(ctx, provider, image); err != nil { + return err + } var routing []map[string]string for _, name := range []string{"consumer-a", "consumer-b"} { api, err := API(filepath.Join(c.State, name, "bootstrap-project.json")) @@ -116,10 +130,6 @@ func Seed(ctx context.Context, c Config) error { return ctx.Err() } w.Stop() - 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: c.Image}}} - if err := ensure(ctx, user, installation); err != nil { - return err - } var ns core.Namespace if err := api.Get(ctx, client.ObjectKey{Name: Namespace}, &ns); err != nil { return err @@ -132,6 +142,14 @@ func Seed(ctx context.Context, c Config) error { if err != nil { return err } + // The provider's publisher publishes the image to the consumer. + if err := ImageCatalog(provider).Publish(ctx, provider, tenancy.Consumer{Ref: tenancy.Project(name), UID: identity.UID, Client: api}, Namespace, imageName); err != nil { + 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}}} + if err := ensure(ctx, user, installation); err != nil { + return err + } routing = append(routing, map[string]string{"route": name, "namespace": Namespace, "namespaceUID": string(ns.UID), "projectUID": string(identity.UID), "machineUID": string(machine.UID), "watch": "Added exact UID"}) } evidence, err := json.MarshalIndent(routing, "", " ") diff --git a/internal/redfish/client.go b/internal/redfish/client.go index f1c085ce..930c305f 100644 --- a/internal/redfish/client.go +++ b/internal/redfish/client.go @@ -227,6 +227,9 @@ type System struct { ResetTarget string `json:"resetTarget"` ResetTypes []string `json:"resetTypes"` BootTargets []string `json:"bootTargets"` + // BootMode is the firmware mode the System boots in, UEFI or BIOS, + // from its BootSourceOverrideMode. Empty when it reports neither. + BootMode string `json:"bootMode,omitempty"` // noOnce records that the System does not offer a one-time override. noOnce bool } @@ -380,6 +383,12 @@ func (c *Client) Identify(ctx context.Context, t Target) (System, error) { sys.BootTargets = append(sys.BootTargets, string(b)) } sys.noOnce = raw.Boot.Enabled != nil && !contains(*raw.Boot.Enabled, "Once") + switch s.Boot.BootSourceOverrideMode { + case "UEFI": + sys.BootMode = "UEFI" + case "Legacy": + sys.BootMode = "BIOS" + } return sys, nil } diff --git a/internal/redfish/client_test.go b/internal/redfish/client_test.go index cf720a44..da85cdd3 100644 --- a/internal/redfish/client_test.go +++ b/internal/redfish/client_test.go @@ -126,6 +126,23 @@ func TestDiscoveryWalksEveryPageOfTheSystemsCollection(t *testing.T) { } } +// TestDiscoveryReadsTheBootMode maps the System's BootSourceOverrideMode +// to a firmware mode, and leaves it empty when the BMC reports neither, so +// the install worker refuses rather than guesses. +func TestDiscoveryReadsTheBootMode(t *testing.T) { + for reported, want := range map[string]string{"UEFI": "UEFI", "Legacy": "BIOS", "": ""} { + b := newStub() + if reported != "" { + b.docs["/redfish/v1/Systems/A"].(map[string]any)["Boot"].(map[string]any)["BootSourceOverrideMode"] = reported + } + c := stubClient(t, b, time.Second) + s, err := c.Discover(context.Background(), Target{SystemID: "A", SystemUUID: uuidA}) + if err != nil || s.BootMode != want { + t.Fatalf("reported %q: boot mode %q, %v", reported, s.BootMode, err) + } + } +} + func TestDiscoveryRefusesPartialOrForeignCollections(t *testing.T) { for name, tc := range map[string]struct { mutate func(*bmcStub) diff --git a/internal/site/redfishwork/kinds.go b/internal/site/redfishwork/kinds.go index 19b2a678..8769e8ff 100644 --- a/internal/site/redfishwork/kinds.go +++ b/internal/site/redfishwork/kinds.go @@ -124,6 +124,11 @@ func (k Installation) Check(_ context.Context, work *site.Work) *custody.Refusal if spec.Bootstrap != nil { return &custody.Refusal{Reason: custody.ReasonBootstrapUnsupported, Message: "bootstrap payloads need the sealed store, which is not implemented"} } + // 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) { + return &custody.Refusal{Reason: custody.ReasonImageIncompatible, Message: "the image does not list the server's current firmware mode"} + } return checkTarget(work, spec.TargetDisks, installPhases) } diff --git a/internal/site/redfishwork/kinds_test.go b/internal/site/redfishwork/kinds_test.go index 264ecbc5..d7d3580a 100644 --- a/internal/site/redfishwork/kinds_test.go +++ b/internal/site/redfishwork/kinds_test.go @@ -25,6 +25,7 @@ import ( ops "go.datum.net/fleet/internal/api/operations/v1alpha1" "go.datum.net/fleet/internal/bmcdiscovery" + "go.datum.net/fleet/internal/custody" "go.datum.net/fleet/internal/redfish" "go.datum.net/fleet/internal/site" ) @@ -116,7 +117,7 @@ func (l *lab) ServeHTTP(w http.ResponseWriter, r *http.Request) { "/redfish/v1": map[string]any{"@odata.id": "/redfish/v1", "Systems": map[string]string{"@odata.id": "/redfish/v1/Systems"}}, "/redfish/v1/Systems": map[string]any{"Members": []any{map[string]string{"@odata.id": path}}}, path: map[string]any{"@odata.id": path, "Id": "A", "UUID": uuid, "PowerState": l.power, - "Boot": map[string]any{"BootSourceOverrideEnabled": l.enabled, "BootSourceOverrideTarget": l.target, "BootSourceOverrideTarget@Redfish.AllowableValues": []string{"Pxe", "Hdd"}}, + "Boot": map[string]any{"BootSourceOverrideEnabled": l.enabled, "BootSourceOverrideTarget": l.target, "BootSourceOverrideMode": "Legacy", "BootSourceOverrideTarget@Redfish.AllowableValues": []string{"Pxe", "Hdd"}}, "Actions": map[string]any{"#ComputerSystem.Reset": map[string]any{"target": path + "/Actions/ComputerSystem.Reset", "ResetType@Redfish.AllowableValues": []string{"On", "ForceOff"}}}}, } doc, ok := docs[strings.TrimSuffix(r.URL.Path, "/")] @@ -213,7 +214,21 @@ func assignment(l *lab, kind, uid string, fence int64, spec any) site.Assignment } func installSpec() ops.DeviceInstallationSpec { - return ops.DeviceInstallationSpec{Image: ops.ImageInput{Name: "debian-12", Digest: "sha256:" + strings.Repeat("a", 64)}, BootInterface: "primary", TargetDisks: []string{"disk-0"}} + return ops.DeviceInstallationSpec{Image: ops.ImageInput{Name: "debian-12", Digest: "sha256:" + strings.Repeat("a", 64), FirmwareModes: []string{"BIOS"}}, BootInterface: "primary", TargetDisks: []string{"disk-0"}} +} + +// TestAnImageForAnotherFirmwareModeSendsNothing reads the mode the server +// boots in now, which can differ from what allocation recorded, and +// refuses before any power or boot change. +func TestAnImageForAnotherFirmwareModeSendsNothing(t *testing.T) { + l := newLab(t) + r := runner(t, l) + spec := installSpec() + spec.Image.FirmwareModes = []string{"UEFI"} + result, err := r.Run(context.Background(), assignment(l, "DeviceInstallation", "op-uefi", 1, spec)) + if err != nil || result.Phase != ops.PhaseFailed || result.Reason != custody.ReasonImageIncompatible || l.onCount() != 0 { + t.Fatalf("result = %+v, %v, %d power-ons", result, err, l.onCount()) + } } func TestInstallationRunsBothPhasesWithOneOnEach(t *testing.T) { diff --git a/internal/site/vmwork/kinds.go b/internal/site/vmwork/kinds.go index 7b2a4ede..e7f670c3 100644 --- a/internal/site/vmwork/kinds.go +++ b/internal/site/vmwork/kinds.go @@ -18,6 +18,7 @@ import ( "os" "os/exec" "path/filepath" + "slices" "strings" "time" @@ -151,6 +152,10 @@ func (k Installation) Check(_ context.Context, work *site.Work) *custody.Refusal if spec.Image.Name+"@"+spec.Image.Digest != k.Image { return &custody.Refusal{Reason: custody.ReasonTargetUnsupported, Message: "the site installs only its verified local image"} } + // Every local guest boots the i440FX machine with SeaBIOS. + if !slices.Contains(spec.Image.FirmwareModes, "BIOS") { + return &custody.Refusal{Reason: custody.ReasonImageIncompatible, Message: "the image does not boot in BIOS mode"} + } return enrolled(work, spec.TargetDisks) } diff --git a/internal/site/vmwork/kinds_test.go b/internal/site/vmwork/kinds_test.go index ce683991..68fe5676 100644 --- a/internal/site/vmwork/kinds_test.go +++ b/internal/site/vmwork/kinds_test.go @@ -125,13 +125,25 @@ func envelope() ops.OperationEnvelope { func installSpec() ops.DeviceInstallationSpec { name, digest, _ := strings.Cut(image, "@") - return ops.DeviceInstallationSpec{OperationEnvelope: envelope(), Image: ops.ImageInput{Name: name, Digest: digest}, BootInterface: "primary", TargetDisks: []string{"disk-0"}} + return ops.DeviceInstallationSpec{OperationEnvelope: envelope(), Image: ops.ImageInput{Name: name, Digest: digest, FirmwareModes: []string{"BIOS"}}, BootInterface: "primary", TargetDisks: []string{"disk-0"}} } func wipeSpec() ops.DeviceWipeSpec { return ops.DeviceWipeSpec{OperationEnvelope: envelope(), Step: 1, CleaningPolicyDigest: "sha256:" + key, TargetDisks: []string{"disk-0"}} } +// TestAUEFIOnlyImageSendsNothing refuses an image the local guest's BIOS +// cannot boot, before any disk or boot. +func TestAUEFIOnlyImageSendsNothing(t *testing.T) { + r := newRig(t) + spec := installSpec() + spec.Image.FirmwareModes = []string{"UEFI"} + result, err := r.runner.Run(context.Background(), r.assignment("DeviceInstallation", "00000000-0000-4000-8000-000000000209", 2, spec)) + if err != nil || result.Phase != ops.PhaseFailed || result.Reason != custody.ReasonImageIncompatible || r.vm.creates != 0 { + t.Fatalf("result = %+v, %v, %d boots", result, err, r.vm.creates) + } +} + // TestInstallThenWipe installs directly, proves each phase by its receipt, // and wipes every disk of the Device. func TestInstallThenWipe(t *testing.T) { diff --git a/internal/standalone/runner.go b/internal/standalone/runner.go index 20dbb4fa..241f7bf3 100644 --- a/internal/standalone/runner.go +++ b/internal/standalone/runner.go @@ -20,6 +20,7 @@ import ( "go.datum.net/fleet/internal/allocation" ops "go.datum.net/fleet/internal/api/operations/v1alpha1" fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/catalog" "go.datum.net/fleet/internal/controller" "go.datum.net/fleet/internal/custody" "go.datum.net/fleet/internal/manager" @@ -44,6 +45,9 @@ type Options struct { InstallationName string ReinstallationName string LocationName string + // ImageName is the provider image the allocate phase publishes into the + // first consumer namespace. + ImageName string // Wait bounds how long a phase waits for the coordinator and the site. Wait time.Duration } @@ -55,7 +59,8 @@ func DefaultOptions() Options { ClassName: "standard-metal", ProfileName: "general-purpose-24c-128g", MachineName: "central1-baremetal-01", ClaimName: "allocation", ReinstallationName: "debian-12-reinstall", InstallationName: "debian-12", - LocationName: "us-central-1", Wait: 3 * time.Minute, + LocationName: "us-central-1", ImageName: "debian-12", + Wait: 3 * time.Minute, } } @@ -112,6 +117,10 @@ func (r Runner) allocate(ctx context.Context) error { if err != nil { return err } + // The provider's publisher publishes its image to the first consumer. + if err := r.catalog().Publish(ctx, r.Client, r.consumerOf(first), r.Options.FirstNamespace, r.Options.ImageName); err != nil { + return fmt.Errorf("publish the image: %w", err) + } second, err := r.prepareClaim(ctx, r.Options.SecondNamespace) if err != nil { return err @@ -169,7 +178,17 @@ func (r Runner) install(ctx context.Context, installationName string) error { if err := r.Client.Status().Update(ctx, first.claim); err != nil { return err } - if operation, err = r.Allocator.Install(ctx, current, allocation.Installation{Installation: &installation, Current: previous}); err != nil { + image, err := r.catalog().Resolve(ctx, r.consumerOf(first), &installation) + if err == nil { + operation, err = r.Allocator.Install(ctx, current, allocation.Installation{Installation: &installation, Current: previous, Image: image}) + } + if refusal := (*catalog.Refusal)(nil); errors.As(err, &refusal) { + apiMeta.SetStatusCondition(&installation.Status.Conditions, condition("Accepted", metav1.ConditionFalse, installation.Generation, refusal.Reason, refusal.Message)) + if serr := r.Client.Status().Update(ctx, &installation); serr != nil { + return serr + } + } + if err != nil { return fmt.Errorf("install synthetic image: %w", err) } } else if err != nil { @@ -187,7 +206,7 @@ func (r Runner) install(ctx context.Context, installationName string) error { return err } now := metav1.NewTime(r.Now().UTC()) - installation.Status = fleetv1.InstallationStatus{Phase: "Ready", CompletedAt: &now, Conditions: []metav1.Condition{ + installation.Status = fleetv1.InstallationStatus{Phase: "Ready", CompletedAt: &now, ResolvedImage: &fleetv1.ResolvedImage{Name: operation.Spec.Image.Name, Digest: operation.Spec.Image.Digest}, Conditions: []metav1.Condition{ condition("Accepted", metav1.ConditionTrue, installation.Generation, "SyntheticFixtureAccepted", "The standalone fixture admitted this request; this is not Milo authorization."), condition("Executing", metav1.ConditionFalse, installation.Generation, "Completed", "The simulator site returned a verified result under the operation's fence."), condition("Ready", metav1.ConditionTrue, installation.Generation, "Installed", "The simulator site verified the installation."), @@ -299,7 +318,7 @@ func (r Runner) inputs(ctx context.Context) (*fleetv1.MachineClass, *fleetv1.Mac if class.Spec.Capacity == nil || class.Spec.Capacity.MachineCapacities.Namespace != r.Options.ProviderNamespace { return nil, nil, nil, errors.New("synthetic provider scope does not match configuration") } - capacity.Status.Hardware = fleetv1.Hardware{CPU: fleetv1.HardwareCPU{Architecture: "amd64", Cores: 24, Threads: 48, Sockets: 2}, Memory: fleetv1.HardwareMemory{Capacity: "128Gi"}} + capacity.Status.Hardware = fleetv1.Hardware{CPU: fleetv1.HardwareCPU{Architecture: "amd64", Cores: 24, Threads: 48, Sockets: 2}, Firmware: &fleetv1.HardwareFirmware{BootMode: fleetv1.FirmwareUEFI}, Memory: fleetv1.HardwareMemory{Capacity: "128Gi"}} capacity.Status.Conditions = []metav1.Condition{ condition("Prepared", metav1.ConditionTrue, capacity.Generation, "SyntheticEvidence", "Synthetic fixture evidence is current."), condition("Healthy", metav1.ConditionTrue, capacity.Generation, "SyntheticEvidence", "Synthetic fixture evidence is current."), @@ -311,6 +330,21 @@ func (r Runner) inputs(ctx context.Context) (*fleetv1.MachineClass, *fleetv1.Mac return &class, &profile, &capacity, nil } +// catalog resolves images in the provider namespace. Its authorizer is the +// fixture's: every creator may use a published image. This is not Milo +// authorization. +func (r Runner) catalog() *catalog.Catalog { + return &catalog.Catalog{Provider: r.Client, Publisher: tenancy.Namespace(r.Options.ProviderNamespace), Namespace: r.Options.ProviderNamespace, + Authorize: func(context.Context, *fleetv1.Installation, *fleetv1.MachineImage, *fleetv1.MachineImage) error { + return nil + }} +} + +// consumerOf is the consumer tenant: in standalone mode, the namespace. +func (r Runner) consumerOf(c claim) tenancy.Consumer { + return tenancy.Consumer{Ref: c.machine.Consumer, UID: c.machine.ConsumerUID, Client: r.Client} +} + type claim struct { claim *fleetv1.Machine machine allocation.Machine From 6fff24869005a8d52ac69582d262573a702a63c3 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sun, 29 Nov 2026 13:38:28 -0600 Subject: [PATCH 2/2] test(allocation): supply resolved images to NSO release scenarios --- internal/allocation/switch_test.go | 2 +- internal/allocation/verify_test.go | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/internal/allocation/switch_test.go b/internal/allocation/switch_test.go index ea8c74e0..42555ee3 100644 --- a/internal/allocation/switch_test.go +++ b/internal/allocation/switch_test.go @@ -28,7 +28,7 @@ func TestASwitchedSourceStillReleasesItsOldClaims(t *testing.T) { if err != nil { t.Fatal(err) } - operation := e.installed(allocation, Installation{Installation: e.installation(1, "debian-12", "")}) + operation := e.installed(allocation, Installation{Image: image(), Installation: e.installation(1, "debian-12", "")}) if claim := operation.Spec.BootNetwork.AddressClaim; claim != bootaddress.Reference(bootaddress.ClaimName(operation.Name)) { t.Fatalf("claim = %+v, want IPAM's", claim) } diff --git a/internal/allocation/verify_test.go b/internal/allocation/verify_test.go index e7045df1..ef73508e 100644 --- a/internal/allocation/verify_test.go +++ b/internal/allocation/verify_test.go @@ -35,7 +35,7 @@ func TestAnNSOReleaseIsVerifiedAfterTheClaimIsGone(t *testing.T) { if err != nil { t.Fatal(err) } - operation := e.installed(allocation, Installation{Installation: e.installation(1, "debian-12", "")}) + operation := e.installed(allocation, Installation{Image: image(), Installation: e.installation(1, "debian-12", "")}) stop() claimName := bootaddress.ClaimName(operation.Name) var allocations unstructured.UnstructuredList @@ -108,7 +108,7 @@ func TestNSOReleaseNeedsNoIPAMAPI(t *testing.T) { if err != nil { t.Fatal(err) } - operation := e.installed(allocation, Installation{Installation: e.installation(1, "debian-12", "")}) + operation := e.installed(allocation, Installation{Image: image(), Installation: e.installation(1, "debian-12", "")}) e.allocator.Provider, e.allocator.Releaser = noIPAM{e.admin}, noIPAM{e.admin} var last error e.until("the NSO boot attachment is released", func() bool { @@ -188,7 +188,7 @@ func TestARetainedAwayOperationsReleaseIsStillVerified(t *testing.T) { if err != nil { t.Fatal(err) } - operation := e.installed(allocation, Installation{Installation: e.installation(1, "debian-12", "")}) + operation := e.installed(allocation, Installation{Image: image(), Installation: e.installation(1, "debian-12", "")}) stop() held := e.ipamAllocations() if len(held) != 1 || len(allocation.Status.BootClaims) != 1 {