From 7935d8be9d57f25e5c2bd09f1154f445074cae48 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Fri, 27 Nov 2026 11:56:15 -0600 Subject: [PATCH 01/35] feat(custody): Record each install's boot method An installation records how its image reaches the server, NetworkBoot or VirtualMedia, before admission, and the input digest pins it. Virtual media also records the central media service, the address mode and two phase windows, 15 and 30 minutes by default, whose sum is the deadline. Sites declare their methods in order of preference. The Metal provider selects the held method when it settles a hold, or else the first offered method the server is qualified for. Admission checks the choice again: a method no serving site offers, one the server is not qualified for, inputs that are not the site's offer, and an installer download not pinned by digest are refused. A settling installation must use the held method, still from the site's offer. While no site offers it, the hold shows HeldMethodNotOffered to staff. Qualification is a staff-set Device annotation until commissioning exists. Workers that deliver only network boot refuse anything else. Co-Authored-By: Claude Opus 5.5 --- cmd/fleet-manager/synthetic.go | 3 +- cmd/fleet-standalone-smoke/main.go | 4 +- .../crds/fleet.datumapis.com.yaml | 58 +++ docs/development/device-custody.md | 22 ++ internal/allocation/allocator.go | 42 ++- internal/allocation/harness_test.go | 3 +- internal/api/operations/v1alpha1/types.go | 79 ++++ internal/custody/admission_test.go | 8 +- internal/custody/coordinator.go | 10 +- internal/custody/delivery.go | 316 ++++++++++++++++ internal/custody/delivery_test.go | 339 ++++++++++++++++++ internal/custody/harness_test.go | 14 +- internal/custody/kinds.go | 18 +- internal/custody/registry.go | 10 +- internal/delivery/delivery.go | 7 + internal/multiplane/scenarios.go | 2 +- internal/site/config.go | 14 +- internal/site/simwork/kinds.go | 3 + internal/site/vmwork/kinds.go | 3 + internal/site/vmwork/kinds_test.go | 2 +- internal/staging/harness_test.go | 3 +- 21 files changed, 936 insertions(+), 24 deletions(-) create mode 100644 internal/custody/delivery.go create mode 100644 internal/custody/delivery_test.go diff --git a/cmd/fleet-manager/synthetic.go b/cmd/fleet-manager/synthetic.go index 8ca09493..dfb89a7e 100644 --- a/cmd/fleet-manager/synthetic.go +++ b/cmd/fleet-manager/synthetic.go @@ -79,7 +79,7 @@ func syntheticCustody(ctx context.Context, scheme *runtime.Scheme, providerConfi return nil, nil, nil, err } namespace := flags.syntheticDeviceNamespace - sites := &delivery.Sites{Sites: map[string]delivery.Site{syntheticSite: remote}, Devices: map[string][]string{}} + sites := &delivery.Sites{Sites: map[string]delivery.Site{syntheticSite: remote}, Devices: map[string][]string{}, Methods: map[string][]custody.OfferedMethod{syntheticSite: custody.NetworkBootOnly}} for device := range enrollment { deviceNamespace, name, _ := strings.Cut(device, "/") if deviceNamespace != namespace { @@ -109,6 +109,7 @@ func syntheticCustody(ctx context.Context, scheme *runtime.Scheme, providerConfi Capacity: &capacity.Projector{Reader: provider, Namespace: namespace, Cleaning: cleaning}, // The synthetic site enrolls one boot NIC and one disk per Device. BootInterface: "primary", TargetDisks: []string{"disk-0"}, + DeliveryMethods: custody.NetworkBootOnly, } // Synthetic staging has no BMC discovery. The manager writes fixture // discovery for the synthetic site's Devices instead. diff --git a/cmd/fleet-standalone-smoke/main.go b/cmd/fleet-standalone-smoke/main.go index de84a7f3..d3340ce7 100644 --- a/cmd/fleet-standalone-smoke/main.go +++ b/cmd/fleet-standalone-smoke/main.go @@ -91,6 +91,8 @@ func main() { Capacity: offers, // The fixture Device's boot NIC and the simulator's one enrolled disk. BootInterface: "primary", TargetDisks: []string{"disk-0"}, + // The simulator site offers only network boot. + DeliveryMethods: custody.NetworkBootOnly, } runner := standalone.Runner{Client: provider, Allocator: allocator, Options: options} if phase == standalone.PhaseCommission { @@ -119,7 +121,7 @@ func coordinate(ctx context.Context, config *rest.Config, registry *custody.Regi if err != nil { return err } - sites := &delivery.Sites{Sites: map[string]delivery.Site{siteName: remote}, Devices: map[string][]string{}} + sites := &delivery.Sites{Sites: map[string]delivery.Site{siteName: remote}, Devices: map[string][]string{}, Methods: map[string][]custody.OfferedMethod{siteName: custody.NetworkBootOnly}} for _, device := range devices { if device = strings.TrimSpace(device); device != "" { sites.Devices[device] = []string{siteName} diff --git a/config/components/device-operations/crds/fleet.datumapis.com.yaml b/config/components/device-operations/crds/fleet.datumapis.com.yaml index 3947d9b6..852b8ce6 100644 --- a/config/components/device-operations/crds/fleet.datumapis.com.yaml +++ b/config/components/device-operations/crds/fleet.datumapis.com.yaml @@ -322,6 +322,18 @@ spec: retryName: type: string maxLength: 253 + waiting: + type: object + properties: + reason: + type: string + maxLength: 128 + message: + type: string + maxLength: 512 + required: + - reason + - message required: - kind - name @@ -486,6 +498,23 @@ spec: digest: type: string pattern: ^sha256:[0-9a-f]{64}$ + downloads: + type: array + maxItems: 8 + items: + type: object + properties: + name: + type: string + minLength: 1 + maxLength: 63 + reference: + type: string + minLength: 1 + maxLength: 512 + required: + - name + - reference required: - name - digest @@ -547,6 +576,34 @@ spec: required: - addressClaim - address + delivery: + type: object + properties: + method: + type: string + enum: + - NetworkBoot + - VirtualMedia + addresses: + type: string + enum: + - DataNetwork + mediaService: + type: string + maxLength: 64 + fetchWindow: + type: string + maxLength: 32 + reportWindow: + type: string + maxLength: 32 + required: + - method + x-kubernetes-validations: + - rule: self.method != 'NetworkBoot' || (!has(self.addresses) && !has(self.mediaService) && !has(self.fetchWindow) && !has(self.reportWindow)) + message: network boot records no virtual media inputs + - rule: self.method != 'VirtualMedia' || (has(self.addresses) && has(self.mediaService) && has(self.fetchWindow) && has(self.reportWindow)) + message: virtual media records the site's address mode, media service and phase windows required: - creator - deviceRef @@ -554,6 +611,7 @@ spec: - image - bootInterface - targetDisks + - delivery x-kubernetes-validations: - rule: self == oldSelf message: an operation spec is immutable after create diff --git a/docs/development/device-custody.md b/docs/development/device-custody.md index 92af7cac..40a11121 100644 --- a/docs/development/device-custody.md +++ b/docs/development/device-custody.md @@ -314,6 +314,28 @@ An operation's creator is the identity a `SelfSubjectReview` reports. Fixture discovery writes Device status the way BMC discovery would. Who writes it depends on the mode; see [Modes](#modes). +### Boot delivery methods (prototype) + +A prototype of [#227](https://github.com/datum-cloud/fleet/pull/227). The +operations guide describes how it runs in the [Redfish lab](../operations/redfish-lab.md#virtual-media-suite-prototype). + +- **Every installation records its method.** `spec.delivery` names + `NetworkBoot` or `VirtualMedia`, and for virtual media the central media + service, the address mode and the fetch and report windows. A virtual + media installation's deadline is the sum of its windows. +- **Sites declare their methods.** `custody.Sites` gains `DeliveryMethods`, + the site's methods in its order of preference. Admission sees the methods + every serving site offers. The Metal provider selects from the same + declaration. +- **Admission checks the method** under the custody update: offered, + qualified, consistent with the other inputs, and every installer download + pinned by digest. The admission snapshot records the method, so a + recovery hold records it too. A settling installation must use the held + method, and a wipe cannot settle a virtual media hold. +- **Workers dispatch on the method.** The Redfish install worker hands the + install to the method's own steps; network boot is unchanged. The local + VM and simulator workers refuse any method but network boot. + ### Federation `internal/coordination` carries one site assignment per `MachineAllocationHandoff` diff --git a/internal/allocation/allocator.go b/internal/allocation/allocator.go index 304bd612..bcc449ef 100644 --- a/internal/allocation/allocator.go +++ b/internal/allocation/allocator.go @@ -166,6 +166,33 @@ type Allocator struct { // through them, by claim kind, until no operation names their kind. // IPAM's claimer always takes part as the default. PreviousBootAddresses []bootaddress.Source + // DeliveryMethods is the site's declared boot delivery methods, in its + // order of preference. It is the same declaration the coordinator + // admits against. Each installation records the method selected from + // it. + DeliveryMethods []custody.OfferedMethod +} + +// ErrNoDeliveryMethod means the site offers no delivery method the server +// is qualified for, so nothing can install it. +var ErrNoDeliveryMethod = errors.New("allocation: the site offers no delivery method the server is qualified for") + +// selectDelivery reads the Device and its custody and selects the method an +// installation records. +func (a *Allocator) selectDelivery(ctx context.Context, allocation *fleetv1.MachineAllocation) (ops.DeliveryInput, error) { + key := client.ObjectKey{Namespace: a.Namespace, Name: allocation.Spec.DeviceRef.Name} + device, state := &inventory.Device{}, &ops.DeviceCustody{} + if err := a.Provider.Get(ctx, key, device); err != nil { + return ops.DeliveryInput{}, err + } + if err := a.Provider.Get(ctx, key, state); err != nil { + return ops.DeliveryInput{}, err + } + input, ok := custody.SelectMethod(a.DeliveryMethods, custody.QualifiedMethods(device), state) + if !ok { + return ops.DeliveryInput{}, ErrNoDeliveryMethod + } + return input, nil } // Get returns the Machine's allocation, or nil. @@ -508,20 +535,27 @@ func (a *Allocator) Install(ctx context.Context, allocation *fleetv1.MachineAllo TargetDisks: slices.Clone(allocation.Spec.TargetDisks), }, } - // An existing installation keeps the boot address it was created with, - // which may already be released. + // An existing installation keeps the delivery and boot address it was + // created with; the address may already be released. existing := &ops.DeviceInstallation{} if err := a.Provider.Get(ctx, client.ObjectKeyFromObject(operation), existing); err == nil { operation.Spec.BootNetwork = existing.Spec.BootNetwork + operation.Spec.Delivery = existing.Spec.Delivery return operation, matchExisting(operation, existing) } else if !apierrors.IsNotFound(err) { return nil, err } - network, err := a.bootNetwork(ctx, a.installClaims(), allocation, "DeviceInstallation", operation.Name) + delivery, err := a.selectDelivery(ctx, allocation) if err != nil { return nil, err } - operation.Spec.BootNetwork = network + operation.Spec.Delivery = delivery + // Only network boot needs a provisioning address. + if delivery.Method == ops.DeliveryNetworkBoot { + if operation.Spec.BootNetwork, err = a.bootNetwork(ctx, a.installClaims(), allocation, "DeviceInstallation", operation.Name); err != nil { + return nil, err + } + } return operation, a.createOnce(ctx, a.Provider, operation, &ops.DeviceInstallation{}) } diff --git a/internal/allocation/harness_test.go b/internal/allocation/harness_test.go index f560d347..c349242f 100644 --- a/internal/allocation/harness_test.go +++ b/internal/allocation/harness_test.go @@ -130,7 +130,7 @@ func startEnvWith(t *testing.T, crds ...*apiextensionsv1.CustomResourceDefinitio if err != nil { t.Fatal(err) } - sites := &delivery.Sites{Sites: map[string]delivery.Site{siteName: remote}, Devices: map[string][]string{}} + sites := &delivery.Sites{Sites: map[string]delivery.Site{siteName: remote}, Devices: map[string][]string{}, Methods: map[string][]custody.OfferedMethod{siteName: custody.NetworkBootOnly}} coordinator := &custody.Coordinator{Client: admin, Registry: registry, Sites: sites, Config: custody.Config{Namespace: namespace, Principals: custody.Principals{ custody.CreatorMetalProvider: {{Username: providerUser}}, custody.CreatorReleaseController: {{Username: releaseUser}}, }}} @@ -144,6 +144,7 @@ func startEnvWith(t *testing.T, crds ...*apiextensionsv1.CustomResourceDefinitio Cleaning: func(string) (string, error) { return policyDigest, nil }, Capacity: e.projector, BootInterface: "primary", TargetDisks: []string{"disk-0"}, + DeliveryMethods: custody.NetworkBootOnly, } // One qualified plan covers every fixture server: one person writes it // and another approves it. diff --git a/internal/api/operations/v1alpha1/types.go b/internal/api/operations/v1alpha1/types.go index 62ebff54..ce177afd 100644 --- a/internal/api/operations/v1alpha1/types.go +++ b/internal/api/operations/v1alpha1/types.go @@ -13,6 +13,7 @@ package v1alpha1 import ( "encoding/json" + "time" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" @@ -185,6 +186,16 @@ type RecoveryHold struct { // operation itself ends unknown, so its retries keep the original // operation's name and count on. RetryName string `json:"retryName,omitempty"` + // Waiting, when set, says why no operation can settle the hold yet, so + // staff see it: the held installation's delivery method is one no site + // serving the Device offers any more. The coordinator sets and clears it. + Waiting *HoldWaiting `json:"waiting,omitempty"` +} + +// HoldWaiting is why a recovery hold cannot be settled yet. +type HoldWaiting struct { + Reason string `json:"reason"` + Message string `json:"message"` } // RejectedResults records site results the coordinator refused because their @@ -308,9 +319,66 @@ type DeviceInstallationSpec struct { TargetDisks []string `json:"targetDisks"` // BootNetwork is the provisioning address for the network boot. It is // required at a site whose DHCP is synchronized and refused elsewhere. + // A virtual media installation never carries one. BootNetwork *BootNetworkInput `json:"bootNetwork,omitempty"` + // Delivery is how the image reaches the server. The requester selects + // it when it creates the operation, and it never changes. + Delivery DeliveryInput `json:"delivery"` } +// DeliveryMethod is how an operation's boot image reaches the server. +type DeliveryMethod string + +const ( + // DeliveryNetworkBoot answers the boot NIC over DHCP and boots it over + // the network, only while the operation runs. + DeliveryNetworkBoot DeliveryMethod = "NetworkBoot" + // DeliveryVirtualMedia has the BMC mount boot media from the site's + // media service and boot from it once. + DeliveryVirtualMedia DeliveryMethod = "VirtualMedia" +) + +// DeliveryMethods is every method, in no preference order. +var DeliveryMethods = []DeliveryMethod{DeliveryNetworkBoot, DeliveryVirtualMedia} + +// AddressMode is how the installed OS gets its addresses at first boot +// under virtual media. Network boot records none. +type AddressMode string + +const ( + // AddressesDataNetwork means the network owner's DHCP on the + // customer's network serves the Machine's addresses. The config medium + // carries none. + AddressesDataNetwork AddressMode = "DataNetwork" +) + +// DeliveryInput is the delivery method an operation was admitted with and +// the method's own inputs. Each is copied from the site's declaration when +// the method is selected, so the worker never reads a mutable source after +// admission. +type DeliveryInput struct { + Method DeliveryMethod `json:"method"` + // Addresses is the site's address mode for virtual media. + Addresses AddressMode `json:"addresses,omitempty"` + // MediaService is the central media service for virtual media, as + // https://IPv4:port: BMCs fetch media from it and the installed OS + // posts its install report to it. + MediaService string `json:"mediaService,omitempty"` + // FetchWindow bounds how long the BMC may fetch the media, and + // ReportWindow how long after that the installed OS has to post its + // first-boot report. The operation's deadline is their sum. + FetchWindow *metav1.Duration `json:"fetchWindow,omitempty"` + ReportWindow *metav1.Duration `json:"reportWindow,omitempty"` +} + +// Default virtual media phases: 15 minutes to fetch the media, then 30 +// minutes for the install and the first-boot report. A site may set its +// own. +const ( + DefaultFetchWindow = 15 * time.Minute + DefaultReportWindow = 30 * time.Minute +) + // BootNetworkInput is the provisioning address the boot address source // assigned to one operation. The site answers DHCP for the boot NIC with // Address only while the operation runs. The requester claims the address @@ -329,6 +397,17 @@ type BootNetworkInput struct { type ImageInput struct { Name string `json:"name"` Digest string `json:"digest"` + // 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. + Downloads []DownloadInput `json:"downloads,omitempty"` +} + +// DownloadInput is one artifact an installer downloads, by a reference +// that pins its digest, such as registry.example/installer@sha256:. +type DownloadInput struct { + Name string `json:"name"` + Reference string `json:"reference"` } // SealedInput is an opaque reference into the sealed store and the digest of diff --git a/internal/custody/admission_test.go b/internal/custody/admission_test.go index aedb3016..c2f6af04 100644 --- a/internal/custody/admission_test.go +++ b/internal/custody/admission_test.go @@ -270,12 +270,12 @@ func TestAdmissionPreconditions(t *testing.T) { fence := e.custody(device.Name).Spec.Fence operation := &ops.DeviceInstallation{ObjectMeta: metav1.ObjectMeta{Name: InstallationName("alloc-boot", "request-1"), Namespace: "default", Labels: map[string]string{ops.LabelInstallationUID: "request-1"}}, Spec: ops.DeviceInstallationSpec{ OperationEnvelope: envelope(device, providerUser, allocated("alloc-boot")), - Image: ops.ImageInput{Name: "debian-12", Digest: imageDigest}, Bootstrap: &ops.SealedInput{Ref: "sealed-example", Digest: imageDigest}, BootInterface: "primary", TargetDisks: []string{"disk-0"}, + Image: ops.ImageInput{Name: "debian-12", Digest: imageDigest}, Bootstrap: &ops.SealedInput{Ref: "sealed-example", Digest: imageDigest}, BootInterface: "primary", TargetDisks: []string{"disk-0"}, Delivery: ops.DeliveryInput{Method: ops.DeliveryNetworkBoot}, }} e.create(operation) missing := &ops.DeviceInstallation{ObjectMeta: metav1.ObjectMeta{Name: InstallationName("alloc-boot", "request-2"), Namespace: "default", Labels: map[string]string{ops.LabelInstallationUID: "request-2"}}, Spec: ops.DeviceInstallationSpec{ OperationEnvelope: envelope(device, providerUser, allocated("alloc-boot")), - Image: ops.ImageInput{Name: "debian-12", Digest: imageDigest}, BootInterface: "absent", TargetDisks: []string{"disk-0"}, + Image: ops.ImageInput{Name: "debian-12", Digest: imageDigest}, BootInterface: "absent", TargetDisks: []string{"disk-0"}, Delivery: ops.DeliveryInput{Method: ops.DeliveryNetworkBoot}, }} e.create(missing) e.settle(device.Name) @@ -301,7 +301,7 @@ func TestAdmissionPreconditions(t *testing.T) { withAddress := func(request string, input *ops.BootNetworkInput) *ops.DeviceInstallation { operation := &ops.DeviceInstallation{ObjectMeta: metav1.ObjectMeta{Name: name(request), Namespace: "default", Labels: map[string]string{ops.LabelInstallationUID: request}}, Spec: ops.DeviceInstallationSpec{ OperationEnvelope: envelope(device, providerUser, allocated("alloc-net")), - Image: ops.ImageInput{Name: "debian-12", Digest: imageDigest}, BootInterface: "primary", TargetDisks: []string{"disk-0"}, BootNetwork: input, + Image: ops.ImageInput{Name: "debian-12", Digest: imageDigest}, BootInterface: "primary", TargetDisks: []string{"disk-0"}, Delivery: ops.DeliveryInput{Method: ops.DeliveryNetworkBoot}, BootNetwork: input, }} e.create(operation) return operation @@ -382,7 +382,7 @@ func TestAdmissionPreconditions(t *testing.T) { e.ipClaim(bootaddress.ClaimName(name), name, "DeviceInstallation", "Bound", "198.51.100.20") operation := &ops.DeviceInstallation{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: "default", Labels: map[string]string{ops.LabelInstallationUID: "request-1"}}, Spec: ops.DeviceInstallationSpec{ OperationEnvelope: envelope(device, providerUser, allocated("alloc-kind")), - Image: ops.ImageInput{Name: "debian-12", Digest: imageDigest}, BootInterface: "primary", TargetDisks: []string{"disk-0"}, + Image: ops.ImageInput{Name: "debian-12", Digest: imageDigest}, BootInterface: "primary", TargetDisks: []string{"disk-0"}, Delivery: ops.DeliveryInput{Method: ops.DeliveryNetworkBoot}, BootNetwork: &ops.BootNetworkInput{AddressClaim: fleetv1.TypedReference{APIGroup: "networking.example.com", Kind: "AddressLease", Name: bootaddress.ClaimName(name)}, Address: "198.51.100.20"}, }} e.create(operation) diff --git a/internal/custody/coordinator.go b/internal/custody/coordinator.go index 4753759f..4e4e69bc 100644 --- a/internal/custody/coordinator.go +++ b/internal/custody/coordinator.go @@ -29,6 +29,9 @@ type Sites interface { // Fence returns the site's fence report for the Device, and false if // the site has not reported one. Fence(ctx context.Context, site string, device *inventory.Device) (SiteFence, bool, error) + // DeliveryMethods returns the boot delivery methods the site declares, + // in its order of preference. A site that declares none offers none. + DeliveryMethods(site string) []OfferedMethod } // SiteFence is one site's fence report for one Device. @@ -180,6 +183,7 @@ func (c *Coordinator) Reconcile(ctx context.Context, name string) (Outcome, erro return c.progressActive(ctx, custody, device) }, func() (Outcome, error) { return c.settleHolder(ctx, custody, device) }, + func() (Outcome, error) { return c.holdWaiting(ctx, custody, device) }, func() (Outcome, error) { return c.admit(ctx, custody, device) }, } for _, step := range steps { @@ -806,7 +810,7 @@ func (c *Coordinator) decide(ctx context.Context, kind *Kind, operation ops.Oper } return fail(ReasonOperationInProgress, "another operation is running, and staff operations never wait") } - admission := &Admission{Operation: operation, Custody: custody.DeepCopy(), Device: device, Row: row, Registry: c.Registry, Reader: c.Client, Now: now, DiscoveryInterval: cfg.DiscoveryInterval} + admission := &Admission{Operation: operation, Custody: custody.DeepCopy(), Device: device, Row: row, Registry: c.Registry, Reader: c.Client, Now: now, DiscoveryInterval: cfg.DiscoveryInterval, Offered: offered(c.Sites, device)} // Rule 7, the kind's own checks, runs before the shared identity and // key checks, so a kind's more specific reason, such as a system UUID // that is not recorded, is the one reported. @@ -988,7 +992,9 @@ func (c *Coordinator) admitOne(ctx context.Context, custody *ops.DeviceCustody, spec.Fence = max(spec.Fence, seen) + 1 deadline := kind.Deadline if kind.DeadlineFor != nil { - deadline = kind.DeadlineFor(operation) + if d := kind.DeadlineFor(operation); d > 0 { + deadline = d + } } active := &ops.ActiveOperation{ OperationReference: ops.OperationReference{Kind: kind.GVK.Kind, Name: operation.GetName()}, diff --git a/internal/custody/delivery.go b/internal/custody/delivery.go new file mode 100644 index 00000000..23433748 --- /dev/null +++ b/internal/custody/delivery.go @@ -0,0 +1,316 @@ +package custody + +import ( + "context" + "fmt" + "regexp" + "slices" + "strings" + "time" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" +) + +// OfferedMethod is one boot delivery method a site offers, with what the +// method needs from the site. +type OfferedMethod struct { + Method ops.DeliveryMethod `json:"method"` + // Addresses is how the installed OS gets its addresses under virtual + // media. Network boot has none. + Addresses ops.AddressMode `json:"addresses,omitempty"` + // MediaService is the central media service virtual media uses at this + // site, as https://IPv4:port. + MediaService string `json:"mediaService,omitempty"` + // FetchWindow and ReportWindow replace the default virtual media + // phases at this site, such as shorter ones in a lab. + FetchWindow *metav1.Duration `json:"fetchWindow,omitempty"` + ReportWindow *metav1.Duration `json:"reportWindow,omitempty"` +} + +// Input is the delivery input an operation records for this offer, with +// the default phases where the site sets none. +func (o OfferedMethod) Input() ops.DeliveryInput { + if o.Method != ops.DeliveryVirtualMedia { + return ops.DeliveryInput{Method: o.Method} + } + fetch, report := &metav1.Duration{Duration: ops.DefaultFetchWindow}, &metav1.Duration{Duration: ops.DefaultReportWindow} + if o.FetchWindow != nil { + fetch = o.FetchWindow + } + if o.ReportWindow != nil { + report = o.ReportWindow + } + return ops.DeliveryInput{Method: o.Method, Addresses: o.Addresses, MediaService: o.MediaService, FetchWindow: fetch, ReportWindow: report} +} + +// DeliveryDeadline is how long an installation may run: the sum of its +// virtual media phases, or zero for the kind's own deadline. +func DeliveryDeadline(delivery ops.DeliveryInput) time.Duration { + if delivery.Method != ops.DeliveryVirtualMedia || delivery.FetchWindow == nil || delivery.ReportWindow == nil { + return 0 + } + return delivery.FetchWindow.Duration + delivery.ReportWindow.Duration +} + +// Reasons for an installation's delivery method. Each is raised at +// admission, before anything is sent. +const ( + // ReasonDeliveryNotOffered means no site serving the Device offers the + // operation's method. + ReasonDeliveryNotOffered = "DeliveryMethodNotOffered" + // ReasonDeliveryUnqualified means the server is not qualified for the + // operation's method. + ReasonDeliveryUnqualified = "DeliveryMethodUnqualified" + // ReasonDeliveryMismatch means the operation settles a hold whose + // operation was prepared with another method. + ReasonDeliveryMismatch = "DeliveryMethodMismatch" + // ReasonDeliveryInputs means the method does not match the operation's + // other inputs, such as a virtual media operation with a boot network. + ReasonDeliveryInputs = "DeliveryInputsMismatch" + // ReasonDownloadUnpinned means the installer would download an + // artifact that the operation does not pin by digest. + ReasonDownloadUnpinned = "InstallDownloadUnpinned" + // ReasonMediaWindowRefused means the central media service refused the + // operation's window before anything reached the BMC. + ReasonMediaWindowRefused = "MediaWindowRefused" + // ReasonMediaTLSUnverified means the server's BMC fetches media without + // verifying the media service's certificate. The fallback that serves + // such a BMC only public media is not implemented. + ReasonMediaTLSUnverified = "VirtualMediaTLSUnverified" +) + +// MediaTLSAnnotation records, as Unverified, a BMC that fetches virtual +// media without verifying the media service's certificate. Like the +// qualification annotation, it stands in for commissioning evidence. +const MediaTLSAnnotation = "fleet.datumapis.com/virtual-media-tls" + +// mediaEndpoint is a media service as https://IPv4:port. +var mediaEndpoint = regexp.MustCompile(`^https://(\d{1,3}\.){3}\d{1,3}:\d{1,5}$`) + +// downloadName is a name the line-oriented config medium can carry. +var downloadName = regexp.MustCompile(`^[a-z0-9][a-z0-9.-]{0,62}$`) + +// maxDownloads bounds what one config medium lists. +const maxDownloads = 8 + +// pinned is a reference that names exactly one digest. +var pinned = regexp.MustCompile(`^[^@\s]+@sha256:[0-9a-f]{64}$`) + +// checkDownloads refuses an installer download that is not pinned by +// digest, so nothing the server installs is chosen after admission. +func checkDownloads(downloads []ops.DownloadInput) *Refusal { + if len(downloads) > maxDownloads { + return refuse(ReasonDeliveryInputs, "an installer lists at most %d downloads", maxDownloads) + } + for _, download := range downloads { + if !downloadName.MatchString(download.Name) { + return refuse(ReasonDeliveryInputs, "an installer download name is not a lowercase name") + } + if !pinned.MatchString(download.Reference) { + return refuse(ReasonDownloadUnpinned, "the installer download %q is not pinned by digest", download.Name) + } + } + return nil +} + +var deliveryReasons = []Reason{{Name: ReasonDeliveryNotOffered, RaisedBy: RaisedByCoordinator}, {Name: ReasonDeliveryUnqualified, RaisedBy: RaisedByCoordinator}, + {Name: ReasonDeliveryMismatch, RaisedBy: RaisedByCoordinator}, {Name: ReasonDeliveryInputs, RaisedBy: RaisedByBoth}, + {Name: ReasonDownloadUnpinned, RaisedBy: RaisedByCoordinator}, {Name: ReasonMediaTLSUnverified, RaisedBy: RaisedByCoordinator}, + {Name: ReasonMediaWindowRefused, RaisedBy: RaisedByWorker}} + +// ExtraDeliveryMethod is the snapshot field that records the method an +// admitted operation prepares. A recovery hold keeps the held operation's +// snapshot, so the hold records the method it must be settled with. +const ExtraDeliveryMethod = "deliveryMethod" + +// QualifiedMethodsAnnotation lists, comma separated, the delivery methods +// the Device's server is qualified for. +// +// It stands in for commissioning, which is not implemented: commissioning +// will record qualification as evidence. A Device without the annotation is +// qualified only for network boot, which discovery's boot target check +// already covers. +const QualifiedMethodsAnnotation = "fleet.datumapis.com/qualified-delivery-methods" + +// QualifiedMethods returns the methods the Device's server is qualified for. +func QualifiedMethods(device *inventory.Device) []ops.DeliveryMethod { + value, ok := device.Annotations[QualifiedMethodsAnnotation] + if !ok { + return []ops.DeliveryMethod{ops.DeliveryNetworkBoot} + } + var out []ops.DeliveryMethod + for _, method := range strings.Split(value, ",") { + if method := ops.DeliveryMethod(strings.TrimSpace(method)); slices.Contains(ops.DeliveryMethods, method) && !slices.Contains(out, method) { + out = append(out, method) + } + } + return out +} + +// HeldMethod returns the delivery method a recovery hold of the kind +// records, and false if custody holds no such hold with a recorded method. +func HeldMethod(custody *ops.DeviceCustody, kind string) (ops.DeliveryMethod, bool) { + hold := custody.Spec.RecoveryHold + if hold == nil || hold.Kind != kind || hold.Snapshot == nil || hold.Snapshot.Extra[ExtraDeliveryMethod] == "" { + return "", false + } + return ops.DeliveryMethod(hold.Snapshot.Extra[ExtraDeliveryMethod]), true +} + +// SelectMethod is the requester's choice for a new operation: the method a +// held installation was prepared with, or else the first method in the +// site's order that the server is qualified for. Admission checks the +// recorded choice again. +func SelectMethod(offered []OfferedMethod, qualified []ops.DeliveryMethod, custody *ops.DeviceCustody) (ops.DeliveryInput, bool) { + held, settling := HeldMethod(custody, "DeviceInstallation") + for _, offer := range offered { + if (settling && offer.Method == held) || (!settling && slices.Contains(qualified, offer.Method)) { + return offer.Input(), true + } + } + // A held method the site no longer offers is still the only one that + // can prove its release, but its media service is no longer declared: + // the hold waits until the site offers the method again. + return ops.DeliveryInput{}, false +} + +// offered returns the methods every site serving the Device offers, in the +// first site's order. A Device no site serves is offered nothing. +func offered(sites Sites, device *inventory.Device) []OfferedMethod { + if sites == nil || device == nil { + return nil + } + serving := sites.Serving(device) + if len(serving) == 0 { + return nil + } + var out []OfferedMethod + for _, offer := range sites.DeliveryMethods(serving[0]) { + everywhere := true + for _, other := range serving[1:] { + // Offers hold window pointers, so they compare by value. + everywhere = everywhere && slices.ContainsFunc(sites.DeliveryMethods(other), func(o OfferedMethod) bool { return equalInput(o.Input(), offer.Input()) }) + } + if everywhere { + out = append(out, offer) + } + } + return out +} + +// checkDelivery is the installation's delivery check. An installation that +// settles a held installation must use the held method, and skips the site +// and qualification checks, which the held operation passed. Any other +// installation must use a method every serving site offers and the server +// is qualified for. +func checkDelivery(admission *Admission, spec *ops.DeviceInstallationSpec) *Refusal { + method := spec.Delivery.Method + switch method { + case ops.DeliveryNetworkBoot: + if spec.Delivery != (ops.DeliveryInput{Method: ops.DeliveryNetworkBoot}) { + return refuse(ReasonDeliveryInputs, "network boot records no virtual media inputs") + } + case ops.DeliveryVirtualMedia: + if spec.BootNetwork != nil { + return refuse(ReasonDeliveryInputs, "a virtual media installation carries no boot network") + } + if spec.Delivery.Addresses != ops.AddressesDataNetwork { + return refuse(ReasonDeliveryInputs, "virtual media supports only the DataNetwork address mode") + } + if !mediaEndpoint.MatchString(spec.Delivery.MediaService) || DeliveryDeadline(spec.Delivery) <= 0 || spec.Delivery.FetchWindow.Duration <= 0 || spec.Delivery.ReportWindow.Duration <= 0 { + return refuse(ReasonDeliveryInputs, "virtual media records its media service and both phase windows") + } + default: + return refuse(ReasonDeliveryInputs, "the delivery method %q is not known", method) + } + if refusal := checkDownloads(spec.Image.Downloads); refusal != nil { + return refusal + } + if method == ops.DeliveryVirtualMedia && admission.Device.Annotations[MediaTLSAnnotation] == "Unverified" { + return refuse(ReasonMediaTLSUnverified, "the server's BMC does not verify the media service's certificate, and the unverified fallback is not implemented") + } + held, settling := HeldMethod(admission.Custody, "DeviceInstallation") + if settling && held != method { + return refuse(ReasonDeliveryMismatch, "the held installation was prepared with %s, so only %s can prove its release", held, held) + } + // A settling installation still takes its inputs from the site's offer; + // only the qualification check, which the held operation passed, is + // skipped. + index := slices.IndexFunc(admission.Offered, func(offer OfferedMethod) bool { return offer.Method == method }) + if index < 0 { + return refuse(ReasonDeliveryNotOffered, "no site serving the Device offers %s", method) + } + if want := admission.Offered[index].Input(); !equalInput(want, spec.Delivery) { + return refuse(ReasonDeliveryInputs, "the site's inputs for %s are not the recorded ones", method) + } + if !settling && !slices.Contains(QualifiedMethods(admission.Device), method) { + return refuse(ReasonDeliveryUnqualified, "the server is not qualified for %s", method) + } + return nil +} + +// checkWipeDelivery refuses a wipe that would settle an installation hold +// prepared with a method other than network boot, the only method a wipe +// uses: it could not prove that method's release. +func checkWipeDelivery(admission *Admission) *Refusal { + if held, ok := HeldMethod(admission.Custody, "DeviceInstallation"); ok && held != ops.DeliveryNetworkBoot { + return refuse(ReasonDeliveryMismatch, "the held installation was prepared with %s, which a wipe cannot release", held) + } + return nil +} + +// NetworkBootOnly is the declaration of a site that offers only network +// boot. +var NetworkBootOnly = []OfferedMethod{{Method: ops.DeliveryNetworkBoot}} + +// OnlyNetworkBoot refuses an installation whose method is not network boot. +// Every site worker that delivers only network boot calls it. +func OnlyNetworkBoot(delivery ops.DeliveryInput) *Refusal { + if delivery != (ops.DeliveryInput{Method: ops.DeliveryNetworkBoot}) { + return refuse(ReasonDeliveryInputs, "this site's workers deliver only network boot") + } + return nil +} + +func equalInput(a, b ops.DeliveryInput) bool { + duration := func(d *metav1.Duration) time.Duration { + if d == nil { + return -1 + } + return d.Duration + } + return a.Method == b.Method && a.Addresses == b.Addresses && a.MediaService == b.MediaService && + duration(a.FetchWindow) == duration(b.FetchWindow) && duration(a.ReportWindow) == duration(b.ReportWindow) +} + +// ReasonHoldMethodNotOffered says a hold waits until a site serving the +// Device offers the held installation's delivery method again: only that +// method can prove its release. +const ReasonHoldMethodNotOffered = "HeldMethodNotOffered" + +// holdWaiting records on the recovery hold, for staff, whether it waits for +// a site to offer the held method again, and clears it once one does. +func (c *Coordinator) holdWaiting(ctx context.Context, custody *ops.DeviceCustody, device *inventory.Device) (Outcome, error) { + hold := custody.Spec.RecoveryHold + if hold == nil || custody.Spec.ActiveOperation != nil { + return Outcome{}, nil + } + var want *ops.HoldWaiting + if method, held := HeldMethod(custody, "DeviceInstallation"); held { + if !slices.ContainsFunc(offered(c.Sites, device), func(offer OfferedMethod) bool { return offer.Method == method }) { + want = &ops.HoldWaiting{Reason: ReasonHoldMethodNotOffered, Message: fmt.Sprintf("waits for a site serving the Device to offer %s again", method)} + } + } + if equalWaiting(hold.Waiting, want) { + return Outcome{}, nil + } + hold.Waiting = want + return c.writeCustody(ctx, custody) +} + +func equalWaiting(a, b *ops.HoldWaiting) bool { + return a == nil && b == nil || a != nil && b != nil && *a == *b +} diff --git a/internal/custody/delivery_test.go b/internal/custody/delivery_test.go new file mode 100644 index 00000000..a01c12fc --- /dev/null +++ b/internal/custody/delivery_test.go @@ -0,0 +1,339 @@ +package custody + +import ( + "context" + "fmt" + "slices" + "strings" + "testing" + "time" + + 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" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/controller-runtime/pkg/client" +) + +const mediaService = "https://192.0.2.10:8443" + +var virtualMedia = OfferedMethod{Method: ops.DeliveryVirtualMedia, Addresses: ops.AddressesDataNetwork, MediaService: mediaService}.Input() + +func TestSelectMethod(t *testing.T) { + both := []OfferedMethod{{Method: ops.DeliveryNetworkBoot}, {Method: ops.DeliveryVirtualMedia, Addresses: ops.AddressesDataNetwork, MediaService: mediaService}} + free := &ops.DeviceCustody{} + held := func(method ops.DeliveryMethod) *ops.DeviceCustody { + return &ops.DeviceCustody{Spec: ops.DeviceCustodySpec{RecoveryHold: &ops.RecoveryHold{OperationReference: ops.OperationReference{Kind: "DeviceInstallation"}, + Snapshot: &ops.DeviceSnapshot{Extra: map[string]string{ExtraDeliveryMethod: string(method)}}}}} + } + for _, tc := range []struct { + name string + offered []OfferedMethod + qualified []ops.DeliveryMethod + custody *ops.DeviceCustody + want ops.DeliveryInput + ok bool + }{ + {"the site's first qualified method", both, []ops.DeliveryMethod{ops.DeliveryNetworkBoot, ops.DeliveryVirtualMedia}, free, ops.DeliveryInput{Method: ops.DeliveryNetworkBoot}, true}, + {"the first method the server qualified for", both, []ops.DeliveryMethod{ops.DeliveryVirtualMedia}, free, virtualMedia, true}, + {"nothing the server qualified for", NetworkBootOnly, []ops.DeliveryMethod{ops.DeliveryVirtualMedia}, free, ops.DeliveryInput{}, false}, + {"a settling install keeps the held method", both, []ops.DeliveryMethod{ops.DeliveryNetworkBoot}, held(ops.DeliveryVirtualMedia), virtualMedia, true}, + {"and waits while the site does not offer it", NetworkBootOnly, []ops.DeliveryMethod{ops.DeliveryNetworkBoot}, held(ops.DeliveryVirtualMedia), ops.DeliveryInput{}, false}, + } { + t.Run(tc.name, func(t *testing.T) { + got, ok := SelectMethod(tc.offered, tc.qualified, tc.custody) + if !equalInput(got, tc.want) || ok != tc.ok { + t.Fatalf("SelectMethod = %+v, %v; want %+v, %v", got, ok, tc.want, tc.ok) + } + }) + } +} + +func TestQualifiedMethods(t *testing.T) { + device := &inventory.Device{} + if got := QualifiedMethods(device); len(got) != 1 || got[0] != ops.DeliveryNetworkBoot { + t.Fatalf("no qualification record = %v", got) + } + device.Annotations = map[string]string{QualifiedMethodsAnnotation: "VirtualMedia, Unknown,VirtualMedia"} + if got := QualifiedMethods(device); len(got) != 1 || got[0] != ops.DeliveryVirtualMedia { + t.Fatalf("qualified = %v", got) + } +} + +// TestDeliveryMethodAdmission covers the delivery checks admission runs +// under the custody update. Each refusal sends nothing and leaves custody's +// fence where it was. +func TestDeliveryMethodAdmission(t *testing.T) { + e := startEnv(t) + n := 900 + held := func(e *env, qualified string) *inventory.Device { + e.t.Helper() + n++ + device := e.device(fmt.Sprintf("server-example-%03d", n), uid(n), fmt.Sprintf("%064x", n)) + if qualified != "" { + device.Annotations = map[string]string{QualifiedMethodsAnnotation: qualified} + if err := e.admin.Update(e.ctx, device); err != nil { + e.t.Fatal(err) + } + e.discover(device, fmt.Sprintf("%064x", n), e.clock.Now()) + } + e.allocation(device, "alloc-d-"+device.Name, "Active") + e.sites.report(device.Name, 0) + e.settle(device.Name) + return device + } + install := func(e *env, device *inventory.Device, request string, delivery ops.DeliveryInput, network *ops.BootNetworkInput) *ops.DeviceInstallation { + e.t.Helper() + allocation := "alloc-d-" + device.Name + operation := &ops.DeviceInstallation{ObjectMeta: metav1.ObjectMeta{Name: InstallationName(allocation, request), Namespace: "default"}, Spec: ops.DeviceInstallationSpec{ + OperationEnvelope: envelope(device, providerUser, allocated(allocation)), RequestUID: request, + Image: ops.ImageInput{Name: "debian-12", Digest: imageDigest}, BootInterface: "primary", TargetDisks: []string{"disk-0"}, BootNetwork: network, Delivery: delivery, + }} + e.create(operation) + return operation + } + + t.Run("a qualified virtual media install is admitted and records its method", func(t *testing.T) { + e := e.sub(t) + device := held(e, "VirtualMedia") + operation := install(e, device, "request-1", virtualMedia, nil) + e.settle(device.Name) + active := e.custody(device.Name).Spec.ActiveOperation + if active == nil || active.UID != string(operation.UID) || active.Snapshot.Extra[ExtraDeliveryMethod] != "VirtualMedia" { + t.Fatalf("the snapshot records %q", active.Snapshot.Extra[ExtraDeliveryMethod]) + } + }) + + t.Run("a method no serving site offers is refused", func(t *testing.T) { + e := e.sub(t) + e.sites.mu.Lock() + e.sites.methods = NetworkBootOnly + e.sites.mu.Unlock() + defer func() { + e.sites.mu.Lock() + e.sites.methods = nil + e.sites.mu.Unlock() + }() + device := held(e, "NetworkBoot,VirtualMedia") + fence := e.custody(device.Name).Spec.Fence + operation := install(e, device, "request-1", virtualMedia, nil) + e.settle(device.Name) + e.requirePhase(operation, ops.PhaseFailed, ReasonDeliveryNotOffered) + e.requireUntouched(device.Name, fence) + }) + + t.Run("a method the server is not qualified for is refused", func(t *testing.T) { + e := e.sub(t) + device := held(e, "") + fence := e.custody(device.Name).Spec.Fence + operation := install(e, device, "request-1", virtualMedia, nil) + e.settle(device.Name) + e.requirePhase(operation, ops.PhaseFailed, ReasonDeliveryUnqualified) + e.requireUntouched(device.Name, fence) + }) + + t.Run("a method that does not match the other inputs is refused", func(t *testing.T) { + e := e.sub(t) + device := held(e, "VirtualMedia") + fence := e.custody(device.Name).Spec.Fence + notURL := virtualMedia + notURL.MediaService = "http://media.example" + if refusal := checkDelivery(&Admission{Device: device, Custody: e.custody(device.Name), Offered: e.sites.DeliveryMethods("")}, &ops.DeviceInstallationSpec{Delivery: notURL}); refusal == nil || refusal.Reason != ReasonDeliveryInputs { + t.Fatalf("a media service that is not https://IPv4:port: %+v", refusal) + } + network := &ops.BootNetworkInput{AddressClaim: fleetv1.TypedReference{APIGroup: "ipam.miloapis.com", Kind: "IPAddressClaim", Name: "claim-example"}, Address: "198.51.100.30"} + operation := install(e, device, "request-1", virtualMedia, network) + e.settle(device.Name) + e.requirePhase(operation, ops.PhaseFailed, ReasonDeliveryInputs) + e.requireUntouched(device.Name, fence) + }) + + t.Run("a held virtual media install is settled only by virtual media", func(t *testing.T) { + e := e.sub(t) + device := held(e, "VirtualMedia") + install(e, device, "request-1", virtualMedia, nil) + e.settle(device.Name) + if err := e.result(device.Name, ops.PhaseOutcomeUnknown, ""); err != nil { + t.Fatal(err) + } + e.settle(device.Name) + custody := e.custody(device.Name) + if method, ok := HeldMethod(custody, "DeviceInstallation"); !ok || method != ops.DeliveryVirtualMedia { + t.Fatalf("the hold records %q, %v", method, ok) + } + fence := custody.Spec.Fence + // The server lost its virtual media qualification and the site's + // preference changed; neither matters to the settling install. + device.Annotations = map[string]string{QualifiedMethodsAnnotation: "NetworkBoot"} + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(device), device); err != nil { + t.Fatal(err) + } + device.Annotations = map[string]string{QualifiedMethodsAnnotation: "NetworkBoot"} + if err := e.admin.Update(e.ctx, device); err != nil { + t.Fatal(err) + } + e.discover(device, fmt.Sprintf("%064x", n), e.clock.Now()) + other := install(e, device, "request-2", ops.DeliveryInput{Method: ops.DeliveryNetworkBoot}, nil) + e.settle(device.Name) + e.requirePhase(other, ops.PhaseFailed, ReasonDeliveryMismatch) + e.requireUntouched(device.Name, fence) + // The settling install still takes its inputs from the site's + // offer: another media service is refused. + elsewhere := virtualMedia + elsewhere.MediaService = "https://198.51.100.9:8443" + redirected := install(e, device, "request-4", elsewhere, nil) + e.settle(device.Name) + e.requirePhase(redirected, ops.PhaseFailed, ReasonDeliveryInputs) + e.requireUntouched(device.Name, fence) + settling := install(e, device, "request-3", virtualMedia, nil) + e.settle(device.Name) + if active := e.custody(device.Name).Spec.ActiveOperation; active == nil || active.UID != string(settling.UID) { + t.Fatalf("the virtual media settling install was not admitted: %+v, %+v", active, e.status(settling)) + } + }) + + t.Run("a hold whose method no site offers says what it waits for", func(t *testing.T) { + e := e.sub(t) + device := held(e, "VirtualMedia") + install(e, device, "request-1", virtualMedia, nil) + e.settle(device.Name) + if err := e.result(device.Name, ops.PhaseOutcomeUnknown, ""); err != nil { + t.Fatal(err) + } + e.settle(device.Name) + if waiting := e.custody(device.Name).Spec.RecoveryHold.Waiting; waiting != nil { + t.Fatalf("a hold whose method is offered waits: %+v", waiting) + } + e.sites.mu.Lock() + e.sites.methods = NetworkBootOnly + e.sites.mu.Unlock() + defer func() { + e.sites.mu.Lock() + e.sites.methods = nil + e.sites.mu.Unlock() + }() + e.settle(device.Name) + waiting := e.custody(device.Name).Spec.RecoveryHold.Waiting + if waiting == nil || waiting.Reason != ReasonHoldMethodNotOffered || !strings.Contains(waiting.Message, "VirtualMedia") { + t.Fatalf("waiting = %+v", waiting) + } + e.sites.mu.Lock() + e.sites.methods = nil + e.sites.mu.Unlock() + e.settle(device.Name) + if waiting := e.custody(device.Name).Spec.RecoveryHold.Waiting; waiting != nil { + t.Fatalf("the hold still waits once the site offers the method again: %+v", waiting) + } + }) + + t.Run("a wipe cannot settle a held virtual media install", func(t *testing.T) { + e := e.sub(t) + device := held(e, "VirtualMedia") + allocation := "alloc-d-" + device.Name + install(e, device, "request-1", virtualMedia, nil) + e.settle(device.Name) + if err := e.result(device.Name, ops.PhaseDispatched, ""); err != nil { + t.Fatal(err) + } + if err := e.coord.BeginRelease(e.ctx, device.Name, allocation); err != nil { + t.Fatal(err) + } + e.settle(device.Name) + e.clock.Advance(DeliveryDeadline(virtualMedia) + DefaultSkewMargin) + e.settle(device.Name) + custody := e.custody(device.Name) + if custody.Spec.Holder.Type != ops.HolderRelease || custody.Spec.RecoveryHold == nil { + t.Fatalf("after the install deadline: %+v", custody.Spec) + } + e.discover(device, fmt.Sprintf("%064x", n), e.clock.Now()) + wipe := e.wipe(device, allocation, 1) + e.settle(device.Name) + e.requirePhase(wipe, ops.PhaseFailed, ReasonDeliveryMismatch) + e.requireUntouched(device.Name, custody.Spec.Fence) + }) + + t.Run("an unpinned installer download is refused", func(t *testing.T) { + e := e.sub(t) + device := held(e, "VirtualMedia") + fence := e.custody(device.Name).Spec.Fence + allocation := "alloc-d-" + device.Name + operation := &ops.DeviceInstallation{ObjectMeta: metav1.ObjectMeta{Name: InstallationName(allocation, "request-1"), Namespace: "default"}, Spec: ops.DeviceInstallationSpec{ + OperationEnvelope: envelope(device, providerUser, allocated(allocation)), RequestUID: "request-1", + Image: ops.ImageInput{Name: "talos", Digest: imageDigest, Downloads: []ops.DownloadInput{{Name: "installer", Reference: "registry.example/installer:v1.0.0"}}}, + BootInterface: "primary", TargetDisks: []string{"disk-0"}, Delivery: virtualMedia, + }} + e.create(operation) + e.settle(device.Name) + e.requirePhase(operation, ops.PhaseFailed, ReasonDownloadUnpinned) + e.requireUntouched(device.Name, fence) + }) + + t.Run("a BMC that does not verify the media service is refused", func(t *testing.T) { + e := e.sub(t) + device := held(e, "VirtualMedia") + device.Annotations[MediaTLSAnnotation] = "Unverified" + if err := e.admin.Update(e.ctx, device); err != nil { + t.Fatal(err) + } + e.discover(device, fmt.Sprintf("%064x", n), e.clock.Now()) + fence := e.custody(device.Name).Spec.Fence + operation := install(e, device, "request-1", virtualMedia, nil) + e.settle(device.Name) + e.requirePhase(operation, ops.PhaseFailed, ReasonMediaTLSUnverified) + e.requireUntouched(device.Name, fence) + }) + + t.Run("a virtual media install's deadline is its phases", func(t *testing.T) { + e := e.sub(t) + device := held(e, "VirtualMedia") + operation := install(e, device, "request-1", virtualMedia, nil) + e.settle(device.Name) + active := e.custody(device.Name).Spec.ActiveOperation + if active == nil || active.UID != string(operation.UID) || active.Deadline.Sub(active.AdmittedAt.Time) != ops.DefaultFetchWindow+ops.DefaultReportWindow { + t.Fatalf("active = %+v", active) + } + }) +} + +// twoSites serves one Device from two sites with their own declarations. +type twoSites map[string][]OfferedMethod + +func (t twoSites) Serving(*inventory.Device) []string { return []string{"site-a", "site-b"} } +func (t twoSites) Fence(context.Context, string, *inventory.Device) (SiteFence, bool, error) { + return SiteFence{}, false, nil +} +func (t twoSites) DeliveryMethods(site string) []OfferedMethod { return t[site] } + +func TestOfferedIsWhatEveryServingSiteOffers(t *testing.T) { + window := func(d time.Duration) *metav1.Duration { return &metav1.Duration{Duration: d} } + media := func() OfferedMethod { + // Each site's declaration holds its own window values. + return OfferedMethod{Method: ops.DeliveryVirtualMedia, Addresses: ops.AddressesDataNetwork, MediaService: mediaService, FetchWindow: window(time.Minute), ReportWindow: window(time.Hour)} + } + got := offered(twoSites{"site-a": {{Method: ops.DeliveryNetworkBoot}, media()}, "site-b": {media()}}, &inventory.Device{}) + if len(got) != 1 || got[0].Method != ops.DeliveryVirtualMedia { + t.Fatalf("offered = %+v, want virtual media alone", got) + } + other := media() + other.ReportWindow = window(time.Minute) + if got := offered(twoSites{"site-a": {media()}, "site-b": {other}}, &inventory.Device{}); len(got) != 0 { + t.Fatalf("sites with different windows offered %+v", got) + } +} + +func TestCheckDownloads(t *testing.T) { + digest := "@sha256:" + strings.Repeat("a", 64) + for name, downloads := range map[string][]ops.DownloadInput{ + "a tag": {{Name: "installer", Reference: "registry.example/installer:v1"}}, + "a newline in name": {{Name: "installer\ntoken=x", Reference: "registry.example/installer" + digest}}, + "a newline in ref": {{Name: "installer", Reference: "registry.example/installer\n" + digest}}, + "too many downloads": slices.Repeat([]ops.DownloadInput{{Name: "installer", Reference: "registry.example/installer" + digest}}, maxDownloads+1), + } { + if checkDownloads(downloads) == nil { + t.Errorf("%s was not refused", name) + } + } + if refusal := checkDownloads([]ops.DownloadInput{{Name: "installer", Reference: "registry.example/installer" + digest}}); refusal != nil { + t.Fatalf("a pinned download was refused: %+v", refusal) + } +} diff --git a/internal/custody/harness_test.go b/internal/custody/harness_test.go index 9d279b8c..81af0b9c 100644 --- a/internal/custody/harness_test.go +++ b/internal/custody/harness_test.go @@ -72,6 +72,18 @@ type fakeSites struct { // place of its stopped fence, as a site whose older worker has not yet // stopped would report. seen map[string]int64 + // methods, when set, replaces the site's declared delivery methods, + // which default to network boot then virtual media. + methods []OfferedMethod +} + +func (s *fakeSites) DeliveryMethods(string) []OfferedMethod { + s.mu.Lock() + defer s.mu.Unlock() + if s.methods != nil { + return s.methods + } + return []OfferedMethod{{Method: ops.DeliveryNetworkBoot}, {Method: ops.DeliveryVirtualMedia, Addresses: ops.AddressesDataNetwork, MediaService: "https://192.0.2.10:8443"}} } func newFakeSites() *fakeSites { @@ -343,7 +355,7 @@ func (e *env) installation(device *inventory.Device, allocation, request string) e.t.Helper() operation := &ops.DeviceInstallation{ObjectMeta: metav1.ObjectMeta{Name: InstallationName(allocation, request), Namespace: "default", Labels: map[string]string{ops.LabelInstallationUID: request}}, Spec: ops.DeviceInstallationSpec{ OperationEnvelope: envelope(device, providerUser, allocated(allocation)), - Image: ops.ImageInput{Name: "debian-12", Digest: imageDigest}, BootInterface: "primary", TargetDisks: []string{"disk-0"}, + Image: ops.ImageInput{Name: "debian-12", Digest: imageDigest}, BootInterface: "primary", TargetDisks: []string{"disk-0"}, Delivery: ops.DeliveryInput{Method: ops.DeliveryNetworkBoot}, }} e.create(operation) return operation diff --git a/internal/custody/kinds.go b/internal/custody/kinds.go index 5ada5456..3fdd8c3d 100644 --- a/internal/custody/kinds.go +++ b/internal/custody/kinds.go @@ -160,7 +160,10 @@ func DeviceInstallationKind() Kind { Name: func(operation ops.Operation) string { return InstallationName(allocationName(operation), operation.GetLabels()[ops.LabelInstallationUID]) }, - Deadline: InstallationDeadline, + Deadline: InstallationDeadline, + DeadlineFor: func(operation ops.Operation) time.Duration { + return DeliveryDeadline(operation.(*ops.DeviceInstallation).Spec.Delivery) + }, Effectful: true, BootInterface: func(operation ops.Operation) string { return operation.(*ops.DeviceInstallation).Spec.BootInterface }, Check: func(ctx context.Context, admission *Admission) *Refusal { @@ -169,10 +172,16 @@ func DeviceInstallationKind() Kind { if installation.Spec.Bootstrap != nil { return refuse(ReasonBootstrapUnsupported, "bootstrap payloads need the sealed store, which is not implemented") } + if refusal := checkDelivery(admission, &installation.Spec); refusal != nil { + return refusal + } return checkNetworkBoot(ctx, admission, "DeviceInstallation", installation.Spec.BootInterface, installation.Spec.BootNetwork) }, + SnapshotExtra: func(admission *Admission) map[string]string { + return map[string]string{ExtraDeliveryMethod: string(admission.Operation.(*ops.DeviceInstallation).Spec.Delivery.Method)} + }, Settles: []SettleRule{{Held: "DeviceInstallation"}}, - Reasons: append(append([]Reason{{Name: ReasonBootstrapUnsupported, RaisedBy: RaisedByBoth}}, networkBootReasons...), workerReasons...), + Reasons: append(append(append([]Reason{{Name: ReasonBootstrapUnsupported, RaisedBy: RaisedByBoth}}, networkBootReasons...), workerReasons...), deliveryReasons...), Evidence: StrictEvidence(evidenceLimit, func(_ ops.Operation, evidence *ops.InstallationEvidence) error { return validateSteps(evidence.Steps) }), @@ -200,13 +209,16 @@ func DeviceWipeKind() Kind { BootInterface: func(operation ops.Operation) string { return operation.(*ops.DeviceWipe).Spec.BootInterface }, Check: func(ctx context.Context, admission *Admission) *Refusal { wipe := admission.Operation.(*ops.DeviceWipe) + if refusal := checkWipeDelivery(admission); refusal != nil { + return refusal + } return checkNetworkBoot(ctx, admission, "DeviceWipe", wipe.Spec.BootInterface, wipe.Spec.BootNetwork) }, // A wipe after release settles an installation hold. A held wipe is // settled by a later wipe only after a DeviceRecovery with Retry. Settles: []SettleRule{{Held: "DeviceInstallation"}, {Held: "DeviceWipe", RequiresRetry: true}}, Retryable: true, - Reasons: append(append([]Reason{}, networkBootReasons...), workerReasons...), + Reasons: append(append([]Reason{{Name: ReasonDeliveryMismatch, RaisedBy: RaisedByCoordinator}}, networkBootReasons...), workerReasons...), Evidence: StrictEvidence(evidenceLimit, func(_ ops.Operation, evidence *ops.WipeEvidence) error { if len(evidence.WipedDisks) > 16 { return errors.New("evidence records at most 16 disks") diff --git a/internal/custody/registry.go b/internal/custody/registry.go index 2e7d6418..8c0a2984 100644 --- a/internal/custody/registry.go +++ b/internal/custody/registry.go @@ -59,9 +59,10 @@ type Kind struct { Name func(ops.Operation) string // Deadline is how long the site may work on an admitted operation. Deadline time.Duration - // DeadlineFor, when set, replaces Deadline with one derived from the - // operation's own inputs, such as a commissioning plan's burn-in - // duration. + // DeadlineFor, when set and positive for an operation, replaces Deadline + // with one derived from the operation's own inputs, such as a + // commissioning plan's burn-in duration or an installation's virtual + // media phases. DeadlineFor func(ops.Operation) time.Duration // KeepsLatest means retention keeps each Device's latest succeeded // operation of this kind, because it is evidence another reader needs, @@ -185,6 +186,9 @@ type Admission struct { Now time.Time // DiscoveryInterval is how often BMC discovery reads each BMC. DiscoveryInterval time.Duration + // Offered is the boot delivery methods every site serving the Device + // offers, in the first site's order of preference. + Offered []OfferedMethod } // RecoverySettleContext is what a held kind's settle hook sees. Hold carries diff --git a/internal/delivery/delivery.go b/internal/delivery/delivery.go index a6573ff9..0b42a6c6 100644 --- a/internal/delivery/delivery.go +++ b/internal/delivery/delivery.go @@ -42,6 +42,13 @@ type Sites struct { Sites map[string]Site // Devices maps a Device name to the names of the sites serving it. Devices map[string][]string + // Methods is each site's declared boot delivery methods, in its order + // of preference. A site with none offers none. + Methods map[string][]custody.OfferedMethod +} + +func (s *Sites) DeliveryMethods(name string) []custody.OfferedMethod { + return slices.Clone(s.Methods[name]) } var _ custody.Sites = (*Sites)(nil) diff --git a/internal/multiplane/scenarios.go b/internal/multiplane/scenarios.go index 0933c7ad..8c89f0ee 100644 --- a/internal/multiplane/scenarios.go +++ b/internal/multiplane/scenarios.go @@ -189,7 +189,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"}, + Image: image, 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/site/config.go b/internal/site/config.go index 8e43b80e..b4d318e7 100644 --- a/internal/site/config.go +++ b/internal/site/config.go @@ -4,6 +4,7 @@ import ( "context" "crypto/sha256" "encoding/hex" + "slices" inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" "go.datum.net/fleet/internal/bmcdiscovery" @@ -55,15 +56,26 @@ func (t StaticTargets) Target(device string) (redfish.Target, bool) { } // Report is the site's fence report for the coordinator. Targets is the -// explicit list of Devices this site serves. +// explicit list of Devices this site serves, and Methods the boot delivery +// methods it declares, in its order of preference. type Report struct { Site string Store *Store Targets StaticTargets + Methods []custody.OfferedMethod } var _ custody.Sites = Report{} +// DeliveryMethods returns the site's declared methods. A site that declares +// none offers none. +func (r Report) DeliveryMethods(site string) []custody.OfferedMethod { + if site != r.Site { + return nil + } + return slices.Clone(r.Methods) +} + func (r Report) Serving(device *inventory.Device) []string { if _, ok := r.Targets[device.Namespace+"/"+device.Name]; ok { return []string{r.Site} diff --git a/internal/site/simwork/kinds.go b/internal/site/simwork/kinds.go index 84a8ed6a..876f0d28 100644 --- a/internal/site/simwork/kinds.go +++ b/internal/site/simwork/kinds.go @@ -109,6 +109,9 @@ func (Installation) Check(_ context.Context, work *site.Work) *custody.Refusal { if spec.Bootstrap != nil { return &custody.Refusal{Reason: custody.ReasonBootstrapUnsupported, Message: "bootstrap payloads need the sealed store, which is not implemented"} } + if refusal := custody.OnlyNetworkBoot(spec.Delivery); refusal != nil { + return refusal + } if refusal := custody.NoBootNetwork(spec.BootNetwork); refusal != nil { return refusal } diff --git a/internal/site/vmwork/kinds.go b/internal/site/vmwork/kinds.go index 89e883c6..1e88f1ba 100644 --- a/internal/site/vmwork/kinds.go +++ b/internal/site/vmwork/kinds.go @@ -159,6 +159,9 @@ func (k Installation) Check(_ context.Context, work *site.Work) *custody.Refusal if spec.Bootstrap != nil { return &custody.Refusal{Reason: custody.ReasonBootstrapUnsupported, Message: "bootstrap payloads need the sealed store, which is not implemented"} } + if refusal := custody.OnlyNetworkBoot(spec.Delivery); refusal != nil { + return refusal + } if refusal := custody.NoBootNetwork(spec.BootNetwork); refusal != nil { return refusal } diff --git a/internal/site/vmwork/kinds_test.go b/internal/site/vmwork/kinds_test.go index 76f8a285..5f6f4af0 100644 --- a/internal/site/vmwork/kinds_test.go +++ b/internal/site/vmwork/kinds_test.go @@ -211,7 +211,7 @@ func envelope() ops.OperationEnvelope { func installSpec() ops.DeviceInstallationSpec { name, digest, _ := strings.Cut(image, "@") - return ops.DeviceInstallationSpec{OperationEnvelope: envelope(), Image: ops.ImageInput{Name: name, Digest: digest}, BootInterface: "primary", TargetDisks: []string{"disk-0"}} + return ops.DeviceInstallationSpec{OperationEnvelope: envelope(), Image: ops.ImageInput{Name: name, Digest: digest}, BootInterface: "primary", TargetDisks: []string{"disk-0"}, Delivery: ops.DeliveryInput{Method: ops.DeliveryNetworkBoot}} } func wipeSpec() ops.DeviceWipeSpec { diff --git a/internal/staging/harness_test.go b/internal/staging/harness_test.go index 20ae74ef..b4d03d2b 100644 --- a/internal/staging/harness_test.go +++ b/internal/staging/harness_test.go @@ -125,7 +125,7 @@ func startStack(t *testing.T) *stack { if err != nil { t.Fatal(err) } - sites := &delivery.Sites{Sites: map[string]delivery.Site{siteName: remote}, Devices: map[string][]string{}} + sites := &delivery.Sites{Sites: map[string]delivery.Site{siteName: remote}, Devices: map[string][]string{}, Methods: map[string][]custody.OfferedMethod{siteName: custody.NetworkBootOnly}} coordinator := &custody.Coordinator{Client: admin, Registry: registry, Sites: sites, Config: custody.Config{Namespace: providerNamespace, Principals: custody.Principals{ custody.CreatorMetalProvider: {{Username: providerUser}}, custody.CreatorReleaseController: {{Username: releaseUser}}, }}} @@ -139,6 +139,7 @@ func startStack(t *testing.T) *stack { Cleaning: func(string) (string, error) { return policyDigest, nil }, Capacity: s.projector, BootInterface: "primary", TargetDisks: []string{"disk-0"}, + DeliveryMethods: custody.NetworkBootOnly, } // One qualified plan covers every fixture server. s.plan = &ops.DeviceCommissioningPlan{ObjectMeta: metav1.ObjectMeta{Name: "example-plan", Namespace: providerNamespace}, Spec: ops.DeviceCommissioningPlanSpec{ From 0cd9e7552bb4f8a361ad4e651b18b38bf029938b Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Fri, 27 Nov 2026 11:56:15 -0600 Subject: [PATCH 02/35] feat(site): Install over Redfish virtual media The Redfish install worker hands each install to its delivery method; network boot is unchanged. Virtual media opens a window at the central media service, which opens it only while custody names the operation active at its fence, and only for the site worker's client certificate. The worker reads that certificate from its own Secret, only for virtual media. The BMC mounts a boot medium and a per-operation config medium over verified HTTPS, and the worker reads both back and boots once from CD. The installed OS proves the install: at first boot it posts the report token, the boot medium's content digest, the salted bootstrap digest and the digests of what it downloaded, from the Machine's address. The worker takes exactly one such report before the report deadline, then proves release from the BMC and the media service. Every step is journaled before it is sent. Anything sent but unproven ends OutcomeUnknown after an undo that is never proof; a window refused before any BMC step ends Failed. The service sweeps config media, and their tokens, that no window can serve. Records keep only digests. Co-Authored-By: Claude Opus 5.5 --- cmd/fleet-multiplane/site.go | 60 +- internal/redfish/enrollment.go | 10 +- internal/redfish/media.go | 147 +++ internal/site/access.go | 42 +- internal/site/config.go | 31 + internal/site/config_test.go | 56 ++ internal/site/redfishwork/kinds.go | 85 +- internal/site/redfishwork/kinds_test.go | 20 +- internal/site/redfishwork/media.go | 835 +++++++++++++++++ internal/site/redfishwork/media_test.go | 1041 ++++++++++++++++++++++ internal/site/redfishwork/mediaserver.go | 800 +++++++++++++++++ internal/site/runner.go | 12 + internal/site/store.go | 16 + 13 files changed, 3146 insertions(+), 9 deletions(-) create mode 100644 internal/redfish/media.go create mode 100644 internal/site/redfishwork/media.go create mode 100644 internal/site/redfishwork/media_test.go create mode 100644 internal/site/redfishwork/mediaserver.go diff --git a/cmd/fleet-multiplane/site.go b/cmd/fleet-multiplane/site.go index b02fc188..8bd865c4 100644 --- a/cmd/fleet-multiplane/site.go +++ b/cmd/fleet-multiplane/site.go @@ -2,9 +2,11 @@ package main import ( "context" + "encoding/base64" "encoding/json" "errors" "fmt" + "net/netip" "os" "path/filepath" "strings" @@ -170,7 +172,29 @@ func redfishConfig() (redfishwork.Config, redfish.Enrollment, error) { if err != nil { return redfishwork.Config{}, redfish.Enrollment{}, err } - return redfishwork.Config{ConsoleRoot: console, BootRoot: boot, Synced: enrollment.DHCP == redfish.DHCPSynced, DHCPInstances: enrollment.DHCPInstances}, enrollment, nil + work := redfishwork.Config{ConsoleRoot: console, BootRoot: boot, Synced: enrollment.DHCP == redfish.DHCPSynced, DHCPInstances: enrollment.DHCPInstances, Artifacts: artifacts} + // The site's trust for the central media service: its certificate in + // PEM, base64 encoded. A site without it cannot use virtual media. + if value := os.Getenv("FLEET_MEDIA_CA"); value != "" { + ca, err := base64.StdEncoding.DecodeString(value) + if err != nil { + return redfishwork.Config{}, redfish.Enrollment{}, errors.New("FLEET_MEDIA_CA must be a base64 PEM certificate") + } + work.MediaCA = ca + } + // Where the media service sees this site's installed servers report + // from: IPv4 or IPv6 prefixes, comma separated. + for _, value := range strings.Split(os.Getenv("FLEET_MEDIA_REPORT_FROM"), ",") { + if value = strings.TrimSpace(value); value == "" { + continue + } + prefix, err := netip.ParsePrefix(value) + if err != nil { + return redfishwork.Config{}, redfish.Enrollment{}, errors.New("FLEET_MEDIA_REPORT_FROM must list address prefixes") + } + work.ReportFrom = append(work.ReportFrom, prefix.Masked()) + } + return work, enrollment, nil } // siteRunner is the site runner for this cell's mode. A Redfish worker reads @@ -206,7 +230,13 @@ func siteRunner(_ context.Context, config *rest.Config, cell string, store *site for _, target := range enrollment.Targets { targets[target.Device] = target } - runner.Access = site.RedfishAccess{Credentials: site.SecretCredentials{Reader: reader, Namespace: namespace, Project: project}, Targets: targets} + access := site.RedfishAccess{Credentials: site.SecretCredentials{Reader: reader, Namespace: namespace, Project: project}, Targets: targets} + // The site worker's media service identity is its own Secret, read under + // a grant of its own, never part of a Device's BMC credential. + if identity := os.Getenv("FLEET_SITE_WORKER_IDENTITY_NAMESPACE"); identity != "" { + access.MediaIdentity = site.SecretWorkerIdentity{Reader: reader, Namespace: identity} + } + runner.Access = access // The site serves one boot image, which also burns in. image, err := siteImage() if err != nil { @@ -307,3 +337,29 @@ func feedEnrollment(raw []byte) (redfish.Enrollment, error) { } return enrollment, nil } + +// mediaStale probes the site store for a delayed worker: below the Device's +// stored fence it can neither open a media window nor journal a media step. +// Both attempts are refused, so the probe writes nothing. +func mediaStale(device string) error { + store, err := openStore() + if err != nil { + return err + } + fence, _, err := store.Peek(device) + if err != nil { + return err + } + if fence < 2 { + return fmt.Errorf("media-stale: the Device has no fence above the first") + } + stale := fence - 1 + if err := store.PutRecord(device, stale, "media", "stale-probe", map[string]any{"operation": "stale-probe", "fence": stale}); !errors.Is(err, site.ErrStaleFence) { + return fmt.Errorf("media-stale: a media window at fence %d was not refused: %v", stale, err) + } + if _, _, err := store.IntendWithPayload(device, stale, "stale-probe", "media-insert-boot", nil); !errors.Is(err, site.ErrStaleFence) { + return fmt.Errorf("media-stale: a media step at fence %d was not refused: %v", stale, err) + } + fmt.Printf("PASS at stored fence %d, a worker at fence %d was refused a media window and the media-insert-boot step\n", fence, stale) + return nil +} diff --git a/internal/redfish/enrollment.go b/internal/redfish/enrollment.go index 16088aee..64bbbbda 100644 --- a/internal/redfish/enrollment.go +++ b/internal/redfish/enrollment.go @@ -10,6 +10,7 @@ import ( "net/url" "os" "path/filepath" + "slices" "strconv" "strings" @@ -127,7 +128,12 @@ func ParseBootOrigin(value string) (string, error) { return "http://" + ip.To4().String() + ":" + strconv.Itoa(port), nil } -// VerifyArtifacts derives the admitted image from the exact two-artifact manifest. +// Artifacts are the image's artifacts, in manifest order: the installer +// kernel and initrd network boot serves, and the boot medium virtual media +// mounts, which holds the same kernel and initrd. +var Artifacts = []string{"kernel", "installer.gz", "boot.iso"} + +// VerifyArtifacts derives the admitted image from the exact artifact manifest. func VerifyArtifacts(dir string) (string, error) { b, err := os.ReadFile(dir + "/SHA256SUMS") if err != nil { @@ -137,7 +143,7 @@ func VerifyArtifacts(dir string) (string, error) { seen := map[string]bool{} for _, line := range lines { f := strings.Fields(line) - if len(lines) != 2 || len(f) != 2 || (f[1] != "kernel" && f[1] != "installer.gz") || seen[f[1]] { + if len(lines) != len(Artifacts) || len(f) != 2 || !slices.Contains(Artifacts, f[1]) || seen[f[1]] { return "", errors.New("invalid artifact manifest") } seen[f[1]] = true diff --git a/internal/redfish/media.go b/internal/redfish/media.go new file mode 100644 index 00000000..227c9759 --- /dev/null +++ b/internal/redfish/media.go @@ -0,0 +1,147 @@ +package redfish + +import ( + "context" + "fmt" + "strings" + + "github.com/stmcginnis/gofish/schemas" +) + +// Media is one virtual media device of a System, as the BMC reports it. +// Image is the URL the BMC holds, which can carry a capability: callers +// compare it by digest and never record it. +type Media struct { + Path string `json:"path"` + ID string `json:"id"` + MediaTypes []string `json:"mediaTypes"` + Inserted bool `json:"inserted"` + Image string `json:"-"` + insert string + eject string +} + +// CanInsert and CanEject report whether the device offers each action. +func (m Media) CanInsert() bool { return m.insert != "" } +func (m Media) CanEject() bool { return m.eject != "" } + +// Empty reports whether the device holds no medium. +func (m Media) Empty() bool { return !m.Inserted && m.Image == "" } + +// rawMedia holds the properties and action targets read from a VirtualMedia +// resource. Only the fields Fleet uses are decoded. +type rawMedia struct { + ID string `json:"Id"` + MediaTypes []string `json:"MediaTypes"` + Inserted bool `json:"Inserted"` + Image *string `json:"Image"` + Actions struct { + Insert struct { + Target string `json:"target"` + } `json:"#VirtualMedia.InsertMedia"` + Eject struct { + Target string `json:"target"` + } `json:"#VirtualMedia.EjectMedia"` + } `json:"Actions"` +} + +// VirtualMedia reads every virtual media device of the retained System. The +// collection must be the System's own, and each device and action target +// must sit inside it, so a link the BMC returns cannot direct an insert to +// another System. It issues GETs only. +func (c *Client) VirtualMedia(ctx context.Context, sys System) ([]Media, error) { + api, err := c.connect(ctx) + if err != nil { + return nil, err + } + var system struct { + ID string + UUID string + VirtualMedia struct { + ID string `json:"@odata.id"` + } + } + if err := getJSON(api, sys.Path, &system); err != nil { + return nil, err + } + if system.ID != sys.ID || !strings.EqualFold(system.UUID, sys.UUID) { + return nil, fmt.Errorf("%w: retained System path changed identity", ErrIdentity) + } + if system.VirtualMedia.ID == "" { + return nil, fmt.Errorf("%w: the System has no VirtualMedia collection", ErrUnsupported) + } + collection, err := cleanPath(system.VirtualMedia.ID) + if err != nil || !strings.HasPrefix(collection, sys.Path+"/") { + return nil, fmt.Errorf("%w: VirtualMedia collection not on the enrolled System", ErrIdentity) + } + var members struct { + Members []struct { + ID string `json:"@odata.id"` + } + } + if err := getJSON(api, collection, &members); err != nil { + return nil, err + } + var out []Media + for _, member := range members.Members { + path, err := cleanPath(member.ID) + if err != nil || !strings.HasPrefix(path, collection+"/") { + return nil, fmt.Errorf("%w: virtual media device outside the collection", ErrIdentity) + } + var raw rawMedia + if err := getJSON(api, path, &raw); err != nil { + return nil, err + } + media := Media{Path: path, ID: raw.ID, MediaTypes: raw.MediaTypes, Inserted: raw.Inserted} + if raw.Image != nil { + media.Image = *raw.Image + } + for target, into := range map[string]*string{raw.Actions.Insert.Target: &media.insert, raw.Actions.Eject.Target: &media.eject} { + if target == "" { + continue + } + clean, err := cleanPath(target) + if err != nil || !strings.HasPrefix(clean, path+"/") { + return nil, fmt.Errorf("%w: virtual media action not on its device", ErrIdentity) + } + *into = clean + } + out = append(out, media) + } + return out, nil +} + +// InsertMedia posts exactly one InsertMedia to the device: the image over +// HTTPS, write protected. HTTP success is not evidence of the effect; +// callers read the device back. +func (c *Client) InsertMedia(ctx context.Context, media Media, image string) error { + if media.insert == "" { + return fmt.Errorf("%w: InsertMedia on %s", ErrUnsupported, media.ID) + } + if !strings.HasPrefix(image, "https://") { + return fmt.Errorf("%w: virtual media is inserted only over HTTPS", ErrUnsupported) + } + api, err := c.connect(ctx) + if err != nil { + return err + } + body := map[string]any{"Image": image, "Inserted": true, "WriteProtected": true, "TransferProtocolType": "HTTPS"} + resp, err := api.PostWithHeaders(media.insert, body, nil) + schemas.DeferredCleanupHTTPResponse(resp) + return classify(err) +} + +// EjectMedia posts exactly one EjectMedia to the device. Callers read the +// device back. +func (c *Client) EjectMedia(ctx context.Context, media Media) error { + if media.eject == "" { + return fmt.Errorf("%w: EjectMedia on %s", ErrUnsupported, media.ID) + } + api, err := c.connect(ctx) + if err != nil { + return err + } + resp, err := api.PostWithHeaders(media.eject, map[string]any{}, nil) + schemas.DeferredCleanupHTTPResponse(resp) + return classify(err) +} diff --git a/internal/site/access.go b/internal/site/access.go index 2e0ad2cc..ac7a65f3 100644 --- a/internal/site/access.go +++ b/internal/site/access.go @@ -2,6 +2,7 @@ package site import ( "context" + "crypto/tls" "errors" "strings" "time" @@ -38,6 +39,27 @@ type RedfishConnection struct { Target redfish.Target System redfish.System BMC *redfish.Client + // identity reads the site worker's media service client certificate. + // Only a method that uses the media service reads it, so a missing or + // broken identity never stops network boot or a wipe. + identity MediaClients + device string +} + +// MediaClient reads the site worker's client certificate for the central +// media service, or nil when the site has none. +func (c *RedfishConnection) MediaClient(ctx context.Context) (*tls.Certificate, error) { + if c.identity == nil { + return nil, nil + } + return c.identity.MediaClient(ctx, c.device) +} + +// MediaClients reads the site worker's client certificate for the central +// media service. It is the worker's own identity, kept apart from every +// Device's BMC credential. +type MediaClients interface { + MediaClient(ctx context.Context, device string) (*tls.Certificate, error) } // Observe reads the verified System's power and boot override. @@ -55,6 +77,21 @@ func (c *RedfishConnection) SetBootOnce(ctx context.Context, target string) erro return c.BMC.SetBootOnce(ctx, c.System, target) } +// VirtualMedia reads the verified System's virtual media devices. +func (c *RedfishConnection) VirtualMedia(ctx context.Context) ([]redfish.Media, error) { + return c.BMC.VirtualMedia(ctx, c.System) +} + +// InsertMedia posts one InsertMedia to a device of the verified System. +func (c *RedfishConnection) InsertMedia(ctx context.Context, media redfish.Media, image string) error { + return c.BMC.InsertMedia(ctx, media, image) +} + +// EjectMedia posts one EjectMedia to a device of the verified System. +func (c *RedfishConnection) EjectMedia(ctx context.Context, media redfish.Media) error { + return c.BMC.EjectMedia(ctx, media) +} + // RedfishAccess reaches a server through its BMC. It checks the site's // enrollment against the admitted snapshot, reads the per-Device credential, // requires the operator-approved pin to equal the key discovery recorded at @@ -62,6 +99,9 @@ func (c *RedfishConnection) SetBootOnce(ctx context.Context, target string) erro type RedfishAccess struct { Credentials Credentials Targets Targets + // MediaIdentity, when set, reads the site worker's media service client + // certificate. + MediaIdentity MediaClients // Dial opens a client pinned to the approved key. Tests replace it. Dial func(endpoint, username, password, pin string) (*redfish.Client, error) } @@ -103,5 +143,5 @@ func (a RedfishAccess) Prepare(ctx context.Context, assignment Assignment) (any, case err != nil: return nil, &custody.Refusal{Reason: ReasonBMCUnavailable, Message: "the BMC could not be read"} } - return &RedfishConnection{Target: target, System: system, BMC: client}, nil + return &RedfishConnection{Target: target, System: system, BMC: client, identity: a.MediaIdentity, device: assignment.Device}, nil } diff --git a/internal/site/config.go b/internal/site/config.go index b4d318e7..b01272e3 100644 --- a/internal/site/config.go +++ b/internal/site/config.go @@ -3,6 +3,7 @@ package site import ( "context" "crypto/sha256" + "crypto/tls" "encoding/hex" "slices" @@ -93,3 +94,33 @@ func (r Report) Fence(_ context.Context, site string, device *inventory.Device) } return custody.SiteFence{Seen: fence, Stopped: stopped}, true, nil } + +// WorkerIdentitySecret is the only Secret, in the site worker identity +// namespace, that holds the site workers' client certificate for the +// central media service, as tls.crt and tls.key. There is one per site +// worker identity, not per Device, and a worker gets exactly it. +const WorkerIdentitySecret = "fleet-site-worker-media" + +// SecretWorkerIdentity reads the site worker's media service client +// certificate from its own Secret, by name and with a direct get, apart from +// any BMC credential. +type SecretWorkerIdentity struct { + Reader client.Reader + Namespace string +} + +// MediaClient returns the site worker's client certificate, or nil when the +// site has none. +func (s SecretWorkerIdentity) MediaClient(ctx context.Context, _ string) (*tls.Certificate, error) { + secret := &corev1.Secret{} + if err := s.Reader.Get(ctx, client.ObjectKey{Namespace: s.Namespace, Name: WorkerIdentitySecret}, secret); apierrors.IsNotFound(err) { + return nil, nil + } else if err != nil { + return nil, err + } + identity, err := tls.X509KeyPair(secret.Data[corev1.TLSCertKey], secret.Data[corev1.TLSPrivateKeyKey]) + if err != nil { + return nil, err + } + return &identity, nil +} diff --git a/internal/site/config_test.go b/internal/site/config_test.go index d0f01db5..a7dc5d0a 100644 --- a/internal/site/config_test.go +++ b/internal/site/config_test.go @@ -2,9 +2,17 @@ package site import ( "context" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/x509" + "crypto/x509/pkix" + "encoding/pem" "errors" + "math/big" "strings" "testing" + "time" inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" "go.datum.net/fleet/internal/bmcdiscovery" @@ -92,3 +100,51 @@ func TestReportGivesTheCoordinatorSeenAndStoppedFences(t *testing.T) { t.Fatalf("fence = %+v", fence) } } + +// TestTheWorkerIdentityIsItsOwnSecret reads the site worker's media service +// client certificate from its one named Secret, with a direct get. Another +// site's identity Secret beside it is never read. +func TestTheWorkerIdentityIsItsOwnSecret(t *testing.T) { + pair := func(cn string) map[string][]byte { + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + template := &x509.Certificate{SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: cn}, NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour)} + der, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key) + if err != nil { + t.Fatal(err) + } + keyDER, err := x509.MarshalECPrivateKey(key) + if err != nil { + t.Fatal(err) + } + return map[string][]byte{corev1.TLSCertKey: pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}), + corev1.TLSPrivateKeyKey: pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: keyDER})} + } + own := &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: WorkerIdentitySecret, Namespace: "fleet-site-worker-identity"}, Data: pair("fleet-site-worker:site-example-a")} + other := &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: WorkerIdentitySecret + "-another-site", Namespace: "fleet-site-worker-identity"}, Data: pair("fleet-site-worker:site-example-b")} + var read []string + reader := interceptor.NewClient(fake.NewClientBuilder().WithObjects(own, other).Build(), interceptor.Funcs{ + Get: func(ctx context.Context, c client.WithWatch, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error { + read = append(read, key.String()) + return c.Get(ctx, key, obj, opts...) + }, + List: func(context.Context, client.WithWatch, client.ObjectList, ...client.ListOption) error { + return errors.New("the worker identity must never be listed") + }, + }) + identity, err := SecretWorkerIdentity{Reader: reader, Namespace: "fleet-site-worker-identity"}.MediaClient(context.Background(), "default/server-example-001") + if err != nil || identity == nil { + t.Fatalf("identity = %v, %v", identity, err) + } + leaf, _ := x509.ParseCertificate(identity.Certificate[0]) + if leaf.Subject.CommonName != "fleet-site-worker:site-example-a" || len(read) != 1 || read[0] != "fleet-site-worker-identity/"+WorkerIdentitySecret { + t.Fatalf("read %v as %s", read, leaf.Subject.CommonName) + } + // A site with no identity Secret has no media service identity. + none, err := SecretWorkerIdentity{Reader: fake.NewClientBuilder().Build(), Namespace: "fleet-site-worker-identity"}.MediaClient(context.Background(), "") + if err != nil || none != nil { + t.Fatalf("no Secret = %v, %v", none, err) + } +} diff --git a/internal/site/redfishwork/kinds.go b/internal/site/redfishwork/kinds.go index ed482d76..c5772c4f 100644 --- a/internal/site/redfishwork/kinds.go +++ b/internal/site/redfishwork/kinds.go @@ -76,6 +76,19 @@ type Config struct { // DHCPInstances is the enrollment's expected DHCP instance set. Only // their reports count, and withdrawal needs every one of them. DHCPInstances []string + // MediaCA is the certificate the site trusts for the central media + // service, in PEM. The worker verifies the service with it, and the + // config medium carries it so the installed OS verifies the service + // when it posts its report. Empty means the site cannot use virtual + // media. + MediaCA []byte + // ReportFrom is where the media service sees the site's installed + // servers post their first-boot reports from. A window takes no report + // from elsewhere. A site without it cannot use virtual media. + ReportFrom []netip.Prefix + // Artifacts holds the image's pinned artifacts and their manifest. A + // virtual media installation derives its boot medium from them. + Artifacts string // ContactQuiet replaces contactQuiet, the least time after an admission // was published before withdrawal can be proven. Tests shorten it. ContactQuiet time.Duration @@ -123,7 +136,7 @@ func conn(work *site.Work) *site.RedfishConnection { return connection } -func (k Installation) Check(_ context.Context, work *site.Work) *custody.Refusal { +func (k Installation) Check(ctx context.Context, work *site.Work) *custody.Refusal { if conn(work) == nil { return &custody.Refusal{Reason: ReasonUnsupportedTarget, Message: "this site does not reach the server over Redfish"} } @@ -134,12 +147,70 @@ func (k Installation) Check(_ context.Context, work *site.Work) *custody.Refusal if spec.Bootstrap != nil { return &custody.Refusal{Reason: custody.ReasonBootstrapUnsupported, Message: "bootstrap payloads need the sealed store, which is not implemented"} } - if refusal := k.checkBootNetwork(work, spec.BootNetwork); refusal != nil { + 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"} + } + return method.check(ctx, work, spec) +} + +// deliveryMethod is one boot delivery method behind the install contract. +// The framework owns the fence, the journal and the result; power and +// evidence are the same for every method. Each method checks its inputs +// before anything is sent, then prepares its delivery under the fence, +// verifies what booted, and proves its delivery path closed before the +// installation can succeed. +type deliveryMethod interface { + check(ctx context.Context, work *site.Work, spec ops.DeviceInstallationSpec) *custody.Refusal + install(ctx context.Context, work *site.Work, spec ops.DeviceInstallationSpec) ([]ops.StepEvidence, error) +} + +// networkBoot is the network boot method: a boot admission for the boot +// NIC, a network-booted installer, and, at a synchronized site, proof that +// DHCP withdrew the reservation. +type networkBoot struct{ Config } + +func (m networkBoot) check(_ context.Context, work *site.Work, spec ops.DeviceInstallationSpec) *custody.Refusal { + if refusal := custody.OnlyNetworkBoot(spec.Delivery); refusal != nil { + return refusal + } + if len(spec.Image.Downloads) > 0 { + return &custody.Refusal{Reason: ReasonUnsupportedTarget, Message: "this site's network boot passes no pinned downloads to the installer"} + } + if refusal := m.checkBootNetwork(work, spec.BootNetwork); refusal != nil { return refusal } return checkTarget(work, spec.TargetDisks, installPhases) } +func (m networkBoot) install(ctx context.Context, work *site.Work, _ ops.DeviceInstallationSpec) ([]ops.StepEvidence, error) { + return m.run(ctx, work, installPhases) +} + +// virtualMedia is the virtual media method: a fenced media window, the BMC +// mounting the boot and config media, the install report from the config +// medium's token, and proof from the BMC and the media service that no +// medium, override or window remains. +type virtualMedia struct{ Config } + +func (m virtualMedia) check(ctx context.Context, work *site.Work, spec ops.DeviceInstallationSpec) *custody.Refusal { + return m.checkMedia(ctx, work, spec) +} + +func (m virtualMedia) install(ctx context.Context, work *site.Work, spec ops.DeviceInstallationSpec) ([]ops.StepEvidence, error) { + return m.runMedia(ctx, work, spec) +} + +func (k Installation) method(method ops.DeliveryMethod) (deliveryMethod, bool) { + switch method { + case ops.DeliveryNetworkBoot: + return networkBoot{k.Config}, true + case ops.DeliveryVirtualMedia: + return virtualMedia{k.Config}, true + } + return nil, false +} + func (k Wipe) Check(_ context.Context, work *site.Work) *custody.Refusal { if conn(work) == nil { return &custody.Refusal{Reason: ReasonUnsupportedTarget, Message: "this site does not reach the server over Redfish"} @@ -228,7 +299,15 @@ func contains(list []string, value string) bool { } func (k Installation) Run(ctx context.Context, work *site.Work) (any, error) { - steps, err := k.run(ctx, work, installPhases) + var spec ops.DeviceInstallationSpec + if err := json.Unmarshal(work.Inputs, &spec); err != nil { + return nil, &custody.Refusal{Reason: ReasonInputs, Message: "the admitted inputs are not a DeviceInstallation spec"} + } + method, ok := k.method(spec.Delivery.Method) + if !ok { + return nil, &custody.Refusal{Reason: custody.ReasonDeliveryInputs, Message: "this site runs no worker for the delivery method"} + } + steps, err := method.install(ctx, work, spec) if err != nil { return nil, err } diff --git a/internal/site/redfishwork/kinds_test.go b/internal/site/redfishwork/kinds_test.go index 288313e6..252f8f44 100644 --- a/internal/site/redfishwork/kinds_test.go +++ b/internal/site/redfishwork/kinds_test.go @@ -363,7 +363,7 @@ func assignment(l *lab, kind, uid string, fence int64, spec any) site.Assignment } func installSpec() ops.DeviceInstallationSpec { - return ops.DeviceInstallationSpec{Image: ops.ImageInput{Name: "debian-12", Digest: "sha256:" + strings.Repeat("a", 64)}, BootInterface: "primary", TargetDisks: []string{"disk-0"}} + return ops.DeviceInstallationSpec{Image: ops.ImageInput{Name: "debian-12", Digest: "sha256:" + strings.Repeat("a", 64)}, BootInterface: "primary", TargetDisks: []string{"disk-0"}, Delivery: ops.DeliveryInput{Method: ops.DeliveryNetworkBoot}} } func TestInstallationRunsBothPhasesWithOneOnEach(t *testing.T) { @@ -385,6 +385,24 @@ func TestInstallationRunsBothPhasesWithOneOnEach(t *testing.T) { } } +// TestNetworkBootNeedsNoWorkerIdentity runs a network boot install and a +// wipe while the site worker's media identity cannot be read: neither reads +// it, and both succeed. +func TestNetworkBootNeedsNoWorkerIdentity(t *testing.T) { + l := newLab(t) + r := runner(t, l) + access := r.Access.(site.RedfishAccess) + access.MediaIdentity = failingIdentity{} + r.Access = access + if result, err := r.Run(context.Background(), assignment(l, "DeviceInstallation", "op-nb-identity", 1, installSpec())); err != nil || result.Phase != ops.PhaseSucceeded { + t.Fatalf("install = %+v, %v", result, err) + } + spec := ops.DeviceWipeSpec{Step: 1, CleaningPolicyDigest: "sha256:" + strings.Repeat("b", 64), TargetDisks: []string{"disk-0"}, BootInterface: "primary"} + if result, err := r.Run(context.Background(), assignment(l, "DeviceWipe", "op-wipe-identity", 2, spec)); err != nil || result.Phase != ops.PhaseSucceeded { + t.Fatalf("wipe = %+v, %v", result, err) + } +} + func TestWipeChecksTheEnrolledDisk(t *testing.T) { l := newLab(t) r := runner(t, l) diff --git a/internal/site/redfishwork/media.go b/internal/site/redfishwork/media.go new file mode 100644 index 00000000..6435a90c --- /dev/null +++ b/internal/site/redfishwork/media.go @@ -0,0 +1,835 @@ +package redfishwork + +import ( + "bytes" + "context" + "crypto/rand" + "crypto/sha256" + "crypto/tls" + "crypto/x509" + "encoding/base64" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "os" + "path/filepath" + "slices" + "strings" + "time" + + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + "go.datum.net/fleet/internal/custody" + "go.datum.net/fleet/internal/redfish" + "go.datum.net/fleet/internal/site" +) + +// Virtual media delivery: the BMC mounts a boot medium and a config medium +// from the central media service and boots from them once. The installed OS +// posts its install report to the media service at first boot. The worker +// opens the operation's window under the Device's fence, which the media +// service checks against custody, and proves before the operation ends that +// no medium, override, window or transfer remains. The site store keeps +// only digests, except the rendered config medium and its URL capability, +// which it deletes when the window closes. + +const ( + // mediaRecords holds each operation's window digests at the site. + mediaRecords = "media" + // mediaConfigs holds each operation's rendered config medium and URL + // capability until its window closes. + mediaConfigs = "mediacfg" + // configMediumSize is the config medium's size: four CD sectors. + configMediumSize = 8192 + // mediaBootTarget is the Redfish boot override target for virtual + // media. + mediaBootTarget = "Cd" +) + +// mediaWindow is the site's record of one operation's window: what the +// installer must report and how the BMC's readback must look, as digests. +type mediaWindow struct { + Operation string `json:"operation"` + Fence int64 `json:"fence"` + BootDigest string `json:"bootDigest"` + // TokenSHA256 is the digest of the report token on the config medium. + TokenSHA256 string `json:"tokenSHA256"` + // Image is the content digest the boot medium must report: its + // manifest of the kernel and initrd. Bootstrap is the salted digest the + // installer must report for the payload it read back from disk. + Image string `json:"image"` + Bootstrap string `json:"bootstrap"` + // BootURLSHA256 and ConfigURLSHA256 compare the BMC's readback of each + // device's URL without recording the URLs. + BootURLSHA256 string `json:"bootURLSHA256"` + ConfigURLSHA256 string `json:"configURLSHA256"` + FetchExpires time.Time `json:"fetchExpires"` + ReportExpires time.Time `json:"reportExpires"` +} + +// configMedium is a rendered config medium and its URL capability. +type configMedium struct { + Data []byte `json:"data"` + Capability string `json:"capability"` +} + +func digest(value string) string { + sum := sha256.Sum256([]byte(value)) + return hex.EncodeToString(sum[:]) +} + +// mediaPlan is what the worker derives from the admitted inputs and the +// pinned artifacts before it sends anything. +type mediaPlan struct { + origin string + bootDigest string + // image is the digest of the boot medium's content manifest. + image string + fetch time.Duration + report time.Duration + downloads []ops.DownloadInput + addresses ops.AddressMode +} + +// planMedia checks the admitted inputs against the site's pinned artifacts +// and reads the boot medium's digest from their manifest. Nothing after +// admission can change which medium boots or where it comes from. +func (c Config) planMedia(spec ops.DeviceInstallationSpec) (mediaPlan, error) { + delivery := spec.Delivery + origin, err := redfish.ParseEndpoint(delivery.MediaService) + if err != nil || !strings.HasPrefix(origin, "https://") || delivery.FetchWindow == nil || delivery.ReportWindow == nil || delivery.FetchWindow.Duration <= 0 || delivery.ReportWindow.Duration <= 0 { + return mediaPlan{}, errors.New("the virtual media inputs name no https media service or phase windows") + } + identity, err := redfish.VerifyArtifacts(c.Artifacts) + if err != nil || identity != spec.Image.Name+"@"+spec.Image.Digest { + return mediaPlan{}, errors.New("the site's artifacts are not the admitted image") + } + manifest, err := os.ReadFile(filepath.Join(c.Artifacts, "SHA256SUMS")) + if err != nil { + return mediaPlan{}, err + } + plan := mediaPlan{origin: origin, fetch: delivery.FetchWindow.Duration, report: delivery.ReportWindow.Duration, downloads: spec.Image.Downloads, addresses: delivery.Addresses} + var content strings.Builder + for _, line := range strings.Split(strings.TrimSpace(string(manifest)), "\n") { + fields := strings.Fields(line) + if fields[1] == "boot.iso" { + plan.bootDigest = fields[0] + } else { + content.WriteString(line + "\n") + } + } + plan.image = "sha256:" + digest(content.String()) + return plan, nil +} + +// checkMedia refuses, before anything is sent, a virtual media installation +// this site cannot deliver. +func (c Config) checkMedia(ctx context.Context, work *site.Work, spec ops.DeviceInstallationSpec) *custody.Refusal { + switch { + case len(c.MediaCA) == 0: + return &custody.Refusal{Reason: ReasonUnsupportedTarget, Message: "this site has no trust for a media service"} + case len(c.ReportFrom) == 0: + return &custody.Refusal{Reason: ReasonUnsupportedTarget, Message: "this site declares no address its installed servers report from"} + case spec.BootNetwork != nil || spec.Delivery.Addresses != ops.AddressesDataNetwork: + return &custody.Refusal{Reason: custody.ReasonDeliveryInputs, Message: "a virtual media installation carries no boot network and the DataNetwork address mode"} + } + if _, err := c.planMedia(spec); err != nil { + return &custody.Refusal{Reason: ReasonInputs, Message: err.Error()} + } + // Only virtual media reads the site worker's media service identity. + if _, err := conn(work).MediaClient(ctx); err != nil { + return &custody.Refusal{Reason: site.ReasonCredentialMissing, Message: "the site worker's media service client certificate is unreadable"} + } + if refusal := checkTarget(work, spec.TargetDisks, mediaPhases); refusal != nil { + return refusal + } + devices, err := conn(work).VirtualMedia(ctx) + if err != nil { + return &custody.Refusal{Reason: ReasonUnsupportedTarget, Message: "the BMC's virtual media could not be read"} + } + if _, _, ok := mediaDevices(devices); !ok { + return &custody.Refusal{Reason: ReasonUnsupportedTarget, Message: "the BMC offers no two CD devices with insert and eject"} + } + return nil +} + +// mediaPhases are the boots of a virtual media installation, for the +// capability checks: the installer from media, then the installed disk. +var mediaPhases = []phase{{"media-installer", mediaBootTarget, "", "install"}, {"disk", "Hdd", "", ""}} + +// mediaDevices picks the boot and config devices: the first two, by Id, +// that accept a CD and offer both actions. +func mediaDevices(devices []redfish.Media) (boot, config redfish.Media, ok bool) { + var usable []redfish.Media + for _, device := range devices { + if slices.Contains(device.MediaTypes, "CD") && device.CanInsert() && device.CanEject() { + usable = append(usable, device) + } + } + slices.SortFunc(usable, func(a, b redfish.Media) int { return strings.Compare(a.ID, b.ID) }) + if len(usable) < 2 { + return redfish.Media{}, redfish.Media{}, false + } + return usable[0], usable[1], true +} + +// renderConfig renders the config medium in the format the lab image reads: +// a text block padded with zeros. It carries the report token and salt, how +// the OS gets its addresses, the pinned downloads, and where the installed +// OS posts its report with the certificate it must verify there. +func renderConfig(token, salt string, bootstrap []byte, plan mediaPlan, reportURL string, reportCA []byte) ([]byte, error) { + var b strings.Builder + fmt.Fprintf(&b, "FLEET-CONFIG-V1\ntoken=%s\nsalt=%s\naddresses=%s\nbootstrap=%s\nreport=%s\nreportca=%s\n", token, salt, plan.addresses, + base64.StdEncoding.EncodeToString(bootstrap), reportURL, base64.StdEncoding.EncodeToString(reportCA)) + for _, download := range plan.downloads { + fmt.Fprintf(&b, "download=%s %s\n", download.Name, download.Reference) + } + b.WriteString("end\n") + if b.Len() > configMediumSize { + return nil, errors.New("the config medium does not fit") + } + data := make([]byte, configMediumSize) + copy(data, b.String()) + return data, nil +} + +// SaltedDigest is the digest the installer reports for the bootstrap +// payload it read back: SHA-256 over the salt, a newline, and the payload. +func SaltedDigest(salt string, payload []byte) string { + sum := sha256.Sum256(append([]byte(salt+"\n"), payload...)) + return "sha256:" + hex.EncodeToString(sum[:]) +} + +func random() (string, error) { + b := make([]byte, 32) + if _, err := rand.Read(b); err != nil { + return "", err + } + return hex.EncodeToString(b), nil +} + +// BootMediumURL is where the media service serves the boot medium through +// one operation's window. +func BootMediumURL(origin, key, bootDigest string) string { + return origin + "/media/" + key + "/boot/" + bootDigest + "/boot.iso" +} + +// ConfigMediumURL is where the media service serves one operation's config +// medium. The capability is the only secret in it. +func ConfigMediumURL(origin, key, capability string) string { + return origin + "/media/" + key + "/config/" + capability + "/config.img" +} + +// ReportURL is where the installed OS posts its install report. +func ReportURL(origin, key string) string { return origin + "/report/" + key } + +// mediaClient is the worker's client of the central media service. It +// verifies the service against the site's trust, never follows redirects +// and uses no environment proxy. +type mediaClient struct { + origin string + http *http.Client +} + +func (c Config) mediaClient(origin string, identity *tls.Certificate) (*mediaClient, error) { + pool := x509.NewCertPool() + if !pool.AppendCertsFromPEM(c.MediaCA) { + return nil, errors.New("the site's media service trust is not a PEM certificate") + } + config := &tls.Config{RootCAs: pool, MinVersion: tls.VersionTLS12} + // The site worker's client certificate is its identity at the media + // service. Without one, the service refuses every window. + if identity != nil { + config.Certificates = []tls.Certificate{*identity} + } + transport := &http.Transport{TLSClientConfig: config} + return &mediaClient{origin: origin, http: &http.Client{Timeout: 30 * time.Second, Transport: transport, + CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}}, nil +} + +func (m *mediaClient) do(ctx context.Context, method, path string, body, into any) (int, error) { + var reader io.Reader + if body != nil { + data, err := json.Marshal(body) + if err != nil { + return 0, err + } + reader = bytes.NewReader(data) + } + request, err := http.NewRequestWithContext(ctx, method, m.origin+path, reader) + if err != nil { + return 0, err + } + response, err := m.http.Do(request) + if err != nil { + return 0, errors.New("the media service could not be reached") + } + defer response.Body.Close() + if into != nil && response.StatusCode < 300 { + if err := json.NewDecoder(io.LimitReader(response.Body, 64<<10)).Decode(into); err != nil { + return response.StatusCode, errors.New("the media service's answer is unreadable") + } + } + return response.StatusCode, nil +} + +func (m *mediaClient) open(ctx context.Context, key string, request OpenRequest) error { + code, err := m.do(ctx, http.MethodPut, "/v1/windows/"+key, request, nil) + switch { + case err != nil: + return err + case code == http.StatusConflict: + return ErrMediaStale + case code == http.StatusUnauthorized || code == http.StatusForbidden: + return ErrMediaUnauthorized + case code != http.StatusOK && code != http.StatusCreated: + return fmt.Errorf("the media service refused the window: HTTP %d", code) + } + return nil +} + +func (m *mediaClient) close(ctx context.Context, key string) error { + code, err := m.do(ctx, http.MethodPost, "/v1/windows/"+key+"/close", nil, nil) + if err == nil && code != http.StatusOK && code != http.StatusNotFound { + err = fmt.Errorf("the media service did not close the window: HTTP %d", code) + } + return err +} + +func (m *mediaClient) window(ctx context.Context, key string) (WindowStatus, error) { + var status WindowStatus + code, err := m.do(ctx, http.MethodGet, "/v1/windows/"+key, nil, &status) + if err == nil && code != http.StatusOK { + err = fmt.Errorf("the media service does not report the window: HTTP %d", code) + } + return status, err +} + +func (m *mediaClient) device(ctx context.Context, device string) (DeviceStatus, error) { + var status DeviceStatus + code, err := m.do(ctx, http.MethodGet, "/v1/devices/"+device, nil, &status) + if err == nil && code != http.StatusOK { + err = fmt.Errorf("the media service does not report the Device: HTTP %d", code) + } + return status, err +} + +// window opens the operation's media window once. It renders the config +// medium with a fresh report token and salt and stores it, with the +// window's digests, under the stored fence before anything is sent. The +// open itself is a journaled step; the media service opens it only while +// custody names the operation active at this fence, and answers a replay of +// the same window again. +func (c Config) window(ctx context.Context, work *site.Work, media *mediaClient, plan mediaPlan) (mediaWindow, error) { + store := work.Store() + key := Key(work.Key()) + var window mediaWindow + var medium configMedium + found, err := store.GetRecord(work.Device, mediaRecords, work.Key(), &window) + if err != nil { + return window, err + } + if !found { + capability, err := random() + if err != nil { + return window, err + } + token, err := random() + if err != nil { + return window, err + } + salt, err := random() + if err != nil { + return window, err + } + // The sealed store is not on this branch, so admission refuses + // bootstrap data and the payload is always empty. + var payload []byte + data, err := renderConfig(token, salt, payload, plan, ReportURL(plan.origin, key), c.MediaCA) + if err != nil { + return window, err + } + now := c.now() + window = mediaWindow{Operation: work.Key(), Fence: work.Fence, BootDigest: plan.bootDigest, TokenSHA256: digest(token), Image: plan.image, Bootstrap: SaltedDigest(salt, payload), + BootURLSHA256: digest(BootMediumURL(plan.origin, key, plan.bootDigest)), ConfigURLSHA256: digest(ConfigMediumURL(plan.origin, key, capability)), + FetchExpires: minTime(now.Add(plan.fetch), work.Deadline), ReportExpires: minTime(now.Add(plan.fetch+plan.report), work.Deadline)} + medium = configMedium{Data: data, Capability: capability} + if err := store.PutRecord(work.Device, work.Fence, mediaConfigs, work.Key(), medium); err != nil { + return window, err + } + if err := store.PutRecord(work.Device, work.Fence, mediaRecords, work.Key(), window); err != nil { + return window, err + } + } else if found, err := store.GetRecord(work.Device, mediaConfigs, work.Key(), &medium); err != nil { + return window, err + } else if !found && !work.Journaled("media-window") { + return window, errors.New("the config medium is gone before its window opened") + } + open := func(ctx context.Context) error { + return media.open(ctx, key, OpenRequest{Device: work.Device, Operation: work.Key(), Fence: work.Fence, BootDigest: window.BootDigest, + CapabilitySHA256: digest(medium.Capability), TokenSHA256: window.TokenSHA256, ConfigMedium: medium.Data, + FetchExpires: window.FetchExpires, ReportExpires: window.ReportExpires, ReportFrom: c.reportFrom()}) + } + if err := work.Step(ctx, site.Step{Name: "media-window", Send: open, Idempotent: true}); err != nil { + return mediaWindow{}, err + } + return window, nil +} + +func (c Config) runMedia(ctx context.Context, work *site.Work, spec ops.DeviceInstallationSpec) (steps []ops.StepEvidence, err error) { + plan, err := c.planMedia(spec) + if err != nil { + return nil, &custody.Refusal{Reason: ReasonInputs, Message: err.Error()} + } + identity, err := conn(work).MediaClient(ctx) + if err != nil { + return nil, &custody.Refusal{Reason: site.ReasonCredentialMissing, Message: "the site worker's media service client certificate is unreadable"} + } + media, err := c.mediaClient(plan.origin, identity) + if err != nil { + return nil, &custody.Refusal{Reason: ReasonUnsupportedTarget, Message: err.Error()} + } + window, err := c.window(ctx, work, media, plan) + if errors.Is(err, ErrMediaStale) || errors.Is(err, ErrMediaUnauthorized) { + // The media service refused the window outright, so it holds no + // window. If the journal shows no BMC step either, nothing reached + // the server and the operation fails; any BMC step leaves it + // unknown. + if !bmcStepJournaled(work) { + return nil, &site.Unsent{Refusal: &custody.Refusal{Reason: custody.ReasonMediaWindowRefused, Message: err.Error()}} + } + return nil, err + } + if err != nil { + return nil, err + } + defer func() { + // Every path into an unknown outcome tries to undo delivery: close + // the windows, delete the config medium and eject what is + // inserted. That attempt is never release proof. A worker stopped + // from outside leaves delivery for its replacement, and one a newer + // fence stopped cannot send anything. + if err != nil && (ctx.Err() == nil || site.DeadlinePassed(ctx)) { + undo, cancel := context.WithTimeout(context.WithoutCancel(ctx), 2*time.Minute) + defer cancel() + c.undoMedia(undo, work, media) + } + }() + if at, done := work.JournaledAt("media-installer-done"); done { + steps = append(steps, ops.StepEvidence{Name: "media-installer", CompletedAt: metaNow(at)}) + } else { + if err := c.prepareMedia(ctx, work, media, window, plan.origin); err != nil { + return nil, err + } + // The installer reports nothing itself: it powers the server off. + // What it installed is proven only by the installed OS's report. + if err := c.awaitOff(ctx, work, mediaBootTarget, window.ReportExpires); err != nil { + return nil, err + } + if err := work.Step(ctx, site.Step{Name: "media-installer-done", Send: func(context.Context) error { return nil }, Idempotent: true}); err != nil { + return nil, err + } + steps = append(steps, ops.StepEvidence{Name: "media-installer", CompletedAt: metaNow(c.now())}) + } + if at, done := work.JournaledAt("media-report-verified"); done { + steps = append(steps, ops.StepEvidence{Name: "first-boot-report", CompletedAt: metaNow(at)}) + } else { + if err := c.bootReport(ctx, work, media, window, plan.downloads); err != nil { + return nil, err + } + steps = append(steps, ops.StepEvidence{Name: "first-boot-report", CompletedAt: metaNow(c.now())}) + } + if err := c.releaseMedia(ctx, work, media); err != nil { + return nil, err + } + return append(steps, ops.StepEvidence{Name: "media-release", CompletedAt: metaNow(c.now())}), nil +} + +// insertPayload is the journaled payload of an insert or eject: which +// device, and the digest of the URL, never the URL. +type insertPayload struct { + Device string `json:"device"` + URLSHA256 string `json:"urlSHA256"` +} + +// prepareMedia ejects anything already inserted and reads every device back +// empty, inserts both media and reads both URLs back, then arms a one-time +// boot from media and powers the server on once. +func (c Config) prepareMedia(ctx context.Context, work *site.Work, media *mediaClient, window mediaWindow, origin string) error { + if !work.Journaled("media-insert-boot") { + if err := c.ejectAll(ctx, work, "media-clear-"); err != nil { + return err + } + } + devices, err := conn(work).VirtualMedia(ctx) + if err != nil { + return err + } + boot, config, ok := mediaDevices(devices) + if !ok { + return errors.New("the BMC no longer offers two CD devices") + } + key := Key(work.Key()) + inserts := []struct { + name string + device redfish.Media + url func() (string, error) + sha string + }{ + {"media-insert-boot", boot, func() (string, error) { return BootMediumURL(origin, key, window.BootDigest), nil }, window.BootURLSHA256}, + {"media-insert-config", config, func() (string, error) { + var medium configMedium + if found, err := work.Store().GetRecord(work.Device, mediaConfigs, work.Key(), &medium); err != nil || !found { + return "", errors.New("the config medium is gone: its window closed") + } + return ConfigMediumURL(origin, key, medium.Capability), nil + }, window.ConfigURLSHA256}, + } + for _, insert := range inserts { + device, sha := insert.device, insert.sha + readback := func(ctx context.Context) (bool, error) { + now, err := conn(work).VirtualMedia(ctx) + if err != nil { + return false, err + } + for _, m := range now { + if m.ID == device.ID { + return m.Inserted && digest(m.Image) == sha, nil + } + } + return false, nil + } + if err := work.Step(ctx, site.Step{ + Name: insert.name, + Payload: insertPayload{Device: device.ID, URLSHA256: sha}, + Send: func(ctx context.Context) error { + url, err := insert.url() + if err != nil { + return err + } + return conn(work).InsertMedia(ctx, device, url) + }, + Observe: func(ctx context.Context, _ json.RawMessage) (bool, error) { return readback(ctx) }, + }); err != nil { + return err + } + // HTTP success is not the effect: the BMC must report the URL. + if inserted, err := readback(ctx); err != nil { + return err + } else if !inserted { + return fmt.Errorf("the BMC does not report the %s medium inserted", strings.TrimPrefix(insert.name, "media-insert-")) + } + } + requested := work.Journaled("media-installer-power-on") + if err := work.Step(ctx, site.Step{Name: "media-installer-power-off", Send: func(ctx context.Context) error { return c.powerOff(ctx, work) }, Idempotent: true}); err != nil { + return err + } + if !requested && !c.now().Before(window.FetchExpires) { + // The BMC must still be able to fetch when it boots. + return errors.New("the media fetch window ended before the boot") + } + if err := work.Step(ctx, site.Step{Name: "media-installer-arm", Send: func(ctx context.Context) error { return conn(work).SetBootOnce(ctx, mediaBootTarget) }, Idempotent: true}); err != nil { + return err + } + // Power on is sent once. After a lost response any sign that the boot + // began counts, and no sign leaves the outcome unknown. + return work.Step(ctx, site.Step{ + Name: "media-installer-power-on", + Payload: powerOn{RequestedAt: c.now().UTC()}, + Send: func(ctx context.Context) error { return conn(work).Reset(ctx, "On") }, + Observe: func(ctx context.Context, _ json.RawMessage) (bool, error) { + return c.bootStarted(ctx, work, mediaBootTarget, media, key) + }, + }) +} + +// bootStarted reports whether a requested boot may have begun: power not +// off, the override consumed, or a report taken. +func (c Config) bootStarted(ctx context.Context, work *site.Work, target string, media *mediaClient, key string) (bool, error) { + power, err := conn(work).Observe(ctx) + if err != nil { + return false, err + } + status, err := media.window(ctx, key) + if err != nil { + return false, err + } + return power.State != "Off" || power.OverrideEnabled != "Once" || power.OverrideTarget != target || status.Report != nil, nil +} + +// awaitOff waits, before the deadline, until the boot requested from target +// began and the server is off again. A BMC may report Off, or the armed +// override, for a while after it accepted the power-on, so Off counts only +// once the server was seen on or the override consumed. The BMC may be +// unreadable for a bounded time. +func (c Config) awaitOff(ctx context.Context, work *site.Work, target string, until time.Time) error { + poll, _, outage, _ := c.durations() + var failingSince time.Time + began := false + for { + power, err := conn(work).Observe(ctx) + switch { + case errors.Is(err, redfish.ErrIdentity): + return err + case err != nil: + if failingSince.IsZero() { + failingSince = c.now() + } + if c.now().Sub(failingSince) > outage { + return fmt.Errorf("the BMC was unreadable while the installer ran: %w", err) + } + default: + failingSince = time.Time{} + began = began || power.State != "Off" || power.OverrideEnabled != "Once" || power.OverrideTarget != target + if began && power.State == "Off" { + return nil + } + } + if !c.now().Before(until) { + return errors.New("the installer did not finish before the report deadline") + } + if err := sleep(ctx, poll); err != nil { + return err + } + } +} + +// bootReport boots the installed disk once and waits for its first-boot +// report at the media service: exactly one report with this operation's +// token, carrying its image and salted bootstrap digests, before the report +// deadline. Another token, no token, a second report or other digests +// never succeed. +func (c Config) bootReport(ctx context.Context, work *site.Work, media *mediaClient, window mediaWindow, downloads []ops.DownloadInput) error { + key := Key(work.Key()) + if err := work.Step(ctx, site.Step{Name: "disk-power-off", Send: func(ctx context.Context) error { return c.powerOff(ctx, work) }, Idempotent: true}); err != nil { + return err + } + if err := work.Step(ctx, site.Step{Name: "disk-arm", Send: func(ctx context.Context) error { return conn(work).SetBootOnce(ctx, "Hdd") }, Idempotent: true}); err != nil { + return err + } + if err := work.Step(ctx, site.Step{ + Name: "disk-power-on", + Payload: powerOn{RequestedAt: c.now().UTC()}, + Send: func(ctx context.Context) error { return conn(work).Reset(ctx, "On") }, + Observe: func(ctx context.Context, _ json.RawMessage) (bool, error) { + return c.bootStarted(ctx, work, "Hdd", media, key) + }, + }); err != nil { + return err + } + poll, _, _, _ := c.durations() + for { + status, err := media.window(ctx, key) + switch { + case err != nil: + // An unreadable media service is retried until the deadline. + case status.Duplicates > 0: + return errors.New("the report token was used more than once") + case status.Report != nil: + if status.Report.Image != window.Image || status.Report.Bootstrap != window.Bootstrap { + return errors.New("the first-boot report does not carry the operation's image and bootstrap digests") + } + if !sameDownloads(status.Report.Downloads, downloads) { + return errors.New("the first-boot report names downloads that are not the operation's pinned inputs") + } + return work.Step(ctx, site.Step{Name: "media-report-verified", Send: func(context.Context) error { return nil }, Idempotent: true}) + } + if !c.now().Before(window.ReportExpires) { + return errors.New("no first-boot report with the operation's token arrived before the report deadline") + } + if err := sleep(ctx, poll); err != nil { + return err + } + } +} + +// ejectAll ejects every device that reports a medium, each as its own +// journaled step, then reads every device back empty. +func (c Config) ejectAll(ctx context.Context, work *site.Work, prefix string) error { + devices, err := conn(work).VirtualMedia(ctx) + if err != nil { + return err + } + for _, device := range devices { + if device.Empty() { + continue + } + if err := work.Step(ctx, site.Step{ + Name: prefix + stepID(device.ID), + Payload: insertPayload{Device: device.ID, URLSHA256: digest(device.Image)}, + Send: func(ctx context.Context) error { return conn(work).EjectMedia(ctx, device) }, + Observe: func(ctx context.Context, _ json.RawMessage) (bool, error) { return deviceEmpty(ctx, work, device.ID) }, + }); err != nil { + return err + } + } + return allEmpty(ctx, work) +} + +func deviceEmpty(ctx context.Context, work *site.Work, id string) (bool, error) { + devices, err := conn(work).VirtualMedia(ctx) + if err != nil { + return false, err + } + for _, device := range devices { + if device.ID == id { + return device.Empty(), nil + } + } + return true, nil +} + +// allEmpty reads every virtual media device back and requires each empty. +func allEmpty(ctx context.Context, work *site.Work) error { + devices, err := conn(work).VirtualMedia(ctx) + if err != nil { + return err + } + for _, device := range devices { + if !device.Empty() { + return fmt.Errorf("virtual media device %s still reports a medium", device.ID) + } + } + return nil +} + +// stepID keeps a BMC device Id usable in a step name. +func stepID(id string) string { + var b strings.Builder + for _, r := range strings.ToLower(id) { + if r >= 'a' && r <= 'z' || r >= '0' && r <= '9' { + b.WriteRune(r) + } + } + out := b.String() + if len(out) > 24 { + out = out[:24] + } + return out +} + +// closeWindows closes, at the media service, every window the site ever +// opened for the Device, not only this operation's, and deletes their +// config media. +func (c Config) closeWindows(ctx context.Context, work *site.Work, media *mediaClient) error { + store := work.Store() + records, err := store.Records(mediaRecords) + if err != nil { + return err + } + for _, record := range records { + if record.Device != work.Device { + continue + } + if err := media.close(ctx, Key(record.Name)); err != nil { + return err + } + if err := store.DeleteRecord(work.Device, mediaConfigs, record.Name); err != nil { + return err + } + } + return nil +} + +// releaseMedia closes every window of the Device and ejects every device, +// then proves release from two independent sources: the BMC reports every +// device empty and no boot override, and the media service reports no open +// window, no transfer in progress and no reused report token for the +// Device. If either cannot be read, release is unproven. +func (c Config) releaseMedia(ctx context.Context, work *site.Work, media *mediaClient) error { + if err := work.Step(ctx, site.Step{Name: "media-close", Send: func(ctx context.Context) error { return c.closeWindows(ctx, work, media) }, Idempotent: true}); err != nil { + return err + } + if err := c.ejectAll(ctx, work, "media-eject-"); err != nil { + return err + } + power, err := conn(work).Observe(ctx) + if err != nil { + return err + } + if power.OverrideEnabled != "Disabled" && power.OverrideTarget != "None" { + return fmt.Errorf("a boot override is still set: %s %s", power.OverrideEnabled, power.OverrideTarget) + } + status, err := media.device(ctx, work.Device) + switch { + case err != nil: + return err + case status.OpenWindows > 0: + return errors.New("a media window of the Device is still open") + case status.OpenTransfers > 0: + return fmt.Errorf("the media service reports %d transfers in progress for the Device", status.OpenTransfers) + case status.Duplicates > 0: + return errors.New("a report token of the Device was used more than once") + } + return work.Step(ctx, site.Step{Name: "media-released", Send: func(context.Context) error { return nil }, Idempotent: true}) +} + +// undoMedia closes what it opened and ejects what is inserted. Its sends +// are journaled steps, so a newer fence stops them. +func (c Config) undoMedia(ctx context.Context, work *site.Work, media *mediaClient) { + _ = work.Step(ctx, site.Step{Name: "media-undo-close", Send: func(ctx context.Context) error { return c.closeWindows(ctx, work, media) }, Idempotent: true}) + devices, err := conn(work).VirtualMedia(ctx) + if err != nil { + return + } + for _, device := range devices { + if device.Empty() { + continue + } + _ = work.Step(ctx, site.Step{Name: "media-undo-eject-" + stepID(device.ID), Send: func(ctx context.Context) error { return conn(work).EjectMedia(ctx, device) }, Idempotent: true}) + } +} + +// minTime is the earlier of a phase's end and the operation's deadline. +func minTime(a, deadline time.Time) time.Time { + if !deadline.IsZero() && deadline.Before(a) { + return deadline.UTC() + } + return a.UTC() +} + +// bmcStepJournaled reports whether the journal holds any step of this +// operation other than opening its media window, the only step that goes to +// the media service rather than the BMC. +func bmcStepJournaled(work *site.Work) bool { + journal, err := work.Store().Journal(work.Device) + if err != nil { + return true + } + for _, entry := range journal { + if entry.Operation == work.Key() && entry.Step != "media-window" { + return true + } + } + return false +} + +func (c Config) reportFrom() []string { + out := make([]string, 0, len(c.ReportFrom)) + for _, prefix := range c.ReportFrom { + out = append(out, prefix.String()) + } + return out +} + +// sameDownloads reports whether the installer reported exactly the recorded +// downloads, each by the digest its reference pins. +func sameDownloads(reported []ReportedDownload, recorded []ops.DownloadInput) bool { + if len(reported) != len(recorded) { + return false + } + want := map[string]string{} + for _, download := range recorded { + _, digest, _ := strings.Cut(download.Reference, "@") + want[download.Name] = digest + } + for _, download := range reported { + if digest, ok := want[download.Name]; !ok || digest != download.Digest { + return false + } + delete(want, download.Name) + } + return len(want) == 0 +} diff --git a/internal/site/redfishwork/media_test.go b/internal/site/redfishwork/media_test.go new file mode 100644 index 00000000..2f9315b7 --- /dev/null +++ b/internal/site/redfishwork/media_test.go @@ -0,0 +1,1041 @@ +package redfishwork + +import ( + "context" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/sha256" + "crypto/tls" + "crypto/x509" + "crypto/x509/pkix" + "encoding/hex" + "encoding/json" + "encoding/pem" + "errors" + "math/big" + "net" + "net/http" + "net/http/httptest" + "net/netip" + neturl "net/url" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + "go.datum.net/fleet/internal/custody" + "go.datum.net/fleet/internal/redfish" + "go.datum.net/fleet/internal/site" +) + +// fakeCustody is the central media service's view of custody: the one +// operation it names active, at its fence. +type fakeCustody struct { + mu sync.Mutex + uid string + fence int64 +} + +func (f *fakeCustody) Active(context.Context, string) (string, int64, bool, error) { + f.mu.Lock() + defer f.mu.Unlock() + return f.uid, f.fence, f.uid != "", nil +} + +func (f *fakeCustody) set(uid string, fence int64) { + f.mu.Lock() + defer f.mu.Unlock() + f.uid, f.fence = uid, fence +} + +// mediaBMC simulates one server behind a TLS Redfish BMC with two virtual +// CD devices. An insert fetches the medium from the central media service, +// as a BMC would. A one-time Cd boot runs the installer, which reads the +// config medium and powers off without reporting; the next disk boot runs +// the installed OS, which posts its report to the media service. +type mediaBMC struct { + mu sync.Mutex + t *testing.T + power string + enabled string + target string + media map[string]string + fetched map[string][]byte + // installed is what the installer wrote for the installed OS. + installed map[string]string + server *httptest.Server + central *MediaServer + requests []string + // onInsert runs as each insert arrives, before its effect. + onInsert func(device string) + // ejectDelay holds the next eject's response past the client timeout + // after applying it, as a lost response. + ejectDelay time.Duration + // ignoreEject keeps media inserted after an eject. + ignoreEject bool + // report replaces fields of the installed OS's report; reports is how + // many times it posts it. + reportToken, reportImage string + reports int + // downloads is what the installer reports it downloaded; extraDownloads + // adds downloads the operation never pinned. + downloads, extraDownloads []ReportedDownload + // lag keeps the server reporting Off, with the override still armed, + // for a while after it accepted a power-on, as some BMCs do. + lag time.Duration +} + +func selfSigned(t *testing.T) tls.Certificate { + t.Helper() + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + template := &x509.Certificate{SerialNumber: big.NewInt(1), NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), IPAddresses: []net.IP{net.ParseIP("127.0.0.1")}} + der, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key) + if err != nil { + t.Fatal(err) + } + return tls.Certificate{Certificate: [][]byte{der}, PrivateKey: key} +} + +func newMediaBMC(t *testing.T, central *MediaServer) *mediaBMC { + t.Helper() + b := &mediaBMC{t: t, power: "Off", enabled: "Disabled", target: "None", media: map[string]string{}, fetched: map[string][]byte{}, installed: map[string]string{}, central: central, reports: 1} + b.server = httptest.NewUnstartedServer(b) + b.server.TLS = &tls.Config{Certificates: []tls.Certificate{selfSigned(t)}} + b.server.StartTLS() + t.Cleanup(b.server.Close) + return b +} + +func (b *mediaBMC) pin() string { + certificate, _ := x509.ParseCertificate(b.server.TLS.Certificates[0].Certificate[0]) + sum := sha256.Sum256(certificate.RawSubjectPublicKeyInfo) + return hex.EncodeToString(sum[:]) +} + +// call sends one request to the central media service from the BMC +// network. +func (b *mediaBMC) call(method, url, body string) ([]byte, int) { + parsed, err := neturl.Parse(url) + if err != nil { + return nil, http.StatusBadRequest + } + request := httptest.NewRequest(method, parsed.Path, strings.NewReader(body)) + request.RemoteAddr = "192.0.2.50:40000" + recorder := httptest.NewRecorder() + b.central.Handler().ServeHTTP(recorder, request) + return recorder.Body.Bytes(), recorder.Code +} + +func (b *mediaBMC) ServeHTTP(w http.ResponseWriter, r *http.Request) { + system := "/redfish/v1/Systems/A" + collection := system + "/VirtualMedia" + b.mu.Lock() + switch { + case r.Method == http.MethodPatch && r.URL.Path == system: + var body struct{ Boot map[string]string } + json.NewDecoder(r.Body).Decode(&body) + b.enabled, b.target = body.Boot["BootSourceOverrideEnabled"], body.Boot["BootSourceOverrideTarget"] + b.requests = append(b.requests, "arm "+b.target) + b.mu.Unlock() + w.WriteHeader(http.StatusNoContent) + return + case r.Method == http.MethodPost && r.URL.Path == system+"/Actions/ComputerSystem.Reset": + var body struct{ ResetType string } + json.NewDecoder(r.Body).Decode(&body) + b.requests = append(b.requests, "reset "+body.ResetType) + switch body.ResetType { + case "ForceOff": + b.power = "Off" + case "On": + target := b.target + if b.lag > 0 { + // The boot starts later, from whatever override is armed then. + go func(lag time.Duration) { + time.Sleep(lag) + b.mu.Lock() + target := b.target + b.power, b.enabled, b.target = "On", "Disabled", "None" + b.mu.Unlock() + b.boot(target) + }(b.lag) + } else { + b.power = "On" + b.enabled, b.target = "Disabled", "None" + go b.boot(target) + } + } + b.mu.Unlock() + w.WriteHeader(http.StatusNoContent) + return + case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/Actions/VirtualMedia.InsertMedia"): + device := strings.TrimSuffix(strings.TrimPrefix(r.URL.Path, collection+"/"), "/Actions/VirtualMedia.InsertMedia") + var body struct{ Image string } + json.NewDecoder(r.Body).Decode(&body) + b.requests = append(b.requests, "insert "+device) + hook := b.onInsert + b.mu.Unlock() + if hook != nil { + hook(device) + } + data, code := b.call(http.MethodGet, body.Image, "") + if code != http.StatusOK { + http.Error(w, "fetch failed", http.StatusBadRequest) + return + } + b.mu.Lock() + b.media[device], b.fetched[device] = body.Image, data + b.mu.Unlock() + w.WriteHeader(http.StatusNoContent) + return + case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/Actions/VirtualMedia.EjectMedia"): + device := strings.TrimSuffix(strings.TrimPrefix(r.URL.Path, collection+"/"), "/Actions/VirtualMedia.EjectMedia") + b.requests = append(b.requests, "eject "+device) + if !b.ignoreEject { + delete(b.media, device) + delete(b.fetched, device) + } + delay := b.ejectDelay + b.ejectDelay = 0 + b.mu.Unlock() + time.Sleep(delay) + w.WriteHeader(http.StatusNoContent) + return + } + docs := map[string]any{ + "/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"}}, + "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"}}}, + } + for _, id := range []string{"CD1", "CD2"} { + path := collection + "/" + id + var image any + if url, ok := b.media[id]; ok { + image = url + } + docs[path] = map[string]any{"@odata.id": path, "Id": id, "MediaTypes": []string{"CD", "DVD"}, "Inserted": image != nil, "Image": image, + "Actions": map[string]any{"#VirtualMedia.InsertMedia": map[string]string{"target": path + "/Actions/VirtualMedia.InsertMedia"}, + "#VirtualMedia.EjectMedia": map[string]string{"target": path + "/Actions/VirtualMedia.EjectMedia"}}} + } + b.mu.Unlock() + doc, ok := docs[strings.TrimSuffix(r.URL.Path, "/")] + if !ok { + w.WriteHeader(http.StatusNotFound) + return + } + json.NewEncoder(w).Encode(doc) +} + +// boot runs the armed boot: a Cd boot is the installer, a disk boot the +// installed OS posting its first-boot report. +func (b *mediaBMC) boot(target string) { + time.Sleep(30 * time.Millisecond) + b.mu.Lock() + switch target { + case "Cd": + values := map[string]string{} + b.downloads = nil + for _, line := range strings.Split(strings.TrimRight(string(b.fetched["CD2"]), "\x00"), "\n") { + if key, value, ok := strings.Cut(line, "="); ok { + values[key] = value + // The installer reports each download by the digest it pins. + if name, reference, ok := strings.Cut(value, " "); key == "download" && ok { + _, pinned, _ := strings.Cut(reference, "@") + b.downloads = append(b.downloads, ReportedDownload{Name: name, Digest: pinned}) + } + } + } + b.downloads = append(b.downloads, b.extraDownloads...) + b.installed = map[string]string{"token": values["token"], "report": values["report"], "bootstrap": SaltedDigest(values["salt"], nil)} + case "Hdd": + token, image := b.installed["token"], b.central.contentImage(b.t) + if b.reportToken != "" { + token = b.reportToken + } + if b.reportImage != "" { + image = b.reportImage + } + report, _ := json.Marshal(InstallReport{Token: token, Image: image, Bootstrap: b.installed["bootstrap"], Downloads: b.downloads}) + url, n := b.installed["report"], b.reports + b.mu.Unlock() + for i := range n { + b.call(http.MethodPost, url, string(report)) + // A retry of the same report changes nothing; a later report + // with the same token is a second install. + b.call(http.MethodPost, url, string(report)) + if i == 0 { + report, _ = json.Marshal(InstallReport{Token: token, Image: image, Bootstrap: "sha256:" + strings.Repeat("0", 64)}) + } + } + b.mu.Lock() + } + b.power = "Off" + b.mu.Unlock() +} + +// contentImage is the digest the boot medium's manifest reports. +func (m *MediaServer) contentImage(t *testing.T) string { + data, err := os.ReadFile(filepath.Join(m.Artifacts, "SHA256SUMS")) + if err != nil { + t.Fatal(err) + } + lines := strings.SplitAfter(string(data), "\n") + return "sha256:" + digest(lines[0]+lines[1]) +} + +func (b *mediaBMC) log() []string { + b.mu.Lock() + defer b.mu.Unlock() + return append([]string(nil), b.requests...) +} + +// artifacts writes a synthetic image: its kernel, initrd and boot medium, +// and their manifest. +func artifacts(t *testing.T) (string, ops.ImageInput) { + t.Helper() + dir := t.TempDir() + var manifest strings.Builder + for _, name := range redfish.Artifacts { + data := []byte("synthetic " + name) + if err := os.WriteFile(filepath.Join(dir, name), data, 0o600); err != nil { + t.Fatal(err) + } + sum := sha256.Sum256(data) + manifest.WriteString(hex.EncodeToString(sum[:]) + " " + name + "\n") + } + if err := os.WriteFile(filepath.Join(dir, "SHA256SUMS"), []byte(manifest.String()), 0o600); err != nil { + t.Fatal(err) + } + identity, err := redfish.VerifyArtifacts(dir) + if err != nil { + t.Fatal(err) + } + name, value, _ := strings.Cut(identity, "@") + return dir, ops.ImageInput{Name: name, Digest: value} +} + +type mediaEnv struct { + bmc *mediaBMC + central *MediaServer + custody *fakeCustody + runner *site.Runner + store *site.Store + image ops.ImageInput + origin string + fetch time.Duration + report time.Duration + workers *workerCA + // downloads are the installer downloads the operation pins. + downloads []ops.DownloadInput +} + +func newMediaEnv(t *testing.T) *mediaEnv { + t.Helper() + root := t.TempDir() + if err := os.Chmod(root, 0o700); err != nil { + t.Fatal(err) + } + store, err := site.OpenStore(root, nil) + if err != nil { + t.Fatal(err) + } + dir, image := artifacts(t) + custodyView := &fakeCustody{} + central := &MediaServer{Root: t.TempDir(), Artifacts: dir, Custody: custodyView, Clients: []netip.Prefix{netip.MustParsePrefix("192.0.2.0/24"), netip.MustParsePrefix("127.0.0.0/8")}, + Workers: func(identity, d string) bool { return identity == workerIdentity && d == device }} + // The worker reaches the central service over TLS it verifies, and + // presents its client certificate from the workers' CA. + certificate := selfSigned(t) + workers := newWorkerCA(t) + api := httptest.NewUnstartedServer(central.Handler()) + api.TLS = &tls.Config{Certificates: []tls.Certificate{certificate}, ClientAuth: tls.VerifyClientCertIfGiven, ClientCAs: workers.pool} + api.StartTLS() + t.Cleanup(api.Close) + ca := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certificate.Certificate[0]}) + b := newMediaBMC(t, central) + // Installed servers report from the BMC network address the fake uses. + config := Config{ConsoleRoot: t.TempDir(), BootRoot: t.TempDir(), Poll: 10 * time.Millisecond, OffGrace: time.Second, MediaCA: ca, Artifacts: dir, + ReportFrom: []netip.Prefix{netip.MustParsePrefix("192.0.2.50/32")}} + runner := &site.Runner{ + Site: "site-example-a", Store: store, Results: site.NewResults(store), + Access: site.RedfishAccess{Credentials: credentials{pin: b.pin()}, MediaIdentity: &mediaIdentity{identity: workers.issue(t, workerIdentity)}, + Targets: site.StaticTargets{device: {Device: "server-example-001", Endpoint: b.server.URL, SystemID: "A", SystemUUID: uuid, DiskBytes: diskBytes, Console: "console.log"}}, + // A short client timeout makes a withheld response a lost one. + Dial: func(endpoint, username, password, pin string) (*redfish.Client, error) { + return redfish.NewPinnedClient(endpoint, username, password, pin, time.Second) + }}, + Kinds: map[string]site.Kind{"DeviceInstallation": Installation{config}}, + Poll: 10 * time.Millisecond, + } + return &mediaEnv{bmc: b, central: central, custody: custodyView, runner: runner, store: store, image: image, origin: api.URL, fetch: time.Minute, report: time.Minute, workers: workers} +} + +const workerIdentity = "fleet-site-worker:site-example-a" + +// mediaIdentity is the site worker's own media service client certificate. +type mediaIdentity struct { + identity *tls.Certificate +} + +func (c *mediaIdentity) MediaClient(context.Context, string) (*tls.Certificate, error) { + return c.identity, nil +} + +// workerCA issues site worker client certificates. +type workerCA struct { + certificate *x509.Certificate + key *ecdsa.PrivateKey + pool *x509.CertPool +} + +func newWorkerCA(t *testing.T) *workerCA { + t.Helper() + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + template := &x509.Certificate{SerialNumber: big.NewInt(10), Subject: pkix.Name{CommonName: "synthetic-site-workers"}, NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), + IsCA: true, BasicConstraintsValid: true, KeyUsage: x509.KeyUsageCertSign} + der, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key) + if err != nil { + t.Fatal(err) + } + certificate, _ := x509.ParseCertificate(der) + pool := x509.NewCertPool() + pool.AddCert(certificate) + return &workerCA{certificate: certificate, key: key, pool: pool} +} + +func (w *workerCA) issue(t *testing.T, identity string) *tls.Certificate { + t.Helper() + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + template := &x509.Certificate{SerialNumber: big.NewInt(time.Now().UnixNano()), Subject: pkix.Name{CommonName: identity}, NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}, KeyUsage: x509.KeyUsageDigitalSignature} + der, err := x509.CreateCertificate(rand.Reader, template, w.certificate, &key.PublicKey, w.key) + if err != nil { + t.Fatal(err) + } + return &tls.Certificate{Certificate: [][]byte{der}, PrivateKey: key} +} + +// asWorker marks a direct handler request as presented with a verified +// client certificate of the identity. +func (w *workerCA) asWorker(t *testing.T, request *http.Request, identity string) *http.Request { + certificate, _ := x509.ParseCertificate(w.issue(t, identity).Certificate[0]) + request.TLS = &tls.ConnectionState{VerifiedChains: [][]*x509.Certificate{{certificate, w.certificate}}} + return request +} + +func (e *mediaEnv) spec() ops.DeviceInstallationSpec { + image := e.image + image.Downloads = e.downloads + return ops.DeviceInstallationSpec{Image: image, BootInterface: "primary", TargetDisks: []string{"disk-0"}, RequestUID: "request-1", + Delivery: ops.DeliveryInput{Method: ops.DeliveryVirtualMedia, Addresses: ops.AddressesDataNetwork, MediaService: e.origin, + FetchWindow: &metav1.Duration{Duration: e.fetch}, ReportWindow: &metav1.Duration{Duration: e.report}}} +} + +// assignment admits the operation: custody names it active at its fence. +func (e *mediaEnv) assignment(uid string, fence int64) site.Assignment { + e.custody.set(uid, fence) + inputs, _ := json.Marshal(e.spec()) + sum := sha256.Sum256(inputs) + return site.Assignment{ + Device: device, Operation: ops.OperationReference{Kind: "DeviceInstallation", Name: "alloc-example-" + uid, UID: uid}, Fence: fence, AdmittedAt: time.Now(), Deadline: time.Now().Add(time.Minute), + Snapshot: ops.DeviceSnapshot{BMCEndpoint: e.bmc.server.URL, SystemUUID: uuid, BMCPublicKeySHA256: e.bmc.pin()}, + InputDigest: "sha256:" + hex.EncodeToString(sum[:]), Inputs: inputs, + } +} + +func (e *mediaEnv) window(t *testing.T, uid string) Window { + t.Helper() + window, found, err := e.central.load(Key(uid)) + if err != nil || !found { + t.Fatalf("window: %v, %v", found, err) + } + return window +} + +func (e *mediaEnv) journaled(uid string) map[string]site.StepState { + journal, _ := e.store.Journal(device) + out := map[string]site.StepState{} + for _, entry := range journal { + if entry.Operation == uid { + out[entry.Step] = entry.State + } + } + return out +} + +func (e *mediaEnv) run(t *testing.T, uid string, fence int64) custody.SiteResult { + t.Helper() + result, err := e.runner.Run(context.Background(), e.assignment(uid, fence)) + if err != nil { + t.Fatal(err) + } + return result +} + +func TestAVirtualMediaInstallIsProvenByItsFirstBootReport(t *testing.T) { + e := newMediaEnv(t) + result := e.run(t, "op-media", 1) + if result.Phase != ops.PhaseSucceeded { + t.Fatalf("result = %+v", result) + } + var evidence ops.InstallationEvidence + if err := json.Unmarshal(result.Evidence, &evidence); err != nil || len(evidence.Steps) != 3 || evidence.Steps[0].Name != "media-installer" || evidence.Steps[1].Name != "first-boot-report" || evidence.Steps[2].Name != "media-release" { + t.Fatalf("evidence = %s", result.Evidence) + } + // The server is already off before each boot, so no ForceOff is sent. + want := []string{"insert CD1", "insert CD2", "arm Cd", "reset On", "arm Hdd", "reset On", "eject CD1", "eject CD2"} + if got := e.bmc.log(); strings.Join(got, ",") != strings.Join(want, ",") { + t.Fatalf("BMC requests = %v, want %v", got, want) + } + // Release: no medium or override at the BMC; at the media service the + // window is closed, its medium dropped, its transfers ended and its + // one report taken. + if len(e.bmc.media) != 0 || e.bmc.enabled != "Disabled" { + t.Fatalf("BMC after release: media %v, override %s", e.bmc.media, e.bmc.enabled) + } + window := e.window(t, "op-media") + if !window.Closed || window.ConfigMedium != nil || window.Report == nil || window.Duplicates != 0 || window.Rejected != 0 { + t.Fatalf("window = %+v", window) + } + transfers, err := e.central.Transfers(Key("op-media")) + if err != nil || len(transfers) != 2 || !transfers[0].Complete || !transfers[1].Complete { + t.Fatalf("transfers = %+v, %v", transfers, err) + } + if found, _ := e.store.GetRecord(device, mediaConfigs, "op-media", &configMedium{}); found { + t.Fatal("the rendered config medium outlived its window") + } + if steps := e.journaled("op-media"); steps["media-released"] != site.StepDone || steps["media-report-verified"] != site.StepDone { + t.Fatalf("journal = %v", steps) + } + // Records keep digests only: neither the journal, the site's window + // record, the media service's window nor the evidence holds the token. + token := e.bmc.installed["token"] + journal, _ := json.Marshal(e.journaled("op-media")) + var site mediaWindow + e.store.GetRecord(device, mediaRecords, "op-media", &site) + siteRecord, _ := json.Marshal(site) + central, _ := os.ReadFile(filepath.Join(e.central.Root, "windows", Key("op-media")+".json")) + for _, text := range [][]byte{journal, siteRecord, central, result.Evidence} { + if len(token) != 64 || strings.Contains(string(text), token) { + t.Fatal("a record carries the report token") + } + } + // The closed window serves nothing, even to its BMC. + if _, code := e.bmc.call(http.MethodGet, BootMediumURL(e.origin, Key("op-media"), window.BootDigest), ""); code != http.StatusForbidden { + t.Fatalf("closed window served the boot medium: %d", code) + } +} + +// TestEveryMediaStepIsJournaledBeforeItIsSent checks, as each insert +// reaches the BMC, that the journal already records it as intended. +func TestEveryMediaStepIsJournaledBeforeItIsSent(t *testing.T) { + e := newMediaEnv(t) + seen := map[string]site.StepState{} + e.bmc.onInsert = func(device string) { + name := map[string]string{"CD1": "media-insert-boot", "CD2": "media-insert-config"}[device] + seen[name] = e.journaled("op-journal")[name] + if e.journaled("op-journal")["media-window"] != site.StepDone { + t.Error("a medium was inserted before its window was journaled open") + } + } + if result := e.run(t, "op-journal", 1); result.Phase != ops.PhaseSucceeded { + t.Fatalf("result = %+v", result) + } + if seen["media-insert-boot"] != site.StepIntended || seen["media-insert-config"] != site.StepIntended { + t.Fatalf("journal at each send = %v, want Intended", seen) + } +} + +// TestAStaleFenceCannotPrepareMedia raises the Device's site fence, and +// custody's, while the first insert is in flight. The worker sends nothing +// more, the media service stops serving the window at once, and the +// outcome is unknown. +func TestAStaleFenceCannotPrepareMedia(t *testing.T) { + e := newMediaEnv(t) + var once sync.Once + e.bmc.onInsert = func(string) { + once.Do(func() { + if err := e.store.Raise(device, 2); err != nil { + t.Error(err) + } + e.custody.set("op-newer", 2) + }) + } + if result := e.run(t, "op-stale", 1); result.Phase != ops.PhaseOutcomeUnknown { + t.Fatalf("result = %+v", result) + } + if got := e.bmc.log(); strings.Join(got, ",") != "insert CD1" { + t.Fatalf("BMC requests after the fence rose = %v, want only the first insert", got) + } + if _, code := e.bmc.call(http.MethodGet, BootMediumURL(e.origin, Key("op-stale"), e.window(t, "op-stale").BootDigest), ""); code != http.StatusForbidden { + t.Fatalf("a window custody no longer names served media: %d", code) + } + // A delayed worker at the old fence is refused by the site store. + if _, err := e.runner.Run(context.Background(), e.assignment("op-delayed", 1)); !errors.Is(err, site.ErrStaleFence) { + t.Fatalf("a stale assignment ran: %v", err) + } + if len(e.bmc.log()) != 1 { + t.Fatalf("the stale assignment reached the BMC: %v", e.bmc.log()) + } +} + +// TestTheMediaServiceOpensAWindowOnlyForCustodysOperation has custody name +// another operation: the media service refuses the window, and the worker +// sends nothing to the BMC. +func TestTheMediaServiceOpensAWindowOnlyForCustodysOperation(t *testing.T) { + e := newMediaEnv(t) + assignment := e.assignment("op-unadmitted", 1) + e.custody.set("op-other", 1) + result, err := e.runner.Run(context.Background(), assignment) + if err != nil { + t.Fatal(err) + } + if result.Phase != ops.PhaseFailed || result.Reason != custody.ReasonMediaWindowRefused || len(e.bmc.log()) != 0 { + t.Fatalf("result = %+v, BMC %v", result, e.bmc.log()) + } + if _, found, _ := e.central.load(Key("op-unadmitted")); found { + t.Fatal("the media service opened a window custody does not name") + } +} + +// TestALostEjectResponseEndsUnknown withholds the response to the first +// release eject past the client timeout. The eject took effect, but the +// worker cannot prove it, so the outcome is unknown and never Succeeded. +func TestALostEjectResponseEndsUnknown(t *testing.T) { + e := newMediaEnv(t) + go func() { + for range 1000 { + if e.journaled("op-lost")["media-report-verified"] == site.StepDone { + e.bmc.mu.Lock() + e.bmc.ejectDelay = 2 * time.Second + e.bmc.mu.Unlock() + return + } + time.Sleep(2 * time.Millisecond) + } + }() + result := e.run(t, "op-lost", 1) + if result.Phase != ops.PhaseOutcomeUnknown || result.Reason != site.ReasonStep { + t.Fatalf("result = %+v", result) + } + if steps := e.journaled("op-lost"); steps["media-released"] != "" || steps["media-eject-cd1"] != site.StepIntended { + t.Fatalf("journal = %v", steps) + } + // The undo closed the window; that is never proof. + if !e.window(t, "op-lost").Closed { + t.Fatal("the undo left the window open") + } +} + +// TestMediaStillReportedAfterEjectIsUnproven keeps the media inserted +// after every eject. +func TestMediaStillReportedAfterEjectIsUnproven(t *testing.T) { + e := newMediaEnv(t) + e.bmc.ignoreEject = true + if result := e.run(t, "op-stuck", 1); result.Phase != ops.PhaseOutcomeUnknown || e.journaled("op-stuck")["media-released"] != "" { + t.Fatalf("result = %+v", result) + } +} + +// TestAFirstBootReportThatDoesNotProveTheInstallNeverSucceeds covers every +// report the media service must not count: another token, none at all, +// another image, and the token used twice. +func TestAFirstBootReportThatDoesNotProveTheInstallNeverSucceeds(t *testing.T) { + for name, set := range map[string]func(*mediaBMC){ + "another token": func(b *mediaBMC) { b.reportToken = strings.Repeat("e", 64) }, + "no report": func(b *mediaBMC) { b.reports = 0 }, + "another image": func(b *mediaBMC) { b.reportImage = "sha256:" + strings.Repeat("f", 64) }, + "a second use": func(b *mediaBMC) { b.reports = 2 }, + } { + t.Run(name, func(t *testing.T) { + e := newMediaEnv(t) + e.fetch, e.report = 500*time.Millisecond, 300*time.Millisecond + set(e.bmc) + result := e.run(t, "op-report", 1) + if result.Phase != ops.PhaseOutcomeUnknown || e.journaled("op-report")["media-released"] != "" { + t.Fatalf("result = %+v, journal %v", result, e.journaled("op-report")) + } + // The failed operation still tried to undo delivery. + if !e.window(t, "op-report").Closed { + t.Fatal("the window stayed open after the failure") + } + }) + } +} + +// TestTheMediaServiceServesAndReportsOnlyThroughAnOpenWindow probes the +// service directly. +func TestTheMediaServiceServesAndReportsOnlyThroughAnOpenWindow(t *testing.T) { + e := newMediaEnv(t) + now := time.Now() + e.central.Now = func() time.Time { return now } + capability, token := strings.Repeat("c", 64), strings.Repeat("d", 64) + e.custody.set("op-serve", 1) + call := func(method, path, body, from string) int { + request := httptest.NewRequest(method, path, strings.NewReader(body)) + request.RemoteAddr = from + if strings.HasPrefix(path, "/v1/") { + e.workers.asWorker(t, request, workerIdentity) + } + recorder := httptest.NewRecorder() + e.central.Handler().ServeHTTP(recorder, request) + return recorder.Code + } + open, _ := json.Marshal(OpenRequest{Device: device, Operation: "op-serve", Fence: 1, BootDigest: strings.Repeat("b", 64), CapabilitySHA256: digest(capability), TokenSHA256: digest(token), + ConfigMedium: []byte("medium"), FetchExpires: now.Add(time.Minute), ReportExpires: now.Add(2 * time.Minute), ReportFrom: []string{"192.0.2.60/32"}}) + key := Key("op-serve") + if code := call(http.MethodPut, "/v1/windows/"+key, string(open), "127.0.0.1:1"); code != http.StatusCreated { + t.Fatalf("open = %d", code) + } + if code := call(http.MethodPut, "/v1/windows/"+key, strings.Replace(string(open), digest(token), digest(capability), 1), "127.0.0.1:1"); code != http.StatusConflict { + t.Fatalf("a second, different open = %d", code) + } + config := "/media/" + key + "/config/" + capability + "/config.img" + if code := call(http.MethodGet, config, "", "192.0.2.50:1"); code != http.StatusOK { + t.Fatalf("the open window's config medium: %d", code) + } + if code := call(http.MethodGet, config, "", "198.51.100.7:1"); code != http.StatusForbidden { + t.Fatalf("a client outside the BMC network was served: %d", code) + } + if code := call(http.MethodGet, "/media/"+key+"/config/"+strings.Repeat("9", 64)+"/config.img", "", "192.0.2.50:1"); code != http.StatusForbidden { + t.Fatalf("another capability was served: %d", code) + } + report := func(body string) int { return call(http.MethodPost, "/report/"+key, body, "192.0.2.60:1") } + if code := report(`{"image":"x"}`); code != http.StatusForbidden { + t.Fatalf("a report with no token = %d", code) + } + if code := report(`{"token":"` + strings.Repeat("e", 64) + `"}`); code != http.StatusForbidden { + t.Fatalf("a report with another token = %d", code) + } + good := `{"token":"` + token + `","image":"sha256:1","bootstrap":"sha256:2"}` + // A report with the right token from an address that is not the + // Machine's is refused for where it came from. + if code := call(http.MethodPost, "/report/"+key, good, "192.0.2.61:1"); code != http.StatusForbidden { + t.Fatalf("a report from another address = %d", code) + } + if window := e.window(t, "op-serve"); window.Report != nil { + t.Fatal("a report from another address was taken") + } + if code := report(good); code != http.StatusOK { + t.Fatalf("the report = %d", code) + } + if code := report(good); code != http.StatusOK { + t.Fatalf("a repeat of the same report = %d", code) + } + if code := report(strings.Replace(good, "sha256:2", "sha256:3", 1)); code != http.StatusConflict { + t.Fatalf("a second, different use of the token = %d", code) + } + window := e.window(t, "op-serve") + if window.Rejected != 3 || window.Duplicates != 1 || window.Report == nil || window.Report.Image != "sha256:1" { + t.Fatalf("window = %+v", window) + } + // Past the fetch deadline the media stop; a fence rise stops everything. + now = now.Add(90 * time.Second) + if code := call(http.MethodGet, config, "", "192.0.2.50:1"); code != http.StatusForbidden { + t.Fatalf("a window past its fetch deadline was served: %d", code) + } + e.custody.set("op-next", 2) + if code := report(good); code != http.StatusForbidden { + t.Fatalf("a report after the fence rose = %d", code) + } +} + +// TestReleaseNeedsTheMediaServiceQuiet checks the media service's half of +// the proof: an open window or an unfinished transfer counts for the +// Device even when the BMC reports empty. +func TestReleaseNeedsTheMediaServiceQuiet(t *testing.T) { + e := newMediaEnv(t) + e.custody.set("op-open", 3) + status := func() DeviceStatus { + request := e.workers.asWorker(t, httptest.NewRequest(http.MethodGet, "/v1/devices/"+device, nil), workerIdentity) + request.RemoteAddr = "127.0.0.1:1" + recorder := httptest.NewRecorder() + e.central.Handler().ServeHTTP(recorder, request) + var out DeviceStatus + json.NewDecoder(recorder.Body).Decode(&out) + return out + } + if err := e.central.save(Key("op-open"), Window{Device: device, Operation: "op-open", Fence: 3, FetchExpires: time.Now().Add(time.Hour), ReportExpires: time.Now().Add(time.Hour)}); err != nil { + t.Fatal(err) + } + if got := status(); got.OpenWindows != 1 { + t.Fatalf("an open window counted as released: %+v", got) + } + if err := appendEvidence(filepath.Join(e.central.Root, "transfers", Key("op-open")), transferLog, "t start 01 boot\n"); err != nil { + t.Fatal(err) + } + e.custody.set("op-next", 4) + if got := status(); got.OpenWindows != 0 || got.OpenTransfers != 1 { + t.Fatalf("a transfer in progress counted as released: %+v", got) + } + // The worker's release reads the same report and stays unproven. + if err := appendEvidence(filepath.Join(e.central.Root, "transfers", Key("op-open")), transferLog, "t end 01 boot bytes=1 complete\n"); err != nil { + t.Fatal(err) + } + if got := status(); got != (DeviceStatus{Windows: 1}) { + t.Fatalf("status = %+v", got) + } +} + +// TestAVirtualMediaSiteRefusesWhatItCannotDeliver refuses, with nothing +// sent, a virtual media installation at a site without media trust, and +// network boot with virtual media inputs or downloads. +func TestAVirtualMediaSiteRefusesWhatItCannotDeliver(t *testing.T) { + e := newMediaEnv(t) + installation := e.runner.Kinds["DeviceInstallation"].(Installation) + installation.MediaCA = nil + e.runner.Kinds["DeviceInstallation"] = installation + result := e.run(t, "op-no-media", 1) + if result.Phase != ops.PhaseFailed || result.Reason != ReasonUnsupportedTarget || len(e.bmc.log()) != 0 { + t.Fatalf("result = %+v, BMC %v", result, e.bmc.log()) + } + if refusal := (networkBoot{}).check(context.Background(), &site.Work{}, ops.DeviceInstallationSpec{Delivery: ops.DeliveryInput{Method: ops.DeliveryNetworkBoot, Addresses: ops.AddressesDataNetwork}}); refusal == nil || refusal.Reason != custody.ReasonDeliveryInputs { + t.Fatalf("network boot with an address mode: %+v", refusal) + } + downloads := ops.DeviceInstallationSpec{Image: ops.ImageInput{Downloads: []ops.DownloadInput{{Name: "installer", Reference: "registry.example/installer@sha256:" + strings.Repeat("a", 64)}}}, + Delivery: ops.DeliveryInput{Method: ops.DeliveryNetworkBoot}} + if refusal := (networkBoot{}).check(context.Background(), &site.Work{}, downloads); refusal == nil || refusal.Reason != ReasonUnsupportedTarget { + t.Fatalf("network boot with downloads: %+v", refusal) + } +} + +// TestTheConfigMediumCarriesPinnedDownloads renders a medium for an image +// whose installer downloads one pinned artifact. +func TestTheConfigMediumCarriesPinnedDownloads(t *testing.T) { + reference := "registry.example/installer@sha256:" + strings.Repeat("a", 64) + data, err := renderConfig(strings.Repeat("1", 64), strings.Repeat("2", 64), nil, mediaPlan{addresses: ops.AddressesDataNetwork, downloads: []ops.DownloadInput{{Name: "installer", Reference: reference}}}, + "https://192.0.2.10:8443/report/0123456789abcdef", []byte("ca")) + if err != nil { + t.Fatal(err) + } + text := strings.TrimRight(string(data), "\x00") + for _, want := range []string{"FLEET-CONFIG-V1\n", "\ndownload=installer " + reference + "\n", "\nreport=https://192.0.2.10:8443/report/0123456789abcdef\n", "\naddresses=DataNetwork\n"} { + if !strings.Contains(text, want) { + t.Fatalf("config medium lacks %q:\n%s", want, text) + } + } +} + +// TestABMCThatReportsOffAfterPowerOnIsWaitedFor keeps the server Off, with +// the override armed, for a while after each power-on. The worker must not +// take that Off as the installer's end. +func TestABMCThatReportsOffAfterPowerOnIsWaitedFor(t *testing.T) { + e := newMediaEnv(t) + e.bmc.lag = 300 * time.Millisecond + if result := e.run(t, "op-lag", 1); result.Phase != ops.PhaseSucceeded { + t.Fatalf("result = %+v", result) + } + want := []string{"insert CD1", "insert CD2", "arm Cd", "reset On", "arm Hdd", "reset On", "eject CD1", "eject CD2"} + if got := e.bmc.log(); strings.Join(got, ",") != strings.Join(want, ",") { + t.Fatalf("BMC requests = %v, want %v", got, want) + } +} + +// TestTheSweepDropsConfigMediaNothingReadsAgain leaves windows open with +// their config media, as a worker that died would: one whose custody moved +// on and one past its report deadline. The sweep drops both media, and so +// their tokens, without any request; a live window keeps its medium. +func TestTheSweepDropsConfigMediaNothingReadsAgain(t *testing.T) { + e := newMediaEnv(t) + e.custody.set("op-live", 3) + for uid, window := range map[string]Window{ + "op-dead": {Device: device, Operation: "op-dead", Fence: 1, ConfigMedium: []byte("token=one"), FetchExpires: time.Now().Add(time.Hour), ReportExpires: time.Now().Add(time.Hour)}, + "op-expired": {Device: device, Operation: "op-live", Fence: 3, ConfigMedium: []byte("token=two"), FetchExpires: time.Now().Add(-time.Hour), ReportExpires: time.Now().Add(-time.Minute)}, + "op-live": {Device: device, Operation: "op-live", Fence: 3, ConfigMedium: []byte("token=three"), FetchExpires: time.Now().Add(time.Hour), ReportExpires: time.Now().Add(time.Hour)}, + } { + if err := e.central.save(Key(uid), window); err != nil { + t.Fatal(err) + } + } + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + go e.central.RunSweeps(ctx, 10*time.Millisecond, func(err error) { t.Error(err) }) + deadline := time.Now().Add(5 * time.Second) + for { + dead, _, _ := e.central.load(Key("op-dead")) + expired, _, _ := e.central.load(Key("op-expired")) + if dead.ConfigMedium == nil && expired.ConfigMedium == nil { + break + } + if time.Now().After(deadline) { + t.Fatal("the sweep left a config medium no window can serve") + } + time.Sleep(10 * time.Millisecond) + } + if live, _, _ := e.central.load(Key("op-live")); live.ConfigMedium == nil { + t.Fatal("the sweep dropped a live window's config medium") + } +} + +// TestTheWorkerAPIRequiresTheSiteWorkersIdentity calls every worker API +// endpoint with no client certificate and with another site's: each is +// refused, and nothing is opened. +func TestTheWorkerAPIRequiresTheSiteWorkersIdentity(t *testing.T) { + e := newMediaEnv(t) + e.custody.set("op-auth", 1) + key := Key("op-auth") + open, _ := json.Marshal(OpenRequest{Device: device, Operation: "op-auth", Fence: 1, BootDigest: strings.Repeat("b", 64), CapabilitySHA256: digest("c"), TokenSHA256: digest("t"), + ConfigMedium: []byte("medium"), FetchExpires: time.Now().Add(time.Minute), ReportExpires: time.Now().Add(2 * time.Minute), ReportFrom: []string{"192.0.2.50/32"}}) + call := func(method, path, body, identity string) int { + request := httptest.NewRequest(method, path, strings.NewReader(body)) + request.RemoteAddr = "127.0.0.1:1" + if identity != "" { + e.workers.asWorker(t, request, identity) + } + recorder := httptest.NewRecorder() + e.central.Handler().ServeHTTP(recorder, request) + return recorder.Code + } + for _, identity := range []string{"", "fleet-site-worker:another-site"} { + want := http.StatusForbidden + if identity == "" { + want = http.StatusUnauthorized + } + if code := call(http.MethodPut, "/v1/windows/"+key, string(open), identity); code != want { + t.Fatalf("open as %q = %d, want %d", identity, code, want) + } + if code := call(http.MethodGet, "/v1/devices/"+device, "", identity); code != want { + t.Fatalf("device status as %q = %d, want %d", identity, code, want) + } + } + if _, found, _ := e.central.load(key); found { + t.Fatal("a refused client opened a window") + } + if code := call(http.MethodPut, "/v1/windows/"+key, string(open), workerIdentity); code != http.StatusCreated { + t.Fatalf("open as the site's worker = %d", code) + } + for _, identity := range []string{"", "fleet-site-worker:another-site"} { + if code := call(http.MethodGet, "/v1/windows/"+key, "", identity); code == http.StatusOK { + t.Fatalf("window status served to %q", identity) + } + if code := call(http.MethodPost, "/v1/windows/"+key+"/close", "", identity); code == http.StatusOK { + t.Fatalf("window close accepted from %q", identity) + } + } + if window := e.window(t, "op-auth"); window.Closed { + t.Fatal("a refused client closed the window") + } +} + +// TestARefusedWindowOpenFailsOnlyWhenNothingReachedTheBMC runs a worker +// without a client certificate, so the media service refuses its window. +// With nothing journaled for the BMC the operation fails. With a BMC step +// already journaled, as after a crash, it is unknown. +func TestARefusedWindowOpenFailsOnlyWhenNothingReachedTheBMC(t *testing.T) { + for name, wantPhase := range map[string]ops.Phase{"nothing at the BMC": ops.PhaseFailed, "a BMC step journaled": ops.PhaseOutcomeUnknown} { + t.Run(name, func(t *testing.T) { + e := newMediaEnv(t) + access := e.runner.Access.(site.RedfishAccess) + access.MediaIdentity.(*mediaIdentity).identity = nil + assignment := e.assignment("op-refused", 1) + if wantPhase == ops.PhaseOutcomeUnknown { + if err := e.store.Raise(device, 1); err != nil { + t.Fatal(err) + } + if _, _, err := e.store.IntendWithPayload(device, 1, "op-refused", "media-clear-cd1", nil); err != nil { + t.Fatal(err) + } + } + result, err := e.runner.Run(context.Background(), assignment) + if err != nil { + t.Fatal(err) + } + if result.Phase != wantPhase { + t.Fatalf("result = %+v, want %s", result, wantPhase) + } + if wantPhase == ops.PhaseFailed && result.Reason != custody.ReasonMediaWindowRefused { + t.Fatalf("reason = %s", result.Reason) + } + if len(e.bmc.log()) != 0 { + t.Fatalf("a refused window reached the BMC: %v", e.bmc.log()) + } + }) + } +} + +// TestAReportMustNameExactlyThePinnedDownloads pins one installer download. +// A report naming it by its digest succeeds; a report that also names a +// download the operation never pinned does not. +func TestAReportMustNameExactlyThePinnedDownloads(t *testing.T) { + pinned := ops.DownloadInput{Name: "installer", Reference: "registry.example/installer@sha256:" + strings.Repeat("a", 64)} + e := newMediaEnv(t) + e.downloads = []ops.DownloadInput{pinned} + if result := e.run(t, "op-pinned", 1); result.Phase != ops.PhaseSucceeded { + t.Fatalf("result = %+v", result) + } + if report := e.window(t, "op-pinned").Report; report == nil || len(report.Downloads) != 1 || report.Downloads[0].Digest != "sha256:"+strings.Repeat("a", 64) { + t.Fatalf("report = %+v", report) + } + e = newMediaEnv(t) + e.downloads = []ops.DownloadInput{pinned} + e.bmc.extraDownloads = []ReportedDownload{{Name: "extension", Digest: "sha256:" + strings.Repeat("b", 64)}} + if result := e.run(t, "op-unpinned", 1); result.Phase != ops.PhaseOutcomeUnknown || e.journaled("op-unpinned")["media-report-verified"] != "" { + t.Fatalf("result = %+v", result) + } +} + +// failingIdentity is a site worker identity Secret that cannot be read. +type failingIdentity struct{} + +func (failingIdentity) MediaClient(context.Context, string) (*tls.Certificate, error) { + return nil, errors.New("the identity Secret is malformed") +} + +// TestOnlyVirtualMediaReadsTheWorkerIdentity breaks the site worker's media +// identity. A virtual media install is refused before anything is sent. +func TestOnlyVirtualMediaReadsTheWorkerIdentity(t *testing.T) { + e := newMediaEnv(t) + access := e.runner.Access.(site.RedfishAccess) + access.MediaIdentity = failingIdentity{} + e.runner.Access = access + result := e.run(t, "op-broken-identity", 1) + if result.Phase != ops.PhaseFailed || result.Reason != site.ReasonCredentialMissing || len(e.bmc.log()) != 0 { + t.Fatalf("result = %+v, BMC %v", result, e.bmc.log()) + } +} + +// TestTheSweepSkipsAnUnreadableWindow puts an unreadable window file first +// in the pass. The sweep counts and reports it, and still drops the stale +// window after it. +func TestTheSweepSkipsAnUnreadableWindow(t *testing.T) { + e := newMediaEnv(t) + e.custody.set("op-next", 2) + if err := os.MkdirAll(filepath.Join(e.central.Root, "windows"), 0o700); err != nil { + t.Fatal(err) + } + // Window files sweep in name order; this one sorts first. + if err := os.WriteFile(filepath.Join(e.central.Root, "windows", "0000000000000000.json"), []byte("{not json"), 0o600); err != nil { + t.Fatal(err) + } + stale := Window{Device: device, Operation: "op-dead", Fence: 1, ConfigMedium: []byte("token=one"), FetchExpires: time.Now().Add(time.Hour), ReportExpires: time.Now().Add(time.Hour)} + if err := e.central.save(Key("op-dead"), stale); err != nil { + t.Fatal(err) + } + result, err := e.central.Sweep(context.Background()) + if err == nil || !strings.Contains(err.Error(), "skipped 1") { + t.Fatalf("sweep error = %v", err) + } + if result != (SweepResult{Dropped: 1, Skipped: 1}) { + t.Fatalf("sweep = %+v", result) + } + if window := e.window(t, "op-dead"); window.ConfigMedium != nil { + t.Fatal("an unreadable window stopped the sweep before a stale one") + } +} diff --git a/internal/site/redfishwork/mediaserver.go b/internal/site/redfishwork/mediaserver.go new file mode 100644 index 00000000..1482124e --- /dev/null +++ b/internal/site/redfishwork/mediaserver.go @@ -0,0 +1,800 @@ +package redfishwork + +import ( + "bytes" + "context" + "crypto/rand" + "crypto/sha256" + "crypto/subtle" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "net/http" + "net/netip" + "os" + "path/filepath" + "slices" + "strconv" + "strings" + "sync" + "time" +) + +// MediaServer is the central media service. It is not part of any site: it +// keeps its own windows and takes each Device's fence from custody, the +// authority every site follows. It serves virtual media to BMCs only through +// open windows, and takes the install report the installed OS posts at +// first boot. +// +// A window belongs to one admitted operation at one fence. The service +// opens it only while custody names that operation active at that fence, +// and serves it only while that is still true, so a fence rise closes every +// window of the Device without a worker. It serves the boot medium by its +// digest and the config medium by its URL capability until the fetch +// deadline, and takes one report carrying the window's report token until +// the report deadline. It records each transfer's start and end, and each +// report's outcome, without URLs, capabilities or tokens. +type MediaServer struct { + // Root holds the service's own state: windows, reports and transfers. + Root string + // Artifacts holds the boot medium and the manifest that pins it. + Artifacts string + // Custody reads which operation custody names active for a Device. + Custody CustodyReader + // Clients are the networks BMCs and installed servers reach the + // service from. Requests from any other address are refused. + Clients []netip.Prefix + // Workers authorizes the worker API: it reports whether the verified + // client certificate identity may open, close and read windows of the + // Device. The TLS listener must verify client certificates against the + // site workers' CA when one is presented; BMCs and installed servers + // present none and use only the media and report endpoints. + Workers func(identity, device string) bool + Now func() time.Time + mu sync.Mutex +} + +// CustodyReader reads custody's active operation for a "/" +// Device: its operation key, as custody.OperationKey builds it from the +// operation's kind, name and fence, and its fence, and false when none is +// active. +type CustodyReader interface { + Active(ctx context.Context, device string) (key string, fence int64, ok bool, err error) +} + +// Window is one operation's media window as the media service keeps it. +type Window struct { + Device string `json:"device"` + Operation string `json:"operation"` + Fence int64 `json:"fence"` + // BootDigest is the boot medium artifact's SHA-256, from the image's + // pinned manifest. + BootDigest string `json:"bootDigest"` + // CapabilitySHA256 and TokenSHA256 are digests of the config URL's + // capability and of the report token. Neither value is kept. + CapabilitySHA256 string `json:"capabilitySHA256"` + TokenSHA256 string `json:"tokenSHA256"` + // ConfigMedium is the rendered config medium, kept only while the + // window is open. + ConfigMedium []byte `json:"configMedium,omitempty"` + // ReportFrom is where the installed OS's report may come from, as the + // media service sees it. A report from any other address is refused. + ReportFrom []string `json:"reportFrom"` + Opened time.Time `json:"opened"` + FetchExpires time.Time `json:"fetchExpires"` + ReportExpires time.Time `json:"reportExpires"` + Closed bool `json:"closed,omitempty"` + // Report is the first report that carried the window's token. + Report *ReceivedReport `json:"report,omitempty"` + // Duplicates counts further, different reports with the window's + // token; the token is single use. Rejected counts reports refused for another or + // a missing token, or after the window ended. + Duplicates int `json:"duplicates,omitempty"` + Rejected int `json:"rejected,omitempty"` +} + +// ReceivedReport is an install report the media service took. +type ReceivedReport struct { + Image string `json:"image"` + Bootstrap string `json:"bootstrap"` + // Downloads are what the installer reports it downloaded. + Downloads []ReportedDownload `json:"downloads,omitempty"` + ReceivedAt time.Time `json:"receivedAt"` +} + +// ReportedDownload is one artifact the installer downloaded, by the digest +// it fetched. +type ReportedDownload struct { + Name string `json:"name"` + Digest string `json:"digest"` +} + +// WindowStatus is what the media service reports about a window. It +// carries no capability, token or medium. +type WindowStatus struct { + FetchOpen bool `json:"fetchOpen"` + ReportOpen bool `json:"reportOpen"` + Closed bool `json:"closed"` + Report *ReceivedReport `json:"report,omitempty"` + Duplicates int `json:"duplicates"` + Rejected int `json:"rejected"` + OpenTransfers int `json:"openTransfers"` + // retire means the window keeps a config medium it can never serve. + retire bool +} + +// DeviceStatus is the media service's release report for a Device. +type DeviceStatus struct { + Windows int `json:"windows"` + OpenWindows int `json:"openWindows"` + OpenTransfers int `json:"openTransfers"` + Duplicates int `json:"duplicates"` +} + +func (m *MediaServer) now() time.Time { + if m.Now != nil { + return m.Now() + } + return time.Now() +} + +func validKey(key string) bool { + if len(key) != 16 { + return false + } + _, err := hex.DecodeString(key) + return err == nil +} + +func (m *MediaServer) load(key string) (Window, bool, error) { + var window Window + if !validKey(key) { + return window, false, nil + } + data, err := os.ReadFile(filepath.Join(m.Root, "windows", key+".json")) + if os.IsNotExist(err) { + return window, false, nil + } + if err != nil { + return window, false, err + } + return window, true, json.Unmarshal(data, &window) +} + +func (m *MediaServer) save(key string, window Window) error { + return writeFile(filepath.Join(m.Root, "windows"), key+".json", window) +} + +func writeFile(dir, name string, value any) error { + if err := os.MkdirAll(dir, 0o700); err != nil { + return err + } + data, err := json.Marshal(value) + if err != nil { + return err + } + tmp, err := os.CreateTemp(dir, ".tmp-") + if err != nil { + return err + } + if _, err := tmp.Write(data); err != nil { + tmp.Close() + return err + } + if err := tmp.Sync(); err != nil { + tmp.Close() + return err + } + if err := tmp.Close(); err != nil { + return err + } + return os.Rename(tmp.Name(), filepath.Join(dir, name)) +} + +// current reports whether custody still names the window's operation +// active at the window's fence. +func (m *MediaServer) current(ctx context.Context, window Window) (bool, error) { + key, fence, ok, err := m.Custody.Active(ctx, window.Device) + if err != nil { + return false, err + } + return ok && key == window.Operation && fence == window.Fence, nil +} + +func (m *MediaServer) status(ctx context.Context, key string, window Window) (WindowStatus, error) { + current, err := m.current(ctx, window) + if err != nil { + return WindowStatus{}, err + } + // A window that can never serve again keeps no config medium, and so + // no report token, even if no worker closed it. The caller drops it. + retire := len(window.ConfigMedium) > 0 && (!current || !m.now().Before(window.ReportExpires)) + open, err := m.openTransfers(key) + if err != nil { + return WindowStatus{}, err + } + now := m.now() + live := current && !window.Closed + return WindowStatus{FetchOpen: live && now.Before(window.FetchExpires), ReportOpen: live && now.Before(window.ReportExpires), Closed: window.Closed, + Report: window.Report, Duplicates: window.Duplicates, Rejected: window.Rejected, OpenTransfers: open, retire: retire}, nil +} + +func (m *MediaServer) client(request *http.Request) bool { + host, _, err := net.SplitHostPort(request.RemoteAddr) + if err != nil { + return false + } + address, err := netip.ParseAddr(host) + if err != nil { + return false + } + for _, prefix := range m.Clients { + if prefix.Contains(address.Unmap()) { + return true + } + } + return false +} + +// OpenRequest is a worker's request to open its operation's window. +type OpenRequest struct { + Device string `json:"device"` + Operation string `json:"operation"` + Fence int64 `json:"fence"` + BootDigest string `json:"bootDigest"` + CapabilitySHA256 string `json:"capabilitySHA256"` + TokenSHA256 string `json:"tokenSHA256"` + ConfigMedium []byte `json:"configMedium"` + // FetchExpires ends the media fetch, and ReportExpires the first-boot + // report. Neither is later than the operation's deadline. + FetchExpires time.Time `json:"fetchExpires"` + ReportExpires time.Time `json:"reportExpires"` + // ReportFrom is the IPv4 or IPv6 prefixes the report may come from. + ReportFrom []string `json:"reportFrom"` +} + +// ErrMediaStale means the media service refused to open a window because +// custody does not name the operation active at that fence. +var ErrMediaStale = errors.New("media service: the operation does not hold the Device's fence") + +// ErrMediaUnauthorized means the media service refused the site worker's +// client certificate, or found none. +var ErrMediaUnauthorized = errors.New("media service: the site worker is not authorized") + +// Handler routes the worker API, the media and the report endpoint. It +// never serves a caller-selected path. +func (m *MediaServer) Handler() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, request *http.Request) { + w.Header().Set("Cache-Control", "no-store") + if request.URL.RawQuery != "" || !m.client(request) { + http.Error(w, "denied", http.StatusForbidden) + return + } + parts := strings.Split(strings.TrimPrefix(request.URL.Path, "/"), "/") + if parts[0] == "v1" && !m.authorized(w, request, parts) { + return + } + switch { + case len(parts) == 3 && parts[0] == "v1" && parts[1] == "windows" && request.Method == http.MethodPut: + m.open(w, request, parts[2]) + case len(parts) == 4 && parts[0] == "v1" && parts[1] == "windows" && parts[3] == "close" && request.Method == http.MethodPost: + m.close(w, parts[2]) + case len(parts) == 3 && parts[0] == "v1" && parts[1] == "windows" && request.Method == http.MethodGet: + m.windowStatus(w, request, parts[2]) + case len(parts) == 4 && parts[0] == "v1" && parts[1] == "devices" && request.Method == http.MethodGet: + m.deviceStatus(w, request, parts[2]+"/"+parts[3]) + case len(parts) == 2 && parts[0] == "report" && request.Method == http.MethodPost: + m.report(w, request, parts[1]) + case len(parts) == 5 && parts[0] == "media" && (request.Method == http.MethodGet || request.Method == http.MethodHead): + m.media(w, request, parts[1], parts[2], parts[3], parts[4]) + default: + http.Error(w, "denied", http.StatusForbidden) + } + }) +} + +// ClientIdentity is the common name of the client certificate the TLS +// listener verified, or empty when the client presented none. +func ClientIdentity(request *http.Request) string { + if request.TLS == nil || len(request.TLS.VerifiedChains) == 0 || len(request.TLS.VerifiedChains[0]) == 0 { + return "" + } + return request.TLS.VerifiedChains[0][0].Subject.CommonName +} + +// authorized refuses a worker API request from a client without a verified +// certificate, 401, or whose identity may not act on the Device, 403. The +// Device is the path's for a Device status, the window's own otherwise, and +// for an open the one the request names. +func (m *MediaServer) authorized(w http.ResponseWriter, request *http.Request, parts []string) bool { + identity := ClientIdentity(request) + if identity == "" { + http.Error(w, "a site worker client certificate is required", http.StatusUnauthorized) + return false + } + var device string + switch { + case len(parts) == 4 && parts[1] == "devices": + device = parts[2] + "/" + parts[3] + case len(parts) >= 3 && parts[1] == "windows" && request.Method == http.MethodPut: + var open OpenRequest + body, err := io.ReadAll(io.LimitReader(request.Body, 64<<10)) + if err != nil || json.Unmarshal(body, &open) != nil { + http.Error(w, "invalid window", http.StatusBadRequest) + return false + } + device = open.Device + request.Body = io.NopCloser(bytes.NewReader(body)) + case len(parts) >= 3 && parts[1] == "windows": + m.mu.Lock() + window, found, err := m.load(parts[2]) + m.mu.Unlock() + if err != nil || !found { + http.Error(w, "no such window", http.StatusNotFound) + return false + } + device = window.Device + } + if device == "" || m.Workers == nil || !m.Workers(identity, device) { + http.Error(w, "this client may not act on the Device", http.StatusForbidden) + return false + } + return true +} + +// SweepResult is what one sweep pass did. +type SweepResult struct { + // Dropped counts the config media it dropped. + Dropped int + // Skipped counts the windows it could not read or judge, such as an + // unreadable window file or custody it could not read. The pass goes + // on past each one; the next pass tries it again. + Skipped int +} + +// Sweep drops the config medium, and so the report token, of every window +// that can never serve again: custody no longer names its operation, or its +// report deadline passed. A window it cannot read or judge is counted and +// skipped, so one bad file never keeps every later window's token at rest. +// It returns an error, after the pass, when it skipped any. +func (m *MediaServer) Sweep(ctx context.Context) (SweepResult, error) { + var result SweepResult + paths, err := filepath.Glob(filepath.Join(m.Root, "windows", "*.json")) + if err != nil { + return result, err + } + var first error + skip := func(key string, err error) { + result.Skipped++ + if first == nil { + first = fmt.Errorf("window %s: %w", key, err) + } + } + for _, path := range paths { + key := strings.TrimSuffix(filepath.Base(path), ".json") + m.mu.Lock() + window, found, err := m.load(key) + m.mu.Unlock() + switch { + case err != nil: + skip(key, err) + continue + case !found: + // Gone since the listing: nothing left to drop. + continue + } + status, err := m.status(ctx, key, window) + if err != nil { + skip(key, err) + continue + } + if status.retire { + if err := m.drop(key); err != nil { + skip(key, err) + continue + } + result.Dropped++ + } + } + if first != nil { + return result, fmt.Errorf("the sweep skipped %d windows; first: %w", result.Skipped, first) + } + return result, nil +} + +// RunSweeps sweeps every interval until ctx ends, so no window keeps a +// token at rest only because nothing reads it again. +func (m *MediaServer) RunSweeps(ctx context.Context, interval time.Duration, onError func(error)) { + ticker := time.NewTicker(interval) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + if _, err := m.Sweep(ctx); err != nil && onError != nil { + onError(err) + } + } + } +} + +func reply(w http.ResponseWriter, code int, value any) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(code) + _ = json.NewEncoder(w).Encode(value) +} + +func (m *MediaServer) open(w http.ResponseWriter, request *http.Request, key string) { + var open OpenRequest + decoder := json.NewDecoder(io.LimitReader(request.Body, 64<<10)) + decoder.DisallowUnknownFields() + if err := decoder.Decode(&open); err != nil || key != Key(open.Operation) || open.Device == "" || open.Fence < 1 || len(open.ConfigMedium) == 0 || len(open.ConfigMedium) > configMediumSize || + len(open.CapabilitySHA256) != 64 || len(open.TokenSHA256) != 64 || len(open.BootDigest) != 64 || + !m.now().Before(open.FetchExpires) || open.ReportExpires.Before(open.FetchExpires) || !validPrefixes(open.ReportFrom) { + http.Error(w, "invalid window", http.StatusBadRequest) + return + } + m.mu.Lock() + defer m.mu.Unlock() + window := Window{Device: open.Device, Operation: open.Operation, Fence: open.Fence, BootDigest: open.BootDigest, CapabilitySHA256: open.CapabilitySHA256, TokenSHA256: open.TokenSHA256, + ReportFrom: open.ReportFrom} + if current, err := m.current(request.Context(), window); err != nil { + http.Error(w, "custody unreadable", http.StatusServiceUnavailable) + return + } else if !current { + http.Error(w, ErrMediaStale.Error(), http.StatusConflict) + return + } + existing, found, err := m.load(key) + if err != nil { + http.Error(w, "state unreadable", http.StatusInternalServerError) + return + } + if found { + // A replayed open of the same window is answered again; any other + // is refused. A window is opened once. + if existing.Operation == open.Operation && existing.Fence == open.Fence && existing.TokenSHA256 == open.TokenSHA256 && existing.CapabilitySHA256 == open.CapabilitySHA256 && !existing.Closed { + reply(w, http.StatusOK, map[string]string{"window": key}) + return + } + http.Error(w, "the window was already opened", http.StatusConflict) + return + } + now := m.now().UTC() + window.ConfigMedium = open.ConfigMedium + window.Opened = now + window.FetchExpires, window.ReportExpires = open.FetchExpires.UTC(), open.ReportExpires.UTC() + if err := m.save(key, window); err != nil { + http.Error(w, "state unwritable", http.StatusInternalServerError) + return + } + reply(w, http.StatusCreated, map[string]string{"window": key}) +} + +// drop removes a window's config medium. +func (m *MediaServer) drop(key string) error { + m.mu.Lock() + defer m.mu.Unlock() + window, found, err := m.load(key) + if err != nil || !found || window.ConfigMedium == nil { + return err + } + window.ConfigMedium = nil + return m.save(key, window) +} + +// close closes a window and drops its config medium. Closing needs no +// fence: it only takes delivery away. +func (m *MediaServer) close(w http.ResponseWriter, key string) { + m.mu.Lock() + defer m.mu.Unlock() + window, found, err := m.load(key) + switch { + case err != nil: + http.Error(w, "state unreadable", http.StatusInternalServerError) + return + case !found: + http.Error(w, "no such window", http.StatusNotFound) + return + } + window.Closed, window.ConfigMedium = true, nil + if err := m.save(key, window); err != nil { + http.Error(w, "state unwritable", http.StatusInternalServerError) + return + } + reply(w, http.StatusOK, map[string]string{"window": key}) +} + +func (m *MediaServer) windowStatus(w http.ResponseWriter, request *http.Request, key string) { + m.mu.Lock() + window, found, err := m.load(key) + m.mu.Unlock() + switch { + case err != nil: + http.Error(w, "state unreadable", http.StatusInternalServerError) + return + case !found: + http.Error(w, "no such window", http.StatusNotFound) + return + } + status, err := m.status(request.Context(), key, window) + if err == nil && status.retire { + err = m.drop(key) + } + if err != nil { + http.Error(w, "custody unreadable", http.StatusServiceUnavailable) + return + } + reply(w, http.StatusOK, status) +} + +// deviceStatus covers every window the service ever opened for the Device, +// so release also covers windows of earlier, held operations. +func (m *MediaServer) deviceStatus(w http.ResponseWriter, request *http.Request, device string) { + paths, err := filepath.Glob(filepath.Join(m.Root, "windows", "*.json")) + if err != nil { + http.Error(w, "state unreadable", http.StatusInternalServerError) + return + } + var out DeviceStatus + for _, path := range paths { + key := strings.TrimSuffix(filepath.Base(path), ".json") + m.mu.Lock() + window, _, err := m.load(key) + m.mu.Unlock() + if err != nil { + http.Error(w, "state unreadable", http.StatusInternalServerError) + return + } + if window.Device != device { + continue + } + status, err := m.status(request.Context(), key, window) + if err == nil && status.retire { + err = m.drop(key) + } + if err != nil { + http.Error(w, "custody unreadable", http.StatusServiceUnavailable) + return + } + out.Windows++ + if status.FetchOpen || status.ReportOpen { + out.OpenWindows++ + } + out.OpenTransfers += status.OpenTransfers + out.Duplicates += status.Duplicates + } + reply(w, http.StatusOK, out) +} + +// InstallReport is the report the installed OS posts at first boot. +type InstallReport struct { + Token string `json:"token"` + Image string `json:"image"` + Bootstrap string `json:"bootstrap"` + Downloads []ReportedDownload `json:"downloads,omitempty"` +} + +func validPrefixes(prefixes []string) bool { + for _, value := range prefixes { + if _, err := netip.ParsePrefix(value); err != nil { + return false + } + } + return len(prefixes) > 0 +} + +// fromAny reports whether the request's source address is in one of the +// prefixes. +func fromAny(request *http.Request, prefixes []string) bool { + host, _, err := net.SplitHostPort(request.RemoteAddr) + if err != nil { + return false + } + address, err := netip.ParseAddr(host) + if err != nil { + return false + } + for _, value := range prefixes { + if prefix, err := netip.ParsePrefix(value); err == nil && prefix.Contains(address.Unmap()) { + return true + } + } + return false +} + +// report takes one install report per window: it must carry the window's +// token, arrive before the report deadline, and come while custody still +// names the operation. A refused or repeated report is counted, never +// taken, and the token is never recorded. +func (m *MediaServer) report(w http.ResponseWriter, request *http.Request, key string) { + var report InstallReport + decoder := json.NewDecoder(io.LimitReader(request.Body, 4<<10)) + decoder.DisallowUnknownFields() + decodeErr := decoder.Decode(&report) + m.mu.Lock() + defer m.mu.Unlock() + window, found, err := m.load(key) + switch { + case err != nil: + http.Error(w, "report denied", http.StatusForbidden) + return + case !found: + http.Error(w, "report denied", http.StatusNotFound) + return + } + status, err := m.status(request.Context(), key, window) + if err != nil { + http.Error(w, "custody unreadable", http.StatusServiceUnavailable) + return + } + if status.retire { + window.ConfigMedium = nil + } + outcome, code := "accepted", http.StatusOK + switch { + case !fromAny(request, window.ReportFrom): + // Checked first, so a report from elsewhere is refused for where it + // came from, whatever token it carries. + outcome, code = "rejected-source", http.StatusForbidden + window.Rejected++ + case decodeErr != nil || len(report.Token) != 64 || subtle.ConstantTimeCompare([]byte(digest(report.Token)), []byte(window.TokenSHA256)) != 1: + outcome, code = "rejected-token", http.StatusForbidden + window.Rejected++ + case !status.ReportOpen: + outcome, code = "rejected-window", http.StatusForbidden + window.Rejected++ + case window.Report != nil && window.Report.Image == report.Image && window.Report.Bootstrap == report.Bootstrap && slices.Equal(window.Report.Downloads, report.Downloads): + // The installed OS retried after a lost answer: the same report + // again changes nothing. + outcome = "repeated" + case window.Report != nil: + // The token is single use: a second, different report means two + // installs, and the operation can no longer succeed. + outcome, code = "duplicate", http.StatusConflict + window.Duplicates++ + default: + window.Report = &ReceivedReport{Image: report.Image, Bootstrap: report.Bootstrap, Downloads: report.Downloads, ReceivedAt: m.now().UTC()} + } + if err := m.save(key, window); err != nil { + http.Error(w, "state unwritable", http.StatusInternalServerError) + return + } + _ = appendEvidence(filepath.Join(m.Root, "transfers", key), "reports.log", fmt.Sprintf("%s report %s\n", m.now().UTC().Format(time.RFC3339), outcome)) + reply(w, code, map[string]string{"report": outcome}) +} + +func (m *MediaServer) media(w http.ResponseWriter, request *http.Request, key, kind, secret, name string) { + deny := func() { http.Error(w, "media denied", http.StatusForbidden) } + m.mu.Lock() + window, found, err := m.load(key) + m.mu.Unlock() + if err != nil || !found { + deny() + return + } + status, err := m.status(request.Context(), key, window) + if err == nil && status.retire { + err = m.drop(key) + } + if err != nil || !status.FetchOpen { + deny() + return + } + var body io.ReadSeeker + var size int64 + switch { + case kind == "boot" && name == "boot.iso" && subtle.ConstantTimeCompare([]byte(secret), []byte(window.BootDigest)) == 1: + // Hash the pinned artifact, then serve the same open file. + file, err := os.Open(filepath.Join(m.Artifacts, "boot.iso")) + if err != nil { + deny() + return + } + defer file.Close() + hash := sha256.New() + if size, err = io.Copy(hash, file); err != nil || hex.EncodeToString(hash.Sum(nil)) != window.BootDigest { + deny() + return + } + if _, err := file.Seek(0, io.SeekStart); err != nil { + deny() + return + } + body = file + case kind == "config" && name == "config.img" && subtle.ConstantTimeCompare([]byte(digest(secret)), []byte(window.CapabilitySHA256)) == 1 && len(window.ConfigMedium) > 0: + body, size = bytes.NewReader(window.ConfigMedium), int64(len(window.ConfigMedium)) + default: + deny() + return + } + w.Header().Set("Content-Type", "application/octet-stream") + w.Header().Set("Content-Length", strconv.FormatInt(size, 10)) + if request.Method == http.MethodHead { + return + } + id, err := transferID() + dir := filepath.Join(m.Root, "transfers", key) + if err != nil || appendEvidence(dir, transferLog, fmt.Sprintf("%s start %s %s\n", m.now().UTC().Format(time.RFC3339), id, kind)) != nil { + deny() + return + } + written, err := io.Copy(w, body) + outcome := "complete" + if err != nil || written != size { + outcome = "incomplete" + } + // The end is recorded even when the client went away: the transfer is + // over either way. + _ = appendEvidence(dir, transferLog, fmt.Sprintf("%s end %s %s bytes=%d %s\n", m.now().UTC().Format(time.RFC3339), id, kind, written, outcome)) +} + +const transferLog = "media-transfer.log" + +func transferID() (string, error) { + b := make([]byte, 8) + if _, err := rand.Read(b); err != nil { + return "", err + } + return hex.EncodeToString(b), nil +} + +// Transfer is one media transfer the media service recorded. +type Transfer struct { + ID, Kind string + Ended bool + Bytes int64 + Complete bool +} + +// Transfers reads the media service's transfer records for a window. +func (m *MediaServer) Transfers(key string) ([]Transfer, error) { + data, err := os.ReadFile(filepath.Join(m.Root, "transfers", key, transferLog)) + if os.IsNotExist(err) { + return nil, nil + } + if err != nil { + return nil, err + } + var out []Transfer + index := map[string]int{} + for _, line := range strings.Split(string(data), "\n") { + fields := strings.Fields(line) + switch { + case len(fields) == 4 && fields[1] == "start": + index[fields[2]] = len(out) + out = append(out, Transfer{ID: fields[2], Kind: fields[3]}) + case len(fields) == 6 && fields[1] == "end": + i, ok := index[fields[2]] + if !ok { + return nil, errors.New("a media transfer ended that never started") + } + n, _ := strconv.ParseInt(strings.TrimPrefix(fields[4], "bytes="), 10, 64) + out[i].Ended, out[i].Bytes, out[i].Complete = true, n, fields[5] == "complete" + case line == "": + default: + return nil, errors.New("an unreadable media transfer record") + } + } + return out, nil +} + +// openTransfers counts a window's transfers that started and never ended. +// An unreadable record is not proof that none is open. +func (m *MediaServer) openTransfers(key string) (int, error) { + transfers, err := m.Transfers(key) + if err != nil { + return 0, err + } + open := 0 + for _, transfer := range transfers { + if !transfer.Ended { + open++ + } + } + return open, nil +} diff --git a/internal/site/runner.go b/internal/site/runner.go index 13d81ff8..8b91f5dc 100644 --- a/internal/site/runner.go +++ b/internal/site/runner.go @@ -416,6 +416,10 @@ func (r *Runner) Run(ctx context.Context, assignment Assignment) (custody.SiteRe return custody.SiteResult{}, context.Cause(parent) } if err != nil { + var unsent *Unsent + if errors.As(err, &unsent) { + return finish(ops.PhaseFailed, unsent.Refusal.Reason, unsent.Refusal.Message, nil) + } var refusal *custody.Refusal if errors.As(err, &refusal) { return end(refusal.Reason, refusal.Message) @@ -432,6 +436,14 @@ func (r *Runner) Run(ctx context.Context, assignment Assignment) (custody.SiteRe var errDeadline = errors.New("the operation's deadline passed") +// Unsent is a refusal a kind raises after it journaled steps that it knows +// took no effect anywhere: each was refused outright by the service it was +// sent to, and none reached the server. The operation ends Failed rather +// than unknown. A kind raises it only when its journal proves that. +type Unsent struct{ Refusal *custody.Refusal } + +func (u *Unsent) Error() string { return u.Refusal.Reason + ": " + u.Refusal.Message } + // DeadlinePassed reports whether ctx ended because the operation's deadline // passed. No replacement worker can resume such an operation. func DeadlinePassed(ctx context.Context) bool { return errors.Is(context.Cause(ctx), errDeadline) } diff --git a/internal/site/store.go b/internal/site/store.go index 2ef38ef6..83b448d5 100644 --- a/internal/site/store.go +++ b/internal/site/store.go @@ -353,6 +353,22 @@ func (s *Store) PutRecord(device string, fence int64, collection, name string, v }) } +// DeleteRecord removes a kind's record, such as a rendered config medium +// once its operation ended. Removing never needs the fence: a worker a newer +// fence stopped still deletes what it rendered. +func (s *Store) DeleteRecord(device, collection, name string) error { + if !validRecordName(collection) || !validRecordName(name) { + return errors.New("site: invalid record name") + } + return s.locked(device, func(*deviceState) (bool, error) { + err := os.Remove(filepath.Join(s.deviceDir(device), collection, name+".json")) + if os.IsNotExist(err) { + return false, nil + } + return false, err + }) +} + // GetRecord reads a kind's record. It returns false if there is none. func (s *Store) GetRecord(device, collection, name string, into any) (bool, error) { if !validRecordName(collection) || !validRecordName(name) { From f5e678b990e14ba5f5573cf091693d426c10c1d4 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Fri, 27 Nov 2026 11:56:16 -0600 Subject: [PATCH 03/35] feat(lab): Boot lab targets from virtual media The lab image gains a boot medium holding the same kernel and installer, and an installer mode that reads a config medium and leaves the report for the installed OS, which posts it over HTTPS at first boot. The lab BMC serves Redfish VirtualMedia: two CD devices, insert over HTTPS that verifies the media service, eject, readback and a one-time CD boot, with faults that corrupt the report token, add an unpinned download, and withhold an eject response. Each worker gets the site worker identity Secret through a per-operation Role that admission pins to that one name, and the media service's certificate through the dispatcher instance. Lab guests may reach the report endpoint and nothing else beyond the boot Service. Co-Authored-By: Claude Opus 5.5 --- config/site/graph/rgd.yaml | 2 + config/site/instance/dispatcher.yaml | 4 + config/site/redfish/base/identity.yaml | 31 +++ config/site/redfish/base/kustomization.yaml | 13 +- config/site/redfish/graph/kustomization.yaml | 60 ++++++ config/site/redfish/services/bmc.yaml | 6 + .../site/redfish/services/kustomization.yaml | 6 + hack/local-vm/Containerfile | 7 +- hack/local-vm/boot | 18 ++ hack/local-vm/dhcp | 10 + hack/local-vm/init | 79 ++++++- hack/local-vm/site-runtime | 8 + hack/redfish-lab/fleet_lab_adapter.py | 193 +++++++++++++++++- hack/redfish-lab/test_adapter.py | 75 ++++++- 14 files changed, 493 insertions(+), 19 deletions(-) create mode 100644 config/site/redfish/base/identity.yaml create mode 100644 hack/local-vm/dhcp diff --git a/config/site/graph/rgd.yaml b/config/site/graph/rgd.yaml index b06e319d..39932d62 100644 --- a/config/site/graph/rgd.yaml +++ b/config/site/graph/rgd.yaml @@ -28,6 +28,8 @@ spec: # The shared runtime's accelerator. Workers refuse a runtime that # published another, and each installation's journal binds it. accelerator: string | required=true + # The central media service's certificate, for virtual media workers. + mediaCA: string | default="" status: bootOrigin: ${"http://" + bootService.spec.clusterIP + ":8080"} workerImage: ${hypervisor.spec.template.spec.containers[0].image} diff --git a/config/site/instance/dispatcher.yaml b/config/site/instance/dispatcher.yaml index 77740c10..04847aee 100644 --- a/config/site/instance/dispatcher.yaml +++ b/config/site/instance/dispatcher.yaml @@ -17,3 +17,7 @@ spec: cell: "${FLEET_CELL}" dispatch: ${FLEET_SITE_DISPATCH} accelerator: "${FLEET_LOCAL_VM_ACCEL}" + # The central media service's certificate in PEM, base64 encoded, or + # empty where no media service runs. It is public; workers verify the + # service with it. + mediaCA: "${FLEET_MEDIA_CA}" diff --git a/config/site/redfish/base/identity.yaml b/config/site/redfish/base/identity.yaml new file mode 100644 index 00000000..5311a43b --- /dev/null +++ b/config/site/redfish/base/identity.yaml @@ -0,0 +1,31 @@ +# The site workers' own identity for the central media service: one client +# certificate Secret per site worker identity, fleet-site-worker-media. The +# harness enrolls it; it is never part of a source revision. It holds no BMC +# credential, and no BMC credential Secret holds it. +apiVersion: v1 +kind: Namespace +metadata: + name: fleet-site-worker-identity + annotations: + # Deleting the namespace deletes the enrolled identity. Never prune it. + kustomize.toolkit.fluxcd.io/prune: disabled +--- +# To create a per-operation Role that gets the identity Secret, kro itself +# must hold get on it. kro cannot list or watch Secrets here. +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: {name: fleet-site-kro-worker-identity, namespace: fleet-site-worker-identity} +rules: + - apiGroups: [rbac.authorization.k8s.io] + resources: [roles, rolebindings] + verbs: [create, update, patch, delete] + - apiGroups: [""] + resources: [secrets] + verbs: [get] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: {name: fleet-site-kro-worker-identity, namespace: fleet-site-worker-identity} +subjects: + - {kind: ServiceAccount, name: kro, namespace: kro-system} +roleRef: {apiGroup: rbac.authorization.k8s.io, kind: Role, name: fleet-site-kro-worker-identity} diff --git a/config/site/redfish/base/kustomization.yaml b/config/site/redfish/base/kustomization.yaml index e1697134..790d4883 100644 --- a/config/site/redfish/base/kustomization.yaml +++ b/config/site/redfish/base/kustomization.yaml @@ -7,6 +7,7 @@ resources: - ../../base - bmc.yaml - credentials.yaml + - identity.yaml patches: - target: {kind: ValidatingAdmissionPolicy, name: fleet-site-kro-worker-jobs} patch: |- @@ -28,8 +29,9 @@ patches: !c.env.exists(e, e.name == 'FLEET_LIBVIRT_URI')) message: a Redfish worker Job must select the Redfish provider and carry no libvirt URI # kro may create, in fleet-site-credentials, only a per-operation Role - # that gets one named credential Secret, bound to that operation's own - # ServiceAccount. + # that gets one named credential Secret, and in fleet-site-worker-identity + # only one that gets the site worker identity Secret, each bound to that + # operation's own ServiceAccount. - target: {kind: ValidatingAdmissionPolicy, name: fleet-site-kro-worker-identity} patch: |- - op: test @@ -37,7 +39,7 @@ patches: value: a worker Role may grant only get on its own handoff - op: replace path: /spec/matchConstraints/namespaceSelector/matchExpressions/0/values - value: [fleet-site, fleet-coordination, fleet-site-credentials] + value: [fleet-site, fleet-coordination, fleet-site-credentials, fleet-site-worker-identity] - op: replace path: /spec/validations/2 value: @@ -46,7 +48,10 @@ patches: (has(object.rules) && size(object.rules) == 1 && object.rules.all(r, r.apiGroups == [''] && r.resources == ['secrets'] && r.verbs == ['get'] && has(r.resourceNames) && size(r.resourceNames) == 1 && r.resourceNames.all(n, n.matches('^bmc-[a-f0-9]{20}$')))) : + request.namespace == 'fleet-site-worker-identity' ? + (has(object.rules) && size(object.rules) == 1 && object.rules.all(r, r.apiGroups == [''] && + r.resources == ['secrets'] && r.verbs == ['get'] && has(r.resourceNames) && r.resourceNames == ['fleet-site-worker-media'])) : (has(object.rules) && size(object.rules) == 1 && object.rules.all(r, r.apiGroups == ['coordination.fleet.datumapis.com'] && r.resources == ['machineallocationhandoffs'] && r.verbs == ['get'] && has(r.resourceNames) && r.resourceNames == [variables.handoff]))) - message: a worker Role may grant only get on its own handoff, or get on one named BMC credential + message: a worker Role may grant only get on its own handoff, get on one named BMC credential, or get on the site worker identity diff --git a/config/site/redfish/graph/kustomization.yaml b/config/site/redfish/graph/kustomization.yaml index 324ce59c..40eff4c6 100644 --- a/config/site/redfish/graph/kustomization.yaml +++ b/config/site/redfish/graph/kustomization.yaml @@ -33,6 +33,16 @@ patches: - name: FLEET_REDFISH_ENROLLMENT value: '{"dhcp":"static","targets":[{"device":"fleet-provider/synthetic-device-central-01","endpoint":"https://10.96.0.81:8443","systemID":"System-1","systemUUID":"7f3d0c2e-1a5b-4c6d-8e9f-0a1b2c3d4e0a","diskBytes":2147483648,"console":"target-a.log"},{"device":"fleet-provider/synthetic-device-central-02","endpoint":"https://10.96.0.81:8443","systemID":"System-2","systemUUID":"7f3d0c2e-1a5b-4c6d-8e9f-0a1b2c3d4e0b","diskBytes":2147483648,"console":"target-b.log"}]}' - {name: HOME, value: /tmp} + # The central media service's certificate, from the dispatcher + # instance: public, per environment. + - {name: FLEET_MEDIA_CA, value: "${schema.spec.mediaCA}"} + # The site worker's own media service identity: one named Secret, + # which the worker gets through a per-operation Role of its own. + - {name: FLEET_SITE_WORKER_IDENTITY_NAMESPACE, value: fleet-site-worker-identity} + # Where the media service sees this site's installed servers post + # their first-boot reports from: the lab network reaches it through + # the runtime's host gateway, which arrives on loopback. + - {name: FLEET_MEDIA_REPORT_FROM, value: 127.0.0.1/32} - op: replace path: /spec/resources/9/template/spec/template/spec/containers/0/volumeMounts value: @@ -97,6 +107,56 @@ patches: - op: add path: /spec/resources/9/template/metadata/annotations/fleet.datumapis.com~1credentials value: ${string(size(workerCredentialBindings))} + # Each worker may get exactly the site worker identity Secret, and no + # other Secret, in the identity namespace. + - op: add + path: /spec/resources/- + value: + id: workerIdentityRoles + includeWhen: + - ${schema.spec.dispatch} + forEach: + - handoff: ${handoffs} + template: + apiVersion: rbac.authorization.k8s.io/v1 + kind: Role + metadata: + name: ${"w-" + handoff.metadata.name} + namespace: fleet-site-worker-identity + labels: {app.kubernetes.io/name: fleet-site-worker} + rules: + - apiGroups: [""] + resources: [secrets] + resourceNames: [fleet-site-worker-media] + verbs: [get] + - op: add + path: /spec/resources/- + value: + id: workerIdentityBindings + includeWhen: + - ${schema.spec.dispatch} + forEach: + - handoff: ${handoffs} + template: + apiVersion: rbac.authorization.k8s.io/v1 + kind: RoleBinding + metadata: + name: ${"w-" + handoff.metadata.name} + namespace: fleet-site-worker-identity + labels: {app.kubernetes.io/name: fleet-site-worker} + annotations: + fleet.datumapis.com/roles: ${string(size(workerIdentityRoles))} + subjects: + - kind: ServiceAccount + name: ${"w-" + handoff.metadata.name} + namespace: fleet-site + roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: ${"w-" + handoff.metadata.name} + - op: add + path: /spec/resources/9/template/metadata/annotations/fleet.datumapis.com~1identity + value: ${string(size(workerIdentityBindings))} - op: add path: /spec/resources/- value: diff --git a/config/site/redfish/services/bmc.yaml b/config/site/redfish/services/bmc.yaml index 2abd7558..459a2955 100644 --- a/config/site/redfish/services/bmc.yaml +++ b/config/site/redfish/services/bmc.yaml @@ -62,6 +62,10 @@ spec: - {name: state, mountPath: /var/lib/fleet-bmc, subPath: bmc-state} - {name: credentials, mountPath: /etc/fleet-bmc-credentials, readOnly: true} - {name: tls, mountPath: /etc/fleet-bmc-tls, readOnly: true} + # Virtual media the BMC fetched, verifying the media service + # against its CA. + - {name: state, mountPath: /var/lib/fleet-lab-media, subPath: lab-media} + - {name: media-ca, mountPath: /etc/fleet-bmc-media-ca, readOnly: true} - {name: tmp, mountPath: /tmp} volumes: - name: state @@ -70,5 +74,7 @@ spec: secret: {secretName: fleet-site-bmc-credentials, defaultMode: 0400} - name: tls secret: {secretName: fleet-site-bmc-tls, defaultMode: 0400} + - name: media-ca + secret: {secretName: fleet-site-media-ca, defaultMode: 0400} - name: tmp emptyDir: {} diff --git a/config/site/redfish/services/kustomization.yaml b/config/site/redfish/services/kustomization.yaml index 70dce65d..0ef27b10 100644 --- a/config/site/redfish/services/kustomization.yaml +++ b/config/site/redfish/services/kustomization.yaml @@ -19,9 +19,15 @@ patches: - name: libvirt env: - {name: FLEET_SITE_PROVIDER, value: redfish} + # The central media service's report endpoint, the one + # address lab guests may reach besides the boot Service. + - {name: FLEET_MEDIA_REPORT, value: "192.168.5.2:28443"} volumeMounts: - {name: state, mountPath: /var/lib/fleet-lab/disks, subPath: lab-disks} - {name: state, mountPath: /var/lib/fleet-lab-console, subPath: lab-console} + # The lab BMC's fetched virtual media, attached to guests + # as CD-ROMs at the path the BMC wrote them. + - {name: state, mountPath: /var/lib/fleet-lab-media, subPath: lab-media, readOnly: true} - target: {kind: Deployment, name: fleet-site-boot} patch: |- apiVersion: apps/v1 diff --git a/hack/local-vm/Containerfile b/hack/local-vm/Containerfile index 64952e68..9cf48a00 100644 --- a/hack/local-vm/Containerfile +++ b/hack/local-vm/Containerfile @@ -1,8 +1,11 @@ FROM --platform=linux/amd64 debian:bookworm-slim@sha256:734a72b3d6142a71993b4bc580ca01d8ca687f77a2c422d96a961d3376b179bc AS guest -RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends linux-image-amd64 initramfs-tools busybox-static grub-pc-bin grub2-common fdisk e2fsprogs cpio && rm -rf /var/lib/apt/lists/* +RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends linux-image-amd64 initramfs-tools busybox-static grub-pc-bin grub2-common fdisk e2fsprogs cpio xorriso curl && rm -rf /var/lib/apt/lists/* COPY init /init COPY boot /fleet-boot -RUN chmod 755 /init /fleet-boot && mkdir -p /out && cp /boot/vmlinuz-* /out/kernel && find . \( -path ./out -o -path ./proc -o -path ./sys -o -path ./dev \) -prune -o -print | cpio -o -H newc | gzip -1 > /out/installer.gz && cd /out && sha256sum kernel installer.gz > SHA256SUMS +COPY dhcp /fleet-dhcp +# The boot medium for virtual media holds the same kernel and installer and +# their content manifest, and nothing specific to an operation. +RUN chmod 755 /init /fleet-boot /fleet-dhcp && mkdir -p /out && cp /boot/vmlinuz-* /out/kernel && find . \( -path ./out -o -path ./proc -o -path ./sys -o -path ./dev \) -prune -o -print | cpio -o -H newc | gzip -1 > /out/installer.gz && cd /out && mkdir -p /iso/boot/grub && cp kernel installer.gz /iso/ && sha256sum kernel installer.gz > /iso/MANIFEST && printf 'serial --unit=0 --speed=115200\nterminal_output serial console\nset timeout=0\nmenuentry Fleet {\n linux /kernel console=ttyS0 rdinit=/init fleet.mode=install fleet.delivery=media\n initrd /installer.gz\n}\n' > /iso/boot/grub/grub.cfg && grub-mkrescue -o /out/boot.iso /iso && sha256sum kernel installer.gz boot.iso > SHA256SUMS FROM debian:bookworm-slim@sha256:734a72b3d6142a71993b4bc580ca01d8ca687f77a2c422d96a961d3376b179bc AS tcg RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends qemu-system-x86 qemu-utils libvirt-daemon-system libvirt-clients tini dnsmasq-base ipxe-qemu iptables && rm -rf /var/lib/apt/lists/* && printf '%s\n' 'user = "root"' 'group = "root"' 'security_driver = "none"' 'dynamic_ownership = 0' 'cgroup_controllers = []' >> /etc/libvirt/qemu.conf && rm -f /etc/libvirt/qemu/networks/autostart/default.xml COPY start-libvirt /usr/local/bin/fleet-start-libvirt diff --git a/hack/local-vm/boot b/hack/local-vm/boot index b40c21ec..d2f20c82 100644 --- a/hack/local-vm/boot +++ b/hack/local-vm/boot @@ -6,5 +6,23 @@ exec >/dev/ttyS0 2>&1 if grep -Eq '^/dev/vda1 / ext4 ' /proc/mounts && test -s /fleet-receipt; then printf 'FLEET-DISK-BOOT:%s\n' "$(cat /fleet-receipt)" fi +# A virtual media install: at first boot the installed OS brings up its +# data network over DHCP and posts its install report over HTTPS, verifying +# the media service. The console shows only the outcome. +if grep -Eq '^/dev/vda1 / ext4 ' /proc/mounts && test -s /fleet-report/token; then + mount -t sysfs sys /sys 2>/dev/null || true + mount -t devtmpfs devtmpfs /dev 2>/dev/null || true + mount -t tmpfs tmpfs /run 2>/dev/null || true + modprobe e1000 || true + # The initramfs may rename the NIC; the data network is the one NIC. + iface=$(ls /sys/class/net | grep -vx lo | head -n 1) + /bin/busybox ip link set "$iface" up + /bin/busybox udhcpc -i "$iface" -n -q -t 20 -s /fleet-dhcp >/dev/null 2>&1 + downloads=$(/bin/busybox awk 'BEGIN{ORS=""} {if (NR>1) print ","; printf "{\"name\":\"%s\",\"digest\":\"%s\"}", $1, $2}' /fleet-report/downloads 2>/dev/null) + body=$(printf '{"token":"%s","image":"%s","bootstrap":"%s","downloads":[%s]}' "$(cat /fleet-report/token)" "$(cat /fleet-report/image)" "$(cat /fleet-report/bootstrap)" "$downloads") + printf 'fleet: data network %s\n' "$(/bin/busybox ip -4 -o addr show dev "$iface" 2>&1 | /bin/busybox awk '{print $4}')" + status=$(curl -sS -o /dev/null -w '%{http_code}' --max-time 60 --retry 5 --retry-all-errors --cacert /fleet-report/ca.pem -H 'Content-Type: application/json' --data "$body" "$(cat /fleet-report/url)" 2>/run/curl.err || true) + printf 'fleet: first-boot report HTTP %s %s\n' "$status" "$(head -c 200 /run/curl.err)" +fi sync /bin/busybox poweroff -f diff --git a/hack/local-vm/dhcp b/hack/local-vm/dhcp new file mode 100644 index 00000000..6d0f4957 --- /dev/null +++ b/hack/local-vm/dhcp @@ -0,0 +1,10 @@ +#!/bin/busybox sh +# udhcpc event script for the installed lab OS: apply the lease's address +# and default route on the data network. +case "$1" in + bound|renew) + /bin/busybox ip addr flush dev "$interface" + /bin/busybox ip addr add "$ip/$mask" dev "$interface" + [ -z "$router" ] || /bin/busybox ip route add default via "${router%% *}" dev "$interface" + ;; +esac diff --git a/hack/local-vm/init b/hack/local-vm/init index a3e9d0bf..1662f93f 100644 --- a/hack/local-vm/init +++ b/hack/local-vm/init @@ -10,7 +10,51 @@ modprobe virtio_pci modprobe virtio_blk modprobe ext4 mode=install -for arg in $(cat /proc/cmdline); do case "$arg" in fleet.receipt=*) receipt=${arg#fleet.receipt=};; fleet.mode=*) mode=${arg#fleet.mode=};; fleet.duration=*) duration=${arg#fleet.duration=};; esac; done +delivery=network +for arg in $(cat /proc/cmdline); do case "$arg" in fleet.receipt=*) receipt=${arg#fleet.receipt=};; fleet.mode=*) mode=${arg#fleet.mode=};; fleet.duration=*) duration=${arg#fleet.duration=};; fleet.delivery=*) delivery=${arg#fleet.delivery=};; esac; done +if [ "$delivery" = media ]; then + # Virtual media: the boot medium carries nothing operation specific. The + # config medium, rendered for one operation, carries the report token, the + # bootstrap salt and payload, how the OS gets addresses, and where the + # installed OS posts its report. The installer brings up no network and + # reports nothing itself: only the installed OS's report proves the install. + modprobe ata_piix || true + modprobe sr_mod + modprobe isofs + config= boot= + for _ in $(seq 1 30); do + for dev in /dev/sr0 /dev/sr1; do + [ -b "$dev" ] || continue + if [ "$(dd if="$dev" bs=2048 count=1 2>/dev/null | head -c 15)" = FLEET-CONFIG-V1 ]; then config=$dev; else boot=$dev; fi + done + [ -n "$config" ] && [ -n "$boot" ] && break + sleep 1 + done + [ -n "$config" ] && [ -n "$boot" ] || /bin/busybox poweroff -f + dd if="$config" bs=2048 count=4 2>/dev/null | tr -d '\000' > /fleet-config + # The console is diagnostics only and must carry no secret: tracing + # would print the token and the bootstrap payload, so it stays off for + # the rest of a virtual media install. + set +x + value() { sed -n "s/^$1=//p" /fleet-config; } + receipt=$(value token) + salt=$(value salt) + grep -qx 'addresses=DataNetwork' /fleet-config || /bin/busybox poweroff -f + value bootstrap | base64 -d > /fleet-bootstrap + report=$(value report) + # The downloads the config medium pins, one "name digest" per line. This + # lab image fetches nothing; it reports each one by the digest its + # reference pins, as an installer that pulled it would. + sed -n 's/^download=\([^ ]*\) [^@]*@\(sha256:[0-9a-f]*\)$/\1 \2/p' /fleet-config > /fleet-downloads + [ ${#salt} = 64 ] || /bin/busybox poweroff -f + # The image identity the boot medium carries: its own content manifest, + # checked against the files it booted. + mkdir -p /media + mount -t iso9660 -o ro "$boot" /media + (cd /media && sha256sum -c MANIFEST) + image=$(sha256sum /media/MANIFEST | cut -d' ' -f1) + umount /media +fi [ ${#receipt} = 64 ] || /bin/busybox poweroff -f if [ "$mode" = wipe ]; then # Redfish-mode cleanup environment: zero the whole disk, then verify by @@ -65,12 +109,22 @@ mkfs.ext4 -F /dev/vda1 mkdir -p /target mount /dev/vda1 /target # The payload is this pinned installer filesystem; exclude virtual mounts. -/bin/tar -cf - --exclude=./target --exclude=./proc --exclude=./sys --exclude=./dev --exclude=./out . | /bin/tar -xf - -C /target +/bin/tar -cf - --exclude=./target --exclude=./proc --exclude=./sys --exclude=./dev --exclude=./out --exclude=./media --exclude=./fleet-config --exclude=./fleet-bootstrap --exclude=./fleet-downloads . | /bin/tar -xf - -C /target mkdir -p /target/dev /target/proc /target/sys mount --bind /dev /target/dev mount --bind /proc /target/proc mount --bind /sys /target/sys -printf '%s\n' "$receipt" > /target/fleet-receipt +if [ "$delivery" = media ]; then + # What the installed OS reports at first boot, kept only on the target + # disk; the console never carries the token. + mkdir -m 0700 /target/fleet-report + printf '%s' "$receipt" > /target/fleet-report/token + printf '%s' "$report" > /target/fleet-report/url + value reportca | base64 -d > /target/fleet-report/ca.pem + cp /fleet-downloads /target/fleet-report/downloads +else + printf '%s\n' "$receipt" > /target/fleet-receipt +fi chroot /target grub-install --target=i386-pc /dev/vda kernel=$(basename /boot/vmlinuz-*) initrd=$(basename /boot/initrd.img-*) @@ -82,5 +136,24 @@ menuentry Fleet { } CFG sync +if [ "$delivery" = media ]; then + # Read the bootstrap payload back from the target disk, not from memory, + # and report its digest salted for this operation. + cp /fleet-bootstrap /target/fleet-bootstrap + sync + umount /target/dev /target/proc /target/sys + umount /target + echo 3 > /proc/sys/vm/drop_caches + mount -o ro /dev/vda1 /target + bootstrap=$({ printf '%s\n' "$salt"; cat /target/fleet-bootstrap; } | sha256sum | cut -d' ' -f1) + umount /target + mount /dev/vda1 /target + printf 'sha256:%s' "$image" > /target/fleet-report/image + printf 'sha256:%s' "$bootstrap" > /target/fleet-report/bootstrap + sync + umount /target + echo 'fleet: virtual media installer finished' + /bin/busybox poweroff -f +fi printf 'FLEET-INSTALLED:%s\n' "$receipt" /bin/busybox poweroff -f diff --git a/hack/local-vm/site-runtime b/hack/local-vm/site-runtime index bf4899ad..ff828f49 100755 --- a/hack/local-vm/site-runtime +++ b/hack/local-vm/site-runtime @@ -22,6 +22,14 @@ iptables -t mangle -N FLEET-PXE 2>/dev/null || iptables -t mangle -F FLEET-PXE iptables -t mangle -A FLEET-PXE -m addrtype --dst-type LOCAL -j RETURN iptables -t mangle -A FLEET-PXE -m addrtype --dst-type BROADCAST -j RETURN iptables -t mangle -A FLEET-PXE -d "$boot_ip" -p tcp --dport 8080 -j RETURN +# A virtual media install's OS posts its first-boot report from this lab +# network, which stands in for the data network: it may reach the central +# media service's report endpoint, IPv4:port, and nothing more. +if [ -n "${FLEET_MEDIA_REPORT:-}" ]; then + report_ip=${FLEET_MEDIA_REPORT%:*} report_port=${FLEET_MEDIA_REPORT##*:} + case "$report_ip:$report_port" in *[!0-9.:]*|:*|*:) echo 'invalid media report endpoint' >&2; exit 1 ;; esac + iptables -t mangle -A FLEET-PXE -d "$report_ip" -p tcp --dport "$report_port" -j RETURN +fi iptables -t mangle -A FLEET-PXE -j DROP iptables -t mangle -C PREROUTING -i fleetpxe0 -j FLEET-PXE 2>/dev/null || iptables -t mangle -A PREROUTING -i fleetpxe0 -j FLEET-PXE if [ "${FLEET_SITE_PROVIDER:-libvirt}" = redfish ]; then diff --git a/hack/redfish-lab/fleet_lab_adapter.py b/hack/redfish-lab/fleet_lab_adapter.py index aa77c3b0..e9f0eec3 100755 --- a/hack/redfish-lab/fleet_lab_adapter.py +++ b/hack/redfish-lab/fleet_lab_adapter.py @@ -10,13 +10,17 @@ * HTTP Basic authentication against a mounted synthetic credential; * ComputerSystem.Reset (On, ForceOff, ForceRestart) applied to an exact persistent libvirt domain per System, and PowerState read from libvirt; - * Boot source override (Pxe or Hdd, Once) persisted like BMC NVRAM and + * Boot source override (Pxe, Hdd or Cd, Once) persisted like BMC NVRAM and consumed when the domain is started; * a firmware inventory (UpdateService and FirmwareInventory) from firmware.json, which upstream does not serve, so a commissioning plan's firmware baseline can be checked against the lab; * LastResetTime, persisted per System and moved forward each time a reset starts the domain; + * VirtualMedia on each System: two CD devices with InsertMedia, which + fetches the image over HTTPS verifying the lab media service's CA, and + EjectMedia, persisted like BMC state; inserted media are attached to the + domain as CD-ROMs; * an append-only request audit log (no bodies, no credentials), each entry naming the client's User-Agent so a check can tell readers apart; * bounded, one-shot lab fault injection driven by a state file. @@ -28,7 +32,10 @@ import base64 import datetime import fcntl +import hashlib import hmac +import ipaddress +import ssl import json import os import re @@ -37,6 +44,8 @@ import tempfile import threading import time +import urllib.parse +import urllib.request UPSTREAM = os.environ.get('FLEET_BMC_UPSTREAM', '/opt/redfish-emulator') CONFIG_DIR = os.environ.get('FLEET_BMC_CONFIG', '/etc/fleet-bmc') @@ -49,7 +58,14 @@ # workers reach it only over a connection pinned to that key. TLS_DIR = os.environ.get('FLEET_BMC_TLS', '/etc/fleet-bmc-tls') RESET_TYPES = ('On', 'ForceOff', 'ForceRestart') -BOOT_TARGETS = ('None', 'Pxe', 'Hdd') +BOOT_TARGETS = ('None', 'Pxe', 'Hdd', 'Cd') +# Virtual media: two CD devices per System, attached to the domain as IDE +# CD-ROMs in this order. Fetched media live on a volume the hypervisor also +# mounts at the same path. +MEDIA_DEVICES = (('CD1', 'hdc'), ('CD2', 'hdd')) +MEDIA_DIR = os.environ.get('FLEET_BMC_MEDIA', '/var/lib/fleet-lab-media') +MEDIA_CA = os.environ.get('FLEET_BMC_MEDIA_CA', '/etc/fleet-bmc-media-ca/ca.crt') +MEDIA_LIMIT = 1 << 30 BOOT_ENABLED = ('Disabled', 'Once') NETWORK = 'fleet-lab-pxe' # The accelerator the lab targets run under, kvm or tcg. The site runtime that @@ -134,7 +150,12 @@ def require_accelerator(): raise LibvirtError('the site runtime publishes accelerator %r, not %r' % (published, ACCEL)) -def domain_xml(t, boot): +def media_xml(media): + return ''.join("" + % (media[dev]['file'], target) for dev, target in MEDIA_DEVICES if media.get(dev, {}).get('Inserted')) + + +def domain_xml(t, boot, media=None): # Persistent lab target: fixed UUID, MAC, disk and console. Only the boot # device changes, from the Redfish boot override at power-on. return ("{domain}{uuid}20482" @@ -146,6 +167,7 @@ def domain_xml(t, boot): "" "" "" + + media_xml(media or {}).replace('{', '{{').replace('}', '}}') + "").format(boot=boot, **t) @@ -169,9 +191,14 @@ def __init__(self, targets, state, boot_ip): self.targets, self.state, self.boot_ip = targets, state, boot_ip self.nvram_path = os.path.join(state, 'nvram.json') self.nvram = read_json(self.nvram_path, {}) + self.media_path = os.path.join(state, 'media.json') + self.media = read_json(self.media_path, {}) for sid in targets: self.nvram.setdefault(sid, {'BootSourceOverrideEnabled': 'Disabled', 'BootSourceOverrideTarget': 'None'}) + for dev, _ in MEDIA_DEVICES: + self.media.setdefault(sid, {}).setdefault(dev, {'Inserted': False, 'Image': None, 'file': None}) atomic_write(self.nvram_path, self.nvram) + atomic_write(self.media_path, self.media) self.reset_path = os.path.join(state, 'last-reset.json') self.last_reset = read_json(self.reset_path, {}) # A real BMC reports a reset time from its first read, so a restart @@ -209,17 +236,18 @@ def power(self, sid): def save(self): atomic_write(self.nvram_path, self.nvram) + atomic_write(self.media_path, self.media) def power_on(self, sid): t, boot = self.targets[sid], 'hd' override = self.nvram[sid] - if override['BootSourceOverrideEnabled'] == 'Once' and override['BootSourceOverrideTarget'] in ('Pxe', 'Hdd'): - boot = 'network' if override['BootSourceOverrideTarget'] == 'Pxe' else 'hd' + if override['BootSourceOverrideEnabled'] == 'Once' and override['BootSourceOverrideTarget'] in ('Pxe', 'Hdd', 'Cd'): + boot = {'Pxe': 'network', 'Hdd': 'hd', 'Cd': 'cdrom'}[override['BootSourceOverrideTarget']] # Once is consumed by this boot. Persisted before start, like NVRAM. self.nvram[sid] = {'BootSourceOverrideEnabled': 'Disabled', 'BootSourceOverrideTarget': 'None'} self.save() require_accelerator() - virsh('define', '/dev/stdin', input=domain_xml(t, boot)) + virsh('define', '/dev/stdin', input=domain_xml(t, boot, self.media[sid])) virsh('start', t['domain']) # The System came out of a reset now, as a BMC reports it. self.last_reset[sid] = now() @@ -233,6 +261,68 @@ def client(user_agent): return ''.join(c for c in user_agent if ' ' <= c <= '~')[:128] +def is_config(path): + """Whether a fetched medium is a config medium.""" + with open(path, 'rb') as f: + return f.read(15) == b'FLEET-CONFIG-V1' + + +def corrupt_token(path): + """Replace a config medium's report token with another value of the + same shape, in place. Returns False for any other medium.""" + with open(path, 'r+b') as f: + data = f.read() + m = re.search(rb'\ntoken=([0-9a-f]{64})\n', data) + if not data.startswith(b'FLEET-CONFIG-V1') or not m: + return False + other = hashlib.sha256(m.group(1)).hexdigest().encode() + f.seek(0) + f.write(data[:m.start(1)] + other + data[m.end(1):]) + return True + + +def add_download(path): + """Add a download line the operation never pinned to a config medium, + in place, within its padded size. Returns False for any other medium.""" + with open(path, 'r+b') as f: + data = f.read() + if not data.startswith(b'FLEET-CONFIG-V1') or b'\nend\n' not in data: + return False + line = b'download=extension registry.example/extension@sha256:' + hashlib.sha256(b'unpinned').hexdigest().encode() + b'\n' + text = data.rstrip(b'\x00').replace(b'\nend\n', b'\n' + line + b'end\n') + if len(text) > len(data): + return False + f.seek(0) + f.write(text.ljust(len(data), b'\x00')) + return True + + +def fetch(url, path): + """Fetch a medium the way a BMC does: HTTPS only, to a literal IPv4 + endpoint, verifying the lab media service's certificate. Returns the + byte count.""" + u = urllib.parse.urlsplit(url) + if u.scheme != 'https' or u.username or u.password or u.query or u.fragment: + raise ValueError('media must be fetched over HTTPS without credentials or a query') + ipaddress.IPv4Address(u.hostname) + context = ssl.create_default_context(cafile=MEDIA_CA) + tmp = path + '.part' + with urllib.request.urlopen(url, context=context, timeout=25) as r, open(tmp, 'wb') as f: + n = 0 + while True: + chunk = r.read(1 << 20) + if not chunk: + break + n += len(chunk) + if n > MEDIA_LIMIT: + raise ValueError('medium exceeds the size bound') + f.write(chunk) + f.flush() + os.fsync(f.fileno()) + os.replace(tmp, path) + return n + + def error(status, message): return {'error': {'code': 'Base.1.0.GeneralError', 'message': message}}, status @@ -272,6 +362,7 @@ def publish(sid, power=None): m['Name'] = targets[sid]['name'] m['Manufacturer'] = 'DMTF Redfish Interface Emulator (Fleet lab adapter)' m['Model'] = 'libvirt/QEMU lab target' + m['VirtualMedia'] = {'@odata.id': '/redfish/v1/Systems/%s/VirtualMedia' % sid} m['Boot'] = dict(lab.nvram[sid], BootSourceOverrideMode='Legacy', **{ 'BootSourceOverrideTarget@Redfish.AllowableValues': list(BOOT_TARGETS), 'BootSourceOverrideEnabled@Redfish.AllowableValues': list(BOOT_ENABLED)}) @@ -348,6 +439,9 @@ def guard(): request_context.principal = 'authenticated' if path in firmware_docs: return (firmware_docs[path], 200) if request.method == 'GET' else error(405, 'the lab firmware inventory is read-only') + v = re.fullmatch(r'/redfish/v1/Systems/([^/]+)/VirtualMedia(?:/([^/]+)(/Actions/VirtualMedia\.(InsertMedia|EjectMedia))?)?', path) + if v and v.group(1) in targets: + return virtual_media(v.group(1), v.group(2), v.group(4)) m = re.fullmatch(r'/redfish/v1/Systems/([^/]+)(/Actions/ComputerSystem\.Reset|/ResetActionInfo)?', path) if not m: return None @@ -386,6 +480,84 @@ def patch_boot(sid, body): request_context.detail = {'boot': current} return cs.members[sid], 200 + def media_resource(sid, dev): + state = lab.media[sid][dev] + base = '/redfish/v1/Systems/%s/VirtualMedia/%s' % (sid, dev) + return {'@odata.id': base, '@odata.type': '#VirtualMedia.v1_6_0.VirtualMedia', 'Id': dev, 'Name': 'Virtual ' + dev, + 'MediaTypes': ['CD', 'DVD'], 'Inserted': state['Inserted'], 'Image': state['Image'], 'WriteProtected': True, + 'TransferProtocolType': 'HTTPS' if state['Inserted'] else None, 'ConnectedVia': 'URI' if state['Inserted'] else 'NotConnected', + 'Actions': {'#VirtualMedia.InsertMedia': {'target': base + '/Actions/VirtualMedia.InsertMedia'}, + '#VirtualMedia.EjectMedia': {'target': base + '/Actions/VirtualMedia.EjectMedia'}}} + + def virtual_media(sid, dev, action): + devices = [d for d, _ in MEDIA_DEVICES] + if dev is None: + if request.method != 'GET': + return error(405, 'method not allowed') + base = '/redfish/v1/Systems/%s/VirtualMedia' % sid + return {'@odata.id': base, '@odata.type': '#VirtualMediaCollection.VirtualMediaCollection', 'Name': 'Virtual media', + 'Members': [{'@odata.id': base + '/' + d} for d in devices], 'Members@odata.count': len(devices)}, 200 + if dev not in devices: + return error(404, 'no such virtual media device') + if action is None: + if request.method != 'GET': + return error(405, 'method not allowed') + return media_resource(sid, dev), 200 + if request.method != 'POST': + return error(405, 'method not allowed') + body = request.get_json(force=True, silent=True) + if not isinstance(body, dict): + return error(400, 'a JSON object is required') + state = lab.media[sid][dev] + if action == 'InsertMedia': + if not set(body) <= {'Image', 'Inserted', 'WriteProtected', 'TransferProtocolType', 'TransferMethod'} or not isinstance(body.get('Image'), str) or body.get('Inserted', True) is not True: + return error(400, 'unsupported InsertMedia parameters') + if body.get('TransferProtocolType', 'HTTPS') != 'HTTPS': + return error(400, 'only HTTPS media are accepted') + if state['Inserted']: + return error(400, 'a medium is already inserted') + url = body['Image'] + path = os.path.join(MEDIA_DIR, '%s-%s.img' % (targets[sid]['domain'], dev)) + request_context.detail = {'media': dev, 'urlSHA256': hashlib.sha256(url.encode()).hexdigest()} + try: + n = fetch(url, path) + except Exception as e: # noqa: BLE001 the class of failure only, never the URL + request_context.detail.update({'effect': 'fetch-failed', 'error': type(e).__name__}) + return error(400, 'the medium could not be fetched') + if is_config(path) and take('corruptConfig', lambda f: f.get('system') == sid) and corrupt_token(path): + # Lab fault: the medium the BMC holds carries another + # report token than the one the media service served. + request_context.detail['fault'] = 'corrupt-config-token' + elif is_config(path) and take('addDownload', lambda f: f.get('system') == sid) and add_download(path): + # Lab fault: the medium the BMC holds lists a download the + # operation never pinned. + request_context.detail['fault'] = 'add-config-download' + with LOCK: + lab.media[sid][dev] = {'Inserted': True, 'Image': url, 'file': path} + lab.save() + request_context.detail.update({'effect': 'inserted', 'bytes': n}) + return '', 204 + if set(body) - {'Inserted'}: + return error(400, 'unsupported EjectMedia parameters') + drop = take('dropEject', lambda f: f.get('system') == sid and f.get('device') == dev) if state['Inserted'] else None + effect = 'none' + if state['Inserted']: + with LOCK: + if state.get('file'): + try: + os.remove(state['file']) + except FileNotFoundError: + pass + lab.media[sid][dev] = {'Inserted': False, 'Image': None, 'file': None} + lab.save() + effect = 'ejected' + request_context.detail = {'media': dev, 'effect': effect} + if drop: + # Lab fault: the eject is applied, the response is withheld past the client timeout. + request_context.detail['fault'] = 'drop-response-after-effect' + time.sleep(min(int(drop.get('seconds', 45)), 120)) + return '', 204 + def reset(sid): body = request.get_json(force=True, silent=True) kind = body.get('ResetType') if isinstance(body, dict) and set(body) == {'ResetType'} else None @@ -459,6 +631,12 @@ def fault_cli(args): if args[:1] == ['drop-response'] and len(args) in (4, 5): skip = int(args[4]) if len(args) == 5 else 0 faults.update(lambda v: v.setdefault('dropResponse', []).append({'system': args[1], 'resetType': args[2], 'seconds': int(args[3]), 'skip': skip})) + elif args[:1] == ['drop-eject'] and len(args) == 4: + faults.update(lambda v: v.setdefault('dropEject', []).append({'system': args[1], 'device': args[2], 'seconds': int(args[3])})) + elif args[:1] == ['add-download'] and len(args) == 2: + faults.update(lambda v: v.setdefault('addDownload', []).append({'system': args[1]})) + elif args[:1] == ['corrupt-config'] and len(args) == 2: + faults.update(lambda v: v.setdefault('corruptConfig', []).append({'system': args[1]})) elif args[:1] == ['reject-auth'] and len(args) == 2: faults.update(lambda v: v.__setitem__('rejectAuth', int(args[1]))) elif args[:1] == ['hide-reset'] and len(args) == 2: @@ -476,7 +654,8 @@ def fault_cli(args): pass else: raise SystemExit('usage: fault drop-response SYSTEM RESETTYPE SECONDS [SKIP] | drop-request SYSTEM RESETTYPE SECONDS [SKIP]' - ' | swap-identity SYSTEM UUID | hide-reset-time SYSTEM | reject-auth COUNT | hide-reset TYPE | clear | show') + ' | swap-identity SYSTEM UUID | hide-reset-time SYSTEM | drop-eject SYSTEM DEVICE SECONDS | corrupt-config SYSTEM | add-download SYSTEM' + ' | reject-auth COUNT | hide-reset TYPE | clear | show') print(json.dumps(faults.read(), sort_keys=True)) diff --git a/hack/redfish-lab/test_adapter.py b/hack/redfish-lab/test_adapter.py index 3b0357d8..ce2d5517 100644 --- a/hack/redfish-lab/test_adapter.py +++ b/hack/redfish-lab/test_adapter.py @@ -20,7 +20,7 @@ (WORK / 'creds' / 'password').write_text('synthetic-test-password\n') (WORK / 'accelerator').write_text('tcg\n') os.environ.update(FLEET_VIRSH=str(HERE / 'fake_virsh.py'), FAKE_VIRSH_STATE=str(WORK / 'virsh.json'), FLEET_BMC_STATE=str(WORK / 'state'), - FLEET_LAB_ACCEL='tcg', FLEET_LAB_RUNTIME_ACCELERATOR=str(WORK / 'accelerator')) + FLEET_LAB_ACCEL='tcg', FLEET_LAB_RUNTIME_ACCELERATOR=str(WORK / 'accelerator'), FLEET_BMC_MEDIA=str(WORK / 'media')) sys.path.insert(0, str(HERE)) import fleet_lab_adapter as adapter # noqa: E402 @@ -64,7 +64,7 @@ def test_3_system_identity_and_capabilities(self): controllers = self.app.get(s['SimpleStorage']['@odata.id'], headers=AUTH).json['Members'] devices = [d for c in controllers for d in self.app.get(c['@odata.id'], headers=AUTH).json['Devices']] self.assertEqual([d['CapacityBytes'] for d in devices], [2 * 1024 ** 3]) - self.assertEqual(s['Boot']['BootSourceOverrideTarget@Redfish.AllowableValues'], ['None', 'Pxe', 'Hdd']) + self.assertEqual(s['Boot']['BootSourceOverrideTarget@Redfish.AllowableValues'], ['None', 'Pxe', 'Hdd', 'Cd']) # Commissioning checks firmware against the lab's inventory, behind # authentication and read-only. self.assertEqual(self.app.get('/redfish/v1/UpdateService/FirmwareInventory').status_code, 401) @@ -73,13 +73,14 @@ def test_3_system_identity_and_capabilities(self): versions = {f['Id']: f['Version'] for f in (self.app.get(m['@odata.id'], headers=AUTH).json for m in members)} self.assertEqual(versions, {'BMC': '1.2.2-fleet-lab.1', 'BIOS': 'lab-bios-1.0.0'}) self.assertEqual(self.app.patch(members[0]['@odata.id'], headers=AUTH, json={'Version': 'x'}).status_code, 405) + self.assertEqual(s['VirtualMedia'], {'@odata.id': '/redfish/v1/Systems/System-1/VirtualMedia'}) info = self.app.get(s['Actions']['#ComputerSystem.Reset']['@Redfish.ActionInfo'], headers=AUTH).json self.assertEqual(info['Parameters'][0]['AllowableValues'], ['On', 'ForceOff', 'ForceRestart']) def test_4_boot_once_is_consumed_by_power_on(self): r = self.app.patch('/redfish/v1/Systems/System-1', headers=AUTH, json={'Boot': {'BootSourceOverrideTarget': 'Pxe', 'BootSourceOverrideEnabled': 'Once'}}) self.assertEqual(r.status_code, 200) - self.assertEqual(self.app.patch('/redfish/v1/Systems/System-1', headers=AUTH, json={'Boot': {'BootSourceOverrideTarget': 'Cd'}}).status_code, 400) + self.assertEqual(self.app.patch('/redfish/v1/Systems/System-1', headers=AUTH, json={'Boot': {'BootSourceOverrideTarget': 'Usb'}}).status_code, 400) r = self.app.post('/redfish/v1/Systems/System-1/Actions/ComputerSystem.Reset', headers=AUTH, json={'ResetType': 'On'}) self.assertEqual(r.status_code, 204) d = virsh_state()['domains'] @@ -166,6 +167,74 @@ def test_5b_power_faults_and_reset_time(self): self.assertEqual(self.audit()[-1]['fault'], 'drop-response-after-effect') self.assertEqual(system()['PowerState'], 'Off') + def test_8_virtual_media_insert_boot_eject(self): + fetched = [] + + def fake_fetch(url, path): + fetched.append(url) + pathlib.Path(path).write_bytes(b'medium') + return 6 + adapter.fetch, real = fake_fetch, adapter.fetch + os.makedirs(adapter.MEDIA_DIR, exist_ok=True) + try: + base = '/redfish/v1/Systems/System-1/VirtualMedia' + members = self.app.get(base, headers=AUTH).json['Members'] + self.assertEqual([m['@odata.id'] for m in members], [base + '/CD1', base + '/CD2']) + self.assertEqual(self.app.get(base, headers=BAD).status_code, 401) + cd1 = self.app.get(base + '/CD1', headers=AUTH).json + self.assertEqual((cd1['Inserted'], cd1['Image']), (False, None)) + insert = cd1['Actions']['#VirtualMedia.InsertMedia']['target'] + url = 'https://10.96.0.80:8443/media/k/boot/d/boot.iso' + self.assertEqual(self.app.post(insert, headers=AUTH, json={'Image': url, 'TransferProtocolType': 'NFS'}).status_code, 400) + self.assertEqual(self.app.post(insert, headers=AUTH, json={'Image': url, 'Inserted': True, 'WriteProtected': True, 'TransferProtocolType': 'HTTPS'}).status_code, 204) + self.assertEqual(self.app.post(insert, headers=AUTH, json={'Image': url}).status_code, 400) + self.assertEqual(fetched, [url]) + cd1 = self.app.get(base + '/CD1', headers=AUTH).json + self.assertEqual((cd1['Inserted'], cd1['Image']), (True, url)) + self.assertNotIn(url, (WORK / 'state' / 'audit.log').read_text()) + # Boot once from CD attaches the inserted medium. + self.app.post('/redfish/v1/Systems/System-1/Actions/ComputerSystem.Reset', headers=AUTH, json={'ResetType': 'ForceOff'}) + self.app.patch('/redfish/v1/Systems/System-1', headers=AUTH, json={'Boot': {'BootSourceOverrideTarget': 'Cd', 'BootSourceOverrideEnabled': 'Once'}}) + self.app.post('/redfish/v1/Systems/System-1/Actions/ComputerSystem.Reset', headers=AUTH, json={'ResetType': 'On'}) + self.assertEqual(virsh_state()['domains']['fleet-lab-target-a']['starts'][-1], 'cdrom') + self.app.post('/redfish/v1/Systems/System-1/Actions/ComputerSystem.Reset', headers=AUTH, json={'ResetType': 'ForceOff'}) + # A corrupted config medium carries another report token. + def config_fetch(url, path): + pathlib.Path(path).write_bytes(b'FLEET-CONFIG-V1\ntoken=' + b'a' * 64 + b'\nend\n') + return 1 + adapter.fault_cli(['corrupt-config', 'System-1']) + # A boot medium does not consume the fault. + cd2 = self.app.get(base + '/CD2', headers=AUTH).json + self.assertEqual(self.app.post(cd2['Actions']['#VirtualMedia.InsertMedia']['target'], headers=AUTH, json={'Image': url}).status_code, 204) + self.assertNotIn('fault', self.audit()[-1]) + self.app.post(cd2['Actions']['#VirtualMedia.EjectMedia']['target'], headers=AUTH, json={}) + adapter.fetch = config_fetch + self.assertEqual(self.app.post(cd2['Actions']['#VirtualMedia.InsertMedia']['target'], headers=AUTH, json={'Image': url}).status_code, 204) + self.assertEqual(self.audit()[-1].get('fault'), 'corrupt-config-token') + held = (WORK / 'media' / 'fleet-lab-target-a-CD2.img').read_bytes() + self.assertIn(b'token=', held) + self.assertNotIn(b'a' * 64, held) + self.app.post(cd2['Actions']['#VirtualMedia.EjectMedia']['target'], headers=AUTH, json={}) + # A config medium can gain a download the operation never pinned. + adapter.fault_cli(['add-download', 'System-1']) + self.assertEqual(self.app.post(cd2['Actions']['#VirtualMedia.InsertMedia']['target'], headers=AUTH, json={'Image': url}).status_code, 204) + self.assertEqual(self.audit()[-1].get('fault'), 'add-config-download') + held = (WORK / 'media' / 'fleet-lab-target-a-CD2.img').read_bytes().rstrip(b'\0') + self.assertIn(b'\ndownload=extension registry.example/extension@sha256:', held) + self.assertTrue(held.endswith(b'\nend\n')) + self.app.post(cd2['Actions']['#VirtualMedia.EjectMedia']['target'], headers=AUTH, json={}) + # A withheld eject response still ejects. + adapter.fault_cli(['drop-eject', 'System-1', 'CD1', '0']) + eject = cd1['Actions']['#VirtualMedia.EjectMedia']['target'] + self.assertEqual(self.app.post(eject, headers=AUTH, json={}).status_code, 204) + self.assertEqual(self.audit()[-1].get('fault'), 'drop-response-after-effect') + cd1 = self.app.get(base + '/CD1', headers=AUTH).json + self.assertEqual((cd1['Inserted'], cd1['Image']), (False, None)) + self.assertEqual(self.app.post(eject, headers=AUTH, json={}).status_code, 204) + self.assertEqual(self.audit()[-1]['effect'], 'none') + finally: + adapter.fetch = real + def test_7_synced_dhcp_network_has_no_dhcp_server(self): targets = {'System-1': {'mac': '52:54:00:77:01:0a', 'ip': '192.168.77.10'}} static = adapter.network_xml(targets, '10.96.0.80', 'static') From 9cafec4ed9e6cd6b67ea0e6b5cc9a73d68b1e869 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Fri, 27 Nov 2026 11:56:16 -0600 Subject: [PATCH 04/35] test(multiplane): Run the virtual media suite run.sh --redfish --virtual-media runs the central media service beside the coordinator and proves, on the lab target, that: - a method the site does not offer and an unpinned download are refused; - a report with the wrong token, none, another token or from another address is never taken, and the install is held; - a report naming a download the install never pinned holds it; - a lost eject response holds the next install; - a fourth install settles the hold, succeeds and proves release; - windows from no certificate, another site or a stale fence are refused. The Redfish suite's worker RBAC step checks the worker gets only its own identity Secret and the BMC credential holds only BMC keys. Co-Authored-By: Claude Opus 5.5 --- Taskfile.yaml | 7 + cmd/fleet-multiplane/main.go | 40 ++- docs/operations/redfish-lab.md | 102 +++++++ hack/multiplane/acceptance-media.sh | 49 ++++ hack/multiplane/flux.py | 5 +- hack/multiplane/harness.py | 6 + hack/multiplane/k8s_evidence.py | 24 +- hack/multiplane/media-central.sh | 48 ++++ hack/multiplane/media_steps.py | 429 ++++++++++++++++++++++++++++ hack/multiplane/redfish_steps.py | 40 +++ hack/multiplane/run.sh | 19 +- hack/multiplane/stop.sh | 1 + hack/multiplane/teardown.sh | 1 + hack/multiplane/verify-rbac.py | 20 +- internal/multiplane/media.go | 393 +++++++++++++++++++++++++ internal/multiplane/runner.go | 22 +- 16 files changed, 1184 insertions(+), 22 deletions(-) create mode 100755 hack/multiplane/acceptance-media.sh create mode 100755 hack/multiplane/media-central.sh create mode 100644 hack/multiplane/media_steps.py create mode 100644 internal/multiplane/media.go diff --git a/Taskfile.yaml b/Taskfile.yaml index 5d288f83..1874038a 100644 --- a/Taskfile.yaml +++ b/Taskfile.yaml @@ -26,6 +26,13 @@ tasks: cmds: - ./hack/multiplane/run.sh --redfish {{.CLI_ARGS}} + multiplane:media-acceptance: + desc: "The Redfish-mode virtual media suite: the worker installs a lab VM over Redfish VirtualMedia from the site's media service, then proves release (same exit codes)." + env: + FLEET_MULTIPLANE_INOTIFY: '1024' + cmds: + - ./hack/multiplane/run.sh --redfish --virtual-media {{.CLI_ARGS}} + multiplane:preflight: desc: Check local prerequisites and implementation readiness without creating resources. env: diff --git a/cmd/fleet-multiplane/main.go b/cmd/fleet-multiplane/main.go index 245add01..8b727c5d 100644 --- a/cmd/fleet-multiplane/main.go +++ b/cmd/fleet-multiplane/main.go @@ -7,6 +7,7 @@ import ( "errors" "flag" "fmt" + "net/netip" "os" "os/signal" "strings" @@ -32,7 +33,7 @@ func main() { func run() error { if len(os.Args) < 2 { - return fmt.Errorf("usage: fleet-multiplane coordinator|site-worker|site-observer|image|boot-service|boot-withhold|boot-denials|dhcp-feed|redfish-probe| [flags]") + return fmt.Errorf("usage: fleet-multiplane coordinator|site-worker|site-observer|image|boot-service|boot-withhold|media-stale|media-service|boot-denials|dhcp-feed|redfish-probe| [flags]") } fs := flag.NewFlagSet(os.Args[1], flag.ContinueOnError) once := fs.Bool("once", false, "one attempt, for fault injection") @@ -52,8 +53,14 @@ func run() error { syncToken := fs.String("sync-token-file", "", "file holding the DHCP synchronizer bearer token (dhcp-feed)") installationDeadline := fs.Duration("installation-deadline", 0, "replace the installation deadline for operations this coordinator admits (coordinator)") skewMargin := fs.Duration("skew-margin", 0, "replace the margin after a deadline before the coordinator declares it exceeded (coordinator)") - tlsCert := fs.String("tls-cert", "", "TLS certificate the DHCP feed serves (dhcp-feed)") - tlsKey := fs.String("tls-key", "", "TLS key of the DHCP feed (dhcp-feed)") + tlsCert := fs.String("tls-cert", "", "TLS certificate the DHCP feed or media service serves (dhcp-feed, media-service)") + tlsKey := fs.String("tls-key", "", "TLS key of the DHCP feed or media service (dhcp-feed, media-service)") + deviceName := fs.String("device", "", "exact / Device (media-stale)") + listen := fs.String("listen", "127.0.0.1:18443", "listen address (media-service)") + mediaRoot := fs.String("state-dir", "", "the media service's own state directory (media-service)") + mediaArtifacts := fs.String("artifacts", "", "directory of the image's pinned artifacts (media-service)") + mediaClients := fs.String("clients", "", "comma-separated IPv4 prefixes the media service serves (media-service)") + clientCA := fs.String("client-ca", "", "CA that signs the site workers' client certificates (media-service)") if err := fs.Parse(os.Args[2:]); err != nil { return err } @@ -69,7 +76,7 @@ func run() error { return multiplane.Coordinate(ctx, config, multiplane.CoordinatorOptions{InstallationDeadline: *installationDeadline, SkewMargin: *skewMargin}, func(err error) { fmt.Fprintf(os.Stderr, "%s coordinator: pass incomplete: %v\n", time.Now().UTC().Format(time.RFC3339), err) }) - case "seed", "commission", "allocate", "install", "admit-install", "admit-install-b", "release", "release-b", "reuse", "recovery-mismatch", "probe-unallocatable", "tenant-isolation": + case "seed", "commission", "allocate", "install", "admit-install", "admit-install-b", "release", "release-b", "reuse", "recovery-mismatch", "probe-unallocatable", "tenant-isolation", "media-not-offered", "media-unpinned", "media-install-held", "media-install-download", "media-install-lost", "media-install": return phase(os.Args[1], *configPath, *once) case "redfish-probe": return probe(*endpoint, *credentials, *system, *uuid, *pin, *clientID) @@ -84,6 +91,28 @@ func run() error { return boot(os.Args[1], *origin, *extraMAC, *syncToken, *tlsCert, *tlsKey) case "boot-withhold": return armWithhold(fs.Arg(0)) + case "media-stale": + return mediaStale(*deviceName) + case "media-service": + config, err := multiplane.ReadConfig(*configPath) + if err != nil { + return err + } + var clients []netip.Prefix + for _, value := range strings.Split(*mediaClients, ",") { + prefix, err := netip.ParsePrefix(strings.TrimSpace(value)) + if err != nil { + return fmt.Errorf("media-service: -clients must list IPv4 prefixes") + } + clients = append(clients, prefix.Masked()) + } + if *mediaRoot == "" || *mediaArtifacts == "" || *tlsCert == "" || *tlsKey == "" || *clientCA == "" { + return fmt.Errorf("media-service needs -state-dir, -artifacts, -tls-cert, -tls-key and -client-ca") + } + ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) + defer cancel() + fmt.Println("media-service: central media service running") + return multiplane.MediaService(ctx, config, *listen, *tlsCert, *tlsKey, *clientCA, *mediaRoot, *mediaArtifacts, clients) case "site-worker", "site-observer": default: return fmt.Errorf("unknown command") @@ -156,6 +185,7 @@ func phase(name, configPath string, once bool) error { "commission": r.Commission, "allocate": r.Allocate, "admit-install": r.AdmitInstall, "install": r.Install, "release": r.Release, "release-b": r.ReleaseSecond, "reuse": r.Reuse, "admit-install-b": r.AdmitInstallSecond, "recovery-mismatch": r.RecoveryMismatch, "probe-unallocatable": r.ProbeUnallocatable, "tenant-isolation": r.TenantIsolation, + "media-not-offered": r.MediaNotOffered, "media-unpinned": r.MediaUnpinned, "media-install-held": r.MediaInstallHeld, "media-install-download": r.MediaInstallDownload, "media-install-lost": r.MediaInstallLost, "media-install": r.MediaInstall, }[name] last := "" for { @@ -170,7 +200,7 @@ func phase(name, configPath string, once bool) error { fmt.Println("Installation admitted and delivered; its result remains Unknown") return nil } - if err == nil && (name == "commission" || name == "recovery-mismatch" || name == "probe-unallocatable" || name == "tenant-isolation") { + if err == nil && (name == "commission" || name == "recovery-mismatch" || name == "probe-unallocatable" || name == "tenant-isolation" || strings.HasPrefix(name, "media-")) { return nil } if err == nil { diff --git a/docs/operations/redfish-lab.md b/docs/operations/redfish-lab.md index 661fbfb3..0f3c8885 100644 --- a/docs/operations/redfish-lab.md +++ b/docs/operations/redfish-lab.md @@ -521,6 +521,108 @@ Redfish-specific evidence files are `redfish-upstream.json`, `physicalHardware`, `physicalBMC`, `vendorRedfishQualified`, `bmcTLS` and `mediaSanitization` flags as `false`. +## Virtual media suite (prototype) + +A prototype of virtual media, the second boot delivery method proposed in +[#227](https://github.com/datum-cloud/fleet/pull/227), built to the +product owner's revision of that contract. It runs as its own Redfish-mode +suite: + +```sh +task multiplane:media-acceptance +# equivalent: +FLEET_MULTIPLANE_INOTIFY=1024 hack/multiplane/run.sh --redfish --virtual-media +``` + +Status: **implemented and verified by unit tests**. The end-to-end record is +in the pull request that adds it. Network boot is unchanged behind the same +seam; the regular Redfish suite above covers it. + +### How an install works + +1. The Metal provider selects the method: the held installation's method + when it settles a hold, or else the first method in the site's order the + server is qualified for. The installation records the method, the central + media service, the address mode and the two phase windows. Admission + checks them again under the custody update. +2. The worker renders a config medium with a fresh report token and salt, + and opens the operation's window at the central media service. The + service opens it only while custody names that operation active at that + fence. +3. The worker ejects any leftover media, inserts the boot and config media, + reads both URLs back by digest, sets a one-time boot from CD and powers + the server on. The BMC fetches both media over HTTPS it verifies. +4. The installer installs the image, reads the bootstrap payload back from + disk, and powers off. It reports nothing. +5. The worker boots the installed disk once. At first boot the installed OS + brings up its data network and posts its report over HTTPS, verifying the + media service: the report token, the boot medium's content digest and the + salted bootstrap digest. +6. The worker takes exactly one report with the token and the expected + digests before the report deadline. It then closes every window of the + Device, ejects every device, and proves release from the BMC (every + device empty, no override) and the media service (no open window, no + transfer in progress, no reused token). + +Any step that was sent and cannot be proven ends `OutcomeUnknown` with a +hold, after an attempt to undo delivery that is never proof. A window the +media service refuses outright ends the operation `Failed` when the journal +holds no BMC step, and `OutcomeUnknown` otherwise. + +A site may stop offering a method at any time: new operations no longer +select it, and a running one finishes with it. A hold prepared with it waits, +because only that method can prove its release. Admission refuses a settling +operation while no serving site offers the method, and the coordinator +records `HeldMethodNotOffered` on the hold for staff until a site offers it +again. The serial +console is diagnostics only and never carries a token. + +The deadline is the sum of the fetch window, 15 minutes by default, and the +report window, 30 minutes by default. A site may set shorter ones; the lab +uses 5 and 10 minutes. + +### What is real and what is stubbed + +| Part | In the prototype | +| --- | --- | +| Delivery inputs | Real. Each installation records its method and the method's inputs before admission; the input digest pins them. | +| Site declaration | Real, with one simplification: the coordinator's site configuration declares each site's methods in preference order. The Metal provider selects from the same declaration. | +| Admission | Real for the site and qualification checks, the settling-hold rule, input consistency and digest-pinned downloads. A machine class cannot restrict methods yet. | +| Qualification | Stubbed. Staff set the `fleet.datumapis.com/qualified-delivery-methods` annotation on the Device. A Device without it is qualified for network boot only. Commissioning will replace it. | +| Central media service | Real windows, fences from custody, media, report endpoint, transfer records and a background sweep that drops config media no window can serve. The sweep skips and counts a window file it cannot read, and goes on. In the lab it runs on the workstation beside the coordinator, on loopback, which lab Pods and guests reach through the runtime's host gateway. | +| Worker authentication | Real. Each site worker presents a client certificate from the site workers' CA. The certificate is its own Secret, `fleet-site-worker-media`, one per site worker identity, in the `fleet-site-worker-identity` namespace. Each worker gets exactly that Secret through a per-operation Role, and BMC credential Secrets hold only BMC credentials. Only virtual media reads it: network boot installs and wipes neither read nor need it. The service refuses every window operation from a client with no certificate, or one that is not the worker for that Device's site. | +| BMC | Real Redfish VirtualMedia on the lab emulator: two CD devices, insert over verified HTTPS, eject, readback, one-time boot from CD. | +| First-boot report | Real. The installed lab OS posts it over HTTPS. Bootstrap data is always empty because the sealed store is not on this branch; admission still refuses bootstrap data. | +| Installer downloads | Admission refuses any download that is not pinned by digest. The config medium lists the pinned downloads, and the first-boot report names each download by the digest the installer fetched. The worker refuses a report whose downloads are not exactly the recorded ones. The lab installer fetches nothing; it reports what its config medium lists. | +| Report source | Each window records where its first-boot report may come from, and the media service refuses a report from any other address. In the lab every report reaches the service through the runtime's host gateway on IPv4 loopback, so the lab checks this with a report sent over IPv6 loopback. Restricting reports to the Machine's own address needs a real site network. | +| BMCs that do not verify HTTPS | Stubbed. Staff record `fleet.datumapis.com/virtual-media-tls: Unverified`, and admission refuses virtual media for that server. The fallback that mounts only the public medium and fetches bootstrap data with a single-use token is not implemented. | +| Lab data network | The lab provisioning network stands in for the customer's data network. Its firewall lets guests reach the boot Service and the central media service's report endpoint, and nothing else. | +| Addresses | `DataNetwork` only: the config medium carries no address and Fleet assigns none. `Static` needs NSO interface claims, which are not on this branch. | +| Media service client scoping | Weaker than proposed. In the lab every request reaches it from loopback, so it cannot tell the Device's BMC from any other client. | + +Talos installs from its ISO by pulling the installer container image that +`machine.install.image` names from a registry, so a Talos image offered on +virtual media must list that image, pinned by digest, as a download. Talos +v1.9.5 installs from a digest-only reference: booted from its metal ISO under +QEMU with `machine.install.image` set to +`ghcr.io/siderolabs/installer@sha256:9e6c6564b870813b0f88032dabf1140fd1157f9ecf8736dfbf8d3df25cb891dd`, +it pulled that reference, installed, and booted the installed disk. + +### Suite phases + +| Phase | What it proves | +| --- | --- | +| `media-not-offered` | While the cell declares network boot only, a virtual media installation is refused with `DeliveryMethodNotOffered`. The fence does not change and nothing is delivered. | +| `media-central`, `media-offer` | The central media service starts with the image's pinned artifacts. The operator adds virtual media after network boot; staff record target A as qualified for virtual media only. | +| `media-unpinned` | An installation whose installer downloads an image by tag is refused with `InstallDownloadUnpinned`. | +| `media-arm-corrupt-token`, `media-install-held`, `media-held-report` | The lab BMC's config medium carries another report token. The installed OS's report is refused, as are a report with no token, one with another token, and one from an address that is not the Machine's, posted while the window is open. No report is taken, and the installation ends `OutcomeUnknown` at its report deadline with a hold that records virtual media. | +| `media-arm-add-download`, `media-install-download`, `media-held-download` | The next installation settles that hold with the held method. The lab BMC adds a download the operation never pinned to its config medium; the first-boot report names it, so the report is never verified and the installation is held. | +| `media-arm-lost-eject`, `media-install-lost`, `media-held-eject` | The next installation settles that hold with the held method. Its report is taken, then the BMC withholds an eject response past the client timeout: `OutcomeUnknown`, release never journaled. | +| `media-install` | A fourth installation settles the third hold, succeeds, and clears it. | +| `media-release-proof` | The BMC reads back both devices empty and no override. The media service reports four windows, none open, no transfer in progress and no reused token, and denies each one live. No config medium is kept anywhere. | +| `media-stale-fence` | For each of the four operations, the media service refuses a window open with no client certificate (401), with another site's worker certificate (403), and as the cell's worker once custody no longer names the operation (409). The site store refuses a media window and step below the stored fence. | +| `media-evidence` | Each taken report carries its operation's digests; target A booted media then disk four times; the console carries no token; target B was never touched. Writes `virtual-media.json`. | + ## Offline checks ```sh diff --git a/hack/multiplane/acceptance-media.sh b/hack/multiplane/acceptance-media.sh new file mode 100755 index 00000000..19f005cb --- /dev/null +++ b/hack/multiplane/acceptance-media.sh @@ -0,0 +1,49 @@ +#!/usr/bin/env bash +# Ordered virtual media acceptance phases (run.sh --redfish --virtual-media). +# The same allocator, Karmada, kro and Flux path as acceptance-redfish.sh; the +# worker delivers the installer as virtual media through the lab BMC's +# Redfish VirtualMedia and the central media service, and the installed OS +# posts its report there at first boot. Each phase is bounded and recorded; +# the first failure stops the run. +set -euo pipefail +umask 077 +state=${1:?private state directory} +export DOCKER_CONTEXT=colima-fleet-acceptance-tcg FLEET_SITE_PROVIDER=redfish +host="$state/fleet-multiplane-host" +ph() { python3 hack/multiplane/harness.py phase --state "$state" --name "$1" --timeout "$2" --echo -- "${@:3}"; } +rf() { ph "redfish-$1" "$2" python3 hack/multiplane/redfish_steps.py "$1" "$state"; } +md() { ph "media-$1" "$2" python3 hack/multiplane/media_steps.py "$1" "$state"; } +run() { ph "$1" "$2" "$host" "$1" --config "$state/acceptance.json"; } + +ph rbac 600 python3 hack/multiplane/verify-rbac.py "$state" +rf baseline 300 +run allocate 900 +# The cell declares network boot only: a virtual media installation is +# refused at admission and nothing is delivered. +run media-not-offered 600 +ph media-central 300 bash hack/multiplane/media-central.sh start "$state" +md offer 300 +# An installer download by tag, not digest, is refused at admission. +run media-unpinned 600 +# Dispatch is a source revision the cell's Flux reconciles, as in the +# Redfish suite; kro then creates a worker Job per delivered operation. +ph dispatch 900 python3 hack/multiplane/flux.py publish "$state" --revision 3 --site dispatch --purpose 'enable dispatch' --cluster cell --timeout 600 +# The first install's report carries another token: it is held. +md arm-corrupt-token 120 +run media-install-held 3000 +md held-report 300 +# The second install settles that hold, but its config medium gains a +# download the operation never pinned: its report names it, and it is held. +md arm-add-download 120 +run media-install-download 3000 +md held-download 300 +# The third install settles that hold, then loses an eject response: held +# again. +md arm-lost-eject 120 +run media-install-lost 3000 +md held-eject 300 +# The fourth install settles that hold, proves release and clears it. +run media-install 3000 +md release-proof 300 +md stale-fence 120 +md evidence 600 diff --git a/hack/multiplane/flux.py b/hack/multiplane/flux.py index 8bc1f903..a6814f7b 100644 --- a/hack/multiplane/flux.py +++ b/hack/multiplane/flux.py @@ -311,7 +311,10 @@ def stage(args): if args.site != 'absent': resources.insert(2, '../../config/multiplane/clusters/cell-site') data.update(FLEET_SITE_IMAGE=env['siteImage'], FLEET_BOOT_SERVICE_IP=BOOT_SERVICE_IP, - FLEET_SITE_DISPATCH='true' if args.site == 'dispatch' else 'false', FLEET_LOCAL_VM_ACCEL=harness.ACCEL) + FLEET_SITE_DISPATCH='true' if args.site == 'dispatch' else 'false', FLEET_LOCAL_VM_ACCEL=harness.ACCEL, + # The central media service's certificate (public), so + # Redfish workers verify it; empty where none runs. + FLEET_MEDIA_CA=env.get('mediaCA', '')) if args.bad_kro_chart: patches.append(child_patch('kro', [{'target': {'kind': 'OCIRepository', 'name': 'kro-chart'}, 'patch': '- op: replace\n path: /spec/ref/digest\n value: %s\n' % MISSING_DIGEST}], diff --git a/hack/multiplane/harness.py b/hack/multiplane/harness.py index ae77b20c..627c7029 100755 --- a/hack/multiplane/harness.py +++ b/hack/multiplane/harness.py @@ -563,6 +563,12 @@ def secrets(state): found.add(json.loads(text).get('token') or '') except (ValueError, AttributeError): pass + # A copied rendered config medium carries its URL capability. + if p.suffix == '.json' and p.parent.name == 'mediacfg': + try: + found.add(json.loads(text).get('capability') or '') + except (ValueError, AttributeError): + pass for m in re.finditer(r'-----BEGIN [A-Z ]*PRIVATE KEY-----[^-]+', text): found.add(m.group(0)[40:100]) return {s for s in found if s and len(s) >= 16} diff --git a/hack/multiplane/k8s_evidence.py b/hack/multiplane/k8s_evidence.py index 00e86e1a..a213c986 100644 --- a/hack/multiplane/k8s_evidence.py +++ b/hack/multiplane/k8s_evidence.py @@ -17,6 +17,8 @@ import harness # noqa: E402 (site store layout) NS, SITE, CREDENTIALS = 'fleet-coordination', 'fleet-site', 'fleet-site-credentials' +IDENTITY, IDENTITY_SECRET = 'fleet-site-worker-identity', 'fleet-site-worker-media' +BMC_CREDENTIAL_KEYS = ['password', 'tlsPublicKeySHA256', 'username'] LIBVIRT = 'qemu:///system?socket=/run/fleet-libvirt/libvirt-sock' REDFISH = os.environ.get('FLEET_SITE_PROVIDER') == 'redfish' CELL_LABEL, ROLE_LABEL = 'coordination.fleet.datumapis.com/cell', 'coordination.fleet.datumapis.com/role' @@ -143,10 +145,28 @@ def worker_rbac(state, name): creds = get(state, '-n', CREDENTIALS, 'get', 'role', 'w-' + name) if creds['rules'] != [{'apiGroups': [''], 'resources': ['secrets'], 'resourceNames': [own], 'verbs': ['get']}]: raise SystemExit('Redfish worker credential Role is not get on its one Secret: %s' % creds['rules']) - record.update(ownCredentialReadable=True, credentialRoleRules=creds['rules']) + # The worker's media service identity is its own Secret: the worker + # gets exactly the site's, never another site's, and lists none. The + # BMC credential carries no client certificate. + own_identity = kubectl(state, '-n', IDENTITY, 'get', 'secret', IDENTITY_SECRET, '-o', 'name', check=False, config='worker-kubeconfig.json') + if own_identity.returncode: + raise SystemExit('Redfish worker cannot get the site worker identity Secret: ' + own_identity.stderr[:200]) + for args in (('-n', IDENTITY, 'get', 'secret', IDENTITY_SECRET + '-another-cell'), ('-n', IDENTITY, 'get', 'secrets')): + r = kubectl(state, *args, check=False, config='worker-kubeconfig.json') + if r.returncode == 0 or 'forbidden' not in r.stderr.lower(): + raise SystemExit('worker identity access allowed: ' + ' '.join(args[:4]) + ' ' + r.stderr[:200]) + denied.append(args[1] + ' ' + ' '.join(args[2:4])) + identity_role = get(state, '-n', IDENTITY, 'get', 'role', 'w-' + name) + if identity_role['rules'] != [{'apiGroups': [''], 'resources': ['secrets'], 'resourceNames': [IDENTITY_SECRET], 'verbs': ['get']}]: + raise SystemExit('Redfish worker identity Role is not get on the one identity Secret: %s' % identity_role['rules']) + keys = sorted(get(state, '-n', CREDENTIALS, 'get', 'secret', spec['credential']).get('data', {})) + if keys != BMC_CREDENTIAL_KEYS: + raise SystemExit('the BMC credential Secret holds more than BMC credentials: %s' % keys) + record.update(ownCredentialReadable=True, credentialRoleRules=creds['rules'], ownIdentityReadable=True, identityRoleRules=identity_role['rules'], + bmcCredentialKeys=keys) write(s / 'k8s-worker-rbac.json', record) print('worker-rbac: per-operation ServiceAccount reads only its own handoff; list, other names, status, spec, Secrets and site writes forbidden' - + ("; it gets only its own Device's BMC credential Secret, never another's, and lists none" if REDFISH else '')) + + ("; it gets only its own Device's BMC credential Secret, never another's, and lists none; it gets the site worker identity Secret, never another site's; the BMC credential holds only BMC keys" if REDFISH else '')) def record_pod_interrupt(state, before, after): diff --git a/hack/multiplane/media-central.sh b/hack/multiplane/media-central.sh new file mode 100755 index 00000000..27f5c115 --- /dev/null +++ b/hack/multiplane/media-central.sh @@ -0,0 +1,48 @@ +#!/usr/bin/env bash +# Start or stop this run's central media service: the workstation process, +# beside the coordinator, that serves virtual media to the lab BMC and takes +# first-boot reports. It listens on loopback only; lab Pods and guests reach +# it through the runtime's host gateway. It reads custody with the +# coordinator's identity, keeps its own state, and logs to the private state +# directory. start extracts the image's pinned artifacts from the site +# image, the same bytes the site serves for network boot. +set -euo pipefail +action=${1:?start or stop} +state=${2:?private run state directory required} +pidfile="$state/media-central.pid" +case $action in + start) + if [[ -f $pidfile ]] && kill -0 "$(cat "$pidfile")" 2>/dev/null; then + echo "media-central: already running" + exit 0 + fi + prefix=$(cat "$state/prefix") + artifacts="$state/media-artifacts" + if [[ ! -f $artifacts/SHA256SUMS ]]; then + mkdir -p "$artifacts" && chmod 0700 "$artifacts" + id=$(docker create "$prefix-site-image" true) + docker cp "$id:/opt/fleet-local/artifacts/." "$artifacts/" >/dev/null + docker rm "$id" >/dev/null + fi + mkdir -p "$state/media-central" && chmod 0700 "$state/media-central" + nohup "$state/fleet-multiplane-host" media-service --config "$state/acceptance.json" --listen "127.0.0.1:28443,[::1]:28443" \ + --tls-cert "$state/redfish/media-tls.crt" --tls-key "$state/redfish/media-tls.key" --client-ca "$state/redfish/media-worker-ca.crt" \ + --state-dir "$state/media-central" --artifacts "$artifacts" --clients 127.0.0.0/8,::1/128 >>"$state/media-central.log" 2>&1 "$pidfile" + sleep 2 + kill -0 "$(cat "$pidfile")" || { echo 'media-central: exited at start; see media-central.log in the state directory' >&2; exit 1; } + echo "media-central: running on loopback; the image's artifacts verified" + ;; + stop) + if [[ -f $pidfile ]]; then + pid=$(cat "$pidfile") + if kill -0 "$pid" 2>/dev/null; then + kill "$pid" + for _ in $(seq 1 30); do kill -0 "$pid" 2>/dev/null || break; sleep 1; done + fi + rm -f "$pidfile" + fi + echo "media-central: stopped" + ;; + *) echo 'usage: media-central.sh start|stop STATE' >&2; exit 64 ;; +esac diff --git a/hack/multiplane/media_steps.py b/hack/multiplane/media_steps.py new file mode 100644 index 00000000..d2609fa9 --- /dev/null +++ b/hack/multiplane/media_steps.py @@ -0,0 +1,429 @@ +#!/usr/bin/env python3 +"""Virtual media acceptance steps (hack/multiplane/run.sh --redfish --virtual-media). + +Observations go through the selected cell's API, the provider project and +the central media service's own records. Lab faults are written only through +the lab BMC adapter's fault file and are recorded. Evidence keeps methods, +paths, outcome classes, fences and digests; never a media URL, a URL +capability or a report token. + + offer the operator adds virtual media after network boot, with + the central media service and the lab's short phases, and + restarts the coordinator; staff record target A as + qualified for virtual media only (the lab stand-in for + commissioning) + arm-corrupt-token one-shot: the lab BMC's next config medium carries another + report token than the one the media service served + held-report the first install booted from media and its OS posted a + report with the wrong token; stray reports without a + token or with another token were refused; nothing was + taken, so it ended OutcomeUnknown + arm-add-download one-shot: the lab BMC's next config medium lists a + download the operation never pinned + held-download the second install's report named that download, so it + was never verified and the install was held + arm-lost-eject one-shot: the BMC applies target A's next CD1 eject and + withholds its response past the worker's client timeout + held-eject the third install's report was taken, then the eject + response was lost: OutcomeUnknown, release never journaled + release-proof after the settling install: the BMC reads back both + devices empty and no override, the media service reports + no open window, transfer or reused token for the Device, + and denies every window + stale-fence the media service refuses to open a window for an + operation custody no longer names, and the site store + refuses a media window and step below the stored fence + evidence the shareable virtual media evidence record +""" +import base64 +import datetime +import hashlib +import json +import pathlib +import re +import ssl +import subprocess +import sys +import time +import urllib.error +import urllib.request + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) +import harness # noqa: E402 (site store layout) +import redfish_steps as rf # noqa: E402 + +SYSTEM = 'System-1' +DEVICE_NAME = harness.DEVICE.split('/')[1] +QUALIFIED = 'fleet.datumapis.com/qualified-delivery-methods' +STORE_ROOT = '/var/lib/fleet-local/site' +LOCAL = 'https://127.0.0.1:%d' % rf.MEDIA_PORT +# The lab's virtual media phases, shorter than the 15 and 30 minute +# defaults, as a site may set. +FETCH, REPORT = '5m0s', '10m0s' + + +def now(): + return datetime.datetime.now(datetime.timezone.utc).isoformat() + + +def later(minutes): + return (datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(minutes=minutes)).isoformat().replace('+00:00', 'Z') + + +def die(message): + raise SystemExit(message) + + +def provider(s, *args, check=True): + """kubectl against the provider project as its bootstrap identity.""" + r = subprocess.run(['kubectl', '--kubeconfig', str(s / 'provider' / 'bootstrap-project.json'), '--request-timeout=30s', *args], + text=True, capture_output=True, timeout=60) + if check and r.returncode: + die('provider kubectl %s failed: %s' % (' '.join(args[:3]), r.stderr.strip()[-300:])) + return r + + +def media_installs(s): + items = json.loads(provider(s, '-n', 'fleet-provider', 'get', 'deviceinstallations', '-o', 'json').stdout)['items'] + return sorted((i for i in items if i['spec'].get('delivery', {}).get('method') == 'VirtualMedia' and i.get('status', {}).get('fence')), + key=lambda i: i['status']['fence']) + + +def key(uid): + return hashlib.sha256(uid.encode()).hexdigest()[:16] + + +def central(s, method, path, body=None, identity='media-worker'): + """A request to the central media service on loopback, verifying it, as + the cell's site worker by default; identity None presents no client + certificate.""" + context = ssl.create_default_context(cafile=str(s / 'redfish' / 'media-tls.crt')) + if identity: + context.load_cert_chain(str(s / 'redfish' / (identity + '.crt')), str(s / 'redfish' / (identity + '.key'))) + data = json.dumps(body).encode() if body is not None else None + request = urllib.request.Request(LOCAL + path, data=data, method=method, headers={'Content-Type': 'application/json'}) + try: + with urllib.request.urlopen(request, context=context, timeout=20) as r: + return r.status, json.loads(r.read() or b'null') + except urllib.error.HTTPError as e: + return e.code, None + + +def window_record(s, uid): + """The central service's own record of a window, without its medium.""" + w = json.loads((s / 'media-central' / 'windows' / (key(uid) + '.json')).read_text()) + w['configMediumKept'] = bool(w.pop('configMedium', None)) + return w + + +def site_window(s, uid): + """The site's digests of a window: what the report had to carry.""" + return json.loads(rf.runtime(s, 'sh', '-c', 'cat %s/devices/*/media/%s.json' % (STORE_ROOT, uid)).stdout) + + +def read_console(s): + """Target A's serial console: diagnostics only. Firmware writes bytes + that are not UTF-8, so it is decoded leniently.""" + r = subprocess.run(['kubectl', '--kubeconfig', str(s / 'cell-admin.yaml'), '--request-timeout=30s', '-n', rf.SITE, 'exec', 'deploy/fleet-site-runtime', '-c', 'libvirt', '--', + 'cat', '/var/lib/fleet-lab-console/target-a.log'], capture_output=True, timeout=180) + return [l.strip() for l in r.stdout.decode(errors='replace').splitlines()] if r.returncode == 0 else [] + + +def steps_of(s, uid): + return dict((n, st) for o in rf.journal(s) if o['operation'] == uid for n, st in o['steps']) + + +def offer(s): + config = json.loads((s / 'acceptance.json').read_text()) + config['DeliveryMethods'] = [{'method': 'NetworkBoot'}, + {'method': 'VirtualMedia', 'addresses': 'DataNetwork', 'mediaService': config['MediaService'], 'fetchWindow': FETCH, 'reportWindow': REPORT}] + (s / 'acceptance.json').write_text(json.dumps(config)) + provider(s, '-n', 'fleet-provider', 'annotate', '--overwrite', 'device', DEVICE_NAME, QUALIFIED + '=VirtualMedia') + subprocess.run(['bash', 'hack/multiplane/coordinator.sh', 'restart', str(s)], check=True, capture_output=True, text=True) + rf.write(s / 'evidence' / 'media-offer.json', {'observedAt': now(), 'deliveryMethods': config['DeliveryMethods'], + 'qualified': {'device': harness.DEVICE, 'methods': ['VirtualMedia'], 'source': 'lab-set annotation; commissioning is not implemented'}}) + print('media-offer: the cell declares NetworkBoot then VirtualMedia (central media service, %s fetch and %s report phases); target A is qualified for VirtualMedia only; coordinator restarted' % (FETCH, REPORT)) + + +def arm(s, *fault): + r = rf.bmc(s, 'python3', '/opt/fleet-lab/fleet_lab_adapter.py', 'fault', *fault) + (s / 'redfish' / ('media-fault-%s.json' % fault[0])).write_text(r.stdout) + + +def arm_corrupt_token(s): + arm(s, 'corrupt-config', SYSTEM) + print('media-arm-corrupt-token: target A\'s next config medium will carry another report token than the media service served') + + +def arm_add_download(s): + arm(s, 'add-download', SYSTEM) + print('media-arm-add-download: target A\'s next config medium will list a download the operation never pinned') + + +def arm_lost_eject(s): + arm(s, 'drop-eject', SYSTEM, 'CD1', '45') + print('media-arm-lost-eject: target A\'s next CD1 eject is applied and its response withheld for 45s, past the 30s client timeout') + + +def media_effects(entries, fault=None): + return [e for e in entries if '/VirtualMedia/' in e['path'] and e['method'] == 'POST' and (fault is None or e.get('fault') == fault)] + + +def summarize(entries): + out = [] + for e in entries: + item = {k: e[k] for k in ('at', 'method', 'path', 'status') if k in e} + item.update({k: e[k] for k in ('media', 'effect', 'bytes', 'urlSHA256', 'resetType', 'fault', 'boot') if k in e}) + out.append(item) + return out + + +def outcomes(s, uid): + path = s / 'media-central' / 'transfers' / key(uid) / 'reports.log' + return [w for w in (path.read_text().split() if path.exists() else []) if w.startswith('rejected') or w in ('accepted', 'duplicate', 'repeated')] + + +def held_report(s): + ops = media_installs(s) + if len(ops) != 1 or ops[0]['status'].get('phase') != 'OutcomeUnknown': + die('expected one held virtual media installation, got %s' % [(o['metadata']['name'], o['status'].get('phase')) for o in ops]) + op = ops[0] + uid = op['metadata']['uid'] + w = window_record(s, uid) + if w.get('report') or w.get('duplicates') or w.get('rejected', 0) < 4: + die('the media service took a report or refused fewer than four: %s' % {k: w.get(k) for k in ('report', 'duplicates', 'rejected')}) + stray = json.loads((s / 'media-stray-reports.json').read_text()) + if stray['answers'] != {'missing-token': 403, 'other-token': 403, 'other-address': 403} or 'rejected-source' not in outcomes(s, uid): + die('the stray reports were not all refused, or none was refused for its address: %s %s' % (stray['answers'], outcomes(s, uid))) + steps = steps_of(s, uid) + for step in ('media-window', 'media-insert-boot', 'media-insert-config', 'media-installer-power-on', 'media-installer-done', 'disk-power-on'): + if steps.get(step) != 'Done': + die('the held installation did not journal %s done: %s' % (step, steps)) + if 'media-report-verified' in steps or 'media-released' in steps: + die('the held installation verified a report or recorded release: %s' % steps) + if len(media_effects(rf.audit(s), 'corrupt-config-token')) != 1: + die('the corrupt-token fault did not fire exactly once') + # The proof is the media service's refusals above; the console is + # diagnostics only and is recorded, never required. + diagnostics = [l for l in read_console(s) if l.startswith('fleet: first-boot report')] + # The worker's media identity is its own Secret: the Device's BMC + # credential holds only BMC keys. + credential = json.loads(rf.kubectl(s, '-n', rf.CREDENTIALS, 'get', 'secret', rf.credential_name(harness.DEVICE), '-o', 'json').stdout) + if sorted(credential.get('data', {})) != ['password', 'tlsPublicKeySHA256', 'username']: + die('the BMC credential Secret holds more than BMC credentials: %s' % sorted(credential.get('data', {}))) + rf.write(s / 'media-held-report.json', {'operation': op['metadata']['name'], 'fence': op['status']['fence'], 'reason': op['status'].get('reason'), + 'mediaService': {'report': None, 'rejected': w['rejected'], 'outcomes': outcomes(s, uid)}, + 'strayReports': stray['answers'], 'steps': steps, 'consoleDiagnostics': diagnostics}) + print('media-held-report: %s booted from media; its OS posted a report with another token (refused); stray reports with no token, another token, and from an address that is not the Machine\'s were refused (%s); ' + 'the media service took no report (%d refused); OutcomeUnknown (%s) at the report deadline' + % (op['metadata']['name'], stray['answers'], w['rejected'], op['status'].get('reason'))) + + +def held_download(s): + ops = media_installs(s) + if [o['status'].get('phase') for o in ops] != ['OutcomeUnknown', 'OutcomeUnknown']: + die('expected two held virtual media installations, got %s' % [(o['metadata']['name'], o['status'].get('phase')) for o in ops]) + op = ops[1] + uid = op['metadata']['uid'] + steps = steps_of(s, uid) + if steps.get('media-installer-done') != 'Done' or 'media-report-verified' in steps or 'media-released' in steps: + die('the second installation verified its report or recorded release: %s' % steps) + if len(media_effects(rf.audit(s), 'add-config-download')) != 1: + die('the add-download fault did not fire exactly once') + w = window_record(s, uid) + named = [d['name'] for d in (w.get('report') or {}).get('downloads') or []] + if not w.get('report') or named != ['extension'] or op['spec']['image'].get('downloads'): + die('the report did not name the unpinned download, or the operation pinned one: %s' % w.get('report')) + rf.write(s / 'media-held-download.json', {'operation': op['metadata']['name'], 'fence': op['status']['fence'], 'reason': op['status'].get('reason'), + 'recordedDownloads': [], 'reportedDownloads': w['report']['downloads'], 'steps': steps}) + print('media-held-download: %s pinned no download; its first-boot report named %s, so it was never verified: OutcomeUnknown (%s)' + % (op['metadata']['name'], named, op['status'].get('reason'))) + + +def held_eject(s): + ops = media_installs(s) + if [o['status'].get('phase') for o in ops] != ['OutcomeUnknown'] * 3: + die('expected three held virtual media installations, got %s' % [(o['metadata']['name'], o['status'].get('phase')) for o in ops]) + op = ops[2] + uid = op['metadata']['uid'] + steps = steps_of(s, uid) + for step in ('media-window', 'media-insert-boot', 'media-insert-config', 'media-installer-done', 'media-report-verified', 'media-close'): + if steps.get(step) != 'Done': + die('the third installation did not journal %s done: %s' % (step, steps)) + if steps.get('media-eject-cd1') != 'Intended' or 'media-released' in steps: + die('the lost eject is not journaled intended-only, or release was recorded: %s' % steps) + # The BMC audits the eject only once it answers, after the 45 seconds it + # withholds the answer, so after the worker gave up on it. + for _ in range(60): + faulted = media_effects(rf.audit(s), 'drop-response-after-effect') + if faulted: + break + time.sleep(2) + if len(faulted) != 1 or faulted[0].get('media') != 'CD1': + die('the lost eject fault did not fire exactly once on CD1') + w, want = window_record(s, uid), site_window(s, uid) + if not w.get('report') or w['report']['image'] != want['image'] or w['report']['bootstrap'] != want['bootstrap'] or w.get('duplicates'): + die('the third installation\'s report was not taken with its own digests') + rf.write(s / 'media-held-eject.json', {'operation': op['metadata']['name'], 'fence': op['status']['fence'], 'reason': op['status'].get('reason'), + 'steps': steps, 'fault': summarize(faulted), 'report': w['report'], 'reportOutcomes': outcomes(s, uid)}) + print('media-held-eject: %s took its first-boot report (image %s..., bootstrap %s...), then lost the CD1 eject response: OutcomeUnknown (%s), media-released never journaled' + % (op['metadata']['name'], w['report']['image'][:19], w['report']['bootstrap'][:19], op['status'].get('reason'))) + + +def redfish_get(s, path): + """GET through the lab BMC's own Redfish API from inside its Pod, with + the mounted synthetic credential. Only the fields the proof needs leave + the Pod; never a media URL.""" + script = r''' +import base64, json, ssl, sys, urllib.request +user = open('/etc/fleet-bmc-credentials/username').read().strip() +password = open('/etc/fleet-bmc-credentials/password').read().strip() +context = ssl.create_default_context(); context.check_hostname = False; context.verify_mode = ssl.CERT_NONE +request = urllib.request.Request('https://127.0.0.1:8443' + sys.argv[1], headers={'Authorization': 'Basic ' + base64.b64encode((user + ':' + password).encode()).decode()}) +doc = json.load(urllib.request.urlopen(request, context=context, timeout=20)) +keep = {k: doc.get(k) for k in ('Id', 'Inserted', 'PowerState', 'Boot', 'Members') if k in doc} +if 'Image' in doc: + keep['ImageEmpty'] = doc['Image'] in (None, '') +if 'Boot' in keep: + keep['Boot'] = {k: v for k, v in keep['Boot'].items() if '@' not in k} +print(json.dumps(keep)) +''' + return json.loads(rf.bmc(s, 'python3', '-c', script, path).stdout) + + +def release_proof(s): + ops = media_installs(s) + if [o['status'].get('phase') for o in ops] != ['OutcomeUnknown'] * 3 + ['Succeeded']: + die('expected three held and then the settling virtual media installation, got %s' % [(o['metadata']['name'], o['status'].get('phase')) for o in ops]) + settling = ops[3] + custody = json.loads(provider(s, '-n', 'fleet-provider', 'get', 'devicecustody', DEVICE_NAME, '-o', 'json').stdout)['spec'] + if custody.get('recoveryHold') or custody.get('activeOperation'): + die('custody still holds a hold or an operation: %s' % {k: custody.get(k) for k in ('recoveryHold', 'activeOperation')}) + # Source one: the BMC, through Redfish. + base = '/redfish/v1/Systems/%s' % SYSTEM + system = redfish_get(s, base) + devices = [redfish_get(s, m['@odata.id']) for m in redfish_get(s, base + '/VirtualMedia')['Members']] + if len(devices) != 2 or any(d['Inserted'] or not d['ImageEmpty'] for d in devices): + die('the BMC still reports media: %s' % devices) + if system['Boot'].get('BootSourceOverrideEnabled') != 'Disabled': + die('the BMC reports a boot override: %s' % system['Boot']) + # Source two: the central media service, live. + code, status = central(s, 'GET', '/v1/devices/' + harness.DEVICE) + if code != 200 or status != {'windows': 4, 'openWindows': 0, 'openTransfers': 0, 'duplicates': 0}: + die('the media service reports %s %s for the Device' % (code, status)) + # The live media service denies every window, from the BMC's own Pod. + denials = [] + for op in ops: + w = window_record(s, op['metadata']['uid']) + url = 'https://%s:%d/media/%s/boot/%s/boot.iso' % (rf.MEDIA_HOST, rf.MEDIA_PORT, key(op['metadata']['uid']), w['bootDigest']) + probe = ("import ssl,sys,urllib.request,urllib.error\nc=ssl.create_default_context(cafile='/etc/fleet-bmc-media-ca/ca.crt')\n" + "try:\n urllib.request.urlopen(sys.argv[1],context=c,timeout=20); print(200)\nexcept urllib.error.HTTPError as e: print(e.code)\n") + answer = rf.bmc(s, 'python3', '-c', probe, url).stdout.strip() + if answer != '403' or not w.get('closed') or w['configMediumKept']: + die('the media service served or kept a window: HTTP %s, closed %s' % (answer, w.get('closed'))) + denials.append({'operation': op['metadata']['name'], 'status': int(answer)}) + # No site store record keeps a rendered config medium. + kept = rf.runtime(s, 'sh', '-c', 'ls %s/devices/*/mediacfg 2>/dev/null | grep -c json || true' % STORE_ROOT).stdout.strip() + if kept not in ('', '0'): + die('the site store still keeps %s config media' % kept) + steps = steps_of(s, settling['metadata']['uid']) + for step in ('media-window', 'media-insert-boot', 'media-insert-config', 'media-installer-done', 'media-report-verified', 'media-close', 'media-eject-cd1', 'media-eject-cd2', 'media-released'): + if steps.get(step) != 'Done': + die('the settling installation did not journal %s done: %s' % (step, steps)) + rf.write(s / 'media-release.json', {'observedAt': now(), 'settling': settling['metadata']['name'], 'fence': settling['status']['fence'], + 'bmc': {'system': system, 'devices': devices}, 'mediaService': {'device': status, 'liveDenials': denials}, + 'journal': steps, 'evidence': settling['status'].get('evidence')}) + print('media-release-proof: BMC reads back CD1 and CD2 empty and override Disabled; the central media service reports 4 windows, none open, no transfer in progress, no reused token, ' + 'and denies all four (HTTP 403); no config medium kept; custody holds no hold') + + +def stale_fence(s): + refused = [] + for op in media_installs(s): + w = window_record(s, op['metadata']['uid']) + body = {'device': harness.DEVICE, 'operation': op['metadata']['uid'], 'fence': op['status']['fence'], 'bootDigest': w['bootDigest'], + 'capabilitySHA256': '0' * 64, 'tokenSHA256': '0' * 64, 'configMedium': base64.b64encode(b'stale').decode(), + 'fetchExpires': later(10), 'reportExpires': later(20)} + # Without a client certificate, and with another site's, the open is + # refused before the service looks at custody; as the cell's worker, + # custody refuses it. + answers = {client: central(s, 'PUT', '/v1/windows/' + key(op['metadata']['uid']), body, identity)[0] + for client, identity in (('unauthenticated', None), ('anotherSite', 'media-worker-other'), ('cellWorker', 'media-worker'))} + if answers != {'unauthenticated': 401, 'anotherSite': 403, 'cellWorker': 409}: + die('the media service answered %s to window opens it must refuse' % answers) + refused.append({'operation': op['metadata']['name'], 'fence': op['status']['fence'], 'answers': answers}) + r = rf.runtime(s, 'fleet-multiplane', 'media-stale', '--device', harness.DEVICE, check=False) + if r.returncode != 0 or not r.stdout.startswith('PASS'): + die('the site store stale fence probe failed: %s %s' % (r.stdout.strip()[-300:], r.stderr.strip()[-300:])) + rf.write(s / 'media-stale.json', {'mediaService': refused, 'siteStore': r.stdout.strip()}) + print('media-stale-fence: for all %d ended operations the media service refused a window open without a client certificate (401), as another site (403), and as the cell\'s worker at the old fence (409); site store: %s' + % (len(refused), r.stdout.strip())) + + +def evidence(s): + ops = media_installs(s) + entries = rf.audit(s) + console = read_console(s) + reports = [] + for op in ops: + uid = op['metadata']['uid'] + w, want = window_record(s, uid), site_window(s, uid) + path = s / 'media-central' / 'transfers' / key(uid) / 'media-transfer.log' + transfers = path.read_text().splitlines() if path.exists() else [] + reports.append({'operation': op['metadata']['name'], 'fence': op['status']['fence'], 'phase': op['status']['phase'], 'reason': op['status'].get('reason'), + 'reportTokenSHA256': w['tokenSHA256'], 'expected': {'image': want['image'], 'bootstrap': want['bootstrap']}, 'report': w.get('report'), + 'reportOutcomes': outcomes(s, uid), 'transfers': [' '.join(t.split()[1:2] + t.split()[3:]) for t in transfers]}) + if [r['report'] is not None for r in reports] != [False, True, True, True]: + die('expected no report for the corrupted install and one for each of the others') + if any(r['report'] and (r['report']['image'] != r['expected']['image'] or r['report']['bootstrap'] != r['expected']['bootstrap']) for r in reports) or \ + [bool((r['report'] or {}).get('downloads')) for r in reports] != [False, True, False, False]: + die('a taken report does not carry its operation\'s digests') + if any(l.startswith('FLEET-REPORT') or 'token=' in l for l in console): + die('the console carries a report or a token') + qemu = rf.runtime(s, 'cat', '/var/log/libvirt/qemu/fleet-lab-target-a.log').stdout + blocks = re.split(r'^\S+ \S+: starting up ', qemu, flags=re.M)[1:] + + def first(block): + # The device QEMU boots first: the one with boot index 1. + segment = next((seg for seg in re.split(r'\s-device\s', block) if '"bootindex":1' in seg or 'bootindex=1' in seg), '') + return 'cdrom' if 'ide-cd' in segment else 'disk' if 'virtio-blk' in segment else 'network' if segment else 'unknown' + starts = [first(b) for b in blocks] + mutations = summarize([e for e in entries if e['method'] != 'GET' and '/Systems/%s' % SYSTEM in e['path']]) + record = {'observedAt': now(), 'device': harness.DEVICE, 'operations': reports, 'qemuStarts': starts, 'bmcEffects': mutations, + 'firstBootConsole': [l for l in console if l.startswith('fleet:')], + 'offer': json.loads((s / 'evidence' / 'media-offer.json').read_text()), 'heldReport': json.loads((s / 'media-held-report.json').read_text()), + 'heldDownload': json.loads((s / 'media-held-download.json').read_text()), 'heldEject': json.loads((s / 'media-held-eject.json').read_text()), 'release': json.loads((s / 'media-release.json').read_text()), + 'staleFence': json.loads((s / 'media-stale.json').read_text())} + # Target B, served by the same BMC, was never touched. + base = json.loads((s / 'redfish-baseline.json').read_text()) + b = rf.TARGET_B + record['targetB'] = {'diskSHA256Unchanged': rf.disk_sha(s, b['disk']) == base['targetB']['diskSHA256'], 'qemuStarts': rf.qemu_starts(s, b['domain']), + 'mutatingRedfishRequests': len(rf.mutating(entries, b['system']))} + if not record['targetB']['diskSHA256Unchanged'] or record['targetB']['qemuStarts'] or record['targetB']['mutatingRedfishRequests']: + die('target B was touched: %s' % record['targetB']) + if starts != ['cdrom', 'disk'] * 4: + die('expected target A to boot from media then disk, four times; got %s' % starts) + rf.write(s / 'evidence' / 'virtual-media.json', record) + # Every check above passed. Only result.json, which run.sh writes last, + # records whether the run passed. + rf.write(s / 'evidence' / 'summary.json', { + 'schemaVersion': 3, 'acceptance': 'evidence-verified', 'suite': 'virtual-media', 'observedAt': now(), 'prefix': (s / 'prefix').read_text().strip(), + 'qualification': {'nativeMiloProjectAPIs': True, 'actualKarmadaDeliveryAndReflection': True, 'kubernetesJobExecution': True, 'actualKroController': True, + 'fluxReconciledServices': True, 'redfishVirtualMedia': 'DMTF Redfish Interface Emulator 1.2.2 + lab-only adapter', + 'centralMediaService': 'workstation process on loopback', 'firstBootReport': True, + 'physicalHardware': False, 'physicalBMC': False, 'vendorRedfishQualified': False, 'uefi': False, 'productionAuthority': False}, + 'scenarios': {'virtualMedia': 'virtual-media.json', 'installs': [{k: r[k] for k in ('operation', 'fence', 'phase', 'reason')} for r in reports]}}) + for name in ('source-SHA256SUMS',): + if (s / name).exists(): + (s / 'evidence' / name).write_text((s / name).read_text()) + paths = [s / 'site-bin' / 'fleet-multiplane', s / 'fleet-multiplane-host'] + (s / 'evidence' / 'binary-SHA256SUMS').write_text(''.join(hashlib.sha256(p.read_bytes()).hexdigest() + ' ' + p.name + '\n' for p in paths)) + print('media-evidence: %d virtual media installs; reports taken %s; target A booted %s; console carries no token; %d BMC effects recorded' + % (len(reports), [r['report'] is not None for r in reports], ', '.join(starts), len(mutations))) + + +if __name__ == '__main__': + step, state = sys.argv[1], pathlib.Path(sys.argv[2]) + {'offer': offer, 'arm-corrupt-token': arm_corrupt_token, 'held-report': held_report, 'arm-add-download': arm_add_download, 'held-download': held_download, + 'arm-lost-eject': arm_lost_eject, 'held-eject': held_eject, + 'release-proof': release_proof, 'stale-fence': stale_fence, 'evidence': evidence}[step](state) diff --git a/hack/multiplane/redfish_steps.py b/hack/multiplane/redfish_steps.py index 6dfc472d..131e6cf1 100644 --- a/hack/multiplane/redfish_steps.py +++ b/hack/multiplane/redfish_steps.py @@ -23,6 +23,7 @@ dhcp-synced synced DHCP: boot addresses, reservations, Kea leases and IPAM's allocations agree, and nothing remains held """ +import base64 import datetime import hashlib import json @@ -45,7 +46,13 @@ SECRET = 'fleet-site-bmc-credentials' TLS_SECRET = 'fleet-site-bmc-tls' CREDENTIALS = 'fleet-site-credentials' +IDENTITY, IDENTITY_SECRET = 'fleet-site-worker-identity', 'fleet-site-worker-media' BMC_IP = '10.96.0.81' +BOOT_IP = '10.96.0.80' +# The workstation as lab Pods and guests reach it (the Colima host gateway), +# where the central media service listens on loopback. +MEDIA_HOST = '192.168.5.2' +MEDIA_PORT = 28443 def now(): @@ -175,6 +182,31 @@ def enroll(s): subprocess.run(['openssl', 'req', '-x509', '-newkey', 'ec', '-pkeyopt', 'ec_paramgen_curve:prime256v1', '-nodes', '-keyout', str(d / 'bmc-tls.key'), '-out', str(d / 'bmc-tls.crt'), '-days', '2', '-subj', '/CN=fleet-lab-bmc', '-addext', 'subjectAltName=IP:%s' % BMC_IP], check=True, capture_output=True) + # The central media service's TLS key, also per run. It runs on the + # workstation, which lab Pods and guests reach at the runtime's host + # gateway. The lab BMC, the workers and the installed OS verify it + # against this certificate. + subprocess.run(['openssl', 'req', '-x509', '-newkey', 'ec', '-pkeyopt', 'ec_paramgen_curve:prime256v1', '-nodes', '-keyout', str(d / 'media-tls.key'), + '-out', str(d / 'media-tls.crt'), '-days', '2', '-subj', '/CN=fleet-lab-media', '-addext', 'subjectAltName=IP:%s,IP:127.0.0.1,IP:::1' % MEDIA_HOST], + check=True, capture_output=True) + # Site workers authenticate to the central media service with client + # certificates from a CA generated per run: the cell's workers, and one + # other identity the service must refuse. + cell = (s / 'prefix').read_text().strip() + '-cell' + subprocess.run(['openssl', 'req', '-x509', '-newkey', 'ec', '-pkeyopt', 'ec_paramgen_curve:prime256v1', '-nodes', '-keyout', str(d / 'media-worker-ca.key'), + '-out', str(d / 'media-worker-ca.crt'), '-days', '2', '-subj', '/CN=fleet-lab-media-workers', '-addext', 'basicConstraints=critical,CA:TRUE', + '-addext', 'keyUsage=critical,keyCertSign'], check=True, capture_output=True) + for name, identity in (('media-worker', 'fleet-site-worker:' + cell), ('media-worker-other', 'fleet-site-worker:another-cell')): + subprocess.run(['openssl', 'req', '-new', '-newkey', 'ec', '-pkeyopt', 'ec_paramgen_curve:prime256v1', '-nodes', '-keyout', str(d / (name + '.key')), + '-out', str(d / (name + '.csr')), '-subj', '/CN=' + identity], check=True, capture_output=True) + ext = d / (name + '.ext') + ext.write_text('extendedKeyUsage=clientAuth\nkeyUsage=critical,digitalSignature\n') + subprocess.run(['openssl', 'x509', '-req', '-in', str(d / (name + '.csr')), '-CA', str(d / 'media-worker-ca.crt'), '-CAkey', str(d / 'media-worker-ca.key'), + '-CAcreateserial', '-days', '2', '-extfile', str(ext), '-out', str(d / (name + '.crt'))], check=True, capture_output=True) + env_path = s / 'gitops-environment.json' + env = json.loads(env_path.read_text()) + env['mediaCA'] = base64.b64encode((d / 'media-tls.crt').read_bytes()).decode() + env_path.write_text(json.dumps(env, indent=2) + '\n') spki = subprocess.run(['openssl', 'x509', '-in', str(d / 'bmc-tls.crt'), '-pubkey', '-noout'], check=True, capture_output=True).stdout der = subprocess.run(['openssl', 'pkey', '-pubin', '-outform', 'der'], input=spki, check=True, capture_output=True).stdout pin = hashlib.sha256(der).hexdigest() @@ -183,8 +215,16 @@ def enroll(s): p.chmod(0o600) kubectl(s, '-n', SITE, 'create', 'secret', 'generic', SECRET, '--from-file=username=%s' % (d / 'bmc-username'), '--from-file=password=%s' % (d / 'bmc-password.token')) kubectl(s, '-n', SITE, 'create', 'secret', 'tls', TLS_SECRET, '--cert=%s' % (d / 'bmc-tls.crt'), '--key=%s' % (d / 'bmc-tls.key')) + kubectl(s, '-n', SITE, 'create', 'secret', 'generic', 'fleet-site-media-ca', '--from-file=ca.crt=%s' % (d / 'media-tls.crt')) if synced(s): enroll_dhcp(s, d) + # The site worker's own media service identity, one Secret per site + # worker identity, apart from every BMC credential; and another site's, + # which no worker here may read. + if kubectl(s, 'get', 'namespace', IDENTITY, check=False).returncode != 0: + kubectl(s, 'create', 'namespace', IDENTITY) + for name, files in ((IDENTITY_SECRET, 'media-worker'), (IDENTITY_SECRET + '-another-cell', 'media-worker-other')): + kubectl(s, '-n', IDENTITY, 'create', 'secret', 'tls', name, '--cert=%s' % (d / (files + '.crt')), '--key=%s' % (d / (files + '.key'))) # One credential Secret per Device, by the BMC discovery contract. if kubectl(s, 'get', 'namespace', CREDENTIALS, check=False).returncode != 0: kubectl(s, 'create', 'namespace', CREDENTIALS) diff --git a/hack/multiplane/run.sh b/hack/multiplane/run.sh index fc41e476..c36672e9 100755 --- a/hack/multiplane/run.sh +++ b/hack/multiplane/run.sh @@ -9,8 +9,8 @@ set -euo pipefail cd "$(dirname "$0")/../.." umask 077 -usage() { echo 'usage: hack/multiplane/run.sh [--redfish [--synced-dhcp]] [--preflight-only] [--bootstrap] [--keep] [--leave-running] [--skip-readiness-tests]' >&2; exit 64; } -preflight_only=0 bootstrap=() keep=0 leave=0 skip_tests=() provider=libvirt lab_dhcp=static +usage() { echo 'usage: hack/multiplane/run.sh [--redfish [--synced-dhcp | --virtual-media]] [--preflight-only] [--bootstrap] [--keep] [--leave-running] [--skip-readiness-tests]' >&2; exit 64; } +preflight_only=0 bootstrap=() keep=0 leave=0 skip_tests=() provider=libvirt lab_dhcp=static media=0 for arg in "$@"; do case "$arg" in --preflight-only) preflight_only=1 ;; @@ -26,10 +26,14 @@ for arg in "$@"; do # (milo-os/ipam) aggregated by the provider Milo API # (docs/operations/redfish-lab.md). --synced-dhcp) lab_dhcp=synced ;; + # Virtual media: the Redfish lab's suite that installs over Redfish + # VirtualMedia and the site's media service (docs/operations/redfish-lab.md). + --virtual-media) media=1 ;; *) usage ;; esac done [[ $lab_dhcp == static || $provider == redfish ]] || usage +[[ $media == 0 || ($provider == redfish && $lab_dhcp == static) ]] || usage # Run parameters (docs/operations/multiplane.md#ci-mode). The defaults are the # task-owned Colima profile: arm64 runtime, TCG guest. Preflight validates them # before any resource exists. @@ -142,7 +146,12 @@ python3 - "$state" "$provider" "$lab_dhcp" <<'PY' import json,pathlib,sys s=pathlib.Path(sys.argv[1]).resolve() enrollment=json.loads((s/'redfish'/'fixture-enrollment.json').read_text() if sys.argv[2]=='redfish' else pathlib.Path('config/site/base/enrollment.json').read_text()) -c={'State':str(s),'HubKubeconfig':str(s/'management-hub.json'),'Cell':(s/'prefix').read_text().strip()+'-cell','Image':(s/'image').read_text().strip(),'Enrollment':enrollment} +c={'State':str(s),'HubKubeconfig':str(s/'management-hub.json'),'Cell':(s/'prefix').read_text().strip()+'-cell','Image':(s/'image').read_text().strip(),'Enrollment':enrollment, + # The cell's declared boot delivery methods: network boot only. The + # virtual media suite adds virtual media as an operator would. + 'DeliveryMethods':[{'method':'NetworkBoot'}], + # The central media service, as lab Pods and guests reach the workstation. + 'MediaService':'https://192.168.5.2:28443'} if sys.argv[3]=='synced':c['BootAddressClass']='lab-provisioning' (s/'acceptance.json').write_text(json.dumps(c)) PY @@ -153,7 +162,9 @@ ph coordinator 120 bash hack/multiplane/coordinator.sh start "$state" ph flux-site 1200 "${flux[@]}" publish "$state" --revision 2 --site off --purpose 'shared site services and dispatcher, dispatch disabled' --cluster cell --cluster hub --cluster platform --timeout 900 ph site-install 900 bash hack/multiplane/site.sh check "$state" ph flux-verify 300 "${flux[@]}" verify "$state" -if [[ $provider == redfish ]]; then +if [[ $media == 1 ]]; then + bash hack/multiplane/acceptance-media.sh "$state" & wait $! +elif [[ $provider == redfish ]]; then bash hack/multiplane/acceptance-redfish.sh "$state" & wait $! else bash hack/multiplane/acceptance.sh "$state" & wait $! diff --git a/hack/multiplane/stop.sh b/hack/multiplane/stop.sh index 1d9b1934..5b2a90bf 100755 --- a/hack/multiplane/stop.sh +++ b/hack/multiplane/stop.sh @@ -6,6 +6,7 @@ prefix=$(cat "$state/prefix") [[ $prefix =~ ^fleet-mp-[a-f0-9]{8}$ ]] || exit 1 # The coordinator is a workstation process: stop it before its clusters. bash hack/multiplane/coordinator.sh stop "$state" >/dev/null +bash hack/multiplane/media-central.sh stop "$state" >/dev/null export DOCKER_CONTEXT=${FLEET_MULTIPLANE_DOCKER_CONTEXT:-colima-fleet-acceptance-tcg} # The cell node holds the site runtime, journal volume, kro and worker Jobs; the # platform node holds the Milo APIs and their etcd volumes; the registry holds diff --git a/hack/multiplane/teardown.sh b/hack/multiplane/teardown.sh index d2aa5ceb..e40a3476 100755 --- a/hack/multiplane/teardown.sh +++ b/hack/multiplane/teardown.sh @@ -15,6 +15,7 @@ prefix=$(cat "$state/prefix") [[ $prefix =~ ^fleet-mp-[a-f0-9]{8}$ ]] || { echo 'unexpected prefix' >&2; exit 1; } # The coordinator is a workstation process: stop it before its clusters. bash hack/multiplane/coordinator.sh stop "$state" >/dev/null +bash hack/multiplane/media-central.sh stop "$state" >/dev/null export DOCKER_CONTEXT=${FLEET_MULTIPLANE_DOCKER_CONTEXT:-colima-fleet-acceptance-tcg} KIND_EXPERIMENTAL_PROVIDER=docker if [[ $mode == passed ]]; then python3 -c 'import json,sys; sys.exit(json.load(open(sys.argv[1])).get("acceptance")!="evidence-verified")' "$state/evidence/summary.json" 2>/dev/null || { diff --git a/hack/multiplane/verify-rbac.py b/hack/multiplane/verify-rbac.py index 6998a8b8..149dc175 100755 --- a/hack/multiplane/verify-rbac.py +++ b/hack/multiplane/verify-rbac.py @@ -56,16 +56,19 @@ def can(*args): return r.stdout.strip()=='yes' allowed=[('create','jobs','-n',site),('create','serviceaccounts','-n',site),('create','roles','-n',ns),('create','rolebindings','-n',ns), ('list','deployments','-A'),('list','services','-A'),('watch',h,'-A'),('get','persistentvolumeclaims','-n',site)] -redfish=os.environ.get('FLEET_SITE_PROVIDER')=='redfish';creds_ns='fleet-site-credentials' +redfish=os.environ.get('FLEET_SITE_PROVIDER')=='redfish';creds_ns='fleet-site-credentials';ident_ns='fleet-site-worker-identity' if redfish: # Redfish mode: kro creates each worker's Role to get its one BMC credential # Secret, so it holds get there and nothing more; it cannot list or watch. - allowed+=[('create','roles','-n',creds_ns),('create','rolebindings','-n',creds_ns),('get','secrets','-n',creds_ns)] + allowed+=[('create','roles','-n',creds_ns),('create','rolebindings','-n',creds_ns),('get','secrets','-n',creds_ns), + # and each worker's Role to get the site worker identity Secret. + ('create','roles','-n',ident_ns),('create','rolebindings','-n',ident_ns),('get','secrets','-n',ident_ns)] denied=[('create','deployments','-n',site),('patch','deployments','-n',site),('create','services','-n',site),('delete','services','-n',site), ('delete','persistentvolumeclaims','-n',site),('patch','configmaps','-n',site),('create','jobs','-n','default'),('create','jobs','-n','kube-system'), ('create','roles','-n',site),('create','rolebindings','-n','kube-system'),('create','clusterroles'),('get','secrets','-n',site), ('patch',h,'-n',ns),('update',h,'--subresource=status','-n',ns),('delete','validatingadmissionpolicies')]+( - [('list','secrets','-n',creds_ns),('create','secrets','-n',creds_ns),('watch','secrets','-n',creds_ns)] if redfish else []) + [('list','secrets','-n',creds_ns),('create','secrets','-n',creds_ns),('watch','secrets','-n',creds_ns), + ('list','secrets','-n',ident_ns),('create','secrets','-n',ident_ns),('watch','secrets','-n',ident_ns)] if redfish else []) bad=[' '.join(a) for a in allowed if not can(*a)]+['denied '+' '.join(a) for a in denied if can(*a)] if bad:raise SystemExit('kro RBAC is not the narrowed grant: '+'; '.join(bad)) # Grants the kro chart keeps because kro needs them: it creates the CRD for each @@ -98,7 +101,8 @@ def job(**change): # its Device's credential Secret, by name, through a per-operation Role. named=[{'apiGroups':[''],'resources':['secrets'],'resourceNames':['bmc-'+'0'*20],'verbs':['get']}] listing=[{'apiGroups':[''],'resources':['secrets'],'verbs':['list']}] - cases['admitted'].update({'Redfish worker Job':job(),'worker credential Role':role(named,creds_ns)}) + identity=[{'apiGroups':[''],'resources':['secrets'],'resourceNames':['fleet-site-worker-media'],'verbs':['get']}] + cases['admitted'].update({'Redfish worker Job':job(),'worker credential Role':role(named,creds_ns),'worker identity Role':role(identity,ident_ns)}) cases['denied'].update({'Redfish worker mounting the libvirt socket':job(volumeMounts=[{'name':'state','mountPath':'/run/fleet-libvirt','subPath':'libvirt-socket'}]), 'Redfish worker mounting the lab disks':job(volumeMounts=[{'name':'state','mountPath':'/var/lib/fleet-lab/disks','subPath':'lab-disks'}]), 'Redfish worker with a libvirt URI':job(env=[{'name':'FLEET_SITE_PROVIDER','value':'redfish'},{'name':'FLEET_LIBVIRT_URI','value':'qemu:///system?socket=/run/fleet-libvirt/libvirt-sock'}]), @@ -110,7 +114,11 @@ def job(**change): 'credential Role getting every Secret':role([dict(named[0],resourceNames=[])],creds_ns), 'credential Role getting two Secrets':role([dict(named[0],resourceNames=['bmc-'+'0'*20,'bmc-'+'1'*20])],creds_ns), 'credential Role naming a Secret outside the rule':role([dict(named[0],resourceNames=['fleet-site-bmc-credentials'])],creds_ns), - 'credential RoleBinding to another Role':binding('w-op-admission-probe','w-op-admission-probe','fleet-site-kro-worker-credentials',creds_ns)}) + 'credential RoleBinding to another Role':binding('w-op-admission-probe','w-op-admission-probe','fleet-site-kro-worker-credentials',creds_ns), + 'identity Role naming another site\'s Secret':role([dict(identity[0],resourceNames=['fleet-site-worker-media-another-cell'])],ident_ns), + 'identity Role getting two Secrets':role([dict(identity[0],resourceNames=['fleet-site-worker-media','fleet-site-worker-media-another-cell'])],ident_ns), + 'identity Role getting a BMC credential name':role([dict(identity[0],resourceNames=['bmc-'+'0'*20])],ident_ns), + 'identity Role listing Secrets':role(listing,ident_ns)}) record={'identity':kro,'allowed':[' '.join(a) for a in allowed],'denied':[' '.join(a) for a in denied],'chartGrantsRetained':retained,'admission':{}} for outcome,objs in cases.items(): for name,obj in objs.items(): @@ -123,7 +131,7 @@ def job(**change): # A credential Role that lists Secrets is outside kro's own grant: kro holds # only get there, so RBAC escalation refuses it before admission. Every other # shape is within kro's grant and must be refused by the policies. -outside_grant={'credential Role listing Secrets'} +outside_grant={'credential Role listing Secrets','identity Role listing Secrets'} wrong=[n for n,v in record['admission'].items() if not v['admitted'] and v['deniedBy']!=('RBAC' if n in outside_grant else 'ValidatingAdmissionPolicy')] if wrong: raise SystemExit('a shape was refused by the wrong layer (%s): %s'%(', '.join(wrong),record['admission'])) diff --git a/internal/multiplane/media.go b/internal/multiplane/media.go new file mode 100644 index 00000000..65d8c41e --- /dev/null +++ b/internal/multiplane/media.go @@ -0,0 +1,393 @@ +package multiplane + +import ( + "context" + "crypto/tls" + "crypto/x509" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/netip" + "os" + "path/filepath" + "strings" + "time" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + meta "k8s.io/apimachinery/pkg/api/meta" + 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" + "go.datum.net/fleet/internal/custody" + "go.datum.net/fleet/internal/redfish" + "go.datum.net/fleet/internal/site/redfishwork" +) + +// The virtual media scenarios (run.sh --redfish --virtual-media). Each +// phase checks one outcome through the provider project API and never +// writes custody. + +// MediaNotOffered creates, while the cell declares only network boot, a +// virtual media installation for consumer A's allocation, as a Metal +// provider that skipped selection would. Admission refuses it before +// anything is delivered, with custody's fence unchanged. +func (r *Runner) MediaNotOffered(ctx context.Context) error { + for _, offer := range r.Config.DeliveryMethods { + if offer.Method == ops.DeliveryVirtualMedia { + return fmt.Errorf("%w: the cell already offers virtual media", errTerminal) + } + } + delivery := custody.OfferedMethod{Method: ops.DeliveryVirtualMedia, Addresses: ops.AddressesDataNetwork, MediaService: r.Config.MediaService}.Input() + return r.refusedInstallation(ctx, "00000000-0000-4000-8000-000000000227", delivery, nil, custody.ReasonDeliveryNotOffered) +} + +// MediaUnpinned creates, once the cell offers virtual media, a virtual +// media installation whose installer would download an image by tag, as an +// image like Talos's would without a digest. Admission refuses it before +// anything is delivered. +func (r *Runner) MediaUnpinned(ctx context.Context) error { + index := -1 + for i, offer := range r.Config.DeliveryMethods { + if offer.Method == ops.DeliveryVirtualMedia { + index = i + } + } + if index < 0 { + return fmt.Errorf("%w: the cell does not offer virtual media", errTerminal) + } + downloads := []ops.DownloadInput{{Name: "installer", Reference: "registry.example/installer:v1.0.0"}} + return r.refusedInstallation(ctx, "00000000-0000-4000-8000-000000000228", r.Config.DeliveryMethods[index].Input(), downloads, custody.ReasonDownloadUnpinned) +} + +// refusedInstallation creates an installation for consumer A's allocation +// with a synthetic request UID, outside the Metal provider's selection, and +// requires admission to refuse it for the reason with custody unchanged. +func (r *Runner) refusedInstallation(ctx context.Context, request string, delivery ops.DeliveryInput, downloads []ops.DownloadInput, reason string) error { + q, err := r.request(ctx, 0) + if err != nil { + return err + } + current, err := r.Allocator.Get(ctx, q.alloc.Machine) + if err != nil { + return err + } + if current == nil || current.Status.Phase != fleet.AllocationActive { + return errNoActiveAllocation + } + before := &ops.DeviceCustody{} + if err := r.Provider.API.Get(ctx, client.ObjectKey{Namespace: DeviceNamespace, Name: Device}, before); err != nil { + return err + } + device := &inventory.Device{} + 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) + if err != nil { + return err + } + image.Downloads = downloads + // A synthetic request UID keeps its name apart from every Installation. + operation := &ops.DeviceInstallation{} + key := client.ObjectKey{Namespace: DeviceNamespace, Name: custody.InstallationName(current.Name, request)} + if err := r.Provider.API.Get(ctx, key, operation); apierrors.IsNotFound(err) { + operation = &ops.DeviceInstallation{ + ObjectMeta: metav1.ObjectMeta{Name: key.Name, Namespace: key.Namespace}, + Spec: ops.DeviceInstallationSpec{ + OperationEnvelope: ops.OperationEnvelope{Creator: r.Allocator.ProviderCreator, DeviceRef: ops.DeviceReference{Name: device.Name, UID: string(device.UID)}, + Authority: ops.Authority{AllocationRef: &ops.LocalReference{Name: current.Name}}}, + RequestUID: request, Image: image, BootInterface: "primary", TargetDisks: []string{"disk-0"}, + Delivery: delivery, + }, + } + if err := r.Provider.API.Create(ctx, operation); err != nil { + return err + } + } else if err != nil { + return err + } + switch phase := operation.Status.Phase; { + case phase == ops.PhaseFailed && operation.Status.Reason == reason: + case phase.Ended() || phase.Running(): + return fmt.Errorf("%w: the virtual media installation is %s: %s", errTerminal, phase, operation.Status.Reason) + default: + return fmt.Errorf("%w: the virtual media installation is %q", errPending, phase) + } + after := &ops.DeviceCustody{} + if err := r.Provider.API.Get(ctx, client.ObjectKey{Namespace: DeviceNamespace, Name: Device}, after); err != nil { + return err + } + if after.Spec.Fence != before.Spec.Fence || after.Spec.ActiveOperation != nil || operation.Status.Fence != 0 || operation.Status.AdmittedAt != nil { + return fmt.Errorf("%w: the refused installation changed custody", errTerminal) + } + fmt.Printf("%s refused for %s before admission; fence %d unchanged, nothing delivered\n", operation.Name, operation.Status.Reason, after.Spec.Fence) + return nil +} + +// mediaInstallation creates one of consumer A's Installations, as the +// customer, and its DeviceInstallation through the Metal provider, which +// selects the delivery method. It requires the selection to be virtual +// media. +func (r *Runner) mediaInstallation(ctx context.Context, name string) (*request, *fleet.Installation, *ops.DeviceInstallation, error) { + customer, err := API(filepath.Join(r.Config.State, "consumer-a", "customer-project.json")) + 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}}} + if err := ensure(ctx, customer, install); err != nil { + return nil, nil, nil, err + } + q, _, install, operation, err := r.installationNamed(ctx, 0, name) + if err != nil { + return nil, nil, nil, err + } + if operation.Spec.Delivery.Method != ops.DeliveryVirtualMedia || operation.Spec.BootNetwork != nil { + return nil, nil, nil, fmt.Errorf("%w: the Metal provider selected %+v", errTerminal, operation.Spec.Delivery) + } + return q, install, operation, nil +} + +// MediaInstallHeld installs consumer A's first virtual media Installation +// while the lab BMC corrupts the report token on the config medium it +// holds. While the report window is open, it also posts, as a stray client +// would, a report with no token and one with another token. No report is +// taken, so the installation ends OutcomeUnknown at its report deadline, +// never Succeeded or Failed, with a hold that records virtual media. +func (r *Runner) MediaInstallHeld(ctx context.Context) error { + return r.mediaHeld(ctx, "debian-media-1", true) +} + +// MediaInstallDownload installs consumer A's second virtual media +// Installation, which settles the first hold, while the lab BMC adds a +// download the operation never pinned to the config medium. The report +// names it, so the installation ends OutcomeUnknown with a new hold. +func (r *Runner) MediaInstallDownload(ctx context.Context) error { + return r.mediaHeld(ctx, "debian-media-2", false) +} + +// MediaInstallLost installs consumer A's third virtual media Installation, +// which settles the second hold, while the lab BMC withholds an eject +// response. It ends OutcomeUnknown with a new hold. +func (r *Runner) MediaInstallLost(ctx context.Context) error { + return r.mediaHeld(ctx, "debian-media-3", false) +} + +func (r *Runner) mediaHeld(ctx context.Context, name string, probe bool) error { + _, _, operation, err := r.mediaInstallation(ctx, name) + if err != nil { + return err + } + if probe && operation.Status.Phase.Running() { + if err := r.strayReports(ctx, operation); err != nil { + return fmt.Errorf("%w: %v", errPending, err) + } + } + switch phase := operation.Status.Phase; { + case phase == ops.PhaseOutcomeUnknown: + case phase.Ended(): + return fmt.Errorf("%w: the installation ended %s: %s", errTerminal, phase, operation.Status.Reason) + default: + return fmt.Errorf("%w: the installation is %q", errPending, phase) + } + state := &ops.DeviceCustody{} + if err := r.Provider.API.Get(ctx, client.ObjectKey{Namespace: DeviceNamespace, Name: Device}, state); err != nil { + return err + } + method, held := custody.HeldMethod(state, "DeviceInstallation") + if !held || state.Spec.RecoveryHold.UID != string(operation.UID) || method != ops.DeliveryVirtualMedia { + return fmt.Errorf("%w: the hold does not record the virtual media installation: %+v", errTerminal, state.Spec.RecoveryHold) + } + if probe { + if _, err := os.Stat(filepath.Join(r.Config.State, "media-stray-reports.json")); err != nil { + return fmt.Errorf("%w: the stray reports were never posted while the report window was open", errTerminal) + } + } + fmt.Printf("%s ended OutcomeUnknown (%s); the recovery hold at fence %d records %s\n", operation.Name, operation.Status.Reason, state.Spec.RecoveryHold.Fence, method) + return nil +} + +// strayReports posts, once, a report with no token and one with another +// token to the operation's report URL while its report window is open, and +// records the answers. Each must be refused. +func (r *Runner) strayReports(ctx context.Context, operation *ops.DeviceInstallation) error { + record := filepath.Join(r.Config.State, "media-stray-reports.json") + if _, err := os.Stat(record); err == nil { + return nil + } + ca, err := os.ReadFile(filepath.Join(r.Config.State, "redfish", "media-tls.crt")) + if err != nil { + return err + } + pool := x509.NewCertPool() + if !pool.AppendCertsFromPEM(ca) { + return errors.New("the media service certificate is unreadable") + } + // The workstation reaches the central service on loopback. Reading a + // window's status is the worker API, so it presents the cell's worker + // certificate; the reports themselves carry none, as an installed OS's. + identity, err := tls.LoadX509KeyPair(filepath.Join(r.Config.State, "redfish", "media-worker.crt"), filepath.Join(r.Config.State, "redfish", "media-worker.key")) + if err != nil { + return err + } + origin := "https://127.0.0.1:28443" + worker := &http.Client{Timeout: 20 * time.Second, Transport: &http.Transport{TLSClientConfig: &tls.Config{RootCAs: pool, Certificates: []tls.Certificate{identity}}}} + client := &http.Client{Timeout: 20 * time.Second, Transport: &http.Transport{TLSClientConfig: &tls.Config{RootCAs: pool}}} + key := redfishwork.Key(string(operation.UID)) + status, err := worker.Get(origin + "/v1/windows/" + key) + if err != nil { + return err + } + var window redfishwork.WindowStatus + err = json.NewDecoder(status.Body).Decode(&window) + status.Body.Close() + if err != nil || status.StatusCode != http.StatusOK || !window.ReportOpen || window.Report != nil { + return errors.New("the report window is not open yet") + } + answers := map[string]int{} + // The installed servers' reports reach the service on IPv4 loopback; a + // report over IPv6 loopback comes from another address. + posts := map[string]struct{ origin, body string }{ + "missing-token": {origin, `{"image":"sha256:` + strings.Repeat("0", 64) + `"}`}, + "other-token": {origin, `{"token":"` + strings.Repeat("e", 64) + `"}`}, + "other-address": {"https://[::1]:28443", `{"token":"` + strings.Repeat("e", 64) + `"}`}, + } + for label, post := range posts { + response, err := client.Post(redfishwork.ReportURL(post.origin, key), "application/json", strings.NewReader(post.body)) + if err != nil { + return err + } + response.Body.Close() + answers[label] = response.StatusCode + if response.StatusCode != http.StatusForbidden { + return fmt.Errorf("%w: a report with %s was answered HTTP %d", errTerminal, label, response.StatusCode) + } + } + data, _ := json.Marshal(map[string]any{"operation": operation.Name, "answers": answers}) + return os.WriteFile(record, data, 0o600) +} + +// MediaInstall installs consumer A's fourth virtual media Installation. It +// settles the third hold, so the Metal provider selects the held method, and it +// must succeed with the hold cleared. The Installation and Machine then +// report Ready. +func (r *Runner) MediaInstall(ctx context.Context) error { + q, install, operation, err := r.mediaInstallation(ctx, "debian-media-4") + if err != nil { + return err + } + switch phase := operation.Status.Phase; { + case phase.Ended() && phase != ops.PhaseSucceeded: + return fmt.Errorf("%w: the installation ended %s: %s", errTerminal, phase, operation.Status.Reason) + case phase != ops.PhaseSucceeded: + return fmt.Errorf("%w: the installation is %s", errPending, phase) + } + state := &ops.DeviceCustody{} + if err := r.Provider.API.Get(ctx, client.ObjectKey{Namespace: DeviceNamespace, Name: Device}, state); err != nil { + return err + } + if state.Spec.RecoveryHold != nil { + return fmt.Errorf("%w: the hold survived the settling installation: %+v", errTerminal, state.Spec.RecoveryHold) + } + install.Status.Phase = "Ready" + install.Status.Conditions = []metav1.Condition{condition("Ready", metav1.ConditionTrue, install.Generation, "LocalVirtualMediaVerified")} + if err := q.project.API.Status().Update(ctx, install); err != nil { + return err + } + m := q.machine + m.Status.CurrentInstallationRef = &fleet.LocalReference{Name: install.Name} + m.Status.Phase = "Ready" + meta.SetStatusCondition(&m.Status.Conditions, condition("Ready", metav1.ConditionTrue, m.Generation, "LocalVirtualMediaVerified")) + if err := q.project.API.Status().Update(ctx, m); err != nil { + return err + } + fmt.Printf("media-install: %s succeeded at fence %d over virtual media and settled the hold\n", operation.Name, operation.Status.Fence) + return nil +} + +// custodyReader reads custody's active operation through the provider +// project API. +type custodyReader struct{ api client.Client } + +func (c custodyReader) Active(ctx context.Context, device string) (string, int64, bool, error) { + namespace, name, ok := strings.Cut(device, "/") + if !ok { + return "", 0, false, nil + } + state := &ops.DeviceCustody{} + if err := c.api.Get(ctx, client.ObjectKey{Namespace: namespace, Name: name}, state); apierrors.IsNotFound(err) { + return "", 0, false, nil + } else if err != nil { + return "", 0, false, err + } + active := state.Spec.ActiveOperation + if active == nil { + return "", 0, false, nil + } + return active.UID, active.Fence, true, nil +} + +// WorkerIdentity is the client certificate common name of a cell's site +// workers at the central media service. +func WorkerIdentity(cell string) string { return "fleet-site-worker:" + cell } + +// MediaService runs the central media service for the acceptance: on the +// workstation, beside the coordinator, with its own state and the +// coordinator's read of custody. Site workers authenticate with client +// certificates from clientCA; a worker of the configured cell may act only +// on the Devices that cell is enrolled to serve. It serves over TLS on +// listen until ctx ends, and sweeps stale config media every half minute. +func MediaService(ctx context.Context, c Config, listen, certFile, keyFile, clientCA, root, artifacts string, clients []netip.Prefix) error { + api, err := API(filepath.Join(c.State, "provider", "coordinator-project.json")) + if err != nil { + return err + } + identity, err := redfish.VerifyArtifacts(artifacts) + if err != nil || identity != c.Image { + return fmt.Errorf("the media service's artifacts are not the acceptance image") + } + caBytes, err := os.ReadFile(clientCA) + if err != nil { + return err + } + pool := x509.NewCertPool() + if !pool.AppendCertsFromPEM(caBytes) { + return errors.New("the site workers' client CA is invalid") + } + workers := func(identity, device string) bool { + _, enrolled := c.Enrollment[device] + return identity == WorkerIdentity(c.Cell) && enrolled + } + media := &redfishwork.MediaServer{Root: root, Artifacts: artifacts, Custody: custodyReader{api: api}, Clients: clients, Workers: workers} + go media.RunSweeps(ctx, 30*time.Second, func(err error) { fmt.Fprintf(os.Stderr, "media-service: sweep incomplete: %v\n", err) }) + // BMCs and installed servers present no certificate; the worker API + // requires one the client CA verified. + // listen is a comma-separated list of addresses, such as loopback over + // IPv4 and IPv6. + addresses := strings.Split(listen, ",") + errs := make(chan error, len(addresses)) + var servers []*http.Server + for _, address := range addresses { + server := &http.Server{Addr: strings.TrimSpace(address), Handler: media.Handler(), ReadHeaderTimeout: 5 * time.Second, WriteTimeout: 30 * time.Minute, IdleTimeout: 5 * time.Second, + TLSConfig: &tls.Config{MinVersion: tls.VersionTLS12, ClientAuth: tls.VerifyClientCertIfGiven, ClientCAs: pool}} + servers = append(servers, server) + go func() { errs <- server.ListenAndServeTLS(certFile, keyFile) }() + } + err = nil + select { + case <-ctx.Done(): + case err = <-errs: + } + for _, server := range servers { + _ = server.Close() + } + if errors.Is(err, http.ErrServerClosed) { + return nil + } + return err +} diff --git a/internal/multiplane/runner.go b/internal/multiplane/runner.go index 73eb6f03..6f55ad46 100644 --- a/internal/multiplane/runner.go +++ b/internal/multiplane/runner.go @@ -69,6 +69,13 @@ type Config struct { // Fleet synchronizes. Empty means the site's DHCP is configured // independently, as in the lab. BootAddressClass string `json:",omitempty"` + // DeliveryMethods is the cell's declared boot delivery methods, in its + // order of preference. The coordinator admits against it and the Metal + // provider selects from it. A cell that declares none offers none. + DeliveryMethods []custody.OfferedMethod `json:",omitempty"` + // MediaService is the central media service's endpoint, as BMCs and + // installed servers reach it, when the acceptance runs one. + MediaService string `json:",omitempty"` } type Project struct { @@ -152,7 +159,7 @@ func coordinator(ctx context.Context, c Config, registry *custody.Registry) (*cu return nil, nil, nil, nil, err } hub := &coordination.Hub{API: dynamicHub, Namespace: "fleet-coordination", Cell: c.Cell, MaxAge: time.Minute} - sites := &delivery.Sites{Sites: map[string]delivery.Site{c.Cell: hub}, Devices: map[string][]string{}} + sites := &delivery.Sites{Sites: map[string]delivery.Site{c.Cell: hub}, Devices: map[string][]string{}, Methods: map[string][]custody.OfferedMethod{c.Cell: c.DeliveryMethods}} for key := range c.Enrollment { namespace, name, _ := strings.Cut(key, "/") if namespace == DeviceNamespace { @@ -262,6 +269,7 @@ func New(ctx context.Context, c Config) (*Runner, error) { }, Capacity: &capacity.Projector{Reader: r.Provider.API, Namespace: DeviceNamespace, Cleaning: cleaningResolver}, BootInterface: "primary", TargetDisks: []string{"disk-0"}, + DeliveryMethods: c.DeliveryMethods, } if c.BootAddressClass != "" { // IPAM, aggregated by the provider project's Milo API, binds each claim @@ -431,6 +439,12 @@ func (r *Runner) projectPower(ctx context.Context, q *request) error { // 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) { + return r.installationNamed(ctx, index, "debian-pxe") +} + +// installationNamed creates the DeviceInstallation for one of the +// consumer's Installations once and returns it with the allocation. +func (r *Runner) installationNamed(ctx context.Context, index int, name string) (*request, *fleet.MachineAllocation, *fleet.Installation, *ops.DeviceInstallation, error) { q, err := r.request(ctx, index) if err != nil { return nil, nil, nil, nil, err @@ -443,12 +457,12 @@ func (r *Runner) installation(ctx context.Context, index int) (*request, *fleet. return nil, nil, nil, nil, errNoActiveAllocation } var install fleet.Installation - if err := q.project.API.Get(ctx, client.ObjectKey{Namespace: Namespace, Name: "debian-pxe"}, &install); err != nil { + if err := q.project.API.Get(ctx, client.ObjectKey{Namespace: Namespace, Name: name}, &install); err != nil { return nil, nil, nil, nil, err } operation := &ops.DeviceInstallation{} - name := custody.InstallationName(current.Name, string(install.UID)) - if err := r.Provider.API.Get(ctx, client.ObjectKey{Namespace: DeviceNamespace, Name: name}, operation); apierrors.IsNotFound(err) { + key := client.ObjectKey{Namespace: DeviceNamespace, Name: custody.InstallationName(current.Name, string(install.UID))} + if err := r.Provider.API.Get(ctx, key, operation); apierrors.IsNotFound(err) { previous := "" if ref := q.machine.Status.CurrentInstallationRef; ref != nil { previous = ref.Name From 801d89e0f178f1906f06fced4ed9730e15a3d228 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Fri, 27 Nov 2026 12:00:07 -0600 Subject: [PATCH 05/35] test(lab): Pad the fake config medium The adapter self-test's fake config medium had no padding, so the add-download fault, which grows the medium within its padded size, refused to apply. Media the service renders are padded to 8192 bytes. Co-Authored-By: Claude Opus 5.5 --- hack/redfish-lab/test_adapter.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/hack/redfish-lab/test_adapter.py b/hack/redfish-lab/test_adapter.py index ce2d5517..a98ff1e7 100644 --- a/hack/redfish-lab/test_adapter.py +++ b/hack/redfish-lab/test_adapter.py @@ -200,7 +200,8 @@ def fake_fetch(url, path): self.app.post('/redfish/v1/Systems/System-1/Actions/ComputerSystem.Reset', headers=AUTH, json={'ResetType': 'ForceOff'}) # A corrupted config medium carries another report token. def config_fetch(url, path): - pathlib.Path(path).write_bytes(b'FLEET-CONFIG-V1\ntoken=' + b'a' * 64 + b'\nend\n') + # Padded with zeros, as the media service renders it. + pathlib.Path(path).write_bytes((b'FLEET-CONFIG-V1\ntoken=' + b'a' * 64 + b'\nend\n').ljust(8192, b'\0')) return 1 adapter.fault_cli(['corrupt-config', 'System-1']) # A boot medium does not consume the fault. From bd1fdac7ec80c56269575b3a9bcaed3e93e63370 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Fri, 27 Nov 2026 12:33:57 -0600 Subject: [PATCH 06/35] test(multiplane): Give stale opens report ranges The stale-fence step's window opens named no report address range, which the media service now requires, so the cell worker's open was refused as malformed (400) before custody refused its fence (409). Co-Authored-By: Claude Opus 5.5 --- hack/multiplane/media_steps.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/hack/multiplane/media_steps.py b/hack/multiplane/media_steps.py index d2609fa9..db02a7f6 100644 --- a/hack/multiplane/media_steps.py +++ b/hack/multiplane/media_steps.py @@ -343,7 +343,8 @@ def stale_fence(s): w = window_record(s, op['metadata']['uid']) body = {'device': harness.DEVICE, 'operation': op['metadata']['uid'], 'fence': op['status']['fence'], 'bootDigest': w['bootDigest'], 'capabilitySHA256': '0' * 64, 'tokenSHA256': '0' * 64, 'configMedium': base64.b64encode(b'stale').decode(), - 'fetchExpires': later(10), 'reportExpires': later(20)} + 'fetchExpires': later(10), 'reportExpires': later(20), 'reportFrom': ['127.0.0.1/32']} + # A well-formed open, so the cell worker's answer is custody's. # Without a client certificate, and with another site's, the open is # refused before the service looks at custody; as the cell's worker, # custody refuses it. From 8a00a792f878f39cb8d5f0854701da5bb573189c Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Fri, 27 Nov 2026 16:22:02 -0600 Subject: [PATCH 07/35] feat(site): Take reports only from the Machine A first-boot report was checked only against the site's report ranges, so another server inside them that learned the token could post it. - A virtual media installation records the Machine's address, claimed from the same source and checked at admission as a network boot's provisioning address is. Admission refuses virtual media without it. - The worker sends it with the window, and writes it to the config medium, so the installed OS reports from it. - The media service keeps the site's ranges as the outer bound and takes a report only from that address. A report from another address in the ranges is refused and recorded, with whether it carried the right token; the token is never kept. - A PROXY protocol listener takes a report's source from a relay or load balancer it trusts, for paths that rewrite source addresses. - A site may set where its installed servers reach the media service. The no-report case's fetch window was too short to open under load, so it is widened. Co-Authored-By: Claude Opus 5.5 --- cmd/fleet-multiplane/site.go | 9 ++ .../crds/fleet.datumapis.com.yaml | 38 +++++- docs/development/device-custody.md | 6 +- internal/allocation/allocator.go | 23 +++- internal/allocation/bootaddress_test.go | 42 +++++++ internal/api/operations/v1alpha1/types.go | 6 + internal/custody/delivery.go | 19 ++- internal/custody/delivery_test.go | 28 ++++- internal/custody/kinds.go | 17 ++- internal/site/redfishwork/kinds.go | 5 + internal/site/redfishwork/media.go | 29 ++++- internal/site/redfishwork/media_test.go | 75 ++++++++++-- internal/site/redfishwork/mediaserver.go | 84 +++++++++++-- internal/site/redfishwork/proxy.go | 112 ++++++++++++++++++ internal/site/redfishwork/proxy_test.go | 87 ++++++++++++++ 15 files changed, 545 insertions(+), 35 deletions(-) create mode 100644 internal/site/redfishwork/proxy.go create mode 100644 internal/site/redfishwork/proxy_test.go diff --git a/cmd/fleet-multiplane/site.go b/cmd/fleet-multiplane/site.go index 8bd865c4..8582c29a 100644 --- a/cmd/fleet-multiplane/site.go +++ b/cmd/fleet-multiplane/site.go @@ -194,6 +194,15 @@ func redfishConfig() (redfishwork.Config, redfish.Enrollment, error) { } work.ReportFrom = append(work.ReportFrom, prefix.Masked()) } + // How this site's installed servers reach the media service, when not + // at its recorded endpoint. + if value := os.Getenv("FLEET_MEDIA_REPORT_ORIGIN"); value != "" { + origin, err := redfish.ParseEndpoint(value) + if err != nil || !strings.HasPrefix(origin, "https://") { + return redfishwork.Config{}, redfish.Enrollment{}, errors.New("FLEET_MEDIA_REPORT_ORIGIN must be https://IP:port") + } + work.ReportOrigin = origin + } return work, enrollment, nil } diff --git a/config/components/device-operations/crds/fleet.datumapis.com.yaml b/config/components/device-operations/crds/fleet.datumapis.com.yaml index 852b8ce6..d805d5bf 100644 --- a/config/components/device-operations/crds/fleet.datumapis.com.yaml +++ b/config/components/device-operations/crds/fleet.datumapis.com.yaml @@ -597,13 +597,45 @@ spec: reportWindow: type: string maxLength: 32 + reportAddress: + type: object + properties: + addressClaim: + type: object + properties: + apiGroup: + type: string + minLength: 1 + maxLength: 253 + kind: + type: string + minLength: 1 + maxLength: 63 + name: + type: string + minLength: 1 + maxLength: 253 + required: + - apiGroup + - kind + - name + address: + type: string + minLength: 2 + maxLength: 45 + x-kubernetes-validations: + - rule: isIP(self) + message: address must be one IP address without a prefix length + required: + - addressClaim + - address required: - method x-kubernetes-validations: - - rule: self.method != 'NetworkBoot' || (!has(self.addresses) && !has(self.mediaService) && !has(self.fetchWindow) && !has(self.reportWindow)) + - rule: self.method != 'NetworkBoot' || (!has(self.addresses) && !has(self.mediaService) && !has(self.fetchWindow) && !has(self.reportWindow) && !has(self.reportAddress)) message: network boot records no virtual media inputs - - rule: self.method != 'VirtualMedia' || (has(self.addresses) && has(self.mediaService) && has(self.fetchWindow) && has(self.reportWindow)) - message: virtual media records the site's address mode, media service and phase windows + - rule: self.method != 'VirtualMedia' || (has(self.addresses) && has(self.mediaService) && has(self.fetchWindow) && has(self.reportWindow) && has(self.reportAddress)) + message: virtual media records the site's address mode, media service, phase windows and the Machine's report address required: - creator - deviceRef diff --git a/docs/development/device-custody.md b/docs/development/device-custody.md index 40a11121..f2712f86 100644 --- a/docs/development/device-custody.md +++ b/docs/development/device-custody.md @@ -321,7 +321,11 @@ operations guide describes how it runs in the [Redfish lab](../operations/redfis - **Every installation records its method.** `spec.delivery` names `NetworkBoot` or `VirtualMedia`, and for virtual media the central media - service, the address mode and the fetch and report windows. A virtual + service, the address mode, the fetch and report windows, and the + Machine's report address. The Metal provider claims that address from the + same source as a network boot's provisioning address, and admission checks + it is still bound to the operation's own claim. The media service takes the + first-boot report only from it. A virtual media installation's deadline is the sum of its windows. - **Sites declare their methods.** `custody.Sites` gains `DeliveryMethods`, the site's methods in its order of preference. Admission sees the methods diff --git a/internal/allocation/allocator.go b/internal/allocation/allocator.go index bcc449ef..ef775bbe 100644 --- a/internal/allocation/allocator.go +++ b/internal/allocation/allocator.go @@ -173,6 +173,11 @@ type Allocator struct { DeliveryMethods []custody.OfferedMethod } +// ErrNoReportAddress means the site has no address source that claims a +// Machine's address without a boot attachment, so a virtual media install +// could not record the address its report must come from. +var ErrNoReportAddress = errors.New("allocation: virtual media needs an address source that claims the Machine's address") + // ErrNoDeliveryMethod means the site offers no delivery method the server // is qualified for, so nothing can install it. var ErrNoDeliveryMethod = errors.New("allocation: the site offers no delivery method the server is qualified for") @@ -549,13 +554,25 @@ func (a *Allocator) Install(ctx context.Context, allocation *fleetv1.MachineAllo if err != nil { return nil, err } - operation.Spec.Delivery = delivery - // Only network boot needs a provisioning address. - if delivery.Method == ops.DeliveryNetworkBoot { + // Network boot needs a provisioning address. Virtual media needs the + // Machine's address instead, which its installed OS reports from; it + // is claimed, recorded and released the same way, with no boot + // attachment. + switch delivery.Method { + case ops.DeliveryNetworkBoot: if operation.Spec.BootNetwork, err = a.bootNetwork(ctx, a.installClaims(), allocation, "DeviceInstallation", operation.Name); err != nil { return nil, err } + case ops.DeliveryVirtualMedia: + source := a.installClaims() + if _, attaching := source.(attaches); source == nil || attaching { + return nil, ErrNoReportAddress + } + if delivery.ReportAddress, err = a.bootNetwork(ctx, source, allocation, "DeviceInstallation", operation.Name); err != nil { + return nil, err + } } + operation.Spec.Delivery = delivery return operation, a.createOnce(ctx, a.Provider, operation, &ops.DeviceInstallation{}) } diff --git a/internal/allocation/bootaddress_test.go b/internal/allocation/bootaddress_test.go index 8b650742..6c960001 100644 --- a/internal/allocation/bootaddress_test.go +++ b/internal/allocation/bootaddress_test.go @@ -293,3 +293,45 @@ func TestAnExhaustedPoolSendsNothing(t *testing.T) { t.Fatalf("operations = %d, %v", len(operations.Items), err) } } + +// TestAVirtualMediaInstallRecordsTheMachinesAddress claims the Machine's +// address for a virtual media install from the same source as a boot +// address, before the operation exists, and records it as the address its +// report must come from; with no such source, no installation is created. +func TestAVirtualMediaInstallRecordsTheMachinesAddress(t *testing.T) { + e := startEnv(t) + recorder := &ipam{Client: e.admin} + e.allocator.Provider, e.allocator.Releaser = writer{recorder, "DeviceInstallation"}, writer{recorder, "DeviceWipe"} + e.allocator.DeliveryMethods = []custody.OfferedMethod{{Method: ops.DeliveryVirtualMedia, Addresses: ops.AddressesDataNetwork, MediaService: "https://192.0.2.10:8443"}} + device := e.server(1) + e.until("staff record the server as qualified for virtual media", func() bool { + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(device), device); err != nil { + t.Fatal(err) + } + device.Annotations = map[string]string{custody.QualifiedMethodsAnnotation: "VirtualMedia"} + return e.admin.Update(e.ctx, device) == nil + }) + allocation, err := e.allocator.Allocate(e.ctx, e.request(1)) + 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) { + t.Fatalf("an install with no address source = %v", err) + } + name := custody.InstallationName(allocation.Name, uid(701)) + if err := e.admin.Get(e.ctx, client.ObjectKey{Namespace: namespace, Name: name}, &ops.DeviceInstallation{}); !apierrors.IsNotFound(err) { + 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", "")}) + if err != nil { + t.Fatal(err) + } + report := operation.Spec.Delivery.ReportAddress + if operation.Spec.BootNetwork != nil || report == nil || report.AddressClaim.Name != bootaddress.ClaimName(operation.Name) || report.Address == "" { + t.Fatalf("boot network %+v, report address %+v", operation.Spec.BootNetwork, report) + } + if creates := recorder.created(); len(creates) < 2 || creates[len(creates)-2] != report.AddressClaim.Name || creates[len(creates)-1] != operation.Name { + t.Fatalf("creates = %v, want the claim before the operation", creates) + } +} diff --git a/internal/api/operations/v1alpha1/types.go b/internal/api/operations/v1alpha1/types.go index ce177afd..ba53831d 100644 --- a/internal/api/operations/v1alpha1/types.go +++ b/internal/api/operations/v1alpha1/types.go @@ -369,6 +369,12 @@ type DeliveryInput struct { // first-boot report. The operation's deadline is their sum. FetchWindow *metav1.Duration `json:"fetchWindow,omitempty"` ReportWindow *metav1.Duration `json:"reportWindow,omitempty"` + // ReportAddress is the Machine's address that IPAM bound for this + // operation, claimed and checked as a boot address claim is. The + // installed OS posts its first-boot report from it, and the media + // service accepts the report from no other address. Virtual media + // requires it. + ReportAddress *BootNetworkInput `json:"reportAddress,omitempty"` } // Default virtual media phases: 15 minutes to fetch the media, then 30 diff --git a/internal/custody/delivery.go b/internal/custody/delivery.go index 23433748..09ec789a 100644 --- a/internal/custody/delivery.go +++ b/internal/custody/delivery.go @@ -3,6 +3,7 @@ package custody import ( "context" "fmt" + "net/netip" "regexp" "slices" "strings" @@ -70,6 +71,10 @@ const ( // ReasonDeliveryInputs means the method does not match the operation's // other inputs, such as a virtual media operation with a boot network. ReasonDeliveryInputs = "DeliveryInputsMismatch" + // ReasonReportAddressRequired means a virtual media installation + // records no IPAM address for its first-boot report, so the media + // service could not tell its report from another server's. + ReasonReportAddressRequired = "ReportAddressRequired" // ReasonDownloadUnpinned means the installer would download an // artifact that the operation does not pin by digest. ReasonDownloadUnpinned = "InstallDownloadUnpinned" @@ -118,7 +123,7 @@ func checkDownloads(downloads []ops.DownloadInput) *Refusal { var deliveryReasons = []Reason{{Name: ReasonDeliveryNotOffered, RaisedBy: RaisedByCoordinator}, {Name: ReasonDeliveryUnqualified, RaisedBy: RaisedByCoordinator}, {Name: ReasonDeliveryMismatch, RaisedBy: RaisedByCoordinator}, {Name: ReasonDeliveryInputs, RaisedBy: RaisedByBoth}, - {Name: ReasonDownloadUnpinned, RaisedBy: RaisedByCoordinator}, {Name: ReasonMediaTLSUnverified, RaisedBy: RaisedByCoordinator}, + {Name: ReasonDownloadUnpinned, RaisedBy: RaisedByCoordinator}, {Name: ReasonReportAddressRequired, RaisedBy: RaisedByBoth}, {Name: ReasonMediaTLSUnverified, RaisedBy: RaisedByCoordinator}, {Name: ReasonMediaWindowRefused, RaisedBy: RaisedByWorker}} // ExtraDeliveryMethod is the snapshot field that records the method an @@ -223,6 +228,9 @@ func checkDelivery(admission *Admission, spec *ops.DeviceInstallationSpec) *Refu if !mediaEndpoint.MatchString(spec.Delivery.MediaService) || DeliveryDeadline(spec.Delivery) <= 0 || spec.Delivery.FetchWindow.Duration <= 0 || spec.Delivery.ReportWindow.Duration <= 0 { return refuse(ReasonDeliveryInputs, "virtual media records its media service and both phase windows") } + if report := spec.Delivery.ReportAddress; report == nil || !validHostAddress(report.Address) { + return refuse(ReasonReportAddressRequired, "virtual media records the Machine's IPAM address, which the installed OS reports from") + } default: return refuse(ReasonDeliveryInputs, "the delivery method %q is not known", method) } @@ -275,6 +283,15 @@ func OnlyNetworkBoot(delivery ops.DeliveryInput) *Refusal { return nil } +// validHostAddress reports whether address is one IP address without a +// prefix length or zone. +func validHostAddress(address string) bool { + parsed, err := netip.ParseAddr(address) + return err == nil && parsed.Zone() == "" && parsed.String() == address +} + +// equalInput compares the site's inputs for a method. The report address +// is the operation's own, not the site's, so it is not compared. func equalInput(a, b ops.DeliveryInput) bool { duration := func(d *metav1.Duration) time.Duration { if d == nil { diff --git a/internal/custody/delivery_test.go b/internal/custody/delivery_test.go index a01c12fc..a0d4ce0a 100644 --- a/internal/custody/delivery_test.go +++ b/internal/custody/delivery_test.go @@ -11,6 +11,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/bootaddress" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/controller-runtime/pkg/client" ) @@ -85,6 +86,12 @@ func TestDeliveryMethodAdmission(t *testing.T) { install := func(e *env, device *inventory.Device, request string, delivery ops.DeliveryInput, network *ops.BootNetworkInput) *ops.DeviceInstallation { e.t.Helper() allocation := "alloc-d-" + device.Name + if delivery.Method == ops.DeliveryVirtualMedia && delivery.ReportAddress == nil { + // The Machine's address, bound to the operation's own claim. + name := InstallationName(allocation, request) + claim := e.ipClaim(bootaddress.ClaimName(name), name, "DeviceInstallation", "Bound", "198.51.100.40") + delivery.ReportAddress = &ops.BootNetworkInput{AddressClaim: bootaddress.Reference(claim.GetName()), Address: "198.51.100.40"} + } operation := &ops.DeviceInstallation{ObjectMeta: metav1.ObjectMeta{Name: InstallationName(allocation, request), Namespace: "default"}, Spec: ops.DeviceInstallationSpec{ OperationEnvelope: envelope(device, providerUser, allocated(allocation)), RequestUID: request, Image: ops.ImageInput{Name: "debian-12", Digest: imageDigest}, BootInterface: "primary", TargetDisks: []string{"disk-0"}, BootNetwork: network, Delivery: delivery, @@ -148,6 +155,23 @@ func TestDeliveryMethodAdmission(t *testing.T) { e.requireUntouched(device.Name, fence) }) + t.Run("a virtual media install reports only from its own claimed address", func(t *testing.T) { + e := e.sub(t) + device := held(e, "VirtualMedia") + fence := e.custody(device.Name).Spec.Fence + if refusal := checkDelivery(&Admission{Device: device, Custody: e.custody(device.Name), Offered: e.sites.DeliveryMethods("")}, &ops.DeviceInstallationSpec{Delivery: virtualMedia}); refusal == nil || refusal.Reason != ReasonReportAddressRequired { + t.Fatalf("virtual media with no report address: %+v", refusal) + } + // Another operation's claim does not hold this one's address. + other := e.ipClaim(bootaddress.ClaimName("alloc-d-other-install"), "alloc-d-other-install", "DeviceInstallation", "Bound", "198.51.100.41") + borrowed := virtualMedia + borrowed.ReportAddress = &ops.BootNetworkInput{AddressClaim: bootaddress.Reference(other.GetName()), Address: "198.51.100.41"} + operation := install(e, device, "request-1", borrowed, nil) + e.settle(device.Name) + e.requirePhase(operation, ops.PhaseFailed, ReasonBootAddressMismatch) + e.requireUntouched(device.Name, fence) + }) + t.Run("a held virtual media install is settled only by virtual media", func(t *testing.T) { e := e.sub(t) device := held(e, "VirtualMedia") @@ -257,10 +281,12 @@ func TestDeliveryMethodAdmission(t *testing.T) { device := held(e, "VirtualMedia") fence := e.custody(device.Name).Spec.Fence allocation := "alloc-d-" + device.Name + delivery := virtualMedia + delivery.ReportAddress = &ops.BootNetworkInput{AddressClaim: bootaddress.Reference(bootaddress.ClaimName(InstallationName(allocation, "request-1"))), Address: "198.51.100.40"} operation := &ops.DeviceInstallation{ObjectMeta: metav1.ObjectMeta{Name: InstallationName(allocation, "request-1"), Namespace: "default"}, Spec: ops.DeviceInstallationSpec{ OperationEnvelope: envelope(device, providerUser, allocated(allocation)), RequestUID: "request-1", Image: ops.ImageInput{Name: "talos", Digest: imageDigest, Downloads: []ops.DownloadInput{{Name: "installer", Reference: "registry.example/installer:v1.0.0"}}}, - BootInterface: "primary", TargetDisks: []string{"disk-0"}, Delivery: virtualMedia, + BootInterface: "primary", TargetDisks: []string{"disk-0"}, Delivery: delivery, }} e.create(operation) e.settle(device.Name) diff --git a/internal/custody/kinds.go b/internal/custody/kinds.go index 3fdd8c3d..e94cf2a0 100644 --- a/internal/custody/kinds.go +++ b/internal/custody/kinds.go @@ -93,12 +93,19 @@ func checkNetworkBoot(ctx context.Context, admission *Admission, kind, bootInter if network == nil { return nil } + return checkAddressClaim(ctx, admission, kind, *network) +} + +// checkAddressClaim requires an operation's recorded address to still be +// bound to the operation's own claim, through the check registered for the +// claim's kind. +func checkAddressClaim(ctx context.Context, admission *Admission, kind string, network ops.BootNetworkInput) *Refusal { claim := network.AddressClaim check := admission.Registry.BootAddressClaim(claim.APIGroup, claim.Kind) if check == nil { return refuse(ReasonBootAddressUnsupported, "boot address claims of kind %s/%s cannot be checked", claim.APIGroup, claim.Kind) } - if err := check(ctx, admission.Reader, admission.Operation, kind, *network); errors.Is(err, bootaddress.ErrUnreachable) { + if err := check(ctx, admission.Reader, admission.Operation, kind, network); errors.Is(err, bootaddress.ErrUnreachable) { // Fail closed without deciding: the claim may still hold the address. refusal := refuse(ReasonBootAddress, "waiting: the boot address claim %s could not be read: %v", claim.Name, err) refusal.Retry = true @@ -175,7 +182,13 @@ func DeviceInstallationKind() Kind { if refusal := checkDelivery(admission, &installation.Spec); refusal != nil { return refusal } - return checkNetworkBoot(ctx, admission, "DeviceInstallation", installation.Spec.BootInterface, installation.Spec.BootNetwork) + if refusal := checkNetworkBoot(ctx, admission, "DeviceInstallation", installation.Spec.BootInterface, installation.Spec.BootNetwork); refusal != nil { + return refusal + } + if report := installation.Spec.Delivery.ReportAddress; report != nil { + return checkAddressClaim(ctx, admission, "DeviceInstallation", *report) + } + return nil }, SnapshotExtra: func(admission *Admission) map[string]string { return map[string]string{ExtraDeliveryMethod: string(admission.Operation.(*ops.DeviceInstallation).Spec.Delivery.Method)} diff --git a/internal/site/redfishwork/kinds.go b/internal/site/redfishwork/kinds.go index c5772c4f..16be7ad2 100644 --- a/internal/site/redfishwork/kinds.go +++ b/internal/site/redfishwork/kinds.go @@ -86,6 +86,11 @@ type Config struct { // servers post their first-boot reports from. A window takes no report // from elsewhere. A site without it cannot use virtual media. ReportFrom []netip.Prefix + // ReportOrigin is the media service as the site's installed servers + // reach it to post their reports, as https://IP:port, when that path + // differs from the recorded media service, such as through a relay that + // keeps each report's source address. Empty means the media service. + ReportOrigin string // Artifacts holds the image's pinned artifacts and their manifest. A // virtual media installation derives its boot medium from them. Artifacts string diff --git a/internal/site/redfishwork/media.go b/internal/site/redfishwork/media.go index 6435a90c..4f9a326a 100644 --- a/internal/site/redfishwork/media.go +++ b/internal/site/redfishwork/media.go @@ -14,6 +14,7 @@ import ( "fmt" "io" "net/http" + "net/netip" "os" "path/filepath" "slices" @@ -91,6 +92,9 @@ type mediaPlan struct { report time.Duration downloads []ops.DownloadInput addresses ops.AddressMode + // reportAddress is the Machine's IPAM address, the only source the + // media service takes this operation's report from. + reportAddress string } // planMedia checks the admitted inputs against the site's pinned artifacts @@ -111,6 +115,14 @@ func (c Config) planMedia(spec ops.DeviceInstallationSpec) (mediaPlan, error) { return mediaPlan{}, err } plan := mediaPlan{origin: origin, fetch: delivery.FetchWindow.Duration, report: delivery.ReportWindow.Duration, downloads: spec.Image.Downloads, addresses: delivery.Addresses} + if delivery.ReportAddress == nil { + return mediaPlan{}, errors.New("the installation records no address for its report") + } + address, err := netip.ParseAddr(delivery.ReportAddress.Address) + if err != nil || address.Zone() != "" || !slices.ContainsFunc(c.ReportFrom, func(prefix netip.Prefix) bool { return prefix.Contains(address) }) { + return mediaPlan{}, errors.New("the installation's report address is not inside this site's report ranges") + } + plan.reportAddress = address.String() var content strings.Builder for _, line := range strings.Split(strings.TrimSpace(string(manifest)), "\n") { fields := strings.Fields(line) @@ -181,8 +193,8 @@ func mediaDevices(devices []redfish.Media) (boot, config redfish.Media, ok bool) // OS posts its report with the certificate it must verify there. func renderConfig(token, salt string, bootstrap []byte, plan mediaPlan, reportURL string, reportCA []byte) ([]byte, error) { var b strings.Builder - fmt.Fprintf(&b, "FLEET-CONFIG-V1\ntoken=%s\nsalt=%s\naddresses=%s\nbootstrap=%s\nreport=%s\nreportca=%s\n", token, salt, plan.addresses, - base64.StdEncoding.EncodeToString(bootstrap), reportURL, base64.StdEncoding.EncodeToString(reportCA)) + fmt.Fprintf(&b, "FLEET-CONFIG-V1\ntoken=%s\nsalt=%s\naddresses=%s\nreportaddress=%s\nbootstrap=%s\nreport=%s\nreportca=%s\n", token, salt, plan.addresses, + plan.reportAddress, base64.StdEncoding.EncodeToString(bootstrap), reportURL, base64.StdEncoding.EncodeToString(reportCA)) for _, download := range plan.downloads { fmt.Fprintf(&b, "download=%s %s\n", download.Name, download.Reference) } @@ -347,7 +359,7 @@ func (c Config) window(ctx context.Context, work *site.Work, media *mediaClient, // The sealed store is not on this branch, so admission refuses // bootstrap data and the payload is always empty. var payload []byte - data, err := renderConfig(token, salt, payload, plan, ReportURL(plan.origin, key), c.MediaCA) + data, err := renderConfig(token, salt, payload, plan, ReportURL(c.reportOrigin(plan), key), c.MediaCA) if err != nil { return window, err } @@ -370,7 +382,7 @@ func (c Config) window(ctx context.Context, work *site.Work, media *mediaClient, open := func(ctx context.Context) error { return media.open(ctx, key, OpenRequest{Device: work.Device, Operation: work.Key(), Fence: work.Fence, BootDigest: window.BootDigest, CapabilitySHA256: digest(medium.Capability), TokenSHA256: window.TokenSHA256, ConfigMedium: medium.Data, - FetchExpires: window.FetchExpires, ReportExpires: window.ReportExpires, ReportFrom: c.reportFrom()}) + FetchExpires: window.FetchExpires, ReportExpires: window.ReportExpires, ReportFrom: c.reportFrom(), ReportAddress: plan.reportAddress}) } if err := work.Step(ctx, site.Step{Name: "media-window", Send: open, Idempotent: true}); err != nil { return mediaWindow{}, err @@ -806,6 +818,15 @@ func bmcStepJournaled(work *site.Work) bool { return false } +// reportOrigin is where the installed OS posts its report: the site's +// report path to the media service, or the recorded media service. +func (c Config) reportOrigin(plan mediaPlan) string { + if c.ReportOrigin != "" { + return c.ReportOrigin + } + return plan.origin +} + func (c Config) reportFrom() []string { out := make([]string, 0, len(c.ReportFrom)) for _, prefix := range c.ReportFrom { diff --git a/internal/site/redfishwork/media_test.go b/internal/site/redfishwork/media_test.go index 2f9315b7..7d101d3a 100644 --- a/internal/site/redfishwork/media_test.go +++ b/internal/site/redfishwork/media_test.go @@ -29,6 +29,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" "go.datum.net/fleet/internal/custody" "go.datum.net/fleet/internal/redfish" "go.datum.net/fleet/internal/site" @@ -445,7 +446,9 @@ func (e *mediaEnv) spec() ops.DeviceInstallationSpec { image.Downloads = e.downloads return ops.DeviceInstallationSpec{Image: image, BootInterface: "primary", TargetDisks: []string{"disk-0"}, RequestUID: "request-1", Delivery: ops.DeliveryInput{Method: ops.DeliveryVirtualMedia, Addresses: ops.AddressesDataNetwork, MediaService: e.origin, - FetchWindow: &metav1.Duration{Duration: e.fetch}, ReportWindow: &metav1.Duration{Duration: e.report}}} + FetchWindow: &metav1.Duration{Duration: e.fetch}, ReportWindow: &metav1.Duration{Duration: e.report}, + // The fake BMC network posts reports from the Machine's address. + ReportAddress: &ops.BootNetworkInput{AddressClaim: fleetv1.TypedReference{APIGroup: "ipam.miloapis.com", Kind: "IPClaim", Name: "alloc-example-install-report"}, Address: "192.0.2.50"}}} } // assignment admits the operation: custody names it active at its fence. @@ -666,7 +669,9 @@ func TestAFirstBootReportThatDoesNotProveTheInstallNeverSucceeds(t *testing.T) { } { t.Run(name, func(t *testing.T) { e := newMediaEnv(t) - e.fetch, e.report = 500*time.Millisecond, 300*time.Millisecond + // The fetch window must outlast opening it under load, or the + // window is refused before it exists. + e.fetch, e.report = 2*time.Second, 300*time.Millisecond set(e.bmc) result := e.run(t, "op-report", 1) if result.Phase != ops.PhaseOutcomeUnknown || e.journaled("op-report")["media-released"] != "" { @@ -699,8 +704,13 @@ func TestTheMediaServiceServesAndReportsOnlyThroughAnOpenWindow(t *testing.T) { return recorder.Code } open, _ := json.Marshal(OpenRequest{Device: device, Operation: "op-serve", Fence: 1, BootDigest: strings.Repeat("b", 64), CapabilitySHA256: digest(capability), TokenSHA256: digest(token), - ConfigMedium: []byte("medium"), FetchExpires: now.Add(time.Minute), ReportExpires: now.Add(2 * time.Minute), ReportFrom: []string{"192.0.2.60/32"}}) + ConfigMedium: []byte("medium"), FetchExpires: now.Add(time.Minute), ReportExpires: now.Add(2 * time.Minute), ReportFrom: []string{"192.0.2.0/24"}, ReportAddress: "192.0.2.60"}) key := Key("op-serve") + // The Machine's address must lie inside the site's report ranges. + outside := strings.Replace(string(open), `"reportAddress":"192.0.2.60"`, `"reportAddress":"198.51.100.60"`, 1) + if code := call(http.MethodPut, "/v1/windows/"+key, outside, "127.0.0.1:1"); code != http.StatusBadRequest { + t.Fatalf("an open whose report address is outside the ranges = %d", code) + } if code := call(http.MethodPut, "/v1/windows/"+key, string(open), "127.0.0.1:1"); code != http.StatusCreated { t.Fatalf("open = %d", code) } @@ -725,13 +735,18 @@ func TestTheMediaServiceServesAndReportsOnlyThroughAnOpenWindow(t *testing.T) { t.Fatalf("a report with another token = %d", code) } good := `{"token":"` + token + `","image":"sha256:1","bootstrap":"sha256:2"}` - // A report with the right token from an address that is not the - // Machine's is refused for where it came from. + // A report with the right token from outside the site's ranges is + // refused for where it came from. + if code := call(http.MethodPost, "/report/"+key, good, "127.0.0.2:1"); code != http.StatusForbidden { + t.Fatalf("a report from outside the ranges = %d", code) + } + // So is one from another server inside them: only the Machine's own + // address may report, and the refusal is recorded without the token. if code := call(http.MethodPost, "/report/"+key, good, "192.0.2.61:1"); code != http.StatusForbidden { - t.Fatalf("a report from another address = %d", code) + t.Fatalf("a report from another address in the ranges = %d", code) } - if window := e.window(t, "op-serve"); window.Report != nil { - t.Fatal("a report from another address was taken") + if window := e.window(t, "op-serve"); window.Report != nil || len(window.Refused) != 1 || window.Refused[0].From != "192.0.2.61" || !window.Refused[0].TokenMatched { + t.Fatalf("a report from another address in the ranges: %+v %+v", window.Report, window.Refused) } if code := report(good); code != http.StatusOK { t.Fatalf("the report = %d", code) @@ -743,7 +758,7 @@ func TestTheMediaServiceServesAndReportsOnlyThroughAnOpenWindow(t *testing.T) { t.Fatalf("a second, different use of the token = %d", code) } window := e.window(t, "op-serve") - if window.Rejected != 3 || window.Duplicates != 1 || window.Report == nil || window.Report.Image != "sha256:1" { + if window.Rejected != 4 || window.Duplicates != 1 || window.Report == nil || window.Report.Image != "sha256:1" { t.Fatalf("window = %+v", window) } // Past the fetch deadline the media stop; a fence rise stops everything. @@ -892,7 +907,7 @@ func TestTheWorkerAPIRequiresTheSiteWorkersIdentity(t *testing.T) { e.custody.set("op-auth", 1) key := Key("op-auth") open, _ := json.Marshal(OpenRequest{Device: device, Operation: "op-auth", Fence: 1, BootDigest: strings.Repeat("b", 64), CapabilitySHA256: digest("c"), TokenSHA256: digest("t"), - ConfigMedium: []byte("medium"), FetchExpires: time.Now().Add(time.Minute), ReportExpires: time.Now().Add(2 * time.Minute), ReportFrom: []string{"192.0.2.50/32"}}) + ConfigMedium: []byte("medium"), FetchExpires: time.Now().Add(time.Minute), ReportExpires: time.Now().Add(2 * time.Minute), ReportFrom: []string{"192.0.2.50/32"}, ReportAddress: "192.0.2.50"}) call := func(method, path, body, identity string) int { request := httptest.NewRequest(method, path, strings.NewReader(body)) request.RemoteAddr = "127.0.0.1:1" @@ -1039,3 +1054,43 @@ func TestTheSweepSkipsAnUnreadableWindow(t *testing.T) { t.Fatal("an unreadable window stopped the sweep before a stale one") } } + +// TestAReportComesOnlyFromTheMachinesAddress takes a first-boot report only +// from the Machine's IPAM address. Another server inside the site's report +// ranges that carries the right token is refused and recorded, and the +// token stays unspent for the Machine itself. +func TestAReportComesOnlyFromTheMachinesAddress(t *testing.T) { + e := newMediaEnv(t) + token := strings.Repeat("a", 64) + e.custody.set("op-address", 1) + open, _ := json.Marshal(OpenRequest{Device: device, Operation: "op-address", Fence: 1, BootDigest: strings.Repeat("b", 64), CapabilitySHA256: digest("c"), TokenSHA256: digest(token), + ConfigMedium: []byte("medium"), FetchExpires: time.Now().Add(time.Minute), ReportExpires: time.Now().Add(2 * time.Minute), + ReportFrom: []string{"192.0.2.0/24"}, ReportAddress: "192.0.2.70"}) + key := Key("op-address") + call := func(method, path, body, from string) int { + request := httptest.NewRequest(method, path, strings.NewReader(body)) + request.RemoteAddr = from + if strings.HasPrefix(path, "/v1/") { + e.workers.asWorker(t, request, workerIdentity) + } + recorder := httptest.NewRecorder() + e.central.Handler().ServeHTTP(recorder, request) + return recorder.Code + } + if code := call(http.MethodPut, "/v1/windows/"+key, string(open), "127.0.0.1:1"); code != http.StatusCreated { + t.Fatalf("open = %d", code) + } + good := `{"token":"` + token + `","image":"sha256:1","bootstrap":"sha256:2"}` + if code := call(http.MethodPost, "/report/"+key, good, "192.0.2.71:1"); code != http.StatusForbidden { + t.Fatalf("the right token from another address in the ranges = %d", code) + } + if window := e.window(t, "op-address"); window.Report != nil || len(window.Refused) != 1 || window.Refused[0].From != "192.0.2.71" || !window.Refused[0].TokenMatched { + t.Fatalf("after a report from another address: %+v, refused %+v", window.Report, window.Refused) + } + if code := call(http.MethodPost, "/report/"+key, good, "192.0.2.70:1"); code != http.StatusOK { + t.Fatalf("the report from the Machine's address = %d", code) + } + if window := e.window(t, "op-address"); window.Report == nil || window.Report.Image != "sha256:1" { + t.Fatalf("the Machine's report was not taken: %+v", window) + } +} diff --git a/internal/site/redfishwork/mediaserver.go b/internal/site/redfishwork/mediaserver.go index 1482124e..58773bf4 100644 --- a/internal/site/redfishwork/mediaserver.go +++ b/internal/site/redfishwork/mediaserver.go @@ -82,7 +82,10 @@ type Window struct { ConfigMedium []byte `json:"configMedium,omitempty"` // ReportFrom is where the installed OS's report may come from, as the // media service sees it. A report from any other address is refused. - ReportFrom []string `json:"reportFrom"` + ReportFrom []string `json:"reportFrom"` + // ReportAddress is the Machine's IPAM address, inside ReportFrom: the + // only source the window takes a report from. + ReportAddress string `json:"reportAddress"` Opened time.Time `json:"opened"` FetchExpires time.Time `json:"fetchExpires"` ReportExpires time.Time `json:"reportExpires"` @@ -94,8 +97,23 @@ type Window struct { // a missing token, or after the window ended. Duplicates int `json:"duplicates,omitempty"` Rejected int `json:"rejected,omitempty"` + // Refused records the first reports refused for coming from inside the + // site's ranges but not from the Machine's address, and whether each + // carried the window's token. The token itself is never kept. + Refused []RefusedReport `json:"refused,omitempty"` +} + +// RefusedReport is a report from inside the site's ranges but not from the +// window's report address. +type RefusedReport struct { + From string `json:"from"` + TokenMatched bool `json:"tokenMatched"` + At time.Time `json:"at"` } +// maxRefused bounds the refused reports a window records. +const maxRefused = 16 + // ReceivedReport is an install report the media service took. type ReceivedReport struct { Image string `json:"image"` @@ -103,6 +121,9 @@ type ReceivedReport struct { // Downloads are what the installer reports it downloaded. Downloads []ReportedDownload `json:"downloads,omitempty"` ReceivedAt time.Time `json:"receivedAt"` + // From is the address the report came from: the window's report + // address. + From string `json:"from"` } // ReportedDownload is one artifact the installer downloaded, by the digest @@ -254,6 +275,9 @@ type OpenRequest struct { ReportExpires time.Time `json:"reportExpires"` // ReportFrom is the IPv4 or IPv6 prefixes the report may come from. ReportFrom []string `json:"reportFrom"` + // ReportAddress is the Machine's address inside them, the only source + // the report is taken from. + ReportAddress string `json:"reportAddress"` } // ErrMediaStale means the media service refused to open a window because @@ -434,14 +458,14 @@ func (m *MediaServer) open(w http.ResponseWriter, request *http.Request, key str decoder.DisallowUnknownFields() if err := decoder.Decode(&open); err != nil || key != Key(open.Operation) || open.Device == "" || open.Fence < 1 || len(open.ConfigMedium) == 0 || len(open.ConfigMedium) > configMediumSize || len(open.CapabilitySHA256) != 64 || len(open.TokenSHA256) != 64 || len(open.BootDigest) != 64 || - !m.now().Before(open.FetchExpires) || open.ReportExpires.Before(open.FetchExpires) || !validPrefixes(open.ReportFrom) { + !m.now().Before(open.FetchExpires) || open.ReportExpires.Before(open.FetchExpires) || !validPrefixes(open.ReportFrom) || !insidePrefixes(open.ReportAddress, open.ReportFrom) { http.Error(w, "invalid window", http.StatusBadRequest) return } m.mu.Lock() defer m.mu.Unlock() window := Window{Device: open.Device, Operation: open.Operation, Fence: open.Fence, BootDigest: open.BootDigest, CapabilitySHA256: open.CapabilitySHA256, TokenSHA256: open.TokenSHA256, - ReportFrom: open.ReportFrom} + ReportFrom: open.ReportFrom, ReportAddress: open.ReportAddress} if current, err := m.current(request.Context(), window); err != nil { http.Error(w, "custody unreadable", http.StatusServiceUnavailable) return @@ -588,25 +612,53 @@ func validPrefixes(prefixes []string) bool { return len(prefixes) > 0 } -// fromAny reports whether the request's source address is in one of the -// prefixes. -func fromAny(request *http.Request, prefixes []string) bool { +// insidePrefixes reports whether address is one host address, without a +// zone, in one of the prefixes. +func insidePrefixes(address string, prefixes []string) bool { + parsed, err := netip.ParseAddr(address) + if err != nil || parsed.Zone() != "" || parsed.String() != address { + return false + } + for _, value := range prefixes { + if prefix, err := netip.ParsePrefix(value); err == nil && prefix.Contains(parsed) { + return true + } + } + return false +} + +// source is the request's source address, as the service sees it. +func source(request *http.Request) (netip.Addr, bool) { host, _, err := net.SplitHostPort(request.RemoteAddr) if err != nil { - return false + return netip.Addr{}, false } address, err := netip.ParseAddr(host) - if err != nil { + return address.Unmap(), err == nil +} + +// fromAny reports whether the request's source address is in one of the +// prefixes. +func fromAny(request *http.Request, prefixes []string) bool { + address, ok := source(request) + if !ok { return false } for _, value := range prefixes { - if prefix, err := netip.ParsePrefix(value); err == nil && prefix.Contains(address.Unmap()) { + if prefix, err := netip.ParsePrefix(value); err == nil && prefix.Contains(address) { return true } } return false } +// fromAddress reports whether the request comes from exactly the address. +func fromAddress(request *http.Request, address string) bool { + from, ok := source(request) + want, err := netip.ParseAddr(address) + return ok && err == nil && from == want.Unmap() +} + // report takes one install report per window: it must carry the window's // token, arrive before the report deadline, and come while custody still // names the operation. A refused or repeated report is counted, never @@ -642,6 +694,17 @@ func (m *MediaServer) report(w http.ResponseWriter, request *http.Request, key s // came from, whatever token it carries. outcome, code = "rejected-source", http.StatusForbidden window.Rejected++ + case !fromAddress(request, window.ReportAddress): + // The site's ranges are only the outer bound: within them, only the + // Machine's own address may report, so another server that learned + // the token still cannot post this report. + outcome, code = "rejected-address", http.StatusForbidden + window.Rejected++ + if len(window.Refused) < maxRefused { + from, _ := source(request) + matched := decodeErr == nil && len(report.Token) == 64 && subtle.ConstantTimeCompare([]byte(digest(report.Token)), []byte(window.TokenSHA256)) == 1 + window.Refused = append(window.Refused, RefusedReport{From: from.String(), TokenMatched: matched, At: m.now().UTC()}) + } case decodeErr != nil || len(report.Token) != 64 || subtle.ConstantTimeCompare([]byte(digest(report.Token)), []byte(window.TokenSHA256)) != 1: outcome, code = "rejected-token", http.StatusForbidden window.Rejected++ @@ -658,7 +721,8 @@ func (m *MediaServer) report(w http.ResponseWriter, request *http.Request, key s outcome, code = "duplicate", http.StatusConflict window.Duplicates++ default: - window.Report = &ReceivedReport{Image: report.Image, Bootstrap: report.Bootstrap, Downloads: report.Downloads, ReceivedAt: m.now().UTC()} + from, _ := source(request) + window.Report = &ReceivedReport{Image: report.Image, Bootstrap: report.Bootstrap, Downloads: report.Downloads, ReceivedAt: m.now().UTC(), From: from.String()} } if err := m.save(key, window); err != nil { http.Error(w, "state unwritable", http.StatusInternalServerError) diff --git a/internal/site/redfishwork/proxy.go b/internal/site/redfishwork/proxy.go new file mode 100644 index 00000000..d19ca37b --- /dev/null +++ b/internal/site/redfishwork/proxy.go @@ -0,0 +1,112 @@ +package redfishwork + +import ( + "errors" + "fmt" + "net" + "net/netip" + "slices" + "strconv" + "strings" + "time" +) + +// maxProxyHeader is the longest PROXY protocol version 1 header. +const maxProxyHeader = 107 + +// ProxyListener accepts connections that a trusted relay or load balancer +// opens on behalf of installed servers, each starting with a PROXY protocol +// version 1 header that names the server's own address. A connection's +// remote address is the one the header names, so the media service checks a +// report's source even when the path to it does not keep source addresses. +// It drops any connection from outside Trusted, and any whose header is +// missing or malformed, before TLS starts. +type ProxyListener struct { + net.Listener + // Trusted are the relays' own addresses. Only they may name a source. + Trusted []netip.Prefix + // OnDrop, when set, is told why a connection was dropped. + OnDrop func(error) +} + +// Accept returns the next connection with a valid header from a trusted +// peer, dropping the others. +func (l ProxyListener) Accept() (net.Conn, error) { + for { + conn, err := l.Listener.Accept() + if err != nil { + return nil, err + } + source, err := l.header(conn) + if err == nil { + return proxied{Conn: conn, source: source}, nil + } + _ = conn.Close() + if l.OnDrop != nil { + l.OnDrop(err) + } + } +} + +// header checks the peer and reads exactly one header line, so the TLS +// handshake that follows reads nothing of it. +func (l ProxyListener) header(conn net.Conn) (net.Addr, error) { + peer, err := netip.ParseAddrPort(conn.RemoteAddr().String()) + if err != nil || !slices.ContainsFunc(l.Trusted, func(prefix netip.Prefix) bool { return prefix.Contains(peer.Addr().Unmap()) }) { + return nil, errors.New("a PROXY connection came from outside the trusted relays") + } + if err := conn.SetReadDeadline(time.Now().Add(5 * time.Second)); err != nil { + return nil, err + } + line := make([]byte, 0, maxProxyHeader) + one := make([]byte, 1) + for len(line) < maxProxyHeader && !strings.HasSuffix(string(line), "\r\n") { + if _, err := conn.Read(one); err != nil { + return nil, errors.New("a PROXY connection sent no complete header") + } + line = append(line, one[0]) + } + if err := conn.SetReadDeadline(time.Time{}); err != nil { + return nil, err + } + return ParseProxyHeader(string(line)) +} + +// ParseProxyHeader reads a PROXY protocol version 1 header for TCP over IPv4 +// or IPv6 and returns its source address and port. +func ParseProxyHeader(line string) (net.Addr, error) { + fields := strings.Split(strings.TrimSuffix(line, "\r\n"), " ") + if !strings.HasSuffix(line, "\r\n") || len(fields) != 6 || fields[0] != "PROXY" || (fields[1] != "TCP4" && fields[1] != "TCP6") { + return nil, errors.New("a PROXY header is not TCP4 or TCP6 version 1") + } + source, sourceErr := netip.ParseAddr(fields[2]) + destination, destinationErr := netip.ParseAddr(fields[3]) + port, portErr := strconv.ParseUint(fields[4], 10, 16) + _, destinationPortErr := strconv.ParseUint(fields[5], 10, 16) + if sourceErr != nil || destinationErr != nil || portErr != nil || destinationPortErr != nil || source.Zone() != "" || + source.Is4() != (fields[1] == "TCP4") || destination.Is4() != (fields[1] == "TCP4") { + return nil, errors.New("a PROXY header names no valid addresses and ports") + } + return net.TCPAddrFromAddrPort(netip.AddrPortFrom(source, uint16(port))), nil +} + +// ProxyHeader is the PROXY protocol version 1 header a relay sends for a +// connection from source to destination. +func ProxyHeader(source, destination netip.AddrPort) string { + family := "TCP6" + if source.Addr().Unmap().Is4() && destination.Addr().Unmap().Is4() { + family = "TCP4" + source = netip.AddrPortFrom(source.Addr().Unmap(), source.Port()) + destination = netip.AddrPortFrom(destination.Addr().Unmap(), destination.Port()) + } + return fmt.Sprintf("PROXY %s %s %s %d %d\r\n", family, source.Addr(), destination.Addr(), source.Port(), destination.Port()) +} + +// proxied is a relayed connection whose remote address is the one its +// header named. +type proxied struct { + net.Conn + source net.Addr +} + +func (p proxied) RemoteAddr() net.Addr { return p.source } diff --git a/internal/site/redfishwork/proxy_test.go b/internal/site/redfishwork/proxy_test.go new file mode 100644 index 00000000..325e7fef --- /dev/null +++ b/internal/site/redfishwork/proxy_test.go @@ -0,0 +1,87 @@ +package redfishwork + +import ( + "io" + "net" + "net/netip" + "testing" + "time" +) + +func TestParseProxyHeader(t *testing.T) { + for line, want := range map[string]string{ + "PROXY TCP4 192.0.2.70 192.0.2.1 40000 28443\r\n": "192.0.2.70:40000", + "PROXY TCP6 2001:db8::70 2001:db8::1 40000 28443\r\n": "[2001:db8::70]:40000", + } { + if got, err := ParseProxyHeader(line); err != nil || got.String() != want { + t.Errorf("%q = %v, %v", line, got, err) + } + } + for _, line := range []string{ + "PROXY TCP4 192.0.2.70 192.0.2.1 40000 28443\n", + "PROXY UNKNOWN\r\n", + "PROXY TCP4 2001:db8::70 192.0.2.1 40000 28443\r\n", + "PROXY TCP4 192.0.2.70 192.0.2.1 70000 28443\r\n", + "PROXY TCP4 192.0.2.70 192.0.2.1 40000\r\n", + "GET / HTTP/1.1\r\n", + } { + if _, err := ParseProxyHeader(line); err == nil { + t.Errorf("%q was accepted", line) + } + } + header := ProxyHeader(netip.MustParseAddrPort("192.0.2.70:40000"), netip.MustParseAddrPort("192.0.2.1:28443")) + if got, err := ParseProxyHeader(header); err != nil || got.String() != "192.0.2.70:40000" { + t.Fatalf("a relay's header %q = %v, %v", header, got, err) + } +} + +// TestTheProxyListenerTrustsOnlyItsRelays takes the source a trusted relay +// names, leaves the rest of the stream to TLS, and drops a connection from +// any other peer or without a valid header. +func TestTheProxyListenerTrustsOnlyItsRelays(t *testing.T) { + listen := func(trusted string) (ProxyListener, chan error) { + inner, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { inner.Close() }) + dropped := make(chan error, 4) + return ProxyListener{Listener: inner, Trusted: []netip.Prefix{netip.MustParsePrefix(trusted)}, OnDrop: func(err error) { dropped <- err }}, dropped + } + send := func(listener ProxyListener, data string) { + conn, err := net.Dial("tcp", listener.Addr().String()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { conn.Close() }) + if _, err := io.WriteString(conn, data); err != nil { + t.Fatal(err) + } + } + + relayed, _ := listen("127.0.0.0/8") + send(relayed, "PROXY TCP4 192.0.2.70 192.0.2.1 40000 28443\r\nhello") + conn, err := relayed.Accept() + if err != nil { + t.Fatal(err) + } + defer conn.Close() + rest := make([]byte, 5) + if _, err := io.ReadFull(conn, rest); err != nil || conn.RemoteAddr().String() != "192.0.2.70:40000" || string(rest) != "hello" { + t.Fatalf("relayed connection from %v read %q, %v", conn.RemoteAddr(), rest, err) + } + + for name, c := range map[string]struct{ trusted, data string }{ + "an untrusted peer": {"198.51.100.0/24", "PROXY TCP4 192.0.2.70 192.0.2.1 40000 28443\r\n"}, + "no header": {"127.0.0.0/8", "GET / HTTP/1.1\r\n"}, + } { + listener, dropped := listen(c.trusted) + send(listener, c.data) + go func() { _, _ = listener.Accept() }() + select { + case <-dropped: + case <-time.After(10 * time.Second): + t.Fatalf("%s was not dropped", name) + } + } +} From 39207e85934e9322dfb89d6531318e0444a0bfb1 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Fri, 27 Nov 2026 16:22:03 -0600 Subject: [PATCH 08/35] test(lab): Report from each guest's IPAM address The lab's path from guests to the workstation rewrites their addresses, so the media service could not tell one guest's report from another's. - The virtual media suite runs IPAM, so each install claims its report address from the lab pool. - Guests post to a relay on the lab bridge, the one address they reach besides the boot Service. It names each guest's address to the service's relay listener in a PROXY header. - The installed OS adds its IPAM address beside its lease and reports from it. A lab BMC fault has it post the right token from another lab address first. - The suite requires that report refused and recorded, the next one taken from the claimed address, and loopback reports refused as outside the site's ranges. Co-Authored-By: Claude Opus 5.5 --- cmd/fleet-multiplane/main.go | 29 ++++++- config/site/redfish/graph/kustomization.yaml | 10 ++- .../site/redfish/services/kustomization.yaml | 21 ++++- docs/operations/redfish-lab.md | 8 +- hack/local-vm/boot | 22 ++++-- hack/local-vm/init | 9 +++ hack/local-vm/site-runtime | 11 +-- hack/multiplane/acceptance-media.sh | 6 +- hack/multiplane/flux.py | 7 +- hack/multiplane/media-central.sh | 6 +- hack/multiplane/media_steps.py | 53 +++++++++++-- hack/multiplane/milo.py | 18 ++--- hack/multiplane/redfish_steps.py | 4 +- hack/multiplane/run.sh | 10 ++- hack/multiplane/test-redfish.py | 2 +- hack/multiplane/topology.sh | 5 +- hack/redfish-lab/fleet_lab_adapter.py | 24 ++++++ hack/redfish-lab/test_adapter.py | 7 ++ internal/multiplane/media.go | 56 ++++++++++---- internal/multiplane/relay.go | 76 +++++++++++++++++++ 20 files changed, 317 insertions(+), 67 deletions(-) create mode 100644 internal/multiplane/relay.go diff --git a/cmd/fleet-multiplane/main.go b/cmd/fleet-multiplane/main.go index 8b727c5d..83014060 100644 --- a/cmd/fleet-multiplane/main.go +++ b/cmd/fleet-multiplane/main.go @@ -60,6 +60,9 @@ func run() error { mediaRoot := fs.String("state-dir", "", "the media service's own state directory (media-service)") mediaArtifacts := fs.String("artifacts", "", "directory of the image's pinned artifacts (media-service)") mediaClients := fs.String("clients", "", "comma-separated IPv4 prefixes the media service serves (media-service)") + proxyListen := fs.String("proxy-listen", "", "comma-separated addresses where report relays connect with a PROXY header (media-service)") + relays := fs.String("relays", "", "comma-separated prefixes of the report relays trusted to name a report's source (media-service)") + upstream := fs.String("upstream", "", "the media service's PROXY listener, IP:port (report-relay)") clientCA := fs.String("client-ca", "", "CA that signs the site workers' client certificates (media-service)") if err := fs.Parse(os.Args[2:]); err != nil { return err @@ -98,7 +101,7 @@ func run() error { if err != nil { return err } - var clients []netip.Prefix + var clients, trusted []netip.Prefix for _, value := range strings.Split(*mediaClients, ",") { prefix, err := netip.ParsePrefix(strings.TrimSpace(value)) if err != nil { @@ -106,13 +109,35 @@ func run() error { } clients = append(clients, prefix.Masked()) } + for _, value := range strings.Split(*relays, ",") { + if value = strings.TrimSpace(value); value == "" { + continue + } + prefix, err := netip.ParsePrefix(value) + if err != nil { + return fmt.Errorf("media-service: -relays must list prefixes") + } + trusted = append(trusted, prefix.Masked()) + } + if *proxyListen != "" && len(trusted) == 0 { + return fmt.Errorf("media-service: -proxy-listen needs -relays") + } if *mediaRoot == "" || *mediaArtifacts == "" || *tlsCert == "" || *tlsKey == "" || *clientCA == "" { return fmt.Errorf("media-service needs -state-dir, -artifacts, -tls-cert, -tls-key and -client-ca") } ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) defer cancel() fmt.Println("media-service: central media service running") - return multiplane.MediaService(ctx, config, *listen, *tlsCert, *tlsKey, *clientCA, *mediaRoot, *mediaArtifacts, clients) + return multiplane.MediaService(ctx, config, *listen, *proxyListen, *tlsCert, *tlsKey, *clientCA, *mediaRoot, *mediaArtifacts, clients, trusted) + case "report-relay": + // Lab only: forwards the guests' report connections, naming each + // guest's address, to the media service's PROXY listener. + if *upstream == "" { + return fmt.Errorf("report-relay needs -listen and -upstream") + } + ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) + defer cancel() + return multiplane.ReportRelay(ctx, *listen, *upstream) case "site-worker", "site-observer": default: return fmt.Errorf("unknown command") diff --git a/config/site/redfish/graph/kustomization.yaml b/config/site/redfish/graph/kustomization.yaml index 40eff4c6..d39e1cdd 100644 --- a/config/site/redfish/graph/kustomization.yaml +++ b/config/site/redfish/graph/kustomization.yaml @@ -40,9 +40,13 @@ patches: # which the worker gets through a per-operation Role of its own. - {name: FLEET_SITE_WORKER_IDENTITY_NAMESPACE, value: fleet-site-worker-identity} # Where the media service sees this site's installed servers post - # their first-boot reports from: the lab network reaches it through - # the runtime's host gateway, which arrives on loopback. - - {name: FLEET_MEDIA_REPORT_FROM, value: 127.0.0.1/32} + # their first-boot reports from: the lab network, named by the + # runtime's report relay. Each install reports from its own IPAM + # address inside it. + - {name: FLEET_MEDIA_REPORT_FROM, value: 192.168.77.0/24} + # How installed servers reach the media service: the relay on the + # lab bridge. + - {name: FLEET_MEDIA_REPORT_ORIGIN, value: "https://192.168.77.1:28443"} - op: replace path: /spec/resources/9/template/spec/template/spec/containers/0/volumeMounts value: diff --git a/config/site/redfish/services/kustomization.yaml b/config/site/redfish/services/kustomization.yaml index 0ef27b10..52ae0236 100644 --- a/config/site/redfish/services/kustomization.yaml +++ b/config/site/redfish/services/kustomization.yaml @@ -19,15 +19,30 @@ patches: - name: libvirt env: - {name: FLEET_SITE_PROVIDER, value: redfish} - # The central media service's report endpoint, the one - # address lab guests may reach besides the boot Service. - - {name: FLEET_MEDIA_REPORT, value: "192.168.5.2:28443"} volumeMounts: - {name: state, mountPath: /var/lib/fleet-lab/disks, subPath: lab-disks} - {name: state, mountPath: /var/lib/fleet-lab-console, subPath: lab-console} # The lab BMC's fetched virtual media, attached to guests # as CD-ROMs at the path the BMC wrote them. - {name: state, mountPath: /var/lib/fleet-lab-media, subPath: lab-media, readOnly: true} + # Lab guests post their first-boot reports to this relay on the + # lab bridge, the one address they reach besides the boot + # Service. The path to the workstation's central media service + # rewrites their addresses, so the relay names each guest's own + # address in a PROXY header on the service's relay listener. + - name: report-relay + image: "${FLEET_SITE_IMAGE}" + imagePullPolicy: IfNotPresent + command: [fleet-multiplane, report-relay, --listen, "192.168.77.1:28443", --upstream, "192.168.5.2:28444"] + securityContext: + runAsUser: 65534 + runAsNonRoot: true + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: {drop: [ALL]} + resources: + requests: {cpu: 10m, memory: 16Mi} + limits: {memory: 64Mi} - target: {kind: Deployment, name: fleet-site-boot} patch: |- apiVersion: apps/v1 diff --git a/docs/operations/redfish-lab.md b/docs/operations/redfish-lab.md index 0f3c8885..d4f9898c 100644 --- a/docs/operations/redfish-lab.md +++ b/docs/operations/redfish-lab.md @@ -589,12 +589,12 @@ uses 5 and 10 minutes. | Site declaration | Real, with one simplification: the coordinator's site configuration declares each site's methods in preference order. The Metal provider selects from the same declaration. | | Admission | Real for the site and qualification checks, the settling-hold rule, input consistency and digest-pinned downloads. A machine class cannot restrict methods yet. | | Qualification | Stubbed. Staff set the `fleet.datumapis.com/qualified-delivery-methods` annotation on the Device. A Device without it is qualified for network boot only. Commissioning will replace it. | -| Central media service | Real windows, fences from custody, media, report endpoint, transfer records and a background sweep that drops config media no window can serve. The sweep skips and counts a window file it cannot read, and goes on. In the lab it runs on the workstation beside the coordinator, on loopback, which lab Pods and guests reach through the runtime's host gateway. | +| Central media service | Real windows, fences from custody, media, report endpoint, transfer records and a background sweep that drops config media no window can serve. The sweep skips and counts a window file it cannot read, and goes on. In the lab it runs on the workstation beside the coordinator, on loopback, which lab Pods reach through the runtime's host gateway. Guests reach it through the report relay. | | Worker authentication | Real. Each site worker presents a client certificate from the site workers' CA. The certificate is its own Secret, `fleet-site-worker-media`, one per site worker identity, in the `fleet-site-worker-identity` namespace. Each worker gets exactly that Secret through a per-operation Role, and BMC credential Secrets hold only BMC credentials. Only virtual media reads it: network boot installs and wipes neither read nor need it. The service refuses every window operation from a client with no certificate, or one that is not the worker for that Device's site. | | BMC | Real Redfish VirtualMedia on the lab emulator: two CD devices, insert over verified HTTPS, eject, readback, one-time boot from CD. | | First-boot report | Real. The installed lab OS posts it over HTTPS. Bootstrap data is always empty because the sealed store is not on this branch; admission still refuses bootstrap data. | | Installer downloads | Admission refuses any download that is not pinned by digest. The config medium lists the pinned downloads, and the first-boot report names each download by the digest the installer fetched. The worker refuses a report whose downloads are not exactly the recorded ones. The lab installer fetches nothing; it reports what its config medium lists. | -| Report source | Each window records where its first-boot report may come from, and the media service refuses a report from any other address. In the lab every report reaches the service through the runtime's host gateway on IPv4 loopback, so the lab checks this with a report sent over IPv6 loopback. Restricting reports to the Machine's own address needs a real site network. | +| Report source | Real. Each virtual media installation records the Machine's address, which IPAM bound to the operation's own claim. The media service takes the report only from that address, and only inside the site's report ranges; a report from another address in the ranges is refused and recorded, token or not. The path from lab guests to the workstation rewrites their addresses, so guests post to a relay on the lab bridge, which names each guest's address to the service's relay listener in a PROXY protocol header. The service trusts that header only from its configured relays. The installed OS adds its IPAM address beside its DHCP lease and reports from it. A real site network, where the Machine's data network serves that address, still needs verifying. | | BMCs that do not verify HTTPS | Stubbed. Staff record `fleet.datumapis.com/virtual-media-tls: Unverified`, and admission refuses virtual media for that server. The fallback that mounts only the public medium and fetches bootstrap data with a single-use token is not implemented. | | Lab data network | The lab provisioning network stands in for the customer's data network. Its firewall lets guests reach the boot Service and the central media service's report endpoint, and nothing else. | | Addresses | `DataNetwork` only: the config medium carries no address and Fleet assigns none. `Static` needs NSO interface claims, which are not on this branch. | @@ -615,10 +615,10 @@ it pulled that reference, installed, and booted the installed disk. | `media-not-offered` | While the cell declares network boot only, a virtual media installation is refused with `DeliveryMethodNotOffered`. The fence does not change and nothing is delivered. | | `media-central`, `media-offer` | The central media service starts with the image's pinned artifacts. The operator adds virtual media after network boot; staff record target A as qualified for virtual media only. | | `media-unpinned` | An installation whose installer downloads an image by tag is refused with `InstallDownloadUnpinned`. | -| `media-arm-corrupt-token`, `media-install-held`, `media-held-report` | The lab BMC's config medium carries another report token. The installed OS's report is refused, as are a report with no token, one with another token, and one from an address that is not the Machine's, posted while the window is open. No report is taken, and the installation ends `OutcomeUnknown` at its report deadline with a hold that records virtual media. | +| `media-arm-corrupt-token`, `media-install-held`, `media-held-report` | The lab BMC's config medium carries another report token. The installed OS's report, from its IPAM address, is refused for its token. Reports posted straight to the service, over IPv4 and IPv6 loopback, come from outside the site's report ranges and are refused for their source. No report is taken, and the installation ends `OutcomeUnknown` at its report deadline with a hold that records virtual media. | | `media-arm-add-download`, `media-install-download`, `media-held-download` | The next installation settles that hold with the held method. The lab BMC adds a download the operation never pinned to its config medium; the first-boot report names it, so the report is never verified and the installation is held. | | `media-arm-lost-eject`, `media-install-lost`, `media-held-eject` | The next installation settles that hold with the held method. Its report is taken, then the BMC withholds an eject response past the client timeout: `OutcomeUnknown`, release never journaled. | -| `media-install` | A fourth installation settles the third hold, succeeds, and clears it. | +| `media-arm-stray-source`, `media-install`, `media-stray-address` | A fourth installation settles the third hold, succeeds, and clears it. Its config medium makes the installed OS post its report, with the right token, from another address in the site's ranges first. The media service refuses and records that report, then takes the one from the address IPAM bound to the installation's claim. | | `media-release-proof` | The BMC reads back both devices empty and no override. The media service reports four windows, none open, no transfer in progress and no reused token, and denies each one live. No config medium is kept anywhere. | | `media-stale-fence` | For each of the four operations, the media service refuses a window open with no client certificate (401), with another site's worker certificate (403), and as the cell's worker once custody no longer names the operation (409). The site store refuses a media window and step below the stored fence. | | `media-evidence` | Each taken report carries its operation's digests; target A booted media then disk four times; the console carries no token; target B was never touched. Writes `virtual-media.json`. | diff --git a/hack/local-vm/boot b/hack/local-vm/boot index d2f20c82..7c8c41dd 100644 --- a/hack/local-vm/boot +++ b/hack/local-vm/boot @@ -7,8 +7,9 @@ if grep -Eq '^/dev/vda1 / ext4 ' /proc/mounts && test -s /fleet-receipt; then printf 'FLEET-DISK-BOOT:%s\n' "$(cat /fleet-receipt)" fi # A virtual media install: at first boot the installed OS brings up its -# data network over DHCP and posts its install report over HTTPS, verifying -# the media service. The console shows only the outcome. +# data network over DHCP, takes its IPAM address beside the lease, and posts +# its install report from that address over HTTPS, verifying the media +# service. The console shows only the outcome. if grep -Eq '^/dev/vda1 / ext4 ' /proc/mounts && test -s /fleet-report/token; then mount -t sysfs sys /sys 2>/dev/null || true mount -t devtmpfs devtmpfs /dev 2>/dev/null || true @@ -20,9 +21,20 @@ if grep -Eq '^/dev/vda1 / ext4 ' /proc/mounts && test -s /fleet-report/token; th /bin/busybox udhcpc -i "$iface" -n -q -t 20 -s /fleet-dhcp >/dev/null 2>&1 downloads=$(/bin/busybox awk 'BEGIN{ORS=""} {if (NR>1) print ","; printf "{\"name\":\"%s\",\"digest\":\"%s\"}", $1, $2}' /fleet-report/downloads 2>/dev/null) body=$(printf '{"token":"%s","image":"%s","bootstrap":"%s","downloads":[%s]}' "$(cat /fleet-report/token)" "$(cat /fleet-report/image)" "$(cat /fleet-report/bootstrap)" "$downloads") - printf 'fleet: data network %s\n' "$(/bin/busybox ip -4 -o addr show dev "$iface" 2>&1 | /bin/busybox awk '{print $4}')" - status=$(curl -sS -o /dev/null -w '%{http_code}' --max-time 60 --retry 5 --retry-all-errors --cacert /fleet-report/ca.pem -H 'Content-Type: application/json' --data "$body" "$(cat /fleet-report/url)" 2>/run/curl.err || true) - printf 'fleet: first-boot report HTTP %s %s\n' "$status" "$(head -c 200 /run/curl.err)" + address=$(cat /fleet-report/address) + /bin/busybox ip addr add "$address/32" dev "$iface" + printf 'fleet: data network %s\n' "$(/bin/busybox ip -4 -o addr show dev "$iface" 2>&1 | /bin/busybox awk '{print $4}' | tr '\n' ' ')" + post() { curl -sS -o /dev/null -w '%{http_code}' --interface "$1" --max-time 60 --retry 5 --retry-all-errors --cacert /fleet-report/ca.pem -H 'Content-Type: application/json' --data "$body" "$(cat /fleet-report/url)" 2>/run/curl.err || true; } + # Lab fault: another server in the site's ranges posts this report, token + # and all, first. The media service must refuse it for its address. + if test -s /fleet-report/stray; then + stray=$(cat /fleet-report/stray) + /bin/busybox ip addr add "$stray/32" dev "$iface" + printf 'fleet: stray report from %s HTTP %s\n' "$stray" "$(post "$stray")" + /bin/busybox ip addr del "$stray/32" dev "$iface" + fi + status=$(post "$address") + printf 'fleet: first-boot report from %s HTTP %s %s\n' "$address" "$status" "$(head -c 200 /run/curl.err)" fi sync /bin/busybox poweroff -f diff --git a/hack/local-vm/init b/hack/local-vm/init index 1662f93f..3fccbdca 100644 --- a/hack/local-vm/init +++ b/hack/local-vm/init @@ -42,6 +42,13 @@ if [ "$delivery" = media ]; then grep -qx 'addresses=DataNetwork' /fleet-config || /bin/busybox poweroff -f value bootstrap | base64 -d > /fleet-bootstrap report=$(value report) + # The Machine's IPAM address, the only one the media service takes this + # install's report from. A lab fault may add a stray address, inside the + # site's ranges but not the Machine's, for one report with the right token. + address=$(value reportaddress) + stray=$(value straysource) + case "$address" in *[!0-9.]*|'') /bin/busybox poweroff -f ;; esac + case "$stray" in *[!0-9.]*) /bin/busybox poweroff -f ;; esac # The downloads the config medium pins, one "name digest" per line. This # lab image fetches nothing; it reports each one by the digest its # reference pins, as an installer that pulled it would. @@ -122,6 +129,8 @@ if [ "$delivery" = media ]; then printf '%s' "$report" > /target/fleet-report/url value reportca | base64 -d > /target/fleet-report/ca.pem cp /fleet-downloads /target/fleet-report/downloads + printf '%s' "$address" > /target/fleet-report/address + [ -z "$stray" ] || printf '%s' "$stray" > /target/fleet-report/stray else printf '%s\n' "$receipt" > /target/fleet-receipt fi diff --git a/hack/local-vm/site-runtime b/hack/local-vm/site-runtime index ff828f49..5efb8f1e 100755 --- a/hack/local-vm/site-runtime +++ b/hack/local-vm/site-runtime @@ -22,14 +22,9 @@ iptables -t mangle -N FLEET-PXE 2>/dev/null || iptables -t mangle -F FLEET-PXE iptables -t mangle -A FLEET-PXE -m addrtype --dst-type LOCAL -j RETURN iptables -t mangle -A FLEET-PXE -m addrtype --dst-type BROADCAST -j RETURN iptables -t mangle -A FLEET-PXE -d "$boot_ip" -p tcp --dport 8080 -j RETURN -# A virtual media install's OS posts its first-boot report from this lab -# network, which stands in for the data network: it may reach the central -# media service's report endpoint, IPv4:port, and nothing more. -if [ -n "${FLEET_MEDIA_REPORT:-}" ]; then - report_ip=${FLEET_MEDIA_REPORT%:*} report_port=${FLEET_MEDIA_REPORT##*:} - case "$report_ip:$report_port" in *[!0-9.:]*|:*|*:) echo 'invalid media report endpoint' >&2; exit 1 ;; esac - iptables -t mangle -A FLEET-PXE -d "$report_ip" -p tcp --dport "$report_port" -j RETURN -fi +# A virtual media install's OS posts its first-boot report to the lab's +# report relay, on this namespace's bridge address, which the first rule +# above already admits. iptables -t mangle -A FLEET-PXE -j DROP iptables -t mangle -C PREROUTING -i fleetpxe0 -j FLEET-PXE 2>/dev/null || iptables -t mangle -A PREROUTING -i fleetpxe0 -j FLEET-PXE if [ "${FLEET_SITE_PROVIDER:-libvirt}" = redfish ]; then diff --git a/hack/multiplane/acceptance-media.sh b/hack/multiplane/acceptance-media.sh index 19f005cb..292267cf 100755 --- a/hack/multiplane/acceptance-media.sh +++ b/hack/multiplane/acceptance-media.sh @@ -42,8 +42,12 @@ md held-download 300 md arm-lost-eject 120 run media-install-lost 3000 md held-eject 300 -# The fourth install settles that hold, proves release and clears it. +# The fourth install settles that hold, proves release and clears it. Its OS +# first posts the right token from another address in the site's ranges, +# which is refused; only its IPAM address may report. +md arm-stray-source 120 run media-install 3000 +md stray-address 300 md release-proof 300 md stale-fence 120 md evidence 600 diff --git a/hack/multiplane/flux.py b/hack/multiplane/flux.py index a6814f7b..da9e783e 100644 --- a/hack/multiplane/flux.py +++ b/hack/multiplane/flux.py @@ -107,6 +107,9 @@ LAB_DHCP = os.environ.get('FLEET_LAB_DHCP', 'static') if LAB_DHCP not in ('static', 'synced') or (LAB_DHCP == 'synced' and PROVIDER != 'redfish'): raise SystemExit('FLEET_LAB_DHCP=synced needs the Redfish provider') +# IPAM runs with synchronized DHCP, and in the virtual media suite for each +# install's report address (run.sh sets FLEET_LAB_IPAM). +LAB_IPAM = LAB_DHCP == 'synced' or os.environ.get('FLEET_LAB_IPAM') == '1' SYNCED_OBJECTS = ['fleet-site_fleet-site-dhcp-base__ConfigMap', 'fleet-site_fleet-site-dhcp-feed__Service', 'fleet-site_fleet-site-redfish-enrollment__ConfigMap'] if LAB_DHCP == 'synced' else [] if LAB_DHCP == 'synced': SHARED.update({('configmaps', SITE, 'fleet-site-dhcp-base'): 'fleet-site-services', ('services', SITE, 'fleet-site-dhcp-feed'): 'fleet-site-services', @@ -128,7 +131,7 @@ '_ipam-apiserver:system:auth-delegator_rbac.authorization.k8s.io_ClusterRoleBinding', 'ipam-system_ipam-apiserver__Service', 'ipam-system_ipam-apiserver_apps_Deployment', 'ipam-system_ipam-apiserver_policy_PodDisruptionBudget', 'ipam-system_ipam-apiserver_networking.k8s.io_NetworkPolicy']), -} if LAB_DHCP == 'synced' else {} +} if LAB_IPAM else {} EXPECTED['platform'] += list(PLATFORM_LAYER_INVENTORY) LAYER_INVENTORY = { 'flux-system/fleet-site-services': sorted(['fleet-site_fleet-site-boot__Service', 'fleet-site_fleet-site-worker-policy__ConfigMap', @@ -293,7 +296,7 @@ def stage(args): data = {'FLEET_CELL': env['cell'], 'FLEET_CELL_ENDPOINT': env['cellEndpoint'], 'FLEET_SOURCE_MARKER': marker} maps = [] patches = [] - if cluster == 'platform' and LAB_DHCP == 'synced': + if cluster == 'platform' and LAB_IPAM: resources.insert(2, '../../config/multiplane/clusters/platform-ipam') if cluster == 'hub': # Karmada-API Kustomizations live beside their kubeconfig Secret. diff --git a/hack/multiplane/media-central.sh b/hack/multiplane/media-central.sh index 27f5c115..ba8491e4 100755 --- a/hack/multiplane/media-central.sh +++ b/hack/multiplane/media-central.sh @@ -1,8 +1,9 @@ #!/usr/bin/env bash # Start or stop this run's central media service: the workstation process, # beside the coordinator, that serves virtual media to the lab BMC and takes -# first-boot reports. It listens on loopback only; lab Pods and guests reach -# it through the runtime's host gateway. It reads custody with the +# first-boot reports. It listens on loopback only; lab Pods reach it through +# the runtime's host gateway, and guests' reports through the runtime's +# report relay, which names each guest's address on the relay listener. It reads custody with the # coordinator's identity, keeps its own state, and logs to the private state # directory. start extracts the image's pinned artifacts from the site # image, the same bytes the site serves for network boot. @@ -26,6 +27,7 @@ case $action in fi mkdir -p "$state/media-central" && chmod 0700 "$state/media-central" nohup "$state/fleet-multiplane-host" media-service --config "$state/acceptance.json" --listen "127.0.0.1:28443,[::1]:28443" \ + --proxy-listen 127.0.0.1:28444 --relays 127.0.0.0/8 \ --tls-cert "$state/redfish/media-tls.crt" --tls-key "$state/redfish/media-tls.key" --client-ca "$state/redfish/media-worker-ca.crt" \ --state-dir "$state/media-central" --artifacts "$artifacts" --clients 127.0.0.0/8,::1/128 >>"$state/media-central.log" 2>&1 "$pidfile" diff --git a/hack/multiplane/media_steps.py b/hack/multiplane/media_steps.py index db02a7f6..10263357 100644 --- a/hack/multiplane/media_steps.py +++ b/hack/multiplane/media_steps.py @@ -26,6 +26,13 @@ withholds its response past the worker's client timeout held-eject the third install's report was taken, then the eject response was lost: OutcomeUnknown, release never journaled + arm-stray-source one-shot: the lab BMC's next config medium makes the + installed OS post its report, with the right token, from + another address inside the site's ranges first + stray-address the fourth install recorded its IPAM-bound report address; + the media service refused and recorded the right token + from the stray address, then took the report from the + Machine's address release-proof after the settling install: the BMC reads back both devices empty and no override, the media service reports no open window, transfer or reused token for the Device, @@ -55,6 +62,9 @@ SYSTEM = 'System-1' DEVICE_NAME = harness.DEVICE.split('/')[1] QUALIFIED = 'fleet.datumapis.com/qualified-delivery-methods' +# Another address on the lab network, inside the site's report ranges and +# outside IPAM's pool and the static leases: another server's. +STRAY_SOURCE = '192.168.77.250' STORE_ROOT = '/var/lib/fleet-local/site' LOCAL = 'https://127.0.0.1:%d' % rf.MEDIA_PORT # The lab's virtual media phases, shorter than the 15 and 30 minute @@ -160,6 +170,34 @@ def arm_add_download(s): print('media-arm-add-download: target A\'s next config medium will list a download the operation never pinned') +def arm_stray_source(s): + arm('stray-source', SYSTEM, STRAY_SOURCE) + print('media-arm-stray-source: target A\'s next config medium makes its installed OS post its report, with the right token, from %s first' % STRAY_SOURCE) + + +def stray_address(s): + op = media_installs(s)[-1] + uid = op['metadata']['uid'] + address = (op['spec']['delivery'].get('reportAddress') or {}) + w = window_record(s, uid) + claim = json.loads(provider(s, '-n', 'fleet-provider', 'get', 'ipclaims.ipam.miloapis.com', address.get('addressClaim', {}).get('name', '-'), '-o', 'json').stdout) + bound = (claim.get('status') or {}).get('address', '').split('/')[0] + if not address.get('address') or bound != address['address'] or not address['address'].startswith('192.168.77.'): + die('the install records no IPAM-bound report address: %s, claim holds %r' % (address, bound)) + refused = w.get('refused') or [] + if [(r['from'], r['tokenMatched']) for r in refused] != [(STRAY_SOURCE, True)]: + die('the media service did not refuse, and record, the right token from %s: %s' % (STRAY_SOURCE, refused)) + if not w.get('report') or w['report'].get('from') != address['address']: + die('the media service took no report from the Machine\'s address %s: %s' % (address['address'], w.get('report'))) + if 'rejected-address' not in outcomes(s, uid) or len(media_effects(rf.audit(s), 'add-stray-source')) != 1: + die('the stray-source fault did not fire exactly once, or no report was refused for its address') + console = [l for l in read_console(s) if l.startswith('fleet: stray report') or l.startswith('fleet: first-boot report from')] + rf.write(s / 'media-stray-address.json', {'operation': op['metadata']['name'], 'reportAddress': address, 'claimBound': bound, 'refused': refused, + 'reportFrom': w['report']['from'], 'consoleDiagnostics': console}) + print('media-stray-address: %s reports only from its IPAM address %s (claim %s); the right token from %s, inside the site\'s ranges, was refused and recorded; ' + 'the report from %s was taken' % (op['metadata']['name'], address['address'], address['addressClaim']['name'], STRAY_SOURCE, address['address'])) + + def arm_lost_eject(s): arm(s, 'drop-eject', SYSTEM, 'CD1', '45') print('media-arm-lost-eject: target A\'s next CD1 eject is applied and its response withheld for 45s, past the 30s client timeout') @@ -190,11 +228,11 @@ def held_report(s): op = ops[0] uid = op['metadata']['uid'] w = window_record(s, uid) - if w.get('report') or w.get('duplicates') or w.get('rejected', 0) < 4: - die('the media service took a report or refused fewer than four: %s' % {k: w.get(k) for k in ('report', 'duplicates', 'rejected')}) + if w.get('report') or w.get('duplicates') or w.get('rejected', 0) < 3: + die('the media service took a report or refused fewer than three: %s' % {k: w.get(k) for k in ('report', 'duplicates', 'rejected')}) stray = json.loads((s / 'media-stray-reports.json').read_text()) - if stray['answers'] != {'missing-token': 403, 'other-token': 403, 'other-address': 403} or 'rejected-source' not in outcomes(s, uid): - die('the stray reports were not all refused, or none was refused for its address: %s %s' % (stray['answers'], outcomes(s, uid))) + if stray['answers'] != {'outside-ranges-ipv4': 403, 'outside-ranges-ipv6': 403} or not {'rejected-source', 'rejected-token'} <= set(outcomes(s, uid)): + die('the stray reports were not all refused for their source, or the guest\'s report was not refused for its token: %s %s' % (stray['answers'], outcomes(s, uid))) steps = steps_of(s, uid) for step in ('media-window', 'media-insert-boot', 'media-insert-config', 'media-installer-power-on', 'media-installer-done', 'disk-power-on'): if steps.get(step) != 'Done': @@ -214,7 +252,7 @@ def held_report(s): rf.write(s / 'media-held-report.json', {'operation': op['metadata']['name'], 'fence': op['status']['fence'], 'reason': op['status'].get('reason'), 'mediaService': {'report': None, 'rejected': w['rejected'], 'outcomes': outcomes(s, uid)}, 'strayReports': stray['answers'], 'steps': steps, 'consoleDiagnostics': diagnostics}) - print('media-held-report: %s booted from media; its OS posted a report with another token (refused); stray reports with no token, another token, and from an address that is not the Machine\'s were refused (%s); ' + print('media-held-report: %s booted from media; its OS posted a report with another token from its IPAM address (refused); stray reports from outside the site\'s report ranges were refused (%s); ' 'the media service took no report (%d refused); OutcomeUnknown (%s) at the report deadline' % (op['metadata']['name'], stray['answers'], w['rejected'], op['status'].get('reason'))) @@ -393,7 +431,8 @@ def first(block): record = {'observedAt': now(), 'device': harness.DEVICE, 'operations': reports, 'qemuStarts': starts, 'bmcEffects': mutations, 'firstBootConsole': [l for l in console if l.startswith('fleet:')], 'offer': json.loads((s / 'evidence' / 'media-offer.json').read_text()), 'heldReport': json.loads((s / 'media-held-report.json').read_text()), - 'heldDownload': json.loads((s / 'media-held-download.json').read_text()), 'heldEject': json.loads((s / 'media-held-eject.json').read_text()), 'release': json.loads((s / 'media-release.json').read_text()), + 'heldDownload': json.loads((s / 'media-held-download.json').read_text()), 'heldEject': json.loads((s / 'media-held-eject.json').read_text()), + 'strayAddress': json.loads((s / 'media-stray-address.json').read_text()), 'release': json.loads((s / 'media-release.json').read_text()), 'staleFence': json.loads((s / 'media-stale.json').read_text())} # Target B, served by the same BMC, was never touched. base = json.loads((s / 'redfish-baseline.json').read_text()) @@ -426,5 +465,5 @@ def first(block): if __name__ == '__main__': step, state = sys.argv[1], pathlib.Path(sys.argv[2]) {'offer': offer, 'arm-corrupt-token': arm_corrupt_token, 'held-report': held_report, 'arm-add-download': arm_add_download, 'held-download': held_download, - 'arm-lost-eject': arm_lost_eject, 'held-eject': held_eject, + 'arm-lost-eject': arm_lost_eject, 'held-eject': held_eject, 'arm-stray-source': arm_stray_source, 'stray-address': stray_address, 'release-proof': release_proof, 'stale-fence': stale_fence, 'evidence': evidence}[step](state) diff --git a/hack/multiplane/milo.py b/hack/multiplane/milo.py index e092338b..a654ecc7 100755 --- a/hack/multiplane/milo.py +++ b/hack/multiplane/milo.py @@ -14,7 +14,7 @@ components each get their own token: the Metal provider (management), the custody coordinator, the release controller and fixture discovery. A staff token creates recoveries. -- in synchronized lab DHCP mode (FLEET_LAB_DHCP=synced), IPAM's credentials +- with IPAM (synchronized lab DHCP or the virtual media suite), IPAM's credentials (its Milo token, serving key and database password), the APIService that aggregates IPAM into the provider API, and the boot address class and pool inside the provider project. @@ -27,7 +27,7 @@ if not a.prefix.startswith('fleet-mp-'):raise SystemExit('task-owned fleet-mp- prefix required') os.environ['DOCKER_CONTEXT']=os.environ.get('FLEET_MULTIPLANE_DOCKER_CONTEXT','colima-fleet-acceptance-tcg') platform=root/'platform-admin.yaml' -synced=os.environ.get('FLEET_LAB_DHCP')=='synced' +with_ipam=os.environ.get('FLEET_LAB_DHCP')=='synced' or os.environ.get('FLEET_LAB_IPAM')=='1' ports=json.loads((root/'platform-ports.json').read_text()) def run(*args,**kw):return subprocess.run(args,check=True,text=True,**kw) def kubectl(config,*args,**kw):return run('kubectl','--kubeconfig',str(config),'--request-timeout=15s',*args,**kw) @@ -105,7 +105,7 @@ def ipam(d,config): # password and the DSN IPAM reads, its serving key (whose certificate is the # APIService caBundle), its kubeconfig for the provider Milo API, and Milo's # front-proxy CA in the control-plane-ca ConfigMap IPAM's manifests mount. -if synced: +if with_ipam: i=root/'ipam';pd=root/'provider' if not i.exists(): i.mkdir(mode=0o700) @@ -124,9 +124,9 @@ def ipam(d,config): enroll('ipam-system','configmap','control-plane-ca',f'--from-file=ca.crt={pd/"front-proxy-ca.crt"}') print('ipam: credentials enrolled (not in the source)',flush=True) # 2. Flux must report each Milo Kustomization Ready (Deployment and etcd -# healthy), and in synced mode IPAM's: PostgreSQL, then the apiserver, which is +# healthy), and with IPAM, IPAM's: PostgreSQL, then the apiserver, which is # Ready only once its delegated authentication has read the provider API. -layers=['milo-'+r for r in roles]+(['ipam-system','ipam-apiserver'] if synced else []) +layers=['milo-'+r for r in roles]+(['ipam-system','ipam-apiserver'] if with_ipam else []) for layer in layers: kubectl(platform,'-n','flux-system','annotate','--overwrite','kustomization',layer,'reconcile.fluxcd.io/requestedAt='+str(time.time()),stdout=subprocess.DEVNULL) for layer in layers: @@ -177,7 +177,7 @@ def ipam(d,config): # release controller reads custody to keep a held operation's claim. claims={'apiGroups':['ipam.miloapis.com'],'resources':['ipclaims'],'verbs':['get','list','create','delete']} allocations={'apiGroups':['ipam.miloapis.com'],'resources':['ipallocations'],'verbs':['get','list']} - if synced:rules+=[claims,allocations] + if with_ipam:rules+=[claims,allocations] # The coordinator rules mirror config/components/device-operations/roles/ # coordinator.yaml: it lists and settles every registered operation kind. components={ @@ -185,8 +185,8 @@ def ipam(d,config): {'apiGroups':['fleet.datumapis.com'],'resources':['deviceinstallations','devicewipes','devicepoweroperations','devicerecoveries','devicecommissionings'],'verbs':['get','list','watch','delete']}, {'apiGroups':['fleet.datumapis.com'],'resources':['deviceinstallations/status','devicewipes/status','devicepoweroperations/status','devicerecoveries/status','devicecommissionings/status'],'verbs':['get','update']}, {'apiGroups':['fleet.datumapis.com'],'resources':['devicecommissioningplans','devicecommissioningplanapprovals'],'verbs':['get','list','watch']}, - {'apiGroups':['metal.datumapis.com'],'resources':['machineallocations'],'verbs':['get','list','watch']}]+([{'apiGroups':['ipam.miloapis.com'],'resources':['ipclaims'],'verbs':['get']}] if synced else []), - 'release':[{'apiGroups':['fleet.datumapis.com'],'resources':['devicewipes'],'verbs':['get','create']}]+([claims,allocations,{'apiGroups':['fleet.datumapis.com'],'resources':['devicecustodies'],'verbs':['get']}] if synced else []), + {'apiGroups':['metal.datumapis.com'],'resources':['machineallocations'],'verbs':['get','list','watch']}]+([{'apiGroups':['ipam.miloapis.com'],'resources':['ipclaims'],'verbs':['get']}] if with_ipam else []), + 'release':[{'apiGroups':['fleet.datumapis.com'],'resources':['devicewipes'],'verbs':['get','create']}]+([claims,allocations,{'apiGroups':['fleet.datumapis.com'],'resources':['devicecustodies'],'verbs':['get']}] if with_ipam else []), # The capacity projector is the only writer of capacity status. 'projector':[{'apiGroups':['metal.datumapis.com'],'resources':['machinecapacities'],'verbs':['get','list','watch']},{'apiGroups':['metal.datumapis.com'],'resources':['machinecapacities/status'],'verbs':['get','update']}, {'apiGroups':['fleet.datumapis.com'],'resources':['devices','devicecustodies','devicecommissionings','devicecommissioningplans','devicecommissioningplanapprovals'],'verbs':['get','list','watch']}], @@ -204,7 +204,7 @@ def ipam(d,config): for who,component in components.items(): apply(d/'bootstrap.json',{'apiVersion':'rbac.authorization.k8s.io/v1','kind':'ClusterRole','metadata':{'name':'fleet-'+who},'rules':component}) apply(d/'bootstrap.json',{'apiVersion':'rbac.authorization.k8s.io/v1','kind':'ClusterRoleBinding','metadata':{'name':'fleet-'+who},'roleRef':{'apiGroup':'rbac.authorization.k8s.io','kind':'ClusterRole','name':'fleet-'+who},'subjects':[{'kind':'User','name':who}]}) - if synced:ipam(d,config) + if with_ipam:ipam(d,config) if role!='provider':rules += [{'apiGroups':['metal.datumapis.com'],'resources':['machines'],'verbs':['update']},{'apiGroups':['metal.datumapis.com'],'resources':['machines/status','installations/status'],'verbs':['update','patch']}] apply(d/'bootstrap.json',{'apiVersion':'rbac.authorization.k8s.io/v1','kind':'ClusterRole','metadata':{'name':'fleet-management'},'rules':rules}) apply(d/'bootstrap.json',{'apiVersion':'rbac.authorization.k8s.io/v1','kind':'ClusterRoleBinding','metadata':{'name':'fleet-management'},'roleRef':{'apiGroup':'rbac.authorization.k8s.io','kind':'ClusterRole','name':'fleet-management'},'subjects':[{'kind':'User','name':'management'}]}) diff --git a/hack/multiplane/redfish_steps.py b/hack/multiplane/redfish_steps.py index 131e6cf1..b4260248 100644 --- a/hack/multiplane/redfish_steps.py +++ b/hack/multiplane/redfish_steps.py @@ -52,6 +52,8 @@ # The workstation as lab Pods and guests reach it (the Colima host gateway), # where the central media service listens on loopback. MEDIA_HOST = '192.168.5.2' +# The report relay on the lab bridge, where guests post their reports. +REPORT_RELAY = '192.168.77.1' MEDIA_PORT = 28443 @@ -187,7 +189,7 @@ def enroll(s): # gateway. The lab BMC, the workers and the installed OS verify it # against this certificate. subprocess.run(['openssl', 'req', '-x509', '-newkey', 'ec', '-pkeyopt', 'ec_paramgen_curve:prime256v1', '-nodes', '-keyout', str(d / 'media-tls.key'), - '-out', str(d / 'media-tls.crt'), '-days', '2', '-subj', '/CN=fleet-lab-media', '-addext', 'subjectAltName=IP:%s,IP:127.0.0.1,IP:::1' % MEDIA_HOST], + '-out', str(d / 'media-tls.crt'), '-days', '2', '-subj', '/CN=fleet-lab-media', '-addext', 'subjectAltName=IP:%s,IP:%s,IP:127.0.0.1,IP:::1' % (MEDIA_HOST, REPORT_RELAY)], check=True, capture_output=True) # Site workers authenticate to the central media service with client # certificates from a CA generated per run: the cell's workers, and one diff --git a/hack/multiplane/run.sh b/hack/multiplane/run.sh index c36672e9..74647fef 100755 --- a/hack/multiplane/run.sh +++ b/hack/multiplane/run.sh @@ -34,6 +34,10 @@ for arg in "$@"; do done [[ $lab_dhcp == static || $provider == redfish ]] || usage [[ $media == 0 || ($provider == redfish && $lab_dhcp == static) ]] || usage +# IPAM runs with synchronized DHCP, for boot addresses, and in the virtual +# media suite, for each install's report address. +lab_ipam=0 +[[ $lab_dhcp == static && $media == 0 ]] || lab_ipam=1 # Run parameters (docs/operations/multiplane.md#ci-mode). The defaults are the # task-owned Colima profile: arm64 runtime, TCG guest. Preflight validates them # before any resource exists. @@ -41,7 +45,7 @@ export FLEET_MULTIPLANE_RUNTIME=${FLEET_MULTIPLANE_RUNTIME:-colima} FLEET_MULTIP export FLEET_MULTIPLANE_ARCH=${FLEET_MULTIPLANE_ARCH:-arm64} FLEET_MULTIPLANE_ACCEL=${FLEET_MULTIPLANE_ACCEL:-tcg} # Scenario group: all by default; CI shards each suite into flux and release. export FLEET_MULTIPLANE_GROUP=${FLEET_MULTIPLANE_GROUP:-all} -export DOCKER_CONTEXT=$FLEET_MULTIPLANE_DOCKER_CONTEXT KIND_EXPERIMENTAL_PROVIDER=docker FLEET_SITE_PROVIDER=$provider FLEET_LAB_DHCP=$lab_dhcp +export DOCKER_CONTEXT=$FLEET_MULTIPLANE_DOCKER_CONTEXT KIND_EXPERIMENTAL_PROVIDER=docker FLEET_SITE_PROVIDER=$provider FLEET_LAB_DHCP=$lab_dhcp FLEET_LAB_IPAM=$lab_ipam harness=(python3 hack/multiplane/harness.py) state=$(mktemp -d "${FLEET_MULTIPLANE_STATE_ROOT:-/tmp}/fleet-multiplane.XXXXXX") mkdir -m 0700 "$state/evidence" @@ -142,7 +146,7 @@ ph federation-enrollment 600 python3 hack/multiplane/roles.py "$state" # Redfish mode enrolls the per-Device BMC credentials and the lab BMC's TLS # key first: fixture discovery reports that key's digest. [[ $provider != redfish ]] || ph redfish-enroll 120 python3 hack/multiplane/redfish_steps.py enroll "$state" -python3 - "$state" "$provider" "$lab_dhcp" <<'PY' +python3 - "$state" "$provider" "$lab_ipam" <<'PY' import json,pathlib,sys s=pathlib.Path(sys.argv[1]).resolve() enrollment=json.loads((s/'redfish'/'fixture-enrollment.json').read_text() if sys.argv[2]=='redfish' else pathlib.Path('config/site/base/enrollment.json').read_text()) @@ -152,7 +156,7 @@ c={'State':str(s),'HubKubeconfig':str(s/'management-hub.json'),'Cell':(s/'prefix 'DeliveryMethods':[{'method':'NetworkBoot'}], # The central media service, as lab Pods and guests reach the workstation. 'MediaService':'https://192.168.5.2:28443'} -if sys.argv[3]=='synced':c['BootAddressClass']='lab-provisioning' +if sys.argv[3]=='1':c['BootAddressClass']='lab-provisioning' (s/'acceptance.json').write_text(json.dumps(c)) PY ph seed 600 "$state/fleet-multiplane-host" seed --config "$state/acceptance.json" diff --git a/hack/multiplane/test-redfish.py b/hack/multiplane/test-redfish.py index 61de0fd5..0323a582 100644 --- a/hack/multiplane/test-redfish.py +++ b/hack/multiplane/test-redfish.py @@ -117,7 +117,7 @@ def build(path): synced_deployments = {d['metadata']['name']: d for d in synced_services if d.get('kind') == 'Deployment'} pod = lambda n: synced_deployments.get(n, {}).get('spec', {}).get('template', {}).get('spec', {}) runtime_containers = {c['name']: c for c in pod('fleet-site-runtime').get('containers', [])} -check('synced runtime adds Kea and the synchronizer beside libvirt', sorted(runtime_containers) == ['dhcp-sync', 'kea', 'libvirt'], str(sorted(runtime_containers))) +check('synced runtime adds Kea and the synchronizer beside libvirt and the report relay', sorted(runtime_containers) == ['dhcp-sync', 'kea', 'libvirt', 'report-relay'], str(sorted(runtime_containers))) check('Kea and the synchronizer are not privileged and add only the network capabilities Kea needs', not any(runtime_containers.get(n, {}).get('securityContext', {}).get('privileged') for n in ('kea', 'dhcp-sync')) and runtime_containers.get('kea', {}).get('securityContext', {}).get('capabilities') == {'drop': ['ALL'], 'add': ['NET_BIND_SERVICE', 'NET_RAW']} diff --git a/hack/multiplane/topology.sh b/hack/multiplane/topology.sh index 41d508e4..81a293b9 100644 --- a/hack/multiplane/topology.sh +++ b/hack/multiplane/topology.sh @@ -39,9 +39,10 @@ nodes: - {containerPort: 30443, hostPort: @port:consumer-b@, listenAddress: 127.0.0.1} YAML kind_create "$prefix-platform" "$state/platform-kind.yaml.template" "$state/platform-ports.json" "$state/platform-admin.yaml" -# Synchronized lab DHCP adds IPAM and its PostgreSQL beside the Milo APIs. +# IPAM (synchronized DHCP or virtual media) adds its PostgreSQL beside the +# Milo APIs. platform_memory=2300m -[[ ${FLEET_LAB_DHCP:-static} != synced ]] || platform_memory=2800m +[[ ${FLEET_LAB_IPAM:-0} != 1 ]] || platform_memory=2800m docker update --memory "$platform_memory" --memory-swap "$platform_memory" --cpus 2 "$prefix-platform-control-plane" >/dev/null cat > "$state/hub-kind.yaml.template" <<'YAML' diff --git a/hack/redfish-lab/fleet_lab_adapter.py b/hack/redfish-lab/fleet_lab_adapter.py index e9f0eec3..490fb4ff 100755 --- a/hack/redfish-lab/fleet_lab_adapter.py +++ b/hack/redfish-lab/fleet_lab_adapter.py @@ -281,6 +281,24 @@ def corrupt_token(path): return True +def add_stray_source(path, address): + """Add a stray source to a config medium, in place, within its padded + size: the installed OS then posts its report, with the right token, from + that address first. Returns False for any other medium.""" + if not re.fullmatch(r'[0-9]{1,3}(\.[0-9]{1,3}){3}', address): + return False + with open(path, 'r+b') as f: + data = f.read() + if not data.startswith(b'FLEET-CONFIG-V1') or b'\nend\n' not in data: + return False + text = data.rstrip(b'\x00').replace(b'\nend\n', b'\nstraysource=' + address.encode() + b'\nend\n') + if len(text) > len(data): + return False + f.seek(0) + f.write(text.ljust(len(data), b'\x00')) + return True + + def add_download(path): """Add a download line the operation never pinned to a config medium, in place, within its padded size. Returns False for any other medium.""" @@ -532,6 +550,10 @@ def virtual_media(sid, dev, action): # Lab fault: the medium the BMC holds lists a download the # operation never pinned. request_context.detail['fault'] = 'add-config-download' + elif is_config(path) and (stray := take('straySource', lambda f: f.get('system') == sid)) and add_stray_source(path, stray['address']): + # Lab fault: another server in the site's ranges posts the + # report with the right token before the Machine does. + request_context.detail['fault'] = 'add-stray-source' with LOCK: lab.media[sid][dev] = {'Inserted': True, 'Image': url, 'file': path} lab.save() @@ -633,6 +655,8 @@ def fault_cli(args): faults.update(lambda v: v.setdefault('dropResponse', []).append({'system': args[1], 'resetType': args[2], 'seconds': int(args[3]), 'skip': skip})) elif args[:1] == ['drop-eject'] and len(args) == 4: faults.update(lambda v: v.setdefault('dropEject', []).append({'system': args[1], 'device': args[2], 'seconds': int(args[3])})) + elif args[:1] == ['stray-source'] and len(args) == 3: + faults.update(lambda v: v.setdefault('straySource', []).append({'system': args[1], 'address': args[2]})) elif args[:1] == ['add-download'] and len(args) == 2: faults.update(lambda v: v.setdefault('addDownload', []).append({'system': args[1]})) elif args[:1] == ['corrupt-config'] and len(args) == 2: diff --git a/hack/redfish-lab/test_adapter.py b/hack/redfish-lab/test_adapter.py index a98ff1e7..f9da6702 100644 --- a/hack/redfish-lab/test_adapter.py +++ b/hack/redfish-lab/test_adapter.py @@ -224,6 +224,13 @@ def config_fetch(url, path): self.assertIn(b'\ndownload=extension registry.example/extension@sha256:', held) self.assertTrue(held.endswith(b'\nend\n')) self.app.post(cd2['Actions']['#VirtualMedia.EjectMedia']['target'], headers=AUTH, json={}) + # A config medium can gain a stray report source. + adapter.fault_cli(['stray-source', 'System-1', '192.168.77.250']) + self.assertEqual(self.app.post(cd2['Actions']['#VirtualMedia.InsertMedia']['target'], headers=AUTH, json={'Image': url}).status_code, 204) + self.assertEqual(self.audit()[-1].get('fault'), 'add-stray-source') + held = (WORK / 'media' / 'fleet-lab-target-a-CD2.img').read_bytes().rstrip(b'\0') + self.assertTrue(held.endswith(b'\nstraysource=192.168.77.250\nend\n')) + self.app.post(cd2['Actions']['#VirtualMedia.EjectMedia']['target'], headers=AUTH, json={}) # A withheld eject response still ejects. adapter.fault_cli(['drop-eject', 'System-1', 'CD1', '0']) eject = cd1['Actions']['#VirtualMedia.EjectMedia']['target'] diff --git a/internal/multiplane/media.go b/internal/multiplane/media.go index 65d8c41e..a41edd23 100644 --- a/internal/multiplane/media.go +++ b/internal/multiplane/media.go @@ -7,6 +7,7 @@ import ( "encoding/json" "errors" "fmt" + "net" "net/http" "net/netip" "os" @@ -147,7 +148,7 @@ func (r *Runner) mediaInstallation(ctx context.Context, name string) (*request, if err != nil { return nil, nil, nil, err } - if operation.Spec.Delivery.Method != ops.DeliveryVirtualMedia || operation.Spec.BootNetwork != nil { + if operation.Spec.Delivery.Method != ops.DeliveryVirtualMedia || operation.Spec.BootNetwork != nil || operation.Spec.Delivery.ReportAddress == nil { return nil, nil, nil, fmt.Errorf("%w: the Metal provider selected %+v", errTerminal, operation.Spec.Delivery) } return q, install, operation, nil @@ -250,12 +251,13 @@ func (r *Runner) strayReports(ctx context.Context, operation *ops.DeviceInstalla return errors.New("the report window is not open yet") } answers := map[string]int{} - // The installed servers' reports reach the service on IPv4 loopback; a - // report over IPv6 loopback comes from another address. + // The installed servers' reports reach the service through the report + // relay, from the lab network. A report straight to the service, over + // IPv4 or IPv6 loopback, comes from outside the site's report ranges. + body := `{"token":"` + strings.Repeat("e", 64) + `"}` posts := map[string]struct{ origin, body string }{ - "missing-token": {origin, `{"image":"sha256:` + strings.Repeat("0", 64) + `"}`}, - "other-token": {origin, `{"token":"` + strings.Repeat("e", 64) + `"}`}, - "other-address": {"https://[::1]:28443", `{"token":"` + strings.Repeat("e", 64) + `"}`}, + "outside-ranges-ipv4": {origin, body}, + "outside-ranges-ipv6": {"https://[::1]:28443", body}, } for label, post := range posts { response, err := client.Post(redfishwork.ReportURL(post.origin, key), "application/json", strings.NewReader(post.body)) @@ -306,7 +308,7 @@ func (r *Runner) MediaInstall(ctx context.Context) error { if err := q.project.API.Status().Update(ctx, m); err != nil { return err } - fmt.Printf("media-install: %s succeeded at fence %d over virtual media and settled the hold\n", operation.Name, operation.Status.Fence) + fmt.Printf("media-install: %s succeeded at fence %d over virtual media, reporting from its IPAM address %s, and settled the hold\n", operation.Name, operation.Status.Fence, operation.Spec.Delivery.ReportAddress.Address) return nil } @@ -342,7 +344,7 @@ func WorkerIdentity(cell string) string { return "fleet-site-worker:" + cell } // certificates from clientCA; a worker of the configured cell may act only // on the Devices that cell is enrolled to serve. It serves over TLS on // listen until ctx ends, and sweeps stale config media every half minute. -func MediaService(ctx context.Context, c Config, listen, certFile, keyFile, clientCA, root, artifacts string, clients []netip.Prefix) error { +func MediaService(ctx context.Context, c Config, listen, proxyListen, certFile, keyFile, clientCA, root, artifacts string, clients, relays []netip.Prefix) error { api, err := API(filepath.Join(c.State, "provider", "coordinator-project.json")) if err != nil { return err @@ -369,14 +371,40 @@ func MediaService(ctx context.Context, c Config, listen, certFile, keyFile, clie // requires one the client CA verified. // listen is a comma-separated list of addresses, such as loopback over // IPv4 and IPv6. - addresses := strings.Split(listen, ",") - errs := make(chan error, len(addresses)) + // proxyListen is where the report relays connect; each connection names + // the installed server's address in a PROXY header, trusted only from + // relays. + certificate, err := tls.LoadX509KeyPair(certFile, keyFile) + if err != nil { + return err + } + type endpoint struct { + address string + proxied bool + } + var endpoints []endpoint + for _, address := range strings.Split(listen, ",") { + endpoints = append(endpoints, endpoint{strings.TrimSpace(address), false}) + } + for _, address := range strings.Split(proxyListen, ",") { + if address = strings.TrimSpace(address); address != "" { + endpoints = append(endpoints, endpoint{address, true}) + } + } + errs := make(chan error, len(endpoints)) var servers []*http.Server - for _, address := range addresses { - server := &http.Server{Addr: strings.TrimSpace(address), Handler: media.Handler(), ReadHeaderTimeout: 5 * time.Second, WriteTimeout: 30 * time.Minute, IdleTimeout: 5 * time.Second, - TLSConfig: &tls.Config{MinVersion: tls.VersionTLS12, ClientAuth: tls.VerifyClientCertIfGiven, ClientCAs: pool}} + for _, e := range endpoints { + config := &tls.Config{MinVersion: tls.VersionTLS12, ClientAuth: tls.VerifyClientCertIfGiven, ClientCAs: pool, Certificates: []tls.Certificate{certificate}} + server := &http.Server{Handler: media.Handler(), ReadHeaderTimeout: 5 * time.Second, WriteTimeout: 30 * time.Minute, IdleTimeout: 5 * time.Second} + listener, err := net.Listen("tcp", e.address) + if err != nil { + return err + } + if e.proxied { + listener = redfishwork.ProxyListener{Listener: listener, Trusted: relays, OnDrop: func(err error) { fmt.Fprintf(os.Stderr, "media-service: relay connection dropped: %v\n", err) }} + } servers = append(servers, server) - go func() { errs <- server.ListenAndServeTLS(certFile, keyFile) }() + go func() { errs <- server.Serve(tls.NewListener(listener, config)) }() } err = nil select { diff --git a/internal/multiplane/relay.go b/internal/multiplane/relay.go new file mode 100644 index 00000000..cf61c339 --- /dev/null +++ b/internal/multiplane/relay.go @@ -0,0 +1,76 @@ +package multiplane + +import ( + "context" + "fmt" + "io" + "net" + "net/netip" + "os" + "time" + + "go.datum.net/fleet/internal/site/redfishwork" +) + +// ReportRelay forwards installed servers' report connections from the lab +// network to the central media service's PROXY listener, naming each +// server's own address in a PROXY header. The lab's path from the guests to +// the workstation rewrites their addresses; through the relay the media +// service still sees each report's source. It listens once the lab bridge +// has its address, retrying until then. +func ReportRelay(ctx context.Context, listen, upstream string) error { + var listener net.Listener + for { + var err error + if listener, err = (&net.ListenConfig{}).Listen(ctx, "tcp", listen); err == nil { + break + } + select { + case <-ctx.Done(): + return nil + case <-time.After(time.Second): + } + } + go func() { <-ctx.Done(); _ = listener.Close() }() + fmt.Println("report-relay: listening") + for { + conn, err := listener.Accept() + if err != nil { + if ctx.Err() != nil { + return nil + } + return err + } + go relay(conn, upstream) + } +} + +func relay(conn net.Conn, upstream string) { + defer conn.Close() + source, sourceErr := netip.ParseAddrPort(conn.RemoteAddr().String()) + destination, destinationErr := netip.ParseAddrPort(conn.LocalAddr().String()) + if sourceErr != nil || destinationErr != nil { + return + } + out, err := net.DialTimeout("tcp", upstream, 10*time.Second) + if err != nil { + fmt.Fprintf(os.Stderr, "report-relay: upstream unreachable: %v\n", err) + return + } + defer out.Close() + if _, err := io.WriteString(out, redfishwork.ProxyHeader(source, destination)); err != nil { + return + } + done := make(chan struct{}, 2) + pipe := func(to, from net.Conn) { + _, _ = io.Copy(to, from) + if tcp, ok := to.(*net.TCPConn); ok { + _ = tcp.CloseWrite() + } + done <- struct{}{} + } + go pipe(out, conn) + go pipe(conn, out) + <-done + <-done +} From 77eaaaea2c6a61491f24901c9112d67b5a723514 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Fri, 27 Nov 2026 16:40:37 -0600 Subject: [PATCH 09/35] fix(multiplane): Give refused installs an address The lab's refused virtual media installations recorded no report address, so the API rejected them before admission could refuse them for their method or download. They now name an address and a claim nothing made; admission refuses them before it reads the claim. The PROXY listener reads each header on its own, so a slow relay delays only its own connection. The lab guide states what the lab's relay trust and shared bridge leave to a real site network. Co-Authored-By: Claude Opus 5.5 --- docs/operations/redfish-lab.md | 2 +- hack/multiplane/media-central.sh | 7 +-- internal/custody/delivery_test.go | 6 ++- internal/multiplane/media.go | 14 +++++- internal/multiplane/media_test.go | 26 ++++++++++ internal/site/redfishwork/proxy.go | 64 +++++++++++++++++-------- internal/site/redfishwork/proxy_test.go | 9 ++-- 7 files changed, 97 insertions(+), 31 deletions(-) create mode 100644 internal/multiplane/media_test.go diff --git a/docs/operations/redfish-lab.md b/docs/operations/redfish-lab.md index d4f9898c..bb828235 100644 --- a/docs/operations/redfish-lab.md +++ b/docs/operations/redfish-lab.md @@ -594,7 +594,7 @@ uses 5 and 10 minutes. | BMC | Real Redfish VirtualMedia on the lab emulator: two CD devices, insert over verified HTTPS, eject, readback, one-time boot from CD. | | First-boot report | Real. The installed lab OS posts it over HTTPS. Bootstrap data is always empty because the sealed store is not on this branch; admission still refuses bootstrap data. | | Installer downloads | Admission refuses any download that is not pinned by digest. The config medium lists the pinned downloads, and the first-boot report names each download by the digest the installer fetched. The worker refuses a report whose downloads are not exactly the recorded ones. The lab installer fetches nothing; it reports what its config medium lists. | -| Report source | Real. Each virtual media installation records the Machine's address, which IPAM bound to the operation's own claim. The media service takes the report only from that address, and only inside the site's report ranges; a report from another address in the ranges is refused and recorded, token or not. The path from lab guests to the workstation rewrites their addresses, so guests post to a relay on the lab bridge, which names each guest's address to the service's relay listener in a PROXY protocol header. The service trusts that header only from its configured relays. The installed OS adds its IPAM address beside its DHCP lease and reports from it. A real site network, where the Machine's data network serves that address, still needs verifying. | +| Report source | Real. Each virtual media installation records the Machine's address, which IPAM bound to the operation's own claim. The media service takes the report only from that address, and only inside the site's report ranges; a report from another address in the ranges is refused and recorded, token or not. The path from lab guests to the workstation rewrites their addresses, so guests post to a relay on the lab bridge, which names each guest's address to the service's relay listener in a PROXY protocol header. The service trusts that header only from its configured relays. The installed OS adds its IPAM address beside its DHCP lease and reports from it. The lab proves the service's check, not the network's binding: its relay set is all of loopback, because every lab Pod arrives there, so any lab Pod could name any source and only the report token stops it. Guests cannot reach the relay listener, but on the shared lab bridge a guest can take any lab address, as the stray-source fault does. A real site network, where only the relay or load balancer reaches the relay listener and the data network serves only the Machine its address, still needs verifying. | | BMCs that do not verify HTTPS | Stubbed. Staff record `fleet.datumapis.com/virtual-media-tls: Unverified`, and admission refuses virtual media for that server. The fallback that mounts only the public medium and fetches bootstrap data with a single-use token is not implemented. | | Lab data network | The lab provisioning network stands in for the customer's data network. Its firewall lets guests reach the boot Service and the central media service's report endpoint, and nothing else. | | Addresses | `DataNetwork` only: the config medium carries no address and Fleet assigns none. `Static` needs NSO interface claims, which are not on this branch. | diff --git a/hack/multiplane/media-central.sh b/hack/multiplane/media-central.sh index ba8491e4..7946a3d9 100755 --- a/hack/multiplane/media-central.sh +++ b/hack/multiplane/media-central.sh @@ -1,9 +1,10 @@ #!/usr/bin/env bash # Start or stop this run's central media service: the workstation process, # beside the coordinator, that serves virtual media to the lab BMC and takes -# first-boot reports. It listens on loopback only; lab Pods reach it through -# the runtime's host gateway, and guests' reports through the runtime's -# report relay, which names each guest's address on the relay listener. It reads custody with the +# first-boot reports. It listens on loopback only; lab Pods reach it +# through the runtime's host gateway, and guests' reports through the +# runtime's report relay, which names each guest's address on the relay +# listener. It reads custody with the # coordinator's identity, keeps its own state, and logs to the private state # directory. start extracts the image's pinned artifacts from the site # image, the same bytes the site serves for network boot. diff --git a/internal/custody/delivery_test.go b/internal/custody/delivery_test.go index a0d4ce0a..d9219903 100644 --- a/internal/custody/delivery_test.go +++ b/internal/custody/delivery_test.go @@ -123,7 +123,11 @@ func TestDeliveryMethodAdmission(t *testing.T) { }() device := held(e, "NetworkBoot,VirtualMedia") fence := e.custody(device.Name).Spec.Fence - operation := install(e, device, "request-1", virtualMedia, nil) + // As the lab's refused installation does, it names a claim nothing + // made: the method is refused before the claim is read. + unclaimed := virtualMedia + unclaimed.ReportAddress = &ops.BootNetworkInput{AddressClaim: bootaddress.Reference(bootaddress.ClaimName("never-claimed")), Address: "198.51.100.99"} + operation := install(e, device, "request-1", unclaimed, nil) e.settle(device.Name) e.requirePhase(operation, ops.PhaseFailed, ReasonDeliveryNotOffered) e.requireUntouched(device.Name, fence) diff --git a/internal/multiplane/media.go b/internal/multiplane/media.go index a41edd23..332a4517 100644 --- a/internal/multiplane/media.go +++ b/internal/multiplane/media.go @@ -24,6 +24,7 @@ import ( inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" ops "go.datum.net/fleet/internal/api/operations/v1alpha1" fleet "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/bootaddress" "go.datum.net/fleet/internal/custody" "go.datum.net/fleet/internal/redfish" "go.datum.net/fleet/internal/site/redfishwork" @@ -65,6 +66,15 @@ func (r *Runner) MediaUnpinned(ctx context.Context) error { return r.refusedInstallation(ctx, "00000000-0000-4000-8000-000000000228", r.Config.DeliveryMethods[index].Input(), downloads, custody.ReasonDownloadUnpinned) } +// unclaimedReportAddress gives a refused installation the report address +// every virtual media installation records, so the API takes it. It names +// a claim nothing made: admission refuses these installations for their +// method or download before it reads the claim. +func unclaimedReportAddress(delivery ops.DeliveryInput, operation string) ops.DeliveryInput { + delivery.ReportAddress = &ops.BootNetworkInput{AddressClaim: bootaddress.Reference(bootaddress.ClaimName(operation)), Address: "192.168.77.99"} + return delivery +} + // refusedInstallation creates an installation for consumer A's allocation // with a synthetic request UID, outside the Metal provider's selection, and // requires admission to refuse it for the reason with custody unchanged. @@ -103,7 +113,7 @@ func (r *Runner) refusedInstallation(ctx context.Context, request string, delive OperationEnvelope: ops.OperationEnvelope{Creator: r.Allocator.ProviderCreator, DeviceRef: ops.DeviceReference{Name: device.Name, UID: string(device.UID)}, Authority: ops.Authority{AllocationRef: &ops.LocalReference{Name: current.Name}}}, RequestUID: request, Image: image, BootInterface: "primary", TargetDisks: []string{"disk-0"}, - Delivery: delivery, + Delivery: unclaimedReportAddress(delivery, key.Name), }, } if err := r.Provider.API.Create(ctx, operation); err != nil { @@ -401,7 +411,7 @@ func MediaService(ctx context.Context, c Config, listen, proxyListen, certFile, return err } if e.proxied { - listener = redfishwork.ProxyListener{Listener: listener, Trusted: relays, OnDrop: func(err error) { fmt.Fprintf(os.Stderr, "media-service: relay connection dropped: %v\n", err) }} + listener = redfishwork.NewProxyListener(listener, relays, func(err error) { fmt.Fprintf(os.Stderr, "media-service: relay connection dropped: %v\n", err) }) } servers = append(servers, server) go func() { errs <- server.Serve(tls.NewListener(listener, config)) }() diff --git a/internal/multiplane/media_test.go b/internal/multiplane/media_test.go new file mode 100644 index 00000000..defba191 --- /dev/null +++ b/internal/multiplane/media_test.go @@ -0,0 +1,26 @@ +package multiplane + +import ( + "net/netip" + "testing" + + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + "go.datum.net/fleet/internal/bootaddress" + "go.datum.net/fleet/internal/custody" +) + +// TestARefusedInstallationRecordsAReportAddress gives the lab's refused +// installations the report address every virtual media installation must +// record, so the API takes them and admission refuses them for their method +// or download. +func TestARefusedInstallationRecordsAReportAddress(t *testing.T) { + offer := custody.OfferedMethod{Method: ops.DeliveryVirtualMedia, Addresses: ops.AddressesDataNetwork, MediaService: "https://192.0.2.10:28443"} + delivery := unclaimedReportAddress(offer.Input(), "alloc-example-install-1") + report := delivery.ReportAddress + if report == nil || report.AddressClaim != bootaddress.Reference(bootaddress.ClaimName("alloc-example-install-1")) { + t.Fatalf("report address = %+v", report) + } + if address, err := netip.ParseAddr(report.Address); err != nil || !netip.MustParsePrefix("192.168.77.0/24").Contains(address) { + t.Fatalf("report address %q is not a lab address", report.Address) + } +} diff --git a/internal/site/redfishwork/proxy.go b/internal/site/redfishwork/proxy.go index d19ca37b..9687449a 100644 --- a/internal/site/redfishwork/proxy.go +++ b/internal/site/redfishwork/proxy.go @@ -19,40 +19,64 @@ const maxProxyHeader = 107 // version 1 header that names the server's own address. A connection's // remote address is the one the header names, so the media service checks a // report's source even when the path to it does not keep source addresses. -// It drops any connection from outside Trusted, and any whose header is -// missing or malformed, before TLS starts. +// It drops any connection from outside trusted, and any whose header is +// missing or malformed, before TLS starts. Each header is read on its own, +// so a slow peer delays only its own connection. type ProxyListener struct { net.Listener - // Trusted are the relays' own addresses. Only they may name a source. - Trusted []netip.Prefix - // OnDrop, when set, is told why a connection was dropped. - OnDrop func(error) + trusted []netip.Prefix + onDrop func(error) + ready chan net.Conn + failed chan error } -// Accept returns the next connection with a valid header from a trusted -// peer, dropping the others. -func (l ProxyListener) Accept() (net.Conn, error) { +// NewProxyListener wraps a listener. trusted are the relays' own +// addresses; only they may name a source. onDrop, when set, is told why a +// connection was dropped. +func NewProxyListener(inner net.Listener, trusted []netip.Prefix, onDrop func(error)) *ProxyListener { + l := &ProxyListener{Listener: inner, trusted: trusted, onDrop: onDrop, ready: make(chan net.Conn), failed: make(chan error, 1)} + go l.accept() + return l +} + +func (l *ProxyListener) accept() { for { conn, err := l.Listener.Accept() if err != nil { - return nil, err - } - source, err := l.header(conn) - if err == nil { - return proxied{Conn: conn, source: source}, nil - } - _ = conn.Close() - if l.OnDrop != nil { - l.OnDrop(err) + l.failed <- err + return } + go func() { + source, err := l.header(conn) + if err != nil { + _ = conn.Close() + if l.onDrop != nil { + l.onDrop(err) + } + return + } + l.ready <- proxied{Conn: conn, source: source} + }() + } +} + +// Accept returns the next connection with a valid header from a trusted +// peer. +func (l *ProxyListener) Accept() (net.Conn, error) { + select { + case conn := <-l.ready: + return conn, nil + case err := <-l.failed: + l.failed <- err + return nil, err } } // header checks the peer and reads exactly one header line, so the TLS // handshake that follows reads nothing of it. -func (l ProxyListener) header(conn net.Conn) (net.Addr, error) { +func (l *ProxyListener) header(conn net.Conn) (net.Addr, error) { peer, err := netip.ParseAddrPort(conn.RemoteAddr().String()) - if err != nil || !slices.ContainsFunc(l.Trusted, func(prefix netip.Prefix) bool { return prefix.Contains(peer.Addr().Unmap()) }) { + if err != nil || !slices.ContainsFunc(l.trusted, func(prefix netip.Prefix) bool { return prefix.Contains(peer.Addr().Unmap()) }) { return nil, errors.New("a PROXY connection came from outside the trusted relays") } if err := conn.SetReadDeadline(time.Now().Add(5 * time.Second)); err != nil { diff --git a/internal/site/redfishwork/proxy_test.go b/internal/site/redfishwork/proxy_test.go index 325e7fef..eca97b0f 100644 --- a/internal/site/redfishwork/proxy_test.go +++ b/internal/site/redfishwork/proxy_test.go @@ -39,16 +39,16 @@ func TestParseProxyHeader(t *testing.T) { // names, leaves the rest of the stream to TLS, and drops a connection from // any other peer or without a valid header. func TestTheProxyListenerTrustsOnlyItsRelays(t *testing.T) { - listen := func(trusted string) (ProxyListener, chan error) { + listen := func(trusted string) (*ProxyListener, chan error) { inner, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { t.Fatal(err) } t.Cleanup(func() { inner.Close() }) dropped := make(chan error, 4) - return ProxyListener{Listener: inner, Trusted: []netip.Prefix{netip.MustParsePrefix(trusted)}, OnDrop: func(err error) { dropped <- err }}, dropped + return NewProxyListener(inner, []netip.Prefix{netip.MustParsePrefix(trusted)}, func(err error) { dropped <- err }), dropped } - send := func(listener ProxyListener, data string) { + send := func(listener *ProxyListener, data string) { conn, err := net.Dial("tcp", listener.Addr().String()) if err != nil { t.Fatal(err) @@ -60,6 +60,8 @@ func TestTheProxyListenerTrustsOnlyItsRelays(t *testing.T) { } relayed, _ := listen("127.0.0.0/8") + // A trusted peer that sends nothing does not hold up the next one. + send(relayed, "") send(relayed, "PROXY TCP4 192.0.2.70 192.0.2.1 40000 28443\r\nhello") conn, err := relayed.Accept() if err != nil { @@ -77,7 +79,6 @@ func TestTheProxyListenerTrustsOnlyItsRelays(t *testing.T) { } { listener, dropped := listen(c.trusted) send(listener, c.data) - go func() { _, _ = listener.Accept() }() select { case <-dropped: case <-time.After(10 * time.Second): From 13fd957399320ac12fb46f2ce08d851fcbdc0ccb Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Fri, 27 Nov 2026 17:43:34 -0600 Subject: [PATCH 10/35] fix(lab): Run IPAM in the media suite on CI The media suite is the first to run IPAM on a CI runner, and two steps that only synchronized DHCP had used failed there. - IPAM's first writes, its address class and pool, reach a fresh database through the provider API's aggregation and outlasted a 15-second request. They now retry with a 60-second bound and report the last refusal. - The Flux waits and the Flux evidence required every Kustomization at the pushed revision, but IPAM's apiserver layer applies IPAM's own published manifests. It is now held to their pinned digest. Co-Authored-By: Claude Opus 5.5 --- hack/multiplane/flux.py | 13 +++++++++++-- hack/multiplane/milo.py | 16 ++++++++++++++-- hack/multiplane/test-flux.py | 5 +++++ 3 files changed, 30 insertions(+), 4 deletions(-) diff --git a/hack/multiplane/flux.py b/hack/multiplane/flux.py index da9e783e..05f11378 100644 --- a/hack/multiplane/flux.py +++ b/hack/multiplane/flux.py @@ -437,6 +437,15 @@ def kustomizations(state, cluster): return {i['metadata']['namespace'] + '/' + i['metadata']['name']: i for i in kget(state, cluster, 'get', 'kustomizations.kustomize.toolkit.fluxcd.io', '-A')['items']} +def at_revision(name, applied, revision): + """Whether a Kustomization applied what this run expects: the pushed + revision, or for IPAM's apiserver layer, which reconciles IPAM's own + published manifests, their pinned digest.""" + if name == 'flux-system/ipam-apiserver': + return str(applied or '').endswith(IPAM_KUSTOMIZE_DIGEST) + return applied == revision + + def wait_cluster(state, cluster, timeout, names=None, revision=None, skip=(), observe_also=()): """All named (default: every) Kustomizations Ready, current generation, at the pushed revision. @@ -472,7 +481,7 @@ def wait_cluster(state, cluster, timeout, names=None, revision=None, skip=(), ob except SystemExit: pass # an unreachable cluster is sampled on the next poll if ready(source) and source.get('status', {}).get('lastHandledReconcileAt') == source_token and source.get('status', {}).get('artifact', {}).get('revision') == revision and all( - v['ready'] and v['revision'] == revision and v['requestedAt'] is not None and v['lastHandledReconcileAt'] == v['requestedAt'] for v in last.values()): + v['ready'] and at_revision(n, v['revision'], revision) and v['requestedAt'] is not None and v['lastHandledReconcileAt'] == v['requestedAt'] for n, v in last.items()): path = pathlib.Path(state) / 'evidence' / 'flux-reconciles.json' records = json.loads(path.read_text()) if path.exists() else [] records.append({'cluster': cluster, 'revision': revision, 'observedAt': now(), 'sourceRequestedAt': source_token, 'sourceLastHandledReconcileAt': source['status']['lastHandledReconcileAt'], 'kustomizations': last, @@ -687,7 +696,7 @@ def verify(args): problems.append('%s source at %s, pushed %s' % (cluster, src.get('artifactRevision'), rev['fluxRevision'])) for n in ['flux-system/fleet-cluster'] + EXPECTED[cluster] + (SITE_LAYERS if cluster == 'cell' else []): k = snap['kustomizations'].get(n) - if not k or ['Ready', 'True', 'ReconciliationSucceeded'] not in k['conditions'] or k['generation'] != k['observedGeneration'] or k['lastAppliedRevision'] != rev['fluxRevision']: + if not k or ['Ready', 'True', 'ReconciliationSucceeded'] not in k['conditions'] or k['generation'] != k['observedGeneration'] or not at_revision(n, k['lastAppliedRevision'], rev['fluxRevision']): problems.append('%s %s not Ready at the pushed revision: %s' % (cluster, n, k and (k['conditions'], k['lastAppliedRevision']))) for n in HELMRELEASES.get(cluster, []): h = snap['helmReleases'].get(n) diff --git a/hack/multiplane/milo.py b/hack/multiplane/milo.py index a654ecc7..fb00e5ae 100755 --- a/hack/multiplane/milo.py +++ b/hack/multiplane/milo.py @@ -58,9 +58,21 @@ def ipam(d,config): wait(lambda:subprocess.run(['kubectl','--kubeconfig',str(config),'--request-timeout=10s','get','ipclasses.ipam.miloapis.com'],capture_output=True).returncode==0,300,'IPAM is not served through the provider project') # Kea's base subnet is 192.168.77.0/24 and the bridge is .1: the pool # withholds .0-.99 and .200-.255, so IPAM hands out only .100-.199. - apply(config,{'apiVersion':'ipam.miloapis.com/v1alpha1','kind':'IPClass','metadata':{'name':'lab-provisioning'}, + def write(obj): + # IPAM's first writes reach its fresh database through the provider API's + # aggregation and may take longer than a request's usual bound; retry + # them, and say why the last was refused. + last='' + for _ in range(12): + r=subprocess.run(['kubectl','--kubeconfig',str(config),'--request-timeout=60s','apply','-f','-'],input=json.dumps(obj),capture_output=True,text=True) + if r.returncode==0:return + last=(r.stderr or r.stdout).strip()[-600:] + print('ipam: %s %s not applied yet: %s'%(obj['kind'],obj['metadata']['name'],last),flush=True) + time.sleep(10) + raise SystemExit('IPAM refused %s %s: %s'%(obj['kind'],obj['metadata']['name'],last)) + write({'apiVersion':'ipam.miloapis.com/v1alpha1','kind':'IPClass','metadata':{'name':'lab-provisioning'}, 'spec':{'ipFamily':'IPv4','addressScope':'Private','allowedPrefixLengths':{'min':32,'max':32},'defaultPrefixLength':32,'reclaimPolicy':'Delete'}}) - apply(config,{'apiVersion':'ipam.miloapis.com/v1alpha1','kind':'IPPool','metadata':{'name':'lab-provisioning'}, + write({'apiVersion':'ipam.miloapis.com/v1alpha1','kind':'IPPool','metadata':{'name':'lab-provisioning'}, 'spec':{'cidr':'192.168.77.0/24','ipFamily':'IPv4','classNames':['lab-provisioning'],'scope':{'location':LOCATION}, 'allocation':{'minPrefixLength':32,'maxPrefixLength':32,'strategy':'FirstFit'},'reservations':{'leading':100,'trailing':56,'unitPrefixLength':32}}}) get=lambda *a:json.loads(kubectl(config,'get',*a,'-o','json',capture_output=True).stdout) diff --git a/hack/multiplane/test-flux.py b/hack/multiplane/test-flux.py index 38f2da5e..7c0091e5 100644 --- a/hack/multiplane/test-flux.py +++ b/hack/multiplane/test-flux.py @@ -108,6 +108,11 @@ def render(rev, cluster): out = subprocess.run(['kustomize', 'build', str(s / 'gitops' / ('r%d' % rev) / 'environment' / cluster)], text=True, capture_output=True, check=True).stdout return out + pushed = 'local@sha256:' + 'd' * 64 + check('a layer counts at the pushed revision only', flux.at_revision('flux-system/fleet-site-base', pushed, pushed) + and not flux.at_revision('flux-system/fleet-site-base', 'sha256:' + 'e' * 64, pushed)) + check('IPAM\'s apiserver layer counts at its own pinned manifests', flux.at_revision('flux-system/ipam-apiserver', flux.IPAM_KUSTOMIZE_DIGEST, pushed) + and not flux.at_revision('flux-system/ipam-apiserver', pushed, pushed) and not flux.at_revision('flux-system/ipam-apiserver', None, pushed)) check('stage platform revision', flux.stage(ns(revision=1)) == 0) cell1 = render(1, 'cell') check('r1 has no site layers', 'name: fleet-site-services' not in cell1 and 'name: fleet-site-dispatch' not in cell1 and 'name: fleet-site-base' in cell1) From 3a789c1e387e26fcb5603655573799956e2b551f Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Fri, 27 Nov 2026 18:05:51 -0600 Subject: [PATCH 11/35] fix(lab): Verify IPAM's Flux layers as Flux writes Two more of the Flux evidence checks that only synchronized DHCP had used failed once the media suite ran IPAM on CI. - The bootstrap gating check counted IPAM's apiserver layer at its own pinned manifests as another revision. It now uses the same rule as the waits. - The expected inventory named the auth-delegator binding with colons, but Flux's inventory writes each colon in a name as two underscores. Co-Authored-By: Claude Opus 5.5 --- hack/multiplane/flux.py | 8 +++++--- hack/multiplane/test-redfish.py | 4 ++++ 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/hack/multiplane/flux.py b/hack/multiplane/flux.py index 05f11378..2548fd8b 100644 --- a/hack/multiplane/flux.py +++ b/hack/multiplane/flux.py @@ -128,7 +128,9 @@ 'flux-system/ipam-apiserver': sorted(['ipam-system_ipam-apiserver__ServiceAccount', '_ipam-apiserver_rbac.authorization.k8s.io_ClusterRole', 'ipam-system_ipam-apiserver-auth-reader_rbac.authorization.k8s.io_RoleBinding', '_ipam-apiserver_rbac.authorization.k8s.io_ClusterRoleBinding', - '_ipam-apiserver:system:auth-delegator_rbac.authorization.k8s.io_ClusterRoleBinding', + # Flux's inventory writes each colon in a name as two + # underscores. + '_ipam-apiserver__system__auth-delegator_rbac.authorization.k8s.io_ClusterRoleBinding', 'ipam-system_ipam-apiserver__Service', 'ipam-system_ipam-apiserver_apps_Deployment', 'ipam-system_ipam-apiserver_policy_PodDisruptionBudget', 'ipam-system_ipam-apiserver_networking.k8s.io_NetworkPolicy']), } if LAB_IPAM else {} @@ -763,9 +765,9 @@ def verify(args): # apply is a dependency re-reconciling at the same revision (for example on # a fresh request) and is recorded, not counted as either evidence or fault. gated = [o for o in events if o['revision'] == first and not o['lastAppliedRevision'] and not o['inventoryEntries']] - regated = [o for o in events if o['revision'] == first and o['lastAppliedRevision'] == first] + regated = [o for o in events if o['revision'] == first and o['lastAppliedRevision'] and at_revision(o['kustomization'], o['lastAppliedRevision'], first)] for o in events: - if o['revision'] == first and o['lastAppliedRevision'] not in (None, first): + if o['revision'] == first and o['lastAppliedRevision'] and not at_revision(o['kustomization'], o['lastAppliedRevision'], first): problems.append('dependent applied another revision during bootstrap: %s' % o) elif o['revision'] == first and not o['lastAppliedRevision'] and o['inventoryEntries']: problems.append('dependent has an inventory before applying while its dependency is not Ready: %s' % o) diff --git a/hack/multiplane/test-redfish.py b/hack/multiplane/test-redfish.py index 0323a582..e9522591 100644 --- a/hack/multiplane/test-redfish.py +++ b/hack/multiplane/test-redfish.py @@ -156,6 +156,10 @@ def build(path): ipam_layer = build(root / 'config/multiplane/ipam') ipam_ids = sorted('%s_%s_%s_%s' % (d['metadata'].get('namespace', ''), d['metadata']['name'], d['apiVersion'].rpartition('/')[0], d['kind']) for d in ipam_layer) check('IPAM layer inventory is exact', ipam_ids == flux.PLATFORM_LAYER_INVENTORY['flux-system/ipam-system'], str(ipam_ids)) +# Flux writes each colon in an inventory name as two underscores, so no +# expected inventory ID may hold one. +colons = [i for ids in list(flux.PLATFORM_LAYER_INVENTORY.values()) + list(flux.LAYER_INVENTORY.values()) for i in ids if ':' in i] +check('expected inventory IDs use Flux\'s escaping', not colons, str(colons)) check('no Secret in the IPAM layer', not any(d.get('kind') == 'Secret' for d in ipam_layer)) postgres = next((d for d in ipam_layer if d.get('kind') == 'StatefulSet'), {}).get('spec', {}).get('template', {}).get('spec', {}) check('IPAM PostgreSQL is pinned and reads its password from the enrolled Secret', From e013b8104c2e5b6fa2fedc38a6e3b0c73dc320f2 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Fri, 27 Nov 2026 18:43:59 -0600 Subject: [PATCH 12/35] test(lab): Report why a media report went missing A media suite failure that found no first-boot report said only how many reports the service refused. It now adds the installed OS's console outcomes, the window's report outcomes, and the recent output of the report relay and the central media service. The relay logs each connection's source address. The lab's fetch and report windows can be shortened for a faster runtime, since each held installation waits out both. Co-Authored-By: Claude Opus 5.5 --- docs/operations/redfish-lab.md | 4 +++- hack/multiplane/media_steps.py | 27 ++++++++++++++++++++++----- internal/multiplane/relay.go | 1 + 3 files changed, 26 insertions(+), 6 deletions(-) diff --git a/docs/operations/redfish-lab.md b/docs/operations/redfish-lab.md index bb828235..27f19d2c 100644 --- a/docs/operations/redfish-lab.md +++ b/docs/operations/redfish-lab.md @@ -579,7 +579,9 @@ console is diagnostics only and never carries a token. The deadline is the sum of the fetch window, 15 minutes by default, and the report window, 30 minutes by default. A site may set shorter ones; the lab -uses 5 and 10 minutes. +uses 5 and 10 minutes. `FLEET_MULTIPLANE_MEDIA_FETCH` and +`FLEET_MULTIPLANE_MEDIA_REPORT` shorten them for a faster runtime, such as +a CI runner's KVM guests. Each held installation waits out both windows. ### What is real and what is stubbed diff --git a/hack/multiplane/media_steps.py b/hack/multiplane/media_steps.py index 10263357..83937465 100644 --- a/hack/multiplane/media_steps.py +++ b/hack/multiplane/media_steps.py @@ -46,6 +46,7 @@ import datetime import hashlib import json +import os import pathlib import re import ssl @@ -68,8 +69,12 @@ STORE_ROOT = '/var/lib/fleet-local/site' LOCAL = 'https://127.0.0.1:%d' % rf.MEDIA_PORT # The lab's virtual media phases, shorter than the 15 and 30 minute -# defaults, as a site may set. -FETCH, REPORT = '5m0s', '10m0s' +# defaults, as a site may set. A faster runtime, such as a CI runner's +# KVM guests, may shorten them further. +FETCH = os.environ.get('FLEET_MULTIPLANE_MEDIA_FETCH') or '5m0s' +REPORT = os.environ.get('FLEET_MULTIPLANE_MEDIA_REPORT') or '10m0s' +if not all(re.fullmatch(r'[1-9][0-9]*m[0-9]+s|[1-9][0-9]*s', w) for w in (FETCH, REPORT)): + raise SystemExit('FLEET_MULTIPLANE_MEDIA_FETCH and FLEET_MULTIPLANE_MEDIA_REPORT must be durations such as 5m0s or 90s') def now(): @@ -139,6 +144,18 @@ def read_console(s): return [l.strip() for l in r.stdout.decode(errors='replace').splitlines()] if r.returncode == 0 else [] +def why(s, uid): + """What the lab saw of an install's report, for a failure message: the + installed OS's console outcomes (never a token), the window's report + outcomes, and the recent output of the report relay and the central + media service.""" + console = [l for l in read_console(s) if l.startswith('fleet:')][-6:] + relay = rf.kubectl(s, '-n', rf.SITE, 'logs', 'deploy/fleet-site-runtime', '-c', 'report-relay', '--tail', '8', check=False).stdout.strip().splitlines() + log = s / 'media-central.log' + central = log.read_text(errors='replace').strip().splitlines()[-8:] if log.exists() else [] + return '; console %s; report outcomes %s; relay %s; media service %s' % (console, outcomes(s, uid), relay, central) + + def steps_of(s, uid): return dict((n, st) for o in rf.journal(s) if o['operation'] == uid for n, st in o['steps']) @@ -186,9 +203,9 @@ def stray_address(s): die('the install records no IPAM-bound report address: %s, claim holds %r' % (address, bound)) refused = w.get('refused') or [] if [(r['from'], r['tokenMatched']) for r in refused] != [(STRAY_SOURCE, True)]: - die('the media service did not refuse, and record, the right token from %s: %s' % (STRAY_SOURCE, refused)) + die('the media service did not refuse, and record, the right token from %s: %s%s' % (STRAY_SOURCE, refused, why(s, uid))) if not w.get('report') or w['report'].get('from') != address['address']: - die('the media service took no report from the Machine\'s address %s: %s' % (address['address'], w.get('report'))) + die('the media service took no report from the Machine\'s address %s: %s%s' % (address['address'], w.get('report'), why(s, uid))) if 'rejected-address' not in outcomes(s, uid) or len(media_effects(rf.audit(s), 'add-stray-source')) != 1: die('the stray-source fault did not fire exactly once, or no report was refused for its address') console = [l for l in read_console(s) if l.startswith('fleet: stray report') or l.startswith('fleet: first-boot report from')] @@ -229,7 +246,7 @@ def held_report(s): uid = op['metadata']['uid'] w = window_record(s, uid) if w.get('report') or w.get('duplicates') or w.get('rejected', 0) < 3: - die('the media service took a report or refused fewer than three: %s' % {k: w.get(k) for k in ('report', 'duplicates', 'rejected')}) + die('the media service took a report or refused fewer than three: %s%s' % ({k: w.get(k) for k in ('report', 'duplicates', 'rejected')}, why(s, uid))) stray = json.loads((s / 'media-stray-reports.json').read_text()) if stray['answers'] != {'outside-ranges-ipv4': 403, 'outside-ranges-ipv6': 403} or not {'rejected-source', 'rejected-token'} <= set(outcomes(s, uid)): die('the stray reports were not all refused for their source, or the guest\'s report was not refused for its token: %s %s' % (stray['answers'], outcomes(s, uid))) diff --git a/internal/multiplane/relay.go b/internal/multiplane/relay.go index cf61c339..bba81341 100644 --- a/internal/multiplane/relay.go +++ b/internal/multiplane/relay.go @@ -61,6 +61,7 @@ func relay(conn net.Conn, upstream string) { if _, err := io.WriteString(out, redfishwork.ProxyHeader(source, destination)); err != nil { return } + fmt.Printf("report-relay: relaying a connection from %s\n", source.Addr()) done := make(chan struct{}, 2) pipe := func(to, from net.Conn) { _, _ = io.Copy(to, from) From 848e5c34d0626470e5294768ac03ce68704a875e Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Fri, 27 Nov 2026 19:14:09 -0600 Subject: [PATCH 13/35] fix(lab): Admit relayed reports to the media service Through the report relay, a guest's report carries its own lab network address, which the central media service's client list did not include. The service refused it before taking it, so the report was never recorded. The lab network is now a client; each window's report ranges and the Machine's address still bound the report. The harness checks the client list covers the site's report range. Co-Authored-By: Claude Opus 5.5 --- hack/multiplane/media-central.sh | 4 +++- hack/multiplane/test-harness.sh | 5 +++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/hack/multiplane/media-central.sh b/hack/multiplane/media-central.sh index 7946a3d9..b7bd5562 100755 --- a/hack/multiplane/media-central.sh +++ b/hack/multiplane/media-central.sh @@ -27,10 +27,12 @@ case $action in docker rm "$id" >/dev/null fi mkdir -p "$state/media-central" && chmod 0700 "$state/media-central" + # Clients: lab Pods arrive on loopback, and installed servers' reports + # through the relay with their own lab network addresses. nohup "$state/fleet-multiplane-host" media-service --config "$state/acceptance.json" --listen "127.0.0.1:28443,[::1]:28443" \ --proxy-listen 127.0.0.1:28444 --relays 127.0.0.0/8 \ --tls-cert "$state/redfish/media-tls.crt" --tls-key "$state/redfish/media-tls.key" --client-ca "$state/redfish/media-worker-ca.crt" \ - --state-dir "$state/media-central" --artifacts "$artifacts" --clients 127.0.0.0/8,::1/128 >>"$state/media-central.log" 2>&1 >"$state/media-central.log" 2>&1 "$pidfile" sleep 2 kill -0 "$(cat "$pidfile")" || { echo 'media-central: exited at start; see media-central.log in the state directory' >&2; exit 1; } diff --git a/hack/multiplane/test-harness.sh b/hack/multiplane/test-harness.sh index 8ac5c6b0..c5629f12 100755 --- a/hack/multiplane/test-harness.sh +++ b/hack/multiplane/test-harness.sh @@ -454,6 +454,11 @@ with tempfile.TemporaryDirectory() as tmp: for f in ('flux-tools', 'topology', 'flux-source', 'flux-bootstrap-$c', 'flux-platform', 'flux-milo', 'federation-enrollment', 'flux-site', 'flux-verify'): check('bootstrap phase present: ' + f, 'ph %s ' % f in run_sh or 'ph "%s" ' % f in run_sh) check('dispatch is a source revision', "--site dispatch" in steps and 'patch handoffdispatcher' not in steps) + graph = (root / 'config/site/redfish/graph/kustomization.yaml').read_text() + report_from = re.search(r'FLEET_MEDIA_REPORT_FROM, value: ([0-9./]+)', graph) + central = (root / 'hack/multiplane/media-central.sh').read_text() + check('the central media service admits the site\'s report range as clients', + report_from is not None and re.search(r'--clients \S*' + re.escape(report_from.group(1)), central) is not None) check('fault injection suspends Flux first', 'suspend milo-consumer-a true' in steps and '"suspend":true' in (root / 'hack/multiplane/reflection-faults.py').read_text()) check('RBAC revocation repaired by Flux, not the harness', "'apply'" not in (root / 'hack/multiplane/verify-rbac.py').read_text()) for path in ('config/site/base/site.yaml', 'config/site/graph/rgd.yaml', 'config/site/instance/dispatcher.yaml', 'config/multiplane/coordination/crd.yaml', From a1ecac98c11ba28a70e633cb43af3b9ee7d315b3 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Fri, 27 Nov 2026 19:27:41 -0600 Subject: [PATCH 14/35] test(lab): Match the report range exactly The check that the central media service's clients cover the site's report range matched the range anywhere in the list, so a longer range that ended with it passed. It now requires the range as a whole entry. Co-Authored-By: Claude Opus 5.5 --- hack/multiplane/test-harness.sh | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/hack/multiplane/test-harness.sh b/hack/multiplane/test-harness.sh index c5629f12..4800fe0e 100755 --- a/hack/multiplane/test-harness.sh +++ b/hack/multiplane/test-harness.sh @@ -457,8 +457,9 @@ with tempfile.TemporaryDirectory() as tmp: graph = (root / 'config/site/redfish/graph/kustomization.yaml').read_text() report_from = re.search(r'FLEET_MEDIA_REPORT_FROM, value: ([0-9./]+)', graph) central = (root / 'hack/multiplane/media-central.sh').read_text() + clients = re.search(r'--clients "?(\S+?)"? ', central) check('the central media service admits the site\'s report range as clients', - report_from is not None and re.search(r'--clients \S*' + re.escape(report_from.group(1)), central) is not None) + report_from is not None and clients is not None and report_from.group(1) in clients.group(1).split(',')) check('fault injection suspends Flux first', 'suspend milo-consumer-a true' in steps and '"suspend":true' in (root / 'hack/multiplane/reflection-faults.py').read_text()) check('RBAC revocation repaired by Flux, not the harness', "'apply'" not in (root / 'hack/multiplane/verify-rbac.py').read_text()) for path in ('config/site/base/site.yaml', 'config/site/graph/rgd.yaml', 'config/site/instance/dispatcher.yaml', 'config/multiplane/coordination/crd.yaml', From d10cb67c3eeba58cffb81fb442f421730c116d12 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Fri, 27 Nov 2026 20:00:54 -0600 Subject: [PATCH 15/35] fix(lab): Arm the stray source with the run state The stray-source step passed its fault to the lab BMC without the run's state, so it failed before the fourth install. The held-download and held-eject steps now say how an install ended, with the BMC's recent virtual media requests, when one did not install from media. Co-Authored-By: Claude Opus 5.5 --- hack/multiplane/media_steps.py | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/hack/multiplane/media_steps.py b/hack/multiplane/media_steps.py index 83937465..073d438e 100644 --- a/hack/multiplane/media_steps.py +++ b/hack/multiplane/media_steps.py @@ -156,6 +156,15 @@ def why(s, uid): return '; console %s; report outcomes %s; relay %s; media service %s' % (console, outcomes(s, uid), relay, central) +def detail(s, op): + """How an install ended, for a failure message: its phase, reason and + message, the BMC's recent virtual media requests, and what the lab saw + of its report.""" + status = op.get('status', {}) + media = summarize([e for e in rf.audit(s) if '/VirtualMedia/' in e['path']])[-6:] + return '; ended %s %s: %s; BMC media requests %s%s' % (status.get('phase'), status.get('reason'), (status.get('message') or '')[:300], media, why(s, op['metadata']['uid'])) + + def steps_of(s, uid): return dict((n, st) for o in rf.journal(s) if o['operation'] == uid for n, st in o['steps']) @@ -188,7 +197,7 @@ def arm_add_download(s): def arm_stray_source(s): - arm('stray-source', SYSTEM, STRAY_SOURCE) + arm(s, 'stray-source', SYSTEM, STRAY_SOURCE) print('media-arm-stray-source: target A\'s next config medium makes its installed OS post its report, with the right token, from %s first' % STRAY_SOURCE) @@ -282,7 +291,7 @@ def held_download(s): uid = op['metadata']['uid'] steps = steps_of(s, uid) if steps.get('media-installer-done') != 'Done' or 'media-report-verified' in steps or 'media-released' in steps: - die('the second installation verified its report or recorded release: %s' % steps) + die('the second installation did not install from media, or verified its report or recorded release: %s%s' % (steps, detail(s, op))) if len(media_effects(rf.audit(s), 'add-config-download')) != 1: die('the add-download fault did not fire exactly once') w = window_record(s, uid) @@ -304,7 +313,7 @@ def held_eject(s): steps = steps_of(s, uid) for step in ('media-window', 'media-insert-boot', 'media-insert-config', 'media-installer-done', 'media-report-verified', 'media-close'): if steps.get(step) != 'Done': - die('the third installation did not journal %s done: %s' % (step, steps)) + die('the third installation did not journal %s done: %s%s' % (step, steps, detail(s, op))) if steps.get('media-eject-cd1') != 'Intended' or 'media-released' in steps: die('the lost eject is not journaled intended-only, or release was recorded: %s' % steps) # The BMC audits the eject only once it answers, after the 45 seconds it From df505279e80a7f55e9b72b8720ede528892110d2 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Fri, 27 Nov 2026 20:03:07 -0600 Subject: [PATCH 16/35] test(lab): Check each lab fault gets the run state The stray-source fault was armed without the run state and failed only in the lab. The harness now requires every media suite fault to pass it. Co-Authored-By: Claude Opus 5.5 --- hack/multiplane/test-harness.sh | 3 +++ 1 file changed, 3 insertions(+) diff --git a/hack/multiplane/test-harness.sh b/hack/multiplane/test-harness.sh index 4800fe0e..95723c09 100755 --- a/hack/multiplane/test-harness.sh +++ b/hack/multiplane/test-harness.sh @@ -454,6 +454,9 @@ with tempfile.TemporaryDirectory() as tmp: for f in ('flux-tools', 'topology', 'flux-source', 'flux-bootstrap-$c', 'flux-platform', 'flux-milo', 'federation-enrollment', 'flux-site', 'flux-verify'): check('bootstrap phase present: ' + f, 'ph %s ' % f in run_sh or 'ph "%s" ' % f in run_sh) check('dispatch is a source revision', "--site dispatch" in steps and 'patch handoffdispatcher' not in steps) + steps_py = (root / 'hack/multiplane/media_steps.py').read_text() + arms = re.findall(r'^\s+arm\(([^,)]*)', steps_py, re.M) + check('every media lab fault is armed with the run state', arms and all(a == 's' for a in arms), str(arms)) graph = (root / 'config/site/redfish/graph/kustomization.yaml').read_text() report_from = re.search(r'FLEET_MEDIA_REPORT_FROM, value: ([0-9./]+)', graph) central = (root / 'hack/multiplane/media-central.sh').read_text() From 0b7f8d30cfd4ad668f2a26a381f549c93d529bf9 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Fri, 27 Nov 2026 20:40:24 -0600 Subject: [PATCH 17/35] fix(lab): Give stale-fence opens a report address The stale-fence step's window opens named no report address, which a window now requires, so the cell worker's open was refused as malformed (400) before custody refused its fence (409). The opens now name the lab's report range and the operation's recorded IPAM address, and the harness checks they send every field a window open takes. Co-Authored-By: Claude Opus 5.5 --- hack/multiplane/media_steps.py | 5 ++++- hack/multiplane/test-harness.sh | 8 ++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/hack/multiplane/media_steps.py b/hack/multiplane/media_steps.py index 073d438e..7672c7f2 100644 --- a/hack/multiplane/media_steps.py +++ b/hack/multiplane/media_steps.py @@ -66,6 +66,8 @@ # Another address on the lab network, inside the site's report ranges and # outside IPAM's pool and the static leases: another server's. STRAY_SOURCE = '192.168.77.250' +# The site's report range, as the lab's site workers declare it. +REPORT_RANGE = '192.168.77.0/24' STORE_ROOT = '/var/lib/fleet-local/site' LOCAL = 'https://127.0.0.1:%d' % rf.MEDIA_PORT # The lab's virtual media phases, shorter than the 15 and 30 minute @@ -407,7 +409,8 @@ def stale_fence(s): w = window_record(s, op['metadata']['uid']) body = {'device': harness.DEVICE, 'operation': op['metadata']['uid'], 'fence': op['status']['fence'], 'bootDigest': w['bootDigest'], 'capabilitySHA256': '0' * 64, 'tokenSHA256': '0' * 64, 'configMedium': base64.b64encode(b'stale').decode(), - 'fetchExpires': later(10), 'reportExpires': later(20), 'reportFrom': ['127.0.0.1/32']} + 'fetchExpires': later(10), 'reportExpires': later(20), 'reportFrom': [REPORT_RANGE], + 'reportAddress': op['spec']['delivery']['reportAddress']['address']} # A well-formed open, so the cell worker's answer is custody's. # Without a client certificate, and with another site's, the open is # refused before the service looks at custody; as the cell's worker, diff --git a/hack/multiplane/test-harness.sh b/hack/multiplane/test-harness.sh index 95723c09..b1b21865 100755 --- a/hack/multiplane/test-harness.sh +++ b/hack/multiplane/test-harness.sh @@ -455,6 +455,14 @@ with tempfile.TemporaryDirectory() as tmp: check('bootstrap phase present: ' + f, 'ph %s ' % f in run_sh or 'ph "%s" ' % f in run_sh) check('dispatch is a source revision', "--site dispatch" in steps and 'patch handoffdispatcher' not in steps) steps_py = (root / 'hack/multiplane/media_steps.py').read_text() + # The stale-fence probe's opens must be well-formed, so only the fence + # decides the cell worker's answer: they send every field a window open + # takes. + server = (root / 'internal/site/redfishwork/mediaserver.go').read_text() + fields = re.findall(r'json:"([a-zA-Z0-9]+)', server[server.index('type OpenRequest struct'):server.index('}', server.index('type OpenRequest struct'))]) + stale = steps_py[steps_py.index('def stale_fence'):steps_py.index('\ndef ', steps_py.index('def stale_fence') + 1)] + missing = [f for f in fields if "'%s'" % f not in stale] + check('the stale-fence probe sends every window open field', fields and not missing, str(missing)) arms = re.findall(r'^\s+arm\(([^,)]*)', steps_py, re.M) check('every media lab fault is armed with the run state', arms and all(a == 's' for a in arms), str(arms)) graph = (root / 'config/site/redfish/graph/kustomization.yaml').read_text() From 3fc692db9a736534477f4ea882ca67e4fd4bd9fc Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sat, 28 Nov 2026 18:08:54 -0600 Subject: [PATCH 18/35] fix: Key virtual media windows by the operation's admission No spec carries an object UID, so a virtual media install's window, its config medium, its journal and its central service records are keyed by the admission's site key: the operation's kind, name and fence. The media service opens a window only while custody names that key active, and the lab's media checks read each window under it. The lab's media phases name an installation's request and Device incarnation in labels. Co-Authored-By: Claude Opus 5.5 --- hack/multiplane/media_steps.py | 91 +++++++++++++------------ internal/custody/delivery_test.go | 20 +++--- internal/multiplane/media.go | 14 ++-- internal/site/redfishwork/media_test.go | 41 +++++++---- 4 files changed, 96 insertions(+), 70 deletions(-) diff --git a/hack/multiplane/media_steps.py b/hack/multiplane/media_steps.py index 7672c7f2..6e23a5c6 100644 --- a/hack/multiplane/media_steps.py +++ b/hack/multiplane/media_steps.py @@ -106,8 +106,15 @@ def media_installs(s): key=lambda i: i['status']['fence']) -def key(uid): - return hashlib.sha256(uid.encode()).hexdigest()[:16] +def key(operation): + return hashlib.sha256(operation.encode()).hexdigest()[:16] + + +def op_key(op): + """The site's key for an admitted operation, which names its journal, + its site records and its media window: kind, name and fence, as + custody.OperationKey builds it. No object UID is in any spec.""" + return harness.operation_key(op['kind'], op['metadata']['name'], op['status']['fence']) def central(s, method, path, body=None, identity='media-worker'): @@ -126,16 +133,16 @@ def central(s, method, path, body=None, identity='media-worker'): return e.code, None -def window_record(s, uid): +def window_record(s, operation): """The central service's own record of a window, without its medium.""" - w = json.loads((s / 'media-central' / 'windows' / (key(uid) + '.json')).read_text()) + w = json.loads((s / 'media-central' / 'windows' / (key(operation) + '.json')).read_text()) w['configMediumKept'] = bool(w.pop('configMedium', None)) return w -def site_window(s, uid): +def site_window(s, operation): """The site's digests of a window: what the report had to carry.""" - return json.loads(rf.runtime(s, 'sh', '-c', 'cat %s/devices/*/media/%s.json' % (STORE_ROOT, uid)).stdout) + return json.loads(rf.runtime(s, 'sh', '-c', 'cat %s/devices/*/media/%s.json' % (STORE_ROOT, operation)).stdout) def read_console(s): @@ -146,7 +153,7 @@ def read_console(s): return [l.strip() for l in r.stdout.decode(errors='replace').splitlines()] if r.returncode == 0 else [] -def why(s, uid): +def why(s, operation): """What the lab saw of an install's report, for a failure message: the installed OS's console outcomes (never a token), the window's report outcomes, and the recent output of the report relay and the central @@ -155,7 +162,7 @@ def why(s, uid): relay = rf.kubectl(s, '-n', rf.SITE, 'logs', 'deploy/fleet-site-runtime', '-c', 'report-relay', '--tail', '8', check=False).stdout.strip().splitlines() log = s / 'media-central.log' central = log.read_text(errors='replace').strip().splitlines()[-8:] if log.exists() else [] - return '; console %s; report outcomes %s; relay %s; media service %s' % (console, outcomes(s, uid), relay, central) + return '; console %s; report outcomes %s; relay %s; media service %s' % (console, outcomes(s, operation), relay, central) def detail(s, op): @@ -164,11 +171,11 @@ def detail(s, op): of its report.""" status = op.get('status', {}) media = summarize([e for e in rf.audit(s) if '/VirtualMedia/' in e['path']])[-6:] - return '; ended %s %s: %s; BMC media requests %s%s' % (status.get('phase'), status.get('reason'), (status.get('message') or '')[:300], media, why(s, op['metadata']['uid'])) + return '; ended %s %s: %s; BMC media requests %s%s' % (status.get('phase'), status.get('reason'), (status.get('message') or '')[:300], media, why(s, op_key(op))) -def steps_of(s, uid): - return dict((n, st) for o in rf.journal(s) if o['operation'] == uid for n, st in o['steps']) +def steps_of(s, operation): + return dict((n, st) for o in rf.journal(s) if o['operation'] == operation for n, st in o['steps']) def offer(s): @@ -205,19 +212,19 @@ def arm_stray_source(s): def stray_address(s): op = media_installs(s)[-1] - uid = op['metadata']['uid'] + operation = op_key(op) address = (op['spec']['delivery'].get('reportAddress') or {}) - w = window_record(s, uid) + w = window_record(s, operation) claim = json.loads(provider(s, '-n', 'fleet-provider', 'get', 'ipclaims.ipam.miloapis.com', address.get('addressClaim', {}).get('name', '-'), '-o', 'json').stdout) bound = (claim.get('status') or {}).get('address', '').split('/')[0] if not address.get('address') or bound != address['address'] or not address['address'].startswith('192.168.77.'): die('the install records no IPAM-bound report address: %s, claim holds %r' % (address, bound)) refused = w.get('refused') or [] if [(r['from'], r['tokenMatched']) for r in refused] != [(STRAY_SOURCE, True)]: - die('the media service did not refuse, and record, the right token from %s: %s%s' % (STRAY_SOURCE, refused, why(s, uid))) + die('the media service did not refuse, and record, the right token from %s: %s%s' % (STRAY_SOURCE, refused, why(s, operation))) if not w.get('report') or w['report'].get('from') != address['address']: - die('the media service took no report from the Machine\'s address %s: %s%s' % (address['address'], w.get('report'), why(s, uid))) - if 'rejected-address' not in outcomes(s, uid) or len(media_effects(rf.audit(s), 'add-stray-source')) != 1: + die('the media service took no report from the Machine\'s address %s: %s%s' % (address['address'], w.get('report'), why(s, operation))) + if 'rejected-address' not in outcomes(s, operation) or len(media_effects(rf.audit(s), 'add-stray-source')) != 1: die('the stray-source fault did not fire exactly once, or no report was refused for its address') console = [l for l in read_console(s) if l.startswith('fleet: stray report') or l.startswith('fleet: first-boot report from')] rf.write(s / 'media-stray-address.json', {'operation': op['metadata']['name'], 'reportAddress': address, 'claimBound': bound, 'refused': refused, @@ -244,8 +251,8 @@ def summarize(entries): return out -def outcomes(s, uid): - path = s / 'media-central' / 'transfers' / key(uid) / 'reports.log' +def outcomes(s, operation): + path = s / 'media-central' / 'transfers' / key(operation) / 'reports.log' return [w for w in (path.read_text().split() if path.exists() else []) if w.startswith('rejected') or w in ('accepted', 'duplicate', 'repeated')] @@ -254,14 +261,14 @@ def held_report(s): if len(ops) != 1 or ops[0]['status'].get('phase') != 'OutcomeUnknown': die('expected one held virtual media installation, got %s' % [(o['metadata']['name'], o['status'].get('phase')) for o in ops]) op = ops[0] - uid = op['metadata']['uid'] - w = window_record(s, uid) + operation = op_key(op) + w = window_record(s, operation) if w.get('report') or w.get('duplicates') or w.get('rejected', 0) < 3: - die('the media service took a report or refused fewer than three: %s%s' % ({k: w.get(k) for k in ('report', 'duplicates', 'rejected')}, why(s, uid))) + die('the media service took a report or refused fewer than three: %s%s' % ({k: w.get(k) for k in ('report', 'duplicates', 'rejected')}, why(s, operation))) stray = json.loads((s / 'media-stray-reports.json').read_text()) - if stray['answers'] != {'outside-ranges-ipv4': 403, 'outside-ranges-ipv6': 403} or not {'rejected-source', 'rejected-token'} <= set(outcomes(s, uid)): - die('the stray reports were not all refused for their source, or the guest\'s report was not refused for its token: %s %s' % (stray['answers'], outcomes(s, uid))) - steps = steps_of(s, uid) + if stray['answers'] != {'outside-ranges-ipv4': 403, 'outside-ranges-ipv6': 403} or not {'rejected-source', 'rejected-token'} <= set(outcomes(s, operation)): + die('the stray reports were not all refused for their source, or the guest\'s report was not refused for its token: %s %s' % (stray['answers'], outcomes(s, operation))) + steps = steps_of(s, operation) for step in ('media-window', 'media-insert-boot', 'media-insert-config', 'media-installer-power-on', 'media-installer-done', 'disk-power-on'): if steps.get(step) != 'Done': die('the held installation did not journal %s done: %s' % (step, steps)) @@ -278,7 +285,7 @@ def held_report(s): if sorted(credential.get('data', {})) != ['password', 'tlsPublicKeySHA256', 'username']: die('the BMC credential Secret holds more than BMC credentials: %s' % sorted(credential.get('data', {}))) rf.write(s / 'media-held-report.json', {'operation': op['metadata']['name'], 'fence': op['status']['fence'], 'reason': op['status'].get('reason'), - 'mediaService': {'report': None, 'rejected': w['rejected'], 'outcomes': outcomes(s, uid)}, + 'mediaService': {'report': None, 'rejected': w['rejected'], 'outcomes': outcomes(s, operation)}, 'strayReports': stray['answers'], 'steps': steps, 'consoleDiagnostics': diagnostics}) print('media-held-report: %s booted from media; its OS posted a report with another token from its IPAM address (refused); stray reports from outside the site\'s report ranges were refused (%s); ' 'the media service took no report (%d refused); OutcomeUnknown (%s) at the report deadline' @@ -290,13 +297,13 @@ def held_download(s): if [o['status'].get('phase') for o in ops] != ['OutcomeUnknown', 'OutcomeUnknown']: die('expected two held virtual media installations, got %s' % [(o['metadata']['name'], o['status'].get('phase')) for o in ops]) op = ops[1] - uid = op['metadata']['uid'] - steps = steps_of(s, uid) + operation = op_key(op) + steps = steps_of(s, operation) if steps.get('media-installer-done') != 'Done' or 'media-report-verified' in steps or 'media-released' in steps: die('the second installation did not install from media, or verified its report or recorded release: %s%s' % (steps, detail(s, op))) if len(media_effects(rf.audit(s), 'add-config-download')) != 1: die('the add-download fault did not fire exactly once') - w = window_record(s, uid) + w = window_record(s, operation) named = [d['name'] for d in (w.get('report') or {}).get('downloads') or []] if not w.get('report') or named != ['extension'] or op['spec']['image'].get('downloads'): die('the report did not name the unpinned download, or the operation pinned one: %s' % w.get('report')) @@ -311,8 +318,8 @@ def held_eject(s): if [o['status'].get('phase') for o in ops] != ['OutcomeUnknown'] * 3: die('expected three held virtual media installations, got %s' % [(o['metadata']['name'], o['status'].get('phase')) for o in ops]) op = ops[2] - uid = op['metadata']['uid'] - steps = steps_of(s, uid) + operation = op_key(op) + steps = steps_of(s, operation) for step in ('media-window', 'media-insert-boot', 'media-insert-config', 'media-installer-done', 'media-report-verified', 'media-close'): if steps.get(step) != 'Done': die('the third installation did not journal %s done: %s%s' % (step, steps, detail(s, op))) @@ -327,11 +334,11 @@ def held_eject(s): time.sleep(2) if len(faulted) != 1 or faulted[0].get('media') != 'CD1': die('the lost eject fault did not fire exactly once on CD1') - w, want = window_record(s, uid), site_window(s, uid) + w, want = window_record(s, operation), site_window(s, operation) if not w.get('report') or w['report']['image'] != want['image'] or w['report']['bootstrap'] != want['bootstrap'] or w.get('duplicates'): die('the third installation\'s report was not taken with its own digests') rf.write(s / 'media-held-eject.json', {'operation': op['metadata']['name'], 'fence': op['status']['fence'], 'reason': op['status'].get('reason'), - 'steps': steps, 'fault': summarize(faulted), 'report': w['report'], 'reportOutcomes': outcomes(s, uid)}) + 'steps': steps, 'fault': summarize(faulted), 'report': w['report'], 'reportOutcomes': outcomes(s, operation)}) print('media-held-eject: %s took its first-boot report (image %s..., bootstrap %s...), then lost the CD1 eject response: OutcomeUnknown (%s), media-released never journaled' % (op['metadata']['name'], w['report']['image'][:19], w['report']['bootstrap'][:19], op['status'].get('reason'))) @@ -380,8 +387,8 @@ def release_proof(s): # The live media service denies every window, from the BMC's own Pod. denials = [] for op in ops: - w = window_record(s, op['metadata']['uid']) - url = 'https://%s:%d/media/%s/boot/%s/boot.iso' % (rf.MEDIA_HOST, rf.MEDIA_PORT, key(op['metadata']['uid']), w['bootDigest']) + w = window_record(s, op_key(op)) + url = 'https://%s:%d/media/%s/boot/%s/boot.iso' % (rf.MEDIA_HOST, rf.MEDIA_PORT, key(op_key(op)), w['bootDigest']) probe = ("import ssl,sys,urllib.request,urllib.error\nc=ssl.create_default_context(cafile='/etc/fleet-bmc-media-ca/ca.crt')\n" "try:\n urllib.request.urlopen(sys.argv[1],context=c,timeout=20); print(200)\nexcept urllib.error.HTTPError as e: print(e.code)\n") answer = rf.bmc(s, 'python3', '-c', probe, url).stdout.strip() @@ -392,7 +399,7 @@ def release_proof(s): kept = rf.runtime(s, 'sh', '-c', 'ls %s/devices/*/mediacfg 2>/dev/null | grep -c json || true' % STORE_ROOT).stdout.strip() if kept not in ('', '0'): die('the site store still keeps %s config media' % kept) - steps = steps_of(s, settling['metadata']['uid']) + steps = steps_of(s, op_key(settling)) for step in ('media-window', 'media-insert-boot', 'media-insert-config', 'media-installer-done', 'media-report-verified', 'media-close', 'media-eject-cd1', 'media-eject-cd2', 'media-released'): if steps.get(step) != 'Done': die('the settling installation did not journal %s done: %s' % (step, steps)) @@ -406,8 +413,8 @@ def release_proof(s): def stale_fence(s): refused = [] for op in media_installs(s): - w = window_record(s, op['metadata']['uid']) - body = {'device': harness.DEVICE, 'operation': op['metadata']['uid'], 'fence': op['status']['fence'], 'bootDigest': w['bootDigest'], + w = window_record(s, op_key(op)) + body = {'device': harness.DEVICE, 'operation': op_key(op), 'fence': op['status']['fence'], 'bootDigest': w['bootDigest'], 'capabilitySHA256': '0' * 64, 'tokenSHA256': '0' * 64, 'configMedium': base64.b64encode(b'stale').decode(), 'fetchExpires': later(10), 'reportExpires': later(20), 'reportFrom': [REPORT_RANGE], 'reportAddress': op['spec']['delivery']['reportAddress']['address']} @@ -415,7 +422,7 @@ def stale_fence(s): # Without a client certificate, and with another site's, the open is # refused before the service looks at custody; as the cell's worker, # custody refuses it. - answers = {client: central(s, 'PUT', '/v1/windows/' + key(op['metadata']['uid']), body, identity)[0] + answers = {client: central(s, 'PUT', '/v1/windows/' + key(op_key(op)), body, identity)[0] for client, identity in (('unauthenticated', None), ('anotherSite', 'media-worker-other'), ('cellWorker', 'media-worker'))} if answers != {'unauthenticated': 401, 'anotherSite': 403, 'cellWorker': 409}: die('the media service answered %s to window opens it must refuse' % answers) @@ -434,13 +441,13 @@ def evidence(s): console = read_console(s) reports = [] for op in ops: - uid = op['metadata']['uid'] - w, want = window_record(s, uid), site_window(s, uid) - path = s / 'media-central' / 'transfers' / key(uid) / 'media-transfer.log' + operation = op_key(op) + w, want = window_record(s, operation), site_window(s, operation) + path = s / 'media-central' / 'transfers' / key(operation) / 'media-transfer.log' transfers = path.read_text().splitlines() if path.exists() else [] reports.append({'operation': op['metadata']['name'], 'fence': op['status']['fence'], 'phase': op['status']['phase'], 'reason': op['status'].get('reason'), 'reportTokenSHA256': w['tokenSHA256'], 'expected': {'image': want['image'], 'bootstrap': want['bootstrap']}, 'report': w.get('report'), - 'reportOutcomes': outcomes(s, uid), 'transfers': [' '.join(t.split()[1:2] + t.split()[3:]) for t in transfers]}) + 'reportOutcomes': outcomes(s, operation), 'transfers': [' '.join(t.split()[1:2] + t.split()[3:]) for t in transfers]}) if [r['report'] is not None for r in reports] != [False, True, True, True]: die('expected no report for the corrupted install and one for each of the others') if any(r['report'] and (r['report']['image'] != r['expected']['image'] or r['report']['bootstrap'] != r['expected']['bootstrap']) for r in reports) or \ diff --git a/internal/custody/delivery_test.go b/internal/custody/delivery_test.go index d9219903..abb5b8b3 100644 --- a/internal/custody/delivery_test.go +++ b/internal/custody/delivery_test.go @@ -92,9 +92,9 @@ func TestDeliveryMethodAdmission(t *testing.T) { claim := e.ipClaim(bootaddress.ClaimName(name), name, "DeviceInstallation", "Bound", "198.51.100.40") delivery.ReportAddress = &ops.BootNetworkInput{AddressClaim: bootaddress.Reference(claim.GetName()), Address: "198.51.100.40"} } - operation := &ops.DeviceInstallation{ObjectMeta: metav1.ObjectMeta{Name: InstallationName(allocation, request), Namespace: "default"}, Spec: ops.DeviceInstallationSpec{ - OperationEnvelope: envelope(device, providerUser, allocated(allocation)), RequestUID: request, - Image: ops.ImageInput{Name: "debian-12", Digest: imageDigest}, BootInterface: "primary", TargetDisks: []string{"disk-0"}, BootNetwork: network, Delivery: delivery, + operation := &ops.DeviceInstallation{ObjectMeta: metav1.ObjectMeta{Name: InstallationName(allocation, request), Namespace: "default", Labels: map[string]string{ops.LabelInstallationUID: request}}, Spec: ops.DeviceInstallationSpec{ + OperationEnvelope: envelope(device, providerUser, allocated(allocation)), + Image: ops.ImageInput{Name: "debian-12", Digest: imageDigest}, BootInterface: "primary", TargetDisks: []string{"disk-0"}, BootNetwork: network, Delivery: delivery, }} e.create(operation) return operation @@ -106,7 +106,7 @@ func TestDeliveryMethodAdmission(t *testing.T) { operation := install(e, device, "request-1", virtualMedia, nil) e.settle(device.Name) active := e.custody(device.Name).Spec.ActiveOperation - if active == nil || active.UID != string(operation.UID) || active.Snapshot.Extra[ExtraDeliveryMethod] != "VirtualMedia" { + if active == nil || active.Name != operation.Name || active.Snapshot.Extra[ExtraDeliveryMethod] != "VirtualMedia" { t.Fatalf("the snapshot records %q", active.Snapshot.Extra[ExtraDeliveryMethod]) } }) @@ -215,7 +215,7 @@ func TestDeliveryMethodAdmission(t *testing.T) { e.requireUntouched(device.Name, fence) settling := install(e, device, "request-3", virtualMedia, nil) e.settle(device.Name) - if active := e.custody(device.Name).Spec.ActiveOperation; active == nil || active.UID != string(settling.UID) { + if active := e.custody(device.Name).Spec.ActiveOperation; active == nil || active.Name != settling.Name { t.Fatalf("the virtual media settling install was not admitted: %+v, %+v", active, e.status(settling)) } }) @@ -287,10 +287,10 @@ func TestDeliveryMethodAdmission(t *testing.T) { allocation := "alloc-d-" + device.Name delivery := virtualMedia delivery.ReportAddress = &ops.BootNetworkInput{AddressClaim: bootaddress.Reference(bootaddress.ClaimName(InstallationName(allocation, "request-1"))), Address: "198.51.100.40"} - operation := &ops.DeviceInstallation{ObjectMeta: metav1.ObjectMeta{Name: InstallationName(allocation, "request-1"), Namespace: "default"}, Spec: ops.DeviceInstallationSpec{ - OperationEnvelope: envelope(device, providerUser, allocated(allocation)), RequestUID: "request-1", - Image: ops.ImageInput{Name: "talos", Digest: imageDigest, Downloads: []ops.DownloadInput{{Name: "installer", Reference: "registry.example/installer:v1.0.0"}}}, - BootInterface: "primary", TargetDisks: []string{"disk-0"}, Delivery: delivery, + operation := &ops.DeviceInstallation{ObjectMeta: metav1.ObjectMeta{Name: InstallationName(allocation, "request-1"), Namespace: "default", Labels: map[string]string{ops.LabelInstallationUID: "request-1"}}, Spec: ops.DeviceInstallationSpec{ + OperationEnvelope: envelope(device, providerUser, allocated(allocation)), + Image: ops.ImageInput{Name: "talos", Digest: imageDigest, Downloads: []ops.DownloadInput{{Name: "installer", Reference: "registry.example/installer:v1.0.0"}}}, + BootInterface: "primary", TargetDisks: []string{"disk-0"}, Delivery: delivery, }} e.create(operation) e.settle(device.Name) @@ -319,7 +319,7 @@ func TestDeliveryMethodAdmission(t *testing.T) { operation := install(e, device, "request-1", virtualMedia, nil) e.settle(device.Name) active := e.custody(device.Name).Spec.ActiveOperation - if active == nil || active.UID != string(operation.UID) || active.Deadline.Sub(active.AdmittedAt.Time) != ops.DefaultFetchWindow+ops.DefaultReportWindow { + if active == nil || active.Name != operation.Name || active.Deadline.Sub(active.AdmittedAt.Time) != ops.DefaultFetchWindow+ops.DefaultReportWindow { t.Fatalf("active = %+v", active) } }) diff --git a/internal/multiplane/media.go b/internal/multiplane/media.go index 332a4517..1f3bad7e 100644 --- a/internal/multiplane/media.go +++ b/internal/multiplane/media.go @@ -108,11 +108,12 @@ func (r *Runner) refusedInstallation(ctx context.Context, request string, delive key := client.ObjectKey{Namespace: DeviceNamespace, Name: custody.InstallationName(current.Name, request)} if err := r.Provider.API.Get(ctx, key, operation); apierrors.IsNotFound(err) { operation = &ops.DeviceInstallation{ - ObjectMeta: metav1.ObjectMeta{Name: key.Name, Namespace: key.Namespace}, + ObjectMeta: metav1.ObjectMeta{Name: key.Name, Namespace: key.Namespace, Labels: map[string]string{ + ops.LabelDeviceUID: string(device.UID), ops.LabelInstallationUID: request}}, Spec: ops.DeviceInstallationSpec{ - OperationEnvelope: ops.OperationEnvelope{Creator: r.Allocator.ProviderCreator, DeviceRef: ops.DeviceReference{Name: device.Name, UID: string(device.UID)}, + OperationEnvelope: ops.OperationEnvelope{Creator: r.Allocator.ProviderCreator, DeviceRef: ops.DeviceReference{Name: device.Name}, Authority: ops.Authority{AllocationRef: &ops.LocalReference{Name: current.Name}}}, - RequestUID: request, Image: image, BootInterface: "primary", TargetDisks: []string{"disk-0"}, + Image: image, BootInterface: "primary", TargetDisks: []string{"disk-0"}, Delivery: unclaimedReportAddress(delivery, key.Name), }, } @@ -211,7 +212,7 @@ func (r *Runner) mediaHeld(ctx context.Context, name string, probe bool) error { return err } method, held := custody.HeldMethod(state, "DeviceInstallation") - if !held || state.Spec.RecoveryHold.UID != string(operation.UID) || method != ops.DeliveryVirtualMedia { + if !held || state.Spec.RecoveryHold.Name != operation.Name || method != ops.DeliveryVirtualMedia { return fmt.Errorf("%w: the hold does not record the virtual media installation: %+v", errTerminal, state.Spec.RecoveryHold) } if probe { @@ -249,7 +250,8 @@ func (r *Runner) strayReports(ctx context.Context, operation *ops.DeviceInstalla origin := "https://127.0.0.1:28443" worker := &http.Client{Timeout: 20 * time.Second, Transport: &http.Transport{TLSClientConfig: &tls.Config{RootCAs: pool, Certificates: []tls.Certificate{identity}}}} client := &http.Client{Timeout: 20 * time.Second, Transport: &http.Transport{TLSClientConfig: &tls.Config{RootCAs: pool}}} - key := redfishwork.Key(string(operation.UID)) + // The worker opened the window under the admission's site key. + key := redfishwork.Key(custody.OperationKey(ops.OperationReference{Kind: "DeviceInstallation", Name: operation.Name}, operation.Status.Fence)) status, err := worker.Get(origin + "/v1/windows/" + key) if err != nil { return err @@ -341,7 +343,7 @@ func (c custodyReader) Active(ctx context.Context, device string) (string, int64 if active == nil { return "", 0, false, nil } - return active.UID, active.Fence, true, nil + return custody.OperationKey(active.OperationReference, active.Fence), active.Fence, true, nil } // WorkerIdentity is the client certificate common name of a cell's site diff --git a/internal/site/redfishwork/media_test.go b/internal/site/redfishwork/media_test.go index 7d101d3a..74ed82c6 100644 --- a/internal/site/redfishwork/media_test.go +++ b/internal/site/redfishwork/media_test.go @@ -339,6 +339,9 @@ type mediaEnv struct { workers *workerCA // downloads are the installer downloads the operation pins. downloads []ops.DownloadInput + // keys maps each admitted test operation to its site key, which names + // its media window. + keys map[string]string } func newMediaEnv(t *testing.T) *mediaEnv { @@ -444,7 +447,7 @@ func (w *workerCA) asWorker(t *testing.T, request *http.Request, identity string func (e *mediaEnv) spec() ops.DeviceInstallationSpec { image := e.image image.Downloads = e.downloads - return ops.DeviceInstallationSpec{Image: image, BootInterface: "primary", TargetDisks: []string{"disk-0"}, RequestUID: "request-1", + return ops.DeviceInstallationSpec{Image: image, BootInterface: "primary", TargetDisks: []string{"disk-0"}, Delivery: ops.DeliveryInput{Method: ops.DeliveryVirtualMedia, Addresses: ops.AddressesDataNetwork, MediaService: e.origin, FetchWindow: &metav1.Duration{Duration: e.fetch}, ReportWindow: &metav1.Duration{Duration: e.report}, // The fake BMC network posts reports from the Machine's address. @@ -453,19 +456,33 @@ func (e *mediaEnv) spec() ops.DeviceInstallationSpec { // assignment admits the operation: custody names it active at its fence. func (e *mediaEnv) assignment(uid string, fence int64) site.Assignment { - e.custody.set(uid, fence) inputs, _ := json.Marshal(e.spec()) sum := sha256.Sum256(inputs) - return site.Assignment{ - Device: device, Operation: ops.OperationReference{Kind: "DeviceInstallation", Name: "alloc-example-" + uid, UID: uid}, Fence: fence, AdmittedAt: time.Now(), Deadline: time.Now().Add(time.Minute), + a := site.Assignment{ + Device: device, Operation: ops.OperationReference{Kind: "DeviceInstallation", Name: "alloc-example-" + uid}, Fence: fence, AdmittedAt: time.Now(), Deadline: time.Now().Add(time.Minute), Snapshot: ops.DeviceSnapshot{BMCEndpoint: e.bmc.server.URL, SystemUUID: uuid, BMCPublicKeySHA256: e.bmc.pin()}, InputDigest: "sha256:" + hex.EncodeToString(sum[:]), Inputs: inputs, } + if e.keys == nil { + e.keys = map[string]string{} + } + e.keys[uid] = a.Key() + e.custody.set(a.Key(), fence) + return a +} + +// key is the window key of an admitted test operation, or of an operation +// a test opened at the media service under its own name. +func (e *mediaEnv) key(uid string) string { + if operation, ok := e.keys[uid]; ok { + return Key(operation) + } + return Key(uid) } func (e *mediaEnv) window(t *testing.T, uid string) Window { t.Helper() - window, found, err := e.central.load(Key(uid)) + window, found, err := e.central.load(e.key(uid)) if err != nil || !found { t.Fatalf("window: %v, %v", found, err) } @@ -476,7 +493,7 @@ func (e *mediaEnv) journaled(uid string) map[string]site.StepState { journal, _ := e.store.Journal(device) out := map[string]site.StepState{} for _, entry := range journal { - if entry.Operation == uid { + if entry.Operation == e.keys[uid] { out[entry.Step] = entry.State } } @@ -517,7 +534,7 @@ func TestAVirtualMediaInstallIsProvenByItsFirstBootReport(t *testing.T) { if !window.Closed || window.ConfigMedium != nil || window.Report == nil || window.Duplicates != 0 || window.Rejected != 0 { t.Fatalf("window = %+v", window) } - transfers, err := e.central.Transfers(Key("op-media")) + transfers, err := e.central.Transfers(e.key("op-media")) if err != nil || len(transfers) != 2 || !transfers[0].Complete || !transfers[1].Complete { t.Fatalf("transfers = %+v, %v", transfers, err) } @@ -534,14 +551,14 @@ func TestAVirtualMediaInstallIsProvenByItsFirstBootReport(t *testing.T) { var site mediaWindow e.store.GetRecord(device, mediaRecords, "op-media", &site) siteRecord, _ := json.Marshal(site) - central, _ := os.ReadFile(filepath.Join(e.central.Root, "windows", Key("op-media")+".json")) + central, _ := os.ReadFile(filepath.Join(e.central.Root, "windows", e.key("op-media")+".json")) for _, text := range [][]byte{journal, siteRecord, central, result.Evidence} { if len(token) != 64 || strings.Contains(string(text), token) { t.Fatal("a record carries the report token") } } // The closed window serves nothing, even to its BMC. - if _, code := e.bmc.call(http.MethodGet, BootMediumURL(e.origin, Key("op-media"), window.BootDigest), ""); code != http.StatusForbidden { + if _, code := e.bmc.call(http.MethodGet, BootMediumURL(e.origin, e.key("op-media"), window.BootDigest), ""); code != http.StatusForbidden { t.Fatalf("closed window served the boot medium: %d", code) } } @@ -587,7 +604,7 @@ func TestAStaleFenceCannotPrepareMedia(t *testing.T) { if got := e.bmc.log(); strings.Join(got, ",") != "insert CD1" { t.Fatalf("BMC requests after the fence rose = %v, want only the first insert", got) } - if _, code := e.bmc.call(http.MethodGet, BootMediumURL(e.origin, Key("op-stale"), e.window(t, "op-stale").BootDigest), ""); code != http.StatusForbidden { + if _, code := e.bmc.call(http.MethodGet, BootMediumURL(e.origin, e.key("op-stale"), e.window(t, "op-stale").BootDigest), ""); code != http.StatusForbidden { t.Fatalf("a window custody no longer names served media: %d", code) } // A delayed worker at the old fence is refused by the site store. @@ -613,7 +630,7 @@ func TestTheMediaServiceOpensAWindowOnlyForCustodysOperation(t *testing.T) { if result.Phase != ops.PhaseFailed || result.Reason != custody.ReasonMediaWindowRefused || len(e.bmc.log()) != 0 { t.Fatalf("result = %+v, BMC %v", result, e.bmc.log()) } - if _, found, _ := e.central.load(Key("op-unadmitted")); found { + if _, found, _ := e.central.load(e.key("op-unadmitted")); found { t.Fatal("the media service opened a window custody does not name") } } @@ -964,7 +981,7 @@ func TestARefusedWindowOpenFailsOnlyWhenNothingReachedTheBMC(t *testing.T) { if err := e.store.Raise(device, 1); err != nil { t.Fatal(err) } - if _, _, err := e.store.IntendWithPayload(device, 1, "op-refused", "media-clear-cd1", nil); err != nil { + if _, _, err := e.store.IntendWithPayload(device, 1, assignment.Key(), "media-clear-cd1", nil); err != nil { t.Fatal(err) } } From 9c82c3978cfb4808a9dd5a72c0838da2ff500bf1 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Fri, 27 Nov 2026 16:26:09 -0600 Subject: [PATCH 19/35] ci(multiplane): Run the virtual media suite The virtual media suite assumed Colima: its Docker context, and the host gateway lab Pods use to reach the workstation's media service. run.sh records the host address and the network Pods arrive from: the host gateway and loopback under Colima, the kind network's gateway and subnet on a CI runner. The certificate, the media service's listeners and the report relay's upstream use them. The workflow runs the suite as a third mode, in one shard. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/multiplane-acceptance.yml | 14 ++++++++++---- .../site/redfish/services/kustomization.yaml | 2 +- hack/multiplane/acceptance-media.sh | 2 +- hack/multiplane/flux.py | 4 +++- hack/multiplane/media-central.sh | 19 ++++++++++++++----- hack/multiplane/media_steps.py | 2 +- hack/multiplane/redfish_steps.py | 7 +++++-- hack/multiplane/run.sh | 13 ++++++++++++- hack/multiplane/test-harness.sh | 2 +- 9 files changed, 48 insertions(+), 17 deletions(-) diff --git a/.github/workflows/multiplane-acceptance.yml b/.github/workflows/multiplane-acceptance.yml index 1337e476..c99d7869 100644 --- a/.github/workflows/multiplane-acceptance.yml +++ b/.github/workflows/multiplane-acceptance.yml @@ -11,7 +11,7 @@ on: mode: description: Site provider type: choice - options: [both, localvm, redfish] + options: [both, localvm, redfish, media] default: both groups: description: Scenario groups @@ -40,8 +40,14 @@ jobs: strategy: fail-fast: false matrix: - mode: ${{ fromJSON(github.event_name == 'workflow_dispatch' && inputs.mode != 'both' && format('["{0}"]', inputs.mode) || '["localvm","redfish"]') }} - group: ${{ fromJSON((github.event_name == 'pull_request' || (github.event_name == 'workflow_dispatch' && inputs.groups == 'split')) && '["flux","release"]' || '["all"]') }} + # Each shard is one suite in one scenario group. A labeled pull request + # run, or a manual run that asks for split, runs the local VM and + # Redfish suites as their flux and release shards; the nightly run, and + # a manual run unless it asks for split, runs each in the all group. The + # virtual media suite (run.sh --redfish --virtual-media) always runs as + # one all shard: its scenarios are one ordered sequence of installs. + # Both selects every suite. + include: ${{ fromJSON(github.event_name == 'workflow_dispatch' && inputs.mode == 'media' && '[{"mode":"media","group":"all"}]' || github.event_name == 'workflow_dispatch' && inputs.mode == 'localvm' && (inputs.groups == 'split' && '[{"mode":"localvm","group":"flux"},{"mode":"localvm","group":"release"}]' || '[{"mode":"localvm","group":"all"}]') || github.event_name == 'workflow_dispatch' && inputs.mode == 'redfish' && (inputs.groups == 'split' && '[{"mode":"redfish","group":"flux"},{"mode":"redfish","group":"release"}]' || '[{"mode":"redfish","group":"all"}]') || (github.event_name == 'pull_request' || (github.event_name == 'workflow_dispatch' && inputs.groups == 'split')) && '[{"mode":"localvm","group":"flux"},{"mode":"localvm","group":"release"},{"mode":"redfish","group":"flux"},{"mode":"redfish","group":"release"},{"mode":"media","group":"all"}]' || '[{"mode":"localvm","group":"all"},{"mode":"redfish","group":"all"},{"mode":"media","group":"all"}]') }} # A newer labeled run for the same pull request replaces an older one; # nightly and manual runs never cancel each other. A cancelled run never # counts as passed. @@ -134,7 +140,7 @@ jobs: - name: Run multi-plane acceptance (${{ matrix.mode }}) timeout-minutes: 100 env: - TASK: ${{ matrix.mode == 'localvm' && 'multiplane:acceptance' || 'multiplane:redfish-acceptance' }} + TASK: ${{ matrix.mode == 'localvm' && 'multiplane:acceptance' || matrix.mode == 'media' && 'multiplane:media-acceptance' || 'multiplane:redfish-acceptance' }} run: | mkdir -m 0700 "$FLEET_MULTIPLANE_STATE_ROOT" task "$TASK" diff --git a/config/site/redfish/services/kustomization.yaml b/config/site/redfish/services/kustomization.yaml index 52ae0236..72f25892 100644 --- a/config/site/redfish/services/kustomization.yaml +++ b/config/site/redfish/services/kustomization.yaml @@ -33,7 +33,7 @@ patches: - name: report-relay image: "${FLEET_SITE_IMAGE}" imagePullPolicy: IfNotPresent - command: [fleet-multiplane, report-relay, --listen, "192.168.77.1:28443", --upstream, "192.168.5.2:28444"] + command: [fleet-multiplane, report-relay, --listen, "192.168.77.1:28443", --upstream, "${FLEET_MEDIA_HOST}:28444"] securityContext: runAsUser: 65534 runAsNonRoot: true diff --git a/hack/multiplane/acceptance-media.sh b/hack/multiplane/acceptance-media.sh index 292267cf..85b01421 100755 --- a/hack/multiplane/acceptance-media.sh +++ b/hack/multiplane/acceptance-media.sh @@ -8,7 +8,7 @@ set -euo pipefail umask 077 state=${1:?private state directory} -export DOCKER_CONTEXT=colima-fleet-acceptance-tcg FLEET_SITE_PROVIDER=redfish +export DOCKER_CONTEXT=${FLEET_MULTIPLANE_DOCKER_CONTEXT:-colima-fleet-acceptance-tcg} FLEET_SITE_PROVIDER=redfish host="$state/fleet-multiplane-host" ph() { python3 hack/multiplane/harness.py phase --state "$state" --name "$1" --timeout "$2" --echo -- "${@:3}"; } rf() { ph "redfish-$1" "$2" python3 hack/multiplane/redfish_steps.py "$1" "$state"; } diff --git a/hack/multiplane/flux.py b/hack/multiplane/flux.py index 2548fd8b..5d377039 100644 --- a/hack/multiplane/flux.py +++ b/hack/multiplane/flux.py @@ -319,7 +319,9 @@ def stage(args): FLEET_SITE_DISPATCH='true' if args.site == 'dispatch' else 'false', FLEET_LOCAL_VM_ACCEL=harness.ACCEL, # The central media service's certificate (public), so # Redfish workers verify it; empty where none runs. - FLEET_MEDIA_CA=env.get('mediaCA', '')) + FLEET_MEDIA_CA=env.get('mediaCA', ''), + # Where lab Pods reach the central media service. + FLEET_MEDIA_HOST=(s / 'media-host').read_text().strip() if (s / 'media-host').exists() else '192.168.5.2') if args.bad_kro_chart: patches.append(child_patch('kro', [{'target': {'kind': 'OCIRepository', 'name': 'kro-chart'}, 'patch': '- op: replace\n path: /spec/ref/digest\n value: %s\n' % MISSING_DIGEST}], diff --git a/hack/multiplane/media-central.sh b/hack/multiplane/media-central.sh index b7bd5562..5005f1e1 100755 --- a/hack/multiplane/media-central.sh +++ b/hack/multiplane/media-central.sh @@ -27,12 +27,21 @@ case $action in docker rm "$id" >/dev/null fi mkdir -p "$state/media-central" && chmod 0700 "$state/media-central" - # Clients: lab Pods arrive on loopback, and installed servers' reports - # through the relay with their own lab network addresses. - nohup "$state/fleet-multiplane-host" media-service --config "$state/acceptance.json" --listen "127.0.0.1:28443,[::1]:28443" \ - --proxy-listen 127.0.0.1:28444 --relays 127.0.0.0/8 \ + # Lab Pods reach the service at the runtime's host address: under Colima + # its gateway, which arrives on loopback; on a CI runner the kind network's + # gateway, from the kind nodes' addresses. + listen="127.0.0.1:28443,[::1]:28443" relay_listen=127.0.0.1:28444 + if [[ ${FLEET_MULTIPLANE_RUNTIME:-colima} == ci ]]; then + host=$(cat "$state/media-host") + listen="$listen,$host:28443" relay_listen="$relay_listen,$host:28444" + fi + # Clients: lab Pods, and installed servers' reports through the relay + # with their own lab network addresses. + clients=$(cat "$state/media-clients") + nohup "$state/fleet-multiplane-host" media-service --config "$state/acceptance.json" --listen "$listen" \ + --proxy-listen "$relay_listen" --relays "127.0.0.0/8,$clients" \ --tls-cert "$state/redfish/media-tls.crt" --tls-key "$state/redfish/media-tls.key" --client-ca "$state/redfish/media-worker-ca.crt" \ - --state-dir "$state/media-central" --artifacts "$artifacts" --clients 127.0.0.0/8,::1/128,192.168.77.0/24 >>"$state/media-central.log" 2>&1 >"$state/media-central.log" 2>&1 "$pidfile" sleep 2 kill -0 "$(cat "$pidfile")" || { echo 'media-central: exited at start; see media-central.log in the state directory' >&2; exit 1; } diff --git a/hack/multiplane/media_steps.py b/hack/multiplane/media_steps.py index 6e23a5c6..e0b94c14 100644 --- a/hack/multiplane/media_steps.py +++ b/hack/multiplane/media_steps.py @@ -388,7 +388,7 @@ def release_proof(s): denials = [] for op in ops: w = window_record(s, op_key(op)) - url = 'https://%s:%d/media/%s/boot/%s/boot.iso' % (rf.MEDIA_HOST, rf.MEDIA_PORT, key(op_key(op)), w['bootDigest']) + url = 'https://%s:%d/media/%s/boot/%s/boot.iso' % (rf.media_host(s), rf.MEDIA_PORT, key(op_key(op)), w['bootDigest']) probe = ("import ssl,sys,urllib.request,urllib.error\nc=ssl.create_default_context(cafile='/etc/fleet-bmc-media-ca/ca.crt')\n" "try:\n urllib.request.urlopen(sys.argv[1],context=c,timeout=20); print(200)\nexcept urllib.error.HTTPError as e: print(e.code)\n") answer = rf.bmc(s, 'python3', '-c', probe, url).stdout.strip() diff --git a/hack/multiplane/redfish_steps.py b/hack/multiplane/redfish_steps.py index b4260248..466eb0dd 100644 --- a/hack/multiplane/redfish_steps.py +++ b/hack/multiplane/redfish_steps.py @@ -51,7 +51,10 @@ BOOT_IP = '10.96.0.80' # The workstation as lab Pods and guests reach it (the Colima host gateway), # where the central media service listens on loopback. -MEDIA_HOST = '192.168.5.2' +def media_host(s): + """Where lab Pods reach the central media service, as run.sh recorded + it for the runtime.""" + return (s / 'media-host').read_text().strip() # The report relay on the lab bridge, where guests post their reports. REPORT_RELAY = '192.168.77.1' MEDIA_PORT = 28443 @@ -189,7 +192,7 @@ def enroll(s): # gateway. The lab BMC, the workers and the installed OS verify it # against this certificate. subprocess.run(['openssl', 'req', '-x509', '-newkey', 'ec', '-pkeyopt', 'ec_paramgen_curve:prime256v1', '-nodes', '-keyout', str(d / 'media-tls.key'), - '-out', str(d / 'media-tls.crt'), '-days', '2', '-subj', '/CN=fleet-lab-media', '-addext', 'subjectAltName=IP:%s,IP:%s,IP:127.0.0.1,IP:::1' % (MEDIA_HOST, REPORT_RELAY)], + '-out', str(d / 'media-tls.crt'), '-days', '2', '-subj', '/CN=fleet-lab-media', '-addext', 'subjectAltName=IP:%s,IP:%s,IP:127.0.0.1,IP:::1' % (media_host(s), REPORT_RELAY)], check=True, capture_output=True) # Site workers authenticate to the central media service with client # certificates from a CA generated per run: the cell's workers, and one diff --git a/hack/multiplane/run.sh b/hack/multiplane/run.sh index 74647fef..7a5ba2d3 100755 --- a/hack/multiplane/run.sh +++ b/hack/multiplane/run.sh @@ -132,6 +132,17 @@ ph flux-tools 300 "${flux[@]}" tools "$state" docker network inspect kind >/dev/null 2>&1 || docker network create kind >/dev/null # Disposable infrastructure only: registry and three kind clusters, no services. ph topology 900 bash hack/multiplane/topology.sh "$state" +# Where lab Pods reach this host's central media service, and the network +# their connections arrive from: Colima's host gateway, which arrives on +# loopback, or on a CI runner the kind network's gateway and subnet. +if [[ $FLEET_MULTIPLANE_RUNTIME == ci ]]; then + docker network inspect kind -f '{{range .IPAM.Config}}{{.Gateway}} {{.Subnet}}{{"\n"}}{{end}}' | + awk -v host="$state/media-host" -v clients="$state/media-clients" '$1 ~ /^[0-9.]+$/ {print $1 > host; print $2 > clients; exit}' + [[ -s $state/media-host && -s $state/media-clients ]] || { echo 'the kind network has no IPv4 gateway' >&2; exit 1; } +else + printf '192.168.5.2\n' > "$state/media-host" + printf '127.0.0.0/8\n' > "$state/media-clients" +fi ph site-image-push 600 bash hack/multiplane/site.sh push "$state" # Revision 1: platform services only. The bootstrap boundary applies each # cluster's Flux components and sync objects once; Flux then owns them too. @@ -155,7 +166,7 @@ c={'State':str(s),'HubKubeconfig':str(s/'management-hub.json'),'Cell':(s/'prefix # virtual media suite adds virtual media as an operator would. 'DeliveryMethods':[{'method':'NetworkBoot'}], # The central media service, as lab Pods and guests reach the workstation. - 'MediaService':'https://192.168.5.2:28443'} + 'MediaService':'https://%s:28443'%(s/'media-host').read_text().strip()} if sys.argv[3]=='1':c['BootAddressClass']='lab-provisioning' (s/'acceptance.json').write_text(json.dumps(c)) PY diff --git a/hack/multiplane/test-harness.sh b/hack/multiplane/test-harness.sh index b1b21865..60f6dcff 100755 --- a/hack/multiplane/test-harness.sh +++ b/hack/multiplane/test-harness.sh @@ -371,7 +371,7 @@ with tempfile.TemporaryDirectory() as tmp: # the all group, so release follows the Flux disruptions somewhere in CI. workflow = (root / '.github/workflows/multiplane-acceptance.yml').read_text() check('pull requests split, nightly and manual runs combine', - "group: ${{ fromJSON((github.event_name == 'pull_request' || (github.event_name == 'workflow_dispatch' && inputs.groups == 'split')) && '[\"flux\",\"release\"]' || '[\"all\"]') }}" in workflow + "(github.event_name == 'pull_request' || (github.event_name == 'workflow_dispatch' && inputs.groups == 'split')) && '[{\"mode\":\"localvm\",\"group\":\"flux\"},{\"mode\":\"localvm\",\"group\":\"release\"},{\"mode\":\"redfish\",\"group\":\"flux\"},{\"mode\":\"redfish\",\"group\":\"release\"},{\"mode\":\"media\",\"group\":\"all\"}]' || '[{\"mode\":\"localvm\",\"group\":\"all\"},{\"mode\":\"redfish\",\"group\":\"all\"},{\"mode\":\"media\",\"group\":\"all\"}]') }}" in workflow and 'options: [all, split]\n default: all' in workflow and "if: always() && matrix.group != 'flux'" in workflow and '--group "$FLEET_MULTIPLANE_GROUP"' in workflow and '[ "$RESULT" = success ]' in workflow) # Each group gates exactly its scenarios in both suites; the rest run in every group. From 202a78566a648470d0e4bc6c7367bf80024edf86 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Fri, 27 Nov 2026 18:44:16 -0600 Subject: [PATCH 20/35] ci(multiplane): Shorten the media suite's windows Each held media installation waited out the lab's 5 and 10 minute windows. On CI the fetch window is 2 minutes, which covers the BMC fetching the boot medium after a held install settles, and the report window 3 minutes. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/multiplane-acceptance.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.github/workflows/multiplane-acceptance.yml b/.github/workflows/multiplane-acceptance.yml index c99d7869..2565eb25 100644 --- a/.github/workflows/multiplane-acceptance.yml +++ b/.github/workflows/multiplane-acceptance.yml @@ -141,6 +141,10 @@ jobs: timeout-minutes: 100 env: TASK: ${{ matrix.mode == 'localvm' && 'multiplane:acceptance' || matrix.mode == 'media' && 'multiplane:media-acceptance' || 'multiplane:redfish-acceptance' }} + # The virtual media suite's lab windows, short enough for KVM guests: + # each held installation waits out both. + FLEET_MULTIPLANE_MEDIA_FETCH: ${{ matrix.mode == 'media' && '2m0s' || '' }} + FLEET_MULTIPLANE_MEDIA_REPORT: ${{ matrix.mode == 'media' && '3m0s' || '' }} run: | mkdir -m 0700 "$FLEET_MULTIPLANE_STATE_ROOT" task "$TASK" From 128d3373ddb854cc136e1b5a104f702919a5952b Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sat, 28 Nov 2026 19:06:53 -0600 Subject: [PATCH 21/35] feat(custody): Network-boot wipes and commissionings only where offered A wipe and a commissioning only network-boot. Admission now refuses either with DeliveryMethodNotOffered unless every serving site offers network boot, and the Metal provider neither creates a release wipe nor claims a boot address for one at a site that does not, so the release reports why. A site that declares only virtual media, or nothing, never uses its DHCP, boot addresses or boot NIC attachment. Burn-in timing reads the boot server's write-complete lines, which virtual media does not write; no burn-in runs over virtual media. Co-Authored-By: Claude Opus 5.5 --- docs/development/device-custody.md | 12 +++++++ internal/allocation/allocator.go | 4 +++ internal/allocation/bootaddress_test.go | 47 +++++++++++++++++++++++++ internal/allocation/release.go | 5 +++ internal/custody/commissioning.go | 6 ++++ internal/custody/commissioning_test.go | 25 +++++++++++++ internal/custody/delivery.go | 22 ++++++++++-- internal/custody/delivery_test.go | 27 ++++++++++++++ internal/custody/kinds.go | 2 +- 9 files changed, 147 insertions(+), 3 deletions(-) diff --git a/docs/development/device-custody.md b/docs/development/device-custody.md index f2712f86..9c3e0d2b 100644 --- a/docs/development/device-custody.md +++ b/docs/development/device-custody.md @@ -336,6 +336,18 @@ operations guide describes how it runs in the [Redfish lab](../operations/redfis pinned by digest. The admission snapshot records the method, so a recovery hold records it too. A settling installation must use the held method, and a wipe cannot settle a virtual media hold. +- **Wipes and commissionings need network boot.** Both only network-boot, + so admission refuses either with `DeliveryMethodNotOffered` unless every + serving site offers network boot. The Metal provider makes no release wipe, + and claims no boot address for one, at a site that does not offer it, and + the release reports why. A site that declares only virtual media, or + nothing, therefore never uses its DHCP, boot addresses or boot NIC + attachment. +- **Burn-in timing stays network boot only.** Burn-in starts when the boot + server finished delivering the image, from its `write-complete` lines. + Virtual media writes none: the central media service records the BMC's + fetches. No burn-in runs over virtual media, because commissioning + records no delivery method and admission refuses it without network boot. - **Workers dispatch on the method.** The Redfish install worker hands the install to the method's own steps; network boot is unchanged. The local VM and simulator workers refuse any method but network boot. diff --git a/internal/allocation/allocator.go b/internal/allocation/allocator.go index ef775bbe..ef3a61b7 100644 --- a/internal/allocation/allocator.go +++ b/internal/allocation/allocator.go @@ -182,6 +182,10 @@ var ErrNoReportAddress = errors.New("allocation: virtual media needs an address // is qualified for, so nothing can install it. var ErrNoDeliveryMethod = errors.New("allocation: the site offers no delivery method the server is qualified for") +// ErrNoWipeMethod means the site offers no network boot, the only method a +// wipe uses, so a release cannot wipe the server there. +var ErrNoWipeMethod = errors.New("allocation: the site offers no network boot, the only method a wipe uses") + // selectDelivery reads the Device and its custody and selects the method an // installation records. func (a *Allocator) selectDelivery(ctx context.Context, allocation *fleetv1.MachineAllocation) (ops.DeliveryInput, error) { diff --git a/internal/allocation/bootaddress_test.go b/internal/allocation/bootaddress_test.go index 6c960001..41af79d6 100644 --- a/internal/allocation/bootaddress_test.go +++ b/internal/allocation/bootaddress_test.go @@ -151,6 +151,53 @@ func TestTheDefaultAllocatorClaimsNoBootAddress(t *testing.T) { } } +// TestAReleaseWipesOnlyWhereTheSiteOffersNetworkBoot releases a server at a +// site that offers only virtual media. A wipe network-boots, its only +// method, so release makes no wipe and claims no boot address there, even +// with a boot address source configured, and says why. +func TestAReleaseWipesOnlyWhereTheSiteOffersNetworkBoot(t *testing.T) { + e := startEnv(t) + recorder := &ipam{Client: e.admin} + e.allocator.Provider, e.allocator.Releaser = writer{recorder, "DeviceInstallation"}, writer{recorder, "DeviceWipe"} + e.allocator.BootAddresses = &bootaddress.Claimer{Class: "provisioning"} + e.allocator.DeliveryMethods = []custody.OfferedMethod{{Method: ops.DeliveryVirtualMedia, Addresses: ops.AddressesDataNetwork, MediaService: "https://192.0.2.10:8443"}} + e.server(1) + allocation, err := e.allocator.Allocate(e.ctx, e.request(1)) + if err != nil { + t.Fatal(err) + } + // Release begins, closes the gates before cleaning, then stops at the + // wipe. + var last error + for range 20 { + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(allocation), allocation); err != nil { + t.Fatal(err) + } + released, err := e.allocator.Release(e.ctx, allocation, machine(1)) + if released { + t.Fatal("the allocation was released without a wipe") + } + if last = err; last != nil { + break + } + } + if !errors.Is(last, ErrNoWipeMethod) { + t.Fatalf("release = %v, want %v", last, ErrNoWipeMethod) + } + if allocation.Status.Wipe != nil { + t.Fatalf("release recorded wipe %+v", allocation.Status.Wipe) + } + var wipes ops.DeviceWipeList + if err := e.admin.List(e.ctx, &wipes); err != nil || len(wipes.Items) != 0 { + t.Fatalf("wipes = %d, %v, want none", len(wipes.Items), err) + } + for _, name := range recorder.created() { + if name != allocation.Name { + t.Fatalf("release created %s; it may create nothing", name) + } + } +} + // TestBootAddressesFollowTheirOperations claims each installation's and // wipe's boot address before the operation exists, carries it into the // admitted inputs, and releases a claim only once its operation ended and diff --git a/internal/allocation/release.go b/internal/allocation/release.go index f7f78c6c..8f2e24f5 100644 --- a/internal/allocation/release.go +++ b/internal/allocation/release.go @@ -317,6 +317,11 @@ func (a *Allocator) clean(ctx context.Context, state *ops.DeviceCustody, allocat // wipe records the wipe in status, then creates it, so a crash between the // two creates the same wipe again. func (a *Allocator) wipe(ctx context.Context, allocation *fleetv1.MachineAllocation, reference fleetv1.WipeReference) error { + // A wipe network-boots, the only method it has. Where the site offers + // no network boot, nothing claims a boot address and no wipe is made. + if !custody.NetworkBootOffered(a.DeliveryMethods) { + return ErrNoWipeMethod + } if current := allocation.Status.Wipe; current == nil || *current != reference { allocation.Status.Wipe = &reference if err := a.Provider.Status().Update(ctx, allocation); err != nil { diff --git a/internal/custody/commissioning.go b/internal/custody/commissioning.go index 11981215..5cd25ac1 100644 --- a/internal/custody/commissioning.go +++ b/internal/custody/commissioning.go @@ -232,6 +232,7 @@ func DeviceCommissioningKind() Kind { {Name: ReasonPlanMismatch, RaisedBy: RaisedByBoth}, {Name: ReasonDeviceNotActive, RaisedBy: RaisedByCoordinator}, {Name: ReasonBootInterfaceUnknown, RaisedBy: RaisedByCoordinator}, + {Name: ReasonDeliveryNotOffered, RaisedBy: RaisedByCoordinator}, {Name: ReasonTargetUnsupported, RaisedBy: RaisedByWorker}, {Name: ReasonInputsUnreadable, RaisedBy: RaisedByWorker}, }, @@ -256,6 +257,11 @@ func checkCommissioning(ctx context.Context, admission *Admission) *Refusal { if !hasBootInterface(admission.Device) { return refuse(ReasonBootInterfaceUnknown, "the Device records no interface %q with a MAC address", CommissioningBootInterface) } + // Burn-in boots its image over the network, and its timing starts when + // the boot server finished delivering it. + if refusal := requireNetworkBoot(admission, "a commissioning"); refusal != nil { + return refusal + } if admission.Reader == nil { return refuse(ReasonPlanNotQualified, "the plan could not be read") } diff --git a/internal/custody/commissioning_test.go b/internal/custody/commissioning_test.go index 33b50ccf..cc23f6c7 100644 --- a/internal/custody/commissioning_test.go +++ b/internal/custody/commissioning_test.go @@ -272,6 +272,31 @@ func TestCommissioning(t *testing.T) { e.requirePhase(operation, ops.PhaseFailed, ReasonPlanMismatch) }) + t.Run("a site that offers no network boot refuses commissioning", func(t *testing.T) { + e, device := next(t, "no-network-boot") + plan := e.plan("no-network-boot-v1", "no-network-boot", planAuthor) + e.approve(plan, planApprover) + defer func() { + e.sites.mu.Lock() + e.sites.methods = nil + e.sites.mu.Unlock() + }() + // Burn-in boots over the network only, so neither a site that + // offers only virtual media nor one that declares nothing may run it. + for name, methods := range map[string][]OfferedMethod{"only virtual media": {{Method: ops.DeliveryVirtualMedia, Addresses: ops.AddressesDataNetwork, MediaService: "https://192.0.2.10:8443"}}, "nothing": {}} { + e.sites.mu.Lock() + e.sites.methods = methods + e.sites.mu.Unlock() + before := e.custody(device.Name).Spec.Fence + operation := e.commission(device, plan, plan.Spec.Content) + e.settle(device.Name) + e.requirePhase(operation, ops.PhaseFailed, ReasonDeliveryNotOffered) + if custody := e.custody(device.Name); custody.Spec.Fence != before || custody.Spec.Holder.Type != ops.HolderNone { + t.Fatalf("%s: a refusal changed custody: %+v", name, custody.Spec) + } + } + }) + t.Run("an inactive Device is refused", func(t *testing.T) { e, device := next(t, "inactive") plan := e.plan("inactive-v1", "inactive", planAuthor) diff --git a/internal/custody/delivery.go b/internal/custody/delivery.go index 09ec789a..5d49bb55 100644 --- a/internal/custody/delivery.go +++ b/internal/custody/delivery.go @@ -262,12 +262,30 @@ func checkDelivery(admission *Admission, spec *ops.DeviceInstallationSpec) *Refu // checkWipeDelivery refuses a wipe that would settle an installation hold // prepared with a method other than network boot, the only method a wipe -// uses: it could not prove that method's release. +// uses: it could not prove that method's release. It also refuses a wipe +// where the sites serving the Device do not offer network boot. func checkWipeDelivery(admission *Admission) *Refusal { if held, ok := HeldMethod(admission.Custody, "DeviceInstallation"); ok && held != ops.DeliveryNetworkBoot { return refuse(ReasonDeliveryMismatch, "the held installation was prepared with %s, which a wipe cannot release", held) } - return nil + return requireNetworkBoot(admission, "a wipe") +} + +// requireNetworkBoot refuses an operation that only network-boots, a wipe +// or a commissioning, unless every site serving the Device offers network +// boot. A site that declares only virtual media, or declares nothing, never +// network-boots a server, so its DHCP, boot addresses and boot NIC +// attachments are never used. +func requireNetworkBoot(admission *Admission, what string) *Refusal { + if NetworkBootOffered(admission.Offered) { + return nil + } + return refuse(ReasonDeliveryNotOffered, "no site serving the Device offers network boot, the only method %s uses", what) +} + +// NetworkBootOffered reports whether the offer includes network boot. +func NetworkBootOffered(offered []OfferedMethod) bool { + return slices.ContainsFunc(offered, func(offer OfferedMethod) bool { return offer.Method == ops.DeliveryNetworkBoot }) } // NetworkBootOnly is the declaration of a site that offers only network diff --git a/internal/custody/delivery_test.go b/internal/custody/delivery_test.go index abb5b8b3..12e8a53f 100644 --- a/internal/custody/delivery_test.go +++ b/internal/custody/delivery_test.go @@ -280,6 +280,33 @@ func TestDeliveryMethodAdmission(t *testing.T) { e.requireUntouched(device.Name, custody.Spec.Fence) }) + t.Run("a wipe is refused where no site offers network boot", func(t *testing.T) { + for name, methods := range map[string][]OfferedMethod{"only virtual media": {{Method: ops.DeliveryVirtualMedia, Addresses: ops.AddressesDataNetwork, MediaService: mediaService}}, "nothing": {}} { + t.Run(name, func(t *testing.T) { + e := e.sub(t) + device := held(e, "") + allocation := "alloc-d-" + device.Name + if err := e.coord.BeginRelease(e.ctx, device.Name, allocation); err != nil { + t.Fatal(err) + } + e.settle(device.Name) + e.sites.mu.Lock() + e.sites.methods = methods + e.sites.mu.Unlock() + defer func() { + e.sites.mu.Lock() + e.sites.methods = nil + e.sites.mu.Unlock() + }() + fence := e.custody(device.Name).Spec.Fence + wipe := e.wipe(device, allocation, 1) + e.settle(device.Name) + e.requirePhase(wipe, ops.PhaseFailed, ReasonDeliveryNotOffered) + e.requireUntouched(device.Name, fence) + }) + } + }) + t.Run("an unpinned installer download is refused", func(t *testing.T) { e := e.sub(t) device := held(e, "VirtualMedia") diff --git a/internal/custody/kinds.go b/internal/custody/kinds.go index e94cf2a0..a3fdc7f0 100644 --- a/internal/custody/kinds.go +++ b/internal/custody/kinds.go @@ -231,7 +231,7 @@ func DeviceWipeKind() Kind { // settled by a later wipe only after a DeviceRecovery with Retry. Settles: []SettleRule{{Held: "DeviceInstallation"}, {Held: "DeviceWipe", RequiresRetry: true}}, Retryable: true, - Reasons: append(append([]Reason{{Name: ReasonDeliveryMismatch, RaisedBy: RaisedByCoordinator}}, networkBootReasons...), workerReasons...), + Reasons: append(append([]Reason{{Name: ReasonDeliveryMismatch, RaisedBy: RaisedByCoordinator}, {Name: ReasonDeliveryNotOffered, RaisedBy: RaisedByCoordinator}}, networkBootReasons...), workerReasons...), Evidence: StrictEvidence(evidenceLimit, func(_ ops.Operation, evidence *ops.WipeEvidence) error { if len(evidence.WipedDisks) > 16 { return errors.New("evidence records at most 16 disks") From 78fdc743229fcd8bdb9ef4381762162523205671 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sat, 28 Nov 2026 19:06:54 -0600 Subject: [PATCH 22/35] fix(lab): Accept a medium's mount before fetching it The lab BMC fetched a medium inside the InsertMedia request. A slow fetch outlasted the worker's 30 second Redfish timeout, so the worker recorded the insert as lost and the install ended unknown, as in 3 of 9 media runs. As a BMC does, the lab BMC now accepts the mount at once and fetches in the background. A power-on during a fetch answers at once, reports On, and starts the target once its media are fetched; a ForceOff cancels it. A medium ejected during its fetch keeps nothing, and one that cannot be fetched stays inserted but is never attached. Each insert's lab fault is chosen with the insert, from the config medium's URL, and recorded there. Co-Authored-By: Claude Opus 5.5 --- docs/operations/redfish-lab.md | 5 +- hack/redfish-lab/fake_virsh.py | 3 +- hack/redfish-lab/fleet_lab_adapter.py | 144 ++++++++++++++++++++------ hack/redfish-lab/test_adapter.py | 122 ++++++++++++++++++++-- 4 files changed, 230 insertions(+), 44 deletions(-) diff --git a/docs/operations/redfish-lab.md b/docs/operations/redfish-lab.md index 27f19d2c..0bd4beb1 100644 --- a/docs/operations/redfish-lab.md +++ b/docs/operations/redfish-lab.md @@ -551,7 +551,8 @@ seam; the regular Redfish suite above covers it. fence. 3. The worker ejects any leftover media, inserts the boot and config media, reads both URLs back by digest, sets a one-time boot from CD and powers - the server on. The BMC fetches both media over HTTPS it verifies. + the server on. The BMC accepts each insert, then fetches the medium over + HTTPS it verifies. 4. The installer installs the image, reads the bootstrap payload back from disk, and powers off. It reports nothing. 5. The worker boots the installed disk once. At first boot the installed OS @@ -593,7 +594,7 @@ a CI runner's KVM guests. Each held installation waits out both windows. | Qualification | Stubbed. Staff set the `fleet.datumapis.com/qualified-delivery-methods` annotation on the Device. A Device without it is qualified for network boot only. Commissioning will replace it. | | Central media service | Real windows, fences from custody, media, report endpoint, transfer records and a background sweep that drops config media no window can serve. The sweep skips and counts a window file it cannot read, and goes on. In the lab it runs on the workstation beside the coordinator, on loopback, which lab Pods reach through the runtime's host gateway. Guests reach it through the report relay. | | Worker authentication | Real. Each site worker presents a client certificate from the site workers' CA. The certificate is its own Secret, `fleet-site-worker-media`, one per site worker identity, in the `fleet-site-worker-identity` namespace. Each worker gets exactly that Secret through a per-operation Role, and BMC credential Secrets hold only BMC credentials. Only virtual media reads it: network boot installs and wipes neither read nor need it. The service refuses every window operation from a client with no certificate, or one that is not the worker for that Device's site. | -| BMC | Real Redfish VirtualMedia on the lab emulator: two CD devices, insert over verified HTTPS, eject, readback, one-time boot from CD. | +| BMC | Real Redfish VirtualMedia on the lab emulator: two CD devices, insert over verified HTTPS, eject, readback, one-time boot from CD. As a BMC does, the lab BMC accepts an insert at once and then fetches the medium, so a slow fetch never outlasts the worker's request. A power-on during a fetch answers at once and starts the target once its media are fetched. A medium the BMC cannot fetch stays inserted but is never attached, so the target boots without it and sends no report. | | First-boot report | Real. The installed lab OS posts it over HTTPS. Bootstrap data is always empty because the sealed store is not on this branch; admission still refuses bootstrap data. | | Installer downloads | Admission refuses any download that is not pinned by digest. The config medium lists the pinned downloads, and the first-boot report names each download by the digest the installer fetched. The worker refuses a report whose downloads are not exactly the recorded ones. The lab installer fetches nothing; it reports what its config medium lists. | | Report source | Real. Each virtual media installation records the Machine's address, which IPAM bound to the operation's own claim. The media service takes the report only from that address, and only inside the site's report ranges; a report from another address in the ranges is refused and recorded, token or not. The path from lab guests to the workstation rewrites their addresses, so guests post to a relay on the lab bridge, which names each guest's address to the service's relay listener in a PROXY protocol header. The service trusts that header only from its configured relays. The installed OS adds its IPAM address beside its DHCP lease and reports from it. The lab proves the service's check, not the network's binding: its relay set is all of loopback, because every lab Pod arrives there, so any lab Pod could name any source and only the report token stops it. Guests cannot reach the relay listener, but on the shared lab bridge a guest can take any lab address, as the stray-source fault does. A real site network, where only the relay or load balancer reaches the relay listener and the data network serves only the Machine its address, still needs verifying. | diff --git a/hack/redfish-lab/fake_virsh.py b/hack/redfish-lab/fake_virsh.py index d936439b..25379edc 100755 --- a/hack/redfish-lab/fake_virsh.py +++ b/hack/redfish-lab/fake_virsh.py @@ -21,7 +21,8 @@ def done(out='', code=0): if cmd == 'define': xml = sys.stdin.read(); name = re.search(r'([^<]+)', xml).group(1) d = s['domains'].setdefault(name, {'running': False, 'starts': []}) - d['uuid'] = re.search(r'([^<]+)', xml).group(1); d['boot'] = re.search(r"([^<]+)', xml).group(1); d['boot'] = re.search(r".*?" - % (media[dev]['file'], target) for dev, target in MEDIA_DEVICES if media.get(dev, {}).get('Inserted')) + % (media[dev]['file'], target) for dev, target in MEDIA_DEVICES if media.get(dev, {}).get('Inserted') and media[dev].get('file')) def domain_xml(t, boot, media=None): @@ -206,6 +212,10 @@ def __init__(self, targets, state, boot_ip): for sid in targets: self.last_reset.setdefault(sid, now()) atomic_write(self.reset_path, self.last_reset) + # In-flight media fetches by (System, device), and power-ons that wait + # for them, by System. Neither survives a restart: a medium whose + # fetch a restart interrupted stays inserted but is never attached. + self.fetches, self.pending = {}, {} def ensure(self, sid): """Define lost libvirt objects (the runtime Pod's libvirt config is not durable).""" @@ -227,6 +237,9 @@ def ensure(self, sid): raise LibvirtError('lab domain identity changed; refusing to control it') def power(self, sid): + if sid in self.pending: + # Powered on, waiting for its media: the firmware has not booted. + return 'On' state = virsh('domstate', self.targets[sid]['domain']) if state in ('running', 'paused', 'idle', 'blocked'): return 'On' @@ -238,6 +251,62 @@ def save(self): atomic_write(self.nvram_path, self.nvram) atomic_write(self.media_path, self.media) + def fetching(self, sid): + return any(s == sid and fetch.is_alive() for (s, _), fetch in self.fetches.items()) + + def fetch_medium(self, sid, dev, insert, url, path, fault, stray): + """Start fetching an accepted medium in the background, then apply the + lab fault its insert took. The medium is attached only once fetched in + full and still the one inserted. Called under LOCK.""" + def run(): + outcome = {} + try: + outcome['bytes'] = fetch(url, path) + applied = {'corrupt-config-token': lambda: corrupt_token(path), 'add-config-download': lambda: add_download(path), + 'add-stray-source': lambda: add_stray_source(path, stray['address'])}.get(fault, lambda: True)() + if not applied: + raise ValueError('the medium did not take the lab fault') + except Exception as e: # noqa: BLE001 the class of failure only, never the URL + outcome = {'fetchError': type(e).__name__} + print('fleet-lab-adapter: %s %s fetch failed: %s' % (sid, dev, type(e).__name__), file=sys.stderr, flush=True) + with LOCK: + current = self.media[sid][dev] + if current.get('insert') != insert or 'fetchError' in outcome: + # Ejected or replaced while it was fetched, or not fetched. + remove(path) + if current.get('insert') == insert: + current.update(outcome, file=None if 'fetchError' in outcome else path) + self.save() + thread = threading.Thread(target=run, daemon=True) + self.fetches[(sid, dev)] = thread + thread.start() + + def defer_power_on(self, sid): + """Power on once the System's media fetches end, within MEDIA_WAIT, as a + server whose firmware waits for its virtual media. Called under LOCK; + a ForceOff in the meantime cancels it. Returns the boot device.""" + token = os.urandom(8).hex() + self.pending[sid] = token + + def run(): + deadline = time.monotonic() + MEDIA_WAIT + for (s, _), fetch in list(self.fetches.items()): + if s == sid: + fetch.join(max(0, deadline - time.monotonic())) + with LOCK: + if self.pending.get(sid) != token: + return + del self.pending[sid] + try: + self.power_on(sid) + except LibvirtError as e: + print('fleet-lab-adapter: %s deferred power-on failed: %s' % (sid, e), file=sys.stderr, flush=True) + threading.Thread(target=run, daemon=True).start() + override = self.nvram[sid] + if override['BootSourceOverrideEnabled'] == 'Once' and override['BootSourceOverrideTarget'] in ('Pxe', 'Hdd', 'Cd'): + return {'Pxe': 'network', 'Hdd': 'hd', 'Cd': 'cdrom'}[override['BootSourceOverrideTarget']] + return 'hd' + def power_on(self, sid): t, boot = self.targets[sid], 'hd' override = self.nvram[sid] @@ -261,10 +330,12 @@ def client(user_agent): return ''.join(c for c in user_agent if ' ' <= c <= '~')[:128] -def is_config(path): - """Whether a fetched medium is a config medium.""" - with open(path, 'rb') as f: - return f.read(15) == b'FLEET-CONFIG-V1' +def remove(path): + for p in (path, path + '.part'): + try: + os.remove(p) + except FileNotFoundError: + pass def corrupt_token(path): @@ -535,29 +606,33 @@ def virtual_media(sid, dev, action): if state['Inserted']: return error(400, 'a medium is already inserted') url = body['Image'] - path = os.path.join(MEDIA_DIR, '%s-%s.img' % (targets[sid]['domain'], dev)) request_context.detail = {'media': dev, 'urlSHA256': hashlib.sha256(url.encode()).hexdigest()} - try: - n = fetch(url, path) - except Exception as e: # noqa: BLE001 the class of failure only, never the URL - request_context.detail.update({'effect': 'fetch-failed', 'error': type(e).__name__}) - return error(400, 'the medium could not be fetched') - if is_config(path) and take('corruptConfig', lambda f: f.get('system') == sid) and corrupt_token(path): - # Lab fault: the medium the BMC holds carries another - # report token than the one the media service served. - request_context.detail['fault'] = 'corrupt-config-token' - elif is_config(path) and take('addDownload', lambda f: f.get('system') == sid) and add_download(path): - # Lab fault: the medium the BMC holds lists a download the - # operation never pinned. - request_context.detail['fault'] = 'add-config-download' - elif is_config(path) and (stray := take('straySource', lambda f: f.get('system') == sid)) and add_stray_source(path, stray['address']): - # Lab fault: another server in the site's ranges posts the - # report with the right token before the Machine does. - request_context.detail['fault'] = 'add-stray-source' + # A BMC accepts the mount, then fetches the medium. The insert's + # lab fault, which only a config medium takes, is chosen now and + # recorded with the insert; the fetch applies it. + fault, stray = None, None + if urllib.parse.urlsplit(url).path.split('/')[3:4] == ['config']: + if take('corruptConfig', lambda f: f.get('system') == sid): + # Lab fault: the medium the BMC holds carries another + # report token than the one the media service served. + fault = 'corrupt-config-token' + elif take('addDownload', lambda f: f.get('system') == sid): + # Lab fault: the medium the BMC holds lists a download + # the operation never pinned. + fault = 'add-config-download' + elif stray := take('straySource', lambda f: f.get('system') == sid): + # Lab fault: another server in the site's ranges posts the + # report with the right token before the Machine does. + fault = 'add-stray-source' + insert = os.urandom(8).hex() + path = os.path.join(MEDIA_DIR, '%s-%s-%s.img' % (targets[sid]['domain'], dev, insert)) with LOCK: - lab.media[sid][dev] = {'Inserted': True, 'Image': url, 'file': path} + lab.media[sid][dev] = {'Inserted': True, 'Image': url, 'file': None, 'insert': insert} lab.save() - request_context.detail.update({'effect': 'inserted', 'bytes': n}) + lab.fetch_medium(sid, dev, insert, url, path, fault, stray) + request_context.detail['effect'] = 'inserted' + if fault: + request_context.detail['fault'] = fault return '', 204 if set(body) - {'Inserted'}: return error(400, 'unsupported EjectMedia parameters') @@ -566,10 +641,7 @@ def virtual_media(sid, dev, action): if state['Inserted']: with LOCK: if state.get('file'): - try: - os.remove(state['file']) - except FileNotFoundError: - pass + remove(state['file']) lab.media[sid][dev] = {'Inserted': False, 'Image': None, 'file': None} lab.save() effect = 'ejected' @@ -599,10 +671,14 @@ def reset(sid): power = lab.power(sid) effect = 'none' if kind in ('ForceOff', 'ForceRestart') and power != 'Off': - virsh('destroy', domain) + # A power-on still waiting for media has started nothing. + if lab.pending.pop(sid, None) is None: + virsh('destroy', domain) effect = 'destroyed' if kind in ('On', 'ForceRestart') and (kind == 'ForceRestart' or power == 'Off'): - effect = 'started:' + lab.power_on(sid) + # Answer at once; the target starts once its media are + # fetched, so a slow fetch never outlasts the request. + effect = 'started:' + (lab.defer_power_on(sid) if lab.fetching(sid) else lab.power_on(sid)) publish(sid, lab.power(sid)) except LibvirtError as e: return error(503, 'lab hardware unavailable: %s' % e) diff --git a/hack/redfish-lab/test_adapter.py b/hack/redfish-lab/test_adapter.py index f9da6702..0ac8c295 100644 --- a/hack/redfish-lab/test_adapter.py +++ b/hack/redfish-lab/test_adapter.py @@ -11,6 +11,8 @@ import pathlib import sys import tempfile +import threading +import time import unittest HERE = pathlib.Path(__file__).resolve().parent @@ -40,6 +42,22 @@ def setUpClass(cls): def audit(self): return [json.loads(l) for l in (WORK / 'state' / 'audit.log').read_text().splitlines()] + def media(self, dev): + """System-1's stored state for one virtual media device.""" + return json.loads((WORK / 'state' / 'media.json').read_text())['System-1'][dev] + + def until(self, what, condition): + for _ in range(250): + if condition(): + return + time.sleep(0.02) + self.fail(what) + + def fetched(self, dev): + """Wait until the device's fetch ended, then return its state.""" + self.until('the %s fetch never ended' % dev, lambda: not self.media(dev)['Inserted'] or self.media(dev).get('file') or self.media(dev).get('fetchError')) + return self.media(dev) + def test_1_service_root_is_upstream_and_unauthenticated(self): r = self.app.get('/redfish/v1/') self.assertEqual(r.status_code, 200) @@ -188,6 +206,7 @@ def fake_fetch(url, path): self.assertEqual(self.app.post(insert, headers=AUTH, json={'Image': url, 'TransferProtocolType': 'NFS'}).status_code, 400) self.assertEqual(self.app.post(insert, headers=AUTH, json={'Image': url, 'Inserted': True, 'WriteProtected': True, 'TransferProtocolType': 'HTTPS'}).status_code, 204) self.assertEqual(self.app.post(insert, headers=AUTH, json={'Image': url}).status_code, 400) + self.fetched('CD1') self.assertEqual(fetched, [url]) cd1 = self.app.get(base + '/CD1', headers=AUTH).json self.assertEqual((cd1['Inserted'], cd1['Image']), (True, url)) @@ -197,8 +216,12 @@ def fake_fetch(url, path): self.app.patch('/redfish/v1/Systems/System-1', headers=AUTH, json={'Boot': {'BootSourceOverrideTarget': 'Cd', 'BootSourceOverrideEnabled': 'Once'}}) self.app.post('/redfish/v1/Systems/System-1/Actions/ComputerSystem.Reset', headers=AUTH, json={'ResetType': 'On'}) self.assertEqual(virsh_state()['domains']['fleet-lab-target-a']['starts'][-1], 'cdrom') + self.assertEqual(virsh_state()['domains']['fleet-lab-target-a']['media'], [self.media('CD1')['file']]) self.app.post('/redfish/v1/Systems/System-1/Actions/ComputerSystem.Reset', headers=AUTH, json={'ResetType': 'ForceOff'}) - # A corrupted config medium carries another report token. + # A config medium, served under /config/, takes a lab fault chosen + # with its insert and applied once it is fetched. A corrupted + # config medium carries another report token. + config = 'https://10.96.0.80:8443/media/k/config/c/config.img' def config_fetch(url, path): # Padded with zeros, as the media service renders it. pathlib.Path(path).write_bytes((b'FLEET-CONFIG-V1\ntoken=' + b'a' * 64 + b'\nend\n').ljust(8192, b'\0')) @@ -208,27 +231,28 @@ def config_fetch(url, path): cd2 = self.app.get(base + '/CD2', headers=AUTH).json self.assertEqual(self.app.post(cd2['Actions']['#VirtualMedia.InsertMedia']['target'], headers=AUTH, json={'Image': url}).status_code, 204) self.assertNotIn('fault', self.audit()[-1]) + self.fetched('CD2') self.app.post(cd2['Actions']['#VirtualMedia.EjectMedia']['target'], headers=AUTH, json={}) adapter.fetch = config_fetch - self.assertEqual(self.app.post(cd2['Actions']['#VirtualMedia.InsertMedia']['target'], headers=AUTH, json={'Image': url}).status_code, 204) + self.assertEqual(self.app.post(cd2['Actions']['#VirtualMedia.InsertMedia']['target'], headers=AUTH, json={'Image': config}).status_code, 204) self.assertEqual(self.audit()[-1].get('fault'), 'corrupt-config-token') - held = (WORK / 'media' / 'fleet-lab-target-a-CD2.img').read_bytes() + held = pathlib.Path(self.fetched('CD2')['file']).read_bytes() self.assertIn(b'token=', held) self.assertNotIn(b'a' * 64, held) self.app.post(cd2['Actions']['#VirtualMedia.EjectMedia']['target'], headers=AUTH, json={}) # A config medium can gain a download the operation never pinned. adapter.fault_cli(['add-download', 'System-1']) - self.assertEqual(self.app.post(cd2['Actions']['#VirtualMedia.InsertMedia']['target'], headers=AUTH, json={'Image': url}).status_code, 204) + self.assertEqual(self.app.post(cd2['Actions']['#VirtualMedia.InsertMedia']['target'], headers=AUTH, json={'Image': config}).status_code, 204) self.assertEqual(self.audit()[-1].get('fault'), 'add-config-download') - held = (WORK / 'media' / 'fleet-lab-target-a-CD2.img').read_bytes().rstrip(b'\0') + held = pathlib.Path(self.fetched('CD2')['file']).read_bytes().rstrip(b'\0') self.assertIn(b'\ndownload=extension registry.example/extension@sha256:', held) self.assertTrue(held.endswith(b'\nend\n')) self.app.post(cd2['Actions']['#VirtualMedia.EjectMedia']['target'], headers=AUTH, json={}) # A config medium can gain a stray report source. adapter.fault_cli(['stray-source', 'System-1', '192.168.77.250']) - self.assertEqual(self.app.post(cd2['Actions']['#VirtualMedia.InsertMedia']['target'], headers=AUTH, json={'Image': url}).status_code, 204) + self.assertEqual(self.app.post(cd2['Actions']['#VirtualMedia.InsertMedia']['target'], headers=AUTH, json={'Image': config}).status_code, 204) self.assertEqual(self.audit()[-1].get('fault'), 'add-stray-source') - held = (WORK / 'media' / 'fleet-lab-target-a-CD2.img').read_bytes().rstrip(b'\0') + held = pathlib.Path(self.fetched('CD2')['file']).read_bytes().rstrip(b'\0') self.assertTrue(held.endswith(b'\nstraysource=192.168.77.250\nend\n')) self.app.post(cd2['Actions']['#VirtualMedia.EjectMedia']['target'], headers=AUTH, json={}) # A withheld eject response still ejects. @@ -243,6 +267,90 @@ def config_fetch(url, path): finally: adapter.fetch = real + def test_9_an_insert_answers_before_its_medium_is_fetched(self): + """A BMC accepts the mount, then fetches the medium, so a slow fetch + never outlasts the insert request. A power-on during the fetch answers + at once and starts the target only once its medium is in.""" + release = threading.Event() + + def slow_fetch(url, path): + if not release.wait(10): + raise TimeoutError('the test never released the fetch') + pathlib.Path(path).write_bytes(b'medium') + return 6 + adapter.fetch, real = slow_fetch, adapter.fetch + os.makedirs(adapter.MEDIA_DIR, exist_ok=True) + system = '/redfish/v1/Systems/System-1' + url = 'https://10.96.0.80:8443/media/k/boot/d/boot.iso' + + def post(path, body): + return self.app.post(system + path, headers=AUTH, json=body).status_code + + def starts(): + return virsh_state()['domains']['fleet-lab-target-a']['starts'] + try: + post('/Actions/ComputerSystem.Reset', {'ResetType': 'ForceOff'}) + began = time.monotonic() + self.assertEqual(post('/VirtualMedia/CD1/Actions/VirtualMedia.InsertMedia', {'Image': url}), 204) + self.assertLess(time.monotonic() - began, 5) + self.assertEqual(self.audit()[-1]['effect'], 'inserted') + cd1 = self.app.get(system + '/VirtualMedia/CD1', headers=AUTH).json + self.assertEqual((cd1['Inserted'], cd1['Image']), (True, url)) + self.assertIsNone(self.media('CD1')['file']) + # Boot once from CD while the fetch runs. + self.app.patch(system, headers=AUTH, json={'Boot': {'BootSourceOverrideTarget': 'Cd', 'BootSourceOverrideEnabled': 'Once'}}) + before = len(starts()) + self.assertEqual(post('/Actions/ComputerSystem.Reset', {'ResetType': 'On'}), 204) + self.assertEqual(self.audit()[-1]['effect'], 'started:cdrom') + self.assertEqual(self.app.get(system, headers=AUTH).json['PowerState'], 'On') + self.assertEqual(len(starts()), before, 'the target started before its medium was fetched') + release.set() + self.until('the target never started', lambda: len(starts()) == before + 1) + domain = virsh_state()['domains']['fleet-lab-target-a'] + self.assertEqual((domain['starts'][-1], domain['media']), ('cdrom', [self.media('CD1')['file']])) + self.assertEqual(self.app.get(system, headers=AUTH).json['Boot']['BootSourceOverrideEnabled'], 'Disabled') + post('/Actions/ComputerSystem.Reset', {'ResetType': 'ForceOff'}) + post('/VirtualMedia/CD1/Actions/VirtualMedia.EjectMedia', {}) + + # A ForceOff while a power-on waits for its media cancels it. + release.clear() + self.assertEqual(post('/VirtualMedia/CD1/Actions/VirtualMedia.InsertMedia', {'Image': url}), 204) + before = len(starts()) + self.assertEqual(post('/Actions/ComputerSystem.Reset', {'ResetType': 'On'}), 204) + self.assertEqual(post('/Actions/ComputerSystem.Reset', {'ResetType': 'ForceOff'}), 204) + self.assertEqual(self.audit()[-1]['effect'], 'destroyed') + self.assertEqual(self.app.get(system, headers=AUTH).json['PowerState'], 'Off') + release.set() + self.fetched('CD1') + time.sleep(0.2) + self.assertEqual(len(starts()), before, 'a cancelled power-on started the target') + post('/VirtualMedia/CD1/Actions/VirtualMedia.EjectMedia', {}) + + # An eject during the fetch keeps nothing of it. + release.clear() + self.assertEqual(post('/VirtualMedia/CD1/Actions/VirtualMedia.InsertMedia', {'Image': url}), 204) + self.assertEqual(post('/VirtualMedia/CD1/Actions/VirtualMedia.EjectMedia', {}), 204) + release.set() + time.sleep(0.2) + self.assertEqual(self.media('CD1'), {'Inserted': False, 'Image': None, 'file': None}) + self.assertEqual([f for f in os.listdir(adapter.MEDIA_DIR) if '-CD1-' in f], []) + + # A medium that cannot be fetched stays inserted, as the BMC + # accepted it, but is never attached. + def failing_fetch(url, path): + raise OSError('the media service is unreachable') + adapter.fetch = failing_fetch + self.assertEqual(post('/VirtualMedia/CD1/Actions/VirtualMedia.InsertMedia', {'Image': url}), 204) + state = self.fetched('CD1') + self.assertEqual((state['Inserted'], state['file'], state['fetchError']), (True, None, 'OSError')) + self.assertEqual(post('/Actions/ComputerSystem.Reset', {'ResetType': 'On'}), 204) + self.assertEqual(virsh_state()['domains']['fleet-lab-target-a']['media'], []) + post('/Actions/ComputerSystem.Reset', {'ResetType': 'ForceOff'}) + post('/VirtualMedia/CD1/Actions/VirtualMedia.EjectMedia', {}) + finally: + adapter.fetch = real + release.set() + def test_7_synced_dhcp_network_has_no_dhcp_server(self): targets = {'System-1': {'mac': '52:54:00:77:01:0a', 'ip': '192.168.77.10'}} static = adapter.network_xml(targets, '10.96.0.80', 'static') From b87e2af0de688259bc874d816e57a6e4a006344f Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sat, 28 Nov 2026 19:06:54 -0600 Subject: [PATCH 23/35] fix(site): Close relayed connections nothing accepted A relayed connection with a valid PROXY header waited forever to be handed to Accept once the listener closed, holding its goroutine and its connection. Closing the listener, or its failing, now closes every connection not yet accepted. Co-Authored-By: Claude Opus 5.5 --- internal/site/redfishwork/proxy.go | 22 ++++++++++++--- internal/site/redfishwork/proxy_test.go | 36 +++++++++++++++++++++++++ 2 files changed, 55 insertions(+), 3 deletions(-) diff --git a/internal/site/redfishwork/proxy.go b/internal/site/redfishwork/proxy.go index 9687449a..148001d4 100644 --- a/internal/site/redfishwork/proxy.go +++ b/internal/site/redfishwork/proxy.go @@ -8,6 +8,7 @@ import ( "slices" "strconv" "strings" + "sync" "time" ) @@ -21,20 +22,24 @@ const maxProxyHeader = 107 // report's source even when the path to it does not keep source addresses. // It drops any connection from outside trusted, and any whose header is // missing or malformed, before TLS starts. Each header is read on its own, -// so a slow peer delays only its own connection. +// so a slow peer delays only its own connection. Once the listener is closed +// or fails, a connection that has not been accepted is closed, so no reader +// waits on it. type ProxyListener struct { net.Listener trusted []netip.Prefix onDrop func(error) ready chan net.Conn failed chan error + done chan struct{} + stop sync.Once } // NewProxyListener wraps a listener. trusted are the relays' own // addresses; only they may name a source. onDrop, when set, is told why a // connection was dropped. func NewProxyListener(inner net.Listener, trusted []netip.Prefix, onDrop func(error)) *ProxyListener { - l := &ProxyListener{Listener: inner, trusted: trusted, onDrop: onDrop, ready: make(chan net.Conn), failed: make(chan error, 1)} + l := &ProxyListener{Listener: inner, trusted: trusted, onDrop: onDrop, ready: make(chan net.Conn), failed: make(chan error, 1), done: make(chan struct{})} go l.accept() return l } @@ -44,6 +49,7 @@ func (l *ProxyListener) accept() { conn, err := l.Listener.Accept() if err != nil { l.failed <- err + l.stop.Do(func() { close(l.done) }) return } go func() { @@ -55,7 +61,11 @@ func (l *ProxyListener) accept() { } return } - l.ready <- proxied{Conn: conn, source: source} + select { + case l.ready <- proxied{Conn: conn, source: source}: + case <-l.done: + _ = conn.Close() + } }() } } @@ -72,6 +82,12 @@ func (l *ProxyListener) Accept() (net.Conn, error) { } } +// Close stops accepting and closes every connection not yet accepted. +func (l *ProxyListener) Close() error { + l.stop.Do(func() { close(l.done) }) + return l.Listener.Close() +} + // header checks the peer and reads exactly one header line, so the TLS // handshake that follows reads nothing of it. func (l *ProxyListener) header(conn net.Conn) (net.Addr, error) { diff --git a/internal/site/redfishwork/proxy_test.go b/internal/site/redfishwork/proxy_test.go index eca97b0f..a307a4d3 100644 --- a/internal/site/redfishwork/proxy_test.go +++ b/internal/site/redfishwork/proxy_test.go @@ -1,6 +1,7 @@ package redfishwork import ( + "errors" "io" "net" "net/netip" @@ -86,3 +87,38 @@ func TestTheProxyListenerTrustsOnlyItsRelays(t *testing.T) { } } } + +// TestAClosedProxyListenerClosesConnectionsItNeverAccepted keeps no +// connection, and no goroutine waiting to hand it over, once the listener is +// closed: a relayed connection with a valid header that nothing accepted is +// closed. +func TestAClosedProxyListenerClosesConnectionsItNeverAccepted(t *testing.T) { + inner, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + listener := NewProxyListener(inner, []netip.Prefix{netip.MustParsePrefix("127.0.0.0/8")}, nil) + conn, err := net.Dial("tcp", inner.Addr().String()) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + if _, err := io.WriteString(conn, ProxyHeader(netip.MustParseAddrPort("192.0.2.70:40000"), netip.MustParseAddrPort("192.0.2.1:28443"))); err != nil { + t.Fatal(err) + } + if err := listener.Close(); err != nil { + t.Fatal(err) + } + if err := conn.SetReadDeadline(time.Now().Add(5 * time.Second)); err != nil { + t.Fatal(err) + } + // Closed either way: EOF once the header was read, a reset if the + // listener closed before reading it. Only a timeout means it was kept. + var timeout net.Error + if n, err := conn.Read(make([]byte, 1)); err == nil || (errors.As(err, &timeout) && timeout.Timeout()) { + t.Fatalf("read = %d, %v; want the unaccepted connection closed", n, err) + } + if _, err := listener.Accept(); err == nil { + t.Fatal("a closed listener accepted a connection") + } +} From 08af73bd376f8fe97d45c0f31cdb62dac5ca4837 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sat, 28 Nov 2026 19:06:54 -0600 Subject: [PATCH 24/35] test(lab): Match the stale-fence probe's open fields exactly The harness passed when each window open field's name appeared anywhere in the probe, such as a comment. It now reads the keys of the body the probe sends and requires exactly the fields a window open takes. Co-Authored-By: Claude Opus 5.5 --- hack/multiplane/test-harness.sh | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/hack/multiplane/test-harness.sh b/hack/multiplane/test-harness.sh index 60f6dcff..2276a430 100755 --- a/hack/multiplane/test-harness.sh +++ b/hack/multiplane/test-harness.sh @@ -456,13 +456,15 @@ with tempfile.TemporaryDirectory() as tmp: check('dispatch is a source revision', "--site dispatch" in steps and 'patch handoffdispatcher' not in steps) steps_py = (root / 'hack/multiplane/media_steps.py').read_text() # The stale-fence probe's opens must be well-formed, so only the fence - # decides the cell worker's answer: they send every field a window open - # takes. + # decides the cell worker's answer: the body it sends has exactly the + # fields a window open takes, by key, not by a name seen anywhere. + import ast server = (root / 'internal/site/redfishwork/mediaserver.go').read_text() fields = re.findall(r'json:"([a-zA-Z0-9]+)', server[server.index('type OpenRequest struct'):server.index('}', server.index('type OpenRequest struct'))]) - stale = steps_py[steps_py.index('def stale_fence'):steps_py.index('\ndef ', steps_py.index('def stale_fence') + 1)] - missing = [f for f in fields if "'%s'" % f not in stale] - check('the stale-fence probe sends every window open field', fields and not missing, str(missing)) + stale = next(n for n in ast.parse(steps_py).body if isinstance(n, ast.FunctionDef) and n.name == 'stale_fence') + bodies = [n.value for n in ast.walk(stale) if isinstance(n, ast.Assign) and [getattr(t, 'id', None) for t in n.targets] == ['body'] and isinstance(n.value, ast.Dict)] + sent = [k.value for k in bodies[0].keys if isinstance(k, ast.Constant)] if len(bodies) == 1 else [] + check('the stale-fence probe sends exactly the window open fields', fields and sorted(sent) == sorted(fields), 'sent %s, open takes %s' % (sorted(sent), sorted(fields))) arms = re.findall(r'^\s+arm\(([^,)]*)', steps_py, re.M) check('every media lab fault is armed with the run state', arms and all(a == 's' for a in arms), str(arms)) graph = (root / 'config/site/redfish/graph/kustomization.yaml').read_text() From ce8431d29a2ad50ce9e4621a2a705054b2bb4ce6 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sat, 28 Nov 2026 19:52:01 -0600 Subject: [PATCH 25/35] fix(custody): Leave an installation's delivery optional in its schema DeviceInstallation gained a required delivery, so an installation stored before it would fail validation on its next write, including the finalizer removal retention needs. The schema now leaves it optional, and admission still refuses an installation that records no known method; a test covers that refusal. The synthetic manager says why its simulated site declares network boot only. Co-Authored-By: Claude Opus 5.5 --- cmd/fleet-manager/synthetic.go | 3 +++ .../device-operations/crds/fleet.datumapis.com.yaml | 4 +++- internal/api/operations/v1alpha1/types.go | 4 +++- internal/custody/delivery_test.go | 5 +++++ 4 files changed, 14 insertions(+), 2 deletions(-) diff --git a/cmd/fleet-manager/synthetic.go b/cmd/fleet-manager/synthetic.go index dfb89a7e..3a3033da 100644 --- a/cmd/fleet-manager/synthetic.go +++ b/cmd/fleet-manager/synthetic.go @@ -79,6 +79,9 @@ func syntheticCustody(ctx context.Context, scheme *runtime.Scheme, providerConfi return nil, nil, nil, err } namespace := flags.syntheticDeviceNamespace + // The simulator's installs and wipes are simulated, so its declaration + // keeps the lifecycle it always had: it starts no DHCP, claims no boot + // address and attaches no boot NIC, and offers no virtual media. sites := &delivery.Sites{Sites: map[string]delivery.Site{syntheticSite: remote}, Devices: map[string][]string{}, Methods: map[string][]custody.OfferedMethod{syntheticSite: custody.NetworkBootOnly}} for device := range enrollment { deviceNamespace, name, _ := strings.Cut(device, "/") diff --git a/config/components/device-operations/crds/fleet.datumapis.com.yaml b/config/components/device-operations/crds/fleet.datumapis.com.yaml index d805d5bf..61baf224 100644 --- a/config/components/device-operations/crds/fleet.datumapis.com.yaml +++ b/config/components/device-operations/crds/fleet.datumapis.com.yaml @@ -576,6 +576,9 @@ spec: required: - addressClaim - address + # Optional in the schema so installations stored before it + # existed stay valid; admission refuses an installation that + # records no known method. delivery: type: object properties: @@ -643,7 +646,6 @@ spec: - image - bootInterface - targetDisks - - delivery x-kubernetes-validations: - rule: self == oldSelf message: an operation spec is immutable after create diff --git a/internal/api/operations/v1alpha1/types.go b/internal/api/operations/v1alpha1/types.go index ba53831d..ed8da18a 100644 --- a/internal/api/operations/v1alpha1/types.go +++ b/internal/api/operations/v1alpha1/types.go @@ -322,7 +322,9 @@ type DeviceInstallationSpec struct { // A virtual media installation never carries one. BootNetwork *BootNetworkInput `json:"bootNetwork,omitempty"` // Delivery is how the image reaches the server. The requester selects - // it when it creates the operation, and it never changes. + // it when it creates the operation, and it never changes. Admission + // requires it; the schema leaves it optional so installations stored + // before it existed stay valid. Delivery DeliveryInput `json:"delivery"` } diff --git a/internal/custody/delivery_test.go b/internal/custody/delivery_test.go index 12e8a53f..4b6e9200 100644 --- a/internal/custody/delivery_test.go +++ b/internal/custody/delivery_test.go @@ -152,6 +152,11 @@ func TestDeliveryMethodAdmission(t *testing.T) { if refusal := checkDelivery(&Admission{Device: device, Custody: e.custody(device.Name), Offered: e.sites.DeliveryMethods("")}, &ops.DeviceInstallationSpec{Delivery: notURL}); refusal == nil || refusal.Reason != ReasonDeliveryInputs { t.Fatalf("a media service that is not https://IPv4:port: %+v", refusal) } + // The schema leaves delivery optional for installations stored + // before it existed; admission refuses one that records no method. + if refusal := checkDelivery(&Admission{Device: device, Custody: e.custody(device.Name), Offered: e.sites.DeliveryMethods("")}, &ops.DeviceInstallationSpec{}); refusal == nil || refusal.Reason != ReasonDeliveryInputs { + t.Fatalf("an installation with no delivery method: %+v", refusal) + } network := &ops.BootNetworkInput{AddressClaim: fleetv1.TypedReference{APIGroup: "ipam.miloapis.com", Kind: "IPAddressClaim", Name: "claim-example"}, Address: "198.51.100.30"} operation := install(e, device, "request-1", virtualMedia, network) e.settle(device.Name) From f904d6dc917b4085fbcbd9f0745138c3ca2dd434 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sat, 28 Nov 2026 19:52:01 -0600 Subject: [PATCH 26/35] fix(site): Prove media release only with every override disabled The release proof took an override reported enabled but with no target as cleared. Any enabled override now leaves release unproven, so the install ends unknown, and a test covers a BMC that clears only the target. A window the media service refuses also deletes the operation's config medium, which holds its report token, at once: no BMC can fetch it. Co-Authored-By: Claude Opus 5.5 --- internal/site/redfishwork/media.go | 14 ++++++++++---- internal/site/redfishwork/media_test.go | 23 +++++++++++++++++++++++ 2 files changed, 33 insertions(+), 4 deletions(-) diff --git a/internal/site/redfishwork/media.go b/internal/site/redfishwork/media.go index 4f9a326a..3da2a539 100644 --- a/internal/site/redfishwork/media.go +++ b/internal/site/redfishwork/media.go @@ -406,9 +406,13 @@ func (c Config) runMedia(ctx context.Context, work *site.Work, spec ops.DeviceIn window, err := c.window(ctx, work, media, plan) if errors.Is(err, ErrMediaStale) || errors.Is(err, ErrMediaUnauthorized) { // The media service refused the window outright, so it holds no - // window. If the journal shows no BMC step either, nothing reached - // the server and the operation fails; any BMC step leaves it - // unknown. + // window and no BMC can fetch the config medium: delete it, with + // its report token, now. If the journal shows no BMC step either, + // nothing reached the server and the operation fails; any BMC step + // leaves it unknown. + if deleteErr := work.Store().DeleteRecord(work.Device, mediaConfigs, work.Key()); deleteErr != nil { + return nil, errors.Join(err, deleteErr) + } if !bmcStepJournaled(work) { return nil, &site.Unsent{Refusal: &custody.Refusal{Reason: custody.ReasonMediaWindowRefused, Message: err.Error()}} } @@ -761,7 +765,9 @@ func (c Config) releaseMedia(ctx context.Context, work *site.Work, media *mediaC if err != nil { return err } - if power.OverrideEnabled != "Disabled" && power.OverrideTarget != "None" { + // Any enabled override is still set, whatever its target: a cleared one + // is Disabled, while its target may stay as it was. + if power.OverrideEnabled != "Disabled" { return fmt.Errorf("a boot override is still set: %s %s", power.OverrideEnabled, power.OverrideTarget) } status, err := media.device(ctx, work.Device) diff --git a/internal/site/redfishwork/media_test.go b/internal/site/redfishwork/media_test.go index 74ed82c6..3c3716e4 100644 --- a/internal/site/redfishwork/media_test.go +++ b/internal/site/redfishwork/media_test.go @@ -90,6 +90,9 @@ type mediaBMC struct { // lag keeps the server reporting Off, with the override still armed, // for a while after it accepted a power-on, as some BMCs do. lag time.Duration + // enabledAfterBoot keeps the override reported enabled after a boot, + // with no target, as a BMC that clears only the target does. + enabledAfterBoot bool } func selfSigned(t *testing.T) tls.Certificate { @@ -171,6 +174,9 @@ func (b *mediaBMC) ServeHTTP(w http.ResponseWriter, r *http.Request) { } else { b.power = "On" b.enabled, b.target = "Disabled", "None" + if b.enabledAfterBoot { + b.enabled = "Once" + } go b.boot(target) } } @@ -633,6 +639,12 @@ func TestTheMediaServiceOpensAWindowOnlyForCustodysOperation(t *testing.T) { if _, found, _ := e.central.load(e.key("op-unadmitted")); found { t.Fatal("the media service opened a window custody does not name") } + // The config medium, which holds the report token, does not outlive + // the refusal. + var medium configMedium + if found, err := e.store.GetRecord(device, mediaConfigs, assignment.Key(), &medium); err != nil || found { + t.Fatalf("the refused window left its config medium: %v, %v", found, err) + } } // TestALostEjectResponseEndsUnknown withholds the response to the first @@ -664,6 +676,17 @@ func TestALostEjectResponseEndsUnknown(t *testing.T) { } } +// TestAnOverrideStillEnabledIsUnproven has the BMC report its boot override +// still enabled after the boots, though with no target. Release needs the +// override disabled, so the install ends unknown. +func TestAnOverrideStillEnabledIsUnproven(t *testing.T) { + e := newMediaEnv(t) + e.bmc.enabledAfterBoot = true + if result := e.run(t, "op-armed", 1); result.Phase != ops.PhaseOutcomeUnknown || e.journaled("op-armed")["media-released"] != "" { + t.Fatalf("result = %+v", result) + } +} + // TestMediaStillReportedAfterEjectIsUnproven keeps the media inserted // after every eject. func TestMediaStillReportedAfterEjectIsUnproven(t *testing.T) { From 25b511f934a6f2fa10b18a8f2926dff124a3d3c9 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sat, 28 Nov 2026 19:52:02 -0600 Subject: [PATCH 27/35] fix(lab): Change media state only under the adapter's lock The lab BMC read a device's state outside its lock, so two inserts could both be accepted and an eject could miss the medium a racing insert left. Both now read and change it under the lock. A deferred power-on waits for every fetch of its System, including one that starts while it waits. A fetch follows no redirect and uses no proxy. At start the adapter sweeps media files no stored state names, and the test's fake virsh writes its state atomically. Co-Authored-By: Claude Opus 5.5 --- hack/redfish-lab/fake_virsh.py | 5 +- hack/redfish-lab/fleet_lab_adapter.py | 106 ++++++++++++++++---------- 2 files changed, 70 insertions(+), 41 deletions(-) mode change 100755 => 100644 hack/redfish-lab/fleet_lab_adapter.py diff --git a/hack/redfish-lab/fake_virsh.py b/hack/redfish-lab/fake_virsh.py index 25379edc..707ad484 100755 --- a/hack/redfish-lab/fake_virsh.py +++ b/hack/redfish-lab/fake_virsh.py @@ -6,7 +6,10 @@ args = sys.argv[3:] # drop --connect URI s['calls'].append(args[0]) def done(out='', code=0): - json.dump(s, open(state_path, 'w')) + # Atomic, so a reader never sees a half-written state. + with open(state_path + '.tmp', 'w') as f: + json.dump(s, f) + os.replace(state_path + '.tmp', state_path) print(out); sys.exit(code) cmd = args[0] if os.environ.get('FAKE_VIRSH_DOWN'): diff --git a/hack/redfish-lab/fleet_lab_adapter.py b/hack/redfish-lab/fleet_lab_adapter.py old mode 100755 new mode 100644 index d63464cd..d46dc3dd --- a/hack/redfish-lab/fleet_lab_adapter.py +++ b/hack/redfish-lab/fleet_lab_adapter.py @@ -214,8 +214,15 @@ def __init__(self, targets, state, boot_ip): atomic_write(self.reset_path, self.last_reset) # In-flight media fetches by (System, device), and power-ons that wait # for them, by System. Neither survives a restart: a medium whose - # fetch a restart interrupted stays inserted but is never attached. + # fetch a restart interrupted stays inserted but is never attached, + # and its partial file is swept with every other file no state names. self.fetches, self.pending = {}, {} + kept = {d.get('file') for devices in self.media.values() for d in devices.values()} + if os.path.isdir(MEDIA_DIR): + for name in os.listdir(MEDIA_DIR): + path = os.path.join(MEDIA_DIR, name) + if path not in kept and os.path.isfile(path): + os.remove(path) def ensure(self, sid): """Define lost libvirt objects (the runtime Pod's libvirt config is not durable).""" @@ -289,18 +296,22 @@ def defer_power_on(self, sid): self.pending[sid] = token def run(): + # Every fetch of the System counts, including one that starts + # while this waits; each check is under LOCK. deadline = time.monotonic() + MEDIA_WAIT - for (s, _), fetch in list(self.fetches.items()): - if s == sid: - fetch.join(max(0, deadline - time.monotonic())) - with LOCK: - if self.pending.get(sid) != token: - return - del self.pending[sid] - try: - self.power_on(sid) - except LibvirtError as e: - print('fleet-lab-adapter: %s deferred power-on failed: %s' % (sid, e), file=sys.stderr, flush=True) + while True: + with LOCK: + waiting = [f for (s, _), f in self.fetches.items() if s == sid and f.is_alive()] + if not waiting or time.monotonic() >= deadline: + if self.pending.get(sid) != token: + return + del self.pending[sid] + try: + self.power_on(sid) + except LibvirtError as e: + print('fleet-lab-adapter: %s deferred power-on failed: %s' % (sid, e), file=sys.stderr, flush=True) + return + waiting[0].join(max(0, min(1, deadline - time.monotonic()))) threading.Thread(target=run, daemon=True).start() override = self.nvram[sid] if override['BootSourceOverrideEnabled'] == 'Once' and override['BootSourceOverrideTarget'] in ('Pxe', 'Hdd', 'Cd'): @@ -386,6 +397,13 @@ def add_download(path): return True +class NoRedirect(urllib.request.HTTPRedirectHandler): + """Refuse every redirect: the response then fails the fetch.""" + + def redirect_request(self, *args, **kwargs): + return None + + def fetch(url, path): """Fetch a medium the way a BMC does: HTTPS only, to a literal IPv4 endpoint, verifying the lab media service's certificate. Returns the @@ -395,8 +413,11 @@ def fetch(url, path): raise ValueError('media must be fetched over HTTPS without credentials or a query') ipaddress.IPv4Address(u.hostname) context = ssl.create_default_context(cafile=MEDIA_CA) + # No proxy, and no redirect, which could lead away from HTTPS to the + # literal address. + opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), urllib.request.HTTPSHandler(context=context), NoRedirect()) tmp = path + '.part' - with urllib.request.urlopen(url, context=context, timeout=25) as r, open(tmp, 'wb') as f: + with opener.open(url, timeout=25) as r, open(tmp, 'wb') as f: n = 0 while True: chunk = r.read(1 << 20) @@ -597,36 +618,38 @@ def virtual_media(sid, dev, action): body = request.get_json(force=True, silent=True) if not isinstance(body, dict): return error(400, 'a JSON object is required') - state = lab.media[sid][dev] if action == 'InsertMedia': if not set(body) <= {'Image', 'Inserted', 'WriteProtected', 'TransferProtocolType', 'TransferMethod'} or not isinstance(body.get('Image'), str) or body.get('Inserted', True) is not True: return error(400, 'unsupported InsertMedia parameters') if body.get('TransferProtocolType', 'HTTPS') != 'HTTPS': return error(400, 'only HTTPS media are accepted') - if state['Inserted']: - return error(400, 'a medium is already inserted') url = body['Image'] request_context.detail = {'media': dev, 'urlSHA256': hashlib.sha256(url.encode()).hexdigest()} - # A BMC accepts the mount, then fetches the medium. The insert's - # lab fault, which only a config medium takes, is chosen now and - # recorded with the insert; the fetch applies it. - fault, stray = None, None - if urllib.parse.urlsplit(url).path.split('/')[3:4] == ['config']: - if take('corruptConfig', lambda f: f.get('system') == sid): - # Lab fault: the medium the BMC holds carries another - # report token than the one the media service served. - fault = 'corrupt-config-token' - elif take('addDownload', lambda f: f.get('system') == sid): - # Lab fault: the medium the BMC holds lists a download - # the operation never pinned. - fault = 'add-config-download' - elif stray := take('straySource', lambda f: f.get('system') == sid): - # Lab fault: another server in the site's ranges posts the - # report with the right token before the Machine does. - fault = 'add-stray-source' - insert = os.urandom(8).hex() - path = os.path.join(MEDIA_DIR, '%s-%s-%s.img' % (targets[sid]['domain'], dev, insert)) + # The device state is read and changed under LOCK, so two inserts + # cannot both be accepted. with LOCK: + if lab.media[sid][dev]['Inserted']: + return error(400, 'a medium is already inserted') + # A BMC accepts the mount, then fetches the medium. The + # insert's lab fault, which only a config medium takes, is + # chosen now and recorded with the insert; the fetch applies it. + fault, stray = None, None + if urllib.parse.urlsplit(url).path.split('/')[3:4] == ['config']: + if take('corruptConfig', lambda f: f.get('system') == sid): + # Lab fault: the medium the BMC holds carries another + # report token than the one the media service served. + fault = 'corrupt-config-token' + elif take('addDownload', lambda f: f.get('system') == sid): + # Lab fault: the medium the BMC holds lists a download + # the operation never pinned. + fault = 'add-config-download' + elif stray := take('straySource', lambda f: f.get('system') == sid): + # Lab fault: another server in the site's ranges posts + # the report with the right token before the Machine + # does. + fault = 'add-stray-source' + insert = os.urandom(8).hex() + path = os.path.join(MEDIA_DIR, '%s-%s-%s.img' % (targets[sid]['domain'], dev, insert)) lab.media[sid][dev] = {'Inserted': True, 'Image': url, 'file': None, 'insert': insert} lab.save() lab.fetch_medium(sid, dev, insert, url, path, fault, stray) @@ -636,15 +659,18 @@ def virtual_media(sid, dev, action): return '', 204 if set(body) - {'Inserted'}: return error(400, 'unsupported EjectMedia parameters') - drop = take('dropEject', lambda f: f.get('system') == sid and f.get('device') == dev) if state['Inserted'] else None - effect = 'none' - if state['Inserted']: - with LOCK: + with LOCK: + # The state ejected, and the file removed, are the ones inserted + # now, not before LOCK was taken. + state = lab.media[sid][dev] + drop = take('dropEject', lambda f: f.get('system') == sid and f.get('device') == dev) if state['Inserted'] else None + effect = 'none' + if state['Inserted']: if state.get('file'): remove(state['file']) lab.media[sid][dev] = {'Inserted': False, 'Image': None, 'file': None} lab.save() - effect = 'ejected' + effect = 'ejected' request_context.detail = {'media': dev, 'effect': effect} if drop: # Lab fault: the eject is applied, the response is withheld past the client timeout. From b284802f5ec6248cbfcd1f834fb084b6c8821cc3 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sat, 28 Nov 2026 20:14:19 -0600 Subject: [PATCH 28/35] fix(lab): Keep the lab adapter executable Rewriting the adapter dropped its executable bit. Co-Authored-By: Claude Opus 5.5 --- hack/redfish-lab/fleet_lab_adapter.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) mode change 100644 => 100755 hack/redfish-lab/fleet_lab_adapter.py diff --git a/hack/redfish-lab/fleet_lab_adapter.py b/hack/redfish-lab/fleet_lab_adapter.py old mode 100644 new mode 100755 From f80266497a406df7d50fa41be146d581203c3265 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sat, 28 Nov 2026 20:48:33 -0600 Subject: [PATCH 29/35] fix(multiplane): Give IPAM's token to every run with IPAM The lab bootstrap read a variable this branch renames, so it failed in every mode. Runs with IPAM, synchronized DHCP or the virtual media suite, now get its token. Co-Authored-By: Claude Opus 5.5 --- hack/multiplane/milo.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/hack/multiplane/milo.py b/hack/multiplane/milo.py index fb00e5ae..cd03188f 100755 --- a/hack/multiplane/milo.py +++ b/hack/multiplane/milo.py @@ -94,8 +94,8 @@ def write(obj): d.mkdir(mode=0o700) # IPAM delegates TokenReview and SubjectAccessReview to the provider API # as system:masters, as the platform's IPAM client identity does. - # Only synchronized DHCP runs IPAM, so only it gets IPAM's token. - who=('bootstrap','management','customer')+(('coordinator','release','discovery','staff','projector','plan-author','plan-approver','operator','capacity-operator')+(('ipam',) if synced else ()) if role=='provider' else ()) + # Only a run with IPAM, synchronized DHCP or virtual media, gets its token. + who=('bootstrap','management','customer')+(('coordinator','release','discovery','staff','projector','plan-author','plan-approver','operator','capacity-operator')+(('ipam',) if with_ipam else ()) if role=='provider' else ()) tokens={r:secrets.token_hex(32) for r in who} (d/'tokens.csv').write_text('\n'.join(f'{v},{k},{k},'+('system:masters' if k in ('bootstrap','ipam') else 'fleet-local') for k,v in tokens.items())+'\n') run('openssl','req','-x509','-newkey','rsa:2048','-nodes','-keyout',str(d/'tls.key'),'-out',str(d/'tls.crt'),'-days','2','-subj','/CN=fleet-local','-addext',f'subjectAltName=DNS:milo-apiserver.{ns}.svc,IP:127.0.0.1',stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL) From 1f94792ef4295f546c4f0393140e0226e064bed3 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sat, 28 Nov 2026 21:21:51 -0600 Subject: [PATCH 30/35] fix(multiplane): Read the worker's own BMC credential by Device The Redfish worker RBAC check read the handoff's credential field, which the handoff no longer has, so the check failed in every Redfish run. It reads the Device's own credential Secret by name, as the check above it does. Co-Authored-By: Claude Opus 5.5 --- hack/multiplane/k8s_evidence.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hack/multiplane/k8s_evidence.py b/hack/multiplane/k8s_evidence.py index a213c986..7e33ae1f 100644 --- a/hack/multiplane/k8s_evidence.py +++ b/hack/multiplane/k8s_evidence.py @@ -159,7 +159,7 @@ def worker_rbac(state, name): identity_role = get(state, '-n', IDENTITY, 'get', 'role', 'w-' + name) if identity_role['rules'] != [{'apiGroups': [''], 'resources': ['secrets'], 'resourceNames': [IDENTITY_SECRET], 'verbs': ['get']}]: raise SystemExit('Redfish worker identity Role is not get on the one identity Secret: %s' % identity_role['rules']) - keys = sorted(get(state, '-n', CREDENTIALS, 'get', 'secret', spec['credential']).get('data', {})) + keys = sorted(get(state, '-n', CREDENTIALS, 'get', 'secret', own).get('data', {})) if keys != BMC_CREDENTIAL_KEYS: raise SystemExit('the BMC credential Secret holds more than BMC credentials: %s' % keys) record.update(ownCredentialReadable=True, credentialRoleRules=creds['rules'], ownIdentityReadable=True, identityRoleRules=identity_role['rules'], From cec34636843e7281c94d55b3b10df19c46dbef8d Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sat, 28 Nov 2026 21:26:17 -0600 Subject: [PATCH 31/35] fix(multiplane): Commission the media suite's target before allocating Capacity is offered only after a passed commissioning, so the media suite timed out allocating a target it never commissioned. It now commissions target A first, as the Redfish suite does, publishes its dispatch revision after those, and expects the burn-in's one network boot before the media installs. Co-Authored-By: Claude Opus 5.5 --- docs/operations/redfish-lab.md | 1 + hack/multiplane/acceptance-media.sh | 11 ++++++++++- hack/multiplane/media_steps.py | 10 ++++++---- 3 files changed, 17 insertions(+), 5 deletions(-) diff --git a/docs/operations/redfish-lab.md b/docs/operations/redfish-lab.md index 0bd4beb1..df6db388 100644 --- a/docs/operations/redfish-lab.md +++ b/docs/operations/redfish-lab.md @@ -615,6 +615,7 @@ it pulled that reference, installed, and booted the installed disk. | Phase | What it proves | | --- | --- | +| `commission-dispatch` to `commission-settle` | As in the Redfish suite, target A passes a commissioning, whose burn-in boots it once over the network, so the projector offers its capacity. | | `media-not-offered` | While the cell declares network boot only, a virtual media installation is refused with `DeliveryMethodNotOffered`. The fence does not change and nothing is delivered. | | `media-central`, `media-offer` | The central media service starts with the image's pinned artifacts. The operator adds virtual media after network boot; staff record target A as qualified for virtual media only. | | `media-unpinned` | An installation whose installer downloads an image by tag is refused with `InstallDownloadUnpinned`. | diff --git a/hack/multiplane/acceptance-media.sh b/hack/multiplane/acceptance-media.sh index 85b01421..24ed5f3e 100755 --- a/hack/multiplane/acceptance-media.sh +++ b/hack/multiplane/acceptance-media.sh @@ -11,12 +11,21 @@ state=${1:?private state directory} export DOCKER_CONTEXT=${FLEET_MULTIPLANE_DOCKER_CONTEXT:-colima-fleet-acceptance-tcg} FLEET_SITE_PROVIDER=redfish host="$state/fleet-multiplane-host" ph() { python3 hack/multiplane/harness.py phase --state "$state" --name "$1" --timeout "$2" --echo -- "${@:3}"; } +step() { ph "$1" "$2" bash hack/multiplane/steps.sh "$1" "$state"; } rf() { ph "redfish-$1" "$2" python3 hack/multiplane/redfish_steps.py "$1" "$state"; } md() { ph "media-$1" "$2" python3 hack/multiplane/media_steps.py "$1" "$state"; } run() { ph "$1" "$2" "$host" "$1" --config "$state/acceptance.json"; } +# The next source revision after every one published so far. +next_revision() { python3 -c 'import json,sys; print(max(r["revision"] for r in json.load(open(sys.argv[1]))) + 1)' "$state/flux-revisions.json"; } ph rbac 600 python3 hack/multiplane/verify-rbac.py "$state" rf baseline 300 +# Capacity is offered only after a passed commissioning, as in the Redfish +# suite: one revision enables dispatch for it, and the next disables it. +step commission-dispatch 900 +ph commission 1500 "$host" commission --config "$state/acceptance.json" +rf commission-mark 120 +step commission-settle 900 run allocate 900 # The cell declares network boot only: a virtual media installation is # refused at admission and nothing is delivered. @@ -27,7 +36,7 @@ md offer 300 run media-unpinned 600 # Dispatch is a source revision the cell's Flux reconciles, as in the # Redfish suite; kro then creates a worker Job per delivered operation. -ph dispatch 900 python3 hack/multiplane/flux.py publish "$state" --revision 3 --site dispatch --purpose 'enable dispatch' --cluster cell --timeout 600 +ph dispatch 900 python3 hack/multiplane/flux.py publish "$state" --revision "$(next_revision)" --site dispatch --purpose 'enable dispatch' --cluster cell --timeout 600 # The first install's report carries another token: it is held. md arm-corrupt-token 120 run media-install-held 3000 diff --git a/hack/multiplane/media_steps.py b/hack/multiplane/media_steps.py index e0b94c14..fd37d77c 100644 --- a/hack/multiplane/media_steps.py +++ b/hack/multiplane/media_steps.py @@ -11,7 +11,7 @@ the central media service and the lab's short phases, and restarts the coordinator; staff record target A as qualified for virtual media only (the lab stand-in for - commissioning) + delivery qualification by commissioning) arm-corrupt-token one-shot: the lab BMC's next config medium carries another report token than the one the media service served held-report the first install booted from media and its OS posted a @@ -186,7 +186,7 @@ def offer(s): provider(s, '-n', 'fleet-provider', 'annotate', '--overwrite', 'device', DEVICE_NAME, QUALIFIED + '=VirtualMedia') subprocess.run(['bash', 'hack/multiplane/coordinator.sh', 'restart', str(s)], check=True, capture_output=True, text=True) rf.write(s / 'evidence' / 'media-offer.json', {'observedAt': now(), 'deliveryMethods': config['DeliveryMethods'], - 'qualified': {'device': harness.DEVICE, 'methods': ['VirtualMedia'], 'source': 'lab-set annotation; commissioning is not implemented'}}) + 'qualified': {'device': harness.DEVICE, 'methods': ['VirtualMedia'], 'source': 'lab-set annotation; commissioning does not qualify delivery methods yet'}}) print('media-offer: the cell declares NetworkBoot then VirtualMedia (central media service, %s fetch and %s report phases); target A is qualified for VirtualMedia only; coordinator restarted' % (FETCH, REPORT)) @@ -477,8 +477,10 @@ def first(block): 'mutatingRedfishRequests': len(rf.mutating(entries, b['system']))} if not record['targetB']['diskSHA256Unchanged'] or record['targetB']['qemuStarts'] or record['targetB']['mutatingRedfishRequests']: die('target B was touched: %s' % record['targetB']) - if starts != ['cdrom', 'disk'] * 4: - die('expected target A to boot from media then disk, four times; got %s' % starts) + # The commissioning that makes target A allocatable network-boots its + # burn-in once, before any install. + if starts != ['network'] + ['cdrom', 'disk'] * 4: + die('expected target A to boot its burn-in from the network, then from media then disk four times; got %s' % starts) rf.write(s / 'evidence' / 'virtual-media.json', record) # Every check above passed. Only result.json, which run.sh writes last, # records whether the run passed. From fe7863f884d59a7e7e948e9aaa30d0220f48a55b Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sun, 29 Nov 2026 00:51:39 -0600 Subject: [PATCH 32/35] fix(lab): Stamp a deferred power-on's reset when it is accepted A power-on that waits for its media started the target later, and only then moved the System's reset time, so a reader right after the reset saw the old time. A BMC reports the reset when it accepts it: the deferred power-on now stamps the time then, and the later start leaves it. Co-Authored-By: Claude Opus 5.5 --- hack/redfish-lab/fleet_lab_adapter.py | 22 +++++++++++++++------- hack/redfish-lab/test_adapter.py | 9 ++++++++- 2 files changed, 23 insertions(+), 8 deletions(-) diff --git a/hack/redfish-lab/fleet_lab_adapter.py b/hack/redfish-lab/fleet_lab_adapter.py index d46dc3dd..401d5228 100755 --- a/hack/redfish-lab/fleet_lab_adapter.py +++ b/hack/redfish-lab/fleet_lab_adapter.py @@ -16,7 +16,8 @@ firmware.json, which upstream does not serve, so a commissioning plan's firmware baseline can be checked against the lab; * LastResetTime, persisted per System and moved forward each time a reset - starts the domain; + starts the domain, or, for a power-on that waits for media, when the + reset is accepted; * VirtualMedia on each System: two CD devices with InsertMedia, which accepts the mount at once and then fetches the image over HTTPS, verifying the lab media service's CA, as a BMC does, and EjectMedia, @@ -291,9 +292,12 @@ def run(): def defer_power_on(self, sid): """Power on once the System's media fetches end, within MEDIA_WAIT, as a server whose firmware waits for its virtual media. Called under LOCK; - a ForceOff in the meantime cancels it. Returns the boot device.""" + a ForceOff in the meantime cancels it. The reset time is the time the + reset was accepted, as a BMC reports it, not the later start. Returns + the boot device.""" token = os.urandom(8).hex() self.pending[sid] = token + self.stamp_reset(sid) def run(): # Every fetch of the System counts, including one that starts @@ -307,7 +311,7 @@ def run(): return del self.pending[sid] try: - self.power_on(sid) + self.power_on(sid, stamp=False) except LibvirtError as e: print('fleet-lab-adapter: %s deferred power-on failed: %s' % (sid, e), file=sys.stderr, flush=True) return @@ -318,7 +322,12 @@ def run(): return {'Pxe': 'network', 'Hdd': 'hd', 'Cd': 'cdrom'}[override['BootSourceOverrideTarget']] return 'hd' - def power_on(self, sid): + def stamp_reset(self, sid): + # The System came out of a reset now, as a BMC reports it. + self.last_reset[sid] = now() + atomic_write(self.reset_path, self.last_reset) + + def power_on(self, sid, stamp=True): t, boot = self.targets[sid], 'hd' override = self.nvram[sid] if override['BootSourceOverrideEnabled'] == 'Once' and override['BootSourceOverrideTarget'] in ('Pxe', 'Hdd', 'Cd'): @@ -329,9 +338,8 @@ def power_on(self, sid): require_accelerator() virsh('define', '/dev/stdin', input=domain_xml(t, boot, self.media[sid])) virsh('start', t['domain']) - # The System came out of a reset now, as a BMC reports it. - self.last_reset[sid] = now() - atomic_write(self.reset_path, self.last_reset) + if stamp: + self.stamp_reset(sid) return boot diff --git a/hack/redfish-lab/test_adapter.py b/hack/redfish-lab/test_adapter.py index 0ac8c295..82b6d25f 100644 --- a/hack/redfish-lab/test_adapter.py +++ b/hack/redfish-lab/test_adapter.py @@ -299,13 +299,20 @@ def starts(): self.assertIsNone(self.media('CD1')['file']) # Boot once from CD while the fetch runs. self.app.patch(system, headers=AUTH, json={'Boot': {'BootSourceOverrideTarget': 'Cd', 'BootSourceOverrideEnabled': 'Once'}}) - before = len(starts()) + before, reset = len(starts()), self.app.get(system, headers=AUTH).json['LastResetTime'] + time.sleep(1.1) self.assertEqual(post('/Actions/ComputerSystem.Reset', {'ResetType': 'On'}), 204) self.assertEqual(self.audit()[-1]['effect'], 'started:cdrom') self.assertEqual(self.app.get(system, headers=AUTH).json['PowerState'], 'On') self.assertEqual(len(starts()), before, 'the target started before its medium was fetched') + # The reset time moves when the reset is accepted, not at the + # later start. + accepted = self.app.get(system, headers=AUTH).json['LastResetTime'] + self.assertGreater(accepted, reset) + time.sleep(1.1) release.set() self.until('the target never started', lambda: len(starts()) == before + 1) + self.assertEqual(self.app.get(system, headers=AUTH).json['LastResetTime'], accepted) domain = virsh_state()['domains']['fleet-lab-target-a'] self.assertEqual((domain['starts'][-1], domain['media']), ('cdrom', [self.media('CD1')['file']])) self.assertEqual(self.app.get(system, headers=AUTH).json['Boot']['BootSourceOverrideEnabled'], 'Disabled') From e451f8c3e8d19d0d9f1ba545d8a4350529d87a3a Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sun, 29 Nov 2026 01:18:20 -0600 Subject: [PATCH 33/35] test(manager): Declare network boot for the customer power site The customer power test merged from the power stack declares no boot delivery method, so its release wipe waits for network boot forever. It now declares network boot only, as the other simulated sites do. Co-Authored-By: Claude Opus 5.5 --- internal/manager/customer_power_envtest_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/internal/manager/customer_power_envtest_test.go b/internal/manager/customer_power_envtest_test.go index 937d22fe..4bcf3e1f 100644 --- a/internal/manager/customer_power_envtest_test.go +++ b/internal/manager/customer_power_envtest_test.go @@ -120,7 +120,7 @@ func startEnv(t *testing.T) *env { if err != nil { t.Fatal(err) } - sites := &delivery.Sites{Sites: map[string]delivery.Site{siteName: remote}, Devices: map[string][]string{}} + sites := &delivery.Sites{Sites: map[string]delivery.Site{siteName: remote}, Devices: map[string][]string{}, Methods: map[string][]custody.OfferedMethod{siteName: custody.NetworkBootOnly}} coordinator := &custody.Coordinator{Client: admin, Registry: registry, Sites: sites, Config: custody.Config{Namespace: namespace, Principals: custody.Principals{ custody.CreatorMetalProvider: {{Username: providerUser}}, custody.CreatorReleaseController: {{Username: releaseUser}}, }}} @@ -129,7 +129,7 @@ func startEnv(t *testing.T) *env { e.allocator = &allocation.Allocator{ Provider: admin, ProviderCreator: ops.Creator{Username: providerUser, UID: uid(801)}, Releaser: admin, ReleaseCreator: ops.Creator{Username: releaseUser, UID: uid(802)}, - Custody: coordinator, Namespace: namespace, + Custody: coordinator, DeliveryMethods: custody.NetworkBootOnly, Namespace: namespace, Cleaning: func(string) (string, error) { return policyDigest, nil }, BootInterface: "primary", TargetDisks: []string{"disk-0"}, Capacity: fixtureOffers{}, From 8b94f85d17ccafd787a20de99a0b1550f2351919 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sun, 29 Nov 2026 01:33:35 -0600 Subject: [PATCH 34/35] fix(lab): Leave a failed deferred power-on Off A power-on that waits for its media reported On and moved the reset time before it was marked pending, so a failed reset-time write left a System reporting On with nothing to start it. A start that failed consumed the boot-once override anyway. The adapter now stamps the reset time first, and a failed start restores the override and leaves the System Off. A cancelled wait ends at its next check rather than at the media deadline, and the lab docs name the accept-time stamp. Co-Authored-By: Claude Opus 5.5 --- docs/operations/redfish-lab.md | 2 +- hack/redfish-lab/fake_virsh.py | 2 ++ hack/redfish-lab/fleet_lab_adapter.py | 31 +++++++++++++++-------- hack/redfish-lab/test_adapter.py | 36 +++++++++++++++++++++++++++ 4 files changed, 59 insertions(+), 12 deletions(-) diff --git a/docs/operations/redfish-lab.md b/docs/operations/redfish-lab.md index df6db388..0babb37d 100644 --- a/docs/operations/redfish-lab.md +++ b/docs/operations/redfish-lab.md @@ -91,7 +91,7 @@ does not fork or patch upstream files. | `ComputerSystem.Reset` with `On`, `ForceOff` and `ForceRestart` applied to one exact persistent libvirt domain per System | Adapter (replaces upstream's in-memory handler for the two lab Systems) | | `PowerState` read from libvirt on every System read | Adapter | | `Boot` source override (`Pxe` or `Hdd`, `Once`), persisted in NVRAM state on the site volume and consumed at power-on | Adapter | -| `LastResetTime`, set for each System when the adapter first starts, persisted on the site volume, and moved forward each time a reset starts the domain | Adapter | +| `LastResetTime`, set for each System when the adapter first starts, persisted on the site volume, and moved forward each time a reset starts the domain or, for a power-on that waits for media, when the reset is accepted | Adapter | | `ResetType` and boot `AllowableValues` narrowed to what the adapter implements; System `UUID` and `SerialNumber` set from the lab target | Adapter | | No `Storage` link on the lab Systems: upstream's sample `Storage` drives are not the target's disk, so commissioning reads the populated `SimpleStorage` device | Adapter | | A read-only `UpdateService` and `FirmwareInventory` from `firmware.json`, synthetic versions upstream does not serve, so a commissioning plan's firmware baseline can be checked | Adapter | diff --git a/hack/redfish-lab/fake_virsh.py b/hack/redfish-lab/fake_virsh.py index 707ad484..afa7e609 100755 --- a/hack/redfish-lab/fake_virsh.py +++ b/hack/redfish-lab/fake_virsh.py @@ -30,6 +30,8 @@ def done(out='', code=0): d = s['domains'].get(args[1]); done(d['uuid']) if d else done(code=1) if cmd == 'domstate': done('running' if s['domains'][args[1]]['running'] else 'shut off') +if cmd == 'start' and os.environ.get('FAKE_VIRSH_FAIL_START'): + print('start failed', file=sys.stderr); done(code=1) if cmd == 'start': d = s['domains'][args[1]]; d['running'] = True; d['starts'].append(d['boot']); done() if cmd == 'destroy': diff --git a/hack/redfish-lab/fleet_lab_adapter.py b/hack/redfish-lab/fleet_lab_adapter.py index 401d5228..c607ebe1 100755 --- a/hack/redfish-lab/fleet_lab_adapter.py +++ b/hack/redfish-lab/fleet_lab_adapter.py @@ -293,11 +293,13 @@ def defer_power_on(self, sid): """Power on once the System's media fetches end, within MEDIA_WAIT, as a server whose firmware waits for its virtual media. Called under LOCK; a ForceOff in the meantime cancels it. The reset time is the time the - reset was accepted, as a BMC reports it, not the later start. Returns - the boot device.""" + reset was accepted, as a BMC reports it, not the later start. A start + that fails leaves the System Off and its boot override unconsumed. + Returns the boot device the override selects when the reset is + accepted; the device actually started is logged.""" token = os.urandom(8).hex() - self.pending[sid] = token self.stamp_reset(sid) + self.pending[sid] = token def run(): # Every fetch of the System counts, including one that starts @@ -305,15 +307,16 @@ def run(): deadline = time.monotonic() + MEDIA_WAIT while True: with LOCK: + if self.pending.get(sid) != token: + return waiting = [f for (s, _), f in self.fetches.items() if s == sid and f.is_alive()] if not waiting or time.monotonic() >= deadline: - if self.pending.get(sid) != token: - return del self.pending[sid] try: - self.power_on(sid, stamp=False) - except LibvirtError as e: - print('fleet-lab-adapter: %s deferred power-on failed: %s' % (sid, e), file=sys.stderr, flush=True) + boot = self.power_on(sid, stamp=False) + print('fleet-lab-adapter: %s deferred power-on started:%s' % (sid, boot), file=sys.stderr, flush=True) + except Exception as e: # noqa: BLE001 the System stays Off + print('fleet-lab-adapter: %s deferred power-on failed: %s' % (sid, type(e).__name__), file=sys.stderr, flush=True) return waiting[0].join(max(0, min(1, deadline - time.monotonic()))) threading.Thread(target=run, daemon=True).start() @@ -335,9 +338,15 @@ def power_on(self, sid, stamp=True): # Once is consumed by this boot. Persisted before start, like NVRAM. self.nvram[sid] = {'BootSourceOverrideEnabled': 'Disabled', 'BootSourceOverrideTarget': 'None'} self.save() - require_accelerator() - virsh('define', '/dev/stdin', input=domain_xml(t, boot, self.media[sid])) - virsh('start', t['domain']) + try: + require_accelerator() + virsh('define', '/dev/stdin', input=domain_xml(t, boot, self.media[sid])) + virsh('start', t['domain']) + except Exception: + # Nothing booted, so nothing consumed the override. + self.nvram[sid] = override + self.save() + raise if stamp: self.stamp_reset(sid) return boot diff --git a/hack/redfish-lab/test_adapter.py b/hack/redfish-lab/test_adapter.py index 82b6d25f..eb2e8d9f 100644 --- a/hack/redfish-lab/test_adapter.py +++ b/hack/redfish-lab/test_adapter.py @@ -333,6 +333,42 @@ def starts(): self.assertEqual(len(starts()), before, 'a cancelled power-on started the target') post('/VirtualMedia/CD1/Actions/VirtualMedia.EjectMedia', {}) + # A deferred start that fails leaves the target Off and its boot + # override unconsumed. + release.clear() + self.assertEqual(post('/VirtualMedia/CD1/Actions/VirtualMedia.InsertMedia', {'Image': url}), 204) + self.app.patch(system, headers=AUTH, json={'Boot': {'BootSourceOverrideTarget': 'Cd', 'BootSourceOverrideEnabled': 'Once'}}) + before = len(starts()) + self.assertEqual(post('/Actions/ComputerSystem.Reset', {'ResetType': 'On'}), 204) + self.assertEqual(self.app.get(system, headers=AUTH).json['PowerState'], 'On') + os.environ['FAKE_VIRSH_FAIL_START'] = '1' + try: + release.set() + self.until('the failed start still reports On', lambda: self.app.get(system, headers=AUTH).json['PowerState'] == 'Off') + finally: + del os.environ['FAKE_VIRSH_FAIL_START'] + self.assertEqual(len(starts()), before) + boot = self.app.get(system, headers=AUTH).json['Boot'] + self.assertEqual((boot['BootSourceOverrideEnabled'], boot['BootSourceOverrideTarget']), ('Once', 'Cd')) + self.app.patch(system, headers=AUTH, json={'Boot': {'BootSourceOverrideEnabled': 'Disabled'}}) + post('/VirtualMedia/CD1/Actions/VirtualMedia.EjectMedia', {}) + + # A ForceRestart while a power-on waits replaces it: one start, + # once the media are in. + release.clear() + self.assertEqual(post('/VirtualMedia/CD1/Actions/VirtualMedia.InsertMedia', {'Image': url}), 204) + before = len(starts()) + self.assertEqual(post('/Actions/ComputerSystem.Reset', {'ResetType': 'On'}), 204) + self.assertEqual(post('/Actions/ComputerSystem.Reset', {'ResetType': 'ForceRestart'}), 204) + self.assertEqual(self.app.get(system, headers=AUTH).json['PowerState'], 'On') + self.assertEqual(len(starts()), before) + release.set() + self.until('the restarted target never started', lambda: len(starts()) == before + 1) + time.sleep(0.2) + self.assertEqual(len(starts()), before + 1, 'the replaced power-on also started the target') + post('/Actions/ComputerSystem.Reset', {'ResetType': 'ForceOff'}) + post('/VirtualMedia/CD1/Actions/VirtualMedia.EjectMedia', {}) + # An eject during the fetch keeps nothing of it. release.clear() self.assertEqual(post('/VirtualMedia/CD1/Actions/VirtualMedia.InsertMedia', {'Image': url}), 204) From 951b40c713df7f626d12623b2c08d62fd02a10d6 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sun, 29 Nov 2026 01:56:11 -0600 Subject: [PATCH 35/35] ci: Split the allocation tests across two shards The allocation package's envtest-backed tests run one after another and took 594s of go test's 600s package timeout in the rest shard; with the site declaration on top they timed out. Its tests are now dealt across two shards, as the custody package's are across three. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0e16be7a..8b7cbc7b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -14,8 +14,10 @@ jobs: # Every Go test runs once, with the race detector. No package is excluded # from race runs by a build tag. The shards partition `go list ./...`: the # rest shard takes every package the others do not name, so a new package - # is always tested. The custody package runs its envtest-backed tests one - # after another, so its tests are dealt round-robin across three shards. + # is always tested. The custody and allocation packages run their + # envtest-backed tests one after another, so their tests are dealt + # round-robin across shards: three for custody and two for allocation, + # whose tests together come near go test's ten-minute package timeout. # -count=1 keeps a restored cache from replaying results, and a skipped test # fails the shard: every skip in this repository means a missing tool or # envtest assets. @@ -30,6 +32,8 @@ jobs: - {shard: custody-1, packages: custody, part: 1, parts: 3} - {shard: custody-2, packages: custody, part: 2, parts: 3} - {shard: custody-3, packages: custody, part: 3, parts: 3} + - {shard: allocation-1, packages: allocation, part: 1, parts: 2} + - {shard: allocation-2, packages: allocation, part: 2, parts: 2} - {shard: api, packages: api, part: 1, parts: 1} - {shard: rest, packages: rest, part: 1, parts: 1} steps: @@ -69,8 +73,9 @@ jobs: all=$(go list ./...) case "$PACKAGES" in custody) packages=$(grep -x "$module/internal/custody" <<<"$all") ;; + allocation) packages=$(grep -x "$module/internal/allocation" <<<"$all") ;; api) packages=$(grep "^$module/internal/api/" <<<"$all") ;; - rest) packages=$(grep -vx -e "$module/internal/custody" -e "$module/internal/api/.*" <<<"$all") ;; + rest) packages=$(grep -vx -e "$module/internal/custody" -e "$module/internal/allocation" -e "$module/internal/api/.*" <<<"$all") ;; esac [ -n "$packages" ] || { echo "shard $PACKAGES has no packages"; exit 1; } run=()