From 29a36ae9369e9eadf6af2f5ef9668a62d4c079c5 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 25 Nov 2026 06:47:51 -0600 Subject: [PATCH 01/16] fix(site): Close a boot admission when its deadline stops the worker A worker stopped at its deadline left its network boot admission open until the boot window expired, so the server could still fetch the installer after nothing could resume or observe the operation. Both the local VM and Redfish workers now close it at the deadline. A worker stopped from outside still leaves it open for its replacement. Co-Authored-By: Claude Opus 5.5 --- internal/site/redfishwork/kinds.go | 9 +++++++++ internal/site/redfishwork/kinds_test.go | 24 ++++++++++++++++++++++++ internal/site/runner.go | 4 ++++ internal/site/vmwork/kinds.go | 7 ++++--- internal/site/vmwork/kinds_test.go | 19 +++++++++++++++++++ 5 files changed, 60 insertions(+), 3 deletions(-) diff --git a/internal/site/redfishwork/kinds.go b/internal/site/redfishwork/kinds.go index 19b2a678..f7f207cb 100644 --- a/internal/site/redfishwork/kinds.go +++ b/internal/site/redfishwork/kinds.go @@ -249,6 +249,15 @@ func (c Config) run(ctx context.Context, work *site.Work, phases []phase) ([]ops if err != nil { return nil, err } + // A worker stopped at its deadline closes its admission: nothing can + // resume the operation, so nothing may boot the server from it. A worker + // stopped from outside leaves it open for its replacement. + defer func() { + if mode != "" && site.DeadlinePassed(ctx) && !boot.Closed { + boot.Phase, boot.Closed = "", true + _ = c.saveBoot(work, boot) + } + }() var evidence []ops.StepEvidence for _, ph := range phases { // A phase verified by an earlier worker is done; resume after it. diff --git a/internal/site/redfishwork/kinds_test.go b/internal/site/redfishwork/kinds_test.go index 264ecbc5..ebb466c1 100644 --- a/internal/site/redfishwork/kinds_test.go +++ b/internal/site/redfishwork/kinds_test.go @@ -53,6 +53,8 @@ type lab struct { bootRoot string store *site.Store operation string + // silent keeps the server running with no console receipt. + silent bool } func newLab(t *testing.T) *lab { @@ -130,6 +132,9 @@ func (l *lab) ServeHTTP(w http.ResponseWriter, r *http.Request) { // boot runs the armed boot, as the server and the boot server would. func (l *lab) boot(target string) { time.Sleep(30 * time.Millisecond) + if l.silent { + return + } var boot Boot if _, err := l.store.GetRecord(device, "boot", l.operation, &boot); err != nil { l.t.Error(err) @@ -292,6 +297,25 @@ func TestAnInterruptedWorkerResumesWithoutASecondOn(t *testing.T) { } } +func TestAWorkerStoppedAtItsDeadlineClosesItsAdmission(t *testing.T) { + l := newLab(t) + l.silent = true + r := runner(t, l) + a := assignment(l, "DeviceInstallation", "00000000-0000-4000-8000-000000000301", 2, installSpec()) + a.Deadline = time.Now().Add(2 * time.Second) + result, err := r.Run(context.Background(), a) + if err != nil || result.Phase != ops.PhaseOutcomeUnknown || result.Reason != site.ReasonDeadline { + t.Fatalf("install past its deadline = %+v, %v", result, err) + } + var boot Boot + if found, err := r.Store.GetRecord(device, bootRecords, a.Key(), &boot); err != nil || !found || !boot.Closed || boot.Phase != "" { + t.Fatalf("admission after the deadline = %+v, %v, %v", boot, found, err) + } + if _, open, _ := OpenAdmission(r.Store, mac, time.Now()); open { + t.Fatal("a worker stopped at its deadline left its admission open") + } +} + func TestOnlyTheCurrentFenceHasAnOpenBootAdmission(t *testing.T) { l := newLab(t) r := runner(t, l) diff --git a/internal/site/runner.go b/internal/site/runner.go index d8eba1c3..dbdd2731 100644 --- a/internal/site/runner.go +++ b/internal/site/runner.go @@ -420,6 +420,10 @@ func (r *Runner) Run(ctx context.Context, assignment Assignment) (custody.SiteRe var errDeadline = errors.New("the operation's deadline passed") +// 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) } + func outcomeReason(ctx context.Context, err error) string { switch cause := context.Cause(ctx); { case errors.Is(err, errSuperseded) || errors.Is(cause, errSuperseded): diff --git a/internal/site/vmwork/kinds.go b/internal/site/vmwork/kinds.go index 7b2a4ede..21f8fd72 100644 --- a/internal/site/vmwork/kinds.go +++ b/internal/site/vmwork/kinds.go @@ -246,10 +246,11 @@ func (k Installation) Run(ctx context.Context, work *site.Work) (any, error) { return nil, err } // A failed network boot closes its admission at once, so the boot - // server stops serving the installer. A worker stopped from outside - // leaves it open for its replacement to resume. + // server stops serving the installer, and so does a worker stopped at + // its deadline, which nothing can resume. A worker stopped from + // outside leaves it open for its replacement to resume. fail := func(err error) error { - if stage == "installer" && k.PXE && boot.Open && ctx.Err() == nil { + if stage == "installer" && k.PXE && boot.Open && (ctx.Err() == nil || site.DeadlinePassed(ctx)) { boot.Open, boot.Closed = false, true _ = k.save(work, boot) } diff --git a/internal/site/vmwork/kinds_test.go b/internal/site/vmwork/kinds_test.go index ce683991..a63d4730 100644 --- a/internal/site/vmwork/kinds_test.go +++ b/internal/site/vmwork/kinds_test.go @@ -261,6 +261,25 @@ func TestTheBootServerServesOnlyAnOpenAdmissionAtTheStoredFence(t *testing.T) { // TestAFailedNetworkBootClosesItsAdmission stops serving the installer as // soon as a network-boot installation fails. +func TestAWorkerStoppedAtItsDeadlineClosesItsAdmission(t *testing.T) { + r := newRig(t) + r.config.PXE = true + r.runner.Kinds["DeviceInstallation"] = Installation{r.config} + // The guest keeps running and never prints a receipt, so the worker is + // still waiting when the deadline passes. + r.vm.hold, r.vm.noReceipt = true, true + assignment := r.assignment("DeviceInstallation", "00000000-0000-4000-8000-000000000207", 2, installSpec()) + assignment.Deadline = time.Now().Add(time.Second) + result, err := r.runner.Run(context.Background(), assignment) + if err != nil || result.Phase != ops.PhaseOutcomeUnknown || result.Reason != site.ReasonDeadline { + t.Fatalf("install past its deadline = %+v, %v", result, err) + } + var boot Boot + if found, err := r.store.GetRecord(device, bootRecords, Key(assignment.Key()), &boot); err != nil || !found || boot.Open || !boot.Closed { + t.Fatalf("admission after the deadline = %+v, %v, %v", boot, found, err) + } +} + func TestAFailedNetworkBootClosesItsAdmission(t *testing.T) { r := newRig(t) r.config.PXE = true From 18b88b9c76cd5d946222c2e25d0fea1641eed84f Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 25 Nov 2026 06:52:08 -0600 Subject: [PATCH 02/16] fix(site): Power off the local VM guest before a wipe The local VM wipe refused to run while any guest was up, so an installation stopped at its deadline, which leaves its guest running, could never be settled by a wipe. The wipe now powers the guest off first, as a Redfish wipe does, and still refuses if it keeps running. Co-Authored-By: Claude Opus 5.5 --- docs/development/device-custody.md | 2 +- internal/site/vmwork/kinds.go | 29 +++++++++++++++++++++++++++++ internal/site/vmwork/kinds_test.go | 26 ++++++++++++++++++++++---- 3 files changed, 52 insertions(+), 5 deletions(-) diff --git a/docs/development/device-custody.md b/docs/development/device-custody.md index 9a8f0d78..c9a646d9 100644 --- a/docs/development/device-custody.md +++ b/docs/development/device-custody.md @@ -968,7 +968,7 @@ Increment C's tests run with `task test:envtest`, and the smoke runs with | An allocation that never held its Device is deleted and the allocator selects again | `TestAnAllocationThatLostItsDeviceIsReplaced` | | The quota claim is named from the Machine and granted once; release is observed, not assumed | `TestTheQuotaClaimIsNamedFromTheMachineAndGrantedOnce`, `TestReleaseIsObservedNotAssumed` | | Federation: an assignment's round trip, only this cell's observation accepted, a stale fence report ignored, a cell runs only its own assignments | `TestAssignmentRoundTrip`, `TestReflectionIsRejectedUnlessItIsThisCellsObservation`, `TestAStaleFenceReportIsNoReport`, `TestTheCellRunsOnlyItsOwnAssignments` | -| The local VM site: install then wipe, a wipe with a running domain not proven, a resumed boot observed and not repeated, the boot server serving only an open admission at the stored fence | `TestInstallThenWipe`, `TestAWipeWithARunningDomainIsNotProven`, `TestAResumedBootIsObservedNotRepeated`, `TestTheBootServerServesOnlyAnOpenAdmissionAtTheStoredFence` | +| The local VM site: install then wipe, a wipe that powers off a running guest first and is not proven while the guest keeps running, a resumed boot observed and not repeated, the boot server serving only an open admission at the stored fence | `TestInstallThenWipe`, `TestAWipePowersOffARunningDomain`, `TestAWipeWithADomainThatKeepsRunningIsNotProven`, `TestAResumedBootIsObservedNotRepeated`, `TestTheBootServerServesOnlyAnOpenAdmissionAtTheStoredFence` | | Synchronized DHCP follows the open admission; a worker waits for the reservation and for its withdrawal | `TestSyncedDHCPFollowsTheOpenAdmission` | | The simulator site's token, enrollment and server bounds | `TestReadToken`, `TestReadEnrollmentRequiresCompleteTargets`, `TestNewServerHasFiniteResourceBounds` | | The manager's synthetic flags, and the creator webhook's trusted caller | `TestSyntheticFlagsRequireAndScopeStaging`, `TestRemovedSingleProjectFlagsAreRejected`, `TestWebhookRequiresTrustedAPIServerClient` | diff --git a/internal/site/vmwork/kinds.go b/internal/site/vmwork/kinds.go index 21f8fd72..c9eddb0b 100644 --- a/internal/site/vmwork/kinds.go +++ b/internal/site/vmwork/kinds.go @@ -429,6 +429,35 @@ func (k Wipe) Run(ctx context.Context, work *site.Work) (any, error) { if refusal != nil { return nil, refusal } + // Power the guest off first, as a Redfish wipe does: an installation + // stopped at its deadline can leave it running. The local VM serves one + // guest, so every local domain is the Device's, and the fence and run + // lock already stopped every older worker. Sending it again is safe. + running := func(ctx context.Context) ([]string, error) { + names, err := k.virsh(ctx, "list", "--name") + var local []string + for _, name := range strings.Fields(names) { + if strings.HasPrefix(name, "fleet-local-") { + local = append(local, name) + } + } + return local, err + } + if err := work.Step(ctx, site.Step{ + Name: "wipe-power-off", + Send: func(ctx context.Context) error { + names, err := running(ctx) + for _, name := range names { + if err == nil { + _, err = k.virsh(ctx, "destroy", name) + } + } + return err + }, + Idempotent: true, + }); err != nil { + return nil, err + } root := filepath.Join(k.Disks, deviceKey(work.Device)) remaining := func() ([]string, error) { paths, err := filepath.Glob(filepath.Join(root, "*", "disk.raw")) diff --git a/internal/site/vmwork/kinds_test.go b/internal/site/vmwork/kinds_test.go index a63d4730..2a15de7e 100644 --- a/internal/site/vmwork/kinds_test.go +++ b/internal/site/vmwork/kinds_test.go @@ -35,6 +35,8 @@ type hypervisor struct { hold bool // noReceipt makes the guest print no receipt. noReceipt bool + // stuck makes destroy leave the domain running. + stuck bool } var receiptArg = regexp.MustCompile(`fleet.receipt=([0-9a-f]{64})`) @@ -74,6 +76,10 @@ func (h *hypervisor) run(_ context.Context, _ string, args ...string) (string, e if !h.hold { delete(h.running, name) } + case "destroy": + if !h.stuck { + delete(h.running, args[1]) + } case "list": var names []string for name := range h.running { @@ -164,14 +170,26 @@ func TestInstallThenWipe(t *testing.T) { } } -// TestAWipeWithARunningDomainIsNotProven keeps a disk in use from counting -// as wiped. -func TestAWipeWithARunningDomainIsNotProven(t *testing.T) { +// TestAWipePowersOffARunningDomain powers off a guest an earlier worker left +// running, then wipes. +func TestAWipePowersOffARunningDomain(t *testing.T) { + r := newRig(t) + r.vm.running["fleet-local-0000000000000000"] = "console" + result, err := r.runner.Run(context.Background(), r.assignment("DeviceWipe", "00000000-0000-4000-8000-000000000208", 2, wipeSpec())) + if err != nil || result.Phase != ops.PhaseSucceeded || len(r.vm.running) != 0 { + t.Fatalf("wipe with a running domain = %+v, %v, running %v", result, err, r.vm.running) + } +} + +// TestAWipeWithADomainThatKeepsRunningIsNotProven keeps a disk in use from +// counting as wiped. +func TestAWipeWithADomainThatKeepsRunningIsNotProven(t *testing.T) { r := newRig(t) r.vm.running["fleet-local-0000000000000000"] = "console" + r.vm.stuck = true result, err := r.runner.Run(context.Background(), r.assignment("DeviceWipe", "00000000-0000-4000-8000-000000000203", 2, wipeSpec())) if err != nil || result.Phase == ops.PhaseSucceeded { - t.Fatalf("wipe with a running domain = %+v, %v", result, err) + t.Fatalf("wipe with a domain that keeps running = %+v, %v", result, err) } } From 76c695328a7f3d90f9d57421067475c1970297b1 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 25 Nov 2026 06:56:31 -0600 Subject: [PATCH 03/16] test(multiplane): Run the #174 failure scenarios end to end Both multi-plane runs now prove these acceptance tests against the real Milo, Karmada, kro and site path: - importing Devices admits, delivers and sends nothing; - staff create recoveries and read custody, and nothing else; - custody names the one winning allocation after contention; - a Machine deleted mid-install makes release wait for the outcome; - an installation past its deadline ends OutcomeUnknown and is held; - a recovery naming the wrong hold is refused with nothing sent; - the release wipe, admitted after the worker stopped, settles the hold; - deleted custody is rebuilt Unverified, allocates nothing, and is Verified again only above the site's fence. The Redfish discovery phase also shows a TLS key other than the pin reaches no request. The coordinator takes a shorter installation deadline for the deadline scenario, and the unused second-install phase is removed. Co-Authored-By: Claude Opus 5.5 --- cmd/fleet-multiplane/main.go | 19 +- hack/multiplane/acceptance-redfish.sh | 8 +- hack/multiplane/acceptance.sh | 9 +- hack/multiplane/coordinator.sh | 9 +- hack/multiplane/evidence.py | 84 ++++--- hack/multiplane/harness.py | 5 +- hack/multiplane/milo.py | 10 +- hack/multiplane/redfish_steps.py | 31 ++- hack/multiplane/scenarios.py | 332 ++++++++++++++++++++++++++ hack/multiplane/steps.sh | 92 ++++++- hack/multiplane/test-harness.sh | 8 +- hack/multiplane/test-redfish.py | 2 +- internal/multiplane/runner.go | 17 +- internal/multiplane/scenarios.go | 126 ++++++++++ 14 files changed, 693 insertions(+), 59 deletions(-) create mode 100644 hack/multiplane/scenarios.py create mode 100644 internal/multiplane/scenarios.go diff --git a/cmd/fleet-multiplane/main.go b/cmd/fleet-multiplane/main.go index ad806389..f6ff60ec 100644 --- a/cmd/fleet-multiplane/main.go +++ b/cmd/fleet-multiplane/main.go @@ -49,6 +49,7 @@ func run() error { uuid := fs.String("uuid", "", "enrolled Redfish System UUID (redfish-probe)") pin := fs.String("pin", "", "the BMC's approved key digest; the probe connects only to that key (redfish-probe)") 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)") if err := fs.Parse(os.Args[2:]); err != nil { return err } @@ -61,10 +62,10 @@ func run() error { ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) defer cancel() fmt.Println("coordinator: custody coordinator running") - return multiplane.Coordinate(ctx, config, func(err error) { + return multiplane.Coordinate(ctx, config, *installationDeadline, func(err error) { fmt.Fprintf(os.Stderr, "%s coordinator: pass incomplete: %v\n", time.Now().UTC().Format(time.RFC3339), err) }) - case "seed", "allocate", "install", "install-b", "admit-install", "release", "release-b", "reuse": + case "seed", "allocate", "install", "admit-install", "admit-install-b", "release", "release-b", "reuse", "recovery-mismatch", "probe-unallocatable": return phase(os.Args[1], *configPath, *once) case "redfish-probe": return probe(*endpoint, *credentials, *system, *uuid, *pin) @@ -142,8 +143,9 @@ func phase(name, configPath string, once bool) error { return err } action := map[string]func(context.Context) error{ - "allocate": r.Allocate, "admit-install": r.AdmitInstall, "install": r.Install, "install-b": r.InstallSecond, + "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, }[name] last := "" for { @@ -154,10 +156,13 @@ func phase(name, configPath string, once bool) error { last = err.Error() fmt.Printf("%s: waiting: %v\n", name, err) } - if name == "admit-install" && errors.Is(err, multiplane.ErrAdmittedUnknown) { + if strings.HasPrefix(name, "admit-install") && errors.Is(err, multiplane.ErrAdmittedUnknown) { fmt.Println("Installation admitted and delivered; its result remains Unknown") return nil } + if err == nil && (name == "recovery-mismatch" || name == "probe-unallocatable") { + return nil + } if err == nil { fmt.Println(name + ": verified local acceptance phase (synthetic authority)") return nil @@ -180,7 +185,8 @@ func redfishMode() bool { return os.Getenv("FLEET_SITE_PROVIDER") == "redfish" } // probe performs read-only Redfish discovery of one enrolled System and // prints only an outcome class. Exit codes: 0 discovered, 10 credential -// rejected, 11 capability unsupported, 12 identity mismatch. +// rejected, 11 capability unsupported, 12 identity mismatch, 13 TLS key +// other than the pin. func probe(endpoint, credentials, system, uuid, pin string) error { user, err1 := os.ReadFile(credentials + "/username") password, err2 := os.ReadFile(credentials + "/password") @@ -204,6 +210,9 @@ func probe(endpoint, credentials, system, uuid, pin string) error { case errors.Is(err, redfish.ErrUnsupported): fmt.Println("redfish-probe: required capability not advertised; no effect issued") os.Exit(11) + case errors.Is(err, redfish.ErrPinMismatch): + fmt.Println("redfish-probe: the BMC's TLS key does not match the pin; no request sent") + os.Exit(13) case errors.Is(err, redfish.ErrIdentity): fmt.Println("redfish-probe: enrolled identity not matched exactly; no effect issued") os.Exit(12) diff --git a/hack/multiplane/acceptance-redfish.sh b/hack/multiplane/acceptance-redfish.sh index 475f3933..bd744fa9 100755 --- a/hack/multiplane/acceptance-redfish.sh +++ b/hack/multiplane/acceptance-redfish.sh @@ -15,6 +15,8 @@ flux() { ph "flux-$1" "$2" python3 hack/multiplane/flux.py "$1" "$state"; } ph rbac 600 python3 hack/multiplane/verify-rbac.py "$state" ph custody-crd-rules 600 python3 hack/multiplane/custody_crd_rules.py "$state" +step import-inert 300 +step staff-access 120 rf baseline 300 rf discovery-faults 600 ph allocate 900 "$host" allocate --config "$state/acceptance.json" @@ -46,9 +48,13 @@ step release-status-a 120 ph reuse 900 "$host" reuse --config "$state/acceptance.json" step reuse-status 120 step delivery-faults 900 -ph install-b 2400 "$host" install-b --config "$state/acceptance.json" +step deadline-admit 1200 +step machine-delete 300 +step deadline-hold 1500 ph release-b 2400 "$host" release-b --config "$state/acceptance.json" +step deadline-settled 300 step release-status-b 120 +step rebuild 1200 step wrong-location 300 step boot-denials 300 step flux-final 900 diff --git a/hack/multiplane/acceptance.sh b/hack/multiplane/acceptance.sh index 8bfc31c3..34f6382c 100755 --- a/hack/multiplane/acceptance.sh +++ b/hack/multiplane/acceptance.sh @@ -12,6 +12,8 @@ flux() { ph "flux-$1" "$2" python3 hack/multiplane/flux.py "$1" "$state"; } ph rbac 600 python3 hack/multiplane/verify-rbac.py "$state" ph custody-crd-rules 600 python3 hack/multiplane/custody_crd_rules.py "$state" +step import-inert 300 +step staff-access 120 ph allocate 900 "$host" allocate --config "$state/acceptance.json" step verify-contention 120 ph admit-install 900 "$host" admit-install --config "$state/acceptance.json" @@ -38,8 +40,13 @@ step release-status-a 120 ph reuse 900 "$host" reuse --config "$state/acceptance.json" step reuse-status 120 step delivery-faults 900 -ph release-b 1200 "$host" release-b --config "$state/acceptance.json" +step deadline-admit 1200 +step machine-delete 300 +step deadline-hold 1500 +ph release-b 2400 "$host" release-b --config "$state/acceptance.json" +step deadline-settled 300 step release-status-b 120 +step rebuild 1200 step wrong-location 300 step boot-denials 300 step flux-final 900 diff --git a/hack/multiplane/coordinator.sh b/hack/multiplane/coordinator.sh index 3e77ed76..a000d468 100755 --- a/hack/multiplane/coordinator.sh +++ b/hack/multiplane/coordinator.sh @@ -13,7 +13,8 @@ case $action in echo "coordinator: already running" exit 0 fi - nohup "$state/fleet-multiplane-host" coordinator --config "$state/acceptance.json" >>"$state/coordinator.log" 2>&1 >"$state/coordinator.log" 2>&1 "$pidfile" sleep 2 kill -0 "$(cat "$pidfile")" || { echo 'coordinator: exited at start; see coordinator.log in the state directory' >&2; exit 1; } @@ -30,5 +31,9 @@ case $action in fi echo "coordinator: stopped" ;; - *) echo 'usage: coordinator.sh start|stop STATE' >&2; exit 64 ;; + restart) + "$0" stop "$state" + "$0" start "$state" "${@:3}" + ;; + *) echo 'usage: coordinator.sh start|stop|restart STATE [coordinator flags]' >&2; exit 64 ;; esac diff --git a/hack/multiplane/evidence.py b/hack/multiplane/evidence.py index 318f0767..bb8f0aae 100755 --- a/hack/multiplane/evidence.py +++ b/hack/multiplane/evidence.py @@ -82,7 +82,11 @@ def copy_out(source, destination): 'kro created the worker Job and per-operation RBAC', 'worker-rbac: per-operation ServiceAccount', 'interrupt-pod: worker Pod force-deleted', 'interrupt-job: running worker Job deleted mid-install', 'resume: replacement worker completed the exact interrupted operation', 'worker Job is Complete while hub/consumer disconnected; public Ready stayed False', 'install: verified', 'lifecycle: runtime, boot and observer Pods', - 'delivery-faults: duplicate refused by the API', 'boot-denials: PASS', 'release: verified', 'release-status-a: consumer-a Machine Released', 'Installation Released, Ready False', 'reuse: verified', 'reuse-status: consumer-b Bound', 'release-b: verified', 'release-status-b: consumer-b Machine Released', + 'delivery-faults: duplicate refused by the API', 'boot-denials: PASS', 'release: verified', 'release-status-a: consumer-a Machine Released', 'Installation Released, Ready False', 'reuse: verified', 'reuse-status: consumer-b Bound', 'release-b: verified', 'release-status-b: consumer-b Machine deleted', + 'import-inert: ', 'staff-access: staff read custody', 'contention-custody: custody holds the Device for the one MachineAllocation', + 'deadline-admit: the second installation was admitted', 'release-waits: the Machine is deleting', 'deadline-hold: the installation ended OutcomeUnknown at its deadline', + 'recovery-mismatch: refused', 'deadline-settled: the release wipe was admitted', 'rebuild-unverified: custody rebuilt Unverified', + 'probe-unallocatable: no eligible capacity while custody is Unverified', 'rebuild-verified: custody Verified', 'wrong-location: denied before allocation', 'Flux restored the binding', 'flux-verify: 3 clusters Ready', 'cell Flux applied the dispatch revision', 'Flux restored consumer-a', 'Flux on every cluster Ready at the current revision', 'flux-drift: helm-controller restored kro', 'recreated the shared boot Service at its fixed ClusterIP and restored the observer', 'flux-graph-lifecycle: deleting the dispatcher removed only kro per-operation objects', @@ -93,7 +97,7 @@ def copy_out(source, destination): markers += ('bmc-upstream: DMTF Redfish-Interface-Emulator 1.2.2 archive verified', 'bmc-self-test: upstream emulator and lab adapter self-test passed', 'redfish-enroll: synthetic per-Device BMC credentials', 'redfish-baseline: both lab target disks present', 'redfish-discovery-faults: real emulator discovery', 'redfish-lost-response: On took effect but its response was lost', 'redfish-bmc-interrupt: lab BMC Pod force-deleted mid-install', - 'install-b: verified', 'redfish-isolation: target B never started') + 'a TLS key other than the pin reached no request', 'redfish-isolation: target B never started') for marker in markers: if marker not in phases: fail('missing acceptance phase: ' + marker) @@ -101,33 +105,43 @@ def copy_out(source, destination): def site_operations(raw): """The Device's journaled operations from the copied site store, matched to the provider project's operations by site key: kind, name and fence. Expected order: consumer A's - install, A's release wipe, (Redfish: consumer B's install,) B's release - wipe, with strictly increasing fences, each Succeeded at its fence.""" + install, A's release wipe, consumer B's install, held at its deadline, + and B's release wipe, with strictly increasing fences. Each operation + but the held one Succeeded at its fence; that one is returned apart.""" store = json.loads((raw / 'site' / 'devices' / harness.device_dir().rsplit('/', 1)[1] / 'state.json').read_text()) journaled = harness.sanitized_operations(store, redfish=REDFISH) # Operations by site key; custody and allocations by kind and name. provider = {(i['kind'] + '/' + i['metadata']['name'] if i['kind'] in ('DeviceCustody', 'MachineAllocation') else harness.provider_key(i)): i for i in harness.custody(s)} - ops = [] + held_key = json.loads((s / 'deadline-install.json').read_text())['key'] + ops, held = [], None + if [o['fence'] for o in journaled] != sorted({o['fence'] for o in journaled}): + fail('journaled fences are not strictly increasing: %s' % [o['fence'] for o in journaled]) for o in journaled: p = provider.get(o['operation']) + if o['operation'] == held_key: + st = (p or {}).get('status', {}) + if not p or p['kind'] != 'DeviceInstallation' or o['done'] or st.get('phase') != 'OutcomeUnknown' or st.get('reason') != 'DeadlineExceeded' or st.get('fence') != o['fence']: + fail('the deadline installation is not held OutcomeUnknown at its fence: %s' % {k: st.get(k) for k in ('phase', 'reason', 'fence')}) + held = dict(o, name=p['metadata']['name'], allocation=p['spec']['authority']['allocationRef']['name'], phase=st['phase']) + continue if not p or p['kind'] != o['kind'] or not o['done']: fail('journaled operation %s is not a finished provider %s' % (o['operation'], o['kind'])) st = p.get('status', {}) if st.get('phase') != 'Succeeded' or st.get('fence') != o['fence']: fail('%s %s is %s at fence %s, journaled at fence %s' % (p['kind'], p['metadata']['name'], st.get('phase'), st.get('fence'), o['fence'])) ops.append(dict(o, name=p['metadata']['name'], allocation=p['spec']['authority']['allocationRef']['name'], phase=st['phase'])) - fences = [o['fence'] for o in ops] - if fences != sorted(set(fences)): - fail('operation fences are not strictly increasing: %s' % fences) - return store, ops, provider + if held is None: + fail('the site journal holds no deadline installation') + return store, ops, provider, held -def check_sequence(ops, interrupt): - """Consumer A's allocation holds the interrupted install; the other is B's.""" +def check_sequence(ops, held, interrupt): + """Consumer A's allocation holds the interrupted install; the other is B's, + whose installation was held at its deadline.""" a = next((o['allocation'] for o in ops if o['operation'] == interrupt['operationID']), None) b = next((o['allocation'] for o in ops if o['allocation'] != a), None) - want = [('DeviceInstallation', a), ('DeviceWipe', a)] + ([('DeviceInstallation', b)] if REDFISH else []) + [('DeviceWipe', b)] - if not a or not b or [(o['kind'], o['allocation']) for o in ops] != want: + want = [('DeviceInstallation', a), ('DeviceWipe', a), ('DeviceWipe', b)] + if not a or not b or held['allocation'] != b or [(o['kind'], o['allocation']) for o in ops] != want: fail('expected %s, got %s' % (want, [(o['kind'], o['allocation']) for o in ops])) if any(o['kind'] == 'DeviceWipe' and o['name'] != o['allocation'] + '-wipe-1' for o in ops): fail('a release wiped the Device other than with its first wipe step') @@ -147,10 +161,14 @@ def custody_evidence(store, ops, provider, a, b): spec = custody['spec'] if spec.get('state') != 'Verified' or spec.get('holder', {}).get('type') != 'None' or spec.get('activeOperation') or spec.get('recoveryHold'): fail('final custody is not Verified with no holder, operation or hold: %s' % {k: spec.get(k) for k in ('state', 'holder', 'activeOperation', 'recoveryHold')}) - if spec.get('fence') != ops[-1]['fence'] or store.get('fence') != ops[-1]['fence'] or store.get('stopped') != ops[-1]['fence']: - fail('custody fence %s, site fence %s/%s and the last operation fence %s differ' % (spec.get('fence'), store.get('fence'), store.get('stopped'), ops[-1]['fence'])) - if any(i['kind'] == 'DeviceRecovery' for i in provider.values()): - fail('a DeviceRecovery exists after an uninterrupted lifecycle') + # Custody was rebuilt after the last operation, with a fence above every + # fence the site stored. + rebuilt = json.loads((ev / 'rebuild.json').read_text()) + if spec.get('fence') != rebuilt['verifiedFence'] or spec['fence'] <= ops[-1]['fence'] or store.get('fence') != ops[-1]['fence'] or store.get('stopped') != ops[-1]['fence']: + fail('custody fence %s, site fence %s/%s and the last operation fence %s do not follow the rebuild' % (spec.get('fence'), store.get('fence'), store.get('stopped'), ops[-1]['fence'])) + recoveries = [i for i in provider.values() if i['kind'] == 'DeviceRecovery'] + if len(recoveries) != 1 or recoveries[0].get('status', {}).get('phase') != 'Failed' or recoveries[0]['status'].get('fence'): + fail('expected only the refused mismatched recovery, never admitted') record = {'observedAt': datetime.datetime.now(datetime.timezone.utc).isoformat(), 'device': harness.DEVICE, 'custody': {'state': spec['state'], 'holder': spec['holder'], 'fence': spec['fence'], 'activeOperation': None, 'recoveryHold': None, 'rejectedResults': spec.get('rejectedResults')}, @@ -177,9 +195,9 @@ def libvirt_provider(): copy_out('/var/lib/fleet-local', raw) copy_out('/var/lib/fleet-boot', raw / 'boot-evidence') copy_out('/var/log/libvirt/qemu', raw / 'libvirt-qemu') - store, ops, provider = site_operations(raw) + store, ops, provider, held = site_operations(raw) interrupt = json.loads((ev / 'interrupt.json').read_text()) - a, b = check_sequence(ops, interrupt) + a, b = check_sequence(ops, held, interrupt) installs = [o for o in ops if o['kind'] == 'DeviceInstallation'] wipes = [o for o in ops if o['kind'] == 'DeviceWipe'] @@ -242,9 +260,9 @@ def redfish_provider(): copy_out('/var/lib/fleet-boot', raw / 'boot-evidence') copy_out('/var/log/libvirt/qemu', raw / 'libvirt-qemu') copy_out('/var/lib/fleet-lab-console', raw / 'lab-console') - store, ops, provider = site_operations(raw) + store, ops, provider, held = site_operations(raw) interrupt = json.loads((ev / 'interrupt.json').read_text()) - a_alloc, b_alloc = check_sequence(ops, interrupt) + a_alloc, b_alloc = check_sequence(ops, held, interrupt) installs = [o for o in ops if o['kind'] == 'DeviceInstallation'] wipes = [o for o in ops if o['kind'] == 'DeviceWipe'] enrollment = json.loads(next(l for l in pathlib.Path('config/site/redfish/graph/kustomization.yaml').read_text().splitlines() if l.strip().startswith("value: '{")).split("'")[1]) @@ -271,8 +289,8 @@ def redfish_provider(): fail('missing completed boot delivery of %s for %s' % (name, o['kind'])) if expected != sorted(expected) or sum(1 for l in console if l.startswith('FLEET-')) != len(expected): fail('console receipts are out of order or include another operation') - if sum(1 for l in console if l.startswith('+ sfdisk /dev/vda')) != 2: - fail('the installer partitioned the target disk other than once per install') + if sum(1 for l in console if l.startswith('+ sfdisk /dev/vda')) != 1: + fail('the installer partitioned the target disk other than once for the one finished install') qemu = (raw / 'libvirt-qemu' / 'fleet-lab-target-a.log').read_text(errors='replace') blocks = re.split(r'^\S+ \S+: starting up ', qemu, flags=re.M)[1:] def network(block): @@ -280,17 +298,19 @@ def network(block): order = ['network' if network(b) else 'disk' for b in blocks] starts = {'targetA': order, 'targetB': (raw / 'libvirt-qemu' / 'fleet-lab-target-b.log').read_text(errors='replace').count(': starting up ') if (raw / 'libvirt-qemu' / 'fleet-lab-target-b.log').exists() else 0} - if order != ['network', 'disk', 'network', 'network', 'disk', 'network'] or starts['targetB']: - fail('expected target A boots network, disk, network, network, disk, network and no target B start; got %s' % starts) + # A install (network, disk), A wipe, B's held install (its network boot + # found no boot server), B wipe. + if order != ['network', 'disk', 'network', 'network', 'network'] or starts['targetB']: + fail('expected target A boots network, disk, network, network, network and no target B start; got %s' % starts) audit = [json.loads(l) for l in (ev / 'redfish-audit.jsonl').read_text().splitlines()] effects = [e for e in audit if e['method'] not in ('GET', 'HEAD')] ons = [e for e in effects if e.get('resetType') == 'On'] - if len(ons) != 6 or any(not e.get('effect', '').startswith('started') for e in ons) or any('/System-1' not in e['path'] for e in effects): - fail('expected exactly six effective On requests, all to System-1, and no other target effect') + if len(ons) != 5 or any(not e.get('effect', '').startswith('started') for e in ons) or any('/System-1' not in e['path'] for e in effects): + fail('expected exactly five effective On requests, all to System-1, and no other target effect') if sum(1 for e in ons if e.get('fault') == 'drop-response-after-effect') != 1: fail('the lost-response fault did not fire exactly once') # Each boot was requested once: one journaled power-on step per phase. - powered = sum(1 for o in ops for n, st in o['steps'] if n.endswith('-power-on') and st == 'Done') + powered = sum(1 for o in ops + [held] for n, st in o['steps'] if n.endswith('-power-on') and st == 'Done') if powered != len(ons): fail('journaled %d power-on steps for %d effective On requests' % (powered, len(ons))) if runtime('virsh', '--connect', 'qemu:///system?socket=/run/fleet-libvirt/libvirt-sock', 'list', '--name').strip(): @@ -401,6 +421,13 @@ def network(block): if any(k['lastAppliedRevision'] != flux_revisions[-1]['fluxRevision'] or k['suspend'] for n, k in snap['kustomizations'].items()): fail('%s has a Kustomization not at the final revision' % cluster) write_env = json.loads((s / 'gitops-environment.json').read_text()) +# The #174 failure scenarios, each written by hack/multiplane/scenarios.py. +FAILURE_SCENARIOS = ('import-inert', 'staff-access', 'contention', 'release-waits', 'deadline-hold', 'deadline-settled', 'rebuild') +failure_scenarios = {} +for name in FAILURE_SCENARIOS: + if not (ev / (name + '.json')).exists(): + fail('missing failure scenario evidence ' + name) + failure_scenarios[name] = json.loads((ev / (name + '.json')).read_text()) summary = { 'schemaVersion': 2, 'acceptance': 'passed', @@ -418,6 +445,7 @@ def network(block): 'evidence': list(flux_files), 'siteImage': write_env['siteImage']}, 'installerStarts': starts, 'reflectionRejections': list(REFLECTION_FAULTS), + 'failureScenarios': failure_scenarios, 'wrongLocationDeniedBeforeAllocation': json.loads((ev / 'wrong-location.json').read_text()), 'custodyCRDRules': custody_rules, 'releasedProjection': {'consumerA': {'machine': 'Released, Bound False, Ready False, no currentInstallationRef, no Fleet finalizer', 'installation': 'Released, Ready False'}, diff --git a/hack/multiplane/harness.py b/hack/multiplane/harness.py index a7d01022..ca78f456 100755 --- a/hack/multiplane/harness.py +++ b/hack/multiplane/harness.py @@ -26,12 +26,13 @@ DEBIAN = 'debian:bookworm-slim@sha256:734a72b3d6142a71993b4bc580ca01d8ca687f77a2c422d96a961d3376b179bc' # Subcommands and errors the live harness depends on. A missing one blocks before any resource exists. REQUIRED_SOURCE_MARKERS = tuple('"%s"' % c for c in ('seed', 'allocate', 'admit-install', 'install', 'release', 'release-b', 'reuse', - 'coordinator', 'image', 'boot-service', 'boot-denials', 'site-worker', 'site-observer')) + ('multiplane.ErrLocationNotServed',) + 'coordinator', 'image', 'boot-service', 'boot-denials', 'site-worker', 'site-observer', + 'admit-install-b', 'recovery-mismatch', 'probe-unallocatable')) + ('multiplane.ErrLocationNotServed',) READINESS_PACKAGES = ('./internal/coordination', './internal/custody', './internal/site/...', './internal/multiplane', './cmd/fleet-multiplane') # Redfish mode (run.sh --redfish) adds its executor and probe to the readiness gate. PROVIDER = os.environ.get('FLEET_SITE_PROVIDER', 'libvirt') if PROVIDER == 'redfish': - REQUIRED_SOURCE_MARKERS += ('"redfish-probe"', '"install-b"', 'redfish.NewPinnedClient') + REQUIRED_SOURCE_MARKERS += ('"redfish-probe"', 'redfish.NewPinnedClient') READINESS_PACKAGES += ('./internal/redfish',) # The one Device the acceptance allocates, as the site store names it. In # Redfish mode it is enrolled as lab target A (System-1), a persistent domain. diff --git a/hack/multiplane/milo.py b/hack/multiplane/milo.py index 5e5ee1c2..2dc8970f 100755 --- a/hack/multiplane/milo.py +++ b/hack/multiplane/milo.py @@ -11,7 +11,8 @@ grants and the metal CRDs inside the project, and in the provider project the inventory and Device custody CRDs. The provider project's Fleet components each get their own token: the Metal provider (management), the - custody coordinator, the release controller and fixture discovery. + custody coordinator, the release controller and fixture discovery. A staff + token creates recoveries. Production uses Milo's own project provisioning, service catalog and IAM; this is not that machinery. """ @@ -38,7 +39,7 @@ def wait(fn,seconds,what): d=root/role;ns='milo-'+role if not d.exists(): d.mkdir(mode=0o700) - who=('bootstrap','management','customer')+(('coordinator','release','discovery') if role=='provider' else ()) + who=('bootstrap','management','customer')+(('coordinator','release','discovery','staff') 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=='bootstrap' 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) @@ -96,7 +97,10 @@ def wait(fn,seconds,what): {'apiGroups':['fleet.datumapis.com'],'resources':['deviceinstallations/status','devicewipes/status','devicerecoveries/status'],'verbs':['get','update']}, {'apiGroups':['metal.datumapis.com'],'resources':['machineallocations'],'verbs':['get','list','watch']}], 'release':[{'apiGroups':['fleet.datumapis.com'],'resources':['devicewipes'],'verbs':['get','create']}], - 'discovery':[{'apiGroups':['fleet.datumapis.com'],'resources':['devices'],'verbs':['get','list']},{'apiGroups':['fleet.datumapis.com'],'resources':['devices/status'],'verbs':['get','update']}]} + 'discovery':[{'apiGroups':['fleet.datumapis.com'],'resources':['devices'],'verbs':['get','list']},{'apiGroups':['fleet.datumapis.com'],'resources':['devices/status'],'verbs':['get','update']}], + # Staff create recoveries and read inventory and custody, nothing else. + # The coordinator treats every unconfigured creator as staff. + 'staff':[{'apiGroups':['fleet.datumapis.com'],'resources':['devices','devicecustodies'],'verbs':['get','list','watch']},{'apiGroups':['fleet.datumapis.com'],'resources':['devicerecoveries'],'verbs':['get','list','watch','create']}]} 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}]}) diff --git a/hack/multiplane/redfish_steps.py b/hack/multiplane/redfish_steps.py index a0aa3941..8460bcf7 100644 --- a/hack/multiplane/redfish_steps.py +++ b/hack/multiplane/redfish_steps.py @@ -224,9 +224,11 @@ def discovery_faults(s): before = len(audit(s)) cases = [] try: - def probe(name, creds, system, uuid, want): + pin = (d / 'bmc-pin').read_text().strip() + + def probe(name, creds, system, uuid, want, pin=pin): r = subprocess.run([str(s / 'fleet-multiplane-host'), 'redfish-probe', '--endpoint', 'https://127.0.0.1:%d' % port, '--credentials', str(creds), - '--system', system, '--uuid', uuid, '--pin', (d / 'bmc-pin').read_text().strip()], text=True, capture_output=True, timeout=120) + '--system', system, '--uuid', uuid, '--pin', pin], text=True, capture_output=True, timeout=120) line = (r.stdout.strip().splitlines() or [''])[-1] cases.append({'case': name, 'system': system, 'exitCode': r.returncode, 'outcome': line}) if r.returncode != want: @@ -241,6 +243,13 @@ def probe(name, creds, system, uuid, want): probe('ResetType On not advertised (injected)', good, TARGET_A['system'], TARGET_A['uuid'], 11) finally: bmc(s, 'python3', '/opt/fleet-lab/fleet_lab_adapter.py', 'fault', 'clear') + # Another key's digest: the TLS handshake fails before any request, + # so the BMC audit gains nothing. + other = pin[:-1] + ('0' if pin[-1] != '0' else '1') + seen = len(audit(s)) + probe('a TLS key other than the pin', good, TARGET_A['system'], TARGET_A['uuid'], 13, pin=other) + if len(audit(s)) != seen: + die('a probe with the wrong pin reached the BMC') probe('target A after the fault is cleared', good, TARGET_A['system'], TARGET_A['uuid'], 0) finally: pf.kill() @@ -255,7 +264,7 @@ def probe(name, creds, system, uuid, want): 'client': 'internal/redfish discovery through fleet-multiplane redfish-probe', 'cases': cases, 'auditRequests': len(window), 'mutatingRequests': 0, 'rejectedRequests': sum(1 for e in window if e['principal'] == 'rejected')}) - print('redfish-discovery-faults: real emulator discovery selected each enrolled System exactly; wrong credential, swapped or unknown identity and an unadvertised ResetType were refused with GETs only') + print('redfish-discovery-faults: real emulator discovery selected each enrolled System exactly; wrong credential, swapped or unknown identity and an unadvertised ResetType were refused with GETs only; a TLS key other than the pin reached no request') def arm_lost_response(s): @@ -378,7 +387,21 @@ def isolation(s): print('redfish-isolation: target B never started, never received a Redfish effect and its disk is unchanged; target A disk independently hashes as all zeroes after the final cleanup') +def audit_mark(s): + """Record the BMC audit's length for a later audit-unchanged.""" + (s / 'redfish' / 'audit-mark').write_text('%d\n' % len(audit(s))) + + +def audit_unchanged(s): + """No request after the mark carried an effect.""" + mark = int((s / 'redfish' / 'audit-mark').read_text()) + effects = mutating(audit(s)[mark:]) + if effects: + die('the BMC received an effect: %s' % [{k: e.get(k) for k in ('method', 'path', 'resetType')} for e in effects]) + + if __name__ == '__main__': step, state = sys.argv[1], pathlib.Path(sys.argv[2]) {'enroll': enroll, 'baseline': baseline, 'discovery-faults': discovery_faults, 'arm-lost-response': arm_lost_response, - 'lost-response': lost_response, 'bmc-interrupt': bmc_interrupt, 'isolation': isolation}[step](state) + 'lost-response': lost_response, 'bmc-interrupt': bmc_interrupt, 'isolation': isolation, + 'audit-mark': audit_mark, 'audit-unchanged': audit_unchanged}[step](state) diff --git a/hack/multiplane/scenarios.py b/hack/multiplane/scenarios.py new file mode 100644 index 00000000..21495569 --- /dev/null +++ b/hack/multiplane/scenarios.py @@ -0,0 +1,332 @@ +#!/usr/bin/env python3 +"""Evidence checks for the #174 failure scenarios in the multi-plane runs. + +Each command reads the provider project with its bootstrap credential and the +cell with its admin kubeconfig, checks one outcome, and writes a sanitized +record under evidence/. None of them writes custody or an operation. +""" +import datetime +import json +import pathlib +import subprocess +import sys +import time + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) +import harness # noqa: E402 (site store layout) + +NS, SITE = 'fleet-coordination', 'fleet-site' +PROVIDER_NS, DEVICE = 'fleet-provider', 'synthetic-device-central-01' +ASSIGNMENTS = 'coordination.fleet.datumapis.com/role=assignment' +REDFISH = harness.PROVIDER == 'redfish' + + +def die(message): + raise SystemExit(message) + + +def kubectl(s, config, *args, check=True, input=None): + r = subprocess.run(['kubectl', '--kubeconfig', str(s / config), '--request-timeout=20s', *args], text=True, capture_output=True, input=input) + if check and r.returncode: + die('kubectl %s failed: %s' % (' '.join(args[:4]), r.stderr.strip()[:300])) + return r + + +def get(s, config, *args): + return json.loads(kubectl(s, config, *args, '-o', 'json').stdout) + + +def provider(s, *args): + return get(s, 'provider/bootstrap-project.json', '-n', PROVIDER_NS, *args) + + +def custody(s): + return provider(s, 'get', 'devicecustody', DEVICE) + + +def items(s, kind): + return provider(s, 'get', kind)['items'] + + +def write(s, name, record): + record = dict(record, observedAt=datetime.datetime.now(datetime.timezone.utc).isoformat()) + (s / 'evidence' / name).write_text(json.dumps(record, indent=2, sort_keys=True) + '\n') + + +def wait_for(fn, timeout, what, interval=3): + end = time.monotonic() + timeout + while time.monotonic() < end: + value = fn() + if value: + return value + time.sleep(interval) + die('timed out waiting for ' + what) + + +def bmc_effects(s): + """Mutating BMC requests in the lab audit, in Redfish mode.""" + if not REDFISH: + return [] + import redfish_steps + return redfish_steps.mutating(redfish_steps.audit(s)) + + +def admitted_key(op): + """An operation's site key at the fence custody admitted it, or None + before the coordinator recorded the admission.""" + fence = (op.get('status', {}).get('admission') or {}).get('fence') + return harness.operation_key(op['kind'], op['metadata']['name'], fence) if fence else None + + +def handoff_for(s, key): + """The assignment handoff for the operation admission with this site key.""" + for h in get(s, 'cell-admin.yaml', '-n', NS, 'get', 'machineallocationhandoffs', '-l', ASSIGNMENTS)['items']: + a = json.loads(h['spec']['assignmentJSON']) + if harness.operation_key(a['operation']['kind'], a['operation']['name'], a['fence']) == key: + return h['metadata']['name'] + return None + + +def same_admission(ref, key): + """Whether custody's operation reference (kind, name, fence) names the + admission with this site key.""" + return bool(ref) and harness.operation_key(ref.get('kind', ''), ref.get('name', ''), ref.get('fence', 0)) == key + + +def import_inert(s): + """Importing Devices admitted, delivered and sent nothing: no operation, + allocation, assignment, worker Job or journal entry exists, and custody + has no active operation, result or hold.""" + found = {kind: [o['metadata']['name'] for o in items(s, kind)] for kind in ('deviceinstallations', 'devicewipes', 'devicerecoveries', 'machineallocations')} + if any(found.values()): + die('records exist before any allocation: %s' % found) + records = items(s, 'devicecustodies') + devices = sorted(d['metadata']['name'] for d in items(s, 'devices')) + if sorted(c['metadata']['name'] for c in records) != devices: + die('custody does not exist for exactly the imported Devices') + for c in records: + spec = c['spec'] + if spec.get('activeOperation') or spec.get('lastResult') or spec.get('recoveryHold') or spec['holder']['type'] != 'None': + die('imported custody is not idle: %s' % c['metadata']['name']) + if get(s, 'cell-admin.yaml', '-n', NS, 'get', 'machineallocationhandoffs', '-l', ASSIGNMENTS)['items']: + die('an assignment was delivered before any allocation') + if get(s, 'cell-admin.yaml', '-n', SITE, 'get', 'jobs')['items']: + die('a worker Job exists before any allocation') + if harness.journal(s): + die('the site journal holds an operation before any allocation') + effects = bmc_effects(s) + if effects: + die('the BMC received an effect before any allocation: %s' % effects) + write(s, 'import-inert.json', {'devices': devices, 'custody': {c['metadata']['name']: {'state': c['spec']['state'], 'fence': c['spec']['fence']} for c in records}, + 'operations': 0, 'allocations': 0, 'assignments': 0, 'workerJobs': 0, 'journalOperations': 0, + 'bmcEffects': 0 if REDFISH else None}) + print('import-inert: %d imported Devices; no operation, allocation, assignment, worker Job or journal entry%s' + % (len(devices), '; the BMC audit holds no effect' if REDFISH else '')) + + +def staff_access(s): + """The staff identity creates recoveries and reads inventory and custody. + It cannot read Secrets, where a bootstrap payload would be sealed, or + write any other operation, allocation or custody. It holds no consumer + project or hub credential.""" + staff = 'provider/staff-project.json' + probe = {'apiVersion': 'fleet.datumapis.com/v1alpha1', 'metadata': {'name': 'staff-probe', 'namespace': PROVIDER_NS}, 'spec': {}} + denied = { + 'get Secrets': ('-n', PROVIDER_NS, 'get', 'secrets'), + 'get Secrets in default': ('-n', 'default', 'get', 'secrets'), + 'create a DeviceInstallation': ('create', '--dry-run=server', '-f', '-', json.dumps(dict(probe, kind='DeviceInstallation'))), + 'create a DeviceWipe': ('create', '--dry-run=server', '-f', '-', json.dumps(dict(probe, kind='DeviceWipe'))), + 'create a MachineAllocation': ('create', '--dry-run=server', '-f', '-', json.dumps(dict(probe, apiVersion='metal.datumapis.com/v1alpha1', kind='MachineAllocation'))), + 'update custody': ('-n', PROVIDER_NS, 'annotate', '--dry-run=server', 'devicecustody', DEVICE, 'probe=staff'), + 'delete custody': ('-n', PROVIDER_NS, 'delete', '--dry-run=server', 'devicecustody', DEVICE), + } + results = {} + for name, args in denied.items(): + stdin = None + if args[-2:-1] == ('-',): + args, stdin = args[:-1], args[-1] + r = kubectl(s, staff, *args, check=False, input=stdin) + if r.returncode == 0 or 'forbidden' not in r.stderr.lower(): + die('staff was not forbidden to %s: %s' % (name, r.stderr.strip()[:200])) + results[name] = 'Forbidden' + for name, args in {'read custody': ('-n', PROVIDER_NS, 'get', 'devicecustody', DEVICE), 'list recoveries': ('-n', PROVIDER_NS, 'get', 'devicerecoveries')}.items(): + if kubectl(s, staff, *args, check=False).returncode: + die('staff cannot ' + name) + results[name] = 'Allowed' + elsewhere = [str(p.relative_to(s)) for p in s.glob('*/staff-project.json') if p.parent.name != 'provider'] + [str(p.relative_to(s)) for p in s.glob('staff*.yaml')] + if elsewhere: + die('staff holds a credential outside the provider project: %s' % elsewhere) + write(s, 'staff-access.json', {'checks': results, 'credentials': ['provider project'], 'bootstrapPayloads': 'refused at admission and at the site'}) + print('staff-access: staff read custody and list recoveries; Secrets, other operations, allocations and custody writes forbidden; no consumer or hub credential') + + +def contention(s): + """Custody names the winner's MachineAllocation, and it is the only one.""" + allocations = [a for a in items(s, 'machineallocations') if a['spec']['deviceRef']['name'] == DEVICE] + winner = get(s, 'consumer-a/management-project.json', '-n', 'default', 'get', 'machine', 'allocation') + # The allocation labels the Machine incarnation it is for. + if len(allocations) != 1 or allocations[0]['metadata'].get('labels', {}).get('fleet.datumapis.com/machine-uid') != winner['metadata']['uid']: + die('expected one MachineAllocation, for consumer-a: %s' % [a['metadata']['name'] for a in allocations]) + holder = custody(s)['spec']['holder'] + if holder['type'] != 'Allocation' or (holder.get('allocationRef') or {}).get('name') != allocations[0]['metadata']['name']: + die('custody does not name the winning allocation: %s' % holder) + write(s, 'contention.json', {'allocations': 1, 'holder': holder['type'], 'holderNamesWinner': True}) + print('contention-custody: custody holds the Device for the one MachineAllocation, consumer-a\'s') + + +def newest_install(s): + ops = sorted(items(s, 'deviceinstallations'), key=lambda o: o['metadata']['creationTimestamp']) + return ops[-1] if ops else None + + +def wait_installer(s, step): + """Wait until the newest installation journaled its installer step.""" + name = newest_install(s)['metadata']['name'] + # The site keys the operation by kind, name and the fence it was admitted + # at; a same-name installation created later is admitted at another. + key = wait_for(lambda: admitted_key(provider(s, 'get', 'deviceinstallation', name)), 300, 'the second installation to be admitted', interval=1) + (s / 'deadline-install.json').write_text(json.dumps({'name': name, 'key': key}) + '\n') + + def journaled(): + for o in harness.journal(s) or []: + if o['operation'] == key and any(n == step for n, _ in o['steps']): + return o + return None + wait_for(journaled, 600, 'the second installation to journal %s' % step, interval=1) + + +def deadline_op(s): + ref = json.loads((s / 'deadline-install.json').read_text()) + op = provider(s, 'get', 'deviceinstallation', ref['name']) + if admitted_key(op) != ref['key']: + die('the deadline installation was replaced') + return op, ref['key'] + + +def wipes_for(s, allocation): + return [w for w in items(s, 'devicewipes') if (w['spec'].get('authority', {}).get('allocationRef') or {}).get('name') == allocation] + + +def release_waits(s): + """The Machine is deleted mid-install. Release begins, and waits: custody + holds the Device for release with the installation still active, and no + wipe exists.""" + op, key = deadline_op(s) + allocation = op['spec']['authority']['allocationRef']['name'] + spec = custody(s)['spec'] + active = spec.get('activeOperation') or {} + if spec['holder']['type'] != 'Release' or not same_admission(active, key): + die('release did not wait for the installation: holder %s, active %s' % (spec['holder']['type'], active.get('kind'))) + if wipes_for(s, allocation): + die('a wipe was created while the installation was active') + machine = kubectl(s, 'consumer-b/management-project.json', '-n', 'default', 'get', 'machine', 'allocation', '-o', 'json') + m = json.loads(machine.stdout) + if not m['metadata'].get('deletionTimestamp'): + die('the Machine is not being deleted') + write(s, 'release-waits.json', {'holder': 'Release', 'activeOperation': 'DeviceInstallation', 'wipes': 0, 'machineDeleting': True, + 'openGates': spec['holder'].get('openGates', [])}) + print('release-waits: the Machine is deleting; custody holds the Device for release with the installation active and no wipe') + + +def deadline_hold(s): + """The installation passes its deadline: it ends OutcomeUnknown with + DeadlineExceeded, custody holds it, and its worker has stopped.""" + def ended(): + op, _ = deadline_op(s) + return op if op.get('status', {}).get('phase') == 'OutcomeUnknown' else None + op = wait_for(ended, 900, 'the installation to end OutcomeUnknown') + key = admitted_key(op) + status = op['status'] + if status.get('reason') != 'DeadlineExceeded': + die('the installation ended OutcomeUnknown for %s, not its deadline' % status.get('reason')) + hold = custody(s)['spec'].get('recoveryHold') or {} + if not same_admission(hold, key) or hold.get('fence') != status.get('fence'): + die('custody does not hold the installation: %s' % hold.get('kind')) + handoff = handoff_for(s, key) + finished = [] + if handoff: + def stopped(): + pods = get(s, 'cell-admin.yaml', '-n', SITE, 'get', 'pods', '-l', 'fleet.datumapis.com/handoff=' + handoff)['items'] + ends = [c['state']['terminated']['finishedAt'] for p in pods for c in p['status'].get('containerStatuses', []) if 'terminated' in c.get('state', {})] + return ends if pods and len(ends) == len(pods) else None + finished = wait_for(stopped, 300, 'the installation worker to stop') + boots = [b for b in harness.journal(s) or [] if b['operation'] == key] + record = {'phase': 'OutcomeUnknown', 'reason': 'DeadlineExceeded', 'fence': status['fence'], 'deadline': status.get('deadline'), + 'holdFence': hold['fence'], 'workerFinishedAt': max(finished) if finished else None, 'journaledSteps': [n for o in boots for n, _ in o['steps']]} + (s / 'deadline-hold.json').write_text(json.dumps(record) + '\n') + write(s, 'deadline-hold.json', record) + print('deadline-hold: the installation ended OutcomeUnknown at its deadline; custody holds it at fence %d; its worker stopped' % status['fence']) + + +def deadline_settled(s): + """The release's wipe settled the installation hold: admitted above the + held fence after the worker stopped, Succeeded, the hold cleared, the + Device free and the Machine gone.""" + op, _ = deadline_op(s) + held = json.loads((s / 'deadline-hold.json').read_text()) + allocation = op['spec']['authority']['allocationRef']['name'] + wipes = [w for w in wipes_for(s, allocation) if w.get('status', {}).get('phase') == 'Succeeded'] + if len(wipes) != 1: + die('expected one succeeded wipe for the released allocation') + wipe = wipes[0]['status'] + spec = custody(s)['spec'] + if wipe['fence'] <= held['fence'] or spec.get('recoveryHold') or spec['holder']['type'] != 'None': + die('the wipe did not settle the installation hold: wipe fence %s, held fence %s, hold %s' % (wipe['fence'], held['fence'], bool(spec.get('recoveryHold')))) + if held['workerFinishedAt'] and wipe['admittedAt'] < held['workerFinishedAt']: + die('the wipe was admitted before the installation worker stopped') + r = kubectl(s, 'consumer-b/management-project.json', '-n', 'default', 'get', 'machine', 'allocation', check=False) + if r.returncode == 0 or 'NotFound' not in r.stderr: + die('the deleted Machine remains') + store, _ = harness.site_store(s) + write(s, 'deadline-settled.json', {'heldFence': held['fence'], 'wipeFence': wipe['fence'], 'wipeAdmittedAt': wipe['admittedAt'], + 'workerFinishedAt': held['workerFinishedAt'], 'siteStopped': (store or {}).get('stopped'), + 'holdCleared': True, 'holder': 'None', 'machineDeleted': True}) + print('deadline-settled: the release wipe was admitted at fence %d after the worker stopped, succeeded and cleared the hold; the Machine is gone' % wipe['fence']) + + +def rebuild_unverified(s): + """Custody was deleted. The coordinator rebuilds it Unverified and keeps + it there while no site reports its fence.""" + def rebuilt(): + r = kubectl(s, 'provider/bootstrap-project.json', '-n', PROVIDER_NS, 'get', 'devicecustody', DEVICE, '-o', 'json', check=False) + return json.loads(r.stdout) if r.returncode == 0 else None + c = wait_for(rebuilt, 300, 'custody to be rebuilt') + old = json.loads((s / 'rebuild-before.json').read_text()) + if c['metadata']['uid'] == old['uid']: + die('custody was not deleted') + if c['spec']['state'] != 'Unverified': + die('rebuilt custody is %s before any site report' % c['spec']['state']) + store, _ = harness.site_store(s) + record = {'oldFence': old['fence'], 'rebuiltState': 'Unverified', 'rebuiltHolder': c['spec']['holder']['type'], 'siteFence': (store or {}).get('fence'), + 'siteStopped': (store or {}).get('stopped')} + (s / 'rebuild-unverified.json').write_text(json.dumps(record) + '\n') + print('rebuild-unverified: custody rebuilt Unverified with holder %s while the site cannot report' % record['rebuiltHolder']) + + +def rebuild_before(s): + c = custody(s) + if c['spec']['state'] != 'Verified' or c['spec']['holder']['type'] != 'None': + die('the rebuild starts from free, Verified custody') + (s / 'rebuild-before.json').write_text(json.dumps({'uid': c['metadata']['uid'], 'fence': c['spec']['fence']}) + '\n') + + +def rebuild_verified(s): + """After the site reports again, custody is Verified with a fence above + every fence the site stored.""" + before = json.loads((s / 'rebuild-unverified.json').read_text()) + c = wait_for(lambda: (lambda c: c if c['spec']['state'] == 'Verified' else None)(custody(s)), 600, 'rebuilt custody to be Verified') + site_fence = max(before['siteFence'] or 0, before['siteStopped'] or 0) + if c['spec']['fence'] <= site_fence or c['spec']['fence'] <= before['oldFence']: + die('rebuilt custody fence %d is not above the site fence %d and the old fence %d' % (c['spec']['fence'], site_fence, before['oldFence'])) + if items(s, 'machineallocations') and any(a['status'].get('phase') != 'Released' for a in items(s, 'machineallocations')): + die('an allocation became active during the rebuild') + write(s, 'rebuild.json', dict(before, verifiedFence=c['spec']['fence'], verifiedHolder=c['spec']['holder']['type'], probeAllocated=False)) + print('rebuild-verified: custody Verified at fence %d, above the site fence %d; nothing was allocated while Unverified' % (c['spec']['fence'], site_fence)) + + +if __name__ == '__main__': + command, state = sys.argv[1], pathlib.Path(sys.argv[2]) + {'import-inert': import_inert, 'staff-access': staff_access, 'contention': contention, 'release-waits': release_waits, + 'deadline-hold': deadline_hold, 'deadline-settled': deadline_settled, 'rebuild-before': rebuild_before, + 'rebuild-unverified': rebuild_unverified, 'rebuild-verified': rebuild_verified, + 'wait-installer': lambda s: wait_installer(s, sys.argv[3])}[command](state) diff --git a/hack/multiplane/steps.sh b/hack/multiplane/steps.sh index 6af24770..4c118e00 100755 --- a/hack/multiplane/steps.sh +++ b/hack/multiplane/steps.sh @@ -47,6 +47,24 @@ print(hashlib.sha256(sys.stdin.buffer.read()).hexdigest())' # The step the install has journaled once its installer boot was requested. installer_step=installer-start [[ $(cat "$state/site-provider" 2>/dev/null) != redfish ]] || installer_step=installer-power-on +scenario() { python3 hack/multiplane/scenarios.py "$@"; } +redfish() { [[ $(cat "$state/site-provider" 2>/dev/null) == redfish ]]; } +# The lab BMC audit: mark its length, then require no effect after the mark. +audit_mark() { ! redfish || python3 hack/multiplane/redfish_steps.py audit-mark "$state"; } +audit_unchanged() { ! redfish || python3 hack/multiplane/redfish_steps.py audit-unchanged "$state"; } +# A cell site Deployment stopped for a fault. Its Flux layer is suspended +# first, so the harness is never a second writer, and resumed to restore it. +site_stop() { + cell -n flux-system patch kustomization/fleet-site-services --field-manager=fleet-fault-injection --type=merge -p '{"spec":{"suspend":true}}' >/dev/null + site scale "deployment/$1" --replicas=0 >/dev/null + for _ in $(seq 1 120); do [[ -z $(site get pods -l "app.kubernetes.io/name=$1" -o name) ]] && return; sleep 1; done + echo "$1 did not stop" >&2; return 1 +} +site_restore() { + cell -n flux-system patch kustomization/fleet-site-services --field-manager=fleet-fault-injection --type=merge -p '{"spec":{"suspend":false}}' >/dev/null + cell -n flux-system annotate --overwrite kustomization/fleet-site-services "reconcile.fluxcd.io/requestedAt=$(date +%s)" >/dev/null + site wait --for=jsonpath='{.status.availableReplicas}'=1 "deployment/$1" --timeout=300s >/dev/null +} wait_running_pod() { for _ in $(seq 1 "${2:-120}"); do uid=$(py running-pod "$state" "$1") @@ -63,6 +81,68 @@ case "$step" in b=$(k "$state/consumer-b/management-project.json" -n default get machine allocation -o jsonpath='{.status.phase}/{.status.conditions[?(@.type=="Bound")].reason}') [[ $a == Bound/* && $b == Pending/InsufficientCapacity ]] || { echo "unexpected contention status: A=$a B=$b" >&2; exit 1; } printf 'contention: consumer-a %s; consumer-b %s\n' "$a" "$b" + scenario contention "$state" + ;; + import-inert) + scenario import-inert "$state" + ;; + staff-access) + scenario staff-access "$state" + ;; + deadline-admit) + # Consumer B's installation is admitted under a four-minute deadline while + # the site's boot server is stopped, so its installer never boots. Only + # this admission uses the short deadline. + site_stop fleet-site-boot + bash hack/multiplane/coordinator.sh restart "$state" --installation-deadline=4m >/dev/null + "$host" admit-install-b --config "$state/acceptance.json" >/dev/null + bash hack/multiplane/coordinator.sh restart "$state" >/dev/null + scenario wait-installer "$state" "$installer_step" + printf 'deadline-admit: the second installation was admitted under a four-minute deadline and journaled its installer boot with the boot server stopped\n' + ;; + machine-delete) + # The customer deletes Machine B mid-install. One release pass begins the + # release, which must wait for the installation. + k "$state/consumer-b/customer-project.json" -n default delete machine allocation --wait=false >/dev/null + "$host" release-b --config "$state/acceptance.json" --once >/dev/null 2>&1 || true + scenario release-waits "$state" + ;; + deadline-hold) + scenario deadline-hold "$state" + # A staff recovery naming the wrong hold is refused before anything is + # delivered or sent. + before=$(journal_digest) + audit_mark + "$host" recovery-mismatch --config "$state/acceptance.json" + [[ $before == "$(journal_digest)" ]] || { echo 'site store changed for a refused recovery' >&2; exit 1; } + audit_unchanged + # Flux restores the boot server before the release's wipe. + site_restore fleet-site-boot + ;; + deadline-settled) + scenario deadline-settled "$state" + ;; + rebuild) + # Custody of the free Device is deleted while the site cannot report its + # fence: the observer answers fence reports, and the hub accepts none + # older than a minute. + scenario rebuild-before "$state" + site_stop fleet-site-observer + sleep 75 + bootstrap="$state/provider/bootstrap-project.json" + k "$bootstrap" -n fleet-provider delete devicecustody synthetic-device-central-01 --wait=false >/dev/null + k "$bootstrap" -n fleet-provider patch devicecustody synthetic-device-central-01 --type=merge -p '{"metadata":{"finalizers":null}}' >/dev/null + scenario rebuild-unverified "$state" + # A new consumer-a Machine finds no eligible capacity while custody is + # Unverified. + customer="$state/consumer-a/customer-project.json" + k "$customer" -n default delete machine allocation --wait --timeout=60s >/dev/null + k "$customer" -n default create -f - >/dev/null <<'JSON' +{"apiVersion":"metal.datumapis.com/v1alpha1","kind":"Machine","metadata":{"name":"allocation","namespace":"default"},"spec":{"machineClassRef":{"name":"local-class"},"machineProfileRef":{"name":"local-profile"},"locationRef":{"name":"local"},"powerState":"Off"}} +JSON + "$host" probe-unallocatable --config "$state/acceptance.json" --once + site_restore fleet-site-observer + scenario rebuild-verified "$state" ;; await-delivery) for _ in $(seq 1 120); do @@ -225,6 +305,7 @@ case "$step" in # duplicate the API refuses, an assignment naming another cell, and a # replay of an admitted operation below the Device's stored fence. before=$(journal_digest) + audit_mark py delivery-faults "$state" create for fault in wrong-cell stale-fence; do job=$(cat "$state/fault-$fault-job") @@ -233,13 +314,20 @@ case "$step" in done after=$(journal_digest) [[ $before == "$after" ]] || { echo 'site store changed during delivery faults' >&2; exit 1; } + audit_unchanged py delivery-faults "$state" verify py delivery-faults "$state" delete printf 'delivery-faults: duplicate refused by the API; wrong-cell and stale-fence deliveries failed their Jobs by podFailurePolicy before effects; site store unchanged; kro pruned them\n' ;; - release-status-a|release-status-b) + release-status-b) + # The customer deleted Machine B; its release removed the finalizer last. + r=$(k "$state/consumer-b/management-project.json" -n default get machine allocation 2>&1 || true) + [[ $r == *NotFound* ]] || { echo "deleted consumer-b Machine remains: $r" >&2; exit 1; } + printf 'release-status-b: consumer-b Machine deleted after its release finished\n' + ;; + release-status-a) # Released claims must not keep public readiness or an installation reference. - project=consumer-a; [[ $step == release-status-a ]] || project=consumer-b + project=consumer-a v=$(k "$state/$project/management-project.json" -n default get machine allocation -o jsonpath='{.status.phase}/{.status.conditions[?(@.type=="Bound")].status}/{.status.conditions[?(@.type=="Ready")].status}/{.status.currentInstallationRef.name}/{.metadata.finalizers}') [[ $v == Released/False/False// ]] || { echo "released $project Machine phase/Bound/Ready/currentInstallationRef/finalizers: $v" >&2; exit 1; } if [[ $step == release-status-a ]]; then diff --git a/hack/multiplane/test-harness.sh b/hack/multiplane/test-harness.sh index 244f8f04..5cceb64d 100755 --- a/hack/multiplane/test-harness.sh +++ b/hack/multiplane/test-harness.sh @@ -68,7 +68,8 @@ with tempfile.TemporaryDirectory() as tmp: d = pathlib.Path(tempfile.mkdtemp(dir=tmp)); d.chmod(0o700); return d good_root = tmp / 'good'; (good_root / 'cmd/fleet-multiplane').mkdir(parents=True) - markers = ['seed', 'allocate', 'admit-install', 'install', 'release', 'release-b', 'reuse', 'coordinator', 'image', 'boot-service', 'boot-denials', 'site-worker', 'site-observer'] + markers = ['seed', 'allocate', 'admit-install', 'install', 'release', 'release-b', 'reuse', 'coordinator', 'image', 'boot-service', 'boot-denials', 'site-worker', 'site-observer', + 'admit-install-b', 'recovery-mismatch', 'probe-unallocatable'] (good_root / 'cmd/fleet-multiplane/main.go').write_text(' '.join('"%s"' % m for m in markers) + ' multiplane.ErrLocationNotServed') bad_root = tmp / 'bad'; (bad_root / 'cmd/fleet-multiplane').mkdir(parents=True) (bad_root / 'cmd/fleet-multiplane/main.go').write_text(' '.join('"%s"' % m for m in markers)) @@ -189,10 +190,11 @@ with tempfile.TemporaryDirectory() as tmp: for name, text in (('steps', steps), ('evidence', evidence), ('harness', harness.read_text())): check('no docker process launch in site execution: ' + name, '-vm' not in text and 'cell.pid' not in text) sequence = (root / 'hack/multiplane/acceptance.sh').read_text() - order = ['custody-crd-rules', 'allocate', 'verify-contention', 'admit-install', 'await-delivery', 'partition', 'dispatch', 'interrupt-pod', 'interrupt-job', 'resume', + order = ['custody-crd-rules', 'import-inert', 'staff-access', 'allocate', 'verify-contention', 'admit-install', 'await-delivery', 'partition', 'dispatch', 'interrupt-pod', 'interrupt-job', 'resume', 'worker-rbac', 'partition-readiness', 'heal', 'install', 'install-repeat', 'lifecycle', 'graph-lifecycle', 'drift', 'restart', 'fail-closed', 'retention', 'reflection-faults', 'release', 'release-status-a', - 'reuse', 'reuse-status', 'delivery-faults', 'release-b', 'release-status-b', 'wrong-location', 'boot-denials', 'flux-final', 'evidence'] + 'reuse', 'reuse-status', 'delivery-faults', 'deadline-admit', 'machine-delete', 'deadline-hold', 'release-b', 'deadline-settled', 'release-status-b', + 'rebuild', 'wrong-location', 'boot-denials', 'flux-final', 'evidence'] positions = [sequence.find(' ' + name + ' ') for name in order] check('acceptance phase order', all(p >= 0 for p in positions) and positions == sorted(positions), str(list(zip(order, positions)))) for name in order: diff --git a/hack/multiplane/test-redfish.py b/hack/multiplane/test-redfish.py index 846eb322..e13f1950 100644 --- a/hack/multiplane/test-redfish.py +++ b/hack/multiplane/test-redfish.py @@ -154,7 +154,7 @@ def build(path): for name in re.findall(r'^rf (\S+)', sequence, re.M): check('redfish step implemented: ' + name, "'%s':" % name in redfish_steps) order = ['baseline', 'discovery-faults', 'allocate', 'arm-lost-response', 'dispatch', 'bmc-interrupt', 'interrupt-pod', 'interrupt-job', 'lost-response', 'resume', 'release', - 'reuse', 'delivery-faults', 'install-b', 'release-b', 'boot-denials', 'isolation', 'evidence'] + 'reuse', 'delivery-faults', 'deadline-admit', 'machine-delete', 'deadline-hold', 'release-b', 'deadline-settled', 'rebuild', 'boot-denials', 'isolation', 'evidence'] positions = [sequence.find(' ' + n + ' ') for n in order] check('Redfish phase order', all(p >= 0 for p in positions) and positions == sorted(positions), str(list(zip(order, positions)))) for path in sorted(list((root / 'internal/redfish').glob('*.go')) + list((root / 'internal/site/redfishwork').glob('*.go'))): diff --git a/internal/multiplane/runner.go b/internal/multiplane/runner.go index f69aaffa..fdac9c4b 100644 --- a/internal/multiplane/runner.go +++ b/internal/multiplane/runner.go @@ -161,11 +161,16 @@ func coordinator(ctx context.Context, c Config, registry *custody.Registry) (*cu // Coordinate is the coordinator process: the custody loop, delivering // through Karmada, and fixture discovery for the cell's Devices under the // discovery identity. -func Coordinate(ctx context.Context, c Config, onError func(error)) error { +// A positive installationDeadline replaces the installation kind's deadline +// for operations this process admits; the deadline scenario uses it. +func Coordinate(ctx context.Context, c Config, installationDeadline time.Duration, onError func(error)) error { registry, err := custody.DefaultRegistry() if err != nil { return err } + if installationDeadline > 0 { + registry.Kind("DeviceInstallation").Deadline = installationDeadline + } coord, _, sites, api, err := coordinator(ctx, c, registry) if err != nil { return err @@ -418,8 +423,10 @@ var ErrAdmittedUnknown = errors.New("installation admitted; its result remains u // AdmitInstall creates consumer A's installation and returns // ErrAdmittedUnknown once custody admitted it and its handoff exists. -func (r *Runner) AdmitInstall(ctx context.Context) error { - _, _, _, operation, err := r.installation(ctx, 0) +func (r *Runner) AdmitInstall(ctx context.Context) error { return r.admitIndex(ctx, 0) } + +func (r *Runner) admitIndex(ctx context.Context, index int) error { + _, _, _, operation, err := r.installation(ctx, index) if err != nil { return err } @@ -436,10 +443,6 @@ func (r *Runner) AdmitInstall(ctx context.Context) error { func (r *Runner) Install(ctx context.Context) error { return r.InstallIndex(ctx, 0) } -// InstallSecond installs consumer B's Installation after it reused the -// capacity, through the same allocator and federation path. -func (r *Runner) InstallSecond(ctx context.Context) error { return r.InstallIndex(ctx, 1) } - func (r *Runner) InstallIndex(ctx context.Context, index int) error { q, _, install, operation, err := r.installation(ctx, index) if err != nil { diff --git a/internal/multiplane/scenarios.go b/internal/multiplane/scenarios.go new file mode 100644 index 00000000..bfdfec90 --- /dev/null +++ b/internal/multiplane/scenarios.go @@ -0,0 +1,126 @@ +package multiplane + +import ( + "context" + "errors" + "fmt" + "path/filepath" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + 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" +) + +// The failure scenarios of #174's acceptance tests. Each phase checks one +// outcome through the provider project API and never writes custody. + +// AdmitInstallSecond creates consumer B's installation and returns +// ErrAdmittedUnknown once custody admitted it. +func (r *Runner) AdmitInstallSecond(ctx context.Context) error { return r.admitIndex(ctx, 1) } + +// recoveryMismatchName names the staff recovery the mismatch phase creates, +// so a retried phase finds the same one. +const recoveryMismatchName = "synthetic-recovery-mismatch" + +// RecoveryMismatch creates, as staff, a DeviceRecovery that names the held +// operation at the wrong fence. Admission refuses it before anything is +// delivered: custody's fence and hold stay as they were. +func (r *Runner) RecoveryMismatch(ctx context.Context) error { + staff, err := API(filepath.Join(r.Config.State, "provider", "staff-project.json")) + if err != nil { + return err + } + before := &ops.DeviceCustody{} + if err := r.Provider.API.Get(ctx, client.ObjectKey{Namespace: DeviceNamespace, Name: Device}, before); err != nil { + return err + } + hold := before.Spec.RecoveryHold + if hold == nil { + return fmt.Errorf("%w: the Device has no recovery hold", errTerminal) + } + device := &inventory.Device{} + if err := r.Provider.API.Get(ctx, client.ObjectKey{Namespace: DeviceNamespace, Name: Device}, device); err != nil { + return err + } + recovery := &ops.DeviceRecovery{} + if err := staff.Get(ctx, client.ObjectKey{Namespace: DeviceNamespace, Name: recoveryMismatchName}, recovery); apierrors.IsNotFound(err) { + creator, err := identity(ctx, filepath.Join(r.Config.State, "provider", "staff-project.json")) + if err != nil { + return err + } + recovery = &ops.DeviceRecovery{ + ObjectMeta: metav1.ObjectMeta{Name: recoveryMismatchName, Namespace: DeviceNamespace, Labels: map[string]string{ops.LabelDeviceUID: string(device.UID)}}, + Spec: ops.DeviceRecoverySpec{ + OperationEnvelope: ops.OperationEnvelope{Creator: creator, DeviceRef: ops.DeviceReference{Name: device.Name}, + Authority: ops.Authority{ServiceRequest: &ops.ServiceRequest{Reason: "synthetic acceptance: a recovery for another hold"}}}, + Decision: ops.DecisionSettle, + Hold: &ops.HeldOperationReference{Kind: hold.Kind, Name: hold.Name, Fence: hold.Fence + 1000}, + Evidence: ops.RecoveryEvidence{ObservedAt: metav1.Now(), Summary: "synthetic acceptance evidence"}, + }, + } + if err := staff.Create(ctx, recovery); err != nil { + return err + } + } else if err != nil { + return err + } + switch phase := recovery.Status.Phase; { + case phase == ops.PhaseFailed: + case phase.Ended(): + return fmt.Errorf("%w: the mismatched recovery ended %s: %s", errTerminal, phase, recovery.Status.Reason) + default: + return fmt.Errorf("%w: the mismatched recovery 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.RecoveryHold == nil || !sameHold(after.Spec.RecoveryHold, hold) || after.Spec.ActiveOperation != nil { + return fmt.Errorf("%w: the refused recovery changed custody", errTerminal) + } + if recovery.Status.Fence != 0 || recovery.Status.AdmittedAt != nil { + return fmt.Errorf("%w: the refused recovery was admitted", errTerminal) + } + fmt.Printf("recovery-mismatch: refused %s; fence %d and the hold unchanged\n", recovery.Status.Reason, after.Spec.Fence) + return nil +} + +// sameHold reports whether two recovery holds name the same operation +// admission: kind, name and fence. +func sameHold(a, b *ops.RecoveryHold) bool { + return a.Kind == b.Kind && a.Name == b.Name && a.Fence == b.Fence +} + +// ProbeUnallocatable tries to allocate consumer A's Machine while custody +// is Unverified. The allocator must find no eligible capacity and record no +// allocation for the Machine. +func (r *Runner) ProbeUnallocatable(ctx context.Context) error { + state := &ops.DeviceCustody{} + if err := r.Provider.API.Get(ctx, client.ObjectKey{Namespace: DeviceNamespace, Name: Device}, state); err != nil { + return fmt.Errorf("%w: custody: %v", errPending, err) + } + if state.Spec.State != ops.CustodyUnverified { + return fmt.Errorf("%w: custody is %s, not Unverified", errTerminal, state.Spec.State) + } + q, err := r.request(ctx, 0) + if err != nil { + return err + } + if _, err := r.Allocator.Allocate(ctx, q.alloc); !errors.Is(err, allocation.ErrInsufficientCapacity) { + return fmt.Errorf("%w: allocation against Unverified custody: %v", errTerminal, err) + } + current, err := r.Allocator.Get(ctx, q.alloc.Machine) + if err != nil { + return err + } + if current != nil && current.Status.Phase != fleet.AllocationReleased { + return fmt.Errorf("%w: an allocation exists for the probe Machine", errTerminal) + } + fmt.Println("probe-unallocatable: no eligible capacity while custody is Unverified; no allocation recorded") + return nil +} From 76bd9e41e6f44670fbc04844a9094f77c74a69dc Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 25 Nov 2026 07:08:18 -0600 Subject: [PATCH 04/16] docs: Map the #174 acceptance tests to their end-to-end phases Record the failure scenarios each multi-plane run proves, the two site gaps they found, and what the emulator lab cannot cover. Increment C is now verified by both multi-plane runs; D's verification is pending. Co-Authored-By: Claude Opus 5.5 --- docs/development/README.md | 4 ++- docs/development/device-custody.md | 52 ++++++++++++++++++++++++++--- docs/development/roadmap.md | 7 ++-- docs/operations/multiplane.md | 53 +++++++++++++++++++++++------- docs/operations/redfish-lab.md | 13 ++++---- hack/multiplane/evidence.py | 6 ++-- test/acceptance/coverage.md | 47 ++++++++++++++------------ 7 files changed, 134 insertions(+), 48 deletions(-) diff --git a/docs/development/README.md b/docs/development/README.md index faf64def..9172a514 100644 --- a/docs/development/README.md +++ b/docs/development/README.md @@ -36,7 +36,9 @@ Increment C, the cutover. Every mode allocates, installs and releases on `DeviceCustody`, with the custody coordinator as its only writer. The Secret-backed coordinator, its private records and the old executors are deleted, and an allocation's private facts live on its MachineAllocation. The standalone -smoke verifies it. The end-to-end failure scenarios (Increment D) are proposed. +smoke and both multi-plane runs verify it. The end-to-end failure scenarios +(Increment D) are implemented, and their verification in both multi-plane runs +is pending. The opt-in [multi-plane acceptance harness](../operations/multiplane.md) composes the [local VM site](../operations/local-vm.md) with native Milo project APIs, the diff --git a/docs/development/device-custody.md b/docs/development/device-custody.md index c9a646d9..a74fe343 100644 --- a/docs/development/device-custody.md +++ b/docs/development/device-custody.md @@ -15,7 +15,7 @@ marked **implemented and verified**, **implemented and inert**, or | A: control-plane foundation | API types and CRDs for `DeviceCustody`, `DeviceInstallation`, `DeviceWipe` and `DeviceRecovery`; CEL rules; IAM resources and roles; the creator webhook; the kind registry and admission rule table; the coordinator's custody reconciler, admission, results, recovery, rebuild and retention; the capacity projector | **Implemented and verified**, except the capacity projector, which is **implemented and inert**. Verified with unit tests and with tests against a real API server. Increment C wires the rest into every mode. | | B: site execution | Per-Device fence store and journal, older-worker stop with a confirmation, deadlines, fenced typed results, per-Device credentials, pinned TLS, identity checks, the handoff payload, the site fence report, and the Redfish install and wipe phases behind the worker contract | **Implemented and verified.** Unit tested, including against TLS BMC stubs. Increment C delivers to it. | | C: cutover | MachineAllocations and quota claims named from the Machine UID, allocation and release on custody, the delivery loop, the simulator, local VM and Redfish sites, the creator webhook in the production Milo root, the manager's power projector, and deletion of the Secret-backed records and executors. See [Cutover](#cutover-increment-c). | **Implemented.** Verified by unit tests, tests against a real API server, the standalone smoke (`task standalone:test`), and both multi-plane runs, local VM and Redfish. | -| D: end-to-end failure scenarios | Harness phases and evidence checks for the #174 acceptance tests | **Proposed** | +| D: end-to-end failure scenarios | Harness phases and evidence checks for the #174 acceptance tests, and the two site fixes they found. See [Failure scenarios](#failure-scenarios-increment-d). | **Implemented.** Unit tested. Verification of both multi-plane runs is pending. | ## What Increment A adds @@ -381,6 +381,42 @@ event. - Bootstrap stays refused (O10). - `DeviceRecovery` needs no second person. +## Failure scenarios (Increment D) + +Both multi-plane runs, local VM and Redfish, run the #174 acceptance tests +end to end. The [coverage +inventory](../../test/acceptance/coverage.md#device-custody-and-operations) maps +each test to its phase, and the [multi-plane +phases](../operations/multiplane.md#acceptance-phases) describe each one. + +| Scenario | How the run produces it | +| --- | --- | +| Importing sends nothing | Checked before any allocation: no operation, assignment, worker Job, journal entry or BMC effect | +| Staff access | A staff token in the provider project reads custody and creates recoveries, and is forbidden everything else | +| Contention | Custody names the one MachineAllocation, the winner's | +| Deadline | The coordinator restarts with a four-minute installation deadline for one admission, and the boot server is stopped, so the installer is never served | +| Machine deleted mid-install | The customer deletes the Machine; release holds the Device and waits for the installation | +| Recovery for the wrong hold | Staff name the held installation at the wrong fence; admission refuses it with nothing delivered or sent | +| A wipe settles the hold | The release wipe is admitted above the held fence after the worker stopped | +| Rebuild | Custody is deleted while the site observer is stopped, so no fence report arrives | +| Pin mismatch | The Redfish probe connects with another key's digest and reaches no request | + +The scenarios found two site gaps, both fixed: + +- **A worker stopped at its deadline left its boot admission open** until the + boot window expired, so the server could still fetch the installer when + nothing could resume or observe the operation. Both workers now close it at + the deadline. A worker stopped from outside still leaves it open for its + replacement. +- **The local VM wipe refused to run while a guest was up**, so it could never + settle an installation stopped at its deadline, which leaves its guest + running. The wipe now powers the guest off first, as a Redfish wipe does, + and still refuses if the guest keeps running. + +The shorter installation deadline is a flag of the acceptance binary's +coordinator, and only the deadline scenario sets it. The emulator lab's limits +are listed in the coverage inventory. + ## Implementation decisions Each decision lists the open point from the implementation brief it settles. @@ -938,7 +974,8 @@ a real API server: | CRD contract, roles, and that nothing ships the component or the test-only kinds | `TestCRDContract`, `TestRolesKeepOneWriterAndKeepStaffFromCustomerSecrets`, `TestComponentIsInert` | Increment A has no site, so "nothing was sent" means custody admitted nothing -and the fence did not rise. Increment D proves it with the lab BMC audit. +and the fence did not rise. Increment D's phases prove it end to end, with the +site journal and, in the Redfish run, the lab BMC audit. Both local end-to-end runs include the `custody-crd-rules` phase. It proves that a Milo project API refuses every write the CRD rules forbid, which @@ -975,7 +1012,14 @@ Increment C's tests run with `task test:envtest`, and the smoke runs with | Where the component ships | `TestComponentRoots` | | The standalone smoke: contention, install, a simulator restart and recovery, reinstall, release with a wipe, reuse, and the role checks that keep one writer per kind | `task standalone:test` | +Increment D's site tests run with `go test -race ./internal/site/...`: + +| Area | Tests | +| --- | --- | +| A worker stopped at its deadline closes its boot admission, in both workers | `TestAWorkerStoppedAtItsDeadlineClosesItsAdmission` | +| A local VM wipe powers off a running guest, and is not proven while it keeps running | `TestAWipePowersOffARunningDomain`, `TestAWipeWithADomainThatKeepsRunningIsNotProven` | + The multi-plane local VM and Redfish runs (`task multiplane:acceptance` and -`task multiplane:redfish-acceptance`) run the same workers. Their verification -is pending. The acceptance state of each #174 test is in the [coverage +`task multiplane:redfish-acceptance`) run the same workers and the failure +scenarios. The acceptance state of each #174 test is in the [coverage inventory](../../test/acceptance/coverage.md#device-custody-and-operations). diff --git a/docs/development/roadmap.md b/docs/development/roadmap.md index c4bfd7b6..4d0968be 100644 --- a/docs/development/roadmap.md +++ b/docs/development/roadmap.md @@ -50,9 +50,10 @@ per-allocation fencing with one custody record per Device, ahead of real hardware qualification. Increment A (the control-plane foundation), Increment B (site execution) and Increment C (the cutover) are implemented. C moves every mode onto custody and deletes the Secret-backed path. An allocation's private -facts live on its MachineAllocation. The standalone smoke verifies C. Verification -of the two multi-plane runs, local VM and Redfish, is pending. Increment D -(end-to-end failure scenarios) is proposed. +facts live on its MachineAllocation. The standalone smoke and both multi-plane +runs, local VM and Redfish, verify C. Increment D (end-to-end failure +scenarios) is implemented, and its verification in both multi-plane runs is +pending. Acceptance: the #174 acceptance tests pass, in envtest and in fresh local end-to-end runs, with "nothing sent" proven by the lab BMC audit. diff --git a/docs/operations/multiplane.md b/docs/operations/multiplane.md index 7bcdfe81..54826f1a 100644 --- a/docs/operations/multiplane.md +++ b/docs/operations/multiplane.md @@ -161,6 +161,7 @@ mode-0700 `/tmp/fleet-multiplane.*` state directory (override the parent with | `custody-crd-rules.json` | Each forbidden custody or operation write and whether the provider project API refused it, and that the CRDs were removed | | `kubernetes-execution.json` | kro version, image and RGD/instance state; Flux-owned site Deployments; retained volume identity; every worker Job's UID, conditions, Pods, exit codes and policies; per-operation RBAC | | `interrupt.json`, `lifecycle.json`, `delivery-faults.json`, `wrong-location.json` | Scenario-specific observations, no secrets | +| `import-inert.json`, `staff-access.json`, `contention.json`, `release-waits.json`, `deadline-hold.json`, `deadline-settled.json`, `rebuild.json` | The #174 failure scenarios ([coverage](../../test/acceptance/coverage.md#device-custody-and-operations)) | | `source-SHA256SUMS`, `binary-SHA256SUMS`, `image-id`, `sysctl.json`, `teardown.json` | Tested inputs and teardown record | Before reporting, the harness scans `evidence/` for every retained static token, @@ -219,9 +220,17 @@ The phases are then: another Device. It then removes the objects and the CRDs. Milo ignores admission policies stored in a project, so this proves the rules hold there. It sends nothing to any server. + `import-inert` then requires that importing the Devices admitted, + delivered and sent nothing: no operation, allocation, assignment, worker + Job or journal entry, and custody with no operation, result or hold. In + Redfish mode the BMC audit must hold no effect. `staff-access` requires + the staff identity to read custody and list recoveries, and to be + forbidden Secrets, every other operation, allocations and custody writes. + Staff hold no consumer-project or hub credential. 2. **Contention.** Two consumers request one provider capacity. Custody grants one allocation; `verify-contention` independently reads Bound for A and - Pending/InsufficientCapacity for B. + Pending/InsufficientCapacity for B, and requires custody to name the one + MachineAllocation, A's. 3. **Admission before effects.** The coordinator admits the `DeviceInstallation` and raises the Device's fence, then writes one immutable hub handoff carrying that exact assignment, before any effect. `await-delivery` requires the @@ -316,24 +325,46 @@ The phases are then: Each of the last two creates a kro Job that must fail once with exit 65 by `podFailurePolicy`. The site store must be unchanged, no status may appear, - consumer B must stay Bound, and kro must prune them once deleted. After B - installs and is released, `release-status-b` repeats the released checks for - B. -14. **Wrong location.** With capacity free, the consumer A customer recreates its + consumer B must stay Bound, and kro must prune them once deleted. In + Redfish mode the BMC audit must gain no effect. +14. **Deadline and Machine deletion.** `deadline-admit` stops the site's boot + server, with its Flux layer suspended, and restarts the coordinator with a + four-minute installation deadline for consumer B's installation only. The + installer boot is requested but never served. `machine-delete` has the + customer delete B's Machine mid-install. One release pass must leave + custody holding the Device for release with the installation still active + and no wipe. `deadline-hold` requires the installation to end + `OutcomeUnknown` with `DeadlineExceeded`, custody to hold it at its fence, + and its worker to have stopped. A staff `DeviceRecovery` naming the + held operation at the wrong fence must be refused, with custody, the site + store and, in Redfish mode, the BMC audit unchanged. Flux then restores the + boot server. The release's wipe must be admitted above the held fence + after the worker stopped, succeed, and clear the hold. `release-status-b` + requires the deleted Machine to be gone. +15. **Custody rebuild.** `rebuild` stops the site observer, so the cell cannot + report its fence, and deletes the free Device's custody as the provider + bootstrap admin. The coordinator must rebuild it `Unverified`, and a new + consumer A Machine must find no eligible capacity and record no + allocation. Once Flux restores the observer, custody must become + `Verified` with a fence above every fence the site stored. +16. **Wrong location.** With capacity free, the consumer A customer recreates its request with `locationRef: remote-elsewhere`. Allocation must fail with the location-not-served error. The custody records, the site store's state, and the Machine's finalizers and status must be unchanged. Free capacity rules out contention as the reason for denial. -15. **Closed boot and evidence.** Live HTTP probes from the runtime Pod to the +17. **Closed boot and evidence.** Live HTTP probes from the runtime Pod to the boot Service are denied after closure. Evidence requires all of: - - PXE mode, one install and two wipes, each `Succeeded` at its own fence, with - the fences strictly increasing; + - PXE mode, one install and two wipes, each `Succeeded` at its own fence, + and B's installation `OutcomeUnknown` at its deadline, with the fences + strictly increasing; - completed broker writes and a DHCP lease for the installer NIC; - network-only installer XML, and disk XML with no NIC or direct kernel; - closed boot admission, no remaining domain or disk; - - kro-created, `Complete` worker Jobs for exactly the one install and two - wipes, each with one successful Pod; + - kro-created, `Complete` worker Jobs for exactly these four operations, + each with one successful Pod; + - custody `Verified` with no holder at the rebuilt fence, and only the + refused recovery; - zero OOM kills. -16. **Final convergence and teardown.** `flux-final` requires all three +18. **Final convergence and teardown.** `flux-final` requires all three clusters at the last revision with nothing suspended, and repeats the single-writer ownership audit. After a pass, only exact-prefix resources are deleted, the inotify value is restored, and private credentials are removed. diff --git a/docs/operations/redfish-lab.md b/docs/operations/redfish-lab.md index 029fadc1..d154d5c0 100644 --- a/docs/operations/redfish-lab.md +++ b/docs/operations/redfish-lab.md @@ -351,23 +351,24 @@ fixture discovery for the lab Devices. Real BMC discovery is not part of this ru | Phase | What it proves | | --- | --- | | `redfish-baseline` | Both target disks exist and neither target was ever started; records target B's disk digest | -| `redfish-discovery-faults` | Uses the real emulator through `fleet-multiplane redfish-probe` and the production discovery code. Each enrolled System is discovered exactly. A wrong credential exits 10. Target A's Id with target B's UUID, or an unknown UUID, exits 12. An injected unadvertised `On` exits 11. The BMC audit shows only GETs in the window. | +| `redfish-discovery-faults` | Uses the real emulator through `fleet-multiplane redfish-probe` and the production discovery code. Each enrolled System is discovered exactly. A wrong credential exits 10. Target A's Id with target B's UUID, or an unknown UUID, exits 12. An injected unadvertised `On` exits 11. A TLS key other than the pin exits 13 and reaches no request. The BMC audit shows only GETs in the window. | | `redfish-bmc-interrupt` | As soon as the installer is running, the BMC Pod is force-deleted and replaced. The guest keeps running; the worker tolerates a bounded BMC outage. | | `interrupt-pod`, `interrupt-job` | As in libvirt mode, now on the Redfish worker, still inside the installer phase | | `redfish-arm-lost-response`, `redfish-lost-response` | Armed before dispatch: the second effective `On` for System-1 (the first install's disk boot) is answered only after 45 seconds. The worker times out and exits 75 (Unknown). Its replacement observes the running or completed target and the consumed override. Exactly one `On` per phase was sent: `powerOnRequests` is one installer and one disk request. | | `resume` | The recreated Job completes the exact operation with one succeeded Pod | -| `install-b` | After the wipe and reuse, consumer B installs on the same physical target under a higher fence with a new receipt | +| `deadline-admit`, `machine-delete`, `deadline-hold` | After the wipe and reuse, consumer B's installation runs under a four-minute deadline with the boot server stopped. Its `On` is sent and its installer is never served. The Machine is deleted mid-install, the installation ends `OutcomeUnknown` at its deadline, and a mismatched staff recovery is refused with no BMC effect. The release wipe powers the target off and settles the hold. | | `boot-denials` | Closed per-MAC scripts and capabilities of all four operations, target B's MAC and unknown identities are denied over the live boot Service | | `redfish-isolation` | Target B: unchanged disk digest, no QEMU start, no console line, no mutating Redfish request. Target A: disk hashes as all zeroes. No domain running. Exports the BMC audit. | The final `evidence` phase adds these independent checks in Redfish mode: - **Console.** Target A's console holds exactly one receipt line per boot, in - operation order: install, disk boot, wipe, install, disk boot, wipe. -- **QEMU.** libvirt's append-only log shows exactly six starts of target A, in - the boot order network, disk, network, network, disk, network (read from + operation order: install, disk boot, wipe, wipe. B's held installation + prints none. +- **QEMU.** libvirt's append-only log shows exactly five starts of target A, in + the boot order network, disk, network, network, network (read from `bootindex`), and none of target B. -- **BMC audit.** Exactly six effective `On` requests, all to System-1, of which +- **BMC audit.** Exactly five effective `On` requests, all to System-1, of which exactly one carried the lost-response fault. - **Kubernetes and admission.** Every worker Job selects the Redfish provider with no hypervisor mount or URI, and the admission probes denied each diff --git a/hack/multiplane/evidence.py b/hack/multiplane/evidence.py index bb8f0aae..2dd880c9 100755 --- a/hack/multiplane/evidence.py +++ b/hack/multiplane/evidence.py @@ -372,8 +372,10 @@ def network(block): mounts = [m.get('subPath', '') + ':' + m['mountPath'] for m in c.get('volumeMounts', [])] if env.get('FLEET_SITE_PROVIDER') != 'redfish' or 'FLEET_LIBVIRT_URI' in env or any('libvirt' in m or 'lab-disks' in m for m in mounts) or any('hostPath' in v for v in pod.get('volumes', [])): fail('a Redfish worker Job had a hypervisor path: ' + job['metadata']['name']) -# One kro-created worker Job per admitted operation, at that operation's fence. -if sorted((j['operationID'], j['fence']) for j in worker_jobs) != sorted((o['operation'], o['fence']) for o in ops) or any(j['createdBy'] != 'workers' for j in worker_jobs): +# One kro-created worker Job per admitted operation, at that operation's +# fence, including the installation held at its deadline. +held_job = (json.loads((s / 'deadline-install.json').read_text())['key'], json.loads((s / 'deadline-hold.json').read_text())['fence']) +if sorted((j['operationID'], j['fence']) for j in worker_jobs) != sorted([(o['operation'], o['fence']) for o in ops] + [held_job]) or any(j['createdBy'] != 'workers' for j in worker_jobs): fail('expected one kro-created worker Job per operation at its fence, got %s' % [(j['kind'], j['name'], j['fence'], j['createdBy']) for j in worker_jobs]) pvc = kget('-n', 'fleet-site', 'get', 'pvc', 'fleet-site-state') pv = kget('get', 'pv', pvc['spec']['volumeName']) diff --git a/test/acceptance/coverage.md b/test/acceptance/coverage.md index 7301d619..51131c8d 100644 --- a/test/acceptance/coverage.md +++ b/test/acceptance/coverage.md @@ -34,28 +34,33 @@ result reports every required phase `Passed`. These are the acceptance tests of [#174 at `d4d17f9`](https://github.com/datum-cloud/fleet/pull/174). Increment A covers them against a real API server, and Increment B covers the site side in unit tests. Increment C runs allocation, installation, release and -reuse end to end in the standalone smoke. The multi-plane local VM and Redfish -runs use the same code, and verification of both is pending. The remaining -end-to-end failure scenarios arrive in Increment D. See [device -custody](../../docs/development/device-custody.md#tests). +reuse end to end. Increment D adds the failure scenarios to both multi-plane +runs, the local VM and the Redfish lab, through real Milo project APIs, Karmada, +kro and the site. See [device custody](../../docs/development/device-custody.md#tests) +and the [multi-plane phases](../../docs/operations/multiplane.md#acceptance-phases). | #174 acceptance test | Executable evidence | Current state | | --- | --- | --- | -| Two allocators race for one server; one wins | `TestConcurrency`, `TestConcurrentAllocatorsOneWinner` | Envtest verified; the standalone smoke verifies two consumers contending for one server | +| Two allocators race for one server; one wins | `TestConcurrency`, `TestConcurrentAllocatorsOneWinner`; the `verify-contention` phase | Envtest verified for true concurrency. End to end, two consumers contend and custody names the one MachineAllocation | | An allocator retries after a lost response and claims no second server | `TestConcurrency`, `TestAnAllocationThatLostItsDeviceIsReplaced` | Envtest verified; the allocation is named from the Machine UID, so a retry finds the same one | -| A staff operation names a customer allocation and is refused | `TestAdmissionPreconditions`, with the test-only staff kind | Envtest verified; end to end deferred to power | -| A commissioning times out and a later one settles the hold | `TestLifecycle`, `TestRecovery`, with the test-only kind and `DeviceWipe` | Deferred: commissioning is out of scope; the mechanism is envtest verified | -| A staff operation targets an allocated, releasing or unsettleable held server and is refused, nothing sent | `TestAdmissionPreconditions`, `TestRecovery` | Envtest verified; end to end proposed | -| A worker passes its deadline; `OutcomeUnknown`; settling waits for the worker to stop | `TestLifecycle`, `TestRecovery` | Envtest verified with a fake site; end to end proposed | -| A delayed worker's step after a newer admission is refused by the journal | `TestTwoWorkersOnOneDevice`, `TestANewerFenceStopsTheOlderWorker`, `TestStoreRefusesOlderFencesAndSurvivesARestart` | Unit verified; the multi-plane `delivery-faults` phase replays an assignment below the stored fence, and its verification is pending | -| A TLS pin mismatch or an identity mismatch sends nothing | `TestPinMismatchSendsNothing`, `TestIdentityMismatchSendsNothing`, against TLS servers | Unit verified. The Redfish run's lab BMC serves TLS with a per-run key and workers reach it only through the pin, so a mismatch is not injected there; verification of the run is pending | -| Custody deleted and restored stays unallocatable until rebuilt with a higher fence | `TestRebuild` | Envtest verified with a fake site; end to end proposed | -| A Machine deleted during installation; release waits; a wipe settles the install hold | `TestLifecycle`, `TestRecovery` | Envtest verified; end to end proposed | -| No staff role can read a bootstrap payload | `TestRolesKeepOneWriterAndKeepStaffFromCustomerSecrets` | Role definitions verified; bootstrap stays refused | - -The emulator lab cannot cover BMC TLS key rotation, vendor Redfish behavior, -UEFI or real PXE firmware, real disks and wipe assurance, real power reset -evidence, clock skew between coordinator and site, more than one site serving -a Device, or a permanently lost site. The multi-plane Milo registers no creator -webhook, so the multi-plane runs do not prove it. None of these tests qualifies -hardware. +| A staff operation names a customer allocation and is refused | `TestAdmissionPreconditions`, with the test-only staff kind | Envtest verified; end to end deferred to power, the first staff kind with an effect | +| A commissioning times out and a later one settles the hold | `TestLifecycle`, `TestRecovery`, with the test-only kind and `DeviceWipe` | Deferred: commissioning is out of scope. The same hold and settle mechanism runs end to end for an installation and a wipe | +| A staff operation targets an allocated, releasing or unsettleable held server and is refused, nothing sent | `TestAdmissionPreconditions`, `TestRecovery`; the `deadline-hold` phase | Envtest verified. End to end, a `DeviceRecovery` naming the held installation at the wrong fence is refused on a releasing Device; custody, the site store and the BMC audit are unchanged | +| A worker passes its deadline; `OutcomeUnknown`; settling waits for the worker to stop | `TestLifecycle`, `TestRecovery`, `TestAWorkerStoppedAtItsDeadlineClosesItsAdmission`; the `deadline-hold` and `deadline-settled` phases | End to end in both runs: the installation ends `OutcomeUnknown` with `DeadlineExceeded`, and the settling wipe is admitted only after its worker stopped | +| A delayed worker's step after a newer admission is refused by the journal | `TestTwoWorkersOnOneDevice`, `TestANewerFenceStopsTheOlderWorker`, `TestStoreRefusesOlderFencesAndSurvivesARestart`; the `delivery-faults` phase | End to end: an assignment below the stored fence fails its Job before any effect, with the journal and the BMC audit unchanged | +| A TLS pin mismatch or an identity mismatch sends nothing | `TestPinMismatchSendsNothing`, `TestIdentityMismatchSendsNothing`; the `redfish-discovery-faults` phase | End to end in the Redfish run: a key other than the pin reaches no request, and a swapped or unknown identity sends only reads | +| Custody deleted and restored stays unallocatable until rebuilt with a higher fence | `TestRebuild`; the `rebuild` phase | End to end: rebuilt `Unverified` while the site cannot report, a new Machine finds no capacity, then `Verified` above the site's fence | +| A Machine deleted during installation; release waits; a wipe settles the install hold | `TestLifecycle`, `TestRecovery`; the `machine-delete`, `deadline-hold` and `deadline-settled` phases | End to end: release holds the Device with the installation active and no wipe, then the wipe settles the hold and the Machine is gone | +| No staff role can read a bootstrap payload | `TestRolesKeepOneWriterAndKeepStaffFromCustomerSecrets`; the `staff-access` phase | Role definitions verified. End to end, staff are forbidden Secrets and every write but recoveries. Bootstrap stays refused, so no payload exists to read | +| Importing a Device sends nothing and makes no capacity Available | `TestImportedDeviceGetsUnverifiedCustodyAndSendsNothing`; the `import-inert` phase | End to end: no operation, assignment, Job, journal entry or BMC effect. The capacity projector is not wired, so the run's fixture writes capacity status itself | + +The emulator lab cannot cover these: + +- BMC TLS key rotation, or one key per server: the lab serves both targets from one BMC with one key, so only target A is a Device; +- vendor Redfish behavior, UEFI or real PXE firmware; +- real disks, wipe assurance or power reset evidence; +- clock skew between the coordinator and a site; +- more than one site serving a Device, or a site lost for good; +- true parallel races between processes, which envtest covers. + +The multi-plane Milo registers no creator webhook, so the multi-plane runs do not prove it. None of these tests qualifies hardware. From 424350af14c591426bf4a0a22e65027a5b38fcb7 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 25 Nov 2026 07:36:09 -0600 Subject: [PATCH 05/16] test(multiplane): Stop the boot server once the deadline worker exists kro creates a worker Job only while the boot server is ready, so stopping it before admission left the deadline installation with no worker at all. The scenario now stops it as soon as kro created the Job, before the firmware can fetch the installer. Co-Authored-By: Claude Opus 5.5 --- hack/multiplane/scenarios.py | 14 +++++++++++--- hack/multiplane/steps.sh | 10 ++++++---- 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/hack/multiplane/scenarios.py b/hack/multiplane/scenarios.py index 21495569..b655323a 100644 --- a/hack/multiplane/scenarios.py +++ b/hack/multiplane/scenarios.py @@ -179,13 +179,21 @@ def newest_install(s): return ops[-1] if ops else None -def wait_installer(s, step): - """Wait until the newest installation journaled its installer step.""" +def wait_job(s): + """Record the newest installation and wait for kro to create its worker + Job.""" name = newest_install(s)['metadata']['name'] # The site keys the operation by kind, name and the fence it was admitted # at; a same-name installation created later is admitted at another. key = wait_for(lambda: admitted_key(provider(s, 'get', 'deviceinstallation', name)), 300, 'the second installation to be admitted', interval=1) (s / 'deadline-install.json').write_text(json.dumps({'name': name, 'key': key}) + '\n') + handoff = wait_for(lambda: handoff_for(s, key), 300, 'the second installation to be delivered', interval=1) + wait_for(lambda: kubectl(s, 'cell-admin.yaml', '-n', SITE, 'get', 'job', 'w-' + handoff, check=False).returncode == 0, 300, 'its worker Job', interval=0.5) + + +def wait_installer(s, step): + """Wait until the deadline installation journaled its installer step.""" + _, key = deadline_op(s) def journaled(): for o in harness.journal(s) or []: @@ -329,4 +337,4 @@ def rebuild_verified(s): {'import-inert': import_inert, 'staff-access': staff_access, 'contention': contention, 'release-waits': release_waits, 'deadline-hold': deadline_hold, 'deadline-settled': deadline_settled, 'rebuild-before': rebuild_before, 'rebuild-unverified': rebuild_unverified, 'rebuild-verified': rebuild_verified, - 'wait-installer': lambda s: wait_installer(s, sys.argv[3])}[command](state) + 'wait-job': wait_job, 'wait-installer': lambda s: wait_installer(s, sys.argv[3])}[command](state) diff --git a/hack/multiplane/steps.sh b/hack/multiplane/steps.sh index 4c118e00..dce01074 100755 --- a/hack/multiplane/steps.sh +++ b/hack/multiplane/steps.sh @@ -90,13 +90,15 @@ case "$step" in scenario staff-access "$state" ;; deadline-admit) - # Consumer B's installation is admitted under a four-minute deadline while - # the site's boot server is stopped, so its installer never boots. Only - # this admission uses the short deadline. - site_stop fleet-site-boot + # Consumer B's installation is admitted under a four-minute deadline. Only + # this admission uses the short deadline. kro creates a worker Job only + # while the boot server is ready, so the boot server is stopped as soon as + # the Job exists, before the firmware can fetch the installer. bash hack/multiplane/coordinator.sh restart "$state" --installation-deadline=4m >/dev/null "$host" admit-install-b --config "$state/acceptance.json" >/dev/null bash hack/multiplane/coordinator.sh restart "$state" >/dev/null + scenario wait-job "$state" + site_stop fleet-site-boot scenario wait-installer "$state" "$installer_step" printf 'deadline-admit: the second installation was admitted under a four-minute deadline and journaled its installer boot with the boot server stopped\n' ;; From b5bc039c3df59a1f2e597ec260cc1a58bddafbc8 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 25 Nov 2026 07:45:12 -0600 Subject: [PATCH 06/16] test(multiplane): Withhold the deadline installer with a lab boot hook Stopping the boot server once the worker Job existed raced the firmware's installer fetch, so the deadline evidence could flake. The acceptance binary's boot service now has a lab-only hook: while its arm file exists it denies every boot and stays Ready, so kro still creates the worker and the installer never runs. Only the local multi-plane site source sets the hook's variable, and a test fails if any other configuration sets it, a production root references that source, or another package names it. The boot servers' listeners move into the acceptance binary with the hook. Co-Authored-By: Claude Opus 5.5 --- cmd/fleet-multiplane/main.go | 4 +- cmd/fleet-multiplane/site.go | 5 +- cmd/fleet-multiplane/withhold.go | 61 ++++++++++++ cmd/fleet-multiplane/withhold_test.go | 138 ++++++++++++++++++++++++++ config/site/services/services.yaml | 4 + docs/development/device-custody.md | 9 +- docs/operations/multiplane.md | 11 +- docs/operations/redfish-lab.md | 2 +- hack/multiplane/evidence.py | 2 +- hack/multiplane/scenarios.py | 15 +-- hack/multiplane/steps.sh | 18 ++-- internal/site/redfishwork/boot.go | 7 -- internal/site/vmwork/boot.go | 7 -- 13 files changed, 237 insertions(+), 46 deletions(-) create mode 100644 cmd/fleet-multiplane/withhold.go create mode 100644 cmd/fleet-multiplane/withhold_test.go diff --git a/cmd/fleet-multiplane/main.go b/cmd/fleet-multiplane/main.go index f6ff60ec..0a78d69d 100644 --- a/cmd/fleet-multiplane/main.go +++ b/cmd/fleet-multiplane/main.go @@ -32,7 +32,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-denials|dhcp-feed|redfish-probe| [flags]") + return fmt.Errorf("usage: fleet-multiplane coordinator|site-worker|site-observer|image|boot-service|boot-withhold|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") @@ -78,6 +78,8 @@ func run() error { return nil case "boot-service", "boot-denials", "dhcp-feed": return boot(os.Args[1], *origin, *extraMAC, *syncToken) + case "boot-withhold": + return armWithhold(fs.Arg(0)) case "site-worker", "site-observer": default: return fmt.Errorf("unknown command") diff --git a/cmd/fleet-multiplane/site.go b/cmd/fleet-multiplane/site.go index 459f59c8..da1c7490 100644 --- a/cmd/fleet-multiplane/site.go +++ b/cmd/fleet-multiplane/site.go @@ -245,7 +245,7 @@ func boot(command, origin, extraMAC, syncToken string) error { } return server.ServeDHCP(strings.TrimSpace(string(token))) } - return server.Serve(vmwork.DefaultBootWindow * 2) + return serveBoot(server.Handler(), vmwork.DefaultBootWindow*2) } if command == "dhcp-feed" { return errors.New("the DHCP reservation feed serves only a Redfish site") @@ -254,5 +254,6 @@ func boot(command, origin, extraMAC, syncToken string) error { if err != nil { return err } - return vm.ServeBoot(store) + // Emulated firmware takes minutes to fetch the installer. + return serveBoot(vm.BootHandler(store), vmwork.DefaultBootWindow) } diff --git a/cmd/fleet-multiplane/withhold.go b/cmd/fleet-multiplane/withhold.go new file mode 100644 index 00000000..8b062c39 --- /dev/null +++ b/cmd/fleet-multiplane/withhold.go @@ -0,0 +1,61 @@ +package main + +import ( + "errors" + "net/http" + "os" + "time" +) + +// labWithholdEnv names the lab-only fault hook's arm file. Only the local +// multi-plane site's Flux source (config/site) sets it, on the boot service; +// no production root may reference that source. The hook lives in this +// acceptance binary, so no production binary contains it. +const labWithholdEnv = "FLEET_LAB_BOOT_WITHHOLD" + +// withhold denies every boot request while the arm file exists, so an +// admitted installation's firmware never receives its installer and the +// worker waits for a receipt until its deadline. The listener stays up, so +// the boot service stays Ready and kro still creates workers. It records no +// delivery evidence for a withheld request. Without the variable it returns +// the handler unchanged. +func withhold(next http.Handler) http.Handler { + path := os.Getenv(labWithholdEnv) + if path == "" { + return next + } + return http.HandlerFunc(func(w http.ResponseWriter, request *http.Request) { + if _, err := os.Stat(path); err == nil { + w.Header().Set("Cache-Control", "no-store") + http.Error(w, "boot denied", http.StatusForbidden) + return + } + next.ServeHTTP(w, request) + }) +} + +// armWithhold creates or removes the arm file. It runs in the boot +// service's container, through the cell API. +func armWithhold(action string) error { + path := os.Getenv(labWithholdEnv) + if path == "" { + return errors.New("the lab boot withhold hook is not configured") + } + switch action { + case "arm": + return os.WriteFile(path, nil, 0o600) + case "clear": + if err := os.Remove(path); err != nil && !os.IsNotExist(err) { + return err + } + return nil + } + return errors.New("boot-withhold takes arm or clear") +} + +// serveBoot listens on :8080 with the same bounds as the site's boot +// servers. The write bound covers emulated firmware fetching the initrd. +func serveBoot(handler http.Handler, window time.Duration) error { + server := &http.Server{Addr: ":8080", Handler: withhold(handler), ReadHeaderTimeout: 5 * time.Second, WriteTimeout: window, IdleTimeout: 5 * time.Second} + return server.ListenAndServe() +} diff --git a/cmd/fleet-multiplane/withhold_test.go b/cmd/fleet-multiplane/withhold_test.go new file mode 100644 index 00000000..fae82a49 --- /dev/null +++ b/cmd/fleet-multiplane/withhold_test.go @@ -0,0 +1,138 @@ +package main + +import ( + "io/fs" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" +) + +func served(t *testing.T, handler http.Handler, path string) int { + t.Helper() + recorder := httptest.NewRecorder() + handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, path, nil)) + return recorder.Code +} + +var ok = http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) }) + +func TestWithholdIsOffWithoutTheLabVariable(t *testing.T) { + t.Setenv(labWithholdEnv, "") + if err := armWithhold("arm"); err == nil { + t.Fatal("the hook armed without its lab variable") + } + if code := served(t, withhold(ok), "/pxe/52-54-00-77-01-0a/boot.ipxe"); code != http.StatusOK { + t.Fatalf("an unconfigured hook changed the response: %d", code) + } +} + +func TestAnArmedWithholdDeniesEveryBootRequest(t *testing.T) { + path := filepath.Join(t.TempDir(), "withhold") + t.Setenv(labWithholdEnv, path) + handler := withhold(ok) + paths := []string{"/pxe/boot.ipxe", "/pxe/52-54-00-77-01-0a/boot.ipxe", "/0123456789abcdef/token/kernel", "/0123456789abcdef/token/installer.gz"} + for _, p := range paths { + if code := served(t, handler, p); code != http.StatusOK { + t.Fatalf("an unarmed hook denied %s: %d", p, code) + } + } + if err := armWithhold("arm"); err != nil { + t.Fatal(err) + } + for _, p := range paths { + if code := served(t, handler, p); code != http.StatusForbidden { + t.Fatalf("an armed hook served %s: %d", p, code) + } + } + if err := armWithhold("clear"); err != nil { + t.Fatal(err) + } + if err := armWithhold("clear"); err != nil { + t.Fatalf("clearing a cleared hook: %v", err) + } + if code := served(t, handler, paths[1]); code != http.StatusOK { + t.Fatalf("a cleared hook still denies: %d", code) + } +} + +// TestOnlyTheLabSiteSourceSetsTheWithholdHook keeps the hook out of +// production: only the boot service of the local multi-plane site's Flux +// source sets the variable, no production root references that source, and +// no other package names the variable. +func TestOnlyTheLabSiteSourceSetsTheWithholdHook(t *testing.T) { + root := filepath.Join("..", "..") + var setters []string + err := filepath.WalkDir(filepath.Join(root, "config"), func(path string, entry fs.DirEntry, err error) error { + if err != nil || entry.IsDir() { + return err + } + data, err := os.ReadFile(path) + if err != nil { + return err + } + rel, _ := filepath.Rel(root, path) + text := string(data) + if strings.Contains(text, labWithholdEnv) { + setters = append(setters, rel) + } + lab := strings.HasPrefix(rel, filepath.Join("config", "site")+string(filepath.Separator)) || strings.HasPrefix(rel, filepath.Join("config", "multiplane")+string(filepath.Separator)) + if !lab && filepath.Base(path) == "kustomization.yaml" { + for _, line := range strings.Split(text, "\n") { + entry := strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(line), "- ")) + if strings.HasPrefix(entry, "#") { + continue + } + if strings.Contains(entry, "/site") && !strings.Contains(entry, "/site-") || strings.Contains(entry, "multiplane") { + t.Errorf("%s references the lab site source: %s", rel, entry) + } + } + } + return nil + }) + if err != nil { + t.Fatal(err) + } + want := filepath.Join("config", "site", "services", "services.yaml") + if len(setters) != 1 || setters[0] != want { + t.Fatalf("the hook is set in %v, want only %s", setters, want) + } + services, err := os.ReadFile(filepath.Join(root, want)) + if err != nil { + t.Fatal(err) + } + boot := strings.Index(string(services), "kind: Deployment\nmetadata:\n name: fleet-site-boot\n") + next := strings.Index(string(services)[boot+1:], "\n---") + if boot < 0 || next < 0 || !strings.Contains(string(services)[boot:boot+1+next], labWithholdEnv) { + t.Fatal("the hook is set outside the boot service's Deployment") + } + for _, dir := range []string{"internal", "cmd"} { + err := filepath.WalkDir(filepath.Join(root, dir), func(path string, entry fs.DirEntry, err error) error { + if err != nil || entry.IsDir() || filepath.Dir(path) == "." { + return err + } + if abs, _ := filepath.Abs(filepath.Dir(path)); abs == mustAbs(t, ".") { + return nil + } + data, err := os.ReadFile(path) + if err == nil && strings.Contains(string(data), labWithholdEnv) { + t.Errorf("%s names the lab hook", path) + } + return err + }) + if err != nil { + t.Fatal(err) + } + } +} + +func mustAbs(t *testing.T, path string) string { + t.Helper() + abs, err := filepath.Abs(path) + if err != nil { + t.Fatal(err) + } + return abs +} diff --git a/config/site/services/services.yaml b/config/site/services/services.yaml index d1290c1a..e5cbac24 100644 --- a/config/site/services/services.yaml +++ b/config/site/services/services.yaml @@ -103,6 +103,10 @@ spec: - {name: FLEET_LOCAL_VM_ACCEL, value: tcg} - {name: FLEET_BOOT_ORIGIN, value: "http://${FLEET_BOOT_SERVICE_IP}:8080"} - {name: FLEET_BOOT_EVIDENCE, value: /var/lib/fleet-boot} + # Lab-only fault hook: while this file exists the boot service + # withholds every boot, and stays Ready. The deadline scenario + # arms it with `fleet-multiplane boot-withhold`. + - {name: FLEET_LAB_BOOT_WITHHOLD, value: /var/lib/fleet-boot/lab-withhold} ports: - {name: http, containerPort: 8080} readinessProbe: diff --git a/docs/development/device-custody.md b/docs/development/device-custody.md index a74fe343..bec7d814 100644 --- a/docs/development/device-custody.md +++ b/docs/development/device-custody.md @@ -394,7 +394,7 @@ phases](../operations/multiplane.md#acceptance-phases) describe each one. | Importing sends nothing | Checked before any allocation: no operation, assignment, worker Job, journal entry or BMC effect | | Staff access | A staff token in the provider project reads custody and creates recoveries, and is forbidden everything else | | Contention | Custody names the one MachineAllocation, the winner's | -| Deadline | The coordinator restarts with a four-minute installation deadline for one admission, and the boot server is stopped, so the installer is never served | +| Deadline | The coordinator restarts with a four-minute installation deadline for one admission, and a lab-only boot hook withholds every boot while it is armed, so the installer is never served | | Machine deleted mid-install | The customer deletes the Machine; release holds the Device and waits for the installation | | Recovery for the wrong hold | Staff name the held installation at the wrong fence; admission refuses it with nothing delivered or sent | | A wipe settles the hold | The release wipe is admitted above the held fence after the worker stopped | @@ -414,7 +414,12 @@ The scenarios found two site gaps, both fixed: and still refuses if the guest keeps running. The shorter installation deadline is a flag of the acceptance binary's -coordinator, and only the deadline scenario sets it. The emulator lab's limits +coordinator, and only the deadline scenario sets it. The boot hook lives in +the acceptance binary's boot service, and only the local multi-plane site's +Flux source configures it, which no production root may reference. +`TestOnlyTheLabSiteSourceSetsTheWithholdHook` fails if any other +configuration sets it, any production root references that source, or any +other package names it. The emulator lab's limits are listed in the coverage inventory. ## Implementation decisions diff --git a/docs/operations/multiplane.md b/docs/operations/multiplane.md index 54826f1a..02dfb1e2 100644 --- a/docs/operations/multiplane.md +++ b/docs/operations/multiplane.md @@ -327,9 +327,10 @@ The phases are then: `podFailurePolicy`. The site store must be unchanged, no status may appear, consumer B must stay Bound, and kro must prune them once deleted. In Redfish mode the BMC audit must gain no effect. -14. **Deadline and Machine deletion.** `deadline-admit` stops the site's boot - server, with its Flux layer suspended, and restarts the coordinator with a - four-minute installation deadline for consumer B's installation only. The +14. **Deadline and Machine deletion.** `deadline-admit` arms a lab-only hook + in the boot service, which then withholds every boot while staying Ready, + and restarts the coordinator with a four-minute installation deadline for + consumer B's installation only. kro still creates the worker, and the installer boot is requested but never served. `machine-delete` has the customer delete B's Machine mid-install. One release pass must leave custody holding the Device for release with the installation still active @@ -337,8 +338,8 @@ The phases are then: `OutcomeUnknown` with `DeadlineExceeded`, custody to hold it at its fence, and its worker to have stopped. A staff `DeviceRecovery` naming the held operation at the wrong fence must be refused, with custody, the site - store and, in Redfish mode, the BMC audit unchanged. Flux then restores the - boot server. The release's wipe must be admitted above the held fence + store and, in Redfish mode, the BMC audit unchanged. The hook is then + cleared. The release's wipe must be admitted above the held fence after the worker stopped, succeed, and clear the hold. `release-status-b` requires the deleted Machine to be gone. 15. **Custody rebuild.** `rebuild` stops the site observer, so the cell cannot diff --git a/docs/operations/redfish-lab.md b/docs/operations/redfish-lab.md index d154d5c0..853c54f6 100644 --- a/docs/operations/redfish-lab.md +++ b/docs/operations/redfish-lab.md @@ -356,7 +356,7 @@ fixture discovery for the lab Devices. Real BMC discovery is not part of this ru | `interrupt-pod`, `interrupt-job` | As in libvirt mode, now on the Redfish worker, still inside the installer phase | | `redfish-arm-lost-response`, `redfish-lost-response` | Armed before dispatch: the second effective `On` for System-1 (the first install's disk boot) is answered only after 45 seconds. The worker times out and exits 75 (Unknown). Its replacement observes the running or completed target and the consumed override. Exactly one `On` per phase was sent: `powerOnRequests` is one installer and one disk request. | | `resume` | The recreated Job completes the exact operation with one succeeded Pod | -| `deadline-admit`, `machine-delete`, `deadline-hold` | After the wipe and reuse, consumer B's installation runs under a four-minute deadline with the boot server stopped. Its `On` is sent and its installer is never served. The Machine is deleted mid-install, the installation ends `OutcomeUnknown` at its deadline, and a mismatched staff recovery is refused with no BMC effect. The release wipe powers the target off and settles the hold. | +| `deadline-admit`, `machine-delete`, `deadline-hold` | After the wipe and reuse, consumer B's installation runs under a four-minute deadline with the lab boot hook armed. Its `On` is sent and its installer is never served. The Machine is deleted mid-install, the installation ends `OutcomeUnknown` at its deadline, and a mismatched staff recovery is refused with no BMC effect. The release wipe powers the target off and settles the hold. | | `boot-denials` | Closed per-MAC scripts and capabilities of all four operations, target B's MAC and unknown identities are denied over the live boot Service | | `redfish-isolation` | Target B: unchanged disk digest, no QEMU start, no console line, no mutating Redfish request. Target A: disk hashes as all zeroes. No domain running. Exports the BMC audit. | diff --git a/hack/multiplane/evidence.py b/hack/multiplane/evidence.py index 2dd880c9..f7eba469 100755 --- a/hack/multiplane/evidence.py +++ b/hack/multiplane/evidence.py @@ -299,7 +299,7 @@ def network(block): starts = {'targetA': order, 'targetB': (raw / 'libvirt-qemu' / 'fleet-lab-target-b.log').read_text(errors='replace').count(': starting up ') if (raw / 'libvirt-qemu' / 'fleet-lab-target-b.log').exists() else 0} # A install (network, disk), A wipe, B's held install (its network boot - # found no boot server), B wipe. + # was withheld by the lab boot hook), B wipe. if order != ['network', 'disk', 'network', 'network', 'network'] or starts['targetB']: fail('expected target A boots network, disk, network, network, network and no target B start; got %s' % starts) audit = [json.loads(l) for l in (ev / 'redfish-audit.jsonl').read_text().splitlines()] diff --git a/hack/multiplane/scenarios.py b/hack/multiplane/scenarios.py index b655323a..e0d5d37e 100644 --- a/hack/multiplane/scenarios.py +++ b/hack/multiplane/scenarios.py @@ -179,21 +179,14 @@ def newest_install(s): return ops[-1] if ops else None -def wait_job(s): - """Record the newest installation and wait for kro to create its worker - Job.""" +def wait_installer(s, step): + """Record the newest installation and wait until it journaled its + installer step.""" name = newest_install(s)['metadata']['name'] # The site keys the operation by kind, name and the fence it was admitted # at; a same-name installation created later is admitted at another. key = wait_for(lambda: admitted_key(provider(s, 'get', 'deviceinstallation', name)), 300, 'the second installation to be admitted', interval=1) (s / 'deadline-install.json').write_text(json.dumps({'name': name, 'key': key}) + '\n') - handoff = wait_for(lambda: handoff_for(s, key), 300, 'the second installation to be delivered', interval=1) - wait_for(lambda: kubectl(s, 'cell-admin.yaml', '-n', SITE, 'get', 'job', 'w-' + handoff, check=False).returncode == 0, 300, 'its worker Job', interval=0.5) - - -def wait_installer(s, step): - """Wait until the deadline installation journaled its installer step.""" - _, key = deadline_op(s) def journaled(): for o in harness.journal(s) or []: @@ -337,4 +330,4 @@ def rebuild_verified(s): {'import-inert': import_inert, 'staff-access': staff_access, 'contention': contention, 'release-waits': release_waits, 'deadline-hold': deadline_hold, 'deadline-settled': deadline_settled, 'rebuild-before': rebuild_before, 'rebuild-unverified': rebuild_unverified, 'rebuild-verified': rebuild_verified, - 'wait-job': wait_job, 'wait-installer': lambda s: wait_installer(s, sys.argv[3])}[command](state) + 'wait-installer': lambda s: wait_installer(s, sys.argv[3])}[command](state) diff --git a/hack/multiplane/steps.sh b/hack/multiplane/steps.sh index dce01074..2d02a88f 100755 --- a/hack/multiplane/steps.sh +++ b/hack/multiplane/steps.sh @@ -90,17 +90,17 @@ case "$step" in scenario staff-access "$state" ;; deadline-admit) - # Consumer B's installation is admitted under a four-minute deadline. Only - # this admission uses the short deadline. kro creates a worker Job only - # while the boot server is ready, so the boot server is stopped as soon as - # the Job exists, before the firmware can fetch the installer. + # Consumer B's installation is admitted under a four-minute deadline with + # the lab boot hook armed: the boot service stays Ready, so kro creates + # the worker, and withholds every boot, so the installer never runs and + # the worker waits for its receipt until the deadline. Only this admission + # uses the short deadline. + site exec deploy/fleet-site-boot -c boot -- fleet-multiplane boot-withhold arm bash hack/multiplane/coordinator.sh restart "$state" --installation-deadline=4m >/dev/null "$host" admit-install-b --config "$state/acceptance.json" >/dev/null bash hack/multiplane/coordinator.sh restart "$state" >/dev/null - scenario wait-job "$state" - site_stop fleet-site-boot scenario wait-installer "$state" "$installer_step" - printf 'deadline-admit: the second installation was admitted under a four-minute deadline and journaled its installer boot with the boot server stopped\n' + printf 'deadline-admit: the second installation was admitted under a four-minute deadline and journaled its installer boot with the lab boot hook withholding it\n' ;; machine-delete) # The customer deletes Machine B mid-install. One release pass begins the @@ -118,8 +118,8 @@ case "$step" in "$host" recovery-mismatch --config "$state/acceptance.json" [[ $before == "$(journal_digest)" ]] || { echo 'site store changed for a refused recovery' >&2; exit 1; } audit_unchanged - # Flux restores the boot server before the release's wipe. - site_restore fleet-site-boot + # The release's wipe boots normally. + site exec deploy/fleet-site-boot -c boot -- fleet-multiplane boot-withhold clear ;; deadline-settled) scenario deadline-settled "$state" diff --git a/internal/site/redfishwork/boot.go b/internal/site/redfishwork/boot.go index 06af2582..e1ed146c 100644 --- a/internal/site/redfishwork/boot.go +++ b/internal/site/redfishwork/boot.go @@ -194,13 +194,6 @@ func appendEvidence(dir, name, line string) error { return parent.Sync() } -// Serve listens on :8080. The write bound covers emulated firmware fetching -// the initrd through the site's NAT path. -func (b BootServer) Serve(window time.Duration) error { - server := &http.Server{Addr: ":8080", Handler: b.Handler(), ReadHeaderTimeout: 5 * time.Second, WriteTimeout: window, IdleTimeout: 5 * time.Second} - return server.ListenAndServe() -} - // CheckClosedBoot probes a live boot server after every admission closed: // each admission's per-MAC script and capability URLs, other enrolled MACs, // an unsupported and an unguarded artifact, and an unknown identity must diff --git a/internal/site/vmwork/boot.go b/internal/site/vmwork/boot.go index 7fa178f1..824d41e4 100644 --- a/internal/site/vmwork/boot.go +++ b/internal/site/vmwork/boot.go @@ -209,13 +209,6 @@ func appendEvidence(dir, line string) error { return syncDir(dir) } -// ServeBoot serves the boot handler. The write bound matches the boot -// window: emulated firmware takes minutes to fetch the installer. -func (c Config) ServeBoot(store *site.Store) error { - server := &http.Server{Addr: ":8080", Handler: c.BootHandler(store), ReadHeaderTimeout: 5 * time.Second, WriteTimeout: c.window(), IdleTimeout: 5 * time.Second} - return server.ListenAndServe() -} - // CheckClosedBoot probes a live boot server with every installation's // closed admission, and with unknown names, and requires each to be denied. // It prints no capability URL. From dc86a341c74a47a3d9c3636fa025515fefb38d0d Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 25 Nov 2026 08:21:33 -0600 Subject: [PATCH 07/16] test(multiplane): Reach the hold check with the mismatched recovery Staff recoveries take generated names, so the fixed name made admission refuse the recovery for its name before it compared the hold. The phase now creates it with a generated name, finds it again by label, and requires the HoldMismatch refusal. Co-Authored-By: Claude Opus 5.5 --- docs/operations/multiplane.md | 2 +- hack/multiplane/evidence.py | 4 ++-- internal/multiplane/scenarios.go | 29 ++++++++++++++++++++--------- test/acceptance/coverage.md | 2 +- 4 files changed, 24 insertions(+), 13 deletions(-) diff --git a/docs/operations/multiplane.md b/docs/operations/multiplane.md index 02dfb1e2..017fdf46 100644 --- a/docs/operations/multiplane.md +++ b/docs/operations/multiplane.md @@ -337,7 +337,7 @@ The phases are then: and no wipe. `deadline-hold` requires the installation to end `OutcomeUnknown` with `DeadlineExceeded`, custody to hold it at its fence, and its worker to have stopped. A staff `DeviceRecovery` naming the - held operation at the wrong fence must be refused, with custody, the site + held operation at the wrong fence must be refused for `HoldMismatch`, with custody, the site store and, in Redfish mode, the BMC audit unchanged. The hook is then cleared. The release's wipe must be admitted above the held fence after the worker stopped, succeed, and clear the hold. `release-status-b` diff --git a/hack/multiplane/evidence.py b/hack/multiplane/evidence.py index f7eba469..a7187f20 100755 --- a/hack/multiplane/evidence.py +++ b/hack/multiplane/evidence.py @@ -167,8 +167,8 @@ def custody_evidence(store, ops, provider, a, b): if spec.get('fence') != rebuilt['verifiedFence'] or spec['fence'] <= ops[-1]['fence'] or store.get('fence') != ops[-1]['fence'] or store.get('stopped') != ops[-1]['fence']: fail('custody fence %s, site fence %s/%s and the last operation fence %s do not follow the rebuild' % (spec.get('fence'), store.get('fence'), store.get('stopped'), ops[-1]['fence'])) recoveries = [i for i in provider.values() if i['kind'] == 'DeviceRecovery'] - if len(recoveries) != 1 or recoveries[0].get('status', {}).get('phase') != 'Failed' or recoveries[0]['status'].get('fence'): - fail('expected only the refused mismatched recovery, never admitted') + if len(recoveries) != 1 or recoveries[0].get('status', {}).get('phase') != 'Failed' or recoveries[0]['status'].get('reason') != 'HoldMismatch' or recoveries[0]['status'].get('fence'): + fail('expected only the mismatched recovery, refused for HoldMismatch and never admitted') record = {'observedAt': datetime.datetime.now(datetime.timezone.utc).isoformat(), 'device': harness.DEVICE, 'custody': {'state': spec['state'], 'holder': spec['holder'], 'fence': spec['fence'], 'activeOperation': None, 'recoveryHold': None, 'rejectedResults': spec.get('rejectedResults')}, diff --git a/internal/multiplane/scenarios.go b/internal/multiplane/scenarios.go index bfdfec90..590a9595 100644 --- a/internal/multiplane/scenarios.go +++ b/internal/multiplane/scenarios.go @@ -6,7 +6,6 @@ import ( "fmt" "path/filepath" - apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/controller-runtime/pkg/client" @@ -14,6 +13,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/custody" ) // The failure scenarios of #174's acceptance tests. Each phase checks one @@ -23,9 +23,10 @@ import ( // ErrAdmittedUnknown once custody admitted it. func (r *Runner) AdmitInstallSecond(ctx context.Context) error { return r.admitIndex(ctx, 1) } -// recoveryMismatchName names the staff recovery the mismatch phase creates, -// so a retried phase finds the same one. -const recoveryMismatchName = "synthetic-recovery-mismatch" +// recoveryMismatchLabel marks the staff recovery the mismatch phase +// creates, so a retried phase finds the same one. Recoveries take generated +// names; admission refuses any other. +const recoveryMismatchLabel = "fleet.datumapis.com/acceptance-scenario" // RecoveryMismatch creates, as staff, a DeviceRecovery that names the held // operation at the wrong fence. Admission refuses it before anything is @@ -47,14 +48,20 @@ func (r *Runner) RecoveryMismatch(ctx context.Context) error { if err := r.Provider.API.Get(ctx, client.ObjectKey{Namespace: DeviceNamespace, Name: Device}, device); err != nil { return err } - recovery := &ops.DeviceRecovery{} - if err := staff.Get(ctx, client.ObjectKey{Namespace: DeviceNamespace, Name: recoveryMismatchName}, recovery); apierrors.IsNotFound(err) { + var existing ops.DeviceRecoveryList + if err := staff.List(ctx, &existing, client.InNamespace(DeviceNamespace), client.MatchingLabels{recoveryMismatchLabel: "recovery-mismatch"}); err != nil { + return err + } + var recovery *ops.DeviceRecovery + switch len(existing.Items) { + case 0: creator, err := identity(ctx, filepath.Join(r.Config.State, "provider", "staff-project.json")) if err != nil { return err } recovery = &ops.DeviceRecovery{ - ObjectMeta: metav1.ObjectMeta{Name: recoveryMismatchName, Namespace: DeviceNamespace, Labels: map[string]string{ops.LabelDeviceUID: string(device.UID)}}, + ObjectMeta: metav1.ObjectMeta{GenerateName: Device + "-recovery-", Namespace: DeviceNamespace, Labels: map[string]string{ + recoveryMismatchLabel: "recovery-mismatch", ops.LabelDeviceUID: string(device.UID)}}, Spec: ops.DeviceRecoverySpec{ OperationEnvelope: ops.OperationEnvelope{Creator: creator, DeviceRef: ops.DeviceReference{Name: device.Name}, Authority: ops.Authority{ServiceRequest: &ops.ServiceRequest{Reason: "synthetic acceptance: a recovery for another hold"}}}, @@ -66,11 +73,15 @@ func (r *Runner) RecoveryMismatch(ctx context.Context) error { if err := staff.Create(ctx, recovery); err != nil { return err } - } else if err != nil { - return err + case 1: + recovery = &existing.Items[0] + default: + return fmt.Errorf("%w: more than one mismatched recovery", errTerminal) } switch phase := recovery.Status.Phase; { + case phase == ops.PhaseFailed && recovery.Status.Reason == custody.ReasonHoldMismatch: case phase == ops.PhaseFailed: + return fmt.Errorf("%w: the mismatched recovery was refused for %s, not the hold", errTerminal, recovery.Status.Reason) case phase.Ended(): return fmt.Errorf("%w: the mismatched recovery ended %s: %s", errTerminal, phase, recovery.Status.Reason) default: diff --git a/test/acceptance/coverage.md b/test/acceptance/coverage.md index 51131c8d..f5933a6c 100644 --- a/test/acceptance/coverage.md +++ b/test/acceptance/coverage.md @@ -45,7 +45,7 @@ and the [multi-plane phases](../../docs/operations/multiplane.md#acceptance-phas | An allocator retries after a lost response and claims no second server | `TestConcurrency`, `TestAnAllocationThatLostItsDeviceIsReplaced` | Envtest verified; the allocation is named from the Machine UID, so a retry finds the same one | | A staff operation names a customer allocation and is refused | `TestAdmissionPreconditions`, with the test-only staff kind | Envtest verified; end to end deferred to power, the first staff kind with an effect | | A commissioning times out and a later one settles the hold | `TestLifecycle`, `TestRecovery`, with the test-only kind and `DeviceWipe` | Deferred: commissioning is out of scope. The same hold and settle mechanism runs end to end for an installation and a wipe | -| A staff operation targets an allocated, releasing or unsettleable held server and is refused, nothing sent | `TestAdmissionPreconditions`, `TestRecovery`; the `deadline-hold` phase | Envtest verified. End to end, a `DeviceRecovery` naming the held installation at the wrong fence is refused on a releasing Device; custody, the site store and the BMC audit are unchanged | +| A staff operation targets an allocated, releasing or unsettleable held server and is refused, nothing sent | `TestAdmissionPreconditions`, `TestRecovery`; the `deadline-hold` phase | Envtest verified. End to end, a `DeviceRecovery` naming the held installation at the wrong fence is refused for `HoldMismatch` on a releasing Device; custody, the site store and the BMC audit are unchanged | | A worker passes its deadline; `OutcomeUnknown`; settling waits for the worker to stop | `TestLifecycle`, `TestRecovery`, `TestAWorkerStoppedAtItsDeadlineClosesItsAdmission`; the `deadline-hold` and `deadline-settled` phases | End to end in both runs: the installation ends `OutcomeUnknown` with `DeadlineExceeded`, and the settling wipe is admitted only after its worker stopped | | A delayed worker's step after a newer admission is refused by the journal | `TestTwoWorkersOnOneDevice`, `TestANewerFenceStopsTheOlderWorker`, `TestStoreRefusesOlderFencesAndSurvivesARestart`; the `delivery-faults` phase | End to end: an assignment below the stored fence fails its Job before any effect, with the journal and the BMC audit unchanged | | A TLS pin mismatch or an identity mismatch sends nothing | `TestPinMismatchSendsNothing`, `TestIdentityMismatchSendsNothing`; the `redfish-discovery-faults` phase | End to end in the Redfish run: a key other than the pin reaches no request, and a swapped or unknown identity sends only reads | From 218a3718223ca8a78c67cf77f72fd17bfbeee2f3 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 25 Nov 2026 09:16:49 -0600 Subject: [PATCH 08/16] test(multiplane): Show a tenant cannot act on hardware it does not hold While consumer A holds the Device, consumer B's project serves no Device API, the allocator refuses to install for B, and an installation the Metal provider names for B's unheld allocation is refused for HolderMismatch. The fence, the site store and the BMC audit stay unchanged and nothing is delivered. The site store digest now treats a store with no state file yet as empty. Co-Authored-By: Claude Opus 5.5 --- cmd/fleet-multiplane/main.go | 6 +- docs/development/device-custody.md | 1 + docs/operations/multiplane.md | 7 ++- hack/multiplane/acceptance-redfish.sh | 1 + hack/multiplane/acceptance.sh | 1 + hack/multiplane/evidence.py | 2 +- hack/multiplane/harness.py | 2 +- hack/multiplane/steps.sh | 13 ++++- hack/multiplane/test-harness.sh | 4 +- internal/multiplane/scenarios.go | 82 +++++++++++++++++++++++++++ test/acceptance/coverage.md | 1 + 11 files changed, 111 insertions(+), 9 deletions(-) diff --git a/cmd/fleet-multiplane/main.go b/cmd/fleet-multiplane/main.go index 0a78d69d..baf5142f 100644 --- a/cmd/fleet-multiplane/main.go +++ b/cmd/fleet-multiplane/main.go @@ -65,7 +65,7 @@ func run() error { return multiplane.Coordinate(ctx, config, *installationDeadline, func(err error) { fmt.Fprintf(os.Stderr, "%s coordinator: pass incomplete: %v\n", time.Now().UTC().Format(time.RFC3339), err) }) - case "seed", "allocate", "install", "admit-install", "admit-install-b", "release", "release-b", "reuse", "recovery-mismatch", "probe-unallocatable": + case "seed", "allocate", "install", "admit-install", "admit-install-b", "release", "release-b", "reuse", "recovery-mismatch", "probe-unallocatable", "tenant-isolation": return phase(os.Args[1], *configPath, *once) case "redfish-probe": return probe(*endpoint, *credentials, *system, *uuid, *pin) @@ -147,7 +147,7 @@ func phase(name, configPath string, once bool) error { action := map[string]func(context.Context) error{ "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, + "admit-install-b": r.AdmitInstallSecond, "recovery-mismatch": r.RecoveryMismatch, "probe-unallocatable": r.ProbeUnallocatable, "tenant-isolation": r.TenantIsolation, }[name] last := "" for { @@ -162,7 +162,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 == "recovery-mismatch" || name == "probe-unallocatable") { + if err == nil && (name == "recovery-mismatch" || name == "probe-unallocatable" || name == "tenant-isolation") { return nil } if err == nil { diff --git a/docs/development/device-custody.md b/docs/development/device-custody.md index bec7d814..84c52c13 100644 --- a/docs/development/device-custody.md +++ b/docs/development/device-custody.md @@ -394,6 +394,7 @@ phases](../operations/multiplane.md#acceptance-phases) describe each one. | Importing sends nothing | Checked before any allocation: no operation, assignment, worker Job, journal entry or BMC effect | | Staff access | A staff token in the provider project reads custody and creates recoveries, and is forbidden everything else | | Contention | Custody names the one MachineAllocation, the winner's | +| Tenant isolation | The losing consumer's project has no Device API, and an installation for its unheld allocation is refused before delivery | | Deadline | The coordinator restarts with a four-minute installation deadline for one admission, and a lab-only boot hook withholds every boot while it is armed, so the installer is never served | | Machine deleted mid-install | The customer deletes the Machine; release holds the Device and waits for the installation | | Recovery for the wrong hold | Staff name the held installation at the wrong fence; admission refuses it with nothing delivered or sent | diff --git a/docs/operations/multiplane.md b/docs/operations/multiplane.md index 017fdf46..c4021abd 100644 --- a/docs/operations/multiplane.md +++ b/docs/operations/multiplane.md @@ -230,7 +230,12 @@ The phases are then: 2. **Contention.** Two consumers request one provider capacity. Custody grants one allocation; `verify-contention` independently reads Bound for A and Pending/InsufficientCapacity for B, and requires custody to name the one - MachineAllocation, A's. + MachineAllocation, A's. `tenant-isolation` then requires that B, which + holds nothing, cannot reach the server: its project serves no Device API, + the allocator refuses to install for it, and an installation named for its + unheld allocation is refused for `HolderMismatch`. The fence, the site + store and, in Redfish mode, the BMC audit stay unchanged, and nothing is + delivered. 3. **Admission before effects.** The coordinator admits the `DeviceInstallation` and raises the Device's fence, then writes one immutable hub handoff carrying that exact assignment, before any effect. `await-delivery` requires the diff --git a/hack/multiplane/acceptance-redfish.sh b/hack/multiplane/acceptance-redfish.sh index bd744fa9..1da7e137 100755 --- a/hack/multiplane/acceptance-redfish.sh +++ b/hack/multiplane/acceptance-redfish.sh @@ -21,6 +21,7 @@ rf baseline 300 rf discovery-faults 600 ph allocate 900 "$host" allocate --config "$state/acceptance.json" step verify-contention 120 +step tenant-isolation 300 ph admit-install 900 "$host" admit-install --config "$state/acceptance.json" step await-delivery 300 rf arm-lost-response 120 diff --git a/hack/multiplane/acceptance.sh b/hack/multiplane/acceptance.sh index 34f6382c..947d42fc 100755 --- a/hack/multiplane/acceptance.sh +++ b/hack/multiplane/acceptance.sh @@ -16,6 +16,7 @@ step import-inert 300 step staff-access 120 ph allocate 900 "$host" allocate --config "$state/acceptance.json" step verify-contention 120 +step tenant-isolation 300 ph admit-install 900 "$host" admit-install --config "$state/acceptance.json" step await-delivery 300 step partition 300 diff --git a/hack/multiplane/evidence.py b/hack/multiplane/evidence.py index a7187f20..f5f25eec 100755 --- a/hack/multiplane/evidence.py +++ b/hack/multiplane/evidence.py @@ -83,7 +83,7 @@ def copy_out(source, destination): 'interrupt-job: running worker Job deleted mid-install', 'resume: replacement worker completed the exact interrupted operation', 'worker Job is Complete while hub/consumer disconnected; public Ready stayed False', 'install: verified', 'lifecycle: runtime, boot and observer Pods', 'delivery-faults: duplicate refused by the API', 'boot-denials: PASS', 'release: verified', 'release-status-a: consumer-a Machine Released', 'Installation Released, Ready False', 'reuse: verified', 'reuse-status: consumer-b Bound', 'release-b: verified', 'release-status-b: consumer-b Machine deleted', - 'import-inert: ', 'staff-access: staff read custody', 'contention-custody: custody holds the Device for the one MachineAllocation', + 'import-inert: ', 'tenant-isolation: consumer B\'s project has no Device API', 'staff-access: staff read custody', 'contention-custody: custody holds the Device for the one MachineAllocation', 'deadline-admit: the second installation was admitted', 'release-waits: the Machine is deleting', 'deadline-hold: the installation ended OutcomeUnknown at its deadline', 'recovery-mismatch: refused', 'deadline-settled: the release wipe was admitted', 'rebuild-unverified: custody rebuilt Unverified', 'probe-unallocatable: no eligible capacity while custody is Unverified', 'rebuild-verified: custody Verified', diff --git a/hack/multiplane/harness.py b/hack/multiplane/harness.py index ca78f456..e3bde2ff 100755 --- a/hack/multiplane/harness.py +++ b/hack/multiplane/harness.py @@ -27,7 +27,7 @@ # Subcommands and errors the live harness depends on. A missing one blocks before any resource exists. REQUIRED_SOURCE_MARKERS = tuple('"%s"' % c for c in ('seed', 'allocate', 'admit-install', 'install', 'release', 'release-b', 'reuse', 'coordinator', 'image', 'boot-service', 'boot-denials', 'site-worker', 'site-observer', - 'admit-install-b', 'recovery-mismatch', 'probe-unallocatable')) + ('multiplane.ErrLocationNotServed',) + 'admit-install-b', 'recovery-mismatch', 'probe-unallocatable', 'tenant-isolation')) + ('multiplane.ErrLocationNotServed',) READINESS_PACKAGES = ('./internal/coordination', './internal/custody', './internal/site/...', './internal/multiplane', './cmd/fleet-multiplane') # Redfish mode (run.sh --redfish) adds its executor and probe to the readiness gate. PROVIDER = os.environ.get('FLEET_SITE_PROVIDER', 'libvirt') diff --git a/hack/multiplane/steps.sh b/hack/multiplane/steps.sh index 2d02a88f..9800d023 100755 --- a/hack/multiplane/steps.sh +++ b/hack/multiplane/steps.sh @@ -39,8 +39,9 @@ local_phase() { cell -n "$ns" get machineallocationhandoffs -l "$assignments" -o custody_digest() { "${harness[@]}" custody-digest --state "$state"; } # The Device's site store state: its fences and journal. store_state=$(python3 -c 'import sys; sys.path.insert(0, "hack/multiplane"); import harness; print(harness.STATE_PATH)') +# A store with no state file yet, before any assignment, digests as empty. journal_digest() { - runtime cat "$store_state" | python3 -c ' + runtime sh -c "cat '$store_state' 2>/dev/null || true" | python3 -c ' import hashlib,sys print(hashlib.sha256(sys.stdin.buffer.read()).hexdigest())' } @@ -83,6 +84,16 @@ case "$step" in printf 'contention: consumer-a %s; consumer-b %s\n' "$a" "$b" scenario contention "$state" ;; + tenant-isolation) + # Consumer A holds the Device and consumer B holds nothing. Nothing B's + # side asks for reaches the site or the server. + before=$(journal_digest) + audit_mark + "$host" tenant-isolation --config "$state/acceptance.json" + [[ $before == "$(journal_digest)" ]] || { echo 'site store changed for an unheld tenant' >&2; exit 1; } + [[ -z $(cell -n "$ns" get machineallocationhandoffs -l "$assignments" -o name) ]] || { echo 'an assignment was delivered for an unheld tenant' >&2; exit 1; } + audit_unchanged + ;; import-inert) scenario import-inert "$state" ;; diff --git a/hack/multiplane/test-harness.sh b/hack/multiplane/test-harness.sh index 5cceb64d..27c22a56 100755 --- a/hack/multiplane/test-harness.sh +++ b/hack/multiplane/test-harness.sh @@ -69,7 +69,7 @@ with tempfile.TemporaryDirectory() as tmp: good_root = tmp / 'good'; (good_root / 'cmd/fleet-multiplane').mkdir(parents=True) markers = ['seed', 'allocate', 'admit-install', 'install', 'release', 'release-b', 'reuse', 'coordinator', 'image', 'boot-service', 'boot-denials', 'site-worker', 'site-observer', - 'admit-install-b', 'recovery-mismatch', 'probe-unallocatable'] + 'admit-install-b', 'recovery-mismatch', 'probe-unallocatable', 'tenant-isolation'] (good_root / 'cmd/fleet-multiplane/main.go').write_text(' '.join('"%s"' % m for m in markers) + ' multiplane.ErrLocationNotServed') bad_root = tmp / 'bad'; (bad_root / 'cmd/fleet-multiplane').mkdir(parents=True) (bad_root / 'cmd/fleet-multiplane/main.go').write_text(' '.join('"%s"' % m for m in markers)) @@ -190,7 +190,7 @@ with tempfile.TemporaryDirectory() as tmp: for name, text in (('steps', steps), ('evidence', evidence), ('harness', harness.read_text())): check('no docker process launch in site execution: ' + name, '-vm' not in text and 'cell.pid' not in text) sequence = (root / 'hack/multiplane/acceptance.sh').read_text() - order = ['custody-crd-rules', 'import-inert', 'staff-access', 'allocate', 'verify-contention', 'admit-install', 'await-delivery', 'partition', 'dispatch', 'interrupt-pod', 'interrupt-job', 'resume', + order = ['custody-crd-rules', 'import-inert', 'staff-access', 'allocate', 'verify-contention', 'tenant-isolation', 'admit-install', 'await-delivery', 'partition', 'dispatch', 'interrupt-pod', 'interrupt-job', 'resume', 'worker-rbac', 'partition-readiness', 'heal', 'install', 'install-repeat', 'lifecycle', 'graph-lifecycle', 'drift', 'restart', 'fail-closed', 'retention', 'reflection-faults', 'release', 'release-status-a', 'reuse', 'reuse-status', 'delivery-faults', 'deadline-admit', 'machine-delete', 'deadline-hold', 'release-b', 'deadline-settled', 'release-status-b', diff --git a/internal/multiplane/scenarios.go b/internal/multiplane/scenarios.go index 590a9595..859415c7 100644 --- a/internal/multiplane/scenarios.go +++ b/internal/multiplane/scenarios.go @@ -6,6 +6,8 @@ import ( "fmt" "path/filepath" + 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" @@ -135,3 +137,83 @@ func (r *Runner) ProbeUnallocatable(ctx context.Context) error { fmt.Println("probe-unallocatable: no eligible capacity while custody is Unverified; no allocation recorded") return nil } + +// TenantIsolation runs while consumer A holds the Device and consumer B +// holds nothing. B's project has no Device API at all; the allocator refuses +// to install for B; and an installation the Metal provider names for B's +// allocation, which never held the Device, is refused before anything is +// delivered, with custody's fence unchanged. +func (r *Runner) TenantIsolation(ctx context.Context) error { + if err := r.Consumers[1].API.List(ctx, &ops.DeviceCustodyList{}); !meta.IsNoMatchError(err) && !apierrors.IsNotFound(err) { + return fmt.Errorf("%w: a consumer project serves Device custody: %v", errTerminal, err) + } + if err := r.Consumers[1].API.List(ctx, &ops.DeviceInstallationList{}); !meta.IsNoMatchError(err) && !apierrors.IsNotFound(err) { + return fmt.Errorf("%w: a consumer project serves Device operations: %v", errTerminal, err) + } + if _, _, _, _, err := r.installation(ctx, 1); err == nil { + return fmt.Errorf("%w: the allocator installed for a consumer that holds nothing", errTerminal) + } + q, err := r.request(ctx, 1) + if err != nil { + return err + } + before := &ops.DeviceCustody{} + if err := r.Provider.API.Get(ctx, client.ObjectKey{Namespace: DeviceNamespace, Name: Device}, before); err != nil { + return err + } + if before.Spec.Holder.Type != ops.HolderAllocation { + return fmt.Errorf("%w: consumer A does not hold the Device", errTerminal) + } + var install fleet.Installation + if err := q.project.API.Get(ctx, client.ObjectKey{Namespace: Namespace, Name: "debian-pxe"}, &install); 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 + } + unheld := allocation.Name(q.alloc.Machine) + image, err := allocation.ParseImage(install.Spec.ImageRef.Name) + if err != nil { + return err + } + // B's allocation takes this name once B reuses the Device, so the refused + // installation names a synthetic Installation UID to keep its name apart + // from B's later installation. It labels the current Device incarnation, + // as the Metal provider does, so admission reaches the holder check. + const request = "00000000-0000-4000-8000-000000000174" + operation := &ops.DeviceInstallation{} + key := client.ObjectKey{Namespace: DeviceNamespace, Name: custody.InstallationName(unheld, 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, 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}, + Authority: ops.Authority{AllocationRef: &ops.LocalReference{Name: unheld}}}, + Image: image, BootInterface: "primary", TargetDisks: []string{"disk-0"}, + }, + } + 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 == custody.ReasonHolderMismatch: + case phase.Ended() || phase.Running(): + return fmt.Errorf("%w: the unheld installation is %s: %s", errTerminal, phase, operation.Status.Reason) + default: + return fmt.Errorf("%w: the unheld 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 { + return fmt.Errorf("%w: the refused installation changed custody", errTerminal) + } + fmt.Println("tenant-isolation: consumer B's project has no Device API; the allocator refused to install for it; an installation for its unheld allocation was refused for HolderMismatch with the fence unchanged") + return nil +} diff --git a/test/acceptance/coverage.md b/test/acceptance/coverage.md index f5933a6c..3be53911 100644 --- a/test/acceptance/coverage.md +++ b/test/acceptance/coverage.md @@ -52,6 +52,7 @@ and the [multi-plane phases](../../docs/operations/multiplane.md#acceptance-phas | Custody deleted and restored stays unallocatable until rebuilt with a higher fence | `TestRebuild`; the `rebuild` phase | End to end: rebuilt `Unverified` while the site cannot report, a new Machine finds no capacity, then `Verified` above the site's fence | | A Machine deleted during installation; release waits; a wipe settles the install hold | `TestLifecycle`, `TestRecovery`; the `machine-delete`, `deadline-hold` and `deadline-settled` phases | End to end: release holds the Device with the installation active and no wipe, then the wipe settles the hold and the Machine is gone | | No staff role can read a bootstrap payload | `TestRolesKeepOneWriterAndKeepStaffFromCustomerSecrets`; the `staff-access` phase | Role definitions verified. End to end, staff are forbidden Secrets and every write but recoveries. Bootstrap stays refused, so no payload exists to read | +| A tenant cannot trigger an operation on hardware it does not hold (a review request beside #174's list) | `TestAdmissionPreconditions`; the `tenant-isolation` phase | End to end: while consumer A holds the Device, consumer B's project serves no Device API, the allocator refuses to install for B, and an installation the Metal provider names for B's unheld allocation is refused for `HolderMismatch`, with the fence, the journal and the BMC audit unchanged and nothing delivered | | Importing a Device sends nothing and makes no capacity Available | `TestImportedDeviceGetsUnverifiedCustodyAndSendsNothing`; the `import-inert` phase | End to end: no operation, assignment, Job, journal entry or BMC effect. The capacity projector is not wired, so the run's fixture writes capacity status itself | The emulator lab cannot cover these: From d9fda85355f75d418b3faee9a0d8975f674b38ef Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 25 Nov 2026 09:47:06 -0600 Subject: [PATCH 09/16] test(custody): Guard how recoveries use site fence reports A recovery for a Device that no site serves was applied, a recovery recorded the highest rather than the lowest fence its sites confirmed, and a Resolve kept a fence below one a site had seen, and no test failed. Three tests now fail on each of those changes. Co-Authored-By: Claude Opus 5.5 --- docs/development/device-custody.md | 14 ++++ internal/custody/fences_test.go | 110 +++++++++++++++++++++++++++++ 2 files changed, 124 insertions(+) create mode 100644 internal/custody/fences_test.go diff --git a/docs/development/device-custody.md b/docs/development/device-custody.md index 84c52c13..af61a969 100644 --- a/docs/development/device-custody.md +++ b/docs/development/device-custody.md @@ -1025,6 +1025,20 @@ Increment D's site tests run with `go test -race ./internal/site/...`: | A worker stopped at its deadline closes its boot admission, in both workers | `TestAWorkerStoppedAtItsDeadlineClosesItsAdmission` | | A local VM wipe powers off a running guest, and is not proven while it keeps running | `TestAWipePowersOffARunningDomain`, `TestAWipeWithADomainThatKeepsRunningIsNotProven` | +Increment D also adds coordinator tests, run with `task test:envtest`, that +fail if the use of site fence reports is weakened. Each was checked against +the change it guards: + +| Guard | Test | +| --- | --- | +| A recovery on a Device that no site serves is never confirmed | `TestARecoveryOnADeviceNoSiteServesIsNeverConfirmed` | +| A recovery records the lowest fence its sites confirmed, and waits for every site | `TestARecoveryConfirmsTheLowestFenceOfItsSites` | +| A Resolve raises custody's fence above every fence a site has seen | `TestAResolveRaisesTheFenceAboveEverySeenFence` | + +`TestFencesFollowTheSiteReport` already fails if admission ignores the seen +fence, if a recovery is confirmed by the seen fence alone, or if an +unreported site counts as confirmed. + The multi-plane local VM and Redfish runs (`task multiplane:acceptance` and `task multiplane:redfish-acceptance`) run the same workers and the failure scenarios. The acceptance state of each #174 test is in the [coverage diff --git a/internal/custody/fences_test.go b/internal/custody/fences_test.go new file mode 100644 index 00000000..7c7527bd --- /dev/null +++ b/internal/custody/fences_test.go @@ -0,0 +1,110 @@ +package custody + +import ( + "fmt" + "testing" + + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" +) + +// These tests guard the coordinator's use of site fence reports: a recovery +// applies only once every serving site confirms its fence, the fence it +// records is the lowest any site confirmed, and a Resolve raises custody's +// fence above every fence a site has seen. Each one fails if its guard is +// removed. + +// reportAt stores the stopped fence one named site reports for a Device. +func (s *fakeSites) reportAt(site, device string, fence int64) { + s.mu.Lock() + defer s.mu.Unlock() + s.fences[site+"/"+device] = fence +} + +// serve sets the sites that serve a Device. +func (s *fakeSites) serve(device string, sites ...string) { + s.mu.Lock() + defer s.mu.Unlock() + s.serving[device] = sites +} + +func TestARecoveryOnADeviceNoSiteServesIsNeverConfirmed(t *testing.T) { + e := startEnv(t) + device := e.verified("server-example-830", uid(830), fmt.Sprintf("%064x", 830)) + hold := e.holdOn(device) + e.sites.serve(device.Name) + retire := e.recovery(device, ops.DeviceRecoverySpec{Decision: ops.DecisionRetire, Hold: heldRef(hold)}) + e.settle(device.Name) + if status := e.status(retire); status.Phase == ops.PhaseSucceeded { + t.Fatalf("a recovery applied with no serving site: %+v", status) + } + e.clock.Advance(RecoveryDeadline + DefaultSkewMargin) + e.settle(device.Name) + if status := e.status(retire); status.Phase == ops.PhaseSucceeded { + t.Fatalf("a recovery applied with no serving site after its deadline: %+v", status) + } + if custody := e.custody(device.Name); custody.Spec.RecoveryHold == nil || *heldRef(*custody.Spec.RecoveryHold) != *heldRef(hold) || custody.Spec.Holder.Type == ops.HolderRetired { + t.Fatalf("custody after an unconfirmed recovery = %+v", custody.Spec) + } +} + +func TestARecoveryConfirmsTheLowestFenceOfItsSites(t *testing.T) { + e := startEnv(t) + device := e.verified("server-example-831", uid(831), fmt.Sprintf("%064x", 831)) + hold := e.holdOn(device) + e.sites.serve(device.Name, testSite, "site-example-b") + e.sites.reportAt("site-example-b", device.Name, hold.Fence) + retire := e.recovery(device, ops.DeviceRecoverySpec{Decision: ops.DecisionRetire, Hold: heldRef(hold)}) + e.settle(device.Name) + active := e.custody(device.Name).Spec.ActiveOperation + if active == nil { + t.Fatal("the recovery was not admitted") + } + // One site confirms; the other has not stopped its older worker yet. + e.sites.reportAt(testSite, device.Name, active.Fence) + e.settle(device.Name) + e.requirePhase(retire, ops.PhaseAdmitted, "") + // Both confirm, at different fences: the lower one is recorded. + e.sites.reportAt(testSite, device.Name, active.Fence+3) + e.sites.reportAt("site-example-b", device.Name, active.Fence) + e.settle(device.Name) + status := e.requirePhase(retire, ops.PhaseSucceeded, "") + var evidence ops.RecoveryResultEvidence + if err := jsonUnmarshal(status.Evidence.Raw, &evidence); err != nil || evidence.ConfirmedFence != active.Fence { + t.Fatalf("recovery evidence = %s, want the lowest confirmed fence %d", status.Evidence.Raw, active.Fence) + } +} + +func TestAResolveRaisesTheFenceAboveEverySeenFence(t *testing.T) { + e := startEnv(t) + device := e.device("server-example-832", uid(832), fmt.Sprintf("%064x", 832)) + allocation := "alloc-s-" + device.Name + e.allocation(device, allocation, "Active") + // Two unproven installations make the rebuild need a Resolve. + for index, fence := range []int64{2, 5} { + install := e.installation(device, allocation, fmt.Sprintf("request-%d", index)) + install.Status = ops.OperationStatus{Admission: admitted(fence), Phase: ops.PhaseOutcomeUnknown, Fence: fence, FinishedAt: ptrTime(e.clock.Now())} + if err := e.admin.Status().Update(e.ctx, install); err != nil { + t.Fatal(err) + } + } + e.sites.report(device.Name, 5) + e.settle(device.Name) + if state := e.custody(device.Name).Spec.State; state != ops.CustodyUnverified { + t.Fatalf("rebuilt custody is %s, want Unverified", state) + } + resolve := e.recovery(device, ops.DeviceRecoverySpec{Decision: ops.DecisionResolve, Resolve: &ops.ResolveInput{Holder: ops.HolderAllocation, AllocationRef: &ops.LocalReference{Name: allocation}}}) + e.settle(device.Name) + active := e.custody(device.Name).Spec.ActiveOperation + if active == nil { + t.Fatal("the Resolve was not admitted") + } + // The site confirms the Resolve's fence, and has seen a higher one from + // an assignment custody never recorded. + e.sites.report(device.Name, active.Fence) + e.sites.reportSeen(device.Name, active.Fence+40) + e.settle(device.Name) + e.requirePhase(resolve, ops.PhaseSucceeded, "") + if custody := e.custody(device.Name); custody.Spec.State != ops.CustodyVerified || custody.Spec.Fence < active.Fence+40 { + t.Fatalf("resolved custody = %+v, want Verified at a fence of at least %d", custody.Spec, active.Fence+40) + } +} From 10371ea3c97732818ea893a70b706e3f4553cd4c Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 25 Nov 2026 12:36:32 -0600 Subject: [PATCH 10/16] test(multiplane): Make the failure scenarios prove what they claim From the adversarial review of the failure scenarios: - the deadline scenario records the worker's handoff at delivery and fails if that worker is not seen stopping, instead of passing with nothing observed; - tenant isolation requires the refusal for a missing allocation, not any error; - every nothing-sent check also compares the hypervisor's running domains and QEMU logs, so the local VM run proves it too; - the deadline is six minutes, the scenario fails fast if the installation ends early, and it picks the held allocation's installation; - a failed step restores the coordinator, the boot hook and the observer; - the hook guard test also rejects a Flux path at the lab site source; - the local VM wipe tolerates a guest that exits before its destroy; - the coverage inventory says what each phase checks and leaves verification to the status table, scoped to what the runs exercise. Co-Authored-By: Claude Opus 5.5 --- cmd/fleet-multiplane/withhold_test.go | 11 +++-- docs/development/device-custody.md | 2 +- docs/operations/multiplane.md | 2 +- docs/operations/redfish-lab.md | 2 +- hack/multiplane/scenarios.py | 61 ++++++++++++++++++--------- hack/multiplane/steps.sh | 36 +++++++++++++--- internal/multiplane/runner.go | 6 ++- internal/multiplane/scenarios.go | 4 +- internal/site/vmwork/kinds.go | 13 ++++-- internal/site/vmwork/kinds_test.go | 25 ++++++++++- test/acceptance/coverage.md | 28 +++++++----- 11 files changed, 137 insertions(+), 53 deletions(-) diff --git a/cmd/fleet-multiplane/withhold_test.go b/cmd/fleet-multiplane/withhold_test.go index fae82a49..a6b38963 100644 --- a/cmd/fleet-multiplane/withhold_test.go +++ b/cmd/fleet-multiplane/withhold_test.go @@ -59,9 +59,11 @@ func TestAnArmedWithholdDeniesEveryBootRequest(t *testing.T) { } // TestOnlyTheLabSiteSourceSetsTheWithholdHook keeps the hook out of -// production: only the boot service of the local multi-plane site's Flux -// source sets the variable, no production root references that source, and -// no other package names the variable. +// production. The primary control is the binary: only this acceptance +// binary reads the variable, and no production image runs it. The test adds +// that only the boot service of the local multi-plane site's Flux source +// sets the variable, that no other configuration includes or points a Flux +// path at that source, and that no other package names the variable. func TestOnlyTheLabSiteSourceSetsTheWithholdHook(t *testing.T) { root := filepath.Join("..", "..") var setters []string @@ -79,6 +81,9 @@ func TestOnlyTheLabSiteSourceSetsTheWithholdHook(t *testing.T) { setters = append(setters, rel) } lab := strings.HasPrefix(rel, filepath.Join("config", "site")+string(filepath.Separator)) || strings.HasPrefix(rel, filepath.Join("config", "multiplane")+string(filepath.Separator)) + if !lab && filepath.Ext(path) != ".md" && strings.Contains(text, "config/site") { + t.Errorf("%s points at the lab site source", rel) + } if !lab && filepath.Base(path) == "kustomization.yaml" { for _, line := range strings.Split(text, "\n") { entry := strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(line), "- ")) diff --git a/docs/development/device-custody.md b/docs/development/device-custody.md index af61a969..c97897c0 100644 --- a/docs/development/device-custody.md +++ b/docs/development/device-custody.md @@ -395,7 +395,7 @@ phases](../operations/multiplane.md#acceptance-phases) describe each one. | Staff access | A staff token in the provider project reads custody and creates recoveries, and is forbidden everything else | | Contention | Custody names the one MachineAllocation, the winner's | | Tenant isolation | The losing consumer's project has no Device API, and an installation for its unheld allocation is refused before delivery | -| Deadline | The coordinator restarts with a four-minute installation deadline for one admission, and a lab-only boot hook withholds every boot while it is armed, so the installer is never served | +| Deadline | The coordinator restarts with a six-minute installation deadline for one admission, and a lab-only boot hook withholds every boot while it is armed, so the installer is never served | | Machine deleted mid-install | The customer deletes the Machine; release holds the Device and waits for the installation | | Recovery for the wrong hold | Staff name the held installation at the wrong fence; admission refuses it with nothing delivered or sent | | A wipe settles the hold | The release wipe is admitted above the held fence after the worker stopped | diff --git a/docs/operations/multiplane.md b/docs/operations/multiplane.md index c4021abd..01a97906 100644 --- a/docs/operations/multiplane.md +++ b/docs/operations/multiplane.md @@ -334,7 +334,7 @@ The phases are then: Redfish mode the BMC audit must gain no effect. 14. **Deadline and Machine deletion.** `deadline-admit` arms a lab-only hook in the boot service, which then withholds every boot while staying Ready, - and restarts the coordinator with a four-minute installation deadline for + and restarts the coordinator with a six-minute installation deadline for consumer B's installation only. kro still creates the worker, and the installer boot is requested but never served. `machine-delete` has the customer delete B's Machine mid-install. One release pass must leave diff --git a/docs/operations/redfish-lab.md b/docs/operations/redfish-lab.md index 853c54f6..1db1520b 100644 --- a/docs/operations/redfish-lab.md +++ b/docs/operations/redfish-lab.md @@ -356,7 +356,7 @@ fixture discovery for the lab Devices. Real BMC discovery is not part of this ru | `interrupt-pod`, `interrupt-job` | As in libvirt mode, now on the Redfish worker, still inside the installer phase | | `redfish-arm-lost-response`, `redfish-lost-response` | Armed before dispatch: the second effective `On` for System-1 (the first install's disk boot) is answered only after 45 seconds. The worker times out and exits 75 (Unknown). Its replacement observes the running or completed target and the consumed override. Exactly one `On` per phase was sent: `powerOnRequests` is one installer and one disk request. | | `resume` | The recreated Job completes the exact operation with one succeeded Pod | -| `deadline-admit`, `machine-delete`, `deadline-hold` | After the wipe and reuse, consumer B's installation runs under a four-minute deadline with the lab boot hook armed. Its `On` is sent and its installer is never served. The Machine is deleted mid-install, the installation ends `OutcomeUnknown` at its deadline, and a mismatched staff recovery is refused with no BMC effect. The release wipe powers the target off and settles the hold. | +| `deadline-admit`, `machine-delete`, `deadline-hold` | After the wipe and reuse, consumer B's installation runs under a six-minute deadline with the lab boot hook armed. Its `On` is sent and its installer is never served. The Machine is deleted mid-install, the installation ends `OutcomeUnknown` at its deadline, and a mismatched staff recovery is refused with no BMC effect. The release wipe powers the target off and settles the hold. | | `boot-denials` | Closed per-MAC scripts and capabilities of all four operations, target B's MAC and unknown identities are denied over the live boot Service | | `redfish-isolation` | Target B: unchanged disk digest, no QEMU start, no console line, no mutating Redfish request. Target A: disk hashes as all zeroes. No domain running. Exports the BMC audit. | diff --git a/hack/multiplane/scenarios.py b/hack/multiplane/scenarios.py index e0d5d37e..34d31a05 100644 --- a/hack/multiplane/scenarios.py +++ b/hack/multiplane/scenarios.py @@ -19,6 +19,9 @@ PROVIDER_NS, DEVICE = 'fleet-provider', 'synthetic-device-central-01' ASSIGNMENTS = 'coordination.fleet.datumapis.com/role=assignment' REDFISH = harness.PROVIDER == 'redfish' +# The Installation UID the tenant-isolation phase's refused installation +# labels (internal/multiplane/scenarios.go). +TENANT_REQUEST = '00000000-0000-4000-8000-000000000174' def die(message): @@ -174,21 +177,32 @@ def contention(s): print('contention-custody: custody holds the Device for the one MachineAllocation, consumer-a\'s') -def newest_install(s): - ops = sorted(items(s, 'deviceinstallations'), key=lambda o: o['metadata']['creationTimestamp']) - return ops[-1] if ops else None +def holder_install(s): + """The one installation for the allocation custody holds, ignoring the + tenant-isolation phase's refused installation.""" + allocation = (custody(s)['spec']['holder'].get('allocationRef') or {}).get('name') + ops = [o for o in items(s, 'deviceinstallations') if (o['spec']['authority'].get('allocationRef') or {}).get('name') == allocation + and o['metadata'].get('labels', {}).get('fleet.datumapis.com/installation-uid') != TENANT_REQUEST] + if not allocation or len(ops) != 1: + die('expected one installation for the held allocation %s, found %d' % (allocation, len(ops))) + return ops[0] def wait_installer(s, step): - """Record the newest installation and wait until it journaled its - installer step.""" - name = newest_install(s)['metadata']['name'] + """Record the held allocation's installation and its handoff, and wait + until it journaled its installer step. It fails at once if the + installation already ended, so a slow start is reported as itself.""" + name = holder_install(s)['metadata']['name'] # The site keys the operation by kind, name and the fence it was admitted # at; a same-name installation created later is admitted at another. - key = wait_for(lambda: admitted_key(provider(s, 'get', 'deviceinstallation', name)), 300, 'the second installation to be admitted', interval=1) - (s / 'deadline-install.json').write_text(json.dumps({'name': name, 'key': key}) + '\n') + key = wait_for(lambda: admitted_key(provider(s, 'get', 'deviceinstallation', name)), 300, 'the installation to be admitted', interval=1) + handoff = wait_for(lambda: handoff_for(s, key), 300, 'the installation to be delivered', interval=1) + (s / 'deadline-install.json').write_text(json.dumps({'name': name, 'key': key, 'handoff': handoff}) + '\n') def journaled(): + phase = deadline_op(s)[0].get('status', {}).get('phase') + if phase in ('Succeeded', 'Failed', 'Cancelled', 'OutcomeUnknown'): + die('the installation ended %s before it journaled %s; its deadline left too little time' % (phase, step)) for o in harness.journal(s) or []: if o['operation'] == key and any(n == step for n, _ in o['steps']): return o @@ -243,17 +257,18 @@ def ended(): hold = custody(s)['spec'].get('recoveryHold') or {} if not same_admission(hold, key) or hold.get('fence') != status.get('fence'): die('custody does not hold the installation: %s' % hold.get('kind')) - handoff = handoff_for(s, key) - finished = [] - if handoff: - def stopped(): - pods = get(s, 'cell-admin.yaml', '-n', SITE, 'get', 'pods', '-l', 'fleet.datumapis.com/handoff=' + handoff)['items'] - ends = [c['state']['terminated']['finishedAt'] for p in pods for c in p['status'].get('containerStatuses', []) if 'terminated' in c.get('state', {})] - return ends if pods and len(ends) == len(pods) else None - finished = wait_for(stopped, 300, 'the installation worker to stop') + # The handoff was recorded at delivery: its worker Pods must show the + # worker stopped. A missing Pod is a failure, never a pass. + handoff = json.loads((s / 'deadline-install.json').read_text())['handoff'] + + def stopped(): + pods = get(s, 'cell-admin.yaml', '-n', SITE, 'get', 'pods', '-l', 'fleet.datumapis.com/handoff=' + handoff)['items'] + ends = [c['state']['terminated']['finishedAt'] for p in pods for c in p['status'].get('containerStatuses', []) if 'terminated' in c.get('state', {})] + return ends if pods and len(ends) == len(pods) else None + finished = wait_for(stopped, 300, 'the installation worker to stop') boots = [b for b in harness.journal(s) or [] if b['operation'] == key] record = {'phase': 'OutcomeUnknown', 'reason': 'DeadlineExceeded', 'fence': status['fence'], 'deadline': status.get('deadline'), - 'holdFence': hold['fence'], 'workerFinishedAt': max(finished) if finished else None, 'journaledSteps': [n for o in boots for n, _ in o['steps']]} + 'holdFence': hold['fence'], 'workerFinishedAt': max(finished), 'journaledSteps': [n for o in boots for n, _ in o['steps']]} (s / 'deadline-hold.json').write_text(json.dumps(record) + '\n') write(s, 'deadline-hold.json', record) print('deadline-hold: the installation ended OutcomeUnknown at its deadline; custody holds it at fence %d; its worker stopped' % status['fence']) @@ -273,7 +288,7 @@ def deadline_settled(s): spec = custody(s)['spec'] if wipe['fence'] <= held['fence'] or spec.get('recoveryHold') or spec['holder']['type'] != 'None': die('the wipe did not settle the installation hold: wipe fence %s, held fence %s, hold %s' % (wipe['fence'], held['fence'], bool(spec.get('recoveryHold')))) - if held['workerFinishedAt'] and wipe['admittedAt'] < held['workerFinishedAt']: + if wipe['admittedAt'] < held['workerFinishedAt']: die('the wipe was admitted before the installation worker stopped') r = kubectl(s, 'consumer-b/management-project.json', '-n', 'default', 'get', 'machine', 'allocation', check=False) if r.returncode == 0 or 'NotFound' not in r.stderr: @@ -319,9 +334,13 @@ def rebuild_verified(s): site_fence = max(before['siteFence'] or 0, before['siteStopped'] or 0) if c['spec']['fence'] <= site_fence or c['spec']['fence'] <= before['oldFence']: die('rebuilt custody fence %d is not above the site fence %d and the old fence %d' % (c['spec']['fence'], site_fence, before['oldFence'])) - if items(s, 'machineallocations') and any(a['status'].get('phase') != 'Released' for a in items(s, 'machineallocations')): - die('an allocation became active during the rebuild') - write(s, 'rebuild.json', dict(before, verifiedFence=c['spec']['fence'], verifiedHolder=c['spec']['holder']['type'], probeAllocated=False)) + probe = get(s, 'consumer-a/management-project.json', '-n', 'default', 'get', 'machine', 'allocation')['metadata']['uid'] + allocations = items(s, 'machineallocations') + # An allocation labels the Machine incarnation it is for. + probe_allocated = any(a['metadata'].get('labels', {}).get('fleet.datumapis.com/machine-uid') == probe for a in allocations) + if probe_allocated or any(a.get('status', {}).get('phase') != 'Released' for a in allocations): + die('an allocation was recorded during the rebuild') + write(s, 'rebuild.json', dict(before, verifiedFence=c['spec']['fence'], verifiedHolder=c['spec']['holder']['type'], probeAllocated=probe_allocated)) print('rebuild-verified: custody Verified at fence %d, above the site fence %d; nothing was allocated while Unverified' % (c['spec']['fence'], site_fence)) diff --git a/hack/multiplane/steps.sh b/hack/multiplane/steps.sh index 9800d023..8bd52f43 100755 --- a/hack/multiplane/steps.sh +++ b/hack/multiplane/steps.sh @@ -50,9 +50,22 @@ installer_step=installer-start [[ $(cat "$state/site-provider" 2>/dev/null) != redfish ]] || installer_step=installer-power-on scenario() { python3 hack/multiplane/scenarios.py "$@"; } redfish() { [[ $(cat "$state/site-provider" 2>/dev/null) == redfish ]]; } -# The lab BMC audit: mark its length, then require no effect after the mark. -audit_mark() { ! redfish || python3 hack/multiplane/redfish_steps.py audit-mark "$state"; } -audit_unchanged() { ! redfish || python3 hack/multiplane/redfish_steps.py audit-unchanged "$state"; } +# Effects on servers, independent of the site journal: the hypervisor's +# running domains and its append-only QEMU logs, in both modes, and the lab +# BMC audit in Redfish mode. Mark them, then require none after the mark. +server_effects() { + runtime sh -c 'virsh --connect "qemu:///system?socket=/run/fleet-libvirt/libvirt-sock" list --name && { ls -ln /var/log/libvirt/qemu 2>/dev/null || true; }' | python3 -c ' +import hashlib,sys +print(hashlib.sha256(sys.stdin.buffer.read()).hexdigest())' +} +audit_mark() { + server_effects > "$state/server-effects-mark" + ! redfish || python3 hack/multiplane/redfish_steps.py audit-mark "$state" +} +audit_unchanged() { + [[ $(server_effects) == "$(cat "$state/server-effects-mark")" ]] || { echo 'a domain started or a QEMU log changed' >&2; return 1; } + ! redfish || python3 hack/multiplane/redfish_steps.py audit-unchanged "$state" +} # A cell site Deployment stopped for a fault. Its Flux layer is suspended # first, so the harness is never a second writer, and resumed to restore it. site_stop() { @@ -101,17 +114,21 @@ case "$step" in scenario staff-access "$state" ;; deadline-admit) - # Consumer B's installation is admitted under a four-minute deadline with + # Consumer B's installation is admitted under a six-minute deadline with # the lab boot hook armed: the boot service stays Ready, so kro creates # the worker, and withholds every boot, so the installer never runs and # the worker waits for its receipt until the deadline. Only this admission - # uses the short deadline. + # uses the short deadline. A failure here restores the default + # coordinator and clears the hook, so a rerun starts clean. + trap 'bash hack/multiplane/coordinator.sh restart "$state" >/dev/null; site exec deploy/fleet-site-boot -c boot -- fleet-multiplane boot-withhold clear' ERR site exec deploy/fleet-site-boot -c boot -- fleet-multiplane boot-withhold arm - bash hack/multiplane/coordinator.sh restart "$state" --installation-deadline=4m >/dev/null + bash hack/multiplane/coordinator.sh restart "$state" --installation-deadline=6m >/dev/null "$host" admit-install-b --config "$state/acceptance.json" >/dev/null bash hack/multiplane/coordinator.sh restart "$state" >/dev/null + trap 'site exec deploy/fleet-site-boot -c boot -- fleet-multiplane boot-withhold clear' ERR scenario wait-installer "$state" "$installer_step" - printf 'deadline-admit: the second installation was admitted under a four-minute deadline and journaled its installer boot with the lab boot hook withholding it\n' + trap - ERR + printf 'deadline-admit: the second installation was admitted under a six-minute deadline and journaled its installer boot with the lab boot hook withholding it\n' ;; machine-delete) # The customer deletes Machine B mid-install. One release pass begins the @@ -121,6 +138,7 @@ case "$step" in scenario release-waits "$state" ;; deadline-hold) + trap 'site exec deploy/fleet-site-boot -c boot -- fleet-multiplane boot-withhold clear' ERR scenario deadline-hold "$state" # A staff recovery naming the wrong hold is refused before anything is # delivered or sent. @@ -130,6 +148,7 @@ case "$step" in [[ $before == "$(journal_digest)" ]] || { echo 'site store changed for a refused recovery' >&2; exit 1; } audit_unchanged # The release's wipe boots normally. + trap - ERR site exec deploy/fleet-site-boot -c boot -- fleet-multiplane boot-withhold clear ;; deadline-settled) @@ -140,6 +159,8 @@ case "$step" in # fence: the observer answers fence reports, and the hub accepts none # older than a minute. scenario rebuild-before "$state" + # A failure hands the observer back to Flux, so a rerun starts clean. + trap 'site_restore fleet-site-observer' ERR site_stop fleet-site-observer sleep 75 bootstrap="$state/provider/bootstrap-project.json" @@ -154,6 +175,7 @@ case "$step" in {"apiVersion":"metal.datumapis.com/v1alpha1","kind":"Machine","metadata":{"name":"allocation","namespace":"default"},"spec":{"machineClassRef":{"name":"local-class"},"machineProfileRef":{"name":"local-profile"},"locationRef":{"name":"local"},"powerState":"Off"}} JSON "$host" probe-unallocatable --config "$state/acceptance.json" --once + trap - ERR site_restore fleet-site-observer scenario rebuild-verified "$state" ;; diff --git a/internal/multiplane/runner.go b/internal/multiplane/runner.go index fdac9c4b..269fbd96 100644 --- a/internal/multiplane/runner.go +++ b/internal/multiplane/runner.go @@ -395,7 +395,7 @@ func (r *Runner) installation(ctx context.Context, index int) (*request, *fleet. return nil, nil, nil, nil, err } if current == nil || current.Status.Phase != fleet.AllocationActive { - return nil, nil, nil, nil, errors.New("the consumer has no active allocation") + 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 { @@ -469,6 +469,10 @@ func (r *Runner) InstallIndex(ctx context.Context, index int) error { return r.projectPower(ctx, q) } +// errNoActiveAllocation means the consumer holds no active allocation, so +// the Metal provider installs nothing for it. +var errNoActiveAllocation = errors.New("the consumer has no active allocation") + // errTerminal marks an error that retrying cannot fix. var errTerminal = errors.New("terminal") diff --git a/internal/multiplane/scenarios.go b/internal/multiplane/scenarios.go index 859415c7..6373a81b 100644 --- a/internal/multiplane/scenarios.go +++ b/internal/multiplane/scenarios.go @@ -150,8 +150,8 @@ func (r *Runner) TenantIsolation(ctx context.Context) error { if err := r.Consumers[1].API.List(ctx, &ops.DeviceInstallationList{}); !meta.IsNoMatchError(err) && !apierrors.IsNotFound(err) { return fmt.Errorf("%w: a consumer project serves Device operations: %v", errTerminal, err) } - if _, _, _, _, err := r.installation(ctx, 1); err == nil { - return fmt.Errorf("%w: the allocator installed for a consumer that holds nothing", errTerminal) + if _, _, _, _, err := r.installation(ctx, 1); !errors.Is(err, errNoActiveAllocation) { + return fmt.Errorf("%w: installing for a consumer that holds nothing was not refused for its missing allocation: %v", errTerminal, err) } q, err := r.request(ctx, 1) if err != nil { diff --git a/internal/site/vmwork/kinds.go b/internal/site/vmwork/kinds.go index c9eddb0b..09e7ec09 100644 --- a/internal/site/vmwork/kinds.go +++ b/internal/site/vmwork/kinds.go @@ -18,6 +18,7 @@ import ( "os" "os/exec" "path/filepath" + "slices" "strings" "time" @@ -447,12 +448,18 @@ func (k Wipe) Run(ctx context.Context, work *site.Work) (any, error) { Name: "wipe-power-off", Send: func(ctx context.Context) error { names, err := running(ctx) + if err != nil { + return err + } for _, name := range names { - if err == nil { - _, err = k.virsh(ctx, "destroy", name) + if _, err := k.virsh(ctx, "destroy", name); err != nil { + // A guest that exited after the list is already off. + if still, lerr := running(ctx); lerr != nil || slices.Contains(still, name) { + return err + } } } - return err + return nil }, Idempotent: true, }); err != nil { diff --git a/internal/site/vmwork/kinds_test.go b/internal/site/vmwork/kinds_test.go index 2a15de7e..69d0692f 100644 --- a/internal/site/vmwork/kinds_test.go +++ b/internal/site/vmwork/kinds_test.go @@ -3,6 +3,7 @@ package vmwork import ( "context" "encoding/json" + "errors" "net/http" "net/http/httptest" "os" @@ -37,6 +38,8 @@ type hypervisor struct { noReceipt bool // stuck makes destroy leave the domain running. stuck bool + // exited makes destroy fail because the guest exited first. + exited bool } var receiptArg = regexp.MustCompile(`fleet.receipt=([0-9a-f]{64})`) @@ -77,6 +80,10 @@ func (h *hypervisor) run(_ context.Context, _ string, args ...string) (string, e delete(h.running, name) } case "destroy": + if h.exited { + delete(h.running, args[1]) + return "", errors.New("error: domain is not running") + } if !h.stuck { delete(h.running, args[1]) } @@ -181,6 +188,18 @@ func TestAWipePowersOffARunningDomain(t *testing.T) { } } +// TestAWipeToleratesAGuestThatExitsBeforeItsDestroy treats a guest that +// stopped between the list and the destroy as powered off. +func TestAWipeToleratesAGuestThatExitsBeforeItsDestroy(t *testing.T) { + r := newRig(t) + r.vm.running["fleet-local-0000000000000000"] = "console" + r.vm.exited = true + result, err := r.runner.Run(context.Background(), r.assignment("DeviceWipe", "00000000-0000-4000-8000-000000000209", 2, wipeSpec())) + if err != nil || result.Phase != ops.PhaseSucceeded { + t.Fatalf("wipe after the guest exited = %+v, %v", result, err) + } +} + // TestAWipeWithADomainThatKeepsRunningIsNotProven keeps a disk in use from // counting as wiped. func TestAWipeWithADomainThatKeepsRunningIsNotProven(t *testing.T) { @@ -277,8 +296,8 @@ func TestTheBootServerServesOnlyAnOpenAdmissionAtTheStoredFence(t *testing.T) { } } -// TestAFailedNetworkBootClosesItsAdmission stops serving the installer as -// soon as a network-boot installation fails. +// TestAWorkerStoppedAtItsDeadlineClosesItsAdmission stops serving the +// installer once nothing can resume the installation. func TestAWorkerStoppedAtItsDeadlineClosesItsAdmission(t *testing.T) { r := newRig(t) r.config.PXE = true @@ -298,6 +317,8 @@ func TestAWorkerStoppedAtItsDeadlineClosesItsAdmission(t *testing.T) { } } +// TestAFailedNetworkBootClosesItsAdmission stops serving the installer as +// soon as a network-boot installation fails. func TestAFailedNetworkBootClosesItsAdmission(t *testing.T) { r := newRig(t) r.config.PXE = true diff --git a/test/acceptance/coverage.md b/test/acceptance/coverage.md index 3be53911..997ceae8 100644 --- a/test/acceptance/coverage.md +++ b/test/acceptance/coverage.md @@ -39,21 +39,27 @@ runs, the local VM and the Redfish lab, through real Milo project APIs, Karmada, kro and the site. See [device custody](../../docs/development/device-custody.md#tests) and the [multi-plane phases](../../docs/operations/multiplane.md#acceptance-phases). +"Nothing sent" in a phase means the site journal, the hypervisor's running +domains and its QEMU logs are unchanged in both runs, and the lab BMC audit +holds no new effect in the Redfish run. Whether both runs passed every phase +at a given head is recorded in the [device custody +status](../../docs/development/device-custody.md#status). + | #174 acceptance test | Executable evidence | Current state | | --- | --- | --- | -| Two allocators race for one server; one wins | `TestConcurrency`, `TestConcurrentAllocatorsOneWinner`; the `verify-contention` phase | Envtest verified for true concurrency. End to end, two consumers contend and custody names the one MachineAllocation | +| Two allocators race for one server; one wins | `TestConcurrency`, `TestConcurrentAllocatorsOneWinner`; the `verify-contention` phase | Envtest verified for true concurrency. The phase checks that two consumers contend and custody names the one MachineAllocation | | An allocator retries after a lost response and claims no second server | `TestConcurrency`, `TestAnAllocationThatLostItsDeviceIsReplaced` | Envtest verified; the allocation is named from the Machine UID, so a retry finds the same one | | A staff operation names a customer allocation and is refused | `TestAdmissionPreconditions`, with the test-only staff kind | Envtest verified; end to end deferred to power, the first staff kind with an effect | -| A commissioning times out and a later one settles the hold | `TestLifecycle`, `TestRecovery`, with the test-only kind and `DeviceWipe` | Deferred: commissioning is out of scope. The same hold and settle mechanism runs end to end for an installation and a wipe | -| A staff operation targets an allocated, releasing or unsettleable held server and is refused, nothing sent | `TestAdmissionPreconditions`, `TestRecovery`; the `deadline-hold` phase | Envtest verified. End to end, a `DeviceRecovery` naming the held installation at the wrong fence is refused for `HoldMismatch` on a releasing Device; custody, the site store and the BMC audit are unchanged | -| A worker passes its deadline; `OutcomeUnknown`; settling waits for the worker to stop | `TestLifecycle`, `TestRecovery`, `TestAWorkerStoppedAtItsDeadlineClosesItsAdmission`; the `deadline-hold` and `deadline-settled` phases | End to end in both runs: the installation ends `OutcomeUnknown` with `DeadlineExceeded`, and the settling wipe is admitted only after its worker stopped | -| A delayed worker's step after a newer admission is refused by the journal | `TestTwoWorkersOnOneDevice`, `TestANewerFenceStopsTheOlderWorker`, `TestStoreRefusesOlderFencesAndSurvivesARestart`; the `delivery-faults` phase | End to end: an assignment below the stored fence fails its Job before any effect, with the journal and the BMC audit unchanged | -| A TLS pin mismatch or an identity mismatch sends nothing | `TestPinMismatchSendsNothing`, `TestIdentityMismatchSendsNothing`; the `redfish-discovery-faults` phase | End to end in the Redfish run: a key other than the pin reaches no request, and a swapped or unknown identity sends only reads | -| Custody deleted and restored stays unallocatable until rebuilt with a higher fence | `TestRebuild`; the `rebuild` phase | End to end: rebuilt `Unverified` while the site cannot report, a new Machine finds no capacity, then `Verified` above the site's fence | -| A Machine deleted during installation; release waits; a wipe settles the install hold | `TestLifecycle`, `TestRecovery`; the `machine-delete`, `deadline-hold` and `deadline-settled` phases | End to end: release holds the Device with the installation active and no wipe, then the wipe settles the hold and the Machine is gone | -| No staff role can read a bootstrap payload | `TestRolesKeepOneWriterAndKeepStaffFromCustomerSecrets`; the `staff-access` phase | Role definitions verified. End to end, staff are forbidden Secrets and every write but recoveries. Bootstrap stays refused, so no payload exists to read | -| A tenant cannot trigger an operation on hardware it does not hold (a review request beside #174's list) | `TestAdmissionPreconditions`; the `tenant-isolation` phase | End to end: while consumer A holds the Device, consumer B's project serves no Device API, the allocator refuses to install for B, and an installation the Metal provider names for B's unheld allocation is refused for `HolderMismatch`, with the fence, the journal and the BMC audit unchanged and nothing delivered | -| Importing a Device sends nothing and makes no capacity Available | `TestImportedDeviceGetsUnverifiedCustodyAndSendsNothing`; the `import-inert` phase | End to end: no operation, assignment, Job, journal entry or BMC effect. The capacity projector is not wired, so the run's fixture writes capacity status itself | +| A commissioning times out and a later one settles the hold | `TestLifecycle`, `TestRecovery`, with the test-only kind and `DeviceWipe` | Deferred: commissioning is out of scope. The phases below run the same hold and settle mechanism for an installation and a wipe | +| A staff operation targets an allocated, releasing or unsettleable held server and is refused, nothing sent | `TestAdmissionPreconditions`, `TestRecovery`; the `deadline-hold` phase | Envtest verified for all three. The phase runs one of them: a `DeviceRecovery` naming the held installation at the wrong fence, on a releasing Device, must be refused for `HoldMismatch` with custody unchanged and nothing sent | +| A worker passes its deadline; `OutcomeUnknown`; settling waits for the worker to stop | `TestLifecycle`, `TestRecovery`, `TestAWorkerStoppedAtItsDeadlineClosesItsAdmission`; the `deadline-hold` and `deadline-settled` phases | The phases check that the installation ends `OutcomeUnknown` with `DeadlineExceeded`, that its worker Pods stopped, and that the settling wipe is admitted only after the worker stopped | +| A delayed worker's step after a newer admission is refused by the journal | `TestTwoWorkersOnOneDevice`, `TestANewerFenceStopsTheOlderWorker`, `TestStoreRefusesOlderFencesAndSurvivesARestart`; the `delivery-faults` phase | Unit verified. The phase checks that an assignment below the stored fence fails its Job before any effect, with nothing sent | +| A TLS pin mismatch or an identity mismatch sends nothing | `TestPinMismatchSendsNothing`, `TestIdentityMismatchSendsNothing`; the `redfish-discovery-faults` phase | Unit verified against TLS servers. The Redfish run's phase checks that a key other than the pin reaches no request, and that a swapped or unknown identity sends only reads | +| Custody deleted and restored stays unallocatable until rebuilt with a higher fence | `TestRebuild`; the `rebuild` phase | Envtest verified. The phase checks that custody is rebuilt `Unverified` while the site cannot report, that a new Machine finds no capacity and records no allocation, and that custody is then `Verified` above the site's fence | +| A Machine deleted during installation; release waits; a wipe settles the install hold | `TestLifecycle`, `TestRecovery`; the `machine-delete`, `deadline-hold` and `deadline-settled` phases | Envtest verified. The phases check that release holds the Device with the installation active and no wipe, that the wipe then settles the hold, and that the Machine is gone | +| No staff role can read a bootstrap payload | `TestRolesKeepOneWriterAndKeepStaffFromCustomerSecrets`; the `staff-access` phase | Role definitions verified. The phase checks that staff are forbidden Secrets and every write but recoveries. Bootstrap stays refused, so no payload exists to read | +| A tenant cannot trigger an operation on hardware it does not hold (a review request beside #174's list) | `TestAdmissionPreconditions`; the `tenant-isolation` phase | Envtest verified. While consumer A holds the Device, the phase checks that consumer B's project serves no Device API, that the allocator refuses to install for B because B has no active allocation, and that an installation the Metal provider names for B's unheld allocation is refused for `HolderMismatch`, with the fence unchanged, nothing delivered and nothing sent | +| Importing a Device sends nothing and makes no capacity Available | `TestImportedDeviceGetsUnverifiedCustodyAndSendsNothing`; the `import-inert` phase | Envtest verified. The phase checks that no operation, assignment, Job, journal entry or, in the Redfish run, BMC effect exists. The capacity projector is not wired, so the run's fixture writes capacity status itself | The emulator lab cannot cover these: From d80acf0ab7b86504bbb20b8d39156d588f3ac00b Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 25 Nov 2026 12:48:41 -0600 Subject: [PATCH 11/16] fix(multiplane): Never record an interrupted run as passed A run that received TERM printed RESULT passed and exited 0: run.sh trapped only EXIT, so its result saw the last command's status, and the result took exit 0 alone as a pass. The phase it was in kept running after the run had gone. The run now traps TERM, INT and HUP, signals every phase it started, and records interrupted with the phase it was in and a nonzero exit. A phase stops its own command and records itself interrupted. Phases and acceptance scripts run in the background and are waited for, so a signal is handled at once. Exit 0 counts as passed only when run.sh wrote its completion marker on its last line; a preflight-only run records preflight-passed. summary.json, written before the secret scan and teardown, records evidence-verified instead of passed. test-interrupt.py runs the real run.sh with fake tools, interrupts it mid-phase with each signal, and checks the RESULT line, result.json, the exit code and that the phase's command stopped. It failed on every check before this change. Co-Authored-By: Claude Opus 5.5 --- docs/operations/multiplane.md | 13 ++- hack/multiplane/evidence.py | 4 +- hack/multiplane/harness.py | 121 +++++++++++++++++--------- hack/multiplane/run.sh | 44 ++++++++-- hack/multiplane/teardown.sh | 9 +- hack/multiplane/test-harness.sh | 10 ++- hack/multiplane/test-interrupt.py | 135 ++++++++++++++++++++++++++++++ 7 files changed, 279 insertions(+), 57 deletions(-) create mode 100644 hack/multiplane/test-interrupt.py diff --git a/docs/operations/multiplane.md b/docs/operations/multiplane.md index 01a97906..da9997f3 100644 --- a/docs/operations/multiplane.md +++ b/docs/operations/multiplane.md @@ -121,12 +121,19 @@ Exit codes and `evidence/result.json` status: | Exit | Status | Meaning | Resources | | --- | --- | --- | --- | -| 0 | `passed` | Every phase and evidence assertion passed | Owned containers, clusters and image tag deleted; private credentials removed | +| 0 | `passed` | Every phase and evidence assertion passed, and the run reached its last line | Owned containers, clusters and image tag deleted; private credentials removed | +| 0 | `preflight-passed` | `--preflight-only`: every prerequisite is present; no acceptance ran | None created | | 1 | `failed` | A phase or assertion failed | Owned containers stopped, state retained, custody Unknown | | 2 | `preflight-failed` | A local prerequisite is missing | None created | | 3 | `blocked` | Implementation readiness gate failed | None created | | 4 | `timeout` | A bounded phase expired; its process group was terminated | Stopped and retained as for 1 | | 64 | `usage` | Invalid option | None created | +| 129, 130, 143 | `interrupted` | The run received HUP, INT or TERM. It stops every phase it started, records the phase it was in as `interrupted`, and names it as the failed phase | Stopped and retained as for 1 | +| 1 | `interrupted` | The run exited 0 before its last line, so nothing proves it finished | Stopped and retained as for 1 | + +Only a run that reaches its last line writes the completion marker the result +requires for `passed`. A result recorded as `passed` before this rule, by a run +that was interrupted, proves nothing. The full run uses three kind nodes (platform, hub, cell), a registry, Flux on each node, three small Milo/etcd pairs, Karmada and kro. Node caps are @@ -155,7 +162,7 @@ mode-0700 `/tmp/fleet-multiplane.*` state directory (override the parent with | `result.json` | Final status, exit code, failed phase, every phase record, retained containers, custody statement | | `phases.jsonl` | One record per bounded phase: name, status, exit code, bound, duration | | `preflight.json` | Each prerequisite and readiness check | -| `summary.json` | Pass only: allowlisted scenario evidence, operations, digests, receipt hashes, qualification flags | +| `summary.json` | Written when the evidence checks pass, with `acceptance: evidence-verified`: allowlisted scenario evidence, operations, digests, receipt hashes, qualification flags. It does not say the run passed; `result.json` does | | `flux-verify.json`, `flux-initial.json`, `flux-rbac-restore.json`, `flux-drift.json`, `flux-graph-lifecycle.json`, `flux-restart.json`, `flux-fail-closed.json`, `flux-retention.json`, `flux-final.json`, `flux-ownership-final.json`, `flux-reconciles.json`, `flux-partition.json`, `flux-reflection-suspension.json`, `gitops-r.SHA256SUMS` | Flux source revisions and digests, Ready/generation/revision of every Kustomization and HelmRelease, inventories and single-writer ownership, and each GitOps scenario ([details](gitops.md#acceptance-coverage)) | | `kro-rbac.json` | kro's allowed and denied verbs and each admission probe's outcome | | `custody-crd-rules.json` | Each forbidden custody or operation write and whether the provider project API refused it, and that the CRDs were removed | @@ -387,7 +394,7 @@ hack/multiplane/teardown.sh /tmp/fleet-multiplane.REPLACE --discard-unknown ``` `teardown.sh` without `--discard-unknown` refuses unless `summary.json` records -a pass. `--discard-unknown` is an explicit human decision after inspection: it +verified acceptance evidence. `--discard-unknown` is an explicit human decision after inspection: it deletes the same exact-prefix resources, keeps every private file, and records in `teardown.json` that it is not release evidence. Neither script touches other prefixes. The original limit of 128 inotify instances was insufficient for this diff --git a/hack/multiplane/evidence.py b/hack/multiplane/evidence.py index f5f25eec..8f285242 100755 --- a/hack/multiplane/evidence.py +++ b/hack/multiplane/evidence.py @@ -432,7 +432,9 @@ def network(block): failure_scenarios[name] = json.loads((ev / (name + '.json')).read_text()) summary = { - 'schemaVersion': 2, 'acceptance': 'passed', + # The evidence verified; the run is not finished. Only result.json, which + # run.sh writes last, records whether the run passed. + 'schemaVersion': 3, 'acceptance': 'evidence-verified', 'observedAt': datetime.datetime.now(datetime.timezone.utc).isoformat(), 'prefix': prefix, 'qualification': {'nativeMiloProjectAPIs': True, 'actualKarmadaDeliveryAndReflection': True, 'realLocalPXE': True, 'kubernetesJobExecution': True, 'actualKroController': True, 'fluxReconciledServices': True, diff --git a/hack/multiplane/harness.py b/hack/multiplane/harness.py index e3bde2ff..33f536e2 100755 --- a/hack/multiplane/harness.py +++ b/hack/multiplane/harness.py @@ -23,6 +23,15 @@ EXIT_PASSED, EXIT_FAILED, EXIT_PREFLIGHT, EXIT_BLOCKED, EXIT_TIMEOUT, EXIT_USAGE = 0, 1, 2, 3, 4, 64 STATUS_BY_EXIT = {EXIT_PASSED: 'passed', EXIT_FAILED: 'failed', EXIT_PREFLIGHT: 'preflight-failed', EXIT_BLOCKED: 'blocked', EXIT_TIMEOUT: 'timeout', EXIT_USAGE: 'usage'} +# A run or phase ended by a signal exits 128 plus the signal number. +INTERRUPT_SIGNALS = (signal.SIGTERM, signal.SIGINT, signal.SIGHUP) +# run.sh writes these markers as its last act, so exit 0 without one is an +# interrupted run, never a pass. +COMPLETED, PREFLIGHT_COMPLETED = 'completed', 'preflight-completed' + + +class Interrupted(Exception): + pass DEBIAN = 'debian:bookworm-slim@sha256:734a72b3d6142a71993b4bc580ca01d8ca687f77a2c422d96a961d3376b179bc' # Subcommands and errors the live harness depends on. A missing one blocks before any resource exists. REQUIRED_SOURCE_MARKERS = tuple('"%s"' % c for c in ('seed', 'allocate', 'admit-install', 'install', 'release', 'release-b', 'reuse', @@ -193,56 +202,77 @@ def phase(args): started = time.monotonic() record = {'name': args.name, 'startedAt': now(), 'timeoutSeconds': args.timeout} print('==> %s (bound %ss)' % (args.name, args.timeout), flush=True) + # A signal stops the phase's command and records the phase interrupted. + received = [] + + def on_signal(signum, _frame): + received.append(signum) + raise Interrupted() + for sig in INTERRUPT_SIGNALS: + signal.signal(sig, on_signal) + (state / 'current-phase').write_text(args.name + '\n') with open(log, 'ab') as out, open(state / 'phases.log', 'ab') as markers: p = subprocess.Popen(args.command, stdout=subprocess.PIPE, stderr=out, start_new_session=True) - deadline = started + args.timeout - timed_out = False - import selectors - sel = selectors.DefaultSelector() - os.set_blocking(p.stdout.fileno(), False) - sel.register(p.stdout, selectors.EVENT_READ) - eof = False - while True: - remaining = deadline - time.monotonic() - if remaining <= 0: - timed_out = True - break - if eof: - try: - p.wait(timeout=remaining) - except subprocess.TimeoutExpired: + try: + deadline = started + args.timeout + timed_out = False + import selectors + sel = selectors.DefaultSelector() + os.set_blocking(p.stdout.fileno(), False) + sel.register(p.stdout, selectors.EVENT_READ) + eof = False + while True: + remaining = deadline - time.monotonic() + if remaining <= 0: timed_out = True - break - if sel.select(timeout=min(remaining, 1.0)): - line = os.read(p.stdout.fileno(), 65536) - if not line: - sel.unregister(p.stdout) - eof = True - continue - out.write(line) - markers.write(line) - out.flush() - markers.flush() - if args.echo: - sys.stdout.write(''.join(' ' + l for l in line.decode(errors='replace').splitlines(True))) - sys.stdout.flush() - sel.close() - p.stdout.close() - if timed_out: + break + if eof: + try: + p.wait(timeout=remaining) + except subprocess.TimeoutExpired: + timed_out = True + break + if sel.select(timeout=min(remaining, 1.0)): + line = os.read(p.stdout.fileno(), 65536) + if not line: + sel.unregister(p.stdout) + eof = True + continue + out.write(line) + markers.write(line) + out.flush() + markers.flush() + if args.echo: + sys.stdout.write(''.join(' ' + l for l in line.decode(errors='replace').splitlines(True))) + sys.stdout.flush() + sel.close() + p.stdout.close() + if timed_out: + terminate(p) + code = p.wait(timeout=5) + except Interrupted: + for sig in INTERRUPT_SIGNALS: + signal.signal(sig, signal.SIG_IGN) terminate(p) - code = p.wait(timeout=5) + p.stdout.close() + code = 128 + received[0] record['durationSeconds'] = round(time.monotonic() - started, 1) record['finishedAt'] = now() - if timed_out: + if received: + record.update(status='interrupted', exitCode=code) + elif timed_out: record.update(status='timeout', exitCode=EXIT_TIMEOUT) else: record.update(status='passed' if code == 0 else 'blocked' if code == EXIT_BLOCKED else 'failed', exitCode=code) with open(evidence_dir(state) / 'phases.jsonl', 'a') as f: f.write(json.dumps(record, sort_keys=True) + '\n') + (state / 'current-phase').unlink(missing_ok=True) if record['status'] != 'passed': print('<== %s %s (exit %s); private log: %s' % (args.name, record['status'], record['exitCode'], log), flush=True) tail = log.read_bytes()[-1500:].decode(errors='replace') print('\n'.join(' ' + l for l in tail.splitlines()[-15:]), flush=True) + if received: + return code return EXIT_TIMEOUT if timed_out else (0 if code == 0 else EXIT_BLOCKED if code == EXIT_BLOCKED else EXIT_FAILED) @@ -463,18 +493,31 @@ def result(args): if prefix: code, out, _ = capture(['docker', 'ps', '-a', '--filter', 'name=^' + prefix + '-', '--format', '{{.Names}}\t{{.State}}'], 30) retained = [dict(zip(('name', 'state'), l.split('\t'))) for l in out.splitlines() if code == 0 and l.strip()] + code = args.exit_code + status = STATUS_BY_EXIT.get(code, 'interrupted' if code in [128 + s for s in INTERRUPT_SIGNALS] else 'failed') + # Exit 0 is a pass only if run.sh reached its last line. + if code == EXIT_PASSED: + if (state / COMPLETED).exists(): + status = 'passed' + elif (state / PREFLIGHT_COMPLETED).exists(): + status = 'preflight-passed' + else: + status, code = 'interrupted', EXIT_FAILED failed = next((p for p in phases if p['status'] != 'passed'), None) - status = STATUS_BY_EXIT.get(args.exit_code, 'failed') + running = state / 'current-phase' + if failed is None and status != 'passed' and running.exists(): + failed = {'name': running.read_text().strip()} summary = ev / 'summary.json' - value = {'schemaVersion': 1, 'observedAt': now(), 'status': status, 'exitCode': args.exit_code, 'prefix': prefix, + value = {'schemaVersion': 1, 'observedAt': now(), 'status': status, 'exitCode': code, 'prefix': prefix, 'failedPhase': failed['name'] if failed else None, 'phases': phases, 'retainedContainers': retained, 'stateDirectory': str(state), 'evidenceDirectory': str(ev), 'summary': 'summary.json' if summary.exists() and status == 'passed' else None, 'custody': 'released and verified' if status == 'passed' else 'Unknown: inspect private state before any cleanup', 'productionAuthority': False} write_json(ev / 'result.json', value) - print('RESULT %s exit=%s evidence=%s' % (status, args.exit_code, ev / 'result.json')) - return 0 + print('RESULT %s exit=%s evidence=%s' % (status, code, ev / 'result.json')) + # run.sh exits with this code, so only a completed run exits 0. + return code def main(): diff --git a/hack/multiplane/run.sh b/hack/multiplane/run.sh index 46e1e226..428de97d 100755 --- a/hack/multiplane/run.sh +++ b/hack/multiplane/run.sh @@ -4,7 +4,8 @@ # and retain exact state as Unknown custody. See docs/operations/multiplane.md. # # Exit codes: 0 passed, 1 failed, 2 preflight failed, 3 blocked by implementation -# readiness, 4 bounded wait expired, 64 usage. +# readiness, 4 bounded wait expired, 64 usage, 128 plus the signal number when +# interrupted. Only a run that reached its last line records passed. set -euo pipefail cd "$(dirname "$0")/../.." umask 077 @@ -42,14 +43,39 @@ finish() { echo "Execution and custody are Unknown. Retained private state: $state. Discard only after inspection: hack/multiplane/teardown.sh $state --discard-unknown" fi [[ $code -eq 0 ]] || "${harness[@]}" scan --state "$state" >/dev/null 2>&1 || true - "${harness[@]}" result --state "$state" --exit-code "$code" - exit "$code" + # The result decides the exit code: exit 0 without the completion marker is + # an interrupted run. + "${harness[@]}" result --state "$state" --exit-code "$code" && exit 0 + exit $? +} +# Every descendant. Parents are signalled before their children, so a phase +# stops its own command and records the interruption; the children are +# listed first, so none is missed when its parent exits. +stop_tree() { + local child children + children=$(pgrep -P "$1" || true) + [[ $1 == "$$" ]] || kill -TERM "$1" 2>/dev/null || true + for child in $children; do stop_tree "$child"; done +} +interrupt() { + trap '' TERM INT HUP + stop_tree $$ + wait || true + finish "$1" } trap 'finish $?' EXIT -ph() { "${harness[@]}" phase --state "$state" --name "$1" --timeout "$2" -- "${@:3}"; } +trap 'interrupt 143' TERM +trap 'interrupt 130' INT +trap 'interrupt 129' HUP +# Phases and acceptance scripts run in the background and are waited for, so +# a signal reaches the traps at once rather than after the current phase. +ph() { "${harness[@]}" phase --state "$state" --name "$1" --timeout "$2" -- "${@:3}" & wait $!; } -"${harness[@]}" preflight --state "$state" --root . "${bootstrap[@]}" "${skip_tests[@]}" -[[ $preflight_only == 0 ]] || exit 0 +"${harness[@]}" preflight --state "$state" --root . "${bootstrap[@]}" "${skip_tests[@]}" & wait $! +if [[ $preflight_only == 1 ]]; then + : > "$state/preflight-completed" + exit 0 +fi prefix="fleet-mp-$(openssl rand -hex 4)" printf '%s\n' "$prefix" > "$state/prefix" @@ -111,9 +137,9 @@ ph flux-site 1200 "${flux[@]}" publish "$state" --revision 2 --site off --purpos ph site-install 900 bash hack/multiplane/site.sh check "$state" ph flux-verify 300 "${flux[@]}" verify "$state" if [[ $provider == redfish ]]; then - bash hack/multiplane/acceptance-redfish.sh "$state" + bash hack/multiplane/acceptance-redfish.sh "$state" & wait $! else - bash hack/multiplane/acceptance.sh "$state" + bash hack/multiplane/acceptance.sh "$state" & wait $! fi ph secret-scan 120 "${harness[@]}" scan --state "$state" if [[ $keep == 1 ]]; then @@ -121,4 +147,6 @@ if [[ $keep == 1 ]]; then else ph teardown 900 bash hack/multiplane/teardown.sh "$state" fi +# The last act of a completed run: only now may the result record passed. +: > "$state/completed" printf 'Local topology/PXE acceptance (%s provider) passed. Production authority and physical hardware remain unqualified.\n' "$provider" diff --git a/hack/multiplane/teardown.sh b/hack/multiplane/teardown.sh index 8d2ec172..5b46126e 100755 --- a/hack/multiplane/teardown.sh +++ b/hack/multiplane/teardown.sh @@ -1,7 +1,8 @@ #!/usr/bin/env bash # Delete only this run's exact containers, kind clusters and provider image tag. -# Default: only after evidence/summary.json records passed acceptance (verified -# cleanup and release), then remove private credentials and keep evidence. +# Default: only after evidence/summary.json records verified acceptance evidence +# (verified cleanup and release), then remove private credentials and keep +# evidence. Whether the run passed is recorded only in evidence/result.json. # --discard-unknown is an explicit human decision to abandon an Unknown run; it # deletes the same exact resources, keeps all private state, and never claims release. set -euo pipefail @@ -16,8 +17,8 @@ prefix=$(cat "$state/prefix") bash hack/multiplane/coordinator.sh stop "$state" >/dev/null export 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")!="passed")' "$state/evidence/summary.json" 2>/dev/null || { - echo 'No passed acceptance summary; refusing teardown. Use --discard-unknown only after inspection.' >&2; exit 1; } + python3 -c 'import json,sys; sys.exit(json.load(open(sys.argv[1])).get("acceptance")!="evidence-verified")' "$state/evidence/summary.json" 2>/dev/null || { + echo 'No verified acceptance evidence; refusing teardown. Use --discard-unknown only after inspection.' >&2; exit 1; } fi hub="$prefix-hub-control-plane" if docker inspect "$hub" >/dev/null 2>&1; then diff --git a/hack/multiplane/test-harness.sh b/hack/multiplane/test-harness.sh index 27c22a56..1c4522f7 100755 --- a/hack/multiplane/test-harness.sh +++ b/hack/multiplane/test-harness.sh @@ -7,6 +7,7 @@ for f in "$root"/hack/multiplane/*.sh; do bash -n "$f"; done python3 -m py_compile "$root"/hack/multiplane/*.py python3 "$root"/hack/multiplane/test-k8s-evidence.py "$root" python3 "$root"/hack/multiplane/test-redfish.py "$root" +python3 "$root"/hack/multiplane/test-interrupt.py "$root" python3 -m py_compile "$root"/hack/redfish-lab/*.py exec python3 - "$root" <<'PY' import json, os, pathlib, re, stat, subprocess, sys, tempfile, time @@ -160,9 +161,11 @@ with tempfile.TemporaryDirectory() as tmp: check('scan detects ' + secret[0], run(['scan', '--state', str(s)]).returncode == 1) check('scan redacts ' + secret[0], secret not in (s / 'evidence/leak.json').read_text()) - # Result: status mapping and retained owned containers. + # Result: status mapping and retained owned containers. Exit 0 is passed + # only with the completion marker run.sh writes last. s = state(); (s / 'prefix').write_text('fleet-mp-0000aaaa\n') - for code, status in ((0, 'passed'), (1, 'failed'), (2, 'preflight-failed'), (3, 'blocked'), (4, 'timeout')): + (s / 'completed').write_text('') + for code, status in ((0, 'passed'), (1, 'failed'), (2, 'preflight-failed'), (3, 'blocked'), (4, 'timeout'), (143, 'interrupted'), (130, 'interrupted')): run(['result', '--state', str(s), '--exit-code', str(code)]) res = json.loads((s / 'evidence/result.json').read_text()) check('result ' + status, res['status'] == status and res['productionAuthority'] is False) @@ -177,6 +180,9 @@ with tempfile.TemporaryDirectory() as tmp: (s / 'evidence/summary.json').write_text('{"acceptance":"failed"}') r = subprocess.run(['bash', str(root / 'hack/multiplane/teardown.sh'), str(s)], text=True, capture_output=True, env=base) check('teardown refuses failed summary', r.returncode == 1) + (s / 'evidence/summary.json').write_text('{"acceptance":"passed"}') + r = subprocess.run(['bash', str(root / 'hack/multiplane/teardown.sh'), str(s)], text=True, capture_output=True, env=base) + check('teardown refuses a summary that claims the run passed', r.returncode == 1) check('teardown refusal is effect-free', trace.read_text() == '') (s / 'prefix').write_text('other-prefix\n') r = subprocess.run(['bash', str(root / 'hack/multiplane/teardown.sh'), str(s), '--discard-unknown'], text=True, capture_output=True, env=base) diff --git a/hack/multiplane/test-interrupt.py b/hack/multiplane/test-interrupt.py new file mode 100644 index 00000000..cf0b41ab --- /dev/null +++ b/hack/multiplane/test-interrupt.py @@ -0,0 +1,135 @@ +#!/usr/bin/env python3 +"""An interrupted run never reports or records passed. + +Runs the real run.sh in a scratch copy of the repository, with the real +harness except for its preflight, which needs a container runtime, and a fake +`go` that keeps the first phase running. Then it interrupts the run mid-phase +and checks the RESULT line, evidence/result.json and the exit code. It also +checks the other exits that end with code 0: a preflight-only run, and a run +that exits 0 before it completed. +""" +import json +import os +import pathlib +import shutil +import signal +import subprocess +import sys +import tempfile +import time + +root = pathlib.Path(sys.argv[1]).resolve() +failures = [] + + +def check(name, condition, detail=''): + if not condition: + failures.append(name + (': ' + detail if detail else '')) + + +SHIM = '''import importlib.util, sys +spec = importlib.util.spec_from_file_location('harness', %r) +harness = importlib.util.module_from_spec(spec) +sys.modules['harness'] = harness +spec.loader.exec_module(harness) +# The preflight needs a container runtime; everything else is the real harness. +harness.preflight = lambda args: 0 +sys.exit(harness.main()) +''' + + +def scratch(tmp): + """A repository copy holding run.sh, a harness shim, and fake tools.""" + repo = tmp / 'repo' + (repo / 'hack/multiplane').mkdir(parents=True) + shutil.copy(root / 'hack/multiplane/run.sh', repo / 'hack/multiplane/run.sh') + (repo / 'hack/multiplane/harness.py').write_text(SHIM % str(root / 'hack/multiplane/harness.py')) + (repo / 'hack/multiplane/stop.sh').write_text('#!/bin/sh\nexit 0\n') + for name in ('go.mod', 'go.sum'): + (repo / name).write_text('') + bin_dir = tmp / 'bin' + bin_dir.mkdir() + # go keeps the build phase running; docker reports no containers. + # The marker names this scratch copy, so the leftover check sees only + # this run's phase command. + for tool, body in (('go', 'exec python3 -c "import time; time.sleep(120)" %s' % tmp.name), ('docker', 'exit 0')): + path = bin_dir / tool + path.write_text('#!/bin/sh\n' + body + '\n') + path.chmod(0o755) + env = dict(os.environ, PATH=str(bin_dir) + os.pathsep + os.environ['PATH'], FLEET_MULTIPLANE_STATE_ROOT=str(tmp)) + return repo, env + + +def result_of(tmp): + results = list(tmp.glob('fleet-multiplane.*/evidence/result.json')) + return json.loads(results[0].read_text()) if len(results) == 1 else None + + +def interrupted(sig): + with tempfile.TemporaryDirectory() as t: + tmp = pathlib.Path(t) + repo, env = scratch(tmp) + log = open(tmp / 'run.out', 'w') + p = subprocess.Popen(['bash', str(repo / 'hack/multiplane/run.sh')], cwd=repo, env=env, text=True, + stdout=log, stderr=subprocess.STDOUT, start_new_session=True) + deadline = time.monotonic() + 60 + while time.monotonic() < deadline and not list(tmp.glob('fleet-multiplane.*/logs/build.log')): + time.sleep(0.2) + check(sig.name + ': the build phase started', bool(list(tmp.glob('fleet-multiplane.*/logs/build.log')))) + time.sleep(1) + # Signal only the run itself, as an operator would. It must stop its + # phase promptly and record the interruption. + p.send_signal(sig) + try: + p.wait(timeout=60) + except subprocess.TimeoutExpired: + check(sig.name + ': the run stopped within 60 seconds of the signal', False) + finally: + time.sleep(1) + leftover = subprocess.run(['pgrep', '-f', r'sleep\(120\) %s' % tmp.name], capture_output=True, text=True).stdout.split() + try: + os.killpg(p.pid, signal.SIGKILL) + except ProcessLookupError: + pass + log.close() + check(sig.name + ': the phase command was stopped', not leftover, str(leftover)) + out = (tmp / 'run.out').read_text() + lines = [l for l in out.splitlines() if l.startswith('RESULT ')] + result = result_of(tmp) + check(sig.name + ': nonzero exit', p.returncode != 0, str(p.returncode)) + check(sig.name + ': RESULT line is not passed', bool(lines) and not lines[-1].startswith('RESULT passed'), str(lines)) + check(sig.name + ': result.json is not passed', result is not None and result['status'] != 'passed', str(result and result['status'])) + check(sig.name + ': result.json names the interrupted phase', result is not None and result.get('failedPhase') == 'build', + str(result and result.get('failedPhase'))) + check(sig.name + ': result.json exit code is nonzero', result is not None and result['exitCode'] != 0, str(result and result['exitCode'])) + + +for sig in (signal.SIGTERM, signal.SIGINT, signal.SIGHUP): + interrupted(sig) + +# A preflight-only run that succeeds is not an acceptance pass. +with tempfile.TemporaryDirectory() as t: + tmp = pathlib.Path(t) + repo, env = scratch(tmp) + r = subprocess.run(['bash', str(repo / 'hack/multiplane/run.sh'), '--preflight-only'], cwd=repo, env=env, text=True, capture_output=True, timeout=120) + result = result_of(tmp) + check('preflight-only: exit 0', r.returncode == 0, str(r.returncode) + r.stdout[-300:] + r.stderr[-300:]) + check('preflight-only: not recorded as passed', result is not None and result['status'] == 'preflight-passed', str(result and result['status'])) + +# An exit 0 without the completion marker is never passed. +with tempfile.TemporaryDirectory() as t: + state = pathlib.Path(t) + (state / 'evidence').mkdir() + env = dict(os.environ, PATH=str(state) + os.pathsep + os.environ['PATH']) + docker = state / 'docker' + docker.write_text('#!/bin/sh\nexit 0\n') + docker.chmod(0o755) + r = subprocess.run([sys.executable, str(root / 'hack/multiplane/harness.py'), 'result', '--state', str(state), '--exit-code', '0'], env=env, text=True, capture_output=True) + result = json.loads((state / 'evidence/result.json').read_text()) + check('incomplete exit 0: not passed', result['status'] != 'passed' and not r.stdout.startswith('RESULT passed'), result['status']) + check('incomplete exit 0: nonzero', r.returncode != 0 and result['exitCode'] != 0, str(r.returncode)) + +if failures: + print('FAIL interrupt tests:\n ' + '\n '.join(failures)) + sys.exit(1) +print('PASS interrupt tests') From 49f543157017da7972bbf361f2c692b7522c5248 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 25 Nov 2026 21:40:07 -0600 Subject: [PATCH 12/16] test(multiplane): Prove the deadline hook denied a boot The deadline phase passed whenever no installer was served, so it would also pass if firmware never asked for a boot. The lab boot hook now counts each request it denies, and deadline-hold requires at least one. A repository-wide test now fails if any file outside the docs, the acceptance binary and the lab steps names the hook, or the boot service sets it more than once. The tenant-isolation phase no longer runs the harness's own install helper, which proved no guard. It claims only what custody admission proves: an installation for B's unheld allocation is refused for HolderMismatch with the fence unchanged. Co-Authored-By: Claude Opus 5.5 --- cmd/fleet-multiplane/withhold.go | 32 +++++++++++++--- cmd/fleet-multiplane/withhold_test.go | 53 +++++++++++++++++++++++++++ docs/development/device-custody.md | 12 ++++-- docs/operations/multiplane.md | 7 ++-- hack/multiplane/steps.sh | 5 +++ internal/multiplane/scenarios.go | 14 +++---- 6 files changed, 103 insertions(+), 20 deletions(-) diff --git a/cmd/fleet-multiplane/withhold.go b/cmd/fleet-multiplane/withhold.go index 8b062c39..0d4a7428 100644 --- a/cmd/fleet-multiplane/withhold.go +++ b/cmd/fleet-multiplane/withhold.go @@ -2,8 +2,10 @@ package main import ( "errors" + "fmt" "net/http" "os" + "strings" "time" ) @@ -17,8 +19,9 @@ const labWithholdEnv = "FLEET_LAB_BOOT_WITHHOLD" // admitted installation's firmware never receives its installer and the // worker waits for a receipt until its deadline. The listener stays up, so // the boot service stays Ready and kro still creates workers. It records no -// delivery evidence for a withheld request. Without the variable it returns -// the handler unchanged. +// delivery evidence for a withheld request, but counts each denial in a file +// beside the arm file, so the lab can prove the hook withheld a boot. +// Without the variable it returns the handler unchanged. func withhold(next http.Handler) http.Handler { path := os.Getenv(labWithholdEnv) if path == "" { @@ -26,6 +29,11 @@ func withhold(next http.Handler) http.Handler { } return http.HandlerFunc(func(w http.ResponseWriter, request *http.Request) { if _, err := os.Stat(path); err == nil { + // The count is evidence only; a failed write still denies. + if f, err := os.OpenFile(path+deniedSuffix, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0o600); err == nil { + _, _ = f.WriteString("denied\n") + _ = f.Close() + } w.Header().Set("Cache-Control", "no-store") http.Error(w, "boot denied", http.StatusForbidden) return @@ -34,8 +42,12 @@ func withhold(next http.Handler) http.Handler { }) } -// armWithhold creates or removes the arm file. It runs in the boot -// service's container, through the cell API. +// deniedSuffix names the file beside the arm file that counts denials. +const deniedSuffix = ".denied" + +// armWithhold creates or removes the arm file, and reports how many boots +// the hook denied since it was last armed. It runs in the boot service's +// container, through the cell API. func armWithhold(action string) error { path := os.Getenv(labWithholdEnv) if path == "" { @@ -43,14 +55,24 @@ func armWithhold(action string) error { } switch action { case "arm": + if err := os.Remove(path + deniedSuffix); err != nil && !os.IsNotExist(err) { + return err + } return os.WriteFile(path, nil, 0o600) + case "denied": + data, err := os.ReadFile(path + deniedSuffix) + if err != nil && !os.IsNotExist(err) { + return err + } + fmt.Println(strings.Count(string(data), "\n")) + return nil case "clear": if err := os.Remove(path); err != nil && !os.IsNotExist(err) { return err } return nil } - return errors.New("boot-withhold takes arm or clear") + return errors.New("boot-withhold takes arm, clear or denied") } // serveBoot listens on :8080 with the same bounds as the site's boot diff --git a/cmd/fleet-multiplane/withhold_test.go b/cmd/fleet-multiplane/withhold_test.go index a6b38963..cf6e9c83 100644 --- a/cmd/fleet-multiplane/withhold_test.go +++ b/cmd/fleet-multiplane/withhold_test.go @@ -47,6 +47,16 @@ func TestAnArmedWithholdDeniesEveryBootRequest(t *testing.T) { t.Fatalf("an armed hook served %s: %d", p, code) } } + if data, err := os.ReadFile(path + deniedSuffix); err != nil || strings.Count(string(data), "\n") != len(paths) { + t.Fatalf("denials counted = %q, %v, want %d", data, err, len(paths)) + } + // Arming again starts a new count. + if err := armWithhold("arm"); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(path + deniedSuffix); !os.IsNotExist(err) { + t.Fatalf("arming kept the earlier count: %v", err) + } if err := armWithhold("clear"); err != nil { t.Fatal(err) } @@ -141,3 +151,46 @@ func mustAbs(t *testing.T, path string) string { } return abs } + +// TestNothingElseInTheRepositorySetsTheWithholdHook scans every tracked +// kind of file outside the docs: only this package, the lab boot service's +// one env entry, and the lab steps that arm and clear it may name the hook. +func TestNothingElseInTheRepositorySetsTheWithholdHook(t *testing.T) { + root := mustAbs(t, filepath.Join("..", "..")) + allowed := map[string]int{ + filepath.Join("config", "site", "services", "services.yaml"): 1, + filepath.Join("hack", "multiplane", "steps.sh"): -1, + } + err := filepath.WalkDir(root, func(path string, entry fs.DirEntry, err error) error { + if err != nil { + return err + } + rel, _ := filepath.Rel(root, path) + if entry.IsDir() { + switch rel { + case ".git", "docs", filepath.Join("cmd", "fleet-multiplane"): + return filepath.SkipDir + } + return nil + } + if strings.HasSuffix(rel, ".md") { + return nil + } + data, err := os.ReadFile(path) + if err != nil { + return err + } + count := strings.Count(string(data), labWithholdEnv) + want, ok := allowed[rel] + switch { + case !ok && (count > 0 || strings.Contains(string(data), "boot-withhold")): + t.Errorf("%s names the lab boot hook", rel) + case ok && want >= 0 && count != want: + t.Errorf("%s sets the lab boot hook %d times, want %d", rel, count, want) + } + return nil + }) + if err != nil { + t.Fatal(err) + } +} diff --git a/docs/development/device-custody.md b/docs/development/device-custody.md index c97897c0..a17f169b 100644 --- a/docs/development/device-custody.md +++ b/docs/development/device-custody.md @@ -15,7 +15,7 @@ marked **implemented and verified**, **implemented and inert**, or | A: control-plane foundation | API types and CRDs for `DeviceCustody`, `DeviceInstallation`, `DeviceWipe` and `DeviceRecovery`; CEL rules; IAM resources and roles; the creator webhook; the kind registry and admission rule table; the coordinator's custody reconciler, admission, results, recovery, rebuild and retention; the capacity projector | **Implemented and verified**, except the capacity projector, which is **implemented and inert**. Verified with unit tests and with tests against a real API server. Increment C wires the rest into every mode. | | B: site execution | Per-Device fence store and journal, older-worker stop with a confirmation, deadlines, fenced typed results, per-Device credentials, pinned TLS, identity checks, the handoff payload, the site fence report, and the Redfish install and wipe phases behind the worker contract | **Implemented and verified.** Unit tested, including against TLS BMC stubs. Increment C delivers to it. | | C: cutover | MachineAllocations and quota claims named from the Machine UID, allocation and release on custody, the delivery loop, the simulator, local VM and Redfish sites, the creator webhook in the production Milo root, the manager's power projector, and deletion of the Secret-backed records and executors. See [Cutover](#cutover-increment-c). | **Implemented.** Verified by unit tests, tests against a real API server, the standalone smoke (`task standalone:test`), and both multi-plane runs, local VM and Redfish. | -| D: end-to-end failure scenarios | Harness phases and evidence checks for the #174 acceptance tests, and the two site fixes they found. See [Failure scenarios](#failure-scenarios-increment-d). | **Implemented.** Unit tested. Verification of both multi-plane runs is pending. | +| D: end-to-end failure scenarios | Harness phases and evidence checks for the #174 acceptance tests, and the two site fixes they found. See [Failure scenarios](#failure-scenarios-increment-d). | **Implemented and verified** by unit tests and both multi-plane runs, local VM and Redfish. | ## What Increment A adds @@ -418,9 +418,13 @@ The shorter installation deadline is a flag of the acceptance binary's coordinator, and only the deadline scenario sets it. The boot hook lives in the acceptance binary's boot service, and only the local multi-plane site's Flux source configures it, which no production root may reference. -`TestOnlyTheLabSiteSourceSetsTheWithholdHook` fails if any other -configuration sets it, any production root references that source, or any -other package names it. The emulator lab's limits +`TestOnlyTheLabSiteSourceSetsTheWithholdHook` fails if any production root +references that source or any other package names it, and +`TestNothingElseInTheRepositorySetsTheWithholdHook` fails if any file outside +the docs, the acceptance binary and the lab steps names it, or the boot +service sets it more than once. The hook counts each boot it denies, and the +`deadline-hold` phase requires at least one denial, so a boot that never +arrived for another reason does not pass as withheld. The emulator lab's limits are listed in the coverage inventory. ## Implementation decisions diff --git a/docs/operations/multiplane.md b/docs/operations/multiplane.md index da9997f3..327deaf2 100644 --- a/docs/operations/multiplane.md +++ b/docs/operations/multiplane.md @@ -239,8 +239,8 @@ The phases are then: Pending/InsufficientCapacity for B, and requires custody to name the one MachineAllocation, A's. `tenant-isolation` then requires that B, which holds nothing, cannot reach the server: its project serves no Device API, - the allocator refuses to install for it, and an installation named for its - unheld allocation is refused for `HolderMismatch`. The fence, the site + and an installation the Metal provider names for its unheld allocation is + refused by custody admission for `HolderMismatch`. The fence, the site store and, in Redfish mode, the BMC audit stay unchanged, and nothing is delivered. 3. **Admission before effects.** The coordinator admits the `DeviceInstallation` @@ -346,7 +346,8 @@ The phases are then: installer boot is requested but never served. `machine-delete` has the customer delete B's Machine mid-install. One release pass must leave custody holding the Device for release with the installation still active - and no wipe. `deadline-hold` requires the installation to end + and no wipe. `deadline-hold` requires the hook to have denied at least + one boot request, and the installation to end `OutcomeUnknown` with `DeadlineExceeded`, custody to hold it at its fence, and its worker to have stopped. A staff `DeviceRecovery` naming the held operation at the wrong fence must be refused for `HoldMismatch`, with custody, the site diff --git a/hack/multiplane/steps.sh b/hack/multiplane/steps.sh index 8bd52f43..4ab95f8c 100755 --- a/hack/multiplane/steps.sh +++ b/hack/multiplane/steps.sh @@ -147,9 +147,14 @@ case "$step" in "$host" recovery-mismatch --config "$state/acceptance.json" [[ $before == "$(journal_digest)" ]] || { echo 'site store changed for a refused recovery' >&2; exit 1; } audit_unchanged + # The hook withheld the installation's boot: it counted at least one + # denial since it was armed. + denied=$(site exec deploy/fleet-site-boot -c boot -- fleet-multiplane boot-withhold denied) + [[ $denied =~ ^[0-9]+$ ]] && (( denied > 0 )) || { echo "the lab boot hook denied no boot request: ${denied:-none}" >&2; exit 1; } # The release's wipe boots normally. trap - ERR site exec deploy/fleet-site-boot -c boot -- fleet-multiplane boot-withhold clear + printf 'deadline-hold: the lab boot hook denied %s boot requests\n' "$denied" ;; deadline-settled) scenario deadline-settled "$state" diff --git a/internal/multiplane/scenarios.go b/internal/multiplane/scenarios.go index 6373a81b..0933c7ad 100644 --- a/internal/multiplane/scenarios.go +++ b/internal/multiplane/scenarios.go @@ -139,10 +139,11 @@ func (r *Runner) ProbeUnallocatable(ctx context.Context) error { } // TenantIsolation runs while consumer A holds the Device and consumer B -// holds nothing. B's project has no Device API at all; the allocator refuses -// to install for B; and an installation the Metal provider names for B's -// allocation, which never held the Device, is refused before anything is -// delivered, with custody's fence unchanged. +// holds nothing. B's project serves no Device API, and an installation the +// Metal provider names for B's allocation, which never held the Device, is +// refused by custody admission for HolderMismatch before anything is +// delivered, with custody's fence unchanged. The holder check is the guard +// this proves. func (r *Runner) TenantIsolation(ctx context.Context) error { if err := r.Consumers[1].API.List(ctx, &ops.DeviceCustodyList{}); !meta.IsNoMatchError(err) && !apierrors.IsNotFound(err) { return fmt.Errorf("%w: a consumer project serves Device custody: %v", errTerminal, err) @@ -150,9 +151,6 @@ func (r *Runner) TenantIsolation(ctx context.Context) error { if err := r.Consumers[1].API.List(ctx, &ops.DeviceInstallationList{}); !meta.IsNoMatchError(err) && !apierrors.IsNotFound(err) { return fmt.Errorf("%w: a consumer project serves Device operations: %v", errTerminal, err) } - if _, _, _, _, err := r.installation(ctx, 1); !errors.Is(err, errNoActiveAllocation) { - return fmt.Errorf("%w: installing for a consumer that holds nothing was not refused for its missing allocation: %v", errTerminal, err) - } q, err := r.request(ctx, 1) if err != nil { return err @@ -214,6 +212,6 @@ func (r *Runner) TenantIsolation(ctx context.Context) error { if after.Spec.Fence != before.Spec.Fence || after.Spec.ActiveOperation != nil || operation.Status.Fence != 0 { return fmt.Errorf("%w: the refused installation changed custody", errTerminal) } - fmt.Println("tenant-isolation: consumer B's project has no Device API; the allocator refused to install for it; an installation for its unheld allocation was refused for HolderMismatch with the fence unchanged") + fmt.Println("tenant-isolation: consumer B's project has no Device API; an installation for its unheld allocation was refused for HolderMismatch with the fence unchanged") return nil } From e7e559819394f2b1a10bd801fc9a75a41a9aafa6 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 25 Nov 2026 22:22:50 -0600 Subject: [PATCH 13/16] test(multiplane): Give the interrupt self-test default signals Run under nohup or as a background job, the test's parent ignores SIGHUP or SIGINT. Bash cannot trap a signal that was ignored when it started, so the SIGINT and SIGHUP cases tested the parent's dispositions instead of run.sh, and failed. The test now resets those signals to their defaults in the run it starts. Co-Authored-By: Claude Opus 5.5 --- hack/multiplane/test-interrupt.py | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/hack/multiplane/test-interrupt.py b/hack/multiplane/test-interrupt.py index cf0b41ab..f5b26a47 100644 --- a/hack/multiplane/test-interrupt.py +++ b/hack/multiplane/test-interrupt.py @@ -65,13 +65,22 @@ def result_of(tmp): return json.loads(results[0].read_text()) if len(results) == 1 else None +def default_signals(): + """Give the run default signal dispositions. A parent started under nohup + or as a background job ignores SIGHUP or SIGINT, and bash cannot trap a + signal that was ignored when it started, so the test would then exercise + the parent's dispositions, not run.sh.""" + for sig in (signal.SIGINT, signal.SIGHUP, signal.SIGTERM): + signal.signal(sig, signal.SIG_DFL) + + def interrupted(sig): with tempfile.TemporaryDirectory() as t: tmp = pathlib.Path(t) repo, env = scratch(tmp) log = open(tmp / 'run.out', 'w') p = subprocess.Popen(['bash', str(repo / 'hack/multiplane/run.sh')], cwd=repo, env=env, text=True, - stdout=log, stderr=subprocess.STDOUT, start_new_session=True) + stdout=log, stderr=subprocess.STDOUT, start_new_session=True, preexec_fn=default_signals) deadline = time.monotonic() + 60 while time.monotonic() < deadline and not list(tmp.glob('fleet-multiplane.*/logs/build.log')): time.sleep(0.2) From c73530ac1027516174a9b7b34c16b159e844dd9e Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 25 Nov 2026 22:36:26 -0600 Subject: [PATCH 14/16] docs: Record that both multi-plane runs pass on custody The multi-plane and Redfish lab pages still called the runs on Device custody pending. Both the local VM and the Redfish runs pass every phase on custody. Co-Authored-By: Claude Opus 5.5 --- docs/development/README.md | 11 +++++------ docs/development/roadmap.md | 3 +-- docs/operations/README.md | 4 ++-- docs/operations/local-vm.md | 2 +- docs/operations/multiplane.md | 6 +++--- docs/operations/redfish-lab.md | 8 ++++---- docs/operations/site-execution.md | 6 +++--- 7 files changed, 19 insertions(+), 21 deletions(-) diff --git a/docs/development/README.md b/docs/development/README.md index 9172a514..d59b3565 100644 --- a/docs/development/README.md +++ b/docs/development/README.md @@ -37,8 +37,7 @@ Increment C, the cutover. Every mode allocates, installs and releases on Secret-backed coordinator, its private records and the old executors are deleted, and an allocation's private facts live on its MachineAllocation. The standalone smoke and both multi-plane runs verify it. The end-to-end failure scenarios -(Increment D) are implemented, and their verification in both multi-plane runs -is pending. +(Increment D) are implemented, and both multi-plane runs verify them. The opt-in [multi-plane acceptance harness](../operations/multiplane.md) composes the [local VM site](../operations/local-vm.md) with native Milo project APIs, the @@ -48,13 +47,13 @@ Each local cluster's [Flux](../operations/gitops.md) installs Milo, Karmada, kro an OCI artifact staged from the checkout. Run it with `task multiplane:acceptance`. Its exit codes, bounded phases and sanitized `evidence/` directory are documented there; `task multiplane:test-harness` runs its -offline tests, which CI also runs. Verification of that run on custody is -pending. The Redfish site workers (`internal/site/redfishwork`) read each +offline tests, which CI also runs. The run passes every phase on custody. The +Redfish site workers (`internal/site/redfishwork`) read each Device's own credential and connect only to its approved TLS key. [Redfish-mode acceptance](../operations/redfish-lab.md) (`task multiplane:redfish-acceptance`) exercises them against the unmodified DMTF -Redfish Interface Emulator and a lab-only libvirt adapter, and its verification is -pending too. They are not qualified against a physical BMC or server, and the +Redfish Interface Emulator and a lab-only libvirt adapter, and that run passes +every phase on custody too. They are not qualified against a physical BMC or server, and the production manager does not use them. Production Kustomize roots now package the implemented manager, admission, API, diff --git a/docs/development/roadmap.md b/docs/development/roadmap.md index 4d0968be..9f842409 100644 --- a/docs/development/roadmap.md +++ b/docs/development/roadmap.md @@ -52,8 +52,7 @@ hardware qualification. Increment A (the control-plane foundation), Increment B mode onto custody and deletes the Secret-backed path. An allocation's private facts live on its MachineAllocation. The standalone smoke and both multi-plane runs, local VM and Redfish, verify C. Increment D (end-to-end failure -scenarios) is implemented, and its verification in both multi-plane runs is -pending. +scenarios) is implemented, and both multi-plane runs verify it. Acceptance: the #174 acceptance tests pass, in envtest and in fresh local end-to-end runs, with "nothing sent" proven by the lab BMC audit. diff --git a/docs/operations/README.md b/docs/operations/README.md index 915aab13..faa1907b 100644 --- a/docs/operations/README.md +++ b/docs/operations/README.md @@ -14,8 +14,8 @@ integrations. Real provider support and live Milo acceptance tests are incomplet | Build and test locally or run the simulator | [Implementation commands](../development/README.md#build-test-and-run) | Behavior of the implemented code and synthetic provider | | Exercise allocation, install recovery, release with a wipe, and reuse | [Standalone smoke environment](standalone-smoke.md) | Same-cluster lifecycle on Device custody, with a simulator site and namespaces as project stand-ins | | Understand the local VM site that the multi-plane run drives | [Local VM site](local-vm.md) | The workers that install a real OS over firmware PXE into a disposable libvirt domain, boot it from disk, and wipe it; the single-plane harness is retired; not KVM or hardware qualification | -| Exercise Milo, Karmada and cell-local PXE end to end with one command | [Multi-plane acceptance](multiplane.md) (`task multiplane:acceptance`) | Native project routing, the custody coordinator, federation delivery/reflection, partition, [Kubernetes site execution](site-execution.md) (Flux-owned shared services, kro-created per-operation Jobs) with worker Pod/Job interruption, delivery and reflection faults, wrong location, release with a wipe and reuse; verification of the run on the custody path is pending; every service [installed by per-cluster Flux](gitops.md) from a source built from the checkout; production authority unqualified | -| Drive the same pipeline through Redfish instead of libvirt | [Redfish-mode acceptance](redfish-lab.md) (`task multiplane:redfish-acceptance`) | Redfish site workers: per-Device credentials over a pinned TLS key, one-time PXE/disk boot overrides, power, lost-response recovery and a booted wipe, against the unmodified DMTF Redfish Interface Emulator with a lab-only libvirt adapter and two persistent lab VMs; synthetic credentials and networking; verification of the run is pending; not physical BMC or hardware qualification | +| Exercise Milo, Karmada and cell-local PXE end to end with one command | [Multi-plane acceptance](multiplane.md) (`task multiplane:acceptance`) | Native project routing, the custody coordinator, federation delivery/reflection, partition, [Kubernetes site execution](site-execution.md) (Flux-owned shared services, kro-created per-operation Jobs) with worker Pod/Job interruption, delivery and reflection faults, wrong location, release with a wipe and reuse; the run on the custody path passes every phase; every service [installed by per-cluster Flux](gitops.md) from a source built from the checkout; production authority unqualified | +| Drive the same pipeline through Redfish instead of libvirt | [Redfish-mode acceptance](redfish-lab.md) (`task multiplane:redfish-acceptance`) | Redfish site workers: per-Device credentials over a pinned TLS key, one-time PXE/disk boot overrides, power, lost-response recovery and a booted wipe, against the unmodified DMTF Redfish Interface Emulator with a lab-only libvirt adapter and two persistent lab VMs; synthetic credentials and networking; the run on custody passes every phase; not physical BMC or hardware qualification | | Publish physical-side DHCP reservations for network boot | [Boot network](boot-network.md) | Per-Device BMC endpoints and provisioning attachments, a reservation feed read from the site store that exists only while a boot is admitted, served and withdrawn evidence from the DHCP owner's Kea synchronizer; unit tested, not exercised at a site | | Plan a rack slot and register the server bound to it | [Planning and registering physical devices](physical-inventory.md) | Operator-written `DeviceClaim` and `Device` records in the provider project in Milo, with immutable identity and binding, shown read-only in the staff portal; no capacity or hardware effect; unit tested | | Record what each Device's BMC reports | [BMC discovery](bmc-discovery.md) | Read-only Redfish discovery into Device status, with TLS public-key pinning approved per BMC and identity compared with spec; unit and TLS end-to-end tested, not qualified on vendor hardware | diff --git a/docs/operations/local-vm.md b/docs/operations/local-vm.md index 64929739..ff1dc7b0 100644 --- a/docs/operations/local-vm.md +++ b/docs/operations/local-vm.md @@ -10,7 +10,7 @@ not KVM or hardware qualification. Status: **implemented**. The standalone smoke does not use it. The [multi-plane acceptance](multiplane.md) (`task multiplane:acceptance`) runs it, -and verification of that run after the cutover is pending. +and that run passes every phase after the cutover. ## The single-plane harness is retired diff --git a/docs/operations/multiplane.md b/docs/operations/multiplane.md index 327deaf2..0e9c2016 100644 --- a/docs/operations/multiplane.md +++ b/docs/operations/multiplane.md @@ -10,8 +10,8 @@ artifact built from the checkout; see [Flux-reconciled local environment](gitops production overlay. Production authority and deployment equivalence remain **unqualified**. -Status: the run on Device custody is **implemented**. Verification of the local VM -run and of the [Redfish run](redfish-lab.md) on custody is pending. The run +Status: the run on Device custody is **implemented and verified**: the local VM +run and the [Redfish run](redfish-lab.md) both pass every phase on custody. The run records under [Verification and remaining gaps](#verification-and-remaining-gaps) were observed on the path before the cutover, with the Secret-backed coordinator, and are not evidence for the custody path. @@ -523,7 +523,7 @@ path before the cutover to Device custody. They used the Secret-backed coordinator, a site-wide provider journal and a single-writer `executor.Client`. They show what the earlier composition proved, and the Flux, kro and Karmada findings there still describe the same infrastructure. They are not evidence for -the custody path. Verification of the local VM run on custody is pending. +the custody path. The local VM and Redfish runs on custody pass every phase. ### Flux-owned shared site acceptance (2026-11-16) diff --git a/docs/operations/redfish-lab.md b/docs/operations/redfish-lab.md index 1db1520b..8dc92da5 100644 --- a/docs/operations/redfish-lab.md +++ b/docs/operations/redfish-lab.md @@ -15,7 +15,7 @@ is the same pipeline: Status: the Redfish workers are **implemented and verified** by unit tests, including against TLS BMC stubs. The multi-plane Redfish run on custody is -**implemented**, and its verification is pending. The execution records at the +**implemented and verified**: it passes every phase. The execution records at the end of this page describe runs on the path before the cutover. It is a **local MVP proof**, not hardware qualification. No physical server, BMC, @@ -332,7 +332,7 @@ These are documented lab seams, not production designs: `hack/multiplane/acceptance-redfish.sh` runs every scenario of the [libvirt-mode sequence](multiplane.md#acceptance-phases) through the same federation and kro path, with these differences. The phase descriptions follow the -harness at this change; verification of the run on custody is pending. +harness at this change, and the run on custody passes every phase. **Before topology:** @@ -445,8 +445,8 @@ kustomize and checks the following: The records below describe runs on the path before the cutover to Device custody, with the old executor, a site-wide journal and a shared credential over plain HTTP. They show what the lab and the harness proved then. They are not evidence -for the Redfish workers. The multi-plane Redfish run on custody is implemented, -and its verification is pending. +for the Redfish workers. The multi-plane Redfish run on custody is implemented +and passes every phase. ### Attempts before the first pass (2026-11-16) diff --git a/docs/operations/site-execution.md b/docs/operations/site-execution.md index 134e3035..439868af 100644 --- a/docs/operations/site-execution.md +++ b/docs/operations/site-execution.md @@ -357,8 +357,8 @@ journal in the site store. ## Implemented versus proposed Rows marked "exercised" were observed in runs on the path before the cutover to -Device custody. The same phases now run on custody. Verification of that run is -pending. +Device custody. The same phases now run on custody, and that run passes every +phase. | Behavior | Status | | --- | --- | @@ -371,7 +371,7 @@ pending. | Pod/Job lifecycle not changing the site store, guest or allocation | Implemented and exercised | | Facility-edge DaemonSet, multi-node volumes, HA runtime, live hardware fencing | Proposed only | | A credential broker so no worker holds a long-lived BMC credential | Proposed only ([open questions](../enhancements/pxe-installation/README.md#open-design-questions)) | -| Redfish workers with no libvirt path, against the DMTF Redfish Interface Emulator and lab VMs | Implemented as a separate mode; see [Redfish-mode acceptance](redfish-lab.md). Verification of the run on custody is pending. | +| Redfish workers with no libvirt path, against the DMTF Redfish Interface Emulator and lab VMs | Implemented as a separate mode and verified by the Redfish run on custody; see [Redfish-mode acceptance](redfish-lab.md). | | Synchronized DHCP boot reservations with served and withdrawn evidence, read from the site store | Implemented and unit tested; not exercised at a site ([Boot network](boot-network.md)) | | Physical Redfish/BMC execution Jobs | Not qualified (lab emulator only; see the [hardware readiness checklist](redfish-lab.md#limitations-and-physical-hardware-readiness)) | | Per-Device fence store and journal, older-worker stop with a confirmation, worker deadlines, fenced typed results, per-Device credentials with the approved TLS pin, and the operation handoff payload ([device custody](../development/device-custody.md#site-execution-increment-b)) | Implemented: unit tested, and every site runs it since the cutover. The multi-plane run on it awaits verification. | From 430a71b2431005645fbfcc619dc6df5471f48dd0 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Fri, 27 Nov 2026 19:54:39 -0600 Subject: [PATCH 15/16] test(multiplane): Count only the probe's requests The discovery-faults scenario read the lab BMC's audit by position: the wrong-pin check required the log not to grow, and the effect and rejection checks scanned every entry in the window. Discovery and workers read the same BMC with the same per-Device credential, so a concurrent reader's request failed the scenario. The lab adapter now records each request's User-Agent, printable and at most 128 characters, never a credential or a body. The Redfish client gains an optional user agent, set before its first request; the production executor does not set it and keeps gofish's default. The probe takes a client identity, the scenario gives every probe one run-scoped value, and the pin, effect and rejected-count checks read only the entries that carry it, requiring at least one. A harness test runs the scenario against a log interleaved with another reader's GET, POST and rejected request, and still fails on the probe's own effect and on a wrong-pin request that reached the BMC. Co-Authored-By: Claude Opus 5.5 --- cmd/fleet-multiplane/main.go | 10 +++- docs/operations/redfish-lab.md | 4 +- hack/multiplane/redfish_steps.py | 22 ++++++--- hack/multiplane/test-redfish.py | 70 +++++++++++++++++++++++++++ hack/redfish-lab/fleet_lab_adapter.py | 11 ++++- hack/redfish-lab/test_adapter.py | 5 ++ internal/redfish/client.go | 24 +++++++++ internal/redfish/client_test.go | 41 ++++++++++++++++ 8 files changed, 175 insertions(+), 12 deletions(-) diff --git a/cmd/fleet-multiplane/main.go b/cmd/fleet-multiplane/main.go index baf5142f..aa409405 100644 --- a/cmd/fleet-multiplane/main.go +++ b/cmd/fleet-multiplane/main.go @@ -48,6 +48,7 @@ func run() error { system := fs.String("system", "", "enrolled Redfish System Id (redfish-probe)") uuid := fs.String("uuid", "", "enrolled Redfish System UUID (redfish-probe)") pin := fs.String("pin", "", "the BMC's approved key digest; the probe connects only to that key (redfish-probe)") + clientID := fs.String("client-id", "", "identity the probe's requests carry as their User-Agent, so the lab BMC audit can tell them apart (redfish-probe)") 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)") if err := fs.Parse(os.Args[2:]); err != nil { @@ -68,7 +69,7 @@ func run() error { case "seed", "allocate", "install", "admit-install", "admit-install-b", "release", "release-b", "reuse", "recovery-mismatch", "probe-unallocatable", "tenant-isolation": return phase(os.Args[1], *configPath, *once) case "redfish-probe": - return probe(*endpoint, *credentials, *system, *uuid, *pin) + return probe(*endpoint, *credentials, *system, *uuid, *pin, *clientID) case "image": image, err := siteImage() if err != nil { @@ -189,7 +190,7 @@ func redfishMode() bool { return os.Getenv("FLEET_SITE_PROVIDER") == "redfish" } // prints only an outcome class. Exit codes: 0 discovered, 10 credential // rejected, 11 capability unsupported, 12 identity mismatch, 13 TLS key // other than the pin. -func probe(endpoint, credentials, system, uuid, pin string) error { +func probe(endpoint, credentials, system, uuid, pin, clientID string) error { user, err1 := os.ReadFile(credentials + "/username") password, err2 := os.ReadFile(credentials + "/password") if credentials == "" || err1 != nil || err2 != nil { @@ -199,6 +200,11 @@ func probe(endpoint, credentials, system, uuid, pin string) error { if err != nil { return err } + if clientID != "" { + if err := c.SetUserAgent("fleet-redfish-probe/" + clientID); err != nil { + return err + } + } ctx, cancel := context.WithTimeout(context.Background(), time.Minute) defer cancel() s, err := c.Discover(ctx, redfish.Target{SystemID: system, SystemUUID: uuid}) diff --git a/docs/operations/redfish-lab.md b/docs/operations/redfish-lab.md index 8dc92da5..3717b698 100644 --- a/docs/operations/redfish-lab.md +++ b/docs/operations/redfish-lab.md @@ -84,7 +84,7 @@ does not fork or patch upstream files. | `Boot` source override (`Pxe` or `Hdd`, `Once`), persisted in NVRAM state on the site volume and consumed at power-on | Adapter | | `ResetType` and boot `AllowableValues` narrowed to what the adapter implements; System `UUID` set from the lab target | Adapter | | Definition of the lab domains and the provisioning network, re-created with the same identity if the runtime loses them | Adapter | -| Append-only request audit: method, path, status, principal class, ResetType, boot override, effect and fault. It never records bodies or credentials. | Adapter | +| Append-only request audit: method, path, status, principal class, client User-Agent, ResetType, boot override, effect and fault. It never records bodies or credentials. | Adapter | | `DELETE /redfish/v1/reset` and non-Redfish paths | Refused by the adapter | | Bounded, one-shot lab faults (`reject-auth`, `hide-reset`, `drop-response`) from a fault file | Adapter, lab only | @@ -351,7 +351,7 @@ fixture discovery for the lab Devices. Real BMC discovery is not part of this ru | Phase | What it proves | | --- | --- | | `redfish-baseline` | Both target disks exist and neither target was ever started; records target B's disk digest | -| `redfish-discovery-faults` | Uses the real emulator through `fleet-multiplane redfish-probe` and the production discovery code. Each enrolled System is discovered exactly. A wrong credential exits 10. Target A's Id with target B's UUID, or an unknown UUID, exits 12. An injected unadvertised `On` exits 11. A TLS key other than the pin exits 13 and reaches no request. The BMC audit shows only GETs in the window. | +| `redfish-discovery-faults` | Uses the real emulator through `fleet-multiplane redfish-probe` and the production discovery code. Each enrolled System is discovered exactly. A wrong credential exits 10. Target A's Id with target B's UUID, or an unknown UUID, exits 12. An injected unadvertised `On` exits 11. A TLS key other than the pin exits 13 and reaches no request. Every probe carries one run-scoped User-Agent, and the checks read only audit entries with it, so discovery or a worker reading the same BMC with the same credential cannot change the result. Those entries are GETs only. | | `redfish-bmc-interrupt` | As soon as the installer is running, the BMC Pod is force-deleted and replaced. The guest keeps running; the worker tolerates a bounded BMC outage. | | `interrupt-pod`, `interrupt-job` | As in libvirt mode, now on the Redfish worker, still inside the installer phase | | `redfish-arm-lost-response`, `redfish-lost-response` | Armed before dispatch: the second effective `On` for System-1 (the first install's disk boot) is answered only after 45 seconds. The worker times out and exits 75 (Unknown). Its replacement observes the running or completed target and the consumed override. Exactly one `On` per phase was sent: `powerOnRequests` is one installer and one disk request. | diff --git a/hack/multiplane/redfish_steps.py b/hack/multiplane/redfish_steps.py index 8460bcf7..7f316c96 100644 --- a/hack/multiplane/redfish_steps.py +++ b/hack/multiplane/redfish_steps.py @@ -77,6 +77,12 @@ def audit(s): return [json.loads(l) for l in r.stdout.splitlines() if l.strip()] if r.returncode == 0 else [] +def own(entries, client): + """Audit entries one client sent. Discovery and workers read the same BMC + with the same credential, so only the client identity separates them.""" + return [e for e in entries if e.get('client') == client] + + def mutating(entries, system=None): return [e for e in entries if e['method'] not in ('GET', 'HEAD') and (system is None or e['path'].rstrip('/').startswith('/redfish/v1/Systems/' + system))] @@ -221,6 +227,10 @@ def discovery_faults(s): (p / 'username').write_text((d / 'bmc-username').read_text()) (p / 'password').write_text(password) pf, port = port_forward(s) + # Every probe of this step carries one run-scoped identity, and the checks + # below read only the audit entries that carry it. + client_id = secrets.token_hex(8) + agent = 'fleet-redfish-probe/' + client_id before = len(audit(s)) cases = [] try: @@ -228,7 +238,7 @@ def discovery_faults(s): def probe(name, creds, system, uuid, want, pin=pin): r = subprocess.run([str(s / 'fleet-multiplane-host'), 'redfish-probe', '--endpoint', 'https://127.0.0.1:%d' % port, '--credentials', str(creds), - '--system', system, '--uuid', uuid, '--pin', pin], text=True, capture_output=True, timeout=120) + '--system', system, '--uuid', uuid, '--pin', pin, '--client-id', client_id], text=True, capture_output=True, timeout=120) line = (r.stdout.strip().splitlines() or [''])[-1] cases.append({'case': name, 'system': system, 'exitCode': r.returncode, 'outcome': line}) if r.returncode != want: @@ -246,9 +256,9 @@ def probe(name, creds, system, uuid, want, pin=pin): # Another key's digest: the TLS handshake fails before any request, # so the BMC audit gains nothing. other = pin[:-1] + ('0' if pin[-1] != '0' else '1') - seen = len(audit(s)) + seen = len(own(audit(s), agent)) probe('a TLS key other than the pin', good, TARGET_A['system'], TARGET_A['uuid'], 13, pin=other) - if len(audit(s)) != seen: + if len(own(audit(s), agent)) != seen: die('a probe with the wrong pin reached the BMC') probe('target A after the fault is cleared', good, TARGET_A['system'], TARGET_A['uuid'], 0) finally: @@ -257,11 +267,11 @@ def probe(name, creds, system, uuid, want, pin=pin): for f in p.iterdir(): f.unlink() p.rmdir() - window = audit(s)[before:] - if mutating(window) or not any(e['principal'] == 'rejected' for e in window): + window = own(audit(s)[before:], agent) + if not window or mutating(window) or not any(e['principal'] == 'rejected' for e in window): die('discovery probes issued an effect or the wrong credential was not rejected: %s' % mutating(window)) write(s / 'evidence' / 'redfish-discovery-faults.json', {'observedAt': now(), 'emulator': 'DMTF Redfish-Interface-Emulator 1.2.2 + lab adapter (live, in the cell)', - 'client': 'internal/redfish discovery through fleet-multiplane redfish-probe', 'cases': cases, + 'client': 'internal/redfish discovery through fleet-multiplane redfish-probe', 'userAgent': agent, 'cases': cases, 'auditRequests': len(window), 'mutatingRequests': 0, 'rejectedRequests': sum(1 for e in window if e['principal'] == 'rejected')}) print('redfish-discovery-faults: real emulator discovery selected each enrolled System exactly; wrong credential, swapped or unknown identity and an unadvertised ResetType were refused with GETs only; a TLS key other than the pin reached no request') diff --git a/hack/multiplane/test-redfish.py b/hack/multiplane/test-redfish.py index e13f1950..d245fc20 100644 --- a/hack/multiplane/test-redfish.py +++ b/hack/multiplane/test-redfish.py @@ -185,6 +185,76 @@ def build(path): check('teardown removes the synthetic BMC credential after a pass', '"$state/redfish"' in teardown) check('teardown removes the BMC image tags', '"$prefix-bmc-image"' in teardown and 'fleet-bmc:$prefix' in teardown) +# Discovery faults count only the probe's own audit entries. A concurrent +# reader with the same credential (discovery, a worker) shares the BMC log, +# including a mutation and a rejected request, and must not change the result. +import types # noqa: E402 +import redfish_steps as rs # noqa: E402 + + +def discovery_run(own_extra=None, wrong_pin_reaches=False): + st = pathlib.Path(tempfile.mkdtemp()) + (st / 'evidence').mkdir() + (st / 'redfish').mkdir() + for name, value in (('bmc-password.token', 'synthetic-password\n'), ('bmc-username', 'lab-operator\n'), ('bmc-pin', 'a' * 64 + '\n')): + (st / 'redfish' / name).write_text(value) + log, hidden = [], set() + + def entry(client, method='GET', principal='authenticated', path='/redfish/v1/Systems/System-1'): + return {'method': method, 'path': path, 'status': 200, 'principal': principal, 'client': client} + + def bmc(_s, *command, check=True): + if command[-2:] == ('hide-reset', 'On'): + hidden.add('On') + if command[-1:] == ('clear',): + hidden.clear() + return types.SimpleNamespace(returncode=0, stdout='', stderr='') + + real_run = subprocess.run + + def run(command, **kw): + if 'redfish-probe' not in command: + return real_run(command, **kw) + arg = dict(zip(command[2::2], command[3::2])) + agent = 'fleet-redfish-probe/' + arg['--client-id'] + # The concurrent reader: discovery polling with the same credential. + log.extend([entry('gofish/1.0'), entry('gofish/1.0', method='POST', path='/redfish/v1/Systems/System-1/Actions/ComputerSystem.Reset'), + entry('gofish/1.0', principal='rejected')]) + if arg['--pin'] != 'a' * 64: + if wrong_pin_reaches: + log.append(entry(agent)) + return types.SimpleNamespace(returncode=13, stdout='redfish-probe: pin mismatch\n', stderr='') + if arg['--credentials'].endswith('probe-bad'): + log.append(entry(agent, principal='rejected')) + return types.SimpleNamespace(returncode=10, stdout='redfish-probe: credential rejected\n', stderr='') + log.extend([entry(agent, path='/redfish/v1/'), entry(agent)] + [entry(agent, **x) for x in (own_extra or [])]) + want = {(rs.TARGET_A['system'], rs.TARGET_A['uuid']): 0, (rs.TARGET_B['system'], rs.TARGET_B['uuid']): 0}.get((arg['--system'], arg['--uuid']), 12) + if want == 0 and hidden: + want = 11 + return types.SimpleNamespace(returncode=want, stdout='redfish-probe: done\n', stderr='') + + saved = (rs.audit, rs.bmc, rs.port_forward, rs.subprocess.run) + rs.audit = lambda _s: list(log) + rs.bmc = bmc + rs.port_forward = lambda _s: (types.SimpleNamespace(kill=lambda: None), 1) + rs.subprocess.run = run + try: + rs.discovery_faults(st) + return None, json.loads((st / 'evidence' / 'redfish-discovery-faults.json').read_text()) + except SystemExit as e: + return str(e), None + finally: + rs.audit, rs.bmc, rs.port_forward, rs.subprocess.run = saved + + +err, record = discovery_run() +check('discovery faults ignore a concurrent reader', err is None and record['userAgent'].startswith('fleet-redfish-probe/') + and record['auditRequests'] == 13 and record['rejectedRequests'] == 1, str(err or record)) +err, _ = discovery_run(own_extra=[{'method': 'POST', 'path': '/redfish/v1/Systems/System-1/Actions/ComputerSystem.Reset'}]) +check("discovery faults still fail on the probe's own effect", err is not None and 'issued an effect' in err, str(err)) +err, _ = discovery_run(wrong_pin_reaches=True) +check('discovery faults still fail when the wrong-pin probe reaches the BMC', err is not None and 'wrong pin reached' in err, str(err)) + if failures: print('FAIL Redfish mode tests:\n ' + '\n '.join(failures)) sys.exit(1) diff --git a/hack/redfish-lab/fleet_lab_adapter.py b/hack/redfish-lab/fleet_lab_adapter.py index 3782e009..da53a691 100755 --- a/hack/redfish-lab/fleet_lab_adapter.py +++ b/hack/redfish-lab/fleet_lab_adapter.py @@ -12,7 +12,8 @@ persistent libvirt domain per System, and PowerState read from libvirt; * Boot source override (Pxe or Hdd, Once) persisted like BMC NVRAM and consumed when the domain is started; - * an append-only request audit log (no bodies, no credentials); + * 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. It is never part of Fleet's production code. It is the only component in @@ -184,6 +185,12 @@ def power_on(self, sid): return boot +def client(user_agent): + """The User-Agent as the audit records it: printable ASCII, at most 128 + characters. It identifies a reader; it is not a credential.""" + return ''.join(c for c in user_agent if ' ' <= c <= '~')[:128] + + def error(status, message): return {'error': {'code': 'Base.1.0.GeneralError', 'message': message}}, status @@ -340,7 +347,7 @@ def reset(sid): @g.app.after_request def audit(response): entry = {'at': now(), 'method': request.method, 'path': request.path, 'status': response.status_code, - 'principal': getattr(request_context, 'principal', 'anonymous')} + 'principal': getattr(request_context, 'principal', 'anonymous'), 'client': client(request.headers.get('User-Agent', ''))} entry.update(getattr(request_context, 'detail', {})) with LOCK, open(audit_path, 'a') as f: f.write(json.dumps(entry, sort_keys=True) + '\n') diff --git a/hack/redfish-lab/test_adapter.py b/hack/redfish-lab/test_adapter.py index e44926a6..10302110 100644 --- a/hack/redfish-lab/test_adapter.py +++ b/hack/redfish-lab/test_adapter.py @@ -76,6 +76,11 @@ def test_4_boot_once_is_consumed_by_power_on(self): self.assertEqual(self.app.get('/redfish/v1/Systems/System-1', headers=AUTH).json['PowerState'], 'Off') self.assertEqual(self.app.post('/redfish/v1/Systems/System-1/Actions/ComputerSystem.Reset', headers=AUTH, json={'ResetType': 'Nmi'}).status_code, 400) + def test_4b_audit_names_each_client(self): + self.app.get('/redfish/v1/Systems', headers=dict(AUTH, **{'User-Agent': 'fleet-redfish-probe/0123abcd'})) + self.app.get('/redfish/v1/Systems', headers=dict(AUTH, **{'User-Agent': 'another-reader\r\nX: y'})) + self.assertEqual([e['client'] for e in self.audit()[-2:]], ['fleet-redfish-probe/0123abcd', 'another-readerX: y']) + def test_5_faults_are_bounded_and_audited(self): adapter.fault_cli(['reject-auth', '1']) self.assertEqual(self.app.get('/redfish/v1/Systems', headers=AUTH).status_code, 401) diff --git a/internal/redfish/client.go b/internal/redfish/client.go index f1c085ce..38fe62e3 100644 --- a/internal/redfish/client.go +++ b/internal/redfish/client.go @@ -106,6 +106,26 @@ func newClient(endpoint, user, password string, timeout time.Duration, tlsConfig }}, nil } +// SetUserAgent makes every request this client sends carry userAgent, so a +// lab BMC's audit can tell its requests from another reader's. Without it the +// client sends gofish's default. It must be called before the first request. +func (c *Client) SetUserAgent(userAgent string) error { + if userAgent == "" || len(userAgent) > 128 || strings.ContainsFunc(userAgent, func(r rune) bool { return r < 0x20 || r > 0x7e }) { + return errors.New("redfish: a user agent must be 1 to 128 printable ASCII characters") + } + c.mu.Lock() + defer c.mu.Unlock() + if c.api != nil { + return errors.New("redfish: the user agent must be set before the first request") + } + httpClient := *c.config.HTTPClient + g := httpClient.Transport.(guard) + g.userAgent = userAgent + httpClient.Transport = g + c.config.HTTPClient = &httpClient + return nil +} + func cleanPath(p string) (string, error) { if (p != "/redfish/v1" && !strings.HasPrefix(p, "/redfish/v1/")) || strings.Contains(p, "..") || strings.ContainsAny(p, "?#\\ ") { return "", fmt.Errorf("%w: unexpected resource path", ErrIdentity) @@ -118,6 +138,7 @@ func cleanPath(p string) (string, error) { // mutation cannot carry a query. type guard struct { scheme, host string + userAgent string next http.RoundTripper } @@ -131,6 +152,9 @@ func (g guard) RoundTrip(r *http.Request) (*http.Response, error) { } r = r.Clone(r.Context()) r.Header.Set("OData-Version", "4.0") + if g.userAgent != "" { + r.Header.Set("User-Agent", g.userAgent) + } resp, err := g.next.RoundTrip(r) if err != nil { return nil, err diff --git a/internal/redfish/client_test.go b/internal/redfish/client_test.go index cf720a44..1c54b957 100644 --- a/internal/redfish/client_test.go +++ b/internal/redfish/client_test.go @@ -22,6 +22,7 @@ type bmcStub struct { hold map[string]time.Duration requests []string ifMatch []string + agents []string } func newStub() *bmcStub { @@ -51,6 +52,7 @@ func (b *bmcStub) ServeHTTP(w http.ResponseWriter, r *http.Request) { } b.mu.Lock() b.requests = append(b.requests, r.Method+" "+key) + b.agents = append(b.agents, r.Header.Get("User-Agent")) if r.Method != http.MethodGet { b.ifMatch = append(b.ifMatch, r.Header.Get("If-Match")) } @@ -126,6 +128,45 @@ func TestDiscoveryWalksEveryPageOfTheSystemsCollection(t *testing.T) { } } +func TestSetUserAgentMarksEveryRequestOnlyWhenSet(t *testing.T) { + b := newStub() + c := stubClient(t, b, time.Second) + if _, err := c.Discover(context.Background(), Target{SystemID: "B", SystemUUID: uuidB}); err != nil { + t.Fatal(err) + } + for _, a := range b.agents { + if strings.HasPrefix(a, "fleet-") { + t.Fatalf("a client without SetUserAgent sent %q", a) + } + } + // Once connected, the identity can no longer change mid-stream. + if err := c.SetUserAgent("fleet-redfish-probe/late"); err == nil { + t.Fatal("set a user agent after the first request") + } + + b = newStub() + c = stubClient(t, b, time.Second) + for _, bad := range []string{"", "two\nlines", strings.Repeat("x", 129), "caf\u00e9"} { + if err := c.SetUserAgent(bad); err == nil { + t.Fatalf("accepted user agent %q", bad) + } + } + if err := c.SetUserAgent("fleet-redfish-probe/0123abcd"); err != nil { + t.Fatal(err) + } + if _, err := c.Discover(context.Background(), Target{SystemID: "B", SystemUUID: uuidB}); err != nil { + t.Fatal(err) + } + if len(b.agents) == 0 { + t.Fatal("no request reached the BMC") + } + for i, a := range b.agents { + if a != "fleet-redfish-probe/0123abcd" { + t.Fatalf("request %s carried user agent %q", b.requests[i], a) + } + } +} + func TestDiscoveryRefusesPartialOrForeignCollections(t *testing.T) { for name, tc := range map[string]struct { mutate func(*bmcStub) From 940493c4899730272c6fb4798d33623349693858 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Fri, 27 Nov 2026 20:42:42 -0600 Subject: [PATCH 16/16] test(redfish-lab): Send valid headers in self-test The adapter self-test sent a User-Agent containing a newline through the Flask test client, and Werkzeug refuses that header with a ValueError before the adapter sees it. The BMC self-test phase failed in every Redfish run. Send a header with a tab, which the audit drops, and check the sanitizer directly for newlines, other control characters and the 128-character cap. Co-Authored-By: Claude Opus 5.5 --- hack/redfish-lab/test_adapter.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/hack/redfish-lab/test_adapter.py b/hack/redfish-lab/test_adapter.py index 10302110..68adb7c9 100644 --- a/hack/redfish-lab/test_adapter.py +++ b/hack/redfish-lab/test_adapter.py @@ -78,8 +78,11 @@ def test_4_boot_once_is_consumed_by_power_on(self): def test_4b_audit_names_each_client(self): self.app.get('/redfish/v1/Systems', headers=dict(AUTH, **{'User-Agent': 'fleet-redfish-probe/0123abcd'})) - self.app.get('/redfish/v1/Systems', headers=dict(AUTH, **{'User-Agent': 'another-reader\r\nX: y'})) - self.assertEqual([e['client'] for e in self.audit()[-2:]], ['fleet-redfish-probe/0123abcd', 'another-readerX: y']) + self.app.get('/redfish/v1/Systems', headers=dict(AUTH, **{'User-Agent': 'another\treader'})) + self.assertEqual([e['client'] for e in self.audit()[-2:]], ['fleet-redfish-probe/0123abcd', 'anotherreader']) + # The HTTP stack refuses a newline in a header before the adapter sees + # it; the audit form also drops other control characters and caps it. + self.assertEqual(adapter.client('a\r\nb\x7fc' + 'z' * 200), ('abc' + 'z' * 200)[:128]) def test_5_faults_are_bounded_and_audited(self): adapter.fault_cli(['reject-auth', '1'])