diff --git a/config/base/crd/metal.datumapis.com.yaml b/config/base/crd/metal.datumapis.com.yaml index aa6844b7..0caa3383 100644 --- a/config/base/crd/metal.datumapis.com.yaml +++ b/config/base/crd/metal.datumapis.com.yaml @@ -629,7 +629,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 7c18f767..739a7e58 100644 --- a/config/components/device-operations/crds/fleet.datumapis.com.yaml +++ b/config/components/device-operations/crds/fleet.datumapis.com.yaml @@ -498,6 +498,14 @@ spec: digest: type: string pattern: ^sha256:[0-9a-f]{64}$ + firmwareModes: + type: array + maxItems: 2 + items: + type: string + enum: + - UEFI + - BIOS downloads: type: array maxItems: 8 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 0830ec6f..4bc87f12 100644 --- a/config/components/iam/roles/controller.yaml +++ b/config/components/iam/roles/controller.yaml @@ -25,3 +25,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/site/base/enrollment.json b/config/site/base/enrollment.json index 9a3508bf..7f958453 100644 --- a/config/site/base/enrollment.json +++ b/config/site/base/enrollment.json @@ -1 +1 @@ -{"fleet-provider/synthetic-device-central-01": {"bmcEndpoint": "https://[2001:db8::51]", "systemUUID": "00000000-0000-4000-8000-000000000051", "bootMACAddress": "52:54:00:77:00:02", "bmcPublicKeySHA256": "5151515151515151515151515151515151515151515151515151515151515151", "disks": ["disk-0"], "hardware": {"cpu": {"architecture": "amd64", "cores": 2}, "memory": "2Gi", "disks": [{"name": "disk-0", "capacity": "2Gi"}], "interfaces": [{"name": "primary", "macAddress": "52:54:00:77:00:02"}]}}} +{"fleet-provider/synthetic-device-central-01": {"bmcEndpoint": "https://[2001:db8::51]", "systemUUID": "00000000-0000-4000-8000-000000000051", "bootMACAddress": "52:54:00:77:00:02", "bmcPublicKeySHA256": "5151515151515151515151515151515151515151515151515151515151515151", "disks": ["disk-0"], "hardware": {"bootMode": "BIOS", "cpu": {"architecture": "amd64", "cores": 2}, "memory": "2Gi", "disks": [{"name": "disk-0", "capacity": "2Gi"}], "interfaces": [{"name": "primary", "macAddress": "52:54:00:77:00:02"}]}}} diff --git a/config/standalone/fixtures.yaml b/config/standalone/fixtures.yaml index b17311da..f3aea79f 100644 --- a/config/standalone/fixtures.yaml +++ b/config/standalone/fixtures.yaml @@ -32,6 +32,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 +--- # The synthetic site overwrites its one disk and reads it back, so the # fixture policy claims only Clear. apiVersion: fleet.datumapis.com/v1alpha1 @@ -82,7 +96,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 @@ -90,4 +104,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 91696bfe..b367c918 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, devicecommissionings, devicecommissioningplans, devicecommissioningplanapprovals] verbs: [get, list] @@ -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/config/standalone/site.yaml b/config/standalone/site.yaml index 9ce143ba..0e50c6a7 100644 --- a/config/standalone/site.yaml +++ b/config/standalone/site.yaml @@ -6,7 +6,7 @@ kind: ConfigMap metadata: {name: fleet-simulator-enrollment, namespace: fleet-system} data: enrollment.json: | - {"fleet-provider/synthetic-device-central-01": {"bmcEndpoint": "https://[2001:db8::21]", "systemUUID": "00000000-0000-4000-8000-000000000021", "bootMACAddress": "02:00:00:00:00:21", "bmcPublicKeySHA256": "2121212121212121212121212121212121212121212121212121212121212121", "disks": ["disk-0"], "hardware": {"cpu": {"architecture": "amd64", "model": "synthetic", "sockets": 2, "cores": 24}, "memory": "128Gi", "disks": [{"name": "disk-0", "capacity": "960Gi"}], "interfaces": [{"name": "primary", "macAddress": "02:00:00:00:00:21"}]}, "firmware": [{"component": "BMC", "version": "synthetic-1.0"}]}} + {"fleet-provider/synthetic-device-central-01": {"bmcEndpoint": "https://[2001:db8::21]", "systemUUID": "00000000-0000-4000-8000-000000000021", "bootMACAddress": "02:00:00:00:00:21", "bmcPublicKeySHA256": "2121212121212121212121212121212121212121212121212121212121212121", "disks": ["disk-0"], "hardware": {"bootMode": "UEFI", "cpu": {"architecture": "amd64", "model": "synthetic", "sockets": 2, "cores": 24}, "memory": "128Gi", "disks": [{"name": "disk-0", "capacity": "960Gi"}], "interfaces": [{"name": "primary", "macAddress": "02:00:00:00:00:21"}]}, "firmware": [{"component": "BMC", "version": "synthetic-1.0"}]}} --- # The custody coordinator: the only writer of custody and of operation # status. It delivers admitted operations to the simulator site and reports diff --git a/docs/development/README.md b/docs/development/README.md index 80e45df0..ce0c2c9c 100644 --- a/docs/development/README.md +++ b/docs/development/README.md @@ -41,6 +41,12 @@ smoke and both multi-plane runs verify it. The end-to-end failure scenarios The [power kind's control plane](device-custody.md#device-power-operations) is implemented on the same custody, and nothing creates power operations yet. +[OS images and bootstrap data](machine-images.md) has its image catalog +**implemented**: a provider-published, digest-pinned `MachineImage` that +admission resolves through a publication record and checks against the +server's architecture and firmware mode. The sealed bootstrap store is +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..30bb47ef --- /dev/null +++ b/docs/development/machine-images.md @@ -0,0 +1,82 @@ +# 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.** Commissioning records the observed firmware mode (Redfish discovery + or synthetic site enrollment). The capacity projector carries that evidence into + the allocator’s hardware snapshot. Catalog publication never writes capacity + status. 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 6e8849c8..aba55ca1 100755 --- a/hack/multiplane/milo.py +++ b/hack/multiplane/milo.py @@ -168,7 +168,7 @@ def write(obj): 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) @@ -180,7 +180,7 @@ def write(obj): # The Metal provider records allocations and creates installations. It # evaluates capacity from custody and commissioning evidence, and never # writes capacity status. - rules+=[{'apiGroups':['metal.datumapis.com'],'resources':['machineallocations'],'verbs':['get','list','watch','create','delete']},{'apiGroups':['metal.datumapis.com'],'resources':['machineallocations/status'],'verbs':['get','update']}, + 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','devicecommissionings','devicecommissioningplans','devicecommissioningplanapprovals'],'verbs':['get','list','watch']}] rules.append({'apiGroups':['fleet.datumapis.com'],'resources':['cleaningpolicies'],'verbs':['get']}) diff --git a/internal/allocation/allocator.go b/internal/allocation/allocator.go index 2f1c95e3..1b2e27f5 100644 --- a/internal/allocation/allocator.go +++ b/internal/allocation/allocator.go @@ -33,6 +33,7 @@ import ( fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" "go.datum.net/fleet/internal/bootaddress" "go.datum.net/fleet/internal/capacity" + "go.datum.net/fleet/internal/catalog" "go.datum.net/fleet/internal/cleaning" "go.datum.net/fleet/internal/custody" "go.datum.net/fleet/internal/tenancy" @@ -530,17 +531,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 @@ -557,8 +551,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) @@ -567,7 +564,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/bootaddress_test.go b/internal/allocation/bootaddress_test.go index dfc18614..4efe35bb 100644 --- a/internal/allocation/bootaddress_test.go +++ b/internal/allocation/bootaddress_test.go @@ -112,7 +112,7 @@ func TestTheDefaultAllocatorClaimsNoBootAddress(t *testing.T) { if err != nil { t.Fatal(err) } - operation, err := e.allocator.Install(e.ctx, allocation, Installation{Installation: e.installation(1, "debian-12", "")}) + operation, err := e.allocator.Install(e.ctx, allocation, Installation{Image: image(), Installation: e.installation(1, "debian-12", "")}) if err != nil { t.Fatal(err) } @@ -220,7 +220,7 @@ func TestBootAddressesFollowTheirOperations(t *testing.T) { if err != nil { t.Fatal(err) } - operation, err := e.allocator.Install(e.ctx, allocation, Installation{Installation: e.installation(1, "debian-12", "")}) + operation, err := e.allocator.Install(e.ctx, allocation, Installation{Image: image(), Installation: e.installation(1, "debian-12", "")}) if err != nil { t.Fatal(err) } @@ -245,7 +245,7 @@ func TestBootAddressesFollowTheirOperations(t *testing.T) { t.Fatalf("custody = %+v", state.Spec) } // Asking again returns the existing operation and claims nothing new. - if _, err := e.allocator.Install(e.ctx, allocation, Installation{Installation: e.installation(1, "debian-12", "")}); err != nil || len(recorder.created()) != 3 { + if _, err := e.allocator.Install(e.ctx, allocation, Installation{Image: image(), Installation: e.installation(1, "debian-12", "")}); err != nil || len(recorder.created()) != 3 { t.Fatalf("repeat install: %v, creates %v", err, recorder.created()) } @@ -337,7 +337,7 @@ func TestAnExhaustedPoolSendsNothing(t *testing.T) { t.Fatal(err) } installation := e.installation(1, "debian-12", "") - if _, err := e.allocator.Install(e.ctx, allocation, Installation{Installation: installation}); !errors.Is(err, bootaddress.ErrExhausted) || !strings.Contains(err.Error(), "lab-provisioning") { + if _, err := e.allocator.Install(e.ctx, allocation, Installation{Image: image(), Installation: installation}); !errors.Is(err, bootaddress.ErrExhausted) || !strings.Contains(err.Error(), "lab-provisioning") { t.Fatalf("install with a full pool: %v", err) } operations := &ops.DeviceInstallationList{} @@ -367,7 +367,7 @@ func TestAVirtualMediaInstallRecordsTheMachinesAddress(t *testing.T) { if err != nil { t.Fatal(err) } - if _, err := e.allocator.Install(e.ctx, allocation, Installation{Installation: e.installation(1, "debian-12", "")}); !errors.Is(err, ErrNoReportAddress) { + if _, err := e.allocator.Install(e.ctx, allocation, Installation{Image: image(), Installation: e.installation(1, "debian-12", "")}); !errors.Is(err, ErrNoReportAddress) { t.Fatalf("an install with no address source = %v", err) } name := custody.InstallationName(allocation.Name, uid(701)) @@ -375,7 +375,7 @@ func TestAVirtualMediaInstallRecordsTheMachinesAddress(t *testing.T) { t.Fatalf("an installation was created without a report address: %v", err) } e.allocator.BootAddresses = &bootaddress.Claimer{Class: "data"} - operation, err := e.allocator.Install(e.ctx, allocation, Installation{Installation: e.installation(1, "debian-12", "")}) + operation, err := e.allocator.Install(e.ctx, allocation, Installation{Image: image(), Installation: e.installation(1, "debian-12", "")}) if err != nil { t.Fatal(err) } diff --git a/internal/allocation/bootclaims_test.go b/internal/allocation/bootclaims_test.go index 52705bd0..1eeca2e1 100644 --- a/internal/allocation/bootclaims_test.go +++ b/internal/allocation/bootclaims_test.go @@ -44,7 +44,7 @@ func TestAFullBootClaimRecordRefusesTheNextClaim(t *testing.T) { full := slices.Clone(allocation.Status.BootClaims) installation := e.installation(1, "debian-12", "") - if _, err := e.allocator.Install(e.ctx, allocation, Installation{Installation: installation}); !errors.Is(err, ErrBootClaimsFull) { + if _, err := e.allocator.Install(e.ctx, allocation, Installation{Image: image(), Installation: installation}); !errors.Is(err, ErrBootClaimsFull) { t.Fatalf("install with a full record: %v", err) } name := custody.InstallationName(allocation.Name, string(installation.UID)) @@ -85,7 +85,7 @@ func TestTheRecordIsWrittenBeforeTheClaim(t *testing.T) { } e.allocator.Provider = noStatus{e.admin} installation := e.installation(1, "debian-12", "") - if _, err := e.allocator.Install(e.ctx, allocation, Installation{Installation: installation}); err == nil { + if _, err := e.allocator.Install(e.ctx, allocation, Installation{Image: image(), Installation: installation}); err == nil { t.Fatal("installed without recording its boot claim") } name := custody.InstallationName(allocation.Name, string(installation.UID)) @@ -118,7 +118,7 @@ func TestIPAMClaimsAreNotRecorded(t *testing.T) { full := slices.Clone(allocation.Status.BootClaims) previous := "" for n, name := range []string{"debian-12", "debian-12-second", "debian-12-third"} { - request := Installation{Installation: e.installation(n+1, name, previous), Current: previous} + request := Installation{Image: image(), Installation: e.installation(n+1, name, previous), Current: previous} operation := e.installed(allocation, request) if claim := operation.Spec.BootNetwork.AddressClaim; claim.Kind != bootaddress.GVK.Kind { t.Fatalf("installation %d claimed %+v, want IPAM's", n, claim) @@ -147,7 +147,7 @@ func TestARecordWithNoClaimIsCleared(t *testing.T) { if err != nil { t.Fatal(err) } - if _, err := e.allocator.Install(e.ctx, allocation, Installation{Installation: e.installation(1, "debian-12", "")}); !errors.Is(err, nso.ErrAttachmentUnknown) { + if _, err := e.allocator.Install(e.ctx, allocation, Installation{Image: image(), Installation: e.installation(1, "debian-12", "")}); !errors.Is(err, nso.ErrAttachmentUnknown) { t.Fatalf("install without a cable record: %v", err) } if len(allocation.Status.BootClaims) != 1 { diff --git a/internal/allocation/delivery_test.go b/internal/allocation/delivery_test.go index 74daa333..12c0a3c5 100644 --- a/internal/allocation/delivery_test.go +++ b/internal/allocation/delivery_test.go @@ -42,7 +42,7 @@ func TestNoInstallationUntilTheSiteDeclaresItsMethods(t *testing.T) { } declared := e.allocator.Sites e.allocator.Sites = undeclared{declared} - request := Installation{Installation: e.installation(1, "debian-12", "")} + request := Installation{Image: image(), Installation: e.installation(1, "debian-12", "")} if _, err := e.allocator.Install(e.ctx, allocation, request); !errors.Is(err, ErrDeliveryUnknown) { t.Fatalf("install err = %v", err) } diff --git a/internal/allocation/flow_test.go b/internal/allocation/flow_test.go index 1108a920..4b8b3d1b 100644 --- a/internal/allocation/flow_test.go +++ b/internal/allocation/flow_test.go @@ -3,6 +3,7 @@ package allocation import ( "context" "errors" + "strings" "sync" "testing" @@ -11,6 +12,7 @@ import ( ops "go.datum.net/fleet/internal/api/operations/v1alpha1" fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/catalog" "go.datum.net/fleet/internal/custody" "go.datum.net/fleet/internal/site/simwork" ) @@ -51,7 +53,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) } @@ -75,9 +77,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 3be9a220..9f7162c8 100644 --- a/internal/allocation/harness_test.go +++ b/internal/allocation/harness_test.go @@ -26,6 +26,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" @@ -36,14 +37,15 @@ import ( ) const ( - fixtureDigest = "sha256:0c2b77e1d9a4000000000000000000000000000000000000000000000000cafe" namespace = "fleet-provider" providerUser = "system:serviceaccount:fleet-system:metal-provider" releaseUser = "system:serviceaccount:fleet-system:release-controller" siteName = "site-example-a" siteToken = "synthetic-site-token" keyDigest = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - imageRef = "debian-12@sha256:9f4ad8d8b8a6f6fc64d2cf2c7e70b9184b74f089adf8c36d84f4fcb99892f3cb" + imageName = "debian-12" + imageDigest = "sha256:9f4ad8d8b8a6f6fc64d2cf2c7e70b9184b74f089adf8c36d84f4fcb99892f3cb" + fixtureDigest = "sha256:0c2b77e1d9a4000000000000000000000000000000000000000000000000cafe" ) func uid(n int) string { return fmt.Sprintf("00000000-0000-4000-8000-%012d", n) } @@ -193,7 +195,7 @@ func (e *env) server(n int) *inventory.Device { e.create(device) key := fmt.Sprintf("%064x", n) e.enrollment[namespace+"/"+name] = fixture.Target{BMCEndpoint: device.Spec.BMC.Endpoint, SystemUUID: uid(100 + n), BootMACAddress: mac, BMCPublicKeySHA256: key, Disks: []string{"disk-0"}, - Hardware: &ops.InspectedHardware{CPU: ops.InspectedCPU{Architecture: "amd64", Cores: 2}, Memory: "2Gi", Disks: []ops.InspectedDisk{{Name: "disk-0", Capacity: "2Gi"}}, Interfaces: []ops.InspectedInterface{{Name: "primary", MACAddress: mac}}}} + Hardware: &ops.InspectedHardware{BootMode: fleetv1.FirmwareUEFI, CPU: ops.InspectedCPU{Architecture: "amd64", Cores: 2}, Memory: "2Gi", Disks: []ops.InspectedDisk{{Name: "disk-0", Capacity: "2Gi"}}, Interfaces: []ops.InspectedInterface{{Name: "primary", MACAddress: mac}}}} e.loop.Courier.Sites.Devices[name] = []string{siteName} 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"}} @@ -260,13 +262,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/allocation/nsoboot_test.go b/internal/allocation/nsoboot_test.go index bbc09f0f..c962c90d 100644 --- a/internal/allocation/nsoboot_test.go +++ b/internal/allocation/nsoboot_test.go @@ -384,7 +384,7 @@ func TestNSOBootWaitsForTheAttachment(t *testing.T) { } return len(list.Items) } - request := Installation{Installation: e.installation(1, "debian-12", "")} + request := Installation{Image: image(), Installation: e.installation(1, "debian-12", "")} healthy := e.allocator.Provider e.allocator.Provider = nsoDown{healthy} if _, err := e.allocator.Install(e.ctx, allocation, request); err == nil || errors.Is(err, bootaddress.ErrPending) || installations() != 0 { @@ -445,7 +445,7 @@ func TestNSOBootNICWaitsForCustody(t *testing.T) { } return len(list.Items) } - request := Installation{Installation: e.installation(1, "debian-12", "")} + request := Installation{Image: image(), Installation: e.installation(1, "debian-12", "")} healthy := e.allocator.Provider for name, set := range map[string]func(*ops.DeviceCustody){ "another operation is running": func(state *ops.DeviceCustody) { @@ -557,7 +557,7 @@ func TestOneWriterPerPortThroughHandover(t *testing.T) { // First install on the shared boot NIC; the customer's claim, made // while it runs as #198's attachment would, stays unprogrammed. - first := e.installed(allocation, Installation{Installation: e.installation(1, "debian-12", "")}) + first := e.installed(allocation, Installation{Image: image(), Installation: e.installation(1, "debian-12", "")}) customerClaim := &networkingv1.NetworkInterfaceClaim{ObjectMeta: metav1.ObjectMeta{Namespace: "default", Name: "fleet-customer-primary", Labels: map[string]string{bootaddress.AllocationLabel: allocation.Name}}, Spec: networkingv1.NetworkInterfaceClaimSpec{Network: networkingv1.LocalNetworkRef{Name: customerNetwork}, InterfaceName: "primary", AttachmentMode: nso.PhysicalMode, IPFamilies: []networkingv1.IPFamily{networkingv1.IPv4Protocol}}} nso.SetAttachmentPoint(customerClaim, nso.AttachmentPoint{MACAddress: "02:00:00:00:00:01", Switch: "switch-example-a", Port: "ethernet7"}) @@ -569,7 +569,7 @@ func TestOneWriterPerPortThroughHandover(t *testing.T) { handedOver("the port is handed to the customer after the first install") // A reinstall moves the port back to the boot network for the install. - second := e.installed(allocation, Installation{Installation: e.installation(2, "debian-12-second", "debian-12"), Current: "debian-12"}) + second := e.installed(allocation, Installation{Image: image(), Installation: e.installation(2, "debian-12-second", "debian-12"), Current: "debian-12"}) if condition := networkReady(); condition.Status != metav1.ConditionFalse { t.Fatalf("NetworkReady during the reinstall = %+v", condition) } 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 { diff --git a/internal/api/operations/v1alpha1/commissioning.go b/internal/api/operations/v1alpha1/commissioning.go index 6fbfad78..d45ce3de 100644 --- a/internal/api/operations/v1alpha1/commissioning.go +++ b/internal/api/operations/v1alpha1/commissioning.go @@ -158,6 +158,7 @@ type CommissioningEvidence struct { // InspectedHardware is what inspection read, in the shape of MachineCapacity // hardware. type InspectedHardware struct { + BootMode string `json:"bootMode,omitempty"` CPU InspectedCPU `json:"cpu"` Memory string `json:"memory"` Disks []InspectedDisk `json:"disks,omitempty"` diff --git a/internal/api/operations/v1alpha1/types.go b/internal/api/operations/v1alpha1/types.go index d7d1efab..d304e313 100644 --- a/internal/api/operations/v1alpha1/types.go +++ b/internal/api/operations/v1alpha1/types.go @@ -405,6 +405,9 @@ type BootNetworkInput 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"` // Downloads are the artifacts the installer fetches during the // install, such as Talos's installer container image. Each is pinned // by digest; admission refuses one that is not. 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 b0aff3a4..83e62747 100644 --- a/internal/api/v1alpha1/crd_validation_test.go +++ b/internal/api/v1alpha1/crd_validation_test.go @@ -221,3 +221,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 22b9a751..b111a304 100644 --- a/internal/api/v1alpha1/types.go +++ b/internal/api/v1alpha1/types.go @@ -146,7 +146,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"` @@ -159,6 +162,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"` } @@ -346,9 +359,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 @@ -530,7 +628,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 } @@ -599,3 +697,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/capacity/projector.go b/internal/capacity/projector.go index a3784935..2e73bebb 100644 --- a/internal/capacity/projector.go +++ b/internal/capacity/projector.go @@ -272,6 +272,9 @@ func hardware(in *ops.InspectedHardware) metal.Hardware { return metal.Hardware{} } out := metal.Hardware{CPU: metal.HardwareCPU{Architecture: in.CPU.Architecture, Model: in.CPU.Model, Sockets: in.CPU.Sockets, Cores: in.CPU.Cores}, Memory: metal.HardwareMemory{Capacity: in.Memory}} + if in.BootMode != "" { + out.Firmware = &metal.HardwareFirmware{BootMode: in.BootMode} + } for _, disk := range in.Disks { out.Disks = append(out.Disks, metal.HardwareDisk{Name: disk.Name, Capacity: disk.Capacity}) } 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 a3fdc7f0..86b9774f 100644 --- a/internal/custody/kinds.go +++ b/internal/custody/kinds.go @@ -51,6 +51,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" // Reasons a site raises when an operation's boot network input does not // fit the site's DHCP. ReasonBootNetworkRequired = "BootNetworkRequired" @@ -194,7 +197,7 @@ func DeviceInstallationKind() Kind { return map[string]string{ExtraDeliveryMethod: string(admission.Operation.(*ops.DeviceInstallation).Spec.Delivery.Method)} }, Settles: []SettleRule{{Held: "DeviceInstallation"}}, - Reasons: append(append(append([]Reason{{Name: ReasonBootstrapUnsupported, RaisedBy: RaisedByBoth}}, networkBootReasons...), workerReasons...), deliveryReasons...), + Reasons: append(append(append([]Reason{{Name: ReasonImageIncompatible, RaisedBy: RaisedByWorker}, {Name: ReasonBootstrapUnsupported, RaisedBy: RaisedByBoth}}, networkBootReasons...), workerReasons...), deliveryReasons...), Evidence: StrictEvidence(evidenceLimit, func(_ ops.Operation, evidence *ops.InstallationEvidence) error { return validateSteps(evidence.Steps) }), diff --git a/internal/manager/customer_power_envtest_test.go b/internal/manager/customer_power_envtest_test.go index 70df3f2d..b83cc0a2 100644 --- a/internal/manager/customer_power_envtest_test.go +++ b/internal/manager/customer_power_envtest_test.go @@ -24,6 +24,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" @@ -43,7 +44,7 @@ const ( siteName = "site-example-a" siteToken = "synthetic-site-token" keyDigest = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - imageRef = "debian-12@sha256:9f4ad8d8b8a6f6fc64d2cf2c7e70b9184b74f089adf8c36d84f4fcb99892f3cb" + imageDigest = "sha256:9f4ad8d8b8a6f6fc64d2cf2c7e70b9184b74f089adf8c36d84f4fcb99892f3cb" policyDigest = "sha256:0c2b77e1d9a4000000000000000000000000000000000000000000000000cafe" ) @@ -181,7 +182,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{Firmware: &fleetv1.HardwareFirmware{BootMode: fleetv1.FirmwareUEFI}, CPU: fleetv1.HardwareCPU{Architecture: "amd64", Cores: 2}, 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()}) } @@ -236,13 +237,13 @@ func (e *env) request(n int) allocation.Request { return allocation.Request{Machine: machine(n), Class: e.class, Profile: e.profile, Authority: fleetv1.AllocationAuthority{Principal: "fixture", Decision: fmt.Sprintf("fixture-%d", n)}} } -func (e *env) installation(n int, name, predecessor string) *fleetv1.Installation { +func (e *env) installation(n int, name, predecessor string) allocation.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: "debian-12"}, ExpectedPredecessor: fleetv1.InstallationPredecessor{Type: "None"}}} if predecessor != "" { installation.Spec.ExpectedPredecessor = fleetv1.InstallationPredecessor{Type: "Installation", Name: predecessor} } - return installation + return allocation.Installation{Installation: installation, Image: catalog.Image{Name: "debian-12", Definition: fleetv1.ImageDefinition{Digest: imageDigest, Architecture: "amd64", FirmwareModes: []string{fleetv1.FirmwareUEFI}}}} } // release repeats Release while the coordinator runs, until it is Released. @@ -459,7 +460,7 @@ func TestCustomerPower(t *testing.T) { } // An installation that finishes after discovery's read proves no // power, so power is unknown until discovery reads it again. - install, err := e.allocator.Install(e.ctx, p.allocation, allocation.Installation{Installation: e.installation(11, "debian-12", "")}) + install, err := e.allocator.Install(e.ctx, p.allocation, e.installation(11, "debian-12", "")) if err != nil { t.Fatal(err) } @@ -482,7 +483,7 @@ func TestCustomerPower(t *testing.T) { if p.machine.Spec.PowerState != "" { t.Fatalf("powerState = %q", p.machine.Spec.PowerState) } - install, err := e.allocator.Install(e.ctx, p.allocation, allocation.Installation{Installation: e.installation(19, "debian-12", "")}) + install, err := e.allocator.Install(e.ctx, p.allocation, e.installation(19, "debian-12", "")) if err != nil { t.Fatal(err) } @@ -573,7 +574,7 @@ func TestCustomerPower(t *testing.T) { t.Run("a power change waits behind a running installation", func(t *testing.T) { p := e.allocatePowered(12) - install, err := e.allocator.Install(e.ctx, p.allocation, allocation.Installation{Installation: e.installation(12, "debian-12", "")}) + install, err := e.allocator.Install(e.ctx, p.allocation, e.installation(12, "debian-12", "")) if err != nil { t.Fatal(err) } @@ -594,7 +595,7 @@ func TestCustomerPower(t *testing.T) { t.Run("a newer power request replaces a pending one", func(t *testing.T) { p := e.allocatePowered(13) - install, err := e.allocator.Install(e.ctx, p.allocation, allocation.Installation{Installation: e.installation(13, "debian-12", "")}) + install, err := e.allocator.Install(e.ctx, p.allocation, e.installation(13, "debian-12", "")) if err != nil { t.Fatal(err) } @@ -623,7 +624,7 @@ func TestCustomerPower(t *testing.T) { t.Run("an intent that returns to the observed state replaces the request that has not run", func(t *testing.T) { p := e.allocatePowered(16) - install, err := e.allocator.Install(e.ctx, p.allocation, allocation.Installation{Installation: e.installation(16, "debian-12", "")}) + install, err := e.allocator.Install(e.ctx, p.allocation, e.installation(16, "debian-12", "")) if err != nil { t.Fatal(err) } diff --git a/internal/multiplane/commission.go b/internal/multiplane/commission.go index ff9c64f7..aaef37c0 100644 --- a/internal/multiplane/commission.go +++ b/internal/multiplane/commission.go @@ -14,7 +14,6 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/controller-runtime/pkg/client" - "go.datum.net/fleet/internal/allocation" 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" @@ -73,7 +72,7 @@ func (r *Runner) Commission(ctx context.Context) error { } staff[who] = api } - image, err := allocation.ParseImage(r.Config.Image) + image, err := cellImage(r.Config.Image) if err != nil { return fmt.Errorf("%w: the site image: %v", errTerminal, err) } diff --git a/internal/multiplane/media.go b/internal/multiplane/media.go index 29dc39ea..d98defc9 100644 --- a/internal/multiplane/media.go +++ b/internal/multiplane/media.go @@ -20,7 +20,6 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/controller-runtime/pkg/client" - "go.datum.net/fleet/internal/allocation" 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" @@ -136,7 +135,7 @@ func (r *Runner) refusedInstallation(ctx context.Context, request string, delive if err := r.Provider.API.Get(ctx, client.ObjectKey{Namespace: DeviceNamespace, Name: Device}, device); err != nil { return err } - image, err := allocation.ParseImage(r.Config.Image) + image, err := cellImage(r.Config.Image) if err != nil { return err } @@ -188,8 +187,12 @@ func (r *Runner) mediaInstallation(ctx context.Context, name string) (*request, if err != nil { return nil, nil, nil, err } + artifact, err := cellImage(r.Config.Image) + if err != nil { + return nil, nil, nil, err + } install := &fleet.Installation{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: Namespace}, Spec: fleet.InstallationSpec{MachineRef: fleet.MachineReference{Name: "allocation"}, - ExpectedPredecessor: fleet.InstallationPredecessor{Type: "None"}, ImageRef: fleet.LocalReference{Name: r.Config.Image}}} + ExpectedPredecessor: fleet.InstallationPredecessor{Type: "None"}, ImageRef: fleet.LocalReference{Name: artifact.Name}}} if err := ensure(ctx, customer, install); err != nil { return nil, nil, nil, err } diff --git a/internal/multiplane/runner.go b/internal/multiplane/runner.go index 71a3a90d..b77bf4ec 100644 --- a/internal/multiplane/runner.go +++ b/internal/multiplane/runner.go @@ -31,6 +31,7 @@ import ( fleet "go.datum.net/fleet/internal/api/v1alpha1" "go.datum.net/fleet/internal/bootaddress" "go.datum.net/fleet/internal/capacity" + "go.datum.net/fleet/internal/catalog" "go.datum.net/fleet/internal/controller" "go.datum.net/fleet/internal/coordination" "go.datum.net/fleet/internal/custody" @@ -414,6 +415,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) { @@ -445,7 +454,23 @@ func (r *Runner) installationNamed(ctx context.Context, index int, name string) 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 { @@ -492,6 +517,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/scenarios.go b/internal/multiplane/scenarios.go index 8c89f0ee..3bfe0e70 100644 --- a/internal/multiplane/scenarios.go +++ b/internal/multiplane/scenarios.go @@ -171,7 +171,11 @@ func (r *Runner) TenantIsolation(ctx context.Context) error { return err } unheld := allocation.Name(q.alloc.Machine) - image, err := allocation.ParseImage(install.Spec.ImageRef.Name) + consumer, err := r.Resolve(ctx, q.alloc.Machine.Consumer) + if err != nil { + return err + } + resolved, err := ImageCatalog(r.Provider.API).Resolve(ctx, consumer, &install) if err != nil { return err } @@ -189,7 +193,7 @@ func (r *Runner) TenantIsolation(ctx context.Context) error { Spec: ops.DeviceInstallationSpec{ OperationEnvelope: ops.OperationEnvelope{Creator: r.Allocator.ProviderCreator, DeviceRef: ops.DeviceReference{Name: device.Name}, Authority: ops.Authority{AllocationRef: &ops.LocalReference{Name: unheld}}}, - Image: image, BootInterface: "primary", TargetDisks: []string{"disk-0"}, Delivery: ops.DeliveryInput{Method: ops.DeliveryNetworkBoot}, + Image: ops.ImageInput{Name: resolved.Name, Digest: resolved.Definition.Digest, FirmwareModes: resolved.Definition.FirmwareModes}, BootInterface: "primary", TargetDisks: []string{"disk-0"}, Delivery: ops.DeliveryInput{Method: ops.DeliveryNetworkBoot}, }, } if err := r.Provider.API.Create(ctx, operation); err != nil { diff --git a/internal/multiplane/seed.go b/internal/multiplane/seed.go index 4d7bd387..cd694233 100644 --- a/internal/multiplane/seed.go +++ b/internal/multiplane/seed.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "errors" + "fmt" "os" "path/filepath" "sort" @@ -59,6 +60,20 @@ func Seed(ctx context.Context, c Config) error { if err := provider.Status().Update(ctx, &class); err != nil { return err } + // The provider defines the one image the cell holds: the pinned + // installer manifest's digest. + artifact, err := cellImage(c.Image) + if err != nil { + return err + } + imageName := artifact.Name + 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: artifact.FirmwareModes, Digest: artifact.Digest}, + 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")) @@ -110,10 +125,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 @@ -126,6 +137,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, "", " ") @@ -164,6 +183,15 @@ func enrolledDevices(c Config) ([]client.Object, error) { return out, nil } +func cellImage(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("the cell image must be name@sha256:<64 hex>") + } + return ops.ImageInput{Name: name, Digest: digest, FirmwareModes: []string{fleet.FirmwareBIOS}}, nil +} + // LabCleaningPolicy is the lab's CleaningPolicy: Clear, by overwriting every // block and reading it back, the only method the lab proves. func LabCleaningPolicy() *ops.CleaningPolicy { diff --git a/internal/redfish/client.go b/internal/redfish/client.go index 86d3706c..b3fa1121 100644 --- a/internal/redfish/client.go +++ b/internal/redfish/client.go @@ -251,6 +251,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 } @@ -375,6 +378,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 ae354c1f..6ae945d3 100644 --- a/internal/redfish/client_test.go +++ b/internal/redfish/client_test.go @@ -128,6 +128,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 TestSetUserAgentMarksEveryRequestOnlyWhenSet(t *testing.T) { b := newStub() c := stubClient(t, b, time.Second) diff --git a/internal/site/redfishwork/commissioning.go b/internal/site/redfishwork/commissioning.go index 209b184e..b3253f9a 100644 --- a/internal/site/redfishwork/commissioning.go +++ b/internal/site/redfishwork/commissioning.go @@ -169,6 +169,7 @@ func (k Commissioning) preflight(ctx context.Context, work *site.Work, spec ops. } evidence.SerialNumber, evidence.SystemUUID = clip(hw.SerialNumber), hw.UUID evidence.Hardware = inspected(hw) + evidence.Hardware.BootMode = conn(work).System.BootMode if mismatches := inspect(spec.Plan.Content.Inspection, hw); len(mismatches) > 0 { return evidence, ops.PhaseInspect, mismatches, nil } diff --git a/internal/site/redfishwork/commissioning_test.go b/internal/site/redfishwork/commissioning_test.go index fb2fed47..0057b0cb 100644 --- a/internal/site/redfishwork/commissioning_test.go +++ b/internal/site/redfishwork/commissioning_test.go @@ -88,7 +88,7 @@ func TestCommissioningPassesAServerThatMeetsThePlan(t *testing.T) { t.Fatalf("result = %+v, evidence %+v, %d power-ons", result, evidence, l.onCount()) } hardware := evidence.Hardware - if hardware.CPU.Architecture != "amd64" || hardware.CPU.Cores != 2 || hardware.Memory != "2Gi" || len(hardware.Disks) != 1 || hardware.Disks[0].Capacity != "64Gi" || len(hardware.Interfaces) != 1 { + if hardware.BootMode != "BIOS" || hardware.CPU.Architecture != "amd64" || hardware.CPU.Cores != 2 || hardware.Memory != "2Gi" || len(hardware.Disks) != 1 || hardware.Disks[0].Capacity != "64Gi" || len(hardware.Interfaces) != 1 { t.Fatalf("hardware = %+v", hardware) } if evidence.SerialNumber != "SERIAL-001" || evidence.BurnIn.Result != ops.BurnInPassed || len(evidence.Firmware) != 1 || evidence.Firmware[0].Version != "1.0.0" { diff --git a/internal/site/redfishwork/kinds.go b/internal/site/redfishwork/kinds.go index 16be7ad2..9bd9bb61 100644 --- a/internal/site/redfishwork/kinds.go +++ b/internal/site/redfishwork/kinds.go @@ -152,6 +152,11 @@ func (k Installation) Check(ctx context.Context, work *site.Work) *custody.Refus 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"} + } method, ok := k.method(spec.Delivery.Method) if !ok { return &custody.Refusal{Reason: custody.ReasonDeliveryInputs, Message: "this site runs no worker for the delivery method"} diff --git a/internal/site/redfishwork/kinds_test.go b/internal/site/redfishwork/kinds_test.go index dff7a00d..42266060 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" "go.datum.net/fleet/internal/site/burnin" @@ -168,7 +169,7 @@ func (l *lab) ServeHTTP(w http.ResponseWriter, r *http.Request) { "Processors": map[string]string{"@odata.id": path + "/Processors"}, "Memory": map[string]string{"@odata.id": path + "/Memory"}, "SimpleStorage": map[string]string{"@odata.id": path + "/SimpleStorage"}, "EthernetInterfaces": map[string]string{"@odata.id": path + "/EthernetInterfaces"}, "Storage": l.storageLink(path), - "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, "/")] @@ -363,7 +364,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"}, Delivery: ops.DeliveryInput{Method: ops.DeliveryNetworkBoot}} + return ops.DeviceInstallationSpec{Image: ops.ImageInput{Name: "debian-12", Digest: "sha256:" + strings.Repeat("a", 64), FirmwareModes: []string{"BIOS"}}, BootInterface: "primary", TargetDisks: []string{"disk-0"}, Delivery: ops.DeliveryInput{Method: ops.DeliveryNetworkBoot}} +} + +// 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/redfishwork/media_test.go b/internal/site/redfishwork/media_test.go index 3c3716e4..cb3a8ff9 100644 --- a/internal/site/redfishwork/media_test.go +++ b/internal/site/redfishwork/media_test.go @@ -221,7 +221,7 @@ func (b *mediaBMC) 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": system}}}, system: map[string]any{"@odata.id": system, "Id": "A", "UUID": uuid, "PowerState": b.power, "VirtualMedia": map[string]string{"@odata.id": collection}, - "Boot": map[string]any{"BootSourceOverrideEnabled": b.enabled, "BootSourceOverrideTarget": b.target, "BootSourceOverrideTarget@Redfish.AllowableValues": []string{"Pxe", "Hdd", "Cd"}}, + "Boot": map[string]any{"BootSourceOverrideEnabled": b.enabled, "BootSourceOverrideMode": "Legacy", "BootSourceOverrideTarget": b.target, "BootSourceOverrideTarget@Redfish.AllowableValues": []string{"Pxe", "Hdd", "Cd"}}, "Actions": map[string]any{"#ComputerSystem.Reset": map[string]any{"target": system + "/Actions/ComputerSystem.Reset", "ResetType@Redfish.AllowableValues": []string{"On", "ForceOff"}}}}, collection: map[string]any{"Members": []any{map[string]string{"@odata.id": collection + "/CD1"}, map[string]string{"@odata.id": collection + "/CD2"}}}, } @@ -329,7 +329,7 @@ func artifacts(t *testing.T) (string, ops.ImageInput) { t.Fatal(err) } name, value, _ := strings.Cut(identity, "@") - return dir, ops.ImageInput{Name: name, Digest: value} + return dir, ops.ImageInput{Name: name, Digest: value, FirmwareModes: []string{"BIOS"}} } type mediaEnv struct { diff --git a/internal/site/vmwork/kinds.go b/internal/site/vmwork/kinds.go index bcf77e1c..645cc6cc 100644 --- a/internal/site/vmwork/kinds.go +++ b/internal/site/vmwork/kinds.go @@ -168,6 +168,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 e8dffb34..3ecc514a 100644 --- a/internal/site/vmwork/kinds_test.go +++ b/internal/site/vmwork/kinds_test.go @@ -211,13 +211,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"}, Delivery: ops.DeliveryInput{Method: ops.DeliveryNetworkBoot}} + return ops.DeviceInstallationSpec{OperationEnvelope: envelope(), Image: ops.ImageInput{Name: name, Digest: digest, FirmwareModes: []string{"BIOS"}}, BootInterface: "primary", TargetDisks: []string{"disk-0"}, Delivery: ops.DeliveryInput{Method: ops.DeliveryNetworkBoot}} } func wipeSpec() ops.DeviceWipeSpec { return ops.DeviceWipeSpec{OperationEnvelope: envelope(), Step: 1, Policy: ops.CleaningPolicyReference{Name: "tenant-reuse-v1", Generation: 1, Digest: "sha256:" + key}, TargetDisks: []string{"disk-0"}, BootInterface: "primary"} } +// 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 894ea5bc..50b95763 100644 --- a/internal/standalone/runner.go +++ b/internal/standalone/runner.go @@ -22,6 +22,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/controller" "go.datum.net/fleet/internal/custody" "go.datum.net/fleet/internal/manager" @@ -47,6 +48,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 } @@ -66,7 +70,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, } } @@ -136,6 +141,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 @@ -190,7 +199,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 { @@ -208,7 +227,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."), @@ -319,6 +338,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