From 770a0898c8819b9142b40885ea064b511932bb0f Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sat, 14 Nov 2026 10:30:05 -0600 Subject: [PATCH 001/518] docs: propose PXE installation architecture --- README.md | 3 + docs/enhancements/pxe-installation/README.md | 375 ++++++++++++++++++ .../diagrams/architecture.svg | 133 +++++++ .../diagrams/installation-workflows.svg | 107 +++++ .../diagrams/user-journeys.svg | 115 ++++++ 5 files changed, 733 insertions(+) create mode 100644 docs/enhancements/pxe-installation/README.md create mode 100644 docs/enhancements/pxe-installation/diagrams/architecture.svg create mode 100644 docs/enhancements/pxe-installation/diagrams/installation-workflows.svg create mode 100644 docs/enhancements/pxe-installation/diagrams/user-journeys.svg diff --git a/README.md b/README.md index 778018b3..010548c4 100644 --- a/README.md +++ b/README.md @@ -47,5 +47,8 @@ today. Then choose a topic: The [Bare Metal CLI enhancement](docs/enhancements/metal-cli/README.md) proposes `datumctl metal` discovery, machine management, and safe recovery workflows. +The [PXE installation enhancement](docs/enhancements/pxe-installation/README.md) +proposes managed images and bounded delegation to customer PXE. + Contributors should also read the [repository guidance](AGENTS.md) and [implementation roadmap](docs/development/roadmap.md). diff --git a/docs/enhancements/pxe-installation/README.md b/docs/enhancements/pxe-installation/README.md new file mode 100644 index 00000000..f911a507 --- /dev/null +++ b/docs/enhancements/pxe-installation/README.md @@ -0,0 +1,375 @@ +--- +status: provisional +stage: alpha +--- + +# PXE installation and delegated network boot + +- [Summary](#summary) +- [Motivation](#motivation) +- [Proposal](#proposal) + - [User stories](#user-stories) + - [Installation modes](#installation-modes) + - [Managed golden image](#managed-golden-image) + - [Delegated customer PXE](#delegated-customer-pxe) +- [Design details](#design-details) + - [Control-plane placement](#control-plane-placement) + - [API design](#api-design) + - [Admission and authority](#admission-and-authority) + - [Location execution](#location-execution) + - [Completion and evidence](#completion-and-evidence) + - [Release and recovery](#release-and-recovery) + - [Security boundaries](#security-boundaries) + - [Acceptance tests](#acceptance-tests) +- [Production readiness review questionnaire](#production-readiness-review-questionnaire) +- [Drawbacks](#drawbacks) +- [Alternatives](#alternatives) +- [Open design questions](#open-design-questions) +- [Infrastructure needed](#infrastructure-needed) + +## Summary + +Fleet will support two ways to install an allocated bare-metal machine. Fleet can +automatically install a platform-approved golden image, or it can temporarily +chain the machine to a customer-supplied PXE service. Both paths use the same +immutable `Installation`, allocation, federation handoff, power, boot fencing, +and release contracts. + +The Fleet management control plane admits the exact operation before any effect. +The Federation Control Plane delivers that operation to one selected location +control plane. The location prepares networking, controls one-time network boot, +executes the selected installation mode, and returns attributable evidence. + +Fleet does not adopt a separate provisioning platform. A location may use +Kubernetes CRDs, Jobs, and Kube Resource Orchestrator (KRO) to compose local work, +but those resources are execution details and cannot allocate a machine, expand +the admitted operation, or release capacity. + +![Control-plane architecture for managed and delegated PXE installation](diagrams/architecture.svg) + +## Motivation + +Some customers want a ready machine built from a supported platform image. Other +customers already operate an installation system and need Fleet to hand an +allocated machine to that system without giving it broad DHCP, BMC, or provider +inventory access. + +Treating those as unrelated workflows would duplicate boot, power, fencing, and +recovery logic. Giving a customer direct control of a shared provisioning network +would let its system affect machines outside its allocation. Requiring Fleet to +understand each customer installer would create an unnecessary backend contract. + +### Goals + +- Install approved golden images through an automated PXE workflow. +- Chain one allocated machine to a customer PXE endpoint for a bounded session. +- Keep Fleet in control of allocation, power, the first boot decision, fencing, + release, and provider cleanup. +- Use one immutable Installation and one durable handoff protocol for both modes. +- Keep DHCP, IPAM, switch configuration, and routing with their existing owners. +- Report what Fleet verified without claiming knowledge of an opaque customer OS. + +### Non-goals + +- Running or adopting Tinkerbell, Metal3, Ironic, or another provisioning control + plane as part of Fleet. +- Giving customers BMC credentials or authority to answer DHCP on a shared + provisioning network. +- Supporting a permanently network-booted workload in the first release. +- Continuously managing or monitoring the installed operating system. +- Making KRO, a Job, or a location-local record an allocation authority. + +## Proposal + +### User stories + +- A customer selects a supported golden image and receives an installed machine + without operating a provisioning service. +- A customer with an existing PXE service installs its own operating system on + an allocated machine while Fleet retains power and boot control. +- A provider controls which MachineClasses permit managed images or delegated PXE. +- An operator can recover a lost response without repeating a destructive action + or exposing uncertain capacity to another customer. + +The two customer journeys share admission and fencing but differ in who supplies +the installer and what Fleet can verify: + +![Customer journeys for managed images and delegated PXE](diagrams/user-journeys.svg) + +### Installation modes + +An Installation has exactly one source: + +| Mode | Installer and image owner | Fleet verifies | +| --- | --- | --- | +| `ManagedImage` | Fleet resolves a platform-approved image and qualified recipe. | Exact image and recipe, target disk evidence, boot fencing, and required first-boot evidence. | +| `DelegatedPXE` | The customer supplies a PXE endpoint and controls its installer. | Exact delegation target, boot session, customer result, boot fencing, and the configured post-install boot observation. | + +MachineClass policy advertises supported modes. It does not grant permission to +use them. Fleet checks current source-use authority, allocation identity, class +revision, endpoint policy, networking feasibility, and predecessor state when it +admits each Installation. + +### Managed golden image + +Fleet resolves the approved image, bootstrap configuration, hardware compatibility, +and location recipe. It retains their exact identities, bytes or digests, and +revisions before dispatch. The selected location then: + +1. obtains provisioning-network readiness from its owner; +2. authorizes one network boot for the selected machine; +3. boots a small Fleet installer; +4. writes and verifies the pinned image on the admitted target disk; +5. revokes network boot and requests local-disk boot; and +6. returns installation and required first-boot evidence. + +### Delegated customer PXE + +The customer provides an HTTPS iPXE endpoint, trust configuration, optional +endpoint credentials, and a completion policy. Fleet retains protected copies of +those inputs before dispatch. The location boot service remains the first boot +decision point and chains only the admitted machine to the customer endpoint. + +The customer does not receive BMC credentials or DHCP authority. Its system may +install any OS allowed by service policy, then sends an operation-scoped completion +callback. The location revokes delegation, requests local-disk boot, and returns +the evidence required by the Installation contract. + +The first release requires delegated PXE to finish with local-disk boot. A +permanently network-booted runtime needs a separate design because it retains boot +authority for the life of the allocation. + +## Design details + +### Control-plane placement + +The design follows the Fleet management control-plane boundaries: + +| Boundary | Responsibility | +| --- | --- | +| Provider project API | MachineClass policy, MachineCapacity, physical inventory, and provider eligibility. | +| Consumer project API | Machine and immutable Installation requests and projected status. | +| Fleet private storage | Exact allocation, caller authority, admitted inputs, operation journal, credentials, and cleanup custody. | +| Fleet management runtime | Admission, allocation coordination, handoff creation, and result validation. | +| Federation hub | Canonical admitted location handoff and cell-owned execution status. | +| Selected location control plane | Network integration, PXE authorization, power, installation execution, fencing, and evidence. | + +The Fleet runtime's deployment cluster is not the canonical store for project +objects or federation intent. Kubernetes UIDs are local evidence and do not cross +project, hub, or cell API boundaries as authored references. + +### API design + +The following shapes are proposals, not implemented schemas. `Installation.spec` +remains immutable and keeps the existing predecessor contract. + +```yaml +apiVersion: metal.datumapis.com/v1alpha1 +kind: Installation +metadata: + name: example-os-1 + namespace: default +spec: + machineRef: {name: example} + expectedPredecessor: {type: None} + source: + managedImage: + imageRef: {name: qualified-linux} + bootstrapConfigRef: {name: example-bootstrap} +``` + +A delegated request selects the other union member: + +```yaml +spec: + machineRef: {name: example} + expectedPredecessor: {type: None} + source: + delegatedPXE: + endpoint: + url: https://pxe.customer.example/boot.ipxe + trustBundleRef: {name: customer-pxe-ca} + authorizationRef: {name: customer-pxe-credentials} + correlation: + workflowID: example-workflow-1 + templateDigest: sha256:example + completion: + mode: Callback + postCompletionBoot: LocalDisk +``` + +The API server applies defaults before Fleet captures the request digest. Fleet +resolves referenced Secrets under the caller's authority and retains protected +copies needed for recovery. Credentials and rendered bootstrap content do not +enter the federation handoff. + +MachineClass definitions add policy describing supported installation modes and +boot capabilities. Publication exposes only the permitted summary. The exact +provider executor, BMC enrollment, installer recipe, and boot-service configuration +remain private location state. + +### Admission and authority + +Before dispatch, Fleet retains: + +- provider and consumer Project identities; +- Machine, MachineAllocation, MachineCapacity, and Installation incarnations; +- the MachineClass and MachineProfile revisions; +- the consumed predecessor and operation identity; +- target location, boot interface, and qualified firmware mode; +- image, recipe, bootstrap, endpoint, trust, and credential digests as applicable; +- current IAM, entitlement, quota, and source-use decisions; and +- an executor fencing token and required completion evidence. + +The handoff contains the exact admitted target and non-secret execution inputs or +protected capability references. Delivery to a cell is not fresh authorization. +The cell cannot select another machine, endpoint, image, or installation mode. + +### Location execution + +A qualified location runs a small platform boot service. Provider DHCP directs +eligible firmware to that service. With no active admitted boot session, the +service returns local boot. With a valid session, it serves the Fleet installer or +chains through an allocation-scoped proxy to the admitted customer endpoint. + +The proxy validates the endpoint and TLS policy, prevents unapproved redirects, +keeps endpoint credentials away from the machine, and records the response digest. +Customer artifacts referenced by the returned script must use approved HTTPS +origins or the same scoped proxy. + +Location implementation may use: + +- a Deployment or facility-edge DaemonSet for boot scripts and callbacks; +- a private execution CRD for the delivered handoff; +- Jobs for bounded Redfish, power, verification, and fencing actions; and +- KRO to create and order those local resources. + +Jobs must recover a retained provider operation before retrying. Job completion +does not by itself prove a remote effect. A KRO instance is derived state and +cannot replace the hub handoff, operation journal, or provider fence. + +![Shared installation workflow and mode-specific execution](diagrams/installation-workflows.svg) + +### Completion and evidence + +The cell issues a short-lived callback capability for delegated PXE. The callback +can report the retained operation's result but cannot choose another target, +extend authority, request release, or write public status. + +Managed-image success proves the qualified image and recipe evidence required by +the class. Delegated success normally proves only that Fleet delegated the correct +machine, the customer reported completion, Fleet revoked the delegation, and the +configured local boot was observed. Public status identifies the result mode and +assurance rather than describing an opaque customer OS as platform verified. + +Fleet validates the target, operation revision, fencing token, evidence freshness, +and required conditions before setting Installation `Ready=True`. Installation +readiness reports completion of the admitted contract, not continuing guest health. + +### Release and recovery + +A timeout or lost response does not prove that an installer stopped. Fleet marks +the outcome unknown, retains the allocation, and recovers the same operation. A +takeover must fence the old executor at the boot, network, power, and provider +effect boundaries before continuing. + +Release closes new boot and power admission, revokes PXE and console sessions, +fences provisioning networking, settles in-flight work, and performs required +provider cleanup. Capacity returns to supply only after cleanup is verified. +Consumer project deletion does not remove these provider-side obligations. + +### Security boundaries + +- The platform remains the first DHCP and iPXE decision point. +- A delegated endpoint applies to one allocation and one admitted operation. +- Customer endpoint access is restricted against server-side request forgery and + cross-allocation data exposure. +- BMC, provider, bootstrap, and endpoint credentials remain in protected stores. +- Boot requests authenticate more than a caller-supplied MAC address. +- Callback capabilities are short lived, single operation, and non-authoritative. +- Logs and evidence retain correlation and digests without secret content. + +### Acceptance tests + +Qualify one UEFI, Redfish, non-Talos hardware and OS combination. Test both modes +through real project admission, federation delivery, networking, and disposable +hardware. + +Acceptance requires: + +- only the allocated machine can use a boot session; +- a managed install writes the retained image and boots from the selected disk; +- a delegated endpoint cannot affect another machine or shared DHCP; +- duplicate delivery and duplicate Jobs recover one retained operation; +- endpoint, cell, image, predecessor, and fencing mismatches cause no effects; +- lost callbacks and cell outages remain unknown rather than ready; +- revocation prevents another network boot after completion; +- release cannot expose capacity before network and provider cleanup; and +- customer project deletion preserves recovery and cleanup custody. + +## Production readiness review questionnaire + +### How is the feature enabled or disabled? + +Enable installation modes per accepted MachineClass and qualified location. +Rollback stops new admission while preserving handoff recovery, boot revocation, +and release. Disabling a controller does not cancel remote work. + +### What must operators monitor? + +Monitor active and expired boot sessions, handoff delivery lag, endpoint failures, +unknown operations, stale callbacks, fencing failures, cleanup age, and quarantined +capacity. Correlate each event with the retained allocation and operation. + +### How are failures recovered? + +Query the retained operation and location evidence before retrying. Reuse its +identity and exact inputs. Fence the previous executor before takeover. Missing or +conflicting evidence blocks readiness and capacity reuse. + +### What must upgrades preserve? + +Preserve allocation custody, immutable Installation inputs, handoff revisions, +executor fencing, active boot sessions, callback correlation, and cleanup +obligations. Test mixed versions and restore while both installation modes run. + +## Drawbacks + +The platform must operate a boot service and small ephemeral installer at each +qualified location. Delegated PXE adds endpoint security and weaker OS assurance. +Strict fencing can keep a machine unavailable when a customer system or location +cannot prove that work stopped. + +## Alternatives + +- **Adopt a provisioning platform:** rejected because it adds overlapping hardware, + workflow, networking, and lifecycle authorities. +- **Give customers direct DHCP or BMC access:** rejected because it can affect + machines outside the allocation and is difficult to revoke safely. +- **Treat delegated PXE as allocate-only with no Fleet operation:** insufficient + when Fleet must provide one-time PXE, power, network isolation, and recovery. +- **Create a public ProvisioningClass now:** deferred. MachineClass policy and the + immutable Installation source establish the first required contract without a + second offering hierarchy. + +## Open design questions + +- Exact MachineClass policy and Installation union schemas. +- Portable handoff encoding and the location status writer contract. +- Boot identity beyond MAC address for the first qualified hardware. +- Customer endpoint connectivity, TLS trust, proxying, and artifact-origin policy. +- The managed installer image, action format, target-disk selector, and signing. +- Callback authentication and the minimum delegated completion evidence. +- Whether repeated endpoint configuration later warrants a reusable public kind. +- Durable journal, credential broker, evidence retention, and restore protocols. + +Record these decisions and their rationale before enabling hardware effects. + +## Infrastructure needed + +Testing needs one provider project, two consumer projects, a federation hub, one +selected location control plane, networking-owner integration, a platform boot +service, an independent customer PXE endpoint, protected artifact and credential +storage, and disposable Redfish/UEFI hardware. Failure injection must cover lost +responses, duplicate delivery, stale workers, endpoint outages, control-plane +outages, credential revocation, and storage restoration. diff --git a/docs/enhancements/pxe-installation/diagrams/architecture.svg b/docs/enhancements/pxe-installation/diagrams/architecture.svg new file mode 100644 index 00000000..b3474131 --- /dev/null +++ b/docs/enhancements/pxe-installation/diagrams/architecture.svg @@ -0,0 +1,133 @@ + + Fleet PXE installation control-plane architecture + Provider and consumer project APIs feed Fleet management. Fleet writes admitted work to a Karmada hub, which targets one location cell. The cell controls networking, boot, power, managed installation, or delegation to a customer PXE endpoint, and returns evidence. + + + + + + + + + PXE installation follows Fleet's existing authority boundaries + + + PROJECT CONTROL PLANES + + + Provider project API + MachineClass policy + MachineCapacity + Fleet physical inventory + Provider and allocator-owned state + remains canonical here. + + + Consumer project API + Machine + Immutable Installation + ManagedImage or DelegatedPXE + Customers write requests; + Fleet projects verified status. + + + Fleet private storage + Allocation custody + Exact admitted inputs + Journal, credentials, cleanup + Not reconstructed from status. + + + MANAGEMENT AND DELIVERY + + + Fleet management + Authenticate and authorize + Allocate and hold quota + Resolve and pin inputs + Admit one exact operation + Validate returned evidence + Its deployment cluster is not + the canonical project store. + + + Karmada federation hub + MachineAllocationHandoff + Exact target and operation + Selected-cell delivery + Management writes intent; + the cell writes execution status. + + + SELECTED LOCATION / CELL + + + Cell execution + Local handoff adapter + Jobs and optional KRO + Provider operation recovery + Cannot change the admitted target. + + + Networking owner + Provisioning attachment + Address and switch state + Cleanup or fencing evidence + Fleet is not another IPAM writer. + + + Platform boot service + First iPXE decision + One-machine boot session + Installer or endpoint proxy + Callback and evidence + No session means local boot. + + + Provider executor + Redfish power and boot + Operation ID and fencing + Local boot transition + Release and cleaning + Credentials remain private. + + + Bare-metal machine + Fleet installer or customer installer + Then local-disk boot + Never becomes allocation authority. + + + Customer PXE endpoint + Customer-owned script and workflow + Operation-scoped callback + Used only for DelegatedPXE. + + + + + + + + + + + + + + + + targeted delivery + admitted request + result + verified status + diff --git a/docs/enhancements/pxe-installation/diagrams/installation-workflows.svg b/docs/enhancements/pxe-installation/diagrams/installation-workflows.svg new file mode 100644 index 00000000..cc512f36 --- /dev/null +++ b/docs/enhancements/pxe-installation/diagrams/installation-workflows.svg @@ -0,0 +1,107 @@ + + Managed image and delegated PXE installation workflows + A shared admission and network preparation flow branches into a managed golden-image installation or a delegated customer PXE installation. Both paths converge on PXE revocation, local boot, verification, and status projection. + + + + + + + + + Both modes share admission, fencing, and release + + + 1. Installation request + ManagedImage or + DelegatedPXE + + + 2. Admit exact inputs + Authority, predecessor, quota + + + 3. Deliver handoff + One selected location + + + 4. Prepare network + Owner returns network + readiness evidence + + + 5. Arm one PXE boot + Retained operation and fence + + + + + + + + + + MANAGED GOLDEN IMAGE + + Serve Fleet installer + Pinned installer and recipe + Machine and disk identity check + + + Write golden image + Verify artifact digest + Return target-disk evidence + + + + DELEGATED CUSTOMER PXE + + Proxy admitted endpoint + Pinned origin, trust, credentials + Record served boot response + + + Customer installs OS + Customer-owned workflow + Operation-scoped callback + + + + + 6. Revoke PXE and fence executor + Disable delegation, close network capability, + and prove the previous worker cannot continue + + + + + + 7. Boot local disk + Provider executor controls BMC + + + 8. Validate evidence + Mode-specific assurance + + + 9. Project status + Ready only after required proof + + + + + + + Unknown outcome + Retain allocation; recover + + timeout, lost response, stale worker + diff --git a/docs/enhancements/pxe-installation/diagrams/user-journeys.svg b/docs/enhancements/pxe-installation/diagrams/user-journeys.svg new file mode 100644 index 00000000..ef98de05 --- /dev/null +++ b/docs/enhancements/pxe-installation/diagrams/user-journeys.svg @@ -0,0 +1,115 @@ + + Managed image and delegated PXE user journeys + Two swimlanes show a customer requesting a managed golden image or supplying a PXE endpoint. Fleet admits each request, the selected location performs bounded boot work, and the machine returns to local boot before Fleet reports completion. + + + + + + + + + Two customer journeys, one Fleet lifecycle + + + + + + + + + + CUSTOMER + FLEET MANAGEMENT + SELECTED CELL + INSTALLER OWNER + MACHINE + + Managed golden image + + + Select image + Create immutable + Installation + + + Admit request + Pin image and authority; + target and prior state + + + Prepare and boot + Network ready; one-time PXE; + provider power operation + + + Fleet installer + Write and verify + golden image + + + Boot local disk + Return required + first-boot evidence + + + + + + + + Validate evidence + Project Ready status + + + Receive result + Qualified image installed + + Delegated customer PXE + + + Supply endpoint + URL, trust, credentials, + workflow correlation + + + Admit delegation + Check class policy; + pin endpoint and target + + + Prepare and chain + One-machine PXE session; + proxy admitted endpoint + + + Customer installer + Install chosen OS; + send scoped callback + + + Boot local disk + PXE delegation revoked; + local boot observed + + + + + + + + Validate evidence + Report delegated assurance + + + Receive result + Contract complete; OS opaque + From 84cefb742f72a92728d1d755e839e4be800bddcb Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sat, 14 Nov 2026 11:58:23 -0600 Subject: [PATCH 002/518] docs: align PXE authority with offerings and BMC lifecycle --- docs/architecture/README.md | 30 ++- docs/architecture/design.md | 26 ++- docs/enhancements/machine-lifecycle/README.md | 183 +++++++++------- .../machine-lifecycle/acceptance-tests.md | 9 +- .../machine-lifecycle/api-examples.md | 133 +++++++----- .../diagrams/public-resources.svg | 13 +- docs/enhancements/pxe-installation/README.md | 196 +++++++++++++++--- .../diagrams/architecture.svg | 25 ++- .../diagrams/installation-workflows.svg | 17 +- .../diagrams/user-journeys.svg | 14 +- 10 files changed, 459 insertions(+), 187 deletions(-) diff --git a/docs/architecture/README.md b/docs/architecture/README.md index 510c6d48..4d305dfe 100644 --- a/docs/architecture/README.md +++ b/docs/architecture/README.md @@ -58,6 +58,7 @@ processes or service-catalog entries. | Group | Resources and responsibility | Status | | --- | --- | --- | | `metal.datumapis.com` | `MachineClass`: offerings and consumer references. `MachineProfile`: hardware requirements. `MachineCapacity`: provider supply. `Machine`: customer allocation and runtime intent. `MachineAllocation`: protected allocation identity. `Installation`: immutable OS installation or reinstall request. | Six alpha CRDs at `v1alpha1`. Production admission and real providers remain incomplete. | +| `provider.metal.datumapis.com` | Proposed `MachineOffering` owns installation/management capability policy; `MachineOfferingAssignment` controls acquisition access. MachineClass becomes only a one-hop published consumer view; MachineProfile remains immutable requirements in Metal. | Proposed target design, not implemented by the six alpha CRDs above. | | `fleet.datumapis.com` | Physical inventory: `Facility`, `Rack`, `DeviceClaim`, `Device`, `Cable`, and `PowerFeed`. Physical preparation and provider execution remain operator responsibilities. | Proposed inventory APIs; no physical inventory CRDs or real provider executor are implemented here. | | `coordination.fleet.datumapis.com` | Intended management-to-location execution handoff, retaining exact allocation identity, location, admitted inputs, release intent, and execution evidence. `MachineAllocationHandoff` is a candidate resource. | Architecture decision only on the current main implementation: no coordination CRD or cell controller is packaged. Replaces the earlier prototype name `internal.fleet.datumapis.com`. | @@ -73,6 +74,18 @@ and Installation identifies an OS incarnation. Managed NodeClaim identity stays above allocation. These identities and lifetimes remain separate. Standalone and managed consumers use the same allocator and installation contract. +Metal is the common public contract, independent of provider implementation. +Fleet is optional for fulfillment. Allocations retain accepted offering identity, +contract/profile and installation/management capabilities. Catalog or assignment +withdrawal blocks new allocations, not retained runtime rights. Current action, +image, secret and endpoint permissions and explicit safety/suspension controls +still apply; cleanup uses retained obligations rather than acquisition grants. +The [PXE design](../enhancements/pxe-installation/README.md) defines the proposed +immutable managedImage/delegatedPXE union, exclusive execution drivers, and +completion assurance. Managed consumers require qualified assurance, not merely +an Installation Ready condition. These changes specify the target design without +compatibility or migration machinery for earlier drafts. + The broader proposals describe managed clusters, node services, image catalogs, and OS policy. Their implementation and final group placement remain separate design work. Vendor and OS adapters may retain typed groups; this document does @@ -87,18 +100,23 @@ not create additional service registrations for them. | Protected allocation custody | Service-owned private storage | The allocator retains exact identities, authority, and cleanup obligations before effects. | | Fleet physical inventory | Intended operator/provider infrastructure control planes | Inventory and provider controllers own their respective facts and execution contracts; exact scopes and deployment remain proposed. | | Coordination intent | Intended Karmada federation hub | Management writes admitted handoff intent. | -| Coordination replicas and execution | Intended selected location/cell | Federation delivers intent; the cell executes location work and reports status directly to the hub. | +| Coordination replicas and execution | Intended selected location/cell | Federation delivers intent; the cell executes location work and writes cell-local results only. | +| Reflected execution results | Intended Karmada federation hub | Karmada reflects results from the selected cell; management validates them before public projection. | The coordination design requires its CRD on the federation hub and participating cells, not in customer Milo project control planes. Management owns handoff -intent and the selected cell owns execution status. The management process's -deployment cluster is not implicitly the authoritative handoff store. +intent; the selected cell owns local execution results, and Karmada alone reflects +them to the hub. Cells receive no hub or consumer-project API credentials. The +management process's deployment cluster is not implicitly the authoritative handoff store. Management retains admission and reservation authority before creating a handoff. Federation targets the selected location, and the cell asks networking -to prepare the admitted interfaces. Current location evidence is projected into -the customer's Metal resource. Release requires verified location cleanup before -provider cleanup and quota settlement complete. Missing, stale, or uncertain +to prepare the admitted interfaces. The status path is cell-local result -> +Karmada reflection -> management validation -> public projection. Validation checks +selected cell, allocation, operation identity/revision, executor fence, and evidence +freshness. Wrong-cell, stale, conflicting, or partition-delayed results cannot +advance readiness; reflected status itself is not authority. Release requires +verified location cleanup before provider cleanup and quota settlement complete. Missing, stale, or uncertain execution evidence remains unknown. Networking/IPAM and Galactic retain authority over attachments, addresses, diff --git a/docs/architecture/design.md b/docs/architecture/design.md index 125d7209..21082fb8 100644 --- a/docs/architecture/design.md +++ b/docs/architecture/design.md @@ -37,7 +37,7 @@ All names below describe proposed resources, not implemented schemas. | Subsystem | Responsibilities and principal resources | | --- | --- | | Inventory | `Facility`, `Rack`, `DeviceClaim`, `Device`, `Cable`, and `PowerFeed`: approved installation plans, actual assets, physical reservations, and verification evidence. | -| Capacity publication | Provider `MachineClass` definitions and consumer-local references; discovery and safe summaries through service enablement and IAM. Publication does not reserve capacity or grant source-use permission. | +| Capacity publication | Provider `MachineOffering` owns capability policy; `MachineOfferingAssignment` grants acquisition access; consumer `MachineClass` is a one-hop published view. `MachineProfile` contains immutable requirements. Publication does not reserve capacity or grant runtime authority. | | Machine allocation | Provider `MachineCapacity`, customer `Machine`, and private `MachineAllocation`: exclusive reservation, admission of consumer operations, activation, and release across provider and consumer projects. | | Bare-metal provisioning | Typed provider resources and adapters: execute admitted preparation, installation, power, console, and cleanup operations against exact assets. Backend workflows remain private. | | OS configuration | `MachineImage`, `InterfaceClass`, `Installation`, and `OSConfigPolicy`: approved artifacts, immutable installation requests, configuration composition, and one selected executor per incarnation. | @@ -57,6 +57,21 @@ logical attachments, address allocation, and switch configuration. Galactic owns fabric and routing intent. DNS, certificates, and service addresses stay with their owning services. Fleet consumes these contracts and their evidence. +The [PXE enhancement](../enhancements/pxe-installation/README.md) defines the target +Metal installation contract, with Fleet as an optional provider implementation. +It supersedes older image-only examples for current design work without rewriting +the pinned source history. Installation has exactly one managedImage/delegatedPXE +source, consumes its predecessor atomically, and retains explicit completion mode, +assurance and one execution driver. Provisioning Redfish sessions attach to that +admitted operation, never independent boot authority. Installation, runtime power, +and release share serialization/fencing; session closure or callbacks do not prove +executor shutdown. Managed consumers require QualifiedImage assurance. + +For Fleet execution, management writes hub intent, the selected cell writes only +local results, Karmada reflects them, management validates exact identity, fence +and freshness, and the projector publishes public status. Cells have no hub +credentials. Partitions or uncertain results never imply readiness or settlement. + ## Lifecycle and authority contracts 1. **Preserve distinct identities.** DeviceClaim describes an approved physical @@ -72,15 +87,20 @@ their owning services. Fleet consumes these contracts and their evidence. 3. **Use one allocator.** Standalone consumers and managed clusters compete through the same durable reservation protocol. Create one immutable, terminal MachineAllocation between the customer Machine and provider MachineCapacity; - retain current authorization, quota holds, class revisions, and local source + retain current authorization, quota holds, accepted offering identity and + contract/profile, installation/management capabilities, and local source object identity as private admission evidence. Names, not cross-control-plane Kubernetes UIDs, are authored references. Overlapping classes must not duplicate supply. 4. **Separate discovery from authorization.** Consumer MachineClasses reference a - provider definition in one hop. Check current source-use permission, + provider MachineOffering in one hop. Check effective acquisition assignment, + current source-use permission, entitlement, quota, and placement feasibility at allocation commit. A copied reference, cached status, namespace, or privileged controller identity is not proof of consumer access. + Withdrawal blocks new allocations, not retained runtime rights. Reinstall uses + retained capabilities plus current install/image/secret/endpoint permissions + and explicit safety/suspension checks. Cleanup retains authority independently. 5. **Persist exact inputs before effects.** Retain admitted plans, artifacts, digests, target identities, predecessor preconditions, execution authority, and operation correlation. Timeouts mean unknown outcomes; recover the existing diff --git a/docs/enhancements/machine-lifecycle/README.md b/docs/enhancements/machine-lifecycle/README.md index 651e968d..86bcea6b 100644 --- a/docs/enhancements/machine-lifecycle/README.md +++ b/docs/enhancements/machine-lifecycle/README.md @@ -38,9 +38,9 @@ stage: alpha ## Summary -Fleet will let consumers allocate and install machines in their project. -Five public resources define the contract: `MachineClass`, `MachineProfile`, -`MachineCapacity`, `Machine`, and `Installation`. Fleet keeps immutable +Metal defines the common public contract; Fleet is an optional provider +implementation. Consumers use `MachineClass`, `MachineProfile`, `Machine`, and +`Installation`; providers expose supply through `MachineCapacity`. Fleet keeps immutable allocation and operation records in the provider project. These internal records retain ownership, execution authority, exact inputs, and cleanup obligations. @@ -126,7 +126,9 @@ machine. Deleting a completed Installation leaves the OS and allocation in place ### Resource relationships across projects -Classes describe provider offerings; profiles describe hardware requirements. +MachineOffering owns provider policy; MachineClass publishes its consumer view. +MachineOfferingAssignment controls acquisition access; profiles contain immutable +hardware requirements, not installation or management policy. An offering can support several profiles, and a profile can serve several offerings. Consumers can define custom profiles where the offering permits them. @@ -192,61 +194,57 @@ not copy an opaque revision, UID, or epoch between requests. #### MachineClass -Provider operators own definitions; the publication service owns consumer -references. The example uses provider types from the -[bare-metal proposal][allocation]. +Provider operators own `MachineOffering` in `provider.metal.datumapis.com`; +MachineClass is a publisher-owned one-hop consumer view, never a provider policy +definition. MachineOfferingAssignment controls acquisition access. These proposed +contracts replace earlier draft shapes without migration or compatibility rules; +they do not describe the current alpha CRD implementation. ```yaml -apiVersion: metal.datumapis.com/v1alpha1 -kind: MachineClass -# Classes span the provider project so namespaces can share an offering. +apiVersion: provider.metal.datumapis.com/v1alpha1 +kind: MachineOffering metadata: name: standard-metal -# The definition owns offering policy; profiles own hardware requirements. -# Its mode cannot change after creation. spec: - # Named profiles select provider-local contracts by name. - # Fleet retains their resolved identities internally. - # Custom profiles default to disabled and require provider validation. profilePolicy: allowedProfiles: - name: accelerated-16c-64g customProfiles: enabled: false - - # Access describes supported operations, not permission to perform them. - # The first implementation supports power control but no console sessions. - access: - consoleModes: [] - powerControl: true - - # Capacity limits selection to existing supply in one provider namespace. - # Labels identify candidates; they confer no eligibility or purchase authority. - capacity: - machineCapacities: - namespace: infra-ops - selector: - matchLabels: - fleet.datumapis.com/capacity-pool: general-metal - - # Provider backend qualification and BMC enrollment are private cell state. - # Public classes select admitted capacity, not an implementation-specific CRD. - -# The projector reports the definition that the class evaluator accepted. -# Acceptance validates the offering; it does not reserve or promise capacity. + capabilities: + installation: + sourceModes: [ManagedImage, DelegatedPXE] + executionDrivers: [ProviderAutomatic, CustomerRedfish] + completionContracts: + - {mode: VerifiedImage, assurance: QualifiedImage} + - {mode: CustomerCallback, assurance: DelegatedContract} + management: + profiles: [ReadOnly, Provisioning] + provisioningSteps: [OneTimePXE, Reset, LocalDisk] + powerControl: true status: - evaluatedRevision: class-revision-example + evaluatedRevision: offering-revision-example conditions: - - {type: Accepted, status: "True"} + - type: Accepted + status: "True" + observedGeneration: 1 + lastTransitionTime: "2026-11-14T12:00:00Z" + reason: OfferingValid + message: "Profile and capability contracts accepted; no capacity reserved." ``` +The offering is a portable service promise. Fleet inventory selectors, executor +configuration, and BMC enrollment belong to private provider implementation state, +not MachineOffering. The permitted source/driver/completion combinations and +management steps follow the [PXE contract](../pxe-installation/README.md). + An offering must allow named profiles, custom profiles, or both. Enabling custom profiles still requires provider validation of the complete configuration at the requested location. Approval applies to a profile's lifetime. A missing or recreated profile blocks its entry. The provider must select a new name or remove and re-add the entry in -separate accepted class revisions to approve a replacement. +separate accepted offering revisions to approve a replacement. Publication, quota, image, and network policy remain separate from the definition. The publication service creates the consumer reference: @@ -262,6 +260,8 @@ metadata: # cannot become a definition or override its policy. spec: source: + apiGroup: provider.metal.datumapis.com + kind: MachineOffering project: provider name: standard-metal @@ -270,8 +270,8 @@ spec: status: # The revision identifies the evaluated offering independently of this # reference object's generation. It does not grant source-use permission. - evaluatedRevision: class-revision-example - resolvedClass: + evaluatedRevision: offering-revision-example + resolvedOffering: # Publication maps allowed provider profiles to protected local copies. # These local names do not expose provider inventory or grant use. profilePolicy: @@ -279,15 +279,19 @@ status: - name: accelerated-16c-64g customProfiles: enabled: false - access: - consoleModes: [] - powerControl: true + capabilities: + installation: + sourceModes: [ManagedImage, DelegatedPXE] + executionDrivers: [ProviderAutomatic, CustomerRedfish] + management: + profiles: [ReadOnly, Provisioning] + powerControl: true conditions: - {type: SourceResolved, status: "True"} ``` -Resolution follows one hop to a definition and rejects cycles, chains, and mixed -modes. Fleet checks current offering policy and authorization at Machine admission; +Resolution follows one hop to MachineOffering and rejects cycles, chains, and +consumer-authored policy overrides. Fleet checks current offering policy and authorization at Machine admission; accepted Machines retain the source identities, revision, and requirements through later edits. [Publication and access rules](#authorization-and-publication) control who receives and may use an offering. @@ -629,11 +633,15 @@ dispatch new work. A named profile must be the provider-approved profile or its protected published copy. Matching names or requirements do not establish that relationship. Other profiles take the custom path, including profiles from another provider. The -class must permit custom profiles, the adapter must accept the complete +offering must permit custom profiles, the adapter must accept the complete configuration, and published sources still require use permission. -A MachineAllocation retains its accepted requirements and hardware snapshot through source -changes or deletion. Later observations can change readiness, but a bound Machine +A MachineAllocation retains the accepted offering identity and contract, immutable +profile requirements, installation/management capabilities, and hardware snapshot +through source changes or deletion. Offering/assignment withdrawal blocks new +allocations, not retained runtime rights; reinstall still checks current action, +image, secret and endpoint permissions and explicit safety/suspension controls. +Cleanup remains authorized by retained obligations, even after withdrawal. Later observations can change readiness, but a bound Machine never moves to another Machine. Owner references cannot replace Fleet's release protocol. @@ -726,23 +734,28 @@ metadata: name: example-os-1 namespace: default # The entire spec is immutable so recovery uses the same authorized inputs. -# Machine and approved image are required. Fleet checks install and image-use -# permissions and internally pins the Machine lifetime, image artifacts, and digests. spec: machineRef: {name: example} # This required precondition prevents competing installs from replacing # an unexpected OS. None identifies a blank allocation with no admitted install. expectedPredecessor: type: None - imageRef: {name: qualified-linux} - - # Optional bootstrap data comes from a Secret in this namespace under - # explicit caller authority. Protected copies of its identity, digest, and bytes - # preserve the accepted input through Secret changes or deletion. - bootstrapConfigRef: {name: example-bootstrap} + source: + managedImage: + imageRef: {name: qualified-linux} + bootstrapConfigRef: {name: example-bootstrap} + execution: + driver: ProviderAutomatic + completion: + mode: VerifiedImage + requiredAssurance: QualifiedImage + postCompletionBoot: LocalDisk # The projector reports the retained installation outcome, not guest health. status: + sourceMode: ManagedImage + completionMode: VerifiedImage + assurance: QualifiedImage completedAt: "2026-10-27T12:00:00Z" conditions: - {type: Accepted, status: "True"} @@ -750,6 +763,27 @@ status: - {type: Ready, status: "True"} ``` +Exactly one non-null `source.managedImage` or `source.delegatedPXE` is required; +both, neither, and mixed member fields are invalid. The entire spec, including +predecessor, driver, and explicit completion mode/required assurance, is immutable. +The [delegated example](api-examples.md#delegated-pxe-installation) uses the same +allocation and predecessor rules. ManagedImage requires VerifiedImage / +QualifiedImage; delegated PXE initially supports CustomerCallback / +DelegatedContract only, with LocalDisk completion for both. Pending or unknown +work has no achieved assurance. Ready describes completion of this explicit +contract, not guest health. Managed consumers must require QualifiedImage at +admission and activation/join (including initial-installation gates); delegated +Ready cannot satisfy them. + +A provisioning-profile management session must bind an already admitted +Installation and its exact operation. ProviderAutomatic and CustomerRedfish are +mutually exclusive drivers, not independent boot authorities. CustomerRedfish is +initially permitted only for delegated PXE. Sessions, automatic PXE, runtime power, +and release share per-allocation serialization and provider fencing. Session +closure and callbacks do not prove a running installer stopped. Independent +executor fencing, PXE/network revocation, and local boot evidence are mandatory; +unknown work holds the allocation. See the [shared BMC execution contract](../pxe-installation/README.md#shared-bmc-and-installation-execution). + A reinstall names the Machine's current `status.currentInstallationRef` in `spec.expectedPredecessor`: @@ -766,7 +800,7 @@ with one nonempty name. `None` is valid only for a verified blank allocation tha has never admitted an installation. Fleet resolves the named predecessor in the same project and namespace and privately pins its exact incarnation and allocation; name reuse cannot replace it. A predecessor reference does not replace install or -image-use permission. +the current permissions required by the selected installation source. Admission atomically consumes the precondition and retains the operation before effects. Only one request can win. A retry of that request recovers its retained @@ -828,9 +862,10 @@ Each resource defines its conditions: - **MachineProfile:** `Accepted` validates structure without promising class compatibility, authorization, or supply. -- **MachineClass:** `Accepted` requires a resolved profile policy and provider - contract. `SourceResolved` requires an authorized, resolved definition. Neither - condition promises capacity or grants every reader source-use permission. +- **MachineOffering:** `Accepted` validates provider profile and capability policy; + it neither reserves capacity nor grants acquisition access. +- **MachineClass:** `SourceResolved` requires an authorized, resolved one-hop + offering. It promises neither capacity nor source-use permission to every reader. - **Machine:** `Prepared` requires preparation evidence; `Healthy` requires health evidence. `Available` also requires eligible policy and no live allocation or cleanup obligation. @@ -843,7 +878,9 @@ Each resource defines its conditions: remains true until cleanup and quota release finish. - **Installation:** `Accepted` requires an admitted operation with exact inputs. `Executing=False` alone cannot establish success. `Ready=True` and `completedAt` - require verified installation and platform handoff, not guest health. Verified + require the explicit completion contract, achieved assurance, executor fencing, + and platform handoff, not guest health. Managed consumers require QualifiedImage + even when a delegated Installation is Ready. Verified failure or cancellation yields `Ready=False`; an uncertain outcome yields `Unknown`. @@ -933,7 +970,8 @@ The initial deployment accepts enrollment only from operator-controlled provider #### Request authority Machine admission checks the initiating principal's local create permission, -provider-project `machineclasses.use`, and local `machineprofiles.use`. Published +provider-project `machineofferings.use` and effective acquisition access through +MachineOfferingAssignment, and local `machineprofiles.use`. Published profiles also require `machineprofiles.use` on their canonical provider source; custom profiles require no provider-profile grant. Cross-project checks preserve the caller and change only the target scope, as the [IPClass checker][ipam-class-use] @@ -953,8 +991,10 @@ use current Machine permissions and the retained contract; the creator's departu does not reclaim the machine. Each action needs separate admission. Installations require Machine `install`, -image-use permission, and access to bootstrap input. Power changes retain their -own caller and generation. Network resolution checks the caller's network-use +image-use permission for managed images, and current secret/endpoint permissions +for their selected source. They use retained capabilities rather than reacquiring +a withdrawn offering or assignment; explicit safety/suspension still applies. +Power changes retain their own caller and generation. Network resolution checks the caller's network-use permission in each selected namespace and the required address authority. These checks are Fleet integration requirements, not permissions granted by references. @@ -970,7 +1010,7 @@ The following are protected service records, not fields a customer authors: ```text (consumer project, local class name + private incarnation evidence) - -> (provider project, definition name + private incarnation evidence, contract digest) + -> (provider project, MachineOffering name + private incarnation evidence, contract digest) (consumer project, local profile name + private incarnation evidence) -> (provider project, source profile name + private incarnation evidence, requirements) ``` @@ -1001,8 +1041,9 @@ Retain the following information: - **Identity:** immutable `metadata.name`, state, consumer and provider project context, customer Machine and provider MachineCapacity names, their private object-incarnation evidence, request digest, and canonical asset identity. -- **Accepted contract:** class and local/source profile names with private - incarnation evidence and contract digests, exact +- **Accepted contract:** offering identity, accepted contract revision and + installation/management capabilities, class publication provenance, and + local/source profile names with private incarnation evidence and digests, exact requirements, dependency identities/content, provider configuration/catalog revision, hardware snapshot, and logical-to-physical device mapping. - **Authority:** authenticated principal, authorization decision, @@ -1186,8 +1227,10 @@ sessions. Lifecycle integration must handle these triggers: - **Project or entitlement suspension:** Deny new allocations, installations, and consumer power actions. Bring committed work to a safe boundary and allow authorized release without automatically wiping active machines. -- **Class/profile withdrawal or Machine disablement:** Block future allocations, - preserve active contracts, and admit reclaim separately. +- **Offering/assignment/profile withdrawal or capacity disablement:** Block future + allocations, preserve active contracts and retained runtime capabilities, and + admit reclaim separately. Runtime safety/suspension is an explicit control, not + an inference from catalog withdrawal; cleanup remains authorized. Milo's [project controller][milo-cleanup] waits for cleanup before reclaiming the control plane, while [suspension admission][milo-suspension] permits deletes and diff --git a/docs/enhancements/machine-lifecycle/acceptance-tests.md b/docs/enhancements/machine-lifecycle/acceptance-tests.md index b611e74a..cab606be 100644 --- a/docs/enhancements/machine-lifecycle/acceptance-tests.md +++ b/docs/enhancements/machine-lifecycle/acceptance-tests.md @@ -2,6 +2,13 @@ Required validation for the [machine lifecycle contract](README.md). +The proposed PXE/Redfish extension additionally requires the concrete +[cross-system acceptance scenarios](../pxe-installation/README.md#acceptance-tests): +competing boot/power/release operations, session closure with a live installer, +offering withdrawal followed by reinstall, hub/cell partitions and stale reflected +results, and managed-consumer assurance enforcement. These scenarios are not +implemented or executed by this documentation change. + Implement the following tests through Milo tenancy, IAM, entitlement, and quota. No implementation tests exist yet. @@ -25,7 +32,7 @@ component, lose responses, and delay old workers to verify recovery. - **Consumer copies a named profile or reuses its name:** Require the custom path or protected publication provenance; reject lifetime substitution. - **Provider recreates an allowed profile under the same name:** Block use until - the provider removes and re-adds the entry in separate accepted class revisions, + the provider removes and re-adds the entry in separate accepted offering revisions, or selects a new name. An unrelated class edit cannot renew approval. - **Custom profiles are disabled, unsupported, or temporarily unverifiable:** Report the specific admission result without reserving capacity or purchasing. diff --git a/docs/enhancements/machine-lifecycle/api-examples.md b/docs/enhancements/machine-lifecycle/api-examples.md index 706484a1..d9b9ce5c 100644 --- a/docs/enhancements/machine-lifecycle/api-examples.md +++ b/docs/enhancements/machine-lifecycle/api-examples.md @@ -5,67 +5,52 @@ They show different lifecycle points, not one simultaneous observation. Names, identifiers, and timestamps are synthetic. They define no implemented APIs or production timing requirements. The enhancement owns field semantics and lifecycle rules. -- [Provider MachineClass](#provider-machineclass) +- [Provider MachineOffering](#provider-machineoffering) - [Consumer MachineClass](#consumer-machineclass) - [MachineProfile](#machineprofile) - [MachineCapacity](#machinecapacity) - [Machine](#machine) - [Installation](#installation) +- [Delegated PXE Installation](#delegated-pxe-installation) - [Reinstallation predecessor](#reinstallation-predecessor) The exact MachineProfile CPU and memory shape, `Machine.status.requestedHardware`, and the `RequestResolved` condition are implemented; the rest of these responses remain proposed. -## Provider MachineClass +## Provider MachineOffering ```yaml -apiVersion: metal.datumapis.com/v1alpha1 -kind: MachineClass -# Classes span the provider project so namespaces can share an offering. +apiVersion: provider.metal.datumapis.com/v1alpha1 +kind: MachineOffering metadata: - generation: 1 name: standard-metal -# The definition owns offering policy; profiles own hardware requirements. -# Its mode cannot change after creation. spec: - # Named profiles select provider-local contracts by name. - # Fleet retains their resolved identities internally. - # Custom profiles default to disabled and require provider validation. profilePolicy: allowedProfiles: - name: accelerated-16c-64g customProfiles: enabled: false - - # Access describes supported operations, not permission to perform them. - # The first implementation supports power control but no console sessions. - access: - consoleModes: [] - powerControl: true - - # Capacity limits selection to existing supply in one provider namespace. - # Labels identify candidates; they confer no eligibility or purchase authority. - capacity: - machineCapacities: - namespace: infra-ops - selector: - matchLabels: - fleet.datumapis.com/capacity-pool: general-metal - - # Provider backend qualification and BMC enrollment are private cell state. - -# The projector reports the definition that the class evaluator accepted. -# Acceptance validates the offering; it does not reserve or promise capacity. + capabilities: + installation: + sourceModes: [ManagedImage, DelegatedPXE] + executionDrivers: [ProviderAutomatic, CustomerRedfish] + completionContracts: + - {mode: VerifiedImage, assurance: QualifiedImage} + - {mode: CustomerCallback, assurance: DelegatedContract} + management: + profiles: [ReadOnly, Provisioning] + provisioningSteps: [OneTimePXE, Reset, LocalDisk] + powerControl: true status: - evaluatedRevision: class-revision-example + evaluatedRevision: offering-revision-example conditions: - type: Accepted status: "True" observedGeneration: 1 - lastTransitionTime: "2026-10-27T12:00:00Z" - reason: DefinitionValid - message: "Profile policy and provider contract resolved." + lastTransitionTime: "2026-11-14T12:00:00Z" + reason: OfferingValid + message: "Profile and capability contracts accepted; no capacity reserved." ``` ## Consumer MachineClass @@ -82,6 +67,8 @@ metadata: # cannot become a definition or override its policy. spec: source: + apiGroup: provider.metal.datumapis.com + kind: MachineOffering project: provider name: standard-metal @@ -90,8 +77,8 @@ spec: status: # The revision identifies the evaluated offering independently of this # reference object's generation. It does not grant source-use permission. - evaluatedRevision: class-revision-example - resolvedClass: + evaluatedRevision: offering-revision-example + resolvedOffering: # Publication maps allowed provider profiles to protected local copies. # These local names do not expose provider inventory or grant use. profilePolicy: @@ -99,9 +86,13 @@ status: - name: accelerated-16c-64g customProfiles: enabled: false - access: - consoleModes: [] - powerControl: true + capabilities: + installation: + sourceModes: [ManagedImage, DelegatedPXE] + executionDrivers: [ProviderAutomatic, CustomerRedfish] + management: + profiles: [ReadOnly, Provisioning] + powerControl: true conditions: - type: SourceResolved status: "True" @@ -463,8 +454,6 @@ metadata: name: example-os-1 namespace: default # The entire spec is immutable so recovery uses the same authorized inputs. -# Machine and approved image are required. Fleet checks install and image-use -# permissions and internally pins the Machine lifetime, image artifacts, and digests. spec: machineRef: name: example @@ -472,17 +461,22 @@ spec: # an unexpected OS. None identifies a blank allocation with no admitted install. expectedPredecessor: type: None - imageRef: - name: qualified-linux - - # Optional bootstrap data comes from a Secret in this namespace under - # explicit caller authority. Protected copies of its identity, digest, and bytes - # preserve the accepted input through Secret changes or deletion. - bootstrapConfigRef: - name: example-bootstrap + source: + managedImage: + imageRef: {name: qualified-linux} + bootstrapConfigRef: {name: example-bootstrap} + execution: + driver: ProviderAutomatic + completion: + mode: VerifiedImage + requiredAssurance: QualifiedImage + postCompletionBoot: LocalDisk # The projector reports the retained installation outcome, not guest health. status: + sourceMode: ManagedImage + completionMode: VerifiedImage + assurance: QualifiedImage completedAt: "2026-10-27T12:00:00Z" conditions: - type: Accepted @@ -523,3 +517,42 @@ expectedPredecessor: type: Installation name: example-os-1 ``` + +## Delegated PXE Installation + +This alternative successor uses the same retained allocation and consumes its +predecessor atomically. It cannot run concurrently with another installation. +The source union, execution driver, and completion contract are immutable. A +provisioning session may attach only after this request is admitted; it cannot +change its endpoint or create another boot operation. Required assurance is not +achieved assurance: pending/unknown status must not claim DelegatedContract. + +```yaml +apiVersion: metal.datumapis.com/v1alpha1 +kind: Installation +metadata: + name: example-os-2 + namespace: default +spec: + machineRef: {name: example} + expectedPredecessor: {type: Installation, name: example-os-1} + source: + delegatedPXE: + endpoint: + url: https://pxe.customer.example/boot.ipxe + trustBundleRef: {name: customer-pxe-ca} + authorizationRef: {name: customer-pxe-credentials} + execution: + driver: CustomerRedfish + completion: + mode: CustomerCallback + requiredAssurance: DelegatedContract + postCompletionBoot: LocalDisk +``` + +After independently verified executor shutdown, PXE/network revocation, local +boot, and management validation of the reflected result, status may report +`sourceMode: DelegatedPXE`, `completionMode: CustomerCallback`, +`assurance: DelegatedContract`, and `Ready=True`. Neither the callback nor session +closure proves shutdown. Managed consumers requiring QualifiedImage reject this +contract and cannot use its Ready condition to open their activation/join gate. diff --git a/docs/enhancements/machine-lifecycle/diagrams/public-resources.svg b/docs/enhancements/machine-lifecycle/diagrams/public-resources.svg index 172d1c76..2b223aa1 100644 --- a/docs/enhancements/machine-lifecycle/diagrams/public-resources.svg +++ b/docs/enhancements/machine-lifecycle/diagrams/public-resources.svg @@ -1,6 +1,6 @@ Public resources across project boundaries - A consumer Machine references a project-wide MachineClass and MachineProfile. Its Installation references the Machine. Each requested interface selects an existing networking.datumapis.com Network in the consumer project. Networking owns its Galactic VPC realization; MachineCapacity remains in the provider project. The local class references a provider definition, which selects provider MachineCapacity and permits named profiles. A dashed arrow shows publication of a provider profile as a protected consumer copy. Public references use scoped names; object-incarnation evidence remains private. Reinstallation names the current Installation as a precondition. + A consumer Machine references a project-wide MachineClass and MachineProfile. Its immutable Installation references the Machine and selects exactly one managedImage or delegatedPXE source with explicit completion and assurance. Each requested interface selects an existing networking.datumapis.com Network in the consumer project. Networking owns its Galactic VPC realization; MachineCapacity remains in the provider project. The local class references a provider MachineOffering, which owns capabilities and permits named profiles. MachineOfferingAssignment grants acquisition access. Fleet capacity selection is private provider implementation state. A dashed arrow shows publication of a provider profile as a protected consumer copy. Public references use scoped names; object-incarnation evidence remains private. Reinstallation names the current Installation as a precondition. @@ -23,8 +23,8 @@ MachineClass Local reference - MachineClass - Offering definition + MachineOffering + Capabilities / provider.metal MachineProfile Published or custom @@ -44,7 +44,9 @@ Machine - Installation + Installation + managedImage | delegatedPXE + Explicit completion + assurance MachineCapacity @@ -59,7 +61,8 @@ network name - selects + private fulfillment + Assignment grants acquisition, not boot. Capacity stays in the provider project. diff --git a/docs/enhancements/pxe-installation/README.md b/docs/enhancements/pxe-installation/README.md index f911a507..faabba4d 100644 --- a/docs/enhancements/pxe-installation/README.md +++ b/docs/enhancements/pxe-installation/README.md @@ -16,6 +16,7 @@ stage: alpha - [Control-plane placement](#control-plane-placement) - [API design](#api-design) - [Admission and authority](#admission-and-authority) + - [Shared BMC and installation execution](#shared-bmc-and-installation-execution) - [Location execution](#location-execution) - [Completion and evidence](#completion-and-evidence) - [Release and recovery](#release-and-recovery) @@ -29,12 +30,30 @@ stage: alpha ## Summary -Fleet will support two ways to install an allocated bare-metal machine. Fleet can +Metal defines the common public installation contract; Fleet is an optional +provider implementation, not a prerequisite for publishing or consuming it. +This proposal describes two ways to install an allocated bare-metal machine. Fleet can automatically install a platform-approved golden image, or it can temporarily chain the machine to a customer-supplied PXE service. Both paths use the same immutable `Installation`, allocation, federation handoff, power, boot fencing, and release contracts. +All behavior below is proposed, not implemented or hardware-qualified. These are +target contracts, with no compatibility or migration requirement for earlier +draft shapes. The [canonical lifecycle design](../machine-lifecycle/README.md) +and [examples](../machine-lifecycle/api-examples.md) use the same source union. + +Companion review on 2026-11-14 used [BMC #41](https://github.com/datum-cloud/fleet/pull/41) +at `b72c314624bd0b05849059815619c9783607818c`, +[control planes #51](https://github.com/datum-cloud/fleet/pull/51) at +`16e7cb2a268cf20bc58d490493b5a3fef9237027`, and +[offerings #58](https://github.com/datum-cloud/fleet/pull/58) at +`031477d011090ea6ec378d526e975bbfae07a060`. The decisions here replace those drafts' +provider MachineClass policy, direct cell-to-hub status writing, and independent +provisioning-session boot authority where they differ. Companion branches must +converge on these contracts; this PR does not edit their branches or rewrite the +[pinned source provenance](../../proposals/fleet-management/MIGRATION.md). + The Fleet management control plane admits the exact operation before any effect. The Federation Control Plane delivers that operation to one selected location control plane. The location prepares networking, controls one-time network boot, @@ -87,7 +106,7 @@ understand each customer installer would create an unnecessary backend contract. without operating a provisioning service. - A customer with an existing PXE service installs its own operating system on an allocated machine while Fleet retains power and boot control. -- A provider controls which MachineClasses permit managed images or delegated PXE. +- A provider controls installation and management capabilities on MachineOffering. - An operator can recover a lost response without repeating a destructive action or exposing uncertain capacity to another customer. @@ -105,10 +124,22 @@ An Installation has exactly one source: | `ManagedImage` | Fleet resolves a platform-approved image and qualified recipe. | Exact image and recipe, target disk evidence, boot fencing, and required first-boot evidence. | | `DelegatedPXE` | The customer supplies a PXE endpoint and controls its installer. | Exact delegation target, boot session, customer result, boot fencing, and the configured post-install boot observation. | -MachineClass policy advertises supported modes. It does not grant permission to -use them. Fleet checks current source-use authority, allocation identity, class -revision, endpoint policy, networking feasibility, and predecessor state when it -admits each Installation. +`MachineOffering` in `provider.metal.datumapis.com` owns installation and +management capability policy. `MachineClass` in `metal.datumapis.com` is only a +consumer-published, one-hop view of that offering. `MachineOfferingAssignment` +grants acquisition access, not runtime boot authority. `MachineProfile` contains +immutable hardware requirements, never installation, management, or audience policy. + +Allocation retains the accepted offering identity and contract revision, exact +profile identity and requirements, and installation/management capabilities. +Offering or assignment withdrawal blocks new allocations, not retained runtime +rights. A reinstall uses that retained contract even if the catalog copy or +offering is gone; it cannot acquire capabilities added after allocation. Admission +still checks current Machine install permission, image-use permission for managed +images, secret-use and endpoint permission as applicable, explicit safety or +suspension controls, network feasibility, and predecessor state. Unavailable +authorization is unknown, not permission. Cleanup remains authorized by retained +provider obligations despite withdrawal, suspension, or project deletion. ### Managed golden image @@ -132,8 +163,9 @@ decision point and chains only the admitted machine to the customer endpoint. The customer does not receive BMC credentials or DHCP authority. Its system may install any OS allowed by service policy, then sends an operation-scoped completion -callback. The location revokes delegation, requests local-disk boot, and returns -the evidence required by the Installation contract. +callback. That is only a customer assertion. The location separately proves the +installer stopped, revokes delegation, performs the admitted local-disk transition, +and returns the evidence required by the Installation contract. The first release requires delegated PXE to finish with local-disk boot. A permanently network-booted runtime needs a separate design because it retains boot @@ -147,17 +179,26 @@ The design follows the Fleet management control-plane boundaries: | Boundary | Responsibility | | --- | --- | -| Provider project API | MachineClass policy, MachineCapacity, physical inventory, and provider eligibility. | +| Provider project API | MachineOffering capability policy and MachineOfferingAssignment acquisition access; Fleet-backed providers additionally own MachineCapacity and inventory. | | Consumer project API | Machine and immutable Installation requests and projected status. | | Fleet private storage | Exact allocation, caller authority, admitted inputs, operation journal, credentials, and cleanup custody. | | Fleet management runtime | Admission, allocation coordination, handoff creation, and result validation. | -| Federation hub | Canonical admitted location handoff and cell-owned execution status. | -| Selected location control plane | Network integration, PXE authorization, power, installation execution, fencing, and evidence. | +| Federation hub | Management-authored admitted intent and Karmada-reflected selected-cell results. | +| Selected location control plane | Delivered intent, locally written execution results, network integration, PXE, power, fencing, and evidence. | The Fleet runtime's deployment cluster is not the canonical store for project objects or federation intent. Kubernetes UIDs are local evidence and do not cross project, hub, or cell API boundaries as authored references. +The only status path is management-authored hub intent -> selected-cell delivery +-> cell-local results -> Karmada reflection -> management validation -> public +projection. Cells have no hub or project API credentials. Karmada transports +results, not authority or readiness decisions. Management validates selected-cell +identity, retained operation and revision, allocation, fencing token, and evidence +freshness before projection. Wrong-cell, duplicated, stale, or conflicting results +cannot advance readiness. A partition leaves results pending or unknown; absence +of a result never proves completion or cancellation. + ### API design The following shapes are proposals, not implemented schemas. `Installation.spec` @@ -176,6 +217,12 @@ spec: managedImage: imageRef: {name: qualified-linux} bootstrapConfigRef: {name: example-bootstrap} + execution: + driver: ProviderAutomatic + completion: + mode: VerifiedImage + requiredAssurance: QualifiedImage + postCompletionBoot: LocalDisk ``` A delegated request selects the other union member: @@ -193,18 +240,30 @@ spec: correlation: workflowID: example-workflow-1 templateDigest: sha256:example - completion: - mode: Callback - postCompletionBoot: LocalDisk + execution: + driver: CustomerRedfish + completion: + mode: CustomerCallback + requiredAssurance: DelegatedContract + postCompletionBoot: LocalDisk ``` -The API server applies defaults before Fleet captures the request digest. Fleet +Exactly one non-null `source.managedImage` or `source.delegatedPXE` is required; +both, neither, and fields from the other member are rejected. Source, predecessor, +execution driver, and completion contract are immutable. Completion and assurance +are explicit, not inferred from a callback or `Ready`. ManagedImage requires +`VerifiedImage` and `QualifiedImage`; delegated PXE initially supports only +`CustomerCallback` and `DelegatedContract`. Both require `LocalDisk`. Other +combinations are rejected until a separate qualified evidence contract exists. + +The API server applies any other defaults before Fleet captures the request digest. Fleet resolves referenced Secrets under the caller's authority and retains protected copies needed for recovery. Credentials and rendered bootstrap content do not enter the federation handoff. -MachineClass definitions add policy describing supported installation modes and -boot capabilities. Publication exposes only the permitted summary. The exact +MachineOffering defines allowed source modes, execution drivers, completion and +assurance combinations, and management profiles/Redfish steps. Publication exposes +only the permitted summary through MachineClass; it cannot override the source. The exact provider executor, BMC enrollment, installer recipe, and boot-service configuration remain private location state. @@ -214,17 +273,77 @@ Before dispatch, Fleet retains: - provider and consumer Project identities; - Machine, MachineAllocation, MachineCapacity, and Installation incarnations; -- the MachineClass and MachineProfile revisions; +- the retained MachineOffering identity, accepted contract and capability policy, + MachineClass publication provenance, and immutable MachineProfile requirements; - the consumed predecessor and operation identity; - target location, boot interface, and qualified firmware mode; - image, recipe, bootstrap, endpoint, trust, and credential digests as applicable; -- current IAM, entitlement, quota, and source-use decisions; and +- current action/source permissions and explicit safety/suspension decisions, + plus the allocation's retained acquisition and quota evidence; and - an executor fencing token and required completion evidence. The handoff contains the exact admitted target and non-secret execution inputs or protected capability references. Delivery to a cell is not fresh authorization. The cell cannot select another machine, endpoint, image, or installation mode. +Retain the operation's validity interval and allowed step budget before dispatch. +Disconnected cells may only recover/execute within that retained scope and +validity; expiry prevents new effects but does not prove a running installer +stopped. Renewal is a management decision for the same exact operation, never a +cell-local expansion. Fencing and cleanup continue under retained obligations. + +Admission atomically consumes the exact predecessor with the operation record. +`None` means a verified blank allocation with no previously admitted installation; +otherwise use the current Installation name, resolved to its retained incarnation. +Competing successors cannot both win. Active or uncertain work offers no usable +predecessor. Request deletion, session closure, or a callback does not restore it. +After failure, a successor requires proven fencing and intact prior state; +partial or uncertain effects require recovery of the same operation or release. + +### Shared BMC and installation execution + +A provisioning-profile `MachineManagementSession` must name an already admitted +Installation in the same project/namespace and allocation. Admission privately +binds its exact incarnation, operation, selected cell, fence, driver, and permitted +step set. Missing, foreign, stale, or completed bindings fail closed. A session +cannot create an Installation, select another endpoint or image, or arm independent +boot authority. Read-only observation does not grant provisioning permissions. +Current session create/use permissions and explicit suspension checks still apply; +neither the retained capability nor knowledge of an Installation name grants access. + +Exactly one execution driver is selected at Installation admission. The public +`ProviderAutomatic` name is provider-neutral: Fleet runs the automatic sequence +when Fleet fulfills the offering; another provider implements the same retained +authority and evidence contract without deploying Fleet: + +| Driver | Effect authority | +| --- | --- | +| `ProviderAutomatic` | The provider (Fleet in this design) orders all boot/power steps. Customer provisioning-session writes are rejected; observation may be allowed. | +| `CustomerRedfish` | The customer submits the offering-permitted Redfish steps through a bound provisioning session. The gateway journals and executes only steps of the admitted Installation; Fleet does not run an automatic competing sequence. | + +CustomerRedfish is permitted only for delegated PXE in the initial qualification. +The gateway maps allowed one-time PXE, reset, and local-disk transitions to the +retained plan; arbitrary boot targets, persistent overrides, virtual media, and +unadmitted resets are rejected. Source choice and execution driver are distinct: +delegated PXE may also use ProviderAutomatic. Switching drivers requires settlement +and a new admitted successor, not editing a session. + +All automatic, gateway, runtime power, and release effects share one durable +per-allocation serialization and fencing domain. A provisioning session attaches +to the Installation's reservation, not a second operation authority. Concurrent +sessions cannot duplicate a step. Power intent queues or fails with an explicit +conflict while installation owns the reservation. Release closes new admission, +revokes sessions, and takes over only through verified fencing and settlement; +there is no lock-free emergency reset path. Recovery deduplicates provider steps +using retained operation identity, including after a lost Redfish response. + +Closing or expiring a session revokes access but does not settle an installer +already running in RAM or remotely. A callback proves neither executor shutdown +nor boot revocation. Completion requires independent stop/fence evidence for all +old effect paths, verified PXE/network revocation, and observed local-disk boot. +If those cannot be proven, keep the Installation unknown and capacity occupied. +Safety/release fencing is retained recovery authority, not a second install driver. + ### Location execution A qualified location runs a small platform boot service. Provider DHCP directs @@ -257,10 +376,17 @@ can report the retained operation's result but cannot choose another target, extend authority, request release, or write public status. Managed-image success proves the qualified image and recipe evidence required by -the class. Delegated success normally proves only that Fleet delegated the correct +the retained offering. Delegated success proves only that Fleet delegated the correct machine, the customer reported completion, Fleet revoked the delegation, and the -configured local boot was observed. Public status identifies the result mode and -assurance rather than describing an opaque customer OS as platform verified. +configured local boot was observed, with the old executor demonstrably stopped. +Public status reports `sourceMode`, `completionMode`, and achieved `assurance` +(`QualifiedImage` or `DelegatedContract`), separately from conditions. Pending or +unknown work has no achieved assurance. An opaque customer OS is not platform verified. + +Managed consumers must explicitly require `QualifiedImage` at admission and +activation/join gates; `Ready=True` with `DelegatedContract` cannot satisfy them. +The same rule applies to a Machine's initial-installation gate for that consumer. +There is no callback-based promotion from delegated to qualified assurance. Fleet validates the target, operation revision, fencing token, evidence freshness, and required conditions before setting Installation `Ready=True`. Installation @@ -295,7 +421,8 @@ Qualify one UEFI, Redfish, non-Talos hardware and OS combination. Test both mode through real project admission, federation delivery, networking, and disposable hardware. -Acceptance requires: +These are required cross-system tests, not executed tests in this documentation +PR. In addition to the cases below, acceptance requires: - only the allocated machine can use a boot session; - a managed install writes the retained image and boots from the selected disk; @@ -307,11 +434,23 @@ Acceptance requires: - release cannot expose capacity before network and provider cleanup; and - customer project deletion preserves recovery and cleanup custody. +| Scenario and fault injection | Required observable result | +| --- | --- | +| Submit both/neither source members, mixed fields, an unsupported completion/assurance pair, or a provisioning session without an admitted Installation (including foreign/recreated names). | Reject before effects; no predecessor consumption or boot authority for invalid requests. Session access also requires current create/use permission. | +| Race ProviderAutomatic PXE with a provisioning-session boot override, two successor requests, and runtime power-on. | One predecessor consumption and one install driver; session write rejected, other successor conflicts, power blocked; provider journal has no duplicate or competing effect. | +| CustomerRedfish sends duplicate resets through two sessions; lose the provider response, then recover gateway and Fleet workers. | Both sessions bind the same admitted operation; one retained step is recovered, never blindly replayed. No automatic installer driver starts. | +| Close the provisioning session or send a successful callback while its installer remains active; concurrently release. | No Ready or usable predecessor; release blocks new steps, fences all old paths and verifies cleanup before reuse. Closure/callback alone never settles work. | +| Withdraw offering/assignment and delete the published class after allocation; request a reinstall and a new Machine. | New allocation denied; reinstall retains original offering/profile/capabilities and succeeds only with current install/source permissions. A later offering capability expansion is not inherited. | +| Repeat that reinstall with revoked image/secret/endpoint permission or explicit runtime suspension. | No new install effects; an authorization outage is unknown. Retained cleanup still completes without reacquiring the withdrawn offering. | +| Partition hub from selected cell during boot; expire authority, duplicate delivery, inject wrong-cell and stale-fence results, then reconnect. | Cell writes only local results, has no hub credentials, and starts no effects beyond its retained validity. Karmada reflects; management rejects mismatches and reconciles the same operation without inferring stop from expiry. | +| Customer callback and local boot succeed but image evidence is absent. | At most DelegatedContract after independent fencing proof; managed admission/join/initial gates requiring QualifiedImage remain closed even if Installation Ready is true. | +| Managed image has wrong digest or stale first-boot evidence; later deliver valid qualified evidence through reflection. | No initial readiness or assurance on invalid evidence; only the validated exact operation can report QualifiedImage and open the managed gate. | + ## Production readiness review questionnaire ### How is the feature enabled or disabled? -Enable installation modes per accepted MachineClass and qualified location. +Enable installation modes per accepted MachineOffering and qualified location. Rollback stops new admission while preserving handoff recovery, boot revocation, and release. Disabling a controller does not cancel remote work. @@ -331,7 +470,8 @@ conflicting evidence blocks readiness and capacity reuse. Preserve allocation custody, immutable Installation inputs, handoff revisions, executor fencing, active boot sessions, callback correlation, and cleanup -obligations. Test mixed versions and restore while both installation modes run. +obligations. Test restore while both installation modes run. This proposal imposes +no backwards-compatibility contract on earlier draft APIs. ## Drawbacks @@ -348,14 +488,14 @@ cannot prove that work stopped. machines outside the allocation and is difficult to revoke safely. - **Treat delegated PXE as allocate-only with no Fleet operation:** insufficient when Fleet must provide one-time PXE, power, network isolation, and recovery. -- **Create a public ProvisioningClass now:** deferred. MachineClass policy and the +- **Create a public ProvisioningClass now:** deferred. MachineOffering policy and the immutable Installation source establish the first required contract without a second offering hierarchy. ## Open design questions -- Exact MachineClass policy and Installation union schemas. -- Portable handoff encoding and the location status writer contract. +- Detailed MachineOffering capability schema and union validation implementation. +- Portable handoff encoding and Karmada reflection enforcement. - Boot identity beyond MAC address for the first qualified hardware. - Customer endpoint connectivity, TLS trust, proxying, and artifact-origin policy. - The managed installer image, action format, target-disk selector, and signing. diff --git a/docs/enhancements/pxe-installation/diagrams/architecture.svg b/docs/enhancements/pxe-installation/diagrams/architecture.svg index b3474131..681ee6b4 100644 --- a/docs/enhancements/pxe-installation/diagrams/architecture.svg +++ b/docs/enhancements/pxe-installation/diagrams/architecture.svg @@ -1,6 +1,6 @@ Fleet PXE installation control-plane architecture - Provider and consumer project APIs feed Fleet management. Fleet writes admitted work to a Karmada hub, which targets one location cell. The cell controls networking, boot, power, managed installation, or delegation to a customer PXE endpoint, and returns evidence. + Provider and consumer project APIs feed Fleet management. Fleet writes admitted work to a Karmada hub, which targets one location cell. The cell controls networking, boot, power, managed installation, or delegation to a customer PXE endpoint, and writes local evidence. Karmada reflects selected-cell results; management validates before public projection. Cells have no hub credentials. Fleet is an optional Metal provider implementation. @@ -18,22 +18,22 @@ - PXE installation follows Fleet's existing authority boundaries + Metal contract / optional Fleet execution: one retained authority PROJECT CONTROL PLANES Provider project API - MachineClass policy + MachineOffering policy MachineCapacity - Fleet physical inventory + Assignments: acquisition access Provider and allocator-owned state remains canonical here. Consumer project API - Machine + Machine + published MachineClass Immutable Installation ManagedImage or DelegatedPXE Customers write requests; @@ -65,17 +65,17 @@ Exact target and operation Selected-cell delivery Management writes intent; - the cell writes execution status. + Karmada reflects local results. SELECTED LOCATION / CELL Cell execution - Local handoff adapter + Delivered intent / local results Jobs and optional KRO Provider operation recovery - Cannot change the admitted target. + No hub or project credentials. Networking owner @@ -94,8 +94,8 @@ Provider executor - Redfish power and boot - Operation ID and fencing + One admitted execution driver + PXE / power / release fence Local boot transition Release and cleaning Credentials remain private. @@ -124,8 +124,11 @@ - + + + Reflected results to validation + Dashed return: Karmada reflection, not a cell hub write targeted delivery admitted request result diff --git a/docs/enhancements/pxe-installation/diagrams/installation-workflows.svg b/docs/enhancements/pxe-installation/diagrams/installation-workflows.svg index cc512f36..65fe2409 100644 --- a/docs/enhancements/pxe-installation/diagrams/installation-workflows.svg +++ b/docs/enhancements/pxe-installation/diagrams/installation-workflows.svg @@ -26,7 +26,8 @@ 2. Admit exact inputs - Authority, predecessor, quota + Offering and predecessor; + one execution driver 3. Deliver handoff @@ -39,7 +40,8 @@ 5. Arm one PXE boot - Retained operation and fence + PXE / power / release + share one fence @@ -71,7 +73,7 @@ Customer installs OS Customer-owned workflow - Operation-scoped callback + Callback is not shutdown proof @@ -88,12 +90,12 @@ Provider executor controls BMC - 8. Validate evidence - Mode-specific assurance + 8. Reflect / validate + Local result → Karmada → Fleet 9. Project status - Ready only after required proof + Required assurance + fencing @@ -103,5 +105,6 @@ Unknown outcome Retain allocation; recover - timeout, lost response, stale worker + Timeout or stale evidence + One admitted driver: ProviderAutomatic or bound CustomerRedfish steps. Managed consumers require QualifiedImage, not delegated Ready. diff --git a/docs/enhancements/pxe-installation/diagrams/user-journeys.svg b/docs/enhancements/pxe-installation/diagrams/user-journeys.svg index ef98de05..14ea003f 100644 --- a/docs/enhancements/pxe-installation/diagrams/user-journeys.svg +++ b/docs/enhancements/pxe-installation/diagrams/user-journeys.svg @@ -48,7 +48,7 @@ Prepare and boot Network ready; one-time PXE; - provider power operation + one admitted driver Fleet installer @@ -71,7 +71,7 @@ Receive result - Qualified image installed + QualifiedImage required Delegated customer PXE @@ -82,12 +82,12 @@ Admit delegation - Check class policy; + Use retained offering; pin endpoint and target Prepare and chain - One-machine PXE session; + Automatic or bound Redfish; proxy admitted endpoint @@ -97,7 +97,7 @@ Boot local disk - PXE delegation revoked; + Fenced; PXE revoked; local boot observed @@ -107,9 +107,11 @@ Validate evidence - Report delegated assurance + DelegatedContract Receive result Contract complete; OS opaque + Return: cell-local results → Karmada reflection → management validation + Callback / session closure ≠ installer stopped; independent fencing required From 9748f52e79522320d484f21e83b3e125bcf85dd1 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sat, 14 Nov 2026 12:01:03 -0600 Subject: [PATCH 003/518] docs: keep PXE summary additive to shared Fleet design --- docs/architecture/design.md | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/docs/architecture/design.md b/docs/architecture/design.md index 21082fb8..05cbfcc8 100644 --- a/docs/architecture/design.md +++ b/docs/architecture/design.md @@ -37,7 +37,7 @@ All names below describe proposed resources, not implemented schemas. | Subsystem | Responsibilities and principal resources | | --- | --- | | Inventory | `Facility`, `Rack`, `DeviceClaim`, `Device`, `Cable`, and `PowerFeed`: approved installation plans, actual assets, physical reservations, and verification evidence. | -| Capacity publication | Provider `MachineOffering` owns capability policy; `MachineOfferingAssignment` grants acquisition access; consumer `MachineClass` is a one-hop published view. `MachineProfile` contains immutable requirements. Publication does not reserve capacity or grant runtime authority. | +| Capacity publication | Provider `MachineClass` definitions and consumer-local references; discovery and safe summaries through service enablement and IAM. Publication does not reserve capacity or grant source-use permission. | | Machine allocation | Provider `MachineCapacity`, customer `Machine`, and private `MachineAllocation`: exclusive reservation, admission of consumer operations, activation, and release across provider and consumer projects. | | Bare-metal provisioning | Typed provider resources and adapters: execute admitted preparation, installation, power, console, and cleanup operations against exact assets. Backend workflows remain private. | | OS configuration | `MachineImage`, `InterfaceClass`, `Installation`, and `OSConfigPolicy`: approved artifacts, immutable installation requests, configuration composition, and one selected executor per incarnation. | @@ -87,20 +87,15 @@ credentials. Partitions or uncertain results never imply readiness or settlement 3. **Use one allocator.** Standalone consumers and managed clusters compete through the same durable reservation protocol. Create one immutable, terminal MachineAllocation between the customer Machine and provider MachineCapacity; - retain current authorization, quota holds, accepted offering identity and - contract/profile, installation/management capabilities, and local source + retain current authorization, quota holds, class revisions, and local source object identity as private admission evidence. Names, not cross-control-plane Kubernetes UIDs, are authored references. Overlapping classes must not duplicate supply. 4. **Separate discovery from authorization.** Consumer MachineClasses reference a - provider MachineOffering in one hop. Check effective acquisition assignment, - current source-use permission, + provider definition in one hop. Check current source-use permission, entitlement, quota, and placement feasibility at allocation commit. A copied reference, cached status, namespace, or privileged controller identity is not proof of consumer access. - Withdrawal blocks new allocations, not retained runtime rights. Reinstall uses - retained capabilities plus current install/image/secret/endpoint permissions - and explicit safety/suspension checks. Cleanup retains authority independently. 5. **Persist exact inputs before effects.** Retain admitted plans, artifacts, digests, target identities, predecessor preconditions, execution authority, and operation correlation. Timeouts mean unknown outcomes; recover the existing From 41e32e2508806f46076ef7966c4554c4e345d224 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sat, 14 Nov 2026 12:01:49 -0600 Subject: [PATCH 004/518] docs: separate PXE overview link from companion additions --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 010548c4..bf883dd0 100644 --- a/README.md +++ b/README.md @@ -31,6 +31,9 @@ The first bare-metal release must exercise a standalone customer workload on a qualified OS other than Talos, without requiring a managed cluster or an ongoing guest agent. Provisioning engines and provider integrations remain pluggable. +The [PXE installation enhancement](docs/enhancements/pxe-installation/README.md) +proposes managed images and bounded delegation to customer PXE. + ## Learn more Start with the [product overview and documentation guide](docs/README.md) to @@ -47,8 +50,5 @@ today. Then choose a topic: The [Bare Metal CLI enhancement](docs/enhancements/metal-cli/README.md) proposes `datumctl metal` discovery, machine management, and safe recovery workflows. -The [PXE installation enhancement](docs/enhancements/pxe-installation/README.md) -proposes managed images and bounded delegation to customer PXE. - Contributors should also read the [repository guidance](AGENTS.md) and [implementation roadmap](docs/development/roadmap.md). From 643f422ccb7bd92a42ffb1a4815997e6f6940304 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 18 Nov 2026 13:14:50 -0600 Subject: [PATCH 005/518] feat(executor): bind terminal results to the exact request Executor results now carry InputDigest, a SHA-256 commitment to the exact request (minus its ID) computed by simulator.RequestDigest. The coordinator rejects any terminal result whose digest does not match the request it retained, treating the mismatch as an unknown outcome rather than success, and returns the digest with each InstallationResult. The standalone install phase checks the retained simulator history against it. The executor contract documents exact-request replay and the meaning of Lookup's not-found/unknown answers, and Lookup rejects dot-segment IDs. Adversarial tests cover wrong-asset evidence, path-segment IDs and digest binding of every request field. Co-Authored-By: Claude Opus 5.5 --- .../controller/evidence_adversarial_test.go | 66 +++++++++++++++++++ internal/controller/lifecycle.go | 19 ++++-- internal/controller/lifecycle_test.go | 6 +- internal/executor/client.go | 10 ++- internal/executor/path_adversarial_test.go | 23 +++++++ internal/milo/adapter_test.go | 6 +- .../simulator/binding_adversarial_test.go | 36 ++++++++++ internal/simulator/store.go | 20 ++++-- internal/simulator/store_test.go | 34 ++++++++++ internal/staging/handler_test.go | 6 +- internal/standalone/runner.go | 6 +- 11 files changed, 214 insertions(+), 18 deletions(-) create mode 100644 internal/controller/evidence_adversarial_test.go create mode 100644 internal/executor/path_adversarial_test.go create mode 100644 internal/simulator/binding_adversarial_test.go diff --git a/internal/controller/evidence_adversarial_test.go b/internal/controller/evidence_adversarial_test.go new file mode 100644 index 00000000..affd3f71 --- /dev/null +++ b/internal/controller/evidence_adversarial_test.go @@ -0,0 +1,66 @@ +package controller + +import ( + "context" + "errors" + "testing" + "time" + + "go.datum.net/fleet/internal/executor" + "go.datum.net/fleet/internal/simulator" +) + +// Return a valid terminal result for the same operation name but a different +// physical target. Exercise both direct completion and lost-response recovery. +type substitutedCleanupExecutor struct { + result simulator.OperationResult + lost bool +} + +func (e *substitutedCleanupExecutor) Execute(_ context.Context, request simulator.Request) (simulator.OperationResult, error) { + request.AssetID += "-different-physical-asset" + digest, err := simulator.RequestDigest(request) + if err != nil { + return simulator.OperationResult{}, err + } + now := time.Now() + e.result = simulator.OperationResult{ID: request.ID, Kind: request.Kind, Phase: "Succeeded", Result: "clean", InputDigest: digest, CompletedAt: &now} + if e.lost { + return simulator.OperationResult{}, executor.ErrOutcomeUnknown + } + return e.result, nil +} + +func (e *substitutedCleanupExecutor) Lookup(context.Context, string) (simulator.OperationResult, bool, error) { + return e.result, true, nil +} + +func TestAdversarialCleanupEvidenceCannotReleaseAnotherAsset(t *testing.T) { + for _, lost := range []bool{false, true} { + name := "direct" + if lost { + name = "recovered" + } + t.Run(name, func(t *testing.T) { + ctx := context.Background() + f := newFixture(t) + owner, waiter := f.request("owner"), f.request("waiter") + for _, request := range []AllocationRequest{owner, waiter} { + if err := f.coordinator.EnsureClaimCustody(ctx, request.Claim, request.NamespaceUID, request.Admission); err != nil { + t.Fatal(err) + } + } + if _, err := f.coordinator.Allocate(ctx, owner); err != nil { + t.Fatal(err) + } + f.coordinator.executor = &substitutedCleanupExecutor{lost: lost} + result, err := f.coordinator.Release(ctx, owner.Claim.UID) + if !errors.Is(err, executor.ErrOutcomeUnknown) || result.SafeToRemoveFinalizer { + t.Errorf("wrong-asset cleanup authorized release: result=%+v err=%v", result, err) + } + if _, err := f.coordinator.Allocate(ctx, waiter); !errors.Is(err, ErrInsufficientCapacity) { + t.Errorf("wrong-asset cleanup exposed occupied capacity: %v", err) + } + }) + } +} diff --git a/internal/controller/lifecycle.go b/internal/controller/lifecycle.go index 87b41e63..3243c04b 100644 --- a/internal/controller/lifecycle.go +++ b/internal/controller/lifecycle.go @@ -1224,8 +1224,9 @@ func installationClaimScope(request InstallationRequest) (ClaimScope, error) { } type InstallationResult struct { - Revision string - Record InstallationRecord + Revision string + Record InstallationRecord + RequestDigest string } func (c *Coordinator) Install(ctx context.Context, request InstallationRequest) (InstallationResult, error) { @@ -1294,11 +1295,16 @@ func (c *Coordinator) Install(ctx context.Context, request InstallationRequest) if operation.InstallationNamespace != request.Installation.Namespace || operation.InstallationName != request.Installation.Name || operation.InstallationUID != request.Installation.UID || operation.NamespaceUID != request.NamespaceUID || operation.ClaimNamespace != request.Claim.Namespace || operation.ClaimName != request.Claim.Name || operation.ClaimUID != request.Claim.UID || operation.ClaimScope != scope || operation.ConsumerProject != request.ConsumerProject || operation.AssetID != asset.AssetID || operation.BindingID != asset.BindingID || operation.Epoch != asset.Epoch || operation.Predecessor != predecessor || operation.ImageName != request.Installation.Spec.ImageRef.Name || operation.Admission != request.Admission { return InstallationResult{}, ErrPredecessorConflict } + execRequest := simulator.Request{ID: operation.OperationID, Kind: "install", AssetID: asset.AssetID, BindingID: asset.BindingID, Epoch: asset.Epoch, FenceToken: asset.FenceToken, Inputs: installationInputs(operation)} + requestDigest, err := simulator.RequestDigest(execRequest) + if err != nil { + return InstallationResult{}, err + } if operation.State == OperationSucceeded { if err := c.publishInstalledName(ctx, asset.AssetID, asset.ClaimUID, operation); err != nil { return InstallationResult{}, err } - return InstallationResult{Revision: operation.ResultRevision, Record: *operation}, nil + return InstallationResult{Revision: operation.ResultRevision, Record: *operation, RequestDigest: requestDigest}, nil } if asset.CurrentInstallationName != predecessor || (asset.ActiveOperationID != "" && asset.ActiveOperationID != operation.OperationID) { return InstallationResult{}, ErrPredecessorConflict @@ -1306,7 +1312,6 @@ func (c *Coordinator) Install(ctx context.Context, request InstallationRequest) if err := c.activateOperation(ctx, asset.AssetID, asset.ClaimUID, predecessor, operation.OperationID); err != nil { return InstallationResult{}, err } - execRequest := simulator.Request{ID: operation.OperationID, Kind: "install", AssetID: asset.AssetID, BindingID: asset.BindingID, Epoch: asset.Epoch, FenceToken: asset.FenceToken, Inputs: installationInputs(operation)} if _, err := c.executeAndRecover(ctx, execRequest); err != nil { return InstallationResult{}, err } @@ -1317,7 +1322,7 @@ func (c *Coordinator) Install(ctx context.Context, request InstallationRequest) if err := c.publishInstalledName(ctx, asset.AssetID, asset.ClaimUID, operation); err != nil { return InstallationResult{}, err } - return InstallationResult{Revision: operation.ResultRevision, Record: *operation}, nil + return InstallationResult{Revision: operation.ResultRevision, Record: *operation, RequestDigest: requestDigest}, nil } func predecessorValue(value fleetv1.InstallationPredecessor) (string, error) { @@ -1541,6 +1546,10 @@ func (c *Coordinator) executeAndRecover(ctx context.Context, request simulator.R } func validateTerminalResult(request simulator.Request, result simulator.OperationResult) error { + digest, err := simulator.RequestDigest(request) + if err != nil || result.InputDigest != digest { + return fmt.Errorf("%w: executor evidence does not bind the exact request", executor.ErrOutcomeUnknown) + } if result.ID != request.ID || result.Kind != request.Kind || result.Phase != "Succeeded" || result.CompletedAt == nil { return fmt.Errorf("%w: executor result is not the correlated terminal operation", executor.ErrOutcomeUnknown) } diff --git a/internal/controller/lifecycle_test.go b/internal/controller/lifecycle_test.go index 5420f2ff..0b68368f 100644 --- a/internal/controller/lifecycle_test.go +++ b/internal/controller/lifecycle_test.go @@ -99,7 +99,11 @@ func (e *memoryExecutor) Execute(_ context.Context, request simulator.Request) ( e.requests = append(e.requests, request) now := time.Now() evidence := map[string]string{"cleanup": "clean", "install": "installed"}[request.Kind] - result := simulator.OperationResult{ID: request.ID, Kind: request.Kind, Phase: "Succeeded", Result: evidence, CompletedAt: &now} + digest, err := simulator.RequestDigest(request) + if err != nil { + return simulator.OperationResult{}, err + } + result := simulator.OperationResult{ID: request.ID, Kind: request.Kind, Phase: "Succeeded", Result: evidence, InputDigest: digest, CompletedAt: &now} if e.malform { result.CompletedAt = nil } diff --git a/internal/executor/client.go b/internal/executor/client.go index 540d3af3..67120813 100644 --- a/internal/executor/client.go +++ b/internal/executor/client.go @@ -31,7 +31,11 @@ var ( // Client is the exact provider-executor contract used by the standalone // lifecycle library. Implementations must preserve the operation ID and return -// only a verified terminal result. +// only a verified terminal result. Execute must accept exact-request replay under +// the same operation ID without duplicating effects. Lookup returning false and +// ErrOutcomeUnknown means a retained unfinished operation may be resumed by +// replaying its exact request. Transport failures must use a different error; +// true with any error never authorizes recovery or establishes success. type Client interface { Execute(context.Context, simulator.Request) (simulator.OperationResult, error) Lookup(context.Context, string) (simulator.OperationResult, bool, error) @@ -138,8 +142,8 @@ func (c *HTTPClient) Execute(ctx context.Context, request simulator.Request) (si } func (c *HTTPClient) Lookup(ctx context.Context, operationID string) (simulator.OperationResult, bool, error) { - if operationID == "" || strings.Contains(operationID, "/") { - return simulator.OperationResult{}, false, errors.New("operation ID is empty or contains a path separator") + if operationID == "" || operationID == "." || operationID == ".." || strings.Contains(operationID, "/") { + return simulator.OperationResult{}, false, errors.New("operation ID is empty, a dot segment, or contains a path separator") } response, err := c.do(ctx, http.MethodGet, path.Join("v1/operations", url.PathEscape(operationID)), nil) if err != nil { diff --git a/internal/executor/path_adversarial_test.go b/internal/executor/path_adversarial_test.go new file mode 100644 index 00000000..fbb19dcb --- /dev/null +++ b/internal/executor/path_adversarial_test.go @@ -0,0 +1,23 @@ +package executor + +import ( + "context" + "net/http" + "testing" +) + +func TestAdversarialLookupRejectsDotSegmentsBeforeTransport(t *testing.T) { + for _, id := range []string{".", ".."} { + t.Run(id, func(t *testing.T) { + called := false + client := clientForHandler(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + called = true + t.Logf("unexpected lookup path: %s", r.URL.Path) + w.WriteHeader(http.StatusNotFound) + }), "synthetic-token") + if _, _, err := client.Lookup(context.Background(), id); err == nil || called { + t.Fatalf("dot-segment ID reached transport or was accepted: called=%v err=%v", called, err) + } + }) + } +} diff --git a/internal/milo/adapter_test.go b/internal/milo/adapter_test.go index 958f562c..e4526e53 100644 --- a/internal/milo/adapter_test.go +++ b/internal/milo/adapter_test.go @@ -33,7 +33,11 @@ func (e *testExecutor) Execute(_ context.Context, request simulator.Request) (si defer e.mu.Unlock() e.requests = append(e.requests, request) now := time.Now() - return simulator.OperationResult{ID: request.ID, Kind: request.Kind, Phase: "Succeeded", Result: map[string]string{"cleanup": "clean", "install": "installed"}[request.Kind], CompletedAt: &now}, nil + digest, err := simulator.RequestDigest(request) + if err != nil { + return simulator.OperationResult{}, err + } + return simulator.OperationResult{ID: request.ID, Kind: request.Kind, Phase: "Succeeded", Result: map[string]string{"cleanup": "clean", "install": "installed"}[request.Kind], InputDigest: digest, CompletedAt: &now}, nil } func (e *testExecutor) Lookup(context.Context, string) (simulator.OperationResult, bool, error) { return simulator.OperationResult{}, false, nil diff --git a/internal/simulator/binding_adversarial_test.go b/internal/simulator/binding_adversarial_test.go new file mode 100644 index 00000000..9f35720f --- /dev/null +++ b/internal/simulator/binding_adversarial_test.go @@ -0,0 +1,36 @@ +package simulator + +import ( + "errors" + "path/filepath" + "reflect" + "testing" +) + +func TestAdversarialReplayCannotRetargetAuthorityAfterRestart(t *testing.T) { + for name, mutate := range map[string]func(*Request){ + "asset": func(r *Request) { r.AssetID = "other-asset" }, + "binding": func(r *Request) { r.BindingID = "other-binding" }, + "epoch": func(r *Request) { r.Epoch++ }, + "fence": func(r *Request) { r.FenceToken = "other-fence" }, + "image": func(r *Request) { r.Inputs = []byte(`{"image":"different-image"}`) }, + } { + t.Run(name, func(t *testing.T) { + path := filepath.Join(t.TempDir(), "state.json") + store := openStore(t, path) + request := operationRequest("retained-install", "install", 1, `{"image":"synthetic-image"}`) + if _, _, err := store.Submit(request); err != nil { + t.Fatal(err) + } + store = openStore(t, path) + before := store.Snapshot() + mutate(&request) + if _, _, err := store.Submit(request); !errors.Is(err, ErrConflict) { + t.Fatalf("retargeted replay: %v", err) + } + if !reflect.DeepEqual(before, store.Snapshot()) { + t.Fatal("rejected replay changed authority or effects") + } + }) + } +} diff --git a/internal/simulator/store.go b/internal/simulator/store.go index 7207e15a..cc70acde 100644 --- a/internal/simulator/store.go +++ b/internal/simulator/store.go @@ -52,6 +52,7 @@ type Operation struct { type OperationResult struct { ID string `json:"id"` + InputDigest string `json:"inputDigest,omitempty"` Kind string `json:"kind"` Phase string `json:"phase"` Result string `json:"result,omitempty"` @@ -61,7 +62,7 @@ type OperationResult struct { func (o Operation) ResultView() OperationResult { return OperationResult{ - ID: o.ID, Kind: o.Kind, Phase: o.Phase, + ID: o.ID, InputDigest: o.InputDigest, Kind: o.Kind, Phase: o.Phase, Result: o.Result, CreatedAt: o.CreatedAt, CompletedAt: cloneTime(o.CompletedAt), } } @@ -559,13 +560,20 @@ func cloneTime(in *time.Time) *time.Time { return &out } +func RequestDigest(request Request) (string, error) { + request.ID = "" + encoded, err := json.Marshal(request) + if err != nil { + return "", err + } + sum := sha256.Sum256(encoded) + return hex.EncodeToString(sum[:]), nil +} + func digest(r Request) string { - copy := r - copy.ID = "" - b, err := json.Marshal(copy) + value, err := RequestDigest(r) if err != nil { panic("marshal validated simulator request") } - sum := sha256.Sum256(b) - return hex.EncodeToString(sum[:]) + return value } diff --git a/internal/simulator/store_test.go b/internal/simulator/store_test.go index 4110048e..f209d797 100644 --- a/internal/simulator/store_test.go +++ b/internal/simulator/store_test.go @@ -241,6 +241,40 @@ func openStore(t *testing.T, path string) *Store { return store } +func TestResultDigestCommitsExactRequestWithoutExposingInputs(t *testing.T) { + request := operationRequest("digest-operation", "install", 1, `{"image":"debian@sha256:1"}`) + store := openStore(t, filepath.Join(t.TempDir(), "state.json")) + operation, _, err := store.Submit(request) + if err != nil { + t.Fatal(err) + } + want, err := RequestDigest(request) + if err != nil || len(want) != 64 || operation.ResultView().InputDigest != want { + t.Fatalf("request commitment mismatch: %v", err) + } + for _, field := range []string{"asset", "binding", "epoch", "fence", "image", "kind"} { + changed := request + switch field { + case "asset": + changed.AssetID += "-other" + case "binding": + changed.BindingID += "-other" + case "epoch": + changed.Epoch++ + case "fence": + changed.FenceToken += "-other" + case "image": + changed.Inputs = json.RawMessage(`{"image":"debian@sha256:2"}`) + case "kind": + changed.Kind = "cleanup" + } + got, err := RequestDigest(changed) + if err != nil || got == want { + t.Fatalf("digest did not bind %s: %v", field, err) + } + } +} + func operationRequest(id, kind string, epoch int64, inputs string) Request { return Request{ ID: id, Kind: kind, AssetID: "asset-1", BindingID: "binding-a", diff --git a/internal/staging/handler_test.go b/internal/staging/handler_test.go index 36a8ecc5..dc6a6131 100644 --- a/internal/staging/handler_test.go +++ b/internal/staging/handler_test.go @@ -25,7 +25,11 @@ type executor struct { func (e *executor) Execute(_ context.Context, request simulator.Request) (simulator.OperationResult, error) { now := time.Now().UTC() - result := simulator.OperationResult{ID: request.ID, Kind: request.Kind, Phase: "Succeeded", Result: "clean", CreatedAt: now, CompletedAt: &now} + digest, err := simulator.RequestDigest(request) + if err != nil { + return simulator.OperationResult{}, err + } + result := simulator.OperationResult{ID: request.ID, Kind: request.Kind, Phase: "Succeeded", Result: "clean", InputDigest: digest, CreatedAt: now, CompletedAt: &now} e.results[request.ID] = result return result, nil } diff --git a/internal/standalone/runner.go b/internal/standalone/runner.go index 9ba449e5..d03ef281 100644 --- a/internal/standalone/runner.go +++ b/internal/standalone/runner.go @@ -150,10 +150,14 @@ func (r Runner) install(ctx context.Context, coordinator *controller.Coordinator return err } imageDecision := "local-test-" + imageDigest(r.Options.ImageName) - _, err = coordinator.Install(ctx, controller.InstallationRequest{Claim: claim, Installation: &installation, NamespaceUID: namespace.UID, Admission: controller.InstallationAdmissionAuthority{PrincipalUID: admission.PrincipalUID, DecisionID: "standalone-install-" + string(installation.UID), CatalogAuthority: "local-test-catalog", CatalogRevision: "local-test-v1", ImageDecisionID: imageDecision}}) + result, err := coordinator.Install(ctx, controller.InstallationRequest{Claim: claim, Installation: &installation, NamespaceUID: namespace.UID, Admission: controller.InstallationAdmissionAuthority{PrincipalUID: admission.PrincipalUID, DecisionID: "standalone-install-" + string(installation.UID), CatalogAuthority: "local-test-catalog", CatalogRevision: "local-test-v1", ImageDecisionID: imageDecision}}) if err != nil { return fmt.Errorf("install synthetic image: %w", err) } + retained, found, err := r.Executor.Lookup(ctx, result.Record.OperationID) + if err != nil || !found || retained.ID != result.Record.OperationID || retained.Kind != "install" || retained.Phase != "Succeeded" || retained.Result != "installed" || retained.CompletedAt == nil || result.RequestDigest == "" || retained.InputDigest != result.RequestDigest { + return fmt.Errorf("%w: simulator installation history is missing or does not match retained authority and inputs", executor.ErrOutcomeUnknown) + } now := metav1.NewTime(r.Now().UTC()) installation.Status = fleetv1.InstallationStatus{Phase: "Ready", CompletedAt: &now, Conditions: []metav1.Condition{condition("Accepted", metav1.ConditionTrue, installation.Generation, "SyntheticFixtureAccepted", "The standalone fixture admitted this request; this is not Milo authorization."), condition("Executing", metav1.ConditionFalse, installation.Generation, "Completed", "The persistent simulator returned a verified terminal result."), condition("Ready", metav1.ConditionTrue, installation.Generation, "Installed", "The synthetic provider verified installation completion.")}} if err := r.Client.Status().Update(ctx, &installation); err != nil { From 21d18bbff3cb9a3869efc6d78b2bcbf9b8812c20 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 18 Nov 2026 13:16:09 -0600 Subject: [PATCH 006/518] feat(standalone): add a reinstall phase and a disposable kind smoke The standalone runner gains a reinstall phase: a distinct Installation that names the initial Installation as its predecessor, on the same allocation, recovering the same successor operation across retries and restarts. Before each install the claim's Ready condition is set Unknown, so an unverified completion closes readiness and keeps the capacity occupied. hack/run-standalone-smoke.sh runs the full allocate, install, reinstall and release lifecycle in a disposable kind cluster (task standalone:test). CI runs its offline tests and a standalone-smoke job that executes it end to end. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 27 ++ Taskfile.yaml | 5 + cmd/fleet-standalone-smoke/main.go | 2 +- config/standalone/fixtures.yaml | 8 + config/standalone/rbac.yaml | 4 +- config/standalone/smoke-cronjobs.yaml | 23 ++ docs/development/README.md | 6 +- docs/operations/standalone-smoke.md | 43 +++- hack/run-standalone-smoke.sh | 156 ++++++++++++ hack/standalone-smoke.sh | 11 + hack/test-run-standalone-smoke.sh | 212 ++++++++++++++++ hack/test-standalone-preflight.sh | 59 +++++ hack/validate-standalone-render.sh | 16 +- internal/standalone/reinstall_test.go | 347 ++++++++++++++++++++++++++ internal/standalone/runner.go | 53 ++-- 15 files changed, 939 insertions(+), 33 deletions(-) create mode 100755 hack/run-standalone-smoke.sh create mode 100755 hack/test-run-standalone-smoke.sh create mode 100644 internal/standalone/reinstall_test.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 848551a1..ffadd068 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -33,4 +33,31 @@ jobs: - run: ./hack/test-standalone-source-id.sh - run: ./hack/test-standalone-preflight.sh - run: ./hack/test-standalone-build-context.sh + - run: ./hack/test-run-standalone-smoke.sh - run: ./hack/validate-doc-links.sh + standalone-smoke: + runs-on: ubuntu-latest + timeout-minutes: 35 + steps: + - uses: actions/checkout@v6 + - uses: actions/setup-go@v6 + with: {go-version-file: go.mod, cache: true} + - uses: imranismail/setup-kustomize@v2 + with: {kustomize-version: 5.8.1} + - name: Install pinned kind and kubectl + shell: bash + run: | + set -euo pipefail + go install sigs.k8s.io/kind@v0.31.0 + directory=$(mktemp -d) + trap 'rm -rf "$directory"' EXIT + cd "$directory" + curl --fail --location --retry 3 --max-time 60 -o kubectl https://dl.k8s.io/release/v1.35.0/bin/linux/amd64/kubectl + curl --fail --location --retry 3 --max-time 60 -o kubectl.sha256 https://dl.k8s.io/release/v1.35.0/bin/linux/amd64/kubectl.sha256 + echo "$(cat kubectl.sha256) kubectl" | sha256sum --check + chmod +x kubectl + mkdir -p "$HOME/.local/bin" + mv kubectl "$HOME/.local/bin/kubectl" + echo "$HOME/.local/bin" >> "$GITHUB_PATH" + - name: Run disposable standalone smoke + run: ./hack/run-standalone-smoke.sh diff --git a/Taskfile.yaml b/Taskfile.yaml index 1765d7b0..a2aa0339 100644 --- a/Taskfile.yaml +++ b/Taskfile.yaml @@ -1,6 +1,11 @@ version: '3' tasks: + standalone:test: + desc: Run the synthetic lifecycle in a disposable local kind cluster. + cmds: + - ./hack/run-standalone-smoke.sh + manifests:validate: desc: Render and validate the production Fleet and Milo manifest roots. cmds: diff --git a/cmd/fleet-standalone-smoke/main.go b/cmd/fleet-standalone-smoke/main.go index 06124f34..8f388da7 100644 --- a/cmd/fleet-standalone-smoke/main.go +++ b/cmd/fleet-standalone-smoke/main.go @@ -22,7 +22,7 @@ import ( func main() { options := standalone.DefaultOptions() var phase, simulatorURL, tokenFile string - flag.StringVar(&phase, "phase", "", "required smoke phase: allocate, install, or release") + flag.StringVar(&phase, "phase", "", "required synthetic smoke phase: allocate, install, reinstall, or release") flag.StringVar(&simulatorURL, "simulator-url", "http://fleet-simulator:8080", "synthetic simulator runtime URL") flag.StringVar(&tokenFile, "runtime-token-file", "", "file containing the synthetic simulator runtime token") flag.StringVar(&options.PrivateNamespace, "private-namespace", options.PrivateNamespace, "private record namespace") diff --git a/config/standalone/fixtures.yaml b/config/standalone/fixtures.yaml index 40b9f723..269582b1 100644 --- a/config/standalone/fixtures.yaml +++ b/config/standalone/fixtures.yaml @@ -55,3 +55,11 @@ spec: machineRef: {name: allocation} expectedPredecessor: {type: None} imageRef: {name: "debian-12@sha256:9f4ad8d8b8a6f6fc64d2cf2c7e70b9184b74f089adf8c36d84f4fcb99892f3cb"} +--- +apiVersion: metal.datumapis.com/v1alpha1 +kind: Installation +metadata: {name: debian-12-reinstall, namespace: fleet-project-a} +spec: + machineRef: {name: allocation} + expectedPredecessor: {type: Installation, name: debian-12} + imageRef: {name: "debian-12@sha256:9f4ad8d8b8a6f6fc64d2cf2c7e70b9184b74f089adf8c36d84f4fcb99892f3cb"} diff --git a/config/standalone/rbac.yaml b/config/standalone/rbac.yaml index f684b667..7ad110cf 100644 --- a/config/standalone/rbac.yaml +++ b/config/standalone/rbac.yaml @@ -60,11 +60,11 @@ rules: verbs: [get, update] - apiGroups: [metal.datumapis.com] resources: [installations] - resourceNames: [debian-12] + resourceNames: [debian-12, debian-12-reinstall] verbs: [get] - apiGroups: [metal.datumapis.com] resources: [installations/status] - resourceNames: [debian-12] + resourceNames: [debian-12, debian-12-reinstall] verbs: [get, update] --- apiVersion: rbac.authorization.k8s.io/v1 diff --git a/config/standalone/smoke-cronjobs.yaml b/config/standalone/smoke-cronjobs.yaml index 6f5251db..fd7e8749 100644 --- a/config/standalone/smoke-cronjobs.yaml +++ b/config/standalone/smoke-cronjobs.yaml @@ -46,6 +46,29 @@ spec: --- apiVersion: batch/v1 kind: CronJob +metadata: {name: fleet-smoke-reinstall, namespace: fleet-system} +spec: + schedule: "0 0 1 1 *" + suspend: true + jobTemplate: + spec: + backoffLimit: 0 + template: + spec: + serviceAccountName: fleet-standalone-smoke + restartPolicy: Never + securityContext: {runAsNonRoot: true, runAsUser: 65532, runAsGroup: 65532, fsGroup: 65532, seccompProfile: {type: RuntimeDefault}} + containers: + - name: smoke + image: ghcr.io/datum-cloud/fleet-standalone-smoke:v0.0.0-dev + imagePullPolicy: Never + args: [--phase=reinstall, --runtime-token-file=/var/run/fleet/token] + securityContext: {allowPrivilegeEscalation: false, capabilities: {drop: [ALL]}, readOnlyRootFilesystem: true} + volumeMounts: [{name: runtime-token, mountPath: /var/run/fleet, readOnly: true}] + volumes: [{name: runtime-token, secret: {secretName: fleet-simulator-runtime, defaultMode: 0440}}] +--- +apiVersion: batch/v1 +kind: CronJob metadata: {name: fleet-smoke-release, namespace: fleet-system} spec: schedule: "0 0 1 1 *" diff --git a/docs/development/README.md b/docs/development/README.md index bd10d00b..c1d4581e 100644 --- a/docs/development/README.md +++ b/docs/development/README.md @@ -251,7 +251,11 @@ namespaces as project stand-ins and one synthetic `us-central-1` machine with 24 cores and 128Gi of memory. The allocate phase retains custody before adding the Fleet finalizer, binds one claim, and leaves the competing claim pending. The install phase admits one exact digest-pinned operation through the persistent -simulator and is idempotent across worker and simulator restart. The release +simulator and is idempotent across worker and simulator restart. A bounded +reinstall phase uses a distinct Installation naming the initial Installation as +its predecessor, retains the same allocation, and recovers the same successor +operation across retries and restart. Unknown completion closes readiness and +keeps the capacity occupied. The release phase verifies cleanup before finalizer removal and advances the retained asset epoch before the waiting claim binds. diff --git a/docs/operations/standalone-smoke.md b/docs/operations/standalone-smoke.md index fab63df5..0f7ccfd0 100644 --- a/docs/operations/standalone-smoke.md +++ b/docs/operations/standalone-smoke.md @@ -18,8 +18,20 @@ The scenario has one `us-central-1` Machine with 24 physical CPU cores and 128Gi of memory. Both consumers request it. Project A binds first while project B remains pending. Project A installs a digest-pinned synthetic Debian image. The script restarts the simulator and reruns the install phase to recover the -same retained operation. It then releases project A, verifies cleanup, and lets -project B bind at a later executor epoch. +same retained operation. A separate `debian-12-reinstall` Installation then names +`debian-12` as its expected predecessor and replaces it on the same allocation. +Another simulator restart and retry recover that exact successor operation. +Every install/reinstall run performs an authenticated simulator lookup and checks +the operation identity, terminal result, and digest of the exact retained request +(including allocation, epoch, fencing authority, and image inputs). Kubernetes +completion records alone cannot pass the restart persistence check. +Project B remains pending throughout. The scenario then releases project A, +verifies cleanup, and lets project B bind at a later executor epoch. + +Reinstall retries preserve the allocation binding and executor epoch. An unknown +executor result leaves the Machine's readiness unknown and retains custody; +neither retry nor release can expose that capacity before recovery and cleanup. +Tests exercise lost responses, concurrent retry, and stale predecessor rejection. No network interface is requested. The `NETWORK` and `ADDRESS` columns are therefore intentionally blank; this environment does not deploy or impersonate @@ -27,6 +39,30 @@ NSO, IPAM, or Galactic programming. ## Run with kind and Colima +For a complete disposable run, install Docker with a Linux container engine, +kind, kubectl, kustomize, Git, and Python 3, then run from the repository: + +```sh +./hack/run-standalone-smoke.sh +# Or: task standalone:test +``` + +The wrapper creates a uniquely named kind cluster and a private temporary +kubeconfig, runs the scenario, and deletes only its own cluster. It does not +change your current Kubernetes context. Failure, timeout, and interrupt paths +also attempt cleanup; unverified cleanup is reported as failure with the exact +cluster name. Command output is withheld by the wrapper to avoid leaking local +credentials. The final phase label identifies where a failure occurred. +`FLEET_SMOKE_TIMEOUT_SECONDS` defaults to 1200 for the whole run and +`FLEET_SMOKE_CLEANUP_TIMEOUT_SECONDS` defaults to 120 for cleanup. + +The `ci` workflow runs this same wrapper on `ubuntu-latest` for pull requests and +main pushes, using Docker and kind rather than self-hosted or nested-KVM runners. +That job exercises the synthetic control-plane lifecycle, not a real guest OS, +Milo production admission, or provider hardware qualification. Passing local +checks is not evidence that a particular GitHub Actions run passed. + +To retain a cluster for local inspection, use the lower-level script instead. Create or select a dedicated kind cluster named `fleet-core`, then run: ```sh @@ -50,7 +86,8 @@ metadata, credentials, documentation, and manifests are never sent to the builder. The script builds and loads both images and verifies each running pod uses the exact source-specific tag with image pulling disabled. Distinct clean commits therefore cannot silently reuse one local workload tag. -It then applies the CRDs and fixture and uses `kubectl wait`/rollout watches for +It applies the CRDs first and waits for establishment before applying fixtures, +then uses `kubectl wait`/rollout watches for phase completion. It never patches status, removes finalizers, or writes lifecycle records itself. The phase Job is the designated synthetic fixture and status writer; the lifecycle diff --git a/hack/run-standalone-smoke.sh b/hack/run-standalone-smoke.sh new file mode 100755 index 00000000..39021fa6 --- /dev/null +++ b/hack/run-standalone-smoke.sh @@ -0,0 +1,156 @@ +#!/bin/sh +set -eu + +root=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd) +if ! command -v python3 >/dev/null 2>&1; then + echo 'standalone smoke requires python3' >&2 + exit 1 +fi +exec python3 - "$root" "$@" <<'PY' +import os +from pathlib import Path +import shutil +import signal +import subprocess +import sys +import tempfile +import time +import uuid + + +class Failure(Exception): + def __init__(self, message, status=1): + super().__init__(message) + self.status = status + + +interrupted = 0 + + +def interrupt(signum, frame): + global interrupted + interrupted = signum + + +def seconds(name, default): + value = os.environ.get(name, str(default)) + if not value.isascii() or not value.isdigit() or not 1 <= int(value) <= 3600: + raise Failure(name + ' must be an integer from 1 to 3600') + return int(value) + + +def run(label, command, environment, deadline, capture=False, cleanup=False, on_start=None): + print('standalone smoke: ' + label, flush=True) + if interrupted and not cleanup: + raise Failure('interrupted', 128 + interrupted) + if time.monotonic() >= deadline: + raise Failure(label + ' timed out', 124) + with tempfile.TemporaryFile(dir=environment['TMPDIR']) as output: + process = subprocess.Popen(command, env=environment, stdin=subprocess.DEVNULL, + stdout=output, stderr=subprocess.DEVNULL, + start_new_session=True) + try: + if on_start: + on_start() + while process.poll() is None: + if interrupted and not cleanup: + raise Failure('interrupted', 128 + interrupted) + if time.monotonic() >= deadline: + raise Failure(label + ' timed out', 124) + time.sleep(0.1) + if interrupted and not cleanup: + raise Failure('interrupted', 128 + interrupted) + if process.returncode != 0: + raise Failure(label + ' failed (exit ' + str(process.returncode) + ')', + process.returncode if process.returncode > 0 else 1) + if capture: + output.seek(0) + return output.read().decode('utf-8') + finally: + try: + os.killpg(process.pid, signal.SIGTERM) + except ProcessLookupError: + pass + try: + process.wait(timeout=2) + except subprocess.TimeoutExpired: + pass + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + process.wait(timeout=2) + + +def main(): + if len(sys.argv) != 2: + raise Failure('usage: hack/run-standalone-smoke.sh (no arguments)') + timeout = seconds('FLEET_SMOKE_TIMEOUT_SECONDS', 1200) + cleanup_timeout = seconds('FLEET_SMOKE_CLEANUP_TIMEOUT_SECONDS', 120) + for tool in ('docker', 'kind', 'kubectl', 'kustomize', 'git'): + if shutil.which(tool) is None: + raise Failure('missing required tool: ' + tool) + os.chdir(sys.argv[1]) + os.umask(0o077) + cluster = 'fleet-smoke-' + uuid.uuid4().hex + created = False + + def mark_created(): + nonlocal created + created = True + + status = 0 + deadline = time.monotonic() + timeout + with tempfile.TemporaryDirectory(prefix='fleet-smoke-') as directory: + kubeconfig = str(Path(directory) / 'kubeconfig') + Path(kubeconfig).touch(mode=0o600) + config = str(Path(directory) / 'kind.yaml') + Path(config).write_text('kind: Cluster\napiVersion: kind.x-k8s.io/v1alpha4\n' + 'nodes:\n- role: control-plane\n') + environment = dict(os.environ, KUBECONFIG=kubeconfig, TMPDIR=directory, + KIND_CLUSTER=cluster, KUBECTL_CONTEXT='kind-' + cluster, + ALLOW_KIND_CONTEXT_ALIAS='false', KIND_EXPERIMENTAL_PROVIDER='docker') + try: + operating_system = run('Docker preflight', ['docker', 'info', '--format', '{{.OSType}}'], + environment, min(deadline, time.monotonic() + 30), capture=True) + if operating_system.strip() != 'linux': + raise Failure('Docker must provide Linux containers') + clusters = run('kind preflight', ['kind', 'get', 'clusters'], environment, + min(deadline, time.monotonic() + 30), capture=True) + if cluster in clusters.splitlines(): + raise Failure('generated cluster name already exists; refusing to adopt or delete it') + print('standalone smoke: disposable cluster ' + cluster, flush=True) + run('create cluster', ['kind', 'create', 'cluster', '--name', cluster, + '--kubeconfig', kubeconfig, '--config', config, '--retain', + '--image', 'kindest/node:v1.35.0@sha256:452d707d4862f52530247495d180205e029056831160e22870e37e3f6c1ac31f', + '--wait', '120s'], environment, + min(deadline, time.monotonic() + 240), on_start=mark_created) + run('synthetic lifecycle', ['./hack/standalone-smoke.sh'], environment, deadline) + except Failure as error: + print('standalone smoke: ' + str(error), file=sys.stderr) + status = error.status + except (OSError, ValueError, subprocess.SubprocessError): + print('standalone smoke: command execution failed; raw diagnostics withheld', file=sys.stderr) + status = 1 + finally: + if created: + try: + run('delete cluster', ['kind', 'delete', 'cluster', '--name', cluster, + '--kubeconfig', kubeconfig], environment, + time.monotonic() + cleanup_timeout, cleanup=True) + except (Failure, OSError, ValueError, subprocess.SubprocessError): + print('standalone smoke: cleanup unverified for ' + cluster + + '; inspect this exact cluster before manual cleanup', file=sys.stderr) + status = status or 1 + return status or (128 + interrupted if interrupted else 0) + + +for signum in (signal.SIGINT, signal.SIGTERM, signal.SIGHUP): + signal.signal(signum, interrupt) +try: + sys.exit(main()) +except (Failure, OSError, ValueError) as error: + print('standalone smoke: ' + (str(error) if isinstance(error, Failure) + else 'local setup failed; raw diagnostics withheld'), file=sys.stderr) + sys.exit(error.status if isinstance(error, Failure) else 1) +PY diff --git a/hack/standalone-smoke.sh b/hack/standalone-smoke.sh index 6ecd610b..9eaed6f2 100755 --- a/hack/standalone-smoke.sh +++ b/hack/standalone-smoke.sh @@ -65,6 +65,9 @@ done docker build -f build/simulator.Dockerfile -t "$simulator_image" . docker build -f build/standalone-smoke.Dockerfile -t "$smoke_image" . kind load docker-image --name "$cluster" "$simulator_image" "$smoke_image" +kustomize build config/base/crd >"$rendered" +kubectl --context "$context" apply -f "$rendered" +kubectl --context "$context" wait --for=condition=Established --timeout=60s -f "$rendered" kustomize build config/standalone | sed -e "s#fleet-simulator:standalone-local#$simulator_image#g" -e "s#fleet-standalone-smoke:standalone-local#$smoke_image#g" >"$rendered" if grep -q 'standalone-local' "$rendered"; then @@ -110,6 +113,14 @@ kubectl --context "$context" -n fleet-project-a get installations,machines test "$(kubectl --context "$context" -n fleet-project-a get installation debian-12 -o jsonpath='{.status.phase}')" = "Ready" test "$(kubectl --context "$context" -n fleet-project-a get machine allocation -o jsonpath='{.status.currentInstallationRef.name}')" = "debian-12" +run_phase reinstall fleet-smoke-reinstall-run +kubectl --context "$context" -n fleet-system rollout restart statefulset/fleet-simulator +kubectl --context "$context" -n fleet-system rollout status statefulset/fleet-simulator --timeout=120s +run_phase reinstall fleet-smoke-reinstall-recovery-run +test "$(kubectl --context "$context" -n fleet-project-a get installation debian-12-reinstall -o jsonpath='{.status.phase}')" = "Ready" +test "$(kubectl --context "$context" -n fleet-project-a get machine allocation -o jsonpath='{.status.currentInstallationRef.name}')" = "debian-12-reinstall" +test "$(kubectl --context "$context" -n fleet-project-b get machine allocation -o jsonpath='{.status.phase}')" = "Pending" + for project in fleet-project-a fleet-project-b; do subject="system:serviceaccount:$project:default" for verb in get list watch create update patch delete; do diff --git a/hack/test-run-standalone-smoke.sh b/hack/test-run-standalone-smoke.sh new file mode 100755 index 00000000..bc453be5 --- /dev/null +++ b/hack/test-run-standalone-smoke.sh @@ -0,0 +1,212 @@ +#!/bin/sh +set -eu + +root=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd) +exec python3 - "$root" <<'PY' +import json +import os +from pathlib import Path +import shutil +import signal +import subprocess +import sys +import tempfile +import time + + +mock = r'''#!PYTHON +import json +import os +from pathlib import Path +import signal +import subprocess +import sys +import time + +tool = Path(sys.argv[0]).name +scenario = os.environ['SCENARIO'] +directory = Path(os.environ['CASE_DIRECTORY']) +arguments = sys.argv[1:] +stage = tool +if tool == 'kind': + stage = arguments[0] +record = {'stage': stage, 'arguments': arguments, + 'cluster': os.environ['KIND_CLUSTER'], 'context': os.environ['KUBECTL_CONTEXT'], + 'kubeconfig': os.environ['KUBECONFIG'], 'temporary': os.environ['TMPDIR'], + 'mode': Path(os.environ['KUBECONFIG']).stat().st_mode & 0o777, + 'directory_mode': Path(os.environ['TMPDIR']).stat().st_mode & 0o777, + 'provider': os.environ['KIND_EXPERIMENTAL_PROVIDER'], + 'alias': os.environ['ALLOW_KIND_CONTEXT_ALIAS']} +with (directory / 'trace').open('a') as trace: + trace.write(json.dumps(record) + '\n') +print('SYNTHETIC-SECRET-MUST-NOT-LEAK', file=sys.stderr, flush=True) +if tool == 'docker': + if scenario == 'docker_fail': + print('SYNTHETIC-SECRET-MUST-NOT-LEAK') + sys.exit(71) + print('windows' if scenario == 'wrong_os' else 'linux') +elif stage == 'get': + if scenario == 'list_fail': + sys.exit(73) + print('unrelated-cluster') + if scenario == 'collision': + print(os.environ['KIND_CLUSTER']) +elif stage == 'create': + assert '--retain' in arguments + assert arguments[arguments.index('--kubeconfig') + 1] == os.environ['KUBECONFIG'] + assert arguments[arguments.index('--name') + 1] == os.environ['KIND_CLUSTER'] + assert '@sha256:' in arguments[arguments.index('--image') + 1] + assert Path(arguments[arguments.index('--config') + 1]).read_text().endswith('- role: control-plane\n') + (directory / 'owned-cluster').touch() + if scenario == 'create_fail': + print('SYNTHETIC-SECRET-MUST-NOT-LEAK') + sys.exit(74) +elif stage == 'delete': + assert arguments[arguments.index('--name') + 1] == os.environ['KIND_CLUSTER'] + assert arguments[arguments.index('--kubeconfig') + 1] == os.environ['KUBECONFIG'] + if scenario in ('delete_fail', 'smoke_delete_fail'): + sys.exit(43) + if scenario != 'delete_timeout': + (directory / 'owned-cluster').unlink() +elif tool == 'standalone-smoke.sh': + assert Path.cwd() == (directory / 'repo').resolve() + print('SYNTHETIC-SECRET-MUST-NOT-LEAK', flush=True) + if scenario in ('smoke_fail', 'smoke_delete_fail'): + sys.exit(42) +else: + sys.exit(99) + +if scenario in (stage + '_timeout', stage + '_signal'): + signal.signal(signal.SIGTERM, signal.SIG_IGN) + child = subprocess.Popen([sys.executable, '-c', + 'import signal,time; signal.signal(signal.SIGTERM, signal.SIG_IGN); time.sleep(60)']) + (directory / 'descendant').write_text(str(child.pid)) + while True: + time.sleep(1) +'''.replace('#!PYTHON', '#!' + sys.executable, 1) + + +def check(condition, message): + if not condition: + raise AssertionError(message) + + +with tempfile.TemporaryDirectory(prefix='test-fleet-smoke-') as temporary: + suite = Path(temporary) + names = [] + + def case(scenario, expected, missing=None, timeout=None, send_signal=None, arguments=()): + directory = suite / (scenario + '-' + str(len(list(suite.iterdir())))) + directory.mkdir() + repository = directory / 'repo' + (repository / 'hack').mkdir(parents=True) + wrapper = repository / 'hack/run-standalone-smoke.sh' + shutil.copy2(Path(sys.argv[1]) / 'hack/run-standalone-smoke.sh', wrapper) + inner = repository / 'hack/standalone-smoke.sh' + inner.write_text(mock) + inner.chmod(0o755) + binaries = directory / 'bin' + binaries.mkdir() + for tool in ('docker', 'kind', 'kubectl', 'kustomize', 'git'): + if tool != missing: + target = binaries / tool + target.write_text(mock) + target.chmod(0o755) + for tool in ('python3', 'dirname'): + if tool != missing: + (binaries / tool).symlink_to(shutil.which(tool)) + home = directory / 'home' + (home / '.kube').mkdir(parents=True) + credentials = [home / '.kube/config', directory / 'first-config', directory / 'second-config'] + for credential in credentials: + credential.write_text('user-config-and-current-context-must-not-change\n') + scratch = directory / 'scratch' + scratch.mkdir() + environment = dict(os.environ, PATH=str(binaries), HOME=str(home), TMPDIR=str(scratch), + KUBECONFIG=str(credentials[1]) + ':' + str(credentials[2]), + KIND_CLUSTER='unrelated-cluster', KUBECTL_CONTEXT='production', + ALLOW_KIND_CONTEXT_ALIAS='true', KIND_EXPERIMENTAL_PROVIDER='podman', + SCENARIO=scenario, CASE_DIRECTORY=str(directory), + FLEET_SMOKE_TIMEOUT_SECONDS=timeout or '10', + FLEET_SMOKE_CLEANUP_TIMEOUT_SECONDS='1') + started = time.monotonic() + process = subprocess.Popen([str(wrapper), *arguments], env=environment, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT) + try: + if send_signal: + deadline = time.monotonic() + 5 + while not (directory / 'descendant').exists(): + check(process.poll() is None, scenario + ' exited before signal') + check(time.monotonic() < deadline, scenario + ' did not start') + time.sleep(0.02) + process.send_signal(send_signal) + output = process.communicate(timeout=15)[0].decode() + finally: + if process.poll() is None: + process.kill() + process.communicate() + check(process.returncode == expected, scenario + ': unexpected status ' + str(process.returncode) + '\n' + output) + check(time.monotonic() - started < 15, scenario + ': unbounded execution') + check('SYNTHETIC-SECRET' not in output, scenario + ': raw diagnostics leaked') + for credential in credentials: + check(credential.read_text() == 'user-config-and-current-context-must-not-change\n', scenario + ': changed user config') + check(not list(scratch.iterdir()), scenario + ': leaked private temporary files') + trace = directory / 'trace' + records = [json.loads(line) for line in trace.read_text().splitlines()] if trace.exists() else [] + stages = [record['stage'] for record in records] + for record in records: + check(record['cluster'].startswith('fleet-smoke-') and record['cluster'] != 'unrelated-cluster', 'unsafe name') + check(record['context'] == 'kind-' + record['cluster'], 'unsafe context') + check(record['provider'] == 'docker' and record['alias'] == 'false', 'unsafe inherited settings') + check(record['mode'] == 0o600 and record['directory_mode'] == 0o700, 'public credentials') + check(Path(record['kubeconfig']).parent == Path(record['temporary']), 'nonprivate kubeconfig') + check(Path(record['temporary']).parent == scratch, 'nonprivate scratch') + check(not Path(record['temporary']).exists(), 'temporary directory survived') + check(stages.count('delete') == (1 if 'create' in stages else 0), scenario + ': wrong cleanup authority') + check(len({record['cluster'] for record in records}) <= 1, scenario + ': changed cluster identity') + if 'create' in stages: + names.append(records[0]['cluster']) + if scenario not in ('delete_fail', 'smoke_delete_fail', 'delete_timeout'): + check(not (directory / 'owned-cluster').exists(), scenario + ': cluster leaked') + else: + check('cleanup unverified' in output, scenario + ': cleanup uncertainty concealed') + if scenario in ('collision', 'create_fail', 'create_timeout', 'create_signal'): + check('standalone-smoke.sh' not in stages, scenario + ': ran smoke without fresh cluster') + if scenario == 'success': + check(stages == ['docker', 'get', 'create', 'standalone-smoke.sh', 'delete'], 'incorrect success lifecycle') + descendant = directory / 'descendant' + if descendant.exists(): + process_id = int(descendant.read_text()) + state = subprocess.run(['ps', '-o', 'stat=', '-p', str(process_id)], + capture_output=True, text=True, check=False).stdout.strip() + check(not state or state.startswith('Z'), scenario + ': descendant survived process-group cleanup') + print('PASS ' + scenario + (': missing ' + missing if missing else '')) + + case('success', 0) + case('success', 0) + for tool in ('python3', 'docker', 'kind', 'kubectl', 'kustomize', 'git'): + case('missing', 1, missing=tool) + case('arguments', 1, arguments=('existing-cluster',)) + for value in ('0', '-1', 'oops', '3601'): + case('invalid_timeout', 1, timeout=value) + case('docker_fail', 71) + case('wrong_os', 1) + case('list_fail', 73) + case('collision', 1) + case('create_fail', 74) + case('smoke_fail', 42) + case('delete_fail', 1) + case('smoke_delete_fail', 42) + case('docker_timeout', 124, timeout='1') + case('get_timeout', 124, timeout='1') + case('create_timeout', 124, timeout='1') + case('standalone-smoke.sh_timeout', 124, timeout='1') + case('delete_timeout', 1) + case('get_signal', 143, send_signal=signal.SIGTERM) + case('create_signal', 143, send_signal=signal.SIGTERM) + case('standalone-smoke.sh_signal', 130, send_signal=signal.SIGINT) + case('standalone-smoke.sh_signal', 129, send_signal=signal.SIGHUP) + case('delete_signal', 1, send_signal=signal.SIGTERM) + check(len(names) == len(set(names)), 'cluster names reused across invocations') + print('All disposable standalone smoke tests passed; no real tools or clusters used.') +PY diff --git a/hack/test-standalone-preflight.sh b/hack/test-standalone-preflight.sh index 2dcad9e0..5edbc741 100755 --- a/hack/test-standalone-preflight.sh +++ b/hack/test-standalone-preflight.sh @@ -55,3 +55,62 @@ for manager in fleet-manager fleet-milo-manager; do fi done grep -q 'fleet-manager.*fleet-milo-manager' "$root/docs/operations/standalone-smoke.md" + +cat >"$temporary/docker" <<'EOF' +#!/bin/sh +exit 0 +EOF +cat >"$temporary/kustomize" <<'EOF' +#!/bin/sh +set -eu +case "$*" in + 'build config/base/crd') echo 'kind: CustomResourceDefinition' ;; + 'build config/standalone') + test -f "$ORDER_DIRECTORY/established" + echo 'kind: Installation' + ;; + *) exit 99 ;; +esac +EOF +cat >"$temporary/kubectl" <<'EOF' +#!/bin/sh +set -eu +case " $* " in + *" config view "*) printf '%s' 'https://127.0.0.1:6443' ;; + *" get deployments -A "*) exit 0 ;; + *" get "*) exit 1 ;; + *" apply -f "*) + for argument do manifest=$argument; done + if grep -q 'CustomResourceDefinition' "$manifest"; then + touch "$ORDER_DIRECTORY/crds-applied" + else + test -f "$ORDER_DIRECTORY/established" + grep -q 'Installation' "$manifest" + touch "$ORDER_DIRECTORY/fixtures-applied" + fi + ;; + *" wait --for=condition=Established "*) + test -f "$ORDER_DIRECTORY/crds-applied" + test "$ESTABLISHMENT_RESULT" = success + touch "$ORDER_DIRECTORY/established" + ;; + *" rollout status "*) echo 'ordering verified'; exit 97 ;; + *) exit 99 ;; +esac +EOF +chmod +x "$temporary/kustomize" +for result in success failure; do + order_directory="$temporary/$result" + mkdir "$order_directory" + if (cd "$root" && ORDER_DIRECTORY="$order_directory" ESTABLISHMENT_RESULT="$result" PATH="$temporary:$PATH" ./hack/standalone-smoke.sh >"$temporary/output" 2>&1); then + echo 'ordering fixture unexpectedly completed a live smoke' >&2 + exit 1 + fi + test -f "$order_directory/crds-applied" + if [ "$result" = success ]; then + test -f "$order_directory/fixtures-applied" + grep -q 'ordering verified' "$temporary/output" + else + test ! -e "$order_directory/fixtures-applied" + fi +done diff --git a/hack/validate-standalone-render.sh b/hack/validate-standalone-render.sh index 7faa9b1e..cba9052c 100755 --- a/hack/validate-standalone-render.sh +++ b/hack/validate-standalone-render.sh @@ -8,19 +8,21 @@ kustomize build config/standalone >"$rendered" require_count() { expected=$1 pattern=$2 - actual=$(grep -c "$pattern" "$rendered" || true) + actual=$(grep -c -- "$pattern" "$rendered" || true) if [ "$actual" -ne "$expected" ]; then echo "rendered manifest count for $pattern = $actual, want $expected" >&2 exit 1 fi } -# One simulator pod template and three suspended phase-job templates. -require_count 4 'runAsUser: 65532' -require_count 4 'runAsGroup: 65532' -require_count 4 'fsGroup: 65532' -require_count 4 'defaultMode: 288' -require_count 4 'imagePullPolicy: Never' +require_count 5 'runAsUser: 65532' +require_count 5 'runAsGroup: 65532' +require_count 5 'fsGroup: 65532' +require_count 5 'defaultMode: 288' +require_count 5 'imagePullPolicy: Never' +require_count 4 'suspend: true' +require_count 1 'name: fleet-smoke-reinstall' +require_count 1 '--phase=reinstall' require_count 1 'fsGroupChangePolicy: OnRootMismatch' require_count 1 'mountPath: /var/lib/fleet' require_count 1 'volumeClaimTemplates:' diff --git a/internal/standalone/reinstall_test.go b/internal/standalone/reinstall_test.go new file mode 100644 index 00000000..28d442f5 --- /dev/null +++ b/internal/standalone/reinstall_test.go @@ -0,0 +1,347 @@ +package standalone + +import ( + "context" + "encoding/json" + "errors" + "reflect" + "sync" + "testing" + "time" + + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + apiMeta "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + + fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/controller" + "go.datum.net/fleet/internal/executor" + "go.datum.net/fleet/internal/simulator" +) + +type unavailableResultExecutor struct { + storeExecutor + beforeEffect func(simulator.Request) +} + +type changedHistoryExecutor struct { + storeExecutor + change func(simulator.OperationResult) (simulator.OperationResult, bool, error) +} + +func (e changedHistoryExecutor) Lookup(ctx context.Context, operationID string) (simulator.OperationResult, bool, error) { + result, _, err := e.storeExecutor.Lookup(ctx, operationID) + if err != nil { + return result, false, err + } + return e.change(result) +} + +func TestCompletedInstallationRequiresSimulatorHistory(t *testing.T) { + for _, phase := range []string{PhaseInstall, PhaseReinstall} { + for _, corruption := range []string{"missing", "unavailable", "identity", "inputs", "kind", "phase", "result", "completion"} { + t.Run(phase+"/"+corruption, func(t *testing.T) { + runner, store, _ := reinstallFixture(t) + ctx := context.Background() + if err := runner.Run(ctx, phase); err != nil { + t.Fatal(err) + } + before := store.Snapshot() + runner.Executor = changedHistoryExecutor{storeExecutor{store}, func(result simulator.OperationResult) (simulator.OperationResult, bool, error) { + switch corruption { + case "missing": + return simulator.OperationResult{}, false, nil + case "unavailable": + return simulator.OperationResult{}, false, executor.ErrOutcomeUnknown + case "identity": + result.ID = "different-operation" + case "inputs": + result.InputDigest = "different-retained-request" + case "kind": + result.Kind = "cleanup" + case "phase": + result.Phase = "Pending" + case "result": + result.Result = "clean" + case "completion": + result.CompletedAt = nil + } + return result, true, nil + }} + if err := runner.Run(ctx, phase); !errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatalf("unverified replay = %v", err) + } + claim, _, _, err := runner.claim(ctx, runner.Options.FirstNamespace) + if err != nil { + t.Fatal(err) + } + if !apiMeta.IsStatusConditionPresentAndEqual(claim.Status.Conditions, "Ready", metav1.ConditionUnknown) { + t.Fatal("unverified history left machine ready") + } + if !reflect.DeepEqual(before, store.Snapshot()) { + t.Fatal("history verification executed a new effect") + } + assertWaitingConsumerBlocked(t, runner) + }) + } + } +} + +func (e unavailableResultExecutor) Execute(ctx context.Context, request simulator.Request) (simulator.OperationResult, error) { + if e.beforeEffect != nil { + e.beforeEffect(request) + } + if _, err := e.storeExecutor.Execute(ctx, request); err != nil { + return simulator.OperationResult{}, err + } + return simulator.OperationResult{}, executor.ErrOutcomeUnknown +} + +func (e unavailableResultExecutor) Lookup(context.Context, string) (simulator.OperationResult, bool, error) { + return simulator.OperationResult{}, false, executor.ErrOutcomeUnknown +} + +func reinstallFixture(t *testing.T) (Runner, *simulator.Store, string) { + t.Helper() + scheme := runtime.NewScheme() + if err := corev1.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + if err := fleetv1.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + options := DefaultOptions() + objects := append(fixtureObjects(options), &fleetv1.Installation{ + ObjectMeta: metav1.ObjectMeta{Namespace: options.FirstNamespace, Name: options.ReinstallationName, UID: "reinstallation-uid", Generation: 1}, + Spec: fleetv1.InstallationSpec{MachineRef: fleetv1.MachineReference{Name: options.ClaimName}, ExpectedPredecessor: fleetv1.InstallationPredecessor{Type: "Installation", Name: options.InstallationName}, ImageRef: fleetv1.LocalReference{Name: options.ImageName}}, + }) + kube := fake.NewClientBuilder().WithScheme(scheme).WithObjects(objects...).WithStatusSubresource(&fleetv1.MachineCapacity{}, &fleetv1.Machine{}, &fleetv1.Installation{}).Build() + path := t.TempDir() + "/state.json" + store, err := simulator.Open(path) + if err != nil { + t.Fatal(err) + } + runner := Runner{Client: kube, Executor: storeExecutor{store}, Options: options, Now: time.Now} + for _, phase := range []string{PhaseAllocate, PhaseInstall} { + if err := runner.Run(context.Background(), phase); err != nil { + t.Fatal(err) + } + } + return runner, store, path +} + +func retainedAsset(t *testing.T, runner Runner) controller.AssetRecord { + t.Helper() + var secrets corev1.SecretList + if err := runner.Client.List(context.Background(), &secrets, client.InNamespace(runner.Options.PrivateNamespace), client.MatchingLabels{"fleet.datumapis.com/private-record": "asset"}); err != nil { + t.Fatal(err) + } + if len(secrets.Items) != 1 { + t.Fatalf("retained assets = %d, want 1", len(secrets.Items)) + } + var record controller.AssetRecord + if err := json.Unmarshal(secrets.Items[0].Data["record.json"], &record); err != nil { + t.Fatal(err) + } + return record +} + +func assertWaitingConsumerBlocked(t *testing.T, runner Runner) { + t.Helper() + ctx := context.Background() + coordinator, err := controller.NewCoordinator(runner.Client, runner.Options.PrivateNamespace, runner.Executor, controller.LocalDigestImageResolver{}, nil, runner.Options.EvidenceAge) + if err != nil { + t.Fatal(err) + } + claim, namespace, admission, err := runner.claim(ctx, runner.Options.SecondNamespace) + if err != nil { + t.Fatal(err) + } + var class fleetv1.MachineClass + var profile fleetv1.MachineProfile + var machine fleetv1.MachineCapacity + for _, object := range []client.Object{&class, &profile, &machine} { + key := client.ObjectKey{} + switch object.(type) { + case *fleetv1.MachineClass: + key.Name = runner.Options.ClassName + case *fleetv1.MachineProfile: + key.Name = runner.Options.ProfileName + default: + key = client.ObjectKey{Namespace: runner.Options.ProviderNamespace, Name: runner.Options.MachineName} + } + if err := runner.Client.Get(ctx, key, object); err != nil { + t.Fatal(err) + } + } + if apiMeta.IsStatusConditionTrue(machine.Status.Conditions, "Available") { + t.Fatal("reinstall exposed occupied capacity as available") + } + apiMeta.SetStatusCondition(&machine.Status.Conditions, condition("Available", metav1.ConditionTrue, machine.Generation, "SyntheticStaleAvailability", "Synthetic stale projection cannot override custody.")) + if _, err := coordinator.Allocate(ctx, allocationRequest(claim, namespace, admission, &class, &profile, &machine, time.Now())); !errors.Is(err, controller.ErrInsufficientCapacity) { + t.Fatalf("waiting allocation with stale Available=True: %v", err) + } +} + +func TestReinstallRecoversExactOperationAndRejectsStalePredecessor(t *testing.T) { + ctx := context.Background() + runner, store, path := reinstallFixture(t) + before := retainedAsset(t, runner) + var operationID string + runner.Executor = unavailableResultExecutor{storeExecutor: storeExecutor{store}, beforeEffect: func(request simulator.Request) { + asset := retainedAsset(t, runner) + if asset.ActiveOperationID != request.ID || asset.CurrentInstallationName != runner.Options.InstallationName || asset.BindingID != before.BindingID || asset.Epoch != before.Epoch { + t.Fatalf("effect lacks retained predecessor/authority: %#v", asset) + } + var secrets corev1.SecretList + if err := runner.Client.List(ctx, &secrets, client.InNamespace(runner.Options.PrivateNamespace)); err != nil { + t.Fatal(err) + } + found := false + for _, secret := range secrets.Items { + var operation controller.InstallationRecord + if json.Unmarshal(secret.Data["record.json"], &operation) == nil && operation.OperationID == request.ID { + found = operation.InstallationUID == "reinstallation-uid" && operation.Predecessor == runner.Options.InstallationName && operation.BindingID == before.BindingID && operation.ImageName == runner.Options.ImageName && operation.Admission.DecisionID == "standalone-install-reinstallation-uid" + } + } + if !found { + t.Fatal("exact reinstall inputs not retained before effect") + } + operationID = request.ID + }} + if err := runner.Run(ctx, PhaseReinstall); !errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatalf("lost result = %v", err) + } + claim, _, _, err := runner.claim(ctx, runner.Options.FirstNamespace) + if err != nil { + t.Fatal(err) + } + if !apiMeta.IsStatusConditionPresentAndEqual(claim.Status.Conditions, "Ready", metav1.ConditionUnknown) || claim.Status.CurrentInstallationRef.Name != runner.Options.InstallationName { + t.Fatalf("unknown reinstall advanced readiness: %#v", claim.Status) + } + assertWaitingConsumerBlocked(t, runner) + reopened, err := simulator.Open(path) + if err != nil { + t.Fatal(err) + } + restarted := Runner{Client: runner.Client, Executor: storeExecutor{reopened}, Options: runner.Options, Now: time.Now} + for range 2 { + if err := restarted.Run(ctx, PhaseReinstall); err != nil { + t.Fatal(err) + } + } + after := retainedAsset(t, restarted) + if after.BindingID != before.BindingID || after.Epoch != before.Epoch || after.ClaimUID != before.ClaimUID || after.CurrentInstallationName != runner.Options.ReinstallationName || after.ActiveOperationID != "" { + t.Fatalf("reinstall changed custody or failed completion: %#v", after) + } + snapshot := reopened.Snapshot() + if len(snapshot.Operations) != 2 || snapshot.Operations[operationID] == nil || !reflect.DeepEqual(snapshot.Operations[operationID], store.Snapshot().Operations[operationID]) { + t.Fatal("retry/restart changed the retained effect") + } + assertWaitingConsumerBlocked(t, restarted) + claim, _, _, err = restarted.claim(ctx, runner.Options.FirstNamespace) + if err != nil { + t.Fatal(err) + } + var installed fleetv1.Installation + if err := runner.Client.Get(ctx, client.ObjectKey{Namespace: runner.Options.FirstNamespace, Name: runner.Options.ReinstallationName}, &installed); err != nil { + t.Fatal(err) + } + if !apiMeta.IsStatusConditionTrue(claim.Status.Conditions, "Ready") || claim.Status.CurrentInstallationRef.Name != installed.Name || installed.Status.Phase != "Ready" || installed.Status.CompletedAt == nil { + t.Fatal("verified reinstall did not project synthetic completion") + } + stale := &fleetv1.Installation{ObjectMeta: metav1.ObjectMeta{Namespace: runner.Options.FirstNamespace, Name: "stale-reinstall", UID: "stale-uid"}, Spec: fleetv1.InstallationSpec{MachineRef: fleetv1.MachineReference{Name: runner.Options.ClaimName}, ExpectedPredecessor: fleetv1.InstallationPredecessor{Type: "Installation", Name: runner.Options.InstallationName}, ImageRef: fleetv1.LocalReference{Name: runner.Options.ImageName}}} + if err := runner.Client.Create(ctx, stale); err != nil { + t.Fatal(err) + } + staleRunner := restarted + staleRunner.Options.InstallationName = stale.Name + if err := staleRunner.Run(ctx, PhaseInstall); !errors.Is(err, controller.ErrPredecessorConflict) { + t.Fatalf("stale predecessor accepted: %v", err) + } + if !reflect.DeepEqual(snapshot, reopened.Snapshot()) { + t.Fatal("stale predecessor produced a simulator effect") + } + if err := restarted.Run(ctx, PhaseReinstall); err != nil { + t.Fatal(err) + } + if err := restarted.Run(ctx, PhaseRelease); err != nil { + t.Fatal(err) + } + if len(reopened.Snapshot().Operations) != 3 { + t.Fatal("release did not retain exactly two installs and one cleanup") + } + assertRetainedOwner(t, runner.Client, runner.Options, "claim-b-uid", 2) +} + +func TestUnknownReinstallBlocksReleaseAndCapacityReuse(t *testing.T) { + runner, store, _ := reinstallFixture(t) + runner.Executor = unavailableResultExecutor{storeExecutor: storeExecutor{store}} + if err := runner.Run(context.Background(), PhaseReinstall); !errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatal(err) + } + if err := runner.Run(context.Background(), PhaseRelease); !errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatalf("release with unresolved reinstall = %v", err) + } + assertRetainedOwner(t, runner.Client, runner.Options, "claim-a-uid", 1) + assertWaitingConsumerBlocked(t, runner) + if len(store.Snapshot().Operations) != 2 { + t.Fatal("unknown reinstall allowed premature cleanup") + } +} + +func TestConcurrentReinstallConvergesWithoutDuplicateEffects(t *testing.T) { + runner, store, _ := reinstallFixture(t) + var workers sync.WaitGroup + results := make(chan error, 4) + for range cap(results) { + workers.Go(func() { results <- runner.Run(context.Background(), PhaseReinstall) }) + } + workers.Wait() + close(results) + for err := range results { + if err != nil && !apierrors.IsConflict(err) && !errors.Is(err, controller.ErrPredecessorConflict) { + t.Fatalf("unexpected concurrent outcome: %v", err) + } + } + if err := runner.Run(context.Background(), PhaseReinstall); err != nil { + t.Fatal(err) + } + if len(store.Snapshot().Operations) != 2 { + t.Fatal("concurrent retries duplicated installation effects") + } + assertRetainedOwner(t, runner.Client, runner.Options, "claim-a-uid", 1) +} + +func TestReinstallRequiresBoundedSuccessorFixture(t *testing.T) { + for _, variant := range []string{"missing", "same-name", "wrong-predecessor"} { + t.Run(variant, func(t *testing.T) { + runner, store, _ := reinstallFixture(t) + switch variant { + case "missing": + runner.Options.ReinstallationName = "" + case "same-name": + runner.Options.ReinstallationName = runner.Options.InstallationName + case "wrong-predecessor": + var installation fleetv1.Installation + if err := runner.Client.Get(context.Background(), client.ObjectKey{Namespace: runner.Options.FirstNamespace, Name: runner.Options.ReinstallationName}, &installation); err != nil { + t.Fatal(err) + } + installation.Spec.ExpectedPredecessor = fleetv1.InstallationPredecessor{Type: "None"} + if err := runner.Client.Update(context.Background(), &installation); err != nil { + t.Fatal(err) + } + } + if err := runner.Run(context.Background(), PhaseReinstall); err == nil { + t.Fatal("invalid successor fixture accepted") + } + if len(store.Snapshot().Operations) != 1 { + t.Fatal("invalid successor produced an effect") + } + }) + } +} diff --git a/internal/standalone/runner.go b/internal/standalone/runner.go index d03ef281..db3ad686 100644 --- a/internal/standalone/runner.go +++ b/internal/standalone/runner.go @@ -23,24 +23,26 @@ import ( ) const ( - PhaseAllocate = "allocate" - PhaseInstall = "install" - PhaseRelease = "release" + PhaseAllocate = "allocate" + PhaseInstall = "install" + PhaseReinstall = "reinstall" + PhaseRelease = "release" ) type Options struct { - PrivateNamespace string - ProviderNamespace string - FirstNamespace string - SecondNamespace string - ClassName string - ProfileName string - MachineName string - ClaimName string - InstallationName string - ImageName string - LocationName string - EvidenceAge time.Duration + PrivateNamespace string + ProviderNamespace string + FirstNamespace string + SecondNamespace string + ClassName string + ProfileName string + MachineName string + ClaimName string + InstallationName string + ReinstallationName string + ImageName string + LocationName string + EvidenceAge time.Duration } func DefaultOptions() Options { @@ -49,7 +51,8 @@ func DefaultOptions() Options { FirstNamespace: "fleet-project-a", SecondNamespace: "fleet-project-b", ClassName: "standard-metal", ProfileName: "general-purpose-24c-128g", MachineName: "central1-baremetal-01", ClaimName: "allocation", - InstallationName: "debian-12", ImageName: "debian-12@sha256:9f4ad8d8b8a6f6fc64d2cf2c7e70b9184b74f089adf8c36d84f4fcb99892f3cb", + ReinstallationName: "debian-12-reinstall", + InstallationName: "debian-12", ImageName: "debian-12@sha256:9f4ad8d8b8a6f6fc64d2cf2c7e70b9184b74f089adf8c36d84f4fcb99892f3cb", LocationName: "us-central-1", EvidenceAge: 5 * time.Minute, } } @@ -89,7 +92,12 @@ func (r Runner) Run(ctx context.Context, phase string) error { case PhaseAllocate: return r.allocate(ctx, coordinator) case PhaseInstall: - return r.install(ctx, coordinator) + return r.install(ctx, coordinator, r.Options.InstallationName) + case PhaseReinstall: + if r.Options.ReinstallationName == "" || r.Options.ReinstallationName == r.Options.InstallationName { + return errors.New("reinstall requires a distinct installation name") + } + return r.install(ctx, coordinator, r.Options.ReinstallationName) case PhaseRelease: return r.release(ctx, coordinator) default: @@ -140,13 +148,20 @@ func (r Runner) allocate(ctx context.Context, coordinator *controller.Coordinato return r.projectPendingClaim(ctx, second, profile, "InsufficientCapacity", "The only synthetic machine is allocated to another consumer.") } -func (r Runner) install(ctx context.Context, coordinator *controller.Coordinator) error { +func (r Runner) install(ctx context.Context, coordinator *controller.Coordinator, installationName string) error { claim, namespace, admission, err := r.claim(ctx, r.Options.FirstNamespace) if err != nil { return err } var installation fleetv1.Installation - if err := r.Client.Get(ctx, client.ObjectKey{Namespace: claim.Namespace, Name: r.Options.InstallationName}, &installation); err != nil { + if err := r.Client.Get(ctx, client.ObjectKey{Namespace: claim.Namespace, Name: installationName}, &installation); err != nil { + return err + } + if installationName == r.Options.ReinstallationName && installation.Spec.ExpectedPredecessor != (fleetv1.InstallationPredecessor{Type: "Installation", Name: r.Options.InstallationName}) { + return errors.New("synthetic reinstall must name the configured initial installation as predecessor") + } + apiMeta.SetStatusCondition(&claim.Status.Conditions, condition("Ready", metav1.ConditionUnknown, claim.Generation, "SyntheticInstallationUnverified", "The synthetic installation request has not yet returned verified completion.")) + if err := r.Client.Status().Update(ctx, claim); err != nil { return err } imageDecision := "local-test-" + imageDigest(r.Options.ImageName) From aa342de78357ac809e4e1cbc3655001480c57d16 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Thu, 19 Nov 2026 13:59:16 -0600 Subject: [PATCH 007/518] fix(standalone): wait for the simulator Service before a smoke phase The kind smoke restarts the simulator and immediately runs the recovery phase. On a slow runner the phase's first request could reach no pod while the Service moved to the new one, and the lifecycle correctly reported that transport failure as an unknown outcome. The phase now waits, without effect, until the simulator answers readiness through its Service, so the recovery check measures recovery and not the handover. Co-Authored-By: Claude Opus 5.5 --- cmd/fleet-standalone-smoke/main.go | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/cmd/fleet-standalone-smoke/main.go b/cmd/fleet-standalone-smoke/main.go index 8f388da7..e8b4c484 100644 --- a/cmd/fleet-standalone-smoke/main.go +++ b/cmd/fleet-standalone-smoke/main.go @@ -57,6 +57,9 @@ func main() { if err != nil { fail(err) } + if err := awaitSimulator(simulatorURL, 2*time.Minute); err != nil { + fail(err) + } if err := (standalone.Runner{Client: kube, Executor: provider, Options: options}).Run(context.Background(), phase); err != nil { fail(err) } @@ -64,3 +67,25 @@ func main() { } func fail(err error) { fmt.Fprintln(os.Stderr, err); os.Exit(1) } + +// awaitSimulator waits until the simulator's Service answers readiness. A +// phase started just after a simulator restart can otherwise reach no pod, +// and the lifecycle correctly reports that transport failure as an unknown +// outcome. Readiness has no effect and is never operation evidence. +func awaitSimulator(base string, limit time.Duration) error { + c := &http.Client{Timeout: 5 * time.Second} + deadline := time.Now().Add(limit) + for { + resp, err := c.Get(strings.TrimRight(base, "/") + "/readyz") + if err == nil { + resp.Body.Close() + if resp.StatusCode == http.StatusOK { + return nil + } + } + if time.Now().After(deadline) { + return fmt.Errorf("simulator did not become reachable and ready within %s", limit) + } + time.Sleep(time.Second) + } +} From 991c886004879d101a946c34773a5fc5cedac142 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 18 Nov 2026 13:28:30 -0600 Subject: [PATCH 008/518] feat(localvm): install a real OS over firmware PXE into a disposable VM internal/localvm is a bounded libvirt executor behind the existing executor contract. It boots a blank disk over iPXE from a digest-pinned installer, admits one-time network boot only for the retained operation, verifies the installed receipt from serial output and the domain's disappearance, then boots disk-only. Recovery replays the retained request without a second installer start; cleanup deletes only that binding's disks after verifying no matching domain, and returns a request-bound clean result. cmd/fleet-local-vm and hack/local-vm/run.sh drive allocation, install, crash recovery, reinstall, cleanup and reuse through the shared lifecycle library against a disposable Kubernetes API (task local-vm:acceptance, TCG in the task-owned Colima profile). This is not KVM, hardware or production qualification. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 1 + .gitignore | 3 + Taskfile.yaml | 8 + cmd/fleet-local-vm/main.go | 230 ++++++ docs/development/README.md | 7 +- docs/operations/README.md | 1 + .../local-vm-adversarial-validation.md | 211 ++++++ docs/operations/local-vm.md | 309 ++++++++ hack/local-vm/Containerfile | 18 + hack/local-vm/boot | 10 + hack/local-vm/init | 37 + hack/local-vm/run.sh | 115 +++ hack/local-vm/start-libvirt | 16 + internal/localvm/boot.go | 258 +++++++ internal/localvm/boot_test.go | 123 +++ internal/localvm/lifecycle_test.go | 294 +++++++ internal/localvm/provider.go | 715 ++++++++++++++++++ internal/localvm/provider_test.go | 35 + .../localvm/pxe_review_adversarial_test.go | 189 +++++ internal/localvm/site_test.go | 116 +++ 20 files changed, 2695 insertions(+), 1 deletion(-) create mode 100644 cmd/fleet-local-vm/main.go create mode 100644 docs/operations/local-vm-adversarial-validation.md create mode 100644 docs/operations/local-vm.md create mode 100644 hack/local-vm/Containerfile create mode 100644 hack/local-vm/boot create mode 100644 hack/local-vm/init create mode 100755 hack/local-vm/run.sh create mode 100644 hack/local-vm/start-libvirt create mode 100644 internal/localvm/boot.go create mode 100644 internal/localvm/boot_test.go create mode 100644 internal/localvm/lifecycle_test.go create mode 100644 internal/localvm/provider.go create mode 100644 internal/localvm/provider_test.go create mode 100644 internal/localvm/pxe_review_adversarial_test.go create mode 100644 internal/localvm/site_test.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ffadd068..b27a066e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -35,6 +35,7 @@ jobs: - run: ./hack/test-standalone-build-context.sh - run: ./hack/test-run-standalone-smoke.sh - run: ./hack/validate-doc-links.sh + - run: shellcheck -S warning hack/local-vm/run.sh hack/local-vm/start-libvirt standalone-smoke: runs-on: ubuntu-latest timeout-minutes: 35 diff --git a/.gitignore b/.gitignore index d105526d..1e2ab3f7 100644 --- a/.gitignore +++ b/.gitignore @@ -27,3 +27,6 @@ # Local agent settings .claude/settings.local.json .claude/worktrees/ + +# Locally built binaries +/fleet-local-vm diff --git a/Taskfile.yaml b/Taskfile.yaml index a2aa0339..700437ce 100644 --- a/Taskfile.yaml +++ b/Taskfile.yaml @@ -6,6 +6,14 @@ tasks: cmds: - ./hack/run-standalone-smoke.sh + local-vm:acceptance: + desc: Single-plane local VM PXE acceptance with explicit TCG in the task-owned Colima profile. + env: + DOCKER_CONTEXT: colima-fleet-acceptance-tcg + FLEET_LOCAL_VM_ACCEL: tcg + cmds: + - bash hack/local-vm/run.sh + manifests:validate: desc: Render and validate the production Fleet and Milo manifest roots. cmds: diff --git a/cmd/fleet-local-vm/main.go b/cmd/fleet-local-vm/main.go new file mode 100644 index 00000000..71ea5570 --- /dev/null +++ b/cmd/fleet-local-vm/main.go @@ -0,0 +1,230 @@ +// fleet-local-vm is an explicit local acceptance harness, not a deployed controller. +package main + +import ( + "context" + "encoding/json" + "errors" + "fmt" + api "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/controller" + "go.datum.net/fleet/internal/executor" + "go.datum.net/fleet/internal/localvm" + "go.datum.net/fleet/internal/simulator" + core "k8s.io/api/core/v1" + meta "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/types" + "k8s.io/client-go/tools/clientcmd" + "os" + "sigs.k8s.io/controller-runtime/pkg/client" + "strings" + "time" +) + +type crashAfterEffect struct{ *localvm.Provider } + +func (p crashAfterEffect) Execute(ctx context.Context, q simulator.Request) (simulator.OperationResult, error) { + r, e := p.Provider.Execute(ctx, q) + if e == nil && q.Kind == "install" { + os.Exit(75) + } + return r, e +} + +func main() { + if e := work(); e != nil { + fmt.Fprintln(os.Stderr, e) + os.Exit(1) + } +} +func work() error { + ctx, cancel := context.WithTimeout(context.Background(), 12*time.Minute) + defer cancel() + p, e := localvm.Open() + if e != nil { + return e + } + if len(os.Args) == 2 && os.Args[1] == "boot-denials" { + summary, err := p.CheckClosedBoot("") + if err != nil { + return err + } + return os.WriteFile(localvm.Root+"/boot-denials.txt", []byte(summary+"\n"), 0600) + } + if len(os.Args) == 2 && os.Args[1] == "boot-service" { + return p.ServeBoot() + } + if len(os.Args) == 2 && os.Args[1] == "image" { + fmt.Println(p.ImageReference()) + return nil + } + if len(os.Args) != 2 { + return errors.New("phase required") + } + config, e := clientcmd.BuildConfigFromFlags("", "/run/fleet/kubeconfig") + if e != nil { + return e + } + scheme := runtime.NewScheme() + core.AddToScheme(scheme) + api.AddToScheme(scheme) + k, e := client.New(config, client.Options{Scheme: scheme}) + if e != nil { + return e + } + var backend executor.Client = p + if os.Args[1] == "install-crash" { + backend = crashAfterEffect{p} + } + c, e := controller.NewCoordinator(k, "fleet-system-private", backend, controller.LocalDigestImageResolver{}, nil, time.Hour) + if e != nil { + return e + } + var capacity api.MachineCapacity + var class api.MachineClass + var profile api.MachineProfile + for _, item := range []struct { + key client.ObjectKey + obj client.Object + }{{client.ObjectKey{Namespace: "fleet-provider", Name: "central1-baremetal-01"}, &capacity}, {client.ObjectKey{Name: "standard-metal"}, &class}, {client.ObjectKey{Name: "general-purpose-24c-128g"}, &profile}} { + if e = k.Get(ctx, item.key, item.obj); e != nil { + return e + } + } + // Explicit operator-owned local inventory; no imported device is adopted. + capacity.Status.Hardware = api.Hardware{CPU: api.HardwareCPU{Architecture: "amd64", Cores: 2, Threads: 2, Sockets: 1}, Memory: api.HardwareMemory{Capacity: "2Gi"}} + now := time.Now().UTC() + for _, name := range []string{"Prepared", "Healthy", "Available"} { + capacity.Status.Conditions = append(capacity.Status.Conditions, meta.Condition{Type: name, Status: meta.ConditionTrue, ObservedGeneration: capacity.Generation, LastTransitionTime: meta.NewTime(now), Reason: "LocalDisposableDevice", Message: "Operator-created local VM slot; private custody is authoritative."}) + } + if e = k.Status().Update(ctx, &capacity); e != nil { + return e + } + getClaim := func(ns string) (*api.Machine, *core.Namespace, error) { + m := &api.Machine{} + n := &core.Namespace{} + if e := k.Get(ctx, client.ObjectKey{Namespace: ns, Name: "allocation"}, m); e != nil { + return nil, nil, e + } + if e := k.Get(ctx, client.ObjectKey{Name: ns}, n); e != nil { + return nil, nil, e + } + return m, n, nil + } + allocate := func(ns string) (*controller.AssetRecord, error) { + m, n, e := getClaim(ns) + if e != nil { + return nil, e + } + auth := controller.AdmissionAuthority{PrincipalUID: "local-operator", DecisionID: "local-" + string(m.UID)} + if e = c.EnsureClaimCustody(ctx, m, n.UID, auth); e != nil { + return nil, e + } + if len(m.Finalizers) == 0 { + m.Finalizers = []string{controller.MachineFinalizer} + if e = k.Update(ctx, m); e != nil { + return nil, e + } + } + return c.Allocate(ctx, controller.AllocationRequest{Claim: m, Class: &class, Profile: &profile, MachineCapacities: []api.MachineCapacity{capacity}, EvidenceObservedAt: map[types.UID]time.Time{capacity.UID: now}, NamespaceUID: n.UID, Admission: auth, LocalClassName: class.Name, LocalClassUID: class.UID, LocalProfileName: profile.Name, LocalProfileUID: profile.UID}) + } + phase := os.Args[1] + switch phase { + case "allocate": + r, e := allocate("fleet-project-a") + if e != nil { + return e + } + if _, e = allocate("fleet-project-b"); !errors.Is(e, controller.ErrInsufficientCapacity) { + return fmt.Errorf("contention failed: %v", e) + } + fmt.Printf("exclusive allocation %s asset %s\n", r.BindingID, r.AssetID) + case "install", "install-crash", "reinstall": + m, n, e := getClaim("fleet-project-a") + if e != nil { + return e + } + name := "debian-12" + if phase == "reinstall" { + name += "-reinstall" + } + var in api.Installation + if e = k.Get(ctx, client.ObjectKey{Namespace: m.Namespace, Name: name}, &in); e != nil { + return e + } + m.Status.Phase = "Pending" + m.Status.Conditions = []meta.Condition{{Type: "Ready", Status: meta.ConditionUnknown, ObservedGeneration: m.Generation, LastTransitionTime: meta.Now(), Reason: "LocalInstallationUnverified", Message: "Installation outcome has not been verified."}} + if e = k.Status().Update(ctx, m); e != nil { + return e + } + result, e := c.Install(ctx, controller.InstallationRequest{Claim: m, Installation: &in, NamespaceUID: n.UID, Admission: controller.InstallationAdmissionAuthority{PrincipalUID: "local-operator", DecisionID: "local-" + string(in.UID), CatalogAuthority: "local-test-catalog", CatalogRevision: "local-test-v1", ImageDecisionID: "local-test-" + strings.Split(p.ImageReference(), "@")[1]}}) + if e != nil { + return e + } + receipt, found, e := p.Lookup(ctx, result.Record.OperationID) + if e != nil || !found || receipt.InputDigest != result.RequestDigest { + return errors.New("exact provider receipt missing") + } + in.Status = api.InstallationStatus{Phase: "Ready", CompletedAt: &meta.Time{Time: *receipt.CompletedAt}, Conditions: []meta.Condition{{Type: "Ready", Status: meta.ConditionTrue, ObservedGeneration: in.Generation, LastTransitionTime: meta.Now(), Reason: "LocalDiskBootVerified", Message: "Pinned Linux installer and disk boot verified through local libvirt."}}} + if e = k.Status().Update(ctx, &in); e != nil { + return e + } + m.Status.CurrentInstallationRef = &api.LocalReference{Name: name} + m.Status.Phase = "Ready" + m.Status.Conditions = []meta.Condition{{Type: "Ready", Status: meta.ConditionTrue, ObservedGeneration: m.Generation, LastTransitionTime: meta.Now(), Reason: "LocalDiskBootVerified", Message: "Exact installation-bound disk boot and powered-off handoff verified."}} + if e = k.Status().Update(ctx, m); e != nil { + return e + } + fmt.Printf("verified installation %s operation %s\n", in.UID, receipt.ID) + case "release": + m, _, e := getClaim("fleet-project-a") + if e != nil { + return e + } + if m.DeletionTimestamp == nil { + if e = k.Delete(ctx, m, client.Preconditions{UID: &m.UID, ResourceVersion: &m.ResourceVersion}); e != nil { + return e + } + } + r, e := c.Release(ctx, m.UID) + if e != nil { + return e + } + if !r.SafeToRemoveFinalizer { + return errors.New("cleanup not verified") + } + current := &api.Machine{} + if e = k.Get(ctx, client.ObjectKeyFromObject(m), current); e != nil { + return e + } + if current.UID != m.UID { + return errors.New("consumer machine identity changed during release") + } + kept := current.Finalizers[:0] + for _, f := range current.Finalizers { + if f != controller.MachineFinalizer { + kept = append(kept, f) + } + } + current.Finalizers = kept + if e = k.Update(ctx, current); e != nil { + return e + } + + if _, e = allocate("fleet-project-b"); e != nil { + return e + } + fmt.Println("cleanup verified; capacity exclusively reused by second consumer") + case "evidence": + var installs api.InstallationList + if e = k.List(ctx, &installs); e != nil { + return e + } + b, _ := json.MarshalIndent(installs, "", " ") + return os.WriteFile(localvm.Root+"/installations.json", b, 0600) + default: + return errors.New("unsupported phase") + } + return nil +} diff --git a/docs/development/README.md b/docs/development/README.md index c1d4581e..e9938887 100644 --- a/docs/development/README.md +++ b/docs/development/README.md @@ -18,7 +18,12 @@ scenario exercises local-scope contention, install recovery, cleanup, and capacity reuse. An explicit Milo-routed synthetic staging overlay exercises event-driven Machine allocation, contention, cleanup, and reuse through the public project API. Production caller-preserving -admission, replayable Milo event adapters, and real providers are not implemented. +admission, replayable Milo event adapters, and production provider integration are not implemented. +An opt-in [local KVM installation harness](../operations/local-vm.md) implements +a bounded libvirt executor and guest installer using the same lifecycle library. +It uses a disposable Kubernetes API and explicit local authority fixtures; it is +not wired into the production manager. + Production Kustomize roots now package the implemented manager, admission, API, Milo IAM, service, and quota boundaries; packaging is not runtime readiness. diff --git a/docs/operations/README.md b/docs/operations/README.md index 7ff2feb7..f29795e1 100644 --- a/docs/operations/README.md +++ b/docs/operations/README.md @@ -13,6 +13,7 @@ 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, cleanup, and reuse | [Standalone smoke environment](standalone-smoke.md) | Same-cluster lifecycle behavior with namespaces as project stand-ins | +| Install a real OS over firmware PXE into a disposable local VM | [Local VM PXE installation](local-vm.md) | Single-plane real install, disk-only boot, recovery, cleanup and reuse under explicit TCG; not KVM or hardware qualification | | Render deployment bundles and supply environment inputs | [Deployment manifests](../../config/README.md) | Packaging and security boundaries, not runtime readiness | | Run the manager across consuming projects | [Project discovery](../../config/README.md#project-discovery) | Discovery, per-project isolation, departure, role bindings, and readiness | | Exercise Milo-routed synthetic staging | [Synthetic staging configuration](../../config/README.md#environment-owned-inputs) | Restricted synthetic publication and lifecycle behavior, not production authority | diff --git a/docs/operations/local-vm-adversarial-validation.md b/docs/operations/local-vm-adversarial-validation.md new file mode 100644 index 00000000..9dced04a --- /dev/null +++ b/docs/operations/local-vm-adversarial-validation.md @@ -0,0 +1,211 @@ +# Local VM prototype: independent validation + +Review date: 2026-11-14. This report covers a shared, uncommitted working tree. +Only the three new adversarial test files and this report belong to this review. +Implementation files, existing tests, and pre-existing dirty changes were not edited. + +## Observed results + +Parent follow-up: both findings below are fixed in the shared working tree. +The coordinator now compares every terminal result's input digest with the exact +request, including cleanup and recovered results. Lookup rejects `.` and `..` +before transport. Synthetic executor fixtures now return genuine request digests. +`go test -race ./internal/controller ./internal/executor ./internal/simulator +./internal/milo ./internal/staging ./internal/standalone` passed, including both +new regression tests. This follow-up is not independent approval of the VM adapter. +The original review observations below describe the pre-fix implementation. + +Commands executed locally: + +```sh +go test ./internal/controller ./internal/executor ./internal/simulator ./internal/standalone +go test -race ./internal/controller ./internal/executor ./internal/simulator ./internal/standalone +git diff --check +``` + +Both Go commands failed on the two new regression tests described below. Simulator +and standalone packages passed; standalone results were cached. No race warning +was reported. Whitespace validation passed. No VM, Docker, kind, deployment, +external review, or hosted CI resources were started by this reviewer. + +### High: wrong-asset cleanup evidence releases custody + +At review time, `validateTerminalResult` in +[lifecycle.go](../../internal/controller/lifecycle.go) (line 1531) checks operation +ID, kind, phase, completion presence, and result text, but does not compare +`InputDigest` with the exact retained request. Both direct completion and lookup +recovery use this validator. + +[The regression test](../../internal/controller/evidence_adversarial_test.go) +returns a successful cleanup with the requested operation ID and a valid digest +computed for a different physical asset. Both direct and recovered responses +produce `State:Released`, `SafeToRemoveFinalizer:true`, and no error. The waiting +consumer then allocates the asset successfully. These are observed unit-test +results, not a hypothetical gap inferred only from code. + +Required fix: compare verified result evidence against the exact request before +any custody transition, including cleanup and recovery. Missing or mismatched +digests must remain unknown. Update synthetic executor fixtures to supply genuine +request digests rather than allowing absent evidence for compatibility. The +standalone runner's additional install-history digest check does not protect +the coordinator's cleanup path. + +### Medium: dot-segment lookup leaves the operation path + +[client.go](../../internal/executor/client.go) (lines 140–144) rejects slash-bearing +IDs but passes `.` and `..` through `path.Join`. The new +[lookup test](../../internal/executor/path_adversarial_test.go) observes requests +to `/v1/operations` and `/v1`, respectively. A 404 produces no error. This is an +HTTP path-confusion finding; it does not establish shell execution or filesystem +access. + +Required fix: reject dot segments before transport, or construct a URL whose +single opaque path segment cannot be normalized out of the operation endpoint. +Retain the negative tests for both values. + +### Passing adversarial coverage + +[The simulator test](../../internal/simulator/binding_adversarial_test.go) retains +an installation, reopens its store, and individually substitutes asset, binding, +epoch, fence, and image under the same operation ID. Every attempt returns +`ErrConflict` without changing the snapshot. This establishes simulator request +binding, not real executor fencing or artifact verification. + +## Existing coverage evaluated + +- [Lifecycle tests](../../internal/controller/lifecycle_test.go): exclusive + allocation, competing candidate selection, custody tombstones, release and + epoch reuse, missing authority, private predecessor checks, unknown-operation + recovery, malformed completion, retained routing identity, and network cleanup + ordering. Tests predominantly use an in-memory executor and fake Kubernetes + client; they do not demonstrate remote-worker fencing or API-server behavior. +- [Simulator tests](../../internal/simulator/store_test.go): serialized duplicate + submissions, request conflicts, fencing, cleanup retirement, lost responses, + persistence failure boundaries, corrupt-state rejection, and digest retention. + These test synthetic effects; no OS is installed. +- [Standalone reinstall tests](../../internal/standalone/reinstall_test.go): exact + operation recovery across simulator reopen, stale predecessors, concurrent + reinstall convergence, unknown result retaining custody, and rejection of + missing/substituted terminal history. These tests were already dirty/untracked + when this review began and were not authored or modified here. +- [Executor tests](../../internal/executor/client_test.go): authentication, token + rotation, lost-response lookup, malformed evidence, operation-specific result + text, and bounded HTTP timeout. They do not qualify libvirt commands or XML. + +## Real adapter inspection boundary + +During ordinary review, [the image build](../../hack/local-vm/Containerfile), +[installer](../../hack/local-vm/init), and [disk boot script](../../hack/local-vm/boot) +appeared. The installer partitions `/dev/vda`, writes a filesystem and receipt, +installs GRUB, and emits `FLEET-INSTALLED`. The boot script checks an ext4 root on +`/dev/vda1` and emits `FLEET-DISK-BOOT` with the receipt. This is source inspection +only. Separate markers are useful, but there is no observed VM execution here. + +The build generates SHA256SUMS, but its Debian base tag and apt package versions +are mutable. Generated checksums alone do not establish trusted artifact +provenance or prove that the executor enforces an admitted checksum. A reproducible +build and verification of the exact locally built bytes are distinct claims. + +No Go real-VM adapter was present in the inspected source inventory. Final adapter +validation remains pending. The parent should request a fresh review after the +adapter and its execution commands are available; this report is not approval of +implementation added after the inspection boundary. + +## Concrete acceptance assertions still required + +These are proposed checks, not successful results. Run destructive cases only +against uniquely scoped disposable domains and disks with a decoy resource to +detect unintended effects. + +1. **Exclusive allocation:** race two consumers for one capacity through the + shared coordinator. Exactly one immutable binding wins, including under stale + `Available=True`. Restart during selection/commit; never admit effects for the + loser or briefly expose occupied capacity. Keep Device, capacity, allocation, + Installation, operation, and libvirt domain identities distinct. +2. **Exact authority:** before the first external command, retain operation ID, + Installation incarnation, predecessor, asset, binding, epoch/fence, domain + UUID, canonical disk identity, artifacts, and configuration digests. Change each + field individually on replay and require rejection without commands. A result + for another target or old epoch must not complete installation or cleanup. +3. **Actual installation and disk boot:** record that the target disk is newly + blank and uniquely owned. Observe partition/filesystem and bootloader creation. + Require a separate subsequent boot with installer kernel/initrd/media removed + from the domain definition. Capture root-device evidence and an exact + installation-specific receipt tied to retained inputs from that boot. Installer + output, a generic login prompt, or a preinstalled image alone cannot pass. + Negative cases: stop after installer boot, omit disk boot, supply old serial + output, or return a predecessor receipt; readiness must remain unverified. +4. **Restart/retry:** interrupt before command, after effect but before journal + update, after completion but before response, and during evidence collection. + Reopen the executor and retry the same operation. Assert one domain/disk set, + stable IDs, no repeated format/install, and bounded recovery. Race two executor + processes, not just goroutines. Ambiguous crash windows retain custody instead + of blindly recreating or reinstalling resources. +5. **Reinstall predecessor:** require a new Installation naming the durable current + predecessor. Race two successors; only one may produce effects. Preserve the + allocation and epoch, change installation evidence, reject late predecessor + callbacks, and ensure stale serial receipts cannot complete the successor. +6. **Unknown outcomes:** inject timeout, command disconnect, missing/corrupt journal, + unavailable lookup, absent completion, and mismatched receipt/digest. Do not + mark ready, advance predecessor, remove finalizers, or admit another consumer. + Cleanup must not race an unresolved installer or surviving worker. +7. **Exact cleanup and reuse:** verify shutdown and absence of the exact retained + domain UUID, installer access, and owned disk artifacts before returning clean. + Preserve decoy domains/files even when names share prefixes. Replace a domain + under the same name or replace a disk path; reject changed identity. Inject + partial cleanup and failure to inspect resources; retain custody. A subsequent + allocation requires a later fence epoch and blank storage; stale cleanup and + install retries must not touch that allocation. +8. **Path/XML/command injection:** exercise traversal, absolute paths, symlinks, + path replacement races, dot segments, quotes, XML markup, newlines, shell + metacharacters, and option-prefixed values in every external-input field. + Capture argv and parse generated XML; assert literal values, bounded paths, + and no unexpected device, host filesystem, network, or command access. Unknown + asset IDs must not create arbitrary domains. Reject requests before effects. +9. **Artifact integrity:** change kernel, installer, disk payload, checksum file, + or symlink after admission. Require verification against an independently + retained expected digest before use, with a defined defense against replacement + between verification and execution. Unsupported/unpinned artifacts, truncated + content, or a valid checksum for another build must fail closed. Pin/check the + relationship between the admitted image and the actual installer payload. + +Real hardware and firmware, production Milo/IAM/quota/network integration, and +hosted CI qualification remain separate acceptance tracks. The synthetic +[standalone smoke](standalone-smoke.md) cannot qualify OS installation. + +## Follow-up: adapter durability and regression coverage + +A subsequent independent adapter review identified a missing directory sync +between disk creation and the `prepared` journal transition, plus insufficient +adapter-specific tests. The parent implementation now syncs the created disk and +its operation directory before advancing the journal. Verified serial evidence +files and their directory are also synced before recording the corresponding +verified stage. Journal writes retain their existing root-directory sync. + +Private provider fields allow tests to substitute a temporary state root, command +execution, and directory-sync failure without changing the production constructor +or exposing new configuration. The new +[adapter lifecycle tests](../../internal/localvm/lifecycle_test.go) exercise exact +request substitution, reopened journal replay without duplicate commands, +authority advancement only after cleanup, live-domain cleanup rejection, decoy +preservation, stale cleanup replay after reuse, directory-sync failure propagation, +exclusive disk creation after uncertain preparation, and absent/stale/wrong-stage +receipt recovery without repeating the installer. These are filesystem and fake +command tests, not completed guest installation evidence or power-loss tests. + +## PXE HTTP evidence correction + +Independent review of the PXE implementation corroborated firmware network boot, +DHCP, real installation, and disk-only boot in the saved acceptance run. It also +reproduced a logging defect: a zero-byte failed HTTP write still recorded the +intended response length as admitted delivery. The parent corrected this by +retaining `admitted` as an attempt and adding `write-complete` only when the +response writer reports the entire body written without error. Both adapter and +harness verification now require completed entries. Regression tests cover failed +writes, short writes without errors, and successful writes. + +A completed server write does not prove client receipt. The separate installer +and disk-boot receipts remain mandatory. The earlier saved PXE acceptance run +uses the old attempt-only logs; it is not evidence that this corrected logging +path has passed a fresh VM run. Subsequent end-to-end acceptance must capture the +new entries. Neither logging scheme alone proves successful OS provisioning. diff --git a/docs/operations/local-vm.md b/docs/operations/local-vm.md new file mode 100644 index 00000000..45d7e3b5 --- /dev/null +++ b/docs/operations/local-vm.md @@ -0,0 +1,309 @@ +# Local Fleet PXE installation with KVM or explicit TCG + +This opt-in development harness uses the existing [lifecycle library](../development/README.md) +and a real disposable Kubernetes API. It does not deploy Fleet or contact a +production cluster. The production manager remains unwired to this provider. + +Run `hack/local-vm/run.sh` from a workstation with Go, Docker, kind, kubectl and +Python 3. The default KVM mode requires Linux amd64 Docker and working `/dev/kvm`. First build the +`fleet-vm-local` runtime described in infra PR 9332; the runner image supplies +libvirt, QEMU and `fleet-start-libvirt`. The harness builds its own guest installer +and Go executable. It never invokes the infrastructure smoke script. + +For a local runtime without reliable x86 KVM, explicitly select software execution: + +```sh +DOCKER_CONTEXT=colima-fleet-acceptance-tcg FLEET_LOCAL_VM_ACCEL=tcg bash hack/local-vm/run.sh +``` + +`task local-vm:acceptance` runs the same TCG command. + +The named Docker context must already identify your dedicated disposable runtime. +TCG builds a native amd64 or arm64 Debian libvirt/QEMU runner and boots the same +amd64 installer and blank disk, with no simulator or preinstalled guest image. +The installer build requires amd64 container execution (for example Rosetta on +an arm64 Colima runtime). TCG acceptance qualifies the real installation/control-plane +path, **not KVM acceleration**. There is no automatic fallback: invalid modes fail, +the runner checks `/dev/kvm` in KVM mode, and the provider rejects changing the +accelerator for a retained journal. Legacy journals without a mode mean KVM. +Evidence records the explicit accelerator, runtime architecture, and transferred +executable checksum. The executable is checksum-verified before being renamed +into its runnable path, preventing a truncated transfer from being executed. + +The wrapper creates a fresh kind cluster and privileged libvirt container on the +disposable Docker kind network. It mounts no host directories or libvirt sockets. +Installer guests have one e1000 NIC on an isolated libvirt bridge inside the +container. Disk-verification guests have **no NIC**. Libvirt/dnsmasq is the sole +local DHCP/network authority; there is no forwarding, host LAN DHCP, external +bridge, or published HTTP port. NSO, Milo, IAM and quota boundaries remain synthetic. Privilege is restricted operationally to this disposable +Docker environment; this is not a sandbox for untrusted users or guest images. +Failures retain the named container, cluster, private kubeconfigs and executor +journal for recovery. Inspect the printed resource name before removing only +those resources with `docker rm -f NAME` and `kind delete cluster --name NAME`. +Do not share the raw failure directory: it contains local kubeconfig credentials +and private fencing tokens. Successful runs remove credentials and redact tokens. + +## Implemented contract + +The operator-owned capacity fixture references a distinct Device slot; this is +local virtual inventory, not physical discovery or a new Device API implementation. +The harness sets its actual configured CPU/memory bounds and uses the existing +Coordinator to reserve the slot exclusively for a consumer Machine. A second +consumer must receive InsufficientCapacity. IAM, image admission and quota are +explicit local test authorities; NSO, Milo and production network policy are not +claimed. Importing a record does not invoke the adapter. + +The adapter implements `executor.Client`. It accepts one fixed asset, one +artifact-manifest-derived image reference, install and cleanup operations. All +resource names derive from hashes of retained operation IDs. Callers cannot +supply XML, commands, paths, URLs, boot arguments, or cleanup targets. One flock +serializes processes. Every exact request, request digest, authority and random +boot receipt is fsynced before effects. The journal survives process restart. +Changed retries conflict; unfinished operations block later operations. Cleanup +closes the allocation epoch; stale authority cannot reopen it. + +A pinned Debian base supplies a Linux kernel, BusyBox and GRUB. Package resolution +currently uses Debian repositories at image-build time, so rebuilding is **not +bit-reproducible**. The build emits SHA256SUMS; the executor verifies both artifacts +and derives the admitted image digest from that exact manifest. Changing either +artifact invalidates the admitted image. Retain the built image ID and artifact +manifest when reproducing an acceptance run. + +The guest firmware obtains DHCP configuration and an HTTP iPXE script, then +fetches the kernel and initrd from the guarded broker. Installer domain XML has +only network boot: no libvirt kernel/initrd or disk-boot shortcut. The guest +installer starts with an empty 2 GiB disk, partitions and formats it, +copies its Linux filesystem, installs GRUB, and writes the operation's random +receipt onto disk. A separate libvirt domain boot uses only that disk: no external +kernel, initrd or installer medium. Its one-shot init script checks that `/` is +`/dev/vda1` ext4, emits the retained receipt on serial, and powers off. Fleet +requires the exact serial line and domain disappearance. Installer exit alone, +QEMU running, an old receipt, or missing evidence never yields installed success. +There is no ongoing guest agent. The minimal guest deliberately powers off after +verification; this does not qualify a production distribution or workload. + +Reinstall creates a new blank disk and a new receipt under the same allocation. +Prior incarnation disks remain private until cleanup; they are never booted or +exposed to another consumer. Cleanup deletes only retained disks for that exact +binding after verifying no matching domain exists, and verifies absence before +returning the full request-bound clean result. This is disposable-file deletion, +not a claim of physical media sanitization. + +The harness crashes the process after verified provider completion, before the +controller receives its result, then starts a new process to recover the same +Installation. It repeats install and reinstall to verify retries, then releases +and allocates the slot to the waiting consumer. Pending effects without sufficient +evidence remain unknown and require inspection; the adapter does not blindly +restart an installer after an ambiguous libvirt start. + +## Local PXE admission and trust boundary + +The executable now selects `pxe` durably in the journal. Journals from the earlier +direct-kernel prototype cannot silently replay under PXE; there is no automatic +migration or runtime direct-boot option. The accelerator remains separately bound. +Tests retain private direct-mode fixtures for the existing lifecycle regressions. + +A random 256-bit bearer capability is retained with the exact admitted operation, +request digest, asset, allocation, epoch, fence and ten-minute expiry before effects. +The HTTP broker reads the atomic journal on every request and permits only the +current `installer-started` operation with an open, unexpired admission. It serves +only its derived iPXE script and the two manifest-bound artifacts. Artifact bytes +and the manifest are rechecked before delivery. Unknown identity, wrong capability, +stale allocation/fence, closed/revoked/expired admission, unsupported paths and +unguarded artifacts are denied. No general file server is exposed. + +The DHCP boot URL contains a short operation locator and scoped capability; the +locator is deliberately short enough for the legacy BOOTP filename field. MAC/IP +are routing information, not authentication. Delivery over HTTP and DHCP trusts the +single-guest isolated lab and container operator. A tenant or hostile peer on this +network could steal the capability: this is **not production attestation**, TLS +bootstrap, or qualified multi-tenant PXE. The listener is reachable in the disposable +container network but no host port is published. The capability cannot select an +image, asset, operation, URL or arbitrary file beyond its retained admission. + +Expiry/revocation prevents new HTTP retrieval, not execution of a downloaded +installer. The provider first observes domain disappearance and the exact installer +receipt, then closes admission durably. It removes the isolated network before the +separate NIC-free disk boot. Missing observations remain Unknown with capacity held; +no timeout triggers a second installer start. Cleanup still requires every retained +domain absent before deleting disks. Network teardown is local test plumbing, not +NSO/IPAM or production fencing evidence. + +Raw runtime state and failed-run directories are private: the journal and network +XML contain capabilities, and kubeconfigs contain Kubernetes credentials. Successful +exports remove these credentials, scan for retained boot capabilities, and retain +only artifact names, byte counts, DHCP leases and exact non-secret receipts. + +## Evidence and limitations + +Successful output includes DHCP leases, guarded HTTP delivery receipts, live +closed-admission HTTP denial probes, sanitized provider journal, both serial logs and +rendered domain definitions per installation, public Installation status, phase +log, image ID and the final domain inventory. The journal binds receipts to exact +requests including allocation, epoch, fence and image. Readiness assurance is +local trusted-executor evidence, not hardware attestation. The local operator and +container root remain trusted. No remote API or production authorization is added. + +See the separately maintained [adversarial validation report](local-vm-adversarial-validation.md). +Actual execution results must be reported separately; a successful Go build or +synthetic simulator test is not evidence of an OS installation. + +## Execution record (2026-11-14) + +`go test -race ./internal/localvm ./cmd/fleet-local-vm`, shell syntax checks, +`hack/validate-doc-links.sh`, and `git diff --check` passed. The Linux executable +and installer image built. Two disposable runs reached real Kubernetes-backed +exclusive allocation and contention rejection. The first real KVM guest booted, +partitioned and formatted its blank disk, then failed during filesystem copying +because BusyBox selected its built-in tar. The installer now calls GNU tar by +absolute path, checks pipeline failures, enables ACPI, and disables automatic +libvirt restart on guest reboot/crash. + +The corrected second run was interrupted by the dedicated Colima VM rebooting +and Docker being gracefully stopped. Subsequent serial-console inspection found +that this reboot followed a nested-KVM host kernel panic, not merely an external +Docker stop. Its journal retained `installer-started` +with an `Unknown` result. The runtime contained only the four containers from +these two runs. One authorized Docker restart restored the internal daemon; +the workstation socket remained unavailable. Restarting the provider daemon +showed no libvirt domains. An attempt to recover the existing installation +exited 139. Subsequent inspection traced exit 139 to an executable truncated at +4,194,304 bytes, compared with the original 37,455,636-byte binary. Restoring that +exact original binary to a separate recovery path, verifying its SHA256, and +retrying the same Installation correctly returned Unknown. No operation was reset +and no disk was reformatted during recovery. +Both runs' resources and private state were retained for inspection. + +**The interrupted KVM attempts did not complete real OS disk boot, post-effect +crash recovery, reinstall, or cleanup/reuse.** The subsequent successful explicit +TCG acceptance is recorded below; it does not qualify this KVM environment. +The original local evidence directory is +`/tmp/fleet-local-evidence.ixHu29`; `summary.json`, `runtime-status.txt`, +`journal-sanitized.json`, `device.json`, and `SHA256SUMS` are safe diagnostic +artifacts. Its kubeconfig files and the raw container journals are private and +must not be published. The retained resource names are +`fleet-local-9c2ad625d67a` and `fleet-local-adcaca5a98e8`, each with a corresponding +`-control-plane` kind container. Inspect those exact resources before cleanup. + +### Follow-up runtime diagnosis + +The dedicated `fleet-e2e-x86` runtime is itself an x86 VM emulated by QEMU TCG on +an Apple Silicon host. A fresh diagnostic run, `fleet-local-9d76bd454637`, reproduced +the host Linux panic at 20:50 CST on November 14, 2026: +`Kernel panic - not syncing: corrupted stack end detected inside scheduler`, +with `Comm: CPU 0/KVM`. The earlier 20:35 CST reboot has the same signature. +The fresh operation also remains `installer-started`/Unknown; its container, +disk, kind cluster and private credentials are retained. No further KVM guest +boots should be attempted in this runtime until the nested virtualization issue +is resolved. The daemon was started only to collect retained diagnostics, without +restarting any provider container or replaying an installer. + +Sanitized panic excerpts and sanitized journals are under +`/tmp/fleet-acceptance-recovery` (`nested-kvm-panic.txt`, +`prior-nested-kvm-panic.txt`, `journal-sanitized.json`, +`first-journal-sanitized.json`, and `diagnostic-journal-sanitized.json`). This +directory also contains private recovery files: share only the named sanitized +files, not the directory. A separate task-owned native arm64 Colima VZ runtime, +`fleet-acceptance-tcg`, was created with no host mounts and without switching the +active Docker context, for explicit TCG acceptance using the updated provider. + +### Successful explicit TCG acceptance (2026-11-14) + +The following command exited zero on November 14, 2026 at approximately 21:03 CST +(November 15, 03:03 UTC), using the parent-updated provider with durable directory +sync, accelerator binding, and lifecycle regression tests: + +```sh +DOCKER_CONTEXT=colima-fleet-acceptance-tcg FLEET_LOCAL_VM_ACCEL=tcg bash hack/local-vm/run.sh +``` + +The runtime has no `/dev/kvm`. Its native arm64 QEMU executed the real amd64 Linux +guest from the built installer, not a simulator or a preinstalled cloud disk. +The run verified Kubernetes-backed exclusive allocation and contention rejection; +partitioning, ext4 formatting, payload copying and GRUB installation onto a blank +2 GiB disk; a separate disk-only boot with the exact installation receipt; exit 75 +after the provider's durable success and recovery by a new process; exact retries; +a second real installation with a distinct receipt and blank disk; and verified +cleanup followed by exclusive allocation to the waiting consumer. + +The fresh resource `fleet-local-00cf3dc540bb` and its kind cluster were removed +after successful cleanup/reuse. Its credentials were removed from the evidence +directory. The new task-owned Colima runtime remains available, with no containers; +none of the three unknown KVM operations was reset, cleaned, or declared ready. + +Sanitized acceptance evidence is in `/tmp/fleet-local-evidence.gz8QaY`: + +- `summary.json`, `phases.log`, `accelerator`, and `runtime-architecture` record + the result and execution mode. +- `provider/journal.json` contains two succeeded installation operations and one + succeeded cleanup operation, with fences redacted and the allocation closed. +- The operation directories contain both installer and disk serial logs and XML; + the two disk-only boot receipts match their retained operations and differ from + each other. Neither disk domain XML contains a kernel, initrd, or network NIC. +- `provider/installations.json` records both public Installation statuses as Ready. +- `domains-after.txt` is empty, and no `disk.raw` remains in the copied provider state. +- `SHA256SUMS`, `binary-SHA256SUMS`, `source-SHA256SUMS`, and `image-id` identify + the exact tested artifacts. The runner image ID is + `sha256:5047968ca9404706a83199f3808eaf23f94ca7d2fb165dda1f1cd3dfa97ea24b`. + +An independent readback checked these journal, receipt, XML, retry, cleanup and +credential-removal assertions after the harness passed. +`go test -race ./internal/localvm ./cmd/fleet-local-vm`, shell syntax checks, ShellCheck on +`run.sh` and `start-libvirt`, documentation links, and `git diff --check` also passed. +The installer has an informational ShellCheck SC2013 diagnostic for intentionally +splitting `/proc/cmdline` into words. Docker reports an intentional fixed-platform +build warning because the installer must remain amd64 on an arm64 runner. + +**This is real OS-install/control-plane acceptance under explicit TCG, not KVM +qualification, production hardware attestation, or a production distribution +qualification.** KVM remains the default and must be qualified separately on a +reliable x86 virtualization host. + +### Successful firmware PXE acceptance (2026-11-14 CST / 2026-11-15 UTC) + +The same explicit TCG command above exited zero with the PXE implementation. +Sanitized evidence is `/tmp/fleet-local-evidence.A5KTID`; its `summary.json` was +produced by a separate readback of the exported artifacts. The runner image ID is +`sha256:2b2c1109b2e11068c03ef25239adec425108898a4299e06a50bce2414ed6e6c3`. +The native arm64 runtime executed amd64 SeaBIOS/e1000 iPXE firmware and Linux with +TCG. This is legacy BIOS PXE, not UEFI or KVM qualification. + +Both fresh blank-disk installations have DHCP leases and guarded requests for +`boot.ipxe`, the 8,234,944-byte kernel and 215,654,737-byte initrd. Readback verified +network-only installer XML with no direct kernel/initrd, real partition/format/ +payload-copy/GRUB logs, distinct exact receipts from separate NIC-free disk boots, +closed admissions, two succeeded installs, succeeded cleanup, no remaining disks +or domains, and allocation to the waiting consumer. The harness also exercised +exclusive contention, exit 75 after durable provider completion, new-process +recovery, repeated exact requests, and reinstall. Twelve live HTTP denials after +reinstall/cleanup cover closed predecessor scripts/artifacts, unknown identity, +unguarded paths and unsupported artifacts; the earlier post-install denial probe +also passed. Expired/revoked admission and cross-operation capabilities were tested +through HTTP against durable synthetic journals in `boot_test.go`, not by expiring +a real destructive guest mid-install. + +`go test -race ./internal/localvm ./cmd/fleet-local-vm`, shell syntax, ShellCheck on +`run.sh` and `start-libvirt`, documentation links, and whitespace validation passed. +The successful harness checks exported credentials, XML boot paths, DHCP evidence, +artifact receipts and disk deletion. Its resource `fleet-local-7ad959c9bb50` and +corresponding kind cluster were removed. No production changes or KVM starts were +made. Base image and artifact checksums are retained; apt package resolution still +is not reproducible. + +Two diagnostic attempts remain in the task-owned TCG runtime, each with its +corresponding `-control-plane` kind container and private credentials/state: + +- `fleet-local-d4e060978d40`: the first DHCP URL exceeded the legacy BOOTP filename + capacity. DHCP succeeded but no HTTP request followed. The guest was explicitly + destroyed and absence observed; the operation remains `installer-started`/Unknown. + Private failure directory: `/tmp/fleet-local-evidence.Hs5F4y`. +- `fleet-local-482c67269d19`: after shortening the locator, real PXE install, + disk-only boot, post-effect recovery and exact retries passed. The harness then + stopped because a newly added probe was unsupported by its already-built binary. + Its single installation is Succeeded, no guest domain remains, and its allocated + disk is retained. Private failure directory: `/tmp/fleet-local-evidence.3W7DIL`. + +Only sanitized diagnostic journals and empty domain inventories are exported in +`/tmp/fleet-pxe-diagnostics`. The earlier three unknown KVM resource sets remain +untouched. Neither those nor the failed PXE operation was inferred clean or ready. +The final complete acceptance used a freshly built executable and a fresh resource. diff --git a/hack/local-vm/Containerfile b/hack/local-vm/Containerfile new file mode 100644 index 00000000..f86ddeda --- /dev/null +++ b/hack/local-vm/Containerfile @@ -0,0 +1,18 @@ +FROM --platform=linux/amd64 debian:bookworm-slim@sha256:734a72b3d6142a71993b4bc580ca01d8ca687f77a2c422d96a961d3376b179bc AS guest +RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends linux-image-amd64 initramfs-tools busybox-static grub-pc-bin grub2-common fdisk e2fsprogs cpio && rm -rf /var/lib/apt/lists/* +COPY init /init +COPY boot /fleet-boot +RUN chmod 755 /init /fleet-boot && mkdir -p /out && cp /boot/vmlinuz-* /out/kernel && find . \( -path ./out -o -path ./proc -o -path ./sys -o -path ./dev \) -prune -o -print | cpio -o -H newc | gzip -1 > /out/installer.gz && cd /out && sha256sum kernel installer.gz > SHA256SUMS +FROM debian:bookworm-slim@sha256:734a72b3d6142a71993b4bc580ca01d8ca687f77a2c422d96a961d3376b179bc AS tcg +RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends qemu-system-x86 qemu-utils libvirt-daemon-system libvirt-clients tini dnsmasq-base ipxe-qemu iptables && rm -rf /var/lib/apt/lists/* && printf '%s\n' 'user = "root"' 'group = "root"' 'security_driver = "none"' 'dynamic_ownership = 0' 'cgroup_controllers = []' >> /etc/libvirt/qemu.conf && rm -f /etc/libvirt/qemu/networks/autostart/default.xml +COPY start-libvirt /usr/local/bin/fleet-start-libvirt +RUN chmod 755 /usr/local/bin/fleet-start-libvirt +COPY --from=guest /out /opt/fleet-local/artifacts +ENV FLEET_LOCAL_VM=disposable-container LIBVIRT_DEFAULT_URI=qemu:///system + +FROM fleet-vm-local AS kvm +USER root +COPY start-libvirt /usr/local/bin/fleet-start-libvirt +RUN chmod 755 /usr/local/bin/fleet-start-libvirt +COPY --from=guest /out /opt/fleet-local/artifacts +ENV FLEET_LOCAL_VM=disposable-container diff --git a/hack/local-vm/boot b/hack/local-vm/boot new file mode 100644 index 00000000..b40c21ec --- /dev/null +++ b/hack/local-vm/boot @@ -0,0 +1,10 @@ +#!/bin/busybox sh +export PATH=/usr/sbin:/usr/bin:/sbin:/bin +mount -t proc proc /proc 2>/dev/null || true +exec >/dev/ttyS0 2>&1 +# Only the disk-root boot emits completion; installer completion is insufficient. +if grep -Eq '^/dev/vda1 / ext4 ' /proc/mounts && test -s /fleet-receipt; then + printf 'FLEET-DISK-BOOT:%s\n' "$(cat /fleet-receipt)" +fi +sync +/bin/busybox poweroff -f diff --git a/hack/local-vm/init b/hack/local-vm/init new file mode 100644 index 00000000..fce1814a --- /dev/null +++ b/hack/local-vm/init @@ -0,0 +1,37 @@ +#!/bin/busybox sh +export PATH=/usr/sbin:/usr/bin:/sbin:/bin +mkdir -p /dev /proc /sys +mount -t devtmpfs devtmpfs /dev +mount -t proc proc /proc +mount -t sysfs sys /sys +exec >/dev/ttyS0 2>&1 +set -exo pipefail +modprobe virtio_pci +modprobe virtio_blk +modprobe ext4 +for arg in $(cat /proc/cmdline); do case "$arg" in fleet.receipt=*) receipt=${arg#fleet.receipt=};; esac; done +[ ${#receipt} = 64 ] || /bin/busybox poweroff -f +printf 'label: dos\n, , L, *\n' | sfdisk /dev/vda +mkfs.ext4 -F /dev/vda1 +mkdir -p /target +mount /dev/vda1 /target +# The payload is this pinned installer filesystem; exclude virtual mounts. +/bin/tar -cf - --exclude=./target --exclude=./proc --exclude=./sys --exclude=./dev --exclude=./out . | /bin/tar -xf - -C /target +mkdir -p /target/dev /target/proc /target/sys +mount --bind /dev /target/dev +mount --bind /proc /target/proc +mount --bind /sys /target/sys +printf '%s\n' "$receipt" > /target/fleet-receipt +chroot /target grub-install --target=i386-pc /dev/vda +kernel=$(basename /boot/vmlinuz-*) +initrd=$(basename /boot/initrd.img-*) +cat > /target/boot/grub/grub.cfg <&2; exit 1; } +export KIND_EXPERIMENTAL_PROVIDER=docker +accelerator=${FLEET_LOCAL_VM_ACCEL:-kvm} +case "$accelerator" in + kvm|tcg) ;; + *) echo 'FLEET_LOCAL_VM_ACCEL must be kvm or tcg' >&2; exit 1;; +esac +case $(docker context inspect --format '{{.Endpoints.docker.Host}}') in + unix://*) ;; + *) echo 'Local Unix Docker endpoint required; remote runtimes are not authorized' >&2; exit 1;; +esac +case $(docker info --format '{{.Architecture}}') in + x86_64|amd64) runtime_arch=amd64 ;; + aarch64|arm64) runtime_arch=arm64 ;; + *) echo 'Unsupported Docker runtime architecture' >&2; exit 1;; +esac +[[ $accelerator == tcg || $runtime_arch == amd64 ]] || { echo 'KVM requires an amd64 runtime for this guest' >&2; exit 1; } +run_id="fleet-local-$(python3 -c 'import uuid; print(uuid.uuid4().hex[:12])')" +evidence=$(mktemp -d /tmp/fleet-local-evidence.XXXXXX) +export KUBECONFIG="$evidence/kubeconfig" +printf '%s\n' "$run_id" > "$evidence/resource-name" +printf '%s\n' "$accelerator" > "$evidence/accelerator" +printf '%s\n' "$runtime_arch" > "$evidence/runtime-architecture" +printf 'Evidence: %s\n' "$evidence" +trap 'echo "Resources retained for inspection: $run_id; evidence: $evidence"' EXIT +python3 - "$evidence/source-SHA256SUMS" <<'PYHASH' +import hashlib,pathlib,sys +paths=[*pathlib.Path('internal/localvm').glob('*.go'),*pathlib.Path('cmd/fleet-local-vm').glob('*.go'),*pathlib.Path('hack/local-vm').glob('*')] +with open(sys.argv[1],'w') as out: + for p in sorted(paths): + if p.is_file(): out.write(hashlib.sha256(p.read_bytes()).hexdigest()+' '+str(p)+'\n') +PYHASH +CGO_ENABLED=0 GOOS=linux GOARCH="$runtime_arch" go build -o "$evidence/fleet-local-vm" ./cmd/fleet-local-vm +docker build --target "$accelerator" -t fleet-local-install -f hack/local-vm/Containerfile hack/local-vm +kind create cluster --name "$run_id" --kubeconfig "$KUBECONFIG" --image kindest/node:v1.35.0@sha256:452d707d4862f52530247495d180205e029056831160e22870e37e3f6c1ac31f --wait 120s +kubectl apply -f config/base/crd/metal.datumapis.com.yaml +kubectl wait --for=condition=Established crd --all --timeout=60s +for ns in fleet-system-private fleet-provider fleet-project-a fleet-project-b; do kubectl create namespace "$ns"; done +docker run -d --name "$run_id" --network kind --privileged --user root -e "FLEET_LOCAL_VM_ACCEL=$accelerator" --entrypoint /usr/local/bin/fleet-start-libvirt fleet-local-install +# No host filesystem mounts, host network, or host libvirt socket. +docker exec "$run_id" mkdir -p /run/fleet +binary_digest=$(python3 - "$evidence/fleet-local-vm" <<'PY' +import hashlib,sys +print(hashlib.sha256(open(sys.argv[1],'rb').read()).hexdigest()) +PY +) +printf '%s fleet-local-vm\n' "$binary_digest" > "$evidence/binary-SHA256SUMS" +docker cp "$evidence/fleet-local-vm" "$run_id:/usr/local/bin/fleet-local-vm.pending" +printf '%s /usr/local/bin/fleet-local-vm.pending\n' "$binary_digest" | docker exec -i "$run_id" sha256sum -c - +docker exec "$run_id" mv /usr/local/bin/fleet-local-vm.pending /usr/local/bin/fleet-local-vm +kind get kubeconfig --name "$run_id" --internal > "$evidence/internal-kubeconfig" +docker cp "$evidence/internal-kubeconfig" "$run_id:/run/fleet/kubeconfig" +docker exec -d "$run_id" fleet-local-vm boot-service +image=$(docker exec "$run_id" fleet-local-vm image) +docker cp "$run_id:/opt/fleet-local/artifacts/SHA256SUMS" "$evidence/SHA256SUMS" +python3 - "$image" > "$evidence/fixtures.yaml" <<'PY' +import sys +s=open('config/standalone/fixtures.yaml').read() +s=s.replace('cores: 24','cores: 2').replace('capacity: 128Gi','capacity: 2Gi') +s=s.replace('debian-12@sha256:9f4ad8d8b8a6f6fc64d2cf2c7e70b9184b74f089adf8c36d84f4fcb99892f3cb',sys.argv[1]) +print(s) +PY +kubectl apply -f "$evidence/fixtures.yaml" +docker exec "$run_id" fleet-local-vm allocate | tee -a "$evidence/phases.log" +set +e +docker exec "$run_id" fleet-local-vm install-crash >> "$evidence/phases.log" 2>&1 +crash_status=$? +set -e +[[ $crash_status == 75 ]] || { echo "Expected post-effect crash 75; got $crash_status"; exit 1; } +printf "post-effect process crash verified (75)\n" >> "$evidence/phases.log" +for phase in install install boot-denials reinstall reinstall boot-denials release boot-denials evidence; do + docker exec "$run_id" fleet-local-vm "$phase" | tee -a "$evidence/phases.log" +done +docker cp "$run_id:/var/lib/fleet-local" "$evidence/provider" +docker exec "$run_id" virsh list --all --name > "$evidence/domains-after.txt" +docker image inspect fleet-local-install --format '{{.Id}}' > "$evidence/image-id" +# Retain receipts but omit fence tokens and all kubeconfigs from shareable evidence. +python3 - "$evidence/provider/journal.json" <<'PY' +import json,sys,pathlib +p=sys.argv[1];j=json.load(open(p));j.pop('fence',None) +tokens=[r.get('bootToken','') for r in j['operations'].values() if r.get('bootToken')] +for r in j['operations'].values(): + r['request'].pop('fenceToken',None) + r.pop('bootToken',None) +json.dump(j,open(p,'w'),indent=2) +root=pathlib.Path(p).parent +(root/'network-private.xml').unlink(missing_ok=True) +for file in root.rglob('*'): + if file.is_file() and any(token.encode() in file.read_bytes() for token in tokens): + raise SystemExit('credential found in exported evidence') +assert j['bootMode']=='pxe' +for r in j['operations'].values(): + if r['request']['kind']!='install': continue + import hashlib + d=root/hashlib.sha256(r['request']['id'].encode()).hexdigest() + installer=(d/'installer.xml').read_text(); disk=(d/'disk.xml').read_text() + assert '' not in installer and '' not in installer and "boot dev='network'" in installer + assert '' not in disk and '' not in disk + assert r['bootClosed'] + for name in ['boot.ipxe','kernel','installer.gz']: assert 'write-complete '+name+' bytes=' in (d/'boot-delivery.log').read_text() + assert '52:54:00:77:00:02' in (d/'dhcp-leases.txt').read_text() + assert 'FLEET-DISK-BOOT:'+r['receipt'] in (d/'disk.log').read_text() + assert not (d/'disk.raw').exists() +PY +rm -f "$evidence/provider/network-private.xml" +docker rm -f "$run_id" +kind delete cluster --name "$run_id" +rm -f "$evidence/kubeconfig" "$evidence/internal-kubeconfig" "$evidence/fleet-local-vm" +trap - EXIT +printf 'PASS: real local installation, retry, reinstall, cleanup and reuse; evidence %s\n' "$evidence" diff --git a/hack/local-vm/start-libvirt b/hack/local-vm/start-libvirt new file mode 100644 index 00000000..3875c759 --- /dev/null +++ b/hack/local-vm/start-libvirt @@ -0,0 +1,16 @@ +#!/bin/sh +set -eu +case "${FLEET_LOCAL_VM_ACCEL:-kvm}" in + kvm) + [ -c /dev/kvm ] && [ -r /dev/kvm ] && [ -w /dev/kvm ] || { + echo 'KVM device unavailable; no automatic software fallback' >&2 + exit 1 + } + ;; + tcg) ;; + *) echo 'Unsupported local VM accelerator' >&2; exit 1 ;; +esac +mkdir -p /run/libvirt /var/lib/libvirt/images /var/log/libvirt +virtlogd --daemon +virtlockd --daemon +exec /usr/bin/tini -- libvirtd diff --git a/internal/localvm/boot.go b/internal/localvm/boot.go new file mode 100644 index 00000000..4f6ab8af --- /dev/null +++ b/internal/localvm/boot.go @@ -0,0 +1,258 @@ +package localvm + +import ( + "context" + "crypto/sha256" + "crypto/subtle" + "encoding/hex" + "fmt" + "io" + "net/http" + "os" + "strconv" + "strings" + "time" +) + +// defaultBootOrigin is the provisioning-bridge address used when the boot +// service shares the hypervisor network namespace (single-container mode). +const defaultBootOrigin = "http://192.168.77.1:8080" + +func (p *Provider) origin() string { + if p.bootOrigin == "" { + return defaultBootOrigin + } + return p.bootOrigin +} + +// prepareNetwork is the sole local network writer. DHCP stays on a bridge in the +// runtime namespace. NAT forwarding lets firmware reach a boot Service outside +// that namespace; the runtime restricts forwarded traffic to that origin. +func (p *Provider) prepareNetwork(ctx context.Context, r *record) error { + names, err := p.virsh(ctx, "net-list", "--name") + if err != nil { + return err + } + for _, n := range strings.Fields(names) { + if n == "fleet-pxe" { + if _, err = p.virsh(ctx, "net-destroy", n); err != nil { + return err + } + } + } + xml := fmt.Sprintf(`fleet-pxe%s`, p.forward(), p.origin(), key(r.Request.ID)[:16], r.BootToken) + path := p.stateRoot() + "/network-private.xml" + if err = os.WriteFile(path, []byte(xml), 0600); err != nil { + return err + } + _, err = p.virsh(ctx, "net-create", path) + return err +} + +// forward is empty when the boot service is on the bridge itself. +func (p *Provider) forward() string { + if p.origin() == defaultBootOrigin { + return "" + } + return "" +} + +// BootHandler never uses a file server or caller-selected filesystem path. +// Atomic journal replacement allows reads while the executor holds its flock. +func (p *Provider) BootHandler() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, q *http.Request) { + w.Header().Set("Cache-Control", "no-store") + deny := func() { http.Error(w, "boot denied", http.StatusForbidden) } + parts := strings.Split(q.URL.Path, "/") + if q.Method != "GET" || q.URL.RawQuery != "" || len(parts) != 4 { + deny() + return + } + j, err := p.read() + if err != nil || p.checkMode(j) != nil || j.BootMode != "pxe" || j.Image != p.image || j.Closed { + deny() + return + } + var r *record + for _, candidate := range j.Operations { + if key(candidate.Request.ID)[:16] == parts[1] { + r = candidate + break + } + } + if r == nil || r.Request.Kind != "install" || r.Stage != "installer-started" || r.BootClosed || !time.Now().Before(r.BootExpires) || len(r.BootToken) != 64 || subtle.ConstantTimeCompare([]byte(parts[2]), []byte(r.BootToken)) != 1 || r.Request.BindingID != j.Binding || r.Request.Epoch != j.Epoch || r.Request.FenceToken != j.Fence || p.validate(r.Request) != nil { + deny() + return + } + name := parts[3] + var data []byte + var artifact *os.File + var size int64 + switch name { + case "boot.ipxe": + base := p.origin() + "/" + parts[1] + "/" + r.BootToken + data = []byte(fmt.Sprintf("#!ipxe\nkernel %s/kernel console=ttyS0 rdinit=/init fleet.receipt=%s\ninitrd %s/installer.gz\nboot\n", base, r.Receipt, base)) + size = int64(len(data)) + case "kernel", "installer.gz": + // Stream: hash the pinned artifact, then serve the same open file. + artifact, err = os.Open(artifacts + "/" + name) + if err != nil { + deny() + return + } + defer artifact.Close() + manifest, e := os.ReadFile(artifacts + "/SHA256SUMS") + sum := sha256.Sum256(manifest) + h := sha256.New() + size, err = io.Copy(h, artifact) + if e != nil || err != nil || p.image != "fleet-local-linux@sha256:"+hex.EncodeToString(sum[:]) || !strings.Contains(string(manifest), hex.EncodeToString(h.Sum(nil))+" "+name+"\n") { + deny() + return + } + if _, err = artifact.Seek(0, io.SeekStart); err != nil { + deny() + return + } + default: + deny() + return + } + // No URLs, headers, credentials or bootstrap script in evidence. + if err := os.MkdirAll(p.bootDirectory(r), 0700); err != nil { + deny() + return + } + f, err := os.OpenFile(p.bootDirectory(r)+"/boot-delivery.log", os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600) + if err != nil { + deny() + return + } + _, err = fmt.Fprintf(f, "%s admitted %s bytes=%d\n", time.Now().UTC().Format(time.RFC3339), name, size) + if err == nil { + err = f.Sync() + } + f.Close() + if err != nil { + deny() + return + } + w.Header().Set("Content-Type", "application/octet-stream") + w.Header().Set("Content-Length", strconv.FormatInt(size, 10)) + var n int64 + var writeErr error + if artifact != nil { + n, writeErr = io.Copy(w, artifact) + } else { + var written int + written, writeErr = w.Write(data) + n = int64(written) + } + if writeErr != nil || n != size { + return + } + // A completed server write is not proof of client receipt or guest boot. + f, err = os.OpenFile(p.bootDirectory(r)+"/boot-delivery.log", os.O_APPEND|os.O_WRONLY, 0600) + if err != nil { + return + } + _, err = fmt.Fprintf(f, "%s write-complete %s bytes=%d\n", time.Now().UTC().Format(time.RFC3339), name, n) + if err == nil { + err = f.Sync() + } + closeErr := f.Close() + if err == nil && closeErr == nil { + _ = p.syncDir(p.bootDirectory(r)) + } + }) +} + +func (p *Provider) ServeBoot() error { + // The write bound matches the boot admission window: through the site's + // NAT path an emulated firmware takes several minutes for the installer. + s := &http.Server{Addr: ":8080", Handler: p.BootHandler(), ReadHeaderTimeout: 5 * time.Second, WriteTimeout: bootWindow, IdleTimeout: 5 * time.Second} + return s.ListenAndServe() +} + +func (p *Provider) verifyNetworkBoot(ctx context.Context, r *record) error { + b, err := os.ReadFile(p.bootDirectory(r) + "/boot-delivery.log") + if err != nil { + return err + } + completed := map[string]bool{} + for _, line := range strings.Split(string(b), "\n") { + fields := strings.Fields(line) + if len(fields) != 4 || fields[1] != "write-complete" || !strings.HasPrefix(fields[3], "bytes=") { + continue + } + n, err := strconv.Atoi(strings.TrimPrefix(fields[3], "bytes=")) + if err == nil && n > 0 { + completed[fields[2]] = true + } + } + for _, name := range []string{"boot.ipxe", "kernel", "installer.gz"} { + if !completed[name] { + return fmt.Errorf("missing network delivery: %s", name) + } + } + leases, err := p.virsh(ctx, "net-dhcp-leases", "fleet-pxe") + if err != nil { + return err + } + if !strings.Contains(leases, "52:54:00:77:00:02") || !strings.Contains(leases, "192.168.77.2") { + return fmt.Errorf("missing firmware DHCP lease") + } + return os.WriteFile(p.directory(r)+"/dhcp-leases.txt", []byte(leases), 0600) +} + +func (p *Provider) stopNetwork(ctx context.Context) error { + names, err := p.virsh(ctx, "net-list", "--name") + if err != nil { + return err + } + for _, n := range strings.Fields(names) { + if n == "fleet-pxe" { + _, err = p.virsh(ctx, "net-destroy", n) + return err + } + } + return nil +} + +// CheckClosedBoot probes a live boot listener without printing capability URLs. +// origin is the listener under test, e.g. the boot Service seen by the runtime. +func (p *Provider) CheckClosedBoot(origin string) (string, error) { + origin, err := parseBootOrigin(origin) + if err != nil { + return "", err + } + j, err := p.read() + if err != nil { + return "", err + } + client := &http.Client{Timeout: 10 * time.Second} + count := 0 + for _, r := range j.Operations { + if r.Request.Kind != "install" { + continue + } + if !r.BootClosed { + return "", fmt.Errorf("boot admission not closed") + } + base := origin + "/" + key(r.Request.ID)[:16] + "/" + r.BootToken + for _, url := range []string{base + "/boot.ipxe", base + "/kernel", base + "/installer.gz", base + "/disk.raw", origin + "/kernel", origin + "/unknown/unknown/boot.ipxe"} { + resp, e := client.Get(url) + if e != nil { + return "", fmt.Errorf("boot denial probe unavailable") + } + resp.Body.Close() + if resp.StatusCode != http.StatusForbidden { + return "", fmt.Errorf("closed/unknown boot access allowed") + } + count++ + } + } + if count == 0 { + return "", fmt.Errorf("no retained admission to probe") + } + return fmt.Sprintf("PASS %d live HTTP denials: closed predecessor scripts/artifacts, unsupported artifact, unguarded artifact, unknown identity", count), nil +} diff --git a/internal/localvm/boot_test.go b/internal/localvm/boot_test.go new file mode 100644 index 00000000..7376d142 --- /dev/null +++ b/internal/localvm/boot_test.go @@ -0,0 +1,123 @@ +package localvm + +import ( + "go.datum.net/fleet/internal/simulator" + "net/http/httptest" + "os" + "strings" + "testing" + "time" +) + +func TestBootAdmission(t *testing.T) { + f := newVMFixture(t) + p := f.p + p.bootMode = "pxe" + q := vmRequest("admitted-installation") + digest, _ := simulator.RequestDigest(q) + base := record{Request: q, Result: simulator.OperationResult{ID: q.ID, Kind: q.Kind, InputDigest: digest, Phase: "Unknown"}, Receipt: strings.Repeat("a", 64), Stage: "installer-started", BootToken: strings.Repeat("b", 64), BootExpires: time.Now().Add(time.Minute)} + os.Mkdir(p.directory(&base), 0700) + for _, tc := range []struct { + name string + change func(*record, *journal) + path string + allowed bool + }{ + {name: "admitted", allowed: true}, + {name: "unknown identity", path: "/unknown/" + base.BootToken + "/boot.ipxe"}, + {name: "wrong operation credential", path: "/" + key(q.ID)[:16] + "/" + strings.Repeat("c", 64) + "/boot.ipxe"}, + {name: "expired", change: func(r *record, j *journal) { r.BootExpires = time.Now().Add(-time.Second) }}, + {name: "revoked", change: func(r *record, j *journal) { r.BootClosed = true }}, + {name: "not started", change: func(r *record, j *journal) { r.Stage = "admitted" }}, + {name: "stale epoch", change: func(r *record, j *journal) { j.Epoch++ }}, + {name: "wrong fence", change: func(r *record, j *journal) { j.Fence = "other" }}, + {name: "closed predecessor", change: func(r *record, j *journal) { r.Stage = "installer-verified"; r.BootClosed = true }}, + {name: "closed allocation", change: func(r *record, j *journal) { j.Closed = true }}, + {name: "unsupported artifact", path: "/" + key(q.ID)[:16] + "/" + base.BootToken + "/disk.raw"}, + {name: "unguarded artifact", path: "/kernel"}, + {name: "traversal", path: "/" + key(q.ID)[:16] + "/" + base.BootToken + "/../journal.json"}, + } { + t.Run(tc.name, func(t *testing.T) { + r := base + j := journal{BootMode: "pxe", Accelerator: p.mode(), Image: p.image, Epoch: q.Epoch, Binding: q.BindingID, Fence: q.FenceToken, Operations: map[string]*record{q.ID: &r}} + if tc.change != nil { + tc.change(&r, &j) + } + if err := p.save(j); err != nil { + t.Fatal(err) + } + path := tc.path + if path == "" { + path = "/" + key(q.ID)[:16] + "/" + base.BootToken + "/boot.ipxe" + } + w := httptest.NewRecorder() + p.BootHandler().ServeHTTP(w, httptest.NewRequest("GET", path, nil)) + want := 403 + if tc.allowed { + want = 200 + } + if w.Code != want { + t.Fatalf("status %d want %d", w.Code, want) + } + }) + } +} +func TestFirmwarePXEAndModeBinding(t *testing.T) { + p := &Provider{bootMode: "pxe"} + r := &record{} + x := p.domainXML(r, "installer") + if strings.Contains(x, "") || strings.Contains(x, "") || strings.Contains(x, "boot dev='hd'") || !strings.Contains(x, "boot dev='network'") || !strings.Contains(x, "") { + t.Fatal(x) + } +} + +func TestCrossOperationCapabilityOverHTTP(t *testing.T) { + f := newVMFixture(t) + p := f.p + p.bootMode = "pxe" + j := journal{BootMode: "pxe", Accelerator: p.mode(), Image: p.image, Epoch: 1, Binding: "allocation", Fence: "fence", Operations: map[string]*record{}} + for i, id := range []string{"predecessor", "successor"} { + q := vmRequest(id) + d, _ := simulator.RequestDigest(q) + r := &record{Request: q, Result: simulator.OperationResult{ID: q.ID, Kind: q.Kind, InputDigest: d, Phase: "Unknown"}, Receipt: strings.Repeat("a", 64), Stage: "installer-started", BootToken: strings.Repeat(string(rune('b'+i)), 64), BootExpires: time.Now().Add(time.Minute)} + j.Operations[id] = r + if err := os.Mkdir(p.directory(r), 0700); err != nil { + t.Fatal(err) + } + } + server := httptest.NewServer(p.BootHandler()) + defer server.Close() + check := func(op, token string, want int) { + t.Helper() + resp, err := server.Client().Get(server.URL + "/" + key(op)[:16] + "/" + token + "/boot.ipxe") + if err != nil { + t.Fatal("HTTP request failed") + } + resp.Body.Close() + if resp.StatusCode != want { + t.Fatalf("status %d want %d", resp.StatusCode, want) + } + } + save := func() { + t.Helper() + if err := p.save(j); err != nil { + t.Fatal(err) + } + } + save() + check("successor", j.Operations["predecessor"].BootToken, 403) + check("successor", j.Operations["successor"].BootToken, 200) + j.Operations["successor"].BootExpires = time.Now().Add(-time.Second) + save() + check("successor", j.Operations["successor"].BootToken, 403) + j.Operations["predecessor"].BootClosed = true + save() + check("predecessor", j.Operations["predecessor"].BootToken, 403) +} diff --git a/internal/localvm/lifecycle_test.go b/internal/localvm/lifecycle_test.go new file mode 100644 index 00000000..5f1b5767 --- /dev/null +++ b/internal/localvm/lifecycle_test.go @@ -0,0 +1,294 @@ +package localvm + +import ( + "context" + "encoding/json" + "errors" + "os" + "path/filepath" + "strings" + "testing" + + "go.datum.net/fleet/internal/executor" + "go.datum.net/fleet/internal/simulator" +) + +type vmFixture struct { + p *Provider + creates []string + failStart bool + present string +} + +func newVMFixture(t *testing.T) *vmFixture { + t.Helper() + f := &vmFixture{p: &Provider{root: t.TempDir(), image: "local@sha256:approved"}} + f.p.command = func(_ context.Context, name string, args ...string) (string, error) { + if name != "virsh" || len(args) < 3 || args[0] != "--connect" || args[1] != "qemu:///system" { + t.Fatalf("unexpected command %s %v", name, args) + } + switch args[2] { + case "list": + return f.present, nil + case "create": + f.creates = append(f.creates, args[3]) + if f.failStart { + return "", errors.New("lost start response") + } + j, err := f.p.read() + if err != nil { + return "", err + } + for _, r := range j.Operations { + stage := strings.TrimSuffix(filepath.Base(args[3]), ".xml") + if args[3] != filepath.Join(f.p.directory(r), stage+".xml") { + continue + } + if r.Stage != stage+"-started" { + t.Fatalf("command preceded durable uncertainty: %s", r.Stage) + } + marker := "FLEET-INSTALLED:" + if stage == "disk" { + marker = "FLEET-DISK-BOOT:" + } + return "", os.WriteFile(filepath.Join(f.p.directory(r), stage+".log"), []byte(marker+r.Receipt+"\n"), 0600) + } + return "", errors.New("command not bound to journal") + default: + t.Fatalf("unexpected virsh operation %v", args) + } + return "", nil + } + return f +} +func vmRequest(id string) simulator.Request { + return simulator.Request{ID: id, Kind: "install", AssetID: AssetID, BindingID: "allocation", Epoch: 1, FenceToken: "fence", Inputs: json.RawMessage(`{"image":"local@sha256:approved"}`)} +} +func TestLocalReplayAndAuthorityTransitions(t *testing.T) { + f := newVMFixture(t) + ctx := context.Background() + q := vmRequest("install") + result, err := f.p.Execute(ctx, q) + if err != nil { + t.Fatal(err) + } + if result.Result != "installed" || len(f.creates) != 2 { + t.Fatalf("unexpected install: %+v %v", result, f.creates) + } + // Reopen state through a fresh provider without changing the command fixture. + f.p = &Provider{root: f.p.root, image: f.p.image, command: f.p.command} + replay, err := f.p.Execute(ctx, q) + if err != nil || replay.InputDigest != result.InputDigest || len(f.creates) != 2 { + t.Fatalf("replay caused effects: %v", err) + } + for _, change := range []func(*simulator.Request){ + func(r *simulator.Request) { r.AssetID = "another" }, func(r *simulator.Request) { r.BindingID = "another" }, + func(r *simulator.Request) { r.Epoch++ }, func(r *simulator.Request) { r.FenceToken = "another" }, + func(r *simulator.Request) { r.Inputs = json.RawMessage(`{"image":"another"}`) }, + } { + altered := q + change(&altered) + if _, err = f.p.Execute(ctx, altered); err == nil { + t.Fatal("accepted substituted retained request") + } + } + next := vmRequest("next") + next.Epoch = 2 + next.BindingID = "next" + next.FenceToken = "next" + if _, err = f.p.Execute(ctx, next); !errors.Is(err, executor.ErrFenced) { + t.Fatalf("advanced before cleanup: %v", err) + } + cleanup := q + cleanup.ID = "cleanup" + cleanup.Kind = "cleanup" + cleanup.Inputs = nil + f.present = domain(&record{Request: q}) + if _, err = f.p.Execute(ctx, cleanup); !errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatalf("cleaned live domain: %v", err) + } + if _, err = os.Stat(f.p.directory(&record{Request: q}) + "/disk.raw"); err != nil { + t.Fatal("deleted live disk", err) + } + f.present = "decoy-domain" + decoy := filepath.Join(f.p.root, "decoy.raw") + if err = os.WriteFile(decoy, []byte("retain"), 0600); err != nil { + t.Fatal(err) + } + if _, err = f.p.Execute(ctx, cleanup); err != nil { + t.Fatal(err) + } + if _, err = os.Stat(f.p.directory(&record{Request: q}) + "/disk.raw"); !os.IsNotExist(err) { + t.Fatalf("disk survived cleanup: %v", err) + } + if b, err := os.ReadFile(decoy); err != nil || string(b) != "retain" { + t.Fatal("decoy changed") + } + stale := vmRequest("stale") + if _, err = f.p.Execute(ctx, stale); !errors.Is(err, executor.ErrFenced) { + t.Fatalf("stale authority accepted: %v", err) + } + if _, err = f.p.Execute(ctx, next); err != nil { + t.Fatal(err) + } + count := len(f.creates) + if _, err = f.p.Execute(ctx, cleanup); err != nil || len(f.creates) != count { + t.Fatal("old cleanup replay changed current allocation") + } + if _, err = os.Stat(f.p.directory(&record{Request: next}) + "/disk.raw"); err != nil { + t.Fatal("old cleanup deleted new disk", err) + } +} +func TestLocalDiskDirectorySyncPrecedesPrepared(t *testing.T) { + f := newVMFixture(t) + ctx := context.Background() + q := vmRequest("sync-failure") + injected := errors.New("directory sync failed") + f.p.syncDirectory = func(path string) error { + j, err := f.p.read() + if err != nil { + t.Fatal(err) + } + if j.Operations[q.ID].Stage != "admitted" { + t.Fatal("journal advanced before sync") + } + info, err := os.Stat(filepath.Join(path, "disk.raw")) + if err != nil || info.Size() != 2<<30 { + t.Fatal("disk not prepared before sync", err) + } + return injected + } + if _, err := f.p.Execute(ctx, q); !errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatalf("sync failure ignored: %v", err) + } + j, err := f.p.read() + if err != nil { + t.Fatal(err) + } + if j.Operations[q.ID].Stage != "admitted" || len(f.creates) != 0 { + t.Fatal("sync failure permitted boot") + } + path := f.p.directory(j.Operations[q.ID]) + "/disk.raw" + file, err := os.OpenFile(path, os.O_WRONLY, 0) + if err != nil { + t.Fatal(err) + } + if _, err = file.Write([]byte("do-not-overwrite")); err != nil { + t.Fatal(err) + } + file.Close() + f.p.syncDirectory = nil + if _, err = f.p.Execute(ctx, q); !errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatalf("overwrote uncertain preparation: %v", err) + } + file, err = os.Open(path) + if err != nil { + t.Fatal(err) + } + defer file.Close() + b := make([]byte, len("do-not-overwrite")) + if _, err = file.Read(b); err != nil { + t.Fatal(err) + } + if string(b) != "do-not-overwrite" { + t.Fatalf("disk overwritten: %q", b) + } +} +func TestLocalUncertainStartRecoversReceiptWithoutReinstall(t *testing.T) { + for _, bad := range []string{"missing", "wrong-receipt", "wrong-stage"} { + t.Run(bad, func(t *testing.T) { + f := newVMFixture(t) + ctx := context.Background() + q := vmRequest("interrupted") + f.failStart = true + if _, err := f.p.Execute(ctx, q); !errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatal(err) + } + j, err := f.p.read() + if err != nil { + t.Fatal(err) + } + r := j.Operations[q.ID] + if r.Stage != "installer-started" { + t.Fatal(r.Stage) + } + if _, _, err = f.p.Lookup(ctx, q.ID); !errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatal("lookup inferred completion") + } + log := f.p.directory(r) + "/installer.log" + content := "FLEET-INSTALLED:stale\n" + if bad == "wrong-stage" { + content = "FLEET-DISK-BOOT:" + r.Receipt + "\n" + } + if bad != "missing" { + if err = os.WriteFile(log, []byte(content), 0600); err != nil { + t.Fatal(err) + } + } + f.failStart = false + if _, err = f.p.Execute(ctx, q); !errors.Is(err, executor.ErrOutcomeUnknown) || len(f.creates) != 1 { + t.Fatalf("uncertain start retried or bad receipt accepted: %v", err) + } + if err = os.WriteFile(log, []byte("FLEET-INSTALLED:"+r.Receipt+"\n"), 0600); err != nil { + t.Fatal(err) + } + if _, err = f.p.Execute(ctx, q); err != nil { + t.Fatal(err) + } + if len(f.creates) != 2 || !strings.HasSuffix(f.creates[1], "/disk.xml") { + t.Fatalf("installer repeated: %v", f.creates) + } + }) + } +} + +func TestExplicitAccelerationAndJournalBinding(t *testing.T) { + for _, value := range []string{"auto", "qemu", "TCG", " kvm"} { + if _, err := parseAccelerator(value); err == nil { + t.Fatalf("accepted unknown accelerator %q", value) + } + } + for _, mode := range []string{"kvm", "tcg"} { + t.Run(mode, func(t *testing.T) { + f := newVMFixture(t) + f.p.accelerator = mode + q := vmRequest("mode-bound") + expected := "kvm" + if mode == "tcg" { + expected = "qemu" + } + if !strings.Contains(f.p.domainXML(&record{Request: q}, "disk"), "") { + t.Fatal("incorrect domain accelerator") + } + if _, err := f.p.Execute(context.Background(), q); err != nil { + t.Fatal(err) + } + j, err := f.p.read() + if err != nil { + t.Fatal(err) + } + if j.Accelerator != mode { + t.Fatal("accelerator not retained") + } + other := "tcg" + if mode == "tcg" { + other = "kvm" + } + f.p.accelerator = other + if _, err = f.p.Execute(context.Background(), q); !errors.Is(err, executor.ErrConflict) { + t.Fatalf("mode changed on replay: %v", err) + } + if _, _, err = f.p.Lookup(context.Background(), q.ID); !errors.Is(err, executor.ErrConflict) { + t.Fatalf("lookup ignored mode: %v", err) + } + }) + } + if mode, err := parseAccelerator(""); err != nil || mode != "kvm" { + t.Fatal("default changed") + } + f := newVMFixture(t) + f.p.accelerator = "tcg" + if err := f.p.checkMode(journal{Image: f.p.image}); !errors.Is(err, executor.ErrConflict) { + t.Fatal("legacy journal was not bound to KVM") + } +} diff --git a/internal/localvm/provider.go b/internal/localvm/provider.go new file mode 100644 index 00000000..ef35cbb0 --- /dev/null +++ b/internal/localvm/provider.go @@ -0,0 +1,715 @@ +// Package localvm implements a deliberately bounded local VM executor. +// It is not a remotely accessible provider or a production authorization boundary. +package localvm + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "net/url" + "os" + "os/exec" + "path/filepath" + "strconv" + "strings" + "time" + + "go.datum.net/fleet/internal/executor" + "go.datum.net/fleet/internal/simulator" + "golang.org/x/sys/unix" +) + +const Root = "/var/lib/fleet-local" +const artifacts = "/opt/fleet-local/artifacts" + +// bootWindow bounds one-time network boot admission after an install is retained. +const bootWindow = 10 * time.Minute + +const AssetID = "fleet-provider/fleet.datumapis.com/Device/synthetic-device-central-01" + +type Provider struct { + bootMode string + image string + accelerator string + root string + // bootRoot holds boot-service delivery evidence. In the Kubernetes site it + // is a separate volume path so the boot service never writes the journal. + bootRoot string + // bootOrigin is the boot Service URL written into the DHCP boot filename. + bootOrigin string + // uri selects the libvirt daemon; the site shares only its socket. + uri string + // readOnly providers (boot service, observer) never take the journal lock, + // create inventory, or execute effects. + readOnly bool + command func(context.Context, string, ...string) (string, error) + syncDirectory func(string) error +} + +func parseAccelerator(value string) (string, error) { + switch value { + case "", "kvm": + return "kvm", nil + case "tcg": + return "tcg", nil + default: + return "", errors.New("FLEET_LOCAL_VM_ACCEL must be kvm or tcg") + } +} +func (p *Provider) mode() string { + if p.accelerator == "" { + return "kvm" + } + return p.accelerator +} +func (p *Provider) checkMode(j journal) error { + mode, err := parseAccelerator(j.Accelerator) + if err != nil { + return err + } + if j.Image != "" && (mode != p.mode() || j.BootMode != p.bootMode) { + return executor.ErrConflict + } + return nil +} +func (p *Provider) stateRoot() string { + if p.root != "" { + return p.root + } + return Root +} +func syncDir(path string) error { + f, err := os.Open(path) + if err != nil { + return err + } + defer f.Close() + return f.Sync() +} +func (p *Provider) syncDir(path string) error { + if p.syncDirectory != nil { + return p.syncDirectory(path) + } + return syncDir(path) +} + +type record struct { + Request simulator.Request `json:"request"` + Result simulator.OperationResult `json:"result"` + Receipt string `json:"receipt"` + Stage string `json:"stage"` + BootToken string `json:"bootToken,omitempty"` + BootExpires time.Time `json:"bootExpires"` + BootClosed bool `json:"bootClosed"` +} +type journal struct { + BootMode string `json:"bootMode"` + Accelerator string `json:"accelerator"` + Image string `json:"image"` + Epoch int64 `json:"epoch"` + Binding string `json:"binding"` + Fence string `json:"fence"` + Closed bool `json:"closed"` + Operations map[string]*record `json:"operations"` +} + +// Open returns the effectful provider used only by per-operation workers. +func Open() (*Provider, error) { + p, err := open() + if err != nil { + return nil, err + } + if err := os.MkdirAll(Root, 0700); err != nil { + return nil, err + } + inventory := []byte(`{"kind":"Device","name":"synthetic-device-central-01","assetID":"` + AssetID + `","management":"LocalOwned","architecture":"amd64","vcpus":2,"memoryMiB":2048,"diskBytes":2147483648,"networkInterfaces":1}`) + guard, e := p.lock() + if e != nil { + return nil, e + } + defer guard.Close() + current, e := os.ReadFile(Root + "/device.json") + if os.IsNotExist(e) { + f, e := os.OpenFile(Root+"/device.json", os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600) + if e != nil { + return nil, e + } + _, e = f.Write(inventory) + if e == nil { + e = f.Sync() + } + f.Close() + if e != nil { + return nil, e + } + } else if e != nil { + return nil, e + } else if string(current) != string(inventory) { + return nil, errors.New("local device inventory differs; adoption is not authorized") + } + return p, nil +} + +// OpenReadOnly verifies the same artifacts and configuration but cannot +// execute, lock, or create state. The boot service and observer use it with +// a read-only journal mount. +func OpenReadOnly() (*Provider, error) { + p, err := open() + if err != nil { + return nil, err + } + p.readOnly = true + return p, nil +} + +func open() (*Provider, error) { + if os.Getenv("FLEET_LOCAL_VM") != "disposable-container" { + return nil, errors.New("local VM provider requires its disposable container") + } + accelerator, err := parseAccelerator(os.Getenv("FLEET_LOCAL_VM_ACCEL")) + if err != nil { + return nil, err + } + if accelerator == "kvm" { + if _, err := os.Stat("/dev/kvm"); err != nil { + return nil, err + } + } + origin, err := parseBootOrigin(os.Getenv("FLEET_BOOT_ORIGIN")) + if err != nil { + return nil, err + } + uri, err := parseLibvirtURI(os.Getenv("FLEET_LIBVIRT_URI")) + if err != nil { + return nil, err + } + bootRoot := os.Getenv("FLEET_BOOT_EVIDENCE") + if bootRoot != "" && (!filepath.IsAbs(bootRoot) || filepath.Clean(bootRoot) != bootRoot) { + return nil, errors.New("FLEET_BOOT_EVIDENCE must be a clean absolute path") + } + b, err := os.ReadFile(artifacts + "/SHA256SUMS") + if err != nil { + return nil, err + } + lines := strings.Split(strings.TrimSpace(string(b)), "\n") + if len(lines) != 2 { + return nil, errors.New("artifact manifest requires exactly two artifacts") + } + seen := map[string]bool{} + for _, line := range lines { + fields := strings.Fields(line) + if len(fields) != 2 || (fields[1] != "kernel" && fields[1] != "installer.gz") { + return nil, errors.New("invalid artifact manifest") + } + if seen[fields[1]] { + return nil, errors.New("duplicate artifact") + } + seen[fields[1]] = true + f, e := os.Open(artifacts + "/" + fields[1]) + if e != nil { + return nil, e + } + h := sha256.New() + _, e = io.Copy(h, f) + f.Close() + if e != nil { + return nil, e + } + if hex.EncodeToString(h.Sum(nil)) != fields[0] { + return nil, errors.New("artifact digest mismatch") + } + } + sum := sha256.Sum256(b) + p := &Provider{accelerator: accelerator, bootMode: "pxe", bootOrigin: origin, bootRoot: bootRoot, uri: uri} + p.image = "fleet-local-linux@sha256:" + hex.EncodeToString(sum[:]) + return p, nil +} + +// parseBootOrigin accepts only a literal http://IPv4:port origin. The site +// derives it from the boot Service ClusterIP; no hostname is resolved. +func parseBootOrigin(value string) (string, error) { + if value == "" { + return defaultBootOrigin, nil + } + u, err := url.Parse(value) + if err != nil || u.Scheme != "http" || u.User != nil || u.Path != "" || u.RawQuery != "" || u.Fragment != "" { + return "", errors.New("FLEET_BOOT_ORIGIN must be http://IPv4:port") + } + ip := net.ParseIP(u.Hostname()) + port, err := strconv.Atoi(u.Port()) + if ip == nil || ip.To4() == nil || err != nil || port < 1 || port > 65535 { + return "", errors.New("FLEET_BOOT_ORIGIN must be http://IPv4:port") + } + return "http://" + ip.To4().String() + ":" + strconv.Itoa(port), nil +} + +// parseLibvirtURI allows only the system daemon, optionally through an +// explicit absolute socket path shared from the runtime Pod. +func parseLibvirtURI(value string) (string, error) { + if value == "" || value == "qemu:///system" { + return "qemu:///system", nil + } + const prefix = "qemu:///system?socket=" + socket := strings.TrimPrefix(value, prefix) + if !strings.HasPrefix(value, prefix) || !filepath.IsAbs(socket) || filepath.Clean(socket) != socket || strings.ContainsAny(socket, "&?#") { + return "", errors.New("FLEET_LIBVIRT_URI must be qemu:///system or qemu:///system?socket=/absolute/path") + } + return value, nil +} + +func (p *Provider) lock() (*os.File, error) { + f, e := os.OpenFile(p.stateRoot()+"/lock", os.O_CREATE|os.O_RDWR, 0600) + if e != nil { + return nil, e + } + if e = unix.Flock(int(f.Fd()), unix.LOCK_EX|unix.LOCK_NB); e != nil { + f.Close() + return nil, e + } + return f, nil +} +func (p *Provider) read() (journal, error) { + var j journal + b, e := os.ReadFile(p.stateRoot() + "/journal.json") + if os.IsNotExist(e) { + j.Operations = map[string]*record{} + return j, nil + } + if e != nil { + return j, e + } + e = json.Unmarshal(b, &j) + if e == nil { + for id, r := range j.Operations { + if r == nil { + return j, errors.New("invalid retained operation") + } + if _, err := hex.DecodeString(r.Receipt); err != nil { + return j, errors.New("invalid receipt") + } + switch r.Stage { + case "admitted", "prepared", "installer-started", "installer-verified", "disk-started", "disk-verified": + if r.Result.Phase != "Unknown" || r.Result.CompletedAt != nil { + return j, errors.New("invalid pending result") + } + case "done": + if r.Result.Phase != "Succeeded" || r.Result.CompletedAt == nil || (r.Request.Kind == "install" && r.Result.Result != "installed") || (r.Request.Kind == "cleanup" && r.Result.Result != "clean") { + return j, errors.New("invalid terminal result") + } + default: + return j, errors.New("unknown journal stage") + } + d, de := simulator.RequestDigest(r.Request) + if de != nil || r.Request.ID != id || r.Result.ID != id || r.Result.Kind != r.Request.Kind || d != r.Result.InputDigest || r.Request.AssetID != AssetID || len(r.Receipt) != 64 { + return j, errors.New("invalid retained request") + } + } + } + if e == nil && j.Operations == nil { + e = errors.New("invalid journal") + } + return j, e +} +func (p *Provider) save(j journal) error { + b, e := json.MarshalIndent(j, "", " ") + if e != nil { + return e + } + f, e := os.OpenFile(p.stateRoot()+"/journal.tmp", os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0600) + if e != nil { + return e + } + _, e = f.Write(b) + if e == nil { + e = f.Sync() + } + ce := f.Close() + if e != nil { + return e + } + if ce != nil { + return ce + } + if e = os.Rename(p.stateRoot()+"/journal.tmp", p.stateRoot()+"/journal.json"); e != nil { + return e + } + d, e := os.Open(p.stateRoot()) + if e != nil { + return e + } + defer d.Close() + return d.Sync() +} +func key(id string) string { s := sha256.Sum256([]byte(id)); return hex.EncodeToString(s[:]) } +func run(ctx context.Context, name string, args ...string) (string, error) { + c := exec.CommandContext(ctx, name, args...) + b, e := c.CombinedOutput() + if e != nil { + return "", fmt.Errorf("%s failed: %w: %s", name, e, b) + } + return strings.TrimSpace(string(b)), nil +} +func (p *Provider) virsh(ctx context.Context, args ...string) (string, error) { + command := p.command + if command == nil { + command = run + } + uri := p.uri + if uri == "" { + uri = "qemu:///system" + } + return command(ctx, "virsh", append([]string{"--connect", uri}, args...)...) +} + +// Lookup reports only terminal retained results. A read-only provider reads +// without the lock: atomic journal replacement makes each read consistent. +func (p *Provider) Lookup(ctx context.Context, id string) (simulator.OperationResult, bool, error) { + if !p.readOnly { + f, e := p.lock() + if e != nil { + return simulator.OperationResult{}, false, e + } + defer f.Close() + } + j, e := p.read() + if e != nil { + return simulator.OperationResult{}, false, e + } + if e = p.checkMode(j); e != nil { + return simulator.OperationResult{}, false, e + } + r := j.Operations[id] + if r == nil { + return simulator.OperationResult{}, false, nil + } + if r.Stage != "done" { + return simulator.OperationResult{}, false, executor.ErrOutcomeUnknown + } + return r.Result, true, nil +} +func (p *Provider) Execute(ctx context.Context, q simulator.Request) (simulator.OperationResult, error) { + if p.readOnly { + return simulator.OperationResult{}, executor.ErrInvalid + } + ctx, cancel := context.WithTimeout(ctx, 10*time.Minute) + defer cancel() + f, e := p.lock() + if e != nil { + return simulator.OperationResult{}, e + } + defer f.Close() + if e = p.validate(q); e != nil { + return simulator.OperationResult{}, e + } + digest, e := simulator.RequestDigest(q) + if e != nil { + return simulator.OperationResult{}, e + } + j, e := p.read() + if e != nil { + return simulator.OperationResult{}, e + } + if e = p.checkMode(j); e != nil { + return simulator.OperationResult{}, e + } + j.Accelerator = p.mode() + j.BootMode = p.bootMode + if j.Image != "" && j.Image != p.image { + return simulator.OperationResult{}, executor.ErrConflict + } + j.Image = p.image + r := j.Operations[q.ID] + if r != nil { + if r.Result.InputDigest != digest { + return simulator.OperationResult{}, executor.ErrConflict + } + if r.Stage == "done" { + return r.Result, nil + } + } else { + for _, old := range j.Operations { + if old.Stage != "done" { + return simulator.OperationResult{}, executor.ErrOutcomeUnknown + } + } + if q.Epoch < j.Epoch || (q.Epoch == j.Epoch && (j.Closed || q.BindingID != j.Binding || q.FenceToken != j.Fence)) || (q.Epoch > j.Epoch && j.Epoch != 0 && !j.Closed) { + return simulator.OperationResult{}, executor.ErrFenced + } + j.Epoch = q.Epoch + j.Binding = q.BindingID + j.Fence = q.FenceToken + j.Closed = false + nonce := make([]byte, 32) + if _, e = rand.Read(nonce); e != nil { + return simulator.OperationResult{}, e + } + r = &record{Request: q, Receipt: hex.EncodeToString(nonce), Stage: "admitted", Result: simulator.OperationResult{ID: q.ID, Kind: q.Kind, InputDigest: digest, Phase: "Unknown", CreatedAt: time.Now().UTC()}} + if p.bootMode == "pxe" && q.Kind == "install" { + token := make([]byte, 32) + if _, e = rand.Read(token); e != nil { + return simulator.OperationResult{}, e + } + r.BootToken = hex.EncodeToString(token) + r.BootExpires = time.Now().UTC().Add(bootWindow) + } + j.Operations[q.ID] = r + if e = p.save(j); e != nil { + return simulator.OperationResult{}, e + } + } + if q.Kind == "install" { + e = p.install(ctx, &j, r) + } else { + e = p.cleanup(ctx, &j, r) + } + if e != nil { + return simulator.OperationResult{}, fmt.Errorf("%w: %v", executor.ErrOutcomeUnknown, e) + } + now := time.Now().UTC() + r.Stage = "done" + r.Result.Phase = "Succeeded" + r.Result.CompletedAt = &now + r.Result.Result = "installed" + if q.Kind == "cleanup" { + r.Result.Result = "clean" + j.Closed = true + } + if e = p.save(j); e != nil { + return simulator.OperationResult{}, fmt.Errorf("%w: %v", executor.ErrOutcomeUnknown, e) + } + return r.Result, nil +} +func (p *Provider) directory(r *record) string { + return filepath.Join(p.stateRoot(), key(r.Request.ID)) +} + +// bootDirectory holds boot-service delivery evidence for one operation. +func (p *Provider) bootDirectory(r *record) string { + if p.bootRoot == "" { + return p.directory(r) + } + return filepath.Join(p.bootRoot, key(r.Request.ID)) +} +func domain(r *record) string { return "fleet-local-" + key(r.Request.ID)[:24] } +func (p *Provider) install(ctx context.Context, j *journal, r *record) error { + dir := p.directory(r) + if r.Stage == "admitted" { + if e := os.Mkdir(dir, 0700); e != nil && !os.IsExist(e) { + return e + } + // Exclusive creation prevents an interrupted preparation from overwriting a disk. + f, e := os.OpenFile(dir+"/disk.raw", os.O_CREATE|os.O_EXCL|os.O_RDWR, 0600) + if e != nil { + return e + } + e = f.Truncate(2 << 30) + if e == nil { + e = f.Sync() + } + closeErr := f.Close() + if e != nil { + return e + } + if closeErr != nil { + return closeErr + } + if e = p.syncDir(dir); e != nil { + return e + } + r.Stage = "prepared" + if e = p.save(*j); e != nil { + return e + } + } + for _, stage := range []string{"installer", "disk"} { + before := "prepared" + if stage == "disk" { + before = "installer-verified" + } + if r.Stage == before { + if stage == "disk" && p.bootMode == "pxe" { + if !r.BootClosed { + return errors.New("boot admission still open") + } + if e := p.stopNetwork(ctx); e != nil { + return e + } + } + if stage == "installer" && p.bootMode == "pxe" { + if !time.Now().Before(r.BootExpires) || r.BootClosed { + return errors.New("boot admission expired or closed") + } + if e := p.prepareNetwork(ctx, r); e != nil { + return e + } + } + xml := p.domainXML(r, stage) + if e := os.WriteFile(dir+"/"+stage+".xml", []byte(xml), 0600); e != nil { + return e + } + // Retain start uncertainty before invoking libvirt. Recovery observes it; + // it never repeats a possibly executed installer boot. + r.Stage = stage + "-started" + if e := p.save(*j); e != nil { + return e + } + if _, e := p.virsh(ctx, "create", dir+"/"+stage+".xml"); e != nil { + return e + } + } + if r.Stage == stage+"-started" { + if e := p.waitReceipt(ctx, r, stage); e != nil { + return e + } + if stage == "installer" && p.bootMode == "pxe" { + if e := p.verifyNetworkBoot(ctx, r); e != nil { + return e + } + r.BootClosed = true + } + r.Stage = stage + "-verified" + if e := p.save(*j); e != nil { + return e + } + } + } + if r.Stage != "disk-verified" { + return errors.New("unexpected installation stage") + } + return nil +} +func (p *Provider) domainXML(r *record, stage string) string { + dir := p.directory(r) + boot := "" + nic := "" + if stage == "installer" { + boot = fmt.Sprintf("%s/kernel%s/installer.gzconsole=ttyS0 rdinit=/init fleet.receipt=%s", artifacts, artifacts, r.Receipt) + } + if stage == "installer" && p.bootMode == "pxe" { + boot = "" + nic = "" + } + domainType := "kvm" + if p.mode() == "tcg" { + domainType = "qemu" + } + return fmt.Sprintf(`%s20482hvm%sdestroydestroydestroy%s/usr/bin/qemu-system-x86_64`, domainType, domain(r), boot, nic, dir, dir, stage) +} +func (p *Provider) waitReceipt(ctx context.Context, r *record, stage string) error { + marker := "FLEET-INSTALLED:" + if stage == "disk" { + marker = "FLEET-DISK-BOOT:" + } + for { + names, e := p.virsh(ctx, "list", "--all", "--name") + if e != nil { + return e + } + present := false + for _, name := range strings.Fields(names) { + if name == domain(r) { + present = true + } + } + if !present { + b, e := os.ReadFile(p.directory(r) + "/" + stage + ".log") + if e != nil { + return e + } + for _, line := range strings.Split(string(b), "\n") { + if strings.TrimSpace(line) == marker+r.Receipt { + evidence, err := os.OpenFile(p.directory(r)+"/"+stage+".log", os.O_RDWR, 0) + if err != nil { + return err + } + err = evidence.Sync() + closeErr := evidence.Close() + if err != nil { + return err + } + if closeErr != nil { + return closeErr + } + return p.syncDir(p.directory(r)) + } + } + return errors.New("guest stopped without exact boot receipt") + } + select { + case <-ctx.Done(): + return ctx.Err() + case <-time.After(time.Second): + } + } +} +func (p *Provider) cleanup(ctx context.Context, j *journal, r *record) error { + // Only retained operations in this allocation identify cleanup targets. + names, e := p.virsh(ctx, "list", "--all", "--name") + if e != nil { + return e + } + for _, old := range j.Operations { + if old.Request.Kind != "install" || old.Request.BindingID != r.Request.BindingID { + continue + } + for _, n := range strings.Fields(names) { + if n == domain(old) { + return errors.New("domain still exists; cleanup remains unknown") + } + } + path := p.directory(old) + "/disk.raw" + if e = os.Remove(path); e != nil && !os.IsNotExist(e) { + return e + } + dir, err := os.Open(p.directory(old)) + if err != nil { + return err + } + err = dir.Sync() + dir.Close() + if err != nil { + return err + } + if _, e = os.Lstat(path); !os.IsNotExist(e) { + return errors.New("disk deletion unverified") + } + } + d, e := os.Open(p.stateRoot()) + if e != nil { + return e + } + defer d.Close() + return d.Sync() +} + +func (p *Provider) validate(q simulator.Request) error { + if q.ID == "" || len(q.ID) > 256 || q.BindingID == "" || len(q.BindingID) > 256 || q.FenceToken == "" || len(q.FenceToken) > 1024 || q.Epoch < 1 || len(q.Inputs) > 4096 { + return executor.ErrInvalid + } + if q.AssetID != AssetID || (q.Kind != "install" && q.Kind != "cleanup") { + return executor.ErrInvalid + } + if q.Kind == "install" { + var in struct { + Image string `json:"image"` + } + d := json.NewDecoder(strings.NewReader(string(q.Inputs))) + d.DisallowUnknownFields() + if d.Decode(&in) != nil || d.Decode(&struct{}{}) != io.EOF || in.Image != p.image { + return executor.ErrInvalid + } + } + if q.Kind == "cleanup" && len(q.Inputs) != 0 && strings.TrimSpace(string(q.Inputs)) != "{}" { + return executor.ErrInvalid + } + return nil +} + +// ImageReference is the locally verified artifact manifest identity. +func (p *Provider) ImageReference() string { return p.image } diff --git a/internal/localvm/provider_test.go b/internal/localvm/provider_test.go new file mode 100644 index 00000000..b35f2c24 --- /dev/null +++ b/internal/localvm/provider_test.go @@ -0,0 +1,35 @@ +package localvm + +import ( + "encoding/json" + "go.datum.net/fleet/internal/simulator" + "strings" + "testing" +) + +func TestBoundedInputs(t *testing.T) { + p := &Provider{image: "approved@sha256:abc"} + base := simulator.Request{ID: "installation", Kind: "install", AssetID: AssetID, BindingID: "allocation", Epoch: 1, FenceToken: "fence", Inputs: json.RawMessage(`{"image":"approved@sha256:abc"}`)} + if e := p.validate(base); e != nil { + t.Fatal(e) + } + for _, mutate := range []func(*simulator.Request){func(q *simulator.Request) { q.AssetID = "other" }, func(q *simulator.Request) { q.Epoch = 0 }, func(q *simulator.Request) { q.FenceToken = "" }, func(q *simulator.Request) { q.Inputs = json.RawMessage(`{"image":"unapproved"}`) }, func(q *simulator.Request) { + q.Inputs = json.RawMessage(`{"image":"approved@sha256:abc","path":"/host"}`) + }, func(q *simulator.Request) { q.Kind = "cleanup"; q.Inputs = json.RawMessage(`{"target":"/host"}`) }, func(q *simulator.Request) { q.Kind = "power" }} { + q := base + mutate(&q) + if p.validate(q) == nil { + t.Fatalf("accepted unsupported request: %#v", q) + } + } +} +func TestDiskBootHasNoInstallerAndNamesAreOpaque(t *testing.T) { + r := &record{Request: simulator.Request{ID: "../../host' "}, Receipt: strings.Repeat("a", 64)} + xml := (&Provider{}).domainXML(r, "disk") + if strings.Contains(xml, "") || strings.Contains(xml, "") || strings.Contains(xml, "") { + t.Fatal("missing disk boot") + } +} diff --git a/internal/localvm/pxe_review_adversarial_test.go b/internal/localvm/pxe_review_adversarial_test.go new file mode 100644 index 00000000..276f5af7 --- /dev/null +++ b/internal/localvm/pxe_review_adversarial_test.go @@ -0,0 +1,189 @@ +package localvm + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "os" + "strings" + "testing" + "time" + + "go.datum.net/fleet/internal/executor" + "go.datum.net/fleet/internal/simulator" +) + +func reviewBootRecord(t *testing.T) (*Provider, journal, *record) { + t.Helper() + p := newVMFixture(t).p + p.bootMode = "pxe" + q := vmRequest("independent-review") + digest, err := simulator.RequestDigest(q) + if err != nil { + t.Fatal(err) + } + r := &record{Request: q, Result: simulator.OperationResult{ID: q.ID, Kind: q.Kind, InputDigest: digest, Phase: "Unknown"}, Receipt: strings.Repeat("a", 64), Stage: "installer-started", BootToken: strings.Repeat("b", 64), BootExpires: time.Now().Add(time.Minute)} + j := journal{BootMode: "pxe", Accelerator: p.mode(), Image: p.image, Epoch: q.Epoch, Binding: q.BindingID, Fence: q.FenceToken, Operations: map[string]*record{q.ID: r}} + if err := os.Mkdir(p.directory(r), 0700); err != nil { + t.Fatal(err) + } + if err := p.save(j); err != nil { + t.Fatal(err) + } + return p, j, r +} + +type reviewFailedResponse struct { + header http.Header + writes int + short bool +} + +func (w *reviewFailedResponse) Header() http.Header { return w.header } +func (w *reviewFailedResponse) WriteHeader(int) {} +func (w *reviewFailedResponse) Write(data []byte) (int, error) { + w.writes++ + if w.short { + return len(data) - 1, nil + } + return 0, errors.New("client disconnected before body") +} + +func TestReviewIncompleteHTTPWriteCannotRecordCompletion(t *testing.T) { + for _, short := range []bool{false, true} { + p, _, r := reviewBootRecord(t) + w := &reviewFailedResponse{header: make(http.Header), short: short} + p.BootHandler().ServeHTTP(w, httptest.NewRequest("GET", "/"+key(r.Request.ID)[:16]+"/"+r.BootToken+"/boot.ipxe", nil)) + if w.writes != 1 { + t.Fatal("did not exercise body write") + } + b, err := os.ReadFile(p.directory(r) + "/boot-delivery.log") + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(b), "admitted boot.ipxe bytes=") || strings.Contains(string(b), "write-complete") { + t.Fatal("incomplete write counted as completion") + } + if err := p.verifyNetworkBoot(context.Background(), r); err == nil { + t.Fatal("attempt counted as network boot evidence") + } + } +} +func TestReviewCompleteHTTPWriteRecordsCompletion(t *testing.T) { + p, _, r := reviewBootRecord(t) + w := httptest.NewRecorder() + p.BootHandler().ServeHTTP(w, httptest.NewRequest("GET", "/"+key(r.Request.ID)[:16]+"/"+r.BootToken+"/boot.ipxe", nil)) + b, err := os.ReadFile(p.directory(r) + "/boot-delivery.log") + if err != nil { + t.Fatal(err) + } + if w.Code != http.StatusOK || !strings.Contains(string(b), "write-complete boot.ipxe bytes=") { + t.Fatal("successful write not recorded") + } +} + +func TestReviewCorruptDigestAndHTTPPathVariantsDenied(t *testing.T) { + p, j, r := reviewBootRecord(t) + base := "/" + key(r.Request.ID)[:16] + "/" + r.BootToken + for _, path := range []string{base + "/kernel/extra", base + "/%2e%2e", base + "/boot.ipxe?token=x", base + "/%2fkernel"} { + w := httptest.NewRecorder() + p.BootHandler().ServeHTTP(w, httptest.NewRequest("GET", path, nil)) + if w.Code != http.StatusForbidden { + t.Fatalf("path variant allowed: status %d", w.Code) + } + } + r.Result.InputDigest = "substituted" + if err := p.save(j); err != nil { + t.Fatal(err) + } + w := httptest.NewRecorder() + p.BootHandler().ServeHTTP(w, httptest.NewRequest("GET", base+"/boot.ipxe", nil)) + if w.Code != http.StatusForbidden { + t.Fatal("corrupt request digest admitted") + } +} + +func TestReviewClosedAdmissionDoesNotSettleLiveInstaller(t *testing.T) { + p, j, r := reviewBootRecord(t) + r.BootClosed = true + r.BootExpires = time.Now().Add(-time.Minute) + if err := p.save(j); err != nil { + t.Fatal(err) + } + // Even an exact receipt cannot settle a domain still present. + if err := os.WriteFile(p.directory(r)+"/installer.log", []byte("FLEET-INSTALLED:"+r.Receipt+"\n"), 0600); err != nil { + t.Fatal(err) + } + p.command = func(_ context.Context, _ string, args ...string) (string, error) { + if args[2] != "list" { + t.Fatalf("unexpected effect %s", args[2]) + } + return domain(r), nil + } + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if _, err := p.Execute(ctx, r.Request); !errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatalf("live expired installer settled: %v", err) + } + got, err := p.read() + if err != nil { + t.Fatal(err) + } + if got.Operations[r.Request.ID].Stage != "installer-started" { + t.Fatal("advanced live installer") + } +} + +func TestReviewNetworkTeardownFailureBlocksDiskBootAndRecovers(t *testing.T) { + p, j, r := reviewBootRecord(t) + r.Stage = "installer-verified" + r.BootClosed = true + if err := p.save(j); err != nil { + t.Fatal(err) + } + fail := true + creates := 0 + p.command = func(_ context.Context, _ string, args ...string) (string, error) { + switch args[2] { + case "net-list": + return "fleet-pxe", nil + case "net-destroy": + if fail { + return "", errors.New("uncertain teardown") + } + return "", nil + case "create": + creates++ + if !strings.HasSuffix(args[3], "/disk.xml") { + t.Fatal("installer replay") + } + return "", os.WriteFile(p.directory(r)+"/disk.log", []byte("FLEET-DISK-BOOT:"+r.Receipt+"\n"), 0600) + case "list": + return "", nil + default: + t.Fatalf("unexpected command %s", args[2]) + return "", nil + } + } + if _, err := p.Execute(context.Background(), r.Request); !errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatalf("teardown failure not unknown: %v", err) + } + if creates != 0 { + t.Fatal("booted despite uncertain teardown") + } + got, err := p.read() + if err != nil { + t.Fatal(err) + } + if got.Operations[r.Request.ID].Stage != "installer-verified" { + t.Fatal("advanced after failure") + } + fail = false + if _, err := p.Execute(context.Background(), r.Request); err != nil { + t.Fatal(err) + } + if creates != 1 { + t.Fatal("unexpected disk boot count") + } +} diff --git a/internal/localvm/site_test.go b/internal/localvm/site_test.go new file mode 100644 index 00000000..1abcf9b0 --- /dev/null +++ b/internal/localvm/site_test.go @@ -0,0 +1,116 @@ +package localvm + +import ( + "context" + "errors" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "go.datum.net/fleet/internal/executor" + "go.datum.net/fleet/internal/simulator" +) + +func TestSiteBootOriginAndLibvirtURIValidation(t *testing.T) { + for value, want := range map[string]string{"": defaultBootOrigin, "http://10.96.12.7:8080": "http://10.96.12.7:8080"} { + if got, err := parseBootOrigin(value); err != nil || got != want { + t.Fatalf("%q: %q %v", value, got, err) + } + } + for _, bad := range []string{"https://10.0.0.1:8080", "http://boot.local:8080", "http://10.0.0.1", "http://10.0.0.1:8080/x", "http://u@10.0.0.1:8080", "http://[::1]:8080", "http://10.0.0.1:0"} { + if _, err := parseBootOrigin(bad); err == nil { + t.Fatalf("accepted boot origin %q", bad) + } + } + for _, good := range []string{"", "qemu:///system", "qemu:///system?socket=/run/fleet-libvirt/libvirt-sock"} { + if _, err := parseLibvirtURI(good); err != nil { + t.Fatalf("%q: %v", good, err) + } + } + for _, bad := range []string{"qemu+tcp://runtime/system", "qemu:///session", "qemu:///system?socket=relative", "qemu:///system?socket=/run/x&no_verify=1", "qemu:///system?socket=/run/../etc"} { + if _, err := parseLibvirtURI(bad); err == nil { + t.Fatalf("accepted libvirt URI %q", bad) + } + } +} + +// The site network forwards only when the boot Service is outside the +// hypervisor namespace, and the DHCP boot file names that exact origin. +func TestSiteNetworkUsesBootServiceOrigin(t *testing.T) { + var defined string + p := &Provider{root: t.TempDir(), bootMode: "pxe", bootOrigin: "http://10.96.0.40:8080", uri: "qemu:///system?socket=/run/fleet-libvirt/libvirt-sock"} + p.command = func(_ context.Context, name string, args ...string) (string, error) { + if args[1] != p.uri { + t.Fatalf("libvirt URI not used: %v", args) + } + if args[2] == "net-create" { + b, err := os.ReadFile(args[3]) + defined = string(b) + return "", err + } + return "", nil + } + r := &record{Request: vmRequest("site-net"), BootToken: strings.Repeat("b", 64)} + if err := p.prepareNetwork(context.Background(), r); err != nil { + t.Fatal(err) + } + if !strings.Contains(defined, "") || !strings.Contains(defined, "file='http://10.96.0.40:8080/"+key(r.Request.ID)[:16]+"/"+r.BootToken+"/boot.ipxe'") { + t.Fatal(defined) + } + single := &Provider{root: t.TempDir(), bootMode: "pxe"} + single.command = func(_ context.Context, name string, args ...string) (string, error) { + if args[2] == "net-create" { + b, _ := os.ReadFile(args[3]) + defined = string(b) + } + return "", nil + } + if err := single.prepareNetwork(context.Background(), r); err != nil { + t.Fatal(err) + } + if strings.Contains(defined, " Date: Wed, 18 Nov 2026 13:33:08 -0600 Subject: [PATCH 009/518] feat(multiplane): local Milo, Karmada and kro acceptance with Flux-owned sites One command (task multiplane:acceptance) composes the local VM executor with native Milo project APIs, real Karmada delivery and reflection, and a Kubernetes-native site in a dedicated Colima profile: - internal/coordination defines the delivered handoff and journal-derived observation contract between management and a cell, with exact-request digests, epoch fencing and wrong-cell, stale and duplicate rejection. - internal/multiplane drives allocation, install, release and reuse through the shared lifecycle library; Coordinator.ClaimReleased lets it avoid restoring protection after verified release. - cmd/fleet-multiplane runs the management phases and the site roles. - config/site holds the Flux-owned shared site services and a kro graph that creates only per-handoff RBAC and bounded worker Jobs; config/multiplane holds per-cluster Flux sources for Milo, Karmada, kro and the site. - hack/multiplane runs the bounded phases, fault injection (worker Pod/Job interruption, delivery and reflection faults, wrong location, Flux drift, restart and fail-closed cases) and writes sanitized evidence. CI runs the harness's offline tests and shellcheck. Production authority, KVM and hardware remain unqualified. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 3 +- .gitignore | 8 + Taskfile.yaml | 27 + cmd/fleet-multiplane/main.go | 211 ++++ config/README.md | 7 + .../cell-federation/federation.yaml | 47 + .../cell-federation/kustomization.yaml | 4 + .../clusters/cell-site/kustomization.yaml | 4 + .../multiplane/clusters/cell-site/site.yaml | 53 + config/multiplane/clusters/cell/cell.yaml | 88 ++ .../clusters/cell/kustomization.yaml | 4 + config/multiplane/clusters/hub/hub.yaml | 100 ++ .../clusters/hub/kustomization.yaml | 4 + .../clusters/platform/kustomization.yaml | 4 + config/multiplane/clusters/platform/milo.yaml | 37 + config/multiplane/coordination/crd.yaml | 42 + .../coordination/kustomization.yaml | 7 + config/multiplane/coordination/namespace.yaml | 8 + config/multiplane/flux/components.yaml | 55 + config/multiplane/host/custody.yaml | 32 + config/multiplane/host/kustomization.yaml | 4 + config/multiplane/karmada-api/hub-rbac.yaml | 19 + .../multiplane/karmada-api/interpreter.yaml | 31 + .../multiplane/karmada-api/kustomization.yaml | 8 + .../karmada-api/member-namespace.yaml | 8 + .../karmada-members/kustomization.yaml | 4 + .../multiplane/karmada-members/members.yaml | 34 + config/multiplane/karmada/karmada.yaml | 81 ++ config/multiplane/karmada/kustomization.yaml | 4 + config/multiplane/kro/kro.yaml | 72 ++ config/multiplane/kro/kustomization.yaml | 4 + .../multiplane/milo/base/kustomization.yaml | 4 + config/multiplane/milo/base/milo.yaml | 112 ++ .../milo/consumer-a/kustomization.yaml | 13 + .../multiplane/milo/consumer-a/namespace.yaml | 7 + .../milo/consumer-b/kustomization.yaml | 13 + .../multiplane/milo/consumer-b/namespace.yaml | 7 + .../milo/provider/kustomization.yaml | 13 + .../multiplane/milo/provider/namespace.yaml | 7 + config/site/base/kro.yaml | 178 +++ config/site/base/kustomization.yaml | 6 + config/site/base/reconcilers.yaml | 81 ++ config/site/base/site.yaml | 78 ++ config/site/graph/kustomization.yaml | 4 + config/site/graph/rgd.yaml | 223 ++++ config/site/instance/dispatcher.yaml | 19 + config/site/instance/kustomization.yaml | 4 + config/site/services/kustomization.yaml | 4 + config/site/services/services.yaml | 161 +++ docs/development/README.md | 8 + docs/enhancements/pxe-installation/README.md | 22 +- docs/operations/README.md | 1 + docs/operations/gitops.md | 304 +++++ docs/operations/local-vm.md | 4 +- docs/operations/multiplane.md | 965 ++++++++++++++ docs/operations/site-execution.md | 386 ++++++ hack/local-vm/Containerfile | 8 + hack/local-vm/site-runtime | 22 + hack/multiplane/acceptance.sh | 45 + hack/multiplane/evidence.py | 276 ++++ hack/multiplane/fault_guard.py | 64 + hack/multiplane/flux.py | 1114 +++++++++++++++++ hack/multiplane/harness.py | 424 +++++++ hack/multiplane/k8s_evidence.py | 291 +++++ hack/multiplane/milo.py | 83 ++ hack/multiplane/reflection-faults.py | 45 + hack/multiplane/roles.py | 49 + hack/multiplane/run.sh | 104 ++ hack/multiplane/site.sh | 58 + hack/multiplane/steps.sh | 309 +++++ hack/multiplane/stop.sh | 27 + hack/multiplane/sysctl.py | 30 + hack/multiplane/teardown.sh | 65 + hack/multiplane/test-flux.py | 288 +++++ hack/multiplane/test-harness.sh | 273 ++++ hack/multiplane/test-k8s-evidence.py | 183 +++ hack/multiplane/topology.sh | 81 ++ hack/multiplane/verify-rbac.py | 101 ++ internal/controller/lifecycle.go | 14 + internal/coordination/mapping.go | 71 ++ internal/coordination/mapping_test.go | 41 + .../coordination/recovery_adversarial_test.go | 159 +++ internal/coordination/run.go | 40 + internal/coordination/site_test.go | 127 ++ internal/coordination/transport.go | 301 +++++ internal/coordination/transport_test.go | 115 ++ .../multiplane_recovery_adversarial_test.go | 139 ++ .../multiplane/location_adversarial_test.go | 131 ++ internal/multiplane/runner.go | 488 ++++++++ internal/multiplane/runner_test.go | 105 ++ 90 files changed, 9302 insertions(+), 7 deletions(-) create mode 100644 cmd/fleet-multiplane/main.go create mode 100644 config/multiplane/cell-federation/federation.yaml create mode 100644 config/multiplane/cell-federation/kustomization.yaml create mode 100644 config/multiplane/clusters/cell-site/kustomization.yaml create mode 100644 config/multiplane/clusters/cell-site/site.yaml create mode 100644 config/multiplane/clusters/cell/cell.yaml create mode 100644 config/multiplane/clusters/cell/kustomization.yaml create mode 100644 config/multiplane/clusters/hub/hub.yaml create mode 100644 config/multiplane/clusters/hub/kustomization.yaml create mode 100644 config/multiplane/clusters/platform/kustomization.yaml create mode 100644 config/multiplane/clusters/platform/milo.yaml create mode 100644 config/multiplane/coordination/crd.yaml create mode 100644 config/multiplane/coordination/kustomization.yaml create mode 100644 config/multiplane/coordination/namespace.yaml create mode 100644 config/multiplane/flux/components.yaml create mode 100644 config/multiplane/host/custody.yaml create mode 100644 config/multiplane/host/kustomization.yaml create mode 100644 config/multiplane/karmada-api/hub-rbac.yaml create mode 100644 config/multiplane/karmada-api/interpreter.yaml create mode 100644 config/multiplane/karmada-api/kustomization.yaml create mode 100644 config/multiplane/karmada-api/member-namespace.yaml create mode 100644 config/multiplane/karmada-members/kustomization.yaml create mode 100644 config/multiplane/karmada-members/members.yaml create mode 100644 config/multiplane/karmada/karmada.yaml create mode 100644 config/multiplane/karmada/kustomization.yaml create mode 100644 config/multiplane/kro/kro.yaml create mode 100644 config/multiplane/kro/kustomization.yaml create mode 100644 config/multiplane/milo/base/kustomization.yaml create mode 100644 config/multiplane/milo/base/milo.yaml create mode 100644 config/multiplane/milo/consumer-a/kustomization.yaml create mode 100644 config/multiplane/milo/consumer-a/namespace.yaml create mode 100644 config/multiplane/milo/consumer-b/kustomization.yaml create mode 100644 config/multiplane/milo/consumer-b/namespace.yaml create mode 100644 config/multiplane/milo/provider/kustomization.yaml create mode 100644 config/multiplane/milo/provider/namespace.yaml create mode 100644 config/site/base/kro.yaml create mode 100644 config/site/base/kustomization.yaml create mode 100644 config/site/base/reconcilers.yaml create mode 100644 config/site/base/site.yaml create mode 100644 config/site/graph/kustomization.yaml create mode 100644 config/site/graph/rgd.yaml create mode 100644 config/site/instance/dispatcher.yaml create mode 100644 config/site/instance/kustomization.yaml create mode 100644 config/site/services/kustomization.yaml create mode 100644 config/site/services/services.yaml create mode 100644 docs/operations/gitops.md create mode 100644 docs/operations/multiplane.md create mode 100644 docs/operations/site-execution.md create mode 100755 hack/local-vm/site-runtime create mode 100755 hack/multiplane/acceptance.sh create mode 100755 hack/multiplane/evidence.py create mode 100644 hack/multiplane/fault_guard.py create mode 100644 hack/multiplane/flux.py create mode 100755 hack/multiplane/harness.py create mode 100644 hack/multiplane/k8s_evidence.py create mode 100755 hack/multiplane/milo.py create mode 100755 hack/multiplane/reflection-faults.py create mode 100755 hack/multiplane/roles.py create mode 100755 hack/multiplane/run.sh create mode 100755 hack/multiplane/site.sh create mode 100755 hack/multiplane/steps.sh create mode 100755 hack/multiplane/stop.sh create mode 100755 hack/multiplane/sysctl.py create mode 100755 hack/multiplane/teardown.sh create mode 100644 hack/multiplane/test-flux.py create mode 100755 hack/multiplane/test-harness.sh create mode 100644 hack/multiplane/test-k8s-evidence.py create mode 100644 hack/multiplane/topology.sh create mode 100755 hack/multiplane/verify-rbac.py create mode 100644 internal/coordination/mapping.go create mode 100644 internal/coordination/mapping_test.go create mode 100644 internal/coordination/recovery_adversarial_test.go create mode 100644 internal/coordination/run.go create mode 100644 internal/coordination/site_test.go create mode 100644 internal/coordination/transport.go create mode 100644 internal/coordination/transport_test.go create mode 100644 internal/localvm/multiplane_recovery_adversarial_test.go create mode 100644 internal/multiplane/location_adversarial_test.go create mode 100644 internal/multiplane/runner.go create mode 100644 internal/multiplane/runner_test.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b27a066e..8cff52de 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -35,7 +35,8 @@ jobs: - run: ./hack/test-standalone-build-context.sh - run: ./hack/test-run-standalone-smoke.sh - run: ./hack/validate-doc-links.sh - - run: shellcheck -S warning hack/local-vm/run.sh hack/local-vm/start-libvirt + - run: ./hack/multiplane/test-harness.sh + - run: shellcheck -S warning hack/multiplane/*.sh hack/local-vm/run.sh hack/local-vm/start-libvirt hack/local-vm/site-runtime standalone-smoke: runs-on: ubuntu-latest timeout-minutes: 35 diff --git a/.gitignore b/.gitignore index 1e2ab3f7..710fb1db 100644 --- a/.gitignore +++ b/.gitignore @@ -28,5 +28,13 @@ .claude/settings.local.json .claude/worktrees/ +# Python tooling caches +__pycache__/ +*.py[cod] + +# Flux install manifest downloaded and verified by hack/multiplane/flux.py; never committed. +config/multiplane/flux/gotk-components.yaml + # Locally built binaries +/fleet-multiplane /fleet-local-vm diff --git a/Taskfile.yaml b/Taskfile.yaml index 700437ce..dce2a9f8 100644 --- a/Taskfile.yaml +++ b/Taskfile.yaml @@ -6,6 +6,33 @@ tasks: cmds: - ./hack/run-standalone-smoke.sh + multiplane:acceptance: + desc: Fresh local Milo/Karmada/kro/PXE acceptance, every service installed by per-cluster Flux from the checkout, in the task-owned Colima profile (exit 0 pass, 1 fail, 2 preflight, 3 blocked, 4 timeout). + env: + # Explicit opt-in for the documented reversible inotify adjustment inside the task VM only. + FLEET_MULTIPLANE_INOTIFY: '1024' + cmds: + - ./hack/multiplane/run.sh {{.CLI_ARGS}} + + multiplane:preflight: + desc: Check local prerequisites and implementation readiness without creating resources. + env: + FLEET_MULTIPLANE_INOTIFY: '1024' + cmds: + - ./hack/multiplane/run.sh --preflight-only {{.CLI_ARGS}} + + multiplane:stop: + desc: Stop (never delete) one retained run's exact containers; custody stays Unknown. + requires: + vars: [STATE] + cmds: + - ./hack/multiplane/stop.sh "{{.STATE}}" + + multiplane:test-harness: + desc: Offline tests for the multi-plane harness with fake runtime tools. + cmds: + - ./hack/multiplane/test-harness.sh + local-vm:acceptance: desc: Single-plane local VM PXE acceptance with explicit TCG in the task-owned Colima profile. env: diff --git a/cmd/fleet-multiplane/main.go b/cmd/fleet-multiplane/main.go new file mode 100644 index 00000000..004b6208 --- /dev/null +++ b/cmd/fleet-multiplane/main.go @@ -0,0 +1,211 @@ +// fleet-multiplane is an opt-in local acceptance binary. Production managers do +// not import its synthetic admission, quota or hardware enrollment fixtures. +package main + +import ( + "context" + "errors" + "flag" + "fmt" + "os" + "os/signal" + "syscall" + "time" + + "go.datum.net/fleet/internal/coordination" + "go.datum.net/fleet/internal/executor" + "go.datum.net/fleet/internal/localvm" + "go.datum.net/fleet/internal/multiplane" + "k8s.io/client-go/dynamic" + "k8s.io/client-go/rest" + "k8s.io/client-go/tools/clientcmd" +) + +func main() { + if err := run(); err != nil { + fmt.Fprintln(os.Stderr, "multi-plane command failed:", err) + os.Exit(1) + } +} +func run() error { + if len(os.Args) < 2 { + return fmt.Errorf("usage: fleet-multiplane site-worker|site-observer|image|boot-service|boot-denials| [flags]") + } + fs := flag.NewFlagSet(os.Args[1], flag.ContinueOnError) + once := fs.Bool("once", false, "one reconcile attempt for fault injection") + handoff := fs.String("handoff", "", "exact delivered handoff name (site-worker)") + origin := fs.String("origin", "", "boot listener origin to probe (boot-denials); default the configured origin") + interval := fs.Duration("interval", 10*time.Second, "observation refresh interval (site-observer)") + configPath := fs.String("config", "", "private acceptance config JSON") + kubeconfig := fs.String("kubeconfig", "", "cell-local kubeconfig; default in-cluster ServiceAccount") + cell := fs.String("cell", "", "exact Karmada member name") + scoped := fs.String("scoped-asset", "", "exact retained provider-scoped Device ID") + if err := fs.Parse(os.Args[2:]); err != nil { + return err + } + switch os.Args[1] { + case "seed", "allocate", "install", "admit-install", "release", "release-b", "reuse", "asset": + config, err := multiplane.ReadConfig(*configPath) + if err != nil { + return err + } + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Minute) + defer cancel() + if os.Args[1] == "seed" { + return multiplane.Seed(ctx, config) + } + r, err := multiplane.New(ctx, config) + if err != nil { + return err + } + if os.Args[1] == "asset" { + fmt.Println(r.ScopedAsset()) + return nil + } + var action func(context.Context) error + switch os.Args[1] { + case "allocate": + action = r.Allocate + case "install", "admit-install": + action = r.Install + case "release": + action = r.Release + case "release-b": + action = r.ReleaseSecond + case "reuse": + action = r.Reuse + } + for { + err = action(ctx) + if os.Args[1] == "admit-install" { + if errors.Is(err, executor.ErrOutcomeUnknown) { + fmt.Println("Installation intent retained; execution result remains Unknown") + return nil + } + if err == nil { + return fmt.Errorf("admission probe unexpectedly completed; run before starting cell") + } + return err + } + if (*once || terminal(err)) && err != nil { + return err + } + if err == nil { + fmt.Println(os.Args[1] + ": verified local acceptance phase (synthetic authority)") + return nil + } + if ctx.Err() != nil { + return fmt.Errorf("%s did not converge; authority retained; last error: %w", os.Args[1], err) + } + time.Sleep(3 * time.Second) + } + } + switch os.Args[1] { + case "image", "boot-service", "boot-denials": + // Read-only: the boot service mounts the journal read-only. + p, err := localvm.OpenReadOnly() + if err != nil { + return err + } + switch os.Args[1] { + case "image": + fmt.Println(p.ImageReference()) + return nil + case "boot-service": + return p.ServeBoot() + } + summary, err := p.CheckClosedBoot(*origin) + if err != nil { + return err + } + fmt.Println(summary) + return nil + case "site-worker", "site-observer": + default: + return fmt.Errorf("unknown command") + } + if *cell == "" || *scoped == "" || (os.Args[1] == "site-worker" && *handoff == "") { + return fmt.Errorf("cell, scoped-asset and (for site-worker) handoff required") + } + cfg, err := rest.InClusterConfig() + if *kubeconfig != "" { + cfg, err = clientcmd.BuildConfigFromFlags("", *kubeconfig) + } + if err != nil { + return err + } + cfg.Timeout = 30 * time.Second + api, err := dynamic.NewForConfig(cfg) + if err != nil { + return err + } + ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) + defer cancel() + if os.Args[1] == "site-observer" { + // The observer never executes: its provider is read-only. + p, err := localvm.OpenReadOnly() + if err != nil { + return err + } + mapping := &coordination.LocalAssetMapping{API: api, Namespace: coordinationNamespace, Cell: *cell, ScopedAsset: *scoped, PhysicalAsset: localvm.AssetID, Backend: p} + observer := coordination.Cell{API: api, Namespace: coordinationNamespace, Name: *cell, Executor: mapping} + return observer.Observe(ctx, *interval, func(name string, err error) { + fmt.Fprintf(os.Stderr, "observer: handoff %s not published: %s\n", name, classify(err)) + }) + } + p, err := localvm.Open() + if err != nil { + return err + } + mapping := &coordination.LocalAssetMapping{API: api, Namespace: coordinationNamespace, Cell: *cell, ScopedAsset: *scoped, PhysicalAsset: localvm.AssetID, Backend: p} + worker := coordination.Cell{API: api, Namespace: coordinationNamespace, Name: *cell, Executor: mapping} + err = worker.Execute(ctx, *handoff) + fmt.Fprintf(os.Stderr, "site-worker: handoff %s: %s\n", *handoff, classify(err)) + if err != nil { + if terminal(err) { + os.Exit(exitRejected) + } + os.Exit(exitRetry) + } + return nil +} + +const coordinationNamespace = "fleet-coordination" + +// Worker exit codes are the Job podFailurePolicy contract: rejected authority +// fails the Job without retry; anything else is retried by the Job controller +// against the same retained operation. Exit 0 only follows a validated +// terminal journal result, and still does not publish or authorize readiness. +const ( + exitRejected = 65 + exitRetry = 75 +) + +// classify names an outcome without printing handoff or journal contents. +func classify(err error) string { + switch { + case err == nil: + return "terminal result verified in provider journal" + case errors.Is(err, executor.ErrFenced): + return "fenced: " + err.Error() + case errors.Is(err, executor.ErrConflict): + return "conflict: " + err.Error() + case errors.Is(err, executor.ErrInvalid): + return "invalid: " + err.Error() + case errors.Is(err, executor.ErrOutcomeUnknown): + return "outcome unknown: " + err.Error() + default: + return "pending: " + err.Error() + } +} + +// terminal errors are authority rejections; retrying cannot change them and +// Unknown (the only retained-uncertainty result) stays retryable. +func terminal(err error) bool { + for _, target := range []error{executor.ErrConflict, executor.ErrFenced, executor.ErrInvalid, multiplane.ErrLocationNotServed} { + if errors.Is(err, target) { + return true + } + } + return false +} diff --git a/config/README.md b/config/README.md index df6693e2..c9f6f9c7 100644 --- a/config/README.md +++ b/config/README.md @@ -30,6 +30,13 @@ A price change is a new `-v2` pricing, since a ServicePricing can't be changed. `config/standalone` remains a synthetic, same-cluster test environment. It must not be referenced by either production root. +`config/multiplane` and `config/site` are the Flux source for the local +multi-plane acceptance only: Flux definitions per local cluster, Milo test +workloads, Karmada and kro releases, the coordination API and the kro site +graph. The harness stages them into an OCI artifact; see +[Flux-reconciled local environment](../docs/operations/gitops.md). They are not +production roots, and neither production root may reference them. + `config/overlays/synthetic-staging` is the temporary Milo-routed acceptance environment. It uses the real private custody, exclusivity, cleanup, and reuse implementation, but substitutes synthetic admission and provider evidence. It diff --git a/config/multiplane/cell-federation/federation.yaml b/config/multiplane/cell-federation/federation.yaml new file mode 100644 index 00000000..f704aa17 --- /dev/null +++ b/config/multiplane/cell-federation/federation.yaml @@ -0,0 +1,47 @@ +# Karmada push-mode member identity on the selected cell. It can deliver +# intent and read local status, but holds no status write or Secret read. +# Its token is minted by bootstrap enrollment, never stored in the source. +apiVersion: v1 +kind: ServiceAccount +metadata: {name: fleet-federation, namespace: fleet-coordination} +automountServiceAccountToken: false +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: {name: fleet-federation, namespace: fleet-coordination} +rules: + - apiGroups: [coordination.fleet.datumapis.com] + resources: [machineallocationhandoffs] + verbs: [get, list, watch, create, update, patch, delete] + - apiGroups: [""] + resources: [events] + verbs: [create, patch] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: {name: fleet-federation, namespace: fleet-coordination} +subjects: + - {kind: ServiceAccount, name: fleet-federation, namespace: fleet-coordination} +roleRef: {apiGroup: rbac.authorization.k8s.io, kind: Role, name: fleet-federation} +--- +# The member informer lists handoffs across namespaces and reads discovery. +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: {name: fleet-federation-discovery} +rules: + - apiGroups: [coordination.fleet.datumapis.com] + resources: [machineallocationhandoffs] + verbs: [get, list, watch] + - apiGroups: [""] + resources: [nodes, pods, namespaces] + verbs: [get, list, watch] + - nonResourceURLs: [/healthz, /readyz, /version, /api, /api/*, /apis, /apis/*] + verbs: [get] +--- +# Discovery is bound to the same federation identity, not a second one. +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: {name: fleet-federation-reader} +subjects: + - {kind: ServiceAccount, name: fleet-federation, namespace: fleet-coordination} +roleRef: {apiGroup: rbac.authorization.k8s.io, kind: ClusterRole, name: fleet-federation-discovery} diff --git a/config/multiplane/cell-federation/kustomization.yaml b/config/multiplane/cell-federation/kustomization.yaml new file mode 100644 index 00000000..66f25f05 --- /dev/null +++ b/config/multiplane/cell-federation/kustomization.yaml @@ -0,0 +1,4 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - federation.yaml diff --git a/config/multiplane/clusters/cell-site/kustomization.yaml b/config/multiplane/clusters/cell-site/kustomization.yaml new file mode 100644 index 00000000..1da011a3 --- /dev/null +++ b/config/multiplane/clusters/cell-site/kustomization.yaml @@ -0,0 +1,4 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - site.yaml diff --git a/config/multiplane/clusters/cell-site/site.yaml b/config/multiplane/clusters/cell-site/site.yaml new file mode 100644 index 00000000..eb209ab2 --- /dev/null +++ b/config/multiplane/clusters/cell-site/site.yaml @@ -0,0 +1,53 @@ +# Site layers present in the environment only once the scoped asset is known. +# +# Shared site services: runtime, boot Deployment and Service, observer and the +# worker admission parameter. Flux owns them directly, applied as a scoped +# identity that can write only Deployments, Services and ConfigMaps in +# fleet-site. wait covers every Deployment becoming Available. +apiVersion: kustomize.toolkit.fluxcd.io/v1 +kind: Kustomization +metadata: {name: fleet-site-services, namespace: flux-system} +spec: + interval: 10m + retryInterval: 30s + timeout: 5m + prune: true + wait: true + sourceRef: {kind: OCIRepository, name: fleet-gitops, namespace: flux-system} + path: ./config/site/services + dependsOn: + - {name: fleet-site-base, namespace: flux-system} + serviceAccountName: fleet-site-services-reconciler + postBuild: + substituteFrom: + - {kind: ConfigMap, name: fleet-environment} +--- +# The one HandoffDispatcher instance, applied as a scoped identity that can +# manage only HandoffDispatchers in fleet-site: never Jobs, Deployments, +# volumes or handoffs. It is applied only after the graph is Active and the +# shared services are healthy, and is itself healthy only when kro reports +# the graph ACTIVE against those Flux-owned references. +apiVersion: kustomize.toolkit.fluxcd.io/v1 +kind: Kustomization +metadata: {name: fleet-site-dispatch, namespace: flux-system} +spec: + interval: 10m + retryInterval: 30s + timeout: 5m + prune: true + wait: true + sourceRef: {kind: OCIRepository, name: fleet-gitops, namespace: flux-system} + path: ./config/site/instance + dependsOn: + - {name: fleet-site-graph, namespace: flux-system} + - {name: fleet-site-services, namespace: flux-system} + - {name: fleet-federation, namespace: flux-system} + serviceAccountName: fleet-site-dispatch-reconciler + postBuild: + substituteFrom: + - {kind: ConfigMap, name: fleet-environment} + healthCheckExprs: + - apiVersion: site.fleet.datumapis.com/v1alpha1 + kind: HandoffDispatcher + current: status.state == 'ACTIVE' + inProgress: status.state != 'ACTIVE' diff --git a/config/multiplane/clusters/cell/cell.yaml b/config/multiplane/clusters/cell/cell.yaml new file mode 100644 index 00000000..2a5df0c4 --- /dev/null +++ b/config/multiplane/clusters/cell/cell.yaml @@ -0,0 +1,88 @@ +# Selected cell. Handoff CRD and namespace; prune false (see the hub copy). +apiVersion: kustomize.toolkit.fluxcd.io/v1 +kind: Kustomization +metadata: {name: fleet-coordination, namespace: flux-system} +spec: + interval: 10m + retryInterval: 30s + timeout: 5m + prune: false + wait: true + sourceRef: {kind: OCIRepository, name: fleet-gitops, namespace: flux-system} + path: ./config/multiplane/coordination +--- +# Karmada push-mode member identity; its token is enrolled by bootstrap. +apiVersion: kustomize.toolkit.fluxcd.io/v1 +kind: Kustomization +metadata: {name: fleet-federation, namespace: flux-system} +spec: + interval: 10m + retryInterval: 30s + timeout: 5m + prune: true + wait: true + sourceRef: {kind: OCIRepository, name: fleet-gitops, namespace: flux-system} + path: ./config/multiplane/cell-federation + dependsOn: + - {name: fleet-coordination, namespace: flux-system} +--- +# kro controller. wait covers the HelmRelease and its OCI chart source, so +# a bad chart revision makes this not Ready and blocks the site layers. +apiVersion: kustomize.toolkit.fluxcd.io/v1 +kind: Kustomization +metadata: {name: kro, namespace: flux-system} +spec: + interval: 10m + retryInterval: 30s + timeout: 3m + prune: true + wait: true + sourceRef: {kind: OCIRepository, name: fleet-gitops, namespace: flux-system} + path: ./config/multiplane/kro +--- +# Site namespace, retained volume, service identities, observer RBAC, kro's +# narrowed grants and the admission policy for kro's writes. Shared site +# infrastructure does not depend on kro: a broken kro release blocks only the +# graph and the dispatcher. The claim binds on first consumer +# (WaitForFirstConsumer). +apiVersion: kustomize.toolkit.fluxcd.io/v1 +kind: Kustomization +metadata: {name: fleet-site-base, namespace: flux-system} +spec: + interval: 10m + retryInterval: 30s + timeout: 5m + prune: true + wait: true + sourceRef: {kind: OCIRepository, name: fleet-gitops, namespace: flux-system} + path: ./config/site/base + dependsOn: + - {name: fleet-coordination, namespace: flux-system} + healthCheckExprs: + - apiVersion: v1 + kind: PersistentVolumeClaim + current: status.phase == 'Pending' || status.phase == 'Bound' + failed: status.phase == 'Lost' +--- +# The HandoffDispatcher ResourceGraphDefinition, applied as a scoped identity +# that can manage only ResourceGraphDefinitions. +apiVersion: kustomize.toolkit.fluxcd.io/v1 +kind: Kustomization +metadata: {name: fleet-site-graph, namespace: flux-system} +spec: + interval: 10m + retryInterval: 30s + timeout: 5m + prune: true + wait: true + sourceRef: {kind: OCIRepository, name: fleet-gitops, namespace: flux-system} + path: ./config/site/graph + dependsOn: + - {name: kro, namespace: flux-system} + - {name: fleet-site-base, namespace: flux-system} + serviceAccountName: fleet-site-graph-reconciler + healthCheckExprs: + - apiVersion: kro.run/v1alpha1 + kind: ResourceGraphDefinition + current: status.state == 'Active' + inProgress: status.state != 'Active' diff --git a/config/multiplane/clusters/cell/kustomization.yaml b/config/multiplane/clusters/cell/kustomization.yaml new file mode 100644 index 00000000..94c2a59e --- /dev/null +++ b/config/multiplane/clusters/cell/kustomization.yaml @@ -0,0 +1,4 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - cell.yaml diff --git a/config/multiplane/clusters/hub/hub.yaml b/config/multiplane/clusters/hub/hub.yaml new file mode 100644 index 00000000..a31b21ce --- /dev/null +++ b/config/multiplane/clusters/hub/hub.yaml @@ -0,0 +1,100 @@ +# The namespace exists before the release so the environment ConfigMap that +# Karmada-API Kustomizations substitute from can live beside their kubeconfig. +apiVersion: v1 +kind: Namespace +metadata: + name: karmada-system + annotations: + kustomize.toolkit.fluxcd.io/prune: disabled +--- +# Karmada chart on the host. wait covers the HelmRelease and its source. +apiVersion: kustomize.toolkit.fluxcd.io/v1 +kind: Kustomization +metadata: {name: karmada, namespace: flux-system} +spec: + interval: 10m + retryInterval: 30s + timeout: 20m + prune: true + wait: true + sourceRef: {kind: OCIRepository, name: fleet-gitops, namespace: flux-system} + path: ./config/multiplane/karmada +--- +# Private custody namespace and the custodian identity on the host API. +apiVersion: kustomize.toolkit.fluxcd.io/v1 +kind: Kustomization +metadata: {name: fleet-host, namespace: flux-system} +spec: + interval: 10m + retryInterval: 30s + timeout: 5m + prune: true + wait: true + sourceRef: {kind: OCIRepository, name: fleet-gitops, namespace: flux-system} + path: ./config/multiplane/host +--- +# Handoff CRD and namespace on the Karmada API. prune false: never +# garbage-collect a CRD with retained intent (as datum-cloud/infra karmada-crds). +apiVersion: kustomize.toolkit.fluxcd.io/v1 +kind: Kustomization +metadata: {name: fleet-karmada-coordination, namespace: karmada-system} +spec: + interval: 10m + retryInterval: 30s + timeout: 5m + prune: false + wait: true + sourceRef: {kind: OCIRepository, name: fleet-gitops, namespace: flux-system} + path: ./config/multiplane/coordination + dependsOn: + - {name: karmada, namespace: flux-system} + # Applied to the Karmada API, not the host, with the chart-generated + # in-cluster admin kubeconfig Secret. + kubeConfig: + secretRef: {name: karmada-kubeconfig, key: kubeconfig} +--- +# Management intent role, the status interpreter and the member Secret namespace. +apiVersion: kustomize.toolkit.fluxcd.io/v1 +kind: Kustomization +metadata: {name: fleet-karmada-api, namespace: karmada-system} +spec: + interval: 10m + retryInterval: 30s + timeout: 5m + prune: true + wait: true + sourceRef: {kind: OCIRepository, name: fleet-gitops, namespace: flux-system} + path: ./config/multiplane/karmada-api + dependsOn: + - {name: fleet-karmada-coordination, namespace: karmada-system} + # Applied to the Karmada API, not the host, with the chart-generated + # in-cluster admin kubeconfig Secret. + kubeConfig: + secretRef: {name: karmada-kubeconfig, key: kubeconfig} +--- +# Member registration and placement. The member credential Secret is +# enrolled by bootstrap; this waits until Karmada reports the member Ready. +apiVersion: kustomize.toolkit.fluxcd.io/v1 +kind: Kustomization +metadata: {name: fleet-karmada-members, namespace: karmada-system} +spec: + interval: 10m + retryInterval: 30s + timeout: 5m + prune: true + wait: true + sourceRef: {kind: OCIRepository, name: fleet-gitops, namespace: flux-system} + path: ./config/multiplane/karmada-members + dependsOn: + - {name: fleet-karmada-api, namespace: karmada-system} + # Applied to the Karmada API, not the host, with the chart-generated + # in-cluster admin kubeconfig Secret. + kubeConfig: + secretRef: {name: karmada-kubeconfig, key: kubeconfig} + postBuild: + substituteFrom: + - {kind: ConfigMap, name: fleet-environment} + healthCheckExprs: + - apiVersion: cluster.karmada.io/v1alpha1 + kind: Cluster + current: status.conditions.exists(e, e.type == 'Ready' && e.status == 'True') diff --git a/config/multiplane/clusters/hub/kustomization.yaml b/config/multiplane/clusters/hub/kustomization.yaml new file mode 100644 index 00000000..7eedca2e --- /dev/null +++ b/config/multiplane/clusters/hub/kustomization.yaml @@ -0,0 +1,4 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - hub.yaml diff --git a/config/multiplane/clusters/platform/kustomization.yaml b/config/multiplane/clusters/platform/kustomization.yaml new file mode 100644 index 00000000..c771d7e5 --- /dev/null +++ b/config/multiplane/clusters/platform/kustomization.yaml @@ -0,0 +1,4 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - milo.yaml diff --git a/config/multiplane/clusters/platform/milo.yaml b/config/multiplane/clusters/platform/milo.yaml new file mode 100644 index 00000000..fc32dff0 --- /dev/null +++ b/config/multiplane/clusters/platform/milo.yaml @@ -0,0 +1,37 @@ +# Platform cluster: three independent Milo project APIs, each with its own +# Kustomization, process, etcd and volume, so each can fail independently. +apiVersion: kustomize.toolkit.fluxcd.io/v1 +kind: Kustomization +metadata: {name: milo-provider, namespace: flux-system} +spec: + interval: 10m + retryInterval: 30s + timeout: 5m + prune: true + wait: true + sourceRef: {kind: OCIRepository, name: fleet-gitops, namespace: flux-system} + path: ./config/multiplane/milo/provider +--- +apiVersion: kustomize.toolkit.fluxcd.io/v1 +kind: Kustomization +metadata: {name: milo-consumer-a, namespace: flux-system} +spec: + interval: 10m + retryInterval: 30s + timeout: 5m + prune: true + wait: true + sourceRef: {kind: OCIRepository, name: fleet-gitops, namespace: flux-system} + path: ./config/multiplane/milo/consumer-a +--- +apiVersion: kustomize.toolkit.fluxcd.io/v1 +kind: Kustomization +metadata: {name: milo-consumer-b, namespace: flux-system} +spec: + interval: 10m + retryInterval: 30s + timeout: 5m + prune: true + wait: true + sourceRef: {kind: OCIRepository, name: fleet-gitops, namespace: flux-system} + path: ./config/multiplane/milo/consumer-b diff --git a/config/multiplane/coordination/crd.yaml b/config/multiplane/coordination/crd.yaml new file mode 100644 index 00000000..bb4d4591 --- /dev/null +++ b/config/multiplane/coordination/crd.yaml @@ -0,0 +1,42 @@ +# Experimental handoff API: install on the Karmada API and participating cells. +# Never install in consumer project APIs. Payloads contain private authority. +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: machineallocationhandoffs.coordination.fleet.datumapis.com + annotations: + # Deleting the CRD deletes every retained handoff. Never prune it. + kustomize.toolkit.fluxcd.io/prune: disabled +spec: + group: coordination.fleet.datumapis.com + scope: Namespaced + names: + plural: machineallocationhandoffs + singular: machineallocationhandoff + kind: MachineAllocationHandoff + versions: + - name: v1alpha1 + served: true + storage: true + subresources: + status: {} + schema: + openAPIV3Schema: + type: object + required: [spec] + properties: + spec: + type: object + required: [cell, requestJSON] + x-kubernetes-validations: + - rule: self == oldSelf + message: Retained handoff intent is immutable + properties: + cell: {type: string, minLength: 1, maxLength: 63} + requestJSON: + type: string + minLength: 1 + maxLength: 1048576 + status: + type: object + x-kubernetes-preserve-unknown-fields: true diff --git a/config/multiplane/coordination/kustomization.yaml b/config/multiplane/coordination/kustomization.yaml new file mode 100644 index 00000000..4e95a55e --- /dev/null +++ b/config/multiplane/coordination/kustomization.yaml @@ -0,0 +1,7 @@ +# Handoff API and namespace for the Karmada API and every participating cell. +# Reconciled by Flux with prune disabled; see docs/operations/gitops.md. +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - namespace.yaml + - crd.yaml diff --git a/config/multiplane/coordination/namespace.yaml b/config/multiplane/coordination/namespace.yaml new file mode 100644 index 00000000..7695e765 --- /dev/null +++ b/config/multiplane/coordination/namespace.yaml @@ -0,0 +1,8 @@ +# Retained handoff intent lives here on the Karmada API and on each cell. +apiVersion: v1 +kind: Namespace +metadata: + name: fleet-coordination + annotations: + # Never garbage-collect: deleting the namespace deletes every handoff. + kustomize.toolkit.fluxcd.io/prune: disabled diff --git a/config/multiplane/flux/components.yaml b/config/multiplane/flux/components.yaml new file mode 100644 index 00000000..933285d6 --- /dev/null +++ b/config/multiplane/flux/components.yaml @@ -0,0 +1,55 @@ +# Flux v2.9.6 controller selection and pins, the same for every local cluster. +# The harness stages this file, unchanged, as environment/flux-components/ +# kustomization.yaml beside the release install.yaml (gotk-components.yaml), +# which it downloads and verifies against the SHA-256 pinned in +# hack/multiplane/flux.py; the upstream manifest is not committed, so this file +# is deliberately not named kustomization.yaml. The bootstrap applies this exact +# build once; afterwards each cluster's Flux reconciles (and owns) its own +# controllers from the source. +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - gotk-components.yaml +images: + - name: ghcr.io/fluxcd/source-controller + digest: sha256:6a6693172589f8ff26123a231d5fa6ceb194a6efb4dc647cdf057c959f76a2e3 + - name: ghcr.io/fluxcd/kustomize-controller + digest: sha256:2ebeaa341da77d52b6abbbba5efcee0450d47f8b42f0e6f33b08f9020262d606 + - name: ghcr.io/fluxcd/helm-controller + digest: sha256:0d52fff5c4d476277b8fcb6beb9041e269adb5db943fe69f5a806ea0c92b1511 + - name: ghcr.io/fluxcd/notification-controller + digest: sha256:840f318265ee26f0d2c48a158bf7896b22aa4e998e320a18646309f0e40b15da +# Image automation and source-watcher are not used. +patches: + - patch: |- + $patch: delete + apiVersion: apps/v1 + kind: Deployment + metadata: {name: image-automation-controller, namespace: flux-system} + - patch: |- + $patch: delete + apiVersion: apps/v1 + kind: Deployment + metadata: {name: image-reflector-controller, namespace: flux-system} + - patch: |- + $patch: delete + apiVersion: apps/v1 + kind: Deployment + metadata: {name: source-watcher, namespace: flux-system} + - patch: |- + $patch: delete + apiVersion: v1 + kind: Service + metadata: {name: source-watcher, namespace: flux-system} + # Local tuning: re-check unready dependencies every 10s instead of 30s, so a + # revision ripples through the four-level site chain in under a minute. + - target: {kind: Deployment, name: kustomize-controller} + patch: |- + - op: add + path: /spec/template/spec/containers/0/args/- + value: --requeue-dependency=10s + - target: {kind: Deployment, name: helm-controller} + patch: |- + - op: add + path: /spec/template/spec/containers/0/args/- + value: --requeue-dependency=10s diff --git a/config/multiplane/host/custody.yaml b/config/multiplane/host/custody.yaml new file mode 100644 index 00000000..327eff17 --- /dev/null +++ b/config/multiplane/host/custody.yaml @@ -0,0 +1,32 @@ +# Private allocation custody on the management host API. Only the shared +# lifecycle coordinator's custodian identity may read or write these Secrets; +# its token is minted by bootstrap and never stored in the source. +apiVersion: v1 +kind: Namespace +metadata: + name: fleet-system-private + annotations: + # Holds retained allocation custody. Never garbage-collect it. Same name + # and policy as the production manager's private namespace. + kustomize.toolkit.fluxcd.io/prune: disabled + fleet.datumapis.com/shared-with-standalone: "true" +--- +apiVersion: v1 +kind: ServiceAccount +metadata: {name: fleet-custodian, namespace: fleet-system-private} +automountServiceAccountToken: false +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: {name: fleet-custodian, namespace: fleet-system-private} +rules: + - apiGroups: [""] + resources: [secrets] + verbs: [get, list, watch, create, update, patch] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: {name: fleet-custodian, namespace: fleet-system-private} +subjects: + - {kind: ServiceAccount, name: fleet-custodian, namespace: fleet-system-private} +roleRef: {apiGroup: rbac.authorization.k8s.io, kind: Role, name: fleet-custodian} diff --git a/config/multiplane/host/kustomization.yaml b/config/multiplane/host/kustomization.yaml new file mode 100644 index 00000000..b838ac56 --- /dev/null +++ b/config/multiplane/host/kustomization.yaml @@ -0,0 +1,4 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - custody.yaml diff --git a/config/multiplane/karmada-api/hub-rbac.yaml b/config/multiplane/karmada-api/hub-rbac.yaml new file mode 100644 index 00000000..858908e6 --- /dev/null +++ b/config/multiplane/karmada-api/hub-rbac.yaml @@ -0,0 +1,19 @@ +apiVersion: v1 +kind: ServiceAccount +metadata: {name: fleet-management, namespace: fleet-coordination} +automountServiceAccountToken: false +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: {name: fleet-management, namespace: fleet-coordination} +rules: + - apiGroups: [coordination.fleet.datumapis.com] + resources: [machineallocationhandoffs] + verbs: [get, list, watch, create] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: {name: fleet-management, namespace: fleet-coordination} +subjects: + - {kind: ServiceAccount, name: fleet-management, namespace: fleet-coordination} +roleRef: {apiGroup: rbac.authorization.k8s.io, kind: Role, name: fleet-management} diff --git a/config/multiplane/karmada-api/interpreter.yaml b/config/multiplane/karmada-api/interpreter.yaml new file mode 100644 index 00000000..736d2141 --- /dev/null +++ b/config/multiplane/karmada-api/interpreter.yaml @@ -0,0 +1,31 @@ +apiVersion: config.karmada.io/v1alpha1 +kind: ResourceInterpreterCustomization +metadata: + name: fleet-machine-allocation-handoff +spec: + target: + apiVersion: coordination.fleet.datumapis.com/v1alpha1 + kind: MachineAllocationHandoff + customizations: + statusReflection: + luaScript: | + function ReflectStatus(observedObj) + if observedObj.status == nil then return {} end + return observedObj.status + end + statusAggregation: + luaScript: | + function AggregateStatus(desiredObj, statusItems) + local reflected = {} + for _, item in ipairs(statusItems or {}) do + if item.status ~= nil and item.status.observation ~= nil then + table.insert(reflected, { + clusterName = item.clusterName, + observation = item.status.observation + }) + end + end + -- Clear missing results; do not retain old success on zero replicas. + desiredObj.status = {reflected = reflected} + return desiredObj + end diff --git a/config/multiplane/karmada-api/kustomization.yaml b/config/multiplane/karmada-api/kustomization.yaml new file mode 100644 index 00000000..34d85767 --- /dev/null +++ b/config/multiplane/karmada-api/kustomization.yaml @@ -0,0 +1,8 @@ +# Karmada API configuration: management's intent-only role and the status +# interpreter. Applied by Flux on the host through the chart's karmada-kubeconfig. +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - hub-rbac.yaml + - interpreter.yaml + - member-namespace.yaml diff --git a/config/multiplane/karmada-api/member-namespace.yaml b/config/multiplane/karmada-api/member-namespace.yaml new file mode 100644 index 00000000..f7136f2d --- /dev/null +++ b/config/multiplane/karmada-api/member-namespace.yaml @@ -0,0 +1,8 @@ +# Holds each member's push-mode credential Secret. The Secret itself is +# credential enrollment, written by bootstrap and never stored in the source. +apiVersion: v1 +kind: Namespace +metadata: + name: karmada-cluster + annotations: + kustomize.toolkit.fluxcd.io/prune: disabled diff --git a/config/multiplane/karmada-members/kustomization.yaml b/config/multiplane/karmada-members/kustomization.yaml new file mode 100644 index 00000000..3066f53f --- /dev/null +++ b/config/multiplane/karmada-members/kustomization.yaml @@ -0,0 +1,4 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - members.yaml diff --git a/config/multiplane/karmada-members/members.yaml b/config/multiplane/karmada-members/members.yaml new file mode 100644 index 00000000..c77d1ed1 --- /dev/null +++ b/config/multiplane/karmada-members/members.yaml @@ -0,0 +1,34 @@ +# Push-mode member registration and placement for the selected cell. Values +# come from the per-environment fleet-environment ConfigMap (postBuild). +# The member's token Secret is enrolled by bootstrap, never stored in Git. +apiVersion: cluster.karmada.io/v1alpha1 +kind: Cluster +metadata: + name: "${FLEET_CELL}" + annotations: + # Unjoining a member deletes what Karmada propagated to it, including + # retained handoffs. Removing a member is an ordered manual procedure. + kustomize.toolkit.fluxcd.io/prune: disabled +spec: + syncMode: Push + apiEndpoint: "${FLEET_CELL_ENDPOINT}" + secretRef: + name: "${FLEET_CELL}" + namespace: karmada-cluster +--- +apiVersion: policy.karmada.io/v1alpha1 +kind: PropagationPolicy +metadata: + name: fleet-selected-cell + namespace: fleet-coordination +spec: + resourceSelectors: + - apiVersion: coordination.fleet.datumapis.com/v1alpha1 + kind: MachineAllocationHandoff + labelSelector: + matchLabels: + coordination.fleet.datumapis.com/cell: "${FLEET_CELL}" + placement: + clusterAffinity: + clusterNames: + - "${FLEET_CELL}" diff --git a/config/multiplane/karmada/karmada.yaml b/config/multiplane/karmada/karmada.yaml new file mode 100644 index 00000000..95dbc1de --- /dev/null +++ b/config/multiplane/karmada/karmada.yaml @@ -0,0 +1,81 @@ +# Karmada v1.16.0 on the management host, the chart pinned by the connected +# datum-cloud/test-infra federation checkout. HelmRepository + HelmRelease +# follows datum-cloud/infra infrastructure/karmada. Keep fsync enabled; single +# local replicas are not an HA qualification. +apiVersion: source.toolkit.fluxcd.io/v1 +kind: HelmRepository +metadata: + name: karmada-charts + namespace: flux-system +spec: + interval: 1h + url: https://raw.githubusercontent.com/karmada-io/karmada/master/charts +--- +apiVersion: helm.toolkit.fluxcd.io/v2 +kind: HelmRelease +metadata: + name: karmada + namespace: flux-system + annotations: + # Uninstalling Karmada deletes retained coordination intent; removing it + # from the source must never garbage-collect the release. + kustomize.toolkit.fluxcd.io/prune: disabled +spec: + interval: 30m + timeout: 15m + releaseName: karmada + targetNamespace: karmada-system + storageNamespace: karmada-system + chart: + spec: + chart: karmada + version: v1.16.0 + sourceRef: {kind: HelmRepository, name: karmada-charts} + interval: 1h + install: + remediation: {retries: 3} + upgrade: + # Chart hooks regenerate certificates on upgrade; a failed upgrade is + # rolled back rather than retried into a different state. + remediation: {retries: 1, strategy: rollback} + crds: Skip + # As in datum-cloud/infra: report drift, do not overwrite. Pre-upgrade cert + # hooks make blind correction of this release unsafe. + driftDetection: {mode: warn} + values: + # Floating chart defaults pinned by index digest. + cfssl: + image: {digest: "sha256:a32a9048078819d3035f5dc46637346a0e7da9df297ab234994c9a80cde10b98"} + kubectl: + image: {digest: "sha256:8919c149c2e3d6860e0143c117900e64d71395172aaef0e01e604bb98c8e7ce0"} + apiServer: + serviceType: NodePort + nodePort: 32443 + resources: + requests: {cpu: 100m, memory: 256Mi} + limits: {memory: 768Mi} + controllerManager: + resources: + requests: {cpu: 50m, memory: 128Mi} + limits: {memory: 384Mi} + scheduler: + resources: + requests: {cpu: 25m, memory: 64Mi} + limits: {memory: 192Mi} + webhook: + resources: + requests: {cpu: 25m, memory: 64Mi} + limits: {memory: 192Mi} + aggregatedApiServer: + resources: + requests: {cpu: 25m, memory: 64Mi} + limits: {memory: 256Mi} + kubeControllerManager: + resources: + requests: {cpu: 25m, memory: 64Mi} + limits: {memory: 256Mi} + etcd: + internal: + resources: + requests: {cpu: 50m, memory: 128Mi} + limits: {memory: 384Mi} diff --git a/config/multiplane/karmada/kustomization.yaml b/config/multiplane/karmada/kustomization.yaml new file mode 100644 index 00000000..4f8395db --- /dev/null +++ b/config/multiplane/karmada/kustomization.yaml @@ -0,0 +1,4 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - karmada.yaml diff --git a/config/multiplane/kro/kro.yaml b/config/multiplane/kro/kro.yaml new file mode 100644 index 00000000..082b3b9d --- /dev/null +++ b/config/multiplane/kro/kro.yaml @@ -0,0 +1,72 @@ +# kro v0.9.4 on the selected cell from its official OCI chart, pinned by +# manifest digest (chart layer SHA-256 ceeb6307...; image by digest below). +apiVersion: v1 +kind: Namespace +metadata: {name: kro-system} +--- +apiVersion: source.toolkit.fluxcd.io/v1 +kind: OCIRepository +metadata: + name: kro-chart + namespace: flux-system +spec: + interval: 1h + url: oci://registry.k8s.io/kro/charts/kro + ref: + digest: sha256:4e8de4d34b7e2c3cede958e140e26cd6d34a377062e63caf355a636d2bf4a67c + layerSelector: + mediaType: application/vnd.cncf.helm.chart.content.v1.tar+gzip + operation: copy +--- +apiVersion: helm.toolkit.fluxcd.io/v2 +kind: HelmRelease +metadata: + name: kro + namespace: flux-system +spec: + interval: 30m + timeout: 5m + releaseName: kro + targetNamespace: kro-system + storageNamespace: kro-system + chartRef: {kind: OCIRepository, name: kro-chart} + install: + crds: Create + remediation: {retries: 3} + upgrade: + # Never replace kro CRDs implicitly; a CRD change is a reviewed upgrade. + crds: Skip + remediation: {retries: 3, strategy: rollback} + # kro holds no durable state: helm-controller corrects drift in its objects. + driftDetection: {mode: enabled} + # The chart's static controller role grants cluster-wide ConfigMap + # read/write, which kro v0.9.4 never uses (leader election uses Leases). + # Remove it. The test op makes a changed chart fail the release instead of + # silently removing another rule. + postRenderers: + - kustomize: + patches: + - target: {kind: ClusterRole, name: "kro:controller:static"} + patch: |- + - op: test + path: /rules/7 + value: {apiGroups: [""], resources: [configmaps], verbs: [get, list, watch, create, update, patch, delete]} + - op: remove + path: /rules/7 + values: + image: + tag: v0.9.4@sha256:eaf9fbaddd9d7f6cf400a8d47ab066b14cbef22b92a79be7bbdc7b3673376fb9 + rbac: + # Minimal controller role plus the aggregated fleet-site-kro ClusterRole. + mode: aggregation + deployment: + resources: + requests: {cpu: 50m, memory: 64Mi} + limits: {memory: 256Mi} + config: + enableLeaderElection: true + logLevel: info + rgd: + # Default per-dimension limit is 10; the acceptance delivers up to + # about 8 handoffs, including injected delivery faults. + maxCollectionDimensionSize: 64 diff --git a/config/multiplane/kro/kustomization.yaml b/config/multiplane/kro/kustomization.yaml new file mode 100644 index 00000000..be57d832 --- /dev/null +++ b/config/multiplane/kro/kustomization.yaml @@ -0,0 +1,4 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - kro.yaml diff --git a/config/multiplane/milo/base/kustomization.yaml b/config/multiplane/milo/base/kustomization.yaml new file mode 100644 index 00000000..c771d7e5 --- /dev/null +++ b/config/multiplane/milo/base/kustomization.yaml @@ -0,0 +1,4 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - milo.yaml diff --git a/config/multiplane/milo/base/milo.yaml b/config/multiplane/milo/base/milo.yaml new file mode 100644 index 00000000..0610c3e5 --- /dev/null +++ b/config/multiplane/milo/base/milo.yaml @@ -0,0 +1,112 @@ +# One independent Milo project API process and its own etcd. Each overlay +# places this in its own namespace, with its own PVC and NodePort. The +# milo-apiserver-private Secret (static tokens and a self-signed serving key) +# is a local credential seam written by bootstrap; it is never in the source. +apiVersion: v1 +kind: Service +metadata: {name: milo-etcd} +spec: + clusterIP: None + selector: {app.kubernetes.io/name: milo-etcd} + ports: + - {name: client, port: 2379, targetPort: 2379} +--- +apiVersion: apps/v1 +kind: StatefulSet +metadata: {name: milo-etcd} +spec: + serviceName: milo-etcd + replicas: 1 + # Project storage outlives the Pod and the StatefulSet. + persistentVolumeClaimRetentionPolicy: {whenDeleted: Retain, whenScaled: Retain} + selector: + matchLabels: {app.kubernetes.io/name: milo-etcd} + template: + metadata: + labels: {app.kubernetes.io/name: milo-etcd} + spec: + automountServiceAccountToken: false + containers: + - name: etcd + image: registry.k8s.io/etcd:3.5.16-0@sha256:c6a9d11cc5c04b114ccdef39a9265eeef818e3d02f5359be035ae784097fdec5 + command: [/usr/local/bin/etcd] + args: + - --name=milo-etcd-0 + - --data-dir=/var/lib/etcd/data + - --listen-client-urls=http://0.0.0.0:2379 + - --advertise-client-urls=http://milo-etcd-0.milo-etcd:2379 + ports: + - {name: client, containerPort: 2379} + resources: + requests: {cpu: 25m, memory: 48Mi} + limits: {memory: 128Mi} + volumeMounts: + - {name: data, mountPath: /var/lib/etcd} + volumeClaimTemplates: + - metadata: {name: data} + spec: + accessModes: [ReadWriteOnce] + resources: {requests: {storage: 1Gi}} +--- +apiVersion: v1 +kind: Service +metadata: {name: milo-apiserver} +spec: + type: NodePort + selector: {app.kubernetes.io/name: milo-apiserver} + ports: + - {name: https, port: 6443, targetPort: 6443, nodePort: 30440} +--- +apiVersion: apps/v1 +kind: Deployment +metadata: {name: milo-apiserver} +spec: + # Fault injection suspends this namespace's Kustomization before scaling; + # otherwise Flux restores this value. + replicas: 1 + strategy: {type: Recreate} + selector: + matchLabels: {app.kubernetes.io/name: milo-apiserver} + template: + metadata: + labels: {app.kubernetes.io/name: milo-apiserver} + spec: + automountServiceAccountToken: false + enableServiceLinks: false + containers: + - name: apiserver + # Milo v0.32.5 (go.mod pin), native arm64 image. + image: ghcr.io/milo-os/milo@sha256:ec90618ecc723d6e175fbf49bc14292fd930be3e0251acb161c1166e6224279f + args: + - apiserver + - --etcd-servers=http://milo-etcd-0.milo-etcd:2379 + - --etcd-prefix=/registry + - --authorization-mode=RBAC + - --token-auth-file=/private/tokens.csv + - --tls-cert-file=/private/tls.crt + - --tls-private-key-file=/private/tls.key + - --service-account-key-file=/private/tls.crt + - --service-account-signing-key-file=/private/tls.key + - --service-account-issuer=https://fleet-local.invalid + - --client-ca-file=/private/tls.crt + - --secure-port=6443 + - --bind-address=0.0.0.0 + - --anonymous-auth=false + - --v=0 + ports: + - {name: https, containerPort: 6443} + readinessProbe: + tcpSocket: {port: 6443} + periodSeconds: 5 + securityContext: + runAsUser: 0 + allowPrivilegeEscalation: false + capabilities: {drop: [ALL]} + resources: + requests: {cpu: 100m, memory: 192Mi} + limits: {memory: 384Mi} + volumeMounts: + - {name: private, mountPath: /private, readOnly: true} + volumes: + - name: private + secret: {secretName: milo-apiserver-private, defaultMode: 0400} diff --git a/config/multiplane/milo/consumer-a/kustomization.yaml b/config/multiplane/milo/consumer-a/kustomization.yaml new file mode 100644 index 00000000..3a381d3e --- /dev/null +++ b/config/multiplane/milo/consumer-a/kustomization.yaml @@ -0,0 +1,13 @@ +# Milo project API "consumer-a": its own process, etcd, PVC and NodePort. +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +namespace: milo-consumer-a +resources: + - namespace.yaml + - ../base +patches: + - target: {kind: Service, name: milo-apiserver} + patch: |- + - op: replace + path: /spec/ports/0/nodePort + value: 30442 diff --git a/config/multiplane/milo/consumer-a/namespace.yaml b/config/multiplane/milo/consumer-a/namespace.yaml new file mode 100644 index 00000000..60b21ec3 --- /dev/null +++ b/config/multiplane/milo/consumer-a/namespace.yaml @@ -0,0 +1,7 @@ +apiVersion: v1 +kind: Namespace +metadata: + name: milo-consumer-a + annotations: + # Holds this project's etcd volume. Never garbage-collect it. + kustomize.toolkit.fluxcd.io/prune: disabled diff --git a/config/multiplane/milo/consumer-b/kustomization.yaml b/config/multiplane/milo/consumer-b/kustomization.yaml new file mode 100644 index 00000000..5c1e727f --- /dev/null +++ b/config/multiplane/milo/consumer-b/kustomization.yaml @@ -0,0 +1,13 @@ +# Milo project API "consumer-b": its own process, etcd, PVC and NodePort. +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +namespace: milo-consumer-b +resources: + - namespace.yaml + - ../base +patches: + - target: {kind: Service, name: milo-apiserver} + patch: |- + - op: replace + path: /spec/ports/0/nodePort + value: 30443 diff --git a/config/multiplane/milo/consumer-b/namespace.yaml b/config/multiplane/milo/consumer-b/namespace.yaml new file mode 100644 index 00000000..2baff5c4 --- /dev/null +++ b/config/multiplane/milo/consumer-b/namespace.yaml @@ -0,0 +1,7 @@ +apiVersion: v1 +kind: Namespace +metadata: + name: milo-consumer-b + annotations: + # Holds this project's etcd volume. Never garbage-collect it. + kustomize.toolkit.fluxcd.io/prune: disabled diff --git a/config/multiplane/milo/provider/kustomization.yaml b/config/multiplane/milo/provider/kustomization.yaml new file mode 100644 index 00000000..64abfc8f --- /dev/null +++ b/config/multiplane/milo/provider/kustomization.yaml @@ -0,0 +1,13 @@ +# Milo project API "provider": its own process, etcd, PVC and NodePort. +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +namespace: milo-provider +resources: + - namespace.yaml + - ../base +patches: + - target: {kind: Service, name: milo-apiserver} + patch: |- + - op: replace + path: /spec/ports/0/nodePort + value: 30441 diff --git a/config/multiplane/milo/provider/namespace.yaml b/config/multiplane/milo/provider/namespace.yaml new file mode 100644 index 00000000..56638df3 --- /dev/null +++ b/config/multiplane/milo/provider/namespace.yaml @@ -0,0 +1,7 @@ +apiVersion: v1 +kind: Namespace +metadata: + name: milo-provider + annotations: + # Holds this project's etcd volume. Never garbage-collect it. + kustomize.toolkit.fluxcd.io/prune: disabled diff --git a/config/site/base/kro.yaml b/config/site/base/kro.yaml new file mode 100644 index 00000000..a6d759d7 --- /dev/null +++ b/config/site/base/kro.yaml @@ -0,0 +1,178 @@ +# kro's grant for the handoff dispatcher graph. kro creates only per-operation +# worker objects; the shared site services, their Service and the journal +# volume are Flux-owned and kro may only read them. +# +# Reads are cluster-wide because kro v0.9.4 watches every kind it manages or +# references with cluster-wide metadata informers. Writes are namespaced: +# Jobs and ServiceAccounts in fleet-site, Roles and RoleBindings in +# fleet-coordination. kro holds no Deployment, Service, volume, ConfigMap or +# Secret write and no handoff spec or status write. To create a per-operation +# Role granting get on one handoff, kro itself must hold that get permission. +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: fleet-site-kro + # Aggregated into the kro controller ClusterRole (chart rbac.mode=aggregation). + labels: {rbac.kro.run/aggregate-to-controller: "true"} +rules: + - apiGroups: [site.fleet.datumapis.com] + resources: [handoffdispatchers, handoffdispatchers/status, handoffdispatchers/finalizers] + verbs: [get, list, watch, create, update, patch, delete] + - apiGroups: [coordination.fleet.datumapis.com] + resources: [machineallocationhandoffs] + verbs: [get, list, watch] + - apiGroups: [""] + resources: [persistentvolumeclaims, services, serviceaccounts] + verbs: [get, list, watch] + - apiGroups: [apps] + resources: [deployments] + verbs: [get, list, watch] + - apiGroups: [batch] + resources: [jobs] + verbs: [get, list, watch] + - apiGroups: [rbac.authorization.k8s.io] + resources: [roles, rolebindings] + verbs: [get, list, watch] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: {name: fleet-site-kro-workers, namespace: fleet-site} +rules: + - apiGroups: [batch] + resources: [jobs] + verbs: [create, update, patch, delete] + - apiGroups: [""] + resources: [serviceaccounts] + verbs: [create, update, patch, delete] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: {name: fleet-site-kro-workers, namespace: fleet-site} +subjects: + - {kind: ServiceAccount, name: kro, namespace: kro-system} +roleRef: {apiGroup: rbac.authorization.k8s.io, kind: Role, name: fleet-site-kro-workers} +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: {name: fleet-site-kro-worker-rbac, namespace: fleet-coordination} +rules: + - apiGroups: [rbac.authorization.k8s.io] + resources: [roles, rolebindings] + verbs: [create, update, patch, delete] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: {name: fleet-site-kro-worker-rbac, namespace: fleet-coordination} +subjects: + - {kind: ServiceAccount, name: kro, namespace: kro-system} +roleRef: {apiGroup: rbac.authorization.k8s.io, kind: Role, name: fleet-site-kro-worker-rbac} +--- +# RBAC alone would still let a graph revision create any Job in fleet-site, +# including one that runs as the observer (the status writer) or as a +# privileged container. These policies bind kro's writes to the per-operation +# shape: w- names, the matching ServiceAccount, the site image the +# shared services run (parameter written by the services layer), no privilege, +# no host namespaces and no volume other than the journal claim and emptyDir. +# They apply only to kro's own requests; nothing else in the cluster is gated. +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicy +metadata: {name: fleet-site-kro-worker-jobs} +spec: + failurePolicy: Fail + paramKind: {apiVersion: v1, kind: ConfigMap} + matchConstraints: + namespaceSelector: + matchLabels: {kubernetes.io/metadata.name: fleet-site} + resourceRules: + - {apiGroups: [batch], apiVersions: ["*"], resources: [jobs], operations: [CREATE, UPDATE]} + matchConditions: + - name: kro-controller + expression: "request.userInfo.username == 'system:serviceaccount:kro-system:kro'" + variables: + - name: pod + expression: object.spec.template.spec + - name: handoff + expression: "has(object.metadata.labels) && 'fleet.datumapis.com/handoff' in object.metadata.labels ? object.metadata.labels['fleet.datumapis.com/handoff'] : ''" + validations: + - expression: "variables.handoff.startsWith('op-') && object.metadata.name == 'w-' + variables.handoff" + message: a worker Job must be named w- and labelled with that handoff + - expression: "has(variables.pod.serviceAccountName) && variables.pod.serviceAccountName == object.metadata.name" + message: a worker Job must run as its own per-operation ServiceAccount + - expression: >- + size(variables.pod.containers) == 1 && + (!has(variables.pod.initContainers) || size(variables.pod.initContainers) == 0) && + variables.pod.containers.all(c, c.image == params.data.image) + message: a worker Job must run one container from the site image the shared services run + - expression: >- + variables.pod.containers.all(c, has(c.securityContext) && + (!has(c.securityContext.privileged) || !c.securityContext.privileged) && + has(c.securityContext.allowPrivilegeEscalation) && !c.securityContext.allowPrivilegeEscalation && + has(c.securityContext.capabilities) && has(c.securityContext.capabilities.drop) && + 'ALL' in c.securityContext.capabilities.drop && + (!has(c.securityContext.capabilities.add) || size(c.securityContext.capabilities.add) == 0)) + message: a worker Job must be unprivileged with all capabilities dropped + - expression: >- + !(has(variables.pod.hostNetwork) && variables.pod.hostNetwork) && + !(has(variables.pod.hostPID) && variables.pod.hostPID) && + !(has(variables.pod.hostIPC) && variables.pod.hostIPC) + message: a worker Job must not use host namespaces + - expression: >- + !has(variables.pod.volumes) || variables.pod.volumes.all(v, + (has(v.persistentVolumeClaim) && v.persistentVolumeClaim.claimName == 'fleet-site-state') || has(v.emptyDir)) + message: a worker Job may mount only the site journal claim and emptyDir +--- +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicyBinding +metadata: {name: fleet-site-kro-worker-jobs} +spec: + policyName: fleet-site-kro-worker-jobs + validationActions: [Deny] + paramRef: + name: fleet-site-worker-policy + namespace: fleet-site + parameterNotFoundAction: Deny +--- +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicy +metadata: {name: fleet-site-kro-worker-identity} +spec: + failurePolicy: Fail + matchConstraints: + namespaceSelector: + matchExpressions: + - {key: kubernetes.io/metadata.name, operator: In, values: [fleet-site, fleet-coordination]} + resourceRules: + - {apiGroups: [""], apiVersions: ["*"], resources: [serviceaccounts], operations: [CREATE, UPDATE]} + - {apiGroups: [rbac.authorization.k8s.io], apiVersions: ["*"], resources: [roles, rolebindings], operations: [CREATE, UPDATE]} + matchConditions: + - name: kro-controller + expression: "request.userInfo.username == 'system:serviceaccount:kro-system:kro'" + variables: + - name: kind + expression: request.resource.resource + - name: handoff + expression: "object.metadata.name.startsWith('w-op-') ? object.metadata.name.substring(2) : ''" + validations: + - expression: "variables.handoff != ''" + message: kro may create only per-operation identities named w- + - expression: "variables.kind != 'serviceaccounts' || request.namespace == 'fleet-site'" + message: worker ServiceAccounts live in fleet-site + - expression: >- + variables.kind != 'roles' || (has(object.rules) && size(object.rules) == 1 && + object.rules.all(r, r.apiGroups == ['coordination.fleet.datumapis.com'] && + r.resources == ['machineallocationhandoffs'] && r.verbs == ['get'] && + has(r.resourceNames) && r.resourceNames == [variables.handoff])) + message: a worker Role may grant only get on its own handoff + - expression: >- + variables.kind != 'rolebindings' || (object.roleRef.kind == 'Role' && + object.roleRef.name == object.metadata.name && has(object.subjects) && size(object.subjects) == 1 && + object.subjects[0].kind == 'ServiceAccount' && object.subjects[0].name == object.metadata.name && + object.subjects[0].namespace == 'fleet-site') + message: a worker RoleBinding may bind only its own Role to its own ServiceAccount +--- +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicyBinding +metadata: {name: fleet-site-kro-worker-identity} +spec: + policyName: fleet-site-kro-worker-identity + validationActions: [Deny] diff --git a/config/site/base/kustomization.yaml b/config/site/base/kustomization.yaml new file mode 100644 index 00000000..064bf927 --- /dev/null +++ b/config/site/base/kustomization.yaml @@ -0,0 +1,6 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - site.yaml + - kro.yaml + - reconcilers.yaml diff --git a/config/site/base/reconcilers.yaml b/config/site/base/reconcilers.yaml new file mode 100644 index 00000000..c95b5a19 --- /dev/null +++ b/config/site/base/reconcilers.yaml @@ -0,0 +1,81 @@ +# Scoped Flux identities for the site layers, created with the site namespace. +# kustomize-controller impersonates these ServiceAccounts, so each layer can +# write only its own kinds: +# fleet-site-services Deployments, the boot Service and the worker-policy +# ConfigMap in fleet-site +# fleet-site-graph ResourceGraphDefinitions +# fleet-site-dispatch HandoffDispatchers in fleet-site +# None of them can write Jobs, volumes, RBAC, admission policy or handoffs. +# Source authors remain trusted: the services layer chooses the privileged +# runtime image, the graph chooses the worker template within the admission +# policy, and the same source owns this admin-applied base. kro remains the +# sole writer of the per-operation objects the graph generates. +apiVersion: v1 +kind: ServiceAccount +metadata: {name: fleet-site-services-reconciler, namespace: flux-system} +automountServiceAccountToken: false +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: {name: fleet-site-services-reconciler, namespace: fleet-site} +rules: + - apiGroups: [apps] + resources: [deployments] + verbs: [get, list, watch, create, update, patch, delete] + - apiGroups: [""] + resources: [services, configmaps] + verbs: [get, list, watch, create, update, patch, delete] + # Read-only, for kstatus health checks of the Deployments. + - apiGroups: [apps] + resources: [replicasets] + verbs: [get, list, watch] + - apiGroups: [""] + resources: [pods] + verbs: [get, list, watch] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: {name: fleet-site-services-reconciler, namespace: fleet-site} +subjects: + - {kind: ServiceAccount, name: fleet-site-services-reconciler, namespace: flux-system} +roleRef: {apiGroup: rbac.authorization.k8s.io, kind: Role, name: fleet-site-services-reconciler} +--- +apiVersion: v1 +kind: ServiceAccount +metadata: {name: fleet-site-graph-reconciler, namespace: flux-system} +automountServiceAccountToken: false +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: {name: fleet-site-graph-reconciler} +rules: + - apiGroups: [kro.run] + resources: [resourcegraphdefinitions] + verbs: [get, list, watch, create, update, patch, delete] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: {name: fleet-site-graph-reconciler} +subjects: + - {kind: ServiceAccount, name: fleet-site-graph-reconciler, namespace: flux-system} +roleRef: {apiGroup: rbac.authorization.k8s.io, kind: ClusterRole, name: fleet-site-graph-reconciler} +--- +apiVersion: v1 +kind: ServiceAccount +metadata: {name: fleet-site-dispatch-reconciler, namespace: flux-system} +automountServiceAccountToken: false +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: {name: fleet-site-dispatch-reconciler, namespace: fleet-site} +rules: + - apiGroups: [site.fleet.datumapis.com] + resources: [handoffdispatchers] + verbs: [get, list, watch, create, update, patch, delete] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: {name: fleet-site-dispatch-reconciler, namespace: fleet-site} +subjects: + - {kind: ServiceAccount, name: fleet-site-dispatch-reconciler, namespace: flux-system} +roleRef: {apiGroup: rbac.authorization.k8s.io, kind: Role, name: fleet-site-dispatch-reconciler} diff --git a/config/site/base/site.yaml b/config/site/base/site.yaml new file mode 100644 index 00000000..38491165 --- /dev/null +++ b/config/site/base/site.yaml @@ -0,0 +1,78 @@ +# Experimental Kubernetes site for one selected local cell. Reconciled by the +# cell's Flux after the MachineAllocationHandoff CRD and fleet-coordination +# namespace exist. See docs/operations/site-execution.md and gitops.md. +apiVersion: v1 +kind: Namespace +metadata: + name: fleet-site + annotations: + # Deleting the namespace would delete the journal volume claim. + kustomize.toolkit.fluxcd.io/prune: disabled +--- +# Retain: deleting the claim never deletes the provider journal, disks or boot +# evidence. A journal reset would let replayed handoffs be admitted as new. +apiVersion: storage.k8s.io/v1 +kind: StorageClass +metadata: + name: fleet-site-retain + annotations: + # StorageClass parameters are immutable; create once, never prune. + kustomize.toolkit.fluxcd.io/prune: disabled + kustomize.toolkit.fluxcd.io/ssa: IfNotPresent +provisioner: rancher.io/local-path +reclaimPolicy: Retain +volumeBindingMode: WaitForFirstConsumer +--- +# The durable site volume belongs to this layer alone. The shared services +# mount it and the dispatcher graph only references it, so neither the services +# layer nor any graph or instance lifecycle can delete it. Flux creates it once +# and never updates or prunes it: removing it from the source, a controller +# restart or a reconcile cannot replace the journal. +apiVersion: v1 +kind: PersistentVolumeClaim +metadata: + name: fleet-site-state + namespace: fleet-site + annotations: + kustomize.toolkit.fluxcd.io/prune: disabled + kustomize.toolkit.fluxcd.io/ssa: IfNotPresent +spec: + storageClassName: fleet-site-retain + accessModes: [ReadWriteOnce] + resources: {requests: {storage: 8Gi}} +--- +# Identities of the shared site services (config/site/services). The runtime +# and boot service hold no API token. +apiVersion: v1 +kind: ServiceAccount +metadata: {name: fleet-site-runtime, namespace: fleet-site} +automountServiceAccountToken: false +--- +apiVersion: v1 +kind: ServiceAccount +metadata: {name: fleet-site-boot, namespace: fleet-site} +automountServiceAccountToken: false +--- +# The observer is the only writer of handoff status on this cell. It holds no +# create/delete or spec-write permission and no Secret access. +apiVersion: v1 +kind: ServiceAccount +metadata: {name: fleet-site-observer, namespace: fleet-site} +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: {name: fleet-site-observer, namespace: fleet-coordination} +rules: + - apiGroups: [coordination.fleet.datumapis.com] + resources: [machineallocationhandoffs] + verbs: [get, list, watch] + - apiGroups: [coordination.fleet.datumapis.com] + resources: [machineallocationhandoffs/status] + verbs: [get, update, patch] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: {name: fleet-site-observer, namespace: fleet-coordination} +subjects: + - {kind: ServiceAccount, name: fleet-site-observer, namespace: fleet-site} +roleRef: {apiGroup: rbac.authorization.k8s.io, kind: Role, name: fleet-site-observer} diff --git a/config/site/graph/kustomization.yaml b/config/site/graph/kustomization.yaml new file mode 100644 index 00000000..24ef86fe --- /dev/null +++ b/config/site/graph/kustomization.yaml @@ -0,0 +1,4 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - rgd.yaml diff --git a/config/site/graph/rgd.yaml b/config/site/graph/rgd.yaml new file mode 100644 index 00000000..d7f6e080 --- /dev/null +++ b/config/site/graph/rgd.yaml @@ -0,0 +1,223 @@ +# kro ResourceGraphDefinition for one selected local cell. For each delivered +# MachineAllocationHandoff it creates one bounded worker Job with its own +# ServiceAccount, Role and RoleBinding, and nothing else. The shared site +# services, their boot Service and the journal volume are owned by the cell's +# Flux (config/site/services, config/site/base); this graph only references +# them, so deleting the instance or the graph cannot delete them. +# +# Every resource here is derived execution state: none of it allocates, admits, +# completes or releases anything. Management trusts only Karmada-reflected, +# journal-derived handoff status. +apiVersion: kro.run/v1alpha1 +kind: ResourceGraphDefinition +metadata: + name: fleet-handoff-dispatcher + annotations: + # Deleting the graph orphans the dispatcher; retiring it is a manual procedure. + kustomize.toolkit.fluxcd.io/prune: disabled +spec: + schema: + apiVersion: v1alpha1 + kind: HandoffDispatcher + group: site.fleet.datumapis.com + spec: + cell: string | required=true + scopedAsset: string | required=true + # Workers are created only after dispatch is enabled. The acceptance uses + # this to prove delivery and retention before any effect can start. + dispatch: boolean | default=false + status: + bootOrigin: ${"http://" + bootService.spec.clusterIP + ":8080"} + workerImage: ${hypervisor.spec.template.spec.containers[0].image} + runtimeAvailable: ${hypervisor.status.?availableReplicas.orValue(0)} + bootAvailable: ${boot.status.?availableReplicas.orValue(0)} + observerAvailable: ${observer.status.?availableReplicas.orValue(0)} + deliveredHandoffs: ${size(handoffs)} + resources: + # Flux-owned site infrastructure, referenced and never managed by kro. A + # reference that is missing or not ready blocks new worker objects and + # disables pruning; existing Jobs are left alone. + - id: state + externalRef: + apiVersion: v1 + kind: PersistentVolumeClaim + metadata: + name: fleet-site-state + - id: bootService + readyWhen: + - ${bootService.spec.?clusterIP.orValue("") != ""} + externalRef: + apiVersion: v1 + kind: Service + metadata: + name: fleet-site-boot + - id: hypervisor + readyWhen: + - ${hypervisor.status.?availableReplicas.orValue(0) == 1} + externalRef: + apiVersion: apps/v1 + kind: Deployment + metadata: + name: fleet-site-runtime + - id: boot + readyWhen: + - ${boot.status.?availableReplicas.orValue(0) == 1} + externalRef: + apiVersion: apps/v1 + kind: Deployment + metadata: + name: fleet-site-boot + - id: observer + readyWhen: + - ${observer.status.?availableReplicas.orValue(0) == 1} + externalRef: + apiVersion: apps/v1 + kind: Deployment + metadata: + name: fleet-site-observer + # Delivered intent for this cell, watched by kro. The workers re-validate + # the cell, name and exact request; selection here is not authority. + - id: handoffs + externalRef: + apiVersion: coordination.fleet.datumapis.com/v1alpha1 + kind: MachineAllocationHandoff + metadata: + namespace: fleet-coordination + selector: + matchExpressions: + - key: coordination.fleet.datumapis.com/cell + operator: In + values: ["${schema.spec.cell}"] + # Per-operation identity and policy: each worker may read exactly its own + # handoff and nothing else. It has no status, list or Secret permission. + # The fleet-site-kro-worker-identity admission policy enforces this shape. + - id: workerAccounts + includeWhen: + - ${schema.spec.dispatch} + forEach: + - handoff: ${handoffs} + template: + apiVersion: v1 + kind: ServiceAccount + metadata: + name: ${"w-" + handoff.metadata.name} + labels: {app.kubernetes.io/name: fleet-site-worker} + - id: workerRoles + includeWhen: + - ${schema.spec.dispatch} + forEach: + - handoff: ${handoffs} + template: + apiVersion: rbac.authorization.k8s.io/v1 + kind: Role + metadata: + name: ${"w-" + handoff.metadata.name} + namespace: fleet-coordination + labels: {app.kubernetes.io/name: fleet-site-worker} + rules: + - apiGroups: [coordination.fleet.datumapis.com] + resources: [machineallocationhandoffs] + resourceNames: ["${handoff.metadata.name}"] + verbs: [get] + - id: workerBindings + includeWhen: + - ${schema.spec.dispatch} + forEach: + - handoff: ${handoffs} + template: + apiVersion: rbac.authorization.k8s.io/v1 + kind: RoleBinding + metadata: + name: ${"w-" + handoff.metadata.name} + namespace: fleet-coordination + labels: {app.kubernetes.io/name: fleet-site-worker} + annotations: + fleet.datumapis.com/accounts: ${string(size(workerAccounts))} + fleet.datumapis.com/roles: ${string(size(workerRoles))} + subjects: + - kind: ServiceAccount + name: ${"w-" + handoff.metadata.name} + namespace: fleet-site + roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: ${"w-" + handoff.metadata.name} + # One bounded Job per delivered operation. The Job controller retries and + # replaces Pods; every Pod replays the same retained operation from the + # journal. Job completion is not readiness: only the observer publishes, + # and only management validates the reflected result. The Job runs the + # runtime's image (the fleet-site-kro-worker-jobs admission policy also + # requires it) and reaches the runtime only through its libvirt socket. + - id: workers + includeWhen: + - ${schema.spec.dispatch} + forEach: + - handoff: ${handoffs} + template: + apiVersion: batch/v1 + kind: Job + metadata: + name: ${"w-" + handoff.metadata.name} + labels: + app.kubernetes.io/name: fleet-site-worker + fleet.datumapis.com/handoff: ${handoff.metadata.name} + annotations: + # Dependency edges: workers start only after the Flux-owned runtime, + # boot service and observer are ready and this operation's RBAC exists. + fleet.datumapis.com/runtime: ${hypervisor.metadata.name} + fleet.datumapis.com/boot: ${boot.metadata.name} + fleet.datumapis.com/observer: ${observer.metadata.name} + fleet.datumapis.com/bindings: ${string(size(workerBindings))} + spec: + backoffLimit: 6 + activeDeadlineSeconds: 3600 + # A replacement Pod starts only after the previous Pod is terminal, + # so two workers for one operation never overlap; the journal lock + # is the second guard. + podReplacementPolicy: Failed + podFailurePolicy: + rules: + # Exit 65: fenced, conflicting or invalid authority. Retrying + # cannot change it; fail without another attempt. + - action: FailJob + onExitCodes: {containerName: worker, operator: In, values: [65]} + - action: Ignore + onPodConditions: [{type: DisruptionTarget}] + template: + metadata: + labels: + app.kubernetes.io/name: fleet-site-worker + fleet.datumapis.com/handoff: ${handoff.metadata.name} + spec: + restartPolicy: Never + serviceAccountName: ${"w-" + handoff.metadata.name} + terminationGracePeriodSeconds: 10 + containers: + - name: worker + image: ${hypervisor.spec.template.spec.containers[0].image} + imagePullPolicy: IfNotPresent + command: [fleet-multiplane, site-worker, --handoff, "${handoff.metadata.name}", --cell, "${schema.spec.cell}", --scoped-asset, "${schema.spec.scopedAsset}"] + env: + - {name: FLEET_LOCAL_VM_ACCEL, value: tcg} + - {name: FLEET_BOOT_ORIGIN, value: "${'http://' + bootService.spec.clusterIP + ':8080'}"} + - {name: FLEET_BOOT_EVIDENCE, value: /var/lib/fleet-boot} + - {name: FLEET_LIBVIRT_URI, value: "qemu:///system?socket=/run/fleet-libvirt/libvirt-sock"} + - {name: HOME, value: /tmp} + securityContext: + runAsUser: 0 + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: {drop: [ALL]} + resources: + requests: {cpu: 50m, memory: 32Mi} + limits: {memory: 192Mi} + volumeMounts: + - {name: state, mountPath: /var/lib/fleet-local, subPath: journal} + - {name: state, mountPath: /var/lib/fleet-boot, subPath: boot-evidence, readOnly: true} + - {name: state, mountPath: /run/fleet-libvirt, subPath: libvirt-socket} + - {name: tmp, mountPath: /tmp} + volumes: + - name: state + persistentVolumeClaim: {claimName: "${state.metadata.name}"} + - name: tmp + emptyDir: {} diff --git a/config/site/instance/dispatcher.yaml b/config/site/instance/dispatcher.yaml new file mode 100644 index 00000000..ae051632 --- /dev/null +++ b/config/site/instance/dispatcher.yaml @@ -0,0 +1,19 @@ +# The one HandoffDispatcher instance for the selected cell. Variables come from +# the environment's fleet-environment ConfigMap through Flux postBuild +# substitution; dispatch is enabled only by a new source revision. The +# instance controls only per-operation worker objects; the shared site +# services it depends on are Flux-owned (config/site/services). +apiVersion: site.fleet.datumapis.com/v1alpha1 +kind: HandoffDispatcher +metadata: + name: dispatcher + namespace: fleet-site + annotations: + # Deleting the instance prunes worker Jobs and their RBAC, which is not + # cancellation. Shared services and the journal are unaffected. + kustomize.toolkit.fluxcd.io/prune: disabled + fleet.datumapis.com/source-marker: "${FLEET_SOURCE_MARKER}" +spec: + cell: "${FLEET_CELL}" + scopedAsset: "${FLEET_SCOPED_ASSET}" + dispatch: ${FLEET_SITE_DISPATCH} diff --git a/config/site/instance/kustomization.yaml b/config/site/instance/kustomization.yaml new file mode 100644 index 00000000..11f41084 --- /dev/null +++ b/config/site/instance/kustomization.yaml @@ -0,0 +1,4 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - dispatcher.yaml diff --git a/config/site/services/kustomization.yaml b/config/site/services/kustomization.yaml new file mode 100644 index 00000000..ee2822bf --- /dev/null +++ b/config/site/services/kustomization.yaml @@ -0,0 +1,4 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - services.yaml diff --git a/config/site/services/services.yaml b/config/site/services/services.yaml new file mode 100644 index 00000000..2ec7f2cf --- /dev/null +++ b/config/site/services/services.yaml @@ -0,0 +1,161 @@ +# Shared site services for one selected local cell, owned directly by the +# cell's Flux (Kustomization fleet-site-services, scoped identity). Values come +# from the environment's fleet-environment ConfigMap through postBuild +# substitution. These services are long-lived site infrastructure, not +# operation state: no graph or instance lifecycle creates or deletes them. +# Every revision of this layer is a reviewed change: a runtime rollout stops any +# running guest, which leaves its operation Unknown and capacity occupied. +# +# The boot Service has a fixed ClusterIP from the cluster's static Service range, +# so Flux recreating it after deletion yields the same boot origin that the +# runtime, the boot service and every worker were configured with. +apiVersion: v1 +kind: Service +metadata: + name: fleet-site-boot + namespace: fleet-site +spec: + type: ClusterIP + clusterIP: "${FLEET_BOOT_SERVICE_IP}" + selector: {app.kubernetes.io/name: fleet-site-boot} + ports: + - {name: http, port: 8080, targetPort: 8080, protocol: TCP} +--- +# Admission parameter for kro-created worker Jobs: they must run the same +# digest-pinned image as these services. +apiVersion: v1 +kind: ConfigMap +metadata: + name: fleet-site-worker-policy + namespace: fleet-site +data: + image: "${FLEET_SITE_IMAGE}" +--- +# Hypervisor and provisioning bridge. Only this Pod is privileged; deleting +# it stops any guest, which leaves the operation Unknown, never released. +apiVersion: apps/v1 +kind: Deployment +metadata: + name: fleet-site-runtime + namespace: fleet-site +spec: + replicas: 1 + strategy: {type: Recreate} + selector: + matchLabels: {app.kubernetes.io/name: fleet-site-runtime} + template: + metadata: + labels: {app.kubernetes.io/name: fleet-site-runtime} + spec: + serviceAccountName: fleet-site-runtime + automountServiceAccountToken: false + terminationGracePeriodSeconds: 30 + containers: + - name: libvirt + image: "${FLEET_SITE_IMAGE}" + imagePullPolicy: IfNotPresent + command: [/usr/local/bin/fleet-site-runtime] + env: + - {name: FLEET_LOCAL_VM_ACCEL, value: tcg} + - {name: FLEET_BOOT_IP, value: "${FLEET_BOOT_SERVICE_IP}"} + securityContext: + privileged: true + runAsUser: 0 + resources: + requests: {cpu: 500m, memory: 2560Mi} + limits: {memory: 3Gi} + readinessProbe: + exec: + command: [virsh, --connect, "qemu:///system?socket=/run/fleet-libvirt/libvirt-sock", list, --name] + periodSeconds: 5 + timeoutSeconds: 10 + volumeMounts: + - {name: state, mountPath: /var/lib/fleet-local, subPath: journal} + - {name: state, mountPath: /run/fleet-libvirt, subPath: libvirt-socket} + - {name: state, mountPath: /var/log/libvirt, subPath: libvirt-log} + - {name: state, mountPath: /var/lib/fleet-boot, subPath: boot-evidence, readOnly: true} + volumes: + - name: state + persistentVolumeClaim: {claimName: fleet-site-state} +--- +# Boot service: journal read-only; writes only its own delivery evidence. +apiVersion: apps/v1 +kind: Deployment +metadata: + name: fleet-site-boot + namespace: fleet-site +spec: + replicas: 1 + selector: + matchLabels: {app.kubernetes.io/name: fleet-site-boot} + template: + metadata: + labels: {app.kubernetes.io/name: fleet-site-boot} + spec: + serviceAccountName: fleet-site-boot + automountServiceAccountToken: false + containers: + - name: boot + image: "${FLEET_SITE_IMAGE}" + imagePullPolicy: IfNotPresent + command: [fleet-multiplane, boot-service] + env: + - {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} + ports: + - {name: http, containerPort: 8080} + readinessProbe: + tcpSocket: {port: 8080} + periodSeconds: 5 + securityContext: + runAsUser: 0 + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: {drop: [ALL]} + resources: + requests: {cpu: 20m, memory: 32Mi} + limits: {memory: 128Mi} + volumeMounts: + - {name: state, mountPath: /var/lib/fleet-local, subPath: journal, readOnly: true} + - {name: state, mountPath: /var/lib/fleet-boot, subPath: boot-evidence} + volumes: + - name: state + persistentVolumeClaim: {claimName: fleet-site-state} +--- +# Observer: the only handoff status writer, from the journal only. +apiVersion: apps/v1 +kind: Deployment +metadata: + name: fleet-site-observer + namespace: fleet-site +spec: + replicas: 1 + strategy: {type: Recreate} + selector: + matchLabels: {app.kubernetes.io/name: fleet-site-observer} + template: + metadata: + labels: {app.kubernetes.io/name: fleet-site-observer} + spec: + serviceAccountName: fleet-site-observer + containers: + - name: observer + image: "${FLEET_SITE_IMAGE}" + imagePullPolicy: IfNotPresent + command: [fleet-multiplane, site-observer, --cell, "${FLEET_CELL}", --scoped-asset, "${FLEET_SCOPED_ASSET}", --interval, 10s] + env: + - {name: FLEET_LOCAL_VM_ACCEL, value: tcg} + securityContext: + runAsUser: 0 + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: {drop: [ALL]} + resources: + requests: {cpu: 20m, memory: 32Mi} + limits: {memory: 128Mi} + volumeMounts: + - {name: state, mountPath: /var/lib/fleet-local, subPath: journal, readOnly: true} + volumes: + - name: state + persistentVolumeClaim: {claimName: fleet-site-state} diff --git a/docs/development/README.md b/docs/development/README.md index e9938887..bf94797f 100644 --- a/docs/development/README.md +++ b/docs/development/README.md @@ -23,6 +23,14 @@ An opt-in [local KVM installation harness](../operations/local-vm.md) implements a bounded libvirt executor and guest installer using the same lifecycle library. It uses a disposable Kubernetes API and explicit local authority fixtures; it is not wired into the production manager. +The opt-in [multi-plane acceptance harness](../operations/multiplane.md) composes +that executor with native Milo project APIs and actual Karmada delivery. On the +selected cell it runs as [Flux-owned site Deployments and kro-created per-operation worker Jobs](../operations/site-execution.md). +Each local cluster's [Flux](../operations/gitops.md) installs Milo, Karmada, kro and the shared site services from +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. Production Kustomize roots now package the implemented manager, admission, API, Milo IAM, service, and quota boundaries; packaging is not runtime readiness. diff --git a/docs/enhancements/pxe-installation/README.md b/docs/enhancements/pxe-installation/README.md index faabba4d..97a26a28 100644 --- a/docs/enhancements/pxe-installation/README.md +++ b/docs/enhancements/pxe-installation/README.md @@ -361,11 +361,23 @@ Location implementation may use: - a Deployment or facility-edge DaemonSet for boot scripts and callbacks; - a private execution CRD for the delivered handoff; - Jobs for bounded Redfish, power, verification, and fencing actions; and -- KRO to create and order those local resources. - -Jobs must recover a retained provider operation before retrying. Job completion -does not by itself prove a remote effect. A KRO instance is derived state and -cannot replace the hub handoff, operation journal, or provider fence. +- KRO to create and order the per-operation resources: one bounded Job and its + scoped identity and RBAC for each delivered handoff. + +Long-lived location services, their policies and RBAC, and durable provider state +have one configuration owner: the environment's GitOps writer (Flux), not an +operation graph. An operation graph references them and cannot create, change or +delete them, so its lifecycle cannot remove a shared service or a provider +journal. Jobs must recover a retained provider operation before retrying. Job +completion does not by itself prove a remote effect. A KRO instance is derived +state and cannot replace the hub handoff, operation journal, or provider fence. + +The local multi-plane acceptance implements this pattern for a disposable +libvirt cell with kro v0.9.4. Flux owns the VM runtime Deployment, the boot +Deployment and Service, the journal-only status observer and the retained +journal volume. kro creates only per-handoff RBAC and bounded Jobs. See +[Kubernetes-native site execution](../../operations/site-execution.md). That is +local evidence for the contract above, not hardware qualification. ![Shared installation workflow and mode-specific execution](diagrams/installation-workflows.svg) diff --git a/docs/operations/README.md b/docs/operations/README.md index f29795e1..7443e355 100644 --- a/docs/operations/README.md +++ b/docs/operations/README.md @@ -14,6 +14,7 @@ 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, cleanup, and reuse | [Standalone smoke environment](standalone-smoke.md) | Same-cluster lifecycle behavior with namespaces as project stand-ins | | Install a real OS over firmware PXE into a disposable local VM | [Local VM PXE installation](local-vm.md) | Single-plane real install, disk-only boot, recovery, cleanup and reuse under explicit TCG; 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, 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, cleanup and reuse; every service [installed by per-cluster Flux](gitops.md) from a source built from the checkout; production authority unqualified | | Render deployment bundles and supply environment inputs | [Deployment manifests](../../config/README.md) | Packaging and security boundaries, not runtime readiness | | Run the manager across consuming projects | [Project discovery](../../config/README.md#project-discovery) | Discovery, per-project isolation, departure, role bindings, and readiness | | Exercise Milo-routed synthetic staging | [Synthetic staging configuration](../../config/README.md#environment-owned-inputs) | Restricted synthetic publication and lifecycle behavior, not production authority | diff --git a/docs/operations/gitops.md b/docs/operations/gitops.md new file mode 100644 index 00000000..d0c03849 --- /dev/null +++ b/docs/operations/gitops.md @@ -0,0 +1,304 @@ +# Flux-reconciled local environment + +The [multi-plane acceptance](multiplane.md) installs every long-running service +the way a real environment would: each cluster runs its own Flux, and Flux +reconciles Helm releases and Kustomizations from one OCI source artifact. +That artifact is built from the current checkout, including uncommitted +changes. The harness no longer runs `helm install`, `kind load`, or +`kubectl apply` for any service, and no Milo API runs as a bare Docker container. + +This is an **implemented local composition**. It shows that the manifests, +dependency ordering, ownership and retention policies work under real Flux +controllers. It does not qualify production deployment: the seams are listed +under [what is not production](#what-is-not-production). + +## Ownership + +```text + run registry (registry:3.0.0, plain HTTP on the kind network) + ├── fleet-gitops:local OCI artifact: config/multiplane + config/site + │ + generated environment/ + └── fleet-site@sha256:… site image + ┌───────────────────┬──────────────┴─────────────┐ + platform cluster hub cluster (host) cell cluster + Flux v2.9.6 Flux v2.9.6 Flux v2.9.6 + ├ milo-provider ├ karmada (HelmRelease) ├ fleet-coordination (CRD, ns) + ├ milo-consumer-a ├ fleet-host (custody RBAC) ├ fleet-federation (member identity) + └ milo-consumer-b └ karmada-system/… ├ kro (OCI chart HelmRelease) + ├ fleet-karmada-coordination├ fleet-site-base (ns, Retain PVC, identities, + ├ fleet-karmada-api │ RBAC, kro grants, admission) + └ fleet-karmada-members ├ fleet-site-services (runtime, boot, observer, + (applied to the Karmada API│ boot Service; scoped identity) + through karmada-kubeconfig)├ fleet-site-graph (RGD; scoped identity) + └ fleet-site-dispatch (HandoffDispatcher; scoped) + │ + ▼ + kro: per-operation ServiceAccount, Role, + RoleBinding and worker Job only +``` + +| Surface | Writer | Never written by | +| --- | --- | --- | +| Flux controllers and sync objects (`flux-system`) | Bootstrap once, then each cluster's own Flux (`fleet-cluster` reconciles `environment//flux-system`) | — | +| Milo project API Deployments, etcd StatefulSets, PVCs, Services | Platform Flux (`milo-`) | Harness (it suspends the Kustomization before fault injection) | +| Karmada chart | hub helm-controller (`HelmRelease karmada`) | Harness (suspended during reflection faults) | +| Handoff CRD, management role, interpreter, member `Cluster`, `PropagationPolicy` on the Karmada API | hub kustomize-controller through the chart's `karmada-kubeconfig` | — | +| Private custody namespace and custodian identity (host) | hub Flux (`fleet-host`) | — | +| kro controller | cell helm-controller (`HelmRelease kro`) | — | +| Site namespace, StorageClass, journal PVC, service identities, observer RBAC, kro grants and admission policies | cell Flux (`fleet-site-base`) | kro does not manage these; its delete grants still cover service identities and coordination RBAC (see trust model) | +| Shared runtime, boot and observer Deployments, boot Service, worker-policy parameter | cell Flux as `fleet-site-services-reconciler` | kro (read only; verified by label, inventory and RBAC), harness (drift is injected, repair is Flux's) | +| `ResourceGraphDefinition fleet-handoff-dispatcher` | cell Flux as `fleet-site-graph-reconciler` | — | +| `HandoffDispatcher/dispatcher`, including `dispatch` | cell Flux as `fleet-site-dispatch-reconciler`, from a source revision | Harness (dispatch is a pushed revision; the graph-lifecycle fault suspends the layer first) | +| Per-operation `w-` ServiceAccounts, Roles, RoleBindings and Jobs | kro only, admission-checked | Flux (verified absent from every inventory) | +| `MachineAllocationHandoff` objects and their status | Management/Karmada (intent), site observer (status) | Flux, kro | +| Allocation custody Secrets | Shared lifecycle coordinator | Flux | +| Credentials: Milo static tokens and serving keys, ServiceAccount tokens, Karmada member Secret | Bootstrap credential enrollment | Any source revision | + +Fleet and Karmada stay the operation authority and delivery path. Nothing per +allocation is written to the source: handoffs, Jobs and results never appear +in an artifact or a Flux inventory. + +## Bootstrap boundary + +`hack/multiplane/run.sh` performs only these imperative steps, each a bounded +phase: + +1. **`topology`** (`topology.sh`) creates the run registry and three kind + clusters with memory caps, the cell's registry mirror configuration and + the reversible inotify adjustment. It installs no service. +2. **`site-image-push`** pushes the built site image; the cell pulls it by digest. +3. **`flux-tools`** downloads the Flux v2.9.6 CLI and `install.yaml` and + verifies both against SHA-256 values pinned in `hack/multiplane/flux.py`. +4. **`flux-source`** stages revision 1 and pushes it with + `flux push artifact --reproducible`. +5. **`flux-bootstrap-`** applies that revision's Flux components, + waits for the CRDs, then applies the two sync objects (`OCIRepository + fleet-gitops`, `Kustomization fleet-cluster`). This is what + `flux bootstrap` commits as `gotk-components.yaml` and `gotk-sync.yaml`. The + apply uses kustomize-controller's field manager, so Flux takes these + objects over without a second owner. From then on each cluster's Flux + reconciles its own controllers from the source. +6. **Credential enrollment.** `milo.py` writes each Milo API's + `milo-apiserver-private` Secret into the namespace Flux created. `roles.py` + mints 24-hour tokens for the Flux-created management, custodian and + federation ServiceAccounts, and writes the Karmada member Secret. +7. **Tenant fixture bootstrap.** `milo.py` creates the Milo Projects, + static-token RBAC grants and metal CRDs inside each project API, and the + management CLI seeds catalog fixtures. These are data inside running + services, not service installation, and are labelled synthetic fixtures. + +Everything else is a Flux reconciliation of a pushed revision. + +## Source revisions + +`flux.py stage` copies `config/multiplane` and `config/site` from the +checkout into `/gitops/r`. It stages the verified `install.yaml` +with `config/multiplane/flux/components.yaml`, unchanged, as +`environment/flux-components`, and adds a generated `environment/` +per cluster. The environment holds the +sync objects and a non-secret `fleet-environment` ConfigMap: cell name, +member endpoint, scoped asset, digest-pinned site image, dispatch flag and a +revision marker. Before pushing, it refuses any file that contains a `Secret` +manifest, a private key, a token-shaped field, or any credential retained in +the run state. It also requires every environment to render with `kustomize`. +The per-file SHA-256 list is copied to `evidence/gitops-r.SHA256SUMS`. +`flux-revisions.json` records the digest, Git HEAD and dirty-checkout content +hash. + +| Revision | Purpose | +| --- | --- | +| r1 | Platform services: Milo, Karmada, host RBAC, Karmada API configuration, kro, site base and graph | +| r2 | Adds the shared site services and the `HandoffDispatcher` instance with `dispatch: false` once the scoped asset is known | +| r3 | `dispatch: true`, pushed while the hub is paused; the cell's Flux applies it from the registry | +| r4 | Fail-closed: kro chart pinned to a digest no registry serves | +| r5 | Recovery: pinned kro chart restored | +| r6 | Retention: the journal PVC removed from the source | +| r7 | Retention: the PVC restored to the source | + +## Versions and pins + +| Component | Pin | Why | +| --- | --- | --- | +| Flux | v2.9.6: `install.yaml` SHA-256 `9c1fda7e…4251c`; CLI `flux_2.9.6_darwin_arm64.tar.gz` SHA-256 `7008a758…c126`; controllers by digest in `config/multiplane/flux/components.yaml` (source v1.9.6, kustomize v1.9.6, helm v1.6.5, notification v1.9.4) | v2.10.0 (2026-10-26) requires Kubernetes ≥ 1.35.2, and the exercised kind node is v1.35.0. v2.9.6 (2026-10-01) is the newest patch of the newest compatible minor, and datum-cloud/infra staging runs v2.9.5. Image automation and source-watcher are removed; notification-controller is kept so controller events have a receiver. | +| Source | OCI artifact `fleet-gitops:local` in the run registry, `registry:3.0.0@sha256:6c5666b8…457e` | The Flux OCI pattern Datum uses for `*-kustomize` bundles, with no external publication of uncommitted changes | +| Karmada | chart v1.16.0 from `HelmRepository` `raw.githubusercontent.com/karmada-io/karmada/master/charts`; chart archive SHA-256 `773ab194…34fe` verified in Flux's HelmChart artifact | Same chart as the connected test-infra federation. The repository and release shape follow datum-cloud/infra `infrastructure/karmada`. The chart's floating `cfssl` and `kubectl` hook images are now pinned by index digest. | +| kro | `OCIRepository` `oci://registry.k8s.io/kro/charts/kro` at manifest digest `sha256:4e8de4d3…a67c` (chart layer `ceeb6307…`), image `v0.9.4@sha256:eaf9fbad…` | Unchanged from [site execution](site-execution.md#versions); `OCIRepository` as a chart source is the Flux-native way to pin an OCI chart by digest | +| Milo | `ghcr.io/milo-os/milo@sha256:ec90618e…` (v0.32.5, arm64); etcd `registry.k8s.io/etcd:3.5.16-0@sha256:c6a9d11c…` | Same Milo build as before, now as Flux-managed workloads | + +## Dependency, health and upgrade policy + +- **Dependencies.** Child Kustomizations use `dependsOn`, so a dependent is + applied only when its dependencies are Ready at their current generation. + The order is: Karmada → API coordination → Karmada API → members; and on + the cell: coordination → federation; coordination → site base → shared + services; kro and site base → graph; graph, services and federation → + dispatcher. Shared site infrastructure does not depend on kro. The only + controller tuning is `--requeue-dependency=10s` (default 30s) on + kustomize-controller and helm-controller, so a revision ripples through the + site chain faster. Flux manages that setting on its own + controllers like any other source change. The Helm + releases are wrapped in Kustomizations with `wait: true`, so a release and + its chart source must both be healthy before anything depends on them. +- **Health.** `wait: true` everywhere, with CEL `healthCheckExprs` for kinds + kstatus cannot judge: + - RGD `status.state == 'Active'`; + - HandoffDispatcher `status.state == 'ACTIVE'`, which kro reports only when + the Flux-owned runtime, boot and observer Deployments and boot Service it + references are ready; + - Karmada `Cluster` Ready; + - PVC `Pending` or `Bound`, because the class is `WaitForFirstConsumer`. + + The Milo Deployments, etcd StatefulSets, kro and the shared site Deployments + use kstatus. +- **CRDs.** The handoff CRD Kustomizations use `prune: false` and the CRD is + annotated `prune: disabled`, as datum-cloud/infra does for Karmada CRDs. + kro installs its CRDs on install and skips them on upgrade. +- **Helm upgrades.** kro: `driftDetection: enabled`, remediation retries with + rollback. Karmada: `driftDetection: warn`, as in datum-cloud/infra, because + its pre-upgrade hooks regenerate certificates. One upgrade retry, then + rollback. Both use `upgrade.crds: Skip`. +- **Scoped identities.** Three site layers impersonate ServiceAccounts with + narrow grants: + - `fleet-site-services`: Deployments, Services and ConfigMaps in `fleet-site`, + plus read access for health checks; + - `fleet-site-graph`: `ResourceGraphDefinitions` only; + - `fleet-site-dispatch`: `HandoffDispatchers` in `fleet-site` only. + + None of these identities can directly write Jobs, volumes, RBAC, admission policy or + handoffs. Source authors remain trusted. The services identity can create a + Deployment using the observer ServiceAccount and thereby obtain its status-write + authority, or create a privileged workload. The services layer chooses the + privileged runtime image. Graph authors choose the worker template within the + admission policy. The same source controls the admin-applied site base. This + is not a sandbox for untrusted site revisions; see the + [trust model](site-execution.md#ownership-and-trust-model). The other + Kustomizations use the controller identity, as in a standard single-tenant + bootstrap. + +## Retention and pruning + +Root and child Kustomizations prune. These objects are annotated +`kustomize.toolkit.fluxcd.io/prune: disabled`, so removing them from the +source, or deleting their Kustomization, never deletes them: + +- the site and coordination namespaces; +- the handoff CRD; +- `fleet-site-retain` and the journal PVC; +- the RGD and the `HandoffDispatcher`; +- the private custody namespace; +- the Karmada `HelmRelease` and member `Cluster`; +- each Milo namespace. + +The shared Deployments and boot Service are prunable by their own layer only: +removing one from the source deletes it, which stops new work and, for the runtime, +any running guest. That leaves operations Unknown rather than released. No graph +or instance lifecycle can delete them. + +The StorageClass and PVC are also `ssa: IfNotPresent`: Flux creates them once +and never updates them. A reconcile, a controller restart or a source change +therefore cannot replace the journal volume. A fresh journal would let replayed +handoffs be admitted as new operations; see the +[known limitations](multiplane.md#known-limitations-of-the-local-mvp). +Retiring a site or unjoining a member is an ordered manual procedure, as in +datum-cloud/infra's Karmada runbook. + +Pruning is still not cancellation. A source revision that changes `dispatch` +has the same effect as the +[documented kro pruning behavior](site-execution.md#lifecycle-and-retention). + +## Acceptance coverage + +These phases run in addition to the existing scenarios; see +[acceptance phases](multiplane.md#acceptance-phases). + +| Phase | Asserts | Evidence | +| --- | --- | --- | +| `flux-verify` | Each cluster's source is at the pushed digest. Every expected Kustomization and HelmRelease is Ready at the current generation and revision. The kro chart source is at the pinned digest, the Karmada chart artifact matches the pinned SHA-256, and controllers are digest-pinned. Ownership audit: the services, graph and dispatch inventories are exactly their objects. Each shared Deployment, Service, ConfigMap, ServiceAccount, Role, binding, policy and the PVC carries its one Flux layer label, is in that inventory, and has no kro label or owner reference. kro has written nothing before dispatch. No Job, Pod, handoff, Secret or `w-` object is in any Flux inventory. Shared layers do not depend on kro. Protected objects carry `prune: disabled`. | `flux-verify.json`, `flux-initial.json` | +| `rbac` | The revoked observer RoleBinding is restored by kustomize-controller under a new UID, not by the harness. As kro's identity, 8 worker-scoped verbs are allowed and 15 others denied, including Deployment, Service, PVC and ConfigMap writes, Jobs outside `fleet-site`, Secrets and handoff status. Server-side dry runs admit worker-shaped objects. They deny, by policy, a Job running as the observer, a privileged Job, another image, a hostPath volume and the host network; a broader Role; a RoleBinding to another Role; and a ServiceAccount outside the worker set. | `flux-rbac-restore.json`, `kro-rbac.json` | +| `flux-graph-lifecycle` | With the install terminal and its workers present, the ownership audit passes. The dispatcher's layer is suspended and the instance deleted. kro removes exactly that handoff's Job, ServiceAccount, Role and RoleBinding. Every shared object, the RGD and the StorageClass keep their UIDs, and the PVC/PV, journal and custody are unchanged. Resuming lets Flux recreate the instance under a new UID, and the recreated Job replays a verified no-op (exit 0). Orphaned terminal Pods are listed. | `flux-graph-lifecycle.json` | +| `partition`, `partition-readiness` | Consumer A is stopped by suspending its Kustomization and scaling it to zero. The suspension, UID, generation, zero replicas and no Pods survive the platform root reconciling r3. Resuming leaves Flux to restore it. | `flux-partition.json`, `flux-reconciles.json` | +| `dispatch` | Dispatch arrives as r3 through the cell's Flux while the hub is paused | `flux-revisions.json` | +| `heal` | Flux on every cluster acknowledges fresh requests and is Ready at the current revision after both node restarts | `flux-reconciles.json` | +| `flux-drift` | Five out-of-band changes are each corrected by Flux, with journal, Jobs, PVC/PV and custody unchanged. helm-controller restores the kro Deployment scaled to 0 (same UID). kustomize-controller recreates the Karmada interpreter deleted on the Karmada API, and reverts a widened `fleet-site-kro` grant. As `fleet-site-services-reconciler`, it recreates the deleted shared boot Service under a new UID with the same fixed ClusterIP, ports and selector, and no kro label. It also restores the shared observer Deployment scaled to 0 (same UID). The dispatcher returns to `ACTIVE` and the ownership audit passes. | `flux-drift.json` | +| `flux-restart` | Every Flux controller Pod on the three clusters is deleted. Each source, Kustomization and HelmRelease then acknowledges a request token issued after the restart. No Helm release revision, inventory, Job, journal or custody changes. | `flux-restart.json`, `flux-reconciles.json` | +| `flux-fail-closed` | r4 leaves the kro chart source and Kustomization not Ready. The graph and dispatcher report `DependencyNotReady` and their new revision is not applied (marker unchanged). The site base and shared services layers are Ready at r4, with every shared object UID and Deployment generation unchanged. The running kro Deployment and site are untouched. r5 converges. | `flux-fail-closed.json` | +| `flux-retention` | r6 drops the PVC from the inventory without deleting it (same PVC/PV UID, journal and custody). r7 re-adopts the same claim. | `flux-retention.json` | +| `flux-final` | All three clusters are at the final revision with nothing suspended, and the ownership audit passes with the cleanup workers present | `flux-final.json`, `flux-ownership-final.json` | + +## What is not production + +- **Source transport.** A plain-HTTP, unauthenticated, unsigned registry on the + disposable kind network (`OCIRepository.spec.insecure`). Production needs TLS, + registry credentials and `spec.verify` (cosign or notation). +- **Credentials.** Credentials are enrolled imperatively. They are never in + the source and are scanned for, but there is no SOPS, External Secrets or + workload identity, and tokens are not rotated. +- **Cluster and Milo topology.** Three kind clusters on one VM, not + independent failure domains. Milo project APIs are Flux-managed workloads on + one platform cluster, with static-token RBAC, self-signed serving keys and + fixture Projects. This is not Milo's project provisioning, IAM or HA + storage. +- **Flux lockdown.** The Karmada API is reconciled with the chart's admin + kubeconfig. datum-cloud/infra uses a dedicated, secretless Flux identity + there. Multi-tenancy lockdown flags, such as `--no-cross-namespace-refs` and a + default ServiceAccount, are not set; only the site layers impersonate scoped + ServiceAccounts. +- **Upstream sources.** Karmada's HelmRepository and the kro chart come from + upstream over the internet. No mirror or signature check is configured. + Pins are verified in evidence (Karmada) or enforced by digest (kro). +- **Acceptance driver.** The management phase CLI (`fleet-multiplane-host`) + remains an explicit acceptance driver run on the host. It is not a deployed + manager. + +The `summary.json` qualification keeps `productionAuthority` and +`productionEquivalence` false. + +## Review follow-up: suspension and reconcile evidence + +Fault injection patches `spec.suspend` with field manager +`fleet-fault-injection`, rather than a `kubectl`-prefixed manager whose fields +Flux may take over. Before resuming, the harness requires the same suspended +object UID and generation, zero Deployment replicas and no matching Pods. +`flux-partition.json` and `flux-reflection-suspension.json` retain those checks. +This prevents a source reconciliation silently ending the injected fault. +While consumer A is still suspended, `partition-readiness` also forces the +platform's source and root sync to reconcile the dispatch revision (r3) with +fresh request tokens. The guard then records the root's applied revision +(`rootReconciledDuringFault`) beside the unchanged suspension receipt. + +Convergence waits require the source and each requested Kustomization to report +`status.lastHandledReconcileAt` equal to its fresh request token, as well as +current readiness and revision. Restart checks additionally require those +receipts from both HelmReleases. `flux-reconciles.json` and `flux-restart.json` +record the acknowledgements. Old Ready status is insufficient. + +A parent Kustomization's server-side apply can remove a `kubectl annotate` +request from the child it manages before any reconcile handles it. A root sync +also applies its own object. In the first fresh run, the cell root lost its only +request this way and the wait timed out. When the request annotation is gone +and the object has not acknowledged it, the wait now issues a new token and +requires that exact token to be acknowledged. `lostRequestsReissued` counts +these per object. A reissue never accepts an older acknowledgement. + +**Bootstrap gating evidence.** The `flux-platform` wait samples the cell and +the hub on every poll (`flux.py wait --observe`), not only the cluster it is +waiting on. Observations are keyed by whether the dependent had already applied +the revision. `flux-verify` requires a `DependencyNotReady` observation on both +the cell and the hub with nothing applied: no applied revision and an empty +inventory. A dependent seen gated *after* applying r1 means a dependency +re-reconciled at the same revision on a fresh request. It is recorded as +`bootstrapRegatedAfterApply` and is neither evidence nor a fault. An inventory +with no applied revision, or another applied revision during bootstrap, fails. +The earlier check sampled the hub only after the cell converged. It treated any +gated observation with r1 applied as "applied before its dependency was Ready", +which it cannot show. The second fresh run of this change, +`/tmp/fleet-multiplane.XjeuF8`, failed on that false positive: its first hub +sample came after the hub had applied r1. That run had created no allocation, +handoff or effect, and was discarded with `teardown.sh --discard-unknown`. + +The [fresh acceptance run](multiplane.md#flux-acknowledgement-acceptance-2026-11-15) +established these stronger claims. They supersede the +[earlier run's](multiplane.md#flux-reconciled-acceptance-2026-11-15) weaker +suspension and restart assertions. That run established PXE results and final +convergence, but not that consumer suspension persisted or that every object +reconciled after the controller restart. diff --git a/docs/operations/local-vm.md b/docs/operations/local-vm.md index 45d7e3b5..06ba44f7 100644 --- a/docs/operations/local-vm.md +++ b/docs/operations/local-vm.md @@ -16,7 +16,9 @@ For a local runtime without reliable x86 KVM, explicitly select software executi DOCKER_CONTEXT=colima-fleet-acceptance-tcg FLEET_LOCAL_VM_ACCEL=tcg bash hack/local-vm/run.sh ``` -`task local-vm:acceptance` runs the same TCG command. +`task local-vm:acceptance` runs the same TCG command. For the multi-plane composition +of this provider with Milo and Karmada, use the one-command +[multi-plane acceptance](multiplane.md) harness instead. The named Docker context must already identify your dedicated disposable runtime. TCG builds a native amd64 or arm64 Debian libvirt/QEMU runner and boots the same diff --git a/docs/operations/multiplane.md b/docs/operations/multiplane.md new file mode 100644 index 00000000..bb097fff --- /dev/null +++ b/docs/operations/multiplane.md @@ -0,0 +1,965 @@ +# Local Milo, Karmada and PXE acceptance + +This opt-in harness runs native Milo project routing, actual Karmada delivery and +status reflection, and the local VM executor through the existing allocator and +installation lifecycle. On the selected cell, execution runs as Flux-owned +Kubernetes Deployments and kro-created per-operation Jobs; see [Kubernetes-native site execution](site-execution.md). +Every long-running service is installed by each cluster's own Flux from a source +artifact built from the checkout; see [Flux-reconciled local environment](gitops.md). It is not enabled by the production manager or any +production overlay. Production authority and deployment equivalence remain +**unqualified**. + +Read the [writer placement contract](../architecture/README.md#control-plane-placement-and-writers), +[pinned design sources](../architecture/design.md#source-proposals), and +[local VM contract](local-vm.md) first. New multi-plane files implement this +composition. The shared lifecycle adds only the read-only +`Coordinator.ClaimReleased` custody query, and the executor interface documents +exact-request replay and its narrow not-found-plus-Unknown lookup contract. + +## Topology and versions + +| Surface | Local implementation | Writer | +| --- | --- | --- | +| Provider project | Milo v0.32.5 native `/projects/provider/control-plane` route; dedicated API Deployment and etcd StatefulSet with its own PVC on the platform kind cluster, reconciled by Flux | Bootstrap fixture supplies definitions and observations; allocator retains exclusive custody | +| Consumer A / B | Two independently restartable Milo v0.32.5 Deployments and etcds, one Flux Kustomization each; native project routes; both use namespace `default` and Machine name `allocation` | Separate customer credentials create/watch requests; management writes public status | +| Private allocation custody | `fleet-system-private` Secrets on the management host Kubernetes API | Shared lifecycle coordinator, with its own scoped credential | +| Coordination intent | Karmada v1.16.0 API (hub Flux `HelmRelease`), separate from the host Kubernetes API | Management credential creates immutable handoffs; cannot write status | +| Selected cell | Separate kind Kubernetes API running its own Flux, the Flux-owned shared site services, kro v0.9.4 and the `HandoffDispatcher` graph | Karmada delivers intent; the site observer ServiceAccount is the only local status writer | +| Reflected results | Karmada interpreter aggregates each member's identity and observation | Karmada; management validates before projection | +| Physical effects | Privileged, Flux-owned VM runtime Deployment (libvirt/QEMU) on the cell; amd64 guest under native arm64 TCG | One bounded kro-created worker Job per handoff invokes `executor.Client`; provider persists exact requests and boot evidence on a retained, Flux-owned PVC | + +The platform integration choices were discovered in these connected sources: + +- Fleet's `go.mod` pins Milo **v0.32.5**. The local Milo checkout reviewed was + `3c2a160d6d5614d6dc7bf119b8d022fc641c5d4f` (v0.32.5 plus later commits). + Its `pkg/server/filters/projects.go` implements project path routing and + `internal/apiserver/storage/project/mux.go` uses `/projects/` etcd + prefixes. The harness runs the released v0.32.5 image, not that dirty checkout. +- `datum-cloud/test-infra` federation checkout + `3619e71d4686c3d1ead01f08a1136f7d272b3344` pins the Karmada Helm chart to + **v1.16.0**. Its Taskfile and `components/karmada/values.yaml` supplied the + bootstrap model. This harness keeps fsync enabled; it does not adopt that + checkout's `unsafe-no-fsync` tuning or insecure TLS kubeconfig rewrites. +- The connected Compute federation interpreter supplied the supported Karmada + `statusReflection` / `statusAggregation` customization interface. Fleet's + interpreter preserves *all* reflected replicas and their Karmada cluster + names, rather than accepting the first result. +- kind nodes use **v1.35.0**, digest-pinned to the already exercised local VM + node image. Karmada's chart pins its own API/controller images to v1.34.1 and + its etcd to 3.6.0-0. Milo's local etcd uses 3.5.16-0. The Milo arm64 image is + digest-pinned in the launcher. Some upstream Helm hook images still use + floating tags; this is a remaining reproducibility seam. +- kro **v0.9.4** is installed on the cell by a Flux `HelmRelease` from its + official OCI Helm chart, pinned by manifest and image digest. The newer v0.10.0 was five days old and is + not used. See [versions](site-execution.md#versions). + +- Flux **v2.9.6** runs on each of the three kind clusters; see + [versions and pins](gitops.md#versions-and-pins) for why not v2.10.0. + +Independent local Milo roots make project process/storage failures independently +injectable without a hand-written proxy. Each is a Flux-managed Deployment with +its own etcd StatefulSet and volume on a dedicated platform kind cluster, not a +bare Docker container. **This is still a local placement seam:** it is not the +platform's complete root/ProjectControlPlane provisioning machinery, Kyverno +orchestration, shared root IAM, or project retirement path. Milo's +native project routing and project storage are real. Separate roots and etcds +prevent namespace-based isolation shortcuts. The management process runs on the +host, and its private storage shares host infrastructure with Karmada, while +using a distinct API endpoint, namespace and credential. + +## Run + +Prerequisites: Go from `go.mod`, Python 3.12+, OpenSSL, Docker, kind, kubectl, +kustomize, curl, Git, Colima, network access to GitHub releases, `ghcr.io`, +`registry.k8s.io` and Docker Hub, and the task-owned native arm64 VZ Colima profile `fleet-acceptance-tcg` +with 4 CPUs, 8 GiB memory, amd64 container emulation, and at least 12 GiB free in +its Docker data root. Never use `fleet-e2e-x86`. The harness never changes the +global Docker context, never creates a Colima profile, and never stops or deletes +another run's containers. Stopped diagnostics from earlier runs are left alone; +only *running* `fleet-local-*`/`fleet-mp-*` containers block a launch. + +One command runs preflight, a fresh topology, every acceptance phase, sanitized +evidence, and owned-resource teardown: + +```sh +task multiplane:acceptance +# equivalent: +FLEET_MULTIPLANE_INOTIFY=1024 hack/multiplane/run.sh +``` + +`FLEET_MULTIPLANE_INOTIFY=1024` (set by the task) is the explicit opt-in for a +reversible, nonpersistent `fs.inotify.max_user_instances` adjustment inside the +task Colima VM only; the original value is restored at teardown or stop and both +values are recorded in `sysctl.json`. Options: + +| Option | Effect | +| --- | --- | +| `--preflight-only` (`task multiplane:preflight`) | Run every check below, create nothing, exit | +| `--bootstrap` | If the existing `fleet-acceptance-tcg` profile is stopped, start it with its saved configuration | +| `--keep` | After a pass, stop instead of delete this run's containers | +| `--leave-running` | After a failure, leave containers running for live diagnosis instead of stopping them | +| `--skip-readiness-tests` | Skip the implementation test gate (diagnosis only) | + +Preflight records `evidence/preflight.json`. Prerequisite checks cover tools, +the exact Docker context socket, reachability, architecture, memory, CPUs, free +disk, amd64 emulation, inotify, and concurrent Fleet runtimes. Readiness checks +require the CLI subcommands and location-denial error the harness drives, then +run `go test -race -count=1 ./internal/coordination ./internal/multiplane +./internal/localvm ./cmd/fleet-multiplane`. Failing either blocks before any +resource is created. + +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 | +| 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 | + +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 +2300 MiB (platform), 2600 MiB (hub), 4400 MiB (cell) and 128 MiB (registry). +They total about 9.2 GiB and deliberately overcommit the 8 GiB VM, because +actual usage is much lower. In a debug run the cgroup peaks were 1.99 GiB for +the platform node (under reclaim pressure at the earlier 1900 MiB cap), 2.06 GiB +for the hub and 1.6 GiB for the cell after its restart; VM usage was about 4 GiB +after the install. Re-measure with `docker stats` and each node's +`memory.peak` if you change workloads. The cell holds the cell API, Flux, kro and the site, including the +VM runtime Pod, whose limit is 3 GiB. Each Milo API has a 384 MiB cap. The VM +guest is configured with 2 GiB and 2 vCPUs, using TCG. A 2.5 GiB provider cap +caused an installer OOM in an earlier fresh run. Evidence fails on any OOM kill +in the runtime Pod, any kind node, or the site, kro, Flux, Karmada or Milo containers. Expect 20 to 60 minutes, +mostly bootstrap, image pulls and builds. Every phase has an explicit bound. +Do not run another full acceptance topology concurrently on an 8 GiB VM. + +### State and evidence layout + +All containers have one fresh `fleet-mp-` prefix. The command prints a +mode-0700 `/tmp/fleet-multiplane.*` state directory (override the parent with +`FLEET_MULTIPLANE_STATE_ROOT`). Only its `evidence/` subdirectory is shareable: + +| File | Content | +| --- | --- | +| `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 | +| `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 | +| `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 | +| `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, +ServiceAccount token (including the short-lived observer and worker probe +tokens), kubeconfig client key, fence and boot capability, and +redacts and fails on any match. Outside `evidence/`, `logs/.log` keeps +each phase's full output and the kubeconfigs, tokens, journals and binaries +remain private. Never publish the state directory itself. + +### Acceptance phases + +`hack/multiplane/acceptance.sh` lists the ordered phases; `steps.sh` implements +the harness-side ones and `k8s_evidence.py` records the Kubernetes facts. Before +acceptance starts, the run does the following: + +- builds the current source and the site image, and verifies its binary checksum; +- verifies the pinned Flux CLI and install manifest; +- creates the run registry and the platform, hub and cell kind clusters, and + pushes the site image (the cell pulls it by digest); +- publishes source revision 1 and bootstraps Flux on each cluster (the + [bootstrap boundary](gitops.md#bootstrap-boundary)). Flux then installs + Milo, Karmada, host RBAC, the Karmada API configuration, kro, the site base + and the graph in dependency order; +- enrolls credentials and seeds fixtures; +- publishes revision 2, which adds the shared site services and the + `HandoffDispatcher` with dispatch disabled. `site.sh check` requires the + following: + - the runtime, boot and observer Deployments Available from the published + digest, each labelled as owned by the Flux `fleet-site-services` layer; + - the boot Service at its fixed ClusterIP; + - the dispatcher reporting the same worker image; + - the volume `Retain`; + - no worker Job; +- runs `flux-verify`. + +The phases are then: + +1. **Native Milo routing and RBAC.** Customer create/watch, with equal namespace and request + names in separate project APIs. Exact Project and namespace UIDs distinguish + lifetimes. `rbac` verifies against real API servers that the site observer + ServiceAccount cannot create objects, write handoff specs, delete intent, read + Secrets or create Jobs. It also checks forbidden project and hub writes, and + that revoking the observer RoleBinding denies its reads. The cell's Flux, + not the harness, then restores the binding. Finally, as kro's own identity, + it proves the narrowed grant and the admission policies on kro's writes + ([trust model](site-execution.md#ownership-and-trust-model)). +2. **Contention.** Two consumers request one provider capacity. One binding + succeeds; `verify-contention` independently reads Bound for A and + Pending/InsufficientCapacity for B. +3. **Retained admission before effects.** Installation admission retains core + authority and inputs, then immutable hub intent, before any effect. + `await-delivery` requires the following: + - exactly one Karmada-delivered handoff; + - kro reporting that handoff in `HandoffDispatcher.status.deliveredHandoffs`; + - no cell status and no worker Job. +4. **Partition.** Suspend consumer A's Flux Kustomization, stop its API and pause + the hub. `dispatch` then publishes revision 3, which sets `dispatch: true`. + The cell's own Flux reconciles it from the registry with no hub access. kro + creates the per-operation ServiceAccount, Role, RoleBinding and Job from its + local replica. +5. **Pod interruption.** `interrupt-pod` waits until the provider journal shows + the install `installer-started` *and* its libvirt domain running. It then + force-deletes the worker Pod with no grace period. It requires: + - no local result; + - the Job controller to record the lost Pod and start a replacement in the + same Job; + - the same unfinished operation. +6. **Job interruption.** `interrupt-job` deletes the whole worker Job as soon as + the replacement exists, still mid-install. kro must recreate the Job under + a new UID for the same operation. +7. **Exact resume.** `resume` requires the recreated Job to be `Complete` with + one succeeded Pod, and the observer to publish `Succeeded` from the journal. + The journal must hold exactly one install. Evidence later proves exactly one + firmware-network installer start followed by exactly one disk-only start. + It uses libvirt's append-only QEMU log, plus one `sfdisk`, one installer + receipt and one disk-boot receipt in the guest serial logs. `worker-rbac` + then proves the worker token can read only its own handoff: no list, no + other names, no status or spec writes, no Secrets, no site writes. +8. **Readiness under partition.** The platform's root sync first reconciles r3 + while consumer A stays suspended at the same UID and generation, with no + Pods (`flux-partition.json`). Consumer A's Kustomization is then resumed and + Flux restores its API. The install Job is + `Complete` but public Ready must still be False while the hub is + disconnected. Job completion is not readiness. +9. **Heal and project.** Restart the hub and the cell node; the cell restart + recreates every site Pod from the retained volume. Flux on every cluster + must return to Ready at the current revision. Karmada reflects the + result, and management validates the following before public projection: + - the exact selected cell, request and operation; + - allocation, asset, epoch and fence; + - input digest and observation freshness. + + Installation is repeated to confirm idempotent recovery. +10. **Pod and Job lifecycle.** `lifecycle` recreates the runtime, boot and + observer Pods and deletes the completed install Job; kro recreates the Job, + which replays a verified no-op. The following must be unchanged: + - journal bytes; + - QEMU start count; + - PVC/PV identity and `Retain` policy; + - domains; + - consumer A's Ready/Bound allocation. + + The restarted observer must republish. + + The GitOps phases follow: + - `flux-graph-lifecycle`: deleting the dispatcher removes only kro's + per-operation objects, and shared services and storage are untouched; + - `flux-drift`: Flux corrects drift, including the shared boot Service and + observer; + - `flux-restart`: controllers restart without duplicate effects; + - `flux-fail-closed`: a broken kro release blocks only the dispatcher + layers; + - `flux-retention`: the journal volume is retained when its claim is + removed from the source. + + See [acceptance coverage](gitops.md#acceptance-coverage). +11. **Invalid and stale results.** With the Karmada `HelmRelease` suspended and its controller stopped, bootstrap + credentials substitute one attribute of the real reflected result at a time: + wrong cell, stale, future, duplicate replicas, wrong intent digest, wrong input + digest, wrong operation ID, incomplete phase, and missing reflection. Management + must reject each. This is fault injection, not a replacement status relay. +12. **Cleanup and reuse.** Cleanup goes through the same federation path and + kro-created Jobs, with synthetic quota settlement. `release-status-a` + requires consumer A's Machine to be Released with Ready False, no + `currentInstallationRef`, and no Fleet finalizer. Consumer B then reuses the + capacity in epoch 2 and must show Bound. +13. **Delivery faults.** `delivery-faults` creates three cell-local handoffs + with cell bootstrap credentials: + - the epoch-1 install under a second name; + - a wrong-cell intent; + - a stale epoch-1 replay. + + Each kro-created Job must fail once with exit 65 by `podFailurePolicy`. + The journal must be unchanged, no status may appear, consumer B must stay + Bound, and kro must prune them once deleted. After B's release, + `release-status-b` repeats the released checks for B. +14. **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. Private custody Secret names/UIDs/resourceVersions, + the provider journal bytes, 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 + boot Service are denied after closure. Evidence requires all of: + - PXE mode, one install and two cleanups, epochs 1 and 2; + - 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 + cleanups, each with one successful Pod; + - zero OOM kills. +16. **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. + +### Failed or interrupted runs + +Failures stop this run's exact containers (never delete them) and retain the full +private state; execution and custody are **Unknown**. `result.json` names the +failed phase and the retained containers. Stopping is not release evidence: + +```sh +hack/multiplane/stop.sh /tmp/fleet-multiplane.REPLACE # stop only; idempotent +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 +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 +API count: the real Karmada webhook exited with `too many open files`. The bounded +value 1024 resolves that local prerequisite. + +Offline harness tests run in CI and locally with `task multiplane:test-harness`. +They use fake runtime tools to cover preflight outcomes, Flux source staging +(credential refusal, revision variants, rendering), push records, reconcile waits +(stale acknowledgements rejected, stripped requests reissued), fault-guard +suspension and root-revision receipts, bounded phase timeouts +that kill the process group, sanitized journal observation, secret detection, +result mapping, and effect-free teardown refusal. + +## Implementation and trust boundaries + +`internal/coordination.Hub` implements `executor.Client`. It creates an immutable +`MachineAllocationHandoff` under `coordination.fleet.datumapis.com/v1alpha1` and +returns Unknown until a valid reflected observation exists. The request is stored +as a JSON string so API-server normalization cannot reorder opaque input fields +and change the retained executor digest. `spec` is immutable through CRD CEL. +Names derive from the operation ID; a changed request under the same ID conflicts. + +`internal/coordination.Cell` is split into two least-privilege roles. Both +validate that the delivered handoff names this cell, that its name is derived +from the operation ID, and that the intent is valid before anything else. + +- **`Cell.Execute`** runs in the per-operation worker Job (`fleet-multiplane + site-worker`). It looks up the provider journal first, and a terminal + result is not re-executed. When lookup reports the operation not found and + Unknown, the worker re-sends the identical retained request under the same + operation ID. The local provider reports exactly this for a retained but + unfinished operation. The provider replays it against its digest-checked + journal and resumes observing an already-started installer instead of + starting another. Conflict, fencing, transport errors and a found-but-errored + lookup stop before any effect. `Execute` never writes status. +- **`Cell.Publish`/`Cell.Observe`** run in the observer Deployment + (`fleet-multiplane site-observer`), which uses a read-only provider. Every 10 + seconds it lists this cell's handoffs and publishes an observation only for + a terminal journal result that passes `ValidateResult`. Unknown is never + published, and periodic refresh keeps observation timestamps fresh. + +Retries, Pod replacement and dependency ordering belong to the Job controller +and kro. Neither role holds a hub, consumer, provider-project or +private-custody credential. This proves recoverable operation completion, not +ongoing guest health or live production hardware attestation. + +Allocation serves exactly one location, `local`, bound to the configured cell. +`Runner.request` rejects any other Machine `locationRef`, an empty `Config.Cell`, +or a hub client with a different cell. It returns `ErrLocationNotServed` before +claim custody, authority records, finalizers or allocation. The CLI treats this +rejection, conflicts, fencing and invalid requests as terminal instead of +retrying until timeout. + +Release projection runs only after verified cleanup made finalizer removal safe. +Each step is retry-safe. The referenced Installation is retired first (`Released`, +Ready False), then `currentInstallationRef` is cleared and the Machine is +published `Released` with Bound and Ready False. The Fleet finalizer is removed +last, from the server's fresh copy, so the removal is not reverted. Later requests +read terminal custody through `Coordinator.ClaimReleased` and never restore the +finalizer on a released claim. Reuse writes consumer B's Bound status only from +the coordinator's committed binding. The CRD types Installation `status.phase` as +a free-form string with no enum or CEL rule, so `Released` is schema-valid. +`release-status-a` reads it back from the real Milo API. + +`LocalAssetMapping` maps exactly one configured provider-scoped Device identity +to `localvm.AssetID`. It obtains the original retained request from the cell API, +validates the translated provider digest, and returns the original digest. +It never aliases by suffix or moves custody into the cell. This explicit +synthetic hardware enrollment is necessary because the local VM provider accepts +one fixed physical asset ID. No Device/capacity/allocation/Installation identity +is substituted for another. + +Cell site identities are as follows: + +- **Observer** (static Role): get/list/watch handoffs and update handoff + status only. +- **Workers** (one kro-created Role each): `get` on exactly one handoff by + `resourceNames`, with an automounted short-lived projected token. +- **kro** (aggregated read-only ClusterRole plus two namespaced Roles): reads + handoffs, the Flux-owned shared services and the PVC cluster-wide. It writes + only Jobs and ServiceAccounts in `fleet-site`, and Roles and RoleBindings in + `fleet-coordination`. Two admission policies pin those writes to the + per-operation shape. It has no Deployment, Service, volume, Secret or + handoff spec/status write. + +Management's hub Role grants intent create/get/list/watch but no status writes. +Karmada uses a separate member ServiceAccount with namespace-scoped intent +writes. It also has cluster-wide read/watch for handoffs, because its member +informer lists that resource across namespaces, and it can read +nodes/pods/namespaces and discovery/health endpoints. It has no Secret-reading +permission or local status-writing grant. Management and Karmada tokens are +24-hour local ServiceAccount tokens; the harness does not refresh them for +long-running deployments. Bootstrap administrator credentials remain on the +host. No cell credential leaves the cell: the cell kubeconfig export from the +previous design was removed. + +Milo static-token RBAC grants live in the native root RBAC store, where its RBAC +authorizer reads them. Customer tokens cannot write status or read Secrets. +Management uses separate project read/status roles. Tests also delete the cell +RoleBinding, verify denial, and restore that exact binding. These tests establish +Kubernetes RBAC behavior, not caller-preserving production Milo IAM. + +The local runner's catalog, publication, hardware observations, source-use +admission, quota holds and settlement are explicit synthetic fixtures. Concrete +synthetic contract records and the existing lifecycle custody are durable before +effects. Networking is deliberately empty; no NSO/IPAM/routing implementation is +substituted. Adoption and production service readiness are never enabled. + +## Verification and remaining gaps + +### Flux-owned shared site acceptance (2026-11-16) + +This run verifies the current ownership split: the cell's Flux owns the shared +site services and storage, and kro owns only per-operation workers (see the +[trust model](site-execution.md#ownership-and-trust-model)). It supersedes the +ownership claims of the runs below, which verified kro-owned shared +Deployments. It re-establishes every other scenario of the +[acknowledgement run](#flux-acknowledgement-acceptance-2026-11-15). + +`task multiplane:acceptance` exited 0 at 00:07 UTC on November 16, 2026, with +the readiness test gate enabled. Run details: + +- state `/tmp/fleet-multiplane.WkV4ul`, prefix `fleet-mp-ed5636ae`; +- all 54 bounded phases passed (one more than before: `flux-graph-lifecycle`), + in 25.6 minutes from build to teardown with cached base images; +- SHA-256 of `source-SHA256SUMS` (155 entries): + `7faa0832c7b543d2504398b462b117ff1bd00cbea721f550b56d23778a17d31e`; +- site binary `ff5c1b26…077a` and host binary `3e03201a…e4b4`, unchanged, because + no Go code changed; +- site image `sha256:66cdc9d8c6cd010825de447f8aa3b108d35bcf93531e6e255e13c5a56dee48ad`, + pulled by the cell by that registry digest; +- seven source revisions from the dirty checkout at HEAD `d7ff793b`, 58 files + each: r1 `4d743778…`, r2 `8e4b05f8…` (shared services and dispatcher), r3 + `84ff7ff0…`, r4 `939fae00…` (bad kro chart), r5 `7f319b98…`, r6 `1afccbf1…` + (claim removed), r7 `cc786e40…`. All three clusters ended at r7. + +New claims, from the sanitized evidence: + +- **Single writer per object** (`flux-verify.json`, `flux-ownership-final.json`). + Before dispatch, 20 shared site objects each carried exactly one Flux layer + label, were in that layer's inventory, and had no kro label or owner + reference. The services, graph and dispatch inventories held exactly their 5, + 1 and 1 objects, and kro had written nothing. At the end, the same 20 objects + passed again. kro had written exactly 12 objects: the Job, ServiceAccount, + Role and RoleBinding for the install and both cleanups. Every shared + Deployment was labelled `fleet-site-services` with no kro label + (`kubernetes-execution.json`). +- **kro's narrowed authority** (`kro-rbac.json`). As kro's identity, 8 worker + verbs were allowed and 15 others denied. Three worker shapes were admitted by + server-side dry run, and 8 violations were each denied by a + ValidatingAdmissionPolicy. Every real worker Job and its RBAC, including the + three delivery-fault Jobs, passed the policies. The chart grants kro keeps + are recorded: CRD create/delete and Leases. +- **Graph lifecycle does not touch shared infrastructure or storage** + (`flux-graph-lifecycle.json`). Deleting `HandoffDispatcher/dispatcher` + (UID `e4c7eb92…`) removed exactly the install's four `w-op-1325c74…` + objects. All 22 tracked identities kept their UIDs: the shared objects, the RGD + and the StorageClass. PVC `bb97aa91…`, the journal (`92ad2c9e…` before and + after) and custody were unchanged, and the handoff stayed `Succeeded`. Flux + recreated the instance (UID `65d41287…`), kro recreated the four objects, + and the Job replayed a verified no-op with exit 0. One orphaned, `Succeeded` + Pod from the deleted Job is recorded. +- **Flux drift repair of shared services** (`flux-drift.json`). The deleted + boot Service was recreated by the services layer under a new UID + (`ace32e5d…` → `26767a93…`), at the same ClusterIP `10.96.0.80` and with an + unchanged spec. The closed-boot probes later ran through it. The observer + Deployment scaled to 0 was restored with the same UID (generation 1 → 3). The + earlier three cases, kro, the Karmada interpreter and the widened kro grant, + were corrected as before. +- **kro failure does not gate shared infrastructure** (`flux-fail-closed.json`). + With r4, the kro chart source and Kustomization failed and the graph and + dispatcher reported `DependencyNotReady`; the dispatcher marker stayed r3. + The base and services layers applied r4 with every shared UID and Deployment + generation unchanged. r5 converged. +- **Bootstrap gating observed before apply** (`flux-verify.json`). Gating was + observed on the hub (Karmada coordination, API and members) and on the cell + (federation, site base, graph), each with nothing applied. + +Re-established, as in the earlier run: + +- **PXE.** Worker Pod force-deleted at `installer-started` with its domain + running and replaced in the same Job. Job deleted mid-install and recreated + by kro. One install operation recorded one network-installer start and one + disk-only start. +- **Recovery.** Partition kept public Ready False with the Job Complete. + Suspension receipts, heal, the idempotent install, lifecycle recreation and + retention all passed (PVC `bb97aa91…`, PV `27b3cd4d…`, `Retain`). +- **Acknowledgement and restart.** All 21 convergence waits required fresh + acknowledgements; 12 stripped requests were reissued. All 12 controller Pods + were replaced, every object acknowledged a post-restart token, and both Helm + releases stayed at version 1. +- **Rejections and denials.** Nine reflection faults were rejected, and release + and reuse passed across epochs 1 and 2 with two cleanups. Three delivery + faults failed by `PodFailurePolicy` at exit 65 and were pruned by kro. Wrong + location was denied with free capacity, and the closed-boot denials passed. +- **Memory, secrets and teardown.** Zero OOM kills; the cell node recorded 89 + `memory.max` events, more than the 17 of the earlier run. 33 evidence files + were clean against 23 retained secrets. Teardown removed every + `fleet-mp-ed5636ae` resource and private credential, and inotify was + restored from 1024 to 128. + +Three earlier fresh attempts of this change failed before any allocation or +effect. Each was inspected and then discarded with `teardown.sh +--discard-unknown`, which is not release evidence: + +1. `/tmp/fleet-multiplane.LpvtO5` (`fleet-mp-a84271ad`) failed in + `flux-platform`. kro rejected the RGD because `runtime` is a reserved + resource ID in kro v0.9.4. The ID is now `hypervisor`, and `test-harness.sh` + checks every ID against kro's reserved list. +2. `/tmp/fleet-multiplane.XjeuF8` (`fleet-mp-39f70830`) failed in `flux-verify`, + on a false positive in the bootstrap ordering check. Its ownership audit had + passed. See + [bootstrap gating evidence](gitops.md#review-follow-up-suspension-and-reconcile-evidence). +3. `/tmp/fleet-multiplane.jnCCQ9` (`fleet-mp-0e269a33`) failed in `rbac`. The + live probe found that the kro chart grants cluster-wide ConfigMap writes, + which kro does not use. The HelmRelease now removes them. + +Before the live runs, the admission policies, the narrowed grants and the +scoped Flux identities were also exercised against a disposable envtest +kube-apiserver v1.36.2 with the kro v0.9.4 controller built from its tag +(`4ba0e410`). Valid worker objects were admitted and violations denied. The +RGD became `Active`, with readiness gating on the referenced Deployments. +Deleting the instance removed only worker objects. This was a manual +pre-check, not a repository test. + +The run has not yet been independently reviewed. + +### Flux acknowledgement acceptance (2026-11-15) + +This run supersedes the partition and restart claims of the +[earlier Flux-reconciled run](#flux-reconciled-acceptance-2026-11-15). It +re-establishes every other scenario of that run. + +`task multiplane:acceptance` exited 0 on November 15, 2026 at 21:40 UTC, with +the readiness test gate enabled. Run details: + +- state `/tmp/fleet-multiplane.Ufjnxs`, prefix `fleet-mp-677f3c68`; +- all 53 bounded phases passed, in 25.6 minutes from build to teardown with + cached base images; +- SHA-256 of `source-SHA256SUMS` (152 entries, now including + `config/base/crd`): `a1a33d8944ba82f9fbd014c13092aca8151e2730210939cb2c6fb59fdf12f2f3`; +- site binary `ff5c1b26…077a` and host binary `3e03201a…e4b4`, unchanged from + the earlier run; +- site image `sha256:efacf7ac9c17d83dab387683a3dc74561d5efce70447975e45b07cb72b31e2f3`, + pulled by the cell by that registry digest; +- seven source revisions from the dirty checkout at HEAD `d7ff793b`, 55 files + each: r1 `497fc276…`, r2 `31f19f68…`, r3 `63d46be3…`, r4 `8ee7a6b1…` (bad + kro chart), r5 `79855353…`, r6 `8bfa826c…` (claim removed), r7 `8cdc7270…`. + All three clusters ended at r7. + +The sanitized evidence records the following new claims. + +- **Partition suspension held** (`flux-partition.json`). Consumer A's + Kustomization kept UID `c58c9f19…` at generation 2, suspended, with zero + Deployment replicas and no Pods, from `partition` through + `partition-readiness`. In between, the platform source and root sync + acknowledged fresh requests and applied r3 (`rootReconciledDuringFault`). + Flux made no concurrent repair. The harness then resumed it and Flux, not the + harness, restored the API. +- **Reflection-fault suspension held** (`flux-reflection-suspension.json`). + The Karmada HelmRelease kept UID `41638898…` at generation 2, suspended, with + the controller at zero replicas and no Pods. That was checked before each of + the nine injected faults and again before resuming. +- **Acknowledged convergence** (`flux-reconciles.json`). All 20 convergence + waits, across bootstrap, revisions, heal, restart and final, required each + source and Kustomization to report `lastHandledReconcileAt` equal to a fresh + token, Ready at the current generation and revision. Fifteen requests were + removed by a parent apply before being handled, and were reissued: the cell + root six times, cell `kro` four, hub `karmada` three, platform root two. Every + final acknowledgement matched the latest token. +- **Restart re-reconciled every object** (`flux-restart.json`). All 12 + controller Pods on the three clusters were replaced (no UID kept). Every + source and Kustomization then acknowledged a post-restart token, and both + HelmReleases acknowledged theirs with no reissue. Helm release versions + stayed at 1; inventories, Jobs, the journal, PVC/PV and custody were + unchanged. + +The other scenarios passed as in the earlier run: + +- **PXE.** The worker Pod was force-deleted at `installer-started` with its + domain running, and replaced in the same Job. The Job was then deleted and + kro recreated it under a new UID. One install operation recorded one + network-installer start and one disk-only start. +- **Lifecycle and recovery.** Partition kept public Ready False with the Job + Complete. Heal, the idempotent install and lifecycle recreation kept the + journal and volume unchanged. +- **Flux.** Drift was corrected by Flux (kro same UID at release v1, Karmada + interpreter recreated, kro grant reverted). The observer RoleBinding was + restored under a new UID. r4 failed closed with `OCIArtifactPullFailed` and + `DependencyNotReady`, and the FleetSite stayed at r3. r6 and r7 retained PVC + `2c18ea7a…` and PV `45670d5d…` (`Retain`). +- **Rejections and denials.** All nine reflection faults were rejected. Release + and reuse passed in epochs 1 and 2, with two cleanups. Three delivery faults + failed by `PodFailurePolicy` at exit 65. Wrong location was denied with free + capacity, and six closed-boot denials were recorded. +- **Memory.** There were zero OOM kills. The cell node recorded 17 + `memory.max` events. +- **Secret scan and teardown.** 30 evidence files were clean against 23 + retained secrets. Teardown removed every `fleet-mp-677f3c68` container, + cluster, image tag and private credential. inotify was restored from 1024 to + 128. + +The first fresh attempt, `/tmp/fleet-multiplane.Xk3Nc9` (`fleet-mp-34c74885`), +failed in `flux-platform` after 11 phases, before any credential, fixture or +effect. The cell root sync was Ready at r1, but its `lastHandledReconcileAt` +stayed null for the 1500-second bound. Inspection showed the request annotation +and its `kubectl-annotate` field manager were gone five seconds after the +request: the root's own apply had removed them. The harness fix is described +under [suspension and reconcile evidence](gitops.md#review-follow-up-suspension-and-reconcile-evidence), +and `test-flux.py` covers it. That topology was discarded with +`teardown.sh --discard-unknown`, which is not release evidence. + +### Flux-reconciled acceptance (2026-11-15) + +Superseded for the partition and restart claims by the +[acknowledgement run](#flux-acknowledgement-acceptance-2026-11-15). Its harness +suspended Kustomizations with a `kubectl`-prefixed field manager and accepted +existing Ready status after the restart. The record below is kept as it was +observed. + +`task multiplane:acceptance` exited 0 on November 15, 2026 at 20:16 UTC, with +the readiness test gate enabled. Run details: + +- state `/tmp/fleet-multiplane.POC1nn`, prefix `fleet-mp-cff2f712`; +- all 53 bounded phases passed, in 22.4 minutes from build to teardown with + cached base images; +- SHA-256 of `source-SHA256SUMS` (149 entries): `f9cbb463949580c1b08216c3b7730a83a8a8faf63a6eff25f904672d08a4c2d2`; +- site binary `ff5c1b26…077a` and host binary `3e03201a…e4b4` (`binary-SHA256SUMS`); +- site image `sha256:cf6871facaefb2d577d5ece8cb7f94b7f6e3b43f3589eb8d22b16890f20b8112`, + pulled by the cell by that registry digest. + +The 39 scenarios of the earlier run are preserved, as the same phases or +documented equivalents: + +| Earlier phase | Now | +| --- | --- | +| `milo-bootstrap` (Docker Milo/etcd) | `milo-bootstrap` (credential enrollment and fixtures) plus `flux-milo`, against Flux-managed Milo workloads | +| `federation-bootstrap` (`helm install` Karmada) | `topology`, `flux-bootstrap-*`, `flux-platform`, `federation-enrollment` | +| `site-image-load` (`kind load`) | `site-image-push` (registry, pulled by digest) | +| `kro-install` (`helm install`) | `flux-platform` (cell `HelmRelease kro`) | +| `site-install` (`kubectl apply`) | `flux-site` (revision 2) and `site-install` (checks only) | + +The 14 new phases are `flux-tools`, `topology`, `flux-source`, three +`flux-bootstrap-*`, `flux-milo`, `flux-verify`, `flux-drift`, `flux-restart`, +`flux-fail-closed`, `flux-retention`, `flux-final` and +`federation-enrollment`. The sanitized evidence records the following. + +- **Source.** Seven revisions were pushed from the dirty checkout at HEAD + `d7ff793b`, each with its per-file SHA-256 list (55 files): + - r1 `38e1c0b6…`, r2 `470cae7a…`, r3 `d26bf3d5…`; + - r4 `a3931e63…` (bad kro chart), r5 `123ccb2c…`; + - r6 `b826eb5b…` (claim removed), r7 `d3a9fdf8…`. + + All three clusters ended at `local@sha256:d3a9fdf8…3122dff82`. +- **Flux.** Flux v2.9.6 ran with the CLI and `install.yaml` digests verified, + and the four controllers digest-pinned on each cluster. + - Every Kustomization and HelmRelease was Ready at the current generation + and revision. + - The Karmada chart artifact digest was `773ab194…34fe`, release v1. The kro + release recorded chart `0.9.4+4e8de4d34b7e`, release v1. + - `DependencyNotReady` was observed for 13 Kustomization states across the + cell and hub chains. Six bootstrap observations had no applied revision or + inventory; seven during r2 retained their r1 revision and inventories. +- **Ownership.** The `fleet-site` inventory was exactly the FleetSite. The six + generated site objects carried kro node labels and no Flux label or + inventory entry. No Job, Pod, handoff or Secret appeared in any Flux + inventory. +- **Drift.** These changes were corrected by Flux, not by the harness: + - the revoked observer RoleBinding was restored under a new UID; + - the kro Deployment scaled to 0 was restored by helm-controller, with the + same UID, still release v1, and a drift event recorded; + - the deleted Karmada interpreter was recreated over the remote kubeconfig; + - a widened `fleet-site-kro` grant was reverted. + + The journal, Jobs, PVC/PV and custody did not change. +- **Restart.** Every Flux controller Pod on the three clusters was replaced + and managed objects were observed Ready. That historical run did not check + acknowledgement of each new reconcile request, so it does not prove every + object re-reconciled after restart. Helm release versions stayed at 1; + inventories, Jobs, the journal and custody were unchanged. +- **Fail-closed.** With r4, the kro chart source failed with + `OCIArtifactPullFailed` and the kro Kustomization with `HealthCheckFailed`. + The graph and FleetSite were `DependencyNotReady`. The FleetSite stayed at + r3 with marker `r3`, and the kro Deployment and site were unchanged. r5 + converged. +- **Retention.** r6 removed the claim from the inventory without deleting it. + The PVC `05b3b322…` and PV `37468f59…` (`Retain`), the journal and custody + were unchanged, and r7 re-adopted the same claim. +- **PXE.** The worker Pod was force-deleted at `installer-started` with its + domain running, and the Job controller replaced it in the same Job. The Job + was then deleted and kro recreated it. The run recorded one install + operation, with one network-installer QEMU start followed by one disk-only + start. Contention, partition (public Ready False with the Job Complete), heal, + idempotent install, lifecycle, nine reflection faults, release and reuse, + three delivery faults, wrong-location denial and six closed-boot denials all + passed as before. +- **Memory.** There were zero OOM kills. The cell node recorded 172 + `memory.max` reclaim events and no OOM. +- **Secret scan.** 27 evidence files were clean against 23 retained secrets. + Teardown removed every `fleet-mp-cff2f712` container, including the registry, + all three kind clusters, the image tags and private credentials. inotify was + restored from 1024 to 128. + +Two earlier attempts with this design never reached a pass: + +- `/tmp/fleet-multiplane.SQ5zAp` (`fleet-mp-bfe2f43e`) failed in + `flux-bootstrap-platform`: the sync objects were applied in the same batch + as the Flux CRDs. +- `/tmp/fleet-multiplane.SSCrNg` (`fleet-mp-8f36be4c`) was a diagnostic run + left running after a `flux-verify` check rejected Flux's digest-suffixed OCI + chart version. Its remaining phases were then driven piecewise to find two + more harness defects: a restart check that compared Deployment rather than + Pod UIDs, and a reworded log marker. It also showed the platform node under + reclaim pressure at a 1900 MiB cap. + +Both were stopped or discarded with `teardown.sh --discard-unknown`, which is +not release evidence. The fixes are in the recorded run. + +### Kubernetes and kro execution acceptance (2026-11-15, superseded installation path) + +This run installed kro, Karmada and the site imperatively, and ran Milo as +Docker containers. Its execution findings are re-established by the +Flux-reconciled run above. + +`FLEET_MULTIPLANE_INOTIFY=1024 hack/multiplane/run.sh` (the command behind +`task multiplane:acceptance`) exited 0 on November 15, 2026 at 18:08 UTC. Run +details: + +- state `/tmp/fleet-multiplane.3TSkFC`, prefix `fleet-mp-b6b817c8`; +- all 39 bounded phases in `evidence/phases.jsonl` passed, in about 8.5 + minutes from build to teardown with cached base images; +- SHA-256 of `source-SHA256SUMS` itself: `20ce9da37d883eb223604c6a46e325dadba90a13dab8d1694a95c63b52feb9aa`; +- site image ID `sha256:ab24def82ee40395698845b9e491c31a9012371c0d914d7da1a0324600024cb0`. + +The sanitized evidence records the following. + +**kro and the site** (`kubernetes-execution.json`): + +- kro v0.9.4 ran image `registry.k8s.io/kro/kro@sha256:eaf9fbad…`, chart + archive `ceeb6307…`, in RBAC `aggregation` mode. +- RGD `fleet-site` was `Active`. `FleetSite/site` was `ACTIVE`, with runtime, + boot and observer Available, boot origin a ClusterIP, and three delivered + handoffs. +- The site volume was `fleet-site-retain`/`Retain` and not managed by kro. +- Exactly three kro-created worker Jobs remained: one install (epoch 1) and + two cleanups (epochs 1 and 2). Each was `Complete` with one succeeded Pod at + exit 0. + +**Interruption** (`interrupt.json`): + +- With the install `installer-started` and its domain running, the worker Pod + was force-deleted. The Job controller recorded `failed: 1` and started a + replacement Pod in the same Job UID. +- The Job was then deleted, still `installer-started`. kro recreated it under + a new UID, and its worker completed the same operation. +- The journal holds one install. libvirt's QEMU log shows exactly one + firmware-network installer start followed by one disk-only start. The guest + logs show one partition, one installer receipt and one disk-boot receipt. + +**Worker RBAC:** the per-operation token could read its own handoff only. +`get` on another name, list, status and spec patches, Secrets, ConfigMap +creation and Job reads were forbidden. + +**Partition:** the install Job was `Complete` while consumer A's public Ready +stayed False. Heal, the repeated install and all nine reflected-result faults +were then rejected as before. + +**Lifecycle** (`lifecycle.json`): the runtime, boot and observer Pods were +recreated, and the completed Job was recreated with a verified no-op replay +(one Pod, exit 0). Unchanged throughout: + +- journal bytes; +- QEMU starts (2); +- PVC/PV UIDs and the Retain policy; +- domains (none); +- consumer A Ready/Bound. + +The observer republished afterwards. + +**Delivery faults** (`delivery-faults.json`): the duplicate, wrong-cell and +stale-epoch handoffs each produced one Pod at exit 65 and a Job `Failed` with +reason `PodFailurePolicy`. They wrote no status, left the journal unchanged and +left consumer B Bound. kro pruned them after deletion. + +**Release, reuse and location:** + +- Released projection for A and B, and reuse Bound for B in epoch 2. +- Wrong-location denial with free capacity: six custody records and the + journal were unchanged. +- Six live closed-boot HTTP denials through the boot Service from the runtime + Pod. No domains or disks remained. +- Zero OOM events in the runtime Pod cgroup, the cell node cgroup, and the + site and kro containers. + +The secret scan checked 12 evidence files against 22 retained secrets. +Teardown removed every `fleet-mp-b6b817c8` container, both kind clusters, the +site image tag and private credentials, and restored inotify from 1024 to 128. +This is local TCG and legacy-BIOS PXE evidence only. KVM, UEFI, production +authority and production equivalence remain false in `summary.json`. + +The first attempt with this design, `/tmp/fleet-multiplane.e7atDk` +(`fleet-mp-ffab61d0`), passed every phase through `install-repeat`, including +both interruptions and exact resume. It then failed at `lifecycle` on a harness +defect: `k8s_evidence.get` rejected a `config` argument. The failure handler +stopped only that run's containers. Its stopped topology was then explicitly +discarded with `teardown.sh --discard-unknown`, which is not release evidence. +The defect is fixed, and `hack/multiplane/test-k8s-evidence.py` now runs every +helper command against a fake `kubectl` in the offline harness tests. + +### Earlier runs (superseded execution model) + +Runs before this change executed the cell as a `fleet-multiplane cell` process +started by `docker exec` in a privileged provider container. One passed on +2026-11-15 as `/tmp/fleet-multiplane.HkE6e5` (`fleet-mp-a6f50082`, 31 phases). +Others, `/tmp/fleet-multiplane.67Z4yk` and `/tmp/fleet-multiplane.CubymM`, +either passed or completed with manual bootstrap recovery. Their findings +(Milo routing, Karmada delivery and reflection, firmware PXE, disk boot, +reflection-fault rejection, and cleanup and reuse) are re-established by the +run above. Their process-launch and SIGKILL evidence no longer describes how +the cell executes and is not current evidence. + +Two earlier failures inform the current bounds. In +`/tmp/fleet-multiplane.4vyisu`, a 2.5 GiB provider cap caused an installer OOM; +the runtime limit is now 3 GiB and OOM is checked. In +`/tmp/fleet-multiplane.omuBXA`, a shell builtin was executed through +`docker exec`; that path no longer exists. Both retained Unknown custody and +were never treated as release evidence. + +### Offline checks + +```sh +go test -race -count=1 ./... +go vet ./... +task multiplane:test-harness # includes hack/multiplane/test-k8s-evidence.py +shellcheck -S warning hack/multiplane/*.sh hack/local-vm/run.sh hack/local-vm/start-libvirt hack/local-vm/site-runtime +git diff --check +``` + +Deterministic Go tests cover these result faults: wrong-cell, stale/future, +duplicate, missing, wrong operation/digest/allocation/epoch/fence, and Unknown. +They also cover: + +- the worker/observer split: the worker never writes status, and the + observer never executes and never publishes Unknown, absent or mismatched + journal results; +- delivery faults fencing before effects, and cell-label selection; +- restart recovery and exact local asset mapping; +- boot-origin and libvirt-URI validation, and read-only providers; +- boot evidence kept outside the journal directory; +- NAT forwarding only for a remote boot Service; +- project identity collisions, concurrent allocation, and unknown cleanup + preventing capacity reuse. + +They do not pretend to implement Karmada, kro or the Job controller in memory. +Only the live command establishes federation, kro, Job and PXE acceptance. + +A known shared-lifecycle diagnostic edge remains: contenders with identical +Machine UIDs in different projects can receive `ErrRecordInvalid` rather than +`InsufficientCapacity`. Tests accept either fail-closed outcome and require one +exclusive winner and no reuse after Unknown cleanup. This harness does not edit +shared core lifecycle code to change that behavior. + +### Known limitations of the local MVP + +Independent review on 2026-11-15 found no blocking safety issue for this +disposable local MVP. It recorded these limits, which the harness does not hide: + +- **The provider journal is the sole fence.** The local provider's + `/var/lib/fleet-local/journal.json` alone binds operation IDs, allocation epoch, + fence and receipts to the physical asset. If provider state is deleted or + replaced and old handoffs are replayed, the provider admits them as new and can + re-image the disk. That is acceptable only because every site volume here is + disposable and created fresh per run. The volume uses `Retain` and is not + managed by kro, but nothing prevents an operator from deleting the PV. Never + reset, delete or replace a journal for a provider whose device or disk is + retained. +- **Location validation is local to this runner.** `ErrLocationNotServed` is + enforced by `internal/multiplane.Runner.request` for its single `local` + location and configured cell. The shared allocator, the standalone runner and + the production manager do not implement location binding. +- **Some crash windows remain Unknown indefinitely.** These include an ambiguous + `virsh create` after `installer-started` or `disk-started` was retained, a crash + after disk creation but before `prepared` (exclusive creation then refuses to + overwrite), and a lost PXE network, lease or broker delivery. The provider will + not restart a possibly executed installer. Custody, capacity and diagnostics stay + retained. Do not reset the journal or retry under new authority to "unstick" it. + No automated operator resolution exists. Resolving such a run means discarding + the whole disposable topology after inspection (`teardown.sh --discard-unknown`). +- **Test coverage seams.** Deterministic tests use identical scoped and physical + asset IDs in places and exercise recovery through the non-PXE provider path. + The live run is therefore the evidence for real firmware PXE with in-flight + worker Pod and Job interruption, exact resume and a single installer start. +- **Single-node site.** The runtime, boot service, observer and workers share + one kind node and one `ReadWriteOnce` local-path volume; the journal lock + depends on that. Losing the runtime Pod stops any running guest; the + operation then stays Unknown. Multi-node or HA execution is not designed. +- **kro is a broad reader, and graph authors are trusted.** kro must read + delivered handoffs, including the fence token in `requestJSON`, to enumerate + them. Its informers need cluster-wide get/list/watch on every referenced + kind. Its writes are namespaced and admission-checked, but an admitted worker + still reaches root libvirtd and the journal; see the + [trust model](site-execution.md#ownership-and-trust-model). Disabling + `dispatch` or deleting a handoff prunes worker Jobs without cancelling + effects. See [site execution](site-execution.md#lifecycle-and-retention). +- **Shared-service revisions roll the runtime.** A services-layer change, such + as a new site image, recreates the runtime Pod and stops any running guest. + The operation then stays Unknown. No migration from the earlier kro-owned + composition is implemented. Retained historical Jobs also have immutable pod + templates: changing the runtime-derived worker image may block kro dispatch. + This upgrade risk has not been exercised; image upgrades require a fresh + disposable topology until a tested upgrade lifecycle exists. See + [site lifecycle limitations](site-execution.md#lifecycle-and-retention). +- **Interrupt timing.** An emulated install takes about a minute. The Job + deletion is issued as soon as the replacement Pod exists; a much faster + guest could finish first, and the phase would then fail rather than pass + vacuously. +- **GitOps seams.** The Flux source is a plain-HTTP, unsigned registry on the + kind network. Credentials are enrolled imperatively, not with SOPS or + External Secrets. The Karmada API is reconciled with its admin kubeconfig, + and the three clusters share one VM. Revisions are staged from the checkout; + nothing is published. See [what is not production](gitops.md#what-is-not-production). + The journal volume's Flux policy (`prune: disabled`, `ssa: IfNotPresent`) + protects it from reconciliation, but not from an operator deleting the PV. +- **Qualification scope.** A non-disposable provider, KVM, UEFI, real hardware/BMC, + production Milo IAM, quota and networking remain out of scope. + +The production gaps include caller-preserving admission, source-use IAM, +service-owned quota recovery/settlement, source publication custody, true project +provisioning/deletion, cell enrollment and revocation at the hardware effect +boundary, live hardware/network attestation, token rotation, sustained outage +behavior beyond configured freshness, and independent durable/HA failure domains. +There is no production-equivalence or production-readiness flag to enable. + +### Automation notes + +Source fingerprints include all internal Go packages, `config/multiplane`, +`config/site`, the harness, and module manifests, and exclude Python caches. +Each Flux source revision also has its own per-file SHA-256 list in evidence. Phase deadlines are +enforced even with partial output or closed stdout. Image-tag removal is +reported separately from container cleanup. Teardown does not verify that +every Docker volume is absent. Scenario booleans in the summary derive from +successful bounded phases and checked log markers. The partition check runs +with the host publisher stopped, as described above. diff --git a/docs/operations/site-execution.md b/docs/operations/site-execution.md new file mode 100644 index 00000000..0bf57f76 --- /dev/null +++ b/docs/operations/site-execution.md @@ -0,0 +1,386 @@ +# Kubernetes-native site execution + +The [multi-plane acceptance](multiplane.md) runs selected-cell execution as +ordinary Kubernetes workloads. The cell's Flux owns the long-lived site services +directly, and an installed [kro](https://kro.run) controller creates only the +per-operation worker Jobs and their RBAC. Before Kubernetes execution, a hand-written cell +process was started with `docker exec` inside a privileged libvirt container. +That process listed and watched handoffs, executed them, retried them, and +wrote status. Now Kubernetes controllers own scheduling, retries, Pod +replacement and dependency ordering. Fleet code is left with only the parts +that carry authority: + +- exact-request replay against the provider journal; +- fencing; +- journal-derived observation. + +This is an **implemented local acceptance composition**, not a production +deployment. The [PXE installation proposal](../enhancements/pxe-installation/README.md#location-execution) +still defines the target contract. Physical Redfish, KVM, UEFI, production +IAM and HA remain out of scope. + +## Versions + +| Component | Pin | Why | +| --- | --- | --- | +| kro | v0.9.4, chart `oci://registry.k8s.io/kro/charts/kro` manifest digest `sha256:4e8de4d34b7e2c3cede958e140e26cd6d34a377062e63caf355a636d2bf4a67c` (archive layer SHA-256 `ceeb630764eb79ca4220dfdcc2907b819a27c30f68cb60d09c1ae3fa2c58b5cd`), image `registry.k8s.io/kro/kro:v0.9.4@sha256:eaf9fbaddd9d7f6cf400a8d47ab066b14cbef22b92a79be7bbdc7b3673376fb9`, installed by the cell's Flux `HelmRelease kro` | Newest patch of the newest minor with a settled release. v0.10.0 was published on 2026-11-10, five days before this work, and is deliberately not used. | +| Kubernetes | kind node v1.35.0 (digest-pinned in `topology.sh`) | Job `podFailurePolicy` and `podReplacementPolicy: Failed` are both available. | +| Site image | Built per run from `hack/local-vm/Containerfile` target `site`; the binary comes from a named build context that holds only the checksum-verified `fleet-multiplane`. Pushed to the run registry and referenced by digest in the source. | One image for runtime, boot service, observer and workers | + +Version sources were read at the pinned tag: the kro installation, schema, +external reference, collection and readiness documentation; the kro Helm chart +values; and kro's `aggregation` RBAC mode. Flux pulls the chart by manifest +digest, and `flux-verify` checks the release history records that digest. See +[Flux-reconciled local environment](gitops.md) for the installation path. + +## Topology on the selected cell + +```text + cell Flux (one source revision, scoped identity per layer) + ┌──────────────────┬───────────────────────┬──────────────────────────┐ + ▼ ▼ ▼ ▼ +fleet-site-base fleet-site-services fleet-site-graph fleet-site-dispatch +ns, Retain PVC, runtime, boot and ResourceGraphDefinition HandoffDispatcher/dispatcher +identities, RBAC, observer Deployments; fleet-handoff-dispatcher (cell, scoped asset, dispatch) +kro grants, boot Service (fixed │ +admission policy ClusterIP); policy param │ kro + ▲ externalRef (read only, readiness-gated) ▼ + └──────────────────────────────────── per delivered handoff (forEach): +Karmada ──delivers──▶ MachineAllocationHandoff ─ external collection ─▶ ServiceAccount, Role + (fleet-coordination, label-selected by cell) (resourceNames: that handoff, + get), RoleBinding, bounded Job + +VM runtime (libvirtd, privileged) ◀─ libvirt socket ─ worker Job ── replays one operation + └─ firmware DHCP/iPXE ─NAT─▶ boot Service ─▶ boot Deployment (journal read-only) +observer Deployment (journal read-only; only handoff status writer) + ╲_____________ fleet-site-state PVC (Retain), Flux-owned __________╱ +``` + +| Resource | Owner (single writer) | Privileges | Volume subpaths | Role | +| --- | --- | --- | --- | --- | +| `fleet-site` namespace, `fleet-site-retain` StorageClass, `fleet-site-state` PVC | Flux `fleet-site-base` (`config/site/base`; never pruned; class and claim created once) | — | — | Durable journal, disks, boot evidence, libvirt socket and QEMU logs. Never in any graph. | +| `fleet-site-runtime`, `fleet-site-boot`, `fleet-site-observer` ServiceAccounts; observer Role and RoleBinding | Flux `fleet-site-base` | Observer: get/list/watch handoffs; update handoff status | — | The observer is the only cell identity that writes handoff status | +| `fleet-site-kro` ClusterRole, `fleet-site-kro-workers` and `fleet-site-kro-worker-rbac` Roles and bindings, two `ValidatingAdmissionPolicies` | Flux `fleet-site-base` | — | — | kro's narrowed grant and the shape of its writes ([trust model](#ownership-and-trust-model)) | +| `fleet-site-runtime` Deployment | Flux `fleet-site-services` | **privileged** (bridge, dnsmasq, tap, iptables) | `journal` rw, `libvirt-socket` rw, `libvirt-log` rw, `boot-evidence` ro | libvirtd and QEMU only. No API token, no TCP listener. | +| `fleet-site-boot` Service and Deployment | Flux `fleet-site-services` | uid 0 with all capabilities dropped, read-only root filesystem, no API token | `journal` **ro**, `boot-evidence` rw | Boot decision point and artifact delivery. The Service has a fixed ClusterIP (`10.96.0.80`). | +| `fleet-site-observer` Deployment | Flux `fleet-site-services` | uid 0 with all capabilities dropped, read-only root filesystem | `journal` **ro** | Publishes validated terminal journal results every 10 seconds | +| `fleet-site-worker-policy` ConfigMap | Flux `fleet-site-services` | — | — | Admission parameter: the image worker Jobs must run | +| `fleet-handoff-dispatcher` ResourceGraphDefinition, `HandoffDispatcher/dispatcher` | Flux `fleet-site-graph`, `fleet-site-dispatch` (each a scoped identity; never pruned) | — | — | Orders per-operation work and projects non-authoritative status | +| `w-` ServiceAccount, Role, RoleBinding, Job | kro `forEach` over delivered handoffs | get on exactly one handoff; uid 0 with all capabilities dropped; read-only root filesystem | `journal` rw, `libvirt-socket` rw, `boot-evidence` ro | Executes or resumes that one retained operation | + +## Ownership and trust model + +This split is **implemented**, and is exercised by the acceptance phases named +below; see [verification](multiplane.md#verification-and-remaining-gaps) for +the run record. It supersedes the earlier composition, in which the graph +also created the three shared Deployments, the boot Service and their +ServiceAccounts. + +**One writer per object.** Each shared site object carries exactly one Flux +`kustomize.toolkit.fluxcd.io/name` label, appears in exactly that layer's +inventory, and carries no kro label or owner reference. Every object kro writes +is a `w-` Job, ServiceAccount, Role or RoleBinding, has a kro node +label, and is in no Flux inventory. `flux-verify` (before dispatch), +`flux-graph-lifecycle` (with workers present), `flux-drift` and `flux-final` +each run this audit (`flux.py ownership`). This audit uses labels, owner +references, RBAC and inventories, not server-recorded `managedFields`. Shared +inventory membership is matched by namespace/name prefix rather than kind, so +same-named resources can satisfy each other; the base inventory is not checked +for exactness. Independent review confirmed the expected kinds in the saved +live inventory. These checks are evidence of the intended ownership split, not +a complete proof that no other field manager has written an object. + +**Dependency and health ordering.** + +1. `fleet-site-base` depends only on the handoff CRD (`fleet-coordination`). +2. `fleet-site-services` depends on the base. It waits for all three + Deployments to be Available; the runtime's readiness probe requires libvirtd. +3. `fleet-site-graph` depends on the kro release and the base, and is healthy + when the RGD is `Active`. +4. `fleet-site-dispatch` depends on the graph, the services and the federation + member identity. It is healthy only when kro reports the instance `ACTIVE`. + +Inside the graph, every worker template references the runtime, boot and +observer Deployments and the boot Service through `externalRef` with +`readyWhen`. kro v0.9.4 treats a missing or unready reference as pending data. +It then creates no new worker object and **disables pruning** for that +reconcile, so a shared-service outage never deletes an existing Job. Shared +infrastructure does not depend on kro: in `flux-fail-closed`, a broken kro +release blocks only the graph and the dispatcher, while the base and services +layers apply the same revision without restarting any service. + +**kro's narrowed authority.** kro v0.9.4 watches every kind it manages or +references with cluster-wide metadata informers, so its aggregated +`fleet-site-kro` ClusterRole keeps cluster-wide get/list/watch. That covers +Deployments, Services, PVCs, ServiceAccounts, Jobs, Roles, RoleBindings and +handoffs. Its only cluster-wide write is to its own `HandoffDispatcher` +instances. Writes are namespaced: + +- Jobs and ServiceAccounts in `fleet-site`; +- Roles and RoleBindings in `fleet-coordination`. + +kro has no Deployment, Service, PVC, ConfigMap or Secret write, and no handoff +spec or status write. The kro chart's own static role also granted +cluster-wide ConfigMap read/write, which kro v0.9.4 never uses. A live `rbac` +probe found it, and the `HelmRelease` now removes it with a post-renderer +patch. A JSON-patch `test` guards that patch, so a changed chart fails the +release rather than removing another rule. The chart grants kro keeps are +cluster-wide CustomResourceDefinition management, which it needs to create +each graph's kind, plus Leases and Events. `kro-rbac.json` records them as +remaining authority. RBAC alone would still let a graph revision create any +Job in `fleet-site`, including one that runs as the observer (the status writer) +or as a privileged container. Two `ValidatingAdmissionPolicies` apply only to +kro's own requests and pin those writes to the worker shape: + +- a `w-` name matching the Job's handoff label; +- the Job's own ServiceAccount; +- one container from the image the shared services run (a parameter written + by the services layer); +- no privilege or added capability; +- no host namespaces; +- only the journal claim and `emptyDir` volumes. + +A Role may grant only `get` on its own handoff, and a RoleBinding may bind only +its own Role to its own ServiceAccount. The `rbac` phase proves this with real +`auth can-i` checks as kro's identity and server-side dry runs. Valid worker +shapes are admitted, and eight violations are each denied by policy +(`kro-rbac.json`). The policies cover CREATE and UPDATE, not DELETE. kro +can still delete any ServiceAccount in `fleet-site` and any Role or RoleBinding +in `fleet-coordination`, including Flux-owned identities and observer or +federation RBAC. Normal pruning targets only tracked worker objects, and the +policies prevent adopting these shared objects, but a controller bug or +compromise could interrupt delivery or status until Flux repairs them. Delete +denials are not covered by the current probes. + +**What graph authors are still trusted with.** This is not a sandbox for +untrusted graph revisions: + +- A worker mounts the journal read-write and reaches root libvirtd through + its socket. A graph author who changes the worker command, within the + admitted image, can therefore drive the hypervisor and rewrite the journal. +- kro must read every delivered handoff, including the fence token in + `requestJSON`, to enumerate them. +- kro keeps cluster-wide CRD create/update/delete from its chart, so a + compromised kro controller could alter or remove CRDs it does not own. +- The services layer chooses the privileged runtime image and its + configuration. +- The same source owns the admin-applied base, including these policies. + +Source review remains the control for all layers. The admission policies remove +the paths a graph revision would otherwise have to the observer's +status-writing token, to a privileged Pod, to another image or volume, and to +other namespaces. Production still needs a narrower action broker in place of +the libvirt socket; see [practical separation decisions](#practical-separation-decisions). + +**Migration from the earlier composition** is not implemented. Every acceptance +run creates a fresh cell. An existing site with kro-owned shared Deployments +would need these steps: + +1. Quiesce: no unfinished operation, and dispatch disabled. +2. Publish a graph revision without the shared resources, and confirm kro + removed them. A gap stops new boots, which is safe but not cancellation. +3. Publish the services layer. + +Doing it in one revision would leave two writers contending for the same +objects. This sequence is proposed only. + +### Practical separation decisions + +- **Only the VM runtime sets `privileged: true`.** Guests run under libvirtd in + that Pod, not under a worker. Losing a worker Pod or Job therefore loses only + an observer process; the installer continues. Losing the runtime Pod stops + any guest. The operation then stays Unknown and capacity stays occupied. +- **Workers reach libvirt through a Unix socket on the site volume** + (`qemu:///system?socket=/run/fleet-libvirt/libvirt-sock`). They hold no + network credential, and nothing listens on TCP. The provider accepts only + that URI shape. This socket still grants broad control over root libvirtd, + including domain definitions backed by paths in the runtime filesystem. + Dropped Linux capabilities do not isolate workers from the runtime's power. + The fixed worker image and graph are trusted in this disposable proof; + production requires a narrower action broker. +- **The boot service is a separate Deployment behind a ClusterIP Service.** The + provisioning bridge uses libvirt NAT forwarding. DHCP hands firmware an + `http://:8080/...` boot file. The Service's ClusterIP is fixed + (`10.96.0.80`, in the static band of kind's default `10.96.0.0/16` Service + range) and comes from the environment's `FLEET_BOOT_SERVICE_IP`. Flux + substitutes it into the runtime and boot Deployments, and kro reads it from + the Service for the workers. A recreated Service therefore keeps the boot + origin that running Pods were configured with; `flux-drift` deletes it and + proves this. The runtime + entrypoint adds a `mangle` chain: traffic from the bridge may reach only + local addresses (DHCP), broadcast, and the boot Service port. Everything + else is dropped. The boot service reads the journal read-only and writes + only its own delivery evidence in a separate subpath. Workers read that + evidence when they verify network boot. +- **One shared volume, separate subpaths and mount modes.** All site Pods run + on the single kind node, so one `ReadWriteOnce` local-path volume serves + them. The journal `flock` is effective because every writer shares one + kernel and inode. +- **The observer is a Deployment, not part of the Job.** Management requires + reflected observations to be fresher than one minute. Refreshing them is a + persistent site service, so freshness does not depend on any Job's + lifetime. It also keeps one status writer per cell. + +## Authority and failure contract + +- **Exact operation before effect.** A worker reads only its handoff. It + checks the cell, checks that the name is derived from the operation ID, and + validates the intent. `LocalAssetMapping` re-reads the same handoff and + compares digests. The provider then replays the journal under the exact + operation ID. A digest conflict, fence mismatch, stale epoch, or an + unfinished prior operation stops before any effect. +- **Worker exit codes are the Job contract.** + - `0`: a terminal result was validated against the journal. + - `65`: fenced, conflicting or invalid authority. `podFailurePolicy` fails + the Job with no retry. + - `75`: Unknown or transport error. The Job controller retries, up to + `backoffLimit: 6` and `activeDeadlineSeconds: 3600`. + + Disruption-target Pod conditions are ignored, not counted. +- **The journal lock serializes effects.** `podReplacementPolicy: Failed` + delays ordinary replacement until the old Pod is terminal. Force deletion + can remove its API object while the old process still runs, and Job recreation + can also overlap workers. The provider's non-blocking journal lock is the + actual execution guard in these cases; a contender exits 75. A recreated + worker replays the same retained operation. +- **Job Complete and kro Ready grant nothing.** The worker never writes + status. The observer publishes only a terminal journal result that passes + `ValidateResult`. Management accepts only the Karmada-reflected observation + that passes `ValidateReflection`, which checks: + - exact cell, operation and intent/input digests; + - freshness; + - a single replica. + + The acceptance shows this directly: during the hub partition the install Job + is `Complete` while public Machine `Ready` stays `False`. A failed Job leaves + the operation Unknown; it never releases capacity. +- **Delivery faults fail closed.** kro selects handoffs by cell label only for + convenience. A duplicate under another name, a wrong-cell intent and a + stale-epoch replay each get a Job. The acceptance injects these faults with + no pending operation: each fails once by policy without touching the journal. + While another operation is unfinished, the provider may reject a stale + request as Unknown before checking its fence. That worker exits 75 and may + exhaust its retry budget instead of failing once with exit 65; no effect is + authorized in either case. + +## Lifecycle and retention + +- `fleet-site-state` uses a StorageClass with `reclaimPolicy: Retain`. Only + `fleet-site-base` declares it. The services mount it and the RGD references + it through `externalRef`, so neither the services layer nor the dispatcher + instance or graph can delete it. kro v0.9.4 skips external references when it + deletes an instance. +- **Operation graph lifecycle cannot remove shared infrastructure.** + `flux-graph-lifecycle` suspends the dispatcher's Flux layer and deletes the + `HandoffDispatcher` instance. kro removes only that handoff's Job, + ServiceAccount, Role and RoleBinding. Every shared object keeps its UID, + including the Deployments, Service, ServiceAccounts, RBAC, admission policies, + PVC and StorageClass. The journal, PV, guests and custody are unchanged, and + the handoff keeps its terminal observation. Resuming lets Flux recreate the + instance; kro recreates the workers and the Job replays a verified no-op. + kro deletes Jobs without a propagation policy, so batch/v1 orphans their + terminal Pods; the evidence lists them. +- **Never delete or replace the journal** of a provider whose disk or device + is retained. A fresh journal would admit replayed handoffs as new + operations; see [known limitations](multiplane.md#known-limitations-of-the-local-mvp). +- After the installation is terminal, recreating the Flux-owned runtime, boot or + observer Pods does not change journal bytes, guest starts, volume identity or + public allocation. Neither does + recreating a completed Job, which only replays a verified no-op. The + `lifecycle` phase asserts all of this. +- **Pruning is not cancellation.** Setting `spec.dispatch` false, deleting a + handoff, or deleting the `HandoffDispatcher` can prune worker Jobs. kro v0.9.4 does not + specify cascading deletion for pruned Jobs, so dependent worker Pods may be + orphaned and continue to completion, as may their guests. The observer can + still publish a completed result if its handoff exists. Re-enabling dispatch + can create a competing worker that exits 75 on the journal lock. The harness + does not exercise pruning an active Job; its explicit Job deletion uses + background propagation. Neither dispatch nor object deletion is an authorized + cancellation or fencing protocol. +- **Shared-service changes are reviewed source revisions.** Changing the + services layer, such as a new site image, rolls the Deployments. The runtime + uses `Recreate`, so a rollout stops any running guest. The operation then stays + Unknown and capacity occupied; schedule such revisions with no operation in + flight. Dispatch changes are also source revisions, and kro remains the + only writer of the per-operation objects. Flux's `fleet-site-dispatch` + inventory is exactly the `HandoffDispatcher`; see [ownership](gitops.md#ownership). + **Image upgrades are not qualified:** historical Jobs are retained, and the + graph derives their image from the runtime Deployment. A changed image can + therefore cause kro to update an immutable Job pod template and block later + dispatch. This is a review-identified risk, not an exercised upgrade failure. + Instance recreation has verified no-op replay with the same image; it does + not qualify upgrades. Use a fresh disposable topology for image changes until + an upgrade lifecycle is implemented and tested. +- kro's controller is not in the authority path. If kro is down, no new + worker is created, existing Jobs continue, and the Flux-owned shared services + keep running and reconciling. Recovery is kro reconciliation followed by + journal replay. + +## Secrets + +The fence token remains inside the handoff's `requestJSON`; this is the existing +federation contract. Cell readers of handoffs are: + +- each worker, for its one handoff only; +- the observer; +- Karmada's member identity; +- kro, which must read handoffs to enumerate them. + +Job specs, Pod arguments, kro instance status and labels carry only handoff +names, the cell name and the scoped asset ID. Worker and observer logs print an +outcome class, never request bodies. The harness creates short-lived tokens for +RBAC probes with names ending in `.token`. It scans every evidence file against +all retained tokens, fences and boot capabilities. + +## What replaced what + +| Removed | Replaced by | +| --- | --- | +| `fleet-multiplane cell` process launched with `docker exec`, its PID file and `kill` signalling | kro-created Jobs and the Job controller | +| `coordination.Cell.Run` list/watch loop and `Reconcile` (execute plus publish) | `Cell.Execute` (worker; no status writes) and `Cell.Publish`/`Cell.Observe` (observer; lookup only) | +| `config/multiplane/cell-rbac.yaml` and an exported cell kubeconfig | Static observer RBAC and kro per-operation RBAC; no cell credential leaves the cell | +| Dedicated privileged provider container and `docker exec` probes | Runtime, boot and observer Deployments; probes through the cell API | +| kro-created runtime, boot and observer Deployments, boot Service and their ServiceAccounts (`FleetSite` graph), with a cluster-wide kro write grant | Flux layer `fleet-site-services` (scoped identity) and identities in `fleet-site-base`; the `HandoffDispatcher` graph references them; kro writes are namespaced and admission-checked | +| `helm install` of kro, `kubectl apply` of the site base and RGD, a `kubectl patch` of `dispatch`, and `kind load` of the image | Cell Flux `HelmRelease`/Kustomizations from a pushed source revision; the image pulled by digest from the run registry ([details](gitops.md)) | + +The single-plane [local VM harness](local-vm.md) still uses its own disposable +container and is unchanged. + +## Implemented versus proposed + +| Behavior | Status | +| --- | --- | +| Flux-owned shared site services and storage; kro-created per-operation RBAC and bounded worker Jobs on a real cell API | Implemented and exercised by `task multiplane:acceptance` | +| Single-writer ownership audit, shared Service drift repair by Flux, graph lifecycle leaving shared services and storage untouched | Implemented and exercised (`flux-verify`, `flux-drift`, `flux-graph-lifecycle`, `flux-final`) | +| Narrowed kro RBAC and admission policies on kro's writes | Implemented and exercised (`rbac`, `kro-rbac.json`); every dispatched Job and its RBAC passed them | +| In-place migration of an existing site from kro-owned shared services | Proposed only ([trust model](#ownership-and-trust-model)) | +| Pod loss and Job deletion mid-install resuming the same operation with one installer start | Implemented and exercised | +| Duplicate, wrong-cell and stale-epoch delivery failing by `podFailurePolicy` before effects | Implemented and exercised | +| Pod/Job lifecycle not changing journal, guest or allocation | Implemented and exercised | +| Facility-edge DaemonSet, multi-node volumes, HA runtime, live hardware fencing | Proposed only | +| Removing the fence token from cell-readable handoff fields (credential broker) | Proposed only ([open questions](../enhancements/pxe-installation/README.md#open-design-questions)) | +| Redfish/BMC execution Jobs | Not implemented | + +## Independent review of the recorded run + +This review covered the run before Flux installation. The +[Flux-reconciled run](multiplane.md#flux-reconciled-acceptance-2026-11-15) +re-established the same execution findings and has not yet been independently +reviewed. + +The reviewer reproduced both binaries byte for byte, verified all 113 source +fingerprint entries and all 39 phase results, and passed the full Go race suite, +vet, offline harness tests and ShellCheck. An adversarial concurrency probe +confirmed that a second worker cannot act while the first holds the journal lock. +No blocker was found for the disposable single-node proof. + +The Job-deletion phase establishes that installation was still at +`installer-started` and that a replacement Job resumed that exact operation. It +does not establish that the replacement worker Pod was already Running or held +the journal lock at the instant its predecessor Job was deleted. Pod interruption +and Job recreation evidence should not be read as a stronger timing guarantee. +That review found that RGD and instance authors remained trusted, because kro's +grant could create workloads using any namespace ServiceAccount, including the +observer's. The current composition closes that path with namespaced kro writes +and admission policies; the remaining trust is listed under +[ownership and trust model](#ownership-and-trust-model). diff --git a/hack/local-vm/Containerfile b/hack/local-vm/Containerfile index f86ddeda..14e4afe6 100644 --- a/hack/local-vm/Containerfile +++ b/hack/local-vm/Containerfile @@ -10,6 +10,14 @@ RUN chmod 755 /usr/local/bin/fleet-start-libvirt COPY --from=guest /out /opt/fleet-local/artifacts ENV FLEET_LOCAL_VM=disposable-container LIBVIRT_DEFAULT_URI=qemu:///system +# Kubernetes site image: the same pinned artifacts plus the checksum-verified +# fleet-multiplane binary from the named build context "fleetbin". Runtime, +# boot service, observer and per-operation worker Jobs all use this image. +FROM tcg AS site +COPY site-runtime /usr/local/bin/fleet-site-runtime +COPY --from=fleetbin fleet-multiplane /usr/local/bin/fleet-multiplane +RUN chmod 755 /usr/local/bin/fleet-site-runtime /usr/local/bin/fleet-multiplane && printf '%s\n' 'unix_sock_dir = "/run/fleet-libvirt"' >> /etc/libvirt/libvirtd.conf + FROM fleet-vm-local AS kvm USER root COPY start-libvirt /usr/local/bin/fleet-start-libvirt diff --git a/hack/local-vm/site-runtime b/hack/local-vm/site-runtime new file mode 100755 index 00000000..2d71dd70 --- /dev/null +++ b/hack/local-vm/site-runtime @@ -0,0 +1,22 @@ +#!/bin/sh +# VM runtime for the Kubernetes site: libvirtd only. Workers reach it through +# the socket directory shared on the site volume; nothing listens on TCP. +set -eu +[ "${FLEET_LOCAL_VM_ACCEL:-}" = tcg ] || { echo 'site runtime requires FLEET_LOCAL_VM_ACCEL=tcg' >&2; exit 1; } +boot_ip=${FLEET_BOOT_IP:?boot Service ClusterIP required} +case "$boot_ip" in *[!0-9.]*|'') echo 'invalid boot Service IP' >&2; exit 1 ;; esac +sock=/run/fleet-libvirt +mkdir -p "$sock" /run/libvirt /var/lib/libvirt/images /var/log/libvirt/qemu +# A previous runtime Pod's socket is stale; libvirtd recreates it. +rm -f "$sock"/libvirt-sock "$sock"/libvirt-sock-ro "$sock"/libvirt-admin-sock +# Firmware on the provisioning bridge may reach this namespace (DHCP) and the +# boot Service only. Anything else forwarded from the bridge is dropped. +iptables -t mangle -N FLEET-PXE 2>/dev/null || iptables -t mangle -F FLEET-PXE +iptables -t mangle -A FLEET-PXE -m addrtype --dst-type LOCAL -j RETURN +iptables -t mangle -A FLEET-PXE -m addrtype --dst-type BROADCAST -j RETURN +iptables -t mangle -A FLEET-PXE -d "$boot_ip" -p tcp --dport 8080 -j RETURN +iptables -t mangle -A FLEET-PXE -j DROP +iptables -t mangle -C PREROUTING -i fleetpxe0 -j FLEET-PXE 2>/dev/null || iptables -t mangle -A PREROUTING -i fleetpxe0 -j FLEET-PXE +virtlogd --daemon +virtlockd --daemon +exec /usr/bin/tini -- libvirtd diff --git a/hack/multiplane/acceptance.sh b/hack/multiplane/acceptance.sh new file mode 100755 index 00000000..54d3c27a --- /dev/null +++ b/hack/multiplane/acceptance.sh @@ -0,0 +1,45 @@ +#!/usr/bin/env bash +# Ordered acceptance phases over an already bootstrapped topology. Each phase is +# bounded and recorded in evidence/phases.jsonl; the first failure stops the run. +set -euo pipefail +umask 077 +state=${1:?private state directory} +export DOCKER_CONTEXT=colima-fleet-acceptance-tcg +host="$state/fleet-multiplane-host" +ph() { python3 hack/multiplane/harness.py phase --state "$state" --name "$1" --timeout "$2" --echo -- "${@:3}"; } +step() { ph "$1" "$2" bash hack/multiplane/steps.sh "$1" "$state"; } +flux() { ph "flux-$1" "$2" python3 hack/multiplane/flux.py "$1" "$state"; } + +ph rbac 600 python3 hack/multiplane/verify-rbac.py "$state" +ph allocate 900 "$host" allocate --config "$state/acceptance.json" +step verify-contention 120 +ph admit-install 900 "$host" admit-install --config "$state/acceptance.json" +step await-delivery 300 +step partition 300 +step dispatch 900 +step interrupt-pod 1200 +step interrupt-job 600 +step resume 1800 +step worker-rbac 120 +step partition-readiness 900 +step heal 1200 +ph install 900 "$host" install --config "$state/acceptance.json" +ph install-repeat 900 "$host" install --config "$state/acceptance.json" +step lifecycle 900 +flux graph-lifecycle 1200 +flux drift 900 +flux restart 1200 +flux fail-closed 1500 +flux retention 1500 +ph reflection-faults 900 python3 hack/multiplane/reflection-faults.py "$state" +ph release 1200 "$host" release --config "$state/acceptance.json" +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 release-status-b 120 +step wrong-location 300 +step boot-denials 300 +step flux-final 900 +ph evidence 300 python3 hack/multiplane/evidence.py "$state" diff --git a/hack/multiplane/evidence.py b/hack/multiplane/evidence.py new file mode 100755 index 00000000..95c96ee5 --- /dev/null +++ b/hack/multiplane/evidence.py @@ -0,0 +1,276 @@ +#!/usr/bin/env python3 +"""Capture private diagnostics and emit an explicit allowlist-only summary. + +Private copies stay in /provider-private. Only evidence/ is shareable, +and run.sh scans it against every retained credential before reporting. +""" +import datetime +import hashlib +import json +import os +import pathlib +import re +import subprocess +import sys +import tarfile + +s = pathlib.Path(sys.argv[1]) +prefix = (s / 'prefix').read_text().strip() +ev = s / 'evidence' +os.environ['DOCKER_CONTEXT'] = 'colima-fleet-acceptance-tcg' + + +def out(*args): + return subprocess.check_output(args, text=True, timeout=60) + + +def fail(message): + raise SystemExit(message + '; retain diagnostics and Unknown custody') + + +def kubectl(*args): + return out('kubectl', '--kubeconfig', str(s / 'cell-admin.yaml'), '--request-timeout=30s', *args) + + +def kget(*args): + return json.loads(kubectl(*args, '-o', 'json')) + + +def runtime(*command): + return kubectl('-n', 'fleet-site', 'exec', 'deploy/fleet-site-runtime', '-c', 'libvirt', '--', *command) + + +def copy_out(source, destination): + """Stream a runtime Pod directory into private state through the cell API.""" + destination.mkdir(mode=0o700, parents=True, exist_ok=True) + p = subprocess.Popen(['kubectl', '--kubeconfig', str(s / 'cell-admin.yaml'), '-n', 'fleet-site', 'exec', 'deploy/fleet-site-runtime', '-c', 'libvirt', + '--', 'tar', '-C', source, '-cf', '-', '.'], stdout=subprocess.PIPE) + with tarfile.open(fileobj=p.stdout, mode='r|') as archive: + archive.extractall(destination, filter='data') + if p.wait(timeout=120): + fail('could not copy ' + source + ' from the runtime Pod') + + +memory_events = dict(line.split() for line in runtime('cat', '/sys/fs/cgroup/memory.events').splitlines()) +node_events = {node: dict(line.split() for line in out('docker', 'exec', prefix + '-' + node + '-control-plane', 'cat', '/sys/fs/cgroup/memory.events').splitlines()) + for node in ('cell', 'hub', 'platform')} +node_memory_events = node_events['cell'] +if int(memory_events.get('oom_kill', '0')) or any(int(e.get('oom_kill', '0')) for e in node_events.values()): + fail('runtime Pod or kind node OOM kill recorded; inspect memory.events') +for config, namespace in (('cell-admin.yaml', 'fleet-site'), ('cell-admin.yaml', 'kro-system'), ('cell-admin.yaml', 'flux-system'), ('host.yaml', 'flux-system'), + ('host.yaml', 'karmada-system'), ('platform-admin.yaml', 'flux-system'), ('platform-admin.yaml', 'milo-provider'), + ('platform-admin.yaml', 'milo-consumer-a'), ('platform-admin.yaml', 'milo-consumer-b')): + for pod in json.loads(out('kubectl', '--kubeconfig', str(s / config), '--request-timeout=30s', '-n', namespace, 'get', 'pods', '-o', 'json'))['items']: + for c in pod['status'].get('containerStatuses', []): + if any(state.get('reason') == 'OOMKilled' for state in (c.get('lastState', {}).get('terminated') or {}, c.get('state', {}).get('terminated') or {})): + fail('OOMKilled container in ' + namespace + '/' + pod['metadata']['name']) +routing = json.loads((s / 'routing.json').read_text()) +if len(routing) != 2 or any(x['namespace'] != 'default' or x['watch'] != 'Added exact UID' for x in routing) or routing[0]['namespaceUID'] == routing[1]['namespaceUID'] or routing[0]['projectUID'] == routing[1]['projectUID']: + fail('missing independent native project create/watch evidence') + +phases = (s / 'phases.log').read_text() +markers = ('Verified forbidden observer/project/hub writes', 'allocate: verified', 'contention: consumer-a Bound', 'delivery: Karmada delivered exactly one', + '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, wrong-cell and stale-epoch', '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', + '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', + 'kro RBAC and admission confine it to per-operation objects', + 'flux-restart: every Flux controller', 'flux-fail-closed: absent kro chart digest', 'shared site layers applied it with services untouched', + 'flux-retention: removing the volume claim', 'flux-final: platform, hub and cell Ready', 'one writer per site object') + tuple(m + ': management rejected' for m in ( + 'wrong-cell', 'stale', 'duplicate', 'future', 'wrong-intent', 'wrong-digest', 'wrong-operation', 'incomplete', 'missing')) +for marker in markers: + if marker not in phases: + fail('missing acceptance phase: ' + marker) + +def libvirt_provider(): + raw = s / 'provider-private' + raw.mkdir(mode=0o700, exist_ok=True) + 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') + j = json.loads((raw / 'journal.json').read_text()) + ops = list(j['operations'].values()) + installs = [o for o in ops if o['request']['kind'] == 'install'] + cleanups = [o for o in ops if o['request']['kind'] == 'cleanup'] + if j.get('bootMode') != 'pxe' or len(installs) != 1 or len(cleanups) != 2 or any(o['result']['phase'] != 'Succeeded' or o.get('stage') != 'done' for o in ops): + fail('expected PXE mode, exactly one install and two verified cleanups') + if not j.get('closed'): + fail('allocation epoch is not closed after final cleanup') + epochs = sorted({o['request']['epoch'] for o in ops}) + if epochs != [1, 2]: + fail('expected allocation epochs 1 and 2, got %s' % epochs) + + interrupt = json.loads((ev / 'interrupt.json').read_text()) + if interrupt['operationID'] != installs[0]['request']['id'] or interrupt['stageAtInterrupt'] != 'installer-started' or not interrupt['domainRunningAtInterrupt']: + fail('interrupt evidence does not identify the retained install operation mid-installer') + + logs = list(raw.rglob('boot-delivery.log')) + written = '\n'.join(p.read_text() for p in logs) + for name in ('boot.ipxe', 'kernel', 'installer.gz'): + if not any('write-complete ' + name + ' bytes=' in line for line in written.splitlines()): + fail('missing completed broker write for ' + name) + + receipts, starts = [], {} + for o in installs: + op_id = o['request']['id'] + directory = raw / hashlib.sha256(op_id.encode()).hexdigest() + for filename, marker in (('installer.log', 'FLEET-INSTALLED:'), ('disk.log', 'FLEET-DISK-BOOT:')): + p = directory / filename + lines = [line.strip() for line in p.read_text(errors='replace').splitlines()] if p.exists() else [] + if lines.count(marker + o['receipt']) != 1 or sum(1 for l in lines if l.startswith(marker)) != 1: + fail('expected exactly one exact guest receipt in ' + filename) + receipts.append({'path': str(p.relative_to(raw)), 'marker': marker.rstrip(':'), 'sha256': hashlib.sha256(p.read_bytes()).hexdigest()}) + if sum(1 for l in (directory / 'installer.log').read_text(errors='replace').splitlines() if re.match(r'^\+ sfdisk /dev/vda', l.strip())) != 1: + fail('installer partitioned the disk other than exactly once') + installer, disk = (directory / 'installer.xml').read_text(), (directory / 'disk.xml').read_text() + if "boot dev='network'" not in installer or '' in installer or '' in installer: + fail('installer domain is not firmware network boot only') + if '' in disk or '' in disk or "boot dev='hd'" not in disk: + fail('disk-only boot has a NIC or direct kernel') + if '52:54:00:77:00:02' not in (directory / 'dhcp-leases.txt').read_text(): + fail('missing DHCP lease for the installer NIC') + if not o.get('bootClosed'): + fail('boot admission not closed') + if (directory / 'disk.raw').exists(): + fail('cleaned allocation still has a guest disk') + # libvirt appends one 'starting up' block per QEMU start. Independent of the + # journal, this proves one firmware-network installer start and one disk start. + qemu = (raw / 'libvirt-qemu' / ('fleet-local-' + hashlib.sha256(op_id.encode()).hexdigest()[:24] + '.log')).read_text(errors='replace') + blocks = [b for b in re.split(r'^\S+ \S+: starting up ', qemu, flags=re.M)[1:]] + network = [b for b in blocks if '-netdev' in b and '52:54:00:77:00:02' in b] + disk_only = [b for b in blocks if '-netdev' not in b and 'virtio-disk0' in b] + starts[op_id] = {'qemuStarts': len(blocks), 'networkInstallerStarts': len(network), 'diskOnlyStarts': len(disk_only)} + if len(blocks) != 2 or len(network) != 1 or len(disk_only) != 1 or blocks.index(network[0]) != 0: + fail('expected exactly one network installer start followed by one disk-only start, got %s' % starts[op_id]) + + domains = runtime('virsh', '--connect', 'qemu:///system?socket=/run/fleet-libvirt/libvirt-sock', 'list', '--all', '--name').strip() + if domains: + fail('provider domain remains after cleanup') + denials = (s / 'boot-denials.txt').read_text().strip() if (s / 'boot-denials.txt').exists() else '' + if not denials.startswith('PASS'): + fail('missing live closed-boot HTTP denial evidence') + return ops, installs, cleanups, epochs, interrupt, receipts, starts, denials + + +ops, installs, cleanups, epochs, interrupt, receipts, starts, denials = libvirt_provider() + +# Kubernetes execution: what actually ran, as names, UIDs, phases and conditions. +kro = kget('-n', 'kro-system', 'get', 'deployment')['items'] +kro_pods = kget('-n', 'kro-system', 'get', 'pods')['items'] +rgd = kget('get', 'resourcegraphdefinition', 'fleet-handoff-dispatcher') +instance = kget('-n', 'fleet-site', 'get', 'handoffdispatcher', 'dispatcher') +if rgd['status'].get('state') != 'Active' or instance['status'].get('state') != 'ACTIVE': + fail('kro RGD or HandoffDispatcher instance not active') +jobs = kget('-n', 'fleet-site', 'get', 'jobs', '-l', 'app.kubernetes.io/name=fleet-site-worker')['items'] +handoffs = {h['metadata']['name']: json.loads(h['spec']['requestJSON']) for h in kget('-n', 'fleet-coordination', 'get', 'machineallocationhandoffs')['items']} +worker_jobs = [] +for job in jobs: + handoff = job['metadata']['labels']['fleet.datumapis.com/handoff'] + conditions = sorted([c['type'], c['status'], c.get('reason', '')] for c in job['status'].get('conditions', [])) + if ['Complete', 'True', 'CompletionsReached'] not in conditions: + fail('worker Job not Complete: ' + job['metadata']['name']) + job_pods = kget('-n', 'fleet-site', 'get', 'pods', '-l', 'batch.kubernetes.io/controller-uid=' + job['metadata']['uid'])['items'] + exits = [next((c['state']['terminated']['exitCode'] for c in p['status'].get('containerStatuses', []) if 'terminated' in c.get('state', {})), None) for p in job_pods] + if exits.count(0) != 1: + fail('worker Job without exactly one successful Pod: ' + job['metadata']['name']) + worker_jobs.append({'job': job['metadata']['name'], 'uid': job['metadata']['uid'], 'operationID': handoffs[handoff]['id'], 'kind': handoffs[handoff]['kind'], + 'epoch': handoffs[handoff]['epoch'], 'conditions': conditions, 'succeeded': job['status'].get('succeeded', 0), 'failed': job['status'].get('failed', 0), + 'pods': [{'uid': p['metadata']['uid'], 'phase': p['status'].get('phase'), 'exitCode': e} for p, e in zip(job_pods, exits)], + 'serviceAccount': job['spec']['template']['spec']['serviceAccountName'], 'podReplacementPolicy': job['spec'].get('podReplacementPolicy'), + 'podFailurePolicy': job['spec'].get('podFailurePolicy'), 'backoffLimit': job['spec'].get('backoffLimit'), + 'activeDeadlineSeconds': job['spec'].get('activeDeadlineSeconds'), 'createdBy': job['metadata']['labels'].get('kro.run/node-id')}) +if sorted(j['kind'] for j in worker_jobs) != ['cleanup', 'cleanup', 'install'] or any(j['createdBy'] != 'workers' for j in worker_jobs): + fail('expected kro-created worker Jobs for exactly one install and two cleanups, got %s' % [(j['kind'], j['createdBy']) for j in worker_jobs]) +pvc = kget('-n', 'fleet-site', 'get', 'pvc', 'fleet-site-state') +pv = kget('get', 'pv', pvc['spec']['volumeName']) +deployments = {d['metadata']['name']: {'uid': d['metadata']['uid'], 'availableReplicas': d['status'].get('availableReplicas', 0), + 'fluxLayer': d['metadata'].get('labels', {}).get('kustomize.toolkit.fluxcd.io/name'), + 'kroLabels': sorted(k for k in d['metadata'].get('labels', {}) if k.startswith('kro.run/') or k.startswith('applyset.kubernetes.io/'))} + for d in kget('-n', 'fleet-site', 'get', 'deployments')['items']} +execution = { + 'observedAt': datetime.datetime.now(datetime.timezone.utc).isoformat(), + 'kro': {'version': 'v0.9.4', 'chart': 'oci://registry.k8s.io/kro/charts/kro@sha256:4e8de4d34b7e2c3cede958e140e26cd6d34a377062e63caf355a636d2bf4a67c', + 'chartArchiveSHA256': 'ceeb630764eb79ca4220dfdcc2907b819a27c30f68cb60d09c1ae3fa2c58b5cd', 'installedBy': 'Flux HelmRelease flux-system/kro', + 'image': kro[0]['spec']['template']['spec']['containers'][0]['image'], 'imageID': kro_pods[0]['status']['containerStatuses'][0]['imageID'], 'rbacMode': 'aggregation', + 'helmReleaseOwner': kro[0]['metadata'].get('labels', {}).get('helm.toolkit.fluxcd.io/name')}, + 'resourceGraphDefinition': {'name': 'fleet-handoff-dispatcher', 'state': rgd['status']['state'], 'conditions': sorted([c['type'], c['status']] for c in rgd['status'].get('conditions', []))}, + 'handoffDispatcher': {k: v for k, v in instance['status'].items() if k != 'conditions'}, + 'siteDeployments': deployments, + 'ownership': 'Flux Kustomization fleet-site-services owns the shared Deployments and boot Service; kro owns only per-operation worker Jobs, ServiceAccounts, Roles and RoleBindings', + 'siteVolume': {'pvc': pvc['metadata']['name'], 'pvcUID': pvc['metadata']['uid'], 'pv': pv['metadata']['name'], 'pvUID': pv['metadata']['uid'], + 'reclaimPolicy': pv['spec']['persistentVolumeReclaimPolicy'], 'storageClass': pvc['spec']['storageClassName'], 'managedByKro': False}, + 'workerJobs': worker_jobs, + 'dispatch': json.loads((s / 'k8s-dispatch-job.json').read_text()), + 'workerRBAC': json.loads((s / 'k8s-worker-rbac.json').read_text()), + 'interruptions': json.loads((ev / 'interrupt.json').read_text()), + 'lifecycle': json.loads((ev / 'lifecycle.json').read_text()), + 'deliveryFaults': json.loads((ev / 'delivery-faults.json').read_text()), + 'authority': 'Job Complete, Flux Ready and kro Ready are execution facts only; management validated Karmada-reflected, journal-derived observations before any projection', +} +if execution['kro']['helmReleaseOwner'] != 'kro': + fail('kro controller is not owned by the Flux HelmRelease') +if pv['spec']['persistentVolumeReclaimPolicy'] != 'Retain' or sorted(deployments) != sorted(['fleet-site-boot', 'fleet-site-observer', 'fleet-site-runtime']) or any( + d['availableReplicas'] != 1 or d['fluxLayer'] != 'fleet-site-services' or d['kroLabels'] for d in deployments.values()): + fail('site volume or Flux-owned shared Deployments not as expected') +(ev / 'kubernetes-execution.json').write_text(json.dumps(execution, indent=2, sort_keys=True) + '\n') +arch = out('docker', 'info', '--format', '{{.Architecture}}').strip() +flux_files = ('flux-verify.json', 'flux-initial.json', 'flux-rbac-restore.json', 'flux-drift.json', 'flux-restart.json', 'flux-fail-closed.json', 'flux-retention.json', 'flux-final.json', + 'flux-graph-lifecycle.json', 'flux-ownership-final.json', 'kro-rbac.json') +for name in flux_files: + if not (ev / name).exists(): + fail('missing Flux evidence ' + name) +flux_revisions = json.loads((s / 'flux-revisions.json').read_text()) +final = json.loads((ev / 'flux-final.json').read_text()) +for cluster, snap in final.items(): + if snap['sources']['flux-system/fleet-gitops']['artifactRevision'] != flux_revisions[-1]['fluxRevision']: + fail('%s did not end on the final source revision' % cluster) + 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()) + +summary = { + 'schemaVersion': 2, 'acceptance': 'passed', + 'observedAt': datetime.datetime.now(datetime.timezone.utc).isoformat(), 'prefix': prefix, + 'qualification': {'nativeMiloProjectAPIs': True, 'actualKarmadaDeliveryAndReflection': True, 'realLocalPXE': True, + 'kubernetesJobExecution': True, 'actualKroController': True, 'fluxReconciledServices': True, + 'kvm': False, 'uefi': False, 'productionAuthority': False, 'productionEquivalence': False}, + 'versions': {'milo': 'v0.32.5', 'karmada': 'v1.16.0', 'kro': 'v0.9.4', 'flux': 'v2.9.6', 'kindNode': 'v1.35.0', 'architecture': arch, 'guestArchitecture': 'amd64', 'accelerator': 'tcg', 'firmware': 'SeaBIOS/iPXE (legacy BIOS)'}, + 'scenarios': { + 'exclusiveContention': True, + 'partitionPublicReadyStayedFalse': True, + 'interruptedWorkerResumedExactOperation': interrupt, + 'kubernetesExecution': 'kubernetes-execution.json', + 'gitops': {'sourceRevisions': [{k: r[k] for k in ('revision', 'digest', 'purpose', 'gitHead', 'contentSumsSHA256', 'files')} for r in flux_revisions], + 'evidence': list(flux_files), 'siteImage': write_env['siteImage']}, + 'installerStarts': starts, + 'reflectionRejections': ['wrong-cell', 'stale', 'duplicate', 'future', 'wrong-intent', 'wrong-digest', 'wrong-operation', 'incomplete', 'missing'], + 'wrongLocationDeniedBeforeAllocation': json.loads((ev / 'wrong-location.json').read_text()), + 'releasedProjection': {'consumerA': {'machine': 'Released, Bound False, Ready False, no currentInstallationRef, no Fleet finalizer', 'installation': 'Released, Ready False'}, + 'consumerB': {'machine': 'Released, Bound False, Ready False, no currentInstallationRef, no Fleet finalizer'}}, + 'cleanupAndReuse': {'epochs': epochs, 'cleanups': len(cleanups), 'domainsAfterCleanup': [], 'disksAfterCleanup': 0}, + 'closedBootDenials': denials, + }, + 'operations': [{'id': o['request']['id'], 'kind': o['request']['kind'], 'epoch': o['request']['epoch'], 'phase': o['result']['phase'], 'result': o['result']['result'], 'inputDigest': o['result']['inputDigest']} for o in ops], + 'projectRouting': routing, 'brokerWriteCompletion': True, 'guestEvidence': receipts, + 'runtimePodMemoryEvents': {key: int(value) for key, value in memory_events.items()}, + 'cellNodeMemoryEvents': {key: int(value) for key, value in node_memory_events.items()}, + 'nodeMemoryEvents': {node: {key: int(value) for key, value in e.items()} for node, e in node_events.items()}, + 'seams': ['static-token root RBAC', 'independent local Milo roots on one platform kind cluster (Flux-managed workloads, bootstrap-enrolled credentials, fixture project bootstrap)', + 'plain-HTTP unsigned local OCI registry as the Flux source', 'bootstrap-minted 24h ServiceAccount tokens and member Secret', 'synthetic source-use admission and publication', + 'synthetic quota and settlement', 'synthetic hardware enrollment mapping', 'networkless workload', + 'privileged disposable VM runtime Pod on a single kind node', 'kro reads delivered handoffs (it must, to enumerate them)', + 'trusted graph and services authors: worker Jobs reach root libvirtd through its socket', + 'reflection faults injected with bootstrap credentials while the Karmada controller is stopped'], + 'privateArtifacts': 'state directory outside evidence/ contains authority; do not publish', +} +(ev / 'summary.json').write_text(json.dumps(summary, indent=2) + '\n') +for name in ('source-SHA256SUMS', 'sysctl.json'): + if (s / name).exists(): + (ev / name).write_text((s / name).read_text()) +paths = [s / 'site-bin' / 'fleet-multiplane', s / 'fleet-multiplane-host'] +(ev / 'binary-SHA256SUMS').write_text(''.join(hashlib.sha256(p.read_bytes()).hexdigest() + ' ' + p.name + '\n' for p in paths)) +(ev / 'image-id').write_text(out('docker', 'image', 'inspect', prefix + '-site-image', '--format', '{{.Id}}').strip() + '\nregistry digest ' + write_env['siteImageDigest'] + '\n') +print('evidence: sanitized summary ' + str(ev / 'summary.json')) diff --git a/hack/multiplane/fault_guard.py b/hack/multiplane/fault_guard.py new file mode 100644 index 00000000..4c6408ad --- /dev/null +++ b/hack/multiplane/fault_guard.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python3 +"""Record and verify that a Flux suspension survived a fault interval.""" +import datetime +import json +import pathlib +import subprocess +import sys + + +def validate(obj, deployment, pods, baseline=None): + metadata = obj['metadata'] + receipt = {'uid': metadata['uid'], 'generation': metadata['generation'], + 'suspended': obj.get('spec', {}).get('suspend') is True, + 'replicas': deployment.get('spec', {}).get('replicas'), + 'activePods': len(pods['items'])} + if not receipt['suspended'] or receipt['replicas'] != 0 or receipt['activePods'] != 0: + raise ValueError('fault isolation lost: suspension, zero replicas and no Pods required') + if baseline is not None and receipt != baseline: + raise ValueError('fault isolation changed during suspension') + return receipt + + +def root_receipt(root, revision): + """The cluster's root sync applied the given source revision while the fault held.""" + status = root.get('status', {}) + ready = any(c.get('type') == 'Ready' and c.get('status') == 'True' for c in status.get('conditions', [])) + if status.get('lastAppliedRevision') != revision or not ready or status.get('observedGeneration') != root['metadata']['generation']: + raise ValueError('root sync did not apply %s during the fault' % revision) + return {'revision': revision, 'lastHandledReconcileAt': status.get('lastHandledReconcileAt')} + + +def main(): + mode, state, config, kind, name, namespace, deployment, evidence = sys.argv[1:9] + # Optional: the source revision the root sync must have applied during the fault. + revision = sys.argv[9] if len(sys.argv) > 9 else None + if mode not in ('record', 'check'): + raise ValueError('expected record or check') + state = pathlib.Path(state) + + def get(*args): + return json.loads(subprocess.check_output( + ['kubectl', '--kubeconfig', str(state / config), '--request-timeout=20s', + *args, '-o', 'json'], text=True)) + + obj = get('-n', 'flux-system', 'get', kind, name) + dep = get('-n', namespace, 'get', 'deployment', deployment) + labels = dep['spec']['selector']['matchLabels'] + pods = get('-n', namespace, 'get', 'pods', '-l', ','.join(k + '=' + v for k, v in sorted(labels.items()))) + path = state / 'evidence' / (evidence + '.json') + previous = json.loads(path.read_text()) if mode == 'check' else None + receipt = validate(obj, dep, pods, previous['before'] if previous else None) + record = previous or {'kind': kind, 'name': name, 'fieldManager': 'fleet-fault-injection', 'before': receipt} + record['checkedAt'] = datetime.datetime.now(datetime.timezone.utc).isoformat() + if mode == 'check': + record['after'] = receipt + record['unchanged'] = True + if revision: + root = get('-n', 'flux-system', 'get', 'kustomizations.kustomize.toolkit.fluxcd.io', 'fleet-cluster') + record['rootReconciledDuringFault'] = root_receipt(root, revision) + path.write_text(json.dumps(record, indent=2) + '\n') + + +if __name__ == '__main__': + main() diff --git a/hack/multiplane/flux.py b/hack/multiplane/flux.py new file mode 100644 index 00000000..30bac12f --- /dev/null +++ b/hack/multiplane/flux.py @@ -0,0 +1,1114 @@ +#!/usr/bin/env python3 +"""Flux source, bootstrap and reconciliation evidence for the local acceptance. + +The acceptance reconciles every long-running service from one OCI artifact, +staged from the current checkout and pushed to this run's local registry. +This module owns only: + + tools download and verify the pinned Flux CLI and install manifest + stage build one source revision (checkout config + generated environment) + push push a staged revision and record its digest + bootstrap apply one cluster's Flux components and sync objects, once + publish stage + push + request reconcile + wait for the given clusters + wait wait until a cluster's Flux objects are Ready at the pushed revision + record write a sanitized snapshot of a cluster's Flux objects + verify, drift, restart, fail-closed, retention, graph-lifecycle + acceptance scenarios; ownership audits who writes each site object + +Every Kubernetes write it makes is either the documented bootstrap boundary +(Flux components and sync objects, applied once), a reconcile request +annotation, or explicit fault injection whose repair is left to Flux. +Nothing here stores credentials in a source revision. +""" +import argparse +import datetime +import hashlib +import json +import os +import pathlib +import re +import shutil +import subprocess +import sys +import tarfile +import time +import urllib.request + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) +import harness # noqa: E402 (secret discovery and exit codes) + +FLUX_VERSION = '2.9.6' +RELEASE = 'https://github.com/fluxcd/flux2/releases/download/v%s/' % FLUX_VERSION +# From flux_2.9.6_checksums.txt of the v2.9.6 GitHub release. +INSTALL_SHA256 = '9c1fda7e401429531ed1478f67ba06b3edff6513b75da7ee47bde9f1c4d4251c' +CLI = {('darwin', 'arm64'): ('flux_2.9.6_darwin_arm64.tar.gz', '7008a758da4b8d57c5845aad6552f256d4d23630c2b2de2ca8da362f9a48c126'), + ('darwin', 'x86_64'): ('flux_2.9.6_darwin_amd64.tar.gz', 'c3c3532c8c6cf689ef7b93125b33dc170df84a9d5d036f578568bfdf88a2d7e6'), + ('linux', 'x86_64'): ('flux_2.9.6_linux_amd64.tar.gz', 'b4d22673e9246cbd628881f1a9ef3b090085dced291e42d804555cee8e8d42c5'), + ('linux', 'aarch64'): ('flux_2.9.6_linux_arm64.tar.gz', '6663c154755b732f43dc993d72321f71c2fc1ff0bcb94b2696e0a8638fa562b4')} +REGISTRY_IMAGE = 'registry:3.0.0@sha256:6c5666b861f3505b116bb9aa9b25175e71210414bd010d92035ff64018f9457e' +KRO_CHART_DIGEST = 'sha256:4e8de4d34b7e2c3cede958e140e26cd6d34a377062e63caf355a636d2bf4a67c' +KRO_CHART_LAYER_SHA256 = 'ceeb630764eb79ca4220dfdcc2907b819a27c30f68cb60d09c1ae3fa2c58b5cd' +KARMADA_CHART_SHA256 = '773ab194cb92dad81d479d2199b968a2c6b0b8366306ba47961afd67616834fe' +# A well-formed digest that no registry serves: the fail-closed revision. +MISSING_DIGEST = 'sha256:' + hashlib.sha256(b'fleet: deliberately absent chart').hexdigest() +TAG = 'local' +CLUSTERS = ('platform', 'hub', 'cell') +KUBECONFIG = {'platform': 'platform-admin.yaml', 'hub': 'host.yaml', 'cell': 'cell-admin.yaml'} +SOURCE_DIRS = ('config/multiplane', 'config/site') +# Expected Flux Kustomizations per cluster (namespace/name), besides the root. +EXPECTED = { + 'platform': ['flux-system/milo-provider', 'flux-system/milo-consumer-a', 'flux-system/milo-consumer-b'], + 'hub': ['flux-system/karmada', 'flux-system/fleet-host', 'karmada-system/fleet-karmada-coordination', + 'karmada-system/fleet-karmada-api', 'karmada-system/fleet-karmada-members'], + 'cell': ['flux-system/fleet-coordination', 'flux-system/fleet-federation', 'flux-system/kro', + 'flux-system/fleet-site-base', 'flux-system/fleet-site-graph'], +} +HELMRELEASES = {'hub': ['flux-system/karmada'], 'cell': ['flux-system/kro']} +# Cell site layers present once the scoped asset is known (revision 2 onwards). +SITE_LAYERS = ['flux-system/fleet-site-services', 'flux-system/fleet-site-dispatch'] +# A fixed ClusterIP in the static band (first 256 addresses) of kind's default +# 10.96.0.0/16 Service range, so a recreated boot Service keeps its origin. +BOOT_SERVICE_IP = '10.96.0.80' +SITE, COORD = 'fleet-site', 'fleet-coordination' +DISPATCHER = ('handoffdispatchers.site.fleet.datumapis.com', 'dispatcher') +RGD = 'fleet-handoff-dispatcher' +# Flux-owned shared site objects and the layer (Kustomization) that writes each. +SHARED = {('deployments', SITE, 'fleet-site-runtime'): 'fleet-site-services', ('deployments', SITE, 'fleet-site-boot'): 'fleet-site-services', + ('deployments', SITE, 'fleet-site-observer'): 'fleet-site-services', ('services', SITE, 'fleet-site-boot'): 'fleet-site-services', + ('configmaps', SITE, 'fleet-site-worker-policy'): 'fleet-site-services', + ('serviceaccounts', SITE, 'fleet-site-runtime'): 'fleet-site-base', ('serviceaccounts', SITE, 'fleet-site-boot'): 'fleet-site-base', + ('serviceaccounts', SITE, 'fleet-site-observer'): 'fleet-site-base', ('persistentvolumeclaims', SITE, 'fleet-site-state'): 'fleet-site-base', + ('roles', COORD, 'fleet-site-observer'): 'fleet-site-base', ('rolebindings', COORD, 'fleet-site-observer'): 'fleet-site-base', + ('roles', SITE, 'fleet-site-kro-workers'): 'fleet-site-base', ('rolebindings', SITE, 'fleet-site-kro-workers'): 'fleet-site-base', + ('roles', COORD, 'fleet-site-kro-worker-rbac'): 'fleet-site-base', ('rolebindings', COORD, 'fleet-site-kro-worker-rbac'): 'fleet-site-base', + ('clusterroles', None, 'fleet-site-kro'): 'fleet-site-base', + ('validatingadmissionpolicies', None, 'fleet-site-kro-worker-jobs'): 'fleet-site-base', + ('validatingadmissionpolicybindings', None, 'fleet-site-kro-worker-jobs'): 'fleet-site-base', + ('validatingadmissionpolicies', None, 'fleet-site-kro-worker-identity'): 'fleet-site-base', + ('validatingadmissionpolicybindings', None, 'fleet-site-kro-worker-identity'): 'fleet-site-base'} +# Exact inventories of the layers that must hold nothing else. +SITE_DEPLOYMENTS = ('fleet-site-runtime', 'fleet-site-boot', 'fleet-site-observer') +LAYER_INVENTORY = { + 'flux-system/fleet-site-services': sorted(['fleet-site_fleet-site-boot__Service', 'fleet-site_fleet-site-worker-policy__ConfigMap', + 'fleet-site_fleet-site-runtime_apps_Deployment', 'fleet-site_fleet-site-boot_apps_Deployment', + 'fleet-site_fleet-site-observer_apps_Deployment']), + 'flux-system/fleet-site-graph': ['_fleet-handoff-dispatcher_kro.run_ResourceGraphDefinition'], + 'flux-system/fleet-site-dispatch': ['fleet-site_dispatcher_site.fleet.datumapis.com_HandoffDispatcher'], +} +# kro writes only these per-operation kinds, all named w-. +WORKER_KINDS = (('jobs', SITE), ('serviceaccounts', SITE), ('roles', COORD), ('rolebindings', COORD)) +FORBIDDEN = (re.compile(r'^kind:\s*Secret\s*$', re.M), re.compile(r'-----BEGIN [A-Z ]*PRIVATE KEY-----'), + re.compile(r'''^\s*(token|client-key-data|password)\s*:\s*\S{16,}''', re.M)) + + +def now(): + return datetime.datetime.now(datetime.timezone.utc).isoformat() + + +def die(message, code=harness.EXIT_FAILED): + print(message, file=sys.stderr) + raise SystemExit(code) + + +def kubectl(state, cluster, *args, input=None, check=True, timeout=60, config=None): + path = pathlib.Path(state) / (config or KUBECONFIG[cluster]) + try: + r = subprocess.run(['kubectl', '--kubeconfig', str(path), '--request-timeout=20s', *args], input=input, + text=True, capture_output=True, timeout=timeout) + except subprocess.TimeoutExpired: + die('kubectl %s on %s timed out' % (' '.join(args[:3]), cluster), harness.EXIT_TIMEOUT) + if check and r.returncode: + die('kubectl %s on %s failed: %s' % (' '.join(args[:4]), cluster, r.stderr.strip()[:400])) + return r + + +def kget(state, cluster, *args, config=None): + return json.loads(kubectl(state, cluster, *args, '-o', 'json', config=config).stdout) + + +def sha256(path): + return hashlib.sha256(pathlib.Path(path).read_bytes()).hexdigest() + + +def write(path, value): + path = pathlib.Path(path) + path.write_text(json.dumps(value, indent=2, sort_keys=True) + '\n') + path.chmod(0o600) + + +def flux_bin(state): + return str(pathlib.Path(state) / 'flux-tools' / 'flux') + + +# ---------------------------------------------------------------- tools + +def fetch(url, dest, digest): + if not dest.exists() or sha256(dest) != digest: + tmp = dest.with_suffix('.part') + with urllib.request.urlopen(url, timeout=120) as r, open(tmp, 'wb') as f: + shutil.copyfileobj(r, f) + tmp.replace(dest) + if sha256(dest) != digest: + die('%s digest mismatch: %s' % (dest.name, sha256(dest))) + + +def tools(args): + d = pathlib.Path(args.state) / 'flux-tools' + d.mkdir(mode=0o700, exist_ok=True) + key = (os.uname().sysname.lower(), os.uname().machine) + if key not in CLI: + die('no pinned Flux CLI for %s/%s' % key, harness.EXIT_PREFLIGHT) + archive, digest = CLI[key] + fetch(RELEASE + archive, d / archive, digest) + fetch(RELEASE + 'install.yaml', d / 'install.yaml', INSTALL_SHA256) + with tarfile.open(d / archive) as t: + t.extract('flux', d, filter='data') + version = subprocess.run([str(d / 'flux'), 'version', '--client'], text=True, capture_output=True).stdout.strip() + if version != 'flux: v' + FLUX_VERSION: + die('unexpected Flux CLI version: ' + version) + record = {'version': 'v' + FLUX_VERSION, 'cli': {'archive': archive, 'sha256': digest, 'binarySHA256': sha256(d / 'flux')}, + 'installManifest': {'url': RELEASE + 'install.yaml', 'sha256': INSTALL_SHA256}} + write(d / 'tools.json', record) + print('flux-tools: Flux CLI v%s and install manifest verified (install.yaml sha256 %s)' % (FLUX_VERSION, INSTALL_SHA256)) + return 0 + + +# ---------------------------------------------------------------- source + +def environment(state): + s = pathlib.Path(state) + env = json.loads((s / 'gitops-environment.json').read_text()) + if (s / 'scoped-asset').exists(): + env['scopedAsset'] = (s / 'scoped-asset').read_text().strip() + return env + + +def sync_objects(cluster, url): + """The per-cluster sync objects that flux bootstrap would commit as gotk-sync.yaml.""" + return '''# Generated per environment: the OCI source and the root sync for %(c)s. +apiVersion: source.toolkit.fluxcd.io/v1 +kind: OCIRepository +metadata: + name: fleet-gitops + namespace: flux-system +spec: + interval: 1m + url: %(url)s + ref: + tag: %(tag)s + # Local seam: a plain-HTTP registry on the disposable kind network. A real + # environment uses TLS and verifies signatures (spec.verify). + insecure: true +--- +apiVersion: kustomize.toolkit.fluxcd.io/v1 +kind: Kustomization +metadata: + name: fleet-cluster + namespace: flux-system +spec: + interval: 10m + retryInterval: 30s + timeout: 5m + prune: true + wait: false + sourceRef: + kind: OCIRepository + name: fleet-gitops + path: ./environment/%(c)s +''' % {'c': cluster, 'url': url, 'tag': TAG} + + +def config_map(name, namespace, data): + lines = ['apiVersion: v1', 'kind: ConfigMap', 'metadata:', ' name: ' + name, ' namespace: ' + namespace, 'data:'] + lines += [' %s: %s' % (k, json.dumps(str(v))) for k, v in sorted(data.items())] + return '\n'.join(lines) + '\n' + + +def stage(args): + s = pathlib.Path(args.state).resolve() + root = pathlib.Path(args.root).resolve() + env = environment(s) + out = s / 'gitops' / ('r%d' % args.revision) + if out.exists(): + shutil.rmtree(out) + out.mkdir(parents=True, mode=0o700) + for name in SOURCE_DIRS: + shutil.copytree(root / name, out / name, ignore=shutil.ignore_patterns('__pycache__', '*.pyc', '.*')) + tools_dir = s / 'flux-tools' + if sha256(tools_dir / 'install.yaml') != INSTALL_SHA256: + die('install manifest changed after verification') + components = out / 'environment' / 'flux-components' + components.mkdir(parents=True) + shutil.copy(tools_dir / 'install.yaml', components / 'gotk-components.yaml') + shutil.copy(root / 'config/multiplane/flux/components.yaml', components / 'kustomization.yaml') + url = 'oci://%s:5000/fleet-gitops' % env['registryHost'] + marker = 'r%d' % args.revision + for cluster in CLUSTERS: + d = out / 'environment' / cluster + (d / 'flux-system').mkdir(parents=True) + (d / 'flux-system' / 'gotk-sync.yaml').write_text(sync_objects(cluster, url)) + (d / 'flux-system' / 'kustomization.yaml').write_text( + 'apiVersion: kustomize.config.k8s.io/v1beta1\nkind: Kustomization\nresources:\n - ../../flux-components\n - gotk-sync.yaml\n') + resources = ['flux-system', '../../config/multiplane/clusters/' + cluster, 'environment.yaml'] + data = {'FLEET_CELL': env['cell'], 'FLEET_CELL_ENDPOINT': env['cellEndpoint'], 'FLEET_SOURCE_MARKER': marker} + maps = [] + patches = [] + if cluster == 'hub': + # Karmada-API Kustomizations live beside their kubeconfig Secret. + maps.append(config_map('fleet-environment', 'karmada-system', data)) + if cluster == 'cell': + if args.site != 'absent': + resources.insert(2, '../../config/multiplane/clusters/cell-site') + data.update(FLEET_SCOPED_ASSET=env['scopedAsset'], FLEET_SITE_IMAGE=env['siteImage'], FLEET_BOOT_SERVICE_IP=BOOT_SERVICE_IP, + FLEET_SITE_DISPATCH='true' if args.site == 'dispatch' else 'false') + if args.bad_kro_chart: + patches.append(child_patch('kro', [{'target': {'kind': 'OCIRepository', 'name': 'kro-chart'}, + 'patch': '- op: replace\n path: /spec/ref/digest\n value: %s\n' % MISSING_DIGEST}])) + if args.drop_site_volume: + patches.append(child_patch('fleet-site-base', [{'patch': '$patch: delete\napiVersion: v1\nkind: PersistentVolumeClaim\n' + 'metadata:\n name: fleet-site-state\n namespace: fleet-site\n'}])) + maps.insert(0, config_map('fleet-environment', 'flux-system', data)) + (d / 'environment.yaml').write_text('# Generated, non-secret environment values for revision %s.\n' % marker + '---\n'.join(maps)) + k = 'apiVersion: kustomize.config.k8s.io/v1beta1\nkind: Kustomization\nresources:\n' + ''.join(' - %s\n' % r for r in resources) + if patches: + k += 'patches:\n' + ''.join(patches) + (d / 'kustomization.yaml').write_text(k) + files = sorted(p for p in out.rglob('*') if p.is_file()) + secrets = harness.secrets(s) + for p in files: + text = p.read_text(errors='ignore') + if any(f.search(text) for f in FORBIDDEN) or any(v in text for v in secrets): + die('refusing to stage credential-like content: ' + str(p.relative_to(out))) + # Every environment must render before it is published. + for cluster in CLUSTERS: + r = subprocess.run(['kustomize', 'build', str(out / 'environment' / cluster)], capture_output=True, text=True) + if r.returncode: + die('environment %s does not render: %s' % (cluster, r.stderr[-400:])) + sums = ''.join('%s %s\n' % (sha256(p), p.relative_to(out)) for p in files) + (s / 'gitops' / ('r%d.SHA256SUMS' % args.revision)).write_text(sums) + print('stage: revision %s with %d files (%s); no credential content' % (marker, len(files), ', '.join( + k for k, v in (('site', args.site != 'absent'), ('dispatch', args.site == 'dispatch'), ('bad-kro-chart', args.bad_kro_chart), + ('site-volume-removed', args.drop_site_volume)) if v) or 'platform only')) + return 0 + + +def child_patch(name, patches): + """Patch a child Kustomization's spec.patches: the effect of a source commit.""" + return ' - target: {kind: Kustomization, name: %s}\n patch: |-\n - op: add\n path: /spec/patches\n value: %s\n' % ( + name, json.dumps(patches)) + + +def revisions(state): + p = pathlib.Path(state) / 'flux-revisions.json' + return json.loads(p.read_text()) if p.exists() else [] + + +def push(args): + s = pathlib.Path(args.state).resolve() + env = environment(s) + root = pathlib.Path(args.root).resolve() + out = s / 'gitops' / ('r%d' % args.revision) + head = subprocess.run(['git', '-C', str(root), 'rev-parse', 'HEAD'], text=True, capture_output=True).stdout.strip() + branch = subprocess.run(['git', '-C', str(root), 'branch', '--show-current'], text=True, capture_output=True).stdout.strip() or 'detached' + sums = s / 'gitops' / ('r%d.SHA256SUMS' % args.revision) + content = hashlib.sha256(sums.read_bytes()).hexdigest() + r = subprocess.run([flux_bin(s), 'push', 'artifact', 'oci://127.0.0.1:%s/fleet-gitops:%s' % (env['registryPort'], TAG), '--path', str(out), + '--source', 'file://fleet-checkout/' + branch, '--revision', '%s@sha1:%s' % (branch, head), '--reproducible', '--insecure-registry', + '--annotations', 'org.opencontainers.image.description=fleet local acceptance r%d; uncommitted checkout content sha256 %s' % (args.revision, content), + '--output', 'json'], text=True, capture_output=True, timeout=180) + if r.returncode: + die('flux push artifact failed: ' + r.stderr[-400:]) + pushed = json.loads(r.stdout) + digest = pushed['digest'] + record = {'revision': args.revision, 'marker': 'r%d' % args.revision, 'digest': digest, 'fluxRevision': '%s@%s' % (TAG, digest), + 'pushedAt': now(), 'gitHead': head, 'gitBranch': branch, 'checkoutDirty': True, 'contentSumsSHA256': content, + 'files': len(sums.read_text().splitlines()), 'purpose': args.purpose} + all_revs = [x for x in revisions(s) if x['revision'] != args.revision] + [record] + write(s / 'flux-revisions.json', all_revs) + shutil.copy(sums, s / 'evidence' / ('gitops-r%d.SHA256SUMS' % args.revision)) + print('push: r%d %s (%s)' % (args.revision, digest, args.purpose)) + return 0 + + +def current(state): + revs = revisions(state) + if not revs: + die('no source revision has been pushed') + return revs[-1] + + +# ---------------------------------------------------------------- reconcile and wait + +def request(state, cluster, kind, ref): + namespace, name = ref.split('/') + token = now() + kubectl(state, cluster, '-n', namespace, 'annotate', '--overwrite', kind, name, REQUEST + '=' + token) + return token + + +REQUEST = 'reconcile.fluxcd.io/requestedAt' + + +def acknowledged(obj, token): + return obj.get('status', {}).get('lastHandledReconcileAt') == token + + +def lost(obj, token): + """A parent Flux apply can strip a kubectl-managed request before any reconcile handles it.""" + return not acknowledged(obj, token) and (obj['metadata'].get('annotations') or {}).get(REQUEST) != token + + +def conditions(obj): + return {c['type']: c for c in obj.get('status', {}).get('conditions', [])} + + +def ready(obj): + c = conditions(obj).get('Ready', {}) + return c.get('status') == 'True' and obj.get('status', {}).get('observedGeneration') == obj['metadata']['generation'] + + +def kustomizations(state, cluster): + return {i['metadata']['namespace'] + '/' + i['metadata']['name']: i for i in kget(state, cluster, 'get', 'kustomizations.kustomize.toolkit.fluxcd.io', '-A')['items']} + + +def wait_cluster(state, cluster, timeout, names=None, revision=None, skip=(), observe_also=()): + """All named (default: every) Kustomizations Ready, current generation, at the pushed revision. + + observe_also samples other clusters' gating while waiting (bootstrap only: + later waits run while a cluster is deliberately paused).""" + revision = revision or current(state)['fluxRevision'] + deadline = time.monotonic() + timeout + source_token = request(state, cluster, 'ocirepositories.source.toolkit.fluxcd.io', 'flux-system/fleet-gitops') + tokens = {} + reissued = {} + last = {} + while time.monotonic() < deadline: + source = kget(state, cluster, '-n', 'flux-system', 'get', 'ocirepositories.source.toolkit.fluxcd.io', 'fleet-gitops') + if lost(source, source_token): + # Only a fresh request counts; the acknowledgement must still match it exactly. + source_token = request(state, cluster, 'ocirepositories.source.toolkit.fluxcd.io', 'flux-system/fleet-gitops') + reissued['flux-system/fleet-gitops'] = reissued.get('flux-system/fleet-gitops', 0) + 1 + ks = kustomizations(state, cluster) + want = [n for n in names or ['flux-system/fleet-cluster'] + EXPECTED[cluster] + ([n for n in SITE_LAYERS if n in ks] if cluster == 'cell' else []) + if n not in skip and not ks.get(n, {}).get('spec', {}).get('suspend')] + for n in want: + if n in ks and (n not in tokens or lost(ks[n], tokens[n])): + if n in tokens: + reissued[n] = reissued.get(n, 0) + 1 + tokens[n] = request(state, cluster, 'kustomizations.kustomize.toolkit.fluxcd.io', n) + last = {n: {'requestedAt': tokens.get(n), 'lastHandledReconcileAt': ks.get(n, {}).get('status', {}).get('lastHandledReconcileAt'), 'ready': ready(ks[n]) if n in ks else False, 'revision': ks.get(n, {}).get('status', {}).get('lastAppliedRevision'), + 'reason': conditions(ks.get(n, {})).get('Ready', {}).get('reason')} for n in want} + observe(state, cluster, revision, ks) + for other in observe_also: + if other != cluster: + try: + observe(state, other, revision, kustomizations(state, other)) + except SystemExit: + pass # an unreachable cluster is sampled on the next poll + if ready(source) and source.get('status', {}).get('lastHandledReconcileAt') == source_token and source.get('status', {}).get('artifact', {}).get('revision') == revision and all( + v['ready'] and v['revision'] == revision and v['requestedAt'] is not None and v['lastHandledReconcileAt'] == v['requestedAt'] for v in last.values()): + path = pathlib.Path(state) / 'evidence' / 'flux-reconciles.json' + records = json.loads(path.read_text()) if path.exists() else [] + records.append({'cluster': cluster, 'revision': revision, 'observedAt': now(), 'sourceRequestedAt': source_token, 'sourceLastHandledReconcileAt': source['status']['lastHandledReconcileAt'], 'kustomizations': last, + 'lostRequestsReissued': reissued}) + write(path, records) + return last + time.sleep(3) + die('%s did not converge on %s: %s' % (cluster, revision, json.dumps(last)), harness.EXIT_TIMEOUT) + + +def observe(state, cluster, revision, ks): + """Record each distinct non-Ready reason seen while waiting, e.g. dependency gating.""" + path = pathlib.Path(state) / 'flux-wait-observations.json' + seen = json.loads(path.read_text()) if path.exists() else [] + # Keyed by whether the revision was already applied, so a dependent seen + # gated after applying (a dependency re-reconciling) never masks the + # gated-before-apply observation, or the reverse. + keys = {(o['cluster'], o['kustomization'], o['revision'], o['reason'], o['lastAppliedRevision'] == o['revision']) for o in seen} + for n, o in ks.items(): + c = conditions(o).get('Ready', {}) + key = (cluster, n, revision, c.get('reason'), o.get('status', {}).get('lastAppliedRevision') == revision) + if c.get('status') != 'True' and key not in keys: + keys.add(key) + seen.append({'cluster': cluster, 'kustomization': n, 'revision': revision, 'reason': c.get('reason'), + 'message': c.get('message', '')[:160], 'lastAppliedRevision': o.get('status', {}).get('lastAppliedRevision'), + 'inventoryEntries': len(inventory(o)), 'observedAt': now()}) + write(path, seen) + + +def wait_cmd(args): + for cluster in args.cluster: + wait_cluster(args.state, cluster, args.timeout, skip=args.skip, observe_also=args.observe) + print('wait: %s Kustomizations Ready at %s' % (cluster, current(args.state)['fluxRevision'])) + return 0 + + +def bootstrap(args): + """The documented bootstrap boundary: Flux components and sync objects, once.""" + s = pathlib.Path(args.state).resolve() + first = s / 'gitops' / 'r1' + components = subprocess.run(['kustomize', 'build', str(first / 'environment/flux-components')], capture_output=True, text=True, check=True).stdout + path = s / ('flux-bootstrap-%s.yaml' % args.cluster) + path.write_text(components) + sync = first / 'environment' / args.cluster / 'flux-system' / 'gotk-sync.yaml' + # Components (with CRDs) first, then the sync objects once the CRDs serve. + # The bootstrap applies under kustomize-controller's own field manager, so + # when Flux reconciles the same objects it takes them over with no residual + # second manager (and no second writer) left behind. + kubectl(s, args.cluster, 'apply', '--server-side', '--field-manager=kustomize-controller', '-f', str(path), timeout=180) + kubectl(s, args.cluster, 'wait', '--for=condition=Established', 'crd/kustomizations.kustomize.toolkit.fluxcd.io', + 'crd/ocirepositories.source.toolkit.fluxcd.io', 'crd/helmreleases.helm.toolkit.fluxcd.io', '--timeout=120s', timeout=140) + kubectl(s, args.cluster, '-n', 'flux-system', 'wait', '--for=condition=Available', 'deployment', '--all', '--timeout=300s', timeout=320) + kubectl(s, args.cluster, 'apply', '--server-side', '--field-manager=kustomize-controller', '-f', str(sync), timeout=60) + record = {'cluster': args.cluster, 'appliedAt': now(), 'componentsSHA256': sha256(path), 'syncSHA256': sha256(sync), 'fieldManager': 'kustomize-controller', + 'objects': len([d for d in components.split('\n---\n') if d.strip()]) + 2} + write(s / ('flux-bootstrap-%s.json' % args.cluster), record) + print('bootstrap: %s Flux v%s controllers Available; sync objects applied once (%d objects)' % (args.cluster, FLUX_VERSION, record['objects'])) + return 0 + + +def publish(args): + a = argparse.Namespace(**vars(args)) + stage(a) + push(a) + for cluster in args.cluster: + wait_cluster(args.state, cluster, args.timeout) + print('publish: r%d reconciled on %s' % (args.revision, ', '.join(args.cluster) or 'no cluster (waited later)')) + return 0 + + +# ---------------------------------------------------------------- evidence + +def inventory(obj): + return sorted(e['id'] for e in obj.get('status', {}).get('inventory', {}).get('entries', [])) + + +def snapshot(state, cluster): + ks = kustomizations(state, cluster) + oci = kget(state, cluster, 'get', 'ocirepositories.source.toolkit.fluxcd.io', '-A')['items'] + hr = kget(state, cluster, 'get', 'helmreleases.helm.toolkit.fluxcd.io', '-A')['items'] + hrepo = kget(state, cluster, 'get', 'helmrepositories.source.toolkit.fluxcd.io', '-A')['items'] + charts = kget(state, cluster, 'get', 'helmcharts.source.toolkit.fluxcd.io', '-A')['items'] + deploys = kget(state, cluster, '-n', 'flux-system', 'get', 'deployments')['items'] + + def cond(o): + return sorted([c['type'], c['status'], c.get('reason', '')] for c in o.get('status', {}).get('conditions', [])) + return { + 'cluster': cluster, 'observedAt': now(), + 'controllers': {d['metadata']['name']: {'image': d['spec']['template']['spec']['containers'][0]['image'], 'uid': d['metadata']['uid'], + 'availableReplicas': d['status'].get('availableReplicas', 0)} for d in deploys}, + 'sources': {o['metadata']['namespace'] + '/' + o['metadata']['name']: { + 'url': o['spec']['url'], 'ref': o['spec'].get('ref'), 'artifactRevision': o.get('status', {}).get('artifact', {}).get('revision'), + 'artifactDigest': o.get('status', {}).get('artifact', {}).get('digest'), 'generation': o['metadata']['generation'], + 'observedGeneration': o.get('status', {}).get('observedGeneration'), 'conditions': cond(o)} for o in oci + hrepo}, + 'helmCharts': {o['metadata']['namespace'] + '/' + o['metadata']['name']: { + 'chart': o['spec'].get('chart'), 'version': o['spec'].get('version'), 'artifactRevision': o.get('status', {}).get('artifact', {}).get('revision'), + 'artifactDigest': o.get('status', {}).get('artifact', {}).get('digest'), 'conditions': cond(o)} for o in charts}, + 'kustomizations': {n: {'path': o['spec']['path'], 'prune': o['spec'].get('prune'), 'wait': o['spec'].get('wait'), + 'dependsOn': o['spec'].get('dependsOn', []), 'serviceAccountName': o['spec'].get('serviceAccountName'), + 'remote': bool(o['spec'].get('kubeConfig')), 'suspend': o['spec'].get('suspend', False), + 'generation': o['metadata']['generation'], 'observedGeneration': o.get('status', {}).get('observedGeneration'), + 'lastAppliedRevision': o.get('status', {}).get('lastAppliedRevision'), + 'lastAttemptedRevision': o.get('status', {}).get('lastAttemptedRevision'), + 'conditions': cond(o), 'inventory': inventory(o)} for n, o in ks.items()}, + 'helmReleases': {o['metadata']['namespace'] + '/' + o['metadata']['name']: { + 'generation': o['metadata']['generation'], 'observedGeneration': o.get('status', {}).get('observedGeneration'), + 'conditions': cond(o), 'driftDetection': o['spec'].get('driftDetection'), + 'history': [{k: h.get(k) for k in ('name', 'namespace', 'version', 'chartName', 'chartVersion', 'appVersion', 'digest', 'status', 'configDigest')} + for h in o.get('status', {}).get('history', [])], + 'lastAttemptedRevision': o.get('status', {}).get('lastAttemptedRevision'), + 'lastAttemptedRevisionDigest': o.get('status', {}).get('lastAttemptedRevisionDigest')} for o in hr}, + } + + +def record(args): + snap = {c: snapshot(args.state, c) for c in args.cluster} + write(pathlib.Path(args.state) / 'evidence' / ('flux-%s.json' % args.name), snap) + print('record: Flux snapshot %s for %s' % (args.name, ', '.join(args.cluster))) + return 0 + + +def labels(obj): + return obj['metadata'].get('labels', {}) or {} + + +def flux_owned(obj): + return 'kustomize.toolkit.fluxcd.io/name' in labels(obj) + + +def kro_marked(obj): + l = labels(obj) + return any(k.startswith('kro.run/') for k in l) or 'applyset.kubernetes.io/part-of' in l or l.get('app.kubernetes.io/managed-by') == 'kro' + + +def ownership(state, snaps): + """One writer per site object: a named Flux layer for shared infrastructure, + kro only for per-operation worker objects. Returns (record, problems).""" + s = pathlib.Path(state) + problems = [] + cell_ks = snaps['cell']['kustomizations'] + every = sorted({e for c in snaps.values() for k in c['kustomizations'].values() for e in k['inventory']}) + layers = {} + for layer, expected in LAYER_INVENTORY.items(): + layers[layer] = cell_ks.get(layer, {}).get('inventory') + if layers[layer] != expected: + problems.append('%s inventory is not exactly %s: %s' % (layer, expected, layers[layer])) + shared = [] + for (kind, ns, name), layer in sorted(SHARED.items(), key=str): + r = kubectl(s, 'cell', *(['-n', ns] if ns else []), 'get', kind, name, '-o', 'json', check=False) + if r.returncode: + problems.append('shared %s %s/%s is missing' % (kind, ns, name)) + continue + o = json.loads(r.stdout) + rec = {'kind': kind, 'namespace': ns, 'name': name, 'uid': o['metadata']['uid'], 'fluxLayer': labels(o).get('kustomize.toolkit.fluxcd.io/name'), + 'kroMarked': kro_marked(o), 'ownerReferences': sorted(x.get('kind', '') for x in o['metadata'].get('ownerReferences', [])), + 'inLayerInventory': any(e.startswith('%s_%s_' % (ns or '', name)) for e in cell_ks.get('flux-system/' + layer, {}).get('inventory', []))} + shared.append(rec) + if rec['fluxLayer'] != layer or rec['kroMarked'] or rec['ownerReferences'] or not rec['inLayerInventory']: + problems.append('shared object not solely owned by Flux %s: %s' % (layer, rec)) + kro_written = [] + for kind, ns in WORKER_KINDS + (('deployments', SITE), ('services', SITE), ('configmaps', SITE), ('persistentvolumeclaims', SITE)): + for o in kget(s, 'cell', '-n', ns, 'get', kind)['items']: + name = o['metadata']['name'] + worker = name.startswith('w-op-') + if kind == 'jobs' and not worker: + problems.append('Job outside the per-operation set: %s' % name) + if not worker and not kro_marked(o): + continue + rec = {'kind': kind, 'namespace': ns, 'name': name, 'uid': o['metadata']['uid'], 'kroNode': labels(o).get('kro.run/node-id'), + 'fluxOwned': flux_owned(o), 'inFluxInventory': any(e.startswith('%s_%s_' % (ns, name)) for e in every)} + kro_written.append(rec) + if (kind, ns) not in WORKER_KINDS or not worker or not rec['kroNode'] or rec['fluxOwned'] or rec['inFluxInventory']: + problems.append('kro wrote outside the per-operation set, or a worker object is not solely kro-owned: %s' % rec) + for forbidden in ('batch_Job', '_Pod', '_MachineAllocationHandoff', '_Secret'): + hits = [e for e in every if e.endswith(forbidden)] + if hits: + problems.append('Flux inventory contains %s: %s' % (forbidden, hits[:4])) + if [e for e in every if '_w-op-' in e]: + problems.append('a per-operation worker object is in a Flux inventory') + deps = {n: sorted(d['name'] for d in cell_ks.get(n, {}).get('dependsOn', [])) for n in ['flux-system/fleet-site-base'] + SITE_LAYERS + ['flux-system/fleet-site-graph']} + if 'kro' in deps['flux-system/fleet-site-base'] + deps['flux-system/fleet-site-services']: + problems.append('shared site infrastructure depends on kro: %s' % deps) + if not {'fleet-site-graph', 'fleet-site-services'} <= set(deps['flux-system/fleet-site-dispatch']): + problems.append('the dispatcher does not depend on the graph and the shared services: %s' % deps) + record = {'observedAt': now(), 'layerInventories': layers, 'sharedObjects': shared, 'kroWrittenObjects': kro_written, + 'siteDependsOn': deps, 'problems': problems} + return record, problems + + +def ownership_cmd(args): + snaps = {c: snapshot(args.state, c) for c in CLUSTERS} + record, problems = ownership(args.state, snaps) + write(pathlib.Path(args.state) / 'evidence' / ('flux-ownership-%s.json' % args.name), record) + if problems: + die('ownership audit failed:\n ' + '\n '.join(problems)) + print('ownership: %d shared site objects each owned by one Flux layer; kro wrote only %d per-operation worker objects' + % (len(record['sharedObjects']), len(record['kroWrittenObjects']))) + return 0 + + +def verify(args): + """Source identity, readiness, ownership and inventory on every cluster.""" + s = pathlib.Path(args.state) + rev = current(s) + problems = [] + snaps = {} + for cluster in CLUSTERS: + snap = snapshot(s, cluster) + snaps[cluster] = snap + src = snap['sources'].get('flux-system/fleet-gitops', {}) + if src.get('artifactRevision') != rev['fluxRevision']: + problems.append('%s source at %s, pushed %s' % (cluster, src.get('artifactRevision'), rev['fluxRevision'])) + for n in ['flux-system/fleet-cluster'] + EXPECTED[cluster] + (SITE_LAYERS if cluster == 'cell' else []): + k = snap['kustomizations'].get(n) + if not k or ['Ready', 'True', 'ReconciliationSucceeded'] not in k['conditions'] or k['generation'] != k['observedGeneration'] or k['lastAppliedRevision'] != rev['fluxRevision']: + problems.append('%s %s not Ready at the pushed revision: %s' % (cluster, n, k and (k['conditions'], k['lastAppliedRevision']))) + for n in HELMRELEASES.get(cluster, []): + h = snap['helmReleases'].get(n) + if not h or ['Ready', 'True', 'InstallSucceeded'] not in h['conditions'] and ['Ready', 'True', 'UpgradeSucceeded'] not in h['conditions'] or h['generation'] != h['observedGeneration']: + problems.append('%s HelmRelease %s not Ready: %s' % (cluster, n, h and h['conditions'])) + if set(snap['controllers']) != {'source-controller', 'kustomize-controller', 'helm-controller', 'notification-controller'} or any( + '@sha256:' not in c['image'] or c['availableReplicas'] != 1 for c in snap['controllers'].values()): + problems.append('%s Flux controllers not the pinned set: %s' % (cluster, snap['controllers'])) + cell = snaps['cell'] + hub = snaps['hub'] + kro_src = cell['sources'].get('flux-system/kro-chart', {}) + if (kro_src.get('ref') or {}).get('digest') != KRO_CHART_DIGEST or not str(kro_src.get('artifactRevision', '')).endswith(KRO_CHART_DIGEST): + problems.append('kro chart source not at pinned digest: %s' % kro_src) + kro_hist = (cell['helmReleases'].get('flux-system/kro', {}).get('history') or [{}])[0] + # helm-controller suffixes an OCI chart's version with its manifest digest. + if kro_hist.get('chartVersion') != '0.9.4+' + KRO_CHART_DIGEST[7:19] or kro_hist.get('status') != 'deployed': + problems.append('kro release history: %s' % kro_hist) + karmada_chart = next((c for c in hub['helmCharts'].values() if c['chart'] == 'karmada'), {}) + if karmada_chart.get('artifactDigest') != 'sha256:' + KARMADA_CHART_SHA256: + problems.append('Karmada chart artifact digest %s, expected sha256:%s' % (karmada_chart.get('artifactDigest'), KARMADA_CHART_SHA256)) + karmada_hist = (hub['helmReleases'].get('flux-system/karmada', {}).get('history') or [{}])[0] + if karmada_hist.get('chartVersion') != 'v1.16.0' or karmada_hist.get('status') != 'deployed': + problems.append('karmada release history: %s' % karmada_hist) + # Ownership: Flux layers own the shared site; kro alone owns per-operation workers. + owners, owner_problems = ownership(s, snaps) + problems += owner_problems + if owners['kroWrittenObjects']: + problems.append('kro wrote objects before dispatch: %s' % owners['kroWrittenObjects']) + pvc = kget(s, 'cell', '-n', 'fleet-site', 'get', 'pvc', 'fleet-site-state') + pvc_ann = pvc['metadata'].get('annotations', {}) + if pvc_ann.get('kustomize.toolkit.fluxcd.io/prune') != 'disabled' or pvc_ann.get('kustomize.toolkit.fluxcd.io/ssa') != 'IfNotPresent': + problems.append('site volume claim is not retained by Flux policy: %s' % pvc_ann) + protected = {} + for cluster, kind, ns, name in (('cell', 'namespace', None, 'fleet-site'), ('cell', 'namespace', None, 'fleet-coordination'), + ('cell', 'crd', None, 'machineallocationhandoffs.coordination.fleet.datumapis.com'), + ('cell', 'resourcegraphdefinition', None, RGD), ('cell', DISPATCHER[0], SITE, DISPATCHER[1]), + ('cell', 'storageclass', None, 'fleet-site-retain'), ('hub', 'namespace', None, 'fleet-system-private')): + o = kget(s, cluster, *(['-n', ns] if ns else []), 'get', kind, name) + value = o['metadata'].get('annotations', {}).get('kustomize.toolkit.fluxcd.io/prune') + protected['%s/%s/%s' % (cluster, kind, name)] = value + if value != 'disabled': + problems.append('%s %s %s is prunable' % (cluster, kind, name)) + handoffs = kget(s, 'cell', '-n', 'fleet-coordination', 'get', 'machineallocationhandoffs')['items'] + if any(flux_owned(h) for h in handoffs): + problems.append('a handoff carries Flux ownership labels') + # Bootstrap dependency ordering, as Flux recorded it while every cluster was sampled. + seen = json.loads((s / 'flux-wait-observations.json').read_text()) if (s / 'flux-wait-observations.json').exists() else [] + first = revisions(s)[0]['fluxRevision'] + events = [o for o in seen if o['reason'] == 'DependencyNotReady'] + # Gating before apply: the dependent had applied nothing of r1. Gating after + # apply is a dependency re-reconciling at the same revision (for example on + # a fresh request) and is recorded, not counted as either evidence or fault. + gated = [o for o in events if o['revision'] == first and not o['lastAppliedRevision'] and not o['inventoryEntries']] + regated = [o for o in events if o['revision'] == first and o['lastAppliedRevision'] == first] + for o in events: + if o['revision'] == first and o['lastAppliedRevision'] not in (None, first): + problems.append('dependent applied another revision during bootstrap: %s' % o) + elif o['revision'] == first and not o['lastAppliedRevision'] and o['inventoryEntries']: + problems.append('dependent has an inventory before applying while its dependency is not Ready: %s' % o) + for cluster in ('cell', 'hub'): + if not [o for o in gated if o['cluster'] == cluster]: + problems.append('no dependency gating before apply was observed on %s during bootstrap' % cluster) + result = {'observedAt': now(), 'revision': rev, 'revisions': revisions(s), 'tools': json.loads((s / 'flux-tools' / 'tools.json').read_text()), + 'bootstrap': [json.loads((s / ('flux-bootstrap-%s.json' % c)).read_text()) for c in CLUSTERS], + 'pins': {'kroChartManifestDigest': KRO_CHART_DIGEST, 'kroChartLayerSHA256': KRO_CHART_LAYER_SHA256, + 'karmadaChartSHA256': KARMADA_CHART_SHA256, 'registryImage': REGISTRY_IMAGE}, + 'ownership': owners, 'pruneProtected': protected, 'siteVolumeAnnotations': {k: v for k, v in pvc_ann.items() if 'fluxcd' in k}, + 'handoffsFluxOwned': False, 'bootstrapDependencyEvents': events, 'bootstrapGatedBeforeApply': gated, + 'bootstrapRegatedAfterApply': regated, 'problems': problems} + write(s / 'evidence' / 'flux-verify.json', result) + write(s / 'evidence' / 'flux-initial.json', snaps) + if problems: + die('flux verification failed:\n ' + '\n '.join(problems)) + print('flux-verify: 3 clusters Ready at %s; pinned charts and controllers; Flux layers own %d shared site objects; kro owns %d per-operation objects; volume, CRD, graph and instance prune-protected' + % (rev['fluxRevision'], len(owners['sharedObjects']), len(owners['kroWrittenObjects']))) + return 0 + + +# ---------------------------------------------------------------- scenarios + +def site_facts(state): + """Effect and custody facts that no GitOps action may change.""" + s = pathlib.Path(state) + jobs = sorted((j['metadata']['name'], j['metadata']['uid']) for j in kget(s, 'cell', '-n', 'fleet-site', 'get', 'jobs')['items']) + pvc = kget(s, 'cell', '-n', 'fleet-site', 'get', 'pvc', 'fleet-site-state') + pv = kget(s, 'cell', 'get', 'pv', pvc['spec']['volumeName']) + journal = kubectl(s, 'cell', '-n', 'fleet-site', 'exec', 'deploy/fleet-site-runtime', '-c', 'libvirt', '--', 'cat', '/var/lib/fleet-local/journal.json').stdout + secrets = kget(s, 'hub', '-n', 'fleet-system-private', 'get', 'secrets')['items'] + custody = hashlib.sha256(json.dumps(sorted((i['metadata']['name'], i['metadata']['uid'], i['metadata']['resourceVersion']) for i in secrets)).encode()).hexdigest() + return {'jobs': jobs, 'pvcUID': pvc['metadata']['uid'], 'pvUID': pv['metadata']['uid'], 'pvPhase': pv['status'].get('phase'), + 'reclaimPolicy': pv['spec']['persistentVolumeReclaimPolicy'], 'journalSHA256': hashlib.sha256(journal.encode()).hexdigest(), + 'custodyRecords': len(secrets), 'custodyDigest': custody} + + +def same_facts(before, after, what): + if before != after: + die('%s changed effect or custody facts: before %s after %s' % (what, before, after)) + + +def wait_for(fn, timeout, what, interval=2): + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + value = fn() + if value: + return value + time.sleep(interval) + die(what + ' not observed before deadline', harness.EXIT_TIMEOUT) + + +def drift(args): + """Out-of-band changes corrected by Flux, not by the harness.""" + s = pathlib.Path(args.state) + before = site_facts(s) + out = {'observedAt': now(), 'cases': []} + # 1. helm-controller drift correction of the kro release. + d = kget(s, 'cell', '-n', 'kro-system', 'get', 'deployment', 'kro') + kubectl(s, 'cell', '-n', 'kro-system', 'scale', 'deployment/kro', '--replicas=0') + request(s, 'cell', 'helmreleases.helm.toolkit.fluxcd.io', 'flux-system/kro') + + def kro_back(): + x = kget(s, 'cell', '-n', 'kro-system', 'get', 'deployment', 'kro') + return x if x['spec']['replicas'] == 1 and x['status'].get('availableReplicas') == 1 else None + restored = wait_for(kro_back, 300, 'helm-controller correction of kro replicas') + hr = kget(s, 'cell', '-n', 'flux-system', 'get', 'helmreleases.helm.toolkit.fluxcd.io', 'kro') + events = [e.get('message', '')[:200] for e in kget(s, 'cell', '-n', 'flux-system', 'get', 'events', '--field-selector', 'involvedObject.name=kro')['items'] + if 'drift' in e.get('message', '').lower()] + out['cases'].append({'case': 'kro Deployment scaled to 0 out of band', 'correctedBy': 'helm-controller driftDetection=enabled', + 'deploymentUID': d['metadata']['uid'], 'sameDeployment': restored['metadata']['uid'] == d['metadata']['uid'], + 'releaseVersion': [h.get('version') for h in hr['status'].get('history', [])][:1], 'events': events[:3]}) + # 2. kustomize-controller recreates a deleted Karmada-API object over the remote kubeconfig. + old = kget(s, 'hub', 'get', 'resourceinterpretercustomizations.config.karmada.io', 'fleet-machine-allocation-handoff', config='hub-admin.yaml') + kubectl(s, 'hub', 'delete', 'resourceinterpretercustomizations.config.karmada.io', 'fleet-machine-allocation-handoff', config='hub-admin.yaml') + request(s, 'hub', 'kustomizations.kustomize.toolkit.fluxcd.io', 'karmada-system/fleet-karmada-api') + + def interp_back(): + r = kubectl(s, 'hub', 'get', 'resourceinterpretercustomizations.config.karmada.io', 'fleet-machine-allocation-handoff', '-o', 'json', check=False, config='hub-admin.yaml') + return json.loads(r.stdout) if r.returncode == 0 else None + new = wait_for(interp_back, 300, 'Flux recreation of the Karmada interpreter') + if new['metadata']['uid'] == old['metadata']['uid'] or new['spec'] != old['spec']: + die('interpreter was not recreated from the source') + out['cases'].append({'case': 'Karmada interpreter deleted on the Karmada API', 'correctedBy': 'kustomize-controller (remote kubeConfig)', + 'oldUID': old['metadata']['uid'], 'newUID': new['metadata']['uid'], 'specFromSource': True}) + # 3. kustomize-controller reverts an in-place edit of a site policy object. + kubectl(s, 'cell', 'patch', 'clusterrole', 'fleet-site-kro', '--type=json', '-p', + '[{"op":"add","path":"/rules/-","value":{"apiGroups":[""],"resources":["secrets"],"verbs":["get"]}}]') + request(s, 'cell', 'kustomizations.kustomize.toolkit.fluxcd.io', 'flux-system/fleet-site-base') + + def role_back(): + rules = kget(s, 'cell', 'get', 'clusterrole', 'fleet-site-kro').get('rules', []) + return not any('secrets' in r.get('resources', []) for r in rules) + wait_for(role_back, 300, 'Flux reversion of the widened kro grant') + out['cases'].append({'case': 'fleet-site-kro ClusterRole widened to read Secrets', 'correctedBy': 'kustomize-controller server-side apply', 'secretReadRemoved': True}) + # 4. kustomize-controller recreates the deleted shared boot Service, with the + # same fixed ClusterIP, as the scoped services identity. kro must not write it. + svc = kget(s, 'cell', '-n', SITE, 'get', 'service', 'fleet-site-boot') + kubectl(s, 'cell', '-n', SITE, 'delete', 'service', 'fleet-site-boot', '--wait=true') + request(s, 'cell', 'kustomizations.kustomize.toolkit.fluxcd.io', 'flux-system/fleet-site-services') + + def svc_back(): + r = kubectl(s, 'cell', '-n', SITE, 'get', 'service', 'fleet-site-boot', '-o', 'json', check=False) + o = json.loads(r.stdout) if r.returncode == 0 else None + return o if o and o['metadata']['uid'] != svc['metadata']['uid'] else None + new_svc = wait_for(svc_back, 300, 'Flux recreation of the boot Service') + same = {k: new_svc['spec'].get(k) == svc['spec'].get(k) for k in ('clusterIP', 'clusterIPs', 'ports', 'selector', 'type')} + if not all(same.values()) or new_svc['spec']['clusterIP'] != BOOT_SERVICE_IP or labels(new_svc).get('kustomize.toolkit.fluxcd.io/name') != 'fleet-site-services' or kro_marked(new_svc): + die('boot Service was not recreated by Flux with the same fixed ClusterIP and spec: %s' % same) + out['cases'].append({'case': 'shared boot Service deleted', 'correctedBy': 'kustomize-controller as fleet-site-services-reconciler', 'oldUID': svc['metadata']['uid'], + 'newUID': new_svc['metadata']['uid'], 'clusterIP': new_svc['spec']['clusterIP'], 'specUnchanged': same, 'fluxLayer': 'fleet-site-services', 'kroMarked': False}) + # 5. kustomize-controller restores the shared observer Deployment scaled to 0. + obs = kget(s, 'cell', '-n', SITE, 'get', 'deployment', 'fleet-site-observer') + kubectl(s, 'cell', '-n', SITE, 'scale', 'deployment/fleet-site-observer', '--replicas=0') + request(s, 'cell', 'kustomizations.kustomize.toolkit.fluxcd.io', 'flux-system/fleet-site-services') + + def obs_back(): + x = kget(s, 'cell', '-n', SITE, 'get', 'deployment', 'fleet-site-observer') + return x if x['spec']['replicas'] == 1 and x['status'].get('availableReplicas') == 1 and x['metadata']['generation'] > obs['metadata']['generation'] else None + restored_obs = wait_for(obs_back, 300, 'Flux restoration of the observer Deployment') + if restored_obs['metadata']['uid'] != obs['metadata']['uid']: + die('observer Deployment was replaced instead of restored') + out['cases'].append({'case': 'shared observer Deployment scaled to 0', 'correctedBy': 'kustomize-controller as fleet-site-services-reconciler', + 'deploymentUID': obs['metadata']['uid'], 'sameDeployment': True, 'generationBefore': obs['metadata']['generation'], + 'generationAfter': restored_obs['metadata']['generation']}) + # The dispatcher must return to ACTIVE against the repaired references. + wait_for(lambda: kget(s, 'cell', '-n', SITE, 'get', DISPATCHER[0], DISPATCHER[1]).get('status', {}).get('state') == 'ACTIVE', 300, 'dispatcher ACTIVE after repair') + snaps = {c: snapshot(s, c) for c in CLUSTERS} + owners, problems = ownership(s, snaps) + if problems: + die('ownership after drift repair:\n ' + '\n '.join(problems)) + out['ownershipAfterRepair'] = owners + after = site_facts(s) + same_facts(before, after, 'drift correction') + out['siteFacts'] = after + write(s / 'evidence' / 'flux-drift.json', out) + print('flux-drift: helm-controller restored kro, kustomize-controller recreated the Karmada interpreter, reverted a widened grant, recreated the shared boot Service at its fixed ClusterIP and restored the observer; journal, Jobs, volume and custody unchanged') + return 0 + + +def suspend(state, cluster, ref, value): + namespace, name = ref.split('/') + kubectl(state, cluster, '-n', namespace, 'patch', 'kustomizations.kustomize.toolkit.fluxcd.io', name, '--field-manager=fleet-fault-injection', + '--type=merge', '-p', json.dumps({'spec': {'suspend': value}})) + + +def shared_uids(state): + """Identity of every Flux-owned shared site object, the PV and the dispatcher graph.""" + s = pathlib.Path(state) + out = {} + for kind, ns, name in sorted(SHARED, key=str): + out['%s/%s/%s' % (kind, ns, name)] = kget(s, 'cell', *(['-n', ns] if ns else []), 'get', kind, name)['metadata']['uid'] + out['rgd'] = kget(s, 'cell', 'get', 'resourcegraphdefinition', RGD)['metadata']['uid'] + out['storageclass'] = kget(s, 'cell', 'get', 'storageclass', 'fleet-site-retain')['metadata']['uid'] + return out + + +def worker_objects(state): + s = pathlib.Path(state) + return sorted((kind, o['metadata']['name'], o['metadata']['uid']) for kind, ns in WORKER_KINDS + for o in kget(s, 'cell', '-n', ns, 'get', kind)['items'] if o['metadata']['name'].startswith('w-op-')) + + +def graph_lifecycle(args): + """Deleting the dispatcher instance removes only kro's per-operation objects. + + Flux then recreates the instance from the source and kro recreates the + workers, which replay a verified no-op. Shared services, the journal + volume, the journal, guests and custody are untouched throughout. + """ + s = pathlib.Path(args.state) + handoff = (s / 'install-handoff').read_text().strip() + snaps = {c: snapshot(s, c) for c in CLUSTERS} + owners, problems = ownership(s, snaps) + if problems: + die('ownership with workers present:\n ' + '\n '.join(problems)) + want = sorted(['jobs', 'serviceaccounts', 'roles', 'rolebindings']) + if sorted(k for k, n, _ in worker_objects(s) if n == 'w-' + handoff) != want: + die('expected one kro-written Job, ServiceAccount, Role and RoleBinding for the install handoff: %s' % worker_objects(s)) + before, uids, workers = site_facts(s), shared_uids(s), worker_objects(s) + status = kget(s, 'cell', '-n', COORD, 'get', 'machineallocationhandoff', handoff).get('status', {}).get('observation', {}).get('result', {}).get('phase') + if status != 'Succeeded': + die('install handoff is not terminal before the graph lifecycle: %s' % status) + old = kget(s, 'cell', '-n', SITE, 'get', DISPATCHER[0], DISPATCHER[1]) + # Explicit ownership transfer for the fault: suspend the instance's Flux + # layer so the harness is never a second concurrent writer, then delete the + # instance out of band. + suspend(s, 'cell', 'flux-system/fleet-site-dispatch', True) + kubectl(s, 'cell', '-n', SITE, 'delete', DISPATCHER[0], DISPATCHER[1], '--wait=true', timeout=300) + wait_for(lambda: not worker_objects(s), 300, 'kro removal of per-operation objects') + during_uids, during = shared_uids(s), site_facts(s) + if during_uids != uids: + die('instance deletion changed shared site objects: %s -> %s' % (uids, during_uids)) + same_facts(dict(before, jobs=[]), during, 'dispatcher instance deletion') + for d in SITE_DEPLOYMENTS: + if kget(s, 'cell', '-n', SITE, 'get', 'deployment', d)['status'].get('availableReplicas') != 1: + die(d + ' became unavailable when the dispatcher was deleted') + # Resuming hands ownership back: Flux, not the harness, restores the instance. + suspend(s, 'cell', 'flux-system/fleet-site-dispatch', False) + wait_cluster(s, 'cell', 600) + new = kget(s, 'cell', '-n', SITE, 'get', DISPATCHER[0], DISPATCHER[1]) + if new['metadata']['uid'] == old['metadata']['uid'] or labels(new).get('kustomize.toolkit.fluxcd.io/name') != 'fleet-site-dispatch': + die('dispatcher was not recreated by Flux') + + def replayed(): + j = kget(s, 'cell', '-n', SITE, 'get', 'jobs')['items'] + done = [x for x in j if x['metadata']['name'] == 'w-' + handoff and any(c['type'] == 'Complete' and c['status'] == 'True' for c in x['status'].get('conditions', []))] + return done[0] if done else None + job = wait_for(replayed, 600, 'recreated worker Job completing its verified no-op replay', interval=3) + pods = [p for p in kget(s, 'cell', '-n', SITE, 'get', 'pods', '-l', 'batch.kubernetes.io/controller-uid=' + job['metadata']['uid'])['items']] + exits = [next((c['state']['terminated']['exitCode'] for c in p['status'].get('containerStatuses', []) if 'terminated' in c.get('state', {})), None) for p in pods] + if exits != [0]: + die('recreated worker Job did not finish with one verified no-op replay: %s' % exits) + after_uids, after = shared_uids(s), site_facts(s) + if after_uids != uids: + die('instance recreation changed shared site objects') + same_facts(dict(before, jobs=[]), dict(after, jobs=[]), 'dispatcher instance recreation') + snaps = {c: snapshot(s, c) for c in CLUSTERS} + owners_after, problems = ownership(s, snaps) + if problems: + die('ownership after the graph lifecycle:\n ' + '\n '.join(problems)) + status_after = kget(s, 'cell', '-n', COORD, 'get', 'machineallocationhandoff', handoff).get('status', {}).get('observation', {}).get('result', {}).get('phase') + if status_after != 'Succeeded': + die('install handoff lost its terminal observation across the graph lifecycle: %s' % status_after) + # kro deletes Jobs without a propagation policy, so batch/v1 orphans their + # (already terminal) Pods. Recorded, not hidden; see site-execution.md. + live_jobs = {j['metadata']['uid'] for j in kget(s, 'cell', '-n', SITE, 'get', 'jobs')['items']} + orphans = [{'pod': p['metadata']['name'], 'phase': p['status'].get('phase')} for p in kget(s, 'cell', '-n', SITE, 'get', 'pods', '-l', 'fleet.datumapis.com/handoff=' + handoff)['items'] + if labels(p).get('batch.kubernetes.io/controller-uid') not in live_jobs] + if any(o['phase'] not in ('Succeeded', 'Failed') for o in orphans): + die('a non-terminal worker Pod outlived its Job: %s' % orphans) + write(s / 'evidence' / 'flux-graph-lifecycle.json', { + 'observedAt': now(), 'handoff': handoff, 'deletedInstanceUID': old['metadata']['uid'], 'recreatedInstanceUID': new['metadata']['uid'], + 'recreatedBy': 'kustomize-controller (Kustomization fleet-site-dispatch)', 'workerObjectsBefore': workers, 'workerObjectsAfter': worker_objects(s), + 'workerObjectsRemovedByKro': True, 'sharedObjectUIDs': uids, 'sharedObjectsUnchanged': True, 'replayJobUID': job['metadata']['uid'], 'replayExitCodes': exits, + 'handoffResultPhase': [status, status_after], 'orphanedTerminalWorkerPods': orphans, 'ownershipWithWorkers': owners, 'ownershipAfter': owners_after, 'siteFactsBefore': before, 'siteFactsAfter': after}) + print('flux-graph-lifecycle: deleting the dispatcher removed only kro per-operation objects; shared services, volume, journal and custody unchanged; Flux recreated it and the replayed Job was a verified no-op') + return 0 + + +def restart(args): + """Restart every Flux controller; reconcile must not re-execute or upgrade anything.""" + s = pathlib.Path(args.state) + before = site_facts(s) + snap_before = {c: snapshot(s, c) for c in CLUSTERS} + + def pod_uids(cluster): + return sorted(p['metadata']['uid'] for p in kget(s, cluster, '-n', 'flux-system', 'get', 'pods')['items'] if not p['metadata'].get('deletionTimestamp')) + pods_before = {c: pod_uids(c) for c in CLUSTERS} + release_tokens = {} + for cluster in CLUSTERS: + kubectl(s, cluster, '-n', 'flux-system', 'delete', 'pod', '--all', '--wait=true', timeout=180) + for cluster in CLUSTERS: + kubectl(s, cluster, '-n', 'flux-system', 'wait', '--for=condition=Available', 'deployment', '--all', '--timeout=300s', timeout=320) + for kind, ref in [('kustomizations.kustomize.toolkit.fluxcd.io', 'flux-system/fleet-cluster')] + [ + ('kustomizations.kustomize.toolkit.fluxcd.io', n) for n in EXPECTED[cluster]] + [('helmreleases.helm.toolkit.fluxcd.io', n) for n in HELMRELEASES.get(cluster, [])]: + token = request(s, cluster, kind, ref) + if kind == 'helmreleases.helm.toolkit.fluxcd.io': + release_tokens[(cluster, ref)] = token + for cluster in CLUSTERS: + wait_cluster(s, cluster, 600) + release_receipts = [] + for (cluster, ref), token in release_tokens.items(): + namespace, name = ref.split('/') + pending = {'token': token, 'reissued': 0} + + def reconciled_release(): + obj = kget(s, cluster, '-n', namespace, 'get', 'helmreleases.helm.toolkit.fluxcd.io', name) + if lost(obj, pending['token']): + pending['token'] = request(s, cluster, 'helmreleases.helm.toolkit.fluxcd.io', ref) + pending['reissued'] += 1 + return None + return obj if ready(obj) and acknowledged(obj, pending['token']) else None + obj = wait_for(reconciled_release, 600, 'post-restart HelmRelease reconcile') + release_receipts.append({'cluster': cluster, 'release': ref, 'requestedAt': pending['token'], 'lastHandledReconcileAt': obj['status']['lastHandledReconcileAt'], + 'lostRequestsReissued': pending['reissued']}) + time.sleep(10) + snap_after = {c: snapshot(s, c) for c in CLUSTERS} + changes = [] + for c in CLUSTERS: + for n, h in snap_before[c]['helmReleases'].items(): + if [x['version'] for x in h['history']] != [x['version'] for x in snap_after[c]['helmReleases'][n]['history']]: + changes.append('%s %s Helm release revision changed' % (c, n)) + for n, k in snap_before[c]['kustomizations'].items(): + if k['inventory'] != snap_after[c]['kustomizations'][n]['inventory']: + changes.append('%s %s inventory changed' % (c, n)) + if set(pods_before[c]) & set(pod_uids(c)) or len(pod_uids(c)) != len(pods_before[c]): + changes.append('%s controller Pods were not all replaced' % c) + if changes: + die('controller restart changed managed state: ' + '; '.join(changes)) + after = site_facts(s) + same_facts(before, after, 'Flux controller restart') + write(s / 'evidence' / 'flux-restart.json', {'observedAt': now(), 'restartedControllers': {c: sorted(snap_after[c]['controllers']) for c in CLUSTERS}, + 'controllerPodsBefore': pods_before, 'controllerPodsAfter': {c: pod_uids(c) for c in CLUSTERS}, + 'helmReleaseVersions': {c: {n: [x['version'] for x in h['history']] for n, h in snap_after[c]['helmReleases'].items()} for c in CLUSTERS}, + 'inventoriesUnchanged': True, 'helmReconcileReceipts': release_receipts, 'siteFacts': after}) + print('flux-restart: every Flux controller on 3 clusters restarted and re-reconciled; no Helm upgrade, inventory change, new Job, journal or custody change') + return 0 + + +def fail_closed(args): + """A bad dependency revision blocks dependents; nothing running is disturbed.""" + s = pathlib.Path(args.state) + before = site_facts(s) + kro_before = kget(s, 'cell', '-n', 'kro-system', 'get', 'deployment', 'kro') + site_before = kget(s, 'cell', '-n', SITE, 'get', DISPATCHER[0], DISPATCHER[1]) + shared_before = shared_uids(s) + services_before = {d: kget(s, 'cell', '-n', SITE, 'get', 'deployment', d)['metadata']['generation'] for d in SITE_DEPLOYMENTS} + good = current(s) + bad = argparse.Namespace(state=str(s), root=args.root, revision=good['revision'] + 1, site='dispatch', bad_kro_chart=True, drop_site_volume=False, + purpose='fail-closed: kro chart pinned to an absent digest', cluster=[], timeout=0) + stage(bad) + push(bad) + rev = current(s)['fluxRevision'] + request(s, 'cell', 'ocirepositories.source.toolkit.fluxcd.io', 'flux-system/fleet-gitops') + + def blocked(): + ks = kustomizations(s, 'cell') + kro, site = ks['flux-system/kro'], ks['flux-system/fleet-site-dispatch'] + oci = kget(s, 'cell', '-n', 'flux-system', 'get', 'ocirepositories.source.toolkit.fluxcd.io', 'kro-chart') + kro_failed = conditions(kro).get('Ready', {}).get('status') == 'False' and kro['status'].get('lastAttemptedRevision') == rev + dep = conditions(site).get('Ready', {}).get('reason') == 'DependencyNotReady' + # Shared site infrastructure does not depend on kro: it applies the new revision. + shared_applied = all(ready(ks[n]) and ks[n]['status'].get('lastAppliedRevision') == rev for n in ('flux-system/fleet-site-base', 'flux-system/fleet-site-services')) + return (kro, site, oci) if kro_failed and dep and shared_applied and conditions(oci).get('Ready', {}).get('status') == 'False' else None + for n in ('flux-system/fleet-site-base', 'flux-system/fleet-site-services', 'flux-system/fleet-site-graph', 'flux-system/fleet-site-dispatch'): + request(s, 'cell', 'kustomizations.kustomize.toolkit.fluxcd.io', n) + kro, site, oci = wait_for(blocked, 600, 'kro failure blocking only the dispatcher layers', interval=5) + graph = kustomizations(s, 'cell')['flux-system/fleet-site-graph'] + site_obj = kget(s, 'cell', '-n', SITE, 'get', DISPATCHER[0], DISPATCHER[1]) + marker = site_obj['metadata'].get('annotations', {}).get('fleet.datumapis.com/source-marker') + if marker != site_before['metadata'].get('annotations', {}).get('fleet.datumapis.com/source-marker') or site.get('status', {}).get('lastAppliedRevision') == rev: + die('the dependent dispatcher revision applied while kro was not Ready') + services_during = {d: kget(s, 'cell', '-n', SITE, 'get', 'deployment', d)['metadata']['generation'] for d in services_before} + if shared_uids(s) != shared_before or services_during != services_before: + die('the failed kro revision disturbed shared site services: %s -> %s' % (services_before, services_during)) + kro_now = kget(s, 'cell', '-n', 'kro-system', 'get', 'deployment', 'kro') + if kro_now['metadata']['uid'] != kro_before['metadata']['uid'] or kro_now['status'].get('availableReplicas') != 1: + die('the running kro controller was disturbed by the failed revision') + during = site_facts(s) + same_facts(before, during, 'failed dependency revision') + blocked_record = {'revision': rev, 'kroKustomization': sorted([c['type'], c['status'], c.get('reason', '')] for c in kro['status']['conditions']), + 'kroChartSource': sorted([c['type'], c['status'], c.get('reason', '')] for c in oci['status']['conditions']), + 'graphReady': conditions(graph).get('Ready', {}).get('reason'), 'siteReady': conditions(site).get('Ready', {}).get('reason'), + 'siteLastAppliedRevision': site['status'].get('lastAppliedRevision'), 'siteMarkerUnchanged': marker, + 'kroDeploymentUnchanged': True, 'siteFactsUnchanged': True, 'sharedLayersAppliedBadRevision': True, + 'sharedServiceGenerationsUnchanged': services_during, 'sharedObjectUIDsUnchanged': True} + fixed = argparse.Namespace(state=str(s), root=args.root, revision=good['revision'] + 2, site='dispatch', bad_kro_chart=False, drop_site_volume=False, + purpose='fail-closed recovery: pinned kro chart restored', cluster=['cell'], timeout=600) + publish(fixed) + site_obj = kget(s, 'cell', '-n', SITE, 'get', DISPATCHER[0], DISPATCHER[1]) + if site_obj['metadata'].get('annotations', {}).get('fleet.datumapis.com/source-marker') != 'r%d' % fixed.revision: + die('recovered revision did not reach the dispatcher') + after = site_facts(s) + same_facts(before, after, 'fail-closed recovery') + write(s / 'evidence' / 'flux-fail-closed.json', {'observedAt': now(), 'blocked': blocked_record, 'recoveredRevision': current(s), 'siteFacts': after, + 'missingDigest': MISSING_DIGEST}) + print('flux-fail-closed: absent kro chart digest left kro not Ready; graph and dispatcher reported DependencyNotReady and were not applied; shared site layers applied it with services untouched; running kro and site untouched; restored revision converged') + return 0 + + +def retention(args): + """Removing the journal volume from the source must not delete or replace it.""" + s = pathlib.Path(args.state) + before = site_facts(s) + base = current(s)['revision'] + drop = argparse.Namespace(state=str(s), root=args.root, revision=base + 1, site='dispatch', bad_kro_chart=False, drop_site_volume=True, + purpose='retention: site volume claim removed from the source', cluster=['cell'], timeout=600) + publish(drop) + inv = kustomizations(s, 'cell')['flux-system/fleet-site-base'] + if any('PersistentVolumeClaim' in e for e in inventory(inv)): + die('volume claim still in the Flux inventory after its removal from the source') + pvc = kget(s, 'cell', '-n', 'fleet-site', 'get', 'pvc', 'fleet-site-state') + if pvc['metadata'].get('deletionTimestamp'): + die('Flux garbage-collected the journal volume claim') + removed = site_facts(s) + same_facts(before, removed, 'source removal of the volume claim') + restore = argparse.Namespace(state=str(s), root=args.root, revision=base + 2, site='dispatch', bad_kro_chart=False, drop_site_volume=False, + purpose='retention: site volume claim restored to the source (create-once policy)', cluster=['cell'], timeout=600) + publish(restore) + inv = kustomizations(s, 'cell')['flux-system/fleet-site-base'] + if not any(e == 'fleet-site_fleet-site-state__PersistentVolumeClaim' for e in inventory(inv)): + die('restored claim not back in the Flux inventory') + after = site_facts(s) + same_facts(before, after, 'restoring the volume claim to the source') + write(s / 'evidence' / 'flux-retention.json', {'observedAt': now(), 'removedAt': drop.revision, 'restoredAt': restore.revision, + 'pvcUID': after['pvcUID'], 'pvUID': after['pvUID'], 'reclaimPolicy': after['reclaimPolicy'], + 'inventoryWithoutClaim': True, 'claimNotDeleted': True, 'siteFacts': after}) + print('flux-retention: removing the volume claim from the source left it, its PV, journal and custody unchanged; restoring it re-adopted the same claim') + return 0 + + +def main(): + p = argparse.ArgumentParser() + sub = p.add_subparsers(dest='cmd', required=True) + + def add(name, *extra): + s = sub.add_parser(name) + s.add_argument('state') + s.add_argument('--root', default='.') + for e in extra: + e(s) + return s + + def staging(s): + s.add_argument('--revision', type=int, required=True) + s.add_argument('--site', choices=('absent', 'off', 'dispatch'), default='absent') + s.add_argument('--bad-kro-chart', action='store_true') + s.add_argument('--drop-site-volume', action='store_true') + s.add_argument('--purpose', default='') + + def clusters(s): + s.add_argument('--cluster', action='append', default=[], choices=CLUSTERS) + s.add_argument('--timeout', type=int, default=900) + add('tools') + add('stage', staging) + add('push', staging) + add('publish', staging, clusters) + add('bootstrap', lambda s: s.add_argument('--cluster', required=True, choices=CLUSTERS)) + add('wait', clusters, lambda s: s.add_argument('--except', dest='skip', action='append', default=[]), + lambda s: s.add_argument('--observe', action='append', default=[], choices=CLUSTERS)) + add('record', clusters, lambda s: s.add_argument('--name', required=True)) + for name in ('verify', 'drift', 'restart', 'fail-closed', 'retention', 'graph-lifecycle'): + add(name) + add('ownership', lambda s: s.add_argument('--name', required=True)) + a = p.parse_args() + return {'tools': tools, 'stage': stage, 'push': push, 'publish': publish, 'bootstrap': bootstrap, 'wait': wait_cmd, 'record': record, + 'verify': verify, 'drift': drift, 'restart': restart, 'fail-closed': fail_closed, 'retention': retention, + 'graph-lifecycle': graph_lifecycle, 'ownership': ownership_cmd}[a.cmd](a) + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/hack/multiplane/harness.py b/hack/multiplane/harness.py new file mode 100755 index 00000000..9127cd17 --- /dev/null +++ b/hack/multiplane/harness.py @@ -0,0 +1,424 @@ +#!/usr/bin/env python3 +"""Shared local acceptance helpers: preflight, bounded phases, sanitized results. + +Exit codes are part of the harness contract (see docs/operations/multiplane.md): +0 passed, 1 failed, 2 preflight failed, 3 blocked by implementation readiness, +4 bounded wait expired, 64 usage. Nothing here deletes resources. +""" +import argparse +import datetime +import hashlib +import json +import os +import pathlib +import re +import shutil +import signal +import subprocess +import sys +import time + +PROFILE = os.environ.get('FLEET_MULTIPLANE_PROFILE', 'fleet-acceptance-tcg') +CONTEXT = 'colima-' + PROFILE +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'} +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', + 'asset', 'image', 'boot-service', 'boot-denials', 'site-worker', 'site-observer')) + ('multiplane.ErrLocationNotServed',) +READINESS_PACKAGES = ('./internal/coordination', './internal/multiplane', './internal/localvm', './cmd/fleet-multiplane') + + +def now(): + return datetime.datetime.now(datetime.timezone.utc).isoformat() + + +def env(): + e = dict(os.environ) + e['DOCKER_CONTEXT'] = CONTEXT + return e + + +def capture(args, timeout=60, **kw): + """Bounded command; returns (code, stdout, stderr). Missing tools return 127.""" + try: + r = subprocess.run(args, text=True, capture_output=True, timeout=timeout, env=kw.pop('env', env()), **kw) + return r.returncode, r.stdout, r.stderr + except FileNotFoundError: + return 127, '', args[0] + ' not found' + except subprocess.TimeoutExpired: + return 124, '', 'timed out after %ss' % timeout + + +def evidence_dir(state): + d = pathlib.Path(state) / 'evidence' + d.mkdir(mode=0o700, parents=True, exist_ok=True) + return d + + +def write_json(path, value): + path = pathlib.Path(path) + tmp = path.with_suffix(path.suffix + '.tmp') + tmp.write_text(json.dumps(value, indent=2, sort_keys=True) + '\n') + tmp.chmod(0o600) + tmp.replace(path) + + +# ---------------------------------------------------------------- preflight + +def preflight(args): + checks = [] + + def check(name, ok, detail='', kind='preflight'): + checks.append({'name': name, 'ok': bool(ok), 'detail': detail, 'kind': kind}) + return ok + + for tool in ('go', 'python3', 'openssl', 'docker', 'kind', 'kubectl', 'kustomize', 'curl', 'git'): + check('tool:' + tool, shutil.which(tool), 'required on PATH') + check('python>=3.12', sys.version_info >= (3, 12), sys.version.split()[0] + ' (evidence extraction uses the tarfile data filter)') + + code, out, _ = capture(['docker', 'context', 'inspect', CONTEXT, '--format', '{{.Endpoints.docker.Host}}'], 20) + endpoint_ok = code == 0 and out.strip().endswith('/.colima/%s/docker.sock' % PROFILE) + if not endpoint_ok and args.bootstrap and shutil.which('colima'): + # Only start an existing task-owned profile with its saved configuration. + code, out, err = capture(['colima', 'list', '--json'], 30, cwd='/') + known = any(json.loads(line).get('name') == PROFILE for line in out.splitlines() if line.strip().startswith('{')) if code == 0 else False + if known: + code, _, err = capture(['colima', 'start', '--profile', PROFILE], 600, cwd='/') + check('bootstrap:colima-start', code == 0, 'started existing profile ' + PROFILE if code == 0 else err.strip()[-300:]) + code, out, _ = capture(['docker', 'context', 'inspect', CONTEXT, '--format', '{{.Endpoints.docker.Host}}'], 20) + endpoint_ok = code == 0 and out.strip().endswith('/.colima/%s/docker.sock' % PROFILE) + check('docker-context', endpoint_ok, CONTEXT + ' must point at the task-owned Colima profile socket; never fleet-e2e-x86') + + info = {} + if endpoint_ok: + code, out, err = capture(['docker', 'info', '--format', '{{json .}}'], 30) + if check('docker-reachable', code == 0, 'start the profile: colima start --profile %s (or run with --bootstrap)' % PROFILE if code else 'reachable'): + info = json.loads(out) + if info: + check('runtime-architecture', info.get('Architecture') in ('aarch64', 'arm64'), '%s (the Milo image pin is native arm64)' % info.get('Architecture')) + check('runtime-memory', int(info.get('MemTotal', 0)) >= 7_800_000_000, '%.2f GiB; 8 GiB required' % (int(info.get('MemTotal', 0)) / 2**30)) + check('runtime-cpus', int(info.get('NCPU', 0)) >= 4, '%s CPUs; 4 required' % info.get('NCPU')) + code, out, _ = capture(['docker', 'ps', '--format', '{{.Names}}'], 30) + active = sorted(n for n in out.split() if re.match(r'^fleet-(local|mp)-', n)) + check('no-concurrent-fleet-runtime', code == 0 and not active, ('running: ' + ', '.join(active[:6])) if active else 'none running; stopped diagnostics are left untouched') + code, out, err = capture(['docker', 'run', '--rm', '--platform', 'linux/amd64', '--entrypoint', 'uname', DEBIAN, '-m'], 300) + check('amd64-emulation', code == 0 and out.strip() == 'x86_64', 'installer image build needs amd64 container execution' + ('' if code == 0 else ': ' + err.strip()[-200:])) + free = vm_free_bytes() + check('runtime-disk', free is not None and free >= 12 * 2**30, ('%.1f GiB free in docker data root; 12 GiB required' % (free / 2**30)) if free is not None else 'unable to read docker data-root free space') + limit = vm_inotify() + opted = os.environ.get('FLEET_MULTIPLANE_INOTIFY') == '1024' + check('inotify-instances', limit is not None and (limit >= 1024 or opted), 'current %s; requires >=1024 or FLEET_MULTIPLANE_INOTIFY=1024 (reversible task-VM adjustment)' % limit) + + root = pathlib.Path(args.root) + main = (root / 'cmd/fleet-multiplane/main.go') + source = main.read_text() if main.exists() else '' + missing = [c for c in REQUIRED_SOURCE_MARKERS if c not in source] + check('implementation:subcommands', not missing, ('missing: ' + ', '.join(missing)) if missing else 'all harness subcommands and denial errors present', 'readiness') + if args.skip_tests: + check('implementation:tests', True, 'skipped by caller', 'readiness') + else: + code, out, err = capture(['go', 'test', '-race', '-count=1', *READINESS_PACKAGES], 900, cwd=str(root), env=dict(os.environ)) + failing = sorted(set(re.findall(r'--- FAIL: (\S+)', out + err))) + check('implementation:tests', code == 0, 'passed' if code == 0 else 'failing: ' + (', '.join(failing[:8]) or (out + err).strip()[-300:]), 'readiness') + + pre = [c for c in checks if c['kind'] == 'preflight' and not c['ok']] + ready = [c for c in checks if c['kind'] == 'readiness' and not c['ok']] + code = EXIT_PREFLIGHT if pre else EXIT_BLOCKED if ready else EXIT_PASSED + write_json(evidence_dir(args.state) / 'preflight.json', {'schemaVersion': 1, 'observedAt': now(), 'profile': PROFILE, 'status': STATUS_BY_EXIT[code], 'checks': checks}) + for c in checks: + print('%-4s %-34s %s' % ('ok' if c['ok'] else 'FAIL', c['name'], c['detail'])) + return code + + +def vm_exec(command, timeout=30): + if not shutil.which('colima'): + return None + code, out, _ = capture(['colima', 'ssh', '--profile', PROFILE, '--', 'sh', '-c', command], timeout, cwd='/') + return out.strip() if code == 0 else None + + +def vm_free_bytes(): + out = vm_exec('df -Pk /var/lib/docker | tail -1') + try: + return int(out.split()[3]) * 1024 + except (AttributeError, IndexError, ValueError): + return None + + +def vm_inotify(): + out = vm_exec('cat /proc/sys/fs/inotify/max_user_instances') + try: + return int(out) + except (TypeError, ValueError): + return None + + +# ---------------------------------------------------------------- phases + +def phase(args): + """Run one bounded phase, keep its full output private, record a sanitized entry.""" + state = pathlib.Path(args.state) + logs = state / 'logs' + logs.mkdir(mode=0o700, exist_ok=True) + log = logs / (args.name + '.log') + started = time.monotonic() + record = {'name': args.name, 'startedAt': now(), 'timeoutSeconds': args.timeout} + print('==> %s (bound %ss)' % (args.name, args.timeout), flush=True) + 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: + 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) + record['durationSeconds'] = round(time.monotonic() - started, 1) + record['finishedAt'] = now() + if 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') + 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) + return EXIT_TIMEOUT if timed_out else (0 if code == 0 else EXIT_BLOCKED if code == EXIT_BLOCKED else EXIT_FAILED) + + +def terminate(p): + for sig, wait in ((signal.SIGTERM, 15), (signal.SIGKILL, 5)): + try: + os.killpg(p.pid, sig) + except ProcessLookupError: + return + try: + p.wait(wait) + # The group may still contain children after its leader exits. + try: + os.killpg(p.pid, signal.SIGKILL) + except ProcessLookupError: + pass + return + except subprocess.TimeoutExpired: + continue + + +# ---------------------------------------------------------------- provider observation + +LIBVIRT_URI = 'qemu:///system?socket=/run/fleet-libvirt/libvirt-sock' + + +def runtime_exec(state, *command, timeout=20): + """Run a read-only command in the site VM runtime Pod through the cell API.""" + kubeconfig = str(pathlib.Path(state) / 'cell-admin.yaml') + return capture(['kubectl', '--kubeconfig', kubeconfig, '--request-timeout=15s', '-n', 'fleet-site', 'exec', + 'deploy/fleet-site-runtime', '-c', 'libvirt', '--', *command], timeout) + + +def journal(state): + code, out, err = runtime_exec(state, 'cat', '/var/lib/fleet-local/journal.json') + if code != 0: + return None + return json.loads(out) + + +def domains(state): + # Running domains only. + code, out, _ = runtime_exec(state, 'virsh', '--connect', LIBVIRT_URI, 'list', '--name') + return out.split() if code == 0 else None + + +def domain_name(operation_id): + return 'fleet-local-' + hashlib.sha256(operation_id.encode()).hexdigest()[:24] + + +def sanitized_operations(j): + """Only non-secret fields: no fence, boot capability or receipt.""" + ops = [] + for r in (j or {}).get('operations', {}).values(): + ops.append({'id': r['request']['id'], 'kind': r['request']['kind'], 'epoch': r['request']['epoch'], + 'stage': r.get('stage'), 'phase': r.get('result', {}).get('phase'), 'bootClosed': r.get('bootClosed', False), + 'domain': domain_name(r['request']['id'])}) + return ops + + +def wait_stage(args): + """Wait until exactly one install is in args.stage with its domain running.""" + deadline = time.monotonic() + args.timeout + last = None + while time.monotonic() < deadline: + ops = sanitized_operations(journal(args.state)) + installs = [o for o in ops if o['kind'] == 'install'] + running = domains(args.state) or [] + last = {'installs': installs, 'runningDomains': len(running)} + if len(installs) > 1: + print(json.dumps({'error': 'more than one install operation', **last})) + return EXIT_FAILED + if installs and installs[0]['stage'] in ('installer-verified', 'disk-armed', 'disk-requested', 'disk-started', 'disk-verified', 'done'): + print(json.dumps({'error': 'installer completed before the interrupt window', **last})) + return EXIT_FAILED + if installs and installs[0]['stage'] == args.stage and installs[0]['domain'] in running: + print(json.dumps({'observedAt': now(), 'operation': installs[0], 'domainRunning': True})) + return 0 + time.sleep(args.interval) + print(json.dumps({'error': 'stage not observed before deadline', **(last or {})})) + return EXIT_TIMEOUT + + +def journal_cmd(args): + print(json.dumps(sanitized_operations(journal(args.state)), sort_keys=True)) + return 0 + + +# ---------------------------------------------------------------- secrets and result + +TOKEN = re.compile(r'''["']?\b(?:token|client-key-data)["']?\s*:\s*["']?([A-Za-z0-9+/=._-]{16,})''') + + +def secrets(state): + state = pathlib.Path(state) + found = set() + for p in state.rglob('*'): + if not p.is_file() or 'evidence' in p.relative_to(state).parts or p.stat().st_size > 4 << 20: + continue + try: + text = p.read_text(errors='ignore') + except OSError: + continue + if p.suffix == '.token': + found.add(text.strip()) + if p.name == 'tokens.csv': + found.update(line.split(',')[0] for line in text.splitlines() if line.count(',') >= 2) + for m in TOKEN.finditer(text): + found.add(m.group(1)) + if p.name == 'journal.json': + try: + j = json.loads(text) + except ValueError: + continue + if j.get('fence'): + found.add(j['fence']) + for r in j.get('operations', {}).values(): + for value in (r.get('bootToken'), r.get('request', {}).get('fenceToken')): + if value: + found.add(value) + for m in re.finditer(r'-----BEGIN [A-Z ]*PRIVATE KEY-----[^-]+', text): + found.add(m.group(0)[40:100]) + return {s for s in found if s and len(s) >= 16} + + +def scan(args): + values = secrets(args.state) | set(args.extra or []) + leaked = [] + for p in evidence_dir(args.state).rglob('*'): + if p.is_file(): + data = p.read_bytes() + if any(v.encode() in data for v in values): + leaked.append(p.name) + if leaked: + for name in leaked: + (evidence_dir(args.state) / name).write_text('{"redacted":"secret scan matched; see private state"}\n') + print('secret scan matched and redacted: ' + ', '.join(sorted(leaked)), file=sys.stderr) + return EXIT_FAILED + print('secret scan: %d evidence files clean against %d retained secrets' % (sum(1 for p in evidence_dir(args.state).rglob('*') if p.is_file()), len(values))) + return 0 + + +def result(args): + state = pathlib.Path(args.state) + ev = evidence_dir(state) + phases = [] + if (ev / 'phases.jsonl').exists(): + phases = [json.loads(l) for l in (ev / 'phases.jsonl').read_text().splitlines() if l.strip()] + prefix = (state / 'prefix').read_text().strip() if (state / 'prefix').exists() else None + retained = [] + 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()] + failed = next((p for p in phases if p['status'] != 'passed'), None) + status = STATUS_BY_EXIT.get(args.exit_code, 'failed') + summary = ev / 'summary.json' + value = {'schemaVersion': 1, 'observedAt': now(), 'status': status, 'exitCode': args.exit_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 + + +def main(): + p = argparse.ArgumentParser() + sub = p.add_subparsers(dest='cmd', required=True) + s = sub.add_parser('preflight') + s.add_argument('--state', required=True) + s.add_argument('--root', default='.') + s.add_argument('--bootstrap', action='store_true') + s.add_argument('--skip-tests', action='store_true') + s = sub.add_parser('phase') + s.add_argument('--state', required=True) + s.add_argument('--name', required=True) + s.add_argument('--timeout', type=int, required=True) + s.add_argument('--echo', action='store_true') + s.add_argument('command', nargs=argparse.REMAINDER) + s = sub.add_parser('wait-stage') + s.add_argument('--state', required=True) + s.add_argument('--stage', required=True) + s.add_argument('--timeout', type=int, default=900) + s.add_argument('--interval', type=float, default=1.0) + s = sub.add_parser('journal') + s.add_argument('--state', required=True) + s = sub.add_parser('scan') + s.add_argument('--state', required=True) + s.add_argument('--extra', nargs='*') + s = sub.add_parser('result') + s.add_argument('--state', required=True) + s.add_argument('--exit-code', type=int, required=True) + a = p.parse_args() + if a.cmd == 'phase': + if a.command[:1] == ['--']: + a.command = a.command[1:] + if not a.command or not re.match(r'^[a-z0-9-]+$', a.name): + return EXIT_USAGE + return {'preflight': preflight, 'phase': phase, 'wait-stage': wait_stage, 'journal': journal_cmd, + 'scan': scan, 'result': result}[a.cmd](a) + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/hack/multiplane/k8s_evidence.py b/hack/multiplane/k8s_evidence.py new file mode 100644 index 00000000..17f7daef --- /dev/null +++ b/hack/multiplane/k8s_evidence.py @@ -0,0 +1,291 @@ +#!/usr/bin/env python3 +"""Kubernetes site observation, fault injection and sanitized execution records. + +Every call goes through the selected cell's API with its bootstrap kubeconfig. +Records keep names, UIDs, phases, exit codes and conditions only: never handoff +specs, journal records, fences, boot capabilities or tokens. +""" +import datetime +import hashlib +import json +import pathlib +import subprocess +import sys + +NS, SITE = 'fleet-coordination', 'fleet-site' +LIBVIRT = 'qemu:///system?socket=/run/fleet-libvirt/libvirt-sock' + + +def now(): + return datetime.datetime.now(datetime.timezone.utc).isoformat() + + +def kubectl(state, *args, input=None, check=True, config='cell-admin.yaml'): + r = subprocess.run(['kubectl', '--kubeconfig', str(pathlib.Path(state) / config), '--request-timeout=20s', *args], + input=input, text=True, capture_output=True) + if check and r.returncode: + raise SystemExit('kubectl %s failed: %s' % (' '.join(args[:4]), r.stderr.strip()[:300])) + return r + + +def get(state, *args, config='cell-admin.yaml'): + return json.loads(kubectl(state, *args, '-o', 'json', config=config).stdout) + + +def job(state, name): + j = get(state, '-n', SITE, 'get', 'job', 'w-' + name) + st = j.get('status', {}) + return {'job': j['metadata']['name'], 'uid': j['metadata']['uid'], 'active': st.get('active', 0), 'failed': st.get('failed', 0), + 'succeeded': st.get('succeeded', 0), 'conditions': sorted([c['type'], c['status'], c.get('reason', '')] for c in st.get('conditions', [])), + 'backoffLimit': j['spec'].get('backoffLimit'), 'podReplacementPolicy': j['spec'].get('podReplacementPolicy'), + 'serviceAccount': j['spec']['template']['spec'].get('serviceAccountName'), + 'kroNodeID': j['metadata'].get('labels', {}).get('kro.run/node-id')} + + +def pods(state, name): + out = [] + for p in get(state, '-n', SITE, 'get', 'pods', '-l', 'fleet.datumapis.com/handoff=' + name)['items']: + exit_code = next((c['state']['terminated']['exitCode'] for c in p['status'].get('containerStatuses', []) if 'terminated' in c.get('state', {})), None) + out.append({'pod': p['metadata']['name'], 'uid': p['metadata']['uid'], 'phase': p['status'].get('phase'), 'exitCode': exit_code, + 'deleting': bool(p['metadata'].get('deletionTimestamp')), 'jobUID': p['metadata'].get('labels', {}).get('batch.kubernetes.io/controller-uid'), + 'node': p['spec'].get('nodeName')}) + return sorted(out, key=lambda p: p['pod']) + + +def running_pod(state, name, phases=('Running',)): + running = [p for p in pods(state, name) if p['phase'] in phases and not p['deleting']] + return running[0]['uid'] if len(running) == 1 else '' + + +def runtime(state, *command): + return kubectl(state, '-n', SITE, 'exec', 'deploy/fleet-site-runtime', '-c', 'libvirt', '--', *command).stdout + + +def evidence(state): + return pathlib.Path(state) / 'evidence' + + +def interrupt_record(state): + return json.loads((evidence(state) / 'interrupt.json').read_text()) + + +def write(path, value): + pathlib.Path(path).write_text(json.dumps(value, indent=2, sort_keys=True) + '\n') + + +def installs(path): + return [o for o in json.loads(pathlib.Path(path).read_text()) if o['kind'] == 'install'] + + +def worker_rbac(state, name): + s = pathlib.Path(state) + cfg = json.loads(kubectl(state, 'config', 'view', '--raw', '--minify', '-o', 'json').stdout) + cfg['users'] = [{'name': 'worker', 'user': {'token': (s / 'worker.token').read_text().strip()}}] + cfg['contexts'][0]['context']['user'] = 'worker' + path = s / 'worker-kubeconfig.json' + path.write_text(json.dumps(cfg)) + path.chmod(0o600) + own = kubectl(state, '-n', NS, 'get', 'machineallocationhandoff', name, '-o', 'name', check=False, config='worker-kubeconfig.json') + if own.returncode: + raise SystemExit('worker cannot read its own handoff: ' + own.stderr[:200]) + denied = [] + for args in (('-n', NS, 'get', 'machineallocationhandoff', 'op-other-operation'), ('-n', NS, 'get', 'machineallocationhandoffs'), + ('-n', NS, 'patch', 'machineallocationhandoff', name, '--subresource=status', '--type=merge', '-p', '{"status":{}}'), + ('-n', NS, 'patch', 'machineallocationhandoff', name, '--type=merge', '-p', '{"spec":{"cell":"other"}}'), + ('-n', NS, 'get', 'secrets'), ('-n', SITE, 'create', 'configmap', 'forbidden', '--from-literal=x=y'), ('-n', SITE, 'get', 'jobs')): + r = kubectl(state, *args, check=False, config='worker-kubeconfig.json') + if r.returncode == 0 or 'forbidden' not in r.stderr.lower(): + raise SystemExit('worker credential allowed: ' + ' '.join(args[:4]) + ' ' + r.stderr[:200]) + denied.append(' '.join(args[2:4]) + (' (status)' if '--subresource=status' in args else '')) + role = get(state, '-n', NS, 'get', 'role', 'w-' + name) + write(s / 'k8s-worker-rbac.json', {'observedAt': now(), 'serviceAccount': 'w-' + name, 'roleRules': role['rules'], + 'ownHandoffReadable': True, 'forbidden': denied, 'roleCreatedBy': role['metadata'].get('labels', {}).get('kro.run/node-id')}) + print('worker-rbac: per-operation ServiceAccount reads only its own handoff; list, other names, status, spec, Secrets and site writes forbidden') + + +def record_pod_interrupt(state, before, after): + s = pathlib.Path(state) + seen = json.loads((s / 'interrupt-observed.json').read_text()) + after_ops = installs(s / 'interrupt-after.json') + jb = json.loads((s / 'interrupt-job-before-pod.json').read_text()) + ja = json.loads((s / 'interrupt-job-after-pod.json').read_text()) + if len(after_ops) != 1 or after_ops[0]['id'] != seen['operation']['id'] or after_ops[0]['stage'] == 'done': + raise SystemExit('interrupted operation is not the same unfinished operation') + if jb['uid'] != ja['uid'] or ja['failed'] < 1: + raise SystemExit('Job controller did not account and replace the lost Pod in the same Job: %s' % ja) + write(evidence(state) / 'interrupt.json', { + 'observedAt': now(), 'operationID': seen['operation']['id'], 'domain': seen['operation']['domain'], + 'stageAtInterrupt': seen['operation']['stage'], 'domainRunningAtInterrupt': seen['domainRunning'], + 'podInterruption': {'method': 'worker Pod force-deleted with grace period 0', 'deletedPodUID': before, 'replacementPodUID': after, + 'jobUID': jb['uid'], 'jobFailedPodsBefore': jb['failed'], 'jobFailedPodsAfter': ja['failed'], 'replacedBy': 'Job controller'}, + 'localObservationAtInterrupt': None, 'stageAfterInterrupt': after_ops[0]['stage'], 'resultPhaseAfterInterrupt': after_ops[0]['phase']}) + + +def record_job_interrupt(state, old, new, pod_before, pod_after): + s = pathlib.Path(state) + i = interrupt_record(state) + before, after = installs(s / 'interrupt-job-before.json'), installs(s / 'interrupt-job-after.json') + if len(before) != 1 or before[0]['stage'] == 'done': + raise SystemExit('install finished before the Job could be deleted mid-operation') + if len(after) != 1 or after[0]['id'] != i['operationID']: + raise SystemExit('Job recreation created another install operation') + i['jobRecreation'] = {'deletedJobUID': old, 'recreatedJobUID': new, 'recreatedBy': 'kro collection reconciliation', + 'podBeforeUID': pod_before, 'podAfterUID': pod_after, 'stageAtDeletion': before[0]['stage'], 'stageAfterRecreation': after[0]['stage']} + write(evidence(state) / 'interrupt.json', i) + + +def record_resume(state, name): + s = pathlib.Path(state) + i = interrupt_record(state) + done = installs(s / 'resume-after.json') + if len(done) != 1 or done[0]['id'] != i['operationID'] or done[0]['stage'] != 'done' or done[0]['phase'] != 'Succeeded': + raise SystemExit('replacement workers did not complete the exact interrupted operation') + j, ps = job(state, name), pods(state, name) + if j['uid'] != i['jobRecreation']['recreatedJobUID'] or ['Complete', 'True', 'CompletionsReached'] not in j['conditions']: + raise SystemExit('recreated Job did not complete: %s' % j) + if [p['exitCode'] for p in ps if p['phase'] == 'Succeeded'] != [0]: + raise SystemExit('expected exactly one succeeded worker Pod in the recreated Job: %s' % ps) + i.update(resumedStage=done[0]['stage'], resumedPhase=done[0]['phase'], installOperations=len(done), completedJob=j, completedJobPods=ps) + write(evidence(state) / 'interrupt.json', i) + + +def qemu_starts(state, operation): + domain = 'fleet-local-' + hashlib.sha256(operation.encode()).hexdigest()[:24] + r = kubectl(state, '-n', SITE, 'exec', 'deploy/fleet-site-runtime', '-c', 'libvirt', '--', 'cat', '/var/log/libvirt/qemu/' + domain + '.log', check=False) + return r.stdout.count(': starting up ') if r.returncode == 0 else None + + +def lifecycle_snapshot(state, name): + s = pathlib.Path(state) + op = interrupt_record(state)['operationID'] + pvc = get(state, '-n', SITE, 'get', 'pvc', 'fleet-site-state') + pv = get(state, 'get', 'pv', pvc['spec']['volumeName']) + machine = get(state, '-n', 'default', 'get', 'machine', 'allocation', config='consumer-a/management-project.json') + conds = {c['type']: c['status'] for c in machine.get('status', {}).get('conditions', [])} + site_pods = {d: [p['metadata']['uid'] for p in get(state, '-n', SITE, 'get', 'pods', '-l', 'app.kubernetes.io/name=' + d)['items']] + for d in ('fleet-site-runtime', 'fleet-site-boot', 'fleet-site-observer')} + print(json.dumps({'observedAt': now(), 'journalSHA256': hashlib.sha256(runtime(state, 'cat', '/var/lib/fleet-local/journal.json').encode()).hexdigest(), + 'qemuStarts': qemu_starts(state, op), 'domains': runtime(state, 'virsh', '--connect', LIBVIRT, 'list', '--name', '--all').split(), + 'pvcUID': pvc['metadata']['uid'], 'pvUID': pv['metadata']['uid'], 'pvReclaimPolicy': pv['spec']['persistentVolumeReclaimPolicy'], + 'machineA': {'phase': machine.get('status', {}).get('phase'), 'bound': conds.get('Bound'), 'ready': conds.get('Ready')}, + 'sitePods': site_pods, 'job': job(state, name)}, sort_keys=True)) + + +def record_lifecycle(state, old, new): + s = pathlib.Path(state) + a, b = json.loads((s / 'lifecycle-before.json').read_text()), json.loads((s / 'lifecycle-after.json').read_text()) + for key in ('journalSHA256', 'qemuStarts', 'pvcUID', 'pvUID', 'pvReclaimPolicy', 'domains', 'machineA'): + if a[key] != b[key]: + raise SystemExit('%s changed across Pod/Job lifecycle: %s -> %s' % (key, a[key], b[key])) + if a['machineA'] != {'phase': 'Ready', 'bound': 'True', 'ready': 'True'} or a['qemuStarts'] != 2 or a['domains'] or a['pvReclaimPolicy'] != 'Retain': + raise SystemExit('unexpected lifecycle baseline: %s' % a) + for d, uids in a['sitePods'].items(): + if set(uids) & set(b['sitePods'][d]) or len(b['sitePods'][d]) != 1: + raise SystemExit(d + ' Pod was not replaced exactly once') + name = (s / 'install-handoff').read_text().strip() + replay = [p for p in pods(state, name) if p['jobUID'] == new] + if [p['exitCode'] for p in replay] != [0]: + raise SystemExit('recreated completed Job did not finish with one verified no-op replay: %s' % replay) + write(evidence(state) / 'lifecycle.json', {'observedAt': now(), 'recreated': ['fleet-site-runtime Pod', 'fleet-site-boot Pod', 'fleet-site-observer Pod', 'completed install Job'], + 'completedJobUIDBefore': old, 'completedJobUIDAfter': new, 'replayPods': replay, + 'unchanged': ['provider journal bytes', 'QEMU starts (2)', 'PVC/PV identity', 'Retain reclaim policy', 'no domains', 'consumer-a Machine Ready/Bound'], + 'journalSHA256': a['journalSHA256'], 'observerRepublished': True, 'before': a, 'after': b}) + + +FAULTS = ('duplicate', 'wrong-cell', 'stale-epoch') + + +def delivery_faults(state, action): + s = pathlib.Path(state) + cell = (s / 'prefix').read_text().strip() + '-cell' + if action == 'create': + handoffs = get(state, '-n', NS, 'get', 'machineallocationhandoffs', '-l', 'coordination.fleet.datumapis.com/cell=' + cell)['items'] + source = [h for h in handoffs if json.loads(h['spec']['requestJSON'])['kind'] == 'install' and json.loads(h['spec']['requestJSON'])['epoch'] == 1] + if len(source) != 1: + raise SystemExit('expected exactly one epoch-1 install handoff to derive faults from') + spec = source[0]['spec'] + request = json.loads(spec['requestJSON']) + objects = {} + # Same retained intent under a second name: name/operation binding fails. + objects['duplicate'] = ('op-fault-duplicate-' + hashlib.sha256(spec['requestJSON'].encode()).hexdigest()[:12], dict(spec)) + # Selected by the cell label, but the intent names another cell. + wrong = dict(request, id=request['id'] + '-fault-wrong-cell') + objects['wrong-cell'] = ('op-' + hashlib.sha256(wrong['id'].encode()).hexdigest()[:40], {'cell': 'remote-elsewhere-cell', 'requestJSON': json.dumps(wrong, separators=(',', ':'))}) + # Well-formed for this cell, but replays the superseded epoch-1 fence. + stale = dict(request, id=request['id'] + '-fault-stale-epoch') + objects['stale-epoch'] = ('op-' + hashlib.sha256(stale['id'].encode()).hexdigest()[:40], {'cell': cell, 'requestJSON': json.dumps(stale, separators=(',', ':'))}) + if request['epoch'] != 1: + raise SystemExit('stale-epoch fault requires the epoch-1 install handoff') + for fault in FAULTS: + name, body = objects[fault] + obj = {'apiVersion': 'coordination.fleet.datumapis.com/v1alpha1', 'kind': 'MachineAllocationHandoff', + 'metadata': {'name': name, 'namespace': NS, 'labels': {'coordination.fleet.datumapis.com/cell': cell, 'fleet.datumapis.com/fault': fault}}, 'spec': body} + kubectl(state, 'create', '-f', '-', input=json.dumps(obj)) + (s / ('fault-%s-job' % fault)).write_text('w-' + name + '\n') + (s / ('fault-%s-handoff' % fault)).write_text(name + '\n') + return + names = {f: (s / ('fault-%s-handoff' % f)).read_text().strip() for f in FAULTS} + if action == 'verify': + record = {'observedAt': now(), 'faults': {}} + for fault, name in names.items(): + j, ps = job(state, name), pods(state, name) + if ['Failed', 'True', 'PodFailurePolicy'] not in j['conditions'] or j['succeeded'] or [p['exitCode'] for p in ps] != [65]: + raise SystemExit('%s fault Job did not fail once by podFailurePolicy exit 65: %s %s' % (fault, j, ps)) + h = get(state, '-n', NS, 'get', 'machineallocationhandoff', name) + if h.get('status'): + raise SystemExit(fault + ' fault handoff gained a status observation') + record['faults'][fault] = {'handoff': name, 'job': j, 'pods': ps, 'status': None} + machine = get(state, '-n', 'default', 'get', 'machine', 'allocation', config='consumer-b/management-project.json') + conds = {c['type']: c['status'] for c in machine.get('status', {}).get('conditions', [])} + if machine.get('status', {}).get('phase') != 'Bound' or conds.get('Bound') != 'True': + raise SystemExit('failed fault Jobs changed consumer-b allocation: %s' % machine.get('status')) + record['providerJournalUnchanged'] = True + record['consumerBStillBound'] = True + write(evidence(state) / 'delivery-faults.json', record) + return + for name in names.values(): + kubectl(state, '-n', NS, 'delete', 'machineallocationhandoff', name, '--wait=true') + for _ in range(120): + left = [n for n in names.values() if kubectl(state, '-n', SITE, 'get', 'job', 'w-' + n, check=False).returncode == 0] + if not left: + break + subprocess.run(['sleep', '1']) + else: + raise SystemExit('kro did not prune fault Jobs: %s' % left) + record = json.loads((evidence(state) / 'delivery-faults.json').read_text()) + record['prunedByKro'] = True + write(evidence(state) / 'delivery-faults.json', record) + + +def main(): + cmd, state, *rest = sys.argv[1:] + if cmd == 'running-pod': + print(running_pod(state, rest[0])) + elif cmd == 'job-pod': + # Any Pod (any phase) created by one exact Job UID. + print(next((p['uid'] for p in pods(state, rest[0]) if p['jobUID'] == rest[1]), '')) + elif cmd == 'live-pod': + # A scheduled or running replacement; used to interrupt as early as possible. + print(running_pod(state, rest[0], ('Pending', 'Running'))) + elif cmd == 'job': + print(json.dumps(job(state, rest[0]), sort_keys=True)) + elif cmd == 'worker-rbac': + worker_rbac(state, rest[0]) + elif cmd == 'record-pod-interrupt': + record_pod_interrupt(state, *rest) + elif cmd == 'record-job-interrupt': + record_job_interrupt(state, *rest) + elif cmd == 'record-resume': + record_resume(state, rest[0]) + elif cmd == 'lifecycle-snapshot': + lifecycle_snapshot(state, rest[0]) + elif cmd == 'record-lifecycle': + record_lifecycle(state, *rest) + elif cmd == 'delivery-faults': + delivery_faults(state, rest[0]) + else: + raise SystemExit('unknown command ' + cmd) + + +if __name__ == '__main__': + main() diff --git a/hack/multiplane/milo.py b/hack/multiplane/milo.py new file mode 100755 index 00000000..0e3dc5e6 --- /dev/null +++ b/hack/multiplane/milo.py @@ -0,0 +1,83 @@ +#!/usr/bin/env python3 +"""Enroll credentials for, then seed, the Flux-managed Milo v0.32.5 project APIs. + +Flux on the platform cluster owns each Milo API's Deployment, etcd StatefulSet, +volume and Service (config/multiplane/milo). This script does only what a +source revision must never hold: + +- credential enrollment: per-API static tokens and a self-signed serving key, + written as the milo-apiserver-private Secret (local credential seam); +- tenant fixture bootstrap through each API: the Project, static-token RBAC + grants and the metal CRDs inside the project. Production uses Milo's own + project provisioning, service catalog and IAM; this is not that machinery. +""" +import argparse, base64, json, os, pathlib, secrets, subprocess, time +p=argparse.ArgumentParser();p.add_argument('state');p.add_argument('prefix');a=p.parse_args() +root=pathlib.Path(a.state).resolve();root.mkdir(mode=0o700,parents=True,exist_ok=True) +if not a.prefix.startswith('fleet-mp-'):raise SystemExit('task-owned fleet-mp- prefix required') +os.environ['DOCKER_CONTEXT']='colima-fleet-acceptance-tcg' +platform=root/'platform-admin.yaml' +ports=json.loads((root/'platform-ports.json').read_text()) +def run(*args,**kw):return subprocess.run(args,check=True,text=True,**kw) +def kubectl(config,*args,**kw):return run('kubectl','--kubeconfig',str(config),'--request-timeout=15s',*args,**kw) +def apply(config,obj):kubectl(config,'apply','-f','-',input=json.dumps(obj),stdout=subprocess.DEVNULL) +def kube(path,server,token,ca): + path.write_text(json.dumps({'apiVersion':'v1','kind':'Config','clusters':[{'name':'local','cluster':{'server':server,'certificate-authority-data':base64.b64encode(ca).decode()}}],'users':[{'name':'role','user':{'token':token}}],'contexts':[{'name':'role','context':{'cluster':'local','user':'role'}}],'current-context':'role'}));path.chmod(0o600) +def wait(fn,seconds,what): + for _ in range(seconds//2): + if fn():return + time.sleep(2) + raise SystemExit(what) +roles=('provider','consumer-a','consumer-b') +# 1. Credential enrollment into the Flux-created namespaces. +for role in roles: + d=root/role;ns='milo-'+role + if not d.exists(): + d.mkdir(mode=0o700) + tokens={r:secrets.token_hex(32) for r in ('bootstrap','management','customer')} + (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) + for f in ('tokens.csv','tls.key','tls.crt'):(d/f).chmod(0o600) + wait(lambda:subprocess.run(['kubectl','--kubeconfig',str(platform),'get','namespace',ns],capture_output=True).returncode==0,300,f'Flux did not create namespace {ns}') + secret=kubectl(platform,'-n',ns,'create','secret','generic','milo-apiserver-private',f'--from-file=tokens.csv={d/"tokens.csv"}',f'--from-file=tls.crt={d/"tls.crt"}',f'--from-file=tls.key={d/"tls.key"}','--dry-run=client','-o','json',capture_output=True).stdout + kubectl(platform,'apply','--server-side','--field-manager=fleet-credential-enrollment','-f','-',input=secret,stdout=subprocess.DEVNULL) + print(role+': credential Secret enrolled (not in the source)',flush=True) +# 2. Flux must report each Milo Kustomization Ready (Deployment and etcd healthy). +for role in roles: + kubectl(platform,'-n','flux-system','annotate','--overwrite','kustomization','milo-'+role,'reconcile.fluxcd.io/requestedAt='+str(time.time()),stdout=subprocess.DEVNULL) +for role in roles: + kubectl(platform,'-n','flux-system','wait','--for=condition=Ready','kustomization/milo-'+role,'--timeout=600s',stdout=subprocess.DEVNULL) +# 3. Tenant fixture bootstrap through each project API. +for role in roles: + d=root/role + tokens={line.split(',')[1]:line.split(',')[0] for line in (d/'tokens.csv').read_text().splitlines()} + server=f'https://127.0.0.1:{ports[role]}';ca=(d/'tls.crt').read_bytes() + kube(d/'bootstrap.json',server,tokens['bootstrap'],ca) + for attempt in range(90): + result=subprocess.run(['kubectl','--kubeconfig',str(d/'bootstrap.json'),'--request-timeout=2s','get','--raw','/readyz'],capture_output=True) + if result.returncode==0: + discovery=subprocess.run(['kubectl','--kubeconfig',str(d/'bootstrap.json'),'get','crd','projects.resourcemanager.miloapis.com'],capture_output=True) + if discovery.returncode==0:break + time.sleep(2) + else:raise SystemExit(f'{role} Milo API did not become ready. Inspect namespace milo-{role} on the platform cluster; private state: {d}') + kubectl(d/'bootstrap.json','wait','--for=condition=Established','crd/projects.resourcemanager.miloapis.com','--timeout=90s',stdout=subprocess.DEVNULL) + apply(d/'bootstrap.json',{'apiVersion':'resourcemanager.miloapis.com/v1alpha1','kind':'Project','metadata':{'name':role},'spec':{'ownerRef':{'kind':'Organization','name':'local-fixture'}}}) + route=server+'/apis/resourcemanager.miloapis.com/v1alpha1/projects/'+role+'/control-plane' + for who in tokens:kube(d/(who+'-project.json'),route,tokens[who],ca) + kube(d/'management-root.json',server,tokens['management'],ca) + apply(d/'bootstrap.json',{'apiVersion':'rbac.authorization.k8s.io/v1','kind':'ClusterRole','metadata':{'name':'fleet-project-reader'},'rules':[{'apiGroups':['resourcemanager.miloapis.com'],'resources':['projects'],'verbs':['get']}]}) + apply(d/'bootstrap.json',{'apiVersion':'rbac.authorization.k8s.io/v1','kind':'ClusterRoleBinding','metadata':{'name':'fleet-project-reader'},'roleRef':{'apiGroup':'rbac.authorization.k8s.io','kind':'ClusterRole','name':'fleet-project-reader'},'subjects':[{'kind':'User','name':'management'}]}) + config=d/'bootstrap-project.json' + kubectl(config,'apply','-f','config/base/crd/metal.datumapis.com.yaml',stdout=subprocess.DEVNULL) + kubectl(config,'wait','--for=condition=Established','crd','--all','--timeout=90s',stdout=subprocess.DEVNULL) + ns='fleet-provider' if role=='provider' else 'default' + apply(config,{'apiVersion':'v1','kind':'Namespace','metadata':{'name':ns}}) + rules=[{'apiGroups':[''],'resources':['namespaces'],'verbs':['get']},{'apiGroups':['metal.datumapis.com'],'resources':['machineclasses','machineprofiles','machinecapacities','machines','installations'],'verbs':['get','list','watch']}] + if role!='provider':rules += [{'apiGroups':['metal.datumapis.com'],'resources':['machines'],'verbs':['update']},{'apiGroups':['metal.datumapis.com'],'resources':['machines/status','installations/status'],'verbs':['update','patch']}] + apply(d/'bootstrap.json',{'apiVersion':'rbac.authorization.k8s.io/v1','kind':'ClusterRole','metadata':{'name':'fleet-management'},'rules':rules}) + apply(d/'bootstrap.json',{'apiVersion':'rbac.authorization.k8s.io/v1','kind':'ClusterRoleBinding','metadata':{'name':'fleet-management'},'roleRef':{'apiGroup':'rbac.authorization.k8s.io','kind':'ClusterRole','name':'fleet-management'},'subjects':[{'kind':'User','name':'management'}]}) + if role!='provider': + apply(d/'bootstrap.json',{'apiVersion':'v1','kind':'Namespace','metadata':{'name':'default'}}) + apply(d/'bootstrap.json',{'apiVersion':'rbac.authorization.k8s.io/v1','kind':'Role','metadata':{'name':'customer','namespace':'default'},'rules':[{'apiGroups':['metal.datumapis.com'],'resources':['machines','installations'],'verbs':['get','list','watch','create','delete']}]}) + apply(d/'bootstrap.json',{'apiVersion':'rbac.authorization.k8s.io/v1','kind':'RoleBinding','metadata':{'name':'customer','namespace':'default'},'roleRef':{'apiGroup':'rbac.authorization.k8s.io','kind':'Role','name':'customer'},'subjects':[{'kind':'User','name':'customer'}]}) + print(role+': Flux-managed Milo project API ready (static-token RBAC test seam)',flush=True) diff --git a/hack/multiplane/reflection-faults.py b/hack/multiplane/reflection-faults.py new file mode 100755 index 00000000..48873a2f --- /dev/null +++ b/hack/multiplane/reflection-faults.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +"""Explicit test-only hub status fault injection; no simulated federation relay.""" +import copy,json,pathlib,subprocess,sys +s=pathlib.Path(sys.argv[1]);hub=s/'hub-admin.yaml';host=s/'host.yaml' +def k(config,*args,input=None):return subprocess.run(['kubectl','--kubeconfig',str(config),'--request-timeout=20s',*args],input=input,text=True,capture_output=True,check=True).stdout +items=json.loads(k(hub,'-n','fleet-coordination','get','machineallocationhandoffs','-o','json'))['items'] +if len(items)!=1:raise SystemExit('run reflection faults after install and before cleanup') +obj=items[0];original=obj.get('status');name=obj['metadata']['name'] +if len((original or {}).get('reflected',[]))!=1:raise SystemExit('no real reflected result to test') +# Explicit ownership transfer: suspend the Flux HelmRelease before stopping the +# controller, so Flux and the harness are never concurrent writers. +k(host,'-n','flux-system','patch','helmrelease/karmada','--field-manager=fleet-fault-injection','--type=merge','-p','{"spec":{"suspend":true}}') +k(host,'-n','karmada-system','scale','deployment/karmada-controller-manager','--replicas=0') +k(host,'-n','karmada-system','wait','--for=delete','pod','-l','app=karmada-controller-manager','--timeout=90s') +def guard(mode): + subprocess.run([sys.executable,str(pathlib.Path(__file__).with_name('fault_guard.py')),mode,str(s),'host.yaml','helmrelease','karmada','karmada-system','karmada-controller-manager','flux-reflection-suspension'],check=True) +guard('record') +def patch(status): + p=s/'status-fault.json';p.write_text(json.dumps({'status':status}));p.chmod(0o600) + k(hub,'-n','fleet-coordination','patch','machineallocationhandoff',name,'--subresource=status','--type=merge','--patch-file',str(p)) +try: + # Each mode changes exactly one attribute of the real reflected result. + for mode in ('wrong-cell','stale','duplicate','future','wrong-intent','wrong-digest','wrong-operation','incomplete','missing'): + status=copy.deepcopy(original);o=status['reflected'][0]['observation'] + if mode=='wrong-cell':status['reflected'][0]['clusterName']='wrong-cell' + elif mode=='stale':o['observedAt']='2000-01-01T00:00:00Z' + elif mode=='duplicate':status['reflected'].append(copy.deepcopy(status['reflected'][0])) + elif mode=='future':o['observedAt']='2999-01-01T00:00:00Z' + elif mode=='wrong-intent':o['intentDigest']='0'*64 + elif mode=='wrong-digest':o['result']['inputDigest']='0'*64 + elif mode=='wrong-operation':o['result']['id']=o['result']['id']+'-other' + elif mode=='incomplete':o['result']['phase']='Unknown' + else:status={'reflected':[]} + guard('check') + patch(status) + result=subprocess.run([str(s/'fleet-multiplane-host'),'install','--once','--config',str(s/'acceptance.json')],text=True,capture_output=True) + if result.returncode==0:raise SystemExit(mode+' incorrectly accepted') + if 'unknown' not in result.stderr.lower():raise SystemExit(mode+' did not reach result validation: '+result.stderr[:200]) + print(mode+': management rejected reflected evidence') +finally: + guard('check') + patch(original) + k(host,'-n','karmada-system','scale','deployment/karmada-controller-manager','--replicas=1') + k(host,'-n','flux-system','patch','helmrelease/karmada','--field-manager=fleet-fault-injection','--type=merge','-p','{"spec":{"suspend":false}}') + k(host,'-n','karmada-system','wait','--for=condition=Available','deployment/karmada-controller-manager','--timeout=180s') diff --git a/hack/multiplane/roles.py b/hack/multiplane/roles.py new file mode 100755 index 00000000..65141651 --- /dev/null +++ b/hack/multiplane/roles.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python3 +"""Credential enrollment for Flux-created identities; installs nothing. + +Flux owns every ServiceAccount, Role, CRD, namespace, interpreter, member +Cluster and PropagationPolicy referenced here (config/multiplane). This script +only mints the short-lived tokens a source must never hold, writes private +mode-0600 kubeconfigs, and enrolls the cell's push-mode member Secret on the +Karmada API. No cell credential can access hub/project/private APIs. +""" +import base64,json,os,pathlib,subprocess,sys,time +state=pathlib.Path(sys.argv[1]).resolve();prefix=(state/'prefix').read_text().strip() +os.environ['DOCKER_CONTEXT']='colima-fleet-acceptance-tcg' +env=json.loads((state/'gitops-environment.json').read_text()) +def k(config,*args,input=None):return subprocess.run(['kubectl','--kubeconfig',str(config),'--request-timeout=30s',*args],input=input,text=True,capture_output=True,check=True).stdout +def exists(config,*args):return subprocess.run(['kubectl','--kubeconfig',str(config),'--request-timeout=15s','get',*args],capture_output=True).returncode==0 +def wait(config,*args): + for _ in range(150): + if exists(config,*args):return + time.sleep(2) + raise SystemExit('Flux did not create '+' '.join(args)) +def credentials(config,ns,name,dest,internal=None,server=None): + wait(config,'-n',ns,'serviceaccount',name) + token=k(config,'-n',ns,'create','token',name,'--duration=24h').strip() + obj=json.loads(k(config,'config','view','--raw','--minify','-o','json')) + obj['users']=[{'name':name,'user':{'token':token}}];obj['contexts'][0]['context']['user']=name + if server or internal:obj['clusters'][0]['cluster']['server']=server or internal + dest.write_text(json.dumps(obj));dest.chmod(0o600) + return token,base64.b64decode(obj['clusters'][0]['cluster']['certificate-authority-data']) +host=state/'host.yaml';hub=state/'hub-admin.yaml';cell=state/'cell-admin.yaml';ns='fleet-coordination' +# Karmada's admin kubeconfig (chart-generated Secret) rewritten to the host port. +wait(host,'-n','karmada-system','secret','karmada-kubeconfig') +raw=base64.b64decode(json.loads(k(host,'-n','karmada-system','get','secret','karmada-kubeconfig','-o','json'))['data']['kubeconfig']) +hub.write_bytes(raw);hub.chmod(0o600) +entry=k(hub,'config','view','-o','jsonpath={.clusters[0].name}') +k(hub,'config','set-cluster',entry,'--server=https://127.0.0.1:%d'%env['karmadaPort']) +# CA verification is retained; the chart includes localhost in its serving SANs. +credentials(hub,ns,'fleet-management',state/'management-hub.json') +credentials(host,'fleet-system-private','fleet-custodian',state/'private.json') +# Cell execution credentials are Kubernetes ServiceAccounts inside the cell +# site; no cell credential is exported to the host. +token,ca=credentials(cell,ns,'fleet-federation',state/'federation-cell.json',env['cellEndpoint']) +wait(hub,'namespace','karmada-cluster') +secret={'apiVersion':'v1','kind':'Secret','metadata':{'name':env['cell'],'namespace':'karmada-cluster'},'data':{'token':base64.b64encode(token.encode()).decode(),'caBundle':base64.b64encode(ca).decode()}} +k(hub,'apply','--server-side','--field-manager=fleet-credential-enrollment','-f','-',input=json.dumps(secret)) +k(host,'-n','karmada-system','annotate','--overwrite','kustomization','fleet-karmada-members','reconcile.fluxcd.io/requestedAt=%f'%time.time()) +wait(hub,'cluster/'+env['cell']) +k(hub,'wait','--for=condition=Ready','cluster/'+env['cell'],'--timeout=300s') +k(host,'-n','karmada-system','wait','--for=condition=Ready','kustomization/fleet-karmada-members','--timeout=300s') +print('Karmada member enrolled; separate management/custodian/cell credentials minted for Flux-created identities') diff --git a/hack/multiplane/run.sh b/hack/multiplane/run.sh new file mode 100755 index 00000000..3fe58150 --- /dev/null +++ b/hack/multiplane/run.sh @@ -0,0 +1,104 @@ +#!/usr/bin/env bash +# One-command local Milo/Karmada/PXE acceptance. Creates only fresh resources with +# one fleet-mp- prefix. Failures stop (never delete) this run's containers +# 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. +set -euo pipefail +cd "$(dirname "$0")/../.." +umask 077 +usage() { echo 'usage: hack/multiplane/run.sh [--preflight-only] [--bootstrap] [--keep] [--leave-running] [--skip-readiness-tests]' >&2; exit 64; } +preflight_only=0 bootstrap=() keep=0 leave=0 skip_tests=() +for arg in "$@"; do + case "$arg" in + --preflight-only) preflight_only=1 ;; + --bootstrap) bootstrap=(--bootstrap) ;; + --keep) keep=1 ;; + --leave-running) leave=1 ;; + --skip-readiness-tests) skip_tests=(--skip-tests) ;; + *) usage ;; + esac +done +export DOCKER_CONTEXT=colima-fleet-acceptance-tcg KIND_EXPERIMENTAL_PROVIDER=docker +harness=(python3 hack/multiplane/harness.py) +state=$(mktemp -d "${FLEET_MULTIPLANE_STATE_ROOT:-/tmp}/fleet-multiplane.XXXXXX") +mkdir -m 0700 "$state/evidence" +printf 'Private run state: %s\nShareable evidence: %s/evidence\n' "$state" "$state" + +finish() { + code=$1 + trap - EXIT + if [[ $code -ne 0 && -f $state/prefix ]]; then + if [[ $leave == 1 ]]; then + echo "Leaving this run's containers running for diagnosis. Stop only them with: hack/multiplane/stop.sh $state" + else + bash hack/multiplane/stop.sh "$state" || echo "stop.sh failed; inspect $(cat "$state/prefix")-* containers" >&2 + fi + 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" +} +trap 'finish $?' EXIT +ph() { "${harness[@]}" phase --state "$state" --name "$1" --timeout "$2" -- "${@:3}"; } + +"${harness[@]}" preflight --state "$state" --root . "${bootstrap[@]}" "${skip_tests[@]}" +[[ $preflight_only == 0 ]] || exit 0 + +prefix="fleet-mp-$(openssl rand -hex 4)" +printf '%s\n' "$prefix" > "$state/prefix" +# Source identity covers uncommitted files as well as tracked files. +python3 - "$state" <<'PY' +import hashlib,pathlib,sys +paths=[] +for name in ('internal','cmd/fleet-multiplane','hack/multiplane','hack/local-vm','config/multiplane','config/site','config/base/crd'): + paths += [p for p in pathlib.Path(name).rglob('*') if p.is_file() and '__pycache__' not in p.parts and p.suffix not in ('.pyc', '.pyo')] +paths += [pathlib.Path(name) for name in ('go.mod', 'go.sum')] +(pathlib.Path(sys.argv[1])/'source-SHA256SUMS').write_text(''.join(hashlib.sha256(p.read_bytes()).hexdigest()+' '+str(p)+'\n' for p in sorted(paths))) +PY +flux=(python3 hack/multiplane/flux.py) +# The site binary is built into its own directory: it is the only build context +# input besides hack/local-vm, so no private state can enter the image. +ph build 600 sh -c 'mkdir -m 0700 "$1/site-bin" && go build -o "$1/fleet-multiplane-host" ./cmd/fleet-multiplane && CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -o "$1/site-bin/fleet-multiplane" ./cmd/fleet-multiplane && cp "$1/site-bin/fleet-multiplane" "$1/fleet-multiplane"' sh "$state" +ph site-image 2400 docker build --target site --build-context "fleetbin=$state/site-bin" -t "$prefix-site-image" -f hack/local-vm/Containerfile hack/local-vm +ph site-image-verify 120 sh -c ' + sum=$(shasum -a 256 "$2/site-bin/fleet-multiplane" | cut -d" " -f1) + printf "%s /usr/local/bin/fleet-multiplane\n" "$sum" | docker run --rm -i --entrypoint sha256sum "$1-site-image" -c - >/dev/null + docker run --rm -e FLEET_LOCAL_VM_ACCEL=tcg --entrypoint fleet-multiplane "$1-site-image" image > "$2/image" + echo "site image: checksum-verified executable; artifact reference recorded"' sh "$prefix" "$state" +ph flux-tools 300 "${flux[@]}" tools "$state" +docker network inspect kind >/dev/null 2>&1 || docker network create kind >/dev/null +# Disposable infrastructure only: registry and three kind clusters, no services. +ph topology 900 bash hack/multiplane/topology.sh "$state" +ph site-image-push 600 bash hack/multiplane/site.sh push "$state" +# Revision 1: platform services only. The bootstrap boundary applies each +# cluster's Flux components and sync objects once; Flux then owns them too. +ph flux-source 300 "${flux[@]}" publish "$state" --revision 1 --purpose 'platform services' +for c in platform hub cell; do ph "flux-bootstrap-$c" 600 "${flux[@]}" bootstrap "$state" --cluster "$c"; done +# Waiting from the moment of bootstrap records dependency gating as it happens. +# The member registration becomes Ready only after credential enrollment. +ph flux-platform 1800 "${flux[@]}" wait "$state" --cluster cell --cluster hub --observe hub --observe cell --except karmada-system/fleet-karmada-members --timeout 1500 +ph milo-bootstrap 1200 python3 hack/multiplane/milo.py "$state" "$prefix" +ph flux-milo 900 "${flux[@]}" wait "$state" --cluster platform --timeout 600 +ph federation-enrollment 600 python3 hack/multiplane/roles.py "$state" +python3 - "$state" <<'PY' +import json,pathlib,sys +s=pathlib.Path(sys.argv[1]).resolve();c={'State':str(s),'HubKubeconfig':str(s/'management-hub.json'),'PrivateKubeconfig':str(s/'private.json'),'Cell':(s/'prefix').read_text().strip()+'-cell','Image':(s/'image').read_text().strip()};(s/'acceptance.json').write_text(json.dumps(c)) +PY +ph seed 600 "$state/fleet-multiplane-host" seed --config "$state/acceptance.json" +ph scoped-asset 120 sh -c '"$1/fleet-multiplane-host" asset --config "$1/acceptance.json" > "$1/scoped-asset" && echo "scoped asset recorded"' sh "$state" +# Revision 2: the Flux-owned shared site services and the HandoffDispatcher +# instance, dispatch disabled. +ph flux-site 1200 "${flux[@]}" publish "$state" --revision 2 --site off --purpose 'shared site services and dispatcher, dispatch disabled' --cluster cell --cluster hub --cluster platform --timeout 900 +ph site-install 900 bash hack/multiplane/site.sh check "$state" +ph flux-verify 300 "${flux[@]}" verify "$state" +bash hack/multiplane/acceptance.sh "$state" +ph secret-scan 120 "${harness[@]}" scan --state "$state" +if [[ $keep == 1 ]]; then + ph stop 300 bash hack/multiplane/stop.sh "$state" +else + ph teardown 900 bash hack/multiplane/teardown.sh "$state" +fi +printf 'Local topology/PXE acceptance passed. Production authority and physical hardware remain unqualified.\n' diff --git a/hack/multiplane/site.sh b/hack/multiplane/site.sh new file mode 100755 index 00000000..d7c35536 --- /dev/null +++ b/hack/multiplane/site.sh @@ -0,0 +1,58 @@ +#!/usr/bin/env bash +# Site image publication and post-reconcile checks for the selected cell. +# site.sh push STATE push the built site image to the run registry; record its digest +# site.sh check STATE after Flux applied the site layers: shared services Available +# and Flux-owned, dispatcher ready, volume Retain, no Job +# Installs nothing: kro, the site base, the shared services, the RGD and the +# HandoffDispatcher are reconciled by the cell's Flux (config/multiplane/clusters). +set -euo pipefail +umask 077 +step=${1:?step required} +state=${2:?private state directory required} +prefix=$(cat "$state/prefix") +[[ $prefix =~ ^fleet-mp-[a-f0-9]{8}$ ]] || { echo "unexpected prefix" >&2; exit 1; } +export DOCKER_CONTEXT=colima-fleet-acceptance-tcg +cell="$state/cell-admin.yaml" +deployments=(fleet-site-runtime fleet-site-boot fleet-site-observer) +k() { kubectl --kubeconfig "$cell" --request-timeout=30s "$@"; } + +case "$step" in + push) + port=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["registryPort"])' "$state/gitops-environment.json") + docker tag "$prefix-site-image" "127.0.0.1:$port/fleet-site:$prefix" >/dev/null + docker push "127.0.0.1:$port/fleet-site:$prefix" >/dev/null + digest=$(docker image inspect "127.0.0.1:$port/fleet-site:$prefix" --format '{{range .RepoDigests}}{{println .}}{{end}}' | grep "^127.0.0.1:$port/fleet-site@" | cut -d@ -f2) + [[ $digest =~ ^sha256:[a-f0-9]{64}$ ]] || { echo "no registry digest for the site image" >&2; exit 1; } + python3 - "$state" "$prefix" "$digest" <<'PY' +import json, pathlib, sys +s, prefix, digest = pathlib.Path(sys.argv[1]), sys.argv[2], sys.argv[3] +env = json.loads((s / 'gitops-environment.json').read_text()) +env['siteImage'] = '%s-registry:5000/fleet-site@%s' % (prefix, digest) +env['siteImageDigest'] = digest +(s / 'gitops-environment.json').write_text(json.dumps(env, indent=2) + '\n') +PY + printf 'site image: pushed to the run registry as fleet-site@%s; the cell pulls it by digest\n' "$digest" + ;; + check) + for d in "${deployments[@]}"; do + for _ in $(seq 1 120); do k -n fleet-site get deployment "$d" >/dev/null 2>&1 && break; sleep 2; done + k -n fleet-site wait --for=condition=Available "deployment/$d" --timeout=300s >/dev/null + done + k -n fleet-site wait --for=jsonpath='{.status.runtimeAvailable}'=1 handoffdispatcher/dispatcher --timeout=120s >/dev/null + [[ -z $(k -n fleet-site get jobs -o name) ]] || { echo 'worker Jobs exist before dispatch' >&2; exit 1; } + pv=$(k -n fleet-site get pvc fleet-site-state -o jsonpath='{.spec.volumeName}') + policy=$(k get pv "$pv" -o jsonpath='{.spec.persistentVolumeReclaimPolicy}') + [[ $policy == Retain ]] || { echo "site volume reclaim policy $policy" >&2; exit 1; } + want=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["siteImage"])' "$state/gitops-environment.json") + for d in fleet-site-runtime fleet-site-boot fleet-site-observer; do + image=$(k -n fleet-site get deployment "$d" -o jsonpath='{.spec.template.spec.containers[0].image}') + [[ $image == "$want" ]] || { echo "$d runs $image, not the published digest" >&2; exit 1; } + owner=$(k -n fleet-site get deployment "$d" -o jsonpath='{.metadata.labels.kustomize\.toolkit\.fluxcd\.io/name}') + [[ $owner == fleet-site-services ]] || { echo "$d is not owned by the Flux services layer" >&2; exit 1; } + done + [[ $(k -n fleet-site get handoffdispatcher dispatcher -o jsonpath='{.status.workerImage}') == "$want" ]] || { echo 'dispatcher worker image is not the services image' >&2; exit 1; } + [[ $(k -n fleet-site get service fleet-site-boot -o jsonpath='{.spec.clusterIP}') == "$(python3 -c 'import sys; sys.path.insert(0, "hack/multiplane"); import flux; print(flux.BOOT_SERVICE_IP)')" ]] || { echo 'boot Service is not at its fixed ClusterIP' >&2; exit 1; } + printf 'site: Flux-owned runtime, boot service and observer Available from the digest-pinned image; boot Service at its fixed ClusterIP; dispatcher ready; volume Retain; dispatch disabled\n' + ;; + *) echo "unknown step: $step" >&2; exit 64 ;; +esac diff --git a/hack/multiplane/steps.sh b/hack/multiplane/steps.sh new file mode 100755 index 00000000..81ee78ee --- /dev/null +++ b/hack/multiplane/steps.sh @@ -0,0 +1,309 @@ +#!/usr/bin/env bash +# Individual acceptance steps. Each runs inside a bounded harness phase, prints +# only non-secret marker lines on stdout, and exits nonzero on any violation. +# Site execution is observed and disturbed only through the cell Kubernetes API. +set -euo pipefail +umask 077 +step=${1:?step required} +state=${2:?private state directory required} +prefix=$(cat "$state/prefix") +[[ $prefix =~ ^fleet-mp-[a-f0-9]{8}$ ]] || { echo "unexpected prefix" >&2; exit 1; } +export DOCKER_CONTEXT=colima-fleet-acceptance-tcg +harness=(python3 hack/multiplane/harness.py) +host="$state/fleet-multiplane-host" +ns=fleet-coordination +helpers=hack/multiplane/k8s_evidence.py + +k() { kubectl --kubeconfig "$1" --request-timeout=20s "${@:2}"; } +cell() { k "$state/cell-admin.yaml" "$@"; } +platform() { k "$state/platform-admin.yaml" "$@"; } +flux() { python3 hack/multiplane/flux.py "$@"; } +# Explicit, recorded ownership transfer for fault injection: suspend the Flux +# object first so the harness is never a second concurrent writer. +suspend() { platform -n flux-system patch "kustomization/$1" --field-manager=fleet-fault-injection --type=merge -p "{\"spec\":{\"suspend\":$2}}" >/dev/null; } +site() { cell -n fleet-site "$@"; } +runtime() { site exec deploy/fleet-site-runtime -c libvirt -- "$@"; } +py() { python3 "$helpers" "$@"; } +wait_api() { + for _ in $(seq 1 120); do + if k "$1" get --raw /readyz >/dev/null 2>&1; then return; fi + sleep 1 + done + echo "API did not recover: $(basename "$1")" >&2; return 1 +} +local_phase() { cell -n "$ns" get machineallocationhandoffs -o jsonpath='{.items[*].status.observation.result.phase}'; } +# Private custody digest: names, UIDs and resourceVersions only; data never leaves memory. +custody_digest() { + k "$state/host.yaml" -n fleet-system-private get secrets -o json | python3 -c ' +import hashlib,json,sys +items=sorted((i["metadata"]["name"],i["metadata"]["uid"],i["metadata"]["resourceVersion"]) for i in json.load(sys.stdin)["items"]) +print(len(items), hashlib.sha256(json.dumps(items).encode()).hexdigest())' +} +journal_digest() { + runtime cat /var/lib/fleet-local/journal.json | python3 -c ' +import hashlib,sys +print(hashlib.sha256(sys.stdin.buffer.read()).hexdigest())' +} +wait_running_pod() { + for _ in $(seq 1 "${2:-120}"); do + uid=$(py running-pod "$state" "$1") + [[ -z $uid ]] || { printf '%s\n' "$uid"; return; } + sleep 1 + done + echo "no single running worker Pod for $1" >&2; return 1 +} + +case "$step" in + verify-contention) + # Independently read public status: one Bound winner, one Pending loser. + a=$(k "$state/consumer-a/management-project.json" -n default get machine allocation -o jsonpath='{.status.phase}/{.status.conditions[?(@.type=="Bound")].reason}') + 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" + ;; + await-delivery) + for _ in $(seq 1 120); do + names=$(cell -n "$ns" get machineallocationhandoffs -o jsonpath='{.items[*].metadata.name}') + [[ -z $names ]] || break + sleep 1 + done + [[ -n $names ]] || { echo 'Karmada did not deliver retained intent' >&2; exit 1; } + [[ $(wc -w <<<"$names") -eq 1 ]] || { echo 'more than one delivered handoff' >&2; exit 1; } + printf '%s\n' "$names" > "$state/install-handoff" + [[ -z $(local_phase) ]] || { echo 'cell status existed before any worker started' >&2; exit 1; } + site wait --for=jsonpath='{.status.deliveredHandoffs}'=1 handoffdispatcher/dispatcher --timeout=120s >/dev/null + [[ -z $(site get jobs -o name) ]] || { echo 'worker Job exists before dispatch' >&2; exit 1; } + printf 'delivery: Karmada delivered exactly one retained handoff; kro observed it; no worker Job before dispatch\n' + ;; + partition) + # Consumer A's API is Flux-managed: suspend its Kustomization, then stop it. + suspend milo-consumer-a true + platform -n milo-consumer-a scale deployment/milo-apiserver --replicas=0 >/dev/null + platform -n milo-consumer-a wait --for=delete pod -l app.kubernetes.io/name=milo-apiserver --timeout=120s >/dev/null + python3 hack/multiplane/fault_guard.py record "$state" platform-admin.yaml kustomization milo-consumer-a milo-consumer-a milo-apiserver flux-partition + docker pause "$prefix-hub-control-plane" >/dev/null + printf 'partition: consumer-a API stopped (its Flux Kustomization suspended) and hub paused before any worker Job exists\n' + ;; + dispatch) + # Dispatch is a source revision, reconciled by the cell's own Flux from the + # registry while the hub is paused; kro then creates per-operation RBAC and the Job. + flux publish "$state" --revision 3 --site dispatch --purpose 'enable dispatch' --cluster cell --timeout 600 >/dev/null + [[ $(site get handoffdispatcher dispatcher -o jsonpath='{.spec.dispatch}') == true ]] || { echo 'dispatch revision not applied' >&2; exit 1; } + name=$(cat "$state/install-handoff") + for _ in $(seq 1 120); do site get job "w-$name" >/dev/null 2>&1 && break; sleep 1; done + py job "$state" "$name" > "$state/k8s-dispatch-job.json" + printf 'dispatch: cell Flux applied the dispatch revision; kro created the worker Job and per-operation RBAC from the delivered handoff with no hub access\n' + ;; + worker-rbac) + name=$(cat "$state/install-handoff") + site create token "w-$name" --duration=10m > "$state/worker.token" + py worker-rbac "$state" "$name" + rm -f "$state/worker-kubeconfig.json" + ;; + interrupt-pod) + name=$(cat "$state/install-handoff") + "${harness[@]}" wait-stage --state "$state" --stage installer-started --timeout 900 --interval 0.5 > "$state/interrupt-observed.json" + before=$(wait_running_pod "$name" 30) + py job "$state" "$name" > "$state/interrupt-job-before-pod.json" + # Abrupt Pod loss with no grace period. The guest runs under the runtime Pod, + # so the in-flight installer continues; only its worker process is lost. + site delete pod -l "fleet.datumapis.com/handoff=$name" --grace-period=0 --force >/dev/null 2>&1 + [[ -z $(local_phase) ]] || { echo 'local result published for an interrupted operation' >&2; exit 1; } + after= + for _ in $(seq 1 180); do + after=$(py live-pod "$state" "$name") + [[ -z $after || $after == "$before" ]] || break + sleep 1 + done + [[ -n $after && $after != "$before" ]] || { echo 'no replacement worker Pod' >&2; exit 1; } + py job "$state" "$name" > "$state/interrupt-job-after-pod.json" + "${harness[@]}" journal --state "$state" > "$state/interrupt-after.json" + py record-pod-interrupt "$state" "$before" "$after" + printf 'interrupt-pod: worker Pod force-deleted while installer-started with its domain running; Job controller replaced it; no local result\n' + ;; + interrupt-job) + name=$(cat "$state/install-handoff") + old_job=$(site get job "w-$name" -o jsonpath='{.metadata.uid}') + # The whole emulated install takes about a minute: delete the Job as soon as + # its replacement worker exists, while the operation is still unfinished. + py live-pod "$state" "$name" > "$state/interrupt-job-pod-before" + [[ -s $state/interrupt-job-pod-before ]] || { echo 'no live worker Pod to interrupt' >&2; exit 1; } + "${harness[@]}" journal --state "$state" > "$state/interrupt-job-before.json" + site delete job "w-$name" --wait=false >/dev/null + new_job= + for _ in $(seq 1 120); do + new_job=$(site get job "w-$name" -o jsonpath='{.metadata.uid}' 2>/dev/null || true) + [[ -z $new_job || $new_job == "$old_job" ]] || break + sleep 1 + done + [[ -n $new_job && $new_job != "$old_job" ]] || { echo 'kro did not recreate the deleted Job' >&2; exit 1; } + pod= + for _ in $(seq 1 240); do pod=$(py job-pod "$state" "$name" "$new_job"); [[ -z $pod ]] || break; sleep 1; done + [[ -n $pod ]] || { echo 'recreated Job created no worker Pod' >&2; exit 1; } + "${harness[@]}" journal --state "$state" > "$state/interrupt-job-after.json" + py record-job-interrupt "$state" "$old_job" "$new_job" "$(cat "$state/interrupt-job-pod-before")" "$pod" + printf 'interrupt-job: running worker Job deleted mid-install; kro recreated it under a new UID for the same operation\n' + ;; + resume) + name=$(cat "$state/install-handoff") + site wait --for=condition=Complete "job/w-$name" --timeout=20m >/dev/null + cell -n "$ns" wait --for=jsonpath='{.status.observation.result.phase}'=Succeeded machineallocationhandoff "$name" --timeout=5m >/dev/null + "${harness[@]}" journal --state "$state" > "$state/resume-after.json" + py record-resume "$state" "$name" + printf 'resume: replacement worker completed the exact interrupted operation; one install operation; observer published from the journal\n' + ;; + partition-readiness) + # The platform's root sync must apply r3 (pushed during the partition) with + # consumer A still suspended, and the suspension must survive it unchanged. + flux wait "$state" --cluster platform --timeout 300 >/dev/null + rev=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))[-1]["fluxRevision"])' "$state/flux-revisions.json") + python3 hack/multiplane/fault_guard.py check "$state" platform-admin.yaml kustomization milo-consumer-a milo-consumer-a milo-apiserver flux-partition "$rev" + # Resuming hands ownership back: Flux, not the harness, restores replicas. + suspend milo-consumer-a false + platform -n flux-system annotate --overwrite kustomization/milo-consumer-a "reconcile.fluxcd.io/requestedAt=$(date +%s)" >/dev/null + platform -n milo-consumer-a wait --for=jsonpath='{.status.availableReplicas}'=1 deployment/milo-apiserver --timeout=240s >/dev/null + wait_api "$state/consumer-a/bootstrap.json" + ready=$(k "$state/consumer-a/management-project.json" -n default get machine allocation -o jsonpath='{.status.conditions[?(@.type=="Ready")].status}') + [[ $ready == False ]] || { echo 'Public readiness advanced during partition' >&2; exit 1; } + name=$(cat "$state/install-handoff") + [[ $(site get job "w-$name" -o jsonpath='{.status.conditions[?(@.type=="Complete")].status}') == True ]] || { echo 'install Job not Complete' >&2; exit 1; } + printf 'PXE succeeded cell-locally and the worker Job is Complete while hub/consumer disconnected; public Ready stayed False; Flux restored consumer-a\n' + ;; + heal) + docker unpause "$prefix-hub-control-plane" >/dev/null + docker restart --timeout 30 "$prefix-hub-control-plane" >/dev/null + docker restart --timeout 30 "$prefix-cell-control-plane" >/dev/null + wait_api "$state/host.yaml" + wait_api "$state/cell-admin.yaml" + k "$state/host.yaml" -n karmada-system wait --for=condition=Available deployment --all --timeout=300s >/dev/null + # The cell node restart recreated every site Pod; the Flux-owned Deployments + # and the retained volume must bring the site back with the same journal. + for d in fleet-site-runtime fleet-site-boot fleet-site-observer; do site wait --for=condition=Available "deployment/$d" --timeout=300s >/dev/null; done + cell -n kro-system wait --for=condition=Available deployment --all --timeout=300s >/dev/null + # Restarted Flux on both nodes; the hub catches up with the dispatch revision. + flux wait "$state" --cluster hub --cluster cell --cluster platform --timeout 600 >/dev/null + printf 'heal: hub and cell APIs restarted; Karmada, kro and site Deployments available; Flux on every cluster Ready at the current revision\n' + ;; + lifecycle) + # Pod and Job lifecycle are not effects: recreating site Pods or a completed + # Job must not change the journal, start a guest, or release capacity. + name=$(cat "$state/install-handoff") + py lifecycle-snapshot "$state" "$name" > "$state/lifecycle-before.json" + started=$(date -u +%Y-%m-%dT%H:%M:%SZ) + old_job=$(site get job "w-$name" -o jsonpath='{.metadata.uid}') + site delete pod -l app.kubernetes.io/name=fleet-site-runtime --wait=true >/dev/null + site delete pod -l app.kubernetes.io/name=fleet-site-boot --wait=true >/dev/null + site delete pod -l app.kubernetes.io/name=fleet-site-observer --wait=true >/dev/null + site delete job "w-$name" --wait=true >/dev/null + for d in fleet-site-runtime fleet-site-boot fleet-site-observer; do + site rollout status "deployment/$d" --timeout=300s >/dev/null + site wait --for=condition=Available "deployment/$d" --timeout=300s >/dev/null + done + for _ in $(seq 1 120); do + new_job=$(site get job "w-$name" -o jsonpath='{.metadata.uid}' 2>/dev/null || true) + [[ -z $new_job || $new_job == "$old_job" ]] || break + sleep 1 + done + [[ -n $new_job && $new_job != "$old_job" ]] || { echo 'kro did not recreate the completed Job' >&2; exit 1; } + site wait --for=condition=Complete "job/w-$name" --timeout=300s >/dev/null + # The restarted observer must republish from the unchanged journal. + for _ in $(seq 1 60); do + at=$(cell -n "$ns" get machineallocationhandoff "$name" -o jsonpath='{.status.observation.observedAt}') + [[ $at > $started ]] && break + sleep 2 + done + [[ $at > $started ]] || { echo 'observer did not republish after restart' >&2; exit 1; } + py lifecycle-snapshot "$state" "$name" > "$state/lifecycle-after.json" + py record-lifecycle "$state" "$old_job" "$new_job" + printf 'lifecycle: runtime, boot and observer Pods and the completed Job recreated; journal, guest starts and volume unchanged; capacity still occupied\n' + ;; + delivery-faults) + # Cell-local delivery faults injected with cell bootstrap credentials: a + # duplicate under another name, a wrong-cell intent, and a stale-epoch replay. + before=$(journal_digest) + py delivery-faults "$state" create + for fault in duplicate wrong-cell stale-epoch; do + job=$(cat "$state/fault-$fault-job") + for _ in $(seq 1 120); do site get job "$job" >/dev/null 2>&1 && break; sleep 1; done + site wait --for=condition=Failed "job/$job" --timeout=300s >/dev/null + done + after=$(journal_digest) + [[ $before == "$after" ]] || { echo 'provider journal changed during delivery faults' >&2; exit 1; } + py delivery-faults "$state" verify + py delivery-faults "$state" delete + printf 'delivery-faults: duplicate, wrong-cell and stale-epoch deliveries failed their Jobs by podFailurePolicy before effects; journal unchanged; kro pruned them\n' + ;; + release-status-a|release-status-b) + # Released claims must not keep public readiness or an installation reference. + project=consumer-a; [[ $step == release-status-a ]] || project=consumer-b + 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 + # The referenced Installation is retired through the real Milo API status subresource. + i=$(k "$state/$project/management-project.json" -n default get installation debian-pxe -o jsonpath='{.status.phase}/{.status.conditions[?(@.type=="Ready")].status}') + [[ $i == Released/False ]] || { echo "released $project Installation phase/Ready: $i" >&2; exit 1; } + fi + printf '%s: %s Machine Released, Bound False, Ready False, no current installation, no finalizer%s\n' "$step" "$project" "$([[ $step == release-status-a ]] && echo '; Installation Released, Ready False')" + ;; + reuse-status) + b=$(k "$state/consumer-b/management-project.json" -n default get machine allocation -o jsonpath='{.status.phase}/{.status.conditions[?(@.type=="Bound")].status}') + [[ $b == Bound/True ]] || { echo "reused consumer-b status: $b" >&2; exit 1; } + printf 'reuse-status: consumer-b Bound after verified cleanup\n' + ;; + wrong-location) + # Runs after both verified cleanups, so capacity is free: denial cannot be + # explained by contention. The customer recreates its request elsewhere. + before_custody=$(custody_digest); before_journal=$(journal_digest) + 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":"remote-elsewhere"},"powerState":"Off"}} +JSON + set +e + "$host" allocate --config "$state/acceptance.json" > "$state/wrong-location.out" 2> "$state/wrong-location.err" + code=$? + set -e + [[ $code -ne 0 ]] || { echo 'wrong-location Machine was allocated' >&2; exit 1; } + grep -q 'not served by the configured cell' "$state/wrong-location.err" || { echo "allocation failed for another reason: $(tail -c 300 "$state/wrong-location.err")" >&2; exit 1; } + after_custody=$(custody_digest); after_journal=$(journal_digest) + [[ $before_custody == "$after_custody" ]] || { echo 'private custody changed during wrong-location attempt' >&2; exit 1; } + [[ $before_journal == "$after_journal" ]] || { echo 'provider journal changed during wrong-location attempt' >&2; exit 1; } + k "$state/consumer-a/management-project.json" -n default get machine allocation -o json > "$state/wrong-location-machine.json" + python3 - "$state" "$code" "$before_custody" <<'PY' +import json,sys,pathlib,datetime +m=json.loads((pathlib.Path(sys.argv[1])/'wrong-location-machine.json').read_text()) +if m['metadata'].get('finalizers') or m.get('status'): raise SystemExit('wrong-location Machine gained finalizers or status') +record={'observedAt':datetime.datetime.now(datetime.timezone.utc).isoformat(),'requestedLocation':m['spec']['locationRef']['name'],'servedLocation':'local', + 'capacityFree':True,'exitCode':int(sys.argv[2]),'error':'ErrLocationNotServed','privateCustodyUnchanged':True,'privateCustodyRecords':int(sys.argv[3].split()[0]), + 'providerJournalUnchanged':True,'machineFinalizers':[],'machineStatus':None} +(pathlib.Path(sys.argv[1])/'evidence'/'wrong-location.json').write_text(json.dumps(record,indent=2,sort_keys=True)+'\n') +PY + printf 'wrong-location: denied before allocation with free capacity; private custody and provider journal unchanged\n' + ;; + boot-denials) + # Probe the boot Service from the runtime Pod: the same path firmware uses. + # The origin comes from the Flux-owned Service, which drift repair recreated. + origin="http://$(site get service fleet-site-boot -o jsonpath='{.spec.clusterIP}'):8080" + [[ $origin == "$(site get handoffdispatcher dispatcher -o jsonpath='{.status.bootOrigin}')" ]] || { echo 'dispatcher boot origin differs from the boot Service' >&2; exit 1; } + runtime fleet-multiplane boot-denials --origin "$origin" > "$state/boot-denials.txt" + grep -q '^PASS ' "$state/boot-denials.txt" || { echo 'closed-boot probe failed' >&2; exit 1; } + printf 'boot-denials: %s through the boot Service\n' "$(cat "$state/boot-denials.txt")" + ;; + flux-final) + # Every cluster converged on the last revision with nothing suspended. + flux wait "$state" --cluster platform --cluster hub --cluster cell --timeout 600 >/dev/null + python3 - "$state" <<'PY' +import json, pathlib, subprocess, sys +s = pathlib.Path(sys.argv[1]) +for c, cfg in (('platform', 'platform-admin.yaml'), ('hub', 'host.yaml'), ('cell', 'cell-admin.yaml')): + items = json.loads(subprocess.check_output(['kubectl', '--kubeconfig', str(s / cfg), 'get', 'kustomizations,helmreleases', '-A', '-o', 'json']))['items'] + held = [i['metadata']['name'] for i in items if i['spec'].get('suspend')] + if held: + raise SystemExit('%s still suspended: %s' % (c, held)) +PY + flux record "$state" --cluster platform --cluster hub --cluster cell --name final >/dev/null + flux ownership "$state" --name final >/dev/null + printf 'flux-final: platform, hub and cell Ready at the final revision with nothing suspended; one writer per site object\n' + ;; + *) echo "unknown step: $step" >&2; exit 64 ;; +esac diff --git a/hack/multiplane/stop.sh b/hack/multiplane/stop.sh new file mode 100755 index 00000000..f0fe3677 --- /dev/null +++ b/hack/multiplane/stop.sh @@ -0,0 +1,27 @@ +#!/usr/bin/env bash +# Stop only this run's exact containers. Preserve volumes and Unknown custody. +set -euo pipefail +state=${1:?private run state directory required} +prefix=$(cat "$state/prefix") +[[ $prefix =~ ^fleet-mp-[a-f0-9]{8}$ ]] || exit 1 +export DOCKER_CONTEXT=colima-fleet-acceptance-tcg +# The cell node holds the site runtime, journal volume, kro and worker Jobs; the +# platform node holds the Milo APIs and their etcd volumes; the registry holds +# the source revisions. Earlier-layout container names are kept for old runs. +for suffix in vm consumer-a consumer-b provider consumer-a-etcd consumer-b-etcd provider-etcd cell-control-plane platform-control-plane registry; do + name="$prefix-$suffix" + if docker inspect "$name" >/dev/null 2>&1; then + if [[ $(docker inspect -f '{{.State.Paused}}' "$name") == true ]]; then docker unpause "$name" >/dev/null; fi + docker stop --timeout 30 "$name" >/dev/null + fi +done +if docker inspect "$prefix-hub-control-plane" >/dev/null 2>&1; then + if [[ $(docker inspect -f '{{.State.Running}}' "$prefix-hub-control-plane") == true ]]; then + if [[ $(docker inspect -f '{{.State.Paused}}' "$prefix-hub-control-plane") == true ]]; then docker unpause "$prefix-hub-control-plane" >/dev/null; fi + if [[ -f "$state/sysctl.json" ]]; then python3 hack/multiplane/sysctl.py "$state" restore; fi + docker stop --timeout 30 "$prefix-hub-control-plane" >/dev/null + else + echo 'Hub already stopped; inspect sysctl.json for prior restoration evidence.' + fi +fi +printf 'Stopped %s; disks, journals and custody retained. Stopping does not prove release.\n' "$prefix" diff --git a/hack/multiplane/sysctl.py b/hack/multiplane/sysctl.py new file mode 100755 index 00000000..2f2b3658 --- /dev/null +++ b/hack/multiplane/sysctl.py @@ -0,0 +1,30 @@ +#!/usr/bin/env python3 +"""Reversible, explicitly opted-in inotify adjustment in the task Colima VM.""" +import json,os,pathlib,subprocess,sys +s=pathlib.Path(sys.argv[1]);action=sys.argv[2];prefix=(s/'prefix').read_text().strip() +os.environ['DOCKER_CONTEXT']='colima-fleet-acceptance-tcg' +def run(*args):return subprocess.check_output(args,text=True).strip() +endpoint=run('docker','context','inspect','colima-fleet-acceptance-tcg','--format','{{.Endpoints.docker.Host}}') +if not endpoint.endswith('/.colima/fleet-acceptance-tcg/docker.sock'):raise SystemExit('unexpected Colima profile') +node=prefix+'-hub-control-plane';current=int(run('docker','exec',node,'cat','/proc/sys/fs/inotify/max_user_instances')) +if action=='set': + if (s/'sysctl.json').exists():raise SystemExit('sysctl evidence already exists; do not overwrite original value') + if current<1024 and os.environ.get('FLEET_MULTIPLANE_INOTIFY')!='1024':raise SystemExit('Requires fs.inotify.max_user_instances>=1024. Opt into reversible task-VM adjustment with FLEET_MULTIPLANE_INOTIFY=1024') + record={'context':'colima-fleet-acceptance-tcg','setting':'fs.inotify.max_user_instances','original':current,'effective':max(current,1024)} + (s/'sysctl.json').write_text(json.dumps(record,indent=2)) + if current<1024:run('docker','exec',node,'sysctl','-w','fs.inotify.max_user_instances=1024') + record['observedEffective']=int(run('docker','exec',node,'cat','/proc/sys/fs/inotify/max_user_instances')) + (s/'sysctl.json').write_text(json.dumps(record,indent=2)) + if record['observedEffective']!=record['effective']:raise SystemExit('inotify adjustment readback mismatch; inspect sysctl.json') +elif action=='restore': + record=json.loads((s/'sysctl.json').read_text()) + record.pop('restored',None);record.pop('restoreSkipped',None) + if current==record['effective'] and current!=record['original']: + run('docker','exec',node,'sysctl','-w','fs.inotify.max_user_instances='+str(record['original']));record['restored']=True + elif current!=record['effective']:record['restoreSkipped']='value changed by another owner' + else:record['restored']=True + record['observedAfterRestore']=int(run('docker','exec',node,'cat','/proc/sys/fs/inotify/max_user_instances')) + (s/'sysctl.json').write_text(json.dumps(record,indent=2)) + if record.get('restored') and record['observedAfterRestore']!=record['original']:raise SystemExit('inotify restoration readback mismatch; inspect sysctl.json') +else:raise SystemExit('expected set or restore') +print(json.dumps(record)) diff --git a/hack/multiplane/teardown.sh b/hack/multiplane/teardown.sh new file mode 100755 index 00000000..299898a5 --- /dev/null +++ b/hack/multiplane/teardown.sh @@ -0,0 +1,65 @@ +#!/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. +# --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 +cd "$(dirname "$0")/../.." +umask 077 +state=${1:?private run state directory required} +mode=${2:-passed} +[[ $mode == passed || $mode == --discard-unknown ]] || { echo 'usage: teardown.sh STATE [--discard-unknown]' >&2; exit 64; } +prefix=$(cat "$state/prefix") +[[ $prefix =~ ^fleet-mp-[a-f0-9]{8}$ ]] || { echo 'unexpected prefix' >&2; exit 1; } +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; } +fi +hub="$prefix-hub-control-plane" +if docker inspect "$hub" >/dev/null 2>&1; then + [[ $(docker inspect -f '{{.State.Paused}}' "$hub") != true ]] || docker unpause "$hub" >/dev/null + if [[ $(docker inspect -f '{{.State.Running}}' "$hub") == true && -f $state/sysctl.json ]] && ! grep -q '"restored": true' "$state/sysctl.json"; then + python3 hack/multiplane/sysctl.py "$state" restore + fi +fi +for cluster in hub cell platform; do + if docker inspect "$prefix-$cluster-control-plane" >/dev/null 2>&1; then + # A private throwaway kubeconfig keeps kind from editing any user kubeconfig. + kind delete cluster --name "$prefix-$cluster" --kubeconfig "$state/kind-delete.kubeconfig" + fi +done +for suffix in registry vm consumer-a consumer-b provider consumer-a-etcd consumer-b-etcd provider-etcd; do + if docker inspect "$prefix-$suffix" >/dev/null 2>&1; then docker rm -f -v "$prefix-$suffix" >/dev/null; fi +done +image_tag_removed=true +pushed=() +if [[ -f $state/gitops-environment.json ]]; then + port=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["registryPort"])' "$state/gitops-environment.json") + pushed=("127.0.0.1:$port/fleet-site:$prefix") +fi +for image in "$prefix-site-image" "$prefix-provider-image" ${pushed[@]+"${pushed[@]}"}; do + docker image rm "$image" >/dev/null 2>&1 || true + if docker image inspect "$image" >/dev/null 2>&1; then image_tag_removed=false; fi +done +remaining=$(docker ps -a --filter "name=^$prefix-" --format '{{.Names}}') +[[ -z $remaining ]] || { echo "owned containers remain: $remaining" >&2; exit 1; } +rm -f "$state/kind-delete.kubeconfig" +if [[ $mode == passed ]]; then + # Credentials and raw journals are no longer needed once the run has passed. + rm -rf "$state/provider" "$state/consumer-a" "$state/consumer-b" "$state/provider-private" + rm -f "$state"/*.yaml "$state"/*-hub.json "$state"/private.json "$state"/cell-worker*.json "$state"/federation-cell.json "$state"/*.token "$state"/*-kubeconfig.json \ + "$state"/status-fault.json "$state"/acceptance.json "$state"/fleet-multiplane "$state"/fleet-multiplane-host + rm -rf "$state/site-bin" "$state/kro-chart" "$state/flux-tools/flux" "$state"/flux-tools/*.tar.gz +fi +[[ ! -f $state/sysctl.json ]] || cp "$state/sysctl.json" "$state/evidence/sysctl.json" +python3 - "$state" "$prefix" "$mode" "$image_tag_removed" <<'PY' +import datetime,json,pathlib,sys +s,prefix,mode=pathlib.Path(sys.argv[1]),sys.argv[2],sys.argv[3] +record={'observedAt':datetime.datetime.now(datetime.timezone.utc).isoformat(),'prefix':prefix,'deleted':'exact prefix containers (including the run registry) and platform, hub and cell kind clusters', 'providerImageTagRemoved':sys.argv[4]=='true', 'volumesVerifiedAbsent':False, + 'mode':'after passed acceptance' if mode=='passed' else 'discarded Unknown run by explicit request; not release evidence', + 'privateCredentialsRemoved':mode=='passed','remainingContainers':[]} +(s/'evidence'/'teardown.json').write_text(json.dumps(record,indent=2)+'\n') +PY +printf 'teardown: removed %s resources (%s)\n' "$prefix" "$mode" diff --git a/hack/multiplane/test-flux.py b/hack/multiplane/test-flux.py new file mode 100644 index 00000000..c9fcd115 --- /dev/null +++ b/hack/multiplane/test-flux.py @@ -0,0 +1,288 @@ +#!/usr/bin/env python3 +"""Offline tests for hack/multiplane/flux.py: source staging, push records and +reconcile waits, with fake flux and kubectl executables. Needs kustomize.""" +import argparse +import importlib.util +import json +import os +import pathlib +import shutil +import subprocess +import sys +import tempfile + +root = pathlib.Path(sys.argv[1]).resolve() +spec = importlib.util.spec_from_file_location('flux', root / 'hack/multiplane/flux.py') +flux = importlib.util.module_from_spec(spec) +sys.path.insert(0, str(root / 'hack/multiplane')) +spec.loader.exec_module(flux) +failures = [] + + +def check(name, ok, detail=''): + if not ok: + failures.append(name + (': ' + detail if detail else '')) + + +def expect_exit(name, fn, code): + try: + fn() + except SystemExit as e: + check(name, e.code == code, 'exit %s' % e.code) + return + check(name, False, 'no exit') + + +FAKE_KUBECTL = r'''#!/usr/bin/env python3 +import json, os, sys +a = sys.argv[1:] +open(os.environ['FAKE_TRACE'], 'a').write(json.dumps(a) + '\n') +rev = os.environ.get('FAKE_REVISION', '') +ready = os.environ.get('FAKE_READY', 'True') +if 'annotate' in a: sys.exit(0) +def requested(name): + calls = [json.loads(l) for l in open(os.environ['FAKE_TRACE'])] + matches = [c[-1].split('=', 1)[1] for c in calls if 'annotate' in c and name in c] + # FAKE_STRIP: a parent apply removed the first request before it was handled. + if name == os.environ.get('FAKE_STRIP') and len(matches) < 2: return None + return matches[-1] if matches else None +def handled(name): + if os.environ.get('FAKE_STALE') == '1': return 'old-request' + return requested(name) +def meta(name, **kw): + r = requested(name) + return dict(kw, name=name, annotations={'reconcile.fluxcd.io/requestedAt': r} if r else {}) +if 'ocirepositories.source.toolkit.fluxcd.io' in a and 'fleet-gitops' in a: + print(json.dumps({'metadata': meta('fleet-gitops', generation=1), 'status': {'observedGeneration': 1, 'conditions': [{'type': 'Ready', 'status': ready}], 'lastHandledReconcileAt': handled('fleet-gitops'), 'artifact': {'revision': rev}}})); sys.exit(0) +if 'kustomizations.kustomize.toolkit.fluxcd.io' in a: + names = ['flux-system/fleet-cluster', 'flux-system/fleet-coordination', 'flux-system/fleet-federation', 'flux-system/kro', + 'flux-system/fleet-site-base', 'flux-system/fleet-site-graph', 'flux-system/fleet-site-services', 'flux-system/fleet-site-dispatch'] + items = [{'metadata': meta(n.split('/')[1], namespace=n.split('/')[0], generation=2), 'spec': {}, + 'status': {'lastHandledReconcileAt': handled(n.split('/')[1]), 'observedGeneration': 2, 'lastAppliedRevision': rev, 'conditions': [{'type': 'Ready', 'status': ready, 'reason': 'ReconciliationSucceeded'}]}} + for n in names] + print(json.dumps({'items': items})); sys.exit(0) +sys.exit(1) +''' +FAKE_FLUX = r'''#!/usr/bin/env python3 +import json, os, sys +open(os.environ['FAKE_TRACE'], 'a').write(json.dumps(['flux'] + sys.argv[1:]) + '\n') +print(json.dumps({'repository': 'x', 'digest': 'sha256:' + 'd' * 64})) +''' + +if not shutil.which('kustomize'): + print('FAIL flux tests: kustomize is required') + sys.exit(1) +with tempfile.TemporaryDirectory() as tmp: + tmp = pathlib.Path(tmp) + bin_dir = tmp / 'bin' + bin_dir.mkdir() + (bin_dir / 'kubectl').write_text(FAKE_KUBECTL.replace('#!/usr/bin/env python3', '#!' + sys.executable)) + (bin_dir / 'kubectl').chmod(0o755) + trace = tmp / 'trace' + os.environ.update(PATH=str(bin_dir) + os.pathsep + os.environ['PATH'], FAKE_TRACE=str(trace)) + s = tmp / 'state' + (s / 'flux-tools').mkdir(parents=True) + (s / 'evidence').mkdir() + (s / 'prefix').write_text('fleet-mp-0000abcd\n') + # A tiny stand-in for the release install.yaml, accepted by overriding its pin. + fake_install = 'apiVersion: v1\nkind: Namespace\nmetadata: {name: flux-system}\n' + for name in ('source-controller', 'kustomize-controller', 'helm-controller', 'notification-controller', 'image-automation-controller', + 'image-reflector-controller', 'source-watcher'): + fake_install += '---\napiVersion: apps/v1\nkind: Deployment\nmetadata: {name: %s, namespace: flux-system}\nspec:\n template:\n spec:\n containers:\n - {name: manager, image: ghcr.io/fluxcd/%s:v0, args: []}\n' % (name, name) + fake_install += '---\napiVersion: v1\nkind: Service\nmetadata: {name: source-watcher, namespace: flux-system}\n' + (s / 'flux-tools' / 'install.yaml').write_text(fake_install) + flux.INSTALL_SHA256 = flux.sha256(s / 'flux-tools' / 'install.yaml') + (s / 'flux-tools' / 'flux').write_text(FAKE_FLUX.replace('#!/usr/bin/env python3', '#!' + sys.executable)) + (s / 'flux-tools' / 'flux').chmod(0o755) + env = {'registryHost': 'fleet-mp-0000abcd-registry', 'registryPort': 5555, 'karmadaPort': 1, 'cell': 'fleet-mp-0000abcd-cell', + 'cellEndpoint': 'https://fleet-mp-0000abcd-cell-control-plane:6443', 'siteImage': 'fleet-mp-0000abcd-registry:5000/fleet-site@sha256:' + 'a' * 64, + 'siteImageDigest': 'sha256:' + 'a' * 64} + (s / 'gitops-environment.json').write_text(json.dumps(env)) + (s / 'scoped-asset').write_text('local-milo/uid/fleet-provider/fleet.datumapis.com/Device/synthetic-device-central-01\n') + + def ns(**kw): + base = dict(state=str(s), root=str(root), revision=1, site='absent', bad_kro_chart=False, drop_site_volume=False, purpose='test', cluster=[], timeout=5) + base.update(kw) + return argparse.Namespace(**base) + + def render(rev, cluster): + out = subprocess.run(['kustomize', 'build', str(s / 'gitops' / ('r%d' % rev) / 'environment' / cluster)], text=True, capture_output=True, check=True).stdout + return out + + check('stage platform revision', flux.stage(ns(revision=1)) == 0) + cell1 = render(1, 'cell') + check('r1 has no site layers', 'name: fleet-site-services' not in cell1 and 'name: fleet-site-dispatch' not in cell1 and 'name: fleet-site-base' in cell1) + check('sync source is the run registry', 'url: oci://fleet-mp-0000abcd-registry:5000/fleet-gitops' in cell1 and 'tag: local' in cell1) + check('controllers pinned by digest', 'ghcr.io/fluxcd/source-controller@sha256:' in cell1) + check('unused controllers removed', 'image-automation-controller' not in cell1 and 'source-watcher' not in cell1) + hub1 = render(1, 'hub') + check('hub environment beside the Karmada kubeconfig', 'name: fleet-environment\n namespace: karmada-system' in hub1 and 'name: fleet-environment\n namespace: flux-system' in hub1) + check('stage dispatch revision', flux.stage(ns(revision=3, site='dispatch')) == 0) + cell3 = render(3, 'cell') + check('dispatch revision carries the site', 'FLEET_SITE_DISPATCH: "true"' in cell3 and 'path: ./config/site/instance' in cell3 and 'FLEET_SCOPED_ASSET' in cell3 + and 'path: ./config/site/services' in cell3 and ('FLEET_BOOT_SERVICE_IP: %s\n' % flux.BOOT_SERVICE_IP) in cell3.replace('"', '')) + # Flux replaces an undefined variable with an empty string, which would give + # the boot Service a random ClusterIP: every substituted variable must be defined. + import re + env_keys = set(re.findall(r'^ (FLEET_[A-Z_]+): ', cell3, re.M)) + used = set() + for layer in ('config/site/services', 'config/site/instance'): + for f in (root / layer).glob('*.yaml'): + used |= set(re.findall(r'\$\{(FLEET_[A-Z_]+)\}', f.read_text())) + check('substituted variables defined', used and used <= env_keys, str(sorted(used - env_keys))) + check('graph uses no Flux variables', not re.findall(r'\$\{FLEET_', (root / 'config/site/graph/rgd.yaml').read_text())) + check('stage off revision', flux.stage(ns(revision=2, site='off')) == 0 and 'FLEET_SITE_DISPATCH: "false"' in render(2, 'cell')) + flux.stage(ns(revision=4, site='dispatch', bad_kro_chart=True)) + check('bad chart revision patches only kro', flux.MISSING_DIGEST in render(4, 'cell') and flux.KRO_CHART_DIGEST not in render(4, 'cell')) + flux.stage(ns(revision=6, site='dispatch', drop_site_volume=True)) + check('volume removal revision', '$patch: delete' in render(6, 'cell') and 'fleet-site-state' in render(6, 'cell')) + sums = (s / 'gitops' / 'r3.SHA256SUMS').read_text() + check('content sums cover checkout config', 'config/site/graph/rgd.yaml' in sums and 'environment/cell/environment.yaml' in sums) + check('no credentials or Secrets staged', 'kind: Secret' not in cell3 + hub1) + + # A retained credential anywhere in the source refuses the revision. + (s / 'provider').mkdir() + secret = 'z' * 64 + (s / 'provider' / 'tokens.csv').write_text(secret + ',bootstrap,bootstrap,system:masters\n') + leaky = tmp / 'leaky' + shutil.copytree(root / 'config', leaky / 'config') + (leaky / 'config/site/instance/leak.yaml').write_text('# ' + secret + '\n') + expect_exit('stage refuses a retained token', lambda: flux.stage(ns(revision=9, root=str(leaky))), 1) + (leaky / 'config/site/instance/leak.yaml').write_text('apiVersion: v1\nkind: Secret\nmetadata: {name: x}\n') + expect_exit('stage refuses a Secret manifest', lambda: flux.stage(ns(revision=9, root=str(leaky))), 1) + os.environ['FLUX_FAKE'] = '1' + tampered = s / 'flux-tools' / 'install.yaml' + tampered.write_text(fake_install + '# changed\n') + expect_exit('stage refuses a changed install manifest', lambda: flux.stage(ns(revision=9)), 1) + tampered.write_text(fake_install) + + # Push records the digest, revision and checkout identity. + check('push', flux.push(ns(revision=3)) == 0) + rec = flux.current(s) + check('push record', rec['digest'] == 'sha256:' + 'd' * 64 and rec['fluxRevision'] == 'local@sha256:' + 'd' * 64 and rec['checkoutDirty'] is True) + calls = [json.loads(l) for l in trace.read_text().splitlines()] + pushc = next(c for c in calls if c[:3] == ['flux', 'push', 'artifact']) + check('push is reproducible and insecure-local only', '--reproducible' in pushc and '--insecure-registry' in pushc and 'oci://127.0.0.1:5555/fleet-gitops:local' in pushc) + + # Waits require Ready, the current generation and the pushed revision. + (s / 'cell-admin.yaml').write_text('') + os.environ['FAKE_REVISION'] = rec['fluxRevision'] + os.environ['FAKE_READY'] = 'True' + check('wait converged', isinstance(flux.wait_cluster(s, 'cell', 10), dict)) + check('wait requested a source reconcile', any('annotate' in c and 'flux-system/fleet-gitops'.split('/')[1] in c for c in + [json.loads(l) for l in trace.read_text().splitlines()])) + trace.write_text('') + os.environ['FAKE_STRIP'] = 'fleet-cluster' + stripped = flux.wait_cluster(s, 'cell', 20) + receipts = json.loads((s / 'evidence' / 'flux-reconciles.json').read_text()) + check('stripped request reissued and acknowledged', stripped['flux-system/fleet-cluster']['lastHandledReconcileAt'] == stripped['flux-system/fleet-cluster']['requestedAt'] + and receipts[-1]['lostRequestsReissued'] == {'flux-system/fleet-cluster': 1}, json.dumps(receipts[-1].get('lostRequestsReissued'))) + os.environ.pop('FAKE_STRIP') + os.environ['FAKE_STALE'] = '1' + expect_exit('Ready old status cannot satisfy new reconcile', lambda: flux.wait_cluster(s, 'cell', 4), 4) + os.environ.pop('FAKE_STALE') + os.environ['FAKE_READY'] = 'False' + expect_exit('wait not Ready times out', lambda: flux.wait_cluster(s, 'cell', 4), 4) + os.environ['FAKE_READY'] = 'True' + os.environ['FAKE_REVISION'] = 'local@sha256:' + 'e' * 64 + expect_exit('wait on another revision times out', lambda: flux.wait_cluster(s, 'cell', 4), 4) + check('wait at an explicit revision', isinstance(flux.wait_cluster(s, 'cell', 10, revision='local@sha256:' + 'e' * 64), dict)) + +# Fault guards reject root reconciliation undoing suspension or changing generation. +import fault_guard +obj = {'metadata': {'uid': 'same', 'generation': 2}, 'spec': {'suspend': True}} +dep = {'spec': {'replicas': 0}} +pods = {'items': []} +receipt = fault_guard.validate(obj, dep, pods) +check('fault guard retains identity', fault_guard.validate(obj, dep, pods, receipt) == receipt) +for changed in ( + {'metadata': {'uid': 'same', 'generation': 3}, 'spec': {'suspend': True}}, + {'metadata': {'uid': 'same', 'generation': 2}, 'spec': {'suspend': False}}, +): + try: + fault_guard.validate(changed, dep, pods, receipt) + check('fault guard rejects drift', False) + except ValueError: + pass +try: + fault_guard.validate(obj, dep, {'items': [{}]}, receipt) + check('fault guard rejects live Pods', False) +except ValueError: + pass + +root = {'metadata': {'generation': 4}, 'status': {'observedGeneration': 4, 'lastAppliedRevision': 'local@sha256:r3', + 'lastHandledReconcileAt': 't3', 'conditions': [{'type': 'Ready', 'status': 'True'}]}} +check('root receipt at the fault revision', fault_guard.root_receipt(root, 'local@sha256:r3')['lastHandledReconcileAt'] == 't3') +for bad in ({'lastAppliedRevision': 'local@sha256:r2'}, {'observedGeneration': 3}, {'conditions': [{'type': 'Ready', 'status': 'False'}]}): + stale = json.loads(json.dumps(root)) + stale['status'].update(bad) + try: + fault_guard.root_receipt(stale, 'local@sha256:r3') + check('root receipt rejects %s' % sorted(bad), False) + except ValueError: + pass + +# Ownership audit: one Flux layer per shared object, kro only for workers. +def world(**faults): + inv = {k: list(v) for k, v in flux.LAYER_INVENTORY.items()} + base_inv = [] + objects = {} + for (kind, ns, name), layer in flux.SHARED.items(): + objects[(kind, ns, name)] = {'metadata': {'name': name, 'uid': 'u-' + name, 'labels': {'kustomize.toolkit.fluxcd.io/name': layer}}} + if layer == 'fleet-site-base': + base_inv.append('%s_%s_x_%s' % (ns or '', name, kind)) + worker = 'w-op-' + 'a' * 40 + for kind, ns in flux.WORKER_KINDS: + objects[(kind, ns, worker)] = {'metadata': {'name': worker, 'uid': 'k-' + kind, 'labels': {'kro.run/node-id': kind, 'app.kubernetes.io/managed-by': 'kro'}}} + if faults.get('kro_deployment'): + objects[('deployments', 'fleet-site', 'fleet-site-boot')]['metadata']['labels']['kro.run/node-id'] = 'boot' + if faults.get('flux_job'): + objects[('jobs', 'fleet-site', worker)]['metadata']['labels']['kustomize.toolkit.fluxcd.io/name'] = 'fleet-site-services' + if faults.get('job_in_inventory'): + inv['flux-system/fleet-site-services'] = sorted(inv['flux-system/fleet-site-services'] + ['fleet-site_%s_batch_Job' % worker]) + if faults.get('kro_configmap'): + objects[('configmaps', 'fleet-site', 'kro-extra')] = {'metadata': {'name': 'kro-extra', 'uid': 'x', 'labels': {'kro.run/node-id': 'extra'}}} + if faults.get('pvc_in_services'): + inv['flux-system/fleet-site-services'] = sorted(inv['flux-system/fleet-site-services'] + ['fleet-site_fleet-site-state__PersistentVolumeClaim']) + if faults.get('missing_service'): + del objects[('services', 'fleet-site', 'fleet-site-boot')] + if faults.get('manual_job'): + objects[('jobs', 'fleet-site', 'manual')] = {'metadata': {'name': 'manual', 'uid': 'm', 'labels': {}}} + deps = {'flux-system/fleet-site-base': ['fleet-coordination'] + (['kro'] if faults.get('base_on_kro') else []), + 'flux-system/fleet-site-services': ['fleet-site-base'], 'flux-system/fleet-site-graph': ['kro', 'fleet-site-base'], + 'flux-system/fleet-site-dispatch': ['fleet-site-graph', 'fleet-site-services', 'fleet-federation']} + ks = {n: {'inventory': inv.get(n, base_inv if n == 'flux-system/fleet-site-base' else []), 'dependsOn': [{'name': d} for d in deps.get(n, [])]} + for n in list(flux.LAYER_INVENTORY) + ['flux-system/fleet-site-base']} + return objects, {'cell': {'kustomizations': ks}, 'hub': {'kustomizations': {}}, 'platform': {'kustomizations': {}}} + + +def audit(**faults): + objects, snaps = world(**faults) + + def fake_kubectl(state, cluster, *args, check=True, **kw): + a = [x for x in args if x not in ('-o', 'json')] + ns = a[1] if a[0] == '-n' else None + kind, name = a[-2], a[-1] + o = objects.get((kind, ns, name)) + return argparse.Namespace(returncode=0 if o else 1, stdout=json.dumps(o or {}), stderr='') + + def fake_kget(state, cluster, *args, **kw): + ns, kind = args[1], args[3] + return {'items': [o for (k, n, _), o in objects.items() if k == kind and n == ns]} + saved = flux.kubectl, flux.kget + flux.kubectl, flux.kget = fake_kubectl, fake_kget + try: + return flux.ownership('unused', snaps) + finally: + flux.kubectl, flux.kget = saved + + +record, problems = audit() +check('ownership audit passes a single-writer site', problems == [] and len(record['kroWrittenObjects']) == 4, str(problems)) +for fault in ('kro_deployment', 'flux_job', 'job_in_inventory', 'kro_configmap', 'pvc_in_services', 'missing_service', 'manual_job', 'base_on_kro'): + check('ownership audit rejects ' + fault, audit(**{fault: True})[1] != []) + +if failures: + print('FAIL flux tests:\n ' + '\n '.join(failures)) + sys.exit(1) +print('PASS flux tests') diff --git a/hack/multiplane/test-harness.sh b/hack/multiplane/test-harness.sh new file mode 100755 index 00000000..a2f5e561 --- /dev/null +++ b/hack/multiplane/test-harness.sh @@ -0,0 +1,273 @@ +#!/bin/sh +# Offline tests for the multi-plane acceptance harness. Uses fake docker, colima +# and go executables; never contacts a container runtime or cluster. +set -eu +root=$(CDPATH='' cd -- "$(dirname "$0")/../.." && pwd) +for f in "$root"/hack/multiplane/*.sh "$root"/hack/local-vm/run.sh; do bash -n "$f"; done +python3 -m py_compile "$root"/hack/multiplane/*.py +python3 "$root"/hack/multiplane/test-k8s-evidence.py "$root" +exec python3 - "$root" <<'PY' +import json, os, pathlib, re, stat, subprocess, sys, tempfile, time + +root = pathlib.Path(sys.argv[1]) +harness = root / 'hack/multiplane/harness.py' +failures = [] + +def check(name, condition, detail=''): + if not condition: + failures.append(name + (': ' + detail if detail else '')) + +FAKE = r'''#!/usr/bin/env python3 +import json, os, sys +tool = os.path.basename(sys.argv[0]); a = sys.argv[1:] +scenario = os.environ.get('FAKE', '') +with open(os.environ['FAKE_TRACE'], 'a') as t: t.write(json.dumps([tool] + a) + '\n') +if tool == 'docker': + if a[:2] == ['context', 'inspect']: + if scenario == 'no-context': sys.exit(1) + print('unix:///Users/x/.colima/fleet-acceptance-tcg/docker.sock'); sys.exit(0) + if a[:1] == ['info']: + print(json.dumps({'Architecture': 'aarch64', 'MemTotal': 8308948992, 'NCPU': 4})); sys.exit(0) + if a[:1] == ['ps']: + if '-a' in a: print('fleet-mp-0000aaaa-vm\texited'); sys.exit(0) + print('fleet-mp-1234abcd-vm' if scenario == 'busy' else 'unrelated'); sys.exit(0) + if a[:1] == ['run']: + print('x86_64'); sys.exit(0) +if tool == 'kubectl' and 'exec' in a and 'deploy/fleet-site-runtime' in a: + if 'journal.json' in a[-1]: + stage = os.environ.get('FAKE_STAGE', 'installer-started') + print(json.dumps({'fence': 'F' * 32, 'operations': {'op': {'request': {'id': 'install-op-1', 'kind': 'install', 'epoch': 1, 'fenceToken': 'T' * 32}, + 'stage': stage, 'bootToken': 'B' * 64, 'receipt': 'R' * 64, 'result': {'phase': 'Unknown'}, 'bootClosed': False}}})); sys.exit(0) + if 'virsh' in a: + import hashlib + print('fleet-local-' + hashlib.sha256(b'install-op-1').hexdigest()[:24]); sys.exit(0) +if tool == 'colima': + if 'df' in a[-1]: print('/dev/vdb1 41000000 20000000 %d 50%% /var/lib/docker' % (int(os.environ.get('FAKE_FREE_KB', '20000000')))) + elif 'inotify' in a[-1]: print(os.environ.get('FAKE_INOTIFY', '1024')) + sys.exit(0) +sys.exit(0) +''' + +with tempfile.TemporaryDirectory() as tmp: + tmp = pathlib.Path(tmp) + bin_dir = tmp / 'bin'; bin_dir.mkdir() + for tool in ('docker', 'colima', 'go', 'kind', 'kubectl', 'helm', 'openssl'): + p = bin_dir / tool; p.write_text(FAKE.replace('#!/usr/bin/env python3', '#!' + sys.executable)); p.chmod(0o755) + trace = tmp / 'trace' + base = dict(os.environ, PATH=str(bin_dir) + os.pathsep + os.environ['PATH'], FAKE_TRACE=str(trace)) + base.pop('FLEET_MULTIPLANE_INOTIFY', None) + + def run(args, env=None, **kw): + return subprocess.run([sys.executable, str(harness), *args], text=True, capture_output=True, env=dict(base, **(env or {})), **kw) + + def state(): + 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', 'asset', 'image', 'boot-service', 'boot-denials', 'site-worker', 'site-observer'] + (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)) + + # Preflight: pass, prerequisite failures (exit 2) and readiness block (exit 3). + for name, env, rootdir, expected in ( + ('pass', {}, good_root, 0), + ('no-context', {'FAKE': 'no-context'}, good_root, 2), + ('concurrent-runtime', {'FAKE': 'busy'}, good_root, 2), + ('low-disk', {'FAKE_FREE_KB': '1000'}, good_root, 2), + ('inotify-without-opt-in', {'FAKE_INOTIFY': '128'}, good_root, 2), + ('missing-location-denial', {}, bad_root, 3)): + s = state() + r = run(['preflight', '--state', str(s), '--root', str(rootdir), '--skip-tests'], env) + check('preflight ' + name, r.returncode == expected, 'exit %s: %s' % (r.returncode, r.stdout[-400:])) + pre = json.loads((s / 'evidence/preflight.json').read_text()) + check('preflight record ' + name, pre['status'] == {0: 'passed', 2: 'preflight-failed', 3: 'blocked'}[expected]) + s = state() + r = run(['preflight', '--state', str(s), '--root', str(good_root), '--skip-tests'], {'FAKE_INOTIFY': '128', 'FLEET_MULTIPLANE_INOTIFY': '1024'}) + check('preflight inotify opt-in', r.returncode == 0, r.stdout[-300:]) + calls = [json.loads(l) for l in trace.read_text().splitlines()] + check('preflight never mutates runtime', not any(c[0] == 'docker' and c[1] in ('rm', 'stop', 'kill', 'network', 'volume', 'system') for c in calls)) + check('preflight never starts colima without --bootstrap', not any(c[0] == 'colima' and 'start' in c for c in calls)) + + # Bounded phases: pass, fail, blocked passthrough, timeout kills the process group. + s = state() + check('phase pass', run(['phase', '--state', str(s), '--name', 'ok', '--timeout', '30', '--', 'sh', '-c', 'echo marker-ok']).returncode == 0) + check('phase fail', run(['phase', '--state', str(s), '--name', 'bad', '--timeout', '30', '--', 'sh', '-c', 'echo secret-in-stderr >&2; exit 7']).returncode == 1) + check('phase blocked', run(['phase', '--state', str(s), '--name', 'blocked', '--timeout', '30', '--', 'sh', '-c', 'exit 3']).returncode == 3) + started = time.monotonic() + pidfile = s / 'child.pid' + r = run(['phase', '--state', str(s), '--name', 'slow', '--timeout', '2', '--', 'sh', '-c', 'sleep 300 & echo $! > "$0"; wait', str(pidfile)]) + check('phase timeout code', r.returncode == 4, str(r.returncode)) + check('phase timeout bounded', time.monotonic() - started < 30) + time.sleep(0.5) + child = int(pidfile.read_text()) + try: + os.kill(child, 0); alive = True + except ProcessLookupError: + alive = False + check('phase timeout kills process group', not alive) + records = [json.loads(l) for l in (s / 'evidence/phases.jsonl').read_text().splitlines()] + check('phase records', [(x['name'], x['status']) for x in records] == [('ok', 'passed'), ('bad', 'failed'), ('blocked', 'blocked'), ('slow', 'timeout')], str(records)) + check('stdout markers retained', 'marker-ok' in (s / 'phases.log').read_text()) + check('stderr kept private', 'secret-in-stderr' not in (s / 'phases.log').read_text() and 'secret-in-stderr' not in (s / 'evidence/phases.jsonl').read_text()) + check('phase name validated', run(['phase', '--state', str(s), '--name', '../x', '--timeout', '1', '--', 'true']).returncode == 64) + + # Partial output and EOF must not bypass the phase deadline. + for name, script in ( + ('partial', 'import sys,time; sys.stdout.write("partial"); sys.stdout.flush(); time.sleep(60)'), + ('closed', 'import os,time; os.close(1); time.sleep(60)'), + ): + started = time.monotonic() + r = run(['phase', '--state', str(state()), '--name', name, '--timeout', '1', '--', sys.executable, '-c', script], timeout=10) + check(name + ' timeout', r.returncode == 4, r.stdout + r.stderr) + check(name + ' bounded', time.monotonic() - started < 8) + + # Provider observation never exposes fence, capability or receipt. + obs = state() + r = run(['wait-stage', '--state', str(obs), '--stage', 'installer-started', '--timeout', '5']) + check('wait-stage observes running installer', r.returncode == 0, r.stdout) + check('wait-stage sanitized', not any(x in r.stdout for x in ('B' * 64, 'R' * 64, 'T' * 32, 'F' * 32)), r.stdout) + r = run(['wait-stage', '--state', str(obs), '--stage', 'installer-started', '--timeout', '5'], {'FAKE_STAGE': 'disk-started'}) + check('wait-stage rejects missed window', r.returncode == 1, r.stdout) + r = run(['wait-stage', '--state', str(obs), '--stage', 'installer-started', '--timeout', '2'], {'FAKE_STAGE': 'prepared'}) + check('wait-stage bounded', r.returncode == 4, r.stdout) + out = run(['journal', '--state', str(obs)]).stdout + check('journal sanitized', 'B' * 64 not in out and 'install-op-1' in out, out) + calls = [json.loads(l) for l in trace.read_text().splitlines()] + check('provider observation only through the cell API', not any(c[0] == 'docker' and 'exec' in c for c in calls) + and any(c[0] == 'kubectl' and 'exec' in c and 'deploy/fleet-site-runtime' in c for c in calls)) + + # Secret scan: every retained credential form is detected and redacted. + s = state(); (s / 'evidence').mkdir() + (s / 'provider').mkdir(); (s / 'provider/tokens.csv').write_text('a' * 64 + ',bootstrap,bootstrap,system:masters\n') + (s / 'hub.json').write_text(json.dumps({'users': [{'user': {'token': 'k' * 40}}]})) + (s / 'provider-private').mkdir(); (s / 'provider-private/journal.json').write_text(json.dumps({'fence': 'f' * 32, 'operations': {'x': {'bootToken': 'b' * 64, 'request': {'fenceToken': 't' * 32}}}})) + (s / 'host.yaml').write_text('users:\n- user:\n client-key-data: ' + 'K' * 48 + '\n') + (s / 'evidence/clean.json').write_text('{"ok":true}') + check('scan clean', run(['scan', '--state', str(s)]).returncode == 0) + (s / 'worker.token').write_text('w' * 40 + '\n') + for secret in ('a' * 64, 'k' * 40, 'f' * 32, 'b' * 64, 't' * 32, 'K' * 48, 'w' * 40): + (s / 'evidence/leak.json').write_text('{"v":"%s"}' % secret) + 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. + 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')): + 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) + check('result lists retained containers', res['retainedContainers'] == [{'name': 'fleet-mp-0000aaaa-vm', 'state': 'exited'}], str(res['retainedContainers'])) + check('result keeps unknown custody', 'Unknown' in res['custody']) + + # Teardown refuses without passed acceptance, before touching the runtime. + s = state(); (s / 'prefix').write_text('fleet-mp-0000aaaa\n'); (s / 'evidence').mkdir() + trace.write_text('') + r = subprocess.run(['bash', str(root / 'hack/multiplane/teardown.sh'), str(s)], text=True, capture_output=True, env=base) + check('teardown refuses unknown', r.returncode == 1 and 'refusing' in r.stderr, r.stderr) + (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) + 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) + check('teardown rejects foreign prefix', r.returncode == 1 and trace.read_text() == '') + r = subprocess.run(['bash', str(root / 'hack/multiplane/run.sh'), '--bogus'], text=True, capture_output=True, env=base) + check('run usage', r.returncode == 64) + + # Static guards for runtime-only step code the offline fakes cannot execute. + steps = (root / 'hack/multiplane/steps.sh').read_text() + evidence = (root / 'hack/multiplane/evidence.py').read_text() + 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 = ['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'] + 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: + if name in ('allocate', 'admit-install', 'install', 'install-repeat', 'release', 'reuse', 'release-b', 'reflection-faults', 'evidence', + 'graph-lifecycle', 'drift', 'restart', 'fail-closed', 'retention'): + continue + check('step implemented: ' + name, ' %s)' % name in steps or '|%s)' % name in steps or ' %s|' % name in steps) + + # The kro graph and the worker exit-code contract must agree. kro owns only + # per-operation workers: the shared services and the durable site volume are + # Flux-owned and only referenced by the graph. + rgd = (root / 'config/site/graph/rgd.yaml').read_text() + services = (root / 'config/site/services/services.yaml').read_text() + main_go = (root / 'cmd/fleet-multiplane/main.go').read_text() + check('Job replacement waits for terminal Pods', 'podReplacementPolicy: Failed' in rgd) + check('rejected authority fails the Job', 'values: [65]' in rgd and 'exitRejected = 65' in main_go) + templates = re.findall(r'\n template:\n apiVersion: \S+\n kind: (\w+)', rgd) + check('graph templates only per-operation kinds', sorted(templates) == ['Job', 'Role', 'RoleBinding', 'ServiceAccount'], str(templates)) + check('every graph template is per handoff', rgd.count('forEach:\n - handoff: ${handoffs}') == 4 and rgd.count('${schema.spec.dispatch}') == 4) + refs = re.findall(r'\n externalRef:\n apiVersion: \S+\n kind: (\w+)', rgd) + check('graph references the shared site and the volume', sorted(refs) == ['Deployment', 'Deployment', 'Deployment', 'MachineAllocationHandoff', 'PersistentVolumeClaim', 'Service'], str(refs)) + check('workers run the runtime image', 'image: ${hypervisor.spec.template.spec.containers[0].image}' in rgd and 'image: "${FLEET_SITE_IMAGE}"' in services) + check('workers get per-operation resourceNames RBAC', 'resourceNames: ["${handoff.metadata.name}"]' in rgd) + # kro v0.9.4 rejects these resource IDs (pkg/graph/validation.go, kroReservedKeyWords and CEL reserved symbols). + reserved = {'apiVersion', 'context', 'dependency', 'dependencies', 'each', 'externalRef', 'externalReference', 'externalRefs', 'externalReferences', + 'graph', 'instance', 'item', 'items', 'kind', 'kro', 'metadata', 'namespace', 'object', 'resource', 'resourcegraphdefinition', + 'resourceGraphDefinition', 'resources', 'root', 'runtime', 'schema', 'self', 'serviceAccountName', 'spec', 'status', 'this', 'variables', + 'vars', 'version', 'true', 'false', 'null', 'in', 'as', 'break', 'const', 'continue', 'else', 'for', 'function', 'if', 'import', 'let', + 'loop', 'package', 'return', 'var', 'void', 'while'} + ids = re.findall(r'^ - id: (\S+)$', rgd, re.M) + check('graph resource IDs valid for kro', len(ids) == 10 and not set(ids) & reserved and all(re.fullmatch(r'[a-z][a-zA-Z0-9]*', i) for i in ids), str(ids)) + check('nothing in the graph is privileged', 'privileged: true' not in rgd) + check('only the runtime is privileged', services.count('privileged: true') == 1) + check('services own no volume', 'kind: PersistentVolumeClaim' not in services and 'kind: StorageClass' not in services) + check('boot Service at a fixed ClusterIP', 'clusterIP: "${FLEET_BOOT_SERVICE_IP}"' in services) + base = (root / 'config/site/base/site.yaml').read_text() + check('site volume is retained', 'reclaimPolicy: Retain' in base) + kro_rbac = (root / 'config/site/base/kro.yaml').read_text() + cluster_role = kro_rbac.split('kind: ClusterRole\n')[1].split('\n---')[0] + check('kro cluster-wide grant is read-only for site kinds', cluster_role.count('verbs: [get, list, watch]') == 5 + and cluster_role.count('create') == 1 and 'handoffdispatchers' in cluster_role.split('create')[0], cluster_role) + roles = {r.split('\n')[0]: r.split('\n---')[0] for r in kro_rbac.split('kind: Role\nmetadata: ')[1:]} + write_roles = {'{name: fleet-site-kro-workers, namespace: fleet-site}': ('jobs', 'serviceaccounts'), + '{name: fleet-site-kro-worker-rbac, namespace: fleet-coordination}': ('roles, rolebindings',)} + check('kro writes only worker kinds in their namespaces', sorted(roles) == sorted(write_roles) and all( + all(k in roles[n] for k in kinds) and not any(x in roles[n] for x in ('deployments', 'services', 'persistentvolumeclaims', 'configmaps', 'secrets')) + for n, kinds in write_roles.items()), str(sorted(roles))) + check('kro writes are shape-checked by admission', kro_rbac.count('kind: ValidatingAdmissionPolicy\n') == 2 and kro_rbac.count('kind: ValidatingAdmissionPolicyBinding\n') == 2 + and kro_rbac.count("request.userInfo.username == 'system:serviceaccount:kro-system:kro'") == 2 and 'parameterNotFoundAction: Deny' in kro_rbac) + kro = (root / 'config/multiplane/kro/kro.yaml').read_text() + check('unused chart ConfigMap grant removed, failing closed', 'postRenderers:' in kro and 'op: test' in kro and 'resources: [configmaps]' in kro and 'op: remove' in kro) + check('kro version pinned consistently', 'tag: v0.9.4@sha256:' in kro and "'version': 'v0.9.4'" in evidence and 'digest: sha256:4e8de4d3' in kro) + + # Imperative service installation is gone: only Flux installs services. + run_sh = (root / 'hack/multiplane/run.sh').read_text() + for name in ('run.sh', 'steps.sh', 'site.sh', 'topology.sh', 'milo.py', 'roles.py', 'verify-rbac.py'): + text = (root / 'hack/multiplane' / name).read_text() + check('no helm install in ' + name, 'helm install' not in text and 'helm upgrade' not in text) + check('no manifest apply of config in ' + name, not any(x in text for x in ("apply -f config/", "'apply','-f','config/multiplane", "'apply','-f','config/site", 'kind load'))) + check('no docker-run Milo API', 'docker' not in (root / 'hack/multiplane/milo.py').read_text().replace("os.environ['DOCKER_CONTEXT']", '')) + for f in ('flux-tools', 'topology', 'flux-source', 'flux-bootstrap-$c', 'flux-platform', 'flux-milo', 'federation-enrollment', 'flux-site', 'flux-verify'): + check('bootstrap phase present: ' + f, 'ph %s ' % f in run_sh or 'ph "%s" ' % f in run_sh) + check('dispatch is a source revision', "--site dispatch" in steps and 'patch handoffdispatcher' not in steps) + check('fault injection suspends Flux first', 'suspend milo-consumer-a true' in steps and '"suspend":true' in (root / 'hack/multiplane/reflection-faults.py').read_text()) + check('RBAC revocation repaired by Flux, not the harness', "'apply'" not in (root / 'hack/multiplane/verify-rbac.py').read_text()) + for path in ('config/site/base/site.yaml', 'config/site/graph/rgd.yaml', 'config/site/instance/dispatcher.yaml', 'config/multiplane/coordination/crd.yaml', + 'config/multiplane/host/custody.yaml', 'config/multiplane/karmada/karmada.yaml', 'config/multiplane/karmada-members/members.yaml'): + check('prune-protected: ' + path, 'kustomize.toolkit.fluxcd.io/prune: disabled' in (root / path).read_text()) + check('site volume is create-once', base.count('kustomize.toolkit.fluxcd.io/ssa: IfNotPresent') == 2) + check('graph has no Flux substitution', 'postBuild' not in (root / 'config/multiplane/clusters/cell/cell.yaml').read_text().split('name: fleet-site-graph')[1]) + cell_layers = (root / 'config/multiplane/clusters/cell/cell.yaml').read_text() + site_layers = (root / 'config/multiplane/clusters/cell-site/site.yaml').read_text() + base_layer = cell_layers.split('name: fleet-site-base')[1].split('\n---')[0] + services_layer = site_layers.split('name: fleet-site-services')[1].split('\n---')[0] + dispatch_layer = site_layers.split('name: fleet-site-dispatch')[1] + check('shared site infrastructure does not depend on kro', 'name: kro' not in base_layer and 'name: kro' not in services_layer and '{name: fleet-site-base' in services_layer) + check('dispatcher waits for graph and shared services', '{name: fleet-site-graph' in dispatch_layer and '{name: fleet-site-services' in dispatch_layer) + check('site layers use scoped identities', 'serviceAccountName: fleet-site-services-reconciler' in services_layer and 'serviceAccountName: fleet-site-dispatch-reconciler' in dispatch_layer) + r = subprocess.run([sys.executable, str(root / 'hack/multiplane/test-flux.py'), str(root)], text=True, capture_output=True) + check('flux source and scenario tests', r.returncode == 0, (r.stdout + r.stderr)[-1500:]) + +if failures: + print('FAIL multi-plane harness tests:\n ' + '\n '.join(failures)) + sys.exit(1) +print('PASS multi-plane harness tests') +PY diff --git a/hack/multiplane/test-k8s-evidence.py b/hack/multiplane/test-k8s-evidence.py new file mode 100644 index 00000000..18fd90a1 --- /dev/null +++ b/hack/multiplane/test-k8s-evidence.py @@ -0,0 +1,183 @@ +#!/usr/bin/env python3 +"""Offline tests for k8s_evidence.py against a fake kubectl. + +Every helper command the live acceptance uses is executed once on the success +path and on representative failure paths, so call-signature and data-shape +mistakes fail here instead of mid-run. Never contacts a cluster. +""" +import json +import os +import pathlib +import subprocess +import sys +import tempfile + +root = pathlib.Path(sys.argv[1]) +helper = root / 'hack/multiplane/k8s_evidence.py' +failures = [] + + +def check(name, ok, detail=''): + if not ok: + failures.append(name + (': ' + detail if detail else '')) + + +FAKE = r'''#!PYTHON +import json, os, sys +a = sys.argv[1:] +world = json.load(open(os.environ['FAKE_WORLD'])) +config = a[a.index('--kubeconfig') + 1] +args = [x for x in a if not x.startswith('--request-timeout')] +args = args[args.index('--kubeconfig') + 2:] +def ns(): + return args[args.index('-n') + 1] if '-n' in args else '' +def emit(v): print(json.dumps(v)); sys.exit(0) +if config.endswith('worker-kubeconfig.json'): + if args[-3:] == ['get', 'machineallocationhandoff', world['handoff']] or args[-5:-2] == ['get', 'machineallocationhandoff', world['handoff']]: + print('machineallocationhandoff/' + world['handoff']); sys.exit(0) + print('Error from server (Forbidden): denied', file=sys.stderr); sys.exit(1) +if args[:3] == ['config', 'view', '--raw']: + emit({'clusters': [{'cluster': {}}], 'contexts': [{'context': {}}], 'users': []}) +if 'exec' in args: + cmd = args[args.index('--') + 1:] + if cmd[:1] == ['cat'] and cmd[1].endswith('journal.json'): print(world['journal']); sys.exit(0) + if cmd[:1] == ['cat'] and '/qemu/' in cmd[1]: print(world['qemu']); sys.exit(0) + if cmd[:1] == ['virsh']: print(''); sys.exit(0) + sys.exit(1) +if args[:1] == ['create']: + obj = json.loads(sys.stdin.read()); world.setdefault('created', []).append(obj['metadata']['name']) + json.dump(world, open(os.environ['FAKE_WORLD'], 'w')); sys.exit(0) +if 'delete' in args: + name = args[args.index('delete') + 2] + world['jobs'].pop('w-' + name, None); json.dump(world, open(os.environ['FAKE_WORLD'], 'w')); sys.exit(0) +verb, kind = args[args.index('get') + 1], None +kind = args[args.index('get') + 1] +rest = args[args.index('get') + 2:] +name = rest[0] if rest and not rest[0].startswith('-') else None +if kind == 'job': + if name not in world['jobs']: print('NotFound', file=sys.stderr); sys.exit(1) + emit(world['jobs'][name]) +if kind == 'pods': + sel = args[args.index('-l') + 1].split('=', 1)[1] + emit({'items': [p for p in world['pods'] if p['metadata']['labels'].get('fleet.datumapis.com/handoff') == sel or p['metadata']['labels'].get('app.kubernetes.io/name') == sel]}) +if kind == 'pvc': emit({'metadata': {'uid': 'pvc-uid'}, 'spec': {'volumeName': 'pv-1'}}) +if kind == 'pv': emit({'metadata': {'uid': 'pv-uid'}, 'spec': {'persistentVolumeReclaimPolicy': 'Retain'}}) +if kind == 'machine': + emit(world['machines'][config.split('/')[-2]]) +if kind == 'role': emit({'metadata': {'labels': {'kro.run/node-id': 'workerRoles'}}, 'rules': [{'resourceNames': [world['handoff']], 'verbs': ['get']}]}) +if kind == 'machineallocationhandoffs': emit({'items': world['handoffs']}) +if kind == 'machineallocationhandoff': emit({'metadata': {'name': name}, 'spec': {}}) +sys.exit(1) +'''.replace('#!PYTHON', '#!' + sys.executable) + + +def job(name, uid, conditions, failed=0, succeeded=0): + return {'metadata': {'name': name, 'uid': uid, 'labels': {'kro.run/node-id': 'workers'}}, + 'spec': {'backoffLimit': 6, 'podReplacementPolicy': 'Failed', 'template': {'spec': {'serviceAccountName': name}}}, + 'status': {'failed': failed, 'succeeded': succeeded, 'conditions': [{'type': t, 'status': 'True', 'reason': r} for t, r in conditions]}} + + +def pod(name, uid, handoff, job_uid, phase, exit_code=None, app=None): + status = {'phase': phase, 'containerStatuses': [{'state': {'terminated': {'exitCode': exit_code}} if exit_code is not None else {'running': {}}}]} + labels = {'batch.kubernetes.io/controller-uid': job_uid} + labels['fleet.datumapis.com/handoff' if handoff else 'app.kubernetes.io/name'] = handoff or app + return {'metadata': {'name': name, 'uid': uid, 'labels': labels}, 'spec': {'nodeName': 'cell'}, 'status': status} + + +with tempfile.TemporaryDirectory() as tmp: + tmp = pathlib.Path(tmp) + bindir = tmp / 'bin'; bindir.mkdir() + (bindir / 'kubectl').write_text(FAKE); (bindir / 'kubectl').chmod(0o755) + state = tmp / 'state'; (state / 'evidence').mkdir(parents=True); (state / 'consumer-a').mkdir(); (state / 'consumer-b').mkdir() + (state / 'prefix').write_text('fleet-mp-1234abcd\n') + h = 'op-' + 'a' * 40 + (state / 'install-handoff').write_text(h + '\n') + request = {'id': 'install-1', 'kind': 'install', 'assetID': 'x', 'bindingID': 'b', 'epoch': 1, 'fenceToken': 'F' * 32} + world = {'handoff': h, 'journal': '{"operations":{}}', 'qemu': 'x: starting up a\nx: starting up b\n', + 'jobs': {'w-' + h: job('w-' + h, 'job-2', [('Complete', 'CompletionsReached')], succeeded=1)}, + 'pods': [pod('p2', 'pod-2', h, 'job-2', 'Succeeded', 0)] + [pod(d, d + '-uid', None, '', 'Running', app=d) for d in ('fleet-site-runtime', 'fleet-site-boot', 'fleet-site-observer')], + 'machines': {'consumer-a': {'status': {'phase': 'Ready', 'conditions': [{'type': 'Bound', 'status': 'True'}, {'type': 'Ready', 'status': 'True'}]}}, + 'consumer-b': {'status': {'phase': 'Bound', 'conditions': [{'type': 'Bound', 'status': 'True'}]}}}, + 'handoffs': [{'metadata': {'name': h}, 'spec': {'cell': 'fleet-mp-1234abcd-cell', 'requestJSON': json.dumps(request)}}]} + wpath = tmp / 'world.json' + env = dict(os.environ, PATH=str(bindir) + os.pathsep + os.environ['PATH'], FAKE_WORLD=str(wpath)) + + def save(): + wpath.write_text(json.dumps(world)) + + def run(*args): + save() + r = subprocess.run([sys.executable, str(helper), args[0], str(state), *args[1:]], text=True, capture_output=True, env=env) + world.update(json.loads(wpath.read_text())) + return r + + r = run('running-pod', h) + check('running-pod ignores completed pods', r.returncode == 0 and r.stdout.strip() == '', r.stdout + r.stderr) + r = run('job-pod', h, 'job-2') + check('job-pod finds pod by job uid', r.stdout.strip() == 'pod-2', r.stdout + r.stderr) + r = run('job', h) + check('job record', r.returncode == 0 and json.loads(r.stdout)['uid'] == 'job-2', r.stderr) + + # Interruption records. + ops = lambda stage: json.dumps([{'id': 'install-1', 'kind': 'install', 'stage': stage, 'phase': 'Unknown' if stage != 'done' else 'Succeeded'}]) + (state / 'interrupt-observed.json').write_text(json.dumps({'operation': {'id': 'install-1', 'stage': 'installer-started', 'domain': 'd'}, 'domainRunning': True})) + (state / 'interrupt-after.json').write_text(ops('installer-started')) + (state / 'interrupt-job-before-pod.json').write_text(json.dumps({'uid': 'job-1', 'failed': 0})) + (state / 'interrupt-job-after-pod.json').write_text(json.dumps({'uid': 'job-1', 'failed': 1})) + r = run('record-pod-interrupt', 'pod-0', 'pod-1') + check('record-pod-interrupt', r.returncode == 0, r.stderr) + (state / 'interrupt-job-before.json').write_text(ops('installer-verified')) + (state / 'interrupt-job-after.json').write_text(ops('disk-started')) + r = run('record-job-interrupt', 'job-1', 'job-2', 'pod-1', 'pod-2') + check('record-job-interrupt', r.returncode == 0, r.stderr) + (state / 'interrupt-job-before.json').write_text(ops('done')) + check('record-job-interrupt rejects finished install', run('record-job-interrupt', 'job-1', 'job-2', 'pod-1', 'pod-2').returncode != 0) + (state / 'interrupt-job-before.json').write_text(ops('installer-verified')) + run('record-job-interrupt', 'job-1', 'job-2', 'pod-1', 'pod-2') + (state / 'resume-after.json').write_text(ops('done')) + r = run('record-resume', h) + check('record-resume', r.returncode == 0, r.stderr) + + # Lifecycle: snapshot, replace site Pods and the Job, record. + r = run('lifecycle-snapshot', h) + check('lifecycle-snapshot', r.returncode == 0, r.stderr) + (state / 'lifecycle-before.json').write_text(r.stdout) + world['pods'] = [pod('p3', 'pod-3', h, 'job-3', 'Succeeded', 0)] + [pod(d, d + '-new', None, '', 'Running', app=d) for d in ('fleet-site-runtime', 'fleet-site-boot', 'fleet-site-observer')] + world['jobs']['w-' + h] = job('w-' + h, 'job-3', [('Complete', 'CompletionsReached')], succeeded=1) + r = run('lifecycle-snapshot', h) + (state / 'lifecycle-after.json').write_text(r.stdout) + r = run('record-lifecycle', 'job-2', 'job-3') + check('record-lifecycle', r.returncode == 0 and (state / 'evidence/lifecycle.json').exists(), r.stderr) + world['journal'] = '{"operations":{"changed":true}}' + (state / 'lifecycle-after.json').write_text(run('lifecycle-snapshot', h).stdout) + check('record-lifecycle rejects journal change', run('record-lifecycle', 'job-2', 'job-3').returncode != 0) + + # Worker RBAC probes. + (state / 'worker.token').write_text('w' * 40) + r = run('worker-rbac', h) + check('worker-rbac', r.returncode == 0 and (state / 'k8s-worker-rbac.json').exists(), r.stderr) + + # Delivery faults: create, verify failure by policy, prune. + r = run('delivery-faults', 'create') + check('delivery-faults create', r.returncode == 0 and len(world.get('created', [])) == 3, r.stderr) + for fault in ('duplicate', 'wrong-cell', 'stale-epoch'): + name = (state / ('fault-%s-handoff' % fault)).read_text().strip() + check('fault name fits worker names: ' + fault, len('w-' + name) <= 63, name) + world['jobs']['w-' + name] = job('w-' + name, fault, [('Failed', 'PodFailurePolicy')], failed=1) + world['pods'].append(pod('f-' + fault, 'f-' + fault, name, fault, 'Failed', 65)) + r = run('delivery-faults', 'verify') + check('delivery-faults verify', r.returncode == 0, r.stderr) + r = run('delivery-faults', 'delete') + check('delivery-faults delete', r.returncode == 0 and json.loads((state / 'evidence/delivery-faults.json').read_text()).get('prunedByKro'), r.stderr) + world['pods'][-1]['status']['containerStatuses'][0]['state']['terminated']['exitCode'] = 75 + world['jobs']['w-' + name] = job('w-' + name, 'x', [('Failed', 'BackoffLimitExceeded')], failed=7) + check('delivery-faults rejects non-policy failure', run('delivery-faults', 'verify').returncode != 0) + + secrets = ['F' * 32, 'w' * 40] + leaked = [p.name for p in (state / 'evidence').rglob('*') if p.is_file() and any(s in p.read_text() for s in secrets)] + check('evidence records contain no fence or token', not leaked, str(leaked)) + +if failures: + print('FAIL k8s evidence tests:\n ' + '\n '.join(failures)) + sys.exit(1) +print('PASS k8s evidence tests') diff --git a/hack/multiplane/topology.sh b/hack/multiplane/topology.sh new file mode 100644 index 00000000..d10e43cf --- /dev/null +++ b/hack/multiplane/topology.sh @@ -0,0 +1,81 @@ +#!/usr/bin/env bash +# Create this run's disposable infrastructure: the local OCI registry and three +# kind clusters (platform for Milo, hub for management/Karmada, cell for the +# site). Installs no service: every service is reconciled by each cluster's +# Flux from the published source (hack/multiplane/flux.py, docs/operations/gitops.md). +set -euo pipefail +umask 077 +state=${1:?private state directory required} +prefix=$(cat "$state/prefix") +[[ $prefix =~ ^fleet-mp-[a-f0-9]{8}$ ]] || { echo "unexpected prefix" >&2; exit 1; } +export DOCKER_CONTEXT=colima-fleet-acceptance-tcg KIND_EXPERIMENTAL_PROVIDER=docker +node='kindest/node:v1.35.0@sha256:452d707d4862f52530247495d180205e029056831160e22870e37e3f6c1ac31f' +registry_image=$(python3 -c 'import sys; sys.path.insert(0, "hack/multiplane"); import flux; print(flux.REGISTRY_IMAGE)') +free_port() { python3 -c 'import socket; s=socket.socket(); s.bind(("127.0.0.1", 0)); print(s.getsockname()[1]); s.close()'; } + +# The source and image registry: plain HTTP on the kind network (local seam). +reg_port=$(free_port) +docker run -d --name "$prefix-registry" --network kind --memory 128m --memory-swap 128m --cpus 0.5 \ + -p "127.0.0.1:$reg_port:5000" "$registry_image" >/dev/null +for _ in $(seq 1 30); do curl -fsS "http://127.0.0.1:$reg_port/v2/" >/dev/null 2>&1 && break; sleep 1; done +curl -fsS "http://127.0.0.1:$reg_port/v2/" >/dev/null || { echo 'registry did not start' >&2; exit 1; } + +# Platform: three Milo project APIs, each published on its own NodePort. +api_port=$(free_port) +{ + echo 'kind: Cluster' + echo 'apiVersion: kind.x-k8s.io/v1alpha4' + echo 'nodes:' + echo ' - role: control-plane' + echo ' extraPortMappings:' +} > "$state/platform-kind.yaml" +printf '{' > "$state/platform-ports.json" +sep= +for entry in provider:30441 consumer-a:30442 consumer-b:30443; do + role=${entry%%:*} np=${entry##*:} hp=$(free_port) + printf ' - {containerPort: %s, hostPort: %s, listenAddress: 127.0.0.1}\n' "$np" "$hp" >> "$state/platform-kind.yaml" + printf '%s"%s": %s' "$sep" "$role" "$hp" >> "$state/platform-ports.json"; sep=', ' +done +printf '}\n' >> "$state/platform-ports.json" +kind create cluster --name "$prefix-platform" --config "$state/platform-kind.yaml" --kubeconfig "$state/platform-admin.yaml" --image "$node" --wait 180s +docker update --memory 2300m --memory-swap 2300m --cpus 2 "$prefix-platform-control-plane" >/dev/null + +cat > "$state/hub-kind.yaml" </dev/null + +# The cell pulls the site image by digest from the run registry. +cat > "$state/cell-kind.yaml" <<'YAML' +kind: Cluster +apiVersion: kind.x-k8s.io/v1alpha4 +containerdConfigPatches: + - |- + [plugins."io.containerd.grpc.v1.cri".registry] + config_path = "/etc/containerd/certs.d" +YAML +kind create cluster --name "$prefix-cell" --config "$state/cell-kind.yaml" --kubeconfig "$state/cell-admin.yaml" --image "$node" --wait 180s +docker exec "$prefix-cell-control-plane" mkdir -p "/etc/containerd/certs.d/$prefix-registry:5000" +printf '[host."http://%s-registry:5000"]\n capabilities = ["pull", "resolve"]\n' "$prefix" | + docker exec -i "$prefix-cell-control-plane" tee "/etc/containerd/certs.d/$prefix-registry:5000/hosts.toml" >/dev/null +# The cell node hosts the cell API, Flux, kro and the site, including the 3 GiB +# VM runtime Pod that runs the TCG guest. +docker update --memory 4400m --memory-swap 4400m --cpus 2 "$prefix-cell-control-plane" >/dev/null +python3 hack/multiplane/sysctl.py "$state" set + +python3 - "$state" "$prefix" "$reg_port" "$api_port" <<'PY' +import json, pathlib, sys +s, prefix, reg, api = pathlib.Path(sys.argv[1]), sys.argv[2], sys.argv[3], sys.argv[4] +env = {'registryHost': prefix + '-registry', 'registryPort': int(reg), 'karmadaPort': int(api), + 'cell': prefix + '-cell', 'cellEndpoint': 'https://%s-cell-control-plane:6443' % prefix} +(s / 'gitops-environment.json').write_text(json.dumps(env, indent=2) + '\n') +PY +printf 'topology: registry, platform, hub and cell clusters created; no service installed\n' diff --git a/hack/multiplane/verify-rbac.py b/hack/multiplane/verify-rbac.py new file mode 100755 index 00000000..2583bbcf --- /dev/null +++ b/hack/multiplane/verify-rbac.py @@ -0,0 +1,101 @@ +#!/usr/bin/env python3 +"""Negative writes and credential revocation against real API servers.""" +import json,pathlib,subprocess,sys,time +s=pathlib.Path(sys.argv[1]);ns='fleet-coordination' +def call(config,*args,input=None):return subprocess.run(['kubectl','--kubeconfig',str(config),'--request-timeout=15s',*args],input=input,text=True,capture_output=True) +def forbidden(config,*args): + r=call(config,*args) + if r.returncode==0 or 'forbidden' not in r.stderr.lower():raise SystemExit('Expected Forbidden for '+config.name+' '+args[0]+': '+r.stderr[:200]) +# The site observer is the only cell identity that writes handoff status. +token=call(s/'cell-admin.yaml','-n','fleet-site','create','token','fleet-site-observer','--duration=10m') +if token.returncode:raise SystemExit(token.stderr) +admin=json.loads(call(s/'cell-admin.yaml','config','view','--raw','--minify','-o','json').stdout) +admin['users']=[{'name':'observer','user':{'token':token.stdout.strip()}}];admin['contexts'][0]['context']['user']='observer' +local=s/'observer-kubeconfig.json';local.write_text(json.dumps(admin));local.chmod(0o600) +try: + r=call(local,'-n',ns,'get','machineallocationhandoffs') + if r.returncode:raise SystemExit('observer cannot list delivered intent: '+r.stderr[:200]) + forbidden(local,'-n',ns,'create','configmap','forbidden-write','--from-literal=x=y') + forbidden(local,'-n',ns,'patch','machineallocationhandoff','forbidden-write','--type=merge','-p','{"spec":{"cell":"other"}}') + forbidden(local,'-n',ns,'delete','machineallocationhandoff','forbidden-write') + forbidden(local,'-n',ns,'get','secrets') + forbidden(local,'-n','fleet-site','create','job','forbidden','--image=x') + forbidden(s/'management-hub.json','-n',ns,'patch','machineallocationhandoff','forbidden-write','--subresource=status','--type=merge','-p','{"status":{}}') + for name in ('consumer-a','consumer-b'): + forbidden(s/name/'customer-project.json','-n','default','patch','machine','allocation','--subresource=status','--type=merge','-p','{"status":{"phase":"Ready"}}') + forbidden(s/name/'customer-project.json','-n','default','get','secrets') + # Revoke the actual observer RoleBinding and prove denied reads. The harness + # never restores it: the cell's Flux recreates it from the source. + old=json.loads(call(s/'cell-admin.yaml','-n',ns,'get','rolebinding','fleet-site-observer','-o','json').stdout)['metadata']['uid'] + r=call(s/'cell-admin.yaml','-n',ns,'delete','rolebinding','fleet-site-observer') + if r.returncode:raise SystemExit(r.stderr) + forbidden(local,'-n',ns,'get','machineallocationhandoffs') + r=call(s/'cell-admin.yaml','-n','flux-system','annotate','--overwrite','kustomization','fleet-site-base','reconcile.fluxcd.io/requestedAt=%f'%time.time()) + if r.returncode:raise SystemExit(r.stderr) + for _ in range(150): + b=call(s/'cell-admin.yaml','-n',ns,'get','rolebinding','fleet-site-observer','-o','json') + if b.returncode==0 and call(local,'-n',ns,'get','machineallocationhandoffs').returncode==0:break + time.sleep(2) + else:raise SystemExit('Flux did not restore the revoked observer RoleBinding') + binding=json.loads(b.stdout) + if binding['metadata']['uid']==old or binding['metadata'].get('labels',{}).get('kustomize.toolkit.fluxcd.io/name')!='fleet-site-base': + raise SystemExit('observer RoleBinding was not recreated by Flux') + (s/'evidence'/'flux-rbac-restore.json').write_text(json.dumps({'object':'fleet-coordination/RoleBinding/fleet-site-observer','revokedUID':old,'restoredUID':binding['metadata']['uid'], + 'restoredBy':'kustomize-controller (Kustomization fleet-site-base)','deniedWhileRevoked':True,'observerReadsRestored':True},indent=2)+'\n') +finally: + local.unlink(missing_ok=True) +print('Verified forbidden observer/project/hub writes and observer RoleBinding revocation; Flux restored the binding') +# kro's narrowed authority: cluster-wide reads, writes only of per-operation +# kinds in their namespaces, and admission policies that bind those writes to +# the worker shape. Checked as kro's own identity through impersonation; +# admission is exercised with server-side dry runs, so nothing is persisted. +kro='system:serviceaccount:kro-system:kro';site='fleet-site';h='machineallocationhandoffs.coordination.fleet.datumapis.com' +def can(*args): + r=call(s/'cell-admin.yaml','auth','can-i',*args,'--as',kro) + if r.stdout.strip() not in ('yes','no'):raise SystemExit('auth can-i failed: '+r.stderr[:200]) + return r.stdout.strip()=='yes' +allowed=[('create','jobs','-n',site),('create','serviceaccounts','-n',site),('create','roles','-n',ns),('create','rolebindings','-n',ns), + ('list','deployments','-A'),('list','services','-A'),('watch',h,'-A'),('get','persistentvolumeclaims','-n',site)] +denied=[('create','deployments','-n',site),('patch','deployments','-n',site),('create','services','-n',site),('delete','services','-n',site), + ('delete','persistentvolumeclaims','-n',site),('patch','configmaps','-n',site),('create','jobs','-n','default'),('create','jobs','-n','kube-system'), + ('create','roles','-n',site),('create','rolebindings','-n','kube-system'),('create','clusterroles'),('get','secrets','-n',site), + ('patch',h,'-n',ns),('update',h,'--subresource=status','-n',ns),('delete','validatingadmissionpolicies')] +bad=[' '.join(a) for a in allowed if not can(*a)]+['denied '+' '.join(a) for a in denied if can(*a)] +if bad:raise SystemExit('kro RBAC is not the narrowed grant: '+'; '.join(bad)) +# Grants the kro chart keeps because kro needs them: it creates the CRD for each +# graph's kind, and elects a leader. Recorded as remaining authority, not hidden. +retained=[('create','customresourcedefinitions'),('delete','customresourcedefinitions'),('update','leases','-n','kro-system')] +retained={' '.join(a):can(*a) for a in retained} +image=json.loads((s/'gitops-environment.json').read_text())['siteImage'] +def job(**change): + c={'name':'worker','image':image,'command':['fleet-multiplane','site-worker'],'securityContext':{'runAsUser':0,'allowPrivilegeEscalation':False,'readOnlyRootFilesystem':True,'capabilities':{'drop':['ALL']}}} + spec={'restartPolicy':'Never','serviceAccountName':'w-op-admission-probe','containers':[c],'volumes':[{'name':'state','persistentVolumeClaim':{'claimName':'fleet-site-state'}},{'name':'tmp','emptyDir':{}}]} + for k,v in change.items(): + (c if k in ('image','securityContext','env','volumeMounts') else spec)[k]=v + return {'apiVersion':'batch/v1','kind':'Job','metadata':{'name':'w-op-admission-probe','namespace':site,'labels':{'fleet.datumapis.com/handoff':'op-admission-probe'}},'spec':{'template':{'spec':spec}}} +role=lambda rules:{'apiVersion':'rbac.authorization.k8s.io/v1','kind':'Role','metadata':{'name':'w-op-admission-probe','namespace':ns},'rules':rules} +own=[{'apiGroups':['coordination.fleet.datumapis.com'],'resources':['machineallocationhandoffs'],'resourceNames':['op-admission-probe'],'verbs':['get']}] +# RBAC resolves a binding's Role before admission runs, so the probe binds an +# existing Role that kro fully holds; a dry run cannot create w- first. +binding=lambda name,sa,ref:{'apiVersion':'rbac.authorization.k8s.io/v1','kind':'RoleBinding','metadata':{'name':name,'namespace':ns}, + 'subjects':[{'kind':'ServiceAccount','name':sa,'namespace':site}],'roleRef':{'apiGroup':'rbac.authorization.k8s.io','kind':'Role','name':ref}} +sa=lambda name:{'apiVersion':'v1','kind':'ServiceAccount','metadata':{'name':name,'namespace':site}} +cases={'admitted':{'worker Job':job(),'worker Role':role(own),'worker ServiceAccount':sa('w-op-admission-probe')}, + 'denied':{'Job as the observer':job(serviceAccountName='fleet-site-observer'),'privileged Job':job(securityContext={'privileged':True,'allowPrivilegeEscalation':True}), + 'Job from another image':job(image='registry.k8s.io/pause:3.10'),'Job with a hostPath volume':job(volumes=[{'name':'host','hostPath':{'path':'/'}}]), + 'Job on the host network':job(hostNetwork=True),'Role listing every handoff':role([dict(own[0],resourceNames=[],verbs=['get','list'])]), + 'RoleBinding to another Role, for the observer':binding('w-op-admission-probe','fleet-site-observer','fleet-site-kro-worker-rbac'),'ServiceAccount outside the worker set':sa('fleet-site-probe')}} +record={'identity':kro,'allowed':[' '.join(a) for a in allowed],'denied':[' '.join(a) for a in denied],'chartGrantsRetained':retained,'admission':{}} +for outcome,objs in cases.items(): + for name,obj in objs.items(): + r=call(s/'cell-admin.yaml','create','--dry-run=server','--as',kro,'-f','-',input=json.dumps(obj)) + ok=r.returncode==0 + by_policy='ValidatingAdmissionPolicy' in r.stderr and 'fleet-site-kro-worker-' in r.stderr + if (outcome=='admitted')!=ok or (not ok and not by_policy and 'forbidden' not in r.stderr.lower()): + raise SystemExit('kro admission %s for %s: %s'%('denied' if not ok else 'admitted',name,r.stderr[:300])) + record['admission'][name]={'expected':outcome,'admitted':ok,'deniedBy':None if ok else ('ValidatingAdmissionPolicy' if by_policy else 'RBAC')} +if any(v['deniedBy']!='ValidatingAdmissionPolicy' for v in record['admission'].values() if not v['admitted']): + raise SystemExit('expected the admission policies, not RBAC, to deny in-namespace shape violations: %s'%record['admission']) +(s/'evidence'/'kro-rbac.json').write_text(json.dumps(record,indent=2,sort_keys=True)+'\n') +print('Verified kro RBAC and admission confine it to per-operation objects: %d allowed, %d denied verbs; %d shapes admitted, %d denied by policy'%( + len(allowed),len(denied),len(cases['admitted']),len(cases['denied']))) diff --git a/internal/controller/lifecycle.go b/internal/controller/lifecycle.go index 3243c04b..0c05d862 100644 --- a/internal/controller/lifecycle.go +++ b/internal/controller/lifecycle.go @@ -1629,6 +1629,20 @@ func (c *Coordinator) HasClaimCustody(ctx context.Context, consumer ProjectIdent return true, nil } +// ClaimReleased reads terminal custody for the exact project and claim lifetime. +// Callers use this to avoid restoring protection after verified release; public +// status is not authority for this decision. Missing or corrupt custody fails. +func (c *Coordinator) ClaimReleased(ctx context.Context, consumer ProjectIdentity, claimUID types.UID) (bool, error) { + if !consumer.Valid() || claimUID == "" { + return false, ErrRecordInvalid + } + record, _, err := c.getCustodyScoped(ctx, ProjectClaimScope(consumer), claimUID) + if err != nil { + return false, err + } + return record.State == CustodyReleased, nil +} + func (c *Coordinator) getCustodyForAsset(ctx context.Context, asset *AssetRecord) (*ClaimCustodyRecord, *corev1.Secret, error) { return c.getCustodyScoped(ctx, asset.ClaimScope, asset.ClaimUID) } diff --git a/internal/coordination/mapping.go b/internal/coordination/mapping.go new file mode 100644 index 00000000..55cefb39 --- /dev/null +++ b/internal/coordination/mapping.go @@ -0,0 +1,71 @@ +package coordination + +import ( + "context" + + "go.datum.net/fleet/internal/executor" + "go.datum.net/fleet/internal/simulator" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/client-go/dynamic" +) + +// LocalAssetMapping is an explicit local-test binding of one project-scoped +// Device to the disposable provider's fixed physical ID. No alias or suffix +// matching is allowed. The exact original request remains durable in the local +// handoff and the backend retains its exact translated request before effects. +// This is a synthetic hardware enrollment seam, not production authority. +type LocalAssetMapping struct { + API dynamic.Interface + Namespace, Cell, ScopedAsset, PhysicalAsset string + Backend executor.Client +} + +func (m *LocalAssetMapping) request(ctx context.Context, id string) (Intent, simulator.Request, error) { + obj, err := m.API.Resource(Resource).Namespace(m.Namespace).Get(ctx, Name(id), metav1.GetOptions{}) + if err != nil { + return Intent{}, simulator.Request{}, err + } + i, _, err := decode(obj) + if err != nil { + return i, simulator.Request{}, err + } + if i.Cell != m.Cell || i.Request.ID != id || m.ScopedAsset == "" || m.PhysicalAsset == "" || i.Request.AssetID != m.ScopedAsset { + return i, simulator.Request{}, executor.ErrFenced + } + translated := i.Request + translated.AssetID = m.PhysicalAsset + return i, translated, nil +} +func (m *LocalAssetMapping) translate(i Intent, translated simulator.Request, r simulator.OperationResult) (simulator.OperationResult, error) { + if err := ValidateResult(Intent{Cell: i.Cell, Request: translated}, r); err != nil { + return simulator.OperationResult{}, err + } + r.InputDigest, _ = simulator.RequestDigest(i.Request) + return r, nil +} +func (m *LocalAssetMapping) Execute(ctx context.Context, r simulator.Request) (simulator.OperationResult, error) { + i, t, err := m.request(ctx, r.ID) + if err != nil { + return simulator.OperationResult{}, err + } + if Digest(Intent{Cell: i.Cell, Request: r}) != Digest(i) { + return simulator.OperationResult{}, executor.ErrConflict + } + result, err := m.Backend.Execute(ctx, t) + if err != nil { + return simulator.OperationResult{}, err + } + return m.translate(i, t, result) +} +func (m *LocalAssetMapping) Lookup(ctx context.Context, id string) (simulator.OperationResult, bool, error) { + i, t, err := m.request(ctx, id) + if err != nil { + return simulator.OperationResult{}, false, err + } + r, found, err := m.Backend.Lookup(ctx, id) + if err != nil || !found { + return r, found, err + } + result, err := m.translate(i, t, r) + return result, true, err +} diff --git a/internal/coordination/mapping_test.go b/internal/coordination/mapping_test.go new file mode 100644 index 00000000..d1fbfd4e --- /dev/null +++ b/internal/coordination/mapping_test.go @@ -0,0 +1,41 @@ +package coordination + +import ( + "context" + "errors" + "go.datum.net/fleet/internal/executor" + "go.datum.net/fleet/internal/simulator" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/client-go/dynamic/fake" + "testing" +) + +func TestLocalMappingRequiresExactAssetAndRecoversDigest(t *testing.T) { + i, s, _ := fixture() + api := fake.NewSimpleDynamicClient(runtime.NewScheme(), object("private", i)) + translated := i.Request + translated.AssetID = "local-physical-device" + digest, _ := simulator.RequestDigest(translated) + result := s.Reflected[0].Observation.Result + result.InputDigest = digest + backend := &effect{result: result} + mapping := LocalAssetMapping{API: api, Namespace: "private", Cell: i.Cell, ScopedAsset: i.Request.AssetID, PhysicalAsset: translated.AssetID, Backend: backend} + original, err := mapping.Execute(context.Background(), i.Request) + if err != nil { + t.Fatal(err) + } + if original.InputDigest != s.Reflected[0].Observation.Result.InputDigest { + t.Fatal("lost original digest") + } + recovered, found, err := mapping.Lookup(context.Background(), i.Request.ID) + if err != nil || !found || recovered.InputDigest != original.InputDigest { + t.Fatal("restart lost exact mapping", err) + } + mapping.ScopedAsset = "another-project/same-device" + if _, err := mapping.Execute(context.Background(), i.Request); !errors.Is(err, executor.ErrFenced) { + t.Fatal("accepted alias", err) + } + if backend.calls != 1 { + t.Fatal("duplicate execution") + } +} diff --git a/internal/coordination/recovery_adversarial_test.go b/internal/coordination/recovery_adversarial_test.go new file mode 100644 index 00000000..a23e92e8 --- /dev/null +++ b/internal/coordination/recovery_adversarial_test.go @@ -0,0 +1,159 @@ +package coordination + +import ( + "context" + "errors" + "testing" + "time" + + "go.datum.net/fleet/internal/executor" + "go.datum.net/fleet/internal/simulator" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/client-go/dynamic/fake" +) + +// journaled models a provider that retains each operation before effects: +// Lookup of an unfinished operation is Unknown, and Execute of a retained ID +// resumes it (digest-checked) rather than starting another effect. +type journaled struct { + retained map[string]simulator.Request + done map[string]simulator.OperationResult + lookupErr error + starts int + resumes []simulator.Request + finish simulator.OperationResult + complete bool +} + +func (j *journaled) Lookup(_ context.Context, id string) (simulator.OperationResult, bool, error) { + if j.lookupErr != nil { + return simulator.OperationResult{}, false, j.lookupErr + } + if r, ok := j.done[id]; ok { + return r, true, nil + } + if _, ok := j.retained[id]; ok { + return simulator.OperationResult{}, false, executor.ErrOutcomeUnknown + } + return simulator.OperationResult{}, false, nil +} +func (j *journaled) Execute(_ context.Context, r simulator.Request) (simulator.OperationResult, error) { + if old, ok := j.retained[r.ID]; ok { + a, _ := simulator.RequestDigest(old) + b, _ := simulator.RequestDigest(r) + if a != b { + return simulator.OperationResult{}, executor.ErrConflict + } + j.resumes = append(j.resumes, r) + } else { + j.retained[r.ID] = r + j.starts++ + } + if !j.complete { + return simulator.OperationResult{}, executor.ErrOutcomeUnknown + } + j.done[r.ID] = j.finish + return j.finish, nil +} + +func observed(t *testing.T, obj *unstructured.Unstructured) bool { + t.Helper() + _, found, err := unstructured.NestedMap(obj.Object, "status", "observation") + if err != nil { + t.Fatal(err) + } + return found +} + +func TestAdversarialCellRestartResumesUnfinishedOperationOnce(t *testing.T) { + ctx := context.Background() + i, s, now := fixture() + api := fake.NewSimpleDynamicClient(runtime.NewScheme(), object("private", i)) + provider := &journaled{retained: map[string]simulator.Request{}, done: map[string]simulator.OperationResult{}, finish: s.Reflected[0].Observation.Result} + name := Name(i.Request.ID) + newCell := func() *Cell { + return &Cell{API: api, Namespace: "private", Name: i.Cell, Executor: provider, Now: func() time.Time { return now }} + } + // First delivery starts the operation; its outcome is lost. + if err := reconcile(newCell(), ctx, name); !errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatalf("lost outcome must stay unknown: %v", err) + } + // A restarted cell sees Lookup Unknown and resumes; still unfinished. + if err := reconcile(newCell(), ctx, name); !errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatalf("unfinished operation must stay unknown: %v", err) + } + obj, err := api.Resource(Resource).Namespace("private").Get(ctx, name, metav1.GetOptions{}) + if err != nil { + t.Fatal(err) + } + if observed(t, obj) { + t.Fatal("unknown outcome was published as an observation") + } + provider.complete = true + if err := reconcile(newCell(), ctx, name); err != nil { + t.Fatalf("restart did not recover the retained operation: %v", err) + } + if err := reconcile(newCell(), ctx, name); err != nil { + t.Fatal(err) + } + if provider.starts != 1 || len(provider.resumes) != 2 { + t.Fatalf("want one start and two exact resumes, got %d starts %d resumes", provider.starts, len(provider.resumes)) + } + for _, r := range provider.resumes { + if Digest(Intent{Cell: i.Cell, Request: r}) != Digest(i) { + t.Fatal("resume did not re-deliver the exact retained request") + } + } + obj, err = api.Resource(Resource).Namespace("private").Get(ctx, name, metav1.GetOptions{}) + if err != nil { + t.Fatal(err) + } + if !observed(t, obj) { + t.Fatal("terminal observation missing after recovery") + } +} + +func TestAdversarialCellLookupFailuresNeverExecute(t *testing.T) { + for name, lookupErr := range map[string]error{ + "conflict": executor.ErrConflict, + "fenced": executor.ErrFenced, + "transport": errors.New("journal unreadable"), + } { + t.Run(name, func(t *testing.T) { + i, s, now := fixture() + api := fake.NewSimpleDynamicClient(runtime.NewScheme(), object("private", i)) + provider := &journaled{retained: map[string]simulator.Request{}, done: map[string]simulator.OperationResult{}, finish: s.Reflected[0].Observation.Result, complete: true, lookupErr: lookupErr} + c := &Cell{API: api, Namespace: "private", Name: i.Cell, Executor: provider, Now: func() time.Time { return now }} + if err := reconcile(c, context.Background(), Name(i.Request.ID)); !errors.Is(err, lookupErr) { + t.Fatalf("lookup failure not reported: %v", err) + } + if provider.starts != 0 || len(provider.resumes) != 0 { + t.Fatal("lookup failure led to an effect") + } + }) + } +} + +// foundUnknown reports a retained but unverifiable terminal record. Resuming +// would only replay the same bytes, so the cell must report it, not execute. +type foundUnknown struct{ calls int } + +func (f *foundUnknown) Lookup(context.Context, string) (simulator.OperationResult, bool, error) { + return simulator.OperationResult{}, true, executor.ErrOutcomeUnknown +} +func (f *foundUnknown) Execute(context.Context, simulator.Request) (simulator.OperationResult, error) { + f.calls++ + return simulator.OperationResult{}, nil +} + +func TestAdversarialCellFoundUnknownIsNotSuccess(t *testing.T) { + i, _, now := fixture() + api := fake.NewSimpleDynamicClient(runtime.NewScheme(), object("private", i)) + e := &foundUnknown{} + c := &Cell{API: api, Namespace: "private", Name: i.Cell, Executor: e, Now: func() time.Time { return now }} + if err := reconcile(c, context.Background(), Name(i.Request.ID)); !errors.Is(err, executor.ErrOutcomeUnknown) || e.calls != 0 { + t.Fatalf("found-unknown result: %v, executes %d", err, e.calls) + } +} diff --git a/internal/coordination/run.go b/internal/coordination/run.go new file mode 100644 index 00000000..c32ea32b --- /dev/null +++ b/internal/coordination/run.go @@ -0,0 +1,40 @@ +package coordination + +import ( + "context" + "errors" + "time" + + "go.datum.net/fleet/internal/executor" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +// CellLabel selects the handoffs delivered for one cell. +const CellLabel = "coordination.fleet.datumapis.com/cell" + +// Observe refreshes journal-derived observations for this cell's delivered +// handoffs on a fixed interval. Execution, retry and replacement belong to the +// Kubernetes Job controller and KRO; this loop only republishes terminal +// results so management can check freshness. A pending or invalid handoff is +// reported to onError, which must not log handoff contents. +func (c *Cell) Observe(ctx context.Context, interval time.Duration, onError func(string, error)) error { + for { + list, err := c.API.Resource(Resource).Namespace(c.Namespace).List(ctx, metav1.ListOptions{LabelSelector: CellLabel + "=" + c.Name}) + if err != nil { + onError("", err) + } else { + for _, obj := range list.Items { + if err := c.Publish(ctx, obj.GetName()); err != nil && !errors.Is(err, executor.ErrOutcomeUnknown) { + onError(obj.GetName(), err) + } + } + } + t := time.NewTimer(interval) + select { + case <-ctx.Done(): + t.Stop() + return ctx.Err() + case <-t.C: + } + } +} diff --git a/internal/coordination/site_test.go b/internal/coordination/site_test.go new file mode 100644 index 00000000..6019a468 --- /dev/null +++ b/internal/coordination/site_test.go @@ -0,0 +1,127 @@ +package coordination + +import ( + "context" + "errors" + "testing" + "time" + + "go.datum.net/fleet/internal/executor" + "go.datum.net/fleet/internal/simulator" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/client-go/dynamic/fake" +) + +// reconcile composes the two site roles: the worker Job executes, then the +// observer publishes from the provider journal. +func reconcile(c *Cell, ctx context.Context, name string) error { + if err := c.Execute(ctx, name); err != nil { + return err + } + return c.Publish(ctx, name) +} + +func TestWorkerExecuteNeverWritesStatus(t *testing.T) { + i, s, now := fixture() + api := fake.NewSimpleDynamicClient(runtime.NewScheme(), object("private", i)) + e := &effect{result: s.Reflected[0].Observation.Result} + c := &Cell{API: api, Namespace: "private", Name: i.Cell, Executor: e, Now: func() time.Time { return now }} + if err := c.Execute(context.Background(), Name(i.Request.ID)); err != nil || e.calls != 1 { + t.Fatalf("execute: %v calls %d", err, e.calls) + } + for _, a := range api.Actions() { + if a.GetVerb() != "get" { + t.Fatalf("worker used %s on %s", a.GetVerb(), a.GetSubresource()) + } + } +} + +func TestObserverPublishNeverExecutes(t *testing.T) { + ctx := context.Background() + i, s, now := fixture() + api := fake.NewSimpleDynamicClient(runtime.NewScheme(), object("private", i)) + provider := &journaled{retained: map[string]simulator.Request{i.Request.ID: i.Request}, done: map[string]simulator.OperationResult{}} + c := &Cell{API: api, Namespace: "private", Name: i.Cell, Executor: provider, Now: func() time.Time { return now }} + if err := c.Publish(ctx, Name(i.Request.ID)); !errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatalf("unfinished journal must stay unknown: %v", err) + } + empty := &journaled{retained: map[string]simulator.Request{}, done: map[string]simulator.OperationResult{}} + c.Executor = empty + if err := c.Publish(ctx, Name(i.Request.ID)); !errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatalf("absent journal record must stay unknown: %v", err) + } + if provider.starts+len(provider.resumes)+empty.starts+len(empty.resumes) != 0 { + t.Fatal("observer executed an effect") + } + obj, _ := api.Resource(Resource).Namespace("private").Get(ctx, Name(i.Request.ID), metav1.GetOptions{}) + if observed(t, obj) { + t.Fatal("unknown outcome published") + } + // A terminal but mismatched journal result is not published either. + wrong := s.Reflected[0].Observation.Result + wrong.InputDigest = "0" + c.Executor = &journaled{retained: map[string]simulator.Request{}, done: map[string]simulator.OperationResult{i.Request.ID: wrong}} + if err := c.Publish(ctx, Name(i.Request.ID)); !errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatalf("mismatched terminal result accepted: %v", err) + } + c.Executor = &journaled{retained: map[string]simulator.Request{}, done: map[string]simulator.OperationResult{i.Request.ID: s.Reflected[0].Observation.Result}} + if err := c.Publish(ctx, Name(i.Request.ID)); err != nil { + t.Fatal(err) + } + obj, _ = api.Resource(Resource).Namespace("private").Get(ctx, Name(i.Request.ID), metav1.GetOptions{}) + if !observed(t, obj) { + t.Fatal("terminal journal result was not published") + } +} + +// A re-delivered copy under another name, a wrong-cell intent, or an invalid +// intent never reaches the executor. +func TestDeliveryFaultsFenceBeforeEffects(t *testing.T) { + i, s, now := fixture() + duplicate := object("private", i) + duplicate.SetName("copy-of-" + Name(i.Request.ID)) + wrongCell := i + wrongCell.Cell = "other-cell" + wrongObj := object("private", wrongCell) + wrongObj.SetLabels(map[string]string{CellLabel: i.Cell}) + invalid := object("private", i) + invalid.SetName("op-invalid") + _ = unstructured.SetNestedField(invalid.Object, "{", "spec", "requestJSON") + api := fake.NewSimpleDynamicClient(runtime.NewScheme(), duplicate, invalid) + _, _ = api.Resource(Resource).Namespace("private").Create(context.Background(), wrongObj, metav1.CreateOptions{}) + for name, want := range map[string]error{duplicate.GetName(): executor.ErrFenced, Name(i.Request.ID): executor.ErrFenced, "op-invalid": executor.ErrInvalid} { + e := &effect{result: s.Reflected[0].Observation.Result} + c := &Cell{API: api, Namespace: "private", Name: i.Cell, Executor: e, Now: func() time.Time { return now }} + if err := c.Execute(context.Background(), name); !errors.Is(err, want) || e.calls != 0 { + t.Fatalf("%s: %v calls %d", name, err, e.calls) + } + if err := c.Publish(context.Background(), name); !errors.Is(err, want) { + t.Fatalf("%s publish: %v", name, err) + } + } +} + +func TestObserveListsOnlyThisCell(t *testing.T) { + i, s, now := fixture() + other := i + other.Cell = "other-cell" + other.Request.ID = "other-op" + api := fake.NewSimpleDynamicClientWithCustomListKinds(runtime.NewScheme(), map[schema.GroupVersionResource]string{Resource: Kind + "List"}, object("private", i), object("private", other)) + done := map[string]simulator.OperationResult{i.Request.ID: s.Reflected[0].Observation.Result} + c := &Cell{API: api, Namespace: "private", Name: i.Cell, Executor: &journaled{retained: map[string]simulator.Request{}, done: done}, Now: func() time.Time { return now }} + ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) + defer cancel() + var errs []error + _ = c.Observe(ctx, time.Hour, func(_ string, err error) { errs = append(errs, err) }) + if len(errs) != 0 { + t.Fatalf("unexpected observer errors: %v", errs) + } + mine, _ := api.Resource(Resource).Namespace("private").Get(context.Background(), Name(i.Request.ID), metav1.GetOptions{}) + theirs, _ := api.Resource(Resource).Namespace("private").Get(context.Background(), Name(other.Request.ID), metav1.GetOptions{}) + if !observed(t, mine) || observed(t, theirs) { + t.Fatal("observer published outside its cell selector") + } +} diff --git a/internal/coordination/transport.go b/internal/coordination/transport.go new file mode 100644 index 00000000..f3b836b5 --- /dev/null +++ b/internal/coordination/transport.go @@ -0,0 +1,301 @@ +// Package coordination implements the experimental management -> Karmada -> +// cell executor transport. It is not a production admission authority. +package coordination + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + + "time" + + "go.datum.net/fleet/internal/executor" + "go.datum.net/fleet/internal/simulator" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/client-go/dynamic" +) + +var Resource = schema.GroupVersionResource{Group: "coordination.fleet.datumapis.com", Version: "v1alpha1", Resource: "machineallocationhandoffs"} + +const Kind = "MachineAllocationHandoff" + +// Intent is immutable. Request retains the allocator's exact operation, asset, +// allocation, epoch, fence and inputs before federation may deliver any effect. +type Intent struct { + Cell string `json:"cell"` + Request simulator.Request `json:"-"` +} + +// Encode exact request bytes as a string so an API server cannot reorder opaque +// input object fields and silently change the executor's retained digest. +func (i Intent) MarshalJSON() ([]byte, error) { + b, err := json.Marshal(i.Request) + if err != nil { + return nil, err + } + return json.Marshal(struct { + Cell string `json:"cell"` + RequestJSON string `json:"requestJSON"` + }{i.Cell, string(b)}) +} +func (i *Intent) UnmarshalJSON(b []byte) error { + var wire struct { + Cell string `json:"cell"` + RequestJSON string `json:"requestJSON"` + } + if err := json.Unmarshal(b, &wire); err != nil { + return err + } + i.Cell = wire.Cell + return json.Unmarshal([]byte(wire.RequestJSON), &i.Request) +} + +type Observation struct { + Cell string `json:"cell"` + IntentDigest string `json:"intentDigest"` + ObservedAt time.Time `json:"observedAt"` + Result simulator.OperationResult `json:"result"` +} +type Reflected struct { + ClusterName string `json:"clusterName"` + Observation Observation `json:"observation"` +} +type Status struct { + Observation *Observation `json:"observation,omitempty"` + Reflected []Reflected `json:"reflected,omitempty"` +} + +func Name(id string) string { + sum := sha256.Sum256([]byte(id)) + return "op-" + hex.EncodeToString(sum[:])[:40] +} +func Digest(i Intent) string { + b, _ := json.Marshal(i) + sum := sha256.Sum256(b) + return hex.EncodeToString(sum[:]) +} +func (i Intent) Validate() error { + r := i.Request + if i.Cell == "" || r.ID == "" || r.AssetID == "" || r.BindingID == "" || r.Epoch < 1 || r.FenceToken == "" { + return errors.New("incomplete retained execution authority") + } + switch r.Kind { + case "install", "cleanup", "power": + default: + return errors.New("unsupported operation kind") + } + _, err := simulator.RequestDigest(r) + return err +} +func decode(obj *unstructured.Unstructured) (Intent, Status, error) { + var i Intent + var s Status + b, err := json.Marshal(obj.Object["spec"]) + if err != nil { + return i, s, err + } + if err = json.Unmarshal(b, &i); err != nil { + return i, s, err + } + b, err = json.Marshal(obj.Object["status"]) + if err != nil { + return i, s, err + } + if err = json.Unmarshal(b, &s); err != nil { + return i, s, err + } + return i, s, i.Validate() +} +func object(ns string, i Intent) *unstructured.Unstructured { + b, _ := json.Marshal(i) + var spec map[string]interface{} + _ = json.Unmarshal(b, &spec) + return &unstructured.Unstructured{Object: map[string]interface{}{"apiVersion": Resource.GroupVersion().String(), "kind": Kind, "metadata": map[string]interface{}{"name": Name(i.Request.ID), "namespace": ns, "labels": map[string]interface{}{CellLabel: i.Cell}}, "spec": spec}} +} + +// ValidateResult never interprets an incomplete/uncertain result as success. +func ValidateResult(i Intent, r simulator.OperationResult) error { + d, err := simulator.RequestDigest(i.Request) + if err != nil || r.ID != i.Request.ID || r.Kind != i.Request.Kind || r.InputDigest != d || r.Phase != "Succeeded" || r.CompletedAt == nil || r.CreatedAt.IsZero() || r.CompletedAt.Before(r.CreatedAt) { + return executor.ErrOutcomeUnknown + } + switch r.Kind { + case "install": + if r.Result != "installed" { + return executor.ErrOutcomeUnknown + } + case "cleanup": + if r.Result != "clean" { + return executor.ErrOutcomeUnknown + } + } + return nil +} +func ValidateReflection(i Intent, s Status, now time.Time, maxAge time.Duration) (simulator.OperationResult, error) { + // ClusterName is supplied by Karmada's status aggregator, independently of + // the cell-reported identity. Never take the first of conflicting replicas. + if i.Validate() != nil || maxAge <= 0 || len(s.Reflected) != 1 { + return simulator.OperationResult{}, executor.ErrOutcomeUnknown + } + r := s.Reflected[0] + o := r.Observation + if r.ClusterName != i.Cell || o.Cell != i.Cell || o.IntentDigest != Digest(i) || o.ObservedAt.IsZero() || o.ObservedAt.After(now) || now.Sub(o.ObservedAt) > maxAge { + return simulator.OperationResult{}, executor.ErrOutcomeUnknown + } + if err := ValidateResult(i, o.Result); err != nil { + return simulator.OperationResult{}, err + } + if o.Result.CompletedAt.After(o.ObservedAt) { + return simulator.OperationResult{}, executor.ErrOutcomeUnknown + } + return o.Result, nil +} + +// Hub implements executor.Client. Only management holds this client. It writes +// immutable intent, reads federation-owned status, and never writes hub status. +// The caller must have retained lifecycle authority before Execute. +type Hub struct { + API dynamic.Interface + Namespace, Cell string + MaxAge time.Duration + Now func() time.Time +} + +func (h *Hub) now() time.Time { + if h.Now != nil { + return h.Now().UTC() + } + return time.Now().UTC() +} +func (h *Hub) Execute(ctx context.Context, r simulator.Request) (simulator.OperationResult, error) { + if h.API == nil || h.Namespace == "" { + return simulator.OperationResult{}, executor.ErrOutcomeUnknown + } + i := Intent{Cell: h.Cell, Request: r} + if err := i.Validate(); err != nil { + return simulator.OperationResult{}, err + } + api := h.API.Resource(Resource).Namespace(h.Namespace) + obj, err := api.Create(ctx, object(h.Namespace, i), metav1.CreateOptions{}) + if apierrors.IsAlreadyExists(err) { + obj, err = api.Get(ctx, Name(r.ID), metav1.GetOptions{}) + } + if err != nil { + return simulator.OperationResult{}, fmt.Errorf("%w: handoff persistence unavailable", executor.ErrOutcomeUnknown) + } + retained, status, err := decode(obj) + if err != nil || Digest(retained) != Digest(i) { + return simulator.OperationResult{}, executor.ErrConflict + } + return ValidateReflection(retained, status, h.now(), h.MaxAge) +} +func (h *Hub) Lookup(ctx context.Context, id string) (simulator.OperationResult, bool, error) { + if h.API == nil || h.Namespace == "" || id == "" { + return simulator.OperationResult{}, false, executor.ErrOutcomeUnknown + } + obj, err := h.API.Resource(Resource).Namespace(h.Namespace).Get(ctx, Name(id), metav1.GetOptions{}) + if apierrors.IsNotFound(err) { + return simulator.OperationResult{}, false, nil + } + if err != nil { + return simulator.OperationResult{}, false, err + } + i, s, err := decode(obj) + if err != nil || i.Request.ID != id || i.Cell != h.Cell { + return simulator.OperationResult{}, true, executor.ErrConflict + } + r, err := ValidateReflection(i, s, h.now(), h.MaxAge) + return r, true, err +} + +// Cell is the selected location's view of delivered intent. Site execution is +// split by least privilege: a per-operation worker Job calls Execute and holds +// only read access to its one handoff; the site observer calls Publish and is +// the only writer of handoff status. Publish derives every observation from +// the provider journal, never from Job, Pod or KRO status. +type Cell struct { + API dynamic.Interface + Namespace, Name string + Executor executor.Client + Now func() time.Time +} + +// intent reads and validates one delivered handoff for this cell. +func (c *Cell) intent(ctx context.Context, name string) (*unstructured.Unstructured, Intent, error) { + if c.API == nil || c.Executor == nil || c.Namespace == "" || c.Name == "" { + return nil, Intent{}, executor.ErrOutcomeUnknown + } + obj, err := c.API.Resource(Resource).Namespace(c.Namespace).Get(ctx, name, metav1.GetOptions{}) + if err != nil { + return nil, Intent{}, err + } + i, _, err := decode(obj) + if err != nil { + return nil, Intent{}, fmt.Errorf("%w: invalid delivered intent", executor.ErrInvalid) + } + if i.Cell != c.Name || name != Name(i.Request.ID) || obj.GetDeletionTimestamp() != nil { + return nil, Intent{}, executor.ErrFenced + } + return obj, i, nil +} + +// Execute runs or resumes exactly the delivered operation and returns nil only +// for a validated terminal provider result. It never writes status. +// +// Lookup Unknown means the provider retained this exact operation but has not +// reached a terminal result. Resuming re-delivers the identical retained +// request under the same operation ID, which the executor contract replays +// against its own journal (digest-checked, never a new operation). Conflict, +// fencing and transport errors stop before any effect. +func (c *Cell) Execute(ctx context.Context, name string) error { + _, i, err := c.intent(ctx, name) + if err != nil { + return err + } + r, found, err := c.Executor.Lookup(ctx, i.Request.ID) + if err != nil && (found || !errors.Is(err, executor.ErrOutcomeUnknown)) { + return err + } + if !found { + if r, err = c.Executor.Execute(ctx, i.Request); err != nil { + return err + } + } + return ValidateResult(i, r) +} + +// Publish writes a fresh observation only for a validated terminal journal +// result. It never executes; absent or unfinished results stay Unknown. +func (c *Cell) Publish(ctx context.Context, name string) error { + obj, i, err := c.intent(ctx, name) + if err != nil { + return err + } + r, found, err := c.Executor.Lookup(ctx, i.Request.ID) + if err != nil { + return err + } + if !found { + return executor.ErrOutcomeUnknown + } + if err = ValidateResult(i, r); err != nil { + return err + } + now := time.Now().UTC() + if c.Now != nil { + now = c.Now().UTC() + } + o := Observation{Cell: c.Name, IntentDigest: Digest(i), ObservedAt: now, Result: r} + b, _ := json.Marshal(Status{Observation: &o}) + var status map[string]interface{} + _ = json.Unmarshal(b, &status) + obj.Object["status"] = status + _, err = c.API.Resource(Resource).Namespace(c.Namespace).UpdateStatus(ctx, obj, metav1.UpdateOptions{}) + return err +} diff --git a/internal/coordination/transport_test.go b/internal/coordination/transport_test.go new file mode 100644 index 00000000..c9be4716 --- /dev/null +++ b/internal/coordination/transport_test.go @@ -0,0 +1,115 @@ +package coordination + +import ( + "context" + "errors" + "testing" + "time" + + "go.datum.net/fleet/internal/executor" + "go.datum.net/fleet/internal/simulator" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/client-go/dynamic/fake" +) + +func fixture() (Intent, Status, time.Time) { + now := time.Date(2026, 11, 14, 12, 0, 0, 0, time.UTC) + i := Intent{Cell: "cell-a", Request: simulator.Request{ID: "op", Kind: "cleanup", AssetID: "device", BindingID: "allocation", Epoch: 2, FenceToken: "synthetic-test-fence"}} + digest, _ := simulator.RequestDigest(i.Request) + r := simulator.OperationResult{ID: "op", Kind: "cleanup", InputDigest: digest, Phase: "Succeeded", Result: "clean", CreatedAt: now.Add(-time.Second), CompletedAt: &now} + return i, Status{Reflected: []Reflected{{ClusterName: i.Cell, Observation: Observation{Cell: i.Cell, IntentDigest: Digest(i), ObservedAt: now, Result: r}}}}, now +} +func TestReflectionRejectsUncertainAndConflictingResults(t *testing.T) { + cases := map[string]func(*Intent, *Status, time.Time){ + "wrong federation cell": func(_ *Intent, s *Status, _ time.Time) { s.Reflected[0].ClusterName = "cell-b" }, + "wrong reported cell": func(_ *Intent, s *Status, _ time.Time) { s.Reflected[0].Observation.Cell = "cell-b" }, + "stale": func(_ *Intent, s *Status, n time.Time) { s.Reflected[0].Observation.ObservedAt = n.Add(-time.Hour) }, + "future": func(_ *Intent, s *Status, n time.Time) { s.Reflected[0].Observation.ObservedAt = n.Add(time.Second) }, + "wrong epoch": func(i *Intent, _ *Status, _ time.Time) { i.Request.Epoch++ }, + "wrong allocation": func(i *Intent, _ *Status, _ time.Time) { i.Request.BindingID = "other" }, + "wrong fence": func(i *Intent, _ *Status, _ time.Time) { i.Request.FenceToken = "other" }, + "wrong inputs": func(_ *Intent, s *Status, _ time.Time) { s.Reflected[0].Observation.Result.InputDigest = "other" }, + "wrong operation": func(_ *Intent, s *Status, _ time.Time) { s.Reflected[0].Observation.Result.ID = "other" }, + "unknown": func(_ *Intent, s *Status, _ time.Time) { s.Reflected[0].Observation.Result.Phase = "Unknown" }, + "unclean": func(_ *Intent, s *Status, _ time.Time) { s.Reflected[0].Observation.Result.Result = "unknown" }, + "duplicate": func(_ *Intent, s *Status, _ time.Time) { s.Reflected = append(s.Reflected, s.Reflected[0]) }, + "missing": func(_ *Intent, s *Status, _ time.Time) { s.Reflected = nil }, + } + for name, change := range cases { + t.Run(name, func(t *testing.T) { + i, s, n := fixture() + change(&i, &s, n) + if _, err := ValidateReflection(i, s, n, time.Minute); !errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatalf("accepted invalid reflection: %v", err) + } + }) + } + i, s, n := fixture() + if _, err := ValidateReflection(i, s, n, time.Minute); err != nil { + t.Fatal(err) + } +} + +type effect struct { + result simulator.OperationResult + calls int + fail bool +} + +func (e *effect) Lookup(context.Context, string) (simulator.OperationResult, bool, error) { + return e.result, e.calls > 0, nil +} +func (e *effect) Execute(_ context.Context, r simulator.Request) (simulator.OperationResult, error) { + e.calls++ + if e.fail { + return simulator.OperationResult{}, executor.ErrOutcomeUnknown + } + return e.result, nil +} +func TestHubCellRestartAndNoFakeFederation(t *testing.T) { + ctx := context.Background() + i, s, now := fixture() + hubAPI := fake.NewSimpleDynamicClientWithCustomListKinds(runtime.NewScheme(), map[schema.GroupVersionResource]string{Resource: Kind + "List"}) + cellAPI := fake.NewSimpleDynamicClientWithCustomListKinds(runtime.NewScheme(), map[schema.GroupVersionResource]string{Resource: Kind + "List"}) + h := &Hub{API: hubAPI, Namespace: "private", Cell: i.Cell, MaxAge: time.Minute, Now: func() time.Time { return now }} + if _, err := h.Execute(ctx, i.Request); !errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatal(err) + } + obj, err := hubAPI.Resource(Resource).Namespace("private").Get(ctx, Name(i.Request.ID), metav1.GetOptions{}) + if err != nil { + t.Fatal(err) + } + if _, err = cellAPI.Resource(Resource).Namespace("private").Create(ctx, obj, metav1.CreateOptions{}); err != nil { + t.Fatal(err) + } + e := &effect{result: s.Reflected[0].Observation.Result} + for range 2 { + c := &Cell{API: cellAPI, Namespace: "private", Name: i.Cell, Executor: e, Now: func() time.Time { return now }} + if err = reconcile(c, ctx, obj.GetName()); err != nil { + t.Fatal(err) + } + } + if e.calls != 1 { + t.Fatalf("duplicate effects: %d", e.calls) + } + // This unit test deliberately does not simulate federation or claim its success. + if _, _, err = h.Lookup(ctx, i.Request.ID); !errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatalf("cell-local success leaked to hub: %v", err) + } + changed := i.Request + changed.Epoch++ + if _, err = h.Execute(ctx, changed); !errors.Is(err, executor.ErrConflict) { + t.Fatalf("accepted changed authority: %v", err) + } +} +func TestCellRejectsWrongCellBeforeEffects(t *testing.T) { + i, s, n := fixture() + api := fake.NewSimpleDynamicClient(runtime.NewScheme(), object("private", i)) + e := &effect{result: s.Reflected[0].Observation.Result} + c := Cell{API: api, Namespace: "private", Name: "wrong", Executor: e, Now: func() time.Time { return n }} + if err := reconcile(&c, context.Background(), Name(i.Request.ID)); !errors.Is(err, executor.ErrFenced) || e.calls != 0 { + t.Fatalf("wrong-cell effect: %v, calls %d", err, e.calls) + } +} diff --git a/internal/localvm/multiplane_recovery_adversarial_test.go b/internal/localvm/multiplane_recovery_adversarial_test.go new file mode 100644 index 00000000..751bfd3f --- /dev/null +++ b/internal/localvm/multiplane_recovery_adversarial_test.go @@ -0,0 +1,139 @@ +package localvm + +import ( + "context" + "encoding/json" + "errors" + "os" + "testing" + "time" + + "go.datum.net/fleet/internal/coordination" + "go.datum.net/fleet/internal/executor" + "go.datum.net/fleet/internal/simulator" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/client-go/dynamic/fake" +) + +func TestAdversarialCellResumesRetainedInstallerWithoutSecondStart(t *testing.T) { + ctx := context.Background() + fixture := newVMFixture(t) + fixture.failStart = true + request := vmRequest("cell-recovery") + intent := coordination.Intent{Cell: "cell-a", Request: request} + name := coordination.Name(request.ID) + api := fake.NewSimpleDynamicClient(runtime.NewScheme(), handoff(t, intent)) + mapping := &coordination.LocalAssetMapping{API: api, Namespace: "private", Cell: "cell-a", ScopedAsset: request.AssetID, PhysicalAsset: AssetID, Backend: fixture.p} + cell := coordination.Cell{API: api, Namespace: "private", Name: "cell-a", Executor: mapping} + if err := reconcile(&cell, ctx, name); !errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatalf("lost installer response must remain unknown: %v", err) + } + journal, err := fixture.p.read() + if err != nil { + t.Fatal(err) + } + retained := journal.Operations[request.ID] + if retained.Stage != "installer-started" || len(fixture.creates) != 1 { + t.Fatal("did not retain exactly one uncertain installer start") + } + if err := os.WriteFile(fixture.p.directory(retained)+"/installer.log", []byte("FLEET-INSTALLED:"+retained.Receipt+"\n"), 0600); err != nil { + t.Fatal(err) + } + fixture.failStart = false + restarted := coordination.Cell{API: api, Namespace: "private", Name: "cell-a", Executor: mapping} + if err := reconcile(&restarted, ctx, name); err != nil { + t.Fatalf("cell cannot resume exact retained request after installer completion: %v", err) + } + if len(fixture.creates) != 2 { + t.Fatalf("want one installer and one disk boot, got %d starts", len(fixture.creates)) + } + updated, err := api.Resource(coordination.Resource).Namespace("private").Get(ctx, name, metav1.GetOptions{}) + if err != nil { + t.Fatal(err) + } + phase, _, _ := unstructured.NestedString(updated.Object, "status", "observation", "result", "phase") + if phase != "Succeeded" { + t.Fatalf("recovered terminal observation missing: %q", phase) + } +} + +func handoff(t *testing.T, intent coordination.Intent) *unstructured.Unstructured { + t.Helper() + encoded, err := json.Marshal(intent) + if err != nil { + t.Fatal(err) + } + var spec map[string]interface{} + if err := json.Unmarshal(encoded, &spec); err != nil { + t.Fatal(err) + } + return &unstructured.Unstructured{Object: map[string]interface{}{ + "apiVersion": coordination.Resource.GroupVersion().String(), + "kind": coordination.Kind, + "metadata": map[string]interface{}{"name": coordination.Name(intent.Request.ID), "namespace": "private"}, + "spec": spec, + }} +} + +// A cell restarted while the retained installer guest is still running must +// observe it, never boot a second installer, and never publish an observation. +// A different handoff for the same device must not act while it is unfinished. +func TestAdversarialCellRestartDuringRunningInstallerAndCompetingHandoff(t *testing.T) { + fixture := newVMFixture(t) + fixture.failStart = true + request := vmRequest("running-install") + cleanup := simulator.Request{ID: "competing-cleanup", Kind: "cleanup", AssetID: request.AssetID, BindingID: request.BindingID, Epoch: request.Epoch, FenceToken: request.FenceToken} + api := fake.NewSimpleDynamicClient(runtime.NewScheme(), handoff(t, coordination.Intent{Cell: "cell-a", Request: request}), handoff(t, coordination.Intent{Cell: "cell-a", Request: cleanup})) + mapping := &coordination.LocalAssetMapping{API: api, Namespace: "private", Cell: "cell-a", ScopedAsset: request.AssetID, PhysicalAsset: AssetID, Backend: fixture.p} + name := coordination.Name(request.ID) + cell := coordination.Cell{API: api, Namespace: "private", Name: "cell-a", Executor: mapping} + if err := reconcile(&cell, context.Background(), name); !errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatalf("lost start must be unknown: %v", err) + } + journal, err := fixture.p.read() + if err != nil { + t.Fatal(err) + } + fixture.present = domain(journal.Operations[request.ID]) + for range 2 { + ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) + restarted := coordination.Cell{API: api, Namespace: "private", Name: "cell-a", Executor: mapping} + err := reconcile(&restarted, ctx, name) + cancel() + if !errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatalf("running installer must remain unknown: %v", err) + } + } + if err := reconcile(&cell, context.Background(), coordination.Name(cleanup.ID)); !errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatalf("competing handoff acted during unfinished install: %v", err) + } + if len(fixture.creates) != 1 { + t.Fatalf("restart started another guest: %v", fixture.creates) + } + journal, err = fixture.p.read() + if err != nil { + t.Fatal(err) + } + if journal.Operations[cleanup.ID] != nil || journal.Operations[request.ID].Stage != "installer-started" { + t.Fatal("unfinished install was superseded") + } + for _, id := range []string{request.ID, cleanup.ID} { + obj, err := api.Resource(coordination.Resource).Namespace("private").Get(context.Background(), coordination.Name(id), metav1.GetOptions{}) + if err != nil { + t.Fatal(err) + } + if _, found, _ := unstructured.NestedMap(obj.Object, "status"); found { + t.Fatalf("unknown outcome published for %s", id) + } + } +} + +// reconcile composes the site worker (Execute) and observer (Publish) roles. +func reconcile(c *coordination.Cell, ctx context.Context, name string) error { + if err := c.Execute(ctx, name); err != nil { + return err + } + return c.Publish(ctx, name) +} diff --git a/internal/multiplane/location_adversarial_test.go b/internal/multiplane/location_adversarial_test.go new file mode 100644 index 00000000..eee7c3d6 --- /dev/null +++ b/internal/multiplane/location_adversarial_test.go @@ -0,0 +1,131 @@ +package multiplane + +import ( + "context" + "errors" + "testing" + "time" + + fleet "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/controller" + core "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/client/interceptor" +) + +func TestAdversarialRejectNonlocalMachineBeforeAllocation(t *testing.T) { + ctx := context.Background() + scheme := Scheme() + private := fake.NewClientBuilder().WithScheme(scheme).WithInterceptorFuncs(interceptor.Funcs{Create: func(ctx context.Context, api client.WithWatch, object client.Object, options ...client.CreateOption) error { + object.SetUID(types.UID("private-" + object.GetName())) + return api.Create(ctx, object, options...) + }}).Build() + coordinator, err := controller.NewCoordinator(private, PrivateNamespace, &disconnected{}, controller.LocalDigestImageResolver{}, nil, time.Hour) + if err != nil { + t.Fatal(err) + } + profile := &fleet.MachineProfile{ObjectMeta: metav1.ObjectMeta{Name: "local-profile", UID: "source-profile"}} + profile.Spec.CPU.Architecture = "amd64" + profile.Spec.CPU.Cores = 2 + profile.Spec.Memory.Capacity = "2Gi" + class := &fleet.MachineClass{ObjectMeta: metav1.ObjectMeta{Name: "local-class", UID: "source-class"}, Spec: fleet.MachineClassSpec{Capacity: &fleet.CapacityPolicy{MachineCapacities: fleet.MachineSelector{Namespace: "fleet-provider"}}}, Status: fleet.MachineClassStatus{EvaluatedRevision: "v1"}} + capacity := &fleet.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: "local-capacity", Namespace: "fleet-provider", UID: "capacity", Generation: 1}, Spec: fleet.MachineCapacitySpec{DeviceRef: fleet.LocalReference{Name: "synthetic-device-central-01"}, AllocationPolicy: "Enabled"}, Status: fleet.MachineCapacityStatus{Hardware: fleet.Hardware{CPU: fleet.HardwareCPU{Architecture: "amd64", Cores: 2}, Memory: fleet.HardwareMemory{Capacity: "2Gi"}}}} + for _, kind := range []string{"Verified", "Healthy", "Prepared", "Available"} { + capacity.Status.Conditions = append(capacity.Status.Conditions, condition(kind, metav1.ConditionTrue, 1, "Fixture")) + } + machine := &fleet.Machine{ObjectMeta: metav1.ObjectMeta{Name: "allocation", Namespace: Namespace, UID: "machine"}, Spec: fleet.MachineSpec{MachineClassRef: fleet.LocalReference{Name: "local-class"}, MachineProfileRef: fleet.LocalReference{Name: "local-profile"}, LocationRef: fleet.LocalReference{Name: "not-the-local-location"}, PowerState: "Off"}} + namespace := &core.Namespace{ObjectMeta: metav1.ObjectMeta{Name: Namespace, UID: "consumer-namespace"}} + localClass := &fleet.MachineClass{ObjectMeta: metav1.ObjectMeta{Name: "local-class", UID: "consumer-class"}, Spec: fleet.MachineClassSpec{Source: &fleet.SourceReference{Project: "provider", Name: "local-class"}}} + localProfile := profile.DeepCopyObject().(*fleet.MachineProfile) + localProfile.UID = "consumer-profile" + runner := Runner{ + Config: Config{Cell: "only-local-cell"}, Private: private, Coordinator: coordinator, + Provider: Project{API: fake.NewClientBuilder().WithScheme(scheme).WithObjects(class, profile, capacity).Build(), Identity: controller.ProjectIdentity{AuthorityID: "test", RouteName: "provider", UID: "provider-project"}}, + } + runner.Consumers[0] = Project{API: fake.NewClientBuilder().WithScheme(scheme).WithObjects(machine, namespace, localClass, localProfile).WithStatusSubresource(&fleet.Machine{}).Build(), Identity: controller.ProjectIdentity{AuthorityID: "test", RouteName: "consumer", UID: "consumer-project"}} + if _, err := runner.request(ctx, 0); !errors.Is(err, ErrLocationNotServed) { + t.Fatalf("nonlocal Machine was not rejected by location: %v", err) + } + // Rejection precedes custody, synthetic authority records and finalizers. + var secrets core.SecretList + if err := private.List(ctx, &secrets); err != nil { + t.Fatal(err) + } + if len(secrets.Items) != 0 { + t.Fatalf("wrong-location request retained %d private records", len(secrets.Items)) + } + var stored fleet.Machine + if err := runner.Consumers[0].API.Get(ctx, client.ObjectKeyFromObject(machine), &stored); err != nil { + t.Fatal(err) + } + if len(stored.Finalizers) != 0 { + t.Fatal("wrong-location request installed a lifecycle finalizer") + } + // The served location is still refused when no cell is configured. + stored.Spec.LocationRef.Name = Location + if err := runner.Consumers[0].API.Update(ctx, &stored); err != nil { + t.Fatal(err) + } + runner.Config.Cell = "" + if _, err := runner.request(ctx, 0); !errors.Is(err, ErrLocationNotServed) { + t.Fatalf("location accepted without a bound cell: %v", err) + } + runner.Config.Cell = "only-local-cell" + req, err := runner.request(ctx, 0) + if err != nil { + t.Fatalf("served location rejected: %v", err) + } + if _, err := coordinator.ReleaseScoped(ctx, req.ConsumerProject, req.Claim.UID); err != nil { + t.Fatal(err) + } + result, err := coordinator.CompleteExternalRelease(ctx, req.Claim.UID, req.Authority, req.ExternalHold, req.ConsumerProject) + if err != nil || !result.SafeToRemoveFinalizer { + t.Fatalf("release: %+v %v", result, err) + } + if err := publishRelease(ctx, runner.Consumers[0].API, req.Claim); err != nil { + t.Fatal(err) + } + if _, err := runner.request(ctx, 0); err != nil { + t.Fatal(err) + } + if err := runner.Consumers[0].API.Get(ctx, client.ObjectKeyFromObject(machine), &stored); err != nil { + t.Fatal(err) + } + if len(stored.Finalizers) != 0 { + t.Fatal("request restored finalizer after terminal custody") + } +} + +func TestAdversarialReleaseRemovesFinalizerAfterStatus(t *testing.T) { + ctx := context.Background() + m := &fleet.Machine{ObjectMeta: metav1.ObjectMeta{Name: "allocation", Namespace: Namespace, UID: "machine", Finalizers: []string{"other.example/keep", controller.MachineFinalizer}}} + m.Status.CurrentInstallationRef = &fleet.LocalReference{Name: "installed"} + install := &fleet.Installation{ObjectMeta: metav1.ObjectMeta{Name: "installed", Namespace: Namespace}, Status: fleet.InstallationStatus{Phase: "Ready", Conditions: []metav1.Condition{condition("Ready", metav1.ConditionTrue, 0, "Installed")}}} + api := fake.NewClientBuilder().WithScheme(Scheme()).WithObjects(m, install).WithStatusSubresource(&fleet.Machine{}, &fleet.Installation{}).Build() + var stored fleet.Machine + if err := api.Get(ctx, client.ObjectKeyFromObject(m), &stored); err != nil { + t.Fatal(err) + } + if err := publishRelease(ctx, api, &stored); err != nil { + t.Fatal(err) + } + if err := api.Get(ctx, client.ObjectKeyFromObject(m), &stored); err != nil { + t.Fatal(err) + } + if stored.Status.CurrentInstallationRef != nil { + t.Fatal("released machine retains current installation") + } + if err := api.Get(ctx, client.ObjectKeyFromObject(install), install); err != nil { + t.Fatal(err) + } + if meta.IsStatusConditionTrue(install.Status.Conditions, "Ready") || install.Status.Phase != "Released" { + t.Fatal("cleaned installation still ready") + } + if stored.Status.Phase != "Released" || len(stored.Finalizers) != 1 || stored.Finalizers[0] != "other.example/keep" { + t.Fatalf("release not published exactly: phase %q finalizers %v", stored.Status.Phase, stored.Finalizers) + } +} diff --git a/internal/multiplane/runner.go b/internal/multiplane/runner.go new file mode 100644 index 00000000..8f62f34f --- /dev/null +++ b/internal/multiplane/runner.go @@ -0,0 +1,488 @@ +// Package multiplane is an explicit local acceptance composition of the shared +// lifecycle, real Milo project APIs, and the Karmada executor transport. +// Admission, quota, catalog publication and hardware evidence are synthetic. +package multiplane + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "strings" + "time" + + fleet "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/controller" + "go.datum.net/fleet/internal/coordination" + "go.datum.net/fleet/internal/executor" + "go.datum.net/fleet/internal/manager" + rm "go.miloapis.com/milo/pkg/apis/resourcemanager/v1alpha1" + core "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + meta "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/types" + "k8s.io/client-go/dynamic" + "k8s.io/client-go/tools/clientcmd" + "sigs.k8s.io/controller-runtime/pkg/client" +) + +const Namespace = "default" +const PrivateNamespace = "fleet-system-private" + +// Location is the only location this acceptance composition serves. It is bound +// to exactly one Karmada member, Config.Cell, and to the one local capacity +// fixture. There is no location catalog: any other Machine locationRef is +// rejected before claim custody, authority records, finalizers, or allocation, +// so a request for elsewhere can never reserve or effect local hardware. +const Location = "local" + +var ErrLocationNotServed = errors.New("machine location is not served by the configured cell") + +type Config struct{ State, HubKubeconfig, PrivateKubeconfig, Cell, Image string } +type Project struct { + API client.Client + Identity controller.ProjectIdentity +} +type Runner struct { + Config Config + Provider Project + Consumers [2]Project + Private client.Client + Hub *coordination.Hub + Coordinator *controller.Coordinator +} + +func Scheme() *runtime.Scheme { + s := runtime.NewScheme() + _ = core.AddToScheme(s) + _ = fleet.AddToScheme(s) + _ = rm.AddToScheme(s) + return s +} +func API(path string) (client.Client, error) { + c, err := clientcmd.BuildConfigFromFlags("", path) + if err != nil { + return nil, err + } + c.Timeout = 30 * time.Second + return client.New(c, client.Options{Scheme: Scheme()}) +} +func New(ctx context.Context, c Config) (*Runner, error) { + r := &Runner{Config: c} + var err error + r.Private, err = API(c.PrivateKubeconfig) + if err != nil { + return nil, err + } + cfg, err := clientcmd.BuildConfigFromFlags("", c.HubKubeconfig) + if err != nil { + return nil, err + } + cfg.Timeout = 30 * time.Second + hub, err := dynamic.NewForConfig(cfg) + if err != nil { + return nil, err + } + r.Hub = &coordination.Hub{API: hub, Namespace: "fleet-coordination", Cell: c.Cell, MaxAge: time.Minute} + r.Coordinator, err = controller.NewCoordinator(r.Private, PrivateNamespace, r.Hub, controller.LocalDigestImageResolver{}, nil, time.Hour) + if err != nil { + return nil, err + } + for index, name := range []string{"provider", "consumer-a", "consumer-b"} { + root, err := API(filepath.Join(c.State, name, "management-root.json")) + if err != nil { + return nil, err + } + identity, err := manager.ResolveProjectIdentity(ctx, root, "local-milo", name) + if err != nil { + return nil, err + } + project, err := API(filepath.Join(c.State, name, "management-project.json")) + if err != nil { + return nil, err + } + p := Project{API: project, Identity: identity} + if index == 0 { + r.Provider = p + } else { + r.Consumers[index-1] = p + } + } + return r, nil +} +func (r *Runner) ScopedAsset() string { + return r.Provider.Identity.AuthorityID + "/" + string(r.Provider.Identity.UID) + "/fleet-provider/fleet.datumapis.com/Device/synthetic-device-central-01" +} +func condition(kind string, status metav1.ConditionStatus, generation int64, reason string) metav1.Condition { + return metav1.Condition{Type: kind, Status: status, ObservedGeneration: generation, Reason: reason, Message: "Local multi-plane acceptance; synthetic IAM, quota, catalog and networkless fixtures", LastTransitionTime: metav1.Now()} +} +func ensure(ctx context.Context, c client.Client, obj client.Object) error { + before, _ := json.Marshal(obj) + var want map[string]interface{} + _ = json.Unmarshal(before, &want) + err := c.Create(ctx, obj) + if !apierrors.IsAlreadyExists(err) { + return err + } + if err := c.Get(ctx, client.ObjectKeyFromObject(obj), obj); err != nil { + return err + } + after, _ := json.Marshal(obj) + var got map[string]interface{} + _ = json.Unmarshal(after, &got) + w, _ := json.Marshal(want["spec"]) + g, _ := json.Marshal(got["spec"]) + if string(w) != string(g) || obj.GetDeletionTimestamp() != nil { + return errors.New("existing fixture differs; refusing replacement") + } + return nil +} + +// Seed uses bootstrap only for provider facts/publication; requests use distinct +// customer credentials and a watch starts before each create. +func Seed(ctx context.Context, c Config) error { + var profile fleet.MachineProfile + var class fleet.MachineClass + var capacity fleet.MachineCapacity + if err := json.Unmarshal([]byte(`{"metadata":{"name":"local-profile"},"spec":{"cpu":{"architecture":"amd64","cores":2},"memory":{"capacity":"2Gi"}}}`), &profile); err != nil { + return err + } + if err := json.Unmarshal([]byte(`{"metadata":{"name":"local-class"},"spec":{"profilePolicy":{"allowedProfiles":[{"name":"local-profile"}],"customProfiles":{"enabled":false}},"capacity":{"machineCapacities":{"namespace":"fleet-provider","selector":{"matchLabels":{"pool":"local"}}}}}}`), &class); err != nil { + return err + } + if err := json.Unmarshal([]byte(`{"metadata":{"name":"local-capacity","namespace":"fleet-provider","labels":{"pool":"local"}},"spec":{"deviceRef":{"name":"synthetic-device-central-01"},"allocationPolicy":"Enabled","cleaningPolicyRef":{"name":"local-cleaning"},"reclaimPolicy":"Retain"}}`), &capacity); err != nil { + return err + } + provider, err := API(filepath.Join(c.State, "provider", "bootstrap-project.json")) + if err != nil { + return err + } + for _, obj := range []client.Object{&profile, &class, &capacity} { + if err := ensure(ctx, provider, obj); err != nil { + return err + } + } + class.Status.EvaluatedRevision = "local-fixture-v1" + if err := provider.Status().Update(ctx, &class); err != nil { + return err + } + capacity.Status.Hardware = fleet.Hardware{CPU: fleet.HardwareCPU{Architecture: "amd64", Cores: 2}, Memory: fleet.HardwareMemory{Capacity: "2Gi"}} + for _, kind := range []string{"Available", "Verified", "Prepared", "Healthy"} { + capacity.Status.Conditions = append(capacity.Status.Conditions, condition(kind, metav1.ConditionTrue, capacity.Generation, "SyntheticHardwareObservation")) + } + if err := provider.Status().Update(ctx, &capacity); err != nil { + return err + } + var routing []map[string]string + for _, name := range []string{"consumer-a", "consumer-b"} { + api, err := API(filepath.Join(c.State, name, "bootstrap-project.json")) + if err != nil { + return err + } + cp := profile.DeepCopyObject().(*fleet.MachineProfile) + cp.ObjectMeta = metav1.ObjectMeta{Name: profile.Name} + cc := &fleet.MachineClass{ObjectMeta: metav1.ObjectMeta{Name: class.Name}, Spec: fleet.MachineClassSpec{Source: &fleet.SourceReference{Project: "provider", Name: class.Name}}} + if err := ensure(ctx, api, cp); err != nil { + return err + } + if err := ensure(ctx, api, cc); err != nil { + return err + } + customer, err := clientcmd.BuildConfigFromFlags("", filepath.Join(c.State, name, "customer-project.json")) + if err != nil { + return err + } + d, err := dynamic.NewForConfig(customer) + if err != nil { + return err + } + gvr := fleet.GroupVersion.WithResource("machines") + seconds := int64(30) + w, err := d.Resource(gvr).Namespace(Namespace).Watch(ctx, metav1.ListOptions{TimeoutSeconds: &seconds}) + if err != nil { + return err + } + user, err := API(filepath.Join(c.State, name, "customer-project.json")) + if err != nil { + w.Stop() + return err + } + machine := &fleet.Machine{ObjectMeta: metav1.ObjectMeta{Name: "allocation", Namespace: Namespace}, Spec: fleet.MachineSpec{MachineClassRef: fleet.LocalReference{Name: class.Name}, MachineProfileRef: fleet.LocalReference{Name: profile.Name}, LocationRef: fleet.LocalReference{Name: Location}, PowerState: "Off"}} + if err := ensure(ctx, user, machine); err != nil { + w.Stop() + return err + } + select { + case event, ok := <-w.ResultChan(): + observed, typed := event.Object.(metav1.Object) + if !ok || event.Type != "ADDED" || !typed || observed.GetUID() != machine.UID || observed.GetName() != machine.Name || observed.GetNamespace() != Namespace { + w.Stop() + return errors.New("Milo create watch did not deliver Added") + } + case <-ctx.Done(): + w.Stop() + return ctx.Err() + } + w.Stop() + installation := &fleet.Installation{ObjectMeta: metav1.ObjectMeta{Name: "debian-pxe", Namespace: Namespace}, Spec: fleet.InstallationSpec{MachineRef: fleet.MachineReference{Name: machine.Name}, ExpectedPredecessor: fleet.InstallationPredecessor{Type: "None"}, ImageRef: fleet.LocalReference{Name: c.Image}}} + if err := ensure(ctx, user, installation); err != nil { + return err + } + var ns core.Namespace + if err := api.Get(ctx, client.ObjectKey{Name: Namespace}, &ns); err != nil { + return err + } + root, err := API(filepath.Join(c.State, name, "management-root.json")) + if err != nil { + return err + } + identity, err := manager.ResolveProjectIdentity(ctx, root, "local-milo", name) + if err != nil { + return err + } + routing = append(routing, map[string]string{"route": name, "namespace": Namespace, "namespaceUID": string(ns.UID), "projectUID": string(identity.UID), "machineUID": string(machine.UID), "watch": "Added exact UID"}) + + } + evidence, err := json.MarshalIndent(routing, "", " ") + if err != nil { + return err + } + return os.WriteFile(filepath.Join(c.State, "routing.json"), evidence, 0600) + +} +func (r *Runner) request(ctx context.Context, index int) (controller.AllocationRequest, error) { + p := r.Consumers[index] + var m fleet.Machine + var ns core.Namespace + var class fleet.MachineClass + var profile fleet.MachineProfile + var capacity fleet.MachineCapacity + var localClass fleet.MachineClass + var localProfile fleet.MachineProfile + objects := []struct { + api client.Client + key client.ObjectKey + obj client.Object + }{{p.API, client.ObjectKey{Namespace: Namespace, Name: "allocation"}, &m}, {p.API, client.ObjectKey{Name: Namespace}, &ns}, {r.Provider.API, client.ObjectKey{Name: "local-class"}, &class}, {r.Provider.API, client.ObjectKey{Name: "local-profile"}, &profile}, {r.Provider.API, client.ObjectKey{Namespace: "fleet-provider", Name: "local-capacity"}, &capacity}, {p.API, client.ObjectKey{Name: "local-class"}, &localClass}, {p.API, client.ObjectKey{Name: "local-profile"}, &localProfile}} + for _, o := range objects { + if err := o.api.Get(ctx, o.key, o.obj); err != nil { + return controller.AllocationRequest{}, err + } + } + if m.Spec.LocationRef.Name != Location || r.Config.Cell == "" || r.Hub != nil && r.Hub.Cell != r.Config.Cell { + return controller.AllocationRequest{}, fmt.Errorf("%w: %q", ErrLocationNotServed, m.Spec.LocationRef.Name) + } + if localClass.Spec.Source == nil || localClass.Spec.Source.Project != "provider" || localClass.Spec.Source.Name != class.Name { + return controller.AllocationRequest{}, errors.New("publication source mismatch") + } + observed := meta.FindStatusCondition(capacity.Status.Conditions, "Verified") + if observed == nil { + return controller.AllocationRequest{}, errors.New("missing hardware fixture evidence") + } + admission := controller.AdmissionAuthority{PrincipalUID: "local-fixture:" + string(p.Identity.UID), DecisionID: "local-fixture:" + string(m.UID)} + if err := r.Coordinator.EnsureClaimCustody(ctx, &m, ns.UID, admission, p.Identity); err != nil { + return controller.AllocationRequest{}, err + } + // Retain a concrete synthetic contract record, not just an invented reference. + contract, _ := json.Marshal(struct { + Consumer, Provider controller.ProjectIdentity + Claim, Capacity, Class, Profile types.UID + }{p.Identity, r.Provider.Identity, m.UID, capacity.UID, class.UID, profile.UID}) + sum := sha256.Sum256(contract) + digest := hex.EncodeToString(sum[:]) + name := "mp-authority-" + digest[:24] + secret := &core.Secret{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: PrivateNamespace}, Data: map[string][]byte{"contract.json": contract}} + if err := r.Private.Create(ctx, secret); apierrors.IsAlreadyExists(err) { + var existing core.Secret + if err := r.Private.Get(ctx, client.ObjectKeyFromObject(secret), &existing); err != nil { + return controller.AllocationRequest{}, err + } + if string(existing.Data["contract.json"]) != string(contract) { + return controller.AllocationRequest{}, errors.New("retained synthetic authority conflict") + } + secret = &existing + } else if err != nil { + return controller.AllocationRequest{}, err + } + authority := controller.AuthorityRef{Provider: "local-fixture", RecordName: name, RecordID: string(secret.UID), ContractDigest: digest} + hold := controller.ExternalHoldRef{Provider: "local-fixture", Namespace: PrivateNamespace, Name: name, UID: secret.UID} + if err := r.Coordinator.RetainClaimAuthority(ctx, m.UID, p.Identity, r.Provider.Identity, authority); err != nil { + return controller.AllocationRequest{}, err + } + if err := r.Coordinator.RetainAllocationAuthority(ctx, m.UID, p.Identity, r.Provider.Identity, authority, hold); err != nil { + return controller.AllocationRequest{}, err + } + hasFinalizer := false + for _, f := range m.Finalizers { + if f == controller.MachineFinalizer { + hasFinalizer = true + } + } + released, err := r.Coordinator.ClaimReleased(ctx, p.Identity, m.UID) + if err != nil { + return controller.AllocationRequest{}, err + } + if !hasFinalizer && !released { + m.Finalizers = append(m.Finalizers, controller.MachineFinalizer) + if err := p.API.Update(ctx, &m); err != nil { + return controller.AllocationRequest{}, err + } + } + return controller.AllocationRequest{Claim: &m, Class: &class, Profile: &profile, MachineCapacities: []fleet.MachineCapacity{capacity}, EvidenceObservedAt: map[types.UID]time.Time{capacity.UID: observed.LastTransitionTime.Time}, NamespaceUID: ns.UID, Admission: admission, LocalClassName: localClass.Name, LocalClassUID: localClass.UID, LocalProfileName: localProfile.Name, LocalProfileUID: localProfile.UID, ConsumerProject: p.Identity, ProviderProject: r.Provider.Identity, Authority: authority, ExternalHold: hold}, nil +} +func (r *Runner) Allocate(ctx context.Context) error { + a, err := r.request(ctx, 0) + if err != nil { + return err + } + b, err := r.request(ctx, 1) + if err != nil { + return err + } + if a.NamespaceUID == b.NamespaceUID || a.ConsumerProject.SameLifetime(b.ConsumerProject) { + return errors.New("consumer control planes do not have distinct identities") + } + if _, err = r.Coordinator.Allocate(ctx, a); err != nil { + return err + } + if _, err = r.Coordinator.Allocate(ctx, b); !errors.Is(err, controller.ErrInsufficientCapacity) { + return fmt.Errorf("contention must retain one winner: %v", err) + } + for index, request := range []controller.AllocationRequest{a, b} { + m := request.Claim + phase, reason := "Bound", "AwaitingVerifiedInstallation" + status := metav1.ConditionTrue + if index == 1 { + phase, reason, status = "Pending", "InsufficientCapacity", metav1.ConditionFalse + } + m.Status.Phase = phase + m.Status.Conditions = []metav1.Condition{condition("Bound", status, m.Generation, reason), condition("Ready", metav1.ConditionFalse, m.Generation, reason)} + if err := r.Consumers[index].API.Status().Update(ctx, m); err != nil { + return err + } + } + return nil +} +func (r *Runner) Install(ctx context.Context) error { return r.InstallIndex(ctx, 0) } + +func (r *Runner) InstallIndex(ctx context.Context, index int) error { + request, err := r.request(ctx, index) + if err != nil { + return err + } + var install fleet.Installation + if err := r.Consumers[index].API.Get(ctx, client.ObjectKey{Namespace: Namespace, Name: "debian-pxe"}, &install); err != nil { + return err + } + result, err := r.Coordinator.Install(ctx, controller.InstallationRequest{Claim: request.Claim, Installation: &install, NamespaceUID: request.NamespaceUID, ConsumerProject: request.ConsumerProject, Admission: controller.InstallationAdmissionAuthority{PrincipalUID: request.Admission.PrincipalUID, DecisionID: "local-install:" + string(install.UID), CatalogAuthority: "local-test-catalog", CatalogRevision: "local-test-v1", ImageDecisionID: "local-test-" + imageDigest(install.Spec.ImageRef.Name)}}) + if err != nil { + return err + } + verified, found, err := r.Hub.Lookup(ctx, result.Record.OperationID) + if err != nil || !found || verified.InputDigest != result.RequestDigest { + return executor.ErrOutcomeUnknown + } + install.Status.Phase = "Ready" + install.Status.Conditions = []metav1.Condition{condition("Ready", metav1.ConditionTrue, install.Generation, "LocalPXEVerifiedViaKarmada")} + if err := r.Consumers[index].API.Status().Update(ctx, &install); err != nil { + return err + } + m := request.Claim + m.Status.CurrentInstallationRef = &fleet.LocalReference{Name: install.Name} + m.Status.Phase = "Ready" + meta.SetStatusCondition(&m.Status.Conditions, condition("Ready", metav1.ConditionTrue, m.Generation, "LocalPXEVerifiedViaKarmada")) + return r.Consumers[index].API.Status().Update(ctx, m) +} +func (r *Runner) Release(ctx context.Context) error { return r.ReleaseIndex(ctx, 0) } +func (r *Runner) ReleaseSecond(ctx context.Context) error { return r.ReleaseIndex(ctx, 1) } +func (r *Runner) ReleaseIndex(ctx context.Context, index int) error { + request, err := r.request(ctx, index) + if err != nil { + return err + } + result, err := r.Coordinator.ReleaseScoped(ctx, request.ConsumerProject, request.Claim.UID) + if err != nil { + return err + } + if result.ExternalSettlementRequired { + result, err = r.Coordinator.CompleteExternalRelease(ctx, request.Claim.UID, request.Authority, request.ExternalHold, request.ConsumerProject) + if err != nil { + return err + } + } + if !result.SafeToRemoveFinalizer { + return executor.ErrOutcomeUnknown + } + return publishRelease(ctx, r.Consumers[index].API, request.Claim) +} + +// publishRelease runs only after verified cleanup made removal safe. Status is +// written first because a status response overwrites the in-memory object, +// including metadata, from the server; the finalizer is removed afterwards +// from that fresh copy so the removal is not silently reverted. +func publishRelease(ctx context.Context, api client.Client, m *fleet.Machine) error { + // Retire the current installation before clearing the reference, so retries + // can finish projection if either API write fails after cleanup. + if ref := m.Status.CurrentInstallationRef; ref != nil { + var install fleet.Installation + err := api.Get(ctx, client.ObjectKey{Namespace: m.Namespace, Name: ref.Name}, &install) + if err != nil && !apierrors.IsNotFound(err) { + return err + } + if err == nil { + install.Status.Phase = "Released" + meta.SetStatusCondition(&install.Status.Conditions, condition("Ready", metav1.ConditionFalse, install.Generation, "Released")) + if err := api.Status().Update(ctx, &install); err != nil { + return err + } + } + } + m.Status.CurrentInstallationRef = nil + m.Status.Phase = "Released" + meta.SetStatusCondition(&m.Status.Conditions, condition("Bound", metav1.ConditionFalse, m.Generation, "Released")) + meta.SetStatusCondition(&m.Status.Conditions, condition("Ready", metav1.ConditionFalse, m.Generation, "Released")) + if err := api.Status().Update(ctx, m); err != nil { + return err + } + retainedFinalizers := make([]string, 0, len(m.Finalizers)) + for _, f := range m.Finalizers { + if f != controller.MachineFinalizer { + retainedFinalizers = append(retainedFinalizers, f) + } + } + m.Finalizers = retainedFinalizers + return api.Update(ctx, m) +} +func (r *Runner) Reuse(ctx context.Context) error { + b, err := r.request(ctx, 1) + if err != nil { + return err + } + if _, err = r.Coordinator.Allocate(ctx, b); err != nil { + return err + } + // Public status follows only the coordinator's committed reuse binding; + // readiness still requires a verified installation for this allocation. + m := b.Claim + m.Status.Phase = "Bound" + meta.SetStatusCondition(&m.Status.Conditions, condition("Bound", metav1.ConditionTrue, m.Generation, "AwaitingVerifiedInstallation")) + meta.SetStatusCondition(&m.Status.Conditions, condition("Ready", metav1.ConditionFalse, m.Generation, "AwaitingVerifiedInstallation")) + return r.Consumers[1].API.Status().Update(ctx, m) +} +func ReadConfig(path string) (Config, error) { + var c Config + b, err := os.ReadFile(path) + if err != nil { + return c, err + } + err = json.Unmarshal(b, &c) + return c, err +} + +func imageDigest(value string) string { _, digest, _ := strings.Cut(value, "@"); return digest } diff --git a/internal/multiplane/runner_test.go b/internal/multiplane/runner_test.go new file mode 100644 index 00000000..6bbdb1f2 --- /dev/null +++ b/internal/multiplane/runner_test.go @@ -0,0 +1,105 @@ +package multiplane + +import ( + "context" + "errors" + "sync" + "testing" + "time" + + fleet "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/controller" + "go.datum.net/fleet/internal/executor" + "go.datum.net/fleet/internal/simulator" + core "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/client/interceptor" +) + +type disconnected struct{ calls int } + +func (d *disconnected) Execute(context.Context, simulator.Request) (simulator.OperationResult, error) { + d.calls++ + return simulator.OperationResult{}, executor.ErrOutcomeUnknown +} +func (d *disconnected) Lookup(context.Context, string) (simulator.OperationResult, bool, error) { + return simulator.OperationResult{}, false, executor.ErrOutcomeUnknown +} +func TestIndependentProjectsContendAndUnknownRetainsCustody(t *testing.T) { + ctx := context.Background() + s := Scheme() + private := fake.NewClientBuilder().WithScheme(s).WithInterceptorFuncs(interceptor.Funcs{Create: func(ctx context.Context, c client.WithWatch, obj client.Object, opts ...client.CreateOption) error { + obj.SetUID(types.UID("private-" + obj.GetName())) + return c.Create(ctx, obj, opts...) + }}).Build() + var profile fleet.MachineProfile + profile.Name = "local-profile" + profile.UID = "source-profile" + profile.Spec.CPU.Architecture = "amd64" + profile.Spec.CPU.Cores = 2 + profile.Spec.Memory.Capacity = "2Gi" + class := &fleet.MachineClass{ObjectMeta: metav1.ObjectMeta{Name: "local-class", UID: "source-class"}, Spec: fleet.MachineClassSpec{Capacity: &fleet.CapacityPolicy{MachineCapacities: fleet.MachineSelector{Namespace: "fleet-provider"}}}, Status: fleet.MachineClassStatus{EvaluatedRevision: "v1"}} + capacity := &fleet.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: "local-capacity", Namespace: "fleet-provider", UID: "capacity", Generation: 1}, Spec: fleet.MachineCapacitySpec{DeviceRef: fleet.LocalReference{Name: "synthetic-device-central-01"}, AllocationPolicy: "Enabled"}, Status: fleet.MachineCapacityStatus{Hardware: fleet.Hardware{CPU: fleet.HardwareCPU{Architecture: "amd64", Cores: 2}, Memory: fleet.HardwareMemory{Capacity: "2Gi"}}}} + for _, kind := range []string{"Verified", "Healthy", "Prepared", "Available"} { + capacity.Status.Conditions = append(capacity.Status.Conditions, condition(kind, metav1.ConditionTrue, 1, "Fixture")) + } + provider := fake.NewClientBuilder().WithScheme(s).WithObjects(class, &profile, capacity).Build() + backend := &disconnected{} + coordinator, err := controller.NewCoordinator(private, PrivateNamespace, backend, controller.LocalDigestImageResolver{}, nil, time.Hour) + if err != nil { + t.Fatal(err) + } + r := Runner{Config: Config{Cell: "cell-a"}, Private: private, Coordinator: coordinator, Provider: Project{API: provider, Identity: controller.ProjectIdentity{AuthorityID: "test", RouteName: "provider", UID: "provider-project"}}} + for index, name := range []string{"a", "b"} { + ns := &core.Namespace{ObjectMeta: metav1.ObjectMeta{Name: Namespace, UID: types.UID(name + "-namespace")}} + // Identical namespace, Machine name AND UID: only project authority separates them. + m := &fleet.Machine{ObjectMeta: metav1.ObjectMeta{Name: "allocation", Namespace: Namespace, UID: "same-machine-uid"}, Spec: fleet.MachineSpec{MachineClassRef: fleet.LocalReference{Name: "local-class"}, MachineProfileRef: fleet.LocalReference{Name: "local-profile"}, LocationRef: fleet.LocalReference{Name: "local"}, PowerState: "Off"}} + localClass := &fleet.MachineClass{ObjectMeta: metav1.ObjectMeta{Name: "local-class", UID: types.UID(name + "-class")}, Spec: fleet.MachineClassSpec{Source: &fleet.SourceReference{Project: "provider", Name: "local-class"}}} + cp := profile.DeepCopyObject().(*fleet.MachineProfile) + cp.UID = types.UID(name + "-profile") + r.Consumers[index] = Project{API: fake.NewClientBuilder().WithScheme(s).WithObjects(ns, m, localClass, cp).Build(), Identity: controller.ProjectIdentity{AuthorityID: "test", RouteName: name, UID: types.UID(name + "-project")}} + } + a, err := r.request(ctx, 0) + if err != nil { + t.Fatal(err) + } + b, err := r.request(ctx, 1) + if err != nil { + t.Fatal(err) + } + results := make([]error, 2) + var wg sync.WaitGroup + for i, q := range []controller.AllocationRequest{a, b} { + wg.Add(1) + go func() { defer wg.Done(); _, results[i] = r.Coordinator.Allocate(ctx, q) }() + } + wg.Wait() + winner, loser := -1, -1 + for i, err := range results { + if err == nil { + if winner != -1 { + t.Fatal("both projects won") + } + winner = i + } else if errors.Is(err, controller.ErrInsufficientCapacity) || errors.Is(err, controller.ErrRecordInvalid) { + loser = i + } else { + t.Fatal(err) + } + } + if winner < 0 || loser < 0 { + t.Fatal("contention did not produce one winner", results) + } + claims := []controller.AllocationRequest{a, b} + _, err = r.Coordinator.ReleaseScoped(ctx, claims[winner].ConsumerProject, claims[winner].Claim.UID) + if !errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatalf("disconnected cleanup must be unknown: %v", err) + } + _, err = r.Coordinator.Allocate(ctx, claims[loser]) + if !(errors.Is(err, controller.ErrInsufficientCapacity) || errors.Is(err, controller.ErrRecordInvalid)) { + t.Fatalf("unknown cleanup exposed capacity: %v", err) + } +} From baf13ba410ddb4b660fd715a5aa7992021e9800e Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 18 Nov 2026 13:34:29 -0600 Subject: [PATCH 010/518] feat(redfish): Redfish executor on gofish with a DMTF emulator lab mode internal/redfish implements the executor contract over Redfish using gofish v0.27.0 for transport and schema decoding, behind Fleet's own guards: exact endpoint and System identity checks across every page of the Systems collection, advertised allowable-value checks, no redirects or environment proxy, bounded bodies and errors that never carry credentials or URLs. Each boot override is one conditional PATCH (If-Match when an ETag is present) with readback and no Settings fallback; each reset is one POST with no resend. Recovery is observation-based and treats lost responses as Unknown. On may be repeated, bounded to three attempts, only while the System is still Off, armed and silent; this is not exactly-once delivery. Cleanup PXE-boots a wipe environment that zeroes and reads back the disk. task multiplane:redfish-acceptance runs the multi-plane composition with Redfish workers that have no libvirt path, against the unmodified DMTF Redfish Interface Emulator 1.2.2 and a lab-only libvirt adapter driving two persistent lab VMs. Credentials are synthetic and per run. This is not physical BMC or hardware qualification; see docs/operations/redfish-lab.md. Co-Authored-By: Claude Opus 5.5 --- Taskfile.yaml | 7 + cmd/fleet-multiplane/main.go | 93 +- config/site/redfish/base/bmc.yaml | 7 + config/site/redfish/base/kustomization.yaml | 40 + config/site/redfish/graph/kustomization.yaml | 56 ++ config/site/redfish/services/bmc.yaml | 68 ++ .../site/redfish/services/kustomization.yaml | 50 ++ docs/development/README.md | 6 + docs/operations/README.md | 1 + docs/operations/local-vm.md | 4 + docs/operations/multiplane.md | 4 + docs/operations/redfish-lab.md | 624 ++++++++++++++ docs/operations/site-execution.md | 3 +- go.mod | 1 + go.sum | 2 + hack/local-vm/init | 25 +- hack/local-vm/site-runtime | 9 + hack/multiplane/acceptance-redfish.sh | 55 ++ hack/multiplane/evidence.py | 123 ++- hack/multiplane/flux.py | 24 +- hack/multiplane/harness.py | 11 +- hack/multiplane/k8s_evidence.py | 7 +- hack/multiplane/redfish_steps.py | 314 +++++++ hack/multiplane/run.sh | 30 +- hack/multiplane/site.sh | 22 + hack/multiplane/steps.sh | 7 +- hack/multiplane/teardown.sh | 7 +- hack/multiplane/test-harness.sh | 2 + hack/multiplane/test-redfish.py | 171 ++++ hack/multiplane/verify-rbac.py | 14 +- hack/redfish-lab/Containerfile | 17 + hack/redfish-lab/emulator-config.json | 7 + hack/redfish-lab/fake_virsh.py | 33 + hack/redfish-lab/fleet_lab_adapter.py | 387 +++++++++ hack/redfish-lab/populate-config.json | 24 + hack/redfish-lab/requirements.lock | 203 +++++ hack/redfish-lab/targets.json | 8 + hack/redfish-lab/test_adapter.py | 117 +++ hack/redfish-lab/upstream.sh | 24 + internal/multiplane/runner.go | 4 + internal/redfish/boot.go | 217 +++++ internal/redfish/client.go | 413 +++++++++ internal/redfish/client_test.go | 247 ++++++ internal/redfish/provider.go | 814 ++++++++++++++++++ internal/redfish/provider_test.go | 629 ++++++++++++++ 45 files changed, 4903 insertions(+), 28 deletions(-) create mode 100644 config/site/redfish/base/bmc.yaml create mode 100644 config/site/redfish/base/kustomization.yaml create mode 100644 config/site/redfish/graph/kustomization.yaml create mode 100644 config/site/redfish/services/bmc.yaml create mode 100644 config/site/redfish/services/kustomization.yaml create mode 100644 docs/operations/redfish-lab.md create mode 100755 hack/multiplane/acceptance-redfish.sh create mode 100644 hack/multiplane/redfish_steps.py create mode 100644 hack/multiplane/test-redfish.py create mode 100644 hack/redfish-lab/Containerfile create mode 100644 hack/redfish-lab/emulator-config.json create mode 100755 hack/redfish-lab/fake_virsh.py create mode 100755 hack/redfish-lab/fleet_lab_adapter.py create mode 100644 hack/redfish-lab/populate-config.json create mode 100644 hack/redfish-lab/requirements.lock create mode 100644 hack/redfish-lab/targets.json create mode 100644 hack/redfish-lab/test_adapter.py create mode 100755 hack/redfish-lab/upstream.sh create mode 100644 internal/redfish/boot.go create mode 100644 internal/redfish/client.go create mode 100644 internal/redfish/client_test.go create mode 100644 internal/redfish/provider.go create mode 100644 internal/redfish/provider_test.go diff --git a/Taskfile.yaml b/Taskfile.yaml index dce2a9f8..6b55c0d2 100644 --- a/Taskfile.yaml +++ b/Taskfile.yaml @@ -14,6 +14,13 @@ tasks: cmds: - ./hack/multiplane/run.sh {{.CLI_ARGS}} + multiplane:redfish-acceptance: + desc: "The multi-plane acceptance in Redfish mode: workers drive two persistent lab VMs only through the DMTF Redfish Interface Emulator and its lab adapter (same exit codes)." + env: + FLEET_MULTIPLANE_INOTIFY: '1024' + cmds: + - ./hack/multiplane/run.sh --redfish {{.CLI_ARGS}} + multiplane:preflight: desc: Check local prerequisites and implementation readiness without creating resources. env: diff --git a/cmd/fleet-multiplane/main.go b/cmd/fleet-multiplane/main.go index 004b6208..d63f851a 100644 --- a/cmd/fleet-multiplane/main.go +++ b/cmd/fleet-multiplane/main.go @@ -9,6 +9,7 @@ import ( "fmt" "os" "os/signal" + "strings" "syscall" "time" @@ -16,6 +17,7 @@ import ( "go.datum.net/fleet/internal/executor" "go.datum.net/fleet/internal/localvm" "go.datum.net/fleet/internal/multiplane" + "go.datum.net/fleet/internal/redfish" "k8s.io/client-go/dynamic" "k8s.io/client-go/rest" "k8s.io/client-go/tools/clientcmd" @@ -29,7 +31,7 @@ func main() { } func run() error { if len(os.Args) < 2 { - return fmt.Errorf("usage: fleet-multiplane site-worker|site-observer|image|boot-service|boot-denials| [flags]") + return fmt.Errorf("usage: fleet-multiplane site-worker|site-observer|image|boot-service|boot-denials|redfish-probe| [flags]") } fs := flag.NewFlagSet(os.Args[1], flag.ContinueOnError) once := fs.Bool("once", false, "one reconcile attempt for fault injection") @@ -40,11 +42,16 @@ func run() error { kubeconfig := fs.String("kubeconfig", "", "cell-local kubeconfig; default in-cluster ServiceAccount") cell := fs.String("cell", "", "exact Karmada member name") scoped := fs.String("scoped-asset", "", "exact retained provider-scoped Device ID") + extraMAC := fs.String("extra-mac", "", "another enrolled NIC whose boot script must be denied (boot-denials, Redfish mode)") + endpoint := fs.String("endpoint", "", "Redfish endpoint (redfish-probe)") + credentials := fs.String("credentials", "", "directory holding username and password files (redfish-probe)") + system := fs.String("system", "", "enrolled Redfish System Id (redfish-probe)") + uuid := fs.String("uuid", "", "enrolled Redfish System UUID (redfish-probe)") if err := fs.Parse(os.Args[2:]); err != nil { return err } switch os.Args[1] { - case "seed", "allocate", "install", "admit-install", "release", "release-b", "reuse", "asset": + case "seed", "allocate", "install", "install-b", "admit-install", "release", "release-b", "reuse", "asset": config, err := multiplane.ReadConfig(*configPath) if err != nil { return err @@ -68,6 +75,8 @@ func run() error { action = r.Allocate case "install", "admit-install": action = r.Install + case "install-b": + action = r.InstallSecond case "release": action = r.Release case "release-b": @@ -100,6 +109,31 @@ func run() error { time.Sleep(3 * time.Second) } } + if os.Args[1] == "redfish-probe" { + return probe(*endpoint, *credentials, *system, *uuid) + } + if redfishMode() { + switch os.Args[1] { + case "boot-service", "boot-denials": + p, err := redfish.OpenReadOnly() + if err != nil { + return err + } + if os.Args[1] == "boot-service" { + return p.ServeBoot() + } + var extra []string + if *extraMAC != "" { + extra = append(extra, *extraMAC) + } + summary, err := p.CheckClosedBoot(*origin, extra) + if err != nil { + return err + } + fmt.Println(summary) + return nil + } + } switch os.Args[1] { case "image", "boot-service", "boot-denials": // Read-only: the boot service mounts the journal read-only. @@ -143,7 +177,13 @@ func run() error { defer cancel() if os.Args[1] == "site-observer" { // The observer never executes: its provider is read-only. - p, err := localvm.OpenReadOnly() + var p executor.Client + var err error + if redfishMode() { + p, err = redfish.OpenReadOnly() + } else { + p, err = localvm.OpenReadOnly() + } if err != nil { return err } @@ -153,7 +193,15 @@ func run() error { fmt.Fprintf(os.Stderr, "observer: handoff %s not published: %s\n", name, classify(err)) }) } - p, err := localvm.Open() + // A Redfish worker has no libvirt fallback: redfish.Open refuses any + // hypervisor configuration, and the worker reaches the target only + // through its enrolled BMC. + var p executor.Client + if redfishMode() { + p, err = redfish.Open() + } else { + p, err = localvm.Open() + } if err != nil { return err } @@ -172,6 +220,43 @@ func run() error { const coordinationNamespace = "fleet-coordination" +// redfishMode selects the Redfish executor for site roles. The site's Flux +// layers set it; there is no automatic choice between providers. +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. +func probe(endpoint, credentials, system, uuid string) error { + user, err1 := os.ReadFile(credentials + "/username") + password, err2 := os.ReadFile(credentials + "/password") + if credentials == "" || err1 != nil || err2 != nil { + return fmt.Errorf("redfish-probe: credentials unavailable") + } + c, err := redfish.NewClient(endpoint, strings.TrimSpace(string(user)), strings.TrimSpace(string(password)), 20*time.Second) + if 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}) + switch { + case err == nil: + fmt.Printf("redfish-probe: discovered %s at %s; ResetType %s; boot targets %s\n", s.ID, s.Path, strings.Join(s.ResetTypes, ","), strings.Join(s.BootTargets, ",")) + return nil + case errors.Is(err, redfish.ErrUnauthorized): + fmt.Println("redfish-probe: credential rejected; no effect issued") + os.Exit(10) + 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.ErrIdentity): + fmt.Println("redfish-probe: enrolled identity not matched exactly; no effect issued") + os.Exit(12) + } + return err +} + // Worker exit codes are the Job podFailurePolicy contract: rejected authority // fails the Job without retry; anything else is retried by the Job controller // against the same retained operation. Exit 0 only follows a validated diff --git a/config/site/redfish/base/bmc.yaml b/config/site/redfish/base/bmc.yaml new file mode 100644 index 00000000..02097f36 --- /dev/null +++ b/config/site/redfish/base/bmc.yaml @@ -0,0 +1,7 @@ +# Lab BMC identity (config/site/redfish/services). It holds no API token. Its +# synthetic credential Secret, fleet-site-bmc-credentials, is enrolled by the +# harness and is never part of a source revision. +apiVersion: v1 +kind: ServiceAccount +metadata: {name: fleet-site-bmc, namespace: fleet-site} +automountServiceAccountToken: false diff --git a/config/site/redfish/base/kustomization.yaml b/config/site/redfish/base/kustomization.yaml new file mode 100644 index 00000000..f9bf8fbd --- /dev/null +++ b/config/site/redfish/base/kustomization.yaml @@ -0,0 +1,40 @@ +# Redfish-mode site base: the shared base plus the lab BMC identity, with the +# kro worker admission policy narrowed for Redfish workers. Selected by the +# environment's fleet-site-base path (hack/multiplane/flux.py --provider redfish). +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - ../../base + - bmc.yaml +patches: + - target: {kind: ValidatingAdmissionPolicy, name: fleet-site-kro-worker-jobs} + patch: |- + # Guard: fail the build if the shared policy's volume rule moved. + - op: test + path: /spec/validations/5/message + value: a worker Job may mount only the site journal claim and emptyDir + - op: replace + path: /spec/validations/5 + value: + expression: >- + !has(variables.pod.volumes) || variables.pod.volumes.all(v, + (has(v.persistentVolumeClaim) && v.persistentVolumeClaim.claimName == 'fleet-site-state') || has(v.emptyDir) || + (has(v.secret) && v.secret.secretName == 'fleet-site-bmc-credentials')) + message: a Redfish worker Job may mount only the site journal claim, emptyDir and the BMC credential + # Redfish workers reach the lab hardware only through Redfish: no + # libvirt socket mount and no libvirt URI, and the Redfish provider. + - op: add + path: /spec/validations/- + value: + expression: >- + variables.pod.containers.all(c, !has(c.volumeMounts) || c.volumeMounts.all(m, + !(has(m.subPath) && m.subPath.startsWith('libvirt')) && !m.mountPath.startsWith('/run/fleet-libvirt') && !m.mountPath.startsWith('/var/lib/fleet-lab/disks'))) + message: a Redfish worker Job must not mount the libvirt socket or lab disks + - op: add + path: /spec/validations/- + value: + expression: >- + variables.pod.containers.all(c, has(c.env) && + c.env.exists(e, e.name == 'FLEET_SITE_PROVIDER' && has(e.value) && e.value == 'redfish') && + !c.env.exists(e, e.name == 'FLEET_LIBVIRT_URI')) + message: a Redfish worker Job must select the Redfish provider and carry no libvirt URI diff --git a/config/site/redfish/graph/kustomization.yaml b/config/site/redfish/graph/kustomization.yaml new file mode 100644 index 00000000..437677c4 --- /dev/null +++ b/config/site/redfish/graph/kustomization.yaml @@ -0,0 +1,56 @@ +# Redfish-mode dispatcher graph: the shared graph with the worker template +# switched to the Redfish provider. Workers mount the journal, the boot +# evidence and the lab console capture (all read-only except the journal) and +# the synthetic BMC credential; they have no libvirt socket. The worker also +# waits for the Flux-owned lab BMC through an externalRef. +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - ../../graph +patches: + - target: {kind: ResourceGraphDefinition, name: fleet-handoff-dispatcher} + patch: |- + - op: test + path: /spec/resources/9/id + value: workers + - op: replace + path: /spec/resources/9/template/spec/template/spec/containers/0/env + value: + - {name: FLEET_SITE_PROVIDER, value: redfish} + - {name: FLEET_BOOT_ORIGIN, value: "${'http://' + bootService.spec.clusterIP + ':8080'}"} + - {name: FLEET_BOOT_EVIDENCE, value: /var/lib/fleet-boot} + - {name: FLEET_REDFISH_CREDENTIALS, value: /etc/fleet-redfish} + - {name: FLEET_REDFISH_CONSOLE, value: /var/lib/fleet-lab-console} + # Explicit site enrollment: each physical asset ID maps to exactly one + # Redfish System (Id and UUID), NIC and console capture. Only target A + # is published as capacity; target B is enrolled to prove isolation. + - name: FLEET_REDFISH_ENROLLMENT + value: '{"endpoint":"http://10.96.0.81:8000","targets":[{"assetID":"fleet-provider/fleet.datumapis.com/Device/synthetic-device-central-01","systemID":"System-1","systemUUID":"7f3d0c2e-1a5b-4c6d-8e9f-0a1b2c3d4e0a","mac":"52:54:00:77:01:0a","diskBytes":2147483648,"console":"target-a.log"},{"assetID":"fleet-provider/fleet.datumapis.com/Device/synthetic-device-central-02","systemID":"System-2","systemUUID":"7f3d0c2e-1a5b-4c6d-8e9f-0a1b2c3d4e0b","mac":"52:54:00:77:01:0b","diskBytes":2147483648,"console":"target-b.log"}]}' + - {name: HOME, value: /tmp} + - op: replace + path: /spec/resources/9/template/spec/template/spec/containers/0/volumeMounts + value: + - {name: state, mountPath: /var/lib/fleet-local, subPath: journal} + - {name: state, mountPath: /var/lib/fleet-boot, subPath: boot-evidence, readOnly: true} + - {name: state, mountPath: /var/lib/fleet-lab-console, subPath: lab-console, readOnly: true} + - {name: credentials, mountPath: /etc/fleet-redfish, readOnly: true} + - {name: tmp, mountPath: /tmp} + - op: add + path: /spec/resources/9/template/spec/template/spec/volumes/- + value: + name: credentials + secret: {secretName: fleet-site-bmc-credentials, defaultMode: 0400} + - op: add + path: /spec/resources/9/template/metadata/annotations/fleet.datumapis.com~1bmc + value: ${bmc.metadata.name} + - op: add + path: /spec/resources/- + value: + id: bmc + readyWhen: + - ${bmc.status.?availableReplicas.orValue(0) == 1} + externalRef: + apiVersion: apps/v1 + kind: Deployment + metadata: + name: fleet-site-bmc diff --git a/config/site/redfish/services/bmc.yaml b/config/site/redfish/services/bmc.yaml new file mode 100644 index 00000000..39407870 --- /dev/null +++ b/config/site/redfish/services/bmc.yaml @@ -0,0 +1,68 @@ +# Lab BMC: the unmodified DMTF Redfish Interface Emulator 1.2.2 with the +# lab-only adapter (hack/redfish-lab), from a digest-pinned image. It is the +# only Redfish endpoint and, besides the runtime, the only holder of the +# libvirt socket. It owns the lab targets' definitions and provisioning +# network; Fleet workers reach it only over HTTP with the synthetic +# credential. Plain HTTP on the cluster network is a documented lab seam. +apiVersion: v1 +kind: Service +metadata: + name: fleet-site-bmc + namespace: fleet-site +spec: + type: ClusterIP + clusterIP: "${FLEET_BMC_SERVICE_IP}" + selector: {app.kubernetes.io/name: fleet-site-bmc} + ports: + - {name: redfish, port: 8000, targetPort: 8000, protocol: TCP} +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: fleet-site-bmc + namespace: fleet-site +spec: + replicas: 1 + strategy: {type: Recreate} + selector: + matchLabels: {app.kubernetes.io/name: fleet-site-bmc} + template: + metadata: + labels: {app.kubernetes.io/name: fleet-site-bmc} + spec: + serviceAccountName: fleet-site-bmc + automountServiceAccountToken: false + containers: + - name: bmc + image: "${FLEET_BMC_IMAGE}" + imagePullPolicy: IfNotPresent + args: [serve] + env: + - {name: FLEET_BOOT_IP, value: "${FLEET_BOOT_SERVICE_IP}"} + - {name: FLEET_LIBVIRT_URI, value: "qemu:///system?socket=/run/fleet-libvirt/libvirt-sock"} + - {name: HOME, value: /tmp} + ports: + - {name: redfish, containerPort: 8000} + readinessProbe: + httpGet: {path: /redfish/v1/, port: 8000} + periodSeconds: 5 + securityContext: + runAsUser: 0 + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: {drop: [ALL]} + resources: + requests: {cpu: 50m, memory: 64Mi} + limits: {memory: 256Mi} + volumeMounts: + - {name: state, mountPath: /run/fleet-libvirt, subPath: libvirt-socket} + - {name: state, mountPath: /var/lib/fleet-bmc, subPath: bmc-state} + - {name: credentials, mountPath: /etc/fleet-bmc-credentials, readOnly: true} + - {name: tmp, mountPath: /tmp} + volumes: + - name: state + persistentVolumeClaim: {claimName: fleet-site-state} + - name: credentials + secret: {secretName: fleet-site-bmc-credentials, defaultMode: 0400} + - name: tmp + emptyDir: {} diff --git a/config/site/redfish/services/kustomization.yaml b/config/site/redfish/services/kustomization.yaml new file mode 100644 index 00000000..70dce65d --- /dev/null +++ b/config/site/redfish/services/kustomization.yaml @@ -0,0 +1,50 @@ +# Redfish-mode shared site services: the shared services plus the lab BMC +# (DMTF Redfish Interface Emulator with the lab-only libvirt adapter). Only +# the runtime and the BMC hold the libvirt socket; workers hold neither. +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - ../../services + - bmc.yaml +patches: + - target: {kind: Deployment, name: fleet-site-runtime} + patch: |- + apiVersion: apps/v1 + kind: Deployment + metadata: {name: fleet-site-runtime, namespace: fleet-site} + spec: + template: + spec: + containers: + - name: libvirt + env: + - {name: FLEET_SITE_PROVIDER, value: redfish} + volumeMounts: + - {name: state, mountPath: /var/lib/fleet-lab/disks, subPath: lab-disks} + - {name: state, mountPath: /var/lib/fleet-lab-console, subPath: lab-console} + - target: {kind: Deployment, name: fleet-site-boot} + patch: |- + apiVersion: apps/v1 + kind: Deployment + metadata: {name: fleet-site-boot, namespace: fleet-site} + spec: + template: + spec: + containers: + - name: boot + env: + - {name: FLEET_SITE_PROVIDER, value: redfish} + - target: {kind: Deployment, name: fleet-site-observer} + patch: |- + apiVersion: apps/v1 + kind: Deployment + metadata: {name: fleet-site-observer, namespace: fleet-site} + spec: + template: + spec: + containers: + - name: observer + env: + - {name: FLEET_SITE_PROVIDER, value: redfish} + - {name: FLEET_BOOT_ORIGIN, value: "http://${FLEET_BOOT_SERVICE_IP}:8080"} + - {name: FLEET_BOOT_EVIDENCE, value: /var/lib/fleet-boot} diff --git a/docs/development/README.md b/docs/development/README.md index bf94797f..84865a75 100644 --- a/docs/development/README.md +++ b/docs/development/README.md @@ -31,6 +31,12 @@ 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. +`internal/redfish` implements a Redfish executor behind the same contracts: discovery, +one-time boot overrides, power, observation-based recovery and a booted wipe +cleanup. [Redfish-mode acceptance](../operations/redfish-lab.md) +(`task multiplane:redfish-acceptance`) exercises it against the unmodified DMTF Redfish +Interface Emulator and a lab-only libvirt adapter. It is not qualified against a +physical BMC or server, and the production manager does not use it. Production Kustomize roots now package the implemented manager, admission, API, Milo IAM, service, and quota boundaries; packaging is not runtime readiness. diff --git a/docs/operations/README.md b/docs/operations/README.md index 7443e355..a78d36b0 100644 --- a/docs/operations/README.md +++ b/docs/operations/README.md @@ -15,6 +15,7 @@ integrations. Real provider support and live Milo acceptance tests are incomplet | Exercise allocation, install recovery, cleanup, and reuse | [Standalone smoke environment](standalone-smoke.md) | Same-cluster lifecycle behavior with namespaces as project stand-ins | | Install a real OS over firmware PXE into a disposable local VM | [Local VM PXE installation](local-vm.md) | Single-plane real install, disk-only boot, recovery, cleanup and reuse under explicit TCG; 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, 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, cleanup and reuse; 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 executor discovery, one-time PXE/disk boot overrides, power, lost-response recovery and a booted wipe cleanup, against the unmodified DMTF Redfish Interface Emulator with a lab-only libvirt adapter and two persistent lab VMs; synthetic credentials and networking; not physical BMC or hardware qualification | | Render deployment bundles and supply environment inputs | [Deployment manifests](../../config/README.md) | Packaging and security boundaries, not runtime readiness | | Run the manager across consuming projects | [Project discovery](../../config/README.md#project-discovery) | Discovery, per-project isolation, departure, role bindings, and readiness | | Exercise Milo-routed synthetic staging | [Synthetic staging configuration](../../config/README.md#environment-owned-inputs) | Restricted synthetic publication and lifecycle behavior, not production authority | diff --git a/docs/operations/local-vm.md b/docs/operations/local-vm.md index 06ba44f7..f7b107e2 100644 --- a/docs/operations/local-vm.md +++ b/docs/operations/local-vm.md @@ -84,6 +84,10 @@ QEMU running, an old receipt, or missing evidence never yields installed success There is no ongoing guest agent. The minimal guest deliberately powers off after verification; this does not qualify a production distribution or workload. +The installer also accepts `fleet.mode=wipe`, which zeroes and verifies the disk. +Only the [Redfish mode](redfish-lab.md) boots it; this harness never selects it, +and its install path is unchanged. + Reinstall creates a new blank disk and a new receipt under the same allocation. Prior incarnation disks remain private until cleanup; they are never booted or exposed to another consumer. Cleanup deletes only retained disks for that exact diff --git a/docs/operations/multiplane.md b/docs/operations/multiplane.md index bb097fff..f521f59a 100644 --- a/docs/operations/multiplane.md +++ b/docs/operations/multiplane.md @@ -16,6 +16,10 @@ composition. The shared lifecycle adds only the read-only `Coordinator.ClaimReleased` custody query, and the executor interface documents exact-request replay and its narrow not-found-plus-Unknown lookup contract. +The [Redfish mode](redfish-lab.md) (`task multiplane:redfish-acceptance`) runs the +same composition with a Redfish executor. Its workers have no libvirt socket and +reach two persistent lab VMs only through the DMTF Redfish Interface Emulator. + ## Topology and versions | Surface | Local implementation | Writer | diff --git a/docs/operations/redfish-lab.md b/docs/operations/redfish-lab.md new file mode 100644 index 00000000..08446eb4 --- /dev/null +++ b/docs/operations/redfish-lab.md @@ -0,0 +1,624 @@ +# Redfish-mode acceptance with the DMTF Redfish Interface Emulator + +This opt-in mode of the [multi-plane acceptance](multiplane.md) replaces the +cell worker's libvirt path with a Redfish executor. Workers reach two persistent +lab VMs only through the DMTF Redfish Interface Emulator and a small lab-only +adapter. Everything else is the existing pipeline: + +- native Milo project APIs; +- the shared allocator and installation lifecycle; +- Karmada delivery and reflection; +- kro-created per-operation Jobs; +- Flux-owned shared services. + +It is a **local MVP proof**, not hardware qualification. No physical server, BMC, +vendor Redfish implementation, UEFI firmware, TLS or production secret store +was involved. See [what remains unqualified](#limitations-and-physical-hardware-readiness). + +```sh +task multiplane:redfish-acceptance +# equivalent: +FLEET_MULTIPLANE_INOTIFY=1024 hack/multiplane/run.sh --redfish +``` + +Prerequisites, exit codes, the state and evidence layout, `--keep`, +`--leave-running`, `stop.sh` and `teardown.sh` are those of the +[multi-plane harness](multiplane.md#run). Redfish mode also needs network access +to GitHub release archives, Docker Hub and PyPI to build the lab BMC image. + +## Upstream emulator and provenance + +| Item | Pin | +| --- | --- | +| Project | [DMTF Redfish-Interface-Emulator](https://github.com/DMTF/Redfish-Interface-Emulator), BSD-3-Clause | +| Version | Release `1.2.2` (2025-09-12), commit `5f51d8ac48e46665a2a85242434f125aa7b25172` | +| Source archive | `https://github.com/DMTF/Redfish-Interface-Emulator/archive/refs/tags/1.2.2.tar.gz`, SHA-256 `acee609abaedaf123b56e7ca5b2534da94bdee6fc1183dde72699c30d63de79f`, verified by `hack/redfish-lab/upstream.sh` before extraction | +| Python | `python:3.12.12-slim-bookworm@sha256:593bd06efe90efa80dc4eee3948be7c0fde4134606dd40d8dd8dbcade98e669c` | +| Python packages | Exact versions with every PyPI file hash in `hack/redfish-lab/requirements.lock`, installed with `pip --require-hashes --no-deps` (Flask 2.3.3, Werkzeug 2.3.8, Flask-RESTful 0.3.10 and their dependencies). Upstream's `requirements.txt` lists names only. | +| libvirt client | Debian `libvirt-clients` from apt, used only by the adapter. This apt resolution is not reproducible, the same caveat as the site image. | + +The 1.2.2 release was 14 months old at integration and is the newest release. +The emulator tree is copied into the image **unmodified**. Configuration comes +from Fleet files: `emulator-config.json`, an infragen `populate-config.json` +with one chassis and two Systems, and `targets.json`. The image ID, its registry +digest and the archive provenance are recorded in `evidence/image-id` and +`evidence/redfish-upstream.json`. + +**No OpenStack component is used.** The image contains no Sushy, sushy-tools, +Ironic or VirtualBMC. The Fleet executor's Redfish client is built on gofish +([BMC client library](#bmc-client-library)). `hack/multiplane/test-redfish.py` +fails if any of these names appears in the lock file, adapter or image +definition. + +### What upstream provides and what the adapter adds + +Inspection of the 1.2.2 source found these limits: + +- `ComputerSystem.Reset` only rewrites an in-memory `PowerState`. +- A System PATCH accepts only `Name`, `HostName`, `AssetTag`, `SerialNumber` + and `UUID`, so it rejects `Boot`. +- `flask_httpauth` is listed but never used, and `AccountService` hard-codes + accounts. **No request is authenticated.** +- `DELETE /redfish/v1/reset` resets the whole emulator. + +The adapter is `hack/redfish-lab/fleet_lab_adapter.py`. It imports the upstream +`emulator` module into the same Flask process and registers request hooks; it +does not fork or patch upstream files. + +| Concern | Served by | +| --- | --- | +| Service root, Systems collection and members, Chassis, Managers, ActionInfo, routing and JSON serialization | Upstream, unmodified | +| HTTP Basic authentication against a mounted credential (the service root stays anonymous, per the Redfish specification) | Adapter | +| `ComputerSystem.Reset` with `On`, `ForceOff` and `ForceRestart` applied to one exact persistent libvirt domain per System | Adapter (replaces upstream's in-memory handler for the two lab Systems) | +| `PowerState` read from libvirt on every System read | Adapter | +| `Boot` source override (`Pxe` or `Hdd`, `Once`), persisted in NVRAM state on the site volume and consumed at power-on | Adapter | +| `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 | +| `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 | + +`hack/redfish-lab/test_adapter.py` runs inside the built image, with the real +upstream emulator and a fake `virsh`, in the `bmc-self-test` phase. + +## Topology on the selected cell + +```text + cell Flux layers (Redfish overlays of config/site) + fleet-site-runtime (privileged) fleet-site-bmc (unprivileged, all caps dropped) + libvirtd + QEMU TCG ◀── libvirt socket ── DMTF emulator 1.2.2 + lab adapter + lab-target-a lab-target-b ▲ Redfish over HTTP, Basic auth + (persistent disks, serial capture) │ Service 10.96.0.81:8000 + │ firmware DHCP/iPXE (static) │ + ▼ │ + fleet-site-boot (journal read-only) kro worker Job (per handoff, Redfish only) + per-MAC chain, artifacts journal rw, boot evidence ro, + console capture ro, BMC credential +``` + +| Component | Owner | Holds | +| --- | --- | --- | +| `fleet-site-runtime` Deployment | Flux `fleet-site-services` (Redfish overlay) | libvirtd and QEMU; creates the two 2 GiB target disks once on the retained volume (`lab-disks`) and the console capture directory (`lab-console`) | +| `fleet-site-bmc` Deployment and Service (fixed ClusterIP `10.96.0.81`) | Flux `fleet-site-services` | The emulator and adapter; the libvirt socket, NVRAM and audit (`bmc-state`), and the credential Secret | +| `fleet-site-bmc` ServiceAccount | Flux `fleet-site-base` (Redfish overlay) | No API token | +| `fleet-site-bmc-credentials` Secret | Created by the harness in the `redfish-enroll` phase; in no source revision or Flux inventory | A synthetic username and a random 256-bit password per run | +| Boot service and observer | Flux, as before | The Redfish read-only provider; no credential | +| `w-` Job, ServiceAccount, Role, RoleBinding | kro, as before | The Redfish worker; **no libvirt socket**, no lab disks | + +Flux selects the overlays with the same source revision: in Redfish mode the +staged cell environment points `fleet-site-base`, `fleet-site-graph` and +`fleet-site-services` at `config/site/redfish/*`. Shared objects are still owned +by exactly one Flux layer, and kro still writes only per-operation objects. The +ownership audit covers the BMC Deployment, Service and ServiceAccount. + +### Lab targets: identity before allocation + +| Target | Redfish System | UUID | NIC MAC / lease | Fleet asset | Role | +| --- | --- | --- | --- | --- | --- | +| A | `System-1` | `7f3d0c2e-…-0a1b2c3d4e0a` | `52:54:00:77:01:0a` / `.10` | `…/Device/synthetic-device-central-01` | The only published capacity | +| B | `System-2` | `7f3d0c2e-…-0a1b2c3d4e0b` | `52:54:00:77:01:0b` / `.11` | `…/Device/synthetic-device-central-02` | Enrolled, never allocated; proves target isolation | + +The disks, domain UUIDs and MACs exist before any allocation. Each installation +or cleanup reuses target A's single persistent disk. The site enrollment is an +explicit asset-to-System mapping in the worker template, with the endpoint, +System Id, UUID, MAC, disk size and console capture name. The executor writes it +once into the journal directory and refuses a changed enrollment later. + +## Redfish executor contract + +`internal/redfish` implements `executor.Client` behind the unchanged +`LocalAssetMapping`, coordination and lifecycle code. It has no process +execution, libvirt client or lab dependency. A Go test parses its imports to +enforce this. `Open` refuses a `FLEET_LIBVIRT_URI` and a mounted +`/run/fleet-libvirt`, so a Redfish worker has no hypervisor fallback. + +**Discovery (GETs only).** The executor walks the service root to the Systems +collection and reads every member. Exactly one member must carry the enrolled +UUID, and it must have the enrolled Id. A member with the enrolled Id and +another UUID is a renumbered or swapped target and is refused. The reset target +and ActionInfo must belong to that System. `On`, `ForceOff`, `Pxe` and `Hdd` must +be advertised, and `Once` too when the System advertises its enabled values. It +never follows redirects or `@odata.id` paths outside `/redfish/v1`. A rejected +credential, a missing capability or an identity mismatch leaves the operation +`admitted`, Unknown and effect-free. + +**BMC client library.** See [BMC client library](#bmc-client-library) for +which requests go through gofish and which helpers are deliberately not used. + +**Exact inputs before effects.** The journal retains these before any Redfish +request, under the same lock and fencing rules as the libvirt provider: + +- the exact request and its digest; +- the enrolled target; +- a random receipt and boot capability, with a 20-minute boot window; +- allocation epoch, binding and fence. + +The discovered System is retained before the first effect. + +**Phases.** An install is a network-boot installer phase (`Pxe`) followed by a +disk-boot phase (`Hdd`). A cleanup is one network-boot wipe phase. Each phase +proceeds in order: + +1. Power off if needed. This is idempotent, because nothing of the phase has + booted. +2. Arm a one-time override and read it back. +3. Retain `-requested`, then `POST Reset On`. +4. Observe until the phase may have started. +5. Wait for the exact receipt and power off. + +**Lost responses and recovery.** HTTP success is never evidence. Any sign of a +boot is treated as "may have run", and the phase is never requested again: + +- power not `Off`; +- the one-time override consumed; +- a boot delivery for the operation; +- a receipt. + +A repeated `On` is sent only when the target is still `Off`, still armed and +silent after a 45-second settle window, within three retained attempts. + +**Completion.** A phase completes only with exactly one console line +`FLEET-INSTALLED:`, `FLEET-DISK-BOOT:` or +`FLEET-WIPED::`, and power `Off`. A second identical receipt +means a duplicate execution and fails rather than succeeding. The installer +phase also requires completed boot deliveries of the script, kernel and initrd; +boot admission then closes durably. Worker exit codes and the +Job/observer/management split are unchanged: +[exit 0 never implies readiness](site-execution.md#authority-and-failure-contract). + +**Cleanup uses a booted environment.** The wipe environment is the same pinned +kernel and initrd with `fleet.mode=wipe`. It zeroes the whole disk with `dd`, +drops caches, compares every byte with `/dev/zero` and only then prints its +receipt. The harness independently hashes target A's disk file as all zeroes +after the final cleanup. This is **logical test cleanup of a virtual disk, not +media sanitization**: it does not address SSD remapping, over-provisioning, HPA +or DCO areas, firmware caches or crypto-erase. + +## BMC client library + +`internal/redfish/client.go` uses +[gofish](https://github.com/stmcginnis/gofish) **v0.27.0** (2026-10-05, the +newest release at adoption, BSD-3-Clause, no transitive module dependencies). It +replaced the handwritten `net/http` request helper and the `map[string]any` +decoding of the service root, Systems collection and ComputerSystem. The +provider (`provider.go`) is unchanged: it still owns validation, the journal, +sequencing, recovery and results, and calls the same `Discover`, `Observe`, +`SetBootOnce` and `Reset` methods. + +**What gofish provides here:** + +- the HTTP client: basic authentication, JSON requests and Redfish error + decoding (`schemas.Error` status codes); +- typed `ComputerSystem` decoding: `Id`, `UUID`, `@odata.id`, `PowerState`, + the boot override and its target `AllowableValues`, and the ETag; +- Systems collection walking, including `Members@odata.nextLink` pages. The + previous client read only the first page, so a duplicate UUID on a later + page went unseen; discovery now reads every page, and a partially read + collection fails discovery. + +**What Fleet still does itself, and why:** + +- **Transport guard.** Every request passes a Fleet `RoundTripper`: the + configured scheme and host only, paths under `/redfish/v1` without `..`, no + query on a mutation, `OData-Version: 4.0`, and a 1 MiB response bound. A + link returned by the BMC cannot send the credential elsewhere. Redirects are + never followed. The environment proxy is not used, so the credential goes + only to the enrolled endpoint. TLS uses the system trust store; there is no + certificate pinning or private CA yet. The endpoint must still be a literal + `http(s)://IPv4:port`. +- **Identity and capability checks.** These are unchanged: one UUID match + across all members with the enrolled Id, a reset target and ActionInfo on + that System, and `On`, `ForceOff`, `Pxe`, `Hdd` and `Once` checked against + advertised values. +- **ActionInfo and Reset annotations.** gofish keeps the reset target, the + ActionInfo link and the `BootSourceOverrideEnabled` allowable values in + unexported fields, so Fleet reads them from the System's raw JSON. + ActionInfo is decoded leniently: gofish's typed `ActionInfo` rejects the + DMTF emulator 1.2.2 document, whose `"Required": "true"` is a string. +- **Error classification.** Errors collapse to credential rejected, + unsupported, identity, precondition failed, HTTP status, or + transport/unreadable response. They never carry a URL, header or response + body. +- **Mutations.** Each is exactly one request, issued through gofish's raw + `PatchWithHeaders` and `PostWithHeaders`. Audited gofish helpers that are + **not** used: + - `ComputerSystem.SetBoot` sends a second PATCH to the `@Redfish.Settings` + resource when the first fails, which could be a lost response. + - `ComputerSystem.Reset` (via `PostWithTask`) resends without `If-Match` + after a 412. + - Sessions (`CreateSession`) would be a BMC mutation with its own lifetime + and cleanup. Basic authentication is used instead, as before. + + The boot override PATCH now carries `If-Match` with the ETag observed + immediately before it, when the BMC returns one. A 412 is reported as + `ErrPrecondition` and not retried. The operation stays Unknown before the + boot is requested, and the next attempt re-observes and re-arms; this is + pre-boot and idempotent, as before. Reset POSTs carry no `If-Match`. A 202 + task monitor is not followed: power and boot state are observed, as before. + +**bmclib was evaluated and not adopted.** bmclib v2.3.5 (2026-03-22, the +newest release) was rejected for these reasons: + +- It pins gofish v0.20.0, whose API is incompatible with v0.27.0, so both + libraries cannot be used together. +- Its Redfish provider selects a System by index or name, not by UUID. +- Its `SystemBootDeviceSet` retries a failed PATCH with fewer fields. +- `SystemPowerOn` skips the request when the System already reports `On`. + This is incompatible with Fleet's recorded-request recovery. +- Its `bmc` power facade tries the next provider after an error. + +Its vendor providers (Dell, Supermicro, ASRockRack, OpenBMC, IPMI) target BIOS, +firmware and virtual-media work that this executor does not perform. **No +vendor-specific compatibility is added by this change.** It reuses a +maintained Redfish client and schema model. It also fixes collection paging +and adds `If-Match` on the boot override. + +**Known compatibility risks to qualify:** + +- **Strict decoding.** gofish decodes the whole ComputerSystem strictly. A + vendor property with an off-schema type fails discovery and observation as + "unreadable response", with no effect issued. The emulator's System decodes + cleanly. +- **`If-Match` rejection.** gofish documents that some BMCs reject `If-Match` + on some endpoints, for example Dell iDRAC10. On such a BMC arming fails + visibly as Unknown instead of sending an unconditional PATCH. Changing that + is a per-vendor decision for qualification. + +## Synthetic credentials and networking + +These are documented lab seams, not production designs: + +- **Credential.** HTTP Basic over plain HTTP on the cell network, with one + synthetic per-run credential shared by the adapter (server side) and Redfish + workers (client side). There is no TLS, rotation, vault or per-BMC account. + The Secret is never in Git, a source revision or evidence. The harness keeps + the password in a `.token` file so the evidence secret scan covers it. Worker + and harness logs print outcome classes only. +- **Provisioning network.** The adapter defines one static libvirt network. + dnsmasq gives each enrolled MAC a fixed address and the same boot file. That + iPXE script chains to `/pxe/${net0/mac:hexhyp}/boot.ipxe`. The boot service + serves a script only to the MAC of a retained operation with open admission. + The MAC is routing information, not authentication: a peer on this network + could impersonate it during the window, and the capability URLs travel in + clear. +- **Receipts.** The worker reads the target's serial-console capture read-only, + as a stand-in for serial-over-LAN or an installer callback. It is observation, + not control. +- **Admission.** The Redfish overlay's admission policy limits kro worker Jobs + to the journal claim, `emptyDir` and the BMC credential. It denies a + `libvirt*` subPath, `/run/fleet-libvirt` or lab-disk mount and a + `FLEET_LIBVIRT_URI`, and requires `FLEET_SITE_PROVIDER=redfish`. The `rbac` + phase proves each denial as kro's identity, and evidence re-checks every real + worker Job spec. + +## Acceptance phases + +`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. + +**Before topology:** + +- `bmc-upstream` fetches and verifies the pinned archive; +- `bmc-image` builds the lab BMC image; +- `bmc-self-test` runs the adapter self-test with no network. + +**Before Flux installs the shared services:** `redfish-enroll` creates the +synthetic credential Secret. + +**Redfish phases:** + +| 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-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 verified cleanup and reuse, consumer B installs on the same physical target in epoch 2 with a new receipt | +| `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 + `bootindex`), and none of target B. +- **BMC audit.** Exactly six 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 + hypervisor path. + +Redfish-specific evidence files are `redfish-upstream.json`, +`redfish-enrollment.json` (no password), `redfish-discovery-faults.json`, +`redfish-lost-response.json`, `redfish-bmc-interrupt.json`, +`redfish-isolation.json` and `redfish-audit.jsonl`. `summary.json` records the +`physicalHardware`, `physicalBMC`, `vendorRedfishQualified`, `bmcTLS` and +`mediaSanitization` flags as `false`. + +## Offline checks + +```sh +go test -race -count=1 ./internal/redfish ./cmd/fleet-multiplane ./internal/multiplane +task multiplane:test-harness # includes hack/multiplane/test-redfish.py +``` + +The Go tests use a fake BMC whose fake guest fetches its script and artifacts +from the real boot handler and writes console receipts. They cover: + +- install, disk boot, cleanup and reuse; +- exact replay; +- a rejected credential, unsupported reset and renumbered or swapped UUIDs, + each with no effect; +- a lost response after the effect, recovered without a repeat; +- a lost request repeated exactly once; +- duplicate receipts and identity change failing; +- changed-retry conflict, stale-epoch fencing and an unenrolled asset; +- journal-lock exclusion; +- boot scoping by MAC, capability, admission and fence; +- refusal of libvirt configuration, and the import-graph guard. + +`client_test.go` covers the gofish-backed client against a recording stub: + +- discovery across a paged Systems collection; +- a duplicate UUID on a later page refused; +- an unreadable, rejected, foreign or cross-host member refused, with no + mutation; +- a reset target or ActionInfo off the System, or no `Once`, refused; +- an oversized response refused; +- the boot override sent as one PATCH with the observed `If-Match`; +- a 412 or 500 not retried and never redirected to the Settings resource; +- a Reset that gets 412, 503 or no response before the timeout sent exactly + once, without `If-Match` or a session; +- an untrusted TLS certificate refused; +- no environment proxy; +- no credential, response body or endpoint in any error. + +The provider's fake BMC serves the emulator's string `"Required"` in +ActionInfo. + +`test-redfish.py` renders the overlays and a staged Redfish revision with +kustomize and checks the following: + +- worker mounts and environment; +- privilege and socket holders; +- enrollment matching `targets.json`; +- variable substitution; +- phase coverage; +- that no fault hook appears in `internal/redfish`; +- source pins, and no OpenStack dependency. + +## Execution record + +### Attempts before the first pass (2026-11-16) + +Every attempt below was a fresh topology owned by this task. Each failure was +inspected from its retained private state, including the stopped cell node's +volume read with `docker cp` and no restart. Each was then discarded with +`teardown.sh --discard-unknown`, which is **not release evidence**. No Unknown +operation was reset or declared ready. + +1. **`fleet-mp-8a37c720`** failed in `milo-bootstrap`, before any allocation or + effect. The new `$state/provider` mode marker collided with the Milo provider + project's credential directory. The marker is now `$state/site-provider`, and + `test-redfish.py` guards it. +2. **`fleet-mp-24371388`** failed in `interrupt-pod` after 37 phases had passed, + including discovery faults and lost-response recovery on the installer `On`. + The real PXE install (one network start, one `On`, an exact receipt) took + about 47 seconds, which left no window for the worker interruptions. The BMC + interruption now runs as soon as the installer starts, and the lost-response + fault targets the disk-boot `On`. +3. **`fleet-mp-052586a6`** failed in `release` after 50 phases. The wipe + environment zeroed the disk, but `cmp -n 2147483648` was rejected (`not in + 0..2147483647`). The guest therefore printed no receipt and powered off, and + the worker kept the cleanup Unknown and retried without inferring success. +4. **`fleet-mp-90c15839`** failed the same way. The chunked `cmp -i` fix had been + tested with GNU `cmp`, but the guest's static BusyBox shell runs its own + applets first, and BusyBox `cmp` has no `-i`. The verifier now calls + `/bin/busybox cmp -n 1GiB … SKIP1 0` per chunk, tested against Debian's + BusyBox 1.35 for a clean disk and for a dirty byte in either GiB. Again no + receipt was printed and the cleanup stayed Unknown. +5. A launch exited 2 in preflight, with 11.6 GiB free against the 12 GiB gate, + and created nothing. Teardown had not removed the new BMC image tags. It now + does, and `test-redfish.py` checks it. This task's leftover BMC tags and + unused build cache were removed. +6. **`fleet-mp-836a521e`** failed in `delivery-faults` after 54 phases. The + booted wipe cleanup, release projection and reuse had passed. Three fault + Jobs started together, and one worker's `redfish.Open` lost the non-blocking + journal lock while recording the enrollment, exiting 1 before validating its + delivered authority. Its retry then failed by policy with 65. Enrollment is + now retained by an atomic create-by-link and an unlocked compare, and a Go + test opens eight workers concurrently while another holds the journal lock. + No effect was issued for any fault handoff. + +7. **`fleet-mp-f7008e93`** failed in `flux-bootstrap-hub`, before any fixture or + effect. The hub node's pulls of the digest-pinned Flux controller images from + `ghcr.io` hit `DeadlineExceeded`, a transient external network failure. The + stopped hub node was started only to read its Pod events. + +8. **`fleet-mp-17555913`** failed in `redfish-bmc-interrupt` after 33 phases. Run + right after dispatch, the step read the journal before the first worker had + created it, and treated the absent file as fatal. The wait now treats an + absent journal as not yet started. The install was in flight when the run + stopped; its custody was Unknown. + +9. **`fleet-mp-5c4ce7c2`** passed 62 of 63 phases, including every Redfish, + federation, Flux, release, reuse, reinstall and isolation phase. Target B + never started and its disk digest was unchanged, and target A's disk hashed + as all zeroes after six boots and twelve Redfish effects. It failed in the + final `evidence` phase: a reworded `redfish-baseline` message no longer + matched its evidence marker. `test-redfish.py` now checks that every + Redfish evidence marker is printed by a phase. This run is not counted as a + pass. + +Attempts 1 to 4 used the original `net/http` client; attempts 6 to 9 used the +gofish client. + +### Fresh pass (2026-11-16) + +`FLEET_MULTIPLANE_INOTIFY=1024 hack/multiplane/run.sh --redfish` (the command +behind `task multiplane:redfish-acceptance`) exited 0, with the readiness test +gate enabled, which includes `./internal/redfish`. Run details: + +- state `/tmp/fleet-multiplane.NryZRD`, prefix `fleet-mp-34dd4bcc`; +- all 65 bounded phases passed in 34 minutes (22:20 to 22:54 UTC); +- SHA-256 of `source-SHA256SUMS` (177 entries): + `6409311d0af13cdffeb09333b3ef7822c25b296b20ed4c06214349c5e9ee0963`; +- site binary `f0ddaf41…`, host binary `b43045e0…`; both use the gofish client; +- site image `sha256:d8e874680f7ee6f047a0cf03f85b25270ec13df1f381448b8c2f7dd5e1e3c24b`; +- lab BMC image `sha256:e4cd737b991570b8f2e6ac373ada523b18bafbd560bebca466851017fdbc0f55`; +- both pulled by the cell by registry digest; +- seven Flux source revisions from the dirty checkout at HEAD `d7ff793b`. + +After the run, `teardown.sh` was changed to also delete the run's synthetic BMC +credential file after a pass, and `test-redfish.py` gained checks for that. +This run's teardown had removed every container, cluster and image tag but left +that file, which was deleted by hand. No other fingerprinted file changed. + +Only `evidence/` is shareable. It holds `summary.json`, `result.json`, +`phases.jsonl`, the `redfish-*.json` files, `redfish-audit.jsonl` and the files +listed for the multi-plane harness. The facts below come from that evidence. + +- **Upstream and authentication.** The pinned emulator archive was verified, + and the image self-test passed. Live discovery through the production client + found `System-1` and `System-2` exactly. A wrong credential exited 10, the + swapped and unknown UUIDs exited 12, and an injected unadvertised `On` exited + 11. Those 38 requests were GETs only, one of them rejected. +- **Install with interruptions.** The BMC Pod was force-deleted at + `installer-started` and replaced while the guest kept running. The worker Pod + was then force-deleted, and the Job controller replaced it. The Job was + deleted mid-installer, and kro recreated it. +- **Lost response.** The disk-boot `On` took effect, but its response was + withheld for 45 seconds. The worker exited 75. Its replacement observed the + consumed override and powered target and did not repeat the `On` + (`powerOnRequests` = one installer and one disk request). +- **Partition and federation.** As in the libvirt mode, partition kept public + Ready False with the Job Complete. Heal, idempotent install and lifecycle + recreation passed. Graph lifecycle, drift repair, controller restart, + fail-closed and retention passed with the BMC included in the ownership + audit. Nine reflection faults were rejected. +- **Cleanup and reuse.** Consumer A's cleanup PXE-booted the wipe environment. + Consumer B reused the target in epoch 2, installed on it with a new receipt, + and was cleaned the same way. Release projection was verified for both. +- **Delivery faults.** The duplicate, wrong-cell and stale-epoch deliveries each + failed once with exit 65 by `podFailurePolicy`, with the journal unchanged, + and kro pruned them. Wrong location was denied with free capacity. +- **Closed boot.** 24 live HTTP denials covered the closed per-MAC scripts and + capabilities of all four operations, target B's MAC and unknown identities. +- **Independent checks.** + - Target A's console held exactly one receipt per boot in operation order. + - libvirt logged six target A starts: network, disk, network, network, disk, + network. + - The BMC audit shows exactly twelve effects, all to System-1: six one-time + overrides and six effective `On` requests, one of them faulted. + - Target B had no start, no console line, no effect and an unchanged disk + digest. Target A's disk hashed as all zeroes. + - All four worker Jobs, created by kro, selected the Redfish provider with no + libvirt mount or URI. + - Admission denied the libvirt socket, lab disk, libvirt URI, libvirt-provider + and foreign-Secret worker shapes, and admitted the Redfish worker shape. +- **Memory, secrets and teardown.** There were zero OOM kills. 40 evidence files + were clean against 27 retained secrets, including the BMC password. Teardown + removed every `fleet-mp-34dd4bcc` container, cluster and image tag, and + restored inotify to 128. + +This proves the composed pipeline against an emulator and lab VMs. It is not +an independent review, and it does not qualify any physical BMC or server. + +### Repeat pass (2026-11-17) + +The same command was rerun on a fresh topology and exited 0. Run details: + +- state `/tmp/fleet-multiplane.MF4gq9`, prefix `fleet-mp-717e7e96`; +- all 65 bounded phases passed in 34 minutes (23:53 to 00:27 UTC); +- SHA-256 of `source-SHA256SUMS` (177 entries): + `c560df28646c1fe2f9b5315886ffe0f9a12fca20c6703c8af10be849ac850023`; +- site binary `f0ddaf41…` and host binary `b43045e0…`, identical to the first + pass, so the executor and its gofish client are unchanged; +- site image `sha256:b484df32c64072896d019e38ed31d065daeb3d9a1d775fc47a5a6681111a6dc4`; +- lab BMC image `sha256:10b8bbb739a4288e734b3a515adb2a92c8fbd1c3170b9ebeab5fc0d74568e935`. + +The evidence shows the following: + +- **Discovery probes.** They matched the first pass: both Systems were found, + with ResetTypes read from the emulator's ActionInfo. The probes exited 10, + 12, 12 and 11 for the injected faults, with no effect. +- **Lost response.** The lost disk-boot `On` was recovered without a repeat + (`powerOnRequests` = one installer and one disk request). +- **Isolation.** Target B received no effect, and target A's disk hashed as + all zeroes. +- **BMC audit.** It recorded 589 GET 200, 6 PATCH 200, 6 POST 204 and one GET + 401. There were no 412 or 5xx responses and no session creation. The + emulator sends no ETag, so `If-Match` was not exercised. +- **Teardown.** This time teardown itself removed the synthetic BMC + credential file and left no containers. + +Physical hardware, physical BMC, vendor Redfish, BMC TLS and media +sanitization all remain `false` in `summary.json`. + +## Limitations and physical-hardware readiness + +These differences from physical hardware are known and **not** addressed by this +MVP. They are listed as an explicit qualification checklist: + +1. **Real BMC.** Qualify the executor against at least one vendor Redfish + implementation. Check ActionInfo and inline `AllowableValues`, the actual + reset semantics (some BMCs reject `On` while on, or report `PoweringOn`), and + whether `Once` overrides are consumed at POST. Check ETag/`If-Match` + behavior on the boot override PATCH (a 412 is never retried + unconditionally), strict gofish decoding of the vendor's ComputerSystem, + session (`X-Auth-Token`) authentication and rate limits. +2. **UEFI.** Only legacy BIOS (SeaBIOS) PXE is exercised. Verify + `BootSourceOverrideMode`, UEFI PXE or HTTP boot, Secure Boot policy and boot + order persistence. +3. **Receipts.** Replace the read-only console capture with serial-over-LAN or + an authenticated installer callback, and decide its trust model. +4. **Credentials and transport.** TLS with pinned CA or certificate, per-BMC + accounts, a credential broker so workers never hold a long-lived password, + and rotation and revocation. +5. **Provisioning network.** Integrate with the networking/IPAM owner: per-host + DHCP or a dedicated provisioning VLAN, and authentication beyond MAC. +6. **Cleanup assurance.** Use vendor or NIST SP 800-88 sanitization (secure + erase, crypto-erase, sanitize commands) with verifiable device evidence. + Distinguish it from this logical overwrite. +7. **Power semantics.** Physical power transitions take longer, may fail and may + report intermediate states. Revisit the settle window, the outage tolerance + and the three-attempt `On` budget. Revisit installer and disk-boot power-off + as the completion signal; a real OS reboots and keeps running. +8. **Fencing and journal.** One site journal fences all targets with one + allocatable target. Per-asset fencing, journal durability and HA are not + designed. Never reset the journal of a retained target + ([known limitations](multiplane.md#known-limitations-of-the-local-mvp)). +9. **Enrollment.** The asset-to-System mapping is a static source value. + Enrollment trust, BMC discovery and attestation of the System identity + (beyond Id and UUID) are open. +10. **Operator recovery.** Unknown operations, for example a power-off without + a receipt or an exhausted `On` budget, have no automated resolution. The + only recovery is to discard the disposable topology after inspection. + +The existing local-MVP limitations also apply: single node, trusted graph and +service authors, and no image upgrade lifecycle. diff --git a/docs/operations/site-execution.md b/docs/operations/site-execution.md index 0bf57f76..440a417d 100644 --- a/docs/operations/site-execution.md +++ b/docs/operations/site-execution.md @@ -359,7 +359,8 @@ container and is unchanged. | Pod/Job lifecycle not changing journal, guest or allocation | Implemented and exercised | | Facility-edge DaemonSet, multi-node volumes, HA runtime, live hardware fencing | Proposed only | | Removing the fence token from cell-readable handoff fields (credential broker) | Proposed only ([open questions](../enhancements/pxe-installation/README.md#open-design-questions)) | -| Redfish/BMC execution Jobs | Not implemented | +| Redfish execution Jobs 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) for its run record | +| Physical Redfish/BMC execution Jobs | Not qualified (lab emulator only; see the [hardware readiness checklist](redfish-lab.md#limitations-and-physical-hardware-readiness)) | ## Independent review of the recorded run diff --git a/go.mod b/go.mod index af7cc58f..7c6a7425 100644 --- a/go.mod +++ b/go.mod @@ -3,6 +3,7 @@ module go.datum.net/fleet go 1.26.4 require ( + github.com/stmcginnis/gofish v0.27.0 go.datum.net/network-services-operator v0.28.5-0.20260925153938-d7fdc43f8524 go.miloapis.com/milo v0.36.9 go.yaml.in/yaml/v3 v3.0.4 diff --git a/go.sum b/go.sum index 1570cd1b..7bf58041 100644 --- a/go.sum +++ b/go.sum @@ -140,6 +140,8 @@ github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiT github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk= github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/stmcginnis/gofish v0.27.0 h1:jyM2BlBhULXtHnayY+/wnkZYXKjIO0ZdR3oBXKl1VYs= +github.com/stmcginnis/gofish v0.27.0/go.mod h1:PzF5i8ecRG9A2ol8XT64npKUunyraJ+7t0kYMpQAtqU= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.5.3 h1:jmXUvGomnU1o3W/V5h2VEradbpJDwGrzugQQvL0POH4= github.com/stretchr/objx v0.5.3/go.mod h1:rDQraq+vQZU7Fde9LOZLr8Tax6zZvy4kuNKF+QYS+U0= diff --git a/hack/local-vm/init b/hack/local-vm/init index fce1814a..a4303d6b 100644 --- a/hack/local-vm/init +++ b/hack/local-vm/init @@ -9,8 +9,31 @@ set -exo pipefail modprobe virtio_pci modprobe virtio_blk modprobe ext4 -for arg in $(cat /proc/cmdline); do case "$arg" in fleet.receipt=*) receipt=${arg#fleet.receipt=};; esac; done +mode=install +for arg in $(cat /proc/cmdline); do case "$arg" in fleet.receipt=*) receipt=${arg#fleet.receipt=};; fleet.mode=*) mode=${arg#fleet.mode=};; esac; done [ ${#receipt} = 64 ] || /bin/busybox poweroff -f +if [ "$mode" = wipe ]; then + # Redfish-mode cleanup environment: zero the whole disk, then verify by + # reading it back. The receipt is printed only after the readback compared + # equal. This is a logical overwrite of a virtual disk, not media sanitization. + trap '/bin/busybox poweroff -f' EXIT + size=$(($(cat /sys/block/vda/size) * 512)) + dd if=/dev/zero of=/dev/vda bs=4M count=$((size / 4194304)) conv=fsync + sync + echo 3 > /proc/sys/vm/drop_caches + # This static BusyBox shell runs its own applets first. BusyBox cmp limits -n + # to INT_MAX and takes skips positionally: compare 1 GiB chunks at offsets. + off=0 + while [ "$off" -lt "$size" ]; do + n=$((size - off)); [ "$n" -le 1073741824 ] || n=1073741824 + /bin/busybox cmp -n "$n" /dev/vda /dev/zero "$off" 0 || exit 1 + off=$((off + n)) + done + printf 'FLEET-WIPED:%s:%s\n' "$receipt" "$size" + sync + exit 0 +fi +[ "$mode" = install ] || /bin/busybox poweroff -f printf 'label: dos\n, , L, *\n' | sfdisk /dev/vda mkfs.ext4 -F /dev/vda1 mkdir -p /target diff --git a/hack/local-vm/site-runtime b/hack/local-vm/site-runtime index 2d71dd70..3f85135c 100755 --- a/hack/local-vm/site-runtime +++ b/hack/local-vm/site-runtime @@ -17,6 +17,15 @@ iptables -t mangle -A FLEET-PXE -m addrtype --dst-type BROADCAST -j RETURN iptables -t mangle -A FLEET-PXE -d "$boot_ip" -p tcp --dport 8080 -j RETURN iptables -t mangle -A FLEET-PXE -j DROP iptables -t mangle -C PREROUTING -i fleetpxe0 -j FLEET-PXE 2>/dev/null || iptables -t mangle -A PREROUTING -i fleetpxe0 -j FLEET-PXE +if [ "${FLEET_SITE_PROVIDER:-libvirt}" = redfish ]; then + # Redfish mode: persistent lab targets. Their disks are created once on the + # retained volume and never recreated; the lab BMC adapter defines the + # domains and the provisioning network through this daemon's socket. + mkdir -p /var/lib/fleet-lab/disks /var/lib/fleet-lab-console + for t in target-a target-b; do + [ -e "/var/lib/fleet-lab/disks/$t.raw" ] || truncate -s 2G "/var/lib/fleet-lab/disks/$t.raw" + done +fi virtlogd --daemon virtlockd --daemon exec /usr/bin/tini -- libvirtd diff --git a/hack/multiplane/acceptance-redfish.sh b/hack/multiplane/acceptance-redfish.sh new file mode 100755 index 00000000..8dc89273 --- /dev/null +++ b/hack/multiplane/acceptance-redfish.sh @@ -0,0 +1,55 @@ +#!/usr/bin/env bash +# Ordered Redfish-mode acceptance phases (run.sh --redfish). The same +# allocator, installation, Karmada, kro and Flux path as acceptance.sh; the +# site worker drives lab targets only through the DMTF Redfish emulator. +# Each phase is bounded and recorded; the first failure stops the run. +set -euo pipefail +umask 077 +state=${1:?private state directory} +export DOCKER_CONTEXT=colima-fleet-acceptance-tcg FLEET_SITE_PROVIDER=redfish +host="$state/fleet-multiplane-host" +ph() { python3 hack/multiplane/harness.py phase --state "$state" --name "$1" --timeout "$2" --echo -- "${@:3}"; } +step() { ph "$1" "$2" bash hack/multiplane/steps.sh "$1" "$state"; } +rf() { ph "redfish-$1" "$2" python3 hack/multiplane/redfish_steps.py "$1" "$state"; } +flux() { ph "flux-$1" "$2" python3 hack/multiplane/flux.py "$1" "$state"; } + +ph rbac 600 python3 hack/multiplane/verify-rbac.py "$state" +rf baseline 300 +rf discovery-faults 600 +ph allocate 900 "$host" allocate --config "$state/acceptance.json" +step verify-contention 120 +ph admit-install 900 "$host" admit-install --config "$state/acceptance.json" +step await-delivery 300 +rf arm-lost-response 120 +step partition 300 +step dispatch 900 +rf bmc-interrupt 600 +step interrupt-pod 1200 +step interrupt-job 600 +rf lost-response 1200 +step resume 2400 +step worker-rbac 120 +step partition-readiness 900 +step heal 1200 +ph install 900 "$host" install --config "$state/acceptance.json" +ph install-repeat 900 "$host" install --config "$state/acceptance.json" +step lifecycle 900 +flux graph-lifecycle 1200 +flux drift 900 +flux restart 1200 +flux fail-closed 1500 +flux retention 1500 +ph reflection-faults 900 python3 hack/multiplane/reflection-faults.py "$state" +ph release 2400 "$host" release --config "$state/acceptance.json" +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" +ph release-b 2400 "$host" release-b --config "$state/acceptance.json" +step release-status-b 120 +step wrong-location 300 +step boot-denials 300 +step flux-final 900 +rf isolation 600 +ph evidence 600 python3 hack/multiplane/evidence.py "$state" diff --git a/hack/multiplane/evidence.py b/hack/multiplane/evidence.py index 95c96ee5..8d18e0b6 100755 --- a/hack/multiplane/evidence.py +++ b/hack/multiplane/evidence.py @@ -18,6 +18,7 @@ prefix = (s / 'prefix').read_text().strip() ev = s / 'evidence' os.environ['DOCKER_CONTEXT'] = 'colima-fleet-acceptance-tcg' +REDFISH = (s / 'site-provider').exists() and (s / 'site-provider').read_text().strip() == 'redfish' def out(*args): @@ -81,6 +82,11 @@ def copy_out(source, destination): 'flux-restart: every Flux controller', 'flux-fail-closed: absent kro chart digest', 'shared site layers applied it with services untouched', 'flux-retention: removing the volume claim', 'flux-final: platform, hub and cell Ready', 'one writer per site object') + tuple(m + ': management rejected' for m in ( 'wrong-cell', 'stale', 'duplicate', 'future', 'wrong-intent', 'wrong-digest', 'wrong-operation', 'incomplete', 'missing')) +if REDFISH: + 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 BMC credential Secret created', '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') for marker in markers: if marker not in phases: fail('missing acceptance phase: ' + marker) @@ -155,7 +161,90 @@ def libvirt_provider(): return ops, installs, cleanups, epochs, interrupt, receipts, starts, denials -ops, installs, cleanups, epochs, interrupt, receipts, starts, denials = libvirt_provider() +def redfish_provider(): + """Redfish mode: the persistent lab target A carries every operation. + Independent of the journal, its serial console proves one exact receipt + per boot, libvirt's QEMU log proves the boot order and count, the BMC + audit proves one On per boot, and target B never ran.""" + raw.mkdir(mode=0o700, exist_ok=True) + 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') + copy_out('/var/lib/fleet-lab-console', raw / 'lab-console') + j = json.loads((raw / 'journal.json').read_text()) + ops = sorted(j['operations'].values(), key=lambda o: o['result']['createdAt']) + installs = [o for o in ops if o['request']['kind'] == 'install'] + cleanups = [o for o in ops if o['request']['kind'] == 'cleanup'] + if j.get('provider') != 'redfish' or len(installs) != 2 or len(cleanups) != 2 or any(o['result']['phase'] != 'Succeeded' or o.get('stage') != 'done' for o in ops): + fail('expected the Redfish provider, two installs and two verified cleanups') + if [o['request']['kind'] for o in ops] != ['install', 'cleanup', 'install', 'cleanup'] or not j.get('closed'): + fail('expected install, cleanup, reinstall, cleanup with the final epoch closed') + epochs = sorted({o['request']['epoch'] for o in ops}) + if epochs != [1, 2]: + fail('expected allocation epochs 1 and 2, got %s' % epochs) + enrolled = json.loads((raw / 'enrollment.json').read_text()) + a = next(t for t in enrolled['targets'] if t['systemID'] == 'System-1') + for o in ops: + if o['target'] != a or o['system']['path'] != '/redfish/v1/Systems/System-1' or o['system']['uuid'] != a['systemUUID'] or not o.get('bootClosed'): + fail('an operation did not retain the exact enrolled target A System with closed boot admission') + interrupt = json.loads((ev / 'interrupt.json').read_text()) + if interrupt['operationID'] != installs[0]['request']['id'] or interrupt['stageAtInterrupt'] != 'installer-started' or not interrupt['domainRunningAtInterrupt']: + fail('interrupt evidence does not identify the retained install operation mid-installer') + console = [l.strip() for l in (raw / 'lab-console' / 'target-a.log').read_text(errors='replace').splitlines()] + expected, receipts = [], [] + for o in ops: + want = ['FLEET-INSTALLED:' + o['receipt'], 'FLEET-DISK-BOOT:' + o['receipt']] if o['request']['kind'] == 'install' else ['FLEET-WIPED:%s:%d' % (o['receipt'], a['diskBytes'])] + for line in want: + if console.count(line) != 1: + fail('expected exactly one exact console receipt %s for %s' % (line.split(':')[0], o['request']['kind'])) + expected.append(console.index(line)) + receipts.append({'operation': o['request']['id'], 'kind': o['request']['kind'], 'epoch': o['request']['epoch'], + 'receipts': [line.split(':')[0] for line in want], 'receiptSHA256': hashlib.sha256(o['receipt'].encode()).hexdigest()}) + log = raw / 'boot-evidence' / hashlib.sha256(o['request']['id'].encode()).hexdigest() / 'boot-delivery.log' + written = log.read_text() if log.exists() else '' + for name in ('boot.ipxe', 'kernel', 'installer.gz'): + if 'write-complete ' + name + ' bytes=' not in written: + fail('missing completed boot delivery of %s for %s' % (name, o['request']['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') + 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): + return any(a['mac'] in seg and ('"bootindex":1' in seg or 'bootindex=1' in seg) for seg in re.split(r'\s-device\s', 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) + 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 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') + if runtime('virsh', '--connect', 'qemu:///system?socket=/run/fleet-libvirt/libvirt-sock', 'list', '--name').strip(): + fail('a lab target is still running') + admission = json.loads((ev / 'kro-rbac.json').read_text())['admission'] + for case in ('Redfish worker mounting the libvirt socket', 'Redfish worker mounting the lab disks', 'Redfish worker with a libvirt URI', 'worker selecting the libvirt provider'): + if admission.get(case, {}).get('deniedBy') != 'ValidatingAdmissionPolicy': + fail('kro admission did not deny: ' + case) + if not admission.get('Redfish worker Job with the BMC credential', {}).get('admitted'): + fail('kro admission did not admit the Redfish worker shape') + for name in ('redfish-upstream.json', 'redfish-enrollment.json', 'redfish-discovery-faults.json', 'redfish-lost-response.json', 'redfish-bmc-interrupt.json', 'redfish-isolation.json'): + if not (ev / name).exists(): + fail('missing Redfish evidence ' + name) + denials = (s / 'boot-denials.txt').read_text().strip() if (s / 'boot-denials.txt').exists() else '' + if not denials.startswith('PASS'): + fail('missing live closed-boot HTTP denial evidence') + starts['redfishEffects'] = [{k: e.get(k) for k in ('method', 'path', 'status', 'resetType', 'boot', 'effect', 'fault')} for e in effects] + return ops, installs, cleanups, epochs, interrupt, receipts, starts, denials + + +raw = s / 'provider-private' +ops, installs, cleanups, epochs, interrupt, receipts, starts, denials = (redfish_provider if REDFISH else libvirt_provider)() # Kubernetes execution: what actually ran, as names, UIDs, phases and conditions. kro = kget('-n', 'kro-system', 'get', 'deployment')['items'] @@ -182,7 +271,17 @@ def libvirt_provider(): 'serviceAccount': job['spec']['template']['spec']['serviceAccountName'], 'podReplacementPolicy': job['spec'].get('podReplacementPolicy'), 'podFailurePolicy': job['spec'].get('podFailurePolicy'), 'backoffLimit': job['spec'].get('backoffLimit'), 'activeDeadlineSeconds': job['spec'].get('activeDeadlineSeconds'), 'createdBy': job['metadata']['labels'].get('kro.run/node-id')}) -if sorted(j['kind'] for j in worker_jobs) != ['cleanup', 'cleanup', 'install'] or any(j['createdBy'] != 'workers' for j in worker_jobs): +if REDFISH: + # Every Redfish worker that ran: Redfish provider, no hypervisor path. + for job in jobs: + pod = job['spec']['template']['spec'] + c = pod['containers'][0] + env = {e['name']: e.get('value') for e in c.get('env', [])} + 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']) +expected_jobs = ['cleanup', 'cleanup', 'install', 'install'] if REDFISH else ['cleanup', 'cleanup', 'install'] +if sorted(j['kind'] for j in worker_jobs) != expected_jobs or any(j['createdBy'] != 'workers' for j in worker_jobs): fail('expected kro-created worker Jobs for exactly one install and two cleanups, got %s' % [(j['kind'], j['createdBy']) for j in worker_jobs]) pvc = kget('-n', 'fleet-site', 'get', 'pvc', 'fleet-site-state') pv = kget('get', 'pv', pvc['spec']['volumeName']) @@ -212,7 +311,7 @@ def libvirt_provider(): } if execution['kro']['helmReleaseOwner'] != 'kro': fail('kro controller is not owned by the Flux HelmRelease') -if pv['spec']['persistentVolumeReclaimPolicy'] != 'Retain' or sorted(deployments) != sorted(['fleet-site-boot', 'fleet-site-observer', 'fleet-site-runtime']) or any( +if pv['spec']['persistentVolumeReclaimPolicy'] != 'Retain' or sorted(deployments) != sorted(['fleet-site-boot', 'fleet-site-observer', 'fleet-site-runtime'] + (['fleet-site-bmc'] if REDFISH else [])) or any( d['availableReplicas'] != 1 or d['fluxLayer'] != 'fleet-site-services' or d['kroLabels'] for d in deployments.values()): fail('site volume or Flux-owned shared Deployments not as expected') (ev / 'kubernetes-execution.json').write_text(json.dumps(execution, indent=2, sort_keys=True) + '\n') @@ -266,11 +365,27 @@ def libvirt_provider(): 'reflection faults injected with bootstrap credentials while the Karmada controller is stopped'], 'privateArtifacts': 'state directory outside evidence/ contains authority; do not publish', } +if REDFISH: + summary['qualification'].update(redfishExecutor=True, dmtfRedfishInterfaceEmulator='1.2.2 (unmodified) + lab-only libvirt adapter', bootedCleanupEnvironment=True, + physicalHardware=False, physicalBMC=False, vendorRedfishQualified=False, bmcTLS=False, mediaSanitization=False) + summary['scenarios']['cleanupAndReuse'] = {'epochs': epochs, 'installs': len(installs), 'cleanups': len(cleanups), 'reinstallOnReusedTarget': True, + 'cleanup': 'PXE-booted wipe environment zeroed and read back the whole 2 GiB virtual disk; the harness hashed the disk file as all zeroes. Logical test cleanup, not media sanitization.'} + summary['scenarios']['redfish'] = {'evidence': ['redfish-upstream.json', 'redfish-enrollment.json', 'redfish-discovery-faults.json', 'redfish-lost-response.json', + 'redfish-bmc-interrupt.json', 'redfish-isolation.json', 'redfish-audit.jsonl'], + 'bootOrderTargetA': starts['targetA'], 'targetBStarts': starts['targetB'], 'effects': starts['redfishEffects']} + summary['seams'] = [x for x in summary['seams'] if 'root libvirtd' not in x] + [ + 'DMTF Redfish Interface Emulator with a lab-only adapter in place of a physical BMC; libvirt/QEMU TCG VMs in place of servers', + 'plain-HTTP Basic authentication with a synthetic per-run credential Secret enrolled by the harness (no TLS, rotation or vault)', + 'static lab provisioning network (libvirt dnsmasq) with MAC-chained iPXE; MAC is routing, not authentication', + 'installation receipts read from a read-only serial-console capture (stand-in for SOL or an installer callback)', + 'trusted graph authors: worker Jobs hold the synthetic BMC credential; only the runtime and the lab BMC hold the libvirt socket', + 'one site journal fences every lab target (one allocatable target)'] (ev / 'summary.json').write_text(json.dumps(summary, indent=2) + '\n') for name in ('source-SHA256SUMS', 'sysctl.json'): if (s / name).exists(): (ev / name).write_text((s / name).read_text()) paths = [s / 'site-bin' / 'fleet-multiplane', s / 'fleet-multiplane-host'] (ev / 'binary-SHA256SUMS').write_text(''.join(hashlib.sha256(p.read_bytes()).hexdigest() + ' ' + p.name + '\n' for p in paths)) -(ev / 'image-id').write_text(out('docker', 'image', 'inspect', prefix + '-site-image', '--format', '{{.Id}}').strip() + '\nregistry digest ' + write_env['siteImageDigest'] + '\n') +(ev / 'image-id').write_text(out('docker', 'image', 'inspect', prefix + '-site-image', '--format', '{{.Id}}').strip() + '\nregistry digest ' + write_env['siteImageDigest'] + '\n' + ( + 'bmc image ' + out('docker', 'image', 'inspect', prefix + '-bmc-image', '--format', '{{.Id}}').strip() + '\nbmc registry digest ' + write_env['bmcImageDigest'] + '\n' if REDFISH else '')) print('evidence: sanitized summary ' + str(ev / 'summary.json')) diff --git a/hack/multiplane/flux.py b/hack/multiplane/flux.py index 30bac12f..1766e672 100644 --- a/hack/multiplane/flux.py +++ b/hack/multiplane/flux.py @@ -87,11 +87,19 @@ ('validatingadmissionpolicies', None, 'fleet-site-kro-worker-identity'): 'fleet-site-base', ('validatingadmissionpolicybindings', None, 'fleet-site-kro-worker-identity'): 'fleet-site-base'} # Exact inventories of the layers that must hold nothing else. -SITE_DEPLOYMENTS = ('fleet-site-runtime', 'fleet-site-boot', 'fleet-site-observer') +# Site provider: libvirt (default) or redfish, from run.sh --provider. Redfish +# mode selects the config/site/redfish overlays and adds the Flux-owned lab BMC. +PROVIDER = os.environ.get('FLEET_SITE_PROVIDER', 'libvirt') +BMC_SERVICE_IP = '10.96.0.81' +SITE_DEPLOYMENTS = ('fleet-site-runtime', 'fleet-site-boot', 'fleet-site-observer') + (('fleet-site-bmc',) if PROVIDER == 'redfish' else ()) +if PROVIDER == 'redfish': + SHARED.update({('deployments', SITE, 'fleet-site-bmc'): 'fleet-site-services', ('services', SITE, 'fleet-site-bmc'): 'fleet-site-services', + ('serviceaccounts', SITE, 'fleet-site-bmc'): 'fleet-site-base'}) LAYER_INVENTORY = { 'flux-system/fleet-site-services': sorted(['fleet-site_fleet-site-boot__Service', 'fleet-site_fleet-site-worker-policy__ConfigMap', 'fleet-site_fleet-site-runtime_apps_Deployment', 'fleet-site_fleet-site-boot_apps_Deployment', - 'fleet-site_fleet-site-observer_apps_Deployment']), + 'fleet-site_fleet-site-observer_apps_Deployment'] + ( + ['fleet-site_fleet-site-bmc__Service', 'fleet-site_fleet-site-bmc_apps_Deployment'] if PROVIDER == 'redfish' else [])), 'flux-system/fleet-site-graph': ['_fleet-handoff-dispatcher_kro.run_ResourceGraphDefinition'], 'flux-system/fleet-site-dispatch': ['fleet-site_dispatcher_site.fleet.datumapis.com_HandoffDispatcher'], } @@ -257,6 +265,13 @@ def stage(args): # Karmada-API Kustomizations live beside their kubeconfig Secret. maps.append(config_map('fleet-environment', 'karmada-system', data)) if cluster == 'cell': + if PROVIDER == 'redfish': + # Environment selection, as a commit would make it: the cell's + # site layers reconcile the Redfish overlays of the same source. + for layer in ('fleet-site-base', 'fleet-site-graph') + (('fleet-site-services',) if args.site != 'absent' else ()): + patches.append(child_path(layer, './config/site/redfish/' + layer.rsplit('-', 1)[1])) + if args.site != 'absent': + data.update(FLEET_BMC_IMAGE=env['bmcImage'], FLEET_BMC_SERVICE_IP=BMC_SERVICE_IP) if args.site != 'absent': resources.insert(2, '../../config/multiplane/clusters/cell-site') data.update(FLEET_SCOPED_ASSET=env['scopedAsset'], FLEET_SITE_IMAGE=env['siteImage'], FLEET_BOOT_SERVICE_IP=BOOT_SERVICE_IP, @@ -292,6 +307,11 @@ def stage(args): return 0 +def child_path(name, path): + """Point a child Kustomization at another path of the same source revision.""" + return ' - target: {kind: Kustomization, name: %s}\n patch: |-\n - op: replace\n path: /spec/path\n value: %s\n' % (name, path) + + def child_patch(name, patches): """Patch a child Kustomization's spec.patches: the effect of a source commit.""" return ' - target: {kind: Kustomization, name: %s}\n patch: |-\n - op: add\n path: /spec/patches\n value: %s\n' % ( diff --git a/hack/multiplane/harness.py b/hack/multiplane/harness.py index 9127cd17..19cbb231 100755 --- a/hack/multiplane/harness.py +++ b/hack/multiplane/harness.py @@ -28,6 +28,13 @@ REQUIRED_SOURCE_MARKERS = tuple('"%s"' % c for c in ('seed', 'allocate', 'admit-install', 'install', 'release', 'release-b', 'reuse', 'asset', 'image', 'boot-service', 'boot-denials', 'site-worker', 'site-observer')) + ('multiplane.ErrLocationNotServed',) READINESS_PACKAGES = ('./internal/coordination', './internal/multiplane', './internal/localvm', './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.Open()') + READINESS_PACKAGES += ('./internal/redfish',) +# Lab targets behind the Redfish emulator: System Id -> persistent libvirt domain. +LAB_DOMAINS = {'System-1': 'fleet-lab-target-a', 'System-2': 'fleet-lab-target-b'} def now(): @@ -257,7 +264,7 @@ def journal(state): def domains(state): - # Running domains only. + # Running domains only; Redfish lab targets stay defined while powered off. code, out, _ = runtime_exec(state, 'virsh', '--connect', LIBVIRT_URI, 'list', '--name') return out.split() if code == 0 else None @@ -272,7 +279,7 @@ def sanitized_operations(j): for r in (j or {}).get('operations', {}).values(): ops.append({'id': r['request']['id'], 'kind': r['request']['kind'], 'epoch': r['request']['epoch'], 'stage': r.get('stage'), 'phase': r.get('result', {}).get('phase'), 'bootClosed': r.get('bootClosed', False), - 'domain': domain_name(r['request']['id'])}) + 'domain': LAB_DOMAINS.get(r.get('target', {}).get('systemID'), '?') if (j or {}).get('provider') == 'redfish' else domain_name(r['request']['id'])}) return ops diff --git a/hack/multiplane/k8s_evidence.py b/hack/multiplane/k8s_evidence.py index 17f7daef..0cc3c4d6 100644 --- a/hack/multiplane/k8s_evidence.py +++ b/hack/multiplane/k8s_evidence.py @@ -8,12 +8,14 @@ import datetime import hashlib import json +import os import pathlib import subprocess import sys NS, SITE = 'fleet-coordination', 'fleet-site' LIBVIRT = 'qemu:///system?socket=/run/fleet-libvirt/libvirt-sock' +REDFISH = os.environ.get('FLEET_SITE_PROVIDER') == 'redfish' def now(): @@ -150,7 +152,8 @@ def record_resume(state, name): def qemu_starts(state, operation): - domain = 'fleet-local-' + hashlib.sha256(operation.encode()).hexdigest()[:24] + # Redfish mode: the persistent lab target A carries every operation. + domain = 'fleet-lab-target-a' if REDFISH else 'fleet-local-' + hashlib.sha256(operation.encode()).hexdigest()[:24] r = kubectl(state, '-n', SITE, 'exec', 'deploy/fleet-site-runtime', '-c', 'libvirt', '--', 'cat', '/var/log/libvirt/qemu/' + domain + '.log', check=False) return r.stdout.count(': starting up ') if r.returncode == 0 else None @@ -165,7 +168,7 @@ def lifecycle_snapshot(state, name): site_pods = {d: [p['metadata']['uid'] for p in get(state, '-n', SITE, 'get', 'pods', '-l', 'app.kubernetes.io/name=' + d)['items']] for d in ('fleet-site-runtime', 'fleet-site-boot', 'fleet-site-observer')} print(json.dumps({'observedAt': now(), 'journalSHA256': hashlib.sha256(runtime(state, 'cat', '/var/lib/fleet-local/journal.json').encode()).hexdigest(), - 'qemuStarts': qemu_starts(state, op), 'domains': runtime(state, 'virsh', '--connect', LIBVIRT, 'list', '--name', '--all').split(), + 'qemuStarts': qemu_starts(state, op), 'domains': runtime(state, 'virsh', '--connect', LIBVIRT, 'list', '--name', *([] if REDFISH else ['--all'])).split(), 'pvcUID': pvc['metadata']['uid'], 'pvUID': pv['metadata']['uid'], 'pvReclaimPolicy': pv['spec']['persistentVolumeReclaimPolicy'], 'machineA': {'phase': machine.get('status', {}).get('phase'), 'bound': conds.get('Bound'), 'ready': conds.get('Ready')}, 'sitePods': site_pods, 'job': job(state, name)}, sort_keys=True)) diff --git a/hack/multiplane/redfish_steps.py b/hack/multiplane/redfish_steps.py new file mode 100644 index 00000000..b6ec0ffc --- /dev/null +++ b/hack/multiplane/redfish_steps.py @@ -0,0 +1,314 @@ +#!/usr/bin/env python3 +"""Redfish-mode acceptance steps (hack/multiplane/run.sh --redfish). + +Every observation goes through the selected cell's API. Lab faults are written +only through the lab BMC adapter's fault file (bounded, one-shot) and are +recorded. Evidence records methods, paths, outcome classes, UIDs and digests, +never the BMC credential, fences, boot capabilities or request bodies. + + enroll create the synthetic BMC credential Secret (never in Git) + baseline snapshot target B and the BMC audit before any operation + discovery-faults real emulator: read-only discovery with good/wrong + credentials, identity mismatch and a hidden ResetType + arm-lost-response one-shot: withhold the response to target A's second + effective On (the disk boot of the first install) + lost-response the worker lost the On response after the effect; + recovery observed the target instead of repeating it + bmc-interrupt delete the BMC Pod mid-installer; the guest keeps running + isolation target B untouched, target A disk verifiably zeroed +""" +import datetime +import hashlib +import json +import pathlib +import secrets +import socket +import subprocess +import sys +import time + +SITE = 'fleet-site' +TARGET_A = {'system': 'System-1', 'uuid': '7f3d0c2e-1a5b-4c6d-8e9f-0a1b2c3d4e0a', 'domain': 'fleet-lab-target-a', 'disk': '/var/lib/fleet-lab/disks/target-a.raw'} +TARGET_B = {'system': 'System-2', 'uuid': '7f3d0c2e-1a5b-4c6d-8e9f-0a1b2c3d4e0b', 'domain': 'fleet-lab-target-b', 'disk': '/var/lib/fleet-lab/disks/target-b.raw'} +DISK_BYTES = 2 << 30 +LIBVIRT = 'qemu:///system?socket=/run/fleet-libvirt/libvirt-sock' +SECRET = 'fleet-site-bmc-credentials' + + +def now(): + return datetime.datetime.now(datetime.timezone.utc).isoformat() + + +def die(message): + raise SystemExit(message) + + +def kubectl(s, *args, check=True, input=None, timeout=60): + r = subprocess.run(['kubectl', '--kubeconfig', str(s / 'cell-admin.yaml'), '--request-timeout=30s', *args], text=True, capture_output=True, input=input, timeout=timeout) + if check and r.returncode: + die('kubectl %s failed: %s' % (' '.join(args[:4]), r.stderr.strip()[-300:])) + return r + + +def kget(s, *args): + return json.loads(kubectl(s, *args, '-o', 'json').stdout) + + +def runtime(s, *command, check=True): + return kubectl(s, '-n', SITE, 'exec', 'deploy/fleet-site-runtime', '-c', 'libvirt', '--', *command, check=check, timeout=180) + + +def bmc(s, *command, check=True): + return kubectl(s, '-n', SITE, 'exec', 'deploy/fleet-site-bmc', '-c', 'bmc', '--', *command, check=check) + + +def write(path, value): + pathlib.Path(path).write_text(json.dumps(value, indent=2, sort_keys=True) + '\n') + + +def audit(s): + r = bmc(s, 'cat', '/var/lib/fleet-bmc/audit.log', check=False) + return [json.loads(l) for l in r.stdout.splitlines() if l.strip()] if r.returncode == 0 else [] + + +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))] + + +def journal(s): + return json.loads(runtime(s, 'cat', '/var/lib/fleet-local/journal.json').stdout) + + +def installs(s, pending_ok=False): + # pending_ok: before the first worker retains its operation there is no journal yet. + if pending_ok: + r = runtime(s, 'cat', '/var/lib/fleet-local/journal.json', check=False) + if r.returncode: + return [] + ops = json.loads(r.stdout)['operations'].values() + else: + ops = journal(s)['operations'].values() + return [o for o in ops if o['request']['kind'] == 'install'] + + +def qemu_starts(s, domain): + r = runtime(s, 'cat', '/var/log/libvirt/qemu/%s.log' % domain, check=False) + return r.stdout.count(': starting up ') if r.returncode == 0 else 0 + + +def disk_sha(s, path): + return runtime(s, 'sha256sum', path).stdout.split()[0] + + +def console_lines(s, name): + r = runtime(s, 'cat', '/var/lib/fleet-lab-console/' + name, check=False) + return [l.strip() for l in r.stdout.splitlines()] if r.returncode == 0 else [] + + +def running(s): + return runtime(s, 'virsh', '--connect', LIBVIRT, 'list', '--name').stdout.split() + + +def enroll(s): + d = s / 'redfish' + d.mkdir(mode=0o700, exist_ok=True) + (d / 'bmc-username').write_text('fleet-lab-operator\n') + # The .token suffix enrolls the value in the harness secret scan. + (d / 'bmc-password.token').write_text(secrets.token_hex(32) + '\n') + for p in d.iterdir(): + p.chmod(0o600) + kubectl(s, '-n', SITE, 'create', 'secret', 'generic', SECRET, '--from-file=username=%s' % (d / 'bmc-username'), '--from-file=password=%s' % (d / 'bmc-password.token')) + write(s / 'evidence' / 'redfish-enrollment.json', { + 'observedAt': now(), 'credentialSecret': SITE + '/' + SECRET, 'username': 'fleet-lab-operator', + 'password': 'synthetic random 256-bit value generated per run; never recorded or committed', + 'transport': 'plain HTTP Basic on the cell network to the fixed BMC Service 10.96.0.81:8000 (lab seam)', + 'readers': ['lab BMC adapter (server side)', 'per-operation Redfish worker Pods (client side)'], + '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]), + 'labTargets': json.loads(pathlib.Path('hack/redfish-lab/targets.json').read_text())}) + print('redfish-enroll: synthetic BMC credential Secret created in the cell; not part of any source revision') + + +def baseline(s): + # Read target B through the BMC once so the adapter defines it, as any + # discovery would, then record its untouched state. + for _ in range(60): + if kubectl(s, '-n', SITE, 'get', 'deployment', 'fleet-site-bmc', '-o', 'jsonpath={.status.availableReplicas}', check=False).stdout == '1': + break + time.sleep(2) + record = {'observedAt': now(), 'targetB': {'diskSHA256': disk_sha(s, TARGET_B['disk']), 'qemuStarts': qemu_starts(s, TARGET_B['domain']), + 'consoleLines': len(console_lines(s, 'target-b.log'))}, + 'targetA': {'diskSHA256': disk_sha(s, TARGET_A['disk']), 'qemuStarts': qemu_starts(s, TARGET_A['domain'])}, + 'auditEntries': len(audit(s)), 'runningDomains': running(s)} + if record['targetB']['qemuStarts'] or record['targetA']['qemuStarts'] or record['runningDomains']: + die('lab targets were started before any operation: %s' % record) + write(s / 'redfish-baseline.json', record) + print('redfish-baseline: both lab target disks present and neither target ever started; target B disk %s...' % record['targetB']['diskSHA256'][:12]) + + +def port_forward(s): + sock = socket.socket() + sock.bind(('127.0.0.1', 0)) + port = sock.getsockname()[1] + sock.close() + p = subprocess.Popen(['kubectl', '--kubeconfig', str(s / 'cell-admin.yaml'), '-n', SITE, 'port-forward', 'svc/fleet-site-bmc', '%d:8000' % port], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + for _ in range(60): + try: + socket.create_connection(('127.0.0.1', port), 1).close() + return p, port + except OSError: + time.sleep(0.5) + p.kill() + die('could not port-forward to the BMC Service') + + +def discovery_faults(s): + d = s / 'redfish' + good, bad = d / 'probe-good', d / 'probe-bad' + for p, password in ((good, (d / 'bmc-password.token').read_text()), (bad, secrets.token_hex(16) + '\n')): + p.mkdir(mode=0o700, exist_ok=True) + (p / 'username').write_text((d / 'bmc-username').read_text()) + (p / 'password').write_text(password) + pf, port = port_forward(s) + before = len(audit(s)) + cases = [] + try: + def probe(name, creds, system, uuid, want): + r = subprocess.run([str(s / 'fleet-multiplane-host'), 'redfish-probe', '--endpoint', 'http://127.0.0.1:%d' % port, '--credentials', str(creds), + '--system', system, '--uuid', uuid], 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: + die('%s: expected exit %d, got %d: %s %s' % (name, want, r.returncode, line, r.stderr[-200:])) + probe('target A with the enrolled credential', good, TARGET_A['system'], TARGET_A['uuid'], 0) + probe('target B with the enrolled credential', good, TARGET_B['system'], TARGET_B['uuid'], 0) + probe('wrong credential', bad, TARGET_A['system'], TARGET_A['uuid'], 10) + probe("target A's Id with target B's UUID (swapped mapping)", good, TARGET_A['system'], TARGET_B['uuid'], 12) + probe('unknown UUID', good, TARGET_A['system'], '00000000-0000-0000-0000-000000000000', 12) + bmc(s, 'python3', '/opt/fleet-lab/fleet_lab_adapter.py', 'fault', 'hide-reset', 'On') + try: + 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') + probe('target A after the fault is cleared', good, TARGET_A['system'], TARGET_A['uuid'], 0) + finally: + pf.kill() + for p in (good, bad): + 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): + 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, + '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') + + +def arm_lost_response(s): + # The installer phase is about a minute under TCG and carries the worker + # Pod, Job and BMC interruptions; the disk boot's On carries this fault. + out = bmc(s, 'python3', '/opt/fleet-lab/fleet_lab_adapter.py', 'fault', 'drop-response', TARGET_A['system'], 'On', '45', '1').stdout + (s / 'redfish-lost-response-armed').write_text(now() + '\n') + print('redfish-arm-lost-response: one-shot fault armed: the second effective On for System-1 (the disk boot) withholds its response for 45s (client timeout 20s): %s' % out.strip()) + + +def lost_response(s): + name = (s / 'install-handoff').read_text().strip() + deadline = time.monotonic() + 900 + record = None + while time.monotonic() < deadline: + fired = [e for e in audit(s) if e.get('fault') == 'drop-response-after-effect'] + pods = kget(s, '-n', SITE, 'get', 'pods', '-l', 'fleet.datumapis.com/handoff=' + name)['items'] + exits = [c['state']['terminated']['exitCode'] for p in pods for c in p['status'].get('containerStatuses', []) if 'terminated' in c.get('state', {})] + if fired and 75 in exits: + failed = next(p for p in pods for c in p['status'].get('containerStatuses', []) if c.get('state', {}).get('terminated', {}).get('exitCode') == 75) + log = kubectl(s, '-n', SITE, 'logs', failed['metadata']['name'], '-c', 'worker', check=False).stdout + # The audit entry is written after the withheld response. + record = {'faultRecordedAt': fired[0]['at'], 'faultedRequest': {k: fired[0].get(k) for k in ('method', 'path', 'resetType', 'effect', 'status')}, + 'failedPodUID': failed['metadata']['uid'], 'failedPodExitCode': 75, + 'workerOutcomeClass': 'outcome unknown' if 'outcome unknown' in log else log.strip()[-160:]} + break + time.sleep(2) + if not record: + die('lost-response fault did not fire and fail one worker with exit 75') + for _ in range(300): + ops = installs(s) + if len(ops) == 1 and ops[0]['stage'] in ('disk-started', 'disk-verified', 'done'): + break + time.sleep(2) + ops = installs(s) + ons = [e for e in mutating(audit(s), TARGET_A['system']) if e.get('resetType') == 'On'] + if len(ops) != 1 or ops[0]['stage'] not in ('disk-started', 'disk-verified', 'done') or len(ons) != 2 or ops[0].get('powerOnRequests') != {'installer': 1, 'disk': 1}: + die('recovery after the lost response repeated or did not observe the boot: %d On requests, %s' % (len(ons), ops[0].get('stage') if ops else None)) + record.update(observedAt=now(), operationID=ops[0]['request']['id'], stageAfterRecovery=ops[0]['stage'], phase='disk boot', powerOnRequests=ops[0]['powerOnRequests'], + onRequestsToTargetA=len(ons), runningDomains=running(s), + recovery='replacement worker observed PowerState and the consumed one-time override; it did not repeat On') + write(s / 'evidence' / 'redfish-lost-response.json', record) + print('redfish-lost-response: On took effect but its response was lost; the worker exited 75 Unknown; its replacement observed the running target and did not repeat the effect') + + +def bmc_interrupt(s): + ops = [] + for _ in range(600): + ops = installs(s, pending_ok=True) + if len(ops) == 1 and ops[0]['stage'] == 'installer-started' and TARGET_A['domain'] in running(s): + break + if len(ops) == 1 and ops[0]['stage'] not in ('admitted', 'discovered', 'installer-armed', 'installer-requested', 'installer-started'): + die('the installer finished before the BMC could be interrupted: %s' % ops[0]['stage']) + time.sleep(0.5) + else: + die('BMC interruption requires the install mid-installer with target A running') + old = kget(s, '-n', SITE, 'get', 'pods', '-l', 'app.kubernetes.io/name=fleet-site-bmc')['items'] + kubectl(s, '-n', SITE, 'delete', 'pod', '-l', 'app.kubernetes.io/name=fleet-site-bmc', '--grace-period=0', '--force', check=False) + new = None + for _ in range(180): + pods = [p for p in kget(s, '-n', SITE, 'get', 'pods', '-l', 'app.kubernetes.io/name=fleet-site-bmc')['items'] + if p['metadata']['uid'] not in {o['metadata']['uid'] for o in old} and any(c['type'] == 'Ready' and c['status'] == 'True' for c in p['status'].get('conditions', []))] + if pods: + new = pods[0] + break + time.sleep(1) + if not new: + die('BMC Pod was not replaced') + after = installs(s) + if TARGET_A['domain'] not in running(s) and after[0]['stage'] == 'installer-started': + die('the guest stopped when the BMC was interrupted') + write(s / 'evidence' / 'redfish-bmc-interrupt.json', {'observedAt': now(), 'deletedBMCPodUIDs': [o['metadata']['uid'] for o in old], 'replacementBMCPodUID': new['metadata']['uid'], + 'operationID': ops[0]['request']['id'], 'stageAtInterrupt': 'installer-started', 'stageAfter': after[0]['stage'], + 'guestRunningAfter': TARGET_A['domain'] in running(s), + 'note': 'the BMC adapter re-reads NVRAM and libvirt state; the worker tolerates a bounded BMC outage while observing'}) + print('redfish-bmc-interrupt: lab BMC Pod force-deleted mid-install and replaced; the guest kept running and the operation stayed unfinished') + + +def isolation(s): + base = json.loads((s / 'redfish-baseline.json').read_text()) + entries = audit(s) + zero = hashlib.sha256() + block = bytes(1 << 20) + for _ in range(DISK_BYTES >> 20): + zero.update(block) + record = {'observedAt': now(), + 'targetB': {'diskSHA256Before': base['targetB']['diskSHA256'], 'diskSHA256After': disk_sha(s, TARGET_B['disk']), 'qemuStarts': qemu_starts(s, TARGET_B['domain']), + 'consoleLines': len(console_lines(s, 'target-b.log')), 'mutatingRedfishRequests': mutating(entries, TARGET_B['system'])}, + 'targetA': {'diskSHA256': disk_sha(s, TARGET_A['disk']), 'zeroDiskSHA256': zero.hexdigest(), 'qemuStarts': qemu_starts(s, TARGET_A['domain']), + 'mutatingRedfishRequests': [{k: e.get(k) for k in ('method', 'path', 'status', 'resetType', 'boot', 'effect', 'fault')} for e in mutating(entries, TARGET_A['system'])]}, + 'runningDomains': running(s), 'auditEntries': len(entries)} + b, a = record['targetB'], record['targetA'] + if b['diskSHA256Before'] != b['diskSHA256After'] or b['qemuStarts'] or b['consoleLines'] != base['targetB']['consoleLines'] or b['mutatingRedfishRequests']: + die('target B was touched: %s' % b) + if a['diskSHA256'] != a['zeroDiskSHA256']: + die('target A disk is not all zeroes after the final verified cleanup') + if record['runningDomains']: + die('a lab target is still running: %s' % record['runningDomains']) + write(s / 'evidence' / 'redfish-isolation.json', record) + (s / 'evidence' / 'redfish-audit.jsonl').write_text(''.join(json.dumps(e, sort_keys=True) + '\n' for e in entries)) + 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') + + +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) diff --git a/hack/multiplane/run.sh b/hack/multiplane/run.sh index 3fe58150..73111d06 100755 --- a/hack/multiplane/run.sh +++ b/hack/multiplane/run.sh @@ -8,8 +8,8 @@ set -euo pipefail cd "$(dirname "$0")/../.." umask 077 -usage() { echo 'usage: hack/multiplane/run.sh [--preflight-only] [--bootstrap] [--keep] [--leave-running] [--skip-readiness-tests]' >&2; exit 64; } -preflight_only=0 bootstrap=() keep=0 leave=0 skip_tests=() +usage() { echo 'usage: hack/multiplane/run.sh [--redfish] [--preflight-only] [--bootstrap] [--keep] [--leave-running] [--skip-readiness-tests]' >&2; exit 64; } +preflight_only=0 bootstrap=() keep=0 leave=0 skip_tests=() provider=libvirt for arg in "$@"; do case "$arg" in --preflight-only) preflight_only=1 ;; @@ -17,14 +17,18 @@ for arg in "$@"; do --keep) keep=1 ;; --leave-running) leave=1 ;; --skip-readiness-tests) skip_tests=(--skip-tests) ;; + # Redfish mode: workers drive lab VMs only through the DMTF Redfish emulator + # and its lab adapter (docs/operations/redfish-lab.md). + --redfish) provider=redfish ;; *) usage ;; esac done -export DOCKER_CONTEXT=colima-fleet-acceptance-tcg KIND_EXPERIMENTAL_PROVIDER=docker +export DOCKER_CONTEXT=colima-fleet-acceptance-tcg KIND_EXPERIMENTAL_PROVIDER=docker FLEET_SITE_PROVIDER=$provider harness=(python3 hack/multiplane/harness.py) state=$(mktemp -d "${FLEET_MULTIPLANE_STATE_ROOT:-/tmp}/fleet-multiplane.XXXXXX") mkdir -m 0700 "$state/evidence" -printf 'Private run state: %s\nShareable evidence: %s/evidence\n' "$state" "$state" +printf '%s\n' "$provider" > "$state/site-provider" +printf 'Private run state: %s\nShareable evidence: %s/evidence\nSite provider: %s\n' "$state" "$state" "$provider" finish() { code=$1 @@ -53,7 +57,7 @@ printf '%s\n' "$prefix" > "$state/prefix" python3 - "$state" <<'PY' import hashlib,pathlib,sys paths=[] -for name in ('internal','cmd/fleet-multiplane','hack/multiplane','hack/local-vm','config/multiplane','config/site','config/base/crd'): +for name in ('internal','cmd/fleet-multiplane','hack/multiplane','hack/local-vm','hack/redfish-lab','config/multiplane','config/site','config/base/crd'): paths += [p for p in pathlib.Path(name).rglob('*') if p.is_file() and '__pycache__' not in p.parts and p.suffix not in ('.pyc', '.pyo')] paths += [pathlib.Path(name) for name in ('go.mod', 'go.sum')] (pathlib.Path(sys.argv[1])/'source-SHA256SUMS').write_text(''.join(hashlib.sha256(p.read_bytes()).hexdigest()+' '+str(p)+'\n' for p in sorted(paths))) @@ -68,6 +72,13 @@ ph site-image-verify 120 sh -c ' printf "%s /usr/local/bin/fleet-multiplane\n" "$sum" | docker run --rm -i --entrypoint sha256sum "$1-site-image" -c - >/dev/null docker run --rm -e FLEET_LOCAL_VM_ACCEL=tcg --entrypoint fleet-multiplane "$1-site-image" image > "$2/image" echo "site image: checksum-verified executable; artifact reference recorded"' sh "$prefix" "$state" +if [[ $provider == redfish ]]; then + # The unmodified upstream emulator, verified before extraction, plus the + # lab-only adapter; its self-test runs the real emulator with a fake virsh. + ph bmc-upstream 300 sh -c 'bash hack/redfish-lab/upstream.sh "$1/redfish-upstream" > "$1/evidence/redfish-upstream.json" && echo "bmc-upstream: DMTF Redfish-Interface-Emulator 1.2.2 archive verified"' sh "$state" + ph bmc-image 1800 docker build --build-context "upstream=$state/redfish-upstream/src/Redfish-Interface-Emulator-1.2.2" -t "$prefix-bmc-image" -f hack/redfish-lab/Containerfile hack/redfish-lab + ph bmc-self-test 300 sh -c 'docker run --rm --network none --entrypoint python3 "$1-bmc-image" /opt/fleet-lab/test_adapter.py >/dev/null 2>&1 && echo "bmc-self-test: upstream emulator and lab adapter self-test passed"' sh "$prefix" +fi ph flux-tools 300 "${flux[@]}" tools "$state" docker network inspect kind >/dev/null 2>&1 || docker network create kind >/dev/null # Disposable infrastructure only: registry and three kind clusters, no services. @@ -89,16 +100,21 @@ s=pathlib.Path(sys.argv[1]).resolve();c={'State':str(s),'HubKubeconfig':str(s/'m PY ph seed 600 "$state/fleet-multiplane-host" seed --config "$state/acceptance.json" ph scoped-asset 120 sh -c '"$1/fleet-multiplane-host" asset --config "$1/acceptance.json" > "$1/scoped-asset" && echo "scoped asset recorded"' sh "$state" +[[ $provider != redfish ]] || ph redfish-enroll 120 python3 hack/multiplane/redfish_steps.py enroll "$state" # Revision 2: the Flux-owned shared site services and the HandoffDispatcher # instance, dispatch disabled. ph flux-site 1200 "${flux[@]}" publish "$state" --revision 2 --site off --purpose 'shared site services and dispatcher, dispatch disabled' --cluster cell --cluster hub --cluster platform --timeout 900 ph site-install 900 bash hack/multiplane/site.sh check "$state" ph flux-verify 300 "${flux[@]}" verify "$state" -bash hack/multiplane/acceptance.sh "$state" +if [[ $provider == redfish ]]; then + bash hack/multiplane/acceptance-redfish.sh "$state" +else + bash hack/multiplane/acceptance.sh "$state" +fi ph secret-scan 120 "${harness[@]}" scan --state "$state" if [[ $keep == 1 ]]; then ph stop 300 bash hack/multiplane/stop.sh "$state" else ph teardown 900 bash hack/multiplane/teardown.sh "$state" fi -printf 'Local topology/PXE acceptance passed. Production authority and physical hardware remain unqualified.\n' +printf 'Local topology/PXE acceptance (%s provider) passed. Production authority and physical hardware remain unqualified.\n' "$provider" diff --git a/hack/multiplane/site.sh b/hack/multiplane/site.sh index d7c35536..d816df6e 100755 --- a/hack/multiplane/site.sh +++ b/hack/multiplane/site.sh @@ -13,7 +13,9 @@ prefix=$(cat "$state/prefix") [[ $prefix =~ ^fleet-mp-[a-f0-9]{8}$ ]] || { echo "unexpected prefix" >&2; exit 1; } export DOCKER_CONTEXT=colima-fleet-acceptance-tcg cell="$state/cell-admin.yaml" +provider=$(cat "$state/site-provider" 2>/dev/null || echo libvirt) deployments=(fleet-site-runtime fleet-site-boot fleet-site-observer) +[[ $provider != redfish ]] || deployments+=(fleet-site-bmc) k() { kubectl --kubeconfig "$cell" --request-timeout=30s "$@"; } case "$step" in @@ -32,6 +34,21 @@ env['siteImageDigest'] = digest (s / 'gitops-environment.json').write_text(json.dumps(env, indent=2) + '\n') PY printf 'site image: pushed to the run registry as fleet-site@%s; the cell pulls it by digest\n' "$digest" + if [[ $provider == redfish ]]; then + docker tag "$prefix-bmc-image" "127.0.0.1:$port/fleet-bmc:$prefix" >/dev/null + docker push "127.0.0.1:$port/fleet-bmc:$prefix" >/dev/null + bmc=$(docker image inspect "127.0.0.1:$port/fleet-bmc:$prefix" --format '{{range .RepoDigests}}{{println .}}{{end}}' | grep "^127.0.0.1:$port/fleet-bmc@" | cut -d@ -f2) + [[ $bmc =~ ^sha256:[a-f0-9]{64}$ ]] || { echo "no registry digest for the BMC image" >&2; exit 1; } + python3 - "$state" "$prefix" "$bmc" <<'PY' +import json, pathlib, sys +s, prefix, digest = pathlib.Path(sys.argv[1]), sys.argv[2], sys.argv[3] +env = json.loads((s / 'gitops-environment.json').read_text()) +env['bmcImage'] = '%s-registry:5000/fleet-bmc@%s' % (prefix, digest) +env['bmcImageDigest'] = digest +(s / 'gitops-environment.json').write_text(json.dumps(env, indent=2) + '\n') +PY + printf 'bmc image: pushed the DMTF emulator lab BMC as fleet-bmc@%s\n' "$bmc" + fi ;; check) for d in "${deployments[@]}"; do @@ -44,6 +61,11 @@ PY policy=$(k get pv "$pv" -o jsonpath='{.spec.persistentVolumeReclaimPolicy}') [[ $policy == Retain ]] || { echo "site volume reclaim policy $policy" >&2; exit 1; } want=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["siteImage"])' "$state/gitops-environment.json") + if [[ $provider == redfish ]]; then + bmc=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["bmcImage"])' "$state/gitops-environment.json") + [[ $(k -n fleet-site get deployment fleet-site-bmc -o jsonpath='{.spec.template.spec.containers[0].image}') == "$bmc" ]] || { echo 'BMC does not run the published digest' >&2; exit 1; } + [[ $(k -n fleet-site get deployment fleet-site-bmc -o jsonpath='{.metadata.labels.kustomize\.toolkit\.fluxcd\.io/name}') == fleet-site-services ]] || { echo 'BMC is not owned by the Flux services layer' >&2; exit 1; } + fi for d in fleet-site-runtime fleet-site-boot fleet-site-observer; do image=$(k -n fleet-site get deployment "$d" -o jsonpath='{.spec.template.spec.containers[0].image}') [[ $image == "$want" ]] || { echo "$d runs $image, not the published digest" >&2; exit 1; } diff --git a/hack/multiplane/steps.sh b/hack/multiplane/steps.sh index 81ee78ee..e6c07852 100755 --- a/hack/multiplane/steps.sh +++ b/hack/multiplane/steps.sh @@ -285,7 +285,12 @@ PY # The origin comes from the Flux-owned Service, which drift repair recreated. origin="http://$(site get service fleet-site-boot -o jsonpath='{.spec.clusterIP}'):8080" [[ $origin == "$(site get handoffdispatcher dispatcher -o jsonpath='{.status.bootOrigin}')" ]] || { echo 'dispatcher boot origin differs from the boot Service' >&2; exit 1; } - runtime fleet-multiplane boot-denials --origin "$origin" > "$state/boot-denials.txt" + if [[ $(cat "$state/site-provider" 2>/dev/null) == redfish ]]; then + # Redfish mode also probes the never-allocated target B's MAC. + runtime env FLEET_BOOT_ORIGIN="$origin" FLEET_BOOT_EVIDENCE=/var/lib/fleet-boot fleet-multiplane boot-denials --origin "$origin" --extra-mac 52:54:00:77:01:0b > "$state/boot-denials.txt" + else + runtime fleet-multiplane boot-denials --origin "$origin" > "$state/boot-denials.txt" + fi grep -q '^PASS ' "$state/boot-denials.txt" || { echo 'closed-boot probe failed' >&2; exit 1; } printf 'boot-denials: %s through the boot Service\n' "$(cat "$state/boot-denials.txt")" ;; diff --git a/hack/multiplane/teardown.sh b/hack/multiplane/teardown.sh index 299898a5..009d4033 100755 --- a/hack/multiplane/teardown.sh +++ b/hack/multiplane/teardown.sh @@ -37,9 +37,10 @@ image_tag_removed=true pushed=() if [[ -f $state/gitops-environment.json ]]; then port=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["registryPort"])' "$state/gitops-environment.json") - pushed=("127.0.0.1:$port/fleet-site:$prefix") + # Redfish mode also built and pushed the lab BMC image. + pushed=("127.0.0.1:$port/fleet-site:$prefix" "127.0.0.1:$port/fleet-bmc:$prefix") fi -for image in "$prefix-site-image" "$prefix-provider-image" ${pushed[@]+"${pushed[@]}"}; do +for image in "$prefix-site-image" "$prefix-provider-image" "$prefix-bmc-image" ${pushed[@]+"${pushed[@]}"}; do docker image rm "$image" >/dev/null 2>&1 || true if docker image inspect "$image" >/dev/null 2>&1; then image_tag_removed=false; fi done @@ -48,7 +49,7 @@ remaining=$(docker ps -a --filter "name=^$prefix-" --format '{{.Names}}') rm -f "$state/kind-delete.kubeconfig" if [[ $mode == passed ]]; then # Credentials and raw journals are no longer needed once the run has passed. - rm -rf "$state/provider" "$state/consumer-a" "$state/consumer-b" "$state/provider-private" + rm -rf "$state/provider" "$state/consumer-a" "$state/consumer-b" "$state/provider-private" "$state/redfish" rm -f "$state"/*.yaml "$state"/*-hub.json "$state"/private.json "$state"/cell-worker*.json "$state"/federation-cell.json "$state"/*.token "$state"/*-kubeconfig.json \ "$state"/status-fault.json "$state"/acceptance.json "$state"/fleet-multiplane "$state"/fleet-multiplane-host rm -rf "$state/site-bin" "$state/kro-chart" "$state/flux-tools/flux" "$state"/flux-tools/*.tar.gz diff --git a/hack/multiplane/test-harness.sh b/hack/multiplane/test-harness.sh index a2f5e561..8b1cb2b1 100755 --- a/hack/multiplane/test-harness.sh +++ b/hack/multiplane/test-harness.sh @@ -6,6 +6,8 @@ root=$(CDPATH='' cd -- "$(dirname "$0")/../.." && pwd) for f in "$root"/hack/multiplane/*.sh "$root"/hack/local-vm/run.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 -m py_compile "$root"/hack/redfish-lab/*.py exec python3 - "$root" <<'PY' import json, os, pathlib, re, stat, subprocess, sys, tempfile, time diff --git a/hack/multiplane/test-redfish.py b/hack/multiplane/test-redfish.py new file mode 100644 index 00000000..317dcf0d --- /dev/null +++ b/hack/multiplane/test-redfish.py @@ -0,0 +1,171 @@ +#!/usr/bin/env python3 +"""Offline checks for the Redfish acceptance mode (run.sh --redfish). + +Renders the Redfish site overlays and a staged Redfish source revision with +the real kustomize, and checks the static contracts the live run relies on: +workers have no hypervisor path, only the runtime is privileged, the lab +enrollment matches the lab targets, and every phase is implemented. Never +contacts a container runtime or cluster. +""" +import argparse +import json +import os +import pathlib +import re +import subprocess +import sys +import tempfile + +root = pathlib.Path(sys.argv[1]).resolve() +os.environ['FLEET_SITE_PROVIDER'] = 'redfish' +sys.path.insert(0, str(root / 'hack/multiplane')) +import flux # noqa: E402 (reads FLEET_SITE_PROVIDER at import) + + +def documents(text): + """Rendered YAML as objects: PyYAML when present, otherwise yq (both are on CI runners).""" + try: + import yaml + return [d for d in yaml.safe_load_all(text) if d] + except ImportError: + out = subprocess.run(['yq', '-o=json', '-I=0', '.'], input=text, text=True, capture_output=True, check=True).stdout + return [json.loads(line) for line in out.splitlines() if line.strip() not in ('', 'null')] + +failures = [] + + +def check(name, ok, detail=''): + if not ok: + failures.append(name + (': ' + detail if detail else '')) + + +def build(path): + r = subprocess.run(['kustomize', 'build', str(path)], text=True, capture_output=True) + if r.returncode: + failures.append('render %s: %s' % (path, r.stderr[-300:])) + return [] + return documents(r.stdout) + + +graph = build(root / 'config/site/redfish/graph') +rgd = next((d for d in graph if d.get('kind') == 'ResourceGraphDefinition'), {}) +resources = {r['id']: r for r in rgd.get('spec', {}).get('resources', [])} +worker = resources.get('workers', {}).get('template', {}).get('spec', {}).get('template', {}).get('spec', {}) +container = (worker.get('containers') or [{}])[0] +env = {e['name']: e.get('value') for e in container.get('env', [])} +mounts = container.get('volumeMounts', []) +check('Redfish worker selects the Redfish provider', env.get('FLEET_SITE_PROVIDER') == 'redfish' and 'FLEET_LIBVIRT_URI' not in env, str(env.keys())) +check('Redfish worker has no libvirt socket or lab disk mount', not any('libvirt' in m.get('subPath', '') + m['mountPath'] or 'lab-disks' in m.get('subPath', '') for m in mounts), str(mounts)) +check('Redfish worker console capture is read-only', any(m.get('subPath') == 'lab-console' and m.get('readOnly') for m in mounts)) +check('Redfish worker credential is the BMC Secret only', [v['secret']['secretName'] for v in worker.get('volumes', []) if 'secret' in v] == ['fleet-site-bmc-credentials'] + and not any('hostPath' in v for v in worker.get('volumes', []))) +check('Redfish worker waits for the Flux-owned BMC', 'bmc' in resources and resources['bmc'].get('externalRef', {}).get('metadata', {}).get('name') == 'fleet-site-bmc' + and '${bmc.metadata.name}' in json.dumps(resources.get('workers', {}))) +check('graph ids still valid for kro', all(re.fullmatch(r'[a-z][a-zA-Z0-9]*', i) for i in resources) and 'runtime' not in resources, str(list(resources))) +check('privileged nothing in the Redfish graph', 'privileged' not in json.dumps(rgd)) + +enrollment = json.loads(env.get('FLEET_REDFISH_ENROLLMENT', '{}')) +targets = json.loads((root / 'hack/redfish-lab/targets.json').read_text()) +by_system = {t['system']: t for t in targets} +check('enrollment endpoint is the fixed BMC Service', enrollment.get('endpoint') == 'http://%s:8000' % flux.BMC_SERVICE_IP) +check('enrollment matches the lab targets exactly', len(enrollment.get('targets', [])) == 2 and all( + t['systemID'] in by_system and by_system[t['systemID']]['uuid'] == t['systemUUID'] and by_system[t['systemID']]['mac'] == t['mac'] + and by_system[t['systemID']]['console'].endswith('/' + t['console']) for t in enrollment.get('targets', [])), json.dumps(enrollment)[:300]) +check('only target A is the published capacity Device', enrollment['targets'][0]['assetID'].endswith('/synthetic-device-central-01') if enrollment.get('targets') else False) + +services = build(root / 'config/site/redfish/services') +deployments = {d['metadata']['name']: d for d in services if d.get('kind') == 'Deployment'} +check('Redfish services add the BMC', sorted(deployments) == ['fleet-site-bmc', 'fleet-site-boot', 'fleet-site-observer', 'fleet-site-runtime'], str(sorted(deployments))) +privileged = [n for n, d in deployments.items() if any(c.get('securityContext', {}).get('privileged') for c in d['spec']['template']['spec']['containers'])] +check('only the runtime is privileged in Redfish mode', privileged == ['fleet-site-runtime'], str(privileged)) +socket_holders = sorted(n for n, d in deployments.items() if any(m.get('subPath') == 'libvirt-socket' for c in d['spec']['template']['spec']['containers'] for m in c.get('volumeMounts', []))) +check('only the runtime and the lab BMC hold the libvirt socket', socket_holders == ['fleet-site-bmc', 'fleet-site-runtime'], str(socket_holders)) +bmc = deployments.get('fleet-site-bmc', {}) +check('BMC image and Service IP substituted by Flux', '${FLEET_BMC_IMAGE}' in json.dumps(bmc) and any( + d.get('kind') == 'Service' and d['metadata']['name'] == 'fleet-site-bmc' and d['spec']['clusterIP'] == '${FLEET_BMC_SERVICE_IP}' for d in services)) +check('every site role selects the Redfish provider', all(any(e.get('name') == 'FLEET_SITE_PROVIDER' and e.get('value') == 'redfish' for e in deployments[n]['spec']['template']['spec']['containers'][0].get('env', [])) + for n in ('fleet-site-runtime', 'fleet-site-boot', 'fleet-site-observer'))) + +base = build(root / 'config/site/redfish/base') +policy = next((d for d in base if d.get('kind') == 'ValidatingAdmissionPolicy' and d['metadata']['name'] == 'fleet-site-kro-worker-jobs'), {}) +text = json.dumps(policy) +check('admission denies libvirt mounts and URIs for kro worker Jobs', "startsWith('/run/fleet-libvirt')" in text and "FLEET_LIBVIRT_URI" in text and 'fleet-site-bmc-credentials' in text) +check('BMC identity in the base', any(d.get('kind') == 'ServiceAccount' and d['metadata']['name'] == 'fleet-site-bmc' for d in base)) +check('no Secret in any Redfish overlay', not any(d.get('kind') == 'Secret' for d in base + services + graph)) + +# A staged Redfish revision points the cell's site layers at the overlays. +with tempfile.TemporaryDirectory() as tmp: + s = pathlib.Path(tmp) / 'state' + (s / 'flux-tools').mkdir(parents=True) + (s / 'evidence').mkdir() + (s / 'prefix').write_text('fleet-mp-0000abcd\n') + # The same stand-in for the release install.yaml that test-flux.py uses. + fake = 'apiVersion: v1\nkind: Namespace\nmetadata: {name: flux-system}\n' + for name in ('source-controller', 'kustomize-controller', 'helm-controller', 'notification-controller', 'image-automation-controller', + 'image-reflector-controller', 'source-watcher'): + fake += '---\napiVersion: apps/v1\nkind: Deployment\nmetadata: {name: %s, namespace: flux-system}\nspec:\n template:\n spec:\n containers:\n - {name: manager, image: ghcr.io/fluxcd/%s:v0, args: []}\n' % (name, name) + fake += '---\napiVersion: v1\nkind: Service\nmetadata: {name: source-watcher, namespace: flux-system}\n' + (s / 'flux-tools' / 'install.yaml').write_text(fake) + flux.INSTALL_SHA256 = flux.sha256(s / 'flux-tools' / 'install.yaml') + (s / 'gitops-environment.json').write_text(json.dumps({'registryHost': 'fleet-mp-0000abcd-registry', 'registryPort': 5555, 'karmadaPort': 1, 'cell': 'fleet-mp-0000abcd-cell', + 'cellEndpoint': 'https://x:6443', 'siteImage': 'r/fleet-site@sha256:' + 'a' * 64, 'siteImageDigest': 'sha256:' + 'a' * 64, + 'bmcImage': 'r/fleet-bmc@sha256:' + 'b' * 64, 'bmcImageDigest': 'sha256:' + 'b' * 64})) + (s / 'scoped-asset').write_text('local-milo/uid/fleet-provider/fleet.datumapis.com/Device/synthetic-device-central-01\n') + args = argparse.Namespace(state=str(s), root=str(root), revision=2, site='off', bad_kro_chart=False, drop_site_volume=True, purpose='test', cluster=[], timeout=5) + check('stage a Redfish revision', flux.stage(args) == 0) + cell = subprocess.run(['kustomize', 'build', str(s / 'gitops/r2/environment/cell')], text=True, capture_output=True).stdout + for layer in ('base', 'services', 'graph'): + check('cell %s layer uses the Redfish overlay' % layer, 'path: ./config/site/redfish/' + layer in cell) + check('Redfish environment values defined', 'FLEET_BMC_IMAGE: r/fleet-bmc@sha256:' in cell.replace('"', '') and ('FLEET_BMC_SERVICE_IP: %s' % flux.BMC_SERVICE_IP) in cell.replace('"', '')) + check('volume-removal patch still targets the Redfish base', '$patch: delete' in cell) + used = set() + for f in (root / 'config/site/redfish/services').glob('*.yaml'): + used |= set(re.findall(r'\$\{(FLEET_[A-Z_]+)\}', f.read_text())) + defined = set(re.findall(r'^ (FLEET_[A-Z_]+): ', cell, re.M)) + check('Redfish substituted variables defined', used <= defined, str(sorted(used - defined))) +check('ownership audit expects the BMC', ('deployments', 'fleet-site', 'fleet-site-bmc') in flux.SHARED and 'fleet-site-bmc' in flux.SITE_DEPLOYMENTS) + +# Every Redfish phase is implemented, and the lab fault hooks stay in the lab. +sequence = (root / 'hack/multiplane/acceptance-redfish.sh').read_text() +steps = (root / 'hack/multiplane/steps.sh').read_text() +redfish_steps = (root / 'hack/multiplane/redfish_steps.py').read_text() +for name in re.findall(r'^step (\S+)', sequence, re.M): + check('step implemented: ' + name, ' %s)' % name in steps or '|%s)' % name in steps or ' %s|' % name in steps) +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'] +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 name in ('internal/redfish/client.go', 'internal/redfish/provider.go', 'internal/redfish/boot.go'): + src = (root / name).read_text() + check('no lab fault hook in production code: ' + name, not re.search(r'\bfaults?\b|drop-response|hide-reset', src, re.I)) +adapter = (root / 'hack/redfish-lab/fleet_lab_adapter.py').read_text() +check('adapter keeps upstream unmodified (imports it)', 'import emulator' in adapter and 'COPY --from=upstream . /opt/redfish-emulator' in (root / 'hack/redfish-lab/Containerfile').read_text()) +check('upstream source pinned by digest and commit', re.search(r'sha256=[0-9a-f]{64}', (root / 'hack/redfish-lab/upstream.sh').read_text()) is not None + and '5f51d8ac48e46665a2a85242434f125aa7b25172' in (root / 'hack/redfish-lab/upstream.sh').read_text()) +check('BMC base image pinned by digest', re.search(r'^FROM \S+@sha256:[0-9a-f]{64}$', (root / 'hack/redfish-lab/Containerfile').read_text(), re.M) is not None) +lock = (root / 'hack/redfish-lab/requirements.lock').read_text() +check('Python dependencies hash-pinned', all('==' in l for l in lock.splitlines() if l and not l.startswith(('#', ' '))) and lock.count('--hash=sha256:') >= 18) +check('no OpenStack dependency', not re.search(r'sushy|openstack|ironic', (lock + adapter + (root / 'hack/redfish-lab/Containerfile').read_text()).lower())) + +run_sh = (root / 'hack/multiplane/run.sh').read_text() +# $state/provider is the Milo provider project's credential directory. +check('site provider marker does not collide with the provider project state', '"$state/site-provider"' in run_sh and '> "$state/provider"' not in run_sh) + +# Every Redfish evidence marker must be printed by some phase, or the +# evidence phase fails after a fully passing run. +evidence_src = (root / 'hack/multiplane/evidence.py').read_text() +block = evidence_src.split('if REDFISH:\n markers += (')[1].split(')\nfor marker')[0] +sources = ''.join(p.read_text() for p in list((root / 'hack/multiplane').glob('*.py')) + list((root / 'hack/multiplane').glob('*.sh')) + [root / 'cmd/fleet-multiplane/main.go'] + if p.name != 'evidence.py') +for marker in re.findall(r"'([^']+)'", block): + check('evidence marker is printed by a phase: ' + marker, marker in sources or marker.split(': ')[0] + ': verified' == marker) +teardown = (root / 'hack/multiplane/teardown.sh').read_text() +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) + +if failures: + print('FAIL Redfish mode tests:\n ' + '\n '.join(failures)) + sys.exit(1) +print('PASS Redfish mode tests') diff --git a/hack/multiplane/verify-rbac.py b/hack/multiplane/verify-rbac.py index 2583bbcf..1c733932 100755 --- a/hack/multiplane/verify-rbac.py +++ b/hack/multiplane/verify-rbac.py @@ -1,6 +1,6 @@ #!/usr/bin/env python3 """Negative writes and credential revocation against real API servers.""" -import json,pathlib,subprocess,sys,time +import json,os,pathlib,subprocess,sys,time s=pathlib.Path(sys.argv[1]);ns='fleet-coordination' def call(config,*args,input=None):return subprocess.run(['kubectl','--kubeconfig',str(config),'--request-timeout=15s',*args],input=input,text=True,capture_output=True) def forbidden(config,*args): @@ -67,8 +67,10 @@ def can(*args): retained=[('create','customresourcedefinitions'),('delete','customresourcedefinitions'),('update','leases','-n','kro-system')] retained={' '.join(a):can(*a) for a in retained} image=json.loads((s/'gitops-environment.json').read_text())['siteImage'] +redfish=os.environ.get('FLEET_SITE_PROVIDER')=='redfish' def job(**change): c={'name':'worker','image':image,'command':['fleet-multiplane','site-worker'],'securityContext':{'runAsUser':0,'allowPrivilegeEscalation':False,'readOnlyRootFilesystem':True,'capabilities':{'drop':['ALL']}}} + if redfish:c['env']=[{'name':'FLEET_SITE_PROVIDER','value':'redfish'}] spec={'restartPolicy':'Never','serviceAccountName':'w-op-admission-probe','containers':[c],'volumes':[{'name':'state','persistentVolumeClaim':{'claimName':'fleet-site-state'}},{'name':'tmp','emptyDir':{}}]} for k,v in change.items(): (c if k in ('image','securityContext','env','volumeMounts') else spec)[k]=v @@ -85,6 +87,16 @@ def job(**change): 'Job from another image':job(image='registry.k8s.io/pause:3.10'),'Job with a hostPath volume':job(volumes=[{'name':'host','hostPath':{'path':'/'}}]), 'Job on the host network':job(hostNetwork=True),'Role listing every handoff':role([dict(own[0],resourceNames=[],verbs=['get','list'])]), 'RoleBinding to another Role, for the observer':binding('w-op-admission-probe','fleet-site-observer','fleet-site-kro-worker-rbac'),'ServiceAccount outside the worker set':sa('fleet-site-probe')}} +if redfish: + # Redfish workers have no hypervisor path: the libvirt socket, the lab disks + # and a libvirt URI are denied by policy; only the BMC credential is added. + creds=[{'name':'state','persistentVolumeClaim':{'claimName':'fleet-site-state'}},{'name':'credentials','secret':{'secretName':'fleet-site-bmc-credentials'}}] + cases['admitted']['Redfish worker Job with the BMC credential']=job(volumes=creds) + cases['denied'].update({'Redfish worker mounting the libvirt socket':job(volumeMounts=[{'name':'state','mountPath':'/run/fleet-libvirt','subPath':'libvirt-socket'}]), + 'Redfish worker mounting the lab disks':job(volumeMounts=[{'name':'state','mountPath':'/var/lib/fleet-lab/disks','subPath':'lab-disks'}]), + 'Redfish worker with a libvirt URI':job(env=[{'name':'FLEET_SITE_PROVIDER','value':'redfish'},{'name':'FLEET_LIBVIRT_URI','value':'qemu:///system?socket=/run/fleet-libvirt/libvirt-sock'}]), + 'worker selecting the libvirt provider':job(env=[{'name':'FLEET_SITE_PROVIDER','value':'libvirt'}]), + 'Redfish worker mounting another Secret':job(volumes=[{'name':'other','secret':{'secretName':'fleet-site-other'}}])}) record={'identity':kro,'allowed':[' '.join(a) for a in allowed],'denied':[' '.join(a) for a in denied],'chartGrantsRetained':retained,'admission':{}} for outcome,objs in cases.items(): for name,obj in objs.items(): diff --git a/hack/redfish-lab/Containerfile b/hack/redfish-lab/Containerfile new file mode 100644 index 00000000..90191e4c --- /dev/null +++ b/hack/redfish-lab/Containerfile @@ -0,0 +1,17 @@ +# Lab BMC: the unmodified DMTF Redfish Interface Emulator 1.2.2 plus the +# lab-only libvirt adapter. The upstream tree comes from the named build +# context "upstream", which the harness fills from the release archive only +# after verifying its SHA-256 (hack/redfish-lab/upstream.sh). Python +# dependencies are hash-pinned; apt resolution of libvirt-clients is not +# reproducible (the same caveat as the site image). +FROM python:3.12.12-slim-bookworm@sha256:593bd06efe90efa80dc4eee3948be7c0fde4134606dd40d8dd8dbcade98e669c +RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends libvirt-clients && rm -rf /var/lib/apt/lists/* +COPY requirements.lock /tmp/requirements.lock +RUN pip install --no-cache-dir --no-deps --require-hashes -r /tmp/requirements.lock && rm /tmp/requirements.lock +COPY --from=upstream . /opt/redfish-emulator +COPY emulator-config.json populate-config.json targets.json /etc/fleet-bmc/ +COPY fleet_lab_adapter.py test_adapter.py fake_virsh.py /opt/fleet-lab/ +RUN chmod 755 /opt/fleet-lab/*.py +ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 +ENTRYPOINT ["python3", "/opt/fleet-lab/fleet_lab_adapter.py"] +CMD ["serve"] diff --git a/hack/redfish-lab/emulator-config.json b/hack/redfish-lab/emulator-config.json new file mode 100644 index 00000000..33297317 --- /dev/null +++ b/hack/redfish-lab/emulator-config.json @@ -0,0 +1,7 @@ +{ + "MODE": "Local", + "HTTPS": "Disable", + "TRAYS": [], + "SPEC": "Redfish", + "POPULATE": "/etc/fleet-bmc/populate-config.json" +} diff --git a/hack/redfish-lab/fake_virsh.py b/hack/redfish-lab/fake_virsh.py new file mode 100755 index 00000000..d936439b --- /dev/null +++ b/hack/redfish-lab/fake_virsh.py @@ -0,0 +1,33 @@ +#!/usr/bin/env python3 +"""Offline stand-in for virsh used only by test_adapter.py: records calls, keeps state in JSON.""" +import json, os, re, sys +state_path = os.environ['FAKE_VIRSH_STATE'] +s = json.load(open(state_path)) if os.path.exists(state_path) else {'domains': {}, 'networks': {}, 'calls': []} +args = sys.argv[3:] # drop --connect URI +s['calls'].append(args[0]) +def done(out='', code=0): + json.dump(s, open(state_path, 'w')) + print(out); sys.exit(code) +cmd = args[0] +if os.environ.get('FAKE_VIRSH_DOWN'): + print('cannot connect', file=sys.stderr); done(code=1) +if cmd == 'net-info': + n = s['networks'].get(args[1]) + done('Active: %s' % ('yes' if n and n['active'] else 'no')) if n else done(code=1) +if cmd == 'net-define': + s['networks'][re.search(r'([^<]+)', sys.stdin.read()).group(1)] = {'active': False}; done() +if cmd == 'net-start': + s['networks'][args[1]]['active'] = True; done() +if cmd == 'define': + xml = sys.stdin.read(); name = re.search(r'([^<]+)', xml).group(1) + d = s['domains'].setdefault(name, {'running': False, 'starts': []}) + d['uuid'] = re.search(r'([^<]+)', xml).group(1); d['boot'] = re.search(r"{domain}{uuid}20482" + "" + "hvm" + "destroydestroydestroy" + "/usr/bin/qemu-system-x86_64" + "" + "" + "" + "" + "").format(boot=boot, **t) + + +def network_xml(targets, boot_ip): + hosts = ''.join("" % (t['mac'], t['ip']) for t in targets.values()) + ips = sorted(t['ip'] for t in targets.values()) + return ("" + NETWORK + "" + "%s" + "") % (ips[0], ips[-1], hosts, boot_ip) + + +class Lab: + """Exact System -> persistent libvirt domain mapping and BMC NVRAM.""" + + def __init__(self, targets, state, boot_ip): + self.targets, self.state, self.boot_ip = targets, state, boot_ip + self.nvram_path = os.path.join(state, 'nvram.json') + self.nvram = read_json(self.nvram_path, {}) + for sid in targets: + self.nvram.setdefault(sid, {'BootSourceOverrideEnabled': 'Disabled', 'BootSourceOverrideTarget': 'None'}) + atomic_write(self.nvram_path, self.nvram) + + def ensure(self, sid): + """Define lost libvirt objects (the runtime Pod's libvirt config is not durable).""" + t = self.targets[sid] + try: + info = virsh('net-info', NETWORK) + if not re.search(r'^Active:\s+yes', info, re.M): + virsh('net-start', NETWORK) + except LibvirtError: + virsh('net-define', '/dev/stdin', input=network_xml(self.targets, self.boot_ip)) + virsh('net-start', NETWORK) + try: + uuid = virsh('domuuid', t['domain']) + except LibvirtError: + virsh('define', '/dev/stdin', input=domain_xml(t, 'hd')) + uuid = virsh('domuuid', t['domain']) + if uuid != t['uuid']: + raise LibvirtError('lab domain identity changed; refusing to control it') + + def power(self, sid): + state = virsh('domstate', self.targets[sid]['domain']) + if state in ('running', 'paused', 'idle', 'blocked'): + return 'On' + if state == 'in shutdown': + return 'PoweringOff' + return 'Off' + + def save(self): + atomic_write(self.nvram_path, self.nvram) + + def power_on(self, sid): + t, boot = self.targets[sid], 'hd' + override = self.nvram[sid] + if override['BootSourceOverrideEnabled'] == 'Once' and override['BootSourceOverrideTarget'] in ('Pxe', 'Hdd'): + boot = 'network' if override['BootSourceOverrideTarget'] == 'Pxe' else 'hd' + # Once is consumed by this boot. Persisted before start, like NVRAM. + self.nvram[sid] = {'BootSourceOverrideEnabled': 'Disabled', 'BootSourceOverrideTarget': 'None'} + self.save() + virsh('define', '/dev/stdin', input=domain_xml(t, boot)) + virsh('start', t['domain']) + return boot + + +def error(status, message): + return {'error': {'code': 'Base.1.0.GeneralError', 'message': message}}, status + + +def challenge(): + body, status = error(401, 'authentication required') + return body, status, {'WWW-Authenticate': 'Basic realm="fleet-lab-bmc"'} + + +def create_app(targets, state, credentials, boot_ip): + os.makedirs(state, exist_ok=True) + os.chdir(CONFIG_DIR) + sys.path.insert(0, UPSTREAM) + import logging + import g # upstream module: Flask app and flask_restful API + import emulator # noqa: F401 upstream: loads resources and runs infragen populate on import + from api_emulator.redfish import ComputerSystem_api as cs + from api_emulator.redfish import ResetActionInfo_api as rai + from flask import g as request_context, request + logging.getLogger().setLevel(logging.WARNING) + lab = Lab(targets, state, boot_ip) + faults = FaultFile(state) + audit_path = os.path.join(state, 'audit.log') + + def publish(sid, power=None): + m = cs.members[sid] + m['UUID'] = targets[sid]['uuid'] + m['Name'] = targets[sid]['name'] + m['Manufacturer'] = 'DMTF Redfish Interface Emulator (Fleet lab adapter)' + m['Model'] = 'libvirt/QEMU lab target' + m['Boot'] = dict(lab.nvram[sid], BootSourceOverrideMode='Legacy', **{ + 'BootSourceOverrideTarget@Redfish.AllowableValues': list(BOOT_TARGETS), + 'BootSourceOverrideEnabled@Redfish.AllowableValues': list(BOOT_ENABLED)}) + if power: + m['PowerState'] = power + hidden = set(faults.read().get('hideResetTypes', [])) + rai.members[sid]['Parameters'][0]['AllowableValues'] = [v for v in RESET_TYPES if v not in hidden] + + for sid in targets: + if sid not in cs.members or sid not in rai.members: + raise SystemExit('populate did not create lab System ' + sid) + publish(sid, 'Off') + + def authorized(): + header = request.headers.get('Authorization', '') + if not header.startswith('Basic '): + return False + try: + user, _, password = base64.b64decode(header[6:], validate=True).decode().partition(':') + except ValueError: + return False + with open(os.path.join(credentials, 'username')) as f: + want_user = f.read().strip() + with open(os.path.join(credentials, 'password')) as f: + want_password = f.read().strip() + return hmac.compare_digest(user.encode(), want_user.encode()) & hmac.compare_digest(password.encode(), want_password.encode()) + + def take(kind, match=None): + def fn(value): + if kind == 'rejectAuth': + if value.get('rejectAuth', 0) > 0: + value['rejectAuth'] -= 1 + return True + return False + for i, f in enumerate(value.get(kind, [])): + if match(f): + if f.get('skip', 0) > 0: + f['skip'] -= 1 # let this matching request through unfaulted + return None + return value[kind].pop(i) + return None + return faults.update(fn) + + @g.app.before_request + def guard(): + request_context.principal, request_context.detail = 'anonymous', {} + path = request.path.rstrip('/') or '/' + if path in ('/redfish', '/redfish/v1') and request.method == 'GET': + return None # the service root is unauthenticated (Redfish specification) + if not path.startswith('/redfish/v1/') or path == '/redfish/v1/reset': + return error(404, 'not served by this lab BMC') + if not authorized(): + request_context.principal = 'rejected' + return challenge() + if take('rejectAuth'): + request_context.principal, request_context.detail = 'rejected', {'fault': 'reject-auth'} + return challenge() + request_context.principal = 'authenticated' + m = re.fullmatch(r'/redfish/v1/Systems/([^/]+)(/Actions/ComputerSystem\.Reset|/ResetActionInfo)?', path) + if not m: + return None + sid, sub = m.group(1), m.group(2) + if sid not in targets: + return None + try: + with LOCK: + lab.ensure(sid) + publish(sid, lab.power(sid)) + except LibvirtError as e: + return error(503, 'lab hardware unavailable: %s' % e) + if sub is None and request.method == 'PATCH': + body = request.get_json(force=True, silent=True) + if not isinstance(body, dict) or 'Boot' not in body: + return None # upstream handles its own patchable properties + return patch_boot(sid, body) + if sub == '/Actions/ComputerSystem.Reset' and request.method == 'POST': + return reset(sid) + return None + + def patch_boot(sid, body): + boot = body['Boot'] + if set(body) != {'Boot'} or not isinstance(boot, dict) or not set(boot) <= {'BootSourceOverrideTarget', 'BootSourceOverrideEnabled', 'BootSourceOverrideMode'}: + return error(400, 'only Boot source override properties are patchable with Boot') + current = dict(lab.nvram[sid]) + current.update({k: v for k, v in boot.items() if k != 'BootSourceOverrideMode'}) + if boot.get('BootSourceOverrideMode', 'Legacy') != 'Legacy' or current['BootSourceOverrideTarget'] not in BOOT_TARGETS or current['BootSourceOverrideEnabled'] not in BOOT_ENABLED: + return error(400, 'unsupported boot override value') + if current['BootSourceOverrideTarget'] == 'None': + current['BootSourceOverrideEnabled'] = 'Disabled' + with LOCK: + lab.nvram[sid] = current + lab.save() + publish(sid) + request_context.detail = {'boot': current} + return cs.members[sid], 200 + + def reset(sid): + body = request.get_json(force=True, silent=True) + kind = body.get('ResetType') if isinstance(body, dict) and set(body) == {'ResetType'} else None + allowed = [v for v in RESET_TYPES if v not in set(faults.read().get('hideResetTypes', []))] + if kind not in allowed: + return error(400, 'unsupported ResetType') + domain = targets[sid]['domain'] + try: + with LOCK: + power = lab.power(sid) + effect = 'none' + if kind in ('ForceOff', 'ForceRestart') and power != 'Off': + virsh('destroy', domain) + effect = 'destroyed' + if kind in ('On', 'ForceRestart') and (kind == 'ForceRestart' or power == 'Off'): + effect = 'started:' + lab.power_on(sid) + publish(sid, lab.power(sid)) + except LibvirtError as e: + return error(503, 'lab hardware unavailable: %s' % e) + request_context.detail = {'resetType': kind, 'effect': effect} + drop = take('dropResponse', lambda f: f.get('system') == sid and f.get('resetType') == kind) if effect.startswith('started') else None + if drop: + # Lab fault: the effect is applied, the response is withheld past the client timeout. + request_context.detail['fault'] = 'drop-response-after-effect' + time.sleep(min(int(drop.get('seconds', 45)), 120)) + return '', 204 + + @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')} + entry.update(getattr(request_context, 'detail', {})) + with LOCK, open(audit_path, 'a') as f: + f.write(json.dumps(entry, sort_keys=True) + '\n') + f.flush() + os.fsync(f.fileno()) + return response + + return g.app + + +def load_targets(): + with open(os.path.join(CONFIG_DIR, 'targets.json')) as f: + return {t['system']: t for t in json.load(f)} + + +def fault_cli(args): + faults = FaultFile(STATE) + if args[:1] == ['drop-response'] and len(args) in (4, 5): + skip = int(args[4]) if len(args) == 5 else 0 + faults.update(lambda v: v.setdefault('dropResponse', []).append({'system': args[1], 'resetType': args[2], 'seconds': int(args[3]), 'skip': skip})) + elif args[:1] == ['reject-auth'] and len(args) == 2: + faults.update(lambda v: v.__setitem__('rejectAuth', int(args[1]))) + elif args[:1] == ['hide-reset'] and len(args) == 2: + faults.update(lambda v: v.setdefault('hideResetTypes', []).append(args[1])) + elif args == ['clear']: + faults.update(lambda v: v.clear()) + elif args == ['show']: + pass + else: + raise SystemExit('usage: fault drop-response SYSTEM RESETTYPE SECONDS [SKIP] | reject-auth COUNT | hide-reset TYPE | clear | show') + print(json.dumps(faults.read(), sort_keys=True)) + + +def main(): + if sys.argv[1:2] == ['serve']: + boot_ip = os.environ.get('FLEET_BOOT_IP', '') + if not re.fullmatch(r'\d+\.\d+\.\d+\.\d+', boot_ip): + raise SystemExit('FLEET_BOOT_IP must be the boot Service IPv4 address') + create_app(load_targets(), STATE, CREDENTIALS, boot_ip).run(host='0.0.0.0', port=PORT, threaded=True) + elif sys.argv[1:2] == ['fault']: + fault_cli(sys.argv[2:]) + else: + raise SystemExit('usage: fleet_lab_adapter.py serve | fault ...') + + +if __name__ == '__main__': + main() diff --git a/hack/redfish-lab/populate-config.json b/hack/redfish-lab/populate-config.json new file mode 100644 index 00000000..a643ce4a --- /dev/null +++ b/hack/redfish-lab/populate-config.json @@ -0,0 +1,24 @@ +{ + "POPULATE": { + "Chassis": [ + { + "Name": "Fleet lab chassis", + "Id": "Chassis-{0}", + "Count": 1, + "Links": { + "ComputerSystems": [ + { + "Name": "Fleet lab target", + "Id": "System-{0}", + "Count": 2, + "Processors": [{"Id": "CPU{0}", "TotalCores": 2, "MaxSpeedMHz": 2000, "Count": 1}], + "Memory": [{"Id": "DRAM{0}", "CapacityMiB": 2048, "MemoryType": "DRAM", "Count": 1}], + "SimpleStorage": [{"Id": "VirtIO-{0}", "Count": 1, "Devices": {"CapacityBytes": 2147483648, "Count": 1}}], + "EthernetInterfaces": [{"Id": "NIC-{0}", "SpeedMbps": 1000, "Count": 1}] + } + ] + } + } + ] + } +} diff --git a/hack/redfish-lab/requirements.lock b/hack/redfish-lab/requirements.lock new file mode 100644 index 00000000..fbfc6321 --- /dev/null +++ b/hack/redfish-lab/requirements.lock @@ -0,0 +1,203 @@ +# Exact Python dependencies of DMTF Redfish-Interface-Emulator 1.2.2 (its requirements.txt +# lists names only). Installed with pip --require-hashes; hashes are every PyPI file of each version. +Flask==2.3.3 \ + --hash=sha256:09c347a92aa7ff4a8e7f3206795f30d826654baf38b873d0744cd571ca609efc \ + --hash=sha256:f69fcd559dc907ed196ab9df0e48471709175e696d6e698dd4dbe940f96ce66b +Werkzeug==2.3.8 \ + --hash=sha256:554b257c74bbeb7a0d254160a4f8ffe185243f52a52035060b761ca62d977f03 \ + --hash=sha256:bba1f19f8ec89d4d607a3bd62f1904bd2e609472d93cd85e9d4e178f472c3748 +Jinja2==3.1.6 \ + --hash=sha256:0137fb05990d35f1275a587e9aee6d56da821fc83491a0fb838183be43f66d6d \ + --hash=sha256:85ece4451f492d0c13c5dd7c13a64681a86afae63a5f347908daf103ce6d2f67 +MarkupSafe==2.1.5 \ + --hash=sha256:00e046b6dd71aa03a41079792f8473dc494d564611a8f89bbbd7cb93295ebdcf \ + --hash=sha256:075202fa5b72c86ad32dc7d0b56024ebdbcf2048c0ba09f1cde31bfdd57bcfff \ + --hash=sha256:0e397ac966fdf721b2c528cf028494e86172b4feba51d65f81ffd65c63798f3f \ + --hash=sha256:17b950fccb810b3293638215058e432159d2b71005c74371d784862b7e4683f3 \ + --hash=sha256:1f3fbcb7ef1f16e48246f704ab79d79da8a46891e2da03f8783a5b6fa41a9532 \ + --hash=sha256:2174c595a0d73a3080ca3257b40096db99799265e1c27cc5a610743acd86d62f \ + --hash=sha256:2b7c57a4dfc4f16f7142221afe5ba4e093e09e728ca65c51f5620c9aaeb9a617 \ + --hash=sha256:2d2d793e36e230fd32babe143b04cec8a8b3eb8a3122d2aceb4a371e6b09b8df \ + --hash=sha256:30b600cf0a7ac9234b2638fbc0fb6158ba5bdcdf46aeb631ead21248b9affbc4 \ + --hash=sha256:397081c1a0bfb5124355710fe79478cdbeb39626492b15d399526ae53422b906 \ + --hash=sha256:3a57fdd7ce31c7ff06cdfbf31dafa96cc533c21e443d57f5b1ecc6cdc668ec7f \ + --hash=sha256:3c6b973f22eb18a789b1460b4b91bf04ae3f0c4234a0a6aa6b0a92f6f7b951d4 \ + --hash=sha256:3e53af139f8579a6d5f7b76549125f0d94d7e630761a2111bc431fd820e163b8 \ + --hash=sha256:4096e9de5c6fdf43fb4f04c26fb114f61ef0bf2e5604b6ee3019d51b69e8c371 \ + --hash=sha256:4275d846e41ecefa46e2015117a9f491e57a71ddd59bbead77e904dc02b1bed2 \ + --hash=sha256:4c31f53cdae6ecfa91a77820e8b151dba54ab528ba65dfd235c80b086d68a465 \ + --hash=sha256:4f11aa001c540f62c6166c7726f71f7573b52c68c31f014c25cc7901deea0b52 \ + --hash=sha256:5049256f536511ee3f7e1b3f87d1d1209d327e818e6ae1365e8653d7e3abb6a6 \ + --hash=sha256:58c98fee265677f63a4385256a6d7683ab1832f3ddd1e66fe948d5880c21a169 \ + --hash=sha256:598e3276b64aff0e7b3451b72e94fa3c238d452e7ddcd893c3ab324717456bad \ + --hash=sha256:5b7b716f97b52c5a14bffdf688f971b2d5ef4029127f1ad7a513973cfd818df2 \ + --hash=sha256:5dedb4db619ba5a2787a94d877bc8ffc0566f92a01c0ef214865e54ecc9ee5e0 \ + --hash=sha256:619bc166c4f2de5caa5a633b8b7326fbe98e0ccbfacabd87268a2b15ff73a029 \ + --hash=sha256:629ddd2ca402ae6dbedfceeba9c46d5f7b2a61d9749597d4307f943ef198fc1f \ + --hash=sha256:656f7526c69fac7f600bd1f400991cc282b417d17539a1b228617081106feb4a \ + --hash=sha256:6ec585f69cec0aa07d945b20805be741395e28ac1627333b1c5b0105962ffced \ + --hash=sha256:72b6be590cc35924b02c78ef34b467da4ba07e4e0f0454a2c5907f473fc50ce5 \ + --hash=sha256:7502934a33b54030eaf1194c21c692a534196063db72176b0c4028e140f8f32c \ + --hash=sha256:7a68b554d356a91cce1236aa7682dc01df0edba8d043fd1ce607c49dd3c1edcf \ + --hash=sha256:7b2e5a267c855eea6b4283940daa6e88a285f5f2a67f2220203786dfa59b37e9 \ + --hash=sha256:823b65d8706e32ad2df51ed89496147a42a2a6e01c13cfb6ffb8b1e92bc910bb \ + --hash=sha256:8590b4ae07a35970728874632fed7bd57b26b0102df2d2b233b6d9d82f6c62ad \ + --hash=sha256:8dd717634f5a044f860435c1d8c16a270ddf0ef8588d4887037c5028b859b0c3 \ + --hash=sha256:8dec4936e9c3100156f8a2dc89c4b88d5c435175ff03413b443469c7c8c5f4d1 \ + --hash=sha256:97cafb1f3cbcd3fd2b6fbfb99ae11cdb14deea0736fc2b0952ee177f2b813a46 \ + --hash=sha256:a17a92de5231666cfbe003f0e4b9b3a7ae3afb1ec2845aadc2bacc93ff85febc \ + --hash=sha256:a549b9c31bec33820e885335b451286e2969a2d9e24879f83fe904a5ce59d70a \ + --hash=sha256:ac07bad82163452a6884fe8fa0963fb98c2346ba78d779ec06bd7a6262132aee \ + --hash=sha256:ae2ad8ae6ebee9d2d94b17fb62763125f3f374c25618198f40cbb8b525411900 \ + --hash=sha256:b91c037585eba9095565a3556f611e3cbfaa42ca1e865f7b8015fe5c7336d5a5 \ + --hash=sha256:bc1667f8b83f48511b94671e0e441401371dfd0f0a795c7daa4a3cd1dde55bea \ + --hash=sha256:bec0a414d016ac1a18862a519e54b2fd0fc8bbfd6890376898a6c0891dd82e9f \ + --hash=sha256:bf50cd79a75d181c9181df03572cdce0fbb75cc353bc350712073108cba98de5 \ + --hash=sha256:bff1b4290a66b490a2f4719358c0cdcd9bafb6b8f061e45c7a2460866bf50c2e \ + --hash=sha256:c061bb86a71b42465156a3ee7bd58c8c2ceacdbeb95d05a99893e08b8467359a \ + --hash=sha256:c8b29db45f8fe46ad280a7294f5c3ec36dbac9491f2d1c17345be8e69cc5928f \ + --hash=sha256:ce409136744f6521e39fd8e2a24c53fa18ad67aa5bc7c2cf83645cce5b5c4e50 \ + --hash=sha256:d050b3361367a06d752db6ead6e7edeb0009be66bc3bae0ee9d97fb326badc2a \ + --hash=sha256:d283d37a890ba4c1ae73ffadf8046435c76e7bc2247bbb63c00bd1a709c6544b \ + --hash=sha256:d9fad5155d72433c921b782e58892377c44bd6252b5af2f67f16b194987338a4 \ + --hash=sha256:daa4ee5a243f0f20d528d939d06670a298dd39b1ad5f8a72a4275124a7819eff \ + --hash=sha256:db0b55e0f3cc0be60c1f19efdde9a637c32740486004f20d1cff53c3c0ece4d2 \ + --hash=sha256:e61659ba32cf2cf1481e575d0462554625196a1f2fc06a1c777d3f48e8865d46 \ + --hash=sha256:ea3d8a3d18833cf4304cd2fc9cbb1efe188ca9b5efef2bdac7adc20594a0e46b \ + --hash=sha256:ec6a563cff360b50eed26f13adc43e61bc0c04d94b8be985e6fb24b81f6dcfdf \ + --hash=sha256:f5dfb42c4604dddc8e4305050aa6deb084540643ed5804d7455b5df8fe16f5e5 \ + --hash=sha256:fa173ec60341d6bb97a89f5ea19c85c5643c1e7dedebc22f5181eb73573142c5 \ + --hash=sha256:fa9db3f79de01457b03d4f01b34cf91bc0048eb2c3846ff26f66687c2f6d16ab \ + --hash=sha256:fce659a462a1be54d2ffcacea5e3ba2d74daa74f30f5f143fe0c58636e355fdd \ + --hash=sha256:ffee1f21e5ef0d712f9033568f8344d5da8cc2869dbd08d87c84656e6a2d2f68 +itsdangerous==2.2.0 \ + --hash=sha256:c6242fc49e35958c8b15141343aa660db5fc54d4f13a1db01a3f5891b98700ef \ + --hash=sha256:e0050c0b7da1eea53ffaf149c0cfbb5c6e2e2b69c4bef22c81fa6eb73e5f6173 +click==8.1.8 \ + --hash=sha256:63c132bbbed01578a06712a2d1f497bb62d9c1c0d329b7903a866228027263b2 \ + --hash=sha256:ed53c9d8990d83c2a27deae68e4ee337473f6330c040a31d4225c9574d16096a +blinker==1.9.0 \ + --hash=sha256:b4ce2265a7abece45e7cc896e98dbebe6cead56bcf805a3d23136d145f5445bf \ + --hash=sha256:ba0efaa9080b619ff2f3459d1d500c57bddea4a6b424b60a91141db6fd2f08bc +Flask-RESTful==0.3.10 \ + --hash=sha256:1cf93c535172f112e080b0d4503a8d15f93a48c88bdd36dd87269bdaf405051b \ + --hash=sha256:fe4af2ef0027df8f9b4f797aba20c5566801b6ade995ac63b588abf1a59cec37 +aniso8601==9.0.1 \ + --hash=sha256:1d2b7ef82963909e93c4f24ce48d4de9e66009a21bf1c1e1c85bdd0812fe412f \ + --hash=sha256:72e3117667eedf66951bb2d93f4296a56b94b078a8a95905a052611fb3f1b973 +pytz==2025.2 \ + --hash=sha256:360b9e3dbb49a209c21ad61809c7fb453643e048b38924c765813546746e81c3 \ + --hash=sha256:5ddf76296dd8c44c26eb8f4b6f35488f3ccbf6fbbd7adee0b7262d43f0ec2f00 +six==1.17.0 \ + --hash=sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274 \ + --hash=sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81 +StringGenerator==0.4.4 \ + --hash=sha256:35f86752460b25b2ccf936f6c8b0ed330cf49b01a34a5400cbf3fa6693dea609 +requests==2.32.3 \ + --hash=sha256:55365417734eb18255590a9ff9eb97e9e1da868d4ccd6402399eaf68af20a760 \ + --hash=sha256:70761cfe03c773ceb22aa2f671b4757976145175cdfca038c02654d061d6dcc6 +urllib3==2.2.3 \ + --hash=sha256:ca899ca043dcb1bafa3e262d73aa25c465bfb49e0bd9dd5d59f1d0acba2f8fac \ + --hash=sha256:e7d814a81dad81e6caf2ec9fdedb284ecc9c73076b62654547cc64ccdcae26e9 +certifi==2025.1.31 \ + --hash=sha256:3d5da6925056f6f18f119200434a4780a94263f10d1c21d032a6f6b2baa20651 \ + --hash=sha256:ca78db4565a652026a4db2bcdf68f2fb589ea80d0be70e03929ed730746b84fe +idna==3.10 \ + --hash=sha256:12f65c9b470abda6dc35cf8e63cc574b1c52b11df2c86030af0ac09b01b13ea9 \ + --hash=sha256:946d195a0d259cbba61165e88e65941f16e9b36ea6ddb97f00452bae8b1287d3 +charset-normalizer==3.4.1 \ + --hash=sha256:0167ddc8ab6508fe81860a57dd472b2ef4060e8d378f0cc555707126830f2537 \ + --hash=sha256:01732659ba9b5b873fc117534143e4feefecf3b2078b0a6a2e925271bb6f4cfa \ + --hash=sha256:01ad647cdd609225c5350561d084b42ddf732f4eeefe6e678765636791e78b9a \ + --hash=sha256:04432ad9479fa40ec0f387795ddad4437a2b50417c69fa275e212933519ff294 \ + --hash=sha256:0907f11d019260cdc3f94fbdb23ff9125f6b5d1039b76003b5b0ac9d6a6c9d5b \ + --hash=sha256:0924e81d3d5e70f8126529951dac65c1010cdf117bb75eb02dd12339b57749dd \ + --hash=sha256:09b26ae6b1abf0d27570633b2b078a2a20419c99d66fb2823173d73f188ce601 \ + --hash=sha256:09b5e6733cbd160dcc09589227187e242a30a49ca5cefa5a7edd3f9d19ed53fd \ + --hash=sha256:0af291f4fe114be0280cdd29d533696a77b5b49cfde5467176ecab32353395c4 \ + --hash=sha256:0f55e69f030f7163dffe9fd0752b32f070566451afe180f99dbeeb81f511ad8d \ + --hash=sha256:1a2bc9f351a75ef49d664206d51f8e5ede9da246602dc2d2726837620ea034b2 \ + --hash=sha256:22e14b5d70560b8dd51ec22863f370d1e595ac3d024cb8ad7d308b4cd95f8313 \ + --hash=sha256:234ac59ea147c59ee4da87a0c0f098e9c8d169f4dc2a159ef720f1a61bbe27cd \ + --hash=sha256:2369eea1ee4a7610a860d88f268eb39b95cb588acd7235e02fd5a5601773d4fa \ + --hash=sha256:237bdbe6159cff53b4f24f397d43c6336c6b0b42affbe857970cefbb620911c8 \ + --hash=sha256:28bf57629c75e810b6ae989f03c0828d64d6b26a5e205535585f96093e405ed1 \ + --hash=sha256:2967f74ad52c3b98de4c3b32e1a44e32975e008a9cd2a8cc8966d6a5218c5cb2 \ + --hash=sha256:2a75d49014d118e4198bcee5ee0a6f25856b29b12dbf7cd012791f8a6cc5c496 \ + --hash=sha256:2bdfe3ac2e1bbe5b59a1a63721eb3b95fc9b6817ae4a46debbb4e11f6232428d \ + --hash=sha256:2d074908e1aecee37a7635990b2c6d504cd4766c7bc9fc86d63f9c09af3fa11b \ + --hash=sha256:2fb9bd477fdea8684f78791a6de97a953c51831ee2981f8e4f583ff3b9d9687e \ + --hash=sha256:311f30128d7d333eebd7896965bfcfbd0065f1716ec92bd5638d7748eb6f936a \ + --hash=sha256:329ce159e82018d646c7ac45b01a430369d526569ec08516081727a20e9e4af4 \ + --hash=sha256:345b0426edd4e18138d6528aed636de7a9ed169b4aaf9d61a8c19e39d26838ca \ + --hash=sha256:363e2f92b0f0174b2f8238240a1a30142e3db7b957a5dd5689b0e75fb717cc78 \ + --hash=sha256:3a3bd0dcd373514dcec91c411ddb9632c0d7d92aed7093b8c3bbb6d69ca74408 \ + --hash=sha256:3bed14e9c89dcb10e8f3a29f9ccac4955aebe93c71ae803af79265c9ca5644c5 \ + --hash=sha256:44251f18cd68a75b56585dd00dae26183e102cd5e0f9f1466e6df5da2ed64ea3 \ + --hash=sha256:44ecbf16649486d4aebafeaa7ec4c9fed8b88101f4dd612dcaf65d5e815f837f \ + --hash=sha256:4532bff1b8421fd0a320463030c7520f56a79c9024a4e88f01c537316019005a \ + --hash=sha256:49402233c892a461407c512a19435d1ce275543138294f7ef013f0b63d5d3765 \ + --hash=sha256:4c0907b1928a36d5a998d72d64d8eaa7244989f7aaaf947500d3a800c83a3fd6 \ + --hash=sha256:4d86f7aff21ee58f26dcf5ae81a9addbd914115cdebcbb2217e4f0ed8982e146 \ + --hash=sha256:5777ee0881f9499ed0f71cc82cf873d9a0ca8af166dfa0af8ec4e675b7df48e6 \ + --hash=sha256:5df196eb874dae23dcfb968c83d4f8fdccb333330fe1fc278ac5ceeb101003a9 \ + --hash=sha256:619a609aa74ae43d90ed2e89bdd784765de0a25ca761b93e196d938b8fd1dbbd \ + --hash=sha256:6e27f48bcd0957c6d4cb9d6fa6b61d192d0b13d5ef563e5f2ae35feafc0d179c \ + --hash=sha256:6ff8a4a60c227ad87030d76e99cd1698345d4491638dfa6673027c48b3cd395f \ + --hash=sha256:73d94b58ec7fecbc7366247d3b0b10a21681004153238750bb67bd9012414545 \ + --hash=sha256:7461baadb4dc00fd9e0acbe254e3d7d2112e7f92ced2adc96e54ef6501c5f176 \ + --hash=sha256:75832c08354f595c760a804588b9357d34ec00ba1c940c15e31e96d902093770 \ + --hash=sha256:7709f51f5f7c853f0fb938bcd3bc59cdfdc5203635ffd18bf354f6967ea0f824 \ + --hash=sha256:78baa6d91634dfb69ec52a463534bc0df05dbd546209b79a3880a34487f4b84f \ + --hash=sha256:7974a0b5ecd505609e3b19742b60cee7aa2aa2fb3151bc917e6e2646d7667dcf \ + --hash=sha256:7a4f97a081603d2050bfaffdefa5b02a9ec823f8348a572e39032caa8404a487 \ + --hash=sha256:7b1bef6280950ee6c177b326508f86cad7ad4dff12454483b51d8b7d673a2c5d \ + --hash=sha256:7d053096f67cd1241601111b698f5cad775f97ab25d81567d3f59219b5f1adbd \ + --hash=sha256:804a4d582ba6e5b747c625bf1255e6b1507465494a40a2130978bda7b932c90b \ + --hash=sha256:807f52c1f798eef6cf26beb819eeb8819b1622ddfeef9d0977a8502d4db6d534 \ + --hash=sha256:80ed5e856eb7f30115aaf94e4a08114ccc8813e6ed1b5efa74f9f82e8509858f \ + --hash=sha256:8417cb1f36cc0bc7eaba8ccb0e04d55f0ee52df06df3ad55259b9a323555fc8b \ + --hash=sha256:8436c508b408b82d87dc5f62496973a1805cd46727c34440b0d29d8a2f50a6c9 \ + --hash=sha256:89149166622f4db9b4b6a449256291dc87a99ee53151c74cbd82a53c8c2f6ccd \ + --hash=sha256:8bfa33f4f2672964266e940dd22a195989ba31669bd84629f05fab3ef4e2d125 \ + --hash=sha256:8c60ca7339acd497a55b0ea5d506b2a2612afb2826560416f6894e8b5770d4a9 \ + --hash=sha256:91b36a978b5ae0ee86c394f5a54d6ef44db1de0815eb43de826d41d21e4af3de \ + --hash=sha256:955f8851919303c92343d2f66165294848d57e9bba6cf6e3625485a70a038d11 \ + --hash=sha256:97f68b8d6831127e4787ad15e6757232e14e12060bec17091b85eb1486b91d8d \ + --hash=sha256:9b23ca7ef998bc739bf6ffc077c2116917eabcc901f88da1b9856b210ef63f35 \ + --hash=sha256:9f0b8b1c6d84c8034a44893aba5e767bf9c7a211e313a9605d9c617d7083829f \ + --hash=sha256:aabfa34badd18f1da5ec1bc2715cadc8dca465868a4e73a0173466b688f29dda \ + --hash=sha256:ab36c8eb7e454e34e60eb55ca5d241a5d18b2c6244f6827a30e451c42410b5f7 \ + --hash=sha256:b010a7a4fd316c3c484d482922d13044979e78d1861f0e0650423144c616a46a \ + --hash=sha256:b1ac5992a838106edb89654e0aebfc24f5848ae2547d22c2c3f66454daa11971 \ + --hash=sha256:b7b2d86dd06bfc2ade3312a83a5c364c7ec2e3498f8734282c6c3d4b07b346b8 \ + --hash=sha256:b97e690a2118911e39b4042088092771b4ae3fc3aa86518f84b8cf6888dbdb41 \ + --hash=sha256:bc2722592d8998c870fa4e290c2eec2c1569b87fe58618e67d38b4665dfa680d \ + --hash=sha256:c0429126cf75e16c4f0ad00ee0eae4242dc652290f940152ca8c75c3a4b6ee8f \ + --hash=sha256:c30197aa96e8eed02200a83fba2657b4c3acd0f0aa4bdc9f6c1af8e8962e0757 \ + --hash=sha256:c4c3e6da02df6fa1410a7680bd3f63d4f710232d3139089536310d027950696a \ + --hash=sha256:c75cb2a3e389853835e84a2d8fb2b81a10645b503eca9bcb98df6b5a43eb8886 \ + --hash=sha256:c96836c97b1238e9c9e3fe90844c947d5afbf4f4c92762679acfe19927d81d77 \ + --hash=sha256:d7f50a1f8c450f3925cb367d011448c39239bb3eb4117c36a6d354794de4ce76 \ + --hash=sha256:d973f03c0cb71c5ed99037b870f2be986c3c05e63622c017ea9816881d2dd247 \ + --hash=sha256:d98b1668f06378c6dbefec3b92299716b931cd4e6061f3c875a71ced1780ab85 \ + --hash=sha256:d9c3cdf5390dcd29aa8056d13e8e99526cda0305acc038b96b30352aff5ff2bb \ + --hash=sha256:dad3e487649f498dd991eeb901125411559b22e8d7ab25d3aeb1af367df5efd7 \ + --hash=sha256:dccbe65bd2f7f7ec22c4ff99ed56faa1e9f785482b9bbd7c717e26fd723a1d1e \ + --hash=sha256:dd78cfcda14a1ef52584dbb008f7ac81c1328c0f58184bf9a84c49c605002da6 \ + --hash=sha256:e218488cd232553829be0664c2292d3af2eeeb94b32bea483cf79ac6a694e037 \ + --hash=sha256:e358e64305fe12299a08e08978f51fc21fac060dcfcddd95453eabe5b93ed0e1 \ + --hash=sha256:ea0d8d539afa5eb2728aa1932a988a9a7af94f18582ffae4bc10b3fbdad0626e \ + --hash=sha256:eab677309cdb30d047996b36d34caeda1dc91149e4fdca0b1a039b3f79d9a807 \ + --hash=sha256:eb8178fe3dba6450a3e024e95ac49ed3400e506fd4e9e5c32d30adda88cbd407 \ + --hash=sha256:ecddf25bee22fe4fe3737a399d0d177d72bc22be6913acfab364b40bce1ba83c \ + --hash=sha256:eea6ee1db730b3483adf394ea72f808b6e18cf3cb6454b4d86e04fa8c4327a12 \ + --hash=sha256:f08ff5e948271dc7e18a35641d2f11a4cd8dfd5634f55228b691e62b37125eb3 \ + --hash=sha256:f30bf9fd9be89ecb2360c7d94a711f00c09b976258846efe40db3d05828e8089 \ + --hash=sha256:fa88b843d6e211393a37219e6a1c1df99d35e8fd90446f1118f4216e307e48cd \ + --hash=sha256:fc54db6c8593ef7d4b2a331b58653356cf04f67c960f584edb7c3d8c97e8f39e \ + --hash=sha256:fd4ec41f914fa74ad1b8304bbc634b3de73d2a0889bd32076342a573e0779e00 \ + --hash=sha256:ffc9202a29ab3920fa812879e95a9e78b2465fd10be7fcbd042899695d75e616 +Flask-HTTPAuth==4.8.0 \ + --hash=sha256:66568a05bc73942c65f1e2201ae746295816dc009edd84b482c44c758d75097a \ + --hash=sha256:a58fedd09989b9975448eef04806b096a3964a7feeebc0a78831ff55685b62b0 diff --git a/hack/redfish-lab/targets.json b/hack/redfish-lab/targets.json new file mode 100644 index 00000000..23e256b0 --- /dev/null +++ b/hack/redfish-lab/targets.json @@ -0,0 +1,8 @@ +[ + {"system": "System-1", "name": "fleet-lab-target-a", "domain": "fleet-lab-target-a", + "uuid": "7f3d0c2e-1a5b-4c6d-8e9f-0a1b2c3d4e0a", "mac": "52:54:00:77:01:0a", "ip": "192.168.77.10", + "disk": "/var/lib/fleet-lab/disks/target-a.raw", "console": "/var/lib/fleet-lab-console/target-a.log"}, + {"system": "System-2", "name": "fleet-lab-target-b", "domain": "fleet-lab-target-b", + "uuid": "7f3d0c2e-1a5b-4c6d-8e9f-0a1b2c3d4e0b", "mac": "52:54:00:77:01:0b", "ip": "192.168.77.11", + "disk": "/var/lib/fleet-lab/disks/target-b.raw", "console": "/var/lib/fleet-lab-console/target-b.log"} +] diff --git a/hack/redfish-lab/test_adapter.py b/hack/redfish-lab/test_adapter.py new file mode 100644 index 00000000..e44926a6 --- /dev/null +++ b/hack/redfish-lab/test_adapter.py @@ -0,0 +1,117 @@ +#!/usr/bin/env python3 +"""Self-test of the unmodified upstream emulator plus the lab adapter. + +Runs inside the built BMC image (it needs the pinned upstream emulator and its +Python dependencies) with fake_virsh.py in place of libvirt. The harness runs +it before creating any cluster; see docs/operations/redfish-lab.md. +""" +import base64 +import json +import os +import pathlib +import sys +import tempfile +import unittest + +HERE = pathlib.Path(__file__).resolve().parent +WORK = pathlib.Path(tempfile.mkdtemp()) +(WORK / 'creds').mkdir() +(WORK / 'creds' / 'username').write_text('lab-operator\n') +(WORK / 'creds' / 'password').write_text('synthetic-test-password\n') +os.environ.update(FLEET_VIRSH=str(HERE / 'fake_virsh.py'), FAKE_VIRSH_STATE=str(WORK / 'virsh.json'), FLEET_BMC_STATE=str(WORK / 'state')) +sys.path.insert(0, str(HERE)) +import fleet_lab_adapter as adapter # noqa: E402 + +AUTH = {'Authorization': 'Basic ' + base64.b64encode(b'lab-operator:synthetic-test-password').decode()} +BAD = {'Authorization': 'Basic ' + base64.b64encode(b'lab-operator:wrong').decode()} + + +def virsh_state(): + return json.loads((WORK / 'virsh.json').read_text()) + + +class AdapterTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.app = adapter.create_app(adapter.load_targets(), str(WORK / 'state'), str(WORK / 'creds'), '10.96.0.80').test_client() + + def audit(self): + return [json.loads(l) for l in (WORK / 'state' / 'audit.log').read_text().splitlines()] + + def test_1_service_root_is_upstream_and_unauthenticated(self): + r = self.app.get('/redfish/v1/') + self.assertEqual(r.status_code, 200) + self.assertEqual(r.json['Systems'], {'@odata.id': '/redfish/v1/Systems'}) + self.assertEqual(self.app.delete('/redfish/v1/reset/').status_code, 404) + + def test_2_authentication_is_enforced(self): + self.assertEqual(self.app.get('/redfish/v1/Systems').status_code, 401) + self.assertEqual(self.app.get('/redfish/v1/Systems', headers=BAD).status_code, 401) + members = self.app.get('/redfish/v1/Systems', headers=AUTH).json['Members'] + self.assertEqual(sorted(m['@odata.id'] for m in members), ['/redfish/v1/Systems/System-1', '/redfish/v1/Systems/System-2']) + + def test_3_system_identity_and_capabilities(self): + s = self.app.get('/redfish/v1/Systems/System-1', headers=AUTH).json + self.assertEqual(s['UUID'], '7f3d0c2e-1a5b-4c6d-8e9f-0a1b2c3d4e0a') + self.assertEqual(s['PowerState'], 'Off') + self.assertEqual(s['Boot']['BootSourceOverrideTarget@Redfish.AllowableValues'], ['None', 'Pxe', 'Hdd']) + info = self.app.get(s['Actions']['#ComputerSystem.Reset']['@Redfish.ActionInfo'], headers=AUTH).json + self.assertEqual(info['Parameters'][0]['AllowableValues'], ['On', 'ForceOff', 'ForceRestart']) + + def test_4_boot_once_is_consumed_by_power_on(self): + r = self.app.patch('/redfish/v1/Systems/System-1', headers=AUTH, json={'Boot': {'BootSourceOverrideTarget': 'Pxe', 'BootSourceOverrideEnabled': 'Once'}}) + self.assertEqual(r.status_code, 200) + self.assertEqual(self.app.patch('/redfish/v1/Systems/System-1', headers=AUTH, json={'Boot': {'BootSourceOverrideTarget': 'Cd'}}).status_code, 400) + r = self.app.post('/redfish/v1/Systems/System-1/Actions/ComputerSystem.Reset', headers=AUTH, json={'ResetType': 'On'}) + self.assertEqual(r.status_code, 204) + d = virsh_state()['domains'] + self.assertEqual(d['fleet-lab-target-a']['starts'], ['network']) + self.assertFalse(d['fleet-lab-target-b']['running'] if 'fleet-lab-target-b' in d else False) + s = self.app.get('/redfish/v1/Systems/System-1', headers=AUTH).json + self.assertEqual((s['PowerState'], s['Boot']['BootSourceOverrideEnabled']), ('On', 'Disabled')) + # On while on is a no-op, never a second start. + self.app.post('/redfish/v1/Systems/System-1/Actions/ComputerSystem.Reset', headers=AUTH, json={'ResetType': 'On'}) + self.assertEqual(virsh_state()['domains']['fleet-lab-target-a']['starts'], ['network']) + self.app.post('/redfish/v1/Systems/System-1/Actions/ComputerSystem.Reset', headers=AUTH, json={'ResetType': 'ForceOff'}) + 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_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) + self.assertEqual(self.app.get('/redfish/v1/Systems', headers=AUTH).status_code, 200) + adapter.fault_cli(['hide-reset', 'On']) + info = self.app.get('/redfish/v1/Systems/System-1/ResetActionInfo', headers=AUTH).json + self.assertNotIn('On', info['Parameters'][0]['AllowableValues']) + self.assertEqual(self.app.post('/redfish/v1/Systems/System-1/Actions/ComputerSystem.Reset', headers=AUTH, json={'ResetType': 'On'}).status_code, 400) + adapter.fault_cli(['clear']) + # Skip one effective On, then withhold the response of the next one. + adapter.fault_cli(['drop-response', 'System-1', 'On', '1', '1']) + self.app.post('/redfish/v1/Systems/System-1/Actions/ComputerSystem.Reset', headers=AUTH, json={'ResetType': 'On'}) + self.assertNotIn('fault', self.audit()[-1]) + self.app.post('/redfish/v1/Systems/System-1/Actions/ComputerSystem.Reset', headers=AUTH, json={'ResetType': 'ForceOff'}) + self.app.post('/redfish/v1/Systems/System-1/Actions/ComputerSystem.Reset', headers=AUTH, json={'ResetType': 'On'}) + entries = self.audit() + self.assertEqual(entries[-1]['fault'], 'drop-response-after-effect') + self.assertEqual(entries[-1]['effect'], 'started:hd') + self.assertEqual(adapter.FaultFile(str(WORK / 'state')).read().get('dropResponse'), []) + text = (WORK / 'state' / 'audit.log').read_text() + self.assertNotIn('synthetic-test-password', text) + self.assertNotIn('Authorization', text) + + def test_6_lost_libvirt_definitions_are_redefined_with_the_same_identity(self): + s = virsh_state() + s['domains'].pop('fleet-lab-target-a') + s['networks'].clear() + (WORK / 'virsh.json').write_text(json.dumps(s)) + self.assertEqual(self.app.get('/redfish/v1/Systems/System-1', headers=AUTH).status_code, 200) + self.assertEqual(virsh_state()['domains']['fleet-lab-target-a']['uuid'], '7f3d0c2e-1a5b-4c6d-8e9f-0a1b2c3d4e0a') + os.environ['FAKE_VIRSH_DOWN'] = '1' + try: + self.assertEqual(self.app.get('/redfish/v1/Systems/System-1', headers=AUTH).status_code, 503) + finally: + del os.environ['FAKE_VIRSH_DOWN'] + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/hack/redfish-lab/upstream.sh b/hack/redfish-lab/upstream.sh new file mode 100755 index 00000000..99845e85 --- /dev/null +++ b/hack/redfish-lab/upstream.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env bash +# Fetch the pinned DMTF Redfish Interface Emulator release into DEST, verified +# before extraction. Prints the provenance record as JSON. +set -euo pipefail +umask 077 +dest=${1:?destination directory} +version=1.2.2 +commit=5f51d8ac48e46665a2a85242434f125aa7b25172 +url=https://github.com/DMTF/Redfish-Interface-Emulator/archive/refs/tags/$version.tar.gz +sha256=acee609abaedaf123b56e7ca5b2534da94bdee6fc1183dde72699c30d63de79f +mkdir -p "$dest" +archive="$dest/redfish-interface-emulator-$version.tar.gz" +[[ -f $archive ]] || curl -fsSL --max-time 120 -o "$archive" "$url" +got=$(shasum -a 256 "$archive" | cut -d' ' -f1) +[[ $got == "$sha256" ]] || { echo "upstream archive digest $got, expected $sha256" >&2; exit 1; } +rm -rf "$dest/src" +mkdir "$dest/src" +python3 - "$archive" "$dest/src" <<'PY' +import sys, tarfile +with tarfile.open(sys.argv[1]) as t: + t.extractall(sys.argv[2], filter='data') +PY +[[ -f $dest/src/Redfish-Interface-Emulator-$version/emulator.py ]] || { echo 'unexpected archive layout' >&2; exit 1; } +printf '{"project":"DMTF Redfish-Interface-Emulator","version":"%s","commit":"%s","archive":"%s","archiveSHA256":"%s","license":"BSD-3-Clause"}\n' "$version" "$commit" "$url" "$sha256" diff --git a/internal/multiplane/runner.go b/internal/multiplane/runner.go index 8f62f34f..869cb956 100644 --- a/internal/multiplane/runner.go +++ b/internal/multiplane/runner.go @@ -371,6 +371,10 @@ func (r *Runner) Allocate(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 lifecycle 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 { request, err := r.request(ctx, index) if err != nil { diff --git a/internal/redfish/boot.go b/internal/redfish/boot.go new file mode 100644 index 00000000..7dd7d1e2 --- /dev/null +++ b/internal/redfish/boot.go @@ -0,0 +1,217 @@ +package redfish + +import ( + "crypto/sha256" + "crypto/subtle" + "encoding/hex" + "fmt" + "io" + "net/http" + "os" + "path/filepath" + "strconv" + "strings" + "time" +) + +// The provisioning network is site infrastructure: its DHCP hands every +// enrolled NIC the same static script, which chains to a per-MAC URL. The MAC +// is routing information, not authentication. Only a retained operation whose +// enrolled target has that MAC and whose boot admission is open receives a +// script, and that script carries the operation's scoped capability. +const chainScript = "#!ipxe\nchain %s/pxe/${net0/mac:hexhyp}/boot.ipxe\n" + +func (p *Provider) admissionOpen(j journal, r *record) bool { + if j.Closed || j.Image != p.image || r.BootClosed || len(r.BootToken) != 64 || !p.clock().Before(r.BootExpires) { + return false + } + if r.Request.BindingID != j.Binding || r.Request.Epoch != j.Epoch || r.Request.FenceToken != j.Fence { + return false + } + for _, ph := range phases[r.Request.Kind] { + if ph.mode != "" && (r.Stage == ph.name+"-requested" || r.Stage == ph.name+"-started") { + return true + } + } + return false +} + +func mode(r *record) string { + if r.Request.Kind == "cleanup" { + return "wipe" + } + return "install" +} + +// BootHandler never serves a caller-selected path. It reads the atomically +// replaced journal on every request and writes only delivery evidence. +func (p *Provider) BootHandler() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, q *http.Request) { + w.Header().Set("Cache-Control", "no-store") + deny := func() { http.Error(w, "boot denied", http.StatusForbidden) } + parts := strings.Split(q.URL.Path, "/") + if q.Method != http.MethodGet || q.URL.RawQuery != "" { + deny() + return + } + if q.URL.Path == "/pxe/boot.ipxe" { + fmt.Fprintf(w, chainScript, p.origin) + return + } + j, err := p.read() + if err != nil || len(parts) != 4 { + deny() + return + } + var r *record + var name string + if parts[1] == "pxe" && parts[3] == "boot.ipxe" { + mac, ok := normalizeMAC(parts[2]) + for _, c := range j.Operations { + if ok && c.Target.MAC == mac && p.admissionOpen(j, c) { + r, name = c, "boot.ipxe" + } + } + } else { + for _, c := range j.Operations { + if key(c.Request.ID)[:16] == parts[1] && len(c.BootToken) == 64 && subtle.ConstantTimeCompare([]byte(parts[2]), []byte(c.BootToken)) == 1 && p.admissionOpen(j, c) { + r, name = c, parts[3] + } + } + } + if r == nil || (name != "boot.ipxe" && name != "kernel" && name != "installer.gz") || (name == "boot.ipxe" && parts[1] != "pxe") { + deny() + return + } + var data []byte + var artifact *os.File + var size int64 + if name == "boot.ipxe" { + base := p.origin + "/" + key(r.Request.ID)[:16] + "/" + r.BootToken + data = []byte(fmt.Sprintf("#!ipxe\nkernel %s/kernel console=ttyS0 rdinit=/init fleet.receipt=%s fleet.mode=%s\ninitrd %s/installer.gz\nboot\n", base, r.Receipt, mode(r), base)) + size = int64(len(data)) + } else { + // Hash the pinned artifact, then serve the same open file. + if artifact, err = os.Open(p.artifacts + "/" + name); err != nil { + deny() + return + } + defer artifact.Close() + manifest, e := os.ReadFile(p.artifacts + "/SHA256SUMS") + sum := sha256.Sum256(manifest) + h := sha256.New() + size, err = io.Copy(h, artifact) + if e != nil || err != nil || p.image != "fleet-local-linux@sha256:"+hex.EncodeToString(sum[:]) || !strings.Contains(string(manifest), hex.EncodeToString(h.Sum(nil))+" "+name+"\n") { + deny() + return + } + if _, err = artifact.Seek(0, io.SeekStart); err != nil { + deny() + return + } + } + if err := p.evidence(r, "admitted", name, size); err != nil { + deny() + return + } + w.Header().Set("Content-Type", "application/octet-stream") + w.Header().Set("Content-Length", strconv.FormatInt(size, 10)) + var n int64 + var werr error + if artifact != nil { + n, werr = io.Copy(w, artifact) + } else { + var written int + written, werr = w.Write(data) + n = int64(written) + } + // A completed server write is not proof of client receipt or boot. + if werr == nil && n == size { + _ = p.evidence(r, "write-complete", name, n) + } + }) +} + +// evidence appends one line without URLs, headers, receipts or capabilities. +func (p *Provider) evidence(r *record, event, name string, size int64) error { + dir := p.bootDirectory(r) + if err := os.MkdirAll(dir, 0700); err != nil { + return err + } + f, err := os.OpenFile(filepath.Join(dir, "boot-delivery.log"), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600) + if err != nil { + return err + } + _, err = fmt.Fprintf(f, "%s %s %s bytes=%d\n", p.clock().Format(time.RFC3339), event, name, size) + if err == nil { + err = f.Sync() + } + if cerr := f.Close(); err == nil { + err = cerr + } + if err == nil { + err = syncDir(dir) + } + return err +} + +// ServeBoot listens on :8080. The write bound covers an emulated firmware +// fetching the initrd through the site's NAT path. +func (p *Provider) ServeBoot() error { + s := &http.Server{Addr: ":8080", Handler: p.BootHandler(), ReadHeaderTimeout: 5 * time.Second, WriteTimeout: bootWindow, IdleTimeout: 5 * time.Second} + return s.ListenAndServe() +} + +// CheckClosedBoot probes a live boot listener after every admission closed: +// each retained operation's MAC script and capability URLs, an unsupported +// artifact, an unguarded artifact and an unknown identity must be denied. +func (p *Provider) CheckClosedBoot(origin string, extraMACs []string) (string, error) { + origin, err := ParseBootOrigin(origin) + if err != nil { + return "", err + } + j, err := p.read() + if err != nil { + return "", err + } + client := &http.Client{Timeout: 10 * time.Second} + count := 0 + probe := func(u string) error { + resp, err := client.Get(u) + if err != nil { + return fmt.Errorf("boot denial probe unavailable") + } + resp.Body.Close() + if resp.StatusCode != http.StatusForbidden { + return fmt.Errorf("closed or unknown boot access allowed") + } + count++ + return nil + } + for _, r := range j.Operations { + if !r.BootClosed { + return "", fmt.Errorf("boot admission not closed") + } + base := origin + "/" + key(r.Request.ID)[:16] + "/" + r.BootToken + macPath := strings.ReplaceAll(r.Target.MAC, ":", "-") + for _, u := range []string{origin + "/pxe/" + macPath + "/boot.ipxe", base + "/kernel", base + "/installer.gz", base + "/disk.raw", base + "/boot.ipxe"} { + if err := probe(u); err != nil { + return "", err + } + } + } + for _, mac := range extraMACs { + if err := probe(origin + "/pxe/" + strings.ReplaceAll(mac, ":", "-") + "/boot.ipxe"); err != nil { + return "", err + } + } + for _, u := range []string{origin + "/kernel", origin + "/unknown/unknown/kernel", origin + "/pxe/not-a-mac/boot.ipxe"} { + if err := probe(u); err != nil { + return "", err + } + } + if len(j.Operations) == 0 { + return "", fmt.Errorf("no retained admission to probe") + } + return fmt.Sprintf("PASS %d live HTTP denials: closed per-MAC scripts and capabilities of %d operations, other enrolled MACs, unsupported and unguarded artifacts, unknown identity", count, len(j.Operations)), nil +} diff --git a/internal/redfish/client.go b/internal/redfish/client.go new file mode 100644 index 00000000..c9c0d1b4 --- /dev/null +++ b/internal/redfish/client.go @@ -0,0 +1,413 @@ +// Package redfish implements a Redfish provisioning executor for one site. +// +// It drives exact enrolled ComputerSystems through standard Redfish requests: +// service-root discovery, ComputerSystem.Reset and a one-time boot source +// override. It holds no hypervisor credential and never shells out. The local +// acceptance runs it against the DMTF Redfish Interface Emulator with a +// lab-only libvirt adapter (hack/redfish-lab); that adapter is not part of +// this package. See docs/operations/redfish-lab.md for what is verified and +// what remains hardware-unqualified. +// +// Redfish requests, schema decoding and collection paging use gofish. Fleet +// issues every mutation itself as one request: gofish's SetBoot (a second +// PATCH to the Settings resource on failure) and Reset (a resend without +// If-Match on 412) are deliberately not used. +package redfish + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "net/http" + "net/url" + "strconv" + "strings" + "sync" + "time" + + "github.com/stmcginnis/gofish" + "github.com/stmcginnis/gofish/schemas" +) + +const maxBody = 1 << 20 + +var ( + // ErrUnauthorized means the BMC rejected the enrolled credential. + ErrUnauthorized = errors.New("redfish: credential rejected") + // ErrUnsupported means a required action or value is not advertised. + ErrUnsupported = errors.New("redfish: required capability not advertised") + // ErrIdentity means the enrolled System is not exactly present. + ErrIdentity = errors.New("redfish: enrolled system identity not matched exactly") + // ErrPrecondition means the BMC refused a mutation's If-Match. It is not + // retried without the precondition; the caller observes and decides. + ErrPrecondition = errors.New("redfish: System changed since it was observed") +) + +// Client is a minimal Redfish client over gofish. Its transport admits only +// /redfish/v1 paths on the configured endpoint, never follows redirects or an +// environment proxy, and bounds every response body. +type Client struct { + config gofish.ClientConfig + mu sync.Mutex + api *gofish.APIClient +} + +// NewClient accepts only an http(s)://IP:port endpoint without path or query. +// It performs no request until first use. +func NewClient(endpoint, user, password string, timeout time.Duration) (*Client, error) { + u, err := url.Parse(endpoint) + if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.User != nil || (u.Path != "" && u.Path != "/") || u.RawQuery != "" || u.Fragment != "" { + return nil, errors.New("redfish endpoint must be http(s)://IPv4:port") + } + port, err := strconv.Atoi(u.Port()) + if ip := net.ParseIP(u.Hostname()); ip == nil || ip.To4() == nil || err != nil || port < 1 || port > 65535 { + return nil, errors.New("redfish endpoint must be http(s)://IPv4:port") + } + if user == "" || password == "" || strings.ContainsAny(user, ":\r\n") || strings.ContainsAny(password, "\r\n") { + return nil, errors.New("redfish credential must be a nonempty single-line username and password") + } + if timeout <= 0 { + return nil, errors.New("redfish client requires a positive timeout") + } + transport := http.DefaultTransport.(*http.Transport).Clone() + transport.Proxy = nil + return &Client{config: gofish.ClientConfig{ + Endpoint: u.Scheme + "://" + u.Host, Username: user, Password: password, + // Basic authentication: creating a session would itself be a BMC + // mutation with its own lifetime and cleanup. + BasicAuth: true, NoModifyTransport: true, + HTTPClient: &http.Client{Timeout: timeout, Transport: guard{scheme: u.Scheme, host: u.Host, next: transport}, + CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}, + }}, 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) + } + return strings.TrimSuffix(p, "/"), nil +} + +// guard is the only path from gofish to the network. A link the BMC returns +// cannot direct a request to another host or outside /redfish/v1, and a +// mutation cannot carry a query. +type guard struct { + scheme, host string + next http.RoundTripper +} + +func (g guard) RoundTrip(r *http.Request) (*http.Response, error) { + u := r.URL + if _, err := cleanPath(u.Path); err != nil || u.Scheme != g.scheme || u.Host != g.host || u.User != nil || u.Fragment != "" || (u.RawQuery != "" && r.Method != http.MethodGet) { + if r.Body != nil { + r.Body.Close() + } + return nil, fmt.Errorf("%w: unexpected resource path", ErrIdentity) + } + r = r.Clone(r.Context()) + r.Header.Set("OData-Version", "4.0") + resp, err := g.next.RoundTrip(r) + if err != nil { + return nil, err + } + resp.Body = &bounded{ReadCloser: resp.Body, left: maxBody} + return resp, nil +} + +type bounded struct { + io.ReadCloser + left int64 +} + +func (b *bounded) Read(p []byte) (int, error) { + if b.left <= 0 { + return 0, errors.New("redfish: response exceeds size bound") + } + if int64(len(p)) > b.left { + p = p[:b.left] + } + n, err := b.ReadCloser.Read(p) + b.left -= int64(n) + return n, err +} + +// Status is a non-2xx Redfish response other than an authentication failure. +type Status struct{ Code int } + +func (s Status) Error() string { return "redfish: HTTP " + strconv.Itoa(s.Code) } + +// classify reduces a gofish error to Fleet's outcome classes. The result +// never carries a URL, header or response body. +func classify(err error) error { + var coll *schemas.CollectionError + if errors.As(err, &coll) { + var worst error + for _, e := range coll.Failures { + e = classify(e) + if worst == nil || errors.Is(e, ErrIdentity) || (errors.Is(e, ErrUnauthorized) && !errors.Is(worst, ErrIdentity)) { + worst = e + } + } + return worst + } + var rf *schemas.Error + switch { + case err == nil: + return nil + case errors.Is(err, ErrIdentity): + return fmt.Errorf("%w: unexpected resource path", ErrIdentity) + case errors.As(err, &rf) && (rf.HTTPReturnedStatusCode == http.StatusUnauthorized || rf.HTTPReturnedStatusCode == http.StatusForbidden): + return ErrUnauthorized + case errors.As(err, &rf) && rf.HTTPReturnedStatusCode == http.StatusPreconditionFailed: + return ErrPrecondition + case errors.As(err, &rf) && rf.HTTPReturnedStatusCode != 0: + return Status{rf.HTTPReturnedStatusCode} + } + // Transport failure, unreadable or oversized response, or a body gofish + // cannot decode as the expected schema. + return errors.New("redfish: transport failure or unreadable response") +} + +// connect reads the unauthenticated service root once and binds the +// stateless basic-auth client to each call's context. +func (c *Client) connect(ctx context.Context) (*gofish.APIClient, error) { + c.mu.Lock() + defer c.mu.Unlock() + if c.api == nil { + api, err := gofish.ConnectContext(ctx, c.config) + if err != nil { + return nil, classify(err) + } + c.api = api + } + return c.api.WithContext(ctx), nil +} + +func contains[T ~string](list []T, v string) bool { + for _, x := range list { + if string(x) == v { + return true + } + } + return false +} + +// System is the discovered, retained identity and capability of one target. +type System struct { + Path string `json:"path"` + ID string `json:"id"` + UUID string `json:"uuid"` + ResetTarget string `json:"resetTarget"` + ResetTypes []string `json:"resetTypes"` + BootTargets []string `json:"bootTargets"` +} + +// Power is one observation of a System's power and boot override state. +type Power struct { + State string `json:"state"` + OverrideEnabled string `json:"overrideEnabled"` + OverrideTarget string `json:"overrideTarget"` + etag string +} + +// resetAction holds the annotations gofish decodes into unexported fields. +type resetAction struct { + Actions struct { + Reset struct { + Target string `json:"target"` + Info string `json:"@Redfish.ActionInfo"` + Allowed []string `json:"ResetType@Redfish.AllowableValues"` + } `json:"#ComputerSystem.Reset"` + } + Boot struct { + Enabled *[]string `json:"BootSourceOverrideEnabled@Redfish.AllowableValues"` + } +} + +// Discover walks the service root to the enrolled System. Every member of the +// Systems collection, across all pages, must be read: exactly one must carry +// the enrolled UUID, and it must have the enrolled Id; a member with the +// enrolled Id but another UUID is a renumbered or swapped target. The reset +// target and ActionInfo must belong to that System, and On, ForceOff, Pxe and +// Hdd must be advertised. Discovery issues GETs only. +func (c *Client) Discover(ctx context.Context, t Target) (System, error) { + api, err := c.connect(ctx) + if err != nil { + return System{}, err + } + // gofish keeps the Systems link unexported; read the root once more to + // validate it, then walk exactly that collection. + resp, err := api.Get(schemas.DefaultServiceRoot) + var root struct { + Systems struct { + ID string `json:"@odata.id"` + } + } + if err == nil { + err = json.NewDecoder(resp.Body).Decode(&root) + } + schemas.DeferredCleanupHTTPResponse(resp) + if err != nil { + return System{}, classify(err) + } + if root.Systems.ID == "" { + return System{}, fmt.Errorf("%w: service root has no Systems collection", ErrUnsupported) + } + collection, err := cleanPath(root.Systems.ID) + if err != nil { + return System{}, err + } + members, err := schemas.GetCollectionObjects[schemas.ComputerSystem](api, collection) + if err != nil { + // A partially read collection cannot prove the UUID is unique. + return System{}, classify(err) + } + var found []*schemas.ComputerSystem + for _, s := range members { + p, err := cleanPath(s.ODataID) + if err != nil || !strings.HasPrefix(p, collection+"/") { + return System{}, fmt.Errorf("%w: system member outside the collection", ErrIdentity) + } + if strings.EqualFold(s.UUID, t.SystemUUID) { + found = append(found, s) + } else if s.ID == t.SystemID { + return System{}, fmt.Errorf("%w: enrolled Id reports another UUID", ErrIdentity) + } + } + if len(found) != 1 || found[0].ID != t.SystemID { + return System{}, fmt.Errorf("%w: %d members carry the enrolled UUID", ErrIdentity, len(found)) + } + s := found[0] + sys := System{ID: t.SystemID, UUID: t.SystemUUID} + sys.Path, _ = cleanPath(s.ODataID) + var raw resetAction + if err := json.Unmarshal(s.RawData, &raw); err != nil { + return System{}, classify(err) + } + reset := raw.Actions.Reset + target, err := cleanPath(reset.Target) + if err != nil || !strings.HasPrefix(target, sys.Path+"/") { + return System{}, fmt.Errorf("%w: ComputerSystem.Reset target not on the enrolled System", ErrUnsupported) + } + sys.ResetTarget = target + sys.ResetTypes = reset.Allowed + if len(sys.ResetTypes) == 0 && reset.Info != "" { + info, err := cleanPath(reset.Info) + if err != nil || !strings.HasPrefix(info, sys.Path+"/") { + return System{}, fmt.Errorf("%w: ActionInfo not on the enrolled System", ErrUnsupported) + } + // Not schemas.ActionInfo: its typed decode rejects the whole document + // for one off-schema property, as the DMTF emulator's string + // "Required": "true". Only the ResetType values are read. + resp, err := api.Get(info) + var ai struct { + Parameters []struct { + Name, DataType string + AllowableValues []string + } + } + if err == nil { + err = json.NewDecoder(resp.Body).Decode(&ai) + } + schemas.DeferredCleanupHTTPResponse(resp) + if err != nil { + return System{}, classify(err) + } + for _, p := range ai.Parameters { + if p.Name == "ResetType" && (p.DataType == "" || p.DataType == "String") { + sys.ResetTypes = p.AllowableValues + } + } + } + for _, b := range s.Boot.AllowableBootSourceOverrideTargetValues { + sys.BootTargets = append(sys.BootTargets, string(b)) + } + for _, need := range []string{"On", "ForceOff"} { + if !contains(sys.ResetTypes, need) { + return System{}, fmt.Errorf("%w: ResetType %s", ErrUnsupported, need) + } + } + for _, need := range []string{"Pxe", "Hdd"} { + if !contains(sys.BootTargets, need) { + return System{}, fmt.Errorf("%w: boot override target %s", ErrUnsupported, need) + } + } + if raw.Boot.Enabled != nil && !contains(*raw.Boot.Enabled, "Once") { + return System{}, fmt.Errorf("%w: one-time boot override", ErrUnsupported) + } + return sys, nil +} + +func observe(api *gofish.APIClient, sys System) (Power, error) { + s, err := schemas.GetObject[schemas.ComputerSystem](api, sys.Path) + if err != nil { + return Power{}, classify(err) + } + if s.ID != sys.ID || !strings.EqualFold(s.UUID, sys.UUID) { + return Power{}, fmt.Errorf("%w: retained System path changed identity", ErrIdentity) + } + return Power{State: string(s.PowerState), OverrideEnabled: string(s.Boot.BootSourceOverrideEnabled), + OverrideTarget: string(s.Boot.BootSourceOverrideTarget), etag: s.ODataEtag}, nil +} + +// Observe reads the retained System again and re-checks its identity. +func (c *Client) Observe(ctx context.Context, sys System) (Power, error) { + api, err := c.connect(ctx) + if err != nil { + return Power{}, err + } + return observe(api, sys) +} + +// SetBootOnce observes the System, sends exactly one PATCH of the one-time +// boot override (conditional on the observed ETag when the BMC provides one), +// and reads it back. A refused precondition is returned, not retried. +func (c *Client) SetBootOnce(ctx context.Context, sys System, target string) error { + if !contains(sys.BootTargets, target) { + return fmt.Errorf("%w: boot override target %s", ErrUnsupported, target) + } + api, err := c.connect(ctx) + if err != nil { + return err + } + before, err := observe(api, sys) + if err != nil { + return err + } + headers := map[string]string{} + if before.etag != "" { + headers["If-Match"] = before.etag + } + resp, err := api.PatchWithHeaders(sys.Path, map[string]any{"Boot": map[string]string{"BootSourceOverrideTarget": target, "BootSourceOverrideEnabled": "Once"}}, headers) + schemas.DeferredCleanupHTTPResponse(resp) + if err != nil { + return classify(err) + } + p, err := observe(api, sys) + if err != nil { + return err + } + if p.OverrideTarget != target || p.OverrideEnabled != "Once" { + return errors.New("redfish: boot override not observed after PATCH") + } + return nil +} + +// Reset posts exactly one ComputerSystem.Reset to the discovered action +// target. HTTP success, including 202 with a task monitor, is not evidence of +// the effect; callers observe the System. +func (c *Client) Reset(ctx context.Context, sys System, kind string) error { + if !contains(sys.ResetTypes, kind) { + return fmt.Errorf("%w: ResetType %s", ErrUnsupported, kind) + } + api, err := c.connect(ctx) + if err != nil { + return err + } + resp, err := api.PostWithHeaders(sys.ResetTarget, map[string]string{"ResetType": kind}, nil) + schemas.DeferredCleanupHTTPResponse(resp) + return classify(err) +} diff --git a/internal/redfish/client_test.go b/internal/redfish/client_test.go new file mode 100644 index 00000000..cf720a44 --- /dev/null +++ b/internal/redfish/client_test.go @@ -0,0 +1,247 @@ +package redfish + +import ( + "context" + "encoding/base64" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" +) + +// bmcStub serves fixed Redfish documents and records every request. +type bmcStub struct { + mu sync.Mutex + docs map[string]any + headers map[string]http.Header + status map[string]int // "METHOD path" -> status + hold map[string]time.Duration + requests []string + ifMatch []string +} + +func newStub() *bmcStub { + sys := func(id, uuid string) map[string]any { + p := "/redfish/v1/Systems/" + id + return map[string]any{"@odata.id": p, "Id": id, "UUID": uuid, "PowerState": "Off", + "Boot": map[string]any{"BootSourceOverrideEnabled": "Disabled", "BootSourceOverrideTarget": "None", + "BootSourceOverrideTarget@Redfish.AllowableValues": []string{"Pxe", "Hdd"}}, + "@Redfish.Settings": map[string]any{"SettingsObject": map[string]string{"@odata.id": p + "/Settings"}}, + "Actions": map[string]any{"#ComputerSystem.Reset": map[string]any{"target": p + "/Actions/ComputerSystem.Reset", + "ResetType@Redfish.AllowableValues": []string{"On", "ForceOff"}}}} + } + return &bmcStub{docs: map[string]any{ + "/redfish/v1/": map[string]any{"@odata.id": "/redfish/v1", "Systems": map[string]string{"@odata.id": "/redfish/v1/Systems"}}, + "/redfish/v1/Systems": map[string]any{"Members": []any{map[string]string{"@odata.id": "/redfish/v1/Systems/A"}}, "Members@odata.nextLink": "/redfish/v1/Systems?$skip=1"}, + "/redfish/v1/Systems?$skip=1": map[string]any{"Members": []any{map[string]string{"@odata.id": "/redfish/v1/Systems/B"}}}, + "/redfish/v1/Systems/A": sys("A", uuidA), + "/redfish/v1/Systems/B": sys("B", uuidB), + "/redfish/v1/Systems/Settings": map[string]any{}, + }, headers: map[string]http.Header{}, status: map[string]int{}, hold: map[string]time.Duration{}} +} + +func (b *bmcStub) ServeHTTP(w http.ResponseWriter, r *http.Request) { + key := r.URL.Path + if r.URL.RawQuery != "" { + key += "?" + r.URL.RawQuery + } + b.mu.Lock() + b.requests = append(b.requests, r.Method+" "+key) + if r.Method != http.MethodGet { + b.ifMatch = append(b.ifMatch, r.Header.Get("If-Match")) + } + doc, ok := b.docs[key] + code, coded := b.status[r.Method+" "+key] + hold := b.hold[r.Method+" "+key] + for k, v := range b.headers[key] { + w.Header()[k] = v + } + b.mu.Unlock() + time.Sleep(hold) + if user, pass, _ := r.BasicAuth(); key != "/redfish/v1/" && (user != "operator" || pass != "synthetic-secret" || r.Header.Get("OData-Version") != "4.0") { + w.WriteHeader(http.StatusUnauthorized) + return + } + switch { + case coded: + w.WriteHeader(code) + w.Write([]byte(`{"error":{"message":"echo synthetic-secret"}}`)) + case r.Method != http.MethodGet: + w.WriteHeader(http.StatusNoContent) + case !ok: + w.WriteHeader(http.StatusNotFound) + default: + json.NewEncoder(w).Encode(doc) + } +} + +func (b *bmcStub) count(prefix string) int { + b.mu.Lock() + defer b.mu.Unlock() + n := 0 + for _, r := range b.requests { + if strings.HasPrefix(r, prefix) { + n++ + } + } + return n +} + +func stubClient(t *testing.T, b *bmcStub, timeout time.Duration) *Client { + t.Helper() + srv := httptest.NewServer(b) + t.Cleanup(srv.Close) + c, err := NewClient(srv.URL, "operator", "synthetic-secret", timeout) + if err != nil { + t.Fatal(err) + } + return c +} + +func noSecret(t *testing.T, err error) { + t.Helper() + if err != nil && (strings.Contains(err.Error(), "synthetic-secret") || strings.Contains(err.Error(), base64.StdEncoding.EncodeToString([]byte("operator:synthetic-secret"))) || strings.Contains(err.Error(), "127.0.0.1")) { + t.Fatalf("error exposes a credential, body or endpoint: %v", err) + } +} + +func TestDiscoveryWalksEveryPageOfTheSystemsCollection(t *testing.T) { + b := newStub() + c := stubClient(t, b, time.Second) + s, err := c.Discover(context.Background(), Target{SystemID: "B", SystemUUID: strings.ToUpper(uuidB)}) + if err != nil || s.Path != "/redfish/v1/Systems/B" || s.ResetTarget != s.Path+"/Actions/ComputerSystem.Reset" || strings.Join(s.BootTargets, ",") != "Pxe,Hdd" { + t.Fatalf("paged discovery: %+v %v", s, err) + } + // The enrolled UUID also on a later page is ambiguous, never first-match. + b.docs["/redfish/v1/Systems/B"].(map[string]any)["UUID"] = uuidA + if _, err := c.Discover(context.Background(), Target{SystemID: "A", SystemUUID: uuidA}); !errors.Is(err, ErrIdentity) { + t.Fatalf("duplicate UUID on a later page: %v", err) + } + if n := b.count("POST") + b.count("PATCH"); n != 0 { + t.Fatalf("discovery mutated: %d", n) + } +} + +func TestDiscoveryRefusesPartialOrForeignCollections(t *testing.T) { + for name, tc := range map[string]struct { + mutate func(*bmcStub) + want error + }{ + "unreadable member": {func(b *bmcStub) { b.status["GET /redfish/v1/Systems/B"] = http.StatusInternalServerError }, Status{}}, + "rejected member": {func(b *bmcStub) { b.status["GET /redfish/v1/Systems/B"] = http.StatusForbidden }, ErrUnauthorized}, + "member under another collection": {func(b *bmcStub) { + b.docs["/redfish/v1/Systems/B"].(map[string]any)["@odata.id"] = "/redfish/v1/Managers/B" + }, ErrIdentity}, + "absolute Systems link to another host": {func(b *bmcStub) { + b.docs["/redfish/v1/"] = map[string]any{"Systems": map[string]string{"@odata.id": "http://198.51.100.1/redfish/v1/Systems"}} + }, ErrIdentity}, + "reset target off the System": {func(b *bmcStub) { + b.docs["/redfish/v1/Systems/A"].(map[string]any)["Actions"] = map[string]any{"#ComputerSystem.Reset": map[string]any{"target": "/redfish/v1/Systems/B/Actions/ComputerSystem.Reset", "ResetType@Redfish.AllowableValues": []string{"On", "ForceOff"}}} + }, ErrUnsupported}, + "ActionInfo off the System": {func(b *bmcStub) { + b.docs["/redfish/v1/Systems/A"].(map[string]any)["Actions"] = map[string]any{"#ComputerSystem.Reset": map[string]any{"target": "/redfish/v1/Systems/A/Actions/ComputerSystem.Reset", "@Redfish.ActionInfo": "/redfish/v1/Systems/B/ResetActionInfo"}} + }, ErrUnsupported}, + "one-time override not advertised": {func(b *bmcStub) { + b.docs["/redfish/v1/Systems/A"].(map[string]any)["Boot"].(map[string]any)["BootSourceOverrideEnabled@Redfish.AllowableValues"] = []string{"Continuous"} + }, ErrUnsupported}, + "oversized response": {func(b *bmcStub) { + b.docs["/redfish/v1/Systems/B"].(map[string]any)["Pad"] = strings.Repeat("x", maxBody) + }, nil}, + } { + t.Run(name, func(t *testing.T) { + b := newStub() + tc.mutate(b) + _, err := stubClient(t, b, time.Second).Discover(context.Background(), Target{SystemID: "A", SystemUUID: uuidA}) + if err == nil || (tc.want != nil && !errors.Is(err, tc.want) && !errors.As(err, new(Status))) || (tc.want == nil && errors.Is(err, ErrIdentity)) { + t.Fatalf("got %v, want %v", err, tc.want) + } + if _, isStatus := tc.want.(Status); isStatus && !errors.As(err, new(Status)) { + t.Fatalf("got %v, want an HTTP status", err) + } + noSecret(t, err) + if n := b.count("POST") + b.count("PATCH"); n != 0 { + t.Fatalf("discovery mutated: %d", n) + } + }) + } +} + +func TestBootOverrideIsOneConditionalPatchWithoutFallback(t *testing.T) { + b := newStub() + b.headers["/redfish/v1/Systems/A"] = http.Header{"Etag": {`W/"7"`}} + c := stubClient(t, b, time.Second) + sys, err := c.Discover(context.Background(), Target{SystemID: "A", SystemUUID: uuidA}) + if err != nil { + t.Fatal(err) + } + b.status["PATCH /redfish/v1/Systems/A"] = http.StatusPreconditionFailed + err = c.SetBootOnce(context.Background(), sys, "Pxe") + if !errors.Is(err, ErrPrecondition) || b.count("PATCH") != 1 || b.ifMatch[0] != `W/"7"` || b.count("GET /redfish/v1/Systems/A/Settings")+b.count("PATCH /redfish/v1/Systems/A/Settings") != 0 { + t.Fatalf("412 must be one conditional PATCH, no retry or Settings fallback: %v %v %v", err, b.requests, b.ifMatch) + } + noSecret(t, err) + delete(b.status, "PATCH /redfish/v1/Systems/A") + b.status["PATCH /redfish/v1/Systems/A"] = http.StatusInternalServerError + if err := c.SetBootOnce(context.Background(), sys, "Pxe"); !errors.As(err, new(Status)) || b.count("PATCH") != 2 { + t.Fatalf("a failed PATCH must not fall back to the Settings resource: %v %v", err, b.requests) + } + if err := c.SetBootOnce(context.Background(), sys, "Cd"); !errors.Is(err, ErrUnsupported) || b.count("PATCH") != 2 { + t.Fatal("unadvertised boot target was sent") + } +} + +func TestResetIsOnePostOnFailureOrLostResponse(t *testing.T) { + b := newStub() + b.headers["/redfish/v1/Systems/A"] = http.Header{"Etag": {`"7"`}} + c := stubClient(t, b, 200*time.Millisecond) + sys, err := c.Discover(context.Background(), Target{SystemID: "A", SystemUUID: uuidA}) + if err != nil { + t.Fatal(err) + } + reset := "POST /redfish/v1/Systems/A/Actions/ComputerSystem.Reset" + for i, inject := range []func(){ + func() { b.status[reset] = http.StatusPreconditionFailed }, + func() { b.status[reset] = http.StatusServiceUnavailable }, + func() { delete(b.status, reset); b.hold[reset] = time.Second }, + } { + inject() + err := c.Reset(context.Background(), sys, "On") + if err == nil || b.count(reset) != i+1 { + t.Fatalf("case %d: a failed or lost Reset must be sent exactly once and reported: %v %v", i, err, b.requests) + } + noSecret(t, err) + } + for _, m := range b.ifMatch { + if m != "" { + t.Fatalf("Reset carried the System ETag as If-Match: %v", b.ifMatch) + } + } + if err := c.Reset(context.Background(), sys, "GracefulRestart"); !errors.Is(err, ErrUnsupported) || b.count(reset) != 3 { + t.Fatal("unadvertised ResetType was sent") + } + if b.count("POST /redfish/v1/SessionService") != 0 { + t.Fatal("client created a session") + } +} + +func TestClientRejectsUntrustedTLSAndEnvironmentProxy(t *testing.T) { + reached := false + srv := httptest.NewTLSServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { reached = true })) + defer srv.Close() + c, err := NewClient(srv.URL, "operator", "synthetic-secret", time.Second) + if err != nil { + t.Fatal(err) + } + _, err = c.Discover(context.Background(), Target{SystemID: "A", SystemUUID: uuidA}) + if err == nil || reached { + t.Fatalf("untrusted certificate accepted: %v", err) + } + noSecret(t, err) + if c.config.HTTPClient.Transport.(guard).next.(*http.Transport).Proxy != nil { + t.Fatal("BMC requests may be sent through an environment proxy") + } +} diff --git a/internal/redfish/provider.go b/internal/redfish/provider.go new file mode 100644 index 00000000..f6327e67 --- /dev/null +++ b/internal/redfish/provider.go @@ -0,0 +1,814 @@ +package redfish + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "net/url" + "os" + "path/filepath" + "strconv" + "strings" + "time" + + "go.datum.net/fleet/internal/executor" + "go.datum.net/fleet/internal/simulator" + "golang.org/x/sys/unix" +) + +const ( + // Root holds the journal; the site mounts its journal subpath here. + Root = "/var/lib/fleet-local" + artifacts = "/opt/fleet-local/artifacts" + // LibvirtSocketDir is the hypervisor socket path of the libvirt mode. Its + // presence in a Redfish worker is a configuration error, never a fallback. + LibvirtSocketDir = "/run/fleet-libvirt" + bootWindow = 20 * time.Minute + maxPowerOn = 3 +) + +// Target is one enrolled physical asset and its exact Redfish System. Console +// names the serial-console capture file for the target (a lab seam; see the +// operations guide). Enrollment is retained before effects and never inferred. +type Target struct { + AssetID string `json:"assetID"` + SystemID string `json:"systemID"` + SystemUUID string `json:"systemUUID"` + MAC string `json:"mac"` + DiskBytes int64 `json:"diskBytes"` + Console string `json:"console"` +} + +// Enrollment is the site's explicit asset to BMC mapping. +type Enrollment struct { + Endpoint string `json:"endpoint"` + Targets []Target `json:"targets"` +} + +func (e Enrollment) target(asset string) (Target, bool) { + for _, t := range e.Targets { + if t.AssetID == asset { + return t, true + } + } + return Target{}, false +} + +func normalizeMAC(v string) (string, bool) { + hw, err := net.ParseMAC(strings.ReplaceAll(v, "-", ":")) + if err != nil || len(hw) != 6 { + return "", false + } + return hw.String(), true +} + +func ParseEnrollment(b []byte) (Enrollment, error) { + var e Enrollment + d := json.NewDecoder(strings.NewReader(string(b))) + d.DisallowUnknownFields() + if err := d.Decode(&e); err != nil || len(e.Targets) == 0 { + return Enrollment{}, errors.New("invalid Redfish enrollment") + } + seen := map[string]bool{} + for i, t := range e.Targets { + mac, ok := normalizeMAC(t.MAC) + if !ok || t.AssetID == "" || t.SystemID == "" || len(t.SystemUUID) != 36 || t.DiskBytes <= 0 || t.Console == "" || filepath.Base(t.Console) != t.Console || + seen["a"+t.AssetID] || seen["s"+t.SystemID] || seen["u"+strings.ToLower(t.SystemUUID)] || seen["m"+mac] { + return Enrollment{}, errors.New("invalid or duplicate Redfish enrollment target") + } + seen["a"+t.AssetID], seen["s"+t.SystemID], seen["u"+strings.ToLower(t.SystemUUID)], seen["m"+mac] = true, true, true, true + e.Targets[i].MAC = mac + } + return e, nil +} + +// phase is one boot of the target: a one-time boot override, power on, and an +// exact console receipt followed by power off. +type phase struct{ name, boot, marker, mode string } + +var phases = map[string][]phase{ + "install": {{"installer", "Pxe", "FLEET-INSTALLED:", "install"}, {"disk", "Hdd", "FLEET-DISK-BOOT:", ""}}, + "cleanup": {{"wipe", "Pxe", "FLEET-WIPED:", "wipe"}}, +} + +type record struct { + Request simulator.Request `json:"request"` + Result simulator.OperationResult `json:"result"` + Receipt string `json:"receipt"` + Stage string `json:"stage"` + BootToken string `json:"bootToken,omitempty"` + BootExpires time.Time `json:"bootExpires"` + BootClosed bool `json:"bootClosed"` + Target Target `json:"target"` + System *System `json:"system,omitempty"` + PowerOn map[string]int `json:"powerOnRequests,omitempty"` + RequestedAt map[string]time.Time `json:"requestedAt,omitempty"` +} + +type journal struct { + Provider string `json:"provider"` + Image string `json:"image"` + Epoch int64 `json:"epoch"` + Binding string `json:"binding"` + Fence string `json:"fence"` + Closed bool `json:"closed"` + Operations map[string]*record `json:"operations"` +} + +// Provider is the Redfish executor. The effectful provider runs only in a +// per-operation worker; read-only providers serve the boot and observer roles. +type Provider struct { + root, bootRoot, consoleRoot, artifacts string + origin, image string + enrollment Enrollment + client *Client + readOnly bool + now func() time.Time + poll, settle, offGrace, outage time.Duration +} + +func (p *Provider) clock() time.Time { + if p.now != nil { + return p.now().UTC() + } + return time.Now().UTC() +} + +// Open builds the effectful worker provider from its environment. It refuses +// any libvirt configuration: Redfish workers have no hypervisor fallback. +func Open() (*Provider, error) { + if os.Getenv("FLEET_LIBVIRT_URI") != "" { + return nil, errors.New("redfish provider refuses a libvirt URI") + } + if _, err := os.Stat(LibvirtSocketDir); err == nil { + return nil, errors.New("redfish provider refuses a mounted libvirt socket") + } + p, err := open() + if err != nil { + return nil, err + } + enrollment, err := ParseEnrollment([]byte(os.Getenv("FLEET_REDFISH_ENROLLMENT"))) + if err != nil { + return nil, err + } + credentials := os.Getenv("FLEET_REDFISH_CREDENTIALS") + user, err1 := os.ReadFile(filepath.Join(credentials, "username")) + password, err2 := os.ReadFile(filepath.Join(credentials, "password")) + if credentials == "" || err1 != nil || err2 != nil { + return nil, errors.New("redfish credentials are unavailable") + } + client, err := NewClient(enrollment.Endpoint, strings.TrimSpace(string(user)), strings.TrimSpace(string(password)), 20*time.Second) + if err != nil { + return nil, err + } + p.consoleRoot = os.Getenv("FLEET_REDFISH_CONSOLE") + if !filepath.IsAbs(p.consoleRoot) { + return nil, errors.New("FLEET_REDFISH_CONSOLE must be an absolute path") + } + p.client, p.enrollment = client, enrollment + return p, p.retainEnrollment() +} + +// OpenReadOnly serves the boot service and observer. It holds no credential, +// cannot lock the journal and cannot execute. +func OpenReadOnly() (*Provider, error) { + p, err := open() + if err != nil { + return nil, err + } + p.readOnly = true + return p, nil +} + +func open() (*Provider, error) { + if os.Getenv("FLEET_SITE_PROVIDER") != "redfish" { + return nil, errors.New("redfish provider requires FLEET_SITE_PROVIDER=redfish") + } + origin, err := ParseBootOrigin(os.Getenv("FLEET_BOOT_ORIGIN")) + if err != nil { + return nil, err + } + bootRoot := os.Getenv("FLEET_BOOT_EVIDENCE") + if !filepath.IsAbs(bootRoot) || filepath.Clean(bootRoot) != bootRoot { + return nil, errors.New("FLEET_BOOT_EVIDENCE must be a clean absolute path") + } + p := &Provider{root: Root, bootRoot: bootRoot, origin: origin, artifacts: artifacts} + if p.image, err = verifyArtifacts(p.artifacts); err != nil { + return nil, err + } + return p, nil +} + +// ParseBootOrigin accepts only a literal http://IPv4:port origin. +func ParseBootOrigin(value string) (string, error) { + u, err := url.Parse(value) + if err != nil || u.Scheme != "http" || u.User != nil || u.Path != "" || u.RawQuery != "" || u.Fragment != "" { + return "", errors.New("FLEET_BOOT_ORIGIN must be http://IPv4:port") + } + ip := net.ParseIP(u.Hostname()) + port, err := strconv.Atoi(u.Port()) + if ip == nil || ip.To4() == nil || err != nil || port < 1 || port > 65535 { + return "", errors.New("FLEET_BOOT_ORIGIN must be http://IPv4:port") + } + return "http://" + ip.To4().String() + ":" + strconv.Itoa(port), nil +} + +// verifyArtifacts derives the admitted image from the exact two-artifact manifest. +func verifyArtifacts(dir string) (string, error) { + b, err := os.ReadFile(dir + "/SHA256SUMS") + if err != nil { + return "", err + } + lines := strings.Split(strings.TrimSpace(string(b)), "\n") + seen := map[string]bool{} + for _, line := range lines { + f := strings.Fields(line) + if len(lines) != 2 || len(f) != 2 || (f[1] != "kernel" && f[1] != "installer.gz") || seen[f[1]] { + return "", errors.New("invalid artifact manifest") + } + seen[f[1]] = true + if sum, err := fileSHA256(dir + "/" + f[1]); err != nil || sum != f[0] { + return "", errors.New("artifact digest mismatch") + } + } + sum := sha256.Sum256(b) + return "fleet-local-linux@sha256:" + hex.EncodeToString(sum[:]), nil +} + +func fileSHA256(path string) (string, error) { + f, err := os.Open(path) + if err != nil { + return "", err + } + defer f.Close() + h := sha256.New() + if _, err := io.Copy(h, f); err != nil { + return "", err + } + return hex.EncodeToString(h.Sum(nil)), nil +} + +func (p *Provider) lock() (*os.File, error) { + f, err := os.OpenFile(p.root+"/lock", os.O_CREATE|os.O_RDWR, 0600) + if err != nil { + return nil, err + } + if err = unix.Flock(int(f.Fd()), unix.LOCK_EX|unix.LOCK_NB); err != nil { + f.Close() + return nil, err + } + return f, nil +} + +func syncDir(path string) error { + d, err := os.Open(path) + if err != nil { + return err + } + defer d.Close() + return d.Sync() +} + +// retainEnrollment records the enrollment once; a changed enrollment for a +// retained journal is a re-mapping that requires an explicit migration. +func (p *Provider) retainEnrollment() error { + // No journal lock: a worker that only opens must never contend with an + // executing worker or a concurrently delivered one. The first writer + // creates the record atomically (link of a synced file); every other + // worker compares it. + if err := os.MkdirAll(p.root, 0700); err != nil { + return err + } + want, _ := json.Marshal(p.enrollment) + path := p.root + "/enrollment.json" + got, err := os.ReadFile(path) + if os.IsNotExist(err) { + tmp, cerr := os.CreateTemp(p.root, ".enrollment-") + if cerr != nil { + return cerr + } + defer os.Remove(tmp.Name()) + _, werr := tmp.Write(want) + if werr == nil { + werr = tmp.Sync() + } + if cerr := tmp.Close(); werr == nil { + werr = cerr + } + if werr != nil { + return werr + } + if lerr := os.Link(tmp.Name(), path); lerr == nil { + return syncDir(p.root) + } else if !os.IsExist(lerr) { + return lerr + } + got, err = os.ReadFile(path) + } + if err != nil { + return err + } + if string(got) != string(want) { + return errors.New("redfish enrollment differs from the retained enrollment; re-mapping is not authorized") + } + return nil +} + +var stages = func() map[string]bool { + m := map[string]bool{"admitted": true, "discovered": true} + for _, list := range phases { + for _, ph := range list { + for _, s := range []string{"armed", "requested", "started", "verified"} { + m[ph.name+"-"+s] = true + } + } + } + return m +}() + +func (p *Provider) read() (journal, error) { + var j journal + b, err := os.ReadFile(p.root + "/journal.json") + if os.IsNotExist(err) { + return journal{Provider: "redfish", Operations: map[string]*record{}}, nil + } + if err != nil { + return j, err + } + if err = json.Unmarshal(b, &j); err != nil || j.Provider != "redfish" || j.Operations == nil { + return j, errors.New("invalid redfish journal") + } + for id, r := range j.Operations { + if r == nil || len(r.Receipt) != 64 { + return j, errors.New("invalid retained operation") + } + if _, err := hex.DecodeString(r.Receipt); err != nil { + return j, errors.New("invalid receipt") + } + if r.Stage == "done" { + if r.Result.Phase != "Succeeded" || r.Result.CompletedAt == nil || (r.Request.Kind == "install" && r.Result.Result != "installed") || (r.Request.Kind == "cleanup" && r.Result.Result != "clean") { + return j, errors.New("invalid terminal result") + } + } else if !stages[r.Stage] || r.Result.Phase != "Unknown" || r.Result.CompletedAt != nil { + return j, errors.New("invalid pending result") + } + d, err := simulator.RequestDigest(r.Request) + if err != nil || r.Request.ID != id || r.Result.ID != id || r.Result.Kind != r.Request.Kind || d != r.Result.InputDigest || r.Target.AssetID != r.Request.AssetID { + return j, errors.New("invalid retained request") + } + } + return j, nil +} + +func (p *Provider) save(j journal) error { + b, err := json.MarshalIndent(j, "", " ") + if err != nil { + return err + } + f, err := os.OpenFile(p.root+"/journal.tmp", os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0600) + if err != nil { + return err + } + _, err = f.Write(b) + if err == nil { + err = f.Sync() + } + if cerr := f.Close(); err == nil { + err = cerr + } + if err != nil { + return err + } + if err = os.Rename(p.root+"/journal.tmp", p.root+"/journal.json"); err != nil { + return err + } + return syncDir(p.root) +} + +func key(id string) string { s := sha256.Sum256([]byte(id)); return hex.EncodeToString(s[:]) } + +// Lookup reports only terminal retained results; a retained unfinished +// operation is not found with Unknown, which authorizes exact replay. +func (p *Provider) Lookup(ctx context.Context, id string) (simulator.OperationResult, bool, error) { + if !p.readOnly { + f, err := p.lock() + if err != nil { + return simulator.OperationResult{}, false, err + } + defer f.Close() + } + j, err := p.read() + if err != nil { + return simulator.OperationResult{}, false, err + } + r := j.Operations[id] + if r == nil { + return simulator.OperationResult{}, false, nil + } + if r.Stage != "done" { + return simulator.OperationResult{}, false, executor.ErrOutcomeUnknown + } + return r.Result, true, nil +} + +func (p *Provider) validate(q simulator.Request) (Target, error) { + if q.ID == "" || len(q.ID) > 256 || q.BindingID == "" || len(q.BindingID) > 256 || q.FenceToken == "" || len(q.FenceToken) > 1024 || q.Epoch < 1 || len(q.Inputs) > 4096 { + return Target{}, executor.ErrInvalid + } + t, ok := p.enrollment.target(q.AssetID) + if !ok || (q.Kind != "install" && q.Kind != "cleanup") { + return Target{}, executor.ErrInvalid + } + if q.Kind == "install" { + var in struct { + Image string `json:"image"` + } + d := json.NewDecoder(strings.NewReader(string(q.Inputs))) + d.DisallowUnknownFields() + if d.Decode(&in) != nil || d.Decode(&struct{}{}) != io.EOF || in.Image != p.image { + return Target{}, executor.ErrInvalid + } + } + if q.Kind == "cleanup" && len(q.Inputs) != 0 && strings.TrimSpace(string(q.Inputs)) != "{}" { + return Target{}, executor.ErrInvalid + } + return t, nil +} + +// Execute runs or resumes exactly one retained operation. The exact request, +// enrolled target, receipt and boot capability are durable before any +// Redfish request; replay under the same ID never repeats an effect that may +// have happened. HTTP success is never success: only observed power state and +// the exact console receipt complete a phase. +func (p *Provider) Execute(ctx context.Context, q simulator.Request) (simulator.OperationResult, error) { + if p.readOnly || p.client == nil { + return simulator.OperationResult{}, executor.ErrInvalid + } + ctx, cancel := context.WithTimeout(ctx, 40*time.Minute) + defer cancel() + f, err := p.lock() + if err != nil { + return simulator.OperationResult{}, err + } + defer f.Close() + target, err := p.validate(q) + if err != nil { + return simulator.OperationResult{}, err + } + digest, err := simulator.RequestDigest(q) + if err != nil { + return simulator.OperationResult{}, err + } + j, err := p.read() + if err != nil { + return simulator.OperationResult{}, err + } + if j.Image != "" && j.Image != p.image { + return simulator.OperationResult{}, executor.ErrConflict + } + j.Image = p.image + r := j.Operations[q.ID] + if r != nil { + if r.Result.InputDigest != digest || r.Target != target { + return simulator.OperationResult{}, executor.ErrConflict + } + if r.Stage == "done" { + return r.Result, nil + } + } else { + for _, old := range j.Operations { + if old.Stage != "done" { + return simulator.OperationResult{}, executor.ErrOutcomeUnknown + } + } + if q.Epoch < j.Epoch || (q.Epoch == j.Epoch && (j.Closed || q.BindingID != j.Binding || q.FenceToken != j.Fence)) || (q.Epoch > j.Epoch && j.Epoch != 0 && !j.Closed) { + return simulator.OperationResult{}, executor.ErrFenced + } + j.Epoch, j.Binding, j.Fence, j.Closed = q.Epoch, q.BindingID, q.FenceToken, false + receipt, token := make([]byte, 32), make([]byte, 32) + if _, err = rand.Read(receipt); err == nil { + _, err = rand.Read(token) + } + if err != nil { + return simulator.OperationResult{}, err + } + r = &record{Request: q, Receipt: hex.EncodeToString(receipt), Stage: "admitted", Target: target, + BootToken: hex.EncodeToString(token), BootExpires: p.clock().Add(bootWindow), PowerOn: map[string]int{}, RequestedAt: map[string]time.Time{}, + Result: simulator.OperationResult{ID: q.ID, Kind: q.Kind, InputDigest: digest, Phase: "Unknown", CreatedAt: p.clock()}} + j.Operations[q.ID] = r + if err = p.save(j); err != nil { + return simulator.OperationResult{}, err + } + } + if err = p.run(ctx, &j, r); err != nil { + return simulator.OperationResult{}, fmt.Errorf("%w: %v", executor.ErrOutcomeUnknown, err) + } + now := p.clock() + r.Stage, r.Result.Phase, r.Result.CompletedAt, r.Result.Result = "done", "Succeeded", &now, "installed" + if q.Kind == "cleanup" { + r.Result.Result = "clean" + j.Closed = true + } + if err = p.save(j); err != nil { + return simulator.OperationResult{}, fmt.Errorf("%w: %v", executor.ErrOutcomeUnknown, err) + } + return r.Result, nil +} + +func (p *Provider) durations() (poll, settle, offGrace, outage time.Duration) { + poll, settle, offGrace, outage = p.poll, p.settle, p.offGrace, p.outage + if poll == 0 { + poll = 2 * time.Second + } + if settle == 0 { + settle = 45 * time.Second + } + if offGrace == 0 { + offGrace = 30 * time.Second + } + if outage == 0 { + outage = 5 * time.Minute + } + return +} + +func sleep(ctx context.Context, d time.Duration) error { + t := time.NewTimer(d) + defer t.Stop() + select { + case <-ctx.Done(): + return ctx.Err() + case <-t.C: + return nil + } +} + +func (p *Provider) run(ctx context.Context, j *journal, r *record) error { + poll, _, _, _ := p.durations() + if r.Stage == "admitted" { + // GETs only: a rejected credential, a missing capability or a + // mismatched identity leaves the operation admitted with no effect. + sys, err := p.client.Discover(ctx, r.Target) + if err != nil { + return fmt.Errorf("discovery: %w", err) + } + r.System, r.Stage = &sys, "discovered" + if err := p.save(*j); err != nil { + return err + } + } + if r.System == nil { + return errors.New("retained operation lacks its discovered System") + } + before := "discovered" + for _, ph := range phases[r.Request.Kind] { + if r.Stage == before { + // Pre-boot: power off and arm the one-time override. Both are + // idempotent here because no boot of this phase was requested. + if err := p.powerOff(ctx, *r.System); err != nil { + return err + } + if ph.mode != "" && (r.BootClosed || !p.clock().Before(r.BootExpires)) { + return errors.New("boot admission expired or closed before network boot") + } + if err := p.client.SetBootOnce(ctx, *r.System, ph.boot); err != nil { + return fmt.Errorf("arm %s boot: %w", ph.boot, err) + } + r.Stage = ph.name + "-armed" + if err := p.save(*j); err != nil { + return err + } + } + if r.Stage == ph.name+"-armed" { + if err := p.requestPowerOn(ctx, j, r, ph); err != nil { + return err + } + } + for r.Stage == ph.name+"-requested" { + started, err := p.started(ctx, j, r, ph) + if err != nil { + return err + } + if started { + r.Stage = ph.name + "-started" + if err := p.save(*j); err != nil { + return err + } + break + } + if err := sleep(ctx, poll); err != nil { + return err + } + } + if r.Stage == ph.name+"-started" { + if err := p.complete(ctx, r, ph); err != nil { + return err + } + if ph.mode != "" { + r.BootClosed = true + } + r.Stage = ph.name + "-verified" + if err := p.save(*j); err != nil { + return err + } + } + before = ph.name + "-verified" + } + if r.Stage != before { + return errors.New("unexpected operation stage " + r.Stage) + } + return nil +} + +func (p *Provider) powerOff(ctx context.Context, sys System) error { + poll, _, _, _ := p.durations() + deadline := p.clock().Add(5 * time.Minute) + requested := false + for { + pw, err := p.client.Observe(ctx, sys) + if err != nil { + return fmt.Errorf("observe before boot: %w", err) + } + if pw.State == "Off" { + return nil + } + if !requested { + // A slow or lost ForceOff response is observed, not trusted: + // power-off before this phase's boot is idempotent. + if err := p.client.Reset(ctx, sys, "ForceOff"); errors.Is(err, ErrUnauthorized) || errors.Is(err, ErrUnsupported) { + return fmt.Errorf("power off: %w", err) + } + requested = true + } + if p.clock().After(deadline) { + return errors.New("target did not power off") + } + if err := sleep(ctx, poll); err != nil { + return err + } + } +} + +// requestPowerOn retains the request, then posts On. A lost or failed +// response leaves the phase requested; recovery observes before any repeat. +func (p *Provider) requestPowerOn(ctx context.Context, j *journal, r *record, ph phase) error { + if r.PowerOn == nil { + r.PowerOn, r.RequestedAt = map[string]int{}, map[string]time.Time{} + } + if r.PowerOn[ph.name] >= maxPowerOn { + return errors.New("power-on request budget exhausted; outcome requires inspection") + } + r.PowerOn[ph.name]++ + r.RequestedAt[ph.name] = p.clock() + r.Stage = ph.name + "-requested" + if err := p.save(*j); err != nil { + return err + } + if err := p.client.Reset(ctx, *r.System, "On"); err != nil { + return fmt.Errorf("power on (%s) response: %w", ph.name, err) + } + return nil +} + +// started reports whether a requested boot may have begun. Any sign of a boot +// (power not Off, the one-time override consumed, a boot delivery or receipt) +// means it may have run, and it is never requested again. Only a target that +// is still Off, still armed and silent after the settle window gets a repeated +// On, within a small retained budget. +func (p *Provider) started(ctx context.Context, j *journal, r *record, ph phase) (bool, error) { + _, settle, _, _ := p.durations() + pw, err := p.client.Observe(ctx, *r.System) + if err != nil { + if errors.Is(err, ErrIdentity) { + return false, err + } + return false, fmt.Errorf("observe requested boot: %w", err) + } + seen, err := p.receipts(r, ph) + if err != nil { + return false, err + } + delivered := ph.mode != "" && p.deliveryStarted(r) + if pw.State != "Off" || pw.OverrideEnabled != "Once" || pw.OverrideTarget != ph.boot || seen > 0 || delivered { + return true, nil + } + if p.clock().Sub(r.RequestedAt[ph.name]) < settle { + return false, nil + } + return false, p.requestPowerOn(ctx, j, r, ph) +} + +// complete waits for exactly one console receipt for this operation and the +// target powered off. BMC outages are tolerated for a bounded period. +func (p *Provider) complete(ctx context.Context, r *record, ph phase) error { + poll, _, offGrace, outage := p.durations() + var offSince, failingSince time.Time + for { + pw, err := p.client.Observe(ctx, *r.System) + switch { + case errors.Is(err, ErrIdentity): + return err + case err != nil: + if failingSince.IsZero() { + failingSince = p.clock() + } + if p.clock().Sub(failingSince) > outage { + return fmt.Errorf("BMC unavailable while observing %s: %w", ph.name, err) + } + default: + failingSince = time.Time{} + seen, err := p.receipts(r, ph) + if err != nil { + return err + } + if pw.State == "Off" { + if seen == 1 { + if ph.mode != "" { + return p.verifyDelivery(r) + } + return nil + } + if offSince.IsZero() { + offSince = p.clock() + } + if p.clock().Sub(offSince) > offGrace { + return fmt.Errorf("target powered off without the exact %s receipt", ph.name) + } + } else { + offSince = time.Time{} + } + } + if err := sleep(ctx, poll); err != nil { + return err + } + } +} + +// receipts counts exact receipt lines for this operation on the target's +// console. More than one is a duplicate execution and never succeeds. +func (p *Provider) receipts(r *record, ph phase) (int, error) { + b, err := os.ReadFile(filepath.Join(p.consoleRoot, r.Target.Console)) + if os.IsNotExist(err) { + return 0, nil + } + if err != nil { + return 0, err + } + want := ph.marker + r.Receipt + if ph.name == "wipe" { + want += ":" + strconv.FormatInt(r.Target.DiskBytes, 10) + } + n := 0 + for _, line := range strings.Split(string(b), "\n") { + if strings.TrimSpace(line) == want { + n++ + } + } + if ph.name == "disk" { + installed, _ := p.receipts(r, phases["install"][0]) + if installed != 1 { + return 0, errors.New("disk receipt without exactly one installer receipt") + } + } + if n > 1 { + return 0, fmt.Errorf("duplicate %s receipt: the phase ran more than once", ph.name) + } + return n, nil +} + +func (p *Provider) bootDirectory(r *record) string { + return filepath.Join(p.bootRoot, key(r.Request.ID)) +} + +func (p *Provider) deliveries(r *record) map[string]bool { + b, _ := os.ReadFile(filepath.Join(p.bootDirectory(r), "boot-delivery.log")) + done := map[string]bool{} + for _, line := range strings.Split(string(b), "\n") { + f := strings.Fields(line) + if len(f) == 4 && (f[1] == "write-complete" || f[1] == "admitted") && strings.HasPrefix(f[3], "bytes=") { + done[f[1]+" "+f[2]] = true + } + } + return done +} + +func (p *Provider) deliveryStarted(r *record) bool { return p.deliveries(r)["admitted boot.ipxe"] } + +func (p *Provider) verifyDelivery(r *record) error { + d := p.deliveries(r) + for _, name := range []string{"boot.ipxe", "kernel", "installer.gz"} { + if !d["write-complete "+name] { + return fmt.Errorf("missing network delivery: %s", name) + } + } + return nil +} + +// ImageReference is the locally verified artifact manifest identity. +func (p *Provider) ImageReference() string { return p.image } diff --git a/internal/redfish/provider_test.go b/internal/redfish/provider_test.go new file mode 100644 index 00000000..c19dad39 --- /dev/null +++ b/internal/redfish/provider_test.go @@ -0,0 +1,629 @@ +package redfish + +import ( + "context" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "go/parser" + "go/token" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "regexp" + "strings" + "sync" + "testing" + "time" + + "go.datum.net/fleet/internal/executor" + "go.datum.net/fleet/internal/simulator" +) + +const ( + assetA = "fleet-provider/fleet.datumapis.com/Device/synthetic-device-central-01" + assetB = "fleet-provider/fleet.datumapis.com/Device/synthetic-device-central-02" + uuidA = "7f3d0c2e-1a5b-4c6d-8e9f-0a1b2c3d4e0a" + uuidB = "7f3d0c2e-1a5b-4c6d-8e9f-0a1b2c3d4e0b" +) + +// fakeSystem is BMC state plus a fake guest that behaves like the lab +// installer: it fetches its script and artifacts from the boot handler, +// prints exactly one receipt on its console, and powers off. +type fakeSystem struct { + id, uuid, mac, console string + power, enabled, target string + disk string // receipt of the installed OS, "" when blank + boots []string +} + +type fakeBMC struct { + t *testing.T + mu sync.Mutex + systems map[string]*fakeSystem + mutations []string + rejectAuth, hideOn, dropOnce, ignoreOnce bool + dropSkip int + hold time.Duration + boot string // boot handler origin + wg sync.WaitGroup +} + +func (b *fakeBMC) handler() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + write := func(v any) { _ = json.NewEncoder(w).Encode(v) } + if r.URL.Path == "/redfish/v1/" { + write(map[string]any{"Systems": map[string]string{"@odata.id": "/redfish/v1/Systems"}}) + return + } + user, pass, ok := r.BasicAuth() + b.mu.Lock() + reject := b.rejectAuth + b.mu.Unlock() + if !ok || user != "operator" || pass != "synthetic" || reject { + w.WriteHeader(http.StatusUnauthorized) + return + } + if r.URL.Path == "/redfish/v1/Systems" { + write(map[string]any{"Members": []any{map[string]string{"@odata.id": "/redfish/v1/Systems/System-1"}, map[string]string{"@odata.id": "/redfish/v1/Systems/System-2"}}}) + return + } + m := regexp.MustCompile(`^/redfish/v1/Systems/([^/]+)(/Actions/ComputerSystem\.Reset|/ResetActionInfo)?$`).FindStringSubmatch(r.URL.Path) + if m == nil { + w.WriteHeader(http.StatusNotFound) + return + } + b.mu.Lock() + s := b.systems[m[1]] + types := []string{"On", "ForceOff", "ForceRestart"} + if b.hideOn { + types = types[1:] + } + switch { + case r.Method == http.MethodGet && m[2] == "": + v := map[string]any{"@odata.id": r.URL.Path, "Id": s.id, "UUID": s.uuid, "PowerState": s.power, + "Boot": map[string]any{"BootSourceOverrideEnabled": s.enabled, "BootSourceOverrideTarget": s.target, + "BootSourceOverrideTarget@Redfish.AllowableValues": []string{"None", "Pxe", "Hdd"}, "BootSourceOverrideEnabled@Redfish.AllowableValues": []string{"Disabled", "Once"}}, + "Actions": map[string]any{"#ComputerSystem.Reset": map[string]string{"target": r.URL.Path + "/Actions/ComputerSystem.Reset", "@Redfish.ActionInfo": r.URL.Path + "/ResetActionInfo"}}} + b.mu.Unlock() + write(v) + case r.Method == http.MethodGet && m[2] == "/ResetActionInfo": + b.mu.Unlock() + // Shaped like the DMTF emulator 1.2.2 template, including its + // off-schema string "Required". + write(map[string]any{"Parameters": []any{map[string]any{"Name": "ResetType", "Required": "true", "DataType": "String", "AllowableValues": types}}}) + case r.Method == http.MethodPatch && m[2] == "": + var body struct{ Boot map[string]string } + _ = json.NewDecoder(r.Body).Decode(&body) + s.enabled, s.target = body.Boot["BootSourceOverrideEnabled"], body.Boot["BootSourceOverrideTarget"] + b.mutations = append(b.mutations, s.id+" PATCH "+s.target) + b.mu.Unlock() + w.WriteHeader(http.StatusOK) + write(map[string]any{}) + case r.Method == http.MethodPost && m[2] != "": + var body struct{ ResetType string } + _ = json.NewDecoder(r.Body).Decode(&body) + b.mutations = append(b.mutations, s.id+" POST "+body.ResetType) + allowed := false + for _, t := range types { + allowed = allowed || t == body.ResetType + } + if !allowed { + b.mu.Unlock() + w.WriteHeader(http.StatusBadRequest) + return + } + if body.ResetType == "On" && b.ignoreOnce { + b.ignoreOnce = false + b.mu.Unlock() + w.WriteHeader(http.StatusNoContent) + return + } + drop := false + if body.ResetType == "On" && s.power == "Off" { + boot := "Hdd" + if s.enabled == "Once" { + boot = s.target + } + s.enabled, s.target, s.power = "Disabled", "None", "On" + s.boots = append(s.boots, boot) + if b.dropOnce && b.dropSkip > 0 { + b.dropSkip-- + } else { + drop, b.dropOnce = b.dropOnce, false + } + b.wg.Add(1) + go b.guest(s, boot) + } + if body.ResetType == "ForceOff" { + s.power = "Off" + } + b.mu.Unlock() + if drop { + time.Sleep(b.hold) + } + w.WriteHeader(http.StatusNoContent) + default: + b.mu.Unlock() + w.WriteHeader(http.StatusMethodNotAllowed) + } + }) +} + +func (b *fakeBMC) console(s *fakeSystem, line string) { + f, err := os.OpenFile(s.console, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600) + if err == nil { + fmt.Fprintln(f, line) + f.Close() + } +} + +func (b *fakeBMC) guest(s *fakeSystem, boot string) { + defer b.wg.Done() + time.Sleep(20 * time.Millisecond) + line := "" + if boot == "Pxe" { + mac := strings.ReplaceAll(s.mac, ":", "-") + script := get(b.boot + "/pxe/" + mac + "/boot.ipxe") + f := regexp.MustCompile(`kernel (\S+) .*fleet\.receipt=([0-9a-f]{64}) fleet\.mode=(\w+)\ninitrd (\S+)`).FindStringSubmatch(script) + if f != nil && get(f[1]) != "" && get(f[4]) != "" { + b.mu.Lock() + if f[3] == "wipe" { + s.disk = "" + line = "FLEET-WIPED:" + f[2] + ":2147483648" + } else { + s.disk = f[2] + line = "FLEET-INSTALLED:" + f[2] + } + b.mu.Unlock() + } + } else if s.disk != "" { + line = "FLEET-DISK-BOOT:" + s.disk + } + if line != "" { + b.console(s, line) + } + time.Sleep(20 * time.Millisecond) + b.mu.Lock() + s.power = "Off" + b.mu.Unlock() +} + +func get(u string) string { + resp, err := http.Get(u) + if err != nil { + return "" + } + defer resp.Body.Close() + b, _ := io.ReadAll(resp.Body) + if resp.StatusCode != http.StatusOK { + return "" + } + return string(b) +} + +func (b *fakeBMC) mutationsFor(id string) []string { + b.mu.Lock() + defer b.mu.Unlock() + var out []string + for _, m := range b.mutations { + if strings.HasPrefix(m, id+" ") { + out = append(out, strings.TrimPrefix(m, id+" ")) + } + } + return out +} + +type fixture struct { + p *Provider + bmc *fakeBMC + dir string +} + +func newFixture(t *testing.T, timeout time.Duration) *fixture { + t.Helper() + dir := t.TempDir() + for _, d := range []string{"journal", "boot", "console", "artifacts"} { + if err := os.Mkdir(filepath.Join(dir, d), 0700); err != nil { + t.Fatal(err) + } + } + os.WriteFile(filepath.Join(dir, "artifacts/kernel"), []byte("kernel"), 0600) + os.WriteFile(filepath.Join(dir, "artifacts/installer.gz"), []byte("initrd"), 0600) + sums := "" + for _, n := range []string{"kernel", "installer.gz"} { + s, _ := fileSHA256(filepath.Join(dir, "artifacts", n)) + sums += s + " " + n + "\n" + } + os.WriteFile(filepath.Join(dir, "artifacts/SHA256SUMS"), []byte(sums), 0600) + image, err := verifyArtifacts(filepath.Join(dir, "artifacts")) + if err != nil { + t.Fatal(err) + } + bmc := &fakeBMC{t: t, hold: 3 * timeout, systems: map[string]*fakeSystem{ + "System-1": {id: "System-1", uuid: uuidA, mac: "52:54:00:77:01:0a", console: filepath.Join(dir, "console/target-a.log"), power: "On", enabled: "Disabled", target: "None"}, + "System-2": {id: "System-2", uuid: uuidB, mac: "52:54:00:77:01:0b", console: filepath.Join(dir, "console/target-b.log"), power: "Off", enabled: "Disabled", target: "None"}}} + rf := httptest.NewServer(bmc.handler()) + t.Cleanup(rf.Close) + enrollment, err := ParseEnrollment([]byte(fmt.Sprintf(`{"endpoint":%q,"targets":[ + {"assetID":%q,"systemID":"System-1","systemUUID":%q,"mac":"52:54:00:77:01:0a","diskBytes":2147483648,"console":"target-a.log"}, + {"assetID":%q,"systemID":"System-2","systemUUID":%q,"mac":"52:54:00:77:01:0b","diskBytes":2147483648,"console":"target-b.log"}]}`, rf.URL, assetA, uuidA, assetB, uuidB))) + if err != nil { + t.Fatal(err) + } + client, err := NewClient(rf.URL, "operator", "synthetic", timeout) + if err != nil { + t.Fatal(err) + } + p := &Provider{root: filepath.Join(dir, "journal"), bootRoot: filepath.Join(dir, "boot"), consoleRoot: filepath.Join(dir, "console"), artifacts: filepath.Join(dir, "artifacts"), + image: image, enrollment: enrollment, client: client, poll: 5 * time.Millisecond, settle: 150 * time.Millisecond, offGrace: 300 * time.Millisecond, outage: time.Second} + boot := httptest.NewServer(p.BootHandler()) + t.Cleanup(boot.Close) + p.origin, bmc.boot = boot.URL, boot.URL + t.Cleanup(bmc.wg.Wait) + return &fixture{p: p, bmc: bmc, dir: dir} +} + +func (f *fixture) install(epoch int64) simulator.Request { + return simulator.Request{ID: fmt.Sprintf("install-%d", epoch), Kind: "install", AssetID: assetA, BindingID: fmt.Sprintf("binding-%d", epoch), Epoch: epoch, + FenceToken: fmt.Sprintf("fence-%d", epoch), Inputs: json.RawMessage(`{"image":"` + f.p.image + `"}`)} +} + +func cleanup(q simulator.Request) simulator.Request { + q.ID, q.Kind, q.Inputs = strings.Replace(q.ID, "install", "cleanup", 1), "cleanup", nil + return q +} + +func (f *fixture) stage(t *testing.T, id string) string { + j, err := f.p.read() + if err != nil { + t.Fatal(err) + } + return j.Operations[id].Stage +} + +func TestInstallDiskBootCleanupAndReuseThroughRedfish(t *testing.T) { + f := newFixture(t, time.Second) + ctx := context.Background() + q := f.install(1) + r, err := f.p.Execute(ctx, q) + if err != nil || r.Result != "installed" { + t.Fatalf("install: %v %+v", err, r) + } + f.bmc.wg.Wait() + if got := f.bmc.mutationsFor("System-1"); strings.Join(got, ",") != "POST ForceOff,PATCH Pxe,POST On,PATCH Hdd,POST On" { + t.Fatalf("unexpected Redfish effects: %v", got) + } + if got := f.bmc.systems["System-1"].boots; strings.Join(got, ",") != "Pxe,Hdd" { + t.Fatalf("expected one network install and one disk boot, got %v", got) + } + // Exact replay is a verified no-op. + same := func(a, b simulator.OperationResult) bool { + return a.ID == b.ID && a.InputDigest == b.InputDigest && a.Result == b.Result && a.CompletedAt.Equal(*b.CompletedAt) + } + if again, err := f.p.Execute(ctx, q); err != nil || !same(again, r) || len(f.bmc.mutationsFor("System-1")) != 5 { + t.Fatalf("replay repeated effects: %v", err) + } + if got, found, err := f.p.Lookup(ctx, q.ID); !found || err != nil || !same(got, r) { + t.Fatalf("lookup: %v %v", found, err) + } + c := cleanup(q) + if r, err := f.p.Execute(ctx, c); err != nil || r.Result != "clean" { + t.Fatalf("cleanup: %v %+v", err, r) + } + f.bmc.wg.Wait() + if f.bmc.systems["System-1"].disk != "" { + t.Fatal("cleanup did not boot the wipe environment") + } + // Stale authority after the closed epoch is fenced before any request. + stale := q + stale.ID = "install-replay" + if _, err := f.p.Execute(ctx, stale); !errors.Is(err, executor.ErrFenced) { + t.Fatalf("stale epoch replay: %v", err) + } + // Reuse in a new epoch installs again with a distinct receipt. + if r, err := f.p.Execute(ctx, f.install(2)); err != nil || r.Result != "installed" { + t.Fatalf("reuse install: %v", err) + } + f.bmc.wg.Wait() + if got := f.bmc.mutationsFor("System-2"); len(got) != 0 { + t.Fatalf("the other enrolled target received effects: %v", got) + } + if b, _ := os.ReadFile(filepath.Join(f.dir, "console/target-b.log")); len(b) != 0 { + t.Fatal("the other enrolled target booted") + } +} + +func TestDiscoveryFailuresIssueNoEffects(t *testing.T) { + for name, inject := range map[string]func(*fixture){ + "rejected credential": func(f *fixture) { f.bmc.rejectAuth = true }, + "unsupported reset": func(f *fixture) { f.bmc.hideOn = true }, + "renumbered system": func(f *fixture) { f.bmc.systems["System-1"].uuid = "00000000-0000-0000-0000-000000000000" }, + "swapped system UUIDs": func(f *fixture) { f.bmc.systems["System-1"].uuid, f.bmc.systems["System-2"].uuid = uuidB, uuidA }, + } { + t.Run(name, func(t *testing.T) { + f := newFixture(t, time.Second) + inject(f) + q := f.install(1) + if _, err := f.p.Execute(context.Background(), q); !errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatalf("expected Unknown, got %v", err) + } + if got := f.bmc.mutations; len(got) != 0 { + t.Fatalf("effects issued before verified discovery: %v", got) + } + if s := f.stage(t, q.ID); s != "admitted" { + t.Fatalf("stage %s", s) + } + if _, found, err := f.p.Lookup(context.Background(), q.ID); found || !errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatal("unfinished operation must look up as not found and Unknown") + } + }) + } + f := newFixture(t, time.Second) + f.bmc.rejectAuth = true + q := f.install(1) + f.p.Execute(context.Background(), q) + f.bmc.rejectAuth = false + if r, err := f.p.Execute(context.Background(), q); err != nil || r.Result != "installed" { + t.Fatalf("repaired credential did not resume: %v", err) + } +} + +func TestLostResponseAfterEffectRecoversWithoutRepeat(t *testing.T) { + f := newFixture(t, 100*time.Millisecond) + f.bmc.dropOnce = true + q := f.install(1) + if _, err := f.p.Execute(context.Background(), q); !errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatalf("lost response must be Unknown: %v", err) + } + if s := f.stage(t, q.ID); s != "installer-requested" { + t.Fatalf("stage after lost response %s", s) + } + if r, err := f.p.Execute(context.Background(), q); err != nil || r.Result != "installed" { + t.Fatalf("recovery: %v", err) + } + f.bmc.wg.Wait() + if got := f.bmc.systems["System-1"].boots; strings.Join(got, ",") != "Pxe,Hdd" { + t.Fatalf("lost response caused a repeated boot: %v", got) + } + ons := 0 + for _, m := range f.bmc.mutationsFor("System-1") { + if m == "POST On" { + ons++ + } + } + if ons != 2 { + t.Fatalf("expected one On per phase, got %d", ons) + } +} + +func TestLostDiskBootResponseRecoversWithoutRepeat(t *testing.T) { + f := newFixture(t, 100*time.Millisecond) + f.bmc.dropOnce, f.bmc.dropSkip = true, 1 + q := f.install(1) + if _, err := f.p.Execute(context.Background(), q); !errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatalf("lost disk-boot response must be Unknown: %v", err) + } + if s := f.stage(t, q.ID); s != "disk-requested" { + t.Fatalf("stage after lost response %s", s) + } + f.bmc.wg.Wait() + if r, err := f.p.Execute(context.Background(), q); err != nil || r.Result != "installed" { + t.Fatalf("recovery: %v", err) + } + j, _ := f.p.read() + if got := f.bmc.systems["System-1"].boots; strings.Join(got, ",") != "Pxe,Hdd" || j.Operations[q.ID].PowerOn["disk"] != 1 { + t.Fatalf("lost disk-boot response caused a repeat: %v %v", got, j.Operations[q.ID].PowerOn) + } +} + +func TestLostRequestIsRepeatedOnlyWhileArmedAndSilent(t *testing.T) { + f := newFixture(t, time.Second) + f.bmc.ignoreOnce = true + q := f.install(1) + if r, err := f.p.Execute(context.Background(), q); err != nil || r.Result != "installed" { + t.Fatalf("install: %v", err) + } + f.bmc.wg.Wait() + j, _ := f.p.read() + if j.Operations[q.ID].PowerOn["installer"] != 2 || strings.Join(f.bmc.systems["System-1"].boots, ",") != "Pxe,Hdd" { + t.Fatalf("expected one repeated On and one boot: %+v %v", j.Operations[q.ID].PowerOn, f.bmc.systems["System-1"].boots) + } +} + +func TestDuplicateReceiptAndIdentityChangeNeverSucceed(t *testing.T) { + f := newFixture(t, time.Second) + q := f.install(1) + if _, err := f.p.Execute(context.Background(), q); err != nil { + t.Fatal(err) + } + f.bmc.wg.Wait() + b, _ := os.ReadFile(filepath.Join(f.dir, "console/target-a.log")) + f.bmc.console(f.bmc.systems["System-1"], strings.Split(string(b), "\n")[0]) + c := cleanup(q) + j, _ := f.p.read() + r := j.Operations[q.ID] + if _, err := f.p.receipts(r, phases["install"][0]); err == nil { + t.Fatal("duplicate installer receipt accepted") + } + f.bmc.systems["System-1"].uuid = "00000000-0000-0000-0000-000000000000" + if _, err := f.p.Execute(context.Background(), c); !errors.Is(err, executor.ErrOutcomeUnknown) || len(f.bmc.mutationsFor("System-1")) != 5 { + t.Fatalf("identity change: %v %v", err, f.bmc.mutationsFor("System-1")) + } +} + +func TestChangedRetryConflictsAndConcurrentWorkerIsExcluded(t *testing.T) { + f := newFixture(t, time.Second) + f.bmc.rejectAuth = true + q := f.install(1) + f.p.Execute(context.Background(), q) + changed := q + changed.FenceToken = "other" + if _, err := f.p.Execute(context.Background(), changed); !errors.Is(err, executor.ErrConflict) { + t.Fatalf("changed retry: %v", err) + } + other := cleanup(f.install(1)) + other.ID = "unrelated" + if _, err := f.p.Execute(context.Background(), other); !errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatalf("an unfinished operation must block later ones: %v", err) + } + guard, err := f.p.lock() + if err != nil { + t.Fatal(err) + } + if _, err := f.p.Execute(context.Background(), q); err == nil || errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatalf("second worker was not excluded by the journal lock: %v", err) + } + guard.Close() + ro := &Provider{root: f.p.root, readOnly: true} + if _, err := ro.Execute(context.Background(), q); !errors.Is(err, executor.ErrInvalid) { + t.Fatal("read-only provider executed") + } + bad := q + bad.AssetID = "fleet-provider/fleet.datumapis.com/Device/not-enrolled" + if _, err := f.p.Execute(context.Background(), bad); !errors.Is(err, executor.ErrInvalid) { + t.Fatal("unenrolled asset accepted") + } +} + +func TestEnrollmentIsRetainedOnceWithoutContendingForTheJournalLock(t *testing.T) { + f := newFixture(t, time.Second) + guard, err := f.p.lock() // an executing worker holds the journal lock + if err != nil { + t.Fatal(err) + } + defer guard.Close() + var wg sync.WaitGroup + errs := make(chan error, 8) + for i := 0; i < 8; i++ { + wg.Add(1) + go func() { defer wg.Done(); errs <- f.p.retainEnrollment() }() + } + wg.Wait() + close(errs) + for err := range errs { + if err != nil { + t.Fatalf("concurrent open failed: %v", err) + } + } + changed := *f.p + changed.enrollment = Enrollment{Endpoint: f.p.enrollment.Endpoint, Targets: f.p.enrollment.Targets[:1]} + if err := changed.retainEnrollment(); err == nil { + t.Fatal("a changed enrollment was accepted for the retained journal") + } +} + +func TestBootHandlerScopesByMACCapabilityAndAdmission(t *testing.T) { + f := newFixture(t, time.Second) + q := f.install(1) + j := journal{Provider: "redfish", Image: f.p.image, Epoch: 1, Binding: q.BindingID, Fence: q.FenceToken, Operations: map[string]*record{}} + digest, _ := simulator.RequestDigest(q) + target, _ := f.p.enrollment.target(assetA) + r := &record{Request: q, Receipt: strings.Repeat("a", 64), Stage: "installer-requested", BootToken: strings.Repeat("b", 64), BootExpires: time.Now().Add(time.Minute), Target: target, + Result: simulator.OperationResult{ID: q.ID, Kind: "install", InputDigest: digest, Phase: "Unknown", CreatedAt: time.Now()}} + j.Operations[q.ID] = r + save := func() { + if err := f.p.save(j); err != nil { + t.Fatal(err) + } + } + save() + base := f.p.origin + "/" + key(q.ID)[:16] + "/" + if s := get(f.p.origin + "/pxe/52-54-00-77-01-0a/boot.ipxe"); !strings.Contains(s, "fleet.mode=install") || !strings.Contains(s, base+r.BootToken+"/kernel") { + t.Fatalf("admitted MAC not served: %q", s) + } + if get(f.p.origin+"/pxe/boot.ipxe") == "" || get(base+r.BootToken+"/kernel") != "kernel" { + t.Fatal("chain script or admitted artifact not served") + } + for _, u := range []string{f.p.origin + "/pxe/52-54-00-77-01-0b/boot.ipxe", base + strings.Repeat("c", 64) + "/kernel", base + r.BootToken + "/SHA256SUMS", base + r.BootToken + "/boot.ipxe"} { + if get(u) != "" { + t.Fatalf("served %s", u) + } + } + for _, mutate := range []func(){func() { r.BootClosed = true }, func() { r.BootExpires = time.Now().Add(-time.Second) }, func() { r.Stage = "disk-requested" }, func() { j.Fence = "superseded" }} { + saved := *r + fence := j.Fence + mutate() + save() + if get(f.p.origin+"/pxe/52-54-00-77-01-0a/boot.ipxe") != "" || get(base+r.BootToken+"/kernel") != "" { + t.Fatal("closed, expired, non-boot or fenced admission served") + } + *r, j.Fence = saved, fence + } + if b, _ := os.ReadFile(filepath.Join(f.p.bootRoot, key(q.ID), "boot-delivery.log")); strings.Contains(string(b), r.BootToken) || strings.Contains(string(b), r.Receipt) { + t.Fatal("delivery evidence contains a capability or receipt") + } +} + +func TestWorkerRefusesHypervisorConfiguration(t *testing.T) { + t.Setenv("FLEET_LIBVIRT_URI", "qemu:///system?socket=/run/fleet-libvirt/libvirt-sock") + if _, err := Open(); err == nil || !strings.Contains(err.Error(), "libvirt") { + t.Fatalf("Open accepted a libvirt URI: %v", err) + } + t.Setenv("FLEET_LIBVIRT_URI", "") + t.Setenv("FLEET_SITE_PROVIDER", "libvirt") + if _, err := OpenReadOnly(); err == nil { + t.Fatal("redfish provider opened outside Redfish mode") + } +} + +// The executor package must have no direct hypervisor path: no process +// execution, no libvirt client and no dependency on the lab VM provider. +func TestPackageHasNoHypervisorPath(t *testing.T) { + files, _ := filepath.Glob("*.go") + for _, name := range files { + if strings.HasSuffix(name, "_test.go") { + continue + } + src, err := os.ReadFile(name) + if err != nil { + t.Fatal(err) + } + parsed, err := parser.ParseFile(token.NewFileSet(), name, src, parser.ImportsOnly) + if err != nil { + t.Fatal(err) + } + for _, imp := range parsed.Imports { + path := strings.Trim(imp.Path.Value, `"`) + if path == "os/exec" || path == "syscall" || strings.Contains(path, "libvirt") || strings.HasSuffix(path, "/internal/localvm") { + t.Fatalf("%s imports %s", name, path) + } + } + if strings.Contains(string(src), "virsh") || strings.Contains(string(src), "qemu:///") { + t.Fatalf("%s references a hypervisor control path", name) + } + } +} + +func TestClientNeverLeaksCredentialOrFollowsForeignPaths(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/redfish/v1/": + json.NewEncoder(w).Encode(map[string]any{"Systems": map[string]string{"@odata.id": "/redfish/v1/Systems"}}) + case "/redfish/v1/Systems": + json.NewEncoder(w).Encode(map[string]any{"Members": []any{map[string]string{"@odata.id": "/other/../redfish/v1/Systems/x"}}}) + default: + http.Redirect(w, r, "http://198.51.100.1/", http.StatusFound) + } + })) + defer srv.Close() + c, err := NewClient(srv.URL, "operator", "synthetic-secret", time.Second) + if err != nil { + t.Fatal(err) + } + _, err = c.Discover(context.Background(), Target{SystemID: "x", SystemUUID: uuidA}) + if !errors.Is(err, ErrIdentity) || strings.Contains(err.Error(), "synthetic-secret") || strings.Contains(err.Error(), base64.StdEncoding.EncodeToString([]byte("operator:synthetic-secret"))) { + t.Fatalf("foreign member path: %v", err) + } + if _, err := c.Observe(context.Background(), System{Path: "/redfish/v1/Managers", ID: "x", UUID: uuidA}); !errors.As(err, new(Status)) { + t.Fatalf("followed a redirect: %v", err) + } + for _, bad := range []string{"ftp://10.0.0.1:1", "http://bmc.example:80", "http://10.0.0.1:80/path", "http://user@10.0.0.1:80"} { + if _, err := NewClient(bad, "u", "p", time.Second); err == nil { + t.Fatalf("accepted endpoint %s", bad) + } + } +} From 80a42b3cce9e7c21db2f5d006b3bba98dce6de3d Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Thu, 19 Nov 2026 13:12:11 -0600 Subject: [PATCH 011/518] feat(bootnet): DHCP boot reservations with served and withdrawn evidence A network boot needs an address, but DHCP configured outside Fleet answers every reboot and cannot prove provisioning access ended. Fleet now publishes a reservation for a boot NIC only while its network boot is admitted, and treats the DHCP owner's applied reports as evidence: no network boot before a report shows the reservation served, and no completion until every instance that served it reports it withdrawn. - Enrollment records per-target BMC endpoints, endpoint-scoped System identity, and a static or synced DHCP mode with validated provisioning attachments. - The site's dhcp-feed role serves the canonical feed and accepts authenticated, self-verifying applied reports on its own listener. - fleet-dhcp-sync applies the feed to Kea through its control socket and reports only what Kea accepted. - The boot network enhancement proposes the design; the operations guide records the implemented contract and what remains proposed. Co-Authored-By: Claude Opus 5.5 --- README.md | 4 +- build/manager.Dockerfile | 4 +- cmd/fleet-dhcp-sync/main.go | 58 ++++ cmd/fleet-multiplane/main.go | 12 +- config/site/redfish/graph/kustomization.yaml | 8 +- docs/enhancements/boot-network/README.md | 348 +++++++++++++++++++ docs/enhancements/pxe-installation/README.md | 9 + docs/operations/README.md | 1 + docs/operations/boot-network.md | 148 ++++++++ docs/operations/redfish-lab.md | 16 +- docs/operations/site-execution.md | 1 + hack/multiplane/test-redfish.py | 3 +- internal/bootnet/feed.go | 150 ++++++++ internal/bootnet/feed_test.go | 55 +++ internal/dhcpsync/sync.go | 195 +++++++++++ internal/dhcpsync/sync_test.go | 206 +++++++++++ internal/redfish/client.go | 24 +- internal/redfish/dhcp.go | 221 ++++++++++++ internal/redfish/dhcp_test.go | 317 +++++++++++++++++ internal/redfish/provider.go | 128 +++++-- internal/redfish/provider_test.go | 23 +- 21 files changed, 1870 insertions(+), 61 deletions(-) create mode 100644 cmd/fleet-dhcp-sync/main.go create mode 100644 docs/enhancements/boot-network/README.md create mode 100644 docs/operations/boot-network.md create mode 100644 internal/bootnet/feed.go create mode 100644 internal/bootnet/feed_test.go create mode 100644 internal/dhcpsync/sync.go create mode 100644 internal/dhcpsync/sync_test.go create mode 100644 internal/redfish/dhcp.go create mode 100644 internal/redfish/dhcp_test.go diff --git a/README.md b/README.md index bf883dd0..345fddbf 100644 --- a/README.md +++ b/README.md @@ -32,7 +32,9 @@ qualified OS other than Talos, without requiring a managed cluster or an ongoing guest agent. Provisioning engines and provider integrations remain pluggable. The [PXE installation enhancement](docs/enhancements/pxe-installation/README.md) -proposes managed images and bounded delegation to customer PXE. +proposes managed images and bounded delegation to customer PXE. The +[boot network enhancement](docs/enhancements/boot-network/README.md) proposes +DHCP reservations that exist only while a machine's network boot is admitted. ## Learn more diff --git a/build/manager.Dockerfile b/build/manager.Dockerfile index 568e18a9..626e0127 100644 --- a/build/manager.Dockerfile +++ b/build/manager.Dockerfile @@ -6,9 +6,11 @@ RUN go mod download COPY cmd/ ./cmd/ COPY internal/ ./internal/ RUN CGO_ENABLED=0 GOOS=${TARGETOS:-linux} GOARCH=${TARGETARCH} go build -trimpath -ldflags='-s -w' -o /out/fleet-manager ./cmd/fleet-manager \ - && CGO_ENABLED=0 GOOS=${TARGETOS:-linux} GOARCH=${TARGETARCH} go build -trimpath -ldflags='-s -w' -o /out/fleet-simulator ./cmd/fleet-simulator + && CGO_ENABLED=0 GOOS=${TARGETOS:-linux} GOARCH=${TARGETARCH} go build -trimpath -ldflags='-s -w' -o /out/fleet-simulator ./cmd/fleet-simulator \ + && CGO_ENABLED=0 GOOS=${TARGETOS:-linux} GOARCH=${TARGETARCH} go build -trimpath -ldflags='-s -w' -o /out/fleet-dhcp-sync ./cmd/fleet-dhcp-sync FROM gcr.io/distroless/static-debian12:nonroot@sha256:afa5c872c891853ca7fcf1f12c3edb23f7eeef36189728842dd51042ff57f7ab COPY --from=build /out/fleet-manager /fleet-manager COPY --from=build /out/fleet-simulator /fleet-simulator +COPY --from=build /out/fleet-dhcp-sync /fleet-dhcp-sync ENTRYPOINT ["/fleet-manager"] diff --git a/cmd/fleet-dhcp-sync/main.go b/cmd/fleet-dhcp-sync/main.go new file mode 100644 index 00000000..74a7a69a --- /dev/null +++ b/cmd/fleet-dhcp-sync/main.go @@ -0,0 +1,58 @@ +// fleet-dhcp-sync runs beside one Kea DHCPv4 instance. It applies a site's +// boot-reservation feed through Kea's control socket and reports each applied +// revision back to the site, which retains it as boot and revocation evidence. +package main + +import ( + "context" + "errors" + "flag" + "fmt" + "log/slog" + "net/http" + "net/url" + "os" + "os/signal" + "strings" + "syscall" + "time" + + "go.datum.net/fleet/internal/dhcpsync" +) + +func main() { + var feed, tokenPath, instance, socket, base string + var interval time.Duration + flag.StringVar(&feed, "feed", "", "site DHCP feed origin, https://host[:port]") + flag.StringVar(&tokenPath, "token-file", "", "file holding the synchronizer bearer token") + flag.StringVar(&instance, "instance", os.Getenv("POD_NAME"), "stable name of this Kea instance") + flag.StringVar(&socket, "kea-socket", "/run/kea/kea4-ctrl-socket", "Kea DHCPv4 unix control socket") + flag.StringVar(&base, "base-config", "/etc/kea/kea-dhcp4.conf", "Kea configuration without Fleet reservations") + flag.DurationVar(&interval, "interval", 5*time.Second, "feed poll interval") + flag.Parse() + logger := slog.New(slog.NewJSONHandler(os.Stdout, nil)) + if err := run(logger, feed, tokenPath, instance, socket, base, interval); err != nil && !errors.Is(err, context.Canceled) { + logger.Error("dhcp sync stopped", "error", err) + os.Exit(1) + } +} + +func run(logger *slog.Logger, feed, tokenPath, instance, socket, base string, interval time.Duration) error { + u, err := url.Parse(feed) + if err != nil || u.Scheme != "https" || u.Host == "" || (u.Path != "" && u.Path != "/") || u.RawQuery != "" || u.User != nil { + return errors.New("feed must be an https origin") + } + token, err := os.ReadFile(tokenPath) + if err != nil { + return fmt.Errorf("token: %w", err) + } + transport := http.DefaultTransport.(*http.Transport).Clone() + transport.Proxy = nil + s := &dhcpsync.Syncer{ + Feed: u.Scheme + "://" + u.Host, Token: strings.TrimSpace(string(token)), Instance: instance, Socket: socket, Base: base, + HTTP: &http.Client{Timeout: 15 * time.Second, Transport: transport, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}, + } + ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) + defer cancel() + return s.Run(ctx, interval, func(err error) { logger.Warn("sync cycle failed", "error", err) }) +} diff --git a/cmd/fleet-multiplane/main.go b/cmd/fleet-multiplane/main.go index d63f851a..0a547a1b 100644 --- a/cmd/fleet-multiplane/main.go +++ b/cmd/fleet-multiplane/main.go @@ -31,7 +31,7 @@ func main() { } func run() error { if len(os.Args) < 2 { - return fmt.Errorf("usage: fleet-multiplane site-worker|site-observer|image|boot-service|boot-denials|redfish-probe| [flags]") + return fmt.Errorf("usage: fleet-multiplane site-worker|site-observer|image|boot-service|boot-denials|dhcp-feed|redfish-probe| [flags]") } fs := flag.NewFlagSet(os.Args[1], flag.ContinueOnError) once := fs.Bool("once", false, "one reconcile attempt for fault injection") @@ -47,6 +47,7 @@ func run() error { credentials := fs.String("credentials", "", "directory holding username and password files (redfish-probe)") system := fs.String("system", "", "enrolled Redfish System Id (redfish-probe)") uuid := fs.String("uuid", "", "enrolled Redfish System UUID (redfish-probe)") + syncToken := fs.String("sync-token-file", "", "file holding the DHCP synchronizer bearer token (dhcp-feed)") if err := fs.Parse(os.Args[2:]); err != nil { return err } @@ -114,7 +115,7 @@ func run() error { } if redfishMode() { switch os.Args[1] { - case "boot-service", "boot-denials": + case "boot-service", "boot-denials", "dhcp-feed": p, err := redfish.OpenReadOnly() if err != nil { return err @@ -122,6 +123,13 @@ func run() error { if os.Args[1] == "boot-service" { return p.ServeBoot() } + if os.Args[1] == "dhcp-feed" { + token, err := os.ReadFile(*syncToken) + if err != nil { + return fmt.Errorf("DHCP synchronizer token: %w", err) + } + return p.ServeDHCP(strings.TrimSpace(string(token))) + } var extra []string if *extraMAC != "" { extra = append(extra, *extraMAC) diff --git a/config/site/redfish/graph/kustomization.yaml b/config/site/redfish/graph/kustomization.yaml index 437677c4..d171e202 100644 --- a/config/site/redfish/graph/kustomization.yaml +++ b/config/site/redfish/graph/kustomization.yaml @@ -22,10 +22,12 @@ patches: - {name: FLEET_REDFISH_CREDENTIALS, value: /etc/fleet-redfish} - {name: FLEET_REDFISH_CONSOLE, value: /var/lib/fleet-lab-console} # Explicit site enrollment: each physical asset ID maps to exactly one - # Redfish System (Id and UUID), NIC and console capture. Only target A - # is published as capacity; target B is enrolled to prove isolation. + # BMC endpoint, Redfish System (Id and UUID), NIC and console capture. + # The lab's dnsmasq hands out static leases, so DHCP is "static" and + # targets carry no provisioning attachment. Only target A is + # published as capacity; target B is enrolled to prove isolation. - name: FLEET_REDFISH_ENROLLMENT - value: '{"endpoint":"http://10.96.0.81:8000","targets":[{"assetID":"fleet-provider/fleet.datumapis.com/Device/synthetic-device-central-01","systemID":"System-1","systemUUID":"7f3d0c2e-1a5b-4c6d-8e9f-0a1b2c3d4e0a","mac":"52:54:00:77:01:0a","diskBytes":2147483648,"console":"target-a.log"},{"assetID":"fleet-provider/fleet.datumapis.com/Device/synthetic-device-central-02","systemID":"System-2","systemUUID":"7f3d0c2e-1a5b-4c6d-8e9f-0a1b2c3d4e0b","mac":"52:54:00:77:01:0b","diskBytes":2147483648,"console":"target-b.log"}]}' + value: '{"dhcp":"static","targets":[{"assetID":"fleet-provider/fleet.datumapis.com/Device/synthetic-device-central-01","endpoint":"http://10.96.0.81:8000","systemID":"System-1","systemUUID":"7f3d0c2e-1a5b-4c6d-8e9f-0a1b2c3d4e0a","mac":"52:54:00:77:01:0a","diskBytes":2147483648,"console":"target-a.log"},{"assetID":"fleet-provider/fleet.datumapis.com/Device/synthetic-device-central-02","endpoint":"http://10.96.0.81:8000","systemID":"System-2","systemUUID":"7f3d0c2e-1a5b-4c6d-8e9f-0a1b2c3d4e0b","mac":"52:54:00:77:01:0b","diskBytes":2147483648,"console":"target-b.log"}]}' - {name: HOME, value: /tmp} - op: replace path: /spec/resources/9/template/spec/template/spec/containers/0/volumeMounts diff --git a/docs/enhancements/boot-network/README.md b/docs/enhancements/boot-network/README.md new file mode 100644 index 00000000..2df4f364 --- /dev/null +++ b/docs/enhancements/boot-network/README.md @@ -0,0 +1,348 @@ +--- +status: provisional +stage: alpha +--- + +# Boot network reservations + +- [Summary](#summary) +- [Motivation](#motivation) + - [Goals](#goals) + - [Non-goals](#non-goals) +- [Proposal](#proposal) + - [User stories](#user-stories) + - [Physical and consumer addresses](#physical-and-consumer-addresses) + - [Reservation lifecycle](#reservation-lifecycle) +- [Design details](#design-details) + - [Ownership](#ownership) + - [Physical asset records](#physical-asset-records) + - [Reservation feed and applied reports](#reservation-feed-and-applied-reports) + - [Evidence gates](#evidence-gates) + - [DHCP synchronizer](#dhcp-synchronizer) + - [What firmware boots](#what-firmware-boots) + - [Release and recovery](#release-and-recovery) + - [Security boundaries](#security-boundaries) + - [Acceptance tests](#acceptance-tests) +- [Production readiness review questionnaire](#production-readiness-review-questionnaire) +- [Drawbacks](#drawbacks) +- [Alternatives](#alternatives) +- [Open design questions](#open-design-questions) +- [Infrastructure needed](#infrastructure-needed) + +## Summary + +A physical machine that network-boots needs an address before Fleet can serve it +an installer. This proposal makes that address a short-lived, physical-side +reservation. Fleet publishes a reservation for a machine's boot NIC only while +that machine's network boot is admitted. The network owner's DHCP applies it and +reports what it applied. Fleet starts a network boot only after DHCP reports the +reservation served. It completes the operation only after every DHCP instance +that served it reports it withdrawn. + +The [PXE installation enhancement](../pxe-installation/README.md) assumes +"provider DHCP directs eligible firmware to that service" and requires release +to fence provisioning networking. This proposal defines how both happen without +moving DHCP ownership into Fleet. + +## Motivation + +A DHCP server configured independently of Fleet answers a machine on every boot. +It cannot tell an admitted installation from a stray reboot, and Fleet cannot +prove that a machine's provisioning access ended. Running DHCP at every location +also adds a stateful service per site. + +The opposite extreme also fails. If Fleet writes DHCP configuration directly, it +becomes a second writer of another owner's system and needs that owner's +credentials. If DHCP asks Fleet on every request, every boot depends on Fleet's +availability and latency, and a failure looks like a DHCP timeout. + +The provisioning address also differs from the addresses a consumer receives. +Release must withdraw provisioning access without touching anything a tenant +uses. That is impossible when firmware and the running OS share one address. + +### Goals + +- Answer DHCP for a machine's boot NIC only while its network boot is admitted. +- Keep DHCP, IPAM and relay configuration with the network owner, with one + writer for DHCP configuration. +- Treat DHCP state as evidence: a network boot requires proof the reservation is + served, and completion requires proof it was withdrawn. +- Separate physical-side provisioning addresses from consumer Machine addresses. +- Let a location use central DHCP through relays, with no DHCP server at the site. +- Keep a location that configures DHCP independently working, explicitly marked. + +### Non-goals + +- Running a DHCP server as part of Fleet. +- Allocating consumer Machine addresses; Networking/IPAM does that through the + Machine. +- Configuring relays, VLANs or switch ports. +- Authenticating firmware by MAC. A MAC routes a request; it never authorizes one. +- Permanently network-booted workloads. + +## Proposal + +### User stories + +- A provider runs central DHCP for several locations. Site routers relay to it, + and no location runs a DHCP server. +- An operator reboots an installed machine. DHCP does not answer its boot NIC, so + it boots from disk and is never reinstalled by accident. +- A release completes only after the machine's provisioning access is proven + gone, so capacity returns to supply with no lingering boot path. +- A DHCP instance restarts or a report is lost. Fleet treats the boot as not yet + ready, or the withdrawal as unproven, and never as success. + +### Physical and consumer addresses + +| | Address | Belongs to | Lifetime | Owner | +| --- | --- | --- | --- | --- | +| Physical | BMC endpoint | Physical asset | The hardware's life | Networking/IPAM (out-of-band) | +| | Provisioning attachment (address and gateway) | Physical asset, during an admitted network boot | The boot window | Networking/IPAM allocates; Fleet publishes | +| | Underlay (loopback, routing peers) | Physical host on the fabric | The host's life at the location | Galactic and IPAM | +| Consumer | Machine interfaces | Allocation | Allocation to release | Networking/IPAM, through the Machine | + +A location must give the install NIC a provisioning network whose addresses are +never consumer addresses. A location where firmware boots on the same untagged +network and address as the running OS does not qualify for synchronized DHCP. + +### Reservation lifecycle + +```mermaid +sequenceDiagram + participant W as Site worker + participant J as Journal + participant F as Reservation feed + participant S as DHCP synchronizer + participant D as DHCP server + participant M as Machine firmware + participant B as Boot service + W->>J: admit operation, open boot window + S->>F: fetch feed + F->>J: derive reservations + F-->>S: boot NIC → provisioning address + S->>D: apply configuration + S->>F: report applied feed + W->>F: wait for a report that serves the reservation + W->>M: arm one-time network boot, power on + M->>D: DHCP (through the location's relay) + D-->>M: provisioning address + M->>B: fetch boot program and installer + W->>J: verify receipt, close boot admission + S->>F: fetch feed (reservation gone) + S->>D: apply configuration + S->>F: report applied feed + W->>F: wait until every serving instance reports withdrawal + W->>J: complete operation +``` + +## Design details + +### Ownership + +| Surface | Single writer | +| --- | --- | +| Which boot NICs hold a reservation, and when | Fleet, derived from the site journal | +| DHCP server configuration | The network owner's synchronizer | +| Provisioning attachments (address, gateway, prefix) | Networking/IPAM | +| Relays, VLANs, switch ports | The network owner | +| Boot program and installer delivery | Fleet's boot service | + +Fleet never connects to the DHCP server. The synchronizer pulls Fleet's feed and +pushes reports, so Fleet needs no credential for the network owner's systems. + +### Physical asset records + +The site enrollment is the retained, explicit record of each physical asset. Per +target it holds the BMC endpoint, the Redfish System (Id and UUID), the boot NIC +MAC and, for synchronized DHCP, the provisioning attachment. A Redfish System Id +is unique only within its BMC; physical BMCs commonly expose one System named +`Self`. System identity is therefore the endpoint plus Id, and the UUID. + +A location declares one DHCP mode: + +- **static:** DHCP is configured independently of Fleet. Targets carry no + provisioning attachment, and no DHCP evidence is required. +- **synced:** every target carries a provisioning attachment, addresses are + unique, and the evidence gates below apply. + +The enrollment is retained once and a changed enrollment is refused for a +retained journal. In the target design, provisioning attachments are allocated +by Networking/IPAM per physical asset and referenced from inventory, and NIC MACs +and BMC endpoints are recorded as inventory observations. Until then the +enrollment carries them as explicit values. + +### Reservation feed and applied reports + +The site exposes an authenticated feed, separate from the firmware-facing boot +listener. It reads the journal read-only and writes only retained reports. + +- **Feed.** The complete desired set of reservations: boot NIC MAC, provisioning + address in prefix form, gateway and expiry. A reservation exists while its + operation holds the journal's current epoch, binding and fence, is not done, + has not closed boot admission and is inside its boot window. That starts at + admission, before power-on, so DHCP is ready when firmware asks. Reservations + are sorted canonically and the revision is a digest of them, so any copy of a + feed is self-verifying. +- **Applied report.** A named DHCP instance reports the exact feed it now + serves. The site accepts only a canonical feed with a matching revision and + retains the report durably before acknowledging it. + +### Evidence gates + +1. **Before arming a network boot**, the worker waits, with no effect, for a + report accepted after admission that serves the boot NIC at its exact + provisioning address. A report from an earlier operation is not evidence. If + the boot window expires first, the operation stays Unknown and effect-free. +2. **Before reporting success**, the worker requires that every instance which + served the reservation during the operation has since reported a feed + without it. A silent instance may still be serving, so the outcome stays + Unknown and replay waits again. + +Report and admission times come from different roles, so they must run on +synchronized clocks. + +### DHCP synchronizer + +The synchronizer runs beside one DHCP server instance and is owned and deployed +by the network owner. Each cycle it verifies the fetched feed, adds each +reservation to the base subnet with exactly its prefix, applies the configuration +when the revision changed or the server restarted, and reports only after the +server accepted it. A reservation with no matching base subnet fails the cycle; +it is never dropped. A restarted server loses its reservations, which fails +closed. + +Instance names must survive restarts, for example StatefulSet pod names. A +restarted instance then reports under the same name, which is its withdrawal +evidence. Before scaling down, drain an instance until it reports an empty feed; +a removed instance that served a reservation never reports again and keeps that +operation Unknown. + +The first synchronizer targets Kea DHCPv4 through its control socket. + +### What firmware boots + +A reservation supplies an address and gateway only. Firmware must also learn +what to boot. The proposed path for UEFI hardware is UEFI HTTP Boot: before +arming the one-time boot, the worker sets the System's `HttpBootUri` through +Redfish to the boot service, scoped to the operation, and arms `UefiHttp`. DHCP +then carries no boot URL. Firmware that cannot accept a Redfish boot URI needs +a DHCP boot-file option, which would extend the reservation; that is deferred. + +Boot URLs and capabilities are never DHCP options in the proposed path. + +### Release and recovery + +Release "fences provisioning networking" by requiring withdrawal evidence for +the cleanup operation, exactly as for installation. Missing, corrupt or +conflicting evidence keeps the operation Unknown and the capacity occupied. An +unreadable retained report is corruption, never evidence in either direction. +Recovery replays the same operation, which resumes at its retained stage and +waits for evidence again; it never repeats an effect that may have happened. + +### Security boundaries + +- The feed and reports require a bearer credential of at least 32 characters + and must be reached over TLS. The feed is never served on the boot listener. +- A report can only claim a canonical, self-consistent feed. The synchronizer is + trusted to report what its server serves; a compromised synchronizer can + falsify withdrawal, so its credential is scoped to one location's feed. +- DHCP is unauthenticated and unencrypted. The central server accepts relayed + traffic only from the location's relay addresses and answers only reserved + MACs, with no pool. Nothing secret is placed in DHCP. +- A MAC is routing information. Boot artifacts remain protected by the boot + service's operation-scoped admission. +- Retained reports hold MACs, addresses, revisions and instance names, never a + credential, receipt or capability. + +### Acceptance tests + +- No reservation is published without an admitted boot, and none outlives it. +- A network boot is never armed before a served report for the same operation. +- A report from before admission does not satisfy the served gate. +- Completion waits while any serving instance has not reported withdrawal, and + proceeds once all have. +- Unauthenticated, non-canonical, mismatched or unknown-field reports are + rejected and not retained. +- A synchronizer reports nothing the server rejected and never drops a + reservation with no matching subnet; a server restart re-applies without a + new report. +- Two BMCs exposing the same System Id enroll as distinct targets; a shared + provisioning address is refused. +- End to end at a location: a relayed DHCP exchange, a UEFI HTTP Boot, release + with withdrawal, and a reboot of an installed machine that DHCP ignores. + +## Production readiness review questionnaire + +### How is the feature enabled or disabled? + +Per location, through the enrollment's DHCP mode. Moving a location from static +to synced changes the retained enrollment and requires an explicit migration +with no operation in flight. Rollback to static stops new reservations; retained +operations still require their withdrawal evidence. + +### What must operators monitor? + +Feed and report latency per instance, operations waiting on the served or +withdrawn gate, instances that served and went silent, rejected reports, +synchronizer cycle failures, and DHCP servers receiving traffic from unexpected +relays. + +### How are failures recovered? + +Restore the synchronizer or server and let it report; the waiting operation +resumes. An instance that is permanently gone after serving requires an operator +decision with evidence that it no longer serves; there is no automatic override. + +### What must upgrades preserve? + +The retained enrollment, journal and report log, feed canonicalization and +revision derivation, and stable instance names. + +## Drawbacks + +- Every network boot depends on the network owner's DHCP and synchronizer being + reachable and reporting, which adds latency and a failure mode to installation. +- Withdrawal evidence can strand an operation as Unknown when an instance + disappears, by design, and operators must resolve it. +- The location must expose an authenticated feed endpoint to the DHCP owner. + +## Alternatives + +- **Static reservations configured outside Fleet.** Kept as the static mode, + but it answers every reboot and cannot prove revocation. +- **Fleet writes DHCP configuration.** Rejected: a second writer of the network + owner's system, with its credentials held by Fleet. +- **DHCP queries Fleet per request.** Rejected: couples every boot to Fleet's + availability and latency. +- **Fleet pushes reservations to DHCP.** Rejected: the location would need to + reach into the network owner's environment; with a pull, the DHCP side starts + every connection. +- **Route reservations and reports through the management plane.** Avoids a + location endpoint and reuses existing coordination, but every gate becomes a + management round trip and management holds evidence only the site uses. + Remains an option if exposing the site feed is impractical. +- **A DHCP server at every location.** Possible behind the same feed, but it adds + a stateful service per site; central DHCP through relays is preferred. + +## Open design questions + +- Provisioning attachments from Networking/IPAM: the claim type, per-asset + lifetime and how inventory references it. +- NIC MACs and BMC endpoints as inventory observations instead of enrollment + values. +- Redfish `HttpBootUri` support across qualified BMCs, and the fallback for + firmware without it. +- Feed transport: a TLS endpoint at the location versus the management-plane + route. +- Resolving a permanently lost instance with evidence instead of an operator + decision alone. +- DHCPv6 reservations and an IPv6 provisioning network. +- Per-location synchronizer credentials, rotation and revocation. + +## Infrastructure needed + +A location with a provisioning network on the install NIC and a relay to the +central DHCP service, the network owner's DHCP service with one synchronizer per +instance and stable instance names, a TLS endpoint for the location's feed, and +disposable UEFI hardware whose BMC accepts a one-time UEFI HTTP Boot target. diff --git a/docs/enhancements/pxe-installation/README.md b/docs/enhancements/pxe-installation/README.md index 97a26a28..b3e1b46d 100644 --- a/docs/enhancements/pxe-installation/README.md +++ b/docs/enhancements/pxe-installation/README.md @@ -351,6 +351,15 @@ eligible firmware to that service. With no active admitted boot session, the service returns local boot. With a valid session, it serves the Fleet installer or chains through an allocation-scoped proxy to the admitted customer endpoint. +Provisioning addresses are physical-side attachments, distinct from consumer +Machine addresses. Where the location's DHCP is synchronized, the boot service +publishes a reservation for the asset's boot NIC only while its boot is admitted. +The network owner's DHCP reports what it applied. A network boot requires a +report that the reservation is served, and completion requires reports that +every instance which served it has withdrawn it. The +[boot network enhancement](../boot-network/README.md) proposes this design; the +implemented contract is in [Boot network](../../operations/boot-network.md). + The proxy validates the endpoint and TLS policy, prevents unapproved redirects, keeps endpoint credentials away from the machine, and records the response digest. Customer artifacts referenced by the returned script must use approved HTTPS diff --git a/docs/operations/README.md b/docs/operations/README.md index a78d36b0..9426bad4 100644 --- a/docs/operations/README.md +++ b/docs/operations/README.md @@ -16,6 +16,7 @@ integrations. Real provider support and live Milo acceptance tests are incomplet | Install a real OS over firmware PXE into a disposable local VM | [Local VM PXE installation](local-vm.md) | Single-plane real install, disk-only boot, recovery, cleanup and reuse under explicit TCG; 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, 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, cleanup and reuse; 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 executor discovery, one-time PXE/disk boot overrides, power, lost-response recovery and a booted wipe cleanup, against the unmodified DMTF Redfish Interface Emulator with a lab-only libvirt adapter and two persistent lab VMs; synthetic credentials and networking; not physical BMC or hardware qualification | +| Publish physical-side DHCP reservations for network boot | [Boot network](boot-network.md) | Per-asset BMC endpoints and provisioning attachments, a reservation feed 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 | | Render deployment bundles and supply environment inputs | [Deployment manifests](../../config/README.md) | Packaging and security boundaries, not runtime readiness | | Run the manager across consuming projects | [Project discovery](../../config/README.md#project-discovery) | Discovery, per-project isolation, departure, role bindings, and readiness | | Exercise Milo-routed synthetic staging | [Synthetic staging configuration](../../config/README.md#environment-owned-inputs) | Restricted synthetic publication and lifecycle behavior, not production authority | diff --git a/docs/operations/boot-network.md b/docs/operations/boot-network.md new file mode 100644 index 00000000..e5f7fd4b --- /dev/null +++ b/docs/operations/boot-network.md @@ -0,0 +1,148 @@ +# Boot network: physical addresses and DHCP reservations + +A physical host has addresses that belong to the asset, separate from the +addresses a consumer's Machine receives. Fleet records the physical ones in the +site enrollment and, for network boot, publishes a DHCP reservation only while an +operation's boot is admitted. The network owner's DHCP applies it and reports +back; those reports are the evidence that the boot was reachable and that +provisioning networking was later revoked. + +This page describes the implemented contract. The design and its alternatives +are in the [boot network enhancement](../enhancements/boot-network/README.md). +What is still proposed is listed under +[Implemented versus proposed](#implemented-versus-proposed). + +## Two kinds of address + +| | Address | Belongs to | Lifetime | Owner | +| --- | --- | --- | --- | --- | +| Physical | BMC endpoint | Physical asset | The hardware's life | Networking/IPAM (out-of-band) | +| | Provisioning attachment (address and gateway) | Physical asset, during an admitted network boot | The boot window | Networking/IPAM allocates; Fleet publishes | +| | Underlay (loopback, routing peers) | Physical host on the fabric | The host's life on the site | Galactic and IPAM | +| Consumer | Machine interfaces (`Machine.spec.networkInterfaces`) | Allocation | Allocation to release | Networking/IPAM, through the Machine | + +A provisioning address must not be a consumer address. Release fences +provisioning networking, so Fleet must be able to withdraw the provisioning +address without touching anything a tenant uses. A site whose firmware boots on +the same untagged network and address as the running OS cannot meet that, and +needs a dedicated provisioning network on the install NIC. + +## Enrollment + +The site enrollment (`FLEET_REDFISH_ENROLLMENT`) is the explicit, retained +mapping of physical assets. It sets a site DHCP mode and, per target, the BMC +endpoint, the Redfish System, the boot NIC and, in synchronized mode, the +provisioning attachment: + +```json +{ + "dhcp": "synced", + "targets": [{ + "assetID": "fleet-provider/fleet.datumapis.com/Device/example-01", + "endpoint": "https://192.0.2.20:443", + "systemID": "Self", + "systemUUID": "00000000-0000-4000-8000-000000000001", + "mac": "00:00:5e:00:53:01", + "provisioning": {"address": "198.51.100.10/24", "gateway": "198.51.100.1"}, + "diskBytes": 960197124096, + "console": "example-01.log" + }] +} +``` + +- **`endpoint`** is per target. Physical BMCs each expose one System, often with + the same Id (`Self`), so a System is identified by its endpoint plus Id, and by + its UUID. +- **`dhcp: static`** means the site's DHCP is configured independently of Fleet. + Targets must not carry a provisioning attachment. The Redfish lab uses this + mode: its dnsmasq hands out fixed leases. +- **`dhcp: synced`** requires a provisioning attachment on every target: a host + address in prefix form and a different host in the same prefix as gateway. + Provisioning addresses are unique within the enrollment. + +The executor retains the enrollment once and refuses a changed enrollment for +the retained journal. + +## Reservation lifecycle + +In synchronized mode the site serves a reservation feed derived only from the +journal. A target's boot NIC holds its provisioning address while its operation: + +- is the journal's current epoch, binding and fence, and is not done; +- has a boot capability whose window has not expired; and +- has not closed boot admission. + +That window opens at admission, before power-on, so DHCP is ready when firmware +asks. The boot handler's narrower rule still decides which scripts and artifacts +are served. + +The worker gates its effects on reports: + +1. **Before arming a network boot** it waits, with no effect, until some DHCP + instance reports a feed that serves the boot NIC at its exact provisioning + address, accepted after this operation was admitted. A report from an earlier + operation is not evidence. If the boot window expires first, the operation + stays Unknown and effect-free. +2. **Before reporting success** it waits until every DHCP instance that served + the reservation during this operation reports a later feed without it. A + silent instance may still be serving, so the outcome stays Unknown and replay + waits again. Completion therefore includes verified withdrawal. + +Report times are the boot service's clock and admission times the worker's, so +both roles must run on synchronized clocks. + +A reservation carries an address and gateway only. It does not tell firmware +what to boot; see the boot-program row below. + +## Feed and reports + +The site's `dhcp-feed` role (`fleet-multiplane dhcp-feed -sync-token-file …`) +listens on `:8081`, never on the firmware-facing boot listener. It reads the +journal read-only and writes only `dhcp-applied.log` in the boot-evidence +directory. Every request needs `Authorization: Bearer `; the token is at +least 32 characters. + +- `GET /dhcp/v1/reservations` returns the canonical feed: + `{"revision": "", "reservations": [{"mac", "address", "gateway", "expires"}]}`. + Reservations are sorted by MAC; the revision is the SHA-256 of their canonical + JSON, so a feed is self-verifying. +- `POST /dhcp/v1/applied` takes `{"instance": "", "feed": }`. The + feed must be canonical with a matching revision; anything else is rejected and + not retained. An accepted report is synced to disk before `204`. + +The retained log holds MACs, addresses, revisions and instance names. It holds +no token, receipt or boot capability. An unreadable line is treated as +corruption, never as evidence. + +## Kea synchronizer + +`fleet-dhcp-sync` (in the manager image) runs beside one Kea DHCPv4 instance, +with a stable instance name such as a StatefulSet pod name. Each cycle it: + +1. fetches and verifies the feed over HTTPS; +2. reads Kea's PID with `status-get`; +3. when the revision changed or Kea restarted, adds each reservation to the base + configuration's subnet with exactly its prefix, sets the gateway as the + host's `routers` option, and sends `config-set` over Kea's control socket; +4. reports the feed only after Kea accepted it, once per revision. + +A reservation with no matching base subnet fails the cycle; it is never +dropped. A restarted Kea loses its reservations and fails closed until the next +cycle re-applies them. An instance that disappears after serving never reports +withdrawal, which keeps that operation Unknown until an operator resolves it, +so instance names must survive restarts. Before scaling down, drain the +instance being removed until it reports an empty feed. + +## Implemented versus proposed + +| Behavior | Status | +| --- | --- | +| Per-target BMC endpoints, endpoint-scoped System identity, static and synced DHCP modes, validated provisioning attachments | Implemented; unit tested | +| Reservation feed, authenticated applied reports, served and withdrawn gates, multi-instance withdrawal | Implemented; unit tested with a fake BMC and synchronizer, including a silent instance | +| Kea synchronizer: exact-subnet placement, restart re-apply, report only after Kea accepted | Implemented; unit tested against a fake Kea control socket | +| Provisioning attachments allocated by Networking/IPAM instead of enrollment values | Proposed | +| NIC MACs and BMC endpoints recorded as Fleet inventory observations | Proposed; the enrollment is the only record | +| Deployment of `dhcp-feed` and the synchronizer, TLS to the feed, relay and provisioning VLAN at a site | Proposed; not exercised end to end | +| Telling firmware what to boot in synced mode (Redfish `HttpBootUri` for UEFI HTTP Boot, or a DHCP boot-file option) | Proposed; the executor still arms `Pxe`, which relies on site DHCP for the boot file | +| DHCPv6 reservations | Proposed; the feed accepts IPv6, the Kea DHCPv4 synchronizer rejects it | +| Lab acceptance in synced mode | Not run; the lab uses static DHCP | diff --git a/docs/operations/redfish-lab.md b/docs/operations/redfish-lab.md index 08446eb4..2fff15d7 100644 --- a/docs/operations/redfish-lab.md +++ b/docs/operations/redfish-lab.md @@ -120,9 +120,12 @@ ownership audit covers the BMC Deployment, Service and ServiceAccount. The disks, domain UUIDs and MACs exist before any allocation. Each installation or cleanup reuses target A's single persistent disk. The site enrollment is an -explicit asset-to-System mapping in the worker template, with the endpoint, -System Id, UUID, MAC, disk size and console capture name. The executor writes it -once into the journal directory and refuses a changed enrollment later. +explicit asset-to-System mapping in the worker template, with each target's BMC +endpoint, System Id, UUID, MAC, disk size and console capture name. The lab sets +`"dhcp": "static"` because its dnsmasq leases are fixed; see +[Boot network](boot-network.md) for synchronized DHCP. The executor writes the +enrollment once into the journal directory and refuses a changed enrollment +later. ## Redfish executor contract @@ -600,8 +603,11 @@ MVP. They are listed as an explicit qualification checklist: 4. **Credentials and transport.** TLS with pinned CA or certificate, per-BMC accounts, a credential broker so workers never hold a long-lived password, and rotation and revocation. -5. **Provisioning network.** Integrate with the networking/IPAM owner: per-host - DHCP or a dedicated provisioning VLAN, and authentication beyond MAC. +5. **Provisioning network.** Synchronized DHCP reservations with served and + withdrawn evidence are implemented and unit tested + ([Boot network](boot-network.md)) but not exercised at a site. Still open: + attachments allocated by Networking/IPAM, a dedicated provisioning VLAN, + and authentication beyond MAC. 6. **Cleanup assurance.** Use vendor or NIST SP 800-88 sanitization (secure erase, crypto-erase, sanitize commands) with verifiable device evidence. Distinguish it from this logical overwrite. diff --git a/docs/operations/site-execution.md b/docs/operations/site-execution.md index 440a417d..fec814ef 100644 --- a/docs/operations/site-execution.md +++ b/docs/operations/site-execution.md @@ -360,6 +360,7 @@ container and is unchanged. | Facility-edge DaemonSet, multi-node volumes, HA runtime, live hardware fencing | Proposed only | | Removing the fence token from cell-readable handoff fields (credential broker) | Proposed only ([open questions](../enhancements/pxe-installation/README.md#open-design-questions)) | | Redfish execution Jobs 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) for its run record | +| Synchronized DHCP boot reservations with served and withdrawn evidence | 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)) | ## Independent review of the recorded run diff --git a/hack/multiplane/test-redfish.py b/hack/multiplane/test-redfish.py index 317dcf0d..d8bd1f38 100644 --- a/hack/multiplane/test-redfish.py +++ b/hack/multiplane/test-redfish.py @@ -67,7 +67,8 @@ def build(path): enrollment = json.loads(env.get('FLEET_REDFISH_ENROLLMENT', '{}')) targets = json.loads((root / 'hack/redfish-lab/targets.json').read_text()) by_system = {t['system']: t for t in targets} -check('enrollment endpoint is the fixed BMC Service', enrollment.get('endpoint') == 'http://%s:8000' % flux.BMC_SERVICE_IP) +check('every enrolled BMC endpoint is the fixed BMC Service', enrollment.get('targets') and all(t.get('endpoint') == 'http://%s:8000' % flux.BMC_SERVICE_IP for t in enrollment['targets'])) +check('lab DHCP is static: no provisioning attachment published', enrollment.get('dhcp') == 'static' and not any('provisioning' in t for t in enrollment.get('targets', []))) check('enrollment matches the lab targets exactly', len(enrollment.get('targets', [])) == 2 and all( t['systemID'] in by_system and by_system[t['systemID']]['uuid'] == t['systemUUID'] and by_system[t['systemID']]['mac'] == t['mac'] and by_system[t['systemID']]['console'].endswith('/' + t['console']) for t in enrollment.get('targets', [])), json.dumps(enrollment)[:300]) diff --git a/internal/bootnet/feed.go b/internal/bootnet/feed.go new file mode 100644 index 00000000..02b4e285 --- /dev/null +++ b/internal/bootnet/feed.go @@ -0,0 +1,150 @@ +// Package bootnet is the boot-reservation contract between a site's boot +// service and the DHCP owner's synchronizer. A reservation maps one enrolled +// boot NIC to the provisioning address the network owner assigned to that +// physical asset, and exists only while an operation's network boot is +// admitted. The synchronizer reports what each DHCP instance applied; those +// reports are the evidence that a reservation was served and later withdrawn. +package bootnet + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "net" + "net/netip" + "regexp" + "sort" + "time" +) + +// Reservation is one boot NIC's provisioning address. Address is in prefix +// form (address/prefix length) so the DHCP side never infers the subnet. +type Reservation struct { + MAC string `json:"mac"` + Address string `json:"address"` + Gateway string `json:"gateway"` + Expires time.Time `json:"expires"` +} + +// Feed is the complete desired reservation set. Revision is derived from the +// reservations, so a report of an applied Feed is self-verifying. +type Feed struct { + Revision string `json:"revision"` + Reservations []Reservation `json:"reservations"` +} + +// Applied reports that one DHCP instance now serves exactly Feed. +type Applied struct { + Instance string `json:"instance"` + Feed Feed `json:"feed"` +} + +var instanceName = regexp.MustCompile(`^[a-z0-9]([a-z0-9.-]{0,61}[a-z0-9])?$`) + +// NormalizeMAC returns the canonical lower-case colon form of a 48-bit MAC. +func NormalizeMAC(v string) (string, bool) { + hw, err := net.ParseMAC(v) + if err != nil || len(hw) != 6 { + return "", false + } + return hw.String(), true +} + +// ValidAttachment checks a provisioning address and its gateway: the address +// is a host in its prefix and the gateway is a different host in the same one. +func ValidAttachment(address, gateway string) error { + p, err := netip.ParsePrefix(address) + if err != nil || p.Addr().Zone() != "" || p.Addr() == p.Masked().Addr() || p.Bits() == p.Addr().BitLen() { + return errors.New("provisioning address must be a host address in prefix form") + } + g, err := netip.ParseAddr(gateway) + if err != nil || g.Zone() != "" || g == p.Addr() || g == p.Masked().Addr() || !p.Masked().Contains(g) { + return errors.New("provisioning gateway must be another host in the address prefix") + } + return nil +} + +func canonical(r Reservation) (Reservation, error) { + mac, ok := NormalizeMAC(r.MAC) + if !ok || r.Expires.IsZero() { + return Reservation{}, errors.New("invalid reservation") + } + if err := ValidAttachment(r.Address, r.Gateway); err != nil { + return Reservation{}, err + } + p, _ := netip.ParsePrefix(r.Address) + g, _ := netip.ParseAddr(r.Gateway) + return Reservation{MAC: mac, Address: p.String(), Gateway: g.String(), Expires: r.Expires.UTC().Truncate(time.Second)}, nil +} + +func revision(rs []Reservation) string { + b, _ := json.Marshal(rs) + s := sha256.Sum256(b) + return hex.EncodeToString(s[:]) +} + +// NewFeed canonicalizes, orders and checks reservations, and derives the +// revision. A MAC or an address may appear only once. +func NewFeed(rs []Reservation) (Feed, error) { + out := make([]Reservation, 0, len(rs)) + for _, r := range rs { + c, err := canonical(r) + if err != nil { + return Feed{}, err + } + out = append(out, c) + } + sort.Slice(out, func(i, j int) bool { return out[i].MAC < out[j].MAC }) + addresses := map[string]bool{} + for i, r := range out { + a, _ := netip.ParsePrefix(r.Address) + if (i > 0 && out[i-1].MAC == r.MAC) || addresses[a.Addr().String()] { + return Feed{}, errors.New("duplicate reservation") + } + addresses[a.Addr().String()] = true + } + return Feed{Revision: revision(out), Reservations: out}, nil +} + +// Verify accepts only a feed already in canonical form whose revision matches. +func (f Feed) Verify() error { + want, err := NewFeed(f.Reservations) + if err != nil { + return err + } + got, _ := json.Marshal(f) + exact, _ := json.Marshal(want) + if string(got) != string(exact) { + return errors.New("feed is not canonical or its revision does not match") + } + return nil +} + +// Verify checks the instance name and the applied feed. +func (a Applied) Verify() error { + if !instanceName.MatchString(a.Instance) { + return errors.New("invalid DHCP instance name") + } + return a.Feed.Verify() +} + +// Has reports whether the feed serves mac at exactly address. +func (f Feed) Has(mac, address string) bool { + for _, r := range f.Reservations { + if r.MAC == mac && r.Address == address { + return true + } + } + return false +} + +// Serves reports whether the feed serves mac at any address. +func (f Feed) Serves(mac string) bool { + for _, r := range f.Reservations { + if r.MAC == mac { + return true + } + } + return false +} diff --git a/internal/bootnet/feed_test.go b/internal/bootnet/feed_test.go new file mode 100644 index 00000000..985483a4 --- /dev/null +++ b/internal/bootnet/feed_test.go @@ -0,0 +1,55 @@ +package bootnet + +import ( + "testing" + "time" +) + +func TestFeedIsCanonicalAndSelfVerifying(t *testing.T) { + exp := time.Date(2030, 1, 2, 3, 4, 5, 999, time.FixedZone("x", 3600)) + a := Reservation{MAC: "52-54-00-77-01-0B", Address: "192.0.2.11/24", Gateway: "192.0.2.1", Expires: exp} + b := Reservation{MAC: "52:54:00:77:01:0a", Address: "192.0.2.10/24", Gateway: "192.0.2.1", Expires: exp} + f1, err := NewFeed([]Reservation{a, b}) + if err != nil { + t.Fatal(err) + } + f2, _ := NewFeed([]Reservation{b, a}) + if f1.Revision != f2.Revision || f1.Reservations[0].MAC != "52:54:00:77:01:0a" || !f1.Reservations[0].Expires.Equal(exp.Truncate(time.Second)) { + t.Fatalf("feed not canonical: %+v", f1) + } + if err := f1.Verify(); err != nil { + t.Fatal(err) + } + if !f1.Has("52:54:00:77:01:0a", "192.0.2.10/24") || f1.Has("52:54:00:77:01:0a", "192.0.2.11/24") || !f1.Serves("52:54:00:77:01:0b") || f1.Serves("52:54:00:77:01:0c") { + t.Fatal("membership is not exact") + } + empty, _ := NewFeed(nil) + for name, f := range map[string]Feed{ + "other revision": {Revision: empty.Revision, Reservations: f1.Reservations}, + "unordered": {Revision: f1.Revision, Reservations: []Reservation{f1.Reservations[1], f1.Reservations[0]}}, + "null reservation": {Revision: empty.Revision}, + } { + if f.Verify() == nil { + t.Errorf("%s: verified", name) + } + } + for name, rs := range map[string][]Reservation{ + "duplicate MAC": {b, {MAC: b.MAC, Address: "192.0.2.12/24", Gateway: "192.0.2.1", Expires: exp}}, + "duplicate address": {b, {MAC: "52:54:00:77:01:0c", Address: "192.0.2.10/25", Gateway: "192.0.2.1", Expires: exp}}, + "no expiry": {{MAC: b.MAC, Address: b.Address, Gateway: b.Gateway}}, + "bare address": {{MAC: b.MAC, Address: "192.0.2.10", Gateway: b.Gateway, Expires: exp}}, + "gateway is host": {{MAC: b.MAC, Address: b.Address, Gateway: "192.0.2.10", Expires: exp}}, + "host route": {{MAC: b.MAC, Address: "192.0.2.10/32", Gateway: "192.0.2.1", Expires: exp}}, + "long MAC": {{MAC: "02:00:5e:10:00:00:00:01", Address: b.Address, Gateway: b.Gateway, Expires: exp}}, + } { + if _, err := NewFeed(rs); err == nil { + t.Errorf("%s: accepted", name) + } + } + if _, err := NewFeed([]Reservation{{MAC: b.MAC, Address: "2001:db8::10/64", Gateway: "2001:db8::1", Expires: exp}}); err != nil { + t.Fatalf("IPv6 attachment: %v", err) + } + if (Applied{Instance: "kea-0", Feed: empty}).Verify() != nil || (Applied{Instance: "-kea", Feed: empty}).Verify() == nil { + t.Fatal("instance names not checked") + } +} diff --git a/internal/dhcpsync/sync.go b/internal/dhcpsync/sync.go new file mode 100644 index 00000000..15f0c596 --- /dev/null +++ b/internal/dhcpsync/sync.go @@ -0,0 +1,195 @@ +// Package dhcpsync applies a site's boot-reservation feed to a Kea DHCPv4 +// server and reports each applied revision back to the site. It runs beside +// one Kea instance, owned with DHCP by the network owner; Fleet only decides +// which reservations exist. A report is sent only after Kea accepted the +// configuration that serves exactly the reported feed. +package dhcpsync + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "net/http" + "net/netip" + "os" + "time" + + "go.datum.net/fleet/internal/bootnet" +) + +// Syncer is one synchronizer for one Kea instance. +type Syncer struct { + Feed string // the site's https DHCP feed origin + Token string + Instance string + Socket string // Kea's unix control socket + Base string // Kea configuration without Fleet reservations + HTTP *http.Client + + applied, reported string + pid float64 +} + +// Cycle fetches the feed, applies it when it changed or Kea restarted, and +// reports a newly applied revision. Any failure leaves the last report as the +// site's evidence; nothing is reported that Kea did not accept. +func (s *Syncer) Cycle(ctx context.Context) error { + feed, err := s.fetch(ctx) + if err != nil { + return err + } + status, err := s.command("status-get", nil) + if err != nil { + return err + } + pid, _ := status["pid"].(float64) + if pid == 0 { + return errors.New("kea status has no pid") + } + if feed.Revision != s.applied || pid != s.pid { + cfg, err := s.config(feed) + if err != nil { + return err + } + if _, err := s.command("config-set", cfg); err != nil { + return err + } + s.applied, s.pid = feed.Revision, pid + } + if s.reported == s.applied { + return nil + } + if err := s.report(ctx, feed); err != nil { + return err + } + s.reported = feed.Revision + return nil +} + +func (s *Syncer) request(ctx context.Context, method, path string, body []byte) (*http.Response, error) { + q, err := http.NewRequestWithContext(ctx, method, s.Feed+path, bytes.NewReader(body)) + if err != nil { + return nil, err + } + q.Header.Set("Authorization", "Bearer "+s.Token) + if body != nil { + q.Header.Set("Content-Type", "application/json") + } + return s.HTTP.Do(q) +} + +func (s *Syncer) fetch(ctx context.Context) (bootnet.Feed, error) { + resp, err := s.request(ctx, http.MethodGet, "/dhcp/v1/reservations", nil) + if err != nil { + return bootnet.Feed{}, err + } + defer resp.Body.Close() + var feed bootnet.Feed + d := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)) + d.DisallowUnknownFields() + if resp.StatusCode != http.StatusOK || d.Decode(&feed) != nil || feed.Verify() != nil { + return bootnet.Feed{}, fmt.Errorf("invalid reservation feed (HTTP %d)", resp.StatusCode) + } + return feed, nil +} + +func (s *Syncer) report(ctx context.Context, feed bootnet.Feed) error { + b, _ := json.Marshal(bootnet.Applied{Instance: s.Instance, Feed: feed}) + resp, err := s.request(ctx, http.MethodPost, "/dhcp/v1/applied", b) + if err != nil { + return err + } + resp.Body.Close() + if resp.StatusCode != http.StatusNoContent { + return fmt.Errorf("applied report rejected (HTTP %d)", resp.StatusCode) + } + return nil +} + +// config adds each reservation to the base subnet with exactly its prefix. +// A reservation with no such subnet is an error: it is never dropped silently. +func (s *Syncer) config(feed bootnet.Feed) (map[string]any, error) { + b, err := os.ReadFile(s.Base) + if err != nil { + return nil, err + } + var cfg map[string]any + if err := json.Unmarshal(b, &cfg); err != nil { + return nil, fmt.Errorf("base Kea configuration: %w", err) + } + dhcp, _ := cfg["Dhcp4"].(map[string]any) + subnets, _ := dhcp["subnet4"].([]any) + if subnets == nil { + return nil, errors.New("base Kea configuration has no Dhcp4 subnet4 list") + } + for _, r := range feed.Reservations { + p := netip.MustParsePrefix(r.Address) + if !p.Addr().Is4() { + return nil, fmt.Errorf("reservation %s is not IPv4", r.MAC) + } + var subnet map[string]any + for _, v := range subnets { + m, _ := v.(map[string]any) + text, _ := m["subnet"].(string) + if sp, err := netip.ParsePrefix(text); err == nil && sp == p.Masked() { + subnet = m + } + } + if subnet == nil { + return nil, fmt.Errorf("no base subnet %s for reservation %s", p.Masked(), r.MAC) + } + hosts, _ := subnet["reservations"].([]any) + subnet["reservations"] = append(hosts, map[string]any{ + "hw-address": r.MAC, "ip-address": p.Addr().String(), + "option-data": []any{map[string]any{"name": "routers", "data": r.Gateway}}, + }) + } + return cfg, nil +} + +// command sends one Kea control command and requires result 0. +func (s *Syncer) command(name string, arguments map[string]any) (map[string]any, error) { + c, err := net.DialTimeout("unix", s.Socket, 5*time.Second) + if err != nil { + return nil, err + } + defer c.Close() + _ = c.SetDeadline(time.Now().Add(30 * time.Second)) + q := map[string]any{"command": name} + if arguments != nil { + q["arguments"] = arguments + } + if err := json.NewEncoder(c).Encode(q); err != nil { + return nil, err + } + var resp struct { + Result int `json:"result"` + Text string `json:"text"` + Arguments map[string]any `json:"arguments"` + } + if err := json.NewDecoder(io.LimitReader(c, 4<<20)).Decode(&resp); err != nil { + return nil, fmt.Errorf("kea %s: %w", name, err) + } + if resp.Result != 0 { + return nil, fmt.Errorf("kea %s failed: %s", name, resp.Text) + } + return resp.Arguments, nil +} + +// Run cycles until the context ends, reporting each failed cycle. +func (s *Syncer) Run(ctx context.Context, interval time.Duration, failed func(error)) error { + for { + if err := s.Cycle(ctx); err != nil { + failed(err) + } + select { + case <-ctx.Done(): + return ctx.Err() + case <-time.After(interval): + } + } +} diff --git a/internal/dhcpsync/sync_test.go b/internal/dhcpsync/sync_test.go new file mode 100644 index 00000000..3121a534 --- /dev/null +++ b/internal/dhcpsync/sync_test.go @@ -0,0 +1,206 @@ +package dhcpsync + +import ( + "context" + "encoding/json" + "io" + "net" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "sync" + "testing" + "time" + + "go.datum.net/fleet/internal/bootnet" +) + +const token = "synthetic-dhcp-synchronizer-token-0123456789" + +// fakeKea answers status-get with its pid and records each config-set. +type fakeKea struct { + mu sync.Mutex + pid float64 + fail bool + configs []map[string]any +} + +func (k *fakeKea) serve(t *testing.T) string { + dir, err := os.MkdirTemp("", "kea") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { os.RemoveAll(dir) }) + path := filepath.Join(dir, "ctrl") + l, err := net.Listen("unix", path) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { l.Close() }) + go func() { + for { + c, err := l.Accept() + if err != nil { + return + } + var q struct { + Command string `json:"command"` + Arguments map[string]any `json:"arguments"` + } + _ = json.NewDecoder(c).Decode(&q) + k.mu.Lock() + resp := map[string]any{"result": 0} + switch { + case q.Command == "status-get": + resp["arguments"] = map[string]any{"pid": k.pid} + case q.Command == "config-set" && k.fail: + resp = map[string]any{"result": 1, "text": "synthetic rejection"} + case q.Command == "config-set": + k.configs = append(k.configs, q.Arguments) + } + k.mu.Unlock() + _ = json.NewEncoder(c).Encode(resp) + c.Close() + } + }() + return path +} + +func (k *fakeKea) applied() int { + k.mu.Lock() + defer k.mu.Unlock() + return len(k.configs) +} + +// fakeSite serves a feed and records applied reports. +type fakeSite struct { + mu sync.Mutex + feed bootnet.Feed + reports []bootnet.Applied +} + +func (f *fakeSite) handler(t *testing.T) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, q *http.Request) { + if q.Header.Get("Authorization") != "Bearer "+token { + w.WriteHeader(http.StatusUnauthorized) + return + } + f.mu.Lock() + defer f.mu.Unlock() + switch q.URL.Path { + case "/dhcp/v1/reservations": + _ = json.NewEncoder(w).Encode(f.feed) + case "/dhcp/v1/applied": + var a bootnet.Applied + b, _ := io.ReadAll(q.Body) + if json.Unmarshal(b, &a) != nil || a.Verify() != nil { + w.WriteHeader(http.StatusBadRequest) + return + } + f.reports = append(f.reports, a) + w.WriteHeader(http.StatusNoContent) + } + }) +} + +func (f *fakeSite) set(t *testing.T, rs ...bootnet.Reservation) { + feed, err := bootnet.NewFeed(rs) + if err != nil { + t.Fatal(err) + } + f.mu.Lock() + f.feed = feed + f.mu.Unlock() +} + +func (f *fakeSite) reported() []bootnet.Applied { + f.mu.Lock() + defer f.mu.Unlock() + return append([]bootnet.Applied(nil), f.reports...) +} + +func newSyncer(t *testing.T) (*Syncer, *fakeKea, *fakeSite) { + kea := &fakeKea{pid: 100} + site := &fakeSite{} + site.set(t) + srv := httptest.NewTLSServer(site.handler(t)) + t.Cleanup(srv.Close) + base := filepath.Join(t.TempDir(), "kea-dhcp4.conf") + os.WriteFile(base, []byte(`{"Dhcp4":{"subnet4":[{"id":1,"subnet":"192.0.2.0/24","relay":{"ip-addresses":["192.0.2.1"]}},{"id":2,"subnet":"198.51.100.0/24"}]}}`), 0600) + return &Syncer{Feed: srv.URL, Token: token, Instance: "kea-0", Socket: kea.serve(t), Base: base, HTTP: srv.Client()}, kea, site +} + +var reservation = bootnet.Reservation{MAC: "52:54:00:77:01:0a", Address: "192.0.2.10/24", Gateway: "192.0.2.1", Expires: time.Now().Add(time.Hour)} + +func TestAppliesReservationIntoItsExactSubnetThenReports(t *testing.T) { + s, kea, site := newSyncer(t) + ctx := context.Background() + if err := s.Cycle(ctx); err != nil || kea.applied() != 1 || len(site.reported()) != 1 { + t.Fatalf("empty feed not applied and reported: %v", err) + } + site.set(t, reservation) + if err := s.Cycle(ctx); err != nil { + t.Fatal(err) + } + kea.mu.Lock() + subnets := kea.configs[1]["Dhcp4"].(map[string]any)["subnet4"].([]any) + kea.mu.Unlock() + hosts, _ := json.Marshal(subnets[0].(map[string]any)["reservations"]) + if string(hosts) != `[{"hw-address":"52:54:00:77:01:0a","ip-address":"192.0.2.10","option-data":[{"data":"192.0.2.1","name":"routers"}]}]` || subnets[1].(map[string]any)["reservations"] != nil { + t.Fatalf("reservation not placed in exactly its subnet: %s", hosts) + } + reports := site.reported() + if len(reports) != 2 || !reports[1].Feed.Has(reservation.MAC, reservation.Address) || reports[1].Instance != "kea-0" { + t.Fatalf("applied revision not reported: %+v", reports) + } + // An unchanged feed is neither re-applied nor re-reported; a restarted + // Kea (new pid) lost its reservations and is re-applied without a report. + if err := s.Cycle(ctx); err != nil || kea.applied() != 2 || len(site.reported()) != 2 { + t.Fatalf("unchanged feed churned: %v", err) + } + kea.mu.Lock() + kea.pid = 101 + kea.mu.Unlock() + if err := s.Cycle(ctx); err != nil || kea.applied() != 3 || len(site.reported()) != 2 { + t.Fatalf("restarted Kea not re-applied: %v", err) + } + site.set(t) + if err := s.Cycle(ctx); err != nil || len(site.reported()) != 3 || site.reported()[2].Feed.Serves(reservation.MAC) { + t.Fatalf("withdrawal not applied and reported: %v", err) + } +} + +func TestNothingIsReportedThatKeaDidNotAccept(t *testing.T) { + s, kea, site := newSyncer(t) + ctx := context.Background() + kea.mu.Lock() + kea.fail = true + kea.mu.Unlock() + site.set(t, reservation) + if err := s.Cycle(ctx); err == nil || len(site.reported()) != 0 { + t.Fatal("a rejected configuration was reported as applied") + } + kea.mu.Lock() + kea.fail = false + kea.mu.Unlock() + site.set(t, bootnet.Reservation{MAC: reservation.MAC, Address: "203.0.113.10/24", Gateway: "203.0.113.1", Expires: reservation.Expires}) + if err := s.Cycle(ctx); err == nil || kea.applied() != 0 || len(site.reported()) != 0 { + t.Fatal("a reservation without a base subnet was dropped or applied") + } + s.Token = "wrong-token-wrong-token-wrong-token-0000" + if err := s.Cycle(ctx); err == nil { + t.Fatal("an unauthenticated feed was accepted") + } +} + +func TestForgedFeedIsRejectedBeforeKea(t *testing.T) { + s, kea, site := newSyncer(t) + site.set(t, reservation) + site.mu.Lock() + site.feed.Reservations[0].Address = "192.0.2.99/24" + site.mu.Unlock() + if err := s.Cycle(context.Background()); err == nil || kea.applied() != 0 { + t.Fatal("a feed whose revision does not match its reservations was applied") + } +} diff --git a/internal/redfish/client.go b/internal/redfish/client.go index c9c0d1b4..3109d62f 100644 --- a/internal/redfish/client.go +++ b/internal/redfish/client.go @@ -55,17 +55,29 @@ type Client struct { api *gofish.APIClient } -// NewClient accepts only an http(s)://IP:port endpoint without path or query. -// It performs no request until first use. -func NewClient(endpoint, user, password string, timeout time.Duration) (*Client, error) { +// ParseEndpoint accepts only an http(s)://IPv4:port BMC endpoint without path +// or query, and returns its canonical form. +func ParseEndpoint(endpoint string) (string, error) { u, err := url.Parse(endpoint) if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.User != nil || (u.Path != "" && u.Path != "/") || u.RawQuery != "" || u.Fragment != "" { - return nil, errors.New("redfish endpoint must be http(s)://IPv4:port") + return "", errors.New("redfish endpoint must be http(s)://IPv4:port") } port, err := strconv.Atoi(u.Port()) - if ip := net.ParseIP(u.Hostname()); ip == nil || ip.To4() == nil || err != nil || port < 1 || port > 65535 { - return nil, errors.New("redfish endpoint must be http(s)://IPv4:port") + ip := net.ParseIP(u.Hostname()) + if ip == nil || ip.To4() == nil || err != nil || port < 1 || port > 65535 { + return "", errors.New("redfish endpoint must be http(s)://IPv4:port") + } + return u.Scheme + "://" + ip.To4().String() + ":" + strconv.Itoa(port), nil +} + +// NewClient accepts only an endpoint ParseEndpoint accepts. It performs no +// request until first use. +func NewClient(endpoint, user, password string, timeout time.Duration) (*Client, error) { + endpoint, err := ParseEndpoint(endpoint) + if err != nil { + return nil, err } + u, _ := url.Parse(endpoint) if user == "" || password == "" || strings.ContainsAny(user, ":\r\n") || strings.ContainsAny(password, "\r\n") { return nil, errors.New("redfish credential must be a nonempty single-line username and password") } diff --git a/internal/redfish/dhcp.go b/internal/redfish/dhcp.go new file mode 100644 index 00000000..b9af3f8c --- /dev/null +++ b/internal/redfish/dhcp.go @@ -0,0 +1,221 @@ +package redfish + +import ( + "bufio" + "context" + "crypto/subtle" + "encoding/json" + "errors" + "io" + "net/http" + "os" + "path/filepath" + "strings" + "time" + + "go.datum.net/fleet/internal/bootnet" +) + +// withdrawalWindow bounds how long a worker waits, after the network boot +// closed, for every DHCP instance that served the reservation to report it +// withdrawn. Past it the outcome stays unknown and replay waits again. +const withdrawalWindow = 10 * time.Minute + +const dhcpLog = "dhcp-applied.log" + +// report is one retained applied report: when the boot service accepted it, +// which DHCP instance applied which exact feed. +type report struct { + At time.Time `json:"at"` + Instance string `json:"instance"` + Feed bootnet.Feed `json:"feed"` +} + +// reserved reports whether the operation's boot NIC should hold its +// provisioning address now: the same admission the boot handler serves, +// widened to the stages before power-on so DHCP is ready when firmware asks. +func (p *Provider) reserved(j journal, r *record, now time.Time) bool { + return r.Target.Provisioning != (Provisioning{}) && !j.Closed && j.Image == p.image && r.Stage != "done" && !r.BootClosed && len(r.BootToken) == 64 && now.Before(r.BootExpires) && + r.Request.BindingID == j.Binding && r.Request.Epoch == j.Epoch && r.Request.FenceToken == j.Fence +} + +// Reservations is the complete desired reservation set derived from the +// journal. It is empty when no network boot is admitted. +func (p *Provider) Reservations() (bootnet.Feed, error) { + j, err := p.read() + if err != nil { + return bootnet.Feed{}, err + } + now := p.clock() + rs := []bootnet.Reservation{} + for _, r := range j.Operations { + if p.reserved(j, r, now) { + rs = append(rs, bootnet.Reservation{MAC: r.Target.MAC, Address: r.Target.Provisioning.Address, Gateway: r.Target.Provisioning.Gateway, Expires: r.BootExpires}) + } + } + return bootnet.NewFeed(rs) +} + +// DHCPHandler serves the reservation feed and accepts applied reports from +// the DHCP owner's synchronizer, authenticated by a shared bearer token. It +// is never served on the firmware-facing boot listener. +func (p *Provider) DHCPHandler(token string) (http.Handler, error) { + if len(token) < 32 || strings.ContainsAny(token, " \t\r\n") { + return nil, errors.New("DHCP synchronizer token must be at least 32 characters without whitespace") + } + return http.HandlerFunc(func(w http.ResponseWriter, q *http.Request) { + w.Header().Set("Cache-Control", "no-store") + got, ok := strings.CutPrefix(q.Header.Get("Authorization"), "Bearer ") + if !ok || subtle.ConstantTimeCompare([]byte(got), []byte(token)) != 1 { + http.Error(w, "unauthorized", http.StatusUnauthorized) + return + } + switch { + case q.Method == http.MethodGet && q.URL.Path == "/dhcp/v1/reservations" && q.URL.RawQuery == "": + feed, err := p.Reservations() + if err != nil { + http.Error(w, "reservations unavailable", http.StatusServiceUnavailable) + return + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(feed) + case q.Method == http.MethodPost && q.URL.Path == "/dhcp/v1/applied" && q.URL.RawQuery == "": + var a bootnet.Applied + d := json.NewDecoder(io.LimitReader(q.Body, 64<<10)) + d.DisallowUnknownFields() + if d.Decode(&a) != nil || d.Decode(&struct{}{}) != io.EOF || a.Verify() != nil { + http.Error(w, "invalid applied report", http.StatusBadRequest) + return + } + if err := p.retainReport(a); err != nil { + http.Error(w, "applied report not retained", http.StatusServiceUnavailable) + return + } + w.WriteHeader(http.StatusNoContent) + default: + http.Error(w, "not found", http.StatusNotFound) + } + }), nil +} + +// ServeDHCP listens on :8081, separate from the boot listener. +func (p *Provider) ServeDHCP(token string) error { + h, err := p.DHCPHandler(token) + if err != nil { + return err + } + s := &http.Server{Addr: ":8081", Handler: h, ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, IdleTimeout: 30 * time.Second} + return s.ListenAndServe() +} + +// retainReport appends one report and syncs it before acknowledging. +func (p *Provider) retainReport(a bootnet.Applied) error { + b, err := json.Marshal(report{At: p.clock(), Instance: a.Instance, Feed: a.Feed}) + if err != nil { + return err + } + if err := os.MkdirAll(p.bootRoot, 0700); err != nil { + return err + } + f, err := os.OpenFile(filepath.Join(p.bootRoot, dhcpLog), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600) + if err != nil { + return err + } + _, err = f.Write(append(b, '\n')) + if err == nil { + err = f.Sync() + } + if cerr := f.Close(); err == nil { + err = cerr + } + if err == nil { + err = syncDir(p.bootRoot) + } + return err +} + +// reports reads every retained report in order. An unreadable line is +// corruption, never evidence in either direction. +func (p *Provider) reports() ([]report, error) { + f, err := os.Open(filepath.Join(p.bootRoot, dhcpLog)) + if os.IsNotExist(err) { + return nil, nil + } + if err != nil { + return nil, err + } + defer f.Close() + var out []report + s := bufio.NewScanner(f) + s.Buffer(make([]byte, 0, 64<<10), 1<<20) + for s.Scan() { + var r report + if json.Unmarshal(s.Bytes(), &r) != nil || r.At.IsZero() || (bootnet.Applied{Instance: r.Instance, Feed: r.Feed}).Verify() != nil { + return nil, errors.New("invalid retained DHCP report") + } + out = append(out, r) + } + return out, s.Err() +} + +// awaitReservation waits, without any effect, until some DHCP instance reports +// serving the target's exact provisioning address for this operation. +func (p *Provider) awaitReservation(ctx context.Context, r *record) error { + poll, _, _, _ := p.durations() + for { + reports, err := p.reports() + if err != nil { + return err + } + for _, a := range reports { + if a.At.After(r.Result.CreatedAt) && a.Feed.Has(r.Target.MAC, r.Target.Provisioning.Address) { + return nil + } + } + if !p.clock().Before(r.BootExpires) { + return errors.New("DHCP did not apply the boot reservation before boot admission expired") + } + if err := sleep(ctx, poll); err != nil { + return err + } + } +} + +// awaitWithdrawal requires that every DHCP instance which served the boot NIC +// during this operation now reports a feed without it. A silent instance +// keeps the outcome unknown: its reservation may still be served. +func (p *Provider) awaitWithdrawal(ctx context.Context, r *record) error { + poll, _, _, _ := p.durations() + deadline := p.clock().Add(withdrawalWindow) + for { + reports, err := p.reports() + if err != nil { + return err + } + served, latest := map[string]bool{}, map[string]bootnet.Feed{} + for _, a := range reports { + if !a.At.After(r.Result.CreatedAt) { + continue + } + if a.Feed.Serves(r.Target.MAC) { + served[a.Instance] = true + } + latest[a.Instance] = a.Feed + } + withdrawn := len(served) > 0 + for instance := range served { + if latest[instance].Serves(r.Target.MAC) { + withdrawn = false + } + } + if withdrawn { + return nil + } + if p.clock().After(deadline) { + return errors.New("DHCP has not reported the boot reservation withdrawn") + } + if err := sleep(ctx, poll); err != nil { + return err + } + } +} diff --git a/internal/redfish/dhcp_test.go b/internal/redfish/dhcp_test.go new file mode 100644 index 00000000..9e60e1cc --- /dev/null +++ b/internal/redfish/dhcp_test.go @@ -0,0 +1,317 @@ +package redfish + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "go.datum.net/fleet/internal/bootnet" + "go.datum.net/fleet/internal/executor" +) + +const syncToken = "synthetic-dhcp-synchronizer-token-0123456789" + +// fakeSync stands in for the DHCP owner's synchronizer: each instance applies +// the current feed and reports it whenever its revision changes. Withholding +// an instance's reports models a DHCP instance that may still serve. +type fakeSync struct { + t *testing.T + h http.Handler + mu sync.Mutex + silent map[string]bool + applied map[string]string + stop chan struct{} + done sync.WaitGroup +} + +func startSync(t *testing.T, p *Provider, instances ...string) *fakeSync { + t.Helper() + h, err := p.DHCPHandler(syncToken) + if err != nil { + t.Fatal(err) + } + s := &fakeSync{t: t, h: h, silent: map[string]bool{}, applied: map[string]string{}, stop: make(chan struct{})} + s.done.Add(1) + go func() { + defer s.done.Done() + for { + select { + case <-s.stop: + return + case <-time.After(2 * time.Millisecond): + } + for _, instance := range instances { + s.cycle(instance) + } + } + }() + t.Cleanup(s.close) + return s +} + +func (s *fakeSync) close() { + select { + case <-s.stop: + default: + close(s.stop) + } + s.done.Wait() +} + +func (s *fakeSync) silence(instance string, v bool) { + s.mu.Lock() + s.silent[instance] = v + s.mu.Unlock() +} + +func (s *fakeSync) cycle(instance string) { + s.mu.Lock() + defer s.mu.Unlock() + if s.silent[instance] { + return + } + w := httptest.NewRecorder() + q := httptest.NewRequest(http.MethodGet, "/dhcp/v1/reservations", nil) + q.Header.Set("Authorization", "Bearer "+syncToken) + s.h.ServeHTTP(w, q) + var feed bootnet.Feed + if w.Code != http.StatusOK || json.Unmarshal(w.Body.Bytes(), &feed) != nil || s.applied[instance] == feed.Revision { + return + } + if code := post(s.h, syncToken, bootnet.Applied{Instance: instance, Feed: feed}); code != http.StatusNoContent { + return + } + s.applied[instance] = feed.Revision +} + +func post(h http.Handler, token string, a any) int { + b, _ := json.Marshal(a) + w := httptest.NewRecorder() + q := httptest.NewRequest(http.MethodPost, "/dhcp/v1/applied", bytes.NewReader(b)) + q.Header.Set("Authorization", "Bearer "+token) + h.ServeHTTP(w, q) + return w.Code +} + +func TestEnrollmentRecordsPhysicalAttachments(t *testing.T) { + target := func(asset, endpoint, system, uuid, mac, prov string) string { + return fmt.Sprintf(`{"assetID":%q,"endpoint":%q,"systemID":%q,"systemUUID":%q,"mac":%q%s,"diskBytes":1,"console":"c.log"}`, asset, endpoint, system, uuid, mac, prov) + } + prov := func(address string) string { + return `,"provisioning":{"address":"` + address + `","gateway":"198.51.100.1"}` + } + // Physical BMCs each expose one System with the same ID: identity is the + // endpoint plus System, so two "Self" systems on two BMCs are distinct. + e, err := ParseEnrollment([]byte(`{"dhcp":"synced","targets":[` + + target("a", "https://192.0.2.20:443", "Self", uuidA, "00-00-5E-00-53-20", prov("198.51.100.21/24")) + `,` + + target("b", "https://192.0.2.21:443", "Self", uuidB, "00:00:5e:00:53:21", prov("198.51.100.22/24")) + `]}`)) + if err != nil { + t.Fatal(err) + } + if got := e.Targets[0]; got.Endpoint != "https://192.0.2.20:443" || got.MAC != "00:00:5e:00:53:20" || got.Provisioning != (Provisioning{Address: "198.51.100.21/24", Gateway: "198.51.100.1"}) { + t.Fatalf("enrollment not canonical: %+v", got) + } + for name, body := range map[string]string{ + "same System on one BMC": `{"dhcp":"synced","targets":[` + target("a", "https://192.0.2.20:443", "Self", uuidA, "00:00:5e:00:53:20", prov("198.51.100.21/24")) + `,` + + target("b", "https://192.0.2.20:443", "Self", uuidB, "00:00:5e:00:53:21", prov("198.51.100.22/24")) + `]}`, + "shared provisioning address": `{"dhcp":"synced","targets":[` + target("a", "https://192.0.2.20:443", "Self", uuidA, "00:00:5e:00:53:20", prov("198.51.100.21/24")) + `,` + + target("b", "https://192.0.2.21:443", "Self", uuidB, "00:00:5e:00:53:21", prov("198.51.100.21/24")) + `]}`, + "synced without attachment": `{"dhcp":"synced","targets":[` + target("a", "https://192.0.2.20:443", "Self", uuidA, "00:00:5e:00:53:20", "") + `]}`, + "static with attachment": `{"dhcp":"static","targets":[` + target("a", "https://192.0.2.20:443", "Self", uuidA, "00:00:5e:00:53:20", prov("198.51.100.21/24")) + `]}`, + "gateway outside prefix": `{"dhcp":"synced","targets":[` + target("a", "https://192.0.2.20:443", "Self", uuidA, "00:00:5e:00:53:20", `,"provisioning":{"address":"198.51.100.21/24","gateway":"203.0.113.1"}`) + `]}`, + "network address as host": `{"dhcp":"synced","targets":[` + target("a", "https://192.0.2.20:443", "Self", uuidA, "00:00:5e:00:53:20", prov("198.51.100.0/24")) + `]}`, + "BMC endpoint with a path": `{"dhcp":"static","targets":[` + target("a", "https://192.0.2.20:443/redfish", "Self", uuidA, "00:00:5e:00:53:20", "") + `]}`, + "missing DHCP mode": `{"targets":[` + target("a", "https://192.0.2.20:443", "Self", uuidA, "00:00:5e:00:53:20", "") + `]}`, + "retired site-wide BMC endpoint": `{"dhcp":"static","endpoint":"https://192.0.2.20:443","targets":[` + target("a", "https://192.0.2.20:443", "Self", uuidA, "00:00:5e:00:53:20", "") + `]}`, + } { + if _, err := ParseEnrollment([]byte(body)); err == nil { + t.Errorf("%s: accepted", name) + } + } +} + +func TestSyncedInstallServesAndWithdrawsTheReservation(t *testing.T) { + f := newDHCPFixture(t, time.Second, DHCPSynced) + ctx := context.Background() + if feed, err := f.p.Reservations(); err != nil || len(feed.Reservations) != 0 { + t.Fatalf("reservations published with no admitted boot: %+v %v", feed, err) + } + s := startSync(t, f.p, "kea-0") + q := f.install(1) + if r, err := f.p.Execute(ctx, q); err != nil || r.Result != "installed" { + t.Fatalf("install: %v %+v", err, r) + } + f.bmc.wg.Wait() + s.close() + reports, err := f.p.reports() + if err != nil { + t.Fatal(err) + } + var served, withdrawn bool + for _, a := range reports { + if a.Feed.Has("52:54:00:77:01:0a", "192.0.2.10/24") { + served = true + } else if served { + withdrawn = true + } + if a.Feed.Serves("52:54:00:77:01:0b") { + t.Fatal("the other enrolled target's attachment was published") + } + } + if !served || !withdrawn { + t.Fatalf("reports do not show the reservation served then withdrawn: %+v", reports) + } + if feed, _ := f.p.Reservations(); len(feed.Reservations) != 0 { + t.Fatalf("reservation outlived the operation: %+v", feed) + } + if b, _ := os.ReadFile(filepath.Join(f.p.bootRoot, dhcpLog)); strings.Contains(string(b), syncToken) { + t.Fatal("DHCP evidence contains the synchronizer token") + } +} + +func TestSyncedBootWaitsForDHCPWithoutEffects(t *testing.T) { + f := newDHCPFixture(t, time.Second, DHCPSynced) + q := f.install(1) + ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond) + defer cancel() + if _, err := f.p.Execute(ctx, q); !errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatalf("network boot proceeded without DHCP evidence: %v", err) + } + if got := strings.Join(f.bmc.mutationsFor("System-1"), ","); strings.Contains(got, "Pxe") || strings.Contains(got, "On") { + t.Fatalf("boot effects before DHCP applied the reservation: %s", got) + } + // A report from before this operation is not evidence for it. + feed, _ := f.p.Reservations() + if len(feed.Reservations) != 1 || !feed.Has("52:54:00:77:01:0a", "192.0.2.10/24") { + t.Fatalf("admitted operation not published: %+v", feed) + } + startSync(t, f.p, "kea-0") + if r, err := f.p.Execute(context.Background(), q); err != nil || r.Result != "installed" { + t.Fatalf("replay after DHCP applied: %v %+v", err, r) + } + f.bmc.wg.Wait() + if got := f.bmc.mutationsFor("System-1"); strings.Join(got, ",") != "POST ForceOff,PATCH Pxe,POST On,PATCH Hdd,POST On" { + t.Fatalf("unexpected Redfish effects: %v", got) + } +} + +func TestUnwithdrawnReservationKeepsTheOutcomeUnknown(t *testing.T) { + f := newDHCPFixture(t, time.Second, DHCPSynced) + s := startSync(t, f.p, "kea-0", "kea-1") + q := f.install(1) + result := make(chan error, 1) + go func() { + r, err := f.p.Execute(context.Background(), q) + if err == nil && r.Result != "installed" { + err = fmt.Errorf("unexpected result %+v", r) + } + result <- err + }() + waitFor := func(what string, ok func() bool) { + t.Helper() + for deadline := time.Now().Add(5 * time.Second); !ok(); time.Sleep(2 * time.Millisecond) { + if time.Now().After(deadline) { + t.Fatal("timed out waiting for " + what) + } + } + } + // Both instances serve the reservation; then kea-1 goes silent, so it + // never reports the withdrawal and may still be serving. + waitFor("both instances to serve", func() bool { + reports, _ := f.p.reports() + served := map[string]bool{} + for _, a := range reports { + if a.Feed.Serves("52:54:00:77:01:0a") { + served[a.Instance] = true + } + } + return len(served) == 2 + }) + s.silence("kea-1", true) + waitFor("the withdrawal gate", func() bool { return f.stage(t, q.ID) == "disk-verified" }) + time.Sleep(50 * time.Millisecond) + observer := *f.p + observer.readOnly = true + if _, found, err := observer.Lookup(context.Background(), q.ID); found || !errors.Is(err, executor.ErrOutcomeUnknown) { + t.Fatalf("completed while one DHCP instance may still serve: %v %v", found, err) + } + s.silence("kea-1", false) + if err := <-result; err != nil { + t.Fatalf("withdrawal by every serving instance did not complete the operation: %v", err) + } + f.bmc.wg.Wait() +} + +func TestDHCPHandlerAuthenticatesAndRejectsForgedReports(t *testing.T) { + f := newDHCPFixture(t, time.Second, DHCPSynced) + if _, err := f.p.DHCPHandler("short"); err == nil { + t.Fatal("a weak token was accepted") + } + h, _ := f.p.DHCPHandler(syncToken) + for _, auth := range []string{"", "Bearer wrong-token-wrong-token-wrong-token-0000", "Basic " + syncToken} { + w := httptest.NewRecorder() + q := httptest.NewRequest(http.MethodGet, "/dhcp/v1/reservations", nil) + if auth != "" { + q.Header.Set("Authorization", auth) + } + h.ServeHTTP(w, q) + if w.Code != http.StatusUnauthorized { + t.Fatalf("%q: %d", auth, w.Code) + } + } + if code := post(h, "wrong-token-wrong-token-wrong-token-0000", bootnet.Applied{Instance: "kea-0", Feed: bootnet.Feed{Reservations: []bootnet.Reservation{}}}); code != http.StatusUnauthorized { + t.Fatalf("unauthenticated report: %d", code) + } + valid, _ := bootnet.NewFeed([]bootnet.Reservation{{MAC: "52:54:00:77:01:0a", Address: "192.0.2.10/24", Gateway: "192.0.2.1", Expires: time.Now().Add(time.Minute)}}) + forged := valid + forged.Reservations = []bootnet.Reservation{} + for name, a := range map[string]any{ + "revision of another set": bootnet.Applied{Instance: "kea-0", Feed: forged}, + "bad instance": bootnet.Applied{Instance: "Kea 0", Feed: valid}, + "unknown field": map[string]any{"instance": "kea-0", "feed": valid, "extra": true}, + } { + if code := post(h, syncToken, a); code != http.StatusBadRequest { + t.Fatalf("%s: %d", name, code) + } + } + if reports, _ := f.p.reports(); len(reports) != 0 { + t.Fatalf("rejected reports were retained: %+v", reports) + } + if code := post(h, syncToken, bootnet.Applied{Instance: "kea-0", Feed: valid}); code != http.StatusNoContent { + t.Fatalf("valid report: %d", code) + } + w := httptest.NewRecorder() + q := httptest.NewRequest(http.MethodGet, "/pxe/boot.ipxe", nil) + q.Header.Set("Authorization", "Bearer "+syncToken) + h.ServeHTTP(w, q) + if w.Code != http.StatusNotFound { + t.Fatalf("DHCP listener served a boot path: %d", w.Code) + } + os.WriteFile(filepath.Join(f.p.bootRoot, dhcpLog), []byte("not json\n"), 0600) + if _, err := f.p.reports(); err == nil { + t.Fatal("corrupt DHCP evidence was read as evidence") + } +} + +func TestShippedLabEnrollmentIsValidAndStatic(t *testing.T) { + b, err := os.ReadFile("../../config/site/redfish/graph/kustomization.yaml") + if err != nil { + t.Fatal(err) + } + _, value, ok := strings.Cut(string(b), "- name: FLEET_REDFISH_ENROLLMENT\n value: '") + value, _, _ = strings.Cut(value, "'\n") + e, err := ParseEnrollment([]byte(value)) + if !ok || err != nil || e.DHCP != DHCPStatic || len(e.Targets) != 2 { + t.Fatalf("shipped lab enrollment: %v %+v", err, e) + } +} diff --git a/internal/redfish/provider.go b/internal/redfish/provider.go index f6327e67..b97d029e 100644 --- a/internal/redfish/provider.go +++ b/internal/redfish/provider.go @@ -17,6 +17,7 @@ import ( "strings" "time" + "go.datum.net/fleet/internal/bootnet" "go.datum.net/fleet/internal/executor" "go.datum.net/fleet/internal/simulator" "golang.org/x/sys/unix" @@ -33,22 +34,42 @@ const ( maxPowerOn = 3 ) -// Target is one enrolled physical asset and its exact Redfish System. Console -// names the serial-console capture file for the target (a lab seam; see the -// operations guide). Enrollment is retained before effects and never inferred. +// Target is one enrolled physical asset: its BMC endpoint, its exact Redfish +// System, its boot NIC and, when the site's DHCP is synchronized, the +// provisioning attachment the network owner assigned to it. Console names the +// serial-console capture file for the target (a lab seam; see the operations +// guide). Enrollment is retained before effects and never inferred. type Target struct { - AssetID string `json:"assetID"` - SystemID string `json:"systemID"` - SystemUUID string `json:"systemUUID"` - MAC string `json:"mac"` - DiskBytes int64 `json:"diskBytes"` - Console string `json:"console"` -} + AssetID string `json:"assetID"` + Endpoint string `json:"endpoint"` + SystemID string `json:"systemID"` + SystemUUID string `json:"systemUUID"` + MAC string `json:"mac"` + Provisioning Provisioning `json:"provisioning,omitzero"` + DiskBytes int64 `json:"diskBytes"` + Console string `json:"console"` +} + +// Provisioning is the asset's address on the provisioning network, in prefix +// form, and that network's gateway. Networking/IPAM allocates it; Fleet only +// publishes it while the asset's network boot is admitted. +type Provisioning struct { + Address string `json:"address"` + Gateway string `json:"gateway"` +} + +// DHCP modes. Static: the site's DHCP is configured independently of Fleet. +// Synced: Fleet publishes boot reservations and a network boot requires +// evidence that DHCP applied the reservation and later withdrew it. +const ( + DHCPStatic = "static" + DHCPSynced = "synced" +) // Enrollment is the site's explicit asset to BMC mapping. type Enrollment struct { - Endpoint string `json:"endpoint"` - Targets []Target `json:"targets"` + DHCP string `json:"dhcp"` + Targets []Target `json:"targets"` } func (e Enrollment) target(asset string) (Target, bool) { @@ -61,29 +82,45 @@ func (e Enrollment) target(asset string) (Target, bool) { } func normalizeMAC(v string) (string, bool) { - hw, err := net.ParseMAC(strings.ReplaceAll(v, "-", ":")) - if err != nil || len(hw) != 6 { - return "", false - } - return hw.String(), true + return bootnet.NormalizeMAC(strings.ReplaceAll(v, "-", ":")) } func ParseEnrollment(b []byte) (Enrollment, error) { var e Enrollment d := json.NewDecoder(strings.NewReader(string(b))) d.DisallowUnknownFields() - if err := d.Decode(&e); err != nil || len(e.Targets) == 0 { + if err := d.Decode(&e); err != nil || len(e.Targets) == 0 || (e.DHCP != DHCPStatic && e.DHCP != DHCPSynced) { return Enrollment{}, errors.New("invalid Redfish enrollment") } seen := map[string]bool{} for i, t := range e.Targets { mac, ok := normalizeMAC(t.MAC) - if !ok || t.AssetID == "" || t.SystemID == "" || len(t.SystemUUID) != 36 || t.DiskBytes <= 0 || t.Console == "" || filepath.Base(t.Console) != t.Console || - seen["a"+t.AssetID] || seen["s"+t.SystemID] || seen["u"+strings.ToLower(t.SystemUUID)] || seen["m"+mac] { + endpoint, err := ParseEndpoint(t.Endpoint) + // A Redfish System ID is unique only within its BMC. + system := "s" + endpoint + " " + t.SystemID + if !ok || err != nil || t.AssetID == "" || t.SystemID == "" || len(t.SystemUUID) != 36 || t.DiskBytes <= 0 || t.Console == "" || filepath.Base(t.Console) != t.Console || + seen["a"+t.AssetID] || seen[system] || seen["u"+strings.ToLower(t.SystemUUID)] || seen["m"+mac] { return Enrollment{}, errors.New("invalid or duplicate Redfish enrollment target") } - seen["a"+t.AssetID], seen["s"+t.SystemID], seen["u"+strings.ToLower(t.SystemUUID)], seen["m"+mac] = true, true, true, true - e.Targets[i].MAC = mac + seen["a"+t.AssetID], seen[system], seen["u"+strings.ToLower(t.SystemUUID)], seen["m"+mac] = true, true, true, true + e.Targets[i].MAC, e.Targets[i].Endpoint = mac, endpoint + if e.DHCP == DHCPStatic { + if t.Provisioning != (Provisioning{}) { + return Enrollment{}, errors.New("a static-DHCP enrollment carries no provisioning attachment") + } + continue + } + feed, err := bootnet.NewFeed([]bootnet.Reservation{{MAC: mac, Address: t.Provisioning.Address, Gateway: t.Provisioning.Gateway, Expires: time.Unix(1, 0)}}) + if err != nil { + return Enrollment{}, errors.New("invalid provisioning attachment for enrolled target " + t.AssetID) + } + r := feed.Reservations[0] + address := "p" + strings.SplitN(r.Address, "/", 2)[0] + if seen[address] { + return Enrollment{}, errors.New("duplicate provisioning address") + } + seen[address] = true + e.Targets[i].Provisioning = Provisioning{Address: r.Address, Gateway: r.Gateway} } return e, nil } @@ -127,7 +164,7 @@ type Provider struct { root, bootRoot, consoleRoot, artifacts string origin, image string enrollment Enrollment - client *Client + clients map[string]*Client readOnly bool now func() time.Time poll, settle, offGrace, outage time.Duration @@ -163,15 +200,20 @@ func Open() (*Provider, error) { if credentials == "" || err1 != nil || err2 != nil { return nil, errors.New("redfish credentials are unavailable") } - client, err := NewClient(enrollment.Endpoint, strings.TrimSpace(string(user)), strings.TrimSpace(string(password)), 20*time.Second) - if err != nil { - return nil, err + p.clients = map[string]*Client{} + for _, t := range enrollment.Targets { + if p.clients[t.Endpoint] != nil { + continue + } + if p.clients[t.Endpoint], err = NewClient(t.Endpoint, strings.TrimSpace(string(user)), strings.TrimSpace(string(password)), 20*time.Second); err != nil { + return nil, err + } } p.consoleRoot = os.Getenv("FLEET_REDFISH_CONSOLE") if !filepath.IsAbs(p.consoleRoot) { return nil, errors.New("FLEET_REDFISH_CONSOLE must be an absolute path") } - p.client, p.enrollment = client, enrollment + p.enrollment = enrollment return p, p.retainEnrollment() } @@ -447,7 +489,7 @@ func (p *Provider) validate(q simulator.Request) (Target, error) { // have happened. HTTP success is never success: only observed power state and // the exact console receipt complete a phase. func (p *Provider) Execute(ctx context.Context, q simulator.Request) (simulator.OperationResult, error) { - if p.readOnly || p.client == nil { + if p.readOnly || len(p.clients) == 0 { return simulator.OperationResult{}, executor.ErrInvalid } ctx, cancel := context.WithTimeout(ctx, 40*time.Minute) @@ -554,7 +596,7 @@ func (p *Provider) run(ctx context.Context, j *journal, r *record) error { if r.Stage == "admitted" { // GETs only: a rejected credential, a missing capability or a // mismatched identity leaves the operation admitted with no effect. - sys, err := p.client.Discover(ctx, r.Target) + sys, err := p.bmc(r).Discover(ctx, r.Target) if err != nil { return fmt.Errorf("discovery: %w", err) } @@ -571,13 +613,18 @@ func (p *Provider) run(ctx context.Context, j *journal, r *record) error { if r.Stage == before { // Pre-boot: power off and arm the one-time override. Both are // idempotent here because no boot of this phase was requested. - if err := p.powerOff(ctx, *r.System); err != nil { + if err := p.powerOff(ctx, r); err != nil { return err } if ph.mode != "" && (r.BootClosed || !p.clock().Before(r.BootExpires)) { return errors.New("boot admission expired or closed before network boot") } - if err := p.client.SetBootOnce(ctx, *r.System, ph.boot); err != nil { + if ph.mode != "" && p.enrollment.DHCP == DHCPSynced { + if err := p.awaitReservation(ctx, r); err != nil { + return err + } + } + if err := p.bmc(r).SetBootOnce(ctx, *r.System, ph.boot); err != nil { return fmt.Errorf("arm %s boot: %w", ph.boot, err) } r.Stage = ph.name + "-armed" @@ -623,15 +670,22 @@ func (p *Provider) run(ctx context.Context, j *journal, r *record) error { if r.Stage != before { return errors.New("unexpected operation stage " + r.Stage) } + if p.enrollment.DHCP == DHCPSynced { + return p.awaitWithdrawal(ctx, r) + } return nil } -func (p *Provider) powerOff(ctx context.Context, sys System) error { +// bmc is the client of the target's own enrolled BMC. +func (p *Provider) bmc(r *record) *Client { return p.clients[r.Target.Endpoint] } + +func (p *Provider) powerOff(ctx context.Context, r *record) error { + sys := *r.System poll, _, _, _ := p.durations() deadline := p.clock().Add(5 * time.Minute) requested := false for { - pw, err := p.client.Observe(ctx, sys) + pw, err := p.bmc(r).Observe(ctx, sys) if err != nil { return fmt.Errorf("observe before boot: %w", err) } @@ -641,7 +695,7 @@ func (p *Provider) powerOff(ctx context.Context, sys System) error { if !requested { // A slow or lost ForceOff response is observed, not trusted: // power-off before this phase's boot is idempotent. - if err := p.client.Reset(ctx, sys, "ForceOff"); errors.Is(err, ErrUnauthorized) || errors.Is(err, ErrUnsupported) { + if err := p.bmc(r).Reset(ctx, sys, "ForceOff"); errors.Is(err, ErrUnauthorized) || errors.Is(err, ErrUnsupported) { return fmt.Errorf("power off: %w", err) } requested = true @@ -670,7 +724,7 @@ func (p *Provider) requestPowerOn(ctx context.Context, j *journal, r *record, ph if err := p.save(*j); err != nil { return err } - if err := p.client.Reset(ctx, *r.System, "On"); err != nil { + if err := p.bmc(r).Reset(ctx, *r.System, "On"); err != nil { return fmt.Errorf("power on (%s) response: %w", ph.name, err) } return nil @@ -683,7 +737,7 @@ func (p *Provider) requestPowerOn(ctx context.Context, j *journal, r *record, ph // On, within a small retained budget. func (p *Provider) started(ctx context.Context, j *journal, r *record, ph phase) (bool, error) { _, settle, _, _ := p.durations() - pw, err := p.client.Observe(ctx, *r.System) + pw, err := p.bmc(r).Observe(ctx, *r.System) if err != nil { if errors.Is(err, ErrIdentity) { return false, err @@ -710,7 +764,7 @@ func (p *Provider) complete(ctx context.Context, r *record, ph phase) error { poll, _, offGrace, outage := p.durations() var offSince, failingSince time.Time for { - pw, err := p.client.Observe(ctx, *r.System) + pw, err := p.bmc(r).Observe(ctx, *r.System) switch { case errors.Is(err, ErrIdentity): return err diff --git a/internal/redfish/provider_test.go b/internal/redfish/provider_test.go index c19dad39..2d2f643f 100644 --- a/internal/redfish/provider_test.go +++ b/internal/redfish/provider_test.go @@ -224,6 +224,13 @@ type fixture struct { } func newFixture(t *testing.T, timeout time.Duration) *fixture { + t.Helper() + return newDHCPFixture(t, timeout, DHCPStatic) +} + +// newDHCPFixture builds the fixture with the given site DHCP mode. Synced +// targets carry documentation-range provisioning attachments. +func newDHCPFixture(t *testing.T, timeout time.Duration, dhcp string) *fixture { t.Helper() dir := t.TempDir() for _, d := range []string{"journal", "boot", "console", "artifacts"} { @@ -248,9 +255,15 @@ func newFixture(t *testing.T, timeout time.Duration) *fixture { "System-2": {id: "System-2", uuid: uuidB, mac: "52:54:00:77:01:0b", console: filepath.Join(dir, "console/target-b.log"), power: "Off", enabled: "Disabled", target: "None"}}} rf := httptest.NewServer(bmc.handler()) t.Cleanup(rf.Close) - enrollment, err := ParseEnrollment([]byte(fmt.Sprintf(`{"endpoint":%q,"targets":[ - {"assetID":%q,"systemID":"System-1","systemUUID":%q,"mac":"52:54:00:77:01:0a","diskBytes":2147483648,"console":"target-a.log"}, - {"assetID":%q,"systemID":"System-2","systemUUID":%q,"mac":"52:54:00:77:01:0b","diskBytes":2147483648,"console":"target-b.log"}]}`, rf.URL, assetA, uuidA, assetB, uuidB))) + provA, provB := "", "" + if dhcp == DHCPSynced { + provA = `,"provisioning":{"address":"192.0.2.10/24","gateway":"192.0.2.1"}` + provB = `,"provisioning":{"address":"192.0.2.11/24","gateway":"192.0.2.1"}` + } + enrollment, err := ParseEnrollment([]byte(fmt.Sprintf(`{"dhcp":%q,"targets":[ + {"assetID":%q,"endpoint":%q,"systemID":"System-1","systemUUID":%q,"mac":"52:54:00:77:01:0a"%s,"diskBytes":2147483648,"console":"target-a.log"}, + {"assetID":%q,"endpoint":%q,"systemID":"System-2","systemUUID":%q,"mac":"52:54:00:77:01:0b"%s,"diskBytes":2147483648,"console":"target-b.log"}]}`, + dhcp, assetA, rf.URL, uuidA, provA, assetB, rf.URL, uuidB, provB))) if err != nil { t.Fatal(err) } @@ -259,7 +272,7 @@ func newFixture(t *testing.T, timeout time.Duration) *fixture { t.Fatal(err) } p := &Provider{root: filepath.Join(dir, "journal"), bootRoot: filepath.Join(dir, "boot"), consoleRoot: filepath.Join(dir, "console"), artifacts: filepath.Join(dir, "artifacts"), - image: image, enrollment: enrollment, client: client, poll: 5 * time.Millisecond, settle: 150 * time.Millisecond, offGrace: 300 * time.Millisecond, outage: time.Second} + image: image, enrollment: enrollment, clients: map[string]*Client{enrollment.Targets[0].Endpoint: client}, poll: 5 * time.Millisecond, settle: 150 * time.Millisecond, offGrace: 300 * time.Millisecond, outage: time.Second} boot := httptest.NewServer(p.BootHandler()) t.Cleanup(boot.Close) p.origin, bmc.boot = boot.URL, boot.URL @@ -510,7 +523,7 @@ func TestEnrollmentIsRetainedOnceWithoutContendingForTheJournalLock(t *testing.T } } changed := *f.p - changed.enrollment = Enrollment{Endpoint: f.p.enrollment.Endpoint, Targets: f.p.enrollment.Targets[:1]} + changed.enrollment = Enrollment{DHCP: f.p.enrollment.DHCP, Targets: f.p.enrollment.Targets[:1]} if err := changed.retainEnrollment(); err == nil { t.Fatal("a changed enrollment was accepted for the retained journal") } From f4da0862b290607d8050e5088eb0b893ace8a66b Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Thu, 19 Nov 2026 15:05:51 -0600 Subject: [PATCH 012/518] feat(inventory): add operator-written DeviceClaim and Device Add a minimal subset of the proposed physical inventory API in fleet.datumapis.com/v1alpha1. A DeviceClaim is the plan for one rack slot: facility, rack, position and face, expected model, and expected ports with their expected cable peers. A Device is the actual asset, bound to exactly one claim when an operator registers detected hardware. It records serial, SMBIOS system UUID, model, optional BMC endpoint, interfaces, and Manual provenance. Both kinds are operator-written and have no controller. Registration authorizes no hardware effect and creates or changes no MachineCapacity. Status is a reserved subresource with no fields and no writer. CEL keeps the records attributable and their identities stable: - every edit must advance provenance.recordedAt - a Device's claimRef and identity are immutable, so a hardware swap is a new Device bound to the same claim - names are unique, MACs are lowercase and recorded once, and BMC endpoints are https without credentials config/inventory packages only the CRDs as an opt-in root. Trust, enrollment, reservations, and the Facility, Rack, and Cable kinds stay deferred to the inventory proposal. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 1 + config/README.md | 5 + config/inventory/fleet.datumapis.com.yaml | 178 ++++++++++ config/inventory/kustomization.yaml | 4 + docs/architecture/README.md | 2 +- docs/development/README.md | 16 +- docs/operations/README.md | 1 + docs/operations/physical-inventory.md | 174 ++++++++++ internal/api/inventory/v1alpha1/crd_test.go | 357 ++++++++++++++++++++ internal/api/inventory/v1alpha1/types.go | 179 ++++++++++ 10 files changed, 915 insertions(+), 2 deletions(-) create mode 100644 config/inventory/fleet.datumapis.com.yaml create mode 100644 config/inventory/kustomization.yaml create mode 100644 docs/operations/physical-inventory.md create mode 100644 internal/api/inventory/v1alpha1/crd_test.go create mode 100644 internal/api/inventory/v1alpha1/types.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8cff52de..27b179fb 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -26,6 +26,7 @@ jobs: - run: kustomize build config/milo >/dev/null - run: kustomize build config/overlays/management-plane >/dev/null - run: kustomize build config/overlays/synthetic-staging >/dev/null + - run: kustomize build config/inventory >/dev/null - run: ./hack/validate-synthetic-staging-render.sh - run: ./hack/validate-overlay-isolation.sh - run: ./hack/test-overlay-isolation.sh diff --git a/config/README.md b/config/README.md index c9f6f9c7..856b91fb 100644 --- a/config/README.md +++ b/config/README.md @@ -27,6 +27,11 @@ contracts charge, as billing ServicePricings for `metal.datumapis.com`. Staging' on `config/milo`; production doesn't, so production has no Bare Metal prices. A price change is a new `-v2` pricing, since a ServicePricing can't be changed. +`config/inventory` is an opt-in root for the Fleet management cluster. It holds +only the CRDs for the operator-written `DeviceClaim` and `Device` subset of the +physical inventory API. Neither production root references it. See +[Planning and registering physical devices](../docs/operations/physical-inventory.md). + `config/standalone` remains a synthetic, same-cluster test environment. It must not be referenced by either production root. diff --git a/config/inventory/fleet.datumapis.com.yaml b/config/inventory/fleet.datumapis.com.yaml new file mode 100644 index 00000000..3033e41c --- /dev/null +++ b/config/inventory/fleet.datumapis.com.yaml @@ -0,0 +1,178 @@ +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: deviceclaims.fleet.datumapis.com +spec: + group: fleet.datumapis.com + names: {kind: DeviceClaim, listKind: DeviceClaimList, plural: deviceclaims, singular: deviceclaim} + scope: Namespaced + versions: + - name: v1alpha1 + served: true + storage: true + subresources: {status: {}} + additionalPrinterColumns: + - {name: Facility, type: string, jsonPath: .spec.placement.facility} + - {name: Rack, type: string, jsonPath: .spec.placement.rack} + - {name: Position, type: integer, jsonPath: .spec.placement.position} + - {name: Model, type: string, jsonPath: .spec.expectedIdentity.model} + - {name: Recorded At, type: date, jsonPath: .spec.provenance.recordedAt} + schema: + openAPIV3Schema: + type: object + required: [spec] + properties: + apiVersion: {type: string} + kind: {type: string} + metadata: {type: object} + spec: + type: object + required: [provenance, expectedIdentity, placement] + x-kubernetes-validations: + - rule: self == oldSelf || self.provenance.recordedAt > oldSelf.provenance.recordedAt + message: every change to a claim must advance provenance.recordedAt + properties: + provenance: + type: object + required: [method, recordedBy, recordedAt] + properties: + method: {type: string, enum: [Manual]} + recordedBy: {type: string, minLength: 1, maxLength: 253} + recordedAt: {type: string, format: date-time} + reference: {type: string, minLength: 1, maxLength: 1024} + expectedIdentity: + type: object + required: [model] + properties: + manufacturer: {type: string, maxLength: 253} + model: {type: string, minLength: 1, maxLength: 253} + serial: {type: string, minLength: 1, maxLength: 253} + placement: + type: object + required: [facility, rack, position, face] + properties: + facility: {type: string, minLength: 1, maxLength: 253} + rack: {type: string, minLength: 1, maxLength: 253} + position: {type: integer, format: int32, minimum: 1, maximum: 100} + height: {type: integer, format: int32, minimum: 1, maximum: 100, default: 1} + face: {type: string, enum: [front, rear]} + ports: + type: array + maxItems: 128 + x-kubernetes-list-type: map + x-kubernetes-list-map-keys: [name] + items: + type: object + required: [name] + properties: + name: {type: string, minLength: 1, maxLength: 63} + type: {type: string, maxLength: 253} + speedMbps: {type: integer, format: int64, minimum: 1} + expectedPeer: + type: object + required: [device, port] + properties: + device: {type: string, minLength: 1, maxLength: 253} + port: {type: string, minLength: 1, maxLength: 253} + status: {type: object} +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: devices.fleet.datumapis.com +spec: + group: fleet.datumapis.com + names: {kind: Device, listKind: DeviceList, plural: devices, singular: device} + scope: Namespaced + versions: + - name: v1alpha1 + served: true + storage: true + subresources: {status: {}} + additionalPrinterColumns: + - {name: Claim, type: string, jsonPath: .spec.claimRef.name} + - {name: Model, type: string, jsonPath: .spec.identity.model} + - {name: Serial, type: string, jsonPath: .spec.identity.serial} + - {name: System UUID, type: string, priority: 1, jsonPath: .spec.identity.systemUUID} + - {name: Recorded At, type: date, jsonPath: .spec.provenance.recordedAt} + schema: + openAPIV3Schema: + type: object + required: [spec] + properties: + apiVersion: {type: string} + kind: {type: string} + metadata: {type: object} + spec: + type: object + required: [claimRef, provenance, identity] + x-kubernetes-validations: + - rule: self == oldSelf || self.provenance.recordedAt > oldSelf.provenance.recordedAt + message: every change to a device must advance provenance.recordedAt + - rule: self.claimRef == oldSelf.claimRef + message: claimRef is immutable; bind replacement hardware as a new Device + - rule: self.identity == oldSelf.identity + message: identity is immutable; a hardware swap is a new Device + - rule: >- + !has(self.interfaces) || self.interfaces.all(a, !has(a.macAddress) || + (self.interfaces.filter(b, has(b.macAddress) && b.macAddress == a.macAddress).size() == 1 && + (!has(self.unmappedMACAddresses) || !(a.macAddress in self.unmappedMACAddresses)))) + message: a MAC address may be recorded only once + properties: + claimRef: + type: object + required: [name] + properties: + name: {type: string, minLength: 1, maxLength: 253} + provenance: + type: object + required: [method, recordedBy, recordedAt] + properties: + method: {type: string, enum: [Manual]} + recordedBy: {type: string, minLength: 1, maxLength: 253} + recordedAt: {type: string, format: date-time} + reference: {type: string, minLength: 1, maxLength: 1024} + identity: + type: object + required: [model] + x-kubernetes-validations: + - rule: has(self.serial) || has(self.systemUUID) + message: a device needs a serial or a system UUID + properties: + manufacturer: {type: string, maxLength: 253} + model: {type: string, minLength: 1, maxLength: 253} + serial: {type: string, minLength: 1, maxLength: 253} + systemUUID: {type: string, pattern: '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$'} + bmc: + type: object + required: [endpoint] + properties: + endpoint: + type: string + maxLength: 2048 + x-kubernetes-validations: + - rule: isURL(self) && url(self).getScheme() == 'https' && !self.contains('@') && url(self).getHostname() != '' + message: bmc.endpoint must be an https URL without credentials + interfaces: + type: array + maxItems: 32 + x-kubernetes-list-type: map + x-kubernetes-list-map-keys: [name] + items: + type: object + required: [name] + properties: + name: {type: string, minLength: 1, maxLength: 63} + macAddress: {type: string, maxLength: 17, pattern: '^([0-9a-f]{2}:){5}[0-9a-f]{2}$'} + peer: + type: object + required: [device, port] + properties: + device: {type: string, minLength: 1, maxLength: 253} + port: {type: string, minLength: 1, maxLength: 253} + unmappedMACAddresses: + type: array + maxItems: 32 + x-kubernetes-list-type: set + items: {type: string, maxLength: 17, pattern: '^([0-9a-f]{2}:){5}[0-9a-f]{2}$'} + status: {type: object} diff --git a/config/inventory/kustomization.yaml b/config/inventory/kustomization.yaml new file mode 100644 index 00000000..9ce565ec --- /dev/null +++ b/config/inventory/kustomization.yaml @@ -0,0 +1,4 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - fleet.datumapis.com.yaml diff --git a/docs/architecture/README.md b/docs/architecture/README.md index 4d305dfe..57c04fa4 100644 --- a/docs/architecture/README.md +++ b/docs/architecture/README.md @@ -59,7 +59,7 @@ processes or service-catalog entries. | --- | --- | --- | | `metal.datumapis.com` | `MachineClass`: offerings and consumer references. `MachineProfile`: hardware requirements. `MachineCapacity`: provider supply. `Machine`: customer allocation and runtime intent. `MachineAllocation`: protected allocation identity. `Installation`: immutable OS installation or reinstall request. | Six alpha CRDs at `v1alpha1`. Production admission and real providers remain incomplete. | | `provider.metal.datumapis.com` | Proposed `MachineOffering` owns installation/management capability policy; `MachineOfferingAssignment` controls acquisition access. MachineClass becomes only a one-hop published consumer view; MachineProfile remains immutable requirements in Metal. | Proposed target design, not implemented by the six alpha CRDs above. | -| `fleet.datumapis.com` | Physical inventory: `Facility`, `Rack`, `DeviceClaim`, `Device`, `Cable`, and `PowerFeed`. Physical preparation and provider execution remain operator responsibilities. | Proposed inventory APIs; no physical inventory CRDs or real provider executor are implemented here. | +| `fleet.datumapis.com` | Physical inventory: `Facility`, `Rack`, `DeviceClaim`, `Device`, `Cable`, and `PowerFeed`. Physical preparation and provider execution remain operator responsibilities. | Proposed inventory APIs. Only a minimal, operator-written subset of `DeviceClaim` and `Device` is implemented, as alpha CRDs in the opt-in [inventory root](../operations/physical-inventory.md), outside the production roots; no controller reads them. No real provider executor is implemented here. | | `coordination.fleet.datumapis.com` | Intended management-to-location execution handoff, retaining exact allocation identity, location, admitted inputs, release intent, and execution evidence. `MachineAllocationHandoff` is a candidate resource. | Architecture decision only on the current main implementation: no coordination CRD or cell controller is packaged. Replaces the earlier prototype name `internal.fleet.datumapis.com`. | MachineCapacity and MachineAllocation belong to the Metal allocation contract diff --git a/docs/development/README.md b/docs/development/README.md index 84865a75..b545c99b 100644 --- a/docs/development/README.md +++ b/docs/development/README.md @@ -45,7 +45,8 @@ Milo IAM, service, and quota boundaries; packaging is not runtime readiness. The allocation APIs now use `metal.datumapis.com/v1alpha1`. Milo registers the Bare Metal service as `metal`; entitlement and location-availability readers use -that reference. Physical Device references use `fleet.datumapis.com`. The +that reference. Physical Device references use `fleet.datumapis.com`; that group +implements only a minimal, operator-written `DeviceClaim` and `Device` today. The [API architecture](../architecture/README.md) documents the proposed coordination group, control-plane placement, and rollout constraints. Group renaming does not migrate stored allocations or establish live acceptance. @@ -701,6 +702,19 @@ The persisted schema and HTTP endpoints are internal alpha interfaces. No compatibility promise exists yet. The process fails closed if retained state is corrupt or uses an unsupported schema version. +## Physical inventory subset + +`internal/api/inventory/v1alpha1` defines `DeviceClaim`, the plan for one rack +slot, and `Device`, the asset bound to one claim. Operators write both by hand. +`config/inventory` packages only their CRDs. CEL requires `Manual` provenance on +both and requires every edit to advance `recordedAt`. It keeps a Device's +`claimRef` and identity immutable, rejects duplicate or ambiguous MACs, and +accepts only credential-free `https` BMC endpoints. Status is a reserved +subresource with no fields and no writer. No production root includes the +package, and nothing reads it. Unit tests run the API server's schema, +list-type, defaulting, and CEL validation offline. See +[Planning and registering physical devices](../operations/physical-inventory.md). + ## Build, test, and run Run the implemented checks from the repository root: diff --git a/docs/operations/README.md b/docs/operations/README.md index 9426bad4..d4606067 100644 --- a/docs/operations/README.md +++ b/docs/operations/README.md @@ -17,6 +17,7 @@ integrations. Real provider support and live Milo acceptance tests are incomplet | Exercise Milo, Karmada and cell-local PXE end to end with one command | [Multi-plane acceptance](multiplane.md) (`task multiplane:acceptance`) | Native project routing, 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, cleanup and reuse; 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 executor discovery, one-time PXE/disk boot overrides, power, lost-response recovery and a booted wipe cleanup, against the unmodified DMTF Redfish Interface Emulator with a lab-only libvirt adapter and two persistent lab VMs; synthetic credentials and networking; not physical BMC or hardware qualification | | Publish physical-side DHCP reservations for network boot | [Boot network](boot-network.md) | Per-asset BMC endpoints and provisioning attachments, a reservation feed 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 with attributable provenance and immutable identity and binding; no capacity or hardware effect; unit tested | | Render deployment bundles and supply environment inputs | [Deployment manifests](../../config/README.md) | Packaging and security boundaries, not runtime readiness | | Run the manager across consuming projects | [Project discovery](../../config/README.md#project-discovery) | Discovery, per-project isolation, departure, role bindings, and readiness | | Exercise Milo-routed synthetic staging | [Synthetic staging configuration](../../config/README.md#environment-owned-inputs) | Restricted synthetic publication and lifecycle behavior, not production authority | diff --git a/docs/operations/physical-inventory.md b/docs/operations/physical-inventory.md new file mode 100644 index 00000000..ddfdfe83 --- /dev/null +++ b/docs/operations/physical-inventory.md @@ -0,0 +1,174 @@ +# Planning and registering physical devices + +[Operations guide](README.md) · [Architecture](../architecture/README.md) · +[Implementation status](../development/README.md) + +Before Fleet can enroll or offer real hardware, operators need to record two +things: where a server is meant to go, and which physical server is actually +there. Recording either must not provision the server, publish capacity, or +take ownership of it. + +This package implements a minimal subset of the +[inventory lifecycle and trust proposal (#63)](https://github.com/datum-cloud/fleet/pull/63). +It has two operator-written kinds in `fleet.datumapis.com/v1alpha1`: + +| Kind | What it is | Writer | +| --- | --- | --- | +| `DeviceClaim` | The installation plan for one slot: facility, rack, position and face, expected model, and expected ports with their expected cable peers. It is usually written before the hardware arrives, and the slot outlives any one Device. | The installation planner (an operator, for now) | +| `Device` | One actual asset, bound to exactly one DeviceClaim when detected hardware is registered. It carries the serial and SMBIOS system UUID, the model, an optional BMC endpoint, interfaces, and provenance. | The registrar (an operator, for now) | + +## Status + +| Aspect | State | +| --- | --- | +| CRDs and Go types | Implemented in `config/inventory` and `internal/api/inventory/v1alpha1`. | +| Tests | Unit tests run the API server's schema, list-type, defaulting, and CEL validation offline, for both kinds. | +| Production roots | Not included. `config/milo`, `config/overlays/management-plane`, and `config/overlays/synthetic-staging` do not reference it. An environment opts in by applying `config/inventory`. | +| Controllers | None. No Fleet code reads or writes these kinds. | +| Hardware qualification | None. Records hold operator-entered facts, not verified hardware state. | + +## What registration does and does not do + +Creating a Device is the explicit, manual binding step. It records that the +registrar saw this hardware in this planned slot. It does not: + +- authorize power, boot, wipe, BMC credential, or network changes; +- create, change, or enable any `MachineCapacity`, or make anything + allocatable; or +- verify identity, placement, cabling, or power. + +Detection is manual too. The registrar records what the BMC (for example +Redfish) and the rack showed them. MachineCapacity is unchanged by this +package. Its `spec.deviceRef` already names a Device by name, and the +allocator forms the asset key +`/fleet.datumapis.com/Device/`. Device names are +Kubernetes object names in the same group and kind, so a later supply step can +reference a Device without renaming it. That step must place the Device and its +MachineCapacity in the same namespace. + +## Writers and validation + +| Rule | Kind | Why | +| --- | --- | --- | +| `provenance` is required: `method: Manual`, `recordedBy`, `recordedAt`, and an optional opaque `reference` | Both | Every plan and registration is attributable to a person and a time. | +| Any spec change must set a later `provenance.recordedAt` | Both | An edit cannot pass off new facts under old provenance. | +| `claimRef` is required and immutable | Device | A Device binds to exactly one claim, and moving hardware to another slot is not an edit. | +| `identity` (manufacturer, model, serial, system UUID) is immutable, including adding a missing field; at least one of serial or system UUID is required | Device | Serial and UUID are matching evidence. A hardware swap is a new Device bound to the same claim. | +| Serial is optional | DeviceClaim | It is usually unknown at plan time. | +| Port and interface names are unique; MACs are lowercase and colon-separated, appear at most once per Device, and are either mapped to an interface or listed in `unmappedMACAddresses`, not both | Both | Malformed or ambiguous facts are rejected. | +| The system UUID is in lowercase canonical form | Device | One spelling per identity. | +| `bmc.endpoint` is an `https` URL without credentials | Device | Credentials never live in inventory records. | +| `status` is a separate subresource that declares no fields | Both | Reserved for future collectors and verifiers to report drift and mismatch. Status never carries identity, and nothing writes it yet. | + +The CRDs cannot check that `claimRef` names an existing DeviceClaim, because +CEL cannot read other objects. Until a registrar enforces it, the operator +creates the claim first. + +Use `unmappedMACAddresses` for MACs detected on the asset that cannot yet be +attributed to a named port. Do not guess a mapping; #63 requires an +authenticated, complete NIC mapping before any network path depends on it. + +## Example + +```yaml +apiVersion: fleet.datumapis.com/v1alpha1 +kind: DeviceClaim +metadata: + name: rack-01-u12 + namespace: fleet-system +spec: + provenance: + method: Manual + recordedBy: planner@example.com + recordedAt: "2026-01-02T03:04:05Z" + reference: rack plan 1234 + expectedIdentity: + manufacturer: Example Vendor + model: Example 1U + placement: + facility: example-facility + rack: rack-01 + position: 12 + face: front + ports: + - name: eth0 + type: 25gbase-x-sfp28 + speedMbps: 25000 + expectedPeer: {device: switch-01, port: Ethernet1/1} + - name: bmc0 + type: 1000base-t + speedMbps: 1000 + expectedPeer: {device: mgmt-switch-01, port: Ethernet5} +--- +apiVersion: fleet.datumapis.com/v1alpha1 +kind: Device +metadata: + name: rack-01-u12-synthetic-0001 + namespace: fleet-system +spec: + claimRef: + name: rack-01-u12 + provenance: + method: Manual + recordedBy: registrar@example.com + recordedAt: "2026-01-09T10:00:00Z" + reference: BMC inventory read during rack turn-up + identity: + manufacturer: Example Vendor + model: Example 1U + serial: SYNTHETIC-0001 + systemUUID: 00000000-0000-4000-8000-000000000001 + bmc: + endpoint: https://192.0.2.100:443 + unmappedMACAddresses: + - 00:00:5e:00:53:01 + - 00:00:5e:00:53:02 +``` + +To replace the hardware, create a new Device with its own name and identity +that names the same claim. Leave the old Device in place until its retirement +is settled. This package does not model retirement. + +## Relationship to the inventory proposal + +The names and writers match #63: + +- DeviceClaim is a physical installation plan written by the installation + planner. +- Device is the canonical asset created only by the registrar. +- Collectors submit observations and never edit Device identity. +- Status is a protected projection. +- Serial and SMBIOS UUID are matching evidence, not authenticators. +- Logical LAGs and VLANs are not ports. + +Deferred to #63, and deliberately absent: + +- `Facility`, `Rack`, `Cable`, and `PowerFeed` kinds. Facility and rack are + names on the claim, and the expected cable peer is inline on each claimed + port, until those kinds replace them. Rack geometry beyond position, height, + and face is also deferred. +- Plan acceptance, revisions, and reservations; canonical-identity + adjudication and duplicate detection; and the protected ledger. +- Trust roots, qualification profiles, enrollment challenges, technician and + collector attestation, and evidence freshness. +- Component incarnations and lineage, maintenance, moves, retirement, and + adopted custody. +- The `Accepted`, `Bound`, `IdentityVerified`, `PlacementVerified`, + `NetworkPathVerified`, and `PowerPathVerified` predicates and any eligibility + publication. +- Separation of planner, approver, registrar, and verifier roles. One operator + can write both kinds today. + +**Divergence to resolve:** this package's convention is that a whole-server +replacement binds a new Device to the same DeviceClaim, because the planned slot +outlives the hardware. #63's current text says whole-server replacement creates a +new DeviceClaim as well. The schema enforces neither convention. Settle this in +#63 before either path is automated. + +## Applying the root + +`config/inventory` contains only the two cluster-scoped CRDs. It needs no +credentials or workload. Apply claims and Devices after the CRDs are +established, claims before the Devices that name them. Keep records with real +serials, UUIDs, MACs, endpoints, or cabling in the environment's private +configuration, not in this repository. diff --git a/internal/api/inventory/v1alpha1/crd_test.go b/internal/api/inventory/v1alpha1/crd_test.go new file mode 100644 index 00000000..21150ef1 --- /dev/null +++ b/internal/api/inventory/v1alpha1/crd_test.go @@ -0,0 +1,357 @@ +package v1alpha1 + +import ( + "bytes" + "context" + "encoding/json" + "io" + "os" + "path/filepath" + "testing" + "time" + + "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions" + extensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + crdvalidation "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation" + structuralschema "k8s.io/apiextensions-apiserver/pkg/apiserver/schema" + "k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel" + structuraldefaulting "k8s.io/apiextensions-apiserver/pkg/apiserver/schema/defaulting" + "k8s.io/apiextensions-apiserver/pkg/apiserver/schema/listtype" + "k8s.io/apiextensions-apiserver/pkg/apiserver/validation" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + utiljson "k8s.io/apimachinery/pkg/util/json" + "k8s.io/apimachinery/pkg/util/validation/field" + "k8s.io/apimachinery/pkg/util/yaml" + celconfig "k8s.io/apiserver/pkg/apis/cel" +) + +var inventoryRoot = filepath.Join("..", "..", "..", "..", "config", "inventory") + +func loadCRDs(t *testing.T) map[string]*extensionsv1.CustomResourceDefinition { + t.Helper() + data, err := os.ReadFile(filepath.Join(inventoryRoot, "fleet.datumapis.com.yaml")) + if err != nil { + t.Fatal(err) + } + decoder := yaml.NewYAMLOrJSONDecoder(bytes.NewReader(data), 4096) + out := map[string]*extensionsv1.CustomResourceDefinition{} + for { + var crd extensionsv1.CustomResourceDefinition + if err := decoder.Decode(&crd); err == io.EOF { + return out + } else if err != nil { + t.Fatal(err) + } + if crd.Name != "" { + copied := crd + out[crd.Spec.Names.Kind] = &copied + } + } +} + +func TestInventoryCRDContract(t *testing.T) { + crds := loadCRDs(t) + if len(crds) != 2 || crds["DeviceClaim"] == nil || crds["Device"] == nil { + t.Fatalf("got CRDs %v, want exactly DeviceClaim and Device", crds) + } + for kind, crd := range crds { + if crd.Spec.Group != GroupVersion.Group || crd.Name != crd.Spec.Names.Plural+"."+GroupVersion.Group || crd.Spec.Scope != extensionsv1.NamespaceScoped { + t.Fatalf("%s identity = %s %s", kind, crd.Name, crd.Spec.Scope) + } + version := crd.Spec.Versions[0] + if len(crd.Spec.Versions) != 1 || version.Name != GroupVersion.Version || !version.Served || !version.Storage { + t.Fatalf("%s must serve and store exactly v1alpha1", kind) + } + if version.Subresources == nil || version.Subresources.Status == nil { + t.Fatalf("%s must reserve status as a separate subresource", kind) + } + if status := version.Schema.OpenAPIV3Schema.Properties["status"]; len(status.Properties) != 0 || status.XPreserveUnknownFields != nil { + t.Fatalf("%s status must stay empty until a collector or verifier owns it", kind) + } + if _, ok := crd.Annotations["discovery.miloapis.com/parent-contexts"]; ok { + t.Fatalf("%s must not be exposed through Milo project discovery", kind) + } + defaulted := crd.DeepCopy() + extensionsv1.SetObjectDefaults_CustomResourceDefinition(defaulted) + defaulted.Status.StoredVersions = []string{GroupVersion.Version} + var internal apiextensions.CustomResourceDefinition + if err := extensionsv1.Convert_v1_CustomResourceDefinition_To_apiextensions_CustomResourceDefinition(defaulted, &internal, nil); err != nil { + t.Fatal(err) + } + if errs := crdvalidation.ValidateCustomResourceDefinition(context.Background(), &internal); len(errs) > 0 { + t.Fatalf("%s: %v", kind, errs.ToAggregate()) + } + } +} + +// admit applies schema defaults to both objects, as stored objects already +// carry them, then the OpenAPI, list-type, and CEL +// validation the API server runs on create (old == nil) or update. Objects are +// decoded with integer-preserving JSON, as the API server decodes them. +func admit(t *testing.T, kind string, object, old map[string]any) field.ErrorList { + t.Helper() + var schema apiextensions.JSONSchemaProps + if err := extensionsv1.Convert_v1_JSONSchemaProps_To_apiextensions_JSONSchemaProps(loadCRDs(t)[kind].Spec.Versions[0].Schema.OpenAPIV3Schema, &schema, nil); err != nil { + t.Fatal(err) + } + structural, err := structuralschema.NewStructural(&schema) + if err != nil { + t.Fatal(err) + } + structuraldefaulting.Default(object, structural) + validator, _, err := validation.NewSchemaValidator(&schema) + if err != nil { + t.Fatal(err) + } + errs := validation.ValidateCustomResource(nil, object, validator) + errs = append(errs, listtype.ValidateListSetsAndMaps(nil, structural, object)...) + var oldObject any + if old != nil { + structuraldefaulting.Default(old, structural) + oldObject = old + } + celErrs, _ := cel.NewValidator(structural, true, celconfig.PerCallLimit).Validate(context.Background(), nil, structural, object, oldObject, celconfig.RuntimeCELCostBudget) + return append(errs, celErrs...) +} + +func object(t *testing.T, value any) map[string]any { + t.Helper() + data, err := json.Marshal(value) + if err != nil { + t.Fatal(err) + } + var out map[string]any + if err := utiljson.Unmarshal(data, &out); err != nil { + t.Fatal(err) + } + return out +} + +var recordedAt = time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC) + +func provenance(at time.Time) Provenance { + return Provenance{Method: ProvenanceManual, RecordedBy: "operator@example.com", RecordedAt: metav1.NewTime(at), Reference: "rack plan 1234"} +} + +func syntheticClaim() DeviceClaim { + return DeviceClaim{ + TypeMeta: metav1.TypeMeta{APIVersion: GroupVersion.String(), Kind: "DeviceClaim"}, + ObjectMeta: metav1.ObjectMeta{Name: "rack-01-u12", Namespace: "fleet-system"}, + Spec: DeviceClaimSpec{ + Provenance: provenance(recordedAt), + ExpectedIdentity: ExpectedIdentity{Manufacturer: "Example Vendor", Model: "Example 1U"}, + Placement: Placement{Facility: "example-facility", Rack: "rack-01", Position: 12, Face: "front"}, + Ports: []ExpectedPort{ + {Name: "eth0", Type: "25gbase-x-sfp28", SpeedMbps: 25000, ExpectedPeer: &PortPeer{Device: "switch-01", Port: "Ethernet1/1"}}, + {Name: "bmc0", Type: "1000base-t", SpeedMbps: 1000, ExpectedPeer: &PortPeer{Device: "mgmt-switch-01", Port: "Ethernet5"}}, + }, + }, + } +} + +func syntheticDevice() Device { + return Device{ + TypeMeta: metav1.TypeMeta{APIVersion: GroupVersion.String(), Kind: "Device"}, + ObjectMeta: metav1.ObjectMeta{Name: "rack-01-u12-synthetic-0001", Namespace: "fleet-system"}, + Spec: DeviceSpec{ + ClaimRef: LocalReference{Name: "rack-01-u12"}, + Provenance: provenance(recordedAt), + Identity: DeviceIdentity{Manufacturer: "Example Vendor", Model: "Example 1U", Serial: "SYNTHETIC-0001", SystemUUID: "00000000-0000-4000-8000-000000000001"}, + BMC: &BMC{Endpoint: "https://192.0.2.100:443"}, + Interfaces: []Interface{ + {Name: "eth0", MACAddress: "00:00:5e:00:53:01", Peer: &PortPeer{Device: "switch-01", Port: "Ethernet1/1"}}, + {Name: "bmc0", MACAddress: "00:00:5e:00:53:02"}, + }, + UnmappedMACAddresses: []string{"00:00:5e:00:53:03"}, + }, + } +} + +func later(d time.Duration) metav1.Time { return metav1.NewTime(recordedAt.Add(d)) } + +func TestValidRecordsAreAccepted(t *testing.T) { + if errs := admit(t, "DeviceClaim", object(t, syntheticClaim()), nil); len(errs) > 0 { + t.Fatalf("claim rejected: %v", errs) + } + if errs := admit(t, "Device", object(t, syntheticDevice()), nil); len(errs) > 0 { + t.Fatalf("device rejected: %v", errs) + } + minimal := syntheticDevice() + minimal.Spec.Identity.Serial = "" + minimal.Spec.BMC, minimal.Spec.Interfaces = nil, nil + if errs := admit(t, "Device", object(t, minimal), nil); len(errs) > 0 { + t.Fatalf("device with only a system UUID rejected: %v", errs) + } +} + +func TestClaimDoesNotRequireSerialAndDefaultsHeight(t *testing.T) { + claim := object(t, syntheticClaim()) + if errs := admit(t, "DeviceClaim", claim, nil); len(errs) > 0 { + t.Fatal(errs) + } + if height := claim["spec"].(map[string]any)["placement"].(map[string]any)["height"]; height != int64(1) { + t.Fatalf("height defaulted to %v", height) + } +} + +func TestInvalidClaimsAreRejected(t *testing.T) { + for name, mutate := range map[string]func(*DeviceClaim){ + "unknown method": func(c *DeviceClaim) { c.Spec.Provenance.Method = "Discovered" }, + "missing recorder": func(c *DeviceClaim) { c.Spec.Provenance.RecordedBy = "" }, + "missing model": func(c *DeviceClaim) { c.Spec.ExpectedIdentity.Model = "" }, + "missing facility": func(c *DeviceClaim) { c.Spec.Placement.Facility = "" }, + "zero position": func(c *DeviceClaim) { c.Spec.Placement.Position = 0 }, + "unknown face": func(c *DeviceClaim) { c.Spec.Placement.Face = "side" }, + "duplicate port": func(c *DeviceClaim) { c.Spec.Ports[1].Name = c.Spec.Ports[0].Name }, + "peer without port": func(c *DeviceClaim) { + c.Spec.Ports[0].ExpectedPeer = &PortPeer{Device: "switch-01"} + }, + } { + claim := syntheticClaim() + mutate(&claim) + if errs := admit(t, "DeviceClaim", object(t, claim), nil); len(errs) == 0 { + t.Errorf("%s accepted", name) + } + } +} + +func TestInvalidDevicesAreRejected(t *testing.T) { + for name, mutate := range map[string]func(*Device){ + "missing claim": func(d *Device) { d.Spec.ClaimRef.Name = "" }, + "no identity key": func(d *Device) { d.Spec.Identity.Serial, d.Spec.Identity.SystemUUID = "", "" }, + "uppercase system UUID": func(d *Device) { d.Spec.Identity.SystemUUID = "00000000-0000-4000-8000-00000000000A" }, + "malformed system UUID": func(d *Device) { d.Spec.Identity.SystemUUID = "not-a-uuid" }, + "uppercase MAC": func(d *Device) { d.Spec.Interfaces[0].MACAddress = "00:00:5E:00:53:01" }, + "malformed MAC": func(d *Device) { d.Spec.UnmappedMACAddresses = []string{"not-a-mac"} }, + "duplicate interface": func(d *Device) { d.Spec.Interfaces[1].Name = d.Spec.Interfaces[0].Name }, + "MAC on two interfaces": func(d *Device) { d.Spec.Interfaces[1].MACAddress = d.Spec.Interfaces[0].MACAddress }, + "MAC mapped and unmapped": func(d *Device) { + d.Spec.UnmappedMACAddresses = []string{d.Spec.Interfaces[0].MACAddress} + }, + "duplicate unmapped MAC": func(d *Device) { + d.Spec.UnmappedMACAddresses = []string{"00:00:5e:00:53:03", "00:00:5e:00:53:03"} + }, + "plain-http BMC": func(d *Device) { d.Spec.BMC.Endpoint = "http://192.0.2.100" }, + "BMC with credentials": func(d *Device) { d.Spec.BMC.Endpoint = "https://admin:secret@192.0.2.100" }, + "BMC not a URL": func(d *Device) { d.Spec.BMC.Endpoint = "192.0.2.100" }, + } { + device := syntheticDevice() + mutate(&device) + if errs := admit(t, "Device", object(t, device), nil); len(errs) == 0 { + t.Errorf("%s accepted", name) + } + } + withoutClaim := object(t, syntheticDevice()) + delete(withoutClaim["spec"].(map[string]any), "claimRef") + if errs := admit(t, "Device", withoutClaim, nil); len(errs) == 0 { + t.Error("device without a claim reference accepted") + } +} + +func TestEveryEditMustAdvanceRecordedAt(t *testing.T) { + oldClaim := object(t, syntheticClaim()) + if errs := admit(t, "DeviceClaim", object(t, syntheticClaim()), oldClaim); len(errs) > 0 { + t.Fatalf("unchanged claim update rejected: %v", errs) + } + for name, at := range map[string]metav1.Time{"same time": metav1.NewTime(recordedAt), "backdated": later(-time.Hour)} { + claim := syntheticClaim() + claim.Spec.Placement.Position = 14 + claim.Spec.Provenance.RecordedAt = at + if errs := admit(t, "DeviceClaim", object(t, claim), oldClaim); len(errs) == 0 { + t.Errorf("claim edit with %s accepted", name) + } + } + replanned := syntheticClaim() + replanned.Spec.Placement.Position = 14 + replanned.Spec.Provenance.RecordedAt = later(time.Hour) + if errs := admit(t, "DeviceClaim", object(t, replanned), oldClaim); len(errs) > 0 { + t.Fatalf("re-recorded claim edit rejected: %v", errs) + } + + oldDevice := object(t, syntheticDevice()) + stale := syntheticDevice() + stale.Spec.BMC.Endpoint = "https://192.0.2.101" + if errs := admit(t, "Device", object(t, stale), oldDevice); len(errs) == 0 { + t.Error("device edit without a newer recordedAt accepted") + } + updated := syntheticDevice() + updated.Spec.BMC.Endpoint = "https://192.0.2.101" + updated.Spec.UnmappedMACAddresses = nil + updated.Spec.Interfaces = append(updated.Spec.Interfaces, Interface{Name: "eth1", MACAddress: "00:00:5e:00:53:03"}) + updated.Spec.Provenance.RecordedAt = later(time.Hour) + if errs := admit(t, "Device", object(t, updated), oldDevice); len(errs) > 0 { + t.Fatalf("re-recorded device edit rejected: %v", errs) + } +} + +func TestClaimBindingAndIdentityAreImmutable(t *testing.T) { + old := object(t, syntheticDevice()) + for name, mutate := range map[string]func(*Device){ + "retarget claim": func(d *Device) { d.Spec.ClaimRef.Name = "rack-01-u14" }, + "change serial": func(d *Device) { d.Spec.Identity.Serial = "SYNTHETIC-0002" }, + "remove serial": func(d *Device) { d.Spec.Identity.Serial = "" }, + "change system UUID": func(d *Device) { d.Spec.Identity.SystemUUID = "00000000-0000-4000-8000-000000000002" }, + "change model": func(d *Device) { d.Spec.Identity.Model = "Example 2U" }, + } { + device := syntheticDevice() + mutate(&device) + device.Spec.Provenance.RecordedAt = later(time.Hour) + if errs := admit(t, "Device", object(t, device), old); len(errs) == 0 { + t.Errorf("%s accepted", name) + } + } + unserialed := syntheticDevice() + unserialed.Spec.Identity.Serial = "" + added := syntheticDevice() + added.Spec.Provenance.RecordedAt = later(time.Hour) + if errs := admit(t, "Device", object(t, added), object(t, unserialed)); len(errs) == 0 { + t.Error("adding a serial to a registered device accepted; a new identity needs a new Device") + } +} + +func TestReplacementBindsANewDeviceToTheSameClaim(t *testing.T) { + replacement := syntheticDevice() + replacement.Name = "rack-01-u12-synthetic-0002" + replacement.Spec.Identity.Serial = "SYNTHETIC-0002" + replacement.Spec.Identity.SystemUUID = "00000000-0000-4000-8000-000000000002" + replacement.Spec.Provenance.RecordedAt = later(24 * time.Hour) + if errs := admit(t, "Device", object(t, replacement), nil); len(errs) > 0 { + t.Fatalf("replacement device for the same claim rejected: %v", errs) + } +} + +func TestStatusAcceptsNoFieldsYet(t *testing.T) { + device := object(t, syntheticDevice()) + device["status"] = map[string]any{"identity": map[string]any{"serial": "SYNTHETIC-0009"}} + if errs := admit(t, "Device", device, nil); len(errs) > 0 { + t.Fatal(errs) + } + var schema apiextensions.JSONSchemaProps + if err := extensionsv1.Convert_v1_JSONSchemaProps_To_apiextensions_JSONSchemaProps(loadCRDs(t)["Device"].Spec.Versions[0].Schema.OpenAPIV3Schema, &schema, nil); err != nil { + t.Fatal(err) + } + structural, err := structuralschema.NewStructural(&schema) + if err != nil { + t.Fatal(err) + } + if structural.Properties["status"].Properties != nil { + t.Fatal("status declares fields") + } +} + +func TestSchemeRegistersBothKinds(t *testing.T) { + scheme := runtime.NewScheme() + if err := AddToScheme(scheme); err != nil { + t.Fatal(err) + } + claim, device := syntheticClaim(), syntheticDevice() + for _, obj := range []runtime.Object{claim.DeepCopyObject(), device.DeepCopyObject(), &DeviceClaimList{}, &DeviceList{}} { + if _, _, err := scheme.ObjectKinds(obj); err != nil { + t.Fatal(err) + } + } + if copied := device.DeepCopyObject().(*Device); copied.Spec.Identity != device.Spec.Identity || &copied.Spec.Interfaces[0] == &device.Spec.Interfaces[0] { + t.Fatal("deep copy did not copy the device") + } +} diff --git a/internal/api/inventory/v1alpha1/types.go b/internal/api/inventory/v1alpha1/types.go new file mode 100644 index 00000000..66351684 --- /dev/null +++ b/internal/api/inventory/v1alpha1/types.go @@ -0,0 +1,179 @@ +// Package v1alpha1 holds a minimal subset of the proposed physical inventory +// API in fleet.datumapis.com: DeviceClaim, the installation plan for one slot, +// and Device, the actual asset bound to a claim. +// +// Both are operator-written records. Neither has a controller. Registering a +// Device authorizes no hardware effect and creates or changes no +// MachineCapacity. Status is reserved for future collectors and verifiers and +// has no writer. +package v1alpha1 + +import ( + "encoding/json" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" +) + +var GroupVersion = schema.GroupVersion{Group: "fleet.datumapis.com", Version: "v1alpha1"} + +// ProvenanceManual marks a record an operator entered by hand. +const ProvenanceManual = "Manual" + +// Provenance says how, by whom, and when a record's spec was written. Every +// change to a spec must advance RecordedAt. +type Provenance struct { + Method string `json:"method"` + RecordedBy string `json:"recordedBy"` + RecordedAt metav1.Time `json:"recordedAt"` + // Reference is an optional, opaque pointer to where the facts came from. + // Fleet does not interpret it. + Reference string `json:"reference,omitempty"` +} + +// DeviceClaim is the plan for one physical slot, written by the installation +// planner before hardware arrives. The slot outlives any one Device. +type DeviceClaim struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + Spec DeviceClaimSpec `json:"spec"` + Status DeviceClaimStatus `json:"status,omitempty"` +} + +type DeviceClaimSpec struct { + Provenance Provenance `json:"provenance"` + ExpectedIdentity ExpectedIdentity `json:"expectedIdentity"` + Placement Placement `json:"placement"` + Ports []ExpectedPort `json:"ports,omitempty"` +} + +// ExpectedIdentity is the planned equipment. Serial is usually unknown at plan +// time and is optional. +type ExpectedIdentity struct { + Manufacturer string `json:"manufacturer,omitempty"` + Model string `json:"model"` + Serial string `json:"serial,omitempty"` +} + +// Placement is the planned mount: the lowest occupied rack unit, the number of +// units, and the face. Facility and Rack are names until those kinds exist. +type Placement struct { + Facility string `json:"facility"` + Rack string `json:"rack"` + Position int32 `json:"position"` + Height int32 `json:"height,omitempty"` + Face string `json:"face"` +} + +// ExpectedPort is a planned physical port and the cable peer it should reach. +// Logical LAGs and VLANs are not ports. +type ExpectedPort struct { + Name string `json:"name"` + Type string `json:"type,omitempty"` + SpeedMbps int64 `json:"speedMbps,omitempty"` + ExpectedPeer *PortPeer `json:"expectedPeer,omitempty"` +} + +// PortPeer names the far end of a cable by device name and port. +type PortPeer struct { + Device string `json:"device"` + Port string `json:"port"` +} + +// DeviceClaimStatus is reserved for verifiers. Nothing writes it yet. +type DeviceClaimStatus struct{} + +// Device is one actual asset, created by the registrar when detected hardware +// is bound to a claim. Its identity and claim binding are immutable: a hardware +// swap is a new Device. +type Device struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + Spec DeviceSpec `json:"spec"` + Status DeviceStatus `json:"status,omitempty"` +} + +type DeviceSpec struct { + ClaimRef LocalReference `json:"claimRef"` + Provenance Provenance `json:"provenance"` + Identity DeviceIdentity `json:"identity"` + BMC *BMC `json:"bmc,omitempty"` + Interfaces []Interface `json:"interfaces,omitempty"` + // UnmappedMACAddresses are MACs detected on the asset that the registrar + // could not attribute to a named interface. + UnmappedMACAddresses []string `json:"unmappedMACAddresses,omitempty"` +} + +type LocalReference struct { + Name string `json:"name"` +} + +// DeviceIdentity is the detected chassis identity. Serial and SystemUUID are +// matching evidence, not authenticators. At least one is required. +type DeviceIdentity struct { + Manufacturer string `json:"manufacturer,omitempty"` + Model string `json:"model"` + Serial string `json:"serial,omitempty"` + // SystemUUID is the SMBIOS system UUID in lowercase canonical form. + SystemUUID string `json:"systemUUID,omitempty"` +} + +// BMC records where the management controller was reached. Credentials never +// belong here. +type BMC struct { + Endpoint string `json:"endpoint"` +} + +type Interface struct { + Name string `json:"name"` + MACAddress string `json:"macAddress,omitempty"` + Peer *PortPeer `json:"peer,omitempty"` +} + +// DeviceStatus is reserved for collectors and verifiers to report drift and +// mismatch. It never carries identity. Nothing writes it yet. +type DeviceStatus struct{} + +type DeviceClaimList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []DeviceClaim `json:"items"` +} + +type DeviceList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []Device `json:"items"` +} + +func addKnown(s *runtime.Scheme) error { + s.AddKnownTypes(GroupVersion, &DeviceClaim{}, &DeviceClaimList{}, &Device{}, &DeviceList{}) + metav1.AddToGroupVersion(s, GroupVersion) + return nil +} + +var AddToScheme = addKnown + +func (in *DeviceClaim) DeepCopyObject() runtime.Object { + out := new(DeviceClaim) + deepCopy(in, out) + return out +} +func (in *DeviceClaimList) DeepCopyObject() runtime.Object { + out := new(DeviceClaimList) + deepCopy(in, out) + return out +} +func (in *Device) DeepCopyObject() runtime.Object { + out := new(Device) + deepCopy(in, out) + return out +} +func (in *DeviceList) DeepCopyObject() runtime.Object { + out := new(DeviceList) + deepCopy(in, out) + return out +} + +func deepCopy[T any](in *T, out *T) { b, _ := json.Marshal(in); _ = json.Unmarshal(b, out) } From 42086bbe2cf05f5d09362fbc777e514907d64462 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Thu, 19 Nov 2026 17:27:06 -0600 Subject: [PATCH 013/518] feat(inventory): register DeviceClaim and Device in Milo Milo becomes the single home for provider inventory. config/milo now includes config/components/inventory: the two CRDs, served in project control planes; their ProtectedResources, with serviceRef fleet.datumapis.com because the authorization provider keys on {apiGroup}/{plural}; and the inventory viewer and editor roles. No metal role includes or inherits them, so consumer, claimant, viewer and provider roles grant no inventory access. No role grants status writes. The Bare Metal staff portal plugin gains a read-only Inventory tab. It lists DeviceClaims with their bound Device, flags Devices whose claim is missing, and has a per-claim detail page. The detail page shows placement, expected ports and peers, identity, BMC endpoint, interfaces, unmapped MACs, and provenance. config/inventory now renders only the CRDs from the component, for the management-cluster install that predates the move. It is removed after that environment cuts over. Co-Authored-By: Claude Opus 5.5 --- config/README.md | 10 +- .../inventory/crds}/fleet.datumapis.com.yaml | 4 + .../inventory/crds/kustomization.yaml | 3 + .../components/inventory/kustomization.yaml | 6 + .../inventory/protected-resources/device.yaml | 14 ++ .../protected-resources/deviceclaim.yaml | 14 ++ .../protected-resources/kustomization.yaml | 5 + config/components/inventory/roles/editor.yaml | 20 +++ .../inventory/roles/kustomization.yaml | 5 + config/components/inventory/roles/viewer.yaml | 16 ++ config/inventory/kustomization.yaml | 2 +- config/milo/kustomization.yaml | 1 + docs/architecture/README.md | 2 +- docs/development/README.md | 22 ++- docs/operations/README.md | 2 +- docs/operations/physical-inventory.md | 74 +++++++-- internal/api/inventory/v1alpha1/crd_test.go | 11 +- internal/api/inventory/v1alpha1/iam_test.go | 154 ++++++++++++++++++ ui/provider/README.md | 18 +- ui/provider/public/plugin-manifest.json | 18 +- ui/provider/src/components/fleet-page.tsx | 1 + .../src/components/inventory-table.tsx | 90 ++++++++++ ui/provider/src/inventory.test.ts | 39 +++++ ui/provider/src/inventory.ts | 62 +++++++ ui/provider/src/lib/api.ts | 27 ++- ui/provider/src/lib/fixtures.ts | 45 +++++ ui/provider/src/main.tsx | 4 + ui/provider/src/pages/device-claim-detail.tsx | 144 ++++++++++++++++ .../src/pages/device-inventory-list.tsx | 64 ++++++++ .../src/pages/device-inventory.test.tsx | 126 ++++++++++++++ ui/provider/vite.config.ts | 2 + ui/shared/fleet-api.ts | 46 ++++++ 32 files changed, 1014 insertions(+), 37 deletions(-) rename config/{inventory => components/inventory/crds}/fleet.datumapis.com.yaml (98%) create mode 100644 config/components/inventory/crds/kustomization.yaml create mode 100644 config/components/inventory/kustomization.yaml create mode 100644 config/components/inventory/protected-resources/device.yaml create mode 100644 config/components/inventory/protected-resources/deviceclaim.yaml create mode 100644 config/components/inventory/protected-resources/kustomization.yaml create mode 100644 config/components/inventory/roles/editor.yaml create mode 100644 config/components/inventory/roles/kustomization.yaml create mode 100644 config/components/inventory/roles/viewer.yaml create mode 100644 internal/api/inventory/v1alpha1/iam_test.go create mode 100644 ui/provider/src/components/inventory-table.tsx create mode 100644 ui/provider/src/inventory.test.ts create mode 100644 ui/provider/src/inventory.ts create mode 100644 ui/provider/src/pages/device-claim-detail.tsx create mode 100644 ui/provider/src/pages/device-inventory-list.tsx create mode 100644 ui/provider/src/pages/device-inventory.test.tsx diff --git a/config/README.md b/config/README.md index 856b91fb..efd3cef5 100644 --- a/config/README.md +++ b/config/README.md @@ -14,7 +14,7 @@ API servers and must be reconciled independently. | Root | Destination | Contents | | --- | --- | --- | -| `config/milo` | Milo root control plane | Fleet CRDs, IAM protected resources and roles, service registration, and machine quota registration | +| `config/milo` | Milo root control plane | Fleet CRDs (including the `fleet.datumapis.com` inventory kinds), IAM protected resources and roles, service registration, and machine quota registration | | `config/overlays/management-plane` | Fleet management cluster | Fleet CRDs, the manager workload and RBAC, private-record namespaces, and admission fences | | `config/overlays/synthetic-staging` | Fleet management cluster (non-production only) | Management-plane resources plus an explicit synthetic allocator/provider integration | @@ -27,9 +27,11 @@ contracts charge, as billing ServicePricings for `metal.datumapis.com`. Staging' on `config/milo`; production doesn't, so production has no Bare Metal prices. A price change is a new `-v2` pricing, since a ServicePricing can't be changed. -`config/inventory` is an opt-in root for the Fleet management cluster. It holds -only the CRDs for the operator-written `DeviceClaim` and `Device` subset of the -physical inventory API. Neither production root references it. See +`config/components/inventory` registers the operator-written `DeviceClaim` and +`Device` kinds of `fleet.datumapis.com` in Milo: their CRDs, ProtectedResources, +and inventory viewer and editor roles. Only `config/milo` includes it; records +live in the provider project. `config/inventory` renders the CRDs alone for a +legacy management-cluster install and will be removed. See [Planning and registering physical devices](../docs/operations/physical-inventory.md). `config/standalone` remains a synthetic, same-cluster test environment. It must diff --git a/config/inventory/fleet.datumapis.com.yaml b/config/components/inventory/crds/fleet.datumapis.com.yaml similarity index 98% rename from config/inventory/fleet.datumapis.com.yaml rename to config/components/inventory/crds/fleet.datumapis.com.yaml index 3033e41c..566569f7 100644 --- a/config/inventory/fleet.datumapis.com.yaml +++ b/config/components/inventory/crds/fleet.datumapis.com.yaml @@ -2,6 +2,8 @@ apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: name: deviceclaims.fleet.datumapis.com + annotations: + discovery.miloapis.com/parent-contexts: Project spec: group: fleet.datumapis.com names: {kind: DeviceClaim, listKind: DeviceClaimList, plural: deviceclaims, singular: deviceclaim} @@ -80,6 +82,8 @@ apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: name: devices.fleet.datumapis.com + annotations: + discovery.miloapis.com/parent-contexts: Project spec: group: fleet.datumapis.com names: {kind: Device, listKind: DeviceList, plural: devices, singular: device} diff --git a/config/components/inventory/crds/kustomization.yaml b/config/components/inventory/crds/kustomization.yaml new file mode 100644 index 00000000..1f890b4c --- /dev/null +++ b/config/components/inventory/crds/kustomization.yaml @@ -0,0 +1,3 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: [fleet.datumapis.com.yaml] diff --git a/config/components/inventory/kustomization.yaml b/config/components/inventory/kustomization.yaml new file mode 100644 index 00000000..cc727f1c --- /dev/null +++ b/config/components/inventory/kustomization.yaml @@ -0,0 +1,6 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - crds + - protected-resources + - roles diff --git a/config/components/inventory/protected-resources/device.yaml b/config/components/inventory/protected-resources/device.yaml new file mode 100644 index 00000000..78bdacfa --- /dev/null +++ b/config/components/inventory/protected-resources/device.yaml @@ -0,0 +1,14 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: fleet.datumapis.com-device +spec: + serviceRef: + name: fleet.datumapis.com + kind: Device + plural: devices + singular: device + permissions: [list, get, watch, create, update, patch, delete] + parentResources: + - apiGroup: resourcemanager.miloapis.com + kind: Project diff --git a/config/components/inventory/protected-resources/deviceclaim.yaml b/config/components/inventory/protected-resources/deviceclaim.yaml new file mode 100644 index 00000000..2d4cad48 --- /dev/null +++ b/config/components/inventory/protected-resources/deviceclaim.yaml @@ -0,0 +1,14 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: fleet.datumapis.com-deviceclaim +spec: + serviceRef: + name: fleet.datumapis.com + kind: DeviceClaim + plural: deviceclaims + singular: deviceclaim + permissions: [list, get, watch, create, update, patch, delete] + parentResources: + - apiGroup: resourcemanager.miloapis.com + kind: Project diff --git a/config/components/inventory/protected-resources/kustomization.yaml b/config/components/inventory/protected-resources/kustomization.yaml new file mode 100644 index 00000000..0a5454da --- /dev/null +++ b/config/components/inventory/protected-resources/kustomization.yaml @@ -0,0 +1,5 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - deviceclaim.yaml + - device.yaml diff --git a/config/components/inventory/roles/editor.yaml b/config/components/inventory/roles/editor.yaml new file mode 100644 index 00000000..e5e28191 --- /dev/null +++ b/config/components/inventory/roles/editor.yaml @@ -0,0 +1,20 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: Role +metadata: + name: fleet.datumapis.com-inventory-editor + annotations: + kubernetes.io/display-name: Fleet Inventory Editor + kubernetes.io/description: Plan slots and register devices in provider inventory +spec: + launchStage: Alpha + inheritedRoles: + - name: fleet.datumapis.com-inventory-viewer + includedPermissions: + - fleet.datumapis.com/deviceclaims.create + - fleet.datumapis.com/deviceclaims.update + - fleet.datumapis.com/deviceclaims.patch + - fleet.datumapis.com/deviceclaims.delete + - fleet.datumapis.com/devices.create + - fleet.datumapis.com/devices.update + - fleet.datumapis.com/devices.patch + - fleet.datumapis.com/devices.delete diff --git a/config/components/inventory/roles/kustomization.yaml b/config/components/inventory/roles/kustomization.yaml new file mode 100644 index 00000000..aa7b7182 --- /dev/null +++ b/config/components/inventory/roles/kustomization.yaml @@ -0,0 +1,5 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - viewer.yaml + - editor.yaml diff --git a/config/components/inventory/roles/viewer.yaml b/config/components/inventory/roles/viewer.yaml new file mode 100644 index 00000000..db0d7f9a --- /dev/null +++ b/config/components/inventory/roles/viewer.yaml @@ -0,0 +1,16 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: Role +metadata: + name: fleet.datumapis.com-inventory-viewer + annotations: + kubernetes.io/display-name: Fleet Inventory Viewer + kubernetes.io/description: View the provider's planned slots and registered devices +spec: + launchStage: Alpha + includedPermissions: + - fleet.datumapis.com/deviceclaims.list + - fleet.datumapis.com/deviceclaims.get + - fleet.datumapis.com/deviceclaims.watch + - fleet.datumapis.com/devices.list + - fleet.datumapis.com/devices.get + - fleet.datumapis.com/devices.watch diff --git a/config/inventory/kustomization.yaml b/config/inventory/kustomization.yaml index 9ce565ec..a44f7dd6 100644 --- a/config/inventory/kustomization.yaml +++ b/config/inventory/kustomization.yaml @@ -1,4 +1,4 @@ apiVersion: kustomize.config.k8s.io/v1beta1 kind: Kustomization resources: - - fleet.datumapis.com.yaml + - ../components/inventory/crds diff --git a/config/milo/kustomization.yaml b/config/milo/kustomization.yaml index baa07462..0f5a7f84 100644 --- a/config/milo/kustomization.yaml +++ b/config/milo/kustomization.yaml @@ -4,3 +4,4 @@ resources: - ../base/crd - ../components/iam - ../components/service-catalog + - ../components/inventory diff --git a/docs/architecture/README.md b/docs/architecture/README.md index 57c04fa4..ab88c8b8 100644 --- a/docs/architecture/README.md +++ b/docs/architecture/README.md @@ -59,7 +59,7 @@ processes or service-catalog entries. | --- | --- | --- | | `metal.datumapis.com` | `MachineClass`: offerings and consumer references. `MachineProfile`: hardware requirements. `MachineCapacity`: provider supply. `Machine`: customer allocation and runtime intent. `MachineAllocation`: protected allocation identity. `Installation`: immutable OS installation or reinstall request. | Six alpha CRDs at `v1alpha1`. Production admission and real providers remain incomplete. | | `provider.metal.datumapis.com` | Proposed `MachineOffering` owns installation/management capability policy; `MachineOfferingAssignment` controls acquisition access. MachineClass becomes only a one-hop published consumer view; MachineProfile remains immutable requirements in Metal. | Proposed target design, not implemented by the six alpha CRDs above. | -| `fleet.datumapis.com` | Physical inventory: `Facility`, `Rack`, `DeviceClaim`, `Device`, `Cable`, and `PowerFeed`. Physical preparation and provider execution remain operator responsibilities. | Proposed inventory APIs. Only a minimal, operator-written subset of `DeviceClaim` and `Device` is implemented, as alpha CRDs in the opt-in [inventory root](../operations/physical-inventory.md), outside the production roots; no controller reads them. No real provider executor is implemented here. | +| `fleet.datumapis.com` | Physical inventory: `Facility`, `Rack`, `DeviceClaim`, `Device`, `Cable`, and `PowerFeed`. Physical preparation and provider execution remain operator responsibilities. | Proposed inventory APIs. Only a minimal, operator-written subset of `DeviceClaim` and `Device` is implemented. Its alpha CRDs, ProtectedResources and inventory roles are [registered in Milo](../operations/physical-inventory.md) by `config/milo`, and the records live in the provider project; no controller reads them. No real provider executor is implemented here. | | `coordination.fleet.datumapis.com` | Intended management-to-location execution handoff, retaining exact allocation identity, location, admitted inputs, release intent, and execution evidence. `MachineAllocationHandoff` is a candidate resource. | Architecture decision only on the current main implementation: no coordination CRD or cell controller is packaged. Replaces the earlier prototype name `internal.fleet.datumapis.com`. | MachineCapacity and MachineAllocation belong to the Metal allocation contract diff --git a/docs/development/README.md b/docs/development/README.md index b545c99b..d4c274de 100644 --- a/docs/development/README.md +++ b/docs/development/README.md @@ -705,14 +705,20 @@ corrupt or uses an unsupported schema version. ## Physical inventory subset `internal/api/inventory/v1alpha1` defines `DeviceClaim`, the plan for one rack -slot, and `Device`, the asset bound to one claim. Operators write both by hand. -`config/inventory` packages only their CRDs. CEL requires `Manual` provenance on -both and requires every edit to advance `recordedAt`. It keeps a Device's -`claimRef` and identity immutable, rejects duplicate or ambiguous MACs, and -accepts only credential-free `https` BMC endpoints. Status is a reserved -subresource with no fields and no writer. No production root includes the -package, and nothing reads it. Unit tests run the API server's schema, -list-type, defaulting, and CEL validation offline. See +slot, and `Device`, the asset bound to one claim. Operators write both by hand +into the provider project in Milo. `config/components/inventory` holds their +CRDs, ProtectedResources, and the `fleet.datumapis.com-inventory-viewer` and +`-editor` roles. Only `config/milo` includes it. + +CEL requires `Manual` provenance on both kinds and requires every edit to +advance `recordedAt`. It keeps a Device's `claimRef` and identity immutable, +rejects duplicate or ambiguous MACs, and accepts only credential-free `https` +BMC endpoints. Status is a reserved subresource with no fields and no writer. +No metal role grants inventory access. + +The staff portal plugin's read-only Inventory tab lists claims and shows each +claim's bound Devices. Unit tests run the API server's validation offline and +check the IAM shape. See [Planning and registering physical devices](../operations/physical-inventory.md). ## Build, test, and run diff --git a/docs/operations/README.md b/docs/operations/README.md index d4606067..8139c173 100644 --- a/docs/operations/README.md +++ b/docs/operations/README.md @@ -17,7 +17,7 @@ integrations. Real provider support and live Milo acceptance tests are incomplet | Exercise Milo, Karmada and cell-local PXE end to end with one command | [Multi-plane acceptance](multiplane.md) (`task multiplane:acceptance`) | Native project routing, 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, cleanup and reuse; 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 executor discovery, one-time PXE/disk boot overrides, power, lost-response recovery and a booted wipe cleanup, against the unmodified DMTF Redfish Interface Emulator with a lab-only libvirt adapter and two persistent lab VMs; synthetic credentials and networking; not physical BMC or hardware qualification | | Publish physical-side DHCP reservations for network boot | [Boot network](boot-network.md) | Per-asset BMC endpoints and provisioning attachments, a reservation feed 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 with attributable provenance and immutable identity and binding; no capacity or hardware effect; unit tested | +| 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 attributable provenance and immutable identity and binding, shown read-only in the staff portal; no capacity or hardware effect; unit tested | | Render deployment bundles and supply environment inputs | [Deployment manifests](../../config/README.md) | Packaging and security boundaries, not runtime readiness | | Run the manager across consuming projects | [Project discovery](../../config/README.md#project-discovery) | Discovery, per-project isolation, departure, role bindings, and readiness | | Exercise Milo-routed synthetic staging | [Synthetic staging configuration](../../config/README.md#environment-owned-inputs) | Restricted synthetic publication and lifecycle behavior, not production authority | diff --git a/docs/operations/physical-inventory.md b/docs/operations/physical-inventory.md index ddfdfe83..7d0f2063 100644 --- a/docs/operations/physical-inventory.md +++ b/docs/operations/physical-inventory.md @@ -21,9 +21,10 @@ It has two operator-written kinds in `fleet.datumapis.com/v1alpha1`: | Aspect | State | | --- | --- | -| CRDs and Go types | Implemented in `config/inventory` and `internal/api/inventory/v1alpha1`. | -| Tests | Unit tests run the API server's schema, list-type, defaulting, and CEL validation offline, for both kinds. | -| Production roots | Not included. `config/milo`, `config/overlays/management-plane`, and `config/overlays/synthetic-staging` do not reference it. An environment opts in by applying `config/inventory`. | +| CRDs and Go types | Implemented in `config/components/inventory` and `internal/api/inventory/v1alpha1`. | +| Home | Milo. `config/milo` registers both CRDs, two ProtectedResources and two IAM roles, like the `metal.datumapis.com` kinds. `config/overlays/management-plane` and `config/overlays/synthetic-staging` install none of them. | +| Staff portal | Read-only **Inventory** tab in the Bare Metal provider plugin (`ui/provider`): a claim list and a per-claim detail page. | +| Tests | Unit tests run the API server's schema, list-type, defaulting, and CEL validation offline, for both kinds. IAM tests check ProtectedResource and role shape and that no metal role grants inventory access. Plugin tests cover the list, detail, restricted, and empty states. | | Controllers | None. No Fleet code reads or writes these kinds. | | Hardware qualification | None. Records hold operator-entered facts, not verified hardware state. | @@ -41,10 +42,40 @@ Detection is manual too. The registrar records what the BMC (for example Redfish) and the rack showed them. MachineCapacity is unchanged by this package. Its `spec.deviceRef` already names a Device by name, and the allocator forms the asset key -`/fleet.datumapis.com/Device/`. Device names are -Kubernetes object names in the same group and kind, so a later supply step can -reference a Device without renaming it. That step must place the Device and its -MachineCapacity in the same namespace. +`/fleet.datumapis.com/Device/`. Devices live in the +provider project next to its MachineCapacities, so a `deviceRef` in the same +namespace resolves by name. Nothing checks that reference yet. + +## Where the records live + +Milo is the single home. DeviceClaims and Devices are namespaced objects in the +**provider project's** control plane, in the same namespace as the +MachineCapacities they will back. No copy exists on the Fleet management +cluster, and no controller syncs them anywhere. + +Both CRDs carry `discovery.miloapis.com/parent-contexts: Project`, so every +project control plane serves the kinds. Access is what keeps consumers out: + +| Role | Grants | +| --- | --- | +| `fleet.datumapis.com-inventory-viewer` | `get`, `list`, `watch` on `deviceclaims` and `devices` | +| `fleet.datumapis.com-inventory-editor` | The viewer role plus `create`, `update`, `patch`, `delete` | + +No `metal.datumapis.com` role includes or inherits either. The consumer, +claimant, and viewer roles that reach customer projects therefore grant no +inventory access, and the provider role does not either. Bind the inventory +roles explicitly, scoped to the provider project. No role grants status +writes, because status has no writer yet. + +The ProtectedResources use `serviceRef: fleet.datumapis.com`. The authorization +provider looks resources up by `{apiGroup}/{plural}`, so the service name must +equal the API group. No `fleet.datumapis.com` Service or ServiceConfiguration +is registered; the kinds are provider-internal, not a catalog offering. + +Staff see the records in the staff portal's Bare Metal plugin, under +**Inventory**. The plugin reads through the portal's Milo proxy with the staff +member's own token, so a staff member needs `fleet.datumapis.com-inventory-viewer` +in the provider project. The plugin never writes. ## Writers and validation @@ -159,16 +190,33 @@ Deferred to #63, and deliberately absent: - Separation of planner, approver, registrar, and verifier roles. One operator can write both kinds today. +**Deliberate divergence: Milo-resident provider inventory.** #63 treats +private inventory, including serials, cable paths, and BMC endpoints, as +material that never reaches consumer catalogs or status, and keeps the +authoritative records in a protected management-side ledger. This package +stores the operator records in the provider project's Milo control plane +instead. Two things keep them away from consumers: they never enter a consumer +project or a catalog, and only the inventory roles can read them. This is a +deliberate change of home, not an oversight. It trades the ledger's isolation +for one authoritative record that MachineCapacity can name and that staff can +read. #63's ledger, trust, and enrollment protocol would still sit behind these +records if adopted. + **Divergence to resolve:** this package's convention is that a whole-server replacement binds a new Device to the same DeviceClaim, because the planned slot outlives the hardware. #63's current text says whole-server replacement creates a new DeviceClaim as well. The schema enforces neither convention. Settle this in #63 before either path is automated. -## Applying the root +## Applying the records + +`config/milo` installs the CRDs, ProtectedResources, and roles into Milo. Apply +claims and Devices into the provider project after those are established, +claims before the Devices that name them. Keep records with real serials, +UUIDs, MACs, endpoints, or cabling in the environment's private configuration, +not in this repository. -`config/inventory` contains only the two cluster-scoped CRDs. It needs no -credentials or workload. Apply claims and Devices after the CRDs are -established, claims before the Devices that name them. Keep records with real -serials, UUIDs, MACs, endpoints, or cabling in the environment's private -configuration, not in this repository. +`config/inventory` still renders the two CRDs alone, for an environment that +applied them to the management cluster before Milo became their home. Once that +environment has moved its records into Milo and stopped reconciling the root, it +will be removed. New environments must not use it. diff --git a/internal/api/inventory/v1alpha1/crd_test.go b/internal/api/inventory/v1alpha1/crd_test.go index 21150ef1..3f498f83 100644 --- a/internal/api/inventory/v1alpha1/crd_test.go +++ b/internal/api/inventory/v1alpha1/crd_test.go @@ -26,11 +26,14 @@ import ( celconfig "k8s.io/apiserver/pkg/apis/cel" ) -var inventoryRoot = filepath.Join("..", "..", "..", "..", "config", "inventory") +var ( + configRoot = filepath.Join("..", "..", "..", "..", "config") + inventoryRoot = filepath.Join(configRoot, "components", "inventory") +) func loadCRDs(t *testing.T) map[string]*extensionsv1.CustomResourceDefinition { t.Helper() - data, err := os.ReadFile(filepath.Join(inventoryRoot, "fleet.datumapis.com.yaml")) + data, err := os.ReadFile(filepath.Join(inventoryRoot, "crds", "fleet.datumapis.com.yaml")) if err != nil { t.Fatal(err) } @@ -69,8 +72,8 @@ func TestInventoryCRDContract(t *testing.T) { if status := version.Schema.OpenAPIV3Schema.Properties["status"]; len(status.Properties) != 0 || status.XPreserveUnknownFields != nil { t.Fatalf("%s status must stay empty until a collector or verifier owns it", kind) } - if _, ok := crd.Annotations["discovery.miloapis.com/parent-contexts"]; ok { - t.Fatalf("%s must not be exposed through Milo project discovery", kind) + if crd.Annotations["discovery.miloapis.com/parent-contexts"] != "Project" { + t.Fatalf("%s must be served in Milo project control planes", kind) } defaulted := crd.DeepCopy() extensionsv1.SetObjectDefaults_CustomResourceDefinition(defaulted) diff --git a/internal/api/inventory/v1alpha1/iam_test.go b/internal/api/inventory/v1alpha1/iam_test.go new file mode 100644 index 00000000..716d54ee --- /dev/null +++ b/internal/api/inventory/v1alpha1/iam_test.go @@ -0,0 +1,154 @@ +package v1alpha1 + +import ( + "bytes" + "io" + "os" + "path/filepath" + "slices" + "strings" + "testing" + + "k8s.io/apimachinery/pkg/util/yaml" +) + +type protectedResource struct { + Metadata struct{ Name string } `json:"metadata"` + Spec struct { + ServiceRef struct{ Name string } `json:"serviceRef"` + Kind string `json:"kind"` + Plural string `json:"plural"` + Singular string `json:"singular"` + Permissions []string `json:"permissions"` + Parents []struct { + APIGroup string `json:"apiGroup"` + Kind string `json:"kind"` + } `json:"parentResources"` + } `json:"spec"` +} + +type role struct { + Metadata struct{ Name string } `json:"metadata"` + Spec struct { + Inherited []struct{ Name string } `json:"inheritedRoles"` + Included []string `json:"includedPermissions"` + } `json:"spec"` +} + +func decodeDir[T any](t *testing.T, dir string) []T { + t.Helper() + files, err := filepath.Glob(filepath.Join(dir, "*.yaml")) + if err != nil { + t.Fatal(err) + } + var out []T + for _, file := range files { + if filepath.Base(file) == "kustomization.yaml" { + continue + } + data, err := os.ReadFile(file) + if err != nil { + t.Fatal(err) + } + decoder := yaml.NewYAMLOrJSONDecoder(bytes.NewReader(data), 4096) + for { + var item T + if err := decoder.Decode(&item); err == io.EOF { + break + } else if err != nil { + t.Fatal(err) + } + out = append(out, item) + } + } + return out +} + +func TestProtectedResourcesMatchTheCRDs(t *testing.T) { + crds := loadCRDs(t) + resources := decodeDir[protectedResource](t, filepath.Join(inventoryRoot, "protected-resources")) + if len(resources) != len(crds) { + t.Fatalf("got %d ProtectedResources for %d CRDs", len(resources), len(crds)) + } + for _, resource := range resources { + crd := crds[resource.Spec.Kind] + if crd == nil { + t.Fatalf("ProtectedResource %s names unknown kind %s", resource.Metadata.Name, resource.Spec.Kind) + } + // The authorization provider indexes ProtectedResources by + // "{apiGroup}/{plural}", so serviceRef must be the API group. + if resource.Spec.ServiceRef.Name != GroupVersion.Group || resource.Spec.Plural != crd.Spec.Names.Plural || resource.Spec.Singular != crd.Spec.Names.Singular { + t.Fatalf("ProtectedResource %s does not match %s", resource.Metadata.Name, crd.Name) + } + if resource.Metadata.Name != GroupVersion.Group+"-"+crd.Spec.Names.Singular { + t.Fatalf("ProtectedResource name %s", resource.Metadata.Name) + } + if len(resource.Spec.Parents) != 1 || resource.Spec.Parents[0].APIGroup != "resourcemanager.miloapis.com" || resource.Spec.Parents[0].Kind != "Project" { + t.Fatalf("%s must be project-scoped", resource.Metadata.Name) + } + if slices.Contains(resource.Spec.Permissions, "updateStatus") { + t.Fatalf("%s grants status writes; status has no writer yet", resource.Metadata.Name) + } + } +} + +func TestInventoryRolesSplitReadFromWrite(t *testing.T) { + declared := map[string]bool{} + for _, resource := range decodeDir[protectedResource](t, filepath.Join(inventoryRoot, "protected-resources")) { + for _, verb := range resource.Spec.Permissions { + declared[GroupVersion.Group+"/"+resource.Spec.Plural+"."+verb] = true + } + } + roles := map[string]role{} + for _, r := range decodeDir[role](t, filepath.Join(inventoryRoot, "roles")) { + roles[r.Metadata.Name] = r + } + viewer, editor := roles["fleet.datumapis.com-inventory-viewer"], roles["fleet.datumapis.com-inventory-editor"] + if len(roles) != 2 || len(viewer.Spec.Included) == 0 || len(editor.Spec.Included) == 0 { + t.Fatalf("want exactly the inventory viewer and editor roles, got %v", roles) + } + for _, permission := range append(slices.Clone(viewer.Spec.Included), editor.Spec.Included...) { + if !declared[permission] { + t.Fatalf("role permission %s has no ProtectedResource", permission) + } + } + for _, permission := range viewer.Spec.Included { + if verb := permission[strings.LastIndex(permission, ".")+1:]; verb != "get" && verb != "list" && verb != "watch" { + t.Fatalf("viewer grants %s", permission) + } + } + if len(editor.Spec.Inherited) != 1 || editor.Spec.Inherited[0].Name != viewer.Metadata.Name { + t.Fatal("editor must inherit the viewer role") + } +} + +func TestOnlyMiloServesTheInventoryKinds(t *testing.T) { + read := func(path string) string { + data, err := os.ReadFile(filepath.Join(configRoot, path, "kustomization.yaml")) + if err != nil { + t.Fatal(err) + } + return string(data) + } + if !strings.Contains(read("milo"), "../components/inventory\n") { + t.Fatal("config/milo must register the inventory kinds") + } + for _, root := range []string{"base/crd", "overlays/management-plane", "overlays/synthetic-staging"} { + if strings.Contains(read(root), "inventory") { + t.Fatalf("config/%s must not install the inventory kinds on the management cluster", root) + } + } + // Metal roles reach consumers. None may grant inventory access. + for _, r := range decodeDir[role](t, filepath.Join(configRoot, "components", "iam", "roles")) { + for _, permission := range r.Spec.Included { + if strings.HasPrefix(permission, GroupVersion.Group+"/") { + t.Fatalf("metal role %s grants inventory permission %s", r.Metadata.Name, permission) + } + } + for _, inherited := range r.Spec.Inherited { + if strings.HasPrefix(inherited.Name, GroupVersion.Group+"-") { + t.Fatalf("metal role %s inherits inventory role %s", r.Metadata.Name, inherited.Name) + } + } + } +} diff --git a/ui/provider/README.md b/ui/provider/README.md index c547e0b3..3514062f 100644 --- a/ui/provider/README.md +++ b/ui/provider/README.md @@ -10,8 +10,8 @@ Operations in the navigation. The page has three tabs: provider's MachineCapacities in every namespace and creates new ones. The form asks only for a name, a class, and whether to offer the capacity for allocation (off by default). It goes in the class's namespace and capacity - pool, with a device reference named after the record (Fleet has no Device - inventory yet) and the standalone fixtures' cleaning policy. The device + pool, with a device reference named after the record (nothing checks that a + Device of that name exists) and the standalone fixtures' cleaning policy. The device reference can't be changed later. Hardware and conditions stay empty until Fleet's discovery reports them. - **Profiles** (`profiles`) lists MachineProfiles and creates new ones. A @@ -20,11 +20,23 @@ Operations in the navigation. The page has three tabs: profiles a class allows, the namespace and capacity-pool label of the MachineCapacities that serve it, and whether consumers get power control. Custom profiles and console access stay off. +- **Inventory** (`inventory`) is read-only. It lists the provider project's + DeviceClaims (`fleet.datumapis.com`) in every namespace, with each claim's + placement, expected model, bound Device and serial. Devices that name a + missing claim are listed separately. `inventory/:namespace/:claim` shows one + claim's planned placement, expected ports and peers, and provenance. It also + shows every Device bound to it: model, serial, system UUID, BMC endpoint, + interfaces, unmapped MACs and provenance, with the most recently recorded + Device as the current one. Operators write these records through GitOps; the + plugin never writes them. The portal proxy forwards the staff member's own token, so creating capacity, profiles and classes needs a Bare Metal role with `machinecapacities.create`, `machineprofiles.create` and `machineclasses.create` in the provider project, -such as `metal.datumapis.com-provider`. Errors show inside the create dialog, +such as `metal.datumapis.com-provider`. The Inventory tab needs `deviceclaims.list` +and `devices.list` in `fleet.datumapis.com`, which +`fleet.datumapis.com-inventory-viewer` grants; metal roles grant no inventory +access. Errors show inside the create dialog, because staff-portal does not share its toast module with plugins. This started as the MVP from [#17](https://github.com/datum-cloud/fleet/issues/17). diff --git a/ui/provider/public/plugin-manifest.json b/ui/provider/public/plugin-manifest.json index b87ffe4b..99722903 100644 --- a/ui/provider/public/plugin-manifest.json +++ b/ui/provider/public/plugin-manifest.json @@ -6,7 +6,9 @@ "exposedModules": { "CapacityList": "./src/pages/capacity-list.tsx", "MachineProfileList": "./src/pages/machine-profile-list.tsx", - "MachineClassList": "./src/pages/machine-class-list.tsx" + "MachineClassList": "./src/pages/machine-class-list.tsx", + "DeviceInventoryList": "./src/pages/device-inventory-list.tsx", + "DeviceClaimDetail": "./src/pages/device-claim-detail.tsx" }, "extensions": [ { @@ -38,6 +40,20 @@ "path": "classes", "component": { "$codeRef": "MachineClassList" } } + }, + { + "type": "portal.page/platform", + "properties": { + "path": "inventory", + "component": { "$codeRef": "DeviceInventoryList" } + } + }, + { + "type": "portal.page/platform", + "properties": { + "path": "inventory/:namespace/:claim", + "component": { "$codeRef": "DeviceClaimDetail" } + } } ] } diff --git a/ui/provider/src/components/fleet-page.tsx b/ui/provider/src/components/fleet-page.tsx index 6139dd0f..6776a46d 100644 --- a/ui/provider/src/components/fleet-page.tsx +++ b/ui/provider/src/components/fleet-page.tsx @@ -25,6 +25,7 @@ export function FleetPage({ { label: 'Capacity', href: base }, { label: 'Profiles', href: `${base}/profiles` }, { label: 'Classes', href: `${base}/classes` }, + { label: 'Inventory', href: `${base}/inventory` }, ]; const active = tabs.slice(1).find((t) => pathname.startsWith(t.href))?.href ?? base; diff --git a/ui/provider/src/components/inventory-table.tsx b/ui/provider/src/components/inventory-table.tsx new file mode 100644 index 00000000..f8552506 --- /dev/null +++ b/ui/provider/src/components/inventory-table.tsx @@ -0,0 +1,90 @@ +import { StatusBadge } from './status-badge'; +import { currentDevice, modelLabel, placementLabel, type InventorySlot } from '../inventory'; +import { DataTable, type DataTableFeatures } from '@datum-cloud/datum-ui/data-table'; +import { Text } from '@datum-cloud/datum-ui/typography'; +import type { ColumnDef } from '@tanstack/react-table'; +import { Link } from 'react-router'; + +type SlotColumn = ColumnDef; + +function Muted({ children }: { children: React.ReactNode }) { + return {children}; +} + +function matchesSearch(slot: InventorySlot, search: string): boolean { + const needle = search.trim().toLowerCase(); + if (!needle) return true; + const { claim } = slot; + return [ + claim.metadata.name, + placementLabel(claim), + modelLabel(claim.spec.expectedIdentity), + claim.spec.expectedIdentity.serial, + ...slot.devices.flatMap((d) => [d.metadata.name, d.spec.identity.serial, d.spec.identity.systemUUID]), + ] + .filter(Boolean) + .join(' ') + .toLowerCase() + .includes(needle); +} + +export function InventoryTable({ slots, base }: { slots: InventorySlot[]; base: string }) { + const columns: SlotColumn[] = [ + { + id: 'name', + accessorFn: (slot) => slot.claim.metadata.name, + header: 'Claim', + cell: ({ row }) => ( + + {row.original.claim.metadata.name} + + ), + }, + { id: 'placement', header: 'Placement', cell: ({ row }) => {placementLabel(row.original.claim)} }, + { + id: 'model', + header: 'Expected model', + cell: ({ row }) => {modelLabel(row.original.claim.spec.expectedIdentity)}, + }, + { + id: 'device', + header: 'Device', + cell: ({ row }) => { + const device = currentDevice(row.original); + if (!device) return Not registered; + return {device.metadata.name}; + }, + }, + { + id: 'serial', + header: 'Serial', + cell: ({ row }) => { + const device = currentDevice(row.original); + return {device?.spec.identity.serial ?? row.original.claim.spec.expectedIdentity.serial ?? '—'}; + }, + }, + ]; + + return ( + slot.key} + defaultSort={[{ id: 'name', desc: false }]} + searchFn={matchesSearch} + className="space-y-6"> + +
+ + No claims match your search. + + } + /> +
+
+ ); +} diff --git a/ui/provider/src/inventory.test.ts b/ui/provider/src/inventory.test.ts new file mode 100644 index 00000000..4581e800 --- /dev/null +++ b/ui/provider/src/inventory.test.ts @@ -0,0 +1,39 @@ +import { currentDevice, placementLabel, toInventory } from './inventory'; +import { fixtureDeviceClaims, fixtureDevices } from './lib/fixtures'; +import { describe, expect, it } from 'vitest'; + +describe('toInventory', () => { + it('binds Devices to claims in the same namespace and keeps orphans visible', () => { + const inventory = toInventory(fixtureDeviceClaims, fixtureDevices); + expect(inventory.slots.map((s) => s.claim.metadata.name)).toEqual(['rack-01-u10', 'rack-01-u12']); + const u12 = inventory.slots.find((s) => s.claim.metadata.name === 'rack-01-u12')!; + expect(currentDevice(u12)?.metadata.name).toBe('rack-01-u12-synthetic-0001'); + expect(currentDevice(inventory.slots[0])).toBeUndefined(); + expect(inventory.unboundDevices.map((d) => d.metadata.name)).toEqual(['orphan-synthetic-0009']); + }); + + it('does not bind a Device to a same-named claim in another namespace', () => { + const elsewhere = { ...fixtureDevices[0], metadata: { ...fixtureDevices[0].metadata, namespace: 'other' } }; + const inventory = toInventory(fixtureDeviceClaims, [elsewhere]); + expect(inventory.slots.every((s) => s.devices.length === 0)).toBe(true); + expect(inventory.unboundDevices).toHaveLength(1); + }); + + it('treats the most recently recorded Device as the current hardware', () => { + const replacement = { + ...fixtureDevices[0], + metadata: { ...fixtureDevices[0].metadata, name: 'rack-01-u12-synthetic-0002' }, + spec: { ...fixtureDevices[0].spec, provenance: { ...fixtureDevices[0].spec.provenance, recordedAt: '2026-02-01T00:00:00Z' } }, + }; + const inventory = toInventory(fixtureDeviceClaims, [replacement, fixtureDevices[0]]); + const u12 = inventory.slots.find((s) => s.claim.metadata.name === 'rack-01-u12')!; + expect(u12.devices).toHaveLength(2); + expect(currentDevice(u12)?.metadata.name).toBe('rack-01-u12-synthetic-0002'); + }); + + it('labels single and multi-unit placements', () => { + expect(placementLabel(fixtureDeviceClaims[0])).toBe('example-facility · rack-01 · U12 front'); + const tall = { ...fixtureDeviceClaims[0], spec: { ...fixtureDeviceClaims[0].spec, placement: { ...fixtureDeviceClaims[0].spec.placement, height: 2 } } }; + expect(placementLabel(tall)).toBe('example-facility · rack-01 · U12–U13 front'); + }); +}); diff --git a/ui/provider/src/inventory.ts b/ui/provider/src/inventory.ts new file mode 100644 index 00000000..cceed449 --- /dev/null +++ b/ui/provider/src/inventory.ts @@ -0,0 +1,62 @@ +// View model for the inventory pages. A slot is one DeviceClaim with every +// Device that names it in the same namespace; a replacement leaves more than +// one. Devices whose claim is missing are kept separately so they stay visible. + +import type { Device as RawDevice, DeviceClaim as RawDeviceClaim, List } from '../../shared/fleet-api'; + +export type { RawDevice, RawDeviceClaim }; +export type RawDeviceList = List; +export type RawDeviceClaimList = List; + +export interface InventorySlot { + key: string; + claim: RawDeviceClaim; + devices: RawDevice[]; +} + +export interface Inventory { + slots: InventorySlot[]; + unboundDevices: RawDevice[]; +} + +export function slotKey(namespace: string | undefined, name: string): string { + return `${namespace ?? ''}/${name}`; +} + +function byRecordedAt(a: RawDevice, b: RawDevice): number { + return a.spec.provenance.recordedAt.localeCompare(b.spec.provenance.recordedAt); +} + +export function toInventory(claims: RawDeviceClaim[], devices: RawDevice[]): Inventory { + const slots = new Map(); + for (const claim of claims) { + const key = slotKey(claim.metadata.namespace, claim.metadata.name); + slots.set(key, { key, claim, devices: [] }); + } + const unboundDevices: RawDevice[] = []; + for (const device of devices) { + const slot = slots.get(slotKey(device.metadata.namespace, device.spec.claimRef.name)); + if (slot) slot.devices.push(device); + else unboundDevices.push(device); + } + for (const slot of slots.values()) slot.devices.sort(byRecordedAt); + return { + slots: [...slots.values()].sort((a, b) => a.key.localeCompare(b.key)), + unboundDevices: unboundDevices.sort((a, b) => a.metadata.name.localeCompare(b.metadata.name)), + }; +} + +export function placementLabel(claim: RawDeviceClaim): string { + const { facility, rack, position, height = 1, face } = claim.spec.placement; + const units = height > 1 ? `U${position}–U${position + height - 1}` : `U${position}`; + return `${facility} · ${rack} · ${units} ${face}`; +} + +export function modelLabel(identity: { manufacturer?: string; model: string }): string { + return identity.manufacturer ? `${identity.manufacturer} ${identity.model}` : identity.model; +} + +// The newest Device bound to a slot is the one currently recorded there. +export function currentDevice(slot: InventorySlot): RawDevice | undefined { + return slot.devices.at(-1); +} diff --git a/ui/provider/src/lib/api.ts b/ui/provider/src/lib/api.ts index 51d77b39..5937bda1 100644 --- a/ui/provider/src/lib/api.ts +++ b/ui/provider/src/lib/api.ts @@ -1,4 +1,5 @@ -import { fixtureClasses, fixtureCapacities, fixtureProfiles } from './fixtures'; +import { fixtureClasses, fixtureCapacities, fixtureDeviceClaims, fixtureDevices, fixtureProfiles } from './fixtures'; +import { toInventory, type Inventory, type RawDeviceClaimList, type RawDeviceList } from '../inventory'; import { toMachineCapacity, toMachineClass, @@ -31,6 +32,7 @@ const USE_FIXTURES = import.meta.env.VITE_FLEET_FIXTURES === 'true'; const REFETCH_INTERVAL_MS = 10_000; const METAL_API = '/apis/metal.datumapis.com/v1alpha1'; +const INVENTORY_API = '/apis/fleet.datumapis.com/v1alpha1'; export class ApiError extends Error { status: number; @@ -251,3 +253,26 @@ export function useDeleteMachineClass(): UseMutationResult { + if (USE_FIXTURES) return toInventory(fixtureDeviceClaims, fixtureDevices); + const [claims, devices] = await Promise.all([ + proxyFetch(PROVIDER_PROJECT, `${INVENTORY_API}/deviceclaims?limit=500`), + proxyFetch(PROVIDER_PROJECT, `${INVENTORY_API}/devices?limit=500`), + ]); + return toInventory(claims.items ?? [], devices.items ?? []); +} + +export function useInventory(): UseQueryResult { + return useQuery({ + queryKey: [PLUGIN_ID, 'inventory', PROVIDER_PROJECT], + queryFn: fetchInventory, + refetchInterval: REFETCH_INTERVAL_MS, + retry: false, + }); +} diff --git a/ui/provider/src/lib/fixtures.ts b/ui/provider/src/lib/fixtures.ts index 26ca5279..ee4577ee 100644 --- a/ui/provider/src/lib/fixtures.ts +++ b/ui/provider/src/lib/fixtures.ts @@ -1,4 +1,5 @@ import { ApiError } from './api'; +import type { RawDevice, RawDeviceClaim } from '../inventory'; import type { RawMachineCapacity, RawMachineClass, RawMachineProfile } from '../types'; // Synthetic MachineCapacities used while the Fleet API cannot be read @@ -153,3 +154,47 @@ export const fixtureClasses = { delete: (name: string): void => remove(classes, 'machineclasses', name, (c) => c.metadata.name === name), }; + +// Synthetic inventory: two planned slots, one with a registered Device whose +// NIC MACs are not yet mapped to ports, plus a Device whose claim is missing. +// Documentation-range addresses and MACs only. + +const INVENTORY_NAMESPACE = 'default'; + +function claim(name: string, position: number): RawDeviceClaim { + return { + metadata: { name, namespace: INVENTORY_NAMESPACE }, + spec: { + provenance: { method: 'Manual', recordedBy: 'planner@example.com', recordedAt: '2026-01-02T03:04:05Z', reference: 'rack plan 1234' }, + expectedIdentity: { manufacturer: 'Example Vendor', model: 'Example 1U' }, + placement: { facility: 'example-facility', rack: 'rack-01', position, height: 1, face: 'front' }, + ports: [ + { name: 'eth0', type: '25gbase-x-sfp28', speedMbps: 25000, expectedPeer: { device: 'switch-01', port: `Ethernet1/${position}` } }, + { name: 'bmc0', type: '1000base-t', speedMbps: 1000, expectedPeer: { device: 'mgmt-switch-01', port: `Ethernet${position}` } }, + ], + }, + }; +} + +export const fixtureDeviceClaims: RawDeviceClaim[] = [claim('rack-01-u12', 12), claim('rack-01-u10', 10)]; + +export const fixtureDevices: RawDevice[] = [ + { + metadata: { name: 'rack-01-u12-synthetic-0001', namespace: INVENTORY_NAMESPACE }, + spec: { + claimRef: { name: 'rack-01-u12' }, + provenance: { method: 'Manual', recordedBy: 'registrar@example.com', recordedAt: '2026-01-09T10:00:00Z', reference: 'BMC inventory read during rack turn-up' }, + identity: { manufacturer: 'Example Vendor', model: 'Example 1U', serial: 'SYNTHETIC-0001', systemUUID: '00000000-0000-4000-8000-000000000001' }, + bmc: { endpoint: 'https://192.0.2.100:443' }, + unmappedMACAddresses: ['00:00:5e:00:53:01', '00:00:5e:00:53:02'], + }, + }, + { + metadata: { name: 'orphan-synthetic-0009', namespace: INVENTORY_NAMESPACE }, + spec: { + claimRef: { name: 'rack-02-u01' }, + provenance: { method: 'Manual', recordedBy: 'registrar@example.com', recordedAt: '2026-01-10T10:00:00Z' }, + identity: { model: 'Example 2U', systemUUID: '00000000-0000-4000-8000-000000000009' }, + }, + }, +]; diff --git a/ui/provider/src/main.tsx b/ui/provider/src/main.tsx index 204d1f38..29b9ace1 100644 --- a/ui/provider/src/main.tsx +++ b/ui/provider/src/main.tsx @@ -1,6 +1,8 @@ import MachineClassList from './pages/machine-class-list'; import CapacityList from './pages/capacity-list'; import MachineProfileList from './pages/machine-profile-list'; +import DeviceInventoryList from './pages/device-inventory-list'; +import DeviceClaimDetail from './pages/device-claim-detail'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { StrictMode } from 'react'; import { createRoot } from 'react-dom/client'; @@ -23,6 +25,8 @@ createRoot(document.getElementById('root')!).render( } /> } /> } /> + } /> + } /> diff --git a/ui/provider/src/pages/device-claim-detail.tsx b/ui/provider/src/pages/device-claim-detail.tsx new file mode 100644 index 00000000..465c667e --- /dev/null +++ b/ui/provider/src/pages/device-claim-detail.tsx @@ -0,0 +1,144 @@ +import { FleetPage } from '../components/fleet-page'; +import { ErrorOrRestrictedState, LoadingState } from '../components/states'; +import { StatusBadge } from '../components/status-badge'; +import { PROVIDER_PROJECT, useInventory } from '../lib/api'; +import { currentDevice, modelLabel, placementLabel, slotKey, type RawDevice } from '../inventory'; +import type { Provenance } from '../../../shared/fleet-api'; +import { Card, CardContent } from '@datum-cloud/datum-ui/card'; +import { Text } from '@datum-cloud/datum-ui/typography'; +import type { ReactNode } from 'react'; +import { Link, useParams } from 'react-router'; + +function Field({ label, children }: { label: string; children: ReactNode }) { + return ( +
+ {label} + {children} +
+ ); +} + +function Section({ title, testId, children }: { title: string; testId: string; children: ReactNode }) { + return ( + + + {title} + {children} + + + ); +} + +function ProvenanceFields({ provenance }: { provenance: Provenance }) { + return ( +
+ {provenance.recordedBy} + {provenance.recordedAt} + {provenance.method} + {provenance.reference && ( +
+ {provenance.reference} +
+ )} +
+ ); +} + +function DeviceSection({ device, current }: { device: RawDevice; current: boolean }) { + const { identity, bmc, interfaces = [], unmappedMACAddresses = [] } = device.spec; + return ( +
+ {!current && Earlier hardware for this slot} +
+ {modelLabel(identity)} + {identity.serial ?? '—'} + {identity.systemUUID ?? '—'} + {bmc?.endpoint ?? '—'} + {device.spec.claimRef.name} +
+ {interfaces.length > 0 && ( +
+ Interfaces + {interfaces.map((iface) => ( + + {iface.name}: {iface.macAddress ?? 'MAC unknown'} + {iface.peer ? ` → ${iface.peer.device} ${iface.peer.port}` : ''} + + ))} +
+ )} +
+ Unmapped MAC addresses + {unmappedMACAddresses.length === 0 ? ( + None + ) : ( + unmappedMACAddresses.map((mac) => {mac}) + )} +
+ +
+ ); +} + +export default function DeviceClaimDetail() { + const { slug, namespace = '', claim: claimName = '' } = useParams(); + const { data, isLoading, error, refetch } = useInventory(); + const slot = data?.slots.find((s) => s.key === slotKey(namespace, claimName)); + const current = slot && currentDevice(slot); + + return ( + + + ← All claims + + + {isLoading && } + + {!isLoading && error && ( + void refetch()} + /> + )} + + {!isLoading && !error && data && !slot && ( + + No DeviceClaim {claimName} in namespace {namespace}. + + )} + + {slot && ( + <> +
+
+ {placementLabel(slot.claim)} + {modelLabel(slot.claim.spec.expectedIdentity)} + {slot.claim.spec.expectedIdentity.serial ?? '—'} + {slot.claim.metadata.namespace ?? '—'} + + {current ? current.metadata.name : Not registered} + +
+ {(slot.claim.spec.ports ?? []).length > 0 && ( +
+ Expected ports + {(slot.claim.spec.ports ?? []).map((port) => ( + + {port.name} + {port.type ? ` (${port.type}${port.speedMbps ? `, ${port.speedMbps} Mb/s` : ''})` : ''} + {port.expectedPeer ? ` → ${port.expectedPeer.device} ${port.expectedPeer.port}` : ''} + + ))} +
+ )} + +
+ {[...slot.devices].reverse().map((device) => ( + + ))} + + )} +
+ ); +} diff --git a/ui/provider/src/pages/device-inventory-list.tsx b/ui/provider/src/pages/device-inventory-list.tsx new file mode 100644 index 00000000..ecaad7a4 --- /dev/null +++ b/ui/provider/src/pages/device-inventory-list.tsx @@ -0,0 +1,64 @@ +import { FleetPage } from '../components/fleet-page'; +import { InventoryTable } from '../components/inventory-table'; +import { ErrorOrRestrictedState, LoadingState } from '../components/states'; +import { PROVIDER_PROJECT, useInventory } from '../lib/api'; +import { modelLabel } from '../inventory'; +import { Card, CardContent } from '@datum-cloud/datum-ui/card'; +import { EmptyContent } from '@datum-cloud/datum-ui/empty-content'; +import { Text } from '@datum-cloud/datum-ui/typography'; +import { useParams } from 'react-router'; + +// Read-only. Planners and registrars write DeviceClaims and Devices through +// GitOps; nothing here creates capacity or acts on hardware. +export default function DeviceInventoryList() { + const { slug } = useParams(); + const base = `/plugins/${slug}`; + const { data, isLoading, error, refetch } = useInventory(); + const isEmpty = !isLoading && !error && data && data.slots.length === 0 && data.unboundDevices.length === 0; + + return ( + + {isLoading && } + + {!isLoading && error && ( + void refetch()} + /> + )} + + {isEmpty && ( +
+ +
+ )} + + {!isLoading && !error && data && data.slots.length > 0 && } + + {!isLoading && !error && data && data.unboundDevices.length > 0 && ( + + + Devices without a matching claim + + These Devices name a DeviceClaim that does not exist in their namespace. + +
    + {data.unboundDevices.map((device) => ( +
  • + + {device.metadata.name} → {device.spec.claimRef.name} ({modelLabel(device.spec.identity)}) + +
  • + ))} +
+
+
+ )} +
+ ); +} diff --git a/ui/provider/src/pages/device-inventory.test.tsx b/ui/provider/src/pages/device-inventory.test.tsx new file mode 100644 index 00000000..7745ad74 --- /dev/null +++ b/ui/provider/src/pages/device-inventory.test.tsx @@ -0,0 +1,126 @@ +import DeviceClaimDetail from './device-claim-detail'; +import DeviceInventoryList from './device-inventory-list'; +import { toInventory } from '../inventory'; +import * as api from '../lib/api'; +import { ApiError } from '../lib/api'; +import { fixtureDeviceClaims, fixtureDevices } from '../lib/fixtures'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { render, screen, within } from '@testing-library/react'; +import { MemoryRouter, Route, Routes } from 'react-router'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +vi.mock('../lib/api', async () => { + const actual = await vi.importActual('../lib/api'); + return { ...actual, useInventory: vi.fn() }; +}); + +const useInventoryMock = vi.mocked(api.useInventory); + +function mockInventory(result: { data?: unknown; isLoading?: boolean; error?: unknown }) { + useInventoryMock.mockReturnValue({ data: undefined, isLoading: false, error: null, refetch: vi.fn(), ...result } as never); +} + +function renderAt(path: string) { + const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + return render( + + + + } /> + } /> + + + + ); +} + +const inventory = toInventory(fixtureDeviceClaims, fixtureDevices); + +beforeEach(() => useInventoryMock.mockReset()); + +describe('DeviceInventoryList', () => { + it('marks the Inventory tab active', () => { + mockInventory({ data: inventory }); + renderAt('/plugins/metal-datumapis-com/inventory'); + expect(screen.getByRole('tab', { name: 'Inventory' })).toHaveAttribute('data-state', 'active'); + }); + + it('lists claims with their bound Device and links to the detail page', () => { + mockInventory({ data: inventory }); + renderAt('/plugins/metal-datumapis-com/inventory'); + const table = screen.getByTestId('fleet-plugin-inventory-table'); + expect(within(table).getByText('rack-01-u12-synthetic-0001')).toBeInTheDocument(); + expect(within(table).getByText('SYNTHETIC-0001')).toBeInTheDocument(); + expect(within(table).getByText('Not registered')).toBeInTheDocument(); + expect(within(table).getByRole('link', { name: 'rack-01-u12' })).toHaveAttribute( + 'href', + '/plugins/metal-datumapis-com/inventory/default/rack-01-u12' + ); + }); + + it('shows Devices whose claim is missing', () => { + mockInventory({ data: inventory }); + renderAt('/plugins/metal-datumapis-com/inventory'); + expect(within(screen.getByTestId('fleet-plugin-unbound-devices')).getByText(/orphan-synthetic-0009/)).toBeInTheDocument(); + }); + + it('shows the restricted state on a 403', () => { + mockInventory({ error: new ApiError(403, 'forbidden') }); + renderAt('/plugins/metal-datumapis-com/inventory'); + expect(screen.getByTestId('fleet-plugin-restricted')).toBeInTheDocument(); + }); + + it('shows the empty state with no records', () => { + mockInventory({ data: toInventory([], []) }); + renderAt('/plugins/metal-datumapis-com/inventory'); + expect(screen.getByTestId('fleet-plugin-inventory-empty')).toBeInTheDocument(); + }); + + it('offers no write actions', () => { + mockInventory({ data: inventory }); + renderAt('/plugins/metal-datumapis-com/inventory'); + expect(screen.queryByRole('button', { name: /create|delete|edit/i })).not.toBeInTheDocument(); + }); +}); + +describe('DeviceClaimDetail', () => { + it('shows placement, ports, binding, identity, BMC endpoint, unmapped MACs and provenance', () => { + mockInventory({ data: inventory }); + renderAt('/plugins/metal-datumapis-com/inventory/default/rack-01-u12'); + const claim = screen.getByTestId('fleet-plugin-claim'); + expect(within(claim).getByText('example-facility · rack-01 · U12 front')).toBeInTheDocument(); + expect(within(claim).getByText(/eth0 \(25gbase-x-sfp28, 25000 Mb\/s\) → switch-01 Ethernet1\/12/)).toBeInTheDocument(); + expect(within(claim).getByText('planner@example.com')).toBeInTheDocument(); + const device = screen.getByTestId('fleet-plugin-device-rack-01-u12-synthetic-0001'); + for (const text of ['SYNTHETIC-0001', '00000000-0000-4000-8000-000000000001', 'https://192.0.2.100:443', 'rack-01-u12', 'registrar@example.com', 'BMC inventory read during rack turn-up']) { + expect(within(device).getByText(text)).toBeInTheDocument(); + } + const macs = within(device).getByTestId('fleet-plugin-unmapped-macs'); + expect(within(macs).getByText('00:00:5e:00:53:01')).toBeInTheDocument(); + expect(within(macs).getByText('00:00:5e:00:53:02')).toBeInTheDocument(); + }); + + it('shows an unregistered slot', () => { + mockInventory({ data: inventory }); + renderAt('/plugins/metal-datumapis-com/inventory/default/rack-01-u10'); + expect(within(screen.getByTestId('fleet-plugin-claim')).getByText('Not registered')).toBeInTheDocument(); + }); + + it('reports a missing claim', () => { + mockInventory({ data: inventory }); + renderAt('/plugins/metal-datumapis-com/inventory/default/nope'); + expect(screen.getByTestId('fleet-plugin-claim-missing')).toBeInTheDocument(); + }); + + it('lists earlier hardware after the current Device', () => { + const replacement = { + ...fixtureDevices[0], + metadata: { ...fixtureDevices[0].metadata, name: 'rack-01-u12-synthetic-0002' }, + spec: { ...fixtureDevices[0].spec, provenance: { ...fixtureDevices[0].spec.provenance, recordedAt: '2026-02-01T00:00:00Z' } }, + }; + mockInventory({ data: toInventory(fixtureDeviceClaims, [fixtureDevices[0], replacement]) }); + renderAt('/plugins/metal-datumapis-com/inventory/default/rack-01-u12'); + expect(within(screen.getByTestId('fleet-plugin-claim')).getByText('rack-01-u12-synthetic-0002')).toBeInTheDocument(); + expect(within(screen.getByTestId('fleet-plugin-device-rack-01-u12-synthetic-0001')).getByText('Earlier hardware for this slot')).toBeInTheDocument(); + }); +}); diff --git a/ui/provider/vite.config.ts b/ui/provider/vite.config.ts index ded67a66..fb7b117b 100644 --- a/ui/provider/vite.config.ts +++ b/ui/provider/vite.config.ts @@ -37,6 +37,8 @@ export default defineConfig({ './CapacityList': './src/pages/capacity-list.tsx', './MachineProfileList': './src/pages/machine-profile-list.tsx', './MachineClassList': './src/pages/machine-class-list.tsx', + './DeviceInventoryList': './src/pages/device-inventory-list.tsx', + './DeviceClaimDetail': './src/pages/device-claim-detail.tsx', }, // requiredVersion:false everywhere: the host's copy always wins, so a // patch or major drift between host and plugin cannot fail the load. diff --git a/ui/shared/fleet-api.ts b/ui/shared/fleet-api.ts index 05b65dba..935c2d5f 100644 --- a/ui/shared/fleet-api.ts +++ b/ui/shared/fleet-api.ts @@ -227,3 +227,49 @@ export interface Machine { /** Held on a Machine until Fleet's release and cleanup complete. */ export const MACHINE_FINALIZER = 'fleet.datumapis.com/machine-protection'; + +// Physical inventory: fleet.datumapis.com/v1alpha1 DeviceClaim and Device, +// transcribed from internal/api/inventory/v1alpha1/types.go and +// config/components/inventory/crds/fleet.datumapis.com.yaml. Operators write +// both; status is reserved and has no fields yet. + +export const INVENTORY_API_GROUP = 'fleet.datumapis.com'; +export const INVENTORY_API_VERSION = 'v1alpha1'; + +export interface Provenance { + method: 'Manual'; + recordedBy: string; + recordedAt: string; + reference?: string; +} + +export interface PortPeer { + device: string; + port: string; +} + +export interface DeviceClaim { + apiVersion?: string; + kind?: string; + metadata: ObjectMeta; + spec: { + provenance: Provenance; + expectedIdentity: { manufacturer?: string; model: string; serial?: string }; + placement: { facility: string; rack: string; position: number; height?: number; face: 'front' | 'rear' }; + ports?: { name: string; type?: string; speedMbps?: number; expectedPeer?: PortPeer }[]; + }; +} + +export interface Device { + apiVersion?: string; + kind?: string; + metadata: ObjectMeta; + spec: { + claimRef: LocalReference; + provenance: Provenance; + identity: { manufacturer?: string; model: string; serial?: string; systemUUID?: string }; + bmc?: { endpoint: string }; + interfaces?: { name: string; macAddress?: string; peer?: PortPeer }[]; + unmappedMACAddresses?: string[]; + }; +} From 6e902811556edb4f9bab6bcb683e4f48a466e8bf Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Fri, 20 Nov 2026 12:09:32 -0600 Subject: [PATCH 014/518] feat(inventory): add observational physical NetBox import --- .github/workflows/ci.yml | 1 + .../inventory/crds/fleet.datumapis.com.yaml | 1247 ++++++++++++++++- .../inventory/protected-resources/cable.yaml | 21 + .../protected-resources/facility.yaml | 21 + .../protected-resources/kustomization.yaml | 4 + .../protected-resources/powerfeed.yaml | 21 + .../inventory/protected-resources/rack.yaml | 21 + config/components/inventory/roles/editor.yaml | 16 + config/components/inventory/roles/viewer.yaml | 12 + docs/development/README.md | 23 +- docs/operations/README.md | 1 + docs/operations/netbox-physical-import.md | 240 ++++ docs/operations/physical-inventory.md | 49 +- docs/proposals/fleet-management/MIGRATION.md | 15 + .../fleet-management/inventory-reference.md | 916 ++++++++++++ docs/proposals/fleet-management/inventory.md | 737 +++------- hack/netbox_inventory.py | 711 ++++++++++ hack/test_netbox_inventory.py | 292 ++++ hack/testdata/netbox/candidates.json | 475 +++++++ hack/testdata/netbox/existing.json | 17 + hack/testdata/netbox/mapping.json | 68 + hack/testdata/netbox/snapshot.json | 209 +++ internal/api/inventory/v1alpha1/crd_test.go | 10 +- internal/api/inventory/v1alpha1/physical.go | 175 +++ .../api/inventory/v1alpha1/physical_test.go | 152 ++ internal/api/inventory/v1alpha1/types.go | 63 +- ui/provider/README.md | 17 +- .../src/components/inventory-table.tsx | 7 +- .../components/physical-inventory.test.tsx | 28 + .../src/components/physical-inventory.tsx | 59 + ui/provider/src/inventory.test.ts | 4 +- ui/provider/src/inventory.ts | 18 +- ui/provider/src/lib/api.ts | 24 +- ui/provider/src/lib/inventory-api.test.ts | 33 + ui/provider/src/pages/device-claim-detail.tsx | 17 +- .../src/pages/device-inventory-list.tsx | 4 +- .../src/pages/device-inventory.test.tsx | 6 +- ui/shared/fleet-api.ts | 52 +- 38 files changed, 5082 insertions(+), 704 deletions(-) create mode 100644 config/components/inventory/protected-resources/cable.yaml create mode 100644 config/components/inventory/protected-resources/facility.yaml create mode 100644 config/components/inventory/protected-resources/powerfeed.yaml create mode 100644 config/components/inventory/protected-resources/rack.yaml create mode 100644 docs/operations/netbox-physical-import.md create mode 100644 docs/proposals/fleet-management/inventory-reference.md create mode 100644 hack/netbox_inventory.py create mode 100644 hack/test_netbox_inventory.py create mode 100644 hack/testdata/netbox/candidates.json create mode 100644 hack/testdata/netbox/existing.json create mode 100644 hack/testdata/netbox/mapping.json create mode 100644 hack/testdata/netbox/snapshot.json create mode 100644 internal/api/inventory/v1alpha1/physical.go create mode 100644 internal/api/inventory/v1alpha1/physical_test.go create mode 100644 ui/provider/src/components/physical-inventory.test.tsx create mode 100644 ui/provider/src/components/physical-inventory.tsx create mode 100644 ui/provider/src/lib/inventory-api.test.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 27b179fb..957de3ce 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -21,6 +21,7 @@ jobs: - run: go test ./... - run: go test -race ./... - run: go vet ./... + - run: python3 -m unittest discover -s hack -p test_netbox_inventory.py - run: go run ./test/acceptance/milo/cmd validate --root . - run: kustomize build config/base/crd >/dev/null - run: kustomize build config/milo >/dev/null diff --git a/config/components/inventory/crds/fleet.datumapis.com.yaml b/config/components/inventory/crds/fleet.datumapis.com.yaml index 566569f7..181d6839 100644 --- a/config/components/inventory/crds/fleet.datumapis.com.yaml +++ b/config/components/inventory/crds/fleet.datumapis.com.yaml @@ -6,77 +6,252 @@ metadata: discovery.miloapis.com/parent-contexts: Project spec: group: fleet.datumapis.com - names: {kind: DeviceClaim, listKind: DeviceClaimList, plural: deviceclaims, singular: deviceclaim} + names: + kind: DeviceClaim + listKind: DeviceClaimList + plural: deviceclaims + singular: deviceclaim scope: Namespaced versions: - name: v1alpha1 served: true storage: true - subresources: {status: {}} + subresources: + status: {} additionalPrinterColumns: - - {name: Facility, type: string, jsonPath: .spec.placement.facility} - - {name: Rack, type: string, jsonPath: .spec.placement.rack} - - {name: Position, type: integer, jsonPath: .spec.placement.position} - - {name: Model, type: string, jsonPath: .spec.expectedIdentity.model} - - {name: Recorded At, type: date, jsonPath: .spec.provenance.recordedAt} + - name: Facility + type: string + jsonPath: .spec.placement.facility + - name: Rack + type: string + jsonPath: .spec.placement.rack + - name: Position + type: integer + jsonPath: .spec.placement.position + - name: Model + type: string + jsonPath: .spec.expectedIdentity.model + - name: Recorded At + type: date + jsonPath: .spec.provenance.recordedAt schema: openAPIV3Schema: type: object - required: [spec] + required: + - spec properties: - apiVersion: {type: string} - kind: {type: string} - metadata: {type: object} + apiVersion: + type: string + kind: + type: string + metadata: + type: object spec: type: object - required: [provenance, expectedIdentity, placement] + required: + - provenance + - expectedIdentity + - placement x-kubernetes-validations: - rule: self == oldSelf || self.provenance.recordedAt > oldSelf.provenance.recordedAt message: every change to a claim must advance provenance.recordedAt + - rule: has(self.lifecycle) == has(oldSelf.lifecycle) + message: legacy claims cannot be reinterpreted as installations + - rule: '!has(self.lifecycle) || self.placement == oldSelf.placement' + message: installation placement is immutable; migration requires an explicit handover + - rule: '!has(self.lifecycle) || !has(self.ports) || self.ports.all(p, !has(p.expectedPeer))' + message: Cable is the only expected topology authority for installations + - rule: has(self.lifecycle) == has(self.placement.scope) + message: typed placement requires an installation lifecycle; legacy slots keep their text placement properties: provenance: type: object - required: [method, recordedBy, recordedAt] + required: + - method + - recordedBy + - recordedAt properties: - method: {type: string, enum: [Manual]} - recordedBy: {type: string, minLength: 1, maxLength: 253} - recordedAt: {type: string, format: date-time} - reference: {type: string, minLength: 1, maxLength: 1024} + method: + type: string + enum: + - Manual + - NetBoxImport + recordedBy: + type: string + minLength: 1 + maxLength: 253 + recordedAt: + type: string + format: date-time + reference: + type: string + minLength: 1 + maxLength: 1024 + source: + type: object + properties: + system: + type: string + minLength: 1 + maxLength: 253 + type: + type: string + minLength: 1 + maxLength: 253 + id: + type: string + minLength: 1 + maxLength: 253 + snapshotDigest: + type: string + pattern: ^sha256:[a-f0-9]{64}$ + mappingRevision: + type: string + minLength: 1 + maxLength: 253 + observedAt: + type: string + format: date-time + required: + - system + - type + - id + - snapshotDigest + - mappingRevision + - observedAt + x-kubernetes-validations: + - rule: self.method != 'NetBoxImport' || has(self.source) + message: NetBox imports require source provenance + - rule: has(self.source) == has(oldSelf.source) && (!has(self.source) || (self.source.system == + oldSelf.source.system && self.source.type == oldSelf.source.type && self.source.id == oldSelf.source.id)) + message: source identity is immutable expectedIdentity: type: object - required: [model] + required: + - model properties: - manufacturer: {type: string, maxLength: 253} - model: {type: string, minLength: 1, maxLength: 253} - serial: {type: string, minLength: 1, maxLength: 253} + manufacturer: + type: string + maxLength: 253 + model: + type: string + minLength: 1 + maxLength: 253 + serial: + type: string + minLength: 1 + maxLength: 253 placement: type: object - required: [facility, rack, position, face] properties: - facility: {type: string, minLength: 1, maxLength: 253} - rack: {type: string, minLength: 1, maxLength: 253} - position: {type: integer, format: int32, minimum: 1, maximum: 100} - height: {type: integer, format: int32, minimum: 1, maximum: 100, default: 1} - face: {type: string, enum: [front, rear]} + facility: + type: string + minLength: 1 + maxLength: 253 + rack: + type: string + minLength: 1 + maxLength: 253 + position: + type: integer + format: int32 + minimum: 1 + maximum: 100 + height: + type: integer + format: int32 + minimum: 1 + maximum: 100 + face: + type: string + enum: + - front + - rear + scope: + type: string + enum: + - Facility + - RackMembership + - RackUnits + - NonRackUnitMount + facilityRef: &id001 + type: object + properties: + name: + type: string + maxLength: 253 + pattern: ^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$ + required: + - name + rackRef: *id001 + mount: + type: string + minLength: 1 + maxLength: 253 + x-kubernetes-validations: + - rule: 'has(self.scope) ? (!has(self.facility) && !has(self.rack)) : (has(self.facility) && has(self.rack) + && has(self.position) && has(self.face) && !has(self.facilityRef) && !has(self.rackRef) && !has(self.mount))' + message: choose legacy text placement or typed placement, never both + - rule: '!has(self.scope) || (self.scope == ''Facility'' ? (has(self.facilityRef) && !has(self.rackRef)) + : (has(self.rackRef) && !has(self.facilityRef)))' + message: typed placement requires exactly the reference appropriate to its scope + - rule: '!has(self.scope) || (self.scope == ''RackUnits'' ? (has(self.position) && has(self.height) + && has(self.face) && !has(self.mount)) : (!has(self.position) && !has(self.height) && !has(self.face) + && (self.scope == ''NonRackUnitMount'' ? has(self.mount) : !has(self.mount))))' + message: partial placement cannot assert rack units; non-unit mounts require a mount identifier ports: type: array maxItems: 128 x-kubernetes-list-type: map - x-kubernetes-list-map-keys: [name] + x-kubernetes-list-map-keys: + - name items: type: object - required: [name] + required: + - name properties: - name: {type: string, minLength: 1, maxLength: 63} - type: {type: string, maxLength: 253} - speedMbps: {type: integer, format: int64, minimum: 1} + name: + type: string + minLength: 1 + maxLength: 63 + type: + type: string + maxLength: 253 + speedMbps: + type: integer + format: int64 + minimum: 1 expectedPeer: type: object - required: [device, port] + required: + - device + - port properties: - device: {type: string, minLength: 1, maxLength: 253} - port: {type: string, minLength: 1, maxLength: 253} - status: {type: object} + device: + type: string + minLength: 1 + maxLength: 253 + port: + type: string + minLength: 1 + maxLength: 253 + lifecycle: + type: string + enum: + - Installation + cableRefs: + type: array + maxItems: 256 + items: *id001 + x-kubernetes-list-type: map + x-kubernetes-list-map-keys: + - name + displayName: + type: string + minLength: 1 + maxLength: 253 + status: + type: object --- apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition @@ -86,30 +261,53 @@ metadata: discovery.miloapis.com/parent-contexts: Project spec: group: fleet.datumapis.com - names: {kind: Device, listKind: DeviceList, plural: devices, singular: device} + names: + kind: Device + listKind: DeviceList + plural: devices + singular: device scope: Namespaced versions: - name: v1alpha1 served: true storage: true - subresources: {status: {}} + subresources: + status: {} additionalPrinterColumns: - - {name: Claim, type: string, jsonPath: .spec.claimRef.name} - - {name: Model, type: string, jsonPath: .spec.identity.model} - - {name: Serial, type: string, jsonPath: .spec.identity.serial} - - {name: System UUID, type: string, priority: 1, jsonPath: .spec.identity.systemUUID} - - {name: Recorded At, type: date, jsonPath: .spec.provenance.recordedAt} + - name: Claim + type: string + jsonPath: .spec.claimRef.name + - name: Model + type: string + jsonPath: .spec.identity.model + - name: Serial + type: string + jsonPath: .spec.identity.serial + - name: System UUID + type: string + priority: 1 + jsonPath: .spec.identity.systemUUID + - name: Recorded At + type: date + jsonPath: .spec.provenance.recordedAt schema: openAPIV3Schema: type: object - required: [spec] + required: + - spec properties: - apiVersion: {type: string} - kind: {type: string} - metadata: {type: object} + apiVersion: + type: string + kind: + type: string + metadata: + type: object spec: type: object - required: [claimRef, provenance, identity] + required: + - claimRef + - provenance + - identity x-kubernetes-validations: - rule: self == oldSelf || self.provenance.recordedAt > oldSelf.provenance.recordedAt message: every change to a device must advance provenance.recordedAt @@ -117,66 +315,961 @@ spec: message: claimRef is immutable; bind replacement hardware as a new Device - rule: self.identity == oldSelf.identity message: identity is immutable; a hardware swap is a new Device - - rule: >- - !has(self.interfaces) || self.interfaces.all(a, !has(a.macAddress) || - (self.interfaces.filter(b, has(b.macAddress) && b.macAddress == a.macAddress).size() == 1 && - (!has(self.unmappedMACAddresses) || !(a.macAddress in self.unmappedMACAddresses)))) + - rule: '!has(self.interfaces) || self.interfaces.all(a, !has(a.macAddress) || (self.interfaces.filter(b, + has(b.macAddress) && b.macAddress == a.macAddress).size() == 1 && (!has(self.unmappedMACAddresses) + || !(a.macAddress in self.unmappedMACAddresses))))' message: a MAC address may be recorded only once + - rule: '!has(self.identity.sourceIdentity) || self.provenance.method == "NetBoxImport"' + message: source identity is for observational imports only + - rule: '!has(self.topologyAuthority) || !has(self.interfaces) || self.interfaces.all(p, !has(p.peer))' + message: Cable topology excludes inline peers + - rule: '!has(self.components) || has(self.topologyAuthority)' + message: typed components require Cable topology + - rule: '!has(self.internalMappings) || (has(self.components) && self.internalMappings.all(m, (m.from.componentID + != m.to.componentID || m.from.position != m.to.position) && self.components.exists(c, c.id == m.from.componentID + && m.from.position <= (has(c.positions) ? c.positions : 1)) && self.components.exists(c, c.id == + m.to.componentID && m.to.position <= (has(c.positions) ? c.positions : 1))))' + message: internal mappings must reference present component positions + - rule: '!has(self.internalMappings) || self.internalMappings.all(m, self.internalMappings.filter(n, + n.from == m.from).size() == 1)' + message: each internal source position maps once + - rule: '!has(self.identity.sourceIdentity) || (has(self.provenance.source) && self.identity.sourceIdentity.system + == self.provenance.source.system && self.identity.sourceIdentity.type == self.provenance.source.type + && self.identity.sourceIdentity.id == self.provenance.source.id)' + message: observational identity must match provenance source identity + - rule: '!has(self.internalMappings) || (has(self.components) && self.internalMappings.all(m, self.components.exists(c, + c.id == m.from.componentID && c.type == ''FrontPort'') ? self.components.exists(c, c.id == m.to.componentID + && c.type == ''RearPort'') : (self.components.exists(c, c.id == m.from.componentID && c.type == + ''PowerOutlet'') && self.components.exists(c, c.id == m.to.componentID && c.type == ''PowerInlet''))))' + message: internal paths must map front to rear or power outlet to inlet + - rule: '!has(self.internalMappings) || (has(self.components) && self.internalMappings.all(m, !self.components.exists(c, + c.id == m.from.componentID && c.type == ''FrontPort'') || self.internalMappings.filter(n, n.to.componentID + == m.to.componentID && n.to.position == m.to.position).size() == 1))' + message: a pass-through rear position can be mapped only once + - rule: '!has(self.serviceAssociations) || (has(self.components) && self.serviceAssociations.all(a, + self.components.exists(c, c.id == a.componentID)))' + message: service associations must reference present components properties: claimRef: type: object - required: [name] + required: + - name properties: - name: {type: string, minLength: 1, maxLength: 253} + name: + type: string + minLength: 1 + maxLength: 253 provenance: type: object - required: [method, recordedBy, recordedAt] + required: + - method + - recordedBy + - recordedAt properties: - method: {type: string, enum: [Manual]} - recordedBy: {type: string, minLength: 1, maxLength: 253} - recordedAt: {type: string, format: date-time} - reference: {type: string, minLength: 1, maxLength: 1024} + method: + type: string + enum: + - Manual + - NetBoxImport + recordedBy: + type: string + minLength: 1 + maxLength: 253 + recordedAt: + type: string + format: date-time + reference: + type: string + minLength: 1 + maxLength: 1024 + source: + type: object + properties: + system: + type: string + minLength: 1 + maxLength: 253 + type: + type: string + minLength: 1 + maxLength: 253 + id: + type: string + minLength: 1 + maxLength: 253 + snapshotDigest: + type: string + pattern: ^sha256:[a-f0-9]{64}$ + mappingRevision: + type: string + minLength: 1 + maxLength: 253 + observedAt: + type: string + format: date-time + required: + - system + - type + - id + - snapshotDigest + - mappingRevision + - observedAt + x-kubernetes-validations: + - rule: self.method != 'NetBoxImport' || has(self.source) + message: NetBox imports require source provenance + - rule: has(self.source) == has(oldSelf.source) && (!has(self.source) || (self.source.system == + oldSelf.source.system && self.source.type == oldSelf.source.type && self.source.id == oldSelf.source.id)) + message: source identity is immutable identity: type: object - required: [model] + required: + - model x-kubernetes-validations: - - rule: has(self.serial) || has(self.systemUUID) - message: a device needs a serial or a system UUID + - rule: has(self.serial) || has(self.systemUUID) || has(self.sourceIdentity) + message: a device needs serial, UUID, or an observational source identity properties: - manufacturer: {type: string, maxLength: 253} - model: {type: string, minLength: 1, maxLength: 253} - serial: {type: string, minLength: 1, maxLength: 253} - systemUUID: {type: string, pattern: '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$'} + manufacturer: + type: string + maxLength: 253 + model: + type: string + minLength: 1 + maxLength: 253 + serial: + type: string + minLength: 1 + maxLength: 253 + systemUUID: + type: string + pattern: ^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$ + sourceIdentity: &id001 + type: object + properties: + system: + type: string + minLength: 1 + maxLength: 253 + type: + type: string + minLength: 1 + maxLength: 253 + id: + type: string + minLength: 1 + maxLength: 253 + required: + - system + - type + - id bmc: type: object - required: [endpoint] + required: + - endpoint properties: endpoint: type: string maxLength: 2048 x-kubernetes-validations: - - rule: isURL(self) && url(self).getScheme() == 'https' && !self.contains('@') && url(self).getHostname() != '' + - rule: isURL(self) && url(self).getScheme() == 'https' && !self.contains('@') && url(self).getHostname() + != '' message: bmc.endpoint must be an https URL without credentials interfaces: type: array maxItems: 32 x-kubernetes-list-type: map - x-kubernetes-list-map-keys: [name] + x-kubernetes-list-map-keys: + - name items: type: object - required: [name] + required: + - name properties: - name: {type: string, minLength: 1, maxLength: 63} - macAddress: {type: string, maxLength: 17, pattern: '^([0-9a-f]{2}:){5}[0-9a-f]{2}$'} + name: + type: string + minLength: 1 + maxLength: 63 + macAddress: + type: string + maxLength: 17 + pattern: ^([0-9a-f]{2}:){5}[0-9a-f]{2}$ peer: type: object - required: [device, port] + required: + - device + - port properties: - device: {type: string, minLength: 1, maxLength: 253} - port: {type: string, minLength: 1, maxLength: 253} + device: + type: string + minLength: 1 + maxLength: 253 + port: + type: string + minLength: 1 + maxLength: 253 unmappedMACAddresses: type: array maxItems: 32 x-kubernetes-list-type: set - items: {type: string, maxLength: 17, pattern: '^([0-9a-f]{2}:){5}[0-9a-f]{2}$'} - status: {type: object} + items: + type: string + maxLength: 17 + pattern: ^([0-9a-f]{2}:){5}[0-9a-f]{2}$ + assetTag: + type: string + minLength: 1 + maxLength: 253 + providerHostRef: *id001 + components: + type: array + maxItems: 256 + items: + type: object + properties: + id: + type: string + minLength: 1 + maxLength: 63 + name: + type: string + minLength: 1 + maxLength: 253 + type: + type: string + enum: + - NetworkPort + - PowerInlet + - PowerOutlet + - ConsolePort + - ConsoleServerPort + - FrontPort + - RearPort + - Module + - InventoryItem + - DeviceBay + connector: + type: string + minLength: 1 + maxLength: 253 + positions: + type: integer + minimum: 1 + maximum: 256 + serial: + type: string + minLength: 1 + maxLength: 253 + assetTag: + type: string + minLength: 1 + maxLength: 253 + sourceRef: *id001 + required: + - id + - name + - type + x-kubernetes-list-type: map + x-kubernetes-list-map-keys: + - id + internalMappings: + type: array + maxItems: 256 + items: + type: object + properties: + from: &id002 + type: object + properties: + componentID: + type: string + minLength: 1 + maxLength: 63 + position: + type: integer + minimum: 1 + maximum: 256 + required: + - componentID + - position + to: *id002 + required: + - from + - to + serviceAssociations: + type: array + maxItems: 128 + items: + type: object + properties: + serviceRef: *id001 + componentID: + type: string + minLength: 1 + maxLength: 63 + required: + - serviceRef + - componentID + topologyAuthority: + type: string + enum: + - Cable + displayName: + type: string + minLength: 1 + maxLength: 253 + modelShape: + type: object + properties: + heightUnits: + type: number + minimum: 0 + maximum: 100 + fullDepth: + type: boolean + status: + type: object +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: facilities.fleet.datumapis.com + annotations: + discovery.miloapis.com/parent-contexts: Project +spec: + group: fleet.datumapis.com + names: + kind: Facility + listKind: FacilityList + plural: facilities + singular: facility + scope: Namespaced + versions: + - name: v1alpha1 + served: true + storage: true + subresources: + status: {} + schema: + openAPIV3Schema: + type: object + properties: + apiVersion: + type: string + kind: + type: string + metadata: + type: object + spec: + type: object + properties: + displayName: + type: string + minLength: 1 + maxLength: 253 + provenance: + type: object + required: + - method + - recordedBy + - recordedAt + properties: + method: + type: string + enum: + - Manual + - NetBoxImport + recordedBy: + type: string + minLength: 1 + maxLength: 253 + recordedAt: + type: string + format: date-time + reference: + type: string + minLength: 1 + maxLength: 1024 + source: + type: object + properties: + system: + type: string + minLength: 1 + maxLength: 253 + type: + type: string + minLength: 1 + maxLength: 253 + id: + type: string + minLength: 1 + maxLength: 253 + snapshotDigest: + type: string + pattern: ^sha256:[a-f0-9]{64}$ + mappingRevision: + type: string + minLength: 1 + maxLength: 253 + observedAt: + type: string + format: date-time + required: + - system + - type + - id + - snapshotDigest + - mappingRevision + - observedAt + x-kubernetes-validations: + - rule: self.method != 'NetBoxImport' || has(self.source) + message: NetBox imports require source provenance + - rule: has(self.source) == has(oldSelf.source) && (!has(self.source) || (self.source.system == + oldSelf.source.system && self.source.type == oldSelf.source.type && self.source.id == oldSelf.source.id)) + message: source identity is immutable + locationRef: + type: object + properties: + name: + type: string + maxLength: 253 + pattern: ^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$ + required: + - name + required: + - displayName + - provenance + x-kubernetes-validations: + - rule: self == oldSelf || self.provenance.recordedAt > oldSelf.provenance.recordedAt + message: every spec change must advance provenance.recordedAt + status: + type: object + required: + - spec +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: racks.fleet.datumapis.com + annotations: + discovery.miloapis.com/parent-contexts: Project +spec: + group: fleet.datumapis.com + names: + kind: Rack + listKind: RackList + plural: racks + singular: rack + scope: Namespaced + versions: + - name: v1alpha1 + served: true + storage: true + subresources: + status: {} + schema: + openAPIV3Schema: + type: object + properties: + apiVersion: + type: string + kind: + type: string + metadata: + type: object + spec: + type: object + properties: + displayName: + type: string + minLength: 1 + maxLength: 253 + provenance: + type: object + required: + - method + - recordedBy + - recordedAt + properties: + method: + type: string + enum: + - Manual + - NetBoxImport + recordedBy: + type: string + minLength: 1 + maxLength: 253 + recordedAt: + type: string + format: date-time + reference: + type: string + minLength: 1 + maxLength: 1024 + source: + type: object + properties: + system: + type: string + minLength: 1 + maxLength: 253 + type: + type: string + minLength: 1 + maxLength: 253 + id: + type: string + minLength: 1 + maxLength: 253 + snapshotDigest: + type: string + pattern: ^sha256:[a-f0-9]{64}$ + mappingRevision: + type: string + minLength: 1 + maxLength: 253 + observedAt: + type: string + format: date-time + required: + - system + - type + - id + - snapshotDigest + - mappingRevision + - observedAt + x-kubernetes-validations: + - rule: self.method != 'NetBoxImport' || has(self.source) + message: NetBox imports require source provenance + - rule: has(self.source) == has(oldSelf.source) && (!has(self.source) || (self.source.system == + oldSelf.source.system && self.source.type == oldSelf.source.type && self.source.id == oldSelf.source.id)) + message: source identity is immutable + facilityRef: + type: object + properties: + name: + type: string + maxLength: 253 + pattern: ^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$ + required: + - name + heightUnits: + type: integer + minimum: 1 + maximum: 100 + required: + - displayName + - provenance + - facilityRef + x-kubernetes-validations: + - rule: self == oldSelf || self.provenance.recordedAt > oldSelf.provenance.recordedAt + message: every spec change must advance provenance.recordedAt + status: + type: object + required: + - spec +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: cables.fleet.datumapis.com + annotations: + discovery.miloapis.com/parent-contexts: Project +spec: + group: fleet.datumapis.com + names: + kind: Cable + listKind: CableList + plural: cables + singular: cable + scope: Namespaced + versions: + - name: v1alpha1 + served: true + storage: true + subresources: + status: {} + schema: + openAPIV3Schema: + type: object + properties: + apiVersion: + type: string + kind: + type: string + metadata: + type: object + spec: + type: object + properties: + displayName: + type: string + minLength: 1 + maxLength: 253 + provenance: + type: object + required: + - method + - recordedBy + - recordedAt + properties: + method: + type: string + enum: + - Manual + - NetBoxImport + recordedBy: + type: string + minLength: 1 + maxLength: 253 + recordedAt: + type: string + format: date-time + reference: + type: string + minLength: 1 + maxLength: 1024 + source: + type: object + properties: + system: + type: string + minLength: 1 + maxLength: 253 + type: + type: string + minLength: 1 + maxLength: 253 + id: + type: string + minLength: 1 + maxLength: 253 + snapshotDigest: + type: string + pattern: ^sha256:[a-f0-9]{64}$ + mappingRevision: + type: string + minLength: 1 + maxLength: 253 + observedAt: + type: string + format: date-time + required: + - system + - type + - id + - snapshotDigest + - mappingRevision + - observedAt + x-kubernetes-validations: + - rule: self.method != 'NetBoxImport' || has(self.source) + message: NetBox imports require source provenance + - rule: has(self.source) == has(oldSelf.source) && (!has(self.source) || (self.source.system == + oldSelf.source.system && self.source.type == oldSelf.source.type && self.source.id == oldSelf.source.id)) + message: source identity is immutable + medium: + type: string + enum: + - Copper + - Fiber + - Power + - Console + - Unknown + lanes: + type: array + maxItems: 64 + items: + type: object + properties: + id: + type: string + minLength: 1 + maxLength: 63 + a: &id002 + type: object + properties: + deviceRef: &id001 + type: object + properties: + name: + type: string + maxLength: 253 + pattern: ^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$ + required: + - name + powerFeedRef: *id001 + componentID: + type: string + minLength: 1 + maxLength: 63 + position: + type: integer + minimum: 1 + maximum: 256 + required: + - componentID + - position + x-kubernetes-validations: + - rule: has(self.deviceRef) != has(self.powerFeedRef) + message: exactly one local endpoint owner is required + b: *id002 + required: + - id + - a + - b + x-kubernetes-validations: + - rule: '!(self.a.componentID == self.b.componentID && self.a.position == self.b.position && ((has(self.a.deviceRef) + && has(self.b.deviceRef) && self.a.deviceRef.name == self.b.deviceRef.name) || (has(self.a.powerFeedRef) + && has(self.b.powerFeedRef) && self.a.powerFeedRef.name == self.b.powerFeedRef.name)))' + message: a cable lane must have different endpoints + x-kubernetes-list-type: map + x-kubernetes-list-map-keys: + - id + minItems: 1 + required: + - displayName + - provenance + - medium + - lanes + x-kubernetes-validations: + - rule: self.lanes.all(l, self.lanes.filter(m, (m.a.componentID == l.a.componentID && m.a.position == + l.a.position && ((has(m.a.deviceRef) && has(l.a.deviceRef) && m.a.deviceRef.name == l.a.deviceRef.name) + || (has(m.a.powerFeedRef) && has(l.a.powerFeedRef) && m.a.powerFeedRef.name == l.a.powerFeedRef.name))) + || (m.b.componentID == l.a.componentID && m.b.position == l.a.position && ((has(m.b.deviceRef) && + has(l.a.deviceRef) && m.b.deviceRef.name == l.a.deviceRef.name) || (has(m.b.powerFeedRef) && has(l.a.powerFeedRef) + && m.b.powerFeedRef.name == l.a.powerFeedRef.name)))).size() == 1 && self.lanes.filter(m, (m.a.componentID + == l.b.componentID && m.a.position == l.b.position && ((has(m.a.deviceRef) && has(l.b.deviceRef) + && m.a.deviceRef.name == l.b.deviceRef.name) || (has(m.a.powerFeedRef) && has(l.b.powerFeedRef) + && m.a.powerFeedRef.name == l.b.powerFeedRef.name))) || (m.b.componentID == l.b.componentID && m.b.position + == l.b.position && ((has(m.b.deviceRef) && has(l.b.deviceRef) && m.b.deviceRef.name == l.b.deviceRef.name) + || (has(m.b.powerFeedRef) && has(l.b.powerFeedRef) && m.b.powerFeedRef.name == l.b.powerFeedRef.name)))).size() + == 1) + message: each termination position can occur only once in a cable + - rule: self == oldSelf || self.provenance.recordedAt > oldSelf.provenance.recordedAt + message: every spec change must advance provenance.recordedAt + status: + type: object + required: + - spec +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: powerfeeds.fleet.datumapis.com + annotations: + discovery.miloapis.com/parent-contexts: Project +spec: + group: fleet.datumapis.com + names: + kind: PowerFeed + listKind: PowerFeedList + plural: powerfeeds + singular: powerfeed + scope: Namespaced + versions: + - name: v1alpha1 + served: true + storage: true + subresources: + status: {} + schema: + openAPIV3Schema: + type: object + properties: + apiVersion: + type: string + kind: + type: string + metadata: + type: object + spec: + type: object + properties: + displayName: + type: string + minLength: 1 + maxLength: 253 + provenance: + type: object + required: + - method + - recordedBy + - recordedAt + properties: + method: + type: string + enum: + - Manual + - NetBoxImport + recordedBy: + type: string + minLength: 1 + maxLength: 253 + recordedAt: + type: string + format: date-time + reference: + type: string + minLength: 1 + maxLength: 1024 + source: + type: object + properties: + system: + type: string + minLength: 1 + maxLength: 253 + type: + type: string + minLength: 1 + maxLength: 253 + id: + type: string + minLength: 1 + maxLength: 253 + snapshotDigest: + type: string + pattern: ^sha256:[a-f0-9]{64}$ + mappingRevision: + type: string + minLength: 1 + maxLength: 253 + observedAt: + type: string + format: date-time + required: + - system + - type + - id + - snapshotDigest + - mappingRevision + - observedAt + x-kubernetes-validations: + - rule: self.method != 'NetBoxImport' || has(self.source) + message: NetBox imports require source provenance + - rule: has(self.source) == has(oldSelf.source) && (!has(self.source) || (self.source.system == + oldSelf.source.system && self.source.type == oldSelf.source.type && self.source.id == oldSelf.source.id)) + message: source identity is immutable + facilityRef: &id001 + type: object + properties: + name: + type: string + maxLength: 253 + pattern: ^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$ + required: + - name + rackRef: *id001 + supply: + type: object + properties: + type: + type: string + enum: + - AC + - DC + - Unknown + voltageV: + type: integer + minimum: 1 + maximum: 100000 + currentA: + type: integer + minimum: 1 + maximum: 100000 + phase: + type: string + enum: + - single-phase + - three-phase + - Unknown + required: + - type + terminations: + type: array + maxItems: 256 + items: + type: object + properties: + id: + type: string + minLength: 1 + maxLength: 63 + name: + type: string + minLength: 1 + maxLength: 253 + type: + type: string + enum: + - NetworkPort + - PowerInlet + - PowerOutlet + - ConsolePort + - ConsoleServerPort + - FrontPort + - RearPort + - Module + - InventoryItem + - DeviceBay + connector: + type: string + minLength: 1 + maxLength: 253 + positions: + type: integer + minimum: 1 + maximum: 256 + serial: + type: string + minLength: 1 + maxLength: 253 + assetTag: + type: string + minLength: 1 + maxLength: 253 + sourceRef: &id002 + type: object + properties: + system: + type: string + minLength: 1 + maxLength: 253 + type: + type: string + minLength: 1 + maxLength: 253 + id: + type: string + minLength: 1 + maxLength: 253 + required: + - system + - type + - id + required: + - id + - name + - type + x-kubernetes-list-type: map + x-kubernetes-list-map-keys: + - id + minItems: 1 + upstreamSources: + type: array + maxItems: 64 + items: *id002 + required: + - displayName + - provenance + - facilityRef + - terminations + x-kubernetes-validations: + - rule: self.terminations.all(t, t.type == 'PowerOutlet') + message: feed terminations must be power outlets + - rule: self == oldSelf || self.provenance.recordedAt > oldSelf.provenance.recordedAt + message: every spec change must advance provenance.recordedAt + status: + type: object + required: + - spec diff --git a/config/components/inventory/protected-resources/cable.yaml b/config/components/inventory/protected-resources/cable.yaml new file mode 100644 index 00000000..f92364db --- /dev/null +++ b/config/components/inventory/protected-resources/cable.yaml @@ -0,0 +1,21 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: fleet.datumapis.com-cable +spec: + serviceRef: + name: fleet.datumapis.com + kind: Cable + plural: cables + singular: cable + permissions: + - list + - get + - watch + - create + - update + - patch + - delete + parentResources: + - apiGroup: resourcemanager.miloapis.com + kind: Project diff --git a/config/components/inventory/protected-resources/facility.yaml b/config/components/inventory/protected-resources/facility.yaml new file mode 100644 index 00000000..5a84110a --- /dev/null +++ b/config/components/inventory/protected-resources/facility.yaml @@ -0,0 +1,21 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: fleet.datumapis.com-facility +spec: + serviceRef: + name: fleet.datumapis.com + kind: Facility + plural: facilities + singular: facility + permissions: + - list + - get + - watch + - create + - update + - patch + - delete + parentResources: + - apiGroup: resourcemanager.miloapis.com + kind: Project diff --git a/config/components/inventory/protected-resources/kustomization.yaml b/config/components/inventory/protected-resources/kustomization.yaml index 0a5454da..06c15c1a 100644 --- a/config/components/inventory/protected-resources/kustomization.yaml +++ b/config/components/inventory/protected-resources/kustomization.yaml @@ -3,3 +3,7 @@ kind: Kustomization resources: - deviceclaim.yaml - device.yaml + - facility.yaml + - rack.yaml + - cable.yaml + - powerfeed.yaml diff --git a/config/components/inventory/protected-resources/powerfeed.yaml b/config/components/inventory/protected-resources/powerfeed.yaml new file mode 100644 index 00000000..f731d7df --- /dev/null +++ b/config/components/inventory/protected-resources/powerfeed.yaml @@ -0,0 +1,21 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: fleet.datumapis.com-powerfeed +spec: + serviceRef: + name: fleet.datumapis.com + kind: PowerFeed + plural: powerfeeds + singular: powerfeed + permissions: + - list + - get + - watch + - create + - update + - patch + - delete + parentResources: + - apiGroup: resourcemanager.miloapis.com + kind: Project diff --git a/config/components/inventory/protected-resources/rack.yaml b/config/components/inventory/protected-resources/rack.yaml new file mode 100644 index 00000000..b1f974aa --- /dev/null +++ b/config/components/inventory/protected-resources/rack.yaml @@ -0,0 +1,21 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: fleet.datumapis.com-rack +spec: + serviceRef: + name: fleet.datumapis.com + kind: Rack + plural: racks + singular: rack + permissions: + - list + - get + - watch + - create + - update + - patch + - delete + parentResources: + - apiGroup: resourcemanager.miloapis.com + kind: Project diff --git a/config/components/inventory/roles/editor.yaml b/config/components/inventory/roles/editor.yaml index e5e28191..fd48db59 100644 --- a/config/components/inventory/roles/editor.yaml +++ b/config/components/inventory/roles/editor.yaml @@ -18,3 +18,19 @@ spec: - fleet.datumapis.com/devices.update - fleet.datumapis.com/devices.patch - fleet.datumapis.com/devices.delete + - fleet.datumapis.com/facilities.create + - fleet.datumapis.com/facilities.update + - fleet.datumapis.com/facilities.patch + - fleet.datumapis.com/facilities.delete + - fleet.datumapis.com/racks.create + - fleet.datumapis.com/racks.update + - fleet.datumapis.com/racks.patch + - fleet.datumapis.com/racks.delete + - fleet.datumapis.com/cables.create + - fleet.datumapis.com/cables.update + - fleet.datumapis.com/cables.patch + - fleet.datumapis.com/cables.delete + - fleet.datumapis.com/powerfeeds.create + - fleet.datumapis.com/powerfeeds.update + - fleet.datumapis.com/powerfeeds.patch + - fleet.datumapis.com/powerfeeds.delete diff --git a/config/components/inventory/roles/viewer.yaml b/config/components/inventory/roles/viewer.yaml index db0d7f9a..32963fa4 100644 --- a/config/components/inventory/roles/viewer.yaml +++ b/config/components/inventory/roles/viewer.yaml @@ -14,3 +14,15 @@ spec: - fleet.datumapis.com/devices.list - fleet.datumapis.com/devices.get - fleet.datumapis.com/devices.watch + - fleet.datumapis.com/facilities.get + - fleet.datumapis.com/facilities.list + - fleet.datumapis.com/facilities.watch + - fleet.datumapis.com/racks.get + - fleet.datumapis.com/racks.list + - fleet.datumapis.com/racks.watch + - fleet.datumapis.com/cables.get + - fleet.datumapis.com/cables.list + - fleet.datumapis.com/cables.watch + - fleet.datumapis.com/powerfeeds.get + - fleet.datumapis.com/powerfeeds.list + - fleet.datumapis.com/powerfeeds.watch diff --git a/docs/development/README.md b/docs/development/README.md index d4c274de..e8900d73 100644 --- a/docs/development/README.md +++ b/docs/development/README.md @@ -704,22 +704,29 @@ corrupt or uses an unsupported schema version. ## Physical inventory subset -`internal/api/inventory/v1alpha1` defines `DeviceClaim`, the plan for one rack -slot, and `Device`, the asset bound to one claim. Operators write both by hand -into the provider project in Milo. `config/components/inventory` holds their +`internal/api/inventory/v1alpha1` defines Facility, Rack, DeviceClaim, Device, +Cable and PowerFeed records. Legacy slot claims coexist with new observational +installation claims; no move or replacement handover is automated. Records live +in the provider project in Milo. `config/components/inventory` holds their CRDs, ProtectedResources, and the `fleet.datumapis.com-inventory-viewer` and `-editor` roles. Only `config/milo` includes it. -CEL requires `Manual` provenance on both kinds and requires every edit to +CEL requires `Manual` or source-attributed `NetBoxImport` provenance and every edit to advance `recordedAt`. It keeps a Device's `claimRef` and identity immutable, rejects duplicate or ambiguous MACs, and accepts only credential-free `https` BMC endpoints. Status is a reserved subresource with no fields and no writer. No metal role grants inventory access. -The staff portal plugin's read-only Inventory tab lists claims and shows each -claim's bound Devices. Unit tests run the API server's validation offline and -check the IAM shape. See -[Planning and registering physical devices](../operations/physical-inventory.md). +The staff portal plugin's read-only Inventory tab pages through all six kinds, +shows physical relationships and components, and can inspect a private import +report locally. Multiple historical bindings remain ambiguous rather than being +resolved by edit time. Python's standard-library `hack/netbox_inventory.py` +exports sanitized GET-only NetBox snapshots and prepares an offline create-only +handoff to the existing Flux writer. Unit tests run API-server validation offline, +check IAM and exercise pagination, source conflicts, omissions and interrupted +imports. See [safe NetBox evaluation](../operations/netbox-physical-import.md). +No live source coverage, deployed revision, physical verification, concurrent +reservation, deletion safety, adoption or new hardware-effect path is established. ## Build, test, and run diff --git a/docs/operations/README.md b/docs/operations/README.md index 8139c173..1f1fdf99 100644 --- a/docs/operations/README.md +++ b/docs/operations/README.md @@ -18,6 +18,7 @@ integrations. Real provider support and live Milo acceptance tests are incomplet | Drive the same pipeline through Redfish instead of libvirt | [Redfish-mode acceptance](redfish-lab.md) (`task multiplane:redfish-acceptance`) | Redfish executor discovery, one-time PXE/disk boot overrides, power, lost-response recovery and a booted wipe cleanup, against the unmodified DMTF Redfish Interface Emulator with a lab-only libvirt adapter and two persistent lab VMs; synthetic credentials and networking; not physical BMC or hardware qualification | | Publish physical-side DHCP reservations for network boot | [Boot network](boot-network.md) | Per-asset BMC endpoints and provisioning attachments, a reservation feed 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 attributable provenance and immutable identity and binding, shown read-only in the staff portal; no capacity or hardware effect; unit tested | +| Review and import NetBox's physical side | [Safe physical snapshot and GitOps handoff](netbox-physical-import.md) | Six physical kinds, typed components and relationships, per-record coverage reports and additive handoff to the existing writer; no live import, readiness or provisioning | | Render deployment bundles and supply environment inputs | [Deployment manifests](../../config/README.md) | Packaging and security boundaries, not runtime readiness | | Run the manager across consuming projects | [Project discovery](../../config/README.md#project-discovery) | Discovery, per-project isolation, departure, role bindings, and readiness | | Exercise Milo-routed synthetic staging | [Synthetic staging configuration](../../config/README.md#environment-owned-inputs) | Restricted synthetic publication and lifecycle behavior, not production authority | diff --git a/docs/operations/netbox-physical-import.md b/docs/operations/netbox-physical-import.md new file mode 100644 index 00000000..7cac4a7c --- /dev/null +++ b/docs/operations/netbox-physical-import.md @@ -0,0 +1,240 @@ +# Evaluate NetBox physical inventory safely + +[Physical inventory](physical-inventory.md) · [Inventory proposal](../proposals/fleet-management/inventory.md) · [Detailed proposed contracts](../proposals/fleet-management/inventory-reference.md) + +This milestone provides six provider-project inventory kinds, read-only staff +browsing, a GET-only NetBox snapshot command, and an **offline, create-only GitOps +handoff**. It does not apply anything to Fleet or NetBox. It is not a verification, +reservation, adoption, enrollment, or provisioning controller. + +## What exists and what remains unknown + +`Facility`, `Rack`, `DeviceClaim`, `Device`, `Cable`, and `PowerFeed` live in the +existing provider project's Milo control plane. No database, management-cluster +copy, new catalog service, or independently running importer was introduced. +`config/milo` installs their CRDs, ProtectedResources and inventory roles. Existing +consumer Metal roles still grant no inventory access; inventory roles do not +grant status writes. Staff use their own identity through the existing Milo proxy. + +The CRDs validate local shapes, provenance, immutable asset/claim identity, +placement scope, component uniqueness, internal component positions, and Cable +lane multiplicity. The offline planner checks local references, compatible +component categories, and conflicting cable terminations against the supplied +Fleet snapshot. **These checks are not concurrent reservations or cross-object +API admission.** A direct API writer can still create dangling references or +cross-object conflicts; do not interpret successful creation as acceptance. +No qualified physical verification, dependency reservation, deletion protection, +move/replacement handover, electrical budget, or eligibility publisher exists. +No status field is populated. Free space, active binding, redundancy and readiness +remain Unknown. Existing editor delete permissions are not a safe retirement API. + +### Compatibility and migration decisions + +- Existing long-lived slot claims keep their names, text placement, ports, and + historical Device bindings. Existing `Device.spec.identity` and `claimRef` + remain immutable. MachineCapacity and its `deviceRef` are not modified. +- New imported claims use `lifecycle: Installation` and typed placement. This + mode cannot be added to a legacy slot; an installation's placement is immutable. + This is an observational installation record, **not** a reservation or an + accepted plan. Moving an existing asset remains blocked on the proposal's + explicit handover protocol; the importer does not create a replacement identity + to work around immutability. +- A Facility reference means no rack is asserted. `RackMembership` records a known + rack but forbids position, height and face. The importer deliberately imports + no exact rack-unit positions, including seemingly plausible positions. This + prevents servers.com's generated 1U placements from becoming occupied or + verified footprints. The API also represents exact `RackUnits` and + `NonRackUnitMount` plans for separately reviewed manual records. +- `height` no longer defaults to 1 in admission: doing so invents a footprint on + partial placements. Previously stored defaulted values remain unchanged; legacy + UI rendering still treats omitted legacy height as one. New exact-unit plans + must supply height. `Device.modelShape` dimensions do not establish occupancy. +- Devices without a genuine serial may have an immutable `identity.sourceIdentity` + matching import provenance. This is a source-record identity, **not authenticated + chassis identity**. A provider host ID is `providerHostRef`; an asset tag is + `assetTag`, never a serial. The importer quarantines potential collisions with + legacy serials/provider IDs rather than rewriting them. +- Typed Devices opt into `topologyAuthority: Cable` and cannot contain inline + peers. New installation claims cannot contain expected inline peers. Existing + inline peers are retained as unmigrated history; they are not automatically + converted or deleted. Cable endpoints name same-namespace Device components or + PowerFeed terminations; unbound claim endpoints are deferred. No second expected + topology graph is written by the importer. +- Snapshot digest, source instance/class/ID, observation time and mapping revision + are retained in provenance. `recordedBy` identifies the offline tool, not an + authenticated source author. Milo/Git audit identifies the actual submitting + user. Imported source identity cannot change in place. Re-import of matching + physical fields is a no-op; differing existing records are quarantined. Changes + require a separate reviewed correction, not last-import-wins. + +## Source coverage + +The exporter discovers **every advertised DCIM and circuits collection**, follows +pagination, and lists errors or missing required collections. The parameterized +`dcim/connected-device` lookup is +explicitly listed under `excludedEndpoints`, rather than mistaken for a collection. +The result is a sequential observation with bounded requests, not a transactional +NetBox database snapshot. +Changing counts, duplicate IDs and pagination cycles fail the affected collection. +Counts can remain equal while content changes; quiesce loaders and rerun for a +stable review. Repeated failed reads never become complete coverage. + +The report classifies every fetched record. `imported` means representable in a +candidate (or already identical in the supplied Fleet snapshot), **not applied**. +`unresolved` means mapping, identity, or dependency needs review. `unsupported` +means an adapter cannot faithfully represent that class/shape. `excluded` always +has a reason. Collection completeness and record parity are distinct: a complete +fetch may still contain many unresolved or unsupported records. + +| Source classes | Treatment | +| --- | --- | +| `dcim/sites`, `dcim/locations` | Explicit premises mapping only. One metro Site may map to several Facilities. Unmapped records stay unresolved; no Fleet policy Site is created. | +| `dcim/racks` | Explicit Facility mapping, label and known height. No free-capacity inference. | +| `dcim/devices`, `device-types`, `manufacturers` | Explicit physical/virtual and serial interpretation; model metadata, optional dimensions, separate asset tag/provider identity. NetActuate/hosted-VM hints force exclusion. Supporting catalog rows are classified excluded as independent assets; referenced model facts are consumed. | +| `interfaces`, `power-ports`, `power-outlets`, `console-ports`, `console-server-ports`, `front-ports`, `rear-ports` | Typed Device components with source IDs. Logical LAG/bridge/virtual interfaces excluded. Front/rear mappings and outlet/input dependencies retained; missing relationships remain Unknown. | +| `modules`, `inventory-items`, `device-bays` | Typed component records, not public kinds. Nested installation/parent semantics not represented by these fields remain in the private source snapshot; these are not component-incarnation controllers. | +| `cables` | Simple, reviewed-medium cables with resolvable physical endpoints. Multi-termination/breakout imports require explicit reviewed lanes covering every source termination on its original side; unsupported mappings never become all-to-all paths. Multi-position trunks never silently collapse to position one. | +| `power-panels`, `power-feeds` | Feed supply ratings and terminations, external panel dependencies. No fabricated panel Device, derated budget, independent UPS proof or usable power reservation. | +| `circuits/circuits`, `circuit-terminations` | Explicit service-owner identifiers and mapped local component associations; no new Circuit kind, service lifecycle, billing, or routing. Unmapped demarcations remain unresolved. | +| Device/module/port templates, regions, site groups, rack roles, virtual chassis, circuit/provider catalogs | Explicitly excluded as independent installed physical assets; reasons recorded per row. | +| Other advertised classes (including new NetBox-version additions) | Fetched and reported unsupported, never silently discarded. | + +IPAM, VLANs, VRFs, routing, virtualization collections, billing and provisioning +are explicitly outside this export. VMs stored in **DCIM** are still inspected and +excluded per record. OOB IP lists and credential/custom-field bodies are not copied; +existing restricted Device BMC facts remain untouched. Sanitization uses a recursive +physical-field allowlist and excludes URLs, comments, custom fields and config +contexts. This intentionally is **not a lossless NetBox backup**. Exports still +contain private asset identities, serials and topology and must stay outside Git. + +## Start with the checked-in synthetic example + +Python 3 uses only the standard library. No provider SDK or cluster access is +needed. Output directories must not already exist; files are mode 0600 inside +mode 0700 directories. No command overwrites a previous run. +Output paths inside a Git checkout are refused, including worktrees. + +```sh +python3 hack/netbox_inventory.py plan \ + --snapshot hack/testdata/netbox/snapshot.json \ + --mapping hack/testdata/netbox/mapping.json \ + --output /private/tmp/fleet-physical-report-example +``` + +Only `report.json` is emitted by default. Inspect every unresolved/unsupported +row; the example intentionally leaves a room mapping unresolved. Staff can open +the report with the Inventory tab's local file picker; its contents are not +uploaded. The portal shows restricted/loading/empty states, paginated collections, +asset components, facility/rack membership, feeds and cables. Multiple historical +Devices on one claim do not select the most recently edited record as active. + +To exercise the explicit handoff **with synthetic data only**: + +```sh +python3 hack/netbox_inventory.py plan \ + --snapshot hack/testdata/netbox/snapshot.json \ + --mapping hack/testdata/netbox/mapping.json \ + --existing hack/testdata/netbox/existing.json \ + --handoff --allow-partial \ + --output /private/tmp/fleet-physical-handoff-example +``` + +`--allow-partial` explicitly acknowledges unresolved/unsupported records; it does +not bypass collection errors or target conflicts. The handoff emits candidate +objects and a receipt containing the exact target plus source, mapping, Fleet +snapshot and candidate digests. Nothing invokes kubectl apply or writes Git. + +## Prepare a private real-data review + +1. Use existing read credentials: `NETBOX_TOKEN`, otherwise `NETBOX_TOKEN_FILE` + (default `~/.config/netbox/token`). Never paste a token into arguments, logs, + mappings or Git. The existing infra bare-metal reader uses Bearer authentication; + `--auth-scheme Token` explicitly supports installations using the legacy scheme. + Redirects, non-HTTPS origins and off-origin/changed-collection pagination are + refused. All requests are GET; retries are bounded to three for transient errors. +2. Quiesce the source loaders if possible, then capture a private snapshot: + + ```sh + python3 hack/netbox_inventory.py snapshot --source reviewed-netbox-instance \ + --output /private/tmp/fleet-netbox-private-snapshot + ``` + +3. Copy the [synthetic mapping shape](../../hack/testdata/netbox/mapping.json) into + a private file. Review each facility, physical device classification, serial + interpretation, placement scope, feed and cable medium. A Source Site name is + not proof of premises. A missing serial is not permission to invent one. + For a breakout or multi-position termination, a cable mapping can supply `lanes` + in the [Cable Go contract](../../internal/api/inventory/v1alpha1/physical.go): + each lane has an ID, `a` and `b`, each endpoint has exactly one local owner, + `componentID` and `position`. Use stable candidate names from a prior dry-run + handoff or the source-key-derived name function. Positions must exist in the + component model; do not invent transceiver lanes absent from source geometry. +4. Export **all six** Fleet kinds from the explicitly selected **provider project's + Milo context**, including empty collections, before preparing candidates. The + [synthetic existing-state envelope](../../hack/testdata/netbox/existing.json) + shows the exact structure: `target` must exactly match the mapping, `collections` + must list all six kinds, and `items` contains the complete list in the reviewed + namespace. Use the project's established authenticated GET/list path; do not + assume a management-cluster context addresses Milo. The envelope is an operator + attestation, not cryptographic proof of scope or freshness. Retain capturedAt and + read evidence privately; re-read before a GitOps merge. +5. Run `plan` with private `--snapshot`, `--mapping`, `--existing` and a fresh output + directory. Add `--previous` with the earlier source snapshot on subsequent runs. + Review source disappearances: missing rows are **retained**, never deleted, + retired, freed, or marked ready. Existing differences, duplicate target IDs, + identity collisions and topology conflicts need adjudication before handoff. +6. Obtain explicit approval for the mapping, exact target and desired cohort. + Only then generate a handoff. Do not put private exports or imported asset facts + in a public Fleet PR. Do not apply the candidate List directly to Milo. +7. Stage individual **new** records additively in the existing private + `provider-inventory` Flux source. Preserve all existing files and object names; + never replace the collection with this partial candidate list. Review the Git + diff for no deletes, no modifications of existing bindings, no capacities and + no readiness/status. Retain source/mapping/report/receipt in the approved private + evidence store. The importer does not commit, push, merge or roll out this change. + +Flux remains the only writer for staging provider-inventory records. This avoids +the conflict that a direct importer would create with reconciliation. Reviewers +must check for concurrent changes since the Fleet snapshot; the offline handoff +does not provide an optimistic-concurrency apply transaction. After an interrupted +reconciliation, refresh the Fleet snapshot and rerun. Matching records become +no-ops; conflicts stay quarantined. Do not roll back by deleting occupied objects. + +The 2026-11-20 configuration observation names `fleet-provider-inventory`, with +path `apps/fleet-system/staging/provider-inventory`, `prune: false` and +`deletionPolicy: Orphan`. The similarly named legacy inventory reconciliations +are not the provider-project destination. Recheck these settings before handoff; +this feature does not modify them or their kubeconfig references. + +## Acceptance and observed limits + +On 2026-11-20, read-only GitHub checks found both infra staging OCI sources configured +for `v0.0.0-feat-manual-inventory-records`; the corresponding Fleet branch head was +`42086bbe2cf05f5d09362fbc777e514907d64462`. This implementation is stacked there, +including the dependent PXE/runtime code. **Configured tag is not an observed +deployed revision.** No cluster rollout or live import was performed. + +The documented environment/token-file paths did not provide authorized NetBox +access in this implementation checkout. No live inventory audit was performed; +present-day counts, parity, source mappings and schema-version compatibility are +unvalidated. Source interpretation comes from the pinned infra +`d9198940a499be4e744ee0564cf3dc0b3bfcee34` loaders and site-build documents, as +recorded in the [source evidence appendix](../proposals/fleet-management/inventory-reference.md#source-evidence-and-limits). + +Before live evaluation, establish a private source audit, resolve required mappings, +render/install the six-kind schema in an explicitly approved environment, and +confirm authorized staff can browse while consumers cannot. Compare counts and +every classified row, test repeated and interrupted handoffs, and confirm original +Device/claim/Capacity identities remain unchanged. None of this establishes +physical qualification or safe capacity release. + +```sh +python3 -m unittest discover -s hack -p test_netbox_inventory.py +go test ./internal/api/inventory/v1alpha1 +pnpm --dir ui/provider typecheck +pnpm --dir ui/provider test +pnpm --dir ui/provider build +kustomize build config/milo >/dev/null +bash hack/validate-doc-links.sh +git diff --check +``` diff --git a/docs/operations/physical-inventory.md b/docs/operations/physical-inventory.md index 7d0f2063..8e71398e 100644 --- a/docs/operations/physical-inventory.md +++ b/docs/operations/physical-inventory.md @@ -10,22 +10,28 @@ take ownership of it. This package implements a minimal subset of the [inventory lifecycle and trust proposal (#63)](https://github.com/datum-cloud/fleet/pull/63). -It has two operator-written kinds in `fleet.datumapis.com/v1alpha1`: +It now has six operator-written kinds in `fleet.datumapis.com/v1alpha1`. +The [NetBox physical import and migration guide](netbox-physical-import.md) +describes the additive physical schema, typed components, partial placement, +same-namespace relationships, import reconciliation and current limits. The +manual examples below preserve the original long-lived-slot representation: | Kind | What it is | Writer | | --- | --- | --- | | `DeviceClaim` | The installation plan for one slot: facility, rack, position and face, expected model, and expected ports with their expected cable peers. It is usually written before the hardware arrives, and the slot outlives any one Device. | The installation planner (an operator, for now) | | `Device` | One actual asset, bound to exactly one DeviceClaim when detected hardware is registered. It carries the serial and SMBIOS system UUID, the model, an optional BMC endpoint, interfaces, and provenance. | The registrar (an operator, for now) | +| `Facility` / `Rack` | Explicit premises and rack definitions; membership is not free-capacity evidence. | Inventory operator through the environment's existing writer | +| `Cable` / `PowerFeed` | Typed termination/lane topology and physical supply dependencies. | Inventory operator through the environment's existing writer | ## Status | Aspect | State | | --- | --- | | CRDs and Go types | Implemented in `config/components/inventory` and `internal/api/inventory/v1alpha1`. | -| Home | Milo. `config/milo` registers both CRDs, two ProtectedResources and two IAM roles, like the `metal.datumapis.com` kinds. `config/overlays/management-plane` and `config/overlays/synthetic-staging` install none of them. | +| Home | Milo. `config/milo` registers six CRDs, six ProtectedResources and two IAM roles. Management and synthetic-staging overlays install none of them. | | Staff portal | Read-only **Inventory** tab in the Bare Metal provider plugin (`ui/provider`): a claim list and a per-claim detail page. | -| Tests | Unit tests run the API server's schema, list-type, defaulting, and CEL validation offline, for both kinds. IAM tests check ProtectedResource and role shape and that no metal role grants inventory access. Plugin tests cover the list, detail, restricted, and empty states. | -| Controllers | None. No Fleet code reads or writes these kinds. | +| Tests | Unit tests run API-server schema, list-type and CEL validation offline for the six kinds and synthetic importer output. IAM tests check ProtectedResource and role shape and that no metal role grants inventory access. Plugin tests cover browse/detail, partial placement, reconciliation, restricted, pagination and empty states. | +| Controllers | None. Offline import and staff browsing read the records; no reconciler accepts plans, verifies hardware, or publishes eligibility. | | Hardware qualification | None. Records hold operator-entered facts, not verified hardware state. | ## What registration does and does not do @@ -48,17 +54,17 @@ namespace resolves by name. Nothing checks that reference yet. ## Where the records live -Milo is the single home. DeviceClaims and Devices are namespaced objects in the +Milo is the single home. All six kinds are namespaced objects in the **provider project's** control plane, in the same namespace as the MachineCapacities they will back. No copy exists on the Fleet management cluster, and no controller syncs them anywhere. -Both CRDs carry `discovery.miloapis.com/parent-contexts: Project`, so every +All six CRDs carry `discovery.miloapis.com/parent-contexts: Project`, so every project control plane serves the kinds. Access is what keeps consumers out: | Role | Grants | | --- | --- | -| `fleet.datumapis.com-inventory-viewer` | `get`, `list`, `watch` on `deviceclaims` and `devices` | +| `fleet.datumapis.com-inventory-viewer` | `get`, `list`, `watch` on all six physical kinds | | `fleet.datumapis.com-inventory-editor` | The viewer role plus `create`, `update`, `patch`, `delete` | No `metal.datumapis.com` role includes or inherits either. The consumer, @@ -81,15 +87,15 @@ in the provider project. The plugin never writes. | Rule | Kind | Why | | --- | --- | --- | -| `provenance` is required: `method: Manual`, `recordedBy`, `recordedAt`, and an optional opaque `reference` | Both | Every plan and registration is attributable to a person and a time. | -| Any spec change must set a later `provenance.recordedAt` | Both | An edit cannot pass off new facts under old provenance. | +| `provenance` is required: `Manual` or `NetBoxImport`, `recordedBy`, `recordedAt`, optional opaque reference; imports also require structured source provenance | All six | Attribution is retained; imported claims are observations, not authenticated hardware evidence. | +| Any spec change must set a later `provenance.recordedAt` | All six | An edit cannot pass off new facts under old provenance. | | `claimRef` is required and immutable | Device | A Device binds to exactly one claim, and moving hardware to another slot is not an edit. | -| `identity` (manufacturer, model, serial, system UUID) is immutable, including adding a missing field; at least one of serial or system UUID is required | Device | Serial and UUID are matching evidence. A hardware swap is a new Device bound to the same claim. | +| `identity` is immutable, including adding missing fields; requires serial, system UUID, or an import source identity matching provenance | Device | Source identity does not prove chassis identity. Legacy bindings are preserved; hardware handover is not automated. | | Serial is optional | DeviceClaim | It is usually unknown at plan time. | | Port and interface names are unique; MACs are lowercase and colon-separated, appear at most once per Device, and are either mapped to an interface or listed in `unmappedMACAddresses`, not both | Both | Malformed or ambiguous facts are rejected. | | The system UUID is in lowercase canonical form | Device | One spelling per identity. | | `bmc.endpoint` is an `https` URL without credentials | Device | Credentials never live in inventory records. | -| `status` is a separate subresource that declares no fields | Both | Reserved for future collectors and verifiers to report drift and mismatch. Status never carries identity, and nothing writes it yet. | +| `status` is a separate subresource that declares no fields | All six | Reserved for future collectors and verifiers to report drift and mismatch. Status never carries identity, and nothing writes it yet. | The CRDs cannot check that `claimRef` names an existing DeviceClaim, because CEL cannot read other objects. Until a registrar enforces it, the operator @@ -172,12 +178,11 @@ The names and writers match #63: - Serial and SMBIOS UUID are matching evidence, not authenticators. - Logical LAGs and VLANs are not ports. -Deferred to #63, and deliberately absent: +Still deferred to #63: -- `Facility`, `Rack`, `Cable`, and `PowerFeed` kinds. Facility and rack are - names on the claim, and the expected cable peer is inline on each claimed - port, until those kinds replace them. Rack geometry beyond position, height, - and face is also deferred. +- Qualified geometry/reservations and automatic migration of legacy text + placement/inline peers. The four additional physical record kinds now exist; + typed records do not silently take over historical surfaces. - Plan acceptance, revisions, and reservations; canonical-identity adjudication and duplicate detection; and the protected ledger. - Trust roots, qualification profiles, enrollment challenges, technician and @@ -202,11 +207,11 @@ for one authoritative record that MachineCapacity can name and that staff can read. #63's ledger, trust, and enrollment protocol would still sit behind these records if adopted. -**Divergence to resolve:** this package's convention is that a whole-server -replacement binds a new Device to the same DeviceClaim, because the planned slot -outlives the hardware. #63's current text says whole-server replacement creates a -new DeviceClaim as well. The schema enforces neither convention. Settle this in -#63 before either path is automated. +**Compatibility decision:** legacy slots retain all historical bindings. New +imports use a distinct `Installation` lifecycle, but no automatic move or +replacement handover exists. Device identity and its original claimRef remain +immutable. The [migration decisions](netbox-physical-import.md#compatibility-and-migration-decisions) +explain why imports cannot delete/recreate or relabel legacy records to bypass this. ## Applying the records @@ -216,7 +221,7 @@ claims before the Devices that name them. Keep records with real serials, UUIDs, MACs, endpoints, or cabling in the environment's private configuration, not in this repository. -`config/inventory` still renders the two CRDs alone, for an environment that +`config/inventory` still renders the inventory CRDs alone, for an environment that applied them to the management cluster before Milo became their home. Once that environment has moved its records into Milo and stopped reconciling the root, it will be removed. New environments must not use it. diff --git a/docs/proposals/fleet-management/MIGRATION.md b/docs/proposals/fleet-management/MIGRATION.md index cc06676f..c1fa51ed 100644 --- a/docs/proposals/fleet-management/MIGRATION.md +++ b/docs/proposals/fleet-management/MIGRATION.md @@ -31,6 +31,21 @@ migration configuration remains in infra. ## Post-import amendments +- 2026-11-20: Added the limited [observational physical inventory implementation](../../operations/netbox-physical-import.md) + on the staging-selected manual-inventory feature base. Six record kinds, typed + components, partial placement, read-only staff relationships and offline NetBox + handoff are implemented separately from this proposal's acceptance, reservations, + verification and lifecycle controllers. Legacy identities/bindings remain intact; + no live source parity, deployed readiness or hardware qualification is asserted. + +- 2026-11-20: Expanded the existing [inventory proposal](inventory.md) with the + six physical contracts, partial placement, typed components, circuit-boundary + proposals, evidence and qualification requirements. Recorded the pinned + manual-record implementation's claim-lifetime and authority migration gates, + plus source-backed NetBox import constraints. These remain proposed contracts, + not implementation changes or proof of live-data parity. The proposal keeps + the design narrative; field details, examples, migration evidence and test + cases are retained in its [reference appendix](inventory-reference.md). - 2026-11-17: MachineProfile CPU cores and memory capacity changed from `min` ranges to exact requests, with the resolved request pinned in Machine status. The `standard-metal` example and the capacity publication text were updated diff --git a/docs/proposals/fleet-management/inventory-reference.md b/docs/proposals/fleet-management/inventory-reference.md new file mode 100644 index 00000000..8c6937df --- /dev/null +++ b/docs/proposals/fleet-management/inventory-reference.md @@ -0,0 +1,916 @@ +--- +status: provisional +stage: alpha +latest-milestone: "v0.1" +--- + +# Fleet inventory reference appendix + +Technical detail supporting the [Fleet inventory product proposal](inventory.md). +Start there for operator needs, the proposed experience and open decisions. +This appendix keeps field definitions, synthetic examples, source findings, +migration steps and test requirements together for implementers and reviewers. +It is part of the same enhancement, not a separate design. + +All contracts and field names remain provisional. Examples are not implemented +CRDs or manifests to apply; illustrative identifiers and evidence do not establish +physical truth. Local object incarnations are retained privately rather than +used as authored cross-control-plane references. + +- [Contract details](#contract-details) + - [Metadata and evidence](#shared-metadata-references-and-evidence) + - [Facility and Rack](#facility-and-rack-contracts) + - [Assets and components](#asset-identity-and-typed-components) + - [Installation examples](#plan-a-physical-installation) + - [Reservations](#reserve-physical-resources) + - [Registration](#register-and-bind-a-device) + - [Verification](#verify-the-installation) + - [Cabling and power](#cabling-power-and-network-configuration) + - [Circuit boundary](#circuit-demarcations-and-external-ownership) + - [Lifecycle transitions](#moves-replacements-and-retirement) +- [Existing records and migration](#existing-records-and-migration) +- [Source evidence and limits](#source-evidence-and-limits) +- [Validation and qualification matrix](#validation-and-qualification-matrix) + +## Contract details + +### Shared metadata, references, and evidence + +The following are proposed contract semantics, not an assertion that these fields +are available in the current API. Keep the initial six kinds; use structured +entries and protected transition records rather than a kind for each work order, +photo, model, approval, or verification run. + +| Surface | Authoritative writer | Contract | +| --- | --- | --- | +| Facility/Rack definitions, DeviceClaim intent, Cable topology, PowerFeed supply plans | Authorized inventory planner | Changes produce reviewed revisions; they cannot rewrite registered observations or prove physical work. | +| Accepted plans, reservations, active placement and historical bindings | Inventory coordinator/registrar | Conditional durable transitions retain approval, exact inputs, and predecessor identities. Planner and collector writes cannot bypass them. | +| Device identity, asset tags and canonical component inventory | Registrar | Adjudicates authenticated observations and corrections; collectors never directly replace canonical identity. | +| Observations and evaluated conditions | Authenticated evidence submission; inventory verifier owns the projection | Preserve source observations separately from approved intent; only the verifier writes verification results. | +| Management endpoints and access | Provider management authority | Restricted references/projections only; inventory does not allocate OOB addresses, issue credentials, or authorize BMC actions. | +| Provider host IDs, service/circuit identifiers and commercial facts | Respective provider/service authority | Inventory retains sourced identifiers and physical associations, not orders, invoices, pricing, or routing intent. | + +All kinds need a human-readable label, optional description, provenance, and +restricted external references. Names and labels are not durable asset identity. +For each imported fact retain source system, source object type and ID, source +revision or snapshot digest when available, observation time, importer identity +and mapping revision. Keep claimed source authors separate from the authenticated +submitter. Conflicting sources require adjudication; last import wins is not a +trust rule. Absence, undisclosed information, a mismatch, and policy-approved +inapplicability are distinct states, never encoded as invented values or zero. + +Typed references identify the allowed kind/group, administrative scope, and name. +A kind-specific field such as `rackRef` fixes kind/group; examples omit scope only +for same-scope references. Cross-scope references require explicit scope and +authorization; they never resolve by a global name search. Acceptance pins the +resolved local incarnation and relevant revision privately. Name reuse, dangling +references, unauthorized targets, and wrong-kind targets cannot inherit evidence. +Foreign source IDs are provenance, not directly resolvable Fleet references. + +`documentRefs` refer to photos, as-built sheets, installation attestations, LOAs, +or contracts in their existing document system. Retain document ID, category, +revision/digest when available, capture time, and the exact asset/plan or path +being supported. Documents keep their own ACLs; a Fleet reference grants no +access and contains no document body, token, signed download URL, or credential. +A mutable URL alone cannot establish evidence for a prior evaluation. A contract +or LOA is not proof of installed cabling; a photo requires an attributed +interpretation and qualified check. Unavailable evidence leaves dependent checks +Unknown rather than copying protected material into public status. + +Audit history retains who requested, approved, and committed a change, its reason, +before/after revisions, supporting references, and affected identities. Retain +supersession, identity corrections, component removals, and retirement events; +do not rewrite history to match the present plan. Retention and deletion policy +must preserve evidence needed by active reservations and consumer obligations. + +### Facility and Rack contracts + +| Kind | Proposed minimum and optional physical metadata | Validation and lifecycle | +| --- | --- | --- | +| Facility | Stable identity, display name, geographic `locationRef`, and physical-premises description. Optional structured postal address, building/room labels, coordinates with source/precision, operator identity reference, external facility-code mappings and document references. Sensitive access instructions stay external. | A metro code alone is insufficient to establish premises. Operator approval establishes or corrects a premises mapping. Closing a Facility blocks new plans; it neither relocates equipment nor releases occupancy. Preserve historical references. | +| Rack | Immutable `facilityRef` after accepted use, local rack label, optional room/row, mounting geometry and capacity, supported faces, depth/width limits, optional load limit with units, 0U mounting locations, and document references. Unknown dimensions remain absent with provenance. | Rack labels are unique within an agreed Facility scope, not globally. Known rack-unit numbering has a documented origin/direction; position denotes the lowest occupied unit. Reject out-of-range footprints, face/depth conflicts, and incompatible mounts. Do not infer usable space from omitted geometry. | + +A Facility is not a provider account, provider metro grouping, or Fleet policy +Site. One physical premises may have several provider codes; one imported metro +grouping may refer to several premises. Mapping records retain both directions +and unresolved candidates without creating a false one-to-one relationship. +Site policy selects eligible Facilities as described in +[Site rules for choosing eligible facilities](cluster-lifecycle.md#site-and-cluster-resources). + +Rack geometry changes that affect reservations require revalidation under the +coordinator, not a metadata edit that evicts occupants. Correcting a mistaken +Facility association requires an audited migration of dependent references and +evidence; physically moving a rack requires coordinated placement transitions +for its occupants. Deletion is blocked while active claims, Devices, Cables, or +feeds depend on the object. An empty inventory list does not prove an empty rack. + +### Asset identity and typed components + +Device identity includes manufacturer/model, independently evidenced chassis +serial when available, and optional SMBIOS UUID. Asset tags are separate +operator-assigned identifiers with issuer/scope and assignment history; replacing +a tag is not replacing a chassis. Provider host IDs belong in namespaced external +identifiers, never `serialNumber`. Serial, UUID, MAC, model, label, or asset tag +alone is not authentication or universally unique. Missing serials on passive +equipment require qualified technician identity evidence, not a fabricated +serial. Duplicate or conflicting matches remain quarantined for adjudication. + +An expected serial or asset tag may be unknown when planning. The accepted claim +pins its matching constraints and qualified hardware shape; registration records +actual identity, records discrepancies, and does not silently relax constraints. +Device role describes physical use, not cluster membership or allocation state. + +Repeated models justify a reusable, versioned **model/port shape**, initially a +reviewed document or configuration artifact rather than a new public kind. It +describes manufacturer/model/variant, dimensions, component slots, labels, +connector capabilities and internal pass-through or power mappings. Claims pin +the shape revision/digest and explicit deviations; updating a template never +retrofits an accepted plan or invents observed components. Provider marketing +models and VM flavors cannot establish chassis geometry. Qualification must +compare the shape to actual hardware variants. + +Each canonical component entry has a Device-local stable ID, a discriminated +type, physical label, optional parent/slot, relevant capabilities, provenance, +and retained incarnation/revision evidence. The registrar owns the canonical +entry; mutable observations and OS aliases are separate. Reject duplicate IDs, +parent cycles, incompatible fields, and references to removed incarnations. + +| Component type | Physical contract | Explicit exclusion or restriction | +| --- | --- | --- | +| Network port | Connector/media family, supported rates with units, lane/position capabilities, optional MAC observations and replaceable transceiver association. Management/Data is a role, not a separate identity system. | No VLAN, bond, IP allocation, BGP peer, or switch configuration. An OS name is only an observed alias. | +| Power inlet/outlet | Input/output direction, connector and AC/DC compatibility, supported voltage/current limits with units; outlet-to-input dependency for a PDU. | No assumption that two inlets or outlets are independent. Unsupported transfer-switch mappings remain unknown. | +| Console port | Serial/USB/Ethernet connector and host/server direction, with physical compatibility parameters where required. | No session credentials or console access authorization. A networked console server's Ethernet port remains a network port. | +| Pass-through termination | Front/rear side, connector, numbered positions, and explicit internal position mappings for a passive panel. | Never infer a direct link through a panel from LLDP alone. | +| Replaceable NIC, optic, PSU or disk | Parent slot, actual component identity/serial where disclosed, model/capabilities and insertion/removal history. Disks may retain observed WWIDs and capacity with units. | A disk is not a Cable endpoint; installation pins exact disk targets separately. A slot reused after repair is not the same component incarnation. | + +Only fields relevant to a component type are allowed. Supported type/connector +vocabularies and required units must be fixed by the first qualified schema; +unknown vendor strings may be retained as observations but cannot pass typed +connection validation. Claim port IDs express intended attachment points and +resolve explicitly to canonical component IDs, never by a guessed array index. + +For example, a synthetic observed panel shape can contain: + +```yaml +# Proposed component excerpt, not a complete Device manifest. +components: + - id: panel-front-01 + type: PassThroughTermination + side: Front + connector: LC + positions: [1, 2] + - id: panel-rear-01 + type: PassThroughTermination + side: Rear + connector: LC + positions: [1, 2] +passThroughMappings: + - from: {componentID: panel-front-01, position: 1} + to: {componentID: panel-rear-01, position: 1} + - from: {componentID: panel-front-01, position: 2} + to: {componentID: panel-rear-01, position: 2} +``` + +These are internal device mappings, not a second expected-cable graph. Cables +remain the only declarations connecting different assets. + +### Plan a physical installation + +The DeviceClaim contract retains role, expected identity constraints, placement +scope, declared attachment points, required Cable references, verification +profile/checks, provenance and approval revision. Where power is reserved, the +plan also pins a maximum load budget with units and the required failure scenario +per supply path. Missing load assumptions block power-capacity acceptance; the +number of PSUs does not supply them. Model-shape references and predecessor/asset +references for moves or replacements are optional inputs that become immutable +within an accepted revision. They do not grant permission to evict a predecessor. + +The Facility describes physical premises. A Fleet `Site` can select eligible +Facilities as operational policy without moving their assets. Location remains +the geographic reference; neither Site nor Facility is a provider identifier. + +```yaml +apiVersion: fleet.datumapis.com/v1alpha1 +kind: Facility +metadata: + name: iad1 + namespace: infra-ops +spec: + displayName: Ashburn Facility 1 + locationRef: + name: us-east-1 +--- +apiVersion: fleet.datumapis.com/v1alpha1 +kind: Rack +metadata: + name: iad1-r12 + namespace: infra-ops +spec: + facilityRef: {name: iad1} + heightUnits: 42 +--- +apiVersion: fleet.datumapis.com/v1alpha1 +kind: DeviceClaim +metadata: + name: iad1-r12-u20-server + namespace: infra-ops +spec: + role: Server + expectedIdentity: + manufacturer: Dell + model: PowerEdge-R650 + serialNumber: EXAMPLE-SERVER-001 + assetTag: {issuer: datum-infra, value: EXAMPLE-ASSET-001} + placement: + rackRef: {name: iad1-r12} + position: 20 + heightUnits: 1 + face: Front + fullDepth: true + verification: + requiredChecks: [Identity, RackPlacement, NetworkPaths, PowerPaths] + ports: + - {id: bmc, type: EthernetPort, role: Management, physicalLabel: BMC} + - {id: nic1-p1, type: EthernetPort, role: Data, physicalLabel: NIC1/P1} + - {id: psu1, type: PowerInlet, physicalLabel: PSU1} + - {id: psu2, type: PowerInlet, physicalLabel: PSU2} + cableRefs: + - {name: iad1-r12-srv01-management} + - {name: iad1-r12-srv01-data} + - {name: iad1-r12-srv01-power-a} + - {name: iad1-r12-srv01-power-b} +``` + +The example assumes an existing management switch `iad1-oob01`, data switch +`iad1-r12-leaf-a`, and PDUs `iad1-r12-pdu-a`/`iad1-r12-pdu-b`, each registered +through its own claim. Their referenced components and upstream power paths +must exist and be verified. These four Cable plans describe the server's +required connections before the server Device exists: + +```yaml +apiVersion: fleet.datumapis.com/v1alpha1 +kind: Cable +metadata: + name: iad1-r12-srv01-management + namespace: infra-ops +spec: + medium: CopperEthernet + a: [{deviceClaimRef: {name: iad1-r12-u20-server}, portID: bmc}] + b: [{deviceRef: {name: iad1-oob01}, componentID: port12}] +--- +apiVersion: fleet.datumapis.com/v1alpha1 +kind: Cable +metadata: + name: iad1-r12-srv01-data + namespace: infra-ops +spec: + medium: DirectAttachCopper + a: [{deviceClaimRef: {name: iad1-r12-u20-server}, portID: nic1-p1}] + b: [{deviceRef: {name: iad1-r12-leaf-a}, componentID: ethernet20}] +--- +apiVersion: fleet.datumapis.com/v1alpha1 +kind: Cable +metadata: + name: iad1-r12-srv01-power-a + namespace: infra-ops +spec: + medium: Power + a: [{deviceRef: {name: iad1-r12-pdu-a}, componentID: outlet20}] + b: [{deviceClaimRef: {name: iad1-r12-u20-server}, portID: psu1}] +--- +apiVersion: fleet.datumapis.com/v1alpha1 +kind: Cable +metadata: + name: iad1-r12-srv01-power-b + namespace: infra-ops +spec: + medium: Power + a: [{deviceRef: {name: iad1-r12-pdu-b}, componentID: outlet20}] + b: [{deviceClaimRef: {name: iad1-r12-u20-server}, portID: psu2}] +``` + +`cableRefs` identifies prerequisites; it does not repeat expected peers. Cable +owns the endpoint declarations. A planned endpoint references a DeviceClaim +and its declared port ID; a registered endpoint references a Device and stable +component ID. Names are convenient authoring references. Acceptance retains the +exact local object incarnations privately and records approved dependency +revisions. Recreating an object with the same name never inherits a reservation. + +Placement may instead name `placement.facilityRef` without a rack. This covers +unracked equipment and rented bare metal whose physical Facility is known but +whose rack/patching is not disclosed. The claim must state its verification +requirements explicitly; for example: + +```yaml +# Excerpt for an identified physical server with facility-level visibility. +spec: + placement: + facilityRef: {name: iad1} + verification: + requiredChecks: [Identity, FacilityPlacement] +``` + +Admission constrains required checks using operator policy and the intended +offering. Authors cannot weaken verification to make a failed installation +pass. Rack placement derives Facility through the Rack; if both references are +supplied they must agree. Undisclosed rack/cable facts remain unknown, not +invented or marked physically inapplicable. `Ready` for a facility-scoped claim +does not imply verified rack position, cabling, power redundancy, or eligibility +for an offering that requires those facts. Historical UUID/IP/disk lists are +migration inputs, not sufficient verification evidence. + +**Rack known, position undisclosed** is a separate supported placement scope, +not facility-only placement and not a fictitious 1U footprint: + +```yaml +# Proposed excerpt for identified rented hardware; all identifiers are synthetic. +spec: + placement: + rackRef: {name: iad1-provider-rack-7} + scope: RackMembership + verification: + requiredChecks: [Identity, RackMembership] +``` + +The proposed placement discriminant distinguishes `Facility`, `RackMembership`, +`RackUnits`, and `NonRackUnitMount`. Existing exact-position examples imply +`RackUnits`; facility-only examples imply `Facility`. The eventual schema must +make this choice unambiguous. RackMembership forbids position, face, height and +full-depth assertions unless a subsequent approved revision establishes an +exact mount. It permits known asset dimensions in the model, but dimensions +alone cannot establish occupied units. NonRackUnitMount requires a qualified +mounting-location identifier for 0U or other non-unit rack mounts. Facility +placement describes unracked or undisclosed-rack equipment without such a mount. + +Acceptance for RackMembership records the known occupancy and may reserve known +terminations/power, but makes **no rack-unit reservation**. An unresolved +footprint prevents declaring the rack's unaccounted space free: block new exact +unit reservations in that rack until occupancy is reconciled, unless a qualified +operator-approved exclusion boundary proves a disjoint area safe. Do not guess +the exclusion boundary. Facility-only imports likewise cannot establish free +rack capacity. A plan requiring exact placement remains Pending until an exact +footprint is approved and reserved. `PlacementVerified` reports Facility, +RackMembership, or exact mount scope; RackMembership readiness cannot satisfy a +RackUnits prerequisite. Imported invented positions never satisfy any placement +check merely because they appear in a source DCIM object. + +### Reserve physical resources + +Acceptance commits a retained plan covering the claim and its required Cable +inputs. Inventory must reserve the applicable declared rack footprint, physical +terminations, and power capacity without races. Rack checks include occupied units, +front/rear constraints, full-depth equipment, and pending installations. The +model also supports 0U mounting and equipment outside a rack; it must not assign +them fictitious rack-unit positions. + +Endpoint reservations belong to one exact Cable incarnation and identify one +exact Device or DeviceClaim incarnation plus termination/position. Local object +identity is retained as private same-API-server evidence. Two cables cannot reserve the same +exclusive termination. Resolving a claim endpoint to a registered component +must preserve that reservation, including conflicts with direct Device +references. A successor placement cannot reserve an occupied resource merely +because the previous object's readiness is False. + +Use durable conditional commits or an equivalent serialized reservation +protocol, not an admission-time list check or controller-local lock. Partial +acquisition stays Pending and is recovered or explicitly unwound. Report +`Accepted=True` only after the complete current plan is committed. Hold +reservations through controller restarts and uncertainty; timeouts and expired +worker leases do not prove that space, cabling, or power is physically free. + +Referenced Cable plans may target other unbound claims. Validate and reserve +the intended endpoints without requiring those Devices to be Ready. Otherwise +two devices awaiting a connection could never be commissioned. Editing an +unbound plan requires revalidation and a new committed plan revision; stale +acceptance or registration requests cannot use the previous revision. + +### Register and bind a device + +A registration request must authenticate its enrollment channel and identify +an existing accepted DeviceClaim and approved plan revision. Match expected +identity against independently trusted evidence. Serial numbers, MAC +addresses, and SMBIOS UUIDs are matching attributes, not authentication. +Passive devices register through an authorized technician or integration; +they do not need to run a host agent. + +The registrar commits one reciprocal DeviceClaim-to-Device relationship and +retains both local object incarnations as private same-API-server evidence. One +claim binds one Device for one installation incarnation. One physical asset +cannot acquire duplicate Device identities, +and one Device has at most one active placement authority. Recovery after a +lost response finds the committed registration instead of creating a second +asset. Ambiguous matches, unexpected identities, expired authorization, or +already-bound claims fail closed. Unknown equipment remains isolated discovery +evidence; it cannot manufacture an accepted claim or eligible capacity. + +Registration does not require all physical verification to have succeeded. A +Device can exist in commissioning with a placement or wiring discrepancy: + +```yaml +# Registrar-created snapshot, not an operator-authored apply input. +apiVersion: fleet.datumapis.com/v1alpha1 +kind: Device +metadata: + name: server-example-001 + namespace: infra-ops +spec: + # Registry-owned. A raw reference edit cannot move the asset. + claimRef: + name: iad1-r12-u20-server + identity: + manufacturer: Dell + model: PowerEdge-R650 + serialNumber: EXAMPLE-SERVER-001 +status: + observedPlacement: + rackRef: + name: iad1-r12 + position: 20 + face: Front + evidenceRef: installation-scan-001 + components: + - {id: management-port-1, type: EthernetPort, physicalLabel: BMC} + - id: nic-slot2-port1 + type: EthernetPort + physicalLabel: NIC1/P1 + macAddress: "02:00:00:00:12:01" + - {id: power-supply-1, type: PowerInlet, physicalLabel: PSU1} + - {id: power-supply-2, type: PowerInlet, physicalLabel: PSU2} +``` + +Declared claim ports resolve using trusted chassis labels, qualified hardware +layout, and physical component identity. A controller cannot swap the mapping +of `nic1-p1` to a different NIC merely to make the observed neighbor match. +The Device records actual components; the claim records the approved mapping +from its intended ports to those components. + +### Verify the installation + +Commissioning has an ordered dependency graph: + +```text +Accepted plan and physical reservations + -> trusted registration and exclusive Device binding + -> claim-port mapping and Cable endpoint resolution + -> identity, placement, network, and power evidence evaluated + -> physical Ready +``` + +Cable resolution depends on binding, not Device Ready. Protected enrollment +connectivity must exist before complete production-path verification. Any +inspection that boots or modifies a device requires a separately authorized +hardware operation; inventory readiness cannot authorize its own evidence +collection effects. + +- **Hardware identity and capabilities:** Authenticated BMC/qualified agent observations + or trusted installation evidence matched to the enrolled asset. Claimed identifiers + alone are insufficient. +- **Switch and port adjacency:** Trusted switch-side observations corroborated with the + enrolled NIC mapping. MAC learning or agent-reported LLDP alone does not prove asset + identity. +- **Link capability:** Current port state, negotiated parameters, and relevant hardware + observations; link-up is not proof of a complete passive path. +- **Exact rack position/orientation:** Authorized installation scans/attestations or + qualified rack instrumentation. Management-network reachability does not establish a + rack unit. +- **Passive cable identity and patch path:** Verified endpoint/cable-label scans or + qualified instrumentation. LLDP does not identify each passive segment. +- **PSU, outlet, and upstream feed:** Verified physical mappings and suitable + observations/instrumentation. Two healthy PSUs do not establish independent supplies. + +Link discovery can supply switch/port observations through qualified collectors; +it does not establish every physical fact above. Redfish's rack/offset fields +are writable metadata, so copying the intended position into a BMC and reading +it back is not independent placement evidence. See the +[Redfish data model](https://redfish.dmtf.org/schemas/v1/DSP0268_2025.3.pdf). + +Conditions report `Accepted`, `Bound`, `IdentityVerified`, `PlacementVerified`, +`NetworkPathVerified`, `PowerPathVerified`, and `Ready` separately. Readiness +requires every admitted required check for the current approved plan and +records the evaluated verification scope. `PlacementVerified` identifies +whether it evaluated Facility, RackMembership, or exact mount placement. Missing +or stale required evidence is Unknown; a verified mismatch is False. Checks outside the +scope remain explicitly unevaluated. A policy may mark a check physically +inapplicable, such as power for a passive panel; absence of evidence must not +silently become an exemption. Downstream controllers require the specific +verified facts their operation or offering needs, not an unqualified Ready bit. + +Each evaluation privately retains the exact local claim, Cable, Rack, PowerFeed, +and Device incarnations and records their revisions, Device +identity/component/trust revision, evaluated input digest, +evidence provenance, and verification time. Standard condition fields include +`observedGeneration`, reason, message, and transition time. The owning object's +generation alone is insufficient: recabling, a NIC replacement, or new trust +material can invalidate evidence without changing that object's spec. + +Keep bounded summaries and protected evidence references in status. Retain the +evaluated plan and evidence needed to explain the result. Evidence freshness +is check-specific: a current adjacency observation and an installation scan +have different validity rules. Relevant topology or hardware changes invalidate +the applicable result; an old `Ready=True` is not blanket authorization. + +```yaml +# Abbreviated controller-written verification snapshot after successful checks. +# Routine condition timestamps/messages are omitted for readability. +apiVersion: fleet.datumapis.com/v1alpha1 +kind: DeviceClaim +metadata: + name: iad1-r12-u20-server + namespace: infra-ops +status: + observedGeneration: 1 + evaluatedPlanDigest: "sha256:" + evaluatedChecks: [Identity, RackPlacement, NetworkPaths, PowerPaths] + evidenceRef: commissioning-evaluation-001 + deviceRef: + name: server-example-001 + portBindings: + - {claimPortID: bmc, deviceComponentID: management-port-1} + - {claimPortID: nic1-p1, deviceComponentID: nic-slot2-port1} + - {claimPortID: psu1, deviceComponentID: power-supply-1} + - {claimPortID: psu2, deviceComponentID: power-supply-2} + conditions: + - {type: Accepted, status: "True", reason: PhysicalReservationsCommitted, observedGeneration: 1} + - {type: Bound, status: "True", reason: ExclusiveDeviceBindingCommitted, observedGeneration: 1} + - {type: IdentityVerified, status: "True", reason: TrustedEnrollmentMatched, observedGeneration: 1} + - {type: PlacementVerified, status: "True", reason: InstallationScanVerified, observedGeneration: 1} + - {type: NetworkPathVerified, status: "True", reason: TrustedPeerEvidenceMatched, observedGeneration: 1} + - {type: PowerPathVerified, status: "True", reason: PowerPathEvidenceVerified, observedGeneration: 1} + - {type: Ready, status: "True", reason: RequiredEvidenceCurrent, observedGeneration: 1} +``` + +Cable status similarly reports resolved Device names/component IDs; protected +evidence privately retains the exact local Device incarnations. It separately +reports evidence for endpoint adjacency, cable identity, and any pass-through +path. It never rewrites spec to agree with discovery. Physical drift blocks +new allocations and operations that require the invalidated fact and alerts +operators. It does not independently authorize eviction, power-off, wiping, or +release of an existing consumer reservation. + +### Cabling, power, and network configuration + +Cable metadata includes a stable record identity, physical label/asset tag where +present, medium, connector information, and optional measured length with units, +color and external evidence references. Distinguish a planned label from an +observed one. Reusing a cable label does not transfer the old cable's verification. +Replacing a physical cable creates a successor Cable identity; repatching the +same cable retains identity but creates an approved endpoint revision and +invalidates affected paths. Preserve disconnected endpoints in history. + +Every Cable endpoint is a discriminated reference to exactly one DeviceClaim +port, Device component, or PowerFeed termination, with lane/position where +needed. Validate type, connector, direction, multiplicity and exclusive +termination use. A simple cable has one endpoint at each end; a qualified +breakout has explicit one-to-many lane mappings, not an unconstrained list that +implies all-to-all connectivity. Reject repeated lanes, unmodeled adapters and +incompatible media. Derive occupied terminations from the retained Cable plan, +not an independently editable peer list on Devices. + +A Cable connects typed physical terminations. Pass-through components on patch +panels retain explicit internal front/rear mappings. Breakout cables require +explicit position/lane mappings. Trace the complete supporting path; reject an +unsupported mapping rather than assuming a direct connection. NetBox's +[physical cable model](https://netboxlabs.com/docs/netbox/models/dcim/cable/) provides an +established physical-path precedent. It is not a requirement to use NetBox's +schema or implementation. + +A PDU is a Device. Its component model maps each outlet to the input that +supplies it. Power cables connect feeds to PDU inputs and outlets to device +inlets; a feed termination uses a typed `powerFeedRef`, resolved by name with its +exact local incarnation retained privately. +PowerFeed records include rated/usable capacity and known upstream +sources; unknown dependencies remain explicit. Reservation calculations must +account for the declared redundancy/failure scenario, not assume that each of +two feeds supplies half the load. Two differently named PDUs can share the same +UPS or upstream circuit. See the +[power feed model](https://netboxlabs.com/docs/netbox/models/dcim/powerfeed/) and +[power outlet model](https://netboxlabs.com/docs/netbox/models/dcim/poweroutlet/) precedents. + +PowerFeed is the physical supply boundary, not a utility bill or a substitute +for a PDU Device. Its proposed contract includes Facility reference, operator +label, optional panel/circuit label, typed termination IDs, AC/DC supply, +nominal voltage, phase count where applicable, rated current/capacity with +units, usable budget and the derating-policy revision that produced it. Unknown +ratings cannot become zero demand or unlimited capacity. Declared reservations +and measured draw remain separate; a low instantaneous draw cannot free a +reserved budget. + +Upstream dependencies identify other PowerFeeds or scoped external electrical +source identities with provenance. Equal external identities mean a shared +dependency; different labels without evidence do not prove independence. +Unresolved dependencies remain Unknown, and cycles are invalid. An electrical +panel/circuit label is distinct from a network service circuit identifier. +Inventory owns the approved dependency graph; qualified measurements and +technician attestations verify it without overwriting the plan. + +```yaml +# Synthetic proposed supply example, not a verified electrical design. +apiVersion: fleet.datumapis.com/v1alpha1 +kind: PowerFeed +metadata: + name: iad1-r12-feed-a + namespace: infra-ops +spec: + facilityRef: {name: iad1} + label: EXAMPLE-PANEL-A-12 + supply: {type: AC, nominalVoltageV: 208, phases: 1, ratedCurrentA: 30} + budget: {usableCurrentA: 24, policyRevision: example-derating-v1} + terminations: + - {id: output-1, type: PowerOutlet, connector: IEC60309} + upstreamSources: + - externalRef: {system: example-facilities, type: UPS, id: EXAMPLE-UPS-1} +--- +apiVersion: fleet.datumapis.com/v1alpha1 +kind: Cable +metadata: + name: iad1-r12-pdu-a-supply + namespace: infra-ops +spec: + medium: Power + a: [{powerFeedRef: {name: iad1-r12-feed-a}, terminationID: output-1}] + b: [{deviceRef: {name: iad1-r12-pdu-a}, componentID: inlet-1}] +``` + +This example assumes a compatible, separately registered PDU inlet. It proves +neither usable capacity nor redundancy. If feeds A and B both depend on +`EXAMPLE-UPS-1`, two working cables do not qualify as UPS-independent supply. +Qualification pins voltage/phase/connector compatibility, load units and a +supported derating/failure model. Converting watts to amperes requires the +necessary electrical assumptions, not implicit arithmetic across unlike units. +Reserve the full admitted failover load on each surviving path required by that +model; reject insufficient headroom or report Unknown for undisclosed inputs. + +Feed decommissioning blocks new dependent plans. Changing a breaker rating, +upstream source or usable budget re-evaluates all affected reservations and +conditions; it never silently sheds load, releases occupied capacity, or powers +off equipment. Retire a feed only after dependent paths are safely removed and +their physical release is evidenced. + +Rack, switch, and power failure domains are derived from verified dependency +information, including shared upstream resources. Labels can expose validated +domains for selection; different labels do not establish physical independence. + +Physical connectivity does not select the VLAN, VRF, IP address, routing +adjacency, or tenant network carried over a link. Network management resources +reference registered Devices/components and own those behaviors. The +bare-metal provider requests attachment or isolation through the networking +authority, which remains the sole writer of the relevant switch configuration. +This physical/logical separation is consistent with +[RFC 8348's hardware model](https://www.rfc-editor.org/rfc/rfc8348.html) and +[RFC 8345's layered topology model](https://www.rfc-editor.org/rfc/rfc8345.html). + +### Circuit demarcations and external ownership + +Transit, transport/interconnection, and OOB circuits need durable identifiers and +physical demarcation records. A Cable alone does not identify the service, and a +BGP session does not prove its cross-connect. **Proposed decision:** keep the six +inventory kinds initially and reference the owning network/provider service +record; do not assume approval for a seventh `Circuit` kind. Selecting that +record's API/owner, or approving a dedicated physical Circuit kind later, remains +an explicit design decision before circuit-dependent commissioning is automated. + +The proposed minimum association is an owner-qualified external circuit ID, +use category (transit, transport or OOB), and named A/Z demarcations as disclosed. +Each physical demarcation records a resolved Facility reference, room/panel label, +and a typed Device/component/position reference when known, with source and +evidence references. A local cross-connect is a Cable or traced Cable path to +the registered demarcation termination. Do not create a fake far-end Device or +Facility for an undisclosed carrier endpoint. Store a reported label as evidence +until the termination is resolved; it cannot satisfy Cable endpoint reservations. + +For example, a synthetic proposed association on a panel termination is: + +```yaml +externalCircuitRef: + system: example-network-services + type: Circuit + id: EXAMPLE-OOB-0042 +demarcation: A +facilityRef: {name: iad1} +termination: {deviceRef: {name: iad1-demarc-panel}, componentID: rear-07, position: 1} +documentRefs: + - {system: example-drive, id: EXAMPLE-LOA-42, revision: "3", category: LOA} +``` + +This is an association excerpt, not a new resource or an implemented Circuit +API. Circuit identifiers are unique only within their provider/service scope. +The service owner owns identifier and delivery facts; inventory owns their +approved association to physical terminations and the local Cable topology. +Network services consume that association rather than authoring another +expected-peer graph. Prices, commitments, billing, orders and contract state +stay with provider/commercial owners. Addresses, VLANs, BGP, routing, service +bandwidth policy and activation stay with networking/IPAM/Galactic. + +Commissioning evaluates physical demarcation/path verification independently +from provider delivery and routing/service readiness. Missing external contract +support is an explicit unresolved prerequisite, not success or an exemption. +Circuit cancellation does not prove a cross-connect removed; removal of a cable +does not cancel the service. Retain retired associations, circuit IDs and LOA/ +as-built evidence without releasing terminations until physical disconnection +is established. + +### Moves, replacements, and retirement + +- **Move the same asset:** create a successor DeviceClaim naming the existing + Device and reserve the destination. A coordinated maintenance transition + transfers active placement authority with exact predecessor/binding + preconditions. The successor cannot become a second active placement claim. + Preserve the Device and MachineCapacity identities; verify the new placement and + paths before restoring eligibility. Release old physical reservations only + after the affected space/terminations are confirmed free. +- **Replace the whole server:** create a new DeviceClaim, Device, and MachineCapacity. + Do not transfer an existing customer Machine or inherit identity from a reused + name, BMC address, serial field, or rack position. Managed-node replacement + uses the separate NodeClaim/fencing contract. +- **Repair a component:** retain Device identity where the asset remains the + same, but record the replacement component identity and inventory/trust + revision. Revalidate affected port, disk, power, and management bindings. + Reusing a slot ID must not make old component evidence current. +- **Retire or remove equipment:** coordinate physical removal, active consumer + obligations, and reference cleanup explicitly. Deleting an inventory object + does not destroy equipment, release a customer Machine, or prove a rack is empty. + +Bound claims retain their committed Device name and private incarnation evidence +as history. A placement handover +changes the registry-owned active relationship, not the historical binding. +Required Cable plans must be explicitly changed or replaced during a move; +they do not silently follow a Device into another rack. Retain fulfilled claims +while Cable references rely on them, or transfer those references through the +placement-change protocol. Protect active references and reservations during +deletion, including recovery from partial transitions. + +The proposed lifecycle distinguishes Draft, Accepted, Bound, Superseded, +Cancelled and Retired intent/history without requiring one overloaded status +enum. Verification conditions remain independent: a Bound asset can have Unknown +placement evidence. Cancelling an unbound plan releases only reservations proven +unused; uncertain installation work keeps a hold. Superseded/retired records +remain referenceable history and cannot be rebound. Marking an asset retired +does not prove physical removal, secure disposal, tenant cleanup, or provider +release. Each obligation retains its owner and evidence. + +For replacement in an occupied rack slot, a successor plan may be retained as +pending contingent on the predecessor; it cannot obtain a second exclusive +reservation of that footprint. The transition must prove removal/fencing and +conditionally transfer the physical reservation, or use a separately reserved +destination. A crash between steps preserves the old hold or an explicit +transition hold. It never makes the slot free merely because readiness is False. + +## Existing records and migration + +### Manual Fleet records: implemented subset versus target + +The comparison below is pinned to Fleet PR #90, branch +`feat/manual-inventory-records`, commit +`08d6dde8563b7c999ecf839565db2bd37b4dda7e`: its [actual types][manual-types] +and [operations guide][manual-guide]. It is not a claim about merge status or +what is deployed. That revision implements operator-written DeviceClaim/Device +CRDs and access controls, not reservation, enrollment, verification, retirement, +or capacity-publication controllers. Its empty status types do not establish +any of the conditions proposed here. + +| Reviewed implementation | Proposed target and migration constraint | +| --- | --- | +| DeviceClaim describes a long-lived slot; a replacement Device names the same claim. Device identity and `claimRef` are immutable. | Retain this proposal's per-installation claim identity: each move/replacement has a successor claim. Keep a stable slot label or provenance association for operator navigation, not a second binding authority or new Slot kind. This is a proposed resolution, not a schema change already approved in #90. | +| Placement requires string `facility`/`rack`, numeric position, height and face. | Resolve approved Facility/Rack references with source mapping. Convert to explicit placement scope; do not treat strings as global IDs or retain fabricated positions as authoritative. | +| Claimed ports have name/type/speed and embedded `expectedPeer`; Device interfaces may contain `peer`. | Convert approved expected connections into Cable plans once; preserve actual peer reports as sourced observations. Reconcile reciprocal/contradictory entries before creating a single Cable authority. Keep old inline fields read-only during cutover, then remove/deprecate through a versioned migration. | +| Device carries model, serial/system UUID, interfaces and unmapped MACs. | Preserve original values and provenance; adjudicate canonical physical identity and component mappings. Do not coerce provider IDs into chassis serials, or turn interface names/MAC lists into trusted component identity. | +| Optional BMC endpoint and manual provenance live on restricted provider-project objects in Milo. | Preserve access restrictions. Endpoint discovery does not authorize access. Transfer endpoint configuration authority explicitly to the provider management surface before exposing only references/read projections; never run two writable copies. | +| No controller checks binding exclusivity, evidence or `MachineCapacity.deviceRef` resolution. | Resolve duplicate/multiple bindings and protect existing occupancy before enabling automation. Do not infer Accepted, Bound, Ready or allocator eligibility from schema admission. | + +**Claim-lifetime decision gate.** The target remains one committed Device binding +per installation claim, with one active placement authority per Device. A +long-lived slot is useful for naming and history but must not replace an +installation incarnation: otherwise a serial swap can inherit old cabling, +acceptance or verification. Before implementation, approve the successor-claim +protocol and versioned conversion of the manual API, or explicitly amend this +proposal to provide equivalent immutable incarnation semantics. Do not automate +the long-lived-slot convention while presenting it as the target contract. + +For a legacy slot with several Devices, retain the original claim and all Device +records, their immutable bindings, and available registration/retirement history. +Adjudicate the active asset and create explicit installation-history mappings; +unknown order or occupancy remains unresolved. Do not choose the newest timestamp +as proof of physical replacement. The migration must select a versioned storage/ +conversion mechanism that preserves original bindings while representing the +registry-owned active relationship. A raw patch of immutable `claimRef`, deleting +and recreating Devices, or renaming them to fit a successor claim is not a safe +conversion. Existing MachineCapacity/asset-key references must continue to resolve +to the same asset; a move is not grounds to manufacture a new capacity identity. + +**Home and authority decision gate.** The reviewed manual API deliberately stores +records in the provider project's Milo control plane, protected by inventory +roles. This proposal does not move them into a second management-cluster copy. +Choose the scopes for shared Facility/Rack/Cable/PowerFeed references and the +private coordinator ledger before implementation. Internal ledgers retain exact +bindings/evidence; they are not independently writable asset catalogs. Qualify +cross-project reads, status writers, reference authorization and consumer redaction +before broadening access or adding cross-scope relationships. + +### NetBox and provider imports + +Import is observational until an explicit ownership transition. These rules are +derived from the pinned source workflows, not from a live NetBox database audit: + +| Source convention or gap | Required treatment | +| --- | --- | +| Loader Sites group provider metros and can union several provider facility codes. | Preserve source Site ID and provider-code mapping. Do not map NetBox Site one-to-one to Fleet Site or Facility. Unresolved premises stay unresolved and block prerequisites needing a physical Facility. | +| Loaders store provider host IDs in NetBox `serial`. | Retain them as owner-qualified external host IDs with the original field provenance. Never claim a verified chassis serial without independent physical evidence. | +| NetActuate VMs are DCIM Devices. | Classify virtual supply through provider/MachineCapacity contracts. Do not create Fleet physical Devices, ports or racks merely because NetBox uses DCIM. | +| servers.com assigns lowest-free 1U positions because physical positions are undisclosed. | Retain those source values only as synthetic display history. Import known rack association as RackMembership, subject to approved premises mapping; neither reserve nor verify invented units, faces or heights. | +| Commissioning uses asset tags, cable labels, circuit IDs, power feeds, photos and as-built records. | Preserve those distinct identifiers and restricted evidence references; do not flatten everything into serial or a free-form note. Address plans remain IPAM-owned. | +| Provisioning joins serial/model/OOB endpoint with networking data. | Preserve authorized consumer projections and explicit joins, not a duplicate networking API. Imported joins authorize no hardware actions, adoption, capacity eligibility or release. | +| Source lifecycle says active, decommissioning, vanished or decommissioned. | Retain as source observations. None proves physical verification, ownership transfer, secure cleanup, released consumer allocations or a free rack/termination. | + +Import batches retain source snapshot identity, mapping decisions, per-record +outcomes and conflicts for repeatable dry runs. The same source object/revision +must not create duplicate assets after a retry. Missing source observations do +not delete records or release occupancy. Never copy local provider tokens, BMC +password custom fields, kubeconfigs or secret-bearing generated configuration. + +Use a staged, reversible handoff rather than destructive in-place normalization: + +1. Snapshot protected records and audit references; classify physical versus + virtual supply, identifier semantics, known occupancy and placement certainty. + Produce a read-only mapping/conflict report with no hardware effects. +2. Approve Facility mappings, model/component shapes and per-installation history. + Create proposed plans without treating imported occupancy as free. Preserve + current allocator reservations and consumer obligations under their owners. +3. Reconcile expected peer pairs into Cable plans and electrical dependencies into + PowerFeeds. Resolve contradictions and unsupported paths explicitly. Validate + partial placement and scoped external circuit associations without inventing + absent endpoints or upstream sources. +4. Shadow-read and compare authorized provisioning inputs (identity, model, + restricted OOB endpoint and network-owned joins). Establish source parity for + the selected cohort, not an assertion of exhaustive NetBox equivalence. +5. Transfer one writable surface at a time with an explicit cutover revision and + predecessor preconditions. Disable its previous writer before enabling the + replacement. Keep compatibility projections read-only and retain source history. +6. Qualify current evidence and separately authorize custody/adoption and consumer + integrations. Never seed Ready from an old active flag. Recovery/rollback uses + retained cutover state; it cannot reactivate a stale writer, erase new history, + or release a reservation whose physical state is uncertain. + +## Source evidence and limits + +This amendment reviewed repository sources and read-only snapshots of infra +`main` at `d9198940a499be4e744ee0564cf3dc0b3bfcee34`. No live NetBox database audit, +provider call, electrical inspection, or hardware qualification was performed. +The sources motivate contract and migration requirements, not verified fleet-wide +data quality or proof that every production consumer has been found. + +| Pinned source | Evidence used | +| --- | --- | +| [Inventory sync guide][sync-guide], [NetActuate loader][na-loader], [servers.com loader][sc-loader] | Metro/provider mappings, host-ID serial semantics, virtual DCIM records, synthetic rack positions, and provider lifecycle observations. | +| [NetBox server guide][netbox-guide] | Operator inventory and provisioning inputs; existing networking/IPAM associations. | +| [Site commissioning][site-build], [rack work][rack-build], [network hardware][network-build], [compute hardware][compute-build] | Racks, serials, asset tags, labels, feeds, circuit IDs, address plans and external photos/LOAs/as-built artifacts. | +| [Out-of-band access commissioning][oob-build], [transit circuit commissioning][transit-build], [transport circuit commissioning][transport-build] | Physical delivery/demarcation and circuit identifiers distinct from service/routing readiness. | +| [Provisioning joins][provisioning-joins], [IPAM validation][ipam-validation] | Serial/model/OOB and network joins; address/routing validation stays with its current owner. | +| [Fleet manual types][manual-types], [Fleet manual operations][manual-guide] | The implemented manual subset and explicit slot-lifetime/storage divergences at the reviewed PR #90 revision. | + +The [infrastructure provider responsibilities](bare-metal-hardware.md#infrastructure-providers), +[capacity readiness reporting](bare-metal-hardware.md#status), and +[ownership of records replaced by Fleet](bare-metal-hardware.md#replaced-artifacts) retain provider +host IDs and commercial observations with provider authorities and logical +networking with its owners. This amendment does not complete those separate APIs. + +## Validation and qualification matrix + +These are required future admission, concurrency, authorization and hardware +qualification tests, **not tests implemented or passed by this documentation +change**. Offline schema tests cannot establish physical truth. + +| Area | Cases to qualify | Required outcome | +| --- | --- | --- | +| References and scope | Wrong kind, missing scope, cross-project denial, dangling reference, name recreation, stale revision | Reject unauthorized/ambiguous resolution; no inherited binding or evidence. | +| Facility and Rack | Multi-premises provider Site, unknown dimensions, conflicting faces/depth, 0U mount, known rack/unknown position | Preserve uncertainty; no invented geometry or false free-space assertion; exact reservations require accounted occupancy. | +| Identity and components | Duplicate serials, provider ID in serial, VM in DCIM, swapped asset tag, OS rename, replaced NIC/PSU/disk in the same slot | Adjudicate identity; retain source history; invalidate affected mappings without changing asset identity on ordinary repairs. | +| Binding and reservations | Concurrent claims, claim versus direct-Device cable endpoints, lost registration response, crash during handover, restored reservation database | One active placement and exclusive termination/footprint ownership; recover exact committed inputs; uncertainty keeps holds. | +| Cable topology | Copper/optical mismatch, console direction, unresolved demarcation, patch-panel polarity, breakout lane collision, repatch/replacement | Reject unsupported paths; verify each required segment and invalidate changed dependencies, not just end-to-end link state. | +| Power | Shared UPS behind distinct PDUs, unknown rating, mixed units, feed cycles, failover overbudget, stale upstream evidence | No false redundancy or capacity; independent sources and full failover budget proven under a qualified electrical model. | +| Evidence and authority | Forged submitter, copied BMC location, stale scan, inaccessible document, unknown external circuit owner, attempted collector spec write | Fail closed for required checks; no self-attestation from copied intent, no status forgery or automatic exemption. | +| Lifecycle | Occupied-slot replacement, move with active allocation, component removal, retirement with active references, cancelled partially installed plan | Retain history and consumer obligations; no premature physical release, destructive side effect or second active claim. | +| Import/cutover | Duplicate batch, conflicting inline peers, invented rack positions, source disappearance, rollback after new writes | Idempotent mapping, single writer, no Ready backfill or free-capacity window; keep unresolved facts unknown. | +| Access/projections | Inventory roles versus consumer roles, OOB/console endpoint reads, document ACLs, secret-bearing source fields | Restricted management details remain restricted; credentials never enter inventory projections or repository fixtures. | + +Before a facility cohort becomes eligible, record the qualified model variants, +supported connector/patch/breakout/electrical layouts, evidence issuers and +freshness policy, verified failure scenarios and recovery results. Exercise the +actual consumer projection against its retained input revisions. Unsupported +hardware or topology stays unavailable for offerings requiring those checks; +registration alone does not satisfy this gate. + +[manual-types]: https://github.com/datum-cloud/fleet/blob/08d6dde8563b7c999ecf839565db2bd37b4dda7e/internal/api/inventory/v1alpha1/types.go +[manual-guide]: https://github.com/datum-cloud/fleet/blob/08d6dde8563b7c999ecf839565db2bd37b4dda7e/docs/operations/physical-inventory.md +[sync-guide]: https://github.com/datum-cloud/infra/blob/d9198940a499be4e744ee0564cf3dc0b3bfcee34/docs/guides/sync-inventory.md +[na-loader]: https://github.com/datum-cloud/infra/blob/d9198940a499be4e744ee0564cf3dc0b3bfcee34/bin/sync-netactuate-inventory +[sc-loader]: https://github.com/datum-cloud/infra/blob/d9198940a499be4e744ee0564cf3dc0b3bfcee34/bin/sync-serversdotcom-inventory +[netbox-guide]: https://github.com/datum-cloud/infra/blob/d9198940a499be4e744ee0564cf3dc0b3bfcee34/docs/guides/netbox-server.md +[site-build]: https://github.com/datum-cloud/infra/blob/d9198940a499be4e744ee0564cf3dc0b3bfcee34/.claude/skills/site-builds/phases/00-site.md +[oob-build]: https://github.com/datum-cloud/infra/blob/d9198940a499be4e744ee0564cf3dc0b3bfcee34/.claude/skills/site-builds/phases/04-oob.md +[transit-build]: https://github.com/datum-cloud/infra/blob/d9198940a499be4e744ee0564cf3dc0b3bfcee34/.claude/skills/site-builds/phases/05-transit.md +[transport-build]: https://github.com/datum-cloud/infra/blob/d9198940a499be4e744ee0564cf3dc0b3bfcee34/.claude/skills/site-builds/phases/06-transport.md +[network-build]: https://github.com/datum-cloud/infra/blob/d9198940a499be4e744ee0564cf3dc0b3bfcee34/.claude/skills/site-builds/phases/07-nethw.md +[compute-build]: https://github.com/datum-cloud/infra/blob/d9198940a499be4e744ee0564cf3dc0b3bfcee34/.claude/skills/site-builds/phases/08-computehw.md +[rack-build]: https://github.com/datum-cloud/infra/blob/d9198940a499be4e744ee0564cf3dc0b3bfcee34/.claude/skills/site-builds/phases/09-rack.md +[provisioning-joins]: https://github.com/datum-cloud/infra/blob/d9198940a499be4e744ee0564cf3dc0b3bfcee34/provisioning/baremetal/lib/common.sh +[ipam-validation]: https://github.com/datum-cloud/infra/blob/d9198940a499be4e744ee0564cf3dc0b3bfcee34/bin/validate-netbox-ipam diff --git a/docs/proposals/fleet-management/inventory.md b/docs/proposals/fleet-management/inventory.md index a96068e9..528827ac 100644 --- a/docs/proposals/fleet-management/inventory.md +++ b/docs/proposals/fleet-management/inventory.md @@ -7,556 +7,213 @@ latest-milestone: "v0.1" # Fleet inventory -Part of the [Fleet infrastructure management service](README.md). Inventory owns -physical installation intent, registered assets, and verified physical -topology. [Machine allocation](bare-metal-hardware.md) consumes those records; -[bare-metal provisioning](bare-metal-provisioning.md) executes authorized work -on the hardware. Separate controllers and permissions preserve these -responsibilities within Fleet. +Part of the [Fleet infrastructure management service](README.md). Fleet inventory +should give infrastructure operators a reliable answer to four questions: what +equipment do we have, where is it, how is it connected, and is it ready for use? + +**Status:** This is a proposal. The existing manual records cover only part of +this experience; the verification and safety requirements below have not yet +been implemented or tested on hardware. Implementation details belong in the +[physical inventory contracts, examples, and migration notes](inventory-reference.md). - [Summary](#summary) -- [Goals](#goals) -- [Non-goals](#non-goals) +- [Goals and boundaries](#goals-and-boundaries) - [Proposal](#proposal) - - [Resources and authority](#resources-and-authority) - - [Plan a physical installation](#plan-a-physical-installation) - - [Reserve physical resources](#reserve-physical-resources) - - [Register and bind a device](#register-and-bind-a-device) - - [Verify the installation](#verify-the-installation) - - [Cabling, power, and network configuration](#cabling-power-and-network-configuration) + - [Resources and responsibilities](#resources-and-responsibilities) + - [From installation plan to ready equipment](#from-installation-plan-to-ready-equipment) + - [Location and equipment identity](#location-and-equipment-identity) + - [Connections and power](#connections-and-power) - [Moves, replacements, and retirement](#moves-replacements-and-retirement) -- [Implementation](#implementation) -- [Rollout plan](#rollout-plan) -- [Open qualification questions](#open-qualification-questions) +- [Bringing existing records into Fleet](#bringing-existing-records-into-fleet) +- [First release and success criteria](#first-release-and-success-criteria) +- [Decisions still needed](#decisions-still-needed) ## Summary -Operators declare a `DeviceClaim` before equipment is registered. It expresses -the expected hardware, approved rack placement, declared ports, and required -cables. Acceptance reserves the physical resources. A trusted registrar matches -the equipment to that accepted plan and creates an exclusively bound `Device`. -Controllers compare physical evidence with the plan before reporting readiness. - -A `DeviceClaim` is a physical installation expectation. A customer `Machine` is -the consumer lifecycle resource whose private MachineAllocation reserves provider -compute capacity. They have independent lifetimes. -Neither registering a Device nor making its DeviceClaim Ready authorizes power -changes, boot-based inspection, installation, cleaning, or consumer allocation. - -This is the target Fleet inventory model, independent of the existing inventory -service's schema. The proposed group is `fleet.datumapis.com/v1alpha1`; -the API group, fields, and scopes remain provisional. Examples show operator -resources in `infra-ops`, not implemented CRDs or manifests to apply. Hardware -identifiers and evidence handles are illustrative; Kubernetes UIDs remain private -same-API-server recreation evidence rather than authored references. - -## Goals - -- Record physical identity, placement, cabling, and power dependencies once. -- Reserve nonconflicting installations before hardware arrives. -- Admit equipment only through trusted registration against an accepted claim. -- Preserve expected and observed state separately, including incomplete work. -- Provide current, attributable evidence for allocation and operation gates. -- Support servers, network devices, power equipment, and passive infrastructure. -- Preserve asset history through repairs, moves, and changes of consumer. - -## Non-goals - -- Allocating compute to consumers, configuring an OS, or managing clusters. -- Storing BMC/switch credentials in broadly readable inventory objects. -- Owning VLANs, VRFs, IP allocations, routing, or workload network attachments. -- Treating discovery as authorization to adopt or modify hardware. -- Inferring physical completion from a YAML declaration or link reachability. -- Automating procurement, warehouse management, or every field-work process in - the first implementation. +Operators need to plan new installations without double-booking rack space, +confirm that delivered equipment matches the plan, and identify missing or +incorrect connections before making it available. They also need to move, repair +and replace equipment without losing its history or disrupting customers by +accident. + +Fleet should keep the installation plan separate from what technicians and +trusted tools actually find. Operators should be able to see what has been +checked, what is wrong, and what is still unknown, with supporting records for +each result. A missing measurement must not look like a successful check. + +Inventory readiness is one input to [machine allocation](bare-metal-hardware.md), +not permission to use or change equipment. Recording a device or marking it ready +must never start it, erase it, install software, assign it to a customer, or end +an existing customer reservation. Those actions require separate approval through +[hardware provisioning and operations](bare-metal-provisioning.md). + +## Goals and boundaries + +- Give operators one reliable record of equipment, placement, cables and power. +- Prevent conflicting installation plans and show what remains to be completed. +- Preserve equipment history through imports, moves, repairs and retirement. +- Support servers, network and power equipment, and passive devices such as patch + panels, including equipment that cannot report its own state. + +Fleet inventory does not replace purchasing, billing, work scheduling, network +address management, routing, or cluster management. It links to those services +rather than keeping competing records. Passwords and other credentials never +belong in public inventory or repository examples. ## Proposal -### Resources and authority - -- **`Facility`:** Provider-neutral physical premises, associated with geographic Location. - Provider codes do not define its identity. -- **`Rack`:** Facility membership, mounting capacity, and physical constraints. -- **`DeviceClaim`:** Operator's expected installation, physical reservations, and one - committed Device binding. -- **`Device`:** Canonical registered physical asset: server, switch, router, PDU, console - server, or patch panel. -- **`Cable`:** Sole authority for expected physical connections and their termination - mappings. -- **`PowerFeed`:** Electrical supply connection, capacity, and upstream dependency - information. - -Ports and components are typed entries with stable IDs within a Device. They do -not require a separate public kind initially. Network interfaces, power -inlets/outlets, console ports, and pass-through terminations have different -connection rules. Component identity must remain distinct from mutable OS names -such as `eth0` and from logical interfaces such as a VLAN or bond. - -For owned servers, `MachineCapacity` has an immutable `deviceRef` to the -registered Device. It is provider capacity with allocation and reclamation -policy; it does not independently edit the asset's serial number, rack placement, -or cabling. A switch or patch panel can be a Device without being -MachineCapacity. Inventory owns -physical observations; the provider owns management configuration and hardware -operations; networking owns network configuration. An inventory relationship -is not a Kubernetes garbage-collection ownership relationship. - -A Device represents identifiable physical equipment. Do not fabricate a Device, -rack, or physical port for a provider VM or an offering that discloses no -physical asset identity. Such providers still participate through the generic -MachineCapacity contract and their own observed capabilities. - -Operator authorization controls claims, physical plans, and manual evidence. -Only the trusted registration service creates registered Devices and writes -identity/placement bindings. Collectors write observations through validated -interfaces; they cannot change the approved plan. References crossing an -administrative scope require explicit authorization on both sides. A namespace -or matching label alone does not grant that authority. - -### Plan a physical installation - -The Facility describes physical premises. A Fleet `Site` can select eligible -Facilities as operational policy without moving their assets. Location remains -the geographic reference; neither Site nor Facility is a provider identifier. - -```yaml -apiVersion: fleet.datumapis.com/v1alpha1 -kind: Facility -metadata: - name: iad1 - namespace: infra-ops -spec: - displayName: Ashburn Facility 1 - locationRef: - name: us-east-1 ---- -apiVersion: fleet.datumapis.com/v1alpha1 -kind: Rack -metadata: - name: iad1-r12 - namespace: infra-ops -spec: - facilityRef: {name: iad1} - heightUnits: 42 ---- -apiVersion: fleet.datumapis.com/v1alpha1 -kind: DeviceClaim -metadata: - name: iad1-r12-u20-server - namespace: infra-ops -spec: - role: Server - expectedIdentity: - manufacturer: Dell - model: PowerEdge-R650 - serialNumber: EXAMPLE-SERVER-001 - placement: - rackRef: {name: iad1-r12} - position: 20 - heightUnits: 1 - face: Front - fullDepth: true - verification: - requiredChecks: [Identity, RackPlacement, NetworkPaths, PowerPaths] - ports: - - {id: bmc, type: EthernetPort, role: Management, physicalLabel: BMC} - - {id: nic1-p1, type: EthernetPort, role: Data, physicalLabel: NIC1/P1} - - {id: psu1, type: PowerInlet, physicalLabel: PSU1} - - {id: psu2, type: PowerInlet, physicalLabel: PSU2} - cableRefs: - - {name: iad1-r12-srv01-management} - - {name: iad1-r12-srv01-data} - - {name: iad1-r12-srv01-power-a} - - {name: iad1-r12-srv01-power-b} -``` - -The example assumes an existing management switch `iad1-oob01`, data switch -`iad1-r12-leaf-a`, and PDUs `iad1-r12-pdu-a`/`iad1-r12-pdu-b`, each registered -through its own claim. Their referenced components and upstream power paths -must exist and be verified. These four Cable plans describe the server's -required connections before the server Device exists: - -```yaml -apiVersion: fleet.datumapis.com/v1alpha1 -kind: Cable -metadata: - name: iad1-r12-srv01-management - namespace: infra-ops -spec: - medium: CopperEthernet - a: [{deviceClaimRef: {name: iad1-r12-u20-server}, portID: bmc}] - b: [{deviceRef: {name: iad1-oob01}, componentID: port12}] ---- -apiVersion: fleet.datumapis.com/v1alpha1 -kind: Cable -metadata: - name: iad1-r12-srv01-data - namespace: infra-ops -spec: - medium: DirectAttachCopper - a: [{deviceClaimRef: {name: iad1-r12-u20-server}, portID: nic1-p1}] - b: [{deviceRef: {name: iad1-r12-leaf-a}, componentID: ethernet20}] ---- -apiVersion: fleet.datumapis.com/v1alpha1 -kind: Cable -metadata: - name: iad1-r12-srv01-power-a - namespace: infra-ops -spec: - medium: Power - a: [{deviceRef: {name: iad1-r12-pdu-a}, componentID: outlet20}] - b: [{deviceClaimRef: {name: iad1-r12-u20-server}, portID: psu1}] ---- -apiVersion: fleet.datumapis.com/v1alpha1 -kind: Cable -metadata: - name: iad1-r12-srv01-power-b - namespace: infra-ops -spec: - medium: Power - a: [{deviceRef: {name: iad1-r12-pdu-b}, componentID: outlet20}] - b: [{deviceClaimRef: {name: iad1-r12-u20-server}, portID: psu2}] -``` - -`cableRefs` identifies prerequisites; it does not repeat expected peers. Cable -owns the endpoint declarations. A planned endpoint references a DeviceClaim -and its declared port ID; a registered endpoint references a Device and stable -component ID. Names are convenient authoring references. Acceptance retains the -exact local object incarnations privately and records approved dependency -revisions. Recreating an object with the same name never inherits a reservation. - -Placement may instead name `placement.facilityRef` without a rack. This covers -unracked equipment and rented bare metal whose physical Facility is known but -whose rack/patching is not disclosed. The claim must state its verification -requirements explicitly; for example: - -```yaml -# Excerpt for an identified physical server with facility-level visibility. -spec: - placement: - facilityRef: {name: iad1} - verification: - requiredChecks: [Identity, FacilityPlacement] -``` - -Admission constrains required checks using operator policy and the intended -offering. Authors cannot weaken verification to make a failed installation -pass. Rack placement derives Facility through the Rack; if both references are -supplied they must agree. Undisclosed rack/cable facts remain unknown, not -invented or marked physically inapplicable. `Ready` for a facility-scoped claim -does not imply verified rack position, cabling, power redundancy, or eligibility -for an offering that requires those facts. Historical UUID/IP/disk lists are -migration inputs, not sufficient verification evidence. - -### Reserve physical resources - -Acceptance commits a retained plan covering the claim and its required Cable -inputs. Inventory must reserve the applicable declared rack footprint, physical -terminations, and power capacity without races. Rack checks include occupied units, -front/rear constraints, full-depth equipment, and pending installations. The -model also supports 0U mounting and equipment outside a rack; it must not assign -them fictitious rack-unit positions. - -Endpoint reservations belong to one exact Cable incarnation and identify one -exact Device or DeviceClaim incarnation plus termination/position. Local object -identity is retained as private same-API-server evidence. Two cables cannot reserve the same -exclusive termination. Resolving a claim endpoint to a registered component -must preserve that reservation, including conflicts with direct Device -references. A successor placement cannot reserve an occupied resource merely -because the previous object's readiness is False. - -Use durable conditional commits or an equivalent serialized reservation -protocol, not an admission-time list check or controller-local lock. Partial -acquisition stays Pending and is recovered or explicitly unwound. Report -`Accepted=True` only after the complete current plan is committed. Hold -reservations through controller restarts and uncertainty; timeouts and expired -worker leases do not prove that space, cabling, or power is physically free. - -Referenced Cable plans may target other unbound claims. Validate and reserve -the intended endpoints without requiring those Devices to be Ready. Otherwise -two devices awaiting a connection could never be commissioned. Editing an -unbound plan requires revalidation and a new committed plan revision; stale -acceptance or registration requests cannot use the previous revision. - -### Register and bind a device - -A registration request must authenticate its enrollment channel and identify -an existing accepted DeviceClaim and approved plan revision. Match expected -identity against independently trusted evidence. Serial numbers, MAC -addresses, and SMBIOS UUIDs are matching attributes, not authentication. -Passive devices register through an authorized technician or integration; -they do not need to run a host agent. - -The registrar commits one reciprocal DeviceClaim-to-Device relationship and -retains both local object incarnations as private same-API-server evidence. One -claim binds one Device for one installation incarnation. One physical asset -cannot acquire duplicate Device identities, -and one Device has at most one active placement authority. Recovery after a -lost response finds the committed registration instead of creating a second -asset. Ambiguous matches, unexpected identities, expired authorization, or -already-bound claims fail closed. Unknown equipment remains isolated discovery -evidence; it cannot manufacture an accepted claim or eligible capacity. - -Registration does not require all physical verification to have succeeded. A -Device can exist in commissioning with a placement or wiring discrepancy: - -```yaml -# Registrar-created snapshot, not an operator-authored apply input. -apiVersion: fleet.datumapis.com/v1alpha1 -kind: Device -metadata: - name: server-example-001 - namespace: infra-ops -spec: - # Registry-owned. A raw reference edit cannot move the asset. - claimRef: - name: iad1-r12-u20-server - identity: - manufacturer: Dell - model: PowerEdge-R650 - serialNumber: EXAMPLE-SERVER-001 -status: - observedPlacement: - rackRef: - name: iad1-r12 - position: 20 - face: Front - evidenceRef: installation-scan-001 - components: - - {id: management-port-1, type: EthernetPort, physicalLabel: BMC} - - id: nic-slot2-port1 - type: EthernetPort - physicalLabel: NIC1/P1 - macAddress: "02:00:00:00:12:01" - - {id: power-supply-1, type: PowerInlet, physicalLabel: PSU1} - - {id: power-supply-2, type: PowerInlet, physicalLabel: PSU2} -``` - -Declared claim ports resolve using trusted chassis labels, qualified hardware -layout, and physical component identity. A controller cannot swap the mapping -of `nic1-p1` to a different NIC merely to make the observed neighbor match. -The Device records actual components; the claim records the approved mapping -from its intended ports to those components. - -### Verify the installation - -Commissioning has an ordered dependency graph: - -```text -Accepted plan and physical reservations - -> trusted registration and exclusive Device binding - -> claim-port mapping and Cable endpoint resolution - -> identity, placement, network, and power evidence evaluated - -> physical Ready -``` - -Cable resolution depends on binding, not Device Ready. Protected enrollment -connectivity must exist before complete production-path verification. Any -inspection that boots or modifies a device requires a separately authorized -hardware operation; inventory readiness cannot authorize its own evidence -collection effects. - -- **Hardware identity and capabilities:** Authenticated BMC/qualified agent observations - or trusted installation evidence matched to the enrolled asset. Claimed identifiers - alone are insufficient. -- **Switch and port adjacency:** Trusted switch-side observations corroborated with the - enrolled NIC mapping. MAC learning or agent-reported LLDP alone does not prove asset - identity. -- **Link capability:** Current port state, negotiated parameters, and relevant hardware - observations; link-up is not proof of a complete passive path. -- **Exact rack position/orientation:** Authorized installation scans/attestations or - qualified rack instrumentation. Management-network reachability does not establish a - rack unit. -- **Passive cable identity and patch path:** Verified endpoint/cable-label scans or - qualified instrumentation. LLDP does not identify each passive segment. -- **PSU, outlet, and upstream feed:** Verified physical mappings and suitable - observations/instrumentation. Two healthy PSUs do not establish independent supplies. - -Link discovery can supply switch/port observations through qualified collectors; -it does not establish every physical fact above. Redfish's rack/offset fields -are writable metadata, so copying the intended position into a BMC and reading -it back is not independent placement evidence. See the -[Redfish data model](https://redfish.dmtf.org/schemas/v1/DSP0268_2025.3.pdf). - -Conditions report `Accepted`, `Bound`, `IdentityVerified`, `PlacementVerified`, -`NetworkPathVerified`, `PowerPathVerified`, and `Ready` separately. Readiness -requires every admitted required check for the current approved plan and -records the evaluated verification scope. `PlacementVerified` identifies -whether it evaluated Facility or exact Rack placement. Missing or stale -required evidence is Unknown; a verified mismatch is False. Checks outside the -scope remain explicitly unevaluated. A policy may mark a check physically -inapplicable, such as power for a passive panel; absence of evidence must not -silently become an exemption. Downstream controllers require the specific -verified facts their operation or offering needs, not an unqualified Ready bit. - -Each evaluation privately retains the exact local claim, Cable, Rack, PowerFeed, -and Device incarnations and records their revisions, Device -identity/component/trust revision, evaluated input digest, -evidence provenance, and verification time. Standard condition fields include -`observedGeneration`, reason, message, and transition time. The owning object's -generation alone is insufficient: recabling, a NIC replacement, or new trust -material can invalidate evidence without changing that object's spec. - -Keep bounded summaries and protected evidence references in status. Retain the -evaluated plan and evidence needed to explain the result. Evidence freshness -is check-specific: a current adjacency observation and an installation scan -have different validity rules. Relevant topology or hardware changes invalidate -the applicable result; an old `Ready=True` is not blanket authorization. - -```yaml -# Abbreviated controller-written verification snapshot after successful checks. -# Routine condition timestamps/messages are omitted for readability. -apiVersion: fleet.datumapis.com/v1alpha1 -kind: DeviceClaim -metadata: - name: iad1-r12-u20-server - namespace: infra-ops -status: - observedGeneration: 1 - evaluatedPlanDigest: "sha256:" - evaluatedChecks: [Identity, RackPlacement, NetworkPaths, PowerPaths] - evidenceRef: commissioning-evaluation-001 - deviceRef: - name: server-example-001 - portBindings: - - {claimPortID: bmc, deviceComponentID: management-port-1} - - {claimPortID: nic1-p1, deviceComponentID: nic-slot2-port1} - - {claimPortID: psu1, deviceComponentID: power-supply-1} - - {claimPortID: psu2, deviceComponentID: power-supply-2} - conditions: - - {type: Accepted, status: "True", reason: PhysicalReservationsCommitted, observedGeneration: 1} - - {type: Bound, status: "True", reason: ExclusiveDeviceBindingCommitted, observedGeneration: 1} - - {type: IdentityVerified, status: "True", reason: TrustedEnrollmentMatched, observedGeneration: 1} - - {type: PlacementVerified, status: "True", reason: InstallationScanVerified, observedGeneration: 1} - - {type: NetworkPathVerified, status: "True", reason: TrustedPeerEvidenceMatched, observedGeneration: 1} - - {type: PowerPathVerified, status: "True", reason: PowerPathEvidenceVerified, observedGeneration: 1} - - {type: Ready, status: "True", reason: RequiredEvidenceCurrent, observedGeneration: 1} -``` - -Cable status similarly reports resolved Device names/component IDs; protected -evidence privately retains the exact local Device incarnations. It separately -reports evidence for endpoint adjacency, cable identity, and any pass-through -path. It never rewrites spec to agree with discovery. Physical drift blocks -new allocations and operations that require the invalidated fact and alerts -operators. It does not independently authorize eviction, power-off, wiping, or -release of an existing consumer reservation. - -### Cabling, power, and network configuration - -A Cable connects typed physical terminations. Pass-through components on patch -panels retain explicit internal front/rear mappings. Breakout cables require -explicit position/lane mappings. Trace the complete supporting path; reject an -unsupported mapping rather than assuming a direct connection. NetBox's -[cable model](https://netboxlabs.com/docs/netbox/models/dcim/cable/) provides an -established physical-path precedent. It is not a requirement to use NetBox's -schema or implementation. - -A PDU is a Device. Its component model maps each outlet to the input that -supplies it. Power cables connect feeds to PDU inputs and outlets to device -inlets; a feed termination uses a typed `powerFeedRef`, resolved by name with its -exact local incarnation retained privately. -PowerFeed records include rated/usable capacity and known upstream -sources; unknown dependencies remain explicit. Reservation calculations must -account for the declared redundancy/failure scenario, not assume that each of -two feeds supplies half the load. Two differently named PDUs can share the same -UPS or upstream circuit. See the -[power-feed](https://netboxlabs.com/docs/netbox/models/dcim/powerfeed/) and -[outlet](https://netboxlabs.com/docs/netbox/models/dcim/poweroutlet/) precedents. - -Rack, switch, and power failure domains are derived from verified dependency -information, including shared upstream resources. Labels can expose validated -domains for selection; different labels do not establish physical independence. - -Physical connectivity does not select the VLAN, VRF, IP address, routing -adjacency, or tenant network carried over a link. Network management resources -reference registered Devices/components and own those behaviors. The -bare-metal provider requests attachment or isolation through the networking -authority, which remains the sole writer of the relevant switch configuration. -This physical/logical separation is consistent with -[RFC 8348's hardware model](https://www.rfc-editor.org/rfc/rfc8348.html) and -[RFC 8345's layered topology model](https://www.rfc-editor.org/rfc/rfc8345.html). +### Resources and responsibilities + +The proposed experience uses six records: + +| Record | What it tells an operator | +| --- | --- | +| Facility | The physical premises where equipment is installed. | +| Rack | The rack's location, available mounting space and physical limits. | +| DeviceClaim | What equipment is expected for one installation and which resources are reserved for it. | +| Device | The actual piece of equipment, its identity and its components. | +| Cable | Which physical ports should be connected. | +| PowerFeed | Where electrical supply comes from and how much load it can support. | + +Geographic Location and physical Facility are separate from +[Site rules for choosing where machines may run](cluster-lifecycle.md#site-and-cluster-resources). +A provider's metro name may cover several buildings; it must not be treated as +one physical facility without checking. + +Operators approve installation plans. Authorized registration establishes which +physical equipment matches each plan. Technicians and trusted tools provide +observations; Fleet checks those observations against the approved plan rather +than silently changing the plan to match them. + +Each record has one responsible writer. Providers remain responsible for hardware +controls, networking services for addresses and switch configuration, and Galactic +for routing. Management addresses, customer information and supporting documents +remain visible only to authorized users. + +### From installation plan to ready equipment + +1. **Plan the installation.** Record the expected equipment, location, cables, + power needs and required checks. Reserve the relevant space, ports and power + so another installation cannot claim them, even if requests arrive together. +2. **Record what arrived.** Check the actual equipment against the approved plan. + One installation plan identifies one device, and a device has only one active + placement. Retrying a registration must not create a duplicate asset. +3. **Check the installation.** Verify equipment identity, placement and required + network and power paths. Show missing work and mismatches separately from + completed checks. Connected devices can be checked together; neither must + already be ready before its cable endpoints can be identified. +4. **Report what is ready.** State which checks passed and what they cover. + For example, confirming a facility does not confirm a rack position. Services + using inventory must require the checks appropriate to their task. + +Keep the approved plan, supporting evidence and change history behind each result. +A cable change or component replacement requires new checks where it affects the +installation. Old results must not carry over merely because a name was reused. +If collecting evidence requires starting or changing equipment, that work needs +separate authorization. + +### Location and equipment identity + +Operators should be able to record only what is known: a facility, a rack without +an exact position, an exact rack position, or a side-mounted location. Unknown +space must not appear available. Invented positions cannot justify reservations +or verification; new reservations need enough evidence to avoid existing equipment. + +Keep manufacturer serial numbers, operator asset tags and provider host IDs +separate, including where each value came from. None alone proves that equipment +is trusted. Virtual machines must not become physical Fleet devices just because +an imported system records them alongside hardware. + +Track network, power, console and patch-panel ports separately, along with +replaceable parts. A software interface name is not a physical port identity. +After a repair, preserve the device history but record the replacement part and +recheck affected connections. Reusable model descriptions can reduce repeated +entry, but must be checked against the actual equipment. + +### Connections and power + +Cable records are the single source for planned physical connections. Device +plans reference them rather than keeping another list of expected neighbors. +Checks must follow patch panels and split cables, not assume that a working +end-to-end link proves every connection is correct. + +Power checks must follow the supply through distribution equipment to the device. +Two power supplies do not prove redundancy if they share an upstream failure +point. Reserve enough power for the agreed failure scenario, not just normal +operation. Unknown supply details must remain unverified. + +Operators also need circuit identifiers and the physical handoff points for +internet, transport and out-of-band management connections. The proposal links +these to the service owner's records and local cables. Service delivery, prices, +addresses and routing remain with their owners. Whether Fleet needs a separate +Circuit record is still an open decision, not an approved addition. ### Moves, replacements, and retirement -- **Move the same asset:** create a successor DeviceClaim naming the existing - Device and reserve the destination. A coordinated maintenance transition - transfers active placement authority with exact predecessor/binding - preconditions. The successor cannot become a second active placement claim. - Preserve the Device and MachineCapacity identities; verify the new placement and - paths before restoring eligibility. Release old physical reservations only - after the affected space/terminations are confirmed free. -- **Replace the whole server:** create a new DeviceClaim, Device, and MachineCapacity. - Do not transfer an existing customer Machine or inherit identity from a reused - name, BMC address, serial field, or rack position. Managed-node replacement - uses the separate NodeClaim/fencing contract. -- **Repair a component:** retain Device identity where the asset remains the - same, but record the replacement component identity and inventory/trust - revision. Revalidate affected port, disk, power, and management bindings. - Reusing a slot ID must not make old component evidence current. -- **Retire or remove equipment:** coordinate physical removal, active consumer - obligations, and reference cleanup explicitly. Deleting an inventory object - does not destroy equipment, release a customer Machine, or prove a rack is empty. - -Bound claims retain their committed Device name and private incarnation evidence -as history. A placement handover -changes the registry-owned active relationship, not the historical binding. -Required Cable plans must be explicitly changed or replaced during a move; -they do not silently follow a Device into another rack. Retain fulfilled claims -while Cable references rely on them, or transfer those references through the -placement-change protocol. Protect active references and reservations during -deletion, including recovery from partial transitions. - -## Implementation - -Inventory requires admission/authorization, a durable reservation and binding -coordinator, trusted registration, and evidence evaluation. These are controller -responsibilities, not a requirement for another public type per process. -Implementations may share infrastructure with other Fleet subsystems while -retaining separate field ownership and credentials. - -Hardware providers and network collectors submit authenticated observations; -authorized technicians submit physical-work evidence. Enrollment of passive -infrastructure follows the same claim and binding rules. Backfill existing -assets through explicit approved claims and non-destructive registration; -importing a record must not invoke boot, cleaning, or network changes. - -Consumers read only the inventory projections they are authorized to see. -Privileged BMC/switch endpoints, credentials, and tenant allocation details -remain in their respective management domains. Physical evidence must be -available to the controllers enforcing prerequisites without requiring those -controllers to assume inventory ownership. - -## Rollout plan - -1. Implement Facility/Rack/DeviceClaim/Device/Cable/PowerFeed contracts, typed - components, physical reservation validation, and trusted operator - registration. Qualify one hardware/rack layout, including passive equipment. -2. Exercise one facility's management, data, console where used, and power - paths. Demonstrate wrong identity, wrong port, wrong rack placement, missing - evidence, and stale evidence remaining unavailable without destructive - side effects. Verify patch-panel/breakout paths used by that facility. -3. Integrate current physical-readiness evidence with MachineCapacity eligibility and - network attachment prerequisites. Test concurrent claims, duplicate - registration, lost responses, controller restart, object-name reuse, and - changes to dependencies during evaluation. -4. Qualify moves, component replacement, retirement, and a recovered reservation - database. Demonstrate no duplicate active placement, premature capacity - reuse, or implicit consumer eviction before expanding to more facilities. - -## Open qualification questions - -- Which platform scopes and IAM permissions govern shared Facilities, operator - claims, registrar writes, evidence submission, and cross-scope references? -- Which durable reservation/commit mechanism enforces rack, termination, - power-capacity, and identity uniqueness through crashes and restoration? -- What independently trusted enrollment mechanism and identity-deduplication - rules apply to each active and passive hardware family? -- Which rack/cable/power checks require technician evidence, which have - qualified instrumentation, and what invalidates or expires each result? -- What component, pass-through, breakout, and redundant-power layouts must the - first facility support, and how is unsupported topology reported? -- What explicit maintenance and placement-handover protocol preserves active - allocations and releases old physical reservations only after verification? - -These are implementation qualification gates. None changes the ownership, -exclusive-binding, or no-implicit-destructive-action contracts above. +- **Move equipment:** create a new installation plan for the same device, reserve + its destination and check its new connections. Keep the device and provider + capacity identities. Release old space and ports only after confirming they + are free. +- **Replace equipment:** create a new installation plan, device record and provider + capacity record. Do not transfer customer assignments or successful checks just + because the replacement uses the same rack position or management address. +- **Repair equipment:** keep the device record, record changed parts and repeat + the affected checks. +- **Retire equipment or cancel a plan:** keep the history and outstanding customer + obligations. Deleting a record does not prove removal, data erasure or release. + +A replacement cannot double-book an occupied slot. When work is interrupted or +its outcome is unclear, retain the reservation until it is safe to release it. +Moves also require explicit cable-plan changes; cables do not automatically +follow a device to its new location. + +## Bringing existing records into Fleet + +The [existing manual inventory guide][manual-guide] describes a smaller model: +installation plans represent long-lived slots, locations are text fields, and +expected connections are stored on ports. This proposal instead uses a new plan +for each installation and separate Cable records. That difference must be settled +before automating moves and replacements. + +Import should preserve existing equipment identities, customer reservations and +history. Change the responsible writer one record type at a time. Do not delete +and recreate assets, assume occupied space is free, or mark old records ready +without new checks. + +Source data needs interpretation: NetBox sites may group several premises, +serial fields may contain provider host IDs, device lists may include virtual +machines, and rack positions may have been invented for display. Preserve these +limitations rather than turning them into verified facts. + +See the [comparison with existing records and migration steps](inventory-reference.md#existing-records-and-migration) +and the [source review and its limits](inventory-reference.md#source-evidence-and-limits). +No live NetBox audit has been performed, and complete coverage of existing data +has not been established. + +## First release and success criteria + +Start with a small set of equipment in one facility. Operators should be able to +plan an installation, register equipment, find incorrect or incomplete work, and +see which checks make it suitable for use. + +Before expanding, demonstrate that Fleet prevents conflicting reservations, +keeps unknown facts visible, and preserves occupied resources after interrupted +work. Moves, replacements, repairs and retirement must preserve history without +accidentally releasing customer equipment. Imported records must not trigger +hardware actions or become available capacity on their own. + +The [detailed validation and hardware acceptance checks](inventory-reference.md#validation-and-qualification-matrix) +describe work still required; they are not a report of tests already passed. + +## Decisions still needed + +- Agree how to move from long-lived slot plans to one plan per installation + without losing existing bindings or history. +- Decide who can view and change shared facilities, racks, cables and feeds, + and where their authoritative records live. +- Choose how reservations survive failures, which hardware and connection layouts + are supported first, and what evidence is sufficient and recent enough. +- Assign ownership of circuit references and physical handoff points, and decide + whether a separate Circuit record is needed. + +[manual-guide]: https://github.com/datum-cloud/fleet/blob/08d6dde8563b7c999ecf839565db2bd37b4dda7e/docs/operations/physical-inventory.md diff --git a/hack/netbox_inventory.py b/hack/netbox_inventory.py new file mode 100644 index 00000000..1d6f3686 --- /dev/null +++ b/hack/netbox_inventory.py @@ -0,0 +1,711 @@ +#!/usr/bin/env python3 +"""GET-only NetBox snapshot and offline, create-only Fleet GitOps handoff.""" + +import argparse +import copy +import datetime +import hashlib +import json +import os +from pathlib import Path +import re +import sys +import time +import urllib.error +import urllib.parse +import urllib.request + + +COMPONENTS = { + "interfaces": "NetworkPort", "power-ports": "PowerInlet", + "power-outlets": "PowerOutlet", "console-ports": "ConsolePort", + "console-server-ports": "ConsoleServerPort", "front-ports": "FrontPort", + "rear-ports": "RearPort", "modules": "Module", + "inventory-items": "InventoryItem", "device-bays": "DeviceBay", +} +SUPPORT = {"manufacturers", "device-types", "module-types", "device-roles", "rack-types"} +REQUIRED = {"dcim/" + name for name in ( + "sites", "locations", "racks", "devices", "device-types", "manufacturers", + "cables", "power-feeds", "power-panels", *COMPONENTS, +)} | {"circuits/circuits", "circuits/circuit-terminations"} +FIELDS = { + "id", "name", "display", "slug", "model", "manufacturer", "device_type", + "module_type", "device", "site", "location", "rack", "region", "parent", + "role", "type", "status", "serial", "asset_tag", "position", "face", + "u_height", "is_full_depth", "rear_port", "rear_port_position", "positions", + "power_port", "power_panel", "supply", "voltage", "amperage", "phase", + "a_terminations", "b_terminations", "object_type", "object_id", "object", + "termination_type", "termination_id", "termination", "circuit", "cid", + "provider", "term_side", "label", "value", "last_updated", "created", +} + + +def canonical(value): + return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=True) + + +def digest(value): + return "sha256:" + hashlib.sha256(canonical(value).encode()).hexdigest() + + +def reference_id(value): + if isinstance(value, dict): + value = value.get("id") + return str(value) if value is not None else "" + + +def value(record, key, default=""): + item = record.get(key, default) + return item.get("value", default) if isinstance(item, dict) else item + + +def sanitize(item): + if isinstance(item, dict): + return {key: sanitize(child) for key, child in item.items() if key in FIELDS} + if isinstance(item, list): + return [sanitize(child) for child in item] + return item + + +def name_ok(name): + return isinstance(name, str) and len(name) <= 253 and re.fullmatch(r"[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?", name) + + +class NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, request, response, code, message, headers, url): + raise ValueError("NetBox redirects are refused; configure the canonical HTTPS origin") + + +class Reader: + def __init__(self, url, token, auth_scheme="Bearer"): + self.base = url.rstrip("/") + parsed = urllib.parse.urlsplit(self.base) + if parsed.scheme != "https" or not parsed.hostname or parsed.username or parsed.password or parsed.query or parsed.fragment or parsed.path: + raise ValueError("NetBox URL must be a credential-free HTTPS origin") + if auth_scheme not in ("Bearer", "Token"): + raise ValueError("unsupported authorization scheme") + self.authorization = auth_scheme + " " + token.strip() + self.opener = urllib.request.build_opener(NoRedirect()) + + def get(self, url): + parsed = urllib.parse.urlsplit(url) + base = urllib.parse.urlsplit(self.base) + if parsed.scheme != base.scheme or parsed.netloc != base.netloc or not parsed.path.startswith("/api/") or parsed.fragment or parsed.username or parsed.password: + raise ValueError("refusing off-origin or non-API pagination link") + request = urllib.request.Request(url, headers={"Authorization": self.authorization, "Accept": "application/json"}, method="GET") + for attempt in range(3): + try: + with self.opener.open(request, timeout=30) as response: + return json.load(response) + except urllib.error.HTTPError as error: + if error.code not in (429, 500, 502, 503, 504) or attempt == 2: + raise ValueError("NetBox GET failed with HTTP " + str(error.code)) from None + except (urllib.error.URLError, TimeoutError): + if attempt == 2: + raise ValueError("NetBox GET failed: network unavailable") from None + time.sleep(2 ** attempt) + + def collection(self, path): + url = self.base + "/api/" + path.strip("/") + "/?limit=200" + seen_urls, records, count = set(), {}, None + while url: + if url in seen_urls: + raise ValueError("pagination cycle") + seen_urls.add(url) + page = self.get(url) + if not isinstance(page, dict) or not isinstance(page.get("results"), list) or not isinstance(page.get("count"), int): + raise ValueError("invalid paginated collection") + if count is not None and count != page["count"]: + raise ValueError("source count changed during export; restart the snapshot") + count = page["count"] + if count < 0 or (not page["results"] and page.get("next")): + raise ValueError("invalid count or empty nonterminal page") + for record in page["results"]: + identity = reference_id(record) + if not identity or identity in records: + raise ValueError("missing or repeated source ID during pagination") + records[identity] = sanitize(record) + if len(records) > count: + raise ValueError("snapshot exceeds advertised source count") + next_url = page.get("next") + url = urllib.parse.urljoin(url, next_url) if next_url else None + if url and urllib.parse.urlsplit(url).path != "/api/" + path.strip("/") + "/": + raise ValueError("pagination changed collection") + if len(records) != count: + raise ValueError("source count does not match snapshot") + return sorted(records.values(), key=lambda record: reference_id(record)) + + +def snapshot(reader, source): + if not name_ok(source): + raise ValueError("source must be a stable DNS-style instance name") + started = datetime.datetime.now(datetime.timezone.utc).isoformat() + objects, errors, excluded_endpoints = {}, {}, {} + for app in ("dcim", "circuits"): + try: + discovery = reader.get(reader.base + "/api/" + app + "/") + if not isinstance(discovery, dict): + raise ValueError("invalid API discovery") + except ValueError as error: + errors[app + "/"] = str(error) + continue + for collection in sorted(discovery): + if not re.fullmatch(r"[a-z0-9-]+", collection): + raise ValueError("invalid API collection name") + path = app + "/" + collection + if path == "dcim/connected-device": + excluded_endpoints[path] = "parameterized connectivity lookup, not an inventory collection" + continue + try: + objects[path] = reader.collection(path) + except ValueError as error: + errors[path] = str(error) + for path in REQUIRED - objects.keys() - errors.keys(): + errors[path] = "required collection not advertised by this NetBox version" + return {"version": 1, "source": source, "observedAt": started, "completedAt": datetime.datetime.now(datetime.timezone.utc).isoformat(), "objects": objects, "errors": errors, "excludedEndpoints": excluded_endpoints} + + +def local_ref(name): + return {"name": name} + + +class Planner: + def __init__(self, source, mapping, existing=None, previous=None): + self.snapshot = source + self.mapping = mapping + self.source = source.get("source", "") + if source.get("version") != 1 or not name_ok(self.source): + raise ValueError("unsupported snapshot or invalid source identity") + datetime.datetime.fromisoformat(source["observedAt"].replace("Z", "+00:00")) + self.target = mapping.get("target", {}) + self.namespace = self.target.get("namespace", "") + self.revision = mapping.get("revision", "") + self.records, self.report, self.candidates = {}, {}, {} + self.existing = existing + if existing is not None and existing.get("target") != self.target: + raise ValueError("Fleet snapshot target must exactly match the reviewed provider project, namespace and application") + if existing is not None and set(existing.get("collections", [])) != {"Facility", "Rack", "DeviceClaim", "Device", "Cable", "PowerFeed"}: + raise ValueError("Fleet snapshot must attest all six inventory collections, including empty ones") + self.previous = previous + self.digest = digest(source) + self.device_names, self.rack_names, self.feed_names = {}, {}, {} + for collection, records in source.get("objects", {}).items(): + for record in records: + identity = reference_id(record) + key = collection + "/" + identity + if not identity or key in self.records: + raise ValueError("duplicate or absent source identity") + self.records[key] = record + self.report[key] = {"source": key, "classification": "unsupported", "reason": "source object class has no physical adapter", "targets": []} + + def rows(self, collection): + return [(key, record) for key, record in sorted(self.records.items()) if key.rsplit("/", 1)[0] == collection] + + def mark(self, key, classification, reason, targets=()): + self.report[key] = {"source": key, "classification": classification, "reason": reason, "targets": list(targets)} + + def stable_name(self, kind, identity): + return "nb-" + hashlib.sha256((self.source + "/" + kind + "/" + identity).encode()).hexdigest()[:24] + + def external(self, key): + collection, identity = key.rsplit("/", 1) + return {"system": self.source, "type": collection, "id": identity} + + def add(self, key, kind, name, spec): + if not name_ok(name): + raise ValueError("invalid mapped Fleet name") + provenance = {"method": "NetBoxImport", "recordedBy": "netbox-inventory-offline", "recordedAt": self.snapshot["observedAt"], "source": dict(self.external(key), snapshotDigest=self.digest, mappingRevision=self.revision or "unreviewed", observedAt=self.snapshot["observedAt"])} + record = {"apiVersion": "fleet.datumapis.com/v1alpha1", "kind": kind, "metadata": {"name": name, "namespace": self.namespace}, "spec": dict(spec, provenance=provenance)} + target = kind + "/" + name + if target in self.candidates: + raise ValueError("multiple source records mapped to the same target") + self.candidates[target] = record + self.mark(key, "imported", "observational candidate; not applied or verified", [*self.report[key]["targets"], target]) + return target + + def facilities(self): + for key, record in self.rows("dcim/sites") + self.rows("dcim/locations"): + self.mark(key, "unresolved", "provider/metro sites and locations require an explicit premises mapping") + for facility in self.mapping.get("facilities", []): + key = facility["source"] + if key not in self.records or key.rsplit("/", 1)[0] not in ("dcim/sites", "dcim/locations"): + raise ValueError("facility source must name a present site or location") + spec = {"displayName": facility["displayName"]} + if facility.get("locationRef"): + spec["locationRef"] = local_ref(facility["locationRef"]) + self.add(key, "Facility", facility["name"], spec) + for key, record in self.rows("dcim/racks"): + selected = self.mapping.get("racks", {}).get(reference_id(record)) + if not selected or "Facility/" + selected.get("facility", "") not in self.candidates: + self.mark(key, "unresolved", "rack needs a mapped physical facility") + continue + name = self.stable_name("rack", reference_id(record)) + spec = {"displayName": record.get("name", name), "facilityRef": local_ref(selected["facility"])} + if isinstance(record.get("u_height"), int) and 1 <= record["u_height"] <= 100: + spec["heightUnits"] = record["u_height"] + self.add(key, "Rack", name, spec) + self.rack_names[reference_id(record)] = name + + def devices(self): + for key, record in self.rows("dcim/devices"): + identity = reference_id(record) + selected = self.mapping.get("devices", {}).get(identity, {}) + role = record.get("role") or {} + dtype = record.get("device_type") or {} + model = self.records.get("dcim/device-types/" + reference_id(dtype), dtype) + manufacturer = model.get("manufacturer") or {} + hints = canonical([role, manufacturer, model.get("model", "")]).lower() + if "netactuate" in hints or "hosted-vm" in hints: + self.mark(key, "excluded", "NetActuate/hosted VM represented in DCIM; not a physical asset") + continue + if selected.get("classification") == "excluded" and selected.get("reason"): + self.mark(key, "excluded", selected["reason"]) + continue + if selected.get("classification") != "physical" or not selected.get("serialMeaning") in ("chassis", "providerHostID", "unknown"): + self.mark(key, "unresolved", "review physical classification and serial meaning for this device") + continue + placement = selected.get("placement", {}) + rack_id = reference_id(record.get("rack")) + if placement.get("scope") == "RackMembership" and rack_id in self.rack_names: + placement = {"scope": "RackMembership", "rackRef": local_ref(self.rack_names[rack_id])} + elif placement.get("scope") == "Facility" and "Facility/" + placement.get("facility", "") in self.candidates: + placement = {"scope": "Facility", "facilityRef": local_ref(placement["facility"])} + else: + self.mark(key, "unresolved", "import accepts reviewed facility or known-rack/unknown-position placement only") + continue + if not model.get("model"): + self.mark(key, "unresolved", "device model is absent") + continue + name = self.stable_name("device", identity) + claim_name = self.stable_name("installation", identity) + asset_identity = {"model": model["model"], "sourceIdentity": self.external(key)} + if manufacturer.get("name"): + asset_identity["manufacturer"] = manufacturer["name"] + serial = record.get("serial") + if serial and ("servers.com" in hints or "serversdotcom" in hints) and selected["serialMeaning"] == "chassis": + self.mark(key, "unresolved", "servers.com loader serial is a provider host ID, not a chassis serial") + continue + if serial and selected["serialMeaning"] == "chassis": + asset_identity["serial"] = serial + spec = {"displayName": record.get("name") or name, "claimRef": local_ref(claim_name), "identity": asset_identity, "topologyAuthority": "Cable"} + shape = {} + try: + height = float(model.get("u_height", "")) + if 0 <= height <= 100: + shape["heightUnits"] = height + except (ValueError, TypeError): + pass + if isinstance(model.get("is_full_depth"), bool): + shape["fullDepth"] = model["is_full_depth"] + if shape: + spec["modelShape"] = shape + if serial and selected["serialMeaning"] == "providerHostID": + if not selected.get("provider"): + self.mark(key, "unresolved", "provider host ID requires its provider authority") + continue + spec["providerHostRef"] = {"system": selected["provider"], "type": "host", "id": serial} + if record.get("asset_tag"): + spec["assetTag"] = record["asset_tag"] + self.add(key, "DeviceClaim", claim_name, {"displayName": record.get("name") or name, "lifecycle": "Installation", "expectedIdentity": {name: item for name, item in asset_identity.items() if name != "sourceIdentity"}, "placement": placement}) + self.add(key, "Device", name, spec) + self.device_names[identity] = name + + def components(self): + for collection, kind in COMPONENTS.items(): + for key, record in self.rows("dcim/" + collection): + device_id = reference_id(record.get("device")) + if device_id not in self.device_names: + parent = self.report.get("dcim/devices/" + device_id, {}) + state = "excluded" if parent.get("classification") == "excluded" else "unresolved" + self.mark(key, state, "parent device is excluded or unresolved") + continue + if collection == "interfaces" and value(record, "type") in ("virtual", "lag", "bridge"): + self.mark(key, "excluded", "logical interface belongs to networking, not physical inventory") + continue + target = "Device/" + self.device_names[device_id] + component = {"id": collection + "-" + reference_id(record), "name": record.get("name") or record.get("display") or reference_id(record), "type": kind, "sourceRef": self.external(key)} + connector = value(record, "type") + if connector: + component["connector"] = connector + positions = record.get("positions") + if isinstance(positions, int) and 1 <= positions <= 256: + component["positions"] = positions + for source_field, target_field in (("serial", "serial"), ("asset_tag", "assetTag")): + if record.get(source_field): + component[target_field] = record[source_field] + self.candidates[target]["spec"].setdefault("components", []).append(component) + self.mark(key, "imported", "typed component on the parent asset", [target]) + for collection, parent_field, parent_collection in (("front-ports", "rear_port", "rear-ports"), ("power-outlets", "power_port", "power-ports")): + for key, record in self.rows("dcim/" + collection): + if self.report[key]["classification"] != "imported": + continue + parent_id = reference_id(record.get(parent_field)) + if not parent_id: + self.report[key]["reason"] += "; internal dependency Unknown" + continue + target = self.report[key]["targets"][0] + parent_key = "dcim/" + parent_collection + "/" + parent_id + if self.report.get(parent_key, {}).get("targets") != [target]: + self.mark(key, "unresolved", "internal dependency has a missing or different parent device", [target]) + continue + mapping = {"from": {"componentID": collection + "-" + reference_id(record), "position": 1}, "to": {"componentID": parent_collection + "-" + parent_id, "position": record.get("rear_port_position") or 1}} + self.candidates[target]["spec"].setdefault("internalMappings", []).append(mapping) + + def feeds(self): + for key, record in self.rows("dcim/power-panels"): + self.mark(key, "unresolved", "panel is external electrical dependency evidence, not a fabricated asset") + for key, record in self.rows("dcim/power-feeds"): + selected = self.mapping.get("feeds", {}).get(reference_id(record), {}) + if "Facility/" + selected.get("facility", "") not in self.candidates: + self.mark(key, "unresolved", "feed requires an explicit facility mapping") + continue + name = self.stable_name("feed", reference_id(record)) + spec = {"displayName": record.get("name", name), "facilityRef": local_ref(selected["facility"]), "terminations": [{"id": "output", "name": "output", "type": "PowerOutlet"}]} + rack = self.rack_names.get(reference_id(record.get("rack"))) + if rack: + spec["rackRef"] = local_ref(rack) + supply = {"type": str(value(record, "supply", "Unknown")).upper()} + if supply["type"] not in ("AC", "DC"): + supply["type"] = "Unknown" + for field, target_field in (("voltage", "voltageV"), ("amperage", "currentA")): + if isinstance(record.get(field), int) and 0 < record[field] <= 100000: + supply[target_field] = record[field] + if value(record, "phase") in ("single-phase", "three-phase"): + supply["phase"] = value(record, "phase") + spec["supply"] = supply + panel_key = "dcim/power-panels/" + reference_id(record.get("power_panel")) + if panel_key in self.records: + spec["upstreamSources"] = [self.external(panel_key)] + self.mark(panel_key, "imported", "external electrical panel reference only; upstream independence Unknown", sorted(set(self.report[panel_key]["targets"] + ["PowerFeed/" + name]))) + self.add(key, "PowerFeed", name, spec) + self.feed_names[reference_id(record)] = name + + def endpoint(self, termination): + kind = termination.get("object_type") or termination.get("termination_type") + identity = reference_id(termination.get("object_id") or termination.get("termination_id") or termination.get("object") or termination.get("termination")) + if kind == "dcim.powerfeed" and identity in self.feed_names: + return {"powerFeedRef": local_ref(self.feed_names[identity]), "componentID": "output", "position": 1} + collection = next((name for name in COMPONENTS if "dcim." + name.replace("-", "").rstrip("s") == kind), None) + if kind == "dcim.inventoryitem": + collection = "inventory-items" + key = "dcim/" + str(collection) + "/" + identity + if kind == "circuits.circuittermination": + selected = self.mapping.get("demarcations", {}).get(identity) + if not selected: + return None + key = selected.get("componentSource", "") + state = self.report.get(key, {}) + if state.get("classification") != "imported" or not state.get("targets"): + return None + target = state["targets"][0] + if not target.startswith("Device/"): + return None + source_class, source_id = key.rsplit("/", 1) + return {"deviceRef": local_ref(target.split("/", 1)[1]), "componentID": source_class.split("/")[1] + "-" + source_id, "position": 1} + + def circuits(self): + for key, record in self.rows("circuits/circuits"): + self.mark(key, "unresolved", "circuit requires an external service-owner reference; no Fleet Circuit kind") + for key, record in self.rows("circuits/circuit-terminations"): + circuit_key = "circuits/circuits/" + reference_id(record.get("circuit")) + owner = self.mapping.get("circuits", {}).get(reference_id(record.get("circuit"))) + endpoint = self.endpoint({"object_type": "circuits.circuittermination", "object_id": reference_id(record)}) + if not owner or not all(owner.get(field) for field in ("system", "type", "id")) or not endpoint or circuit_key not in self.records: + self.mark(key, "unresolved", "local demarcation and external service owner must both be mapped") + continue + target = "Device/" + endpoint["deviceRef"]["name"] + self.candidates[target]["spec"].setdefault("serviceAssociations", []).append({"serviceRef": {field: owner[field] for field in ("system", "type", "id")}, "componentID": endpoint["componentID"]}) + self.mark(key, "imported", "local physical demarcation association only", [target]) + self.mark(circuit_key, "imported", "external service-owner reference only; no service or IPAM migration", sorted(set(self.report[circuit_key]["targets"] + [target]))) + + def cables(self): + for key, record in self.rows("dcim/cables"): + ends = [record.get("a_terminations", []), record.get("b_terminations", [])] + selected = self.mapping.get("cables", {}).get(reference_id(record), {}) + lanes = selected.get("lanes") + available = [[self.endpoint(termination) for termination in end] for end in ends] + if not all(available) or any(endpoint is None for side in available for endpoint in side): + self.mark(key, "unresolved", "cable endpoint is missing, excluded, or has no reviewed demarcation") + continue + if lanes: + lanes = copy.deepcopy(lanes) + represented = [set(), set()] + valid = isinstance(lanes, list) and len(lanes) <= 64 + for lane in lanes if valid else []: + if not isinstance(lane, dict) or not name_ok(lane.get("id")): + valid = False + break + for index, side in enumerate(("a", "b")): + endpoint = lane.get(side) + if not isinstance(endpoint, dict) or not isinstance(endpoint.get("position"), int) or endpoint["position"] < 1: + valid = False + break + base_endpoint = dict(endpoint, position=1) + if base_endpoint not in available[index]: + valid = False + break + represented[index].add(canonical(base_endpoint)) + if not valid or any(represented[index] != {canonical(endpoint) for endpoint in available[index]} for index in (0, 1)): + self.mark(key, "unresolved", "reviewed lanes must account for every source termination on its original side") + continue + else: + if any(len(end) != 1 for end in ends): + self.mark(key, "unsupported", "multi-termination cable needs reviewed explicit lane mappings; no all-to-all inference") + continue + endpoints = [end[0] for end in available] + multiposition = False + for endpoint in endpoints: + if endpoint.get("deviceRef"): + device = self.candidates["Device/" + endpoint["deviceRef"]["name"]] + component = next(component for component in device["spec"]["components"] if component["id"] == endpoint["componentID"]) + multiposition |= component.get("positions", 1) > 1 + if multiposition: + self.mark(key, "unresolved", "multi-position termination needs explicit lanes; never infer position one for a trunk") + continue + lanes = [{"id": "lane-1", "a": endpoints[0], "b": endpoints[1]}] + medium = selected.get("medium") + if medium not in ("Copper", "Fiber", "Power", "Console"): + self.mark(key, "unresolved", "cable medium requires review; source connector codes are not qualification") + continue + name = self.stable_name("cable", reference_id(record)) + self.add(key, "Cable", name, {"displayName": record.get("label") or name, "medium": medium, "lanes": lanes}) + + def reconcile(self): + current = {} + for record in (self.existing or {}).get("items", []): + if record.get("apiVersion") != "fleet.datumapis.com/v1alpha1" or record.get("metadata", {}).get("namespace") != self.namespace: + raise ValueError("Fleet snapshot must contain only this namespace's physical inventory") + key = record["kind"] + "/" + record["metadata"]["name"] + if key in current: + raise ValueError("duplicate Fleet target identity") + current[key] = record + conflicts, unchanged = {}, set() + for key, candidate in self.candidates.items(): + if key in current: + old_spec, new_spec = copy.deepcopy(current[key]["spec"]), copy.deepcopy(candidate["spec"]) + old_provenance, new_provenance = old_spec.pop("provenance"), new_spec.pop("provenance") + source_fields = ("system", "type", "id") + same_source = all(old_provenance.get("source", {}).get(field) == new_provenance["source"][field] for field in source_fields) + if same_source and old_spec == new_spec: + unchanged.add(key) + else: + conflicts[key] = "existing target differs; no automatic update, claim rebinding, or ownership takeover" + if candidate["kind"] == "Device": + spec = candidate["spec"] + for other_key, other in {**current, **self.candidates}.items(): + if other_key == key or other.get("kind") != "Device": + continue + other_spec = other["spec"] + pairs = [(spec.get("assetTag"), other_spec.get("assetTag")), (spec.get("providerHostRef"), other_spec.get("providerHostRef")), (spec.get("providerHostRef", {}).get("id"), other_spec["identity"].get("serial")), (spec["identity"].get("serial"), other_spec["identity"].get("serial")), (spec["identity"].get("sourceIdentity"), other_spec["identity"].get("sourceIdentity"))] + if any(left and left == right for left, right in pairs): + conflicts[key] = "possible existing asset identity; preserve Device/claim/capacity and adjudicate privately" + all_records = {**current, **self.candidates} + for key, reasons in validate_graph(all_records).items(): + if key in self.candidates: + conflicts[key] = "; ".join(reasons) + changed = True + while changed: + changed = False + for entry in self.report.values(): + if entry["classification"] == "unresolved": + for target in entry["targets"]: + if target not in conflicts: + conflicts[target] = "one or more source relationships are unresolved" + changed = True + if any(target in conflicts for target in entry["targets"]): + for target in entry["targets"]: + if target not in conflicts: + conflicts[target] = "same source record has a quarantined dependency" + changed = True + for key, record in self.candidates.items(): + if key not in conflicts and any(target in conflicts for target in dependencies(record)): + conflicts[key] = "referenced candidate is quarantined" + changed = True + for entry in self.report.values(): + failed = [target for target in entry["targets"] if target in conflicts] + if failed: + entry.update(classification="unresolved", reason=conflicts[failed[0]]) + elif entry["targets"] and all(target in unchanged for target in entry["targets"]): + entry["reason"] = "already present with same source identity and physical fields; no write" + self.candidates = {key: record for key, record in self.candidates.items() if key not in conflicts and key not in unchanged} + return conflicts + + def run(self): + self.facilities() + self.devices() + self.components() + self.feeds() + self.circuits() + self.cables() + for key in self.records: + collection = key.rsplit("/", 1)[0] + if collection.startswith("dcim/") and collection.split("/")[1] in SUPPORT: + self.mark(key, "excluded", "model/catalog metadata consumed where referenced; no independent physical asset") + elif collection.endswith("-templates"): + self.mark(key, "excluded", "model template is not installed hardware; actual instances imported separately") + elif collection in ("dcim/regions", "dcim/site-groups", "dcim/rack-roles", "dcim/virtual-chassis", "circuits/providers", "circuits/provider-accounts", "circuits/provider-networks", "circuits/circuit-types"): + self.mark(key, "excluded", "grouping or service-owner metadata; not physical premises or installed assets") + conflicts = self.reconcile() + omitted = sorted(set((self.previous or {}).get("objects", {})) - set(self.snapshot.get("objects", {}))) + prior_keys = {collection + "/" + reference_id(record) for collection, rows in (self.previous or {}).get("objects", {}).items() for record in rows} + if self.previous and self.previous.get("source") != self.source: + raise ValueError("previous snapshot belongs to another source") + errors = dict(self.snapshot.get("errors", {})) + for collection in REQUIRED - self.snapshot.get("objects", {}).keys(): + errors.setdefault(collection, "required collection absent; coverage unknown") + retained = [] + for record in (self.existing or {}).get("items", []): + source = record.get("spec", {}).get("provenance", {}).get("source", {}) + if source.get("system") == self.source and source.get("type", "") + "/" + source.get("id", "") not in self.records: + retained.append(record["kind"] + "/" + record["metadata"]["name"]) + return {"version": 1, "source": self.source, "snapshotDigest": self.digest, "observedAt": self.snapshot["observedAt"], "target": self.target, "mappingRevision": self.revision, "coverageComplete": not errors, "collectionErrors": errors, "excludedEndpoints": self.snapshot.get("excludedEndpoints", {}), "omittedCollections": omitted, "missingSincePrevious": sorted(prior_keys - self.records.keys()), "retainedMissingSource": retained, "deletions": [], "conflicts": conflicts, "records": list(self.report.values()), "candidateCount": len(self.candidates), "readiness": "Unknown", "applied": False}, list(self.candidates.values()) + + +def dependencies(record): + spec = record["spec"] + references = [] + for field, kind in (("claimRef", "DeviceClaim"), ("facilityRef", "Facility"), ("rackRef", "Rack")): + if spec.get(field): + references.append(kind + "/" + spec[field]["name"]) + if spec.get("placement", {}).get(field): + references.append(kind + "/" + spec["placement"][field]["name"]) + for lane in spec.get("lanes", []): + for endpoint in (lane["a"], lane["b"]): + for field, kind in (("deviceRef", "Device"), ("powerFeedRef", "PowerFeed")): + if endpoint.get(field): + references.append(kind + "/" + endpoint[field]["name"]) + return references + + +def validate_graph(records): + errors, occupied = {}, {} + def fail(key, reason): + errors.setdefault(key, []).append(reason) + for key, record in records.items(): + for target in dependencies(record): + if target not in records: + fail(key, "missing local reference " + target) + spec = record["spec"] + components = {component["id"]: component for component in spec.get("components", [])} + mapped_positions = set() + for mapping in spec.get("internalMappings", []): + for end in (mapping["from"], mapping["to"]): + component = components.get(end["componentID"]) + if not component or not 1 <= end["position"] <= component.get("positions", 1): + fail(key, "invalid internal component mapping") + source_type = components.get(mapping["from"]["componentID"], {}).get("type") + target_type = components.get(mapping["to"]["componentID"], {}).get("type") + if (source_type, target_type) not in (("FrontPort", "RearPort"), ("PowerOutlet", "PowerInlet")): + fail(key, "incompatible internal component types") + if source_type == "FrontPort": + position = canonical(mapping["to"]) + if position in mapped_positions: + fail(key, "pass-through rear position mapped more than once") + mapped_positions.add(position) + for association in spec.get("serviceAssociations", []): + if association["componentID"] not in components: + fail(key, "service demarcation names a missing component") + for lane in spec.get("lanes", []): + kinds = [] + for endpoint in (lane["a"], lane["b"]): + owner = ("Device/" + endpoint["deviceRef"]["name"]) if endpoint.get("deviceRef") else ("PowerFeed/" + endpoint["powerFeedRef"]["name"]) + target = records.get(owner, {}).get("spec", {}) + components = target.get("components", []) + target.get("terminations", []) + component = next((component for component in components if component["id"] == endpoint["componentID"]), None) + if not component or not 1 <= endpoint["position"] <= component.get("positions", 1): + fail(key, "unresolved endpoint component or position") + continue + kinds.append(component["type"]) + connector = component.get("connector", "").lower() + if spec.get("medium") == "Fiber" and ("base-t" in connector or "rj45" in connector): + fail(key, "fiber cable on a copper termination") + identity = owner + "/" + endpoint["componentID"] + "/" + str(endpoint["position"]) + if identity in occupied: + fail(key, "termination already used") + fail(occupied[identity], "termination already used") + occupied[identity] = key + allowed = {"Power": {"PowerInlet", "PowerOutlet"}, "Console": {"ConsolePort", "ConsoleServerPort", "FrontPort", "RearPort"}, "Copper": {"NetworkPort", "FrontPort", "RearPort"}, "Fiber": {"NetworkPort", "FrontPort", "RearPort"}} + if spec.get("medium") not in allowed or not set(kinds) <= allowed[spec["medium"]]: + fail(key, "incompatible or unknown cable medium and component types") + if spec.get("medium") == "Power" and sorted(kinds) != ["PowerInlet", "PowerOutlet"]: + fail(key, "power cable must connect an outlet to an inlet") + if spec.get("medium") == "Console" and all(kind in ("ConsolePort", "ConsoleServerPort") for kind in kinds) and sorted(kinds) != ["ConsolePort", "ConsoleServerPort"]: + fail(key, "unsupported console direction; adapter mapping required") + return errors + + +def read_json(path): + with open(path) as stream: + return json.load(stream) + + +def write_private(path, content): + descriptor = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) + with os.fdopen(descriptor, "w") as stream: + json.dump(content, stream, sort_keys=True, indent=2) + stream.write("\n") + + +def private_output(path): + resolved = path.resolve() + if any((parent / ".git").exists() for parent in (resolved, *resolved.parents)): + raise ValueError("private snapshots and handoffs must be written outside Git checkouts") + path.mkdir(mode=0o700, parents=False, exist_ok=False) + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + subparsers = parser.add_subparsers(dest="command", required=True) + export = subparsers.add_parser("snapshot") + export.add_argument("--url", default=os.environ.get("NETBOX_URL", "https://netbox.datum-infra.net")) + export.add_argument("--source", required=True) + export.add_argument("--auth-scheme", choices=("Bearer", "Token"), default="Bearer") + export.add_argument("--output", required=True) + plan = subparsers.add_parser("plan") + plan.add_argument("--snapshot", required=True) + plan.add_argument("--mapping") + plan.add_argument("--existing") + plan.add_argument("--previous") + plan.add_argument("--output", required=True) + plan.add_argument("--handoff", action="store_true") + plan.add_argument("--allow-partial", action="store_true") + args = parser.parse_args(argv) + output = Path(args.output) + private_output(output) + if args.command == "snapshot": + token = os.environ.get("NETBOX_TOKEN") + if not token: + token_path = Path(os.environ.get("NETBOX_TOKEN_FILE", "~/.config/netbox/token")).expanduser() + if not token_path.is_file(): + raise ValueError("no authorized NetBox read credential in the documented environment/file paths") + token = token_path.read_text().strip() + result = snapshot(Reader(args.url, token, args.auth_scheme), args.source) + write_private(output / "snapshot.json", result) + print("Private snapshot saved; collection errors:", len(result["errors"])) + return 2 if result["errors"] else 0 + mapping = read_json(args.mapping) if args.mapping else {} + planner = Planner(read_json(args.snapshot), mapping, read_json(args.existing) if args.existing else None, read_json(args.previous) if args.previous else None) + report, candidates = planner.run() + write_private(output / "report.json", report) + if args.handoff: + target = mapping.get("target", {}) + if not args.existing or not mapping.get("revision") or not name_ok(target.get("project")) or not name_ok(target.get("namespace")) or target.get("writer") != "Flux" or target.get("application") != "provider-inventory": + raise ValueError("handoff requires an explicit provider project/namespace, reviewed mapping revision, Flux/provider-inventory target, and current Fleet snapshot") + if report["collectionErrors"] or report["conflicts"]: + raise ValueError("handoff blocked by incomplete source coverage or reconciliation conflicts; inspect the private report") + if not args.allow_partial and any(row["classification"] in ("unresolved", "unsupported") for row in report["records"]): + raise ValueError("handoff has unresolved or unsupported records; review the report and explicitly choose --allow-partial for a partial cohort") + write_private(output / "candidates.json", {"apiVersion": "v1", "kind": "List", "items": candidates}) + write_private(output / "handoff.json", {"target": target, "snapshotDigest": report["snapshotDigest"], "mappingDigest": digest(mapping), "existingDigest": digest(planner.existing), "candidateDigest": digest(candidates), "application": "review and add individual new records to the private Flux provider-inventory source; never replace or prune that source", "applied": False}) + print("Private report saved; observational candidates:", len(candidates), "(nothing applied)") + counts = {state: sum(row["classification"] == state for row in report["records"]) for state in ("imported", "unresolved", "unsupported", "excluded")} + print("Record classifications:", canonical(counts), "; collection errors:", len(report["collectionErrors"]), "; readiness: Unknown") + return 0 + + +if __name__ == "__main__": + try: + sys.exit(main()) + except (ValueError, OSError, KeyError, TypeError) as error: + print("Inventory import stopped:", str(error) if isinstance(error, ValueError) else type(error).__name__, file=sys.stderr) + sys.exit(2) diff --git a/hack/test_netbox_inventory.py b/hack/test_netbox_inventory.py new file mode 100644 index 00000000..6be9732f --- /dev/null +++ b/hack/test_netbox_inventory.py @@ -0,0 +1,292 @@ +import copy +import io +import json +import os +from pathlib import Path +import tempfile +import unittest +from unittest.mock import patch +import urllib.error + +import netbox_inventory as inventory + + +def fixture(): + objects = {collection: [] for collection in inventory.REQUIRED} + objects.update({ + "dcim/sites": [{"id": 1, "name": "Example metro grouping"}], + "dcim/locations": [{"id": 1, "name": "Example room"}], + "dcim/racks": [{"id": 1, "name": "Example rack", "u_height": 42}], + "dcim/manufacturers": [{"id": 1, "name": "Example"}], + "dcim/device-types": [{"id": 1, "model": "Example physical model", "manufacturer": {"id": 1, "name": "Example"}}], + "dcim/devices": [ + {"id": 1, "name": "Example server", "serial": "provider-001", "asset_tag": "asset-001", "device_type": {"id": 1}, "rack": {"id": 1}, "position": 1}, + {"id": 2, "name": "Example PDU", "device_type": {"id": 1}, "rack": {"id": 1}}, + {"id": 3, "name": "Example panel", "device_type": {"id": 1}}, + {"id": 4, "name": "Example VM", "device_type": {"model": "netactuate VM"}}, + ], + "dcim/interfaces": [{"id": 1, "name": "eth0", "device": {"id": 1}, "type": "1000base-t"}, {"id": 2, "name": "bond0", "device": {"id": 1}, "type": "lag"}], + "dcim/power-ports": [{"id": 1, "name": "PSU1", "device": {"id": 1}}, {"id": 2, "name": "inlet", "device": {"id": 2}}], + "dcim/power-outlets": [{"id": 1, "name": "outlet-1", "device": {"id": 2}, "power_port": {"id": 2}}], + "dcim/front-ports": [{"id": 1, "name": "front-1", "device": {"id": 3}, "rear_port": {"id": 1}, "rear_port_position": 1}], + "dcim/rear-ports": [{"id": 1, "name": "rear-1", "device": {"id": 3}, "positions": 2}], + "dcim/power-panels": [{"id": 1, "name": "Panel A"}], + "dcim/power-feeds": [{"id": 1, "name": "Feed A", "power_panel": {"id": 1}, "rack": {"id": 1}, "supply": "ac", "voltage": 208, "amperage": 30}], + "dcim/cables": [{"id": 1, "label": "Power 1", "a_terminations": [{"object_type": "dcim.poweroutlet", "object_id": 1}], "b_terminations": [{"object_type": "dcim.powerport", "object_id": 1}]}], + "circuits/circuits": [{"id": 1, "cid": "Example-service"}], + "circuits/circuit-terminations": [{"id": 1, "circuit": {"id": 1}}], + }) + source = {"version": 1, "source": "example-netbox", "observedAt": "2026-11-20T12:00:00Z", "objects": objects, "errors": {}} + mapping = { + "revision": "example-reviewed-1", + "target": {"project": "example-provider", "namespace": "inventory", "writer": "Flux", "application": "provider-inventory"}, + "facilities": [{"source": "dcim/sites/1", "name": "example-premises", "displayName": "Example premises"}], + "racks": {"1": {"facility": "example-premises"}}, + "devices": { + "1": {"classification": "physical", "serialMeaning": "providerHostID", "provider": "example-provider", "placement": {"scope": "RackMembership"}}, + "2": {"classification": "physical", "serialMeaning": "unknown", "placement": {"scope": "RackMembership"}}, + "3": {"classification": "physical", "serialMeaning": "unknown", "placement": {"scope": "Facility", "facility": "example-premises"}}, + }, + "feeds": {"1": {"facility": "example-premises"}}, + "cables": {"1": {"medium": "Power"}}, + "circuits": {"1": {"system": "example-service-owner", "type": "transport", "id": "Example-service"}}, + "demarcations": {"1": {"componentSource": "dcim/rear-ports/1"}}, + } + return source, mapping + + +class PlanTests(unittest.TestCase): + def setUp(self): + self.source, self.mapping = fixture() + + def plan(self, existing=None, previous=None): + if existing is not None: + existing = dict(existing, target=self.mapping["target"], collections=["Facility", "Rack", "DeviceClaim", "Device", "Cable", "PowerFeed"]) + return inventory.Planner(self.source, self.mapping, existing, previous).run() + + def test_physical_shapes_and_no_hardware_authority(self): + report, records = self.plan() + self.assertTrue(report["coverageComplete"]) + self.assertEqual({}, report["conflicts"]) + self.assertEqual({"Facility", "Rack", "DeviceClaim", "Device", "Cable", "PowerFeed"}, {record["kind"] for record in records}) + self.assertEqual(sum(len(rows) for rows in self.source["objects"].values()), len(report["records"])) + server = next(record for record in records if record["kind"] == "Device" and record["spec"].get("assetTag")) + self.assertNotIn("serial", server["spec"]["identity"]) + self.assertEqual("provider-001", server["spec"]["providerHostRef"]["id"]) + self.assertEqual("asset-001", server["spec"]["assetTag"]) + for record in records: + self.assertNotIn("status", record) + self.assertNotIn("bmc", record["spec"]) + if record["kind"] == "DeviceClaim": + self.assertNotIn("position", record["spec"]["placement"]) + self.assertNotIn("height", record["spec"]["placement"]) + states = {row["source"]: row["classification"] for row in report["records"]} + self.assertEqual("excluded", states["dcim/devices/4"]) + self.assertEqual("excluded", states["dcim/interfaces/2"]) + self.assertEqual("imported", states["circuits/circuit-terminations/1"]) + + def test_checked_in_synthetic_handoff_matches_planner(self): + _, records = self.plan() + fixture_path = Path(__file__).parent / "testdata/netbox/candidates.json" + self.assertEqual(inventory.read_json(fixture_path)["items"], records) + + def test_existing_snapshot_wrong_project_and_missing_collections(self): + with self.assertRaisesRegex(ValueError, "target"): + inventory.Planner(self.source, self.mapping, {"items": [], "target": {"project": "other"}}) + with self.assertRaisesRegex(ValueError, "six"): + inventory.Planner(self.source, self.mapping, {"items": [], "target": self.mapping["target"]}) + + def test_repeated_and_interrupted_run(self): + report, records = self.plan() + self.assertEqual((report, records), self.plan()) + second, remaining = self.plan({"items": records}) + self.assertEqual({}, second["conflicts"]) + self.assertEqual([], remaining) + partial, remaining = self.plan({"items": records[:2]}) + self.assertEqual({}, partial["conflicts"]) + self.assertEqual(len(records) - 2, len(remaining)) + + def test_existing_identity_is_never_recreated(self): + _, records = self.plan() + server = copy.deepcopy(next(record for record in records if record["kind"] == "Device" and record["spec"].get("assetTag"))) + server["metadata"]["name"] = "original-asset" + server["spec"]["identity"] = {"model": "Legacy", "serial": "provider-001"} + server["spec"].pop("assetTag") + server["spec"].pop("providerHostRef") + report, candidates = self.plan({"items": [server]}) + self.assertTrue(report["conflicts"]) + self.assertFalse(any(record["kind"] == "Device" and record["spec"].get("providerHostRef") for record in candidates)) + self.assertEqual("original-asset", server["metadata"]["name"]) + + def test_changed_source_and_different_writer_are_conflicts(self): + _, records = self.plan() + records[0]["spec"]["displayName"] = "Manual correction" + report, _ = self.plan({"items": records}) + self.assertTrue(report["conflicts"]) + _, records = self.plan() + records[0]["spec"]["provenance"]["source"]["system"] = "other-source" + report, _ = self.plan({"items": records}) + self.assertTrue(report["conflicts"]) + + def test_omission_preserves_records_and_does_not_prune(self): + previous = copy.deepcopy(self.source) + self.source["objects"]["dcim/devices"] = self.source["objects"]["dcim/devices"][1:] + report, _ = self.plan(previous=previous) + self.assertIn("dcim/devices/1", report["missingSincePrevious"]) + self.assertEqual([], report["deletions"]) + + def test_unknown_collections_and_missing_collections_are_visible(self): + self.source["objects"]["dcim/new-physical-kind"] = [{"id": 1}] + del self.source["objects"]["dcim/console-ports"] + report, _ = self.plan() + self.assertFalse(report["coverageComplete"]) + self.assertEqual("unsupported", next(row for row in report["records"] if row["source"] == "dcim/new-physical-kind/1")["classification"]) + + def test_duplicate_identity_and_target_mapping_rejected(self): + self.source["objects"]["dcim/sites"].append({"id": 1}) + with self.assertRaises(ValueError): + self.plan() + self.source, self.mapping = fixture() + self.mapping["facilities"].append(copy.deepcopy(self.mapping["facilities"][0])) + with self.assertRaises(ValueError): + self.plan() + + def test_site_can_map_to_several_premises(self): + self.mapping["facilities"].append({"source": "dcim/sites/1", "name": "another-premises", "displayName": "Other premises"}) + _, records = self.plan() + self.assertEqual(2, sum(record["kind"] == "Facility" for record in records)) + + def test_no_mapping_means_no_guessed_assets(self): + self.mapping = {} + report, records = self.plan() + self.assertEqual([], records) + self.assertTrue(any(row["classification"] == "unresolved" for row in report["records"])) + + def test_duplicate_cable_termination_quarantines_both(self): + cable = copy.deepcopy(self.source["objects"]["dcim/cables"][0]) + cable["id"] = 2 + self.source["objects"]["dcim/cables"].append(cable) + self.mapping["cables"]["2"] = {"medium": "Power"} + report, records = self.plan() + self.assertFalse(any(record["kind"] == "Cable" for record in records)) + self.assertTrue(report["conflicts"]) + + def test_breakout_requires_reviewed_lanes_and_every_termination(self): + self.source["objects"]["dcim/interfaces"].append({"id": 3, "name": "eth1", "device": {"id": 1}, "type": "1000base-t"}) + self.source["objects"]["dcim/cables"] = [{"id": 2, "a_terminations": [{"object_type": "dcim.rearport", "object_id": 1}], "b_terminations": [{"object_type": "dcim.interface", "object_id": 1}, {"object_type": "dcim.interface", "object_id": 3}]}] + planner = inventory.Planner(self.source, self.mapping) + panel = planner.stable_name("device", "3") + server = planner.stable_name("device", "1") + self.mapping["cables"]["2"] = {"medium": "Copper"} + report, records = self.plan() + self.assertFalse(any(record["kind"] == "Cable" for record in records)) + lanes = [{"id": "lane-" + str(position), "a": {"deviceRef": {"name": panel}, "componentID": "rear-ports-1", "position": position}, "b": {"deviceRef": {"name": server}, "componentID": "interfaces-" + identity, "position": 1}} for position, identity in ((1, "1"), (2, "3"))] + self.mapping["cables"]["2"]["lanes"] = lanes + report, records = self.plan() + self.assertEqual({}, report["conflicts"]) + self.assertEqual(1, sum(record["kind"] == "Cable" for record in records)) + self.mapping["cables"]["2"]["lanes"] = lanes[:1] + report, records = self.plan() + self.assertFalse(any(record["kind"] == "Cable" for record in records)) + + def test_incompatible_medium_and_missing_internal_mapping(self): + self.mapping["cables"]["1"]["medium"] = "Fiber" + self.source["objects"]["dcim/front-ports"][0]["rear_port_position"] = 3 + report, _ = self.plan() + self.assertGreaterEqual(len(report["conflicts"]), 2) + + def test_redaction_uses_allowlisted_fields(self): + source = {"id": 1, "comments": "SECRET", "custom_fields": {"bmc_password": "SECRET"}, "config_context": {"token": "SECRET"}, "device": {"id": 2, "url": "https://user:SECRET@example.invalid"}} + self.assertNotIn("SECRET", json.dumps(inventory.sanitize(source))) + + def test_output_is_private_and_never_overwritten(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "report.json" + inventory.write_private(path, {"example": True}) + self.assertEqual(0o600, path.stat().st_mode & 0o777) + with self.assertRaises(FileExistsError): + inventory.write_private(path, {}) + + def test_export_refuses_repository_output(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + (root / ".git").write_text("gitdir: example") + with self.assertRaisesRegex(ValueError, "outside Git"): + inventory.private_output(root / "private-export") + self.assertFalse((root / "private-export").exists()) + + def test_handoff_requires_target_existing_and_partial_acknowledgement(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + for name, data in (("source", self.source), ("mapping", self.mapping), ("existing", {"items": [], "target": self.mapping["target"], "collections": ["Facility", "Rack", "DeviceClaim", "Device", "Cable", "PowerFeed"]})): + inventory.write_private(root / (name + ".json"), data) + args = ["plan", "--snapshot", str(root / "source.json"), "--mapping", str(root / "mapping.json"), "--output", str(root / "blocked"), "--handoff"] + with self.assertRaises(ValueError): + inventory.main(args) + self.assertFalse((root / "blocked/candidates.json").exists()) + args[args.index(str(root / "blocked"))] = str(root / "allowed") + args.extend(["--existing", str(root / "existing.json"), "--allow-partial"]) + self.assertEqual(0, inventory.main(args)) + self.assertTrue((root / "allowed/candidates.json").exists()) + with self.assertRaises(FileExistsError): + inventory.main(args) + + +class ReaderTests(unittest.TestCase): + def reader(self): + return inventory.Reader("https://example.invalid", "synthetic-token") + + def test_discovery_reports_lookup_exclusion_and_missing_collections(self): + reader = self.reader() + with patch.object(reader, "get", side_effect=[{"devices": "unused", "connected-device": "unused"}, {}]), patch.object(reader, "collection", return_value=[]) as collection: + result = inventory.snapshot(reader, "example-netbox") + collection.assert_called_once_with("dcim/devices") + self.assertIn("dcim/connected-device", result["excludedEndpoints"]) + self.assertIn("dcim/sites", result["errors"]) + + def test_discovery_permission_error_retains_partial_snapshot(self): + reader = self.reader() + with patch.object(reader, "get", side_effect=[{"devices": "unused"}, ValueError("NetBox GET failed with HTTP 403")]), patch.object(reader, "collection", return_value=[{"id": 1}]): + result = inventory.snapshot(reader, "example-netbox") + self.assertEqual([{"id": 1}], result["objects"]["dcim/devices"]) + self.assertIn("HTTP 403", result["errors"]["circuits/"]) + + def test_pagination_and_duplicates(self): + reader = self.reader() + with patch.object(reader, "get", side_effect=[{"count": 2, "results": [{"id": 1}], "next": "?offset=1"}, {"count": 2, "results": [{"id": 2}], "next": None}]): + self.assertEqual(2, len(reader.collection("dcim/devices"))) + with patch.object(reader, "get", side_effect=[{"count": 2, "results": [{"id": 1}], "next": "?offset=1"}, {"count": 2, "results": [{"id": 1}], "next": None}]): + with self.assertRaisesRegex(ValueError, "repeated"): + reader.collection("dcim/devices") + + def test_partial_pagination_and_cycles_fail_closed(self): + reader = self.reader() + for page in ({"count": 2, "results": [{"id": 1}], "next": None}, {"count": 1, "results": [], "next": "?limit=200"}, {"count": 1, "results": [], "next": "/api/users/"}): + with patch.object(reader, "get", return_value=page), self.assertRaises(ValueError): + reader.collection("dcim/devices") + + def test_cross_origin_and_http_and_credentials_refused(self): + reader = self.reader() + with patch.object(reader.opener, "open") as opener: + for url in ("https://attacker.invalid/api/dcim/devices", "http://example.invalid/api/dcim/devices", "https://user:password@example.invalid/api/dcim/devices"): + with self.assertRaises(ValueError): + reader.get(url) + opener.assert_not_called() + + def test_retries_get_only_and_permission_errors_redacted(self): + reader = self.reader() + forbidden = urllib.error.HTTPError("https://example.invalid", 403, "SECRET", {}, None) + with patch.object(reader.opener, "open", side_effect=forbidden) as opener: + with self.assertRaisesRegex(ValueError, "HTTP 403") as caught: + reader.get("https://example.invalid/api/dcim/") + self.assertNotIn("SECRET", str(caught.exception)) + self.assertEqual("GET", opener.call_args.args[0].method) + self.assertEqual(1, opener.call_count) + unavailable = urllib.error.HTTPError("https://example.invalid", 503, "SECRET", {}, None) + with patch.object(reader.opener, "open", side_effect=[unavailable, io.StringIO('{"ok":true}')]) as opener, patch.object(inventory.time, "sleep"): + self.assertTrue(reader.get("https://example.invalid/api/dcim/")["ok"]) + self.assertEqual(2, opener.call_count) + + +if __name__ == "__main__": + unittest.main() diff --git a/hack/testdata/netbox/candidates.json b/hack/testdata/netbox/candidates.json new file mode 100644 index 00000000..66ecd1ce --- /dev/null +++ b/hack/testdata/netbox/candidates.json @@ -0,0 +1,475 @@ +{ + "apiVersion": "v1", + "items": [ + { + "apiVersion": "fleet.datumapis.com/v1alpha1", + "kind": "Facility", + "metadata": { + "name": "example-premises", + "namespace": "inventory" + }, + "spec": { + "displayName": "Example premises", + "provenance": { + "method": "NetBoxImport", + "recordedAt": "2026-11-20T12:00:00Z", + "recordedBy": "netbox-inventory-offline", + "source": { + "id": "1", + "mappingRevision": "example-reviewed-1", + "observedAt": "2026-11-20T12:00:00Z", + "snapshotDigest": "sha256:faeabf49ee04c9376ce308d9347196e38ec07c6dd92d9bc18ea5fc29878ddb08", + "system": "example-netbox", + "type": "dcim/sites" + } + } + } + }, + { + "apiVersion": "fleet.datumapis.com/v1alpha1", + "kind": "Rack", + "metadata": { + "name": "nb-2f51dc9cdc336da3c50b9a8b", + "namespace": "inventory" + }, + "spec": { + "displayName": "Example rack", + "facilityRef": { + "name": "example-premises" + }, + "heightUnits": 42, + "provenance": { + "method": "NetBoxImport", + "recordedAt": "2026-11-20T12:00:00Z", + "recordedBy": "netbox-inventory-offline", + "source": { + "id": "1", + "mappingRevision": "example-reviewed-1", + "observedAt": "2026-11-20T12:00:00Z", + "snapshotDigest": "sha256:faeabf49ee04c9376ce308d9347196e38ec07c6dd92d9bc18ea5fc29878ddb08", + "system": "example-netbox", + "type": "dcim/racks" + } + } + } + }, + { + "apiVersion": "fleet.datumapis.com/v1alpha1", + "kind": "DeviceClaim", + "metadata": { + "name": "nb-d2728cbb6945a3e726ab702b", + "namespace": "inventory" + }, + "spec": { + "displayName": "Example server", + "expectedIdentity": { + "manufacturer": "Example", + "model": "Example physical model" + }, + "lifecycle": "Installation", + "placement": { + "rackRef": { + "name": "nb-2f51dc9cdc336da3c50b9a8b" + }, + "scope": "RackMembership" + }, + "provenance": { + "method": "NetBoxImport", + "recordedAt": "2026-11-20T12:00:00Z", + "recordedBy": "netbox-inventory-offline", + "source": { + "id": "1", + "mappingRevision": "example-reviewed-1", + "observedAt": "2026-11-20T12:00:00Z", + "snapshotDigest": "sha256:faeabf49ee04c9376ce308d9347196e38ec07c6dd92d9bc18ea5fc29878ddb08", + "system": "example-netbox", + "type": "dcim/devices" + } + } + } + }, + { + "apiVersion": "fleet.datumapis.com/v1alpha1", + "kind": "Device", + "metadata": { + "name": "nb-b4a16a61aea025fc10ded221", + "namespace": "inventory" + }, + "spec": { + "assetTag": "asset-001", + "claimRef": { + "name": "nb-d2728cbb6945a3e726ab702b" + }, + "components": [ + { + "connector": "1000base-t", + "id": "interfaces-1", + "name": "eth0", + "sourceRef": { + "id": "1", + "system": "example-netbox", + "type": "dcim/interfaces" + }, + "type": "NetworkPort" + }, + { + "id": "power-ports-1", + "name": "PSU1", + "sourceRef": { + "id": "1", + "system": "example-netbox", + "type": "dcim/power-ports" + }, + "type": "PowerInlet" + } + ], + "displayName": "Example server", + "identity": { + "manufacturer": "Example", + "model": "Example physical model", + "sourceIdentity": { + "id": "1", + "system": "example-netbox", + "type": "dcim/devices" + } + }, + "provenance": { + "method": "NetBoxImport", + "recordedAt": "2026-11-20T12:00:00Z", + "recordedBy": "netbox-inventory-offline", + "source": { + "id": "1", + "mappingRevision": "example-reviewed-1", + "observedAt": "2026-11-20T12:00:00Z", + "snapshotDigest": "sha256:faeabf49ee04c9376ce308d9347196e38ec07c6dd92d9bc18ea5fc29878ddb08", + "system": "example-netbox", + "type": "dcim/devices" + } + }, + "providerHostRef": { + "id": "provider-001", + "system": "example-provider", + "type": "host" + }, + "topologyAuthority": "Cable" + } + }, + { + "apiVersion": "fleet.datumapis.com/v1alpha1", + "kind": "DeviceClaim", + "metadata": { + "name": "nb-80a1dd16980a83974841e810", + "namespace": "inventory" + }, + "spec": { + "displayName": "Example PDU", + "expectedIdentity": { + "manufacturer": "Example", + "model": "Example physical model" + }, + "lifecycle": "Installation", + "placement": { + "rackRef": { + "name": "nb-2f51dc9cdc336da3c50b9a8b" + }, + "scope": "RackMembership" + }, + "provenance": { + "method": "NetBoxImport", + "recordedAt": "2026-11-20T12:00:00Z", + "recordedBy": "netbox-inventory-offline", + "source": { + "id": "2", + "mappingRevision": "example-reviewed-1", + "observedAt": "2026-11-20T12:00:00Z", + "snapshotDigest": "sha256:faeabf49ee04c9376ce308d9347196e38ec07c6dd92d9bc18ea5fc29878ddb08", + "system": "example-netbox", + "type": "dcim/devices" + } + } + } + }, + { + "apiVersion": "fleet.datumapis.com/v1alpha1", + "kind": "Device", + "metadata": { + "name": "nb-64e11cbf2b3c9f4866fa9eda", + "namespace": "inventory" + }, + "spec": { + "claimRef": { + "name": "nb-80a1dd16980a83974841e810" + }, + "components": [ + { + "id": "power-ports-2", + "name": "inlet", + "sourceRef": { + "id": "2", + "system": "example-netbox", + "type": "dcim/power-ports" + }, + "type": "PowerInlet" + }, + { + "id": "power-outlets-1", + "name": "outlet-1", + "sourceRef": { + "id": "1", + "system": "example-netbox", + "type": "dcim/power-outlets" + }, + "type": "PowerOutlet" + } + ], + "displayName": "Example PDU", + "identity": { + "manufacturer": "Example", + "model": "Example physical model", + "sourceIdentity": { + "id": "2", + "system": "example-netbox", + "type": "dcim/devices" + } + }, + "internalMappings": [ + { + "from": { + "componentID": "power-outlets-1", + "position": 1 + }, + "to": { + "componentID": "power-ports-2", + "position": 1 + } + } + ], + "provenance": { + "method": "NetBoxImport", + "recordedAt": "2026-11-20T12:00:00Z", + "recordedBy": "netbox-inventory-offline", + "source": { + "id": "2", + "mappingRevision": "example-reviewed-1", + "observedAt": "2026-11-20T12:00:00Z", + "snapshotDigest": "sha256:faeabf49ee04c9376ce308d9347196e38ec07c6dd92d9bc18ea5fc29878ddb08", + "system": "example-netbox", + "type": "dcim/devices" + } + }, + "topologyAuthority": "Cable" + } + }, + { + "apiVersion": "fleet.datumapis.com/v1alpha1", + "kind": "DeviceClaim", + "metadata": { + "name": "nb-9032aa5e04cb441d10d37851", + "namespace": "inventory" + }, + "spec": { + "displayName": "Example panel", + "expectedIdentity": { + "manufacturer": "Example", + "model": "Example physical model" + }, + "lifecycle": "Installation", + "placement": { + "facilityRef": { + "name": "example-premises" + }, + "scope": "Facility" + }, + "provenance": { + "method": "NetBoxImport", + "recordedAt": "2026-11-20T12:00:00Z", + "recordedBy": "netbox-inventory-offline", + "source": { + "id": "3", + "mappingRevision": "example-reviewed-1", + "observedAt": "2026-11-20T12:00:00Z", + "snapshotDigest": "sha256:faeabf49ee04c9376ce308d9347196e38ec07c6dd92d9bc18ea5fc29878ddb08", + "system": "example-netbox", + "type": "dcim/devices" + } + } + } + }, + { + "apiVersion": "fleet.datumapis.com/v1alpha1", + "kind": "Device", + "metadata": { + "name": "nb-25d8e4b769fdb899553c233e", + "namespace": "inventory" + }, + "spec": { + "claimRef": { + "name": "nb-9032aa5e04cb441d10d37851" + }, + "components": [ + { + "id": "front-ports-1", + "name": "front-1", + "sourceRef": { + "id": "1", + "system": "example-netbox", + "type": "dcim/front-ports" + }, + "type": "FrontPort" + }, + { + "id": "rear-ports-1", + "name": "rear-1", + "positions": 2, + "sourceRef": { + "id": "1", + "system": "example-netbox", + "type": "dcim/rear-ports" + }, + "type": "RearPort" + } + ], + "displayName": "Example panel", + "identity": { + "manufacturer": "Example", + "model": "Example physical model", + "sourceIdentity": { + "id": "3", + "system": "example-netbox", + "type": "dcim/devices" + } + }, + "internalMappings": [ + { + "from": { + "componentID": "front-ports-1", + "position": 1 + }, + "to": { + "componentID": "rear-ports-1", + "position": 1 + } + } + ], + "provenance": { + "method": "NetBoxImport", + "recordedAt": "2026-11-20T12:00:00Z", + "recordedBy": "netbox-inventory-offline", + "source": { + "id": "3", + "mappingRevision": "example-reviewed-1", + "observedAt": "2026-11-20T12:00:00Z", + "snapshotDigest": "sha256:faeabf49ee04c9376ce308d9347196e38ec07c6dd92d9bc18ea5fc29878ddb08", + "system": "example-netbox", + "type": "dcim/devices" + } + }, + "serviceAssociations": [ + { + "componentID": "rear-ports-1", + "serviceRef": { + "id": "Example-service", + "system": "example-service-owner", + "type": "transport" + } + } + ], + "topologyAuthority": "Cable" + } + }, + { + "apiVersion": "fleet.datumapis.com/v1alpha1", + "kind": "PowerFeed", + "metadata": { + "name": "nb-15e9e7aa88e11d9ab395e929", + "namespace": "inventory" + }, + "spec": { + "displayName": "Feed A", + "facilityRef": { + "name": "example-premises" + }, + "provenance": { + "method": "NetBoxImport", + "recordedAt": "2026-11-20T12:00:00Z", + "recordedBy": "netbox-inventory-offline", + "source": { + "id": "1", + "mappingRevision": "example-reviewed-1", + "observedAt": "2026-11-20T12:00:00Z", + "snapshotDigest": "sha256:faeabf49ee04c9376ce308d9347196e38ec07c6dd92d9bc18ea5fc29878ddb08", + "system": "example-netbox", + "type": "dcim/power-feeds" + } + }, + "rackRef": { + "name": "nb-2f51dc9cdc336da3c50b9a8b" + }, + "supply": { + "currentA": 30, + "type": "AC", + "voltageV": 208 + }, + "terminations": [ + { + "id": "output", + "name": "output", + "type": "PowerOutlet" + } + ], + "upstreamSources": [ + { + "id": "1", + "system": "example-netbox", + "type": "dcim/power-panels" + } + ] + } + }, + { + "apiVersion": "fleet.datumapis.com/v1alpha1", + "kind": "Cable", + "metadata": { + "name": "nb-4cf1484ca48ba078ba94107c", + "namespace": "inventory" + }, + "spec": { + "displayName": "Power 1", + "lanes": [ + { + "a": { + "componentID": "power-outlets-1", + "deviceRef": { + "name": "nb-64e11cbf2b3c9f4866fa9eda" + }, + "position": 1 + }, + "b": { + "componentID": "power-ports-1", + "deviceRef": { + "name": "nb-b4a16a61aea025fc10ded221" + }, + "position": 1 + }, + "id": "lane-1" + } + ], + "medium": "Power", + "provenance": { + "method": "NetBoxImport", + "recordedAt": "2026-11-20T12:00:00Z", + "recordedBy": "netbox-inventory-offline", + "source": { + "id": "1", + "mappingRevision": "example-reviewed-1", + "observedAt": "2026-11-20T12:00:00Z", + "snapshotDigest": "sha256:faeabf49ee04c9376ce308d9347196e38ec07c6dd92d9bc18ea5fc29878ddb08", + "system": "example-netbox", + "type": "dcim/cables" + } + } + } + } + ], + "kind": "List" +} diff --git a/hack/testdata/netbox/existing.json b/hack/testdata/netbox/existing.json new file mode 100644 index 00000000..1e972629 --- /dev/null +++ b/hack/testdata/netbox/existing.json @@ -0,0 +1,17 @@ +{ + "collections": [ + "Facility", + "Rack", + "DeviceClaim", + "Device", + "Cable", + "PowerFeed" + ], + "items": [], + "target": { + "application": "provider-inventory", + "namespace": "inventory", + "project": "example-provider", + "writer": "Flux" + } +} diff --git a/hack/testdata/netbox/mapping.json b/hack/testdata/netbox/mapping.json new file mode 100644 index 00000000..c0499aee --- /dev/null +++ b/hack/testdata/netbox/mapping.json @@ -0,0 +1,68 @@ +{ + "cables": { + "1": { + "medium": "Power" + } + }, + "circuits": { + "1": { + "id": "Example-service", + "system": "example-service-owner", + "type": "transport" + } + }, + "demarcations": { + "1": { + "componentSource": "dcim/rear-ports/1" + } + }, + "devices": { + "1": { + "classification": "physical", + "placement": { + "scope": "RackMembership" + }, + "provider": "example-provider", + "serialMeaning": "providerHostID" + }, + "2": { + "classification": "physical", + "placement": { + "scope": "RackMembership" + }, + "serialMeaning": "unknown" + }, + "3": { + "classification": "physical", + "placement": { + "facility": "example-premises", + "scope": "Facility" + }, + "serialMeaning": "unknown" + } + }, + "facilities": [ + { + "displayName": "Example premises", + "name": "example-premises", + "source": "dcim/sites/1" + } + ], + "feeds": { + "1": { + "facility": "example-premises" + } + }, + "racks": { + "1": { + "facility": "example-premises" + } + }, + "revision": "example-reviewed-1", + "target": { + "application": "provider-inventory", + "namespace": "inventory", + "project": "example-provider", + "writer": "Flux" + } +} diff --git a/hack/testdata/netbox/snapshot.json b/hack/testdata/netbox/snapshot.json new file mode 100644 index 00000000..c839e5c0 --- /dev/null +++ b/hack/testdata/netbox/snapshot.json @@ -0,0 +1,209 @@ +{ + "errors": {}, + "objects": { + "circuits/circuit-terminations": [ + { + "circuit": { + "id": 1 + }, + "id": 1 + } + ], + "circuits/circuits": [ + { + "cid": "Example-service", + "id": 1 + } + ], + "dcim/cables": [ + { + "a_terminations": [ + { + "object_id": 1, + "object_type": "dcim.poweroutlet" + } + ], + "b_terminations": [ + { + "object_id": 1, + "object_type": "dcim.powerport" + } + ], + "id": 1, + "label": "Power 1" + } + ], + "dcim/console-ports": [], + "dcim/console-server-ports": [], + "dcim/device-bays": [], + "dcim/device-types": [ + { + "id": 1, + "manufacturer": { + "id": 1, + "name": "Example" + }, + "model": "Example physical model" + } + ], + "dcim/devices": [ + { + "asset_tag": "asset-001", + "device_type": { + "id": 1 + }, + "id": 1, + "name": "Example server", + "position": 1, + "rack": { + "id": 1 + }, + "serial": "provider-001" + }, + { + "device_type": { + "id": 1 + }, + "id": 2, + "name": "Example PDU", + "rack": { + "id": 1 + } + }, + { + "device_type": { + "id": 1 + }, + "id": 3, + "name": "Example panel" + }, + { + "device_type": { + "model": "netactuate VM" + }, + "id": 4, + "name": "Example VM" + } + ], + "dcim/front-ports": [ + { + "device": { + "id": 3 + }, + "id": 1, + "name": "front-1", + "rear_port": { + "id": 1 + }, + "rear_port_position": 1 + } + ], + "dcim/interfaces": [ + { + "device": { + "id": 1 + }, + "id": 1, + "name": "eth0", + "type": "1000base-t" + }, + { + "device": { + "id": 1 + }, + "id": 2, + "name": "bond0", + "type": "lag" + } + ], + "dcim/inventory-items": [], + "dcim/locations": [ + { + "id": 1, + "name": "Example room" + } + ], + "dcim/manufacturers": [ + { + "id": 1, + "name": "Example" + } + ], + "dcim/modules": [], + "dcim/power-feeds": [ + { + "amperage": 30, + "id": 1, + "name": "Feed A", + "power_panel": { + "id": 1 + }, + "rack": { + "id": 1 + }, + "supply": "ac", + "voltage": 208 + } + ], + "dcim/power-outlets": [ + { + "device": { + "id": 2 + }, + "id": 1, + "name": "outlet-1", + "power_port": { + "id": 2 + } + } + ], + "dcim/power-panels": [ + { + "id": 1, + "name": "Panel A" + } + ], + "dcim/power-ports": [ + { + "device": { + "id": 1 + }, + "id": 1, + "name": "PSU1" + }, + { + "device": { + "id": 2 + }, + "id": 2, + "name": "inlet" + } + ], + "dcim/racks": [ + { + "id": 1, + "name": "Example rack", + "u_height": 42 + } + ], + "dcim/rear-ports": [ + { + "device": { + "id": 3 + }, + "id": 1, + "name": "rear-1", + "positions": 2 + } + ], + "dcim/sites": [ + { + "id": 1, + "name": "Example metro grouping" + } + ] + }, + "observedAt": "2026-11-20T12:00:00Z", + "source": "example-netbox", + "version": 1 +} diff --git a/internal/api/inventory/v1alpha1/crd_test.go b/internal/api/inventory/v1alpha1/crd_test.go index 3f498f83..ae30e735 100644 --- a/internal/api/inventory/v1alpha1/crd_test.go +++ b/internal/api/inventory/v1alpha1/crd_test.go @@ -55,8 +55,8 @@ func loadCRDs(t *testing.T) map[string]*extensionsv1.CustomResourceDefinition { func TestInventoryCRDContract(t *testing.T) { crds := loadCRDs(t) - if len(crds) != 2 || crds["DeviceClaim"] == nil || crds["Device"] == nil { - t.Fatalf("got CRDs %v, want exactly DeviceClaim and Device", crds) + if len(crds) != 6 || crds["DeviceClaim"] == nil || crds["Device"] == nil { + t.Fatalf("got %d CRDs, want six physical kinds", len(crds)) } for kind, crd := range crds { if crd.Spec.Group != GroupVersion.Group || crd.Name != crd.Spec.Names.Plural+"."+GroupVersion.Group || crd.Spec.Scope != extensionsv1.NamespaceScoped { @@ -188,13 +188,13 @@ func TestValidRecordsAreAccepted(t *testing.T) { } } -func TestClaimDoesNotRequireSerialAndDefaultsHeight(t *testing.T) { +func TestClaimDoesNotRequireSerialOrInventHeight(t *testing.T) { claim := object(t, syntheticClaim()) if errs := admit(t, "DeviceClaim", claim, nil); len(errs) > 0 { t.Fatal(errs) } - if height := claim["spec"].(map[string]any)["placement"].(map[string]any)["height"]; height != int64(1) { - t.Fatalf("height defaulted to %v", height) + if height := claim["spec"].(map[string]any)["placement"].(map[string]any)["height"]; height != nil { + t.Fatalf("height must not invent a partial-placement footprint: %v", height) } } diff --git a/internal/api/inventory/v1alpha1/physical.go b/internal/api/inventory/v1alpha1/physical.go new file mode 100644 index 00000000..c50f6451 --- /dev/null +++ b/internal/api/inventory/v1alpha1/physical.go @@ -0,0 +1,175 @@ +package v1alpha1 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" +) + +type ExternalReference struct { + System string `json:"system"` + Type string `json:"type"` + ID string `json:"id"` +} + +type ModelShape struct { + HeightUnits *float64 `json:"heightUnits,omitempty"` + FullDepth *bool `json:"fullDepth,omitempty"` +} + +type SourceReference struct { + ExternalReference `json:",inline"` + SnapshotDigest string `json:"snapshotDigest"` + MappingRevision string `json:"mappingRevision"` + ObservedAt metav1.Time `json:"observedAt"` +} + +type PhysicalMetadata struct { + DisplayName string `json:"displayName"` + Provenance Provenance `json:"provenance"` +} + +type FacilitySpec struct { + PhysicalMetadata `json:",inline"` + LocationRef *LocalReference `json:"locationRef,omitempty"` +} + +type RackSpec struct { + PhysicalMetadata `json:",inline"` + FacilityRef LocalReference `json:"facilityRef"` + HeightUnits int32 `json:"heightUnits,omitempty"` +} + +type Component struct { + ID string `json:"id"` + Name string `json:"name"` + Type string `json:"type"` + Connector string `json:"connector,omitempty"` + Positions int32 `json:"positions,omitempty"` + Serial string `json:"serial,omitempty"` + AssetTag string `json:"assetTag,omitempty"` + SourceRef *ExternalReference `json:"sourceRef,omitempty"` +} + +type ComponentPosition struct { + ComponentID string `json:"componentID"` + Position int32 `json:"position"` +} + +type InternalMapping struct { + From ComponentPosition `json:"from"` + To ComponentPosition `json:"to"` +} + +type ServiceAssociation struct { + ServiceRef ExternalReference `json:"serviceRef"` + ComponentID string `json:"componentID"` +} + +type CableEndpoint struct { + DeviceRef *LocalReference `json:"deviceRef,omitempty"` + PowerFeedRef *LocalReference `json:"powerFeedRef,omitempty"` + ComponentID string `json:"componentID"` + Position int32 `json:"position"` +} + +type CableLane struct { + ID string `json:"id"` + A CableEndpoint `json:"a"` + B CableEndpoint `json:"b"` +} + +type CableSpec struct { + PhysicalMetadata `json:",inline"` + Medium string `json:"medium"` + Lanes []CableLane `json:"lanes"` +} + +type PowerSupply struct { + Type string `json:"type"` + VoltageV int32 `json:"voltageV,omitempty"` + CurrentA int32 `json:"currentA,omitempty"` + Phase string `json:"phase,omitempty"` +} + +type PowerFeedSpec struct { + PhysicalMetadata `json:",inline"` + FacilityRef LocalReference `json:"facilityRef"` + RackRef *LocalReference `json:"rackRef,omitempty"` + Supply *PowerSupply `json:"supply,omitempty"` + Terminations []Component `json:"terminations"` + UpstreamSources []ExternalReference `json:"upstreamSources,omitempty"` +} + +type Facility struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + Spec FacilitySpec `json:"spec"` +} +type Rack struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + Spec RackSpec `json:"spec"` +} +type Cable struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + Spec CableSpec `json:"spec"` +} +type PowerFeed struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + Spec PowerFeedSpec `json:"spec"` +} +type FacilityList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []Facility `json:"items"` +} +type RackList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []Rack `json:"items"` +} +type CableList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []Cable `json:"items"` +} +type PowerFeedList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []PowerFeed `json:"items"` +} + +func (in *Facility) DeepCopyObject() runtime.Object { + out := new(Facility) + deepCopy(in, out) + return out +} +func (in *Rack) DeepCopyObject() runtime.Object { out := new(Rack); deepCopy(in, out); return out } +func (in *Cable) DeepCopyObject() runtime.Object { out := new(Cable); deepCopy(in, out); return out } +func (in *PowerFeed) DeepCopyObject() runtime.Object { + out := new(PowerFeed) + deepCopy(in, out) + return out +} +func (in *FacilityList) DeepCopyObject() runtime.Object { + out := new(FacilityList) + deepCopy(in, out) + return out +} +func (in *RackList) DeepCopyObject() runtime.Object { + out := new(RackList) + deepCopy(in, out) + return out +} +func (in *CableList) DeepCopyObject() runtime.Object { + out := new(CableList) + deepCopy(in, out) + return out +} +func (in *PowerFeedList) DeepCopyObject() runtime.Object { + out := new(PowerFeedList) + deepCopy(in, out) + return out +} diff --git a/internal/api/inventory/v1alpha1/physical_test.go b/internal/api/inventory/v1alpha1/physical_test.go new file mode 100644 index 00000000..8229849b --- /dev/null +++ b/internal/api/inventory/v1alpha1/physical_test.go @@ -0,0 +1,152 @@ +package v1alpha1 + +import ( + "encoding/json" + "os" + "strings" + "testing" + "time" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" +) + +func TestSyntheticNetBoxHandoffPassesAdmission(t *testing.T) { + data, err := os.ReadFile("../../../../hack/testdata/netbox/candidates.json") + if err != nil { + t.Fatal(err) + } + var list struct { + Items []json.RawMessage `json:"items"` + } + if err := json.Unmarshal(data, &list); err != nil { + t.Fatal(err) + } + for _, raw := range list.Items { + var record map[string]any + if err := json.Unmarshal(raw, &record); err != nil { + t.Fatal(err) + } + kind := record["kind"].(string) + if errs := admit(t, kind, object(t, record), nil); len(errs) != 0 { + t.Fatalf("%s: %v", kind, errs) + } + } +} + +func TestTypedPlacementAndLegacyBinding(t *testing.T) { + claim := syntheticClaim() + claim.Spec.Lifecycle = "Installation" + claim.Spec.Ports = nil + claim.Spec.Placement = Placement{Scope: "RackMembership", RackRef: &LocalReference{Name: "rack-a"}} + if errs := admit(t, "DeviceClaim", object(t, claim), nil); len(errs) != 0 { + t.Fatal(errs) + } + for _, placement := range []Placement{ + {Scope: "Facility", FacilityRef: &LocalReference{Name: "facility-a"}}, + {Scope: "RackUnits", RackRef: &LocalReference{Name: "rack-a"}, Position: 12, Height: 1, Face: "front"}, + {Scope: "NonRackUnitMount", RackRef: &LocalReference{Name: "rack-a"}, Mount: "side-a"}, + } { + candidate := claim + candidate.Spec.Placement = placement + if errs := admit(t, "DeviceClaim", object(t, candidate), nil); len(errs) != 0 { + t.Fatal(errs) + } + candidate.Spec.Provenance.RecordedAt = later(time.Hour) + if errs := admit(t, "DeviceClaim", object(t, candidate), object(t, claim)); len(errs) == 0 { + t.Fatal("moved an installation by editing placement") + } + } + candidate := claim + candidate.Spec.Placement.Position = 1 + if errs := admit(t, "DeviceClaim", object(t, candidate), nil); len(errs) == 0 { + t.Fatal("accepted synthetic units on rack membership") + } + candidate = claim + candidate.Spec.Provenance.RecordedAt = later(time.Hour) + if errs := admit(t, "DeviceClaim", object(t, candidate), object(t, syntheticClaim())); len(errs) == 0 { + t.Fatal("converted a legacy slot in place") + } + candidate.Spec.Ports = syntheticClaim().Spec.Ports + if errs := admit(t, "DeviceClaim", object(t, candidate), nil); len(errs) == 0 { + t.Fatal("accepted competing inline topology") + } +} + +func TestPhysicalKindsSchemeAndAdmission(t *testing.T) { + scheme := runtime.NewScheme() + if err := AddToScheme(scheme); err != nil { + t.Fatal(err) + } + common := PhysicalMetadata{DisplayName: "Example", Provenance: provenance(recordedAt)} + metadata := metav1.ObjectMeta{Name: "example", Namespace: "inventory"} + records := []runtime.Object{ + &Facility{ObjectMeta: metadata, Spec: FacilitySpec{PhysicalMetadata: common}}, + &Rack{ObjectMeta: metadata, Spec: RackSpec{PhysicalMetadata: common, FacilityRef: LocalReference{Name: "example"}, HeightUnits: 42}}, + &PowerFeed{ObjectMeta: metadata, Spec: PowerFeedSpec{PhysicalMetadata: common, FacilityRef: LocalReference{Name: "example"}, Terminations: []Component{{ID: "output", Name: "output", Type: "PowerOutlet"}}}}, + &Cable{ObjectMeta: metadata, Spec: CableSpec{PhysicalMetadata: common, Medium: "Power", Lanes: []CableLane{{ID: "one", A: CableEndpoint{PowerFeedRef: &LocalReference{Name: "example"}, ComponentID: "output", Position: 1}, B: CableEndpoint{DeviceRef: &LocalReference{Name: "server"}, ComponentID: "inlet", Position: 1}}}}}, + } + for _, record := range records { + kinds, _, err := scheme.ObjectKinds(record) + if err != nil { + t.Fatal(err) + } + kind := kinds[0].Kind + if errs := admit(t, kind, object(t, record.DeepCopyObject()), nil); len(errs) != 0 { + t.Fatalf("%s: %v", kind, errs) + } + } + cable := records[3].(*Cable) + cable.Spec.Lanes[0].A.DeviceRef = &LocalReference{Name: "other"} + if errs := admit(t, "Cable", object(t, cable), nil); len(errs) == 0 { + t.Fatal("accepted ambiguous endpoint owner") + } + cable.Spec.Lanes[0].A.DeviceRef = nil + cable.Spec.Lanes = append(cable.Spec.Lanes, cable.Spec.Lanes[0]) + cable.Spec.Lanes[1].ID = "two" + if errs := admit(t, "Cable", object(t, cable), nil); len(errs) == 0 { + t.Fatal("accepted duplicate lane endpoint") + } +} + +func TestObservationalIdentityAndComponentSafety(t *testing.T) { + device := syntheticDevice() + device.Spec.Interfaces = nil + device.Spec.TopologyAuthority = "Cable" + device.Spec.Identity.Serial, device.Spec.Identity.SystemUUID = "", "" + source := ExternalReference{System: "example-netbox", Type: "dcim/devices", ID: "1"} + device.Spec.Identity.SourceIdentity = &source + device.Spec.Provenance.Method = "NetBoxImport" + device.Spec.Provenance.Source = &SourceReference{ExternalReference: source, SnapshotDigest: "sha256:" + strings.Repeat("a", 64), MappingRevision: "example-1", ObservedAt: metav1.NewTime(recordedAt)} + device.Spec.Components = []Component{{ID: "front", Name: "front", Type: "FrontPort"}, {ID: "rear", Name: "rear", Type: "RearPort", Positions: 2}} + device.Spec.InternalMappings = []InternalMapping{{From: ComponentPosition{ComponentID: "front", Position: 1}, To: ComponentPosition{ComponentID: "rear", Position: 2}}} + if errs := admit(t, "Device", object(t, device), nil); len(errs) != 0 { + t.Fatal(errs) + } + candidate := device.DeepCopyObject().(*Device) + candidate.Spec.InternalMappings[0].To.Position = 3 + if errs := admit(t, "Device", object(t, candidate), nil); len(errs) == 0 { + t.Fatal("accepted nonexistent panel position") + } + candidate = device.DeepCopyObject().(*Device) + candidate.Spec.Components = append(candidate.Spec.Components, candidate.Spec.Components[0]) + if errs := admit(t, "Device", object(t, candidate), nil); len(errs) == 0 { + t.Fatal("accepted duplicate component ID") + } + candidate = device.DeepCopyObject().(*Device) + candidate.Spec.Components[1].Type = "NetworkPort" + if errs := admit(t, "Device", object(t, candidate), nil); len(errs) == 0 { + t.Fatal("accepted incompatible pass-through component types") + } + candidate = device.DeepCopyObject().(*Device) + candidate.Spec.Provenance.Source.ID = "2" + candidate.Spec.Provenance.RecordedAt = later(time.Hour) + if errs := admit(t, "Device", object(t, candidate), object(t, device)); len(errs) == 0 { + t.Fatal("accepted source identity takeover") + } + candidate = device.DeepCopyObject().(*Device) + candidate.Spec.Interfaces = syntheticDevice().Spec.Interfaces + if errs := admit(t, "Device", object(t, candidate), nil); len(errs) == 0 { + t.Fatal("accepted Cable and inline topology writers") + } +} diff --git a/internal/api/inventory/v1alpha1/types.go b/internal/api/inventory/v1alpha1/types.go index 66351684..eb77dfb1 100644 --- a/internal/api/inventory/v1alpha1/types.go +++ b/internal/api/inventory/v1alpha1/types.go @@ -1,8 +1,8 @@ -// Package v1alpha1 holds a minimal subset of the proposed physical inventory -// API in fleet.datumapis.com: DeviceClaim, the installation plan for one slot, -// and Device, the actual asset bound to a claim. +// Package v1alpha1 holds the six observational physical inventory kinds in +// fleet.datumapis.com. Legacy slot claims retain their historical bindings; +// new typed claims describe individual installations without accepting them. // -// Both are operator-written records. Neither has a controller. Registering a +// All are operator-written records. None has a controller. Registering a // Device authorizes no hardware effect and creates or changes no // MachineCapacity. Status is reserved for future collectors and verifiers and // has no writer. @@ -29,11 +29,11 @@ type Provenance struct { RecordedAt metav1.Time `json:"recordedAt"` // Reference is an optional, opaque pointer to where the facts came from. // Fleet does not interpret it. - Reference string `json:"reference,omitempty"` + Reference string `json:"reference,omitempty"` + Source *SourceReference `json:"source,omitempty"` } -// DeviceClaim is the plan for one physical slot, written by the installation -// planner before hardware arrives. The slot outlives any one Device. +// DeviceClaim retains legacy slot plans and typed observational installations. type DeviceClaim struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty"` @@ -42,6 +42,9 @@ type DeviceClaim struct { } type DeviceClaimSpec struct { + DisplayName string `json:"displayName,omitempty"` + Lifecycle string `json:"lifecycle,omitempty"` + CableRefs []LocalReference `json:"cableRefs,omitempty"` Provenance Provenance `json:"provenance"` ExpectedIdentity ExpectedIdentity `json:"expectedIdentity"` Placement Placement `json:"placement"` @@ -56,14 +59,17 @@ type ExpectedIdentity struct { Serial string `json:"serial,omitempty"` } -// Placement is the planned mount: the lowest occupied rack unit, the number of -// units, and the face. Facility and Rack are names until those kinds exist. +// Placement retains legacy text placement or an explicit typed scope. type Placement struct { - Facility string `json:"facility"` - Rack string `json:"rack"` - Position int32 `json:"position"` - Height int32 `json:"height,omitempty"` - Face string `json:"face"` + Scope string `json:"scope,omitempty"` + FacilityRef *LocalReference `json:"facilityRef,omitempty"` + RackRef *LocalReference `json:"rackRef,omitempty"` + Mount string `json:"mount,omitempty"` + Facility string `json:"facility,omitempty"` + Rack string `json:"rack,omitempty"` + Position int32 `json:"position,omitempty"` + Height int32 `json:"height,omitempty"` + Face string `json:"face,omitempty"` } // ExpectedPort is a planned physical port and the cable peer it should reach. @@ -95,11 +101,19 @@ type Device struct { } type DeviceSpec struct { - ClaimRef LocalReference `json:"claimRef"` - Provenance Provenance `json:"provenance"` - Identity DeviceIdentity `json:"identity"` - BMC *BMC `json:"bmc,omitempty"` - Interfaces []Interface `json:"interfaces,omitempty"` + DisplayName string `json:"displayName,omitempty"` + ModelShape *ModelShape `json:"modelShape,omitempty"` + AssetTag string `json:"assetTag,omitempty"` + ProviderHostRef *ExternalReference `json:"providerHostRef,omitempty"` + Components []Component `json:"components,omitempty"` + InternalMappings []InternalMapping `json:"internalMappings,omitempty"` + ServiceAssociations []ServiceAssociation `json:"serviceAssociations,omitempty"` + TopologyAuthority string `json:"topologyAuthority,omitempty"` + ClaimRef LocalReference `json:"claimRef"` + Provenance Provenance `json:"provenance"` + Identity DeviceIdentity `json:"identity"` + BMC *BMC `json:"bmc,omitempty"` + Interfaces []Interface `json:"interfaces,omitempty"` // UnmappedMACAddresses are MACs detected on the asset that the registrar // could not attribute to a named interface. UnmappedMACAddresses []string `json:"unmappedMACAddresses,omitempty"` @@ -110,11 +124,12 @@ type LocalReference struct { } // DeviceIdentity is the detected chassis identity. Serial and SystemUUID are -// matching evidence, not authenticators. At least one is required. +// matching evidence, not authenticators. Imports can instead retain source identity. type DeviceIdentity struct { - Manufacturer string `json:"manufacturer,omitempty"` - Model string `json:"model"` - Serial string `json:"serial,omitempty"` + SourceIdentity *ExternalReference `json:"sourceIdentity,omitempty"` + Manufacturer string `json:"manufacturer,omitempty"` + Model string `json:"model"` + Serial string `json:"serial,omitempty"` // SystemUUID is the SMBIOS system UUID in lowercase canonical form. SystemUUID string `json:"systemUUID,omitempty"` } @@ -148,7 +163,7 @@ type DeviceList struct { } func addKnown(s *runtime.Scheme) error { - s.AddKnownTypes(GroupVersion, &DeviceClaim{}, &DeviceClaimList{}, &Device{}, &DeviceList{}) + s.AddKnownTypes(GroupVersion, &DeviceClaim{}, &DeviceClaimList{}, &Device{}, &DeviceList{}, &Facility{}, &FacilityList{}, &Rack{}, &RackList{}, &Cable{}, &CableList{}, &PowerFeed{}, &PowerFeedList{}) metav1.AddToGroupVersion(s, GroupVersion) return nil } diff --git a/ui/provider/README.md b/ui/provider/README.md index 3514062f..eccd8ba6 100644 --- a/ui/provider/README.md +++ b/ui/provider/README.md @@ -26,15 +26,16 @@ Operations in the navigation. The page has three tabs: missing claim are listed separately. `inventory/:namespace/:claim` shows one claim's planned placement, expected ports and peers, and provenance. It also shows every Device bound to it: model, serial, system UUID, BMC endpoint, - interfaces, unmapped MACs and provenance, with the most recently recorded - Device as the current one. Operators write these records through GitOps; the + interfaces, typed components, separate asset tags/provider IDs, unmapped MACs + and provenance. Multiple historical Devices keep the active binding Unknown; + edit time does not establish current hardware. Operators write through GitOps; the plugin never writes them. The portal proxy forwards the staff member's own token, so creating capacity, profiles and classes needs a Bare Metal role with `machinecapacities.create`, `machineprofiles.create` and `machineclasses.create` in the provider project, -such as `metal.datumapis.com-provider`. The Inventory tab needs `deviceclaims.list` -and `devices.list` in `fleet.datumapis.com`, which +such as `metal.datumapis.com-provider`. The Inventory tab needs list access to +all six physical kinds in `fleet.datumapis.com`, which `fleet.datumapis.com-inventory-viewer` grants; metal roles grant no inventory access. Errors show inside the create dialog, because staff-portal does not share its toast module with plugins. @@ -86,6 +87,14 @@ to that array instead. ## Differences from the consumer plugin +The read-only Inventory tab now loads all six physical inventory collections +with pagination. It retains unknown placement and ambiguous historical bindings, +shows Facility/Rack/Cable/PowerFeed relationships and typed asset components, +and supports local-only review of import reports. These reads require the +provider-scoped inventory viewer role, not a consumer Metal role. See the +[physical import operator guide](../../docs/operations/netbox-physical-import.md) +for the offline Flux handoff and the distinction between records and readiness. + - staff-portal runs react-router 7, so this plugin pins it for types and shares it with `requiredVersion: false`. - staff-portal shares only the `badge`, `button`, `card`, `icons` and diff --git a/ui/provider/src/components/inventory-table.tsx b/ui/provider/src/components/inventory-table.tsx index f8552506..8076ad40 100644 --- a/ui/provider/src/components/inventory-table.tsx +++ b/ui/provider/src/components/inventory-table.tsx @@ -17,10 +17,11 @@ function matchesSearch(slot: InventorySlot, search: string): boolean { const { claim } = slot; return [ claim.metadata.name, + claim.spec.displayName, placementLabel(claim), modelLabel(claim.spec.expectedIdentity), claim.spec.expectedIdentity.serial, - ...slot.devices.flatMap((d) => [d.metadata.name, d.spec.identity.serial, d.spec.identity.systemUUID]), + ...slot.devices.flatMap((d) => [d.metadata.name, d.spec.displayName, d.spec.assetTag, d.spec.providerHostRef?.id, d.spec.identity.serial, d.spec.identity.systemUUID]), ] .filter(Boolean) .join(' ') @@ -38,7 +39,7 @@ export function InventoryTable({ slots, base }: { slots: InventorySlot[]; base: - {row.original.claim.metadata.name} + {row.original.claim.spec.displayName ?? row.original.claim.metadata.name} ), }, @@ -53,7 +54,7 @@ export function InventoryTable({ slots, base }: { slots: InventorySlot[]; base: header: 'Device', cell: ({ row }) => { const device = currentDevice(row.original); - if (!device) return Not registered; + if (!device) return {row.original.devices.length > 1 ? 'Active binding Unknown' : 'Not registered'}; return {device.metadata.name}; }, }, diff --git a/ui/provider/src/components/physical-inventory.test.tsx b/ui/provider/src/components/physical-inventory.test.tsx new file mode 100644 index 00000000..dcd255a2 --- /dev/null +++ b/ui/provider/src/components/physical-inventory.test.tsx @@ -0,0 +1,28 @@ +import { fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { describe, expect, it } from 'vitest'; +import { PhysicalInventory } from './physical-inventory'; +import { toInventory, placementLabel } from '../inventory'; +import { fixtureDeviceClaims } from '../lib/fixtures'; + +describe('physical inventory', () => { + it('keeps partial placement and free space unknown', () => { + const claim = { ...fixtureDeviceClaims[0], spec: { ...fixtureDeviceClaims[0].spec, placement: { scope: 'RackMembership' as const, rackRef: { name: 'rack-example' } } } }; + expect(placementLabel(claim)).toContain('no reserved units'); + const inventory = toInventory([claim], [], [{ kind: 'Rack', metadata: { name: 'rack-example', namespace: 'default' }, spec: { displayName: 'Rack example', facilityRef: { name: 'example' }, provenance: claim.spec.provenance } }]); + render(); + expect(screen.getByText(/Free space: Unknown/)).toBeInTheDocument(); + expect(screen.queryByText(/1 registered assets/)).not.toBeInTheDocument(); + expect(screen.getByText(/0 registered assets; occupancy unverified/)).toBeInTheDocument(); + }); + + it('reads reconciliation locally and rejects malformed reports', async () => { + render(); + const input = screen.getByLabelText(/Inspect a private import report/); + fireEvent.change(input, { target: { files: [{ size: 100, text: async () => JSON.stringify({ version: 1, records: [{ source: 'dcim/devices/1', classification: 'unresolved', reason: 'Review premises' }] }) }] } }); + await waitFor(() => expect(screen.getByText(/dcim\/devices\/1: unresolved/)).toBeInTheDocument()); + expect(screen.getByText(/Incomplete or Unknown/)).toBeInTheDocument(); + fireEvent.change(input, { target: { files: [{ size: 100, text: async () => '{"version":1,"records":[null]}' }] } }); + await waitFor(() => expect(screen.getByRole('alert')).toBeInTheDocument()); + expect(screen.queryByText(/dcim\/devices\/1: unresolved/)).not.toBeInTheDocument(); + }); +}); diff --git a/ui/provider/src/components/physical-inventory.tsx b/ui/provider/src/components/physical-inventory.tsx new file mode 100644 index 00000000..0c032dca --- /dev/null +++ b/ui/provider/src/components/physical-inventory.tsx @@ -0,0 +1,59 @@ +import type { Inventory } from '../inventory'; +import type { CableEndpoint } from '../../../shared/fleet-api'; +import { useState } from 'react'; + +export function endpointLabel(endpoint: CableEndpoint): string { + return `${endpoint.deviceRef?.name ?? endpoint.powerFeedRef?.name ?? 'Unknown'}/${endpoint.componentID}:${endpoint.position}`; +} + +export function PhysicalInventory({ inventory }: { inventory: Inventory }) { + const [report, setReport] = useState<{ source: string; classification: string; reason: string }[]>([]); + const [error, setError] = useState(''); + const [summary, setSummary] = useState<{ complete: boolean; errors: string[]; missing: string[] }>(); + const [search, setSearch] = useState(''); + const matching = report.filter((row) => `${row.source} ${row.classification} ${row.reason}`.toLowerCase().includes(search.toLowerCase())); + return
+

Physical records · verification Unknown

+

Observational records do not reserve space, establish an active binding, or authorize hardware operations. Cable is the typed topology authority; legacy inline peers remain unmigrated history.

+ + {error &&

{error}

} + {summary &&

Import reconciliation — candidates, not applied records

+

Collection fetch: {summary.complete ? 'Complete (not physical parity)' : 'Incomplete or Unknown'} · {report.length} classified records

+
    {summary.errors.map((message) =>
  • {message}
  • )}
+

Missing source records are retained, never deleted: {summary.missing.length}

+
    {summary.missing.map((identity, index) =>
  • {identity}
  • )}
+ +

Showing {Math.min(matching.length, 250)} of {matching.length} matching rows

+
    {matching.slice(0, 250).map((row) =>
  • {row.source}: {row.classification} — {row.reason}
  • )}
+
} + {inventory.physical.map((record) =>
+ {record.kind}: {record.spec.displayName} ({record.metadata.name}) +

Namespace: {record.metadata.namespace} · Source: {record.spec.provenance.method} · Verification: Unknown

+ {record.spec.provenance.source &&

Source object: {record.spec.provenance.source.system}/{record.spec.provenance.source.type}/{record.spec.provenance.source.id} · Mapping: {record.spec.provenance.source.mappingRevision}

} + {record.spec.facilityRef &&

Facility: {record.spec.facilityRef.name}

} + {record.spec.rackRef &&

Rack: {record.spec.rackRef.name}

} + {record.spec.locationRef &&

Geographic location reference: {record.spec.locationRef.name}

} + {record.kind === 'Rack' &&

Height: {record.spec.heightUnits ?? 'Unknown'} · Free space: Unknown

} + {record.spec.lanes?.map((lane) =>

{lane.id}: {endpointLabel(lane.a)} ↔ {endpointLabel(lane.b)} ({record.spec.medium})

)} + {record.kind === 'PowerFeed' &&

Supply: {record.spec.supply?.type ?? 'Unknown'} · Voltage: {record.spec.supply?.voltageV ?? 'Unknown'} V · Current rating: {record.spec.supply?.currentA ?? 'Unknown'} A · Usable budget and redundancy: Unknown

} + {record.spec.upstreamSources?.map((source) =>

Upstream: {source.system}/{source.type}/{source.id}

)} +
    {inventory.slots.filter((slot) => slot.claim.metadata.namespace === record.metadata.namespace && (slot.claim.spec.placement.rackRef?.name === record.metadata.name && record.kind === 'Rack' || slot.claim.spec.placement.facilityRef?.name === record.metadata.name && record.kind === 'Facility')).map((slot) =>
  • {slot.claim.metadata.name} — {slot.devices.length} registered assets; occupancy unverified
  • )}
+
)} +
; +} diff --git a/ui/provider/src/inventory.test.ts b/ui/provider/src/inventory.test.ts index 4581e800..b938ceab 100644 --- a/ui/provider/src/inventory.test.ts +++ b/ui/provider/src/inventory.test.ts @@ -19,7 +19,7 @@ describe('toInventory', () => { expect(inventory.unboundDevices).toHaveLength(1); }); - it('treats the most recently recorded Device as the current hardware', () => { + it('does not infer active hardware from the most recently edited record', () => { const replacement = { ...fixtureDevices[0], metadata: { ...fixtureDevices[0].metadata, name: 'rack-01-u12-synthetic-0002' }, @@ -28,7 +28,7 @@ describe('toInventory', () => { const inventory = toInventory(fixtureDeviceClaims, [replacement, fixtureDevices[0]]); const u12 = inventory.slots.find((s) => s.claim.metadata.name === 'rack-01-u12')!; expect(u12.devices).toHaveLength(2); - expect(currentDevice(u12)?.metadata.name).toBe('rack-01-u12-synthetic-0002'); + expect(currentDevice(u12)).toBeUndefined(); }); it('labels single and multi-unit placements', () => { diff --git a/ui/provider/src/inventory.ts b/ui/provider/src/inventory.ts index cceed449..54b8efc5 100644 --- a/ui/provider/src/inventory.ts +++ b/ui/provider/src/inventory.ts @@ -2,7 +2,7 @@ // Device that names it in the same namespace; a replacement leaves more than // one. Devices whose claim is missing are kept separately so they stay visible. -import type { Device as RawDevice, DeviceClaim as RawDeviceClaim, List } from '../../shared/fleet-api'; +import type { Device as RawDevice, DeviceClaim as RawDeviceClaim, List, PhysicalRecord } from '../../shared/fleet-api'; export type { RawDevice, RawDeviceClaim }; export type RawDeviceList = List; @@ -17,6 +17,7 @@ export interface InventorySlot { export interface Inventory { slots: InventorySlot[]; unboundDevices: RawDevice[]; + physical: PhysicalRecord[]; } export function slotKey(namespace: string | undefined, name: string): string { @@ -27,7 +28,7 @@ function byRecordedAt(a: RawDevice, b: RawDevice): number { return a.spec.provenance.recordedAt.localeCompare(b.spec.provenance.recordedAt); } -export function toInventory(claims: RawDeviceClaim[], devices: RawDevice[]): Inventory { +export function toInventory(claims: RawDeviceClaim[], devices: RawDevice[], physical: PhysicalRecord[] = []): Inventory { const slots = new Map(); for (const claim of claims) { const key = slotKey(claim.metadata.namespace, claim.metadata.name); @@ -41,22 +42,27 @@ export function toInventory(claims: RawDeviceClaim[], devices: RawDevice[]): Inv } for (const slot of slots.values()) slot.devices.sort(byRecordedAt); return { + physical, slots: [...slots.values()].sort((a, b) => a.key.localeCompare(b.key)), unboundDevices: unboundDevices.sort((a, b) => a.metadata.name.localeCompare(b.metadata.name)), }; } export function placementLabel(claim: RawDeviceClaim): string { - const { facility, rack, position, height = 1, face } = claim.spec.placement; + const { facility, rack, position, height = 1, face, scope, facilityRef, rackRef, mount } = claim.spec.placement; + if (scope === 'Facility') return `${facilityRef?.name} · rack and position Unknown`; + if (scope === 'RackMembership') return `${rackRef?.name} · position Unknown (no reserved units)`; + if (scope === 'NonRackUnitMount') return `${rackRef?.name} · mount ${mount}`; + if (position === undefined) return 'Placement Unknown'; const units = height > 1 ? `U${position}–U${position + height - 1}` : `U${position}`; - return `${facility} · ${rack} · ${units} ${face}`; + return `${facility ?? 'Facility via rack'} · ${rack ?? rackRef?.name} · ${units} ${face}`; } export function modelLabel(identity: { manufacturer?: string; model: string }): string { return identity.manufacturer ? `${identity.manufacturer} ${identity.model}` : identity.model; } -// The newest Device bound to a slot is the one currently recorded there. +// Multiple historical registrations cannot establish the active binding. export function currentDevice(slot: InventorySlot): RawDevice | undefined { - return slot.devices.at(-1); + return slot.devices.length === 1 ? slot.devices[0] : undefined; } diff --git a/ui/provider/src/lib/api.ts b/ui/provider/src/lib/api.ts index 5937bda1..9e8cf42f 100644 --- a/ui/provider/src/lib/api.ts +++ b/ui/provider/src/lib/api.ts @@ -1,5 +1,6 @@ import { fixtureClasses, fixtureCapacities, fixtureDeviceClaims, fixtureDevices, fixtureProfiles } from './fixtures'; import { toInventory, type Inventory, type RawDeviceClaimList, type RawDeviceList } from '../inventory'; +import type { List, PhysicalRecord } from '../../../shared/fleet-api'; import { toMachineCapacity, toMachineClass, @@ -261,11 +262,26 @@ export function useDeleteMachineClass(): UseMutationResult { if (USE_FIXTURES) return toInventory(fixtureDeviceClaims, fixtureDevices); - const [claims, devices] = await Promise.all([ - proxyFetch(PROVIDER_PROJECT, `${INVENTORY_API}/deviceclaims?limit=500`), - proxyFetch(PROVIDER_PROJECT, `${INVENTORY_API}/devices?limit=500`), + const [claims, devices, ...physical] = await Promise.all([ + fetchInventoryCollection[number]>('deviceclaims'), + fetchInventoryCollection[number]>('devices'), + ...['facilities', 'racks', 'cables', 'powerfeeds'].map((kind) => fetchInventoryCollection(kind)), ]); - return toInventory(claims.items ?? [], devices.items ?? []); + return toInventory(claims, devices, physical.flat()); +} + +export async function fetchInventoryCollection(plural: string): Promise { + const items: T[] = []; + const seen = new Set(); + let continuation = ''; + do { + const page = await proxyFetch & { metadata?: { continue?: string } }>(PROVIDER_PROJECT, `${INVENTORY_API}/${plural}?limit=500${continuation ? `&continue=${encodeURIComponent(continuation)}` : ''}`); + items.push(...(page.items ?? [])); + continuation = page.metadata?.continue ?? ''; + if (continuation && seen.has(continuation)) throw new ApiError(502, 'Inventory pagination repeated; completeness Unknown'); + seen.add(continuation); + } while (continuation); + return items; } export function useInventory(): UseQueryResult { diff --git a/ui/provider/src/lib/inventory-api.test.ts b/ui/provider/src/lib/inventory-api.test.ts new file mode 100644 index 00000000..16e68802 --- /dev/null +++ b/ui/provider/src/lib/inventory-api.test.ts @@ -0,0 +1,33 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { fetchInventory, fetchInventoryCollection } from './api'; + +afterEach(() => vi.unstubAllGlobals()); + +function response(data: unknown, status = 200) { + return { ok: status === 200, status, json: async () => ({ data }) }; +} + +describe('physical inventory reads', () => { + it('reads every page with the project proxy and only GET', async () => { + const fetch = vi.fn().mockResolvedValueOnce(response({ items: [{ id: 1 }], metadata: { continue: 'opaque+/=' } })).mockResolvedValueOnce(response({ items: [{ id: 2 }] })); + vi.stubGlobal('fetch', fetch); + expect(await fetchInventoryCollection('racks')).toEqual([{ id: 1 }, { id: 2 }]); + expect(fetch.mock.calls[1][0]).toContain('continue=opaque%2B%2F%3D'); + expect(fetch.mock.calls[0][0]).toContain('/projects/datum-cloud/control-plane/'); + expect(fetch.mock.calls.every((call) => call[1].method === 'GET')).toBe(true); + }); + + it('does not treat a pagination cycle as complete', async () => { + vi.stubGlobal('fetch', vi.fn().mockResolvedValue(response({ items: [], metadata: { continue: 'repeat' } }))); + await expect(fetchInventoryCollection('racks')).rejects.toThrow('completeness Unknown'); + }); + + it('requires all six collections and propagates restricted errors', async () => { + const fetch = vi.fn().mockResolvedValue(response({ items: [] })); + vi.stubGlobal('fetch', fetch); + expect((await fetchInventory()).physical).toEqual([]); + expect(fetch).toHaveBeenCalledTimes(6); + fetch.mockResolvedValue(response(undefined, 403)); + await expect(fetchInventory()).rejects.toMatchObject({ status: 403 }); + }); +}); diff --git a/ui/provider/src/pages/device-claim-detail.tsx b/ui/provider/src/pages/device-claim-detail.tsx index 465c667e..bd00eda0 100644 --- a/ui/provider/src/pages/device-claim-detail.tsx +++ b/ui/provider/src/pages/device-claim-detail.tsx @@ -1,4 +1,5 @@ import { FleetPage } from '../components/fleet-page'; +import { endpointLabel } from '../components/physical-inventory'; import { ErrorOrRestrictedState, LoadingState } from '../components/states'; import { StatusBadge } from '../components/status-badge'; import { PROVIDER_PROJECT, useInventory } from '../lib/api'; @@ -35,6 +36,7 @@ function ProvenanceFields({ provenance }: { provenance: Provenance }) { {provenance.recordedBy} {provenance.recordedAt} {provenance.method} + {provenance.source && {provenance.source.system}/{provenance.source.type}/{provenance.source.id} · mapping {provenance.source.mappingRevision} · observed {provenance.source.observedAt} · verification Unknown} {provenance.reference && (
{provenance.reference} @@ -48,14 +50,21 @@ function DeviceSection({ device, current }: { device: RawDevice; current: boolea const { identity, bmc, interfaces = [], unmappedMACAddresses = [] } = device.spec; return (
- {!current && Earlier hardware for this slot} + {!current && Historical binding; active placement Unknown}
{modelLabel(identity)} + {device.spec.displayName ?? device.metadata.name} + {device.spec.modelShape?.heightUnits ?? 'Unknown'} U {identity.serial ?? '—'} {identity.systemUUID ?? '—'} {bmc?.endpoint ?? '—'} {device.spec.claimRef.name} + {device.spec.assetTag ?? 'Unknown'} + {device.spec.providerHostRef ? `${device.spec.providerHostRef.system}/${device.spec.providerHostRef.id}` : 'Unknown'}
+ {device.spec.components?.map((component) => {component.name} ({component.type}) · {component.id} · connector {component.connector ?? 'Unknown'})} + {device.spec.internalMappings?.map((mapping) => Internal path: {mapping.from.componentID}:{mapping.from.position} → {mapping.to.componentID}:{mapping.to.position})} + {device.spec.serviceAssociations?.map((association) => Demarcation {association.componentID} → {association.serviceRef.system}/{association.serviceRef.type}/{association.serviceRef.id})} {interfaces.length > 0 && (
Interfaces @@ -117,7 +126,7 @@ export default function DeviceClaimDetail() { {slot.claim.spec.expectedIdentity.serial ?? '—'} {slot.claim.metadata.namespace ?? '—'} - {current ? current.metadata.name : Not registered} + {current ? current.metadata.name : {slot.devices.length > 1 ? 'Multiple records; active binding Unknown' : 'Not registered'}}
{(slot.claim.spec.ports ?? []).length > 0 && ( @@ -137,6 +146,10 @@ export default function DeviceClaimDetail() { {[...slot.devices].reverse().map((device) => ( ))} +
+ {data?.physical.filter((record) => record.kind === 'Cable' && record.metadata.namespace === slot.claim.metadata.namespace && record.spec.lanes?.some((lane) => slot.devices.some((device) => lane.a.deviceRef?.name === device.metadata.name || lane.b.deviceRef?.name === device.metadata.name))).map((cable) =>
{cable.spec.displayName} · verification Unknown{cable.spec.lanes?.map((lane) => {endpointLabel(lane.a)} ↔ {endpointLabel(lane.b)})}
)} + No displayed path proves an uncabled or free termination. +
)} diff --git a/ui/provider/src/pages/device-inventory-list.tsx b/ui/provider/src/pages/device-inventory-list.tsx index ecaad7a4..c17b2655 100644 --- a/ui/provider/src/pages/device-inventory-list.tsx +++ b/ui/provider/src/pages/device-inventory-list.tsx @@ -1,4 +1,5 @@ import { FleetPage } from '../components/fleet-page'; +import { PhysicalInventory } from '../components/physical-inventory'; import { InventoryTable } from '../components/inventory-table'; import { ErrorOrRestrictedState, LoadingState } from '../components/states'; import { PROVIDER_PROJECT, useInventory } from '../lib/api'; @@ -14,10 +15,11 @@ export default function DeviceInventoryList() { const { slug } = useParams(); const base = `/plugins/${slug}`; const { data, isLoading, error, refetch } = useInventory(); - const isEmpty = !isLoading && !error && data && data.slots.length === 0 && data.unboundDevices.length === 0; + const isEmpty = !isLoading && !error && data && data.slots.length === 0 && data.unboundDevices.length === 0 && data.physical.length === 0; return ( + {!isLoading && !error && data && } {isLoading && } {!isLoading && error && ( diff --git a/ui/provider/src/pages/device-inventory.test.tsx b/ui/provider/src/pages/device-inventory.test.tsx index 7745ad74..2e018184 100644 --- a/ui/provider/src/pages/device-inventory.test.tsx +++ b/ui/provider/src/pages/device-inventory.test.tsx @@ -112,7 +112,7 @@ describe('DeviceClaimDetail', () => { expect(screen.getByTestId('fleet-plugin-claim-missing')).toBeInTheDocument(); }); - it('lists earlier hardware after the current Device', () => { + it('preserves history without guessing an active replacement', () => { const replacement = { ...fixtureDevices[0], metadata: { ...fixtureDevices[0].metadata, name: 'rack-01-u12-synthetic-0002' }, @@ -120,7 +120,7 @@ describe('DeviceClaimDetail', () => { }; mockInventory({ data: toInventory(fixtureDeviceClaims, [fixtureDevices[0], replacement]) }); renderAt('/plugins/metal-datumapis-com/inventory/default/rack-01-u12'); - expect(within(screen.getByTestId('fleet-plugin-claim')).getByText('rack-01-u12-synthetic-0002')).toBeInTheDocument(); - expect(within(screen.getByTestId('fleet-plugin-device-rack-01-u12-synthetic-0001')).getByText('Earlier hardware for this slot')).toBeInTheDocument(); + expect(within(screen.getByTestId('fleet-plugin-claim')).getByText('Multiple records; active binding Unknown')).toBeInTheDocument(); + expect(within(screen.getByTestId('fleet-plugin-device-rack-01-u12-synthetic-0001')).getByText('Historical binding; active placement Unknown')).toBeInTheDocument(); }); }); diff --git a/ui/shared/fleet-api.ts b/ui/shared/fleet-api.ts index 935c2d5f..3cbf6f06 100644 --- a/ui/shared/fleet-api.ts +++ b/ui/shared/fleet-api.ts @@ -237,10 +237,11 @@ export const INVENTORY_API_GROUP = 'fleet.datumapis.com'; export const INVENTORY_API_VERSION = 'v1alpha1'; export interface Provenance { - method: 'Manual'; + method: 'Manual' | 'NetBoxImport'; recordedBy: string; recordedAt: string; reference?: string; + source?: ExternalReference & { snapshotDigest: string; mappingRevision: string; observedAt: string }; } export interface PortPeer { @@ -255,7 +256,10 @@ export interface DeviceClaim { spec: { provenance: Provenance; expectedIdentity: { manufacturer?: string; model: string; serial?: string }; - placement: { facility: string; rack: string; position: number; height?: number; face: 'front' | 'rear' }; + lifecycle?: 'Installation'; + displayName?: string; + cableRefs?: LocalReference[]; + placement: { facility?: string; rack?: string; position?: number; height?: number; face?: 'front' | 'rear'; scope?: 'Facility' | 'RackMembership' | 'RackUnits' | 'NonRackUnitMount'; facilityRef?: LocalReference; rackRef?: LocalReference; mount?: string }; ports?: { name: string; type?: string; speedMbps?: number; expectedPeer?: PortPeer }[]; }; } @@ -267,9 +271,51 @@ export interface Device { spec: { claimRef: LocalReference; provenance: Provenance; - identity: { manufacturer?: string; model: string; serial?: string; systemUUID?: string }; + identity: { manufacturer?: string; model: string; serial?: string; systemUUID?: string; sourceIdentity?: ExternalReference }; + assetTag?: string; + displayName?: string; + modelShape?: { heightUnits?: number; fullDepth?: boolean }; + providerHostRef?: ExternalReference; + topologyAuthority?: 'Cable'; + components?: PhysicalComponent[]; + internalMappings?: { from: ComponentPosition; to: ComponentPosition }[]; + serviceAssociations?: { serviceRef: ExternalReference; componentID: string }[]; bmc?: { endpoint: string }; interfaces?: { name: string; macAddress?: string; peer?: PortPeer }[]; unmappedMACAddresses?: string[]; }; } + +export interface ExternalReference { system: string; type: string; id: string } +export interface ComponentPosition { componentID: string; position: number } +export interface PhysicalComponent { + id: string; + name: string; + type: 'NetworkPort' | 'PowerInlet' | 'PowerOutlet' | 'ConsolePort' | 'ConsoleServerPort' | 'FrontPort' | 'RearPort' | 'Module' | 'InventoryItem' | 'DeviceBay'; + connector?: string; + positions?: number; + serial?: string; + assetTag?: string; + sourceRef?: ExternalReference; +} +export interface CableEndpoint extends ComponentPosition { + deviceRef?: LocalReference; + powerFeedRef?: LocalReference; +} +export interface PhysicalRecord { + metadata: ObjectMeta; + kind: 'Facility' | 'Rack' | 'Cable' | 'PowerFeed'; + spec: { + displayName: string; + provenance: Provenance; + facilityRef?: LocalReference; + rackRef?: LocalReference; + locationRef?: LocalReference; + heightUnits?: number; + medium?: string; + lanes?: { id: string; a: CableEndpoint; b: CableEndpoint }[]; + supply?: { type: string; voltageV?: number; currentA?: number; phase?: string }; + terminations?: PhysicalComponent[]; + upstreamSources?: ExternalReference[]; + }; +} From 180e438006e0adae7a74511dfeb605a9ae9d0758 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Fri, 20 Nov 2026 13:34:45 -0600 Subject: [PATCH 015/518] fix(manager): drain in-flight reconciles before project departure --- internal/manager/projects.go | 19 ++++++ internal/manager/projects_test.go | 97 +++++++++++++++++++++++++++++++ internal/manager/reconcilers.go | 6 +- 3 files changed, 120 insertions(+), 2 deletions(-) create mode 100644 internal/manager/projects_test.go diff --git a/internal/manager/projects.go b/internal/manager/projects.go index aa67f387..d9948e06 100644 --- a/internal/manager/projects.go +++ b/internal/manager/projects.go @@ -41,6 +41,24 @@ type ProjectRuntime struct { Mappers Mappers Machine *LifecycleOwner Installation *LifecycleOwner + + reconcileMu sync.RWMutex + stopped bool +} + +func (r *ProjectRuntime) acquire() bool { + r.reconcileMu.RLock() + if r.stopped { + r.reconcileMu.RUnlock() + return false + } + return true +} + +func (r *ProjectRuntime) stop() { + r.reconcileMu.Lock() + defer r.reconcileMu.Unlock() + r.stopped = true } // ProjectResolver resolves an engaged cluster name to its immutable project @@ -125,6 +143,7 @@ func (p *Projects) Engage(ctx context.Context, name multicluster.ClusterName, cl } func (p *Projects) unbind(name multicluster.ClusterName, runtime *ProjectRuntime) { + runtime.stop() p.mu.Lock() defer p.mu.Unlock() if p.byCluster[name] != runtime { diff --git a/internal/manager/projects_test.go b/internal/manager/projects_test.go new file mode 100644 index 00000000..d16e73ba --- /dev/null +++ b/internal/manager/projects_test.go @@ -0,0 +1,97 @@ +package manager + +import ( + "context" + "sync" + "sync/atomic" + "testing" + "time" + + "sigs.k8s.io/multicluster-runtime/pkg/multicluster" + + "go.datum.net/fleet/internal/controller" +) + +func TestProjectDepartureDrainsReconciliation(t *testing.T) { + for _, routed := range []bool{false, true} { + name := "direct" + if routed { + name = "dependency route" + } + t.Run(name, func(t *testing.T) { + identity := controller.ProjectIdentity{AuthorityID: testAuthority, RouteName: "east", UID: "east-project"} + consumer := newConsumer(t, "east", mcMachine("m", "machine", "general")) + started, release := make(chan struct{}), make(chan struct{}) + var releaseOnce sync.Once + unblock := func() { releaseOnce.Do(func() { close(release) }) } + defer unblock() + var calls atomic.Int32 + owner := NewLifecycleOwner(HandlerFunc(func(context.Context, ProjectRequest) Outcome { + if calls.Add(1) == 1 { + close(started) + <-release + } + return Outcome{} + }), BlockedHandler, nil) + runtime := &ProjectRuntime{ + Binding: ProjectBinding{ClusterName: "east", Project: identity}, + Verifier: ProjectVerifierFunc(func(context.Context, controller.ProjectIdentity) error { return nil }), + Mappers: Mappers{Reader: consumer.Client, Project: identity, ClusterName: "east"}, + Machine: owner, + } + projects := newProjects(nil, nil, nil) + projects.byCluster["east"] = runtime + projects.byProject[projectKey{identity.AuthorityID, identity.UID}] = multicluster.ClusterName("east") + selectOwner := func(runtime *ProjectRuntime) *LifecycleOwner { return runtime.Machine } + reconcile := func() error { + if routed { + _, err := (ClusterRouteReconciler{Projects: projects, Owner: selectOwner}).Reconcile(context.Background(), RouteRequest{ClusterName: "east", AuthorityID: identity.AuthorityID, ProjectUID: identity.UID, Kind: RouteProfile, Name: "general", UID: "profile", Deleted: true}) + return err + } + _, err := (ClusterProjectReconciler{Projects: projects, Owner: selectOwner}).Reconcile(context.Background(), ProjectRequest{ClusterName: "east", AuthorityID: identity.AuthorityID, ProjectUID: identity.UID, Namespace: "default", Name: "m", UID: "machine"}) + return err + } + done := make(chan error, 1) + go func() { done <- reconcile() }() + select { + case <-started: + case <-time.After(5 * time.Second): + t.Fatal("handler did not start") + } + departed := make(chan struct{}) + go func() { projects.unbind("east", runtime); close(departed) }() + select { + case <-departed: + t.Fatal("departure completed while a handler could still write") + case <-time.After(50 * time.Millisecond): + } + if projects.Get("east") != runtime { + t.Fatal("runtime removed before reconciliation drained") + } + unblock() + select { + case err := <-done: + if err != nil { + t.Fatal(err) + } + case <-time.After(5 * time.Second): + t.Fatal("reconciliation did not drain") + } + select { + case <-departed: + case <-time.After(5 * time.Second): + t.Fatal("departure did not finish") + } + if projects.Get("east") != nil || projects.ForProject(identity.AuthorityID, identity.UID) != nil { + t.Fatal("departed runtime still registered") + } + if err := reconcile(); err != nil || calls.Load() != 1 { + t.Fatalf("post-departure reconcile: error=%v calls=%d", err, calls.Load()) + } + if runtime.acquire() { + runtime.reconcileMu.RUnlock() + t.Fatal("a previously resolved runtime admitted work after departure") + } + }) + } +} diff --git a/internal/manager/reconcilers.go b/internal/manager/reconcilers.go index efe5d109..c4816ae3 100644 --- a/internal/manager/reconcilers.go +++ b/internal/manager/reconcilers.go @@ -97,9 +97,10 @@ func (r ClusterProjectReconciler) Reconcile(ctx context.Context, request Project return reconcile.Result{}, ErrEventWiringUnavailable } runtime := r.Projects.For(request) - if runtime == nil { + if runtime == nil || !runtime.acquire() { return reconcile.Result{}, nil } + defer runtime.reconcileMu.RUnlock() return ProjectReconciler{Project: runtime.Binding.Project, Handler: r.Owner(runtime), Verifier: runtime.Verifier}.Reconcile(ctx, request) } @@ -115,8 +116,9 @@ func (r ClusterRouteReconciler) Reconcile(ctx context.Context, request RouteRequ return reconcile.Result{}, ErrEventWiringUnavailable } runtime := r.Projects.Get(request.ClusterName) - if runtime == nil { + if runtime == nil || !runtime.acquire() { return reconcile.Result{}, nil } + defer runtime.reconcileMu.RUnlock() return RouteReconciler{Project: runtime.Binding.Project, Verifier: runtime.Verifier, Mappers: runtime.Mappers, Handler: r.Owner(runtime)}.Reconcile(ctx, request) } From 8007368aa787c6017e0b4f560b43250adaf79bdf Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Fri, 20 Nov 2026 13:34:45 -0600 Subject: [PATCH 016/518] fix(inventory): make manual migration the primary workflow --- docs/development/README.md | 20 ++- docs/operations/README.md | 2 +- docs/operations/netbox-physical-import.md | 50 ++++--- docs/operations/physical-inventory-staging.md | 127 ++++++++++++++++++ docs/operations/physical-inventory.md | 79 +++++++++-- docs/proposals/fleet-management/inventory.md | 6 +- hack/netbox_inventory.py | 12 +- hack/testdata/physical/manual.yaml | 94 +++++++++++++ .../api/inventory/v1alpha1/physical_test.go | 58 ++++++++ ui/provider/README.md | 6 +- .../components/physical-inventory.test.tsx | 22 ++- .../src/components/physical-inventory.tsx | 7 +- 12 files changed, 438 insertions(+), 45 deletions(-) create mode 100644 docs/operations/physical-inventory-staging.md create mode 100644 hack/testdata/physical/manual.yaml diff --git a/docs/development/README.md b/docs/development/README.md index e8900d73..6bf1c59a 100644 --- a/docs/development/README.md +++ b/docs/development/README.md @@ -184,7 +184,15 @@ service catalog's consumer provider (`internal/projectdiscovery`). There is no consumer set. It does not release custody, call a provider, delete records, or rewrite status, including for a project with active custody. Its deadlines and queued events are dropped, and re-engagement resumes from the - retained private records. + retained private records. Unbinding drains direct and dependency-route + reconciliations that already acquired the runtime before removing it from the + registry; a retained runtime pointer cannot start work after that barrier. + A blocked in-flight handler therefore delays completed departure rather than + falsely reporting it. This fixes an inherited race where informer removal and + registry removal could finish while a handler could still write. It does not + roll back effects already admitted before departure. Regression tests block a + handler explicitly and assert the barrier, in addition to the active-custody + no-write/no-release test. - **Observational discovery.** The provider declares no managed resources, teardowns, or suspend hooks, so it adds no ServiceConsumer finalizer. Its discovery clients refuse every write. The library would otherwise patch @@ -720,12 +728,14 @@ No metal role grants inventory access. The staff portal plugin's read-only Inventory tab pages through all six kinds, shows physical relationships and components, and can inspect a private import report locally. Multiple historical bindings remain ambiguous rather than being -resolved by edit time. Python's standard-library `hack/netbox_inventory.py` -exports sanitized GET-only NetBox snapshots and prepares an offline create-only -handoff to the existing Flux writer. Unit tests run API-server validation offline, +resolved by edit time. The primary workflow is [manual entry and review](../operations/physical-inventory.md#manually-record-a-small-installation) +through the existing Flux writer, with no NetBox dependency. The optional, +operator-invoked standard-library `hack/netbox_inventory.py` reads GET-only snapshots +and generates offline review candidates; it never applies, schedules, synchronizes, +deletes or changes Git. Unit tests run API-server validation offline, check IAM and exercise pagination, source conflicts, omissions and interrupted imports. See [safe NetBox evaluation](../operations/netbox-physical-import.md). -No live source coverage, deployed revision, physical verification, concurrent +No live source coverage, deployment of this physical extension, physical verification, concurrent reservation, deletion safety, adoption or new hardware-effect path is established. ## Build, test, and run diff --git a/docs/operations/README.md b/docs/operations/README.md index 1f1fdf99..c229fb0d 100644 --- a/docs/operations/README.md +++ b/docs/operations/README.md @@ -18,7 +18,7 @@ integrations. Real provider support and live Milo acceptance tests are incomplet | Drive the same pipeline through Redfish instead of libvirt | [Redfish-mode acceptance](redfish-lab.md) (`task multiplane:redfish-acceptance`) | Redfish executor discovery, one-time PXE/disk boot overrides, power, lost-response recovery and a booted wipe cleanup, against the unmodified DMTF Redfish Interface Emulator with a lab-only libvirt adapter and two persistent lab VMs; synthetic credentials and networking; not physical BMC or hardware qualification | | Publish physical-side DHCP reservations for network boot | [Boot network](boot-network.md) | Per-asset BMC endpoints and provisioning attachments, a reservation feed 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 attributable provenance and immutable identity and binding, shown read-only in the staff portal; no capacity or hardware effect; unit tested | -| Review and import NetBox's physical side | [Safe physical snapshot and GitOps handoff](netbox-physical-import.md) | Six physical kinds, typed components and relationships, per-record coverage reports and additive handoff to the existing writer; no live import, readiness or provisioning | +| Optionally compare an existing NetBox source | [Operator-run snapshot and candidate review](netbox-physical-import.md) | Optional local review aids only; manual inventory needs no NetBox, automated migration or live import | | Render deployment bundles and supply environment inputs | [Deployment manifests](../../config/README.md) | Packaging and security boundaries, not runtime readiness | | Run the manager across consuming projects | [Project discovery](../../config/README.md#project-discovery) | Discovery, per-project isolation, departure, role bindings, and readiness | | Exercise Milo-routed synthetic staging | [Synthetic staging configuration](../../config/README.md#environment-owned-inputs) | Restricted synthetic publication and lifecycle behavior, not production authority | diff --git a/docs/operations/netbox-physical-import.md b/docs/operations/netbox-physical-import.md index 7cac4a7c..150e0401 100644 --- a/docs/operations/netbox-physical-import.md +++ b/docs/operations/netbox-physical-import.md @@ -1,11 +1,19 @@ -# Evaluate NetBox physical inventory safely +# Optional NetBox review aids for manual inventory [Physical inventory](physical-inventory.md) · [Inventory proposal](../proposals/fleet-management/inventory.md) · [Detailed proposed contracts](../proposals/fleet-management/inventory-reference.md) -This milestone provides six provider-project inventory kinds, read-only staff -browsing, a GET-only NetBox snapshot command, and an **offline, create-only GitOps -handoff**. It does not apply anything to Fleet or NetBox. It is not a verification, -reservation, adoption, enrollment, or provisioning controller. +Start with [manual entry and operator review](physical-inventory.md#manually-record-a-small-installation). +Physical inventory needs neither NetBox access nor a bulk importer. Operators +write and review records individually; Flux remains the sole staging writer. + +This guide covers **optional, explicitly invoked review aids**: a GET-only snapshot +command and offline candidate generation. They help compare an existing source +when an operator chooses to use it; they are not an automated migration. There +are no scheduled imports, discovery or sync controllers, background NetBox updates, +auto-apply or auto-delete. Neither command applies anything to Fleet or NetBox. +The retained `--handoff` option writes candidate files for human review only; it +does not hand execution to Flux, change Git, or transfer ownership. No verification, +reservation, adoption, enrollment, or provisioning controller is included. ## What exists and what remains unknown @@ -33,7 +41,7 @@ remain Unknown. Existing editor delete permissions are not a safe retirement API - Existing long-lived slot claims keep their names, text placement, ports, and historical Device bindings. Existing `Device.spec.identity` and `claimRef` remain immutable. MachineCapacity and its `deviceRef` are not modified. -- New imported claims use `lifecycle: Installation` and typed placement. This +- New manually entered or optionally generated claims use `lifecycle: Installation` and typed placement. This mode cannot be added to a legacy slot; an installation's placement is immutable. This is an observational installation record, **not** a reservation or an accepted plan. Moving an existing asset remains blocked on the proposal's @@ -107,7 +115,7 @@ physical-field allowlist and excludes URLs, comments, custom fields and config contexts. This intentionally is **not a lossless NetBox backup**. Exports still contain private asset identities, serials and topology and must stay outside Git. -## Start with the checked-in synthetic example +## Optionally compare the checked-in synthetic example Python 3 uses only the standard library. No provider SDK or cluster access is needed. Output directories must not already exist; files are mode 0600 inside @@ -121,7 +129,9 @@ python3 hack/netbox_inventory.py plan \ --output /private/tmp/fleet-physical-report-example ``` -Only `report.json` is emitted by default. Inspect every unresolved/unsupported +Only `report.json` is emitted by default. The historical `imported` classification +means an offline candidate was representable, **not that any record was applied**. +Inspect every unresolved/unsupported row; the example intentionally leaves a room mapping unresolved. Staff can open the report with the Inventory tab's local file picker; its contents are not uploaded. The portal shows restricted/loading/empty states, paginated collections, @@ -144,7 +154,11 @@ not bypass collection errors or target conflicts. The handoff emits candidate objects and a receipt containing the exact target plus source, mapping, Fleet snapshot and candidate digests. Nothing invokes kubectl apply or writes Git. -## Prepare a private real-data review +## Optional private source comparison + +Skip this entire section for manual entry. No NetBox credentials or parity audit +are required to evaluate the manual physical-inventory features. Only perform a +source comparison when separately requested and authorized by the operator. 1. Use existing read credentials: `NETBOX_TOKEN`, otherwise `NETBOX_TOKEN_FILE` (default `~/.config/netbox/token`). Never paste a token into arguments, logs, @@ -211,8 +225,11 @@ this feature does not modify them or their kubeconfig references. On 2026-11-20, read-only GitHub checks found both infra staging OCI sources configured for `v0.0.0-feat-manual-inventory-records`; the corresponding Fleet branch head was `42086bbe2cf05f5d09362fbc777e514907d64462`. This implementation is stacked there, -including the dependent PXE/runtime code. **Configured tag is not an observed -deployed revision.** No cluster rollout or live import was performed. +including the dependent PXE/runtime code. **That original configured-tag check +was not a deployed-revision observation.** A subsequent read-only staging API +check is recorded in the [staging baseline and acceptance checklist](physical-inventory-staging.md#read-only-baseline-observed-on-november-20-2026). +It observed the manual-inventory base, not this physical extension. No cluster +rollout or live import was performed. The documented environment/token-file paths did not provide authorized NetBox access in this implementation checkout. No live inventory audit was performed; @@ -221,12 +238,11 @@ unvalidated. Source interpretation comes from the pinned infra `d9198940a499be4e744ee0564cf3dc0b3bfcee34` loaders and site-build documents, as recorded in the [source evidence appendix](../proposals/fleet-management/inventory-reference.md#source-evidence-and-limits). -Before live evaluation, establish a private source audit, resolve required mappings, -render/install the six-kind schema in an explicitly approved environment, and -confirm authorized staff can browse while consumers cannot. Compare counts and -every classified row, test repeated and interrupted handoffs, and confirm original -Device/claim/Capacity identities remain unchanged. None of this establishes -physical qualification or safe capacity release. +For manual staging evaluation, use the [acceptance and rollback checklist](physical-inventory-staging.md). +If an operator separately chooses the optional source comparison, establish its +private audit and mappings, compare every classified row, and test repeated and +interrupted candidate generation. No live NetBox access means no claim of source +parity, not a blocker for manually entering and reviewing physical records. ```sh python3 -m unittest discover -s hack -p test_netbox_inventory.py diff --git a/docs/operations/physical-inventory-staging.md b/docs/operations/physical-inventory-staging.md new file mode 100644 index 00000000..ae80f318 --- /dev/null +++ b/docs/operations/physical-inventory-staging.md @@ -0,0 +1,127 @@ +# Evaluate manual physical inventory in staging + +[Manual entry and review](physical-inventory.md#manually-record-a-small-installation) · +[Optional source comparison](netbox-physical-import.md) + +This checklist is for an explicitly approved staging evaluation after independent +adversarial review. It is not approval to deploy or evidence of physical readiness. +No live imports, deployment, source-tag changes, hardware actions, or inventory +writes were performed during the implementation checks below. + +## Read-only baseline observed on November 20, 2026 + +The physical-inventory PR is stacked on `feat/manual-inventory-records` at +`42086bbe2cf05f5d09362fbc777e514907d64462`. Infrastructure configuration was read +at `3bde916629c7b6c49a6820bc40c2546bbf2afdc1`. Preserve that dependent base; +do not retarget the PR or mistake a new artifact publication for deployment. + +Read-only staging API queries on that date found: + +- Both `fleet-kustomize` and `fleet-inventory-kustomize` configured for + `v0.0.0-feat-manual-inventory-records`, with artifact digest + `sha256:45dfd12971b44a92d3d078007cfd41dcb23f4d278d17e3c5ea8f02c65d3f2fdc`. +- `fleet-milo-configuration` reporting Ready with that exact applied artifact. +- `fleet-provider-inventory` reporting Ready at the infrastructure revision above, + with `prune: false`, `deletionPolicy: Orphan`, and the private + `apps/fleet-system/staging/provider-inventory` source. +- Manager and provider/consumer UI Deployments referencing the manual-inventory + build ending `20261120-165214`, with one manager and two replicas of each UI ready. + +The three DeviceClaims and one Device in that applied Git source passed offline +creation and unchanged-update validation against the proposed six-kind schemas. +The source files were handled privately outside Git; no real identities were +added to public fixtures. Existing identity and claim-binding immutability also +have negative regression tests. This is schema compatibility, not a live-object +or hardware audit: the management-cluster project API route did not expose the +provider project, so direct live provider-record comparison remains an operator +acceptance step. No production project context was used as a substitute. + +## Acceptance gates for an authorized operator + +1. Require independent adversarial sign-off and successful CI for the exact PR + head. In particular, run both formerly optional manager envtest tests with real + Kubernetes binaries, not skips. Retain the reviewed head and artifact digests. +2. Re-read staging source and applied revisions, the provider project/namespace, + existing DeviceClaim/Device identities and bindings, and MachineCapacity + references through the established authorized project route. Keep a private + before-state. Stop if the baseline changed or the intended target is unclear. +3. Separately approve and review the infrastructure change that selects the exact + reviewed build. Preserve Flux ownership, provider-project placement, and + non-pruning inventory reconciliation. Apply the additive CRDs and IAM before + introducing new record kinds; retain old claims, Devices and capacity unchanged. +4. Manually prepare a small, separately approved cohort using the + [synthetic six-kind example](../../hack/testdata/physical/manual.yaml) as a shape + reference. Review premises, references and every cable endpoint. For new + records use `Installation`, typed components and Cable-only expected topology. + Include facility-only or rack-membership placement; missing units, electrical + budgets, verification and readiness must remain Unknown. Do not register an + asset without a genuine identity or manufacture a serial from a provider ID. +5. Review and merge individual records into the private provider-inventory Git + source; let Flux be the only API writer. No NetBox access, bulk conversion, + discovery, sync, or scheduled import is needed. No capacity, billing, IPAM, + routing, provisioning, hardware, customer-release or status changes are allowed. +6. Verify authorized staff can browse all six kinds, typed components, relationships, + partial placement and historical bindings. Confirm consumer identities cannot + read them and inventory roles cannot write status. Test denied and missing + references without treating them as empty or ready. Verify before/after immutable + bindings and capacity references privately, including across reconciliation retries. +7. Stop on mismatches, unknown execution or authorization failures. Record these as + unknown/failed acceptance, not readiness. Even successful acceptance establishes + only manual recordkeeping and restricted browsing, not qualification or eligibility. + +## Rollback without losing inventory + +- Record the last known-good manager/UI artifacts and Git revisions before the + approved rollout. Revert an unsuccessful application change through its existing + infrastructure GitOps source; do not patch a competing live writer. +- Do **not** blindly downgrade the six-kind schema to the two-kind base after new + data exists. Retain additive CRDs, typed fields and records until a separate + compatibility review proves any schema rollback preserves them. Older software + may not display the new records; missing UI visibility is not permission to delete. +- Keep `prune: false` and `deletionPolicy: Orphan`. Reverting an additive Git entry + alone does not delete its live object. Never delete/recreate an occupied Device, + rewrite its identity/claimRef, or release capacity to make rollback appear clean. +- If reconciliation is interrupted, inspect actual records and Flux state, retain + the before-state and unresolved work, and reconcile only the reviewed Git intent. + No automatic cleanup, readiness assertion or ownership handover follows a rollback. + +## Local validation + +Implementation checks passed `go test ./...`, `go test -race ./...` and `go vet +./...` with Kubernetes 1.37.0 envtest assets installed. Both named envtest cases +also passed an explicit uncached race run without skips. The departure regression +and existing active-custody test passed 50 repetitions under the race detector. +The new blocked-handler reproducer failed on the original manager for both direct +and dependency-route reconciliation; that manager code was unchanged from the +stack's base. No safety assertion or timeout was relaxed. + +The manual six-kind fixture, private Git-source compatibility checks, 24 optional +review-aid tests, 58 provider UI tests, 44 consumer UI tests, both UI typechecks and +builds, Milo packaging, all five CI Kustomize renders, overlay isolation, standalone +render/source/preflight and mocked smoke checks, multi-plane harness, shellcheck, +local documentation links and whitespace checks passed. The local Docker daemon +was unavailable, so `hack/test-standalone-build-context.sh` could not complete; +no real disposable standalone smoke was run locally. Require the fresh CI build +context and standalone-smoke gates, not the previous head's results. UI builds +retain non-fatal dependency/Module Federation warnings. + +```sh +export KUBEBUILDER_ASSETS="$(go run sigs.k8s.io/controller-runtime/tools/setup-envtest@v0.25.2 use 1.37.0 -p path)" +go test ./... +go test -race ./... +go vet ./... +go test -race ./internal/manager -run 'TestProjectDepartureDrainsReconciliation|TestDisengageWithActiveCustody' -count=50 +go test -race ./internal/manager -run '^(TestManagerEndToEndAgainstSyntheticMilo|TestConsumerDiscoveryIgnoresOtherServicesAndBacksOff)$' -count=1 -v +python3 -m unittest discover -s hack -p test_netbox_inventory.py +pnpm --dir ui/provider typecheck +pnpm --dir ui/provider test +pnpm --dir ui/provider build +go run ./test/acceptance/milo/cmd validate --root . +kustomize build config/milo >/dev/null +bash hack/validate-doc-links.sh +git diff --check +``` + +There is no live NetBox parity claim. Optional snapshots and candidate conversion +remain solely to help an operator compare a source when separately requested; +they never apply records or change Git. Their synthetic tests are not a source audit. diff --git a/docs/operations/physical-inventory.md b/docs/operations/physical-inventory.md index 8e71398e..edab0661 100644 --- a/docs/operations/physical-inventory.md +++ b/docs/operations/physical-inventory.md @@ -11,14 +11,14 @@ take ownership of it. This package implements a minimal subset of the [inventory lifecycle and trust proposal (#63)](https://github.com/datum-cloud/fleet/pull/63). It now has six operator-written kinds in `fleet.datumapis.com/v1alpha1`. -The [NetBox physical import and migration guide](netbox-physical-import.md) -describes the additive physical schema, typed components, partial placement, -same-namespace relationships, import reconciliation and current limits. The -manual examples below preserve the original long-lived-slot representation: +The primary workflow is **manual entry, operator review, and explicit GitOps +ownership**. NetBox, bulk conversion, and a source reconciliation service are not +required. The [optional NetBox comparison guide](netbox-physical-import.md) +describes a separately invoked review aid, not an automated migration. | Kind | What it is | Writer | | --- | --- | --- | -| `DeviceClaim` | The installation plan for one slot: facility, rack, position and face, expected model, and expected ports with their expected cable peers. It is usually written before the hardware arrives, and the slot outlives any one Device. | The installation planner (an operator, for now) | +| `DeviceClaim` | An observational installation plan with expected model and known placement. New records use typed placement and Cable references; existing long-lived slots retain their legacy representation. | Installation planner, through the existing GitOps writer | | `Device` | One actual asset, bound to exactly one DeviceClaim when detected hardware is registered. It carries the serial and SMBIOS system UUID, the model, an optional BMC endpoint, interfaces, and provenance. | The registrar (an operator, for now) | | `Facility` / `Rack` | Explicit premises and rack definitions; membership is not free-capacity evidence. | Inventory operator through the environment's existing writer | | `Cable` / `PowerFeed` | Typed termination/lane topology and physical supply dependencies. | Inventory operator through the environment's existing writer | @@ -31,7 +31,7 @@ manual examples below preserve the original long-lived-slot representation: | Home | Milo. `config/milo` registers six CRDs, six ProtectedResources and two IAM roles. Management and synthetic-staging overlays install none of them. | | Staff portal | Read-only **Inventory** tab in the Bare Metal provider plugin (`ui/provider`): a claim list and a per-claim detail page. | | Tests | Unit tests run API-server schema, list-type and CEL validation offline for the six kinds and synthetic importer output. IAM tests check ProtectedResource and role shape and that no metal role grants inventory access. Plugin tests cover browse/detail, partial placement, reconciliation, restricted, pagination and empty states. | -| Controllers | None. Offline import and staff browsing read the records; no reconciler accepts plans, verifies hardware, or publishes eligibility. | +| Controllers | None for inventory. Staff browsing is read-only; no reconciler accepts plans, verifies hardware, discovers or synchronizes NetBox, or publishes eligibility. Flux applies only operator-reviewed Git records. | | Hardware qualification | None. Records hold operator-entered facts, not verified hardware state. | ## What registration does and does not do @@ -105,7 +105,65 @@ Use `unmappedMACAddresses` for MACs detected on the asset that cannot yet be attributed to a named port. Do not guess a mapping; #63 requires an authenticated, complete NIC mapping before any network path depends on it. -## Example +## Manually record a small installation + +1. Choose the provider project and namespace, and inspect its existing private + inventory source. In staging, `fleet-provider-inventory` reconciles + `apps/fleet-system/staging/provider-inventory` with `prune: false` and + `deletionPolicy: Orphan`. Flux is the sole API writer. Do not run a parallel + `kubectl apply`, importer, scheduled job, or discovery controller. +2. Enter the Facility and Rack facts you actually know. Record the operator and + time with `provenance.method: Manual`. Leave unknown dimensions absent. Rack + membership is not a reserved footprint or evidence of available space. +3. For a new installation, set `DeviceClaim.spec.lifecycle: Installation` and + typed placement. Use `Facility` when only the premises are known, + `RackMembership` when the rack is known, or explicitly reviewed `RackUnits` + with position, height and face. Never guess a rack position. Use a new record + only for a genuinely new installation, not to evade an existing immutable binding. +4. Register an actual Device against that claim only when its identity is known. + A manual Device requires a real serial or system UUID; if neither is known, + keep the plan and defer registration. Provider host IDs and asset tags are + not serials. Use typed `components` and `topologyAuthority: Cable`; put expected + connections in Cable records, not `ports.expectedPeer` or `interfaces.peer`. + Add PowerFeed facts without inferring usable power or independent redundancy. +5. Review every reference in the same namespace, component type and position, + cable endpoint, and potential duplicate against existing records. API validation + cannot enforce cross-object existence or exclusive endpoints. Preserve existing + names, Device identities, claim bindings and MachineCapacity references. +6. Review the private Git diff with another operator. It must contain no status, + capacity publication, hardware action, deletion or ownership transfer. Submit + only the individually approved records through the established Flux source. + After reconciliation, compare the intended records with read-only API and + staff views. An interrupted or failed reconciliation is not readiness. + +The [complete synthetic six-record example](../../hack/testdata/physical/manual.yaml) +shows this workflow without NetBox or credentials. It includes a partial rack +placement, typed network and power components, and one Cable from a PowerFeed to +the Device. It is a test fixture, not an automatically installed overlay. Copy +its shape into private configuration and replace synthetic facts only after +review. No physical status is asserted. + +Validate the synthetic example locally: + +```sh +go test ./internal/api/inventory/v1alpha1 -run TestManualInventoryRecordsPassAdmission -v +``` + +The same offline check accepts a private multi-document YAML file of existing +records. It validates creation and unchanged updates against the proposed schemas; +it does not read a cluster, check cross-object relationships, or write records. +Keep the file outside Git. Diagnostics report only kind, ordinal and error count. + +```sh +go test ./internal/api/inventory/v1alpha1 -run TestManualInventoryRecordsPassAdmission \ + -count=1 -v -args -inventory-records /private/tmp/reviewed-inventory.yaml +``` + +## Historical legacy example + +The following representation remains supported for existing long-lived slots. +It is **not the template for new records**. Do not convert existing claims in +place or copy their inline topology into a second Cable authority. ```yaml apiVersion: fleet.datumapis.com/v1alpha1 @@ -208,7 +266,7 @@ read. #63's ledger, trust, and enrollment protocol would still sit behind these records if adopted. **Compatibility decision:** legacy slots retain all historical bindings. New -imports use a distinct `Installation` lifecycle, but no automatic move or +typed records use a distinct `Installation` lifecycle, but no automatic move or replacement handover exists. Device identity and its original claimRef remain immutable. The [migration decisions](netbox-physical-import.md#compatibility-and-migration-decisions) explain why imports cannot delete/recreate or relabel legacy records to bypass this. @@ -216,8 +274,9 @@ explain why imports cannot delete/recreate or relabel legacy records to bypass t ## Applying the records `config/milo` installs the CRDs, ProtectedResources, and roles into Milo. Apply -claims and Devices into the provider project after those are established, -claims before the Devices that name them. Keep records with real serials, +operator-reviewed records through the provider project's established GitOps +source after those are established, claims before the Devices that name them. +Do not apply directly to staging; Flux remains its only writer. Keep records with real serials, UUIDs, MACs, endpoints, or cabling in the environment's private configuration, not in this repository. diff --git a/docs/proposals/fleet-management/inventory.md b/docs/proposals/fleet-management/inventory.md index 528827ac..69d4fcce 100644 --- a/docs/proposals/fleet-management/inventory.md +++ b/docs/proposals/fleet-management/inventory.md @@ -175,8 +175,10 @@ expected connections are stored on ports. This proposal instead uses a new plan for each installation and separate Cable records. That difference must be settled before automating moves and replacements. -Import should preserve existing equipment identities, customer reservations and -history. Change the responsible writer one record type at a time. Do not delete +The current implementation uses manual entry and operator-controlled migration, +not automated import. NetBox and optional offline candidate review are not required. +Migration must preserve existing equipment identities, customer reservations and +history. Change the responsible writer only through an explicit approval. Do not delete and recreate assets, assume occupied space is free, or mark old records ready without new checks. diff --git a/hack/netbox_inventory.py b/hack/netbox_inventory.py index 1d6f3686..c2072240 100644 --- a/hack/netbox_inventory.py +++ b/hack/netbox_inventory.py @@ -1,5 +1,9 @@ #!/usr/bin/env python3 -"""GET-only NetBox snapshot and offline, create-only Fleet GitOps handoff.""" +"""Optional operator-run review aid: GET-only snapshots and offline candidates. + +Manual inventory entry needs neither NetBox nor this tool. Nothing is applied, +scheduled, synchronized, or deleted; an operator reviews every proposed record. +""" import argparse import copy @@ -656,18 +660,18 @@ def private_output(path): def main(argv=None): parser = argparse.ArgumentParser(description=__doc__) subparsers = parser.add_subparsers(dest="command", required=True) - export = subparsers.add_parser("snapshot") + export = subparsers.add_parser("snapshot", help="explicitly read a private NetBox snapshot; optional") export.add_argument("--url", default=os.environ.get("NETBOX_URL", "https://netbox.datum-infra.net")) export.add_argument("--source", required=True) export.add_argument("--auth-scheme", choices=("Bearer", "Token"), default="Bearer") export.add_argument("--output", required=True) - plan = subparsers.add_parser("plan") + plan = subparsers.add_parser("plan", help="review a local snapshot offline; never apply records") plan.add_argument("--snapshot", required=True) plan.add_argument("--mapping") plan.add_argument("--existing") plan.add_argument("--previous") plan.add_argument("--output", required=True) - plan.add_argument("--handoff", action="store_true") + plan.add_argument("--handoff", action="store_true", help="also write optional review candidates; never apply, commit, or push") plan.add_argument("--allow-partial", action="store_true") args = parser.parse_args(argv) output = Path(args.output) diff --git a/hack/testdata/physical/manual.yaml b/hack/testdata/physical/manual.yaml new file mode 100644 index 00000000..e6c3dc81 --- /dev/null +++ b/hack/testdata/physical/manual.yaml @@ -0,0 +1,94 @@ +apiVersion: fleet.datumapis.com/v1alpha1 +kind: Facility +metadata: + name: example-facility + namespace: default +spec: + displayName: Example premises + provenance: + method: Manual + recordedBy: operator@example.com + recordedAt: "2026-11-20T12:00:00Z" +--- +apiVersion: fleet.datumapis.com/v1alpha1 +kind: Rack +metadata: + name: example-rack + namespace: default +spec: + displayName: Example rack + facilityRef: {name: example-facility} + provenance: + method: Manual + recordedBy: operator@example.com + recordedAt: "2026-11-20T12:00:00Z" +--- +apiVersion: fleet.datumapis.com/v1alpha1 +kind: DeviceClaim +metadata: + name: example-installation + namespace: default +spec: + lifecycle: Installation + expectedIdentity: {manufacturer: Example Vendor, model: Example server} + placement: + scope: RackMembership + rackRef: {name: example-rack} + cableRefs: [{name: example-power-cable}] + provenance: + method: Manual + recordedBy: planner@example.com + recordedAt: "2026-11-20T12:00:00Z" +--- +apiVersion: fleet.datumapis.com/v1alpha1 +kind: Device +metadata: + name: example-server + namespace: default +spec: + claimRef: {name: example-installation} + identity: + manufacturer: Example Vendor + model: Example server + serial: SYNTHETIC-MANUAL-0001 + topologyAuthority: Cable + components: + - {id: psu-a, name: PSU A input, type: PowerInlet} + - {id: eth0, name: Ethernet 0, type: NetworkPort} + provenance: + method: Manual + recordedBy: registrar@example.com + recordedAt: "2026-11-20T12:00:00Z" +--- +apiVersion: fleet.datumapis.com/v1alpha1 +kind: PowerFeed +metadata: + name: example-feed + namespace: default +spec: + displayName: Example feed + facilityRef: {name: example-facility} + rackRef: {name: example-rack} + terminations: + - {id: outlet-a, name: Outlet A, type: PowerOutlet} + provenance: + method: Manual + recordedBy: operator@example.com + recordedAt: "2026-11-20T12:00:00Z" +--- +apiVersion: fleet.datumapis.com/v1alpha1 +kind: Cable +metadata: + name: example-power-cable + namespace: default +spec: + displayName: Example power cable + medium: Power + lanes: + - id: power + a: {powerFeedRef: {name: example-feed}, componentID: outlet-a, position: 1} + b: {deviceRef: {name: example-server}, componentID: psu-a, position: 1} + provenance: + method: Manual + recordedBy: operator@example.com + recordedAt: "2026-11-20T12:00:00Z" diff --git a/internal/api/inventory/v1alpha1/physical_test.go b/internal/api/inventory/v1alpha1/physical_test.go index 8229849b..4497c3dc 100644 --- a/internal/api/inventory/v1alpha1/physical_test.go +++ b/internal/api/inventory/v1alpha1/physical_test.go @@ -1,7 +1,10 @@ package v1alpha1 import ( + "bytes" "encoding/json" + "flag" + "io" "os" "strings" "testing" @@ -9,8 +12,63 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/util/yaml" ) +const manualInventoryExample = "../../../../hack/testdata/physical/manual.yaml" + +var inventoryRecords = flag.String("inventory-records", manualInventoryExample, "private YAML records to validate offline; never applies records") + +func TestManualInventoryRecordsPassAdmission(t *testing.T) { + data, err := os.ReadFile(*inventoryRecords) + if err != nil { + t.Fatal("cannot read inventory records") + } + decoder := yaml.NewYAMLOrJSONDecoder(bytes.NewReader(data), 4096) + crds := loadCRDs(t) + seen := map[string]bool{} + count := 0 + for { + var record map[string]any + if err := decoder.Decode(&record); err == io.EOF { + break + } else if err != nil { + t.Fatal("cannot decode inventory records") + } + if len(record) == 0 { + continue + } + kind, ok := record["kind"].(string) + if !ok || crds[kind] == nil { + t.Fatal("expected one of the six physical kinds") + } + seen[kind] = true + if *inventoryRecords == manualInventoryExample { + spec := record["spec"].(map[string]any) + provenance := spec["provenance"].(map[string]any) + if provenance["method"] != "Manual" || provenance["source"] != nil || record["status"] != nil { + t.Fatal("manual example must have no source dependency or status assertion") + } + if kind == "DeviceClaim" && spec["lifecycle"] != "Installation" || kind == "Device" && spec["topologyAuthority"] != "Cable" { + t.Fatal("new manual records must use typed installation and Cable topology") + } + } + for _, previous := range []map[string]any{nil, object(t, record)} { + if errs := admit(t, kind, object(t, record), previous); len(errs) != 0 { + t.Fatalf("record %d (%s) failed admission with %d errors; inspect privately", count+1, kind, len(errs)) + } + } + count++ + } + if count == 0 { + t.Fatal("no inventory records validated") + } + if *inventoryRecords == manualInventoryExample && len(seen) != 6 { + t.Fatal("manual example must exercise all six physical kinds") + } + t.Logf("validated %d records for create and unchanged update; no API writes", count) +} + func TestSyntheticNetBoxHandoffPassesAdmission(t *testing.T) { data, err := os.ReadFile("../../../../hack/testdata/netbox/candidates.json") if err != nil { diff --git a/ui/provider/README.md b/ui/provider/README.md index eccd8ba6..fe7f6b4e 100644 --- a/ui/provider/README.md +++ b/ui/provider/README.md @@ -90,9 +90,11 @@ to that array instead. The read-only Inventory tab now loads all six physical inventory collections with pagination. It retains unknown placement and ambiguous historical bindings, shows Facility/Rack/Cable/PowerFeed relationships and typed asset components, -and supports local-only review of import reports. These reads require the +and supports optional local-only review of source-comparison reports. Manual +inventory needs no NetBox or report; operators review the private Git source and +Flux is the sole staging writer. The portal never writes or synchronizes records. These reads require the provider-scoped inventory viewer role, not a consumer Metal role. See the -[physical import operator guide](../../docs/operations/netbox-physical-import.md) +[optional source-comparison guide](../../docs/operations/netbox-physical-import.md) for the offline Flux handoff and the distinction between records and readiness. - staff-portal runs react-router 7, so this plugin pins it for types and diff --git a/ui/provider/src/components/physical-inventory.test.tsx b/ui/provider/src/components/physical-inventory.test.tsx index dcd255a2..a3e454fc 100644 --- a/ui/provider/src/components/physical-inventory.test.tsx +++ b/ui/provider/src/components/physical-inventory.test.tsx @@ -5,6 +5,25 @@ import { toInventory, placementLabel } from '../inventory'; import { fixtureDeviceClaims } from '../lib/fixtures'; describe('physical inventory', () => { + it('browses manual facilities, racks, cables and feeds without a source report', () => { + const provenance = fixtureDeviceClaims[0].spec.provenance; + const inventory = toInventory([], [], [ + { kind: 'Facility', metadata: { name: 'premises', namespace: 'default' }, spec: { displayName: 'Manual premises', provenance } }, + { kind: 'Rack', metadata: { name: 'rack', namespace: 'default' }, spec: { displayName: 'Manual rack', facilityRef: { name: 'premises' }, provenance } }, + { kind: 'PowerFeed', metadata: { name: 'feed', namespace: 'default' }, spec: { displayName: 'Manual feed', facilityRef: { name: 'premises' }, rackRef: { name: 'rack' }, provenance } }, + { kind: 'Cable', metadata: { name: 'cable', namespace: 'default' }, spec: { displayName: 'Manual cable', medium: 'Power', lanes: [{ id: 'power', a: { powerFeedRef: { name: 'feed' }, componentID: 'outlet', position: 1 }, b: { deviceRef: { name: 'server' }, componentID: 'psu', position: 1 } }], provenance } }, + ]); + render(); + for (const kind of ['Facility', 'Rack', 'PowerFeed', 'Cable']) { + expect(screen.getByText(new RegExp(`^${kind}: Manual`))).toBeInTheDocument(); + } + expect(screen.getByText(/feed\/outlet:1 ↔ server\/psu:1/)).toBeInTheDocument(); + expect(screen.getByText(/Usable budget and redundancy: Unknown/)).toBeInTheDocument(); + expect(screen.getAllByText(/Verification: Unknown/)).toHaveLength(4); + expect(screen.queryByText(/classified records/)).not.toBeInTheDocument(); + expect(screen.queryByRole('button', { name: /apply|sync|import|delete/i })).not.toBeInTheDocument(); + }); + it('keeps partial placement and free space unknown', () => { const claim = { ...fixtureDeviceClaims[0], spec: { ...fixtureDeviceClaims[0].spec, placement: { scope: 'RackMembership' as const, rackRef: { name: 'rack-example' } } } }; expect(placementLabel(claim)).toContain('no reserved units'); @@ -17,7 +36,8 @@ describe('physical inventory', () => { it('reads reconciliation locally and rejects malformed reports', async () => { render(); - const input = screen.getByLabelText(/Inspect a private import report/); + expect(screen.getByText(/NetBox and import reports are not required/)).toBeInTheDocument(); + const input = screen.getByLabelText(/Optional: inspect a private review report/); fireEvent.change(input, { target: { files: [{ size: 100, text: async () => JSON.stringify({ version: 1, records: [{ source: 'dcim/devices/1', classification: 'unresolved', reason: 'Review premises' }] }) }] } }); await waitFor(() => expect(screen.getByText(/dcim\/devices\/1: unresolved/)).toBeInTheDocument()); expect(screen.getByText(/Incomplete or Unknown/)).toBeInTheDocument(); diff --git a/ui/provider/src/components/physical-inventory.tsx b/ui/provider/src/components/physical-inventory.tsx index 0c032dca..e7e790f0 100644 --- a/ui/provider/src/components/physical-inventory.tsx +++ b/ui/provider/src/components/physical-inventory.tsx @@ -15,7 +15,8 @@ export function PhysicalInventory({ inventory }: { inventory: Inventory }) { return

Physical records · verification Unknown

Observational records do not reserve space, establish an active binding, or authorize hardware operations. Cable is the typed topology authority; legacy inline peers remain unmigrated history.

-
- {[...slot.devices].reverse().map((device) => ( + {data?.issues?.Device && } + {(!data?.issues?.Device ? [...slot.devices].reverse() : []).map((device) => ( ))}
- {data?.physical.filter((record) => record.kind === 'Cable' && record.metadata.namespace === slot.claim.metadata.namespace && record.spec.lanes?.some((lane) => slot.devices.some((device) => lane.a.deviceRef?.name === device.metadata.name || lane.b.deviceRef?.name === device.metadata.name))).map((cable) =>
{cable.spec.displayName} · verification Unknown{cable.spec.lanes?.map((lane) => {endpointLabel(lane.a)} ↔ {endpointLabel(lane.b)})}
)} + {data?.issues?.Cable ? : !data?.issues?.Device && data?.physical.filter((record) => record.kind === 'Cable' && record.metadata.namespace === slot.claim.metadata.namespace && record.spec.lanes?.some((lane) => slot.devices.some((device) => lane.a.deviceRef?.name === device.metadata.name || lane.b.deviceRef?.name === device.metadata.name))).map((cable) =>
{cable.spec.displayName} · verification Unknown{cable.spec.lanes?.map((lane) => {endpointLabel(lane.a)} ↔ {endpointLabel(lane.b)})}
)} No displayed path proves an uncabled or free termination.
diff --git a/ui/provider/src/pages/device-inventory-list.tsx b/ui/provider/src/pages/device-inventory-list.tsx index c17b2655..14cbd237 100644 --- a/ui/provider/src/pages/device-inventory-list.tsx +++ b/ui/provider/src/pages/device-inventory-list.tsx @@ -1,66 +1,19 @@ import { FleetPage } from '../components/fleet-page'; import { PhysicalInventory } from '../components/physical-inventory'; -import { InventoryTable } from '../components/inventory-table'; -import { ErrorOrRestrictedState, LoadingState } from '../components/states'; -import { PROVIDER_PROJECT, useInventory } from '../lib/api'; -import { modelLabel } from '../inventory'; -import { Card, CardContent } from '@datum-cloud/datum-ui/card'; -import { EmptyContent } from '@datum-cloud/datum-ui/empty-content'; -import { Text } from '@datum-cloud/datum-ui/typography'; -import { useParams } from 'react-router'; +import { LoadingState } from '../components/states'; +import { InventoryAccessState } from '../components/inventory-access-state'; +import { useInventory } from '../lib/api'; +import { InventorySessionBoundary } from '../components/inventory-session-boundary'; -// Read-only. Planners and registrars write DeviceClaims and Devices through -// GitOps; nothing here creates capacity or acts on hardware. export default function DeviceInventoryList() { - const { slug } = useParams(); - const base = `/plugins/${slug}`; - const { data, isLoading, error, refetch } = useInventory(); - const isEmpty = !isLoading && !error && data && data.slots.length === 0 && data.unboundDevices.length === 0 && data.physical.length === 0; - - return ( - - {!isLoading && !error && data && } - {isLoading && } - - {!isLoading && error && ( - void refetch()} - /> - )} - - {isEmpty && ( -
- -
- )} - - {!isLoading && !error && data && data.slots.length > 0 && } + return ; +} - {!isLoading && !error && data && data.unboundDevices.length > 0 && ( - - - Devices without a matching claim - - These Devices name a DeviceClaim that does not exist in their namespace. - -
    - {data.unboundDevices.map((device) => ( -
  • - - {device.metadata.name} → {device.spec.claimRef.name} ({modelLabel(device.spec.identity)}) - -
  • - ))} -
-
-
- )} -
- ); +function InventoryListContent() { + const { data, isLoading, error, refetch } = useInventory(); + return + {isLoading && } + {!isLoading && error && void refetch()} />} + {!isLoading && !error && data && void refetch()} />} + ; } diff --git a/ui/provider/src/pages/device-inventory.test.tsx b/ui/provider/src/pages/device-inventory.test.tsx index 2e018184..57bed228 100644 --- a/ui/provider/src/pages/device-inventory.test.tsx +++ b/ui/provider/src/pages/device-inventory.test.tsx @@ -3,9 +3,10 @@ import DeviceInventoryList from './device-inventory-list'; import { toInventory } from '../inventory'; import * as api from '../lib/api'; import { ApiError } from '../lib/api'; +import { InventoryPreviewContext } from '../components/inventory-session-boundary'; import { fixtureDeviceClaims, fixtureDevices } from '../lib/fixtures'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; -import { render, screen, within } from '@testing-library/react'; +import { fireEvent, render, screen, within } from '@testing-library/react'; import { MemoryRouter, Route, Routes } from 'react-router'; import { beforeEach, describe, expect, it, vi } from 'vitest'; @@ -24,12 +25,14 @@ function renderAt(path: string) { const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); return render( + } /> } /> + ); } @@ -45,29 +48,54 @@ describe('DeviceInventoryList', () => { expect(screen.getByRole('tab', { name: 'Inventory' })).toHaveAttribute('data-state', 'active'); }); - it('lists claims with their bound Device and links to the detail page', () => { + it('starts with physical devices and links to their own identity', () => { mockInventory({ data: inventory }); renderAt('/plugins/metal-datumapis-com/inventory'); const table = screen.getByTestId('fleet-plugin-inventory-table'); expect(within(table).getByText('rack-01-u12-synthetic-0001')).toBeInTheDocument(); expect(within(table).getByText('SYNTHETIC-0001')).toBeInTheDocument(); - expect(within(table).getByText('Not registered')).toBeInTheDocument(); - expect(within(table).getByRole('link', { name: 'rack-01-u12' })).toHaveAttribute( + expect(within(table).getByRole('link', { name: 'rack-01-u12-synthetic-0001' })).toHaveAttribute( 'href', - '/plugins/metal-datumapis-com/inventory/default/rack-01-u12' + '/plugins/metal-datumapis-com/inventory?kind=Device&record=rack-01-u12-synthetic-0001&namespace=default' ); }); it('shows Devices whose claim is missing', () => { mockInventory({ data: inventory }); renderAt('/plugins/metal-datumapis-com/inventory'); - expect(within(screen.getByTestId('fleet-plugin-unbound-devices')).getByText(/orphan-synthetic-0009/)).toBeInTheDocument(); + expect(within(screen.getByTestId('fleet-plugin-inventory-table')).getByText(/orphan-synthetic-0009/)).toBeInTheDocument(); + expect(screen.getByText('Claim record not found')).toBeInTheDocument(); }); it('shows the restricted state on a 403', () => { mockInventory({ error: new ApiError(403, 'forbidden') }); renderAt('/plugins/metal-datumapis-com/inventory'); - expect(screen.getByTestId('fleet-plugin-restricted')).toBeInTheDocument(); + expect(screen.getByTestId('inventory-access-403')).toBeInTheDocument(); + }); + + it('handles an expired session without exposing cached inventory', () => { + mockInventory({ data: inventory, error: new ApiError(401, 'Private backend detail') }); + renderAt('/plugins/metal-datumapis-com/inventory'); + expect(screen.getByRole('heading', { name: 'Your session has expired' })).toBeInTheDocument(); + expect(screen.queryByText('SYNTHETIC-0001')).not.toBeInTheDocument(); + expect(screen.queryByText('Private backend detail')).not.toBeInTheDocument(); + expect(screen.getByRole('link', { name: 'Return to staff portal' })).toHaveAttribute('href', '/'); + }); + + it('does not show record counts before loading completes', () => { + mockInventory({ isLoading: true }); + renderAt('/plugins/metal-datumapis-com/inventory'); + expect(screen.getByTestId('fleet-plugin-loading')).toBeInTheDocument(); + expect(screen.queryByRole('navigation', { name: 'Inventory categories' })).not.toBeInTheDocument(); + }); + + it('hides stale counts on a failed read and allows retry', () => { + mockInventory({ data: inventory, error: new ApiError(500, 'Inventory unavailable') }); + renderAt('/plugins/metal-datumapis-com/inventory'); + expect(screen.getByTestId('inventory-access-500')).toBeInTheDocument(); + expect(screen.queryByRole('navigation', { name: 'Inventory categories' })).not.toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: 'Try again' })); + expect(useInventoryMock.mock.results[0].value.refetch).toHaveBeenCalledOnce(); }); it('shows the empty state with no records', () => { @@ -84,6 +112,14 @@ describe('DeviceInventoryList', () => { }); describe('DeviceClaimDetail', () => { + it('denies old direct links without leaking cached claims or devices', () => { + mockInventory({ data: inventory, error: new ApiError(403, 'Secret error') }); + renderAt('/plugins/metal-datumapis-com/inventory/default/rack-01-u12'); + expect(screen.getByRole('heading', { name: 'Inventory access needed' })).toBeInTheDocument(); + expect(screen.queryByText('SYNTHETIC-0001')).not.toBeInTheDocument(); + expect(screen.queryByTestId('fleet-plugin-claim')).not.toBeInTheDocument(); + }); + it('shows placement, ports, binding, identity, BMC endpoint, unmapped MACs and provenance', () => { mockInventory({ data: inventory }); renderAt('/plugins/metal-datumapis-com/inventory/default/rack-01-u12'); diff --git a/ui/provider/src/preview.css b/ui/provider/src/preview.css new file mode 100644 index 00000000..88af64a5 --- /dev/null +++ b/ui/provider/src/preview.css @@ -0,0 +1,5 @@ +@import 'tailwindcss'; +@import '@datum-cloud/datum-ui/styles'; + +.fleet-preview { max-width:1440px; margin:0 auto; } +.fleet-preview-notice { padding:10px 24px; font-size:12px; background:var(--muted); color:var(--muted-foreground); border-bottom:1px solid var(--border); } diff --git a/ui/provider/vite.config.ts b/ui/provider/vite.config.ts index fb7b117b..e1314693 100644 --- a/ui/provider/vite.config.ts +++ b/ui/provider/vite.config.ts @@ -1,5 +1,6 @@ import { federation } from '@module-federation/vite'; import react from '@vitejs/plugin-react'; +import tailwindcss from '@tailwindcss/vite'; import { defineConfig } from 'vite'; // The host (staff-portal) loads this remote and provides react / react-dom / @@ -26,6 +27,7 @@ export default defineConfig({ minify: false, }, plugins: [ + tailwindcss(), react(), federation({ // MUST equal the manifest `name`; the host keys the remote by this id. diff --git a/ui/shared/fleet-api.ts b/ui/shared/fleet-api.ts index 3cbf6f06..30d93cd4 100644 --- a/ui/shared/fleet-api.ts +++ b/ui/shared/fleet-api.ts @@ -27,6 +27,7 @@ export interface ObjectMeta { deletionTimestamp?: string; labels?: Record; annotations?: Record; + managedFields?: { manager?: string; subresource?: string }[]; finalizers?: string[]; } From 5363687980a0b758d4bec28fd7feb210d97d09c9 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Fri, 20 Nov 2026 17:09:26 -0600 Subject: [PATCH 022/518] fix(inventory): revoke stale operation authority --- docs/development/staff-inventory-ui.md | 40 +++++- .../components/adversarial-review.test.tsx | 120 ++++++++++++++++++ .../inventory-management-lifetime.test.tsx | 47 +++++++ .../src/components/inventory-management.tsx | 41 +++++- .../inventory-session-boundary.test.tsx | 20 +++ .../components/inventory-session-boundary.tsx | 41 ++++-- .../src/lib/inventory-management.test.ts | 13 +- ui/provider/src/lib/inventory-management.ts | 19 ++- .../src/lib/inventory-operation.test.ts | 81 ++++++++++++ ui/provider/src/lib/inventory-operation.ts | 41 ++++++ 10 files changed, 434 insertions(+), 29 deletions(-) create mode 100644 ui/provider/src/components/adversarial-review.test.tsx create mode 100644 ui/provider/src/components/inventory-management-lifetime.test.tsx create mode 100644 ui/provider/src/lib/inventory-operation.test.ts create mode 100644 ui/provider/src/lib/inventory-operation.ts diff --git a/docs/development/staff-inventory-ui.md b/docs/development/staff-inventory-ui.md index ee1d1f12..17fecd9e 100644 --- a/docs/development/staff-inventory-ui.md +++ b/docs/development/staff-inventory-ui.md @@ -82,6 +82,21 @@ Locally implemented management is deliberately narrower than that role: - Submit denial, expiry, and conflicts retain safe input without reporting success. Ambiguous network/server failures stop repeat submission and ask the operator to inspect inventory before another attempt. +- Every imperative create/edit requires an operation lease tied to both the form + lifetime and host session generation. The router subscription invalidates it + synchronously when revalidation/navigation begins or identity changes, before + React needs to commit an unmount. Blur, page hide, hidden-document and unmount + boundaries also revoke it. Each awaited permission/record prerequisite is + followed by an authority check before any write dispatch. Revoked work never + dispatches a later POST/PATCH under the next cookie session. +- An already-dispatched write cannot be recalled by invalidating its lease. + Its late response (including success) remains an unknown outcome to the stale + operation. No automatic retry, cancellation-success or late save confirmation + is produced. Refresh and inspect authoritative inventory before another attempt. +- Opening an edit captures a deep copy of its original UID/resourceVersion and + display name. Refreshing props never advances that open form's baseline. A + concurrent change produces a conflict while retaining input; explicitly closing + and reopening starts a new reviewed baseline. Host integration was inspected at staff-portal HEAD `b1489125fe5b77ea6fc379ad378c8e1951174de5` on November 20, 2026: @@ -128,7 +143,9 @@ changes synchronously replace the query scope. Blur, page hide and hidden-docume events remove inventory and clear its private cache. Focus, visibility restoration and back-forward-cache restoration revalidate the actual protected host loader before mounting a fresh inventory view. Pending/failed revalidation cannot render -old records. This intentionally resets open forms on session/background boundaries; +old records. Focus checks carry a generation and foreground/visibility condition; +obsolete completions cannot undo a later hide or a newer check. This intentionally +resets open forms on session/background boundaries; submit denial while the view remains active still retains safe unsaved input. There is no automatic save or retry when returning to a page. @@ -160,7 +177,7 @@ For local browser checks: `VITE_FLEET_FIXTURES=true pnpm dev --port 7796`, then open the Inventory tab. Synthetic data is explicitly labeled and includes all six kinds. No live inventory calls are made in fixture mode. -Local checks: 98 tests in 11 files pass; typecheck and production build pass. +Local checks after review fixes: 121 tests in 14 files pass; typecheck and production build pass. The inventory Go package tests validate the exact manager/viewer/editor grants. Both ordinary and race-enabled package tests pass. The build reports transitive undici sharing and Zod annotation warnings; these @@ -207,3 +224,22 @@ authorization. Native Pencil fidelity remains a design gap, not an IAM gate. These are local checks, not evidence of deployed availability, authorization, hardware verification, or a completed native Pencil visual comparison. + +### Adversarial review regressions + +The independent suite against `0673b82f073ab065327192a14c74d2dc6720b003` +was copied into `ui/provider/src/components/adversarial-review.test.tsx` with +its original assertions intact. Before fixes it reproduced three failures and +one passing no-read check. All now pass; additional tests cover same-tick router +invalidation before React commits, create/edit permission and GET prerequisites, +blur/unmount, repeated session generations, Strict Mode lifecycle restart, +already-dispatched success/failure remaining unknown, frozen edit conflicts, +and out-of-order focus completions. + +Synthetic browser replay independently delayed the create SSAR, switched the +host principal and released the review: zero writes dispatched. An edit opened +at revision 1 retained input while props/API advanced to revision 2: zero patches +and a calm conflict state. A delayed focus revalidation completed after a second +blur without restoring inventory; a new focus restored it only after a fresh +check. Desktop/mobile checks used intercepted requests only. These fixes await +a new independent review; passing local regressions are not self-approval. diff --git a/ui/provider/src/components/adversarial-review.test.tsx b/ui/provider/src/components/adversarial-review.test.tsx new file mode 100644 index 00000000..17dc7898 --- /dev/null +++ b/ui/provider/src/components/adversarial-review.test.tsx @@ -0,0 +1,120 @@ +import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { createMemoryRouter, Outlet, RouterProvider } from 'react-router'; +import { afterEach, expect, it, vi } from 'vitest'; +import { InventoryManagement } from './inventory-management'; +import { InventorySessionBoundary } from './inventory-session-boundary'; +import DeviceInventoryList from '../pages/device-inventory-list'; +import { inventoryPayload, INVENTORY_FIELD_MANAGER } from '../lib/inventory-management'; + +const values = { name: 'review-facility', namespace: 'default', displayName: 'Original label', recordedBy: 'synthetic-reviewer', reference: '', facility: '', height: '' }; +const original = { ...inventoryPayload('Facility', values, '2026-01-01T00:00:00Z'), metadata: { name: values.name, namespace: 'default', uid: 'synthetic-only', resourceVersion: '1', managedFields: [{ manager: INVENTORY_FIELD_MANAGER }] } }; +const response = (data: unknown) => ({ ok: true, status: 200, json: async () => ({ data }) }); +afterEach(() => { cleanup(); vi.unstubAllGlobals(); }); + +it('renders calm denied access with exactly six list attempts and no permission reviews or writes', async () => { + const requests = vi.fn(async () => ({ ok: false, status: 403, json: async () => ({ error: 'DO NOT DISPLAY internal authorization diagnostic' }) })); + vi.stubGlobal('fetch', requests); + const router = createMemoryRouter([{ id: 'layouts/milo.layout', path: '/', loader: () => ({ user: { metadata: { uid: 'denied-staff' } } }), element: , children: [{ index: true, element: }] }]); + render(); + await screen.findByRole('heading', { name: 'Inventory access needed' }); + expect(requests).toHaveBeenCalledTimes(6); + for (const [, init] of requests.mock.calls as unknown as [string, RequestInit][]) expect(init.method).toBe('GET'); + expect(screen.queryByText(/DO NOT DISPLAY/)).not.toBeInTheDocument(); + expect(screen.queryByText(/Create facility/)).not.toBeInTheDocument(); +}); +it('invalidates authority synchronously before React commits the session transition', async () => { + let principal = 'staff-a'; + let releaseReview: ((value: unknown) => void) | undefined; + let reviews = 0; + const writes: string[] = []; + vi.stubGlobal('fetch', vi.fn(async (url: string, init: RequestInit) => { + if (url.includes('selfsubjectaccessreviews')) { + reviews++; + if (reviews === 2) return new Promise(resolve => { releaseReview = resolve; }); + return response({ status: { allowed: true } }); + } + if (init.method === 'POST') writes.push(principal); + return response(original); + })); + const router = createMemoryRouter([{ id: 'layouts/milo.layout', path: '/', loader: () => ({ user: { metadata: { uid: principal } } }), element: , children: [{ index: true, element: }] }]); + render(); + await screen.findByRole('button', { name: 'Create facility' }); + fireEvent.click(screen.getByText('Manage facilities')); + fireEvent.click(screen.getByRole('button', { name: 'Create facility' })); + fireEvent.change(screen.getByLabelText('Record name'), { target: { value: values.name } }); + fireEvent.change(screen.getByLabelText('Display name'), { target: { value: values.displayName } }); + fireEvent.change(screen.getByLabelText('Recorded by'), { target: { value: values.recordedBy } }); + fireEvent.click(screen.getByRole('button', { name: 'Create facility record' })); + await waitFor(() => expect(releaseReview).toBeDefined()); + principal = 'staff-b'; + await act(async () => { void router.revalidate(); releaseReview!(response({ status: { allowed: true } })); }); + expect(writes).toEqual([]); +}); + +it('must not send a create after the initiating authenticated principal unmounts', async () => { + let principal = 'staff-a'; + let releaseReview: ((value: unknown) => void) | undefined; + let reviews = 0; + const writes: string[] = []; + vi.stubGlobal('fetch', vi.fn(async (url: string, init: RequestInit) => { + if (url.includes('selfsubjectaccessreviews')) { + reviews++; + if (reviews === 2) return new Promise(resolve => { releaseReview = resolve; }); + return response({ status: { allowed: true } }); + } + if (init.method === 'POST') writes.push(principal); + return response(original); + })); + const router = createMemoryRouter([{ id: 'layouts/milo.layout', path: '/', loader: () => ({ user: { metadata: { uid: principal } } }), element: , children: [{ index: true, element: }] }]); + render(); + await screen.findByRole('button', { name: 'Create facility' }); + fireEvent.click(screen.getByText('Manage facilities')); + fireEvent.click(screen.getByRole('button', { name: 'Create facility' })); + fireEvent.change(screen.getByLabelText('Record name'), { target: { value: values.name } }); + fireEvent.change(screen.getByLabelText('Display name'), { target: { value: values.displayName } }); + fireEvent.change(screen.getByLabelText('Recorded by'), { target: { value: values.recordedBy } }); + fireEvent.click(screen.getByRole('button', { name: 'Create facility record' })); + await waitFor(() => expect(releaseReview).toBeDefined()); + principal = 'staff-b'; + await act(async () => { await router.revalidate(); }); + await act(async () => { releaseReview!(response({ status: { allowed: true } })); }); + expect(writes).toEqual([]); +}); + +it('must not silently advance an open edit form to a refreshed resourceVersion', async () => { + let current = original; + const patches: unknown[] = []; + vi.stubGlobal('fetch', vi.fn(async (url: string, init: RequestInit) => { + if (url.includes('selfsubjectaccessreviews')) return response({ status: { allowed: true } }); + if (init.method === 'PATCH') patches.push(JSON.parse(String(init.body))); + return response(current); + })); + const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + const content = () => ; + const mounted = render(content()); + await screen.findByRole('button', { name: 'Edit display name' }); + fireEvent.click(screen.getByText('Manage this record')); + fireEvent.click(screen.getByRole('button', { name: 'Edit display name' })); + fireEvent.change(screen.getByLabelText('Display name'), { target: { value: 'My unsaved label' } }); + fireEvent.change(screen.getByLabelText('Recorded by'), { target: { value: values.recordedBy } }); + current = { ...original, metadata: { ...original.metadata, resourceVersion: '2' }, spec: { ...original.spec, displayName: 'Other operator saved this' } }; + mounted.rerender(content()); + fireEvent.click(screen.getByRole('button', { name: 'Save display name' })); + await waitFor(() => expect(screen.getByRole('status')).toBeInTheDocument()); + expect(patches).toEqual([]); +}); + +it('must keep inventory concealed if focus verification finishes after another blur', async () => { + let release: (() => void) | undefined; + let count = 0; + const router = createMemoryRouter([{ id: 'layouts/milo.layout', path: '/', loader: async () => { if (++count === 2) await new Promise(resolve => { release = resolve; }); return { user: { metadata: { uid: 'staff-a' } } }; }, element: , children: [{ index: true, element: Private inventory label }] }]); + render(); + await screen.findByText('Private inventory label'); + fireEvent(window, new Event('blur')); + fireEvent(window, new Event('focus')); + await waitFor(() => expect(release).toBeDefined()); + fireEvent(window, new Event('blur')); + await act(async () => { release!(); }); + expect(screen.queryByText('Private inventory label')).not.toBeInTheDocument(); +}); diff --git a/ui/provider/src/components/inventory-management-lifetime.test.tsx b/ui/provider/src/components/inventory-management-lifetime.test.tsx new file mode 100644 index 00000000..b92cd7dc --- /dev/null +++ b/ui/provider/src/components/inventory-management-lifetime.test.tsx @@ -0,0 +1,47 @@ +import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { afterEach, expect, it, vi } from 'vitest'; +import { InventoryManagement } from './inventory-management'; +import { inventoryPayload, INVENTORY_FIELD_MANAGER } from '../lib/inventory-management'; + +const values = { name: 'synthetic-only', namespace: 'default', displayName: 'Original', recordedBy: 'operator', reference: '', facility: '', height: '' }; +const original = { ...inventoryPayload('Facility', values, '2026-01-01T00:00:00Z'), metadata: { name: values.name, namespace: 'default', uid: 'synthetic', resourceVersion: '1', managedFields: [{ manager: INVENTORY_FIELD_MANAGER }] } }; +const response = (data: unknown) => ({ ok: true, status: 200, json: async () => ({ data }) }); +afterEach(() => vi.unstubAllGlobals()); + +it.each(['create-blur', 'create-unmount', 'edit-blur', 'edit-unmount', 'create-dispatched-blur', 'edit-dispatched-blur'])('revokes pending authority on %s', async mode => { + let release: ((value: unknown) => void) | undefined; + let reviews = 0; + const writes: string[] = []; + vi.stubGlobal('fetch', vi.fn(async (url: string, init: RequestInit) => { + if (url.includes('selfsubjectaccessreviews')) { + if (++reviews === 2 && !mode.includes('dispatched')) return new Promise(resolve => { release = resolve; }); + return response({ status: { allowed: true } }); + } + if (init.method !== 'GET') { + writes.push(init.method!); + if (mode.includes('dispatched')) return new Promise(resolve => { release = resolve; }); + } + return response(original); + })); + const editing = mode.startsWith('edit'); + const mounted = render(); + await screen.findByRole('button', { name: editing ? 'Edit display name' : 'Create facility' }); + fireEvent.click(screen.getByText(editing ? 'Manage this record' : 'Manage facilities')); + fireEvent.click(screen.getByRole('button', { name: editing ? 'Edit display name' : 'Create facility' })); + if (!editing) fireEvent.change(screen.getByLabelText('Record name'), { target: { value: values.name } }); + fireEvent.change(screen.getByLabelText('Display name'), { target: { value: 'Retained safe input' } }); + fireEvent.change(screen.getByLabelText('Recorded by'), { target: { value: values.recordedBy } }); + fireEvent.click(screen.getByRole('button', { name: editing ? 'Save display name' : 'Create facility record' })); + await waitFor(() => expect(release).toBeDefined()); + if (mode.endsWith('unmount')) mounted.unmount(); + else fireEvent(window, new Event('blur')); + await act(async () => { release!(response(mode.includes('dispatched') ? original : { status: { allowed: true } })); }); + expect(writes).toEqual(mode.includes('dispatched') ? [editing ? 'PATCH' : 'POST'] : []); + if (mode.endsWith('blur')) { + expect(screen.getByRole('status')).toHaveTextContent(mode.includes('dispatched') ? 'outcome is unknown' : 'No write was dispatched'); + expect(screen.queryByText(/Display name saved\.|Facility record created\./)).not.toBeInTheDocument(); + expect(screen.getByLabelText('Display name')).toHaveValue('Retained safe input'); + expect(screen.getByRole('button', { name: editing ? 'Save display name' : 'Create facility record' })).toBeDisabled(); + } +}); diff --git a/ui/provider/src/components/inventory-management.tsx b/ui/provider/src/components/inventory-management.tsx index 21a71c44..7de8de6a 100644 --- a/ui/provider/src/components/inventory-management.tsx +++ b/ui/provider/src/components/inventory-management.tsx @@ -1,12 +1,31 @@ -import { useState, type FormEvent } from 'react'; +import { useContext, useLayoutEffect, useRef, useState, type FormEvent } from 'react'; import { useQueryClient } from '@tanstack/react-query'; import { Button } from '@datum-cloud/datum-ui/button'; import { ApiError, PLUGIN_ID, PROVIDER_PROJECT } from '../lib/api'; import { canEditInventoryLabel, createInventoryRecord, editInventoryLabel, useInventoryPermission, type InventoryFormValues, type ManagedKind } from '../lib/inventory-management'; import type { PhysicalRecord } from '../../../shared/fleet-api'; +import { InventoryOperationContext, InventoryOperationInvalidated, InventoryOperationScope } from '../lib/inventory-operation'; export function InventoryManagement({ kind, record, facilities }: { kind: ManagedKind; record?: PhysicalRecord; facilities: PhysicalRecord[] }) { const client = useQueryClient(); + const sessionScope = useContext(InventoryOperationContext); + const scope = useRef(new InventoryOperationScope()); + useLayoutEffect(() => { + const current = new InventoryOperationScope(); + scope.current = current; + const invalidate = () => current.invalidate(); + const visibility = () => { if (document.visibilityState === 'hidden') invalidate(); }; + window.addEventListener('blur', invalidate); + window.addEventListener('pagehide', invalidate); + document.addEventListener('visibilitychange', visibility); + return () => { + invalidate(); + window.removeEventListener('blur', invalidate); + window.removeEventListener('pagehide', invalidate); + document.removeEventListener('visibilitychange', visibility); + }; + }, []); + const [baseline, setBaseline] = useState(); const [namespace, setNamespace] = useState(record?.metadata.namespace ?? 'default'); const editable = !record || canEditInventoryLabel(record); const permission = useInventoryPermission(kind, editable ? namespace : '', record ? 'patch' : 'create', record?.metadata.name); @@ -21,13 +40,18 @@ export function InventoryManagement({ kind, record, facilities }: { kind: Manage event.preventDefault(); if (!allowed || pending || blocked) return; setPending(true); setMessage(''); + const operation = scope.current.begin(sessionScope); try { - if (record) await editInventoryLabel(record, values); - else await createInventoryRecord(kind, { ...values, namespace }); + if (record) { + if (!baseline) throw new ApiError(409, 'Reopen the form to review this record.'); + await editInventoryLabel(baseline, values, operation); + } else await createInventoryRecord(kind, { ...values, namespace }, operation); + operation.assertCurrent(); setMessage(record ? 'Display name saved.' : `${kind} record created.`); setOpen(false); await client.invalidateQueries({ queryKey: [PLUGIN_ID, 'inventory', PROVIDER_PROJECT] }); } catch (error) { - if (error instanceof ApiError && error.status === 403) { setMessage('Your management permission changed. Your input is kept here. Ask your administrator for access before trying again.'); setBlocked(true); } + if (error instanceof InventoryOperationInvalidated) { setMessage(error.message); setBlocked(true); } + else if (error instanceof ApiError && error.status === 403) { setMessage('Your management permission changed. Your input is kept here. Ask your administrator for access before trying again.'); setBlocked(true); } else if (error instanceof ApiError && error.status === 401) { setMessage('Your session expired. Your input is kept here. Sign in through the staff portal before continuing.'); setBlocked(true); } else if (error instanceof ApiError && error.status === 409) { setMessage('The record already exists, changed, or has another writer. Your input is kept here. Refresh and review the record before continuing.'); setBlocked(true); } else if (error instanceof ApiError && error.status === 422) setMessage('The API could not accept these values. Review the fields and try again.'); @@ -38,7 +62,14 @@ export function InventoryManagement({ kind, record, facilities }: { kind: Manage Manage {record ? 'this record' : `${kind === 'Facility' ? 'facilities' : 'racks'}`} {!record && } {!editable ?

This record has another or unknown writer. It needs an explicit ownership review before portal editing. No ownership changes are made here.

: permission.isFetching ?

Checking management access…

: permission.error instanceof ApiError && permission.error.status === 401 ?

Your session expired. Sign in again through the staff portal before continuing. Unsaved input remains here.

: !allowed &&

Viewing and management access are separate. Ask your administrator about physical-inventory management access. A permission check must succeed before changes are available.

} - {allowed && !open && } + {allowed && !open && } {open &&

{record ? 'Only the display name and recording details change. Identity, placement, geometry, connections, and history remain untouched.' : 'Create a physical record only. This does not verify equipment, reserve space, or provision hardware.'}

{!record && } diff --git a/ui/provider/src/components/inventory-session-boundary.test.tsx b/ui/provider/src/components/inventory-session-boundary.test.tsx index 073fc973..d90b4648 100644 --- a/ui/provider/src/components/inventory-session-boundary.test.tsx +++ b/ui/provider/src/components/inventory-session-boundary.test.tsx @@ -64,4 +64,24 @@ describe('host inventory session isolation', () => { expect(loader).toHaveBeenCalledTimes(2); expect(screen.queryByText('Restricted inventory')).not.toBeInTheDocument(); }); + + it('only restores the newest focused generation after successive blur and focus events', async () => { + const releases: (() => void)[] = []; + let reads = 0; + mountHost(async () => { + if (++reads > 1) await new Promise(resolve => releases.push(resolve)); + return { user: { metadata: { uid: 'staff-a' } } }; + }, 'Private inventory'); + await screen.findByText('Private inventory'); + fireEvent(window, new Event('blur')); + fireEvent(window, new Event('focus')); + await waitFor(() => expect(releases).toHaveLength(1)); + fireEvent(window, new Event('blur')); + fireEvent(window, new Event('focus')); + await waitFor(() => expect(releases).toHaveLength(2)); + await act(async () => releases[0]()); + expect(screen.queryByText('Private inventory')).not.toBeInTheDocument(); + await act(async () => releases[1]()); + await screen.findByText('Private inventory'); + }); }); diff --git a/ui/provider/src/components/inventory-session-boundary.tsx b/ui/provider/src/components/inventory-session-boundary.tsx index 5e488128..2eca4841 100644 --- a/ui/provider/src/components/inventory-session-boundary.tsx +++ b/ui/provider/src/components/inventory-session-boundary.tsx @@ -1,15 +1,26 @@ -import { createContext, useContext, useEffect, useRef, useState, type ReactNode } from 'react'; +import { createContext, useContext, useEffect, useLayoutEffect, useRef, useState, type ReactNode } from 'react'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; -import { UNSAFE_DataRouterStateContext, useRevalidator, useRouteLoaderData } from 'react-router'; +import { UNSAFE_DataRouterContext, UNSAFE_DataRouterStateContext, useRevalidator, useRouteLoaderData } from 'react-router'; import { InventoryAccessState } from './inventory-access-state'; import { LoadingState } from './states'; +import { InventoryOperationContext, InventoryOperationScope } from '../lib/inventory-operation'; export const InventoryPreviewContext = createContext(false); -function SessionQueries({ children }: { children: ReactNode }) { +function SessionQueries({ children, principal }: { children: ReactNode; principal: string }) { const [client] = useState(() => new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } })); + const [scope] = useState(() => new InventoryOperationScope()); + const host = useContext(UNSAFE_DataRouterContext); + useLayoutEffect(() => { + scope.startLifecycle(); + const unsubscribe = host?.router.subscribe(state => { + const identity = state.loaderData['layouts/milo.layout'] as { user?: { metadata?: { uid?: string; name?: string } } } | undefined; + if (state.revalidation !== 'idle' || state.navigation.state !== 'idle' || (identity?.user?.metadata?.uid ?? identity?.user?.metadata?.name) !== principal) scope.invalidate(); + }); + return () => { scope.invalidate(); unsubscribe?.(); }; + }, [host, principal, scope]); useEffect(() => () => client.clear(), [client]); - return {children}; + return {children}; } function HostedInventory({ children }: { children: ReactNode }) { @@ -20,20 +31,25 @@ function HostedInventory({ children }: { children: ReactNode }) { revalidate.current = revalidator.revalidate; const [checking, setChecking] = useState(() => typeof document !== 'undefined' && document.visibilityState === 'hidden'); const [failed, setFailed] = useState(false); - const checkingRef = useRef(false); + const generation = useRef(0); + const foreground = useRef(true); useEffect(() => { let active = true; - const hide = () => setChecking(true); + const hide = () => { + generation.current++; + foreground.current = false; + setChecking(true); + }; const verify = () => { - if (document.visibilityState === 'hidden' || checkingRef.current) return; - checkingRef.current = true; + if (document.visibilityState === 'hidden') return; + foreground.current = true; + const attempt = ++generation.current; setChecking(true); setFailed(false); void revalidate.current().catch(() => { - if (active) setFailed(true); + if (active && attempt === generation.current && foreground.current) setFailed(true); }).finally(() => { - checkingRef.current = false; - if (active) setChecking(false); + if (active && attempt === generation.current && foreground.current && document.visibilityState !== 'hidden') setChecking(false); }); }; const visibility = () => document.visibilityState === 'hidden' ? hide() : verify(); @@ -45,6 +61,7 @@ function HostedInventory({ children }: { children: ReactNode }) { document.addEventListener('visibilitychange', visibility); return () => { active = false; + generation.current++; window.removeEventListener('blur', hide); window.removeEventListener('focus', verify); window.removeEventListener('pagehide', hide); @@ -55,7 +72,7 @@ function HostedInventory({ children }: { children: ReactNode }) { if (checking || revalidator.state !== 'idle') return ; if (failed) return ; if (!principal) return ; - return {children}; + return {children}; } export function InventorySessionBoundary({ children }: { children: ReactNode }) { diff --git a/ui/provider/src/lib/inventory-management.test.ts b/ui/provider/src/lib/inventory-management.test.ts index affcf1d1..eb63c180 100644 --- a/ui/provider/src/lib/inventory-management.test.ts +++ b/ui/provider/src/lib/inventory-management.test.ts @@ -1,3 +1,4 @@ +import { InventoryOperationScope } from './inventory-operation'; import { afterEach, describe, expect, it, vi } from 'vitest'; import { canEditInventoryLabel, createInventoryRecord, editInventoryLabel, inventoryPayload, inventoryPermission, INVENTORY_FIELD_MANAGER, type InventoryFormValues } from './inventory-management'; import type { PhysicalRecord } from '../../../shared/fleet-api'; @@ -24,14 +25,14 @@ describe('inventory management authority', () => { it('cannot write when permission is revoked at submit', async () => { const fetch = vi.fn().mockResolvedValue(response({ status: { allowed: false } })); vi.stubGlobal('fetch', fetch); - await expect(createInventoryRecord('Facility', values)).rejects.toMatchObject({ status: 403 }); + await expect(createInventoryRecord('Facility', values, new InventoryOperationScope().begin())).rejects.toMatchObject({ status: 403 }); expect(fetch).toHaveBeenCalledTimes(1); }); it('creates only an explicitly named observational record, without apply or overwrite', async () => { const fetch = vi.fn().mockResolvedValueOnce(response({ status: { allowed: true } })).mockResolvedValueOnce(response(owned, 201)); vi.stubGlobal('fetch', fetch); - expect(await createInventoryRecord('Facility', values)).toEqual(owned); + expect(await createInventoryRecord('Facility', values, new InventoryOperationScope().begin())).toEqual(owned); const [url, init] = fetch.mock.calls[1]; expect(url).toContain('/namespaces/default/facilities?fieldManager=fleet-staff-inventory-ui'); expect(init.method).toBe('POST'); @@ -55,7 +56,7 @@ describe('inventory management authority', () => { it('edits only a display name and provenance with UID and revision preconditions', async () => { const fetch = vi.fn().mockResolvedValueOnce(response({ status: { allowed: true } })).mockResolvedValueOnce(response(owned)).mockResolvedValueOnce(response(owned)); vi.stubGlobal('fetch', fetch); - await editInventoryLabel(owned, { ...values, displayName: 'New name' }); + await editInventoryLabel(owned, { ...values, displayName: 'New name' }, new InventoryOperationScope().begin()); const init = fetch.mock.calls[2][1]; expect(init.method).toBe('PATCH'); expect(init.headers['Content-Type']).toBe('application/json-patch+json'); @@ -65,17 +66,17 @@ describe('inventory management authority', () => { it('does not patch after ownership or revision changes', async () => { const fetch = vi.fn().mockResolvedValueOnce(response({ status: { allowed: true } })).mockResolvedValueOnce(response({ ...owned, metadata: { ...owned.metadata, resourceVersion: '2' } })); vi.stubGlobal('fetch', fetch); - await expect(editInventoryLabel(owned, values)).rejects.toMatchObject({ status: 409 }); + await expect(editInventoryLabel(owned, values, new InventoryOperationScope().begin())).rejects.toMatchObject({ status: 409 }); expect(fetch).toHaveBeenCalledTimes(2); }); it('does not retry a backend denial or unknown save outcome', async () => { const fetch = vi.fn().mockResolvedValueOnce(response({ status: { allowed: true } })).mockResolvedValueOnce(response(undefined, 403)); vi.stubGlobal('fetch', fetch); - await expect(createInventoryRecord('Facility', values)).rejects.toMatchObject({ status: 403 }); + await expect(createInventoryRecord('Facility', values, new InventoryOperationScope().begin())).rejects.toMatchObject({ status: 403 }); expect(fetch).toHaveBeenCalledTimes(2); fetch.mockReset().mockResolvedValueOnce(response({ status: { allowed: true } })).mockRejectedValueOnce(new Error('Connection lost')); - await expect(createInventoryRecord('Facility', values)).rejects.toThrow('Connection lost'); + await expect(createInventoryRecord('Facility', values, new InventoryOperationScope().begin())).rejects.toThrow('Connection lost'); expect(fetch).toHaveBeenCalledTimes(2); }); }); diff --git a/ui/provider/src/lib/inventory-management.ts b/ui/provider/src/lib/inventory-management.ts index 222c6fa0..3df70a73 100644 --- a/ui/provider/src/lib/inventory-management.ts +++ b/ui/provider/src/lib/inventory-management.ts @@ -1,6 +1,7 @@ import { useQuery } from '@tanstack/react-query'; import { ApiError, PLUGIN_ID, PROVIDER_PROJECT, proxyFetch } from './api'; import type { PhysicalRecord } from '../../../shared/fleet-api'; +import type { InventoryOperation } from './inventory-operation'; export type ManagedKind = 'Facility' | 'Rack'; export const INVENTORY_FIELD_MANAGER = 'fleet-staff-inventory-ui'; @@ -53,35 +54,45 @@ async function requirePermission(kind: ManagedKind, namespace: string, verb: 'cr if (!await inventoryPermission(kind, namespace, verb, name)) throw new ApiError(403, 'Inventory management permission is not available.'); } -export async function createInventoryRecord(kind: ManagedKind, values: InventoryFormValues) { +export async function createInventoryRecord(kind: ManagedKind, values: InventoryFormValues, operation: InventoryOperation) { + operation.assertCurrent(); const payload = inventoryPayload(kind, values); await requirePermission(kind, values.namespace, 'create'); + operation.assertCurrent(); if (kind === 'Rack') { const facility = await proxyFetch(PROVIDER_PROJECT, `${resourcePath('Facility', values.namespace)}/${encodeURIComponent(values.facility)}`); + operation.assertCurrent(); if (!facility?.metadata?.uid || facility.metadata.deletionTimestamp) throw new ApiError(409, 'Facility is not available. Refresh inventory before continuing.'); } - const record = await proxyFetch(PROVIDER_PROJECT, `${resourcePath(kind, values.namespace)}?fieldManager=${INVENTORY_FIELD_MANAGER}`, { method: 'POST', body: payload }); + operation.dispatch(); + const record = await proxyFetch(PROVIDER_PROJECT, `${resourcePath(kind, values.namespace)}?fieldManager=${INVENTORY_FIELD_MANAGER}`, { method: 'POST', body: payload }).catch(error => { operation.assertCurrent(); throw error; }); + operation.assertCurrent(); if (!record?.metadata?.uid) throw new Error('Save outcome could not be confirmed.'); return record; } -export async function editInventoryLabel(original: PhysicalRecord, values: InventoryFormValues) { +export async function editInventoryLabel(original: PhysicalRecord, values: InventoryFormValues, operation: InventoryOperation) { + operation.assertCurrent(); if (!canEditInventoryLabel(original)) throw new ApiError(409, 'This record needs an explicit ownership review before editing.'); const kind = original.kind as ManagedKind; const namespace = original.metadata.namespace ?? ''; await requirePermission(kind, namespace, 'patch', original.metadata.name); + operation.assertCurrent(); const path = `${resourcePath(kind, namespace)}/${encodeURIComponent(original.metadata.name)}`; const current = await proxyFetch(PROVIDER_PROJECT, path); + operation.assertCurrent(); if (!current || current.metadata.uid !== original.metadata.uid || current.metadata.resourceVersion !== original.metadata.resourceVersion || !canEditInventoryLabel(current)) throw new ApiError(409, 'The record or its ownership changed. Reload it before editing.'); const now = new Date().toISOString(); if (now <= current.spec.provenance.recordedAt) throw new ApiError(409, 'The recorded timestamp is not earlier than this clock. Review the record before editing.'); const validated = inventoryPayload('Facility', { ...values, name: original.metadata.name, namespace }, now); + operation.dispatch(); const record = await proxyFetch(PROVIDER_PROJECT, `${path}?fieldManager=${INVENTORY_FIELD_MANAGER}`, { method: 'PATCH', contentType: 'application/json-patch+json', body: [ { op: 'test', path: '/metadata/uid', value: current.metadata.uid }, { op: 'test', path: '/metadata/resourceVersion', value: current.metadata.resourceVersion }, { op: 'replace', path: '/spec/displayName', value: validated.spec.displayName }, { op: 'replace', path: '/spec/provenance', value: validated.spec.provenance }, - ] }); + ] }).catch(error => { operation.assertCurrent(); throw error; }); + operation.assertCurrent(); if (!record?.metadata?.uid) throw new Error('Save outcome could not be confirmed.'); return record; } diff --git a/ui/provider/src/lib/inventory-operation.test.ts b/ui/provider/src/lib/inventory-operation.test.ts new file mode 100644 index 00000000..adc2dd6b --- /dev/null +++ b/ui/provider/src/lib/inventory-operation.test.ts @@ -0,0 +1,81 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { waitFor } from '@testing-library/react'; +import { createInventoryRecord, editInventoryLabel, inventoryPayload, INVENTORY_FIELD_MANAGER } from './inventory-management'; +import { InventoryOperationInvalidated, InventoryOperationScope } from './inventory-operation'; + +const values = { name: 'synthetic-facility', namespace: 'default', displayName: 'Original', recordedBy: 'synthetic-operator', reference: '', facility: 'parent', height: '' }; +const original = { ...inventoryPayload('Facility', values, '2026-01-01T00:00:00Z'), metadata: { name: values.name, namespace: values.namespace, uid: 'synthetic-uid', resourceVersion: '1', managedFields: [{ manager: INVENTORY_FIELD_MANAGER }] } }; +const response = (data: unknown, status = 200) => ({ ok: status < 400, status, json: async () => ({ data }) }); +afterEach(() => vi.unstubAllGlobals()); + +describe('imperative inventory operation authority', () => { + it.each(['facility-review', 'rack-review', 'rack-get', 'edit-review', 'edit-get'])('stops after invalidation during %s without dispatching a write', async stage => { + const scope = new InventoryOperationScope(); + let release: ((value: unknown) => void) | undefined; + const requests = vi.fn(async (url: string, init: RequestInit) => { + const review = url.includes('selfsubjectaccessreviews'); + if ((stage.endsWith('review') && review) || (stage.endsWith('get') && init.method === 'GET')) { + return new Promise(resolve => { release = resolve; }); + } + return response(review ? { status: { allowed: true } } : original); + }); + vi.stubGlobal('fetch', requests); + const pending = stage.startsWith('edit') + ? editInventoryLabel(original, values, scope.begin()) + : createInventoryRecord(stage.startsWith('rack') ? 'Rack' : 'Facility', values, scope.begin()); + const outcome = pending.catch(error => error); + await waitFor(() => expect(release).toBeDefined()); + scope.invalidate(); + release!(response(stage.endsWith('review') ? { status: { allowed: true } } : original)); + expect(await outcome).toBeInstanceOf(InventoryOperationInvalidated); + expect(await outcome).toMatchObject({ dispatched: false }); + expect(requests.mock.calls.filter(([url, init]) => !url.includes('selfsubjectaccessreviews') && init.method !== 'GET')).toEqual([]); + }); + + it.each(['create-success', 'create-error', 'edit-success', 'edit-error'])('keeps invalidated dispatched %s outcomes unknown and never retries', async mode => { + const scope = new InventoryOperationScope(); + let release: ((value: unknown) => void) | undefined; + const requests = vi.fn(async (url: string, init: RequestInit) => { + if (url.includes('selfsubjectaccessreviews')) return response({ status: { allowed: true } }); + if (init.method === 'GET') return response(original); + return new Promise(resolve => { release = resolve; }); + }); + vi.stubGlobal('fetch', requests); + const outcome = (mode.startsWith('edit') + ? editInventoryLabel(original, values, scope.begin()) + : createInventoryRecord('Facility', values, scope.begin())).catch(error => error); + await waitFor(() => expect(release).toBeDefined()); + scope.invalidate(); + release!(response(original, mode.endsWith('error') ? 503 : 200)); + expect(await outcome).toBeInstanceOf(InventoryOperationInvalidated); + expect(await outcome).toMatchObject({ dispatched: true }); + expect((await outcome).message).toMatch(/outcome is unknown/); + expect(requests.mock.calls.filter(([url, init]) => !url.includes('selfsubjectaccessreviews') && init.method !== 'GET')).toHaveLength(1); + }); + + it('never revives earlier operation generations when new sessions start', async () => { + const requests = vi.fn(); + vi.stubGlobal('fetch', requests); + const first = new InventoryOperationScope(); + const pending = first.begin(); + first.invalidate(); + const second = new InventoryOperationScope(); + const later = second.begin(); + second.invalidate(); + new InventoryOperationScope().begin().assertCurrent(); + await expect(createInventoryRecord('Facility', values, pending)).rejects.toMatchObject({ dispatched: false }); + await expect(editInventoryLabel(original, values, later)).rejects.toMatchObject({ dispatched: false }); + await expect(createInventoryRecord('Facility', values, first.begin())).rejects.toMatchObject({ dispatched: false }); + expect(requests).not.toHaveBeenCalled(); + }); + + it('does not revive pending work when Strict Mode restarts a scope lifecycle', () => { + const parent = new InventoryOperationScope(); + const child = new InventoryOperationScope(); + const old = child.begin(parent); + parent.invalidate(); + parent.startLifecycle(); + expect(() => old.assertCurrent()).toThrow(InventoryOperationInvalidated); + expect(() => child.begin(parent).assertCurrent()).not.toThrow(); + }); +}); diff --git a/ui/provider/src/lib/inventory-operation.ts b/ui/provider/src/lib/inventory-operation.ts new file mode 100644 index 00000000..289eda09 --- /dev/null +++ b/ui/provider/src/lib/inventory-operation.ts @@ -0,0 +1,41 @@ +import { createContext } from 'react'; + +export class InventoryOperationInvalidated extends Error { + constructor(readonly dispatched: boolean) { + super(dispatched + ? 'The save outcome is unknown because the session changed after dispatch. Check inventory before another attempt.' + : 'The session or page changed before saving. No write was dispatched. Your input is kept here; return to inventory and reopen the form after checking your session.'); + } +} + +export class InventoryOperationScope { + private active = true; + private generation = 0; + + invalidate() { this.active = false; } + + startLifecycle() { this.generation++; this.active = true; } + + begin(parent?: InventoryOperationScope) { + const generation = this.generation; + const parentGeneration = parent?.generation; + return new InventoryOperation(() => this.active && this.generation === generation && (!parent || (parent.active && parent.generation === parentGeneration))); + } +} + +export const InventoryOperationContext = createContext(undefined); + +export class InventoryOperation { + private dispatched = false; + + constructor(private readonly active: () => boolean) {} + + assertCurrent() { + if (!this.active()) throw new InventoryOperationInvalidated(this.dispatched); + } + + dispatch() { + this.assertCurrent(); + this.dispatched = true; + } +} From 59948e7eb30ab4e7236025cc5fddb15efc366564 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Fri, 20 Nov 2026 17:23:00 -0600 Subject: [PATCH 023/518] fix(inventory): renew operation scope after navigation --- docs/development/staff-inventory-ui.md | 3 + .../inventory-navigation-safety.test.tsx | 166 ++++++++++++++++++ .../components/inventory-session-boundary.tsx | 8 +- 3 files changed, 174 insertions(+), 3 deletions(-) create mode 100644 ui/provider/src/components/inventory-navigation-safety.test.tsx diff --git a/docs/development/staff-inventory-ui.md b/docs/development/staff-inventory-ui.md index 17fecd9e..bba94b8a 100644 --- a/docs/development/staff-inventory-ui.md +++ b/docs/development/staff-inventory-ui.md @@ -149,6 +149,9 @@ resets open forms on session/background boundaries; submit denial while the view remains active still retains safe unsaved input. There is no automatic save or retry when returning to a page. +Completed route navigation starts a new operation scope and query cache, even +when the principal is unchanged. Pending navigation unmounts the inventory view; +old operations stay revoked rather than being reactivated for new forms. Inventory queries are also isolated per mounted view and refresh manually. Known-denied collections are removed from the rendered data, including stale supplied results and related names; diff --git a/ui/provider/src/components/inventory-navigation-safety.test.tsx b/ui/provider/src/components/inventory-navigation-safety.test.tsx new file mode 100644 index 00000000..9017bce8 --- /dev/null +++ b/ui/provider/src/components/inventory-navigation-safety.test.tsx @@ -0,0 +1,166 @@ +import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { createMemoryRouter, Outlet, RouterProvider } from 'react-router'; +import { afterEach, expect, it, vi } from 'vitest'; +import { InventoryManagement } from './inventory-management'; +import { InventorySessionBoundary } from './inventory-session-boundary'; +import DeviceInventoryList from '../pages/device-inventory-list'; +import { inventoryPayload, INVENTORY_FIELD_MANAGER } from '../lib/inventory-management'; + +const values = { name: 'independent-review', namespace: 'default', displayName: 'Original', recordedBy: 'synthetic-reviewer', reference: '', facility: '', height: '' }; +const original = { ...inventoryPayload('Facility', values, '2026-01-01T00:00:00Z'), metadata: { name: values.name, namespace: 'default', uid: 'synthetic-only', resourceVersion: '1', managedFields: [{ manager: INVENTORY_FIELD_MANAGER }] } }; +const response = (data: unknown, status = 200) => ({ ok: status < 400, status, json: async () => ({ data, error: 'PRIVATE DIAGNOSTIC' }) }); +afterEach(() => { cleanup(); vi.unstubAllGlobals(); }); + +it('real directory category Link followed by fresh create remains usable', async () => { + const writes: string[] = []; + vi.stubGlobal('fetch', vi.fn(async (url: string, init: RequestInit) => { + if (url.includes('selfsubjectaccessreviews')) return response({ status: { allowed: true } }); + if (init.method !== 'GET') { writes.push(init.method!); return response(original); } + return response({ items: [] }); + })); + const router = createMemoryRouter([{ id: 'layouts/milo.layout', path: '/', loader: () => ({ user: { metadata: { uid: 'staff-a' } } }), element: , children: [{ index: true, element: }] }]); + render(); + fireEvent.click(await screen.findByRole('link', { name: /Facilities/ })); + await open(false); + fireEvent.click(screen.getByRole('button', { name: 'Create facility record' })); + expect(await screen.findByRole('status')).not.toHaveTextContent('No write was dispatched'); + expect(writes).toEqual(['POST']); +}); + +it.each([false, true])('same-principal query navigation retains usable management authority: edit=%s', async editing => { + const writes: string[] = []; + vi.stubGlobal('fetch', vi.fn(async (url: string, init: RequestInit) => { + if (url.includes('selfsubjectaccessreviews')) return response({ status: { allowed: true } }); + if (init.method !== 'GET') writes.push(init.method!); + return response(original); + })); + const router = createMemoryRouter([{ id: 'layouts/milo.layout', path: '/', loader: () => ({ user: { metadata: { uid: 'staff-a' } } }), element: , children: [{ index: true, element: }] }]); + render(); + await screen.findByRole('button', { name: editing ? 'Edit display name' : 'Create facility' }); + await act(async () => { await router.navigate('/?kind=Facility'); }); + await open(editing); + fireEvent.click(screen.getByRole('button', { name: editing ? 'Save display name' : 'Create facility record' })); + await screen.findByRole('status'); + expect(writes).toEqual([editing ? 'PATCH' : 'POST']); +}); + +it.each([false, true])('navigation revokes pending work while admitting a fresh form: edit=%s', async editing => { + let reviews = 0; + let release: ((value: unknown) => void) | undefined; + const writes: string[] = []; + vi.stubGlobal('fetch', vi.fn(async (url: string, init: RequestInit) => { + if (url.includes('selfsubjectaccessreviews')) { + if (++reviews === 2) return new Promise(resolve => { release = resolve; }); + return response({ status: { allowed: true } }); + } + if (init.method !== 'GET') writes.push(init.method!); + return response(original); + })); + const router = createMemoryRouter([{ id: 'layouts/milo.layout', path: '/', loader: () => ({ user: { metadata: { uid: 'staff-a' } } }), element: , children: [{ index: true, element: }] }]); + render(); + await open(editing); + fireEvent.click(screen.getByRole('button', { name: editing ? 'Save display name' : 'Create facility record' })); + await waitFor(() => expect(release).toBeDefined()); + await act(async () => { await router.navigate('/?kind=Facility&name=independent-review'); }); + await open(editing); + await act(async () => release!(response({ status: { allowed: true } }))); + expect(writes).toEqual([]); + expect(screen.queryByText(/Display name saved\.|Facility record created\./)).not.toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: editing ? 'Save display name' : 'Create facility record' })); + await screen.findByText(editing ? 'Display name saved.' : 'Facility record created.'); + expect(writes).toEqual([editing ? 'PATCH' : 'POST']); +}); + +async function open(editing: boolean) { + const opener = await screen.findByRole('button', { name: editing ? 'Edit display name' : 'Create facility' }); + fireEvent.click(opener); + if (!editing) fireEvent.change(screen.getByLabelText('Record name'), { target: { value: values.name } }); + fireEvent.change(screen.getByLabelText('Display name'), { target: { value: 'Independent safe input' } }); + fireEvent.change(screen.getByLabelText('Recorded by'), { target: { value: values.recordedBy } }); +} + +it.each(['create-review', 'edit-review', 'edit-get', 'create-dispatch', 'edit-dispatch'])('A-B-A session transitions fence old %s while new form remains usable', async mode => { + let principal = 'staff-a'; + let reviews = 0; + let release: ((value: unknown) => void) | undefined; + let intercepted = false; + const writes: string[] = []; + const editing = mode.startsWith('edit'); + vi.stubGlobal('fetch', vi.fn(async (url: string, init: RequestInit) => { + const review = url.includes('selfsubjectaccessreviews'); + if (review) reviews++; + const write = !review && init.method !== 'GET'; + if (write) writes.push(principal); + if (!intercepted && ((mode.endsWith('review') && review && reviews === 2) || (mode.endsWith('get') && init.method === 'GET') || (mode.endsWith('dispatch') && write))) { + intercepted = true; + return new Promise(resolve => { release = resolve; }); + } + return response(review ? { status: { allowed: true } } : original); + })); + const router = createMemoryRouter([{ id: 'layouts/milo.layout', path: '/', loader: () => ({ user: { metadata: { uid: principal } } }), element: , children: [{ index: true, element: }] }]); + render(); + await open(editing); + fireEvent.click(screen.getByRole('button', { name: editing ? 'Save display name' : 'Create facility record' })); + await waitFor(() => expect(release).toBeDefined()); + expect(screen.getByRole('button', { name: 'Close form' })).toBeDisabled(); + principal = 'staff-b'; + await act(async () => { await router.revalidate(); }); + principal = 'staff-a'; + await act(async () => { await router.revalidate(); }); + await open(editing); + await act(async () => release!(response(mode.endsWith('review') ? { status: { allowed: true } } : original))); + expect(writes).toEqual(mode.endsWith('dispatch') ? ['staff-a'] : []); + expect(screen.queryByText(/Display name saved\.|Facility record created\./)).not.toBeInTheDocument(); + expect(screen.getByLabelText('Display name')).toHaveValue('Independent safe input'); + fireEvent.click(screen.getByRole('button', { name: editing ? 'Save display name' : 'Create facility record' })); + await screen.findByText(editing ? 'Display name saved.' : 'Facility record created.'); + expect(writes).toHaveLength(mode.endsWith('dispatch') ? 2 : 1); +}); + +it('closing a conflicted edit and reopening explicitly takes the new baseline', async () => { + let current = original; + const patches: Array> = []; + vi.stubGlobal('fetch', vi.fn(async (url: string, init: RequestInit) => { + if (url.includes('selfsubjectaccessreviews')) return response({ status: { allowed: true } }); + if (init.method === 'PATCH') patches.push(JSON.parse(String(init.body))); + return response(current); + })); + const client = new QueryClient(); + const content = () => ; + const mounted = render(content()); + await open(true); + current = { ...original, metadata: { ...original.metadata, resourceVersion: '2' }, spec: { ...original.spec, displayName: 'Other operator' } }; + mounted.rerender(content()); + fireEvent.click(screen.getByRole('button', { name: 'Save display name' })); + await screen.findByText(/already exists, changed/); + expect(patches).toEqual([]); + fireEvent.click(screen.getByRole('button', { name: 'Close form' })); + fireEvent.click(screen.getByRole('button', { name: 'Edit display name' })); + expect(screen.getByLabelText('Display name')).toHaveValue('Other operator'); + fireEvent.change(screen.getByLabelText('Display name'), { target: { value: 'Reviewed replacement' } }); + fireEvent.click(screen.getByRole('button', { name: 'Save display name' })); + await screen.findByText('Display name saved.'); + expect(patches[0].find(operation => operation.path === '/metadata/resourceVersion')?.value).toBe('2'); +}); + +it.each([401, 403, 404, 503])('submit-time SSAR HTTP %s fails closed for both create and edit', async status => { + for (const editing of [false, true]) { + let reviews = 0; + const writes: string[] = []; + vi.stubGlobal('fetch', vi.fn(async (url: string, init: RequestInit) => { + if (url.includes('selfsubjectaccessreviews')) return response({ status: { allowed: true } }, ++reviews === 1 ? 200 : status); + writes.push(init.method!); + return response(original); + })); + render(); + await open(editing); + fireEvent.click(screen.getByRole('button', { name: editing ? 'Save display name' : 'Create facility record' })); + await screen.findByRole('status'); + expect(writes).toEqual([]); + expect(screen.getByLabelText('Display name')).toHaveValue('Independent safe input'); + expect(screen.getByRole('button', { name: editing ? 'Save display name' : 'Create facility record' })).toBeDisabled(); + expect(screen.queryByText('PRIVATE DIAGNOSTIC')).not.toBeInTheDocument(); + cleanup(); + } +}); diff --git a/ui/provider/src/components/inventory-session-boundary.tsx b/ui/provider/src/components/inventory-session-boundary.tsx index 2eca4841..f8440223 100644 --- a/ui/provider/src/components/inventory-session-boundary.tsx +++ b/ui/provider/src/components/inventory-session-boundary.tsx @@ -1,6 +1,6 @@ import { createContext, useContext, useEffect, useLayoutEffect, useRef, useState, type ReactNode } from 'react'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; -import { UNSAFE_DataRouterContext, UNSAFE_DataRouterStateContext, useRevalidator, useRouteLoaderData } from 'react-router'; +import { UNSAFE_DataRouterContext, UNSAFE_DataRouterStateContext, useLocation, useNavigation, useRevalidator, useRouteLoaderData } from 'react-router'; import { InventoryAccessState } from './inventory-access-state'; import { LoadingState } from './states'; import { InventoryOperationContext, InventoryOperationScope } from '../lib/inventory-operation'; @@ -26,6 +26,8 @@ function SessionQueries({ children, principal }: { children: ReactNode; principa function HostedInventory({ children }: { children: ReactNode }) { const identity = useRouteLoaderData('layouts/milo.layout') as { user?: { metadata?: { uid?: string; name?: string } } } | undefined; const principal = identity?.user?.metadata?.uid ?? identity?.user?.metadata?.name; + const location = useLocation(); + const navigation = useNavigation(); const revalidator = useRevalidator(); const revalidate = useRef(revalidator.revalidate); revalidate.current = revalidator.revalidate; @@ -69,10 +71,10 @@ function HostedInventory({ children }: { children: ReactNode }) { document.removeEventListener('visibilitychange', visibility); }; }, []); - if (checking || revalidator.state !== 'idle') return ; + if (checking || revalidator.state !== 'idle' || navigation.state !== 'idle') return ; if (failed) return ; if (!principal) return ; - return {children}; + return {children}; } export function InventorySessionBoundary({ children }: { children: ReactNode }) { From 239dd31280037eb66e3858583b69ed5fc22c2faa Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Fri, 20 Nov 2026 17:42:10 -0600 Subject: [PATCH 024/518] fix(inventory): fence completed host revalidation generations --- docs/development/staff-inventory-ui.md | 3 + .../inventory-navigation-safety.test.tsx | 7 +- .../inventory-revalidation-safety.test.tsx | 79 +++++++++++++++++++ .../components/inventory-session-boundary.tsx | 16 +++- 4 files changed, 102 insertions(+), 3 deletions(-) create mode 100644 ui/provider/src/components/inventory-revalidation-safety.test.tsx diff --git a/docs/development/staff-inventory-ui.md b/docs/development/staff-inventory-ui.md index bba94b8a..bad4b16f 100644 --- a/docs/development/staff-inventory-ui.md +++ b/docs/development/staff-inventory-ui.md @@ -152,6 +152,9 @@ There is no automatic save or retry when returning to a page. Completed route navigation starts a new operation scope and query cache, even when the principal is unchanged. Pending navigation unmounts the inventory view; old operations stay revoked rather than being reactivated for new forms. +The host router subscription also tracks completed revalidation generations. +Even if React batches loading and idle without rendering a loading screen, +completion replaces the scope and cache; it never renews old operation objects. Inventory queries are also isolated per mounted view and refresh manually. Known-denied collections are removed from the rendered data, including stale supplied results and related names; diff --git a/ui/provider/src/components/inventory-navigation-safety.test.tsx b/ui/provider/src/components/inventory-navigation-safety.test.tsx index 9017bce8..82a973a4 100644 --- a/ui/provider/src/components/inventory-navigation-safety.test.tsx +++ b/ui/provider/src/components/inventory-navigation-safety.test.tsx @@ -45,7 +45,7 @@ it.each([false, true])('same-principal query navigation retains usable managemen expect(writes).toEqual([editing ? 'PATCH' : 'POST']); }); -it.each([false, true])('navigation revokes pending work while admitting a fresh form: edit=%s', async editing => { +it.each([false, true].flatMap(editing => ['navigation', 'revalidation'].map(transition => ({ editing, transition }))))('$transition revokes pending work while admitting a fresh form: edit=$editing', async ({ editing, transition }) => { let reviews = 0; let release: ((value: unknown) => void) | undefined; const writes: string[] = []; @@ -62,7 +62,10 @@ it.each([false, true])('navigation revokes pending work while admitting a fresh await open(editing); fireEvent.click(screen.getByRole('button', { name: editing ? 'Save display name' : 'Create facility record' })); await waitFor(() => expect(release).toBeDefined()); - await act(async () => { await router.navigate('/?kind=Facility&name=independent-review'); }); + await act(async () => { + if (transition === 'revalidation') await router.revalidate(); + else await router.navigate('/?kind=Facility&name=independent-review'); + }); await open(editing); await act(async () => release!(response({ status: { allowed: true } }))); expect(writes).toEqual([]); diff --git a/ui/provider/src/components/inventory-revalidation-safety.test.tsx b/ui/provider/src/components/inventory-revalidation-safety.test.tsx new file mode 100644 index 00000000..f04b2f2a --- /dev/null +++ b/ui/provider/src/components/inventory-revalidation-safety.test.tsx @@ -0,0 +1,79 @@ +import { StrictMode } from 'react'; +import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { createMemoryRouter, Outlet, RouterProvider } from 'react-router'; +import { afterEach, expect, it, vi } from 'vitest'; +import { InventoryManagement } from './inventory-management'; +import { InventorySessionBoundary } from './inventory-session-boundary'; +import { inventoryPayload, INVENTORY_FIELD_MANAGER } from '../lib/inventory-management'; + +const values = { name: 'fresh-test', namespace: 'default', displayName: 'Fresh record', recordedBy: 'reviewer', reference: '', facility: 'fresh-test', height: '' }; +const original = { ...inventoryPayload('Facility', values, '2026-01-01T00:00:00Z'), metadata: { name: values.name, namespace: 'default', uid: 'synthetic', resourceVersion: '1', managedFields: [{ manager: INVENTORY_FIELD_MANAGER }] } }; +const response = (data: unknown) => ({ ok: true, status: 200, json: async () => ({ data }) }); +afterEach(() => { cleanup(); vi.unstubAllGlobals(); }); + +async function open(editing: boolean, rack = false) { + fireEvent.click(await screen.findByRole('button', { name: editing ? 'Edit display name' : rack ? 'Create rack' : 'Create facility' })); + if (!editing) fireEvent.change(screen.getByLabelText('Record name'), { target: { value: values.name } }); + fireEvent.change(screen.getByLabelText('Display name'), { target: { value: 'New input' } }); + fireEvent.change(screen.getByLabelText('Recorded by'), { target: { value: 'reviewer' } }); + if (rack) fireEvent.change(screen.getByLabelText('Facility'), { target: { value: values.name } }); +} + +it.each(['same-url', 'replace', 'back-forward', 'revalidate', 'focus', 'visible', 'pageshow'].flatMap(navigation => [false, true].flatMap(editing => [false, true].map(strict => ({ navigation, editing, strict })))) )('fresh authority after $navigation edit=$editing strict=$strict', async ({ navigation, editing, strict }) => { + const writes: string[] = []; + vi.stubGlobal('fetch', vi.fn(async (url: string, init: RequestInit) => { + if (url.includes('selfsubjectaccessreviews')) return response({ status: { allowed: true } }); + if (init.method !== 'GET') writes.push(init.method!); + return response(original); + })); + const router = createMemoryRouter([{ id: 'layouts/milo.layout', path: '/', loader: () => ({ user: { metadata: { uid: 'staff-a' } } }), element: , children: [{ index: true, element: }] }]); + render(strict ? : ); + await screen.findByRole('button', { name: editing ? 'Edit display name' : 'Create facility' }); + await act(async () => { + if (navigation === 'revalidate') await router.revalidate(); + else if (navigation === 'focus') window.dispatchEvent(new Event('focus')); + else if (navigation === 'visible') document.dispatchEvent(new Event('visibilitychange')); + else if (navigation === 'pageshow') window.dispatchEvent(new PageTransitionEvent('pageshow', { persisted: true })); + else if (navigation === 'back-forward') { await router.navigate('/?kind=Facility'); await router.navigate(-1); await router.navigate(1); } + else await router.navigate('/', { replace: navigation === 'replace' }); + }); + await open(editing); + fireEvent.click(screen.getByRole('button', { name: editing ? 'Save display name' : 'Create facility record' })); + await waitFor(() => expect(writes).toEqual([editing ? 'PATCH' : 'POST'])); + await screen.findByText(editing ? 'Display name saved.' : 'Facility record created.'); +}); + +it.each(['create-review', 'rack-get', 'edit-review', 'edit-get', 'create-dispatch', 'edit-dispatch'])('same-url navigation retires %s and permits only new work', async mode => { + const editing = mode.startsWith('edit'); + const rack = mode.startsWith('rack'); + let reviews = 0; + let release: ((value: unknown) => void) | undefined; + let intercepted = false; + const writes: string[] = []; + vi.stubGlobal('fetch', vi.fn(async (url: string, init: RequestInit) => { + const review = url.includes('selfsubjectaccessreviews'); + if (review) reviews++; + const write = !review && init.method !== 'GET'; + if (write) writes.push(init.method!); + if (!intercepted && ((mode.endsWith('review') && review && reviews === 2) || (mode.endsWith('get') && init.method === 'GET') || (mode.endsWith('dispatch') && write))) { + intercepted = true; + return new Promise(resolve => { release = resolve; }); + } + return response(review ? { status: { allowed: true } } : original); + })); + const router = createMemoryRouter([{ id: 'layouts/milo.layout', path: '/', loader: () => ({ user: { metadata: { uid: 'staff-a' } } }), element: , children: [{ index: true, element: }] }]); + render(); + await open(editing, rack); + const submit = editing ? 'Save display name' : rack ? 'Create rack record' : 'Create facility record'; + fireEvent.click(screen.getByRole('button', { name: submit })); + await waitFor(() => expect(release).toBeDefined()); + await act(async () => { await router.navigate('/'); }); + await open(editing, rack); + await act(async () => release!(response(mode.endsWith('review') ? { status: { allowed: true } } : original))); + expect(writes).toHaveLength(mode.endsWith('dispatch') ? 1 : 0); + expect(screen.queryByText(/Display name saved\.|Facility record created\./)).not.toBeInTheDocument(); + expect(screen.getByLabelText('Display name')).toHaveValue('New input'); + fireEvent.click(screen.getByRole('button', { name: submit })); + await screen.findByText(editing ? 'Display name saved.' : rack ? 'Rack record created.' : 'Facility record created.'); + expect(writes).toHaveLength(mode.endsWith('dispatch') ? 2 : 1); +}); diff --git a/ui/provider/src/components/inventory-session-boundary.tsx b/ui/provider/src/components/inventory-session-boundary.tsx index f8440223..aa7d63ea 100644 --- a/ui/provider/src/components/inventory-session-boundary.tsx +++ b/ui/provider/src/components/inventory-session-boundary.tsx @@ -24,6 +24,20 @@ function SessionQueries({ children, principal }: { children: ReactNode; principa } function HostedInventory({ children }: { children: ReactNode }) { + const host = useContext(UNSAFE_DataRouterContext); + const [hostGeneration, setHostGeneration] = useState(0); + useLayoutEffect(() => { + if (!host) return; + let pending = host.router.state.revalidation !== 'idle' || host.router.state.navigation.state !== 'idle'; + return host.router.subscribe(state => { + if (state.revalidation !== 'idle' || state.navigation.state !== 'idle') { + pending = true; + } else if (pending) { + pending = false; + setHostGeneration(current => current + 1); + } + }); + }, [host]); const identity = useRouteLoaderData('layouts/milo.layout') as { user?: { metadata?: { uid?: string; name?: string } } } | undefined; const principal = identity?.user?.metadata?.uid ?? identity?.user?.metadata?.name; const location = useLocation(); @@ -74,7 +88,7 @@ function HostedInventory({ children }: { children: ReactNode }) { if (checking || revalidator.state !== 'idle' || navigation.state !== 'idle') return ; if (failed) return ; if (!principal) return ; - return {children}; + return {children}; } export function InventorySessionBoundary({ children }: { children: ReactNode }) { From fafc3d2d655b566b9e57d4cf785d0e51f6c4b3f3 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Fri, 20 Nov 2026 22:07:12 -0600 Subject: [PATCH 025/518] feat: align physical inventory UI with hardware design --- docs/development/staff-inventory-ui.md | 432 ++++++++---------- docs/operations/physical-inventory.md | 24 +- ui/provider/README.md | 18 +- .../exact-head-independent.test.tsx | 118 +++++ ui/provider/src/components/fleet-page.tsx | 5 +- .../inventory-hardware-fields.test.tsx | 96 ++++ .../components/inventory-hardware-fields.tsx | 50 ++ .../components/inventory-location.test.tsx | 57 +++ .../src/components/inventory-location.tsx | 64 +++ .../src/components/inventory-management.tsx | 41 +- .../src/components/physical-inventory.css | 54 ++- .../components/physical-inventory.test.tsx | 2 +- .../src/components/physical-inventory.tsx | 121 +++-- .../src/lib/inventory-hardware.test.ts | 94 ++++ ui/provider/src/lib/inventory-hardware.ts | 81 ++++ ui/provider/src/lib/inventory-management.ts | 29 +- 16 files changed, 939 insertions(+), 347 deletions(-) create mode 100644 ui/provider/src/components/exact-head-independent.test.tsx create mode 100644 ui/provider/src/components/inventory-hardware-fields.test.tsx create mode 100644 ui/provider/src/components/inventory-hardware-fields.tsx create mode 100644 ui/provider/src/components/inventory-location.test.tsx create mode 100644 ui/provider/src/components/inventory-location.tsx create mode 100644 ui/provider/src/lib/inventory-hardware.test.ts create mode 100644 ui/provider/src/lib/inventory-hardware.ts diff --git a/docs/development/staff-inventory-ui.md b/docs/development/staff-inventory-ui.md index bad4b16f..40b3e023 100644 --- a/docs/development/staff-inventory-ui.md +++ b/docs/development/staff-inventory-ui.md @@ -1,251 +1,187 @@ -# Staff hardware directory - -Local implementation on the PR94 baseline (`bebb7eba0af040bd1234a736c8a9c8aeee47b5d8`), -not a deployment or a change to inventory ownership. The -[provider plugin](../../ui/provider/README.md) remains the existing staff-portal -Module Federation remote. Contracts come from the current six-kind API, not the -broader [inventory proposal](../proposals/fleet-management/inventory.md). - -## Design direction - -Inspected `/Users/scotwells/Downloads/asset-inventory.pen` as read-only JSON, not -`iam.pen`. Relevant native frames are Physical Devices (`IqwfB`), Locations -(`IReVL`), Site Detail (`fbmDU`), Rack Detail (`Kick4`), Cable Plant (`qLV4T`), and -Rack Elevation (`i8lb9P`). The 1440×900 screens use a compact sidebar, a heading -and description, search/filter row, bordered tables, location drill-downs, and -separate rack/connection detail. Reuse those information patterns within the -existing portal shell rather than introducing the design's second sidebar. - -Pencil `get_app_state` and `read_skill` both failed with -`transport not connected to app: desktop`; no Pencil app was available locally. -Consequently native visual rendering of the source design is **not verified**. -The structural review is not a claim of pixel-faithful implementation. The source -was never written. Its observed SHA-256 is +# Staff physical inventory UI + +Local, uncommitted implementation on `0b6c8977227157575d388a42aac127769258f998` +(PR95 merged into `feat/manual-inventory-records`). This phase does not publish, +deploy, import records, change IAM membership, or change inventory ownership. +The [provider plugin](../../ui/provider/README.md) remains the existing staff-portal +Module Federation remote. The implemented six-kind API, not the broader +[inventory proposal](../proposals/fleet-management/inventory.md), bounds the UI. + +## Native Pencil comparison + +Read and rendered `/Users/scotwells/Downloads/asset-inventory.pen` with Pencil's +native Get, TakeScreenshot and Export tools. No design mutations were made. +Source SHA-256: `1c20996c68b29206597c69ad2bd6b7833854b906427b2ec30d63b6afd0c40590`. -## Implemented locally - -- Hardware-first Devices list, plus Facilities, Racks, Claims, Cables and Power - feeds with actual record counts, search, detail links, and category empty states. -- Kind/namespace/name query links support host navigation without adding exposed - modules. Same-namespace typed references resolve to descriptive labels; missing - references remain visible and never resolve to another namespace's namesake. -- Facilities and racks expose installation plans. A plan's placement remains - planned, not proof of a device's present location. Legacy location strings are - displayed but do not fabricate typed relationships. -- Devices retain serials, asset tags, UUIDs, provider/source identifiers, BMC - endpoint text, typed components, internal mappings, service references, legacy - interfaces/peers, unmapped MACs, and provenance. All registrations remain visible. -- Cable lanes preserve both typed endpoint references and component positions. - Power feeds show supply ratings, terminations, and external upstream references. -- Verification and implementation caveats move into contextual disclosures; - occupancy and power uncertainty remain beside the relevant facts. The optional - report file picker is removed. Inventory editing is not framed as Git-only. -- Existing six-kind API reads, pagination, federation exports, and the old - claim-detail route are retained. Narrow authorized record management is - described below. No sync, provisioning, capacity authorization, IPAM, routing, - or billing behavior is added. -- Local fixture preview now compiles the installed Datum UI theme. The preview - stylesheet is isolated from federated pages; inventory CSS uses host tokens. - -## Management and authorization contract - -The integrated companion IAM role is `fleet.datumapis.com-inventory-manager`, -inheriting `fleet.datumapis.com-inventory-viewer` and adding create/update/patch -for all six kinds. Its empty `physical-inventory-managers` group is bound to -the `datum-cloud` Project, not only the `default` namespace. Existing staff -viewers remain readers. The Fleet role and regression tests are included here; -the infra group/binding patch is separate and has not been applied by this work. -No live membership, grant, or deployed authorization is asserted. The UI never checks -group names or assumes staff membership permits a write. - -Locally implemented management is deliberately narrower than that role: - -- Facility and Rack creation by namespaced POST, without apply or overwrite. - The namespace defaults to `default` but is editable; it is not an IAM boundary. - Rack creation requires an existing same-namespace Facility. Unknown height - remains absent; known height must be a whole number from 1 through 100. -- Display-name edits only for Manual records whose managed fields all belong to - `fleet-staff-inventory-ui`, with no import source, deletion marker, or detected - Flux/Argo/ownership marker. Flux-owned, imported, and unknown-writer records - remain read-only with an ownership-review explanation. IAM grants do not - transfer ownership. A reviewed transition for migrated records remains open. -- Before enabling controls and again before submission, POST a - `SelfSubjectAccessReview` to the provider project's control-plane authorization - API for the exact namespace/resource/name and create or patch verb. Missing, - denied, errored, or unresolved permission reviews fail closed. The actual - inventory API must still authorize the request using the signed-in user's token. -- Edits re-read the record and revalidate ownership, UID and resourceVersion. - JSON Patch tests UID and resourceVersion atomically, changing only displayName - and provenance with a newer recordedAt. Identity, claim binding, placement, - topology and lifecycle fields remain untouched. No delete/status controls exist. -- Submit denial, expiry, and conflicts retain safe input without reporting - success. Ambiguous network/server failures stop repeat submission and ask the - operator to inspect inventory before another attempt. -- Every imperative create/edit requires an operation lease tied to both the form - lifetime and host session generation. The router subscription invalidates it - synchronously when revalidation/navigation begins or identity changes, before - React needs to commit an unmount. Blur, page hide, hidden-document and unmount - boundaries also revoke it. Each awaited permission/record prerequisite is - followed by an authority check before any write dispatch. Revoked work never - dispatches a later POST/PATCH under the next cookie session. -- An already-dispatched write cannot be recalled by invalidating its lease. - Its late response (including success) remains an unknown outcome to the stale - operation. No automatic retry, cancellation-success or late save confirmation - is produced. Refresh and inspect authoritative inventory before another attempt. -- Opening an edit captures a deep copy of its original UID/resourceVersion and - display name. Refreshing props never advances that open form's baseline. A - concurrent change produces a conflict while retaining input; explicitly closing - and reopening starts a new reviewed baseline. - -Host integration was inspected at staff-portal HEAD -`b1489125fe5b77ea6fc379ad378c8e1951174de5` on November 20, 2026: - -- `app/server/routes/internal.ts` accepts all methods under `/api/internal/*`. - `app/server/lib/proxy.ts` forwards method, body, Content-Type and the caller's - bearer token, including SSAR POST, inventory POST and JSON Patch. -- `app/server/middleware/auth.ts` requires an authenticated staff session. - `same-origin.ts` additionally rejects mutation requests without matching - Origin or same-origin fetch metadata. The browser sends ordinary same-origin - requests; the plugin neither manufactures auth headers nor bypasses this check. -- `app/server/response.ts` returns successful data in the `data` envelope with - HTTP 200 and no-store headers, and errors with their actual HTTP status and - `error` string. The plugin does not depend on upstream creation returning 201. -- `app/layouts/milo.layout.tsx` loads `requireStaffUser`, which returns the - authenticated IAM User; the route ID is `layouts/milo.layout` in `app/routes.ts`. - The plugin reads only its metadata UID/name, never tokens or group claims. -- `app/routes/auth/logout.tsx` redirects out of the protected layout; OAuth - login/callback remount it. The host's QueryClient is a module singleton and - is not cleared by logout, so inventory must not reuse its caches across users. - -The existing access-review contract was inspected at cloud-portal commit -`116ffb527a0c4acc1e28257c7b2b686967d46e5c` (access-review resource service/schema -and generated authorization SDK). This verifies source support, not the revision -running in staging or deployed upstream SSAR grants. Live acceptance must verify -the deployed host revision, same-origin configuration and upstream authorization. -No new proxy endpoint or IAM permission is invented by this implementation. - -## Viewing and denial behavior - -Collection results are handled independently. Forbidden categories are hidden; -explicit links to them show calm access guidance, not empty or zero inventory. -Other readable categories remain accessible. Unavailable categories show no -count. Both query-linked details and the existing claim detail route handle -denial. Session expiry (401), access needed (403), unavailable API (404), missing -record, and transient failure have separate plain-language states. No raw proxy -errors, global error toast, invented request-access flow, or automatic retry loop -is introduced. - -Inventory runs under a private QueryClient keyed to the host loader's authenticated -principal, not the host's persistent singleton. Missing host identity fails closed; -the standalone preview explicitly opts into a separate preview context. Principal -changes synchronously replace the query scope. Blur, page hide and hidden-document -events remove inventory and clear its private cache. Focus, visibility restoration -and back-forward-cache restoration revalidate the actual protected host loader -before mounting a fresh inventory view. Pending/failed revalidation cannot render -old records. Focus checks carry a generation and foreground/visibility condition; -obsolete completions cannot undo a later hide or a newer check. This intentionally -resets open forms on session/background boundaries; -submit denial while the view remains active still retains safe unsaved input. -There is no automatic save or retry when returning to a page. - -Completed route navigation starts a new operation scope and query cache, even -when the principal is unchanged. Pending navigation unmounts the inventory view; -old operations stay revoked rather than being reactivated for new forms. -The host router subscription also tracks completed revalidation generations. -Even if React batches loading and idle without rendering a loading screen, -completion replaces the scope and cache; it never renews old operation objects. -Inventory queries are also isolated per mounted view and refresh manually. -Known-denied collections are removed -from the rendered data, including stale supplied results and related names; -global session failure suppresses the inventory. Instantaneous server-side role -revocation while an idle page stays foregrounded is not observable without a -server event; the next read or submit enforces the new result. Live revocation -and total effective grants require integration testing; synthetic checks do not -prove deployed authorization. - -## Deliberate gaps - -| Design capability | Current boundary | +Inspected Physical Devices (`IqwfB`), Locations (`IReVL`), Site Detail (`fbmDU`), +Rack Detail (`Kick4`), Rack Elevation (`i8lb9P`), Cable Plant (`qLV4T`), device +create/edit (`owtU7`, `txtZw`), site registration (`lj6gc`), add-device panel +(`vSVae`), non-racked equipment (`GcX1u`), and cable creation (`zFUzi`). Native +exports of Devices, Rack Detail and Cable Plant are retained locally under +`/tmp/fleet-pencil-reference/`; they are not runtime assets. + +| Design pattern | Before this phase | Local implementation | +| --- | --- | --- | +| Compact heading, search/filter, dense bordered rows | Duplicate Bare Metal and inventory headings; six large kind tiles | Inherited portal tabs, compact category tabs and one section heading; real model/facility/medium filters | +| Location drill-down | Generic record/relationship directory | Facility racks and facility-only equipment; descriptive facility → rack → equipment links | +| Front/rear elevation beside equipment | Placement text only | Recorded plan geometry beside equipment; separate unpositioned and non-unit mounts | +| Device identity and components | Read-only generic details | Hardware registration with typed components; immutable identity preserved in details | +| Cable plant and endpoints | Generic records | Endpoint columns, medium filter, lane details and typed endpoint creation | +| Restrained physical forms | Facility/Rack only | Facility, Rack, installation plan, Device and Cable creation with permission checks | + +The result follows the actual design's information layout, not its invented +operational facts. The host sidebar is not duplicated. Phone layouts stack +sections and keep wide tables internally scrollable. This is not a claim of +pixel identity or completed authenticated staging acceptance. + +## Supported workflows + +- Browse Devices, Facilities, Racks, Installation plans (the API's DeviceClaim), + Cables and Power feeds. Counts are loaded records, not verified hardware. +- Search recorded values; filter by actual model, facility and cable medium. + Namespaced detail links, typed references and historical registrations remain. +- Rack elevation renders only complete, in-range RackUnits plans with a known + front/rear face and known rack height. Blank units are unverified, never free + capacity. Unknown placement stays in the explicit unpositioned section; + NonRackUnitMount remains separate. Multiple registrations do not select an + active device. Overlapping plans are labeled for review, not resolved silently. +- Create Facility/Rack facts; rack height is optional. Create an Installation + plan at a known Facility or Rack with unknown unit position, then separately + register a Device with a real serial or system UUID and typed components. + This is not an atomic multi-record workflow or an adoption operation. +- Create Cable records with a medium and named lanes using existing readable + Device/PowerFeed components with recorded positions. No guessed ports, cable + lengths or live connectivity. Reference owner UID/resourceVersion is retained + and checked before creation; the API still cannot atomically reserve endpoints. +- Edit display name and recording details only for records with established + portal ownership. No device identity, claim binding, components, topology, + placement, lifecycle, status or operational changes are exposed through edit. + +## Authorization, ownership and concurrency + +The existing `fleet.datumapis.com-inventory-manager` role inherits the viewer and +adds create/update/patch for six kinds, project-wide. The UI uses exact-resource +SelfSubjectAccessReviews and the signed-in principal's API request, never group +names or staff membership. Role/binding deployment and membership are separate +work; nothing here asserts their live state. There are no delete/status grants. + +Inventory is direct API/operator-managed, not GitOps-only. Import provenance is +history, **not evidence of Flux ownership**. Legacy Flux-managed records keep +their writer until an explicit safe transition. This UI's deliberately narrow +edit policy still requires Manual provenance and exclusively +`fleet-staff-inventory-ui` managed fields, with no import/deletion/other-owner +markers. Imported and unknown-writer records remain read-only pending an agreed +writer/ownership policy; API authorization alone does not establish a handover. +New authorized API records do not require editing Git. + +Before writes, the UI renews exact create/patch permission. Hardware references +are re-read and checked against selected UID/resourceVersion and lifecycle/type. +Each awaited prerequisite rechecks the operation authority. Edits freeze their +original UID/resourceVersion and use atomic JSON Patch test operations. They do +not silently adopt a refreshed baseline. No automatic write retries occur. + +Existing session protections are retained: principal-isolated QueryClients, +authority invalidation at session/revalidation/navigation/background/unmount +boundaries, fresh authority generations even for React-batched revalidation, +and generation-guarded focus checks. Already-dispatched uncertain outcomes stay +unknown rather than becoming cancelled-success. This phase does not modify the +session-boundary or operation-authority implementations. + +Read-only users browse without enabled writes. No-read and direct-link denials +show calm access guidance, not empty/zero inventory. Partial collection failures +preserve readable sections and do not offer inaccessible references as choices. +401, 403, 404 and transient errors remain distinct. Submit denial retains safe +input, blocks retries and explains the change. Restricted cached records are +removed on an observed denial/session boundary. Reads are manually refreshed; +this is not instantaneous notification of a server-side grant change during an +idle session. Detail pages now offer the same explicit Refresh inventory action. + +### Retained host source evidence + +The prior implementation inspected staff-portal source at +`b1489125fe5b77ea6fc379ad378c8e1951174de5`: `app/server/routes/internal.ts` +accepts methods under `/api/internal/*`; `app/server/lib/proxy.ts` forwards body, +Content-Type and the caller's token, supporting SSAR POST, inventory POST and +JSON Patch. Authentication and same-origin middleware still apply. Successful +responses use an HTTP 200 `data` envelope; failures retain actual HTTP status +and an `error` string. No new proxy method is assumed by the added forms. + +The protected `layouts/milo.layout` loader supplies the IAM User metadata +UID/name. The host QueryClient is a singleton and must not be reused for private +inventory across principals. The existing plugin boundary provides the isolated +cache and synchronous router invalidation. Source support does not prove the +deployed revision, upstream SSAR permission, or authenticated runtime behavior. + +## Deliberate gaps and decisions + +| Interaction | Remaining boundary | +| --- | --- | +| Imported/other-writer edits | Requires a reviewed ownership policy/transition, not a Git-only requirement; do not simply remove guards | +| Rack position entry, move/assign equipment | Not exposed; immutable installation/binding and handover semantics need an explicit workflow. New plan creation records unknown position only | +| PowerFeed creation; component or endpoint edits | API kinds exist, but these forms are not implemented. Existing records remain browsable; no dead action buttons | +| Online/active/connected badges, occupancy/free units, power utilization | No verified evidence projection; never infer health/readiness from inventory | +| Device role/primary IP, cages/maps/address, cable length/color | No matching authoritative fields in the present contract | +| Hosted infrastructure, circuit/service CRUD, provisioning | Out of scope; networking, IPAM, routing and billing remain with their owners | +| Cross-object consistency and endpoint exclusivity | Prerequisite re-reads are not backend transactions/reservations; operators must review duplicates and changed references | +| Authenticated host acceptance | Still unverified. Supplied host pin `b1489125fe5b77ea6fc379ad378c8e1951174de5` uses Router `^8.3.1`; local harness uses Router 7.18.2. No live login was manipulated | + +## Validation and review + +Run from the repository: + +```sh +pnpm --dir ui/provider test +pnpm --dir ui/provider typecheck +pnpm --dir ui/provider build +go test ./internal/api/inventory/... +git diff --check +``` + +Final local results: 278 tests in 20 files, TypeScript check, production build, +and the Go inventory package tests pass. Build warnings concern the existing +transitive undici share and Zod annotation handling; they do not fail the build. +Documentation relative links and whitespace are checked. The 68 independent +tests remain byte-for-byte identical to the supplied review suite. + +The final independent suite from the previously reviewed `239dd312` head is +copied unchanged into `exact-head-independent.test.tsx` (68 cases), alongside +the original adversarial regressions. New tests cover geometry, unknown height, +non-unit mounts, real filters, hardware payloads, typed references, permission +denial, input retention, unavailable prerequisites, and unmount during delayed +endpoint validation. These are regression evidence, not a new independent review. + +Local browser checks use the existing standalone harness with synthetic fixtures +or intercepted `/api/internal` envelopes only. Desktop and 390×844 phone checks +cover compact lists, rack faces/equipment, location and cable links, device and +cable forms, reader/manager controls, denial after submit, partial/no-read states, +session expiry, backend failure, and removed stale identities after observed +denial. Synthetic successful submissions are not live inventory mutations. +Screenshots are local browser artifacts; the original Pencil exports are separate. + +### Local visual evidence + +Screenshots below are in `/Users/scotwells/.t3/userdata/browser-artifacts/` +(synthetic data only, not committed application assets): + +| Check | Screenshot file | | --- | --- | -| Device/Claim/Cable/PowerFeed create/edit, assign device, placement actions | Not implemented. The proposed manager role permits record writes, but safe field/lifecycle forms and ownership transitions remain to be designed. Facility/Rack creation and portal-owned display-name editing are the only write affordances. Deletion is excluded entirely. | -| Online/active/connected badges, verified occupancy, free rack units, power utilization or redundancy | The API has no verification status/evidence projection. Do not infer them from records, dimensions, port count, or ratings. | -| Front/rear rack elevation | Deferred. Planned positions are displayed as text, including partial and non-rack-unit placement; no empty space is depicted as available. | -| Device type filters and primary IP | No authoritative device-role/primary-IP fields in this inventory contract. Models, identifiers and existing management endpoint text are shown instead. | -| Cages, maps, site address, circuit/service CRUD, hosted infrastructure | Not represented by the six-kind API. External service identities remain references, not new Fleet authorities. | -| Audit timeline and active replacement | Provenance and all registrations are visible, but neither constitutes a complete revision history or verified active binding. | -| Native Pencil comparison and real host integration | Pencil desktop connection was unavailable. Browser checks use the existing local harness with synthetic data; production staff-portal authentication/proxy and deployment are not exercised. | - -## Validation - -From `ui/provider`, run `pnpm test`, `pnpm typecheck`, and `pnpm build`. -For local browser checks: `VITE_FLEET_FIXTURES=true pnpm dev --port 7796`, then -open the Inventory tab. Synthetic data is explicitly labeled and includes all -six kinds. No live inventory calls are made in fixture mode. - -Local checks after review fixes: 121 tests in 14 files pass; typecheck and production build pass. -The inventory Go package tests validate the exact manager/viewer/editor grants. -Both ordinary and race-enabled package tests pass. -The build reports transitive undici sharing and Zod annotation warnings; these -do not fail the build. Federation exposes retain scoped inventory CSS without -the standalone preview's global theme stylesheet. - -Tests cover category navigation, filtering, empty/missing records, typed links, -same-namespace relationship resolution (not namespace authorization isolation), -historical registrations, components, uncertainty, no-read/read-only/manager -states, direct links, partial denial, stale denied data, session expiry, backend -failure, exact access reviews, submit revocation, ownership and revision changes. - -Synthetic browser checks exercise facility → rack → claim → device and cable → -feed, search and details at 1280/1440 desktop widths and 390×844 phone size. -Additional intercepted requests verify reader controls are unavailable, manager -creation succeeds only with an acknowledged response, revoked submit retains -input without a write, and subsequent read denial removes visible records. -Desktop/mobile access-needed states, detail-route partial denial, session expiry, -404 and transient failure are checked without raw error leakage or page-wide -horizontal overflow. No live write was made. The standalone harness uses an -in-memory router; direct entry paths are also covered in route tests. - -After adding session isolation, browser checks mounted the production boundary -under a synthetic host-shaped data router (not the preview bypass). Switching -authenticated loader identity from a reader to a denied principal removed all -previous device names; blur/focus with an expired identity produced the calm -sign-in state without stale data. A synthetic authorized JSON Patch updated the -facility name; changing its writer to Flux then removed editing controls. These -checks used the real plugin and intercepted proxy envelopes, at desktop and -390×844 phone size, without a live host session or inventory mutation. - -## Review and rollout gates - -This branch targets `feat/manual-inventory-records` at -`bebb7eba0af040bd1234a736c8a9c8aeee47b5d8`. Publication is authorized; merge and -deployment remain with the parent after independent adversarial review and CI. -The manager role must be deployed before the separate infrastructure group -binding. This work does not import records, add memberships, or modify infra. -Validate the deployed staff-portal revision and authenticated loader ID/shape, -SSAR availability, same-origin proxy configuration, reader/manager/denied users, -session switching and actual upstream denials before accepting staging rollout. -Neither the offline IAM tests nor the intercepted browser harness proves live -authorization. Native Pencil fidelity remains a design gap, not an IAM gate. - -These are local checks, not evidence of deployed availability, authorization, -hardware verification, or a completed native Pencil visual comparison. - -### Adversarial review regressions - -The independent suite against `0673b82f073ab065327192a14c74d2dc6720b003` -was copied into `ui/provider/src/components/adversarial-review.test.tsx` with -its original assertions intact. Before fixes it reproduced three failures and -one passing no-read check. All now pass; additional tests cover same-tick router -invalidation before React commits, create/edit permission and GET prerequisites, -blur/unmount, repeated session generations, Strict Mode lifecycle restart, -already-dispatched success/failure remaining unknown, frozen edit conflicts, -and out-of-order focus completions. - -Synthetic browser replay independently delayed the create SSAR, switched the -host principal and released the review: zero writes dispatched. An edit opened -at revision 1 retained input while props/API advanced to revision 2: zero patches -and a calm conflict state. A delayed focus revalidation completed after a second -blur without restoring inventory; a new focus restored it only after a fresh -check. Desktop/mobile checks used intercepted requests only. These fixes await -a new independent review; passing local regressions are not self-approval. +| Before: generic directory | `browser-screenshot-localhost-mwpst023-01d6f601.png` | +| After: compact desktop devices | `browser-screenshot-localhost-mwptcps2-5bac903c.png` | +| After: desktop rack and equipment | `browser-screenshot-127-0-0-1-mwpvdwjl-dfeb7d93.png` | +| After: mobile devices | `browser-screenshot-127-0-0-1-mwpv9qeo-18b6794c.png` | +| After: mobile device form | `browser-screenshot-127-0-0-1-mwpvb96u-707e61d0.png` | +| After: mobile rack faces | `browser-screenshot-127-0-0-1-mwpvcnqw-6a677229.png` | +| Detail read revocation, desktop | `browser-screenshot-127-0-0-1-mwpvf3ib-0af0ac53.png` | +| Detail read revocation, mobile | `browser-screenshot-127-0-0-1-mwpvfer9-fdda9c70.png` | + +Keyboard search and Tab navigation, Enter on the rear-face control, facility → +rack and cable → device links were checked. Explicit detail refresh after a +synthetic 403 removed the restricted device name while retaining other categories. +Mobile lists, forms and rack views had no page-wide horizontal overflow. These +checks do not replace screen-reader testing or authenticated host acceptance. + +The tested local diff requires a **new independent adversarial review** before +publication. No commit, push, PR, merge, deployment or live mutation is authorized +in this implementation phase. Authenticated staging integration, including host +principal changes and proxy enforcement, remains a release acceptance check. diff --git a/docs/operations/physical-inventory.md b/docs/operations/physical-inventory.md index 3123c6b0..ffe06975 100644 --- a/docs/operations/physical-inventory.md +++ b/docs/operations/physical-inventory.md @@ -133,11 +133,14 @@ authenticated, complete NIC mapping before any network path depends on it. ## Manually record a small installation -1. Choose the provider project and namespace, and inspect its existing private - inventory source. In staging, `fleet-provider-inventory` reconciles +1. Choose the provider project and namespace, and inspect existing records and + their writers. The legacy staging `fleet-provider-inventory` reconciles `apps/fleet-system/staging/provider-inventory` with `prune: false` and - `deletionPolicy: Orphan`. Flux is the sole API writer. Do not run a parallel - `kubectl apply`, importer, scheduled job, or discovery controller. + `deletionPolicy: Orphan`. Flux remains the sole writer of those legacy records + until an explicit ownership transition. Do not run a competing apply/import + against them. New and separately imported inventory can be direct + API/operator-managed; GitOps is not required. Establish the authorized writer + per record before making changes; import provenance is not Flux ownership. 2. Enter the Facility and Rack facts you actually know. Record the operator and time with `provenance.method: Manual`. Leave unknown dimensions absent. Rack membership is not a reserved footprint or evidence of available space. @@ -156,11 +159,14 @@ authenticated, complete NIC mapping before any network path depends on it. cable endpoint, and potential duplicate against existing records. API validation cannot enforce cross-object existence or exclusive endpoints. Preserve existing names, Device identities, claim bindings and MachineCapacity references. -6. Review the private Git diff with another operator. It must contain no status, - capacity publication, hardware action, deletion or ownership transfer. Submit - only the individually approved records through the established Flux source. - After reconciliation, compare the intended records with read-only API and - staff views. An interrupted or failed reconciliation is not readiness. +6. Review the intended record changes with another operator. They must contain + no status, capacity publication, hardware action, deletion or implicit + ownership transfer. Submit individually approved new records through the + authorized API/operator workflow; use the established Flux source for records + still owned by Flux. Compare acknowledged writes with read-only API and staff + views. An interrupted or uncertain request is unknown, not failed or ready; + inspect the record before retrying. Portal forms expose only the subset + documented in the [staff UI scope](../development/staff-inventory-ui.md). The [complete synthetic six-record example](../../hack/testdata/physical/manual.yaml) shows this workflow without NetBox or credentials. It includes a partial rack diff --git a/ui/provider/README.md b/ui/provider/README.md index d280c50e..1b37d70a 100644 --- a/ui/provider/README.md +++ b/ui/provider/README.md @@ -94,11 +94,13 @@ occupancy, power budgets, and ambiguous bindings stay unknown. Contextual help explains these boundaries; there is no report picker, automatic import, sync, or hardware action. Reads require the provider-scoped inventory viewer role, not a consumer Metal role. Management separately checks backend create/patch permission -in the provider project: Facility/Rack creation and portal-owned display-name -editing only. The proposed `fleet.datumapis.com-inventory-manager` role and -`physical-inventory-managers` group binding are separate IAM work, not deployed -by this UI. Group names/staff membership never enable controls. Flux/imported -records remain read-only pending ownership review. Namespace choice is not an +in the provider project: Facility/Rack/Installation-plan/Device/Cable creation +and portal-owned display-name editing. The existing +`fleet.datumapis.com-inventory-manager` role and separate +`physical-inventory-managers` group binding are not deployed by this UI phase. +Group names/staff membership never enable controls. Flux/imported/unknown-writer +records remain read-only pending ownership review; import provenance does not +mean Git ownership. New inventory is direct API/operator-managed. Namespace choice is not an authorization boundary. Denied collections and detail links show access guidance, not empty inventory; readable sections remain available. See [hardware directory scope and design gaps](../../docs/development/staff-inventory-ui.md). @@ -110,8 +112,10 @@ still supplies its design system. Inventory-specific CSS is scoped under navigation is introduced. Fixture mode includes all six inventory kinds with explicitly synthetic identities and no verified state. -- staff-portal runs react-router 7, so this plugin pins it for types and - shares it with `requiredVersion: false`. +- The local harness pins react-router 7.18.2 and shares it with + `requiredVersion: false`. The supplied current host pin uses Router ^8.3.1; + authenticated host integration remains an acceptance check, not proven by + local harness tests. - staff-portal shares only the `badge`, `button`, `card`, `icons` and `skeleton` datum-ui subpaths. Everything else, including the data table, is bundled, so its peer packages are runtime dependencies here. diff --git a/ui/provider/src/components/exact-head-independent.test.tsx b/ui/provider/src/components/exact-head-independent.test.tsx new file mode 100644 index 00000000..dee349cc --- /dev/null +++ b/ui/provider/src/components/exact-head-independent.test.tsx @@ -0,0 +1,118 @@ +import { StrictMode } from 'react'; +import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { createMemoryRouter, Outlet, RouterProvider } from 'react-router'; +import { afterEach, expect, it, vi } from 'vitest'; +import { InventoryManagement } from './inventory-management'; +import { InventorySessionBoundary } from './inventory-session-boundary'; +import { inventoryPayload, INVENTORY_FIELD_MANAGER } from '../lib/inventory-management'; +import DeviceInventoryList from '../pages/device-inventory-list'; + +const values = { name: 'exact-review', namespace: 'default', displayName: 'Original', recordedBy: 'synthetic', reference: '', facility: '', height: '' }; +const original = { ...inventoryPayload('Facility', values, '2026-01-01T00:00:00Z'), metadata: { name: values.name, namespace: 'default', uid: 'synthetic', resourceVersion: '1', managedFields: [{ manager: INVENTORY_FIELD_MANAGER }] } }; +const response = (data: unknown, status = 200) => ({ ok: status < 400, status, json: async () => ({ data }) }); +afterEach(() => { cleanup(); vi.unstubAllGlobals(); }); + +async function open(editing: boolean, label: string) { + fireEvent.click(await screen.findByRole('button', { name: editing ? 'Edit display name' : 'Create facility' })); + if (!editing) fireEvent.change(screen.getByLabelText('Record name'), { target: { value: values.name } }); + fireEvent.change(screen.getByLabelText('Display name'), { target: { value: label } }); + fireEvent.change(screen.getByLabelText('Recorded by'), { target: { value: 'synthetic' } }); +} + +it.each([false, true].flatMap(strict => [false, true].flatMap(editing => ['review', 'dispatch-ok', 'dispatch-error'].flatMap(stage => ['fast-repeat', 'slow', 'overlap', 'cancel-navigation', 'focus-blur'].map(transition => ({ strict, editing, stage, transition }))))))('independent $transition $stage edit=$editing strict=$strict', async ({ strict, editing, stage, transition }) => { + let submitting = false; + let intercepted = false; + let releaseOperation: ((value: unknown) => void) | undefined; + let holdLoader = false; + const loaders: (() => void)[] = []; + const writes: string[] = []; + vi.stubGlobal('fetch', vi.fn(async (url: string, init: RequestInit) => { + const review = url.includes('selfsubjectaccessreviews'); + const write = !review && init.method !== 'GET'; + if (write) writes.push(init.method!); + if (submitting && !intercepted && ((stage === 'review' && review) || (stage !== 'review' && write))) { + intercepted = true; + return new Promise(resolve => { releaseOperation = resolve; }); + } + return response(review ? { status: { allowed: true } } : original); + })); + const router = createMemoryRouter([{ id: 'layouts/milo.layout', path: '/', loader: async () => { + if (holdLoader) await new Promise(resolve => loaders.push(resolve)); + return { user: { metadata: { uid: 'same-user' } } }; + }, element: , children: [{ index: true, element: }] }]); + render(strict ? : ); + await open(editing, 'Old input'); + const submit = editing ? 'Save display name' : 'Create facility record'; + submitting = true; + fireEvent.click(screen.getByRole('button', { name: submit })); + await waitFor(() => expect(releaseOperation).toBeDefined()); + if (transition === 'fast-repeat') { + await act(async () => { await router.revalidate(); await router.revalidate(); await router.revalidate(); }); + } else { + holdLoader = true; + act(() => { if (transition === 'focus-blur') window.dispatchEvent(new Event('focus')); else if (transition === 'cancel-navigation') void router.navigate('/?kind=Rack'); else void router.revalidate(); }); + await waitFor(() => expect(loaders).toHaveLength(1)); + expect(screen.queryByLabelText('Display name')).not.toBeInTheDocument(); + if (transition === 'focus-blur') { + fireEvent(window, new Event('blur')); + await act(async () => loaders[0]()); + expect(screen.queryByLabelText('Display name')).not.toBeInTheDocument(); + expect(screen.queryByRole('button', { name: 'Create facility' })).not.toBeInTheDocument(); + holdLoader = false; + await act(async () => window.dispatchEvent(new Event('focus'))); + } else if (transition === 'overlap' || transition === 'cancel-navigation') { + act(() => { if (transition === 'cancel-navigation') void router.navigate('/?kind=Facility'); else void router.revalidate(); }); + await waitFor(() => expect(loaders).toHaveLength(2)); + await act(async () => loaders[1]()); + await act(async () => loaders[0]()); + holdLoader = false; + } else { + await act(async () => loaders[0]()); + holdLoader = false; + } + } + await open(editing, 'Fresh input'); + await act(async () => releaseOperation!(response(stage === 'review' ? { status: { allowed: true } } : original, stage === 'dispatch-error' ? 503 : 200))); + expect(writes).toHaveLength(stage === 'review' ? 0 : 1); + expect(screen.queryByText(/Display name saved\.|Facility record created\./)).not.toBeInTheDocument(); + expect(screen.getByLabelText('Display name')).toHaveValue('Fresh input'); + fireEvent.click(screen.getByRole('button', { name: submit })); + await screen.findByText(editing ? 'Display name saved.' : 'Facility record created.'); + expect(writes).toHaveLength(stage === 'review' ? 1 : 2); + router.dispose(); +}); + +it.each([false, true].flatMap(strict => [401, 403, 404, 503].map(status => ({ strict, status }))))('late previous cache never overrides new denial $status strict=$strict', async ({ strict, status }) => { + let phase = 'initial'; + const releases: (() => void)[] = []; + const freshRequests: string[] = []; + const privateRecord = { ...original, spec: { ...original.spec, displayName: 'Private facility label' } }; + vi.stubGlobal('fetch', vi.fn(async (url: string, init: RequestInit) => { + if (phase === 'denied') { + freshRequests.push(init.method!); + return response(undefined, status); + } + if (url.includes('selfsubjectaccessreviews')) return response({ status: { allowed: true } }); + const result = response({ items: url.includes('/facilities?') ? [privateRecord] : [] }); + if (phase === 'pending') return new Promise(resolve => releases.push(() => resolve(result))); + return result; + })); + const router = createMemoryRouter([{ id: 'layouts/milo.layout', path: '/', loader: () => ({ user: { metadata: { uid: 'same-user' } } }), element: , children: [{ index: true, element: }] }], { initialEntries: ['/?kind=Facility'] }); + render(strict ? : ); + await screen.findByRole('link', { name: /Private facility label/ }); + await screen.findByRole('button', { name: 'Create facility' }); + phase = 'pending'; + fireEvent.click(screen.getByRole('button', { name: 'Refresh inventory' })); + await waitFor(() => expect(releases).toHaveLength(6)); + phase = 'denied'; + await act(async () => { await router.revalidate(); await router.revalidate(); }); + const title = status === 401 ? 'Your session has expired' : status === 403 ? 'Inventory access needed' : status === 404 ? 'Inventory section unavailable' : 'Inventory is temporarily unavailable'; + await screen.findByRole('heading', { name: title }); + await act(async () => releases.forEach(release => release())); + expect(screen.getByRole('heading', { name: title })).toBeInTheDocument(); + expect(screen.queryByText('Private facility label')).not.toBeInTheDocument(); + expect(screen.queryByRole('button', { name: 'Create facility' })).not.toBeInTheDocument(); + expect(freshRequests.length).toBeGreaterThanOrEqual(6); + expect(freshRequests.every(method => method === 'GET')).toBe(true); + router.dispose(); +}); diff --git a/ui/provider/src/components/fleet-page.tsx b/ui/provider/src/components/fleet-page.tsx index 6776a46d..0426b8ac 100644 --- a/ui/provider/src/components/fleet-page.tsx +++ b/ui/provider/src/components/fleet-page.tsx @@ -28,14 +28,15 @@ export function FleetPage({ { label: 'Inventory', href: `${base}/inventory` }, ]; const active = tabs.slice(1).find((t) => pathname.startsWith(t.href))?.href ?? base; + const inventory = pathname.startsWith(`${base}/inventory`); return (
- + />}
diff --git a/ui/provider/src/components/inventory-hardware-fields.test.tsx b/ui/provider/src/components/inventory-hardware-fields.test.tsx new file mode 100644 index 00000000..19c8d8d0 --- /dev/null +++ b/ui/provider/src/components/inventory-hardware-fields.test.tsx @@ -0,0 +1,96 @@ +import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { afterEach, expect, it, vi } from 'vitest'; +import { InventoryManagement } from './inventory-management'; +import { fixturePhysicalClaims, fixturePhysicalDevices, fixturePhysicalRecords } from '../lib/fixtures'; + +const claim = { ...fixturePhysicalClaims[0], metadata: { ...fixturePhysicalClaims[0].metadata, uid: 'plan-uid', resourceVersion: '1' }, spec: { ...fixturePhysicalClaims[0].spec, lifecycle: 'Installation' as const } }; +const device = { ...fixturePhysicalDevices[0], metadata: { ...fixturePhysicalDevices[0].metadata, uid: 'device-uid', resourceVersion: '1' } }; +const feed = { ...fixturePhysicalRecords[2], metadata: { ...fixturePhysicalRecords[2].metadata, uid: 'feed-uid', resourceVersion: '1' } }; +const response = (data: unknown, status = 200) => ({ ok: status < 400, status, json: async () => ({ data }) }); +afterEach(() => vi.unstubAllGlobals()); +function renderForm(kind: 'Device' | 'Cable') { + return render(); +} +async function open(kind: 'Device' | 'Cable') { + fireEvent.click(screen.getByText(`Manage ${kind.toLowerCase()}s`)); + fireEvent.click(await screen.findByRole('button', { name: `Create ${kind.toLowerCase()}` })); + for (const [label, value] of [['Record name', 'synthetic-new'], ['Display name', 'Synthetic record'], ['Recorded by', 'synthetic-operator']]) fireEvent.change(screen.getByLabelText(label), { target: { value } }); +} +it('registers hardware through the real form without changing claim identity', async () => { + const writes: unknown[] = []; + vi.stubGlobal('fetch', vi.fn(async (url: string, init: RequestInit) => { + if (url.includes('selfsubjectaccessreviews')) return response({ status: { allowed: true } }); + if (init.method === 'GET') return response(claim); + writes.push(JSON.parse(init.body as string)); return response({ metadata: { uid: 'new-uid' } }); + })); + renderForm('Device'); await open('Device'); + fireEvent.change(screen.getByLabelText('Installation plan'), { target: { value: 'plan-uid' } }); + fireEvent.change(screen.getByLabelText('Model'), { target: { value: 'Recorded model' } }); + fireEvent.change(screen.getByLabelText('Serial number'), { target: { value: 'SYNTHETIC-NEW' } }); + fireEvent.click(screen.getByRole('button', { name: 'Add component' })); + fireEvent.change(screen.getByLabelText('Component 1 id'), { target: { value: 'nic-1' } }); + fireEvent.change(screen.getByLabelText('Component 1 name'), { target: { value: 'NIC port 1' } }); + fireEvent.click(screen.getByRole('button', { name: 'Create device record' })); + await screen.findByText('Device record created.'); + expect(writes).toHaveLength(1); + expect(writes[0]).toMatchObject({ kind: 'Device', spec: { claimRef: { name: claim.metadata.name }, identity: { serial: 'SYNTHETIC-NEW' }, components: [{ id: 'nic-1', type: 'NetworkPort' }] } }); +}); +it('uses typed feed and device endpoints and retains input on submit denial', async () => { + let reviews = 0; + const writes: unknown[] = []; + vi.stubGlobal('fetch', vi.fn(async (url: string, init: RequestInit) => { + if (url.includes('selfsubjectaccessreviews')) return response({ status: { allowed: ++reviews === 1 } }); + writes.push(init); return response({}); + })); + renderForm('Cable'); await open('Cable'); + fireEvent.change(screen.getByLabelText('Cable medium'), { target: { value: 'Power' } }); + const select = (label: string, contains: string) => { const control = screen.getByLabelText(label) as HTMLSelectElement; const option = [...control.options].find(item => item.text.includes(contains))!; fireEvent.change(control, { target: { value: option.value } }); }; + select('Lane 1 end A', 'Feed A'); select('Lane 1 end B', 'Power supply 1'); + fireEvent.click(screen.getByRole('button', { name: 'Create cable record' })); + await screen.findByText(/Your management permission changed/); + expect(screen.getByLabelText('Display name')).toHaveValue('Synthetic record'); + expect(screen.getByRole('button', { name: 'Create cable record' })).toBeDisabled(); + expect(writes).toEqual([]); +}); +it('does not offer unknown or inaccessible endpoint positions', async () => { + vi.stubGlobal('fetch', vi.fn().mockResolvedValue(response({ status: { allowed: true } }))); + render(); + await open('Cable'); + expect((screen.getByLabelText('Lane 1 end A') as HTMLSelectElement).options).toHaveLength(1); +}); +it('does not present an unreadable installation collection as an empty device prerequisite', async () => { + vi.stubGlobal('fetch', vi.fn().mockResolvedValue(response({ status: { allowed: true } }))); + render(); + fireEvent.click(screen.getByText('Manage devices')); + await waitFor(() => expect(screen.queryByText('Checking management access…')).not.toBeInTheDocument()); + expect(screen.getByText(/Related records are unavailable, not empty/)).toBeInTheDocument(); + expect(screen.queryByRole('button', { name: 'Create device' })).not.toBeInTheDocument(); +}); +it('keeps readable cable endpoint choices with a partial-access explanation', async () => { + vi.stubGlobal('fetch', vi.fn().mockResolvedValue(response({ status: { allowed: true } }))); + render(); + await open('Cable'); + expect(screen.getByText(/Some endpoint records are unavailable/)).toBeInTheDocument(); + expect((screen.getByLabelText('Lane 1 end A') as HTMLSelectElement).options.length).toBeGreaterThan(1); + expect(screen.queryByRole('option', { name: /Feed A/ })).not.toBeInTheDocument(); +}); +it('revokes a pending cable form on unmount before delayed endpoint validation completes', async () => { + let release: ((data: unknown) => void) | undefined; + const writes: unknown[] = []; + vi.stubGlobal('fetch', vi.fn(async (url: string, init: RequestInit) => { + if (url.includes('selfsubjectaccessreviews')) return response({ status: { allowed: true } }); + if (init.method === 'GET') return new Promise(resolve => { release = resolve; }); + writes.push(init); return response({}); + })); + const mounted = renderForm('Cable'); await open('Cable'); + fireEvent.change(screen.getByLabelText('Cable medium'), { target: { value: 'Power' } }); + for (const [label, text] of [['Lane 1 end A', 'Feed A'], ['Lane 1 end B', 'Power supply 1']]) { + const select = screen.getByLabelText(label) as HTMLSelectElement; + fireEvent.change(select, { target: { value: [...select.options].find(option => option.text.includes(text))!.value } }); + } + fireEvent.click(screen.getByRole('button', { name: 'Create cable record' })); + await waitFor(() => expect(release).toBeDefined()); mounted.unmount(); + await act(async () => { release!(response(feed)); }); + expect(writes).toEqual([]); +}); diff --git a/ui/provider/src/components/inventory-hardware-fields.tsx b/ui/provider/src/components/inventory-hardware-fields.tsx new file mode 100644 index 00000000..8e37e17c --- /dev/null +++ b/ui/provider/src/components/inventory-hardware-fields.tsx @@ -0,0 +1,50 @@ +import type { Device, DeviceClaim, PhysicalComponent, PhysicalRecord } from '../../../shared/fleet-api'; +import { cableMedia, componentTypes, isTermination, type ReferencedEndpoint } from '../lib/inventory-hardware'; +import type { InventoryFormValues } from '../lib/inventory-management'; + +export function InventoryHardwareFields({ kind, values, onChange, namespace, claims, devices, feeds, locations }: { kind: 'Device' | 'Cable' | 'DeviceClaim'; values: InventoryFormValues; onChange: (values: InventoryFormValues) => void; namespace: string; claims: DeviceClaim[]; devices: Device[]; feeds: PhysicalRecord[]; locations: PhysicalRecord[] }) { + const field = (name: keyof InventoryFormValues, value: unknown) => onChange({ ...values, [name]: value }); + if (kind === 'DeviceClaim') return
New installation plan + +
{([['manufacturer', 'Expected manufacturer'], ['model', 'Expected model'], ['serial', 'Expected serial (optional)']] as const).map(([name, label]) => )}
+

This records a new installation at a facility or rack with position unknown. It reserves no units and moves no existing equipment. Placement is immutable; corrections require a separately reviewed handover.

+
; + if (kind === 'Device') return <> +
Installation & identity + +

Identity and installation binding cannot be changed later. Existing registrations are kept; this does not replace hardware or identify the active device. Legacy slot bindings are not offered.

+
{([['manufacturer', 'Manufacturer'], ['model', 'Model'], ['serial', 'Serial number'], ['systemUUID', 'System UUID'], ['assetTag', 'Asset tag']] as const).map(([name, label]) => )}
+

A real serial or system UUID is required. Leave unknown values blank; do not use an asset tag or provider ID as a serial.

+
+
Physical components

Record physical ports and parts only. Empty means not recorded, not absent. No logical interfaces or IP assignments.

+ {(values.components ?? []).map((component, index) =>
+
{(['id', 'name', 'connector'] as const).map(name => )} + + +
+
)} + +
+ ; + const endpoints: { key: string; label: string; endpoint: ReferencedEndpoint }[] = []; + for (const record of [...devices, ...feeds]) { + if (record.metadata.namespace !== namespace || !record.metadata.uid || !record.metadata.resourceVersion || record.metadata.deletionTimestamp) continue; + const device = 'identity' in record.spec; + const components = device ? (record as Device).spec.components : (record as PhysicalRecord).spec.terminations; + for (const component of components ?? []) { + if (!isTermination(component) || !component.positions) continue; + for (let position = 1; position <= Math.min(component.positions, 256); position++) { + const endpoint: ReferencedEndpoint = { kind: device ? 'Device' : 'PowerFeed', name: record.metadata.name, uid: record.metadata.uid, resourceVersion: record.metadata.resourceVersion, componentID: component.id, position }; + endpoints.push({ key: JSON.stringify(endpoint), label: `${record.spec.displayName || record.metadata.name} / ${component.name} · ${component.type} · ${position}`, endpoint }); + } + } + } + const lanes = values.cableLanes ?? [{ id: 'lane-1' }]; + return <> + +
Physical endpoints

Only readable recorded ports with known positions are offered. Review existing cable connections before saving. Recording a cable does not reserve ports or verify a working link.

+ {lanes.map((lane, index) =>
{(['a', 'b'] as const).map(side => )}
{lanes.length > 1 && }
)} + +
+ ; +} diff --git a/ui/provider/src/components/inventory-location.test.tsx b/ui/provider/src/components/inventory-location.test.tsx new file mode 100644 index 00000000..3f2dd22b --- /dev/null +++ b/ui/provider/src/components/inventory-location.test.tsx @@ -0,0 +1,57 @@ +import { fireEvent, render, screen, within } from '@testing-library/react'; +import { expect, it } from 'vitest'; +import { MemoryRouter } from 'react-router'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { PhysicalInventory } from './physical-inventory'; +import { toInventory } from '../inventory'; +import { fixturePhysicalClaims, fixturePhysicalDevices, fixturePhysicalRecords } from '../lib/fixtures'; + +const rack = fixturePhysicalRecords[1]; +function show(placement = fixturePhysicalClaims[0].spec.placement, issues = {}, height: number | null = 42) { + const claim = { ...fixturePhysicalClaims[0], spec: { ...fixturePhysicalClaims[0].spec, placement } }; + return render(); +} +it('renders recorded front/rear plans, never free units or occupancy percentages', () => { + show(); + const front = screen.getByRole('list', { name: 'front recorded plans' }); + expect(within(front).getByRole('link', { name: /Review Server installation/ })).toBeInTheDocument(); + expect(screen.queryByText(/%|available units|Online/)).not.toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: 'Rear' })); + expect(screen.queryByRole('list', { name: 'front recorded plans' })).not.toBeInTheDocument(); + expect(screen.getByRole('list', { name: 'rear recorded plans' })).toBeInTheDocument(); +}); +it.each([ + { scope: 'RackMembership' as const, rackRef: { name: 'rack-01' } }, + { scope: 'RackUnits' as const, rackRef: { name: 'rack-01' }, position: 45, height: 1, face: 'front' as const }, + { scope: 'RackUnits' as const, rackRef: { name: 'rack-01' }, position: 12, height: 1 }, +])('keeps incomplete or out-of-range geometry out of the elevation: %j', placement => { + show(placement); + expect(within(screen.getByRole('list', { name: 'front recorded plans' })).queryByRole('link')).not.toBeInTheDocument(); + const section = screen.getByRole('heading', { name: /Unpositioned equipment/ }).parentElement!; + expect(within(section).getByRole('link', { name: 'Example compute server' })).toBeInTheDocument(); +}); +it('separates non-unit mounts rather than consuming rack units', () => { + show({ scope: 'NonRackUnitMount', rackRef: { name: 'rack-01' }, mount: 'left-rail' }); + const section = screen.getByRole('heading', { name: /Non-racked mounts/ }).parentElement!; + expect(within(section).getByText('left-rail')).toBeInTheDocument(); + expect(within(screen.getByRole('list', { name: 'front recorded plans' })).queryByRole('link')).not.toBeInTheDocument(); +}); +it('does not disguise denied installation collections as empty geometry', () => { + show(undefined, { DeviceClaim: { status: 403 } }); + expect(screen.getByText(/This is not an empty rack/)).toBeInTheDocument(); + expect(screen.queryByRole('list', { name: 'front recorded plans' })).not.toBeInTheDocument(); + expect(screen.queryByText('Example compute server')).not.toBeInTheDocument(); +}); +it('does not invent rack units when the rack height is unknown', () => { + show(undefined, {}, null); + expect(screen.queryByRole('list', { name: 'front recorded plans' })).not.toBeInTheDocument(); +}); +it('filters by recorded model and facility without manufacturing a hardware type', () => { + render(); + fireEvent.change(screen.getByRole('combobox', { name: 'Filter by model' }), { target: { value: 'Example 1U' } }); + expect(screen.queryByRole('link', { name: 'orphan-synthetic-0009' })).not.toBeInTheDocument(); + fireEvent.change(screen.getByRole('combobox', { name: 'Filter by facility' }), { target: { value: 'default/example-facility' } }); + expect(screen.getByRole('link', { name: 'Example compute server' })).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: 'Clear filters' })); + expect(screen.getByRole('link', { name: 'orphan-synthetic-0009' })).toBeInTheDocument(); +}); diff --git a/ui/provider/src/components/inventory-location.tsx b/ui/provider/src/components/inventory-location.tsx new file mode 100644 index 00000000..c58eec5b --- /dev/null +++ b/ui/provider/src/components/inventory-location.tsx @@ -0,0 +1,64 @@ +import { useState } from 'react'; +import { Link } from 'react-router'; +import { slotKey, type Inventory, type InventorySlot } from '../inventory'; +import type { PhysicalRecord } from '../../../shared/fleet-api'; + +export function inventoryHref(kind: string, namespace?: string, name?: string) { + const params = new URLSearchParams({ kind }); + if (name !== undefined) { params.set('record', name); params.set('namespace', namespace ?? ''); } + return `?${params}`; +} + +export function rackGeometry(slot: InventorySlot, rack: PhysicalRecord) { + const placement = slot.claim.spec.placement; + const { position, height, face } = placement; + if (placement.scope !== 'RackUnits' || !Number.isInteger(position) || !Number.isInteger(height) || !position || !height || position < 1 || height < 1 || !rack.spec.heightUnits || position + height - 1 > rack.spec.heightUnits || (face !== 'front' && face !== 'rear')) return undefined; + return { position, height, face }; +} + +function Equipment({ slots, devicesDenied }: { slots: InventorySlot[]; devicesDenied: boolean }) { + return
+ {slots.map(slot => )} +
EquipmentInstallation planRecorded placement
{devicesDenied ? 'Device details unavailable' : slot.devices.length ? slot.devices.map(device =>
{device.spec.displayName || device.metadata.name}
) : 'No device registration recorded'}{slot.devices.length > 1 && Multiple registrations · active device unknown}
{slot.claim.spec.displayName || slot.claim.metadata.name}{slot.claim.spec.placement.scope === 'NonRackUnitMount' ? slot.claim.spec.placement.mount || 'Mount not recorded' : slot.claim.spec.placement.scope === 'RackUnits' ? `U${slot.claim.spec.placement.position ?? '?'} · ${slot.claim.spec.placement.height ?? '?'}U · ${slot.claim.spec.placement.face ?? 'Face unknown'}` : 'Position not recorded'}
; +} + +export function RackOverview({ rack, inventory }: { rack: PhysicalRecord; inventory: Inventory }) { + const [face, setFace] = useState<'both' | 'front' | 'rear'>('both'); + const slots = inventory.slots.filter(slot => slot.claim.metadata.namespace === rack.metadata.namespace && slot.claim.spec.placement.rackRef?.name === rack.metadata.name); + const positioned = slots.filter(slot => rackGeometry(slot, rack)); + const nonRacked = slots.filter(slot => slot.claim.spec.placement.scope === 'NonRackUnitMount'); + const unpositioned = slots.filter(slot => !rackGeometry(slot, rack) && slot.claim.spec.placement.scope !== 'NonRackUnitMount'); + const denied = !!inventory.issues?.DeviceClaim; + const devicesDenied = !!inventory.issues?.Device; + const height = rack.spec.heightUnits; + return
+ +
+

Equipment & installation plans

+ {denied ?

Installation details unavailable. This is not an empty rack.

: <> +

Positioned plans {positioned.length}

{positioned.length ? :

No complete in-range unit positions recorded.

}
+

Unpositioned equipment {unpositioned.length}

{unpositioned.length ? :

No unpositioned plans recorded for this rack.

}
+

Non-racked mounts {nonRacked.length}

{nonRacked.length ? :

No side, rail, or other non-unit mounts recorded.

}
+ {!slots.length &&

No related records found. This does not establish that equipment is absent.

} + } +
+
; +} + +export function FacilityOverview({ facility, inventory }: { facility: PhysicalRecord; inventory: Inventory }) { + const racks = inventory.physical.filter(record => record.kind === 'Rack' && record.metadata.namespace === facility.metadata.namespace && record.spec.facilityRef?.name === facility.metadata.name); + const facilityOnly = inventory.slots.filter(slot => slot.claim.metadata.namespace === facility.metadata.namespace && slot.claim.spec.placement.scope === 'Facility' && slot.claim.spec.placement.facilityRef?.name === facility.metadata.name); + return

Racks

{inventory.issues?.Rack ?

Rack details unavailable. The facility's rack count is unknown.

: racks.length ?
{racks.map(rack => )}
RackRecorded heightInstallation plansAvailable space
{rack.spec.displayName || rack.metadata.name}{rack.spec.heightUnits ? `${rack.spec.heightUnits}U` : 'Not recorded'}{inventory.issues?.DeviceClaim ? 'Unavailable' : inventory.slots.filter(slot => slot.claim.metadata.namespace === rack.metadata.namespace && slot.claim.spec.placement.rackRef?.name === rack.metadata.name).length}Not verified
:

No racks recorded in this facility.

} +

Equipment without a recorded rack

{inventory.issues?.DeviceClaim ?

Installation details unavailable.

: facilityOnly.length ? :

No facility-only installation plans recorded.

} +
; +} diff --git a/ui/provider/src/components/inventory-management.tsx b/ui/provider/src/components/inventory-management.tsx index 7de8de6a..5ed01201 100644 --- a/ui/provider/src/components/inventory-management.tsx +++ b/ui/provider/src/components/inventory-management.tsx @@ -2,11 +2,13 @@ import { useContext, useLayoutEffect, useRef, useState, type FormEvent } from 'r import { useQueryClient } from '@tanstack/react-query'; import { Button } from '@datum-cloud/datum-ui/button'; import { ApiError, PLUGIN_ID, PROVIDER_PROJECT } from '../lib/api'; -import { canEditInventoryLabel, createInventoryRecord, editInventoryLabel, useInventoryPermission, type InventoryFormValues, type ManagedKind } from '../lib/inventory-management'; -import type { PhysicalRecord } from '../../../shared/fleet-api'; +import { canEditInventoryLabel, createInventoryRecord, editInventoryLabel, useInventoryPermission, type InventoryFormValues, type ManagedKind, type ManagedRecord } from '../lib/inventory-management'; +import type { Device, DeviceClaim, PhysicalRecord } from '../../../shared/fleet-api'; import { InventoryOperationContext, InventoryOperationInvalidated, InventoryOperationScope } from '../lib/inventory-operation'; +import { InventoryHardwareFields } from './inventory-hardware-fields'; +import type { Inventory } from '../inventory'; -export function InventoryManagement({ kind, record, facilities }: { kind: ManagedKind; record?: PhysicalRecord; facilities: PhysicalRecord[] }) { +export function InventoryManagement({ kind, record, facilities, claims = [], devices = [], feeds = [], racks = [], compact = false, issues }: { kind: ManagedKind; record?: ManagedRecord; facilities: PhysicalRecord[]; claims?: DeviceClaim[]; devices?: Device[]; feeds?: PhysicalRecord[]; racks?: PhysicalRecord[]; compact?: boolean; issues?: Inventory['issues'] }) { const client = useQueryClient(); const sessionScope = useContext(InventoryOperationContext); const scope = useRef(new InventoryOperationScope()); @@ -25,17 +27,19 @@ export function InventoryManagement({ kind, record, facilities }: { kind: Manage document.removeEventListener('visibilitychange', visibility); }; }, []); - const [baseline, setBaseline] = useState(); + const [baseline, setBaseline] = useState(); const [namespace, setNamespace] = useState(record?.metadata.namespace ?? 'default'); const editable = !record || canEditInventoryLabel(record); const permission = useInventoryPermission(kind, editable ? namespace : '', record ? 'patch' : 'create', record?.metadata.name); - const allowed = permission.data === true && !permission.isFetching && !permission.error && editable; + const dependenciesUnavailable = !record && ((kind === 'Device' && !!issues?.DeviceClaim) || (kind === 'Rack' && !!issues?.Facility) || (kind === 'DeviceClaim' && !!issues?.Facility && !!issues?.Rack) || (kind === 'Cable' && !!issues?.Device && !!issues?.PowerFeed)); + const allowed = permission.data === true && !permission.isFetching && !permission.error && editable && !dependenciesUnavailable; const [open, setOpen] = useState(false); const [pending, setPending] = useState(false); const [blocked, setBlocked] = useState(false); const [message, setMessage] = useState(''); const [values, setValues] = useState({ name: record?.metadata.name ?? '', namespace, displayName: record?.spec.displayName ?? '', recordedBy: '', reference: '', facility: '', height: '' }); const field = (name: keyof InventoryFormValues, value: string) => setValues(previous => ({ ...previous, [name]: value })); + const kindLabel = kind === 'DeviceClaim' ? 'installation plan' : kind.toLowerCase(); async function save(event: FormEvent) { event.preventDefault(); if (!allowed || pending || blocked) return; @@ -54,35 +58,46 @@ export function InventoryManagement({ kind, record, facilities }: { kind: Manage else if (error instanceof ApiError && error.status === 403) { setMessage('Your management permission changed. Your input is kept here. Ask your administrator for access before trying again.'); setBlocked(true); } else if (error instanceof ApiError && error.status === 401) { setMessage('Your session expired. Your input is kept here. Sign in through the staff portal before continuing.'); setBlocked(true); } else if (error instanceof ApiError && error.status === 409) { setMessage('The record already exists, changed, or has another writer. Your input is kept here. Refresh and review the record before continuing.'); setBlocked(true); } + else if (error instanceof ApiError && error.status === 404) { setMessage('A referenced record is no longer available. Your input is kept here. Refresh inventory and review the references before continuing.'); setBlocked(true); } else if (error instanceof ApiError && error.status === 422) setMessage('The API could not accept these values. Review the fields and try again.'); else { setMessage('The save outcome is unknown. Your input is kept here. Check inventory before attempting another save; do not assume the change failed.'); setBlocked(true); } } finally { setPending(false); } } - return
- Manage {record ? 'this record' : `${kind === 'Facility' ? 'facilities' : 'racks'}`} + const Container = compact ? 'section' : 'details'; + const Access = compact ? 'details' : 'div'; + return + {!compact && Manage {record ? 'this record' : `${kind === 'Facility' ? 'facilities' : `${kindLabel}s`}`}} +
+ {compact && {record ? 'Editing access' : 'Namespace & access'}} {!record && } - {!editable ?

This record has another or unknown writer. It needs an explicit ownership review before portal editing. No ownership changes are made here.

: permission.isFetching ?

Checking management access…

: permission.error instanceof ApiError && permission.error.status === 401 ?

Your session expired. Sign in again through the staff portal before continuing. Unsaved input remains here.

: !allowed &&

Viewing and management access are separate. Ask your administrator about physical-inventory management access. A permission check must succeed before changes are available.

} + {dependenciesUnavailable &&

Related records are unavailable, not empty. Creation needs readable location, installation, or endpoint records. Ask your administrator about viewing access, or try again after a temporary failure.

} + {!editable ?

This record has another or unknown writer. It needs an explicit ownership review before portal editing. Import provenance is history, not Git ownership; this portal has not established a writable handover for this record. No ownership changes are made here.

: permission.isFetching ?

Checking management access…

: permission.error instanceof ApiError && permission.error.status === 401 ?

Your session expired. Sign in again through the staff portal before continuing. Unsaved input remains here.

: !allowed &&

Viewing and management access are separate. Ask your administrator about physical-inventory management access. A permission check must succeed before changes are available.

} +
{allowed && !open && } + }}> {record ? 'Edit display name' : `Create ${kindLabel}`} } +
{open &&

{record ? 'Only the display name and recording details change. Identity, placement, geometry, connections, and history remain untouched.' : 'Create a physical record only. This does not verify equipment, reserve space, or provision hardware.'}

{!record && } + {!record && (kind === 'Device' || kind === 'Cable' || kind === 'DeviceClaim') && } + {!record && kind === 'Cable' && (issues?.Device || issues?.PowerFeed) &&

Some endpoint records are unavailable. Only readable equipment and power feeds are offered; missing choices do not mean those records are absent.

} + {!record && kind === 'DeviceClaim' && (issues?.Facility || issues?.Rack) &&

Some location records are unavailable. Only readable facilities and racks are offered; missing choices do not mean those records are absent.

} {!record && kind === 'Rack' && <>

Leave height blank if unknown. A rack record does not establish free space.

}

The recorder is an attributed observation, not a replacement for the API audit identity of your signed-in account.

- -
+ +
} {message &&

{message}

} -
; + ; } diff --git a/ui/provider/src/components/physical-inventory.css b/ui/provider/src/components/physical-inventory.css index bee1b3ce..933c2fd9 100644 --- a/ui/provider/src/components/physical-inventory.css +++ b/ui/provider/src/components/physical-inventory.css @@ -7,22 +7,24 @@ .inventory-eyebrow { font-size:10px; font-weight:600; letter-spacing:.12em; color:var(--muted-foreground,#667571); margin-bottom:6px!important; } .inventory-muted,.fleet-inventory small,.fleet-inventory dt { color:var(--muted-foreground,#667571); } .inventory-readonly { border:1px solid var(--border,#dce3df); border-radius:6px; padding:4px 10px; white-space:nowrap; font-size:12px; } -.inventory-sections { display:grid; grid-template-columns:repeat(6,minmax(0,1fr)); gap:8px; } -.inventory-sections a { display:flex; align-items:center; gap:10px; padding:16px 12px; border:1px solid var(--border,#dce3df); border-radius:8px; text-decoration:none!important; color:inherit; background:var(--card,#fff); } +.inventory-sections { display:flex; gap:4px; flex-wrap:wrap; border-bottom:1px solid var(--border,#dce3df); padding-bottom:8px; } +.inventory-sections a { display:flex; align-items:center; gap:7px; padding:7px 10px; border:1px solid transparent; border-radius:6px; text-decoration:none!important; color:inherit; font-size:12px; } .inventory-sections a[aria-current] { border-color:var(--primary,#264b42); background:var(--accent,#eaf1ed); } -.inventory-sections strong { margin-left:auto; font-size:18px; } +.inventory-sections strong { font-size:11px; font-weight:500; opacity:.7; } .inventory-sections svg { flex-shrink:0; } -.inventory-body { display:flex; flex-direction:column; gap:20px; padding:24px; min-width:0; } +.inventory-body { display:flex; flex-direction:column; gap:16px; min-width:0; } .inventory-search { display:flex; align-items:center; gap:10px; border:1px solid var(--border,#dce3df); border-radius:6px; padding:9px 12px; max-width:520px; } .inventory-search input { min-width:0; width:100%; background:transparent; border:0; font:inherit; color:inherit; outline:none; } .inventory-search:focus-within { outline:2px solid var(--ring,#547f6f); outline-offset:2px; } .fleet-inventory a { color:inherit; text-decoration:underline; text-underline-offset:3px; } .fleet-inventory a:hover { color:var(--primary,#264b42); } .fleet-inventory a:focus-visible,.fleet-inventory summary:focus-visible,.fleet-inventory button:focus-visible { outline:2px solid var(--ring,#547f6f); outline-offset:3px; } +.fleet-inventory h2[tabindex="-1"]:focus { outline:none; } +.inventory-scroll:focus-visible { outline:2px solid var(--ring,#547f6f); outline-offset:3px; } .inventory-scroll { overflow:auto; border:1px solid var(--border,#dce3df); border-radius:8px; } .fleet-inventory table { width:100%; border-collapse:collapse; text-align:left; font-size:13px; } .fleet-inventory th { font-size:12px; font-weight:500; background:var(--muted,#f5f7f5); color:var(--foreground,#182b2a); } -.fleet-inventory th,.fleet-inventory td { padding:14px 16px; border-bottom:1px solid var(--border,#dce3df); vertical-align:top; min-width:140px; max-width:380px; overflow-wrap:anywhere; } +.fleet-inventory th,.fleet-inventory td { padding:9px 14px; border-bottom:1px solid var(--border,#dce3df); vertical-align:top; min-width:120px; max-width:380px; overflow-wrap:anywhere; } .fleet-inventory tr:last-child td { border-bottom:0; } .fleet-inventory tbody tr:hover { background:var(--muted,#f8faf8); } .fleet-inventory td a { font-weight:500; } @@ -41,11 +43,49 @@ .inventory-related li { display:grid; grid-template-columns:120px 1fr 1fr; gap:12px; padding:12px; border:1px solid var(--border,#dce3df); border-radius:6px; overflow-wrap:anywhere; } .inventory-empty { display:flex; flex-direction:column; align-items:center; gap:12px; padding:48px 20px; text-align:center; color:var(--muted-foreground,#667571); } .inventory-empty button { cursor:pointer; padding:8px 16px; border:1px solid var(--border,#dce3df); border-radius:6px; color:var(--foreground,#182b2a); } -.inventory-management { display:block; max-width:680px; } +.inventory-management { display:block; } .inventory-management > [role="status"] { margin-top:16px; } .inventory-management label { display:flex; flex-direction:column; gap:6px; margin:12px 0; } .inventory-management input,.inventory-management select { padding:9px 12px; background:var(--card,#fff); color:var(--foreground,#182b2a); border:1px solid var(--border,#dce3df); border-radius:6px; } .inventory-management input:focus-visible,.inventory-management select:focus-visible { outline:2px solid var(--ring,#547f6f); outline-offset:2px; } -.inventory-form { display:flex; flex-direction:column; gap:10px; margin-top:16px; } +.inventory-form { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:12px 24px; margin-top:16px; padding:20px; border:1px solid var(--border,#dce3df); border-radius:10px; background:var(--card,#fff); } +.inventory-form > p,.inventory-form > div,.inventory-form > fieldset { grid-column:1/-1; } +.inventory-toolbar { display:flex; gap:10px; align-items:center; flex-wrap:wrap; } +.inventory-toolbar .inventory-search { flex:1; max-width:none; min-width:200px; } +.inventory-toolbar select { padding:9px 12px; border:1px solid var(--border,#dce3df); border-radius:6px; background:var(--card,#fff); font:inherit; max-width:100%; } +.inventory-rack-layout { display:grid; grid-template-columns:minmax(280px, .9fr) minmax(0,1.7fr); gap:24px; align-items:start; } +.inventory-elevation { border:1px solid var(--border,#dce3df); border-radius:10px; padding:16px; display:grid; gap:12px; background:var(--card,#fff); } +.inventory-elevation p { font-size:12px; } +.inventory-rack-faces { display:flex; gap:10px; } +.inventory-rack-faces > div { flex:1; min-width:0; } +.inventory-rack-faces h4 { text-align:center; text-transform:uppercase; font-size:11px; letter-spacing:.06em; margin-bottom:8px; } +.inventory-rack-units { list-style:none; padding:0; margin:0; border:1px solid var(--border,#dce3df); } +.inventory-rack-units li { height:16px; display:grid; grid-template-columns:28px 1fr; border-bottom:1px solid var(--border,#dce3df); font-size:9px; line-height:15px; } +.inventory-rack-units li > span { padding:0 3px; background:var(--muted,#f5f7f5); } +.inventory-rack-units li > div { min-width:0; padding:0 3px; display:flex; } +.inventory-rack-units li a { display:block; flex:1; min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; } +.inventory-unit-recorded { background:var(--accent,#eaf1ed); } +.inventory-face-switch { display:flex; gap:4px; } +.inventory-face-switch button { flex:1; padding:6px; border:1px solid var(--border,#dce3df); border-radius:5px; font-size:12px; cursor:pointer; } +.inventory-face-switch button[aria-pressed=true] { background:var(--accent,#eaf1ed); font-weight:600; } +.inventory-equipment-sections { display:grid; gap:16px; min-width:0; } +.inventory-equipment-sections section { display:grid; gap:10px; } +.inventory-count { font-size:11px; color:var(--muted-foreground,#667571); font-weight:400; } +.inventory-form fieldset { border-top:1px solid var(--border,#dce3df); padding-top:12px; min-width:0; } +.inventory-form legend { font-weight:600; } +.inventory-topline { display:grid; grid-template-columns:minmax(0,1fr) auto; align-items:start; gap:12px 24px; } +.inventory-management-compact { display:contents; } +.inventory-management-compact .inventory-management-controls { display:flex; gap:12px; align-items:start; justify-content:flex-end; } +.inventory-management-compact .inventory-management-access { border:0; padding:0; font-size:12px; max-width:320px; } +.inventory-management-compact .inventory-management-access[open] { padding:12px; border:1px solid var(--border,#dce3df); border-radius:6px; } +.inventory-management-compact .inventory-form,.inventory-management-compact > [role=status] { grid-column:1/-1; } +@media(max-width:800px) { .inventory-topline { grid-template-columns:1fr; } .inventory-management-compact .inventory-management-controls { justify-content:flex-start; } } +.inventory-form-grid { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:0 20px; } +.inventory-component-editor { border:1px solid var(--border,#dce3df); padding:12px; border-radius:6px; margin:12px 0; } +.inventory-form input,.inventory-form select { min-width:0; width:100%; } +@media(max-width:600px) { .inventory-form-grid { grid-template-columns:1fr; } } +@media(max-width:600px) { .fleet-inventory th,.fleet-inventory td { min-width:180px; } .inventory-topline .inventory-list-heading { flex-wrap:wrap; flex-direction:row; align-items:center; } .inventory-topline .inventory-list-heading > div { flex:1 1 100%; } } +@media(max-width:900px) { .inventory-rack-layout { grid-template-columns:1fr; } .inventory-elevation { max-width:560px; width:100%; } } +@media(max-width:600px) { .inventory-form { grid-template-columns:1fr; padding:16px; } .inventory-sections a { padding:6px 8px!important; } .inventory-body { padding:0!important; } } @media(max-width:1100px) { .inventory-sections { grid-template-columns:repeat(3,minmax(0,1fr)); } } @media(max-width:600px) { .inventory-sections { grid-template-columns:repeat(2,minmax(0,1fr)); } .inventory-fields { grid-template-columns:1fr; } .inventory-body { padding:16px; } .inventory-heading,.inventory-list-heading { align-items:flex-start; flex-direction:column; } .inventory-related li { grid-template-columns:1fr; gap:4px; } .inventory-sections a { padding:12px; font-size:12px; } } diff --git a/ui/provider/src/components/physical-inventory.test.tsx b/ui/provider/src/components/physical-inventory.test.tsx index 4e754261..42f77131 100644 --- a/ui/provider/src/components/physical-inventory.test.tsx +++ b/ui/provider/src/components/physical-inventory.test.tsx @@ -51,7 +51,7 @@ describe('hardware directory', () => { it('offers six navigable kinds without writes or a report upload', () => { const { container } = browse(); const navigation = within(screen.getByRole('navigation', { name: 'Inventory categories' })); - for (const name of ['Devices', 'Facilities', 'Racks', 'Claims', 'Cables', 'Power feeds']) expect(navigation.getByRole('link', { name: new RegExp(name) })).toBeInTheDocument(); + for (const name of ['Devices', 'Facilities', 'Racks', 'Installation plans', 'Cables', 'Power feeds']) expect(navigation.getByRole('link', { name: new RegExp(name) })).toBeInTheDocument(); expect(screen.queryByRole('button', { name: /create|edit|delete|apply|sync|import/i })).not.toBeInTheDocument(); expect(container.querySelector('input[type="file"]')).toBeNull(); expect(screen.queryByText(/GitOps|Flux/)).not.toBeInTheDocument(); diff --git a/ui/provider/src/components/physical-inventory.tsx b/ui/provider/src/components/physical-inventory.tsx index e92c2d1e..3d1a086f 100644 --- a/ui/provider/src/components/physical-inventory.tsx +++ b/ui/provider/src/components/physical-inventory.tsx @@ -1,6 +1,5 @@ import { useEffect, useRef, useState, type ReactNode } from 'react'; import { Link, useSearchParams } from 'react-router'; -import { Card, CardContent } from '@datum-cloud/datum-ui/card'; import { Building2, Cable, ClipboardList, HardDrive, Search, Server, Zap } from 'lucide-react'; import { modelLabel, @@ -14,6 +13,8 @@ import type { CableEndpoint, PhysicalComponent, PhysicalRecord } from '../../../ import './physical-inventory.css'; import { InventoryAccessState } from './inventory-access-state'; import { InventoryManagement } from './inventory-management'; +import type { ManagedKind, ManagedRecord } from '../lib/inventory-management'; +import { FacilityOverview, RackOverview, inventoryHref as href } from './inventory-location'; type Kind = 'Device' | 'Facility' | 'Rack' | 'DeviceClaim' | 'Cable' | 'PowerFeed'; type RecordEntry = { kind: Kind; record: RawDevice | RawDeviceClaim | PhysicalRecord }; @@ -38,7 +39,7 @@ const sections = [ }, { kind: 'DeviceClaim', - title: 'Claims', + title: 'Installation plans', icon: ClipboardList, description: 'Installation plans, kept separate from physical hardware.', }, @@ -64,15 +65,6 @@ function recordName(entry: RecordEntry) { return entry.record.spec.displayName || entry.record.metadata.name; } -function href(kind: Kind, namespace?: string, name?: string) { - const params = new URLSearchParams({ kind }); - if (name !== undefined) { - params.set('record', name); - params.set('namespace', namespace ?? ''); - } - return `?${params}`; -} - function Field({ label, children }: { label: string; children: ReactNode }) { return (
@@ -136,6 +128,8 @@ export function PhysicalInventory({ inventory: source, onRetry }: { inventory: I }; const [params] = useSearchParams(); const [search, setSearch] = useState(''); + const [locationFilter, setLocationFilter] = useState(''); + const [modelFilter, setModelFilter] = useState(''); const heading = useRef(null); const section = sections.find((item) => item.kind === params.get('kind')) ?? sections.find(item => !inventory.issues?.[item.kind]) ?? sections[0]; const entries: RecordEntry[] = [ @@ -154,6 +148,8 @@ export function PhysicalInventory({ inventory: source, onRetry }: { inventory: I ); useEffect(() => { setSearch(''); + setLocationFilter(''); + setModelFilter(''); if (selectedName !== null) heading.current?.focus(); }, [section.kind, selectedName, selectedNamespace]); const find = (kind: Kind, namespace: string | undefined, name: string) => @@ -185,8 +181,8 @@ export function PhysicalInventory({ inventory: source, onRetry }: { inventory: I location.facilityRef?.name ?? (rack?.record as PhysicalRecord | undefined)?.spec.facilityRef?.name; const facility = facilityName ? find('Facility', claim.metadata.namespace, facilityName) : undefined; const parts = [ - facility ? recordName(facility) : facilityName, - rack ? recordName(rack) : location.rackRef?.name, + inventory.issues?.Facility ? 'Facility unavailable' : facility ? recordName(facility) : facilityName, + inventory.issues?.Rack ? 'Rack unavailable' : rack ? recordName(rack) : location.rackRef?.name, ]; if (location.scope === 'Facility') parts.push('Rack not recorded'); if (location.scope === 'RackMembership') parts.push('Position not recorded'); @@ -232,7 +228,17 @@ export function PhysicalInventory({ inventory: source, onRetry }: { inventory: I return 'Physical premises'; }; const records = entries.filter((entry) => entry.kind === section.kind); + const locationKey = (entry: RecordEntry) => { + const claim = entry.kind === 'Device' ? claimFor(entry.record as RawDevice)?.claim : entry.kind === 'DeviceClaim' ? entry.record as RawDeviceClaim : undefined; + const rackName = claim?.spec.placement.rackRef?.name ?? (entry.record as PhysicalRecord).spec.rackRef?.name; + const rack = rackName && !inventory.issues?.Rack ? find('Rack', entry.record.metadata.namespace, rackName)?.record as PhysicalRecord | undefined : undefined; + const facilityName = claim?.spec.placement.facilityRef?.name ?? (entry.record as PhysicalRecord).spec.facilityRef?.name ?? rack?.spec.facilityRef?.name; + return facilityName ? slotKey(entry.record.metadata.namespace, facilityName) : ''; + }; + const modelKey = (entry: RecordEntry) => entry.kind === 'Device' ? (entry.record as RawDevice).spec.identity.model : entry.kind === 'Cable' ? (entry.record as PhysicalRecord).spec.medium ?? '' : ''; + const filterOptions = [...new Set(records.map(modelKey).filter(Boolean))].sort(); const matching = records + .filter(entry => (!locationFilter || locationKey(entry) === locationFilter) && (!modelFilter || modelKey(entry) === modelFilter)) .filter((entry) => `${JSON.stringify(entry.record)} ${placement(entry)}` .toLowerCase() @@ -300,18 +306,27 @@ export function PhysicalInventory({ inventory: source, onRetry }: { inventory: I const target = candidate.record as PhysicalRecord; if (target.kind === 'Cable') return target.spec.lanes?.some((lane) => - [lane.a, lane.b].some((endpoint) => - kind === 'Device' + [lane.a, lane.b].some((endpoint) => { + if ((kind === 'Rack' || kind === 'Facility') && endpoint.deviceRef) { + const targetDevice = find('Device', namespace, endpoint.deviceRef.name)?.record as RawDevice | undefined; + const location = targetDevice && claimFor(targetDevice)?.claim.spec.placement; + const rack = location?.rackRef && find('Rack', namespace, location.rackRef.name)?.record as PhysicalRecord | undefined; + return kind === 'Rack' ? location?.rackRef?.name === record.metadata.name : location?.facilityRef?.name === record.metadata.name || rack?.spec.facilityRef?.name === record.metadata.name; + } + return kind === 'Device' ? endpoint.deviceRef?.name === record.metadata.name - : kind === 'PowerFeed' && endpoint.powerFeedRef?.name === record.metadata.name, - ), + : kind === 'PowerFeed' && endpoint.powerFeedRef?.name === record.metadata.name; + }), ); return kind === 'Facility' ? target.spec.facilityRef?.name === record.metadata.name : kind === 'Rack' && target.spec.rackRef?.name === record.metadata.name; }); + const relatedRecords = kind === 'Facility' || kind === 'Rack' ? related.filter(item => item.kind === 'Cable' || item.kind === 'PowerFeed') : related; return ( <> + {kind === 'Facility' && } + {kind === 'Rack' && }
{record.metadata.name} {namespace || 'Not recorded'} @@ -321,7 +336,7 @@ export function PhysicalInventory({ inventory: source, onRetry }: { inventory: I {device.spec.identity.serial} {device.spec.assetTag} {device.spec.identity.systemUUID} - + {reference('DeviceClaim', namespace, device.spec.claimRef.name)} {placement(entry)} @@ -515,14 +530,12 @@ export function PhysicalInventory({ inventory: source, onRetry }: { inventory: I )} )} -

- {kind === 'Rack' || kind === 'Facility' - ? 'Recorded contents & installation plans' - : 'Related records'} + {(kind !== 'Facility' && kind !== 'Rack' || relatedRecords.length > 0) && <>

+ Related records

- {related.length ? ( + {relatedRecords.length ? (
    - {related.map((item) => ( + {relatedRecords.map((item) => (
  • {sections.find((section) => section.kind === item.kind)?.title} @@ -537,7 +550,7 @@ export function PhysicalInventory({ inventory: source, onRetry }: { inventory: I No related records found in this namespace. This does not establish that equipment or connections are absent.

    - )} + )}}
    Record history & verification
    @@ -562,16 +575,22 @@ export function PhysicalInventory({ inventory: source, onRetry }: { inventory: I ); } + const management = !inventory.issues?.[section.kind] && + (['Facility', 'Rack', 'Device', 'Cable'].includes(section.kind) || (section.kind === 'DeviceClaim' && selectedName === null)) && + (selectedName === null || selected) ? record.kind === 'Facility')} + racks={inventory.physical.filter(record => record.kind === 'Rack')} + claims={inventory.slots.map(slot => slot.claim)} + devices={entries.filter(entry => entry.kind === 'Device').map(entry => entry.record as RawDevice)} + feeds={inventory.physical.filter(record => record.kind === 'PowerFeed')} + /> : null; return (
    -
    -
    -

    HARDWARE DIRECTORY

    -

    Physical inventory

    -

    Explore facilities, equipment, and physical connections.

    -
    - {onRetry && } -
    - - +
    {inventory.issues?.[section.kind] ? : selectedName !== null ? ( <> - ← Back to {section.title.toLowerCase()} -

    +
    ← Back to {section.title.toLowerCase()}{onRetry && }
    +

    {selected ? recordName(selected) : 'Record not found'} -

    +

    {management}
    {selected ? ( <>

    @@ -610,7 +628,7 @@ export function PhysicalInventory({ inventory: source, onRetry }: { inventory: I ) : ( <> -

    +

    {section.title}

    {section.description}

    @@ -618,7 +636,10 @@ export function PhysicalInventory({ inventory: source, onRetry }: { inventory: I {matching.length} of {records.length} records + {onRetry && }
    + {management}
    +
    + {!inventory.issues?.Facility && ['Device', 'DeviceClaim', 'Rack', 'PowerFeed'].includes(section.kind) && } + {filterOptions.length > 0 && } + {(locationFilter || modelFilter) && } +
    {matching.length ? ( -
    +
    @@ -641,11 +666,11 @@ export function PhysicalInventory({ inventory: source, onRetry }: { inventory: I : 'Details'} - + @@ -667,9 +692,9 @@ export function PhysicalInventory({ inventory: source, onRetry }: { inventory: I - +
    - {section.kind === 'Device' || section.kind === 'DeviceClaim' + {section.kind === 'Cable' ? 'End A' : section.kind === 'Device' || section.kind === 'DeviceClaim' ? 'Planned location' : 'Location / reference'} {section.kind === 'Device' ? 'Serial / asset tag' : 'Namespace'}{section.kind === 'Cable' ? 'End B' : section.kind === 'Device' ? 'Serial / asset tag' : 'Namespace'}
    {summary(entry)}{placement(entry)}{entry.kind === 'Cable' ? (entry.record as PhysicalRecord).spec.lanes?.map(lane =>
    ) : entry.kind === 'Rack' && (entry.record as PhysicalRecord).spec.facilityRef ? reference('Facility', entry.record.metadata.namespace, (entry.record as PhysicalRecord).spec.facilityRef!.name) : placement(entry)}
    - {entry.kind === 'Device' ? ( + {entry.kind === 'Cable' ? (entry.record as PhysicalRecord).spec.lanes?.map(lane =>
    ) : entry.kind === 'Device' ? ( <> {(entry.record as RawDevice).spec.identity.serial ?? 'Serial not recorded'} @@ -705,9 +730,7 @@ export function PhysicalInventory({ inventory: source, onRetry }: { inventory: I )} )} - - - {!inventory.issues?.[section.kind] && (section.kind === 'Facility' || section.kind === 'Rack') && (selectedName === null || selected) && record.kind === 'Facility')} />} +
    About this inventory

    @@ -715,8 +738,8 @@ export function PhysicalInventory({ inventory: source, onRetry }: { inventory: I establish availability, verified placement, working connections, or permission to operate equipment.

    - Viewing and management permissions are separate. Authorized inventory managers can create facilities - and racks here, and edit display names of records created by this portal. Other records require an + Viewing and management permissions are separate. Authorized inventory managers can create facilities, + racks, installation plans with unknown positions, device registrations, and cables here, and edit display names of records created by this portal. Other records require an explicit ownership review. Nothing here synchronizes external systems or provisions hardware.

    diff --git a/ui/provider/src/lib/inventory-hardware.test.ts b/ui/provider/src/lib/inventory-hardware.test.ts new file mode 100644 index 00000000..980756ab --- /dev/null +++ b/ui/provider/src/lib/inventory-hardware.test.ts @@ -0,0 +1,94 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { waitFor } from '@testing-library/react'; +import { createInventoryRecord, editInventoryLabel, INVENTORY_FIELD_MANAGER, inventoryPayload, type InventoryFormValues } from './inventory-management'; +import { hardwarePayload, type ReferencedEndpoint } from './inventory-hardware'; +import { InventoryOperationScope } from './inventory-operation'; + +const values: InventoryFormValues = { name: 'synthetic', namespace: 'default', displayName: 'Synthetic hardware', recordedBy: 'operator', reference: '', height: '', facility: '', model: 'Example', serial: 'SYNTHETIC-1', claim: { name: 'plan', uid: 'plan-uid', resourceVersion: '1' }, components: [{ id: 'port', name: 'Port', type: 'NetworkPort', positions: 1 }] }; +const endpoint: ReferencedEndpoint = { kind: 'Device', name: 'synthetic-device', uid: 'device-uid', resourceVersion: '1', componentID: 'port', position: 1 }; +const cableValues: InventoryFormValues = { ...values, medium: 'Copper', cableLanes: [{ id: 'lane-1', a: endpoint, b: { ...endpoint, name: 'other', uid: 'other-uid' } }] }; +const planValues: InventoryFormValues = { ...values, planLocation: { kind: 'Rack', name: 'rack', uid: 'rack-uid', resourceVersion: '1' } }; +const common = inventoryPayload('Facility', values, '2026-01-01T00:00:00Z'); +const claim = { metadata: { name: 'plan', uid: 'plan-uid', resourceVersion: '1' }, spec: { lifecycle: 'Installation' } }; +const device = { ...hardwarePayload('Device', values, common), metadata: { name: 'synthetic-device', namespace: 'default', uid: 'device-uid', resourceVersion: '1', managedFields: [{ manager: INVENTORY_FIELD_MANAGER }] } }; +const response = (data: unknown, status = 200) => ({ ok: status < 400, status, json: async () => ({ data }) }); +afterEach(() => vi.unstubAllGlobals()); + +describe('physical record creation', () => { + it.each(['Facility', 'Rack'] as const)('creates a new observational plan at a %s without inventing geometry', async kind => { + const planValues = { ...values, planLocation: { kind, name: 'location', uid: 'location-uid', resourceVersion: '1' } }; + const requests = vi.fn().mockResolvedValueOnce(response({ status: { allowed: true } })).mockResolvedValueOnce(response({ metadata: { uid: 'location-uid', resourceVersion: '1' } })).mockResolvedValueOnce(response({ metadata: { uid: 'plan-uid' } })); + vi.stubGlobal('fetch', requests); + await createInventoryRecord('DeviceClaim', planValues, new InventoryOperationScope().begin()); + const payload = JSON.parse(requests.mock.calls[2][1].body); + expect(payload.spec.lifecycle).toBe('Installation'); + expect(payload.spec.placement).toEqual(kind === 'Facility' ? { scope: 'Facility', facilityRef: { name: 'location' } } : { scope: 'RackMembership', rackRef: { name: 'location' } }); + expect(payload.status).toBeUndefined(); + }); + it('creates typed immutable identity without assigning IP, status, or capacity', async () => { + const requests = vi.fn().mockResolvedValueOnce(response({ status: { allowed: true } })).mockResolvedValueOnce(response(claim)).mockResolvedValueOnce(response(device)); + vi.stubGlobal('fetch', requests); + await createInventoryRecord('Device', values, new InventoryOperationScope().begin()); + const body = JSON.parse(requests.mock.calls[2][1].body); + expect(body.kind).toBe('Device'); + expect(body.spec.claimRef).toEqual({ name: 'plan' }); + expect(body.spec.identity).toEqual({ model: 'Example', serial: 'SYNTHETIC-1' }); + expect(body.spec.components[0].type).toBe('NetworkPort'); + expect(Object.keys(body.spec).sort()).toEqual(['claimRef', 'components', 'displayName', 'identity', 'provenance', 'topologyAuthority'].sort()); + expect(body.status).toBeUndefined(); + }); + it.each([{ serial: '', systemUUID: '' }, { model: '' }, { systemUUID: 'invented' }, { components: [{ id: 'a', name: 'A', type: 'NetworkPort', positions: 0 }] }, { components: [values.components![0], values.components![0]] }])('rejects incomplete or invalid hardware: %j', invalid => { + expect(() => hardwarePayload('Device', { ...values, ...invalid } as InventoryFormValues, common)).toThrow(); + }); + it.each(['legacy', 'changed', 'deleted'])('does not register against %s plans', async mode => { + const changed = { ...claim, metadata: { ...claim.metadata, ...(mode === 'changed' && { resourceVersion: '2' }), ...(mode === 'deleted' && { deletionTimestamp: 'now' }) }, spec: { lifecycle: mode === 'legacy' ? undefined : 'Installation' } }; + const requests = vi.fn().mockResolvedValueOnce(response({ status: { allowed: true } })).mockResolvedValueOnce(response(changed)); + vi.stubGlobal('fetch', requests); + await expect(createInventoryRecord('Device', values, new InventoryOperationScope().begin())).rejects.toMatchObject({ status: 409 }); + expect(requests).toHaveBeenCalledTimes(2); + }); + it('creates typed cable lanes only after re-reading endpoint identities and positions', async () => { + const requests = vi.fn().mockResolvedValueOnce(response({ status: { allowed: true } })).mockResolvedValueOnce(response(device)).mockResolvedValueOnce(response({ ...device, metadata: { ...device.metadata, uid: 'other-uid' } })).mockResolvedValueOnce(response({ metadata: { uid: 'cable-uid' } })); + vi.stubGlobal('fetch', requests); + await createInventoryRecord('Cable', cableValues, new InventoryOperationScope().begin()); + const payload = JSON.parse(requests.mock.calls[3][1].body); + expect(payload.spec.lanes).toEqual([{ id: 'lane-1', a: { deviceRef: { name: 'synthetic-device' }, componentID: 'port', position: 1 }, b: { deviceRef: { name: 'other' }, componentID: 'port', position: 1 } }]); + expect(payload.status).toBeUndefined(); + }); + it('rejects repeated endpoints across lanes and self-connections', () => { + for (const cableLanes of [[{ id: 'lane', a: endpoint, b: endpoint }], [...cableValues.cableLanes!, { ...cableValues.cableLanes![0], id: 'lane-2' }]]) expect(() => hardwarePayload('Cable', { ...cableValues, cableLanes }, common)).toThrow(); + }); + it.each(['revision', 'missing-component', 'unknown-positions', 'not-a-port'])('refuses a cable with %s', async mode => { + const changed = { ...device, metadata: { ...device.metadata, resourceVersion: mode === 'revision' ? '2' : '1' }, spec: { ...device.spec, components: mode === 'missing-component' ? [] : [{ ...values.components![0], positions: mode === 'unknown-positions' ? undefined : 1, type: mode === 'not-a-port' ? 'Module' : 'NetworkPort' }] } }; + const requests = vi.fn().mockResolvedValueOnce(response({ status: { allowed: true } })).mockResolvedValueOnce(response(changed)); + vi.stubGlobal('fetch', requests); + await expect(createInventoryRecord('Cable', cableValues, new InventoryOperationScope().begin())).rejects.toMatchObject({ status: 409 }); + expect(requests).toHaveBeenCalledTimes(2); + }); + it.each(['Device', 'Cable', 'DeviceClaim'] as const)('keeps %s submit authority revoked after a delayed prerequisite', async kind => { + const scope = new InventoryOperationScope(); + let release: ((value: unknown) => void) | undefined; + const requests = vi.fn().mockResolvedValueOnce(response({ status: { allowed: true } })).mockImplementationOnce(() => new Promise(resolve => { release = resolve; })); + vi.stubGlobal('fetch', requests); + const outcome = createInventoryRecord(kind, kind === 'Device' ? values : kind === 'Cable' ? cableValues : planValues, scope.begin()).catch(error => error); + await waitFor(() => expect(release).toBeDefined()); + scope.invalidate(); + release!(response(kind === 'Device' ? claim : device)); + expect(await outcome).toMatchObject({ dispatched: false }); + expect(requests).toHaveBeenCalledTimes(2); + }); + it.each(['Device', 'Cable', 'DeviceClaim'] as const)('does not dispatch %s after denied/expired prerequisite', async kind => { + for (const status of [401, 403, 404, 503]) { + const requests = vi.fn().mockResolvedValueOnce(response({ status: { allowed: true } })).mockResolvedValueOnce(response(undefined, status)); + vi.stubGlobal('fetch', requests); + await expect(createInventoryRecord(kind, kind === 'Device' ? values : kind === 'Cable' ? cableValues : planValues, new InventoryOperationScope().begin())).rejects.toMatchObject({ status }); + expect(requests).toHaveBeenCalledTimes(2); + } + }); + it('limits device edits to labels/provenance, preserving identity and components', async () => { + const requests = vi.fn().mockResolvedValueOnce(response({ status: { allowed: true } })).mockResolvedValueOnce(response(device)).mockResolvedValueOnce(response(device)); + vi.stubGlobal('fetch', requests); + await editInventoryLabel(device, values, new InventoryOperationScope().begin()); + expect(JSON.parse(requests.mock.calls[2][1].body).map((operation: { path: string }) => operation.path)).toEqual(['/metadata/uid', '/metadata/resourceVersion', '/spec/displayName', '/spec/provenance']); + }); +}); diff --git a/ui/provider/src/lib/inventory-hardware.ts b/ui/provider/src/lib/inventory-hardware.ts new file mode 100644 index 00000000..81caca37 --- /dev/null +++ b/ui/provider/src/lib/inventory-hardware.ts @@ -0,0 +1,81 @@ +import type { CableEndpoint, Device, DeviceClaim, PhysicalComponent, PhysicalRecord } from '../../../shared/fleet-api'; +import { ApiError, PROVIDER_PROJECT, proxyFetch } from './api'; +import type { InventoryOperation } from './inventory-operation'; +import type { InventoryFormValues } from './inventory-management'; + +export interface ReferencedEndpoint { + kind: 'Device' | 'PowerFeed'; + name: string; + uid: string; + resourceVersion: string; + componentID: string; + position: number; +} +export interface HardwareFields { + planLocation?: { kind: 'Facility' | 'Rack'; name: string; uid: string; resourceVersion: string }; + claim?: { name: string; uid: string; resourceVersion: string }; + manufacturer?: string; + model?: string; + serial?: string; + systemUUID?: string; + assetTag?: string; + components?: PhysicalComponent[]; + medium?: string; + cableLanes?: { id: string; a?: ReferencedEndpoint; b?: ReferencedEndpoint }[]; +} +export const cableMedia = ['Copper', 'Fiber', 'Power', 'Console', 'Unknown']; +export const componentTypes: PhysicalComponent['type'][] = ['NetworkPort', 'PowerInlet', 'PowerOutlet', 'ConsolePort', 'ConsoleServerPort', 'FrontPort', 'RearPort', 'Module', 'InventoryItem', 'DeviceBay']; +export function isTermination(component: PhysicalComponent) { return !['Module', 'InventoryItem', 'DeviceBay'].includes(component.type); } +const namePattern = /^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$/; +const endpointKey = (endpoint: ReferencedEndpoint) => `${endpoint.kind}/${endpoint.name}/${endpoint.componentID}/${endpoint.position}`; + +export function hardwarePayload(kind: 'Device' | 'Cable' | 'DeviceClaim', values: InventoryFormValues, common: PhysicalRecord & { apiVersion: string }): Device | PhysicalRecord | DeviceClaim { + if (kind === 'DeviceClaim') { + const location = values.planLocation; + if (!location?.uid || !location.resourceVersion || !['Facility', 'Rack'].includes(location.kind) || !namePattern.test(location.name) || !values.model?.trim() || [values.model, values.manufacturer, values.serial].some(value => (value?.length ?? 0) > 253)) throw new ApiError(422, 'Choose a recorded location and an expected hardware model.'); + return { ...common, kind, spec: { displayName: values.displayName.trim(), provenance: common.spec.provenance, lifecycle: 'Installation', expectedIdentity: { model: values.model.trim(), ...(values.manufacturer?.trim() && { manufacturer: values.manufacturer.trim() }), ...(values.serial?.trim() && { serial: values.serial.trim() }) }, placement: location.kind === 'Facility' ? { scope: 'Facility', facilityRef: { name: location.name } } : { scope: 'RackMembership', rackRef: { name: location.name } } } }; + } + if (kind === 'Device') { + if (!values.claim?.uid || !values.claim.resourceVersion || !namePattern.test(values.claim.name) || !values.model?.trim() || (!values.serial?.trim() && !values.systemUUID)) throw new ApiError(422, 'Choose an installation plan and enter a model and a serial or system UUID.'); + if (values.systemUUID && !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(values.systemUUID)) throw new ApiError(422, 'Enter a valid lowercase system UUID.'); + if ([values.manufacturer, values.model, values.serial, values.assetTag].some(value => (value?.length ?? 0) > 253)) throw new ApiError(422, 'Hardware fields must be at most 253 characters.'); + const components = values.components ?? []; + if (components.length > 256 || new Set(components.map(component => component.id)).size !== components.length || components.some(component => !component.id.trim() || component.id.length > 63 || !component.name.trim() || component.name.length > 253 || !componentTypes.includes(component.type) || (component.connector?.length ?? 0) > 253 || !Number.isInteger(component.positions) || component.positions! < 1 || component.positions! > 256)) throw new ApiError(422, 'Review component IDs, names, types, and positions.'); + return { ...common, kind, spec: { displayName: values.displayName.trim(), provenance: common.spec.provenance, claimRef: { name: values.claim.name }, identity: { model: values.model.trim(), ...(values.manufacturer?.trim() && { manufacturer: values.manufacturer.trim() }), ...(values.serial?.trim() && { serial: values.serial.trim() }), ...(values.systemUUID && { systemUUID: values.systemUUID }) }, ...(values.assetTag?.trim() && { assetTag: values.assetTag.trim() }), topologyAuthority: 'Cable', components } }; + } + const lanes = values.cableLanes ?? []; + if (!cableMedia.includes(values.medium ?? '') || !lanes.length || lanes.length > 64 || new Set(lanes.map(lane => lane.id)).size !== lanes.length) throw new ApiError(422, 'Choose a medium and one or more uniquely named lanes.'); + const used = new Set(); + const endpoint = (value?: ReferencedEndpoint): CableEndpoint => { + if (!value || !['Device', 'PowerFeed'].includes(value.kind) || !value.uid || !value.resourceVersion || !namePattern.test(value.name) || !value.componentID.trim() || value.componentID.length > 63 || !Number.isInteger(value.position) || value.position < 1 || value.position > 256 || used.has(endpointKey(value))) throw new ApiError(422, 'Choose distinct, fully recorded endpoints for every lane.'); + used.add(endpointKey(value)); + return { ...(value.kind === 'Device' ? { deviceRef: { name: value.name } } : { powerFeedRef: { name: value.name } }), componentID: value.componentID, position: value.position }; + }; + return { ...common, kind, spec: { ...common.spec, medium: values.medium, lanes: lanes.map(lane => { if (!lane.id.trim() || lane.id.length > 63) throw new ApiError(422, 'Lane IDs are required.'); return { id: lane.id, a: endpoint(lane.a), b: endpoint(lane.b) }; }) } }; +} + +export async function validateHardwareReferences(kind: 'Device' | 'Cable' | 'DeviceClaim', values: InventoryFormValues, operation: InventoryOperation) { + const base = `/apis/fleet.datumapis.com/v1alpha1/namespaces/${encodeURIComponent(values.namespace)}`; + if (kind === 'DeviceClaim') { + const snapshot = values.planLocation!; + const location = await proxyFetch(PROVIDER_PROJECT, `${base}/${snapshot.kind === 'Facility' ? 'facilities' : 'racks'}/${encodeURIComponent(snapshot.name)}`); + operation.assertCurrent(); + if (!location || location.metadata.uid !== snapshot.uid || location.metadata.resourceVersion !== snapshot.resourceVersion || location.metadata.deletionTimestamp) throw new ApiError(409, 'The location changed. Review the installation plan.'); + return; + } + if (kind === 'Device') { + const snapshot = values.claim!; + const claim = await proxyFetch(PROVIDER_PROJECT, `${base}/deviceclaims/${encodeURIComponent(snapshot.name)}`); + operation.assertCurrent(); + if (!claim || claim.metadata.uid !== snapshot.uid || claim.metadata.resourceVersion !== snapshot.resourceVersion || claim.metadata.deletionTimestamp || claim.spec.lifecycle !== 'Installation') throw new ApiError(409, 'The installation plan changed or is a legacy binding. Review it before registration.'); + return; + } + for (const lane of values.cableLanes ?? []) for (const endpoint of [lane.a!, lane.b!]) { + const record = await proxyFetch(PROVIDER_PROJECT, `${base}/${endpoint.kind === 'Device' ? 'devices' : 'powerfeeds'}/${encodeURIComponent(endpoint.name)}`); + operation.assertCurrent(); + if (!record || record.metadata.uid !== endpoint.uid || record.metadata.resourceVersion !== endpoint.resourceVersion || record.metadata.deletionTimestamp) throw new ApiError(409, 'An endpoint changed. Review the cable before recording.'); + const components = endpoint.kind === 'Device' ? (record as Device).spec.components : (record as PhysicalRecord).spec.terminations; + const component = components?.find(item => item.id === endpoint.componentID); + if (!component || !isTermination(component) || component.positions === undefined || endpoint.position > component.positions) throw new ApiError(409, 'An endpoint position is no longer recorded.'); + } +} diff --git a/ui/provider/src/lib/inventory-management.ts b/ui/provider/src/lib/inventory-management.ts index 3df70a73..694b74ff 100644 --- a/ui/provider/src/lib/inventory-management.ts +++ b/ui/provider/src/lib/inventory-management.ts @@ -1,11 +1,14 @@ import { useQuery } from '@tanstack/react-query'; import { ApiError, PLUGIN_ID, PROVIDER_PROJECT, proxyFetch } from './api'; -import type { PhysicalRecord } from '../../../shared/fleet-api'; +import type { Device, DeviceClaim, PhysicalRecord } from '../../../shared/fleet-api'; import type { InventoryOperation } from './inventory-operation'; +import { hardwarePayload, validateHardwareReferences, type HardwareFields } from './inventory-hardware'; +import { inventoryResources } from '../inventory'; -export type ManagedKind = 'Facility' | 'Rack'; +export type ManagedKind = 'Facility' | 'Rack' | 'Device' | 'Cable' | 'DeviceClaim'; +export type ManagedRecord = PhysicalRecord | Device | DeviceClaim; export const INVENTORY_FIELD_MANAGER = 'fleet-staff-inventory-ui'; -const resources = { Facility: 'facilities', Rack: 'racks' } as const; +const resources = inventoryResources; const fixtures = import.meta.env.VITE_FLEET_FIXTURES === 'true'; const resourcePath = (kind: ManagedKind, namespace: string) => `/apis/fleet.datumapis.com/v1alpha1/namespaces/${encodeURIComponent(namespace)}/${resources[kind]}`; @@ -21,14 +24,14 @@ export function useInventoryPermission(kind: ManagedKind, namespace: string, ver return useQuery({ queryKey: [PLUGIN_ID, 'inventory-permission', PROVIDER_PROJECT, kind, namespace, verb, name], queryFn: () => inventoryPermission(kind, namespace, verb, name), enabled: !!namespace, retry: false, gcTime: 0, staleTime: 0, refetchOnMount: 'always' }); } -export function canEditInventoryLabel(record: PhysicalRecord): boolean { +export function canEditInventoryLabel(record: ManagedRecord): boolean { const { metadata, spec } = record; - return (record.kind === 'Facility' || record.kind === 'Rack') && !!metadata.uid && !!metadata.resourceVersion && !metadata.deletionTimestamp && !spec.provenance.source && spec.provenance.method === 'Manual' && + return ['Facility', 'Rack', 'Device', 'Cable'].includes(record.kind ?? '') && !!metadata.uid && !!metadata.resourceVersion && !metadata.deletionTimestamp && !spec.provenance.source && spec.provenance.method === 'Manual' && !Object.keys({ ...metadata.labels, ...metadata.annotations }).some(key => /fluxcd\.io|argocd|inventory.*owner/i.test(key)) && !!metadata.managedFields?.length && metadata.managedFields.every(field => field.manager === INVENTORY_FIELD_MANAGER && !field.subresource); } -export interface InventoryFormValues { +export interface InventoryFormValues extends HardwareFields { name: string; namespace: string; displayName: string; @@ -38,10 +41,11 @@ export interface InventoryFormValues { height: string; } -export function inventoryPayload(kind: ManagedKind, values: InventoryFormValues, now = new Date().toISOString()): PhysicalRecord & { apiVersion: string } { +export function inventoryPayload(kind: 'Facility' | 'Rack', values: InventoryFormValues, now = new Date().toISOString()): PhysicalRecord & { apiVersion: string } { const resourceName = /^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$/; if (!resourceName.test(values.name) || values.name.length > 253 || !/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(values.namespace) || values.namespace.length > 63) throw new ApiError(422, 'Enter a valid record name and namespace.'); if (!values.displayName.trim() || values.displayName.trim().length > 253 || !values.recordedBy.trim() || values.recordedBy.trim().length > 253) throw new ApiError(422, 'Display name and recorder are required (at most 253 characters each).'); + if (values.reference.trim().length > 1024) throw new ApiError(422, 'The change reference is too long.'); if (kind === 'Rack' && !resourceName.test(values.facility)) throw new ApiError(422, 'Choose a facility in this namespace.'); if (kind === 'Rack' && values.height && (!/^\d+$/.test(values.height) || Number(values.height) < 1 || Number(values.height) > 100)) throw new ApiError(422, 'Rack height must be a whole number from 1 to 100, or left blank when unknown.'); return { apiVersion: 'fleet.datumapis.com/v1alpha1', kind, metadata: { name: values.name, namespace: values.namespace }, spec: { @@ -56,9 +60,12 @@ async function requirePermission(kind: ManagedKind, namespace: string, verb: 'cr export async function createInventoryRecord(kind: ManagedKind, values: InventoryFormValues, operation: InventoryOperation) { operation.assertCurrent(); - const payload = inventoryPayload(kind, values); + const common = inventoryPayload(kind === 'Rack' ? 'Rack' : 'Facility', values); + const payload = kind === 'Device' || kind === 'Cable' || kind === 'DeviceClaim' ? hardwarePayload(kind, values, common) : common; await requirePermission(kind, values.namespace, 'create'); operation.assertCurrent(); + if (kind === 'Device' || kind === 'Cable' || kind === 'DeviceClaim') await validateHardwareReferences(kind, values, operation); + operation.assertCurrent(); if (kind === 'Rack') { const facility = await proxyFetch(PROVIDER_PROJECT, `${resourcePath('Facility', values.namespace)}/${encodeURIComponent(values.facility)}`); operation.assertCurrent(); @@ -71,7 +78,7 @@ export async function createInventoryRecord(kind: ManagedKind, values: Inventory return record; } -export async function editInventoryLabel(original: PhysicalRecord, values: InventoryFormValues, operation: InventoryOperation) { +export async function editInventoryLabel(original: ManagedRecord, values: InventoryFormValues, operation: InventoryOperation) { operation.assertCurrent(); if (!canEditInventoryLabel(original)) throw new ApiError(409, 'This record needs an explicit ownership review before editing.'); const kind = original.kind as ManagedKind; @@ -79,7 +86,7 @@ export async function editInventoryLabel(original: PhysicalRecord, values: Inven await requirePermission(kind, namespace, 'patch', original.metadata.name); operation.assertCurrent(); const path = `${resourcePath(kind, namespace)}/${encodeURIComponent(original.metadata.name)}`; - const current = await proxyFetch(PROVIDER_PROJECT, path); + const current = await proxyFetch(PROVIDER_PROJECT, path); operation.assertCurrent(); if (!current || current.metadata.uid !== original.metadata.uid || current.metadata.resourceVersion !== original.metadata.resourceVersion || !canEditInventoryLabel(current)) throw new ApiError(409, 'The record or its ownership changed. Reload it before editing.'); const now = new Date().toISOString(); @@ -89,7 +96,7 @@ export async function editInventoryLabel(original: PhysicalRecord, values: Inven const record = await proxyFetch(PROVIDER_PROJECT, `${path}?fieldManager=${INVENTORY_FIELD_MANAGER}`, { method: 'PATCH', contentType: 'application/json-patch+json', body: [ { op: 'test', path: '/metadata/uid', value: current.metadata.uid }, { op: 'test', path: '/metadata/resourceVersion', value: current.metadata.resourceVersion }, - { op: 'replace', path: '/spec/displayName', value: validated.spec.displayName }, + { op: current.spec.displayName === undefined ? 'add' : 'replace', path: '/spec/displayName', value: validated.spec.displayName }, { op: 'replace', path: '/spec/provenance', value: validated.spec.provenance }, ] }).catch(error => { operation.assertCurrent(); throw error; }); operation.assertCurrent(); From a52afefb6d3d63ffa9f8cdfafcb169949c61454e Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Fri, 20 Nov 2026 22:17:53 -0600 Subject: [PATCH 026/518] fix: redact inventory after reference access failures --- docs/development/staff-inventory-ui.md | 9 +++ .../src/components/inventory-management.tsx | 33 +++++++- .../components/inventory-read-access.test.tsx | 75 +++++++++++++++++++ .../src/components/physical-inventory.tsx | 42 ++++++----- ui/provider/src/lib/inventory-hardware.ts | 10 +-- ui/provider/src/lib/inventory-management.ts | 5 +- ui/provider/src/lib/inventory-read-access.ts | 40 ++++++++++ 7 files changed, 188 insertions(+), 26 deletions(-) create mode 100644 ui/provider/src/components/inventory-read-access.test.tsx create mode 100644 ui/provider/src/lib/inventory-read-access.ts diff --git a/docs/development/staff-inventory-ui.md b/docs/development/staff-inventory-ui.md index 40b3e023..84d47129 100644 --- a/docs/development/staff-inventory-ui.md +++ b/docs/development/staff-inventory-ui.md @@ -97,6 +97,15 @@ removed on an observed denial/session boundary. Reads are manually refreshed; this is not instantaneous notification of a server-side grant change during an idle session. Detail pages now offer the same explicit Refresh inventory action. +A failed submit-time reference read is distinct from a denied write. It carries +the reference kind and namespace, removes that kind's cached records and form +choices conservatively across the current view, and clears selected references +without discarding unrelated user-entered fields. In-flight inventory reads are +cancelled before cached records are removed. Session expiry hides all kinds. +Reopening inventory starts a fresh access evaluation; refreshing an existing view +does not clear its recorded read failures. Search indexes explicit visible fields +and readable endpoint identities, not raw records or redacted references. + ### Retained host source evidence The prior implementation inspected staff-portal source at diff --git a/ui/provider/src/components/inventory-management.tsx b/ui/provider/src/components/inventory-management.tsx index 5ed01201..a13063ef 100644 --- a/ui/provider/src/components/inventory-management.tsx +++ b/ui/provider/src/components/inventory-management.tsx @@ -7,9 +7,18 @@ import type { Device, DeviceClaim, PhysicalRecord } from '../../../shared/fleet- import { InventoryOperationContext, InventoryOperationInvalidated, InventoryOperationScope } from '../lib/inventory-operation'; import { InventoryHardwareFields } from './inventory-hardware-fields'; import type { Inventory } from '../inventory'; +import { InventoryReadAccessContext, InventoryReferenceReadError, readFailureIssues, redactInventory } from '../lib/inventory-read-access'; -export function InventoryManagement({ kind, record, facilities, claims = [], devices = [], feeds = [], racks = [], compact = false, issues }: { kind: ManagedKind; record?: ManagedRecord; facilities: PhysicalRecord[]; claims?: DeviceClaim[]; devices?: Device[]; feeds?: PhysicalRecord[]; racks?: PhysicalRecord[]; compact?: boolean; issues?: Inventory['issues'] }) { +export function InventoryManagement({ kind, record, facilities: sourceFacilities, claims: sourceClaims = [], devices: sourceDevices = [], feeds: sourceFeeds = [], racks: sourceRacks = [], compact = false, issues: sourceIssues }: { kind: ManagedKind; record?: ManagedRecord; facilities: PhysicalRecord[]; claims?: DeviceClaim[]; devices?: Device[]; feeds?: PhysicalRecord[]; racks?: PhysicalRecord[]; compact?: boolean; issues?: Inventory['issues'] }) { const client = useQueryClient(); + const onReadFailure = useContext(InventoryReadAccessContext); + const [readIssues, setReadIssues] = useState({}); + const issues = { ...sourceIssues, ...readIssues }; + const facilities = issues.Facility ? [] : sourceFacilities; + const claims = issues.DeviceClaim ? [] : sourceClaims; + const devices = issues.Device ? [] : sourceDevices; + const feeds = issues.PowerFeed ? [] : sourceFeeds; + const racks = issues.Rack ? [] : sourceRacks; const sessionScope = useContext(InventoryOperationContext); const scope = useRef(new InventoryOperationScope()); useLayoutEffect(() => { @@ -32,7 +41,7 @@ export function InventoryManagement({ kind, record, facilities, claims = [], dev const editable = !record || canEditInventoryLabel(record); const permission = useInventoryPermission(kind, editable ? namespace : '', record ? 'patch' : 'create', record?.metadata.name); const dependenciesUnavailable = !record && ((kind === 'Device' && !!issues?.DeviceClaim) || (kind === 'Rack' && !!issues?.Facility) || (kind === 'DeviceClaim' && !!issues?.Facility && !!issues?.Rack) || (kind === 'Cable' && !!issues?.Device && !!issues?.PowerFeed)); - const allowed = permission.data === true && !permission.isFetching && !permission.error && editable && !dependenciesUnavailable; + const allowed = permission.data === true && !permission.isFetching && !permission.error && editable && !dependenciesUnavailable && !issues[kind]; const [open, setOpen] = useState(false); const [pending, setPending] = useState(false); const [blocked, setBlocked] = useState(false); @@ -55,6 +64,26 @@ export function InventoryManagement({ kind, record, facilities, claims = [], dev await client.invalidateQueries({ queryKey: [PLUGIN_ID, 'inventory', PROVIDER_PROJECT] }); } catch (error) { if (error instanceof InventoryOperationInvalidated) { setMessage(error.message); setBlocked(true); } + else if (error instanceof InventoryReferenceReadError) { + const denied = readFailureIssues(error); + setReadIssues(previous => ({ ...previous, ...denied })); + onReadFailure(error); + setValues(previous => ({ ...previous, + facility: denied?.Facility ? '' : previous.facility, + claim: denied?.DeviceClaim ? undefined : previous.claim, + planLocation: previous.planLocation && denied?.[previous.planLocation.kind] ? undefined : previous.planLocation, + cableLanes: previous.cableLanes?.map(lane => ({ ...lane, + a: lane.a && denied?.[lane.a.kind] ? undefined : lane.a, + b: lane.b && denied?.[lane.b.kind] ? undefined : lane.b, + })), + })); + if (record || error.status === 401) { setOpen(false); setBaseline(undefined); } + setMessage(error.status === 401 ? 'Your session expired. Sign in through the staff portal before continuing.' : 'Related inventory is no longer readable. Restricted choices were removed; your other input is kept. Reopen inventory after viewing access is restored.'); + setBlocked(true); + const queryKey = [PLUGIN_ID, 'inventory', PROVIDER_PROJECT]; + await client.cancelQueries({ queryKey }); + client.setQueriesData({ queryKey }, previous => previous ? redactInventory(previous, denied) : previous); + } else if (error instanceof ApiError && error.status === 403) { setMessage('Your management permission changed. Your input is kept here. Ask your administrator for access before trying again.'); setBlocked(true); } else if (error instanceof ApiError && error.status === 401) { setMessage('Your session expired. Your input is kept here. Sign in through the staff portal before continuing.'); setBlocked(true); } else if (error instanceof ApiError && error.status === 409) { setMessage('The record already exists, changed, or has another writer. Your input is kept here. Refresh and review the record before continuing.'); setBlocked(true); } diff --git a/ui/provider/src/components/inventory-read-access.test.tsx b/ui/provider/src/components/inventory-read-access.test.tsx new file mode 100644 index 00000000..cc584562 --- /dev/null +++ b/ui/provider/src/components/inventory-read-access.test.tsx @@ -0,0 +1,75 @@ +import { fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { MemoryRouter } from 'react-router'; +import { afterEach, expect, it, vi } from 'vitest'; +import { InventoryManagement } from './inventory-management'; +import { PhysicalInventory } from './physical-inventory'; +import { fixturePhysicalClaims, fixturePhysicalDevices, fixturePhysicalRecords } from '../lib/fixtures'; +import { toInventory, type Inventory } from '../inventory'; +import { PLUGIN_ID, PROVIDER_PROJECT } from '../lib/api'; +import { readInventoryReference, InventoryReferenceReadError } from '../lib/inventory-read-access'; +import { InventoryOperationScope } from '../lib/inventory-operation'; + +const response = (data: unknown, status = 200) => ({ ok: status < 400, status, json: async () => ({ data }) }); +afterEach(() => vi.unstubAllGlobals()); + +it.each([false, true])('removes denied prerequisite choices and cached records, integrated=%s', async integrated => { + const claim = structuredClone(fixturePhysicalClaims[0]); + claim.metadata = { ...claim.metadata, uid: 'plan-uid', resourceVersion: '1' }; + claim.spec = { ...claim.spec, displayName: 'Restricted plan label', lifecycle: 'Installation' }; + const inventory = toInventory([claim], fixturePhysicalDevices, fixturePhysicalRecords); + const client = new QueryClient(); + const queryKey = [PLUGIN_ID, 'inventory', PROVIDER_PROJECT, 'test']; + client.setQueryData(queryKey, inventory); + const writes: unknown[] = []; + vi.stubGlobal('fetch', vi.fn(async (url: string, init: RequestInit) => { + if (url.includes('selfsubjectaccessreviews')) return response({ status: { allowed: true } }); + if (init.method === 'GET') return response(undefined, 403); + writes.push(init); return response({}); + })); + render( + {integrated ? : } + ); + fireEvent.click(await screen.findByRole('button', { name: 'Create device' })); + for (const [label, value] of [['Record name', 'synthetic-new'], ['Display name', 'Safe unsaved name'], ['Recorded by', 'operator'], ['Model', 'Example'], ['Serial number', 'SYNTHETIC-NEW'], ['Installation plan', 'plan-uid']]) fireEvent.change(screen.getByLabelText(label), { target: { value } }); + fireEvent.click(screen.getByRole('button', { name: 'Create device record' })); + await screen.findByText(/Restricted choices were removed/); + expect(writes).toEqual([]); + expect(screen.queryByText('Restricted plan label')).not.toBeInTheDocument(); + expect(screen.getByLabelText('Installation plan')).toHaveValue(''); + expect(screen.getByLabelText('Display name')).toHaveValue('Safe unsaved name'); + expect(screen.getByRole('button', { name: 'Create device record' })).toBeDisabled(); + await waitFor(() => expect(client.getQueryData(queryKey)?.slots).toEqual([])); + expect(client.getQueryData(queryKey)?.issues?.DeviceClaim?.status).toBe(403); +}); + +it.each(['Facility', 'Rack'] as const)('redacts denied %s references in PowerFeed rows and search', kind => { + const feed = structuredClone(fixturePhysicalRecords.find(record => record.kind === 'PowerFeed')!); + delete feed.spec.rackRef; + delete feed.spec.facilityRef; + feed.spec[kind === 'Facility' ? 'facilityRef' : 'rackRef'] = { name: 'restricted-location' }; + const inventory = { ...toInventory([], [], [feed]), issues: { [kind]: { status: 403 } } }; + render(); + expect(screen.queryByText('restricted-location')).not.toBeInTheDocument(); + fireEvent.change(screen.getByRole('searchbox'), { target: { value: 'restricted-location' } }); + expect(screen.queryByRole('link', { name: feed.spec.displayName })).not.toBeInTheDocument(); +}); + +it.each(['Device', 'PowerFeed'] as const)('does not search denied %s cable endpoints', kind => { + const cable = structuredClone(fixturePhysicalRecords.find(record => record.kind === 'Cable')!); + cable.spec.lanes![0].a = { componentID: 'port', position: 1, ...(kind === 'Device' ? { deviceRef: { name: 'restricted-endpoint' } } : { powerFeedRef: { name: 'restricted-endpoint' } }) }; + const inventory = { ...toInventory([], [], [cable]), issues: { [kind]: { status: 403 } } }; + render(); + fireEvent.change(screen.getByRole('searchbox'), { target: { value: 'restricted-endpoint' } }); + expect(screen.queryByRole('link', { name: cable.spec.displayName })).not.toBeInTheDocument(); + fireEvent.change(screen.getByRole('searchbox'), { target: { value: cable.spec.displayName! } }); + expect(screen.getByRole('link', { name: cable.spec.displayName })).toBeInTheDocument(); +}); + +it.each(['Facility', 'Rack', 'DeviceClaim', 'Device', 'PowerFeed'] as const)('retains the failed %s read scope separately from write denial', async kind => { + vi.stubGlobal('fetch', vi.fn(async () => response(undefined, 403))); + const operation = new InventoryOperationScope().begin(); + const failure = await readInventoryReference(kind, 'synthetic-namespace', 'synthetic-record', operation).catch(error => error); + expect(failure).toBeInstanceOf(InventoryReferenceReadError); + expect(failure).toMatchObject({ kind, namespace: 'synthetic-namespace', status: 403 }); +}); diff --git a/ui/provider/src/components/physical-inventory.tsx b/ui/provider/src/components/physical-inventory.tsx index 3d1a086f..41b1c7c7 100644 --- a/ui/provider/src/components/physical-inventory.tsx +++ b/ui/provider/src/components/physical-inventory.tsx @@ -14,6 +14,7 @@ import './physical-inventory.css'; import { InventoryAccessState } from './inventory-access-state'; import { InventoryManagement } from './inventory-management'; import type { ManagedKind, ManagedRecord } from '../lib/inventory-management'; +import { InventoryReadAccessContext, readFailureIssues, redactInventory } from '../lib/inventory-read-access'; import { FacilityOverview, RackOverview, inventoryHref as href } from './inventory-location'; type Kind = 'Device' | 'Facility' | 'Rack' | 'DeviceClaim' | 'Cable' | 'PowerFeed'; @@ -120,12 +121,8 @@ function Components({ components }: { components: PhysicalComponent[] }) { } export function PhysicalInventory({ inventory: source, onRetry }: { inventory: Inventory; onRetry?: () => void }) { - const inventory: Inventory = { - ...source, - slots: source.issues?.DeviceClaim ? [] : source.slots.map(slot => ({ ...slot, devices: source.issues?.Device ? [] : slot.devices })), - unboundDevices: source.issues?.Device ? [] : [...source.unboundDevices, ...(source.issues?.DeviceClaim ? source.slots.flatMap(slot => slot.devices) : [])], - physical: source.physical.filter(record => !source.issues?.[record.kind]), - }; + const [readIssues, setReadIssues] = useState({}); + const inventory = redactInventory(source, readIssues); const [params] = useSearchParams(); const [search, setSearch] = useState(''); const [locationFilter, setLocationFilter] = useState(''); @@ -175,7 +172,7 @@ export function PhysicalInventory({ inventory: source, onRetry }: { inventory: I ); const plannedPlacement = (claim: RawDeviceClaim) => { const location = claim.spec.placement; - if (!location.scope) return placementLabel(claim); + if (!location.scope) return placementLabel({ ...claim, spec: { ...claim.spec, placement: { ...location, facility: inventory.issues?.Facility ? 'Facility unavailable' : location.facility, rack: inventory.issues?.Rack ? 'Rack unavailable' : location.rack } } }); const rack = location.rackRef ? find('Rack', claim.metadata.namespace, location.rackRef.name) : undefined; const facilityName = location.facilityRef?.name ?? (rack?.record as PhysicalRecord | undefined)?.spec.facilityRef?.name; @@ -205,12 +202,9 @@ export function PhysicalInventory({ inventory: source, onRetry }: { inventory: I : 'Claim record not found'; } const record = entry.record as PhysicalRecord; - return ( - record.spec.rackRef?.name ?? - record.spec.facilityRef?.name ?? - record.spec.locationRef?.name ?? - 'Not recorded' - ); + if (record.spec.rackRef) return inventory.issues?.Rack ? 'Rack unavailable' : record.spec.rackRef.name; + if (record.spec.facilityRef) return inventory.issues?.Facility ? 'Facility unavailable' : record.spec.facilityRef.name; + return 'Not recorded'; }; const summary = (entry: RecordEntry): string => { if (entry.kind === 'Device') return modelLabel((entry.record as RawDevice).spec.identity); @@ -229,6 +223,7 @@ export function PhysicalInventory({ inventory: source, onRetry }: { inventory: I }; const records = entries.filter((entry) => entry.kind === section.kind); const locationKey = (entry: RecordEntry) => { + if (inventory.issues?.Facility || (entry.kind === 'Device' && inventory.issues?.DeviceClaim)) return ''; const claim = entry.kind === 'Device' ? claimFor(entry.record as RawDevice)?.claim : entry.kind === 'DeviceClaim' ? entry.record as RawDeviceClaim : undefined; const rackName = claim?.spec.placement.rackRef?.name ?? (entry.record as PhysicalRecord).spec.rackRef?.name; const rack = rackName && !inventory.issues?.Rack ? find('Rack', entry.record.metadata.namespace, rackName)?.record as PhysicalRecord | undefined : undefined; @@ -237,12 +232,22 @@ export function PhysicalInventory({ inventory: source, onRetry }: { inventory: I }; const modelKey = (entry: RecordEntry) => entry.kind === 'Device' ? (entry.record as RawDevice).spec.identity.model : entry.kind === 'Cable' ? (entry.record as PhysicalRecord).spec.medium ?? '' : ''; const filterOptions = [...new Set(records.map(modelKey).filter(Boolean))].sort(); + const searchText = (entry: RecordEntry) => { + const device = entry.kind === 'Device' ? entry.record as RawDevice : undefined; + const physical = entry.record as PhysicalRecord; + const endpoints = entry.kind === 'Cable' ? physical.spec.lanes?.flatMap(lane => [lane.a, lane.b]).flatMap(endpoint => { + const kind = endpoint.deviceRef ? 'Device' : 'PowerFeed'; + if (inventory.issues?.[kind]) return []; + const name = endpoint.deviceRef?.name ?? endpoint.powerFeedRef?.name ?? ''; + const target = find(kind, entry.record.metadata.namespace, name); + return [name, target ? recordName(target) : '', endpoint.componentID]; + }) : []; + return [recordName(entry), entry.record.metadata.name, entry.record.metadata.namespace, summary(entry), placement(entry), device?.spec.identity.serial, device?.spec.identity.systemUUID, device?.spec.assetTag, ...(endpoints ?? [])].filter(Boolean).join(' ').toLowerCase(); + }; const matching = records .filter(entry => (!locationFilter || locationKey(entry) === locationFilter) && (!modelFilter || modelKey(entry) === modelFilter)) .filter((entry) => - `${JSON.stringify(entry.record)} ${placement(entry)}` - .toLowerCase() - .includes(search.trim().toLowerCase()), + searchText(entry).includes(search.trim().toLowerCase()), ) .sort( (left, right) => @@ -579,7 +584,7 @@ export function PhysicalInventory({ inventory: source, onRetry }: { inventory: I (['Facility', 'Rack', 'Device', 'Cable'].includes(section.kind) || (section.kind === 'DeviceClaim' && selectedName === null)) && (selectedName === null || selected) ? entry.kind === 'Device').map(entry => entry.record as RawDevice)} feeds={inventory.physical.filter(record => record.kind === 'PowerFeed')} /> : null; + if (Object.values(inventory.issues ?? {}).some(issue => issue?.status === 401)) return ; return ( + setReadIssues(previous => ({ ...previous, ...readFailureIssues(error) }))}>

    + ); } diff --git a/ui/provider/src/lib/inventory-hardware.ts b/ui/provider/src/lib/inventory-hardware.ts index 81caca37..97232a4d 100644 --- a/ui/provider/src/lib/inventory-hardware.ts +++ b/ui/provider/src/lib/inventory-hardware.ts @@ -1,5 +1,6 @@ import type { CableEndpoint, Device, DeviceClaim, PhysicalComponent, PhysicalRecord } from '../../../shared/fleet-api'; -import { ApiError, PROVIDER_PROJECT, proxyFetch } from './api'; +import { ApiError } from './api'; +import { readInventoryReference } from './inventory-read-access'; import type { InventoryOperation } from './inventory-operation'; import type { InventoryFormValues } from './inventory-management'; @@ -55,23 +56,22 @@ export function hardwarePayload(kind: 'Device' | 'Cable' | 'DeviceClaim', values } export async function validateHardwareReferences(kind: 'Device' | 'Cable' | 'DeviceClaim', values: InventoryFormValues, operation: InventoryOperation) { - const base = `/apis/fleet.datumapis.com/v1alpha1/namespaces/${encodeURIComponent(values.namespace)}`; if (kind === 'DeviceClaim') { const snapshot = values.planLocation!; - const location = await proxyFetch(PROVIDER_PROJECT, `${base}/${snapshot.kind === 'Facility' ? 'facilities' : 'racks'}/${encodeURIComponent(snapshot.name)}`); + const location = await readInventoryReference(snapshot.kind, values.namespace, snapshot.name, operation); operation.assertCurrent(); if (!location || location.metadata.uid !== snapshot.uid || location.metadata.resourceVersion !== snapshot.resourceVersion || location.metadata.deletionTimestamp) throw new ApiError(409, 'The location changed. Review the installation plan.'); return; } if (kind === 'Device') { const snapshot = values.claim!; - const claim = await proxyFetch(PROVIDER_PROJECT, `${base}/deviceclaims/${encodeURIComponent(snapshot.name)}`); + const claim = await readInventoryReference('DeviceClaim', values.namespace, snapshot.name, operation); operation.assertCurrent(); if (!claim || claim.metadata.uid !== snapshot.uid || claim.metadata.resourceVersion !== snapshot.resourceVersion || claim.metadata.deletionTimestamp || claim.spec.lifecycle !== 'Installation') throw new ApiError(409, 'The installation plan changed or is a legacy binding. Review it before registration.'); return; } for (const lane of values.cableLanes ?? []) for (const endpoint of [lane.a!, lane.b!]) { - const record = await proxyFetch(PROVIDER_PROJECT, `${base}/${endpoint.kind === 'Device' ? 'devices' : 'powerfeeds'}/${encodeURIComponent(endpoint.name)}`); + const record = await readInventoryReference(endpoint.kind, values.namespace, endpoint.name, operation); operation.assertCurrent(); if (!record || record.metadata.uid !== endpoint.uid || record.metadata.resourceVersion !== endpoint.resourceVersion || record.metadata.deletionTimestamp) throw new ApiError(409, 'An endpoint changed. Review the cable before recording.'); const components = endpoint.kind === 'Device' ? (record as Device).spec.components : (record as PhysicalRecord).spec.terminations; diff --git a/ui/provider/src/lib/inventory-management.ts b/ui/provider/src/lib/inventory-management.ts index 694b74ff..a2ef418a 100644 --- a/ui/provider/src/lib/inventory-management.ts +++ b/ui/provider/src/lib/inventory-management.ts @@ -4,6 +4,7 @@ import type { Device, DeviceClaim, PhysicalRecord } from '../../../shared/fleet- import type { InventoryOperation } from './inventory-operation'; import { hardwarePayload, validateHardwareReferences, type HardwareFields } from './inventory-hardware'; import { inventoryResources } from '../inventory'; +import { readInventoryReference } from './inventory-read-access'; export type ManagedKind = 'Facility' | 'Rack' | 'Device' | 'Cable' | 'DeviceClaim'; export type ManagedRecord = PhysicalRecord | Device | DeviceClaim; @@ -67,7 +68,7 @@ export async function createInventoryRecord(kind: ManagedKind, values: Inventory if (kind === 'Device' || kind === 'Cable' || kind === 'DeviceClaim') await validateHardwareReferences(kind, values, operation); operation.assertCurrent(); if (kind === 'Rack') { - const facility = await proxyFetch(PROVIDER_PROJECT, `${resourcePath('Facility', values.namespace)}/${encodeURIComponent(values.facility)}`); + const facility = await readInventoryReference('Facility', values.namespace, values.facility, operation); operation.assertCurrent(); if (!facility?.metadata?.uid || facility.metadata.deletionTimestamp) throw new ApiError(409, 'Facility is not available. Refresh inventory before continuing.'); } @@ -86,7 +87,7 @@ export async function editInventoryLabel(original: ManagedRecord, values: Invent await requirePermission(kind, namespace, 'patch', original.metadata.name); operation.assertCurrent(); const path = `${resourcePath(kind, namespace)}/${encodeURIComponent(original.metadata.name)}`; - const current = await proxyFetch(PROVIDER_PROJECT, path); + const current = await readInventoryReference(kind, namespace, original.metadata.name, operation); operation.assertCurrent(); if (!current || current.metadata.uid !== original.metadata.uid || current.metadata.resourceVersion !== original.metadata.resourceVersion || !canEditInventoryLabel(current)) throw new ApiError(409, 'The record or its ownership changed. Reload it before editing.'); const now = new Date().toISOString(); diff --git a/ui/provider/src/lib/inventory-read-access.ts b/ui/provider/src/lib/inventory-read-access.ts new file mode 100644 index 00000000..4fffaccb --- /dev/null +++ b/ui/provider/src/lib/inventory-read-access.ts @@ -0,0 +1,40 @@ +import { createContext } from 'react'; +import { ApiError, PROVIDER_PROJECT, proxyFetch } from './api'; +import { inventoryResources, type Inventory, type InventoryKind } from '../inventory'; +import type { InventoryOperation } from './inventory-operation'; + +export class InventoryReferenceReadError extends ApiError { + constructor(readonly kind: InventoryKind, readonly namespace: string, status: number) { + super(status, 'A related inventory record is unavailable.'); + } +} + +export const InventoryReadAccessContext = createContext<(error: InventoryReferenceReadError) => void>(() => {}); + +export function readFailureIssues(error: InventoryReferenceReadError): Inventory['issues'] { + return error.status === 401 + ? Object.fromEntries(Object.keys(inventoryResources).map(kind => [kind, { status: 401 }])) + : { [error.kind]: { status: error.status } }; +} + +export function redactInventory(source: Inventory, issues: Inventory['issues']): Inventory { + const combined = { ...source.issues, ...issues }; + return { + issues: combined, + slots: combined.DeviceClaim ? [] : source.slots.map(slot => ({ ...slot, devices: combined.Device ? [] : slot.devices })), + unboundDevices: combined.Device ? [] : [...source.unboundDevices, ...(combined.DeviceClaim ? source.slots.flatMap(slot => slot.devices) : [])], + physical: source.physical.filter(record => !combined[record.kind]), + }; +} + +export async function readInventoryReference(kind: InventoryKind, namespace: string, name: string, operation: InventoryOperation): Promise { + operation.assertCurrent(); + try { + const record = await proxyFetch(PROVIDER_PROJECT, `/apis/fleet.datumapis.com/v1alpha1/namespaces/${encodeURIComponent(namespace)}/${inventoryResources[kind]}/${encodeURIComponent(name)}`); + operation.assertCurrent(); + return record; + } catch (error) { + operation.assertCurrent(); + throw new InventoryReferenceReadError(kind, namespace, error instanceof ApiError ? error.status : 0); + } +} From bdde8cfedba2d0a28af69c7e0650cbf01b260b36 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Fri, 20 Nov 2026 22:33:14 -0600 Subject: [PATCH 027/518] fix: mask restricted inventory detail references --- docs/development/staff-inventory-ui.md | 3 ++ .../components/direct-claim-access.test.tsx | 31 +++++++++++++++++++ .../components/legacy-peer-access.test.tsx | 19 ++++++++++++ .../src/components/physical-inventory.tsx | 12 +++---- ui/provider/src/inventory.ts | 23 ++++++++++---- ui/provider/src/pages/device-claim-detail.tsx | 9 +++--- 6 files changed, 80 insertions(+), 17 deletions(-) create mode 100644 ui/provider/src/components/direct-claim-access.test.tsx create mode 100644 ui/provider/src/components/legacy-peer-access.test.tsx diff --git a/docs/development/staff-inventory-ui.md b/docs/development/staff-inventory-ui.md index 84d47129..77850ca1 100644 --- a/docs/development/staff-inventory-ui.md +++ b/docs/development/staff-inventory-ui.md @@ -105,6 +105,9 @@ cancelled before cached records are removed. Session expiry hides all kinds. Reopening inventory starts a fresh access evaluation; refreshing an existing view does not clear its recorded read failures. Search indexes explicit visible fields and readable endpoint identities, not raw records or redacted references. +The retained direct claim route uses the same issue-aware placement and endpoint +labels. Legacy expected peers hide both the referenced device and port whenever +Device reads are unavailable, including temporary collection failures. ### Retained host source evidence diff --git a/ui/provider/src/components/direct-claim-access.test.tsx b/ui/provider/src/components/direct-claim-access.test.tsx new file mode 100644 index 00000000..5571d25b --- /dev/null +++ b/ui/provider/src/components/direct-claim-access.test.tsx @@ -0,0 +1,31 @@ +import { cleanup, render, screen } from '@testing-library/react'; +import { createMemoryRouter, Outlet, RouterProvider } from 'react-router'; +import { afterEach, expect, it, vi } from 'vitest'; +import DeviceClaimDetail from '../pages/device-claim-detail'; +import { fixturePhysicalClaims, fixturePhysicalDevices, fixturePhysicalRecords } from '../lib/fixtures'; +import { inventoryResources } from '../inventory'; + +afterEach(() => { cleanup(); vi.unstubAllGlobals(); }); +it.each(['Facility', 'Rack', 'PowerFeed'] as const)('direct claim route hides denied %s reference with real query and session boundary', async kind => { + const claim = structuredClone(fixturePhysicalClaims[0]); + claim.metadata.namespace = 'default'; + claim.spec.placement = kind === 'Facility' ? { scope: 'Facility', facilityRef: { name: 'secret-denied-reference' } } : { scope: 'RackMembership', rackRef: { name: 'secret-denied-reference' } }; + if (kind === 'PowerFeed') claim.spec.placement = { scope: 'RackMembership', rackRef: { name: 'readable-rack' } }; + const device = structuredClone(fixturePhysicalDevices[0]); + device.metadata.namespace = 'default'; + device.spec.claimRef.name = claim.metadata.name; + const cable = structuredClone(fixturePhysicalRecords.find(record => record.kind === 'Cable')!); + cable.metadata.namespace = 'default'; + cable.spec.lanes = [{ id: 'lane', a: { deviceRef: { name: device.metadata.name }, componentID: 'port', position: 1 }, b: { powerFeedRef: { name: 'secret-denied-reference' }, componentID: 'outlet', position: 1 } }]; + vi.stubGlobal('fetch', vi.fn(async (url: string, init: RequestInit) => { + expect(init.method).toBe('GET'); + const status = url.includes(`/${inventoryResources[kind]}?`) ? 403 : 200; + const items = url.includes('/deviceclaims?') ? [claim] : url.includes('/devices?') ? [device] : url.includes('/cables?') && kind === 'PowerFeed' ? [cable] : []; + return { ok: status === 200, status, json: async () => ({ data: { items } }) }; + })); + const router = createMemoryRouter([{ id: 'layouts/milo.layout', path: '/', loader: () => ({ user: { metadata: { uid: 'reviewer' } } }), element: , children: [{ path: 'plugins/:slug/inventory/:namespace/:claim', element: }] }], { initialEntries: [`/plugins/test/inventory/default/${claim.metadata.name}`] }); + render(); + await screen.findByTestId('fleet-plugin-claim'); + expect(screen.queryAllByText(/secret-denied-reference/)).toEqual([]); + router.dispose(); +}); diff --git a/ui/provider/src/components/legacy-peer-access.test.tsx b/ui/provider/src/components/legacy-peer-access.test.tsx new file mode 100644 index 00000000..89b7dd84 --- /dev/null +++ b/ui/provider/src/components/legacy-peer-access.test.tsx @@ -0,0 +1,19 @@ +import { cleanup, fireEvent, render, screen } from '@testing-library/react'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { MemoryRouter } from 'react-router'; +import { afterEach, expect, it } from 'vitest'; +import { PhysicalInventory } from './physical-inventory'; +import { fixturePhysicalClaims } from '../lib/fixtures'; +import { toInventory } from '../inventory'; + +afterEach(cleanup); +it.each([403, 503])('legacy expected peer must not disclose denied Device identity after %s', status => { + const claim = structuredClone(fixturePhysicalClaims[0]); + delete claim.spec.lifecycle; + claim.spec.ports = [{ name: 'eth0', expectedPeer: { device: 'secret-denied-device', port: 'secret-port' } }]; + const inventory = { ...toInventory([claim], [], []), issues: { Device: { status } } }; + const params = new URLSearchParams({ kind: 'DeviceClaim', record: claim.metadata.name, namespace: claim.metadata.namespace! }); + render(); + fireEvent.click(screen.getByText('Legacy expected ports')); + expect(screen.queryByText(/secret-denied-device/)).not.toBeInTheDocument(); +}); diff --git a/ui/provider/src/components/physical-inventory.tsx b/ui/provider/src/components/physical-inventory.tsx index 41b1c7c7..31d847d6 100644 --- a/ui/provider/src/components/physical-inventory.tsx +++ b/ui/provider/src/components/physical-inventory.tsx @@ -4,6 +4,7 @@ import { Building2, Cable, ClipboardList, HardDrive, Search, Server, Zap } from import { modelLabel, placementLabel, + legacyPeerLabel, slotKey, type Inventory, type RawDevice, @@ -58,9 +59,7 @@ const sections = [ }, ] as const; -export function endpointLabel(endpoint: CableEndpoint): string { - return `${endpoint.deviceRef?.name ?? endpoint.powerFeedRef?.name ?? 'Unknown'}/${endpoint.componentID}:${endpoint.position}`; -} +export { endpointLabel } from '../inventory'; function recordName(entry: RecordEntry) { return entry.record.spec.displayName || entry.record.metadata.name; @@ -172,7 +171,7 @@ export function PhysicalInventory({ inventory: source, onRetry }: { inventory: I ); const plannedPlacement = (claim: RawDeviceClaim) => { const location = claim.spec.placement; - if (!location.scope) return placementLabel({ ...claim, spec: { ...claim.spec, placement: { ...location, facility: inventory.issues?.Facility ? 'Facility unavailable' : location.facility, rack: inventory.issues?.Rack ? 'Rack unavailable' : location.rack } } }); + if (!location.scope) return placementLabel(claim, inventory.issues); const rack = location.rackRef ? find('Rack', claim.metadata.namespace, location.rackRef.name) : undefined; const facilityName = location.facilityRef?.name ?? (rack?.record as PhysicalRecord | undefined)?.spec.facilityRef?.name; @@ -258,6 +257,7 @@ export function PhysicalInventory({ inventory: source, onRetry }: { inventory: I ); function Endpoint({ endpoint, namespace }: { endpoint: CableEndpoint; namespace?: string }) { + if ((endpoint.deviceRef && inventory.issues?.Device) || (endpoint.powerFeedRef && inventory.issues?.PowerFeed)) return Related endpoint unavailable; return ( {endpoint.deviceRef @@ -451,7 +451,7 @@ export function PhysicalInventory({ inventory: source, onRetry }: { inventory: I {device.spec.interfaces?.map((iface) => (
  • {iface.name} · {iface.macAddress ?? 'MAC not recorded'} - {iface.peer && ` · legacy peer ${iface.peer.device}/${iface.peer.port}`} + {iface.peer && ` · legacy peer ${legacyPeerLabel(iface.peer, inventory.issues)}`}
  • ))} @@ -477,7 +477,7 @@ export function PhysicalInventory({ inventory: source, onRetry }: { inventory: I {claim.spec.ports?.map((port) => (
  • {port.name} · {port.type ?? 'Type not recorded'} · {port.speedMbps ?? 'Unknown'} Mb/s - {port.expectedPeer && ` → ${port.expectedPeer.device}/${port.expectedPeer.port}`} + {port.expectedPeer && ` → ${legacyPeerLabel(port.expectedPeer, inventory.issues)}`}
  • ))} diff --git a/ui/provider/src/inventory.ts b/ui/provider/src/inventory.ts index 0f920fa6..e5e6e73e 100644 --- a/ui/provider/src/inventory.ts +++ b/ui/provider/src/inventory.ts @@ -2,7 +2,7 @@ // Device that names it in the same namespace; a replacement leaves more than // one. Devices whose claim is missing are kept separately so they stay visible. -import type { Device as RawDevice, DeviceClaim as RawDeviceClaim, List, PhysicalRecord } from '../../shared/fleet-api'; +import type { CableEndpoint, Device as RawDevice, DeviceClaim as RawDeviceClaim, List, PhysicalRecord } from '../../shared/fleet-api'; export type { RawDevice, RawDeviceClaim }; export type RawDeviceList = List; @@ -53,14 +53,25 @@ export function toInventory(claims: RawDeviceClaim[], devices: RawDevice[], phys }; } -export function placementLabel(claim: RawDeviceClaim): string { +export function placementLabel(claim: RawDeviceClaim, issues?: Inventory['issues']): string { const { facility, rack, position, height = 1, face, scope, facilityRef, rackRef, mount } = claim.spec.placement; - if (scope === 'Facility') return `${facilityRef?.name} · rack and position Unknown`; - if (scope === 'RackMembership') return `${rackRef?.name} · position Unknown (no reserved units)`; - if (scope === 'NonRackUnitMount') return `${rackRef?.name} · mount ${mount}`; + const facilityName = issues?.Facility ? 'Facility unavailable' : facility ?? facilityRef?.name; + const rackName = issues?.Rack ? 'Rack unavailable' : rack ?? rackRef?.name; + if (scope === 'Facility') return `${facilityName} · rack and position Unknown`; + if (scope === 'RackMembership') return `${rackName} · position Unknown (no reserved units)`; + if (scope === 'NonRackUnitMount') return `${rackName} · mount ${mount}`; if (position === undefined) return 'Placement Unknown'; const units = height > 1 ? `U${position}–U${position + height - 1}` : `U${position}`; - return `${facility ?? 'Facility via rack'} · ${rack ?? rackRef?.name} · ${units} ${face}`; + return `${facilityName ?? 'Facility via rack'} · ${rackName} · ${units} ${face}`; +} + +export function endpointLabel(endpoint: CableEndpoint, issues?: Inventory['issues']): string { + if ((endpoint.deviceRef && issues?.Device) || (endpoint.powerFeedRef && issues?.PowerFeed)) return 'Related endpoint unavailable'; + return `${endpoint.deviceRef?.name ?? endpoint.powerFeedRef?.name ?? 'Unknown'}/${endpoint.componentID}:${endpoint.position}`; +} + +export function legacyPeerLabel(peer: { device: string; port: string }, issues?: Inventory['issues'], separator = '/'): string { + return issues?.Device ? 'Related device unavailable' : `${peer.device}${separator}${peer.port}`; } export function modelLabel(identity: { manufacturer?: string; model: string }): string { diff --git a/ui/provider/src/pages/device-claim-detail.tsx b/ui/provider/src/pages/device-claim-detail.tsx index 0cead55f..0a41e0a4 100644 --- a/ui/provider/src/pages/device-claim-detail.tsx +++ b/ui/provider/src/pages/device-claim-detail.tsx @@ -1,11 +1,10 @@ import { FleetPage } from '../components/fleet-page'; -import { endpointLabel } from '../components/physical-inventory'; import { LoadingState } from '../components/states'; import { InventoryAccessState } from '../components/inventory-access-state'; import { InventorySessionBoundary } from '../components/inventory-session-boundary'; import { StatusBadge } from '../components/status-badge'; import { useInventory } from '../lib/api'; -import { currentDevice, modelLabel, placementLabel, slotKey, type RawDevice } from '../inventory'; +import { currentDevice, endpointLabel, legacyPeerLabel, modelLabel, placementLabel, slotKey, type RawDevice } from '../inventory'; import type { Provenance } from '../../../shared/fleet-api'; import { Card, CardContent } from '@datum-cloud/datum-ui/card'; import { Text } from '@datum-cloud/datum-ui/typography'; @@ -122,7 +121,7 @@ function ClaimDetailContent() { <>
    - {placementLabel(slot.claim)} + {placementLabel(slot.claim, data?.issues)} {modelLabel(slot.claim.spec.expectedIdentity)} {slot.claim.spec.expectedIdentity.serial ?? '—'} {slot.claim.metadata.namespace ?? '—'} @@ -137,7 +136,7 @@ function ClaimDetailContent() { {port.name} {port.type ? ` (${port.type}${port.speedMbps ? `, ${port.speedMbps} Mb/s` : ''})` : ''} - {port.expectedPeer ? ` → ${port.expectedPeer.device} ${port.expectedPeer.port}` : ''} + {port.expectedPeer ? ` → ${legacyPeerLabel(port.expectedPeer, data?.issues, ' ')}` : ''} ))}
    @@ -149,7 +148,7 @@ function ClaimDetailContent() { ))}
    - {data?.issues?.Cable ? : !data?.issues?.Device && data?.physical.filter((record) => record.kind === 'Cable' && record.metadata.namespace === slot.claim.metadata.namespace && record.spec.lanes?.some((lane) => slot.devices.some((device) => lane.a.deviceRef?.name === device.metadata.name || lane.b.deviceRef?.name === device.metadata.name))).map((cable) =>
    {cable.spec.displayName} · verification Unknown{cable.spec.lanes?.map((lane) => {endpointLabel(lane.a)} ↔ {endpointLabel(lane.b)})}
    )} + {data?.issues?.Cable ? : !data?.issues?.Device && data?.physical.filter((record) => record.kind === 'Cable' && record.metadata.namespace === slot.claim.metadata.namespace && record.spec.lanes?.some((lane) => slot.devices.some((device) => lane.a.deviceRef?.name === device.metadata.name || lane.b.deviceRef?.name === device.metadata.name))).map((cable) =>
    {cable.spec.displayName} · verification Unknown{cable.spec.lanes?.map((lane) => {endpointLabel(lane.a, data?.issues)} ↔ {endpointLabel(lane.b, data?.issues)})}
    )} No displayed path proves an uncabled or free termination.
    From e99e11a517e27c6276e139c044a2c48b328d7490 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Fri, 20 Nov 2026 23:32:51 -0600 Subject: [PATCH 028/518] fix: render multi-unit rack plans as continuous blocks --- docs/development/staff-inventory-ui.md | 3 ++ .../components/inventory-location.test.tsx | 25 ++++++++++++ .../src/components/inventory-location.tsx | 39 ++++++++++++++++--- .../src/components/physical-inventory.css | 13 ++++--- 4 files changed, 68 insertions(+), 12 deletions(-) diff --git a/docs/development/staff-inventory-ui.md b/docs/development/staff-inventory-ui.md index 77850ca1..76077149 100644 --- a/docs/development/staff-inventory-ui.md +++ b/docs/development/staff-inventory-ui.md @@ -46,6 +46,9 @@ pixel identity or completed authenticated staging acceptance. capacity. Unknown placement stays in the explicit unpositioned section; NonRackUnitMount remains separate. Multiple registrations do not select an active device. Overlapping plans are labeled for review, not resolved silently. + Multi-unit plans render as one continuous block spanning their recorded unit + range, with one detail link; overlapping plans occupy separate visual columns. + Model height alone never supplies missing placement geometry. - Create Facility/Rack facts; rack height is optional. Create an Installation plan at a known Facility or Rack with unknown unit position, then separately register a Device with a real serial or system UUID and typed components. diff --git a/ui/provider/src/components/inventory-location.test.tsx b/ui/provider/src/components/inventory-location.test.tsx index 3f2dd22b..a683f208 100644 --- a/ui/provider/src/components/inventory-location.test.tsx +++ b/ui/provider/src/components/inventory-location.test.tsx @@ -11,6 +11,29 @@ function show(placement = fixturePhysicalClaims[0].spec.placement, issues = {}, const claim = { ...fixturePhysicalClaims[0], spec: { ...fixturePhysicalClaims[0].spec, placement } }; return render(); } +it.each([ + { position: 1, height: 2, face: 'front' as const, row: '41 / span 2' }, + { position: 39, height: 4, face: 'rear' as const, row: '1 / span 4' }, + { position: 12, height: 4, face: 'front' as const, row: '28 / span 4' }, +])('renders one continuous block for $height units at $position on $face', ({ position, height, face, row }) => { + show({ scope: 'RackUnits', rackRef: { name: 'rack-01' }, position, height, face }); + const elevation = screen.getByRole('list', { name: `${face} recorded plans` }); + const links = within(elevation).getAllByRole('link'); + expect(links).toHaveLength(1); + expect(links[0]).toHaveAccessibleName(new RegExp(`U${position}–U${position + height - 1}.*${height}U`)); + expect(links[0].parentElement).toHaveStyle({ gridRow: row, gridColumn: '2' }); + expect(within(elevation).getAllByLabelText('Occupancy unverified')).toHaveLength(42 - height); + expect(within(screen.getByRole('list', { name: `${face === 'front' ? 'rear' : 'front'} recorded plans` })).queryByRole('link')).not.toBeInTheDocument(); +}); +it('keeps overlapping multi-unit plans in separate columns without hiding either', () => { + const claims = [10, 11].map((position, index) => ({ ...fixturePhysicalClaims[0], metadata: { ...fixturePhysicalClaims[0].metadata, name: `overlap-${index}` }, spec: { ...fixturePhysicalClaims[0].spec, displayName: `Plan ${index}`, placement: { scope: 'RackUnits' as const, rackRef: { name: 'rack-01' }, position, height: 2, face: 'front' as const } } })); + render(); + const elevation = screen.getByRole('list', { name: 'front recorded plans' }); + const links = within(elevation).getAllByRole('link', { name: /overlapping plans/ }); + expect(links).toHaveLength(2); + expect(links[0].parentElement).toHaveStyle({ gridColumn: '2', gridRow: '32 / span 2' }); + expect(links[1].parentElement).toHaveStyle({ gridColumn: '3', gridRow: '31 / span 2' }); +}); it('renders recorded front/rear plans, never free units or occupancy percentages', () => { show(); const front = screen.getByRole('list', { name: 'front recorded plans' }); @@ -24,6 +47,8 @@ it.each([ { scope: 'RackMembership' as const, rackRef: { name: 'rack-01' } }, { scope: 'RackUnits' as const, rackRef: { name: 'rack-01' }, position: 45, height: 1, face: 'front' as const }, { scope: 'RackUnits' as const, rackRef: { name: 'rack-01' }, position: 12, height: 1 }, + { scope: 'RackUnits' as const, rackRef: { name: 'rack-01' }, position: 41, height: 4, face: 'front' as const }, + { scope: 'RackUnits' as const, rackRef: { name: 'rack-01' }, position: 12, face: 'front' as const }, ])('keeps incomplete or out-of-range geometry out of the elevation: %j', placement => { show(placement); expect(within(screen.getByRole('list', { name: 'front recorded plans' })).queryByRole('link')).not.toBeInTheDocument(); diff --git a/ui/provider/src/components/inventory-location.tsx b/ui/provider/src/components/inventory-location.tsx index c58eec5b..883459ad 100644 --- a/ui/provider/src/components/inventory-location.tsx +++ b/ui/provider/src/components/inventory-location.tsx @@ -22,6 +22,38 @@ function Equipment({ slots, devicesDenied }: { slots: InventorySlot[]; devicesDe
    ; } +function RackFace({ rack, slots, side }: { rack: PhysicalRecord; slots: InventorySlot[]; side: 'front' | 'rear' }) { + const height = rack.spec.heightUnits!; + const plans = slots.map(slot => ({ slot, ...rackGeometry(slot, rack)! })) + .filter(plan => plan.face === side) + .sort((first, second) => first.position - second.position || first.slot.key.localeCompare(second.slot.key)); + const laneEnds: number[] = []; + const placed = plans.map(plan => { + let lane = laneEnds.findIndex(end => end < plan.position); + if (lane === -1) lane = laneEnds.length; + laneEnds[lane] = plan.position + plan.height - 1; + return { ...plan, lane }; + }); + return

    {side === 'front' ? 'Front' : 'Rear'}

    +
      + {Array.from({ length: height }, (_, index) => height - index).map(unit => { + const recorded = plans.some(plan => unit >= plan.position && unit < plan.position + plan.height); + return
    1. U{unit}{!recorded && —}
    2. ; + })} + {placed.map(plan => { + const top = plan.position + plan.height - 1; + const overlap = plans.some(other => other.slot.key !== plan.slot.key && other.position <= top && other.position + other.height > plan.position); + const name = plan.slot.claim.spec.displayName || plan.slot.claim.metadata.name; + const range = plan.height === 1 ? `U${plan.position}` : `U${plan.position}–U${top}`; + const label = `${name} · ${range} · ${plan.height}U${overlap ? ' · overlapping plans, review required' : ''}`; + return
    3. + {name}{plan.height > 1 && {range} · {plan.height}U}{overlap && Overlapping plans} +
    4. ; + })} +
    +
    ; +} + export function RackOverview({ rack, inventory }: { rack: PhysicalRecord; inventory: Inventory }) { const [face, setFace] = useState<'both' | 'front' | 'rear'>('both'); const slots = inventory.slots.filter(slot => slot.claim.metadata.namespace === rack.metadata.namespace && slot.claim.spec.placement.rackRef?.name === rack.metadata.name); @@ -36,12 +68,7 @@ export function RackOverview({ rack, inventory }: { rack: PhysicalRecord; invent

    Rack elevation

    {height ? `${height}U` : 'Height unknown'}
    {(['both', 'front', 'rear'] as const).map(value => )}

    Recorded installation plans, not verified occupancy. Blank units are not available space.

    - {denied ?

    Installation details unavailable. Rack positions cannot be shown.

    : !height ?

    Rack height is not recorded. Equipment remains listed without invented slots.

    :
    {(['front', 'rear'] as const).filter(value => face === 'both' || face === value).map(side =>

    {side === 'front' ? 'Front' : 'Rear'}

      - {Array.from({ length: Math.min(height, 100) }, (_, index) => height - index).map(unit => { - const plans = positioned.filter(slot => { const geometry = rackGeometry(slot, rack)!; return geometry.face === side && unit >= geometry.position && unit < geometry.position + geometry.height; }); - return
    1. U{unit}
      {plans.length ? plans.map(slot => 1 ? ' · overlapping plans, review required' : ''}`} to={inventoryHref('DeviceClaim', slot.claim.metadata.namespace, slot.claim.metadata.name)} aria-label={`Review ${slot.claim.spec.displayName || slot.claim.metadata.name} at U${unit}, ${side}${plans.length > 1 ? ', overlapping plans' : ''}`}>{slot.claim.spec.displayName || slot.claim.metadata.name}) : —}
    2. ; - })} -
    )}
    } + {denied ?

    Installation details unavailable. Rack positions cannot be shown.

    : !height ?

    Rack height is not recorded. Equipment remains listed without invented slots.

    :
    {(['front', 'rear'] as const).filter(value => face === 'both' || face === value).map(side => )}
    }

    Equipment & installation plans

    diff --git a/ui/provider/src/components/physical-inventory.css b/ui/provider/src/components/physical-inventory.css index 933c2fd9..e2c407ab 100644 --- a/ui/provider/src/components/physical-inventory.css +++ b/ui/provider/src/components/physical-inventory.css @@ -59,12 +59,13 @@ .inventory-rack-faces { display:flex; gap:10px; } .inventory-rack-faces > div { flex:1; min-width:0; } .inventory-rack-faces h4 { text-align:center; text-transform:uppercase; font-size:11px; letter-spacing:.06em; margin-bottom:8px; } -.inventory-rack-units { list-style:none; padding:0; margin:0; border:1px solid var(--border,#dce3df); } -.inventory-rack-units li { height:16px; display:grid; grid-template-columns:28px 1fr; border-bottom:1px solid var(--border,#dce3df); font-size:9px; line-height:15px; } -.inventory-rack-units li > span { padding:0 3px; background:var(--muted,#f5f7f5); } -.inventory-rack-units li > div { min-width:0; padding:0 3px; display:flex; } -.inventory-rack-units li a { display:block; flex:1; min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; } -.inventory-unit-recorded { background:var(--accent,#eaf1ed); } +.inventory-rack-units { display:grid; list-style:none; padding:0; margin:0; border:1px solid var(--border,#dce3df); font-size:9px; line-height:15px; } +.inventory-rack-unit { display:grid; grid-template-columns:28px 1fr; border-bottom:1px solid var(--border,#dce3df); } +.inventory-rack-unit > span { padding:0 3px; background:var(--muted,#f5f7f5); } +.inventory-rack-plan { z-index:1; min-width:0; min-height:0; border:1px solid var(--border,#dce3df); background:var(--accent,#eaf1ed); } +.inventory-rack-plan a { display:flex; flex-direction:column; justify-content:center; height:100%; min-width:0; padding:0 3px; overflow:hidden; white-space:nowrap; } +.inventory-rack-plan a:focus-visible { outline:2px solid var(--ring,#32765a); outline-offset:-2px; } +.inventory-rack-plan small { font-size:8px; line-height:12px; } .inventory-face-switch { display:flex; gap:4px; } .inventory-face-switch button { flex:1; padding:6px; border:1px solid var(--border,#dce3df); border-radius:5px; font-size:12px; cursor:pointer; } .inventory-face-switch button[aria-pressed=true] { background:var(--accent,#eaf1ed); font-weight:600; } From 2e7ad8a3dbe0e6eeada4842ec5afcdee9543bd72 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Fri, 20 Nov 2026 23:39:54 -0600 Subject: [PATCH 029/518] fix: fit overlap labels within short rack plans --- .../src/components/inventory-location.test.tsx | 14 ++++++++++---- ui/provider/src/components/inventory-location.tsx | 4 ++-- ui/provider/src/components/physical-inventory.css | 5 ++++- 3 files changed, 16 insertions(+), 7 deletions(-) diff --git a/ui/provider/src/components/inventory-location.test.tsx b/ui/provider/src/components/inventory-location.test.tsx index a683f208..790b4c71 100644 --- a/ui/provider/src/components/inventory-location.test.tsx +++ b/ui/provider/src/components/inventory-location.test.tsx @@ -25,14 +25,20 @@ it.each([ expect(within(elevation).getAllByLabelText('Occupancy unverified')).toHaveLength(42 - height); expect(within(screen.getByRole('list', { name: `${face === 'front' ? 'rear' : 'front'} recorded plans` })).queryByRole('link')).not.toBeInTheDocument(); }); -it('keeps overlapping multi-unit plans in separate columns without hiding either', () => { - const claims = [10, 11].map((position, index) => ({ ...fixturePhysicalClaims[0], metadata: { ...fixturePhysicalClaims[0].metadata, name: `overlap-${index}` }, spec: { ...fixturePhysicalClaims[0].spec, displayName: `Plan ${index}`, placement: { scope: 'RackUnits' as const, rackRef: { name: 'rack-01' }, position, height: 2, face: 'front' as const } } })); +it.each([1, 2])('keeps overlapping %iU plans identifiable with height-aware labels', height => { + const claims = [10, 10 + height - 1].map((position, index) => ({ ...fixturePhysicalClaims[0], metadata: { ...fixturePhysicalClaims[0].metadata, name: `overlap-${index}` }, spec: { ...fixturePhysicalClaims[0].spec, displayName: `Plan ${index}`, placement: { scope: 'RackUnits' as const, rackRef: { name: 'rack-01' }, position, height, face: 'front' as const } } })); render(); const elevation = screen.getByRole('list', { name: 'front recorded plans' }); const links = within(elevation).getAllByRole('link', { name: /overlapping plans/ }); expect(links).toHaveLength(2); - expect(links[0].parentElement).toHaveStyle({ gridColumn: '2', gridRow: '32 / span 2' }); - expect(links[1].parentElement).toHaveStyle({ gridColumn: '3', gridRow: '31 / span 2' }); + expect(links[0].parentElement).toHaveStyle({ gridColumn: '2', gridRow: `${34 - height} / span ${height}` }); + expect(links[1].parentElement).toHaveStyle({ gridColumn: '3', gridRow: `${35 - 2 * height} / span ${height}` }); + for (const link of links) { + expect(within(link).getByText('!')).toHaveClass('inventory-rack-overlap'); + expect(link.querySelectorAll('small')).toHaveLength(height > 1 ? 1 : 0); + expect(link.querySelector('.inventory-rack-plan-name')).toHaveTextContent(/Plan/); + } + expect(screen.getByText(/! indicates overlapping plans requiring review/)).toBeInTheDocument(); }); it('renders recorded front/rear plans, never free units or occupancy percentages', () => { show(); diff --git a/ui/provider/src/components/inventory-location.tsx b/ui/provider/src/components/inventory-location.tsx index 883459ad..df20fae1 100644 --- a/ui/provider/src/components/inventory-location.tsx +++ b/ui/provider/src/components/inventory-location.tsx @@ -47,7 +47,7 @@ function RackFace({ rack, slots, side }: { rack: PhysicalRecord; slots: Inventor const range = plan.height === 1 ? `U${plan.position}` : `U${plan.position}–U${top}`; const label = `${name} · ${range} · ${plan.height}U${overlap ? ' · overlapping plans, review required' : ''}`; return
  • - {name}{plan.height > 1 && {range} · {plan.height}U}{overlap && Overlapping plans} + {overlap && }{name}{plan.height > 1 && {range} · {plan.height}U}
  • ; })} @@ -67,7 +67,7 @@ export function RackOverview({ rack, inventory }: { rack: PhysicalRecord; invent
    diff --git a/ui/provider/src/components/physical-inventory.css b/ui/provider/src/components/physical-inventory.css index e2c407ab..4db9331a 100644 --- a/ui/provider/src/components/physical-inventory.css +++ b/ui/provider/src/components/physical-inventory.css @@ -64,8 +64,11 @@ .inventory-rack-unit > span { padding:0 3px; background:var(--muted,#f5f7f5); } .inventory-rack-plan { z-index:1; min-width:0; min-height:0; border:1px solid var(--border,#dce3df); background:var(--accent,#eaf1ed); } .inventory-rack-plan a { display:flex; flex-direction:column; justify-content:center; height:100%; min-width:0; padding:0 3px; overflow:hidden; white-space:nowrap; } +.inventory-rack-plan-heading { display:flex; align-items:center; gap:3px; flex:none; min-width:0; line-height:12px; } +.inventory-rack-plan-name { min-width:0; overflow:hidden; text-overflow:ellipsis; } +.inventory-rack-overlap { flex:none; font-weight:700; } .inventory-rack-plan a:focus-visible { outline:2px solid var(--ring,#32765a); outline-offset:-2px; } -.inventory-rack-plan small { font-size:8px; line-height:12px; } +.inventory-rack-plan small { flex:none; overflow:hidden; text-overflow:ellipsis; font-size:8px; line-height:12px; } .inventory-face-switch { display:flex; gap:4px; } .inventory-face-switch button { flex:1; padding:6px; border:1px solid var(--border,#dce3df); border-radius:5px; font-size:12px; cursor:pointer; } .inventory-face-switch button[aria-pressed=true] { background:var(--accent,#eaf1ed); font-weight:600; } From f6a2cf4d6e8414b3c377ab907a7e63a2a03c7987 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sat, 21 Nov 2026 09:37:37 -0600 Subject: [PATCH 030/518] feat: add observational Device placement and device-first inventory views --- .../inventory/crds/fleet.datumapis.com.yaml | 60 ++++++++ docs/development/device-reported-placement.md | 134 +++++++++++++++++ docs/development/staff-inventory-ui.md | 5 + docs/operations/netbox-physical-import.md | 8 +- docs/operations/physical-inventory.md | 3 + hack/device_placement.py | 138 ++++++++++++++++++ hack/netbox_inventory.py | 5 + hack/test_device_placement.py | 88 +++++++++++ .../v1alpha1/reported_placement_test.go | 106 ++++++++++++++ internal/api/inventory/v1alpha1/types.go | 14 ++ .../components/inventory-location.test.tsx | 36 +++-- .../src/components/inventory-location.tsx | 54 +++---- .../components/physical-inventory.test.tsx | 2 +- .../src/components/physical-inventory.tsx | 39 +++-- ui/provider/src/lib/device-placement.test.ts | 61 ++++++++ ui/provider/src/lib/device-placement.ts | 59 ++++++++ ui/provider/src/pages/device-claim-detail.tsx | 11 +- ui/shared/fleet-api.ts | 14 ++ 18 files changed, 776 insertions(+), 61 deletions(-) create mode 100644 docs/development/device-reported-placement.md create mode 100644 hack/device_placement.py create mode 100644 hack/test_device_placement.py create mode 100644 internal/api/inventory/v1alpha1/reported_placement_test.go create mode 100644 ui/provider/src/lib/device-placement.test.ts create mode 100644 ui/provider/src/lib/device-placement.ts diff --git a/config/components/inventory/crds/fleet.datumapis.com.yaml b/config/components/inventory/crds/fleet.datumapis.com.yaml index 181d6839..6a417007 100644 --- a/config/components/inventory/crds/fleet.datumapis.com.yaml +++ b/config/components/inventory/crds/fleet.datumapis.com.yaml @@ -315,6 +315,12 @@ spec: message: claimRef is immutable; bind replacement hardware as a new Device - rule: self.identity == oldSelf.identity message: identity is immutable; a hardware swap is a new Device + - rule: has(self.reportedPlacement) == has(oldSelf.reportedPlacement) && (!has(self.reportedPlacement) || self.reportedPlacement == oldSelf.reportedPlacement) + message: placement corrections are disabled pending authenticated durable audit; additions and removals are corrections too + - rule: '!has(self.reportedPlacement) || (has(self.identity.sourceIdentity) && has(self.provenance.source) && self.provenance.method == "NetBoxImport" && self.reportedPlacement.observedAt == self.provenance.source.observedAt && self.reportedPlacement.snapshotDigest == self.provenance.source.snapshotDigest)' + message: reported placement must retain the imported source snapshot and observation time + - rule: '!has(self.reportedPlacement) || self.reportedPlacement.observedAt <= self.provenance.recordedAt' + message: the source observation cannot postdate its recording - rule: '!has(self.interfaces) || self.interfaces.all(a, !has(a.macAddress) || (self.interfaces.filter(b, has(b.macAddress) && b.macAddress == a.macAddress).size() == 1 && (!has(self.unmappedMACAddresses) || !(a.macAddress in self.unmappedMACAddresses))))' @@ -350,6 +356,60 @@ spec: self.components.exists(c, c.id == a.componentID)))' message: service associations must reference present components properties: + reportedPlacement: + type: object + required: [revision, observedAt, snapshotDigest] + x-kubernetes-validations: + - rule: '(!has(self.position) && !has(self.height) && !has(self.face) && !has(self.fullDepth) && !has(self.mount)) || has(self.rackRef)' + message: rack geometry requires a reported rack + - rule: '!has(self.mount) || (!has(self.position) && !has(self.height) && !has(self.face) && !has(self.fullDepth))' + message: non-unit mounts cannot also report unit geometry + - rule: '!has(self.position) || !has(self.height) || self.position + self.height <= 101.0' + message: reported geometry exceeds supported rack bounds + properties: + revision: + type: integer + enum: [1] + observedAt: + type: string + format: date-time + snapshotDigest: + type: string + pattern: ^sha256:[a-f0-9]{64}$ + facilityRef: + type: object + required: [name] + properties: + name: + type: string + minLength: 1 + maxLength: 253 + rackRef: + type: object + required: [name] + properties: + name: + type: string + minLength: 1 + maxLength: 253 + position: + type: number + minimum: 1 + maximum: 100 + height: + type: number + minimum: 0 + exclusiveMinimum: true + maximum: 100 + face: + type: string + enum: [front, rear] + fullDepth: + type: boolean + mount: + type: string + minLength: 1 + maxLength: 253 claimRef: type: object required: diff --git a/docs/development/device-reported-placement.md b/docs/development/device-reported-placement.md new file mode 100644 index 00000000..44792a7a --- /dev/null +++ b/docs/development/device-reported-placement.md @@ -0,0 +1,134 @@ +# Device-reported placement + +[Physical inventory](../operations/physical-inventory.md) · [Staff inventory UI](staff-inventory-ui.md) · [Optional NetBox review](../operations/netbox-physical-import.md) + +## Implemented contract + +`Device.spec.reportedPlacement` is optional observational data on the existing +physical asset, not another inventory, allocation, or installation identity. +It describes what the retained import source reported. It does not assert a +physical move, verified occupancy, reservation, availability, or active binding. +Inventory has no placement verification or reservation controller today. +MachineCapacity's device reference and allocator authority are unchanged. + +The report contains `revision: 1`, `observedAt`, `snapshotDigest`, optional +`facilityRef`/`rackRef`, and independently optional `position`, `height`, `face`, +`fullDepth`, or a non-unit `mount`. Omission means unknown; there are no inferred +1U, face, depth, or mount defaults. Geometry requires a rack; mount and unit +geometry are mutually exclusive. Positive fractional position and height can be +retained, but only complete integral in-range geometry is drawn in an elevation. +Full-depth reports appear on both faces; unknown depth never proves opposite-face +clearance. Overlap columns and continuous multi-U blocks are retained. + +Initially reports can be supplied **only when creating a new imported Device**. +They require matching NetBoxImport/source identity, observation time and snapshot +digest in existing provenance. Source identity is not authenticated chassis +identity. `recordedBy` is client attribution, not an authenticated audit principal. +The ordinary spec timestamp rule still applies to other edits. + +Old objects without reports remain valid, including unchanged updates. Device +identity/claimRef immutability, typed claim placement immutability, lifecycle +removal rejection and legacy placement behavior are unchanged. References remain +name-only: CEL cannot validate existence, incarnation, ownership, rack bounds or +agreement with a claim. Offline checks are not cross-object admission guarantees. + +## Corrections are deliberately disabled + +There is no inventory authenticated correction service, durable append-only audit +store, or server-side per-record ownership policy. The manager role grants +create/update/patch project-wide across six kinds, not owner/namespace isolation. +Portal managed-field checks are a UI restriction, not a security boundary. +Labels, field managers and caller-supplied actors cannot authorize corrections. +No privileges are added here. + +Device CEL rejects **all changes to reportedPlacement on update**, including +adding the first report, removing it, same-rack enrichment and moves. Direct +PATCH/PUT and bundled edits cannot bypass this gate. The UI explains the disabled +state; it has no correction dispatch path. This does not freeze unrelated existing +inventory edits or promise authenticated history for them. Initial report +creation still uses existing IAM, not special importer-only authorization. + +Revision 1 is an immutable snapshot, **not an append-only revision history**. +Enabling corrections requires a separately reviewed implementation retaining +exact inputs before effects, independently established operator ownership, +project/namespace and UID/resourceVersion/reference-incarnation checks, same-rack +enrichment only, protected-field/bundled-change rejection, authenticated durable +actor/reason/before/after evidence, and readback/unknown-outcome reconciliation. +That audit contract must be implemented and tested before lifting CEL. Legacy +Flux ownership, unresolved ownership, contradictions and rack moves remain +blocked. Never delete/recreate/rebind to bypass the gate. + +## Readers and history + +Device detail, filters, location links, rack/facility equipment and elevations +prefer the Device report. Partial reports never borrow geometry from a claim. +Without a report, the claim is explicitly labelled **Claim-derived fallback**, +not verified current location. Multiple registrations remain historical; neither +newest timestamp nor latest registration selects an active asset. A reported +Device is not duplicated as claim fallback. Claimless readable reports remain +visible. Denied references are masked; denied claims cannot supply fallback; +partial collection counts remain incomplete. + +The claim section is registration/intent history. `lifecycle: Installation` is +the sole typed lifecycle, not an existing/prospective discriminator. No automatic +future-installation classification is added. Existing session, navigation/focus, +denial, keyboard and uncertain-dispatch protections are reused. + +## Offline review and rollout + +For a **new** import candidate, per-device mapping `includeReportedPlacement: true` +opts into source reports. Default importer output is unchanged; existing cohorts +are not migrated. This is direct API candidate data, not GitOps or periodic sync. +Review source semantics: reported positions can themselves be synthetic. + +For existing devices, the offline review tool takes only local files: + +```sh +python3 hack/device_placement.py --snapshot /private/path/source.json \ + --target /private/path/target.json --allowlist /private/path/allowlist.json \ + --output /private/path/review +``` + +Target has `target` (exact reviewed project/namespace destination) and `items` +with retained Device, DeviceClaim and Rack snapshots. Allowlist has exactly +`target` and `devices`; each selection has exactly `name`, `namespace`, `uid`, +`resourceVersion`, `sourceID`. The private, **non-executable, blocked** output +retains source/target digests, before/proposed-after records, reference snapshots, +and UID/resourceVersion test preconditions. No patch body, API client, retry or +apply mode exists. Source snapshots remain outside Git. + +The planner rejects stale/replaced targets, duplicate selections, source/rack +contradictions, unknown incarnations, positioned/legacy claims, Flux markers, +absent source positions and out-of-bounds geometry. Absence of Flux markers does +not prove ownership: every output is blocked. Proposed provenance preserves +method/source identity, advancing evidence only in the proposed record. + +The requested small enrichment cohort is a private review artifact, not a rollout. +Null-position PDUs remain unknown; separately imported exact-position claims +remain labelled fallback. Legacy inventory and capacity are untouched. Later +migration requires fresh source and target snapshots, not these retained inputs. + +After independent review/CI, deploy additive schema and readers before explicit +new-record writers. Verify roundtrip before enabling writers. Existing-record +writers remain disabled in this release. After a future audit implementation, +separately approve one same-rack canary, retain exact UID/resourceVersion inputs, +write conditionally, and read back exact UID/spec before proceeding. Timeout is +unknown: GET and reconcile. Replaced UID, changed baseline or competing revision +is conflict, never automatic retry permission. Do not roll back to a schema that +prunes reports or delete objects as rollback. No live writes/deployment are part +of this change. + +## Validation + +```sh +go test -race ./internal/api/inventory/v1alpha1 ./internal/controller/... +python3 -m unittest discover -s hack -p 'test_netbox_inventory.py' +python3 -m unittest discover -s hack -p 'test_device_placement.py' +cd ui/provider && pnpm test && pnpm typecheck && pnpm build +``` + +Tests cover old admission, geometry, provenance, direct-update bypass attempts, +exact selection, stale UID/revision, contradictions, projection/fallback, denials, +multiple registrations and existing session/navigation regressions. They do not +establish live IAM enforcement, durable audit, cross-object admission, browser +acceptance or deployment readiness. diff --git a/docs/development/staff-inventory-ui.md b/docs/development/staff-inventory-ui.md index 76077149..35d6b398 100644 --- a/docs/development/staff-inventory-ui.md +++ b/docs/development/staff-inventory-ui.md @@ -63,6 +63,11 @@ pixel identity or completed authenticated staging acceptance. ## Authorization, ownership and concurrency +Device source reports and labelled claim fallback now share a placement +projection. See [Device-reported placement](device-reported-placement.md) for the +additive contract and server-enforced correction freeze. Imported corrections +remain disabled; import provenance alone is not proof of another writer's ownership. + The existing `fleet.datumapis.com-inventory-manager` role inherits the viewer and adds create/update/patch for six kinds, project-wide. The UI uses exact-resource SelfSubjectAccessReviews and the signed-in principal's API request, never group diff --git a/docs/operations/netbox-physical-import.md b/docs/operations/netbox-physical-import.md index b7de9fae..12332415 100644 --- a/docs/operations/netbox-physical-import.md +++ b/docs/operations/netbox-physical-import.md @@ -1,5 +1,9 @@ # Optional NetBox review aids for manual inventory +[Device-reported placement](../development/device-reported-placement.md) adds +explicit per-device source-report opt-in for new candidates and a blocked offline +review planner for existing records. Claim placement semantics remain unchanged. + [Physical inventory](physical-inventory.md) · [Inventory proposal](../proposals/fleet-management/inventory.md) · [Detailed proposed contracts](../proposals/fleet-management/inventory-reference.md) Start with [manual entry and operator review](physical-inventory.md#manually-record-a-small-installation). @@ -50,8 +54,8 @@ remain Unknown. Existing editor delete permissions are not a safe retirement API explicit handover protocol; the importer does not create a replacement identity to work around immutability. - A Facility reference means no rack is asserted. `RackMembership` records a known - rack but forbids position, height and face. The importer deliberately imports - no exact rack-unit positions, including seemingly plausible positions. This + rack but forbids position, height and face. The default importer deliberately imports + no exact claim rack-unit positions, including seemingly plausible positions. This prevents servers.com's generated 1U placements from becoming occupied or verified footprints. The API also represents exact `RackUnits` and `NonRackUnitMount` plans for separately reviewed manual records. diff --git a/docs/operations/physical-inventory.md b/docs/operations/physical-inventory.md index ffe06975..5a3c24b3 100644 --- a/docs/operations/physical-inventory.md +++ b/docs/operations/physical-inventory.md @@ -1,5 +1,8 @@ # Planning and registering physical devices +For additive source reports and the server-enforced correction freeze, see +[Device-reported placement](../development/device-reported-placement.md). + [Operations guide](README.md) · [Architecture](../architecture/README.md) · [Implementation status](../development/README.md) diff --git a/hack/device_placement.py b/hack/device_placement.py new file mode 100644 index 00000000..c8760268 --- /dev/null +++ b/hack/device_placement.py @@ -0,0 +1,138 @@ +"""Offline Device placement review only. No API client or execution path.""" + +import argparse +import copy +import datetime +import math +import sys +from pathlib import Path + +from netbox_inventory import digest, read_json, reference_id, write_private, private_output + + +def source_report(snapshot, device, model, rack_name=None, facility_name=None): + report = {"revision": 1, "observedAt": snapshot["observedAt"], "snapshotDigest": digest(snapshot)} + if facility_name: + report["facilityRef"] = {"name": facility_name} + if not rack_name: + return report + report["rackRef"] = {"name": rack_name} + for source, field, minimum in ((device, "position", 1), (model, "u_height", 0)): + raw = source.get(field) + if raw is None: + continue + if isinstance(raw, bool): + raise ValueError("invalid source geometry") + try: + number = float(raw) + except (ValueError, TypeError): + raise ValueError("invalid source geometry") from None + if field == "u_height" and number == 0: + continue + if not math.isfinite(number) or number < minimum or number > 100: + raise ValueError("invalid source geometry") + report["position" if field == "position" else "height"] = number + if report.get("position", 1) + report.get("height", 0) > 101: + raise ValueError("source geometry exceeds supported rack bounds") + face = device.get("face") + if isinstance(face, dict): + face = face.get("value") + if face is not None and face != "": + if face not in ("front", "rear"): + raise ValueError("invalid source face") + report["face"] = face + if isinstance(model.get("is_full_depth"), bool): + report["fullDepth"] = model["is_full_depth"] + return report + + +def enrichment_plan(snapshot, target, allowlist): + destination = target.get("target", {}) + if set(destination) != {"project", "namespace"} or not all(isinstance(value, str) and value for value in destination.values()): + raise ValueError("explicit direct-API project and namespace required") + if set(allowlist) != {"target", "devices"} or allowlist["target"] != target.get("target"): + raise ValueError("exact target and device allowlist required") + if not allowlist["devices"] or snapshot.get("errors"): + raise ValueError("empty allowlist or incomplete source snapshot") + datetime.datetime.fromisoformat(snapshot["observedAt"].replace("Z", "+00:00")) + objects = snapshot["objects"] + sources = {str(record["id"]): record for record in objects["dcim/devices"]} + models = {str(record["id"]): record for record in objects["dcim/device-types"]} + if len(sources) != len(objects["dcim/devices"]) or len(models) != len(objects["dcim/device-types"]): + raise ValueError("duplicate source identity") + records = {} + for record in target["items"]: + key = (record["kind"], record["metadata"].get("namespace"), record["metadata"]["name"]) + if key in records: + raise ValueError("duplicate target identity") + records[key] = record + planned, seen = [], set() + for selection in allowlist["devices"]: + if set(selection) != {"name", "namespace", "uid", "resourceVersion", "sourceID"}: + raise ValueError("device allowlist has unexpected or missing fields") + if selection["namespace"] != destination["namespace"]: + raise ValueError("selection is outside the reviewed target namespace") + key = ("Device", selection["namespace"], selection["name"]) + if key in seen: + raise ValueError("duplicate allowlist target") + seen.add(key) + device = records[key] + metadata, spec = device["metadata"], device["spec"] + if any(not selection[field] or metadata.get(field) != selection[field] for field in ("uid", "resourceVersion")) or metadata.get("deletionTimestamp"): + raise ValueError("stale or replaced target") + provenance = spec["provenance"] + if datetime.datetime.fromisoformat(snapshot["observedAt"].replace("Z", "+00:00")) <= datetime.datetime.fromisoformat(provenance["recordedAt"].replace("Z", "+00:00")): + raise ValueError("source snapshot does not advance the retained record revision") + identity = {"system": snapshot["source"], "type": "dcim/devices", "id": selection["sourceID"]} + if provenance["method"] != "NetBoxImport" or spec["identity"].get("sourceIdentity") != identity or any(provenance.get("source", {}).get(field) != value for field, value in identity.items()): + raise ValueError("not a matching imported device") + if any("flux" in entry.get("manager", "").lower() or "kustomize-controller" in entry.get("manager", "").lower() for entry in metadata.get("managedFields", [])): + raise ValueError("legacy Flux records are excluded") + claim = records[("DeviceClaim", selection["namespace"], spec["claimRef"]["name"])] + placement = claim["spec"]["placement"] + if claim["spec"].get("lifecycle") != "Installation" or placement.get("scope") != "RackMembership" or spec.get("reportedPlacement"): + raise ValueError("only previously unreported rack-membership enrichment is reviewable") + rack = records[("Rack", selection["namespace"], placement["rackRef"]["name"])] + source = sources[selection["sourceID"]] + rack_source = rack["spec"]["provenance"].get("source", {}) + if rack_source.get("system") != snapshot["source"] or rack_source.get("type") != "dcim/racks" or rack_source.get("id") != reference_id(source.get("rack")): + raise ValueError("rack contradiction or unresolved rack source") + for reference in (claim, rack): + if not reference["metadata"].get("uid") or not reference["metadata"].get("resourceVersion") or reference["metadata"].get("deletionTimestamp"): + raise ValueError("reference incarnation unresolved") + model = models[reference_id(source["device_type"])] + report = source_report(snapshot, source, model, rack["metadata"]["name"]) + if report.get("position") is None: + raise ValueError("selected enrichment lacks a source position") + height = rack["spec"].get("heightUnits") + if not height or report["position"] > height or ("height" in report and report["position"] + report["height"] - 1 > height): + raise ValueError("source position outside retained rack bounds") + after = copy.deepcopy(device) + after["spec"]["reportedPlacement"] = report + after["spec"]["provenance"]["recordedAt"] = snapshot["observedAt"] + after["spec"]["provenance"]["source"].update(observedAt=snapshot["observedAt"], snapshotDigest=digest(snapshot), mappingRevision="device-reported-placement-review-v1") + planned.append({"selection": selection, "before": device, "proposedAfter": after, "references": [claim, rack], "sourceDevice": source, "sourceModel": model, + "preconditions": [{"op": "test", "path": "/metadata/uid", "value": selection["uid"]}, {"op": "test", "path": "/metadata/resourceVersion", "value": selection["resourceVersion"]}], + "disposition": "Blocked: correction admission closed; ownership and authenticated durable audit unresolved"}) + return {"version": 1, "executable": False, "applied": False, "sourceDigest": digest(snapshot), "targetDigest": digest(target), "allowlistDigest": digest(allowlist), "target": target["target"], "devices": planned, + "next": "Fresh source and target snapshots required after reviewed audit/admission implementation. Review one canary, retain exact inputs before dispatch, read back exact UID/spec. On timeout reconcile by GET; changed UID or competing revision is conflict, never retry automatically. No rollback deletion or observation-pruning schema rollback."} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + for name in ("snapshot", "target", "allowlist", "output"): + parser.add_argument("--" + name, required=True) + args = parser.parse_args() + result = enrichment_plan(read_json(args.snapshot), read_json(args.target), read_json(args.allowlist)) + output = Path(args.output) + private_output(output) + write_private(output / "placement-review.json", result) + print("Blocked offline review saved; no writes dispatched:", len(result["devices"])) + + +if __name__ == "__main__": + try: + main() + except (ValueError, OSError, KeyError, TypeError) as error: + print("Placement review stopped:", str(error) if isinstance(error, ValueError) else type(error).__name__, file=sys.stderr) + sys.exit(2) diff --git a/hack/netbox_inventory.py b/hack/netbox_inventory.py index c4dbeb0d..f6661ec5 100644 --- a/hack/netbox_inventory.py +++ b/hack/netbox_inventory.py @@ -292,6 +292,9 @@ def devices(self): if serial and selected["serialMeaning"] == "chassis": asset_identity["serial"] = serial spec = {"displayName": record.get("name") or name, "claimRef": local_ref(claim_name), "identity": asset_identity, "topologyAuthority": "Cable"} + if selected.get("includeReportedPlacement") is True: + from device_placement import source_report + spec["reportedPlacement"] = source_report(self.snapshot, record, model, placement.get("rackRef", {}).get("name"), placement.get("facilityRef", {}).get("name")) shape = {} try: height = float(model.get("u_height", "")) @@ -582,6 +585,8 @@ def dependencies(record): references.append(kind + "/" + spec[field]["name"]) if spec.get("placement", {}).get(field): references.append(kind + "/" + spec["placement"][field]["name"]) + if spec.get("reportedPlacement", {}).get(field): + references.append(kind + "/" + spec["reportedPlacement"][field]["name"]) for lane in spec.get("lanes", []): for endpoint in (lane["a"], lane["b"]): for field, kind in (("deviceRef", "Device"), ("powerFeedRef", "PowerFeed")): diff --git a/hack/test_device_placement.py b/hack/test_device_placement.py new file mode 100644 index 00000000..41037d50 --- /dev/null +++ b/hack/test_device_placement.py @@ -0,0 +1,88 @@ +import copy +import unittest + +import device_placement as placement +import netbox_inventory as inventory +from test_netbox_inventory import fixture + + +def inputs(): + snapshot, mapping = fixture() + _, candidates = inventory.Planner(snapshot, mapping).run() + for index, record in enumerate(candidates): + record["metadata"].update(uid="synthetic-" + str(index), resourceVersion="7") + device = next(record for record in candidates if record["kind"] == "Device" and record["spec"]["identity"]["sourceIdentity"]["id"] == "1") + snapshot = copy.deepcopy(snapshot) + snapshot["observedAt"] = "2026-11-22T00:00:00Z" + snapshot["objects"]["dcim/devices"][0]["face"] = {"value": "rear"} + snapshot["objects"]["dcim/device-types"][0].update(u_height=2, is_full_depth=True) + selection = {field: device["metadata"][field] for field in ("name", "namespace", "uid", "resourceVersion")} + selection["sourceID"] = "1" + destination = {field: mapping["target"][field] for field in ("project", "namespace")} + return snapshot, {"target": destination, "items": candidates}, {"target": destination, "devices": [selection]} + + +class PlacementTests(unittest.TestCase): + def test_same_rack_plan_is_blocked_and_preserves_inputs(self): + snapshot, target, allowlist = inputs() + before = copy.deepcopy(target) + result = placement.enrichment_plan(snapshot, target, allowlist) + self.assertEqual(target, before) + self.assertFalse(result["executable"]) + self.assertFalse(result["applied"]) + item = result["devices"][0] + self.assertEqual([test["path"] for test in item["preconditions"]], ["/metadata/uid", "/metadata/resourceVersion"]) + original, proposed = item["before"]["spec"], item["proposedAfter"]["spec"] + for field in set(original) - {"provenance"}: + self.assertEqual(original[field], proposed[field]) + for field in ("method", "recordedBy"): + self.assertEqual(original["provenance"][field], proposed["provenance"][field]) + self.assertEqual(proposed["reportedPlacement"]["face"], "rear") + self.assertEqual(proposed["reportedPlacement"]["height"], 2) + + def test_rejects_conflicts_and_nonallowlisted_changes(self): + for case in ("uid", "resourceVersion", "extra", "rack", "flux", "legacy", "positioned", "duplicate", "source", "unknown", "null", "bounds", "stale", "namespace"): + with self.subTest(case=case): + snapshot, target, allowlist = inputs() + device = next(record for record in target["items"] if record["metadata"]["name"] == allowlist["devices"][0]["name"]) + claim = next(record for record in target["items"] if record["kind"] == "DeviceClaim" and record["metadata"]["name"] == device["spec"]["claimRef"]["name"]) + if case in ("uid", "resourceVersion"): + device["metadata"][case] = "changed" + elif case == "extra": allowlist["devices"][0]["actor"] = "admin" + elif case == "rack": snapshot["objects"]["dcim/devices"][0]["rack"] = {"id": "other"} + elif case == "flux": device["metadata"]["managedFields"] = [{"manager": "kustomize-controller"}] + elif case == "legacy": claim["spec"].pop("lifecycle") + elif case == "positioned": claim["spec"]["placement"]["scope"] = "RackUnits" + elif case == "duplicate": allowlist["devices"].append(allowlist["devices"][0]) + elif case == "source": device["spec"]["provenance"]["source"]["id"] = "other" + elif case == "unknown": device["metadata"].pop("uid") + elif case == "null": snapshot["objects"]["dcim/devices"][0]["position"] = None + elif case == "bounds": snapshot["objects"]["dcim/devices"][0]["position"] = 42 + elif case == "stale": snapshot["observedAt"] = device["spec"]["provenance"]["recordedAt"] + elif case == "namespace": allowlist["devices"][0]["namespace"] = "other" + with self.assertRaises(ValueError): placement.enrichment_plan(snapshot, target, allowlist) + + def test_partial_and_nonunit_geometry_is_not_invented(self): + snapshot, _, _ = inputs() + report = placement.source_report(snapshot, {"position": None, "face": None}, {"u_height": 0}, "rack") + self.assertEqual(set(report), {"revision", "observedAt", "snapshotDigest", "rackRef"}) + report = placement.source_report(snapshot, {"position": "12.5"}, {"u_height": "0.5"}, "rack") + self.assertEqual(report["position"], 12.5) + self.assertEqual(report["height"], 0.5) + for raw in (True, -1, "nan", "inf", "invalid"): + with self.assertRaises(ValueError): placement.source_report(snapshot, {"position": raw}, {}, "rack") + + def test_create_report_requires_explicit_per_device_selection(self): + snapshot, mapping = fixture() + _, old = inventory.Planner(snapshot, mapping).run() + self.assertFalse(any("reportedPlacement" in record["spec"] for record in old)) + mapping["devices"]["1"]["includeReportedPlacement"] = True + _, candidates = inventory.Planner(snapshot, mapping).run() + reports = [record for record in candidates if "reportedPlacement" in record["spec"]] + self.assertEqual(len(reports), 1) + self.assertEqual(reports[0]["spec"]["reportedPlacement"]["snapshotDigest"], reports[0]["spec"]["provenance"]["source"]["snapshotDigest"]) + self.assertEqual(reports[0]["spec"]["reportedPlacement"]["position"], 1) + + +if __name__ == "__main__": + unittest.main() diff --git a/internal/api/inventory/v1alpha1/reported_placement_test.go b/internal/api/inventory/v1alpha1/reported_placement_test.go new file mode 100644 index 00000000..eb0d78c5 --- /dev/null +++ b/internal/api/inventory/v1alpha1/reported_placement_test.go @@ -0,0 +1,106 @@ +package v1alpha1 + +import ( + "strings" + "testing" + "time" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +func reportedDevice() Device { + device := syntheticDevice() + source := ExternalReference{System: "example-netbox", Type: "dcim/devices", ID: "1"} + device.Spec.Identity.SourceIdentity = &source + device.Spec.Provenance.Method = "NetBoxImport" + device.Spec.Provenance.Source = &SourceReference{ExternalReference: source, SnapshotDigest: "sha256:" + strings.Repeat("a", 64), MappingRevision: "example-1", ObservedAt: metav1.NewTime(recordedAt)} + device.Spec.ReportedPlacement = &ReportedPlacement{Revision: 1, ObservedAt: metav1.NewTime(recordedAt), SnapshotDigest: device.Spec.Provenance.Source.SnapshotDigest, RackRef: &LocalReference{Name: "rack-a"}} + return device +} + +func TestReportedPlacementAdmission(t *testing.T) { + for _, device := range []Device{syntheticDevice(), reportedDevice()} { + for _, previous := range []map[string]any{nil, object(t, device)} { + if errs := admit(t, "Device", object(t, device), previous); len(errs) != 0 { + t.Fatal(errs) + } + } + } + for _, height := range []float64{0.5, 1, 4} { + device := reportedDevice() + position := 12.5 + device.Spec.ReportedPlacement.Height = &height + device.Spec.ReportedPlacement.Position = &position + if errs := admit(t, "Device", object(t, device), nil); len(errs) != 0 { + t.Fatal(errs) + } + } + for name, mutate := range map[string]func(*Device){ + "negative": func(device *Device) { value := -1.0; device.Spec.ReportedPlacement.Position = &value }, + "zero height": func(device *Device) { value := 0.0; device.Spec.ReportedPlacement.Height = &value }, + "invalid face": func(device *Device) { device.Spec.ReportedPlacement.Face = "unknown" }, + "geometry without rack": func(device *Device) { + device.Spec.ReportedPlacement.RackRef = nil + device.Spec.ReportedPlacement.Face = "front" + }, + "mount and units": func(device *Device) { + device.Spec.ReportedPlacement.Mount = "side" + device.Spec.ReportedPlacement.Face = "front" + }, + "snapshot": func(device *Device) { + device.Spec.ReportedPlacement.SnapshotDigest = "sha256:" + strings.Repeat("b", 64) + }, + "time": func(device *Device) { device.Spec.ReportedPlacement.ObservedAt = later(time.Hour) }, + "revision": func(device *Device) { device.Spec.ReportedPlacement.Revision = 2 }, + "manual": func(device *Device) { device.Spec.Provenance.Method = "Manual" }, + } { + t.Run(name, func(t *testing.T) { + device := reportedDevice() + mutate(&device) + if errs := admit(t, "Device", object(t, device), nil); len(errs) == 0 { + t.Fatal("accepted invalid report") + } + }) + } +} + +func TestPlacementCorrectionGateCannotBeBypassed(t *testing.T) { + for name, mutate := range map[string]func(*Device){ + "same rack enrichment": func(device *Device) { value := 12.0; device.Spec.ReportedPlacement.Position = &value }, + "rack move": func(device *Device) { device.Spec.ReportedPlacement.RackRef.Name = "rack-b" }, + "removal": func(device *Device) { device.Spec.ReportedPlacement = nil }, + "rebinding": func(device *Device) { device.Spec.ClaimRef.Name = "other" }, + "identity": func(device *Device) { device.Spec.Identity.Serial = "other" }, + "source": func(device *Device) { + device.Spec.Provenance.Source.ID = "other" + device.Spec.Identity.SourceIdentity.ID = "other" + }, + } { + t.Run(name, func(t *testing.T) { + old := reportedDevice() + device := old.DeepCopyObject().(*Device) + mutate(device) + device.Spec.DisplayName = "bundled edit" + device.Spec.Provenance.RecordedAt = later(time.Hour) + device.Spec.Provenance.RecordedBy = "forged-administrator" + device.Labels = map[string]string{"owner": "operator", "audit-approved": "true"} + device.ManagedFields = []metav1.ManagedFieldsEntry{{Manager: "fleet-staff-inventory-ui", Operation: metav1.ManagedFieldsOperationUpdate}} + if errs := admit(t, "Device", object(t, device), object(t, old)); len(errs) == 0 { + t.Fatal("direct update bypassed gate") + } + }) + } + device := reportedDevice() + old := device.DeepCopyObject().(*Device) + old.Spec.ReportedPlacement = nil + device.Spec.Provenance.RecordedAt = later(time.Hour) + if errs := admit(t, "Device", object(t, device), object(t, old)); len(errs) == 0 { + t.Fatal("accepted addition to existing imported device") + } + old = device.DeepCopyObject().(*Device) + device.Spec.DisplayName = "unrelated recordkeeping" + device.Spec.Provenance.RecordedAt = later(2 * time.Hour) + if errs := admit(t, "Device", object(t, device), object(t, old)); len(errs) != 0 { + t.Fatal(errs) + } +} diff --git a/internal/api/inventory/v1alpha1/types.go b/internal/api/inventory/v1alpha1/types.go index eb77dfb1..6568fe79 100644 --- a/internal/api/inventory/v1alpha1/types.go +++ b/internal/api/inventory/v1alpha1/types.go @@ -101,6 +101,7 @@ type Device struct { } type DeviceSpec struct { + ReportedPlacement *ReportedPlacement `json:"reportedPlacement,omitempty"` DisplayName string `json:"displayName,omitempty"` ModelShape *ModelShape `json:"modelShape,omitempty"` AssetTag string `json:"assetTag,omitempty"` @@ -119,6 +120,19 @@ type DeviceSpec struct { UnmappedMACAddresses []string `json:"unmappedMACAddresses,omitempty"` } +type ReportedPlacement struct { + Revision int32 `json:"revision"` + ObservedAt metav1.Time `json:"observedAt"` + SnapshotDigest string `json:"snapshotDigest"` + FacilityRef *LocalReference `json:"facilityRef,omitempty"` + RackRef *LocalReference `json:"rackRef,omitempty"` + Position *float64 `json:"position,omitempty"` + Height *float64 `json:"height,omitempty"` + Face string `json:"face,omitempty"` + FullDepth *bool `json:"fullDepth,omitempty"` + Mount string `json:"mount,omitempty"` +} + type LocalReference struct { Name string `json:"name"` } diff --git a/ui/provider/src/components/inventory-location.test.tsx b/ui/provider/src/components/inventory-location.test.tsx index 790b4c71..9309695e 100644 --- a/ui/provider/src/components/inventory-location.test.tsx +++ b/ui/provider/src/components/inventory-location.test.tsx @@ -7,6 +7,16 @@ import { toInventory } from '../inventory'; import { fixturePhysicalClaims, fixturePhysicalDevices, fixturePhysicalRecords } from '../lib/fixtures'; const rack = fixturePhysicalRecords[1]; +it.each([true, false, undefined])('draws reported Device geometry with explicit depth %s', fullDepth => { + const device = { ...fixturePhysicalDevices[0], spec: { ...fixturePhysicalDevices[0].spec, reportedPlacement: { revision: 1 as const, observedAt: '2026-11-21T00:00:00Z', snapshotDigest: `sha256:${'a'.repeat(64)}`, rackRef: { name: rack.metadata.name }, position: 12, height: 4, face: 'rear' as const, fullDepth } } }; + render(); + const rear = within(screen.getByRole('list', { name: 'rear recorded placements' })).getByRole('link', { name: /Reported placement/ }); + expect(rear).toHaveAttribute('href', expect.stringContaining('kind=Device&')); + expect(rear.parentElement).toHaveStyle({ gridRow: '28 / span 4' }); + const front = within(screen.getByRole('list', { name: 'front recorded placements' })).queryAllByRole('link'); + expect(front).toHaveLength(fullDepth ? 1 : 0); + expect(screen.queryByRole('link', { name: /Review Server installation/ })).not.toBeInTheDocument(); +}); function show(placement = fixturePhysicalClaims[0].spec.placement, issues = {}, height: number | null = 42) { const claim = { ...fixturePhysicalClaims[0], spec: { ...fixturePhysicalClaims[0].spec, placement } }; return render(); @@ -17,19 +27,19 @@ it.each([ { position: 12, height: 4, face: 'front' as const, row: '28 / span 4' }, ])('renders one continuous block for $height units at $position on $face', ({ position, height, face, row }) => { show({ scope: 'RackUnits', rackRef: { name: 'rack-01' }, position, height, face }); - const elevation = screen.getByRole('list', { name: `${face} recorded plans` }); + const elevation = screen.getByRole('list', { name: `${face} recorded placements` }); const links = within(elevation).getAllByRole('link'); expect(links).toHaveLength(1); expect(links[0]).toHaveAccessibleName(new RegExp(`U${position}–U${position + height - 1}.*${height}U`)); expect(links[0].parentElement).toHaveStyle({ gridRow: row, gridColumn: '2' }); expect(within(elevation).getAllByLabelText('Occupancy unverified')).toHaveLength(42 - height); - expect(within(screen.getByRole('list', { name: `${face === 'front' ? 'rear' : 'front'} recorded plans` })).queryByRole('link')).not.toBeInTheDocument(); + expect(within(screen.getByRole('list', { name: `${face === 'front' ? 'rear' : 'front'} recorded placements` })).queryByRole('link')).not.toBeInTheDocument(); }); it.each([1, 2])('keeps overlapping %iU plans identifiable with height-aware labels', height => { const claims = [10, 10 + height - 1].map((position, index) => ({ ...fixturePhysicalClaims[0], metadata: { ...fixturePhysicalClaims[0].metadata, name: `overlap-${index}` }, spec: { ...fixturePhysicalClaims[0].spec, displayName: `Plan ${index}`, placement: { scope: 'RackUnits' as const, rackRef: { name: 'rack-01' }, position, height, face: 'front' as const } } })); render(); - const elevation = screen.getByRole('list', { name: 'front recorded plans' }); - const links = within(elevation).getAllByRole('link', { name: /overlapping plans/ }); + const elevation = screen.getByRole('list', { name: 'front recorded placements' }); + const links = within(elevation).getAllByRole('link', { name: /overlapping placements/ }); expect(links).toHaveLength(2); expect(links[0].parentElement).toHaveStyle({ gridColumn: '2', gridRow: `${34 - height} / span ${height}` }); expect(links[1].parentElement).toHaveStyle({ gridColumn: '3', gridRow: `${35 - 2 * height} / span ${height}` }); @@ -38,16 +48,16 @@ it.each([1, 2])('keeps overlapping %iU plans identifiable with height-aware labe expect(link.querySelectorAll('small')).toHaveLength(height > 1 ? 1 : 0); expect(link.querySelector('.inventory-rack-plan-name')).toHaveTextContent(/Plan/); } - expect(screen.getByText(/! indicates overlapping plans requiring review/)).toBeInTheDocument(); + expect(screen.getByText(/! indicates overlapping placements requiring review/)).toBeInTheDocument(); }); it('renders recorded front/rear plans, never free units or occupancy percentages', () => { show(); - const front = screen.getByRole('list', { name: 'front recorded plans' }); + const front = screen.getByRole('list', { name: 'front recorded placements' }); expect(within(front).getByRole('link', { name: /Review Server installation/ })).toBeInTheDocument(); expect(screen.queryByText(/%|available units|Online/)).not.toBeInTheDocument(); fireEvent.click(screen.getByRole('button', { name: 'Rear' })); - expect(screen.queryByRole('list', { name: 'front recorded plans' })).not.toBeInTheDocument(); - expect(screen.getByRole('list', { name: 'rear recorded plans' })).toBeInTheDocument(); + expect(screen.queryByRole('list', { name: 'front recorded placements' })).not.toBeInTheDocument(); + expect(screen.getByRole('list', { name: 'rear recorded placements' })).toBeInTheDocument(); }); it.each([ { scope: 'RackMembership' as const, rackRef: { name: 'rack-01' } }, @@ -57,25 +67,25 @@ it.each([ { scope: 'RackUnits' as const, rackRef: { name: 'rack-01' }, position: 12, face: 'front' as const }, ])('keeps incomplete or out-of-range geometry out of the elevation: %j', placement => { show(placement); - expect(within(screen.getByRole('list', { name: 'front recorded plans' })).queryByRole('link')).not.toBeInTheDocument(); + expect(within(screen.getByRole('list', { name: 'front recorded placements' })).queryByRole('link')).not.toBeInTheDocument(); const section = screen.getByRole('heading', { name: /Unpositioned equipment/ }).parentElement!; expect(within(section).getByRole('link', { name: 'Example compute server' })).toBeInTheDocument(); }); it('separates non-unit mounts rather than consuming rack units', () => { show({ scope: 'NonRackUnitMount', rackRef: { name: 'rack-01' }, mount: 'left-rail' }); const section = screen.getByRole('heading', { name: /Non-racked mounts/ }).parentElement!; - expect(within(section).getByText('left-rail')).toBeInTheDocument(); - expect(within(screen.getByRole('list', { name: 'front recorded plans' })).queryByRole('link')).not.toBeInTheDocument(); + expect(within(section).getByText(/Mount: left-rail/)).toBeInTheDocument(); + expect(within(screen.getByRole('list', { name: 'front recorded placements' })).queryByRole('link')).not.toBeInTheDocument(); }); it('does not disguise denied installation collections as empty geometry', () => { show(undefined, { DeviceClaim: { status: 403 } }); expect(screen.getByText(/This is not an empty rack/)).toBeInTheDocument(); - expect(screen.queryByRole('list', { name: 'front recorded plans' })).not.toBeInTheDocument(); + expect(screen.queryByRole('list', { name: 'front recorded placements' })).not.toBeInTheDocument(); expect(screen.queryByText('Example compute server')).not.toBeInTheDocument(); }); it('does not invent rack units when the rack height is unknown', () => { show(undefined, {}, null); - expect(screen.queryByRole('list', { name: 'front recorded plans' })).not.toBeInTheDocument(); + expect(screen.queryByRole('list', { name: 'front recorded placements' })).not.toBeInTheDocument(); }); it('filters by recorded model and facility without manufacturing a hardware type', () => { render(); diff --git a/ui/provider/src/components/inventory-location.tsx b/ui/provider/src/components/inventory-location.tsx index df20fae1..b068a3f4 100644 --- a/ui/provider/src/components/inventory-location.tsx +++ b/ui/provider/src/components/inventory-location.tsx @@ -2,6 +2,7 @@ import { useState } from 'react'; import { Link } from 'react-router'; import { slotKey, type Inventory, type InventorySlot } from '../inventory'; import type { PhysicalRecord } from '../../../shared/fleet-api'; +import { equipmentGeometry, equipmentPlacements, reportedPlacementLabel, type EquipmentPlacement } from '../lib/device-placement'; export function inventoryHref(kind: string, namespace?: string, name?: string) { const params = new URLSearchParams({ kind }); @@ -10,22 +11,19 @@ export function inventoryHref(kind: string, namespace?: string, name?: string) { } export function rackGeometry(slot: InventorySlot, rack: PhysicalRecord) { - const placement = slot.claim.spec.placement; - const { position, height, face } = placement; - if (placement.scope !== 'RackUnits' || !Number.isInteger(position) || !Number.isInteger(height) || !position || !height || position < 1 || height < 1 || !rack.spec.heightUnits || position + height - 1 > rack.spec.heightUnits || (face !== 'front' && face !== 'rear')) return undefined; - return { position, height, face }; + return equipmentGeometry({ ...slot, kind: 'DeviceClaim', record: slot.claim, placement: slot.claim.spec.placement, basis: 'Claim-derived fallback' }, rack); } -function Equipment({ slots, devicesDenied }: { slots: InventorySlot[]; devicesDenied: boolean }) { - return
    - {slots.map(slot => )} +function Equipment({ slots, devicesDenied, inventory }: { slots: EquipmentPlacement[]; devicesDenied: boolean; inventory: Inventory }) { + return
    EquipmentInstallation planRecorded placement
    {devicesDenied ? 'Device details unavailable' : slot.devices.length ? slot.devices.map(device =>
    {device.spec.displayName || device.metadata.name}
    ) : 'No device registration recorded'}{slot.devices.length > 1 && Multiple registrations · active device unknown}
    {slot.claim.spec.displayName || slot.claim.metadata.name}{slot.claim.spec.placement.scope === 'NonRackUnitMount' ? slot.claim.spec.placement.mount || 'Mount not recorded' : slot.claim.spec.placement.scope === 'RackUnits' ? `U${slot.claim.spec.placement.position ?? '?'} · ${slot.claim.spec.placement.height ?? '?'}U · ${slot.claim.spec.placement.face ?? 'Face unknown'}` : 'Position not recorded'}
    + {slots.map(slot => )}
    EquipmentClaim / registration historyLocation / Reported placement
    {devicesDenied ? 'Device details unavailable' : slot.devices.length ? slot.devices.map(device =>
    {device.spec.displayName || device.metadata.name}
    ) : 'No device registration recorded'}{slot.devices.length > 1 && Multiple registrations · active device unknown}
    {slot.claim ? {slot.claim.spec.displayName || slot.claim.metadata.name} : 'Claim details unavailable'}{reportedPlacementLabel(slot, inventory)}
    ; } -function RackFace({ rack, slots, side }: { rack: PhysicalRecord; slots: InventorySlot[]; side: 'front' | 'rear' }) { +function RackFace({ rack, slots, side }: { rack: PhysicalRecord; slots: EquipmentPlacement[]; side: 'front' | 'rear' }) { const height = rack.spec.heightUnits!; - const plans = slots.map(slot => ({ slot, ...rackGeometry(slot, rack)! })) - .filter(plan => plan.face === side) + const plans = slots.map(slot => ({ slot, ...equipmentGeometry(slot, rack)! })) + .filter(plan => plan.face === side || plan.fullDepth === true) .sort((first, second) => first.position - second.position || first.slot.key.localeCompare(second.slot.key)); const laneEnds: number[] = []; const placed = plans.map(plan => { @@ -35,7 +33,7 @@ function RackFace({ rack, slots, side }: { rack: PhysicalRecord; slots: Inventor return { ...plan, lane }; }); return

    {side === 'front' ? 'Front' : 'Rear'}

    -
      +
        {Array.from({ length: height }, (_, index) => height - index).map(unit => { const recorded = plans.some(plan => unit >= plan.position && unit < plan.position + plan.height); return
      1. U{unit}{!recorded && —}
      2. ; @@ -43,11 +41,11 @@ function RackFace({ rack, slots, side }: { rack: PhysicalRecord; slots: Inventor {placed.map(plan => { const top = plan.position + plan.height - 1; const overlap = plans.some(other => other.slot.key !== plan.slot.key && other.position <= top && other.position + other.height > plan.position); - const name = plan.slot.claim.spec.displayName || plan.slot.claim.metadata.name; + const name = plan.slot.record.spec.displayName || plan.slot.record.metadata.name; const range = plan.height === 1 ? `U${plan.position}` : `U${plan.position}–U${top}`; - const label = `${name} · ${range} · ${plan.height}U${overlap ? ' · overlapping plans, review required' : ''}`; + const label = `${name} · ${range} · ${plan.height}U · ${plan.slot.basis}${overlap ? ' · overlapping placements, review required' : ''}`; return
      3. - {overlap && }{name}{plan.height > 1 && {range} · {plan.height}U} + {overlap && }{name}{plan.height > 1 && {range} · {plan.height}U}
      4. ; })}
      @@ -56,26 +54,27 @@ function RackFace({ rack, slots, side }: { rack: PhysicalRecord; slots: Inventor export function RackOverview({ rack, inventory }: { rack: PhysicalRecord; inventory: Inventory }) { const [face, setFace] = useState<'both' | 'front' | 'rear'>('both'); - const slots = inventory.slots.filter(slot => slot.claim.metadata.namespace === rack.metadata.namespace && slot.claim.spec.placement.rackRef?.name === rack.metadata.name); - const positioned = slots.filter(slot => rackGeometry(slot, rack)); - const nonRacked = slots.filter(slot => slot.claim.spec.placement.scope === 'NonRackUnitMount'); - const unpositioned = slots.filter(slot => !rackGeometry(slot, rack) && slot.claim.spec.placement.scope !== 'NonRackUnitMount'); - const denied = !!inventory.issues?.DeviceClaim; + const slots = equipmentPlacements(inventory).filter(slot => slot.record.metadata.namespace === rack.metadata.namespace && slot.placement.rackRef?.name === rack.metadata.name); + const positioned = slots.filter(slot => equipmentGeometry(slot, rack)); + const nonRacked = slots.filter(slot => slot.placement.scope === 'NonRackUnitMount'); + const unpositioned = slots.filter(slot => !equipmentGeometry(slot, rack) && slot.placement.scope !== 'NonRackUnitMount'); + const denied = !!inventory.issues?.DeviceClaim && !slots.length; const devicesDenied = !!inventory.issues?.Device; const height = rack.spec.heightUnits; return
      -

      Equipment & installation plans

      +

      Equipment & registration history

      + {(inventory.issues?.Device || inventory.issues?.DeviceClaim) &&

      Some records are unavailable; equipment counts are incomplete.

      } {denied ?

      Installation details unavailable. This is not an empty rack.

      : <> -

      Positioned plans {positioned.length}

      {positioned.length ? :

      No complete in-range unit positions recorded.

      }
      -

      Unpositioned equipment {unpositioned.length}

      {unpositioned.length ? :

      No unpositioned plans recorded for this rack.

      }
      -

      Non-racked mounts {nonRacked.length}

      {nonRacked.length ? :

      No side, rail, or other non-unit mounts recorded.

      }
      +

      Positioned equipment {positioned.length}

      {positioned.length ? :

      No complete in-range unit positions recorded.

      }
      +

      Unpositioned equipment {unpositioned.length}

      {unpositioned.length ? :

      No unpositioned reports or claims recorded for this rack.

      }
      +

      Non-racked mounts {nonRacked.length}

      {nonRacked.length ? :

      No side, rail, or other non-unit mounts recorded.

      }
      {!slots.length &&

      No related records found. This does not establish that equipment is absent.

      } }
      @@ -84,8 +83,9 @@ export function RackOverview({ rack, inventory }: { rack: PhysicalRecord; invent export function FacilityOverview({ facility, inventory }: { facility: PhysicalRecord; inventory: Inventory }) { const racks = inventory.physical.filter(record => record.kind === 'Rack' && record.metadata.namespace === facility.metadata.namespace && record.spec.facilityRef?.name === facility.metadata.name); - const facilityOnly = inventory.slots.filter(slot => slot.claim.metadata.namespace === facility.metadata.namespace && slot.claim.spec.placement.scope === 'Facility' && slot.claim.spec.placement.facilityRef?.name === facility.metadata.name); - return

      Racks

      {inventory.issues?.Rack ?

      Rack details unavailable. The facility's rack count is unknown.

      : racks.length ?
      {racks.map(rack => )}
      RackRecorded heightInstallation plansAvailable space
      {rack.spec.displayName || rack.metadata.name}{rack.spec.heightUnits ? `${rack.spec.heightUnits}U` : 'Not recorded'}{inventory.issues?.DeviceClaim ? 'Unavailable' : inventory.slots.filter(slot => slot.claim.metadata.namespace === rack.metadata.namespace && slot.claim.spec.placement.rackRef?.name === rack.metadata.name).length}Not verified
      :

      No racks recorded in this facility.

      } -

      Equipment without a recorded rack

      {inventory.issues?.DeviceClaim ?

      Installation details unavailable.

      : facilityOnly.length ? :

      No facility-only installation plans recorded.

      } + const equipment = equipmentPlacements(inventory); + const facilityOnly = equipment.filter(slot => slot.record.metadata.namespace === facility.metadata.namespace && !slot.placement.rackRef && slot.placement.facilityRef?.name === facility.metadata.name); + return

      Racks

      {inventory.issues?.Rack ?

      Rack details unavailable. The facility's rack count is unknown.

      : racks.length ?
      {racks.map(rack => )}
      RackRecorded heightEquipment reports / claim fallbackAvailable space
      {rack.spec.displayName || rack.metadata.name}{rack.spec.heightUnits ? `${rack.spec.heightUnits}U` : 'Not recorded'}{inventory.issues?.DeviceClaim || inventory.issues?.Device ? 'Incomplete' : equipment.filter(slot => slot.record.metadata.namespace === rack.metadata.namespace && slot.placement.rackRef?.name === rack.metadata.name).length}Not verified
      :

      No racks recorded in this facility.

      } +

      Equipment without a recorded rack

      {facilityOnly.length ? : inventory.issues?.DeviceClaim || inventory.issues?.Device ?

      Equipment details unavailable.

      :

      No facility-only reports or claims recorded.

      }
      ; } diff --git a/ui/provider/src/components/physical-inventory.test.tsx b/ui/provider/src/components/physical-inventory.test.tsx index 42f77131..2656832a 100644 --- a/ui/provider/src/components/physical-inventory.test.tsx +++ b/ui/provider/src/components/physical-inventory.test.tsx @@ -51,7 +51,7 @@ describe('hardware directory', () => { it('offers six navigable kinds without writes or a report upload', () => { const { container } = browse(); const navigation = within(screen.getByRole('navigation', { name: 'Inventory categories' })); - for (const name of ['Devices', 'Facilities', 'Racks', 'Installation plans', 'Cables', 'Power feeds']) expect(navigation.getByRole('link', { name: new RegExp(name) })).toBeInTheDocument(); + for (const name of ['Devices', 'Facilities', 'Racks', 'Claims & registrations', 'Cables', 'Power feeds']) expect(navigation.getByRole('link', { name: new RegExp(name) })).toBeInTheDocument(); expect(screen.queryByRole('button', { name: /create|edit|delete|apply|sync|import/i })).not.toBeInTheDocument(); expect(container.querySelector('input[type="file"]')).toBeNull(); expect(screen.queryByText(/GitOps|Flux/)).not.toBeInTheDocument(); diff --git a/ui/provider/src/components/physical-inventory.tsx b/ui/provider/src/components/physical-inventory.tsx index 31d847d6..a0a6a10a 100644 --- a/ui/provider/src/components/physical-inventory.tsx +++ b/ui/provider/src/components/physical-inventory.tsx @@ -17,6 +17,7 @@ import { InventoryManagement } from './inventory-management'; import type { ManagedKind, ManagedRecord } from '../lib/inventory-management'; import { InventoryReadAccessContext, readFailureIssues, redactInventory } from '../lib/inventory-read-access'; import { FacilityOverview, RackOverview, inventoryHref as href } from './inventory-location'; +import { devicePlacement, placementFacility, reportedPlacementLabel } from '../lib/device-placement'; type Kind = 'Device' | 'Facility' | 'Rack' | 'DeviceClaim' | 'Cable' | 'PowerFeed'; type RecordEntry = { kind: Kind; record: RawDevice | RawDeviceClaim | PhysicalRecord }; @@ -37,13 +38,13 @@ const sections = [ kind: 'Rack', title: 'Racks', icon: Server, - description: 'Rack definitions and planned equipment placement.', + description: 'Rack definitions and reported equipment placement.', }, { kind: 'DeviceClaim', - title: 'Installation plans', + title: 'Claims & registrations', icon: ClipboardList, - description: 'Installation plans, kept separate from physical hardware.', + description: 'Registration and intent history, kept separate from physical hardware. Installation lifecycle alone does not distinguish prospective from existing equipment.', }, { kind: 'Cable', @@ -194,10 +195,11 @@ export function PhysicalInventory({ inventory: source, onRetry }: { inventory: I const placement = (entry: RecordEntry): string => { if (entry.kind === 'DeviceClaim') return plannedPlacement(entry.record as RawDeviceClaim); if (entry.kind === 'Device') { + const projected = devicePlacement(entry.record as RawDevice, inventory); + if (projected?.basis === 'Reported placement') return reportedPlacementLabel(projected, inventory); if (inventory.issues?.DeviceClaim) return 'Claim details unavailable'; - const slot = claimFor(entry.record as RawDevice); - return slot - ? `${plannedPlacement(slot.claim)}${slot.devices.length > 1 ? ' · multiple registrations' : ''}` + return projected?.claim + ? `Claim-derived fallback · ${plannedPlacement(projected.claim)}${projected.multipleRegistrations ? ' · multiple registrations · active device unknown' : ''}` : 'Claim record not found'; } const record = entry.record as PhysicalRecord; @@ -222,8 +224,13 @@ export function PhysicalInventory({ inventory: source, onRetry }: { inventory: I }; const records = entries.filter((entry) => entry.kind === section.kind); const locationKey = (entry: RecordEntry) => { - if (inventory.issues?.Facility || (entry.kind === 'Device' && inventory.issues?.DeviceClaim)) return ''; - const claim = entry.kind === 'Device' ? claimFor(entry.record as RawDevice)?.claim : entry.kind === 'DeviceClaim' ? entry.record as RawDeviceClaim : undefined; + if (entry.kind === 'Device') { + const projected = devicePlacement(entry.record as RawDevice, inventory); + const facility = projected && placementFacility(projected.placement, entry.record.metadata.namespace, inventory); + return facility ? slotKey(entry.record.metadata.namespace, facility) : ''; + } + if (inventory.issues?.Facility) return ''; + const claim = entry.kind === 'DeviceClaim' ? entry.record as RawDeviceClaim : undefined; const rackName = claim?.spec.placement.rackRef?.name ?? (entry.record as PhysicalRecord).spec.rackRef?.name; const rack = rackName && !inventory.issues?.Rack ? find('Rack', entry.record.metadata.namespace, rackName)?.record as PhysicalRecord | undefined : undefined; const facilityName = claim?.spec.placement.facilityRef?.name ?? (entry.record as PhysicalRecord).spec.facilityRef?.name ?? rack?.spec.facilityRef?.name; @@ -314,7 +321,7 @@ export function PhysicalInventory({ inventory: source, onRetry }: { inventory: I [lane.a, lane.b].some((endpoint) => { if ((kind === 'Rack' || kind === 'Facility') && endpoint.deviceRef) { const targetDevice = find('Device', namespace, endpoint.deviceRef.name)?.record as RawDevice | undefined; - const location = targetDevice && claimFor(targetDevice)?.claim.spec.placement; + const location = targetDevice && devicePlacement(targetDevice, inventory)?.placement; const rack = location?.rackRef && find('Rack', namespace, location.rackRef.name)?.record as PhysicalRecord | undefined; return kind === 'Rack' ? location?.rackRef?.name === record.metadata.name : location?.facilityRef?.name === record.metadata.name || rack?.spec.facilityRef?.name === record.metadata.name; } @@ -341,10 +348,14 @@ export function PhysicalInventory({ inventory: source, onRetry }: { inventory: I {device.spec.identity.serial} {device.spec.assetTag} {device.spec.identity.systemUUID} - + {reference('DeviceClaim', namespace, device.spec.claimRef.name)} - {placement(entry)} + {placement(entry)} + {device.spec.reportedPlacement?.rackRef && {reference('Rack', namespace, device.spec.reportedPlacement.rackRef.name)}} + {device.spec.reportedPlacement?.facilityRef && {reference('Facility', namespace, device.spec.reportedPlacement.facilityRef.name)}} + {device.spec.reportedPlacement && Revision {device.spec.reportedPlacement.revision} · {device.spec.reportedPlacement.observedAt} · source-reported, not physically verified} + Disabled pending authenticated durable audit. Recordkeeping is not a physical move or a capacity reservation. {device.spec.modelShape ? `${device.spec.modelShape.heightUnits ?? 'Unknown'}U · ${device.spec.modelShape.fullDepth === undefined ? 'Depth not recorded' : device.spec.modelShape.fullDepth ? 'Full depth' : 'Partial depth'}` @@ -365,7 +376,7 @@ export function PhysicalInventory({ inventory: source, onRetry }: { inventory: I <> {modelLabel(claim.spec.expectedIdentity)} {claim.spec.expectedIdentity.serial} - {plannedPlacement(claim)} + {plannedPlacement(claim)} {inventory.issues?.Device ? 'Device details unavailable' : slot?.devices.length ?? 0} {claim.spec.placement.facilityRef && ( @@ -674,7 +685,7 @@ export function PhysicalInventory({ inventory: source, onRetry }: { inventory: I {section.kind === 'Cable' ? 'End A' : section.kind === 'Device' || section.kind === 'DeviceClaim' - ? 'Planned location' + ? 'Location / Reported placement' : 'Location / reference'} {section.kind === 'Cable' ? 'End B' : section.kind === 'Device' ? 'Serial / asset tag' : 'Namespace'} @@ -741,7 +752,7 @@ export function PhysicalInventory({ inventory: source, onRetry }: { inventory: I
      About this inventory

      - These are recorded facts and installation plans, not live hardware status. A record does not + These are source reports and registration / intent history, not live hardware status. A record does not establish availability, verified placement, working connections, or permission to operate equipment.

      diff --git a/ui/provider/src/lib/device-placement.test.ts b/ui/provider/src/lib/device-placement.test.ts new file mode 100644 index 00000000..eaa8f0e4 --- /dev/null +++ b/ui/provider/src/lib/device-placement.test.ts @@ -0,0 +1,61 @@ +import { describe, expect, it } from 'vitest'; +import { toInventory } from '../inventory'; +import { fixturePhysicalClaims, fixturePhysicalDevices, fixturePhysicalRecords } from './fixtures'; +import { devicePlacement, equipmentGeometry, equipmentPlacements, placementFacility, reportedPlacementLabel } from './device-placement'; +import type { ReportedPlacement } from '../../../shared/fleet-api'; + +const report: ReportedPlacement = { revision: 1, observedAt: '2026-11-21T00:00:00Z', snapshotDigest: `sha256:${'a'.repeat(64)}`, rackRef: { name: 'rack-01' }, position: 12, height: 4, face: 'rear', fullDepth: true }; +const device = { ...fixturePhysicalDevices[0], spec: { ...fixturePhysicalDevices[0].spec, reportedPlacement: report } }; +const inventory = toInventory(fixturePhysicalClaims, [device], fixturePhysicalRecords); + +describe('Device observational placement projection', () => { + it('prefers the report without changing the claim or inventory inputs', () => { + const before = JSON.stringify(inventory); + const entry = devicePlacement(device, inventory)!; + expect(entry.basis).toBe('Reported placement'); + expect(entry.placement.position).toBe(12); + expect(entry.placement.face).toBe('rear'); + expect(JSON.stringify(inventory)).toBe(before); + expect(equipmentPlacements(inventory).filter(item => item.claim?.metadata.name === device.spec.claimRef.name)).toHaveLength(1); + }); + it('never borrows geometry from a claim to complete a partial report', () => { + const partial = { ...device, spec: { ...device.spec, reportedPlacement: { ...report, position: undefined, height: undefined, face: undefined } } }; + const entry = devicePlacement(partial, inventory)!; + expect(entry.placement.position).toBeUndefined(); + expect(equipmentGeometry(entry, fixturePhysicalRecords[1])).toBeUndefined(); + expect(reportedPlacementLabel(entry, inventory)).toContain('Position not recorded'); + }); + it.each([401, 403, 404, 500])('preserves reports when claims cannot be read (%i)', status => { + const denied = { ...inventory, issues: { DeviceClaim: { status } } }; + expect(devicePlacement(device, denied)?.claim).toBeUndefined(); + expect(devicePlacement(device, denied)?.basis).toBe('Reported placement'); + expect(devicePlacement(fixturePhysicalDevices[0], denied)).toBeUndefined(); + }); + it('masks denied location names and hides denied devices', () => { + const denied = { ...inventory, issues: { Rack: { status: 403 }, Facility: { status: 403 } } }; + const label = reportedPlacementLabel(devicePlacement(device, denied)!, denied); + expect(label).toContain('Rack unavailable'); + expect(label).not.toContain('rack-01'); + expect(placementFacility(report, device.metadata.namespace, denied)).toBeUndefined(); + expect(devicePlacement(device, { ...inventory, issues: { Device: { status: 403 } } })).toBeUndefined(); + }); + it('retains orphan reports and does not infer a missing claim', () => { + const orphan = toInventory([], [device], fixturePhysicalRecords); + expect(equipmentPlacements(orphan)[0].kind).toBe('Device'); + expect(equipmentPlacements(orphan)[0].claim).toBeUndefined(); + }); + it('keeps multiple registrations separate without choosing the newest active device', () => { + const older = { ...fixturePhysicalDevices[0], metadata: { ...device.metadata, name: 'older' } }; + const mixed = toInventory(fixturePhysicalClaims, [older, device], fixturePhysicalRecords); + const entries = equipmentPlacements(mixed).filter(entry => entry.claim?.metadata.name === device.spec.claimRef.name); + expect(entries).toHaveLength(2); + expect(entries.find(entry => entry.kind === 'DeviceClaim')?.devices.map(item => item.metadata.name)).toEqual(['older']); + expect(entries.every(entry => reportedPlacementLabel(entry, mixed).includes('active device unknown'))).toBe(true); + }); + it.each([ + { position: 41, height: 4 }, { position: 12.5 }, { height: 0.5 }, { position: undefined }, { height: undefined }, { face: undefined }, { position: 0 }, { height: 0 }, + ])('does not draw unknown, non-integral or out-of-range geometry: %j', fields => { + const entry = devicePlacement({ ...device, spec: { ...device.spec, reportedPlacement: { ...report, ...fields } } }, inventory)!; + expect(equipmentGeometry(entry, fixturePhysicalRecords[1])).toBeUndefined(); + }); +}); diff --git a/ui/provider/src/lib/device-placement.ts b/ui/provider/src/lib/device-placement.ts new file mode 100644 index 00000000..b5e83c4f --- /dev/null +++ b/ui/provider/src/lib/device-placement.ts @@ -0,0 +1,59 @@ +import type { Device, DeviceClaim, PhysicalRecord, ReportedPlacement } from '../../../shared/fleet-api'; +import { slotKey, type Inventory } from '../inventory'; + +export type Placement = DeviceClaim['spec']['placement'] & { fullDepth?: boolean }; +export interface EquipmentPlacement { + key: string; + kind: 'Device' | 'DeviceClaim'; + record: Device | DeviceClaim; + placement: Placement; + basis: 'Reported placement' | 'Claim-derived fallback'; + devices: Device[]; + claim?: DeviceClaim; + multipleRegistrations?: boolean; +} + +function reportedPlacement(report: ReportedPlacement): Placement { + return { ...report, scope: report.mount ? 'NonRackUnitMount' : report.rackRef ? 'RackUnits' : 'Facility' }; +} + +export function devicePlacement(device: Device, inventory: Inventory): EquipmentPlacement | undefined { + if (inventory.issues?.Device) return undefined; + const slot = !inventory.issues?.DeviceClaim ? inventory.slots.find(candidate => candidate.key === slotKey(device.metadata.namespace, device.spec.claimRef.name)) : undefined; + if (device.spec.reportedPlacement) return { key: `Device/${slotKey(device.metadata.namespace, device.metadata.name)}`, kind: 'Device', record: device, placement: reportedPlacement(device.spec.reportedPlacement), basis: 'Reported placement', devices: [device], claim: slot?.claim, multipleRegistrations: !!slot && slot.devices.length > 1 }; + if (!slot) return undefined; + return { key: `DeviceClaim/${slot.key}`, kind: 'DeviceClaim', record: slot.claim, placement: slot.claim.spec.placement, basis: 'Claim-derived fallback', devices: slot.devices.filter(candidate => !candidate.spec.reportedPlacement), claim: slot.claim, multipleRegistrations: slot.devices.length > 1 }; +} + +export function equipmentPlacements(inventory: Inventory): EquipmentPlacement[] { + const entries = new Map(); + if (!inventory.issues?.Device) for (const device of [...inventory.slots.flatMap(slot => slot.devices), ...inventory.unboundDevices]) { + const entry = devicePlacement(device, inventory); + if (entry) entries.set(entry.key, entry); + } + if (!inventory.issues?.DeviceClaim) for (const slot of inventory.slots) { + if (slot.devices.length && !inventory.issues?.Device) continue; + entries.set(`DeviceClaim/${slot.key}`, { key: `DeviceClaim/${slot.key}`, kind: 'DeviceClaim', record: slot.claim, placement: slot.claim.spec.placement, basis: 'Claim-derived fallback', devices: [], claim: slot.claim }); + } + return [...entries.values()]; +} + +export function placementFacility(placement: Placement, namespace: string | undefined, inventory: Inventory): string | undefined { + if (inventory.issues?.Facility) return undefined; + if (placement.facilityRef) return placement.facilityRef.name; + if (inventory.issues?.Rack) return undefined; + return inventory.physical.find(record => record.kind === 'Rack' && record.metadata.namespace === namespace && record.metadata.name === placement.rackRef?.name)?.spec.facilityRef?.name; +} + +export function reportedPlacementLabel(entry: EquipmentPlacement, inventory: Inventory): string { + const { placement, record } = entry; + const facilityName = placementFacility(placement, record.metadata.namespace, inventory); + const display = (kind: 'Facility' | 'Rack', name?: string) => inventory.issues?.[kind] ? `${kind} unavailable` : inventory.physical.find(item => item.kind === kind && item.metadata.namespace === record.metadata.namespace && item.metadata.name === name)?.spec.displayName || name; + return [entry.basis, display('Facility', facilityName), display('Rack', placement.rackRef?.name), placement.mount ? `Mount: ${placement.mount}` : placement.position === undefined ? 'Position not recorded' : `U${placement.position}`, placement.height === undefined ? 'Height unknown' : `${placement.height}U`, placement.face ?? 'Face unknown', placement.fullDepth === true ? 'Full depth' : placement.fullDepth === false ? 'Partial depth' : 'Depth unknown', entry.multipleRegistrations ? 'multiple registrations · active device unknown' : undefined].filter(Boolean).join(' · '); +} + +export function equipmentGeometry(entry: EquipmentPlacement, rack: PhysicalRecord) { + const { position, height, face, fullDepth } = entry.placement; + if (entry.placement.scope !== 'RackUnits' || !Number.isInteger(position) || !Number.isInteger(height) || !position || !height || position < 1 || height < 1 || !rack.spec.heightUnits || position + height - 1 > rack.spec.heightUnits || (face !== 'front' && face !== 'rear')) return undefined; + return { position, height, face, fullDepth }; +} diff --git a/ui/provider/src/pages/device-claim-detail.tsx b/ui/provider/src/pages/device-claim-detail.tsx index 0a41e0a4..efbe5fe4 100644 --- a/ui/provider/src/pages/device-claim-detail.tsx +++ b/ui/provider/src/pages/device-claim-detail.tsx @@ -4,7 +4,8 @@ import { InventoryAccessState } from '../components/inventory-access-state'; import { InventorySessionBoundary } from '../components/inventory-session-boundary'; import { StatusBadge } from '../components/status-badge'; import { useInventory } from '../lib/api'; -import { currentDevice, endpointLabel, legacyPeerLabel, modelLabel, placementLabel, slotKey, type RawDevice } from '../inventory'; +import { currentDevice, endpointLabel, legacyPeerLabel, modelLabel, placementLabel, slotKey, type Inventory, type RawDevice } from '../inventory'; +import { devicePlacement, reportedPlacementLabel } from '../lib/device-placement'; import type { Provenance } from '../../../shared/fleet-api'; import { Card, CardContent } from '@datum-cloud/datum-ui/card'; import { Text } from '@datum-cloud/datum-ui/typography'; @@ -47,14 +48,16 @@ function ProvenanceFields({ provenance }: { provenance: Provenance }) { ); } -function DeviceSection({ device, current }: { device: RawDevice; current: boolean }) { +function DeviceSection({ device, current, inventory }: { device: RawDevice; current: boolean; inventory: Inventory }) { const { identity, bmc, interfaces = [], unmappedMACAddresses = [] } = device.spec; + const placement = devicePlacement(device, inventory); return (

      {!current && Historical binding; active placement Unknown}
      {modelLabel(identity)} {device.spec.displayName ?? device.metadata.name} + {placement ? reportedPlacementLabel(placement, inventory) : 'Unknown'} · not physically verified {device.spec.modelShape?.heightUnits ?? 'Unknown'} U {identity.serial ?? '—'} {identity.systemUUID ?? '—'} @@ -121,7 +124,7 @@ function ClaimDetailContent() { <>
      - {placementLabel(slot.claim, data?.issues)} + {placementLabel(slot.claim, data?.issues)} {modelLabel(slot.claim.spec.expectedIdentity)} {slot.claim.spec.expectedIdentity.serial ?? '—'} {slot.claim.metadata.namespace ?? '—'} @@ -145,7 +148,7 @@ function ClaimDetailContent() {
      {data?.issues?.Device && } {(!data?.issues?.Device ? [...slot.devices].reverse() : []).map((device) => ( - + ))}
      {data?.issues?.Cable ? : !data?.issues?.Device && data?.physical.filter((record) => record.kind === 'Cable' && record.metadata.namespace === slot.claim.metadata.namespace && record.spec.lanes?.some((lane) => slot.devices.some((device) => lane.a.deviceRef?.name === device.metadata.name || lane.b.deviceRef?.name === device.metadata.name))).map((cable) =>
      {cable.spec.displayName} · verification Unknown{cable.spec.lanes?.map((lane) => {endpointLabel(lane.a, data?.issues)} ↔ {endpointLabel(lane.b, data?.issues)})}
      )} diff --git a/ui/shared/fleet-api.ts b/ui/shared/fleet-api.ts index 30d93cd4..25b827ca 100644 --- a/ui/shared/fleet-api.ts +++ b/ui/shared/fleet-api.ts @@ -270,6 +270,7 @@ export interface Device { kind?: string; metadata: ObjectMeta; spec: { + reportedPlacement?: ReportedPlacement; claimRef: LocalReference; provenance: Provenance; identity: { manufacturer?: string; model: string; serial?: string; systemUUID?: string; sourceIdentity?: ExternalReference }; @@ -287,6 +288,19 @@ export interface Device { }; } +export interface ReportedPlacement { + revision: 1; + observedAt: string; + snapshotDigest: string; + facilityRef?: LocalReference; + rackRef?: LocalReference; + position?: number; + height?: number; + face?: 'front' | 'rear'; + fullDepth?: boolean; + mount?: string; +} + export interface ExternalReference { system: string; type: string; id: string } export interface ComponentPosition { componentID: string; position: number } export interface PhysicalComponent { From c421fbafbfb516216ab1ddc0acb564465f0c1eb0 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sat, 21 Nov 2026 12:54:56 -0600 Subject: [PATCH 031/518] feat(inventory): allow revisioned Device location corrections --- .../inventory/crds/fleet.datumapis.com.yaml | 29 +++- .../v1alpha1/reported_placement_test.go | 163 +++++++++++++++++- internal/api/inventory/v1alpha1/types.go | 5 +- ui/shared/fleet-api.ts | 7 +- 4 files changed, 187 insertions(+), 17 deletions(-) diff --git a/config/components/inventory/crds/fleet.datumapis.com.yaml b/config/components/inventory/crds/fleet.datumapis.com.yaml index 6a417007..a165f551 100644 --- a/config/components/inventory/crds/fleet.datumapis.com.yaml +++ b/config/components/inventory/crds/fleet.datumapis.com.yaml @@ -315,9 +315,12 @@ spec: message: claimRef is immutable; bind replacement hardware as a new Device - rule: self.identity == oldSelf.identity message: identity is immutable; a hardware swap is a new Device - - rule: has(self.reportedPlacement) == has(oldSelf.reportedPlacement) && (!has(self.reportedPlacement) || self.reportedPlacement == oldSelf.reportedPlacement) - message: placement corrections are disabled pending authenticated durable audit; additions and removals are corrections too - - rule: '!has(self.reportedPlacement) || (has(self.identity.sourceIdentity) && has(self.provenance.source) && self.provenance.method == "NetBoxImport" && self.reportedPlacement.observedAt == self.provenance.source.observedAt && self.reportedPlacement.snapshotDigest == self.provenance.source.snapshotDigest)' + - rule: '!has(oldSelf.reportedPlacement) || has(self.reportedPlacement)' + message: retain a report; omit unknown location fields rather than removing the report + - rule: '!has(self.reportedPlacement) || (oldSelf.hasValue() && has(oldSelf.value().reportedPlacement) ? (self.reportedPlacement == oldSelf.value().reportedPlacement || self.reportedPlacement.revision == oldSelf.value().reportedPlacement.revision + 1) : self.reportedPlacement.revision == 1)' + optionalOldSelf: true + message: first report revision must be 1; every changed report must increment revision exactly once + - rule: '!has(self.reportedPlacement) || (has(self.reportedPlacement.method) && self.reportedPlacement.method == "Manual") || (has(self.identity.sourceIdentity) && has(self.provenance.source) && self.provenance.method == "NetBoxImport" && has(self.reportedPlacement.snapshotDigest) && self.reportedPlacement.observedAt == self.provenance.source.observedAt && self.reportedPlacement.snapshotDigest == self.provenance.source.snapshotDigest)' message: reported placement must retain the imported source snapshot and observation time - rule: '!has(self.reportedPlacement) || self.reportedPlacement.observedAt <= self.provenance.recordedAt' message: the source observation cannot postdate its recording @@ -358,8 +361,10 @@ spec: properties: reportedPlacement: type: object - required: [revision, observedAt, snapshotDigest] + required: [revision, observedAt] x-kubernetes-validations: + - rule: 'has(self.method) && self.method == "Manual" ? (has(self.reason) && has(self.reference) && !has(self.snapshotDigest)) : has(self.snapshotDigest)' + message: manual reports require reason and evidence reference, not an imported snapshot digest - rule: '(!has(self.position) && !has(self.height) && !has(self.face) && !has(self.fullDepth) && !has(self.mount)) || has(self.rackRef)' message: rack geometry requires a reported rack - rule: '!has(self.mount) || (!has(self.position) && !has(self.height) && !has(self.face) && !has(self.fullDepth))' @@ -369,7 +374,21 @@ spec: properties: revision: type: integer - enum: [1] + minimum: 1 + maximum: 2147483647 + method: + type: string + enum: [Manual, NetBoxImport] + reason: + type: string + minLength: 1 + maxLength: 1024 + pattern: '\S' + reference: + type: string + minLength: 1 + maxLength: 1024 + pattern: '\S' observedAt: type: string format: date-time diff --git a/internal/api/inventory/v1alpha1/reported_placement_test.go b/internal/api/inventory/v1alpha1/reported_placement_test.go index eb0d78c5..9cf658fc 100644 --- a/internal/api/inventory/v1alpha1/reported_placement_test.go +++ b/internal/api/inventory/v1alpha1/reported_placement_test.go @@ -1,13 +1,78 @@ package v1alpha1 import ( + "bytes" + "encoding/json" + "reflect" "strings" "testing" "time" + jsonpatch "github.com/evanphx/json-patch/v5" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) +func TestPlacementJSONPatchPreconditionsBeforeAdmission(t *testing.T) { + baseline := reportedDevice() + baseline.UID = "device-uid" + baseline.ResourceVersion = "7" + report := &ReportedPlacement{Revision: 2, Method: "Manual", ObservedAt: later(time.Minute), Reason: "Correct record", Reference: "ticket/example"} + request, err := json.Marshal([]map[string]any{ + {"op": "test", "path": "/metadata/uid", "value": string(baseline.UID)}, + {"op": "test", "path": "/metadata/resourceVersion", "value": baseline.ResourceVersion}, + {"op": "add", "path": "/spec/reportedPlacement", "value": report}, + {"op": "replace", "path": "/spec/provenance/recordedAt", "value": later(time.Hour)}, + }) + if err != nil { + t.Fatal(err) + } + patch, err := jsonpatch.DecodePatch(request) + if err != nil { + t.Fatal(err) + } + for _, conflict := range []string{"", "uid", "resourceVersion"} { + t.Run(conflict, func(t *testing.T) { + current := baseline.DeepCopyObject().(*Device) + if conflict == "uid" { + current.UID = "replacement" + } + if conflict == "resourceVersion" { + current.ResourceVersion = "8" + } + before, err := json.Marshal(current) + if err != nil { + t.Fatal(err) + } + retained := bytes.Clone(before) + candidate, err := patch.Apply(before) + if !bytes.Equal(before, retained) { + t.Fatal("mutated input before commit") + } + if conflict != "" { + if err == nil || candidate != nil { + t.Fatal("precondition did not reject before mutation") + } + return + } + if err != nil { + t.Fatal(err) + } + var changed Device + if err := json.Unmarshal(candidate, &changed); err != nil { + t.Fatal(err) + } + if errs := admit(t, "Device", object(t, changed), object(t, current)); len(errs) != 0 { + t.Fatal(errs) + } + beforeSpec := object(t, baseline)["spec"].(map[string]any) + afterSpec := object(t, changed)["spec"].(map[string]any) + if !reflect.DeepEqual(afterSpec["provenance"].(map[string]any)["source"], beforeSpec["provenance"].(map[string]any)["source"]) || !reflect.DeepEqual(afterSpec["identity"], beforeSpec["identity"]) || changed.Spec.ClaimRef != baseline.Spec.ClaimRef { + t.Fatal("changed protected fields") + } + }) + } +} + func reportedDevice() Device { device := syntheticDevice() source := ExternalReference{System: "example-netbox", Type: "dcim/devices", ID: "1"} @@ -36,7 +101,14 @@ func TestReportedPlacementAdmission(t *testing.T) { } } for name, mutate := range map[string]func(*Device){ - "negative": func(device *Device) { value := -1.0; device.Spec.ReportedPlacement.Position = &value }, + "negative": func(device *Device) { value := -1.0; device.Spec.ReportedPlacement.Position = &value }, + "position range": func(device *Device) { value := 101.0; device.Spec.ReportedPlacement.Position = &value }, + "height range": func(device *Device) { value := 101.0; device.Spec.ReportedPlacement.Height = &value }, + "end range": func(device *Device) { + position, height := 100.0, 2.0 + device.Spec.ReportedPlacement.Position = &position + device.Spec.ReportedPlacement.Height = &height + }, "zero height": func(device *Device) { value := 0.0; device.Spec.ReportedPlacement.Height = &value }, "invalid face": func(device *Device) { device.Spec.ReportedPlacement.Face = "unknown" }, "geometry without rack": func(device *Device) { @@ -64,13 +136,13 @@ func TestReportedPlacementAdmission(t *testing.T) { } } -func TestPlacementCorrectionGateCannotBeBypassed(t *testing.T) { +func TestPlacementCorrectionProtectsIdentityAndRevision(t *testing.T) { for name, mutate := range map[string]func(*Device){ - "same rack enrichment": func(device *Device) { value := 12.0; device.Spec.ReportedPlacement.Position = &value }, - "rack move": func(device *Device) { device.Spec.ReportedPlacement.RackRef.Name = "rack-b" }, - "removal": func(device *Device) { device.Spec.ReportedPlacement = nil }, - "rebinding": func(device *Device) { device.Spec.ClaimRef.Name = "other" }, - "identity": func(device *Device) { device.Spec.Identity.Serial = "other" }, + "stale revision enrichment": func(device *Device) { value := 12.0; device.Spec.ReportedPlacement.Position = &value }, + "stale revision rack move": func(device *Device) { device.Spec.ReportedPlacement.RackRef.Name = "rack-b" }, + "removal": func(device *Device) { device.Spec.ReportedPlacement = nil }, + "rebinding": func(device *Device) { device.Spec.ClaimRef.Name = "other" }, + "identity": func(device *Device) { device.Spec.Identity.Serial = "other" }, "source": func(device *Device) { device.Spec.Provenance.Source.ID = "other" device.Spec.Identity.SourceIdentity.ID = "other" @@ -94,8 +166,8 @@ func TestPlacementCorrectionGateCannotBeBypassed(t *testing.T) { old := device.DeepCopyObject().(*Device) old.Spec.ReportedPlacement = nil device.Spec.Provenance.RecordedAt = later(time.Hour) - if errs := admit(t, "Device", object(t, device), object(t, old)); len(errs) == 0 { - t.Fatal("accepted addition to existing imported device") + if errs := admit(t, "Device", object(t, device), object(t, old)); len(errs) != 0 { + t.Fatal(errs) } old = device.DeepCopyObject().(*Device) device.Spec.DisplayName = "unrelated recordkeeping" @@ -104,3 +176,76 @@ func TestPlacementCorrectionGateCannotBeBypassed(t *testing.T) { t.Fatal(errs) } } + +func TestManualPlacementCorrections(t *testing.T) { + for _, imported := range []bool{false, true} { + for _, existing := range []bool{false, true} { + old := syntheticDevice() + if imported { + old = reportedDevice() + } + if existing && !imported { + old.Spec.ReportedPlacement = &ReportedPlacement{Revision: 1, Method: "Manual", ObservedAt: metav1.NewTime(recordedAt), Reason: "Initial report", Reference: "ticket/initial"} + } + if !existing { + old.Spec.ReportedPlacement = nil + } + device := old.DeepCopyObject().(*Device) + revision := int32(1) + if old.Spec.ReportedPlacement != nil { + revision++ + } + device.Spec.ReportedPlacement = &ReportedPlacement{Revision: revision, Method: "Manual", ObservedAt: later(time.Minute), Reason: "Correct record", Reference: "ticket/example", RackRef: &LocalReference{Name: "other-rack"}} + device.Spec.Provenance.RecordedAt = later(time.Hour) + if errs := admit(t, "Device", object(t, device), object(t, old)); len(errs) != 0 { + t.Fatal(errs) + } + for name, mutate := range map[string]func(*Device){ + "missing reason": func(record *Device) { record.Spec.ReportedPlacement.Reason = "" }, + "blank reason": func(record *Device) { record.Spec.ReportedPlacement.Reason = " " }, + "missing evidence": func(record *Device) { record.Spec.ReportedPlacement.Reference = "" }, + "false snapshot attribution": func(record *Device) { + record.Spec.ReportedPlacement.SnapshotDigest = "sha256:" + strings.Repeat("a", 64) + }, + "skipped revision": func(record *Device) { record.Spec.ReportedPlacement.Revision += 2 }, + "claim binding": func(record *Device) { record.Spec.ClaimRef.Name = "other" }, + "identity": func(record *Device) { record.Spec.Identity.Serial = "other" }, + } { + t.Run(name, func(t *testing.T) { + invalid := device.DeepCopyObject().(*Device) + mutate(invalid) + if errs := admit(t, "Device", object(t, invalid), object(t, old)); len(errs) == 0 { + t.Fatal("accepted invalid correction") + } + }) + } + if imported { + for _, field := range []string{"method", "system", "type", "id", "removal"} { + invalid := device.DeepCopyObject().(*Device) + switch field { + case "method": + invalid.Spec.Provenance.Method = "Manual" + case "system": + invalid.Spec.Provenance.Source.System = "other" + case "type": + invalid.Spec.Provenance.Source.Type = "other" + case "id": + invalid.Spec.Provenance.Source.ID = "other" + case "removal": + invalid.Spec.Provenance.Source = nil + } + if errs := admit(t, "Device", object(t, invalid), object(t, old)); len(errs) == 0 { + t.Fatalf("accepted changed import %s", field) + } + } + } + unknown := device.DeepCopyObject().(*Device) + unknown.Spec.ReportedPlacement.RackRef = nil + unknown.Spec.ReportedPlacement.Revision++ + unknown.Spec.Provenance.RecordedAt = later(2 * time.Hour) + if errs := admit(t, "Device", object(t, unknown), object(t, device)); len(errs) != 0 { + t.Fatal(errs) + } + } + } +} diff --git a/internal/api/inventory/v1alpha1/types.go b/internal/api/inventory/v1alpha1/types.go index 6568fe79..635522fc 100644 --- a/internal/api/inventory/v1alpha1/types.go +++ b/internal/api/inventory/v1alpha1/types.go @@ -123,7 +123,10 @@ type DeviceSpec struct { type ReportedPlacement struct { Revision int32 `json:"revision"` ObservedAt metav1.Time `json:"observedAt"` - SnapshotDigest string `json:"snapshotDigest"` + SnapshotDigest string `json:"snapshotDigest,omitempty"` + Method string `json:"method,omitempty"` + Reason string `json:"reason,omitempty"` + Reference string `json:"reference,omitempty"` FacilityRef *LocalReference `json:"facilityRef,omitempty"` RackRef *LocalReference `json:"rackRef,omitempty"` Position *float64 `json:"position,omitempty"` diff --git a/ui/shared/fleet-api.ts b/ui/shared/fleet-api.ts index 25b827ca..70ce7288 100644 --- a/ui/shared/fleet-api.ts +++ b/ui/shared/fleet-api.ts @@ -289,9 +289,12 @@ export interface Device { } export interface ReportedPlacement { - revision: 1; + revision: number; observedAt: string; - snapshotDigest: string; + snapshotDigest?: string; + method?: 'Manual' | 'NetBoxImport'; + reason?: string; + reference?: string; facilityRef?: LocalReference; rackRef?: LocalReference; position?: number; From e57ac654294526ff24ee6a751e310b4ca212ad4b Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sat, 21 Nov 2026 12:54:57 -0600 Subject: [PATCH 032/518] feat(provider): add guarded reported-location editor --- .../components/device-placement-edit.test.tsx | 129 ++++++++++++++++++ .../src/components/device-placement-edit.tsx | 112 +++++++++++++++ .../src/components/inventory-management.tsx | 2 +- .../src/components/physical-inventory.tsx | 7 +- .../src/lib/device-placement-edit.test.ts | 92 +++++++++++++ ui/provider/src/lib/device-placement-edit.ts | 107 +++++++++++++++ 6 files changed, 446 insertions(+), 3 deletions(-) create mode 100644 ui/provider/src/components/device-placement-edit.test.tsx create mode 100644 ui/provider/src/components/device-placement-edit.tsx create mode 100644 ui/provider/src/lib/device-placement-edit.test.ts create mode 100644 ui/provider/src/lib/device-placement-edit.ts diff --git a/ui/provider/src/components/device-placement-edit.test.tsx b/ui/provider/src/components/device-placement-edit.test.tsx new file mode 100644 index 00000000..a86a3aff --- /dev/null +++ b/ui/provider/src/components/device-placement-edit.test.tsx @@ -0,0 +1,129 @@ +import { fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import type { Device, PhysicalRecord } from '../../../shared/fleet-api'; +import { fixturePhysicalDevices } from '../lib/fixtures'; +import { DevicePlacementEdit } from './device-placement-edit'; +import { useInventoryPermission } from '../lib/inventory-management'; +import { InventoryOperationContext, InventoryOperationScope } from '../lib/inventory-operation'; + +vi.mock('../lib/inventory-management', async () => ({ ...await vi.importActual('../lib/inventory-management'), useInventoryPermission: vi.fn() })); +const permission = vi.mocked(useInventoryPermission); +const device: Device = { ...fixturePhysicalDevices[0], metadata: { name: 'example', namespace: 'default', uid: 'uid', resourceVersion: '7' }, spec: { ...fixturePhysicalDevices[0].spec, reportedPlacement: undefined, provenance: { ...fixturePhysicalDevices[0].spec.provenance, method: 'NetBoxImport', recordedAt: '2026-01-01T00:00:00Z' } } }; +const rack: PhysicalRecord = { kind: 'Rack', metadata: { name: 'rack', namespace: 'default', uid: 'rack-uid' }, spec: { displayName: 'Restricted rack name', heightUnits: 42, provenance: device.spec.provenance } }; +const response = (data: unknown, status = 200) => ({ ok: status < 400, status, json: async () => ({ data }) }); +function setup(record = device, session = new InventoryOperationScope()) { + const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + const view = render(); + return { ...view, client, session }; +} +function openAndFill(existing = false) { + fireEvent.click(screen.getByRole('button', { name: existing ? 'Correct location' : 'Add reported location' })); + fireEvent.change(screen.getByLabelText('Observation time (ISO 8601)'), { target: { value: '2026-01-02T00:00:00Z' } }); + fireEvent.change(screen.getByLabelText('Correction reason'), { target: { value: 'Correct source record' } }); + fireEvent.change(screen.getByLabelText('Evidence reference'), { target: { value: 'ticket/example' } }); +} +beforeEach(() => { vi.clearAllMocks(); permission.mockReturnValue({ data: true, isFetching: false, error: null } as never); }); +afterEach(() => vi.unstubAllGlobals()); + +describe('reported location editor', () => { + it.each([false, true])('adds/edits an imported Device and refreshes projections: %s', async existing => { + const record = structuredClone(device); + if (existing) record.spec.reportedPlacement = { revision: 1, observedAt: '2026-01-01T00:00:00Z', snapshotDigest: `sha256:${'a'.repeat(64)}`, rackRef: { name: 'rack' }, position: 12, height: 4, face: 'rear', fullDepth: true }; + const fetch = vi.fn().mockImplementation(async (_url: string, request: RequestInit) => { + if (request.method === 'POST') return response({ status: { allowed: true } }); + if (request.method === 'PATCH') return response({ ...record, metadata: { ...record.metadata, resourceVersion: '8' }, spec: { ...record.spec, reportedPlacement: JSON.parse(request.body as string)[2].value } }); + return response(_url.includes('/racks/') ? rack : record); + }); + vi.stubGlobal('fetch', fetch); + const { client } = setup(record); + const invalidate = vi.spyOn(client, 'invalidateQueries'); + openAndFill(existing); + fireEvent.click(screen.getByRole('button', { name: 'Save reported location' })); + await waitFor(() => expect(screen.getByRole('status')).toHaveTextContent('Reported location saved')); + expect(invalidate).toHaveBeenCalled(); + const patch = JSON.parse(fetch.mock.calls.find(([, request]) => request.method === 'PATCH')![1].body as string); + expect(patch[2].value.revision).toBe(existing ? 2 : 1); + expect(patch[2].value.height).toBe(existing ? 4 : undefined); + expect(patch[2].value.fullDepth).toBe(existing ? true : undefined); + }); + it.each([401, 403, 404, 409, 422, 503])('does not retry failed dispatch %s', async status => { + const fetch = vi.fn().mockResolvedValueOnce(response({ status: { allowed: true } })).mockResolvedValueOnce(response(device)).mockResolvedValueOnce(response({}, status)); + vi.stubGlobal('fetch', fetch); setup(); openAndFill(); + fireEvent.click(screen.getByRole('button', { name: 'Save reported location' })); + await waitFor(() => expect(screen.getByRole('status')).toBeInTheDocument()); + expect(screen.getByRole('status')).not.toHaveTextContent('saved'); + expect(screen.getByRole('button', { name: 'Save reported location' })).toBeDisabled(); + expect(fetch).toHaveBeenCalledTimes(3); + if (status === 503) expect(screen.getByRole('status')).toHaveTextContent('unknown'); + }); + it.each([401, 403, 404, 503])('purges denied rack references and choices: %s', async status => { + const fetch = vi.fn().mockResolvedValueOnce(response({ status: { allowed: true } })).mockResolvedValueOnce(response(device)).mockResolvedValueOnce(response({}, status)); + vi.stubGlobal('fetch', fetch); setup(); openAndFill(); + fireEvent.change(screen.getByLabelText('Actual rack (optional)'), { target: { value: 'rack' } }); + fireEvent.click(screen.getByRole('button', { name: 'Save reported location' })); + await waitFor(() => expect(screen.getByRole('status')).toHaveTextContent('Restricted names and choices were removed')); + expect(screen.queryByText('Restricted rack name')).not.toBeInTheDocument(); + expect(screen.queryByDisplayValue('rack')).not.toBeInTheDocument(); + expect(fetch).toHaveBeenCalledTimes(3); + }); + it.each(['session', 'blur', 'unmount', 'revalidation'])('revokes a delayed permission read on %s', async event => { + let resolve!: (value: unknown) => void; + const fetch = vi.fn().mockImplementationOnce(() => new Promise(done => { resolve = done; })); + vi.stubGlobal('fetch', fetch); + const view = setup(); openAndFill(); fireEvent.click(screen.getByRole('button', { name: 'Save reported location' })); + await waitFor(() => expect(resolve).toBeDefined()); + if (event === 'session') view.session.invalidate(); + if (event === 'blur') fireEvent(window, new Event('blur')); + if (event === 'unmount') view.unmount(); + if (event === 'revalidation') { + permission.mockReturnValue({ data: true, isFetching: true, error: null } as never); + view.rerender(); + } + resolve(response({ status: { allowed: true } })); + if (event !== 'unmount') await waitFor(() => expect(screen.getByRole('status')).toHaveTextContent('No write was dispatched')); + else await new Promise(done => setTimeout(done, 0)); + expect(fetch).toHaveBeenCalledTimes(1); + }); + it('freezes the original baseline instead of accepting a later render', async () => { + const fetch = vi.fn(); vi.stubGlobal('fetch', fetch); + const view = setup(); openAndFill(); + view.rerender(); + expect(screen.getByRole('button', { name: 'Save reported location' })).toBeDisabled(); + expect(fetch).not.toHaveBeenCalled(); + }); + it.each(['session', 'navigation', 'blur/focus'])('revokes a delayed reference read across %s', async event => { + let resolve!: (value: unknown) => void; + const fetch = vi.fn().mockResolvedValueOnce(response({ status: { allowed: true } })).mockResolvedValueOnce(response(device)).mockImplementationOnce(() => new Promise(done => { resolve = done; })); + vi.stubGlobal('fetch', fetch); + const view = setup(); openAndFill(); + fireEvent.change(screen.getByLabelText('Actual rack (optional)'), { target: { value: 'rack' } }); + fireEvent.click(screen.getByRole('button', { name: 'Save reported location' })); + await waitFor(() => expect(resolve).toBeDefined()); + if (event === 'session') view.session.invalidate(); + if (event === 'navigation') view.unmount(); + if (event === 'blur/focus') { fireEvent(window, new Event('blur')); fireEvent(window, new Event('focus')); } + resolve(response(rack)); + if (event !== 'navigation') await waitFor(() => expect(screen.getByRole('status')).toHaveTextContent('No write was dispatched')); + else await new Promise(done => setTimeout(done, 0)); + expect(fetch).toHaveBeenCalledTimes(3); + }); + it('shows unknown, not success or retry, after a dispatched write loses authority', async () => { + let resolve!: (value: unknown) => void; + const fetch = vi.fn().mockResolvedValueOnce(response({ status: { allowed: true } })).mockResolvedValueOnce(response(device)).mockImplementationOnce(() => new Promise(done => { resolve = done; })); + vi.stubGlobal('fetch', fetch); + const view = setup(); openAndFill(); fireEvent.click(screen.getByRole('button', { name: 'Save reported location' })); + await waitFor(() => expect(resolve).toBeDefined()); + view.session.invalidate(); resolve(response(device)); + await waitFor(() => expect(screen.getByRole('status')).toHaveTextContent('outcome is unknown')); + expect(screen.getByRole('button', { name: 'Save reported location' })).toBeDisabled(); + expect(fetch).toHaveBeenCalledTimes(3); + fireEvent.click(screen.getByRole('button', { name: 'Close location form' })); + expect(screen.queryByRole('button', { name: 'Add reported location' })).not.toBeInTheDocument(); + }); + it('hides editing for denied permission and legacy Flux', () => { + permission.mockReturnValue({ data: false, isFetching: false, error: null } as never); + setup({ ...device, metadata: { ...device.metadata, managedFields: [{ manager: 'kustomize-controller' }] } }); + expect(screen.queryByRole('button', { name: 'Add reported location' })).not.toBeInTheDocument(); + }); +}); diff --git a/ui/provider/src/components/device-placement-edit.tsx b/ui/provider/src/components/device-placement-edit.tsx new file mode 100644 index 00000000..32357081 --- /dev/null +++ b/ui/provider/src/components/device-placement-edit.tsx @@ -0,0 +1,112 @@ +import { useContext, useLayoutEffect, useRef, useState, type FormEvent } from 'react'; +import { useQueryClient } from '@tanstack/react-query'; +import type { Device, PhysicalRecord } from '../../../shared/fleet-api'; +import type { Inventory } from '../inventory'; +import { ApiError, PLUGIN_ID, PROVIDER_PROJECT } from '../lib/api'; +import { canCorrectPlacement, correctDevicePlacement, placementFields, type PlacementFields } from '../lib/device-placement-edit'; +import { useInventoryPermission } from '../lib/inventory-management'; +import { InventoryOperationContext, InventoryOperationInvalidated, InventoryOperationScope } from '../lib/inventory-operation'; +import { InventoryReadAccessContext, InventoryReferenceReadError, readFailureIssues, redactInventory } from '../lib/inventory-read-access'; + +export function DevicePlacementEdit({ device, locations, issues }: { device: Device; locations: PhysicalRecord[]; issues?: Inventory['issues'] }) { + const client = useQueryClient(); + const session = useContext(InventoryOperationContext); + const readFailure = useContext(InventoryReadAccessContext); + const scope = useRef(new InventoryOperationScope()); + const [baseline, setBaseline] = useState(); + const [fields, setFields] = useState(() => placementFields()); + const [pending, setPending] = useState(false); + const [blocked, setBlocked] = useState(false); + const [needsRefresh, setNeedsRefresh] = useState(false); + const [message, setMessage] = useState(''); + const [denied, setDenied] = useState({}); + const unavailable = { ...issues, ...denied }; + const namespace = device.metadata.namespace ?? ''; + const editable = canCorrectPlacement(device); + const permission = useInventoryPermission('Device', editable ? namespace : '', 'patch', device.metadata.name); + const allowed = editable && permission.data === true && !permission.isFetching && !permission.error && !unavailable.Device && !(device.spec.reportedPlacement?.facilityRef && unavailable.Facility) && !(device.spec.reportedPlacement?.rackRef && unavailable.Rack); + const visible = locations.filter(record => !unavailable[record.kind] && record.metadata.namespace === namespace && !record.metadata.deletionTimestamp); + const field = (key: keyof PlacementFields, value: string) => setFields(previous => ({ ...previous, [key]: value })); + useLayoutEffect(() => { + const invalidate = () => { scope.current.invalidate(); setBlocked(true); }; + const visibility = () => { if (document.visibilityState === 'hidden') invalidate(); }; + window.addEventListener('blur', invalidate); + window.addEventListener('pagehide', invalidate); + document.addEventListener('visibilitychange', visibility); + return () => { + scope.current.invalidate(); + window.removeEventListener('blur', invalidate); + window.removeEventListener('pagehide', invalidate); + document.removeEventListener('visibilitychange', visibility); + }; + }, []); + useLayoutEffect(() => { + scope.current.invalidate(); + setBlocked(true); + }, [device.metadata.uid, device.metadata.resourceVersion, allowed, permission.isFetching, session]); + useLayoutEffect(() => { setNeedsRefresh(false); }, [device.metadata.uid, device.metadata.resourceVersion]); + useLayoutEffect(() => { + if (!issues?.Facility && !issues?.Rack && !issues?.Device) return; + scope.current.invalidate(); setBlocked(true); setBaseline(undefined); + setFields(placementFields()); + }, [issues?.Facility, issues?.Rack, issues?.Device]); + async function save(event: FormEvent) { + event.preventDefault(); + if (!baseline || !allowed || pending || blocked) return; + const operation = scope.current.begin(session); + setPending(true); setMessage(''); + try { + await correctDevicePlacement(baseline, fields, operation); + operation.assertCurrent(); + setBaseline(undefined); setMessage('Reported location saved. No physical move or reservation was performed.'); + await client.invalidateQueries({ queryKey: [PLUGIN_ID, 'inventory', PROVIDER_PROJECT] }); + } catch (error) { + setBlocked(true); + setNeedsRefresh(true); + if (error instanceof InventoryOperationInvalidated) setMessage(error.message); + else if (error instanceof InventoryReferenceReadError) { + const failures = readFailureIssues(error); + setDenied(previous => ({ ...previous, ...failures })); + setBaseline(undefined); setFields(placementFields()); readFailure(error); + setMessage('Related inventory is unavailable. Restricted names and choices were removed. Reopen inventory after access is restored. No write was dispatched.'); + const queryKey = [PLUGIN_ID, 'inventory', PROVIDER_PROJECT]; + await client.cancelQueries({ queryKey }); + client.setQueriesData({ queryKey }, previous => previous ? redactInventory(previous, failures) : previous); + } else if (error instanceof ApiError && error.status === 422) { setBlocked(false); setNeedsRefresh(false); setMessage('Review the location, geometry, observation time, reason, and evidence. The API did not accept these values.'); } + else if (error instanceof ApiError && [401, 403].includes(error.status)) setMessage('Session or management access is no longer valid. Reopen inventory after access is restored.'); + else if (error instanceof ApiError && [404, 409].includes(error.status)) setMessage('The Device or a reference changed or disappeared. Refresh and reopen the form; do not retry this baseline.'); + else setMessage('The save outcome is unknown. Check the Device before another attempt; do not retry blindly.'); + } finally { setPending(false); } + } + return
      +

      Reported location

      +

      Correct a record, not a physical move, installation handover, or reservation. Identity and claim binding stay unchanged. Blank geometry means unknown; model and claim dimensions are not copied.

      + {!editable ?

      Legacy GitOps-managed or unavailable Devices are outside this editor.

      : !allowed &&

      Device management permission must be confirmed before correcting location.

      } + {allowed && !baseline && !needsRefresh && } + {baseline &&
      +

      Source: manual observation/correction. Original import provenance is retained. Authenticated actor history uses existing resource audit logs, not this form's attribution.

      + + + + + + + + + + +

      Do not include credentials or secrets in evidence.

      + + + {blocked &&

      This form is no longer authorized to save. Refresh inventory and reopen it.

      } +
      } + {message &&

      {message}

      } +
      ; +} diff --git a/ui/provider/src/components/inventory-management.tsx b/ui/provider/src/components/inventory-management.tsx index a13063ef..9338a861 100644 --- a/ui/provider/src/components/inventory-management.tsx +++ b/ui/provider/src/components/inventory-management.tsx @@ -100,7 +100,7 @@ export function InventoryManagement({ kind, record, facilities: sourceFacilities {compact && {record ? 'Editing access' : 'Namespace & access'}} {!record && } {dependenciesUnavailable &&

      Related records are unavailable, not empty. Creation needs readable location, installation, or endpoint records. Ask your administrator about viewing access, or try again after a temporary failure.

      } - {!editable ?

      This record has another or unknown writer. It needs an explicit ownership review before portal editing. Import provenance is history, not Git ownership; this portal has not established a writable handover for this record. No ownership changes are made here.

      : permission.isFetching ?

      Checking management access…

      : permission.error instanceof ApiError && permission.error.status === 401 ?

      Your session expired. Sign in again through the staff portal before continuing. Unsaved input remains here.

      : !allowed &&

      Viewing and management access are separate. Ask your administrator about physical-inventory management access. A permission check must succeed before changes are available.

      } + {!editable ?

      Display-name editing uses a narrower portal writer policy and is unavailable for this record. Import provenance is history, not Git ownership or server authorization. Device location correction, when separately available, uses ordinary management access and does not perform an ownership handover.

      : permission.isFetching ?

      Checking management access…

      : permission.error instanceof ApiError && permission.error.status === 401 ?

      Your session expired. Sign in again through the staff portal before continuing. Unsaved input remains here.

      : !allowed &&

      Viewing and management access are separate. Ask your administrator about physical-inventory management access. A permission check must succeed before changes are available.

      } {allowed && !open && } - {baseline &&
      + {open && permitted && +

      Source: manual observation/correction. Original import provenance is retained. Authenticated actor history uses existing resource audit logs, not this form's attribution.

      @@ -109,10 +115,9 @@ function DevicePlacementForm({ device, locations, issues }: { device: Device; lo

      Do not include credentials or secrets in evidence.

      +
      - - {blocked &&

      This form is no longer authorized to save. Refresh inventory and reopen it.

      } +
      } - {message &&

      {message}

      }
      ; } diff --git a/ui/provider/src/components/exact-head-independent.test.tsx b/ui/provider/src/components/exact-head-independent.test.tsx index ddfbc901..dd0ce8b0 100644 --- a/ui/provider/src/components/exact-head-independent.test.tsx +++ b/ui/provider/src/components/exact-head-independent.test.tsx @@ -13,13 +13,15 @@ const response = (data: unknown, status = 200) => ({ ok: status < 400, status, j afterEach(() => { cleanup(); vi.unstubAllGlobals(); }); async function open(editing: boolean, label: string) { + await waitFor(() => expect(screen.getByRole('button', { name: editing ? 'Edit display name' : 'Create facility' })).toBeEnabled()); fireEvent.click(await screen.findByRole('button', { name: editing ? 'Edit display name' : 'Create facility' })); if (!editing) fireEvent.change(screen.getByLabelText('Record name'), { target: { value: values.name } }); fireEvent.change(screen.getByLabelText('Display name'), { target: { value: label } }); fireEvent.change(screen.getByLabelText('Recorded by'), { target: { value: 'synthetic' } }); } -it.each([false, true].flatMap(strict => [false, true].flatMap(editing => ['review', 'dispatch-ok', 'dispatch-error'].flatMap(stage => ['fast-repeat', 'slow', 'overlap', 'cancel-navigation', 'focus-blur', 'focus-pagehide'].map(transition => ({ strict, editing, stage, transition }))))))('independent $transition $stage edit=$editing strict=$strict', async ({ strict, editing, stage, transition }) => { +it.each([false, true].flatMap(strict => [false, true].flatMap(editing => ['review', 'dispatch-ok', 'dispatch-error'].flatMap(stage => ['fast-repeat', 'principal-repeat', 'slow', 'overlap', 'cancel-navigation', 'focus-blur', 'focus-pagehide'].map(transition => ({ strict, editing, stage, transition }))))))('independent $transition $stage edit=$editing strict=$strict', async ({ strict, editing, stage, transition }) => { + let principal = 'same-user'; let submitting = false; let intercepted = false; let releaseOperation: ((value: unknown) => void) | undefined; @@ -38,25 +40,34 @@ it.each([false, true].flatMap(strict => [false, true].flatMap(editing => ['revie })); const router = createMemoryRouter([{ id: 'layouts/milo.layout', path: '/', loader: async () => { if (holdLoader) await new Promise(resolve => loaders.push(resolve)); - return { user: { metadata: { uid: 'same-user' } } }; + return { user: { metadata: { uid: principal } } }; }, element: , children: [{ index: true, element: }] }]); render(strict ? : ); await open(editing, 'Old input'); + const oldInput = screen.getByLabelText('Display name'); const submit = editing ? 'Save display name' : 'Create facility record'; submitting = true; fireEvent.click(screen.getByRole('button', { name: submit })); await waitFor(() => expect(releaseOperation).toBeDefined()); - if (transition === 'fast-repeat') { + if (transition === 'principal-repeat') { + await act(async () => { principal = 'other-user'; await router.revalidate(); principal = 'same-user'; await router.revalidate(); }); + } else if (transition === 'fast-repeat') { await act(async () => { await router.revalidate(); await router.revalidate(); await router.revalidate(); }); } else { holdLoader = true; act(() => { if (transition.startsWith('focus-')) window.dispatchEvent(new Event('focus')); else if (transition === 'cancel-navigation') void router.navigate('/?kind=Rack'); else void router.revalidate(); }); await waitFor(() => expect(loaders).toHaveLength(1)); - expect(screen.queryByLabelText('Display name')).not.toBeInTheDocument(); + if (transition.startsWith('focus-')) { + expect(screen.getByLabelText('Display name')).toBe(oldInput); + expect(oldInput).toBeDisabled(); + } else expect(screen.queryByLabelText('Display name')).not.toBeInTheDocument(); if (transition.startsWith('focus-')) { fireEvent(window, new Event(transition === 'focus-blur' ? 'blur' : 'pagehide')); await act(async () => loaders[0]()); - expect(screen.queryByLabelText('Display name')).not.toBeInTheDocument(); + if (transition === 'focus-blur') { + expect(screen.getByLabelText('Display name')).toBe(oldInput); + expect(oldInput).toBeDisabled(); + } else expect(screen.queryByLabelText('Display name')).not.toBeInTheDocument(); expect(screen.queryByRole('button', { name: 'Create facility' })).not.toBeInTheDocument(); holdLoader = false; await act(async () => window.dispatchEvent(new Event('focus'))); @@ -71,6 +82,15 @@ it.each([false, true].flatMap(strict => [false, true].flatMap(editing => ['revie holdLoader = false; } } + if (transition === 'focus-blur') { + await act(async () => releaseOperation!(response(stage === 'review' ? { status: { allowed: true } } : original, stage === 'dispatch-error' ? 503 : 200))); + await waitFor(() => expect(screen.getByRole('button', { name: 'Close form' })).toBeEnabled()); + expect(screen.getByRole('status')).toHaveTextContent(stage === 'review' ? 'No write was dispatched' : 'outcome is unknown'); + expect(oldInput).toBeDisabled(); + fireEvent.submit(oldInput.closest('form')!); + expect(writes).toHaveLength(stage === 'review' ? 0 : 1); + fireEvent.click(screen.getByRole('button', { name: 'Close form' })); + } await open(editing, 'Fresh input'); await act(async () => releaseOperation!(response(stage === 'review' ? { status: { allowed: true } } : original, stage === 'dispatch-error' ? 503 : 200))); expect(writes).toHaveLength(stage === 'review' ? 0 : 1); diff --git a/ui/provider/src/components/inventory-management.tsx b/ui/provider/src/components/inventory-management.tsx index 2c2bc5b6..af9a91ff 100644 --- a/ui/provider/src/components/inventory-management.tsx +++ b/ui/provider/src/components/inventory-management.tsx @@ -10,9 +10,7 @@ import type { Inventory } from '../inventory'; import { InventoryReadAccessContext, InventoryReferenceReadError, readFailureIssues, redactInventory } from '../lib/inventory-read-access'; export function InventoryManagement(props: ComponentProps) { - const generation = useContext(InventoryOperationGenerationContext); - const ready = useContext(InventoryOperationReadyContext); - return ready ? : null; + return ; } function InventoryManagementForm({ kind, record, facilities: sourceFacilities, claims: sourceClaims = [], devices: sourceDevices = [], feeds: sourceFeeds = [], racks: sourceRacks = [], compact = false, issues: sourceIssues }: { kind: ManagedKind; record?: ManagedRecord; facilities: PhysicalRecord[]; claims?: DeviceClaim[]; devices?: Device[]; feeds?: PhysicalRecord[]; racks?: PhysicalRecord[]; compact?: boolean; issues?: Inventory['issues'] }) { @@ -26,11 +24,13 @@ function InventoryManagementForm({ kind, record, facilities: sourceFacilities, c const feeds = issues.PowerFeed ? [] : sourceFeeds; const racks = issues.Rack ? [] : sourceRacks; const sessionScope = useContext(InventoryOperationContext); + const ready = useContext(InventoryOperationReadyContext); + const generation = useContext(InventoryOperationGenerationContext); const scope = useRef(new InventoryOperationScope()); useLayoutEffect(() => { const current = new InventoryOperationScope(); scope.current = current; - const invalidate = () => current.invalidate(); + const invalidate = () => { scope.current.invalidate(); setBaseline(undefined); setBlocked(true); }; const visibility = () => { if (document.visibilityState === 'hidden') invalidate(); }; window.addEventListener('blur', invalidate); window.addEventListener('pagehide', invalidate); @@ -47,12 +47,16 @@ function InventoryManagementForm({ kind, record, facilities: sourceFacilities, c const editable = !record || canEditInventoryLabel(record); const permission = useInventoryPermission(kind, editable ? namespace : '', record ? 'patch' : 'create', record?.metadata.name); const dependenciesUnavailable = !record && ((kind === 'Device' && !!issues?.DeviceClaim) || (kind === 'Rack' && !!issues?.Facility) || (kind === 'DeviceClaim' && !!issues?.Facility && !!issues?.Rack) || (kind === 'Cable' && !!issues?.Device && !!issues?.PowerFeed)); - const allowed = permission.data === true && !permission.isFetching && !permission.error && editable && !dependenciesUnavailable && !issues[kind]; + const visible = permission.data === true && !permission.error && editable && !dependenciesUnavailable && !issues[kind]; + const allowed = ready && visible && !permission.isFetching; const [open, setOpen] = useState(false); const [pending, setPending] = useState(false); const [blocked, setBlocked] = useState(false); const [message, setMessage] = useState(''); const [values, setValues] = useState({ name: record?.metadata.name ?? '', namespace, displayName: record?.spec.displayName ?? '', recordedBy: '', reference: '', facility: '', height: '' }); + useLayoutEffect(() => { + scope.current.invalidate(); setBaseline(undefined); setBlocked(true); + }, [ready, generation, permission.isFetching, visible]); const field = (name: keyof InventoryFormValues, value: string) => setValues(previous => ({ ...previous, [name]: value })); const kindLabel = kind === 'DeviceClaim' ? 'installation plan' : kind.toLowerCase(); async function save(event: FormEvent) { @@ -104,11 +108,13 @@ function InventoryManagementForm({ kind, record, facilities: sourceFacilities, c {!compact && Manage {record ? 'this record' : `${kind === 'Facility' ? 'facilities' : `${kindLabel}s`}`}}
      {compact && {record ? 'Editing access' : 'Namespace & access'}} - {!record && } + {!record && } {dependenciesUnavailable &&

      Related records are unavailable, not empty. Creation needs readable location, installation, or endpoint records. Ask your administrator about viewing access, or try again after a temporary failure.

      } - {!editable ?

      Display-name editing uses a narrower portal writer policy and is unavailable for this record. Import provenance is history, not Git ownership or server authorization. Device location correction, when separately available, uses ordinary management access and does not perform an ownership handover.

      : permission.isFetching ?

      Checking management access…

      : permission.error instanceof ApiError && permission.error.status === 401 ?

      Your session expired. Sign in again through the staff portal before continuing. Unsaved input remains here.

      : !allowed &&

      Viewing and management access are separate. Ask your administrator about physical-inventory management access. A permission check must succeed before changes are available.

      } + {!editable ?

      Display-name editing uses a narrower portal writer policy and is unavailable for this record. Import provenance is history, not Git ownership or server authorization. Device location correction, when separately available, uses ordinary management access and does not perform an ownership handover.

      : permission.error instanceof ApiError && permission.error.status === 401 ?

      Your session expired. Sign in again through the staff portal before continuing. Unsaved input remains here.

      : !visible &&

      Viewing and management access are separate. Ask your administrator about physical-inventory management access. A permission check must succeed before changes are available.

      }
      - {allowed && !open && }
      - {open &&
      +

      {message || (!ready || permission.isFetching ? 'Management: verification pending.' : open && blocked ? 'Management: close and reopen this form to continue.' : allowed ? 'Management: access checked.' : 'Management: unavailable.')}

      + {open && permission.data === true && !permission.error && !issues[kind] && +

      {record ? 'Only the display name and recording details change. Identity, placement, geometry, connections, and history remain untouched.' : 'Create a physical record only. This does not verify equipment, reserve space, or provision hardware.'}

      {!record && } @@ -131,8 +139,8 @@ function InventoryManagementForm({ kind, record, facilities: sourceFacilities, c

      The recorder is an attributed observation, not a replacement for the API audit identity of your signed-in account.

      -
      +
      +
      } - {message &&

      {message}

      } ; } diff --git a/ui/provider/src/components/inventory-session-boundary.test.tsx b/ui/provider/src/components/inventory-session-boundary.test.tsx index 879a87bd..36e517f4 100644 --- a/ui/provider/src/components/inventory-session-boundary.test.tsx +++ b/ui/provider/src/components/inventory-session-boundary.test.tsx @@ -51,12 +51,13 @@ describe('host inventory session isolation', () => { await act(async () => release!()); expect(screen.getByText('Visible inventory')).toBeInTheDocument(); expect(() => scope!.begin().assertCurrent()).toThrow(InventoryOperationInvalidated); + expect(inventoryRead).toHaveBeenCalledTimes(1); release = undefined; fireEvent(window, new Event('focus')); await waitFor(() => expect(release).toBeDefined()); await act(async () => release!()); expect(screen.getByText('Visible inventory')).toBeInTheDocument(); - expect(inventoryRead).toHaveBeenCalledTimes(3); + expect(inventoryRead).toHaveBeenCalledTimes(2); expect(() => scope!.begin().assertCurrent()).not.toThrow(); expect(() => before.assertCurrent()).toThrow(InventoryOperationInvalidated); expect(() => during.assertCurrent()).toThrow(InventoryOperationInvalidated); diff --git a/ui/provider/src/components/inventory-session-boundary.tsx b/ui/provider/src/components/inventory-session-boundary.tsx index aaef69b3..47ea9f08 100644 --- a/ui/provider/src/components/inventory-session-boundary.tsx +++ b/ui/provider/src/components/inventory-session-boundary.tsx @@ -44,7 +44,7 @@ export function SessionQueries({ children, principal, authority, generation }: { }; }, [host, principal, scope, ready, generation, authority, reads, client]); useEffect(() => { - if (readGeneration.current === generation) return; + if (!authority || readGeneration.current === generation) return; readGeneration.current = generation; let active = true; void client.cancelQueries().then(async () => { @@ -55,10 +55,13 @@ export function SessionQueries({ children, principal, authority, generation }: { const inventory = query.state.data as Inventory | undefined; return query.state.status === 'success' && query.state.fetchStatus === 'idle' && !Object.keys(inventoryResources).every(kind => inventory?.issues?.[kind as InventoryKind]); }); - if (active && readable) setReadyGeneration(generation); + if (active && readable) { + await client.invalidateQueries({ predicate: query => query.queryKey[1] === 'inventory-permission' }); + if (active) setReadyGeneration(generation); + } }); return () => { active = false; }; - }, [client, generation]); + }, [client, generation, authority]); useEffect(() => () => client.clear(), [client]); return {children}; } diff --git a/ui/provider/src/components/inventory-stable-controls.test.tsx b/ui/provider/src/components/inventory-stable-controls.test.tsx new file mode 100644 index 00000000..e6a0f8d6 --- /dev/null +++ b/ui/provider/src/components/inventory-stable-controls.test.tsx @@ -0,0 +1,124 @@ +import { StrictMode, type ReactNode } from 'react'; +import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { createMemoryRouter, Outlet, RouterProvider } from 'react-router'; +import { afterEach, expect, it, vi } from 'vitest'; +import { InventoryManagement } from './inventory-management'; +import { DevicePlacementEdit } from './device-placement-edit'; +import { InventorySessionBoundary } from './inventory-session-boundary'; +import { inventoryPayload, INVENTORY_FIELD_MANAGER, type ManagedKind } from '../lib/inventory-management'; +import { fixturePhysicalDevices } from '../lib/fixtures'; + +const values = { name: 'synthetic', namespace: 'default', displayName: 'Original', recordedBy: 'synthetic', reference: '', facility: '', height: '' }; +const record = { ...inventoryPayload('Facility', values), metadata: { name: 'synthetic', namespace: 'default', uid: 'synthetic', resourceVersion: '1', managedFields: [{ manager: INVENTORY_FIELD_MANAGER }] } }; +const device = { ...fixturePhysicalDevices[0], metadata: { ...record.metadata }, kind: 'Device' as const }; +const response = (data: unknown) => ({ ok: true, status: 200, json: async () => ({ data }) }); +afterEach(() => { vi.unstubAllGlobals(); vi.restoreAllMocks(); }); + +function host(content: ReactNode, strict = false) { + let hold = false; + let allow = true; + let principal = 'staff-a'; + let releaseHost: (() => void) | undefined; + let releasePermission: (() => void) | undefined; + const writes = vi.fn(); + const fetch = vi.fn(async (url: string, init: RequestInit) => { + if (url.includes('selfsubjectaccessreviews')) { + if (hold) await new Promise(resolve => { releasePermission = resolve; }); + return response({ status: { allowed: allow } }); + } + if (init.method !== 'GET') writes(); + return response(record); + }); + vi.stubGlobal('fetch', fetch); + const router = createMemoryRouter([{ id: 'layouts/milo.layout', path: '/', loader: async () => { + if (hold) await new Promise(resolve => { releaseHost = resolve; }); + return { user: { metadata: { uid: principal } } }; + }, element: , children: [{ index: true, element: {content} }] }]); + render(strict ? : ); + return { + router, writes, fetch, + hold: () => { hold = true; }, deny: () => { allow = false; }, + principal: (value: string) => { principal = value; }, + releaseHost: async () => { await waitFor(() => expect(releaseHost).toBeDefined()); await act(async () => releaseHost!()); }, + releasePermission: async () => { await waitFor(() => expect(releasePermission).toBeDefined()); hold = false; await act(async () => releasePermission!()); }, + }; +} + +const kinds: ManagedKind[] = ['Facility', 'Rack', 'Device', 'DeviceClaim', 'Cable']; +const cases = [...kinds.map(kind => ({ kind, mode: 'create', button: `Create ${kind === 'DeviceClaim' ? 'installation plan' : kind.toLowerCase()}` })), + { kind: 'Facility' as const, mode: 'label', button: 'Edit display name' }, + { kind: 'Device' as const, mode: 'location', button: 'Add reported location' }]; + +it.each(cases.flatMap(test => [false, true].flatMap(strict => [false, true].map(expanded => ({ ...test, strict, expanded })))))('retains $mode $kind DOM and revokes baselines expanded=$expanded strict=$strict', async ({ kind, mode, button, strict, expanded }) => { + const view = host(mode === 'location' ? : , strict); + await waitFor(() => expect(screen.getByRole('button', { name: button })).toBeEnabled()); + const access = screen.queryByText(mode === 'label' ? 'Editing access' : 'Namespace & access')?.closest('details'); + if (access && expanded) fireEvent.click(access.querySelector('summary')!); + const opener = screen.getByRole('button', { name: button }); + view.hold(); + fireEvent(window, new Event('blur')); + expect(screen.getByRole('button', { name: button })).toBe(opener); + expect(opener).toBeDisabled(); + const requests = view.fetch.mock.calls.length; + fireEvent.click(opener); + expect(view.fetch).toHaveBeenCalledTimes(requests); + fireEvent(window, new Event('focus')); + await view.releaseHost(); + expect(screen.getByRole('button', { name: button })).toBe(opener); + expect(opener).toBeDisabled(); + expect(screen.getByRole('status')).toHaveTextContent('verification pending'); + await view.releasePermission(); + await waitFor(() => expect(opener).toBeEnabled()); + fireEvent.click(opener); + const input = screen.getByLabelText(mode === 'location' ? 'Correction reason' : 'Display name'); + fireEvent.change(input, { target: { value: 'Safe draft' } }); + const form = input.closest('form')!; + view.hold(); + fireEvent(window, new Event('blur')); + expect(screen.getByLabelText(mode === 'location' ? 'Correction reason' : 'Display name')).toBe(input); + expect(input).toBeDisabled(); + fireEvent.submit(form); + fireEvent(window, new Event('focus')); + await view.releaseHost(); + expect(input).toBeDisabled(); + fireEvent.submit(form); + await view.releasePermission(); + const close = screen.getByRole('button', { name: mode === 'location' ? 'Close location form' : 'Close form' }); + await waitFor(() => expect(close).toBeEnabled()); + expect(input).toHaveValue('Safe draft'); + expect(input).toBeDisabled(); + expect(screen.getByRole('status')).toHaveTextContent('close and reopen'); + fireEvent.submit(form); + expect(view.writes).not.toHaveBeenCalled(); + if (access) { + expect(screen.getByText(mode === 'label' ? 'Editing access' : 'Namespace & access').closest('details')).toBe(access); + expect(access.open).toBe(expanded); + } + fireEvent.click(close); + fireEvent.click(screen.getByRole('button', { name: button })); + expect(screen.getByLabelText(mode === 'location' ? 'Correction reason' : 'Display name')).toBeEnabled(); + if (mode === 'create') expect(screen.getByLabelText('Display name')).toHaveValue('Safe draft'); + view.router.dispose(); +}); + +it.each(['denied', 'principal', 'hidden', 'pagehide'])('removes retained private drafts on confirmed %s', async transition => { + const view = host(); + fireEvent.click(await screen.findByRole('button', { name: 'Create facility' })); + fireEvent.change(screen.getByLabelText('Display name'), { target: { value: 'Private draft' } }); + view.hold(); + fireEvent(window, new Event('blur')); + if (transition === 'hidden') { + vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('hidden'); + fireEvent(document, new Event('visibilitychange')); + } else if (transition === 'pagehide') fireEvent(window, new Event('pagehide')); + else { + if (transition === 'denied') view.deny(); + else view.principal('staff-b'); + fireEvent(window, new Event('focus')); + await view.releaseHost(); + await view.releasePermission(); + } + await waitFor(() => expect(screen.queryByDisplayValue('Private draft')).not.toBeInTheDocument()); + expect(view.writes).not.toHaveBeenCalled(); + view.router.dispose(); +}); diff --git a/ui/provider/src/components/physical-inventory.css b/ui/provider/src/components/physical-inventory.css index 4db9331a..30211c99 100644 --- a/ui/provider/src/components/physical-inventory.css +++ b/ui/provider/src/components/physical-inventory.css @@ -44,6 +44,9 @@ .inventory-empty { display:flex; flex-direction:column; align-items:center; gap:12px; padding:48px 20px; text-align:center; color:var(--muted-foreground,#667571); } .inventory-empty button { cursor:pointer; padding:8px 16px; border:1px solid var(--border,#dce3df); border-radius:6px; color:var(--foreground,#182b2a); } .inventory-management { display:block; } +.inventory-management-status { min-height:3em; font-size:12px; } +.inventory-form > fieldset.inventory-form-gate { display:contents; } +.inventory-form-gate > p,.inventory-form-gate > div,.inventory-form-gate > fieldset { grid-column:1/-1; } .inventory-management > [role="status"] { margin-top:16px; } .inventory-management label { display:flex; flex-direction:column; gap:6px; margin:12px 0; } .inventory-management input,.inventory-management select { padding:9px 12px; background:var(--card,#fff); color:var(--foreground,#182b2a); border:1px solid var(--border,#dce3df); border-radius:6px; } diff --git a/ui/provider/src/components/pr103-review-negatives.test.tsx b/ui/provider/src/components/pr103-review-negatives.test.tsx index 764118d2..7583189d 100644 --- a/ui/provider/src/components/pr103-review-negatives.test.tsx +++ b/ui/provider/src/components/pr103-review-negatives.test.tsx @@ -54,6 +54,7 @@ it.each(['visible', 'overlap', 'hidden', 'denied'])('renews management only afte const table = screen.getByRole('table'); fireEvent.click(screen.getByRole('button', { name: 'Create facility' })); fireEvent.change(screen.getByLabelText('Display name'), { target: { value: 'Abandoned old form' } }); + const input = screen.getByLabelText('Display name'); holding = true; if (scenario === 'hidden') { visibility.mockReturnValue('hidden'); @@ -63,7 +64,11 @@ it.each(['visible', 'overlap', 'hidden', 'denied'])('renews management only afte } else fireEvent(window, new Event('blur')); fireEvent(window, new Event('focus')); await waitFor(() => expect(releases).toHaveLength(1)); - expect(screen.queryByLabelText('Display name')).not.toBeInTheDocument(); + if (scenario === 'hidden') expect(screen.queryByLabelText('Display name')).not.toBeInTheDocument(); + else { + expect(screen.getByLabelText('Display name')).toBe(input); + expect(input).toBeDisabled(); + } if (scenario === 'overlap') { fireEvent(window, new Event('focus')); await waitFor(() => expect(releases).toHaveLength(2)); @@ -79,10 +84,17 @@ it.each(['visible', 'overlap', 'hidden', 'denied'])('renews management only afte holding = false; fireEvent(window, new Event('focus')); } - await screen.findByRole('button', { name: 'Create facility' }); - if (scenario === 'visible' || scenario === 'overlap') expect(screen.getByRole('table')).toBe(table); + if (scenario === 'visible' || scenario === 'overlap') { + await waitFor(() => expect(screen.getByRole('button', { name: 'Close form' })).toBeEnabled()); + expect(screen.getByRole('table')).toBe(table); + expect(screen.getByLabelText('Display name')).toBe(input); + expect(input).toBeDisabled(); + expect(screen.getByRole('button', { name: 'Create facility record' })).toBeDisabled(); + fireEvent.click(screen.getByRole('button', { name: 'Close form' })); + } + await waitFor(() => expect(screen.getByRole('button', { name: 'Create facility' })).toBeEnabled()); fireEvent.click(screen.getByRole('button', { name: 'Create facility' })); - expect(screen.getByLabelText('Display name')).toHaveValue(''); + expect(screen.getByLabelText('Display name')).toHaveValue(scenario === 'visible' || scenario === 'overlap' ? 'Abandoned old form' : ''); router.dispose(); visibility.mockRestore(); }); diff --git a/ui/provider/src/test/session-browser-fixture.tsx b/ui/provider/src/test/session-browser-fixture.tsx index 3e618da2..ef7991e5 100644 --- a/ui/provider/src/test/session-browser-fixture.tsx +++ b/ui/provider/src/test/session-browser-fixture.tsx @@ -2,6 +2,7 @@ import { createRoot } from 'react-dom/client'; import { createMemoryRouter, Outlet, RouterProvider } from 'react-router'; import DeviceInventoryList from '../pages/device-inventory-list'; import { fixturePhysicalClaims, fixturePhysicalDevices, fixturePhysicalRecords } from '../lib/fixtures'; +import { INVENTORY_FIELD_MANAGER } from '../lib/inventory-management'; import '../preview.css'; let principal: string | null = 'synthetic-staff-a'; @@ -23,7 +24,10 @@ window.fetch = async (input, init) => { if (denied) return Response.json({ error: 'Synthetic read denial' }, { status: 403 }); const kind = url.includes('/facilities') ? 'Facility' : url.includes('/racks') ? 'Rack' : url.includes('/cables') ? 'Cable' : url.includes('/powerfeeds') ? 'PowerFeed' : 'Site'; const items = url.includes('/devices') ? fixturePhysicalDevices : url.includes('/deviceclaims') ? fixturePhysicalClaims : fixturePhysicalRecords.filter(record => record.kind === kind); - return Response.json({ data: { items } }); + return Response.json({ data: { items: items.map(record => ({ ...record, + metadata: { ...record.metadata, uid: `synthetic-${record.metadata.name}`, resourceVersion: '1', managedFields: [{ manager: INVENTORY_FIELD_MANAGER }] }, + spec: { ...record.spec, provenance: { ...record.spec.provenance, method: 'Manual', source: undefined } }, + })) } }); }; const router = createMemoryRouter([{ From e54d8bd859d0c01e5f77550dce77c0af27a0d236 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sat, 21 Nov 2026 18:23:52 -0600 Subject: [PATCH 044/518] feat(inventory): add observational shared hardware catalog --- .github/workflows/ci.yml | 1 + .../inventory/crds/fleet.datumapis.com.yaml | 378 ++++++++++++++++++ .../protected-resources/devicetype.yaml | 21 + .../protected-resources/kustomization.yaml | 2 + .../protected-resources/manufacturer.yaml | 21 + config/components/inventory/roles/editor.yaml | 8 + .../components/inventory/roles/manager.yaml | 6 + config/components/inventory/roles/viewer.yaml | 6 + docs/development/README.md | 5 + docs/development/hardware-catalog.md | 169 ++++++++ hack/netbox_catalog.py | 232 +++++++++++ hack/test_netbox_catalog.py | 143 +++++++ hack/testdata/catalog/candidates.json | 76 ++++ hack/testdata/catalog/existing.json | 12 + hack/testdata/catalog/mapping.json | 27 ++ hack/testdata/catalog/snapshot.json | 23 ++ internal/api/inventory/v1alpha1/catalog.go | 98 +++++ .../v1alpha1/catalog_envtest_test.go | 99 +++++ .../api/inventory/v1alpha1/catalog_test.go | 225 +++++++++++ internal/api/inventory/v1alpha1/crd_test.go | 4 +- internal/api/inventory/v1alpha1/iam_test.go | 2 +- internal/api/inventory/v1alpha1/types.go | 2 + .../components/adversarial-review.test.tsx | 4 +- .../exact-head-independent.test.tsx | 4 +- .../src/components/hardware-catalog.test.tsx | 109 +++++ .../components/inventory-hardware-fields.tsx | 12 +- .../src/components/inventory-management.tsx | 10 +- .../components/physical-inventory.test.tsx | 2 +- .../src/components/physical-inventory.tsx | 31 +- ui/provider/src/inventory.ts | 3 +- ui/provider/src/lib/hardware-catalog.ts | 14 + ui/provider/src/lib/inventory-api.test.ts | 6 +- .../src/lib/inventory-hardware.test.ts | 52 +++ ui/provider/src/lib/inventory-hardware.ts | 13 +- ui/provider/src/lib/inventory-management.ts | 2 +- ui/provider/src/lib/inventory-read-access.ts | 1 + ui/shared/fleet-api.ts | 10 +- 37 files changed, 1810 insertions(+), 23 deletions(-) create mode 100644 config/components/inventory/protected-resources/devicetype.yaml create mode 100644 config/components/inventory/protected-resources/manufacturer.yaml create mode 100644 docs/development/hardware-catalog.md create mode 100644 hack/netbox_catalog.py create mode 100644 hack/test_netbox_catalog.py create mode 100644 hack/testdata/catalog/candidates.json create mode 100644 hack/testdata/catalog/existing.json create mode 100644 hack/testdata/catalog/mapping.json create mode 100644 hack/testdata/catalog/snapshot.json create mode 100644 internal/api/inventory/v1alpha1/catalog.go create mode 100644 internal/api/inventory/v1alpha1/catalog_envtest_test.go create mode 100644 internal/api/inventory/v1alpha1/catalog_test.go create mode 100644 ui/provider/src/components/hardware-catalog.test.tsx create mode 100644 ui/provider/src/lib/hardware-catalog.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 957de3ce..4be3167e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -22,6 +22,7 @@ jobs: - run: go test -race ./... - run: go vet ./... - run: python3 -m unittest discover -s hack -p test_netbox_inventory.py + - run: python3 -m unittest discover -s hack -p test_netbox_catalog.py - run: go run ./test/acceptance/milo/cmd validate --root . - run: kustomize build config/base/crd >/dev/null - run: kustomize build config/milo >/dev/null diff --git a/config/components/inventory/crds/fleet.datumapis.com.yaml b/config/components/inventory/crds/fleet.datumapis.com.yaml index 15481000..382ae9a0 100644 --- a/config/components/inventory/crds/fleet.datumapis.com.yaml +++ b/config/components/inventory/crds/fleet.datumapis.com.yaml @@ -315,6 +315,8 @@ spec: message: claimRef is immutable; bind replacement hardware as a new Device - rule: self.identity == oldSelf.identity message: identity is immutable; a hardware swap is a new Device + - rule: '!has(oldSelf.deviceTypeRef) || (has(self.deviceTypeRef) && self.deviceTypeRef == oldSelf.deviceTypeRef)' + message: an assigned catalog reference cannot be removed or rebound - rule: '!has(oldSelf.reportedPlacement) || has(self.reportedPlacement)' message: retain a report; omit unknown location fields rather than removing the report - rule: '!has(self.reportedPlacement) || (oldSelf.hasValue() && has(oldSelf.value().reportedPlacement) ? (self.reportedPlacement == oldSelf.value().reportedPlacement || self.reportedPlacement.revision == oldSelf.value().reportedPlacement.revision + 1) : self.reportedPlacement.revision == 1)' @@ -359,6 +361,16 @@ spec: self.components.exists(c, c.id == a.componentID)))' message: service associations must reference present components properties: + deviceTypeRef: + type: object + required: + - name + properties: + name: + type: string + minLength: 1 + maxLength: 253 + pattern: '^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$' reportedPlacement: type: object required: [revision, observedAt] @@ -1500,3 +1512,369 @@ spec: type: object required: - spec +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: manufacturers.fleet.datumapis.com + annotations: + discovery.miloapis.com/parent-contexts: Project +spec: + group: fleet.datumapis.com + names: + kind: Manufacturer + listKind: ManufacturerList + plural: manufacturers + singular: manufacturer + scope: Namespaced + versions: + - name: v1alpha1 + served: true + storage: true + subresources: + status: {} + schema: + openAPIV3Schema: + type: object + required: + - spec + properties: + apiVersion: + type: string + kind: + type: string + metadata: + type: object + spec: + type: object + required: + - displayName + - provenance + - canonicalName + properties: + displayName: + type: string + minLength: 1 + maxLength: 253 + provenance: + type: object + required: + - method + - recordedBy + - recordedAt + properties: + method: + type: string + enum: + - Manual + - NetBoxImport + recordedBy: + type: string + minLength: 1 + maxLength: 253 + recordedAt: + type: string + format: date-time + reference: + type: string + minLength: 1 + maxLength: 1024 + source: + type: object + properties: + system: + type: string + minLength: 1 + maxLength: 253 + type: + type: string + minLength: 1 + maxLength: 253 + id: + type: string + minLength: 1 + maxLength: 253 + snapshotDigest: + type: string + pattern: ^sha256:[a-f0-9]{64}$ + mappingRevision: + type: string + minLength: 1 + maxLength: 253 + observedAt: + type: string + format: date-time + required: + - system + - type + - id + - snapshotDigest + - mappingRevision + - observedAt + x-kubernetes-validations: + - rule: self.method != 'NetBoxImport' || has(self.source) + message: NetBox imports require source provenance + - rule: has(self.source) == has(oldSelf.source) && (!has(self.source) + || (self.source.system == oldSelf.source.system && self.source.type + == oldSelf.source.type && self.source.id == oldSelf.source.id)) + message: source identity is immutable + sourceIdentity: + type: object + properties: + system: + type: string + minLength: 1 + maxLength: 253 + type: + type: string + minLength: 1 + maxLength: 253 + id: + type: string + minLength: 1 + maxLength: 253 + required: + - system + - type + - id + canonicalName: &id001 + type: string + minLength: 1 + maxLength: 253 + pattern: '^[A-Za-z0-9]([ -~]*[!-~])?$' + aliases: + type: array + maxItems: 32 + x-kubernetes-list-type: set + items: *id001 + x-kubernetes-validations: + - rule: self == oldSelf || self.provenance.recordedAt > oldSelf.provenance.recordedAt + message: every spec change must advance provenance.recordedAt + - rule: has(self.sourceIdentity) == has(oldSelf.sourceIdentity) && (!has(self.sourceIdentity) + || self.sourceIdentity == oldSelf.sourceIdentity) + message: source identity is immutable including its presence + - rule: '!has(self.sourceIdentity) || (self.provenance.method == "NetBoxImport" + && has(self.provenance.source) && self.sourceIdentity.system == self.provenance.source.system + && self.sourceIdentity.type == self.provenance.source.type && self.sourceIdentity.id + == self.provenance.source.id)' + message: imported identity must match provenance + - rule: self.provenance.method != "NetBoxImport" || has(self.sourceIdentity) + message: imported catalog entries require explicit source identity + - rule: '!has(self.aliases) || self.aliases.all(a, a.lowerAscii() != self.canonicalName.lowerAscii() + && self.aliases.filter(b, a.lowerAscii() == b.lowerAscii()).size() + == 1)' + message: aliases must be distinct ignoring ASCII case and cannot repeat + the canonical name + status: + type: object +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: devicetypes.fleet.datumapis.com + annotations: + discovery.miloapis.com/parent-contexts: Project +spec: + group: fleet.datumapis.com + names: + kind: DeviceType + listKind: DeviceTypeList + plural: devicetypes + singular: devicetype + scope: Namespaced + versions: + - name: v1alpha1 + served: true + storage: true + subresources: + status: {} + schema: + openAPIV3Schema: + type: object + required: + - spec + properties: + apiVersion: + type: string + kind: + type: string + metadata: + type: object + spec: + type: object + required: + - displayName + - provenance + - manufacturerRef + - model + properties: + displayName: + type: string + minLength: 1 + maxLength: 253 + provenance: + type: object + required: + - method + - recordedBy + - recordedAt + properties: + method: + type: string + enum: + - Manual + - NetBoxImport + recordedBy: + type: string + minLength: 1 + maxLength: 253 + recordedAt: + type: string + format: date-time + reference: + type: string + minLength: 1 + maxLength: 1024 + source: + type: object + properties: + system: + type: string + minLength: 1 + maxLength: 253 + type: + type: string + minLength: 1 + maxLength: 253 + id: + type: string + minLength: 1 + maxLength: 253 + snapshotDigest: + type: string + pattern: ^sha256:[a-f0-9]{64}$ + mappingRevision: + type: string + minLength: 1 + maxLength: 253 + observedAt: + type: string + format: date-time + required: + - system + - type + - id + - snapshotDigest + - mappingRevision + - observedAt + x-kubernetes-validations: + - rule: self.method != 'NetBoxImport' || has(self.source) + message: NetBox imports require source provenance + - rule: has(self.source) == has(oldSelf.source) && (!has(self.source) + || (self.source.system == oldSelf.source.system && self.source.type + == oldSelf.source.type && self.source.id == oldSelf.source.id)) + message: source identity is immutable + sourceIdentity: + type: object + properties: + system: + type: string + minLength: 1 + maxLength: 253 + type: + type: string + minLength: 1 + maxLength: 253 + id: + type: string + minLength: 1 + maxLength: 253 + required: + - system + - type + - id + manufacturerRef: + type: object + required: + - name + properties: + name: + type: string + minLength: 1 + maxLength: 253 + pattern: '^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$' + model: + type: string + minLength: 1 + maxLength: 253 + pattern: ^[a-z0-9]+(-[a-z0-9]+)*$ + modelShape: + type: object + properties: + heightUnits: + type: number + minimum: 0 + maximum: 100 + fullDepth: + type: boolean + componentTemplates: + type: array + maxItems: 256 + items: + type: object + properties: + id: + type: string + minLength: 1 + maxLength: 63 + name: + type: string + minLength: 1 + maxLength: 253 + type: + type: string + enum: + - NetworkPort + - PowerInlet + - PowerOutlet + - ConsolePort + - ConsoleServerPort + - FrontPort + - RearPort + - Module + - InventoryItem + - DeviceBay + connector: + type: string + minLength: 1 + maxLength: 253 + positions: + type: integer + minimum: 1 + maximum: 256 + required: + - id + - name + - type + x-kubernetes-list-type: map + x-kubernetes-list-map-keys: + - id + x-kubernetes-validations: + - rule: self == oldSelf || self.provenance.recordedAt > oldSelf.provenance.recordedAt + message: every spec change must advance provenance.recordedAt + - rule: has(self.sourceIdentity) == has(oldSelf.sourceIdentity) && (!has(self.sourceIdentity) + || self.sourceIdentity == oldSelf.sourceIdentity) + message: source identity is immutable including its presence + - rule: '!has(self.sourceIdentity) || (self.provenance.method == "NetBoxImport" + && has(self.provenance.source) && self.sourceIdentity.system == self.provenance.source.system + && self.sourceIdentity.type == self.provenance.source.type && self.sourceIdentity.id + == self.provenance.source.id)' + message: imported identity must match provenance + - rule: self.provenance.method != "NetBoxImport" || has(self.sourceIdentity) + message: imported catalog entries require explicit source identity + - rule: self.manufacturerRef == oldSelf.manufacturerRef && self.model + == oldSelf.model + message: manufacturer and normalized model identity are immutable; displayName + is mutable + status: + type: object diff --git a/config/components/inventory/protected-resources/devicetype.yaml b/config/components/inventory/protected-resources/devicetype.yaml new file mode 100644 index 00000000..8a268545 --- /dev/null +++ b/config/components/inventory/protected-resources/devicetype.yaml @@ -0,0 +1,21 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: fleet.datumapis.com-devicetype +spec: + serviceRef: + name: fleet.datumapis.com + kind: DeviceType + plural: devicetypes + singular: devicetype + permissions: + - list + - get + - watch + - create + - update + - patch + - delete + parentResources: + - apiGroup: resourcemanager.miloapis.com + kind: Project diff --git a/config/components/inventory/protected-resources/kustomization.yaml b/config/components/inventory/protected-resources/kustomization.yaml index 9e778c3c..b107ad0e 100644 --- a/config/components/inventory/protected-resources/kustomization.yaml +++ b/config/components/inventory/protected-resources/kustomization.yaml @@ -1,6 +1,8 @@ apiVersion: kustomize.config.k8s.io/v1beta1 kind: Kustomization resources: + - manufacturer.yaml + - devicetype.yaml - deviceclaim.yaml - device.yaml - facility.yaml diff --git a/config/components/inventory/protected-resources/manufacturer.yaml b/config/components/inventory/protected-resources/manufacturer.yaml new file mode 100644 index 00000000..e5e1f632 --- /dev/null +++ b/config/components/inventory/protected-resources/manufacturer.yaml @@ -0,0 +1,21 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: fleet.datumapis.com-manufacturer +spec: + serviceRef: + name: fleet.datumapis.com + kind: Manufacturer + plural: manufacturers + singular: manufacturer + permissions: + - list + - get + - watch + - create + - update + - patch + - delete + parentResources: + - apiGroup: resourcemanager.miloapis.com + kind: Project diff --git a/config/components/inventory/roles/editor.yaml b/config/components/inventory/roles/editor.yaml index 75f05f5b..a951878d 100644 --- a/config/components/inventory/roles/editor.yaml +++ b/config/components/inventory/roles/editor.yaml @@ -10,6 +10,14 @@ spec: inheritedRoles: - name: fleet.datumapis.com-inventory-viewer includedPermissions: + - fleet.datumapis.com/manufacturers.create + - fleet.datumapis.com/manufacturers.update + - fleet.datumapis.com/manufacturers.patch + - fleet.datumapis.com/manufacturers.delete + - fleet.datumapis.com/devicetypes.create + - fleet.datumapis.com/devicetypes.update + - fleet.datumapis.com/devicetypes.patch + - fleet.datumapis.com/devicetypes.delete - fleet.datumapis.com/sites.create - fleet.datumapis.com/sites.update - fleet.datumapis.com/sites.patch diff --git a/config/components/inventory/roles/manager.yaml b/config/components/inventory/roles/manager.yaml index ff6e9f04..f9f79f74 100644 --- a/config/components/inventory/roles/manager.yaml +++ b/config/components/inventory/roles/manager.yaml @@ -10,6 +10,12 @@ spec: inheritedRoles: - name: fleet.datumapis.com-inventory-viewer includedPermissions: + - fleet.datumapis.com/manufacturers.create + - fleet.datumapis.com/manufacturers.update + - fleet.datumapis.com/manufacturers.patch + - fleet.datumapis.com/devicetypes.create + - fleet.datumapis.com/devicetypes.update + - fleet.datumapis.com/devicetypes.patch - fleet.datumapis.com/sites.create - fleet.datumapis.com/sites.update - fleet.datumapis.com/sites.patch diff --git a/config/components/inventory/roles/viewer.yaml b/config/components/inventory/roles/viewer.yaml index 1f4e80a4..72e63237 100644 --- a/config/components/inventory/roles/viewer.yaml +++ b/config/components/inventory/roles/viewer.yaml @@ -8,6 +8,12 @@ metadata: spec: launchStage: Alpha includedPermissions: + - fleet.datumapis.com/manufacturers.get + - fleet.datumapis.com/manufacturers.list + - fleet.datumapis.com/manufacturers.watch + - fleet.datumapis.com/devicetypes.get + - fleet.datumapis.com/devicetypes.list + - fleet.datumapis.com/devicetypes.watch - fleet.datumapis.com/sites.get - fleet.datumapis.com/sites.list - fleet.datumapis.com/sites.watch diff --git a/docs/development/README.md b/docs/development/README.md index d68bfcb6..e5581095 100644 --- a/docs/development/README.md +++ b/docs/development/README.md @@ -43,6 +43,11 @@ Milo IAM, service, and quota boundaries; packaging is not runtime readiness. ## API group naming +The additive [shared hardware catalog](hardware-catalog.md) implements +Manufacturer/DeviceType records, denial-aware staff readers, and an optional +offline create-only catalog handoff. New registrations can select catalog models; +existing-device migration is deferred. Templates never modify installed assets. + The allocation APIs now use `metal.datumapis.com/v1alpha1`. Milo registers the Bare Metal service as `metal`; entitlement and location-availability readers use that reference. Physical Device references use `fleet.datumapis.com`; that group diff --git a/docs/development/hardware-catalog.md b/docs/development/hardware-catalog.md new file mode 100644 index 00000000..073449e6 --- /dev/null +++ b/docs/development/hardware-catalog.md @@ -0,0 +1,169 @@ +# Shared hardware catalog: implemented additive slice + +[Implementation status](README.md) · [Physical inventory](../operations/physical-inventory.md) + +This implementation builds on staging branch `feat/manual-inventory-records` at +`f190d28397fc6110e02c9c83e6819a3a584258d0`, including Site/Facility membership and +Device reported placement. It does not replace those APIs or their writers. +The [pinned inventory proposal](../proposals/fleet-management/inventory-reference.md#asset-identity-and-typed-components) +already describes a reusable model/port shape, initially a document rather than a +public kind. This authorized implementation promotes that concept to Manufacturer +and DeviceType records. It does **not** implement the proposal's accepted-plan +shape pinning, physical qualification, reservations, or component reconciliation. + +## Implemented contracts + +- `fleet.datumapis.com/v1alpha1` Manufacturer and DeviceType are namespaced, + operator-written catalog records served in the provider's Milo Project. + There is no catalog controller, status writer, capacity publication, allocation, + installation, node, networking, provisioning, or IAM membership effect. +- Manufacturer has a mutable `canonicalName`, human `displayName`, and optional + descriptive `aliases`. ASCII labels are bounded and cannot have leading/trailing + spaces; case-insensitive aliases must be distinct within one object and cannot + repeat its canonical name. Aliases never merge identities or resolve references. +- DeviceType has an immutable `manufacturerRef: {name}` and normalized `model` + identity key (`[a-z0-9]+(-[a-z0-9]+)*`). `displayName` is its mutable human model + label. Stable metadata names are operator-selected, not regenerated from labels. + Distinct hardware variants need distinct reviewed model keys. +- Shared `modelShape` reuses the existing height-in-rack-units/full-depth shape; + absent values mean unknown. It is **nominal**, never a measured installation or + observed occupancy. `componentTemplates` reuse the component type, connector, + position, name and stable local-ID vocabulary, but have no serial, asset tag or + source-instance identity. They do not create installed ports, topology or assets. +- Both kinds retain normal provenance. Every changed spec must advance + `provenance.recordedAt`. Imported `sourceIdentity` is immutable, including its + presence, and must match NetBoxImport provenance. A catalog edit changes no + Device, claim, installed component, source observation, or reported placement. +- Device gains an optional `deviceTypeRef: {name}` outside immutable `identity`. + A first explicit attachment must advance existing provenance; once attached, + the reference cannot be removed or rebound. Existing inline manufacturer/model, + serial, sourceIdentity and claimRef remain unchanged and immutable. Imported + Devices retain their original NetBoxImport source evidence when an authorized + writer records an attachment; catalog edits never overwrite source observations. + +## Scope, guarantees, and reader safety + +References always resolve in the referring object's namespace and provider +Project. No spec accepts a UID or an explicit cross-namespace reference. Ordinary +Kubernetes unknown-field pruning is **not** rejection: clients must use +`fieldValidation=Strict`; the offline importer rejects unknown mapping keys and +UIDs. Disposable API tests exercise strict decoding as well as conflict handling. + +These are name references, not incarnation pins. Missing or deleting targets are +unavailable; recreating a name resolves to the replacement object. This never +proves physical continuity or triggers instance changes. Do not reuse names during +routine catalog maintenance. Preventing reuse requires a separately reviewed +retention/tombstone policy, not a UID added to the spec. + +CRD admission validates **one object's** syntax, alias uniqueness, immutable +fields and provenance. It cannot atomically enforce uniqueness of a normalized +model across objects within a manufacturer, canonical manufacturer names across +objects, source IDs across objects, or the existence/authorization of references. +Distinct resource names can still describe the same model. No webhook or global +uniqueness reservation is claimed. Offline cohort checks detect known collisions, +but a target snapshot is not a transaction and races remain possible. + +The Go reader requires a caller-authorized `client.Reader`; do not substitute an +unrestricted controller credential for a staff caller. It reads both targets and +returns no partial catalog/error detail when either is unavailable. UI collection +reads use existing provider proxy and session-generation fencing. Denial or +unavailability of Manufacturers suppresses dependent DeviceTypes, including deep +links, search and filters. Device labels use the catalog only when both references +are readable; otherwise the Device's independently authorized legacy/source +observation remains available. Catalog fallback does not query aliases or leak +denied reference names. Existing session, focus and late-response safety tests +remain intact; only their collection cardinality increases from seven to nine. + +Inventory viewer gains catalog get/list/watch. Manager gains create/update/patch; +editor also has delete, consistent with the existing editor role. No status, +wildcard, consumer, membership or operational permission is added. Deploying +these definitions does not bind anyone to these roles. + +## Optional offline catalog handoff + +`hack/netbox_catalog.py` consumes the existing version-1 NetBox snapshot format, +an explicit mapping, and a complete namespace-local Manufacturer/DeviceType +snapshot. It never calls NetBox or Fleet. Run, retaining output privately: + +```sh +python3 hack/netbox_catalog.py --snapshot /private/netbox.json \ + --mapping /private/catalog-mapping.json --existing /private/fleet-catalog.json \ + --recorded-by operator-identity --recorded-at 2026-11-21T01:00:00Z +``` + +The synthetic [mapping fixture](../../hack/testdata/catalog/mapping.json) shows +the format. `target` requires `project`, `namespace`, and `writer: DirectAPI`. +The Fleet snapshot must attest `collections: [Manufacturer, DeviceType]`, contain +that same target, and include both complete collections, including empty ones. +Manufacturer `sourceID` and DeviceType `sourceID`/`manufacturerSourceID` are +explicit positive NetBox IDs, never aliases, host IDs or chassis serials. Model +normalization lowercases ASCII and collapses non-alphanumeric runs to a hyphen; +the explicitly supplied key must match. Normalization collisions are quarantined, +not silently deduplicated. Non-ASCII source models require adjudication. + +Deduplication uses `(source system, source collection, source ID)` and the exact +stable target name. Repeated identical imports are no-ops; interrupted creates +are handled by refreshing the snapshot. Conflicting existing records, alias or +canonical-name collisions, duplicate normalized model pairs, missing references, +malformed inputs, unknown mapping fields and duplicate JSON keys quarantine the +**entire cohort** with no candidates. Source/catalog evidence stays private. + +Output is a review envelope, not an automatically applied Kubernetes List. +The approved owner must re-read authorization, existing identities and conflicts +immediately before individual create-only API requests. Reject existing names; +never apply/overwrite, adopt a source, change its writer or claim, or treat an +uncertain creation as success. Retain receipts and refresh after interruption. +No GitOps inventory/catalog records, recurring sync, or live migration is added +or authorized by this command. The older physical importer is not invoked. + +## Explicitly deferred user-visible work + +Staff can browse Manufacturers/DeviceTypes and see catalog-backed Device labels, +source observations and nominal template details. New manual Device registrations +offer an optional same-namespace catalog selection, with fresh authorized reads +and UID/resourceVersion checks of both targets immediately before create. Strict +field validation prevents an older Device schema silently dropping the reference. +Selection never copies labels, components or shape into source observations; +inline observed model data remains required. These reads are not an atomic +cross-object lock: a later recreation follows the documented name semantics. +Catalog create/edit forms and attachment/correction forms for **existing** Devices +are not implemented. Importing catalog records does not attach +existing or new Devices; shape/template import, legacy-source migration, +assignment correction/rebinding and accepted-plan revision pinning need follow-up. + +An explicit direct-API attachment must use the Device's current owner, require +fresh authorized reads of both same-namespace targets, retain exact inputs, and +test metadata UID and resourceVersion before adding the reference and advancing +provenance. UIDs are request preconditions, never spec references. Use Strict +field validation. A failed or uncertain request requires readback, not a blind +retry. No live attachment is performed here. Correcting an already attached +reference requires a reviewed compatibility contract; do not weaken identity +immutability, delete/recreate the Device, or transfer its claim to work around it. + +## Validation and rollout gates + +```sh +go test ./... +go test -race ./... +go vet ./... +python3 -m unittest discover -s hack -p 'test_netbox*.py' +pnpm --dir ui/provider typecheck && pnpm --dir ui/provider test && pnpm --dir ui/provider build +pnpm --dir ui/consumer typecheck && pnpm --dir ui/consumer test && pnpm --dir ui/consumer build +kustomize build config/milo >/dev/null +kustomize build config/inventory >/dev/null +bash hack/validate-doc-links.sh +git diff --check +``` + +Set `KUBEBUILDER_ASSETS` to the repository's pinned envtest assets to include the +disposable API checks; without it that test is explicitly skipped. These checks +are not proof of real Milo authorization or live NetBox parity. + +The parent task owns independent adversarial review, CI and staging deployment. +Roll out additive CRDs and least-privilege IAM definitions, then denial-aware +readers, **before any writer**. Confirm existing Site/Facility/Device placement +behavior and unreadable/missing catalog fallback on staging. Never roll back by +pruning CRDs or catalog/occupied records, downgrading schemas to prune retained +fields, deleting Devices, or rebinding identity. Roll back readers first while +retaining additive schemas, records and existing writer authority. Live migration +and any ownership transition remain separately approved operations. diff --git a/hack/netbox_catalog.py b/hack/netbox_catalog.py new file mode 100644 index 00000000..d2f60b8f --- /dev/null +++ b/hack/netbox_catalog.py @@ -0,0 +1,232 @@ +"""Offline, create-only catalog candidate review; never writes to a live API.""" + +import argparse +import copy +import datetime +import json +import re +import sys + +from netbox_inventory import digest, name_ok + + +KINDS = {"Manufacturer": "dcim/manufacturers", "DeviceType": "dcim/device-types"} +LABEL = re.compile(r"[A-Za-z0-9]([ -~]*[!-~])?") + + +def fields(value, required, optional=()): + if not isinstance(value, dict) or not set(required) <= value.keys() or value.keys() - set(required) - set(optional): + raise ValueError("missing or unknown mapping/identity fields") + + +def text(value): + if not isinstance(value, str) or not value or len(value) > 253 or value != value.strip(): + raise ValueError("invalid catalog text") + return value + + +def label(value): + if not LABEL.fullmatch(text(value)): + raise ValueError("invalid ASCII catalog label") + return value + + +def model_key(value): + value = text(value) + if not value.isascii(): + raise ValueError("non-ASCII source model requires adjudication") + result = re.sub(r"[^a-z0-9]+", "-", value.lower()).strip("-") + if not result: + raise ValueError("empty normalized model") + return result + + +def source_id(value): + if type(value) is int and value > 0: + return str(value) + if isinstance(value, str) and re.fullmatch(r"[1-9][0-9]*", value): + return value + raise ValueError("invalid explicit NetBox source ID") + + +def timestamp(value): + if not isinstance(value, str): + raise ValueError("invalid observation time") + parsed = datetime.datetime.fromisoformat(value.replace("Z", "+00:00")) + if parsed.tzinfo is None: + raise ValueError("timestamp requires timezone") + return parsed + + +def identity(value): + fields(value, ("system", "type", "id")) + return tuple(text(value[key]) for key in ("system", "type", "id")) + + +def no_uid(value): + if isinstance(value, dict): + if "uid" in value: + raise ValueError("UID fields are not allowed in specs or mappings") + for child in value.values(): + no_uid(child) + elif isinstance(value, list): + for child in value: + no_uid(child) + + +def plan(snapshot, mapping, existing, recorded_by, recorded_at): + no_uid(mapping) + fields(mapping, ("revision", "target", "manufacturers", "deviceTypes")) + target = mapping["target"] + fields(target, ("project", "namespace", "writer")) + if target["writer"] != "DirectAPI" or not name_ok(target["project"]) or not name_ok(target["namespace"]): + raise ValueError("catalog requires an explicit operator-managed DirectAPI target") + revision = text(mapping["revision"]) + text(recorded_by) + if not isinstance(snapshot, dict) or snapshot.get("version") != 1 or snapshot.get("errors"): + raise ValueError("complete version-1 snapshot required") + system = text(snapshot.get("source")) + observed = snapshot.get("observedAt") + if timestamp(recorded_at) < timestamp(observed): + raise ValueError("recording predates observation") + fields(existing, ("target", "collections", "items")) + if existing["target"] != target or sorted(existing["collections"]) != sorted(KINDS) or not isinstance(existing["items"], list): + raise ValueError("complete matching catalog snapshot required") + objects = snapshot.get("objects") + if not isinstance(objects, dict): + raise ValueError("source collections required") + sources = {} + for collection in KINDS.values(): + if not isinstance(objects.get(collection), list): + raise ValueError("missing catalog source collection") + for row in objects[collection]: + if not isinstance(row, dict): + raise ValueError("malformed source row") + key = (collection, source_id(row.get("id"))) + if key in sources: + raise ValueError("duplicate source identity") + sources[key] = row + records = {} + source_names = {} + for record in existing["items"]: + if not isinstance(record, dict) or record.get("kind") not in KINDS or record.get("apiVersion") != "fleet.datumapis.com/v1alpha1": + raise ValueError("invalid existing catalog record") + meta, spec = record.get("metadata", {}), record.get("spec", {}) + no_uid(spec) + if meta.get("namespace") != target["namespace"] or not name_ok(meta.get("name")) or meta.get("deletionTimestamp"): + raise ValueError("invalid or terminating existing target") + key = (record["kind"], meta["name"]) + if key in records: + raise ValueError("duplicate existing target") + records[key] = copy.deepcopy(record) + if "sourceIdentity" in spec: + source = identity(spec["sourceIdentity"]) + if source in source_names: + raise ValueError("ambiguous existing source identity") + source_names[source] = key + candidates = [] + mapped_sources = set() + mapped_names = set() + manufacturer_names = {} + for kind, mapping_key in (("Manufacturer", "manufacturers"), ("DeviceType", "deviceTypes")): + entries = mapping[mapping_key] + if not isinstance(entries, list): + raise ValueError("catalog mappings must be lists") + for entry in entries: + required = ("sourceID", "name", "canonicalName") if kind == "Manufacturer" else ("sourceID", "name", "manufacturerSourceID", "model", "displayName") + fields(entry, required, ("aliases",) if kind == "Manufacturer" else ()) + identifier = source_id(entry["sourceID"]) + name = entry["name"] + if not name_ok(name): + raise ValueError("invalid stable resource name") + source = (system, KINDS[kind], identifier) + key = (kind, name) + if source in mapped_sources or key in mapped_names: + raise ValueError("duplicate mapping identity or target") + mapped_sources.add(source) + mapped_names.add(key) + row = sources.get((KINDS[kind], identifier)) + if row is None: + raise ValueError("mapped source ID missing") + if source in source_names and source_names[source] != key: + raise ValueError("source identity already has a different stable target name") + external = dict(zip(("system", "type", "id"), source)) + spec = {"sourceIdentity": external, "provenance": {"method": "NetBoxImport", "recordedBy": recorded_by, "recordedAt": recorded_at, "source": {**external, "snapshotDigest": digest(snapshot), "mappingRevision": revision, "observedAt": observed}}} + if kind == "Manufacturer": + canonical = label(entry["canonicalName"]) + if canonical != row.get("name"): + raise ValueError("canonical name differs from source; adjudicate explicitly outside import") + aliases = entry.get("aliases", []) + if not isinstance(aliases, list) or len(aliases) > 32: + raise ValueError("invalid aliases") + spec.update(displayName=canonical, canonicalName=canonical) + if aliases: + spec["aliases"] = [label(alias) for alias in aliases] + manufacturer_names[identifier] = name + else: + parent = source_id(entry["manufacturerSourceID"]) + parent_record = row.get("manufacturer") + if not isinstance(parent_record, dict) or source_id(parent_record.get("id")) != parent or parent not in manufacturer_names: + raise ValueError("manufacturer source mapping missing or mismatched") + if entry["model"] != model_key(row.get("model")): + raise ValueError("model key must match normalized source model") + spec.update(displayName=text(entry["displayName"]), manufacturerRef={"name": manufacturer_names[parent]}, model=entry["model"]) + candidate = {"apiVersion": "fleet.datumapis.com/v1alpha1", "kind": kind, "metadata": {"name": name, "namespace": target["namespace"]}, "spec": spec} + if key in records: + old_spec = records[key]["spec"] + if {field: value for field, value in old_spec.items() if field != "provenance"} != {field: value for field, value in spec.items() if field != "provenance"}: + raise ValueError("existing target differs; no update, merge, rebind or takeover permitted") + else: + records[key] = candidate + candidates.append(candidate) + labels, models = set(), set() + for (kind, name), record in records.items(): + spec = record["spec"] + if kind == "Manufacturer": + aliases = spec.get("aliases", []) + if not isinstance(aliases, list) or len(aliases) > 32: + raise ValueError("invalid existing aliases") + for value in [spec.get("canonicalName"), *aliases]: + normalized = label(value).lower() + if normalized in labels: + raise ValueError("ambiguous canonical name or alias collision") + labels.add(normalized) + else: + fields(spec.get("manufacturerRef"), ("name",)) + parent = spec["manufacturerRef"]["name"] + model = text(spec.get("model")) + if not name_ok(parent) or ("Manufacturer", parent) not in records or not re.fullmatch(r"[a-z0-9]+(-[a-z0-9]+)*", model) or (parent, model) in models: + raise ValueError("missing manufacturer or duplicate/invalid normalized model") + models.add((parent, model)) + return {"target": target, "items": candidates, "report": "Create-only candidates; no device migration, synchronization, GitOps or live effects. Re-read target before individual creates; reject existing names."} + + +def unique_object(pairs): + result = {} + for key, value in pairs: + if key in result: + raise ValueError("duplicate JSON key") + result[key] = value + return result + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + for name in ("snapshot", "mapping", "existing", "recorded-by", "recorded-at"): + parser.add_argument("--" + name, required=True) + args = parser.parse_args() + try: + inputs = [] + for path in (args.snapshot, args.mapping, args.existing): + with open(path, encoding="utf-8") as stream: + inputs.append(json.load(stream, object_pairs_hook=unique_object)) + result = plan(*inputs, args.recorded_by, args.recorded_at) + except (ValueError, TypeError, KeyError, AttributeError, OSError) as error: + print(json.dumps({"items": [], "quarantined": True, "reason": str(error)})) + return 1 + print(json.dumps(result, indent=2)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/hack/test_netbox_catalog.py b/hack/test_netbox_catalog.py new file mode 100644 index 00000000..1ae3ea6b --- /dev/null +++ b/hack/test_netbox_catalog.py @@ -0,0 +1,143 @@ +import copy +import json +from pathlib import Path +import subprocess +import tempfile +import unittest + +import netbox_catalog as catalog + + +def fixture(): + snapshot = {"version": 1, "source": "example-netbox", "observedAt": "2026-11-21T00:00:00Z", "errors": {}, "objects": { + "dcim/manufacturers": [{"id": 1, "name": "Example Vendor"}], + "dcim/device-types": [{"id": 2, "model": "Example 1U", "manufacturer": {"id": 1}}], + }} + mapping = {"revision": "reviewed-1", "target": {"project": "example-provider", "namespace": "inventory", "writer": "DirectAPI"}, + "manufacturers": [{"sourceID": "1", "name": "vendor-stable", "canonicalName": "Example Vendor", "aliases": ["Old Vendor"]}], + "deviceTypes": [{"sourceID": "2", "name": "type-stable", "manufacturerSourceID": "1", "model": "example-1u", "displayName": "Example 1U"}]} + existing = {"target": copy.deepcopy(mapping["target"]), "collections": ["Manufacturer", "DeviceType"], "items": []} + return snapshot, mapping, existing + + +def plan(snapshot, mapping, existing): + return catalog.plan(snapshot, mapping, existing, "synthetic-operator", "2026-11-21T01:00:00Z") + + +class CatalogTests(unittest.TestCase): + def test_punctuated_human_names_are_not_resource_names(self): + snapshot, mapping, existing = fixture() + snapshot["objects"]["dcim/manufacturers"][0]["name"] = "Example Vendor, Inc." + mapping["manufacturers"][0]["canonicalName"] = "Example Vendor, Inc." + self.assertEqual("vendor-stable", plan(snapshot, mapping, existing)["items"][0]["metadata"]["name"]) + + def test_checked_in_candidates_are_reproducible(self): + root = Path(__file__).parent / "testdata" / "catalog" + inputs = [json.loads((root / (name + ".json")).read_text()) for name in ("snapshot", "mapping", "existing")] + self.assertEqual(json.loads((root / "candidates.json").read_text()), plan(*inputs)) + + def test_create_only_and_repeat_noop(self): + snapshot, mapping, existing = fixture() + retained = copy.deepcopy((snapshot, mapping, existing)) + result = plan(snapshot, mapping, existing) + self.assertEqual(["Manufacturer", "DeviceType"], [item["kind"] for item in result["items"]]) + self.assertEqual({"name": "vendor-stable"}, result["items"][1]["spec"]["manufacturerRef"]) + self.assertEqual("2", result["items"][1]["spec"]["sourceIdentity"]["id"]) + self.assertEqual(retained, (snapshot, mapping, existing)) + existing["items"] = result["items"] + self.assertEqual([], plan(snapshot, mapping, existing)["items"]) + mapping["deviceTypes"][0]["name"] = "new-target" + with self.assertRaises(ValueError): + plan(snapshot, mapping, existing) + + def test_interrupted_import_retains_existing_manufacturer(self): + snapshot, mapping, existing = fixture() + existing["items"] = plan(snapshot, mapping, existing)["items"][:1] + self.assertEqual(["DeviceType"], [item["kind"] for item in plan(snapshot, mapping, existing)["items"]]) + + def test_aliases_and_normalization_collisions_quarantine_whole_cohort(self): + for aliases in (["Old Vendor", "old vendor"], ["EXAMPLE VENDOR"], [" trailing "], [""], [None], {}, "alias"): + snapshot, mapping, existing = fixture() + mapping["manufacturers"][0]["aliases"] = aliases + with self.subTest(aliases=aliases), self.assertRaises(ValueError): + plan(snapshot, mapping, existing) + snapshot, mapping, existing = fixture() + snapshot["objects"]["dcim/manufacturers"].append({"id": 3, "name": "Other Vendor"}) + mapping["manufacturers"].append({"sourceID": "3", "name": "other-vendor", "canonicalName": "Other Vendor", "aliases": ["old vendor"]}) + with self.assertRaises(ValueError): + plan(snapshot, mapping, existing) + snapshot, mapping, existing = fixture() + snapshot["objects"]["dcim/device-types"].append({"id": 3, "model": "Example--1U", "manufacturer": {"id": 1}}) + mapping["deviceTypes"].append(dict(mapping["deviceTypes"][0], sourceID="3", name="other-type")) + with self.assertRaises(ValueError): + plan(snapshot, mapping, existing) + + def test_malformed_mappings_and_unknown_uid_fields(self): + for key, value in (("uid", "forbidden"), ("namespace", "other"), ("sourceID", True), ("sourceID", "01"), ("name", "Upper"), ("model", "Wrong Model"), ("manufacturerSourceID", "9")): + snapshot, mapping, existing = fixture() + mapping["deviceTypes"][0][key] = value + with self.subTest(key=key), self.assertRaises(ValueError): + plan(snapshot, mapping, existing) + for value in (None, [], "wrong", {"uid": "forbidden"}): + snapshot, mapping, existing = fixture() + mapping["deviceTypes"] = [value] + with self.subTest(value=value), self.assertRaises(ValueError): + plan(snapshot, mapping, existing) + + def test_existing_collisions_and_mutations_are_not_updates(self): + for mutation in ("label", "source", "uid", "duplicate", "namespace", "terminating", "unknown-reference"): + snapshot, mapping, existing = fixture() + existing["items"] = plan(snapshot, mapping, existing)["items"] + record = existing["items"][1] + if mutation == "label": + record["spec"]["displayName"] = "Operator changed" + elif mutation == "source": + record["spec"]["sourceIdentity"]["id"] = "9" + elif mutation == "uid": + record["spec"]["manufacturerRef"]["uid"] = "not-allowed" + elif mutation == "duplicate": + duplicate = copy.deepcopy(record) + duplicate["metadata"]["name"] = "duplicate-source" + existing["items"].append(duplicate) + elif mutation == "namespace": + record["metadata"]["namespace"] = "other" + elif mutation == "terminating": + record["metadata"]["deletionTimestamp"] = "2026-11-21T00:00:00Z" + else: + record["spec"]["manufacturerRef"]["extra"] = "invalid" + with self.subTest(mutation=mutation), self.assertRaises(ValueError): + plan(snapshot, mapping, existing) + + def test_incomplete_source_and_gitops_are_refused(self): + for mutation in ("errors", "missing", "duplicate", "gitops", "stale", "incomplete"): + snapshot, mapping, existing = fixture() + if mutation == "errors": + snapshot["errors"] = {"dcim/manufacturers": "denied"} + elif mutation == "missing": + del snapshot["objects"]["dcim/device-types"] + elif mutation == "duplicate": + snapshot["objects"]["dcim/manufacturers"] *= 2 + elif mutation == "gitops": + mapping["target"]["writer"] = "Flux" + elif mutation == "stale": + snapshot["observedAt"] = "2026-11-22T00:00:00Z" + else: + existing["collections"] = ["DeviceType"] + with self.subTest(mutation=mutation), self.assertRaises(ValueError): + plan(snapshot, mapping, existing) + + def test_cli_quarantines_duplicate_json_keys_without_candidates(self): + with tempfile.TemporaryDirectory() as directory: + files = [] + for index, value in enumerate(fixture()): + path = Path(directory) / f"{index}.json" + path.write_text(json.dumps(value)) + files.append(str(path)) + Path(files[1]).write_text('{"uid":"one","uid":"two"}') + result = subprocess.run(["python3", str(Path(catalog.__file__)), "--snapshot", files[0], "--mapping", files[1], "--existing", files[2], "--recorded-by", "synthetic", "--recorded-at", "2026-11-21T01:00:00Z"], capture_output=True, text=True) + self.assertEqual(1, result.returncode) + self.assertEqual([], json.loads(result.stdout)["items"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/hack/testdata/catalog/candidates.json b/hack/testdata/catalog/candidates.json new file mode 100644 index 00000000..8696108a --- /dev/null +++ b/hack/testdata/catalog/candidates.json @@ -0,0 +1,76 @@ +{ + "target": { + "project": "example-provider", + "namespace": "inventory", + "writer": "DirectAPI" + }, + "items": [ + { + "apiVersion": "fleet.datumapis.com/v1alpha1", + "kind": "Manufacturer", + "metadata": { + "name": "vendor-stable", + "namespace": "inventory" + }, + "spec": { + "sourceIdentity": { + "system": "example-netbox", + "type": "dcim/manufacturers", + "id": "1" + }, + "provenance": { + "method": "NetBoxImport", + "recordedBy": "synthetic-operator", + "recordedAt": "2026-11-21T01:00:00Z", + "source": { + "system": "example-netbox", + "type": "dcim/manufacturers", + "id": "1", + "snapshotDigest": "sha256:0486ee8b35c860b5e615acb20a0189321112a97472f6a0c59ad8c10cd9ad55c1", + "mappingRevision": "reviewed-1", + "observedAt": "2026-11-21T00:00:00Z" + } + }, + "displayName": "Example Vendor", + "canonicalName": "Example Vendor", + "aliases": [ + "Old Vendor" + ] + } + }, + { + "apiVersion": "fleet.datumapis.com/v1alpha1", + "kind": "DeviceType", + "metadata": { + "name": "type-stable", + "namespace": "inventory" + }, + "spec": { + "sourceIdentity": { + "system": "example-netbox", + "type": "dcim/device-types", + "id": "2" + }, + "provenance": { + "method": "NetBoxImport", + "recordedBy": "synthetic-operator", + "recordedAt": "2026-11-21T01:00:00Z", + "source": { + "system": "example-netbox", + "type": "dcim/device-types", + "id": "2", + "snapshotDigest": "sha256:0486ee8b35c860b5e615acb20a0189321112a97472f6a0c59ad8c10cd9ad55c1", + "mappingRevision": "reviewed-1", + "observedAt": "2026-11-21T00:00:00Z" + } + }, + "displayName": "Example 1U", + "manufacturerRef": { + "name": "vendor-stable" + }, + "model": "example-1u" + } + } + ], + "report": "Create-only candidates; no device migration, synchronization, GitOps or live effects. Re-read target before individual creates; reject existing names." +} diff --git a/hack/testdata/catalog/existing.json b/hack/testdata/catalog/existing.json new file mode 100644 index 00000000..7b686f57 --- /dev/null +++ b/hack/testdata/catalog/existing.json @@ -0,0 +1,12 @@ +{ + "target": { + "project": "example-provider", + "namespace": "inventory", + "writer": "DirectAPI" + }, + "collections": [ + "Manufacturer", + "DeviceType" + ], + "items": [] +} diff --git a/hack/testdata/catalog/mapping.json b/hack/testdata/catalog/mapping.json new file mode 100644 index 00000000..975467b1 --- /dev/null +++ b/hack/testdata/catalog/mapping.json @@ -0,0 +1,27 @@ +{ + "revision": "reviewed-1", + "target": { + "project": "example-provider", + "namespace": "inventory", + "writer": "DirectAPI" + }, + "manufacturers": [ + { + "sourceID": "1", + "name": "vendor-stable", + "canonicalName": "Example Vendor", + "aliases": [ + "Old Vendor" + ] + } + ], + "deviceTypes": [ + { + "sourceID": "2", + "name": "type-stable", + "manufacturerSourceID": "1", + "model": "example-1u", + "displayName": "Example 1U" + } + ] +} diff --git a/hack/testdata/catalog/snapshot.json b/hack/testdata/catalog/snapshot.json new file mode 100644 index 00000000..98c003df --- /dev/null +++ b/hack/testdata/catalog/snapshot.json @@ -0,0 +1,23 @@ +{ + "version": 1, + "source": "example-netbox", + "observedAt": "2026-11-21T00:00:00Z", + "errors": {}, + "objects": { + "dcim/manufacturers": [ + { + "id": 1, + "name": "Example Vendor" + } + ], + "dcim/device-types": [ + { + "id": 2, + "model": "Example 1U", + "manufacturer": { + "id": 1 + } + } + ] + } +} diff --git a/internal/api/inventory/v1alpha1/catalog.go b/internal/api/inventory/v1alpha1/catalog.go new file mode 100644 index 00000000..d3d841ec --- /dev/null +++ b/internal/api/inventory/v1alpha1/catalog.go @@ -0,0 +1,98 @@ +package v1alpha1 + +import ( + "context" + "fmt" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "sigs.k8s.io/controller-runtime/pkg/client" +) + +type ManufacturerSpec struct { + PhysicalMetadata `json:",inline"` + CanonicalName string `json:"canonicalName"` + Aliases []string `json:"aliases,omitempty"` + SourceIdentity *ExternalReference `json:"sourceIdentity,omitempty"` +} + +type ComponentTemplate struct { + ID string `json:"id"` + Name string `json:"name"` + Type string `json:"type"` + Connector string `json:"connector,omitempty"` + Positions int32 `json:"positions,omitempty"` +} + +type DeviceTypeSpec struct { + PhysicalMetadata `json:",inline"` + ManufacturerRef LocalReference `json:"manufacturerRef"` + Model string `json:"model"` + ModelShape *ModelShape `json:"modelShape,omitempty"` + ComponentTemplates []ComponentTemplate `json:"componentTemplates,omitempty"` + SourceIdentity *ExternalReference `json:"sourceIdentity,omitempty"` +} + +type Manufacturer struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + Spec ManufacturerSpec `json:"spec"` +} + +type ManufacturerList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []Manufacturer `json:"items"` +} + +type DeviceType struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + Spec DeviceTypeSpec `json:"spec"` +} + +type DeviceTypeList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []DeviceType `json:"items"` +} + +func (in *Manufacturer) DeepCopyObject() runtime.Object { + out := new(Manufacturer) + deepCopy(in, out) + return out +} + +func (in *ManufacturerList) DeepCopyObject() runtime.Object { + out := new(ManufacturerList) + deepCopy(in, out) + return out +} + +func (in *DeviceType) DeepCopyObject() runtime.Object { + out := new(DeviceType) + deepCopy(in, out) + return out +} + +func (in *DeviceTypeList) DeepCopyObject() runtime.Object { + out := new(DeviceTypeList) + deepCopy(in, out) + return out +} + +func ReadDeviceCatalog(ctx context.Context, reader client.Reader, device *Device) (*DeviceType, *Manufacturer, error) { + unavailable := fmt.Errorf("hardware catalog unavailable") + if reader == nil || device == nil || device.Namespace == "" || !device.DeletionTimestamp.IsZero() || device.Spec.DeviceTypeRef == nil || device.Spec.DeviceTypeRef.Name == "" { + return nil, nil, unavailable + } + var model DeviceType + if err := reader.Get(ctx, client.ObjectKey{Namespace: device.Namespace, Name: device.Spec.DeviceTypeRef.Name}, &model); err != nil || !model.DeletionTimestamp.IsZero() || model.Spec.ManufacturerRef.Name == "" { + return nil, nil, unavailable + } + var manufacturer Manufacturer + if err := reader.Get(ctx, client.ObjectKey{Namespace: device.Namespace, Name: model.Spec.ManufacturerRef.Name}, &manufacturer); err != nil || !manufacturer.DeletionTimestamp.IsZero() { + return nil, nil, unavailable + } + return &model, &manufacturer, nil +} diff --git a/internal/api/inventory/v1alpha1/catalog_envtest_test.go b/internal/api/inventory/v1alpha1/catalog_envtest_test.go new file mode 100644 index 00000000..337d2c77 --- /dev/null +++ b/internal/api/inventory/v1alpha1/catalog_envtest_test.go @@ -0,0 +1,99 @@ +package v1alpha1 + +import ( + "context" + "encoding/json" + "os" + "path/filepath" + "testing" + "time" + + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/client-go/kubernetes" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/envtest" +) + +func TestCatalogAPIConcurrencyAndStrictFields(t *testing.T) { + if os.Getenv("KUBEBUILDER_ASSETS") == "" { + t.Skip("KUBEBUILDER_ASSETS required for disposable catalog API validation") + } + environment := &envtest.Environment{CRDDirectoryPaths: []string{filepath.Join(inventoryRoot, "crds")}, ErrorIfCRDPathMissing: true} + config, err := environment.Start() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if err := environment.Stop(); err != nil { + t.Error(err) + } + }) + scheme := runtime.NewScheme() + if err := AddToScheme(scheme); err != nil { + t.Fatal(err) + } + if err := corev1.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + api, err := client.New(config, client.Options{Scheme: scheme}) + if err != nil { + t.Fatal(err) + } + ctx := context.Background() + if err := api.Create(ctx, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "fleet-system"}}); err != nil { + t.Fatal(err) + } + manufacturer, model := catalogRecords() + device := syntheticDevice() + for _, record := range []client.Object{manufacturer, model, &device} { + if err := api.Create(ctx, record); err != nil { + t.Fatal(err) + } + } + stale := device.DeepCopyObject().(*Device) + device.Spec.DeviceTypeRef = &LocalReference{Name: model.Name} + device.Spec.Provenance.RecordedAt = later(time.Hour) + if err := api.Update(ctx, &device); err != nil { + t.Fatal(err) + } + stale.Spec.DeviceTypeRef = &LocalReference{Name: "different"} + stale.Spec.Provenance.RecordedAt = later(2 * time.Hour) + if err := api.Update(ctx, stale); !apierrors.IsConflict(err) { + t.Fatalf("stale writer did not conflict: %v", err) + } + device.Spec.DeviceTypeRef = nil + device.Spec.Provenance.RecordedAt = later(2 * time.Hour) + if err := api.Update(ctx, &device); !apierrors.IsInvalid(err) { + t.Fatalf("reference removal accepted: %v", err) + } + model.Spec.DisplayName = "Edited catalog only" + model.Spec.Provenance.RecordedAt = later(time.Hour) + if err := api.Update(ctx, model); err != nil { + t.Fatal(err) + } + var unchanged Device + if err := api.Get(ctx, client.ObjectKeyFromObject(&device), &unchanged); err != nil { + t.Fatal(err) + } + if unchanged.Spec.Identity != syntheticDevice().Spec.Identity || unchanged.Spec.DeviceTypeRef.Name != model.Name || len(unchanged.Spec.Components) != 0 { + t.Fatal("catalog edit changed physical instance") + } + core, err := kubernetes.NewForConfig(config) + if err != nil { + t.Fatal(err) + } + invalid := object(t, syntheticDevice()) + invalid["metadata"].(map[string]any)["name"] = "invalid-reference" + invalid["spec"].(map[string]any)["deviceTypeRef"] = map[string]any{"name": model.Name, "uid": "not-a-spec-field", "namespace": "other"} + body, err := json.Marshal(invalid) + if err != nil { + t.Fatal(err) + } + err = core.RESTClient().Post().AbsPath("/apis/fleet.datumapis.com/v1alpha1/namespaces/fleet-system/devices").Param("fieldValidation", "Strict").Body(body).Do(ctx).Error() + if !apierrors.IsBadRequest(err) { + t.Fatalf("strict API did not reject unknown reference fields: %v", err) + } +} diff --git a/internal/api/inventory/v1alpha1/catalog_test.go b/internal/api/inventory/v1alpha1/catalog_test.go new file mode 100644 index 00000000..525628de --- /dev/null +++ b/internal/api/inventory/v1alpha1/catalog_test.go @@ -0,0 +1,225 @@ +package v1alpha1 + +import ( + "context" + "encoding/json" + "fmt" + "os" + "reflect" + "testing" + "time" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" +) + +func TestImportedCatalogCandidatesPassAdmission(t *testing.T) { + data, err := os.ReadFile("../../../../hack/testdata/catalog/candidates.json") + if err != nil { + t.Fatal(err) + } + var candidates struct { + Items []json.RawMessage `json:"items"` + } + if err := json.Unmarshal(data, &candidates); err != nil { + t.Fatal(err) + } + if len(candidates.Items) != 2 { + t.Fatal("expected both catalog kinds") + } + for _, raw := range candidates.Items { + candidate := object(t, raw) + kind := candidate["kind"].(string) + for _, old := range []map[string]any{nil, candidate} { + if errs := admit(t, kind, candidate, old); len(errs) != 0 { + t.Fatal(errs) + } + } + } +} + +func catalogRecords() (*Manufacturer, *DeviceType) { + metadata := PhysicalMetadata{DisplayName: "Example", Provenance: provenance(recordedAt)} + manufacturer := &Manufacturer{TypeMeta: metav1.TypeMeta{APIVersion: GroupVersion.String(), Kind: "Manufacturer"}, ObjectMeta: metav1.ObjectMeta{Name: "vendor-stable", Namespace: "fleet-system"}, Spec: ManufacturerSpec{PhysicalMetadata: metadata, CanonicalName: "Example Vendor", Aliases: []string{"Old Vendor"}}} + model := &DeviceType{TypeMeta: metav1.TypeMeta{APIVersion: GroupVersion.String(), Kind: "DeviceType"}, ObjectMeta: metav1.ObjectMeta{Name: "model-stable", Namespace: "fleet-system"}, Spec: DeviceTypeSpec{PhysicalMetadata: metadata, ManufacturerRef: LocalReference{Name: manufacturer.Name}, Model: "example-1u", ComponentTemplates: []ComponentTemplate{{ID: "port-1", Name: "Port 1", Type: "NetworkPort"}}}} + return manufacturer, model +} + +func TestCatalogAdmission(t *testing.T) { + manufacturer, model := catalogRecords() + manufacturer.Spec.CanonicalName = "Example Vendor, Inc." + manufacturer.Spec.Aliases = []string{"Old Vendor", "Example Vendor"} + for _, record := range []any{manufacturer, model} { + candidate := object(t, record) + if errs := admit(t, candidate["kind"].(string), candidate, nil); len(errs) != 0 { + t.Fatal(errs) + } + } + manufacturer, _ = catalogRecords() + for _, aliases := range [][]string{{"Old Vendor", "old vendor"}, {"Example Vendor"}, {" leading"}, {"trailing "}, {""}} { + candidate := manufacturer.DeepCopyObject().(*Manufacturer) + candidate.Spec.Aliases = aliases + if errs := admit(t, "Manufacturer", object(t, candidate), nil); len(errs) == 0 { + t.Fatalf("accepted aliases %v", aliases) + } + } + for _, key := range []string{"Example-1u", "example 1u", "example--1u", "", "example_1u"} { + candidate := model.DeepCopyObject().(*DeviceType) + candidate.Spec.Model = key + if errs := admit(t, "DeviceType", object(t, candidate), nil); len(errs) == 0 { + t.Fatalf("accepted non-normalized key %q", key) + } + } + for _, name := range []string{"", "Upper", "vendor..one", "vendor/one", "vendor.-one"} { + candidate := model.DeepCopyObject().(*DeviceType) + candidate.Spec.ManufacturerRef.Name = name + if errs := admit(t, "DeviceType", object(t, candidate), nil); len(errs) == 0 { + t.Fatalf("accepted invalid reference %q", name) + } + } + duplicate := model.DeepCopyObject().(*DeviceType) + duplicate.Spec.ComponentTemplates = append(duplicate.Spec.ComponentTemplates, duplicate.Spec.ComponentTemplates[0]) + if errs := admit(t, "DeviceType", object(t, duplicate), nil); len(errs) == 0 { + t.Fatal("accepted duplicate template ID") + } + duplicate = model.DeepCopyObject().(*DeviceType) + duplicate.Name = "different-resource-name" + if errs := admit(t, "DeviceType", object(t, duplicate), nil); len(errs) != 0 { + t.Fatal("local admission must not claim cross-object uniqueness", errs) + } +} + +func TestCatalogSourceIdentityAndScheme(t *testing.T) { + scheme := runtime.NewScheme() + if err := AddToScheme(scheme); err != nil { + t.Fatal(err) + } + for _, kind := range []string{"Manufacturer", "ManufacturerList", "DeviceType", "DeviceTypeList"} { + if _, err := scheme.New(GroupVersion.WithKind(kind)); err != nil { + t.Fatal(err) + } + } + manufacturer, _ := catalogRecords() + source := ExternalReference{System: "synthetic-netbox", Type: "dcim/manufacturers", ID: "1"} + manufacturer.Spec.SourceIdentity = &source + manufacturer.Spec.Provenance.Method = "NetBoxImport" + manufacturer.Spec.Provenance.Source = &SourceReference{ExternalReference: source, SnapshotDigest: "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", MappingRevision: "reviewed-1", ObservedAt: later(-time.Hour)} + if errs := admit(t, "Manufacturer", object(t, manufacturer), nil); len(errs) != 0 { + t.Fatal(errs) + } + for _, mode := range []string{"rebind", "remove", "provenance-mismatch"} { + changed := manufacturer.DeepCopyObject().(*Manufacturer) + changed.Spec.Provenance.RecordedAt = later(time.Hour) + switch mode { + case "rebind": + changed.Spec.SourceIdentity.ID = "2" + changed.Spec.Provenance.Source.ID = "2" + case "remove": + changed.Spec.SourceIdentity = nil + changed.Spec.Provenance.Source = nil + changed.Spec.Provenance.Method = "Manual" + default: + changed.Spec.Provenance.Source.ID = "2" + } + if errs := admit(t, "Manufacturer", object(t, changed), object(t, manufacturer)); len(errs) == 0 { + t.Fatal("accepted imported catalog identity mutation", mode) + } + } +} + +func TestCatalogUpdatesAndDeviceCompatibility(t *testing.T) { + _, model := catalogRecords() + changed := model.DeepCopyObject().(*DeviceType) + changed.Spec.DisplayName = "New human label" + changed.Spec.ComponentTemplates[0].Name = "Renamed template only" + if errs := admit(t, "DeviceType", object(t, changed), object(t, model)); len(errs) == 0 { + t.Fatal("accepted edit without provenance advance") + } + changed.Spec.Provenance.RecordedAt = later(time.Second) + if errs := admit(t, "DeviceType", object(t, changed), object(t, model)); len(errs) != 0 { + t.Fatal(errs) + } + changed.Spec.Model = "different-model" + if errs := admit(t, "DeviceType", object(t, changed), object(t, model)); len(errs) == 0 { + t.Fatal("accepted model identity mutation") + } + for _, baseline := range []Device{syntheticDevice(), reportedDevice()} { + attached := baseline.DeepCopyObject().(*Device) + attached.Spec.DeviceTypeRef = &LocalReference{Name: model.Name} + if errs := admit(t, "Device", object(t, attached), object(t, baseline)); len(errs) == 0 { + t.Fatal("attachment did not require provenance") + } + attached.Spec.Provenance.RecordedAt = later(time.Hour) + if errs := admit(t, "Device", object(t, attached), object(t, baseline)); len(errs) != 0 { + t.Fatal(errs) + } + for _, reference := range []*LocalReference{nil, {Name: "another-model"}} { + rebound := attached.DeepCopyObject().(*Device) + rebound.Spec.DeviceTypeRef = reference + rebound.Spec.Provenance.RecordedAt = later(2 * time.Hour) + if errs := admit(t, "Device", object(t, rebound), object(t, attached)); len(errs) == 0 { + t.Fatal("accepted catalog removal or rebind") + } + } + attached.Spec.DeviceTypeRef = nil + attached.Spec.Provenance = baseline.Spec.Provenance + if !reflect.DeepEqual(object(t, attached.Spec), object(t, baseline.Spec)) { + t.Fatal("catalog attachment changed an observation or physical identity") + } + } +} + +type deniedCatalogReader struct{ client.Reader } + +func (deniedCatalogReader) Get(context.Context, client.ObjectKey, client.Object, ...client.GetOption) error { + return fmt.Errorf("denied secret manufacturer and model") +} + +func TestCatalogResolutionAndDeepCopy(t *testing.T) { + scheme := runtime.NewScheme() + if err := AddToScheme(scheme); err != nil { + t.Fatal(err) + } + manufacturer, model := catalogRecords() + device := syntheticDevice() + device.Spec.DeviceTypeRef = &LocalReference{Name: model.Name} + before := object(t, device) + reader := fake.NewClientBuilder().WithScheme(scheme).WithObjects(manufacturer, model).Build() + resolved, vendor, err := ReadDeviceCatalog(context.Background(), reader, &device) + if err != nil || vendor.Name != manufacturer.Name || resolved.Name != model.Name { + t.Fatal("same-namespace reference failed", err) + } + resolved.Spec.ComponentTemplates[0].Name = "mutated copy" + if model.Spec.ComponentTemplates[0].Name != "Port 1" || !reflect.DeepEqual(before, object(t, device)) { + t.Fatal("resolution mutated source or device") + } + for _, namespace := range []string{"", "another-namespace"} { + other := device.DeepCopyObject().(*Device) + other.Namespace = namespace + if model, vendor, err := ReadDeviceCatalog(context.Background(), reader, other); err == nil || model != nil || vendor != nil { + t.Fatal("resolved across namespace boundary") + } + } + if model, vendor, err := ReadDeviceCatalog(context.Background(), deniedCatalogReader{}, &device); err == nil || err.Error() != "hardware catalog unavailable" || model != nil || vendor != nil { + t.Fatal("denied reference disclosed details") + } + if err := reader.Delete(context.Background(), manufacturer); err != nil { + t.Fatal(err) + } + if model, vendor, err := ReadDeviceCatalog(context.Background(), reader, &device); err == nil || model != nil || vendor != nil { + t.Fatal("dangling reference returned partial catalog") + } + replacement := manufacturer.DeepCopyObject().(*Manufacturer) + replacement.ResourceVersion = "" + replacement.UID = "replacement" + replacement.Spec.CanonicalName = "Replacement Vendor" + if err := reader.Create(context.Background(), replacement); err != nil { + t.Fatal(err) + } + _, vendor, err = ReadDeviceCatalog(context.Background(), reader, &device) + if err != nil || vendor.UID != "replacement" || !reflect.DeepEqual(before, object(t, device)) { + t.Fatal("name reuse must resolve without rewriting device", err) + } +} diff --git a/internal/api/inventory/v1alpha1/crd_test.go b/internal/api/inventory/v1alpha1/crd_test.go index a8c971a7..5f6390dc 100644 --- a/internal/api/inventory/v1alpha1/crd_test.go +++ b/internal/api/inventory/v1alpha1/crd_test.go @@ -55,8 +55,8 @@ func loadCRDs(t *testing.T) map[string]*extensionsv1.CustomResourceDefinition { func TestInventoryCRDContract(t *testing.T) { crds := loadCRDs(t) -if len(crds) != 7 || crds["Site"] == nil || crds["DeviceClaim"] == nil || crds["Device"] == nil { -t.Fatalf("got %d CRDs, want six physical kinds and Site", len(crds)) + if len(crds) != 9 || crds["Manufacturer"] == nil || crds["DeviceType"] == nil || crds["Site"] == nil || crds["DeviceClaim"] == nil || crds["Device"] == nil { + t.Fatalf("got %d CRDs, want six physical kinds, Site and two catalog kinds", len(crds)) } for kind, crd := range crds { if crd.Spec.Group != GroupVersion.Group || crd.Name != crd.Spec.Names.Plural+"."+GroupVersion.Group || crd.Spec.Scope != extensionsv1.NamespaceScoped { diff --git a/internal/api/inventory/v1alpha1/iam_test.go b/internal/api/inventory/v1alpha1/iam_test.go index c7ddb0aa..38fed71f 100644 --- a/internal/api/inventory/v1alpha1/iam_test.go +++ b/internal/api/inventory/v1alpha1/iam_test.go @@ -118,7 +118,7 @@ func TestInventoryRolesSplitReadFromWrite(t *testing.T) { t.Fatalf("missing role %s", name) } var expected []string - for _, resource := range []string{"sites", "deviceclaims", "devices", "facilities", "racks", "cables", "powerfeeds"} { + for _, resource := range []string{"manufacturers", "devicetypes", "sites", "deviceclaims", "devices", "facilities", "racks", "cables", "powerfeeds"} { for _, verb := range verbs { expected = append(expected, GroupVersion.Group+"/"+resource+"."+verb) } diff --git a/internal/api/inventory/v1alpha1/types.go b/internal/api/inventory/v1alpha1/types.go index 5f30c431..0c4bc4f3 100644 --- a/internal/api/inventory/v1alpha1/types.go +++ b/internal/api/inventory/v1alpha1/types.go @@ -101,6 +101,7 @@ type Device struct { } type DeviceSpec struct { + DeviceTypeRef *LocalReference `json:"deviceTypeRef,omitempty"` ReportedPlacement *ReportedPlacement `json:"reportedPlacement,omitempty"` DisplayName string `json:"displayName,omitempty"` ModelShape *ModelShape `json:"modelShape,omitempty"` @@ -180,6 +181,7 @@ type DeviceList struct { } func addKnown(s *runtime.Scheme) error { + s.AddKnownTypes(GroupVersion, &Manufacturer{}, &ManufacturerList{}, &DeviceType{}, &DeviceTypeList{}) s.AddKnownTypes(GroupVersion, &Site{}, &SiteList{}, &DeviceClaim{}, &DeviceClaimList{}, &Device{}, &DeviceList{}, &Facility{}, &FacilityList{}, &Rack{}, &RackList{}, &Cable{}, &CableList{}, &PowerFeed{}, &PowerFeedList{}) metav1.AddToGroupVersion(s, GroupVersion) return nil diff --git a/ui/provider/src/components/adversarial-review.test.tsx b/ui/provider/src/components/adversarial-review.test.tsx index 39d0d611..1d962941 100644 --- a/ui/provider/src/components/adversarial-review.test.tsx +++ b/ui/provider/src/components/adversarial-review.test.tsx @@ -49,13 +49,13 @@ it.each([false, true])('keeps real table mounted on visible focus and refreshes expect(loadingStates).not.toContain(true); }); -it('renders calm denied access with exactly seven list attempts and no permission reviews or writes', async () => { +it('renders calm denied access with exactly nine list attempts and no permission reviews or writes', async () => { const requests = vi.fn(async () => ({ ok: false, status: 403, json: async () => ({ error: 'DO NOT DISPLAY internal authorization diagnostic' }) })); vi.stubGlobal('fetch', requests); const router = createMemoryRouter([{ id: 'layouts/milo.layout', path: '/', loader: () => ({ user: { metadata: { uid: 'denied-staff' } } }), element: , children: [{ index: true, element: }] }]); render(); await screen.findByRole('heading', { name: 'Inventory access needed' }); - expect(requests).toHaveBeenCalledTimes(7); + expect(requests).toHaveBeenCalledTimes(9); for (const [, init] of requests.mock.calls as unknown as [string, RequestInit][]) expect(init.method).toBe('GET'); expect(screen.queryByText(/DO NOT DISPLAY/)).not.toBeInTheDocument(); expect(screen.queryByText(/Create facility/)).not.toBeInTheDocument(); diff --git a/ui/provider/src/components/exact-head-independent.test.tsx b/ui/provider/src/components/exact-head-independent.test.tsx index ddfbc901..c8d76601 100644 --- a/ui/provider/src/components/exact-head-independent.test.tsx +++ b/ui/provider/src/components/exact-head-independent.test.tsx @@ -103,7 +103,7 @@ it.each([false, true].flatMap(strict => [401, 403, 404, 503].flatMap(status => [ await screen.findByRole('button', { name: 'Create facility' }); phase = 'pending'; fireEvent.click(screen.getByRole('button', { name: 'Refresh inventory' })); - await waitFor(() => expect(releases).toHaveLength(7)); + await waitFor(() => expect(releases).toHaveLength(9)); phase = 'denied'; await act(async () => { if (transition === 'focus') { fireEvent(window, new Event('blur')); fireEvent(window, new Event('focus')); } @@ -115,7 +115,7 @@ it.each([false, true].flatMap(strict => [401, 403, 404, 503].flatMap(status => [ expect(screen.getByRole('heading', { name: title })).toBeInTheDocument(); expect(screen.queryByText('Private facility label')).not.toBeInTheDocument(); expect(screen.queryByRole('button', { name: 'Create facility' })).not.toBeInTheDocument(); - expect(freshRequests.length).toBeGreaterThanOrEqual(7); + expect(freshRequests.length).toBeGreaterThanOrEqual(9); expect(freshRequests.every(method => method === 'GET')).toBe(true); router.dispose(); }); diff --git a/ui/provider/src/components/hardware-catalog.test.tsx b/ui/provider/src/components/hardware-catalog.test.tsx new file mode 100644 index 00000000..d595acc0 --- /dev/null +++ b/ui/provider/src/components/hardware-catalog.test.tsx @@ -0,0 +1,109 @@ +import { fireEvent, render, screen } from '@testing-library/react'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { MemoryRouter } from 'react-router'; +import { describe, expect, it, vi } from 'vitest'; +import type { PhysicalRecord } from '../../../shared/fleet-api'; +import { PhysicalInventory } from './physical-inventory'; +import { toInventory, type Inventory } from '../inventory'; +import { deviceCatalog, deviceModelLabel } from '../lib/hardware-catalog'; +import { fixturePhysicalDevices } from '../lib/fixtures'; +import { InventoryHardwareFields } from './inventory-hardware-fields'; +import type { InventoryFormValues } from '../lib/inventory-management'; + +function fixture() { + const device = structuredClone(fixturePhysicalDevices[0]); + device.spec.deviceTypeRef = { name: 'private-model-key' }; + const manufacturer: PhysicalRecord = { kind: 'Manufacturer', metadata: { name: 'private-vendor-key', namespace: device.metadata.namespace }, spec: { displayName: 'Private vendor label', canonicalName: 'Private canonical vendor', aliases: ['Private old vendor'], provenance: device.spec.provenance } }; + const model: PhysicalRecord = { kind: 'DeviceType', metadata: { name: 'private-model-key', namespace: device.metadata.namespace }, spec: { displayName: 'Private model label', model: 'private-normalized-model', manufacturerRef: { name: manufacturer.metadata.name }, modelShape: { heightUnits: 8 }, componentTemplates: [{ id: 'template-only', name: 'Template-only port', type: 'NetworkPort' }], provenance: device.spec.provenance } }; + return { device, manufacturer, model, inventory: toInventory([], [device], [manufacturer, model]) }; +} + +function show(inventory: Inventory, query = '?kind=Device') { + return render(); +} + +describe('hardware catalog readers', () => { + it('selects only readable same-namespace records without populating observed hardware', () => { + const { manufacturer, model } = fixture(); + manufacturer.metadata = { ...manufacturer.metadata, uid: 'vendor-uid', resourceVersion: '1' }; + model.metadata = { ...model.metadata, uid: 'model-uid', resourceVersion: '2' }; + const other = { ...model, metadata: { ...model.metadata, uid: 'other-uid', namespace: 'another' }, spec: { ...model.spec, displayName: 'Other namespace model' } }; + const values: InventoryFormValues = { name: 'new-device', namespace: 'default', displayName: 'New hardware', recordedBy: 'synthetic', reference: '', height: '', facility: '', manufacturer: 'Observed vendor', model: 'Observed model', components: [] }; + const change = vi.fn(); + const form = (current: InventoryFormValues, catalog: PhysicalRecord[]) => ; + const result = render(form(values, [manufacturer, model, other])); + expect(screen.queryByRole('option', { name: /Other namespace/ })).not.toBeInTheDocument(); + fireEvent.change(screen.getByLabelText('Shared catalog model (optional)'), { target: { value: 'model-uid' } }); + const selected = change.mock.calls[0][0]; + expect(selected.catalog).toEqual({ namespace: 'default', name: model.metadata.name, uid: 'model-uid', resourceVersion: '2', manufacturer: { name: manufacturer.metadata.name, uid: 'vendor-uid', resourceVersion: '1' } }); + expect(selected.model).toBe(values.model); + expect(selected.manufacturer).toBe(values.manufacturer); + expect(selected.components).toEqual([]); + result.rerender(form(selected, [])); + expect(screen.getByRole('option', { name: /Selected catalog unavailable/ })).toBeInTheDocument(); + expect(result.container.textContent).not.toMatch(/Private|private-model|private-vendor/); + }); + + it('prefers available same-namespace catalog without mutating source observations or instances', () => { + const { device, model, inventory } = fixture(); + const before = structuredClone(device); + expect(deviceModelLabel(device, inventory)).toBe('Private canonical vendor Private model label'); + model.spec.displayName = 'Changed model label'; + model.spec.componentTemplates!.push({ id: 'new-port', name: 'New reference port', type: 'NetworkPort' }); + expect(deviceModelLabel(device, inventory)).toContain('Changed model label'); + expect(device).toEqual(before); + expect(device.spec.components).not.toContainEqual(expect.objectContaining({ id: 'new-port' })); + }); + + it('keeps legacy source fallback through missing, cross-namespace and recreated references', () => { + const { device, manufacturer, model, inventory } = fixture(); + inventory.physical = []; + expect(deviceModelLabel(device, inventory)).toContain(device.spec.identity.model); + inventory.physical = [manufacturer, { ...model, metadata: { ...model.metadata, namespace: 'another' } }]; + expect(deviceCatalog(device, inventory)).toBeUndefined(); + inventory.physical = [manufacturer, { ...model, metadata: { ...model.metadata, uid: 'recreated' } }]; + expect(deviceCatalog(device, inventory)?.model.metadata.uid).toBe('recreated'); + inventory.physical[1].metadata.deletionTimestamp = '2026-11-21T00:00:00Z'; + expect(deviceCatalog(device, inventory)).toBeUndefined(); + }); + + it.each(['Manufacturer', 'DeviceType'] as const)('redacts denied %s references from search, filters and details', kind => { + const { device, inventory } = fixture(); + inventory.issues = { [kind]: { status: 403 } }; + const result = show(inventory); + expect(result.container.textContent).not.toMatch(/Private|private-model|private-vendor|private-normalized/); + fireEvent.change(screen.getByRole('searchbox'), { target: { value: 'Private model label' } }); + expect(screen.queryByRole('link', { name: device.spec.displayName })).not.toBeInTheDocument(); + }); + + it('hides stale catalog labels immediately on permission change', () => { + const { device, inventory } = fixture(); + const client = new QueryClient(); + const view = (data: Inventory) => ; + const result = render(view(inventory)); + expect(result.container.textContent).toContain('Private model label'); + result.rerender(view({ ...inventory, issues: { Manufacturer: { status: 403 } } })); + expect(result.container.textContent).not.toMatch(/Private|private-model|private-vendor/); + expect(screen.getByText('Catalog unavailable · showing source observation')).toBeInTheDocument(); + }); + + it('browses aliases and nominal templates without inventing installed components', () => { + const { inventory, model } = fixture(); + show(inventory, '?kind=Manufacturer'); + fireEvent.change(screen.getByRole('searchbox'), { target: { value: 'private old vendor' } }); + expect(screen.getByRole('link', { name: 'Private vendor label' })).toBeInTheDocument(); + fireEvent.click(screen.getByRole('link', { name: /Device types/ })); + fireEvent.click(screen.getByRole('link', { name: model.spec.displayName })); + expect(screen.getByText(/Template-only port/)).toBeInTheDocument(); + expect(screen.getByText(/not installed|No installed assets/)).toBeInTheDocument(); + expect(screen.queryByRole('button', { name: /create|edit|delete|apply|select/i })).not.toBeInTheDocument(); + }); + + it('never echoes a denied catalog deep link', () => { + const { inventory } = fixture(); + inventory.issues = { Manufacturer: { status: 403 } }; + const result = show(inventory, '?kind=DeviceType&namespace=default&record=private-model-key'); + expect(screen.getByText('Inventory access needed')).toBeInTheDocument(); + expect(result.container.textContent).not.toMatch(/Private|private-model|private-vendor/); + }); +}); diff --git a/ui/provider/src/components/inventory-hardware-fields.tsx b/ui/provider/src/components/inventory-hardware-fields.tsx index 8e37e17c..6c0d65d6 100644 --- a/ui/provider/src/components/inventory-hardware-fields.tsx +++ b/ui/provider/src/components/inventory-hardware-fields.tsx @@ -2,8 +2,13 @@ import type { Device, DeviceClaim, PhysicalComponent, PhysicalRecord } from '../ import { cableMedia, componentTypes, isTermination, type ReferencedEndpoint } from '../lib/inventory-hardware'; import type { InventoryFormValues } from '../lib/inventory-management'; -export function InventoryHardwareFields({ kind, values, onChange, namespace, claims, devices, feeds, locations }: { kind: 'Device' | 'Cable' | 'DeviceClaim'; values: InventoryFormValues; onChange: (values: InventoryFormValues) => void; namespace: string; claims: DeviceClaim[]; devices: Device[]; feeds: PhysicalRecord[]; locations: PhysicalRecord[] }) { +export function InventoryHardwareFields({ kind, values, onChange, namespace, claims, devices, feeds, locations, catalog = [] }: { kind: 'Device' | 'Cable' | 'DeviceClaim'; values: InventoryFormValues; onChange: (values: InventoryFormValues) => void; namespace: string; claims: DeviceClaim[]; devices: Device[]; feeds: PhysicalRecord[]; locations: PhysicalRecord[]; catalog?: PhysicalRecord[] }) { const field = (name: keyof InventoryFormValues, value: unknown) => onChange({ ...values, [name]: value }); + const readable = catalog.filter(record => record.metadata.namespace === namespace && record.metadata.uid && record.metadata.resourceVersion && !record.metadata.deletionTimestamp); + const models = readable.filter(record => record.kind === 'DeviceType').flatMap(model => { + const manufacturer = readable.find(record => record.kind === 'Manufacturer' && record.metadata.name === model.spec.manufacturerRef?.name); + return manufacturer ? [{ model, manufacturer }] : []; + }); if (kind === 'DeviceClaim') return
      New installation plan
      {([['manufacturer', 'Expected manufacturer'], ['model', 'Expected model'], ['serial', 'Expected serial (optional)']] as const).map(([name, label]) => )}
      @@ -11,6 +16,11 @@ export function InventoryHardwareFields({ kind, values, onChange, namespace, cla
      ; if (kind === 'Device') return <>
      Installation & identity + +

      Only readable same-namespace models are offered. Assignment is immutable after creation. Record observed identity below; selection never fills source observations, components or placement.

      Identity and installation binding cannot be changed later. Existing registrations are kept; this does not replace hardware or identify the active device. Legacy slot bindings are not offered.

      {([['manufacturer', 'Manufacturer'], ['model', 'Model'], ['serial', 'Serial number'], ['systemUUID', 'System UUID'], ['assetTag', 'Asset tag']] as const).map(([name, label]) => )}
      diff --git a/ui/provider/src/components/inventory-management.tsx b/ui/provider/src/components/inventory-management.tsx index 2c2bc5b6..135caf60 100644 --- a/ui/provider/src/components/inventory-management.tsx +++ b/ui/provider/src/components/inventory-management.tsx @@ -15,7 +15,7 @@ export function InventoryManagement(props: ComponentProps : null; } -function InventoryManagementForm({ kind, record, facilities: sourceFacilities, claims: sourceClaims = [], devices: sourceDevices = [], feeds: sourceFeeds = [], racks: sourceRacks = [], compact = false, issues: sourceIssues }: { kind: ManagedKind; record?: ManagedRecord; facilities: PhysicalRecord[]; claims?: DeviceClaim[]; devices?: Device[]; feeds?: PhysicalRecord[]; racks?: PhysicalRecord[]; compact?: boolean; issues?: Inventory['issues'] }) { +function InventoryManagementForm({ kind, record, facilities: sourceFacilities, claims: sourceClaims = [], devices: sourceDevices = [], feeds: sourceFeeds = [], racks: sourceRacks = [], catalog: sourceCatalog = [], compact = false, issues: sourceIssues }: { kind: ManagedKind; record?: ManagedRecord; facilities: PhysicalRecord[]; claims?: DeviceClaim[]; devices?: Device[]; feeds?: PhysicalRecord[]; racks?: PhysicalRecord[]; catalog?: PhysicalRecord[]; compact?: boolean; issues?: Inventory['issues'] }) { const client = useQueryClient(); const onReadFailure = useContext(InventoryReadAccessContext); const [readIssues, setReadIssues] = useState({}); @@ -25,6 +25,7 @@ function InventoryManagementForm({ kind, record, facilities: sourceFacilities, c const devices = issues.Device ? [] : sourceDevices; const feeds = issues.PowerFeed ? [] : sourceFeeds; const racks = issues.Rack ? [] : sourceRacks; + const catalog = issues.Manufacturer || issues.DeviceType ? [] : sourceCatalog; const sessionScope = useContext(InventoryOperationContext); const scope = useRef(new InventoryOperationScope()); useLayoutEffect(() => { @@ -58,6 +59,10 @@ function InventoryManagementForm({ kind, record, facilities: sourceFacilities, c async function save(event: FormEvent) { event.preventDefault(); if (!allowed || pending || blocked) return; + if (!record && values.catalog && (issues.DeviceType || issues.Manufacturer || !catalog.some(item => item.kind === 'DeviceType' && item.metadata.uid === values.catalog?.uid && item.metadata.namespace === namespace))) { + setMessage('Selected catalog unavailable. Clear the selection or refresh before registration.'); + return; + } setPending(true); setMessage(''); const operation = scope.current.begin(sessionScope); try { @@ -77,6 +82,7 @@ function InventoryManagementForm({ kind, record, facilities: sourceFacilities, c setValues(previous => ({ ...previous, facility: denied?.Facility ? '' : previous.facility, claim: denied?.DeviceClaim ? undefined : previous.claim, + catalog: denied?.DeviceType || denied?.Manufacturer ? undefined : previous.catalog, planLocation: previous.planLocation && denied?.[previous.planLocation.kind] ? undefined : previous.planLocation, cableLanes: previous.cableLanes?.map(lane => ({ ...lane, a: lane.a && denied?.[lane.a.kind] ? undefined : lane.a, @@ -121,7 +127,7 @@ function InventoryManagementForm({ kind, record, facilities: sourceFacilities, c

      {record ? 'Only the display name and recording details change. Identity, placement, geometry, connections, and history remain untouched.' : 'Create a physical record only. This does not verify equipment, reserve space, or provision hardware.'}

      {!record && } - {!record && (kind === 'Device' || kind === 'Cable' || kind === 'DeviceClaim') && } + {!record && (kind === 'Device' || kind === 'Cable' || kind === 'DeviceClaim') && } {!record && kind === 'Cable' && (issues?.Device || issues?.PowerFeed) &&

      Some endpoint records are unavailable. Only readable equipment and power feeds are offered; missing choices do not mean those records are absent.

      } {!record && kind === 'DeviceClaim' && (issues?.Facility || issues?.Rack) &&

      Some location records are unavailable. Only readable facilities and racks are offered; missing choices do not mean those records are absent.

      } {!record && kind === 'Rack' && <> diff --git a/ui/provider/src/components/physical-inventory.test.tsx b/ui/provider/src/components/physical-inventory.test.tsx index d140c015..1a81a724 100644 --- a/ui/provider/src/components/physical-inventory.test.tsx +++ b/ui/provider/src/components/physical-inventory.test.tsx @@ -14,7 +14,7 @@ function browse(query = '', data = inventory) { describe('hardware directory', () => { it('does not turn no-read permission into empty inventory or zero counts', () => { - browse('', { ...inventory, issues: { Site: { status: 403 }, Device: { status: 403 }, DeviceClaim: { status: 403 }, Facility: { status: 403 }, Rack: { status: 403 }, Cable: { status: 403 }, PowerFeed: { status: 403 } } }); + browse('', { ...inventory, issues: { Manufacturer: { status: 403 }, DeviceType: { status: 403 }, Site: { status: 403 }, Device: { status: 403 }, DeviceClaim: { status: 403 }, Facility: { status: 403 }, Rack: { status: 403 }, Cable: { status: 403 }, PowerFeed: { status: 403 } } }); expect(screen.getByRole('heading', { name: 'Inventory access needed' })).toBeInTheDocument(); expect(screen.queryByText('No devices recorded')).not.toBeInTheDocument(); expect(screen.queryByText('Example compute server')).not.toBeInTheDocument(); diff --git a/ui/provider/src/components/physical-inventory.tsx b/ui/provider/src/components/physical-inventory.tsx index 7f0aa5de..61a13937 100644 --- a/ui/provider/src/components/physical-inventory.tsx +++ b/ui/provider/src/components/physical-inventory.tsx @@ -20,8 +20,9 @@ import { InventoryReadAccessContext, readFailureIssues, redactInventory } from ' import { FacilityOverview, RackOverview, inventoryHref as href } from './inventory-location'; import { devicePlacement, placementFacility, reportedPlacementLabel } from '../lib/device-placement'; import { facilityIdentifiers, facilitySites, siteFacilities } from '../lib/site-membership'; +import { deviceCatalog, deviceModelLabel } from '../lib/hardware-catalog'; -type Kind = 'Site' | 'Device' | 'Facility' | 'Rack' | 'DeviceClaim' | 'Cable' | 'PowerFeed'; +type Kind = 'Site' | 'Device' | 'Facility' | 'Rack' | 'DeviceClaim' | 'Cable' | 'PowerFeed' | 'Manufacturer' | 'DeviceType'; type RecordEntry = { kind: Kind; record: RawDevice | RawDeviceClaim | PhysicalRecord }; const sections = [ { @@ -66,6 +67,8 @@ const sections = [ icon: Zap, description: 'Supply ratings, terminations, and upstream sources.', }, + { kind: 'Manufacturer', title: 'Manufacturers', icon: Building2, description: 'Shared canonical names and descriptive aliases. Aliases never merge identities.' }, + { kind: 'DeviceType', title: 'Device types', icon: Server, description: 'Reference-only model shapes and component templates, not installed equipment or occupancy.' }, ] as const; export { endpointLabel } from '../inventory'; @@ -218,11 +221,13 @@ export function PhysicalInventory({ inventory: source, onRetry }: { inventory: I return 'Not recorded'; }; const summary = (entry: RecordEntry): string => { - if (entry.kind === 'Device') return modelLabel((entry.record as RawDevice).spec.identity); + if (entry.kind === 'Device') return deviceModelLabel(entry.record as RawDevice, inventory); if (entry.kind === 'DeviceClaim') return modelLabel((entry.record as RawDeviceClaim).spec.expectedIdentity); const record = entry.record as PhysicalRecord; if (entry.kind === 'Site') return `Operational Site · ${record.spec.code}`; + if (entry.kind === 'Manufacturer') return [record.spec.canonicalName, ...(record.spec.aliases ?? [])].join(' · '); + if (entry.kind === 'DeviceType') return `Model key: ${record.spec.model} · reference template`; if (entry.kind === 'Facility') return facilityIdentifiers(record); if (entry.kind === 'Rack') return record.spec.heightUnits ? `${record.spec.heightUnits}U rack` : 'Height not recorded'; @@ -248,7 +253,7 @@ export function PhysicalInventory({ inventory: source, onRetry }: { inventory: I const facilityName = claim?.spec.placement.facilityRef?.name ?? (entry.record as PhysicalRecord).spec.facilityRef?.name ?? rack?.spec.facilityRef?.name; return facilityName ? slotKey(entry.record.metadata.namespace, facilityName) : ''; }; - const modelKey = (entry: RecordEntry) => entry.kind === 'Device' ? (entry.record as RawDevice).spec.identity.model : entry.kind === 'Cable' ? (entry.record as PhysicalRecord).spec.medium ?? '' : ''; + const modelKey = (entry: RecordEntry) => entry.kind === 'Device' ? deviceCatalog(entry.record as RawDevice, inventory)?.model.spec.model ?? (entry.record as RawDevice).spec.identity.model : entry.kind === 'Cable' ? (entry.record as PhysicalRecord).spec.medium ?? '' : ''; const filterOptions = [...new Set(records.map(modelKey).filter(Boolean))].sort(); const searchText = (entry: RecordEntry) => { const device = entry.kind === 'Device' ? entry.record as RawDevice : undefined; @@ -296,6 +301,7 @@ export function PhysicalInventory({ inventory: source, onRetry }: { inventory: I const namespace = record.metadata.namespace; const provenance = record.spec.provenance; const device = kind === 'Device' ? (record as RawDevice) : undefined; + const catalog = device && deviceCatalog(device, inventory); const claim = kind === 'DeviceClaim' ? (record as RawDeviceClaim) : undefined; const physical = !device && !claim ? (record as PhysicalRecord) : undefined; const slot = device @@ -352,6 +358,17 @@ export function PhysicalInventory({ inventory: source, onRetry }: { inventory: I {kind === 'Facility' && } {kind === 'Rack' && }
      + {kind === 'Manufacturer' && <> + {physical?.spec.canonicalName} + {physical?.spec.aliases?.join(' · ')} + } + {kind === 'DeviceType' && <> + {physical?.spec.manufacturerRef && reference('Manufacturer', namespace, physical.spec.manufacturerRef.name)} + {physical?.spec.model} + {physical?.spec.modelShape ? `${physical.spec.modelShape.heightUnits ?? 'Unknown'}U · ${physical.spec.modelShape.fullDepth === undefined ? 'Depth unknown' : physical.spec.modelShape.fullDepth ? 'Full depth' : 'Partial depth'}` : 'Unknown'} + {physical?.spec.componentTemplates?.map(template =>
      {template.name} · {template.type} · {template.connector ?? 'Connector unknown'} · {template.positions ?? 1} position(s)
      ) ?? 'Not recorded'}
      + Reference defaults only. No installed assets, measured geometry, observed occupancy, or automatic materialization. + } {kind === 'Site' && <> {(record as PhysicalRecord).spec.code} {siteFacilities(record as PhysicalRecord, inventory).map((membership, index) =>
      {membership.facility ? <>{reference('Facility', namespace, membership.facility.metadata.name)} · {facilityIdentifiers(membership.facility)} : membership.state}
      )}{!inventory.issues?.Facility && !(record as PhysicalRecord).spec.facilityRefs?.length && 'Unmapped · no Facilities recorded'}
      @@ -367,7 +384,10 @@ export function PhysicalInventory({ inventory: source, onRetry }: { inventory: I {namespace || 'Not recorded'} {device && ( <> - {modelLabel(device.spec.identity)} + {deviceModelLabel(device, inventory)} + {modelLabel(device.spec.identity)} + {catalog ? reference('DeviceType', namespace, catalog.model.metadata.name) : device.spec.deviceTypeRef ? 'Catalog unavailable · showing source observation' : 'Not assigned · showing source observation'} + {catalog?.model.spec.modelShape?.heightUnits === undefined ? 'Unknown' : `${catalog.model.spec.modelShape.heightUnits}U · not measured or used for occupancy`} {device.spec.identity.serial} {device.spec.assetTag} {device.spec.identity.systemUUID} @@ -379,7 +399,7 @@ export function PhysicalInventory({ inventory: source, onRetry }: { inventory: I {device.spec.reportedPlacement?.facilityRef && {reference('Facility', namespace, device.spec.reportedPlacement.facilityRef.name)}} {device.spec.reportedPlacement && Revision {device.spec.reportedPlacement.revision} · {device.spec.reportedPlacement.observedAt} · {device.spec.reportedPlacement.method === 'Manual' ? 'Manual observation/correction' : 'NetBox source report'}, not physically verified{device.spec.reportedPlacement.reason && ` · Reason: ${device.spec.reportedPlacement.reason}`}{device.spec.reportedPlacement.reference && ` · Evidence: ${device.spec.reportedPlacement.reference}`}} Recordkeeping is not a physical move or a capacity reservation. - + {device.spec.modelShape ? `${device.spec.modelShape.heightUnits ?? 'Unknown'}U · ${device.spec.modelShape.fullDepth === undefined ? 'Depth not recorded' : device.spec.modelShape.fullDepth ? 'Full depth' : 'Partial depth'}` : undefined} @@ -627,6 +647,7 @@ export function PhysicalInventory({ inventory: source, onRetry }: { inventory: I claims={inventory.slots.map(slot => slot.claim)} devices={entries.filter(entry => entry.kind === 'Device').map(entry => entry.record as RawDevice)} feeds={inventory.physical.filter(record => record.kind === 'PowerFeed')} + catalog={inventory.physical.filter(record => record.kind === 'Manufacturer' || record.kind === 'DeviceType')} /> : null; const placementEditor = selected?.kind === 'Device' && !inventory.issues?.Device ? : null; if (Object.values(inventory.issues ?? {}).some(issue => issue?.status === 401)) return ; diff --git a/ui/provider/src/inventory.ts b/ui/provider/src/inventory.ts index 871b151b..5ad60d20 100644 --- a/ui/provider/src/inventory.ts +++ b/ui/provider/src/inventory.ts @@ -7,8 +7,9 @@ import type { CableEndpoint, Device as RawDevice, DeviceClaim as RawDeviceClaim, export type { RawDevice, RawDeviceClaim }; export type RawDeviceList = List; export type RawDeviceClaimList = List; -export type InventoryKind = 'Site' | 'Device' | 'DeviceClaim' | 'Facility' | 'Rack' | 'Cable' | 'PowerFeed'; +export type InventoryKind = 'Site' | 'Device' | 'DeviceClaim' | 'Facility' | 'Rack' | 'Cable' | 'PowerFeed' | 'Manufacturer' | 'DeviceType'; export const inventoryResources: Record = { + Manufacturer: 'manufacturers', DeviceType: 'devicetypes', Site: 'sites', Device: 'devices', DeviceClaim: 'deviceclaims', Facility: 'facilities', Rack: 'racks', Cable: 'cables', PowerFeed: 'powerfeeds', }; diff --git a/ui/provider/src/lib/hardware-catalog.ts b/ui/provider/src/lib/hardware-catalog.ts new file mode 100644 index 00000000..2119f692 --- /dev/null +++ b/ui/provider/src/lib/hardware-catalog.ts @@ -0,0 +1,14 @@ +import type { Device, PhysicalRecord } from '../../../shared/fleet-api'; +import { modelLabel, type Inventory } from '../inventory'; + +export function deviceCatalog(device: Device, inventory: Inventory): { model: PhysicalRecord; manufacturer: PhysicalRecord } | undefined { + if (!device.metadata.namespace || !device.spec.deviceTypeRef || inventory.issues?.DeviceType || inventory.issues?.Manufacturer) return; + const model = inventory.physical.find(record => record.kind === 'DeviceType' && record.metadata.namespace === device.metadata.namespace && record.metadata.name === device.spec.deviceTypeRef?.name && !record.metadata.deletionTimestamp); + const manufacturer = model && inventory.physical.find(record => record.kind === 'Manufacturer' && record.metadata.namespace === device.metadata.namespace && record.metadata.name === model.spec.manufacturerRef?.name && !record.metadata.deletionTimestamp); + if (model && manufacturer) return { model, manufacturer }; +} + +export function deviceModelLabel(device: Device, inventory: Inventory): string { + const catalog = deviceCatalog(device, inventory); + return catalog ? `${catalog.manufacturer.spec.canonicalName} ${catalog.model.spec.displayName}` : modelLabel(device.spec.identity); +} diff --git a/ui/provider/src/lib/inventory-api.test.ts b/ui/provider/src/lib/inventory-api.test.ts index 2dd0be52..409475f2 100644 --- a/ui/provider/src/lib/inventory-api.test.ts +++ b/ui/provider/src/lib/inventory-api.test.ts @@ -29,14 +29,14 @@ describe('physical inventory reads', () => { await expect(fetchInventoryCollection('racks')).rejects.toThrow('completeness Unknown'); }); - it('reads six physical collections and Sites and retains per-kind denial without fake inventory', async () => { + it('reads six physical collections, Sites and two catalog collections and retains per-kind denial', async () => { const fetch = vi.fn().mockResolvedValue(response({ items: [] })); vi.stubGlobal('fetch', fetch); expect((await fetchInventory()).physical).toEqual([]); - expect(fetch).toHaveBeenCalledTimes(7); + expect(fetch).toHaveBeenCalledTimes(9); fetch.mockResolvedValue(response(undefined, 403)); const inventory = await fetchInventory(); - expect(Object.values(inventory.issues ?? {})).toEqual(Array.from({ length: 7 }, () => ({ status: 403 }))); + expect(Object.values(inventory.issues ?? {})).toEqual(Array.from({ length: 9 }, () => ({ status: 403 }))); expect(inventory.physical).toEqual([]); }); diff --git a/ui/provider/src/lib/inventory-hardware.test.ts b/ui/provider/src/lib/inventory-hardware.test.ts index 980756ab..5d0d30a3 100644 --- a/ui/provider/src/lib/inventory-hardware.test.ts +++ b/ui/provider/src/lib/inventory-hardware.test.ts @@ -14,6 +14,58 @@ const device = { ...hardwarePayload('Device', values, common), metadata: { name: const response = (data: unknown, status = 200) => ({ ok: status < 400, status, json: async () => ({ data }) }); afterEach(() => vi.unstubAllGlobals()); +describe('catalog selection for new devices', () => { + const selection = { namespace: 'default', name: 'model-stable', uid: 'model-uid', resourceVersion: '3', manufacturer: { name: 'vendor-stable', uid: 'vendor-uid', resourceVersion: '4' } }; + const model = { metadata: { namespace: 'default', name: 'model-stable', uid: 'model-uid', resourceVersion: '3' }, spec: { manufacturerRef: { name: 'vendor-stable' }, componentTemplates: [{ id: 'not-installed' }], modelShape: { heightUnits: 8 } } }; + const manufacturer = { metadata: { namespace: 'default', name: 'vendor-stable', uid: 'vendor-uid', resourceVersion: '4' } }; + + it('rechecks catalog identities and revisions, sending only name references under strict validation', async () => { + const requests = vi.fn().mockResolvedValueOnce(response({ status: { allowed: true } })).mockResolvedValueOnce(response(claim)).mockResolvedValueOnce(response(model)).mockResolvedValueOnce(response(manufacturer)).mockResolvedValueOnce(response({ metadata: { uid: 'new-device' } })); + vi.stubGlobal('fetch', requests); + await createInventoryRecord('Device', { ...values, catalog: selection }, new InventoryOperationScope().begin()); + const payload = JSON.parse(requests.mock.calls[4][1].body); + expect(requests.mock.calls[4][0]).toContain('fieldValidation=Strict'); + expect(payload.spec.deviceTypeRef).toEqual({ name: 'model-stable' }); + expect(payload.spec.identity.model).toBe(values.model); + expect(payload.spec.components).toEqual(values.components); + expect(payload.spec.modelShape).toBeUndefined(); + expect(payload.spec.reportedPlacement).toBeUndefined(); + expect(JSON.stringify(payload.spec)).not.toContain('uid'); + }); + + it.each(['uid', 'resourceVersion', 'namespace', 'name', 'deletionTimestamp'])('rejects changed catalog %s before registration', async field => { + const changed = { ...model, metadata: { ...model.metadata, [field]: 'changed' } }; + const requests = vi.fn().mockResolvedValueOnce(response({ status: { allowed: true } })).mockResolvedValueOnce(response(claim)).mockResolvedValueOnce(response(changed)); + vi.stubGlobal('fetch', requests); + await expect(createInventoryRecord('Device', { ...values, catalog: selection }, new InventoryOperationScope().begin())).rejects.toMatchObject({ status: 409 }); + expect(requests).toHaveBeenCalledTimes(3); + }); + + it.each([401, 403, 404, 503])('does not register after catalog denial/unavailability %s', async status => { + for (const target of ['model', 'manufacturer']) { + const requests = vi.fn().mockResolvedValueOnce(response({ status: { allowed: true } })).mockResolvedValueOnce(response(claim)); + if (target === 'manufacturer') requests.mockResolvedValueOnce(response(model)); + requests.mockResolvedValueOnce(response(undefined, status)); + vi.stubGlobal('fetch', requests); + await expect(createInventoryRecord('Device', { ...values, catalog: selection }, new InventoryOperationScope().begin())).rejects.toMatchObject({ status }); + expect(requests).toHaveBeenCalledTimes(target === 'model' ? 3 : 4); + } + }); + + it('fences a late catalog read after session revocation', async () => { + const scope = new InventoryOperationScope(); + let release: ((value: unknown) => void) | undefined; + const requests = vi.fn().mockResolvedValueOnce(response({ status: { allowed: true } })).mockResolvedValueOnce(response(claim)).mockImplementationOnce(() => new Promise(resolve => { release = resolve; })); + vi.stubGlobal('fetch', requests); + const outcome = createInventoryRecord('Device', { ...values, catalog: selection }, scope.begin()).catch(error => error); + await waitFor(() => expect(release).toBeDefined()); + scope.invalidate(); + release!(response(model)); + expect(await outcome).toMatchObject({ dispatched: false }); + expect(requests).toHaveBeenCalledTimes(3); + }); +}); + describe('physical record creation', () => { it.each(['Facility', 'Rack'] as const)('creates a new observational plan at a %s without inventing geometry', async kind => { const planValues = { ...values, planLocation: { kind, name: 'location', uid: 'location-uid', resourceVersion: '1' } }; diff --git a/ui/provider/src/lib/inventory-hardware.ts b/ui/provider/src/lib/inventory-hardware.ts index 97232a4d..441850b1 100644 --- a/ui/provider/src/lib/inventory-hardware.ts +++ b/ui/provider/src/lib/inventory-hardware.ts @@ -13,6 +13,7 @@ export interface ReferencedEndpoint { position: number; } export interface HardwareFields { + catalog?: { namespace: string; name: string; uid: string; resourceVersion: string; manufacturer: { name: string; uid: string; resourceVersion: string } }; planLocation?: { kind: 'Facility' | 'Rack'; name: string; uid: string; resourceVersion: string }; claim?: { name: string; uid: string; resourceVersion: string }; manufacturer?: string; @@ -37,12 +38,13 @@ export function hardwarePayload(kind: 'Device' | 'Cable' | 'DeviceClaim', values return { ...common, kind, spec: { displayName: values.displayName.trim(), provenance: common.spec.provenance, lifecycle: 'Installation', expectedIdentity: { model: values.model.trim(), ...(values.manufacturer?.trim() && { manufacturer: values.manufacturer.trim() }), ...(values.serial?.trim() && { serial: values.serial.trim() }) }, placement: location.kind === 'Facility' ? { scope: 'Facility', facilityRef: { name: location.name } } : { scope: 'RackMembership', rackRef: { name: location.name } } } }; } if (kind === 'Device') { + if (values.catalog && (values.catalog.namespace !== values.namespace || !values.catalog.uid || !values.catalog.resourceVersion || !values.catalog.manufacturer?.uid || !values.catalog.manufacturer.resourceVersion || !namePattern.test(values.catalog.name) || !namePattern.test(values.catalog.manufacturer.name))) throw new ApiError(422, 'Choose a readable catalog model in this namespace.'); if (!values.claim?.uid || !values.claim.resourceVersion || !namePattern.test(values.claim.name) || !values.model?.trim() || (!values.serial?.trim() && !values.systemUUID)) throw new ApiError(422, 'Choose an installation plan and enter a model and a serial or system UUID.'); if (values.systemUUID && !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(values.systemUUID)) throw new ApiError(422, 'Enter a valid lowercase system UUID.'); if ([values.manufacturer, values.model, values.serial, values.assetTag].some(value => (value?.length ?? 0) > 253)) throw new ApiError(422, 'Hardware fields must be at most 253 characters.'); const components = values.components ?? []; if (components.length > 256 || new Set(components.map(component => component.id)).size !== components.length || components.some(component => !component.id.trim() || component.id.length > 63 || !component.name.trim() || component.name.length > 253 || !componentTypes.includes(component.type) || (component.connector?.length ?? 0) > 253 || !Number.isInteger(component.positions) || component.positions! < 1 || component.positions! > 256)) throw new ApiError(422, 'Review component IDs, names, types, and positions.'); - return { ...common, kind, spec: { displayName: values.displayName.trim(), provenance: common.spec.provenance, claimRef: { name: values.claim.name }, identity: { model: values.model.trim(), ...(values.manufacturer?.trim() && { manufacturer: values.manufacturer.trim() }), ...(values.serial?.trim() && { serial: values.serial.trim() }), ...(values.systemUUID && { systemUUID: values.systemUUID }) }, ...(values.assetTag?.trim() && { assetTag: values.assetTag.trim() }), topologyAuthority: 'Cable', components } }; + return { ...common, kind, spec: { displayName: values.displayName.trim(), provenance: common.spec.provenance, claimRef: { name: values.claim.name }, ...(values.catalog && { deviceTypeRef: { name: values.catalog.name } }), identity: { model: values.model.trim(), ...(values.manufacturer?.trim() && { manufacturer: values.manufacturer.trim() }), ...(values.serial?.trim() && { serial: values.serial.trim() }), ...(values.systemUUID && { systemUUID: values.systemUUID }) }, ...(values.assetTag?.trim() && { assetTag: values.assetTag.trim() }), topologyAuthority: 'Cable', components } }; } const lanes = values.cableLanes ?? []; if (!cableMedia.includes(values.medium ?? '') || !lanes.length || lanes.length > 64 || new Set(lanes.map(lane => lane.id)).size !== lanes.length) throw new ApiError(422, 'Choose a medium and one or more uniquely named lanes.'); @@ -68,6 +70,15 @@ export async function validateHardwareReferences(kind: 'Device' | 'Cable' | 'Dev const claim = await readInventoryReference('DeviceClaim', values.namespace, snapshot.name, operation); operation.assertCurrent(); if (!claim || claim.metadata.uid !== snapshot.uid || claim.metadata.resourceVersion !== snapshot.resourceVersion || claim.metadata.deletionTimestamp || claim.spec.lifecycle !== 'Installation') throw new ApiError(409, 'The installation plan changed or is a legacy binding. Review it before registration.'); + if (values.catalog) { + const selected = values.catalog; + const model = await readInventoryReference('DeviceType', values.namespace, selected.name, operation); + operation.assertCurrent(); + if (selected.namespace !== values.namespace || model.metadata.namespace !== values.namespace || model.metadata.name !== selected.name || model.metadata.uid !== selected.uid || model.metadata.resourceVersion !== selected.resourceVersion || model.metadata.deletionTimestamp || model.spec.manufacturerRef?.name !== selected.manufacturer.name) throw new ApiError(409, 'The catalog changed. Refresh and review the selection.'); + const manufacturer = await readInventoryReference('Manufacturer', values.namespace, selected.manufacturer.name, operation); + operation.assertCurrent(); + if (manufacturer.metadata.namespace !== values.namespace || manufacturer.metadata.name !== selected.manufacturer.name || manufacturer.metadata.uid !== selected.manufacturer.uid || manufacturer.metadata.resourceVersion !== selected.manufacturer.resourceVersion || manufacturer.metadata.deletionTimestamp) throw new ApiError(409, 'The catalog changed. Refresh and review the selection.'); + } return; } for (const lane of values.cableLanes ?? []) for (const endpoint of [lane.a!, lane.b!]) { diff --git a/ui/provider/src/lib/inventory-management.ts b/ui/provider/src/lib/inventory-management.ts index 5883731d..438b4042 100644 --- a/ui/provider/src/lib/inventory-management.ts +++ b/ui/provider/src/lib/inventory-management.ts @@ -75,7 +75,7 @@ export async function createInventoryRecord(kind: ManagedKind, values: Inventory if (!facility?.metadata?.uid || facility.metadata.deletionTimestamp) throw new ApiError(409, 'Facility is not available. Refresh inventory before continuing.'); } operation.dispatch(); - const record = await proxyFetch(PROVIDER_PROJECT, `${resourcePath(kind, values.namespace)}?fieldManager=${INVENTORY_FIELD_MANAGER}`, { method: 'POST', body: payload }).catch(error => { operation.assertCurrent(); throw error; }); + const record = await proxyFetch(PROVIDER_PROJECT, `${resourcePath(kind, values.namespace)}?fieldManager=${INVENTORY_FIELD_MANAGER}${kind === 'Device' && values.catalog ? '&fieldValidation=Strict' : ''}`, { method: 'POST', body: payload }).catch(error => { operation.assertCurrent(); throw error; }); operation.assertCurrent(); if (!record?.metadata?.uid) throw new Error('Save outcome could not be confirmed.'); return record; diff --git a/ui/provider/src/lib/inventory-read-access.ts b/ui/provider/src/lib/inventory-read-access.ts index 4fffaccb..173eed13 100644 --- a/ui/provider/src/lib/inventory-read-access.ts +++ b/ui/provider/src/lib/inventory-read-access.ts @@ -19,6 +19,7 @@ export function readFailureIssues(error: InventoryReferenceReadError): Inventory export function redactInventory(source: Inventory, issues: Inventory['issues']): Inventory { const combined = { ...source.issues, ...issues }; + if (combined.Manufacturer) combined.DeviceType = combined.Manufacturer; return { issues: combined, slots: combined.DeviceClaim ? [] : source.slots.map(slot => ({ ...slot, devices: combined.Device ? [] : slot.devices })), diff --git a/ui/shared/fleet-api.ts b/ui/shared/fleet-api.ts index 725f3a58..e6ecc6f7 100644 --- a/ui/shared/fleet-api.ts +++ b/ui/shared/fleet-api.ts @@ -271,6 +271,7 @@ export interface Device { metadata: ObjectMeta; spec: { reportedPlacement?: ReportedPlacement; + deviceTypeRef?: LocalReference; claimRef: LocalReference; provenance: Provenance; identity: { manufacturer?: string; model: string; serial?: string; systemUUID?: string; sourceIdentity?: ExternalReference }; @@ -322,11 +323,18 @@ export interface CableEndpoint extends ComponentPosition { } export interface PhysicalRecord { metadata: ObjectMeta; - kind: 'Site' | 'Facility' | 'Rack' | 'Cable' | 'PowerFeed'; + kind: 'Site' | 'Facility' | 'Rack' | 'Cable' | 'PowerFeed' | 'Manufacturer' | 'DeviceType'; spec: { displayName: string; provenance: Provenance; code?: string; + canonicalName?: string; + aliases?: string[]; + manufacturerRef?: LocalReference; + model?: string; + modelShape?: { heightUnits?: number; fullDepth?: boolean }; + componentTemplates?: Omit[]; + sourceIdentity?: ExternalReference; facilityRefs?: LocalReference[]; identifiers?: { provider: string; type: 'PremisesCode' | 'PremisesAlias' | 'PremisesID'; value: string }[]; facilityRef?: LocalReference; From b3c8e68b69c7707c9ed01ff050244103b4e27f19 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sat, 21 Nov 2026 18:25:34 -0600 Subject: [PATCH 045/518] fix(inventory): let imported Devices stop sending provenance Three Device rules dereferenced provenance whenever identity.sourceIdentity was set. Because identity is immutable, an imported Device could never drop provenance. Skip those rules when provenance is absent. Co-Authored-By: Claude Opus 5.5 --- config/components/inventory/crds/fleet.datumapis.com.yaml | 6 +++--- internal/api/inventory/v1alpha1/crd_test.go | 8 ++++++++ 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/config/components/inventory/crds/fleet.datumapis.com.yaml b/config/components/inventory/crds/fleet.datumapis.com.yaml index 16c146de..54478179 100644 --- a/config/components/inventory/crds/fleet.datumapis.com.yaml +++ b/config/components/inventory/crds/fleet.datumapis.com.yaml @@ -314,13 +314,13 @@ spec: - rule: '!has(self.reportedPlacement) || (oldSelf.hasValue() && has(oldSelf.value().reportedPlacement) ? (self.reportedPlacement == oldSelf.value().reportedPlacement || self.reportedPlacement.revision == oldSelf.value().reportedPlacement.revision + 1) : self.reportedPlacement.revision == 1)' optionalOldSelf: true message: first report revision must be 1; every changed report must increment revision exactly once - - rule: '!has(self.reportedPlacement) || (has(self.reportedPlacement.method) && self.reportedPlacement.method == "Manual") || (has(self.identity.sourceIdentity) && has(self.provenance.source) && self.provenance.method == "NetBoxImport" && has(self.reportedPlacement.snapshotDigest) && self.reportedPlacement.observedAt == self.provenance.source.observedAt && self.reportedPlacement.snapshotDigest == self.provenance.source.snapshotDigest)' + - rule: '!has(self.reportedPlacement) || !has(self.provenance) || (has(self.reportedPlacement.method) && self.reportedPlacement.method == "Manual") || (has(self.identity.sourceIdentity) && has(self.provenance.source) && self.provenance.method == "NetBoxImport" && has(self.reportedPlacement.snapshotDigest) && self.reportedPlacement.observedAt == self.provenance.source.observedAt && self.reportedPlacement.snapshotDigest == self.provenance.source.snapshotDigest)' message: reported placement must retain the imported source snapshot and observation time - rule: '!has(self.interfaces) || self.interfaces.all(a, !has(a.macAddress) || (self.interfaces.filter(b, has(b.macAddress) && b.macAddress == a.macAddress).size() == 1 && (!has(self.unmappedMACAddresses) || !(a.macAddress in self.unmappedMACAddresses))))' message: a MAC address may be recorded only once - - rule: '!has(self.identity.sourceIdentity) || self.provenance.method == "NetBoxImport"' + - rule: '!has(self.identity.sourceIdentity) || !has(self.provenance) || self.provenance.method == "NetBoxImport"' message: source identity is for observational imports only - rule: '!has(self.topologyAuthority) || !has(self.interfaces) || self.interfaces.all(p, !has(p.peer))' message: Cable topology excludes inline peers @@ -334,7 +334,7 @@ spec: - rule: '!has(self.internalMappings) || self.internalMappings.all(m, self.internalMappings.filter(n, n.from == m.from).size() == 1)' message: each internal source position maps once - - rule: '!has(self.identity.sourceIdentity) || (has(self.provenance.source) && self.identity.sourceIdentity.system + - rule: '!has(self.identity.sourceIdentity) || !has(self.provenance) || (has(self.provenance.source) && self.identity.sourceIdentity.system == self.provenance.source.system && self.identity.sourceIdentity.type == self.provenance.source.type && self.identity.sourceIdentity.id == self.provenance.source.id)' message: observational identity must match provenance source identity diff --git a/internal/api/inventory/v1alpha1/crd_test.go b/internal/api/inventory/v1alpha1/crd_test.go index 451168f3..ed66e5cc 100644 --- a/internal/api/inventory/v1alpha1/crd_test.go +++ b/internal/api/inventory/v1alpha1/crd_test.go @@ -264,6 +264,14 @@ func TestProvenanceIsOptional(t *testing.T) { if errs := admit(t, "Device", object(t, without), withProvenance); len(errs) > 0 { t.Fatalf("dropping provenance rejected: %v", errs) } + // identity is immutable, so an imported Device keeps its sourceIdentity and + // must still be able to stop sending provenance. + imported := reportedDevice() + importedWithout := reportedDevice() + importedWithout.Spec.Provenance = nil + if errs := admit(t, "Device", object(t, importedWithout), object(t, imported)); len(errs) > 0 { + t.Fatalf("dropping provenance from an imported device rejected: %v", errs) + } claim := syntheticClaim() claim.Spec.Provenance = nil if errs := admit(t, "DeviceClaim", object(t, claim), object(t, syntheticClaim())); len(errs) > 0 { From 6498473ae00dc6ea16edd8f05016f23976793002 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sat, 21 Nov 2026 18:25:55 -0600 Subject: [PATCH 046/518] fix(inventory): ignore visible window focus changes --- docs/development/staff-inventory-ui.md | 210 +++++++----------- .../components/adversarial-review.test.tsx | 23 +- .../components/device-placement-edit.test.tsx | 13 +- .../src/components/device-placement-edit.tsx | 2 - .../exact-head-independent.test.tsx | 41 ++-- .../inventory-management-lifetime.test.tsx | 6 +- .../src/components/inventory-management.tsx | 2 - .../inventory-revalidation-safety.test.tsx | 17 +- .../inventory-session-boundary.test.tsx | 60 +++-- .../components/inventory-session-boundary.tsx | 85 ++----- .../inventory-stable-controls.test.tsx | 69 +++--- .../inventory-visible-focus-save.test.tsx | 89 ++++++++ .../pr103-review-negatives.test.tsx | 38 ++-- ui/provider/src/lib/api.ts | 2 +- 14 files changed, 307 insertions(+), 350 deletions(-) create mode 100644 ui/provider/src/components/inventory-visible-focus-save.test.tsx diff --git a/docs/development/staff-inventory-ui.md b/docs/development/staff-inventory-ui.md index c4f789b9..f221d968 100644 --- a/docs/development/staff-inventory-ui.md +++ b/docs/development/staff-inventory-ui.md @@ -102,142 +102,96 @@ not silently adopt a refreshed baseline. No automatic write retries occur. Existing session protections are retained: principal-isolated QueryClients, authority invalidation at session/revalidation/navigation/background/unmount boundaries, fresh authority generations even for React-batched revalidation, -and generation-guarded focus checks. Already-dispatched uncertain outcomes stay -unknown rather than becoming cancelled-success. - -### Visible browser blur versus session authority - -Visible blur also suspends new inventory/permission query dispatch and publication -and cancels outstanding queries without removing their previously authorized data. -Manual refresh cannot publish responses during unresolved host identity checks. -Read generations reject late successes and errors, even after authority resumes; -only the verified principal's fresh reads can renew management controls. -Rejected focus verification keeps the view masked during subsequent attempts; -only a successful attempt removes that mask. Regression tests directly check -cache replacement for batched principal changes and reject operation lifecycle -renewal when the host principal differs from the mounted principal. - -The visible-blur correction separates read visibility from write authority. -Previously, opening Safari's URL bar called the same hide path as backgrounding -the document, unmounting inventory and showing LoadingState. A visible window -blur is not evidence of logout, account switching, or document backgrounding. -It can also mean focus moved to another visible window. Intentionally, already -authorized inventory remains on screen in all these visible-blur cases; this -is not a screen-privacy curtain for unfocused windows. - -Writes remain conservatively fenced synchronously on every blur, pagehide, -hidden visibility transition, router revalidation/navigation, and principal -change. Returning focus verifies the real host loader. During that verification, -the existing same-principal read view stays mounted but operation authority -remains invalid. Management views now stay mounted, with disabled controls and -an accessible verification-pending status; cached permission is only evidence -for retaining the view, never current approval to write. Old operations never regain authority, including SSAR/reference -reads completing after an await; dispatched writes retain unknown outcomes. -After verification, an open form remains disabled until explicitly closed and -reopened. Namespace/access disclosure state and safe draft input survive visible -blur; create drafts survive reopening, while edits capture a new baseline and -reset to the refreshed record. Neither operative authority nor an immutable edit -baseline crosses the generation. Closing never submits or revives pending intent. -In-flight operations must settle before closing; a dispatched stale result is -unknown, never success. The inventory table and its view-specific query key stay -unchanged. Native disabled fieldsets cover nested hardware controls as well as -inputs; submit handlers independently enforce readiness and revocation. - -Successful same-principal focus checks cancel older query work and refresh reads -in the isolated client before explicitly refreshing management permissions. -Refresh starts only after host authority is verified, not on a host completion -while still blurred or while the verification promise is pending. A failed or wholly unavailable inventory read keeps forms suspended -until the next successful focus verification or reopened inventory. The cache's -settled read result, not a potentially delayed React observer, gates this renewal: -no SSAR is sent for stale forms while the new read result denies all inventory. -An observed read denial still redacts records; revalidation is not removed. Hidden documents and pagehide immediately -unmount and clear the client; foreground restoration waits for verification. -Explicit host revalidation/navigation also retains its masking/cache-reset -policy. Principal transitions reset the client, including observed A→B→A -transitions batched into one React render. Missing identities and host failures -remove private content. A focus check completing after a newer blur cannot -restore write authority; after a newer hidden/pagehide event it cannot restore -read visibility either. The host completion generation is still observed via -the synchronous router subscription, not only React's possibly batched loading -state. The soft-read policy remains latched until the next router cycle so a -promise completion preceding React's idle render cannot momentarily unmount it. - -This intentionally replaces tests that treated visible blur as a privacy mask. -Equivalent pagehide/hidden coverage is retained, and the adversarial write matrix -now exercises both visible focus/blur and focus/pagehide (create/edit, -pending SSAR, dispatched success/error, and StrictMode). Actual inventory-table -tests assert DOM identity through visible focus and verify refreshed denials; -operation-generation tests retain stale-completion and A→B→A protection. -Confirmed permission denial/error removes management actions and retained form -contents, rather than treating a cached grant as current. Related-read denials -still redact choices while preserving unrelated safe input. Genuine background, -principal changes and failed host verification still clear private content. - -### Stable management controls follow-up +and generation-guarded background-return checks. Already-dispatched uncertain +outcomes stay unknown rather than becoming cancelled-success. + +### Browser focus is not a session boundary Implemented against PR103's merged staging base -`f190d28397fc6110e02c9c83e6819a3a584258d0`, not the earlier documentation branch. -The generation-keyed ready/null wrappers caused the reported Namespace & access -and create/edit sections to disappear on URL-bar focus. The replacement separates -view lifetime from authority lifetime for all five create kinds, display-name -editing, and reported-location editing. A reserved status area avoids adding a -new row only when verification starts. This is implemented behavior, not a new -inventory, ownership, or IAM contract. - -The stable-controls suite checks identical DOM nodes, disabled controls, retained -disclosures/input, held host and permission verification, explicit baseline -renewal, denied permission and hard masking, with StrictMode variants. Earlier -review tests intentionally change only visible-blur removal expectations to -same-node/disabled assertions; hidden/pagehide assertions remain. Pending-write -tests retain zero pre-dispatch writes and unknown post-dispatch outcomes, and -include observed A→B→A. The changed tests are regression evidence, not independent -review signoff. - -Follow-up local validation (2026-11-21): provider 475 tests in 31 files and -consumer 44 tests in 3 files pass, as do both TypeScript checks and production -builds, `go test ./internal/api/inventory/...`, relative documentation links, and -`git diff --check`. Temporary mutations restoring ready/null unmounting or -removing readiness from the management gate each fail 24 of the 32 stable-view -tests; both mutations were reverted before final validation. - -Synthetic browser DOM/geometry checks retain identical control, form and table -nodes and bounding rectangles through blur and held focus verification. Checks -cover all five create kinds with collapsed/expanded access at 390px, Device -creation at 1280px, and display-name/location editors at 390px. No page-wide -mobile overflow was observed. Retained forms stay disabled after verification -until explicit reopening. Keyboard Tab/Enter and native disabled-focus checks -dispatch zero writes; pagehide removes private content and forms. The harness -supplies synthetic UIDs, resource versions and manual writer metadata for these -edit checks; no real ownership or server data changes. Preview screenshots timed -out, so this follow-up's browser evidence is DOM identity, geometry and event -checks, not screenshot or screen-reader acceptance. The real staging URL again -redirected to sign-in; authenticated Safari URL-bar acceptance remains unverified. - -For a synthetic browser check, run from `ui/provider`: +`f190d28397fc6110e02c9c83e6819a3a584258d0`. Ordinary visible window blur/focus +is deliberately ignored. Opening the URL bar does not change the session: +it does not suspend reads or writes, reset edit baselines, close or disable forms, +change Namespace & access disclosures, or start host/permission/inventory requests. +Both the session boundary and individual management/location forms have no +blur/focus listeners. QueryClient defaults and inventory queries disable window +focus refetch. Drafts and frozen baselines remain usable without reopening. + +Actual document hidden/pagehide events still synchronously invalidate operation +and read scopes, cancel queries and mask private children. Visibility restoration +or pageshow revalidates the host only after an observed hidden/pagehide boundary. +Overlapping background events advance a generation so an older verification +cannot restore authority. Failed verification remains masked. Explicit host +revalidation/navigation and observed principal changes also fence operations and +replace the private query cache, including fast batched A→B→A transitions. +Cached permission is never substituted for a confirmed denial; denied references +are redacted. Genuine session boundaries do not transfer drafts, immutable edit +baselines or pending intents into a new authority generation. + +The original PR104 disable-on-blur/reopen design was superseded by this simpler +trigger model before review/merge. Stable wrappers and native disabled controls +remain useful for actual permission refreshes, but browser chrome focus alone +never activates those states. This is not a new inventory or IAM contract. + +Backend per-request authentication/authorization, submit-time exact permission +checks, after-await operation checks, and atomic UID/resourceVersion JSON Patch +tests remain required. A cookie/account change not yet observed by the host +cannot be detected atomically by this UI. Focus is not authentication, and this +change does not claim protection against an unobserved cookie transition between +requests. Observed host boundaries revoke pending work; backend checks protect +each dispatched request. Unknown dispatched outcomes are not reported as success. + +### Regression evidence and acceptance limits + +The actual-component stable-controls matrix covers all five create kinds, +display-name and location editing, collapsed/expanded access, and StrictMode. +Repeated visible blur/focus preserves exact markup, DOM nodes, enabled controls, +drafts, disclosures and captured operation authority with no added requests. +Hosted pending-save tests cover delayed permission, baseline reads and dispatch; +saves continue across visible focus with the original UID/resourceVersion tests. +The same hosted cases revoke pending work across true hidden/visible and principal +changes; already-dispatched results never publish success into the new view. +Inventory-page tests also drive the query focus manager and assert no added +requests. Previous blur-revocation cases now use real hidden/pagehide or explicit +host boundaries, retaining delayed-operation, A→B→A, denied-read and unknown-write +coverage. These tests are local regression evidence, not independent signoff. + +Earlier synthetic browser geometry/keyboard checks at PR104 head `4a30bb7` +exercised the now-superseded disabled-view behavior; they are not acceptance +evidence for this revision. The real staging URL redirected to sign-in and no +login was manipulated. Authenticated Safari URL-bar acceptance remains unverified. +Independent review, CI and authenticated staging/Safari acceptance remain release +gates; this work does not merge, deploy or change live inventory/IAM/NetBox data. + +Revised local validation (2026-11-21): provider 495 tests in 32 files and consumer +44 tests in 3 files pass, along with both TypeScript checks/production builds, +`go test ./internal/api/inventory/...`, documentation links and whitespace. +Temporarily restoring the management form's blur invalidation fails 29 of 56 +focused stable-controls/pending-save tests; the mutation was removed before the +full passing run. This is sensitivity evidence, not independent review. + +Revised synthetic browser checks at 390px retain identical markup, form/control +nodes, bounding rectangles and request counters across visible blur/focus for +all five create kinds with collapsed/expanded access, plus display-name and +location editors. Native Tab advances to an enabled form input; subsequent +synthetic blur/focus retains that focus and markup without requests. Pagehide +removes forms, held pageshow verification keeps them absent, and release restores +fresh data without old drafts. No writes occurred. These are synthetic Chromium +DOM/geometry/event checks, not real browser-chrome or Safari acceptance. The owned +tab and fixture server were closed after checking. + +For an optional synthetic browser check, run from `ui/provider`: ```sh pnpm exec vite --config vitest.config.ts --host 127.0.0.1 --port 7793 ``` Open `/session-fixture.html`. This mounts the actual inventory page and boundary -under a synthetic host loader, not the preview bypass. All API calls are handled -in memory; writes return a synthetic failure and never reach an API. The browser -console's `inventorySessionFixture` exposes `hold(boolean)`, `release()`, -`principal(string|null)`, `denied(boolean)`, and `stats()` for controlled loader -completion, account transitions, and read denial. Dispatch window blur/focus or -pagehide to inspect transitions. This harness is not a production build entry. - -Local browser evidence on 2026-11-21 uses synthetic events and data. Visible -blur/focus retained the identical table DOM node with no observed LoadingState; -collection reads renewed from seven to fourteen. Pagehide removed the table and -kept LoadingState through the held return-focus check; release restored a fresh -read view. A subsequent synthetic 403 replaced it with access guidance and no -private table. No fixture writes were dispatched. The real -staging URL redirected to sign-in; no login was manipulated. That evidence and -the supplied Safari screenshot do not prove authenticated Safari URL-bar -acceptance. Independent adversarial signoff, CI, and authenticated staging/Safari -acceptance remain deployment gates; no inventory, IAM, or NetBox data is changed -by this correction. +under a synthetic host loader, not the preview bypass. API calls are handled in +memory; writes return a synthetic failure and never reach an API. The console's +`inventorySessionFixture` exposes `hold(boolean)`, `release()`, +`principal(string|null)`, `denied(boolean)`, and `stats()`. Blur/focus should do +nothing; pagehide followed by pageshow exercises held restoration. This harness +is not a production build entry and is not evidence of real Safari acceptance. Read-only users browse without enabled writes. No-read and direct-link denials show calm access guidance, not empty/zero inventory. Partial collection failures diff --git a/ui/provider/src/components/adversarial-review.test.tsx b/ui/provider/src/components/adversarial-review.test.tsx index 39d0d611..2080e08a 100644 --- a/ui/provider/src/components/adversarial-review.test.tsx +++ b/ui/provider/src/components/adversarial-review.test.tsx @@ -6,25 +6,23 @@ import { InventoryManagement } from './inventory-management'; import { InventorySessionBoundary } from './inventory-session-boundary'; import DeviceInventoryList from '../pages/device-inventory-list'; import { inventoryPayload, INVENTORY_FIELD_MANAGER } from '../lib/inventory-management'; +import { focusManager } from '@tanstack/react-query'; const values = { name: 'review-facility', namespace: 'default', displayName: 'Original label', recordedBy: 'synthetic-reviewer', reference: '', facility: '', height: '' }; const original = { ...inventoryPayload('Facility', values, '2026-01-01T00:00:00Z'), metadata: { name: values.name, namespace: 'default', uid: 'synthetic-only', resourceVersion: '1', managedFields: [{ manager: INVENTORY_FIELD_MANAGER }] } }; const response = (data: unknown) => ({ ok: true, status: 200, json: async () => ({ data }) }); -afterEach(() => { cleanup(); vi.unstubAllGlobals(); }); +afterEach(() => { cleanup(); vi.unstubAllGlobals(); focusManager.setFocused(undefined); }); -it.each([false, true])('keeps real table mounted on visible focus and refreshes read authorization denied=%s', async denied => { +it.each([false, true])('visible focus never refreshes real inventory; explicit refresh observes denial=%s', async denied => { let rechecking = false; - let release: (() => void) | undefined; const requests = vi.fn(async (url: string) => { if (url.includes('selfsubjectaccessreviews')) return response({ status: { allowed: false } }); if (rechecking && denied) return { ok: false, status: 403, json: async () => ({ error: 'Private diagnostic' }) }; return response({ items: url.includes('/facilities?') ? [original] : [] }); }); vi.stubGlobal('fetch', requests); - const router = createMemoryRouter([{ id: 'layouts/milo.layout', path: '/', loader: async () => { - if (rechecking) await new Promise(resolve => { release = resolve; }); - return { user: { metadata: { uid: 'staff-a' } } }; - }, element: , children: [{ index: true, element: }] }], { initialEntries: ['/?kind=Facility'] }); + const loader = vi.fn(() => ({ user: { metadata: { uid: 'staff-a' } } })); + const router = createMemoryRouter([{ id: 'layouts/milo.layout', path: '/', loader, element: , children: [{ index: true, element: }] }], { initialEntries: ['/?kind=Facility'] }); render(); await screen.findByRole('link', { name: /Original label/ }); const table = screen.getByRole('table'); @@ -32,12 +30,15 @@ it.each([false, true])('keeps real table mounted on visible focus and refreshes const observer = new MutationObserver(() => loadingStates.push(!!screen.queryByTestId('fleet-plugin-loading'))); observer.observe(document.body, { childList: true, subtree: true }); rechecking = true; + const before = requests.mock.calls.length; fireEvent(window, new Event('blur')); expect(screen.getByRole('table')).toBe(table); fireEvent(window, new Event('focus')); - await waitFor(() => expect(release).toBeDefined()); + await act(async () => { focusManager.setFocused(false); focusManager.setFocused(true); await new Promise(resolve => setTimeout(resolve, 0)); }); expect(screen.getByRole('table')).toBe(table); - await act(async () => release!()); + expect(requests).toHaveBeenCalledTimes(before); + expect(loader).toHaveBeenCalledTimes(1); + fireEvent.click(screen.getByRole('button', { name: 'Refresh inventory' })); if (denied) { await screen.findByRole('heading', { name: 'Inventory access needed' }); expect(screen.queryByText(/Original label|Private diagnostic/)).not.toBeInTheDocument(); @@ -142,14 +143,14 @@ it('must not silently advance an open edit form to a refreshed resourceVersion', expect(patches).toEqual([]); }); -it('must keep inventory concealed if focus verification finishes after pagehide', async () => { +it('must keep inventory concealed if foreground verification finishes after another pagehide', async () => { let release: (() => void) | undefined; let count = 0; const router = createMemoryRouter([{ id: 'layouts/milo.layout', path: '/', loader: async () => { if (++count === 2) await new Promise(resolve => { release = resolve; }); return { user: { metadata: { uid: 'staff-a' } } }; }, element: , children: [{ index: true, element: Private inventory label }] }]); render(); await screen.findByText('Private inventory label'); fireEvent(window, new Event('pagehide')); - fireEvent(window, new Event('focus')); + fireEvent(window, new Event('pageshow')); await waitFor(() => expect(release).toBeDefined()); fireEvent(window, new Event('pagehide')); await act(async () => { release!(); }); diff --git a/ui/provider/src/components/device-placement-edit.test.tsx b/ui/provider/src/components/device-placement-edit.test.tsx index a86a3aff..d256d347 100644 --- a/ui/provider/src/components/device-placement-edit.test.tsx +++ b/ui/provider/src/components/device-placement-edit.test.tsx @@ -24,7 +24,7 @@ function openAndFill(existing = false) { fireEvent.change(screen.getByLabelText('Evidence reference'), { target: { value: 'ticket/example' } }); } beforeEach(() => { vi.clearAllMocks(); permission.mockReturnValue({ data: true, isFetching: false, error: null } as never); }); -afterEach(() => vi.unstubAllGlobals()); +afterEach(() => { vi.unstubAllGlobals(); vi.restoreAllMocks(); }); describe('reported location editor', () => { it.each([false, true])('adds/edits an imported Device and refreshes projections: %s', async existing => { @@ -67,14 +67,17 @@ describe('reported location editor', () => { expect(screen.queryByDisplayValue('rack')).not.toBeInTheDocument(); expect(fetch).toHaveBeenCalledTimes(3); }); - it.each(['session', 'blur', 'unmount', 'revalidation'])('revokes a delayed permission read on %s', async event => { + it.each(['session', 'hidden', 'unmount', 'revalidation'])('revokes a delayed permission read on %s', async event => { let resolve!: (value: unknown) => void; const fetch = vi.fn().mockImplementationOnce(() => new Promise(done => { resolve = done; })); vi.stubGlobal('fetch', fetch); const view = setup(); openAndFill(); fireEvent.click(screen.getByRole('button', { name: 'Save reported location' })); await waitFor(() => expect(resolve).toBeDefined()); if (event === 'session') view.session.invalidate(); - if (event === 'blur') fireEvent(window, new Event('blur')); + if (event === 'hidden') { + vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('hidden'); + fireEvent(document, new Event('visibilitychange')); + } if (event === 'unmount') view.unmount(); if (event === 'revalidation') { permission.mockReturnValue({ data: true, isFetching: true, error: null } as never); @@ -92,7 +95,7 @@ describe('reported location editor', () => { expect(screen.getByRole('button', { name: 'Save reported location' })).toBeDisabled(); expect(fetch).not.toHaveBeenCalled(); }); - it.each(['session', 'navigation', 'blur/focus'])('revokes a delayed reference read across %s', async event => { + it.each(['session', 'navigation', 'pagehide/pageshow'])('revokes a delayed reference read across %s', async event => { let resolve!: (value: unknown) => void; const fetch = vi.fn().mockResolvedValueOnce(response({ status: { allowed: true } })).mockResolvedValueOnce(response(device)).mockImplementationOnce(() => new Promise(done => { resolve = done; })); vi.stubGlobal('fetch', fetch); @@ -102,7 +105,7 @@ describe('reported location editor', () => { await waitFor(() => expect(resolve).toBeDefined()); if (event === 'session') view.session.invalidate(); if (event === 'navigation') view.unmount(); - if (event === 'blur/focus') { fireEvent(window, new Event('blur')); fireEvent(window, new Event('focus')); } + if (event === 'pagehide/pageshow') { fireEvent(window, new Event('pagehide')); fireEvent(window, new Event('pageshow')); } resolve(response(rack)); if (event !== 'navigation') await waitFor(() => expect(screen.getByRole('status')).toHaveTextContent('No write was dispatched')); else await new Promise(done => setTimeout(done, 0)); diff --git a/ui/provider/src/components/device-placement-edit.tsx b/ui/provider/src/components/device-placement-edit.tsx index 92be4144..888f823a 100644 --- a/ui/provider/src/components/device-placement-edit.tsx +++ b/ui/provider/src/components/device-placement-edit.tsx @@ -38,12 +38,10 @@ function DevicePlacementForm({ device, locations, issues }: { device: Device; lo useLayoutEffect(() => { const invalidate = () => { scope.current.invalidate(); setBlocked(true); setBaseline(undefined); }; const visibility = () => { if (document.visibilityState === 'hidden') invalidate(); }; - window.addEventListener('blur', invalidate); window.addEventListener('pagehide', invalidate); document.addEventListener('visibilitychange', visibility); return () => { scope.current.invalidate(); - window.removeEventListener('blur', invalidate); window.removeEventListener('pagehide', invalidate); document.removeEventListener('visibilitychange', visibility); }; diff --git a/ui/provider/src/components/exact-head-independent.test.tsx b/ui/provider/src/components/exact-head-independent.test.tsx index dd0ce8b0..fd17f9e3 100644 --- a/ui/provider/src/components/exact-head-independent.test.tsx +++ b/ui/provider/src/components/exact-head-independent.test.tsx @@ -10,7 +10,7 @@ import DeviceInventoryList from '../pages/device-inventory-list'; const values = { name: 'exact-review', namespace: 'default', displayName: 'Original', recordedBy: 'synthetic', reference: '', facility: '', height: '' }; const original = { ...inventoryPayload('Facility', values, '2026-01-01T00:00:00Z'), metadata: { name: values.name, namespace: 'default', uid: 'synthetic', resourceVersion: '1', managedFields: [{ manager: INVENTORY_FIELD_MANAGER }] } }; const response = (data: unknown, status = 200) => ({ ok: status < 400, status, json: async () => ({ data }) }); -afterEach(() => { cleanup(); vi.unstubAllGlobals(); }); +afterEach(() => { cleanup(); vi.unstubAllGlobals(); vi.restoreAllMocks(); }); async function open(editing: boolean, label: string) { await waitFor(() => expect(screen.getByRole('button', { name: editing ? 'Edit display name' : 'Create facility' })).toBeEnabled()); @@ -20,7 +20,8 @@ async function open(editing: boolean, label: string) { fireEvent.change(screen.getByLabelText('Recorded by'), { target: { value: 'synthetic' } }); } -it.each([false, true].flatMap(strict => [false, true].flatMap(editing => ['review', 'dispatch-ok', 'dispatch-error'].flatMap(stage => ['fast-repeat', 'principal-repeat', 'slow', 'overlap', 'cancel-navigation', 'focus-blur', 'focus-pagehide'].map(transition => ({ strict, editing, stage, transition }))))))('independent $transition $stage edit=$editing strict=$strict', async ({ strict, editing, stage, transition }) => { +it.each([false, true].flatMap(strict => [false, true].flatMap(editing => ['review', 'dispatch-ok', 'dispatch-error'].flatMap(stage => ['fast-repeat', 'principal-repeat', 'slow', 'overlap', 'cancel-navigation', 'restore-hidden', 'restore-pagehide'].map(transition => ({ strict, editing, stage, transition }))))))('independent $transition $stage edit=$editing strict=$strict', async ({ strict, editing, stage, transition }) => { + const visibility = vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('visible'); let principal = 'same-user'; let submitting = false; let intercepted = false; @@ -44,7 +45,6 @@ it.each([false, true].flatMap(strict => [false, true].flatMap(editing => ['revie }, element: , children: [{ index: true, element: }] }]); render(strict ? : ); await open(editing, 'Old input'); - const oldInput = screen.getByLabelText('Display name'); const submit = editing ? 'Save display name' : 'Create facility record'; submitting = true; fireEvent.click(screen.getByRole('button', { name: submit })); @@ -55,22 +55,20 @@ it.each([false, true].flatMap(strict => [false, true].flatMap(editing => ['revie await act(async () => { await router.revalidate(); await router.revalidate(); await router.revalidate(); }); } else { holdLoader = true; - act(() => { if (transition.startsWith('focus-')) window.dispatchEvent(new Event('focus')); else if (transition === 'cancel-navigation') void router.navigate('/?kind=Rack'); else void router.revalidate(); }); + act(() => { if (transition.startsWith('restore-')) { window.dispatchEvent(new Event('pagehide')); window.dispatchEvent(new Event('pageshow')); } else if (transition === 'cancel-navigation') void router.navigate('/?kind=Rack'); else void router.revalidate(); }); await waitFor(() => expect(loaders).toHaveLength(1)); - if (transition.startsWith('focus-')) { - expect(screen.getByLabelText('Display name')).toBe(oldInput); - expect(oldInput).toBeDisabled(); - } else expect(screen.queryByLabelText('Display name')).not.toBeInTheDocument(); - if (transition.startsWith('focus-')) { - fireEvent(window, new Event(transition === 'focus-blur' ? 'blur' : 'pagehide')); + expect(screen.queryByLabelText('Display name')).not.toBeInTheDocument(); + if (transition.startsWith('restore-')) { + if (transition === 'restore-hidden') { + visibility.mockReturnValue('hidden'); + fireEvent(document, new Event('visibilitychange')); + } else fireEvent(window, new Event('pagehide')); await act(async () => loaders[0]()); - if (transition === 'focus-blur') { - expect(screen.getByLabelText('Display name')).toBe(oldInput); - expect(oldInput).toBeDisabled(); - } else expect(screen.queryByLabelText('Display name')).not.toBeInTheDocument(); + expect(screen.queryByLabelText('Display name')).not.toBeInTheDocument(); expect(screen.queryByRole('button', { name: 'Create facility' })).not.toBeInTheDocument(); holdLoader = false; - await act(async () => window.dispatchEvent(new Event('focus'))); + visibility.mockReturnValue('visible'); + await act(async () => window.dispatchEvent(new Event('pageshow'))); } else if (transition === 'overlap' || transition === 'cancel-navigation') { act(() => { if (transition === 'cancel-navigation') void router.navigate('/?kind=Facility'); else void router.revalidate(); }); await waitFor(() => expect(loaders).toHaveLength(2)); @@ -82,15 +80,6 @@ it.each([false, true].flatMap(strict => [false, true].flatMap(editing => ['revie holdLoader = false; } } - if (transition === 'focus-blur') { - await act(async () => releaseOperation!(response(stage === 'review' ? { status: { allowed: true } } : original, stage === 'dispatch-error' ? 503 : 200))); - await waitFor(() => expect(screen.getByRole('button', { name: 'Close form' })).toBeEnabled()); - expect(screen.getByRole('status')).toHaveTextContent(stage === 'review' ? 'No write was dispatched' : 'outcome is unknown'); - expect(oldInput).toBeDisabled(); - fireEvent.submit(oldInput.closest('form')!); - expect(writes).toHaveLength(stage === 'review' ? 0 : 1); - fireEvent.click(screen.getByRole('button', { name: 'Close form' })); - } await open(editing, 'Fresh input'); await act(async () => releaseOperation!(response(stage === 'review' ? { status: { allowed: true } } : original, stage === 'dispatch-error' ? 503 : 200))); expect(writes).toHaveLength(stage === 'review' ? 0 : 1); @@ -102,7 +91,7 @@ it.each([false, true].flatMap(strict => [false, true].flatMap(editing => ['revie router.dispose(); }); -it.each([false, true].flatMap(strict => [401, 403, 404, 503].flatMap(status => ['revalidate', 'focus'].map(transition => ({ strict, status, transition })))))('late previous cache never overrides new denial $status strict=$strict via=$transition', async ({ strict, status, transition }) => { +it.each([false, true].flatMap(strict => [401, 403, 404, 503].flatMap(status => ['revalidate', 'restore'].map(transition => ({ strict, status, transition })))))('late previous cache never overrides new denial $status strict=$strict via=$transition', async ({ strict, status, transition }) => { let phase = 'initial'; const releases: (() => void)[] = []; const freshRequests: string[] = []; @@ -126,7 +115,7 @@ it.each([false, true].flatMap(strict => [401, 403, 404, 503].flatMap(status => [ await waitFor(() => expect(releases).toHaveLength(7)); phase = 'denied'; await act(async () => { - if (transition === 'focus') { fireEvent(window, new Event('blur')); fireEvent(window, new Event('focus')); } + if (transition === 'restore') { fireEvent(window, new Event('pagehide')); fireEvent(window, new Event('pageshow')); } else { await router.revalidate(); await router.revalidate(); } }); const title = status === 401 ? 'Your session has expired' : status === 403 ? 'Inventory access needed' : status === 404 ? 'Inventory section unavailable' : 'Inventory is temporarily unavailable'; diff --git a/ui/provider/src/components/inventory-management-lifetime.test.tsx b/ui/provider/src/components/inventory-management-lifetime.test.tsx index b92cd7dc..deaff352 100644 --- a/ui/provider/src/components/inventory-management-lifetime.test.tsx +++ b/ui/provider/src/components/inventory-management-lifetime.test.tsx @@ -9,7 +9,7 @@ const original = { ...inventoryPayload('Facility', values, '2026-01-01T00:00:00Z const response = (data: unknown) => ({ ok: true, status: 200, json: async () => ({ data }) }); afterEach(() => vi.unstubAllGlobals()); -it.each(['create-blur', 'create-unmount', 'edit-blur', 'edit-unmount', 'create-dispatched-blur', 'edit-dispatched-blur'])('revokes pending authority on %s', async mode => { +it.each(['create-pagehide', 'create-unmount', 'edit-pagehide', 'edit-unmount', 'create-dispatched-pagehide', 'edit-dispatched-pagehide'])('revokes pending authority on %s', async mode => { let release: ((value: unknown) => void) | undefined; let reviews = 0; const writes: string[] = []; @@ -35,10 +35,10 @@ it.each(['create-blur', 'create-unmount', 'edit-blur', 'edit-unmount', 'create-d fireEvent.click(screen.getByRole('button', { name: editing ? 'Save display name' : 'Create facility record' })); await waitFor(() => expect(release).toBeDefined()); if (mode.endsWith('unmount')) mounted.unmount(); - else fireEvent(window, new Event('blur')); + else fireEvent(window, new Event('pagehide')); await act(async () => { release!(response(mode.includes('dispatched') ? original : { status: { allowed: true } })); }); expect(writes).toEqual(mode.includes('dispatched') ? [editing ? 'PATCH' : 'POST'] : []); - if (mode.endsWith('blur')) { + if (mode.endsWith('pagehide')) { expect(screen.getByRole('status')).toHaveTextContent(mode.includes('dispatched') ? 'outcome is unknown' : 'No write was dispatched'); expect(screen.queryByText(/Display name saved\.|Facility record created\./)).not.toBeInTheDocument(); expect(screen.getByLabelText('Display name')).toHaveValue('Retained safe input'); diff --git a/ui/provider/src/components/inventory-management.tsx b/ui/provider/src/components/inventory-management.tsx index af9a91ff..3bdc2816 100644 --- a/ui/provider/src/components/inventory-management.tsx +++ b/ui/provider/src/components/inventory-management.tsx @@ -32,12 +32,10 @@ function InventoryManagementForm({ kind, record, facilities: sourceFacilities, c scope.current = current; const invalidate = () => { scope.current.invalidate(); setBaseline(undefined); setBlocked(true); }; const visibility = () => { if (document.visibilityState === 'hidden') invalidate(); }; - window.addEventListener('blur', invalidate); window.addEventListener('pagehide', invalidate); document.addEventListener('visibilitychange', visibility); return () => { invalidate(); - window.removeEventListener('blur', invalidate); window.removeEventListener('pagehide', invalidate); document.removeEventListener('visibilitychange', visibility); }; diff --git a/ui/provider/src/components/inventory-revalidation-safety.test.tsx b/ui/provider/src/components/inventory-revalidation-safety.test.tsx index f04b2f2a..94a93874 100644 --- a/ui/provider/src/components/inventory-revalidation-safety.test.tsx +++ b/ui/provider/src/components/inventory-revalidation-safety.test.tsx @@ -9,7 +9,7 @@ import { inventoryPayload, INVENTORY_FIELD_MANAGER } from '../lib/inventory-mana const values = { name: 'fresh-test', namespace: 'default', displayName: 'Fresh record', recordedBy: 'reviewer', reference: '', facility: 'fresh-test', height: '' }; const original = { ...inventoryPayload('Facility', values, '2026-01-01T00:00:00Z'), metadata: { name: values.name, namespace: 'default', uid: 'synthetic', resourceVersion: '1', managedFields: [{ manager: INVENTORY_FIELD_MANAGER }] } }; const response = (data: unknown) => ({ ok: true, status: 200, json: async () => ({ data }) }); -afterEach(() => { cleanup(); vi.unstubAllGlobals(); }); +afterEach(() => { cleanup(); vi.unstubAllGlobals(); vi.restoreAllMocks(); }); async function open(editing: boolean, rack = false) { fireEvent.click(await screen.findByRole('button', { name: editing ? 'Edit display name' : rack ? 'Create rack' : 'Create facility' })); @@ -19,7 +19,7 @@ async function open(editing: boolean, rack = false) { if (rack) fireEvent.change(screen.getByLabelText('Facility'), { target: { value: values.name } }); } -it.each(['same-url', 'replace', 'back-forward', 'revalidate', 'focus', 'visible', 'pageshow'].flatMap(navigation => [false, true].flatMap(editing => [false, true].map(strict => ({ navigation, editing, strict })))) )('fresh authority after $navigation edit=$editing strict=$strict', async ({ navigation, editing, strict }) => { +it.each(['same-url', 'replace', 'back-forward', 'revalidate', 'hidden-return', 'pagehide-return'].flatMap(navigation => [false, true].flatMap(editing => [false, true].map(strict => ({ navigation, editing, strict })))) )('fresh authority after $navigation edit=$editing strict=$strict', async ({ navigation, editing, strict }) => { const writes: string[] = []; vi.stubGlobal('fetch', vi.fn(async (url: string, init: RequestInit) => { if (url.includes('selfsubjectaccessreviews')) return response({ status: { allowed: true } }); @@ -31,9 +31,16 @@ it.each(['same-url', 'replace', 'back-forward', 'revalidate', 'focus', 'visible' await screen.findByRole('button', { name: editing ? 'Edit display name' : 'Create facility' }); await act(async () => { if (navigation === 'revalidate') await router.revalidate(); - else if (navigation === 'focus') window.dispatchEvent(new Event('focus')); - else if (navigation === 'visible') document.dispatchEvent(new Event('visibilitychange')); - else if (navigation === 'pageshow') window.dispatchEvent(new PageTransitionEvent('pageshow', { persisted: true })); + else if (navigation === 'hidden-return') { + const visibility = vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('hidden'); + document.dispatchEvent(new Event('visibilitychange')); + visibility.mockReturnValue('visible'); + document.dispatchEvent(new Event('visibilitychange')); + } + else if (navigation === 'pagehide-return') { + window.dispatchEvent(new PageTransitionEvent('pagehide', { persisted: true })); + window.dispatchEvent(new PageTransitionEvent('pageshow', { persisted: true })); + } else if (navigation === 'back-forward') { await router.navigate('/?kind=Facility'); await router.navigate(-1); await router.navigate(1); } else await router.navigate('/', { replace: navigation === 'replace' }); }); diff --git a/ui/provider/src/components/inventory-session-boundary.test.tsx b/ui/provider/src/components/inventory-session-boundary.test.tsx index 36e517f4..f8cda862 100644 --- a/ui/provider/src/components/inventory-session-boundary.test.tsx +++ b/ui/provider/src/components/inventory-session-boundary.test.tsx @@ -20,51 +20,40 @@ function mountHost(loader: () => unknown, content: React.ReactNode) { describe('host inventory session isolation', () => { afterEach(() => vi.restoreAllMocks()); - it('keeps visible inventory through browser-chrome blur/focus while fencing old and pending authority', async () => { + it('leaves visible inventory and operation authority unchanged on browser-chrome blur/focus', async () => { let scope: InventoryOperationScope | undefined; - let release: (() => void) | undefined; - let reads = 0; const inventoryRead = vi.fn(async () => 'Visible inventory'); function Records() { scope = useContext(InventoryOperationContext); const query = useQuery({ queryKey: ['inventory'], queryFn: inventoryRead, staleTime: Infinity }); return

      {query.data ?? 'Empty inventory cache'}

      ; } - mountHost(async () => { - if (++reads > 1) await new Promise(resolve => { release = resolve; }); - return { user: { metadata: { uid: 'staff-a' } } }; - }, ); + const loader = vi.fn(() => ({ user: { metadata: { uid: 'staff-a' } } })); + mountHost(loader, ); await screen.findByText('Visible inventory'); const before = scope!.begin(); const dispatched = scope!.begin(); dispatched.dispatch(); fireEvent(window, new Event('blur')); expect(screen.getByText('Visible inventory')).toBeInTheDocument(); - expect(() => before.assertCurrent()).toThrow(InventoryOperationInvalidated); - expect(() => dispatched.assertCurrent()).toThrow(/outcome is unknown/); + expect(() => before.assertCurrent()).not.toThrow(); + expect(() => dispatched.assertCurrent()).not.toThrow(); fireEvent(window, new Event('focus')); - await waitFor(() => expect(release).toBeDefined()); - expect(screen.getByText('Visible inventory')).toBeInTheDocument(); const during = scope!.begin(); - expect(() => during.assertCurrent()).toThrow(InventoryOperationInvalidated); + expect(() => during.assertCurrent()).not.toThrow(); fireEvent(window, new Event('blur')); - await act(async () => release!()); - expect(screen.getByText('Visible inventory')).toBeInTheDocument(); - expect(() => scope!.begin().assertCurrent()).toThrow(InventoryOperationInvalidated); - expect(inventoryRead).toHaveBeenCalledTimes(1); - release = undefined; fireEvent(window, new Event('focus')); - await waitFor(() => expect(release).toBeDefined()); - await act(async () => release!()); + await act(async () => { await new Promise(resolve => setTimeout(resolve, 0)); }); expect(screen.getByText('Visible inventory')).toBeInTheDocument(); - expect(inventoryRead).toHaveBeenCalledTimes(2); + expect(inventoryRead).toHaveBeenCalledTimes(1); + expect(loader).toHaveBeenCalledTimes(1); expect(() => scope!.begin().assertCurrent()).not.toThrow(); - expect(() => before.assertCurrent()).toThrow(InventoryOperationInvalidated); - expect(() => during.assertCurrent()).toThrow(InventoryOperationInvalidated); - expect(() => dispatched.assertCurrent()).toThrow(/outcome is unknown/); + expect(() => before.assertCurrent()).not.toThrow(); + expect(() => during.assertCurrent()).not.toThrow(); + expect(() => dispatched.assertCurrent()).not.toThrow(); }); - it('replaces caches on visible focus principal changes including batched A to B to A', async () => { + it('replaces caches on actual host principal changes including batched A to B to A', async () => { let client: QueryClient | undefined; let principal = 'staff-a'; let revision = 1; @@ -79,7 +68,6 @@ describe('host inventory session isolation', () => { const originalClient = client; await act(async () => { principal = 'staff-b'; - fireEvent(window, new Event('focus')); await router.revalidate(); principal = 'staff-a'; revision++; @@ -133,14 +121,16 @@ describe('host inventory session isolation', () => { router.dispose(); }); - it('keeps failed focus verification masked until the next verification succeeds', async () => { + it('keeps failed foreground restoration masked until the next restoration succeeds', async () => { const router = mountHost(() => ({ user: { metadata: { uid: 'staff-a' } } }), 'Private inventory'); await screen.findByText('Private inventory'); let release!: () => void; vi.spyOn(router, 'revalidate').mockRejectedValueOnce(new Error('verification failed')).mockImplementationOnce(() => new Promise(resolve => { release = resolve; })); - fireEvent(window, new Event('focus')); + fireEvent(window, new Event('pagehide')); + fireEvent(window, new Event('pageshow')); await waitFor(() => expect(screen.queryByText('Private inventory')).not.toBeInTheDocument()); - fireEvent(window, new Event('focus')); + fireEvent(window, new Event('pagehide')); + fireEvent(window, new Event('pageshow')); await waitFor(() => expect(release).toBeDefined()); expect(screen.queryByText('Private inventory')).not.toBeInTheDocument(); await act(async () => release()); @@ -148,7 +138,7 @@ describe('host inventory session isolation', () => { router.dispose(); }); - it.each(['logout', 'failure'])('clears visible data when focus verification observes %s', async outcome => { + it.each(['logout', 'failure'])('clears private data when foreground restoration observes %s', async outcome => { let expired = false; mountHost(() => { if (expired && outcome === 'failure') throw new Response('Synthetic failure', { status: 503 }); @@ -157,8 +147,8 @@ describe('host inventory session isolation', () => { }, 'Visible inventory'); await screen.findByText('Visible inventory'); expired = true; - fireEvent(window, new Event('blur')); - fireEvent(window, new Event('focus')); + fireEvent(window, new Event('pagehide')); + fireEvent(window, new Event('pageshow')); await waitFor(() => expect(screen.queryByText('Visible inventory')).not.toBeInTheDocument()); }); @@ -231,13 +221,13 @@ describe('host inventory session isolation', () => { expect(screen.queryByText('Restricted inventory')).not.toBeInTheDocument(); loader.mockReturnValue({ user: null } as never); visibility.mockReturnValue('visible'); - fireEvent(window, new Event('focus')); + fireEvent(document, new Event('visibilitychange')); await screen.findByText('Your session has expired'); expect(loader).toHaveBeenCalledTimes(2); expect(screen.queryByText('Restricted inventory')).not.toBeInTheDocument(); }); - it('only restores the newest foreground generation after successive pagehide and focus events', async () => { + it('only restores the newest foreground generation after successive pagehide and pageshow events', async () => { const releases: (() => void)[] = []; let reads = 0; mountHost(async () => { @@ -246,10 +236,10 @@ describe('host inventory session isolation', () => { }, 'Private inventory'); await screen.findByText('Private inventory'); fireEvent(window, new Event('pagehide')); - fireEvent(window, new Event('focus')); + fireEvent(window, new Event('pageshow')); await waitFor(() => expect(releases).toHaveLength(1)); fireEvent(window, new Event('pagehide')); - fireEvent(window, new Event('focus')); + fireEvent(window, new Event('pageshow')); await waitFor(() => expect(releases).toHaveLength(2)); await act(async () => releases[0]()); expect(screen.queryByText('Private inventory')).not.toBeInTheDocument(); diff --git a/ui/provider/src/components/inventory-session-boundary.tsx b/ui/provider/src/components/inventory-session-boundary.tsx index 47ea9f08..e5aba11a 100644 --- a/ui/provider/src/components/inventory-session-boundary.tsx +++ b/ui/provider/src/components/inventory-session-boundary.tsx @@ -4,18 +4,15 @@ import { UNSAFE_DataRouterContext, UNSAFE_DataRouterStateContext, useLocation, u import { InventoryAccessState } from './inventory-access-state'; import { LoadingState } from './states'; import { InventoryOperationContext, InventoryOperationGenerationContext, InventoryOperationReadyContext, InventoryOperationScope } from '../lib/inventory-operation'; -import { inventoryResources, type Inventory, type InventoryKind } from '../inventory'; import { InventoryReadContext, InventoryReadScope } from '../lib/inventory-read'; export const InventoryPreviewContext = createContext(false); export function SessionQueries({ children, principal, authority, generation }: { children: ReactNode; principal: string; authority: boolean; generation: number }) { - const [client] = useState(() => new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } })); + const [client] = useState(() => new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0, refetchOnWindowFocus: false } } })); const [scope] = useState(() => new InventoryOperationScope()); const [reads] = useState(() => new InventoryReadScope()); - const readGeneration = useRef(generation); - const [readyGeneration, setReadyGeneration] = useState(generation); - const ready = authority && readyGeneration === generation; + const ready = authority; const host = useContext(UNSAFE_DataRouterContext); useLayoutEffect(() => { const identity = host?.router.state.loaderData['layouts/milo.layout'] as { user?: { metadata?: { uid?: string; name?: string } } } | undefined; @@ -29,7 +26,6 @@ export function SessionQueries({ children, principal, authority, generation }: { if (authority && host?.router.state.revalidation === 'idle' && host.router.state.navigation.state === 'idle' && (identity?.user?.metadata?.uid ?? identity?.user?.metadata?.name) === principal) reads.resume(); else invalidate(); const visibility = () => { if (document.visibilityState === 'hidden') invalidate(); }; - window.addEventListener('blur', invalidate); window.addEventListener('pagehide', invalidate); document.addEventListener('visibilitychange', visibility); const unsubscribe = host?.router.subscribe(state => { @@ -38,39 +34,17 @@ export function SessionQueries({ children, principal, authority, generation }: { }); return () => { invalidate(); unsubscribe?.(); - window.removeEventListener('blur', invalidate); window.removeEventListener('pagehide', invalidate); document.removeEventListener('visibilitychange', visibility); }; }, [host, principal, scope, ready, generation, authority, reads, client]); - useEffect(() => { - if (!authority || readGeneration.current === generation) return; - readGeneration.current = generation; - let active = true; - void client.cancelQueries().then(async () => { - if (!active) return; - await client.invalidateQueries({ predicate: query => query.queryKey[1] !== 'inventory-permission' }); - const readable = client.getQueryCache().getAll().every(query => { - if (query.queryKey[1] !== 'inventory') return true; - const inventory = query.state.data as Inventory | undefined; - return query.state.status === 'success' && query.state.fetchStatus === 'idle' && !Object.keys(inventoryResources).every(kind => inventory?.issues?.[kind as InventoryKind]); - }); - if (active && readable) { - await client.invalidateQueries({ predicate: query => query.queryKey[1] === 'inventory-permission' }); - if (active) setReadyGeneration(generation); - } - }); - return () => { active = false; }; - }, [client, generation, authority]); useEffect(() => () => client.clear(), [client]); return {children}; } function HostedInventory({ children }: { children: ReactNode }) { const host = useContext(UNSAFE_DataRouterContext); - const [hostGeneration, setHostGeneration] = useState(0); const [sessionGeneration, setSessionGeneration] = useState(0); - const softRequested = useRef(false); useLayoutEffect(() => { if (!host) return; const readPrincipal = (state: typeof host.router.state) => { @@ -79,7 +53,6 @@ function HostedInventory({ children }: { children: ReactNode }) { }; let observedPrincipal = readPrincipal(host.router.state); let pending = host.router.state.revalidation !== 'idle' || host.router.state.navigation.state !== 'idle'; - let preserveCache = false; return host.router.subscribe(state => { const nextPrincipal = readPrincipal(state); if (nextPrincipal !== observedPrincipal) { @@ -87,15 +60,10 @@ function HostedInventory({ children }: { children: ReactNode }) { setSessionGeneration(current => current + 1); } if (state.revalidation !== 'idle' || state.navigation.state !== 'idle') { - if (!pending) { - preserveCache = softRequested.current; - setSoftVerification(preserveCache); - } pending = true; } else if (pending) { pending = false; - if (!preserveCache) setSessionGeneration(current => current + 1); - setHostGeneration(current => current + 1); + setSessionGeneration(current => current + 1); } }); }, [host]); @@ -108,76 +76,49 @@ function HostedInventory({ children }: { children: ReactNode }) { revalidate.current = revalidator.revalidate; const [checking, setChecking] = useState(() => typeof document !== 'undefined' && document.visibilityState === 'hidden'); const [failed, setFailed] = useState(false); - const [verifying, setVerifying] = useState(false); - const [focused, setFocused] = useState(true); - const [softVerification, setSoftVerification] = useState(false); - const masked = useRef(checking); const generation = useRef(0); - const foreground = useRef(true); useEffect(() => { let active = true; + let awaitingReturn = document.visibilityState === 'hidden'; const hide = () => { generation.current++; - foreground.current = false; - masked.current = true; - softRequested.current = false; - setFocused(false); - setSoftVerification(false); + awaitingReturn = true; setChecking(true); }; - const blur = () => { - generation.current++; - foreground.current = false; - setFocused(false); - if (document.visibilityState === 'hidden') hide(); - }; const verify = () => { - if (document.visibilityState === 'hidden') return; - foreground.current = true; - setFocused(true); + if (!awaitingReturn || document.visibilityState === 'hidden') return; + awaitingReturn = false; const attempt = ++generation.current; - setVerifying(true); - softRequested.current = !masked.current; - setSoftVerification(!masked.current); setFailed(false); let succeeded = true; void revalidate.current().catch(() => { succeeded = false; - if (active && attempt === generation.current && foreground.current) { - masked.current = true; + if (active && attempt === generation.current) { setChecking(true); setFailed(true); } }).finally(() => { - if (active && attempt === generation.current && foreground.current && document.visibilityState !== 'hidden') { - setVerifying(false); - softRequested.current = false; + if (active && attempt === generation.current && document.visibilityState !== 'hidden') { setChecking(!succeeded); - masked.current = !succeeded; } }); }; const visibility = () => document.visibilityState === 'hidden' ? hide() : verify(); - const restore = (event: PageTransitionEvent) => { if (event.persisted) verify(); }; - window.addEventListener('blur', blur); - window.addEventListener('focus', verify); window.addEventListener('pagehide', hide); - window.addEventListener('pageshow', restore); + window.addEventListener('pageshow', verify); document.addEventListener('visibilitychange', visibility); return () => { active = false; generation.current++; - window.removeEventListener('blur', blur); - window.removeEventListener('focus', verify); window.removeEventListener('pagehide', hide); - window.removeEventListener('pageshow', restore); + window.removeEventListener('pageshow', verify); document.removeEventListener('visibilitychange', visibility); }; }, []); if (failed) return ; - if (checking || (revalidator.state !== 'idle' && !softVerification) || navigation.state !== 'idle') return ; + if (checking || revalidator.state !== 'idle' || navigation.state !== 'idle') return ; if (!principal) return ; - return {children}; + return {children}; } export function InventorySessionBoundary({ children }: { children: ReactNode }) { diff --git a/ui/provider/src/components/inventory-stable-controls.test.tsx b/ui/provider/src/components/inventory-stable-controls.test.tsx index e6a0f8d6..35b44f26 100644 --- a/ui/provider/src/components/inventory-stable-controls.test.tsx +++ b/ui/provider/src/components/inventory-stable-controls.test.tsx @@ -1,4 +1,4 @@ -import { StrictMode, type ReactNode } from 'react'; +import { StrictMode, useContext, type ReactNode } from 'react'; import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'; import { createMemoryRouter, Outlet, RouterProvider } from 'react-router'; import { afterEach, expect, it, vi } from 'vitest'; @@ -7,6 +7,7 @@ import { DevicePlacementEdit } from './device-placement-edit'; import { InventorySessionBoundary } from './inventory-session-boundary'; import { inventoryPayload, INVENTORY_FIELD_MANAGER, type ManagedKind } from '../lib/inventory-management'; import { fixturePhysicalDevices } from '../lib/fixtures'; +import { InventoryOperationContext, type InventoryOperationScope } from '../lib/inventory-operation'; const values = { name: 'synthetic', namespace: 'default', displayName: 'Original', recordedBy: 'synthetic', reference: '', facility: '', height: '' }; const record = { ...inventoryPayload('Facility', values), metadata: { name: 'synthetic', namespace: 'default', uid: 'synthetic', resourceVersion: '1', managedFields: [{ manager: INVENTORY_FIELD_MANAGER }] } }; @@ -20,6 +21,11 @@ function host(content: ReactNode, strict = false) { let principal = 'staff-a'; let releaseHost: (() => void) | undefined; let releasePermission: (() => void) | undefined; + let scope: InventoryOperationScope | undefined; + function Content() { + scope = useContext(InventoryOperationContext); + return content; + } const writes = vi.fn(); const fetch = vi.fn(async (url: string, init: RequestInit) => { if (url.includes('selfsubjectaccessreviews')) { @@ -30,13 +36,14 @@ function host(content: ReactNode, strict = false) { return response(record); }); vi.stubGlobal('fetch', fetch); - const router = createMemoryRouter([{ id: 'layouts/milo.layout', path: '/', loader: async () => { + const loader = vi.fn(async () => { if (hold) await new Promise(resolve => { releaseHost = resolve; }); return { user: { metadata: { uid: principal } } }; - }, element: , children: [{ index: true, element: {content} }] }]); + }); + const router = createMemoryRouter([{ id: 'layouts/milo.layout', path: '/', loader, element: , children: [{ index: true, element: }] }]); render(strict ? : ); return { - router, writes, fetch, + router, writes, fetch, loader, operation: () => scope!.begin(), hold: () => { hold = true; }, deny: () => { allow = false; }, principal: (value: string) => { principal = value; }, releaseHost: async () => { await waitFor(() => expect(releaseHost).toBeDefined()); await act(async () => releaseHost!()); }, @@ -49,55 +56,45 @@ const cases = [...kinds.map(kind => ({ kind, mode: 'create', button: `Create ${k { kind: 'Facility' as const, mode: 'label', button: 'Edit display name' }, { kind: 'Device' as const, mode: 'location', button: 'Add reported location' }]; -it.each(cases.flatMap(test => [false, true].flatMap(strict => [false, true].map(expanded => ({ ...test, strict, expanded })))))('retains $mode $kind DOM and revokes baselines expanded=$expanded strict=$strict', async ({ kind, mode, button, strict, expanded }) => { +it.each(cases.flatMap(test => [false, true].flatMap(strict => [false, true].map(expanded => ({ ...test, strict, expanded })))))('visible blur/focus leaves $mode $kind unchanged expanded=$expanded strict=$strict', async ({ kind, mode, button, strict, expanded }) => { const view = host(mode === 'location' ? : , strict); await waitFor(() => expect(screen.getByRole('button', { name: button })).toBeEnabled()); const access = screen.queryByText(mode === 'label' ? 'Editing access' : 'Namespace & access')?.closest('details'); if (access && expanded) fireEvent.click(access.querySelector('summary')!); const opener = screen.getByRole('button', { name: button }); - view.hold(); + const operation = view.operation(); + const requests = view.fetch.mock.calls.length; + const loads = view.loader.mock.calls.length; + const closedMarkup = document.body.innerHTML; fireEvent(window, new Event('blur')); expect(screen.getByRole('button', { name: button })).toBe(opener); - expect(opener).toBeDisabled(); - const requests = view.fetch.mock.calls.length; - fireEvent.click(opener); - expect(view.fetch).toHaveBeenCalledTimes(requests); + expect(opener).toBeEnabled(); fireEvent(window, new Event('focus')); - await view.releaseHost(); - expect(screen.getByRole('button', { name: button })).toBe(opener); - expect(opener).toBeDisabled(); - expect(screen.getByRole('status')).toHaveTextContent('verification pending'); - await view.releasePermission(); - await waitFor(() => expect(opener).toBeEnabled()); + await act(async () => { await new Promise(resolve => setTimeout(resolve, 0)); }); + expect(document.body.innerHTML).toBe(closedMarkup); + expect(() => operation.assertCurrent()).not.toThrow(); fireEvent.click(opener); const input = screen.getByLabelText(mode === 'location' ? 'Correction reason' : 'Display name'); fireEvent.change(input, { target: { value: 'Safe draft' } }); - const form = input.closest('form')!; - view.hold(); - fireEvent(window, new Event('blur')); + const openMarkup = document.body.innerHTML; + for (let cycle = 0; cycle < 3; cycle++) { + fireEvent(window, new Event('blur')); + expect(input).toBeEnabled(); + fireEvent(window, new Event('focus')); + } + await act(async () => { await new Promise(resolve => setTimeout(resolve, 0)); }); expect(screen.getByLabelText(mode === 'location' ? 'Correction reason' : 'Display name')).toBe(input); - expect(input).toBeDisabled(); - fireEvent.submit(form); - fireEvent(window, new Event('focus')); - await view.releaseHost(); - expect(input).toBeDisabled(); - fireEvent.submit(form); - await view.releasePermission(); - const close = screen.getByRole('button', { name: mode === 'location' ? 'Close location form' : 'Close form' }); - await waitFor(() => expect(close).toBeEnabled()); + expect(document.body.innerHTML).toBe(openMarkup); expect(input).toHaveValue('Safe draft'); - expect(input).toBeDisabled(); - expect(screen.getByRole('status')).toHaveTextContent('close and reopen'); - fireEvent.submit(form); + expect(input).toBeEnabled(); + expect(() => operation.assertCurrent()).not.toThrow(); + expect(view.fetch).toHaveBeenCalledTimes(requests); + expect(view.loader).toHaveBeenCalledTimes(loads); expect(view.writes).not.toHaveBeenCalled(); if (access) { expect(screen.getByText(mode === 'label' ? 'Editing access' : 'Namespace & access').closest('details')).toBe(access); expect(access.open).toBe(expanded); } - fireEvent.click(close); - fireEvent.click(screen.getByRole('button', { name: button })); - expect(screen.getByLabelText(mode === 'location' ? 'Correction reason' : 'Display name')).toBeEnabled(); - if (mode === 'create') expect(screen.getByLabelText('Display name')).toHaveValue('Safe draft'); view.router.dispose(); }); @@ -114,7 +111,7 @@ it.each(['denied', 'principal', 'hidden', 'pagehide'])('removes retained private else { if (transition === 'denied') view.deny(); else view.principal('staff-b'); - fireEvent(window, new Event('focus')); + act(() => { void view.router.revalidate(); }); await view.releaseHost(); await view.releasePermission(); } diff --git a/ui/provider/src/components/inventory-visible-focus-save.test.tsx b/ui/provider/src/components/inventory-visible-focus-save.test.tsx new file mode 100644 index 00000000..8d3dac84 --- /dev/null +++ b/ui/provider/src/components/inventory-visible-focus-save.test.tsx @@ -0,0 +1,89 @@ +import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { createMemoryRouter, Outlet, RouterProvider } from 'react-router'; +import { afterEach, expect, it, vi } from 'vitest'; +import { InventoryManagement } from './inventory-management'; +import { DevicePlacementEdit } from './device-placement-edit'; +import { InventorySessionBoundary } from './inventory-session-boundary'; +import { inventoryPayload, INVENTORY_FIELD_MANAGER } from '../lib/inventory-management'; +import { fixturePhysicalDevices } from '../lib/fixtures'; + +const values = { name: 'synthetic', namespace: 'default', displayName: 'Original', recordedBy: 'synthetic', reference: '', facility: '', height: '' }; +const metadata = { name: 'synthetic', namespace: 'default', uid: 'synthetic', resourceVersion: '1', managedFields: [{ manager: INVENTORY_FIELD_MANAGER }] }; +const facility = { ...inventoryPayload('Facility', values), metadata }; +const device = { ...fixturePhysicalDevices[0], metadata, spec: { ...fixturePhysicalDevices[0].spec, reportedPlacement: undefined } }; +const response = (data: unknown) => ({ ok: true, status: 200, json: async () => ({ data }) }); +afterEach(() => { vi.unstubAllGlobals(); vi.restoreAllMocks(); }); + +it.each(['create', 'label', 'location'].flatMap(mode => ['review', 'read', 'dispatch'].filter(stage => mode !== 'create' || stage !== 'read').flatMap(stage => ['focus', 'hidden', 'principal'].map(transition => ({ mode, stage, transition })))))('$transition handles pending $mode $stage without transferring authority', async ({ mode, stage, transition }) => { + let release: (() => void) | undefined; + let reviews = 0; + let held = false; + const original = mode === 'location' ? device : facility; + const fetch = vi.fn(async (url: string, init: RequestInit) => { + const review = url.includes('selfsubjectaccessreviews'); + if (review) reviews++; + const write = !review && init.method !== 'GET'; + if (!held && ((stage === 'review' && review && reviews === 2) || (stage === 'read' && init.method === 'GET') || (stage === 'dispatch' && write))) { + held = true; + await new Promise(resolve => { release = resolve; }); + } + if (review) return response({ status: { allowed: true } }); + if (mode === 'location' && write) return response({ ...device, metadata: { ...metadata, resourceVersion: '2' }, spec: { ...device.spec, reportedPlacement: JSON.parse(init.body as string)[2].value } }); + return response(original); + }); + vi.stubGlobal('fetch', fetch); + let principal = 'staff-a'; + const loader = vi.fn(() => ({ user: { metadata: { uid: principal } } })); + const content = mode === 'location' ? : ; + const router = createMemoryRouter([{ id: 'layouts/milo.layout', path: '/', loader, element: , children: [{ index: true, element: {content} }] }]); + render(); + const opener = await screen.findByRole('button', { name: mode === 'location' ? 'Add reported location' : mode === 'label' ? 'Edit display name' : 'Create facility' }); + await waitFor(() => expect(opener).toBeEnabled()); + fireEvent.click(opener); + if (mode === 'location') { + fireEvent.change(screen.getByLabelText('Observation time (ISO 8601)'), { target: { value: '2026-01-02T00:00:00Z' } }); + fireEvent.change(screen.getByLabelText('Correction reason'), { target: { value: 'Synthetic correction' } }); + fireEvent.change(screen.getByLabelText('Evidence reference'), { target: { value: 'ticket/synthetic' } }); + } else { + if (mode === 'create') fireEvent.change(screen.getByLabelText('Record name'), { target: { value: 'synthetic' } }); + fireEvent.change(screen.getByLabelText('Display name'), { target: { value: 'New label' } }); + fireEvent.change(screen.getByLabelText('Recorded by'), { target: { value: 'synthetic' } }); + } + fireEvent.click(screen.getByRole('button', { name: mode === 'location' ? 'Save reported location' : mode === 'label' ? 'Save display name' : 'Create facility record' })); + await waitFor(() => expect(release).toBeDefined()); + if (transition !== 'focus') { + if (transition === 'hidden') { + const visibility = vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('hidden'); + fireEvent(document, new Event('visibilitychange')); + expect(opener).not.toBeInTheDocument(); + visibility.mockReturnValue('visible'); + fireEvent(document, new Event('visibilitychange')); + } else { + principal = 'staff-b'; + await act(async () => router.revalidate()); + } + await waitFor(() => expect(loader).toHaveBeenCalledTimes(2)); + await act(async () => release!()); + expect(opener).not.toBeInTheDocument(); + expect(screen.queryByText(/Reported location saved|Display name saved\.|Facility record created\./)).not.toBeInTheDocument(); + expect(screen.queryByLabelText(mode === 'location' ? 'Correction reason' : 'Display name')).not.toBeInTheDocument(); + expect(fetch.mock.calls.filter(([url, init]) => !url.includes('selfsubjectaccessreviews') && init.method !== 'GET')).toHaveLength(stage === 'dispatch' ? 1 : 0); + return; + } + const markup = document.body.innerHTML; + const requests = fetch.mock.calls.length; + fireEvent(window, new Event('blur')); + fireEvent(window, new Event('focus')); + await act(async () => { await new Promise(resolve => setTimeout(resolve, 0)); }); + expect(document.body.innerHTML).toBe(markup); + expect(fetch).toHaveBeenCalledTimes(requests); + expect(loader).toHaveBeenCalledTimes(1); + await act(async () => release!()); + await screen.findByText(mode === 'location' ? /Reported location saved/ : mode === 'label' ? 'Display name saved.' : 'Facility record created.'); + const writes = fetch.mock.calls.filter(([url, init]) => !url.includes('selfsubjectaccessreviews') && init.method !== 'GET'); + expect(writes).toHaveLength(1); + if (mode !== 'create') expect(JSON.parse(writes[0][1].body as string).slice(0, 2)).toEqual([ + { op: 'test', path: '/metadata/uid', value: 'synthetic' }, + { op: 'test', path: '/metadata/resourceVersion', value: '1' }, + ]); +}); diff --git a/ui/provider/src/components/pr103-review-negatives.test.tsx b/ui/provider/src/components/pr103-review-negatives.test.tsx index 7583189d..a11fbc3d 100644 --- a/ui/provider/src/components/pr103-review-negatives.test.tsx +++ b/ui/provider/src/components/pr103-review-negatives.test.tsx @@ -7,7 +7,7 @@ import { StrictMode } from 'react'; afterEach(() => { cleanup(); vi.unstubAllGlobals(); }); const response = (data: unknown) => ({ ok: true, status: 200, json: async () => ({ data }) }); -it.each([false, true])('does not publish new-principal reads while focus identity is unresolved strict=%s', async strict => { +it.each([false, true])('does not publish new-principal reads while explicit host identity is unresolved strict=%s', async strict => { let principal = 'staff-a'; let release: (() => void) | undefined; const requests = vi.fn(async (url: string) => { @@ -22,18 +22,20 @@ it.each([false, true])('does not publish new-principal reads while focus identit }, element: , children: [{ index: true, element: }] }], { initialEntries: ['/?kind=Facility'] }); render(strict ? : ); await screen.findByRole('link', { name: /Private staff-a/ }); + const refresh = screen.getByRole('button', { name: 'Refresh inventory' }); + const before = requests.mock.calls.length; principal = 'staff-b'; - fireEvent(window, new Event('blur')); - fireEvent(window, new Event('focus')); + act(() => { void router.revalidate(); }); await waitFor(() => expect(release).toBeDefined()); - fireEvent.click(screen.getByRole('button', { name: 'Refresh inventory' })); + fireEvent.click(refresh); await act(async () => { await new Promise(resolve => setTimeout(resolve, 30)); }); expect(router.state.loaderData['layouts/milo.layout'].user.metadata.uid).toBe('staff-a'); expect(screen.queryByRole('link', { name: /Private staff-b/ })).not.toBeInTheDocument(); + expect(requests).toHaveBeenCalledTimes(before); router.dispose(); }); -it.each(['visible', 'overlap', 'hidden', 'denied'])('renews management only after a fresh successful read: %s', async scenario => { +it.each(['revalidate', 'overlap', 'hidden', 'denied'])('renews management only after a genuine boundary and fresh successful read: %s', async scenario => { let holding = false; let denied = false; const releases: (() => void)[] = []; @@ -54,23 +56,18 @@ it.each(['visible', 'overlap', 'hidden', 'denied'])('renews management only afte const table = screen.getByRole('table'); fireEvent.click(screen.getByRole('button', { name: 'Create facility' })); fireEvent.change(screen.getByLabelText('Display name'), { target: { value: 'Abandoned old form' } }); - const input = screen.getByLabelText('Display name'); holding = true; if (scenario === 'hidden') { visibility.mockReturnValue('hidden'); fireEvent(document, new Event('visibilitychange')); expect(screen.queryByRole('table')).not.toBeInTheDocument(); visibility.mockReturnValue('visible'); - } else fireEvent(window, new Event('blur')); - fireEvent(window, new Event('focus')); + fireEvent(document, new Event('visibilitychange')); + } else act(() => { void router.revalidate(); }); await waitFor(() => expect(releases).toHaveLength(1)); - if (scenario === 'hidden') expect(screen.queryByLabelText('Display name')).not.toBeInTheDocument(); - else { - expect(screen.getByLabelText('Display name')).toBe(input); - expect(input).toBeDisabled(); - } + expect(screen.queryByLabelText('Display name')).not.toBeInTheDocument(); if (scenario === 'overlap') { - fireEvent(window, new Event('focus')); + act(() => { void router.revalidate(); }); await waitFor(() => expect(releases).toHaveLength(2)); await act(async () => releases[0]()); expect(screen.queryByRole('button', { name: 'Create facility' })).not.toBeInTheDocument(); @@ -82,19 +79,12 @@ it.each(['visible', 'overlap', 'hidden', 'denied'])('renews management only afte expect(screen.queryByRole('button', { name: 'Create facility' })).not.toBeInTheDocument(); denied = false; holding = false; - fireEvent(window, new Event('focus')); - } - if (scenario === 'visible' || scenario === 'overlap') { - await waitFor(() => expect(screen.getByRole('button', { name: 'Close form' })).toBeEnabled()); - expect(screen.getByRole('table')).toBe(table); - expect(screen.getByLabelText('Display name')).toBe(input); - expect(input).toBeDisabled(); - expect(screen.getByRole('button', { name: 'Create facility record' })).toBeDisabled(); - fireEvent.click(screen.getByRole('button', { name: 'Close form' })); + act(() => { void router.revalidate(); }); } await waitFor(() => expect(screen.getByRole('button', { name: 'Create facility' })).toBeEnabled()); + expect(screen.getByRole('table')).not.toBe(table); fireEvent.click(screen.getByRole('button', { name: 'Create facility' })); - expect(screen.getByLabelText('Display name')).toHaveValue(scenario === 'visible' || scenario === 'overlap' ? 'Abandoned old form' : ''); + expect(screen.getByLabelText('Display name')).toHaveValue(''); router.dispose(); visibility.mockRestore(); }); diff --git a/ui/provider/src/lib/api.ts b/ui/provider/src/lib/api.ts index 89d7225a..c91be52f 100644 --- a/ui/provider/src/lib/api.ts +++ b/ui/provider/src/lib/api.ts @@ -299,7 +299,7 @@ export function useInventory(): UseQueryResult { queryKey: [PLUGIN_ID, 'inventory', PROVIDER_PROJECT, view], queryFn: read, refetchInterval: false, - refetchOnWindowFocus: 'always', + refetchOnWindowFocus: false, gcTime: 0, retry: false, }); From 11778ec901812747ad7cb5e915f6c7658836bc04 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sat, 21 Nov 2026 18:13:00 -0600 Subject: [PATCH 047/518] feat(inventory)!: remove provenance and NetBox import support Fleet's physical inventory API no longer records where its records came from. Resource audit logs say who changed a record and metadata.creationTimestamp says when it was created; a writer that needs to remember the origin of its facts keeps that on its own labels and annotations. API and CRDs (still served and stored as v1alpha1): - Drop spec.provenance (Provenance, ProvenanceManual, SourceReference) from all seven kinds, including PhysicalMetadata. - Drop Device identity.sourceIdentity; identity now requires a serial or system UUID. - Drop component sourceRef on Device components and PowerFeed terminations. ExternalReference stays for providerHostRef, serviceRef and upstreamSources. - Drop reportedPlacement.method and snapshotDigest and the CEL rules tying a report to imported provenance; reason and reference are now required. - Replace the "Recorded At" printer column with Age. Stored objects need no migration: the structural schemas prune the removed fields on read and write, and a new test pins that behavior. Remove the offline NetBox importer, the placement enrichment planner, their tests and fixtures, the CI step, the operations guide, and the ignore entry for its local token file. The staff UI no longer shows, asks for or writes provenance, recorder, source reports or NetBox labels; it shows creation time instead. Docs describe the new contract and the compatibility note. BREAKING CHANGE: writers must stop sending spec.provenance, identity.sourceIdentity, component sourceRef and reportedPlacement method/snapshotDigest. Clients that use strict field validation are rejected if they still send them; others get an unknown-field warning. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 1 - .gitignore | 1 - .../inventory/crds/fleet.datumapis.com.yaml | 556 ++---------- docs/development/README.md | 19 +- docs/development/device-reported-placement.md | 98 +-- .../development/site-facility-relationship.md | 82 +- docs/development/staff-inventory-ui.md | 26 +- docs/operations/README.md | 3 +- docs/operations/netbox-physical-import.md | 280 ------ docs/operations/physical-inventory-staging.md | 14 +- docs/operations/physical-inventory.md | 71 +- docs/proposals/fleet-management/MIGRATION.md | 17 +- .../fleet-management/inventory-reference.md | 121 +-- docs/proposals/fleet-management/inventory.md | 19 +- hack/device_placement.py | 160 ---- hack/netbox_inventory.py | 797 ------------------ hack/test_device_placement.py | 118 --- hack/test_netbox_inventory.py | 511 ----------- hack/test_pr100_independent.py | 44 - hack/testdata/netbox/candidates.json | 475 ----------- hack/testdata/netbox/existing.json | 17 - hack/testdata/netbox/mapping.json | 68 -- hack/testdata/netbox/snapshot.json | 209 ----- hack/testdata/physical/manual.yaml | 24 - internal/api/inventory/v1alpha1/crd_test.go | 137 ++- internal/api/inventory/v1alpha1/physical.go | 25 +- .../api/inventory/v1alpha1/physical_test.go | 48 +- .../v1alpha1/reported_placement_test.go | 132 +-- internal/api/inventory/v1alpha1/site_test.go | 4 +- internal/api/inventory/v1alpha1/types.go | 51 +- ui/provider/README.md | 23 +- .../components/adversarial-review.test.tsx | 7 +- .../components/device-placement-edit.test.tsx | 10 +- .../src/components/device-placement-edit.tsx | 2 +- .../exact-head-independent.test.tsx | 5 +- .../inventory-hardware-fields.test.tsx | 2 +- .../components/inventory-location.test.tsx | 2 +- .../src/components/inventory-location.tsx | 2 +- .../inventory-management-lifetime.test.tsx | 5 +- .../components/inventory-management.test.tsx | 2 - .../src/components/inventory-management.tsx | 9 +- .../inventory-navigation-safety.test.tsx | 5 +- .../components/inventory-read-access.test.tsx | 2 +- .../inventory-revalidation-safety.test.tsx | 5 +- .../src/components/physical-inventory.tsx | 29 +- .../pr103-review-negatives.test.tsx | 4 +- .../src/components/site-inventory.test.tsx | 5 +- ui/provider/src/inventory.test.ts | 3 +- ui/provider/src/inventory.ts | 6 +- .../src/lib/device-placement-edit.test.ts | 14 +- ui/provider/src/lib/device-placement-edit.ts | 9 +- ui/provider/src/lib/device-placement.test.ts | 2 +- ui/provider/src/lib/fixtures.ts | 21 +- .../src/lib/inventory-hardware.test.ts | 10 +- ui/provider/src/lib/inventory-hardware.ts | 4 +- .../src/lib/inventory-management.test.ts | 13 +- ui/provider/src/lib/inventory-management.ts | 16 +- .../src/lib/inventory-operation.test.ts | 4 +- ui/provider/src/lib/site-membership.test.ts | 5 +- ui/provider/src/pages/device-claim-detail.tsx | 22 +- .../src/pages/device-inventory.test.tsx | 9 +- ui/shared/fleet-api.ts | 20 +- 62 files changed, 485 insertions(+), 3920 deletions(-) delete mode 100644 docs/operations/netbox-physical-import.md delete mode 100644 hack/device_placement.py delete mode 100644 hack/netbox_inventory.py delete mode 100644 hack/test_device_placement.py delete mode 100644 hack/test_netbox_inventory.py delete mode 100644 hack/test_pr100_independent.py delete mode 100644 hack/testdata/netbox/candidates.json delete mode 100644 hack/testdata/netbox/existing.json delete mode 100644 hack/testdata/netbox/mapping.json delete mode 100644 hack/testdata/netbox/snapshot.json diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 957de3ce..27b179fb 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -21,7 +21,6 @@ jobs: - run: go test ./... - run: go test -race ./... - run: go vet ./... - - run: python3 -m unittest discover -s hack -p test_netbox_inventory.py - run: go run ./test/acceptance/milo/cmd validate --root . - run: kustomize build config/base/crd >/dev/null - run: kustomize build config/milo >/dev/null diff --git a/.gitignore b/.gitignore index 710fb1db..f0b5f928 100644 --- a/.gitignore +++ b/.gitignore @@ -13,7 +13,6 @@ /kubeconfig /kubeconfig.* /talosconfig -/netbox.txt /servers.com.txt # Local outputs and scratch work diff --git a/config/components/inventory/crds/fleet.datumapis.com.yaml b/config/components/inventory/crds/fleet.datumapis.com.yaml index 54478179..c4d08a6c 100644 --- a/config/components/inventory/crds/fleet.datumapis.com.yaml +++ b/config/components/inventory/crds/fleet.datumapis.com.yaml @@ -31,9 +31,9 @@ spec: - name: Model type: string jsonPath: .spec.expectedIdentity.model - - name: Recorded At + - name: Age type: date - jsonPath: .spec.provenance.recordedAt + jsonPath: .metadata.creationTimestamp schema: openAPIV3Schema: type: object @@ -61,67 +61,6 @@ spec: - rule: has(self.lifecycle) == has(self.placement.scope) message: typed placement requires an installation lifecycle; legacy slots keep their text placement properties: - provenance: - type: object - required: - - method - - recordedBy - - recordedAt - properties: - method: - type: string - enum: - - Manual - - NetBoxImport - recordedBy: - type: string - minLength: 1 - maxLength: 253 - recordedAt: - type: string - format: date-time - reference: - type: string - minLength: 1 - maxLength: 1024 - source: - type: object - properties: - system: - type: string - minLength: 1 - maxLength: 253 - type: - type: string - minLength: 1 - maxLength: 253 - id: - type: string - minLength: 1 - maxLength: 253 - snapshotDigest: - type: string - pattern: ^sha256:[a-f0-9]{64}$ - mappingRevision: - type: string - minLength: 1 - maxLength: 253 - observedAt: - type: string - format: date-time - required: - - system - - type - - id - - snapshotDigest - - mappingRevision - - observedAt - x-kubernetes-validations: - - rule: self.method != 'NetBoxImport' || has(self.source) - message: NetBox imports require source provenance - - rule: has(self.source) == has(oldSelf.source) && (!has(self.source) || (self.source.system == - oldSelf.source.system && self.source.type == oldSelf.source.type && self.source.id == oldSelf.source.id)) - message: source identity is immutable expectedIdentity: type: object required: @@ -284,9 +223,9 @@ spec: type: string priority: 1 jsonPath: .spec.identity.systemUUID - - name: Recorded At + - name: Age type: date - jsonPath: .spec.provenance.recordedAt + jsonPath: .metadata.creationTimestamp schema: openAPIV3Schema: type: object @@ -314,14 +253,10 @@ spec: - rule: '!has(self.reportedPlacement) || (oldSelf.hasValue() && has(oldSelf.value().reportedPlacement) ? (self.reportedPlacement == oldSelf.value().reportedPlacement || self.reportedPlacement.revision == oldSelf.value().reportedPlacement.revision + 1) : self.reportedPlacement.revision == 1)' optionalOldSelf: true message: first report revision must be 1; every changed report must increment revision exactly once - - rule: '!has(self.reportedPlacement) || !has(self.provenance) || (has(self.reportedPlacement.method) && self.reportedPlacement.method == "Manual") || (has(self.identity.sourceIdentity) && has(self.provenance.source) && self.provenance.method == "NetBoxImport" && has(self.reportedPlacement.snapshotDigest) && self.reportedPlacement.observedAt == self.provenance.source.observedAt && self.reportedPlacement.snapshotDigest == self.provenance.source.snapshotDigest)' - message: reported placement must retain the imported source snapshot and observation time - rule: '!has(self.interfaces) || self.interfaces.all(a, !has(a.macAddress) || (self.interfaces.filter(b, has(b.macAddress) && b.macAddress == a.macAddress).size() == 1 && (!has(self.unmappedMACAddresses) || !(a.macAddress in self.unmappedMACAddresses))))' message: a MAC address may be recorded only once - - rule: '!has(self.identity.sourceIdentity) || !has(self.provenance) || self.provenance.method == "NetBoxImport"' - message: source identity is for observational imports only - rule: '!has(self.topologyAuthority) || !has(self.interfaces) || self.interfaces.all(p, !has(p.peer))' message: Cable topology excludes inline peers - rule: '!has(self.components) || has(self.topologyAuthority)' @@ -334,10 +269,6 @@ spec: - rule: '!has(self.internalMappings) || self.internalMappings.all(m, self.internalMappings.filter(n, n.from == m.from).size() == 1)' message: each internal source position maps once - - rule: '!has(self.identity.sourceIdentity) || !has(self.provenance) || (has(self.provenance.source) && self.identity.sourceIdentity.system - == self.provenance.source.system && self.identity.sourceIdentity.type == self.provenance.source.type - && self.identity.sourceIdentity.id == self.provenance.source.id)' - message: observational identity must match provenance source identity - rule: '!has(self.internalMappings) || (has(self.components) && self.internalMappings.all(m, self.components.exists(c, c.id == m.from.componentID && c.type == ''FrontPort'') ? self.components.exists(c, c.id == m.to.componentID && c.type == ''RearPort'') : (self.components.exists(c, c.id == m.from.componentID && c.type == @@ -353,10 +284,8 @@ spec: properties: reportedPlacement: type: object - required: [revision, observedAt] + required: [revision, observedAt, reason, reference] x-kubernetes-validations: - - rule: 'has(self.method) && self.method == "Manual" ? (has(self.reason) && has(self.reference) && !has(self.snapshotDigest)) : has(self.snapshotDigest)' - message: manual reports require reason and evidence reference, not an imported snapshot digest - rule: '(!has(self.position) && !has(self.height) && !has(self.face) && !has(self.fullDepth) && !has(self.mount)) || has(self.rackRef)' message: rack geometry requires a reported rack - rule: '!has(self.mount) || (!has(self.position) && !has(self.height) && !has(self.face) && !has(self.fullDepth))' @@ -368,9 +297,6 @@ spec: type: integer minimum: 1 maximum: 2147483647 - method: - type: string - enum: [Manual, NetBoxImport] reason: type: string minLength: 1 @@ -384,9 +310,6 @@ spec: observedAt: type: string format: date-time - snapshotDigest: - type: string - pattern: ^sha256:[a-f0-9]{64}$ facilityRef: type: object required: [name] @@ -430,74 +353,13 @@ spec: type: string minLength: 1 maxLength: 253 - provenance: - type: object - required: - - method - - recordedBy - - recordedAt - properties: - method: - type: string - enum: - - Manual - - NetBoxImport - recordedBy: - type: string - minLength: 1 - maxLength: 253 - recordedAt: - type: string - format: date-time - reference: - type: string - minLength: 1 - maxLength: 1024 - source: - type: object - properties: - system: - type: string - minLength: 1 - maxLength: 253 - type: - type: string - minLength: 1 - maxLength: 253 - id: - type: string - minLength: 1 - maxLength: 253 - snapshotDigest: - type: string - pattern: ^sha256:[a-f0-9]{64}$ - mappingRevision: - type: string - minLength: 1 - maxLength: 253 - observedAt: - type: string - format: date-time - required: - - system - - type - - id - - snapshotDigest - - mappingRevision - - observedAt - x-kubernetes-validations: - - rule: self.method != 'NetBoxImport' || has(self.source) - message: NetBox imports require source provenance - - rule: has(self.source) == has(oldSelf.source) && (!has(self.source) || (self.source.system == - oldSelf.source.system && self.source.type == oldSelf.source.type && self.source.id == oldSelf.source.id)) - message: source identity is immutable identity: type: object required: - model x-kubernetes-validations: - - rule: has(self.serial) || has(self.systemUUID) || has(self.sourceIdentity) - message: a device needs serial, UUID, or an observational source identity + - rule: has(self.serial) || has(self.systemUUID) + message: a device needs a serial or system UUID properties: manufacturer: type: string @@ -513,25 +375,6 @@ spec: systemUUID: type: string pattern: ^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$ - sourceIdentity: &id001 - type: object - properties: - system: - type: string - minLength: 1 - maxLength: 253 - type: - type: string - minLength: 1 - maxLength: 253 - id: - type: string - minLength: 1 - maxLength: 253 - required: - - system - - type - - id bmc: type: object required: @@ -589,7 +432,25 @@ spec: type: string minLength: 1 maxLength: 253 - providerHostRef: *id001 + providerHostRef: + type: object + properties: + system: + type: string + minLength: 1 + maxLength: 253 + type: + type: string + minLength: 1 + maxLength: 253 + id: + type: string + minLength: 1 + maxLength: 253 + required: + - system + - type + - id components: type: array maxItems: 256 @@ -633,7 +494,6 @@ spec: type: string minLength: 1 maxLength: 253 - sourceRef: *id001 required: - id - name @@ -671,7 +531,25 @@ spec: items: type: object properties: - serviceRef: *id001 + serviceRef: + type: object + properties: + system: + type: string + minLength: 1 + maxLength: 253 + type: + type: string + minLength: 1 + maxLength: 253 + id: + type: string + minLength: 1 + maxLength: 253 + required: + - system + - type + - id componentID: type: string minLength: 1 @@ -736,67 +614,6 @@ spec: type: string minLength: 1 maxLength: 253 - provenance: - type: object - required: - - method - - recordedBy - - recordedAt - properties: - method: - type: string - enum: - - Manual - - NetBoxImport - recordedBy: - type: string - minLength: 1 - maxLength: 253 - recordedAt: - type: string - format: date-time - reference: - type: string - minLength: 1 - maxLength: 1024 - source: - type: object - properties: - system: - type: string - minLength: 1 - maxLength: 253 - type: - type: string - minLength: 1 - maxLength: 253 - id: - type: string - minLength: 1 - maxLength: 253 - snapshotDigest: - type: string - pattern: ^sha256:[a-f0-9]{64}$ - mappingRevision: - type: string - minLength: 1 - maxLength: 253 - observedAt: - type: string - format: date-time - required: - - system - - type - - id - - snapshotDigest - - mappingRevision - - observedAt - x-kubernetes-validations: - - rule: self.method != 'NetBoxImport' || has(self.source) - message: NetBox imports require source provenance - - rule: has(self.source) == has(oldSelf.source) && (!has(self.source) || (self.source.system == - oldSelf.source.system && self.source.type == oldSelf.source.type && self.source.id == oldSelf.source.id)) - message: source identity is immutable identifiers: type: array maxItems: 64 @@ -871,67 +688,6 @@ spec: type: string minLength: 1 maxLength: 253 - provenance: - type: object - required: - - method - - recordedBy - - recordedAt - properties: - method: - type: string - enum: - - Manual - - NetBoxImport - recordedBy: - type: string - minLength: 1 - maxLength: 253 - recordedAt: - type: string - format: date-time - reference: - type: string - minLength: 1 - maxLength: 1024 - source: - type: object - properties: - system: - type: string - minLength: 1 - maxLength: 253 - type: - type: string - minLength: 1 - maxLength: 253 - id: - type: string - minLength: 1 - maxLength: 253 - snapshotDigest: - type: string - pattern: ^sha256:[a-f0-9]{64}$ - mappingRevision: - type: string - minLength: 1 - maxLength: 253 - observedAt: - type: string - format: date-time - required: - - system - - type - - id - - snapshotDigest - - mappingRevision - - observedAt - x-kubernetes-validations: - - rule: self.method != 'NetBoxImport' || has(self.source) - message: NetBox imports require source provenance - - rule: has(self.source) == has(oldSelf.source) && (!has(self.source) || (self.source.system == - oldSelf.source.system && self.source.type == oldSelf.source.type && self.source.id == oldSelf.source.id)) - message: source identity is immutable code: type: string minLength: 1 @@ -994,67 +750,6 @@ spec: type: string minLength: 1 maxLength: 253 - provenance: - type: object - required: - - method - - recordedBy - - recordedAt - properties: - method: - type: string - enum: - - Manual - - NetBoxImport - recordedBy: - type: string - minLength: 1 - maxLength: 253 - recordedAt: - type: string - format: date-time - reference: - type: string - minLength: 1 - maxLength: 1024 - source: - type: object - properties: - system: - type: string - minLength: 1 - maxLength: 253 - type: - type: string - minLength: 1 - maxLength: 253 - id: - type: string - minLength: 1 - maxLength: 253 - snapshotDigest: - type: string - pattern: ^sha256:[a-f0-9]{64}$ - mappingRevision: - type: string - minLength: 1 - maxLength: 253 - observedAt: - type: string - format: date-time - required: - - system - - type - - id - - snapshotDigest - - mappingRevision - - observedAt - x-kubernetes-validations: - - rule: self.method != 'NetBoxImport' || has(self.source) - message: NetBox imports require source provenance - - rule: has(self.source) == has(oldSelf.source) && (!has(self.source) || (self.source.system == - oldSelf.source.system && self.source.type == oldSelf.source.type && self.source.id == oldSelf.source.id)) - message: source identity is immutable facilityRef: type: object properties: @@ -1113,67 +808,6 @@ spec: type: string minLength: 1 maxLength: 253 - provenance: - type: object - required: - - method - - recordedBy - - recordedAt - properties: - method: - type: string - enum: - - Manual - - NetBoxImport - recordedBy: - type: string - minLength: 1 - maxLength: 253 - recordedAt: - type: string - format: date-time - reference: - type: string - minLength: 1 - maxLength: 1024 - source: - type: object - properties: - system: - type: string - minLength: 1 - maxLength: 253 - type: - type: string - minLength: 1 - maxLength: 253 - id: - type: string - minLength: 1 - maxLength: 253 - snapshotDigest: - type: string - pattern: ^sha256:[a-f0-9]{64}$ - mappingRevision: - type: string - minLength: 1 - maxLength: 253 - observedAt: - type: string - format: date-time - required: - - system - - type - - id - - snapshotDigest - - mappingRevision - - observedAt - x-kubernetes-validations: - - rule: self.method != 'NetBoxImport' || has(self.source) - message: NetBox imports require source provenance - - rule: has(self.source) == has(oldSelf.source) && (!has(self.source) || (self.source.system == - oldSelf.source.system && self.source.type == oldSelf.source.type && self.source.id == oldSelf.source.id)) - message: source identity is immutable medium: type: string enum: @@ -1293,67 +927,6 @@ spec: type: string minLength: 1 maxLength: 253 - provenance: - type: object - required: - - method - - recordedBy - - recordedAt - properties: - method: - type: string - enum: - - Manual - - NetBoxImport - recordedBy: - type: string - minLength: 1 - maxLength: 253 - recordedAt: - type: string - format: date-time - reference: - type: string - minLength: 1 - maxLength: 1024 - source: - type: object - properties: - system: - type: string - minLength: 1 - maxLength: 253 - type: - type: string - minLength: 1 - maxLength: 253 - id: - type: string - minLength: 1 - maxLength: 253 - snapshotDigest: - type: string - pattern: ^sha256:[a-f0-9]{64}$ - mappingRevision: - type: string - minLength: 1 - maxLength: 253 - observedAt: - type: string - format: date-time - required: - - system - - type - - id - - snapshotDigest - - mappingRevision - - observedAt - x-kubernetes-validations: - - rule: self.method != 'NetBoxImport' || has(self.source) - message: NetBox imports require source provenance - - rule: has(self.source) == has(oldSelf.source) && (!has(self.source) || (self.source.system == - oldSelf.source.system && self.source.type == oldSelf.source.type && self.source.id == oldSelf.source.id)) - message: source identity is immutable facilityRef: &id001 type: object properties: @@ -1432,25 +1005,6 @@ spec: type: string minLength: 1 maxLength: 253 - sourceRef: &id002 - type: object - properties: - system: - type: string - minLength: 1 - maxLength: 253 - type: - type: string - minLength: 1 - maxLength: 253 - id: - type: string - minLength: 1 - maxLength: 253 - required: - - system - - type - - id required: - id - name @@ -1462,7 +1016,25 @@ spec: upstreamSources: type: array maxItems: 64 - items: *id002 + items: + type: object + properties: + system: + type: string + minLength: 1 + maxLength: 253 + type: + type: string + minLength: 1 + maxLength: 253 + id: + type: string + minLength: 1 + maxLength: 253 + required: + - system + - type + - id required: - displayName - facilityRef diff --git a/docs/development/README.md b/docs/development/README.md index d68bfcb6..76119506 100644 --- a/docs/development/README.md +++ b/docs/development/README.md @@ -762,23 +762,20 @@ in the provider project in Milo. `config/components/inventory` holds their CRDs, ProtectedResources, and the `fleet.datumapis.com-inventory-viewer` and `-editor` roles. Only `config/milo` includes it. -CEL requires `Manual` or source-attributed `NetBoxImport` provenance and every edit to -advance `recordedAt`. It keeps a Device's `claimRef` and identity immutable, +Records carry no attribution fields: resource audit logs record who changed a +record and `metadata.creationTimestamp` records when it was created. CEL requires +a Device serial or system UUID and keeps a Device's `claimRef` and identity immutable, rejects duplicate or ambiguous MACs, and accepts only credential-free `https` BMC endpoints. Status is a reserved subresource with no fields and no writer. No metal role grants inventory access. The staff portal plugin's read-only Inventory tab pages through all six kinds, -shows physical relationships and components, and can inspect a private import -report locally. Multiple historical bindings remain ambiguous rather than being +shows physical relationships and components. Multiple historical bindings remain ambiguous rather than being resolved by edit time. The primary workflow is [manual entry and review](../operations/physical-inventory.md#manually-record-a-small-installation) -through the existing Flux writer, with no NetBox dependency. The optional, -operator-invoked standard-library `hack/netbox_inventory.py` reads GET-only snapshots -and generates offline review candidates; it never applies, schedules, synchronizes, -deletes or changes Git. Unit tests run API-server validation offline, -check IAM and exercise pagination, source conflicts, omissions and interrupted -imports. See [safe NetBox evaluation](../operations/netbox-physical-import.md). -No live source coverage, deployment of this physical extension, physical verification, concurrent +through the existing Flux writer. Fleet reads no external inventory source; a +separate writer that copies records in uses the same API and validation. Unit +tests run API-server validation offline, including pruning of retired fields, +and check IAM. No deployment of this physical extension, physical verification, concurrent reservation, deletion safety, adoption or new hardware-effect path is established. ## Build, test, and run diff --git a/docs/development/device-reported-placement.md b/docs/development/device-reported-placement.md index 091d17c1..b5858cac 100644 --- a/docs/development/device-reported-placement.md +++ b/docs/development/device-reported-placement.md @@ -1,6 +1,6 @@ # Device-reported placement -[Physical inventory](../operations/physical-inventory.md) · [Staff inventory UI](staff-inventory-ui.md) · [Optional NetBox review](../operations/netbox-physical-import.md) +[Physical inventory](../operations/physical-inventory.md) · [Staff inventory UI](staff-inventory-ui.md) ## Implemented contract @@ -10,48 +10,41 @@ Authorized managers can add the first report or correct an existing report using ordinary direct API PATCH/PUT. A reported location can change without a new or superseded installation. This is record correction, **not acceptance of a physical move, handover, reservation, verified occupancy, availability, or active binding**. -Device identity (including source identity) and claimRef remain immutable. Typed +Device identity and claimRef remain immutable. Typed claim lifecycle and placement constraints remain unchanged. No hardware, status, capacity, provisioning, allocator, network, IPAM, or routing effects are introduced. The first report has `revision: 1`; every changed report increments revision by -exactly one. Unchanged reports need no increment. Every changed Device spec still -advances `provenance.recordedAt`. A report cannot be removed; correcting all its +exactly one. Unchanged reports need no increment. A report cannot be removed; correcting all its location fields to unknown retains its revision and evidence. The report is the **latest snapshot, not append-only history**. Resource audit logs, not a second per-Device history or bespoke correction service, are the history integration. -Reports have `observedAt`, optional `facilityRef`/`rackRef`, and independently -optional `position`, `height`, `face`, `fullDepth`, or a non-unit `mount`. -Omission means unknown. Neither the editor nor importer infers actual geometry -from a model or claim. The importer retains model shape separately. Positive +Reports have `observedAt`, a required `reason` and evidence `reference`, optional +`facilityRef`/`rackRef`, and independently optional `position`, `height`, `face`, +`fullDepth`, or a non-unit `mount`. Omission means unknown. The editor does not +infer actual geometry from a model or claim. Positive fractional position/height is valid but only complete integral in-range geometry is drawn in an elevation. Position is 1–100; height is greater than zero and at most 100; position + height cannot exceed 101. Geometry requires a rack, and mount -and unit geometry are mutually exclusive. Observation cannot postdate recording; -a correction may cite an older observation. Name-only references are local to the +and unit geometry are mutually exclusive. A correction may cite an older +observation. Name-only references are local to the Device namespace. There is no new cross-object admission or reference transaction: CEL cannot verify existence, incarnation, actual rack height, or facility/rack agreement. The editor re-reads selected locations and checks those facts before dispatch, but a referenced object can subsequently change. -### Report source and original import provenance - -- `method: Manual` requires nonblank `reason` and `reference` (evidence), each at - most 1024 characters, and forbids `snapshotDigest`. A human correction of an - imported Device is attributed to manual observation, **not NetBox authorship**. -- `method: NetBoxImport` requires the matching imported identity, observation - time and snapshot digest in Device provenance. Legacy reports without `method` - retain these same import semantics. Existing revision-1 reports remain valid. -- Imported Devices retain `provenance.method: NetBoxImport` and immutable source - system/type/id matching `identity.sourceIdentity`. The editor changes only - `reportedPlacement` and `provenance.recordedAt`; original source digest, source - observation, mapping revision, recordedBy, identity and claimRef are preserved. - A separately reviewed fresh-source import can advance source evidence without - changing its system/type/id. `recordedBy` is client attribution, never an - authenticated actor or authorization grant. +### Report evidence + +- `reason` and `reference` (evidence) are required and nonblank, each at most + 1024 characters. A report does not say which writer or system produced it: + resource audit logs record who wrote it, and a writer that needs to remember + where the facts came from uses its own labels and annotations. - Old objects without reports remain valid on creation and unchanged updates. No migration, delete/recreate, identity replacement or claim rebind is required. + Earlier reports may have carried `method` or `snapshotDigest`; the API server + prunes those fields. A stored report without `reason` or `reference` must gain + both the next time it changes. ## Authorization and UI @@ -59,17 +52,17 @@ The existing manager role grants create/update/patch for six inventory kinds project-wide; this change adds **no privilege**, delete/status or hardware grant. It does not introduce owner or namespace isolation. Managed-field/Flux markers are a UI/migration exclusion for legacy GitOps records, not server authorization. -Imported operator-managed records are eligible for ordinary manager corrections. +Operator-managed records are eligible for ordinary manager corrections. Absence of a marker does not prove ownership, and direct API RBAC still applies. The separate display-name editor retains its older, narrower UI policy. -Device detail offers **Add reported location** or **Correct location**, manual -source explanation, evidence/reason, observation time, unknown geometry and +Device detail offers **Add reported location** or **Correct location**, an +evidence reference and reason, observation time, unknown geometry and optional readable facility/rack choices. Forms freeze the target UID and resourceVersion on open. Saving renews exact patch permission and re-reads the Device and selected references, checking operation authority after every awaited prerequisite, including failed reads. JSON Patch tests UID and resourceVersion -**before** adding the report and advancing recordedAt. Stale baselines, replacement, +**before** adding the report. Stale baselines, replacement, session switches, blur, navigation, revalidation and unmount cannot authorize a new dispatch. Rejected patch admission/preconditions require reopening the form. @@ -108,57 +101,12 @@ patch and response through Activity after deployment, plus actual retention and delivery configuration. Do not claim full change-body history until then. This specific logging integration gap does not disable ordinary authorized edits. -## Prepare-only enrichment - -For new candidates, `includeReportedPlacement: true` still explicitly opts in -per Device; default importer output is unchanged. Existing-record enrichment is -prepared with: - -```sh -python3 hack/device_placement.py \ - --snapshot /private/tmp/review/source.json \ - --target /private/tmp/review/target.json \ - --allowlist /private/tmp/review/allowlist.json \ - --output /private/tmp/review/prepared -``` - -Target contains `target: {project, namespace}`, `observedAt` from the actual fresh -read and `items`. Allowlist has exactly `source` (source system), `target`, and -`devices`, each with `name`, `namespace`, `uid`, `resourceVersion`, `sourceID`. -Source and target reads must be no more than 15 minutes old and not future-dated. -Preparation binds source/target/allowlist/patch digests, exact before/proposed-after, -UID/resourceVersion tests, dependency snapshots and the server dry-run query. -Output remains `executable: false`, `applied: false`; no API client exists here. -It rejects duplicate selections/source IDs, stale/replaced targets, incomplete -sources, source/rack contradictions, Flux references, legacy/positioned claims, -null source positions and rack overflow. It only prepares first-report enrichment -for already imported RackMembership Devices; claims themselves never change. - -The private cohort review is retained outside Git. Existing counts, capacity, -memberships and legacy Flux records must remain unchanged. Null-position PDUs -are not selected and must not acquire guessed position, height or depth. Retained -source/target snapshots are **not fresh execution inputs**. After independent -review and deployment, refresh reads, validate the exact private source/name/ -position/face allowlist, confirm the deployed head/schema, retain operation -authority, and server-dry-run each exact patch. Separately approve one canary; -read back its UID and exact spec and inspect its resource audit event before the -remainder. Recheck reference UID/resourceVersion before each future dispatch. - -The readback helper classifies exact expected state as Applied, exact unchanged -baseline as Unchanged (never automatic retry), mismatched incarnation/competing -state as Conflict, and unavailable reads as Unknown. A later apply workflow must -reconcile every uncertain dispatch. Never delete, recreate, rebind or prune the -report schema as rollback. This implementation performs **no live writes or -deployment** and does not renew a past authorization to execute migration. - ## Validation scope ```sh go test ./internal/api/inventory/v1alpha1 go test ./... go test -race ./internal/api/inventory/v1alpha1 ./internal/controller/... -python3 -m unittest discover -s hack -p 'test_netbox_inventory.py' -python3 -m unittest discover -s hack -p 'test_device_placement.py' pnpm --dir ui/provider test pnpm --dir ui/provider typecheck pnpm --dir ui/provider build @@ -169,7 +117,7 @@ bash hack/validate-doc-links.sh git diff --check ``` -Local CEL/schema, JSON Patch, IAM configuration, mocked API/editor and planner +Local CEL/schema, JSON Patch, IAM configuration, mocked API/editor tests verify the implemented contracts and regressions. They do not prove live IAM enforcement, deployed audit coverage, browser acceptance, cross-object transactions or readiness to operate hardware. diff --git a/docs/development/site-facility-relationship.md b/docs/development/site-facility-relationship.md index 2f8fe01c..e9513d71 100644 --- a/docs/development/site-facility-relationship.md +++ b/docs/development/site-facility-relationship.md @@ -7,7 +7,7 @@ This additive implementation starts from staging feature revision `0bc37cf23ca949df97b6ede8bc78f2a71c670ac4`. It adds an operator-written `Site` record, Facility premises identifiers, observational readers, IAM declarations, -staff directory views and an offline import option. It does not install these +and staff directory views. It does not install these changes, mutate live records or assert authenticated staging acceptance. The clarification **Datum Site DFW3 relates to DataBank premises DFW1** describes @@ -45,7 +45,7 @@ resource, provider metro code, account grouping, or Location readiness claim. every device, installation, allocation, or NodeClaim there to that Site. Per-consumer operational membership remains with its future owning contract. - Site and Facility are namespaced provider-project inventory records with the - same explicit direct-API writer and provenance discipline. This adds no mapping + same explicit direct-API writer discipline. This adds no mapping service, controller, synchronization owner, or GitOps ownership for records. ## Stable identity and references @@ -78,7 +78,7 @@ even though its server UID differs. This does not preserve historical incarnatio identity or prove physical continuity; the spec may remain unchanged. Operators must review reused names and physical evidence, not treat a resolved reference as verification, capacity or authority. A reference edit still requires explicit -operator review and advanced provenance. This is observational validation, not +operator review. This is observational validation, not atomic graph admission or a referential-integrity controller. No new status fields are necessary: there is no Site reconciler or observation @@ -91,11 +91,10 @@ unchanged; they protect an individual edit, not indefinite reference binding. The only UID-bearing spec field introduced by the first PR100 revision was `Site.spec.facilityRefs[].uid`; it has been removed from Go and TypeScript types, -CRD schema, importer mappings/candidates, fixtures and examples. The reference +CRD schema, fixtures and examples. The reference now reuses the existing `LocalReference` type, and deep copies retain name-only references independently while preserving server metadata. Site status remains -empty. Provider identifiers, Site codes and record provenance introduce no -resource UID fields. +empty. Provider identifiers and Site codes introduce no resource UID fields. Separately, the preexisting `Device.spec.identity.systemUUID` field is a hardware SMBIOS UUID, not a Kubernetes resource UID; it is unchanged. No other explicit @@ -113,7 +112,6 @@ duplicate entries are rejected. These are sourced descriptive facts, not resourc references or global uniqueness claims. A repeated qualified identifier on different Facilities requires human adjudication; it never merges records. Provider metro, account, service and host identifiers are not premises identifiers. -Identifier edits, Site code changes and membership edits must advance provenance. ## Staff access and compatibility @@ -135,74 +133,18 @@ also covers the additional collection. No credentials or secret-bearing fields are added to search, details or forms. Old Facilities without identifiers remain valid and browsable, and all existing -rack/device/claim references, resource UIDs, immutable identity/source bindings, +rack/device/claim references, resource UIDs, immutable identity bindings, reportedPlacement revisions and unknown geometry retain their contracts. No allocation, installation, provisioning, capacity, reservation or verification effects result from any new record. Empty rack units and missing Site mappings remain observations, not available capacity or readiness. -## Explicit offline importer mapping - -The existing NetBox planner still makes no writes. Facility mapping may optionally -include `identifiers` and `identifiersVerified: true`; identifiers are not inferred -from source names. Invalid types such as Metro or Account are quarantined. -An optional `operationalSites` list accepts this synthetic shape: - -```json -{ - "name": "site-stable", - "displayName": "Example operational boundary", - "code": "EX3", - "source": "dcim/sites/1", - "verified": true, - "facilityRefs": [{"name": "premises-stable"}] -} -``` - -The source must be a present source site/location, but that alone establishes no -mapping. The explicit verified entry and a complete current Fleet snapshot, -including the Site collection, are required. Each Facility must already exist at -the referenced namespace/name, not be deleting, and survive graph reconciliation. -The importer continues to require an existing Facility snapshot rather than a -new candidate alone; this is a review boundary, not UID pinning. Mapping entries -containing `uid` or other extra reference fields are rejected, not copied into -specs. Regenerate earlier PR100 mapping files using name-only references. A -subsequent snapshot with a new server UID at the same name resolves by name; -no indefinite incarnation guarantee is claimed. Existing -six-collection snapshots remain usable when no operational Site mapping is -requested. Existing target differences still block automatic updates or takeover. -All candidate changes, including identifiers on an existing Facility, require -separate operator review. Name similarity never creates a mapping. - -Facility identifier mappings must be lists of at most 64 objects containing exactly -the string fields `provider`, `type`, and `value`. Unknown fields (including `uid`), -malformed containers/elements, duplicate identities, and invalid field values -quarantine the Facility and dependent candidates before handoff; they are not -silently stripped or left for server-side pruning. - -Malformed Site names, code/display-name types or lengths, unknown mapping fields, -and malformed, duplicate or oversized reference lists quarantine the source's -candidate cohort. Missing verification, unavailable referenced premises or an -unusable source/snapshot fail closed before handoff. New reference and provider -names enforce DNS subdomain label boundaries (no empty labels or leading/trailing -hyphens within labels). This does not migrate unrelated legacy CRD references. - -For new imports use target `writer: Operator` and `application: provider-inventory` -in both the mapping and matching Fleet snapshot. Handoffs containing operational -Site mappings always prescribe individually reviewed direct API creation, including -when an older snapshot attests a Flux target. The receipt records `writer: Operator` -for that new cohort; the original mapping/snapshot digests preserve the reviewed -inputs. It does not transfer existing record ownership or authorize updates. -Legacy physical-only Flux handoffs remain supported solely for compatibility; -they are not the operational Site workflow. All handoffs remain offline and require -fresh authorized reads and absence checks before any separately approved creation. - ## Rollout and remaining gates 1. Review and deploy CRD/IAM definitions through the existing packaging path, then the provider UI. Do not apply any example records. The UI tolerates Site API absence before rollout while keeping physical inventory browsable. -2. Read existing records privately and preserve stable names, UIDs, provenance, +2. Read existing records privately and preserve stable names, UIDs, ownership and revision baselines. Agree canonical provider namespaces and verify individual premises identity before adding descriptive identifiers. 3. Separately authorize any Site creation or membership edit. Use names from @@ -222,9 +164,6 @@ premises truth or production readiness. ```sh go test -race ./internal/api/inventory/v1alpha1 ./internal/location -python3 -m unittest discover -s hack -p 'test_*inventory.py' -python3 -m unittest discover -s hack -p 'test_pr100_independent.py' -python3 -m unittest discover -s hack -p 'test_device_placement.py' (cd ui/provider && pnpm test && pnpm typecheck && pnpm build) (cd ui/consumer && pnpm test && pnpm typecheck && pnpm build) bash hack/validate-doc-links.sh @@ -232,15 +171,14 @@ git diff --check ``` Tests cover additive schema, provider qualification/collisions, legacy records, -provenance, name references despite label changes, name-reuse rebinding, invalid relationships, -read denial/redaction, observational imports and existing independent safety +name references despite label changes, name-reuse rebinding, invalid relationships, +read denial/redaction and existing independent safety scenarios. Existing six-collection request-count assertions now count seven; their denial, session lifetime, operation and no-write assertions remain intact. Local validation on this implementation passed the full `go test -race ./...` suite with Kubernetes 1.37 envtest assets, provider (392) and consumer (44) -tests/typechecks/builds, 37 importer tests plus three independent importer -regressions, six reported-placement planner tests, inventory and Milo manifest +tests/typechecks/builds, inventory and Milo manifest rendering, local documentation links and whitespace checks. This is not authenticated staging acceptance. Mobile inspection was attempted at 390×844 with synthetic fixtures, but both browser snapshots timed diff --git a/docs/development/staff-inventory-ui.md b/docs/development/staff-inventory-ui.md index 28f16b48..ec45e86f 100644 --- a/docs/development/staff-inventory-ui.md +++ b/docs/development/staff-inventory-ui.md @@ -6,7 +6,7 @@ Its identity/membership fields are managed by direct API, not new UI forms. Local, uncommitted implementation on `0b6c8977227157575d388a42aac127769258f998` (PR95 merged into `feat/manual-inventory-records`). This phase does not publish, -deploy, import records, change IAM membership, or change inventory ownership. +deploy, change IAM membership, or change inventory ownership. The [provider plugin](../../ui/provider/README.md) remains the existing staff-portal Module Federation remote. The implemented six-kind API, not the broader [inventory proposal](../proposals/fleet-management/inventory.md), bounds the UI. @@ -61,20 +61,19 @@ pixel identity or completed authenticated staging acceptance. Device/PowerFeed components with recorded positions. No guessed ports, cable lengths or live connectivity. Reference owner UID/resourceVersion is retained and checked before creation; the API still cannot atomically reserve endpoints. -- Edit display name and recording details only for records with established +- Edit display name only for records with established portal ownership. No device identity, claim binding, components, topology, placement, lifecycle, status or operational changes are exposed through edit. - Correct Device-reported location in a separate form, including the first report - on an existing imported Device. Manual source/evidence/reason and explicit + on an existing Device. Evidence reference, reason and explicit unknown geometry are retained without changing identity or claim binding. ## Authorization, ownership and concurrency -Device source reports and labelled claim fallback now share a placement +Device-reported locations and labelled claim fallback now share a placement projection. See [Device-reported placement](device-reported-placement.md) for the additive contract and ordinary authorized corrections, including first reports -on existing imported Devices. Original import provenance and immutable identity -remain intact; manual corrections do not claim NetBox authorship. +on existing Devices. Immutable identity and claim binding remain intact. The existing `fleet.datumapis.com-inventory-manager` role inherits the viewer and adds create/update/patch for six kinds, project-wide. The UI uses exact-resource @@ -82,12 +81,11 @@ SelfSubjectAccessReviews and the signed-in principal's API request, never group names or staff membership. Role/binding deployment and membership are separate work; nothing here asserts their live state. There are no delete/status grants. -Inventory is direct API/operator-managed, not GitOps-only. Import provenance is -history, **not evidence of Flux ownership**. Legacy Flux-managed records keep -their writer until an explicit safe transition. This UI's deliberately narrow -display-name edit policy still requires Manual provenance and exclusively -`fleet-staff-inventory-ui` managed fields, with no import/deletion/other-owner -markers. The separate reported-location editor permits imported operator-managed +Inventory is direct API/operator-managed, not GitOps-only. Legacy Flux-managed +records keep their writer until an explicit safe transition. This UI's +deliberately narrow display-name edit policy still requires exclusively +`fleet-staff-inventory-ui` managed fields, with no deletion/other-owner +markers. The separate reported-location editor permits operator-managed Devices under normal manager authorization, excluding legacy Flux markers from its UI. These markers are not server authorization or owner isolation. Location record correction is not a handover or installation move. @@ -184,7 +182,7 @@ private table. No fixture writes were dispatched. The real staging URL redirected to sign-in; no login was manipulated. That evidence and the supplied Safari screenshot do not prove authenticated Safari URL-bar acceptance. Independent adversarial signoff, CI, and authenticated staging/Safari -acceptance remain deployment gates; no inventory, IAM, or NetBox data is changed +acceptance remain deployment gates; no inventory or IAM data is changed by this correction. Read-only users browse without enabled writes. No-read and direct-link denials @@ -228,7 +226,7 @@ deployed revision, upstream SSAR permission, or authenticated runtime behavior. | Interaction | Remaining boundary | | --- | --- | -| Imported/other-writer edits | Reported-location correction is available to managers, including imported Devices; legacy Flux remains outside the UI. Other edit forms retain their existing restrictions | +| Other-writer edits | Reported-location correction is available to managers for operator-managed Devices; legacy Flux remains outside the UI. Other edit forms retain their existing restrictions | | Rack position entry, move/assign equipment | Reported-location correction supports unknown or explicit geometry; physical moves, installation/binding changes and handovers still require separate workflows | | PowerFeed creation; component or endpoint edits | API kinds exist, but these forms are not implemented. Existing records remain browsable; no dead action buttons | | Online/active/connected badges, occupancy/free units, power utilization | No verified evidence projection; never infer health/readiness from inventory | diff --git a/docs/operations/README.md b/docs/operations/README.md index c229fb0d..f0bad0b3 100644 --- a/docs/operations/README.md +++ b/docs/operations/README.md @@ -17,8 +17,7 @@ integrations. Real provider support and live Milo acceptance tests are incomplet | Exercise Milo, Karmada and cell-local PXE end to end with one command | [Multi-plane acceptance](multiplane.md) (`task multiplane:acceptance`) | Native project routing, 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, cleanup and reuse; 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 executor discovery, one-time PXE/disk boot overrides, power, lost-response recovery and a booted wipe cleanup, against the unmodified DMTF Redfish Interface Emulator with a lab-only libvirt adapter and two persistent lab VMs; synthetic credentials and networking; not physical BMC or hardware qualification | | Publish physical-side DHCP reservations for network boot | [Boot network](boot-network.md) | Per-asset BMC endpoints and provisioning attachments, a reservation feed 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 attributable provenance and immutable identity and binding, shown read-only in the staff portal; no capacity or hardware effect; unit tested | -| Optionally compare an existing NetBox source | [Operator-run snapshot and candidate review](netbox-physical-import.md) | Optional local review aids only; manual inventory needs no NetBox, automated migration or live import | +| 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 | | Render deployment bundles and supply environment inputs | [Deployment manifests](../../config/README.md) | Packaging and security boundaries, not runtime readiness | | Run the manager across consuming projects | [Project discovery](../../config/README.md#project-discovery) | Discovery, per-project isolation, departure, role bindings, and readiness | | Exercise Milo-routed synthetic staging | [Synthetic staging configuration](../../config/README.md#environment-owned-inputs) | Restricted synthetic publication and lifecycle behavior, not production authority | diff --git a/docs/operations/netbox-physical-import.md b/docs/operations/netbox-physical-import.md deleted file mode 100644 index a5ed35bd..00000000 --- a/docs/operations/netbox-physical-import.md +++ /dev/null @@ -1,280 +0,0 @@ -# Optional NetBox review aids for manual inventory - -[Operational Site mappings](../development/site-facility-relationship.md#explicit-offline-importer-mapping) -are optional, explicitly verified and namespace/name-based. They never infer premises from -provider metros, accounts or similar names. - -[Device-reported placement](../development/device-reported-placement.md) adds -explicit per-device source-report opt-in for new candidates and a prepare-only -guarded patch planner for existing records. Claim placement semantics remain unchanged. - -[Physical inventory](physical-inventory.md) · [Inventory proposal](../proposals/fleet-management/inventory.md) · [Detailed proposed contracts](../proposals/fleet-management/inventory-reference.md) - -Start with [manual entry and operator review](physical-inventory.md#manually-record-a-small-installation). -Physical inventory needs neither NetBox access nor a bulk importer. Operators -write and review records individually. New/imported records may use approved -direct API creation; existing Flux-owned records retain that writer until an -explicit reviewed ownership transition. - -This guide covers **optional, explicitly invoked review aids**: a GET-only snapshot -command and offline candidate generation. They help compare an existing source -when an operator chooses to use it; they are not an automated migration. There -are no scheduled imports, discovery or sync controllers, background NetBox updates, -auto-apply or auto-delete. Neither command applies anything to Fleet or NetBox. -The retained `--handoff` option writes candidate files for human review only; it -does not hand execution to Flux, change Git, or transfer ownership. No verification, -reservation, adoption, enrollment, or provisioning controller is included. - -## What exists and what remains unknown - -`Facility`, `Rack`, `DeviceClaim`, `Device`, `Cable`, and `PowerFeed` live in the -existing provider project's Milo control plane. No database, management-cluster -copy, new catalog service, or independently running importer was introduced. -`config/milo` installs their CRDs, ProtectedResources and inventory roles. Existing -consumer Metal roles still grant no inventory access; inventory roles do not -grant status writes. Staff use their own identity through the existing Milo proxy. - -The CRDs validate local shapes, provenance, immutable asset/claim identity, -placement scope, component uniqueness, internal component positions, and Cable -lane multiplicity. The offline planner checks local references, compatible -component categories, and conflicting cable terminations against the supplied -Fleet snapshot. **These checks are not concurrent reservations or cross-object -API admission.** A direct API writer can still create dangling references or -cross-object conflicts; do not interpret successful creation as acceptance. -No qualified physical verification, dependency reservation, deletion protection, -move/replacement handover, electrical budget, or eligibility publisher exists. -No status field is populated. Free space, active binding, redundancy and readiness -remain Unknown. Existing editor delete permissions are not a safe retirement API. - -### Compatibility and migration decisions - -- Existing long-lived slot claims keep their names, text placement, ports, and - historical Device bindings. Existing `Device.spec.identity` and `claimRef` - remain immutable. MachineCapacity and its `deviceRef` are not modified. -- New manually entered or optionally generated claims use `lifecycle: Installation` and typed placement. This - mode cannot be added to a legacy slot; an installation's placement is immutable. - This is an observational installation record, **not** a reservation or an - accepted plan. Moving an existing asset remains blocked on the proposal's - explicit handover protocol; the importer does not create a replacement identity - to work around immutability. -- A Facility reference means no rack is asserted. `RackMembership` records a known - rack but forbids position, height and face. The default importer deliberately imports - no exact claim rack-unit positions, including seemingly plausible positions. This - prevents servers.com's generated 1U placements from becoming occupied or - verified footprints. The API also represents exact `RackUnits` and - `NonRackUnitMount` plans for separately reviewed manual records. -- `height` no longer defaults to 1 in admission: doing so invents a footprint on - partial placements. Previously stored defaulted values remain unchanged; legacy - UI rendering still treats omitted legacy height as one. New exact-unit plans - must supply height. `Device.modelShape` dimensions do not establish occupancy. -- Devices without a genuine serial may have an immutable `identity.sourceIdentity` - matching import provenance. This is a source-record identity, **not authenticated - chassis identity**. A provider host ID is `providerHostRef`; an asset tag is - `assetTag`, never a serial. The importer quarantines potential collisions with - legacy serials/provider IDs rather than rewriting them. -- Typed Devices opt into `topologyAuthority: Cable` and cannot contain inline - peers. New installation claims cannot contain expected inline peers. Existing - inline peers are retained as unmigrated history; they are not automatically - converted or deleted. Cable endpoints name same-namespace Device components or - PowerFeed terminations; unbound claim endpoints are deferred. No second expected - topology graph is written by the importer. -- Snapshot digest, source instance/class/ID, observation time and mapping revision - are retained in provenance. `recordedBy` identifies the offline tool, not an - authenticated source author. Milo/Git audit identifies the actual submitting - user. Imported source identity cannot change in place. Re-import of matching - physical fields is a no-op; differing existing records are quarantined. Changes - require a separate reviewed correction, not last-import-wins. - -## Source coverage - -The exporter discovers **every advertised DCIM and circuits collection**, follows -pagination, and lists errors or missing required collections. The parameterized -`dcim/connected-device` lookup is -explicitly listed under `excludedEndpoints`, rather than mistaken for a collection. -The result is a sequential observation with bounded requests, not a transactional -NetBox database snapshot. -Changing counts, duplicate IDs and pagination cycles fail the affected collection. -Counts can remain equal while content changes; quiesce loaders and rerun for a -stable review. Repeated failed reads never become complete coverage. - -The report classifies every fetched record. `imported` means representable in a -candidate (or already identical in the supplied Fleet snapshot), **not applied**. -`unresolved` means mapping, identity, or dependency needs review. `unsupported` -means an adapter cannot faithfully represent that class/shape. `excluded` always -has a reason. Collection completeness and record parity are distinct: a complete -fetch may still contain many unresolved or unsupported records. - -| Source classes | Treatment | -| --- | --- | -| `dcim/sites`, `dcim/locations` | Explicit premises mapping only. One metro Site may map to several Facilities. Unmapped records stay unresolved; no Fleet policy Site is created. | -| `dcim/racks` | Explicit Facility mapping, label and known height. No free-capacity inference. | -| `dcim/devices`, `device-types`, `manufacturers` | Explicit physical/virtual and serial interpretation; model metadata, optional dimensions, separate asset tag/provider identity. NetActuate/hosted-VM hints force exclusion. Supporting catalog rows are classified excluded as independent assets; referenced model facts are consumed. | -| `interfaces`, `power-ports`, `power-outlets`, `console-ports`, `console-server-ports`, `front-ports`, `rear-ports` | Typed Device components with source IDs. Logical LAG/bridge/virtual interfaces excluded. Front/rear mappings and outlet/input dependencies retained; missing relationships remain Unknown. | -| `modules`, `inventory-items`, `device-bays` | Typed component records, not public kinds. Nested installation/parent semantics not represented by these fields remain in the private source snapshot; these are not component-incarnation controllers. | -| `cables` | Simple, reviewed-medium cables with resolvable physical endpoints. Multi-termination/breakout imports require explicit reviewed lanes covering every source termination on its original side; unsupported mappings never become all-to-all paths. Multi-position trunks never silently collapse to position one. | -| `power-panels`, `power-feeds` | Feed supply ratings and terminations, external panel dependencies. No fabricated panel Device, derated budget, independent UPS proof or usable power reservation. | -| `circuits/circuits`, `circuit-terminations` | Explicit service-owner identifiers and mapped local component associations; no new Circuit kind, service lifecycle, billing, or routing. Unmapped demarcations remain unresolved. | -| Device/module/port templates, regions, site groups, rack roles, virtual chassis, circuit/provider catalogs | Explicitly excluded as independent installed physical assets; reasons recorded per row. | -| Other advertised classes (including new NetBox-version additions) | Fetched and reported unsupported, never silently discarded. | - -IPAM, VLANs, VRFs, routing, virtualization collections, billing and provisioning -are explicitly outside this export. VMs stored in **DCIM** are still inspected and -excluded per record. OOB IP lists and credential/custom-field bodies are not copied; -existing restricted Device BMC facts remain untouched. Sanitization uses a recursive -physical-field allowlist and excludes URLs, comments, custom fields and config -contexts. This intentionally is **not a lossless NetBox backup**. Exports still -contain private asset identities, serials and topology and must stay outside Git. - -## Optionally compare the checked-in synthetic example - -Python 3 uses only the standard library. No provider SDK or cluster access is -needed. Output directories must not already exist; files are mode 0600 inside -mode 0700 directories. No command overwrites a previous run. -Output paths inside a Git checkout are refused, including worktrees. - -```sh -python3 hack/netbox_inventory.py plan \ - --snapshot hack/testdata/netbox/snapshot.json \ - --mapping hack/testdata/netbox/mapping.json \ - --output /private/tmp/fleet-physical-report-example -``` - -Only `report.json` is emitted by default. The historical `imported` classification -means an offline candidate was representable, **not that any record was applied**. -Inspect every unresolved/unsupported -row; the example intentionally leaves a room mapping unresolved. Staff can open -the report with the Inventory tab's local file picker; its contents are not -uploaded. The portal shows restricted/loading/empty states, paginated collections, -asset components, facility/rack membership, feeds and cables. Multiple historical -Devices on one claim do not select the most recently edited record as active. - -To exercise the explicit handoff **with synthetic data only**: - -```sh -python3 hack/netbox_inventory.py plan \ - --snapshot hack/testdata/netbox/snapshot.json \ - --mapping hack/testdata/netbox/mapping.json \ - --existing hack/testdata/netbox/existing.json \ - --handoff --allow-partial \ - --output /private/tmp/fleet-physical-handoff-example -``` - -`--allow-partial` explicitly acknowledges unresolved/unsupported records; it does -not bypass collection errors or target conflicts. The handoff emits candidate -objects and a receipt containing the exact target plus source, mapping, Fleet -snapshot and candidate digests. Nothing invokes kubectl apply or writes Git. - -New direct-API handoffs use `target.writer: Operator` and -`target.application: provider-inventory` in the mapping and matching snapshot. -An operational Site mapping always produces operator/direct-API guidance, even -when its input snapshot retains the legacy Flux target: the receipt's writer is -Operator for new candidates only, not an ownership transfer. Physical-only legacy -Flux handoffs remain compatible; do not use them for the Site import workflow. -Site field validation quarantines malformed candidate cohorts; `--allow-partial` -cannot override their conflicts. See the [Site relationship contract](../development/site-facility-relationship.md) -for name-only references, name-reuse semantics and validation boundaries. - -## Optional private source comparison - -Skip this entire section for manual entry. No NetBox credentials or parity audit -are required to evaluate the manual physical-inventory features. Only perform a -source comparison when separately requested and authorized by the operator. - -1. Use existing read credentials: `NETBOX_TOKEN`, otherwise `NETBOX_TOKEN_FILE` - (default `~/.config/netbox/token`). Never paste a token into arguments, logs, - mappings or Git. The existing infra bare-metal reader uses Bearer authentication; - `--auth-scheme Token` explicitly supports installations using the legacy scheme. - Redirects, non-HTTPS origins and off-origin/changed-collection pagination are - refused. All requests are GET; retries are bounded to three for transient errors. -2. Quiesce the source loaders if possible, then capture a private snapshot: - - ```sh - python3 hack/netbox_inventory.py snapshot --source reviewed-netbox-instance \ - --output /private/tmp/fleet-netbox-private-snapshot - ``` - -3. Copy the [synthetic mapping shape](../../hack/testdata/netbox/mapping.json) into - a private file. Review each facility, physical device classification, serial - interpretation, placement scope, feed and cable medium. A Source Site name is - not proof of premises. A missing serial is not permission to invent one. - For a breakout or multi-position termination, a cable mapping can supply `lanes` - in the [Cable Go contract](../../internal/api/inventory/v1alpha1/physical.go): - each lane has an ID, `a` and `b`, each endpoint has exactly one local owner, - `componentID` and `position`. Use stable candidate names from a prior dry-run - handoff or the source-key-derived name function. Positions must exist in the - component model; do not invent transceiver lanes absent from source geometry. -4. Export **all six** Fleet kinds from the explicitly selected **provider project's - Milo context**, including empty collections, before preparing candidates. The - [synthetic existing-state envelope](../../hack/testdata/netbox/existing.json) - shows the exact structure: `target` must exactly match the mapping, `collections` - must list all six kinds, and `items` contains the complete list in the reviewed - namespace. Use the project's established authenticated GET/list path; do not - assume a management-cluster context addresses Milo. The envelope is an operator - attestation, not cryptographic proof of scope or freshness. Retain capturedAt and - read evidence privately; re-read before any approved creation or source merge. -5. Run `plan` with private `--snapshot`, `--mapping`, `--existing` and a fresh output - directory. Add `--previous` with the earlier source snapshot on subsequent runs. - Review source disappearances: missing rows are **retained**, never deleted, - retired, freed, or marked ready. Existing differences, duplicate target IDs, - identity collisions and topology conflicts need adjudication before handoff. -6. Obtain explicit approval for the mapping, exact target and desired cohort. - Only then generate a handoff. Do not put private exports or imported asset facts - in a public Fleet PR. Do not apply the candidate List directly to Milo. -7. Use the explicitly approved writer for individual **new** records. A separately - authorized one-time API creation must be additive, reject existing names rather - than overwrite them, and retain per-record receipts for recovery. Operational - Site imports use this direct-API path, never GitOps. Only for the unrelated - legacy physical-only Flux workflow, stage approved new records additively in - its private source. Preserve existing files, identities and bindings; never replace - the collection with this partial candidate list. Review exact inputs for no - deletes, modifications of existing bindings, capacities or readiness/status. - Retain source/mapping/report/receipts in the approved private evidence store. - This offline importer itself does not execute API writes, commit, push or deploy. - -Flux remains the writer for records it already owns; direct creation of new records -does not authorize editing or taking over that cohort. Reviewers must check for -concurrent changes since the Fleet snapshot; the offline handoff does not provide -an optimistic-concurrency apply transaction. After an interrupted creation or -reconciliation, refresh the Fleet snapshot and rerun. Matching records become -no-ops; conflicts stay quarantined. Do not roll back by deleting occupied objects. - -The 2026-11-20 configuration observation names `fleet-provider-inventory`, with -path `apps/fleet-system/staging/provider-inventory`, `prune: false` and -`deletionPolicy: Orphan`. The similarly named legacy inventory reconciliations -are not the provider-project destination. Recheck these settings before handoff; -this feature does not modify them or their kubeconfig references. - -## Acceptance and observed limits - -On 2026-11-20, read-only GitHub checks found both infra staging OCI sources configured -for `v0.0.0-feat-manual-inventory-records`; the corresponding Fleet branch head was -`42086bbe2cf05f5d09362fbc777e514907d64462`. This implementation is stacked there, -including the dependent PXE/runtime code. **That original configured-tag check -was not a deployed-revision observation.** A subsequent read-only staging API -check is recorded in the [staging baseline and acceptance checklist](physical-inventory-staging.md#read-only-baseline-observed-on-november-20-2026). -It observed the manual-inventory base, not this physical extension. No cluster -rollout or live import was performed. - -The documented environment/token-file paths did not provide authorized NetBox -access in this implementation checkout. No live inventory audit was performed; -present-day counts, parity, source mappings and schema-version compatibility are -unvalidated. Source interpretation comes from the pinned infra -`d9198940a499be4e744ee0564cf3dc0b3bfcee34` loaders and site-build documents, as -recorded in the [source evidence appendix](../proposals/fleet-management/inventory-reference.md#source-evidence-and-limits). - -For manual staging evaluation, use the [acceptance and rollback checklist](physical-inventory-staging.md). -If an operator separately chooses the optional source comparison, establish its -private audit and mappings, compare every classified row, and test repeated and -interrupted candidate generation. No live NetBox access means no claim of source -parity, not a blocker for manually entering and reviewing physical records. - -```sh -python3 -m unittest discover -s hack -p test_netbox_inventory.py -go test ./internal/api/inventory/v1alpha1 -pnpm --dir ui/provider typecheck -pnpm --dir ui/provider test -pnpm --dir ui/provider build -kustomize build config/milo >/dev/null -bash hack/validate-doc-links.sh -git diff --check -``` diff --git a/docs/operations/physical-inventory-staging.md b/docs/operations/physical-inventory-staging.md index c86b1aa5..4fcc30b1 100644 --- a/docs/operations/physical-inventory-staging.md +++ b/docs/operations/physical-inventory-staging.md @@ -1,11 +1,10 @@ # Evaluate manual physical inventory in staging -[Manual entry and review](physical-inventory.md#manually-record-a-small-installation) · -[Optional source comparison](netbox-physical-import.md) +[Manual entry and review](physical-inventory.md#manually-record-a-small-installation) This checklist is for an explicitly approved staging evaluation after independent adversarial review. It is not approval to deploy or evidence of physical readiness. -No live imports, deployment, source-tag changes, hardware actions, or inventory +No deployment, source-tag changes, hardware actions, or inventory writes were performed during the implementation checks below. ## Read-only baseline observed on November 20, 2026 @@ -57,8 +56,8 @@ acceptance step. No production project context was used as a substitute. budgets, verification and readiness must remain Unknown. Do not register an asset without a genuine identity or manufacture a serial from a provider ID. 5. Review and merge individual records into the private provider-inventory Git - source; let Flux be the only API writer. No NetBox access, bulk conversion, - discovery, sync, or scheduled import is needed. No capacity, billing, IPAM, + source; let Flux be the only API writer. No external inventory access, bulk conversion, + discovery, or sync is needed. No capacity, billing, IPAM, routing, provisioning, hardware, customer-release or status changes are allowed. 6. Verify authorized staff can browse all six kinds, typed components, relationships, partial placement and historical bindings. Confirm consumer identities cannot @@ -121,7 +120,6 @@ go test -race ./... go vet ./... go test -race ./internal/manager -run 'TestProject(Reengagement|Departure)|TestConcurrentProjectReengagement|TestDisengageWithActiveCustody' -count=50 go test -race ./internal/manager -run '^(TestManagerEndToEndAgainstSyntheticMilo|TestConsumerDiscoveryIgnoresOtherServicesAndBacksOff)$' -count=1 -v -python3 -m unittest discover -s hack -p test_netbox_inventory.py pnpm --dir ui/provider typecheck pnpm --dir ui/provider test pnpm --dir ui/provider build @@ -131,6 +129,4 @@ bash hack/validate-doc-links.sh git diff --check ``` -There is no live NetBox parity claim. Optional snapshots and candidate conversion -remain solely to help an operator compare a source when separately requested; -they never apply records or change Git. Their synthetic tests are not a source audit. +There is no claim of parity with any external inventory source. diff --git a/docs/operations/physical-inventory.md b/docs/operations/physical-inventory.md index 9f038b43..413c272d 100644 --- a/docs/operations/physical-inventory.md +++ b/docs/operations/physical-inventory.md @@ -1,6 +1,6 @@ # Planning and registering physical devices -For source reports and authorized, concurrency-safe location record corrections, see +For reported locations and authorized, concurrency-safe location record corrections, see [Device-reported placement](../development/device-reported-placement.md). [Operations guide](README.md) · [Architecture](../architecture/README.md) · @@ -18,16 +18,17 @@ It has six physical kinds plus the observational operational `Site` kind in [Site–Facility relationship](../development/site-facility-relationship.md) for stable membership references, provider premises identifiers and rollout gates. The primary workflow is **manual entry, operator review, and explicit record -ownership**. Authorized direct API creation is supported for new/imported records; +ownership**. Authorized direct API creation is supported for new records; legacy Flux-owned records require a reviewed ownership transition before edits -by another writer. NetBox, bulk conversion, and a source reconciliation service are not -required. The [optional NetBox comparison guide](netbox-physical-import.md) -describes a separately invoked review aid, not an automated migration. +by another writer. Fleet does not read or reconcile any external inventory +source. A separate writer may copy records in from another system; it writes +ordinary records through the same API and validation, and keeps any record of +where facts came from on its own labels and annotations. | Kind | What it is | Writer | | --- | --- | --- | | `DeviceClaim` | An observational installation plan with expected model and known placement. New records use typed placement and Cable references; existing long-lived slots retain their legacy representation. | Installation planner, through the record's explicitly assigned writer | -| `Device` | One actual asset, bound to exactly one DeviceClaim when detected hardware is registered. It carries the serial and SMBIOS system UUID, the model, an optional BMC endpoint, interfaces, and provenance. | The registrar (an operator, for now) | +| `Device` | One actual asset, bound to exactly one DeviceClaim when detected hardware is registered. It carries the serial and SMBIOS system UUID, the model, an optional BMC endpoint, and interfaces. | The registrar (an operator, for now) | | `Facility` / `Rack` | Explicit premises and rack definitions; membership is not free-capacity evidence. | Inventory operator through the environment's existing writer | | `Cable` / `PowerFeed` | Typed termination/lane topology and physical supply dependencies. | Inventory operator through the environment's existing writer | @@ -38,8 +39,8 @@ describes a separately invoked review aid, not an automated migration. | CRDs and Go types | Implemented in `config/components/inventory` and `internal/api/inventory/v1alpha1`. | | Home | Milo. `config/milo` registers six CRDs, six ProtectedResources and three IAM roles. Management and synthetic-staging overlays install none of them. | | Staff portal | Six-kind hardware directory in the Bare Metal provider plugin (`ui/provider`), with permission-aware browsing and limited authorized Facility/Rack creation and portal-owned name edits. See [implementation scope](../development/staff-inventory-ui.md). | -| Tests | Unit tests run API-server schema, list-type and CEL validation offline for the six kinds and synthetic importer output. IAM tests check ProtectedResource and role shape and that no metal role grants inventory access. Plugin tests cover browse/detail, partial placement, reconciliation, restricted, pagination and empty states. | -| Controllers | None for inventory. Staff browsing is read-only; no reconciler accepts plans, verifies hardware, discovers or synchronizes NetBox, or publishes eligibility. Flux applies only operator-reviewed Git records. | +| Tests | Unit tests run API-server schema, list-type and CEL validation offline for the six kinds, including pruning of retired fields. IAM tests check ProtectedResource and role shape and that no metal role grants inventory access. Plugin tests cover browse/detail, partial placement, reconciliation, restricted, pagination and empty states. | +| Controllers | None for inventory. Staff browsing is read-only; no reconciler accepts plans, verifies hardware, discovers or synchronizes external inventory, or publishes eligibility. Flux applies only operator-reviewed Git records. | | Hardware qualification | None. Records hold operator-entered facts, not verified hardware state. | ## What registration does and does not do @@ -119,9 +120,9 @@ in the provider project. The plugin never writes. | Rule | Kind | Why | | --- | --- | --- | -| `provenance` is optional and deprecated; when present it is still validated. Spec changes no longer need a later `provenance.recordedAt` | All six | Transitional: provenance is being removed. Resource audit logs record who changed a record and `metadata.creationTimestamp` records when it was created. | +| Records carry no attribution fields | All six | Resource audit logs record who changed a record and `metadata.creationTimestamp` records when it was created. A writer that needs to remember where facts came from uses its own labels and annotations. | | `claimRef` is required and immutable | Device | A Device binds to exactly one claim, and moving hardware to another slot is not an edit. | -| `identity` is immutable, including adding missing fields; requires serial, system UUID, or an import source identity matching provenance | Device | Source identity does not prove chassis identity. Legacy bindings are preserved; hardware handover is not automated. | +| `identity` is immutable, including adding missing fields; requires a serial or system UUID | Device | Neither proves chassis identity. Legacy bindings are preserved; hardware handover is not automated. | | Serial is optional | DeviceClaim | It is usually unknown at plan time. | | Port and interface names are unique; MACs are lowercase and colon-separated, appear at most once per Device, and are either mapped to an interface or listed in `unmappedMACAddresses`, not both | Both | Malformed or ambiguous facts are rejected. | | The system UUID is in lowercase canonical form | Device | One spelling per identity. | @@ -142,12 +143,12 @@ authenticated, complete NIC mapping before any network path depends on it. their writers. The legacy staging `fleet-provider-inventory` reconciles `apps/fleet-system/staging/provider-inventory` with `prune: false` and `deletionPolicy: Orphan`. Flux remains the sole writer of those legacy records - until an explicit ownership transition. Do not run a competing apply/import - against them. New and separately imported inventory can be direct + until an explicit ownership transition. Do not run a competing apply + against them. New and separately created inventory can be direct API/operator-managed; GitOps is not required. Establish the authorized writer - per record before making changes; import provenance is not Flux ownership. -2. Enter the Facility and Rack facts you actually know. Record the operator and - time with `provenance.method: Manual`. Leave unknown dimensions absent. Rack + per record before making changes. +2. Enter the Facility and Rack facts you actually know. Leave unknown + dimensions absent. Rack membership is not a reserved footprint or evidence of available space. 3. For a new installation, set `DeviceClaim.spec.lifecycle: Installation` and typed placement. Use `Facility` when only the premises are known, @@ -174,7 +175,7 @@ authenticated, complete NIC mapping before any network path depends on it. documented in the [staff UI scope](../development/staff-inventory-ui.md). The [complete synthetic six-record example](../../hack/testdata/physical/manual.yaml) -shows this workflow without NetBox or credentials. It includes a partial rack +shows this workflow without external sources or credentials. It includes a partial rack placement, typed network and power components, and one Cable from a PowerFeed to the Device. It is a test fixture, not an automatically installed overlay. Copy its shape into private configuration and replace synthetic facts only after @@ -209,11 +210,6 @@ metadata: name: rack-01-u12 namespace: fleet-system spec: - provenance: - method: Manual - recordedBy: planner@example.com - recordedAt: "2026-01-02T03:04:05Z" - reference: rack plan 1234 expectedIdentity: manufacturer: Example Vendor model: Example 1U @@ -240,11 +236,6 @@ metadata: spec: claimRef: name: rack-01-u12 - provenance: - method: Manual - recordedBy: registrar@example.com - recordedAt: "2026-01-09T10:00:00Z" - reference: BMC inventory read during rack turn-up identity: manufacturer: Example Vendor model: Example 1U @@ -305,14 +296,13 @@ records if adopted. **Compatibility decision:** legacy slots retain all historical bindings. New typed records use a distinct `Installation` lifecycle, but no automatic move or replacement handover exists. Device identity and its original claimRef remain -immutable. The [migration decisions](netbox-physical-import.md#compatibility-and-migration-decisions) -explain why imports cannot delete/recreate or relabel legacy records to bypass this. +immutable. No writer may delete/recreate or relabel legacy records to bypass this. ## Applying the records `config/milo` installs the CRDs, ProtectedResources, and roles into Milo. Apply operator-reviewed records through their approved writer after those are established, -claims before the Devices that name them. New or imported records may be created +claims before the Devices that name them. New records may be created directly through the provider API with authorization and ownership safeguards. Existing Flux-owned records remain with Flux until a reviewed transition stops reconciliation for those exact records. Do not overwrite or adopt them implicitly. @@ -324,3 +314,26 @@ not in this repository. applied them to the management cluster before Milo became their home. Once that environment has moved its records into Milo and stopped reconciling the root, it will be removed. New environments must not use it. + +## Compatibility + +Earlier `v1alpha1` schemas required `spec.provenance` (method, recorder, +recording time, optional reference and import source) on every kind, required +each spec change to advance `provenance.recordedAt`, and accepted Device +`identity.sourceIdentity`, component `sourceRef`, and +`reportedPlacement.method`/`snapshotDigest`. These fields are gone. The served +and stored version remains `v1alpha1`; this is an alpha breaking change. + +No migration is needed. Each schema is structural and does not preserve unknown +fields, so the API server prunes the removed fields from stored objects when it +reads them and drops them from requests; they leave storage on the next write. +A client that still sends them is not rejected unless it asks for strict field +validation: by default the server drops the fields and returns an unknown-field +warning, while strict validation (the `kubectl` default) returns an error. +Remove the fields from GitOps sources and other writers. An old reported +placement that lacks `reason` or `reference` must gain both the next time its +report changes. + +Retirement happened in two steps so that GitOps-applied records could drop the +fields first: provenance became optional and stopped gating edits, then the +fields were removed. diff --git a/docs/proposals/fleet-management/MIGRATION.md b/docs/proposals/fleet-management/MIGRATION.md index c1fa51ed..281a0d52 100644 --- a/docs/proposals/fleet-management/MIGRATION.md +++ b/docs/proposals/fleet-management/MIGRATION.md @@ -31,18 +31,25 @@ migration configuration remains in infra. ## Post-import amendments -- 2026-11-20: Added the limited [observational physical inventory implementation](../../operations/netbox-physical-import.md) +- 2026-11-21: Removed record provenance from the physical inventory API. Records + no longer carry `spec.provenance`, Device `identity.sourceIdentity`, component + `sourceRef`, or an import method on reported placement, and the offline import + tooling was deleted. Who changed a record comes from resource audit logs and + when it was created from `metadata.creationTimestamp`; writers that need to + remember where facts came from keep that on their own labels and annotations. + See [physical inventory](../../operations/physical-inventory.md#compatibility). + +- 2026-11-20: Added the limited [observational physical inventory implementation](../../operations/physical-inventory.md) on the staging-selected manual-inventory feature base. Six record kinds, typed - components, partial placement, read-only staff relationships and offline NetBox - handoff are implemented separately from this proposal's acceptance, reservations, + components, partial placement and read-only staff relationships are implemented separately from this proposal's acceptance, reservations, verification and lifecycle controllers. Legacy identities/bindings remain intact; no live source parity, deployed readiness or hardware qualification is asserted. - 2026-11-20: Expanded the existing [inventory proposal](inventory.md) with the six physical contracts, partial placement, typed components, circuit-boundary proposals, evidence and qualification requirements. Recorded the pinned - manual-record implementation's claim-lifetime and authority migration gates, - plus source-backed NetBox import constraints. These remain proposed contracts, + manual-record implementation's claim-lifetime and authority migration gates. + These remain proposed contracts, not implementation changes or proof of live-data parity. The proposal keeps the design narrative; field details, examples, migration evidence and test cases are retained in its [reference appendix](inventory-reference.md). diff --git a/docs/proposals/fleet-management/inventory-reference.md b/docs/proposals/fleet-management/inventory-reference.md index c0397492..b737a55d 100644 --- a/docs/proposals/fleet-management/inventory-reference.md +++ b/docs/proposals/fleet-management/inventory-reference.md @@ -8,7 +8,7 @@ latest-milestone: "v0.1" Technical detail supporting the [Fleet inventory product proposal](inventory.md). Start there for operator needs, the proposed experience and open decisions. -This appendix keeps field definitions, synthetic examples, source findings, +This appendix keeps field definitions, synthetic examples, migration steps and test requirements together for implementers and reviewers. It is part of the same enhancement, not a separate design. @@ -35,7 +35,6 @@ rebinds the relationship; observed resource UIDs do not belong in desired-state - [Circuit boundary](#circuit-demarcations-and-external-ownership) - [Lifecycle transitions](#moves-replacements-and-retirement) - [Existing records and migration](#existing-records-and-migration) -- [Source evidence and limits](#source-evidence-and-limits) - [Validation and qualification matrix](#validation-and-qualification-matrix) ## Contract details @@ -56,14 +55,14 @@ photo, model, approval, or verification run. | Management endpoints and access | Provider management authority | Restricted references/projections only; inventory does not allocate OOB addresses, issue credentials, or authorize BMC actions. | | Provider host IDs, service/circuit identifiers and commercial facts | Respective provider/service authority | Inventory retains sourced identifiers and physical associations, not orders, invoices, pricing, or routing intent. | -All kinds need a human-readable label, optional description, provenance, and -restricted external references. Names and labels are not durable asset identity. -For each imported fact retain source system, source object type and ID, source -revision or snapshot digest when available, observation time, importer identity -and mapping revision. Keep claimed source authors separate from the authenticated -submitter. Conflicting sources require adjudication; last import wins is not a -trust rule. Absence, undisclosed information, a mismatch, and policy-approved -inapplicability are distinct states, never encoded as invented values or zero. +All kinds need a human-readable label, optional description, and restricted +external references. Names and labels are not durable asset identity. Records do +not carry their own attribution: resource audit logs record who changed a record +and `metadata.creationTimestamp` records when it was created. A writer that copies +facts from another system keeps any record of where they came from on its own +labels and annotations; Fleet does not interpret them. Absence, undisclosed +information, a mismatch, and policy-approved inapplicability are distinct states, +never encoded as invented values or zero. Typed references identify the allowed kind/group, administrative scope, and name. A kind-specific field such as `rackRef` fixes kind/group; examples omit scope only @@ -71,7 +70,7 @@ for same-scope references. Cross-scope references require explicit scope and authorization; they never resolve by a global name search. Acceptance pins the resolved local incarnation and relevant revision privately. Name reuse, dangling references, unauthorized targets, and wrong-kind targets cannot inherit evidence. -Foreign source IDs are provenance, not directly resolvable Fleet references. +Identifiers from other systems are not directly resolvable Fleet references. `documentRefs` refer to photos, as-built sheets, installation attestations, LOAs, or contracts in their existing document system. Retain document ID, category, @@ -94,10 +93,10 @@ must preserve evidence needed by active reservations and consumer obligations. | Kind | Proposed minimum and optional physical metadata | Validation and lifecycle | | --- | --- | --- | | Facility | Stable identity, display name, geographic `locationRef`, and physical-premises description. Optional structured postal address, building/room labels, coordinates with source/precision, operator identity reference, external facility-code mappings and document references. Sensitive access instructions stay external. | A metro code alone is insufficient to establish premises. Operator approval establishes or corrects a premises mapping. Closing a Facility blocks new plans; it neither relocates equipment nor releases occupancy. Preserve historical references. | -| Rack | Immutable `facilityRef` after accepted use, local rack label, optional room/row, mounting geometry and capacity, supported faces, depth/width limits, optional load limit with units, 0U mounting locations, and document references. Unknown dimensions remain absent with provenance. | Rack labels are unique within an agreed Facility scope, not globally. Known rack-unit numbering has a documented origin/direction; position denotes the lowest occupied unit. Reject out-of-range footprints, face/depth conflicts, and incompatible mounts. Do not infer usable space from omitted geometry. | +| Rack | Immutable `facilityRef` after accepted use, local rack label, optional room/row, mounting geometry and capacity, supported faces, depth/width limits, optional load limit with units, 0U mounting locations, and document references. Unknown dimensions remain absent. | Rack labels are unique within an agreed Facility scope, not globally. Known rack-unit numbering has a documented origin/direction; position denotes the lowest occupied unit. Reject out-of-range footprints, face/depth conflicts, and incompatible mounts. Do not infer usable space from omitted geometry. | A Facility is not a provider account, provider metro grouping, or Fleet policy -Site. One physical premises may have several provider codes; one imported metro +Site. One physical premises may have several provider codes; one provider metro grouping may refer to several premises. Mapping records retain both directions and unresolved candidates without creating a false one-to-one relationship. Site policy selects eligible Facilities as described in @@ -136,7 +135,7 @@ models and VM flavors cannot establish chassis geometry. Qualification must compare the shape to actual hardware variants. Each canonical component entry has a Device-local stable ID, a discriminated -type, physical label, optional parent/slot, relevant capabilities, provenance, +type, physical label, optional parent/slot, relevant capabilities, and retained incarnation/revision evidence. The registrar owns the canonical entry; mutable observations and OS aliases are separate. Reject duplicate IDs, parent cycles, incompatible fields, and references to removed incarnations. @@ -184,7 +183,7 @@ remain the only declarations connecting different assets. The DeviceClaim contract retains role, expected identity constraints, placement scope, declared attachment points, required Cable references, verification -profile/checks, provenance and approval revision. Where power is reserved, the +profile/checks and approval revision. Where power is reserved, the plan also pins a maximum load budget with units and the required failure scenario per supply path. Missing load assumptions block power-capacity acceptance; the number of PSUs does not supply them. Model-shape references and predecessor/asset @@ -353,12 +352,12 @@ terminations/power, but makes **no rack-unit reservation**. An unresolved footprint prevents declaring the rack's unaccounted space free: block new exact unit reservations in that rack until occupancy is reconciled, unless a qualified operator-approved exclusion boundary proves a disjoint area safe. Do not guess -the exclusion boundary. Facility-only imports likewise cannot establish free +the exclusion boundary. Facility-only records likewise cannot establish free rack capacity. A plan requiring exact placement remains Pending until an exact footprint is approved and reserved. `PlacementVerified` reports Facility, RackMembership, or exact mount scope; RackMembership readiness cannot satisfy a -RackUnits prerequisite. Imported invented positions never satisfy any placement -check merely because they appear in a source DCIM object. +RackUnits prerequisite. Invented positions copied from another system never +satisfy any placement check. ### Reserve physical resources @@ -575,10 +574,7 @@ not an independently editable peer list on Devices. A Cable connects typed physical terminations. Pass-through components on patch panels retain explicit internal front/rear mappings. Breakout cables require explicit position/lane mappings. Trace the complete supporting path; reject an -unsupported mapping rather than assuming a direct connection. NetBox's -[physical cable model](https://netboxlabs.com/docs/netbox/models/dcim/cable/) provides an -established physical-path precedent. It is not a requirement to use NetBox's -schema or implementation. +unsupported mapping rather than assuming a direct connection. A PDU is a Device. Its component model maps each outlet to the input that supplies it. Power cables connect feeds to PDU inputs and outlets to device @@ -588,9 +584,7 @@ PowerFeed records include rated/usable capacity and known upstream sources; unknown dependencies remain explicit. Reservation calculations must account for the declared redundancy/failure scenario, not assume that each of two feeds supplies half the load. Two differently named PDUs can share the same -UPS or upstream circuit. See the -[power feed model](https://netboxlabs.com/docs/netbox/models/dcim/powerfeed/) and -[power outlet model](https://netboxlabs.com/docs/netbox/models/dcim/poweroutlet/) precedents. +UPS or upstream circuit. PowerFeed is the physical supply boundary, not a utility bill or a substitute for a PDU Device. Its proposed contract includes Facility reference, operator @@ -602,7 +596,7 @@ and measured draw remain separate; a low instantaneous draw cannot free a reserved budget. Upstream dependencies identify other PowerFeeds or scoped external electrical -source identities with provenance. Equal external identities mean a shared +source identities. Equal external identities mean a shared dependency; different labels without evidence do not prove independence. Unresolved dependencies remain Unknown, and cycles are invalid. An electrical panel/circuit label is distinct from a network service circuit identifier. @@ -776,11 +770,11 @@ any of the conditions proposed here. | Reviewed implementation | Proposed target and migration constraint | | --- | --- | -| DeviceClaim describes a long-lived slot; a replacement Device names the same claim. Device identity and `claimRef` are immutable. | Retain this proposal's per-installation claim identity: each move/replacement has a successor claim. Keep a stable slot label or provenance association for operator navigation, not a second binding authority or new Slot kind. This is a proposed resolution, not a schema change already approved in #90. | -| Placement requires string `facility`/`rack`, numeric position, height and face. | Resolve approved Facility/Rack references with source mapping. Convert to explicit placement scope; do not treat strings as global IDs or retain fabricated positions as authoritative. | +| DeviceClaim describes a long-lived slot; a replacement Device names the same claim. Device identity and `claimRef` are immutable. | Retain this proposal's per-installation claim identity: each move/replacement has a successor claim. Keep a stable slot label for operator navigation, not a second binding authority or new Slot kind. This is a proposed resolution, not a schema change already approved in #90. | +| Placement requires string `facility`/`rack`, numeric position, height and face. | Resolve approved Facility/Rack references. Convert to explicit placement scope; do not treat strings as global IDs or retain fabricated positions as authoritative. | | Claimed ports have name/type/speed and embedded `expectedPeer`; Device interfaces may contain `peer`. | Convert approved expected connections into Cable plans once; preserve actual peer reports as sourced observations. Reconcile reciprocal/contradictory entries before creating a single Cable authority. Keep old inline fields read-only during cutover, then remove/deprecate through a versioned migration. | -| Device carries model, serial/system UUID, interfaces and unmapped MACs. | Preserve original values and provenance; adjudicate canonical physical identity and component mappings. Do not coerce provider IDs into chassis serials, or turn interface names/MAC lists into trusted component identity. | -| Optional BMC endpoint and manual provenance live on restricted provider-project objects in Milo. | Preserve access restrictions. Endpoint discovery does not authorize access. Transfer endpoint configuration authority explicitly to the provider management surface before exposing only references/read projections; never run two writable copies. | +| Device carries model, serial/system UUID, interfaces and unmapped MACs. | Preserve original values; adjudicate canonical physical identity and component mappings. Do not coerce provider IDs into chassis serials, or turn interface names/MAC lists into trusted component identity. | +| Optional BMC endpoint lives on restricted provider-project objects in Milo. | Preserve access restrictions. Endpoint discovery does not authorize access. Transfer endpoint configuration authority explicitly to the provider management surface before exposing only references/read projections; never run two writable copies. | | No controller checks binding exclusivity, evidence or `MachineCapacity.deviceRef` resolution. | Resolve duplicate/multiple bindings and protect existing occupancy before enabling automation. Do not infer Accepted, Bound, Ready or allocator eligibility from schema admission. | **Claim-lifetime decision gate.** The target remains one committed Device binding @@ -812,26 +806,13 @@ bindings/evidence; they are not independently writable asset catalogs. Qualify cross-project reads, status writers, reference authorization and consumer redaction before broadening access or adding cross-scope relationships. -### NetBox and provider imports +### Moving records from another inventory system -Import is observational until an explicit ownership transition. These rules are -derived from the pinned source workflows, not from a live NetBox database audit: - -| Source convention or gap | Required treatment | -| --- | --- | -| Loader Sites group provider metros and can union several provider facility codes. | Preserve source Site ID and provider-code mapping. Do not map NetBox Site one-to-one to Fleet Site or Facility. Unresolved premises stay unresolved and block prerequisites needing a physical Facility. | -| Loaders store provider host IDs in NetBox `serial`. | Retain them as owner-qualified external host IDs with the original field provenance. Never claim a verified chassis serial without independent physical evidence. | -| NetActuate VMs are DCIM Devices. | Classify virtual supply through provider/MachineCapacity contracts. Do not create Fleet physical Devices, ports or racks merely because NetBox uses DCIM. | -| servers.com assigns lowest-free 1U positions because physical positions are undisclosed. | Retain those source values only as synthetic display history. Import known rack association as RackMembership, subject to approved premises mapping; neither reserve nor verify invented units, faces or heights. | -| Commissioning uses asset tags, cable labels, circuit IDs, power feeds, photos and as-built records. | Preserve those distinct identifiers and restricted evidence references; do not flatten everything into serial or a free-form note. Address plans remain IPAM-owned. | -| Provisioning joins serial/model/OOB endpoint with networking data. | Preserve authorized consumer projections and explicit joins, not a duplicate networking API. Imported joins authorize no hardware actions, adoption, capacity eligibility or release. | -| Source lifecycle says active, decommissioning, vanished or decommissioned. | Retain as source observations. None proves physical verification, ownership transfer, secure cleanup, released consumer allocations or a free rack/termination. | - -Import batches retain source snapshot identity, mapping decisions, per-record -outcomes and conflicts for repeatable dry runs. The same source object/revision -must not create duplicate assets after a retry. Missing source observations do -not delete records or release occupancy. Never copy local provider tokens, BMC -password custom fields, kubeconfigs or secret-bearing generated configuration. +A writer that copies records from another system into Fleet writes ordinary +records through the same API and admission as any other writer, and is +observational until an explicit ownership transition. Fleet does not model +where those records came from. Never copy local provider tokens, BMC password +fields, kubeconfigs or secret-bearing generated configuration. Use a staged, reversible handoff rather than destructive in-place normalization: @@ -839,40 +820,23 @@ Use a staged, reversible handoff rather than destructive in-place normalization: virtual supply, identifier semantics, known occupancy and placement certainty. Produce a read-only mapping/conflict report with no hardware effects. 2. Approve Facility mappings, model/component shapes and per-installation history. - Create proposed plans without treating imported occupancy as free. Preserve + Create proposed plans without treating copied occupancy as free. Preserve current allocator reservations and consumer obligations under their owners. 3. Reconcile expected peer pairs into Cable plans and electrical dependencies into PowerFeeds. Resolve contradictions and unsupported paths explicitly. Validate partial placement and scoped external circuit associations without inventing absent endpoints or upstream sources. 4. Shadow-read and compare authorized provisioning inputs (identity, model, - restricted OOB endpoint and network-owned joins). Establish source parity for - the selected cohort, not an assertion of exhaustive NetBox equivalence. + restricted OOB endpoint and network-owned joins). Establish parity for + the selected cohort, not an assertion of exhaustive equivalence. 5. Transfer one writable surface at a time with an explicit cutover revision and predecessor preconditions. Disable its previous writer before enabling the - replacement. Keep compatibility projections read-only and retain source history. + replacement. Keep compatibility projections read-only. 6. Qualify current evidence and separately authorize custody/adoption and consumer integrations. Never seed Ready from an old active flag. Recovery/rollback uses retained cutover state; it cannot reactivate a stale writer, erase new history, or release a reservation whose physical state is uncertain. -## Source evidence and limits - -This amendment reviewed repository sources and read-only snapshots of infra -`main` at `d9198940a499be4e744ee0564cf3dc0b3bfcee34`. No live NetBox database audit, -provider call, electrical inspection, or hardware qualification was performed. -The sources motivate contract and migration requirements, not verified fleet-wide -data quality or proof that every production consumer has been found. - -| Pinned source | Evidence used | -| --- | --- | -| [Inventory sync guide][sync-guide], [NetActuate loader][na-loader], [servers.com loader][sc-loader] | Metro/provider mappings, host-ID serial semantics, virtual DCIM records, synthetic rack positions, and provider lifecycle observations. | -| [NetBox server guide][netbox-guide] | Operator inventory and provisioning inputs; existing networking/IPAM associations. | -| [Site commissioning][site-build], [rack work][rack-build], [network hardware][network-build], [compute hardware][compute-build] | Racks, serials, asset tags, labels, feeds, circuit IDs, address plans and external photos/LOAs/as-built artifacts. | -| [Out-of-band access commissioning][oob-build], [transit circuit commissioning][transit-build], [transport circuit commissioning][transport-build] | Physical delivery/demarcation and circuit identifiers distinct from service/routing readiness. | -| [Provisioning joins][provisioning-joins], [IPAM validation][ipam-validation] | Serial/model/OOB and network joins; address/routing validation stays with its current owner. | -| [Fleet manual types][manual-types], [Fleet manual operations][manual-guide] | The implemented manual subset and explicit slot-lifetime/storage divergences at the reviewed PR #90 revision. | - The [infrastructure provider responsibilities](bare-metal-hardware.md#infrastructure-providers), [capacity readiness reporting](bare-metal-hardware.md#status), and [ownership of records replaced by Fleet](bare-metal-hardware.md#replaced-artifacts) retain provider @@ -889,13 +853,13 @@ change**. Offline schema tests cannot establish physical truth. | --- | --- | --- | | References and scope | Wrong kind, missing scope, cross-project denial, dangling reference, name recreation, stale revision | Reject unauthorized/ambiguous resolution; no inherited binding or evidence. | | Facility and Rack | Multi-premises provider Site, unknown dimensions, conflicting faces/depth, 0U mount, known rack/unknown position | Preserve uncertainty; no invented geometry or false free-space assertion; exact reservations require accounted occupancy. | -| Identity and components | Duplicate serials, provider ID in serial, VM in DCIM, swapped asset tag, OS rename, replaced NIC/PSU/disk in the same slot | Adjudicate identity; retain source history; invalidate affected mappings without changing asset identity on ordinary repairs. | +| Identity and components | Duplicate serials, provider ID in serial, VM in DCIM, swapped asset tag, OS rename, replaced NIC/PSU/disk in the same slot | Adjudicate identity; retain history; invalidate affected mappings without changing asset identity on ordinary repairs. | | Binding and reservations | Concurrent claims, claim versus direct-Device cable endpoints, lost registration response, crash during handover, restored reservation database | One active placement and exclusive termination/footprint ownership; recover exact committed inputs; uncertainty keeps holds. | | Cable topology | Copper/optical mismatch, console direction, unresolved demarcation, patch-panel polarity, breakout lane collision, repatch/replacement | Reject unsupported paths; verify each required segment and invalidate changed dependencies, not just end-to-end link state. | | Power | Shared UPS behind distinct PDUs, unknown rating, mixed units, feed cycles, failover overbudget, stale upstream evidence | No false redundancy or capacity; independent sources and full failover budget proven under a qualified electrical model. | | Evidence and authority | Forged submitter, copied BMC location, stale scan, inaccessible document, unknown external circuit owner, attempted collector spec write | Fail closed for required checks; no self-attestation from copied intent, no status forgery or automatic exemption. | | Lifecycle | Occupied-slot replacement, move with active allocation, component removal, retirement with active references, cancelled partially installed plan | Retain history and consumer obligations; no premature physical release, destructive side effect or second active claim. | -| Import/cutover | Duplicate batch, conflicting inline peers, invented rack positions, source disappearance, rollback after new writes | Idempotent mapping, single writer, no Ready backfill or free-capacity window; keep unresolved facts unknown. | +| Migration/cutover | Duplicate batch, conflicting inline peers, invented rack positions, disappearing records, rollback after new writes | Idempotent mapping, single writer, no Ready backfill or free-capacity window; keep unresolved facts unknown. | | Access/projections | Inventory roles versus consumer roles, OOB/console endpoint reads, document ACLs, secret-bearing source fields | Restricted management details remain restricted; credentials never enter inventory projections or repository fixtures. | Before a facility cohort becomes eligible, record the qualified model variants, @@ -907,16 +871,3 @@ registration alone does not satisfy this gate. [manual-types]: https://github.com/datum-cloud/fleet/blob/08d6dde8563b7c999ecf839565db2bd37b4dda7e/internal/api/inventory/v1alpha1/types.go [manual-guide]: https://github.com/datum-cloud/fleet/blob/08d6dde8563b7c999ecf839565db2bd37b4dda7e/docs/operations/physical-inventory.md -[sync-guide]: https://github.com/datum-cloud/infra/blob/d9198940a499be4e744ee0564cf3dc0b3bfcee34/docs/guides/sync-inventory.md -[na-loader]: https://github.com/datum-cloud/infra/blob/d9198940a499be4e744ee0564cf3dc0b3bfcee34/bin/sync-netactuate-inventory -[sc-loader]: https://github.com/datum-cloud/infra/blob/d9198940a499be4e744ee0564cf3dc0b3bfcee34/bin/sync-serversdotcom-inventory -[netbox-guide]: https://github.com/datum-cloud/infra/blob/d9198940a499be4e744ee0564cf3dc0b3bfcee34/docs/guides/netbox-server.md -[site-build]: https://github.com/datum-cloud/infra/blob/d9198940a499be4e744ee0564cf3dc0b3bfcee34/.claude/skills/site-builds/phases/00-site.md -[oob-build]: https://github.com/datum-cloud/infra/blob/d9198940a499be4e744ee0564cf3dc0b3bfcee34/.claude/skills/site-builds/phases/04-oob.md -[transit-build]: https://github.com/datum-cloud/infra/blob/d9198940a499be4e744ee0564cf3dc0b3bfcee34/.claude/skills/site-builds/phases/05-transit.md -[transport-build]: https://github.com/datum-cloud/infra/blob/d9198940a499be4e744ee0564cf3dc0b3bfcee34/.claude/skills/site-builds/phases/06-transport.md -[network-build]: https://github.com/datum-cloud/infra/blob/d9198940a499be4e744ee0564cf3dc0b3bfcee34/.claude/skills/site-builds/phases/07-nethw.md -[compute-build]: https://github.com/datum-cloud/infra/blob/d9198940a499be4e744ee0564cf3dc0b3bfcee34/.claude/skills/site-builds/phases/08-computehw.md -[rack-build]: https://github.com/datum-cloud/infra/blob/d9198940a499be4e744ee0564cf3dc0b3bfcee34/.claude/skills/site-builds/phases/09-rack.md -[provisioning-joins]: https://github.com/datum-cloud/infra/blob/d9198940a499be4e744ee0564cf3dc0b3bfcee34/provisioning/baremetal/lib/common.sh -[ipam-validation]: https://github.com/datum-cloud/infra/blob/d9198940a499be4e744ee0564cf3dc0b3bfcee34/bin/validate-netbox-ipam diff --git a/docs/proposals/fleet-management/inventory.md b/docs/proposals/fleet-management/inventory.md index 69d4fcce..7122fe9f 100644 --- a/docs/proposals/fleet-management/inventory.md +++ b/docs/proposals/fleet-management/inventory.md @@ -176,21 +176,22 @@ for each installation and separate Cable records. That difference must be settle before automating moves and replacements. The current implementation uses manual entry and operator-controlled migration, -not automated import. NetBox and optional offline candidate review are not required. +not automated import. Fleet does not read any external inventory source. Migration must preserve existing equipment identities, customer reservations and history. Change the responsible writer only through an explicit approval. Do not delete and recreate assets, assume occupied space is free, or mark old records ready without new checks. -Source data needs interpretation: NetBox sites may group several premises, -serial fields may contain provider host IDs, device lists may include virtual -machines, and rack positions may have been invented for display. Preserve these -limitations rather than turning them into verified facts. +A separate writer that copies records from another system into Fleet writes +ordinary records through the same API and validation as any other writer. Data +copied that way needs interpretation: one external site may group several +premises, serial fields may contain provider host IDs, device lists may include +virtual machines, and rack positions may have been invented for display. Such a +writer should preserve these limitations rather than turning them into verified +facts. Where facts came from is that writer's concern, recorded on its own labels +and annotations; Fleet does not model it. -See the [comparison with existing records and migration steps](inventory-reference.md#existing-records-and-migration) -and the [source review and its limits](inventory-reference.md#source-evidence-and-limits). -No live NetBox audit has been performed, and complete coverage of existing data -has not been established. +See the [comparison with existing records and migration steps](inventory-reference.md#existing-records-and-migration). ## First release and success criteria diff --git a/hack/device_placement.py b/hack/device_placement.py deleted file mode 100644 index a0985c7d..00000000 --- a/hack/device_placement.py +++ /dev/null @@ -1,160 +0,0 @@ -"""Prepare guarded Device placement patches only. No API client or execution path.""" - -import argparse -import copy -import datetime -import math -import sys -from pathlib import Path - -from netbox_inventory import digest, read_json, reference_id, write_private, private_output - - -def source_report(snapshot, device, model, rack_name=None, facility_name=None): - report = {"revision": 1, "method": "NetBoxImport", "observedAt": snapshot["observedAt"], "snapshotDigest": digest(snapshot)} - if facility_name: - report["facilityRef"] = {"name": facility_name} - if not rack_name: - return report - report["rackRef"] = {"name": rack_name} - raw = device.get("position") - if raw is not None: - if isinstance(raw, bool): - raise ValueError("invalid source geometry") - try: - number = float(raw) - except (ValueError, TypeError): - raise ValueError("invalid source geometry") from None - if not math.isfinite(number) or number < 1 or number > 100: - raise ValueError("invalid source geometry") - report["position"] = number - face = device.get("face") - if isinstance(face, dict): - face = face.get("value") - if face is not None and face != "": - if face not in ("front", "rear"): - raise ValueError("invalid source face") - report["face"] = face - return report - - -def enrichment_plan(snapshot, target, allowlist, now=None): - now = now or datetime.datetime.now(datetime.timezone.utc) - for observed in (snapshot.get("observedAt"), target.get("observedAt")): - if not isinstance(observed, str): - raise ValueError("fresh source and target observation timestamps required") - timestamp = datetime.datetime.fromisoformat(observed.replace("Z", "+00:00")) - if timestamp.tzinfo is None or not 0 <= (now - timestamp).total_seconds() <= 900: - raise ValueError("source and target reads must be no more than 15 minutes old") - destination = target.get("target", {}) - if set(destination) != {"project", "namespace"} or not all(isinstance(value, str) and value for value in destination.values()): - raise ValueError("explicit direct-API project and namespace required") - if set(allowlist) != {"source", "target", "devices"} or allowlist["target"] != target.get("target") or allowlist["source"] != snapshot.get("source"): - raise ValueError("exact target and device allowlist required") - if not allowlist["devices"] or snapshot.get("errors"): - raise ValueError("empty allowlist or incomplete source snapshot") - datetime.datetime.fromisoformat(snapshot["observedAt"].replace("Z", "+00:00")) - objects = snapshot["objects"] - sources = {str(record["id"]): record for record in objects["dcim/devices"]} - models = {str(record["id"]): record for record in objects["dcim/device-types"]} - if len(sources) != len(objects["dcim/devices"]) or len(models) != len(objects["dcim/device-types"]): - raise ValueError("duplicate source identity") - records = {} - for record in target["items"]: - key = (record["kind"], record["metadata"].get("namespace"), record["metadata"]["name"]) - if key in records: - raise ValueError("duplicate target identity") - records[key] = record - planned, seen, seen_sources = [], set(), set() - for selection in allowlist["devices"]: - if set(selection) != {"name", "namespace", "uid", "resourceVersion", "sourceID"}: - raise ValueError("device allowlist has unexpected or missing fields") - if selection["namespace"] != destination["namespace"]: - raise ValueError("selection is outside the reviewed target namespace") - key = ("Device", selection["namespace"], selection["name"]) - if key in seen or selection["sourceID"] in seen_sources: - raise ValueError("duplicate allowlist target") - seen.add(key) - seen_sources.add(selection["sourceID"]) - device = records[key] - metadata, spec = device["metadata"], device["spec"] - if any(not selection[field] or metadata.get(field) != selection[field] for field in ("uid", "resourceVersion")) or metadata.get("deletionTimestamp"): - raise ValueError("stale or replaced target") - provenance = spec["provenance"] - if datetime.datetime.fromisoformat(snapshot["observedAt"].replace("Z", "+00:00")) <= datetime.datetime.fromisoformat(provenance["recordedAt"].replace("Z", "+00:00")): - raise ValueError("source snapshot does not advance the retained record revision") - identity = {"system": snapshot["source"], "type": "dcim/devices", "id": selection["sourceID"]} - if provenance["method"] != "NetBoxImport" or spec["identity"].get("sourceIdentity") != identity or any(provenance.get("source", {}).get(field) != value for field, value in identity.items()): - raise ValueError("not a matching imported device") - if gitops_owned(device): - raise ValueError("legacy Flux records are excluded") - claim = records[("DeviceClaim", selection["namespace"], spec["claimRef"]["name"])] - placement = claim["spec"]["placement"] - if claim["spec"].get("lifecycle") != "Installation" or placement.get("scope") != "RackMembership" or spec.get("reportedPlacement"): - raise ValueError("only previously unreported rack-membership enrichment is reviewable") - rack = records[("Rack", selection["namespace"], placement["rackRef"]["name"])] - source = sources[selection["sourceID"]] - rack_source = rack["spec"]["provenance"].get("source", {}) - if rack_source.get("system") != snapshot["source"] or rack_source.get("type") != "dcim/racks" or rack_source.get("id") != reference_id(source.get("rack")): - raise ValueError("rack contradiction or unresolved rack source") - for reference in (claim, rack): - if gitops_owned(reference): - raise ValueError("legacy Flux references are excluded") - if not reference["metadata"].get("uid") or not reference["metadata"].get("resourceVersion") or reference["metadata"].get("deletionTimestamp"): - raise ValueError("reference incarnation unresolved") - model = models[reference_id(source["device_type"])] - report = source_report(snapshot, source, model, rack["metadata"]["name"]) - if report.get("position") is None: - raise ValueError("selected enrichment lacks a source position") - height = rack["spec"].get("heightUnits") - if not height or report["position"] > height or ("height" in report and report["position"] + report["height"] - 1 > height): - raise ValueError("source position outside retained rack bounds") - after = copy.deepcopy(device) - after["spec"]["reportedPlacement"] = report - after["spec"]["provenance"]["recordedAt"] = snapshot["observedAt"] - after["spec"]["provenance"]["source"].update(observedAt=snapshot["observedAt"], snapshotDigest=digest(snapshot), mappingRevision="device-reported-placement-review-v2") - preconditions = [{"op": "test", "path": "/metadata/uid", "value": selection["uid"]}, {"op": "test", "path": "/metadata/resourceVersion", "value": selection["resourceVersion"]}] - patch = preconditions + [{"op": "add", "path": "/spec/reportedPlacement", "value": report}, {"op": "replace", "path": "/spec/provenance", "value": after["spec"]["provenance"]}] - planned.append({"selection": selection, "before": device, "proposedAfter": after, "references": [claim, rack], "sourceDevice": source, "sourceModel": model, - "preconditions": preconditions, "patch": patch, "patchDigest": digest(patch), - "contentType": "application/json-patch+json", "serverDryRunQuery": "dryRun=All&fieldManager=fleet-placement-enrichment", - "disposition": "Prepared only: require reviewed deployed head, fresh dependency reads, server dry-run, approved canary and exact readback"}) - return {"version": 2, "executable": False, "applied": False, "preparedAt": now.isoformat(), "sourceDigest": digest(snapshot), "targetDigest": digest(target), "allowlistDigest": digest(allowlist), "target": target["target"], "devices": planned, - "next": "Do not execute from this file alone. Confirm reviewed deployed schema head, refresh source/target and exact allowlist, retain authority and digests, server dry-run each patch, approve one canary, read back UID/spec before the remainder. Timeout is unknown: reconcile by GET; changed UID or competing revision is conflict, never retry automatically. No deletion or schema pruning rollback."} - - -def gitops_owned(record): - metadata = record["metadata"] - return any(any(marker in key.lower() for marker in ("fluxcd.io", "argocd")) for key in {**metadata.get("labels", {}), **metadata.get("annotations", {})}) or any(any(marker in entry.get("manager", "").lower() for marker in ("flux", "kustomize-controller", "helm-controller", "argocd")) for entry in metadata.get("managedFields", [])) - - -def reconcile(item, current): - if not isinstance(current, dict) or "metadata" not in current or "spec" not in current: - return "Unknown" - if current["metadata"].get("uid") != item["selection"]["uid"] or current["metadata"].get("deletionTimestamp"): - return "Conflict" - if current["spec"] == item["proposedAfter"]["spec"] and current["metadata"].get("resourceVersion") and current["metadata"]["resourceVersion"] != item["selection"]["resourceVersion"]: - return "Applied" - if current["spec"] == item["before"]["spec"] and current["metadata"].get("resourceVersion") == item["selection"]["resourceVersion"]: - return "Unchanged; no automatic retry" - return "Conflict" - - -def main(): - parser = argparse.ArgumentParser(description=__doc__) - for name in ("snapshot", "target", "allowlist", "output"): - parser.add_argument("--" + name, required=True) - args = parser.parse_args() - result = enrichment_plan(read_json(args.snapshot), read_json(args.target), read_json(args.allowlist)) - output = Path(args.output) - private_output(output) - write_private(output / "placement-review.json", result) - print("Prepared offline review saved; no writes dispatched:", len(result["devices"])) - - -if __name__ == "__main__": - try: - main() - except (ValueError, OSError, KeyError, TypeError) as error: - print("Placement review stopped:", str(error) if isinstance(error, ValueError) else type(error).__name__, file=sys.stderr) - sys.exit(2) diff --git a/hack/netbox_inventory.py b/hack/netbox_inventory.py deleted file mode 100644 index d2276285..00000000 --- a/hack/netbox_inventory.py +++ /dev/null @@ -1,797 +0,0 @@ -#!/usr/bin/env python3 -"""Optional operator-run review aid: GET-only snapshots and offline candidates. - -Manual inventory entry needs neither NetBox nor this tool. Nothing is applied, -scheduled, synchronized, or deleted; an operator reviews every proposed record. -""" - -import argparse -import copy -import datetime -import hashlib -import json -import os -from pathlib import Path -import re -import sys -import time -import urllib.error -import urllib.parse -import urllib.request - - -COMPONENTS = { - "interfaces": "NetworkPort", "power-ports": "PowerInlet", - "power-outlets": "PowerOutlet", "console-ports": "ConsolePort", - "console-server-ports": "ConsoleServerPort", "front-ports": "FrontPort", - "rear-ports": "RearPort", "modules": "Module", - "inventory-items": "InventoryItem", "device-bays": "DeviceBay", -} -SUPPORT = {"manufacturers", "device-types", "module-types", "device-roles", "rack-types"} -REQUIRED = {"dcim/" + name for name in ( - "sites", "locations", "racks", "devices", "device-types", "manufacturers", - "cables", "power-feeds", "power-panels", *COMPONENTS, -)} | {"circuits/circuits", "circuits/circuit-terminations"} -FIELDS = { - "id", "name", "display", "slug", "model", "manufacturer", "device_type", - "module_type", "device", "site", "location", "rack", "region", "parent", - "role", "type", "status", "serial", "asset_tag", "position", "face", - "u_height", "is_full_depth", "rear_port", "rear_port_position", "positions", - "power_port", "power_panel", "supply", "voltage", "amperage", "phase", - "a_terminations", "b_terminations", "object_type", "object_id", "object", - "termination_type", "termination_id", "termination", "circuit", "cid", - "provider", "term_side", "label", "value", "last_updated", "created", -} - - -def canonical(value): - return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=True) - - -def digest(value): - return "sha256:" + hashlib.sha256(canonical(value).encode()).hexdigest() - - -def reference_id(value): - if isinstance(value, dict): - value = value.get("id") - return str(value) if value is not None else "" - - -def value(record, key, default=""): - item = record.get(key, default) - return item.get("value", default) if isinstance(item, dict) else item - - -def sanitize(item): - if isinstance(item, dict): - return {key: sanitize(child) for key, child in item.items() if key in FIELDS} - if isinstance(item, list): - return [sanitize(child) for child in item] - return item - - -def name_ok(name): - return isinstance(name, str) and len(name) <= 253 and re.fullmatch(r"[a-z0-9](?:[-a-z0-9]*[a-z0-9])?(?:\.[a-z0-9](?:[-a-z0-9]*[a-z0-9])?)*", name) - - -class NoRedirect(urllib.request.HTTPRedirectHandler): - def redirect_request(self, request, response, code, message, headers, url): - raise ValueError("NetBox redirects are refused; configure the canonical HTTPS origin") - - -class Reader: - def __init__(self, url, token, auth_scheme="Bearer"): - self.base = url.rstrip("/") - parsed = urllib.parse.urlsplit(self.base) - if parsed.scheme != "https" or not parsed.hostname or parsed.username or parsed.password or parsed.query or parsed.fragment or parsed.path: - raise ValueError("NetBox URL must be a credential-free HTTPS origin") - if auth_scheme not in ("Bearer", "Token"): - raise ValueError("unsupported authorization scheme") - self.authorization = auth_scheme + " " + token.strip() - self.opener = urllib.request.build_opener(NoRedirect()) - - def get(self, url): - parsed = urllib.parse.urlsplit(url) - base = urllib.parse.urlsplit(self.base) - if parsed.scheme != base.scheme or parsed.netloc != base.netloc or not parsed.path.startswith("/api/") or parsed.fragment or parsed.username or parsed.password: - raise ValueError("refusing off-origin or non-API pagination link") - request = urllib.request.Request(url, headers={"Authorization": self.authorization, "Accept": "application/json"}, method="GET") - for attempt in range(3): - try: - with self.opener.open(request, timeout=30) as response: - return json.load(response) - except urllib.error.HTTPError as error: - if error.code not in (429, 500, 502, 503, 504) or attempt == 2: - raise ValueError("NetBox GET failed with HTTP " + str(error.code)) from None - except (urllib.error.URLError, TimeoutError): - if attempt == 2: - raise ValueError("NetBox GET failed: network unavailable") from None - time.sleep(2 ** attempt) - - def collection(self, path): - url = self.base + "/api/" + path.strip("/") + "/?limit=200" - seen_urls, records, count = set(), {}, None - while url: - if url in seen_urls: - raise ValueError("pagination cycle") - seen_urls.add(url) - page = self.get(url) - if not isinstance(page, dict) or not isinstance(page.get("results"), list) or not isinstance(page.get("count"), int): - raise ValueError("invalid paginated collection") - if count is not None and count != page["count"]: - raise ValueError("source count changed during export; restart the snapshot") - count = page["count"] - if count < 0 or (not page["results"] and page.get("next")): - raise ValueError("invalid count or empty nonterminal page") - for record in page["results"]: - identity = reference_id(record) - if not identity or identity in records: - raise ValueError("missing or repeated source ID during pagination") - records[identity] = sanitize(record) - if len(records) > count: - raise ValueError("snapshot exceeds advertised source count") - next_url = page.get("next") - url = urllib.parse.urljoin(url, next_url) if next_url else None - if url and urllib.parse.urlsplit(url).path != "/api/" + path.strip("/") + "/": - raise ValueError("pagination changed collection") - if len(records) != count: - raise ValueError("source count does not match snapshot") - return sorted(records.values(), key=lambda record: reference_id(record)) - - -def snapshot(reader, source): - if not name_ok(source): - raise ValueError("source must be a stable DNS-style instance name") - started = datetime.datetime.now(datetime.timezone.utc).isoformat() - objects, errors, excluded_endpoints = {}, {}, {} - for app in ("dcim", "circuits"): - try: - discovery = reader.get(reader.base + "/api/" + app + "/") - if not isinstance(discovery, dict): - raise ValueError("invalid API discovery") - except ValueError as error: - errors[app + "/"] = str(error) - continue - for collection in sorted(discovery): - if not re.fullmatch(r"[a-z0-9-]+", collection): - raise ValueError("invalid API collection name") - path = app + "/" + collection - if path == "dcim/connected-device": - excluded_endpoints[path] = "parameterized connectivity lookup, not an inventory collection" - continue - try: - objects[path] = reader.collection(path) - except ValueError as error: - errors[path] = str(error) - for path in REQUIRED - objects.keys() - errors.keys(): - errors[path] = "required collection not advertised by this NetBox version" - return {"version": 1, "source": source, "observedAt": started, "completedAt": datetime.datetime.now(datetime.timezone.utc).isoformat(), "objects": objects, "errors": errors, "excludedEndpoints": excluded_endpoints} - - -def local_ref(name): - return {"name": name} - - -class Planner: - def __init__(self, source, mapping, existing=None, previous=None): - self.snapshot = source - self.mapping = mapping - self.source = source.get("source", "") - if source.get("version") != 1 or not name_ok(self.source): - raise ValueError("unsupported snapshot or invalid source identity") - datetime.datetime.fromisoformat(source["observedAt"].replace("Z", "+00:00")) - self.target = mapping.get("target", {}) - self.namespace = self.target.get("namespace", "") - self.revision = mapping.get("revision", "") - self.records, self.report, self.candidates = {}, {}, {} - self.existing = existing - if existing is not None and existing.get("target") != self.target: - raise ValueError("Fleet snapshot target must exactly match the reviewed provider project, namespace and application") - physical_kinds = {"Facility", "Rack", "DeviceClaim", "Device", "Cable", "PowerFeed"} - if existing is not None and set(existing.get("collections", [])) not in (physical_kinds, physical_kinds | {"Site"}): - raise ValueError("Fleet snapshot must attest all six inventory collections, including empty ones") - if mapping.get("operationalSites") and (existing is None or "Site" not in existing.get("collections", [])): - raise ValueError("operational Site mapping requires a complete Fleet snapshot including Sites") - self.previous = previous - self.digest = digest(source) - self.device_names, self.rack_names, self.feed_names = {}, {}, {} - for collection, records in source.get("objects", {}).items(): - for record in records: - identity = reference_id(record) - key = collection + "/" + identity - if not identity or key in self.records: - raise ValueError("duplicate or absent source identity") - self.records[key] = record - self.report[key] = {"source": key, "classification": "unsupported", "reason": "source object class has no physical adapter", "targets": []} - - def rows(self, collection): - return [(key, record) for key, record in sorted(self.records.items()) if key.rsplit("/", 1)[0] == collection] - - def mark(self, key, classification, reason, targets=()): - self.report[key] = {"source": key, "classification": classification, "reason": reason, "targets": list(targets)} - - def stable_name(self, kind, identity): - return "nb-" + hashlib.sha256((self.source + "/" + kind + "/" + identity).encode()).hexdigest()[:24] - - def external(self, key): - collection, identity = key.rsplit("/", 1) - return {"system": self.source, "type": collection, "id": identity} - - def add(self, key, kind, name, spec): - if not name_ok(name): - raise ValueError("invalid mapped Fleet name") - provenance = {"method": "NetBoxImport", "recordedBy": "netbox-inventory-offline", "recordedAt": self.snapshot["observedAt"], "source": dict(self.external(key), snapshotDigest=self.digest, mappingRevision=self.revision or "unreviewed", observedAt=self.snapshot["observedAt"])} - record = {"apiVersion": "fleet.datumapis.com/v1alpha1", "kind": kind, "metadata": {"name": name, "namespace": self.namespace}, "spec": dict(spec, provenance=provenance)} - target = kind + "/" + name - if target in self.candidates: - raise ValueError("multiple source records mapped to the same target") - self.candidates[target] = record - self.mark(key, "imported", "observational candidate; not applied or verified", [*self.report[key]["targets"], target]) - return target - - def facilities(self): - for key, record in self.rows("dcim/sites") + self.rows("dcim/locations"): - self.mark(key, "unresolved", "provider/metro sites and locations require an explicit premises mapping") - for facility in self.mapping.get("facilities", []): - key = facility["source"] - if key not in self.records or key.rsplit("/", 1)[0] not in ("dcim/sites", "dcim/locations"): - raise ValueError("facility source must name a present site or location") - spec = {"displayName": facility["displayName"]} - if "identifiers" in facility: - if facility.get("identifiersVerified") is not True: - raise ValueError("provider premises identifiers require explicit verification") - spec["identifiers"] = copy.deepcopy(facility["identifiers"]) - if facility.get("locationRef"): - spec["locationRef"] = local_ref(facility["locationRef"]) - self.add(key, "Facility", facility["name"], spec) - for key, record in self.rows("dcim/racks"): - selected = self.mapping.get("racks", {}).get(reference_id(record)) - if not selected or "Facility/" + selected.get("facility", "") not in self.candidates: - self.mark(key, "unresolved", "rack needs a mapped physical facility") - continue - name = self.stable_name("rack", reference_id(record)) - spec = {"displayName": record.get("name", name), "facilityRef": local_ref(selected["facility"])} - if isinstance(record.get("u_height"), int) and 1 <= record["u_height"] <= 100: - spec["heightUnits"] = record["u_height"] - self.add(key, "Rack", name, spec) - self.rack_names[reference_id(record)] = name - - def devices(self): - for key, record in self.rows("dcim/devices"): - identity = reference_id(record) - selected = self.mapping.get("devices", {}).get(identity, {}) - role = record.get("role") or {} - dtype = record.get("device_type") or {} - model = self.records.get("dcim/device-types/" + reference_id(dtype), dtype) - manufacturer = model.get("manufacturer") or {} - hints = canonical([role, manufacturer, model.get("model", "")]).lower() - if "netactuate" in hints or "hosted-vm" in hints: - self.mark(key, "excluded", "NetActuate/hosted VM represented in DCIM; not a physical asset") - continue - if selected.get("classification") == "excluded" and selected.get("reason"): - self.mark(key, "excluded", selected["reason"]) - continue - if selected.get("classification") != "physical" or not selected.get("serialMeaning") in ("chassis", "providerHostID", "unknown"): - self.mark(key, "unresolved", "review physical classification and serial meaning for this device") - continue - placement = selected.get("placement", {}) - rack_id = reference_id(record.get("rack")) - if placement.get("scope") == "RackMembership" and rack_id in self.rack_names: - placement = {"scope": "RackMembership", "rackRef": local_ref(self.rack_names[rack_id])} - elif placement.get("scope") == "Facility" and "Facility/" + placement.get("facility", "") in self.candidates: - placement = {"scope": "Facility", "facilityRef": local_ref(placement["facility"])} - else: - self.mark(key, "unresolved", "import accepts reviewed facility or known-rack/unknown-position placement only") - continue - if not model.get("model"): - self.mark(key, "unresolved", "device model is absent") - continue - name = self.stable_name("device", identity) - claim_name = self.stable_name("installation", identity) - asset_identity = {"model": model["model"], "sourceIdentity": self.external(key)} - if manufacturer.get("name"): - asset_identity["manufacturer"] = manufacturer["name"] - serial = record.get("serial") - if serial and ("servers.com" in hints or "serversdotcom" in hints) and selected["serialMeaning"] == "chassis": - self.mark(key, "unresolved", "servers.com loader serial is a provider host ID, not a chassis serial") - continue - if serial and selected["serialMeaning"] == "chassis": - asset_identity["serial"] = serial - spec = {"displayName": record.get("name") or name, "claimRef": local_ref(claim_name), "identity": asset_identity, "topologyAuthority": "Cable"} - if selected.get("includeReportedPlacement") is True: - from device_placement import source_report - spec["reportedPlacement"] = source_report(self.snapshot, record, model, placement.get("rackRef", {}).get("name"), placement.get("facilityRef", {}).get("name")) - shape = {} - try: - height = float(model.get("u_height", "")) - if 0 <= height <= 100: - shape["heightUnits"] = height - except (ValueError, TypeError): - pass - if isinstance(model.get("is_full_depth"), bool): - shape["fullDepth"] = model["is_full_depth"] - if shape: - spec["modelShape"] = shape - if serial and selected["serialMeaning"] == "providerHostID": - if not selected.get("provider"): - self.mark(key, "unresolved", "provider host ID requires its provider authority") - continue - spec["providerHostRef"] = {"system": selected["provider"], "type": "host", "id": serial} - if record.get("asset_tag"): - spec["assetTag"] = record["asset_tag"] - self.add(key, "DeviceClaim", claim_name, {"displayName": record.get("name") or name, "lifecycle": "Installation", "expectedIdentity": {name: item for name, item in asset_identity.items() if name != "sourceIdentity"}, "placement": placement}) - self.add(key, "Device", name, spec) - self.device_names[identity] = name - - def components(self): - for collection, kind in COMPONENTS.items(): - for key, record in self.rows("dcim/" + collection): - device_id = reference_id(record.get("device")) - if device_id not in self.device_names: - parent = self.report.get("dcim/devices/" + device_id, {}) - state = "excluded" if parent.get("classification") == "excluded" else "unresolved" - self.mark(key, state, "parent device is excluded or unresolved") - continue - if collection == "interfaces" and value(record, "type") in ("virtual", "lag", "bridge"): - self.mark(key, "excluded", "logical interface belongs to networking, not physical inventory") - continue - target = "Device/" + self.device_names[device_id] - component = {"id": collection + "-" + reference_id(record), "name": record.get("name") or record.get("display") or reference_id(record), "type": kind, "sourceRef": self.external(key)} - connector = value(record, "type") - if connector: - component["connector"] = connector - positions = record.get("positions") - if (collection == "rear-ports" or "positions" in record) and (type(positions) is not int or not 1 <= positions <= 256): - self.mark(key, "unresolved", "component capacity must be an explicit integer from 1 to 256; never infer singleton geometry", [target]) - continue - if positions is not None: - component["positions"] = positions - for source_field, target_field in (("serial", "serial"), ("asset_tag", "assetTag")): - if record.get(source_field): - component[target_field] = record[source_field] - self.candidates[target]["spec"].setdefault("components", []).append(component) - self.mark(key, "imported", "typed component on the parent asset", [target]) - for collection, parent_field, parent_collection in (("front-ports", "rear_port", "rear-ports"), ("power-outlets", "power_port", "power-ports")): - for key, record in self.rows("dcim/" + collection): - if self.report[key]["classification"] != "imported": - continue - parent_id = reference_id(record.get(parent_field)) - if not parent_id: - self.report[key]["reason"] += "; internal dependency Unknown" - continue - target = self.report[key]["targets"][0] - parent_key = "dcim/" + parent_collection + "/" + parent_id - if self.report.get(parent_key, {}).get("targets") != [target]: - self.mark(key, "unresolved", "internal dependency has a missing or different parent device", [target]) - continue - parent_position = 1 - if collection == "front-ports": - parent_position = record.get("rear_port_position") - if type(parent_position) is not int or not 1 <= parent_position <= 256: - self.mark(key, "unresolved", "front port requires an explicit valid rear-port position; never infer position one", [target]) - continue - mapping = {"from": {"componentID": collection + "-" + reference_id(record), "position": 1}, "to": {"componentID": parent_collection + "-" + parent_id, "position": parent_position}} - self.candidates[target]["spec"].setdefault("internalMappings", []).append(mapping) - - def feeds(self): - for key, record in self.rows("dcim/power-panels"): - self.mark(key, "unresolved", "panel is external electrical dependency evidence, not a fabricated asset") - for key, record in self.rows("dcim/power-feeds"): - selected = self.mapping.get("feeds", {}).get(reference_id(record), {}) - if "Facility/" + selected.get("facility", "") not in self.candidates: - self.mark(key, "unresolved", "feed requires an explicit facility mapping") - continue - name = self.stable_name("feed", reference_id(record)) - spec = {"displayName": record.get("name", name), "facilityRef": local_ref(selected["facility"]), "terminations": [{"id": "output", "name": "output", "type": "PowerOutlet"}]} - rack = self.rack_names.get(reference_id(record.get("rack"))) - if rack: - spec["rackRef"] = local_ref(rack) - supply = {"type": str(value(record, "supply", "Unknown")).upper()} - if supply["type"] not in ("AC", "DC"): - supply["type"] = "Unknown" - for field, target_field in (("voltage", "voltageV"), ("amperage", "currentA")): - if isinstance(record.get(field), int) and 0 < record[field] <= 100000: - supply[target_field] = record[field] - if value(record, "phase") in ("single-phase", "three-phase"): - supply["phase"] = value(record, "phase") - spec["supply"] = supply - panel_key = "dcim/power-panels/" + reference_id(record.get("power_panel")) - if panel_key in self.records: - spec["upstreamSources"] = [self.external(panel_key)] - self.mark(panel_key, "imported", "external electrical panel reference only; upstream independence Unknown", sorted(set(self.report[panel_key]["targets"] + ["PowerFeed/" + name]))) - self.add(key, "PowerFeed", name, spec) - self.feed_names[reference_id(record)] = name - - def endpoint(self, termination): - kind = termination.get("object_type") or termination.get("termination_type") - identity = reference_id(termination.get("object_id") or termination.get("termination_id") or termination.get("object") or termination.get("termination")) - if kind == "dcim.powerfeed" and identity in self.feed_names: - return {"powerFeedRef": local_ref(self.feed_names[identity]), "componentID": "output", "position": 1} - collection = next((name for name in COMPONENTS if "dcim." + name.replace("-", "").rstrip("s") == kind), None) - if kind == "dcim.inventoryitem": - collection = "inventory-items" - key = "dcim/" + str(collection) + "/" + identity - if kind == "circuits.circuittermination": - selected = self.mapping.get("demarcations", {}).get(identity) - if not selected: - return None - key = selected.get("componentSource", "") - state = self.report.get(key, {}) - if state.get("classification") != "imported" or not state.get("targets"): - return None - target = state["targets"][0] - if not target.startswith("Device/"): - return None - source_class, source_id = key.rsplit("/", 1) - return {"deviceRef": local_ref(target.split("/", 1)[1]), "componentID": source_class.split("/")[1] + "-" + source_id, "position": 1} - - def circuits(self): - for key, record in self.rows("circuits/circuits"): - self.mark(key, "unresolved", "circuit requires an external service-owner reference; no Fleet Circuit kind") - for key, record in self.rows("circuits/circuit-terminations"): - circuit_key = "circuits/circuits/" + reference_id(record.get("circuit")) - owner = self.mapping.get("circuits", {}).get(reference_id(record.get("circuit"))) - endpoint = self.endpoint({"object_type": "circuits.circuittermination", "object_id": reference_id(record)}) - if not owner or not all(owner.get(field) for field in ("system", "type", "id")) or not endpoint or circuit_key not in self.records: - self.mark(key, "unresolved", "local demarcation and external service owner must both be mapped") - continue - target = "Device/" + endpoint["deviceRef"]["name"] - self.candidates[target]["spec"].setdefault("serviceAssociations", []).append({"serviceRef": {field: owner[field] for field in ("system", "type", "id")}, "componentID": endpoint["componentID"]}) - self.mark(key, "imported", "local physical demarcation association only", [target]) - self.mark(circuit_key, "imported", "external service-owner reference only; no service or IPAM migration", sorted(set(self.report[circuit_key]["targets"] + [target]))) - - def cables(self): - for key, record in self.rows("dcim/cables"): - ends = [record.get("a_terminations", []), record.get("b_terminations", [])] - selected = self.mapping.get("cables", {}).get(reference_id(record), {}) - lanes = selected.get("lanes") - available = [[self.endpoint(termination) for termination in end] for end in ends] - if not all(available) or any(endpoint is None for side in available for endpoint in side): - self.mark(key, "unresolved", "cable endpoint is missing, excluded, or has no reviewed demarcation") - continue - if lanes: - lanes = copy.deepcopy(lanes) - represented = [set(), set()] - valid = isinstance(lanes, list) and len(lanes) <= 64 - for lane in lanes if valid else []: - if not isinstance(lane, dict) or not name_ok(lane.get("id")): - valid = False - break - for index, side in enumerate(("a", "b")): - endpoint = lane.get(side) - if not isinstance(endpoint, dict) or not isinstance(endpoint.get("position"), int) or endpoint["position"] < 1: - valid = False - break - base_endpoint = dict(endpoint, position=1) - if base_endpoint not in available[index]: - valid = False - break - represented[index].add(canonical(base_endpoint)) - if not valid or any(represented[index] != {canonical(endpoint) for endpoint in available[index]} for index in (0, 1)): - self.mark(key, "unresolved", "reviewed lanes must account for every source termination on its original side") - continue - else: - if any(len(end) != 1 for end in ends): - self.mark(key, "unsupported", "multi-termination cable needs reviewed explicit lane mappings; no all-to-all inference") - continue - endpoints = [end[0] for end in available] - multiposition = False - for endpoint in endpoints: - if endpoint.get("deviceRef"): - device = self.candidates["Device/" + endpoint["deviceRef"]["name"]] - component = next(component for component in device["spec"]["components"] if component["id"] == endpoint["componentID"]) - multiposition |= component.get("positions", 1) > 1 - if multiposition: - self.mark(key, "unresolved", "multi-position termination needs explicit lanes; never infer position one for a trunk") - continue - lanes = [{"id": "lane-1", "a": endpoints[0], "b": endpoints[1]}] - medium = selected.get("medium") - if medium not in ("Copper", "Fiber", "Power", "Console"): - self.mark(key, "unresolved", "cable medium requires review; source connector codes are not qualification") - continue - name = self.stable_name("cable", reference_id(record)) - self.add(key, "Cable", name, {"displayName": record.get("label") or name, "medium": medium, "lanes": lanes}) - - def operational_sites(self): - existing = {record["kind"] + "/" + record["metadata"]["name"]: record for record in (self.existing or {}).get("items", [])} - malformed_sources = set() - sites = self.mapping.get("operationalSites", []) - if not isinstance(sites, list): - raise ValueError("operational Site mappings must be a list") - for site in sites: - if not isinstance(site, dict): - raise ValueError("operational Site mapping must be an object") - if site.get("verified") is not True: - raise ValueError("operational Site mapping requires explicit verified Facility references") - source = site.get("source", "") - if not isinstance(source, str) or source not in self.records or source.rsplit("/", 1)[0] not in ("dcim/sites", "dcim/locations"): - raise ValueError("operational Site source must name a present site or location") - refs = site.get("facilityRefs") - valid = (set(site) <= {"name", "displayName", "code", "source", "verified", "facilityRefs"} - and name_ok(site.get("name")) - and isinstance(site.get("displayName"), str) and 1 <= len(site["displayName"]) <= 253 - and isinstance(site.get("code"), str) and 1 <= len(site["code"]) <= 64 - and isinstance(refs, list) and 1 <= len(refs) <= 64 - and all(isinstance(ref, dict) and set(ref) == {"name"} and name_ok(ref["name"]) for ref in refs)) - if not valid or len({ref["name"] for ref in refs}) != len(refs): - malformed_sources.add(source) - continue - for reference in site["facilityRefs"]: - facility = existing.get("Facility/" + reference.get("name", ""), {}) - metadata = facility.get("metadata", {}) - if set(reference) != {"name"} or not name_ok(reference.get("name")) or metadata.get("namespace") != self.namespace or metadata.get("deletionTimestamp"): - raise ValueError("operational Site mapping requires a name-only reference to an existing Facility in this namespace") - self.add(source, "Site", site["name"], {"displayName": site["displayName"], "code": site["code"], "facilityRefs": copy.deepcopy(site["facilityRefs"])}) - for source in malformed_sources: - self.mark(source, "unresolved", "malformed operational Site mapping; review field types, lengths and unique name-only references", self.report[source]["targets"]) - - def reconcile(self): - current = {} - for record in (self.existing or {}).get("items", []): - if record.get("apiVersion") != "fleet.datumapis.com/v1alpha1" or record.get("metadata", {}).get("namespace") != self.namespace: - raise ValueError("Fleet snapshot must contain only this namespace's physical inventory") - key = record["kind"] + "/" + record["metadata"]["name"] - if key in current: - raise ValueError("duplicate Fleet target identity") - current[key] = record - conflicts, unchanged = {}, set() - for key, candidate in self.candidates.items(): - if key in current: - old_spec, new_spec = copy.deepcopy(current[key]["spec"]), copy.deepcopy(candidate["spec"]) - old_provenance, new_provenance = old_spec.pop("provenance"), new_spec.pop("provenance") - source_fields = ("system", "type", "id") - same_source = all(old_provenance.get("source", {}).get(field) == new_provenance["source"][field] for field in source_fields) - if same_source and old_spec == new_spec: - unchanged.add(key) - else: - conflicts[key] = "existing target differs; no automatic update, claim rebinding, or ownership takeover" - if candidate["kind"] == "Device": - spec = candidate["spec"] - for other_key, other in {**current, **self.candidates}.items(): - if other_key == key or other.get("kind") != "Device": - continue - other_spec = other["spec"] - pairs = [(spec.get("assetTag"), other_spec.get("assetTag")), (spec.get("providerHostRef"), other_spec.get("providerHostRef")), (spec.get("providerHostRef", {}).get("id"), other_spec["identity"].get("serial")), (spec["identity"].get("serial"), other_spec["identity"].get("serial")), (spec["identity"].get("sourceIdentity"), other_spec["identity"].get("sourceIdentity"))] - if any(left and left == right for left, right in pairs): - conflicts[key] = "possible existing asset identity; preserve Device/claim/capacity and adjudicate privately" - all_records = {**current, **self.candidates} - for key, reasons in validate_graph(all_records).items(): - if key in self.candidates: - conflicts[key] = "; ".join(reasons) - changed = True - while changed: - changed = False - for entry in self.report.values(): - if entry["classification"] == "unresolved": - for target in entry["targets"]: - if target not in conflicts: - conflicts[target] = "one or more source relationships are unresolved" - changed = True - if any(target in conflicts for target in entry["targets"]): - for target in entry["targets"]: - if target not in conflicts: - conflicts[target] = "same source record has a quarantined dependency" - changed = True - for key, record in self.candidates.items(): - if key not in conflicts and any(target in conflicts for target in dependencies(record)): - conflicts[key] = "referenced candidate is quarantined" - changed = True - for entry in self.report.values(): - failed = [target for target in entry["targets"] if target in conflicts] - if failed: - entry.update(classification="unresolved", reason=conflicts[failed[0]]) - elif entry["targets"] and all(target in unchanged for target in entry["targets"]): - entry["reason"] = "already present with same source identity and physical fields; no write" - self.candidates = {key: record for key, record in self.candidates.items() if key not in conflicts and key not in unchanged} - return conflicts - - def run(self): - self.facilities() - self.devices() - self.components() - self.feeds() - self.circuits() - self.cables() - self.operational_sites() - for key in self.records: - collection = key.rsplit("/", 1)[0] - if collection.startswith("dcim/") and collection.split("/")[1] in SUPPORT: - self.mark(key, "excluded", "model/catalog metadata consumed where referenced; no independent physical asset") - elif collection.endswith("-templates"): - self.mark(key, "excluded", "model template is not installed hardware; actual instances imported separately") - elif collection in ("dcim/regions", "dcim/site-groups", "dcim/rack-roles", "dcim/virtual-chassis", "circuits/providers", "circuits/provider-accounts", "circuits/provider-networks", "circuits/circuit-types"): - self.mark(key, "excluded", "grouping or service-owner metadata; not physical premises or installed assets") - conflicts = self.reconcile() - omitted = sorted(set((self.previous or {}).get("objects", {})) - set(self.snapshot.get("objects", {}))) - prior_keys = {collection + "/" + reference_id(record) for collection, rows in (self.previous or {}).get("objects", {}).items() for record in rows} - if self.previous and self.previous.get("source") != self.source: - raise ValueError("previous snapshot belongs to another source") - errors = dict(self.snapshot.get("errors", {})) - for collection in REQUIRED - self.snapshot.get("objects", {}).keys(): - errors.setdefault(collection, "required collection absent; coverage unknown") - retained = [] - for record in (self.existing or {}).get("items", []): - source = record.get("spec", {}).get("provenance", {}).get("source", {}) - if source.get("system") == self.source and source.get("type", "") + "/" + source.get("id", "") not in self.records: - retained.append(record["kind"] + "/" + record["metadata"]["name"]) - return {"version": 1, "source": self.source, "snapshotDigest": self.digest, "observedAt": self.snapshot["observedAt"], "target": self.target, "mappingRevision": self.revision, "coverageComplete": not errors, "collectionErrors": errors, "excludedEndpoints": self.snapshot.get("excludedEndpoints", {}), "omittedCollections": omitted, "missingSincePrevious": sorted(prior_keys - self.records.keys()), "retainedMissingSource": retained, "deletions": [], "conflicts": conflicts, "records": list(self.report.values()), "candidateCount": len(self.candidates), "readiness": "Unknown", "applied": False}, list(self.candidates.values()) - - -def dependencies(record): - spec = record["spec"] - references = [] - for reference in spec.get("facilityRefs", []): - references.append("Facility/" + reference["name"]) - for field, kind in (("claimRef", "DeviceClaim"), ("facilityRef", "Facility"), ("rackRef", "Rack")): - if spec.get(field): - references.append(kind + "/" + spec[field]["name"]) - if spec.get("placement", {}).get(field): - references.append(kind + "/" + spec["placement"][field]["name"]) - if spec.get("reportedPlacement", {}).get(field): - references.append(kind + "/" + spec["reportedPlacement"][field]["name"]) - for lane in spec.get("lanes", []): - for endpoint in (lane["a"], lane["b"]): - for field, kind in (("deviceRef", "Device"), ("powerFeedRef", "PowerFeed")): - if endpoint.get(field): - references.append(kind + "/" + endpoint[field]["name"]) - return references - - -def validate_graph(records): - errors, occupied = {}, {} - def fail(key, reason): - errors.setdefault(key, []).append(reason) - for key, record in records.items(): - for target in dependencies(record): - if target not in records: - fail(key, "missing local reference " + target) - spec = record["spec"] - if record["kind"] == "Site": - seen_names = set() - for reference in spec.get("facilityRefs", []): - target = records.get("Facility/" + reference.get("name", ""), {}) - metadata = target.get("metadata", {}) - if set(reference) != {"name"} or not name_ok(reference.get("name")) or metadata.get("namespace") != record["metadata"].get("namespace") or metadata.get("deletionTimestamp") or reference.get("name") in seen_names: - fail(key, "invalid or unavailable Facility membership reference") - seen_names.add(reference.get("name")) - if record["kind"] == "Facility": - seen_identifiers = set() - identifiers = spec.get("identifiers", []) - if not isinstance(identifiers, list) or len(identifiers) > 64: - fail(key, "premises identifiers must be a list with at most 64 entries") - identifiers = [] - for identifier in identifiers: - if not isinstance(identifier, dict) or set(identifier) != {"provider", "type", "value"} or not all(isinstance(value, str) for value in identifier.values()): - fail(key, "premises identifier must contain only provider, type and value strings") - continue - identity = tuple(identifier.get(field) for field in ("provider", "type", "value")) - if not name_ok(identifier.get("provider")) or identifier.get("type") not in ("PremisesCode", "PremisesAlias", "PremisesID") or not isinstance(identifier.get("value"), str) or not 1 <= len(identifier["value"]) <= 253 or identity in seen_identifiers: - fail(key, "invalid provider-qualified premises identifier") - seen_identifiers.add(identity) - components = {component["id"]: component for component in spec.get("components", [])} - mapped_positions = set() - for mapping in spec.get("internalMappings", []): - for end in (mapping["from"], mapping["to"]): - component = components.get(end["componentID"]) - if not component or not 1 <= end["position"] <= component.get("positions", 1): - fail(key, "invalid internal component mapping") - source_type = components.get(mapping["from"]["componentID"], {}).get("type") - target_type = components.get(mapping["to"]["componentID"], {}).get("type") - if (source_type, target_type) not in (("FrontPort", "RearPort"), ("PowerOutlet", "PowerInlet")): - fail(key, "incompatible internal component types") - if source_type == "FrontPort": - position = canonical(mapping["to"]) - if position in mapped_positions: - fail(key, "pass-through rear position mapped more than once") - mapped_positions.add(position) - for association in spec.get("serviceAssociations", []): - if association["componentID"] not in components: - fail(key, "service demarcation names a missing component") - for lane in spec.get("lanes", []): - kinds = [] - for endpoint in (lane["a"], lane["b"]): - owner = ("Device/" + endpoint["deviceRef"]["name"]) if endpoint.get("deviceRef") else ("PowerFeed/" + endpoint["powerFeedRef"]["name"]) - target = records.get(owner, {}).get("spec", {}) - components = target.get("components", []) + target.get("terminations", []) - component = next((component for component in components if component["id"] == endpoint["componentID"]), None) - if not component or not 1 <= endpoint["position"] <= component.get("positions", 1): - fail(key, "unresolved endpoint component or position") - continue - kinds.append(component["type"]) - connector = component.get("connector", "").lower() - if spec.get("medium") == "Fiber" and ("base-t" in connector or "rj45" in connector): - fail(key, "fiber cable on a copper termination") - identity = owner + "/" + endpoint["componentID"] + "/" + str(endpoint["position"]) - if identity in occupied: - fail(key, "termination already used") - fail(occupied[identity], "termination already used") - occupied[identity] = key - allowed = {"Power": {"PowerInlet", "PowerOutlet"}, "Console": {"ConsolePort", "ConsoleServerPort", "FrontPort", "RearPort"}, "Copper": {"NetworkPort", "FrontPort", "RearPort"}, "Fiber": {"NetworkPort", "FrontPort", "RearPort"}} - if spec.get("medium") not in allowed or not set(kinds) <= allowed[spec["medium"]]: - fail(key, "incompatible or unknown cable medium and component types") - if spec.get("medium") == "Power" and sorted(kinds) != ["PowerInlet", "PowerOutlet"]: - fail(key, "power cable must connect an outlet to an inlet") - if spec.get("medium") == "Console" and all(kind in ("ConsolePort", "ConsoleServerPort") for kind in kinds) and sorted(kinds) != ["ConsolePort", "ConsoleServerPort"]: - fail(key, "unsupported console direction; adapter mapping required") - return errors - - -def read_json(path): - with open(path) as stream: - return json.load(stream) - - -def write_private(path, content): - descriptor = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) - with os.fdopen(descriptor, "w") as stream: - json.dump(content, stream, sort_keys=True, indent=2) - stream.write("\n") - - -def private_output(path): - resolved = path.resolve() - if any((parent / ".git").exists() for parent in (resolved, *resolved.parents)): - raise ValueError("private snapshots and handoffs must be written outside Git checkouts") - path.mkdir(mode=0o700, parents=False, exist_ok=False) - - -def main(argv=None): - parser = argparse.ArgumentParser(description=__doc__) - subparsers = parser.add_subparsers(dest="command", required=True) - export = subparsers.add_parser("snapshot", help="explicitly read a private NetBox snapshot; optional") - export.add_argument("--url", default=os.environ.get("NETBOX_URL", "https://netbox.datum-infra.net")) - export.add_argument("--source", required=True) - export.add_argument("--auth-scheme", choices=("Bearer", "Token"), default="Bearer") - export.add_argument("--output", required=True) - plan = subparsers.add_parser("plan", help="review a local snapshot offline; never apply records") - plan.add_argument("--snapshot", required=True) - plan.add_argument("--mapping") - plan.add_argument("--existing") - plan.add_argument("--previous") - plan.add_argument("--output", required=True) - plan.add_argument("--handoff", action="store_true", help="also write optional review candidates; never apply, commit, or push") - plan.add_argument("--allow-partial", action="store_true") - args = parser.parse_args(argv) - output = Path(args.output) - private_output(output) - if args.command == "snapshot": - token = os.environ.get("NETBOX_TOKEN") - if not token: - token_path = Path(os.environ.get("NETBOX_TOKEN_FILE", "~/.config/netbox/token")).expanduser() - if not token_path.is_file(): - raise ValueError("no authorized NetBox read credential in the documented environment/file paths") - token = token_path.read_text().strip() - result = snapshot(Reader(args.url, token, args.auth_scheme), args.source) - write_private(output / "snapshot.json", result) - print("Private snapshot saved; collection errors:", len(result["errors"])) - return 2 if result["errors"] else 0 - mapping = read_json(args.mapping) if args.mapping else {} - planner = Planner(read_json(args.snapshot), mapping, read_json(args.existing) if args.existing else None, read_json(args.previous) if args.previous else None) - report, candidates = planner.run() - write_private(output / "report.json", report) - if args.handoff: - target = mapping.get("target", {}) - direct = bool(mapping.get("operationalSites")) or target.get("writer") == "Operator" - if not args.existing or not mapping.get("revision") or not name_ok(target.get("project")) or not name_ok(target.get("namespace")) or target.get("writer") not in ("Flux", "Operator") or target.get("application") != "provider-inventory": - raise ValueError("handoff requires an explicit provider project/namespace, reviewed mapping revision, Operator (or legacy Flux)/provider-inventory target, and current Fleet snapshot") - if report["collectionErrors"] or report["conflicts"]: - raise ValueError("handoff blocked by incomplete source coverage or reconciliation conflicts; inspect the private report") - if not args.allow_partial and any(row["classification"] in ("unresolved", "unsupported") for row in report["records"]): - raise ValueError("handoff has unresolved or unsupported records; review the report and explicitly choose --allow-partial for a partial cohort") - write_private(output / "candidates.json", {"apiVersion": "v1", "kind": "List", "items": candidates}) - application = ("operator review and individual direct API creation of new records only; re-read authorized targets and check absence before creating; never update, replace, prune, or transfer existing ownership" - if direct else "review and add individual new records to the private Flux provider-inventory source; never replace or prune that source") - write_private(output / "handoff.json", {"target": dict(target, writer="Operator") if direct else target, "snapshotDigest": report["snapshotDigest"], "mappingDigest": digest(mapping), "existingDigest": digest(planner.existing), "candidateDigest": digest(candidates), "application": application, "applied": False}) - print("Private report saved; observational candidates:", len(candidates), "(nothing applied)") - counts = {state: sum(row["classification"] == state for row in report["records"]) for state in ("imported", "unresolved", "unsupported", "excluded")} - print("Record classifications:", canonical(counts), "; collection errors:", len(report["collectionErrors"]), "; readiness: Unknown") - return 0 - - -if __name__ == "__main__": - try: - sys.exit(main()) - except (ValueError, OSError, KeyError, TypeError) as error: - print("Inventory import stopped:", str(error) if isinstance(error, ValueError) else type(error).__name__, file=sys.stderr) - sys.exit(2) diff --git a/hack/test_device_placement.py b/hack/test_device_placement.py deleted file mode 100644 index 66ab230e..00000000 --- a/hack/test_device_placement.py +++ /dev/null @@ -1,118 +0,0 @@ -import copy -import datetime -import unittest - -import device_placement as placement -import netbox_inventory as inventory -from test_netbox_inventory import fixture - - -def inputs(): - snapshot, mapping = fixture() - _, candidates = inventory.Planner(snapshot, mapping).run() - for index, record in enumerate(candidates): - record["metadata"].update(uid="synthetic-" + str(index), resourceVersion="7") - device = next(record for record in candidates if record["kind"] == "Device" and record["spec"]["identity"]["sourceIdentity"]["id"] == "1") - snapshot = copy.deepcopy(snapshot) - snapshot["observedAt"] = "2026-11-22T00:00:00Z" - snapshot["objects"]["dcim/devices"][0]["face"] = {"value": "rear"} - snapshot["objects"]["dcim/device-types"][0].update(u_height=2, is_full_depth=True) - selection = {field: device["metadata"][field] for field in ("name", "namespace", "uid", "resourceVersion")} - selection["sourceID"] = "1" - destination = {field: mapping["target"][field] for field in ("project", "namespace")} - return snapshot, {"target": destination, "observedAt": snapshot["observedAt"], "items": candidates}, {"source": snapshot["source"], "target": destination, "devices": [selection]} - - -def plan(snapshot, target, allowlist): - return placement.enrichment_plan(snapshot, target, allowlist, datetime.datetime(2026, 11, 22, 0, 1, tzinfo=datetime.timezone.utc)) - - -class PlacementTests(unittest.TestCase): - def test_same_rack_plan_is_prepared_only_and_preserves_inputs(self): - snapshot, target, allowlist = inputs() - before = copy.deepcopy(target) - result = plan(snapshot, target, allowlist) - self.assertEqual(target, before) - self.assertFalse(result["executable"]) - self.assertFalse(result["applied"]) - item = result["devices"][0] - self.assertEqual([test["path"] for test in item["preconditions"]], ["/metadata/uid", "/metadata/resourceVersion"]) - original, proposed = item["before"]["spec"], item["proposedAfter"]["spec"] - for field in set(original) - {"provenance"}: - self.assertEqual(original[field], proposed[field]) - for field in ("method", "recordedBy"): - self.assertEqual(original["provenance"][field], proposed["provenance"][field]) - self.assertEqual(proposed["reportedPlacement"]["face"], "rear") - self.assertNotIn("height", proposed["reportedPlacement"]) - self.assertNotIn("fullDepth", proposed["reportedPlacement"]) - self.assertEqual(item["patch"][:2], item["preconditions"]) - self.assertEqual(item["patchDigest"], inventory.digest(item["patch"])) - self.assertEqual([entry["path"] for entry in item["patch"]][2:], ["/spec/reportedPlacement", "/spec/provenance"]) - - def test_rejects_conflicts_and_nonallowlisted_changes(self): - for case in ("uid", "resourceVersion", "extra", "rack", "flux", "legacy", "positioned", "duplicate", "source", "unknown", "null", "bounds", "stale", "namespace"): - with self.subTest(case=case): - snapshot, target, allowlist = inputs() - device = next(record for record in target["items"] if record["metadata"]["name"] == allowlist["devices"][0]["name"]) - claim = next(record for record in target["items"] if record["kind"] == "DeviceClaim" and record["metadata"]["name"] == device["spec"]["claimRef"]["name"]) - if case in ("uid", "resourceVersion"): - device["metadata"][case] = "changed" - elif case == "extra": allowlist["devices"][0]["actor"] = "admin" - elif case == "rack": snapshot["objects"]["dcim/devices"][0]["rack"] = {"id": "other"} - elif case == "flux": device["metadata"]["managedFields"] = [{"manager": "kustomize-controller"}] - elif case == "legacy": claim["spec"].pop("lifecycle") - elif case == "positioned": claim["spec"]["placement"]["scope"] = "RackUnits" - elif case == "duplicate": allowlist["devices"].append(allowlist["devices"][0]) - elif case == "source": device["spec"]["provenance"]["source"]["id"] = "other" - elif case == "unknown": device["metadata"].pop("uid") - elif case == "null": snapshot["objects"]["dcim/devices"][0]["position"] = None - elif case == "bounds": snapshot["objects"]["dcim/devices"][0]["position"] = 43 - elif case == "stale": snapshot["observedAt"] = device["spec"]["provenance"]["recordedAt"] - elif case == "namespace": allowlist["devices"][0]["namespace"] = "other" - with self.assertRaises(ValueError): plan(snapshot, target, allowlist) - - def test_partial_and_nonunit_geometry_is_not_invented(self): - snapshot, _, _ = inputs() - report = placement.source_report(snapshot, {"position": None, "face": None}, {"u_height": 0}, "rack") - self.assertEqual(set(report), {"revision", "method", "observedAt", "snapshotDigest", "rackRef"}) - report = placement.source_report(snapshot, {"position": "12.5"}, {"u_height": "0.5"}, "rack") - self.assertEqual(report["position"], 12.5) - self.assertNotIn("height", report) - for raw in (True, -1, "nan", "inf", "invalid"): - with self.assertRaises(ValueError): placement.source_report(snapshot, {"position": raw}, {}, "rack") - - def test_create_report_requires_explicit_per_device_selection(self): - snapshot, mapping = fixture() - _, old = inventory.Planner(snapshot, mapping).run() - self.assertFalse(any("reportedPlacement" in record["spec"] for record in old)) - mapping["devices"]["1"]["includeReportedPlacement"] = True - _, candidates = inventory.Planner(snapshot, mapping).run() - reports = [record for record in candidates if "reportedPlacement" in record["spec"]] - self.assertEqual(len(reports), 1) - self.assertEqual(reports[0]["spec"]["reportedPlacement"]["snapshotDigest"], reports[0]["spec"]["provenance"]["source"]["snapshotDigest"]) - self.assertEqual(reports[0]["spec"]["reportedPlacement"]["position"], 1) - - def test_fresh_reads_and_exact_source_required(self): - for field in ("source", "target", "missing", "future", "source-system"): - snapshot, target, allowlist = inputs() - if field == "source": snapshot["observedAt"] = "2026-11-21T00:00:00Z" - if field == "target": target["observedAt"] = "2026-11-21T00:00:00Z" - if field == "missing": target.pop("observedAt") - if field == "future": target["observedAt"] = "2026-11-23T00:00:00Z" - if field == "source-system": allowlist["source"] = "other" - with self.subTest(field=field), self.assertRaises(ValueError): plan(snapshot, target, allowlist) - - def test_readback_reconciliation_never_authorizes_retry(self): - item = plan(*inputs())["devices"][0] - self.assertEqual(placement.reconcile(item, None), "Unknown") - self.assertEqual(placement.reconcile(item, item["before"]), "Unchanged; no automatic retry") - after = copy.deepcopy(item["proposedAfter"]) - self.assertEqual(placement.reconcile(item, after), "Conflict") - after["metadata"]["resourceVersion"] = "8" - self.assertEqual(placement.reconcile(item, after), "Applied") - after["metadata"]["uid"] = "replaced" - self.assertEqual(placement.reconcile(item, after), "Conflict") - - -if __name__ == "__main__": - unittest.main() diff --git a/hack/test_netbox_inventory.py b/hack/test_netbox_inventory.py deleted file mode 100644 index 200041a2..00000000 --- a/hack/test_netbox_inventory.py +++ /dev/null @@ -1,511 +0,0 @@ -import copy -import io -import json -import os -from pathlib import Path -import tempfile -import unittest -from unittest.mock import patch -import urllib.error - -import netbox_inventory as inventory - - -def fixture(): - objects = {collection: [] for collection in inventory.REQUIRED} - objects.update({ - "dcim/sites": [{"id": 1, "name": "Example metro grouping"}], - "dcim/locations": [{"id": 1, "name": "Example room"}], - "dcim/racks": [{"id": 1, "name": "Example rack", "u_height": 42}], - "dcim/manufacturers": [{"id": 1, "name": "Example"}], - "dcim/device-types": [{"id": 1, "model": "Example physical model", "manufacturer": {"id": 1, "name": "Example"}}], - "dcim/devices": [ - {"id": 1, "name": "Example server", "serial": "provider-001", "asset_tag": "asset-001", "device_type": {"id": 1}, "rack": {"id": 1}, "position": 1}, - {"id": 2, "name": "Example PDU", "device_type": {"id": 1}, "rack": {"id": 1}}, - {"id": 3, "name": "Example panel", "device_type": {"id": 1}}, - {"id": 4, "name": "Example VM", "device_type": {"model": "netactuate VM"}}, - ], - "dcim/interfaces": [{"id": 1, "name": "eth0", "device": {"id": 1}, "type": "1000base-t"}, {"id": 2, "name": "bond0", "device": {"id": 1}, "type": "lag"}], - "dcim/power-ports": [{"id": 1, "name": "PSU1", "device": {"id": 1}}, {"id": 2, "name": "inlet", "device": {"id": 2}}], - "dcim/power-outlets": [{"id": 1, "name": "outlet-1", "device": {"id": 2}, "power_port": {"id": 2}}], - "dcim/front-ports": [{"id": 1, "name": "front-1", "device": {"id": 3}, "rear_port": {"id": 1}, "rear_port_position": 1}], - "dcim/rear-ports": [{"id": 1, "name": "rear-1", "device": {"id": 3}, "positions": 2}], - "dcim/power-panels": [{"id": 1, "name": "Panel A"}], - "dcim/power-feeds": [{"id": 1, "name": "Feed A", "power_panel": {"id": 1}, "rack": {"id": 1}, "supply": "ac", "voltage": 208, "amperage": 30}], - "dcim/cables": [{"id": 1, "label": "Power 1", "a_terminations": [{"object_type": "dcim.poweroutlet", "object_id": 1}], "b_terminations": [{"object_type": "dcim.powerport", "object_id": 1}]}], - "circuits/circuits": [{"id": 1, "cid": "Example-service"}], - "circuits/circuit-terminations": [{"id": 1, "circuit": {"id": 1}}], - }) - source = {"version": 1, "source": "example-netbox", "observedAt": "2026-11-20T12:00:00Z", "objects": objects, "errors": {}} - mapping = { - "revision": "example-reviewed-1", - "target": {"project": "example-provider", "namespace": "inventory", "writer": "Flux", "application": "provider-inventory"}, - "facilities": [{"source": "dcim/sites/1", "name": "example-premises", "displayName": "Example premises"}], - "racks": {"1": {"facility": "example-premises"}}, - "devices": { - "1": {"classification": "physical", "serialMeaning": "providerHostID", "provider": "example-provider", "placement": {"scope": "RackMembership"}}, - "2": {"classification": "physical", "serialMeaning": "unknown", "placement": {"scope": "RackMembership"}}, - "3": {"classification": "physical", "serialMeaning": "unknown", "placement": {"scope": "Facility", "facility": "example-premises"}}, - }, - "feeds": {"1": {"facility": "example-premises"}}, - "cables": {"1": {"medium": "Power"}}, - "circuits": {"1": {"system": "example-service-owner", "type": "transport", "id": "Example-service"}}, - "demarcations": {"1": {"componentSource": "dcim/rear-ports/1"}}, - } - return source, mapping - - -class PlanTests(unittest.TestCase): - def test_invalid_identifier_shapes_are_quarantined(self): - valid = {"provider": "example", "type": "PremisesCode", "value": "EX1"} - invalid = [None, {}, "invalid", 1, False, [None], ["invalid"], [[]], - [dict(valid, uid="forbidden")], [dict(valid, other="unknown")], - [dict(valid, provider=[])], [dict(valid, type={})], - [dict(valid, value=None)], [{"provider": "example"}], - [valid, valid], [dict(valid, value=str(index)) for index in range(65)]] - for identifiers in invalid: - with self.subTest(identifiers=identifiers): - source, mapping = fixture() - mapping["facilities"][0].update(identifiersVerified=True, identifiers=identifiers) - report, candidates = inventory.Planner(source, mapping).run() - self.assertIn("Facility/example-premises", report["conflicts"]) - self.assertFalse(any(record["kind"] == "Facility" for record in candidates)) - - def test_identifier_cardinality_boundary(self): - for count in (0, 64): - with self.subTest(count=count): - source, mapping = fixture() - identifiers = [{"provider": "example", "type": "PremisesCode", "value": str(index)} for index in range(count)] - mapping["facilities"][0].update(identifiersVerified=True, identifiers=identifiers) - report, candidates = inventory.Planner(source, mapping).run() - self.assertNotIn("Facility/example-premises", report["conflicts"]) - facility = next(record for record in candidates if record["kind"] == "Facility") - self.assertEqual(facility["spec"]["identifiers"], identifiers) - - def operational_mapping(self): - source, mapping = fixture() - _, records = inventory.Planner(source, mapping).run() - for record in records: - record["metadata"]["uid"] = "uid-" + record["metadata"]["name"] - facility = next(record for record in records if record["kind"] == "Facility") - existing = {"target": mapping["target"], "collections": ["Site", "Facility", "Rack", "DeviceClaim", "Device", "Cable", "PowerFeed"], "items": records} - mapping["operationalSites"] = [{"name": "site-stable", "displayName": "Example operational identity", "code": "EX3", "source": "dcim/sites/1", "verified": True, "facilityRefs": [{"name": facility["metadata"]["name"]}]}] - return source, mapping, existing - - def test_site_mapping_is_explicit_and_observational(self): - source, mapping, existing = self.operational_mapping() - before = copy.deepcopy(existing) - report, records = inventory.Planner(source, mapping, existing).run() - self.assertEqual({}, report["conflicts"]) - self.assertEqual(["Site"], [record["kind"] for record in records]) - self.assertEqual("EX3", records[0]["spec"]["code"]) - self.assertEqual([{"name": "example-premises"}], records[0]["spec"]["facilityRefs"]) - self.assertEqual(before, existing) - self.assertEqual([], report["deletions"]) - self.assertFalse(report["applied"]) - self.assertEqual("Unknown", report["readiness"]) - mapping.pop("operationalSites") - _, records = inventory.Planner(source, mapping, existing).run() - self.assertFalse(any(record["kind"] == "Site" for record in records)) - - def test_site_mapping_requires_verified_existing_names(self): - for invalid in ("unverified", "uid", "missing", "incomplete", "namespace", "deleting", "empty-name", "extra-namespace"): - with self.subTest(invalid=invalid): - source, mapping, existing = self.operational_mapping() - site = mapping["operationalSites"][0] - facility = next(record for record in existing["items"] if record["kind"] == "Facility") - if invalid == "unverified": - site["verified"] = False - elif invalid == "uid": - site["facilityRefs"][0]["uid"] = "other-uid" - elif invalid == "empty-name": - site["facilityRefs"][0]["name"] = "" - elif invalid == "extra-namespace": - site["facilityRefs"][0]["namespace"] = "other" - elif invalid == "missing": - existing["items"] = [] - elif invalid == "incomplete": - existing["collections"].remove("Site") - elif invalid == "namespace": - facility["metadata"]["namespace"] = "other" - else: - facility["metadata"]["deletionTimestamp"] = source["observedAt"] - if invalid in ("uid", "empty-name", "extra-namespace"): - report, records = inventory.Planner(source, mapping, existing).run() - self.assertTrue(report["conflicts"]) - self.assertFalse(any(record["kind"] == "Site" for record in records)) - else: - with self.assertRaises(ValueError): - inventory.Planner(source, mapping, existing).run() - - def test_malformed_site_fields_are_quarantined(self): - invalid_fields = [("code", value) for value in ("", None, 1, [], "x" * 65)] - invalid_fields += [("displayName", value) for value in ("", None, 1, "x" * 254)] - invalid_fields += [("name", value) for value in ("", "premises..one", "premises.-one", "premises-.one", "x" * 254)] - invalid_fields += [("facilityRefs", value) for value in (None, [], "bad", [None], [{"name": "premises..one"}], [{"name": "example-premises"}] * 2, [{"name": "example-premises"}] * 65)] - invalid_fields += [("uid", "not-a-spec-field")] - for field, value in invalid_fields: - with self.subTest(field=field, value=value): - source, mapping, existing = self.operational_mapping() - mapping["operationalSites"][0][field] = value - report, records = inventory.Planner(source, mapping, existing).run() - self.assertTrue(report["conflicts"]) - self.assertFalse(any(record["kind"] == "Site" for record in records)) - - def test_operator_handoff_supports_site_and_physical_candidates(self): - for sites in (True, False): - with self.subTest(sites=sites), tempfile.TemporaryDirectory() as directory: - source, mapping, existing = self.operational_mapping() - mapping["target"]["writer"] = "Operator" - if not sites: - mapping.pop("operationalSites") - existing["items"] = [] - root = Path(directory) - for name, data in (("source", source), ("mapping", mapping), ("existing", existing)): - inventory.write_private(root / (name + ".json"), data) - inventory.main(["plan", "--snapshot", str(root / "source.json"), "--mapping", str(root / "mapping.json"), "--existing", str(root / "existing.json"), "--output", str(root / "output"), "--handoff", "--allow-partial"]) - handoff = json.loads((root / "output/handoff.json").read_text()) - self.assertEqual("Operator", handoff["target"]["writer"]) - self.assertIn("direct API", handoff["application"]) - self.assertNotIn("Flux", handoff["application"]) - self.assertFalse(handoff["applied"]) - - def test_valid_mapping_cannot_clear_same_source_quarantine(self): - source, mapping, existing = self.operational_mapping() - malformed = dict(mapping["operationalSites"][0], code="", name="malformed-site") - mapping["operationalSites"].insert(0, malformed) - report, records = inventory.Planner(source, mapping, existing).run() - self.assertTrue(report["conflicts"]) - self.assertFalse(any(record["kind"] == "Site" for record in records)) - - def test_site_mapping_does_not_pin_server_uids(self): - source, mapping, existing = self.operational_mapping() - facility = next(record for record in existing["items"] if record["kind"] == "Facility") - facility["metadata"]["uid"] = "replacement-server-uid" - report, records = inventory.Planner(source, mapping, existing).run() - self.assertEqual({}, report["conflicts"]) - self.assertEqual([{"name": "example-premises"}], records[0]["spec"]["facilityRefs"]) - facility["metadata"].pop("uid") - report_without_uid, records_without_uid = inventory.Planner(source, mapping, existing).run() - self.assertEqual({}, report_without_uid["conflicts"]) - self.assertEqual(records, records_without_uid) - - def test_provider_identifier_collisions_are_qualified_not_inferred(self): - source, mapping = fixture() - identifiers = [{"provider": provider, "type": "PremisesCode", "value": "EX1"} for provider in ("example-a", "example-b")] - mapping["facilities"][0].update(identifiers=identifiers, identifiersVerified=True) - report, records = inventory.Planner(source, mapping).run() - self.assertEqual({}, report["conflicts"]) - self.assertEqual(identifiers, next(record for record in records if record["kind"] == "Facility")["spec"]["identifiers"]) - self.assertFalse(any(record["kind"] == "Site" for record in records)) - mapping["facilities"][0]["identifiersVerified"] = False - with self.assertRaises(ValueError): - inventory.Planner(source, mapping).run() - - def test_provider_metro_is_not_a_premises_identifier(self): - source, mapping = fixture() - mapping["facilities"][0].update(identifiers=[{"provider": "example", "type": "Metro", "value": "EX"}], identifiersVerified=True) - report, _ = inventory.Planner(source, mapping).run() - self.assertIn("Facility/example-premises", report["conflicts"]) - - def setUp(self): - self.source, self.mapping = fixture() - - def plan(self, existing=None, previous=None): - if existing is not None: - existing = dict(existing, target=self.mapping["target"], collections=["Facility", "Rack", "DeviceClaim", "Device", "Cable", "PowerFeed"]) - return inventory.Planner(self.source, self.mapping, existing, previous).run() - - def test_physical_shapes_and_no_hardware_authority(self): - report, records = self.plan() - self.assertTrue(report["coverageComplete"]) - self.assertEqual({}, report["conflicts"]) - self.assertEqual({"Facility", "Rack", "DeviceClaim", "Device", "Cable", "PowerFeed"}, {record["kind"] for record in records}) - self.assertEqual(sum(len(rows) for rows in self.source["objects"].values()), len(report["records"])) - server = next(record for record in records if record["kind"] == "Device" and record["spec"].get("assetTag")) - self.assertNotIn("serial", server["spec"]["identity"]) - self.assertEqual("provider-001", server["spec"]["providerHostRef"]["id"]) - self.assertEqual("asset-001", server["spec"]["assetTag"]) - for record in records: - self.assertNotIn("status", record) - self.assertNotIn("bmc", record["spec"]) - if record["kind"] == "DeviceClaim": - self.assertNotIn("position", record["spec"]["placement"]) - self.assertNotIn("height", record["spec"]["placement"]) - states = {row["source"]: row["classification"] for row in report["records"]} - self.assertEqual("excluded", states["dcim/devices/4"]) - self.assertEqual("excluded", states["dcim/interfaces/2"]) - self.assertEqual("imported", states["circuits/circuit-terminations/1"]) - - def test_checked_in_synthetic_handoff_matches_planner(self): - _, records = self.plan() - fixture_path = Path(__file__).parent / "testdata/netbox/candidates.json" - self.assertEqual(inventory.read_json(fixture_path)["items"], records) - - def test_existing_snapshot_wrong_project_and_missing_collections(self): - with self.assertRaisesRegex(ValueError, "target"): - inventory.Planner(self.source, self.mapping, {"items": [], "target": {"project": "other"}}) - with self.assertRaisesRegex(ValueError, "six"): - inventory.Planner(self.source, self.mapping, {"items": [], "target": self.mapping["target"]}) - - def test_repeated_and_interrupted_run(self): - report, records = self.plan() - self.assertEqual((report, records), self.plan()) - second, remaining = self.plan({"items": records}) - self.assertEqual({}, second["conflicts"]) - self.assertEqual([], remaining) - partial, remaining = self.plan({"items": records[:2]}) - self.assertEqual({}, partial["conflicts"]) - self.assertEqual(len(records) - 2, len(remaining)) - - def test_existing_identity_is_never_recreated(self): - _, records = self.plan() - server = copy.deepcopy(next(record for record in records if record["kind"] == "Device" and record["spec"].get("assetTag"))) - server["metadata"]["name"] = "original-asset" - server["spec"]["identity"] = {"model": "Legacy", "serial": "provider-001"} - server["spec"].pop("assetTag") - server["spec"].pop("providerHostRef") - report, candidates = self.plan({"items": [server]}) - self.assertTrue(report["conflicts"]) - self.assertFalse(any(record["kind"] == "Device" and record["spec"].get("providerHostRef") for record in candidates)) - self.assertEqual("original-asset", server["metadata"]["name"]) - - def test_changed_source_and_different_writer_are_conflicts(self): - _, records = self.plan() - records[0]["spec"]["displayName"] = "Manual correction" - report, _ = self.plan({"items": records}) - self.assertTrue(report["conflicts"]) - _, records = self.plan() - records[0]["spec"]["provenance"]["source"]["system"] = "other-source" - report, _ = self.plan({"items": records}) - self.assertTrue(report["conflicts"]) - - def test_omission_preserves_records_and_does_not_prune(self): - previous = copy.deepcopy(self.source) - self.source["objects"]["dcim/devices"] = self.source["objects"]["dcim/devices"][1:] - report, _ = self.plan(previous=previous) - self.assertIn("dcim/devices/1", report["missingSincePrevious"]) - self.assertEqual([], report["deletions"]) - - def test_unknown_collections_and_missing_collections_are_visible(self): - self.source["objects"]["dcim/new-physical-kind"] = [{"id": 1}] - del self.source["objects"]["dcim/console-ports"] - report, _ = self.plan() - self.assertFalse(report["coverageComplete"]) - self.assertEqual("unsupported", next(row for row in report["records"] if row["source"] == "dcim/new-physical-kind/1")["classification"]) - - def test_duplicate_identity_and_target_mapping_rejected(self): - self.source["objects"]["dcim/sites"].append({"id": 1}) - with self.assertRaises(ValueError): - self.plan() - self.source, self.mapping = fixture() - self.mapping["facilities"].append(copy.deepcopy(self.mapping["facilities"][0])) - with self.assertRaises(ValueError): - self.plan() - - def test_site_can_map_to_several_premises(self): - self.mapping["facilities"].append({"source": "dcim/sites/1", "name": "another-premises", "displayName": "Other premises"}) - _, records = self.plan() - self.assertEqual(2, sum(record["kind"] == "Facility" for record in records)) - - def test_no_mapping_means_no_guessed_assets(self): - self.mapping = {} - report, records = self.plan() - self.assertEqual([], records) - self.assertTrue(any(row["classification"] == "unresolved" for row in report["records"])) - - def test_duplicate_cable_termination_quarantines_both(self): - cable = copy.deepcopy(self.source["objects"]["dcim/cables"][0]) - cable["id"] = 2 - self.source["objects"]["dcim/cables"].append(cable) - self.mapping["cables"]["2"] = {"medium": "Power"} - report, records = self.plan() - self.assertFalse(any(record["kind"] == "Cable" for record in records)) - self.assertTrue(report["conflicts"]) - - def test_breakout_requires_reviewed_lanes_and_every_termination(self): - self.source["objects"]["dcim/interfaces"].append({"id": 3, "name": "eth1", "device": {"id": 1}, "type": "1000base-t"}) - self.source["objects"]["dcim/cables"] = [{"id": 2, "a_terminations": [{"object_type": "dcim.rearport", "object_id": 1}], "b_terminations": [{"object_type": "dcim.interface", "object_id": 1}, {"object_type": "dcim.interface", "object_id": 3}]}] - planner = inventory.Planner(self.source, self.mapping) - panel = planner.stable_name("device", "3") - server = planner.stable_name("device", "1") - self.mapping["cables"]["2"] = {"medium": "Copper"} - report, records = self.plan() - self.assertFalse(any(record["kind"] == "Cable" for record in records)) - lanes = [{"id": "lane-" + str(position), "a": {"deviceRef": {"name": panel}, "componentID": "rear-ports-1", "position": position}, "b": {"deviceRef": {"name": server}, "componentID": "interfaces-" + identity, "position": 1}} for position, identity in ((1, "1"), (2, "3"))] - self.mapping["cables"]["2"]["lanes"] = lanes - report, records = self.plan() - self.assertEqual({}, report["conflicts"]) - self.assertEqual(1, sum(record["kind"] == "Cable" for record in records)) - self.mapping["cables"]["2"]["lanes"] = lanes[:1] - report, records = self.plan() - self.assertFalse(any(record["kind"] == "Cable" for record in records)) - - def test_incompatible_medium_and_missing_internal_mapping(self): - self.mapping["cables"]["1"]["medium"] = "Fiber" - self.source["objects"]["dcim/front-ports"][0]["rear_port_position"] = 3 - report, _ = self.plan() - self.assertGreaterEqual(len(report["conflicts"]), 2) - - def test_rear_capacity_cannot_default_to_singleton_or_allow_handoff(self): - for capacity in (None, 0, -1, True, False, 1.5, "2", 257, "missing"): - with self.subTest(capacity=capacity): - self.source, self.mapping = fixture() - rear = self.source["objects"]["dcim/rear-ports"][0] - rear["positions"] = capacity - if capacity == "missing": - del rear["positions"] - self.source["objects"]["dcim/cables"].append({"id": 2, "a_terminations": [{"object_type": "dcim.rearport", "object_id": 1}], "b_terminations": [{"object_type": "dcim.interface", "object_id": 1}]}) - self.mapping["cables"]["2"] = {"medium": "Copper"} - report, records = self.plan() - entry = next(row for row in report["records"] if row["source"] == "dcim/rear-ports/1") - self.assertEqual("unresolved", entry["classification"]) - self.assertTrue(report["conflicts"]) - self.assertFalse(any(component["id"] == "rear-ports-1" for record in records for component in record["spec"].get("components", []))) - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - existing = {"items": [], "target": self.mapping["target"], "collections": ["Facility", "Rack", "DeviceClaim", "Device", "Cable", "PowerFeed"]} - for name, data in (("source", self.source), ("mapping", self.mapping), ("existing", existing)): - inventory.write_private(root / (name + ".json"), data) - with self.assertRaisesRegex(ValueError, "reconciliation conflicts"): - inventory.main(["plan", "--snapshot", str(root / "source.json"), "--mapping", str(root / "mapping.json"), "--existing", str(root / "existing.json"), "--output", str(root / "blocked"), "--handoff", "--allow-partial"]) - self.assertFalse((root / "blocked/candidates.json").exists()) - - def test_rear_capacity_preserves_supported_geometry(self): - for capacity in (1, 2, 256): - with self.subTest(capacity=capacity): - self.source["objects"]["dcim/rear-ports"][0]["positions"] = capacity - report, records = self.plan() - self.assertEqual({}, report["conflicts"]) - rear = next(component for record in records for component in record["spec"].get("components", []) if component["id"] == "rear-ports-1") - self.assertEqual(capacity, rear["positions"]) - - def test_front_port_requires_explicit_valid_rear_position(self): - for position in (None, 0, -1, True, False, 1.0, "1", 257, "missing"): - with self.subTest(position=position): - front = self.source["objects"]["dcim/front-ports"][0] - front["rear_port_position"] = position - if position == "missing": - del front["rear_port_position"] - report, records = self.plan() - entry = next(row for row in report["records"] if row["source"] == "dcim/front-ports/1") - self.assertEqual("unresolved", entry["classification"]) - self.assertTrue(report["conflicts"]) - self.assertFalse(any(component["id"] == "front-ports-1" for record in records for component in record["spec"].get("components", []))) - - def test_front_port_preserves_explicit_multi_position_mapping(self): - for position in (1, 2): - with self.subTest(position=position): - self.source["objects"]["dcim/front-ports"][0]["rear_port_position"] = position - report, records = self.plan() - self.assertEqual({}, report["conflicts"]) - mappings = [mapping for record in records for mapping in record["spec"].get("internalMappings", []) if mapping["from"]["componentID"] == "front-ports-1"] - self.assertEqual(1, len(mappings)) - self.assertEqual(position, mappings[0]["to"]["position"]) - - def test_partial_handoff_cannot_bypass_unknown_front_port_position(self): - del self.source["objects"]["dcim/front-ports"][0]["rear_port_position"] - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - existing = {"items": [], "target": self.mapping["target"], "collections": ["Facility", "Rack", "DeviceClaim", "Device", "Cable", "PowerFeed"]} - for name, data in (("source", self.source), ("mapping", self.mapping), ("existing", existing)): - inventory.write_private(root / (name + ".json"), data) - with self.assertRaisesRegex(ValueError, "reconciliation conflicts"): - inventory.main(["plan", "--snapshot", str(root / "source.json"), "--mapping", str(root / "mapping.json"), "--existing", str(root / "existing.json"), "--output", str(root / "blocked"), "--handoff", "--allow-partial"]) - self.assertFalse((root / "blocked/candidates.json").exists()) - - def test_redaction_uses_allowlisted_fields(self): - source = {"id": 1, "comments": "SECRET", "custom_fields": {"bmc_password": "SECRET"}, "config_context": {"token": "SECRET"}, "device": {"id": 2, "url": "https://user:SECRET@example.invalid"}} - self.assertNotIn("SECRET", json.dumps(inventory.sanitize(source))) - - def test_output_is_private_and_never_overwritten(self): - with tempfile.TemporaryDirectory() as directory: - path = Path(directory) / "report.json" - inventory.write_private(path, {"example": True}) - self.assertEqual(0o600, path.stat().st_mode & 0o777) - with self.assertRaises(FileExistsError): - inventory.write_private(path, {}) - - def test_export_refuses_repository_output(self): - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - (root / ".git").write_text("gitdir: example") - with self.assertRaisesRegex(ValueError, "outside Git"): - inventory.private_output(root / "private-export") - self.assertFalse((root / "private-export").exists()) - - def test_handoff_requires_target_existing_and_partial_acknowledgement(self): - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - for name, data in (("source", self.source), ("mapping", self.mapping), ("existing", {"items": [], "target": self.mapping["target"], "collections": ["Facility", "Rack", "DeviceClaim", "Device", "Cable", "PowerFeed"]})): - inventory.write_private(root / (name + ".json"), data) - args = ["plan", "--snapshot", str(root / "source.json"), "--mapping", str(root / "mapping.json"), "--output", str(root / "blocked"), "--handoff"] - with self.assertRaises(ValueError): - inventory.main(args) - self.assertFalse((root / "blocked/candidates.json").exists()) - args[args.index(str(root / "blocked"))] = str(root / "allowed") - args.extend(["--existing", str(root / "existing.json"), "--allow-partial"]) - self.assertEqual(0, inventory.main(args)) - self.assertTrue((root / "allowed/candidates.json").exists()) - with self.assertRaises(FileExistsError): - inventory.main(args) - - -class ReaderTests(unittest.TestCase): - def reader(self): - return inventory.Reader("https://example.invalid", "synthetic-token") - - def test_discovery_reports_lookup_exclusion_and_missing_collections(self): - reader = self.reader() - with patch.object(reader, "get", side_effect=[{"devices": "unused", "connected-device": "unused"}, {}]), patch.object(reader, "collection", return_value=[]) as collection: - result = inventory.snapshot(reader, "example-netbox") - collection.assert_called_once_with("dcim/devices") - self.assertIn("dcim/connected-device", result["excludedEndpoints"]) - self.assertIn("dcim/sites", result["errors"]) - - def test_discovery_permission_error_retains_partial_snapshot(self): - reader = self.reader() - with patch.object(reader, "get", side_effect=[{"devices": "unused"}, ValueError("NetBox GET failed with HTTP 403")]), patch.object(reader, "collection", return_value=[{"id": 1}]): - result = inventory.snapshot(reader, "example-netbox") - self.assertEqual([{"id": 1}], result["objects"]["dcim/devices"]) - self.assertIn("HTTP 403", result["errors"]["circuits/"]) - - def test_pagination_and_duplicates(self): - reader = self.reader() - with patch.object(reader, "get", side_effect=[{"count": 2, "results": [{"id": 1}], "next": "?offset=1"}, {"count": 2, "results": [{"id": 2}], "next": None}]): - self.assertEqual(2, len(reader.collection("dcim/devices"))) - with patch.object(reader, "get", side_effect=[{"count": 2, "results": [{"id": 1}], "next": "?offset=1"}, {"count": 2, "results": [{"id": 1}], "next": None}]): - with self.assertRaisesRegex(ValueError, "repeated"): - reader.collection("dcim/devices") - - def test_partial_pagination_and_cycles_fail_closed(self): - reader = self.reader() - for page in ({"count": 2, "results": [{"id": 1}], "next": None}, {"count": 1, "results": [], "next": "?limit=200"}, {"count": 1, "results": [], "next": "/api/users/"}): - with patch.object(reader, "get", return_value=page), self.assertRaises(ValueError): - reader.collection("dcim/devices") - - def test_cross_origin_and_http_and_credentials_refused(self): - reader = self.reader() - with patch.object(reader.opener, "open") as opener: - for url in ("https://attacker.invalid/api/dcim/devices", "http://example.invalid/api/dcim/devices", "https://user:password@example.invalid/api/dcim/devices"): - with self.assertRaises(ValueError): - reader.get(url) - opener.assert_not_called() - - def test_retries_get_only_and_permission_errors_redacted(self): - reader = self.reader() - forbidden = urllib.error.HTTPError("https://example.invalid", 403, "SECRET", {}, None) - with patch.object(reader.opener, "open", side_effect=forbidden) as opener: - with self.assertRaisesRegex(ValueError, "HTTP 403") as caught: - reader.get("https://example.invalid/api/dcim/") - self.assertNotIn("SECRET", str(caught.exception)) - self.assertEqual("GET", opener.call_args.args[0].method) - self.assertEqual(1, opener.call_count) - unavailable = urllib.error.HTTPError("https://example.invalid", 503, "SECRET", {}, None) - with patch.object(reader.opener, "open", side_effect=[unavailable, io.StringIO('{"ok":true}')]) as opener, patch.object(inventory.time, "sleep"): - self.assertTrue(reader.get("https://example.invalid/api/dcim/")["ok"]) - self.assertEqual(2, opener.call_count) - - -if __name__ == "__main__": - unittest.main() diff --git a/hack/test_pr100_independent.py b/hack/test_pr100_independent.py deleted file mode 100644 index 38756e36..00000000 --- a/hack/test_pr100_independent.py +++ /dev/null @@ -1,44 +0,0 @@ -import copy -import json -import tempfile -import unittest -from pathlib import Path - -import netbox_inventory as inventory -from test_netbox_inventory import PlanTests - - -class IndependentReviewTests(unittest.TestCase): - def test_new_site_handoff_does_not_prescribe_gitops(self): - source, mapping, existing = PlanTests().operational_mapping() - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - for name, data in (("source", source), ("mapping", mapping), ("existing", existing)): - (root / (name + ".json")).write_text(json.dumps(data)) - inventory.main(["plan", "--snapshot", str(root / "source.json"), "--mapping", str(root / "mapping.json"), "--existing", str(root / "existing.json"), "--output", str(root / "output"), "--handoff", "--allow-partial"]) - candidates = json.loads((root / "output/candidates.json").read_text()) - self.assertEqual(["Site"], [record["kind"] for record in candidates["items"]]) - handoff = json.loads((root / "output/handoff.json").read_text()) - self.assertFalse(handoff["applied"]) - self.assertNotIn("Flux", handoff["application"]) - - def test_invalid_site_code_is_quarantined(self): - source, mapping, existing = PlanTests().operational_mapping() - mapping["operationalSites"][0]["code"] = "" - report, candidates = inventory.Planner(source, mapping, existing).run() - self.assertFalse(any(record["kind"] == "Site" for record in candidates), report) - - def test_duplicate_aliases_do_not_merge_premises(self): - source, mapping, existing = PlanTests().operational_mapping() - facility = next(record for record in existing["items"] if record["kind"] == "Facility") - identifiers = [{"provider": "example-provider", "type": "PremisesAlias", "value": "SHARED-ALIAS"}] - facility["spec"]["identifiers"] = copy.deepcopy(identifiers) - mapping["facilities"][0].update(identifiers=identifiers, identifiersVerified=True) - other = copy.deepcopy(facility) - other["metadata"].update(name="other-premises", uid="other-uid") - existing["items"].append(other) - before = copy.deepcopy(existing) - report, candidates = inventory.Planner(source, mapping, existing).run() - self.assertEqual({}, report["conflicts"]) - self.assertEqual(existing, before) - self.assertEqual(["Site"], [record["kind"] for record in candidates]) diff --git a/hack/testdata/netbox/candidates.json b/hack/testdata/netbox/candidates.json deleted file mode 100644 index 66ecd1ce..00000000 --- a/hack/testdata/netbox/candidates.json +++ /dev/null @@ -1,475 +0,0 @@ -{ - "apiVersion": "v1", - "items": [ - { - "apiVersion": "fleet.datumapis.com/v1alpha1", - "kind": "Facility", - "metadata": { - "name": "example-premises", - "namespace": "inventory" - }, - "spec": { - "displayName": "Example premises", - "provenance": { - "method": "NetBoxImport", - "recordedAt": "2026-11-20T12:00:00Z", - "recordedBy": "netbox-inventory-offline", - "source": { - "id": "1", - "mappingRevision": "example-reviewed-1", - "observedAt": "2026-11-20T12:00:00Z", - "snapshotDigest": "sha256:faeabf49ee04c9376ce308d9347196e38ec07c6dd92d9bc18ea5fc29878ddb08", - "system": "example-netbox", - "type": "dcim/sites" - } - } - } - }, - { - "apiVersion": "fleet.datumapis.com/v1alpha1", - "kind": "Rack", - "metadata": { - "name": "nb-2f51dc9cdc336da3c50b9a8b", - "namespace": "inventory" - }, - "spec": { - "displayName": "Example rack", - "facilityRef": { - "name": "example-premises" - }, - "heightUnits": 42, - "provenance": { - "method": "NetBoxImport", - "recordedAt": "2026-11-20T12:00:00Z", - "recordedBy": "netbox-inventory-offline", - "source": { - "id": "1", - "mappingRevision": "example-reviewed-1", - "observedAt": "2026-11-20T12:00:00Z", - "snapshotDigest": "sha256:faeabf49ee04c9376ce308d9347196e38ec07c6dd92d9bc18ea5fc29878ddb08", - "system": "example-netbox", - "type": "dcim/racks" - } - } - } - }, - { - "apiVersion": "fleet.datumapis.com/v1alpha1", - "kind": "DeviceClaim", - "metadata": { - "name": "nb-d2728cbb6945a3e726ab702b", - "namespace": "inventory" - }, - "spec": { - "displayName": "Example server", - "expectedIdentity": { - "manufacturer": "Example", - "model": "Example physical model" - }, - "lifecycle": "Installation", - "placement": { - "rackRef": { - "name": "nb-2f51dc9cdc336da3c50b9a8b" - }, - "scope": "RackMembership" - }, - "provenance": { - "method": "NetBoxImport", - "recordedAt": "2026-11-20T12:00:00Z", - "recordedBy": "netbox-inventory-offline", - "source": { - "id": "1", - "mappingRevision": "example-reviewed-1", - "observedAt": "2026-11-20T12:00:00Z", - "snapshotDigest": "sha256:faeabf49ee04c9376ce308d9347196e38ec07c6dd92d9bc18ea5fc29878ddb08", - "system": "example-netbox", - "type": "dcim/devices" - } - } - } - }, - { - "apiVersion": "fleet.datumapis.com/v1alpha1", - "kind": "Device", - "metadata": { - "name": "nb-b4a16a61aea025fc10ded221", - "namespace": "inventory" - }, - "spec": { - "assetTag": "asset-001", - "claimRef": { - "name": "nb-d2728cbb6945a3e726ab702b" - }, - "components": [ - { - "connector": "1000base-t", - "id": "interfaces-1", - "name": "eth0", - "sourceRef": { - "id": "1", - "system": "example-netbox", - "type": "dcim/interfaces" - }, - "type": "NetworkPort" - }, - { - "id": "power-ports-1", - "name": "PSU1", - "sourceRef": { - "id": "1", - "system": "example-netbox", - "type": "dcim/power-ports" - }, - "type": "PowerInlet" - } - ], - "displayName": "Example server", - "identity": { - "manufacturer": "Example", - "model": "Example physical model", - "sourceIdentity": { - "id": "1", - "system": "example-netbox", - "type": "dcim/devices" - } - }, - "provenance": { - "method": "NetBoxImport", - "recordedAt": "2026-11-20T12:00:00Z", - "recordedBy": "netbox-inventory-offline", - "source": { - "id": "1", - "mappingRevision": "example-reviewed-1", - "observedAt": "2026-11-20T12:00:00Z", - "snapshotDigest": "sha256:faeabf49ee04c9376ce308d9347196e38ec07c6dd92d9bc18ea5fc29878ddb08", - "system": "example-netbox", - "type": "dcim/devices" - } - }, - "providerHostRef": { - "id": "provider-001", - "system": "example-provider", - "type": "host" - }, - "topologyAuthority": "Cable" - } - }, - { - "apiVersion": "fleet.datumapis.com/v1alpha1", - "kind": "DeviceClaim", - "metadata": { - "name": "nb-80a1dd16980a83974841e810", - "namespace": "inventory" - }, - "spec": { - "displayName": "Example PDU", - "expectedIdentity": { - "manufacturer": "Example", - "model": "Example physical model" - }, - "lifecycle": "Installation", - "placement": { - "rackRef": { - "name": "nb-2f51dc9cdc336da3c50b9a8b" - }, - "scope": "RackMembership" - }, - "provenance": { - "method": "NetBoxImport", - "recordedAt": "2026-11-20T12:00:00Z", - "recordedBy": "netbox-inventory-offline", - "source": { - "id": "2", - "mappingRevision": "example-reviewed-1", - "observedAt": "2026-11-20T12:00:00Z", - "snapshotDigest": "sha256:faeabf49ee04c9376ce308d9347196e38ec07c6dd92d9bc18ea5fc29878ddb08", - "system": "example-netbox", - "type": "dcim/devices" - } - } - } - }, - { - "apiVersion": "fleet.datumapis.com/v1alpha1", - "kind": "Device", - "metadata": { - "name": "nb-64e11cbf2b3c9f4866fa9eda", - "namespace": "inventory" - }, - "spec": { - "claimRef": { - "name": "nb-80a1dd16980a83974841e810" - }, - "components": [ - { - "id": "power-ports-2", - "name": "inlet", - "sourceRef": { - "id": "2", - "system": "example-netbox", - "type": "dcim/power-ports" - }, - "type": "PowerInlet" - }, - { - "id": "power-outlets-1", - "name": "outlet-1", - "sourceRef": { - "id": "1", - "system": "example-netbox", - "type": "dcim/power-outlets" - }, - "type": "PowerOutlet" - } - ], - "displayName": "Example PDU", - "identity": { - "manufacturer": "Example", - "model": "Example physical model", - "sourceIdentity": { - "id": "2", - "system": "example-netbox", - "type": "dcim/devices" - } - }, - "internalMappings": [ - { - "from": { - "componentID": "power-outlets-1", - "position": 1 - }, - "to": { - "componentID": "power-ports-2", - "position": 1 - } - } - ], - "provenance": { - "method": "NetBoxImport", - "recordedAt": "2026-11-20T12:00:00Z", - "recordedBy": "netbox-inventory-offline", - "source": { - "id": "2", - "mappingRevision": "example-reviewed-1", - "observedAt": "2026-11-20T12:00:00Z", - "snapshotDigest": "sha256:faeabf49ee04c9376ce308d9347196e38ec07c6dd92d9bc18ea5fc29878ddb08", - "system": "example-netbox", - "type": "dcim/devices" - } - }, - "topologyAuthority": "Cable" - } - }, - { - "apiVersion": "fleet.datumapis.com/v1alpha1", - "kind": "DeviceClaim", - "metadata": { - "name": "nb-9032aa5e04cb441d10d37851", - "namespace": "inventory" - }, - "spec": { - "displayName": "Example panel", - "expectedIdentity": { - "manufacturer": "Example", - "model": "Example physical model" - }, - "lifecycle": "Installation", - "placement": { - "facilityRef": { - "name": "example-premises" - }, - "scope": "Facility" - }, - "provenance": { - "method": "NetBoxImport", - "recordedAt": "2026-11-20T12:00:00Z", - "recordedBy": "netbox-inventory-offline", - "source": { - "id": "3", - "mappingRevision": "example-reviewed-1", - "observedAt": "2026-11-20T12:00:00Z", - "snapshotDigest": "sha256:faeabf49ee04c9376ce308d9347196e38ec07c6dd92d9bc18ea5fc29878ddb08", - "system": "example-netbox", - "type": "dcim/devices" - } - } - } - }, - { - "apiVersion": "fleet.datumapis.com/v1alpha1", - "kind": "Device", - "metadata": { - "name": "nb-25d8e4b769fdb899553c233e", - "namespace": "inventory" - }, - "spec": { - "claimRef": { - "name": "nb-9032aa5e04cb441d10d37851" - }, - "components": [ - { - "id": "front-ports-1", - "name": "front-1", - "sourceRef": { - "id": "1", - "system": "example-netbox", - "type": "dcim/front-ports" - }, - "type": "FrontPort" - }, - { - "id": "rear-ports-1", - "name": "rear-1", - "positions": 2, - "sourceRef": { - "id": "1", - "system": "example-netbox", - "type": "dcim/rear-ports" - }, - "type": "RearPort" - } - ], - "displayName": "Example panel", - "identity": { - "manufacturer": "Example", - "model": "Example physical model", - "sourceIdentity": { - "id": "3", - "system": "example-netbox", - "type": "dcim/devices" - } - }, - "internalMappings": [ - { - "from": { - "componentID": "front-ports-1", - "position": 1 - }, - "to": { - "componentID": "rear-ports-1", - "position": 1 - } - } - ], - "provenance": { - "method": "NetBoxImport", - "recordedAt": "2026-11-20T12:00:00Z", - "recordedBy": "netbox-inventory-offline", - "source": { - "id": "3", - "mappingRevision": "example-reviewed-1", - "observedAt": "2026-11-20T12:00:00Z", - "snapshotDigest": "sha256:faeabf49ee04c9376ce308d9347196e38ec07c6dd92d9bc18ea5fc29878ddb08", - "system": "example-netbox", - "type": "dcim/devices" - } - }, - "serviceAssociations": [ - { - "componentID": "rear-ports-1", - "serviceRef": { - "id": "Example-service", - "system": "example-service-owner", - "type": "transport" - } - } - ], - "topologyAuthority": "Cable" - } - }, - { - "apiVersion": "fleet.datumapis.com/v1alpha1", - "kind": "PowerFeed", - "metadata": { - "name": "nb-15e9e7aa88e11d9ab395e929", - "namespace": "inventory" - }, - "spec": { - "displayName": "Feed A", - "facilityRef": { - "name": "example-premises" - }, - "provenance": { - "method": "NetBoxImport", - "recordedAt": "2026-11-20T12:00:00Z", - "recordedBy": "netbox-inventory-offline", - "source": { - "id": "1", - "mappingRevision": "example-reviewed-1", - "observedAt": "2026-11-20T12:00:00Z", - "snapshotDigest": "sha256:faeabf49ee04c9376ce308d9347196e38ec07c6dd92d9bc18ea5fc29878ddb08", - "system": "example-netbox", - "type": "dcim/power-feeds" - } - }, - "rackRef": { - "name": "nb-2f51dc9cdc336da3c50b9a8b" - }, - "supply": { - "currentA": 30, - "type": "AC", - "voltageV": 208 - }, - "terminations": [ - { - "id": "output", - "name": "output", - "type": "PowerOutlet" - } - ], - "upstreamSources": [ - { - "id": "1", - "system": "example-netbox", - "type": "dcim/power-panels" - } - ] - } - }, - { - "apiVersion": "fleet.datumapis.com/v1alpha1", - "kind": "Cable", - "metadata": { - "name": "nb-4cf1484ca48ba078ba94107c", - "namespace": "inventory" - }, - "spec": { - "displayName": "Power 1", - "lanes": [ - { - "a": { - "componentID": "power-outlets-1", - "deviceRef": { - "name": "nb-64e11cbf2b3c9f4866fa9eda" - }, - "position": 1 - }, - "b": { - "componentID": "power-ports-1", - "deviceRef": { - "name": "nb-b4a16a61aea025fc10ded221" - }, - "position": 1 - }, - "id": "lane-1" - } - ], - "medium": "Power", - "provenance": { - "method": "NetBoxImport", - "recordedAt": "2026-11-20T12:00:00Z", - "recordedBy": "netbox-inventory-offline", - "source": { - "id": "1", - "mappingRevision": "example-reviewed-1", - "observedAt": "2026-11-20T12:00:00Z", - "snapshotDigest": "sha256:faeabf49ee04c9376ce308d9347196e38ec07c6dd92d9bc18ea5fc29878ddb08", - "system": "example-netbox", - "type": "dcim/cables" - } - } - } - } - ], - "kind": "List" -} diff --git a/hack/testdata/netbox/existing.json b/hack/testdata/netbox/existing.json deleted file mode 100644 index 1e972629..00000000 --- a/hack/testdata/netbox/existing.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "collections": [ - "Facility", - "Rack", - "DeviceClaim", - "Device", - "Cable", - "PowerFeed" - ], - "items": [], - "target": { - "application": "provider-inventory", - "namespace": "inventory", - "project": "example-provider", - "writer": "Flux" - } -} diff --git a/hack/testdata/netbox/mapping.json b/hack/testdata/netbox/mapping.json deleted file mode 100644 index c0499aee..00000000 --- a/hack/testdata/netbox/mapping.json +++ /dev/null @@ -1,68 +0,0 @@ -{ - "cables": { - "1": { - "medium": "Power" - } - }, - "circuits": { - "1": { - "id": "Example-service", - "system": "example-service-owner", - "type": "transport" - } - }, - "demarcations": { - "1": { - "componentSource": "dcim/rear-ports/1" - } - }, - "devices": { - "1": { - "classification": "physical", - "placement": { - "scope": "RackMembership" - }, - "provider": "example-provider", - "serialMeaning": "providerHostID" - }, - "2": { - "classification": "physical", - "placement": { - "scope": "RackMembership" - }, - "serialMeaning": "unknown" - }, - "3": { - "classification": "physical", - "placement": { - "facility": "example-premises", - "scope": "Facility" - }, - "serialMeaning": "unknown" - } - }, - "facilities": [ - { - "displayName": "Example premises", - "name": "example-premises", - "source": "dcim/sites/1" - } - ], - "feeds": { - "1": { - "facility": "example-premises" - } - }, - "racks": { - "1": { - "facility": "example-premises" - } - }, - "revision": "example-reviewed-1", - "target": { - "application": "provider-inventory", - "namespace": "inventory", - "project": "example-provider", - "writer": "Flux" - } -} diff --git a/hack/testdata/netbox/snapshot.json b/hack/testdata/netbox/snapshot.json deleted file mode 100644 index c839e5c0..00000000 --- a/hack/testdata/netbox/snapshot.json +++ /dev/null @@ -1,209 +0,0 @@ -{ - "errors": {}, - "objects": { - "circuits/circuit-terminations": [ - { - "circuit": { - "id": 1 - }, - "id": 1 - } - ], - "circuits/circuits": [ - { - "cid": "Example-service", - "id": 1 - } - ], - "dcim/cables": [ - { - "a_terminations": [ - { - "object_id": 1, - "object_type": "dcim.poweroutlet" - } - ], - "b_terminations": [ - { - "object_id": 1, - "object_type": "dcim.powerport" - } - ], - "id": 1, - "label": "Power 1" - } - ], - "dcim/console-ports": [], - "dcim/console-server-ports": [], - "dcim/device-bays": [], - "dcim/device-types": [ - { - "id": 1, - "manufacturer": { - "id": 1, - "name": "Example" - }, - "model": "Example physical model" - } - ], - "dcim/devices": [ - { - "asset_tag": "asset-001", - "device_type": { - "id": 1 - }, - "id": 1, - "name": "Example server", - "position": 1, - "rack": { - "id": 1 - }, - "serial": "provider-001" - }, - { - "device_type": { - "id": 1 - }, - "id": 2, - "name": "Example PDU", - "rack": { - "id": 1 - } - }, - { - "device_type": { - "id": 1 - }, - "id": 3, - "name": "Example panel" - }, - { - "device_type": { - "model": "netactuate VM" - }, - "id": 4, - "name": "Example VM" - } - ], - "dcim/front-ports": [ - { - "device": { - "id": 3 - }, - "id": 1, - "name": "front-1", - "rear_port": { - "id": 1 - }, - "rear_port_position": 1 - } - ], - "dcim/interfaces": [ - { - "device": { - "id": 1 - }, - "id": 1, - "name": "eth0", - "type": "1000base-t" - }, - { - "device": { - "id": 1 - }, - "id": 2, - "name": "bond0", - "type": "lag" - } - ], - "dcim/inventory-items": [], - "dcim/locations": [ - { - "id": 1, - "name": "Example room" - } - ], - "dcim/manufacturers": [ - { - "id": 1, - "name": "Example" - } - ], - "dcim/modules": [], - "dcim/power-feeds": [ - { - "amperage": 30, - "id": 1, - "name": "Feed A", - "power_panel": { - "id": 1 - }, - "rack": { - "id": 1 - }, - "supply": "ac", - "voltage": 208 - } - ], - "dcim/power-outlets": [ - { - "device": { - "id": 2 - }, - "id": 1, - "name": "outlet-1", - "power_port": { - "id": 2 - } - } - ], - "dcim/power-panels": [ - { - "id": 1, - "name": "Panel A" - } - ], - "dcim/power-ports": [ - { - "device": { - "id": 1 - }, - "id": 1, - "name": "PSU1" - }, - { - "device": { - "id": 2 - }, - "id": 2, - "name": "inlet" - } - ], - "dcim/racks": [ - { - "id": 1, - "name": "Example rack", - "u_height": 42 - } - ], - "dcim/rear-ports": [ - { - "device": { - "id": 3 - }, - "id": 1, - "name": "rear-1", - "positions": 2 - } - ], - "dcim/sites": [ - { - "id": 1, - "name": "Example metro grouping" - } - ] - }, - "observedAt": "2026-11-20T12:00:00Z", - "source": "example-netbox", - "version": 1 -} diff --git a/hack/testdata/physical/manual.yaml b/hack/testdata/physical/manual.yaml index e6c3dc81..003a7bbf 100644 --- a/hack/testdata/physical/manual.yaml +++ b/hack/testdata/physical/manual.yaml @@ -5,10 +5,6 @@ metadata: namespace: default spec: displayName: Example premises - provenance: - method: Manual - recordedBy: operator@example.com - recordedAt: "2026-11-20T12:00:00Z" --- apiVersion: fleet.datumapis.com/v1alpha1 kind: Rack @@ -18,10 +14,6 @@ metadata: spec: displayName: Example rack facilityRef: {name: example-facility} - provenance: - method: Manual - recordedBy: operator@example.com - recordedAt: "2026-11-20T12:00:00Z" --- apiVersion: fleet.datumapis.com/v1alpha1 kind: DeviceClaim @@ -35,10 +27,6 @@ spec: scope: RackMembership rackRef: {name: example-rack} cableRefs: [{name: example-power-cable}] - provenance: - method: Manual - recordedBy: planner@example.com - recordedAt: "2026-11-20T12:00:00Z" --- apiVersion: fleet.datumapis.com/v1alpha1 kind: Device @@ -55,10 +43,6 @@ spec: components: - {id: psu-a, name: PSU A input, type: PowerInlet} - {id: eth0, name: Ethernet 0, type: NetworkPort} - provenance: - method: Manual - recordedBy: registrar@example.com - recordedAt: "2026-11-20T12:00:00Z" --- apiVersion: fleet.datumapis.com/v1alpha1 kind: PowerFeed @@ -71,10 +55,6 @@ spec: rackRef: {name: example-rack} terminations: - {id: outlet-a, name: Outlet A, type: PowerOutlet} - provenance: - method: Manual - recordedBy: operator@example.com - recordedAt: "2026-11-20T12:00:00Z" --- apiVersion: fleet.datumapis.com/v1alpha1 kind: Cable @@ -88,7 +68,3 @@ spec: - id: power a: {powerFeedRef: {name: example-feed}, componentID: outlet-a, position: 1} b: {deviceRef: {name: example-server}, componentID: psu-a, position: 1} - provenance: - method: Manual - recordedBy: operator@example.com - recordedAt: "2026-11-20T12:00:00Z" diff --git a/internal/api/inventory/v1alpha1/crd_test.go b/internal/api/inventory/v1alpha1/crd_test.go index ed66e5cc..79960816 100644 --- a/internal/api/inventory/v1alpha1/crd_test.go +++ b/internal/api/inventory/v1alpha1/crd_test.go @@ -7,6 +7,7 @@ import ( "io" "os" "path/filepath" + "strings" "testing" "time" @@ -17,6 +18,7 @@ import ( "k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel" structuraldefaulting "k8s.io/apiextensions-apiserver/pkg/apiserver/schema/defaulting" "k8s.io/apiextensions-apiserver/pkg/apiserver/schema/listtype" + "k8s.io/apiextensions-apiserver/pkg/apiserver/schema/pruning" "k8s.io/apiextensions-apiserver/pkg/apiserver/validation" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" @@ -55,8 +57,8 @@ func loadCRDs(t *testing.T) map[string]*extensionsv1.CustomResourceDefinition { func TestInventoryCRDContract(t *testing.T) { crds := loadCRDs(t) -if len(crds) != 7 || crds["Site"] == nil || crds["DeviceClaim"] == nil || crds["Device"] == nil { -t.Fatalf("got %d CRDs, want six physical kinds and Site", len(crds)) + if len(crds) != 7 || crds["Site"] == nil || crds["DeviceClaim"] == nil || crds["Device"] == nil { + t.Fatalf("got %d CRDs, want six physical kinds and Site", len(crds)) } for kind, crd := range crds { if crd.Spec.Group != GroupVersion.Group || crd.Name != crd.Spec.Names.Plural+"."+GroupVersion.Group || crd.Spec.Scope != extensionsv1.NamespaceScoped { @@ -131,18 +133,13 @@ func object(t *testing.T, value any) map[string]any { return out } -var recordedAt = time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC) - -func provenance(at time.Time) *Provenance { - return &Provenance{Method: ProvenanceManual, RecordedBy: "operator@example.com", RecordedAt: metav1.NewTime(at), Reference: "rack plan 1234"} -} +var baseTime = time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC) func syntheticClaim() DeviceClaim { return DeviceClaim{ TypeMeta: metav1.TypeMeta{APIVersion: GroupVersion.String(), Kind: "DeviceClaim"}, ObjectMeta: metav1.ObjectMeta{Name: "rack-01-u12", Namespace: "fleet-system"}, Spec: DeviceClaimSpec{ - Provenance: provenance(recordedAt), ExpectedIdentity: ExpectedIdentity{Manufacturer: "Example Vendor", Model: "Example 1U"}, Placement: Placement{Facility: "example-facility", Rack: "rack-01", Position: 12, Face: "front"}, Ports: []ExpectedPort{ @@ -158,10 +155,9 @@ func syntheticDevice() Device { TypeMeta: metav1.TypeMeta{APIVersion: GroupVersion.String(), Kind: "Device"}, ObjectMeta: metav1.ObjectMeta{Name: "rack-01-u12-synthetic-0001", Namespace: "fleet-system"}, Spec: DeviceSpec{ - ClaimRef: LocalReference{Name: "rack-01-u12"}, - Provenance: provenance(recordedAt), - Identity: DeviceIdentity{Manufacturer: "Example Vendor", Model: "Example 1U", Serial: "SYNTHETIC-0001", SystemUUID: "00000000-0000-4000-8000-000000000001"}, - BMC: &BMC{Endpoint: "https://192.0.2.100:443"}, + ClaimRef: LocalReference{Name: "rack-01-u12"}, + Identity: DeviceIdentity{Manufacturer: "Example Vendor", Model: "Example 1U", Serial: "SYNTHETIC-0001", SystemUUID: "00000000-0000-4000-8000-000000000001"}, + BMC: &BMC{Endpoint: "https://192.0.2.100:443"}, Interfaces: []Interface{ {Name: "eth0", MACAddress: "00:00:5e:00:53:01", Peer: &PortPeer{Device: "switch-01", Port: "Ethernet1/1"}}, {Name: "bmc0", MACAddress: "00:00:5e:00:53:02"}, @@ -171,7 +167,7 @@ func syntheticDevice() Device { } } -func later(d time.Duration) metav1.Time { return metav1.NewTime(recordedAt.Add(d)) } +func later(d time.Duration) metav1.Time { return metav1.NewTime(baseTime.Add(d)) } func TestValidRecordsAreAccepted(t *testing.T) { if errs := admit(t, "DeviceClaim", object(t, syntheticClaim()), nil); len(errs) > 0 { @@ -200,8 +196,6 @@ func TestClaimDoesNotRequireSerialOrInventHeight(t *testing.T) { func TestInvalidClaimsAreRejected(t *testing.T) { for name, mutate := range map[string]func(*DeviceClaim){ - "unknown method": func(c *DeviceClaim) { c.Spec.Provenance.Method = "Discovered" }, - "missing recorder": func(c *DeviceClaim) { c.Spec.Provenance.RecordedBy = "" }, "missing model": func(c *DeviceClaim) { c.Spec.ExpectedIdentity.Model = "" }, "missing facility": func(c *DeviceClaim) { c.Spec.Placement.Facility = "" }, "zero position": func(c *DeviceClaim) { c.Spec.Placement.Position = 0 }, @@ -252,35 +246,95 @@ func TestInvalidDevicesAreRejected(t *testing.T) { } } -// TestProvenanceIsOptional keeps records written before and after provenance -// was retired admissible, including an update that drops it. -func TestProvenanceIsOptional(t *testing.T) { - withProvenance := object(t, syntheticDevice()) - without := syntheticDevice() - without.Spec.Provenance = nil - if errs := admit(t, "Device", object(t, without), nil); len(errs) > 0 { - t.Fatalf("device without provenance rejected: %v", errs) - } - if errs := admit(t, "Device", object(t, without), withProvenance); len(errs) > 0 { - t.Fatalf("dropping provenance rejected: %v", errs) - } - // identity is immutable, so an imported Device keeps its sourceIdentity and - // must still be able to stop sending provenance. - imported := reportedDevice() - importedWithout := reportedDevice() - importedWithout.Spec.Provenance = nil - if errs := admit(t, "Device", object(t, importedWithout), object(t, imported)); len(errs) > 0 { - t.Fatalf("dropping provenance from an imported device rejected: %v", errs) +func TestDeviceIdentityNeedsSerialOrSystemUUID(t *testing.T) { + serialOnly := syntheticDevice() + serialOnly.Spec.Identity.SystemUUID = "" + serialOnly.Spec.BMC, serialOnly.Spec.Interfaces, serialOnly.Spec.UnmappedMACAddresses = nil, nil, nil + record := object(t, serialOnly) + if _, ok := record["spec"].(map[string]any)["provenance"]; ok { + t.Fatal("device fixture must not carry provenance") + } + if errs := admit(t, "Device", record, nil); len(errs) > 0 { + t.Fatalf("device with only a serial rejected: %v", errs) + } + neither := serialOnly + neither.Spec.Identity.Serial = "" + if errs := admit(t, "Device", object(t, neither), nil); len(errs) == 0 { + t.Fatal("device with neither serial nor system UUID accepted") } +} + +// TestEditsDoNotNeedARecordingTimestamp pins that spec changes carry no +// attribution field; audit logs record who changed a record. +func TestEditsDoNotNeedARecordingTimestamp(t *testing.T) { claim := syntheticClaim() - claim.Spec.Provenance = nil + claim.Spec.Placement.Position = 14 if errs := admit(t, "DeviceClaim", object(t, claim), object(t, syntheticClaim())); len(errs) > 0 { - t.Fatalf("dropping claim provenance rejected: %v", errs) + t.Fatalf("claim edit rejected: %v", errs) + } + device := syntheticDevice() + device.Spec.BMC.Endpoint = "https://192.0.2.101" + if errs := admit(t, "Device", object(t, device), object(t, syntheticDevice())); len(errs) > 0 { + t.Fatalf("device edit rejected: %v", errs) + } +} + +// TestRetiredFieldsArePruned shows that objects stored with the retired +// provenance, source identity, component source and report import fields +// lose them when read or written through the structural schema, and that +// what remains is admitted. No migration is needed. +func TestRetiredFieldsArePruned(t *testing.T) { + legacy := object(t, reportedDevice()) + spec := legacy["spec"].(map[string]any) + spec["provenance"] = map[string]any{"method": "Manual", "recordedBy": "operator@example.com", "recordedAt": "2026-01-02T03:04:05Z", "reference": "rack plan 1234"} + spec["identity"].(map[string]any)["sourceIdentity"] = map[string]any{"system": "example", "type": "device", "id": "1"} + report := spec["reportedPlacement"].(map[string]any) + report["method"] = "Manual" + report["snapshotDigest"] = "sha256:" + strings.Repeat("a", 64) + spec["topologyAuthority"] = "Cable" + delete(spec, "interfaces") + spec["components"] = []any{map[string]any{"id": "front", "name": "front", "type": "FrontPort", "sourceRef": map[string]any{"system": "example", "type": "port", "id": "1"}}} + var schema apiextensions.JSONSchemaProps + if err := extensionsv1.Convert_v1_JSONSchemaProps_To_apiextensions_JSONSchemaProps(loadCRDs(t)["Device"].Spec.Versions[0].Schema.OpenAPIV3Schema, &schema, nil); err != nil { + t.Fatal(err) + } + structural, err := structuralschema.NewStructural(&schema) + if err != nil { + t.Fatal(err) + } + pruning.Prune(legacy, structural, true) + spec = legacy["spec"].(map[string]any) + if _, ok := spec["provenance"]; ok { + t.Fatal("provenance survived pruning") + } + if _, ok := spec["identity"].(map[string]any)["sourceIdentity"]; ok { + t.Fatal("sourceIdentity survived pruning") + } + if _, ok := spec["components"].([]any)[0].(map[string]any)["sourceRef"]; ok { + t.Fatal("component sourceRef survived pruning") + } + report = spec["reportedPlacement"].(map[string]any) + if _, ok := report["method"]; ok { + t.Fatal("report method survived pruning") + } + if _, ok := report["snapshotDigest"]; ok { + t.Fatal("report snapshotDigest survived pruning") } - edited := syntheticClaim() - edited.Spec.Placement.Position = 14 - if errs := admit(t, "DeviceClaim", object(t, edited), object(t, syntheticClaim())); len(errs) > 0 { - t.Fatalf("claim edit without a newer recordedAt rejected: %v", errs) + if errs := admit(t, "Device", legacy, nil); len(errs) > 0 { + t.Fatalf("pruned legacy device rejected: %v", errs) + } + for _, kind := range []string{"DeviceClaim", "Facility", "Site", "Rack", "Cable", "PowerFeed"} { + var schema apiextensions.JSONSchemaProps + if err := extensionsv1.Convert_v1_JSONSchemaProps_To_apiextensions_JSONSchemaProps(loadCRDs(t)[kind].Spec.Versions[0].Schema.OpenAPIV3Schema, &schema, nil); err != nil { + t.Fatal(err) + } + structural, err := structuralschema.NewStructural(&schema) + if err != nil { + t.Fatal(err) + } + if _, ok := structural.Properties["spec"].Properties["provenance"]; ok || structural.Properties["spec"].XPreserveUnknownFields { + t.Fatalf("%s spec must not declare or preserve provenance", kind) + } } } @@ -295,7 +349,6 @@ func TestClaimBindingAndIdentityAreImmutable(t *testing.T) { } { device := syntheticDevice() mutate(&device) - device.Spec.Provenance.RecordedAt = later(time.Hour) if errs := admit(t, "Device", object(t, device), old); len(errs) == 0 { t.Errorf("%s accepted", name) } @@ -303,7 +356,6 @@ func TestClaimBindingAndIdentityAreImmutable(t *testing.T) { unserialed := syntheticDevice() unserialed.Spec.Identity.Serial = "" added := syntheticDevice() - added.Spec.Provenance.RecordedAt = later(time.Hour) if errs := admit(t, "Device", object(t, added), object(t, unserialed)); len(errs) == 0 { t.Error("adding a serial to a registered device accepted; a new identity needs a new Device") } @@ -314,7 +366,6 @@ func TestReplacementBindsANewDeviceToTheSameClaim(t *testing.T) { replacement.Name = "rack-01-u12-synthetic-0002" replacement.Spec.Identity.Serial = "SYNTHETIC-0002" replacement.Spec.Identity.SystemUUID = "00000000-0000-4000-8000-000000000002" - replacement.Spec.Provenance.RecordedAt = later(24 * time.Hour) if errs := admit(t, "Device", object(t, replacement), nil); len(errs) > 0 { t.Fatalf("replacement device for the same claim rejected: %v", errs) } diff --git a/internal/api/inventory/v1alpha1/physical.go b/internal/api/inventory/v1alpha1/physical.go index b4eda254..7b6ddd84 100644 --- a/internal/api/inventory/v1alpha1/physical.go +++ b/internal/api/inventory/v1alpha1/physical.go @@ -16,16 +16,8 @@ type ModelShape struct { FullDepth *bool `json:"fullDepth,omitempty"` } -type SourceReference struct { - ExternalReference `json:",inline"` - SnapshotDigest string `json:"snapshotDigest"` - MappingRevision string `json:"mappingRevision"` - ObservedAt metav1.Time `json:"observedAt"` -} - type PhysicalMetadata struct { - DisplayName string `json:"displayName"` - Provenance *Provenance `json:"provenance,omitempty"` + DisplayName string `json:"displayName"` } type FacilitySpec struct { @@ -77,14 +69,13 @@ type RackSpec struct { } type Component struct { - ID string `json:"id"` - Name string `json:"name"` - Type string `json:"type"` - Connector string `json:"connector,omitempty"` - Positions int32 `json:"positions,omitempty"` - Serial string `json:"serial,omitempty"` - AssetTag string `json:"assetTag,omitempty"` - SourceRef *ExternalReference `json:"sourceRef,omitempty"` + ID string `json:"id"` + Name string `json:"name"` + Type string `json:"type"` + Connector string `json:"connector,omitempty"` + Positions int32 `json:"positions,omitempty"` + Serial string `json:"serial,omitempty"` + AssetTag string `json:"assetTag,omitempty"` } type ComponentPosition struct { diff --git a/internal/api/inventory/v1alpha1/physical_test.go b/internal/api/inventory/v1alpha1/physical_test.go index 4497c3dc..ba337dc4 100644 --- a/internal/api/inventory/v1alpha1/physical_test.go +++ b/internal/api/inventory/v1alpha1/physical_test.go @@ -2,13 +2,10 @@ package v1alpha1 import ( "bytes" - "encoding/json" "flag" "io" "os" - "strings" "testing" - "time" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" @@ -45,9 +42,8 @@ func TestManualInventoryRecordsPassAdmission(t *testing.T) { seen[kind] = true if *inventoryRecords == manualInventoryExample { spec := record["spec"].(map[string]any) - provenance := spec["provenance"].(map[string]any) - if provenance["method"] != "Manual" || provenance["source"] != nil || record["status"] != nil { - t.Fatal("manual example must have no source dependency or status assertion") + if spec["provenance"] != nil || record["status"] != nil { + t.Fatal("manual example must carry no provenance or status assertion") } if kind == "DeviceClaim" && spec["lifecycle"] != "Installation" || kind == "Device" && spec["topologyAuthority"] != "Cable" { t.Fatal("new manual records must use typed installation and Cable topology") @@ -69,29 +65,6 @@ func TestManualInventoryRecordsPassAdmission(t *testing.T) { t.Logf("validated %d records for create and unchanged update; no API writes", count) } -func TestSyntheticNetBoxHandoffPassesAdmission(t *testing.T) { - data, err := os.ReadFile("../../../../hack/testdata/netbox/candidates.json") - if err != nil { - t.Fatal(err) - } - var list struct { - Items []json.RawMessage `json:"items"` - } - if err := json.Unmarshal(data, &list); err != nil { - t.Fatal(err) - } - for _, raw := range list.Items { - var record map[string]any - if err := json.Unmarshal(raw, &record); err != nil { - t.Fatal(err) - } - kind := record["kind"].(string) - if errs := admit(t, kind, object(t, record), nil); len(errs) != 0 { - t.Fatalf("%s: %v", kind, errs) - } - } -} - func TestTypedPlacementAndLegacyBinding(t *testing.T) { claim := syntheticClaim() claim.Spec.Lifecycle = "Installation" @@ -110,7 +83,6 @@ func TestTypedPlacementAndLegacyBinding(t *testing.T) { if errs := admit(t, "DeviceClaim", object(t, candidate), nil); len(errs) != 0 { t.Fatal(errs) } - candidate.Spec.Provenance.RecordedAt = later(time.Hour) if errs := admit(t, "DeviceClaim", object(t, candidate), object(t, claim)); len(errs) == 0 { t.Fatal("moved an installation by editing placement") } @@ -121,7 +93,6 @@ func TestTypedPlacementAndLegacyBinding(t *testing.T) { t.Fatal("accepted synthetic units on rack membership") } candidate = claim - candidate.Spec.Provenance.RecordedAt = later(time.Hour) if errs := admit(t, "DeviceClaim", object(t, candidate), object(t, syntheticClaim())); len(errs) == 0 { t.Fatal("converted a legacy slot in place") } @@ -136,7 +107,7 @@ func TestPhysicalKindsSchemeAndAdmission(t *testing.T) { if err := AddToScheme(scheme); err != nil { t.Fatal(err) } - common := PhysicalMetadata{DisplayName: "Example", Provenance: provenance(recordedAt)} + common := PhysicalMetadata{DisplayName: "Example"} metadata := metav1.ObjectMeta{Name: "example", Namespace: "inventory"} records := []runtime.Object{ &Facility{ObjectMeta: metadata, Spec: FacilitySpec{PhysicalMetadata: common}}, @@ -167,15 +138,10 @@ func TestPhysicalKindsSchemeAndAdmission(t *testing.T) { } } -func TestObservationalIdentityAndComponentSafety(t *testing.T) { +func TestComponentSafety(t *testing.T) { device := syntheticDevice() device.Spec.Interfaces = nil device.Spec.TopologyAuthority = "Cable" - device.Spec.Identity.Serial, device.Spec.Identity.SystemUUID = "", "" - source := ExternalReference{System: "example-netbox", Type: "dcim/devices", ID: "1"} - device.Spec.Identity.SourceIdentity = &source - device.Spec.Provenance.Method = "NetBoxImport" - device.Spec.Provenance.Source = &SourceReference{ExternalReference: source, SnapshotDigest: "sha256:" + strings.Repeat("a", 64), MappingRevision: "example-1", ObservedAt: metav1.NewTime(recordedAt)} device.Spec.Components = []Component{{ID: "front", Name: "front", Type: "FrontPort"}, {ID: "rear", Name: "rear", Type: "RearPort", Positions: 2}} device.Spec.InternalMappings = []InternalMapping{{From: ComponentPosition{ComponentID: "front", Position: 1}, To: ComponentPosition{ComponentID: "rear", Position: 2}}} if errs := admit(t, "Device", object(t, device), nil); len(errs) != 0 { @@ -197,12 +163,6 @@ func TestObservationalIdentityAndComponentSafety(t *testing.T) { t.Fatal("accepted incompatible pass-through component types") } candidate = device.DeepCopyObject().(*Device) - candidate.Spec.Provenance.Source.ID = "2" - candidate.Spec.Provenance.RecordedAt = later(time.Hour) - if errs := admit(t, "Device", object(t, candidate), object(t, device)); len(errs) == 0 { - t.Fatal("accepted source identity takeover") - } - candidate = device.DeepCopyObject().(*Device) candidate.Spec.Interfaces = syntheticDevice().Spec.Interfaces if errs := admit(t, "Device", object(t, candidate), nil); len(errs) == 0 { t.Fatal("accepted Cable and inline topology writers") diff --git a/internal/api/inventory/v1alpha1/reported_placement_test.go b/internal/api/inventory/v1alpha1/reported_placement_test.go index 9cf658fc..4ab655ca 100644 --- a/internal/api/inventory/v1alpha1/reported_placement_test.go +++ b/internal/api/inventory/v1alpha1/reported_placement_test.go @@ -4,7 +4,6 @@ import ( "bytes" "encoding/json" "reflect" - "strings" "testing" "time" @@ -16,12 +15,11 @@ func TestPlacementJSONPatchPreconditionsBeforeAdmission(t *testing.T) { baseline := reportedDevice() baseline.UID = "device-uid" baseline.ResourceVersion = "7" - report := &ReportedPlacement{Revision: 2, Method: "Manual", ObservedAt: later(time.Minute), Reason: "Correct record", Reference: "ticket/example"} + report := &ReportedPlacement{Revision: 2, ObservedAt: later(time.Minute), Reason: "Correct record", Reference: "ticket/example"} request, err := json.Marshal([]map[string]any{ {"op": "test", "path": "/metadata/uid", "value": string(baseline.UID)}, {"op": "test", "path": "/metadata/resourceVersion", "value": baseline.ResourceVersion}, {"op": "add", "path": "/spec/reportedPlacement", "value": report}, - {"op": "replace", "path": "/spec/provenance/recordedAt", "value": later(time.Hour)}, }) if err != nil { t.Fatal(err) @@ -66,7 +64,7 @@ func TestPlacementJSONPatchPreconditionsBeforeAdmission(t *testing.T) { } beforeSpec := object(t, baseline)["spec"].(map[string]any) afterSpec := object(t, changed)["spec"].(map[string]any) - if !reflect.DeepEqual(afterSpec["provenance"].(map[string]any)["source"], beforeSpec["provenance"].(map[string]any)["source"]) || !reflect.DeepEqual(afterSpec["identity"], beforeSpec["identity"]) || changed.Spec.ClaimRef != baseline.Spec.ClaimRef { + if !reflect.DeepEqual(afterSpec["identity"], beforeSpec["identity"]) || changed.Spec.ClaimRef != baseline.Spec.ClaimRef { t.Fatal("changed protected fields") } }) @@ -75,11 +73,7 @@ func TestPlacementJSONPatchPreconditionsBeforeAdmission(t *testing.T) { func reportedDevice() Device { device := syntheticDevice() - source := ExternalReference{System: "example-netbox", Type: "dcim/devices", ID: "1"} - device.Spec.Identity.SourceIdentity = &source - device.Spec.Provenance.Method = "NetBoxImport" - device.Spec.Provenance.Source = &SourceReference{ExternalReference: source, SnapshotDigest: "sha256:" + strings.Repeat("a", 64), MappingRevision: "example-1", ObservedAt: metav1.NewTime(recordedAt)} - device.Spec.ReportedPlacement = &ReportedPlacement{Revision: 1, ObservedAt: metav1.NewTime(recordedAt), SnapshotDigest: device.Spec.Provenance.Source.SnapshotDigest, RackRef: &LocalReference{Name: "rack-a"}} + device.Spec.ReportedPlacement = &ReportedPlacement{Revision: 1, ObservedAt: metav1.NewTime(baseTime), Reason: "Initial report", Reference: "ticket/initial", RackRef: &LocalReference{Name: "rack-a"}} return device } @@ -119,12 +113,9 @@ func TestReportedPlacementAdmission(t *testing.T) { device.Spec.ReportedPlacement.Mount = "side" device.Spec.ReportedPlacement.Face = "front" }, - "snapshot": func(device *Device) { - device.Spec.ReportedPlacement.SnapshotDigest = "sha256:" + strings.Repeat("b", 64) - }, - "time": func(device *Device) { device.Spec.ReportedPlacement.ObservedAt = later(time.Hour) }, - "revision": func(device *Device) { device.Spec.ReportedPlacement.Revision = 2 }, - "manual": func(device *Device) { device.Spec.Provenance.Method = "Manual" }, + "missing reason": func(device *Device) { device.Spec.ReportedPlacement.Reason = "" }, + "missing reference": func(device *Device) { device.Spec.ReportedPlacement.Reference = "" }, + "revision": func(device *Device) { device.Spec.ReportedPlacement.Revision = 2 }, } { t.Run(name, func(t *testing.T) { device := reportedDevice() @@ -143,18 +134,12 @@ func TestPlacementCorrectionProtectsIdentityAndRevision(t *testing.T) { "removal": func(device *Device) { device.Spec.ReportedPlacement = nil }, "rebinding": func(device *Device) { device.Spec.ClaimRef.Name = "other" }, "identity": func(device *Device) { device.Spec.Identity.Serial = "other" }, - "source": func(device *Device) { - device.Spec.Provenance.Source.ID = "other" - device.Spec.Identity.SourceIdentity.ID = "other" - }, } { t.Run(name, func(t *testing.T) { old := reportedDevice() device := old.DeepCopyObject().(*Device) mutate(device) device.Spec.DisplayName = "bundled edit" - device.Spec.Provenance.RecordedAt = later(time.Hour) - device.Spec.Provenance.RecordedBy = "forged-administrator" device.Labels = map[string]string{"owner": "operator", "audit-approved": "true"} device.ManagedFields = []metav1.ManagedFieldsEntry{{Manager: "fleet-staff-inventory-ui", Operation: metav1.ManagedFieldsOperationUpdate}} if errs := admit(t, "Device", object(t, device), object(t, old)); len(errs) == 0 { @@ -165,87 +150,52 @@ func TestPlacementCorrectionProtectsIdentityAndRevision(t *testing.T) { device := reportedDevice() old := device.DeepCopyObject().(*Device) old.Spec.ReportedPlacement = nil - device.Spec.Provenance.RecordedAt = later(time.Hour) if errs := admit(t, "Device", object(t, device), object(t, old)); len(errs) != 0 { t.Fatal(errs) } old = device.DeepCopyObject().(*Device) device.Spec.DisplayName = "unrelated recordkeeping" - device.Spec.Provenance.RecordedAt = later(2 * time.Hour) if errs := admit(t, "Device", object(t, device), object(t, old)); len(errs) != 0 { t.Fatal(errs) } } -func TestManualPlacementCorrections(t *testing.T) { - for _, imported := range []bool{false, true} { - for _, existing := range []bool{false, true} { - old := syntheticDevice() - if imported { - old = reportedDevice() - } - if existing && !imported { - old.Spec.ReportedPlacement = &ReportedPlacement{Revision: 1, Method: "Manual", ObservedAt: metav1.NewTime(recordedAt), Reason: "Initial report", Reference: "ticket/initial"} - } - if !existing { - old.Spec.ReportedPlacement = nil - } - device := old.DeepCopyObject().(*Device) - revision := int32(1) - if old.Spec.ReportedPlacement != nil { - revision++ - } - device.Spec.ReportedPlacement = &ReportedPlacement{Revision: revision, Method: "Manual", ObservedAt: later(time.Minute), Reason: "Correct record", Reference: "ticket/example", RackRef: &LocalReference{Name: "other-rack"}} - device.Spec.Provenance.RecordedAt = later(time.Hour) - if errs := admit(t, "Device", object(t, device), object(t, old)); len(errs) != 0 { - t.Fatal(errs) - } - for name, mutate := range map[string]func(*Device){ - "missing reason": func(record *Device) { record.Spec.ReportedPlacement.Reason = "" }, - "blank reason": func(record *Device) { record.Spec.ReportedPlacement.Reason = " " }, - "missing evidence": func(record *Device) { record.Spec.ReportedPlacement.Reference = "" }, - "false snapshot attribution": func(record *Device) { - record.Spec.ReportedPlacement.SnapshotDigest = "sha256:" + strings.Repeat("a", 64) - }, - "skipped revision": func(record *Device) { record.Spec.ReportedPlacement.Revision += 2 }, - "claim binding": func(record *Device) { record.Spec.ClaimRef.Name = "other" }, - "identity": func(record *Device) { record.Spec.Identity.Serial = "other" }, - } { - t.Run(name, func(t *testing.T) { - invalid := device.DeepCopyObject().(*Device) - mutate(invalid) - if errs := admit(t, "Device", object(t, invalid), object(t, old)); len(errs) == 0 { - t.Fatal("accepted invalid correction") - } - }) - } - if imported { - for _, field := range []string{"method", "system", "type", "id", "removal"} { - invalid := device.DeepCopyObject().(*Device) - switch field { - case "method": - invalid.Spec.Provenance.Method = "Manual" - case "system": - invalid.Spec.Provenance.Source.System = "other" - case "type": - invalid.Spec.Provenance.Source.Type = "other" - case "id": - invalid.Spec.Provenance.Source.ID = "other" - case "removal": - invalid.Spec.Provenance.Source = nil - } - if errs := admit(t, "Device", object(t, invalid), object(t, old)); len(errs) == 0 { - t.Fatalf("accepted changed import %s", field) - } +func TestPlacementCorrections(t *testing.T) { + for _, existing := range []bool{false, true} { + old := reportedDevice() + if !existing { + old.Spec.ReportedPlacement = nil + } + device := old.DeepCopyObject().(*Device) + revision := int32(1) + if old.Spec.ReportedPlacement != nil { + revision++ + } + device.Spec.ReportedPlacement = &ReportedPlacement{Revision: revision, ObservedAt: later(time.Minute), Reason: "Correct record", Reference: "ticket/example", RackRef: &LocalReference{Name: "other-rack"}} + if errs := admit(t, "Device", object(t, device), object(t, old)); len(errs) != 0 { + t.Fatal(errs) + } + for name, mutate := range map[string]func(*Device){ + "missing reason": func(record *Device) { record.Spec.ReportedPlacement.Reason = "" }, + "blank reason": func(record *Device) { record.Spec.ReportedPlacement.Reason = " " }, + "missing evidence": func(record *Device) { record.Spec.ReportedPlacement.Reference = "" }, + "skipped revision": func(record *Device) { record.Spec.ReportedPlacement.Revision += 2 }, + "claim binding": func(record *Device) { record.Spec.ClaimRef.Name = "other" }, + "identity": func(record *Device) { record.Spec.Identity.Serial = "other" }, + } { + t.Run(name, func(t *testing.T) { + invalid := device.DeepCopyObject().(*Device) + mutate(invalid) + if errs := admit(t, "Device", object(t, invalid), object(t, old)); len(errs) == 0 { + t.Fatal("accepted invalid correction") } - } - unknown := device.DeepCopyObject().(*Device) - unknown.Spec.ReportedPlacement.RackRef = nil - unknown.Spec.ReportedPlacement.Revision++ - unknown.Spec.Provenance.RecordedAt = later(2 * time.Hour) - if errs := admit(t, "Device", object(t, unknown), object(t, device)); len(errs) != 0 { - t.Fatal(errs) - } + }) + } + unknown := device.DeepCopyObject().(*Device) + unknown.Spec.ReportedPlacement.RackRef = nil + unknown.Spec.ReportedPlacement.Revision++ + if errs := admit(t, "Device", object(t, unknown), object(t, device)); len(errs) != 0 { + t.Fatal(errs) } } } diff --git a/internal/api/inventory/v1alpha1/site_test.go b/internal/api/inventory/v1alpha1/site_test.go index 775d0a2a..b3f3d8f1 100644 --- a/internal/api/inventory/v1alpha1/site_test.go +++ b/internal/api/inventory/v1alpha1/site_test.go @@ -18,7 +18,7 @@ func syntheticSite() *Site { return &Site{ TypeMeta: metav1.TypeMeta{APIVersion: GroupVersion.String(), Kind: "Site"}, ObjectMeta: metav1.ObjectMeta{Name: "site-stable", Namespace: "inventory", UID: "site-uid"}, - Spec: SiteSpec{PhysicalMetadata: PhysicalMetadata{DisplayName: "Example operational site", Provenance: &Provenance{Method: "Manual", RecordedBy: "synthetic", RecordedAt: metav1.NewTime(recordedAt)}}, Code: "EX3", FacilityRefs: []LocalReference{{Name: "facility-stable"}}}, + Spec: SiteSpec{PhysicalMetadata: PhysicalMetadata{DisplayName: "Example operational site"}, Code: "EX3", FacilityRefs: []LocalReference{{Name: "facility-stable"}}}, } } @@ -173,7 +173,7 @@ func TestSiteNameReuseResolvesReplacementWithoutChangingDesiredState(t *testing. if !reflect.DeepEqual(object(t, site)["spec"], object(t, before)["spec"]) { t.Fatal("reader changed desired state") } - replacement.DeletionTimestamp = &metav1.Time{Time: recordedAt} + replacement.DeletionTimestamp = &metav1.Time{Time: baseTime} replacement.Finalizers = []string{"test.example/retain"} deleting := fake.NewClientBuilder().WithScheme(scheme).WithObjects(replacement).Build() if records, err := ReadSiteFacilities(context.Background(), deleting, site); err == nil || records != nil { diff --git a/internal/api/inventory/v1alpha1/types.go b/internal/api/inventory/v1alpha1/types.go index 2cc1a7aa..d0c82e23 100644 --- a/internal/api/inventory/v1alpha1/types.go +++ b/internal/api/inventory/v1alpha1/types.go @@ -18,21 +18,6 @@ import ( var GroupVersion = schema.GroupVersion{Group: "fleet.datumapis.com", Version: "v1alpha1"} -// ProvenanceManual marks a record an operator entered by hand. -const ProvenanceManual = "Manual" - -// Provenance optionally says how, by whom, and when a record's spec was -// written. It is deprecated and no longer required. -type Provenance struct { - Method string `json:"method"` - RecordedBy string `json:"recordedBy"` - RecordedAt metav1.Time `json:"recordedAt"` - // Reference is an optional, opaque pointer to where the facts came from. - // Fleet does not interpret it. - Reference string `json:"reference,omitempty"` - Source *SourceReference `json:"source,omitempty"` -} - // DeviceClaim retains legacy slot plans and typed observational installations. type DeviceClaim struct { metav1.TypeMeta `json:",inline"` @@ -45,7 +30,6 @@ type DeviceClaimSpec struct { DisplayName string `json:"displayName,omitempty"` Lifecycle string `json:"lifecycle,omitempty"` CableRefs []LocalReference `json:"cableRefs,omitempty"` - Provenance *Provenance `json:"provenance,omitempty"` ExpectedIdentity ExpectedIdentity `json:"expectedIdentity"` Placement Placement `json:"placement"` Ports []ExpectedPort `json:"ports,omitempty"` @@ -111,7 +95,6 @@ type DeviceSpec struct { ServiceAssociations []ServiceAssociation `json:"serviceAssociations,omitempty"` TopologyAuthority string `json:"topologyAuthority,omitempty"` ClaimRef LocalReference `json:"claimRef"` - Provenance *Provenance `json:"provenance,omitempty"` Identity DeviceIdentity `json:"identity"` BMC *BMC `json:"bmc,omitempty"` Interfaces []Interface `json:"interfaces,omitempty"` @@ -121,19 +104,18 @@ type DeviceSpec struct { } type ReportedPlacement struct { - Revision int32 `json:"revision"` - ObservedAt metav1.Time `json:"observedAt"` - SnapshotDigest string `json:"snapshotDigest,omitempty"` - Method string `json:"method,omitempty"` - Reason string `json:"reason,omitempty"` - Reference string `json:"reference,omitempty"` - FacilityRef *LocalReference `json:"facilityRef,omitempty"` - RackRef *LocalReference `json:"rackRef,omitempty"` - Position *float64 `json:"position,omitempty"` - Height *float64 `json:"height,omitempty"` - Face string `json:"face,omitempty"` - FullDepth *bool `json:"fullDepth,omitempty"` - Mount string `json:"mount,omitempty"` + Revision int32 `json:"revision"` + ObservedAt metav1.Time `json:"observedAt"` + // Reason and Reference explain and evidence the report. Both are required. + Reason string `json:"reason"` + Reference string `json:"reference"` + FacilityRef *LocalReference `json:"facilityRef,omitempty"` + RackRef *LocalReference `json:"rackRef,omitempty"` + Position *float64 `json:"position,omitempty"` + Height *float64 `json:"height,omitempty"` + Face string `json:"face,omitempty"` + FullDepth *bool `json:"fullDepth,omitempty"` + Mount string `json:"mount,omitempty"` } type LocalReference struct { @@ -141,12 +123,11 @@ type LocalReference struct { } // DeviceIdentity is the detected chassis identity. Serial and SystemUUID are -// matching evidence, not authenticators. Imports can instead retain source identity. +// matching evidence, not authenticators; at least one is required. type DeviceIdentity struct { - SourceIdentity *ExternalReference `json:"sourceIdentity,omitempty"` - Manufacturer string `json:"manufacturer,omitempty"` - Model string `json:"model"` - Serial string `json:"serial,omitempty"` + Manufacturer string `json:"manufacturer,omitempty"` + Model string `json:"model"` + Serial string `json:"serial,omitempty"` // SystemUUID is the SMBIOS system UUID in lowercase canonical form. SystemUUID string `json:"systemUUID,omitempty"` } diff --git a/ui/provider/README.md b/ui/provider/README.md index 14abe2ba..9c015e1e 100644 --- a/ui/provider/README.md +++ b/ui/provider/README.md @@ -26,9 +26,9 @@ Operations in the navigation. The page has four tabs: links retain the kind, namespace, and record name without adding host routes. Facilities lead to racks and installation plans; claims lead to all registered devices; cable endpoints lead to devices or feeds. Identity, typed components, - internal paths, external service references, legacy peers, and provenance remain - visible. Missing claims do not hide hardware, and historical registrations do - not establish an active device. The original `inventory/:namespace/:claim` + internal paths, external service references, legacy peers, and creation times + remain visible. Missing claims do not hide hardware, and historical + registrations do not establish an active device. The original `inventory/:namespace/:claim` route remains available for existing links. Authorized manual management uses the existing guarded forms; Site membership and premises identifiers remain direct API operations. Records are not managed through Git. See the @@ -93,18 +93,17 @@ to that array instead. The Inventory tab loads all six physical inventory collections with API pagination. Counts describe loaded records, not capacity or verified equipment. Unknown occupancy, power budgets, and ambiguous bindings stay unknown. Contextual help -explains these boundaries; there is no report picker, automatic import, sync, or -hardware action. Reads require the provider-scoped inventory viewer role, not a -consumer Metal role. Management separately checks backend create/patch permission -in the provider project: Facility/Rack/Installation-plan/Device/Cable creation +explains these boundaries; there is no report picker, sync, or hardware action. +Reads require the provider-scoped inventory viewer role, not a consumer Metal +role. Management separately checks backend create/patch permission in the +provider project: Facility/Rack/Installation-plan/Device/Cable creation and portal-owned display-name editing. The existing `fleet.datumapis.com-inventory-manager` role and separate `physical-inventory-managers` group binding are not deployed by this UI phase. -Group names/staff membership never enable controls. Flux/imported/unknown-writer -records remain read-only pending ownership review; import provenance does not -mean Git ownership. New inventory is direct API/operator-managed. Namespace choice is not an -authorization boundary. Denied collections and detail links show access guidance, -not empty inventory; readable sections remain available. +Group names/staff membership never enable controls. Flux-managed and unknown-writer +records remain read-only pending ownership review. New inventory is direct +API/operator-managed. Namespace choice is not an authorization boundary. Denied +collections and detail links show access guidance, not empty inventory; readable sections remain available. See [hardware directory scope and design gaps](../../docs/development/staff-inventory-ui.md). The standalone harness imports `src/preview.css`, compiling the installed Datum UI diff --git a/ui/provider/src/components/adversarial-review.test.tsx b/ui/provider/src/components/adversarial-review.test.tsx index 39d0d611..9d963d02 100644 --- a/ui/provider/src/components/adversarial-review.test.tsx +++ b/ui/provider/src/components/adversarial-review.test.tsx @@ -7,8 +7,8 @@ import { InventorySessionBoundary } from './inventory-session-boundary'; import DeviceInventoryList from '../pages/device-inventory-list'; import { inventoryPayload, INVENTORY_FIELD_MANAGER } from '../lib/inventory-management'; -const values = { name: 'review-facility', namespace: 'default', displayName: 'Original label', recordedBy: 'synthetic-reviewer', reference: '', facility: '', height: '' }; -const original = { ...inventoryPayload('Facility', values, '2026-01-01T00:00:00Z'), metadata: { name: values.name, namespace: 'default', uid: 'synthetic-only', resourceVersion: '1', managedFields: [{ manager: INVENTORY_FIELD_MANAGER }] } }; +const values = { name: 'review-facility', namespace: 'default', displayName: 'Original label', facility: '', height: '' }; +const original = { ...inventoryPayload('Facility', values), metadata: { name: values.name, namespace: 'default', uid: 'synthetic-only', resourceVersion: '1', managedFields: [{ manager: INVENTORY_FIELD_MANAGER }] } }; const response = (data: unknown) => ({ ok: true, status: 200, json: async () => ({ data }) }); afterEach(() => { cleanup(); vi.unstubAllGlobals(); }); @@ -81,7 +81,6 @@ it('invalidates authority synchronously before React commits the session transit fireEvent.click(screen.getByRole('button', { name: 'Create facility' })); fireEvent.change(screen.getByLabelText('Record name'), { target: { value: values.name } }); fireEvent.change(screen.getByLabelText('Display name'), { target: { value: values.displayName } }); - fireEvent.change(screen.getByLabelText('Recorded by'), { target: { value: values.recordedBy } }); fireEvent.click(screen.getByRole('button', { name: 'Create facility record' })); await waitFor(() => expect(releaseReview).toBeDefined()); principal = 'staff-b'; @@ -110,7 +109,6 @@ it('must not send a create after the initiating authenticated principal unmounts fireEvent.click(screen.getByRole('button', { name: 'Create facility' })); fireEvent.change(screen.getByLabelText('Record name'), { target: { value: values.name } }); fireEvent.change(screen.getByLabelText('Display name'), { target: { value: values.displayName } }); - fireEvent.change(screen.getByLabelText('Recorded by'), { target: { value: values.recordedBy } }); fireEvent.click(screen.getByRole('button', { name: 'Create facility record' })); await waitFor(() => expect(releaseReview).toBeDefined()); principal = 'staff-b'; @@ -134,7 +132,6 @@ it('must not silently advance an open edit form to a refreshed resourceVersion', fireEvent.click(screen.getByText('Manage this record')); fireEvent.click(screen.getByRole('button', { name: 'Edit display name' })); fireEvent.change(screen.getByLabelText('Display name'), { target: { value: 'My unsaved label' } }); - fireEvent.change(screen.getByLabelText('Recorded by'), { target: { value: values.recordedBy } }); current = { ...original, metadata: { ...original.metadata, resourceVersion: '2' }, spec: { ...original.spec, displayName: 'Other operator saved this' } }; mounted.rerender(content()); fireEvent.click(screen.getByRole('button', { name: 'Save display name' })); diff --git a/ui/provider/src/components/device-placement-edit.test.tsx b/ui/provider/src/components/device-placement-edit.test.tsx index a86a3aff..96fa021b 100644 --- a/ui/provider/src/components/device-placement-edit.test.tsx +++ b/ui/provider/src/components/device-placement-edit.test.tsx @@ -9,8 +9,8 @@ import { InventoryOperationContext, InventoryOperationScope } from '../lib/inven vi.mock('../lib/inventory-management', async () => ({ ...await vi.importActual('../lib/inventory-management'), useInventoryPermission: vi.fn() })); const permission = vi.mocked(useInventoryPermission); -const device: Device = { ...fixturePhysicalDevices[0], metadata: { name: 'example', namespace: 'default', uid: 'uid', resourceVersion: '7' }, spec: { ...fixturePhysicalDevices[0].spec, reportedPlacement: undefined, provenance: { ...fixturePhysicalDevices[0].spec.provenance, method: 'NetBoxImport', recordedAt: '2026-01-01T00:00:00Z' } } }; -const rack: PhysicalRecord = { kind: 'Rack', metadata: { name: 'rack', namespace: 'default', uid: 'rack-uid' }, spec: { displayName: 'Restricted rack name', heightUnits: 42, provenance: device.spec.provenance } }; +const device: Device = { ...fixturePhysicalDevices[0], metadata: { name: 'example', namespace: 'default', uid: 'uid', resourceVersion: '7' }, spec: { ...fixturePhysicalDevices[0].spec, reportedPlacement: undefined } }; +const rack: PhysicalRecord = { kind: 'Rack', metadata: { name: 'rack', namespace: 'default', uid: 'rack-uid' }, spec: { displayName: 'Restricted rack name', heightUnits: 42 } }; const response = (data: unknown, status = 200) => ({ ok: status < 400, status, json: async () => ({ data }) }); function setup(record = device, session = new InventoryOperationScope()) { const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); @@ -20,16 +20,16 @@ function setup(record = device, session = new InventoryOperationScope()) { function openAndFill(existing = false) { fireEvent.click(screen.getByRole('button', { name: existing ? 'Correct location' : 'Add reported location' })); fireEvent.change(screen.getByLabelText('Observation time (ISO 8601)'), { target: { value: '2026-01-02T00:00:00Z' } }); - fireEvent.change(screen.getByLabelText('Correction reason'), { target: { value: 'Correct source record' } }); + fireEvent.change(screen.getByLabelText('Correction reason'), { target: { value: 'Correct recorded location' } }); fireEvent.change(screen.getByLabelText('Evidence reference'), { target: { value: 'ticket/example' } }); } beforeEach(() => { vi.clearAllMocks(); permission.mockReturnValue({ data: true, isFetching: false, error: null } as never); }); afterEach(() => vi.unstubAllGlobals()); describe('reported location editor', () => { - it.each([false, true])('adds/edits an imported Device and refreshes projections: %s', async existing => { + it.each([false, true])('adds/edits a Device reported location and refreshes projections: %s', async existing => { const record = structuredClone(device); - if (existing) record.spec.reportedPlacement = { revision: 1, observedAt: '2026-01-01T00:00:00Z', snapshotDigest: `sha256:${'a'.repeat(64)}`, rackRef: { name: 'rack' }, position: 12, height: 4, face: 'rear', fullDepth: true }; + if (existing) record.spec.reportedPlacement = { revision: 1, observedAt: '2026-01-01T00:00:00Z', reason: 'Synthetic survey', reference: 'ticket/synthetic', rackRef: { name: 'rack' }, position: 12, height: 4, face: 'rear', fullDepth: true }; const fetch = vi.fn().mockImplementation(async (_url: string, request: RequestInit) => { if (request.method === 'POST') return response({ status: { allowed: true } }); if (request.method === 'PATCH') return response({ ...record, metadata: { ...record.metadata, resourceVersion: '8' }, spec: { ...record.spec, reportedPlacement: JSON.parse(request.body as string)[2].value } }); diff --git a/ui/provider/src/components/device-placement-edit.tsx b/ui/provider/src/components/device-placement-edit.tsx index 2f1db7d1..77550db4 100644 --- a/ui/provider/src/components/device-placement-edit.tsx +++ b/ui/provider/src/components/device-placement-edit.tsx @@ -97,7 +97,7 @@ function DevicePlacementForm({ device, locations, issues }: { device: Device; lo setFields(next); setBlocked(false); setMessage(''); }}>{device.spec.reportedPlacement ? 'Correct location' : 'Add reported location'}} {baseline &&
      -

      Source: manual observation/correction. Original import provenance is retained. Authenticated actor history uses existing resource audit logs, not this form's attribution.

      +

      Authenticated actor history uses existing resource audit logs.

      diff --git a/ui/provider/src/components/exact-head-independent.test.tsx b/ui/provider/src/components/exact-head-independent.test.tsx index ddfbc901..864f87ab 100644 --- a/ui/provider/src/components/exact-head-independent.test.tsx +++ b/ui/provider/src/components/exact-head-independent.test.tsx @@ -7,8 +7,8 @@ import { InventorySessionBoundary } from './inventory-session-boundary'; import { inventoryPayload, INVENTORY_FIELD_MANAGER } from '../lib/inventory-management'; import DeviceInventoryList from '../pages/device-inventory-list'; -const values = { name: 'exact-review', namespace: 'default', displayName: 'Original', recordedBy: 'synthetic', reference: '', facility: '', height: '' }; -const original = { ...inventoryPayload('Facility', values, '2026-01-01T00:00:00Z'), metadata: { name: values.name, namespace: 'default', uid: 'synthetic', resourceVersion: '1', managedFields: [{ manager: INVENTORY_FIELD_MANAGER }] } }; +const values = { name: 'exact-review', namespace: 'default', displayName: 'Original', facility: '', height: '' }; +const original = { ...inventoryPayload('Facility', values), metadata: { name: values.name, namespace: 'default', uid: 'synthetic', resourceVersion: '1', managedFields: [{ manager: INVENTORY_FIELD_MANAGER }] } }; const response = (data: unknown, status = 200) => ({ ok: status < 400, status, json: async () => ({ data }) }); afterEach(() => { cleanup(); vi.unstubAllGlobals(); }); @@ -16,7 +16,6 @@ async function open(editing: boolean, label: string) { fireEvent.click(await screen.findByRole('button', { name: editing ? 'Edit display name' : 'Create facility' })); if (!editing) fireEvent.change(screen.getByLabelText('Record name'), { target: { value: values.name } }); fireEvent.change(screen.getByLabelText('Display name'), { target: { value: label } }); - fireEvent.change(screen.getByLabelText('Recorded by'), { target: { value: 'synthetic' } }); } it.each([false, true].flatMap(strict => [false, true].flatMap(editing => ['review', 'dispatch-ok', 'dispatch-error'].flatMap(stage => ['fast-repeat', 'slow', 'overlap', 'cancel-navigation', 'focus-blur', 'focus-pagehide'].map(transition => ({ strict, editing, stage, transition }))))))('independent $transition $stage edit=$editing strict=$strict', async ({ strict, editing, stage, transition }) => { diff --git a/ui/provider/src/components/inventory-hardware-fields.test.tsx b/ui/provider/src/components/inventory-hardware-fields.test.tsx index 19c8d8d0..4b64db12 100644 --- a/ui/provider/src/components/inventory-hardware-fields.test.tsx +++ b/ui/provider/src/components/inventory-hardware-fields.test.tsx @@ -15,7 +15,7 @@ function renderForm(kind: 'Device' | 'Cable') { async function open(kind: 'Device' | 'Cable') { fireEvent.click(screen.getByText(`Manage ${kind.toLowerCase()}s`)); fireEvent.click(await screen.findByRole('button', { name: `Create ${kind.toLowerCase()}` })); - for (const [label, value] of [['Record name', 'synthetic-new'], ['Display name', 'Synthetic record'], ['Recorded by', 'synthetic-operator']]) fireEvent.change(screen.getByLabelText(label), { target: { value } }); + for (const [label, value] of [['Record name', 'synthetic-new'], ['Display name', 'Synthetic record']]) fireEvent.change(screen.getByLabelText(label), { target: { value } }); } it('registers hardware through the real form without changing claim identity', async () => { const writes: unknown[] = []; diff --git a/ui/provider/src/components/inventory-location.test.tsx b/ui/provider/src/components/inventory-location.test.tsx index 9309695e..9cda7be9 100644 --- a/ui/provider/src/components/inventory-location.test.tsx +++ b/ui/provider/src/components/inventory-location.test.tsx @@ -8,7 +8,7 @@ import { fixturePhysicalClaims, fixturePhysicalDevices, fixturePhysicalRecords } const rack = fixturePhysicalRecords[1]; it.each([true, false, undefined])('draws reported Device geometry with explicit depth %s', fullDepth => { - const device = { ...fixturePhysicalDevices[0], spec: { ...fixturePhysicalDevices[0].spec, reportedPlacement: { revision: 1 as const, observedAt: '2026-11-21T00:00:00Z', snapshotDigest: `sha256:${'a'.repeat(64)}`, rackRef: { name: rack.metadata.name }, position: 12, height: 4, face: 'rear' as const, fullDepth } } }; + const device = { ...fixturePhysicalDevices[0], spec: { ...fixturePhysicalDevices[0].spec, reportedPlacement: { revision: 1 as const, observedAt: '2026-11-21T00:00:00Z', reason: 'Synthetic survey', reference: 'ticket/synthetic', rackRef: { name: rack.metadata.name }, position: 12, height: 4, face: 'rear' as const, fullDepth } } }; render(); const rear = within(screen.getByRole('list', { name: 'rear recorded placements' })).getByRole('link', { name: /Reported placement/ }); expect(rear).toHaveAttribute('href', expect.stringContaining('kind=Device&')); diff --git a/ui/provider/src/components/inventory-location.tsx b/ui/provider/src/components/inventory-location.tsx index b068a3f4..20070f8f 100644 --- a/ui/provider/src/components/inventory-location.tsx +++ b/ui/provider/src/components/inventory-location.tsx @@ -65,7 +65,7 @@ export function RackOverview({ rack, inventory }: { rack: PhysicalRecord; invent
      diff --git a/ui/provider/src/components/inventory-management-lifetime.test.tsx b/ui/provider/src/components/inventory-management-lifetime.test.tsx index b92cd7dc..2a935370 100644 --- a/ui/provider/src/components/inventory-management-lifetime.test.tsx +++ b/ui/provider/src/components/inventory-management-lifetime.test.tsx @@ -4,8 +4,8 @@ import { afterEach, expect, it, vi } from 'vitest'; import { InventoryManagement } from './inventory-management'; import { inventoryPayload, INVENTORY_FIELD_MANAGER } from '../lib/inventory-management'; -const values = { name: 'synthetic-only', namespace: 'default', displayName: 'Original', recordedBy: 'operator', reference: '', facility: '', height: '' }; -const original = { ...inventoryPayload('Facility', values, '2026-01-01T00:00:00Z'), metadata: { name: values.name, namespace: 'default', uid: 'synthetic', resourceVersion: '1', managedFields: [{ manager: INVENTORY_FIELD_MANAGER }] } }; +const values = { name: 'synthetic-only', namespace: 'default', displayName: 'Original', facility: '', height: '' }; +const original = { ...inventoryPayload('Facility', values), metadata: { name: values.name, namespace: 'default', uid: 'synthetic', resourceVersion: '1', managedFields: [{ manager: INVENTORY_FIELD_MANAGER }] } }; const response = (data: unknown) => ({ ok: true, status: 200, json: async () => ({ data }) }); afterEach(() => vi.unstubAllGlobals()); @@ -31,7 +31,6 @@ it.each(['create-blur', 'create-unmount', 'edit-blur', 'edit-unmount', 'create-d fireEvent.click(screen.getByRole('button', { name: editing ? 'Edit display name' : 'Create facility' })); if (!editing) fireEvent.change(screen.getByLabelText('Record name'), { target: { value: values.name } }); fireEvent.change(screen.getByLabelText('Display name'), { target: { value: 'Retained safe input' } }); - fireEvent.change(screen.getByLabelText('Recorded by'), { target: { value: values.recordedBy } }); fireEvent.click(screen.getByRole('button', { name: editing ? 'Save display name' : 'Create facility record' })); await waitFor(() => expect(release).toBeDefined()); if (mode.endsWith('unmount')) mounted.unmount(); diff --git a/ui/provider/src/components/inventory-management.test.tsx b/ui/provider/src/components/inventory-management.test.tsx index 6d3cc3d8..3d58043d 100644 --- a/ui/provider/src/components/inventory-management.test.tsx +++ b/ui/provider/src/components/inventory-management.test.tsx @@ -32,7 +32,6 @@ describe('management affordances', () => { fireEvent.click(screen.getByRole('button', { name: 'Create facility' })); fireEvent.change(screen.getByLabelText('Record name'), { target: { value: 'example' } }); fireEvent.change(screen.getByLabelText('Display name'), { target: { value: 'Example' } }); - fireEvent.change(screen.getByLabelText('Recorded by'), { target: { value: 'operator@example.com' } }); fireEvent.click(screen.getByRole('button', { name: 'Create facility record' })); await waitFor(() => expect(screen.getByRole('status')).toHaveTextContent('Facility record created.')); }); @@ -43,7 +42,6 @@ describe('management affordances', () => { fireEvent.click(screen.getByRole('button', { name: 'Create facility' })); fireEvent.change(screen.getByLabelText('Record name'), { target: { value: 'example' } }); fireEvent.change(screen.getByLabelText('Display name'), { target: { value: 'Unsaved facility' } }); - fireEvent.change(screen.getByLabelText('Recorded by'), { target: { value: 'operator@example.com' } }); fireEvent.click(screen.getByRole('button', { name: 'Create facility record' })); await waitFor(() => expect(screen.getByRole('status')).toHaveTextContent('input is kept here')); expect(screen.getByLabelText('Display name')).toHaveValue('Unsaved facility'); diff --git a/ui/provider/src/components/inventory-management.tsx b/ui/provider/src/components/inventory-management.tsx index 2c2bc5b6..28f5c67f 100644 --- a/ui/provider/src/components/inventory-management.tsx +++ b/ui/provider/src/components/inventory-management.tsx @@ -52,7 +52,7 @@ function InventoryManagementForm({ kind, record, facilities: sourceFacilities, c const [pending, setPending] = useState(false); const [blocked, setBlocked] = useState(false); const [message, setMessage] = useState(''); - const [values, setValues] = useState({ name: record?.metadata.name ?? '', namespace, displayName: record?.spec.displayName ?? '', recordedBy: '', reference: '', facility: '', height: '' }); + const [values, setValues] = useState({ name: record?.metadata.name ?? '', namespace, displayName: record?.spec.displayName ?? '', facility: '', height: '' }); const field = (name: keyof InventoryFormValues, value: string) => setValues(previous => ({ ...previous, [name]: value })); const kindLabel = kind === 'DeviceClaim' ? 'installation plan' : kind.toLowerCase(); async function save(event: FormEvent) { @@ -106,7 +106,7 @@ function InventoryManagementForm({ kind, record, facilities: sourceFacilities, c {compact && {record ? 'Editing access' : 'Namespace & access'}} {!record && } {dependenciesUnavailable &&

      Related records are unavailable, not empty. Creation needs readable location, installation, or endpoint records. Ask your administrator about viewing access, or try again after a temporary failure.

      } - {!editable ?

      Display-name editing uses a narrower portal writer policy and is unavailable for this record. Import provenance is history, not Git ownership or server authorization. Device location correction, when separately available, uses ordinary management access and does not perform an ownership handover.

      : permission.isFetching ?

      Checking management access…

      : permission.error instanceof ApiError && permission.error.status === 401 ?

      Your session expired. Sign in again through the staff portal before continuing. Unsaved input remains here.

      : !allowed &&

      Viewing and management access are separate. Ask your administrator about physical-inventory management access. A permission check must succeed before changes are available.

      } + {!editable ?

      Display-name editing uses a narrower portal writer policy and is unavailable for this record. Device location correction, when separately available, uses ordinary management access and does not perform an ownership handover.

      : permission.isFetching ?

      Checking management access…

      : permission.error instanceof ApiError && permission.error.status === 401 ?

      Your session expired. Sign in again through the staff portal before continuing. Unsaved input remains here.

      : !allowed &&

      Viewing and management access are separate. Ask your administrator about physical-inventory management access. A permission check must succeed before changes are available.

      } {allowed && !open && }
      {open && -

      {record ? 'Only the display name and recording details change. Identity, placement, geometry, connections, and history remain untouched.' : 'Create a physical record only. This does not verify equipment, reserve space, or provision hardware.'}

      +

      {record ? 'Only the display name changes. Identity, placement, geometry, connections, and history remain untouched.' : 'Create a physical record only. This does not verify equipment, reserve space, or provision hardware.'}

      {!record && } {!record && (kind === 'Device' || kind === 'Cable' || kind === 'DeviceClaim') && } @@ -128,9 +128,6 @@ function InventoryManagementForm({ kind, record, facilities: sourceFacilities, c

      Leave height blank if unknown. A rack record does not establish free space.

      } - -

      The recorder is an attributed observation, not a replacement for the API audit identity of your signed-in account.

      -
      } {message &&

      {message}

      } diff --git a/ui/provider/src/components/inventory-navigation-safety.test.tsx b/ui/provider/src/components/inventory-navigation-safety.test.tsx index 82a973a4..9a50a68a 100644 --- a/ui/provider/src/components/inventory-navigation-safety.test.tsx +++ b/ui/provider/src/components/inventory-navigation-safety.test.tsx @@ -7,8 +7,8 @@ import { InventorySessionBoundary } from './inventory-session-boundary'; import DeviceInventoryList from '../pages/device-inventory-list'; import { inventoryPayload, INVENTORY_FIELD_MANAGER } from '../lib/inventory-management'; -const values = { name: 'independent-review', namespace: 'default', displayName: 'Original', recordedBy: 'synthetic-reviewer', reference: '', facility: '', height: '' }; -const original = { ...inventoryPayload('Facility', values, '2026-01-01T00:00:00Z'), metadata: { name: values.name, namespace: 'default', uid: 'synthetic-only', resourceVersion: '1', managedFields: [{ manager: INVENTORY_FIELD_MANAGER }] } }; +const values = { name: 'independent-review', namespace: 'default', displayName: 'Original', facility: '', height: '' }; +const original = { ...inventoryPayload('Facility', values), metadata: { name: values.name, namespace: 'default', uid: 'synthetic-only', resourceVersion: '1', managedFields: [{ manager: INVENTORY_FIELD_MANAGER }] } }; const response = (data: unknown, status = 200) => ({ ok: status < 400, status, json: async () => ({ data, error: 'PRIVATE DIAGNOSTIC' }) }); afterEach(() => { cleanup(); vi.unstubAllGlobals(); }); @@ -80,7 +80,6 @@ async function open(editing: boolean) { fireEvent.click(opener); if (!editing) fireEvent.change(screen.getByLabelText('Record name'), { target: { value: values.name } }); fireEvent.change(screen.getByLabelText('Display name'), { target: { value: 'Independent safe input' } }); - fireEvent.change(screen.getByLabelText('Recorded by'), { target: { value: values.recordedBy } }); } it.each(['create-review', 'edit-review', 'edit-get', 'create-dispatch', 'edit-dispatch'])('A-B-A session transitions fence old %s while new form remains usable', async mode => { diff --git a/ui/provider/src/components/inventory-read-access.test.tsx b/ui/provider/src/components/inventory-read-access.test.tsx index cc584562..f4fbc8ea 100644 --- a/ui/provider/src/components/inventory-read-access.test.tsx +++ b/ui/provider/src/components/inventory-read-access.test.tsx @@ -31,7 +31,7 @@ it.each([false, true])('removes denied prerequisite choices and cached records, {integrated ? : } ); fireEvent.click(await screen.findByRole('button', { name: 'Create device' })); - for (const [label, value] of [['Record name', 'synthetic-new'], ['Display name', 'Safe unsaved name'], ['Recorded by', 'operator'], ['Model', 'Example'], ['Serial number', 'SYNTHETIC-NEW'], ['Installation plan', 'plan-uid']]) fireEvent.change(screen.getByLabelText(label), { target: { value } }); + for (const [label, value] of [['Record name', 'synthetic-new'], ['Display name', 'Safe unsaved name'], ['Model', 'Example'], ['Serial number', 'SYNTHETIC-NEW'], ['Installation plan', 'plan-uid']]) fireEvent.change(screen.getByLabelText(label), { target: { value } }); fireEvent.click(screen.getByRole('button', { name: 'Create device record' })); await screen.findByText(/Restricted choices were removed/); expect(writes).toEqual([]); diff --git a/ui/provider/src/components/inventory-revalidation-safety.test.tsx b/ui/provider/src/components/inventory-revalidation-safety.test.tsx index f04b2f2a..f3d359a5 100644 --- a/ui/provider/src/components/inventory-revalidation-safety.test.tsx +++ b/ui/provider/src/components/inventory-revalidation-safety.test.tsx @@ -6,8 +6,8 @@ import { InventoryManagement } from './inventory-management'; import { InventorySessionBoundary } from './inventory-session-boundary'; import { inventoryPayload, INVENTORY_FIELD_MANAGER } from '../lib/inventory-management'; -const values = { name: 'fresh-test', namespace: 'default', displayName: 'Fresh record', recordedBy: 'reviewer', reference: '', facility: 'fresh-test', height: '' }; -const original = { ...inventoryPayload('Facility', values, '2026-01-01T00:00:00Z'), metadata: { name: values.name, namespace: 'default', uid: 'synthetic', resourceVersion: '1', managedFields: [{ manager: INVENTORY_FIELD_MANAGER }] } }; +const values = { name: 'fresh-test', namespace: 'default', displayName: 'Fresh record', facility: 'fresh-test', height: '' }; +const original = { ...inventoryPayload('Facility', values), metadata: { name: values.name, namespace: 'default', uid: 'synthetic', resourceVersion: '1', managedFields: [{ manager: INVENTORY_FIELD_MANAGER }] } }; const response = (data: unknown) => ({ ok: true, status: 200, json: async () => ({ data }) }); afterEach(() => { cleanup(); vi.unstubAllGlobals(); }); @@ -15,7 +15,6 @@ async function open(editing: boolean, rack = false) { fireEvent.click(await screen.findByRole('button', { name: editing ? 'Edit display name' : rack ? 'Create rack' : 'Create facility' })); if (!editing) fireEvent.change(screen.getByLabelText('Record name'), { target: { value: values.name } }); fireEvent.change(screen.getByLabelText('Display name'), { target: { value: 'New input' } }); - fireEvent.change(screen.getByLabelText('Recorded by'), { target: { value: 'reviewer' } }); if (rack) fireEvent.change(screen.getByLabelText('Facility'), { target: { value: values.name } }); } diff --git a/ui/provider/src/components/physical-inventory.tsx b/ui/provider/src/components/physical-inventory.tsx index 7f0aa5de..7af39c94 100644 --- a/ui/provider/src/components/physical-inventory.tsx +++ b/ui/provider/src/components/physical-inventory.tsx @@ -112,11 +112,6 @@ function Components({ components }: { components: PhysicalComponent[] }) { {component.assetTag ? `Asset tag: ${component.assetTag}` : 'No asset tag recorded'} - {component.sourceRef && ( - - {component.sourceRef.system}/{component.sourceRef.type}/{component.sourceRef.id} - - )} ))} @@ -294,7 +289,6 @@ export function PhysicalInventory({ inventory: source, onRetry }: { inventory: I function Detail({ entry }: { entry: RecordEntry }) { const { record, kind } = entry; const namespace = record.metadata.namespace; - const provenance = record.spec.provenance; const device = kind === 'Device' ? (record as RawDevice) : undefined; const claim = kind === 'DeviceClaim' ? (record as RawDeviceClaim) : undefined; const physical = !device && !claim ? (record as PhysicalRecord) : undefined; @@ -377,7 +371,7 @@ export function PhysicalInventory({ inventory: source, onRetry }: { inventory: I {placement(entry)} {device.spec.reportedPlacement?.rackRef && {reference('Rack', namespace, device.spec.reportedPlacement.rackRef.name)}} {device.spec.reportedPlacement?.facilityRef && {reference('Facility', namespace, device.spec.reportedPlacement.facilityRef.name)}} - {device.spec.reportedPlacement && Revision {device.spec.reportedPlacement.revision} · {device.spec.reportedPlacement.observedAt} · {device.spec.reportedPlacement.method === 'Manual' ? 'Manual observation/correction' : 'NetBox source report'}, not physically verified{device.spec.reportedPlacement.reason && ` · Reason: ${device.spec.reportedPlacement.reason}`}{device.spec.reportedPlacement.reference && ` · Evidence: ${device.spec.reportedPlacement.reference}`}} + {device.spec.reportedPlacement && Revision {device.spec.reportedPlacement.revision} · {device.spec.reportedPlacement.observedAt}, not physically verified · Reason: {device.spec.reportedPlacement.reason} · Evidence: {device.spec.reportedPlacement.reference}} Recordkeeping is not a physical move or a capacity reservation. {device.spec.modelShape @@ -389,10 +383,6 @@ export function PhysicalInventory({ inventory: source, onRetry }: { inventory: I {device.spec.providerHostRef && `${device.spec.providerHostRef.system}/${device.spec.providerHostRef.type}/${device.spec.providerHostRef.id}`} - - {device.spec.identity.sourceIdentity && - `${device.spec.identity.sourceIdentity.system}/${device.spec.identity.sourceIdentity.type}/${device.spec.identity.sourceIdentity.id}`} - )} {claim && ( @@ -594,20 +584,7 @@ export function PhysicalInventory({ inventory: source, onRetry }: { inventory: I Record history & verification
      Unknown — no verification evidence is available. - {provenance.recordedBy} - {provenance.recordedAt} - {provenance.method} - {provenance.reference} - {provenance.source && ( - <> - - {provenance.source.system}/{provenance.source.type}/{provenance.source.id} - - {provenance.source.mappingRevision} - {provenance.source.observedAt} - {provenance.source.snapshotDigest} - - )} + {record.metadata.creationTimestamp}
      @@ -777,7 +754,7 @@ export function PhysicalInventory({ inventory: source, onRetry }: { inventory: I
      About this inventory

      - These are source reports and registration / intent history, not live hardware status. A record does not + These are reported records and registration / intent history, not live hardware status. A record does not establish availability, verified placement, working connections, or permission to operate equipment.

      diff --git a/ui/provider/src/components/pr103-review-negatives.test.tsx b/ui/provider/src/components/pr103-review-negatives.test.tsx index 764118d2..95c17144 100644 --- a/ui/provider/src/components/pr103-review-negatives.test.tsx +++ b/ui/provider/src/components/pr103-review-negatives.test.tsx @@ -12,7 +12,7 @@ it.each([false, true])('does not publish new-principal reads while focus identit let release: (() => void) | undefined; const requests = vi.fn(async (url: string) => { if (url.includes('selfsubjectaccessreviews')) return response({ status: { allowed: true } }); - const record = inventoryPayload('Facility', { name: 'review-facility', namespace: 'default', displayName: `Private ${principal}`, recordedBy: 'synthetic', reference: '', facility: '', height: '' }, '2026-01-01T00:00:00Z'); + const record = inventoryPayload('Facility', { name: 'review-facility', namespace: 'default', displayName: `Private ${principal}`, facility: '', height: '' }); return response({ items: url.includes('/facilities?') ? [record] : [] }); }); vi.stubGlobal('fetch', requests); @@ -38,7 +38,7 @@ it.each(['visible', 'overlap', 'hidden', 'denied'])('renews management only afte let denied = false; const releases: (() => void)[] = []; const visibility = vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('visible'); - const record = inventoryPayload('Facility', { name: 'fresh', namespace: 'default', displayName: 'Synthetic fresh facility', recordedBy: 'synthetic', reference: '', facility: '', height: '' }, '2026-01-01T00:00:00Z'); + const record = inventoryPayload('Facility', { name: 'fresh', namespace: 'default', displayName: 'Synthetic fresh facility', facility: '', height: '' }); vi.stubGlobal('fetch', vi.fn(async (url: string) => { if (url.includes('selfsubjectaccessaccessreviews')) throw new Error('invalid endpoint'); if (url.includes('selfsubjectaccessreviews')) return response({ status: { allowed: true } }); diff --git a/ui/provider/src/components/site-inventory.test.tsx b/ui/provider/src/components/site-inventory.test.tsx index 4d89e413..c60ba154 100644 --- a/ui/provider/src/components/site-inventory.test.tsx +++ b/ui/provider/src/components/site-inventory.test.tsx @@ -6,9 +6,8 @@ import type { PhysicalRecord } from '../../../shared/fleet-api'; import { PhysicalInventory } from './physical-inventory'; import { toInventory, type Inventory } from '../inventory'; -const provenance = { method: 'Manual' as const, recordedBy: 'synthetic', recordedAt: '2026-01-01T00:00:00Z' }; -const facility: PhysicalRecord = { kind: 'Facility', metadata: { name: 'premises-stable', namespace: 'inventory', uid: 'premises-uid' }, spec: { displayName: 'Physical premises', provenance, identifiers: [{ provider: 'example-provider', type: 'PremisesCode', value: 'EX1' }] } }; -const site: PhysicalRecord = { kind: 'Site', metadata: { name: 'site-stable', namespace: 'inventory', uid: 'site-uid' }, spec: { displayName: 'Operational identity', code: 'EX3', provenance, facilityRefs: [{ name: facility.metadata.name }] } }; +const facility: PhysicalRecord = { kind: 'Facility', metadata: { name: 'premises-stable', namespace: 'inventory', uid: 'premises-uid' }, spec: { displayName: 'Physical premises', identifiers: [{ provider: 'example-provider', type: 'PremisesCode', value: 'EX1' }] } }; +const site: PhysicalRecord = { kind: 'Site', metadata: { name: 'site-stable', namespace: 'inventory', uid: 'site-uid' }, spec: { displayName: 'Operational identity', code: 'EX3', facilityRefs: [{ name: facility.metadata.name }] } }; const inventory = toInventory([], [], [facility, site]); function view(query: string, data: Inventory) { diff --git a/ui/provider/src/inventory.test.ts b/ui/provider/src/inventory.test.ts index b938ceab..d5e18093 100644 --- a/ui/provider/src/inventory.test.ts +++ b/ui/provider/src/inventory.test.ts @@ -22,8 +22,7 @@ describe('toInventory', () => { it('does not infer active hardware from the most recently edited record', () => { const replacement = { ...fixtureDevices[0], - metadata: { ...fixtureDevices[0].metadata, name: 'rack-01-u12-synthetic-0002' }, - spec: { ...fixtureDevices[0].spec, provenance: { ...fixtureDevices[0].spec.provenance, recordedAt: '2026-02-01T00:00:00Z' } }, + metadata: { ...fixtureDevices[0].metadata, name: 'rack-01-u12-synthetic-0002', creationTimestamp: '2026-02-01T00:00:00Z' }, }; const inventory = toInventory(fixtureDeviceClaims, [replacement, fixtureDevices[0]]); const u12 = inventory.slots.find((s) => s.claim.metadata.name === 'rack-01-u12')!; diff --git a/ui/provider/src/inventory.ts b/ui/provider/src/inventory.ts index 871b151b..a1f716a0 100644 --- a/ui/provider/src/inventory.ts +++ b/ui/provider/src/inventory.ts @@ -29,8 +29,8 @@ export function slotKey(namespace: string | undefined, name: string): string { return `${namespace ?? ''}/${name}`; } -function byRecordedAt(a: RawDevice, b: RawDevice): number { - return a.spec.provenance.recordedAt.localeCompare(b.spec.provenance.recordedAt); +function byCreationTimestamp(a: RawDevice, b: RawDevice): number { + return (a.metadata.creationTimestamp ?? '').localeCompare(b.metadata.creationTimestamp ?? ''); } export function toInventory(claims: RawDeviceClaim[], devices: RawDevice[], physical: PhysicalRecord[] = []): Inventory { @@ -45,7 +45,7 @@ export function toInventory(claims: RawDeviceClaim[], devices: RawDevice[], phys if (slot) slot.devices.push(device); else unboundDevices.push(device); } - for (const slot of slots.values()) slot.devices.sort(byRecordedAt); + for (const slot of slots.values()) slot.devices.sort(byCreationTimestamp); return { physical, slots: [...slots.values()].sort((a, b) => a.key.localeCompare(b.key)), diff --git a/ui/provider/src/lib/device-placement-edit.test.ts b/ui/provider/src/lib/device-placement-edit.test.ts index 1320984c..c0d32dc5 100644 --- a/ui/provider/src/lib/device-placement-edit.test.ts +++ b/ui/provider/src/lib/device-placement-edit.test.ts @@ -4,7 +4,7 @@ import { fixturePhysicalDevices } from './fixtures'; import { canCorrectPlacement, correctDevicePlacement, placementFields, placementPayload } from './device-placement-edit'; import { InventoryOperationScope } from './inventory-operation'; -const original: Device = { ...fixturePhysicalDevices[0], metadata: { name: 'example', namespace: 'default', uid: 'device-uid', resourceVersion: '7' }, spec: { ...fixturePhysicalDevices[0].spec, provenance: { method: 'NetBoxImport', recordedAt: '2026-01-01T00:00:00Z', recordedBy: 'original-importer', source: { system: 'example', type: 'dcim/devices', id: '1', observedAt: '2026-01-01T00:00:00Z', snapshotDigest: `sha256:${'a'.repeat(64)}`, mappingRevision: 'example' } } } }; +const original: Device = { ...fixturePhysicalDevices[0], metadata: { name: 'example', namespace: 'default', uid: 'device-uid', resourceVersion: '7' } }; const fields = { ...placementFields(), observedAt: '2026-01-02T00:00:00Z', reason: 'Correct location', reference: 'ticket/example' }; const response = (data: unknown, status = 200) => ({ ok: status < 400, status, json: async () => ({ data }) }); const saved = (request: RequestInit) => { @@ -14,21 +14,19 @@ const saved = (request: RequestInit) => { afterEach(() => vi.unstubAllGlobals()); describe('direct placement correction', () => { - it.each([false, true])('adds/updates imported records without altering import provenance: %s', async existing => { + it.each([false, true])('adds/updates the reported location with only UID/resourceVersion preconditions: %s', async existing => { const baseline = structuredClone(original); - if (existing) baseline.spec.reportedPlacement = { revision: 1, observedAt: fields.observedAt, snapshotDigest: `sha256:${'a'.repeat(64)}` }; + if (existing) baseline.spec.reportedPlacement = { revision: 1, observedAt: fields.observedAt, reason: 'Synthetic survey', reference: 'ticket/synthetic' }; const fetch = vi.fn().mockResolvedValueOnce(response({ status: { allowed: true } })).mockResolvedValueOnce(response(baseline)).mockImplementationOnce((_url, request) => saved(request)); vi.stubGlobal('fetch', fetch); await correctDevicePlacement(baseline, fields, new InventoryOperationScope().begin()); const patch = JSON.parse(fetch.mock.calls[2][1].body); expect(patch.slice(0, 2)).toEqual([{ op: 'test', path: '/metadata/uid', value: 'device-uid' }, { op: 'test', path: '/metadata/resourceVersion', value: '7' }]); - expect(patch.map((entry: { path: string }) => entry.path)).toEqual(['/metadata/uid', '/metadata/resourceVersion', '/spec/reportedPlacement', '/spec/provenance/recordedAt']); - expect(patch[2].value).toMatchObject({ method: 'Manual', revision: existing ? 2 : 1 }); - expect(patch[2].value.snapshotDigest).toBeUndefined(); - expect(baseline.spec.provenance).toEqual(original.spec.provenance); + expect(patch.map((entry: { path: string }) => entry.path)).toEqual(['/metadata/uid', '/metadata/resourceVersion', '/spec/reportedPlacement']); + expect(patch[2].value).toMatchObject({ revision: existing ? 2 : 1, reason: fields.reason, reference: fields.reference }); }); it('does not infer geometry or location from a model or claim', () => { - expect(placementPayload(original, fields)).toEqual({ revision: 1, observedAt: fields.observedAt.replace('Z', '.000Z'), method: 'Manual', reason: fields.reason, reference: fields.reference }); + expect(placementPayload(original, fields)).toEqual({ revision: 1, observedAt: fields.observedAt.replace('Z', '.000Z'), reason: fields.reason, reference: fields.reference }); expect(canCorrectPlacement(original)).toBe(true); expect(canCorrectPlacement({ ...original, metadata: { ...original.metadata, managedFields: [{ manager: 'kustomize-controller' }] } })).toBe(false); }); diff --git a/ui/provider/src/lib/device-placement-edit.ts b/ui/provider/src/lib/device-placement-edit.ts index 4f06382a..0ebedd83 100644 --- a/ui/provider/src/lib/device-placement-edit.ts +++ b/ui/provider/src/lib/device-placement-edit.ts @@ -33,8 +33,8 @@ export function placementPayload(original: Device, fields: PlacementFields, now for (const value of [fields.facility, fields.rack]) if (value && (!name.test(value) || value.length > 253)) invalid('Choose a valid location record.'); if (!fields.reason.trim() || !fields.reference.trim() || fields.reason.trim().length > 1024 || fields.reference.trim().length > 1024) invalid('Reason and evidence reference are required (at most 1024 characters).'); const observed = Date.parse(fields.observedAt); - if (!Number.isFinite(observed) || observed > Date.parse(now)) invalid('Observation time must be valid and no later than recording time.'); - const report: ReportedPlacement = { revision: (original.spec.reportedPlacement?.revision ?? 0) + 1, method: 'Manual', observedAt: new Date(observed).toISOString(), reason: fields.reason.trim(), reference: fields.reference.trim() }; + if (!Number.isFinite(observed) || observed > Date.parse(now)) invalid('Observation time must be valid and no later than the current time.'); + const report: ReportedPlacement = { revision: (original.spec.reportedPlacement?.revision ?? 0) + 1, observedAt: new Date(observed).toISOString(), reason: fields.reason.trim(), reference: fields.reference.trim() }; if (fields.facility) report.facilityRef = { name: fields.facility }; if (fields.rack) report.rackRef = { name: fields.rack }; for (const field of ['position', 'height'] as const) { @@ -73,9 +73,7 @@ export async function correctDevicePlacement(original: Device, fields: Placement const current = await readInventoryReference('Device', namespace, original.metadata.name, operation); operation.assertCurrent(); if (current.metadata.uid !== original.metadata.uid || current.metadata.resourceVersion !== original.metadata.resourceVersion || !canCorrectPlacement(current)) throw new ApiError(409, 'The Device changed. Refresh and reopen the form.'); - const now = new Date().toISOString(); - if (Date.parse(now) <= Date.parse(current.spec.provenance.recordedAt)) throw new ApiError(409, 'Recording time must advance.'); - const report = placementPayload(original, fields, now); + const report = placementPayload(original, fields); if (report.facilityRef) { const facility = await readInventoryReference('Facility', namespace, report.facilityRef.name, operation); operation.assertCurrent(); @@ -93,7 +91,6 @@ export async function correctDevicePlacement(original: Device, fields: Placement { op: 'test', path: '/metadata/uid', value: original.metadata.uid }, { op: 'test', path: '/metadata/resourceVersion', value: original.metadata.resourceVersion }, { op: 'add', path: '/spec/reportedPlacement', value: report }, - { op: 'replace', path: '/spec/provenance/recordedAt', value: now }, ]; operation.dispatch(); const saved = await proxyFetch(PROVIDER_PROJECT, path, { method: 'PATCH', contentType: 'application/json-patch+json', body: patch }).catch(error => { diff --git a/ui/provider/src/lib/device-placement.test.ts b/ui/provider/src/lib/device-placement.test.ts index eaa8f0e4..eb998693 100644 --- a/ui/provider/src/lib/device-placement.test.ts +++ b/ui/provider/src/lib/device-placement.test.ts @@ -4,7 +4,7 @@ import { fixturePhysicalClaims, fixturePhysicalDevices, fixturePhysicalRecords } import { devicePlacement, equipmentGeometry, equipmentPlacements, placementFacility, reportedPlacementLabel } from './device-placement'; import type { ReportedPlacement } from '../../../shared/fleet-api'; -const report: ReportedPlacement = { revision: 1, observedAt: '2026-11-21T00:00:00Z', snapshotDigest: `sha256:${'a'.repeat(64)}`, rackRef: { name: 'rack-01' }, position: 12, height: 4, face: 'rear', fullDepth: true }; +const report: ReportedPlacement = { revision: 1, observedAt: '2026-11-21T00:00:00Z', reason: 'Synthetic survey', reference: 'ticket/synthetic', rackRef: { name: 'rack-01' }, position: 12, height: 4, face: 'rear', fullDepth: true }; const device = { ...fixturePhysicalDevices[0], spec: { ...fixturePhysicalDevices[0].spec, reportedPlacement: report } }; const inventory = toInventory(fixturePhysicalClaims, [device], fixturePhysicalRecords); diff --git a/ui/provider/src/lib/fixtures.ts b/ui/provider/src/lib/fixtures.ts index ff10fe5b..65fa4ed9 100644 --- a/ui/provider/src/lib/fixtures.ts +++ b/ui/provider/src/lib/fixtures.ts @@ -164,9 +164,8 @@ const INVENTORY_NAMESPACE = 'default'; function claim(name: string, position: number): RawDeviceClaim { return { - metadata: { name, namespace: INVENTORY_NAMESPACE }, + metadata: { name, namespace: INVENTORY_NAMESPACE, creationTimestamp: '2026-01-02T03:04:05Z' }, spec: { - provenance: { method: 'Manual', recordedBy: 'planner@example.com', recordedAt: '2026-01-02T03:04:05Z', reference: 'rack plan 1234' }, expectedIdentity: { manufacturer: 'Example Vendor', model: 'Example 1U' }, placement: { facility: 'example-facility', rack: 'rack-01', position, height: 1, face: 'front' }, ports: [ @@ -181,33 +180,29 @@ export const fixtureDeviceClaims: RawDeviceClaim[] = [claim('rack-01-u12', 12), export const fixtureDevices: RawDevice[] = [ { - metadata: { name: 'rack-01-u12-synthetic-0001', namespace: INVENTORY_NAMESPACE }, + metadata: { name: 'rack-01-u12-synthetic-0001', namespace: INVENTORY_NAMESPACE, creationTimestamp: '2026-01-09T10:00:00Z' }, spec: { claimRef: { name: 'rack-01-u12' }, - provenance: { method: 'Manual', recordedBy: 'registrar@example.com', recordedAt: '2026-01-09T10:00:00Z', reference: 'BMC inventory read during rack turn-up' }, identity: { manufacturer: 'Example Vendor', model: 'Example 1U', serial: 'SYNTHETIC-0001', systemUUID: '00000000-0000-4000-8000-000000000001' }, bmc: { endpoint: 'https://192.0.2.100:443' }, unmappedMACAddresses: ['00:00:5e:00:53:01', '00:00:5e:00:53:02'], }, }, { - metadata: { name: 'orphan-synthetic-0009', namespace: INVENTORY_NAMESPACE }, + metadata: { name: 'orphan-synthetic-0009', namespace: INVENTORY_NAMESPACE, creationTimestamp: '2026-01-10T10:00:00Z' }, spec: { claimRef: { name: 'rack-02-u01' }, - provenance: { method: 'Manual', recordedBy: 'registrar@example.com', recordedAt: '2026-01-10T10:00:00Z' }, identity: { model: 'Example 2U', systemUUID: '00000000-0000-4000-8000-000000000009' }, }, }, ]; -const inventoryProvenance = { method: 'Manual' as const, recordedBy: 'inventory@example.com', recordedAt: '2026-01-10T10:00:00Z' }; - export const fixturePhysicalRecords: PhysicalRecord[] = [ - { kind: 'Facility', metadata: { name: 'example-facility', namespace: INVENTORY_NAMESPACE, uid: 'synthetic-facility-uid' }, spec: { displayName: 'Example facility', provenance: inventoryProvenance, locationRef: { name: 'example-region' }, identifiers: [{ provider: 'example-provider', type: 'PremisesCode', value: 'EX1' }] } }, - { kind: 'Rack', metadata: { name: 'rack-01', namespace: INVENTORY_NAMESPACE }, spec: { displayName: 'Rack 01', provenance: inventoryProvenance, facilityRef: { name: 'example-facility' }, heightUnits: 42 } }, - { kind: 'PowerFeed', metadata: { name: 'feed-a', namespace: INVENTORY_NAMESPACE }, spec: { displayName: 'Feed A', provenance: inventoryProvenance, facilityRef: { name: 'example-facility' }, rackRef: { name: 'rack-01' }, supply: { type: 'AC', voltageV: 208, currentA: 30, phase: 'Single' }, terminations: [{ id: 'outlet-1', name: 'Outlet 1', type: 'PowerOutlet', connector: 'IEC C13', positions: 1 }], upstreamSources: [{ system: 'example-provider', type: 'Supply', id: 'synthetic-supply-a' }] } }, - { kind: 'Cable', metadata: { name: 'power-01', namespace: INVENTORY_NAMESPACE }, spec: { displayName: 'Server power cable', provenance: inventoryProvenance, medium: 'Power', lanes: [{ id: 'power', a: { powerFeedRef: { name: 'feed-a' }, componentID: 'outlet-1', position: 1 }, b: { deviceRef: { name: 'rack-01-u12-synthetic-0001' }, componentID: 'psu-1', position: 1 } }] } }, - { kind: 'Site', metadata: { name: 'example-site', namespace: INVENTORY_NAMESPACE, uid: 'synthetic-site-uid' }, spec: { displayName: 'Example operational site', code: 'EX3', provenance: inventoryProvenance, facilityRefs: [{ name: 'example-facility' }] } }, + { kind: 'Facility', metadata: { name: 'example-facility', namespace: INVENTORY_NAMESPACE, uid: 'synthetic-facility-uid' }, spec: { displayName: 'Example facility', locationRef: { name: 'example-region' }, identifiers: [{ provider: 'example-provider', type: 'PremisesCode', value: 'EX1' }] } }, + { kind: 'Rack', metadata: { name: 'rack-01', namespace: INVENTORY_NAMESPACE }, spec: { displayName: 'Rack 01', facilityRef: { name: 'example-facility' }, heightUnits: 42 } }, + { kind: 'PowerFeed', metadata: { name: 'feed-a', namespace: INVENTORY_NAMESPACE }, spec: { displayName: 'Feed A', facilityRef: { name: 'example-facility' }, rackRef: { name: 'rack-01' }, supply: { type: 'AC', voltageV: 208, currentA: 30, phase: 'Single' }, terminations: [{ id: 'outlet-1', name: 'Outlet 1', type: 'PowerOutlet', connector: 'IEC C13', positions: 1 }], upstreamSources: [{ system: 'example-provider', type: 'Supply', id: 'synthetic-supply-a' }] } }, + { kind: 'Cable', metadata: { name: 'power-01', namespace: INVENTORY_NAMESPACE }, spec: { displayName: 'Server power cable', medium: 'Power', lanes: [{ id: 'power', a: { powerFeedRef: { name: 'feed-a' }, componentID: 'outlet-1', position: 1 }, b: { deviceRef: { name: 'rack-01-u12-synthetic-0001' }, componentID: 'psu-1', position: 1 } }] } }, + { kind: 'Site', metadata: { name: 'example-site', namespace: INVENTORY_NAMESPACE, uid: 'synthetic-site-uid' }, spec: { displayName: 'Example operational site', code: 'EX3', facilityRefs: [{ name: 'example-facility' }] } }, ]; export const fixturePhysicalClaims: RawDeviceClaim[] = fixtureDeviceClaims.map(record => ({ ...record, spec: { ...record.spec, displayName: `Server installation · U${record.spec.placement.position}`, placement: { scope: 'RackUnits', rackRef: { name: 'rack-01' }, position: record.spec.placement.position, height: 1, face: 'front' } } })); diff --git a/ui/provider/src/lib/inventory-hardware.test.ts b/ui/provider/src/lib/inventory-hardware.test.ts index 980756ab..b75a8e9a 100644 --- a/ui/provider/src/lib/inventory-hardware.test.ts +++ b/ui/provider/src/lib/inventory-hardware.test.ts @@ -4,11 +4,11 @@ import { createInventoryRecord, editInventoryLabel, INVENTORY_FIELD_MANAGER, inv import { hardwarePayload, type ReferencedEndpoint } from './inventory-hardware'; import { InventoryOperationScope } from './inventory-operation'; -const values: InventoryFormValues = { name: 'synthetic', namespace: 'default', displayName: 'Synthetic hardware', recordedBy: 'operator', reference: '', height: '', facility: '', model: 'Example', serial: 'SYNTHETIC-1', claim: { name: 'plan', uid: 'plan-uid', resourceVersion: '1' }, components: [{ id: 'port', name: 'Port', type: 'NetworkPort', positions: 1 }] }; +const values: InventoryFormValues = { name: 'synthetic', namespace: 'default', displayName: 'Synthetic hardware', height: '', facility: '', model: 'Example', serial: 'SYNTHETIC-1', claim: { name: 'plan', uid: 'plan-uid', resourceVersion: '1' }, components: [{ id: 'port', name: 'Port', type: 'NetworkPort', positions: 1 }] }; const endpoint: ReferencedEndpoint = { kind: 'Device', name: 'synthetic-device', uid: 'device-uid', resourceVersion: '1', componentID: 'port', position: 1 }; const cableValues: InventoryFormValues = { ...values, medium: 'Copper', cableLanes: [{ id: 'lane-1', a: endpoint, b: { ...endpoint, name: 'other', uid: 'other-uid' } }] }; const planValues: InventoryFormValues = { ...values, planLocation: { kind: 'Rack', name: 'rack', uid: 'rack-uid', resourceVersion: '1' } }; -const common = inventoryPayload('Facility', values, '2026-01-01T00:00:00Z'); +const common = inventoryPayload('Facility', values); const claim = { metadata: { name: 'plan', uid: 'plan-uid', resourceVersion: '1' }, spec: { lifecycle: 'Installation' } }; const device = { ...hardwarePayload('Device', values, common), metadata: { name: 'synthetic-device', namespace: 'default', uid: 'device-uid', resourceVersion: '1', managedFields: [{ manager: INVENTORY_FIELD_MANAGER }] } }; const response = (data: unknown, status = 200) => ({ ok: status < 400, status, json: async () => ({ data }) }); @@ -34,7 +34,7 @@ describe('physical record creation', () => { expect(body.spec.claimRef).toEqual({ name: 'plan' }); expect(body.spec.identity).toEqual({ model: 'Example', serial: 'SYNTHETIC-1' }); expect(body.spec.components[0].type).toBe('NetworkPort'); - expect(Object.keys(body.spec).sort()).toEqual(['claimRef', 'components', 'displayName', 'identity', 'provenance', 'topologyAuthority'].sort()); + expect(Object.keys(body.spec).sort()).toEqual(['claimRef', 'components', 'displayName', 'identity', 'topologyAuthority'].sort()); expect(body.status).toBeUndefined(); }); it.each([{ serial: '', systemUUID: '' }, { model: '' }, { systemUUID: 'invented' }, { components: [{ id: 'a', name: 'A', type: 'NetworkPort', positions: 0 }] }, { components: [values.components![0], values.components![0]] }])('rejects incomplete or invalid hardware: %j', invalid => { @@ -85,10 +85,10 @@ describe('physical record creation', () => { expect(requests).toHaveBeenCalledTimes(2); } }); - it('limits device edits to labels/provenance, preserving identity and components', async () => { + it('limits device edits to the display name, preserving identity and components', async () => { const requests = vi.fn().mockResolvedValueOnce(response({ status: { allowed: true } })).mockResolvedValueOnce(response(device)).mockResolvedValueOnce(response(device)); vi.stubGlobal('fetch', requests); await editInventoryLabel(device, values, new InventoryOperationScope().begin()); - expect(JSON.parse(requests.mock.calls[2][1].body).map((operation: { path: string }) => operation.path)).toEqual(['/metadata/uid', '/metadata/resourceVersion', '/spec/displayName', '/spec/provenance']); + expect(JSON.parse(requests.mock.calls[2][1].body).map((operation: { path: string }) => operation.path)).toEqual(['/metadata/uid', '/metadata/resourceVersion', '/spec/displayName']); }); }); diff --git a/ui/provider/src/lib/inventory-hardware.ts b/ui/provider/src/lib/inventory-hardware.ts index 97232a4d..4d094997 100644 --- a/ui/provider/src/lib/inventory-hardware.ts +++ b/ui/provider/src/lib/inventory-hardware.ts @@ -34,7 +34,7 @@ export function hardwarePayload(kind: 'Device' | 'Cable' | 'DeviceClaim', values if (kind === 'DeviceClaim') { const location = values.planLocation; if (!location?.uid || !location.resourceVersion || !['Facility', 'Rack'].includes(location.kind) || !namePattern.test(location.name) || !values.model?.trim() || [values.model, values.manufacturer, values.serial].some(value => (value?.length ?? 0) > 253)) throw new ApiError(422, 'Choose a recorded location and an expected hardware model.'); - return { ...common, kind, spec: { displayName: values.displayName.trim(), provenance: common.spec.provenance, lifecycle: 'Installation', expectedIdentity: { model: values.model.trim(), ...(values.manufacturer?.trim() && { manufacturer: values.manufacturer.trim() }), ...(values.serial?.trim() && { serial: values.serial.trim() }) }, placement: location.kind === 'Facility' ? { scope: 'Facility', facilityRef: { name: location.name } } : { scope: 'RackMembership', rackRef: { name: location.name } } } }; + return { ...common, kind, spec: { displayName: values.displayName.trim(), lifecycle: 'Installation', expectedIdentity: { model: values.model.trim(), ...(values.manufacturer?.trim() && { manufacturer: values.manufacturer.trim() }), ...(values.serial?.trim() && { serial: values.serial.trim() }) }, placement: location.kind === 'Facility' ? { scope: 'Facility', facilityRef: { name: location.name } } : { scope: 'RackMembership', rackRef: { name: location.name } } } }; } if (kind === 'Device') { if (!values.claim?.uid || !values.claim.resourceVersion || !namePattern.test(values.claim.name) || !values.model?.trim() || (!values.serial?.trim() && !values.systemUUID)) throw new ApiError(422, 'Choose an installation plan and enter a model and a serial or system UUID.'); @@ -42,7 +42,7 @@ export function hardwarePayload(kind: 'Device' | 'Cable' | 'DeviceClaim', values if ([values.manufacturer, values.model, values.serial, values.assetTag].some(value => (value?.length ?? 0) > 253)) throw new ApiError(422, 'Hardware fields must be at most 253 characters.'); const components = values.components ?? []; if (components.length > 256 || new Set(components.map(component => component.id)).size !== components.length || components.some(component => !component.id.trim() || component.id.length > 63 || !component.name.trim() || component.name.length > 253 || !componentTypes.includes(component.type) || (component.connector?.length ?? 0) > 253 || !Number.isInteger(component.positions) || component.positions! < 1 || component.positions! > 256)) throw new ApiError(422, 'Review component IDs, names, types, and positions.'); - return { ...common, kind, spec: { displayName: values.displayName.trim(), provenance: common.spec.provenance, claimRef: { name: values.claim.name }, identity: { model: values.model.trim(), ...(values.manufacturer?.trim() && { manufacturer: values.manufacturer.trim() }), ...(values.serial?.trim() && { serial: values.serial.trim() }), ...(values.systemUUID && { systemUUID: values.systemUUID }) }, ...(values.assetTag?.trim() && { assetTag: values.assetTag.trim() }), topologyAuthority: 'Cable', components } }; + return { ...common, kind, spec: { displayName: values.displayName.trim(), claimRef: { name: values.claim.name }, identity: { model: values.model.trim(), ...(values.manufacturer?.trim() && { manufacturer: values.manufacturer.trim() }), ...(values.serial?.trim() && { serial: values.serial.trim() }), ...(values.systemUUID && { systemUUID: values.systemUUID }) }, ...(values.assetTag?.trim() && { assetTag: values.assetTag.trim() }), topologyAuthority: 'Cable', components } }; } const lanes = values.cableLanes ?? []; if (!cableMedia.includes(values.medium ?? '') || !lanes.length || lanes.length > 64 || new Set(lanes.map(lane => lane.id)).size !== lanes.length) throw new ApiError(422, 'Choose a medium and one or more uniquely named lanes.'); diff --git a/ui/provider/src/lib/inventory-management.test.ts b/ui/provider/src/lib/inventory-management.test.ts index eb63c180..8f8fa3c0 100644 --- a/ui/provider/src/lib/inventory-management.test.ts +++ b/ui/provider/src/lib/inventory-management.test.ts @@ -3,8 +3,8 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; import { canEditInventoryLabel, createInventoryRecord, editInventoryLabel, inventoryPayload, inventoryPermission, INVENTORY_FIELD_MANAGER, type InventoryFormValues } from './inventory-management'; import type { PhysicalRecord } from '../../../shared/fleet-api'; -const values: InventoryFormValues = { name: 'example-facility', namespace: 'default', displayName: 'Example facility', recordedBy: 'operator@example.com', reference: 'Example review', facility: '', height: '' }; -const owned: PhysicalRecord = { ...inventoryPayload('Facility', values, '2026-01-01T00:00:00Z'), metadata: { name: values.name, namespace: values.namespace, uid: 'synthetic-uid', resourceVersion: '1', managedFields: [{ manager: INVENTORY_FIELD_MANAGER }] } }; +const values: InventoryFormValues = { name: 'example-facility', namespace: 'default', displayName: 'Example facility', facility: '', height: '' }; +const owned: PhysicalRecord = { ...inventoryPayload('Facility', values), metadata: { name: values.name, namespace: values.namespace, uid: 'synthetic-uid', resourceVersion: '1', managedFields: [{ manager: INVENTORY_FIELD_MANAGER }] } }; const response = (data: unknown, status = 200) => ({ ok: status >= 200 && status < 300, status, json: async () => ({ data }) }); afterEach(() => vi.unstubAllGlobals()); @@ -38,7 +38,7 @@ describe('inventory management authority', () => { expect(init.method).toBe('POST'); const payload = JSON.parse(init.body); expect(payload.status).toBeUndefined(); - expect(payload.spec.provenance.method).toBe('Manual'); + expect(Object.keys(payload.spec)).toEqual(['displayName']); expect(payload.metadata).toEqual({ name: values.name, namespace: 'default' }); }); @@ -47,20 +47,19 @@ describe('inventory management authority', () => { for (const height of ['0', '101', '1.5', '-2']) expect(() => inventoryPayload('Rack', { ...values, facility: 'example-facility', height })).toThrow(); }); - it('rejects Flux-owned, imported, deleting and unknown-writer records', () => { + it('rejects Flux-owned, deleting and unknown-writer records', () => { expect(canEditInventoryLabel(owned)).toBe(true); for (const metadata of [{ ...owned.metadata, managedFields: undefined }, { ...owned.metadata, managedFields: [{ manager: 'kustomize-controller' }] }, { ...owned.metadata, deletionTimestamp: '2026-01-01T00:00:00Z' }, { ...owned.metadata, labels: { 'kustomize.toolkit.fluxcd.io/name': 'inventory' } }]) expect(canEditInventoryLabel({ ...owned, metadata })).toBe(false); - expect(canEditInventoryLabel({ ...owned, spec: { ...owned.spec, provenance: { ...owned.spec.provenance, method: 'NetBoxImport' } } })).toBe(false); }); - it('edits only a display name and provenance with UID and revision preconditions', async () => { + it('edits only a display name with UID and revision preconditions', async () => { const fetch = vi.fn().mockResolvedValueOnce(response({ status: { allowed: true } })).mockResolvedValueOnce(response(owned)).mockResolvedValueOnce(response(owned)); vi.stubGlobal('fetch', fetch); await editInventoryLabel(owned, { ...values, displayName: 'New name' }, new InventoryOperationScope().begin()); const init = fetch.mock.calls[2][1]; expect(init.method).toBe('PATCH'); expect(init.headers['Content-Type']).toBe('application/json-patch+json'); - expect(JSON.parse(init.body).map((operation: { path: string }) => operation.path)).toEqual(['/metadata/uid', '/metadata/resourceVersion', '/spec/displayName', '/spec/provenance']); + expect(JSON.parse(init.body).map((operation: { path: string }) => operation.path)).toEqual(['/metadata/uid', '/metadata/resourceVersion', '/spec/displayName']); }); it('does not patch after ownership or revision changes', async () => { diff --git a/ui/provider/src/lib/inventory-management.ts b/ui/provider/src/lib/inventory-management.ts index 5883731d..8729f95e 100644 --- a/ui/provider/src/lib/inventory-management.ts +++ b/ui/provider/src/lib/inventory-management.ts @@ -29,7 +29,7 @@ export function useInventoryPermission(kind: ManagedKind, namespace: string, ver export function canEditInventoryLabel(record: ManagedRecord): boolean { const { metadata, spec } = record; - return ['Facility', 'Rack', 'Device', 'Cable'].includes(record.kind ?? '') && !!metadata.uid && !!metadata.resourceVersion && !metadata.deletionTimestamp && !spec.provenance.source && spec.provenance.method === 'Manual' && + return ['Facility', 'Rack', 'Device', 'Cable'].includes(record.kind ?? '') && !!metadata.uid && !!metadata.resourceVersion && !metadata.deletionTimestamp && !Object.keys({ ...metadata.labels, ...metadata.annotations }).some(key => /fluxcd\.io|argocd|inventory.*owner/i.test(key)) && !!metadata.managedFields?.length && metadata.managedFields.every(field => field.manager === INVENTORY_FIELD_MANAGER && !field.subresource); } @@ -38,21 +38,18 @@ export interface InventoryFormValues extends HardwareFields { name: string; namespace: string; displayName: string; - recordedBy: string; - reference: string; facility: string; height: string; } -export function inventoryPayload(kind: 'Facility' | 'Rack', values: InventoryFormValues, now = new Date().toISOString()): PhysicalRecord & { apiVersion: string } { +export function inventoryPayload(kind: 'Facility' | 'Rack', values: InventoryFormValues): PhysicalRecord & { apiVersion: string } { const resourceName = /^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$/; if (!resourceName.test(values.name) || values.name.length > 253 || !/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(values.namespace) || values.namespace.length > 63) throw new ApiError(422, 'Enter a valid record name and namespace.'); - if (!values.displayName.trim() || values.displayName.trim().length > 253 || !values.recordedBy.trim() || values.recordedBy.trim().length > 253) throw new ApiError(422, 'Display name and recorder are required (at most 253 characters each).'); - if (values.reference.trim().length > 1024) throw new ApiError(422, 'The change reference is too long.'); + if (!values.displayName.trim() || values.displayName.trim().length > 253) throw new ApiError(422, 'A display name is required (at most 253 characters).'); if (kind === 'Rack' && !resourceName.test(values.facility)) throw new ApiError(422, 'Choose a facility in this namespace.'); if (kind === 'Rack' && values.height && (!/^\d+$/.test(values.height) || Number(values.height) < 1 || Number(values.height) > 100)) throw new ApiError(422, 'Rack height must be a whole number from 1 to 100, or left blank when unknown.'); return { apiVersion: 'fleet.datumapis.com/v1alpha1', kind, metadata: { name: values.name, namespace: values.namespace }, spec: { - displayName: values.displayName.trim(), provenance: { method: 'Manual', recordedBy: values.recordedBy.trim(), recordedAt: now, ...(values.reference.trim() && { reference: values.reference.trim() }) }, + displayName: values.displayName.trim(), ...(kind === 'Rack' && { facilityRef: { name: values.facility }, ...(values.height && { heightUnits: Number(values.height) }) }), } }; } @@ -92,15 +89,12 @@ export async function editInventoryLabel(original: ManagedRecord, values: Invent const current = await readInventoryReference(kind, namespace, original.metadata.name, operation); operation.assertCurrent(); if (!current || current.metadata.uid !== original.metadata.uid || current.metadata.resourceVersion !== original.metadata.resourceVersion || !canEditInventoryLabel(current)) throw new ApiError(409, 'The record or its ownership changed. Reload it before editing.'); - const now = new Date().toISOString(); - if (now <= current.spec.provenance.recordedAt) throw new ApiError(409, 'The recorded timestamp is not earlier than this clock. Review the record before editing.'); - const validated = inventoryPayload('Facility', { ...values, name: original.metadata.name, namespace }, now); + const validated = inventoryPayload('Facility', { ...values, name: original.metadata.name, namespace }); operation.dispatch(); const record = await proxyFetch(PROVIDER_PROJECT, `${path}?fieldManager=${INVENTORY_FIELD_MANAGER}`, { method: 'PATCH', contentType: 'application/json-patch+json', body: [ { op: 'test', path: '/metadata/uid', value: current.metadata.uid }, { op: 'test', path: '/metadata/resourceVersion', value: current.metadata.resourceVersion }, { op: current.spec.displayName === undefined ? 'add' : 'replace', path: '/spec/displayName', value: validated.spec.displayName }, - { op: 'replace', path: '/spec/provenance', value: validated.spec.provenance }, ] }).catch(error => { operation.assertCurrent(); throw error; }); operation.assertCurrent(); if (!record?.metadata?.uid) throw new Error('Save outcome could not be confirmed.'); diff --git a/ui/provider/src/lib/inventory-operation.test.ts b/ui/provider/src/lib/inventory-operation.test.ts index adc2dd6b..7d04fcd8 100644 --- a/ui/provider/src/lib/inventory-operation.test.ts +++ b/ui/provider/src/lib/inventory-operation.test.ts @@ -3,8 +3,8 @@ import { waitFor } from '@testing-library/react'; import { createInventoryRecord, editInventoryLabel, inventoryPayload, INVENTORY_FIELD_MANAGER } from './inventory-management'; import { InventoryOperationInvalidated, InventoryOperationScope } from './inventory-operation'; -const values = { name: 'synthetic-facility', namespace: 'default', displayName: 'Original', recordedBy: 'synthetic-operator', reference: '', facility: 'parent', height: '' }; -const original = { ...inventoryPayload('Facility', values, '2026-01-01T00:00:00Z'), metadata: { name: values.name, namespace: values.namespace, uid: 'synthetic-uid', resourceVersion: '1', managedFields: [{ manager: INVENTORY_FIELD_MANAGER }] } }; +const values = { name: 'synthetic-facility', namespace: 'default', displayName: 'Original', facility: 'parent', height: '' }; +const original = { ...inventoryPayload('Facility', values), metadata: { name: values.name, namespace: values.namespace, uid: 'synthetic-uid', resourceVersion: '1', managedFields: [{ manager: INVENTORY_FIELD_MANAGER }] } }; const response = (data: unknown, status = 200) => ({ ok: status < 400, status, json: async () => ({ data }) }); afterEach(() => vi.unstubAllGlobals()); diff --git a/ui/provider/src/lib/site-membership.test.ts b/ui/provider/src/lib/site-membership.test.ts index a88ef12a..a3ed7104 100644 --- a/ui/provider/src/lib/site-membership.test.ts +++ b/ui/provider/src/lib/site-membership.test.ts @@ -4,9 +4,8 @@ import { toInventory } from '../inventory'; import { redactInventory } from './inventory-read-access'; import { facilityIdentifiers, facilitySites, siteFacilities } from './site-membership'; -const provenance = { method: 'Manual' as const, recordedBy: 'synthetic', recordedAt: '2026-01-01T00:00:00Z' }; -const facility: PhysicalRecord = { kind: 'Facility', metadata: { name: 'premises-stable', namespace: 'inventory', uid: 'premises-uid' }, spec: { displayName: 'Physical premises', provenance, identifiers: [{ provider: 'example-a', type: 'PremisesCode', value: 'EX1' }, { provider: 'example-b', type: 'PremisesCode', value: 'EX1' }] } }; -const site: PhysicalRecord = { kind: 'Site', metadata: { name: 'site-stable', namespace: 'inventory', uid: 'site-uid' }, spec: { displayName: 'Operational identity', code: 'EX3', provenance, facilityRefs: [{ name: facility.metadata.name }] } }; +const facility: PhysicalRecord = { kind: 'Facility', metadata: { name: 'premises-stable', namespace: 'inventory', uid: 'premises-uid' }, spec: { displayName: 'Physical premises', identifiers: [{ provider: 'example-a', type: 'PremisesCode', value: 'EX1' }, { provider: 'example-b', type: 'PremisesCode', value: 'EX1' }] } }; +const site: PhysicalRecord = { kind: 'Site', metadata: { name: 'site-stable', namespace: 'inventory', uid: 'site-uid' }, spec: { displayName: 'Operational identity', code: 'EX3', facilityRefs: [{ name: facility.metadata.name }] } }; describe('observational Site membership', () => { it('keeps legacy Facilities explicitly unmapped and provider codes qualified', () => { diff --git a/ui/provider/src/pages/device-claim-detail.tsx b/ui/provider/src/pages/device-claim-detail.tsx index efbe5fe4..c9d9ed9a 100644 --- a/ui/provider/src/pages/device-claim-detail.tsx +++ b/ui/provider/src/pages/device-claim-detail.tsx @@ -6,7 +6,7 @@ import { StatusBadge } from '../components/status-badge'; import { useInventory } from '../lib/api'; import { currentDevice, endpointLabel, legacyPeerLabel, modelLabel, placementLabel, slotKey, type Inventory, type RawDevice } from '../inventory'; import { devicePlacement, reportedPlacementLabel } from '../lib/device-placement'; -import type { Provenance } from '../../../shared/fleet-api'; +import type { ObjectMeta } from '../../../shared/fleet-api'; import { Card, CardContent } from '@datum-cloud/datum-ui/card'; import { Text } from '@datum-cloud/datum-ui/typography'; import type { ReactNode } from 'react'; @@ -32,20 +32,8 @@ function Section({ title, testId, children }: { title: string; testId: string; c ); } -function ProvenanceFields({ provenance }: { provenance: Provenance }) { - return ( -

      - {provenance.recordedBy} - {provenance.recordedAt} - {provenance.method} - {provenance.source && {provenance.source.system}/{provenance.source.type}/{provenance.source.id} · mapping {provenance.source.mappingRevision} · observed {provenance.source.observedAt} · verification Unknown} - {provenance.reference && ( -
      - {provenance.reference} -
      - )} -
      - ); +function CreatedField({ metadata }: { metadata: ObjectMeta }) { + return {metadata.creationTimestamp ?? 'Not recorded'}; } function DeviceSection({ device, current, inventory }: { device: RawDevice; current: boolean; inventory: Inventory }) { @@ -88,7 +76,7 @@ function DeviceSection({ device, current, inventory }: { device: RawDevice; curr unmappedMACAddresses.map((mac) => {mac}) )}
    - +
    ); } @@ -144,7 +132,7 @@ function ClaimDetailContent() { ))}
)} - +
{data?.issues?.Device && } {(!data?.issues?.Device ? [...slot.devices].reverse() : []).map((device) => ( diff --git a/ui/provider/src/pages/device-inventory.test.tsx b/ui/provider/src/pages/device-inventory.test.tsx index 57bed228..351cdd8f 100644 --- a/ui/provider/src/pages/device-inventory.test.tsx +++ b/ui/provider/src/pages/device-inventory.test.tsx @@ -120,15 +120,15 @@ describe('DeviceClaimDetail', () => { expect(screen.queryByTestId('fleet-plugin-claim')).not.toBeInTheDocument(); }); - it('shows placement, ports, binding, identity, BMC endpoint, unmapped MACs and provenance', () => { + it('shows placement, ports, binding, identity, BMC endpoint, unmapped MACs and created time', () => { mockInventory({ data: inventory }); renderAt('/plugins/metal-datumapis-com/inventory/default/rack-01-u12'); const claim = screen.getByTestId('fleet-plugin-claim'); expect(within(claim).getByText('example-facility · rack-01 · U12 front')).toBeInTheDocument(); expect(within(claim).getByText(/eth0 \(25gbase-x-sfp28, 25000 Mb\/s\) → switch-01 Ethernet1\/12/)).toBeInTheDocument(); - expect(within(claim).getByText('planner@example.com')).toBeInTheDocument(); + expect(within(claim).getByText('2026-01-02T03:04:05Z')).toBeInTheDocument(); const device = screen.getByTestId('fleet-plugin-device-rack-01-u12-synthetic-0001'); - for (const text of ['SYNTHETIC-0001', '00000000-0000-4000-8000-000000000001', 'https://192.0.2.100:443', 'rack-01-u12', 'registrar@example.com', 'BMC inventory read during rack turn-up']) { + for (const text of ['SYNTHETIC-0001', '00000000-0000-4000-8000-000000000001', 'https://192.0.2.100:443', 'rack-01-u12', '2026-01-09T10:00:00Z']) { expect(within(device).getByText(text)).toBeInTheDocument(); } const macs = within(device).getByTestId('fleet-plugin-unmapped-macs'); @@ -151,8 +151,7 @@ describe('DeviceClaimDetail', () => { it('preserves history without guessing an active replacement', () => { const replacement = { ...fixtureDevices[0], - metadata: { ...fixtureDevices[0].metadata, name: 'rack-01-u12-synthetic-0002' }, - spec: { ...fixtureDevices[0].spec, provenance: { ...fixtureDevices[0].spec.provenance, recordedAt: '2026-02-01T00:00:00Z' } }, + metadata: { ...fixtureDevices[0].metadata, name: 'rack-01-u12-synthetic-0002', creationTimestamp: '2026-02-01T00:00:00Z' }, }; mockInventory({ data: toInventory(fixtureDeviceClaims, [fixtureDevices[0], replacement]) }); renderAt('/plugins/metal-datumapis-com/inventory/default/rack-01-u12'); diff --git a/ui/shared/fleet-api.ts b/ui/shared/fleet-api.ts index 725f3a58..9d4aaaec 100644 --- a/ui/shared/fleet-api.ts +++ b/ui/shared/fleet-api.ts @@ -237,14 +237,6 @@ export const MACHINE_FINALIZER = 'fleet.datumapis.com/machine-protection'; export const INVENTORY_API_GROUP = 'fleet.datumapis.com'; export const INVENTORY_API_VERSION = 'v1alpha1'; -export interface Provenance { - method: 'Manual' | 'NetBoxImport'; - recordedBy: string; - recordedAt: string; - reference?: string; - source?: ExternalReference & { snapshotDigest: string; mappingRevision: string; observedAt: string }; -} - export interface PortPeer { device: string; port: string; @@ -255,7 +247,6 @@ export interface DeviceClaim { kind?: string; metadata: ObjectMeta; spec: { - provenance: Provenance; expectedIdentity: { manufacturer?: string; model: string; serial?: string }; lifecycle?: 'Installation'; displayName?: string; @@ -272,8 +263,7 @@ export interface Device { spec: { reportedPlacement?: ReportedPlacement; claimRef: LocalReference; - provenance: Provenance; - identity: { manufacturer?: string; model: string; serial?: string; systemUUID?: string; sourceIdentity?: ExternalReference }; + identity: { manufacturer?: string; model: string; serial?: string; systemUUID?: string }; assetTag?: string; displayName?: string; modelShape?: { heightUnits?: number; fullDepth?: boolean }; @@ -291,10 +281,8 @@ export interface Device { export interface ReportedPlacement { revision: number; observedAt: string; - snapshotDigest?: string; - method?: 'Manual' | 'NetBoxImport'; - reason?: string; - reference?: string; + reason: string; + reference: string; facilityRef?: LocalReference; rackRef?: LocalReference; position?: number; @@ -314,7 +302,6 @@ export interface PhysicalComponent { positions?: number; serial?: string; assetTag?: string; - sourceRef?: ExternalReference; } export interface CableEndpoint extends ComponentPosition { deviceRef?: LocalReference; @@ -325,7 +312,6 @@ export interface PhysicalRecord { kind: 'Site' | 'Facility' | 'Rack' | 'Cable' | 'PowerFeed'; spec: { displayName: string; - provenance: Provenance; code?: string; facilityRefs?: LocalReference[]; identifiers?: { provider: string; type: 'PremisesCode' | 'PremisesAlias' | 'PremisesID'; value: string }[]; From 677a5f8210a49a9fa567c4f84b370f6c177aa892 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sat, 21 Nov 2026 18:36:23 -0600 Subject: [PATCH 048/518] fix(inventory): validate catalog snapshot evidence before deduplication --- .github/workflows/ci.yml | 1 + docs/development/hardware-catalog.md | 4 ++ hack/netbox_catalog.py | 41 +++++++++-- hack/reviewer_catalog_validation_test.py | 42 ++++++++++++ hack/test_netbox_catalog.py | 87 ++++++++++++++++++++++++ 5 files changed, 170 insertions(+), 5 deletions(-) create mode 100644 hack/reviewer_catalog_validation_test.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4be3167e..e14e5639 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -23,6 +23,7 @@ jobs: - run: go vet ./... - run: python3 -m unittest discover -s hack -p test_netbox_inventory.py - run: python3 -m unittest discover -s hack -p test_netbox_catalog.py + - run: python3 -m unittest discover -s hack -p reviewer_catalog_validation_test.py - run: go run ./test/acceptance/milo/cmd validate --root . - run: kustomize build config/base/crd >/dev/null - run: kustomize build config/milo >/dev/null diff --git a/docs/development/hardware-catalog.md b/docs/development/hardware-catalog.md index b0083eb7..6fce748c 100644 --- a/docs/development/hardware-catalog.md +++ b/docs/development/hardware-catalog.md @@ -110,6 +110,10 @@ are handled by refreshing the snapshot. Conflicting existing records, alias or canonical-name collisions, duplicate normalized model pairs, missing references, malformed inputs, unknown mapping fields and duplicate JSON keys quarantine the **entire cohort** with no candidates. Source/catalog evidence stays private. +Snapshot version must be an integer and collection attestations must be lists. +Existing-record provenance and source identity must validate before deduplication +ignores changing receipt fields. Observation and recording timestamps use strict +RFC3339 date-times; broader Python ISO formats are rejected rather than emitted. Output is a review envelope, not an automatically applied Kubernetes List. The approved owner must re-read authorization, existing identities and conflicts diff --git a/hack/netbox_catalog.py b/hack/netbox_catalog.py index d2f60b8f..d73557e7 100644 --- a/hack/netbox_catalog.py +++ b/hack/netbox_catalog.py @@ -50,8 +50,8 @@ def source_id(value): def timestamp(value): - if not isinstance(value, str): - raise ValueError("invalid observation time") + if not isinstance(value, str) or not re.fullmatch(r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\.[0-9]+)?(Z|[+-](?:[01][0-9]|2[0-3]):[0-5][0-9])", value): + raise ValueError("timestamp requires RFC3339 date-time") parsed = datetime.datetime.fromisoformat(value.replace("Z", "+00:00")) if parsed.tzinfo is None: raise ValueError("timestamp requires timezone") @@ -63,6 +63,35 @@ def identity(value): return tuple(text(value[key]) for key in ("system", "type", "id")) +def validate_provenance(spec): + if not isinstance(spec, dict): + raise ValueError("invalid existing catalog spec") + provenance = spec.get("provenance") + fields(provenance, ("method", "recordedBy", "recordedAt"), ("reference", "source")) + if provenance["method"] not in ("Manual", "NetBoxImport"): + raise ValueError("invalid provenance method") + text(provenance["recordedBy"]) + timestamp(provenance["recordedAt"]) + if "reference" in provenance: + reference = provenance["reference"] + if not isinstance(reference, str) or not 1 <= len(reference) <= 1024: + raise ValueError("invalid provenance reference") + source = None + if "source" in provenance: + evidence = provenance["source"] + fields(evidence, ("system", "type", "id", "snapshotDigest", "mappingRevision", "observedAt")) + source = identity({key: evidence[key] for key in ("system", "type", "id")}) + if not isinstance(evidence["snapshotDigest"], str) or not re.fullmatch(r"sha256:[a-f0-9]{64}", evidence["snapshotDigest"]): + raise ValueError("invalid provenance snapshot digest") + text(evidence["mappingRevision"]) + timestamp(evidence["observedAt"]) + if "sourceIdentity" in spec: + if provenance["method"] != "NetBoxImport" or identity(spec["sourceIdentity"]) != source: + raise ValueError("source identity contradicts provenance") + elif provenance["method"] == "NetBoxImport": + raise ValueError("imported catalog record requires source identity") + + def no_uid(value): if isinstance(value, dict): if "uid" in value: @@ -83,14 +112,15 @@ def plan(snapshot, mapping, existing, recorded_by, recorded_at): raise ValueError("catalog requires an explicit operator-managed DirectAPI target") revision = text(mapping["revision"]) text(recorded_by) - if not isinstance(snapshot, dict) or snapshot.get("version") != 1 or snapshot.get("errors"): + if not isinstance(snapshot, dict) or type(snapshot.get("version")) is not int or snapshot["version"] != 1 or not isinstance(snapshot.get("errors"), dict) or snapshot["errors"]: raise ValueError("complete version-1 snapshot required") system = text(snapshot.get("source")) observed = snapshot.get("observedAt") if timestamp(recorded_at) < timestamp(observed): raise ValueError("recording predates observation") fields(existing, ("target", "collections", "items")) - if existing["target"] != target or sorted(existing["collections"]) != sorted(KINDS) or not isinstance(existing["items"], list): + collections = existing["collections"] + if existing["target"] != target or not isinstance(collections, list) or not all(isinstance(kind, str) for kind in collections) or sorted(collections) != sorted(KINDS) or not isinstance(existing["items"], list): raise ValueError("complete matching catalog snapshot required") objects = snapshot.get("objects") if not isinstance(objects, dict): @@ -113,7 +143,8 @@ def plan(snapshot, mapping, existing, recorded_by, recorded_at): raise ValueError("invalid existing catalog record") meta, spec = record.get("metadata", {}), record.get("spec", {}) no_uid(spec) - if meta.get("namespace") != target["namespace"] or not name_ok(meta.get("name")) or meta.get("deletionTimestamp"): + validate_provenance(spec) + if not isinstance(meta, dict) or meta.get("namespace") != target["namespace"] or not name_ok(meta.get("name")) or meta.get("deletionTimestamp"): raise ValueError("invalid or terminating existing target") key = (record["kind"], meta["name"]) if key in records: diff --git a/hack/reviewer_catalog_validation_test.py b/hack/reviewer_catalog_validation_test.py new file mode 100644 index 00000000..c720c0b7 --- /dev/null +++ b/hack/reviewer_catalog_validation_test.py @@ -0,0 +1,42 @@ +import copy +import unittest + +from test_netbox_catalog import fixture, plan + + +class IndependentCatalogValidation(unittest.TestCase): + def test_collection_attestation_must_be_a_list(self): + snapshot, mapping, existing = fixture() + existing['collections'] = {'Manufacturer': False, 'DeviceType': False} + with self.assertRaises(ValueError): + plan(snapshot, mapping, existing) + + def test_source_version_must_not_be_boolean(self): + snapshot, mapping, existing = fixture() + snapshot['version'] = True + with self.assertRaises(ValueError): + plan(snapshot, mapping, existing) + + def test_existing_identity_requires_provenance(self): + snapshot, mapping, existing = fixture() + existing['items'] = plan(snapshot, mapping, existing)['items'][:1] + del existing['items'][0]['spec']['provenance'] + with self.assertRaises(ValueError): + plan(snapshot, mapping, existing) + + def test_existing_identity_requires_matching_source_evidence(self): + snapshot, mapping, existing = fixture() + existing['items'] = plan(snapshot, mapping, existing)['items'][:1] + existing['items'][0]['spec']['provenance']['source']['id'] = '999' + with self.assertRaises(ValueError): + plan(snapshot, mapping, existing) + + def test_observation_timestamp_must_be_rfc3339(self): + snapshot, mapping, existing = fixture() + snapshot['observedAt'] = '20261121T000000+0000' + with self.assertRaises(ValueError): + plan(snapshot, mapping, existing) + + +if __name__ == '__main__': + unittest.main() diff --git a/hack/test_netbox_catalog.py b/hack/test_netbox_catalog.py index 1ae3ea6b..8cfd1d6d 100644 --- a/hack/test_netbox_catalog.py +++ b/hack/test_netbox_catalog.py @@ -25,6 +25,69 @@ def plan(snapshot, mapping, existing): class CatalogTests(unittest.TestCase): + def test_snapshot_envelope_types(self): + for value in (True, 1.0, "1", None): + snapshot, mapping, existing = fixture() + snapshot["version"] = value + with self.subTest(version=value), self.assertRaises(ValueError): + plan(snapshot, mapping, existing) + for value in (None, False, [], ""): + snapshot, mapping, existing = fixture() + snapshot["errors"] = value + with self.subTest(errors=value), self.assertRaises(ValueError): + plan(snapshot, mapping, existing) + for value in ({"Manufacturer": False, "DeviceType": False}, None, [None, "DeviceType"], ["Manufacturer", "Manufacturer", "DeviceType"]): + snapshot, mapping, existing = fixture() + existing["collections"] = value + with self.subTest(collections=value), self.assertRaises(ValueError): + plan(snapshot, mapping, existing) + + def test_provenance_validates_before_duplicate_comparison(self): + mutations = [ + ("method", "Manual"), ("method", "Unknown"), ("recordedBy", ""), + ("recordedAt", "20261121T000000+0000"), ("source", None), + ("reference", ""), ("reference", "x" * 1025), ("extra", "field"), + ] + for key, value in mutations: + snapshot, mapping, existing = fixture() + existing["items"] = plan(snapshot, mapping, existing)["items"][:1] + existing["items"][0]["spec"]["provenance"][key] = value + with self.subTest(key=key, value=value), self.assertRaises(ValueError): + plan(snapshot, mapping, existing) + for key, value in (("system", "other"), ("type", "other"), ("id", "999"), ("snapshotDigest", "invalid"), ("mappingRevision", ""), ("observedAt", "20261121T000000+0000"), ("extra", "field")): + snapshot, mapping, existing = fixture() + existing["items"] = plan(snapshot, mapping, existing)["items"][:1] + existing["items"][0]["spec"]["provenance"]["source"][key] = value + with self.subTest(source_key=key), self.assertRaises(ValueError): + plan(snapshot, mapping, existing) + + def test_valid_historical_receipt_is_not_replaced(self): + snapshot, mapping, existing = fixture() + existing["items"] = plan(snapshot, mapping, existing)["items"][:1] + provenance = existing["items"][0]["spec"]["provenance"] + provenance["recordedBy"] = "original-operator" + provenance["source"]["mappingRevision"] = "original-review" + provenance["source"]["snapshotDigest"] = "sha256:" + "0" * 64 + retained = copy.deepcopy(existing) + self.assertEqual(["DeviceType"], [item["kind"] for item in plan(snapshot, mapping, existing)["items"]]) + self.assertEqual(retained, existing) + + def test_timestamp_syntax_for_observation_and_recording(self): + for value in ("20261121T000000+0000", "2026-11-21 00:00:00Z", "2026-11-21T00:00:00", "2026-11-21T00:00:00+00:99", "2026-11-21T00:00:00+24:00", "2026-02-30T00:00:00Z", True): + for field in ("observedAt", "recordedAt"): + snapshot, mapping, existing = fixture() + recorded = "2026-11-21T01:00:00Z" + if field == "observedAt": + snapshot[field] = value + else: + recorded = value + with self.subTest(field=field, value=value), self.assertRaises(ValueError): + catalog.plan(snapshot, mapping, existing, "synthetic", recorded) + snapshot, mapping, existing = fixture() + snapshot["observedAt"] = "2026-11-21T00:00:00.123+00:00" + result = catalog.plan(snapshot, mapping, existing, "synthetic", "2026-11-20T20:00:00-05:00") + self.assertEqual(2, len(result["items"])) + def test_punctuated_human_names_are_not_resource_names(self): snapshot, mapping, existing = fixture() snapshot["objects"]["dcim/manufacturers"][0]["name"] = "Example Vendor, Inc." @@ -138,6 +201,30 @@ def test_cli_quarantines_duplicate_json_keys_without_candidates(self): self.assertEqual(1, result.returncode) self.assertEqual([], json.loads(result.stdout)["items"]) + def test_cli_quarantines_invalid_existing_evidence_without_partial_candidates(self): + for mutation in ("missing-provenance", "source-mismatch", "collections", "timestamp"): + snapshot, mapping, existing = fixture() + existing["items"] = plan(snapshot, mapping, existing)["items"][:1] + if mutation == "missing-provenance": + del existing["items"][0]["spec"]["provenance"] + elif mutation == "source-mismatch": + existing["items"][0]["spec"]["provenance"]["source"]["id"] = "999" + elif mutation == "collections": + existing["collections"] = {"Manufacturer": False, "DeviceType": False} + else: + snapshot["observedAt"] = "20261121T000000+0000" + with self.subTest(mutation=mutation), tempfile.TemporaryDirectory() as directory: + files = [] + for index, value in enumerate((snapshot, mapping, existing)): + path = Path(directory) / f"{index}.json" + path.write_text(json.dumps(value)) + files.append(str(path)) + result = subprocess.run(["python3", str(Path(catalog.__file__)), "--snapshot", files[0], "--mapping", files[1], "--existing", files[2], "--recorded-by", "synthetic", "--recorded-at", "2026-11-21T01:00:00Z"], capture_output=True, text=True) + self.assertEqual(1, result.returncode) + report = json.loads(result.stdout) + self.assertTrue(report["quarantined"]) + self.assertEqual([], report["items"]) + if __name__ == "__main__": unittest.main() From 4810fbf8b75fe50731a988326dd057f56e6b16cb Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sat, 21 Nov 2026 18:49:49 -0600 Subject: [PATCH 049/518] fix(ui): handle inventory records without provenance --- docs/operations/physical-inventory.md | 6 ++++++ .../src/components/device-placement-edit.test.tsx | 4 ++-- .../src/components/physical-inventory.test.tsx | 7 +++++++ ui/provider/src/components/physical-inventory.tsx | 10 +++++----- .../src/components/reviewer-current-target.test.tsx | 12 ++++++++++++ ui/provider/src/inventory.test.ts | 11 ++++++++++- ui/provider/src/inventory.ts | 2 +- ui/provider/src/lib/device-placement-edit.test.ts | 10 ++++++++++ ui/provider/src/lib/device-placement-edit.ts | 4 ++-- ui/provider/src/lib/inventory-management.test.ts | 3 ++- ui/provider/src/lib/inventory-management.ts | 4 ++-- ui/provider/src/pages/device-claim-detail.tsx | 3 ++- ui/provider/src/pages/device-inventory.test.tsx | 2 +- ui/shared/fleet-api.ts | 6 +++--- 14 files changed, 65 insertions(+), 19 deletions(-) create mode 100644 ui/provider/src/components/reviewer-current-target.test.tsx diff --git a/docs/operations/physical-inventory.md b/docs/operations/physical-inventory.md index 7cb79e05..1cc56cea 100644 --- a/docs/operations/physical-inventory.md +++ b/docs/operations/physical-inventory.md @@ -1,5 +1,11 @@ # Planning and registering physical devices +Portal readers accept records without provenance. Missing history is displayed as +unknown, not inferred ownership. The portal's narrower display-name editor still +requires its existing manual-record ownership evidence. Authorized location +corrections retain UID/resourceVersion preconditions and do not fabricate +provenance when none is present. + For source reports and authorized, concurrency-safe location record corrections, see [Device-reported placement](../development/device-reported-placement.md). diff --git a/ui/provider/src/components/device-placement-edit.test.tsx b/ui/provider/src/components/device-placement-edit.test.tsx index d256d347..534e01e6 100644 --- a/ui/provider/src/components/device-placement-edit.test.tsx +++ b/ui/provider/src/components/device-placement-edit.test.tsx @@ -9,7 +9,7 @@ import { InventoryOperationContext, InventoryOperationScope } from '../lib/inven vi.mock('../lib/inventory-management', async () => ({ ...await vi.importActual('../lib/inventory-management'), useInventoryPermission: vi.fn() })); const permission = vi.mocked(useInventoryPermission); -const device: Device = { ...fixturePhysicalDevices[0], metadata: { name: 'example', namespace: 'default', uid: 'uid', resourceVersion: '7' }, spec: { ...fixturePhysicalDevices[0].spec, reportedPlacement: undefined, provenance: { ...fixturePhysicalDevices[0].spec.provenance, method: 'NetBoxImport', recordedAt: '2026-01-01T00:00:00Z' } } }; +const device: Device = { ...fixturePhysicalDevices[0], metadata: { name: 'example', namespace: 'default', uid: 'uid', resourceVersion: '7' }, spec: { ...fixturePhysicalDevices[0].spec, reportedPlacement: undefined, provenance: { ...fixturePhysicalDevices[0].spec.provenance!, method: 'NetBoxImport', recordedAt: '2026-01-01T00:00:00Z' } } }; const rack: PhysicalRecord = { kind: 'Rack', metadata: { name: 'rack', namespace: 'default', uid: 'rack-uid' }, spec: { displayName: 'Restricted rack name', heightUnits: 42, provenance: device.spec.provenance } }; const response = (data: unknown, status = 200) => ({ ok: status < 400, status, json: async () => ({ data }) }); function setup(record = device, session = new InventoryOperationScope()) { @@ -51,7 +51,7 @@ describe('reported location editor', () => { const fetch = vi.fn().mockResolvedValueOnce(response({ status: { allowed: true } })).mockResolvedValueOnce(response(device)).mockResolvedValueOnce(response({}, status)); vi.stubGlobal('fetch', fetch); setup(); openAndFill(); fireEvent.click(screen.getByRole('button', { name: 'Save reported location' })); - await waitFor(() => expect(screen.getByRole('status')).toBeInTheDocument()); + await waitFor(() => expect(screen.getByRole('status')).toHaveTextContent(/no longer valid|changed or disappeared|unknown/)); expect(screen.getByRole('status')).not.toHaveTextContent('saved'); expect(screen.getByRole('button', { name: 'Save reported location' })).toBeDisabled(); expect(fetch).toHaveBeenCalledTimes(3); diff --git a/ui/provider/src/components/physical-inventory.test.tsx b/ui/provider/src/components/physical-inventory.test.tsx index d140c015..97a7a88d 100644 --- a/ui/provider/src/components/physical-inventory.test.tsx +++ b/ui/provider/src/components/physical-inventory.test.tsx @@ -13,6 +13,13 @@ function browse(query = '', data = inventory) { } describe('hardware directory', () => { + it.each(inventory.physical)('renders $kind details without provenance', record => { + const data = structuredClone(inventory); + for (const item of data.physical) delete item.spec.provenance; + browse(`?kind=${record.kind}&record=${record.metadata.name}&namespace=${record.metadata.namespace}`, data); + expect(screen.getByText('Record history & verification')).toBeInTheDocument(); + expect(screen.queryByText(/Unexpected Application Error/)).not.toBeInTheDocument(); + }); it('does not turn no-read permission into empty inventory or zero counts', () => { browse('', { ...inventory, issues: { Site: { status: 403 }, Device: { status: 403 }, DeviceClaim: { status: 403 }, Facility: { status: 403 }, Rack: { status: 403 }, Cable: { status: 403 }, PowerFeed: { status: 403 } } }); expect(screen.getByRole('heading', { name: 'Inventory access needed' })).toBeInTheDocument(); diff --git a/ui/provider/src/components/physical-inventory.tsx b/ui/provider/src/components/physical-inventory.tsx index 7f0aa5de..e6fdd70f 100644 --- a/ui/provider/src/components/physical-inventory.tsx +++ b/ui/provider/src/components/physical-inventory.tsx @@ -594,11 +594,11 @@ export function PhysicalInventory({ inventory: source, onRetry }: { inventory: I Record history & verification
Unknown — no verification evidence is available. - {provenance.recordedBy} - {provenance.recordedAt} - {provenance.method} - {provenance.reference} - {provenance.source && ( + {provenance?.recordedBy} + {provenance?.recordedAt} + {provenance?.method} + {provenance?.reference} + {provenance?.source && ( <> {provenance.source.system}/{provenance.source.type}/{provenance.source.id} diff --git a/ui/provider/src/components/reviewer-current-target.test.tsx b/ui/provider/src/components/reviewer-current-target.test.tsx new file mode 100644 index 00000000..17da3297 --- /dev/null +++ b/ui/provider/src/components/reviewer-current-target.test.tsx @@ -0,0 +1,12 @@ +import { render } from '@testing-library/react'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { expect, it } from 'vitest'; +import { InventoryManagement } from './inventory-management'; +import { inventoryPayload, INVENTORY_FIELD_MANAGER } from '../lib/inventory-management'; + +it('current target permits omitted provenance, which must not crash the production editor', () => { + const record = JSON.parse(JSON.stringify({ ...inventoryPayload('Facility', { name: 'independent', namespace: 'default', displayName: 'Independent facility', recordedBy: 'synthetic', reference: '', facility: '', height: '' }), metadata: { name: 'independent', namespace: 'default', uid: 'synthetic', resourceVersion: '1', managedFields: [{ manager: INVENTORY_FIELD_MANAGER }] } })); + delete record.spec.provenance; + const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + expect(() => render()).not.toThrow(); +}); diff --git a/ui/provider/src/inventory.test.ts b/ui/provider/src/inventory.test.ts index b938ceab..f82c003d 100644 --- a/ui/provider/src/inventory.test.ts +++ b/ui/provider/src/inventory.test.ts @@ -3,6 +3,15 @@ import { fixtureDeviceClaims, fixtureDevices } from './lib/fixtures'; import { describe, expect, it } from 'vitest'; describe('toInventory', () => { + it('keeps provenance-free claim members visible without inferring a current device', () => { + const devices = structuredClone(fixtureDevices); + devices.push({ ...structuredClone(devices[0]), metadata: { ...devices[0].metadata, name: 'another-device' } }); + for (const device of devices) delete device.spec.provenance; + const inventory = toInventory(fixtureDeviceClaims, devices); + const slot = inventory.slots.find(item => item.claim.metadata.name === devices[0].spec.claimRef.name)!; + expect(slot.devices).toHaveLength(2); + expect(currentDevice(slot)).toBeUndefined(); + }); it('binds Devices to claims in the same namespace and keeps orphans visible', () => { const inventory = toInventory(fixtureDeviceClaims, fixtureDevices); expect(inventory.slots.map((s) => s.claim.metadata.name)).toEqual(['rack-01-u10', 'rack-01-u12']); @@ -23,7 +32,7 @@ describe('toInventory', () => { const replacement = { ...fixtureDevices[0], metadata: { ...fixtureDevices[0].metadata, name: 'rack-01-u12-synthetic-0002' }, - spec: { ...fixtureDevices[0].spec, provenance: { ...fixtureDevices[0].spec.provenance, recordedAt: '2026-02-01T00:00:00Z' } }, + spec: { ...fixtureDevices[0].spec, provenance: { ...fixtureDevices[0].spec.provenance!, recordedAt: '2026-02-01T00:00:00Z' } }, }; const inventory = toInventory(fixtureDeviceClaims, [replacement, fixtureDevices[0]]); const u12 = inventory.slots.find((s) => s.claim.metadata.name === 'rack-01-u12')!; diff --git a/ui/provider/src/inventory.ts b/ui/provider/src/inventory.ts index 871b151b..940f7ccc 100644 --- a/ui/provider/src/inventory.ts +++ b/ui/provider/src/inventory.ts @@ -30,7 +30,7 @@ export function slotKey(namespace: string | undefined, name: string): string { } function byRecordedAt(a: RawDevice, b: RawDevice): number { - return a.spec.provenance.recordedAt.localeCompare(b.spec.provenance.recordedAt); + return (a.spec.provenance?.recordedAt ?? '').localeCompare(b.spec.provenance?.recordedAt ?? '') || slotKey(a.metadata.namespace, a.metadata.name).localeCompare(slotKey(b.metadata.namespace, b.metadata.name)); } export function toInventory(claims: RawDeviceClaim[], devices: RawDevice[], physical: PhysicalRecord[] = []): Inventory { diff --git a/ui/provider/src/lib/device-placement-edit.test.ts b/ui/provider/src/lib/device-placement-edit.test.ts index 1320984c..db69ff51 100644 --- a/ui/provider/src/lib/device-placement-edit.test.ts +++ b/ui/provider/src/lib/device-placement-edit.test.ts @@ -14,6 +14,16 @@ const saved = (request: RequestInit) => { afterEach(() => vi.unstubAllGlobals()); describe('direct placement correction', () => { + it('corrects provenance-free records without inventing a receipt', async () => { + const baseline = structuredClone(original); + delete baseline.spec.provenance; + const fetch = vi.fn().mockResolvedValueOnce(response({ status: { allowed: true } })).mockResolvedValueOnce(response(baseline)).mockImplementationOnce((_url, request) => response({ ...baseline, metadata: { ...baseline.metadata, resourceVersion: '8' }, spec: { ...baseline.spec, reportedPlacement: JSON.parse(request.body).at(-1).value } })); + vi.stubGlobal('fetch', fetch); + const result = await correctDevicePlacement(baseline, fields, new InventoryOperationScope().begin()); + const patch = JSON.parse(fetch.mock.calls[2][1].body); + expect(patch.map((entry: { path: string }) => entry.path)).toEqual(['/metadata/uid', '/metadata/resourceVersion', '/spec/reportedPlacement']); + expect(result.spec.provenance).toBeUndefined(); + }); it.each([false, true])('adds/updates imported records without altering import provenance: %s', async existing => { const baseline = structuredClone(original); if (existing) baseline.spec.reportedPlacement = { revision: 1, observedAt: fields.observedAt, snapshotDigest: `sha256:${'a'.repeat(64)}` }; diff --git a/ui/provider/src/lib/device-placement-edit.ts b/ui/provider/src/lib/device-placement-edit.ts index 4f06382a..a4e8e6bb 100644 --- a/ui/provider/src/lib/device-placement-edit.ts +++ b/ui/provider/src/lib/device-placement-edit.ts @@ -74,7 +74,7 @@ export async function correctDevicePlacement(original: Device, fields: Placement operation.assertCurrent(); if (current.metadata.uid !== original.metadata.uid || current.metadata.resourceVersion !== original.metadata.resourceVersion || !canCorrectPlacement(current)) throw new ApiError(409, 'The Device changed. Refresh and reopen the form.'); const now = new Date().toISOString(); - if (Date.parse(now) <= Date.parse(current.spec.provenance.recordedAt)) throw new ApiError(409, 'Recording time must advance.'); + if (current.spec.provenance && Date.parse(now) <= Date.parse(current.spec.provenance.recordedAt)) throw new ApiError(409, 'Recording time must advance.'); const report = placementPayload(original, fields, now); if (report.facilityRef) { const facility = await readInventoryReference('Facility', namespace, report.facilityRef.name, operation); @@ -93,7 +93,7 @@ export async function correctDevicePlacement(original: Device, fields: Placement { op: 'test', path: '/metadata/uid', value: original.metadata.uid }, { op: 'test', path: '/metadata/resourceVersion', value: original.metadata.resourceVersion }, { op: 'add', path: '/spec/reportedPlacement', value: report }, - { op: 'replace', path: '/spec/provenance/recordedAt', value: now }, + ...(current.spec.provenance ? [{ op: 'replace', path: '/spec/provenance/recordedAt', value: now }] : []), ]; operation.dispatch(); const saved = await proxyFetch(PROVIDER_PROJECT, path, { method: 'PATCH', contentType: 'application/json-patch+json', body: patch }).catch(error => { diff --git a/ui/provider/src/lib/inventory-management.test.ts b/ui/provider/src/lib/inventory-management.test.ts index eb63c180..325adba4 100644 --- a/ui/provider/src/lib/inventory-management.test.ts +++ b/ui/provider/src/lib/inventory-management.test.ts @@ -50,7 +50,8 @@ describe('inventory management authority', () => { it('rejects Flux-owned, imported, deleting and unknown-writer records', () => { expect(canEditInventoryLabel(owned)).toBe(true); for (const metadata of [{ ...owned.metadata, managedFields: undefined }, { ...owned.metadata, managedFields: [{ manager: 'kustomize-controller' }] }, { ...owned.metadata, deletionTimestamp: '2026-01-01T00:00:00Z' }, { ...owned.metadata, labels: { 'kustomize.toolkit.fluxcd.io/name': 'inventory' } }]) expect(canEditInventoryLabel({ ...owned, metadata })).toBe(false); - expect(canEditInventoryLabel({ ...owned, spec: { ...owned.spec, provenance: { ...owned.spec.provenance, method: 'NetBoxImport' } } })).toBe(false); + expect(canEditInventoryLabel({ ...owned, spec: { ...owned.spec, provenance: { ...owned.spec.provenance!, method: 'NetBoxImport' } } })).toBe(false); + expect(canEditInventoryLabel({ ...owned, spec: { ...owned.spec, provenance: undefined } })).toBe(false); }); it('edits only a display name and provenance with UID and revision preconditions', async () => { diff --git a/ui/provider/src/lib/inventory-management.ts b/ui/provider/src/lib/inventory-management.ts index 5883731d..ea969332 100644 --- a/ui/provider/src/lib/inventory-management.ts +++ b/ui/provider/src/lib/inventory-management.ts @@ -29,7 +29,7 @@ export function useInventoryPermission(kind: ManagedKind, namespace: string, ver export function canEditInventoryLabel(record: ManagedRecord): boolean { const { metadata, spec } = record; - return ['Facility', 'Rack', 'Device', 'Cable'].includes(record.kind ?? '') && !!metadata.uid && !!metadata.resourceVersion && !metadata.deletionTimestamp && !spec.provenance.source && spec.provenance.method === 'Manual' && + return ['Facility', 'Rack', 'Device', 'Cable'].includes(record.kind ?? '') && !!metadata.uid && !!metadata.resourceVersion && !metadata.deletionTimestamp && !!spec.provenance && !spec.provenance.source && spec.provenance.method === 'Manual' && !Object.keys({ ...metadata.labels, ...metadata.annotations }).some(key => /fluxcd\.io|argocd|inventory.*owner/i.test(key)) && !!metadata.managedFields?.length && metadata.managedFields.every(field => field.manager === INVENTORY_FIELD_MANAGER && !field.subresource); } @@ -93,7 +93,7 @@ export async function editInventoryLabel(original: ManagedRecord, values: Invent operation.assertCurrent(); if (!current || current.metadata.uid !== original.metadata.uid || current.metadata.resourceVersion !== original.metadata.resourceVersion || !canEditInventoryLabel(current)) throw new ApiError(409, 'The record or its ownership changed. Reload it before editing.'); const now = new Date().toISOString(); - if (now <= current.spec.provenance.recordedAt) throw new ApiError(409, 'The recorded timestamp is not earlier than this clock. Review the record before editing.'); + if (!current.spec.provenance || now <= current.spec.provenance.recordedAt) throw new ApiError(409, 'The recorded timestamp is missing or not earlier than this clock. Review the record before editing.'); const validated = inventoryPayload('Facility', { ...values, name: original.metadata.name, namespace }, now); operation.dispatch(); const record = await proxyFetch(PROVIDER_PROJECT, `${path}?fieldManager=${INVENTORY_FIELD_MANAGER}`, { method: 'PATCH', contentType: 'application/json-patch+json', body: [ diff --git a/ui/provider/src/pages/device-claim-detail.tsx b/ui/provider/src/pages/device-claim-detail.tsx index efbe5fe4..85bc0adc 100644 --- a/ui/provider/src/pages/device-claim-detail.tsx +++ b/ui/provider/src/pages/device-claim-detail.tsx @@ -32,7 +32,8 @@ function Section({ title, testId, children }: { title: string; testId: string; c ); } -function ProvenanceFields({ provenance }: { provenance: Provenance }) { +function ProvenanceFields({ provenance }: { provenance?: Provenance }) { + if (!provenance) return Not recorded; return (
{provenance.recordedBy} diff --git a/ui/provider/src/pages/device-inventory.test.tsx b/ui/provider/src/pages/device-inventory.test.tsx index 57bed228..21fb41f8 100644 --- a/ui/provider/src/pages/device-inventory.test.tsx +++ b/ui/provider/src/pages/device-inventory.test.tsx @@ -152,7 +152,7 @@ describe('DeviceClaimDetail', () => { const replacement = { ...fixtureDevices[0], metadata: { ...fixtureDevices[0].metadata, name: 'rack-01-u12-synthetic-0002' }, - spec: { ...fixtureDevices[0].spec, provenance: { ...fixtureDevices[0].spec.provenance, recordedAt: '2026-02-01T00:00:00Z' } }, + spec: { ...fixtureDevices[0].spec, provenance: { ...fixtureDevices[0].spec.provenance!, recordedAt: '2026-02-01T00:00:00Z' } }, }; mockInventory({ data: toInventory(fixtureDeviceClaims, [fixtureDevices[0], replacement]) }); renderAt('/plugins/metal-datumapis-com/inventory/default/rack-01-u12'); diff --git a/ui/shared/fleet-api.ts b/ui/shared/fleet-api.ts index 725f3a58..f6bafefb 100644 --- a/ui/shared/fleet-api.ts +++ b/ui/shared/fleet-api.ts @@ -255,7 +255,7 @@ export interface DeviceClaim { kind?: string; metadata: ObjectMeta; spec: { - provenance: Provenance; + provenance?: Provenance; expectedIdentity: { manufacturer?: string; model: string; serial?: string }; lifecycle?: 'Installation'; displayName?: string; @@ -272,7 +272,7 @@ export interface Device { spec: { reportedPlacement?: ReportedPlacement; claimRef: LocalReference; - provenance: Provenance; + provenance?: Provenance; identity: { manufacturer?: string; model: string; serial?: string; systemUUID?: string; sourceIdentity?: ExternalReference }; assetTag?: string; displayName?: string; @@ -325,7 +325,7 @@ export interface PhysicalRecord { kind: 'Site' | 'Facility' | 'Rack' | 'Cable' | 'PowerFeed'; spec: { displayName: string; - provenance: Provenance; + provenance?: Provenance; code?: string; facilityRefs?: LocalReference[]; identifiers?: { provider: string; type: 'PremisesCode' | 'PremisesAlias' | 'PremisesID'; value: string }[]; From 038951c1127a3198c64f95c9afc921a67503a147 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sat, 21 Nov 2026 18:50:17 -0600 Subject: [PATCH 050/518] fix(inventory): bound catalog source IDs before candidate emission --- hack/netbox_catalog.py | 4 ++-- hack/test_netbox_catalog.py | 23 +++++++++++++++++++++-- 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/hack/netbox_catalog.py b/hack/netbox_catalog.py index d73557e7..ab460963 100644 --- a/hack/netbox_catalog.py +++ b/hack/netbox_catalog.py @@ -43,8 +43,8 @@ def model_key(value): def source_id(value): if type(value) is int and value > 0: - return str(value) - if isinstance(value, str) and re.fullmatch(r"[1-9][0-9]*", value): + value = str(value) + if isinstance(value, str) and len(value) <= 253 and re.fullmatch(r"[1-9][0-9]*", value): return value raise ValueError("invalid explicit NetBox source ID") diff --git a/hack/test_netbox_catalog.py b/hack/test_netbox_catalog.py index 8cfd1d6d..c26274c9 100644 --- a/hack/test_netbox_catalog.py +++ b/hack/test_netbox_catalog.py @@ -25,6 +25,21 @@ def plan(snapshot, mapping, existing): class CatalogTests(unittest.TestCase): + def test_source_id_length_boundaries(self): + for convert in (str, int): + for size in (1, 253, 254): + snapshot, mapping, existing = fixture() + value = convert("9" * size) + snapshot["objects"]["dcim/device-types"][0]["id"] = value + mapping["deviceTypes"][0]["sourceID"] = value + with self.subTest(conversion=convert.__name__, size=size): + if size > 253: + with self.assertRaises(ValueError): + plan(snapshot, mapping, existing) + else: + result = plan(snapshot, mapping, existing) + self.assertEqual(str(value), result["items"][1]["spec"]["sourceIdentity"]["id"]) + def test_snapshot_envelope_types(self): for value in (True, 1.0, "1", None): snapshot, mapping, existing = fixture() @@ -202,7 +217,7 @@ def test_cli_quarantines_duplicate_json_keys_without_candidates(self): self.assertEqual([], json.loads(result.stdout)["items"]) def test_cli_quarantines_invalid_existing_evidence_without_partial_candidates(self): - for mutation in ("missing-provenance", "source-mismatch", "collections", "timestamp"): + for mutation in ("missing-provenance", "source-mismatch", "collections", "timestamp", "long-string", "long-integer"): snapshot, mapping, existing = fixture() existing["items"] = plan(snapshot, mapping, existing)["items"][:1] if mutation == "missing-provenance": @@ -211,8 +226,12 @@ def test_cli_quarantines_invalid_existing_evidence_without_partial_candidates(se existing["items"][0]["spec"]["provenance"]["source"]["id"] = "999" elif mutation == "collections": existing["collections"] = {"Manufacturer": False, "DeviceType": False} - else: + elif mutation == "timestamp": snapshot["observedAt"] = "20261121T000000+0000" + else: + value = "9" * 254 if mutation == "long-string" else int("9" * 254) + snapshot["objects"]["dcim/device-types"][0]["id"] = value + mapping["deviceTypes"][0]["sourceID"] = value with self.subTest(mutation=mutation), tempfile.TemporaryDirectory() as directory: files = [] for index, value in enumerate((snapshot, mapping, existing)): From aeb45bb641b38b1b2da5a02350b8c34b351c3c52 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sat, 21 Nov 2026 18:49:49 -0600 Subject: [PATCH 051/518] fix(ui): handle inventory records without provenance --- docs/operations/physical-inventory.md | 6 ++++++ .../src/components/device-placement-edit.test.tsx | 4 ++-- .../src/components/physical-inventory.test.tsx | 7 +++++++ ui/provider/src/components/physical-inventory.tsx | 10 +++++----- .../src/components/reviewer-current-target.test.tsx | 12 ++++++++++++ ui/provider/src/inventory.test.ts | 11 ++++++++++- ui/provider/src/inventory.ts | 2 +- ui/provider/src/lib/device-placement-edit.test.ts | 10 ++++++++++ ui/provider/src/lib/device-placement-edit.ts | 4 ++-- ui/provider/src/lib/inventory-management.test.ts | 3 ++- ui/provider/src/lib/inventory-management.ts | 4 ++-- ui/provider/src/pages/device-claim-detail.tsx | 3 ++- ui/provider/src/pages/device-inventory.test.tsx | 2 +- ui/shared/fleet-api.ts | 6 +++--- 14 files changed, 65 insertions(+), 19 deletions(-) create mode 100644 ui/provider/src/components/reviewer-current-target.test.tsx diff --git a/docs/operations/physical-inventory.md b/docs/operations/physical-inventory.md index 7cb79e05..1cc56cea 100644 --- a/docs/operations/physical-inventory.md +++ b/docs/operations/physical-inventory.md @@ -1,5 +1,11 @@ # Planning and registering physical devices +Portal readers accept records without provenance. Missing history is displayed as +unknown, not inferred ownership. The portal's narrower display-name editor still +requires its existing manual-record ownership evidence. Authorized location +corrections retain UID/resourceVersion preconditions and do not fabricate +provenance when none is present. + For source reports and authorized, concurrency-safe location record corrections, see [Device-reported placement](../development/device-reported-placement.md). diff --git a/ui/provider/src/components/device-placement-edit.test.tsx b/ui/provider/src/components/device-placement-edit.test.tsx index a86a3aff..33dea039 100644 --- a/ui/provider/src/components/device-placement-edit.test.tsx +++ b/ui/provider/src/components/device-placement-edit.test.tsx @@ -9,7 +9,7 @@ import { InventoryOperationContext, InventoryOperationScope } from '../lib/inven vi.mock('../lib/inventory-management', async () => ({ ...await vi.importActual('../lib/inventory-management'), useInventoryPermission: vi.fn() })); const permission = vi.mocked(useInventoryPermission); -const device: Device = { ...fixturePhysicalDevices[0], metadata: { name: 'example', namespace: 'default', uid: 'uid', resourceVersion: '7' }, spec: { ...fixturePhysicalDevices[0].spec, reportedPlacement: undefined, provenance: { ...fixturePhysicalDevices[0].spec.provenance, method: 'NetBoxImport', recordedAt: '2026-01-01T00:00:00Z' } } }; +const device: Device = { ...fixturePhysicalDevices[0], metadata: { name: 'example', namespace: 'default', uid: 'uid', resourceVersion: '7' }, spec: { ...fixturePhysicalDevices[0].spec, reportedPlacement: undefined, provenance: { ...fixturePhysicalDevices[0].spec.provenance!, method: 'NetBoxImport', recordedAt: '2026-01-01T00:00:00Z' } } }; const rack: PhysicalRecord = { kind: 'Rack', metadata: { name: 'rack', namespace: 'default', uid: 'rack-uid' }, spec: { displayName: 'Restricted rack name', heightUnits: 42, provenance: device.spec.provenance } }; const response = (data: unknown, status = 200) => ({ ok: status < 400, status, json: async () => ({ data }) }); function setup(record = device, session = new InventoryOperationScope()) { @@ -51,7 +51,7 @@ describe('reported location editor', () => { const fetch = vi.fn().mockResolvedValueOnce(response({ status: { allowed: true } })).mockResolvedValueOnce(response(device)).mockResolvedValueOnce(response({}, status)); vi.stubGlobal('fetch', fetch); setup(); openAndFill(); fireEvent.click(screen.getByRole('button', { name: 'Save reported location' })); - await waitFor(() => expect(screen.getByRole('status')).toBeInTheDocument()); + await waitFor(() => expect(screen.getByRole('status')).toHaveTextContent(/no longer valid|changed or disappeared|unknown/)); expect(screen.getByRole('status')).not.toHaveTextContent('saved'); expect(screen.getByRole('button', { name: 'Save reported location' })).toBeDisabled(); expect(fetch).toHaveBeenCalledTimes(3); diff --git a/ui/provider/src/components/physical-inventory.test.tsx b/ui/provider/src/components/physical-inventory.test.tsx index 1a81a724..7eaa43a9 100644 --- a/ui/provider/src/components/physical-inventory.test.tsx +++ b/ui/provider/src/components/physical-inventory.test.tsx @@ -13,6 +13,13 @@ function browse(query = '', data = inventory) { } describe('hardware directory', () => { + it.each(inventory.physical)('renders $kind details without provenance', record => { + const data = structuredClone(inventory); + for (const item of data.physical) delete item.spec.provenance; + browse(`?kind=${record.kind}&record=${record.metadata.name}&namespace=${record.metadata.namespace}`, data); + expect(screen.getByText('Record history & verification')).toBeInTheDocument(); + expect(screen.queryByText(/Unexpected Application Error/)).not.toBeInTheDocument(); + }); it('does not turn no-read permission into empty inventory or zero counts', () => { browse('', { ...inventory, issues: { Manufacturer: { status: 403 }, DeviceType: { status: 403 }, Site: { status: 403 }, Device: { status: 403 }, DeviceClaim: { status: 403 }, Facility: { status: 403 }, Rack: { status: 403 }, Cable: { status: 403 }, PowerFeed: { status: 403 } } }); expect(screen.getByRole('heading', { name: 'Inventory access needed' })).toBeInTheDocument(); diff --git a/ui/provider/src/components/physical-inventory.tsx b/ui/provider/src/components/physical-inventory.tsx index 61a13937..04e20743 100644 --- a/ui/provider/src/components/physical-inventory.tsx +++ b/ui/provider/src/components/physical-inventory.tsx @@ -614,11 +614,11 @@ export function PhysicalInventory({ inventory: source, onRetry }: { inventory: I Record history & verification
Unknown — no verification evidence is available. - {provenance.recordedBy} - {provenance.recordedAt} - {provenance.method} - {provenance.reference} - {provenance.source && ( + {provenance?.recordedBy} + {provenance?.recordedAt} + {provenance?.method} + {provenance?.reference} + {provenance?.source && ( <> {provenance.source.system}/{provenance.source.type}/{provenance.source.id} diff --git a/ui/provider/src/components/reviewer-current-target.test.tsx b/ui/provider/src/components/reviewer-current-target.test.tsx new file mode 100644 index 00000000..17da3297 --- /dev/null +++ b/ui/provider/src/components/reviewer-current-target.test.tsx @@ -0,0 +1,12 @@ +import { render } from '@testing-library/react'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { expect, it } from 'vitest'; +import { InventoryManagement } from './inventory-management'; +import { inventoryPayload, INVENTORY_FIELD_MANAGER } from '../lib/inventory-management'; + +it('current target permits omitted provenance, which must not crash the production editor', () => { + const record = JSON.parse(JSON.stringify({ ...inventoryPayload('Facility', { name: 'independent', namespace: 'default', displayName: 'Independent facility', recordedBy: 'synthetic', reference: '', facility: '', height: '' }), metadata: { name: 'independent', namespace: 'default', uid: 'synthetic', resourceVersion: '1', managedFields: [{ manager: INVENTORY_FIELD_MANAGER }] } })); + delete record.spec.provenance; + const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + expect(() => render()).not.toThrow(); +}); diff --git a/ui/provider/src/inventory.test.ts b/ui/provider/src/inventory.test.ts index b938ceab..f82c003d 100644 --- a/ui/provider/src/inventory.test.ts +++ b/ui/provider/src/inventory.test.ts @@ -3,6 +3,15 @@ import { fixtureDeviceClaims, fixtureDevices } from './lib/fixtures'; import { describe, expect, it } from 'vitest'; describe('toInventory', () => { + it('keeps provenance-free claim members visible without inferring a current device', () => { + const devices = structuredClone(fixtureDevices); + devices.push({ ...structuredClone(devices[0]), metadata: { ...devices[0].metadata, name: 'another-device' } }); + for (const device of devices) delete device.spec.provenance; + const inventory = toInventory(fixtureDeviceClaims, devices); + const slot = inventory.slots.find(item => item.claim.metadata.name === devices[0].spec.claimRef.name)!; + expect(slot.devices).toHaveLength(2); + expect(currentDevice(slot)).toBeUndefined(); + }); it('binds Devices to claims in the same namespace and keeps orphans visible', () => { const inventory = toInventory(fixtureDeviceClaims, fixtureDevices); expect(inventory.slots.map((s) => s.claim.metadata.name)).toEqual(['rack-01-u10', 'rack-01-u12']); @@ -23,7 +32,7 @@ describe('toInventory', () => { const replacement = { ...fixtureDevices[0], metadata: { ...fixtureDevices[0].metadata, name: 'rack-01-u12-synthetic-0002' }, - spec: { ...fixtureDevices[0].spec, provenance: { ...fixtureDevices[0].spec.provenance, recordedAt: '2026-02-01T00:00:00Z' } }, + spec: { ...fixtureDevices[0].spec, provenance: { ...fixtureDevices[0].spec.provenance!, recordedAt: '2026-02-01T00:00:00Z' } }, }; const inventory = toInventory(fixtureDeviceClaims, [replacement, fixtureDevices[0]]); const u12 = inventory.slots.find((s) => s.claim.metadata.name === 'rack-01-u12')!; diff --git a/ui/provider/src/inventory.ts b/ui/provider/src/inventory.ts index 5ad60d20..3b07ea99 100644 --- a/ui/provider/src/inventory.ts +++ b/ui/provider/src/inventory.ts @@ -31,7 +31,7 @@ export function slotKey(namespace: string | undefined, name: string): string { } function byRecordedAt(a: RawDevice, b: RawDevice): number { - return a.spec.provenance.recordedAt.localeCompare(b.spec.provenance.recordedAt); + return (a.spec.provenance?.recordedAt ?? '').localeCompare(b.spec.provenance?.recordedAt ?? '') || slotKey(a.metadata.namespace, a.metadata.name).localeCompare(slotKey(b.metadata.namespace, b.metadata.name)); } export function toInventory(claims: RawDeviceClaim[], devices: RawDevice[], physical: PhysicalRecord[] = []): Inventory { diff --git a/ui/provider/src/lib/device-placement-edit.test.ts b/ui/provider/src/lib/device-placement-edit.test.ts index 1320984c..db69ff51 100644 --- a/ui/provider/src/lib/device-placement-edit.test.ts +++ b/ui/provider/src/lib/device-placement-edit.test.ts @@ -14,6 +14,16 @@ const saved = (request: RequestInit) => { afterEach(() => vi.unstubAllGlobals()); describe('direct placement correction', () => { + it('corrects provenance-free records without inventing a receipt', async () => { + const baseline = structuredClone(original); + delete baseline.spec.provenance; + const fetch = vi.fn().mockResolvedValueOnce(response({ status: { allowed: true } })).mockResolvedValueOnce(response(baseline)).mockImplementationOnce((_url, request) => response({ ...baseline, metadata: { ...baseline.metadata, resourceVersion: '8' }, spec: { ...baseline.spec, reportedPlacement: JSON.parse(request.body).at(-1).value } })); + vi.stubGlobal('fetch', fetch); + const result = await correctDevicePlacement(baseline, fields, new InventoryOperationScope().begin()); + const patch = JSON.parse(fetch.mock.calls[2][1].body); + expect(patch.map((entry: { path: string }) => entry.path)).toEqual(['/metadata/uid', '/metadata/resourceVersion', '/spec/reportedPlacement']); + expect(result.spec.provenance).toBeUndefined(); + }); it.each([false, true])('adds/updates imported records without altering import provenance: %s', async existing => { const baseline = structuredClone(original); if (existing) baseline.spec.reportedPlacement = { revision: 1, observedAt: fields.observedAt, snapshotDigest: `sha256:${'a'.repeat(64)}` }; diff --git a/ui/provider/src/lib/device-placement-edit.ts b/ui/provider/src/lib/device-placement-edit.ts index 4f06382a..a4e8e6bb 100644 --- a/ui/provider/src/lib/device-placement-edit.ts +++ b/ui/provider/src/lib/device-placement-edit.ts @@ -74,7 +74,7 @@ export async function correctDevicePlacement(original: Device, fields: Placement operation.assertCurrent(); if (current.metadata.uid !== original.metadata.uid || current.metadata.resourceVersion !== original.metadata.resourceVersion || !canCorrectPlacement(current)) throw new ApiError(409, 'The Device changed. Refresh and reopen the form.'); const now = new Date().toISOString(); - if (Date.parse(now) <= Date.parse(current.spec.provenance.recordedAt)) throw new ApiError(409, 'Recording time must advance.'); + if (current.spec.provenance && Date.parse(now) <= Date.parse(current.spec.provenance.recordedAt)) throw new ApiError(409, 'Recording time must advance.'); const report = placementPayload(original, fields, now); if (report.facilityRef) { const facility = await readInventoryReference('Facility', namespace, report.facilityRef.name, operation); @@ -93,7 +93,7 @@ export async function correctDevicePlacement(original: Device, fields: Placement { op: 'test', path: '/metadata/uid', value: original.metadata.uid }, { op: 'test', path: '/metadata/resourceVersion', value: original.metadata.resourceVersion }, { op: 'add', path: '/spec/reportedPlacement', value: report }, - { op: 'replace', path: '/spec/provenance/recordedAt', value: now }, + ...(current.spec.provenance ? [{ op: 'replace', path: '/spec/provenance/recordedAt', value: now }] : []), ]; operation.dispatch(); const saved = await proxyFetch(PROVIDER_PROJECT, path, { method: 'PATCH', contentType: 'application/json-patch+json', body: patch }).catch(error => { diff --git a/ui/provider/src/lib/inventory-management.test.ts b/ui/provider/src/lib/inventory-management.test.ts index eb63c180..325adba4 100644 --- a/ui/provider/src/lib/inventory-management.test.ts +++ b/ui/provider/src/lib/inventory-management.test.ts @@ -50,7 +50,8 @@ describe('inventory management authority', () => { it('rejects Flux-owned, imported, deleting and unknown-writer records', () => { expect(canEditInventoryLabel(owned)).toBe(true); for (const metadata of [{ ...owned.metadata, managedFields: undefined }, { ...owned.metadata, managedFields: [{ manager: 'kustomize-controller' }] }, { ...owned.metadata, deletionTimestamp: '2026-01-01T00:00:00Z' }, { ...owned.metadata, labels: { 'kustomize.toolkit.fluxcd.io/name': 'inventory' } }]) expect(canEditInventoryLabel({ ...owned, metadata })).toBe(false); - expect(canEditInventoryLabel({ ...owned, spec: { ...owned.spec, provenance: { ...owned.spec.provenance, method: 'NetBoxImport' } } })).toBe(false); + expect(canEditInventoryLabel({ ...owned, spec: { ...owned.spec, provenance: { ...owned.spec.provenance!, method: 'NetBoxImport' } } })).toBe(false); + expect(canEditInventoryLabel({ ...owned, spec: { ...owned.spec, provenance: undefined } })).toBe(false); }); it('edits only a display name and provenance with UID and revision preconditions', async () => { diff --git a/ui/provider/src/lib/inventory-management.ts b/ui/provider/src/lib/inventory-management.ts index 438b4042..44c492dd 100644 --- a/ui/provider/src/lib/inventory-management.ts +++ b/ui/provider/src/lib/inventory-management.ts @@ -29,7 +29,7 @@ export function useInventoryPermission(kind: ManagedKind, namespace: string, ver export function canEditInventoryLabel(record: ManagedRecord): boolean { const { metadata, spec } = record; - return ['Facility', 'Rack', 'Device', 'Cable'].includes(record.kind ?? '') && !!metadata.uid && !!metadata.resourceVersion && !metadata.deletionTimestamp && !spec.provenance.source && spec.provenance.method === 'Manual' && + return ['Facility', 'Rack', 'Device', 'Cable'].includes(record.kind ?? '') && !!metadata.uid && !!metadata.resourceVersion && !metadata.deletionTimestamp && !!spec.provenance && !spec.provenance.source && spec.provenance.method === 'Manual' && !Object.keys({ ...metadata.labels, ...metadata.annotations }).some(key => /fluxcd\.io|argocd|inventory.*owner/i.test(key)) && !!metadata.managedFields?.length && metadata.managedFields.every(field => field.manager === INVENTORY_FIELD_MANAGER && !field.subresource); } @@ -93,7 +93,7 @@ export async function editInventoryLabel(original: ManagedRecord, values: Invent operation.assertCurrent(); if (!current || current.metadata.uid !== original.metadata.uid || current.metadata.resourceVersion !== original.metadata.resourceVersion || !canEditInventoryLabel(current)) throw new ApiError(409, 'The record or its ownership changed. Reload it before editing.'); const now = new Date().toISOString(); - if (now <= current.spec.provenance.recordedAt) throw new ApiError(409, 'The recorded timestamp is not earlier than this clock. Review the record before editing.'); + if (!current.spec.provenance || now <= current.spec.provenance.recordedAt) throw new ApiError(409, 'The recorded timestamp is missing or not earlier than this clock. Review the record before editing.'); const validated = inventoryPayload('Facility', { ...values, name: original.metadata.name, namespace }, now); operation.dispatch(); const record = await proxyFetch(PROVIDER_PROJECT, `${path}?fieldManager=${INVENTORY_FIELD_MANAGER}`, { method: 'PATCH', contentType: 'application/json-patch+json', body: [ diff --git a/ui/provider/src/pages/device-claim-detail.tsx b/ui/provider/src/pages/device-claim-detail.tsx index efbe5fe4..85bc0adc 100644 --- a/ui/provider/src/pages/device-claim-detail.tsx +++ b/ui/provider/src/pages/device-claim-detail.tsx @@ -32,7 +32,8 @@ function Section({ title, testId, children }: { title: string; testId: string; c ); } -function ProvenanceFields({ provenance }: { provenance: Provenance }) { +function ProvenanceFields({ provenance }: { provenance?: Provenance }) { + if (!provenance) return Not recorded; return (
{provenance.recordedBy} diff --git a/ui/provider/src/pages/device-inventory.test.tsx b/ui/provider/src/pages/device-inventory.test.tsx index 57bed228..21fb41f8 100644 --- a/ui/provider/src/pages/device-inventory.test.tsx +++ b/ui/provider/src/pages/device-inventory.test.tsx @@ -152,7 +152,7 @@ describe('DeviceClaimDetail', () => { const replacement = { ...fixtureDevices[0], metadata: { ...fixtureDevices[0].metadata, name: 'rack-01-u12-synthetic-0002' }, - spec: { ...fixtureDevices[0].spec, provenance: { ...fixtureDevices[0].spec.provenance, recordedAt: '2026-02-01T00:00:00Z' } }, + spec: { ...fixtureDevices[0].spec, provenance: { ...fixtureDevices[0].spec.provenance!, recordedAt: '2026-02-01T00:00:00Z' } }, }; mockInventory({ data: toInventory(fixtureDeviceClaims, [fixtureDevices[0], replacement]) }); renderAt('/plugins/metal-datumapis-com/inventory/default/rack-01-u12'); diff --git a/ui/shared/fleet-api.ts b/ui/shared/fleet-api.ts index e6ecc6f7..89464c96 100644 --- a/ui/shared/fleet-api.ts +++ b/ui/shared/fleet-api.ts @@ -255,7 +255,7 @@ export interface DeviceClaim { kind?: string; metadata: ObjectMeta; spec: { - provenance: Provenance; + provenance?: Provenance; expectedIdentity: { manufacturer?: string; model: string; serial?: string }; lifecycle?: 'Installation'; displayName?: string; @@ -273,7 +273,7 @@ export interface Device { reportedPlacement?: ReportedPlacement; deviceTypeRef?: LocalReference; claimRef: LocalReference; - provenance: Provenance; + provenance?: Provenance; identity: { manufacturer?: string; model: string; serial?: string; systemUUID?: string; sourceIdentity?: ExternalReference }; assetTag?: string; displayName?: string; @@ -326,7 +326,7 @@ export interface PhysicalRecord { kind: 'Site' | 'Facility' | 'Rack' | 'Cable' | 'PowerFeed' | 'Manufacturer' | 'DeviceType'; spec: { displayName: string; - provenance: Provenance; + provenance?: Provenance; code?: string; canonicalName?: string; aliases?: string[]; From 3f02e83f07af8381f645f524c9e0dd9253eb3150 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sat, 21 Nov 2026 18:51:32 -0600 Subject: [PATCH 052/518] test(inventory): align Device catalog attachment with optional provenance --- docs/development/hardware-catalog.md | 8 +++++--- internal/api/inventory/v1alpha1/catalog_test.go | 9 +++------ 2 files changed, 8 insertions(+), 9 deletions(-) diff --git a/docs/development/hardware-catalog.md b/docs/development/hardware-catalog.md index 6fce748c..8bde44a0 100644 --- a/docs/development/hardware-catalog.md +++ b/docs/development/hardware-catalog.md @@ -35,11 +35,13 @@ shape pinning, physical qualification, reservations, or component reconciliation presence, and must match NetBoxImport provenance. A catalog edit changes no Device, claim, installed component, source observation, or reported placement. - Device gains an optional `deviceTypeRef: {name}` outside immutable `identity`. - A first explicit attachment must advance existing provenance; once attached, + Device provenance is optional under the physical-inventory API contract; an + explicit attachment does not require a synthetic receipt or timestamp advance. Once attached, the reference cannot be removed or rebound. Existing inline manufacturer/model, serial, sourceIdentity and claimRef remain unchanged and immutable. Imported - Devices retain their original NetBoxImport source evidence when an authorized - writer records an attachment; catalog edits never overwrite source observations. + Devices retain their immutable source identity when an authorized writer records + an attachment; catalog edits never overwrite source observations. Catalog + Manufacturer and DeviceType records still require their own provenance. ## Scope, guarantees, and reader safety diff --git a/internal/api/inventory/v1alpha1/catalog_test.go b/internal/api/inventory/v1alpha1/catalog_test.go index 525628de..521c6ac1 100644 --- a/internal/api/inventory/v1alpha1/catalog_test.go +++ b/internal/api/inventory/v1alpha1/catalog_test.go @@ -145,20 +145,17 @@ func TestCatalogUpdatesAndDeviceCompatibility(t *testing.T) { if errs := admit(t, "DeviceType", object(t, changed), object(t, model)); len(errs) == 0 { t.Fatal("accepted model identity mutation") } - for _, baseline := range []Device{syntheticDevice(), reportedDevice()} { + withoutProvenance := syntheticDevice() + withoutProvenance.Spec.Provenance = nil + for _, baseline := range []Device{syntheticDevice(), reportedDevice(), withoutProvenance} { attached := baseline.DeepCopyObject().(*Device) attached.Spec.DeviceTypeRef = &LocalReference{Name: model.Name} - if errs := admit(t, "Device", object(t, attached), object(t, baseline)); len(errs) == 0 { - t.Fatal("attachment did not require provenance") - } - attached.Spec.Provenance.RecordedAt = later(time.Hour) if errs := admit(t, "Device", object(t, attached), object(t, baseline)); len(errs) != 0 { t.Fatal(errs) } for _, reference := range []*LocalReference{nil, {Name: "another-model"}} { rebound := attached.DeepCopyObject().(*Device) rebound.Spec.DeviceTypeRef = reference - rebound.Spec.Provenance.RecordedAt = later(2 * time.Hour) if errs := admit(t, "Device", object(t, rebound), object(t, attached)); len(errs) == 0 { t.Fatal("accepted catalog removal or rebind") } From 318695ba30873230926ba8b7bfc26432f90dcdb0 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sat, 21 Nov 2026 18:55:10 -0600 Subject: [PATCH 053/518] test(ui): await completed host restoration before privacy assertions --- .../inventory-session-boundary.test.tsx | 24 ++++++++++++++----- 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/ui/provider/src/components/inventory-session-boundary.test.tsx b/ui/provider/src/components/inventory-session-boundary.test.tsx index f8cda862..d3878f7d 100644 --- a/ui/provider/src/components/inventory-session-boundary.test.tsx +++ b/ui/provider/src/components/inventory-session-boundary.test.tsx @@ -140,16 +140,28 @@ describe('host inventory session isolation', () => { it.each(['logout', 'failure'])('clears private data when foreground restoration observes %s', async outcome => { let expired = false; - mountHost(() => { + const loader = vi.fn(() => { if (expired && outcome === 'failure') throw new Response('Synthetic failure', { status: 503 }); if (expired) return { user: null }; return { user: { metadata: { uid: 'staff-a' } } }; - }, 'Visible inventory'); - await screen.findByText('Visible inventory'); + }); + let router!: ReturnType; + await act(async () => { router = mountHost(loader, 'Visible inventory'); }); + expect(screen.getByText('Visible inventory')).toBeInTheDocument(); + expect(loader).toHaveBeenCalledTimes(1); expired = true; - fireEvent(window, new Event('pagehide')); - fireEvent(window, new Event('pageshow')); - await waitFor(() => expect(screen.queryByText('Visible inventory')).not.toBeInTheDocument()); + await act(async () => { + fireEvent(window, new Event('pagehide')); + fireEvent(window, new Event('pageshow')); + }); + await waitFor(() => { + expect(loader).toHaveBeenCalledTimes(2); + expect(router.state.revalidation).toBe('idle'); + if (outcome === 'logout') expect(router.state.loaderData['layouts/milo.layout']).toEqual({ user: null }); + else expect(router.state.errors).not.toBeNull(); + expect(screen.queryByText('Visible inventory')).not.toBeInTheDocument(); + }); + router.dispose(); }); it('discards genuine hidden data and waits for visible verification before a fresh read', async () => { From 295107385e7a089932a90fa2268171f7c018843b Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sat, 21 Nov 2026 19:02:26 -0600 Subject: [PATCH 054/518] test(ui): settle host mounts before restoration events --- .../inventory-session-boundary.test.tsx | 28 ++-- .../reviewer-exact-staging.test.tsx | 149 ++++++++++++++++++ 2 files changed, 165 insertions(+), 12 deletions(-) create mode 100644 ui/provider/src/components/reviewer-exact-staging.test.tsx diff --git a/ui/provider/src/components/inventory-session-boundary.test.tsx b/ui/provider/src/components/inventory-session-boundary.test.tsx index d3878f7d..1f1a0e08 100644 --- a/ui/provider/src/components/inventory-session-boundary.test.tsx +++ b/ui/provider/src/components/inventory-session-boundary.test.tsx @@ -6,7 +6,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; import { InventorySessionBoundary, SessionQueries } from './inventory-session-boundary'; import { InventoryOperationContext, InventoryOperationInvalidated, InventoryOperationScope } from '../lib/inventory-operation'; -function mountHost(loader: () => unknown, content: React.ReactNode) { +async function mountHost(loader: () => unknown, content: React.ReactNode) { const router = createMemoryRouter([{ id: 'layouts/milo.layout', path: '/', @@ -14,7 +14,9 @@ function mountHost(loader: () => unknown, content: React.ReactNode) { element: , children: [{ index: true, element: {content} }], }]); - render(); + await act(async () => { render(); }); + expect(router.state.initialized).toBe(true); + expect(router.state.revalidation).toBe('idle'); return router; } @@ -29,7 +31,7 @@ describe('host inventory session isolation', () => { return

{query.data ?? 'Empty inventory cache'}

; } const loader = vi.fn(() => ({ user: { metadata: { uid: 'staff-a' } } })); - mountHost(loader, ); + await mountHost(loader, ); await screen.findByText('Visible inventory'); const before = scope!.begin(); const dispatched = scope!.begin(); @@ -63,7 +65,7 @@ describe('host inventory session isolation', () => { const query = useQuery({ queryKey: ['inventory'], queryFn: read, staleTime: Infinity }); return

{query.data}

; } - const router = mountHost(() => ({ user: { metadata: { uid: principal } } }), ); + const router = await mountHost(() => ({ user: { metadata: { uid: principal } } }), ); await screen.findByText('staff-a inventory 1'); const originalClient = client; await act(async () => { @@ -122,7 +124,7 @@ describe('host inventory session isolation', () => { }); it('keeps failed foreground restoration masked until the next restoration succeeds', async () => { - const router = mountHost(() => ({ user: { metadata: { uid: 'staff-a' } } }), 'Private inventory'); + const router = await mountHost(() => ({ user: { metadata: { uid: 'staff-a' } } }), 'Private inventory'); await screen.findByText('Private inventory'); let release!: () => void; vi.spyOn(router, 'revalidate').mockRejectedValueOnce(new Error('verification failed')).mockImplementationOnce(() => new Promise(resolve => { release = resolve; })); @@ -145,8 +147,7 @@ describe('host inventory session isolation', () => { if (expired) return { user: null }; return { user: { metadata: { uid: 'staff-a' } } }; }); - let router!: ReturnType; - await act(async () => { router = mountHost(loader, 'Visible inventory'); }); + const router = await mountHost(loader, 'Visible inventory'); expect(screen.getByText('Visible inventory')).toBeInTheDocument(); expect(loader).toHaveBeenCalledTimes(1); expired = true; @@ -173,7 +174,7 @@ describe('host inventory session isolation', () => { const query = useQuery({ queryKey: ['inventory'], queryFn: inventoryRead, staleTime: Infinity }); return

{query.data}

; } - mountHost(async () => { + await mountHost(async () => { if (++reads > 1) await new Promise(resolve => { release = resolve; }); return { user: { metadata: { uid: 'staff-a' } } }; }, ); @@ -196,7 +197,7 @@ describe('host inventory session isolation', () => { }); it('does not read inventory without an authenticated loader identity', async () => { - mountHost(() => ({ user: null }), 'Restricted inventory'); + await mountHost(() => ({ user: null }), 'Restricted inventory'); await screen.findByText('Your session has expired'); expect(screen.queryByText('Restricted inventory')).not.toBeInTheDocument(); }); @@ -209,7 +210,7 @@ describe('host inventory session isolation', () => { const query = useQuery({ queryKey: ['inventory'], queryFn: read }); return

{query.data}

; } - const router = mountHost(async () => { + const router = await mountHost(async () => { if (principal === 'staff-b') await new Promise(resolve => { release = resolve; }); return { user: { metadata: { uid: principal } } }; }, ); @@ -226,7 +227,7 @@ describe('host inventory session isolation', () => { it('hides background data and revalidates the actual host loader before restoring it', async () => { const loader = vi.fn(() => ({ user: { metadata: { uid: 'staff-a' } } })); - mountHost(loader, 'Restricted inventory'); + await mountHost(loader, 'Restricted inventory'); await screen.findByText('Restricted inventory'); const visibility = vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('hidden'); fireEvent(document, new Event('visibilitychange')); @@ -242,7 +243,7 @@ describe('host inventory session isolation', () => { it('only restores the newest foreground generation after successive pagehide and pageshow events', async () => { const releases: (() => void)[] = []; let reads = 0; - mountHost(async () => { + const router = await mountHost(async () => { if (++reads > 1) await new Promise(resolve => releases.push(resolve)); return { user: { metadata: { uid: 'staff-a' } } }; }, 'Private inventory'); @@ -257,5 +258,8 @@ describe('host inventory session isolation', () => { expect(screen.queryByText('Private inventory')).not.toBeInTheDocument(); await act(async () => releases[1]()); await screen.findByText('Private inventory'); + expect(reads).toBe(3); + expect(router.state.revalidation).toBe('idle'); + router.dispose(); }); }); diff --git a/ui/provider/src/components/reviewer-exact-staging.test.tsx b/ui/provider/src/components/reviewer-exact-staging.test.tsx new file mode 100644 index 00000000..5ccb2a5c --- /dev/null +++ b/ui/provider/src/components/reviewer-exact-staging.test.tsx @@ -0,0 +1,149 @@ +import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { createMemoryRouter, Outlet, RouterProvider } from 'react-router'; +import { afterEach, expect, it, vi } from 'vitest'; +import { InventoryManagement } from './inventory-management'; +import { DevicePlacementEdit } from './device-placement-edit'; +import { InventorySessionBoundary } from './inventory-session-boundary'; +import { inventoryPayload, INVENTORY_FIELD_MANAGER } from '../lib/inventory-management'; +import { fixturePhysicalDevices } from '../lib/fixtures'; + +const metadata = { name: 'review-only', namespace: 'default', uid: 'synthetic-review', resourceVersion: '7', managedFields: [{ manager: INVENTORY_FIELD_MANAGER }] }; +const facility = { ...inventoryPayload('Facility', { name: 'review-only', namespace: 'default', displayName: 'Original', recordedBy: 'synthetic', reference: '', facility: '', height: '' }), metadata }; +const device = { ...fixturePhysicalDevices[0], metadata, spec: { ...fixturePhysicalDevices[0].spec, provenance: undefined, reportedPlacement: undefined } }; +const response = (data: unknown, status = 200) => ({ ok: status < 400, status, json: async () => ({ data }) }); +afterEach(() => { vi.unstubAllGlobals(); vi.restoreAllMocks(); }); + +it('settled host keeps earlier foreground generations masked until the newest loader finishes', async () => { + const releases: (() => void)[] = []; + let reads = 0; + const loader = vi.fn(async () => { + if (++reads > 1) await new Promise(resolve => releases.push(resolve)); + return { user: { metadata: { uid: 'synthetic-staff' } } }; + }); + const router = createMemoryRouter([{ id: 'layouts/milo.layout', path: '/', loader, element: , children: [{ index: true, element: Private generation inventory }] }]); + await act(async () => { render(); }); + await screen.findByText('Private generation inventory'); + await act(async () => {}); + for (const expectedReads of [1, 2]) { + await act(async () => { + fireEvent(window, new Event('pagehide')); + fireEvent(window, new Event('pageshow')); + }); + await waitFor(() => expect(releases).toHaveLength(expectedReads)); + expect(screen.queryByText('Private generation inventory')).not.toBeInTheDocument(); + } + await act(async () => releases[0]()); + expect(screen.queryByText('Private generation inventory')).not.toBeInTheDocument(); + await act(async () => releases[1]()); + await screen.findByText('Private generation inventory'); + expect(router.state.revalidation).toBe('idle'); + expect(loader).toHaveBeenCalledTimes(3); + router.dispose(); +}); + +it.each(['label', 'location'].flatMap(mode => [401, 403, 404, 409, 422, 503, 0].map(status => ({ mode, status }))))('held $mode PATCH keeps visible focus inert then handles terminal $status', async ({ mode, status }) => { + let rejectWrite: (() => void) | undefined; + const original = mode === 'location' ? device : facility; + const fetch = vi.fn(async (url: string, init: RequestInit) => { + if (url.includes('selfsubjectaccessreviews')) return response({ status: { allowed: true } }); + if (init.method === 'GET') return response(original); + await new Promise(resolve => { rejectWrite = resolve; }); + if (status === 0) throw new TypeError('Synthetic connection lost after dispatch'); + return response({}, status); + }); + vi.stubGlobal('fetch', fetch); + const loader = vi.fn(() => ({ user: { metadata: { uid: 'synthetic-staff' } } })); + const content = mode === 'location' ? : ; + const router = createMemoryRouter([{ id: 'layouts/milo.layout', path: '/', loader, element: , children: [{ index: true, element: {content} }] }]); + render(); + const opener = await screen.findByRole('button', { name: mode === 'location' ? 'Add reported location' : 'Edit display name' }); + await waitFor(() => expect(opener).toBeEnabled()); + fireEvent.click(opener); + const input = screen.getByLabelText(mode === 'location' ? 'Correction reason' : 'Display name'); + fireEvent.change(input, { target: { value: 'Retain this draft' } }); + if (mode === 'location') { + fireEvent.change(screen.getByLabelText('Observation time (ISO 8601)'), { target: { value: '2026-01-02T00:00:00Z' } }); + fireEvent.change(screen.getByLabelText('Evidence reference'), { target: { value: 'ticket/synthetic' } }); + } else fireEvent.change(screen.getByLabelText('Recorded by'), { target: { value: 'synthetic' } }); + fireEvent.click(screen.getByRole('button', { name: mode === 'location' ? 'Save reported location' : 'Save display name' })); + await waitFor(() => expect(rejectWrite).toBeDefined()); + const markup = document.body.innerHTML; + const requestCount = fetch.mock.calls.length; + fireEvent(window, new Event('blur')); + fireEvent(window, new Event('focus')); + await act(async () => { await new Promise(resolve => setTimeout(resolve, 0)); }); + expect(document.body.innerHTML).toBe(markup); + expect(fetch).toHaveBeenCalledTimes(requestCount); + expect(loader).toHaveBeenCalledTimes(1); + expect(screen.getByLabelText(mode === 'location' ? 'Correction reason' : 'Display name')).toBe(input); + expect(input).toHaveValue('Retain this draft'); + expect(screen.getByRole('status')).not.toHaveTextContent(/outcome is unknown|saved\./i); + await act(async () => rejectWrite!()); + await waitFor(() => expect(screen.getByRole('status')).toHaveTextContent(/no longer valid|changed|disappeared|unknown|could not accept|session expired|no longer available/)); + expect(screen.getByRole('status')).not.toHaveTextContent(/saved\./i); + const save = screen.getByRole('button', { name: mode === 'location' ? 'Save reported location' : 'Save display name' }); + if (mode === 'label' && status === 422) expect(save).toBeEnabled(); + else expect(save).toBeDisabled(); + if (status === 503 || status === 0) expect(screen.getByRole('status')).toHaveTextContent('outcome is unknown'); + if (!(mode === 'label' && status === 422)) fireEvent.click(save); + fireEvent(window, new Event('blur')); + fireEvent(window, new Event('focus')); + await act(async () => { await new Promise(resolve => setTimeout(resolve, 0)); }); + expect(fetch).toHaveBeenCalledTimes(requestCount); + const writes = fetch.mock.calls.filter(([, init]) => init.method === 'PATCH'); + expect(writes).toHaveLength(1); + const patch = JSON.parse(writes[0][1].body as string); + expect(patch.slice(0, 2)).toEqual([{ op: 'test', path: '/metadata/uid', value: metadata.uid }, { op: 'test', path: '/metadata/resourceVersion', value: metadata.resourceVersion }]); + if (mode === 'location') { + expect(patch).toHaveLength(3); + expect(patch[2].path).toBe('/spec/reportedPlacement'); + expect(patch.some((entry: { path: string }) => entry.path.includes('provenance'))).toBe(false); + } + router.dispose(); +}); + +it.each(['logout', 'failure'].flatMap(outcome => ['pagehide', 'hidden'].flatMap(transition => ['immediate', 'held'].map(timing => ({ outcome, transition, timing })))))('settled host $transition restoration handles $timing $outcome', async ({ outcome, transition, timing }) => { + let expired = false; + let release: (() => void) | undefined; + const loader = vi.fn(async () => { + if (!expired) return { user: { metadata: { uid: 'synthetic-staff' } } }; + if (timing === 'held') await new Promise(resolve => { release = resolve; }); + if (outcome === 'failure') throw new Response('Synthetic failure', { status: 503 }); + return { user: null }; + }); + const router = createMemoryRouter([{ id: 'layouts/milo.layout', path: '/', loader, element: , errorElement:

Host failure

, children: [{ index: true, element: Private review inventory }] }]); + await act(async () => { render(); }); + await screen.findByText('Private review inventory'); + await act(async () => {}); + expired = true; + const visibility = vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('visible'); + await act(async () => { + if (transition === 'hidden') { + visibility.mockReturnValue('hidden'); + fireEvent(document, new Event('visibilitychange')); + } else fireEvent(window, new Event('pagehide')); + }); + expect(screen.queryByText('Private review inventory')).not.toBeInTheDocument(); + await act(async () => { + if (transition === 'hidden') { + visibility.mockReturnValue('visible'); + fireEvent(document, new Event('visibilitychange')); + } else fireEvent(window, new Event('pageshow')); + }); + if (timing === 'held') { + await waitFor(() => expect(release).toBeDefined()); + expect(router.state.revalidation).toBe('loading'); + expect(screen.queryByText('Private review inventory')).not.toBeInTheDocument(); + await act(async () => release!()); + } + await waitFor(() => expect(router.state.revalidation).toBe('idle')); + expect(loader).toHaveBeenCalledTimes(2); + if (outcome === 'logout') expect(router.state.loaderData['layouts/milo.layout']).toEqual({ user: null }); + else expect(router.state.errors).not.toBeNull(); + expect(screen.queryByText('Private review inventory')).not.toBeInTheDocument(); + fireEvent(window, new Event('focus')); + await act(async () => {}); + expect(screen.queryByText('Private review inventory')).not.toBeInTheDocument(); + expect(loader).toHaveBeenCalledTimes(2); + router.dispose(); +}); From 3804b620965427a2e7a580022d47f67d1a42e1fb Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sat, 21 Nov 2026 19:06:51 -0600 Subject: [PATCH 055/518] fix: quarantine invalid catalog target namespaces --- docs/development/hardware-catalog.md | 6 ++-- hack/netbox_catalog.py | 5 +++- hack/test_netbox_catalog.py | 29 +++++++++++++++++++ .../api/inventory/v1alpha1/catalog_test.go | 26 +++++++++++++++++ 4 files changed, 63 insertions(+), 3 deletions(-) diff --git a/docs/development/hardware-catalog.md b/docs/development/hardware-catalog.md index 8bde44a0..62aae3e0 100644 --- a/docs/development/hardware-catalog.md +++ b/docs/development/hardware-catalog.md @@ -98,6 +98,7 @@ python3 hack/netbox_catalog.py --snapshot /private/netbox.json \ The synthetic [mapping fixture](../../hack/testdata/catalog/mapping.json) shows the format. `target` requires `project`, `namespace`, and `writer: DirectAPI`. +Namespaces must be DNS labels of 1–63 characters, not dotted resource names. The Fleet snapshot must attest `collections: [Manufacturer, DeviceType]`, contain that same target, and include both complete collections, including empty ones. Manufacturer `sourceID` and DeviceType `sourceID`/`manufacturerSourceID` are @@ -142,8 +143,9 @@ assignment correction/rebinding and accepted-plan revision pinning need follow-u An explicit direct-API attachment must use the Device's current owner, require fresh authorized reads of both same-namespace targets, retain exact inputs, and -test metadata UID and resourceVersion before adding the reference and advancing -provenance. UIDs are request preconditions, never spec references. Use Strict +test metadata UID and resourceVersion before adding the reference. Device +provenance is optional; attachment does not require advancing or inventing it. +UIDs are request preconditions, never spec references. Use Strict field validation. A failed or uncertain request requires readback, not a blind retry. No live attachment is performed here. Correcting an already attached reference requires a reviewed compatibility contract; do not weaken identity diff --git a/hack/netbox_catalog.py b/hack/netbox_catalog.py index ab460963..b14eada7 100644 --- a/hack/netbox_catalog.py +++ b/hack/netbox_catalog.py @@ -108,7 +108,10 @@ def plan(snapshot, mapping, existing, recorded_by, recorded_at): fields(mapping, ("revision", "target", "manufacturers", "deviceTypes")) target = mapping["target"] fields(target, ("project", "namespace", "writer")) - if target["writer"] != "DirectAPI" or not name_ok(target["project"]) or not name_ok(target["namespace"]): + namespace = target["namespace"] + if not isinstance(namespace, str) or not 1 <= len(namespace) <= 63 or not re.fullmatch(r"[a-z0-9](?:[-a-z0-9]*[a-z0-9])?", namespace): + raise ValueError("target namespace requires a DNS label of at most 63 characters") + if target["writer"] != "DirectAPI" or not name_ok(target["project"]): raise ValueError("catalog requires an explicit operator-managed DirectAPI target") revision = text(mapping["revision"]) text(recorded_by) diff --git a/hack/test_netbox_catalog.py b/hack/test_netbox_catalog.py index c26274c9..d9614ada 100644 --- a/hack/test_netbox_catalog.py +++ b/hack/test_netbox_catalog.py @@ -25,6 +25,35 @@ def plan(snapshot, mapping, existing): class CatalogTests(unittest.TestCase): + def test_namespace_boundaries(self): + for namespace in ("a", "a" * 63, "has.dot", "a" * 64, "", "-a", "a-", "A", None, False): + snapshot, mapping, existing = fixture() + mapping["target"]["namespace"] = namespace + existing["target"]["namespace"] = namespace + valid = namespace in ("a", "a" * 63) + with self.subTest(namespace=namespace): + if valid: + result = plan(snapshot, mapping, existing) + self.assertEqual(2, len(result["items"])) + self.assertTrue(all(item["metadata"]["namespace"] == namespace for item in result["items"])) + else: + with self.assertRaises(ValueError): + plan(snapshot, mapping, existing) + with tempfile.TemporaryDirectory() as directory: + files = [] + for index, value in enumerate((snapshot, mapping, existing)): + path = Path(directory) / f"{index}.json" + path.write_text(json.dumps(value)) + files.append(str(path)) + result = subprocess.run(["python3", str(Path(catalog.__file__)), "--snapshot", files[0], "--mapping", files[1], "--existing", files[2], "--recorded-by", "synthetic", "--recorded-at", "2026-11-21T01:00:00Z"], capture_output=True, text=True) + self.assertEqual(0 if valid else 1, result.returncode) + report = json.loads(result.stdout) + if valid: + self.assertEqual(2, len(report["items"])) + else: + self.assertTrue(report["quarantined"]) + self.assertEqual([], report["items"]) + def test_source_id_length_boundaries(self): for convert in (str, int): for size in (1, 253, 254): diff --git a/internal/api/inventory/v1alpha1/catalog_test.go b/internal/api/inventory/v1alpha1/catalog_test.go index 521c6ac1..0313965a 100644 --- a/internal/api/inventory/v1alpha1/catalog_test.go +++ b/internal/api/inventory/v1alpha1/catalog_test.go @@ -6,15 +6,41 @@ import ( "fmt" "os" "reflect" + "strings" "testing" "time" + metavalidation "k8s.io/apimachinery/pkg/api/validation" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/util/validation/field" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/fake" ) +func TestCatalogNamespaceBoundaries(t *testing.T) { + for _, namespace := range []string{"a", strings.Repeat("a", 63), "has.dot", strings.Repeat("a", 64)} { + t.Run(namespace, func(t *testing.T) { + manufacturer, model := catalogRecords() + for _, record := range []client.Object{manufacturer, model} { + record.SetNamespace(namespace) + metadata := metav1.ObjectMeta{Name: record.GetName(), Namespace: namespace} + errors := metavalidation.ValidateObjectMeta(&metadata, true, metavalidation.NameIsDNSSubdomain, field.NewPath("metadata")) + valid := namespace == "a" || namespace == strings.Repeat("a", 63) + if (len(errors) == 0) != valid { + t.Fatalf("unexpected metadata validation: %v", errors) + } + if valid { + candidate := object(t, record) + if errors := admit(t, candidate["kind"].(string), candidate, nil); len(errors) != 0 { + t.Fatal(errors) + } + } + } + }) + } +} + func TestImportedCatalogCandidatesPassAdmission(t *testing.T) { data, err := os.ReadFile("../../../../hack/testdata/catalog/candidates.json") if err != nil { From 5a1aeb5546afb9b1233ba63075b407e11179853d Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sat, 21 Nov 2026 19:12:28 -0600 Subject: [PATCH 056/518] docs(inventory): narrow the no-migration claim for retired fields A stored Device whose only identity was sourceIdentity prunes to an identity with no serial or system UUID, so it no longer validates and, because identity is immutable, has to be deleted and recreated. Pin that case in a test, state it and the reportedPlacement case in the compatibility notes, and describe what CRD validation ratcheting still allows. Co-Authored-By: Claude Opus 5.5 --- docs/operations/physical-inventory.md | 25 ++++++++++++++----- internal/api/inventory/v1alpha1/crd_test.go | 27 ++++++++++++++++++++- 2 files changed, 45 insertions(+), 7 deletions(-) diff --git a/docs/operations/physical-inventory.md b/docs/operations/physical-inventory.md index 287ec775..fcc092b0 100644 --- a/docs/operations/physical-inventory.md +++ b/docs/operations/physical-inventory.md @@ -333,15 +333,28 @@ each spec change to advance `provenance.recordedAt`, and accepted Device `reportedPlacement.method`/`snapshotDigest`. These fields are gone. The served and stored version remains `v1alpha1`; this is an alpha breaking change. -No migration is needed. Each schema is structural and does not preserve unknown -fields, so the API server prunes the removed fields from stored objects when it -reads them and drops them from requests; they leave storage on the next write. +Records that still validate without the removed fields need no migration. Each +schema is structural and does not preserve unknown fields, so the API server +prunes the removed fields from stored objects when it reads them and drops them +from requests; they leave storage on the next write. + +Two kinds of stored record no longer validate once pruned: + +- A Device whose only identity was `identity.sourceIdentity` is left with no + serial or system UUID. Because `identity` is immutable, delete it and create + a new Device with a serial or system UUID. +- A Device whose `reportedPlacement` lacks `reason` or `reference` must gain + both the next time its report changes. + +Until then, such a record can still be read and deleted, and it accepts +metadata or status updates that leave the invalid fields unchanged, through +CRD validation ratcheting. Ratcheting is always on from Kubernetes 1.33, and +Milo builds on 1.37. Any other spec change is rejected until the record is +valid. A client that still sends them is not rejected unless it asks for strict field validation: by default the server drops the fields and returns an unknown-field warning, while strict validation (the `kubectl` default) returns an error. -Remove the fields from GitOps sources and other writers. An old reported -placement that lacks `reason` or `reference` must gain both the next time its -report changes. +Remove the fields from GitOps sources and other writers. Retirement happened in two steps so that GitOps-applied records could drop the fields first: provenance became optional and stopped gating edits, then the diff --git a/internal/api/inventory/v1alpha1/crd_test.go b/internal/api/inventory/v1alpha1/crd_test.go index 79960816..402073dc 100644 --- a/internal/api/inventory/v1alpha1/crd_test.go +++ b/internal/api/inventory/v1alpha1/crd_test.go @@ -282,7 +282,7 @@ func TestEditsDoNotNeedARecordingTimestamp(t *testing.T) { // TestRetiredFieldsArePruned shows that objects stored with the retired // provenance, source identity, component source and report import fields // lose them when read or written through the structural schema, and that -// what remains is admitted. No migration is needed. +// what remains is admitted when it still has a serial or system UUID. func TestRetiredFieldsArePruned(t *testing.T) { legacy := object(t, reportedDevice()) spec := legacy["spec"].(map[string]any) @@ -338,6 +338,31 @@ func TestRetiredFieldsArePruned(t *testing.T) { } } +// TestSourceOnlyIdentityDoesNotSurvivePruning pins the case that does need +// action: a Device whose only identity was sourceIdentity prunes to an +// identity without a serial or system UUID, which is no longer valid. Because +// identity is immutable, such a Device has to be deleted and recreated. +func TestSourceOnlyIdentityDoesNotSurvivePruning(t *testing.T) { + legacy := object(t, syntheticDevice()) + spec := legacy["spec"].(map[string]any) + identity := spec["identity"].(map[string]any) + delete(identity, "serial") + delete(identity, "systemUUID") + identity["sourceIdentity"] = map[string]any{"system": "example", "type": "device", "id": "1"} + var schema apiextensions.JSONSchemaProps + if err := extensionsv1.Convert_v1_JSONSchemaProps_To_apiextensions_JSONSchemaProps(loadCRDs(t)["Device"].Spec.Versions[0].Schema.OpenAPIV3Schema, &schema, nil); err != nil { + t.Fatal(err) + } + structural, err := structuralschema.NewStructural(&schema) + if err != nil { + t.Fatal(err) + } + pruning.Prune(legacy, structural, true) + if errs := admit(t, "Device", legacy, nil); len(errs) == 0 { + t.Fatal("a Device with only a pruned source identity was admitted") + } +} + func TestClaimBindingAndIdentityAreImmutable(t *testing.T) { old := object(t, syntheticDevice()) for name, mutate := range map[string]func(*Device){ From 110e1a4241e9109420f6f5650b36998c5d9eda9f Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sat, 21 Nov 2026 19:16:16 -0600 Subject: [PATCH 057/518] fix(ui): align inventory with Datum and preserve tab navigation --- .../datum-inventory-ui-alignment.md | 155 ++++++++++++ .../src/components/device-placement-edit.tsx | 34 +-- .../src/components/inventory-access-state.tsx | 12 +- .../inventory-hardware-fields.test.tsx | 11 + .../components/inventory-hardware-fields.tsx | 27 +- .../src/components/inventory-location.tsx | 19 +- .../src/components/inventory-management.tsx | 16 +- .../src/components/inventory-navigation.tsx | 63 +++++ .../components/inventory-session-boundary.tsx | 33 ++- .../inventory-stable-controls.test.tsx | 3 + .../inventory-tab-navigation.test.tsx | 164 ++++++++++++ .../src/components/physical-inventory.css | 83 +++---- .../components/physical-inventory.test.tsx | 27 +- .../src/components/physical-inventory.tsx | 233 +++++++----------- ui/provider/src/lib/api.ts | 7 +- .../src/pages/device-inventory-list.tsx | 15 +- .../src/pages/device-inventory.test.tsx | 4 +- ui/provider/vitest.config.ts | 3 +- 18 files changed, 653 insertions(+), 256 deletions(-) create mode 100644 docs/development/datum-inventory-ui-alignment.md create mode 100644 ui/provider/src/components/inventory-navigation.tsx create mode 100644 ui/provider/src/components/inventory-tab-navigation.test.tsx diff --git a/docs/development/datum-inventory-ui-alignment.md b/docs/development/datum-inventory-ui-alignment.md new file mode 100644 index 00000000..21c0882e --- /dev/null +++ b/docs/development/datum-inventory-ui-alignment.md @@ -0,0 +1,155 @@ +# Inventory Datum UI alignment and stable navigation + +## Scope and sources + +This change starts at PR104 commit +`4810fbf8b75fe50731a988326dd057f56e6b16cb`, including its visible blur/focus +no-op and optional-provenance behavior. It does not merge PR104's subsequent +test-synchronization commit `318695ba30873230926ba8b7bfc26432f90dcdb0` or PR107's +unmerged catalog work. It is a stacked change targeting +`t3/preserve-inventory-controls-on-blur`; retarget to the default branch only +after PR104 merges and review the resulting diff. + +Design inputs are the [Fleet architecture](../architecture/design.md), the +[pinned inventory proposal](../proposals/fleet-management/inventory.md), and the +[existing inventory UI contract](staff-inventory-ui.md). These distinguish physical +records from allocation, installation, verification, and authority. + +Both frozen lockfiles resolve the declared `@datum-cloud/datum-ui: ^3.5.0` to +3.7.0. The implementation uses that installed package's README, exported type +declarations, emitted component source, and theme styles. No package manifest or +lockfile changes are needed. This is actual component adoption, not a root +package import plus custom lookalike controls. + +Host routing was inspected at staff-portal commit +`a0c4cd3e4bd9e0343ffe3310caaa25b160073b41`: + +- [`milo.layout.tsx`](https://github.com/datum-cloud/staff-portal/blob/a0c4cd3e4bd9e0343ffe3310caaa25b160073b41/app/layouts/milo.layout.tsx) + calls `requireStaffUser` in its loader and supplies no query-only + `shouldRevalidate` exemption. +- [`plugin-page-outlet.tsx`](https://github.com/datum-cloud/staff-portal/blob/a0c4cd3e4bd9e0343ffe3310caaa25b160073b41/app/modules/plugins/client/plugin-page-outlet.tsx) + keys page routes and error resets by path, not inventory query parameters. +- [`federation-host.ts`](https://github.com/datum-cloud/staff-portal/blob/a0c4cd3e4bd9e0343ffe3310caaa25b160073b41/app/modules/plugins/client/federation-host.ts) + shares the Button and Card modules, with the host's versions winning. Its + package manifest currently declares Datum UI `^3.12.1` and React Router + `^8.3.1`; that is source evidence, not verification of any deployed host. + +No shallow-routing support is assumed. No host code, router loader, authentication +policy, or dependency version is changed here. + +## Implemented component alignment + +| Surface | Actual Datum UI use | +| --- | --- | +| Directory search, namespace, create/edit and reported-location inputs | `Input` and `Label`, preserving input types, bounds, required attributes, controlled values and accessible field names | +| Refresh, clear, component/lane add/remove, location actions, rack face controls | `Button`, explicitly using `htmlType` so auxiliary actions cannot submit a form | +| Inventory category navigation | `LinkButton as={Link}` with native router links and `aria-current`; no nested button/link or custom click/history implementation | +| Directory, physical components, cable lanes, equipment | `Table`, `TableHeader`, `TableBody`, `TableRow`, `TableHead`, `TableCell`, and `TableCaption` | +| Access guidance | `Card`, `CardContent`, `Title`, and `Text`, retaining named region, heading, retry and error semantics | +| Section headings | `Title`; the programmatically focused detail heading uses `titleVariants` on its existing ref-bearing `h2` | + +The installed Button implementation renders a button even though its type surface +includes `asChild`; navigation therefore uses the implemented `LinkButton` API. +The pre-existing outer Fleet tabs, legacy claim table, and page-title components +already use Datum components and are not redesigned. + +Removed custom input, button, heading, table decoration and category-link skin +rules so they no longer override the adopted components. Remaining specialized +geometry and responsive layout use Datum semantic color/radius tokens instead of +hardcoded fallback palettes. The existing focusable table region retains scroll +ownership; the library's inner table container does not add a second scroller. + +## Stable tabs without bypassing host authority + +The directory's Fleet header and category navigation now live outside the private +session boundary. They contain only fixed category labels, never record names, +namespace values, counts or management controls. Counts remain in authorized +content. Hosted category links therefore remain present during initial loading, +permission denial and session checking, and select access guidance when denied. +The default hosted category stays Devices rather than silently choosing a different +readable category while the static tab still says Devices. + +For same-path navigation changing only `kind`, `record`, or `namespace`, without +a form submission or explicit revalidation: + +1. Normal React Router links run the real host loader. Back/forward and direct + namespaced links retain their URLs. No extra authority request is added. +2. Pending host checks still suspend read publication, invalidate operations, + and unmount private content/forms. Only static tabs and localized + “Checking inventory access…” text remain; the whole page is not replaced + with skeletons. +3. A successfully returned **same principal** may reuse its isolated QueryClient's + previously authorized inventory snapshot. The collection key no longer uses + per-mount `useId`; it remains scoped to plugin, provider project and that + private session client. It is retained for five minutes while inactive and is + fresh until explicit refresh/invalidation within that session. +4. Operation lifetimes restart after every completed host transition, including + batched transitions that never paint a pending frame. Reusing collection data + never revives an old operation, immutable edit baseline or draft. + +Explicit host revalidation, changed principal (including A–B–A), logout, hidden +visibility/pagehide and non-presentation navigation continue to discard the +session client or invalidate its generation. Read denials redact records; cached +data does not win over an observed error. Fresh form permission checks and guarded +submit-time exact reads/permission checks remain unchanged. Visible window +blur/focus still performs no request, remount, disabling or baseline reset. + +This intentionally trades seamless private-content continuity for a short localized +access-check message while the host is pending. It does not promise zero host +loader requests. Same-session presentation changes avoid redundant seven-collection +inventory reads; explicit refresh and real authority changes fetch again. Snapshot +reuse is not a live freshness or newly granted permission claim. + +## Deliberate remaining gaps + +- Native selects remain for filters, record references, component types, endpoints + and reported geometry. Datum 3.7.0 exports a Radix Select, not a drop-in native + select. Replacing these safely needs a separate keyboard, required/empty-value, + implicit-label, native fieldset-disabling and portal review. This change does + not invent an adapter or claim these are Datum Selects. +- Native details/summary, fieldsets/legends, semantic definition lists, responsive + form grids and bespoke rack geometry remain. Rack overlap and occupancy meaning + are unchanged. The source-defined muted palette is used, not a new palette. +- PR107's catalog views are not integrated or covered. Audit them after that work + merges; this is not catalog UX parity. +- No authenticated staff-portal/Safari acceptance, deployed Module Federation + compatibility, production operation, or live API write is claimed. The parent + must review and run its deployment/host gates separately. + +## Validation + +- Provider: `pnpm --dir ui/provider test` — 34 files, 516 tests; typecheck and + production build pass. Coverage asserts actual library slots/variants, field + and button semantics, visible blur/focus node identity, permissions, immutable + baselines, unknown outcomes and existing read/write fences. +- New route integration tests use the actual inventory page and host loader: + stable tab DOM during a held loader, seven total collection reads across + category/detail/back/forward transitions, direct links, immediate/batched + navigation management readiness, in-flight create fencing, and fresh reads on + principal, logout, denial, hidden/pagehide, explicit revalidation and unknown + query changes. These do not mock Datum components. +- Consumer: `pnpm --dir ui/consumer test` — 3 files, 44 tests; typecheck and + production build pass. Consumer implementation is untouched. +- Documentation: `bash hack/validate-doc-links.sh`; whitespace: `git diff --check`. +- Synthetic rendering: the existing `session-fixture.html` uses in-memory API + responses and never writes a live API. The test Vite config now includes the + existing Tailwind plugin so this harness compiles the same Datum tokens and + component utilities instead of inspecting unprocessed CSS. +- Local headless Brave/Chromium 146 checks at 1280px and 390px inspected directory, + create, display-name edit, reported-location edit and rack rendering, light/dark + tokens, horizontal overflow, keyboard rack-face activation, exact visible + blur/focus markup/counters, stable tab nodes during held host loading and denied + read redaction. Seven collection reads across loaded category/detail transitions; + fourteen after an explicit denied refresh; zero writes and no page errors. + Shared preview snapshots timed out, so these checks used a fresh local headless + browser profile, not an authenticated browser session. + +To inspect the same synthetic harness locally: + +```sh +pnpm --dir ui/provider exec vite --config vitest.config.ts --host 127.0.0.1 --port 7793 +``` + +Open `/session-fixture.html`; the existing `inventorySessionFixture` exposes held +host responses, principal changes, denial and read/write counters. Local screenshots +are transient verification artifacts, not checked-in production evidence. diff --git a/ui/provider/src/components/device-placement-edit.tsx b/ui/provider/src/components/device-placement-edit.tsx index 888f823a..f9f73c3c 100644 --- a/ui/provider/src/components/device-placement-edit.tsx +++ b/ui/provider/src/components/device-placement-edit.tsx @@ -1,3 +1,7 @@ +import { Input } from '@datum-cloud/datum-ui/input'; +import { Label } from '@datum-cloud/datum-ui/label'; +import { Button } from '@datum-cloud/datum-ui/button'; +import { Title } from '@datum-cloud/datum-ui/typography'; import { useContext, useLayoutEffect, useRef, useState, type ComponentProps, type FormEvent } from 'react'; import { useQueryClient } from '@tanstack/react-query'; import type { Device, PhysicalRecord } from '../../../shared/fleet-api'; @@ -85,11 +89,11 @@ function DevicePlacementForm({ device, locations, issues }: { device: Device; lo } finally { setPending(false); } } return
-

Reported location

+ Reported location

Correct a record, not a physical move, installation handover, or reservation. Identity and claim binding stay unchanged. Blank geometry means unknown; model and claim dimensions are not copied.

{!editable ?

Legacy GitOps-managed or unavailable Devices are outside this editor.

: !permitted &&

Device management permission must be confirmed before correcting location.

}

{message || (!ready || permission.isFetching ? 'Management: verification pending.' : open && blocked ? 'Management: close and reopen this form to continue.' : allowed ? 'Management: access checked.' : 'Management: unavailable.')}

- {permitted && !open && !needsRefresh && } + }}>{device.spec.reportedPlacement ? 'Correct location' : 'Add reported location'}} {open && permitted &&

Source: manual observation/correction. Original import provenance is retained. Authenticated actor history uses existing resource audit logs, not this form's attribution.

- - - - - - - - - - + + + + + + + + + +

Do not include credentials or secrets in evidence.

- - + +
}
; } diff --git a/ui/provider/src/components/inventory-access-state.tsx b/ui/provider/src/components/inventory-access-state.tsx index 2541c768..328d64f4 100644 --- a/ui/provider/src/components/inventory-access-state.tsx +++ b/ui/provider/src/components/inventory-access-state.tsx @@ -1,5 +1,7 @@ import { Link, useParams } from 'react-router'; import { Button } from '@datum-cloud/datum-ui/button'; +import { Card, CardContent } from '@datum-cloud/datum-ui/card'; +import { Title, Text } from '@datum-cloud/datum-ui/typography'; export function InventoryAccessState({ status, onRetry }: { status: number; onRetry?: () => void }) { const { slug } = useParams(); @@ -11,13 +13,15 @@ export function InventoryAccessState({ status, onRetry }: { status: number; onRe : status === 404 ? 'This inventory API is not available here. Your administrator can check the provider project configuration.' : 'We could not load this section. Other inventory sections may still be available. Please try again shortly.'; - return
-

{title}

-

{message}

+ return + + {title} + {message}
{slug ? 'Back to Bare Metal' : 'Back to staff portal'} {status === 401 && slug && Return to staff portal} {![401, 403, 404].includes(status) && onRetry && }
-
; + + ; } diff --git a/ui/provider/src/components/inventory-hardware-fields.test.tsx b/ui/provider/src/components/inventory-hardware-fields.test.tsx index 19c8d8d0..4469f5eb 100644 --- a/ui/provider/src/components/inventory-hardware-fields.test.tsx +++ b/ui/provider/src/components/inventory-hardware-fields.test.tsx @@ -3,6 +3,8 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { afterEach, expect, it, vi } from 'vitest'; import { InventoryManagement } from './inventory-management'; import { fixturePhysicalClaims, fixturePhysicalDevices, fixturePhysicalRecords } from '../lib/fixtures'; +import { buttonVariants } from '@datum-cloud/datum-ui/button'; +import { cn } from '@datum-cloud/datum-ui/utils'; const claim = { ...fixturePhysicalClaims[0], metadata: { ...fixturePhysicalClaims[0].metadata, uid: 'plan-uid', resourceVersion: '1' }, spec: { ...fixturePhysicalClaims[0].spec, lifecycle: 'Installation' as const } }; const device = { ...fixturePhysicalDevices[0], metadata: { ...fixturePhysicalDevices[0].metadata, uid: 'device-uid', resourceVersion: '1' } }; @@ -25,6 +27,15 @@ it('registers hardware through the real form without changing claim identity', a writes.push(JSON.parse(init.body as string)); return response({ metadata: { uid: 'new-uid' } }); })); renderForm('Device'); await open('Device'); + const model = screen.getByLabelText('Model'); + expect(model).toHaveAttribute('data-slot', 'input'); + expect(model.closest('label')).toHaveAttribute('data-slot', 'label'); + expect(model).toBeRequired(); + expect(screen.getByLabelText('Management namespace')).toHaveAttribute('data-slot', 'input'); + expect(screen.getByLabelText('Management namespace')).toBeDisabled(); + const addComponent = screen.getByRole('button', { name: 'Add component' }); + expect(addComponent).toHaveClass(...cn(buttonVariants({ type: 'secondary', theme: 'outline', size: 'small' })).split(' ')); + expect(addComponent).toHaveAttribute('type', 'button'); fireEvent.change(screen.getByLabelText('Installation plan'), { target: { value: 'plan-uid' } }); fireEvent.change(screen.getByLabelText('Model'), { target: { value: 'Recorded model' } }); fireEvent.change(screen.getByLabelText('Serial number'), { target: { value: 'SYNTHETIC-NEW' } }); diff --git a/ui/provider/src/components/inventory-hardware-fields.tsx b/ui/provider/src/components/inventory-hardware-fields.tsx index 8e37e17c..b8a141f5 100644 --- a/ui/provider/src/components/inventory-hardware-fields.tsx +++ b/ui/provider/src/components/inventory-hardware-fields.tsx @@ -1,3 +1,6 @@ +import { Input } from '@datum-cloud/datum-ui/input'; +import { Label } from '@datum-cloud/datum-ui/label'; +import { Button } from '@datum-cloud/datum-ui/button'; import type { Device, DeviceClaim, PhysicalComponent, PhysicalRecord } from '../../../shared/fleet-api'; import { cableMedia, componentTypes, isTermination, type ReferencedEndpoint } from '../lib/inventory-hardware'; import type { InventoryFormValues } from '../lib/inventory-management'; @@ -5,25 +8,25 @@ import type { InventoryFormValues } from '../lib/inventory-management'; export function InventoryHardwareFields({ kind, values, onChange, namespace, claims, devices, feeds, locations }: { kind: 'Device' | 'Cable' | 'DeviceClaim'; values: InventoryFormValues; onChange: (values: InventoryFormValues) => void; namespace: string; claims: DeviceClaim[]; devices: Device[]; feeds: PhysicalRecord[]; locations: PhysicalRecord[] }) { const field = (name: keyof InventoryFormValues, value: unknown) => onChange({ ...values, [name]: value }); if (kind === 'DeviceClaim') return
New installation plan - -
{([['manufacturer', 'Expected manufacturer'], ['model', 'Expected model'], ['serial', 'Expected serial (optional)']] as const).map(([name, label]) => )}
+ +
{([['manufacturer', 'Expected manufacturer'], ['model', 'Expected model'], ['serial', 'Expected serial (optional)']] as const).map(([name, label]) => )}

This records a new installation at a facility or rack with position unknown. It reserves no units and moves no existing equipment. Placement is immutable; corrections require a separately reviewed handover.

; if (kind === 'Device') return <>
Installation & identity - +

Identity and installation binding cannot be changed later. Existing registrations are kept; this does not replace hardware or identify the active device. Legacy slot bindings are not offered.

-
{([['manufacturer', 'Manufacturer'], ['model', 'Model'], ['serial', 'Serial number'], ['systemUUID', 'System UUID'], ['assetTag', 'Asset tag']] as const).map(([name, label]) => )}
+
{([['manufacturer', 'Manufacturer'], ['model', 'Model'], ['serial', 'Serial number'], ['systemUUID', 'System UUID'], ['assetTag', 'Asset tag']] as const).map(([name, label]) => )}

A real serial or system UUID is required. Leave unknown values blank; do not use an asset tag or provider ID as a serial.

Physical components

Record physical ports and parts only. Empty means not recorded, not absent. No logical interfaces or IP assignments.

{(values.components ?? []).map((component, index) =>
-
{(['id', 'name', 'connector'] as const).map(name => )} - - -
+
{(['id', 'name', 'connector'] as const).map(name => )} + + +
)} - +
; const endpoints: { key: string; label: string; endpoint: ReferencedEndpoint }[] = []; @@ -41,10 +44,10 @@ export function InventoryHardwareFields({ kind, values, onChange, namespace, cla } const lanes = values.cableLanes ?? [{ id: 'lane-1' }]; return <> - +
Physical endpoints

Only readable recorded ports with known positions are offered. Review existing cable connections before saving. Recording a cable does not reserve ports or verify a working link.

- {lanes.map((lane, index) =>
{(['a', 'b'] as const).map(side => )}
{lanes.length > 1 && }
)} - + {lanes.map((lane, index) =>
{(['a', 'b'] as const).map(side => )}
{lanes.length > 1 && }
)} +
; } diff --git a/ui/provider/src/components/inventory-location.tsx b/ui/provider/src/components/inventory-location.tsx index b068a3f4..9b72ff89 100644 --- a/ui/provider/src/components/inventory-location.tsx +++ b/ui/provider/src/components/inventory-location.tsx @@ -1,3 +1,6 @@ +import { Button } from '@datum-cloud/datum-ui/button'; +import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from '@datum-cloud/datum-ui/table'; +import { Title } from '@datum-cloud/datum-ui/typography'; import { useState } from 'react'; import { Link } from 'react-router'; import { slotKey, type Inventory, type InventorySlot } from '../inventory'; @@ -15,9 +18,9 @@ export function rackGeometry(slot: InventorySlot, rack: PhysicalRecord) { } function Equipment({ slots, devicesDenied, inventory }: { slots: EquipmentPlacement[]; devicesDenied: boolean; inventory: Inventory }) { - return
- {slots.map(slot => )} -
EquipmentClaim / registration historyLocation / Reported placement
{devicesDenied ? 'Device details unavailable' : slot.devices.length ? slot.devices.map(device =>
{device.spec.displayName || device.metadata.name}
) : 'No device registration recorded'}{slot.devices.length > 1 && Multiple registrations · active device unknown}
{slot.claim ? {slot.claim.spec.displayName || slot.claim.metadata.name} : 'Claim details unavailable'}{reportedPlacementLabel(slot, inventory)}
; + return
EquipmentClaim / registration historyLocation / Reported placement + {slots.map(slot => {devicesDenied ? 'Device details unavailable' : slot.devices.length ? slot.devices.map(device =>
{device.spec.displayName || device.metadata.name}
) : 'No device registration recorded'}{slot.devices.length > 1 && Multiple registrations · active device unknown}
{slot.claim ? {slot.claim.spec.displayName || slot.claim.metadata.name} : 'Claim details unavailable'}{reportedPlacementLabel(slot, inventory)}
)} +
; } function RackFace({ rack, slots, side }: { rack: PhysicalRecord; slots: EquipmentPlacement[]; side: 'front' | 'rear' }) { @@ -63,13 +66,13 @@ export function RackOverview({ rack, inventory }: { rack: PhysicalRecord; invent const height = rack.spec.heightUnits; return
-

Equipment & registration history

+ Equipment & registration history {(inventory.issues?.Device || inventory.issues?.DeviceClaim) &&

Some records are unavailable; equipment counts are incomplete.

} {denied ?

Installation details unavailable. This is not an empty rack.

: <>

Positioned equipment {positioned.length}

{positioned.length ? :

No complete in-range unit positions recorded.

}
@@ -85,7 +88,7 @@ export function FacilityOverview({ facility, inventory }: { facility: PhysicalRe const racks = inventory.physical.filter(record => record.kind === 'Rack' && record.metadata.namespace === facility.metadata.namespace && record.spec.facilityRef?.name === facility.metadata.name); const equipment = equipmentPlacements(inventory); const facilityOnly = equipment.filter(slot => slot.record.metadata.namespace === facility.metadata.namespace && !slot.placement.rackRef && slot.placement.facilityRef?.name === facility.metadata.name); - return

Racks

{inventory.issues?.Rack ?

Rack details unavailable. The facility's rack count is unknown.

: racks.length ?
{racks.map(rack => )}
RackRecorded heightEquipment reports / claim fallbackAvailable space
{rack.spec.displayName || rack.metadata.name}{rack.spec.heightUnits ? `${rack.spec.heightUnits}U` : 'Not recorded'}{inventory.issues?.DeviceClaim || inventory.issues?.Device ? 'Incomplete' : equipment.filter(slot => slot.record.metadata.namespace === rack.metadata.namespace && slot.placement.rackRef?.name === rack.metadata.name).length}Not verified
:

No racks recorded in this facility.

} -

Equipment without a recorded rack

{facilityOnly.length ? : inventory.issues?.DeviceClaim || inventory.issues?.Device ?

Equipment details unavailable.

:

No facility-only reports or claims recorded.

} + return
Racks{inventory.issues?.Rack ?

Rack details unavailable. The facility's rack count is unknown.

: racks.length ?
RackRecorded heightEquipment reports / claim fallbackAvailable space{racks.map(rack => {rack.spec.displayName || rack.metadata.name}{rack.spec.heightUnits ? `${rack.spec.heightUnits}U` : 'Not recorded'}{inventory.issues?.DeviceClaim || inventory.issues?.Device ? 'Incomplete' : equipment.filter(slot => slot.record.metadata.namespace === rack.metadata.namespace && slot.placement.rackRef?.name === rack.metadata.name).length}Not verified)}
:

No racks recorded in this facility.

} + Equipment without a recorded rack{facilityOnly.length ? : inventory.issues?.DeviceClaim || inventory.issues?.Device ?

Equipment details unavailable.

:

No facility-only reports or claims recorded.

}
; } diff --git a/ui/provider/src/components/inventory-management.tsx b/ui/provider/src/components/inventory-management.tsx index 3bdc2816..468d3af1 100644 --- a/ui/provider/src/components/inventory-management.tsx +++ b/ui/provider/src/components/inventory-management.tsx @@ -1,3 +1,5 @@ +import { Input } from '@datum-cloud/datum-ui/input'; +import { Label } from '@datum-cloud/datum-ui/label'; import { useContext, useLayoutEffect, useRef, useState, type ComponentProps, type FormEvent } from 'react'; import { useQueryClient } from '@tanstack/react-query'; import { Button } from '@datum-cloud/datum-ui/button'; @@ -106,7 +108,7 @@ function InventoryManagementForm({ kind, record, facilities: sourceFacilities, c {!compact && Manage {record ? 'this record' : `${kind === 'Facility' ? 'facilities' : `${kindLabel}s`}`}}
{compact && {record ? 'Editing access' : 'Namespace & access'}} - {!record && } + {!record && } {dependenciesUnavailable &&

Related records are unavailable, not empty. Creation needs readable location, installation, or endpoint records. Ask your administrator about viewing access, or try again after a temporary failure.

} {!editable ?

Display-name editing uses a narrower portal writer policy and is unavailable for this record. Import provenance is history, not Git ownership or server authorization. Device location correction, when separately available, uses ordinary management access and does not perform an ownership handover.

: permission.error instanceof ApiError && permission.error.status === 401 ?

Your session expired. Sign in again through the staff portal before continuing. Unsaved input remains here.

: !visible &&

Viewing and management access are separate. Ask your administrator about physical-inventory management access. A permission check must succeed before changes are available.

}
@@ -125,18 +127,18 @@ function InventoryManagementForm({ kind, record, facilities: sourceFacilities, c {open && permission.data === true && !permission.error && !issues[kind] &&

{record ? 'Only the display name and recording details change. Identity, placement, geometry, connections, and history remain untouched.' : 'Create a physical record only. This does not verify equipment, reserve space, or provision hardware.'}

- {!record && } - + {!record && } + {!record && (kind === 'Device' || kind === 'Cable' || kind === 'DeviceClaim') && } {!record && kind === 'Cable' && (issues?.Device || issues?.PowerFeed) &&

Some endpoint records are unavailable. Only readable equipment and power feeds are offered; missing choices do not mean those records are absent.

} {!record && kind === 'DeviceClaim' && (issues?.Facility || issues?.Rack) &&

Some location records are unavailable. Only readable facilities and racks are offered; missing choices do not mean those records are absent.

} {!record && kind === 'Rack' && <> - -

Leave height blank if unknown. A rack record does not establish free space.

+ +

Leave height blank if unknown. A rack record does not establish free space.

} - +

The recorder is an attributed observation, not a replacement for the API audit identity of your signed-in account.

- +
} diff --git a/ui/provider/src/components/inventory-navigation.tsx b/ui/provider/src/components/inventory-navigation.tsx new file mode 100644 index 00000000..51695100 --- /dev/null +++ b/ui/provider/src/components/inventory-navigation.tsx @@ -0,0 +1,63 @@ +import { Link, useSearchParams } from 'react-router'; +import { LinkButton } from '@datum-cloud/datum-ui/button'; +import { Building2, Cable, ClipboardList, HardDrive, Server, Zap } from 'lucide-react'; +import type { Inventory } from '../inventory'; +import { inventoryHref } from './inventory-location'; + +export const sections = [ + { + kind: 'Device', + title: 'Devices', + icon: HardDrive, + description: 'Physical hardware, identity, and recorded connections.', + }, + { + kind: 'Site', + title: 'Operational sites', + icon: Building2, + description: 'Internal operational identity and recorded premises membership. Not placement eligibility or authority.', + }, + { + kind: 'Facility', + title: 'Facilities', + icon: Building2, + description: 'Premises and the racks and equipment recorded within them.', + }, + { + kind: 'Rack', + title: 'Racks', + icon: Server, + description: 'Rack definitions and reported equipment placement.', + }, + { + kind: 'DeviceClaim', + title: 'Claims & registrations', + icon: ClipboardList, + description: 'Registration and intent history, kept separate from physical hardware. Installation lifecycle alone does not distinguish prospective from existing equipment.', + }, + { + kind: 'Cable', + title: 'Cables', + icon: Cable, + description: 'Recorded cable lanes and their physical terminations.', + }, + { + kind: 'PowerFeed', + title: 'Power feeds', + icon: Zap, + description: 'Supply ratings, terminations, and upstream sources.', + }, +] as const; + +export function InventoryNavigation({ inventory }: { inventory?: Inventory }) { + const [params] = useSearchParams(); + const active = sections.find(item => item.kind === params.get('kind')) ?? sections.find(item => !inventory?.issues?.[item.kind]) ?? sections[0]; + return ; +} diff --git a/ui/provider/src/components/inventory-session-boundary.tsx b/ui/provider/src/components/inventory-session-boundary.tsx index e5aba11a..eb90dab1 100644 --- a/ui/provider/src/components/inventory-session-boundary.tsx +++ b/ui/provider/src/components/inventory-session-boundary.tsx @@ -1,6 +1,6 @@ import { createContext, useContext, useEffect, useLayoutEffect, useRef, useState, type ReactNode } from 'react'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; -import { UNSAFE_DataRouterContext, UNSAFE_DataRouterStateContext, useLocation, useNavigation, useRevalidator, useRouteLoaderData } from 'react-router'; +import { UNSAFE_DataRouterContext, UNSAFE_DataRouterStateContext, useLocation, useNavigation, useRevalidator, useRouteLoaderData, type Location } from 'react-router'; import { InventoryAccessState } from './inventory-access-state'; import { LoadingState } from './states'; import { InventoryOperationContext, InventoryOperationGenerationContext, InventoryOperationReadyContext, InventoryOperationScope } from '../lib/inventory-operation'; @@ -42,9 +42,21 @@ export function SessionQueries({ children, principal, authority, generation }: { return {children}; } -function HostedInventory({ children }: { children: ReactNode }) { +function isPresentationNavigation(current: Location, next: Location | undefined) { + if (!next || current.pathname !== next.pathname || current.search === next.search) return false; + const currentParams = new URLSearchParams(current.search); + const nextParams = new URLSearchParams(next.search); + for (const key of ['kind', 'record', 'namespace']) { + currentParams.delete(key); + nextParams.delete(key); + } + return currentParams.toString() === nextParams.toString(); +} + +function HostedInventory({ children, retainPresentationData = false, pending: pendingContent = }: { children: ReactNode; retainPresentationData?: boolean; pending?: ReactNode }) { const host = useContext(UNSAFE_DataRouterContext); const [sessionGeneration, setSessionGeneration] = useState(0); + const [operationGeneration, setOperationGeneration] = useState(0); useLayoutEffect(() => { if (!host) return; const readPrincipal = (state: typeof host.router.state) => { @@ -53,6 +65,7 @@ function HostedInventory({ children }: { children: ReactNode }) { }; let observedPrincipal = readPrincipal(host.router.state); let pending = host.router.state.revalidation !== 'idle' || host.router.state.navigation.state !== 'idle'; + let resetAfterPending = pending; return host.router.subscribe(state => { const nextPrincipal = readPrincipal(state); if (nextPrincipal !== observedPrincipal) { @@ -61,12 +74,15 @@ function HostedInventory({ children }: { children: ReactNode }) { } if (state.revalidation !== 'idle' || state.navigation.state !== 'idle') { pending = true; + if (!retainPresentationData || state.revalidation !== 'idle' || state.navigation.formMethod || !isPresentationNavigation(state.location, state.navigation.location)) resetAfterPending = true; } else if (pending) { pending = false; - setSessionGeneration(current => current + 1); + setOperationGeneration(current => current + 1); + if (resetAfterPending) setSessionGeneration(current => current + 1); + resetAfterPending = false; } }); - }, [host]); + }, [host, retainPresentationData]); const identity = useRouteLoaderData('layouts/milo.layout') as { user?: { metadata?: { uid?: string; name?: string } } } | undefined; const principal = identity?.user?.metadata?.uid ?? identity?.user?.metadata?.name; const location = useLocation(); @@ -116,15 +132,16 @@ function HostedInventory({ children }: { children: ReactNode }) { }; }, []); if (failed) return ; - if (checking || revalidator.state !== 'idle' || navigation.state !== 'idle') return ; + const presentationPending = retainPresentationData && !navigation.formMethod && isPresentationNavigation(location, navigation.location); + if (checking || revalidator.state !== 'idle' || navigation.state !== 'idle' && !presentationPending) return <>{pendingContent}; if (!principal) return ; - return {children}; + return {navigation.state !== 'idle' ? pendingContent : children}; } -export function InventorySessionBoundary({ children }: { children: ReactNode }) { +export function InventorySessionBoundary({ children, retainPresentationData, pending }: { children: ReactNode; retainPresentationData?: boolean; pending?: ReactNode }) { const router = useContext(UNSAFE_DataRouterStateContext); const preview = useContext(InventoryPreviewContext); if (preview) return <>{children}; if (!router) return ; - return {children}; + return {children}; } diff --git a/ui/provider/src/components/inventory-stable-controls.test.tsx b/ui/provider/src/components/inventory-stable-controls.test.tsx index 35b44f26..7919b267 100644 --- a/ui/provider/src/components/inventory-stable-controls.test.tsx +++ b/ui/provider/src/components/inventory-stable-controls.test.tsx @@ -75,6 +75,9 @@ it.each(cases.flatMap(test => [false, true].flatMap(strict => [false, true].map( expect(() => operation.assertCurrent()).not.toThrow(); fireEvent.click(opener); const input = screen.getByLabelText(mode === 'location' ? 'Correction reason' : 'Display name'); + expect(input).toHaveAttribute('data-slot', 'input'); + expect(input.closest('label')).toHaveAttribute('data-slot', 'label'); + if (mode === 'location') expect(screen.getByRole('button', { name: 'Save reported location' })).toHaveAttribute('type', 'submit'); fireEvent.change(input, { target: { value: 'Safe draft' } }); const openMarkup = document.body.innerHTML; for (let cycle = 0; cycle < 3; cycle++) { diff --git a/ui/provider/src/components/inventory-tab-navigation.test.tsx b/ui/provider/src/components/inventory-tab-navigation.test.tsx new file mode 100644 index 00000000..4152630b --- /dev/null +++ b/ui/provider/src/components/inventory-tab-navigation.test.tsx @@ -0,0 +1,164 @@ +import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; +import { createMemoryRouter, Outlet, RouterProvider } from 'react-router'; +import { afterEach, expect, it, vi } from 'vitest'; +import DeviceInventoryList from '../pages/device-inventory-list'; +import { fixturePhysicalClaims, fixturePhysicalDevices, fixturePhysicalRecords } from '../lib/fixtures'; + +afterEach(() => { vi.unstubAllGlobals(); vi.restoreAllMocks(); }); + +function host(query = '', management = false) { + let principal: string | null = 'staff-a'; + let denied = false; + let held = false; + let release: (() => void) | undefined; + let holdReview = false; + let releaseReview: (() => void) | undefined; + const collections = vi.fn(); + const writes = vi.fn(); + vi.stubGlobal('fetch', vi.fn(async (url: string, init: RequestInit) => { + if (url.includes('selfsubjectaccessreviews')) { + if (holdReview) { + holdReview = false; + await new Promise(resolve => { releaseReview = resolve; }); + } + return Response.json({ data: { status: { allowed: management } } }); + } + if (init.method !== 'GET') writes(); + collections(); + if (denied) return Response.json({ error: 'Denied' }, { status: 403 }); + const kind = url.includes('/facilities') ? 'Facility' : url.includes('/racks') ? 'Rack' : url.includes('/cables') ? 'Cable' : url.includes('/powerfeeds') ? 'PowerFeed' : 'Site'; + const items = url.includes('/devices') ? fixturePhysicalDevices : url.includes('/deviceclaims') ? fixturePhysicalClaims : fixturePhysicalRecords.filter(record => record.kind === kind); + return Response.json({ data: { items } }); + })); + const loader = vi.fn(async () => { + if (held) await new Promise(resolve => { release = resolve; }); + return { user: principal ? { metadata: { uid: principal } } : null }; + }); + const router = createMemoryRouter([{ id: 'layouts/milo.layout', path: '/', loader, element: , children: [{ path: 'plugins/:slug/inventory', element: }] }], { initialEntries: [`/plugins/metal/inventory${query}`] }); + render(); + return { router, loader, collections, writes, + hold: () => { held = true; release = undefined; }, + holdReview: () => { holdReview = true; }, + releaseReview: async () => { await waitFor(() => expect(releaseReview).toBeDefined()); await act(async () => releaseReview!()); }, + principal: (next: string | null) => { principal = next; }, + deny: () => { denied = true; }, + release: async () => { await waitFor(() => expect(release).toBeDefined()); held = false; await act(async () => release!()); }, + }; +} + +it('keeps actual tab DOM through host checks, reuses collections, and preserves detail/back/forward URLs', async () => { + const view = host(); + await screen.findByRole('searchbox', { name: 'Search devices' }); + expect(view.collections).toHaveBeenCalledTimes(7); + const navigation = screen.getByRole('navigation', { name: 'Inventory categories' }); + const facilities = within(navigation).getByRole('link', { name: 'Facilities' }); + view.hold(); + fireEvent.click(facilities); + await screen.findByText('Checking inventory access…'); + expect(screen.getByRole('navigation', { name: 'Inventory categories' })).toBe(navigation); + expect(within(navigation).getByRole('link', { name: 'Facilities' })).toBe(facilities); + expect(screen.queryByText('Example compute server')).not.toBeInTheDocument(); + expect(screen.queryByTestId('fleet-plugin-loading')).not.toBeInTheDocument(); + expect(navigation.textContent).not.toMatch(/\d/); + await view.release(); + await screen.findByRole('searchbox', { name: 'Search facilities' }); + expect(view.router.state.location.search).toBe('?kind=Facility'); + fireEvent.click(screen.getByRole('link', { name: 'Example facility' })); + await screen.findByRole('heading', { name: 'Example facility' }); + expect(view.router.state.location.search).toContain('record=example-facility&namespace=default'); + await act(async () => { await view.router.navigate(-1); }); + await screen.findByRole('searchbox', { name: 'Search facilities' }); + await act(async () => { await view.router.navigate(-1); }); + await screen.findByRole('searchbox', { name: 'Search devices' }); + await act(async () => { await view.router.navigate(1); }); + await screen.findByRole('searchbox', { name: 'Search facilities' }); + expect(screen.getByRole('navigation', { name: 'Inventory categories' })).toBe(navigation); + expect(view.collections).toHaveBeenCalledTimes(7); + expect(view.loader).toHaveBeenCalledTimes(6); + expect(view.writes).not.toHaveBeenCalled(); + view.router.dispose(); +}); + +it('fences an in-flight create across a cached tab transition without carrying its draft', async () => { + const view = host('?kind=Facility', true); + fireEvent.click(await screen.findByRole('button', { name: 'Create facility' })); + for (const [label, value] of [['Record name', 'synthetic'], ['Display name', 'Private pending draft'], ['Recorded by', 'synthetic-operator']]) fireEvent.change(screen.getByLabelText(label), { target: { value } }); + view.holdReview(); + fireEvent.click(screen.getByRole('button', { name: 'Create facility record' })); + await screen.findByRole('button', { name: 'Saving…' }); + fireEvent.click(within(screen.getByRole('navigation', { name: 'Inventory categories' })).getByRole('link', { name: 'Devices' })); + await screen.findByRole('searchbox', { name: 'Search devices' }); + await view.releaseReview(); + expect(view.collections).toHaveBeenCalledTimes(7); + expect(view.writes).not.toHaveBeenCalled(); + fireEvent.click(within(screen.getByRole('navigation', { name: 'Inventory categories' })).getByRole('link', { name: 'Facilities' })); + fireEvent.click(await screen.findByRole('button', { name: 'Create facility' })); + expect(screen.getByLabelText('Display name')).toHaveValue(''); + expect(screen.queryByText('Facility record created.')).not.toBeInTheDocument(); + view.router.dispose(); +}); + +it('loads a direct namespaced link without requiring a previous directory visit', async () => { + const view = host('?kind=Facility&record=example-facility&namespace=default'); + await screen.findByRole('heading', { name: 'Example facility' }); + expect(view.collections).toHaveBeenCalledTimes(7); + expect(within(screen.getByRole('navigation', { name: 'Inventory categories' })).getByRole('link', { name: 'Facilities' })).toHaveAttribute('aria-current', 'page'); + view.router.dispose(); +}); + +it('restarts management authority after immediate same-principal host navigation', async () => { + const view = host('?kind=Facility', true); + await screen.findByRole('button', { name: 'Create facility' }); + for (const [category, action] of [['Devices', 'Create device'], ['Facilities', 'Create facility'], ['Devices', 'Create device']]) { + await act(async () => { + fireEvent.click(within(screen.getByRole('navigation', { name: 'Inventory categories' })).getByRole('link', { name: category })); + }); + await waitFor(() => expect(screen.getByRole('button', { name: action })).toBeEnabled()); + } + expect(view.collections).toHaveBeenCalledTimes(7); + expect(view.writes).not.toHaveBeenCalled(); + view.router.dispose(); +}); + +it.each(['principal', 'logout', 'denial', 'hidden', 'pagehide', 'revalidation', 'unknown-query'])('retains only static chrome across a real %s boundary', async transition => { + const view = host(); + await screen.findByRole('searchbox', { name: 'Search devices' }); + const navigation = screen.getByRole('navigation', { name: 'Inventory categories' }); + view.hold(); + if (transition === 'principal') view.principal('staff-b'); + if (transition === 'logout') view.principal(null); + if (transition === 'denial') view.deny(); + if (transition === 'hidden') { + const visibility = vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('hidden'); + fireEvent(document, new Event('visibilitychange')); + expect(screen.queryByText('Example compute server')).not.toBeInTheDocument(); + visibility.mockReturnValue('visible'); + fireEvent(document, new Event('visibilitychange')); + } else if (transition === 'pagehide') { + fireEvent(window, new Event('pagehide')); + expect(screen.queryByText('Example compute server')).not.toBeInTheDocument(); + fireEvent(window, new Event('pageshow')); + } else if (transition === 'principal' || transition === 'logout') { + fireEvent.click(within(navigation).getByRole('link', { name: 'Facilities' })); + } else if (transition === 'unknown-query') { + act(() => { void view.router.navigate('?kind=Device&scope=other'); }); + } else act(() => { void view.router.revalidate(); }); + await screen.findByText('Checking inventory access…'); + expect(screen.queryByText('Example compute server')).not.toBeInTheDocument(); + expect(screen.getByRole('navigation', { name: 'Inventory categories' })).toBe(navigation); + expect(navigation.textContent).not.toMatch(/\d/); + await view.release(); + if (transition === 'logout') { + await screen.findByText('Your session has expired'); + expect(view.collections).toHaveBeenCalledTimes(7); + } else if (transition === 'denial') { + await screen.findByRole('heading', { name: 'Inventory access needed' }); + expect(screen.queryByText('Example compute server')).not.toBeInTheDocument(); + expect(view.collections).toHaveBeenCalledTimes(14); + } else { + await screen.findByRole('searchbox'); + expect(view.collections).toHaveBeenCalledTimes(14); + } + expect(view.writes).not.toHaveBeenCalled(); + view.router.dispose(); +}); diff --git a/ui/provider/src/components/physical-inventory.css b/ui/provider/src/components/physical-inventory.css index 30211c99..77f7cd10 100644 --- a/ui/provider/src/components/physical-inventory.css +++ b/ui/provider/src/components/physical-inventory.css @@ -1,98 +1,85 @@ -.fleet-inventory { display:flex; flex-direction:column; gap:24px; min-width:0; color:var(--foreground, #182b2a); font-size:14px; line-height:1.5; } -.fleet-inventory h2 { font-size:24px; font-weight:600; letter-spacing:-.025em; margin:0; } -.fleet-inventory h3 { font-size:17px; font-weight:600; margin:0; } +.fleet-inventory { display:flex; flex-direction:column; gap:24px; min-width:0; color:var(--foreground); font-size:14px; line-height:1.5; } .fleet-inventory h4 { font-weight:600; } .fleet-inventory p { margin:0; } .inventory-heading,.inventory-list-heading { display:flex; justify-content:space-between; align-items:center; gap:16px; } -.inventory-eyebrow { font-size:10px; font-weight:600; letter-spacing:.12em; color:var(--muted-foreground,#667571); margin-bottom:6px!important; } -.inventory-muted,.fleet-inventory small,.fleet-inventory dt { color:var(--muted-foreground,#667571); } -.inventory-readonly { border:1px solid var(--border,#dce3df); border-radius:6px; padding:4px 10px; white-space:nowrap; font-size:12px; } -.inventory-sections { display:flex; gap:4px; flex-wrap:wrap; border-bottom:1px solid var(--border,#dce3df); padding-bottom:8px; } -.inventory-sections a { display:flex; align-items:center; gap:7px; padding:7px 10px; border:1px solid transparent; border-radius:6px; text-decoration:none!important; color:inherit; font-size:12px; } -.inventory-sections a[aria-current] { border-color:var(--primary,#264b42); background:var(--accent,#eaf1ed); } -.inventory-sections strong { font-size:11px; font-weight:500; opacity:.7; } +.inventory-muted,.fleet-inventory small,.fleet-inventory dt { color:var(--muted-foreground); } +.inventory-sections { display:flex; gap:4px; flex-wrap:wrap; border-bottom:1px solid var(--border); padding-bottom:8px; } .inventory-sections svg { flex-shrink:0; } .inventory-body { display:flex; flex-direction:column; gap:16px; min-width:0; } -.inventory-search { display:flex; align-items:center; gap:10px; border:1px solid var(--border,#dce3df); border-radius:6px; padding:9px 12px; max-width:520px; } -.inventory-search input { min-width:0; width:100%; background:transparent; border:0; font:inherit; color:inherit; outline:none; } -.inventory-search:focus-within { outline:2px solid var(--ring,#547f6f); outline-offset:2px; } -.fleet-inventory a { color:inherit; text-decoration:underline; text-underline-offset:3px; } -.fleet-inventory a:hover { color:var(--primary,#264b42); } -.fleet-inventory a:focus-visible,.fleet-inventory summary:focus-visible,.fleet-inventory button:focus-visible { outline:2px solid var(--ring,#547f6f); outline-offset:3px; } +.inventory-search { display:flex; align-items:center; gap:10px; max-width:520px; } +.inventory-search input { min-width:0; width:100%; } +.fleet-inventory a:not(.inventory-sections a) { color:inherit; text-decoration:underline; text-underline-offset:3px; } +.fleet-inventory a:not(.inventory-sections a):hover { color:var(--primary); } +.fleet-inventory a:focus-visible,.fleet-inventory summary:focus-visible { outline:2px solid var(--ring); outline-offset:3px; } .fleet-inventory h2[tabindex="-1"]:focus { outline:none; } -.inventory-scroll:focus-visible { outline:2px solid var(--ring,#547f6f); outline-offset:3px; } -.inventory-scroll { overflow:auto; border:1px solid var(--border,#dce3df); border-radius:8px; } -.fleet-inventory table { width:100%; border-collapse:collapse; text-align:left; font-size:13px; } -.fleet-inventory th { font-size:12px; font-weight:500; background:var(--muted,#f5f7f5); color:var(--foreground,#182b2a); } -.fleet-inventory th,.fleet-inventory td { padding:9px 14px; border-bottom:1px solid var(--border,#dce3df); vertical-align:top; min-width:120px; max-width:380px; overflow-wrap:anywhere; } -.fleet-inventory tr:last-child td { border-bottom:0; } -.fleet-inventory tbody tr:hover { background:var(--muted,#f8faf8); } +.inventory-scroll:focus-visible { outline:2px solid var(--ring); outline-offset:3px; } +.inventory-scroll { overflow:auto; border:1px solid var(--border); border-radius:var(--radius); } +.inventory-scroll > [data-slot="table-container"] { overflow:visible; } +.fleet-inventory th,.fleet-inventory td { vertical-align:top; min-width:120px; max-width:380px; white-space:normal; overflow-wrap:anywhere; } .fleet-inventory td a { font-weight:500; } .fleet-inventory small { display:block; font-size:11px; margin-top:4px; } .fleet-inventory caption { text-align:left; padding:12px 16px; font-weight:500; } .inventory-fields { display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:20px 28px; margin:0; } .fleet-inventory dt { font-size:12px; margin-bottom:4px; } .fleet-inventory dd { margin:0; overflow-wrap:anywhere; } -.fleet-inventory details { border-top:1px solid var(--border,#dce3df); padding-top:16px; } +.fleet-inventory details { border-top:1px solid var(--border); padding-top:16px; } .fleet-inventory summary { cursor:pointer; font-weight:500; } .fleet-inventory details[open]>summary { margin-bottom:16px; } .fleet-inventory details p+p { margin-top:8px; } -.inventory-help { font-size:12px; color:var(--muted-foreground,#667571); } -.inventory-note { padding:12px 16px; background:var(--muted,#f5f7f5); border-left:3px solid var(--border,#dce3df); } +.inventory-help { font-size:12px; color:var(--muted-foreground); } +.inventory-note { padding:12px 16px; background:var(--muted); border-left:3px solid var(--border); } .inventory-related { list-style:none; padding:0; margin:0; display:grid; gap:8px; } -.inventory-related li { display:grid; grid-template-columns:120px 1fr 1fr; gap:12px; padding:12px; border:1px solid var(--border,#dce3df); border-radius:6px; overflow-wrap:anywhere; } -.inventory-empty { display:flex; flex-direction:column; align-items:center; gap:12px; padding:48px 20px; text-align:center; color:var(--muted-foreground,#667571); } -.inventory-empty button { cursor:pointer; padding:8px 16px; border:1px solid var(--border,#dce3df); border-radius:6px; color:var(--foreground,#182b2a); } +.inventory-related li { display:grid; grid-template-columns:120px 1fr 1fr; gap:12px; padding:12px; border:1px solid var(--border); border-radius:var(--radius); overflow-wrap:anywhere; } +.inventory-empty { display:flex; flex-direction:column; align-items:center; gap:12px; padding:48px 20px; text-align:center; color:var(--muted-foreground); } .inventory-management { display:block; } .inventory-management-status { min-height:3em; font-size:12px; } .inventory-form > fieldset.inventory-form-gate { display:contents; } .inventory-form-gate > p,.inventory-form-gate > div,.inventory-form-gate > fieldset { grid-column:1/-1; } .inventory-management > [role="status"] { margin-top:16px; } -.inventory-management label { display:flex; flex-direction:column; gap:6px; margin:12px 0; } -.inventory-management input,.inventory-management select { padding:9px 12px; background:var(--card,#fff); color:var(--foreground,#182b2a); border:1px solid var(--border,#dce3df); border-radius:6px; } -.inventory-management input:focus-visible,.inventory-management select:focus-visible { outline:2px solid var(--ring,#547f6f); outline-offset:2px; } -.inventory-form { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:12px 24px; margin-top:16px; padding:20px; border:1px solid var(--border,#dce3df); border-radius:10px; background:var(--card,#fff); } +.inventory-management label { display:flex; flex-direction:column; align-items:stretch; gap:6px; margin:12px 0; line-height:1.5; } +.inventory-management select { padding:9px 12px; background:var(--card); color:var(--foreground); border:1px solid var(--border); border-radius:var(--radius); } +.inventory-management select:focus-visible { outline:2px solid var(--ring); outline-offset:2px; } +.inventory-form { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:12px 24px; margin-top:16px; padding:20px; border:1px solid var(--border); border-radius:var(--radius); background:var(--card); } .inventory-form > p,.inventory-form > div,.inventory-form > fieldset { grid-column:1/-1; } .inventory-toolbar { display:flex; gap:10px; align-items:center; flex-wrap:wrap; } .inventory-toolbar .inventory-search { flex:1; max-width:none; min-width:200px; } -.inventory-toolbar select { padding:9px 12px; border:1px solid var(--border,#dce3df); border-radius:6px; background:var(--card,#fff); font:inherit; max-width:100%; } +.inventory-toolbar select { padding:9px 12px; border:1px solid var(--border); border-radius:var(--radius); background:var(--card); font:inherit; max-width:100%; } .inventory-rack-layout { display:grid; grid-template-columns:minmax(280px, .9fr) minmax(0,1.7fr); gap:24px; align-items:start; } -.inventory-elevation { border:1px solid var(--border,#dce3df); border-radius:10px; padding:16px; display:grid; gap:12px; background:var(--card,#fff); } +.inventory-elevation { border:1px solid var(--border); border-radius:var(--radius); padding:16px; display:grid; gap:12px; background:var(--card); } .inventory-elevation p { font-size:12px; } .inventory-rack-faces { display:flex; gap:10px; } .inventory-rack-faces > div { flex:1; min-width:0; } .inventory-rack-faces h4 { text-align:center; text-transform:uppercase; font-size:11px; letter-spacing:.06em; margin-bottom:8px; } -.inventory-rack-units { display:grid; list-style:none; padding:0; margin:0; border:1px solid var(--border,#dce3df); font-size:9px; line-height:15px; } -.inventory-rack-unit { display:grid; grid-template-columns:28px 1fr; border-bottom:1px solid var(--border,#dce3df); } -.inventory-rack-unit > span { padding:0 3px; background:var(--muted,#f5f7f5); } -.inventory-rack-plan { z-index:1; min-width:0; min-height:0; border:1px solid var(--border,#dce3df); background:var(--accent,#eaf1ed); } +.inventory-rack-units { display:grid; list-style:none; padding:0; margin:0; border:1px solid var(--border); font-size:9px; line-height:15px; } +.inventory-rack-unit { display:grid; grid-template-columns:28px 1fr; border-bottom:1px solid var(--border); } +.inventory-rack-unit > span { padding:0 3px; background:var(--muted); } +.inventory-rack-plan { z-index:1; min-width:0; min-height:0; border:1px solid var(--border); background:var(--accent); } .inventory-rack-plan a { display:flex; flex-direction:column; justify-content:center; height:100%; min-width:0; padding:0 3px; overflow:hidden; white-space:nowrap; } .inventory-rack-plan-heading { display:flex; align-items:center; gap:3px; flex:none; min-width:0; line-height:12px; } .inventory-rack-plan-name { min-width:0; overflow:hidden; text-overflow:ellipsis; } .inventory-rack-overlap { flex:none; font-weight:700; } -.inventory-rack-plan a:focus-visible { outline:2px solid var(--ring,#32765a); outline-offset:-2px; } +.inventory-rack-plan a:focus-visible { outline:2px solid var(--ring); outline-offset:-2px; } .inventory-rack-plan small { flex:none; overflow:hidden; text-overflow:ellipsis; font-size:8px; line-height:12px; } .inventory-face-switch { display:flex; gap:4px; } -.inventory-face-switch button { flex:1; padding:6px; border:1px solid var(--border,#dce3df); border-radius:5px; font-size:12px; cursor:pointer; } -.inventory-face-switch button[aria-pressed=true] { background:var(--accent,#eaf1ed); font-weight:600; } +.inventory-face-switch button { flex:1; } .inventory-equipment-sections { display:grid; gap:16px; min-width:0; } .inventory-equipment-sections section { display:grid; gap:10px; } -.inventory-count { font-size:11px; color:var(--muted-foreground,#667571); font-weight:400; } -.inventory-form fieldset { border-top:1px solid var(--border,#dce3df); padding-top:12px; min-width:0; } +.inventory-count { font-size:11px; color:var(--muted-foreground); font-weight:400; } +.inventory-form fieldset { border-top:1px solid var(--border); padding-top:12px; min-width:0; } .inventory-form legend { font-weight:600; } .inventory-topline { display:grid; grid-template-columns:minmax(0,1fr) auto; align-items:start; gap:12px 24px; } .inventory-management-compact { display:contents; } .inventory-management-compact .inventory-management-controls { display:flex; gap:12px; align-items:start; justify-content:flex-end; } .inventory-management-compact .inventory-management-access { border:0; padding:0; font-size:12px; max-width:320px; } -.inventory-management-compact .inventory-management-access[open] { padding:12px; border:1px solid var(--border,#dce3df); border-radius:6px; } +.inventory-management-compact .inventory-management-access[open] { padding:12px; border:1px solid var(--border); border-radius:var(--radius); } .inventory-management-compact .inventory-form,.inventory-management-compact > [role=status] { grid-column:1/-1; } @media(max-width:800px) { .inventory-topline { grid-template-columns:1fr; } .inventory-management-compact .inventory-management-controls { justify-content:flex-start; } } .inventory-form-grid { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:0 20px; } -.inventory-component-editor { border:1px solid var(--border,#dce3df); padding:12px; border-radius:6px; margin:12px 0; } +.inventory-component-editor { border:1px solid var(--border); padding:12px; border-radius:var(--radius); margin:12px 0; } .inventory-form input,.inventory-form select { min-width:0; width:100%; } @media(max-width:600px) { .inventory-form-grid { grid-template-columns:1fr; } } @media(max-width:600px) { .fleet-inventory th,.fleet-inventory td { min-width:180px; } .inventory-topline .inventory-list-heading { flex-wrap:wrap; flex-direction:row; align-items:center; } .inventory-topline .inventory-list-heading > div { flex:1 1 100%; } } @media(max-width:900px) { .inventory-rack-layout { grid-template-columns:1fr; } .inventory-elevation { max-width:560px; width:100%; } } -@media(max-width:600px) { .inventory-form { grid-template-columns:1fr; padding:16px; } .inventory-sections a { padding:6px 8px!important; } .inventory-body { padding:0!important; } } +@media(max-width:600px) { .inventory-form { grid-template-columns:1fr; padding:16px; } .inventory-body { padding:0!important; } } @media(max-width:1100px) { .inventory-sections { grid-template-columns:repeat(3,minmax(0,1fr)); } } -@media(max-width:600px) { .inventory-sections { grid-template-columns:repeat(2,minmax(0,1fr)); } .inventory-fields { grid-template-columns:1fr; } .inventory-body { padding:16px; } .inventory-heading,.inventory-list-heading { align-items:flex-start; flex-direction:column; } .inventory-related li { grid-template-columns:1fr; gap:4px; } .inventory-sections a { padding:12px; font-size:12px; } } +@media(max-width:600px) { .inventory-sections { grid-template-columns:repeat(2,minmax(0,1fr)); } .inventory-fields { grid-template-columns:1fr; } .inventory-body { padding:16px; } .inventory-heading,.inventory-list-heading { align-items:flex-start; flex-direction:column; } .inventory-related li { grid-template-columns:1fr; gap:4px; } } diff --git a/ui/provider/src/components/physical-inventory.test.tsx b/ui/provider/src/components/physical-inventory.test.tsx index 97a7a88d..714a30fe 100644 --- a/ui/provider/src/components/physical-inventory.test.tsx +++ b/ui/provider/src/components/physical-inventory.test.tsx @@ -5,6 +5,8 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { PhysicalInventory } from './physical-inventory'; import { toInventory } from '../inventory'; import { fixturePhysicalClaims, fixturePhysicalDevices, fixturePhysicalRecords } from '../lib/fixtures'; +import { buttonVariants } from '@datum-cloud/datum-ui/button'; +import { cn } from '@datum-cloud/datum-ui/utils'; const inventory = toInventory(fixturePhysicalClaims, fixturePhysicalDevices, fixturePhysicalRecords); @@ -13,6 +15,27 @@ function browse(query = '', data = inventory) { } describe('hardware directory', () => { + it('uses Datum inputs, link buttons and table slots without nesting interactive controls', () => { + browse(); + expect(screen.getByRole('searchbox', { name: 'Search devices' })).toHaveAttribute('data-slot', 'input'); + const navigation = screen.getByRole('navigation', { name: 'Inventory categories' }); + const devices = within(navigation).getByRole('link', { name: /^Devices/ }); + expect(devices).toHaveClass(...cn(buttonVariants({ type: 'secondary', theme: 'light', size: 'small' })).split(' ')); + expect(devices).toHaveAttribute('aria-current', 'page'); + expect(navigation.querySelector('button')).toBeNull(); + const table = screen.getByRole('table'); + expect(table).toHaveAttribute('data-slot', 'table'); + expect(within(table).getAllByRole('columnheader')[0]).toHaveAttribute('data-slot', 'table-head'); + fireEvent.click(within(navigation).getByRole('link', { name: /^Facilities/ })); + expect(screen.getByRole('searchbox', { name: 'Search facilities' })).toHaveValue(''); + }); + + it('uses the Datum card access state while keeping retry and region semantics', () => { + browse('', { ...inventory, issues: { Device: { status: 403 }, Site: { status: 403 }, Facility: { status: 403 }, Rack: { status: 403 }, DeviceClaim: { status: 403 }, Cable: { status: 403 }, PowerFeed: { status: 403 } } }); + expect(screen.getByRole('region', { name: 'Inventory access needed' })).toHaveAttribute('data-slot', 'card'); + expect(screen.queryByRole('button', { name: 'Try again' })).not.toBeInTheDocument(); + }); + it.each(inventory.physical)('renders $kind details without provenance', record => { const data = structuredClone(inventory); for (const item of data.physical) delete item.spec.provenance; @@ -34,7 +57,7 @@ describe('hardware directory', () => { expect(screen.getByText('Inventory access needed')).toBeInTheDocument(); expect(screen.queryByText(/private-device/)).not.toBeInTheDocument(); expect(screen.queryByRole('link', { name: /Devices/ })).not.toBeInTheDocument(); - fireEvent.click(screen.getByRole('link', { name: /Facilities 1/ })); + fireEvent.click(screen.getByRole('link', { name: 'Facilities' })); expect(screen.getByRole('link', { name: 'Example facility' })).toBeInTheDocument(); }); @@ -72,7 +95,7 @@ describe('hardware directory', () => { fireEvent.change(screen.getByRole('searchbox'), { target: { value: 'no-such-serial' } }); expect(screen.getByText('No matching records')).toBeInTheDocument(); fireEvent.click(screen.getByRole('button', { name: 'Clear search' })); - fireEvent.click(screen.getByRole('link', { name: /Facilities 1/ })); + fireEvent.click(screen.getByRole('link', { name: 'Facilities' })); expect(screen.getByRole('searchbox')).toHaveValue(''); expect(screen.getByRole('link', { name: 'Example facility' })).toBeInTheDocument(); }); diff --git a/ui/provider/src/components/physical-inventory.tsx b/ui/provider/src/components/physical-inventory.tsx index e6fdd70f..acda1b4d 100644 --- a/ui/provider/src/components/physical-inventory.tsx +++ b/ui/provider/src/components/physical-inventory.tsx @@ -1,6 +1,12 @@ +import { Input } from '@datum-cloud/datum-ui/input'; +import { Label } from '@datum-cloud/datum-ui/label'; +import { Button } from '@datum-cloud/datum-ui/button'; +import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell, TableCaption } from '@datum-cloud/datum-ui/table'; +import { Title, titleVariants } from '@datum-cloud/datum-ui/typography'; import { useEffect, useRef, useState, type ReactNode } from 'react'; import { Link, useSearchParams } from 'react-router'; -import { Building2, Cable, ClipboardList, HardDrive, Search, Server, Zap } from 'lucide-react'; +import { Search } from 'lucide-react'; +import { InventoryNavigation, sections } from './inventory-navigation'; import { modelLabel, placementLabel, @@ -23,50 +29,7 @@ import { facilityIdentifiers, facilitySites, siteFacilities } from '../lib/site- type Kind = 'Site' | 'Device' | 'Facility' | 'Rack' | 'DeviceClaim' | 'Cable' | 'PowerFeed'; type RecordEntry = { kind: Kind; record: RawDevice | RawDeviceClaim | PhysicalRecord }; -const sections = [ - { - kind: 'Device', - title: 'Devices', - icon: HardDrive, - description: 'Physical hardware, identity, and recorded connections.', - }, - { - kind: 'Site', - title: 'Operational sites', - icon: Building2, - description: 'Internal operational identity and recorded premises membership. Not placement eligibility or authority.', - }, - { - kind: 'Facility', - title: 'Facilities', - icon: Building2, - description: 'Premises and the racks and equipment recorded within them.', - }, - { - kind: 'Rack', - title: 'Racks', - icon: Server, - description: 'Rack definitions and reported equipment placement.', - }, - { - kind: 'DeviceClaim', - title: 'Claims & registrations', - icon: ClipboardList, - description: 'Registration and intent history, kept separate from physical hardware. Installation lifecycle alone does not distinguish prospective from existing equipment.', - }, - { - kind: 'Cable', - title: 'Cables', - icon: Cable, - description: 'Recorded cable lanes and their physical terminations.', - }, - { - kind: 'PowerFeed', - title: 'Power feeds', - icon: Zap, - description: 'Supply ratings, terminations, and upstream sources.', - }, -] as const; + export { endpointLabel } from '../inventory'; @@ -86,28 +49,28 @@ function Field({ label, children }: { label: string; children: ReactNode }) { function Components({ components }: { components: PhysicalComponent[] }) { return components.length ? (
- - - - - - - - - - - +
Physical components
Name / IDTypeConnector / positionsIdentity
+ Physical components + + + Name / ID + Type + Connector / positions + Identity + + + {components.map((component) => ( - - - - - - + + ))} - -
+ + {component.name} {component.id} - {component.type} + + {component.type} + {component.connector ?? 'Not recorded'} / {component.positions ?? 'Not recorded'} - + + {component.serial ?? 'No serial recorded'} {component.assetTag ? `Asset tag: ${component.assetTag}` : 'No asset tag recorded'} @@ -117,18 +80,18 @@ function Components({ components }: { components: PhysicalComponent[] }) { {component.sourceRef.system}/{component.sourceRef.type}/{component.sourceRef.id} )} -
+ +
) : (

No components recorded.

); } -export function PhysicalInventory({ inventory: source, onRetry }: { inventory: Inventory; onRetry?: () => void }) { +export function PhysicalInventory({ inventory: source, onRetry, showNavigation = true }: { inventory: Inventory; onRetry?: () => void; showNavigation?: boolean }) { const [readIssues, setReadIssues] = useState({}); const inventory = redactInventory(source, readIssues); const [params] = useSearchParams(); @@ -136,7 +99,7 @@ export function PhysicalInventory({ inventory: source, onRetry }: { inventory: I const [locationFilter, setLocationFilter] = useState(''); const [modelFilter, setModelFilter] = useState(''); const heading = useRef(null); - const section = sections.find((item) => item.kind === params.get('kind')) ?? sections.find(item => !inventory.issues?.[item.kind]) ?? sections[0]; + const section = sections.find((item) => item.kind === params.get('kind')) ?? (showNavigation ? sections.find(item => !inventory.issues?.[item.kind]) : undefined) ?? sections[0]; const entries: RecordEntry[] = [ ...inventory.slots.flatMap((slot) => slot.devices.map((record) => ({ kind: 'Device' as const, record }))), ...inventory.unboundDevices.map((record) => ({ kind: 'Device' as const, record })), @@ -447,7 +410,7 @@ export function PhysicalInventory({ inventory: source, onRetry }: { inventory: I )} {device && ( <> -

Components & connections

+ Components & connections {!!device.spec.internalMappings?.length && ( <> @@ -496,7 +459,7 @@ export function PhysicalInventory({ inventory: source, onRetry }: { inventory: I )} {claim && ( <> -

Planned connections

+ Planned connections
    {claim.spec.cableRefs?.map((cable) => (
  • {reference('Cable', namespace, cable.name)}
  • @@ -521,31 +484,31 @@ export function PhysicalInventory({ inventory: source, onRetry }: { inventory: I )} {kind === 'Cable' && ( <> -

    Cable lanes

    + Cable lanes {physical?.spec.lanes?.length ? (
    - - - - - - - - - +
    LaneEnd AEnd B
    + + + Lane + End A + End B + + + {physical.spec.lanes.map((lane) => ( - - - - - + + ))} - -
    {lane.id} + + {lane.id} + - + + -
    + +
    ) : (

    No lanes recorded.

    @@ -554,9 +517,9 @@ export function PhysicalInventory({ inventory: source, onRetry }: { inventory: I )} {kind === 'PowerFeed' && ( <> -

    Terminations

    + Terminations -

    Upstream sources

    + Upstream sources
      {physical?.spec.upstreamSources?.map((source, index) => (
    • @@ -569,9 +532,9 @@ export function PhysicalInventory({ inventory: source, onRetry }: { inventory: I )} )} - {(kind !== 'Facility' && kind !== 'Rack' || relatedRecords.length > 0) && <>

      + {(kind !== 'Facility' && kind !== 'Rack' || relatedRecords.length > 0) && <> Related records - </h3> + {relatedRecords.length ? (
        {relatedRecords.map((item) => ( @@ -633,24 +596,12 @@ export function PhysicalInventory({ inventory: source, onRetry }: { inventory: I return ( setReadIssues(previous => ({ ...previous, ...readFailureIssues(error) }))}>
        - + {showNavigation && }
        {inventory.issues?.[section.kind] ? : selectedName !== null ? ( <> -
        ← Back to {section.title.toLowerCase()}{onRetry && }
        -

        +
        ← Back to {section.title.toLowerCase()}{onRetry && }
        +

        {selected ? recordName(selected) : 'Record not found'}

        {management}
        {placementEditor} @@ -673,53 +624,53 @@ export function PhysicalInventory({ inventory: source, onRetry }: { inventory: I <>
        -

        {section.title}

        + {section.title}

        {section.description}

        {matching.length} of {records.length} records - {onRetry && } + {onRetry && }
        {management}
        - {!inventory.issues?.Facility && ['Device', 'DeviceClaim', 'Rack', 'PowerFeed'].includes(section.kind) && } {filterOptions.length > 0 && } - {(locationFilter || modelFilter) && } + {(locationFilter || modelFilter) && }
        {matching.length ? (
        - - - - -
        Name + + + + Name + {section.kind === 'Device' || section.kind === 'DeviceClaim' ? 'Hardware' : 'Details'} - - - - - - + + {section.kind === 'Cable' ? 'End B' : section.kind === 'Device' ? 'Serial / asset tag' : 'Namespace'} + + + {matching.map((entry) => ( - - - - - - + + ))} - -
        + + {section.kind === 'Cable' ? 'End A' : section.kind === 'Device' || section.kind === 'DeviceClaim' ? 'Location / Reported placement' : 'Location / reference'} - {section.kind === 'Cable' ? 'End B' : section.kind === 'Device' ? 'Serial / asset tag' : 'Namespace'}
        + + - {summary(entry)}{entry.kind === 'Cable' ? (entry.record as PhysicalRecord).spec.lanes?.map(lane =>
        ) : entry.kind === 'Rack' && (entry.record as PhysicalRecord).spec.facilityRef ? reference('Facility', entry.record.metadata.namespace, (entry.record as PhysicalRecord).spec.facilityRef!.name) : placement(entry)}
        + + {summary(entry)} + {entry.kind === 'Cable' ? (entry.record as PhysicalRecord).spec.lanes?.map(lane =>
        ) : entry.kind === 'Rack' && (entry.record as PhysicalRecord).spec.facilityRef ? reference('Facility', entry.record.metadata.namespace, (entry.record as PhysicalRecord).spec.facilityRef!.name) : placement(entry)}
        + {entry.kind === 'Cable' ? (entry.record as PhysicalRecord).spec.lanes?.map(lane =>
        ) : entry.kind === 'Device' ? ( <> {(entry.record as RawDevice).spec.identity.serial ?? 'Serial not recorded'} @@ -747,27 +698,27 @@ export function PhysicalInventory({ inventory: source, onRetry }: { inventory: I ) : ( entry.record.metadata.namespace || 'Not recorded' )} -
        + +
        ) : (
        )} diff --git a/ui/provider/src/lib/api.ts b/ui/provider/src/lib/api.ts index c91be52f..8b311b9e 100644 --- a/ui/provider/src/lib/api.ts +++ b/ui/provider/src/lib/api.ts @@ -1,6 +1,5 @@ import { fixtureClasses, fixtureCapacities, fixturePhysicalClaims, fixturePhysicalDevices, fixturePhysicalRecords, fixtureProfiles } from './fixtures'; import { toInventory, inventoryResources, type InventoryKind, type Inventory, type RawDeviceClaimList, type RawDeviceList } from '../inventory'; -import { useId } from 'react'; import { useInventoryRead } from './inventory-read'; import type { List, PhysicalRecord } from '../../../shared/fleet-api'; import { @@ -293,14 +292,14 @@ export async function fetchInventoryCollection(plural: string): Promise } export function useInventory(): UseQueryResult { - const view = useId(); const read = useInventoryRead(fetchInventory); return useQuery({ - queryKey: [PLUGIN_ID, 'inventory', PROVIDER_PROJECT, view], + queryKey: [PLUGIN_ID, 'inventory', PROVIDER_PROJECT], queryFn: read, refetchInterval: false, refetchOnWindowFocus: false, - gcTime: 0, + gcTime: 300_000, + staleTime: Infinity, retry: false, }); } diff --git a/ui/provider/src/pages/device-inventory-list.tsx b/ui/provider/src/pages/device-inventory-list.tsx index 14cbd237..44b60e7b 100644 --- a/ui/provider/src/pages/device-inventory-list.tsx +++ b/ui/provider/src/pages/device-inventory-list.tsx @@ -4,16 +4,23 @@ import { LoadingState } from '../components/states'; import { InventoryAccessState } from '../components/inventory-access-state'; import { useInventory } from '../lib/api'; import { InventorySessionBoundary } from '../components/inventory-session-boundary'; +import { InventoryNavigation } from '../components/inventory-navigation'; +import { Text } from '@datum-cloud/datum-ui/typography'; export default function DeviceInventoryList() { - return ; + return + + Checking inventory access…}> + + + ; } function InventoryListContent() { const { data, isLoading, error, refetch } = useInventory(); - return + return <> {isLoading && } {!isLoading && error && void refetch()} />} - {!isLoading && !error && data && void refetch()} />} - ; + {!isLoading && !error && data && void refetch()} />} + ; } diff --git a/ui/provider/src/pages/device-inventory.test.tsx b/ui/provider/src/pages/device-inventory.test.tsx index 21fb41f8..3976030b 100644 --- a/ui/provider/src/pages/device-inventory.test.tsx +++ b/ui/provider/src/pages/device-inventory.test.tsx @@ -86,14 +86,14 @@ describe('DeviceInventoryList', () => { mockInventory({ isLoading: true }); renderAt('/plugins/metal-datumapis-com/inventory'); expect(screen.getByTestId('fleet-plugin-loading')).toBeInTheDocument(); - expect(screen.queryByRole('navigation', { name: 'Inventory categories' })).not.toBeInTheDocument(); + expect(screen.getByRole('navigation', { name: 'Inventory categories' }).textContent).not.toMatch(/\d/); }); it('hides stale counts on a failed read and allows retry', () => { mockInventory({ data: inventory, error: new ApiError(500, 'Inventory unavailable') }); renderAt('/plugins/metal-datumapis-com/inventory'); expect(screen.getByTestId('inventory-access-500')).toBeInTheDocument(); - expect(screen.queryByRole('navigation', { name: 'Inventory categories' })).not.toBeInTheDocument(); + expect(screen.getByRole('navigation', { name: 'Inventory categories' }).textContent).not.toMatch(/\d/); fireEvent.click(screen.getByRole('button', { name: 'Try again' })); expect(useInventoryMock.mock.results[0].value.refetch).toHaveBeenCalledOnce(); }); diff --git a/ui/provider/vitest.config.ts b/ui/provider/vitest.config.ts index 58ff9d2b..065fa36f 100644 --- a/ui/provider/vitest.config.ts +++ b/ui/provider/vitest.config.ts @@ -1,4 +1,5 @@ import react from '@vitejs/plugin-react'; +import tailwindcss from '@tailwindcss/vite'; import { defineConfig } from 'vitest/config'; // Separate from vite.config.ts on purpose: the Module Federation plugin there @@ -6,7 +7,7 @@ import { defineConfig } from 'vitest/config'; // process, so tests get their own minimal Vite config (React + jsdom) rather // than trying to make MF cooperate with vitest. export default defineConfig({ - plugins: [react()], + plugins: [tailwindcss(), react()], test: { environment: 'jsdom', setupFiles: ['./src/test/setup.ts'], From 2f2dc231e81330ef431ef0fe56b18d52057fd88b Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sat, 21 Nov 2026 19:26:56 -0600 Subject: [PATCH 058/518] test: settle catalog host session before focus verification --- .../inventory-session-boundary.test.tsx | 30 +++++++++++-------- 1 file changed, 17 insertions(+), 13 deletions(-) diff --git a/ui/provider/src/components/inventory-session-boundary.test.tsx b/ui/provider/src/components/inventory-session-boundary.test.tsx index 879a87bd..b33f262e 100644 --- a/ui/provider/src/components/inventory-session-boundary.test.tsx +++ b/ui/provider/src/components/inventory-session-boundary.test.tsx @@ -6,7 +6,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; import { InventorySessionBoundary, SessionQueries } from './inventory-session-boundary'; import { InventoryOperationContext, InventoryOperationInvalidated, InventoryOperationScope } from '../lib/inventory-operation'; -function mountHost(loader: () => unknown, content: React.ReactNode) { +async function mountHost(loader: () => unknown, content: React.ReactNode) { const router = createMemoryRouter([{ id: 'layouts/milo.layout', path: '/', @@ -14,7 +14,9 @@ function mountHost(loader: () => unknown, content: React.ReactNode) { element: , children: [{ index: true, element: {content} }], }]); - render(); + await act(async () => { render(); }); + expect(router.state.initialized).toBe(true); + expect(router.state.revalidation).toBe('idle'); return router; } @@ -30,7 +32,7 @@ describe('host inventory session isolation', () => { const query = useQuery({ queryKey: ['inventory'], queryFn: inventoryRead, staleTime: Infinity }); return

        {query.data ?? 'Empty inventory cache'}

        ; } - mountHost(async () => { + await mountHost(async () => { if (++reads > 1) await new Promise(resolve => { release = resolve; }); return { user: { metadata: { uid: 'staff-a' } } }; }, ); @@ -73,7 +75,7 @@ describe('host inventory session isolation', () => { const query = useQuery({ queryKey: ['inventory'], queryFn: read, staleTime: Infinity }); return

        {query.data}

        ; } - const router = mountHost(() => ({ user: { metadata: { uid: principal } } }), ); + const router = await mountHost(() => ({ user: { metadata: { uid: principal } } }), ); await screen.findByText('staff-a inventory 1'); const originalClient = client; await act(async () => { @@ -133,14 +135,16 @@ describe('host inventory session isolation', () => { }); it('keeps failed focus verification masked until the next verification succeeds', async () => { - const router = mountHost(() => ({ user: { metadata: { uid: 'staff-a' } } }), 'Private inventory'); + const router = await mountHost(() => ({ user: { metadata: { uid: 'staff-a' } } }), 'Private inventory'); await screen.findByText('Private inventory'); let release!: () => void; - vi.spyOn(router, 'revalidate').mockRejectedValueOnce(new Error('verification failed')).mockImplementationOnce(() => new Promise(resolve => { release = resolve; })); - fireEvent(window, new Event('focus')); + const revalidate = vi.spyOn(router, 'revalidate').mockRejectedValueOnce(new Error('verification failed')).mockImplementationOnce(() => new Promise(resolve => { release = resolve; })); + await act(async () => { fireEvent(window, new Event('focus')); }); + expect(revalidate).toHaveBeenCalledTimes(1); await waitFor(() => expect(screen.queryByText('Private inventory')).not.toBeInTheDocument()); fireEvent(window, new Event('focus')); await waitFor(() => expect(release).toBeDefined()); + expect(revalidate).toHaveBeenCalledTimes(2); expect(screen.queryByText('Private inventory')).not.toBeInTheDocument(); await act(async () => release()); await screen.findByText('Private inventory'); @@ -149,7 +153,7 @@ describe('host inventory session isolation', () => { it.each(['logout', 'failure'])('clears visible data when focus verification observes %s', async outcome => { let expired = false; - mountHost(() => { + await mountHost(() => { if (expired && outcome === 'failure') throw new Response('Synthetic failure', { status: 503 }); if (expired) return { user: null }; return { user: { metadata: { uid: 'staff-a' } } }; @@ -170,7 +174,7 @@ describe('host inventory session isolation', () => { const query = useQuery({ queryKey: ['inventory'], queryFn: inventoryRead, staleTime: Infinity }); return

        {query.data}

        ; } - mountHost(async () => { + await mountHost(async () => { if (++reads > 1) await new Promise(resolve => { release = resolve; }); return { user: { metadata: { uid: 'staff-a' } } }; }, ); @@ -193,7 +197,7 @@ describe('host inventory session isolation', () => { }); it('does not read inventory without an authenticated loader identity', async () => { - mountHost(() => ({ user: null }), 'Restricted inventory'); + await mountHost(() => ({ user: null }), 'Restricted inventory'); await screen.findByText('Your session has expired'); expect(screen.queryByText('Restricted inventory')).not.toBeInTheDocument(); }); @@ -206,7 +210,7 @@ describe('host inventory session isolation', () => { const query = useQuery({ queryKey: ['inventory'], queryFn: read }); return

        {query.data}

        ; } - const router = mountHost(async () => { + const router = await mountHost(async () => { if (principal === 'staff-b') await new Promise(resolve => { release = resolve; }); return { user: { metadata: { uid: principal } } }; }, ); @@ -223,7 +227,7 @@ describe('host inventory session isolation', () => { it('hides background data and revalidates the actual host loader before restoring it', async () => { const loader = vi.fn(() => ({ user: { metadata: { uid: 'staff-a' } } })); - mountHost(loader, 'Restricted inventory'); + await mountHost(loader, 'Restricted inventory'); await screen.findByText('Restricted inventory'); const visibility = vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('hidden'); fireEvent(document, new Event('visibilitychange')); @@ -239,7 +243,7 @@ describe('host inventory session isolation', () => { it('only restores the newest foreground generation after successive pagehide and focus events', async () => { const releases: (() => void)[] = []; let reads = 0; - mountHost(async () => { + await mountHost(async () => { if (++reads > 1) await new Promise(resolve => releases.push(resolve)); return { user: { metadata: { uid: 'staff-a' } } }; }, 'Private inventory'); From 50b17ae86dfb71d376119ec8bf34f25caccef70a Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sat, 21 Nov 2026 19:51:03 -0600 Subject: [PATCH 059/518] feat(inventory): Record Devices that have no hardware identity Passive gear such as patch panels, and active gear whose serial was never recorded, could not be registered because a Device required a serial or system UUID. Cables reference Devices, so most cabling could not be represented. A Device can now set identity.unidentified: true with a required, nonblank identity.unidentifiedReason, and then carries no serial or system UUID. Every Device has exactly one of the two forms. The marker is part of identity and stays immutable, so recording a serial later is a new Device. An unidentified Device cannot record a BMC endpoint, and CapacityBackingError is the deviceRef resolution contract that rejects it as MachineCapacity backing. The staff portal shows the marker and its reason. Co-Authored-By: Claude Opus 5.5 --- .../inventory/crds/fleet.datumapis.com.yaml | 23 ++- docs/development/README.md | 3 +- docs/development/staff-inventory-ui.md | 3 + docs/operations/physical-inventory.md | 70 ++++++- internal/api/inventory/v1alpha1/capacity.go | 31 +++ internal/api/inventory/v1alpha1/types.go | 10 +- .../inventory/v1alpha1/unidentified_test.go | 187 ++++++++++++++++++ .../src/components/inventory-table.tsx | 2 +- .../components/physical-inventory.test.tsx | 9 + .../src/components/physical-inventory.tsx | 5 +- ui/provider/src/pages/device-claim-detail.tsx | 1 + ui/shared/fleet-api.ts | 4 +- 12 files changed, 337 insertions(+), 11 deletions(-) create mode 100644 internal/api/inventory/v1alpha1/capacity.go create mode 100644 internal/api/inventory/v1alpha1/unidentified_test.go diff --git a/config/components/inventory/crds/fleet.datumapis.com.yaml b/config/components/inventory/crds/fleet.datumapis.com.yaml index c4d08a6c..53944a42 100644 --- a/config/components/inventory/crds/fleet.datumapis.com.yaml +++ b/config/components/inventory/crds/fleet.datumapis.com.yaml @@ -223,6 +223,10 @@ spec: type: string priority: 1 jsonPath: .spec.identity.systemUUID + - name: Unidentified + type: boolean + priority: 1 + jsonPath: .spec.identity.unidentified - name: Age type: date jsonPath: .metadata.creationTimestamp @@ -248,6 +252,8 @@ spec: message: claimRef is immutable; bind replacement hardware as a new Device - rule: self.identity == oldSelf.identity message: identity is immutable; a hardware swap is a new Device + - rule: '!has(self.identity.unidentified) || !has(self.bmc)' + message: a device without hardware identity cannot record a BMC endpoint; it cannot be enrolled as machine capacity - rule: '!has(oldSelf.reportedPlacement) || has(self.reportedPlacement)' message: retain a report; omit unknown location fields rather than removing the report - rule: '!has(self.reportedPlacement) || (oldSelf.hasValue() && has(oldSelf.value().reportedPlacement) ? (self.reportedPlacement == oldSelf.value().reportedPlacement || self.reportedPlacement.revision == oldSelf.value().reportedPlacement.revision + 1) : self.reportedPlacement.revision == 1)' @@ -358,8 +364,14 @@ spec: required: - model x-kubernetes-validations: - - rule: has(self.serial) || has(self.systemUUID) - message: a device needs a serial or system UUID + - rule: has(self.serial) || has(self.systemUUID) || has(self.unidentified) + message: a device needs a serial or system UUID, or unidentified set to true with a reason + - rule: '!has(self.unidentified) || self.unidentified' + message: unidentified may only be true; omit it when the device has a serial or system UUID + - rule: has(self.unidentified) == has(self.unidentifiedReason) + message: unidentified and unidentifiedReason must be set together + - rule: '!has(self.unidentified) || (!has(self.serial) && !has(self.systemUUID))' + message: an unidentified device cannot carry a serial or system UUID; record identified hardware as a new Device properties: manufacturer: type: string @@ -375,6 +387,13 @@ spec: systemUUID: type: string pattern: ^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$ + unidentified: + type: boolean + unidentifiedReason: + type: string + minLength: 1 + maxLength: 1024 + pattern: '\S' bmc: type: object required: diff --git a/docs/development/README.md b/docs/development/README.md index 76119506..83f8fd67 100644 --- a/docs/development/README.md +++ b/docs/development/README.md @@ -764,7 +764,8 @@ CRDs, ProtectedResources, and the `fleet.datumapis.com-inventory-viewer` and Records carry no attribution fields: resource audit logs record who changed a record and `metadata.creationTimestamp` records when it was created. CEL requires -a Device serial or system UUID and keeps a Device's `claimRef` and identity immutable, +a Device serial or system UUID, or the explicit `identity.unidentified` marker +with a reason and neither, and keeps a Device's `claimRef` and identity immutable, rejects duplicate or ambiguous MACs, and accepts only credential-free `https` BMC endpoints. Status is a reserved subresource with no fields and no writer. No metal role grants inventory access. diff --git a/docs/development/staff-inventory-ui.md b/docs/development/staff-inventory-ui.md index ccaf7d14..e89c6ac7 100644 --- a/docs/development/staff-inventory-ui.md +++ b/docs/development/staff-inventory-ui.md @@ -56,6 +56,9 @@ pixel identity or completed authenticated staging acceptance. - Create Facility/Rack facts; rack height is optional. Create an Installation plan at a known Facility or Rack with unknown unit position, then separately register a Device with a real serial or system UUID and typed components. + The form does not offer the `identity.unidentified` marker; record such a + Device through the API. Directory and detail views show the marker and its + reason as "No hardware identity". This is not an atomic multi-record workflow or an adoption operation. - Create Cable records with a medium and named lanes using existing readable Device/PowerFeed components with recorded positions. No guessed ports, cable diff --git a/docs/operations/physical-inventory.md b/docs/operations/physical-inventory.md index fcc092b0..45dbf388 100644 --- a/docs/operations/physical-inventory.md +++ b/docs/operations/physical-inventory.md @@ -28,7 +28,7 @@ where facts came from on its own labels and annotations. | Kind | What it is | Writer | | --- | --- | --- | | `DeviceClaim` | An observational installation plan with expected model and known placement. New records use typed placement and Cable references; existing long-lived slots retain their legacy representation. | Installation planner, through the record's explicitly assigned writer | -| `Device` | One actual asset, bound to exactly one DeviceClaim when detected hardware is registered. It carries the serial and SMBIOS system UUID, the model, an optional BMC endpoint, and interfaces. | The registrar (an operator, for now) | +| `Device` | One actual asset, bound to exactly one DeviceClaim when detected hardware is registered. It carries the serial and SMBIOS system UUID, or an explicit marker that neither is on record, the model, an optional BMC endpoint, and interfaces. | The registrar (an operator, for now) | | `Facility` / `Rack` | Explicit premises and rack definitions; membership is not free-capacity evidence. | Inventory operator through the environment's existing writer | | `Cable` / `PowerFeed` | Typed termination/lane topology and physical supply dependencies. | Inventory operator through the environment's existing writer | @@ -131,7 +131,8 @@ in the provider project. The plugin never writes. | --- | --- | --- | | Records carry no attribution fields | All six | Resource audit logs record who changed a record and `metadata.creationTimestamp` records when it was created. A writer that needs to remember where facts came from uses its own labels and annotations. | | `claimRef` is required and immutable | Device | A Device binds to exactly one claim, and moving hardware to another slot is not an edit. | -| `identity` is immutable, including adding missing fields; requires a serial or system UUID | Device | Neither proves chassis identity. Legacy bindings are preserved; hardware handover is not automated. | +| `identity` is immutable, including adding missing fields; requires a serial or system UUID, or `unidentified: true` with a reason and neither | Device | Neither proves chassis identity. Legacy bindings are preserved; hardware handover is not automated. See [Devices without hardware identity](#devices-without-hardware-identity). | +| An unidentified Device cannot record a `bmc` endpoint | Device | Equipment that cannot be matched to a chassis must not be enrolled as machine capacity. | | Serial is optional | DeviceClaim | It is usually unknown at plan time. | | Port and interface names are unique; MACs are lowercase and colon-separated, appear at most once per Device, and are either mapped to an interface or listed in `unmappedMACAddresses`, not both | Both | Malformed or ambiguous facts are rejected. | | The system UUID is in lowercase canonical form | Device | One spelling per identity. | @@ -142,6 +143,67 @@ The CRDs cannot check that `claimRef` names an existing DeviceClaim, because CEL cannot read other objects. Until a registrar enforces it, the operator creates the claim first. +## Devices without hardware identity + +Some equipment has no serial or system UUID on record: passive gear such as +patch panels and cable managers, and active gear such as PDUs, switches, +routers or console servers whose serial was never recorded or does not exist. +Cables reference Devices, so this equipment still needs a Device record. +Record it with an explicit marker instead of inventing a serial: + +```yaml +spec: + claimRef: + name: rack-01-u40 + identity: + manufacturer: Example Vendor + model: Example 24-port panel + unidentified: true + unidentifiedReason: passive patch panel; no serial on the chassis +``` + +The rules: + +- `identity.unidentified` may only be `true`. Omit it for a Device with a + serial or system UUID; there is no `false` spelling. +- `identity.unidentifiedReason` is required with the marker and allowed only + with it: 1 to 1024 characters, not all whitespace. Say why no identity is + recorded, not where the record came from. +- A marked Device carries no `serial` and no `systemUUID`. Every Device has + exactly one of the two forms. +- The marker is part of `identity` and is immutable. If a serial is found or + recorded later, create a new Device with that identity against the same + claim, as for a hardware swap. Cables that name the old Device keep naming + it until they are updated. +- A marked Device cannot record `bmc`. + +Use the marker only when no serial or system UUID is known. Do not use it to +skip reading a serial that the equipment reports, and do not put an asset tag +or provider host ID in `serial` to avoid it. + +**What it prevents.** A Device without hardware identity cannot back a +MachineCapacity. Nothing can match it to a chassis, so enrollment, wiping and +allocation could reach the wrong machine. Two things enforce this today: + +- Admission rejects a `bmc` endpoint on a marked Device, so it has no + management endpoint to enroll through. +- `CapacityBackingError` in `internal/api/inventory/v1alpha1` is the + resolution contract for `MachineCapacity.spec.deviceRef`. It returns + `ErrUnidentifiedDevice` for a marked Device and `ErrDeviceIdentityMissing` + for one with no identity at all. Any resolver of `deviceRef` must call it + and treat a non-nil result as ineligible. + +Nothing resolves `deviceRef` yet: the allocator uses the name only to form the +asset key and never reads the Device. Admission cannot check the reference +either, because MachineCapacity is a separate API group and CEL cannot read +other objects. Until a resolver exists, operators must not create a +MachineCapacity whose `deviceRef` names a marked Device, just as they must not +name a Device that does not exist. + +A marked Device still binds to a DeviceClaim through `claimRef`. Do not bind it +to a claim whose `expectedIdentity.serial` is set; that claim expects +identified hardware. Admission cannot check this across objects. + Use `unmappedMACAddresses` for MACs detected on the asset that cannot yet be attributed to a named port. Do not guess a mapping; #63 requires an authenticated, complete NIC mapping before any network path depends on it. @@ -165,7 +227,9 @@ authenticated, complete NIC mapping before any network path depends on it. with position, height and face. Never guess a rack position. Use a new record only for a genuinely new installation, not to evade an existing immutable binding. 4. Register an actual Device against that claim only when its identity is known. - A manual Device requires a real serial or system UUID; if neither is known, + A manual Device requires a real serial or system UUID. If neither exists or + was recorded, use the explicit + [no-hardware-identity marker](#devices-without-hardware-identity); otherwise keep the plan and defer registration. Provider host IDs and asset tags are not serials. Use typed `components` and `topologyAuthority: Cable`; put expected connections in Cable records, not `ports.expectedPeer` or `interfaces.peer`. diff --git a/internal/api/inventory/v1alpha1/capacity.go b/internal/api/inventory/v1alpha1/capacity.go new file mode 100644 index 00000000..664fcc61 --- /dev/null +++ b/internal/api/inventory/v1alpha1/capacity.go @@ -0,0 +1,31 @@ +package v1alpha1 + +import "errors" + +var ( + // ErrUnidentifiedDevice means a Device was recorded without hardware + // identity and cannot back MachineCapacity. + ErrUnidentifiedDevice = errors.New("device has no recorded hardware identity and cannot back machine capacity") + // ErrDeviceIdentityMissing means a Device carries neither a serial nor a + // system UUID, for example a legacy record whose only identity was pruned. + ErrDeviceIdentityMissing = errors.New("device has no serial or system UUID and cannot back machine capacity") +) + +// CapacityBackingError reports why a Device cannot back a MachineCapacity, or +// nil when it may. Nothing resolves MachineCapacity.spec.deviceRef yet; any +// resolver that does must call this and treat a non-nil result as ineligible. +// It checks only recorded identity, which is matching evidence: a nil result +// is not verification or allocator eligibility. +func CapacityBackingError(device *Device) error { + if device == nil { + return ErrDeviceIdentityMissing + } + identity := device.Spec.Identity + if identity.Unidentified || identity.UnidentifiedReason != "" { + return ErrUnidentifiedDevice + } + if identity.Serial == "" && identity.SystemUUID == "" { + return ErrDeviceIdentityMissing + } + return nil +} diff --git a/internal/api/inventory/v1alpha1/types.go b/internal/api/inventory/v1alpha1/types.go index d0c82e23..7d101b1a 100644 --- a/internal/api/inventory/v1alpha1/types.go +++ b/internal/api/inventory/v1alpha1/types.go @@ -123,13 +123,21 @@ type LocalReference struct { } // DeviceIdentity is the detected chassis identity. Serial and SystemUUID are -// matching evidence, not authenticators; at least one is required. +// matching evidence, not authenticators. A Device carries at least one of +// them, or sets Unidentified with neither. type DeviceIdentity struct { Manufacturer string `json:"manufacturer,omitempty"` Model string `json:"model"` Serial string `json:"serial,omitempty"` // SystemUUID is the SMBIOS system UUID in lowercase canonical form. SystemUUID string `json:"systemUUID,omitempty"` + // Unidentified records deliberately that the equipment has no serial or + // system UUID on record, such as a patch panel. It may only be true, needs + // UnidentifiedReason, and excludes Serial and SystemUUID. Like the rest of + // identity it is immutable: recording a serial later is a new Device. An + // unidentified Device cannot back MachineCapacity. + Unidentified bool `json:"unidentified,omitempty"` + UnidentifiedReason string `json:"unidentifiedReason,omitempty"` } // BMC records where the management controller was reached. Credentials never diff --git a/internal/api/inventory/v1alpha1/unidentified_test.go b/internal/api/inventory/v1alpha1/unidentified_test.go new file mode 100644 index 00000000..c940c5c1 --- /dev/null +++ b/internal/api/inventory/v1alpha1/unidentified_test.go @@ -0,0 +1,187 @@ +package v1alpha1 + +import ( + "context" + "errors" + "os" + "path/filepath" + "strings" + "testing" + + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/util/validation/field" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/envtest" +) + +// syntheticPatchPanel is passive equipment with no serial or system UUID on +// record, registered with the explicit marker so Cables can reference it. +func syntheticPatchPanel() Device { + device := syntheticDevice() + device.Name = "rack-01-u40-patch-panel" + device.Spec.ClaimRef = LocalReference{Name: "rack-01-u40"} + device.Spec.Identity = DeviceIdentity{Manufacturer: "Example Vendor", Model: "Example 24-port panel", Unidentified: true, UnidentifiedReason: "passive patch panel; no serial on the chassis"} + device.Spec.BMC, device.Spec.Interfaces, device.Spec.UnmappedMACAddresses = nil, nil, nil + device.Spec.TopologyAuthority = "Cable" + device.Spec.Components = []Component{{ID: "front", Name: "Front ports", Type: "FrontPort", Positions: 24}, {ID: "rear", Name: "Rear ports", Type: "RearPort", Positions: 24}} + return device +} + +func rejectedWith(errs field.ErrorList, message string) bool { + for _, err := range errs { + if strings.Contains(err.Error(), message) { + return true + } + } + return false +} + +func TestUnidentifiedMarkerAdmitsDeviceWithoutSerial(t *testing.T) { + if errs := admit(t, "Device", object(t, syntheticPatchPanel()), nil); len(errs) > 0 { + t.Fatalf("unidentified device rejected: %v", errs) + } +} + +func TestUnidentifiedMarkerRules(t *testing.T) { + for name, tc := range map[string]struct { + mutate func(*DeviceIdentity) + message string + }{ + "marker with serial": {func(i *DeviceIdentity) { i.Serial = "SYNTHETIC-0040" }, "cannot carry a serial or system UUID"}, + "marker with system UUID": {func(i *DeviceIdentity) { i.SystemUUID = "00000000-0000-4000-8000-000000000040" }, "cannot carry a serial or system UUID"}, + "neither marker nor identity": {func(i *DeviceIdentity) { i.Unidentified, i.UnidentifiedReason = false, "" }, + "a device needs a serial or system UUID"}, + "marker without reason": {func(i *DeviceIdentity) { i.UnidentifiedReason = "" }, "must be set together"}, + "blank reason": {func(i *DeviceIdentity) { i.UnidentifiedReason = " \t " }, "unidentifiedReason"}, + "reason without marker": {func(i *DeviceIdentity) { i.Unidentified, i.Serial = false, "SYNTHETIC-0040" }, "must be set together"}, + "overlong reason": {func(i *DeviceIdentity) { i.UnidentifiedReason = strings.Repeat("x", 1025) }, "unidentifiedReason"}, + } { + device := syntheticPatchPanel() + tc.mutate(&device.Spec.Identity) + if errs := admit(t, "Device", object(t, device), nil); !rejectedWith(errs, tc.message) { + t.Errorf("%s: want rejection containing %q, got %v", name, tc.message, errs) + } + } + explicitFalse := object(t, syntheticDevice()) + explicitFalse["spec"].(map[string]any)["identity"].(map[string]any)["unidentified"] = false + if errs := admit(t, "Device", explicitFalse, nil); !rejectedWith(errs, "unidentified may only be true") { + t.Errorf("unidentified: false accepted: %v", errs) + } +} + +func TestUnidentifiedIdentityIsImmutable(t *testing.T) { + old := object(t, syntheticPatchPanel()) + identified := syntheticPatchPanel() + identified.Spec.Identity.Unidentified, identified.Spec.Identity.UnidentifiedReason, identified.Spec.Identity.Serial = false, "", "SYNTHETIC-0040" + for name, mutate := range map[string]func(*DeviceIdentity){ + "add serial": func(i *DeviceIdentity) { *i = identified.Spec.Identity }, + "change reason": func(i *DeviceIdentity) { i.UnidentifiedReason = "cable manager" }, + } { + device := syntheticPatchPanel() + mutate(&device.Spec.Identity) + if errs := admit(t, "Device", object(t, device), old); !rejectedWith(errs, "identity is immutable") { + t.Errorf("%s: want immutability rejection, got %v", name, errs) + } + } + marked := syntheticDevice() + marked.Spec.BMC = nil + marked.Spec.Identity = syntheticPatchPanel().Spec.Identity + if errs := admit(t, "Device", object(t, marked), object(t, syntheticDevice())); !rejectedWith(errs, "identity is immutable") { + t.Errorf("marking an identified device unidentified: want immutability rejection, got %v", errs) + } + renamed := syntheticPatchPanel() + renamed.Spec.DisplayName = "Rack 01 patch panel" + if errs := admit(t, "Device", object(t, renamed), old); len(errs) > 0 { + t.Errorf("non-identity edit of an unidentified device rejected: %v", errs) + } +} + +// An unidentified Device cannot record a BMC, the management endpoint +// enrollment would use, and the capacity contract rejects it. +func TestUnidentifiedDeviceCannotBackCapacity(t *testing.T) { + withBMC := syntheticPatchPanel() + withBMC.Spec.BMC = &BMC{Endpoint: "https://192.0.2.140:443"} + if errs := admit(t, "Device", object(t, withBMC), nil); !rejectedWith(errs, "cannot record a BMC endpoint") { + t.Errorf("unidentified device with a BMC: want rejection, got %v", errs) + } + panel := syntheticPatchPanel() + if err := CapacityBackingError(&panel); !errors.Is(err, ErrUnidentifiedDevice) { + t.Errorf("unidentified device: got %v, want ErrUnidentifiedDevice", err) + } + reasonOnly := syntheticPatchPanel() + reasonOnly.Spec.Identity.Unidentified = false + if err := CapacityBackingError(&reasonOnly); !errors.Is(err, ErrUnidentifiedDevice) { + t.Errorf("device with only an unidentified reason: got %v, want ErrUnidentifiedDevice", err) + } + pruned := syntheticDevice() + pruned.Spec.Identity.Serial, pruned.Spec.Identity.SystemUUID = "", "" + if err := CapacityBackingError(&pruned); !errors.Is(err, ErrDeviceIdentityMissing) { + t.Errorf("device without identity: got %v, want ErrDeviceIdentityMissing", err) + } + if err := CapacityBackingError(nil); !errors.Is(err, ErrDeviceIdentityMissing) { + t.Errorf("missing device: got %v, want ErrDeviceIdentityMissing", err) + } + for _, mutate := range []func(*DeviceIdentity){ + func(i *DeviceIdentity) {}, + func(i *DeviceIdentity) { i.SystemUUID = "" }, + func(i *DeviceIdentity) { i.Serial = "" }, + } { + device := syntheticDevice() + mutate(&device.Spec.Identity) + if err := CapacityBackingError(&device); err != nil { + t.Errorf("identified device %+v rejected: %v", device.Spec.Identity, err) + } + } +} + +// TestUnidentifiedMarkerAgainstAPIServer checks the same rules in a real API +// server, including the update path. It needs envtest binaries +// (KUBEBUILDER_ASSETS) and is skipped without them. +func TestUnidentifiedMarkerAgainstAPIServer(t *testing.T) { + if os.Getenv("KUBEBUILDER_ASSETS") == "" { + t.Skip("KUBEBUILDER_ASSETS is not set; see docs/development/README.md") + } + env := &envtest.Environment{CRDDirectoryPaths: []string{filepath.Join(inventoryRoot, "crds")}, ErrorIfCRDPathMissing: true} + cfg, err := env.Start() + if err != nil { + t.Fatalf("start envtest: %v", err) + } + t.Cleanup(func() { _ = env.Stop() }) + c, err := client.New(cfg, client.Options{}) + if err != nil { + t.Fatal(err) + } + ctx := context.Background() + toUnstructured := func(device Device) *unstructured.Unstructured { + device.Namespace = "default" + return &unstructured.Unstructured{Object: object(t, device)} + } + + panel := toUnstructured(syntheticPatchPanel()) + if err := c.Create(ctx, panel); err != nil { + t.Fatalf("create unidentified device: %v", err) + } + for name, mutate := range map[string]func(*Device){ + "marker with serial": func(d *Device) { d.Spec.Identity.Serial = "SYNTHETIC-0041" }, + "blank reason": func(d *Device) { d.Spec.Identity.UnidentifiedReason = " " }, + "neither": func(d *Device) { + d.Spec.Identity.Unidentified, d.Spec.Identity.UnidentifiedReason = false, "" + }, + "BMC": func(d *Device) { d.Spec.BMC = &BMC{Endpoint: "https://192.0.2.141:443"} }, + } { + device := syntheticPatchPanel() + device.Name = "rejected-" + strings.ReplaceAll(name, " ", "-") + mutate(&device) + if err := c.Create(ctx, toUnstructured(device)); err == nil { + t.Errorf("%s: create accepted", name) + } + } + + identity := panel.Object["spec"].(map[string]any)["identity"].(map[string]any) + delete(identity, "unidentified") + delete(identity, "unidentifiedReason") + identity["serial"] = "SYNTHETIC-0041" + if err := c.Update(ctx, panel); err == nil || !strings.Contains(err.Error(), "identity is immutable") { + t.Errorf("adding a serial to an unidentified device: got %v, want immutability rejection", err) + } +} diff --git a/ui/provider/src/components/inventory-table.tsx b/ui/provider/src/components/inventory-table.tsx index 8076ad40..1262d2b3 100644 --- a/ui/provider/src/components/inventory-table.tsx +++ b/ui/provider/src/components/inventory-table.tsx @@ -63,7 +63,7 @@ export function InventoryTable({ slots, base }: { slots: InventorySlot[]; base: header: 'Serial', cell: ({ row }) => { const device = currentDevice(row.original); - return {device?.spec.identity.serial ?? row.original.claim.spec.expectedIdentity.serial ?? '—'}; + return {device?.spec.identity.serial ?? (device?.spec.identity.unidentified ? 'No hardware identity' : row.original.claim.spec.expectedIdentity.serial ?? '—')}; }, }, ]; diff --git a/ui/provider/src/components/physical-inventory.test.tsx b/ui/provider/src/components/physical-inventory.test.tsx index 7582c051..d53f7a58 100644 --- a/ui/provider/src/components/physical-inventory.test.tsx +++ b/ui/provider/src/components/physical-inventory.test.tsx @@ -155,6 +155,15 @@ describe('hardware directory', () => { expect(screen.getByText('Claim record not found')).toBeInTheDocument(); }); + it('shows the explicit no-hardware-identity marker instead of a missing serial', () => { + const original = fixturePhysicalDevices[0]; + const panel = { ...original, metadata: { ...original.metadata, name: 'synthetic-patch-panel' }, spec: { ...original.spec, displayName: 'Synthetic patch panel', bmc: undefined, identity: { model: 'Example 24-port panel', unidentified: true, unidentifiedReason: 'passive panel; no serial on the chassis' } } }; + browse('?kind=Device', toInventory(fixturePhysicalClaims, [panel])); + expect(screen.getByText('No hardware identity')).toBeInTheDocument(); + fireEvent.click(screen.getByRole('link', { name: 'Synthetic patch panel' })); + expect(screen.getByText(/passive panel; no serial on the chassis · cannot back machine capacity/)).toBeInTheDocument(); + }); + it('does not fabricate a rack relationship from legacy location text', () => { const legacy = { ...fixturePhysicalClaims[0], spec: { ...fixturePhysicalClaims[0].spec, placement: { facility: 'example-facility', rack: 'rack-01', position: 12 } } }; browse('?kind=Rack&record=rack-01&namespace=default', toInventory([legacy], [], [fixturePhysicalRecords[1]])); diff --git a/ui/provider/src/components/physical-inventory.tsx b/ui/provider/src/components/physical-inventory.tsx index bef2aaf3..b7c23033 100644 --- a/ui/provider/src/components/physical-inventory.tsx +++ b/ui/provider/src/components/physical-inventory.tsx @@ -218,7 +218,7 @@ export function PhysicalInventory({ inventory: source, onRetry, showNavigation = const target = find(kind, entry.record.metadata.namespace, name); return [name, target ? recordName(target) : '', endpoint.componentID]; }) : []; - return [recordName(entry), entry.record.metadata.name, entry.record.metadata.namespace, summary(entry), placement(entry), device?.spec.identity.serial, device?.spec.identity.systemUUID, device?.spec.assetTag, ...(endpoints ?? [])].filter(Boolean).join(' ').toLowerCase(); + return [recordName(entry), entry.record.metadata.name, entry.record.metadata.namespace, summary(entry), placement(entry), device?.spec.identity.serial, device?.spec.identity.systemUUID, device?.spec.identity.unidentifiedReason, device?.spec.assetTag, ...(endpoints ?? [])].filter(Boolean).join(' ').toLowerCase(); }; const matching = records .filter(entry => (!locationFilter || locationKey(entry) === locationFilter) && (!modelFilter || modelKey(entry) === modelFilter)) @@ -328,6 +328,7 @@ export function PhysicalInventory({ inventory: source, onRetry, showNavigation = {device.spec.identity.serial} {device.spec.assetTag} {device.spec.identity.systemUUID} + {device.spec.identity.unidentified && No serial or system UUID recorded · {device.spec.identity.unidentifiedReason} · cannot back machine capacity} {reference('DeviceClaim', namespace, device.spec.claimRef.name)} @@ -667,7 +668,7 @@ export function PhysicalInventory({ inventory: source, onRetry, showNavigation = {entry.kind === 'Cable' ? (entry.record as PhysicalRecord).spec.lanes?.map(lane =>
        ) : entry.kind === 'Device' ? ( <> - {(entry.record as RawDevice).spec.identity.serial ?? 'Serial not recorded'} + {(entry.record as RawDevice).spec.identity.serial ?? ((entry.record as RawDevice).spec.identity.unidentified ? 'No hardware identity' : 'Serial not recorded')} {(entry.record as RawDevice).spec.assetTag ?? 'Asset tag not recorded'} diff --git a/ui/provider/src/pages/device-claim-detail.tsx b/ui/provider/src/pages/device-claim-detail.tsx index c9d9ed9a..4dc14817 100644 --- a/ui/provider/src/pages/device-claim-detail.tsx +++ b/ui/provider/src/pages/device-claim-detail.tsx @@ -49,6 +49,7 @@ function DeviceSection({ device, current, inventory }: { device: RawDevice; curr {device.spec.modelShape?.heightUnits ?? 'Unknown'} U {identity.serial ?? '—'} {identity.systemUUID ?? '—'} + {identity.unidentified && No serial or system UUID recorded · {identity.unidentifiedReason} · cannot back machine capacity} {bmc?.endpoint ?? '—'} {device.spec.claimRef.name} {device.spec.assetTag ?? 'Unknown'} diff --git a/ui/shared/fleet-api.ts b/ui/shared/fleet-api.ts index 9d4aaaec..170ff16b 100644 --- a/ui/shared/fleet-api.ts +++ b/ui/shared/fleet-api.ts @@ -263,7 +263,9 @@ export interface Device { spec: { reportedPlacement?: ReportedPlacement; claimRef: LocalReference; - identity: { manufacturer?: string; model: string; serial?: string; systemUUID?: string }; + // unidentified records deliberately that no serial or system UUID exists; + // it excludes both and requires unidentifiedReason. + identity: { manufacturer?: string; model: string; serial?: string; systemUUID?: string; unidentified?: boolean; unidentifiedReason?: string }; assetTag?: string; displayName?: string; modelShape?: { heightUnits?: number; fullDepth?: boolean }; From 0644a207f1f7200c6df90e54ad00c92b2455a15c Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sat, 21 Nov 2026 20:09:42 -0600 Subject: [PATCH 060/518] fix(provider-ui): scope inventory to default and stabilize access chrome --- docs/development/staff-inventory-ui.md | 85 ++++++++++++++++- ui/provider/README.md | 15 ++- .../components/adversarial-review.test.tsx | 7 +- .../components/device-placement-edit.test.tsx | 6 +- .../src/components/device-placement-edit.tsx | 7 +- .../exact-head-independent.test.tsx | 7 +- .../src/components/hardware-catalog.test.tsx | 3 +- .../inventory-default-layout.test.tsx | 94 +++++++++++++++++++ .../inventory-directory-heading.tsx | 42 +++++++++ .../inventory-hardware-fields.test.tsx | 8 +- .../inventory-management-lifetime.test.tsx | 3 +- .../components/inventory-management.test.tsx | 6 +- .../src/components/inventory-management.tsx | 31 +++--- .../inventory-navigation-safety.test.tsx | 5 +- .../src/components/inventory-navigation.tsx | 6 +- .../components/inventory-read-access.test.tsx | 7 +- .../inventory-revalidation-safety.test.tsx | 5 +- .../components/inventory-session-boundary.tsx | 12 +-- .../inventory-stable-controls.test.tsx | 3 +- .../inventory-tab-navigation.test.tsx | 7 +- .../src/components/inventory-table.tsx | 3 +- .../inventory-visible-focus-save.test.tsx | 3 +- .../src/components/physical-inventory.css | 9 +- .../components/physical-inventory.test.tsx | 15 +-- .../src/components/physical-inventory.tsx | 57 +++-------- .../pr103-review-negatives.test.tsx | 7 +- .../reviewer-exact-staging.test.tsx | 3 +- .../src/components/site-inventory.test.tsx | 10 +- ui/provider/src/lib/api.ts | 15 +-- .../src/lib/device-placement-edit.test.ts | 2 +- ui/provider/src/lib/device-placement-edit.ts | 3 +- ui/provider/src/lib/inventory-api.test.ts | 8 +- .../src/lib/inventory-hardware.test.ts | 8 +- .../src/lib/inventory-management.test.ts | 4 +- ui/provider/src/lib/inventory-management.ts | 6 +- .../src/lib/inventory-namespace.test.ts | 73 ++++++++++++++ ui/provider/src/lib/inventory-namespace.ts | 5 + ui/provider/src/lib/inventory-read-access.ts | 9 +- ui/provider/src/pages/device-claim-detail.tsx | 10 +- .../src/pages/device-inventory-list.tsx | 7 +- .../src/pages/device-inventory.test.tsx | 14 ++- ui/provider/src/test/enabled-button.ts | 7 ++ 42 files changed, 475 insertions(+), 162 deletions(-) create mode 100644 ui/provider/src/components/inventory-default-layout.test.tsx create mode 100644 ui/provider/src/components/inventory-directory-heading.tsx create mode 100644 ui/provider/src/lib/inventory-namespace.test.ts create mode 100644 ui/provider/src/lib/inventory-namespace.ts create mode 100644 ui/provider/src/test/enabled-button.ts diff --git a/docs/development/staff-inventory-ui.md b/docs/development/staff-inventory-ui.md index ccaf7d14..883487fa 100644 --- a/docs/development/staff-inventory-ui.md +++ b/docs/development/staff-inventory-ui.md @@ -1,5 +1,88 @@ # Staff physical inventory UI +## Default-only directory and stable controls + +Implemented on top of `baa210318fe17927f447a8e9e9e8053a23f6b173` on +`feat/manual-inventory-records`. This update supersedes the namespace-choice and +access-dependent navigation descriptions in the historical phase notes below. + +- All nine inventory collections, including Sites, Manufacturers, and DeviceTypes, + are read from `/namespaces/default/`, including every continuation page. + Collection responses and rendered inventory are filtered to explicit `default` + metadata; foreign and missing namespaces are not silently relabeled. +- The directory, query-string details, and legacy claim detail route cannot select + a foreign namespace. A missing query namespace means `default`; an explicit + foreign namespace shows safe unsupported-scope guidance rather than resolving + even a same-named default record. Old explicit default links still work. +- Creation, display-name editing, reported-placement editing, management reviews, + and reference rereads reject nondefault scope before any request. Reference + responses must also belong to `default`. Reference choices and relationship + projections only use readable default records. Inventory query cache keys + include the fixed namespace; real denial still redacts cached data and drafts. +- The namespace input and Namespace & access disclosure are removed. Namespace + columns and repeated default labels are unnecessary in this UI. The nine public + category labels never disappear or change their active default because of + access results. No private record names or counts appear in the public shell. +- Pending, allowed, and denied directory states share heading, action, count, + status, and search/filter layout slots. Actions remain mounted and disabled + until usable; successful authorization adds no “access checked” clutter. + Explanations for ownership restrictions, denied access, unavailable references, + expired sessions, and uncertain saves remain visible. Long failure explanations + may wrap rather than being clipped. Forms expand only after an explicit action. +- Existing immutable edit baselines, submit-time authorization, read/write + generation guards, principal/logout and hidden/pagehide fences are retained. + Visible window blur/focus remains a complete no-op, including draft, DOM, + request, loader, and operation-authority behavior. + +This is a frontend scope restriction, not a new security boundary. Backend +namespace support, schemas, IAM policies, other Bare Metal surfaces, audit logs, +and live inventory are unchanged. Backend default-only enforcement or namespace +migration remains deferred and would require separate design and authorization. + +Validation includes provider and consumer Vitest suites, typechecks and builds, +inventory Go tests, documentation links and whitespace. New synthetic tests cover +all nine kinds, static layout structure through access transitions, foreign URL +and legacy-route selection, paginated default requests, and foreign reference and +mutation guards. DOM/CSS structure checks do not prove pixel geometry in the +authenticated staff portal. No browser login manipulation, live writes, deployment, +or authenticated visual acceptance was performed for this update. + +### Platform composition follow-up (not implemented) + +The platform audit confirms that the mismatch is page/form composition, not a +missing Datum primitive library. Source exemplars reviewed from the supplied audit +archives (these are source observations, not authenticated visual acceptance): + +| Source and supplied pin | Concrete pattern | Fleet follow-up | +| --- | --- | --- | +| [Compute page chrome](https://github.com/datum-cloud/compute/blob/9521a49e10c55e13b42d652533caaa5c7fe09494/ui/consumer/src/components/workload-page-chrome.tsx) and [plugin tabs](https://github.com/datum-cloud/compute/blob/9521a49e10c55e13b42d652533caaa5c7fe09494/ui/consumer/src/components/plugin-tabs.tsx) | Breadcrumb, PageTitle actions, and line-style route tabs; disabled action while authority is pending | Standardize directory/detail breadcrumb and title/action/table chrome without copying provisioning behavior or introducing a global sidebar | +| [Cloud portal domain form](https://github.com/datum-cloud/cloud-portal/blob/7456e469a8589d03afe13623b15992e712563d0f/app/features/edge/domain/domain-form-dialog.tsx) | Focused controlled `Form.Dialog`, closing after an acknowledged successful mutation | Separate focused display-name and reported-location dialogs; compact Facility/Rack create dialogs | +| [Infra configurator part form](https://github.com/datum-cloud/infra-configurator/blob/25e5dc7d26ba892643f7dd7dadbc8711e4b1abe8/src/components/catalog/part-form-dialog.tsx) | Controlled Datum Dialog with an explicit viewport height cap and overflow scrolling | Bound dialog scrolling and keep explicit Cancel / Create record / Save changes actions accessible | + +Device, Cable, and installation-plan creation should move to dedicated child task +routes rather than expanding the directory. Inline forms intentionally remain in +this namespace/layout PR: migrating their mount points and navigation lifecycle +at the same time would change the operation fences and immutable edit baselines +this change must preserve. This PR does **not** claim whole-platform parity or +completion of the user's non-expanding-form experience. + +That follow-up must add dirty-dismissal protection, dialog focus trap and return, +bounded scrolling, and explicit dismissal coverage. Cancel after dispatch must +not imply cancellation of a write; unknown results must neither auto-close as +success nor encourage an automatic retry. Retain separate label/location writes, +all after-await guards, real hidden/logout/denial fences, and no-op visible focus. +Keep verification Unknown visible; do not invent an Activity/history API. + +The current Fleet federation configuration shares only Datum badge, button, card, +icons, and skeleton subpaths. This PR adds no shared module or dependency. +Before the follow-up imports Form/Dialog/PageTitle/Breadcrumb, verify the actual +current staff-portal host contract and decide which subpaths must be bundled; +`Form` cannot be assumed shared. Portal `Table.Client` and `useTableUrlAdapter` +are application-local and must not be imported into this remote. No second writer +or host navigation surface is introduced. + +## Historical implementation phases + The additive [Site–Facility directory](site-facility-relationship.md) extends this baseline with operational Site reads and provider-qualified premises identifiers. Its identity/membership fields are managed by direct API, not new UI forms. @@ -109,7 +192,7 @@ Implemented against PR103's merged staging base `f190d28397fc6110e02c9c83e6819a3a584258d0`. Ordinary visible window blur/focus is deliberately ignored. Opening the URL bar does not change the session: it does not suspend reads or writes, reset edit baselines, close or disable forms, -change Namespace & access disclosures, or start host/permission/inventory requests. +change controls, or start host/permission/inventory requests. Both the session boundary and individual management/location forms have no blur/focus listeners. QueryClient defaults and inventory queries disable window focus refetch. Drafts and frozen baselines remain usable without reopening. diff --git a/ui/provider/README.md b/ui/provider/README.md index 9c015e1e..b0782288 100644 --- a/ui/provider/README.md +++ b/ui/provider/README.md @@ -21,15 +21,18 @@ Operations in the navigation. The page has four tabs: MachineCapacities that serve it, and whether consumers get power control. Custom profiles and console access stay off. - **Inventory** (`inventory`) is a hardware directory, starting with - Devices rather than installation claims. Seven searchable categories cover - Devices, Operational sites, Facilities, Racks, Claims, Cables, and Power feeds. Query-string detail - links retain the kind, namespace, and record name without adding host routes. + Devices rather than installation claims. Nine static searchable categories cover + Devices, Operational sites, Facilities, Racks, Claims, Cables, Power feeds, + Manufacturers, and Device types. Inventory reads and writes use only `default`. + Query-string detail links retain the kind and record name (and accept the existing + explicit `namespace=default`) without adding host routes. Foreign namespace + links never resolve records or change request scope. Facilities lead to racks and installation plans; claims lead to all registered devices; cable endpoints lead to devices or feeds. Identity, typed components, internal paths, external service references, legacy peers, and creation times remain visible. Missing claims do not hide hardware, and historical registrations do not establish an active device. The original `inventory/:namespace/:claim` - route remains available for existing links. Authorized manual management uses + route remains available for existing `default` links. Authorized manual management uses the existing guarded forms; Site membership and premises identifiers remain direct API operations. Records are not managed through Git. See the [Site–Facility contract](../../docs/development/site-facility-relationship.md). @@ -102,7 +105,9 @@ and portal-owned display-name editing. The existing `physical-inventory-managers` group binding are not deployed by this UI phase. Group names/staff membership never enable controls. Flux-managed and unknown-writer records remain read-only pending ownership review. New inventory is direct -API/operator-managed. Namespace choice is not an authorization boundary. Denied +API/operator-managed. There is no namespace selector or namespace/access disclosure. +Default-only UI scope is not a backend authorization boundary; namespaced APIs and +existing IAM remain unchanged. Denied collections and detail links show access guidance, not empty inventory; readable sections remain available. See [hardware directory scope and design gaps](../../docs/development/staff-inventory-ui.md). diff --git a/ui/provider/src/components/adversarial-review.test.tsx b/ui/provider/src/components/adversarial-review.test.tsx index 9b3157fd..6a76c6e4 100644 --- a/ui/provider/src/components/adversarial-review.test.tsx +++ b/ui/provider/src/components/adversarial-review.test.tsx @@ -1,3 +1,4 @@ +import { findEnabledButton } from '../test/enabled-button'; import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { createMemoryRouter, Outlet, RouterProvider } from 'react-router'; @@ -77,7 +78,7 @@ it('invalidates authority synchronously before React commits the session transit })); const router = createMemoryRouter([{ id: 'layouts/milo.layout', path: '/', loader: () => ({ user: { metadata: { uid: principal } } }), element: , children: [{ index: true, element: }] }]); render(); - await screen.findByRole('button', { name: 'Create facility' }); + await findEnabledButton({ name: 'Create facility' }); fireEvent.click(screen.getByText('Manage facilities')); fireEvent.click(screen.getByRole('button', { name: 'Create facility' })); fireEvent.change(screen.getByLabelText('Record name'), { target: { value: values.name } }); @@ -105,7 +106,7 @@ it('must not send a create after the initiating authenticated principal unmounts })); const router = createMemoryRouter([{ id: 'layouts/milo.layout', path: '/', loader: () => ({ user: { metadata: { uid: principal } } }), element: , children: [{ index: true, element: }] }]); render(); - await screen.findByRole('button', { name: 'Create facility' }); + await findEnabledButton({ name: 'Create facility' }); fireEvent.click(screen.getByText('Manage facilities')); fireEvent.click(screen.getByRole('button', { name: 'Create facility' })); fireEvent.change(screen.getByLabelText('Record name'), { target: { value: values.name } }); @@ -129,7 +130,7 @@ it('must not silently advance an open edit form to a refreshed resourceVersion', const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); const content = () => ; const mounted = render(content()); - await screen.findByRole('button', { name: 'Edit display name' }); + await findEnabledButton({ name: 'Edit display name' }); fireEvent.click(screen.getByText('Manage this record')); fireEvent.click(screen.getByRole('button', { name: 'Edit display name' })); fireEvent.change(screen.getByLabelText('Display name'), { target: { value: 'My unsaved label' } }); diff --git a/ui/provider/src/components/device-placement-edit.test.tsx b/ui/provider/src/components/device-placement-edit.test.tsx index 96f58102..a0f74ae5 100644 --- a/ui/provider/src/components/device-placement-edit.test.tsx +++ b/ui/provider/src/components/device-placement-edit.test.tsx @@ -122,11 +122,11 @@ describe('reported location editor', () => { expect(screen.getByRole('button', { name: 'Save reported location' })).toBeDisabled(); expect(fetch).toHaveBeenCalledTimes(3); fireEvent.click(screen.getByRole('button', { name: 'Close location form' })); - expect(screen.queryByRole('button', { name: 'Add reported location' })).not.toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Add reported location' })).toBeDisabled(); }); - it('hides editing for denied permission and legacy Flux', () => { + it('disables editing for denied permission and legacy Flux', () => { permission.mockReturnValue({ data: false, isFetching: false, error: null } as never); setup({ ...device, metadata: { ...device.metadata, managedFields: [{ manager: 'kustomize-controller' }] } }); - expect(screen.queryByRole('button', { name: 'Add reported location' })).not.toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Add reported location' })).toBeDisabled(); }); }); diff --git a/ui/provider/src/components/device-placement-edit.tsx b/ui/provider/src/components/device-placement-edit.tsx index 6c053845..a7036009 100644 --- a/ui/provider/src/components/device-placement-edit.tsx +++ b/ui/provider/src/components/device-placement-edit.tsx @@ -91,9 +91,8 @@ function DevicePlacementForm({ device, locations, issues }: { device: Device; lo return
        Reported location

        Correct a record, not a physical move, installation handover, or reservation. Identity and claim binding stay unchanged. Blank geometry means unknown; model and claim dimensions are not copied.

        - {!editable ?

        Legacy GitOps-managed or unavailable Devices are outside this editor.

        : !permitted &&

        Device management permission must be confirmed before correcting location.

        } -

        {message || (!ready || permission.isFetching ? 'Management: verification pending.' : open && blocked ? 'Management: close and reopen this form to continue.' : allowed ? 'Management: access checked.' : 'Management: unavailable.')}

        - {permitted && !open && !needsRefresh && } + }}>{device.spec.reportedPlacement ? 'Correct location' : 'Add reported location'} {open && permitted &&

        Authenticated actor history uses existing resource audit logs.

        diff --git a/ui/provider/src/components/exact-head-independent.test.tsx b/ui/provider/src/components/exact-head-independent.test.tsx index ab99ac1c..a7f277c0 100644 --- a/ui/provider/src/components/exact-head-independent.test.tsx +++ b/ui/provider/src/components/exact-head-independent.test.tsx @@ -1,3 +1,4 @@ +import { findEnabledButton } from '../test/enabled-button'; import { StrictMode } from 'react'; import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; import { createMemoryRouter, Outlet, RouterProvider } from 'react-router'; @@ -14,7 +15,7 @@ afterEach(() => { cleanup(); vi.unstubAllGlobals(); vi.restoreAllMocks(); }); async function open(editing: boolean, label: string) { await waitFor(() => expect(screen.getByRole('button', { name: editing ? 'Edit display name' : 'Create facility' })).toBeEnabled()); - fireEvent.click(await screen.findByRole('button', { name: editing ? 'Edit display name' : 'Create facility' })); + fireEvent.click(await findEnabledButton({ name: editing ? 'Edit display name' : 'Create facility' })); if (!editing) fireEvent.change(screen.getByLabelText('Record name'), { target: { value: values.name } }); fireEvent.change(screen.getByLabelText('Display name'), { target: { value: label } }); } @@ -108,7 +109,7 @@ it.each([false, true].flatMap(strict => [401, 403, 404, 503].flatMap(status => [ const router = createMemoryRouter([{ id: 'layouts/milo.layout', path: '/', loader: () => ({ user: { metadata: { uid: 'same-user' } } }), element: , children: [{ index: true, element: }] }], { initialEntries: ['/?kind=Facility'] }); render(strict ? : ); await screen.findByRole('link', { name: /Private facility label/ }); - await screen.findByRole('button', { name: 'Create facility' }); + await findEnabledButton({ name: 'Create facility' }); phase = 'pending'; fireEvent.click(screen.getByRole('button', { name: 'Refresh inventory' })); await waitFor(() => expect(releases).toHaveLength(9)); @@ -122,7 +123,7 @@ it.each([false, true].flatMap(strict => [401, 403, 404, 503].flatMap(status => [ await act(async () => releases.forEach(release => release())); expect(screen.getByRole('heading', { name: title })).toBeInTheDocument(); expect(screen.queryByText('Private facility label')).not.toBeInTheDocument(); - expect(screen.queryByRole('button', { name: 'Create facility' })).not.toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Create facility' })).toBeDisabled(); expect(freshRequests.length).toBeGreaterThanOrEqual(9); expect(freshRequests.every(method => method === 'GET')).toBe(true); router.dispose(); diff --git a/ui/provider/src/components/hardware-catalog.test.tsx b/ui/provider/src/components/hardware-catalog.test.tsx index f377248f..568b82bc 100644 --- a/ui/provider/src/components/hardware-catalog.test.tsx +++ b/ui/provider/src/components/hardware-catalog.test.tsx @@ -1,3 +1,4 @@ +import { findEnabledButton } from '../test/enabled-button'; import { fireEvent, render, screen } from '@testing-library/react'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { MemoryRouter } from 'react-router'; @@ -42,7 +43,7 @@ describe('hardware catalog readers', () => { })); render(); fireEvent.click(screen.getByText('Manage devices')); - fireEvent.click(await screen.findByRole('button', { name: 'Create device' })); + fireEvent.click(await findEnabledButton({ name: 'Create device' })); for (const [label, value] of [['Record name', 'synthetic-new'], ['Display name', 'Synthetic record'], ['Installation plan', 'plan-uid'], ['Model', 'Observed model'], ['Serial number', 'SYNTHETIC-NEW'], ['Shared catalog model (optional)', 'model-uid']]) { fireEvent.change(screen.getByLabelText(label), { target: { value } }); } diff --git a/ui/provider/src/components/inventory-default-layout.test.tsx b/ui/provider/src/components/inventory-default-layout.test.tsx new file mode 100644 index 00000000..df15733b --- /dev/null +++ b/ui/provider/src/components/inventory-default-layout.test.tsx @@ -0,0 +1,94 @@ +import { fireEvent, render, screen, within } from '@testing-library/react'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { MemoryRouter } from 'react-router'; +import { beforeEach, expect, it, vi } from 'vitest'; +import { PhysicalInventory } from './physical-inventory'; +import { InventoryNavigation, sections } from './inventory-navigation'; +import { InventoryPendingShell } from './inventory-directory-heading'; +import { toInventory, type Inventory } from '../inventory'; +import { fixturePhysicalClaims, fixturePhysicalDevices, fixturePhysicalRecords } from '../lib/fixtures'; +import { useInventoryPermission } from '../lib/inventory-management'; +import type { PhysicalRecord } from '../../../shared/fleet-api'; +import { readFileSync } from 'node:fs'; + +const styles = readFileSync('src/components/physical-inventory.css', 'utf8'); + +vi.mock('../lib/inventory-management', async () => ({ ...await vi.importActual('../lib/inventory-management'), useInventoryPermission: vi.fn() })); +const permission = vi.mocked(useInventoryPermission); +const catalog: PhysicalRecord[] = [ + { kind: 'Manufacturer', metadata: { name: 'vendor', namespace: 'default' }, spec: { displayName: 'Private vendor' } }, + { kind: 'DeviceType', metadata: { name: 'model', namespace: 'default' }, spec: { displayName: 'Private model', model: 'Private model', manufacturerRef: { name: 'vendor' } } }, +]; +const inventory = toInventory(fixturePhysicalClaims, fixturePhysicalDevices, [...fixturePhysicalRecords, ...catalog]); +beforeEach(() => permission.mockReturnValue({ data: true, isFetching: false, error: null } as never)); + +function shape(container: HTMLElement) { + return [...container.querySelectorAll('.inventory-topline, .inventory-list-heading, .inventory-record-count, .inventory-management-controls, .inventory-management-status, .inventory-toolbar')].map(element => [element.tagName, element.className]); +} + +it.each(sections)('keeps $kind category, heading, action and filter structure across pending/allowed/denied', section => { + const client = new QueryClient(); + const view = (data?: Inventory) => {data ? :

        Checking inventory access…

        }
        ; + const result = render(view()); + const nav = screen.getByRole('navigation', { name: 'Inventory categories' }); + const navMarkup = nav.innerHTML; + const pendingShape = shape(result.container); + const toolbarLabels = [...result.container.querySelectorAll('.inventory-toolbar [aria-label]')].map(element => element.getAttribute('aria-label')); + expect(within(nav).getAllByRole('link')).toHaveLength(9); + expect(screen.getByRole('heading', { name: section.title })).toBeInTheDocument(); + expect(screen.getByRole('searchbox')).toBeDisabled(); + expect(result.container.textContent).not.toMatch(/Private vendor|Private model|Example compute server|\d+ of \d+ records/); + result.rerender(view(inventory)); + expect(shape(result.container)).toEqual(pendingShape); + expect(screen.getByRole('searchbox')).toBeEnabled(); + expect(screen.getByRole('navigation', { name: 'Inventory categories' })).toBe(nav); + expect(nav.innerHTML).toBe(navMarkup); + result.rerender(view({ ...inventory, issues: { [section.kind]: { status: 403 } } })); + expect(shape(result.container)).toEqual(pendingShape); + expect(nav.innerHTML).toBe(navMarkup); + expect(screen.getByRole('heading', { name: section.title })).toBeInTheDocument(); + expect(screen.getByRole('searchbox')).toBeDisabled(); + expect([...result.container.querySelectorAll('.inventory-toolbar [aria-label]')].map(element => element.getAttribute('aria-label'))).toEqual(toolbarLabels); + expect(screen.queryByRole('table')).not.toBeInTheDocument(); + expect(result.container.textContent).not.toMatch(/Private vendor|Private model|Example compute server|\d+ of \d+ records/); + expect(screen.queryByText('Namespace & access')).not.toBeInTheDocument(); + expect(screen.queryByLabelText('Management namespace')).not.toBeInTheDocument(); + result.rerender(view(inventory)); + expect(shape(result.container)).toEqual(pendingShape); + expect(nav.innerHTML).toBe(navMarkup); +}); + +it('retains the same action DOM while permission changes and reserves CSS geometry', () => { + const client = new QueryClient(); + const view = () => ; + permission.mockReturnValue({ data: undefined, isFetching: true, error: null } as never); + const result = render(view()); + const button = screen.getByRole('button', { name: 'Create rack' }); + const heading = screen.getByRole('heading', { name: 'Racks' }); + expect(button).toBeDisabled(); + for (const allowed of [true, false, true]) { + permission.mockReturnValue({ data: allowed, isFetching: false, error: null } as never); + result.rerender(view()); + expect(screen.getByRole('button', { name: 'Create rack' })).toBe(button); + expect(screen.getByRole('heading', { name: 'Racks' })).toBe(heading); + expect(button.hasAttribute('disabled')).toBe(!allowed); + } + expect(styles).toContain('.fleet-inventory .inventory-management-controls > button { min-width:180px; }'); + expect(styles).toContain('.fleet-inventory .inventory-record-count { min-width:130px; min-height:1.5em; }'); + expect(styles).toContain('min-height:3em;'); +}); + +it.each(sections)('rejects a forced foreign $kind detail even when a same-named record is supplied', section => { + const records = [...inventory.physical, ...fixturePhysicalDevices.map(record => ({ ...record, kind: 'Device' as const })), ...fixturePhysicalClaims.map(record => ({ ...record, kind: 'DeviceClaim' as const }))]; + const selected = records.find(record => record.kind === section.kind)!; + const foreign = { ...selected, metadata: { ...selected.metadata, namespace: 'other' }, spec: { ...selected.spec, displayName: 'Foreign private record' } }; + const source = toInventory([...fixturePhysicalClaims, ...(section.kind === 'DeviceClaim' ? [foreign as typeof fixturePhysicalClaims[number]] : [])], [...fixturePhysicalDevices, ...(section.kind === 'Device' ? [foreign as typeof fixturePhysicalDevices[number]] : [])], [...inventory.physical, ...(!['Device', 'DeviceClaim'].includes(section.kind) ? [foreign as PhysicalRecord] : [])]); + render(); + expect(screen.getByRole('heading', { name: 'Record not found' })).toBeInTheDocument(); + expect(screen.getByText(/only supports the default namespace/)).toBeInTheDocument(); + expect(screen.queryByText('Foreign private record')).not.toBeInTheDocument(); + expect(screen.queryByRole('button', { name: /Edit display name|Correct location/ })).not.toBeInTheDocument(); + fireEvent.click(within(screen.getByRole('navigation', { name: 'Inventory categories' })).getByRole('link', { name: section.title })); + expect(screen.queryByText('Foreign private record')).not.toBeInTheDocument(); + expect(screen.queryByRole('columnheader', { name: 'Namespace' })).not.toBeInTheDocument(); +}); diff --git a/ui/provider/src/components/inventory-directory-heading.tsx b/ui/provider/src/components/inventory-directory-heading.tsx new file mode 100644 index 00000000..8f296acb --- /dev/null +++ b/ui/provider/src/components/inventory-directory-heading.tsx @@ -0,0 +1,42 @@ +import { Button } from '@datum-cloud/datum-ui/button'; +import { Title } from '@datum-cloud/datum-ui/typography'; +import { Input } from '@datum-cloud/datum-ui/input'; +import { Label } from '@datum-cloud/datum-ui/label'; +import { Search } from 'lucide-react'; +import type { ReactNode } from 'react'; +import { useSearchParams } from 'react-router'; +import { sections } from './inventory-navigation'; +import './physical-inventory.css'; + +export function InventoryDirectoryHeading({ section, count, management, onRetry }: { section: typeof sections[number]; count?: string; management?: ReactNode; onRetry?: () => void }) { + const creatable = ['Facility', 'Rack', 'Device', 'Cable', 'DeviceClaim'].includes(section.kind); + return
        +
        +
        {section.title}

        {section.description}

        + {count} + +
        + {management ?? <>
        {creatable && }

        } +

        ; +} + +export function InventoryPendingShell({ children }: { children: ReactNode }) { + const [params] = useSearchParams(); + const section = sections.find(item => item.kind === params.get('kind')) ?? sections[0]; + return
        {children}
        ; +} + +export function InventoryToolbar({ section, search = '', onSearch, location = '', onLocation, facilities = [], model = '', onModel, models = [] }: { + section: typeof sections[number]; search?: string; onSearch?: (value: string) => void; + location?: string; onLocation?: (value: string) => void; facilities?: { value: string; label: string }[]; + model?: string; onModel?: (value: string) => void; models?: string[]; +}) { + const hasLocation = ['Device', 'DeviceClaim', 'Rack', 'PowerFeed'].includes(section.kind); + const hasModel = ['Device', 'Cable'].includes(section.kind); + return
        + + {hasLocation && } + {hasModel && } + {(hasLocation || hasModel) && } +
        ; +} diff --git a/ui/provider/src/components/inventory-hardware-fields.test.tsx b/ui/provider/src/components/inventory-hardware-fields.test.tsx index c0acac70..f38a777e 100644 --- a/ui/provider/src/components/inventory-hardware-fields.test.tsx +++ b/ui/provider/src/components/inventory-hardware-fields.test.tsx @@ -1,3 +1,4 @@ +import { findEnabledButton } from '../test/enabled-button'; import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { afterEach, expect, it, vi } from 'vitest'; @@ -16,7 +17,7 @@ function renderForm(kind: 'Device' | 'Cable') { } async function open(kind: 'Device' | 'Cable') { fireEvent.click(screen.getByText(`Manage ${kind.toLowerCase()}s`)); - fireEvent.click(await screen.findByRole('button', { name: `Create ${kind.toLowerCase()}` })); + fireEvent.click(await findEnabledButton({ name: `Create ${kind.toLowerCase()}` })); for (const [label, value] of [['Record name', 'synthetic-new'], ['Display name', 'Synthetic record']]) fireEvent.change(screen.getByLabelText(label), { target: { value } }); } it('registers hardware through the real form without changing claim identity', async () => { @@ -31,8 +32,7 @@ it('registers hardware through the real form without changing claim identity', a expect(model).toHaveAttribute('data-slot', 'input'); expect(model.closest('label')).toHaveAttribute('data-slot', 'label'); expect(model).toBeRequired(); - expect(screen.getByLabelText('Management namespace')).toHaveAttribute('data-slot', 'input'); - expect(screen.getByLabelText('Management namespace')).toBeDisabled(); + expect(screen.queryByLabelText('Management namespace')).not.toBeInTheDocument(); const addComponent = screen.getByRole('button', { name: 'Add component' }); expect(addComponent).toHaveClass(...cn(buttonVariants({ type: 'secondary', theme: 'outline', size: 'small' })).split(' ')); expect(addComponent).toHaveAttribute('type', 'button'); @@ -76,7 +76,7 @@ it('does not present an unreadable installation collection as an empty device pr fireEvent.click(screen.getByText('Manage devices')); await waitFor(() => expect(screen.queryByText('Checking management access…')).not.toBeInTheDocument()); expect(screen.getByText(/Related records are unavailable, not empty/)).toBeInTheDocument(); - expect(screen.queryByRole('button', { name: 'Create device' })).not.toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Create device' })).toBeDisabled(); }); it('keeps readable cable endpoint choices with a partial-access explanation', async () => { vi.stubGlobal('fetch', vi.fn().mockResolvedValue(response({ status: { allowed: true } }))); diff --git a/ui/provider/src/components/inventory-management-lifetime.test.tsx b/ui/provider/src/components/inventory-management-lifetime.test.tsx index 1b0909eb..dcf8c756 100644 --- a/ui/provider/src/components/inventory-management-lifetime.test.tsx +++ b/ui/provider/src/components/inventory-management-lifetime.test.tsx @@ -1,3 +1,4 @@ +import { findEnabledButton } from '../test/enabled-button'; import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { afterEach, expect, it, vi } from 'vitest'; @@ -26,7 +27,7 @@ it.each(['create-pagehide', 'create-unmount', 'edit-pagehide', 'edit-unmount', ' })); const editing = mode.startsWith('edit'); const mounted = render(); - await screen.findByRole('button', { name: editing ? 'Edit display name' : 'Create facility' }); + await findEnabledButton({ name: editing ? 'Edit display name' : 'Create facility' }); fireEvent.click(screen.getByText(editing ? 'Manage this record' : 'Manage facilities')); fireEvent.click(screen.getByRole('button', { name: editing ? 'Edit display name' : 'Create facility' })); if (!editing) fireEvent.change(screen.getByLabelText('Record name'), { target: { value: values.name } }); diff --git a/ui/provider/src/components/inventory-management.test.tsx b/ui/provider/src/components/inventory-management.test.tsx index 3d58043d..3416c018 100644 --- a/ui/provider/src/components/inventory-management.test.tsx +++ b/ui/provider/src/components/inventory-management.test.tsx @@ -16,13 +16,13 @@ describe('management affordances', () => { permission.mockReturnValue({ data: undefined, isFetching: false, error: new ApiError(401, 'private upstream error') } as never); renderManagement(); expect(screen.getByText(/Your session expired/)).toBeInTheDocument(); - expect(screen.queryByRole('button', { name: 'Create facility' })).not.toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Create facility', hidden: true })).toBeDisabled(); expect(screen.queryByText(/private upstream error/)).not.toBeInTheDocument(); }); - it('hides create from viewers, denied users and unresolved reviews', () => { + it('disables create for viewers, denied users and unresolved reviews', () => { permission.mockReturnValue({ data: false, isFetching: false, error: null } as never); renderManagement(); - expect(screen.queryByRole('button', { name: 'Create facility' })).not.toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Create facility', hidden: true })).toBeDisabled(); expect(create).not.toHaveBeenCalled(); }); it('permits an authorized manager to create and confirms only an acknowledged result', async () => { diff --git a/ui/provider/src/components/inventory-management.tsx b/ui/provider/src/components/inventory-management.tsx index 23e680f2..4c2757d5 100644 --- a/ui/provider/src/components/inventory-management.tsx +++ b/ui/provider/src/components/inventory-management.tsx @@ -10,6 +10,7 @@ import { InventoryOperationContext, InventoryOperationGenerationContext, Invento import { InventoryHardwareFields } from './inventory-hardware-fields'; import type { Inventory } from '../inventory'; import { InventoryReadAccessContext, InventoryReferenceReadError, readFailureIssues, redactInventory } from '../lib/inventory-read-access'; +import { INVENTORY_NAMESPACE, inInventoryNamespace } from '../lib/inventory-namespace'; export function InventoryManagement(props: ComponentProps) { return ; @@ -20,12 +21,12 @@ function InventoryManagementForm({ kind, record, facilities: sourceFacilities, c const onReadFailure = useContext(InventoryReadAccessContext); const [readIssues, setReadIssues] = useState({}); const issues = { ...sourceIssues, ...readIssues }; - const facilities = issues.Facility ? [] : sourceFacilities; - const claims = issues.DeviceClaim ? [] : sourceClaims; - const devices = issues.Device ? [] : sourceDevices; - const feeds = issues.PowerFeed ? [] : sourceFeeds; - const racks = issues.Rack ? [] : sourceRacks; - const catalog = issues.Manufacturer || issues.DeviceType ? [] : sourceCatalog; + const facilities = issues.Facility ? [] : sourceFacilities.filter(inInventoryNamespace); + const claims = issues.DeviceClaim ? [] : sourceClaims.filter(inInventoryNamespace); + const devices = issues.Device ? [] : sourceDevices.filter(inInventoryNamespace); + const feeds = issues.PowerFeed ? [] : sourceFeeds.filter(inInventoryNamespace); + const racks = issues.Rack ? [] : sourceRacks.filter(inInventoryNamespace); + const catalog = issues.Manufacturer || issues.DeviceType ? [] : sourceCatalog.filter(inInventoryNamespace); const sessionScope = useContext(InventoryOperationContext); const ready = useContext(InventoryOperationReadyContext); const generation = useContext(InventoryOperationGenerationContext); @@ -44,9 +45,9 @@ function InventoryManagementForm({ kind, record, facilities: sourceFacilities, c }; }, []); const [baseline, setBaseline] = useState(); - const [namespace, setNamespace] = useState(record?.metadata.namespace ?? 'default'); + const namespace = INVENTORY_NAMESPACE; const editable = !record || canEditInventoryLabel(record); - const permission = useInventoryPermission(kind, editable ? namespace : '', record ? 'patch' : 'create', record?.metadata.name); + const permission = useInventoryPermission(kind, editable && !issues[kind] ? namespace : '', record ? 'patch' : 'create', record?.metadata.name); const dependenciesUnavailable = !record && ((kind === 'Device' && !!issues?.DeviceClaim) || (kind === 'Rack' && !!issues?.Facility) || (kind === 'DeviceClaim' && !!issues?.Facility && !!issues?.Rack) || (kind === 'Cable' && !!issues?.Device && !!issues?.PowerFeed)); const visible = permission.data === true && !permission.error && editable && !dependenciesUnavailable && !issues[kind]; const allowed = ready && visible && !permission.isFetching; @@ -108,16 +109,10 @@ function InventoryManagementForm({ kind, record, facilities: sourceFacilities, c } finally { setPending(false); } } const Container = compact ? 'section' : 'details'; - const Access = compact ? 'details' : 'div'; return {!compact && Manage {record ? 'this record' : `${kind === 'Facility' ? 'facilities' : `${kindLabel}s`}`}} -
        - {compact && {record ? 'Editing access' : 'Namespace & access'}} - {!record && } - {dependenciesUnavailable &&

        Related records are unavailable, not empty. Creation needs readable location, installation, or endpoint records. Ask your administrator about viewing access, or try again after a temporary failure.

        } - {!editable ?

        Display-name editing uses a narrower portal writer policy and is unavailable for this record. Device location correction, when separately available, uses ordinary management access and does not perform an ownership handover.

        : permission.error instanceof ApiError && permission.error.status === 401 ?

        Your session expired. Sign in again through the staff portal before continuing. Unsaved input remains here.

        : !visible &&

        Viewing and management access are separate. Ask your administrator about physical-inventory management access. A permission check must succeed before changes are available.

        } -
        - {visible && !open && } + }}> {record ? 'Edit display name' : `Create ${kindLabel}`}
        -

        {message || (!ready || permission.isFetching ? 'Management: verification pending.' : open && blocked ? 'Management: close and reopen this form to continue.' : allowed ? 'Management: access checked.' : 'Management: unavailable.')}

        +

        {message || (!editable ? 'Display-name editing requires a portal-owned record. Other records need ownership review.' : !ready || permission.isFetching ? 'Checking management access…' : dependenciesUnavailable ? 'Related records are unavailable, not empty. Creation requires viewing access to its references.' : permission.error instanceof ApiError && permission.error.status === 401 ? 'Your session expired. Sign in again through the staff portal.' : open && blocked ? 'Close and reopen this form to continue.' : !visible ? 'Viewing and management access are separate. Ask your administrator for physical-inventory management access, or retry after a temporary failure.' : '')}

        {open && permission.data === true && !permission.error && !issues[kind] &&

        {record ? 'Only the display name changes. Identity, placement, geometry, connections, and history remain untouched.' : 'Create a physical record only. This does not verify equipment, reserve space, or provision hardware.'}

        diff --git a/ui/provider/src/components/inventory-navigation-safety.test.tsx b/ui/provider/src/components/inventory-navigation-safety.test.tsx index 9a50a68a..6acfd72f 100644 --- a/ui/provider/src/components/inventory-navigation-safety.test.tsx +++ b/ui/provider/src/components/inventory-navigation-safety.test.tsx @@ -1,3 +1,4 @@ +import { findEnabledButton } from '../test/enabled-button'; import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { createMemoryRouter, Outlet, RouterProvider } from 'react-router'; @@ -37,7 +38,7 @@ it.each([false, true])('same-principal query navigation retains usable managemen })); const router = createMemoryRouter([{ id: 'layouts/milo.layout', path: '/', loader: () => ({ user: { metadata: { uid: 'staff-a' } } }), element: , children: [{ index: true, element: }] }]); render(); - await screen.findByRole('button', { name: editing ? 'Edit display name' : 'Create facility' }); + await findEnabledButton({ name: editing ? 'Edit display name' : 'Create facility' }); await act(async () => { await router.navigate('/?kind=Facility'); }); await open(editing); fireEvent.click(screen.getByRole('button', { name: editing ? 'Save display name' : 'Create facility record' })); @@ -76,7 +77,7 @@ it.each([false, true].flatMap(editing => ['navigation', 'revalidation'].map(tran }); async function open(editing: boolean) { - const opener = await screen.findByRole('button', { name: editing ? 'Edit display name' : 'Create facility' }); + const opener = await findEnabledButton({ name: editing ? 'Edit display name' : 'Create facility' }); fireEvent.click(opener); if (!editing) fireEvent.change(screen.getByLabelText('Record name'), { target: { value: values.name } }); fireEvent.change(screen.getByLabelText('Display name'), { target: { value: 'Independent safe input' } }); diff --git a/ui/provider/src/components/inventory-navigation.tsx b/ui/provider/src/components/inventory-navigation.tsx index a9cca760..ea75b481 100644 --- a/ui/provider/src/components/inventory-navigation.tsx +++ b/ui/provider/src/components/inventory-navigation.tsx @@ -51,11 +51,11 @@ export const sections = [ { kind: 'DeviceType', title: 'Device types', icon: Server, description: 'Reference-only model shapes and component templates, not installed equipment or occupancy.' }, ] as const; -export function InventoryNavigation({ inventory }: { inventory?: Inventory }) { +export function InventoryNavigation(_props: { inventory?: Inventory }) { const [params] = useSearchParams(); - const active = sections.find(item => item.kind === params.get('kind')) ?? sections.find(item => !inventory?.issues?.[item.kind]) ?? sections[0]; + const active = sections.find(item => item.kind === params.get('kind')) ?? sections[0]; return
        +
        + Installation plans at linked facilities + {!mapped ?

        Plans cannot be summarized until linked facilities are readable.

        : inventory.issues?.DeviceClaim ?

        {unavailable('DeviceClaim')}

        : <> +

        {plans.length} {planIncomplete ? 'found · incomplete' : 'recorded'} · execution status is not recorded by the current API.

        + {plans.length ?
          {plans.map(plan =>
        • {link('DeviceClaim', plan)} · Recorded installation plan
        • )}
        :

        No matching installation plans found. Review installation plans and their location references.

        } +

        Legacy claims remain in Claims & registrations. A recorded plan does not establish installation progress.

        + } +
        +
        + Technical details +
        +
        Internal Site code
        {site.spec.code || 'Not recorded'}
        +
        Record name
        {site.metadata.name}
        +
        Resource UID
        {site.metadata.uid || 'Not recorded'}
        +
        Created
        {site.metadata.creationTimestamp || 'Not recorded'}
        +
        +

        Membership grants no placement eligibility, capacity, or operational authority.

        +

        Facility references follow namespace/name. Recreating a name resolves to the replacement; this does not verify physical continuity.

        +
        +

        ; +} From 257f4aed155dd476cacf0a95c3ce680f80c19d9f Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sun, 22 Nov 2026 11:33:30 -0600 Subject: [PATCH 065/518] feat: register inert inventory-backed capacity with admission fencing --- .github/workflows/ci.yml | 1 + build/manager.Dockerfile | 2 + cmd/fleet-registration/main.go | 135 +++++ cmd/fleet-registration/main_test.go | 74 +++ config/README.md | 24 +- config/base/crd/metal.datumapis.com.yaml | 4 +- config/base/registration/deployment.yaml | 86 +++ config/base/registration/kustomization.yaml | 6 + config/base/registration/protection.yaml | 50 ++ config/base/registration/rbac.yaml | 24 + .../registration-admission/kustomization.yaml | 4 + .../registration-admission/webhook.yaml | 34 ++ config/milo-synthetic/kustomization.yaml | 7 + config/milo/kustomization.yaml | 1 + .../management-plane/kustomization.yaml | 1 + .../synthetic-staging/kustomization.yaml | 1 + .../registration-exclusion.yaml | 58 ++ docs/architecture/design.md | 6 + docs/development/README.md | 7 +- .../inventory-capacity-registration.md | 224 ++++++++ internal/api/inventory/v1alpha1/capacity.go | 7 +- internal/api/v1alpha1/crd_validation_test.go | 19 + internal/registration/admission.go | 367 +++++++++++++ internal/registration/admission_test.go | 502 ++++++++++++++++++ internal/registration/envtest_test.go | 258 +++++++++ internal/registration/fence.go | 56 ++ internal/registration/fence_test.go | 58 ++ internal/registration/ledger.go | 94 ++++ internal/registration/runtime.go | 114 ++++ ui/provider/README.md | 18 +- ui/provider/src/components/capacity-table.tsx | 2 +- .../src/components/create-capacity-dialog.tsx | 226 +++----- ui/provider/src/lib/api.ts | 18 - .../src/lib/capacity-registration.test.ts | 63 +++ ui/provider/src/lib/capacity-registration.ts | 61 +++ ui/provider/src/pages/capacity-list.test.tsx | 102 +--- ui/provider/src/pages/capacity-list.tsx | 4 +- .../src/pages/capacity-registration.test.tsx | 58 ++ ui/provider/src/types.ts | 2 + ui/shared/fleet-api.ts | 2 +- 40 files changed, 2506 insertions(+), 274 deletions(-) create mode 100644 cmd/fleet-registration/main.go create mode 100644 cmd/fleet-registration/main_test.go create mode 100644 config/base/registration/deployment.yaml create mode 100644 config/base/registration/kustomization.yaml create mode 100644 config/base/registration/protection.yaml create mode 100644 config/base/registration/rbac.yaml create mode 100644 config/components/registration-admission/kustomization.yaml create mode 100644 config/components/registration-admission/webhook.yaml create mode 100644 config/milo-synthetic/kustomization.yaml create mode 100644 config/overlays/synthetic-staging/registration-exclusion.yaml create mode 100644 docs/development/inventory-capacity-registration.md create mode 100644 internal/registration/admission.go create mode 100644 internal/registration/admission_test.go create mode 100644 internal/registration/envtest_test.go create mode 100644 internal/registration/fence.go create mode 100644 internal/registration/fence_test.go create mode 100644 internal/registration/ledger.go create mode 100644 internal/registration/runtime.go create mode 100644 ui/provider/src/lib/capacity-registration.test.ts create mode 100644 ui/provider/src/lib/capacity-registration.ts create mode 100644 ui/provider/src/pages/capacity-registration.test.tsx diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 27b179fb..d537961b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -24,6 +24,7 @@ jobs: - run: go run ./test/acceptance/milo/cmd validate --root . - run: kustomize build config/base/crd >/dev/null - run: kustomize build config/milo >/dev/null + - run: kustomize build config/milo-synthetic >/dev/null - run: kustomize build config/overlays/management-plane >/dev/null - run: kustomize build config/overlays/synthetic-staging >/dev/null - run: kustomize build config/inventory >/dev/null diff --git a/build/manager.Dockerfile b/build/manager.Dockerfile index 626e0127..4d0d2328 100644 --- a/build/manager.Dockerfile +++ b/build/manager.Dockerfile @@ -6,11 +6,13 @@ RUN go mod download COPY cmd/ ./cmd/ COPY internal/ ./internal/ RUN CGO_ENABLED=0 GOOS=${TARGETOS:-linux} GOARCH=${TARGETARCH} go build -trimpath -ldflags='-s -w' -o /out/fleet-manager ./cmd/fleet-manager \ + && CGO_ENABLED=0 GOOS=${TARGETOS:-linux} GOARCH=${TARGETARCH} go build -trimpath -ldflags='-s -w' -o /out/fleet-registration ./cmd/fleet-registration \ && CGO_ENABLED=0 GOOS=${TARGETOS:-linux} GOARCH=${TARGETARCH} go build -trimpath -ldflags='-s -w' -o /out/fleet-simulator ./cmd/fleet-simulator \ && CGO_ENABLED=0 GOOS=${TARGETOS:-linux} GOARCH=${TARGETARCH} go build -trimpath -ldflags='-s -w' -o /out/fleet-dhcp-sync ./cmd/fleet-dhcp-sync FROM gcr.io/distroless/static-debian12:nonroot@sha256:afa5c872c891853ca7fcf1f12c3edb23f7eeef36189728842dd51042ff57f7ab COPY --from=build /out/fleet-manager /fleet-manager +COPY --from=build /out/fleet-registration /fleet-registration COPY --from=build /out/fleet-simulator /fleet-simulator COPY --from=build /out/fleet-dhcp-sync /fleet-dhcp-sync ENTRYPOINT ["/fleet-manager"] diff --git a/cmd/fleet-registration/main.go b/cmd/fleet-registration/main.go new file mode 100644 index 00000000..3497c443 --- /dev/null +++ b/cmd/fleet-registration/main.go @@ -0,0 +1,135 @@ +package main + +import ( + "context" + "crypto/tls" + "crypto/x509" + "errors" + "flag" + "fmt" + "net/http" + "os" + "sort" + "strings" + "time" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + metal "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/projectdiscovery" + "go.datum.net/fleet/internal/registration" + resourcemanager "go.miloapis.com/milo/pkg/apis/resourcemanager/v1alpha1" + "k8s.io/apimachinery/pkg/runtime" + clientgoscheme "k8s.io/client-go/kubernetes/scheme" + "k8s.io/client-go/rest" + "k8s.io/client-go/tools/clientcmd" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/webhook/admission" +) + +func main() { + var configFile, providers, privateNamespace, cert, key, clientCA string + flag.StringVar(&configFile, "config", "", "Fleet manager discovery configuration") + flag.StringVar(&providers, "provider-projects", "", "complete comma-separated provider identity scope, fixed in the private ledger") + flag.StringVar(&privateNamespace, "private-namespace", "fleet-system-private", "private registration ledger namespace") + flag.StringVar(&cert, "tls-cert", "/etc/fleet/registration/tls.crt", "serving certificate") + flag.StringVar(&key, "tls-key", "/etc/fleet/registration/tls.key", "serving key") + flag.StringVar(&clientCA, "client-ca", "/etc/fleet/registration/client-ca.crt", "CA dedicated to trusted API-server webhook clients") + flag.Parse() + if err := run(ctrl.SetupSignalHandler(), configFile, providers, privateNamespace, cert, key, clientCA); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } +} + +func run(ctx context.Context, configFile, providers, namespace, cert, key, clientCA string) error { + config, err := projectdiscovery.LoadConfig(configFile) + if err != nil { + return err + } + projects := strings.Split(providers, ",") + sort.Strings(projects) + for index, name := range projects { + if name == "" || strings.TrimSpace(name) != name || (index > 0 && projects[index-1] == name) { + return errors.New("a nonempty, unique provider scope is required") + } + } + scheme := runtime.NewScheme() + for _, add := range []func(*runtime.Scheme) error{clientgoscheme.AddToScheme, inventory.AddToScheme, metal.AddToScheme, resourcemanager.AddToScheme} { + if err := add(scheme); err != nil { + return err + } + } + host, err := rest.InClusterConfig() + if err != nil { + return err + } + private, err := client.New(host, client.Options{Scheme: scheme}) + if err != nil { + return err + } + rootConfig, err := clientcmd.BuildConfigFromFlags("", config.Discovery.DiscoveryKubeconfigPath) + if err != nil { + return err + } + root, err := client.New(rootConfig, client.Options{Scheme: scheme}) + if err != nil { + return err + } + template := rootConfig + if config.Discovery.ProjectKubeconfigPath != "" { + template, err = clientcmd.BuildConfigFromFlags("", config.Discovery.ProjectKubeconfigPath) + if err != nil { + return err + } + } + handler := registration.NewHandler(registration.Store{Client: private, Namespace: namespace, Authority: config.AuthorityID, Projects: projects}, root, template, scheme) + if err := handler.VerifyFence(ctx); err != nil { + return err + } + if _, _, err := handler.Store.Read(ctx); err != nil { + return err + } + tlsConfig, err := webhookTLS(clientCA) + if err != nil { + return err + } + webhook := &admission.Webhook{Handler: handler} + mux := http.NewServeMux() + mux.Handle("/validate-registration", webhook) + server := &http.Server{Addr: ":9443", Handler: http.MaxBytesHandler(mux, 2<<20), ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 15 * time.Second, WriteTimeout: 20 * time.Second, TLSConfig: tlsConfig} + go func() { + ticker := time.NewTicker(30 * time.Second) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + shutdown, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + _ = server.Shutdown(shutdown) + return + case <-ticker.C: + if err := handler.Recover(ctx); err != nil { + fmt.Fprintln(os.Stderr, "registration recovery remains unknown:", err) + } + } + } + }() + err = server.ListenAndServeTLS(cert, key) + if errors.Is(err, http.ErrServerClosed) { + return nil + } + return err +} + +func webhookTLS(clientCA string) (*tls.Config, error) { + caBytes, err := os.ReadFile(clientCA) + if err != nil { + return nil, err + } + pool := x509.NewCertPool() + if !pool.AppendCertsFromPEM(caBytes) { + return nil, errors.New("API-server client CA is invalid") + } + return &tls.Config{MinVersion: tls.VersionTLS13, ClientAuth: tls.RequireAndVerifyClientCert, ClientCAs: pool}, nil +} diff --git a/cmd/fleet-registration/main_test.go b/cmd/fleet-registration/main_test.go new file mode 100644 index 00000000..c93dbcf3 --- /dev/null +++ b/cmd/fleet-registration/main_test.go @@ -0,0 +1,74 @@ +package main + +import ( + "crypto/ed25519" + "crypto/rand" + "crypto/tls" + "crypto/x509" + "crypto/x509/pkix" + "encoding/pem" + "io" + "log" + "math/big" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "testing" + "time" +) + +func TestWebhookRequiresTrustedAPIServerClient(t *testing.T) { + publicKey, privateKey, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + t.Fatal(err) + } + issuer := &x509.Certificate{SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "synthetic-api-server-ca"}, NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), IsCA: true, BasicConstraintsValid: true, KeyUsage: x509.KeyUsageCertSign} + ca, err := x509.CreateCertificate(rand.Reader, issuer, issuer, publicKey, privateKey) + if err != nil { + t.Fatal(err) + } + leaf := &x509.Certificate{SerialNumber: big.NewInt(2), Subject: pkix.Name{CommonName: "synthetic-api-server"}, NotBefore: issuer.NotBefore, NotAfter: issuer.NotAfter, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}, KeyUsage: x509.KeyUsageDigitalSignature} + certificate, err := x509.CreateCertificate(rand.Reader, leaf, issuer, publicKey, privateKey) + if err != nil { + t.Fatal(err) + } + path := filepath.Join(t.TempDir(), "client-ca.crt") + if err := os.WriteFile(path, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: ca}), 0600); err != nil { + t.Fatal(err) + } + config, err := webhookTLS(path) + if err != nil { + t.Fatal(err) + } + server := httptest.NewUnstartedServer(http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) { writer.WriteHeader(http.StatusNoContent) })) + server.TLS = config + server.Config.ErrorLog = log.New(io.Discard, "", 0) + server.StartTLS() + defer server.Close() + if response, err := server.Client().Get(server.URL); err == nil { + response.Body.Close() + t.Fatal("unauthenticated AdmissionReview transport was accepted") + } + transport := server.Client().Transport.(*http.Transport).Clone() + transport.TLSClientConfig.Certificates = []tls.Certificate{{Certificate: [][]byte{certificate}, PrivateKey: privateKey}} + trusted := &http.Client{Transport: transport} + response, err := trusted.Get(server.URL) + if err != nil { + t.Fatal(err) + } + response.Body.Close() + if response.StatusCode != http.StatusNoContent { + t.Fatal("trusted API-server client failed") + } + untrustedTransport := server.Client().Transport.(*http.Transport).Clone() + untrustedTransport.TLSClientConfig.Certificates = server.TLS.Certificates + untrusted := &http.Client{Transport: untrustedTransport} + if response, err := untrusted.Get(server.URL); err == nil { + response.Body.Close() + t.Fatal("untrusted client certificate was accepted") + } + if _, err := webhookTLS(filepath.Join(t.TempDir(), "absent")); err == nil { + t.Fatal("missing CA accepted") + } +} diff --git a/config/README.md b/config/README.md index efd3cef5..7e01a159 100644 --- a/config/README.md +++ b/config/README.md @@ -14,13 +14,29 @@ API servers and must be reconciled independently. | Root | Destination | Contents | | --- | --- | --- | -| `config/milo` | Milo root control plane | Fleet CRDs (including the `fleet.datumapis.com` inventory kinds), IAM protected resources and roles, service registration, and machine quota registration | -| `config/overlays/management-plane` | Fleet management cluster | Fleet CRDs, the manager workload and RBAC, private-record namespaces, and admission fences | +| `config/milo` | Milo root control plane | Fleet CRDs (including the `fleet.datumapis.com` inventory kinds), IAM protected resources and roles, service/quota registration, and the mandatory capacity-registration webhook | +| `config/overlays/management-plane` | Fleet management cluster | Fleet CRDs, manager and inert-registration workloads and RBAC, private-record namespaces, and admission fences | | `config/overlays/synthetic-staging` | Fleet management cluster (non-production only) | Management-plane resources plus an explicit synthetic allocator/provider integration | +The synthetic staging overlay explicitly excludes the inert-registration +service and its retention policies. Pair it with `config/milo-synthetic` in a +**separate non-production Milo control plane**, not production `config/milo`. +That root preserves the pre-registration synthetic API contract. There is no +request field, actor exemption, or runtime switch that bypasses production +registration admission. Never point synthetic lifecycle handlers at the +production registration authority or its private ledger. + The one `fleet-manager` Deployment serves every Milo project that consumes the `metal` service; see [project discovery](#project-discovery). +The separate `fleet-registration` Deployment serves inert inventory-backed +capacity admission only. Its TLS trust, read/SAR credentials, webhook serving CA +and one-time private ledger bootstrap are environment-owned. Read the +[registration rollout contract](../docs/development/inventory-capacity-registration.md#production-packaging-and-rollout) +before applying either root: an unavailable or incompletely configured authority +blocks writes, and the ledger must never be reset by GitOps. This does not enable +production allocation or provisioning. + `config/components/service-catalog-staging` is a Kustomize component with staging's Bare Metal prices: committed servers and server setup, which contracts charge, as billing ServicePricings for `metal.datumapis.com`. Staging's infra enables it @@ -29,7 +45,8 @@ A price change is a new `-v2` pricing, since a ServicePricing can't be changed. `config/components/inventory` registers the operator-written `DeviceClaim` and `Device` kinds of `fleet.datumapis.com` in Milo: their CRDs, ProtectedResources, -and inventory viewer and editor roles. Only `config/milo` includes it; records +and inventory viewer and editor roles. The production `config/milo` and isolated +non-production `config/milo-synthetic` roots include it; records live in the provider project. `config/inventory` renders the CRDs alone for a legacy management-cluster install and will be removed. See [Planning and registering physical devices](../docs/operations/physical-inventory.md). @@ -96,6 +113,7 @@ Render both production roots before publishing the Kustomize bundle: ```sh kustomize build config/milo >/dev/null +kustomize build config/milo-synthetic >/dev/null kustomize build config/overlays/management-plane >/dev/null kustomize build config/overlays/synthetic-staging >/dev/null ``` diff --git a/config/base/crd/metal.datumapis.com.yaml b/config/base/crd/metal.datumapis.com.yaml index 1e48fc93..16a1fde1 100644 --- a/config/base/crd/metal.datumapis.com.yaml +++ b/config/base/crd/metal.datumapis.com.yaml @@ -146,6 +146,8 @@ spec: - rule: >- self.deviceRef == oldSelf.deviceRef message: physical-device identity is immutable + - rule: self.cleaningPolicyRef.name != '' || self.allocationPolicy == 'Disabled' + message: unconfigured cleaning policy is permitted only for Disabled records properties: deviceRef: type: object @@ -155,7 +157,7 @@ spec: cleaningPolicyRef: type: object required: [name] - properties: {name: {type: string, minLength: 1}} + properties: {name: {type: string}} reclaimPolicy: {type: string, enum: [Retain]} status: type: object diff --git a/config/base/registration/deployment.yaml b/config/base/registration/deployment.yaml new file mode 100644 index 00000000..135c91a2 --- /dev/null +++ b/config/base/registration/deployment.yaml @@ -0,0 +1,86 @@ +apiVersion: v1 +kind: ServiceAccount +metadata: + name: fleet-registration + namespace: fleet-system +--- +apiVersion: v1 +kind: Service +metadata: + name: fleet-registration + namespace: fleet-system +spec: + selector: + app.kubernetes.io/name: fleet-registration + ports: + - name: https + port: 9443 + targetPort: https +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: fleet-registration + namespace: fleet-system +spec: + replicas: 2 + selector: + matchLabels: + app.kubernetes.io/name: fleet-registration + template: + metadata: + labels: + app.kubernetes.io/name: fleet-registration + spec: + serviceAccountName: fleet-registration + securityContext: + runAsNonRoot: true + runAsUser: 65532 + runAsGroup: 65532 + fsGroup: 65532 + seccompProfile: + type: RuntimeDefault + containers: + - name: registration + image: ghcr.io/datum-cloud/fleet:latest + command: [/fleet-registration] + args: + - --config=/etc/fleet/manager/config.yaml + - --provider-projects=datum-cloud + ports: + - name: https + containerPort: 9443 + readinessProbe: + tcpSocket: + port: https + resources: + requests: {cpu: 50m, memory: 64Mi} + limits: {memory: 256Mi} + securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: [ALL] + volumeMounts: + - {name: config, mountPath: /etc/fleet/manager, readOnly: true} + - {name: root, mountPath: /var/run/fleet/milo, readOnly: true} + - {name: projects, mountPath: /var/run/fleet/projects, readOnly: true} + - {name: tls, mountPath: /etc/fleet/registration, readOnly: true} + volumes: + - name: config + configMap: + name: fleet-manager-config + - name: root + secret: + secretName: fleet-registration-milo-kubeconfig + defaultMode: 0440 + items: [{key: value, path: kubeconfig}] + - name: projects + secret: + secretName: fleet-registration-project-kubeconfig + defaultMode: 0440 + items: [{key: value, path: kubeconfig}] + - name: tls + secret: + secretName: fleet-registration-tls + defaultMode: 0440 diff --git a/config/base/registration/kustomization.yaml b/config/base/registration/kustomization.yaml new file mode 100644 index 00000000..ab998324 --- /dev/null +++ b/config/base/registration/kustomization.yaml @@ -0,0 +1,6 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - deployment.yaml + - rbac.yaml + - protection.yaml diff --git a/config/base/registration/protection.yaml b/config/base/registration/protection.yaml new file mode 100644 index 00000000..d1e54d70 --- /dev/null +++ b/config/base/registration/protection.yaml @@ -0,0 +1,50 @@ +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicy +metadata: + name: fleet-registration-ledger-protection +spec: + failurePolicy: Fail + matchConstraints: + resourceRules: + - apiGroups: [''] + apiVersions: [v1] + operations: [UPDATE, DELETE] + resources: [secrets] + matchConditions: + - name: registration-ledger + expression: request.namespace == 'fleet-system-private' && request.name == 'fleet-capacity-registration-v1' + validations: + - expression: request.operation == 'UPDATE' && request.userInfo.username == 'system:serviceaccount:fleet-system:fleet-registration' + message: Registration reservations are retained; only the registration service may update this ledger. +--- +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicyBinding +metadata: + name: fleet-registration-ledger-protection +spec: + policyName: fleet-registration-ledger-protection + validationActions: [Deny] +--- +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicy +metadata: + name: fleet-registration-namespace-protection +spec: + failurePolicy: Fail + matchConstraints: + resourceRules: + - apiGroups: [''] + apiVersions: [v1] + operations: [DELETE] + resources: [namespaces] + validations: + - expression: request.name != 'fleet-system-private' + message: The private registration namespace contains permanent reservations and cannot be deleted. +--- +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicyBinding +metadata: + name: fleet-registration-namespace-protection +spec: + policyName: fleet-registration-namespace-protection + validationActions: [Deny] diff --git a/config/base/registration/rbac.yaml b/config/base/registration/rbac.yaml new file mode 100644 index 00000000..79a5cb2a --- /dev/null +++ b/config/base/registration/rbac.yaml @@ -0,0 +1,24 @@ +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: fleet-registration-ledger + namespace: fleet-system-private +rules: + - apiGroups: [''] + resources: [secrets] + resourceNames: [fleet-capacity-registration-v1] + verbs: [get, update] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: fleet-registration-ledger + namespace: fleet-system-private +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: fleet-registration-ledger +subjects: + - kind: ServiceAccount + name: fleet-registration + namespace: fleet-system diff --git a/config/components/registration-admission/kustomization.yaml b/config/components/registration-admission/kustomization.yaml new file mode 100644 index 00000000..4fd00748 --- /dev/null +++ b/config/components/registration-admission/kustomization.yaml @@ -0,0 +1,4 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - webhook.yaml diff --git a/config/components/registration-admission/webhook.yaml b/config/components/registration-admission/webhook.yaml new file mode 100644 index 00000000..840037b8 --- /dev/null +++ b/config/components/registration-admission/webhook.yaml @@ -0,0 +1,34 @@ +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingWebhookConfiguration +metadata: + name: fleet-capacity-registration +webhooks: + - name: registration.fleet.datumapis.com + admissionReviewVersions: [v1] + failurePolicy: Fail + matchPolicy: Equivalent + sideEffects: NoneOnDryRun + timeoutSeconds: 20 + clientConfig: + url: https://fleet-registration.fleet-system.svc:9443/validate-registration + rules: + - apiGroups: [metal.datumapis.com] + apiVersions: [v1alpha1] + operations: [CREATE, UPDATE, DELETE] + resources: [machinecapacities, machinecapacities/status] + scope: Namespaced + - apiGroups: [fleet.datumapis.com] + apiVersions: [v1alpha1] + operations: [CREATE, UPDATE, DELETE] + resources: [devices, devices/status] + scope: Namespaced + - apiGroups: [''] + apiVersions: [v1] + operations: [DELETE] + resources: [namespaces] + scope: Cluster + - apiGroups: [resourcemanager.miloapis.com] + apiVersions: [v1alpha1] + operations: [DELETE] + resources: [projects] + scope: Cluster diff --git a/config/milo-synthetic/kustomization.yaml b/config/milo-synthetic/kustomization.yaml new file mode 100644 index 00000000..0f5a7f84 --- /dev/null +++ b/config/milo-synthetic/kustomization.yaml @@ -0,0 +1,7 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - ../base/crd + - ../components/iam + - ../components/service-catalog + - ../components/inventory diff --git a/config/milo/kustomization.yaml b/config/milo/kustomization.yaml index 0f5a7f84..c6a9b5d5 100644 --- a/config/milo/kustomization.yaml +++ b/config/milo/kustomization.yaml @@ -5,3 +5,4 @@ resources: - ../components/iam - ../components/service-catalog - ../components/inventory + - ../components/registration-admission diff --git a/config/overlays/management-plane/kustomization.yaml b/config/overlays/management-plane/kustomization.yaml index 38194887..dbeae129 100644 --- a/config/overlays/management-plane/kustomization.yaml +++ b/config/overlays/management-plane/kustomization.yaml @@ -3,6 +3,7 @@ kind: Kustomization resources: - ../../base/crd - ../../base/manager + - ../../base/registration - ../../components/admission components: - ../../components/consumer-ui-plugin diff --git a/config/overlays/synthetic-staging/kustomization.yaml b/config/overlays/synthetic-staging/kustomization.yaml index 62241eef..f8b3b726 100644 --- a/config/overlays/synthetic-staging/kustomization.yaml +++ b/config/overlays/synthetic-staging/kustomization.yaml @@ -4,6 +4,7 @@ resources: - ../management-plane - provider.yaml patches: + - path: registration-exclusion.yaml - target: group: apps version: v1 diff --git a/config/overlays/synthetic-staging/registration-exclusion.yaml b/config/overlays/synthetic-staging/registration-exclusion.yaml new file mode 100644 index 00000000..3b18c0a9 --- /dev/null +++ b/config/overlays/synthetic-staging/registration-exclusion.yaml @@ -0,0 +1,58 @@ +$patch: delete +apiVersion: apps/v1 +kind: Deployment +metadata: + name: fleet-registration + namespace: fleet-system +--- +$patch: delete +apiVersion: v1 +kind: Service +metadata: + name: fleet-registration + namespace: fleet-system +--- +$patch: delete +apiVersion: v1 +kind: ServiceAccount +metadata: + name: fleet-registration + namespace: fleet-system +--- +$patch: delete +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: fleet-registration-ledger + namespace: fleet-system-private +--- +$patch: delete +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: fleet-registration-ledger + namespace: fleet-system-private +--- +$patch: delete +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicy +metadata: + name: fleet-registration-ledger-protection +--- +$patch: delete +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicyBinding +metadata: + name: fleet-registration-ledger-protection +--- +$patch: delete +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicy +metadata: + name: fleet-registration-namespace-protection +--- +$patch: delete +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicyBinding +metadata: + name: fleet-registration-namespace-protection diff --git a/docs/architecture/design.md b/docs/architecture/design.md index 48d76da7..f44765d7 100644 --- a/docs/architecture/design.md +++ b/docs/architecture/design.md @@ -18,6 +18,12 @@ proposal plus the extension. The [combined proposal](../proposals/fleet-manageme examples, and diagrams now live in this repository. The [migration record](../proposals/fleet-management/MIGRATION.md) preserves provenance and outstanding review points; the original discussions remain in `infra`. +The implemented [stage-1 registration decision](../development/inventory-capacity-registration.md) +allows explicitly unconfigured cleaning only for inert Disabled/Retain records. +It uses a separate private CAS ledger and project-plane admission, not allocation +custody or provider enrollment. Enabling and preparation remain forbidden until +their policy resolution and authorization contracts are implemented. + ## Problem and intended outcome Operators currently repeat infrastructure facts across inventory, provisioning, diff --git a/docs/development/README.md b/docs/development/README.md index 7442b405..e486d2bb 100644 --- a/docs/development/README.md +++ b/docs/development/README.md @@ -17,8 +17,13 @@ incarnation evidence remains private. A packaged standalone synthetic smoke scenario exercises local-scope contention, install recovery, cleanup, and capacity reuse. An explicit Milo-routed synthetic staging overlay exercises event-driven Machine allocation, contention, cleanup, and reuse through the -public project API. Production caller-preserving +public project API. Production caller-preserving allocation admission, replayable Milo event adapters, and production provider integration are not implemented. +Inert [inventory-backed capacity registration](inventory-capacity-registration.md) +now has a caller-preserving admission service, a separate CAS registration +ledger, exact-incarnation recovery, and a session-fenced default-namespace Device +picker. It admits only Disabled/Retain records with cleaning explicitly +unconfigured; deployment trust inputs and live Milo acceptance remain required. An opt-in [local KVM installation harness](../operations/local-vm.md) implements a bounded libvirt executor and guest installer using the same lifecycle library. It uses a disposable Kubernetes API and explicit local authority fixtures; it is diff --git a/docs/development/inventory-capacity-registration.md b/docs/development/inventory-capacity-registration.md new file mode 100644 index 00000000..5dc5d222 --- /dev/null +++ b/docs/development/inventory-capacity-registration.md @@ -0,0 +1,224 @@ +# Inventory-backed capacity registration, stage 1 + +[Implementation status](README.md) · [Inventory proposal](../proposals/fleet-management/inventory.md) · [Enrollment contract](../proposals/fleet-management/bare-metal-provisioning.md#enrollment-and-explicit-preparation) + +This implements an inert registration boundary, not hardware enrollment, +preparation, allocation, or verification. It supersedes the blocker-only UI +guardrail in PR140 (`12439e1fdf0d229352b4e32c27d9985993ca117d`). The synthetic +name-derived Device reference, invented cleaning default, allocation checkbox, +and unrestricted frontend create helper remain removed. Existing capacity +listing and legacy values remain visible; no existing object is migrated. + +## Public contract and authority + +The staff form selects an existing `Device` in `default`, retains its UID and +resourceVersion as an immutable selection baseline, and authors an independent +capacity name. It POSTs to the existing provider project's `MachineCapacity` +API using the staff portal's caller-preserving proxy. `spec.deviceRef` remains +a name-only reference. It must not be a generated capacity name masquerading as +a Device name. + +The only admitted new capacity contract is: + +```yaml +spec: + deviceRef: {name: selected-device} + allocationPolicy: Disabled + reclaimPolicy: Retain + cleaningPolicyRef: {name: ""} +``` + +An empty cleaning-policy name explicitly means **unconfigured**, not a policy +named `default`, synthetic cleaning, or authorization to prepare. The CRD permits +it only while Disabled. The production admission handler rejects *all* capacity +updates, status updates and deletes, including setting a nonempty policy and +enabling in the same request. Real policy resolution and policy-use authorization +are future prerequisites for a separately designed transition; there is no +stage-1 preparation endpoint. Legacy nonempty cleaning references remain valid +in the schema and synthetic lifecycle environments remain separate. + +Three protected request-precondition annotations carry the selected UID, +selected resourceVersion and stable client operation ID: +`fleet.datumapis.com/registration-device-uid`, +`fleet.datumapis.com/registration-device-version`, and +`fleet.datumapis.com/registration-operation`. They are not authentication or +ownership proofs. A create with copied annotations still goes through the full +admission protocol; updates and deletion cannot remove or replace them. The +private ledger, not these public annotations, binds the exact capacity UID. + +`cmd/fleet-registration` serves a validating admission webhook. Its production +implementation uses Milo's authenticated `iam.miloapis.com/parent-*` extras, +requires a single Project context and an actor UID, and resolves the current +Project UID through the root Milo client. It does not use a project, actor or +permission bypass from request annotations. Separate SubjectAccessReviews pass +through the caller's username, UID, groups and extras for current +`machinecapacities.create` and named `devices.get` in `default`. Permission errors, +denials, missing identity and incomplete evaluations fail closed. Both checks +are repeated before reservation, alongside uncached Device and namespace +lifetime/version reads. Controller credentials supply reads and SAR evaluation, +not the caller's registration authority. + +The webhook accepts only mutually authenticated TLS from a dedicated API-server +client CA. Do not use a broad tenant/client CA: an AdmissionReview received from +an untrusted client is not evidence of an authenticated actor. The server also +checks the installed root webhook configuration at startup and before admission: +required write rules, explicit serving CA, Fail policy and no selectors or match +conditions that allow a caller to skip the fence. + +## Physical identity and bounded deduplication + +The complete operator-configured provider-project list and Milo authority are +fixed in one private ledger. All replicas, names and projects in that scope use +the same resourceVersion CAS. Configuration must match the retained scope +exactly; changing the list requires an explicit ledger migration, not a restart +with a smaller list. The packaged UI and deployment use `datum-cloud`. + +Eligible Devices must have **both** a recorded non-placeholder serial and a +canonical non-placeholder system UUID. The canonical asset key is the digest of +`uuid:` plus that UUID. Known reservation aliases include the digests of the +normalized serial, UUID, and, when present, provider host system/type/ID tuple. +Normalization trims and lowercases values; conservative false-positive +collisions require operator investigation rather than choosing a winner. +MAC addresses, BMC endpoints, installation claims, rack placement and asset tags +are not canonical chassis identifiers in this stage. + +Every known alias is claimed in the same CAS transaction. A second Device with +any shared alias, including inconsistent serial/UUID pairs or a shared provider +host reference, is ambiguous and is rejected rather than merged or adopted. +Before reservation the handler reads Devices and capacities in **all namespaces +of every configured provider project**. Existing unresolved legacy capacity +blocks new registration because non-conflict cannot be established. Existing +capacity bound to a conflicting asset blocks it regardless of allocation +policy or reported readiness. None of these records or allocations is changed. + +This is **not universal physical deduplication** or proof of real hardware +identity. Serial-only and UUID-only records cannot prove the same hardware in +the absence of shared evidence; neither can be selected for registration. +Different fabricated or incomplete identifiers, assets outside the configured +provider scope, and physical equipment absent from inventory cannot be compared +reliably. Recording identity does not establish physical verification or +ownership. Production allocation remains disabled independently. + +## Serialization and recovery + +`fleet-capacity-registration-v1` is a separate host-cluster Secret in +`fleet-system-private`; it is **not** allocation custody. The service has only +get/update permission on that single Secret. Its JSON retains the actor, exact +API-normalized create object, admission request UID, client operation ID, +Project/namespace lifetimes, Device UID/resourceVersion, aliases, canonical key, +and API-assigned capacity UID **before allowing the public create**. Kubernetes +assigns that UID before validating admission; envtest verifies a caller-supplied +UID is replaced and the retained UID matches the actual result. + +CAS conflicts repeat authorization and observation before another reservation +attempt. No public object, allocation, status, provider, networking, or cleaning +write is performed by the registration service. Capacity persistence is the +original caller's API-server operation. All new entries start `Unknown` because +another admission plugin, API storage failure, timeout or crash can still prevent +the create. A failed CAS response may itself have committed: it is not released. + +Device creation also reserves its known aliases before admission completes. +Device deletion retains a permanent UID tombstone before admission completes. +Both use the same ledger CAS, closing the registration-versus-pending-create or +delete race. Device updates retain their old resourceVersion before admission +completes. Registration rejects a selected version with such an update fence; +only an explicitly selected newer persisted version can pass it. This serializes +pending metadata/spec updates with registration without silently refreshing the +selection. An update whose completion is unknown can leave its old version +ineligible even if storage made no change. Failed Device creates can likewise retain an alias reservation. +The selected Device's own successful creation reservation is not a conflict. +Identity/provider-alias changes are forbidden; registered Device specs are +frozen, and its deletion and same-name replacement are forbidden. The default +provider namespace and configured provider Project deletions are denied. + +Recovery observes the exact retained capacity UID, namespace and Project +lifetimes, Device incarnation, aliases and authored input. An exact observed +object becomes `Recorded`, which means only that the inert record exists. +Absence remains `Unknown`; replacement or lifetime loss is a conflict/tombstone, +never adoption. Recovery never creates, deletes, retries under a different name, +or publishes positive readiness. It runs every 30 seconds and after restart; +CAS conflicts leave evidence retained for a later observation. Repeating POST +is not the recovery mechanism: inspect the original name and retained operation. + +Reservations and tombstones have no automatic expiry or release path in stage 1. +The bounded ledger refuses growth past 750,000 encoded bytes. Lost or corrupt +ledger state, scope changes, uncertain operations and full ledgers require +operator-led reconciliation/migration; deleting or recreating the ledger is not +a repair. Ledger update protection and private-namespace deletion protection +are installed in the host cluster. Cluster administrators who can remove those +fences or restore arbitrary storage remain outside the guarantee. + +## Production packaging and rollout + +- `config/milo` includes the mandatory Fail-closed registration webhook on the + **actual project resource path**, not just a manager-side helper. It matches + capacity create/update/delete/status, Device create/update/delete/status, + namespace deletion, and root Project deletion. No object-label opt-in exists. +- `config/overlays/management-plane` includes a separate two-replica registration + Deployment, TLS Service, narrowly scoped host RBAC, and private retention + policies. It does not enable production lifecycle handlers. +- The webhook consumes parent context from Milo's standard admission extras. + The repository-pinned Milo module enables validating admission by default and + documents these extras in its cluster-aware webhook implementation. +- Legacy capacity writes in configured production scope fail closed; legacy + records remain readable and unchanged. Outside configured provider scope, + ordinary inventory writes are unaffected, but new capacity writes are denied. + The synthetic/standalone test APIs do not install this production webhook. + Pair the synthetic staging overlay with `config/milo-synthetic` on a separate + non-production API server; that overlay excludes registration workloads and + retention policies. Never use these synthetic roots in production or share + the registration authority's ledger. This is deployment isolation, not a + caller-selected bypass. + +Environment-owned inputs are required, just as for the existing manager. No +real credentials or certificates are supplied by this repository: + +1. Preserve the existing `fleet-manager-config` authority and discovery paths. + Supply separate `fleet-registration-milo-kubeconfig` and + `fleet-registration-project-kubeconfig` Secrets at the mounted paths. The root + credential needs Project reads and registration webhook-configuration reads; + the project credential needs Device and capacity get/list across the complete + scope, namespace get, and SubjectAccessReview create. It needs **no public + capacity or Device writes**, allocation permissions or provider credentials. +2. Supply `fleet-registration-tls` with `tls.crt`, `tls.key`, and a dedicated + `client-ca.crt`. Configure Milo's admission webhook client kubeconfig with an + API-server client certificate signed by that CA. Patch the webhook URL for + actual cross-cluster reachability and set `clientConfig.caBundle` to the + serving CA. No empty or guessed trust defaults are accepted. +3. Install the host retention policies. Bootstrap the ledger **once**, using + create, never apply/upsert, with environment-matching authority and sorted + projects. Its initial JSON has `authority`, `projects`, `entries: []` and + `deviceFences: []`. It is intentionally absent from GitOps resources so a + later reconcile cannot overwrite accumulated reservations. Do not label it + as legacy allocation custody (`fleet.datumapis.com/private-record`). +4. Quiesce provider inventory/capacity writes while installing the root webhook + and service. Validate the complete provider scope and legacy inventory before + reopening writes. Unavailable TLS, credentials, ledger or service leave + creates blocked. Readiness is process reachability, not asset eligibility. +5. Before rolling out the UI, verify caller-preserving project routing, named + Device read denial, registration denial, direct write/status/delete fences, + TLS rejection, and duplicate concurrency in the target environment. This + change performs **no live writes or deployment**, so it does not claim those + environment-specific checks have been performed. + +## UI and verification + +The Datum dialog uses the existing real host-session boundary and isolated read +cache. Missing host authority, denied registration, unavailable Devices and +partial identity have explicit explanations. Selecting a Device snapshots its +baseline; neither refetch nor visible browser-chrome blur/focus changes it. A +named current read immediately precedes dispatch. Session changes fence pending +work. After dispatch, uncertain results retain the authored name and disable +retry; the existing unfenced legacy deletion helper is never used for rollback. + +Tests cover concurrent CAS, serial/UUID/provider aliases and provider projects, +stale UID/RV, Device deletion fences, namespace/Project recreation, permission +revocation, unknown commit and restart, copied-annotation incarnation conflicts, +real API-assigned UID binding, direct mutation fences and no public effects. +Envtest exercises the production authorization function against real SARs, +the packaged validating webhook, and the host retention policies against a +disposable API server. TLS tests reject unauthenticated webhook transport. It is not a live Milo +deployment or independent security review. Frontend tests use real session +components and mocked transport. Run the existing Go/envtest, race, vet, +provider/consumer test/typecheck/build, manifest-isolation and documentation +checks described in the [development guide](README.md#build-test-and-run). diff --git a/internal/api/inventory/v1alpha1/capacity.go b/internal/api/inventory/v1alpha1/capacity.go index 664fcc61..866e7e15 100644 --- a/internal/api/inventory/v1alpha1/capacity.go +++ b/internal/api/inventory/v1alpha1/capacity.go @@ -12,10 +12,9 @@ var ( ) // CapacityBackingError reports why a Device cannot back a MachineCapacity, or -// nil when it may. Nothing resolves MachineCapacity.spec.deviceRef yet; any -// resolver that does must call this and treat a non-nil result as ineligible. -// It checks only recorded identity, which is matching evidence: a nil result -// is not verification or allocator eligibility. +// nil when this basic identity check passes. Registration applies additional +// paired-identity, alias, incarnation and authorization checks. Recorded identity +// is matching evidence: a nil result is not verification or allocator eligibility. func CapacityBackingError(device *Device) error { if device == nil { return ErrDeviceIdentityMissing diff --git a/internal/api/v1alpha1/crd_validation_test.go b/internal/api/v1alpha1/crd_validation_test.go index e3014369..3f2cabde 100644 --- a/internal/api/v1alpha1/crd_validation_test.go +++ b/internal/api/v1alpha1/crd_validation_test.go @@ -41,6 +41,25 @@ func TestCRDsPassAPIServerDefinitionValidation(t *testing.T) { } } +func TestCapacityUnconfiguredCleaningIsDisabledOnly(t *testing.T) { + crd := loadCRDs(t)["machinecapacities.metal.datumapis.com"] + for _, test := range []struct { + name, policy, cleaning string + allowed bool + }{ + {"inert registration", "Disabled", "", true}, + {"legacy synthetic", "Enabled", "synthetic-tenant-reuse-v1", true}, + {"unconfigured enabled", "Enabled", "", false}, + } { + t.Run(test.name, func(t *testing.T) { + object := map[string]any{"apiVersion": "metal.datumapis.com/v1alpha1", "kind": "MachineCapacity", "metadata": map[string]any{"name": "record", "namespace": "default"}, "spec": map[string]any{"deviceRef": map[string]any{"name": "device"}, "allocationPolicy": test.policy, "cleaningPolicyRef": map[string]any{"name": test.cleaning}, "reclaimPolicy": "Retain"}} + if errs := validateObject(t, crd, object, nil); (len(errs) == 0) != test.allowed { + t.Fatalf("unexpected cleaning contract result: %v", errs) + } + }) + } +} + func validateObject(t *testing.T, crd *extensionsv1.CustomResourceDefinition, object, old map[string]any) field.ErrorList { t.Helper() schema := internalSchema(t, crd) diff --git a/internal/registration/admission.go b/internal/registration/admission.go new file mode 100644 index 00000000..f7b97941 --- /dev/null +++ b/internal/registration/admission.go @@ -0,0 +1,367 @@ +package registration + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "reflect" + "regexp" + "slices" + "strings" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + metal "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/controller" + iam "go.miloapis.com/milo/pkg/apis/iam/v1alpha1" + admissionv1 "k8s.io/api/admission/v1" + authenticationv1 "k8s.io/api/authentication/v1" + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/types" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/webhook/admission" +) + +const ( + DeviceUIDAnnotation = "fleet.datumapis.com/registration-device-uid" + DeviceVersionAnnotation = "fleet.datumapis.com/registration-device-version" + OperationAnnotation = "fleet.datumapis.com/registration-operation" +) + +type Project struct { + Identity controller.ProjectIdentity + Client client.Client +} + +type Handler struct { + Store Store + VerifyFence func(context.Context) error + Resolve func(context.Context, string) (Project, error) + Authorize func(context.Context, Project, authenticationv1.UserInfo, string, string, string) error +} + +func aliases(device *inventory.Device) []string { + var result []string + pairs := [][2]string{{"serial", strings.ToLower(strings.TrimSpace(device.Spec.Identity.Serial))}, {"uuid", strings.ToLower(strings.TrimSpace(device.Spec.Identity.SystemUUID))}} + if reference := device.Spec.ProviderHostRef; reference != nil { + encoded, _ := json.Marshal([]string{strings.ToLower(strings.TrimSpace(reference.System)), strings.ToLower(strings.TrimSpace(reference.Type)), strings.ToLower(strings.TrimSpace(reference.ID))}) + pairs = append(pairs, [2]string{"provider", string(encoded)}) + } + for _, pair := range pairs { + if pair[1] != "" { + digest := sha256.Sum256([]byte(pair[0] + ":" + pair[1])) + result = append(result, pair[0]+":"+hex.EncodeToString(digest[:])) + } + } + return result +} + +var systemUUIDPattern = regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`) + +func eligible(device *inventory.Device) bool { + if reference := device.Spec.ProviderHostRef; reference != nil && (strings.TrimSpace(reference.System) == "" || strings.TrimSpace(reference.Type) == "" || strings.TrimSpace(reference.ID) == "") { + return false + } + serial := strings.ToLower(strings.TrimSpace(device.Spec.Identity.Serial)) + uuid := device.Spec.Identity.SystemUUID + return inventory.CapacityBackingError(device) == nil && serial != "" && !slices.Contains([]string{"unknown", "none", "n/a", "default string", "to be filled by o.e.m."}, serial) && systemUUIDPattern.MatchString(uuid) && uuid != "00000000-0000-0000-0000-000000000000" && uuid != "ffffffff-ffff-ffff-ffff-ffffffffffff" +} + +func projectName(actor authenticationv1.UserInfo) (string, error) { + for key, expected := range map[string]string{iam.ParentKindExtraKey: "Project", iam.ParentAPIGroupExtraKey: "resourcemanager.miloapis.com"} { + if values := actor.Extra[key]; len(values) != 1 || values[0] != expected { + return "", errors.New("authenticated Milo project context is required") + } + } + values := actor.Extra[iam.ParentNameExtraKey] + if len(values) != 1 || values[0] == "" || actor.Username == "" || actor.UID == "" { + return "", errors.New("authenticated actor and project identity are required") + } + return values[0], nil +} + +func (handler *Handler) Handle(ctx context.Context, request admission.Request) admission.Response { + if request.Resource.Group == "" && request.Resource.Resource == "namespaces" && request.Name != "default" { + return admission.Allowed("outside the retained inventory namespace") + } + if request.Resource.Group == "resourcemanager.miloapis.com" && request.Resource.Resource == "projects" && request.Operation == admissionv1.Delete { + if slices.Contains(handler.Store.Projects, request.Name) { + return admission.Denied("provider project lifetime is retained by the registration authority") + } + return admission.Allowed("outside the provider registration scope") + } + if request.DryRun != nil && *request.DryRun { + return admission.Denied("registration admission retains reservations and does not support dry-run") + } + name, err := projectName(request.UserInfo) + if err != nil { + return admission.Denied(err.Error()) + } + if !slices.Contains(handler.Store.Projects, name) { + if (request.Resource.Group == "fleet.datumapis.com" && request.Resource.Resource == "devices") || (request.Resource.Group == "" && request.Resource.Resource == "namespaces") { + return admission.Allowed("outside the configured provider identity scope") + } + return admission.Denied("project is outside the configured registration authority") + } + if request.UID == "" { + return admission.Denied("admission operation identity is required") + } + for attempt := 0; attempt < 6; attempt++ { + err = handler.evaluate(ctx, name, request) + if !apierrors.IsConflict(err) { + break + } + } + if err != nil { + return admission.Denied(err.Error()) + } + return admission.Allowed("inert inventory registration only; no availability or preparation authority") +} + +func (handler *Handler) evaluate(ctx context.Context, name string, request admission.Request) error { + if handler.VerifyFence != nil { + if err := handler.VerifyFence(ctx); err != nil { + return err + } + } + secret, ledger, err := handler.Store.Read(ctx) + if err != nil { + return fmt.Errorf("registration unavailable: %w", err) + } + project, err := handler.Resolve(ctx, name) + if err != nil { + return err + } + if !project.Identity.Valid() || project.Identity.RouteName != name || project.Identity.AuthorityID != ledger.Authority { + return errors.New("project lifetime unavailable") + } + if request.Resource.Group == "" && request.Resource.Resource == "namespaces" { + if request.Name == "default" && request.Operation == admissionv1.Delete { + return errors.New("the inventory namespace cannot be deleted within the registration authority") + } + return nil + } + if request.Resource.Group == "fleet.datumapis.com" && request.Resource.Resource == "devices" { + return handler.device(ctx, project, request, secret, ledger) + } + if request.Resource.Group != "metal.datumapis.com" || request.Resource.Resource != "machinecapacities" { + return errors.New("unsupported registration admission resource") + } + if request.Operation != admissionv1.Create || request.SubResource != "" { + return errors.New("capacity mutation and deletion are disabled; retained and legacy capacity require operator reconciliation") + } + if request.Namespace != "default" { + return errors.New("registration requires the default inventory namespace") + } + var capacity metal.MachineCapacity + if err := json.Unmarshal(request.Object.Raw, &capacity); err != nil { + return err + } + if capacity.UID == "" || capacity.Name == "" || capacity.Name != request.Name || capacity.Namespace != "default" || capacity.GenerateName != "" || !capacity.DeletionTimestamp.IsZero() { + return errors.New("an explicit capacity name and API-assigned incarnation are required") + } + if capacity.Spec.AllocationPolicy != "Disabled" || capacity.Spec.ReclaimPolicy != "Retain" || capacity.Spec.CleaningPolicyRef.Name != "" || !reflect.DeepEqual(capacity.Status, metal.MachineCapacityStatus{}) || len(capacity.OwnerReferences) != 0 || len(capacity.Finalizers) != 0 { + return errors.New("only Disabled/Retain registration with an explicitly unconfigured cleaning policy and no status or ownership is supported") + } + annotations := capacity.Annotations + if len(annotations) != 3 || annotations[DeviceUIDAnnotation] == "" || annotations[DeviceVersionAnnotation] == "" || annotations[OperationAnnotation] == "" { + return errors.New("exact Device UID/resourceVersion and a stable registration operation are required") + } + if len(annotations[OperationAnnotation]) > 128 { + return errors.New("registration operation is too long") + } + if err := handler.Authorize(ctx, project, request.UserInfo, "metal.datumapis.com", "machinecapacities", ""); err != nil { + return err + } + if err := handler.Authorize(ctx, project, request.UserInfo, "fleet.datumapis.com", "devices", capacity.Spec.DeviceRef.Name); err != nil { + return err + } + namespace := &corev1.Namespace{} + if err := project.Client.Get(ctx, client.ObjectKey{Name: "default"}, namespace); err != nil { + return err + } + if namespace.UID == "" || !namespace.DeletionTimestamp.IsZero() { + return errors.New("inventory namespace lifetime unavailable") + } + device := &inventory.Device{} + if err := project.Client.Get(ctx, client.ObjectKey{Namespace: "default", Name: capacity.Spec.DeviceRef.Name}, device); err != nil { + return errors.New("selected Device is unavailable") + } + if device.UID != types.UID(annotations[DeviceUIDAnnotation]) || device.ResourceVersion != annotations[DeviceVersionAnnotation] || !device.DeletionTimestamp.IsZero() { + return errors.New("selected Device incarnation or version changed; do not silently refresh the selection") + } + if !eligible(device) { + return errors.New("registration requires non-placeholder serial, canonical system UUID, and complete provider aliases; incomplete identity is ambiguous") + } + entry := Entry{Operation: request.UID, Actor: request.UserInfo, Project: name, ProjectUID: project.Identity.UID, NamespaceUID: namespace.UID, Name: capacity.Name, CapacityUID: capacity.UID, DeviceName: device.Name, DeviceUID: device.UID, DeviceVersion: device.ResourceVersion, Aliases: aliases(device), Input: append(json.RawMessage(nil), request.Object.Raw...), Outcome: "Unknown"} + entry.AssetID = entry.Aliases[1] + for _, retained := range ledger.Entries { + if retained.Operation == entry.Operation && reflect.DeepEqual(retained, entry) { + return nil + } + if overlaps(retained.Aliases, entry.Aliases) || (retained.Project == name && (retained.Name == entry.Name || retained.DeviceUID == entry.DeviceUID)) { + return ErrConflict + } + var prior metal.MachineCapacity + if json.Unmarshal(retained.Input, &prior) != nil { + return errors.New("retained registration is corrupt") + } + if retained.Project == name && prior.Annotations[OperationAnnotation] == annotations[OperationAnnotation] { + return ErrConflict + } + } + for _, fence := range ledger.DeviceFences { + if fence.Project == name && fence.UID == device.UID { + if fence.Deleted || (fence.Version != "" && fence.Version == device.ResourceVersion) { + return ErrConflict + } + continue + } + if overlaps(fence.Aliases, entry.Aliases) { + return ErrConflict + } + } + if err := handler.scan(ctx, entry); err != nil { + return err + } + current, err := handler.Resolve(ctx, name) + if err != nil || current.Identity != project.Identity { + return errors.New("project lifetime changed") + } + if err := project.Client.Get(ctx, client.ObjectKeyFromObject(namespace), namespace); err != nil || namespace.UID != entry.NamespaceUID || !namespace.DeletionTimestamp.IsZero() { + return errors.New("namespace lifetime changed") + } + if err := project.Client.Get(ctx, client.ObjectKeyFromObject(device), device); err != nil || device.UID != entry.DeviceUID || device.ResourceVersion != entry.DeviceVersion || !device.DeletionTimestamp.IsZero() { + return errors.New("selected Device changed") + } + if err := handler.Authorize(ctx, project, request.UserInfo, "metal.datumapis.com", "machinecapacities", ""); err != nil { + return err + } + if err := handler.Authorize(ctx, project, request.UserInfo, "fleet.datumapis.com", "devices", device.Name); err != nil { + return err + } + current, err = handler.Resolve(ctx, name) + if err != nil || current.Identity != project.Identity { + return errors.New("project lifetime changed during authorization") + } + if err := project.Client.Get(ctx, client.ObjectKeyFromObject(namespace), namespace); err != nil || namespace.UID != entry.NamespaceUID || !namespace.DeletionTimestamp.IsZero() { + return errors.New("namespace lifetime changed during authorization") + } + if err := project.Client.Get(ctx, client.ObjectKeyFromObject(device), device); err != nil || device.UID != entry.DeviceUID || device.ResourceVersion != entry.DeviceVersion || !device.DeletionTimestamp.IsZero() { + return errors.New("selected Device changed during authorization") + } + ledger.Entries = append(ledger.Entries, entry) + return handler.Store.Write(ctx, secret, ledger) +} + +func (handler *Handler) scan(ctx context.Context, entry Entry) error { + for _, name := range handler.Store.Projects { + project, err := handler.Resolve(ctx, name) + if err != nil { + return errors.New("provider identity scope is unavailable") + } + var devices inventory.DeviceList + var capacities metal.MachineCapacityList + if err := project.Client.List(ctx, &devices); err != nil { + return errors.New("provider identity inventory is unavailable") + } + if err := project.Client.List(ctx, &capacities); err != nil { + return errors.New("provider capacity inventory is unavailable") + } + for _, device := range devices.Items { + if name == entry.Project && device.UID == entry.DeviceUID { + continue + } + if overlaps(aliases(&device), entry.Aliases) { + return errors.New("another Device shares recorded hardware identity; resolve aliases before registration") + } + } + for _, capacity := range capacities.Items { + if name == entry.Project && capacity.Namespace == "default" && capacity.Name == entry.Name { + return ErrConflict + } + var matched *inventory.Device + for index := range devices.Items { + device := &devices.Items[index] + if device.Name == capacity.Spec.DeviceRef.Name && device.Namespace == capacity.Namespace { + matched = device + break + } + } + if matched == nil || inventory.CapacityBackingError(matched) != nil { + return errors.New("legacy capacity has unresolved physical identity; registration cannot establish non-conflict") + } + if overlaps(aliases(matched), entry.Aliases) { + return ErrConflict + } + } + } + return nil +} + +func (handler *Handler) device(ctx context.Context, project Project, request admission.Request, secret *corev1.Secret, ledger Ledger) error { + var device, old inventory.Device + if request.Operation != admissionv1.Create { + if err := json.Unmarshal(request.OldObject.Raw, &old); err != nil { + return err + } + } + if request.Operation != admissionv1.Delete { + if err := json.Unmarshal(request.Object.Raw, &device); err != nil { + return err + } + } else { + device = old + } + for _, entry := range ledger.Entries { + bound := entry.Project == project.Identity.RouteName && entry.DeviceUID == device.UID + if entry.Project == project.Identity.RouteName && device.Namespace == "default" && entry.DeviceName == device.Name && !bound { + return ErrConflict + } + if bound && (entry.ProjectUID != project.Identity.UID || request.Operation == admissionv1.Delete) { + return ErrConflict + } + if overlaps(entry.Aliases, aliases(&device)) && !bound { + return ErrConflict + } + if bound && !reflect.DeepEqual(device.Spec, old.Spec) { + return errors.New("registered Device specification is frozen") + } + } + if request.Operation == admissionv1.Update { + if device.UID != old.UID || !reflect.DeepEqual(device.Spec.Identity, old.Spec.Identity) || !reflect.DeepEqual(aliases(&device), aliases(&old)) { + return errors.New("Device incarnation and identity are immutable") + } + if old.ResourceVersion == "" { + return errors.New("Device update baseline is unavailable") + } + } + if request.Operation != admissionv1.Create && request.Operation != admissionv1.Delete && request.Operation != admissionv1.Update { + return errors.New("unsupported Device operation") + } + if device.UID == "" { + return errors.New("Device incarnation unavailable") + } + fence := DeviceFence{Project: project.Identity.RouteName, UID: device.UID, Deleted: request.Operation == admissionv1.Delete} + if request.Operation == admissionv1.Update { + fence.Version = old.ResourceVersion + } + if request.Operation == admissionv1.Create { + fence.Aliases = aliases(&device) + for _, retained := range ledger.DeviceFences { + if overlaps(retained.Aliases, fence.Aliases) && !reflect.DeepEqual(retained, fence) { + return ErrConflict + } + } + } + for _, retained := range ledger.DeviceFences { + if reflect.DeepEqual(retained, fence) { + return nil + } + } + ledger.DeviceFences = append(ledger.DeviceFences, fence) + return handler.Store.Write(ctx, secret, ledger) +} diff --git a/internal/registration/admission_test.go b/internal/registration/admission_test.go new file mode 100644 index 00000000..efd71d74 --- /dev/null +++ b/internal/registration/admission_test.go @@ -0,0 +1,502 @@ +package registration + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "sync" + "sync/atomic" + "testing" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + metal "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/controller" + iam "go.miloapis.com/milo/pkg/apis/iam/v1alpha1" + admissionv1 "k8s.io/api/admission/v1" + authenticationv1 "k8s.io/api/authentication/v1" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/types" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/webhook/admission" +) + +func fixture(t *testing.T) (*Handler, *inventory.Device) { + t.Helper() + scheme := runtime.NewScheme() + for _, add := range []func(*runtime.Scheme) error{corev1.AddToScheme, metal.AddToScheme, inventory.AddToScheme} { + if err := add(scheme); err != nil { + t.Fatal(err) + } + } + device := &inventory.Device{ObjectMeta: metav1.ObjectMeta{Name: "server", Namespace: "default", UID: "device-1", ResourceVersion: "1"}, Spec: inventory.DeviceSpec{Identity: inventory.DeviceIdentity{Serial: "SERIAL-1", SystemUUID: "11111111-1111-1111-1111-111111111111", Model: "test"}}} + namespace := &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "default", UID: "namespace-1"}} + api := fake.NewClientBuilder().WithScheme(scheme).WithObjects(device, namespace).Build() + encoded, _ := json.Marshal(Ledger{Authority: "milo", Projects: []string{"provider"}}) + private := fake.NewClientBuilder().WithScheme(scheme).WithObjects(&corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: LedgerName, Namespace: "private", UID: "ledger-1"}, Data: map[string][]byte{"ledger.json": encoded}}).Build() + return &Handler{Store: Store{Client: private, Namespace: "private", Authority: "milo", Projects: []string{"provider"}}, Resolve: func(context.Context, string) (Project, error) { + return Project{Identity: controller.ProjectIdentity{AuthorityID: "milo", RouteName: "provider", UID: "project-1"}, Client: api}, nil + }, Authorize: func(context.Context, Project, authenticationv1.UserInfo, string, string, string) error { return nil }}, device +} + +func registrationRequest(t *testing.T, device *inventory.Device, name string) admission.Request { + t.Helper() + capacity := metal.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: "default", UID: types.UID("capacity-" + name), Annotations: map[string]string{DeviceUIDAnnotation: string(device.UID), DeviceVersionAnnotation: device.ResourceVersion, OperationAnnotation: "client-" + name}}, Spec: metal.MachineCapacitySpec{DeviceRef: metal.LocalReference{Name: device.Name}, AllocationPolicy: "Disabled", ReclaimPolicy: "Retain"}} + raw, err := json.Marshal(capacity) + if err != nil { + t.Fatal(err) + } + return admission.Request{AdmissionRequest: admissionv1.AdmissionRequest{UID: types.UID("request-" + name), Name: name, Namespace: "default", Operation: admissionv1.Create, Resource: metav1.GroupVersionResource{Group: "metal.datumapis.com", Version: "v1alpha1", Resource: "machinecapacities"}, UserInfo: authenticationv1.UserInfo{Username: "operator", UID: "actor-1", Extra: map[string]authenticationv1.ExtraValue{iam.ParentKindExtraKey: {"Project"}, iam.ParentAPIGroupExtraKey: {"resourcemanager.miloapis.com"}, iam.ParentNameExtraKey: {"provider"}}}, Object: runtime.RawExtension{Raw: raw}}} +} + +func TestConcurrentRegistrationReservesOnce(t *testing.T) { + handler, device := fixture(t) + var allowed atomic.Int32 + var workers sync.WaitGroup + for index := 0; index < 20; index++ { + request := registrationRequest(t, device, fmt.Sprintf("capacity-%d", index)) + workers.Add(1) + go func() { + defer workers.Done() + if handler.Handle(context.Background(), request).Allowed { + allowed.Add(1) + } + }() + } + workers.Wait() + if allowed.Load() != 1 { + t.Fatalf("allowed %d registrations", allowed.Load()) + } + _, ledger, err := handler.Store.Read(context.Background()) + if err != nil || len(ledger.Entries) != 1 { + t.Fatalf("ledger: %+v %v", ledger, err) + } + entry := ledger.Entries[0] + if entry.Actor.UID != "actor-1" || entry.DeviceUID != device.UID || entry.DeviceVersion != device.ResourceVersion || entry.ProjectUID != "project-1" || entry.NamespaceUID != "namespace-1" || entry.Outcome != "Unknown" { + t.Fatalf("authority not retained: %+v", entry) + } + project, _ := handler.Resolve(context.Background(), "provider") + var capacities metal.MachineCapacityList + if err := project.Client.List(context.Background(), &capacities); err != nil || len(capacities.Items) != 0 { + t.Fatal("admission caused public effects") + } +} + +func TestRegistrationNegatives(t *testing.T) { + tests := map[string]func(*Handler, *inventory.Device, *admission.Request){ + "stale UID": func(_ *Handler, _ *inventory.Device, request *admission.Request) { + changeCapacity(request, func(capacity *metal.MachineCapacity) { capacity.Annotations[DeviceUIDAnnotation] = "old" }) + }, + "stale RV": func(_ *Handler, _ *inventory.Device, request *admission.Request) { + changeCapacity(request, func(capacity *metal.MachineCapacity) { capacity.Annotations[DeviceVersionAnnotation] = "old" }) + }, + "enabled": func(_ *Handler, _ *inventory.Device, request *admission.Request) { + changeCapacity(request, func(capacity *metal.MachineCapacity) { capacity.Spec.AllocationPolicy = "Enabled" }) + }, + "invented policy": func(_ *Handler, _ *inventory.Device, request *admission.Request) { + changeCapacity(request, func(capacity *metal.MachineCapacity) { + capacity.Spec.CleaningPolicyRef.Name = "synthetic-tenant-reuse-v1" + }) + }, + "no baseline": func(_ *Handler, _ *inventory.Device, request *admission.Request) { + changeCapacity(request, func(capacity *metal.MachineCapacity) { capacity.Annotations = nil }) + }, + "direct update": func(_ *Handler, _ *inventory.Device, request *admission.Request) { + request.Operation = admissionv1.Update + }, + "direct delete": func(_ *Handler, _ *inventory.Device, request *admission.Request) { + request.Operation = admissionv1.Delete + }, + "status": func(_ *Handler, _ *inventory.Device, request *admission.Request) { request.SubResource = "status" }, + "missing project": func(_ *Handler, _ *inventory.Device, request *admission.Request) { request.UserInfo.Extra = nil }, + "wrong project": func(_ *Handler, _ *inventory.Device, request *admission.Request) { + request.UserInfo.Extra[iam.ParentNameExtraKey] = authenticationv1.ExtraValue{"consumer"} + }, + "namespace": func(_ *Handler, _ *inventory.Device, request *admission.Request) { request.Namespace = "other" }, + "permission revoked": func(handler *Handler, _ *inventory.Device, _ *admission.Request) { + handler.Authorize = func(context.Context, Project, authenticationv1.UserInfo, string, string, string) error { + return errors.New("denied") + } + }, + "partial identity": func(handler *Handler, device *inventory.Device, request *admission.Request) { + project, _ := handler.Resolve(context.Background(), "provider") + device.Spec.Identity.SystemUUID = "" + if err := project.Client.Update(context.Background(), device); err != nil { + t.Fatal(err) + } + *request = registrationRequest(t, device, request.Name) + }, + "unresolved legacy": func(handler *Handler, _ *inventory.Device, _ *admission.Request) { + project, _ := handler.Resolve(context.Background(), "provider") + if err := project.Client.Create(context.Background(), &metal.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: "legacy", Namespace: "default"}, Spec: metal.MachineCapacitySpec{DeviceRef: metal.LocalReference{Name: "missing"}, AllocationPolicy: "Enabled"}}); err != nil { + t.Fatal(err) + } + }, + } + for name, mutate := range tests { + t.Run(name, func(t *testing.T) { + handler, device := fixture(t) + request := registrationRequest(t, device, "record") + mutate(handler, device, &request) + if response := handler.Handle(context.Background(), request); response.Allowed { + t.Fatal("unsafe registration allowed") + } + _, ledger, err := handler.Store.Read(context.Background()) + if err != nil || len(ledger.Entries) != 0 { + t.Fatal("negative modified registration ledger", err) + } + }) + } +} + +func changeCapacity(request *admission.Request, mutate func(*metal.MachineCapacity)) { + var capacity metal.MachineCapacity + _ = json.Unmarshal(request.Object.Raw, &capacity) + mutate(&capacity) + request.Object.Raw, _ = json.Marshal(capacity) +} + +func TestUnknownRecoveryDoesNotAdoptCopiedAnnotation(t *testing.T) { + handler, device := fixture(t) + request := registrationRequest(t, device, "record") + if !handler.Handle(context.Background(), request).Allowed { + t.Fatal("registration denied") + } + restarted := *handler + if err := restarted.Recover(context.Background()); err != nil { + t.Fatal(err) + } + if handler.Handle(context.Background(), registrationRequest(t, device, "different-name")).Allowed { + t.Fatal("unknown reservation was released") + } + var recreated metal.MachineCapacity + _ = json.Unmarshal(request.Object.Raw, &recreated) + recreated.UID = "recreated-with-copied-annotations" + project, _ := handler.Resolve(context.Background(), "provider") + if err := project.Client.Create(context.Background(), &recreated); err != nil { + t.Fatal(err) + } + if err := restarted.Recover(context.Background()); err != nil { + t.Fatal(err) + } + _, ledger, _ := handler.Store.Read(context.Background()) + if ledger.Entries[0].Outcome != "IncarnationConflict" { + t.Fatal("recreated capacity was adopted") + } +} + +func TestSharedAliasesAndProjectScope(t *testing.T) { + for _, alias := range []string{"serial", "uuid"} { + t.Run(alias, func(t *testing.T) { + handler, device := fixture(t) + project, _ := handler.Resolve(context.Background(), "provider") + duplicate := device.DeepCopyObject().(*inventory.Device) + duplicate.Name, duplicate.UID, duplicate.ResourceVersion = "alias", "alias-uid", "" + if alias == "serial" { + duplicate.Spec.Identity.SystemUUID = "22222222-2222-2222-2222-222222222222" + } else { + duplicate.Spec.Identity.Serial = "other" + } + if err := project.Client.Create(context.Background(), duplicate); err != nil { + t.Fatal(err) + } + if handler.Handle(context.Background(), registrationRequest(t, device, "record")).Allowed { + t.Fatal("ambiguous alias accepted") + } + }) + } +} + +func TestDeviceDeleteRaceRetainsFence(t *testing.T) { + handler, device := fixture(t) + request := registrationRequest(t, device, "record") + deletion := request + deletion.Resource = metav1.GroupVersionResource{Group: "fleet.datumapis.com", Version: "v1alpha1", Resource: "devices"} + deletion.Operation = admissionv1.Delete + deletion.OldObject.Raw, _ = json.Marshal(device) + if !handler.Handle(context.Background(), deletion).Allowed { + t.Fatal("unbound deletion denied") + } + if handler.Handle(context.Background(), request).Allowed { + t.Fatal("registration raced a pending Device deletion") + } + other, selected := fixture(t) + if !other.Handle(context.Background(), registrationRequest(t, selected, "record")).Allowed { + t.Fatal("registration denied") + } + if other.Handle(context.Background(), deletion).Allowed { + t.Fatal("bound Device deletion allowed") + } +} + +func TestProjectLifetimeRecheck(t *testing.T) { + handler, device := fixture(t) + resolve := handler.Resolve + var calls int + handler.Resolve = func(ctx context.Context, name string) (Project, error) { + project, err := resolve(ctx, name) + calls++ + if calls > 1 { + project.Identity.UID = "recreated" + } + return project, err + } + if handler.Handle(context.Background(), registrationRequest(t, device, "record")).Allowed { + t.Fatal("project recreation accepted") + } +} + +func TestNamespaceRecreationAndPermissionRevocationDuringAdmission(t *testing.T) { + for _, mode := range []string{"namespace", "permission"} { + t.Run(mode, func(t *testing.T) { + handler, device := fixture(t) + var calls int + handler.Authorize = func(ctx context.Context, project Project, _ authenticationv1.UserInfo, _, _, _ string) error { + calls++ + if calls == 3 { + if mode == "permission" { + return errors.New("revoked") + } + var namespace corev1.Namespace + if err := project.Client.Get(ctx, client.ObjectKey{Name: "default"}, &namespace); err != nil { + return err + } + if err := project.Client.Delete(ctx, &namespace); err != nil { + return err + } + return project.Client.Create(ctx, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "default", UID: "recreated"}}) + } + return nil + } + response := handler.Handle(context.Background(), registrationRequest(t, device, "record")) + if mode == "permission" && response.Allowed { + t.Fatal("revocation accepted") + } + if mode == "namespace" && response.Allowed { + t.Fatal("namespace recreation admitted") + } + }) + } +} + +func TestCrossProjectAmbiguityAndSharedProviderAlias(t *testing.T) { + for _, shared := range []string{"serial", "uuid", "provider"} { + t.Run(shared, func(t *testing.T) { + handler, device := fixture(t) + first, _ := handler.Resolve(context.Background(), "provider") + other := device.DeepCopyObject().(*inventory.Device) + other.Name, other.UID = "second", "device-2" + other.Spec.Identity.Serial = "second-serial" + other.Spec.Identity.SystemUUID = "22222222-2222-2222-2222-222222222222" + switch shared { + case "serial": + other.Spec.Identity.Serial = " serial-1 " + case "uuid": + other.Spec.Identity.SystemUUID = device.Spec.Identity.SystemUUID + case "provider": + device.Spec.ProviderHostRef = &inventory.ExternalReference{System: "provider", Type: "server", ID: "shared-asset"} + other.Spec.ProviderHostRef = device.Spec.ProviderHostRef + if err := first.Client.Update(context.Background(), device); err != nil { + t.Fatal(err) + } + } + second := fake.NewClientBuilder().WithScheme(first.Client.Scheme()).WithObjects(other, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "default", UID: "namespace-2"}}).Build() + secret, ledger, _ := handler.Store.Read(context.Background()) + ledger.Projects = []string{"provider", "second"} + if err := handler.Store.Write(context.Background(), secret, ledger); err != nil { + t.Fatal(err) + } + handler.Store.Projects = ledger.Projects + handler.Resolve = func(_ context.Context, name string) (Project, error) { + if name == "provider" { + return first, nil + } + return Project{Identity: controller.ProjectIdentity{AuthorityID: "milo", RouteName: "second", UID: "project-2"}, Client: second}, nil + } + firstRequest := registrationRequest(t, device, "one") + secondRequest := registrationRequest(t, other, "two") + secondRequest.UserInfo.Extra[iam.ParentNameExtraKey] = authenticationv1.ExtraValue{"second"} + var workers sync.WaitGroup + for _, request := range []admission.Request{firstRequest, secondRequest} { + workers.Add(1) + go func() { + defer workers.Done() + if handler.Handle(context.Background(), request).Allowed { + t.Error("cross-project alias ambiguity accepted") + } + }() + } + workers.Wait() + }) + } +} + +type timeoutAfterWrite struct{ client.Client } + +func (api timeoutAfterWrite) Update(ctx context.Context, object client.Object, options ...client.UpdateOption) error { + if err := api.Client.Update(ctx, object, options...); err != nil { + return err + } + return errors.New("timeout after commit") +} + +func TestLedgerWriteTimeoutRetainsReservationAcrossRestart(t *testing.T) { + handler, device := fixture(t) + private := handler.Store.Client + handler.Store.Client = timeoutAfterWrite{private} + if handler.Handle(context.Background(), registrationRequest(t, device, "record")).Allowed { + t.Fatal("timeout became success") + } + handler.Store.Client = private + restarted := *handler + if err := restarted.Recover(context.Background()); err != nil { + t.Fatal(err) + } + if restarted.Handle(context.Background(), registrationRequest(t, device, "new-name")).Allowed { + t.Fatal("unknown reservation was reused") + } + _, ledger, _ := restarted.Store.Read(context.Background()) + if len(ledger.Entries) != 1 || ledger.Entries[0].Outcome != "Unknown" { + t.Fatal("unknown reservation lost") + } +} + +func TestDeviceCreatedThroughAdmissionCanRegister(t *testing.T) { + handler, device := fixture(t) + request := registrationRequest(t, device, "record") + creation := request + creation.Resource = metav1.GroupVersionResource{Group: "fleet.datumapis.com", Resource: "devices", Version: "v1alpha1"} + creation.Object.Raw, _ = json.Marshal(device) + if !handler.Handle(context.Background(), creation).Allowed { + t.Fatal("Device create admission denied") + } + if !handler.Handle(context.Background(), request).Allowed { + t.Fatal("own Device creation fence prevented registration") + } +} + +func TestRootProjectDeletionAndDeviceNameReuseAreFenced(t *testing.T) { + handler, device := fixture(t) + request := registrationRequest(t, device, "record") + if !handler.Handle(context.Background(), request).Allowed { + t.Fatal("registration denied") + } + deletion := request + deletion.Name = "provider" + deletion.Operation = admissionv1.Delete + deletion.Resource = metav1.GroupVersionResource{Group: "resourcemanager.miloapis.com", Version: "v1alpha1", Resource: "projects"} + deletion.UserInfo.Extra = nil + if handler.Handle(context.Background(), deletion).Allowed { + t.Fatal("root Project deletion bypass") + } + replacement := device.DeepCopyObject().(*inventory.Device) + replacement.UID = "recreated" + replacement.Spec.Identity.Serial = "new-serial" + replacement.Spec.Identity.SystemUUID = "22222222-2222-2222-2222-222222222222" + creation := registrationRequest(t, device, "record") + creation.Resource = metav1.GroupVersionResource{Group: "fleet.datumapis.com", Version: "v1alpha1", Resource: "devices"} + creation.Object.Raw, _ = json.Marshal(replacement) + if handler.Handle(context.Background(), creation).Allowed { + t.Fatal("registered Device name was reused by a new incarnation") + } +} + +func TestNonConflictingLegacyCapacityAndAllocationRemainUntouched(t *testing.T) { + handler, device := fixture(t) + ctx := context.Background() + project, _ := handler.Resolve(ctx, "provider") + legacyDevice := device.DeepCopyObject().(*inventory.Device) + legacyDevice.Name, legacyDevice.UID, legacyDevice.ResourceVersion = "legacy-device", "legacy-device-uid", "" + legacyDevice.Spec.Identity.Serial, legacyDevice.Spec.Identity.SystemUUID = "legacy-serial", "22222222-2222-2222-2222-222222222222" + legacy := &metal.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: "legacy", Namespace: "default", UID: "legacy-uid"}, Spec: metal.MachineCapacitySpec{DeviceRef: metal.LocalReference{Name: legacyDevice.Name}, AllocationPolicy: "Enabled", ReclaimPolicy: "Retain", CleaningPolicyRef: metal.LocalReference{Name: "synthetic-tenant-reuse-v1"}}, Status: metal.MachineCapacityStatus{Conditions: []metav1.Condition{{Type: "Available", Status: metav1.ConditionFalse, Reason: "Occupied"}}}} + allocation := &metal.MachineAllocation{ObjectMeta: metav1.ObjectMeta{Name: "occupied", Namespace: "default", UID: "allocation-uid"}} + for _, object := range []client.Object{legacyDevice, legacy, allocation} { + if err := project.Client.Create(ctx, object); err != nil { + t.Fatal(err) + } + } + beforeCapacity, _ := json.Marshal(legacy) + beforeAllocation, _ := json.Marshal(allocation) + if !handler.Handle(ctx, registrationRequest(t, device, "record")).Allowed { + t.Fatal("non-conflicting legacy capacity blocked registration") + } + if err := project.Client.Get(ctx, client.ObjectKeyFromObject(legacy), legacy); err != nil { + t.Fatal(err) + } + if err := project.Client.Get(ctx, client.ObjectKeyFromObject(allocation), allocation); err != nil { + t.Fatal(err) + } + afterCapacity, _ := json.Marshal(legacy) + afterAllocation, _ := json.Marshal(allocation) + if string(beforeCapacity) != string(afterCapacity) || string(beforeAllocation) != string(afterAllocation) { + t.Fatal("registration modified legacy state") + } + if handler.Handle(ctx, registrationRequest(t, legacyDevice, "conflicting")).Allowed { + t.Fatal("occupied legacy asset was registered") + } +} + +func TestRecoveryReadFailureBecomesUnknownWithoutReleasing(t *testing.T) { + handler, device := fixture(t) + ctx := context.Background() + request := registrationRequest(t, device, "record") + if !handler.Handle(ctx, request).Allowed { + t.Fatal("registration denied") + } + var capacity metal.MachineCapacity + if err := json.Unmarshal(request.Object.Raw, &capacity); err != nil { + t.Fatal(err) + } + project, _ := handler.Resolve(ctx, "provider") + if err := project.Client.Create(ctx, &capacity); err != nil { + t.Fatal(err) + } + if err := handler.Recover(ctx); err != nil { + t.Fatal(err) + } + _, before, _ := handler.Store.Read(ctx) + if before.Entries[0].Outcome != "Recorded" { + t.Fatal("exact completion not recovered") + } + handler.Resolve = func(context.Context, string) (Project, error) { + return Project{}, errors.New("read authority unavailable") + } + if err := handler.Recover(ctx); err == nil { + t.Fatal("read failure became success") + } + _, after, _ := handler.Store.Read(ctx) + if len(after.Entries) != 1 || after.Entries[0].Outcome != "Unknown" || after.Entries[0].CapacityUID != before.Entries[0].CapacityUID { + t.Fatal("uncertain recovery lost its reservation or retained a positive observation") + } +} + +func TestPendingDeviceUpdateCannotRaceSelectedVersion(t *testing.T) { + handler, device := fixture(t) + ctx := context.Background() + registration := registrationRequest(t, device, "record") + update := registration + update.Resource = metav1.GroupVersionResource{Group: "fleet.datumapis.com", Version: "v1alpha1", Resource: "devices"} + update.Operation = admissionv1.Update + update.OldObject.Raw, _ = json.Marshal(device) + device.Labels = map[string]string{"display": "changed"} + update.Object.Raw, _ = json.Marshal(device) + if !handler.Handle(ctx, update).Allowed { + t.Fatal("unbound Device update rejected") + } + if handler.Handle(ctx, registration).Allowed { + t.Fatal("registration raced an admitted but uncompleted Device update") + } + project, _ := handler.Resolve(ctx, "provider") + if err := project.Client.Update(ctx, device); err != nil { + t.Fatal(err) + } + if handler.Handle(ctx, registration).Allowed { + t.Fatal("stale UI selection silently refreshed") + } + if !handler.Handle(ctx, registrationRequest(t, device, "explicit-new-selection")).Allowed { + t.Fatal("explicit new persisted baseline rejected") + } +} diff --git a/internal/registration/envtest_test.go b/internal/registration/envtest_test.go new file mode 100644 index 00000000..f21bcadc --- /dev/null +++ b/internal/registration/envtest_test.go @@ -0,0 +1,258 @@ +package registration + +import ( + "bytes" + "context" + "encoding/json" + "encoding/pem" + "io" + "net/http/httptest" + "os" + "path/filepath" + "sync" + "sync/atomic" + "testing" + "time" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + metal "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/controller" + iam "go.miloapis.com/milo/pkg/apis/iam/v1alpha1" + admissionregistrationv1 "k8s.io/api/admissionregistration/v1" + authenticationv1 "k8s.io/api/authentication/v1" + authorizationv1 "k8s.io/api/authorization/v1" + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime" + utilyaml "k8s.io/apimachinery/pkg/util/yaml" + "k8s.io/client-go/rest" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/envtest" + "sigs.k8s.io/controller-runtime/pkg/webhook/admission" + "sigs.k8s.io/yaml" +) + +func pemCertificate(raw []byte) []byte { + return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: raw}) +} + +func TestRealAPIServerAdmissionAndCAS(t *testing.T) { + if os.Getenv("KUBEBUILDER_ASSETS") == "" { + t.Skip("KUBEBUILDER_ASSETS required") + } + environment := &envtest.Environment{CRDDirectoryPaths: []string{filepath.Join("..", "..", "config", "base", "crd"), filepath.Join("..", "..", "config", "components", "inventory", "crds")}, ErrorIfCRDPathMissing: true} + config, err := environment.Start() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if err := environment.Stop(); err != nil { + t.Error(err) + } + }) + scheme := runtime.NewScheme() + for _, add := range []func(*runtime.Scheme) error{corev1.AddToScheme, inventory.AddToScheme, metal.AddToScheme, admissionregistrationv1.AddToScheme, authorizationv1.AddToScheme} { + if err := add(scheme); err != nil { + t.Fatal(err) + } + } + api, err := client.New(config, client.Options{Scheme: scheme}) + if err != nil { + t.Fatal(err) + } + ctx := context.Background() + if err := api.Create(ctx, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "fleet-system-private"}}); err != nil { + t.Fatal(err) + } + device := &inventory.Device{TypeMeta: metav1.TypeMeta{APIVersion: inventory.GroupVersion.String(), Kind: "Device"}, ObjectMeta: metav1.ObjectMeta{Name: "hardware", Namespace: "default"}, Spec: inventory.DeviceSpec{ClaimRef: inventory.LocalReference{Name: "installation"}, Identity: inventory.DeviceIdentity{Model: "test", Serial: "serial-1", SystemUUID: "11111111-1111-1111-1111-111111111111"}}} + if err := api.Create(ctx, device); err != nil { + t.Fatal(err) + } + encoded, _ := json.Marshal(Ledger{Authority: "milo", Projects: []string{"provider"}}) + if err := api.Create(ctx, &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: LedgerName, Namespace: "fleet-system-private"}, Data: map[string][]byte{"ledger.json": encoded}}); err != nil { + t.Fatal(err) + } + protection, err := os.ReadFile("../../config/base/registration/protection.yaml") + if err != nil { + t.Fatal(err) + } + decoder := utilyaml.NewYAMLOrJSONDecoder(bytes.NewReader(protection), 4096) + for { + var object unstructured.Unstructured + err := decoder.Decode(&object.Object) + if err == io.EOF { + break + } + if err != nil { + t.Fatal(err) + } + if err := api.Create(ctx, &object); err != nil { + t.Fatal(err) + } + } + protectionDeadline := time.Now().Add(10 * time.Second) + for { + probe := &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: LedgerName, Namespace: "fleet-system-private"}} + err := api.Delete(ctx, probe, client.DryRunAll) + if apierrors.IsInvalid(err) || apierrors.IsForbidden(err) { + break + } + if time.Now().After(protectionDeadline) { + t.Fatalf("ledger retention policy did not engage: %v", err) + } + time.Sleep(30 * time.Millisecond) + } + for { + probe := &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "fleet-system-private"}} + err := api.Delete(ctx, probe, client.DryRunAll) + if apierrors.IsInvalid(err) || apierrors.IsForbidden(err) { + break + } + if time.Now().After(protectionDeadline) { + t.Fatalf("namespace retention policy did not engage: %v", err) + } + time.Sleep(30 * time.Millisecond) + } + privateConfig := rest.CopyConfig(config) + privateConfig.Impersonate = rest.ImpersonationConfig{UserName: "system:serviceaccount:fleet-system:fleet-registration", Groups: []string{"system:masters"}} + private, err := client.New(privateConfig, client.Options{Scheme: scheme}) + if err != nil { + t.Fatal(err) + } + var denied atomic.Bool + handler := &Handler{Store: Store{Client: private, Namespace: "fleet-system-private", Authority: "milo", Projects: []string{"provider"}}, VerifyFence: func(ctx context.Context) error { return VerifyFence(ctx, api) }, Resolve: func(context.Context, string) (Project, error) { + return Project{Identity: controller.ProjectIdentity{AuthorityID: "milo", RouteName: "provider", UID: "project-1"}, Client: api}, nil + }, Authorize: func(ctx context.Context, project Project, actor authenticationv1.UserInfo, group, resource, name string) error { + if denied.Load() { + return ErrConflict + } + return Authorize(ctx, project, actor, group, resource, name) + }} + server := httptest.NewTLSServer(&admission.Webhook{Handler: handler}) + t.Cleanup(server.Close) + url := server.URL + data, err := os.ReadFile("../../config/components/registration-admission/webhook.yaml") + if err != nil { + t.Fatal(err) + } + webhooks := &admissionregistrationv1.ValidatingWebhookConfiguration{} + if err := yaml.UnmarshalStrict(data, webhooks); err != nil { + t.Fatal(err) + } + webhooks.Webhooks[0].ClientConfig = admissionregistrationv1.WebhookClientConfig{URL: &url, CABundle: pemCertificate(server.Certificate().Raw)} + if err := api.Create(ctx, webhooks); err != nil { + t.Fatal(err) + } + actorConfig := rest.CopyConfig(config) + actorConfig.Impersonate = rest.ImpersonationConfig{UserName: "operator", UID: "actor-1", Groups: []string{"system:masters"}, Extra: map[string][]string{iam.ParentKindExtraKey: {"Project"}, iam.ParentAPIGroupExtraKey: {"resourcemanager.miloapis.com"}, iam.ParentNameExtraKey: {"provider"}}} + actor, err := client.New(actorConfig, client.Options{Scheme: scheme}) + if err != nil { + t.Fatal(err) + } + deadline := time.Now().Add(10 * time.Second) + for { + probe := &metal.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: "dry-run-probe", Namespace: "default"}, Spec: metal.MachineCapacitySpec{DeviceRef: metal.LocalReference{Name: device.Name}, AllocationPolicy: "Disabled", ReclaimPolicy: "Retain"}} + err = actor.Create(ctx, probe, client.DryRunAll) + if apierrors.IsForbidden(err) { + break + } + if time.Now().After(deadline) { + t.Fatalf("webhook did not engage: %v", err) + } + time.Sleep(30 * time.Millisecond) + } + var wins atomic.Int32 + var workers sync.WaitGroup + for _, name := range []string{"first", "second", "third"} { + request := registrationRequest(t, device, name) + var capacity metal.MachineCapacity + _ = json.Unmarshal(request.Object.Raw, &capacity) + capacity.UID = "forged-client-uid" + workers.Add(1) + go func() { + defer workers.Done() + if actor.Create(ctx, &capacity) == nil { + wins.Add(1) + } + }() + } + workers.Wait() + if wins.Load() != 1 { + t.Fatalf("wanted one admission, got %d", wins.Load()) + } + if err := handler.Recover(ctx); err != nil { + t.Fatal(err) + } + _, ledger, err := handler.Store.Read(ctx) + if err != nil || len(ledger.Entries) != 1 || ledger.Entries[0].Outcome != "Recorded" || ledger.Entries[0].CapacityUID == "forged-client-uid" { + t.Fatalf("incarnation not bound by real API: %+v %v", ledger, err) + } + var capacity metal.MachineCapacity + if err := actor.Get(ctx, client.ObjectKey{Namespace: "default", Name: ledger.Entries[0].Name}, &capacity); err != nil { + t.Fatal(err) + } + capacity.Spec.AllocationPolicy = "Enabled" + capacity.Spec.CleaningPolicyRef.Name = "invented-policy" + if err := actor.Update(ctx, &capacity); !apierrors.IsForbidden(err) { + t.Fatalf("direct enabling bypass: %v", err) + } + if err := actor.Get(ctx, client.ObjectKeyFromObject(&capacity), &capacity); err != nil { + t.Fatal(err) + } + capacity.Annotations[DeviceUIDAnnotation] = "copied-other-incarnation" + if err := actor.Update(ctx, &capacity); !apierrors.IsForbidden(err) { + t.Fatalf("binding annotation bypass: %v", err) + } + if err := actor.Get(ctx, client.ObjectKeyFromObject(&capacity), &capacity); err != nil { + t.Fatal(err) + } + capacity.Status.Conditions = []metav1.Condition{{Type: "Available", Status: metav1.ConditionTrue, Reason: "Fabricated", Message: "Must not be accepted", LastTransitionTime: metav1.Now()}} + if err := actor.Status().Update(ctx, &capacity); !apierrors.IsForbidden(err) { + t.Fatalf("positive readiness bypass: %v", err) + } + if err := actor.Delete(ctx, &capacity); !apierrors.IsForbidden(err) { + t.Fatalf("direct deletion bypass: %v", err) + } + if err := actor.Delete(ctx, device); !apierrors.IsForbidden(err) { + t.Fatalf("Device deletion bypass: %v", err) + } + var namespace corev1.Namespace + if err := actor.Get(ctx, client.ObjectKey{Name: "default"}, &namespace); err != nil { + t.Fatal(err) + } + if err := actor.Delete(ctx, &namespace); !apierrors.IsForbidden(err) { + t.Fatalf("inventory namespace deletion bypass: %v", err) + } + var privateNamespace corev1.Namespace + if err := api.Get(ctx, client.ObjectKey{Name: "fleet-system-private"}, &privateNamespace); err != nil { + t.Fatal(err) + } + if err := api.Delete(ctx, &privateNamespace); !apierrors.IsInvalid(err) && !apierrors.IsForbidden(err) { + t.Fatalf("private namespace deletion bypass: %v", err) + } + secret, _, err := handler.Store.Read(ctx) + if err != nil { + t.Fatal(err) + } + if err := api.Delete(ctx, secret); !apierrors.IsInvalid(err) && !apierrors.IsForbidden(err) { + t.Fatalf("ledger deletion bypass: %v", err) + } + if err := api.Update(ctx, secret); !apierrors.IsInvalid(err) && !apierrors.IsForbidden(err) { + t.Fatalf("ledger overwrite bypass: %v", err) + } + duplicate := device.DeepCopyObject().(*inventory.Device) + duplicate.Name, duplicate.UID, duplicate.ResourceVersion = "other", "", "" + if err := actor.Create(ctx, duplicate); !apierrors.IsForbidden(err) { + t.Fatalf("alias bypass: %v", err) + } + denied.Store(true) + request := registrationRequest(t, device, "denied") + var rejected metal.MachineCapacity + _ = json.Unmarshal(request.Object.Raw, &rejected) + rejected.UID = "" + if err := actor.Create(ctx, &rejected); !apierrors.IsForbidden(err) { + t.Fatalf("revoked authorization bypass: %v", err) + } +} diff --git a/internal/registration/fence.go b/internal/registration/fence.go new file mode 100644 index 00000000..9f2330ba --- /dev/null +++ b/internal/registration/fence.go @@ -0,0 +1,56 @@ +package registration + +import ( + "context" + "errors" + "slices" + + admissionv1 "k8s.io/api/admissionregistration/v1" + "sigs.k8s.io/controller-runtime/pkg/client" +) + +func VerifyFence(ctx context.Context, reader client.Reader) error { + var configuration admissionv1.ValidatingWebhookConfiguration + if err := reader.Get(ctx, client.ObjectKey{Name: "fleet-capacity-registration"}, &configuration); err != nil { + return errors.New("project-plane registration admission configuration is unavailable") + } + if !configuration.DeletionTimestamp.IsZero() { + return errors.New("registration admission configuration is deleting") + } + for _, webhook := range configuration.Webhooks { + if webhook.Name != "registration.fleet.datumapis.com" { + continue + } + if webhook.FailurePolicy == nil || *webhook.FailurePolicy != admissionv1.Fail || webhook.SideEffects == nil || *webhook.SideEffects != admissionv1.SideEffectClassNoneOnDryRun || len(webhook.MatchConditions) != 0 || (webhook.NamespaceSelector != nil && (len(webhook.NamespaceSelector.MatchLabels) != 0 || len(webhook.NamespaceSelector.MatchExpressions) != 0)) || (webhook.ObjectSelector != nil && (len(webhook.ObjectSelector.MatchLabels) != 0 || len(webhook.ObjectSelector.MatchExpressions) != 0)) || len(webhook.ClientConfig.CABundle) == 0 { + return errors.New("registration admission must be fail-closed, unfiltered, and have an explicit serving CA") + } + for _, required := range []struct { + group, resource, version string + operations []admissionv1.OperationType + }{ + {"metal.datumapis.com", "machinecapacities", "v1alpha1", []admissionv1.OperationType{admissionv1.Create, admissionv1.Update, admissionv1.Delete}}, + {"metal.datumapis.com", "machinecapacities/status", "v1alpha1", []admissionv1.OperationType{admissionv1.Update}}, + {"fleet.datumapis.com", "devices", "v1alpha1", []admissionv1.OperationType{admissionv1.Create, admissionv1.Update, admissionv1.Delete}}, + {"", "namespaces", "v1", []admissionv1.OperationType{admissionv1.Delete}}, + {"resourcemanager.miloapis.com", "projects", "v1alpha1", []admissionv1.OperationType{admissionv1.Delete}}, + } { + for _, operation := range required.operations { + found := false + wantedScope := admissionv1.NamespacedScope + if required.resource == "namespaces" || required.resource == "projects" { + wantedScope = admissionv1.ClusterScope + } + for _, rule := range webhook.Rules { + if (rule.Scope == nil || *rule.Scope == admissionv1.AllScopes || *rule.Scope == wantedScope) && slices.Contains(rule.APIGroups, required.group) && slices.Contains(rule.APIVersions, required.version) && slices.Contains(rule.Resources, required.resource) && slices.Contains(rule.Operations, operation) { + found = true + } + } + if !found { + return errors.New("registration admission omits a required write fence") + } + } + } + return nil + } + return errors.New("registration admission webhook is missing") +} diff --git a/internal/registration/fence_test.go b/internal/registration/fence_test.go new file mode 100644 index 00000000..31287684 --- /dev/null +++ b/internal/registration/fence_test.go @@ -0,0 +1,58 @@ +package registration + +import ( + "context" + "os" + "testing" + + admissionv1 "k8s.io/api/admissionregistration/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/yaml" +) + +func TestPackagedProjectAdmissionFence(t *testing.T) { + data, err := os.ReadFile("../../config/components/registration-admission/webhook.yaml") + if err != nil { + t.Fatal(err) + } + var configured admissionv1.ValidatingWebhookConfiguration + if err := yaml.UnmarshalStrict(data, &configured); err != nil { + t.Fatal(err) + } + configured.Webhooks[0].ClientConfig.CABundle = []byte("environment-owned-serving-ca") + for _, test := range []struct { + name string + mutate func(*admissionv1.ValidatingWebhookConfiguration) + allowed bool + }{ + {"complete", func(*admissionv1.ValidatingWebhookConfiguration) {}, true}, + {"no serving CA", func(configuration *admissionv1.ValidatingWebhookConfiguration) { + configuration.Webhooks[0].ClientConfig.CABundle = nil + }, false}, + {"fail open", func(configuration *admissionv1.ValidatingWebhookConfiguration) { + policy := admissionv1.Ignore + configuration.Webhooks[0].FailurePolicy = &policy + }, false}, + {"missing Device protection", func(configuration *admissionv1.ValidatingWebhookConfiguration) { + configuration.Webhooks[0].Rules = configuration.Webhooks[0].Rules[:1] + }, false}, + {"caller annotation selector", func(configuration *admissionv1.ValidatingWebhookConfiguration) { + configuration.Webhooks[0].ObjectSelector = &metav1.LabelSelector{MatchLabels: map[string]string{"registration": "true"}} + }, false}, + } { + t.Run(test.name, func(t *testing.T) { + configuration := configured.DeepCopy() + test.mutate(configuration) + scheme := runtime.NewScheme() + if err := admissionv1.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + api := fake.NewClientBuilder().WithScheme(scheme).WithObjects(configuration).Build() + if err := VerifyFence(context.Background(), api); (err == nil) != test.allowed { + t.Fatalf("unexpected fence result: %v", err) + } + }) + } +} diff --git a/internal/registration/ledger.go b/internal/registration/ledger.go new file mode 100644 index 00000000..8452bc8b --- /dev/null +++ b/internal/registration/ledger.go @@ -0,0 +1,94 @@ +package registration + +import ( + "context" + "encoding/json" + "errors" + "reflect" + + authenticationv1 "k8s.io/api/authentication/v1" + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/types" + "sigs.k8s.io/controller-runtime/pkg/client" +) + +const LedgerName = "fleet-capacity-registration-v1" + +var ErrConflict = errors.New("registration conflicts with retained identity or an unknown operation; operator reconciliation is required") + +type Entry struct { + Operation types.UID `json:"operation"` + Actor authenticationv1.UserInfo `json:"actor"` + Project string `json:"project"` + ProjectUID types.UID `json:"projectUID"` + NamespaceUID types.UID `json:"namespaceUID"` + Name string `json:"name"` + CapacityUID types.UID `json:"capacityUID"` + DeviceName string `json:"deviceName"` + DeviceUID types.UID `json:"deviceUID"` + DeviceVersion string `json:"deviceVersion"` + Aliases []string `json:"aliases"` + AssetID string `json:"assetID"` + Input json.RawMessage `json:"input"` + Outcome string `json:"outcome"` +} + +type DeviceFence struct { + Project string `json:"project"` + UID types.UID `json:"uid"` + Aliases []string `json:"aliases,omitempty"` + Deleted bool `json:"deleted,omitempty"` + Version string `json:"version,omitempty"` +} + +type Ledger struct { + Authority string `json:"authority"` + Projects []string `json:"projects"` + Entries []Entry `json:"entries"` + DeviceFences []DeviceFence `json:"deviceFences"` +} + +type Store struct { + Client client.Client + Namespace string + Authority string + Projects []string +} + +func (store Store) Read(ctx context.Context) (*corev1.Secret, Ledger, error) { + secret := &corev1.Secret{} + if err := store.Client.Get(ctx, client.ObjectKey{Namespace: store.Namespace, Name: LedgerName}, secret); err != nil { + return nil, Ledger{}, err + } + var ledger Ledger + if err := json.Unmarshal(secret.Data["ledger.json"], &ledger); err != nil { + return nil, Ledger{}, err + } + if secret.UID == "" || !secret.DeletionTimestamp.IsZero() || ledger.Authority != store.Authority || !reflect.DeepEqual(ledger.Projects, store.Projects) { + return nil, Ledger{}, errors.New("registration ledger lifetime or configured scope is unavailable") + } + return secret, ledger, nil +} + +func (store Store) Write(ctx context.Context, secret *corev1.Secret, ledger Ledger) error { + encoded, err := json.Marshal(ledger) + if err != nil { + return err + } + if len(encoded) > 750000 { + return errors.New("registration ledger is full; reservations were not released") + } + secret.Data["ledger.json"] = encoded + return store.Client.Update(ctx, secret) +} + +func overlaps(left, right []string) bool { + for _, first := range left { + for _, second := range right { + if first == second { + return true + } + } + } + return false +} diff --git a/internal/registration/runtime.go b/internal/registration/runtime.go new file mode 100644 index 00000000..b19091b8 --- /dev/null +++ b/internal/registration/runtime.go @@ -0,0 +1,114 @@ +package registration + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "reflect" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + metal "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/manager" + "go.datum.net/fleet/internal/projectdiscovery" + authenticationv1 "k8s.io/api/authentication/v1" + authorizationv1 "k8s.io/api/authorization/v1" + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/client-go/rest" + "sigs.k8s.io/controller-runtime/pkg/client" +) + +func NewHandler(store Store, root client.Client, template *rest.Config, scheme *runtime.Scheme) *Handler { + return &Handler{Store: store, VerifyFence: func(ctx context.Context) error { return VerifyFence(ctx, root) }, Resolve: func(ctx context.Context, name string) (Project, error) { + identity, err := manager.ResolveProjectIdentity(ctx, root, store.Authority, name) + if err != nil { + return Project{}, err + } + config, err := projectdiscovery.ProjectRESTConfig(template, name) + if err != nil { + return Project{}, err + } + api, err := client.New(config, client.Options{Scheme: scheme}) + return Project{Identity: identity, Client: api}, err + }, Authorize: Authorize} +} + +func Authorize(ctx context.Context, project Project, actor authenticationv1.UserInfo, group, resource, name string) error { + verb := "get" + if resource == "machinecapacities" { + verb = "create" + } + extra := map[string]authorizationv1.ExtraValue{} + for key, values := range actor.Extra { + extra[key] = authorizationv1.ExtraValue(append([]string(nil), values...)) + } + review := &authorizationv1.SubjectAccessReview{Spec: authorizationv1.SubjectAccessReviewSpec{User: actor.Username, UID: actor.UID, Groups: append([]string(nil), actor.Groups...), Extra: extra, ResourceAttributes: &authorizationv1.ResourceAttributes{Group: group, Resource: resource, Version: "v1alpha1", Namespace: "default", Verb: verb, Name: name}}} + if err := project.Client.Create(ctx, review); err != nil { + return errors.New("current registration authorization is unavailable") + } + if !review.Status.Allowed || review.Status.Denied || review.Status.EvaluationError != "" { + return fmt.Errorf("current %s permission on %s is required", verb, resource) + } + return nil +} + +func (handler *Handler) Recover(ctx context.Context) error { + secret, ledger, err := handler.Store.Read(ctx) + if err != nil { + return err + } + changed := false + var failures error + for index := range ledger.Entries { + entry := &ledger.Entries[index] + outcome, err := handler.observe(ctx, *entry) + failures = errors.Join(failures, err) + if entry.Outcome != outcome { + entry.Outcome = outcome + changed = true + } + } + if changed { + failures = errors.Join(failures, handler.Store.Write(ctx, secret, ledger)) + } + return failures +} + +func (handler *Handler) observe(ctx context.Context, entry Entry) (string, error) { + project, err := handler.Resolve(ctx, entry.Project) + if err != nil { + return "Unknown", err + } + if project.Identity.UID != entry.ProjectUID { + return "LifetimeLost", nil + } + var namespace corev1.Namespace + if err := project.Client.Get(ctx, client.ObjectKey{Name: "default"}, &namespace); err != nil && !apierrors.IsNotFound(err) { + return "Unknown", err + } + var device inventory.Device + if err := project.Client.Get(ctx, client.ObjectKey{Namespace: "default", Name: entry.DeviceName}, &device); err != nil && !apierrors.IsNotFound(err) { + return "Unknown", err + } + if namespace.UID != entry.NamespaceUID || !namespace.DeletionTimestamp.IsZero() || device.UID != entry.DeviceUID || !device.DeletionTimestamp.IsZero() || !reflect.DeepEqual(aliases(&device), entry.Aliases) { + return "LifetimeLost", nil + } + var current metal.MachineCapacity + err = project.Client.Get(ctx, client.ObjectKey{Namespace: "default", Name: entry.Name}, ¤t) + if apierrors.IsNotFound(err) { + return "Unknown", nil + } + if err != nil { + return "Unknown", err + } + var input metal.MachineCapacity + if err := json.Unmarshal(entry.Input, &input); err != nil { + return "Unknown", err + } + if current.UID != entry.CapacityUID || !reflect.DeepEqual(current.Spec, input.Spec) || !reflect.DeepEqual(current.Annotations, input.Annotations) || !reflect.DeepEqual(current.Labels, input.Labels) || !current.DeletionTimestamp.IsZero() { + return "IncarnationConflict", nil + } + return "Recorded", nil +} diff --git a/ui/provider/README.md b/ui/provider/README.md index e6f9b08a..ef4567c8 100644 --- a/ui/provider/README.md +++ b/ui/provider/README.md @@ -7,13 +7,14 @@ mounts its pages under `/plugins//`, with a **Bare Metal** item under Operations in the navigation. The page has four tabs: - **Capacity** (the mount root, where the nav item points) lists the - provider's MachineCapacities in every namespace and creates new ones. The - form asks only for a name, a class, and whether to offer the capacity for - allocation (off by default). It goes in the class's namespace and capacity - pool, with a device reference named after the record (nothing checks that a - Device of that name exists) and the standalone fixtures' cleaning policy. The device - reference can't be changed later. Hardware and conditions stay empty until - Fleet's discovery reports them. + provider's MachineCapacities in every namespace. A verified host session can + register an existing `default` Device under an independently authored name. + Selection retains the exact Device UID/resourceVersion; the named reference + is immutable. Registration is Disabled/Retain with cleaning explicitly + unconfigured, without class assignment, allocation, preparation or positive + readiness. The server enforces permissions, physical-alias reservations and + lifetime fences. Unknown completion blocks retries and never deletes capacity + to roll back. See the [registration contract](../../docs/development/inventory-capacity-registration.md). - **Profiles** (`profiles`) lists MachineProfiles and creates new ones. A profile can't be changed after it is created, so there is no edit. - **Classes** (`classes`) lists MachineClasses and creates new ones: the @@ -49,7 +50,8 @@ profiles and classes needs a Bare Metal role with `machinecapacities.create`, such as `metal.datumapis.com-provider`. The Inventory tab needs list access to the six physical kinds and observational Sites in `fleet.datumapis.com`, which `fleet.datumapis.com-inventory-viewer` grants; metal roles grant no inventory -access. Errors show inside the create dialog, +access. Capacity registration additionally requires current named Device read +permission. Fixture builds cannot register capacity. Errors show inside the create dialog, because staff-portal does not share its toast module with plugins. This started as the MVP from [#17](https://github.com/datum-cloud/fleet/issues/17). diff --git a/ui/provider/src/components/capacity-table.tsx b/ui/provider/src/components/capacity-table.tsx index 6aefcdca..5e073a02 100644 --- a/ui/provider/src/components/capacity-table.tsx +++ b/ui/provider/src/components/capacity-table.tsx @@ -94,7 +94,7 @@ export function CapacityTable({ header: '', cell: ({ row }) => (
        - onDelete(row.original)} /> + {row.original.registrationProtected ? Retained registration : onDelete(row.original)} />}
        ), }, diff --git a/ui/provider/src/components/create-capacity-dialog.tsx b/ui/provider/src/components/create-capacity-dialog.tsx index c37e5835..df50a62b 100644 --- a/ui/provider/src/components/create-capacity-dialog.tsx +++ b/ui/provider/src/components/create-capacity-dialog.tsx @@ -1,164 +1,76 @@ -import { CAPACITY_POOL_LABEL, type MachineClass, type RawMachineCapacity } from '../types'; -import { useCreateMachineCapacity, useMachineClasses } from '../lib/api'; -import { Alert, AlertDescription } from '@datum-cloud/datum-ui/alert'; import { Button } from '@datum-cloud/datum-ui/button'; -import { Form } from '@datum-cloud/datum-ui/form'; -import { ConformAdapter } from '@datum-cloud/datum-ui/form/adapters/conform'; -import { Icon } from '@datum-cloud/datum-ui/icons'; -import { Text } from '@datum-cloud/datum-ui/typography'; -import { PlusIcon } from 'lucide-react'; -import { useState } from 'react'; -import { z } from 'zod'; +import { Input } from '@datum-cloud/datum-ui/input'; +import { Label } from '@datum-cloud/datum-ui/label'; +import { useQuery } from '@tanstack/react-query'; +import { useContext, useLayoutEffect, useRef, useState, type FormEvent } from 'react'; +import type { Device } from '../../../shared/fleet-api'; +import { ineligibleReason, registerCapacity, registrationDevices, registrationPermission, RegistrationUnknown } from '../lib/capacity-registration'; +import { InventoryOperationContext, InventoryOperationReadyContext, InventoryOperationScope, type InventoryOperation } from '../lib/inventory-operation'; +import { useInventoryRead } from '../lib/inventory-read'; +import { confirmInventoryDismissal, InventoryDraftGuard, InventoryForm, InventoryFormSurface } from './inventory-form-surface'; +import { InventorySessionBoundary } from './inventory-session-boundary'; -const NAME_PATTERN = /^[a-z0-9]([-a-z0-9]*[a-z0-9])?$/; -const NAME_MESSAGE = - 'Lowercase letters, numbers, and hyphens only. Must start and end with a letter or number.'; - -const resourceName = (label: string) => - z.string({ error: `${label} is required.` }).max(63, 'At most 63 characters.').regex(NAME_PATTERN, NAME_MESSAGE); - -// A class that draws from a namespace and capacity pool; only these can -// place new capacity where the class will find it. -export type CapacityTarget = MachineClass & { capacityNamespace: string; capacityPool: string }; - -export function capacityTargets(classes: MachineClass[] | undefined): CapacityTarget[] { - return (classes ?? []).filter( - (c): c is CapacityTarget => !c.source && !!c.capacityNamespace && !!c.capacityPool - ); +export function CreateCapacityDialog({ onRegistered }: { onRegistered?: () => void }) { + return Checking registration session…

        } unavailable={() =>

        Registration unavailable: a verified staff session is required.

        }>
        ; } -// The form fills in the rest of the spec. Fleet has no Device inventory yet, -// so the device reference is named after the capacity; it can't be changed -// later. The cleaning policy is the name Fleet's standalone fixtures use; -// nothing defines cleaning policies yet. Allocation stays off unless asked. -export const SYNTHETIC_CLEANING_POLICY = 'synthetic-tenant-reuse-v1'; - -export const capacityFormSchema = z.object({ - name: resourceName('Name'), - machineClass: z.string({ error: 'Choose a class.' }).min(1, 'Choose a class.'), - allocationEnabled: z.boolean().optional(), -}); - -export type CapacityFormValues = z.infer; - -export function toRawCapacity(values: CapacityFormValues, target: CapacityTarget): RawMachineCapacity { - return { - metadata: { - name: values.name, - namespace: target.capacityNamespace, - labels: { [CAPACITY_POOL_LABEL]: target.capacityPool }, - }, - spec: { - deviceRef: { name: values.name }, - allocationPolicy: values.allocationEnabled ? 'Enabled' : 'Disabled', - cleaningPolicyRef: { name: SYNTHETIC_CLEANING_POLICY }, - reclaimPolicy: 'Retain', - }, - }; -} - -function Placement({ targets }: { targets: CapacityTarget[] }) { - const selected = Form.useWatch('machineClass'); - const target = targets.find((t) => t.name === selected); - if (!target) return null; - return ( - - Created in namespace{' '} - - {target.capacityNamespace} - {' '} - with capacity pool{' '} - - {target.capacityPool} - - . - - ); -} - -// Errors render in the dialog because staff-portal does not share its toast -// module with plugins. -export function CreateCapacityDialog() { +export function CapacityRegistrationForm({ onRegistered }: { onRegistered?: () => void }) { + const parent = useContext(InventoryOperationContext); + const ready = useContext(InventoryOperationReadyContext); + const [scope] = useState(() => new InventoryOperationScope()); + const operation = useRef(undefined); + const operationID = useRef(''); const [open, setOpen] = useState(false); - const mutation = useCreateMachineCapacity(); - const { data: classes } = useMachineClasses(); - const targets = capacityTargets(classes); - - const setOpenAndReset = (next: boolean) => { - if (next) mutation.reset(); - setOpen(next); + const [name, setName] = useState(''); + const [selected, setSelected] = useState(); + const [pending, setPending] = useState(false); + const [unknown, setUnknown] = useState(false); + const [message, setMessage] = useState(''); + const readPermission = useInventoryRead(registrationPermission); + const permission = useQuery({ queryKey: ['capacity-registration-permission'], queryFn: readPermission, retry: false, refetchOnWindowFocus: false }); + const readDevices = useInventoryRead(registrationDevices); + const devices = useQuery({ queryKey: ['capacity-registration-devices'], queryFn: readDevices, enabled: open && permission.data === true, retry: false, refetchOnWindowFocus: false }); + useLayoutEffect(() => { scope.startLifecycle(); return () => scope.invalidate(); }, [scope]); + const available = ready && !!parent && permission.data === true; + const dismiss = () => { + if (confirmInventoryDismissal(!!name || !!selected, pending, unknown)) { scope.invalidate(); setOpen(false); } }; - - const handleSubmit = (values: CapacityFormValues) => { - const target = targets.find((t) => t.name === values.machineClass); - if (!target) return; - mutation.mutate(toRawCapacity(values, target), { onSuccess: () => setOpen(false) }); - }; - - return ( - <> - - - -
        - {mutation.error && ( - - {mutation.error.message} - - )} - - - - - {targets.length > 0 ? ( - - {targets.map((t) => ( - - {t.name} - - ))} - - ) : ( - - No classes with a capacity pool yet. Create one on the Classes tab first. - - )} - - - - - -
        -
        -
        - - ); + async function submit(event: FormEvent) { + event.preventDefault(); + if (!available || pending || unknown || !selected || !operation.current) return; + setPending(true); setMessage(''); + try { + await registerCapacity(name, selected, operationID.current, operation.current); + setMessage(`Registered ${name} as Disabled/Retain. Cleaning is unconfigured; readiness and availability remain unknown.`); + setName(''); setSelected(undefined); setOpen(false); onRegistered?.(); + } catch (error) { + setUnknown(error instanceof RegistrationUnknown); + setMessage(error instanceof Error ? error.message : 'Registration unavailable.'); + } finally { setPending(false); } + } + const status = <>{message &&

        {message}

        }{!available &&

        {permission.isPending ? 'Checking registration permission…' : permission.error ? 'Registration unavailable: authorization could not be checked.' : 'Registration denied or unavailable for this session. Synthetic previews cannot register capacity.'}

        }; + return <> + + { + scope.startLifecycle(); operation.current = scope.begin(parent); operationID.current = crypto.randomUUID(); + setName(''); setSelected(undefined); setUnknown(false); setMessage(''); setOpen(true); + }}>Register capacity}> + void submit(event)} message={message}> +

        Choose a Device in default. This creates an inert Disabled/Retain record, not usable capacity. Cleaning remains explicitly unconfigured. No hardware is prepared or changed.

        +
        + + + {devices.isPending &&

        Loading Devices…

        } + {devices.error &&

        Devices are unavailable or access is denied. Registration is blocked.

        } + {devices.data?.length === 0 &&

        No Devices are available in default.

        } + {selected &&

        The authored Device reference {selected.metadata.name} is immutable. This selection retains its exact incarnation and version; it is never silently refreshed.

        } + +
        + +
        +
        + ; } diff --git a/ui/provider/src/lib/api.ts b/ui/provider/src/lib/api.ts index f199b221..b06ec53e 100644 --- a/ui/provider/src/lib/api.ts +++ b/ui/provider/src/lib/api.ts @@ -97,24 +97,6 @@ export function useMachineCapacities(): UseQueryResult { - if (USE_FIXTURES) return fixtureCapacities.create(capacity); - const namespace = encodeURIComponent(capacity.metadata.namespace ?? ''); - return proxyFetch(PROVIDER_PROJECT, `${METAL_API}/namespaces/${namespace}/machinecapacities`, { - method: 'POST', - body: { apiVersion: 'metal.datumapis.com/v1alpha1', kind: 'MachineCapacity', ...capacity }, - }); -} - -export function useCreateMachineCapacity(): UseMutationResult { - const queryClient = useQueryClient(); - return useMutation({ - mutationFn: createMachineCapacity, - onSuccess: () => - queryClient.invalidateQueries({ queryKey: [PLUGIN_ID, 'machinecapacities', PROVIDER_PROJECT] }), - }); -} - export async function deleteMachineCapacity(capacity: { namespace?: string; name: string }): Promise { if (USE_FIXTURES) return fixtureCapacities.delete(capacity.namespace ?? '', capacity.name); const namespace = encodeURIComponent(capacity.namespace ?? ''); diff --git a/ui/provider/src/lib/capacity-registration.test.ts b/ui/provider/src/lib/capacity-registration.test.ts new file mode 100644 index 00000000..a3713191 --- /dev/null +++ b/ui/provider/src/lib/capacity-registration.test.ts @@ -0,0 +1,63 @@ +import { beforeEach, expect, it, vi } from 'vitest'; +import type { Device } from '../../../shared/fleet-api'; +import { registerCapacity, ineligibleReason, REGISTRATION_DEVICE_UID, REGISTRATION_DEVICE_VERSION, RegistrationUnknown } from './capacity-registration'; +import { InventoryOperationScope } from './inventory-operation'; + +const device: Device = { metadata: { name: 'chosen-hardware', namespace: 'default', uid: 'device-1', resourceVersion: '7' }, spec: { claimRef: { name: 'installation' }, identity: { model: 'test', serial: 'serial-1', systemUUID: '11111111-1111-1111-1111-111111111111' } } }; +const transport = vi.fn(); +beforeEach(() => { + transport.mockReset(); vi.stubGlobal('fetch', transport); + transport.mockImplementation(async (input, init) => { + if (String(input).includes('selfsubjectaccessreviews')) return Response.json({ data: { status: { allowed: true } } }); + if (init?.method === 'POST') { const body = JSON.parse(String(init.body)); return Response.json({ data: { ...body, metadata: { ...body.metadata, uid: 'capacity-1' } } }); } + return Response.json({ data: device }); + }); +}); + +it('uses the exact selected Device, authored name, Disabled/Retain and no synthetic policy', async () => { + const result = await registerCapacity('authored-name', device, 'operation-1', new InventoryOperationScope().begin()); + expect(result.spec).toEqual({ deviceRef: { name: 'chosen-hardware' }, allocationPolicy: 'Disabled', reclaimPolicy: 'Retain', cleaningPolicyRef: { name: '' } }); + expect(result.metadata.annotations).toMatchObject({ [REGISTRATION_DEVICE_UID]: 'device-1', [REGISTRATION_DEVICE_VERSION]: '7' }); + expect(result.status).toBeUndefined(); + const writes = transport.mock.calls.filter(([url, init]) => String(url).includes('machinecapacities?') && init?.method === 'POST'); + expect(writes).toHaveLength(1); + expect(String(writes[0][0])).toContain('/projects/datum-cloud/control-plane/apis/metal.datumapis.com/v1alpha1/namespaces/default/machinecapacities'); +}); + +it.each(['uid', 'resourceVersion'] as const)('rejects stale selected %s without refreshing or dispatching', async field => { + transport.mockImplementation(async input => String(input).includes('selfsubjectaccessreviews') ? Response.json({ data: { status: { allowed: true } } }) : Response.json({ data: { ...device, metadata: { ...device.metadata, [field]: 'changed' } } })); + await expect(registerCapacity('record', device, 'operation', new InventoryOperationScope().begin())).rejects.toThrow('selected Device changed'); + expect(transport.mock.calls.some(([url]) => String(url).includes('machinecapacities?'))).toBe(false); +}); + +it('does not dispatch on permission revocation', async () => { + transport.mockResolvedValue(Response.json({ data: { status: { allowed: false } } })); + await expect(registerCapacity('record', device, 'operation', new InventoryOperationScope().begin())).rejects.toThrow('permission is denied'); + expect(transport).toHaveBeenCalledTimes(1); +}); + +it('fences a session change before dispatch', async () => { + const scope = new InventoryOperationScope(); + transport.mockImplementation(async () => { scope.invalidate(); return Response.json({ data: { status: { allowed: true } } }); }); + await expect(registerCapacity('record', device, 'operation', scope.begin())).rejects.toThrow('No write was dispatched'); + expect(transport).toHaveBeenCalledTimes(1); +}); + +it.each(['network', 'timeout', 'session', 'bad receipt'])('retains an unknown outcome after dispatch: %s', async failure => { + const scope = new InventoryOperationScope(); + transport.mockImplementation(async (input, init) => { + if (String(input).includes('selfsubjectaccessreviews')) return Response.json({ data: { status: { allowed: true } } }); + if (init?.method !== 'POST') return Response.json({ data: device }); + if (failure === 'network') throw new Error('network interrupted'); + if (failure === 'timeout') return Response.json({ error: 'timeout' }, { status: 504 }); + if (failure === 'session') scope.invalidate(); + return Response.json({ data: { metadata: {} } }); + }); + await expect(registerCapacity('record', device, 'operation', scope.begin())).rejects.toBeInstanceOf(RegistrationUnknown); + expect(transport.mock.calls.some(([, init]) => init?.method === 'DELETE')).toBe(false); +}); + +it('rejects partial and unidentified identity and non-default inventory', () => { + expect(ineligibleReason({ ...device, spec: { ...device.spec, identity: { model: 'test', serial: 'only-serial' } } })).toContain('ambiguous'); + expect(ineligibleReason({ ...device, metadata: { ...device.metadata, namespace: 'other' } })).toContain('unavailable'); +}); diff --git a/ui/provider/src/lib/capacity-registration.ts b/ui/provider/src/lib/capacity-registration.ts new file mode 100644 index 00000000..8fbcc619 --- /dev/null +++ b/ui/provider/src/lib/capacity-registration.ts @@ -0,0 +1,61 @@ +import type { Device, List, MachineCapacity } from '../../../shared/fleet-api'; +import { ApiError, PROVIDER_PROJECT, proxyFetch } from './api'; +import type { InventoryOperation } from './inventory-operation'; + +export const REGISTRATION_DEVICE_UID = 'fleet.datumapis.com/registration-device-uid'; +export const REGISTRATION_DEVICE_VERSION = 'fleet.datumapis.com/registration-device-version'; +export const REGISTRATION_OPERATION = 'fleet.datumapis.com/registration-operation'; +const devicesPath = '/apis/fleet.datumapis.com/v1alpha1/namespaces/default/devices'; +const capacitiesPath = '/apis/metal.datumapis.com/v1alpha1/namespaces/default/machinecapacities'; + +export function ineligibleReason(device: Device): string | undefined { + if (device.metadata.namespace !== 'default' || !device.metadata.uid || !device.metadata.resourceVersion || device.metadata.deletionTimestamp) return 'Device incarnation is unavailable or deleting'; + if (device.spec.identity.unidentified || !device.spec.identity.serial?.trim() || !device.spec.identity.systemUUID) return 'Both serial and system UUID are required; partial identity is ambiguous'; + if (['unknown', 'none', 'n/a', 'default string', 'to be filled by o.e.m.'].includes(device.spec.identity.serial.trim().toLowerCase()) || ['00000000-0000-0000-0000-000000000000', 'ffffffff-ffff-ffff-ffff-ffffffffffff'].includes(device.spec.identity.systemUUID)) return 'Placeholder identity is ineligible'; + return undefined; +} + +export async function registrationPermission(): Promise { + if (import.meta.env.VITE_FLEET_FIXTURES === 'true') return false; + const result = await proxyFetch<{ status?: { allowed?: boolean; denied?: boolean; evaluationError?: string } }>(PROVIDER_PROJECT, '/apis/authorization.k8s.io/v1/selfsubjectaccessreviews', { + method: 'POST', body: { apiVersion: 'authorization.k8s.io/v1', kind: 'SelfSubjectAccessReview', spec: { resourceAttributes: { group: 'metal.datumapis.com', version: 'v1alpha1', resource: 'machinecapacities', namespace: 'default', verb: 'create' } } }, + }); + return result.status?.allowed === true && result.status.denied !== true && !result.status.evaluationError; +} + +export async function registrationDevices(): Promise { + if (import.meta.env.VITE_FLEET_FIXTURES === 'true') return []; + const result = await proxyFetch>(PROVIDER_PROJECT, devicesPath); + return result.items ?? []; +} + +export class RegistrationUnknown extends Error { + constructor(name: string, readonly operationID: string, detail: string) { + super(`Registration of ${name} is not confirmed. ${detail} Reservations may be retained. Do not retry under another name or delete capacity to roll back; ask an operator to reconcile operation ${operationID}.`); + } +} + +export async function registerCapacity(name: string, selected: Device, operationID: string, operation: InventoryOperation): Promise { + operation.assertCurrent(); + if (!/^[a-z0-9]([-a-z0-9]*[a-z0-9])?$/.test(name) || name.length > 63 || !operationID) throw new Error('Enter a valid authored capacity name.'); + if (ineligibleReason(selected)) throw new Error(ineligibleReason(selected)); + if (!await registrationPermission()) throw new ApiError(403, 'Capacity registration permission is denied or unavailable.'); + operation.assertCurrent(); + const current = await proxyFetch(PROVIDER_PROJECT, `${devicesPath}/${encodeURIComponent(selected.metadata.name)}`); + operation.assertCurrent(); + if (ineligibleReason(current) || current.metadata.uid !== selected.metadata.uid || current.metadata.resourceVersion !== selected.metadata.resourceVersion) throw new Error('The selected Device changed. Close the form, inspect inventory, and explicitly select it again. No registration was dispatched.'); + const body: MachineCapacity & { apiVersion: string; kind: string } = { + apiVersion: 'metal.datumapis.com/v1alpha1', kind: 'MachineCapacity', + metadata: { name, namespace: 'default', annotations: { [REGISTRATION_DEVICE_UID]: selected.metadata.uid!, [REGISTRATION_DEVICE_VERSION]: selected.metadata.resourceVersion!, [REGISTRATION_OPERATION]: operationID } }, + spec: { deviceRef: { name: selected.metadata.name }, allocationPolicy: 'Disabled', cleaningPolicyRef: { name: '' }, reclaimPolicy: 'Retain' }, + }; + operation.dispatch(); + try { + const result = await proxyFetch(PROVIDER_PROJECT, `${capacitiesPath}?fieldManager=fleet-capacity-registration&fieldValidation=Strict`, { method: 'POST', body }); + operation.assertCurrent(); + if (!result.metadata.uid || result.metadata.name !== name || result.metadata.namespace !== 'default' || result.metadata.annotations?.[REGISTRATION_OPERATION] !== operationID || result.metadata.annotations?.[REGISTRATION_DEVICE_UID] !== selected.metadata.uid || result.metadata.annotations?.[REGISTRATION_DEVICE_VERSION] !== selected.metadata.resourceVersion || result.spec.deviceRef.name !== selected.metadata.name || result.spec.allocationPolicy !== 'Disabled' || result.spec.reclaimPolicy !== 'Retain' || result.spec.cleaningPolicyRef.name !== '') throw new Error('The returned record does not match the exact requested binding.'); + return result; + } catch (error) { + throw new RegistrationUnknown(name, operationID, error instanceof Error ? error.message : 'The API did not return a confirmed result.'); + } +} diff --git a/ui/provider/src/pages/capacity-list.test.tsx b/ui/provider/src/pages/capacity-list.test.tsx index c4ef8031..47151b3a 100644 --- a/ui/provider/src/pages/capacity-list.test.tsx +++ b/ui/provider/src/pages/capacity-list.test.tsx @@ -1,9 +1,8 @@ import CapacityList from './capacity-list'; -import { capacityTargets, toRawCapacity } from '../components/create-capacity-dialog'; import * as api from '../lib/api'; import { ApiError } from '../lib/api'; -import { FIXTURE_CAPACITIES, fixtureClasses } from '../lib/fixtures'; -import { toMachineCapacity, toMachineClass } from '../types'; +import { FIXTURE_CAPACITIES } from '../lib/fixtures'; +import { toMachineCapacity } from '../types'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'; import { MemoryRouter, Route, Routes } from 'react-router'; @@ -11,12 +10,10 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; vi.mock('../lib/api', async () => { const actual = await vi.importActual('../lib/api'); - return { ...actual, useMachineCapacities: vi.fn(), useMachineClasses: vi.fn(), useCreateMachineCapacity: vi.fn(), useDeleteMachineCapacity: vi.fn() }; + return { ...actual, useMachineCapacities: vi.fn(), useDeleteMachineCapacity: vi.fn() }; }); const useCapacitiesMock = vi.mocked(api.useMachineCapacities); -const mutate = vi.fn(); -const CLASSES = fixtureClasses.list().map(toMachineClass); const remove = vi.fn(); @@ -72,16 +69,8 @@ function row(table: HTMLElement, name: string): HTMLElement { beforeEach(() => { useCapacitiesMock.mockReset(); - mutate.mockReset(); remove.mockReset(); mockDelete(api.useDeleteMachineCapacity); - vi.mocked(api.useMachineClasses).mockReturnValue({ data: CLASSES } as never); - vi.mocked(api.useCreateMachineCapacity).mockReturnValue({ - mutate, - reset: vi.fn(), - error: null, - isPending: false, - } as never); }); describe('CapacityList', () => { @@ -141,52 +130,27 @@ describe('CapacityList', () => { expect(within(enrolled).getAllByText('—').length).toBeGreaterThan(0); // nothing observed }); - it('creates capacity in the namespace and pool of the chosen class', async () => { - mockResult({ data: [] }); - renderPage(); - fireEvent.click(screen.getByRole('button', { name: /Create capacity/ })); - const form = await screen.findByTestId('fleet-plugin-create-capacity-form'); - const input = (name: string) => form.querySelector(`[name="${name}"]`) as HTMLInputElement; - fireEvent.change(input('name'), { target: { value: 'central1-baremetal-04' } }); - // Radix renders a hidden native select alongside its combobox. - fireEvent.change(form.querySelector('select') as HTMLSelectElement, { - target: { value: 'standard-metal' }, - }); - expect(await within(form).findByTestId('fleet-plugin-capacity-placement')).toHaveTextContent( - 'Created in namespace fleet-provider with capacity pool central-metal.' - ); - fireEvent.click(screen.getByRole('button', { name: 'Create' })); - - await waitFor(() => expect(mutate).toHaveBeenCalled()); - expect(mutate.mock.calls[0][0]).toEqual({ - metadata: { - name: 'central1-baremetal-04', - namespace: 'fleet-provider', - labels: { 'fleet.datumapis.com/capacity-pool': 'central-metal' }, - }, - spec: { - deviceRef: { name: 'central1-baremetal-04' }, - allocationPolicy: 'Disabled', - cleaningPolicyRef: { name: 'synthetic-tenant-reuse-v1' }, - reclaimPolicy: 'Retain', - }, - }); - }); - - it('asks for a class with a capacity pool when there is none', async () => { - vi.mocked(api.useMachineClasses).mockReturnValue({ data: [] } as never); - mockResult({ data: [] }); + it.each([ + { data: [] }, + { data: FIXTURE_CAPACITIES.map(toMachineCapacity) }, + { isLoading: true }, + { error: new ApiError(403, 'forbidden') }, + { error: new ApiError(503, 'unavailable') }, + ])('does not offer registration without a verified host session: %j', (result) => { + mockResult(result); renderPage(); - fireEvent.click(screen.getByRole('button', { name: /Create capacity/ })); - const form = await screen.findByTestId('fleet-plugin-create-capacity-form'); - expect(within(form).getByText(/No classes with a capacity pool yet/)).toBeInTheDocument(); + expect(screen.getByText('Registration unavailable: a verified staff session is required.')).toBeInTheDocument(); + expect(screen.queryByRole('button', { name: /Create capacity|Register capacity/ })).toBeNull(); + expect(screen.queryByRole('checkbox', { name: /Offer for allocation/ })).toBeNull(); + expect(screen.queryByTestId('fleet-plugin-create-capacity-form')).toBeNull(); + expect(remove).not.toHaveBeenCalled(); }); it('deletes capacity once its name is typed', async () => { mockResult({ data: FIXTURE_CAPACITIES.map(toMachineCapacity) }); renderPage(); const form = await confirmDelete('central1-baremetal-03'); - expect(within(form).getByText(/removed from fleet-provider straight away/)).toBeInTheDocument(); + expect(within(form).getByText(/Deletion in fleet-provider is subject to server lifecycle fences/)).toBeInTheDocument(); await waitFor(() => expect(remove).toHaveBeenCalled()); expect(remove.mock.calls[0][0]).toMatchObject({ name: 'central1-baremetal-03', @@ -202,6 +166,13 @@ describe('CapacityList', () => { expect(remove).not.toHaveBeenCalled(); }); + it('shows registration retention instead of an unsafe rollback action', () => { + mockResult({ data: [{ ...toMachineCapacity(FIXTURE_CAPACITIES[0]), registrationProtected: true }] }); + renderPage(); + expect(screen.getByText('Retained registration')).toBeInTheDocument(); + expect(screen.queryByRole('button', { name: `Delete ${FIXTURE_CAPACITIES[0].metadata.name}` })).toBeNull(); + }); + it('shows a failed delete in the dialog', async () => { mockDelete(api.useDeleteMachineCapacity, { error: new ApiError(403, 'machinecapacities "x" is forbidden') }); mockResult({ data: FIXTURE_CAPACITIES.map(toMachineCapacity) }); @@ -211,28 +182,3 @@ describe('CapacityList', () => { expect(within(form).getByText('machinecapacities "x" is forbidden')).toBeInTheDocument(); }); }); - -describe('capacityTargets', () => { - it('skips published classes and classes without a capacity pool', () => { - const targets = capacityTargets([ - ...CLASSES, - toMachineClass({ metadata: { name: 'no-pool' }, spec: {} }), - toMachineClass({ - metadata: { name: 'published' }, - spec: { source: { project: 'provider', name: 'standard-metal' } }, - }), - ]); - expect(targets.map((t) => t.name)).toEqual(['standard-metal']); - }); -}); - -describe('toRawCapacity', () => { - it('enables allocation only when asked', () => { - const [target] = capacityTargets(CLASSES); - const values = { name: 'm', machineClass: 'standard-metal' }; - expect(toRawCapacity(values, target).spec.allocationPolicy).toBe('Disabled'); - expect(toRawCapacity({ ...values, allocationEnabled: true }, target).spec.allocationPolicy).toBe( - 'Enabled' - ); - }); -}); diff --git a/ui/provider/src/pages/capacity-list.tsx b/ui/provider/src/pages/capacity-list.tsx index f4441e25..06672c8b 100644 --- a/ui/provider/src/pages/capacity-list.tsx +++ b/ui/provider/src/pages/capacity-list.tsx @@ -22,7 +22,7 @@ export default function CapacityList() { ); return ( - }> + void refetch()} />}> {isLoading && } {!isLoading && error && ( @@ -50,7 +50,7 @@ export default function CapacityList() { diff --git a/ui/provider/src/pages/capacity-registration.test.tsx b/ui/provider/src/pages/capacity-registration.test.tsx new file mode 100644 index 00000000..10769010 --- /dev/null +++ b/ui/provider/src/pages/capacity-registration.test.tsx @@ -0,0 +1,58 @@ +import { beforeEach, expect, it, vi } from 'vitest'; +import { fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { createMemoryRouter, Outlet, RouterProvider } from 'react-router'; +import { CreateCapacityDialog } from '../components/create-capacity-dialog'; +import type { Device } from '../../../shared/fleet-api'; + +const device: Device = { metadata: { name: 'server-a', namespace: 'default', uid: 'device-1', resourceVersion: '1' }, spec: { claimRef: { name: 'plan' }, identity: { model: 'test', serial: 'serial', systemUUID: '11111111-1111-1111-1111-111111111111' } } }; +const fetcher = vi.fn(); +beforeEach(() => { + fetcher.mockReset(); vi.stubGlobal('fetch', fetcher); + fetcher.mockImplementation(async (input, init) => { + if (String(input).includes('selfsubjectaccessreviews')) return Response.json({ data: { status: { allowed: true } } }); + if (init?.method === 'POST') { const body = JSON.parse(String(init.body)); return Response.json({ data: { ...body, metadata: { ...body.metadata, uid: 'capacity-1' } } }); } + return Response.json({ data: String(input).endsWith('/devices') ? { items: [device] } : device }); + }); +}); + +async function openForm() { + const router = createMemoryRouter([{ id: 'layouts/milo.layout', path: '/', loader: () => ({ user: { metadata: { uid: 'operator-1' } } }), element: , children: [{ index: true, element: }] }]); + render(); + const trigger = await screen.findByRole('button', { name: 'Register capacity' }); + await waitFor(() => expect(trigger).toBeEnabled()); fireEvent.click(trigger); + await screen.findByRole('option', { name: 'server-a' }); + fireEvent.change(screen.getByLabelText('Capacity name'), { target: { value: 'authored-record' } }); + fireEvent.change(screen.getByLabelText('Device'), { target: { value: 'device-1' } }); + return router; +} + +it('registers the selected incarnation through a real host session fence', async () => { + await openForm(); + fireEvent.click(screen.getByRole('button', { name: 'Register Disabled capacity' })); + expect(await screen.findByText(/Registered authored-record as Disabled\/Retain/)).toBeInTheDocument(); + expect(fetcher.mock.calls.filter(([url, init]) => String(url).includes('machinecapacities?') && init?.method === 'POST')).toHaveLength(1); + expect(screen.queryByRole('checkbox')).toBeNull(); +}); + +it('visible blur/focus is a no-op for the selected baseline and draft', async () => { + await openForm(); + const before = fetcher.mock.calls.length; + fireEvent(window, new Event('blur')); fireEvent(window, new Event('focus')); + expect(screen.getByLabelText('Capacity name')).toHaveValue('authored-record'); + expect(screen.getByLabelText('Device')).toHaveValue('device-1'); + expect(fetcher.mock.calls).toHaveLength(before); +}); + +it('keeps unknown completion in the form and prevents retry and rollback', async () => { + await openForm(); + fetcher.mockImplementation(async (input, init) => { + if (String(input).includes('selfsubjectaccessreviews')) return Response.json({ data: { status: { allowed: true } } }); + if (init?.method === 'POST') throw new Error('network lost'); + return Response.json({ data: device }); + }); + fireEvent.click(screen.getByRole('button', { name: 'Register Disabled capacity' })); + expect(await screen.findByText(/Reservations may be retained/)).toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Register Disabled capacity' })).toBeDisabled(); + expect(screen.getByLabelText('Capacity name')).toHaveValue('authored-record'); + expect(fetcher.mock.calls.some(([, init]) => init?.method === 'DELETE')).toBe(false); +}); diff --git a/ui/provider/src/types.ts b/ui/provider/src/types.ts index c148cf7f..3673379d 100644 --- a/ui/provider/src/types.ts +++ b/ui/provider/src/types.ts @@ -26,6 +26,7 @@ export interface ConditionSummary { export interface MachineCapacity { name: string; + registrationProtected?: boolean; namespace?: string; pool?: string; allocationPolicy: string; @@ -54,6 +55,7 @@ export function toMachineCapacity(raw: RawMachineCapacity): MachineCapacity { const hw = raw.status?.hardware; return { name: raw.metadata.name, + ...(raw.metadata.annotations?.['fleet.datumapis.com/registration-operation'] && { registrationProtected: true }), namespace: raw.metadata.namespace, pool: raw.metadata.labels?.[CAPACITY_POOL_LABEL], allocationPolicy: raw.spec.allocationPolicy ?? 'Disabled', diff --git a/ui/shared/fleet-api.ts b/ui/shared/fleet-api.ts index 3c0cb15d..7baf6b96 100644 --- a/ui/shared/fleet-api.ts +++ b/ui/shared/fleet-api.ts @@ -143,7 +143,7 @@ export type AllocationPolicy = 'Enabled' | 'Disabled'; export interface MachineCapacity { metadata: ObjectMeta; spec: { - /** Immutable. Names the physical Device; nothing resolves it yet. */ + /** Immutable authored name. Registration retains incarnation evidence privately. */ deviceRef: LocalReference; /** Defaults to Disabled. */ allocationPolicy: AllocationPolicy; From ee29fa709a9fc7474408754b445d2e68aec2054c Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sun, 22 Nov 2026 12:14:34 -0600 Subject: [PATCH 066/518] fix(registration): isolate outages and preserve unchanged devices --- config/README.md | 8 +- .../registration-admission/webhook.yaml | 41 +++ .../inventory-capacity-registration.md | 114 +++++++- go.mod | 13 + go.sum | 6 + internal/registration/admission.go | 26 ++ .../admission_regression_envtest_test.go | 273 ++++++++++++++++++ .../registration/admission_regression_test.go | 75 +++++ internal/registration/envtest_test.go | 12 +- internal/registration/fence.go | 72 ++--- internal/registration/fence_test.go | 61 +++- internal/registration/project_context_test.go | 71 +++++ internal/registration/runtime.go | 2 +- .../testdata/review_adversarial_test.go.txt | 172 +++++++++++ 14 files changed, 887 insertions(+), 59 deletions(-) create mode 100644 internal/registration/admission_regression_envtest_test.go create mode 100644 internal/registration/admission_regression_test.go create mode 100644 internal/registration/project_context_test.go create mode 100644 internal/registration/testdata/review_adversarial_test.go.txt diff --git a/config/README.md b/config/README.md index 7e01a159..1fd166fa 100644 --- a/config/README.md +++ b/config/README.md @@ -33,8 +33,12 @@ The separate `fleet-registration` Deployment serves inert inventory-backed capacity admission only. Its TLS trust, read/SAR credentials, webhook serving CA and one-time private ledger bootstrap are environment-owned. Read the [registration rollout contract](../docs/development/inventory-capacity-registration.md#production-packaging-and-rollout) -before applying either root: an unavailable or incompletely configured authority -blocks writes, and the ledger must never be reset by GitOps. This does not enable +before applying either root: an unavailable authority blocks capacity writes +globally, and fences Device writes and protected lifetime deletions in provider +or ambiguous inventory contexts. Admission-time trusted-context conditions keep +proven unrelated Project inventory independent of webhook availability. All four webhook +entries require the same serving CA and endpoint; their scope must match the +private ledger, which must never be reset by GitOps. This does not enable production allocation or provisioning. `config/components/service-catalog-staging` is a Kustomize component with diff --git a/config/components/registration-admission/webhook.yaml b/config/components/registration-admission/webhook.yaml index 840037b8..25069d84 100644 --- a/config/components/registration-admission/webhook.yaml +++ b/config/components/registration-admission/webhook.yaml @@ -17,16 +17,57 @@ webhooks: operations: [CREATE, UPDATE, DELETE] resources: [machinecapacities, machinecapacities/status] scope: Namespaced + - name: inventory.registration.fleet.datumapis.com + admissionReviewVersions: [v1] + failurePolicy: Fail + matchPolicy: Equivalent + sideEffects: NoneOnDryRun + timeoutSeconds: 20 + clientConfig: + url: https://fleet-registration.fleet-system.svc:9443/validate-registration + matchConditions: + - name: provider-project-context + expression: >- + !(has(request.userInfo.extra) && "iam.miloapis.com/parent-type" in request.userInfo.extra && request.userInfo.extra["iam.miloapis.com/parent-type"] == ['Project'] && "iam.miloapis.com/parent-api-group" in request.userInfo.extra && request.userInfo.extra["iam.miloapis.com/parent-api-group"] == ['resourcemanager.miloapis.com'] && "iam.miloapis.com/parent-name" in request.userInfo.extra && size(request.userInfo.extra["iam.miloapis.com/parent-name"]) == 1 && request.userInfo.extra["iam.miloapis.com/parent-name"][0] != '') || request.userInfo.extra["iam.miloapis.com/parent-name"][0] in ["datum-cloud"] + rules: - apiGroups: [fleet.datumapis.com] apiVersions: [v1alpha1] operations: [CREATE, UPDATE, DELETE] resources: [devices, devices/status] scope: Namespaced + - name: namespace.registration.fleet.datumapis.com + admissionReviewVersions: [v1] + failurePolicy: Fail + matchPolicy: Equivalent + sideEffects: NoneOnDryRun + timeoutSeconds: 20 + clientConfig: + url: https://fleet-registration.fleet-system.svc:9443/validate-registration + matchConditions: + - name: provider-project-context + expression: >- + !(has(request.userInfo.extra) && "iam.miloapis.com/parent-type" in request.userInfo.extra && request.userInfo.extra["iam.miloapis.com/parent-type"] == ['Project'] && "iam.miloapis.com/parent-api-group" in request.userInfo.extra && request.userInfo.extra["iam.miloapis.com/parent-api-group"] == ['resourcemanager.miloapis.com'] && "iam.miloapis.com/parent-name" in request.userInfo.extra && size(request.userInfo.extra["iam.miloapis.com/parent-name"]) == 1 && request.userInfo.extra["iam.miloapis.com/parent-name"][0] != '') || request.userInfo.extra["iam.miloapis.com/parent-name"][0] in ["datum-cloud"] + - name: inventory-namespace + expression: "!has(request.name) || request.name == '' || request.name == 'default'" + rules: - apiGroups: [''] apiVersions: [v1] operations: [DELETE] resources: [namespaces] scope: Cluster + - name: project.registration.fleet.datumapis.com + admissionReviewVersions: [v1] + failurePolicy: Fail + matchPolicy: Equivalent + sideEffects: NoneOnDryRun + timeoutSeconds: 20 + clientConfig: + url: https://fleet-registration.fleet-system.svc:9443/validate-registration + matchConditions: + - name: provider-project-name + expression: >- + !has(request.name) || request.name == '' || request.name in ["datum-cloud"] + rules: - apiGroups: [resourcemanager.miloapis.com] apiVersions: [v1alpha1] operations: [DELETE] diff --git a/docs/development/inventory-capacity-registration.md b/docs/development/inventory-capacity-registration.md index 5dc5d222..2def3da5 100644 --- a/docs/development/inventory-capacity-registration.md +++ b/docs/development/inventory-capacity-registration.md @@ -62,8 +62,11 @@ The webhook accepts only mutually authenticated TLS from a dedicated API-server client CA. Do not use a broad tenant/client CA: an AdmissionReview received from an untrusted client is not evidence of an authenticated actor. The server also checks the installed root webhook configuration at startup and before admission: -required write rules, explicit serving CA, Fail policy and no selectors or match -conditions that allow a caller to skip the fence. +the exact write rules, explicit serving CA, Fail policy, common authority +endpoint, and the restricted match conditions described below. Label selectors, +missing fences, expanded rules, and conditions differing from the configured +provider scope are rejected. Scope changes require an operator-coordinated +manifest and ledger migration, not caller-selected labels or annotations. ## Physical identity and bounded deduplication @@ -120,12 +123,25 @@ the create. A failed CAS response may itself have committed: it is not released. Device creation also reserves its known aliases before admission completes. Device deletion retains a permanent UID tombstone before admission completes. Both use the same ledger CAS, closing the registration-versus-pending-create or -delete race. Device updates retain their old resourceVersion before admission -completes. Registration rejects a selected version with such an update fence; +delete race. Potentially changing Device updates retain their old resourceVersion +before admission completes. Registration rejects a selected version with such an update fence; only an explicitly selected newer persisted version can pass it. This serializes pending metadata/spec updates with registration without silently refreshing the -selection. An update whose completion is unknown can leave its old version -ineligible even if storage made no change. Failed Device creates can likewise retain an alias reservation. +selection. The sole exception is a provably unchanged update: the complete old +and new admission JSON objects are equal, including metadata, managed fields, +status and any fields unknown to Fleet's typed Device. JSON key order and +whitespace are immaterial; numbers are compared without floating-point rounding. +An unchanged Kubernetes update can keep its existing resourceVersion, and must +not permanently fence that still-current version. This exception adds no new +reservation and **never removes an existing pending-update fence**. It does not +infer success from a later read, refresh a selected version, or relax identity +and registered-spec checks. Any differing field still takes the conservative +fencing path. An uncertain potentially changing update can therefore leave its +old version ineligible even if storage ultimately made no change. Failed Device +creates can likewise retain an alias reservation. +The fix does not erase fences retained by older builds: those cannot be safely +distinguished from unfinished real updates. Recovery still requires a genuine +persisted change and explicit new selection, not automatic ledger cleanup. The selected Device's own successful creation reservation is not a conflict. Identity/provider-alias changes are forbidden; registered Device specs are frozen, and its deletion and same-name replacement are forbidden. The default @@ -151,15 +167,48 @@ fences or restore arbitrary storage remain outside the guarantee. ## Production packaging and rollout - `config/milo` includes the mandatory Fail-closed registration webhook on the - **actual project resource path**, not just a manager-side helper. It matches - capacity create/update/delete/status, Device create/update/delete/status, - namespace deletion, and root Project deletion. No object-label opt-in exists. + **actual project resource path**, not just a manager-side helper. Four separate + admission entries use the same endpoint. Capacity create/update/delete/status + remains globally fenced. Device create/update/delete/status excludes only + proven unrelated Project contexts (in **all namespaces**, because alias scans + cover all of them). Namespace deletion matches only `default` in protected or + ambiguous contexts. Project deletion matches only exact configured provider Project + names, including root requests without parent extras. Unnamed collection + deletion cannot prove exclusion of protected lifetimes and is explicitly + denied (including when transport is healthy); delete unrelated lifetimes by + exact name instead. No object-label opt-in or opt-out exists. - `config/overlays/management-plane` includes a separate two-replica registration Deployment, TLS Service, narrowly scoped host RBAC, and private retention policies. It does not enable production lifecycle handlers. - The webhook consumes parent context from Milo's standard admission extras. - The repository-pinned Milo module enables validating admission by default and - documents these extras in its cluster-aware webhook implementation. + The API server evaluates the inventory/lifetime CEL match conditions **before + webhook transport**. An unreachable service or incomplete certificate rollout + therefore cannot block unrelated consumers' Device writes, other namespaces, + or unrelated Project deletions through these entries. In-scope writes remain + Fail-closed during transport failure; capacity writes remain globally blocked. + Handler-side exemptions alone are not an outage-isolation boundary. +- These conditions rely on **server-established routing context**, not arbitrary + identity-provider claims. In pinned Milo `v0.36.9`, + `ProjectRouterWithRequestInfo` establishes the project from the routed path; + `ProjectContextAuthorizationDecorator` overwrites all three parent extras + after authentication/impersonation and before authorization/admission + (`cmd/milo/apiserver/config.go`). The pinned filter regression verifies that + conflicting caller extras are overwritten while actor identity is preserved. + Only a singleton `Project` / `resourcemanager.miloapis.com` / nonempty name + outside the protected list proves that inventory is unrelated and skips the + webhook. Missing, malformed, root, Organization and User inventory contexts + remain fail-closed. This conservative fallback matters: pinned Milo's later + Organization/User decorators can obscure the Project extras for nested paths; + a non-Project context must not be mistaken for proof of unrelated storage. + Regression tests exercise those actual pinned decorators and the resulting + admission matching. Root Project deletion still uses only exact protected + names; other namespace names remain outside the namespace fence. + This scope is **not safe on a server that lets caller-supplied extras replace + its actual routing context**, or exposes an alternate provider-storage path + appearing as a different valid Project. Confirm these properties on the + deployed Milo path before enabling use. Unscoped/root Device writes are not + supported by this pilot; that is an explicit fail-closed limit, not universal + outage isolation for every possible inventory route. - Legacy capacity writes in configured production scope fail closed; legacy records remain readable and unchanged. Outside configured provider scope, ordinary inventory writes are unaffected, but new capacity writes are denied. @@ -183,8 +232,9 @@ real credentials or certificates are supplied by this repository: 2. Supply `fleet-registration-tls` with `tls.crt`, `tls.key`, and a dedicated `client-ca.crt`. Configure Milo's admission webhook client kubeconfig with an API-server client certificate signed by that CA. Patch the webhook URL for - actual cross-cluster reachability and set `clientConfig.caBundle` to the - serving CA. No empty or guessed trust defaults are accepted. + actual cross-cluster reachability and set every entry's + `clientConfig.caBundle` to the serving CA. All four entries must have the same + client configuration. No empty or guessed trust defaults are accepted. 3. Install the host retention policies. Bootstrap the ledger **once**, using create, never apply/upsert, with environment-matching authority and sorted projects. Its initial JSON has `authority`, `projects`, `entries: []` and @@ -194,7 +244,13 @@ real credentials or certificates are supplied by this repository: 4. Quiesce provider inventory/capacity writes while installing the root webhook and service. Validate the complete provider scope and legacy inventory before reopening writes. Unavailable TLS, credentials, ledger or service leave - creates blocked. Readiness is process reachability, not asset eligibility. + in-scope writes blocked. The API server must support webhook CEL match + conditions; preserve the packaged conditions, including the exact sorted + provider-name lists matching `--provider-projects` and the private ledger. + Do not replace them with namespace/object label selectors. A missing or + mismatched fence also prevents registration startup/admission; this does not + authorize unquiesced partial installation or deletion of admission policy. + Readiness is process reachability, not asset eligibility. 5. Before rolling out the UI, verify caller-preserving project routing, named Device read denial, registration denial, direct write/status/delete fences, TLS rejection, and duplicate concurrency in the target environment. This @@ -215,10 +271,38 @@ Tests cover concurrent CAS, serial/UUID/provider aliases and provider projects, stale UID/RV, Device deletion fences, namespace/Project recreation, permission revocation, unknown commit and restart, copied-annotation incarnation conflicts, real API-assigned UID binding, direct mutation fences and no public effects. +Regression coverage also includes real successful unchanged updates retaining +their RV followed by `Recorded` registration, genuine-edit/stale-selection +controls, preservation of pending real-update fences, and transport-outage +isolation for Device writes and namespace/Project deletion. The original reviewer +reproduction is retained byte-for-byte in +`internal/registration/testdata/review_adversarial_test.go.txt`; it is evidence, +not an executable regression because it asserts the former outage failure and +assumes the no-op registration failed before its same-asset control. Derived +regressions use separate assets and assert the corrected behavior. Envtest exercises the production authorization function against real SARs, the packaged validating webhook, and the host retention policies against a -disposable API server. TLS tests reject unauthenticated webhook transport. It is not a live Milo +disposable API server. The outage regression uses a minimal Project CRD solely +to exercise root deletion admission and disables envtest's built-in +NamespaceLifecycle plugin so its independent ban on deleting `default` cannot +mask the webhook test. It uses dry-run deletion for shared `default`, and actual +deletion for unrelated namespaces/Projects. This does not alter production +admission plugins. The trust-boundary test imports the pinned Milo routing +filters (their test-build transitive dependencies are now recorded in `go.mod`). +TLS tests reject unauthenticated webhook transport. It is not a live Milo deployment or independent security review. Frontend tests use real session components and mocked transport. Run the existing Go/envtest, race, vet, provider/consumer test/typecheck/build, manifest-isolation and documentation checks described in the [development guide](README.md#build-test-and-run). + +### Review-fix validation, November 22, 2026 + +- Full `go test -race ./...` with Kubernetes 1.37.0 envtest assets, `go vet ./...`, + and `go build ./cmd/...` pass locally. +- Provider tests: 693 pass; consumer tests: 44 pass. Both typechecks and builds + pass. One initial provider timing failure under concurrent validation load + passed on a full rerun without modifying UI code or reviewer tests. +- Production and synthetic manifest renders, overlay isolation tests, + standalone/synthetic render checks, documentation links and whitespace pass. +- These are local checks, not live Milo acceptance or independent re-review. + No deployment, merge, live resource mutation, or ledger migration was performed. diff --git a/go.mod b/go.mod index 7c6a7425..e7205964 100644 --- a/go.mod +++ b/go.mod @@ -19,17 +19,28 @@ require ( require ( cel.dev/expr v0.25.2 // indirect + github.com/NYTimes/gziphandler v1.1.1 // indirect github.com/antlr4-go/antlr/v4 v4.13.1 // indirect github.com/blang/semver/v4 v4.0.0 // indirect github.com/cenkalti/backoff/v5 v5.0.3 // indirect + github.com/coreos/go-semver v0.3.1 // indirect + github.com/coreos/go-systemd/v22 v22.7.0 // indirect github.com/felixge/httpsnoop v1.1.0 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/go-openapi/swag/pools v0.27.1 // indirect + github.com/golang/protobuf v1.5.4 // indirect github.com/google/cel-go v0.30.0 // indirect + github.com/grpc-ecosystem/go-grpc-middleware/providers/prometheus v1.1.0 // indirect + github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.3.3 // indirect github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect + github.com/kylelemons/godebug v1.1.0 // indirect github.com/spf13/cobra v1.10.2 // indirect + go.etcd.io/etcd/api/v3 v3.7.0 // indirect + go.etcd.io/etcd/client/pkg/v3 v3.7.0 // indirect + go.etcd.io/etcd/client/v3 v3.7.0 // indirect go.opentelemetry.io/auto/sdk v1.2.1 // indirect + go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.68.0 // indirect go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0 // indirect go.opentelemetry.io/otel v1.45.0 // indirect go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.45.0 // indirect @@ -38,11 +49,13 @@ require ( go.opentelemetry.io/otel/sdk v1.45.0 // indirect go.opentelemetry.io/otel/trace v1.45.0 // indirect go.opentelemetry.io/proto/otlp v1.11.0 // indirect + golang.org/x/crypto v0.57.0 // indirect golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f // indirect google.golang.org/genproto/googleapis/api v0.0.0-20260803160001-6ac0973c030d // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20260803160001-6ac0973c030d // indirect google.golang.org/grpc v1.83.2 // indirect k8s.io/component-base v0.37.1 // indirect + k8s.io/streaming v0.37.1 // indirect sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.36.0 // indirect ) diff --git a/go.sum b/go.sum index 7bf58041..aac2b214 100644 --- a/go.sum +++ b/go.sum @@ -2,6 +2,8 @@ cel.dev/expr v0.25.2 h1:K6j46C81hXtZQfuX60cVWQFBJahKSE2gfRbNuvr5bFs= cel.dev/expr v0.25.2/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4= github.com/Masterminds/semver/v3 v3.5.0 h1:kQceYJfbupGfZOKZQg0kou0DgAKhzDg2NZPAwZ/2OOE= github.com/Masterminds/semver/v3 v3.5.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM= +github.com/NYTimes/gziphandler v1.1.1 h1:ZUDjpQae29j0ryrS0u/B8HZfJBtBQHjqw2rQ2cqUQ3I= +github.com/NYTimes/gziphandler v1.1.1/go.mod h1:n/CVRwUEOgIxrgPvAQhUUr9oeUtvrhMomdKFjzJNB0c= github.com/antlr4-go/antlr/v4 v4.13.1 h1:SqQKkuVZ+zWkMMNkjy5FZe5mr5WURWnlpmOuzYWrPrQ= github.com/antlr4-go/antlr/v4 v4.13.1/go.mod h1:GKmUxMtwp6ZgGwZSva4eWPC5mS6vUAmOABFgjdkM7Nw= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= @@ -196,6 +198,8 @@ go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ= go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ= go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= +golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M= +golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA= golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f h1:W3F4c+6OLc6H2lb//N1q4WpJkhzJCK5J6kUi1NTVXfM= golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f/go.mod h1:J1xhfL/vlindoeF/aINzNzt2Bket5bjo9sdOYzOsU80= golang.org/x/mod v0.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c= @@ -253,6 +257,8 @@ k8s.io/klog/v2 v2.140.0 h1:Tf+J3AH7xnUzZyVVXhTgGhEKnFqye14aadWv7bzXdzc= k8s.io/klog/v2 v2.140.0/go.mod h1:o+/RWfJ6PwpnFn7OyAG3QnO47BFsymfEfrz6XyYSSp0= k8s.io/kube-openapi v0.0.0-20260721132016-d427ff9ee9ad h1:oXImqH8mQNk7PmvzKhmN3ddJoY6OnyM225MXwGHPm0A= k8s.io/kube-openapi v0.0.0-20260721132016-d427ff9ee9ad/go.mod h1:0/mqHCVhlumdJ3BhCfnjSZQE037nAhNodh1/hK0T8/I= +k8s.io/streaming v0.37.1 h1:TpzVfQeFuVndn2g9mFqxy1UcUYPwDzqjUmwR/IzJCWc= +k8s.io/streaming v0.37.1/go.mod h1:APlJR26ZWRcVy5bIEj0QRrKUXROtBHPcxl2NT7EAzPU= k8s.io/utils v0.0.0-20260626114624-be93311217bd h1:Ea7fgQ5we8Y9T0OX5o0dAHzQOBRI07D/dEYRaB9ZZEs= k8s.io/utils v0.0.0-20260626114624-be93311217bd/go.mod h1:xDxuJ0whA3d0I4mf/C4ppKHxXynQ+fxnkmQH0vTHnuk= sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.36.0 h1:/YpDJ4vReG7ZmzSpBGxduXgywWkJU9zHubgJG03MT+Y= diff --git a/internal/registration/admission.go b/internal/registration/admission.go index f7b97941..5a146b70 100644 --- a/internal/registration/admission.go +++ b/internal/registration/admission.go @@ -1,12 +1,14 @@ package registration import ( + "bytes" "context" "crypto/sha256" "encoding/hex" "encoding/json" "errors" "fmt" + "io" "reflect" "regexp" "slices" @@ -84,6 +86,9 @@ func projectName(actor authenticationv1.UserInfo) (string, error) { } func (handler *Handler) Handle(ctx context.Context, request admission.Request) admission.Response { + if request.Operation == admissionv1.Delete && request.Name == "" && ((request.Resource.Group == "" && request.Resource.Resource == "namespaces") || (request.Resource.Group == "resourcemanager.miloapis.com" && request.Resource.Resource == "projects")) { + return admission.Denied("lifetime deletion requires an exact resource name; collection deletion cannot prove exclusion of retained lifetimes") + } if request.Resource.Group == "" && request.Resource.Resource == "namespaces" && request.Name != "default" { return admission.Allowed("outside the retained inventory namespace") } @@ -345,6 +350,9 @@ func (handler *Handler) device(ctx context.Context, project Project, request adm if device.UID == "" { return errors.New("Device incarnation unavailable") } + if request.Operation == admissionv1.Update && identicalObjects(request.OldObject.Raw, request.Object.Raw) { + return nil + } fence := DeviceFence{Project: project.Identity.RouteName, UID: device.UID, Deleted: request.Operation == admissionv1.Delete} if request.Operation == admissionv1.Update { fence.Version = old.ResourceVersion @@ -365,3 +373,21 @@ func (handler *Handler) device(ctx context.Context, project Project, request adm ledger.DeviceFences = append(ledger.DeviceFences, fence) return handler.Store.Write(ctx, secret, ledger) } + +func identicalObjects(old, current []byte) bool { + decode := func(raw []byte) (map[string]any, error) { + decoder := json.NewDecoder(bytes.NewReader(raw)) + decoder.UseNumber() + var object map[string]any + if err := decoder.Decode(&object); err != nil { + return nil, err + } + if err := decoder.Decode(new(any)); err != io.EOF { + return nil, errors.New("expected exactly one JSON object") + } + return object, nil + } + before, beforeErr := decode(old) + after, afterErr := decode(current) + return beforeErr == nil && afterErr == nil && before != nil && after != nil && reflect.DeepEqual(before, after) +} diff --git a/internal/registration/admission_regression_envtest_test.go b/internal/registration/admission_regression_envtest_test.go new file mode 100644 index 00000000..b07b2b97 --- /dev/null +++ b/internal/registration/admission_regression_envtest_test.go @@ -0,0 +1,273 @@ +package registration + +import ( + "context" + "encoding/json" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + "time" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + metal "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/controller" + iam "go.miloapis.com/milo/pkg/apis/iam/v1alpha1" + resourcemanager "go.miloapis.com/milo/pkg/apis/resourcemanager/v1alpha1" + admissionregistrationv1 "k8s.io/api/admissionregistration/v1" + authorizationv1 "k8s.io/api/authorization/v1" + corev1 "k8s.io/api/core/v1" + extensions "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/client-go/rest" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/envtest" + "sigs.k8s.io/controller-runtime/pkg/webhook/admission" + "sigs.k8s.io/yaml" +) + +func TestRealNoopRegistrationAndScopedTransportFailure(t *testing.T) { + if os.Getenv("KUBEBUILDER_ASSETS") == "" { + t.Skip("KUBEBUILDER_ASSETS required") + } + ctx := context.Background() + projectCRD := &extensions.CustomResourceDefinition{ObjectMeta: metav1.ObjectMeta{Name: "projects.resourcemanager.miloapis.com"}, Spec: extensions.CustomResourceDefinitionSpec{Group: "resourcemanager.miloapis.com", Names: extensions.CustomResourceDefinitionNames{Plural: "projects", Singular: "project", Kind: "Project", ListKind: "ProjectList"}, Scope: extensions.ClusterScoped, Versions: []extensions.CustomResourceDefinitionVersion{{Name: "v1alpha1", Served: true, Storage: true, Schema: &extensions.CustomResourceValidation{OpenAPIV3Schema: &extensions.JSONSchemaProps{Type: "object"}}}}}} + environment := &envtest.Environment{CRDDirectoryPaths: []string{filepath.Join("..", "..", "config", "base", "crd"), filepath.Join("..", "..", "config", "components", "inventory", "crds")}, CRDs: []*extensions.CustomResourceDefinition{projectCRD}, ErrorIfCRDPathMissing: true} + environment.ControlPlane.GetAPIServer().Configure().Append("disable-admission-plugins", "NamespaceLifecycle") + config, err := environment.Start() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if err := environment.Stop(); err != nil { + t.Error(err) + } + }) + scheme := runtime.NewScheme() + for _, add := range []func(*runtime.Scheme) error{corev1.AddToScheme, inventory.AddToScheme, metal.AddToScheme, resourcemanager.AddToScheme, admissionregistrationv1.AddToScheme, authorizationv1.AddToScheme} { + if err := add(scheme); err != nil { + t.Fatal(err) + } + } + api, err := client.New(config, client.Options{Scheme: scheme}) + if err != nil { + t.Fatal(err) + } + devices := []*inventory.Device{ + {ObjectMeta: metav1.ObjectMeta{Name: "noop-hardware", Namespace: "default"}, Spec: inventory.DeviceSpec{ClaimRef: inventory.LocalReference{Name: "installation"}, Identity: inventory.DeviceIdentity{Model: "test", Serial: "noop-serial", SystemUUID: "11111111-1111-1111-1111-111111111111"}}}, + {ObjectMeta: metav1.ObjectMeta{Name: "real-edit-hardware", Namespace: "default"}, Spec: inventory.DeviceSpec{ClaimRef: inventory.LocalReference{Name: "installation"}, Identity: inventory.DeviceIdentity{Model: "test", Serial: "edit-serial", SystemUUID: "22222222-2222-2222-2222-222222222222"}}}, + } + for _, device := range devices { + if err := api.Create(ctx, device, client.FieldOwner("review")); err != nil { + t.Fatal(err) + } + } + for _, name := range []string{"datum-cloud", "unrelated-consumer"} { + if err := api.Create(ctx, &resourcemanager.Project{ObjectMeta: metav1.ObjectMeta{Name: name}}); err != nil { + t.Fatal(err) + } + } + if err := api.Create(ctx, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "other-namespace"}}); err != nil { + t.Fatal(err) + } + encoded, _ := json.Marshal(Ledger{Authority: "milo", Projects: []string{"datum-cloud"}}) + if err := api.Create(ctx, &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: LedgerName, Namespace: "default"}, Data: map[string][]byte{"ledger.json": encoded}}); err != nil { + t.Fatal(err) + } + handler := &Handler{Store: Store{Client: api, Namespace: "default", Authority: "milo", Projects: []string{"datum-cloud"}}, VerifyFence: func(ctx context.Context) error { return VerifyFence(ctx, api, []string{"datum-cloud"}) }, Resolve: func(context.Context, string) (Project, error) { + return Project{Identity: controller.ProjectIdentity{AuthorityID: "milo", RouteName: "datum-cloud", UID: "project-1"}, Client: api}, nil + }, Authorize: Authorize} + server := httptest.NewTLSServer(&admission.Webhook{Handler: handler}) + t.Cleanup(server.Close) + data, err := os.ReadFile("../../config/components/registration-admission/webhook.yaml") + if err != nil { + t.Fatal(err) + } + var webhooks admissionregistrationv1.ValidatingWebhookConfiguration + if err := yaml.UnmarshalStrict(data, &webhooks); err != nil { + t.Fatal(err) + } + url := server.URL + for index := range webhooks.Webhooks { + webhooks.Webhooks[index].ClientConfig = admissionregistrationv1.WebhookClientConfig{URL: &url, CABundle: pemCertificate(server.Certificate().Raw)} + } + if err := api.Create(ctx, &webhooks); err != nil { + t.Fatal(err) + } + actorConfig := rest.CopyConfig(config) + actorConfig.Impersonate = rest.ImpersonationConfig{UserName: "review-operator", UID: "actor-1", Groups: []string{"system:masters"}, Extra: map[string][]string{iam.ParentKindExtraKey: {"Project"}, iam.ParentAPIGroupExtraKey: {"resourcemanager.miloapis.com"}, iam.ParentNameExtraKey: {"datum-cloud"}}} + actor, err := client.New(actorConfig, client.Options{Scheme: scheme}) + if err != nil { + t.Fatal(err) + } + outsideConfig := rest.CopyConfig(actorConfig) + outsideConfig.Impersonate.Extra = map[string][]string{iam.ParentKindExtraKey: {"Project"}, iam.ParentAPIGroupExtraKey: {"resourcemanager.miloapis.com"}, iam.ParentNameExtraKey: {"unrelated-consumer"}} + outside, err := client.New(outsideConfig, client.Options{Scheme: scheme}) + if err != nil { + t.Fatal(err) + } + deadline := time.Now().Add(10 * time.Second) + for { + err := actor.Update(ctx, devices[0].DeepCopyObject().(*inventory.Device), client.DryRunAll) + if apierrors.IsForbidden(err) { + break + } + if time.Now().After(deadline) { + t.Fatalf("inventory webhook did not engage: %v", err) + } + time.Sleep(30 * time.Millisecond) + } + register := func(t *testing.T, device *inventory.Device, name string) error { + t.Helper() + request := registrationRequest(t, device, name) + var capacity metal.MachineCapacity + if err := json.Unmarshal(request.Object.Raw, &capacity); err != nil { + t.Fatal(err) + } + capacity.UID = "" + return actor.Create(ctx, &capacity) + } + t.Run("unchanged-success-retains-current-RV-and-registers", func(t *testing.T) { + device := devices[0] + unchanged := false + for attempt := 0; attempt < 3; attempt++ { + if err := actor.Get(ctx, client.ObjectKeyFromObject(device), device); err != nil { + t.Fatal(err) + } + before := device.ResourceVersion + if err := actor.Update(ctx, device, client.FieldOwner("review")); err != nil { + t.Fatal(err) + } + if before == device.ResourceVersion { + unchanged = true + break + } + } + if !unchanged { + t.Fatal("API server did not reproduce the unchanged resourceVersion") + } + if err := actor.Get(ctx, client.ObjectKeyFromObject(device), device); err != nil { + t.Fatal(err) + } + if err := register(t, device, "after-noop"); err != nil { + t.Fatalf("unchanged successful update poisoned the current selection: %v", err) + } + }) + t.Run("genuine-edit-requires-explicit-new-selection", func(t *testing.T) { + device := devices[1] + baseline := device.DeepCopyObject().(*inventory.Device) + device.Labels = map[string]string{"review-control": "real-change"} + if err := actor.Update(ctx, device, client.FieldOwner("review")); err != nil { + t.Fatal(err) + } + if baseline.ResourceVersion == device.ResourceVersion { + t.Fatal("real edit did not change the version") + } + if err := register(t, baseline, "stale-selection"); !apierrors.IsForbidden(err) { + t.Fatalf("stale selection not fenced: %v", err) + } + if err := actor.Get(ctx, client.ObjectKeyFromObject(device), device); err != nil { + t.Fatal(err) + } + if err := register(t, device, "after-real-edit"); err != nil { + t.Fatal(err) + } + }) + if err := handler.Recover(ctx); err != nil { + t.Fatal(err) + } + _, ledger, err := handler.Store.Read(ctx) + if err != nil || len(ledger.Entries) != 2 { + t.Fatalf("expected both registrations: %+v %v", ledger, err) + } + for _, entry := range ledger.Entries { + if entry.Outcome != "Recorded" || entry.CapacityUID == "" { + t.Fatalf("registration not recorded: %+v", entry) + } + } + if err := api.DeleteAllOf(ctx, &resourcemanager.Project{}); !apierrors.IsForbidden(err) || !strings.Contains(err.Error(), "collection deletion") { + t.Fatalf("healthy authority did not reject unnamed lifetime deletion: %v", err) + } + server.Close() + for _, test := range []struct { + name string + write func() error + blocked bool + }{ + {"unrelated Device create", func() error { + device := devices[0].DeepCopyObject().(*inventory.Device) + device.Name, device.UID, device.ResourceVersion, device.ManagedFields = "outside-after-outage", "", "", nil + device.Labels = map[string]string{"provider": "datum-cloud"} + return outside.Create(ctx, device) + }, false}, + {"provider Device create without opt-in labels", func() error { + device := devices[0].DeepCopyObject().(*inventory.Device) + device.Name, device.UID, device.ResourceVersion, device.ManagedFields = "inside-after-outage", "", "", nil + device.Namespace = "other-namespace" + device.Labels = map[string]string{"provider": "unrelated-consumer"} + return actor.Create(ctx, device) + }, true}, + {"provider Device update", func() error { return actor.Update(ctx, devices[0], client.DryRunAll) }, true}, + {"provider Device status update", func() error { return actor.Status().Update(ctx, devices[0], client.DryRunAll) }, true}, + {"provider Device delete", func() error { return actor.Delete(ctx, devices[0]) }, true}, + {"unrelated default namespace delete", func() error { + return outside.Delete(ctx, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "default"}}, client.DryRunAll) + }, false}, + {"provider other namespace delete", func() error { + return actor.Delete(ctx, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "other-namespace"}}) + }, false}, + {"provider default namespace delete", func() error { + return actor.Delete(ctx, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "default"}}, client.DryRunAll) + }, true}, + {"unrelated root Project delete", func() error { + return api.Delete(ctx, &resourcemanager.Project{ObjectMeta: metav1.ObjectMeta{Name: "unrelated-consumer"}}) + }, false}, + {"protected root Project delete", func() error { + return api.Delete(ctx, &resourcemanager.Project{ObjectMeta: metav1.ObjectMeta{Name: "datum-cloud"}}) + }, true}, + {"protected root Project collection delete", func() error { return api.DeleteAllOf(ctx, &resourcemanager.Project{}) }, true}, + {"global capacity create", func() error { + return outside.Create(ctx, &metal.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: "outside-capacity", Namespace: "default"}, Spec: metal.MachineCapacitySpec{DeviceRef: metal.LocalReference{Name: devices[0].Name}, AllocationPolicy: "Disabled", ReclaimPolicy: "Retain"}}) + }, true}, + } { + t.Run(test.name, func(t *testing.T) { + err := test.write() + if test.blocked { + if err == nil || !strings.Contains(err.Error(), "failed calling webhook") { + t.Fatalf("expected fail-closed transport error, got %v", err) + } + } else if err != nil { + t.Fatalf("unrelated operation depends on unavailable webhook: %v", err) + } + }) + } + for _, test := range []struct { + name string + extra map[string][]string + }{ + {"missing context", nil}, + {"nested organization context", map[string][]string{iam.ParentKindExtraKey: {"Organization"}, iam.ParentAPIGroupExtraKey: {"resourcemanager.miloapis.com"}, iam.ParentNameExtraKey: {"unrelated-consumer"}}}, + {"nested user context", map[string][]string{iam.ParentKindExtraKey: {"User"}, iam.ParentAPIGroupExtraKey: {"iam.miloapis.com"}, iam.ParentNameExtraKey: {"unrelated-consumer"}}}, + {"ambiguous context", map[string][]string{iam.ParentKindExtraKey: {"Project"}, iam.ParentAPIGroupExtraKey: {"resourcemanager.miloapis.com"}, iam.ParentNameExtraKey: {"unrelated-consumer", "datum-cloud"}}}, + {"empty context", map[string][]string{iam.ParentKindExtraKey: {"Project"}, iam.ParentAPIGroupExtraKey: {"resourcemanager.miloapis.com"}, iam.ParentNameExtraKey: {""}}}, + } { + t.Run(test.name, func(t *testing.T) { + unprovenConfig := rest.CopyConfig(actorConfig) + unprovenConfig.Impersonate.Extra = test.extra + unproven, err := client.New(unprovenConfig, client.Options{Scheme: scheme}) + if err != nil { + t.Fatal(err) + } + device := devices[0].DeepCopyObject().(*inventory.Device) + device.Name, device.UID, device.ResourceVersion, device.ManagedFields = "unproven-context", "", "", nil + for _, err := range []error{unproven.Create(ctx, device), unproven.Delete(ctx, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "default"}}, client.DryRunAll)} { + if err == nil || !strings.Contains(err.Error(), "failed calling webhook") { + t.Fatalf("ambiguous routing context bypassed fail-closed transport: %v", err) + } + } + }) + } +} diff --git a/internal/registration/admission_regression_test.go b/internal/registration/admission_regression_test.go new file mode 100644 index 00000000..763d9732 --- /dev/null +++ b/internal/registration/admission_regression_test.go @@ -0,0 +1,75 @@ +package registration + +import ( + "context" + "encoding/json" + "testing" + + admissionv1 "k8s.io/api/admission/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +func TestIdenticalAdmissionObjects(t *testing.T) { + for _, test := range []struct { + name, old, current string + identical bool + }{ + {"key order and whitespace", `{"metadata":{"resourceVersion":"1"},"spec":{}}`, ` {"spec":{},"metadata":{"resourceVersion":"1"}} `, true}, + {"unknown field", `{"future":1}`, `{"future":2}`, false}, + {"large exact integers", `{"future":9007199254740992}`, `{"future":9007199254740993}`, false}, + {"managed fields", `{"metadata":{"managedFields":[]}}`, `{"metadata":{"managedFields":[{"manager":"new"}]}}`, false}, + {"status", `{"status":{}}`, `{"status":{"ready":true}}`, false}, + {"null versus absent", `{}`, `{"future":null}`, false}, + {"array order", `{"future":[1,2]}`, `{"future":[2,1]}`, false}, + {"null objects", `null`, `null`, false}, + {"malformed", `{`, `{`, false}, + {"trailing document", `{} {}`, `{}`, false}, + } { + t.Run(test.name, func(t *testing.T) { + if identicalObjects([]byte(test.old), []byte(test.current)) != test.identical { + t.Fatal("unexpected whole-object comparison") + } + }) + } +} + +func TestNoopCannotClearPendingRealUpdateFence(t *testing.T) { + handler, device := fixture(t) + ctx := context.Background() + registration := registrationRequest(t, device, "record") + update := registration + update.Resource = metav1.GroupVersionResource{Group: "fleet.datumapis.com", Version: "v1alpha1", Resource: "devices"} + update.Operation = admissionv1.Update + update.OldObject.Raw, _ = json.Marshal(device) + changed := device.DeepCopyObject() + raw, _ := json.Marshal(changed) + var object map[string]any + _ = json.Unmarshal(raw, &object) + object["futureField"] = "changed" + update.Object.Raw, _ = json.Marshal(object) + if !handler.Handle(ctx, update).Allowed { + t.Fatal("real update rejected") + } + update.Object.Raw = update.OldObject.Raw + if !handler.Handle(ctx, update).Allowed { + t.Fatal("no-op rejected") + } + if handler.Handle(ctx, registration).Allowed { + t.Fatal("no-op cleared the pending real-update reservation") + } +} + +func TestLifetimeCollectionDeletionDenied(t *testing.T) { + for _, resource := range []metav1.GroupVersionResource{{Version: "v1", Resource: "namespaces"}, {Group: "resourcemanager.miloapis.com", Version: "v1alpha1", Resource: "projects"}} { + t.Run(resource.Resource, func(t *testing.T) { + handler, device := fixture(t) + request := registrationRequest(t, device, "unused") + request.Operation = admissionv1.Delete + request.Name = "" + request.Resource = resource + if handler.Handle(context.Background(), request).Allowed { + t.Fatal("unnamed deletion cannot exclude a protected lifetime") + } + }) + } +} diff --git a/internal/registration/envtest_test.go b/internal/registration/envtest_test.go index f21bcadc..3793aa73 100644 --- a/internal/registration/envtest_test.go +++ b/internal/registration/envtest_test.go @@ -70,7 +70,7 @@ func TestRealAPIServerAdmissionAndCAS(t *testing.T) { if err := api.Create(ctx, device); err != nil { t.Fatal(err) } - encoded, _ := json.Marshal(Ledger{Authority: "milo", Projects: []string{"provider"}}) + encoded, _ := json.Marshal(Ledger{Authority: "milo", Projects: []string{"datum-cloud"}}) if err := api.Create(ctx, &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: LedgerName, Namespace: "fleet-system-private"}, Data: map[string][]byte{"ledger.json": encoded}}); err != nil { t.Fatal(err) } @@ -122,8 +122,8 @@ func TestRealAPIServerAdmissionAndCAS(t *testing.T) { t.Fatal(err) } var denied atomic.Bool - handler := &Handler{Store: Store{Client: private, Namespace: "fleet-system-private", Authority: "milo", Projects: []string{"provider"}}, VerifyFence: func(ctx context.Context) error { return VerifyFence(ctx, api) }, Resolve: func(context.Context, string) (Project, error) { - return Project{Identity: controller.ProjectIdentity{AuthorityID: "milo", RouteName: "provider", UID: "project-1"}, Client: api}, nil + handler := &Handler{Store: Store{Client: private, Namespace: "fleet-system-private", Authority: "milo", Projects: []string{"datum-cloud"}}, VerifyFence: func(ctx context.Context) error { return VerifyFence(ctx, api, []string{"datum-cloud"}) }, Resolve: func(context.Context, string) (Project, error) { + return Project{Identity: controller.ProjectIdentity{AuthorityID: "milo", RouteName: "datum-cloud", UID: "project-1"}, Client: api}, nil }, Authorize: func(ctx context.Context, project Project, actor authenticationv1.UserInfo, group, resource, name string) error { if denied.Load() { return ErrConflict @@ -141,12 +141,14 @@ func TestRealAPIServerAdmissionAndCAS(t *testing.T) { if err := yaml.UnmarshalStrict(data, webhooks); err != nil { t.Fatal(err) } - webhooks.Webhooks[0].ClientConfig = admissionregistrationv1.WebhookClientConfig{URL: &url, CABundle: pemCertificate(server.Certificate().Raw)} + for index := range webhooks.Webhooks { + webhooks.Webhooks[index].ClientConfig = admissionregistrationv1.WebhookClientConfig{URL: &url, CABundle: pemCertificate(server.Certificate().Raw)} + } if err := api.Create(ctx, webhooks); err != nil { t.Fatal(err) } actorConfig := rest.CopyConfig(config) - actorConfig.Impersonate = rest.ImpersonationConfig{UserName: "operator", UID: "actor-1", Groups: []string{"system:masters"}, Extra: map[string][]string{iam.ParentKindExtraKey: {"Project"}, iam.ParentAPIGroupExtraKey: {"resourcemanager.miloapis.com"}, iam.ParentNameExtraKey: {"provider"}}} + actorConfig.Impersonate = rest.ImpersonationConfig{UserName: "operator", UID: "actor-1", Groups: []string{"system:masters"}, Extra: map[string][]string{iam.ParentKindExtraKey: {"Project"}, iam.ParentAPIGroupExtraKey: {"resourcemanager.miloapis.com"}, iam.ParentNameExtraKey: {"datum-cloud"}}} actor, err := client.New(actorConfig, client.Options{Scheme: scheme}) if err != nil { t.Fatal(err) diff --git a/internal/registration/fence.go b/internal/registration/fence.go index 9f2330ba..2f9fbcef 100644 --- a/internal/registration/fence.go +++ b/internal/registration/fence.go @@ -2,14 +2,35 @@ package registration import ( "context" + "encoding/json" "errors" + "fmt" + "reflect" "slices" + iam "go.miloapis.com/milo/pkg/apis/iam/v1alpha1" admissionv1 "k8s.io/api/admissionregistration/v1" "sigs.k8s.io/controller-runtime/pkg/client" ) -func VerifyFence(ctx context.Context, reader client.Reader) error { +func requiredFences(projects []string) []admissionv1.ValidatingWebhook { + names, _ := json.Marshal(projects) + projectContext := fmt.Sprintf("has(request.userInfo.extra) && %q in request.userInfo.extra && request.userInfo.extra[%q] == ['Project'] && %q in request.userInfo.extra && request.userInfo.extra[%q] == ['resourcemanager.miloapis.com'] && %q in request.userInfo.extra && size(request.userInfo.extra[%q]) == 1 && request.userInfo.extra[%q][0] != ''", iam.ParentKindExtraKey, iam.ParentKindExtraKey, iam.ParentAPIGroupExtraKey, iam.ParentAPIGroupExtraKey, iam.ParentNameExtraKey, iam.ParentNameExtraKey, iam.ParentNameExtraKey) + protectedContext := fmt.Sprintf("!(%s) || request.userInfo.extra[%q][0] in %s", projectContext, iam.ParentNameExtraKey, names) + namespaced, cluster := admissionv1.NamespacedScope, admissionv1.ClusterScope + writes := []admissionv1.OperationType{admissionv1.Create, admissionv1.Update, admissionv1.Delete} + return []admissionv1.ValidatingWebhook{ + {Name: "registration.fleet.datumapis.com", Rules: []admissionv1.RuleWithOperations{{Operations: writes, Rule: admissionv1.Rule{APIGroups: []string{"metal.datumapis.com"}, APIVersions: []string{"v1alpha1"}, Resources: []string{"machinecapacities", "machinecapacities/status"}, Scope: &namespaced}}}}, + {Name: "inventory.registration.fleet.datumapis.com", Rules: []admissionv1.RuleWithOperations{{Operations: writes, Rule: admissionv1.Rule{APIGroups: []string{"fleet.datumapis.com"}, APIVersions: []string{"v1alpha1"}, Resources: []string{"devices", "devices/status"}, Scope: &namespaced}}}, MatchConditions: []admissionv1.MatchCondition{{Name: "provider-project-context", Expression: protectedContext}}}, + {Name: "namespace.registration.fleet.datumapis.com", Rules: []admissionv1.RuleWithOperations{{Operations: []admissionv1.OperationType{admissionv1.Delete}, Rule: admissionv1.Rule{APIGroups: []string{""}, APIVersions: []string{"v1"}, Resources: []string{"namespaces"}, Scope: &cluster}}}, MatchConditions: []admissionv1.MatchCondition{{Name: "provider-project-context", Expression: protectedContext}, {Name: "inventory-namespace", Expression: "!has(request.name) || request.name == '' || request.name == 'default'"}}}, + {Name: "project.registration.fleet.datumapis.com", Rules: []admissionv1.RuleWithOperations{{Operations: []admissionv1.OperationType{admissionv1.Delete}, Rule: admissionv1.Rule{APIGroups: []string{"resourcemanager.miloapis.com"}, APIVersions: []string{"v1alpha1"}, Resources: []string{"projects"}, Scope: &cluster}}}, MatchConditions: []admissionv1.MatchCondition{{Name: "provider-project-name", Expression: "!has(request.name) || request.name == '' || request.name in " + string(names)}}}, + } +} + +func VerifyFence(ctx context.Context, reader client.Reader, projects []string) error { + if len(projects) == 0 || slices.Contains(projects, "") || !slices.IsSorted(projects) || len(slices.Compact(slices.Clone(projects))) != len(projects) { + return errors.New("registration admission requires the exact sorted provider scope") + } var configuration admissionv1.ValidatingWebhookConfiguration if err := reader.Get(ctx, client.ObjectKey{Name: "fleet-capacity-registration"}, &configuration); err != nil { return errors.New("project-plane registration admission configuration is unavailable") @@ -17,40 +38,25 @@ func VerifyFence(ctx context.Context, reader client.Reader) error { if !configuration.DeletionTimestamp.IsZero() { return errors.New("registration admission configuration is deleting") } - for _, webhook := range configuration.Webhooks { - if webhook.Name != "registration.fleet.datumapis.com" { - continue + required := requiredFences(projects) + if len(configuration.Webhooks) != len(required) { + return errors.New("registration admission requires separate capacity, inventory, namespace and project fences") + } + for _, expected := range required { + index := slices.IndexFunc(configuration.Webhooks, func(webhook admissionv1.ValidatingWebhook) bool { return webhook.Name == expected.Name }) + if index < 0 { + return errors.New("registration admission webhook is missing") + } + webhook := configuration.Webhooks[index] + if webhook.FailurePolicy == nil || *webhook.FailurePolicy != admissionv1.Fail || webhook.SideEffects == nil || *webhook.SideEffects != admissionv1.SideEffectClassNoneOnDryRun || webhook.MatchPolicy == nil || *webhook.MatchPolicy != admissionv1.Equivalent || !slices.Contains(webhook.AdmissionReviewVersions, "v1") || (webhook.NamespaceSelector != nil && (len(webhook.NamespaceSelector.MatchLabels) != 0 || len(webhook.NamespaceSelector.MatchExpressions) != 0)) || (webhook.ObjectSelector != nil && (len(webhook.ObjectSelector.MatchLabels) != 0 || len(webhook.ObjectSelector.MatchExpressions) != 0)) || len(webhook.ClientConfig.CABundle) == 0 { + return errors.New("registration admission must be fail-closed, without label selectors, and have an explicit serving CA") } - if webhook.FailurePolicy == nil || *webhook.FailurePolicy != admissionv1.Fail || webhook.SideEffects == nil || *webhook.SideEffects != admissionv1.SideEffectClassNoneOnDryRun || len(webhook.MatchConditions) != 0 || (webhook.NamespaceSelector != nil && (len(webhook.NamespaceSelector.MatchLabels) != 0 || len(webhook.NamespaceSelector.MatchExpressions) != 0)) || (webhook.ObjectSelector != nil && (len(webhook.ObjectSelector.MatchLabels) != 0 || len(webhook.ObjectSelector.MatchExpressions) != 0)) || len(webhook.ClientConfig.CABundle) == 0 { - return errors.New("registration admission must be fail-closed, unfiltered, and have an explicit serving CA") + if !reflect.DeepEqual(webhook.Rules, expected.Rules) || !slices.Equal(webhook.MatchConditions, expected.MatchConditions) { + return errors.New("registration admission rules and trusted-context conditions must exactly match the retained provider scope") } - for _, required := range []struct { - group, resource, version string - operations []admissionv1.OperationType - }{ - {"metal.datumapis.com", "machinecapacities", "v1alpha1", []admissionv1.OperationType{admissionv1.Create, admissionv1.Update, admissionv1.Delete}}, - {"metal.datumapis.com", "machinecapacities/status", "v1alpha1", []admissionv1.OperationType{admissionv1.Update}}, - {"fleet.datumapis.com", "devices", "v1alpha1", []admissionv1.OperationType{admissionv1.Create, admissionv1.Update, admissionv1.Delete}}, - {"", "namespaces", "v1", []admissionv1.OperationType{admissionv1.Delete}}, - {"resourcemanager.miloapis.com", "projects", "v1alpha1", []admissionv1.OperationType{admissionv1.Delete}}, - } { - for _, operation := range required.operations { - found := false - wantedScope := admissionv1.NamespacedScope - if required.resource == "namespaces" || required.resource == "projects" { - wantedScope = admissionv1.ClusterScope - } - for _, rule := range webhook.Rules { - if (rule.Scope == nil || *rule.Scope == admissionv1.AllScopes || *rule.Scope == wantedScope) && slices.Contains(rule.APIGroups, required.group) && slices.Contains(rule.APIVersions, required.version) && slices.Contains(rule.Resources, required.resource) && slices.Contains(rule.Operations, operation) { - found = true - } - } - if !found { - return errors.New("registration admission omits a required write fence") - } - } + if !reflect.DeepEqual(webhook.ClientConfig, configuration.Webhooks[0].ClientConfig) { + return errors.New("registration fences must use the same authenticated authority endpoint") } - return nil } - return errors.New("registration admission webhook is missing") + return nil } diff --git a/internal/registration/fence_test.go b/internal/registration/fence_test.go index 31287684..6aa89617 100644 --- a/internal/registration/fence_test.go +++ b/internal/registration/fence_test.go @@ -21,13 +21,18 @@ func TestPackagedProjectAdmissionFence(t *testing.T) { if err := yaml.UnmarshalStrict(data, &configured); err != nil { t.Fatal(err) } - configured.Webhooks[0].ClientConfig.CABundle = []byte("environment-owned-serving-ca") + for index := range configured.Webhooks { + configured.Webhooks[index].ClientConfig.CABundle = []byte("environment-owned-serving-ca") + } for _, test := range []struct { name string mutate func(*admissionv1.ValidatingWebhookConfiguration) allowed bool }{ {"complete", func(*admissionv1.ValidatingWebhookConfiguration) {}, true}, + {"incomplete deployment", func(configuration *admissionv1.ValidatingWebhookConfiguration) { + configuration.Webhooks = configuration.Webhooks[:1] + }, false}, {"no serving CA", func(configuration *admissionv1.ValidatingWebhookConfiguration) { configuration.Webhooks[0].ClientConfig.CABundle = nil }, false}, @@ -36,7 +41,39 @@ func TestPackagedProjectAdmissionFence(t *testing.T) { configuration.Webhooks[0].FailurePolicy = &policy }, false}, {"missing Device protection", func(configuration *admissionv1.ValidatingWebhookConfiguration) { - configuration.Webhooks[0].Rules = configuration.Webhooks[0].Rules[:1] + configuration.Webhooks[1].Rules = nil + }, false}, + {"global inventory blast radius", func(configuration *admissionv1.ValidatingWebhookConfiguration) { + configuration.Webhooks[1].MatchConditions = nil + }, false}, + {"broadened inventory rule", func(configuration *admissionv1.ValidatingWebhookConfiguration) { + configuration.Webhooks[0].Rules = append(configuration.Webhooks[0].Rules, configuration.Webhooks[1].Rules...) + }, false}, + {"wrong retained project scope", func(configuration *admissionv1.ValidatingWebhookConfiguration) { + configuration.Webhooks[1].MatchConditions = requiredFences([]string{"different"})[1].MatchConditions + }, false}, + {"namespace name omitted", func(configuration *admissionv1.ValidatingWebhookConfiguration) { + configuration.Webhooks[2].MatchConditions = configuration.Webhooks[2].MatchConditions[:1] + }, false}, + {"global project deletion blast radius", func(configuration *admissionv1.ValidatingWebhookConfiguration) { + configuration.Webhooks[3].MatchConditions = nil + }, false}, + {"caller label condition", func(configuration *admissionv1.ValidatingWebhookConfiguration) { + configuration.Webhooks[1].MatchConditions[0].Expression = "object.metadata.labels['provider'] == 'datum-cloud'" + }, false}, + {"Device status protection omitted", func(configuration *admissionv1.ValidatingWebhookConfiguration) { + configuration.Webhooks[1].Rules[0].Resources = []string{"devices"} + }, false}, + {"inventory fail open", func(configuration *admissionv1.ValidatingWebhookConfiguration) { + policy := admissionv1.Ignore + configuration.Webhooks[1].FailurePolicy = &policy + }, false}, + {"capacity exemption", func(configuration *admissionv1.ValidatingWebhookConfiguration) { + configuration.Webhooks[0].MatchConditions = configuration.Webhooks[1].MatchConditions + }, false}, + {"split authority", func(configuration *admissionv1.ValidatingWebhookConfiguration) { + other := "https://another.invalid/webhook" + configuration.Webhooks[1].ClientConfig.URL = &other }, false}, {"caller annotation selector", func(configuration *admissionv1.ValidatingWebhookConfiguration) { configuration.Webhooks[0].ObjectSelector = &metav1.LabelSelector{MatchLabels: map[string]string{"registration": "true"}} @@ -50,9 +87,27 @@ func TestPackagedProjectAdmissionFence(t *testing.T) { t.Fatal(err) } api := fake.NewClientBuilder().WithScheme(scheme).WithObjects(configuration).Build() - if err := VerifyFence(context.Background(), api); (err == nil) != test.allowed { + if err := VerifyFence(context.Background(), api, []string{"datum-cloud"}); (err == nil) != test.allowed { t.Fatalf("unexpected fence result: %v", err) } }) } } + +func TestIncompleteFenceDeniesRegistrationWithoutReservation(t *testing.T) { + handler, device := fixture(t) + scheme := runtime.NewScheme() + if err := admissionv1.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + configuration := &admissionv1.ValidatingWebhookConfiguration{ObjectMeta: metav1.ObjectMeta{Name: "fleet-capacity-registration"}} + api := fake.NewClientBuilder().WithScheme(scheme).WithObjects(configuration).Build() + handler.VerifyFence = func(ctx context.Context) error { return VerifyFence(ctx, api, handler.Store.Projects) } + if handler.Handle(context.Background(), registrationRequest(t, device, "incomplete")).Allowed { + t.Fatal("incomplete admission deployment admitted registration") + } + _, ledger, err := handler.Store.Read(context.Background()) + if err != nil || len(ledger.Entries) != 0 { + t.Fatalf("incomplete fence changed registration state: %+v %v", ledger, err) + } +} diff --git a/internal/registration/project_context_test.go b/internal/registration/project_context_test.go new file mode 100644 index 00000000..f3f8aa4e --- /dev/null +++ b/internal/registration/project_context_test.go @@ -0,0 +1,71 @@ +package registration + +import ( + "net/http" + "net/http/httptest" + "reflect" + "testing" + + iam "go.miloapis.com/milo/pkg/apis/iam/v1alpha1" + filters "go.miloapis.com/milo/pkg/server/filters" + "k8s.io/apimachinery/pkg/util/sets" + "k8s.io/apiserver/pkg/authentication/user" + requestcontext "k8s.io/apiserver/pkg/endpoints/request" +) + +func TestPinnedMiloRouteOverwritesCallerProjectExtras(t *testing.T) { + for _, route := range []string{"datum-cloud", "unrelated-consumer"} { + t.Run(route, func(t *testing.T) { + caller := &user.DefaultInfo{Name: "operator", UID: "actor-1", Extra: map[string][]string{iam.ParentKindExtraKey: {"Organization"}, iam.ParentAPIGroupExtraKey: {"caller.invalid"}, iam.ParentNameExtraKey: {"forged", "datum-cloud"}}} + called := false + downstream := http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + called = true + actor, ok := requestcontext.UserFrom(request.Context()) + if !ok || actor.GetName() != caller.Name || actor.GetUID() != caller.UID { + t.Fatal("caller identity was not preserved") + } + for key, expected := range map[string][]string{iam.ParentKindExtraKey: {"Project"}, iam.ParentAPIGroupExtraKey: {"resourcemanager.miloapis.com"}, iam.ParentNameExtraKey: {route}} { + if !reflect.DeepEqual(actor.GetExtra()[key], expected) { + t.Fatalf("routing did not establish trusted %s: %v", key, actor.GetExtra()) + } + } + writer.WriteHeader(http.StatusNoContent) + }) + router := filters.ProjectRouterWithRequestInfo(filters.ProjectContextAuthorizationDecorator(downstream), &requestcontext.RequestInfoFactory{APIPrefixes: sets.NewString("api", "apis"), GrouplessAPIPrefixes: sets.NewString("api")}) + request := httptest.NewRequest(http.MethodPost, "/apis/resourcemanager.miloapis.com/v1alpha1/projects/"+route+"/control-plane/apis/fleet.datumapis.com/v1alpha1/namespaces/default/devices", nil) + request = request.WithContext(requestcontext.WithUser(request.Context(), caller)) + router.ServeHTTP(httptest.NewRecorder(), request) + if !called || !reflect.DeepEqual(caller.Extra[iam.ParentNameExtraKey], []string{"forged", "datum-cloud"}) { + t.Fatal("routing failed or modified cached caller context") + } + }) + } +} + +func TestPinnedMiloNestedScopesCannotProveUnrelatedProject(t *testing.T) { + for _, nested := range []struct{ path, kind, group string }{ + {"resourcemanager.miloapis.com/v1alpha1/organizations/unrelated-consumer", "Organization", "resourcemanager.miloapis.com"}, + {"iam.miloapis.com/v1alpha1/users/unrelated-consumer", "User", "iam.miloapis.com"}, + } { + t.Run(nested.kind, func(t *testing.T) { + called := false + downstream := http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + called = true + actor, ok := requestcontext.UserFrom(request.Context()) + if !ok || !reflect.DeepEqual(actor.GetExtra()[iam.ParentKindExtraKey], []string{nested.kind}) || !reflect.DeepEqual(actor.GetExtra()[iam.ParentAPIGroupExtraKey], []string{nested.group}) || !reflect.DeepEqual(actor.GetExtra()[iam.ParentNameExtraKey], []string{"unrelated-consumer"}) { + t.Fatal("pinned Milo nested-scope behavior changed; reassess the admission trust boundary") + } + writer.WriteHeader(http.StatusNoContent) + }) + decorated := filters.ProjectContextAuthorizationDecorator(filters.OrganizationContextAuthorizationDecorator(filters.UserContextAuthorizationDecorator(downstream))) + routed := filters.UserContextHandler(filters.OrganizationContextHandler(decorated, nil), nil) + router := filters.ProjectRouterWithRequestInfo(routed, &requestcontext.RequestInfoFactory{APIPrefixes: sets.NewString("api", "apis"), GrouplessAPIPrefixes: sets.NewString("api")}) + request := httptest.NewRequest(http.MethodPost, "/apis/resourcemanager.miloapis.com/v1alpha1/projects/datum-cloud/control-plane/apis/"+nested.path+"/control-plane/apis/fleet.datumapis.com/v1alpha1/namespaces/default/devices", nil) + request = request.WithContext(requestcontext.WithUser(request.Context(), &user.DefaultInfo{Name: "operator", UID: "actor-1"})) + router.ServeHTTP(httptest.NewRecorder(), request) + if !called { + t.Fatal("nested route did not reach the scope decorators") + } + }) + } +} diff --git a/internal/registration/runtime.go b/internal/registration/runtime.go index b19091b8..9d58323e 100644 --- a/internal/registration/runtime.go +++ b/internal/registration/runtime.go @@ -21,7 +21,7 @@ import ( ) func NewHandler(store Store, root client.Client, template *rest.Config, scheme *runtime.Scheme) *Handler { - return &Handler{Store: store, VerifyFence: func(ctx context.Context) error { return VerifyFence(ctx, root) }, Resolve: func(ctx context.Context, name string) (Project, error) { + return &Handler{Store: store, VerifyFence: func(ctx context.Context) error { return VerifyFence(ctx, root, store.Projects) }, Resolve: func(ctx context.Context, name string) (Project, error) { identity, err := manager.ResolveProjectIdentity(ctx, root, store.Authority, name) if err != nil { return Project{}, err diff --git a/internal/registration/testdata/review_adversarial_test.go.txt b/internal/registration/testdata/review_adversarial_test.go.txt new file mode 100644 index 00000000..fefd78ba --- /dev/null +++ b/internal/registration/testdata/review_adversarial_test.go.txt @@ -0,0 +1,172 @@ +package registration + +import ( + "context" + "encoding/json" + "net/http/httptest" + "os" + "path/filepath" + "testing" + "time" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + metal "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/controller" + iam "go.miloapis.com/milo/pkg/apis/iam/v1alpha1" + admissionregistrationv1 "k8s.io/api/admissionregistration/v1" + authorizationv1 "k8s.io/api/authorization/v1" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/client-go/rest" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/envtest" + "sigs.k8s.io/controller-runtime/pkg/webhook/admission" + "sigs.k8s.io/yaml" +) + +func TestReviewRealNoopAndOutage(t *testing.T) { + if os.Getenv("KUBEBUILDER_ASSETS") == "" { + t.Skip("KUBEBUILDER_ASSETS required") + } + ctx := context.Background() + environment := &envtest.Environment{CRDDirectoryPaths: []string{filepath.Join("..", "..", "config", "base", "crd"), filepath.Join("..", "..", "config", "components", "inventory", "crds")}, ErrorIfCRDPathMissing: true} + config, err := environment.Start() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if err := environment.Stop(); err != nil { + t.Error(err) + } + }) + scheme := runtime.NewScheme() + for _, add := range []func(*runtime.Scheme) error{corev1.AddToScheme, inventory.AddToScheme, metal.AddToScheme, admissionregistrationv1.AddToScheme, authorizationv1.AddToScheme} { + if err := add(scheme); err != nil { + t.Fatal(err) + } + } + api, err := client.New(config, client.Options{Scheme: scheme}) + if err != nil { + t.Fatal(err) + } + device := &inventory.Device{ObjectMeta: metav1.ObjectMeta{Name: "noop-hardware", Namespace: "default"}, Spec: inventory.DeviceSpec{ClaimRef: inventory.LocalReference{Name: "installation"}, Identity: inventory.DeviceIdentity{Model: "test", Serial: "noop-serial", SystemUUID: "11111111-1111-1111-1111-111111111111"}}} + if err := api.Create(ctx, device, client.FieldOwner("review")); err != nil { + t.Fatal(err) + } + encoded, _ := json.Marshal(Ledger{Authority: "milo", Projects: []string{"provider"}}) + if err := api.Create(ctx, &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: LedgerName, Namespace: "default"}, Data: map[string][]byte{"ledger.json": encoded}}); err != nil { + t.Fatal(err) + } + handler := &Handler{Store: Store{Client: api, Namespace: "default", Authority: "milo", Projects: []string{"provider"}}, VerifyFence: func(ctx context.Context) error { return VerifyFence(ctx, api) }, Resolve: func(context.Context, string) (Project, error) { + return Project{Identity: controller.ProjectIdentity{AuthorityID: "milo", RouteName: "provider", UID: "project-1"}, Client: api}, nil + }, Authorize: Authorize} + server := httptest.NewTLSServer(&admission.Webhook{Handler: handler}) + t.Cleanup(server.Close) + data, err := os.ReadFile("../../config/components/registration-admission/webhook.yaml") + if err != nil { + t.Fatal(err) + } + var webhooks admissionregistrationv1.ValidatingWebhookConfiguration + if err := yaml.UnmarshalStrict(data, &webhooks); err != nil { + t.Fatal(err) + } + url := server.URL + webhooks.Webhooks[0].ClientConfig = admissionregistrationv1.WebhookClientConfig{URL: &url, CABundle: pemCertificate(server.Certificate().Raw)} + if err := api.Create(ctx, &webhooks); err != nil { + t.Fatal(err) + } + actorConfig := rest.CopyConfig(config) + actorConfig.Impersonate = rest.ImpersonationConfig{UserName: "review-operator", UID: "actor-1", Groups: []string{"system:masters"}, Extra: map[string][]string{iam.ParentKindExtraKey: {"Project"}, iam.ParentAPIGroupExtraKey: {"resourcemanager.miloapis.com"}, iam.ParentNameExtraKey: {"provider"}}} + actor, err := client.New(actorConfig, client.Options{Scheme: scheme}) + if err != nil { + t.Fatal(err) + } + deadline := time.Now().Add(10 * time.Second) + for { + if err := actor.Update(ctx, device.DeepCopyObject().(*inventory.Device), client.DryRunAll); err != nil { + break + } + if time.Now().After(deadline) { + t.Fatal("webhook did not engage") + } + time.Sleep(30 * time.Millisecond) + } + t.Run("successful-noop-must-not-poison-current-device", func(t *testing.T) { + unchanged := false + for attempt := 0; attempt < 3; attempt++ { + if err := actor.Get(ctx, client.ObjectKeyFromObject(device), device); err != nil { + t.Fatal(err) + } + before := device.ResourceVersion + if err := actor.Update(ctx, device, client.FieldOwner("review")); err != nil { + t.Fatal(err) + } + if before == device.ResourceVersion { + unchanged = true + break + } + } + if !unchanged { + t.Fatal("could not reproduce a no-op update") + } + request := registrationRequest(t, device, "after-noop") + var capacity metal.MachineCapacity + if err := json.Unmarshal(request.Object.Raw, &capacity); err != nil { + t.Fatal(err) + } + capacity.UID = "" + if err := actor.Create(ctx, &capacity); err != nil { + t.Errorf("completed no-op left current RV %s ineligible: %v", device.ResourceVersion, err) + } + }) + t.Run("explicit-real-edit-control-restores-registration", func(t *testing.T) { + if err := actor.Get(ctx, client.ObjectKeyFromObject(device), device); err != nil { + t.Fatal(err) + } + before := device.ResourceVersion + device.Labels = map[string]string{"review-control": "real-change"} + if err := actor.Update(ctx, device, client.FieldOwner("review")); err != nil { + t.Fatal(err) + } + if device.ResourceVersion == before { + t.Fatal("control edit did not change RV") + } + request := registrationRequest(t, device, "after-real-edit") + var capacity metal.MachineCapacity + if err := json.Unmarshal(request.Object.Raw, &capacity); err != nil { + t.Fatal(err) + } + capacity.UID = "" + if err := actor.Create(ctx, &capacity); err != nil { + t.Fatalf("explicitly reselected changed Device should register: %v", err) + } + if err := handler.Recover(ctx); err != nil { + t.Fatal(err) + } + _, ledger, err := handler.Store.Read(ctx) + if err != nil || len(ledger.Entries) != 1 || ledger.Entries[0].Outcome != "Recorded" { + t.Fatalf("control failed: %+v %v", ledger, err) + } + }) + t.Run("out-of-scope-inventory-outage-blast-radius", func(t *testing.T) { + outsideConfig := rest.CopyConfig(actorConfig) + outsideConfig.Impersonate.Extra = map[string][]string{iam.ParentKindExtraKey: {"Project"}, iam.ParentAPIGroupExtraKey: {"resourcemanager.miloapis.com"}, iam.ParentNameExtraKey: {"unrelated-consumer"}} + outside, err := client.New(outsideConfig, client.Options{Scheme: scheme}) + if err != nil { + t.Fatal(err) + } + other := device.DeepCopyObject().(*inventory.Device) + other.Name, other.UID, other.ResourceVersion, other.ManagedFields = "outside-before-outage", "", "", nil + if err := outside.Create(ctx, other); err != nil { + t.Fatal(err) + } + server.Close() + other.Name, other.UID, other.ResourceVersion, other.ManagedFields = "outside-after-outage", "", "", nil + if err := outside.Create(ctx, other); err == nil { + t.Fatal("expected packaged fail-closed webhook to block unrelated inventory too") + } else { + t.Logf("confirmed unrelated project inventory outage: %v", err) + } + }) +} From 0e5ceaf93c5373e8c3b26eb381d408bd8b67c15e Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sun, 22 Nov 2026 12:17:14 -0600 Subject: [PATCH 067/518] Show manufacturer models and linked inventory devices --- docs/development/hardware-catalog.md | 30 +++ .../src/components/hardware-catalog.test.tsx | 2 +- .../components/inventory-hardware-fields.tsx | 3 +- .../components/manufacturer-overview.test.tsx | 205 ++++++++++++++++++ .../src/components/manufacturer-overview.tsx | 55 +++++ .../src/components/physical-inventory.tsx | 19 +- ui/provider/src/lib/hardware-catalog.ts | 5 +- ui/provider/src/lib/manufacturer-inventory.ts | 29 +++ .../src/pages/device-inventory.test.tsx | 7 + 9 files changed, 342 insertions(+), 13 deletions(-) create mode 100644 ui/provider/src/components/manufacturer-overview.test.tsx create mode 100644 ui/provider/src/components/manufacturer-overview.tsx create mode 100644 ui/provider/src/lib/manufacturer-inventory.ts diff --git a/docs/development/hardware-catalog.md b/docs/development/hardware-catalog.md index 913cac42..899e9725 100644 --- a/docs/development/hardware-catalog.md +++ b/docs/development/hardware-catalog.md @@ -103,6 +103,36 @@ labels/annotations and audit logs; Fleet does not interpret it or acquire owners from it. Creating catalog records remains observational, never a capacity or provisioning action. +## Manufacturer detail (implemented) + +Manufacturer detail now shows recorded overview fields, linked DeviceTypes with +associated Device counts, and linked Devices with their model and reported +location. Joins use same-namespace `manufacturerRef` and `deviceTypeRef` only; +inline manufacturer text and aliases never establish relationships. Rows/counts +are deduplicated by namespace/name. Deleting or missing targets remain unresolved. +Locations use the Device's report only, with links to readable Facility/Rack +records; plans and nominal templates never fill in physical observations. + +Display names lead catalog tables, links and registration choices, with resource +names as fallback and contextual identifiers only for colliding labels. The +manufacturer's metadata is collapsed under Technical details. Existing Datum +tables, page chrome, query/history behavior and authorized collection cache are +reused, without new reads, forms, mutations, session policies or backend changes. +Unavailable model/device collections produce unknown counts, not zero; unreadable +dependencies lose their labels and links immediately. Resolved subsets remain +visible with missing-reference guidance. Initial loading stays in the page shell. + +Local validation on 2026-11-22: provider full suite (42 files / 692 tests), +typecheck and production build pass, as do documentation-link and whitespace +checks. Validation used Node 22.22.0 and pnpm 11.28.9; the documented Node 26 +runtime was not exercised. Focused tests cover reference scope, unrelated and +dangling records, duplicate rows/counts/labels, fallback labels, catalog picker +choices, denied/partial collections, actual destination URLs, reported-only +location, loading and history/filter retention. Existing session, write-precondition +and visible-focus regressions also pass. Shared/consumer code is unchanged, so +consumer validation is not required. No browser/host acceptance, live reads or +writes, migration, deployment, physical verification or readiness is claimed. + ## Explicitly deferred user-visible work Staff can browse Manufacturers/DeviceTypes and see catalog-backed Device labels, diff --git a/ui/provider/src/components/hardware-catalog.test.tsx b/ui/provider/src/components/hardware-catalog.test.tsx index 282ab70e..53228aa2 100644 --- a/ui/provider/src/components/hardware-catalog.test.tsx +++ b/ui/provider/src/components/hardware-catalog.test.tsx @@ -81,7 +81,7 @@ describe('hardware catalog readers', () => { it('prefers available same-namespace catalog without mutating recorded observations or instances', () => { const { device, model, inventory } = fixture(); const before = structuredClone(device); - expect(deviceModelLabel(device, inventory)).toBe('Private canonical vendor Private model label'); + expect(deviceModelLabel(device, inventory)).toBe('Private vendor label Private model label'); model.spec.displayName = 'Changed model label'; model.spec.componentTemplates!.push({ id: 'new-port', name: 'New reference port', type: 'NetworkPort' }); expect(deviceModelLabel(device, inventory)).toContain('Changed model label'); diff --git a/ui/provider/src/components/inventory-hardware-fields.tsx b/ui/provider/src/components/inventory-hardware-fields.tsx index e51c7909..cf2049b6 100644 --- a/ui/provider/src/components/inventory-hardware-fields.tsx +++ b/ui/provider/src/components/inventory-hardware-fields.tsx @@ -1,6 +1,7 @@ import { Input } from '@datum-cloud/datum-ui/input'; import { Label } from '@datum-cloud/datum-ui/label'; import { Button } from '@datum-cloud/datum-ui/button'; +import { catalogLabel } from '../lib/manufacturer-inventory'; import type { Device, DeviceClaim, PhysicalComponent, PhysicalRecord } from '../../../shared/fleet-api'; import { cableMedia, componentTypes, isTermination, type ReferencedEndpoint } from '../lib/inventory-hardware'; import type { InventoryFormValues } from '../lib/inventory-management'; @@ -22,7 +23,7 @@ export function InventoryHardwareFields({ kind, values, onChange, namespace, cla + }}>{values.catalog && !models.some(({ model }) => model.metadata.uid === values.catalog?.uid) && }{models.map(({ model, manufacturer }) => )}

        Only readable same-namespace models are offered. Assignment is immutable after creation. Record observed identity below; selection never fills recorded observations, components or placement.

        Identity and installation binding cannot be changed later. Existing registrations are kept; this does not replace hardware or identify the active device. Legacy slot bindings are not offered.

        diff --git a/ui/provider/src/components/manufacturer-overview.test.tsx b/ui/provider/src/components/manufacturer-overview.test.tsx new file mode 100644 index 00000000..4116992c --- /dev/null +++ b/ui/provider/src/components/manufacturer-overview.test.tsx @@ -0,0 +1,205 @@ +import { fireEvent, render, screen, within } from '@testing-library/react'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { MemoryRouter, useNavigate } from 'react-router'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import type { PhysicalRecord } from '../../../shared/fleet-api'; +import { toInventory, type Inventory } from '../inventory'; +import { fixturePhysicalDevices, fixturePhysicalClaims } from '../lib/fixtures'; +import { manufacturerInventory } from '../lib/manufacturer-inventory'; +import { PhysicalInventory } from './physical-inventory'; +import { InventoryHardwareFields } from './inventory-hardware-fields'; + +afterEach(() => vi.unstubAllGlobals()); + +function fixture() { + const manufacturer: PhysicalRecord = { kind: 'Manufacturer', metadata: { name: 'vendor-key', namespace: 'default', uid: 'vendor-uid', resourceVersion: '1' }, spec: { displayName: 'Acme hardware', canonicalName: 'acme', aliases: ['Old Acme'] } }; + const model: PhysicalRecord = { kind: 'DeviceType', metadata: { name: 'model-key', namespace: 'default', uid: 'model-uid', resourceVersion: '1' }, spec: { displayName: 'Compute model', manufacturerRef: { name: 'vendor-key' }, model: 'compute', modelShape: { heightUnits: 8 } } }; + const facility: PhysicalRecord = { kind: 'Facility', metadata: { name: 'premises-key', namespace: 'default' }, spec: { displayName: 'Reported premises' } }; + const rack: PhysicalRecord = { kind: 'Rack', metadata: { name: 'rack-key', namespace: 'default' }, spec: { displayName: 'Reported rack' } }; + const device = structuredClone(fixturePhysicalDevices[0]); + device.metadata = { ...device.metadata, namespace: 'default', name: 'device-key' }; + device.spec.displayName = 'Physical server'; + device.spec.deviceTypeRef = { name: 'model-key' }; + device.spec.reportedPlacement = { revision: 1, observedAt: '2026-11-22T00:00:00Z', reason: 'Recorded location', reference: 'synthetic-ticket', facilityRef: { name: 'premises-key' }, rackRef: { name: 'rack-key' }, position: 4, face: 'front' }; + const inventory = toInventory([], [device], [manufacturer, model, facility, rack]); + return { manufacturer, model, device, inventory }; +} + +function History() { + const navigate = useNavigate(); + return <>; +} + +function show(inventory: Inventory, query = '?kind=Manufacturer&namespace=default&record=vendor-key&q=Acme') { + const client = new QueryClient(); + const view = (data: Inventory) => ; + const result = render(view(inventory)); + return { ...result, update: (data: Inventory) => result.rerender(view(data)) }; +} + +describe('manufacturer detail', () => { + it('shows linked models, deduplicated device counts and real reported-location links', () => { + const { inventory, manufacturer, model, device } = fixture(); + inventory.physical.push(model); + inventory.unboundDevices.push(device); + inventory.slots.push({ key: 'default/plan', claim: structuredClone(fixturePhysicalClaims[0]), devices: [device] }); + expect(manufacturerInventory(manufacturer, inventory).devices).toHaveLength(1); + show(inventory); + const models = within(screen.getByRole('region', { name: 'Manufacturer device types table' })); + expect(models.getAllByRole('row')).toHaveLength(2); + expect(models.getByRole('cell', { name: '1' })).toBeInTheDocument(); + const devices = within(screen.getByRole('region', { name: 'Manufacturer devices table' })); + expect(devices.getAllByRole('row')).toHaveLength(2); + for (const [label, kind, name] of [['Physical server', 'Device', 'device-key'], ['Compute model', 'DeviceType', 'model-key'], ['Reported premises', 'Facility', 'premises-key'], ['Reported rack', 'Rack', 'rack-key']]) { + const params = new URL(devices.getByRole('link', { name: label }).getAttribute('href')!, 'https://inventory.test').searchParams; + expect(params.get('kind')).toBe(kind); + expect(params.get('record')).toBe(name); + expect(params.get('namespace')).toBe('default'); + } + expect(devices.getByText(/U4/)).toBeInTheDocument(); + expect(screen.queryByText(/Manufacturers \/ vendor-key/)).not.toBeInTheDocument(); + expect(screen.getByText('vendor-key').closest('details')).toHaveTextContent('Technical details'); + }); + + it('uses only same-namespace references, not text, templates or dangling targets', () => { + const { inventory, manufacturer, model, device } = fixture(); + inventory.physical.push({ ...model, metadata: { ...model.metadata, name: 'other-model' }, spec: { ...model.spec, manufacturerRef: { name: 'other-vendor' } } }); + inventory.unboundDevices = [ + { ...device, spec: { ...device.spec, deviceTypeRef: undefined, identity: { ...device.spec.identity, manufacturer: 'acme' } } }, + { ...device, metadata: { ...device.metadata, name: 'unrelated' }, spec: { ...device.spec, deviceTypeRef: { name: 'other-model' } } }, + { ...device, metadata: { ...device.metadata, name: 'dangling' }, spec: { ...device.spec, deviceTypeRef: { name: 'missing-secret-model' } } }, + { ...device, metadata: { ...device.metadata, namespace: 'other' } }, + ]; + expect(manufacturerInventory(manufacturer, inventory).devices).toEqual([]); + show(inventory); + expect(screen.getByText(/Some device type references are missing/)).toBeInTheDocument(); + expect(screen.getByText('No resolved device relationships found.')).toBeInTheDocument(); + expect(screen.queryByRole('link', { name: 'Physical server' })).not.toBeInTheDocument(); + expect(screen.queryByText('missing-secret-model')).not.toBeInTheDocument(); + }); + + it.each(['DeviceType', 'Device'] as const)('keeps %s failures unknown instead of zero and hides stale rows', kind => { + const { inventory } = fixture(); + const result = show(inventory); + result.update({ ...inventory, issues: { [kind]: { status: 403 } } }); + expect(screen.getByText(/Access denied/)).toBeInTheDocument(); + expect(screen.queryByRole('link', { name: 'Physical server' })).not.toBeInTheDocument(); + expect(screen.queryByRole('cell', { name: '0' })).not.toBeInTheDocument(); + if (kind === 'DeviceType') expect(screen.queryByRole('link', { name: 'Compute model' })).not.toBeInTheDocument(); + else expect(screen.getByRole('cell', { name: 'Unknown' })).toBeInTheDocument(); + result.update({ ...inventory, issues: { [kind]: { status: 502 } } }); + expect(screen.getByText(/Records unavailable/)).toBeInTheDocument(); + expect(screen.queryByText(/No devices explicitly/)).not.toBeInTheDocument(); + }); + + it('redacts a denied manufacturer and its dependent catalog entirely', () => { + const { inventory } = fixture(); + const result = show(inventory); + result.update({ ...inventory, issues: { Manufacturer: { status: 403 } } }); + expect(screen.getByText('Inventory access needed')).toBeInTheDocument(); + expect(result.container.textContent).not.toMatch(/Acme|Compute model|Physical server|vendor-key/); + }); + + it('retains linked devices when locations are denied, unavailable or missing', () => { + const { inventory } = fixture(); + inventory.issues = { Facility: { status: 403 }, Rack: { status: 502 } }; + const result = show(inventory); + expect(screen.getByText('Facility access denied')).toBeInTheDocument(); + expect(screen.getByText('Rack unavailable')).toBeInTheDocument(); + expect(result.container.textContent).not.toMatch(/Reported premises|Reported rack|premises-key|rack-key/); + expect(screen.getByRole('link', { name: 'Physical server' })).toBeInTheDocument(); + result.update({ ...inventory, issues: {}, physical: inventory.physical.filter(record => record.kind !== 'Facility' && record.kind !== 'Rack') }); + expect(screen.getByText('Facility reference missing')).toBeInTheDocument(); + expect(screen.getByText('Rack reference missing')).toBeInTheDocument(); + }); + + it('never substitutes claim placement or nominal model geometry', () => { + const { inventory, device } = fixture(); + delete device.spec.reportedPlacement; + inventory.slots.push({ key: `default/${device.spec.claimRef.name}`, claim: structuredClone(fixturePhysicalClaims[0]), devices: [device] }); + show(inventory); + const devices = within(screen.getByRole('region', { name: 'Manufacturer devices table' })); + expect(devices.getByRole('cell', { name: 'Not recorded' })).toBeInTheDocument(); + expect(devices.queryByText(/8U|Claim-derived/)).not.toBeInTheDocument(); + }); + + it('distinguishes empty records from unresolved and deleting references', () => { + const { inventory, manufacturer, model } = fixture(); + inventory.unboundDevices = []; + const result = show(inventory); + expect(screen.getByRole('cell', { name: '0' })).toBeInTheDocument(); + expect(screen.getByText('No devices explicitly linked to these device types.')).toBeInTheDocument(); + result.update({ ...inventory, physical: [manufacturer] }); + expect(screen.getByText('No device types linked to this manufacturer.')).toBeInTheDocument(); + const fresh = fixture(); + fresh.model.metadata.deletionTimestamp = '2026-11-22T00:00:00Z'; + expect(manufacturerInventory(fresh.manufacturer, fresh.inventory).unresolved).toBe(true); + model.metadata.namespace = 'elsewhere'; + expect(manufacturerInventory(manufacturer, inventory).models).toHaveLength(0); + }); + + it('uses display labels, fallback names and contextual duplicate identifiers', () => { + const { inventory, model, device } = fixture(); + inventory.physical.push({ ...model, metadata: { ...model.metadata, name: 'second-model' } }); + inventory.unboundDevices.push({ ...device, metadata: { ...device.metadata, name: 'second-device' } }); + show(inventory); + expect(screen.getByRole('link', { name: 'Physical server (device-key)' })).toBeInTheDocument(); + expect(screen.getByRole('link', { name: 'Physical server (second-device)' })).toBeInTheDocument(); + expect(screen.getAllByRole('link', { name: 'Compute model (model-key)' }).length).toBeGreaterThan(0); + expect(screen.getByRole('link', { name: 'Compute model (second-model)' })).toBeInTheDocument(); + }); + + it('uses fallback labels in the overview and picker without canonical-name substitution', () => { + const { inventory, manufacturer, model } = fixture(); + manufacturer.spec.displayName = ''; + model.spec.displayName = ''; + show(inventory); + expect(screen.getByRole('heading', { name: 'vendor-key' })).toBeInTheDocument(); + expect(screen.getAllByRole('link', { name: 'model-key' })).toHaveLength(2); + render( {}} namespace="default" claims={[]} devices={[]} feeds={[]} locations={[]} catalog={[manufacturer, model]} />); + expect(screen.getByRole('option', { name: 'vendor-key · model-key' })).toBeInTheDocument(); + }); + + it('preserves filters and history and adds no network reads or visible-focus effects', () => { + const { inventory } = fixture(); + const fetch = vi.fn(); + vi.stubGlobal('fetch', fetch); + show(inventory); + fireEvent.click(screen.getByRole('link', { name: '← Back to manufacturers' })); + expect(screen.getByRole('searchbox')).toHaveValue('Acme'); + expect(screen.queryByText('vendor-key')).not.toBeInTheDocument(); + fireEvent.click(screen.getByRole('link', { name: 'Acme hardware' })); + fireEvent.click(screen.getByRole('link', { name: 'Physical server' })); + fireEvent.click(screen.getByRole('button', { name: 'History back' })); + expect(screen.getByRole('region', { name: 'Manufacturer devices table' })).toBeInTheDocument(); + fireEvent.blur(window); + fireEvent.focus(window); + fireEvent.click(screen.getByRole('button', { name: 'History forward' })); + expect(screen.getByRole('heading', { name: 'Physical server' })).toBeInTheDocument(); + expect(fetch).not.toHaveBeenCalled(); + }); + + it('disambiguates picker choices only when display labels collide', () => { + const { manufacturer, model } = fixture(); + const secondManufacturer = { ...manufacturer, metadata: { ...manufacturer.metadata, name: 'other-vendor', uid: 'other-vendor-uid' } }; + const secondModel = { ...model, metadata: { ...model.metadata, name: 'other-model', uid: 'other-model-uid' } }; + const otherVendorModel = { ...model, metadata: { ...model.metadata, name: 'third-model', uid: 'third-model-uid' }, spec: { ...model.spec, manufacturerRef: { name: 'other-vendor' } } }; + render( {}} namespace="default" claims={[]} devices={[]} feeds={[]} locations={[]} catalog={[manufacturer, secondManufacturer, model, secondModel, otherVendorModel]} />); + expect(screen.getByRole('option', { name: 'Acme hardware (vendor-key) · Compute model (model-key)' })).toBeInTheDocument(); + expect(screen.getByRole('option', { name: 'Acme hardware (vendor-key) · Compute model (other-model)' })).toBeInTheDocument(); + expect(screen.getByRole('option', { name: 'Acme hardware (other-vendor) · Compute model' })).toBeInTheDocument(); + }); + + it('retains authorized devices when claims are denied and rejects foreign deep links', () => { + const { inventory, device } = fixture(); + inventory.unboundDevices = []; + inventory.slots.push({ key: 'default/plan', claim: structuredClone(fixturePhysicalClaims[0]), devices: [device] }); + inventory.issues = { DeviceClaim: { status: 403 } }; + const result = show(inventory); + expect(screen.getByRole('link', { name: 'Physical server' })).toBeInTheDocument(); + result.unmount(); + show(inventory, '?kind=Manufacturer&namespace=elsewhere&record=vendor-key'); + expect(screen.getByText(/only supports the default namespace/)).toBeInTheDocument(); + expect(screen.queryByRole('region', { name: 'Manufacturer devices table' })).not.toBeInTheDocument(); + }); +}); diff --git a/ui/provider/src/components/manufacturer-overview.tsx b/ui/provider/src/components/manufacturer-overview.tsx new file mode 100644 index 00000000..8fcf097a --- /dev/null +++ b/ui/provider/src/components/manufacturer-overview.tsx @@ -0,0 +1,55 @@ +import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from '@datum-cloud/datum-ui/table'; +import { Title } from '@datum-cloud/datum-ui/typography'; +import { Link } from 'react-router'; +import type { Device, PhysicalRecord } from '../../../shared/fleet-api'; +import type { Inventory, InventoryKind } from '../inventory'; +import { catalogLabel, manufacturerInventory } from '../lib/manufacturer-inventory'; +import { inventoryHref } from './inventory-location'; + +export function ManufacturerOverview({ manufacturer, inventory }: { manufacturer: PhysicalRecord; inventory: Inventory }) { + const { models, devices, unresolved } = manufacturerInventory(manufacturer, inventory); + if (manufacturer.metadata.deletionTimestamp) return

        Manufacturer is deleting; catalog relationships are unavailable, not empty.

        ; + const issue = (kind: InventoryKind) => inventory.issues?.[kind]; + const unavailable = (kind: InventoryKind) => issue(kind)?.status === 403 ? 'Access denied. Request inventory read access, then refresh.' : 'Records unavailable. Refresh inventory to retry; counts are unknown.'; + const link = (kind: string, record: PhysicalRecord | Device, peers: (PhysicalRecord | Device)[]) => {catalogLabel(record, peers)}; + const location = (device: Device) => { + const placement = device.spec.reportedPlacement; + if (!placement) return 'Not recorded'; + const reference = (kind: 'Facility' | 'Rack', name: string) => { + if (issue(kind)) return {kind} {issue(kind)?.status === 403 ? 'access denied' : 'unavailable'}; + const peers = inventory.physical.filter(record => record.kind === kind && record.metadata.namespace === device.metadata.namespace && !record.metadata.deletionTimestamp); + const target = peers.find(record => record.metadata.name === name); + return target ? link(kind, target, peers) : {kind} reference missing; + }; + return <>{placement.facilityRef && reference('Facility', placement.facilityRef.name)}{placement.facilityRef && placement.rackRef && ' · '}{placement.rackRef && reference('Rack', placement.rackRef.name)}{placement.position !== undefined && ` · U${placement.position}`}{placement.mount && ` · Mount: ${placement.mount}`}{placement.face && ` · ${placement.face}`}; + }; + return
        +
        + Overview +
        +
        Manufacturer
        {catalogLabel(manufacturer)}
        +
        Canonical name
        {manufacturer.spec.canonicalName || 'Not recorded'}
        +
        Descriptive aliases
        {manufacturer.spec.aliases?.join(' · ') || 'Not recorded'}
        +
        +

        Relationships use explicit catalog references in the default namespace, not recorded manufacturer text. Counts describe linked inventory records, not readiness or available capacity.

        +
        +
        + Device types + {issue('DeviceType') ?

        {unavailable('DeviceType')}

        : models.length ?
        Device typeAssociated devices{models.map(model => {link('DeviceType', model, models)}{issue('Device') ? 'Unknown' : devices.filter(entry => entry.model.metadata.name === model.metadata.name).length})}
        :

        No device types linked to this manufacturer.

        } +
        +
        + Devices + {issue('DeviceType') ?

        Device relationships unavailable until device types are readable. Counts are unknown.

        : issue('Device') ?

        {unavailable('Device')}

        : <> + {unresolved &&

        Some device type references are missing or deleting. Those devices cannot be attributed to a manufacturer; only resolved relationships are shown.

        } + {devices.length ?
        DeviceModelReported location{devices.map(({ device, model }) => {link('Device', device, devices.map(entry => entry.device))}{link('DeviceType', model, models)}{location(device)})}
        :

        {unresolved ? 'No resolved device relationships found.' : 'No devices explicitly linked to these device types.'}

        } +

        Locations come only from each device’s reported placement, never installation plans or catalog templates. Missing location references do not remove a device from the count.

        + } +
        +
        Technical details
        +
        Record name
        {manufacturer.metadata.name}
        +
        Namespace
        {manufacturer.metadata.namespace}
        +
        Resource UID
        {manufacturer.metadata.uid || 'Not recorded'}
        +
        Created
        {manufacturer.metadata.creationTimestamp || 'Not recorded'}
        +

        References follow namespace/name. Recreating a name does not verify physical continuity.

        +
        ; +} diff --git a/ui/provider/src/components/physical-inventory.tsx b/ui/provider/src/components/physical-inventory.tsx index 26a7e211..31a3d2fe 100644 --- a/ui/provider/src/components/physical-inventory.tsx +++ b/ui/provider/src/components/physical-inventory.tsx @@ -16,6 +16,8 @@ import { import type { CableEndpoint, PhysicalComponent, PhysicalRecord } from '../../../shared/fleet-api'; import './physical-inventory.css'; import { SiteOverview } from './site-overview'; +import { ManufacturerOverview } from './manufacturer-overview'; +import { catalogLabel } from '../lib/manufacturer-inventory'; import { InventoryAccessState } from './inventory-access-state'; import { InventoryManagement } from './inventory-management'; import { DevicePlacementEdit } from './device-placement-edit'; @@ -135,7 +137,7 @@ export function PhysicalInventory({ inventory: source, onRetry, showNavigation = if (inventory.issues?.[kind]) return Related record unavailable; const target = find(kind, namespace, name); return target ? ( - {recordName(target)} + {kind === 'Manufacturer' || kind === 'DeviceType' ? catalogLabel(target.record, entries.filter(entry => entry.kind === kind && entry.record.metadata.namespace === namespace).map(entry => entry.record)) : recordName(target)} ) : ( {name} (record not found) @@ -264,6 +266,7 @@ export function PhysicalInventory({ inventory: source, onRetry, showNavigation = function Detail({ entry }: { entry: RecordEntry }) { const { record, kind } = entry; if (kind === 'Site') return ; + if (kind === 'Manufacturer') return ; const namespace = record.metadata.namespace; const device = kind === 'Device' ? (record as RawDevice) : undefined; const catalog = device && deviceCatalog(device, inventory); @@ -323,10 +326,6 @@ export function PhysicalInventory({ inventory: source, onRetry, showNavigation = {kind === 'Facility' && } {kind === 'Rack' && }
        - {kind === 'Manufacturer' && <> - {physical?.spec.canonicalName} - {physical?.spec.aliases?.join(' · ')} - } {kind === 'DeviceType' && <> {physical?.spec.manufacturerRef && reference('Manufacturer', namespace, physical.spec.manufacturerRef.name)} {physical?.spec.model} @@ -606,7 +605,7 @@ export function PhysicalInventory({ inventory: source, onRetry, showNavigation = {placementEditor} {selected ? ( <> - {selected.kind !== 'Site' &&

        + {selected.kind !== 'Site' && selected.kind !== 'Manufacturer' &&

        {section.title} /{' '} {selected.record.metadata.name}

        } @@ -633,11 +632,11 @@ export function PhysicalInventory({ inventory: source, onRetry, showNavigation = ? 'Hardware' : 'Details'} - + {section.kind !== 'Manufacturer' && {section.kind === 'Cable' ? 'End A' : section.kind === 'Device' || section.kind === 'DeviceClaim' ? 'Location / Reported placement' : 'Location / reference'} - + } {(section.kind === 'Cable' || section.kind === 'Device') && {section.kind === 'Cable' ? 'End B' : 'Serial / asset tag'}} @@ -654,10 +653,10 @@ export function PhysicalInventory({ inventory: source, onRetry, showNavigation = > {recordName(entry)} - {entry.record.spec.displayName && {entry.record.metadata.name}} + {entry.record.spec.displayName && (entry.kind !== 'Manufacturer' && entry.kind !== 'DeviceType' || catalogLabel(entry.record, records.map(item => item.record)) !== recordName(entry)) && {entry.record.metadata.name}} {summary(entry)} - {entry.kind === 'Cable' ? (entry.record as PhysicalRecord).spec.lanes?.map(lane =>
        ) : entry.kind === 'Rack' && (entry.record as PhysicalRecord).spec.facilityRef ? reference('Facility', entry.record.metadata.namespace, (entry.record as PhysicalRecord).spec.facilityRef!.name) : placement(entry)}
        + {entry.kind !== 'Manufacturer' && {entry.kind === 'Cable' ? (entry.record as PhysicalRecord).spec.lanes?.map(lane =>
        ) : entry.kind === 'Rack' && (entry.record as PhysicalRecord).spec.facilityRef ? reference('Facility', entry.record.metadata.namespace, (entry.record as PhysicalRecord).spec.facilityRef!.name) : placement(entry)}
        } {(entry.kind === 'Cable' || entry.kind === 'Device') && {entry.kind === 'Cable' ? (entry.record as PhysicalRecord).spec.lanes?.map(lane =>
        ) : entry.kind === 'Device' ? ( <> diff --git a/ui/provider/src/lib/hardware-catalog.ts b/ui/provider/src/lib/hardware-catalog.ts index 2119f692..fedf5b0a 100644 --- a/ui/provider/src/lib/hardware-catalog.ts +++ b/ui/provider/src/lib/hardware-catalog.ts @@ -1,5 +1,6 @@ import type { Device, PhysicalRecord } from '../../../shared/fleet-api'; import { modelLabel, type Inventory } from '../inventory'; +import { catalogLabel } from './manufacturer-inventory'; export function deviceCatalog(device: Device, inventory: Inventory): { model: PhysicalRecord; manufacturer: PhysicalRecord } | undefined { if (!device.metadata.namespace || !device.spec.deviceTypeRef || inventory.issues?.DeviceType || inventory.issues?.Manufacturer) return; @@ -10,5 +11,7 @@ export function deviceCatalog(device: Device, inventory: Inventory): { model: Ph export function deviceModelLabel(device: Device, inventory: Inventory): string { const catalog = deviceCatalog(device, inventory); - return catalog ? `${catalog.manufacturer.spec.canonicalName} ${catalog.model.spec.displayName}` : modelLabel(device.spec.identity); + if (!catalog) return modelLabel(device.spec.identity); + const peers = inventory.physical.filter(record => record.metadata.namespace === device.metadata.namespace && !record.metadata.deletionTimestamp); + return `${catalogLabel(catalog.manufacturer, peers.filter(record => record.kind === 'Manufacturer'))} ${catalogLabel(catalog.model, peers.filter(record => record.kind === 'DeviceType' && record.spec.manufacturerRef?.name === catalog.manufacturer.metadata.name))}`; } diff --git a/ui/provider/src/lib/manufacturer-inventory.ts b/ui/provider/src/lib/manufacturer-inventory.ts new file mode 100644 index 00000000..ee25c0fb --- /dev/null +++ b/ui/provider/src/lib/manufacturer-inventory.ts @@ -0,0 +1,29 @@ +import type { Device, PhysicalRecord } from '../../../shared/fleet-api'; +import { slotKey, type Inventory } from '../inventory'; +import { INVENTORY_NAMESPACE } from './inventory-namespace'; + +type NamedRecord = { metadata: { name: string; namespace?: string }; spec: { displayName?: string } }; + +export function catalogLabel(record: NamedRecord, peers: NamedRecord[] = []): string { + const label = record.spec.displayName || record.metadata.name; + const ambiguous = peers.some(peer => slotKey(peer.metadata.namespace, peer.metadata.name) !== slotKey(record.metadata.namespace, record.metadata.name) && (peer.spec.displayName || peer.metadata.name) === label); + return ambiguous ? `${label} (${record.metadata.name})` : label; +} + +function unique(records: Record[]): Record[] { + return [...new Map(records.map(record => [slotKey(record.metadata.namespace, record.metadata.name), record])).values()]; +} + +export function manufacturerInventory(manufacturer: PhysicalRecord, inventory: Inventory) { + const namespace = manufacturer.metadata.namespace; + const readable = namespace === INVENTORY_NAMESPACE && !manufacturer.metadata.deletionTimestamp && !inventory.issues?.Manufacturer; + const models = readable && !inventory.issues?.DeviceType ? unique(inventory.physical.filter(record => record.kind === 'DeviceType' && record.metadata.namespace === namespace && !record.metadata.deletionTimestamp)) : []; + const linkedModels = models.filter(model => model.spec.manufacturerRef?.name === manufacturer.metadata.name); + const devices = readable && !inventory.issues?.Device && !inventory.issues?.DeviceType ? unique([...inventory.slots.flatMap(slot => slot.devices), ...inventory.unboundDevices].filter(device => device.metadata.namespace === namespace && !device.metadata.deletionTimestamp)) : []; + const related: { device: Device; model: PhysicalRecord }[] = devices.flatMap(device => { + const model = linkedModels.find(candidate => candidate.metadata.name === device.spec.deviceTypeRef?.name); + return model ? [{ device, model }] : []; + }); + const unresolved = devices.some(device => device.spec.deviceTypeRef && !models.some(model => model.metadata.name === device.spec.deviceTypeRef?.name)); + return { models: linkedModels, devices: related, unresolved }; +} diff --git a/ui/provider/src/pages/device-inventory.test.tsx b/ui/provider/src/pages/device-inventory.test.tsx index 8e1f67ad..a408d447 100644 --- a/ui/provider/src/pages/device-inventory.test.tsx +++ b/ui/provider/src/pages/device-inventory.test.tsx @@ -42,6 +42,13 @@ const inventory = toInventory(fixtureDeviceClaims, fixtureDevices); beforeEach(() => useInventoryMock.mockReset()); describe('DeviceInventoryList', () => { + it('keeps manufacturer deep links in loading state without claiming empty relationships', () => { + mockInventory({ isLoading: true }); + renderAt('/plugins/metal-datumapis-com/inventory?kind=Manufacturer&namespace=default&record=private-vendor'); + expect(screen.getByTestId('fleet-plugin-loading')).toBeInTheDocument(); + expect(screen.queryByText(/No device types linked|No devices explicitly linked|private-vendor/)).not.toBeInTheDocument(); + }); + it('marks the Inventory tab active', () => { mockInventory({ data: inventory }); renderAt('/plugins/metal-datumapis-com/inventory'); From 4e383d22627b66d6a610a30eb5ed95ec37088d29 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sun, 22 Nov 2026 12:43:59 -0600 Subject: [PATCH 068/518] Bound inventory admission fences per device incarnation --- .github/workflows/publish.yml | 1 + .../inventory-capacity-registration.md | 70 +++++- internal/registration/admission.go | 32 ++- .../admission_regression_envtest_test.go | 169 ++++++++++++++- internal/registration/bounded_fences_test.go | 200 ++++++++++++++++++ internal/registration/bundle_test.go | 91 ++++++++ .../registration/contention_envtest_test.go | 112 ++++++++++ 7 files changed, 665 insertions(+), 10 deletions(-) create mode 100644 internal/registration/bounded_fences_test.go create mode 100644 internal/registration/bundle_test.go create mode 100644 internal/registration/contention_envtest_test.go diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 2ada75ca..53cd39c7 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -63,6 +63,7 @@ jobs: bundle-path: config images: | - { path: config/base/manager, name: ghcr.io/datum-cloud/fleet, tag: "${{ needs.publish-container-image.outputs.tag }}" } + - { path: config/base/registration, name: ghcr.io/datum-cloud/fleet, tag: "${{ needs.publish-container-image.outputs.tag }}" } - { path: config/overlays/synthetic-staging, name: ghcr.io/datum-cloud/fleet, tag: "${{ needs.publish-container-image.outputs.tag }}" } - { path: config/components/consumer-ui-plugin, name: ghcr.io/datum-cloud/fleet-consumer-ui-plugin, tag: "${{ needs.publish-consumer-ui-plugin-image.outputs.tag }}" } - { path: config/components/provider-ui-plugin, name: ghcr.io/datum-cloud/fleet-provider-ui-plugin, tag: "${{ needs.publish-provider-ui-plugin-image.outputs.tag }}" } diff --git a/docs/development/inventory-capacity-registration.md b/docs/development/inventory-capacity-registration.md index 2def3da5..a6a6078e 100644 --- a/docs/development/inventory-capacity-registration.md +++ b/docs/development/inventory-capacity-registration.md @@ -139,9 +139,28 @@ and registered-spec checks. Any differing field still takes the conservative fencing path. An uncertain potentially changing update can therefore leave its old version ineligible even if storage ultimately made no change. Failed Device creates can likewise retain an alias reservation. -The fix does not erase fences retained by older builds: those cannot be safely -distinguished from unfinished real updates. Recovery still requires a genuine -persisted change and explicit new selection, not automatic ledger cleanup. +Update fences are coalesced to one record per provider Project and Device UID, +not one per observation. Before replacing a retained version, admission reads +the Device directly through the uncached project client and requires the current +UID and resourceVersion to equal both incoming update incarnations/baselines. +It rejects stale admissions rather than replacing a newer pending fence. The +ledger snapshot precedes that authoritative read; a competing ledger write +forces a full CAS retry and another Device read. All concurrent updates at the +same baseline share its fence. Once the API server has persisted a newer version, +optimistic concurrency prevents an older-baseline write from subsequently +committing; an API-server storage retry must re-enter admission at its new +baseline. Thus superseded fences can be compacted without allowing an unfinished +current-baseline update to race registration. ResourceVersions are compared only +for equality, never ordered numerically. + +Coalescing unions creation aliases and never clears a deletion tombstone. +A deletion replaces update history with a permanent all-version tombstone; +later changing updates for that UID are rejected. Older-build multiple-version +records are compacted only when this same authoritative update check succeeds, +or when deletion installs a stronger permanent tombstone. Unrelated incarnations +are untouched. An unknown/rejected write at the still-current version stays +fenced, including after restart and no-op updates. Recovery still requires a +genuine persisted change and explicit new selection, not automatic ledger cleanup. The selected Device's own successful creation reservation is not a conflict. Identity/provider-alias changes are forbidden; registered Device specs are frozen, and its deletion and same-name replacement are forbidden. The default @@ -157,7 +176,22 @@ CAS conflicts leave evidence retained for a later observation. Repeating POST is not the recovery mechanism: inspect the original name and retained operation. Reservations and tombstones have no automatic expiry or release path in stage 1. -The bounded ledger refuses growth past 750,000 encoded bytes. Lost or corrupt +This deliberately includes create attempts that never persisted and deleted +Devices that were never registered: their known hardware aliases remain reserved, +and recreating that hardware under a new UID fails closed. Stage 1 has no safe +operator release command. Future reconciliation must prove the original outcome, +all competing operations and lifetime ownership before designing a fenced release; +neither manual Secret editing nor speculative expiry is an accepted workaround. + +Routine updates to an incarnation use one record with at most one pending +resourceVersion, retained aliases and a deletion bit. This bounds growth by +distinct incarnations/aliases and registration operations, **not** by elapsed +collector observations. It is not an unlimited-inventory or universal deduplication +guarantee: retained incarnations and reservations can still fill the pilot ledger. +The ledger refuses growth past 750,000 encoded bytes (the boundary itself fits). +Admission makes at most six CAS attempts with complete reevaluation after conflicts; +exhaustion emits a structured error with project, operation identity and attempt +count, without actor credentials or ledger contents. Lost or corrupt ledger state, scope changes, uncertain operations and full ledgers require operator-led reconciliation/migration; deleting or recreating the ledger is not a repair. Ledger update protection and private-namespace deletion protection @@ -295,6 +329,31 @@ components and mocked transport. Run the existing Go/envtest, race, vet, provider/consumer test/typecheck/build, manifest-isolation and documentation checks described in the [development guide](README.md#build-test-and-run). +Boundedness regressions perform 120 successive persisted collector observations +and 120 metadata updates through the packaged webhook, assert one incarnation +fence and stable ledger size, then register the current selection and recover it +to `Recorded`. The disposable Device CRD adds a test-only integer status observation +because the current production `DeviceStatus` is empty; this exercises real +`/status` storage and admission without inventing a production collector API. +Deterministic interleavings retain a newer pending fence while stale admission +retries, and keep unknown/rejected baselines fenced across restart/no-op requests. +An envtest race pauses two admitted updates at successive resourceVersions: after +coalescing, the older in-flight update conflicts at actual API-server storage, +the newer pending version remains unregistrable, and only its persisted successor +can be explicitly selected and recorded. +Real API-server Secret conflicts exercise success after five conflicts and six-conflict +exhaustion/logging. Separate tests assert the exact size boundary and effect-free +dry-run denial. + +The publishing workflow applies the server build tag to `config/base/registration`, +as it does to the manager. A regression reads the workflow's image transforms, +applies them to a temporary config tree, and renders the management-plane bundle +to assert that `/fleet-registration` uses the published server image tag rather +than `latest`. It also verifies registration remains absent from synthetic staging. +Raw source manifests still contain template `latest` references: direct deployment +must supply equivalent immutable build-tag or digest transforms, plus the required +trust/credential configuration. No published bundle or live deployment was tested. + ### Review-fix validation, November 22, 2026 - Full `go test -race ./...` with Kubernetes 1.37.0 envtest assets, `go vet ./...`, @@ -304,5 +363,8 @@ checks described in the [development guide](README.md#build-test-and-run). passed on a full rerun without modifying UI code or reviewer tests. - Production and synthetic manifest renders, overlay isolation tests, standalone/synthetic render checks, documentation links and whitespace pass. +- The bounded-fencing rework adds real delayed-update and Secret-contention races, + exact-size/dry-run guards, repeated status-write bounds, and rendered publishing + image-transform checks. The original reviewer reproduction remains byte-identical. - These are local checks, not live Milo acceptance or independent re-review. No deployment, merge, live resource mutation, or ledger migration was performed. diff --git a/internal/registration/admission.go b/internal/registration/admission.go index 5a146b70..8168a1e2 100644 --- a/internal/registration/admission.go +++ b/internal/registration/admission.go @@ -9,6 +9,7 @@ import ( "errors" "fmt" "io" + "log/slog" "reflect" "regexp" "slices" @@ -121,6 +122,9 @@ func (handler *Handler) Handle(ctx context.Context, request admission.Request) a } } if err != nil { + if apierrors.IsConflict(err) { + slog.ErrorContext(ctx, "registration ledger CAS retries exhausted", "attempts", 6, "project", name, "operation", request.UID) + } return admission.Denied(err.Error()) } return admission.Allowed("inert inventory registration only; no availability or preparation authority") @@ -355,6 +359,13 @@ func (handler *Handler) device(ctx context.Context, project Project, request adm } fence := DeviceFence{Project: project.Identity.RouteName, UID: device.UID, Deleted: request.Operation == admissionv1.Delete} if request.Operation == admissionv1.Update { + current := &inventory.Device{} + if err := project.Client.Get(ctx, client.ObjectKeyFromObject(&old), current); err != nil { + return err + } + if current.UID != old.UID || current.ResourceVersion != old.ResourceVersion || device.ResourceVersion != old.ResourceVersion || !current.DeletionTimestamp.IsZero() { + return errors.New("Device update baseline is no longer current") + } fence.Version = old.ResourceVersion } if request.Operation == admissionv1.Create { @@ -365,12 +376,27 @@ func (handler *Handler) device(ctx context.Context, project Project, request adm } } } + coalesced := make([]DeviceFence, 0, len(ledger.DeviceFences)+1) for _, retained := range ledger.DeviceFences { - if reflect.DeepEqual(retained, fence) { - return nil + if retained.Project != fence.Project || retained.UID != fence.UID { + coalesced = append(coalesced, retained) + continue } + if (retained.Deleted && !fence.Deleted) || (request.Operation == admissionv1.Create && !reflect.DeepEqual(retained, fence)) { + return ErrConflict + } + for _, alias := range retained.Aliases { + if !slices.Contains(fence.Aliases, alias) { + fence.Aliases = append(fence.Aliases, alias) + } + } + } + slices.Sort(fence.Aliases) + coalesced = append(coalesced, fence) + if reflect.DeepEqual(ledger.DeviceFences, coalesced) { + return nil } - ledger.DeviceFences = append(ledger.DeviceFences, fence) + ledger.DeviceFences = coalesced return handler.Store.Write(ctx, secret, ledger) } diff --git a/internal/registration/admission_regression_envtest_test.go b/internal/registration/admission_regression_envtest_test.go index b07b2b97..0fe71ef5 100644 --- a/internal/registration/admission_regression_envtest_test.go +++ b/internal/registration/admission_regression_envtest_test.go @@ -3,10 +3,12 @@ package registration import ( "context" "encoding/json" + "fmt" "net/http/httptest" "os" "path/filepath" "strings" + "sync" "testing" "time" @@ -15,12 +17,14 @@ import ( "go.datum.net/fleet/internal/controller" iam "go.miloapis.com/milo/pkg/apis/iam/v1alpha1" resourcemanager "go.miloapis.com/milo/pkg/apis/resourcemanager/v1alpha1" + admissionv1 "k8s.io/api/admission/v1" admissionregistrationv1 "k8s.io/api/admissionregistration/v1" authorizationv1 "k8s.io/api/authorization/v1" corev1 "k8s.io/api/core/v1" extensions "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" "k8s.io/client-go/rest" "sigs.k8s.io/controller-runtime/pkg/client" @@ -56,9 +60,22 @@ func TestRealNoopRegistrationAndScopedTransportFailure(t *testing.T) { if err != nil { t.Fatal(err) } + if err := extensions.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + deviceCRD := &extensions.CustomResourceDefinition{} + if err := api.Get(ctx, client.ObjectKey{Name: "devices.fleet.datumapis.com"}, deviceCRD); err != nil { + t.Fatal(err) + } + deviceCRD.Spec.Versions[0].Schema.OpenAPIV3Schema.Properties["status"] = extensions.JSONSchemaProps{Type: "object", Properties: map[string]extensions.JSONSchemaProps{"observation": {Type: "integer"}}} + if err := api.Update(ctx, deviceCRD); err != nil { + t.Fatal(err) + } devices := []*inventory.Device{ {ObjectMeta: metav1.ObjectMeta{Name: "noop-hardware", Namespace: "default"}, Spec: inventory.DeviceSpec{ClaimRef: inventory.LocalReference{Name: "installation"}, Identity: inventory.DeviceIdentity{Model: "test", Serial: "noop-serial", SystemUUID: "11111111-1111-1111-1111-111111111111"}}}, {ObjectMeta: metav1.ObjectMeta{Name: "real-edit-hardware", Namespace: "default"}, Spec: inventory.DeviceSpec{ClaimRef: inventory.LocalReference{Name: "installation"}, Identity: inventory.DeviceIdentity{Model: "test", Serial: "edit-serial", SystemUUID: "22222222-2222-2222-2222-222222222222"}}}, + {ObjectMeta: metav1.ObjectMeta{Name: "collector-hardware", Namespace: "default"}, Spec: inventory.DeviceSpec{ClaimRef: inventory.LocalReference{Name: "installation"}, Identity: inventory.DeviceIdentity{Model: "test", Serial: "collector-serial", SystemUUID: "33333333-3333-3333-3333-333333333333"}}}, + {ObjectMeta: metav1.ObjectMeta{Name: "concurrent-hardware", Namespace: "default"}, Spec: inventory.DeviceSpec{ClaimRef: inventory.LocalReference{Name: "installation"}, Identity: inventory.DeviceIdentity{Model: "test", Serial: "concurrent-serial", SystemUUID: "44444444-4444-4444-4444-444444444444"}}}, } for _, device := range devices { if err := api.Create(ctx, device, client.FieldOwner("review")); err != nil { @@ -80,7 +97,32 @@ func TestRealNoopRegistrationAndScopedTransportFailure(t *testing.T) { handler := &Handler{Store: Store{Client: api, Namespace: "default", Authority: "milo", Projects: []string{"datum-cloud"}}, VerifyFence: func(ctx context.Context) error { return VerifyFence(ctx, api, []string{"datum-cloud"}) }, Resolve: func(context.Context, string) (Project, error) { return Project{Identity: controller.ProjectIdentity{AuthorityID: "milo", RouteName: "datum-cloud", UID: "project-1"}, Client: api}, nil }, Authorize: Authorize} - server := httptest.NewTLSServer(&admission.Webhook{Handler: handler}) + type gate struct { + entered, release chan struct{} + once sync.Once + } + gates := map[string]*gate{ + "first": {entered: make(chan struct{}), release: make(chan struct{})}, + "second": {entered: make(chan struct{}), release: make(chan struct{})}, + } + server := httptest.NewTLSServer(&admission.Webhook{Handler: admission.HandlerFunc(func(ctx context.Context, request admission.Request) admission.Response { + response := handler.Handle(ctx, request) + if response.Allowed && request.Operation == admissionv1.Update && request.Resource.Resource == "devices" && request.Name == "concurrent-hardware" { + var device inventory.Device + if json.Unmarshal(request.Object.Raw, &device) == nil { + if pending := gates[device.Labels["admission-delay"]]; pending != nil { + pending.once.Do(func() { + close(pending.entered) + select { + case <-pending.release: + case <-ctx.Done(): + } + }) + } + } + } + return response + })}) t.Cleanup(server.Close) data, err := os.ReadFile("../../config/components/registration-admission/webhook.yaml") if err != nil { @@ -176,12 +218,133 @@ func TestRealNoopRegistrationAndScopedTransportFailure(t *testing.T) { t.Fatal(err) } }) + t.Run("repeated-status-and-metadata-writes-remain-bounded", func(t *testing.T) { + device := devices[2] + var initialSize int + for observation := 1; observation <= 120; observation++ { + if err := actor.Get(ctx, client.ObjectKeyFromObject(device), device); err != nil { + t.Fatal(err) + } + device.Labels = map[string]string{"observation": fmt.Sprint(observation)} + if err := actor.Update(ctx, device); err != nil { + t.Fatal(err) + } + current := &unstructured.Unstructured{} + current.SetAPIVersion("fleet.datumapis.com/v1alpha1") + current.SetKind("Device") + if err := actor.Get(ctx, client.ObjectKeyFromObject(device), current); err != nil { + t.Fatal(err) + } + before := current.GetResourceVersion() + current.Object["status"] = map[string]any{"observation": int64(observation)} + if err := actor.Status().Update(ctx, current, client.FieldOwner("inventory-collector")); err != nil { + t.Fatal(err) + } + if before == current.GetResourceVersion() { + t.Fatal("status observation did not persist") + } + secret, ledger, err := handler.Store.Read(ctx) + if err != nil { + t.Fatal(err) + } + count := 0 + for _, fence := range ledger.DeviceFences { + if fence.UID == device.UID { + count++ + } + } + if count != 1 { + t.Fatalf("%d fences after %d observations", count, observation) + } + if observation == 1 { + initialSize = len(secret.Data["ledger.json"]) + } + if len(secret.Data["ledger.json"]) > initialSize+20 { + t.Fatal("ledger grows with routine observations") + } + } + if err := actor.Get(ctx, client.ObjectKeyFromObject(device), device); err != nil { + t.Fatal(err) + } + if err := register(t, device, "after-collector"); err != nil { + t.Fatal(err) + } + }) + t.Run("delayed-old-write-cannot-commit-after-coalescing", func(t *testing.T) { + firstRelease := sync.OnceFunc(func() { close(gates["first"].release) }) + secondRelease := sync.OnceFunc(func() { close(gates["second"].release) }) + defer firstRelease() + defer secondRelease() + wait := func(pending *gate) { + t.Helper() + select { + case <-pending.entered: + case <-time.After(5 * time.Second): + t.Fatal("pending update did not enter admission") + } + } + device := devices[3] + first := device.DeepCopyObject().(*inventory.Device) + first.Labels = map[string]string{"admission-delay": "first"} + firstDone := make(chan error, 1) + go func() { firstDone <- actor.Update(ctx, first) }() + wait(gates["first"]) + device.Labels = map[string]string{"competing": "persisted"} + if err := actor.Update(ctx, device); err != nil { + t.Fatal(err) + } + currentVersion := device.ResourceVersion + second := device.DeepCopyObject().(*inventory.Device) + second.Labels = map[string]string{"admission-delay": "second"} + secondDone := make(chan error, 1) + go func() { secondDone <- actor.Update(ctx, second) }() + wait(gates["second"]) + firstRelease() + if err := <-firstDone; !apierrors.IsConflict(err) { + t.Fatalf("old in-flight baseline must conflict at storage: %v", err) + } + if err := actor.Get(ctx, client.ObjectKeyFromObject(device), device); err != nil { + t.Fatal(err) + } + if device.ResourceVersion != currentVersion { + t.Fatal("old in-flight write changed current version") + } + if err := register(t, device, "during-second-pending"); !apierrors.IsForbidden(err) { + t.Fatalf("coalescing lost current pending fence: %v", err) + } + _, ledger, err := handler.Store.Read(ctx) + if err != nil { + t.Fatal(err) + } + count := 0 + for _, fence := range ledger.DeviceFences { + if fence.UID == device.UID { + count++ + if fence.Version != currentVersion { + t.Fatal("retained wrong pending version") + } + } + } + if count != 1 { + t.Fatalf("concurrent versions created %d fences", count) + } + secondRelease() + if err := <-secondDone; err != nil { + t.Fatal(err) + } + if err := actor.Get(ctx, client.ObjectKeyFromObject(device), device); err != nil { + t.Fatal(err) + } + if err := register(t, device, "after-concurrent-writes"); err != nil { + t.Fatal(err) + } + }) if err := handler.Recover(ctx); err != nil { t.Fatal(err) } _, ledger, err := handler.Store.Read(ctx) - if err != nil || len(ledger.Entries) != 2 { - t.Fatalf("expected both registrations: %+v %v", ledger, err) + if err != nil || len(ledger.Entries) != 4 { + t.Fatalf("expected all registrations: %+v %v", ledger, err) } for _, entry := range ledger.Entries { if entry.Outcome != "Recorded" || entry.CapacityUID == "" { diff --git a/internal/registration/bounded_fences_test.go b/internal/registration/bounded_fences_test.go new file mode 100644 index 00000000..1dbd19a0 --- /dev/null +++ b/internal/registration/bounded_fences_test.go @@ -0,0 +1,200 @@ +package registration + +import ( + "context" + "encoding/json" + "strings" + "testing" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + admissionv1 "k8s.io/api/admission/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/webhook/admission" +) + +func deviceUpdate(t *testing.T, device *inventory.Device) admission.Request { + t.Helper() + request := registrationRequest(t, device, "unused") + request.Resource = metav1.GroupVersionResource{Group: "fleet.datumapis.com", Version: "v1alpha1", Resource: "devices"} + request.Name = device.Name + request.Operation = admissionv1.Update + request.OldObject.Raw, _ = json.Marshal(device) + changed := device.DeepCopyObject().(*inventory.Device) + changed.Labels = map[string]string{"observation": "changed"} + request.Object.Raw, _ = json.Marshal(changed) + return request +} + +func TestCoalescingRetainsPendingAndUnknownVersions(t *testing.T) { + ctx := context.Background() + handler, device := fixture(t) + project, _ := handler.Resolve(ctx, "provider") + oldRequest := deviceUpdate(t, device) + for attempt := 0; attempt < 10; attempt++ { + if response := handler.Handle(ctx, oldRequest); !response.Allowed { + t.Fatal(response.Result) + } + } + if handler.Handle(ctx, registrationRequest(t, device, "pending-first")).Allowed { + t.Fatal("pending concurrent updates did not fence current version") + } + device.Labels = map[string]string{"committed": "first"} + if err := project.Client.Update(ctx, device); err != nil { + t.Fatal(err) + } + newRequest := deviceUpdate(t, device) + if response := handler.Handle(ctx, newRequest); !response.Allowed { + t.Fatal(response.Result) + } + if handler.Handle(ctx, oldRequest).Allowed { + t.Fatal("late stale admission replaced the current pending fence") + } + _, ledger, err := handler.Store.Read(ctx) + if err != nil || len(ledger.DeviceFences) != 1 || ledger.DeviceFences[0].Version != device.ResourceVersion { + t.Fatalf("not coalesced at current pending baseline: %+v %v", ledger, err) + } + restarted := *handler + if restarted.Handle(ctx, registrationRequest(t, device, "unknown-second")).Allowed { + t.Fatal("unknown or rejected write released after restart") + } + noop := newRequest + noop.Object = noop.OldObject + if !restarted.Handle(ctx, noop).Allowed || restarted.Handle(ctx, registrationRequest(t, device, "after-noop")).Allowed { + t.Fatal("no-op must neither fail nor release a pending baseline") + } + device.Labels["committed"] = "second" + if err := project.Client.Update(ctx, device); err != nil { + t.Fatal(err) + } + if response := restarted.Handle(ctx, registrationRequest(t, device, "fresh")); !response.Allowed { + t.Fatal(response.Result) + } +} + +func TestCoalescingLegacyFencesPreservesAliasesAndTombstones(t *testing.T) { + ctx := context.Background() + handler, device := fixture(t) + secret, ledger, _ := handler.Store.Read(ctx) + ledger.DeviceFences = []DeviceFence{ + {Project: "provider", UID: device.UID, Aliases: aliases(device)}, + {Project: "provider", UID: device.UID, Version: "older"}, + {Project: "provider", UID: device.UID, Version: device.ResourceVersion}, + {Project: "other", UID: device.UID, Version: "unrelated"}, + } + if err := handler.Store.Write(ctx, secret, ledger); err != nil { + t.Fatal(err) + } + update := deviceUpdate(t, device) + if response := handler.Handle(ctx, update); !response.Allowed { + t.Fatal(response.Result) + } + _, ledger, _ = handler.Store.Read(ctx) + if len(ledger.DeviceFences) != 2 || len(ledger.DeviceFences[1].Aliases) != len(aliases(device)) || ledger.DeviceFences[0].Project != "other" { + t.Fatalf("lost aliases or unrelated fences: %+v", ledger) + } + deletion := update + deletion.Operation = admissionv1.Delete + if !handler.Handle(ctx, deletion).Allowed || handler.Handle(ctx, update).Allowed { + t.Fatal("delete must permanently dominate pending update fences") + } + create := update + create.Operation = admissionv1.Create + recreated := device.DeepCopyObject().(*inventory.Device) + recreated.UID = "recreated" + create.Object.Raw, _ = json.Marshal(recreated) + if handler.Handle(ctx, create).Allowed { + t.Fatal("never-registered deleted hardware aliases were released") + } + _, ledger, _ = handler.Store.Read(ctx) + if len(ledger.DeviceFences) != 2 || !ledger.DeviceFences[1].Deleted || ledger.DeviceFences[1].Version != "" { + t.Fatalf("delete did not coalesce into permanent tombstone: %+v", ledger) + } +} + +func TestLedgerExactSizeCap(t *testing.T) { + ctx := context.Background() + handler, _ := fixture(t) + secret, ledger, _ := handler.Store.Read(ctx) + ledger.DeviceFences = []DeviceFence{{Project: "provider", UID: "device", Aliases: []string{""}}} + encoded, _ := json.Marshal(ledger) + ledger.DeviceFences[0].Aliases[0] = strings.Repeat("x", 750000-len(encoded)) + if err := handler.Store.Write(ctx, secret, ledger); err != nil { + t.Fatalf("exactly 750000 bytes must fit: %v", err) + } + before := secret.ResourceVersion + ledger.DeviceFences[0].Aliases[0] += "x" + if err := handler.Store.Write(ctx, secret, ledger); err == nil || !strings.Contains(err.Error(), "ledger is full") { + t.Fatalf("750001 bytes must fail closed: %v", err) + } + current, _, err := handler.Store.Read(ctx) + if err != nil || current.ResourceVersion != before || len(current.Data["ledger.json"]) != 750000 { + t.Fatal("oversized write changed durable reservations") + } +} + +func TestDryRunCannotReserve(t *testing.T) { + ctx := context.Background() + handler, device := fixture(t) + before, _, _ := handler.Store.Read(ctx) + for _, request := range []admission.Request{registrationRequest(t, device, "dry"), deviceUpdate(t, device)} { + dry := true + request.DryRun = &dry + if response := handler.Handle(ctx, request); response.Allowed || !strings.Contains(response.Result.Message, "dry-run") { + t.Fatalf("dry run was not explicitly denied: %+v", response) + } + } + after, ledger, _ := handler.Store.Read(ctx) + if before.ResourceVersion != after.ResourceVersion || len(ledger.Entries) != 0 || len(ledger.DeviceFences) != 0 { + t.Fatal("dry-run retained effects") + } + project, _ := handler.Resolve(ctx, "provider") + if err := project.Client.Get(ctx, client.ObjectKeyFromObject(device), device); err != nil || device.ResourceVersion != "1" { + t.Fatal("dry-run changed Device") + } +} + +type afterDeviceReadClient struct { + client.Client + after func() +} + +func (api *afterDeviceReadClient) Get(ctx context.Context, key client.ObjectKey, object client.Object, options ...client.GetOption) error { + err := api.Client.Get(ctx, key, object, options...) + if _, device := object.(*inventory.Device); err == nil && device && api.after != nil { + after := api.after + api.after = nil + after() + } + return err +} + +func TestConcurrentNewerPendingFenceForcesBaselineRecheck(t *testing.T) { + ctx := context.Background() + handler, device := fixture(t) + project, _ := handler.Resolve(ctx, "provider") + oldRequest := deviceUpdate(t, device) + interleaved := &afterDeviceReadClient{Client: project.Client} + interleaved.after = func() { + device.Labels = map[string]string{"committed": "first"} + if err := project.Client.Update(ctx, device); err != nil { + t.Fatal(err) + } + if response := handler.Handle(ctx, deviceUpdate(t, device)); !response.Allowed { + t.Fatal(response.Result) + } + } + handler.Resolve = func(context.Context, string) (Project, error) { + return Project{Identity: project.Identity, Client: interleaved}, nil + } + if handler.Handle(ctx, oldRequest).Allowed { + t.Fatal("stale admission survived newer pending fence CAS") + } + _, ledger, err := handler.Store.Read(ctx) + if err != nil || len(ledger.DeviceFences) != 1 || ledger.DeviceFences[0].Version != device.ResourceVersion { + t.Fatalf("newer pending fence lost: %+v %v", ledger, err) + } + if handler.Handle(ctx, registrationRequest(t, device, "still-pending")).Allowed { + t.Fatal("newer pending version became registrable") + } +} diff --git a/internal/registration/bundle_test.go b/internal/registration/bundle_test.go new file mode 100644 index 00000000..3e068d2d --- /dev/null +++ b/internal/registration/bundle_test.go @@ -0,0 +1,91 @@ +package registration + +import ( + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + + "sigs.k8s.io/yaml" +) + +func TestPublishedBundlePinsRegistrationImage(t *testing.T) { + kustomize, err := exec.LookPath("kustomize") + if err != nil { + t.Skip("kustomize required") + } + root := filepath.Join("..", "..") + data, err := os.ReadFile(filepath.Join(root, ".github", "workflows", "publish.yml")) + if err != nil { + t.Fatal(err) + } + var workflow struct { + Jobs map[string]struct{ With struct{ Images string } } + } + if err := yaml.Unmarshal(data, &workflow); err != nil { + t.Fatal(err) + } + var images []struct{ Path, Name, Tag string } + if err := yaml.UnmarshalStrict([]byte(workflow.Jobs["publish-kustomize-bundle"].With.Images), &images); err != nil { + t.Fatal(err) + } + temporary := t.TempDir() + if err := os.CopyFS(filepath.Join(temporary, "config"), os.DirFS(filepath.Join(root, "config"))); err != nil { + t.Fatal(err) + } + const pinnedTag = "sha-0123456789abcdef" + registrationTransform := false + for _, image := range images { + if image.Path == "config/base/registration" { + registrationTransform = image.Name == "ghcr.io/datum-cloud/fleet" && image.Tag == "${{ needs.publish-container-image.outputs.tag }}" + } + command := exec.Command(kustomize, "edit", "set", "image", image.Name+"="+image.Name+":"+pinnedTag) + command.Dir = filepath.Join(temporary, image.Path) + if output, err := command.CombinedOutput(); err != nil { + t.Fatalf("bundle transform: %v\n%s", err, output) + } + } + if !registrationTransform { + t.Fatal("registration is not pinned to the published server build") + } + for _, overlay := range []string{"management-plane", "synthetic-staging"} { + output, err := exec.Command(kustomize, "build", filepath.Join(temporary, "config", "overlays", overlay)).CombinedOutput() + if err != nil { + t.Fatalf("render %s: %v\n%s", overlay, err, output) + } + found := false + for _, document := range strings.Split(string(output), "\n---\n") { + var deployment struct { + Kind string + Spec struct { + Template struct { + Spec struct { + Containers []struct { + Command []string + Image string + } + } + } + } + } + if err := yaml.Unmarshal([]byte(document), &deployment); err != nil { + t.Fatal(err) + } + if deployment.Kind != "Deployment" { + continue + } + for _, container := range deployment.Spec.Template.Spec.Containers { + if len(container.Command) > 0 && container.Command[0] == "/fleet-registration" { + found = true + if container.Image != "ghcr.io/datum-cloud/fleet:"+pinnedTag { + t.Fatalf("%s registration image is %s", overlay, container.Image) + } + } + } + } + if found != (overlay == "management-plane") { + t.Fatalf("%s registration deployment presence violates isolation: %v", overlay, found) + } + } +} diff --git a/internal/registration/contention_envtest_test.go b/internal/registration/contention_envtest_test.go new file mode 100644 index 00000000..f6862092 --- /dev/null +++ b/internal/registration/contention_envtest_test.go @@ -0,0 +1,112 @@ +package registration + +import ( + "bytes" + "context" + "fmt" + "log/slog" + "os" + "strings" + "testing" + + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/envtest" +) + +type contendedLedgerClient struct { + client.Client + remaining int + attempts int + conflicts int +} + +func (contender *contendedLedgerClient) Update(ctx context.Context, object client.Object, options ...client.UpdateOption) error { + contender.attempts++ + if contender.remaining > 0 { + contender.remaining-- + completed := make(chan error, 1) + go func() { + current := &corev1.Secret{} + if err := contender.Client.Get(ctx, client.ObjectKeyFromObject(object), current); err != nil { + completed <- err + return + } + current.Annotations = map[string]string{"competing-writer": fmt.Sprint(contender.attempts)} + completed <- contender.Client.Update(ctx, current) + }() + if err := <-completed; err != nil { + return err + } + } + err := contender.Client.Update(ctx, object, options...) + if apierrors.IsConflict(err) { + contender.conflicts++ + } + return err +} + +func TestRealLedgerCASRetryBudget(t *testing.T) { + if os.Getenv("KUBEBUILDER_ASSETS") == "" { + t.Skip("KUBEBUILDER_ASSETS required") + } + environment := &envtest.Environment{} + config, err := environment.Start() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if err := environment.Stop(); err != nil { + t.Error(err) + } + }) + scheme := runtime.NewScheme() + if err := corev1.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + api, err := client.New(config, client.Options{Scheme: scheme}) + if err != nil { + t.Fatal(err) + } + ctx := context.Background() + for _, conflicts := range []int{5, 6} { + t.Run(fmt.Sprintf("conflicts-%d", conflicts), func(t *testing.T) { + handler, device := fixture(t) + secret, _, err := handler.Store.Read(ctx) + if err != nil { + t.Fatal(err) + } + namespace := fmt.Sprintf("cas-%d", conflicts) + if err := api.Create(ctx, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: namespace}}); err != nil { + t.Fatal(err) + } + secret.Namespace, secret.UID, secret.ResourceVersion = namespace, "", "" + if err := api.Create(ctx, secret); err != nil { + t.Fatal(err) + } + contender := &contendedLedgerClient{Client: api, remaining: conflicts} + handler.Store.Client, handler.Store.Namespace = contender, namespace + var logs bytes.Buffer + previous := slog.Default() + slog.SetDefault(slog.New(slog.NewJSONHandler(&logs, nil))) + defer slog.SetDefault(previous) + response := handler.Handle(ctx, registrationRequest(t, device, "contended")) + if response.Allowed != (conflicts == 5) || contender.attempts != 6 || contender.conflicts != conflicts { + t.Fatalf("real CAS retry budget: allowed=%v attempts=%d conflicts=%d result=%v", response.Allowed, contender.attempts, contender.conflicts, response.Result) + } + _, ledger, err := handler.Store.Read(ctx) + if err != nil { + t.Fatal(err) + } + if conflicts == 5 && (len(ledger.Entries) != 1 || ledger.Entries[0].Outcome != "Unknown") { + t.Fatal("successful CAS did not retain unknown reservation") + } + if conflicts == 6 && (len(ledger.Entries) != 0 || !strings.Contains(logs.String(), "CAS retries exhausted") || !strings.Contains(logs.String(), `"attempts":6`)) { + t.Fatalf("exhaustion was not observable or wrote reservation: %s", logs.String()) + } + }) + } +} From eb7a60691b30026748b66d79e422c3f813c41ee2 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sun, 22 Nov 2026 14:01:06 -0600 Subject: [PATCH 069/518] feat(registration): add signed bootstrap and lossless ledger expansion --- cmd/fleet-registration-control/main.go | 56 +++ cmd/fleet-registration-control/main_test.go | 51 +++ cmd/fleet-registration/main.go | 40 +- config/README.md | 5 + config/base/registration/deployment.yaml | 7 +- config/base/registration/protection.yaml | 13 +- config/base/registration/rbac.yaml | 3 + .../inventory-capacity-registration.md | 13 +- .../registration-storage-rollout.md | 190 +++++++++ internal/registration/admission.go | 30 +- internal/registration/bounded_fences_test.go | 8 +- internal/registration/control.go | 235 +++++++++++ internal/registration/control_test.go | 150 +++++++ internal/registration/envtest_test.go | 101 ++++- internal/registration/fence.go | 21 +- internal/registration/ledger.go | 34 +- internal/registration/runtime.go | 5 +- internal/registration/segments.go | 253 ++++++++++++ .../registration/segments_envtest_test.go | 382 ++++++++++++++++++ internal/registration/transport.go | 104 +++++ 20 files changed, 1657 insertions(+), 44 deletions(-) create mode 100644 cmd/fleet-registration-control/main.go create mode 100644 cmd/fleet-registration-control/main_test.go create mode 100644 docs/development/registration-storage-rollout.md create mode 100644 internal/registration/control.go create mode 100644 internal/registration/control_test.go create mode 100644 internal/registration/segments.go create mode 100644 internal/registration/segments_envtest_test.go create mode 100644 internal/registration/transport.go diff --git a/cmd/fleet-registration-control/main.go b/cmd/fleet-registration-control/main.go new file mode 100644 index 00000000..1e135e9c --- /dev/null +++ b/cmd/fleet-registration-control/main.go @@ -0,0 +1,56 @@ +package main + +import ( + "crypto/ed25519" + "crypto/x509" + "encoding/json" + "encoding/pem" + "errors" + "flag" + "fmt" + "io" + "os" + + "go.datum.net/fleet/internal/registration" +) + +func main() { + requestPath := flag.String("request", "", "unsigned ControlRequest JSON, exact observed root UID/resourceVersion/epoch and scope") + keyPath := flag.String("key", "", "offline Ed25519 PKCS8 private key; never mount in the service") + flag.Parse() + if err := sign(*requestPath, *keyPath, os.Stdout); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } +} + +func sign(requestPath, keyPath string, output io.Writer) error { + encoded, err := os.ReadFile(requestPath) + if err != nil { + return err + } + if len(encoded) > 8192 { + return errors.New("request exceeds budget") + } + var request registration.ControlRequest + if err := json.Unmarshal(encoded, &request); err != nil { + return err + } + encoded, err = os.ReadFile(keyPath) + if err != nil { + return err + } + block, rest := pem.Decode(encoded) + if block == nil || len(rest) != 0 { + return errors.New("expected one PKCS8 private key") + } + parsed, err := x509.ParsePKCS8PrivateKey(block.Bytes) + if err != nil { + return err + } + key, ok := parsed.(ed25519.PrivateKey) + if !ok { + return errors.New("control key must be Ed25519") + } + return json.NewEncoder(output).Encode(registration.SignControl(request, key)) +} diff --git a/cmd/fleet-registration-control/main_test.go b/cmd/fleet-registration-control/main_test.go new file mode 100644 index 00000000..18c185da --- /dev/null +++ b/cmd/fleet-registration-control/main_test.go @@ -0,0 +1,51 @@ +package main + +import ( + "bytes" + "crypto/ed25519" + "crypto/rand" + "crypto/x509" + "encoding/json" + "encoding/pem" + "os" + "path/filepath" + "reflect" + "testing" + + "go.datum.net/fleet/internal/registration" +) + +func TestOfflineControlSigner(t *testing.T) { + _, key, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + t.Fatal(err) + } + request := registration.ControlRequest{Action: "expand", ID: "change", Reason: "synthetic", RootUID: "root", ResourceVersion: "9", Epoch: 2, Authority: "milo", Projects: []string{"provider"}} + encoded, _ := json.Marshal(request) + directory := t.TempDir() + requestPath, keyPath := filepath.Join(directory, "request"), filepath.Join(directory, "private") + if err := os.WriteFile(requestPath, encoded, 0600); err != nil { + t.Fatal(err) + } + der, err := x509.MarshalPKCS8PrivateKey(key) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(keyPath, pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: der}), 0600); err != nil { + t.Fatal(err) + } + var output bytes.Buffer + if err := sign(requestPath, keyPath, &output); err != nil { + t.Fatal(err) + } + actual, err := registration.ParseControl(output.Bytes()) + if err != nil || !reflect.DeepEqual(actual, registration.SignControl(request, key)) { + t.Fatal("signer changed request", err) + } + if err := os.WriteFile(keyPath, []byte("not a private key"), 0600); err != nil { + t.Fatal(err) + } + if err := sign(requestPath, keyPath, &output); err == nil { + t.Fatal("invalid key accepted") + } +} diff --git a/cmd/fleet-registration/main.go b/cmd/fleet-registration/main.go index 3497c443..29cd97f6 100644 --- a/cmd/fleet-registration/main.go +++ b/cmd/fleet-registration/main.go @@ -24,25 +24,26 @@ import ( "k8s.io/client-go/tools/clientcmd" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/webhook/admission" ) func main() { - var configFile, providers, privateNamespace, cert, key, clientCA string + var configFile, providers, privateNamespace, cert, key, clientCA, controlKey, controlRequest string flag.StringVar(&configFile, "config", "", "Fleet manager discovery configuration") flag.StringVar(&providers, "provider-projects", "", "complete comma-separated provider identity scope, fixed in the private ledger") flag.StringVar(&privateNamespace, "private-namespace", "fleet-system-private", "private registration ledger namespace") flag.StringVar(&cert, "tls-cert", "/etc/fleet/registration/tls.crt", "serving certificate") flag.StringVar(&key, "tls-key", "/etc/fleet/registration/tls.key", "serving key") flag.StringVar(&clientCA, "client-ca", "/etc/fleet/registration/client-ca.crt", "CA dedicated to trusted API-server webhook clients") + flag.StringVar(&controlKey, "control-key", "/etc/fleet/registration-control/public.pem", "operator Ed25519 public key; never a private key") + flag.StringVar(&controlRequest, "control-request", "/etc/fleet/registration-control/request.json", "optional signed activation or expansion request") flag.Parse() - if err := run(ctrl.SetupSignalHandler(), configFile, providers, privateNamespace, cert, key, clientCA); err != nil { + if err := run(ctrl.SetupSignalHandler(), configFile, providers, privateNamespace, cert, key, clientCA, controlKey, controlRequest); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } -func run(ctx context.Context, configFile, providers, namespace, cert, key, clientCA string) error { +func run(ctx context.Context, configFile, providers, namespace, cert, key, clientCA, controlKey, controlRequest string) error { config, err := projectdiscovery.LoadConfig(configFile) if err != nil { return err @@ -83,21 +84,20 @@ func run(ctx context.Context, configFile, providers, namespace, cert, key, clien return err } } - handler := registration.NewHandler(registration.Store{Client: private, Namespace: namespace, Authority: config.AuthorityID, Projects: projects}, root, template, scheme) - if err := handler.VerifyFence(ctx); err != nil { + keyBytes, err := os.ReadFile(controlKey) + if err != nil { return err } - if _, _, err := handler.Store.Read(ctx); err != nil { + publicKey, err := registration.ParseControlKey(keyBytes) + if err != nil { return err } + handler := registration.NewHandler(registration.Store{Client: private, Namespace: namespace, Authority: config.AuthorityID, Projects: projects, ControlKey: publicKey, RequireActive: true}, root, template, scheme) tlsConfig, err := webhookTLS(clientCA) if err != nil { return err } - webhook := &admission.Webhook{Handler: handler} - mux := http.NewServeMux() - mux.Handle("/validate-registration", webhook) - server := &http.Server{Addr: ":9443", Handler: http.MaxBytesHandler(mux, 2<<20), ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 15 * time.Second, WriteTimeout: 20 * time.Second, TLSConfig: tlsConfig} + server := &http.Server{Addr: ":9443", Handler: http.MaxBytesHandler(handler.Transport(), 2<<20), ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 15 * time.Second, WriteTimeout: 20 * time.Second, TLSConfig: tlsConfig} go func() { ticker := time.NewTicker(30 * time.Second) defer ticker.Stop() @@ -109,9 +109,25 @@ func run(ctx context.Context, configFile, providers, namespace, cert, key, clien _ = server.Shutdown(shutdown) return case <-ticker.C: - if err := handler.Recover(ctx); err != nil { + operation, cancel := context.WithTimeout(ctx, 20*time.Second) + if err := handler.Store.ResumeExpansion(operation); err != nil { + fmt.Fprintln(os.Stderr, "registration expansion remains fenced:", err) + } + if encoded, err := os.ReadFile(controlRequest); err == nil { + control, err := registration.ParseControl(encoded) + if err == nil { + err = handler.ApplyControl(operation, control) + } + if err != nil { + fmt.Fprintln(os.Stderr, "registration control not applied:", err) + } + } else if !os.IsNotExist(err) { + fmt.Fprintln(os.Stderr, "registration control unavailable:", err) + } + if err := handler.Recover(operation); err != nil { fmt.Fprintln(os.Stderr, "registration recovery remains unknown:", err) } + cancel() } } }() diff --git a/config/README.md b/config/README.md index 1fd166fa..8a36c5e2 100644 --- a/config/README.md +++ b/config/README.md @@ -29,6 +29,11 @@ production registration authority or its private ledger. The one `fleet-manager` Deployment serves every Milo project that consumes the `metal` service; see [project discovery](#project-discovery). +The [signed expansion and transport-first contract](../docs/development/registration-storage-rollout.md) +defines the required operator public-key ConfigMap, retained segments, activation +gate, byte budgets and ordered parent infrastructure work. Pod TCP readiness is +transport-only; it must not enable UI registration. + The separate `fleet-registration` Deployment serves inert inventory-backed capacity admission only. Its TLS trust, read/SAR credentials, webhook serving CA and one-time private ledger bootstrap are environment-owned. Read the diff --git a/config/base/registration/deployment.yaml b/config/base/registration/deployment.yaml index 135c91a2..c48eff73 100644 --- a/config/base/registration/deployment.yaml +++ b/config/base/registration/deployment.yaml @@ -55,7 +55,7 @@ spec: port: https resources: requests: {cpu: 50m, memory: 64Mi} - limits: {memory: 256Mi} + limits: {memory: 512Mi} securityContext: allowPrivilegeEscalation: false readOnlyRootFilesystem: true @@ -66,7 +66,12 @@ spec: - {name: root, mountPath: /var/run/fleet/milo, readOnly: true} - {name: projects, mountPath: /var/run/fleet/projects, readOnly: true} - {name: tls, mountPath: /etc/fleet/registration, readOnly: true} + - {name: control, mountPath: /etc/fleet/registration-control, readOnly: true} volumes: + - name: control + configMap: + name: fleet-registration-control + defaultMode: 0440 - name: config configMap: name: fleet-manager-config diff --git a/config/base/registration/protection.yaml b/config/base/registration/protection.yaml index d1e54d70..cabc8fbd 100644 --- a/config/base/registration/protection.yaml +++ b/config/base/registration/protection.yaml @@ -8,14 +8,19 @@ spec: resourceRules: - apiGroups: [''] apiVersions: [v1] - operations: [UPDATE, DELETE] + operations: [CREATE, UPDATE, DELETE] resources: [secrets] matchConditions: - name: registration-ledger - expression: request.namespace == 'fleet-system-private' && request.name == 'fleet-capacity-registration-v1' + expression: request.namespace == 'fleet-system-private' && (request.name == 'fleet-capacity-registration-v1' || request.name.startsWith('fleet-registration-segment-') || request.userInfo.username == 'system:serviceaccount:fleet-system:fleet-registration') validations: - - expression: request.operation == 'UPDATE' && request.userInfo.username == 'system:serviceaccount:fleet-system:fleet-registration' - message: Registration reservations are retained; only the registration service may update this ledger. + - expression: >- + (request.operation == 'CREATE' && request.name == 'fleet-capacity-registration-v1' && request.userInfo.username != 'system:serviceaccount:fleet-system:fleet-registration') || + (request.operation == 'UPDATE' && request.name == 'fleet-capacity-registration-v1' && request.userInfo.username == 'system:serviceaccount:fleet-system:fleet-registration' && + (!has(oldObject.data) || !('routing.json' in oldObject.data) || + (has(object.data) && 'routing.json' in object.data && 'ledger.json' in object.data && object.data['ledger.json'] == oldObject.data['ledger.json']))) || + (request.operation == 'CREATE' && request.name.startsWith('fleet-registration-segment-') && request.userInfo.username == 'system:serviceaccount:fleet-system:fleet-registration' && has(object.immutable) && object.immutable) + message: Registration roots cannot be downgraded or deleted; only the service may update the root or create immutable retained segments. --- apiVersion: admissionregistration.k8s.io/v1 kind: ValidatingAdmissionPolicyBinding diff --git a/config/base/registration/rbac.yaml b/config/base/registration/rbac.yaml index 79a5cb2a..1e08d94c 100644 --- a/config/base/registration/rbac.yaml +++ b/config/base/registration/rbac.yaml @@ -4,6 +4,9 @@ metadata: name: fleet-registration-ledger namespace: fleet-system-private rules: + - apiGroups: [''] + resources: [secrets] + verbs: [get, create] - apiGroups: [''] resources: [secrets] resourceNames: [fleet-capacity-registration-v1] diff --git a/docs/development/inventory-capacity-registration.md b/docs/development/inventory-capacity-registration.md index a6a6078e..976716fd 100644 --- a/docs/development/inventory-capacity-registration.md +++ b/docs/development/inventory-capacity-registration.md @@ -61,7 +61,7 @@ not the caller's registration authority. The webhook accepts only mutually authenticated TLS from a dedicated API-server client CA. Do not use a broad tenant/client CA: an AdmissionReview received from an untrusted client is not evidence of an authenticated actor. The server also -checks the installed root webhook configuration at startup and before admission: +checks the installed root webhook configuration at signed activation and before admission: the exact write rules, explicit serving CA, Fail policy, common authority endpoint, and the restricted match conditions described below. Label selectors, missing fences, expanded rules, and conditions differing from the configured @@ -105,8 +105,10 @@ ownership. Production allocation remains disabled independently. ## Serialization and recovery `fleet-capacity-registration-v1` is a separate host-cluster Secret in -`fleet-system-private`; it is **not** allocation custody. The service has only -get/update permission on that single Secret. Its JSON retains the actor, exact +`fleet-system-private`; it is **not** allocation custody. The service updates only +that root and can create/read immutable retained segments under the host policy. +The [storage and bootstrap protocol](registration-storage-rollout.md) adds signed +lossless expansion and deny-only transport startup. Its JSON retains the actor, exact API-normalized create object, admission request UID, client operation ID, Project/namespace lifetimes, Device UID/resourceVersion, aliases, canonical key, and API-assigned capacity UID **before allowing the public create**. Kubernetes @@ -188,7 +190,10 @@ resourceVersion, retained aliases and a deletion bit. This bounds growth by distinct incarnations/aliases and registration operations, **not** by elapsed collector observations. It is not an unlimited-inventory or universal deduplication guarantee: retained incarnations and reservations can still fill the pilot ledger. -The ledger refuses growth past 750,000 encoded bytes (the boundary itself fits). +The mutable tail refuses growth past 650,000 encoded bytes (the boundary fits), +leaving sealing headroom. Signed expansion seals up to sixteen immutable segments; +existing v1 tails up to 750,000 bytes can migrate losslessly. This is bounded growth, +not unlimited capacity, alias expiry, or permission to increase caps. Admission makes at most six CAS attempts with complete reevaluation after conflicts; exhaustion emits a structured error with project, operation identity and attempt count, without actor credentials or ledger contents. Lost or corrupt diff --git a/docs/development/registration-storage-rollout.md b/docs/development/registration-storage-rollout.md new file mode 100644 index 00000000..8b4e089b --- /dev/null +++ b/docs/development/registration-storage-rollout.md @@ -0,0 +1,190 @@ +# Registration storage expansion and non-admitting bootstrap + +[Stage-1 contract](inventory-capacity-registration.md) · [Packaging](../../config/README.md) + +## Delivery boundary + +Implemented against feature revision `32c3c200b7afd50a43ae705609f8f5fad0c63d40`. +This change is independent of pending PR144 (`dc0f872977ecf817557b96fa82d53b853110a198`), +whose staging integration document was read in full. It does not replace that +PR's availability work or evidence; reconcile overlapping deployment/ledger edits +when combining them. **Parent independent adversarial review is required.** + +The two Fleet prerequisites are addressed by bounded, lossless expansion (not +alias release) and transport-first, deny-only startup. This is not live acceptance. +No live mutation, grant, deployment, allocation or provider effect is authorized +by this change. The reported mixed live pairing (synthetic host without the service, +production Milo Fail webhook without caBundle) must not be repaired by relaxing +admission or changing host overlays indiscriminately. Existing Enabled capacity +and synthetic consumers are not disposable acceptance fixtures. + +## Single-CAS storage protocol + +The original `fleet-capacity-registration-v1` Secret and UID remain the sole CAS +root. Version 2 adds `routing.json` and `tail.json`. Immutable Secrets named +`fleet-registration-segment--` retain sealed tails. +Every read verifies segment name, UID, immutability, deletion state, payload digest +and authority/provider scope. Missing/replaced/corrupt/unreadable storage is never +an empty partition. The same root still serializes all aliases and provider projects. + +Segments are ordered overlays, not independently admitting hash shards. Groups +are keyed by admission operation UID for registrations and Project route/Device UID +for Device fences. Only changed groups are copied into the mutable tail, whole. +Legacy multiple-version groups are sealed without reinterpretation. Existing +authoritative update/coalescing rules alone supersede pending versions. The writer +also rejects dropping registrations, aliases, tombstones or known lifetime identity. +New Device fences retain Project UID, namespace name/UID and Device name; missing +legacy fields are not backfilled or proof of safe release. + +An operator signs `expand`, binding exact root UID, resourceVersion, epoch, +authority, sorted provider scope, change ID and reason. The service: + +1. Verifies the pinned Ed25519 key and CAS-retains the request as pending before + effects. First conversion replaces `ledger.json` with an incompatible authority + sentinel, retaining its original bytes in `tail.json`. Old binaries reject it; + old in-flight writes lose CAS. Host policy forbids reverting the v2 format. +2. Creates one deterministic immutable segment with the frozen tail, root UID and + signed request. Every replica resumes the same name. AlreadyExists requires + exact content and immutable lifetime checks, never overwrite permission. +3. Reads back the segment, then CAS-appends its name/UID/digest, advances epoch and + empties the tail. Prior segments, activation and audit history remain retained. +4. Resumes admission under the same activation and full fence checks. Migration + never changes `Unknown`, `Recorded`, tombstones, reservations or eligibility. + +Crash/timeout before freeze has no authorized storage effect. After freeze, any +replica resumes retained authority even without the request file. A prepared +segment is associated with the pending operation, not garbage. A lost final CAS +response is reconciled from the root. No timeout/lease/age/absence cancels pending +work. Stale plans fail; inspect before re-signing. A public request admitted before +freeze may persist afterwards: its reservation was copied, so no claim of fencing +the API server's later storage commit is needed. A not-yet-reserved writer must win +the current root CAS or be denied/re-evaluated. No orphan alias is discarded. + +This does not implement release, scope changes, arbitrary restore or custody +compaction. Rollbacks need a v2-aware binary. Never restore an old root alone; +root plus all segments are one retained recovery set. Administrators who remove +policies or restore arbitrary storage remain outside the guarantee. + +## Enforced budgets + +| Surface | Hard bound | +| --- | --- | +| Mutable tail | 650,000 encoded bytes; larger candidate denied before admission success | +| Legacy tail accepted for sealing | 750,000 bytes, including an already-full v1 ledger | +| Root data including routing/control | 850,000 bytes, below the 1 MiB Secret data limit | +| Sealed segments | 16 plus the mutable tail; expansion is operator-authorized, not infinite | +| Signed payload / mounted envelope | 8,192 / 16,384 bytes | +| Activation audit | Current activation plus seven previous signed activations, never pruned | + +The ordinary stop leaves 100 KB relative to the former ledger cap for safe sealing; +the root budget additionally accommodates routing/control. A segment is at most +750 KB plus its small control envelope. Failed creates, aliases, distinct Device +incarnations and failed registrations consume budget. Oversized requests cannot +consume transition reserve. Segment retries target one name, not orphan snapshots. +Maximum ledger payload is 16 × 750,000 + 650,000 bytes plus bounded control metadata. +This deliberately retains complete provider scans and the single-root bottleneck; +it is not a throughput qualification. Pod memory is bounded at 512 MiB. + +The mTLS-only `/status` reports tail bytes, headroom, remaining segments, epoch, +pending state, root UID/RV, scope and verified fence digest, without reservation +contents or actor data. Parent monitoring must alert below 100,000 bytes headroom +and before only two segments remain. Sign expansion before exhaustion. At the +terminal bound, stop protected growth and escalate for a separately reviewed +storage migration; never increase caps or delete/reset/release records manually. +Public inventory reads remain unaffected. Denied/timed-out private writes deny +admission even if reads succeed; uncertain commits stay retained. + +## Transport versus activation + +The process loads credentials, TLS material and the operator public key, then +listens without requiring the ledger or installed webhook. It denies **every** +admission in bootstrap. `/transportz` returns 204 on the same mTLS listener for +SAN/CA/routing verification. The pod TCP readiness probe intentionally supplies +Service endpoints during bootstrap; it is not the UI admission gate. +`/activationz` returns 503 until activation and current readable dependencies +verify. It is not proof of write permission, future availability or capacity +eligibility. Request headers/labels/annotations/extras cannot enable admission; +there is no bootstrap bypass flag or public control endpoint. + +Signed `activate` also pins the digest of the installed, API-defaulted webhook +`webhooks` array, obtained from `/status` after `VerifyFence` succeeds. Activation +CAS and every admission retain full fence verification. Missing trust, changed +endpoint/CA, partial deployment, relaxed rules or degraded dependencies deny. +Approved trust changes require another exact signed activation; prior signatures +remain in bounded root audit history. The configured signing key is an operator +trust boundary, not caller authority; coordinate changes with pending signatures. +Global capacity fencing and privileged/root-context limitations are unchanged. + +## Exact staged parent infrastructure contract + +These steps require a separately approved infra PR; none authorizes live execution. + +1. Preserve private baseline evidence. Resolve registration authority and complete + provider scope separately from synthetic consumers. Do not narrow scope to + conceal legacy capacity or reuse manager root grants. Capacity writes remain + globally fenced, including outside `datum-cloud`. +2. Install retention policies before bootstrap or broader RBAC. The service gets + get/create Secrets in the dedicated private namespace and update only on the + root. Fail host admission restricts its creates to immutable segment names; + it cannot create the root/arbitrary Secrets or update/delete segments. Prove + negative cases and retain backups of **all** segments; never use GitOps to + reconcile an empty root. Namespace/root deletion remains forbidden. +3. Provision separate root/project read-and-SAR identities, serving SAN/CA, + dedicated webhook client certificate/CA, and `fleet-registration-control` + ConfigMap in `fleet-system` with `public.pem` (Ed25519 PKIX PEM). Restrict + ConfigMap/workload writers as operator trust authorities. No signing private + key, kubeconfig or rendered secret-bearing configuration belongs in Git. +4. Pin the reviewed image and deploy registration before activating a new Fail + webhook. With the already-broken live fence, leave protection installed. + Verify `/transportz` from the API-server route with trusted client TLS, and + reject missing/untrusted clients. No public write is a health probe; never + remove/relax the existing fence to test routing. +5. Create the empty root once with exact authority and sorted projects in + `ledger.json`, after retention acceptance. Abort on AlreadyExists and inspect + rather than replace. Existing v1 roots activate/migrate in place with the same UID. +6. Wire Milo's dedicated webhook client and serving caBundle in environment-owned + overlays. Verify complete Fail rules. Fetch `/status` over trusted transport + and review the installed fence and root UID/RV/epoch/scope/fence digest. +7. Sign a `ControlRequest` JSON containing `action: "activate"`, `id`, `reason`, + `authority`, `projects`, `rootUID`, `resourceVersion`, `epoch`, `fenceDigest`: + + ```sh + go run ./cmd/fleet-registration-control --request="$PRIVATE_REQUEST" --key="$OFFLINE_KEY" > "$PRIVATE_SIGNED_REQUEST" + ``` + + The helper requires a PKCS8 Ed25519 private key. Only its signed envelope goes + into ConfigMap `request.json`; the private key is never mounted. The process + checks every 30 seconds. Reconcile through `/status` and `/activationz`, not + ConfigMap update success. For expansion use `action: "expand"`; no fence + digest is required, and expansion cannot activate a bootstrap root. +8. Keep UI registration gated until real staff proxy identity, named Device and + create authorization denials, direct mutation denials, duplicate contention, + lifetime/legacy behavior, Unknown recovery and unchanged baselines are accepted + on intended Milo routes. Use disposable environments for outages/failures, + never shared-service disruption or real-asset smoke tests. Only the parent + can then report environment acceptance. + +## Local verification + +Tests exercise real Secret CAS/retention, bounded expansion, legacy integrity, +multi-replica migration, signature/scope/epoch spoofing, read-only RBAC and +persisted-but-timed-out writes. A real API request paused after admission fails +public persistence after migration; its aliases remain reserved and Unknown. +Five subprocess exits cover freeze, before/after segment persistence and +before/after root switch, recovered by new processes. Missing/replaced segments +fail closed. Existing identity, authorization, legacy and outage tests remain. + +```sh +KUBEBUILDER_ASSETS="$(go run sigs.k8s.io/controller-runtime/tools/setup-envtest@v0.25.2 use 1.37.0 -p path)" go test -race ./... +go vet ./... +go build ./... +kustomize build config/milo >/dev/null +kustomize build config/overlays/management-plane >/dev/null +./hack/validate-overlay-isolation.sh +./hack/test-overlay-isolation.sh +./hack/validate-doc-links.sh +git diff --check +``` + +No UI files change. These checks do not accept deployed Milo routing, credential +mounts, grants, GitOps ordering or real inventory. Disabled/Retain remains inert. diff --git a/internal/registration/admission.go b/internal/registration/admission.go index 8168a1e2..28cc087b 100644 --- a/internal/registration/admission.go +++ b/internal/registration/admission.go @@ -42,6 +42,7 @@ type Project struct { type Handler struct { Store Store VerifyFence func(context.Context) error + FenceDigest func(context.Context) (string, error) Resolve func(context.Context, string) (Project, error) Authorize func(context.Context, Project, authenticationv1.UserInfo, string, string, string) error } @@ -87,6 +88,11 @@ func projectName(actor authenticationv1.UserInfo) (string, error) { } func (handler *Handler) Handle(ctx context.Context, request admission.Request) admission.Response { + if handler.Store.RequireActive { + if err := handler.Ready(ctx); err != nil { + return admission.Denied(err.Error()) + } + } if request.Operation == admissionv1.Delete && request.Name == "" && ((request.Resource.Group == "" && request.Resource.Resource == "namespaces") || (request.Resource.Group == "resourcemanager.miloapis.com" && request.Resource.Resource == "projects")) { return admission.Denied("lifetime deletion requires an exact resource name; collection deletion cannot prove exclusion of retained lifetimes") } @@ -140,6 +146,15 @@ func (handler *Handler) evaluate(ctx context.Context, name string, request admis if err != nil { return fmt.Errorf("registration unavailable: %w", err) } + if _, exists := secret.Data["routing.json"]; exists { + route, err := decodeRouting(secret) + if err != nil { + return err + } + if route.Pending != nil { + return errors.New("registration expansion is fenced") + } + } project, err := handler.Resolve(ctx, name) if err != nil { return err @@ -224,6 +239,9 @@ func (handler *Handler) evaluate(ctx context.Context, name string, request admis } for _, fence := range ledger.DeviceFences { if fence.Project == name && fence.UID == device.UID { + if (fence.ProjectUID != "" && fence.ProjectUID != entry.ProjectUID) || (fence.NamespaceUID != "" && fence.NamespaceUID != entry.NamespaceUID) || (fence.Name != "" && (fence.Name != device.Name || fence.Namespace != device.Namespace)) { + return ErrConflict + } if fence.Deleted || (fence.Version != "" && fence.Version == device.ResourceVersion) { return ErrConflict } @@ -357,7 +375,14 @@ func (handler *Handler) device(ctx context.Context, project Project, request adm if request.Operation == admissionv1.Update && identicalObjects(request.OldObject.Raw, request.Object.Raw) { return nil } - fence := DeviceFence{Project: project.Identity.RouteName, UID: device.UID, Deleted: request.Operation == admissionv1.Delete} + var namespace corev1.Namespace + if err := project.Client.Get(ctx, client.ObjectKey{Name: device.Namespace}, &namespace); err != nil { + return err + } + if namespace.UID == "" || !namespace.DeletionTimestamp.IsZero() { + return errors.New("Device namespace lifetime unavailable") + } + fence := DeviceFence{Project: project.Identity.RouteName, ProjectUID: project.Identity.UID, Namespace: device.Namespace, NamespaceUID: namespace.UID, Name: device.Name, UID: device.UID, Deleted: request.Operation == admissionv1.Delete} if request.Operation == admissionv1.Update { current := &inventory.Device{} if err := project.Client.Get(ctx, client.ObjectKeyFromObject(&old), current); err != nil { @@ -385,6 +410,9 @@ func (handler *Handler) device(ctx context.Context, project Project, request adm if (retained.Deleted && !fence.Deleted) || (request.Operation == admissionv1.Create && !reflect.DeepEqual(retained, fence)) { return ErrConflict } + if (retained.ProjectUID != "" && retained.ProjectUID != fence.ProjectUID) || (retained.NamespaceUID != "" && retained.NamespaceUID != fence.NamespaceUID) || (retained.Name != "" && (retained.Name != fence.Name || retained.Namespace != fence.Namespace)) { + return ErrConflict + } for _, alias := range retained.Aliases { if !slices.Contains(fence.Aliases, alias) { fence.Aliases = append(fence.Aliases, alias) diff --git a/internal/registration/bounded_fences_test.go b/internal/registration/bounded_fences_test.go index 1dbd19a0..8121d7f0 100644 --- a/internal/registration/bounded_fences_test.go +++ b/internal/registration/bounded_fences_test.go @@ -118,17 +118,17 @@ func TestLedgerExactSizeCap(t *testing.T) { secret, ledger, _ := handler.Store.Read(ctx) ledger.DeviceFences = []DeviceFence{{Project: "provider", UID: "device", Aliases: []string{""}}} encoded, _ := json.Marshal(ledger) - ledger.DeviceFences[0].Aliases[0] = strings.Repeat("x", 750000-len(encoded)) + ledger.DeviceFences[0].Aliases[0] = strings.Repeat("x", TailBudget-len(encoded)) if err := handler.Store.Write(ctx, secret, ledger); err != nil { - t.Fatalf("exactly 750000 bytes must fit: %v", err) + t.Fatalf("exact tail budget must fit: %v", err) } before := secret.ResourceVersion ledger.DeviceFences[0].Aliases[0] += "x" if err := handler.Store.Write(ctx, secret, ledger); err == nil || !strings.Contains(err.Error(), "ledger is full") { - t.Fatalf("750001 bytes must fail closed: %v", err) + t.Fatalf("tail budget plus one must fail closed: %v", err) } current, _, err := handler.Store.Read(ctx) - if err != nil || current.ResourceVersion != before || len(current.Data["ledger.json"]) != 750000 { + if err != nil || current.ResourceVersion != before || len(current.Data["ledger.json"]) != TailBudget { t.Fatal("oversized write changed durable reservations") } } diff --git a/internal/registration/control.go b/internal/registration/control.go new file mode 100644 index 00000000..7e96415b --- /dev/null +++ b/internal/registration/control.go @@ -0,0 +1,235 @@ +package registration + +import ( + "context" + "crypto/ed25519" + "encoding/json" + "errors" + "log/slog" + "reflect" + + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + "sigs.k8s.io/controller-runtime/pkg/client" +) + +type ControlRequest struct { + Action string `json:"action"` + ID string `json:"id"` + Reason string `json:"reason"` + Authority string `json:"authority"` + Projects []string `json:"projects"` + RootUID types.UID `json:"rootUID"` + ResourceVersion string `json:"resourceVersion"` + Epoch uint64 `json:"epoch"` + FenceDigest string `json:"fenceDigest,omitempty"` +} + +type SignedControl struct { + Request ControlRequest `json:"request"` + Signature []byte `json:"signature"` +} + +func SignControl(request ControlRequest, key ed25519.PrivateKey) SignedControl { + encoded, _ := json.Marshal(request) + return SignedControl{Request: request, Signature: ed25519.Sign(key, append([]byte("fleet-registration-control-v2\n"), encoded...))} +} + +func (store Store) verifyControl(control SignedControl, uid types.UID) error { + request := control.Request + encoded, err := json.Marshal(request) + if err != nil { + return err + } + if len(store.ControlKey) != ed25519.PublicKeySize || len(encoded) > 8192 || !ed25519.Verify(store.ControlKey, append([]byte("fleet-registration-control-v2\n"), encoded...), control.Signature) { + return errors.New("registration control signature unavailable or invalid") + } + if request.RootUID != uid || request.Authority != store.Authority || !reflect.DeepEqual(request.Projects, store.Projects) || request.ResourceVersion == "" || request.ID == "" || request.Reason == "" || (request.Action != "expand" && request.Action != "activate") { + return errors.New("registration control authority or action mismatch") + } + return nil +} + +func (store Store) root(ctx context.Context) (*corev1.Secret, Routing, error) { + secret := &corev1.Secret{} + if err := store.Client.Get(ctx, client.ObjectKey{Namespace: store.Namespace, Name: LedgerName}, secret); err != nil { + return nil, Routing{}, err + } + if secret.UID == "" || !secret.DeletionTimestamp.IsZero() { + return nil, Routing{}, errors.New("ledger lifetime unavailable") + } + if _, exists := secret.Data["routing.json"]; exists { + route, err := decodeRouting(secret) + return secret, route, err + } + return secret, Routing{Version: 2, RootUID: secret.UID}, nil +} + +func encodeRoute(secret *corev1.Secret, route Routing) error { + encoded, err := json.Marshal(route) + if err != nil { + return err + } + if _, exists := secret.Data["routing.json"]; !exists { + secret.Data["tail.json"] = secret.Data["ledger.json"] + secret.Data["ledger.json"] = []byte(`{"authority":"v2-routing-required","projects":[]}`) + } + secret.Data["routing.json"] = encoded + return nil +} + +func (handler *Handler) ApplyControl(ctx context.Context, control SignedControl) error { + secret, route, err := handler.Store.root(ctx) + if err != nil { + return err + } + if err := handler.Store.verifyControl(control, secret.UID); err != nil { + return err + } + if control.Request.Action == "expand" && control.Request.Epoch < route.Epoch { + reference := route.Segments[control.Request.Epoch] + segment := &corev1.Secret{} + if err := handler.Store.Client.Get(ctx, client.ObjectKey{Namespace: handler.Store.Namespace, Name: reference.Name}, segment); err != nil { + return err + } + encoded, _ := json.Marshal(control) + if segment.UID != reference.UID || segment.Immutable == nil || !*segment.Immutable || !segment.DeletionTimestamp.IsZero() || digest(segment.Data["ledger.json"]) != reference.Digest || string(segment.Data["control.json"]) != string(encoded) { + return errors.New("stale expansion does not match retained completion") + } + return nil + } + if route.Pending != nil { + if !reflect.DeepEqual(*route.Pending, control) { + return errors.New("another signed expansion is pending") + } + return handler.Store.ResumeExpansion(ctx) + } + if route.Activation != nil && reflect.DeepEqual(*route.Activation, control) { + return nil + } + if route.Epoch != control.Request.Epoch || secret.ResourceVersion != control.Request.ResourceVersion { + return errors.New("stale control epoch or CAS baseline; inspect current root") + } + if _, _, err := handler.Store.Read(ctx); err != nil { + return err + } + switch control.Request.Action { + case "activate": + if err := handler.verifyActivation(ctx, control); err != nil { + return err + } + if route.Activation != nil { + if len(route.ActivationHistory) >= 7 { + return errors.New("activation audit budget exhausted; retained history requires a reviewed migration") + } + route.ActivationHistory = append(route.ActivationHistory, *route.Activation) + } + route.Activation = &control + case "expand": + if len(route.Segments) >= MaxSegments { + return ErrGrowthStopped + } + route.Pending = &control + } + if err := encodeRoute(secret, route); err != nil { + return err + } + if err := handler.Store.updateRoot(ctx, secret); err != nil { + return err + } + slog.InfoContext(ctx, "registration signed control retained", "action", control.Request.Action, "id", control.Request.ID, "rootUID", secret.UID, "epoch", route.Epoch, "signer", digest(handler.Store.ControlKey)) + if route.Pending != nil { + return handler.Store.ResumeExpansion(ctx) + } + return nil +} + +func (store Store) ResumeExpansion(ctx context.Context) error { + secret, route, err := store.root(ctx) + if err != nil || route.Pending == nil { + return err + } + if err := store.verifyControl(*route.Pending, secret.UID); err != nil { + return err + } + if route.Pending.Request.Action != "expand" || route.Pending.Request.Epoch != route.Epoch || len(route.Segments) >= MaxSegments { + return errors.New("invalid pending expansion") + } + if _, _, err := store.readSnapshot(ctx, secret); err != nil { + return err + } + tail := secret.Data["tail.json"] + if len(tail) > SegmentBudget { + return ErrGrowthStopped + } + control, _ := json.Marshal(route.Pending) + immutable := true + segment := &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Namespace: store.Namespace, Name: segmentName(secret.UID, route.Epoch)}, Immutable: &immutable, Data: map[string][]byte{"ledger.json": tail, "control.json": control, "rootUID": []byte(secret.UID)}} + if err := store.Client.Create(ctx, segment); err != nil && !apierrors.IsAlreadyExists(err) { + return err + } + stored := &corev1.Secret{} + if err := store.Client.Get(ctx, client.ObjectKeyFromObject(segment), stored); err != nil { + return err + } + if stored.UID == "" || !stored.DeletionTimestamp.IsZero() || stored.Immutable == nil || !*stored.Immutable || !reflect.DeepEqual(stored.Data, segment.Data) { + return errors.New("expansion segment identity or contents conflict; remain fenced") + } + route.Segments = append(route.Segments, Segment{Name: stored.Name, UID: stored.UID, Digest: digest(tail)}) + route.Epoch++ + route.Pending = nil + empty, _ := json.Marshal(Ledger{Authority: store.Authority, Projects: store.Projects}) + secret.Data["tail.json"] = empty + if err := encodeRoute(secret, route); err != nil { + return err + } + if err := store.updateRoot(ctx, secret); err != nil { + return err + } + slog.InfoContext(ctx, "registration expansion committed", "rootUID", secret.UID, "epoch", route.Epoch, "segmentUID", stored.UID) + return nil +} + +func (handler *Handler) verifyActivation(ctx context.Context, control SignedControl) error { + if handler.VerifyFence == nil || handler.FenceDigest == nil { + return errors.New("activation fence verification unavailable") + } + if err := handler.VerifyFence(ctx); err != nil { + return err + } + actual, err := handler.FenceDigest(ctx) + if err != nil { + return err + } + if actual == "" || actual != control.Request.FenceDigest { + return errors.New("installed fence differs from signed activation") + } + return nil +} + +func (handler *Handler) Ready(ctx context.Context) error { + secret, route, err := handler.Store.root(ctx) + if err != nil { + return err + } + return handler.readySnapshot(ctx, secret, route) +} + +func (handler *Handler) readySnapshot(ctx context.Context, secret *corev1.Secret, route Routing) error { + if route.Pending != nil || route.Activation == nil { + return errors.New("registration is non-admitting: signed activation or expansion incomplete") + } + if err := handler.Store.verifyControl(*route.Activation, secret.UID); err != nil { + return err + } + if route.Activation.Request.Action != "activate" { + return errors.New("invalid activation action") + } + if err := handler.verifyActivation(ctx, *route.Activation); err != nil { + return err + } + _, _, err := handler.Store.readSnapshot(ctx, secret) + return err +} diff --git a/internal/registration/control_test.go b/internal/registration/control_test.go new file mode 100644 index 00000000..072f7de1 --- /dev/null +++ b/internal/registration/control_test.go @@ -0,0 +1,150 @@ +package registration + +import ( + "context" + "crypto/ed25519" + "crypto/rand" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "reflect" + "testing" + + admissionv1 "k8s.io/api/admission/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +func controlFor(t *testing.T, handler *Handler, key ed25519.PrivateKey, action string) SignedControl { + t.Helper() + secret, route, err := handler.Store.root(context.Background()) + if err != nil { + t.Fatal(err) + } + return SignControl(ControlRequest{Action: action, ID: "operator-change-" + secret.ResourceVersion, Reason: "synthetic test approval", Authority: handler.Store.Authority, Projects: handler.Store.Projects, RootUID: secret.UID, ResourceVersion: secret.ResourceVersion, Epoch: route.Epoch, FenceDigest: "approved-fence"}, key) +} + +func controlFixture(t *testing.T, handler *Handler) ed25519.PrivateKey { + t.Helper() + public, private, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + t.Fatal(err) + } + handler.Store.ControlKey = public + handler.Store.RequireActive = true + handler.VerifyFence = func(context.Context) error { return nil } + handler.FenceDigest = func(context.Context) (string, error) { return "approved-fence", nil } + return private +} + +func TestBootstrapDoesNotAdmitOrInterpretCallerConfiguration(t *testing.T) { + ctx := context.Background() + handler, device := fixture(t) + private := controlFixture(t, handler) + server := httptest.NewServer(handler.Transport()) + defer server.Close() + for path, expected := range map[string]int{"/transportz": http.StatusNoContent, "/activationz": http.StatusServiceUnavailable} { + response, err := server.Client().Get(server.URL + path) + if err != nil { + t.Fatal(err) + } + response.Body.Close() + if response.StatusCode != expected { + t.Fatalf("%s: %d", path, response.StatusCode) + } + } + request := registrationRequest(t, device, "bootstrap") + for _, resource := range []metav1.GroupVersionResource{{Group: "metal.datumapis.com", Resource: "machinecapacities"}, {Group: "fleet.datumapis.com", Resource: "devices"}, {Resource: "namespaces"}, {Group: "resourcemanager.miloapis.com", Resource: "projects"}} { + request.Resource, request.Operation, request.Name = resource, admissionv1.Delete, "unrelated" + if handler.Handle(ctx, request).Allowed { + t.Fatal("bootstrap admitted a request") + } + } + control := controlFor(t, handler, private, "activate") + for name, mutate := range map[string]func(*SignedControl){ + "signature": func(control *SignedControl) { control.Signature[0] ^= 1 }, + "authority": func(control *SignedControl) { control.Request.Authority = "other" }, + "scope": func(control *SignedControl) { control.Request.Projects = []string{"other"} }, + "epoch": func(control *SignedControl) { control.Request.Epoch++ }, + "root": func(control *SignedControl) { control.Request.RootUID = "replacement" }, + "fence": func(control *SignedControl) { control.Request.FenceDigest = "relaxed" }, + } { + t.Run(name, func(t *testing.T) { + encoded, _ := json.Marshal(control) + var changed SignedControl + _ = json.Unmarshal(encoded, &changed) + mutate(&changed) + if handler.ApplyControl(ctx, changed) == nil { + t.Fatal("tampered configuration accepted") + } + if name != "signature" { + changed = SignControl(changed.Request, private) + if handler.ApplyControl(ctx, changed) == nil { + t.Fatal("wrong signed target accepted") + } + } + }) + } + handler.VerifyFence = func(context.Context) error { return errors.New("missing Fail webhook") } + if handler.ApplyControl(ctx, control) == nil { + t.Fatal("missing fence activated") + } + handler.VerifyFence = func(context.Context) error { return nil } + if err := handler.ApplyControl(ctx, control); err != nil { + t.Fatal(err) + } + if err := handler.ApplyControl(ctx, control); err != nil { + t.Fatal("activation retry", err) + } + if err := handler.Ready(ctx); err != nil { + t.Fatal(err) + } + secret, before, err := handler.Store.Read(ctx) + if err != nil { + t.Fatal(err) + } + var legacy Ledger + if err := json.Unmarshal(secret.Data["ledger.json"], &legacy); err != nil || legacy.Authority == handler.Store.Authority { + t.Fatal("old binary not fenced") + } + handler.FenceDigest = func(context.Context) (string, error) { return "changed-fence", nil } + if handler.Handle(ctx, registrationRequest(t, device, "changed-trust")).Allowed { + t.Fatal("changed fence bypassed activation") + } + _, after, _ := handler.Store.Read(ctx) + if !reflect.DeepEqual(before, after) { + t.Fatal("denial changed reservations") + } + handler.FenceDigest = func(context.Context) (string, error) { return "approved-fence", nil } + handler.VerifyFence = func(context.Context) error { return errors.New("unavailable") } + if handler.Ready(ctx) == nil { + t.Fatal("lost fence reported active") + } + handler.VerifyFence = func(context.Context) error { return nil } + for range 7 { + if err := handler.ApplyControl(ctx, controlFor(t, handler, private, "activate")); err != nil { + t.Fatal(err) + } + } + if err := handler.ApplyControl(ctx, controlFor(t, handler, private, "activate")); err == nil { + t.Fatal("activation audit history exceeded its bound") + } + current, _, err := handler.Store.root(ctx) + if err != nil { + t.Fatal(err) + } + if err := handler.Store.Client.Delete(ctx, current); err != nil { + t.Fatal(err) + } + if handler.Handle(ctx, registrationRequest(t, device, "lost-ledger")).Allowed { + t.Fatal("missing ledger admitted") + } + response, err := server.Client().Get(server.URL + "/transportz") + if err != nil { + t.Fatal(err) + } + response.Body.Close() + if response.StatusCode != http.StatusNoContent { + t.Fatal("missing ledger prevented transport inspection") + } +} diff --git a/internal/registration/envtest_test.go b/internal/registration/envtest_test.go index 3793aa73..8e21127f 100644 --- a/internal/registration/envtest_test.go +++ b/internal/registration/envtest_test.go @@ -130,7 +130,29 @@ func TestRealAPIServerAdmissionAndCAS(t *testing.T) { } return Authorize(ctx, project, actor, group, resource, name) }} - server := httptest.NewTLSServer(&admission.Webhook{Handler: handler}) + privateKey := controlFixture(t, handler) + handler.VerifyFence = func(ctx context.Context) error { return VerifyFence(ctx, api, []string{"datum-cloud"}) } + handler.FenceDigest = func(ctx context.Context) (string, error) { + var current admissionregistrationv1.ValidatingWebhookConfiguration + if err := api.Get(ctx, client.ObjectKey{Name: "fleet-capacity-registration"}, ¤t); err != nil { + return "", err + } + encoded, err := json.Marshal(current.Webhooks) + return digest(encoded), err + } + lateAdmission, release := make(chan struct{}), make(chan struct{}) + server := httptest.NewTLSServer(&admission.Webhook{Handler: admission.HandlerFunc(func(ctx context.Context, request admission.Request) admission.Response { + response := handler.Handle(ctx, request) + if response.Allowed && request.Resource.Resource == "machinecapacities" && request.Name == "admitted-never-persisted" { + close(lateAdmission) + select { + case <-release: + case <-ctx.Done(): + } + return admission.Denied("synthetic later admission/storage failure") + } + return response + })}) t.Cleanup(server.Close) url := server.URL data, err := os.ReadFile("../../config/components/registration-admission/webhook.yaml") @@ -147,6 +169,14 @@ func TestRealAPIServerAdmissionAndCAS(t *testing.T) { if err := api.Create(ctx, webhooks); err != nil { t.Fatal(err) } + activation := controlFor(t, handler, privateKey, "activate").Request + activation.FenceDigest, err = handler.FenceDigest(ctx) + if err != nil { + t.Fatal(err) + } + if err := handler.ApplyControl(ctx, SignControl(activation, privateKey)); err != nil { + t.Fatal(err) + } actorConfig := rest.CopyConfig(config) actorConfig.Impersonate = rest.ImpersonationConfig{UserName: "operator", UID: "actor-1", Groups: []string{"system:masters"}, Extra: map[string][]string{iam.ParentKindExtraKey: {"Project"}, iam.ParentAPIGroupExtraKey: {"resourcemanager.miloapis.com"}, iam.ParentNameExtraKey: {"datum-cloud"}}} actor, err := client.New(actorConfig, client.Options{Scheme: scheme}) @@ -257,4 +287,73 @@ func TestRealAPIServerAdmissionAndCAS(t *testing.T) { if err := actor.Create(ctx, &rejected); !apierrors.IsForbidden(err) { t.Fatalf("revoked authorization bypass: %v", err) } + denied.Store(false) + pendingDevice := device.DeepCopyObject().(*inventory.Device) + pendingDevice.Name, pendingDevice.UID, pendingDevice.ResourceVersion = "pending-hardware", "", "" + pendingDevice.Spec.Identity.Serial = "pending-serial" + pendingDevice.Spec.Identity.SystemUUID = "22222222-2222-2222-2222-222222222222" + if err := actor.Create(ctx, pendingDevice); err != nil { + t.Fatal(err) + } + pendingRequest := registrationRequest(t, pendingDevice, "admitted-never-persisted") + var pendingCapacity metal.MachineCapacity + _ = json.Unmarshal(pendingRequest.Object.Raw, &pendingCapacity) + completed := make(chan error, 1) + go func() { completed <- actor.Create(ctx, &pendingCapacity) }() + select { + case <-lateAdmission: + case <-time.After(10 * time.Second): + t.Fatal("admission did not reach pause") + } + if err := handler.ApplyControl(ctx, controlFor(t, handler, privateKey, "expand")); err != nil { + close(release) + t.Fatal(err) + } + close(release) + if err := <-completed; !apierrors.IsForbidden(err) { + t.Fatal("expected later admission failure", err) + } + if err := handler.Recover(ctx); err != nil { + t.Fatal(err) + } + _, retained, err := handler.Store.Read(ctx) + if err != nil || len(retained.Entries) != 2 { + t.Fatal("lost pending public create", err) + } + for _, entry := range retained.Entries { + if entry.Name == pendingCapacity.Name && entry.Outcome != "Unknown" { + t.Fatal("absent object became free or recorded") + } + } + duplicateRequest := registrationRequest(t, pendingDevice, "after-expansion") + var duplicateCapacity metal.MachineCapacity + _ = json.Unmarshal(duplicateRequest.Object.Raw, &duplicateCapacity) + if err := actor.Create(ctx, &duplicateCapacity); !apierrors.IsForbidden(err) { + t.Fatal("expansion orphaned aliases", err) + } + _, route, err := handler.Store.root(ctx) + if err != nil { + t.Fatal(err) + } + segment := &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: route.Segments[0].Name, Namespace: "fleet-system-private"}} + if err := api.Delete(ctx, segment); !apierrors.IsInvalid(err) && !apierrors.IsForbidden(err) { + t.Fatal("segment deletion bypass", err) + } + if err := private.Delete(ctx, segment); !apierrors.IsInvalid(err) && !apierrors.IsForbidden(err) { + t.Fatal("service segment deletion bypass", err) + } + downgrade, _, err := handler.Store.Read(ctx) + if err != nil { + t.Fatal(err) + } + delete(downgrade.Data, "routing.json") + if err := private.Update(ctx, downgrade); !apierrors.IsInvalid(err) && !apierrors.IsForbidden(err) { + t.Fatal("v2 format downgrade bypass", err) + } + for _, name := range []string{"arbitrary-credential", LedgerName, SegmentPrefix + "mutable"} { + probe := &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Namespace: "fleet-system-private", Name: name}} + if err := private.Create(ctx, probe); !apierrors.IsInvalid(err) && !apierrors.IsForbidden(err) { + t.Fatal("service create boundary bypass", name, err) + } + } } diff --git a/internal/registration/fence.go b/internal/registration/fence.go index 2f9fbcef..3cb3fa9c 100644 --- a/internal/registration/fence.go +++ b/internal/registration/fence.go @@ -28,12 +28,25 @@ func requiredFences(projects []string) []admissionv1.ValidatingWebhook { } func VerifyFence(ctx context.Context, reader client.Reader, projects []string) error { - if len(projects) == 0 || slices.Contains(projects, "") || !slices.IsSorted(projects) || len(slices.Compact(slices.Clone(projects))) != len(projects) { - return errors.New("registration admission requires the exact sorted provider scope") - } + _, err := VerifiedFenceDigest(ctx, reader, projects) + return err +} + +func VerifiedFenceDigest(ctx context.Context, reader client.Reader, projects []string) (string, error) { var configuration admissionv1.ValidatingWebhookConfiguration if err := reader.Get(ctx, client.ObjectKey{Name: "fleet-capacity-registration"}, &configuration); err != nil { - return errors.New("project-plane registration admission configuration is unavailable") + return "", errors.New("project-plane registration admission configuration is unavailable") + } + if err := verifyFenceConfiguration(configuration, projects); err != nil { + return "", err + } + encoded, err := json.Marshal(configuration.Webhooks) + return digest(encoded), err +} + +func verifyFenceConfiguration(configuration admissionv1.ValidatingWebhookConfiguration, projects []string) error { + if len(projects) == 0 || slices.Contains(projects, "") || !slices.IsSorted(projects) || len(slices.Compact(slices.Clone(projects))) != len(projects) { + return errors.New("registration admission requires the exact sorted provider scope") } if !configuration.DeletionTimestamp.IsZero() { return errors.New("registration admission configuration is deleting") diff --git a/internal/registration/ledger.go b/internal/registration/ledger.go index 8452bc8b..ecfcc078 100644 --- a/internal/registration/ledger.go +++ b/internal/registration/ledger.go @@ -2,6 +2,7 @@ package registration import ( "context" + "crypto/ed25519" "encoding/json" "errors" "reflect" @@ -34,11 +35,15 @@ type Entry struct { } type DeviceFence struct { - Project string `json:"project"` - UID types.UID `json:"uid"` - Aliases []string `json:"aliases,omitempty"` - Deleted bool `json:"deleted,omitempty"` - Version string `json:"version,omitempty"` + Project string `json:"project"` + ProjectUID types.UID `json:"projectUID,omitempty"` + Namespace string `json:"namespace,omitempty"` + NamespaceUID types.UID `json:"namespaceUID,omitempty"` + Name string `json:"name,omitempty"` + UID types.UID `json:"uid"` + Aliases []string `json:"aliases,omitempty"` + Deleted bool `json:"deleted,omitempty"` + Version string `json:"version,omitempty"` } type Ledger struct { @@ -49,10 +54,12 @@ type Ledger struct { } type Store struct { - Client client.Client - Namespace string - Authority string - Projects []string + Client client.Client + Namespace string + Authority string + Projects []string + ControlKey ed25519.PublicKey + RequireActive bool } func (store Store) Read(ctx context.Context) (*corev1.Secret, Ledger, error) { @@ -60,8 +67,8 @@ func (store Store) Read(ctx context.Context) (*corev1.Secret, Ledger, error) { if err := store.Client.Get(ctx, client.ObjectKey{Namespace: store.Namespace, Name: LedgerName}, secret); err != nil { return nil, Ledger{}, err } - var ledger Ledger - if err := json.Unmarshal(secret.Data["ledger.json"], &ledger); err != nil { + ledger, _, err := store.readSnapshot(ctx, secret) + if err != nil { return nil, Ledger{}, err } if secret.UID == "" || !secret.DeletionTimestamp.IsZero() || ledger.Authority != store.Authority || !reflect.DeepEqual(ledger.Projects, store.Projects) { @@ -71,11 +78,14 @@ func (store Store) Read(ctx context.Context) (*corev1.Secret, Ledger, error) { } func (store Store) Write(ctx context.Context, secret *corev1.Secret, ledger Ledger) error { + if _, exists := secret.Data["routing.json"]; exists { + return store.writeSnapshot(ctx, secret, ledger) + } encoded, err := json.Marshal(ledger) if err != nil { return err } - if len(encoded) > 750000 { + if len(encoded) > TailBudget { return errors.New("registration ledger is full; reservations were not released") } secret.Data["ledger.json"] = encoded diff --git a/internal/registration/runtime.go b/internal/registration/runtime.go index 9d58323e..4f34c211 100644 --- a/internal/registration/runtime.go +++ b/internal/registration/runtime.go @@ -21,6 +21,7 @@ import ( ) func NewHandler(store Store, root client.Client, template *rest.Config, scheme *runtime.Scheme) *Handler { + store.RequireActive = true return &Handler{Store: store, VerifyFence: func(ctx context.Context) error { return VerifyFence(ctx, root, store.Projects) }, Resolve: func(ctx context.Context, name string) (Project, error) { identity, err := manager.ResolveProjectIdentity(ctx, root, store.Authority, name) if err != nil { @@ -32,7 +33,9 @@ func NewHandler(store Store, root client.Client, template *rest.Config, scheme * } api, err := client.New(config, client.Options{Scheme: scheme}) return Project{Identity: identity, Client: api}, err - }, Authorize: Authorize} + }, Authorize: Authorize, FenceDigest: func(ctx context.Context) (string, error) { + return VerifiedFenceDigest(ctx, root, store.Projects) + }} } func Authorize(ctx context.Context, project Project, actor authenticationv1.UserInfo, group, resource, name string) error { diff --git a/internal/registration/segments.go b/internal/registration/segments.go new file mode 100644 index 00000000..bbaca92a --- /dev/null +++ b/internal/registration/segments.go @@ -0,0 +1,253 @@ +package registration + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "reflect" + "slices" + + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/types" + "sigs.k8s.io/controller-runtime/pkg/client" +) + +const ( + TailBudget = 650000 + SegmentBudget = 750000 + MaxSegments = 16 + RootBudget = 850000 + SegmentPrefix = "fleet-registration-segment-" +) + +var ErrGrowthStopped = errors.New("registration growth stopped; signed lossless expansion required, reservations remain retained") + +type Segment struct { + Name string `json:"name"` + UID types.UID `json:"uid"` + Digest string `json:"digest"` +} + +type Routing struct { + Version int `json:"version"` + Epoch uint64 `json:"epoch"` + RootUID types.UID `json:"rootUID"` + Segments []Segment `json:"segments"` + Pending *SignedControl `json:"pending,omitempty"` + Activation *SignedControl `json:"activation,omitempty"` + ActivationHistory []SignedControl `json:"activationHistory,omitempty"` +} + +func digest(data []byte) string { + value := sha256.Sum256(data) + return hex.EncodeToString(value[:]) +} + +func decodeRouting(secret *corev1.Secret) (Routing, error) { + var route Routing + if err := json.Unmarshal(secret.Data["routing.json"], &route); err != nil { + return route, err + } + if route.Version != 2 || route.RootUID != secret.UID || route.Epoch != uint64(len(route.Segments)) || len(route.Segments) > MaxSegments || len(route.ActivationHistory) > 7 { + return route, errors.New("invalid registration routing identity or epoch") + } + return route, nil +} + +func (store Store) readSnapshot(ctx context.Context, secret *corev1.Secret) (Ledger, Ledger, error) { + base := Ledger{Authority: store.Authority, Projects: store.Projects} + key := "ledger.json" + if _, exists := secret.Data["routing.json"]; exists { + route, err := decodeRouting(secret) + if err != nil { + return Ledger{}, Ledger{}, err + } + key = "tail.json" + for index, reference := range route.Segments { + if reference.Name != segmentName(secret.UID, uint64(index)) || reference.UID == "" { + return Ledger{}, Ledger{}, errors.New("invalid segment identity") + } + segment := &corev1.Secret{} + if err := store.Client.Get(ctx, client.ObjectKey{Namespace: store.Namespace, Name: reference.Name}, segment); err != nil { + return Ledger{}, Ledger{}, err + } + if segment.UID != reference.UID || segment.Immutable == nil || !*segment.Immutable || !segment.DeletionTimestamp.IsZero() || digest(segment.Data["ledger.json"]) != reference.Digest { + return Ledger{}, Ledger{}, errors.New("segment lifetime or integrity unavailable") + } + var delta Ledger + if err := json.Unmarshal(segment.Data["ledger.json"], &delta); err != nil { + return Ledger{}, Ledger{}, err + } + if delta.Authority != store.Authority || !reflect.DeepEqual(delta.Projects, store.Projects) { + return Ledger{}, Ledger{}, errors.New("segment scope mismatch") + } + base = overlay(base, delta) + } + } + var tail Ledger + if err := json.Unmarshal(secret.Data[key], &tail); err != nil { + return Ledger{}, Ledger{}, err + } + if tail.Authority != store.Authority || !reflect.DeepEqual(tail.Projects, store.Projects) { + return Ledger{}, Ledger{}, errors.New("ledger scope mismatch") + } + return overlay(base, tail), base, nil +} + +func fenceKey(fence DeviceFence) string { + encoded, _ := json.Marshal([]string{fence.Project, string(fence.UID)}) + return string(encoded) +} + +func overlay(base, tail Ledger) Ledger { + result := Ledger{Authority: base.Authority, Projects: base.Projects} + entries := map[types.UID]bool{} + fences := map[string]bool{} + for _, entry := range tail.Entries { + entries[entry.Operation] = true + } + for _, fence := range tail.DeviceFences { + fences[fenceKey(fence)] = true + } + for _, entry := range base.Entries { + if !entries[entry.Operation] { + result.Entries = append(result.Entries, entry) + } + } + for _, fence := range base.DeviceFences { + if !fences[fenceKey(fence)] { + result.DeviceFences = append(result.DeviceFences, fence) + } + } + result.Entries = append(result.Entries, tail.Entries...) + result.DeviceFences = append(result.DeviceFences, tail.DeviceFences...) + return result +} + +func deltaFrom(base, current Ledger) Ledger { + delta := Ledger{Authority: current.Authority, Projects: current.Projects} + baseEntries := map[types.UID][]Entry{} + currentEntries := map[types.UID][]Entry{} + baseFences := map[string][]DeviceFence{} + currentFences := map[string][]DeviceFence{} + for _, entry := range base.Entries { + baseEntries[entry.Operation] = append(baseEntries[entry.Operation], entry) + } + for _, entry := range current.Entries { + currentEntries[entry.Operation] = append(currentEntries[entry.Operation], entry) + } + for _, fence := range base.DeviceFences { + baseFences[fenceKey(fence)] = append(baseFences[fenceKey(fence)], fence) + } + for _, fence := range current.DeviceFences { + currentFences[fenceKey(fence)] = append(currentFences[fenceKey(fence)], fence) + } + for _, entry := range current.Entries { + if !reflect.DeepEqual(baseEntries[entry.Operation], currentEntries[entry.Operation]) { + delta.Entries = append(delta.Entries, entry) + } + } + for _, fence := range current.DeviceFences { + if !reflect.DeepEqual(baseFences[fenceKey(fence)], currentFences[fenceKey(fence)]) { + delta.DeviceFences = append(delta.DeviceFences, fence) + } + } + return delta +} + +func preservesReservations(before, after Ledger) bool { + if before.Authority != after.Authority || !reflect.DeepEqual(before.Projects, after.Projects) { + return false + } + entries := map[types.UID][]Entry{} + fences := map[string][]DeviceFence{} + for _, entry := range after.Entries { + entries[entry.Operation] = append(entries[entry.Operation], entry) + } + for _, fence := range after.DeviceFences { + fences[fenceKey(fence)] = append(fences[fenceKey(fence)], fence) + } + for _, previous := range before.Entries { + found := false + for _, next := range entries[previous.Operation] { + next.Outcome = previous.Outcome + if reflect.DeepEqual(previous, next) { + found = true + break + } + } + if !found { + return false + } + } + for _, previous := range before.DeviceFences { + found := false + for _, next := range fences[fenceKey(previous)] { + if fenceKey(previous) != fenceKey(next) || (previous.Deleted && !next.Deleted) { + continue + } + if previous.ProjectUID != "" && previous.ProjectUID != next.ProjectUID { + continue + } + if previous.NamespaceUID != "" && previous.NamespaceUID != next.NamespaceUID { + continue + } + if previous.Name != "" && (previous.Name != next.Name || previous.Namespace != next.Namespace) { + continue + } + if slices.ContainsFunc(previous.Aliases, func(alias string) bool { return !slices.Contains(next.Aliases, alias) }) { + continue + } + found = true + } + if !found { + return false + } + } + return true +} + +func (store Store) writeSnapshot(ctx context.Context, secret *corev1.Secret, current Ledger) error { + route, err := decodeRouting(secret) + if err != nil { + return err + } + if route.Pending != nil { + return errors.New("registration expansion is fenced") + } + previous, base, err := store.readSnapshot(ctx, secret) + if err != nil { + return err + } + if !preservesReservations(previous, current) { + return errors.New("registration write would discard retained authority") + } + encoded, err := json.Marshal(deltaFrom(base, current)) + if err != nil { + return err + } + if len(encoded) > TailBudget { + return ErrGrowthStopped + } + updated := secret.DeepCopy() + updated.Data["tail.json"] = encoded + return store.updateRoot(ctx, updated) +} + +func (store Store) updateRoot(ctx context.Context, secret *corev1.Secret) error { + size := 0 + for key, value := range secret.Data { + size += len(key) + len(value) + } + if size > RootBudget { + return ErrGrowthStopped + } + return store.Client.Update(ctx, secret) +} + +func segmentName(uid types.UID, epoch uint64) string { + return fmt.Sprintf("%s%s-%02d", SegmentPrefix, digest([]byte(uid))[:24], epoch) +} diff --git a/internal/registration/segments_envtest_test.go b/internal/registration/segments_envtest_test.go new file mode 100644 index 00000000..a5eb8168 --- /dev/null +++ b/internal/registration/segments_envtest_test.go @@ -0,0 +1,382 @@ +package registration + +import ( + "context" + "crypto/ed25519" + "crypto/x509" + "encoding/json" + "encoding/pem" + "errors" + "fmt" + "os" + "os/exec" + "path/filepath" + "reflect" + "strings" + "sync" + "testing" + + corev1 "k8s.io/api/core/v1" + rbacv1 "k8s.io/api/rbac/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/types" + "k8s.io/client-go/rest" + "k8s.io/client-go/tools/clientcmd" + clientcmdapi "k8s.io/client-go/tools/clientcmd/api" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/envtest" +) + +type faultClient struct { + client.Client + createAfter bool + createBefore bool + updateAt int + updates int + updateAfter bool + crash bool +} + +func (fault *faultClient) fail() error { + if fault.crash { + os.Exit(23) + } + return context.DeadlineExceeded +} + +func (fault *faultClient) Create(ctx context.Context, object client.Object, options ...client.CreateOption) error { + if fault.createBefore { + return fault.fail() + } + if err := fault.Client.Create(ctx, object, options...); err != nil { + return err + } + if fault.createAfter { + return fault.fail() + } + return nil +} + +func (fault *faultClient) Update(ctx context.Context, object client.Object, options ...client.UpdateOption) error { + fault.updates++ + if fault.updates == fault.updateAt && !fault.updateAfter { + return fault.fail() + } + if err := fault.Client.Update(ctx, object, options...); err != nil { + return err + } + if fault.updates == fault.updateAt && fault.updateAfter { + return fault.fail() + } + return nil +} + +func TestRegistrationExpansionWorker(t *testing.T) { + configPath := os.Getenv("FLEET_TEST_CONFIG") + if configPath == "" { + return + } + config, err := clientcmd.BuildConfigFromFlags("", configPath) + if err != nil { + t.Fatal(err) + } + scheme := runtime.NewScheme() + _ = corev1.AddToScheme(scheme) + _ = rbacv1.AddToScheme(scheme) + api, err := client.New(config, client.Options{Scheme: scheme}) + if err != nil { + t.Fatal(err) + } + encoded, err := os.ReadFile(os.Getenv("FLEET_TEST_PUBLIC")) + if err != nil { + t.Fatal(err) + } + public, err := ParseControlKey(encoded) + if err != nil { + t.Fatal(err) + } + store := Store{Client: api, Namespace: os.Getenv("FLEET_TEST_NAMESPACE"), Authority: "milo", Projects: []string{"provider"}, ControlKey: public} + fault := &faultClient{Client: api, crash: true} + switch os.Getenv("FLEET_TEST_CRASH") { + case "freeze": + fault.updateAt, fault.updateAfter = 1, true + case "segment-before": + fault.createBefore = true + case "segment-after": + fault.createAfter = true + case "switch-before": + fault.updateAt = 2 + case "switch-after": + fault.updateAt, fault.updateAfter = 2, true + default: + if err := store.ResumeExpansion(context.Background()); err != nil { + t.Fatal(err) + } + return + } + store.Client = fault + encoded, err = os.ReadFile(os.Getenv("FLEET_TEST_REQUEST")) + if err != nil { + t.Fatal(err) + } + control, err := ParseControl(encoded) + if err != nil { + t.Fatal(err) + } + handler := &Handler{Store: store} + if err := handler.ApplyControl(context.Background(), control); err != nil { + t.Fatal(err) + } + t.Fatal("fault boundary was not reached") +} + +func TestRealLosslessExpansionAndProcessRecovery(t *testing.T) { + if os.Getenv("KUBEBUILDER_ASSETS") == "" { + t.Skip("KUBEBUILDER_ASSETS required") + } + environment := &envtest.Environment{} + config, err := environment.Start() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if err := environment.Stop(); err != nil { + t.Error(err) + } + }) + scheme := runtime.NewScheme() + _ = corev1.AddToScheme(scheme) + _ = rbacv1.AddToScheme(scheme) + api, err := client.New(config, client.Options{Scheme: scheme}) + if err != nil { + t.Fatal(err) + } + ctx := context.Background() + newHandler := func(t *testing.T, namespace string) (*Handler, ed25519.PrivateKey) { + handler, _ := fixture(t) + secret, ledger, err := handler.Store.Read(ctx) + if err != nil { + t.Fatal(err) + } + ledger.Entries = []Entry{{Operation: "admitted-not-persisted", Project: "provider", ProjectUID: "project-1", NamespaceUID: "namespace-1", CapacityUID: "public-uid", DeviceUID: "device-1", DeviceVersion: "v1", Aliases: []string{"uuid:reserved"}, Input: json.RawMessage(`{"spec":{"allocationPolicy":"Disabled","reclaimPolicy":"Retain"}}`), Outcome: "Unknown"}} + ledger.DeviceFences = []DeviceFence{{Project: "provider", UID: "legacy", Version: "old", Aliases: []string{"legacy-alias"}}, {Project: "provider", UID: "legacy", Version: "pending"}, {Project: "provider", UID: "deleted", Deleted: true, Aliases: []string{"never-release"}}} + secret.Data["ledger.json"], _ = json.Marshal(ledger) + secret.Namespace, secret.UID, secret.ResourceVersion = namespace, "", "" + if err := api.Create(ctx, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: namespace}}); err != nil { + t.Fatal(err) + } + if err := api.Create(ctx, secret); err != nil { + t.Fatal(err) + } + handler.Store.Client, handler.Store.Namespace = api, namespace + return handler, controlFixture(t, handler) + } + kubeconfig := clientcmdapi.Config{Clusters: map[string]*clientcmdapi.Cluster{"test": {Server: config.Host, CertificateAuthorityData: config.CAData}}, AuthInfos: map[string]*clientcmdapi.AuthInfo{"test": {ClientCertificateData: config.CertData, ClientKeyData: config.KeyData}}, Contexts: map[string]*clientcmdapi.Context{"test": {Cluster: "test", AuthInfo: "test"}}, CurrentContext: "test"} + kubeBytes, err := clientcmd.Write(kubeconfig) + if err != nil { + t.Fatal(err) + } + kubePath := filepath.Join(t.TempDir(), "config") + if err := os.WriteFile(kubePath, kubeBytes, 0600); err != nil { + t.Fatal(err) + } + for _, boundary := range []string{"freeze", "segment-before", "segment-after", "switch-before", "switch-after"} { + t.Run(boundary, func(t *testing.T) { + handler, key := newHandler(t, boundary) + stale, before, err := handler.Store.Read(ctx) + if err != nil { + t.Fatal(err) + } + control := controlFor(t, handler, key, "expand") + encoded, _ := json.Marshal(control) + requestPath := filepath.Join(t.TempDir(), "request") + if err := os.WriteFile(requestPath, encoded, 0600); err != nil { + t.Fatal(err) + } + publicDER, _ := x509.MarshalPKIXPublicKey(handler.Store.ControlKey) + publicPath := filepath.Join(t.TempDir(), "public") + if err := os.WriteFile(publicPath, pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: publicDER}), 0600); err != nil { + t.Fatal(err) + } + runWorker := func(crash string) error { + command := exec.Command(os.Args[0], "-test.run=^TestRegistrationExpansionWorker$") + command.Env = append(os.Environ(), "FLEET_TEST_CONFIG="+kubePath, "FLEET_TEST_NAMESPACE="+handler.Store.Namespace, "FLEET_TEST_PUBLIC="+publicPath, "FLEET_TEST_REQUEST="+requestPath, "FLEET_TEST_CRASH="+crash) + output, err := command.CombinedOutput() + if err != nil && crash == "" { + t.Log(string(output)) + } + return err + } + var exit *exec.ExitError + if err := runWorker(boundary); !errors.As(err, &exit) || exit.ExitCode() != 23 { + t.Fatalf("expected injected process crash: %v", err) + } + if handler.Store.Write(ctx, stale, before) == nil { + t.Fatal("pre-freeze writer committed") + } + if err := runWorker(""); err != nil { + t.Fatal("restart", err) + } + _, after, err := handler.Store.Read(ctx) + if err != nil || !reflect.DeepEqual(before, after) { + t.Fatalf("restart lost reservations: %v\n%+v", err, after) + } + _, route, err := handler.Store.root(ctx) + if err != nil || route.Pending != nil || route.Epoch != 1 || len(route.Segments) != 1 { + t.Fatalf("unfinished expansion: %+v %v", route, err) + } + var segments corev1.SecretList + if err := api.List(ctx, &segments, client.InNamespace(handler.Store.Namespace)); err != nil || len(segments.Items) != 2 { + t.Fatalf("orphan segments: %d %v", len(segments.Items), err) + } + }) + } + t.Run("full-legacy-sealing", func(t *testing.T) { + handler, key := newHandler(t, "full-legacy") + secret, before, err := handler.Store.Read(ctx) + if err != nil { + t.Fatal(err) + } + before.DeviceFences = append(before.DeviceFences, DeviceFence{Project: "provider", UID: "large", Aliases: []string{""}}) + encoded, _ := json.Marshal(before) + before.DeviceFences[len(before.DeviceFences)-1].Aliases[0] = strings.Repeat("x", SegmentBudget-len(encoded)) + secret.Data["ledger.json"], _ = json.Marshal(before) + if err := api.Update(ctx, secret); err != nil { + t.Fatal(err) + } + if err := handler.ApplyControl(ctx, controlFor(t, handler, key, "expand")); err != nil { + t.Fatal(err) + } + _, after, err := handler.Store.Read(ctx) + if err != nil || !reflect.DeepEqual(before, after) { + t.Fatal("full legacy data lost", err) + } + status, err := handler.Status(ctx) + if err != nil || status.HeadroomBytes < TailBudget-1000 || status.Epoch != 1 || status.ActivationVerified { + t.Fatalf("bad expanded bootstrap status: %+v %v", status, err) + } + }) + t.Run("multi-replica-and-growth", func(t *testing.T) { + handler, key := newHandler(t, "replicas") + _, before, _ := handler.Store.Read(ctx) + control := controlFor(t, handler, key, "expand") + var workers sync.WaitGroup + for range 8 { + workers.Add(1) + go func() { defer workers.Done(); replica := *handler; _ = replica.ApplyControl(ctx, control) }() + } + workers.Wait() + if err := handler.Store.ResumeExpansion(ctx); err != nil { + t.Fatal(err) + } + if err := handler.ApplyControl(ctx, control); err != nil { + t.Fatal("lost completion response cannot be reconciled", err) + } + secret, after, err := handler.Store.Read(ctx) + if err != nil || !reflect.DeepEqual(before, after) { + t.Fatal("concurrent migration lost history", err) + } + for attempt := 1; attempt < MaxSegments; attempt++ { + after.DeviceFences = append(after.DeviceFences, DeviceFence{Project: "provider", UID: types.UID(fmt.Sprint("new-", attempt)), Aliases: []string{strings.Repeat("a", TailBudget-1000)}}) + if err := handler.Store.Write(ctx, secret, after); err != nil { + t.Fatal(err) + } + secret, after, _ = handler.Store.Read(ctx) + tooLarge := after + tooLarge.DeviceFences = append(append([]DeviceFence(nil), after.DeviceFences...), DeviceFence{Project: "provider", UID: "oversize", Aliases: []string{strings.Repeat("b", 2000)}}) + if !errors.Is(handler.Store.Write(ctx, secret, tooLarge), ErrGrowthStopped) { + t.Fatal("tail headroom not enforced") + } + if err := handler.ApplyControl(ctx, controlFor(t, handler, key, "expand")); err != nil { + t.Fatal(err) + } + secret, after, err = handler.Store.Read(ctx) + if err != nil { + t.Fatal(err) + } + } + if !errors.Is(handler.ApplyControl(ctx, controlFor(t, handler, key, "expand")), ErrGrowthStopped) { + t.Fatal("unbounded expansion") + } + if after.Entries[0].Outcome != "Unknown" || len(after.DeviceFences) != len(before.DeviceFences)+MaxSegments-1 { + t.Fatal("growth changed custody") + } + _, route, _ := handler.Store.root(ctx) + segment := &corev1.Secret{} + if err := api.Get(ctx, client.ObjectKey{Namespace: handler.Store.Namespace, Name: route.Segments[0].Name}, segment); err != nil { + t.Fatal(err) + } + segment.Data["ledger.json"] = []byte("{}") + if err := api.Update(ctx, segment); !apierrors.IsInvalid(err) { + t.Fatal("segment mutable", err) + } + if err := api.Delete(ctx, segment); err != nil { + t.Fatal(err) + } + if _, _, err := handler.Store.Read(ctx); err == nil { + t.Fatal("missing segment treated as free") + } + segment.UID, segment.ResourceVersion = "", "" + if err := api.Create(ctx, segment); err != nil { + t.Fatal(err) + } + if _, _, err := handler.Store.Read(ctx); err == nil { + t.Fatal("replacement segment adopted") + } + }) + t.Run("uncertain-write-and-read-only", func(t *testing.T) { + handler, key := newHandler(t, "uncertain") + if err := handler.ApplyControl(ctx, controlFor(t, handler, key, "expand")); err != nil { + t.Fatal(err) + } + secret, ledger, _ := handler.Store.Read(ctx) + ledger.DeviceFences = append(ledger.DeviceFences, DeviceFence{Project: "provider", UID: "uncertain", Aliases: []string{"retained"}}) + store := handler.Store + store.Client = &faultClient{Client: api, updateAt: 1, updateAfter: true} + if !errors.Is(store.Write(ctx, secret, ledger), context.DeadlineExceeded) { + t.Fatal("write should be uncertain") + } + secret, observed, err := handler.Store.Read(ctx) + if err != nil || !reflect.DeepEqual(ledger, observed) { + t.Fatal("persist timeout released state", err) + } + store.Client = &faultClient{Client: api, updateAt: 1} + observed.DeviceFences = append(observed.DeviceFences, DeviceFence{Project: "provider", UID: "denied"}) + if store.Write(ctx, secret, observed) == nil { + t.Fatal("read-only storage admitted") + } + _, retained, err := handler.Store.Read(ctx) + if err != nil || !reflect.DeepEqual(ledger, retained) { + t.Fatal("read-only failure changed history", err) + } + retained.DeviceFences = nil + if handler.Store.Write(ctx, secret, retained) == nil { + t.Fatal("alias removal accepted") + } + role := &rbacv1.Role{ObjectMeta: metav1.ObjectMeta{Name: "reader", Namespace: handler.Store.Namespace}, Rules: []rbacv1.PolicyRule{{APIGroups: []string{""}, Resources: []string{"secrets"}, Verbs: []string{"get"}}}} + if err := api.Create(ctx, role); err != nil { + t.Fatal(err) + } + binding := &rbacv1.RoleBinding{ObjectMeta: metav1.ObjectMeta{Name: "reader", Namespace: handler.Store.Namespace}, Subjects: []rbacv1.Subject{{Kind: "User", Name: "ledger-reader"}}, RoleRef: rbacv1.RoleRef{APIGroup: "rbac.authorization.k8s.io", Kind: "Role", Name: "reader"}} + if err := api.Create(ctx, binding); err != nil { + t.Fatal(err) + } + readOnlyConfig := rest.CopyConfig(config) + readOnlyConfig.Impersonate = rest.ImpersonationConfig{UserName: "ledger-reader", Groups: []string{"system:authenticated"}} + readOnly, err := client.New(readOnlyConfig, client.Options{Scheme: scheme}) + if err != nil { + t.Fatal(err) + } + store.Client = readOnly + secret, observed, err = store.Read(ctx) + if err != nil { + t.Fatal("read-only observation should work", err) + } + observed.DeviceFences = append(observed.DeviceFences, DeviceFence{Project: "provider", UID: "forbidden"}) + if err := store.Write(ctx, secret, observed); !apierrors.IsForbidden(err) { + t.Fatal("read-only storage wrote", err) + } + }) +} diff --git a/internal/registration/transport.go b/internal/registration/transport.go new file mode 100644 index 00000000..1113fe89 --- /dev/null +++ b/internal/registration/transport.go @@ -0,0 +1,104 @@ +package registration + +import ( + "context" + "crypto/ed25519" + "crypto/x509" + "encoding/json" + "encoding/pem" + "errors" + "net/http" + "time" + + "k8s.io/apimachinery/pkg/types" + + "sigs.k8s.io/controller-runtime/pkg/webhook/admission" +) + +func ParseControlKey(encoded []byte) (ed25519.PublicKey, error) { + block, rest := pem.Decode(encoded) + if block == nil || len(rest) != 0 { + return nil, errors.New("expected one PKIX public key") + } + parsed, err := x509.ParsePKIXPublicKey(block.Bytes) + if err != nil { + return nil, err + } + key, ok := parsed.(ed25519.PublicKey) + if !ok { + return nil, errors.New("control key must be Ed25519") + } + return key, nil +} + +func ParseControl(encoded []byte) (SignedControl, error) { + var control SignedControl + if len(encoded) > 16384 { + return control, errors.New("control request exceeds budget") + } + err := json.Unmarshal(encoded, &control) + return control, err +} + +func (handler *Handler) Transport() http.Handler { + mux := http.NewServeMux() + mux.Handle("/validate-registration", &admission.Webhook{Handler: handler}) + mux.HandleFunc("/transportz", func(writer http.ResponseWriter, request *http.Request) { + writer.WriteHeader(http.StatusNoContent) + }) + mux.HandleFunc("/activationz", func(writer http.ResponseWriter, request *http.Request) { + ctx, cancel := context.WithTimeout(request.Context(), 5*time.Second) + defer cancel() + if err := handler.Ready(ctx); err != nil { + http.Error(writer, "registration non-admitting or dependencies unavailable", http.StatusServiceUnavailable) + return + } + writer.WriteHeader(http.StatusNoContent) + }) + mux.HandleFunc("/status", func(writer http.ResponseWriter, request *http.Request) { + ctx, cancel := context.WithTimeout(request.Context(), 5*time.Second) + defer cancel() + status, err := handler.Status(ctx) + if err != nil { + http.Error(writer, "registration ledger unavailable", http.StatusServiceUnavailable) + return + } + writer.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(writer).Encode(status) + }) + return mux +} + +type Status struct { + Authority string `json:"authority"` + Projects []string `json:"projects"` + RootUID types.UID `json:"rootUID"` + ResourceVersion string `json:"resourceVersion"` + Epoch uint64 `json:"epoch"` + TailBytes int `json:"tailBytes"` + HeadroomBytes int `json:"headroomBytes"` + RemainingSegments int `json:"remainingSegments"` + Pending bool `json:"pending"` + ActivationVerified bool `json:"activationVerified"` + FenceDigest string `json:"fenceDigest,omitempty"` +} + +func (handler *Handler) Status(ctx context.Context) (Status, error) { + secret, route, err := handler.Store.root(ctx) + if err != nil { + return Status{}, err + } + if _, _, err := handler.Store.readSnapshot(ctx, secret); err != nil { + return Status{}, err + } + tail := secret.Data["tail.json"] + if _, exists := secret.Data["routing.json"]; !exists { + tail = secret.Data["ledger.json"] + } + status := Status{Authority: handler.Store.Authority, Projects: handler.Store.Projects, RootUID: secret.UID, ResourceVersion: secret.ResourceVersion, Epoch: route.Epoch, TailBytes: len(tail), HeadroomBytes: max(0, TailBudget-len(tail)), RemainingSegments: MaxSegments - len(route.Segments), Pending: route.Pending != nil} + status.ActivationVerified = handler.readySnapshot(ctx, secret, route) == nil + if handler.FenceDigest != nil { + status.FenceDigest, _ = handler.FenceDigest(ctx) + } + return status, nil +} From 844c9bb6206b68cfb3300ab80cb92b149fab11ad Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sun, 22 Nov 2026 14:31:47 -0600 Subject: [PATCH 070/518] fix(registration): drain terminating namespaces and fail closed by default Device deletes and finalizer-only updates no longer need a live namespace. They bind the terminating namespace UID, or the UID already recorded once the namespace is gone, and still write a permanent tombstone. Before this, a Device delete in a terminating provider namespace was denied and the namespace could stay in Terminating. At 16 sealed segments, writes and expand now return ErrSegmentsExhausted, which says a reviewed storage migration is required and cites the runbook. It still matches ErrGrowthStopped. A full v1 ledger now says to sign an expand request. The activation gate is on by default. Store.RequireActive becomes AllowInactiveForTests, and NewHandler forces it off. Co-Authored-By: Claude Opus 5.5 --- cmd/fleet-registration/main.go | 2 +- internal/registration/admission.go | 92 +++++++++- .../admission_regression_envtest_test.go | 2 +- internal/registration/admission_test.go | 2 +- internal/registration/control.go | 2 +- internal/registration/control_test.go | 2 +- internal/registration/ledger.go | 16 +- .../registration/namespace_lifetime_test.go | 167 ++++++++++++++++++ internal/registration/runtime.go | 2 +- internal/registration/segments.go | 16 ++ internal/registration/terminal_errors_test.go | 121 +++++++++++++ 11 files changed, 402 insertions(+), 22 deletions(-) create mode 100644 internal/registration/namespace_lifetime_test.go create mode 100644 internal/registration/terminal_errors_test.go diff --git a/cmd/fleet-registration/main.go b/cmd/fleet-registration/main.go index 29cd97f6..f37c2e8a 100644 --- a/cmd/fleet-registration/main.go +++ b/cmd/fleet-registration/main.go @@ -92,7 +92,7 @@ func run(ctx context.Context, configFile, providers, namespace, cert, key, clien if err != nil { return err } - handler := registration.NewHandler(registration.Store{Client: private, Namespace: namespace, Authority: config.AuthorityID, Projects: projects, ControlKey: publicKey, RequireActive: true}, root, template, scheme) + handler := registration.NewHandler(registration.Store{Client: private, Namespace: namespace, Authority: config.AuthorityID, Projects: projects, ControlKey: publicKey}, root, template, scheme) tlsConfig, err := webhookTLS(clientCA) if err != nil { return err diff --git a/internal/registration/admission.go b/internal/registration/admission.go index 28cc087b..f4959d2b 100644 --- a/internal/registration/admission.go +++ b/internal/registration/admission.go @@ -88,7 +88,7 @@ func projectName(actor authenticationv1.UserInfo) (string, error) { } func (handler *Handler) Handle(ctx context.Context, request admission.Request) admission.Response { - if handler.Store.RequireActive { + if !handler.Store.AllowInactiveForTests { if err := handler.Ready(ctx); err != nil { return admission.Denied(err.Error()) } @@ -375,23 +375,26 @@ func (handler *Handler) device(ctx context.Context, project Project, request adm if request.Operation == admissionv1.Update && identicalObjects(request.OldObject.Raw, request.Object.Raw) { return nil } - var namespace corev1.Namespace - if err := project.Client.Get(ctx, client.ObjectKey{Name: device.Namespace}, &namespace); err != nil { + // Deletes and finalizer removals are how a terminating namespace drains its + // Devices, so they must not depend on the namespace still being live. + releasing := request.Operation == admissionv1.Delete || (request.Operation == admissionv1.Update && finalizerRemoval(request.OldObject.Raw, request.Object.Raw)) + deleting := request.Operation == admissionv1.Delete || (releasing && !old.DeletionTimestamp.IsZero()) + namespaceUID, err := deviceNamespace(ctx, project, device, ledger, releasing) + if err != nil { return err } - if namespace.UID == "" || !namespace.DeletionTimestamp.IsZero() { - return errors.New("Device namespace lifetime unavailable") - } - fence := DeviceFence{Project: project.Identity.RouteName, ProjectUID: project.Identity.UID, Namespace: device.Namespace, NamespaceUID: namespace.UID, Name: device.Name, UID: device.UID, Deleted: request.Operation == admissionv1.Delete} + fence := DeviceFence{Project: project.Identity.RouteName, ProjectUID: project.Identity.UID, Namespace: device.Namespace, NamespaceUID: namespaceUID, Name: device.Name, UID: device.UID, Deleted: deleting} if request.Operation == admissionv1.Update { current := &inventory.Device{} if err := project.Client.Get(ctx, client.ObjectKeyFromObject(&old), current); err != nil { return err } - if current.UID != old.UID || current.ResourceVersion != old.ResourceVersion || device.ResourceVersion != old.ResourceVersion || !current.DeletionTimestamp.IsZero() { + if current.UID != old.UID || current.ResourceVersion != old.ResourceVersion || device.ResourceVersion != old.ResourceVersion || (!current.DeletionTimestamp.IsZero() && !deleting) { return errors.New("Device update baseline is no longer current") } - fence.Version = old.ResourceVersion + if !deleting { + fence.Version = old.ResourceVersion + } } if request.Operation == admissionv1.Create { fence.Aliases = aliases(&device) @@ -428,6 +431,77 @@ func (handler *Handler) device(ctx context.Context, project Project, request adm return handler.Store.Write(ctx, secret, ledger) } +// deviceNamespace returns the namespace lifetime to bind into the Device fence. +// Ordinary writes require a live namespace. Releasing writes accept a +// terminating namespace, and once the namespace is gone they fall back to the +// lifetime already recorded for this Device so the tombstone never loses it. +func deviceNamespace(ctx context.Context, project Project, device inventory.Device, ledger Ledger, releasing bool) (types.UID, error) { + var namespace corev1.Namespace + err := project.Client.Get(ctx, client.ObjectKey{Name: device.Namespace}, &namespace) + if err != nil && (!releasing || !apierrors.IsNotFound(err)) { + return "", err + } + if err == nil { + if namespace.UID == "" || (!releasing && !namespace.DeletionTimestamp.IsZero()) { + return "", errors.New("Device namespace lifetime unavailable") + } + return namespace.UID, nil + } + for _, retained := range ledger.DeviceFences { + if retained.Project == project.Identity.RouteName && retained.UID == device.UID && retained.NamespaceUID != "" { + return retained.NamespaceUID, nil + } + } + // A legacy fence never recorded the namespace; the tombstone stays + // legacy-shaped rather than inventing a lifetime or denying the delete. + return "", nil +} + +// finalizerRemoval reports whether an update only removes finalizers. Server +// managed field bookkeeping is ignored; any other change is a real edit. +func finalizerRemoval(old, current []byte) bool { + decode := func(raw []byte) (map[string]any, []string, bool) { + decoder := json.NewDecoder(bytes.NewReader(raw)) + decoder.UseNumber() + var object map[string]any + if err := decoder.Decode(&object); err != nil || object == nil || decoder.Decode(new(any)) != io.EOF { + return nil, nil, false + } + metadata, _ := object["metadata"].(map[string]any) + if metadata == nil { + return nil, nil, false + } + var finalizers []string + if values, exists := metadata["finalizers"]; exists { + list, ok := values.([]any) + if !ok { + return nil, nil, false + } + for _, value := range list { + name, ok := value.(string) + if !ok { + return nil, nil, false + } + finalizers = append(finalizers, name) + } + } + delete(metadata, "finalizers") + delete(metadata, "managedFields") + return object, finalizers, true + } + before, beforeFinalizers, beforeOK := decode(old) + after, afterFinalizers, afterOK := decode(current) + if !beforeOK || !afterOK || len(afterFinalizers) >= len(beforeFinalizers) || !reflect.DeepEqual(before, after) { + return false + } + for _, name := range afterFinalizers { + if !slices.Contains(beforeFinalizers, name) { + return false + } + } + return true +} + func identicalObjects(old, current []byte) bool { decode := func(raw []byte) (map[string]any, error) { decoder := json.NewDecoder(bytes.NewReader(raw)) diff --git a/internal/registration/admission_regression_envtest_test.go b/internal/registration/admission_regression_envtest_test.go index 0fe71ef5..ff65a8f7 100644 --- a/internal/registration/admission_regression_envtest_test.go +++ b/internal/registration/admission_regression_envtest_test.go @@ -94,7 +94,7 @@ func TestRealNoopRegistrationAndScopedTransportFailure(t *testing.T) { if err := api.Create(ctx, &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: LedgerName, Namespace: "default"}, Data: map[string][]byte{"ledger.json": encoded}}); err != nil { t.Fatal(err) } - handler := &Handler{Store: Store{Client: api, Namespace: "default", Authority: "milo", Projects: []string{"datum-cloud"}}, VerifyFence: func(ctx context.Context) error { return VerifyFence(ctx, api, []string{"datum-cloud"}) }, Resolve: func(context.Context, string) (Project, error) { + handler := &Handler{Store: Store{Client: api, Namespace: "default", Authority: "milo", Projects: []string{"datum-cloud"}, AllowInactiveForTests: true}, VerifyFence: func(ctx context.Context) error { return VerifyFence(ctx, api, []string{"datum-cloud"}) }, Resolve: func(context.Context, string) (Project, error) { return Project{Identity: controller.ProjectIdentity{AuthorityID: "milo", RouteName: "datum-cloud", UID: "project-1"}, Client: api}, nil }, Authorize: Authorize} type gate struct { diff --git a/internal/registration/admission_test.go b/internal/registration/admission_test.go index efd71d74..14ac05b5 100644 --- a/internal/registration/admission_test.go +++ b/internal/registration/admission_test.go @@ -37,7 +37,7 @@ func fixture(t *testing.T) (*Handler, *inventory.Device) { api := fake.NewClientBuilder().WithScheme(scheme).WithObjects(device, namespace).Build() encoded, _ := json.Marshal(Ledger{Authority: "milo", Projects: []string{"provider"}}) private := fake.NewClientBuilder().WithScheme(scheme).WithObjects(&corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: LedgerName, Namespace: "private", UID: "ledger-1"}, Data: map[string][]byte{"ledger.json": encoded}}).Build() - return &Handler{Store: Store{Client: private, Namespace: "private", Authority: "milo", Projects: []string{"provider"}}, Resolve: func(context.Context, string) (Project, error) { + return &Handler{Store: Store{Client: private, Namespace: "private", Authority: "milo", Projects: []string{"provider"}, AllowInactiveForTests: true}, Resolve: func(context.Context, string) (Project, error) { return Project{Identity: controller.ProjectIdentity{AuthorityID: "milo", RouteName: "provider", UID: "project-1"}, Client: api}, nil }, Authorize: func(context.Context, Project, authenticationv1.UserInfo, string, string, string) error { return nil }}, device } diff --git a/internal/registration/control.go b/internal/registration/control.go index 7e96415b..4e46d7d0 100644 --- a/internal/registration/control.go +++ b/internal/registration/control.go @@ -129,7 +129,7 @@ func (handler *Handler) ApplyControl(ctx context.Context, control SignedControl) route.Activation = &control case "expand": if len(route.Segments) >= MaxSegments { - return ErrGrowthStopped + return ErrSegmentsExhausted } route.Pending = &control } diff --git a/internal/registration/control_test.go b/internal/registration/control_test.go index 072f7de1..4b7572d7 100644 --- a/internal/registration/control_test.go +++ b/internal/registration/control_test.go @@ -31,7 +31,7 @@ func controlFixture(t *testing.T, handler *Handler) ed25519.PrivateKey { t.Fatal(err) } handler.Store.ControlKey = public - handler.Store.RequireActive = true + handler.Store.AllowInactiveForTests = false handler.VerifyFence = func(context.Context) error { return nil } handler.FenceDigest = func(context.Context) (string, error) { return "approved-fence", nil } return private diff --git a/internal/registration/ledger.go b/internal/registration/ledger.go index ecfcc078..eec32ac5 100644 --- a/internal/registration/ledger.go +++ b/internal/registration/ledger.go @@ -54,12 +54,14 @@ type Ledger struct { } type Store struct { - Client client.Client - Namespace string - Authority string - Projects []string - ControlKey ed25519.PublicKey - RequireActive bool + Client client.Client + Namespace string + Authority string + Projects []string + ControlKey ed25519.PublicKey + // AllowInactiveForTests skips the signed activation gate. The zero value + // is gated; production wiring forces it off. + AllowInactiveForTests bool } func (store Store) Read(ctx context.Context) (*corev1.Secret, Ledger, error) { @@ -86,7 +88,7 @@ func (store Store) Write(ctx context.Context, secret *corev1.Secret, ledger Ledg return err } if len(encoded) > TailBudget { - return errors.New("registration ledger is full; reservations were not released") + return errors.New("registration ledger is full; sign an expand control request to seal it losslessly, see docs/development/registration-storage-rollout.md; reservations were not released") } secret.Data["ledger.json"] = encoded return store.Client.Update(ctx, secret) diff --git a/internal/registration/namespace_lifetime_test.go b/internal/registration/namespace_lifetime_test.go new file mode 100644 index 00000000..ff2270e0 --- /dev/null +++ b/internal/registration/namespace_lifetime_test.go @@ -0,0 +1,167 @@ +package registration + +import ( + "context" + "encoding/json" + "testing" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + iam "go.miloapis.com/milo/pkg/apis/iam/v1alpha1" + admissionv1 "k8s.io/api/admission/v1" + authenticationv1 "k8s.io/api/authentication/v1" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/types" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/webhook/admission" +) + +// terminatingDevice creates a Device in a provider-project namespace other +// than default, records its fence while the namespace is live, and then +// deletes the namespace while a finalizer still holds it in Terminating. +func terminatingDevice(t *testing.T, handler *Handler, name, uuid string) (Project, *inventory.Device) { + t.Helper() + ctx := context.Background() + project, _ := handler.Resolve(ctx, "provider") + namespace := &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "decommissioned-" + name, UID: types.UID("namespace-" + name), Finalizers: []string{"synthetic.example/hold"}}} + if err := project.Client.Create(ctx, namespace); err != nil { + t.Fatal(err) + } + device := &inventory.Device{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: namespace.Name, UID: types.UID("device-" + name)}, Spec: inventory.DeviceSpec{Identity: inventory.DeviceIdentity{Serial: "SERIAL-" + name, SystemUUID: uuid, Model: "test"}}} + if err := project.Client.Create(ctx, device); err != nil { + t.Fatal(err) + } + if response := handler.Handle(ctx, deviceRequest(t, admissionv1.Create, nil, device)); !response.Allowed { + t.Fatalf("live namespace Device create denied: %s", response.Result.Message) + } + if err := project.Client.Delete(ctx, namespace); err != nil { + t.Fatal(err) + } + if err := project.Client.Get(ctx, client.ObjectKeyFromObject(namespace), namespace); err != nil || namespace.DeletionTimestamp.IsZero() { + t.Fatalf("namespace is not terminating: %v", err) + } + return project, device +} + +func deviceRequest(t *testing.T, operation admissionv1.Operation, old, current *inventory.Device) admission.Request { + t.Helper() + request := admission.Request{AdmissionRequest: admissionv1.AdmissionRequest{UID: types.UID("device-request-" + string(operation)), Operation: operation, Resource: metav1.GroupVersionResource{Group: "fleet.datumapis.com", Version: "v1alpha1", Resource: "devices"}, UserInfo: authenticationv1.UserInfo{Username: "operator", UID: "actor-1", Extra: map[string]authenticationv1.ExtraValue{iam.ParentKindExtraKey: {"Project"}, iam.ParentAPIGroupExtraKey: {"resourcemanager.miloapis.com"}, iam.ParentNameExtraKey: {"provider"}}}}} + for _, pair := range []struct { + device *inventory.Device + raw *runtime.RawExtension + }{{old, &request.OldObject}, {current, &request.Object}} { + if pair.device == nil { + continue + } + encoded, err := json.Marshal(pair.device) + if err != nil { + t.Fatal(err) + } + pair.raw.Raw = encoded + request.Name, request.Namespace = pair.device.Name, pair.device.Namespace + } + return request +} + +func retainedFence(t *testing.T, handler *Handler, uid types.UID) DeviceFence { + t.Helper() + _, ledger, err := handler.Store.Read(context.Background()) + if err != nil { + t.Fatal(err) + } + var found []DeviceFence + for _, fence := range ledger.DeviceFences { + if fence.UID == uid { + found = append(found, fence) + } + } + if len(found) != 1 { + t.Fatalf("expected one retained fence for %s: %+v", uid, ledger.DeviceFences) + } + return found[0] +} + +func TestDeviceDeleteInTerminatingNamespaceRetainsTombstone(t *testing.T) { + ctx := context.Background() + handler, _ := fixture(t) + _, device := terminatingDevice(t, handler, "retired", "22222222-2222-2222-2222-222222222222") + created := retainedFence(t, handler, device.UID) + if created.NamespaceUID == "" || len(created.Aliases) == 0 { + t.Fatalf("create did not record namespace lifetime and aliases: %+v", created) + } + if response := handler.Handle(ctx, deviceRequest(t, admissionv1.Delete, device, nil)); !response.Allowed { + t.Fatalf("Device delete in a terminating namespace was denied, so the namespace cannot finish terminating: %s", response.Result.Message) + } + tombstone := retainedFence(t, handler, device.UID) + if !tombstone.Deleted || tombstone.NamespaceUID != created.NamespaceUID || tombstone.Version != "" || !preservesReservations(Ledger{DeviceFences: []DeviceFence{created}}, Ledger{DeviceFences: []DeviceFence{tombstone}}) { + t.Fatalf("tombstone lost retained lifetime: before %+v after %+v", created, tombstone) + } + recreated := device.DeepCopyObject().(*inventory.Device) + recreated.Namespace, recreated.UID = "default", "recreated" + if handler.Handle(ctx, deviceRequest(t, admissionv1.Create, nil, recreated)).Allowed { + t.Fatal("deleted hardware aliases were released by the terminating namespace path") + } +} + +func TestDeviceDeleteAfterNamespaceRemovalUsesRecordedLifetime(t *testing.T) { + ctx := context.Background() + handler, _ := fixture(t) + project, device := terminatingDevice(t, handler, "removed", "33333333-3333-3333-3333-333333333333") + created := retainedFence(t, handler, device.UID) + namespace := &corev1.Namespace{} + if err := project.Client.Get(ctx, client.ObjectKey{Name: device.Namespace}, namespace); err != nil { + t.Fatal(err) + } + namespace.Finalizers = nil + if err := project.Client.Update(ctx, namespace); err != nil { + t.Fatal(err) + } + if err := project.Client.Get(ctx, client.ObjectKeyFromObject(namespace), namespace); err == nil { + t.Fatal("namespace was not removed") + } + if response := handler.Handle(ctx, deviceRequest(t, admissionv1.Delete, device, nil)); !response.Allowed { + t.Fatalf("Device delete after namespace removal was denied: %s", response.Result.Message) + } + tombstone := retainedFence(t, handler, device.UID) + if !tombstone.Deleted || tombstone.NamespaceUID != created.NamespaceUID || !preservesReservations(Ledger{DeviceFences: []DeviceFence{created}}, Ledger{DeviceFences: []DeviceFence{tombstone}}) { + t.Fatalf("tombstone did not keep the recorded namespace lifetime: before %+v after %+v", created, tombstone) + } +} + +func TestDeviceFinalizerRemovalInTerminatingNamespaceRetainsTombstone(t *testing.T) { + ctx := context.Background() + handler, _ := fixture(t) + project, device := terminatingDevice(t, handler, "finalized", "44444444-4444-4444-4444-444444444444") + if err := project.Client.Get(ctx, client.ObjectKeyFromObject(device), device); err != nil { + t.Fatal(err) + } + device.Finalizers = []string{"synthetic.example/drain"} + if err := project.Client.Update(ctx, device); err != nil { + t.Fatal(err) + } + if err := project.Client.Delete(ctx, device); err != nil { + t.Fatal(err) + } + deleting := &inventory.Device{} + if err := project.Client.Get(ctx, client.ObjectKeyFromObject(device), deleting); err != nil || deleting.DeletionTimestamp.IsZero() { + t.Fatalf("Device is not deleting: %v", err) + } + if response := handler.Handle(ctx, deviceRequest(t, admissionv1.Delete, deleting, nil)); !response.Allowed { + t.Fatalf("Device delete in a terminating namespace was denied: %s", response.Result.Message) + } + released := deleting.DeepCopyObject().(*inventory.Device) + released.Finalizers = nil + if response := handler.Handle(ctx, deviceRequest(t, admissionv1.Update, deleting, released)); !response.Allowed { + t.Fatalf("finalizer removal in a terminating namespace was denied: %s", response.Result.Message) + } + tombstone := retainedFence(t, handler, device.UID) + if !tombstone.Deleted || tombstone.NamespaceUID == "" || len(tombstone.Aliases) == 0 { + t.Fatalf("finalizer removal lost the tombstone: %+v", tombstone) + } + edited := deleting.DeepCopyObject().(*inventory.Device) + edited.Finalizers, edited.Labels = nil, map[string]string{"edited": "true"} + if handler.Handle(ctx, deviceRequest(t, admissionv1.Update, deleting, edited)).Allowed { + t.Fatal("a non-finalizer edit was admitted without a live namespace") + } +} diff --git a/internal/registration/runtime.go b/internal/registration/runtime.go index 4f34c211..26ce2bff 100644 --- a/internal/registration/runtime.go +++ b/internal/registration/runtime.go @@ -21,7 +21,7 @@ import ( ) func NewHandler(store Store, root client.Client, template *rest.Config, scheme *runtime.Scheme) *Handler { - store.RequireActive = true + store.AllowInactiveForTests = false return &Handler{Store: store, VerifyFence: func(ctx context.Context) error { return VerifyFence(ctx, root, store.Projects) }, Resolve: func(ctx context.Context, name string) (Project, error) { identity, err := manager.ResolveProjectIdentity(ctx, root, store.Authority, name) if err != nil { diff --git a/internal/registration/segments.go b/internal/registration/segments.go index bbaca92a..710c85fe 100644 --- a/internal/registration/segments.go +++ b/internal/registration/segments.go @@ -25,6 +25,19 @@ const ( var ErrGrowthStopped = errors.New("registration growth stopped; signed lossless expansion required, reservations remain retained") +// ErrSegmentsExhausted is the terminal growth stop: every sealed segment is in +// use, so expansion itself is refused. It still matches ErrGrowthStopped for +// callers that only distinguish stopped growth. +var ErrSegmentsExhausted error = segmentsExhausted{} + +type segmentsExhausted struct{} + +func (segmentsExhausted) Error() string { + return fmt.Sprintf("registration segments exhausted (%d of %d sealed); expansion is refused and a reviewed storage migration is required, see docs/development/registration-storage-rollout.md; reservations remain retained, do not raise caps or delete records", MaxSegments, MaxSegments) +} + +func (segmentsExhausted) Is(target error) bool { return target == ErrGrowthStopped } + type Segment struct { Name string `json:"name"` UID types.UID `json:"uid"` @@ -230,6 +243,9 @@ func (store Store) writeSnapshot(ctx context.Context, secret *corev1.Secret, cur return err } if len(encoded) > TailBudget { + if len(route.Segments) >= MaxSegments { + return ErrSegmentsExhausted + } return ErrGrowthStopped } updated := secret.DeepCopy() diff --git a/internal/registration/terminal_errors_test.go b/internal/registration/terminal_errors_test.go new file mode 100644 index 00000000..7d6d9932 --- /dev/null +++ b/internal/registration/terminal_errors_test.go @@ -0,0 +1,121 @@ +package registration + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "strings" + "testing" + + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/types" + "k8s.io/client-go/rest" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" +) + +const runbook = "docs/development/registration-storage-rollout.md" + +// sealedRoot converts the fixture root to v2 routing with the given number of +// sealed segments, each a valid immutable overlay of the configured scope. +func sealedRoot(t *testing.T, handler *Handler, sealed int) { + t.Helper() + ctx := context.Background() + store := handler.Store + secret := &corev1.Secret{} + if err := store.Client.Get(ctx, client.ObjectKey{Namespace: store.Namespace, Name: LedgerName}, secret); err != nil { + t.Fatal(err) + } + empty, _ := json.Marshal(Ledger{Authority: store.Authority, Projects: store.Projects}) + route := Routing{Version: 2, RootUID: secret.UID, Epoch: uint64(sealed)} + immutable := true + for epoch := 0; epoch < sealed; epoch++ { + segment := &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Namespace: store.Namespace, Name: segmentName(secret.UID, uint64(epoch)), UID: types.UID(fmt.Sprint("segment-", epoch))}, Immutable: &immutable, Data: map[string][]byte{"ledger.json": empty}} + if err := store.Client.Create(ctx, segment); err != nil { + t.Fatal(err) + } + if segment.UID == "" { + t.Fatal("segment UID not retained") + } + route.Segments = append(route.Segments, Segment{Name: segment.Name, UID: segment.UID, Digest: digest(empty)}) + } + encoded, _ := json.Marshal(route) + secret.Data = map[string][]byte{"ledger.json": []byte(`{"authority":"v2-routing-required","projects":[]}`), "tail.json": empty, "routing.json": encoded} + if err := store.Client.Update(ctx, secret); err != nil { + t.Fatal(err) + } +} + +func oversizedWrite(t *testing.T, handler *Handler) error { + t.Helper() + secret, ledger, err := handler.Store.Read(context.Background()) + if err != nil { + t.Fatal(err) + } + ledger.DeviceFences = append(ledger.DeviceFences, DeviceFence{Project: "provider", UID: "oversize", Aliases: []string{strings.Repeat("x", TailBudget)}}) + return handler.Store.Write(context.Background(), secret, ledger) +} + +func TestSegmentExhaustionIsDistinctAndActionable(t *testing.T) { + ctx := context.Background() + handler, _ := fixture(t) + key := controlFixture(t, handler) + sealedRoot(t, handler, MaxSegments) + for name, err := range map[string]error{ + "expand": handler.ApplyControl(ctx, controlFor(t, handler, key, "expand")), + "write": oversizedWrite(t, handler), + } { + if !errors.Is(err, ErrSegmentsExhausted) || !errors.Is(err, ErrGrowthStopped) { + t.Fatalf("%s: terminal growth stop not distinct: %v", name, err) + } + message := err.Error() + if strings.Contains(message, "expansion required") || !strings.Contains(message, "segments exhausted") || !strings.Contains(message, "reviewed storage migration") || !strings.Contains(message, runbook) { + t.Fatalf("%s: terminal error is not operator-actionable: %s", name, message) + } + } + _, route, err := handler.Store.root(ctx) + if err != nil || route.Pending != nil || len(route.Segments) != MaxSegments { + t.Fatalf("refused expansion changed routing: %+v %v", route, err) + } +} + +func TestGrowthStopBelowSegmentCapStillAsksForExpansion(t *testing.T) { + handler, _ := fixture(t) + controlFixture(t, handler) + sealedRoot(t, handler, MaxSegments-1) + err := oversizedWrite(t, handler) + if !errors.Is(err, ErrGrowthStopped) || errors.Is(err, ErrSegmentsExhausted) { + t.Fatalf("expandable root reported terminal exhaustion: %v", err) + } +} + +func TestFullLegacyLedgerNamesExpandRequest(t *testing.T) { + handler, _ := fixture(t) + err := oversizedWrite(t, handler) + if err == nil || !strings.Contains(err.Error(), "sign an expand") || !strings.Contains(err.Error(), runbook) { + t.Fatalf("full v1 ledger does not say how to proceed: %v", err) + } +} + +func TestActivationGateIsDefaultAndProductionForcesIt(t *testing.T) { + ctx := context.Background() + handler, device := fixture(t) + handler.Store.AllowInactiveForTests = false + if handler.Handle(ctx, registrationRequest(t, device, "zero-value")).Allowed { + t.Fatal("zero-value store admitted without signed activation") + } + if _, ledger, err := handler.Store.Read(ctx); err != nil || len(ledger.Entries) != 0 { + t.Fatalf("gated admission retained a reservation: %+v %v", ledger, err) + } + scheme := runtime.NewScheme() + if err := corev1.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + production := NewHandler(Store{Client: handler.Store.Client, Namespace: "private", Authority: "milo", Projects: []string{"provider"}, AllowInactiveForTests: true}, fake.NewClientBuilder().WithScheme(scheme).Build(), &rest.Config{Host: "https://synthetic.invalid"}, scheme) + if production.Store.AllowInactiveForTests { + t.Fatal("production wiring kept the test-only activation opt-out") + } +} From e81a01bb2d375f26acf04c06d1d29d3cac47adbd Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sun, 22 Nov 2026 14:31:48 -0600 Subject: [PATCH 071/518] docs(registration): document activation cap, key rotation and drain path The activation history cap is a lifetime limit until a reviewed compaction migration exists. CA rotation and defaulted-field drift each use one slot. Key rotation must happen with no expansion pending and is followed by a restart and a fresh activation. The terminal growth errors and the Device delete behaviour in terminating namespaces are also described. Co-Authored-By: Claude Opus 5.5 --- .../registration-storage-rollout.md | 52 +++++++++++++++++-- 1 file changed, 47 insertions(+), 5 deletions(-) diff --git a/docs/development/registration-storage-rollout.md b/docs/development/registration-storage-rollout.md index 8b4e089b..44ed4512 100644 --- a/docs/development/registration-storage-rollout.md +++ b/docs/development/registration-storage-rollout.md @@ -34,7 +34,11 @@ Legacy multiple-version groups are sealed without reinterpretation. Existing authoritative update/coalescing rules alone supersede pending versions. The writer also rejects dropping registrations, aliases, tombstones or known lifetime identity. New Device fences retain Project UID, namespace name/UID and Device name; missing -legacy fields are not backfilled or proof of safe release. +legacy fields are not backfilled or proof of safe release. Creates and edits +require a live namespace. Deletes and finalizer-only updates do not, so a +terminating provider namespace can drain its Devices. They bind the terminating +namespace's UID, or the UID already recorded once the namespace is gone, and +still write a permanent tombstone. Registered Devices remain undeletable. An operator signs `expand`, binding exact root UID, resourceVersion, epoch, authority, sorted provider scope, change ID and reason. The service: @@ -74,7 +78,7 @@ policies or restore arbitrary storage remain outside the guarantee. | Root data including routing/control | 850,000 bytes, below the 1 MiB Secret data limit | | Sealed segments | 16 plus the mutable tail; expansion is operator-authorized, not infinite | | Signed payload / mounted envelope | 8,192 / 16,384 bytes | -| Activation audit | Current activation plus seven previous signed activations, never pruned | +| Activation audit | Current activation plus seven previous signed activations, never pruned; the ninth activation fails (lifetime limit) | The ordinary stop leaves 100 KB relative to the former ledger cap for safe sealing; the root budget additionally accommodates routing/control. A segment is at most @@ -88,9 +92,14 @@ it is not a throughput qualification. Pod memory is bounded at 512 MiB. The mTLS-only `/status` reports tail bytes, headroom, remaining segments, epoch, pending state, root UID/RV, scope and verified fence digest, without reservation contents or actor data. Parent monitoring must alert below 100,000 bytes headroom -and before only two segments remain. Sign expansion before exhaustion. At the -terminal bound, stop protected growth and escalate for a separately reviewed -storage migration; never increase caps or delete/reset/release records manually. +and before only two segments remain. Sign expansion before exhaustion. A full v1 +ledger reports `registration ledger is full; sign an expand control request`; +a full v2 tail with segments left reports `registration growth stopped`. Both +mean sign `expand` as in step 7 below. Once all 16 segments are sealed, writes +and `expand` report `registration segments exhausted`: expansion is refused, so +re-signing it cannot help. At that terminal bound, stop protected growth and +escalate for a separately reviewed storage migration; never increase caps or +delete/reset/release records manually. Public inventory reads remain unaffected. Denied/timed-out private writes deny admission even if reads succeed; uncertain commits stay retained. @@ -115,6 +124,39 @@ remain in bounded root audit history. The configured signing key is an operator trust boundary, not caller authority; coordinate changes with pending signatures. Global capacity fencing and privileged/root-context limitations are unchanged. +### Activation budget is a lifetime limit + +The root keeps the current activation plus seven previous ones. The ninth +activation of a root fails with `activation audit budget exhausted`. Nothing +prunes or compacts this history, so the limit applies to the root's whole life +until a separately reviewed compaction migration exists. Every change to the +pinned fence digest needs a new activation and uses one slot. That includes +webhook CA rotation (the `caBundle` is part of the digest) and API-server drift +in defaulted webhook fields after an upgrade. Batch planned trust changes into +one activation where possible, and count the remaining slots before each one. +At the cap, admission stays on its current activation while that activation's +fence still verifies. If the fence has already changed, registration stays +non-admitting. Do not delete or edit `routing.json`, and do not create a new +root to reset the count. Escalate for the reviewed compaction migration. + +### Rotating the operator signing key + +The public key is read once at process startup from `public.pem`, and every +signature is verified against the key the process currently holds. A pending +expansion cannot be cancelled, and `ResumeExpansion` re-verifies the pending +signature against the current key. If the key rotates while an expansion is +pending, the expansion cannot complete and the root stays fenced. Rotate in +this order: + +1. Fetch `/status` and confirm no expansion is pending. If one is, let it + complete under the current key and confirm the epoch advanced. Do not sign + a new `expand` until the rotation is finished. +2. Replace `public.pem` in `fleet-registration-control`, then restart every + registration replica, because a running process keeps the key it loaded. +3. The retained activation was signed by the old key, so the restarted + processes stay non-admitting. Sign a fresh `activate` with the new key + (step 7 below). This uses one activation slot. + ## Exact staged parent infrastructure contract These steps require a separately approved infra PR; none authorizes live execution. From 661af5b82ea440bf8f86079f503c1cf1fe2097a8 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sun, 22 Nov 2026 16:22:32 -0600 Subject: [PATCH 072/518] refactor(registration): check live Devices only Remove the registration ledger and everything that served it: the Secret-backed CAS store, sealed segments, signed activation and expansion, the control ConfigMap and key, /activationz and /status, cmd/fleet-registration-control, the ledger retention policies and the ledger Secret RBAC. The webhook now keeps no state. A capacity create must be named device-, so the API server refuses a second capacity for the same Device. It is checked against the live Device, the caller's SARs, aliases on every live Device in the provider scope, and every existing capacity. The webhook fences capacity writes only; Device, namespace and Project writes no longer pass through it. The registration pod mounts no service account token. Co-Authored-By: Claude Opus 5.5 --- cmd/fleet-registration-control/main.go | 56 -- cmd/fleet-registration-control/main_test.go | 51 -- cmd/fleet-registration/main.go | 85 +-- config/base/registration/deployment.yaml | 8 +- config/base/registration/kustomization.yaml | 2 - config/base/registration/protection.yaml | 55 -- config/base/registration/rbac.yaml | 27 - .../registration-admission/webhook.yaml | 60 +- .../registration-exclusion.yaml | 40 +- .../registration-storage-rollout.md | 232 -------- internal/registration/admission.go | 443 +++----------- .../admission_regression_envtest_test.go | 436 -------------- .../registration/admission_regression_test.go | 75 --- internal/registration/admission_test.go | 479 ++++++--------- internal/registration/bounded_fences_test.go | 200 ------- .../registration/contention_envtest_test.go | 112 ---- internal/registration/control.go | 235 -------- internal/registration/control_test.go | 150 ----- internal/registration/envtest_test.go | 559 +++++++++--------- internal/registration/fence.go | 75 --- internal/registration/fence_test.go | 113 ---- internal/registration/ledger.go | 106 ---- internal/registration/manifest_test.go | 40 ++ .../registration/namespace_lifetime_test.go | 167 ------ internal/registration/runtime.go | 84 +-- internal/registration/segments.go | 269 --------- .../registration/segments_envtest_test.go | 382 ------------ internal/registration/terminal_errors_test.go | 121 ---- .../testdata/review_adversarial_test.go.txt | 172 ------ internal/registration/transport.go | 92 +-- 30 files changed, 652 insertions(+), 4274 deletions(-) delete mode 100644 cmd/fleet-registration-control/main.go delete mode 100644 cmd/fleet-registration-control/main_test.go delete mode 100644 config/base/registration/protection.yaml delete mode 100644 config/base/registration/rbac.yaml delete mode 100644 docs/development/registration-storage-rollout.md delete mode 100644 internal/registration/admission_regression_envtest_test.go delete mode 100644 internal/registration/admission_regression_test.go delete mode 100644 internal/registration/bounded_fences_test.go delete mode 100644 internal/registration/contention_envtest_test.go delete mode 100644 internal/registration/control.go delete mode 100644 internal/registration/control_test.go delete mode 100644 internal/registration/fence.go delete mode 100644 internal/registration/fence_test.go delete mode 100644 internal/registration/ledger.go create mode 100644 internal/registration/manifest_test.go delete mode 100644 internal/registration/namespace_lifetime_test.go delete mode 100644 internal/registration/segments.go delete mode 100644 internal/registration/segments_envtest_test.go delete mode 100644 internal/registration/terminal_errors_test.go delete mode 100644 internal/registration/testdata/review_adversarial_test.go.txt diff --git a/cmd/fleet-registration-control/main.go b/cmd/fleet-registration-control/main.go deleted file mode 100644 index 1e135e9c..00000000 --- a/cmd/fleet-registration-control/main.go +++ /dev/null @@ -1,56 +0,0 @@ -package main - -import ( - "crypto/ed25519" - "crypto/x509" - "encoding/json" - "encoding/pem" - "errors" - "flag" - "fmt" - "io" - "os" - - "go.datum.net/fleet/internal/registration" -) - -func main() { - requestPath := flag.String("request", "", "unsigned ControlRequest JSON, exact observed root UID/resourceVersion/epoch and scope") - keyPath := flag.String("key", "", "offline Ed25519 PKCS8 private key; never mount in the service") - flag.Parse() - if err := sign(*requestPath, *keyPath, os.Stdout); err != nil { - fmt.Fprintln(os.Stderr, err) - os.Exit(1) - } -} - -func sign(requestPath, keyPath string, output io.Writer) error { - encoded, err := os.ReadFile(requestPath) - if err != nil { - return err - } - if len(encoded) > 8192 { - return errors.New("request exceeds budget") - } - var request registration.ControlRequest - if err := json.Unmarshal(encoded, &request); err != nil { - return err - } - encoded, err = os.ReadFile(keyPath) - if err != nil { - return err - } - block, rest := pem.Decode(encoded) - if block == nil || len(rest) != 0 { - return errors.New("expected one PKCS8 private key") - } - parsed, err := x509.ParsePKCS8PrivateKey(block.Bytes) - if err != nil { - return err - } - key, ok := parsed.(ed25519.PrivateKey) - if !ok { - return errors.New("control key must be Ed25519") - } - return json.NewEncoder(output).Encode(registration.SignControl(request, key)) -} diff --git a/cmd/fleet-registration-control/main_test.go b/cmd/fleet-registration-control/main_test.go deleted file mode 100644 index 18c185da..00000000 --- a/cmd/fleet-registration-control/main_test.go +++ /dev/null @@ -1,51 +0,0 @@ -package main - -import ( - "bytes" - "crypto/ed25519" - "crypto/rand" - "crypto/x509" - "encoding/json" - "encoding/pem" - "os" - "path/filepath" - "reflect" - "testing" - - "go.datum.net/fleet/internal/registration" -) - -func TestOfflineControlSigner(t *testing.T) { - _, key, err := ed25519.GenerateKey(rand.Reader) - if err != nil { - t.Fatal(err) - } - request := registration.ControlRequest{Action: "expand", ID: "change", Reason: "synthetic", RootUID: "root", ResourceVersion: "9", Epoch: 2, Authority: "milo", Projects: []string{"provider"}} - encoded, _ := json.Marshal(request) - directory := t.TempDir() - requestPath, keyPath := filepath.Join(directory, "request"), filepath.Join(directory, "private") - if err := os.WriteFile(requestPath, encoded, 0600); err != nil { - t.Fatal(err) - } - der, err := x509.MarshalPKCS8PrivateKey(key) - if err != nil { - t.Fatal(err) - } - if err := os.WriteFile(keyPath, pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: der}), 0600); err != nil { - t.Fatal(err) - } - var output bytes.Buffer - if err := sign(requestPath, keyPath, &output); err != nil { - t.Fatal(err) - } - actual, err := registration.ParseControl(output.Bytes()) - if err != nil || !reflect.DeepEqual(actual, registration.SignControl(request, key)) { - t.Fatal("signer changed request", err) - } - if err := os.WriteFile(keyPath, []byte("not a private key"), 0600); err != nil { - t.Fatal(err) - } - if err := sign(requestPath, keyPath, &output); err == nil { - t.Fatal("invalid key accepted") - } -} diff --git a/cmd/fleet-registration/main.go b/cmd/fleet-registration/main.go index f37c2e8a..a6e33268 100644 --- a/cmd/fleet-registration/main.go +++ b/cmd/fleet-registration/main.go @@ -20,40 +20,33 @@ import ( resourcemanager "go.miloapis.com/milo/pkg/apis/resourcemanager/v1alpha1" "k8s.io/apimachinery/pkg/runtime" clientgoscheme "k8s.io/client-go/kubernetes/scheme" - "k8s.io/client-go/rest" "k8s.io/client-go/tools/clientcmd" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" ) func main() { - var configFile, providers, privateNamespace, cert, key, clientCA, controlKey, controlRequest string + var configFile, providers, cert, key, clientCA string flag.StringVar(&configFile, "config", "", "Fleet manager discovery configuration") - flag.StringVar(&providers, "provider-projects", "", "complete comma-separated provider identity scope, fixed in the private ledger") - flag.StringVar(&privateNamespace, "private-namespace", "fleet-system-private", "private registration ledger namespace") + flag.StringVar(&providers, "provider-projects", "", "complete comma-separated provider scope searched for duplicate hardware identity") flag.StringVar(&cert, "tls-cert", "/etc/fleet/registration/tls.crt", "serving certificate") flag.StringVar(&key, "tls-key", "/etc/fleet/registration/tls.key", "serving key") flag.StringVar(&clientCA, "client-ca", "/etc/fleet/registration/client-ca.crt", "CA dedicated to trusted API-server webhook clients") - flag.StringVar(&controlKey, "control-key", "/etc/fleet/registration-control/public.pem", "operator Ed25519 public key; never a private key") - flag.StringVar(&controlRequest, "control-request", "/etc/fleet/registration-control/request.json", "optional signed activation or expansion request") flag.Parse() - if err := run(ctrl.SetupSignalHandler(), configFile, providers, privateNamespace, cert, key, clientCA, controlKey, controlRequest); err != nil { + if err := run(ctrl.SetupSignalHandler(), configFile, providers, cert, key, clientCA); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } -func run(ctx context.Context, configFile, providers, namespace, cert, key, clientCA, controlKey, controlRequest string) error { +func run(ctx context.Context, configFile, providers, cert, key, clientCA string) error { config, err := projectdiscovery.LoadConfig(configFile) if err != nil { return err } - projects := strings.Split(providers, ",") - sort.Strings(projects) - for index, name := range projects { - if name == "" || strings.TrimSpace(name) != name || (index > 0 && projects[index-1] == name) { - return errors.New("a nonempty, unique provider scope is required") - } + projects, err := providerScope(providers) + if err != nil { + return err } scheme := runtime.NewScheme() for _, add := range []func(*runtime.Scheme) error{clientgoscheme.AddToScheme, inventory.AddToScheme, metal.AddToScheme, resourcemanager.AddToScheme} { @@ -61,14 +54,6 @@ func run(ctx context.Context, configFile, providers, namespace, cert, key, clien return err } } - host, err := rest.InClusterConfig() - if err != nil { - return err - } - private, err := client.New(host, client.Options{Scheme: scheme}) - if err != nil { - return err - } rootConfig, err := clientcmd.BuildConfigFromFlags("", config.Discovery.DiscoveryKubeconfigPath) if err != nil { return err @@ -84,52 +69,17 @@ func run(ctx context.Context, configFile, providers, namespace, cert, key, clien return err } } - keyBytes, err := os.ReadFile(controlKey) - if err != nil { - return err - } - publicKey, err := registration.ParseControlKey(keyBytes) - if err != nil { - return err - } - handler := registration.NewHandler(registration.Store{Client: private, Namespace: namespace, Authority: config.AuthorityID, Projects: projects, ControlKey: publicKey}, root, template, scheme) + handler := registration.NewHandler(config.AuthorityID, projects, root, template, scheme) tlsConfig, err := webhookTLS(clientCA) if err != nil { return err } server := &http.Server{Addr: ":9443", Handler: http.MaxBytesHandler(handler.Transport(), 2<<20), ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 15 * time.Second, WriteTimeout: 20 * time.Second, TLSConfig: tlsConfig} go func() { - ticker := time.NewTicker(30 * time.Second) - defer ticker.Stop() - for { - select { - case <-ctx.Done(): - shutdown, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - _ = server.Shutdown(shutdown) - return - case <-ticker.C: - operation, cancel := context.WithTimeout(ctx, 20*time.Second) - if err := handler.Store.ResumeExpansion(operation); err != nil { - fmt.Fprintln(os.Stderr, "registration expansion remains fenced:", err) - } - if encoded, err := os.ReadFile(controlRequest); err == nil { - control, err := registration.ParseControl(encoded) - if err == nil { - err = handler.ApplyControl(operation, control) - } - if err != nil { - fmt.Fprintln(os.Stderr, "registration control not applied:", err) - } - } else if !os.IsNotExist(err) { - fmt.Fprintln(os.Stderr, "registration control unavailable:", err) - } - if err := handler.Recover(operation); err != nil { - fmt.Fprintln(os.Stderr, "registration recovery remains unknown:", err) - } - cancel() - } - } + <-ctx.Done() + shutdown, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + _ = server.Shutdown(shutdown) }() err = server.ListenAndServeTLS(cert, key) if errors.Is(err, http.ErrServerClosed) { @@ -138,6 +88,17 @@ func run(ctx context.Context, configFile, providers, namespace, cert, key, clien return err } +func providerScope(providers string) ([]string, error) { + projects := strings.Split(providers, ",") + sort.Strings(projects) + for index, name := range projects { + if name == "" || strings.TrimSpace(name) != name || (index > 0 && projects[index-1] == name) { + return nil, errors.New("a nonempty, unique provider scope is required") + } + } + return projects, nil +} + func webhookTLS(clientCA string) (*tls.Config, error) { caBytes, err := os.ReadFile(clientCA) if err != nil { diff --git a/config/base/registration/deployment.yaml b/config/base/registration/deployment.yaml index c48eff73..327f18fe 100644 --- a/config/base/registration/deployment.yaml +++ b/config/base/registration/deployment.yaml @@ -33,6 +33,9 @@ spec: app.kubernetes.io/name: fleet-registration spec: serviceAccountName: fleet-registration + # The service reads Milo through mounted credentials only; it needs no + # host Kubernetes API access. + automountServiceAccountToken: false securityContext: runAsNonRoot: true runAsUser: 65532 @@ -66,12 +69,7 @@ spec: - {name: root, mountPath: /var/run/fleet/milo, readOnly: true} - {name: projects, mountPath: /var/run/fleet/projects, readOnly: true} - {name: tls, mountPath: /etc/fleet/registration, readOnly: true} - - {name: control, mountPath: /etc/fleet/registration-control, readOnly: true} volumes: - - name: control - configMap: - name: fleet-registration-control - defaultMode: 0440 - name: config configMap: name: fleet-manager-config diff --git a/config/base/registration/kustomization.yaml b/config/base/registration/kustomization.yaml index ab998324..9c2d28b0 100644 --- a/config/base/registration/kustomization.yaml +++ b/config/base/registration/kustomization.yaml @@ -2,5 +2,3 @@ apiVersion: kustomize.config.k8s.io/v1beta1 kind: Kustomization resources: - deployment.yaml - - rbac.yaml - - protection.yaml diff --git a/config/base/registration/protection.yaml b/config/base/registration/protection.yaml deleted file mode 100644 index cabc8fbd..00000000 --- a/config/base/registration/protection.yaml +++ /dev/null @@ -1,55 +0,0 @@ -apiVersion: admissionregistration.k8s.io/v1 -kind: ValidatingAdmissionPolicy -metadata: - name: fleet-registration-ledger-protection -spec: - failurePolicy: Fail - matchConstraints: - resourceRules: - - apiGroups: [''] - apiVersions: [v1] - operations: [CREATE, UPDATE, DELETE] - resources: [secrets] - matchConditions: - - name: registration-ledger - expression: request.namespace == 'fleet-system-private' && (request.name == 'fleet-capacity-registration-v1' || request.name.startsWith('fleet-registration-segment-') || request.userInfo.username == 'system:serviceaccount:fleet-system:fleet-registration') - validations: - - expression: >- - (request.operation == 'CREATE' && request.name == 'fleet-capacity-registration-v1' && request.userInfo.username != 'system:serviceaccount:fleet-system:fleet-registration') || - (request.operation == 'UPDATE' && request.name == 'fleet-capacity-registration-v1' && request.userInfo.username == 'system:serviceaccount:fleet-system:fleet-registration' && - (!has(oldObject.data) || !('routing.json' in oldObject.data) || - (has(object.data) && 'routing.json' in object.data && 'ledger.json' in object.data && object.data['ledger.json'] == oldObject.data['ledger.json']))) || - (request.operation == 'CREATE' && request.name.startsWith('fleet-registration-segment-') && request.userInfo.username == 'system:serviceaccount:fleet-system:fleet-registration' && has(object.immutable) && object.immutable) - message: Registration roots cannot be downgraded or deleted; only the service may update the root or create immutable retained segments. ---- -apiVersion: admissionregistration.k8s.io/v1 -kind: ValidatingAdmissionPolicyBinding -metadata: - name: fleet-registration-ledger-protection -spec: - policyName: fleet-registration-ledger-protection - validationActions: [Deny] ---- -apiVersion: admissionregistration.k8s.io/v1 -kind: ValidatingAdmissionPolicy -metadata: - name: fleet-registration-namespace-protection -spec: - failurePolicy: Fail - matchConstraints: - resourceRules: - - apiGroups: [''] - apiVersions: [v1] - operations: [DELETE] - resources: [namespaces] - validations: - - expression: request.name != 'fleet-system-private' - message: The private registration namespace contains permanent reservations and cannot be deleted. ---- -apiVersion: admissionregistration.k8s.io/v1 -kind: ValidatingAdmissionPolicyBinding -metadata: - name: fleet-registration-namespace-protection -spec: - policyName: fleet-registration-namespace-protection - validationActions: [Deny] diff --git a/config/base/registration/rbac.yaml b/config/base/registration/rbac.yaml deleted file mode 100644 index 1e08d94c..00000000 --- a/config/base/registration/rbac.yaml +++ /dev/null @@ -1,27 +0,0 @@ -apiVersion: rbac.authorization.k8s.io/v1 -kind: Role -metadata: - name: fleet-registration-ledger - namespace: fleet-system-private -rules: - - apiGroups: [''] - resources: [secrets] - verbs: [get, create] - - apiGroups: [''] - resources: [secrets] - resourceNames: [fleet-capacity-registration-v1] - verbs: [get, update] ---- -apiVersion: rbac.authorization.k8s.io/v1 -kind: RoleBinding -metadata: - name: fleet-registration-ledger - namespace: fleet-system-private -roleRef: - apiGroup: rbac.authorization.k8s.io - kind: Role - name: fleet-registration-ledger -subjects: - - kind: ServiceAccount - name: fleet-registration - namespace: fleet-system diff --git a/config/components/registration-admission/webhook.yaml b/config/components/registration-admission/webhook.yaml index 25069d84..b75500a9 100644 --- a/config/components/registration-admission/webhook.yaml +++ b/config/components/registration-admission/webhook.yaml @@ -3,11 +3,13 @@ kind: ValidatingWebhookConfiguration metadata: name: fleet-capacity-registration webhooks: + # Every capacity write is fail-closed. Creates are checked against live + # Devices; updates, status writes and deletes are always denied. - name: registration.fleet.datumapis.com admissionReviewVersions: [v1] failurePolicy: Fail matchPolicy: Equivalent - sideEffects: NoneOnDryRun + sideEffects: None timeoutSeconds: 20 clientConfig: url: https://fleet-registration.fleet-system.svc:9443/validate-registration @@ -17,59 +19,3 @@ webhooks: operations: [CREATE, UPDATE, DELETE] resources: [machinecapacities, machinecapacities/status] scope: Namespaced - - name: inventory.registration.fleet.datumapis.com - admissionReviewVersions: [v1] - failurePolicy: Fail - matchPolicy: Equivalent - sideEffects: NoneOnDryRun - timeoutSeconds: 20 - clientConfig: - url: https://fleet-registration.fleet-system.svc:9443/validate-registration - matchConditions: - - name: provider-project-context - expression: >- - !(has(request.userInfo.extra) && "iam.miloapis.com/parent-type" in request.userInfo.extra && request.userInfo.extra["iam.miloapis.com/parent-type"] == ['Project'] && "iam.miloapis.com/parent-api-group" in request.userInfo.extra && request.userInfo.extra["iam.miloapis.com/parent-api-group"] == ['resourcemanager.miloapis.com'] && "iam.miloapis.com/parent-name" in request.userInfo.extra && size(request.userInfo.extra["iam.miloapis.com/parent-name"]) == 1 && request.userInfo.extra["iam.miloapis.com/parent-name"][0] != '') || request.userInfo.extra["iam.miloapis.com/parent-name"][0] in ["datum-cloud"] - rules: - - apiGroups: [fleet.datumapis.com] - apiVersions: [v1alpha1] - operations: [CREATE, UPDATE, DELETE] - resources: [devices, devices/status] - scope: Namespaced - - name: namespace.registration.fleet.datumapis.com - admissionReviewVersions: [v1] - failurePolicy: Fail - matchPolicy: Equivalent - sideEffects: NoneOnDryRun - timeoutSeconds: 20 - clientConfig: - url: https://fleet-registration.fleet-system.svc:9443/validate-registration - matchConditions: - - name: provider-project-context - expression: >- - !(has(request.userInfo.extra) && "iam.miloapis.com/parent-type" in request.userInfo.extra && request.userInfo.extra["iam.miloapis.com/parent-type"] == ['Project'] && "iam.miloapis.com/parent-api-group" in request.userInfo.extra && request.userInfo.extra["iam.miloapis.com/parent-api-group"] == ['resourcemanager.miloapis.com'] && "iam.miloapis.com/parent-name" in request.userInfo.extra && size(request.userInfo.extra["iam.miloapis.com/parent-name"]) == 1 && request.userInfo.extra["iam.miloapis.com/parent-name"][0] != '') || request.userInfo.extra["iam.miloapis.com/parent-name"][0] in ["datum-cloud"] - - name: inventory-namespace - expression: "!has(request.name) || request.name == '' || request.name == 'default'" - rules: - - apiGroups: [''] - apiVersions: [v1] - operations: [DELETE] - resources: [namespaces] - scope: Cluster - - name: project.registration.fleet.datumapis.com - admissionReviewVersions: [v1] - failurePolicy: Fail - matchPolicy: Equivalent - sideEffects: NoneOnDryRun - timeoutSeconds: 20 - clientConfig: - url: https://fleet-registration.fleet-system.svc:9443/validate-registration - matchConditions: - - name: provider-project-name - expression: >- - !has(request.name) || request.name == '' || request.name in ["datum-cloud"] - rules: - - apiGroups: [resourcemanager.miloapis.com] - apiVersions: [v1alpha1] - operations: [DELETE] - resources: [projects] - scope: Cluster diff --git a/config/overlays/synthetic-staging/registration-exclusion.yaml b/config/overlays/synthetic-staging/registration-exclusion.yaml index 3b18c0a9..e4801d66 100644 --- a/config/overlays/synthetic-staging/registration-exclusion.yaml +++ b/config/overlays/synthetic-staging/registration-exclusion.yaml @@ -1,3 +1,5 @@ +# The synthetic Milo root (config/milo-synthetic) installs no registration +# webhook, so the registration workload has nothing to serve here. $patch: delete apiVersion: apps/v1 kind: Deployment @@ -18,41 +20,3 @@ kind: ServiceAccount metadata: name: fleet-registration namespace: fleet-system ---- -$patch: delete -apiVersion: rbac.authorization.k8s.io/v1 -kind: Role -metadata: - name: fleet-registration-ledger - namespace: fleet-system-private ---- -$patch: delete -apiVersion: rbac.authorization.k8s.io/v1 -kind: RoleBinding -metadata: - name: fleet-registration-ledger - namespace: fleet-system-private ---- -$patch: delete -apiVersion: admissionregistration.k8s.io/v1 -kind: ValidatingAdmissionPolicy -metadata: - name: fleet-registration-ledger-protection ---- -$patch: delete -apiVersion: admissionregistration.k8s.io/v1 -kind: ValidatingAdmissionPolicyBinding -metadata: - name: fleet-registration-ledger-protection ---- -$patch: delete -apiVersion: admissionregistration.k8s.io/v1 -kind: ValidatingAdmissionPolicy -metadata: - name: fleet-registration-namespace-protection ---- -$patch: delete -apiVersion: admissionregistration.k8s.io/v1 -kind: ValidatingAdmissionPolicyBinding -metadata: - name: fleet-registration-namespace-protection diff --git a/docs/development/registration-storage-rollout.md b/docs/development/registration-storage-rollout.md deleted file mode 100644 index 44ed4512..00000000 --- a/docs/development/registration-storage-rollout.md +++ /dev/null @@ -1,232 +0,0 @@ -# Registration storage expansion and non-admitting bootstrap - -[Stage-1 contract](inventory-capacity-registration.md) · [Packaging](../../config/README.md) - -## Delivery boundary - -Implemented against feature revision `32c3c200b7afd50a43ae705609f8f5fad0c63d40`. -This change is independent of pending PR144 (`dc0f872977ecf817557b96fa82d53b853110a198`), -whose staging integration document was read in full. It does not replace that -PR's availability work or evidence; reconcile overlapping deployment/ledger edits -when combining them. **Parent independent adversarial review is required.** - -The two Fleet prerequisites are addressed by bounded, lossless expansion (not -alias release) and transport-first, deny-only startup. This is not live acceptance. -No live mutation, grant, deployment, allocation or provider effect is authorized -by this change. The reported mixed live pairing (synthetic host without the service, -production Milo Fail webhook without caBundle) must not be repaired by relaxing -admission or changing host overlays indiscriminately. Existing Enabled capacity -and synthetic consumers are not disposable acceptance fixtures. - -## Single-CAS storage protocol - -The original `fleet-capacity-registration-v1` Secret and UID remain the sole CAS -root. Version 2 adds `routing.json` and `tail.json`. Immutable Secrets named -`fleet-registration-segment--` retain sealed tails. -Every read verifies segment name, UID, immutability, deletion state, payload digest -and authority/provider scope. Missing/replaced/corrupt/unreadable storage is never -an empty partition. The same root still serializes all aliases and provider projects. - -Segments are ordered overlays, not independently admitting hash shards. Groups -are keyed by admission operation UID for registrations and Project route/Device UID -for Device fences. Only changed groups are copied into the mutable tail, whole. -Legacy multiple-version groups are sealed without reinterpretation. Existing -authoritative update/coalescing rules alone supersede pending versions. The writer -also rejects dropping registrations, aliases, tombstones or known lifetime identity. -New Device fences retain Project UID, namespace name/UID and Device name; missing -legacy fields are not backfilled or proof of safe release. Creates and edits -require a live namespace. Deletes and finalizer-only updates do not, so a -terminating provider namespace can drain its Devices. They bind the terminating -namespace's UID, or the UID already recorded once the namespace is gone, and -still write a permanent tombstone. Registered Devices remain undeletable. - -An operator signs `expand`, binding exact root UID, resourceVersion, epoch, -authority, sorted provider scope, change ID and reason. The service: - -1. Verifies the pinned Ed25519 key and CAS-retains the request as pending before - effects. First conversion replaces `ledger.json` with an incompatible authority - sentinel, retaining its original bytes in `tail.json`. Old binaries reject it; - old in-flight writes lose CAS. Host policy forbids reverting the v2 format. -2. Creates one deterministic immutable segment with the frozen tail, root UID and - signed request. Every replica resumes the same name. AlreadyExists requires - exact content and immutable lifetime checks, never overwrite permission. -3. Reads back the segment, then CAS-appends its name/UID/digest, advances epoch and - empties the tail. Prior segments, activation and audit history remain retained. -4. Resumes admission under the same activation and full fence checks. Migration - never changes `Unknown`, `Recorded`, tombstones, reservations or eligibility. - -Crash/timeout before freeze has no authorized storage effect. After freeze, any -replica resumes retained authority even without the request file. A prepared -segment is associated with the pending operation, not garbage. A lost final CAS -response is reconciled from the root. No timeout/lease/age/absence cancels pending -work. Stale plans fail; inspect before re-signing. A public request admitted before -freeze may persist afterwards: its reservation was copied, so no claim of fencing -the API server's later storage commit is needed. A not-yet-reserved writer must win -the current root CAS or be denied/re-evaluated. No orphan alias is discarded. - -This does not implement release, scope changes, arbitrary restore or custody -compaction. Rollbacks need a v2-aware binary. Never restore an old root alone; -root plus all segments are one retained recovery set. Administrators who remove -policies or restore arbitrary storage remain outside the guarantee. - -## Enforced budgets - -| Surface | Hard bound | -| --- | --- | -| Mutable tail | 650,000 encoded bytes; larger candidate denied before admission success | -| Legacy tail accepted for sealing | 750,000 bytes, including an already-full v1 ledger | -| Root data including routing/control | 850,000 bytes, below the 1 MiB Secret data limit | -| Sealed segments | 16 plus the mutable tail; expansion is operator-authorized, not infinite | -| Signed payload / mounted envelope | 8,192 / 16,384 bytes | -| Activation audit | Current activation plus seven previous signed activations, never pruned; the ninth activation fails (lifetime limit) | - -The ordinary stop leaves 100 KB relative to the former ledger cap for safe sealing; -the root budget additionally accommodates routing/control. A segment is at most -750 KB plus its small control envelope. Failed creates, aliases, distinct Device -incarnations and failed registrations consume budget. Oversized requests cannot -consume transition reserve. Segment retries target one name, not orphan snapshots. -Maximum ledger payload is 16 × 750,000 + 650,000 bytes plus bounded control metadata. -This deliberately retains complete provider scans and the single-root bottleneck; -it is not a throughput qualification. Pod memory is bounded at 512 MiB. - -The mTLS-only `/status` reports tail bytes, headroom, remaining segments, epoch, -pending state, root UID/RV, scope and verified fence digest, without reservation -contents or actor data. Parent monitoring must alert below 100,000 bytes headroom -and before only two segments remain. Sign expansion before exhaustion. A full v1 -ledger reports `registration ledger is full; sign an expand control request`; -a full v2 tail with segments left reports `registration growth stopped`. Both -mean sign `expand` as in step 7 below. Once all 16 segments are sealed, writes -and `expand` report `registration segments exhausted`: expansion is refused, so -re-signing it cannot help. At that terminal bound, stop protected growth and -escalate for a separately reviewed storage migration; never increase caps or -delete/reset/release records manually. -Public inventory reads remain unaffected. Denied/timed-out private writes deny -admission even if reads succeed; uncertain commits stay retained. - -## Transport versus activation - -The process loads credentials, TLS material and the operator public key, then -listens without requiring the ledger or installed webhook. It denies **every** -admission in bootstrap. `/transportz` returns 204 on the same mTLS listener for -SAN/CA/routing verification. The pod TCP readiness probe intentionally supplies -Service endpoints during bootstrap; it is not the UI admission gate. -`/activationz` returns 503 until activation and current readable dependencies -verify. It is not proof of write permission, future availability or capacity -eligibility. Request headers/labels/annotations/extras cannot enable admission; -there is no bootstrap bypass flag or public control endpoint. - -Signed `activate` also pins the digest of the installed, API-defaulted webhook -`webhooks` array, obtained from `/status` after `VerifyFence` succeeds. Activation -CAS and every admission retain full fence verification. Missing trust, changed -endpoint/CA, partial deployment, relaxed rules or degraded dependencies deny. -Approved trust changes require another exact signed activation; prior signatures -remain in bounded root audit history. The configured signing key is an operator -trust boundary, not caller authority; coordinate changes with pending signatures. -Global capacity fencing and privileged/root-context limitations are unchanged. - -### Activation budget is a lifetime limit - -The root keeps the current activation plus seven previous ones. The ninth -activation of a root fails with `activation audit budget exhausted`. Nothing -prunes or compacts this history, so the limit applies to the root's whole life -until a separately reviewed compaction migration exists. Every change to the -pinned fence digest needs a new activation and uses one slot. That includes -webhook CA rotation (the `caBundle` is part of the digest) and API-server drift -in defaulted webhook fields after an upgrade. Batch planned trust changes into -one activation where possible, and count the remaining slots before each one. -At the cap, admission stays on its current activation while that activation's -fence still verifies. If the fence has already changed, registration stays -non-admitting. Do not delete or edit `routing.json`, and do not create a new -root to reset the count. Escalate for the reviewed compaction migration. - -### Rotating the operator signing key - -The public key is read once at process startup from `public.pem`, and every -signature is verified against the key the process currently holds. A pending -expansion cannot be cancelled, and `ResumeExpansion` re-verifies the pending -signature against the current key. If the key rotates while an expansion is -pending, the expansion cannot complete and the root stays fenced. Rotate in -this order: - -1. Fetch `/status` and confirm no expansion is pending. If one is, let it - complete under the current key and confirm the epoch advanced. Do not sign - a new `expand` until the rotation is finished. -2. Replace `public.pem` in `fleet-registration-control`, then restart every - registration replica, because a running process keeps the key it loaded. -3. The retained activation was signed by the old key, so the restarted - processes stay non-admitting. Sign a fresh `activate` with the new key - (step 7 below). This uses one activation slot. - -## Exact staged parent infrastructure contract - -These steps require a separately approved infra PR; none authorizes live execution. - -1. Preserve private baseline evidence. Resolve registration authority and complete - provider scope separately from synthetic consumers. Do not narrow scope to - conceal legacy capacity or reuse manager root grants. Capacity writes remain - globally fenced, including outside `datum-cloud`. -2. Install retention policies before bootstrap or broader RBAC. The service gets - get/create Secrets in the dedicated private namespace and update only on the - root. Fail host admission restricts its creates to immutable segment names; - it cannot create the root/arbitrary Secrets or update/delete segments. Prove - negative cases and retain backups of **all** segments; never use GitOps to - reconcile an empty root. Namespace/root deletion remains forbidden. -3. Provision separate root/project read-and-SAR identities, serving SAN/CA, - dedicated webhook client certificate/CA, and `fleet-registration-control` - ConfigMap in `fleet-system` with `public.pem` (Ed25519 PKIX PEM). Restrict - ConfigMap/workload writers as operator trust authorities. No signing private - key, kubeconfig or rendered secret-bearing configuration belongs in Git. -4. Pin the reviewed image and deploy registration before activating a new Fail - webhook. With the already-broken live fence, leave protection installed. - Verify `/transportz` from the API-server route with trusted client TLS, and - reject missing/untrusted clients. No public write is a health probe; never - remove/relax the existing fence to test routing. -5. Create the empty root once with exact authority and sorted projects in - `ledger.json`, after retention acceptance. Abort on AlreadyExists and inspect - rather than replace. Existing v1 roots activate/migrate in place with the same UID. -6. Wire Milo's dedicated webhook client and serving caBundle in environment-owned - overlays. Verify complete Fail rules. Fetch `/status` over trusted transport - and review the installed fence and root UID/RV/epoch/scope/fence digest. -7. Sign a `ControlRequest` JSON containing `action: "activate"`, `id`, `reason`, - `authority`, `projects`, `rootUID`, `resourceVersion`, `epoch`, `fenceDigest`: - - ```sh - go run ./cmd/fleet-registration-control --request="$PRIVATE_REQUEST" --key="$OFFLINE_KEY" > "$PRIVATE_SIGNED_REQUEST" - ``` - - The helper requires a PKCS8 Ed25519 private key. Only its signed envelope goes - into ConfigMap `request.json`; the private key is never mounted. The process - checks every 30 seconds. Reconcile through `/status` and `/activationz`, not - ConfigMap update success. For expansion use `action: "expand"`; no fence - digest is required, and expansion cannot activate a bootstrap root. -8. Keep UI registration gated until real staff proxy identity, named Device and - create authorization denials, direct mutation denials, duplicate contention, - lifetime/legacy behavior, Unknown recovery and unchanged baselines are accepted - on intended Milo routes. Use disposable environments for outages/failures, - never shared-service disruption or real-asset smoke tests. Only the parent - can then report environment acceptance. - -## Local verification - -Tests exercise real Secret CAS/retention, bounded expansion, legacy integrity, -multi-replica migration, signature/scope/epoch spoofing, read-only RBAC and -persisted-but-timed-out writes. A real API request paused after admission fails -public persistence after migration; its aliases remain reserved and Unknown. -Five subprocess exits cover freeze, before/after segment persistence and -before/after root switch, recovered by new processes. Missing/replaced segments -fail closed. Existing identity, authorization, legacy and outage tests remain. - -```sh -KUBEBUILDER_ASSETS="$(go run sigs.k8s.io/controller-runtime/tools/setup-envtest@v0.25.2 use 1.37.0 -p path)" go test -race ./... -go vet ./... -go build ./... -kustomize build config/milo >/dev/null -kustomize build config/overlays/management-plane >/dev/null -./hack/validate-overlay-isolation.sh -./hack/test-overlay-isolation.sh -./hack/validate-doc-links.sh -git diff --check -``` - -No UI files change. These checks do not accept deployed Milo routing, credential -mounts, grants, GitOps ordering or real inventory. Disabled/Retain remains inert. diff --git a/internal/registration/admission.go b/internal/registration/admission.go index f4959d2b..0982a8b8 100644 --- a/internal/registration/admission.go +++ b/internal/registration/admission.go @@ -1,15 +1,19 @@ +// Package registration admits inert, inventory-backed MachineCapacity records. +// +// The webhook keeps no state of its own. Every decision is made against live +// Devices and capacities in the configured provider projects, so the API +// server remains the only store. One capacity per Device is enforced by the +// API server itself: the capacity name is derived from the Device UID, and two +// creates for the same Device collide on that name. package registration import ( - "bytes" "context" "crypto/sha256" "encoding/hex" "encoding/json" "errors" "fmt" - "io" - "log/slog" "reflect" "regexp" "slices" @@ -21,7 +25,6 @@ import ( iam "go.miloapis.com/milo/pkg/apis/iam/v1alpha1" admissionv1 "k8s.io/api/admission/v1" authenticationv1 "k8s.io/api/authentication/v1" - corev1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" @@ -32,22 +35,39 @@ const ( DeviceUIDAnnotation = "fleet.datumapis.com/registration-device-uid" DeviceVersionAnnotation = "fleet.datumapis.com/registration-device-version" OperationAnnotation = "fleet.datumapis.com/registration-operation" + + // CapacityNamePrefix starts every registered capacity name. The rest of + // the name is the backing Device's UID. + CapacityNamePrefix = "device-" + + // InventoryNamespace is the only namespace registration reads and writes. + InventoryNamespace = "default" ) +// CapacityName is the only name a registered capacity for this Device +// incarnation may have. Because the API server rejects a second object with +// the same name, concurrent registrations of one Device cannot both persist. +func CapacityName(deviceUID types.UID) string { + return CapacityNamePrefix + string(deviceUID) +} + type Project struct { Identity controller.ProjectIdentity Client client.Client } type Handler struct { - Store Store - VerifyFence func(context.Context) error - FenceDigest func(context.Context) (string, error) - Resolve func(context.Context, string) (Project, error) - Authorize func(context.Context, Project, authenticationv1.UserInfo, string, string, string) error + // Projects is the complete provider scope. Duplicate identities are + // searched across all of it. + Projects []string + Resolve func(context.Context, string) (Project, error) + Authorize func(context.Context, Project, authenticationv1.UserInfo, string, string, string) error } -func aliases(device *inventory.Device) []string { +// Aliases returns the normalized hardware identifiers of a Device: serial, +// system UUID and, when present, the provider host reference. Two Devices +// sharing any alias may be the same machine. +func Aliases(device *inventory.Device) []string { var result []string pairs := [][2]string{{"serial", strings.ToLower(strings.TrimSpace(device.Spec.Identity.Serial))}, {"uuid", strings.ToLower(strings.TrimSpace(device.Spec.Identity.SystemUUID))}} if reference := device.Spec.ProviderHostRef; reference != nil { @@ -88,130 +108,69 @@ func projectName(actor authenticationv1.UserInfo) (string, error) { } func (handler *Handler) Handle(ctx context.Context, request admission.Request) admission.Response { - if !handler.Store.AllowInactiveForTests { - if err := handler.Ready(ctx); err != nil { - return admission.Denied(err.Error()) - } - } - if request.Operation == admissionv1.Delete && request.Name == "" && ((request.Resource.Group == "" && request.Resource.Resource == "namespaces") || (request.Resource.Group == "resourcemanager.miloapis.com" && request.Resource.Resource == "projects")) { - return admission.Denied("lifetime deletion requires an exact resource name; collection deletion cannot prove exclusion of retained lifetimes") + if request.Resource.Group != metal.GroupVersion.Group || request.Resource.Resource != "machinecapacities" { + return admission.Denied("unsupported registration admission resource") } - if request.Resource.Group == "" && request.Resource.Resource == "namespaces" && request.Name != "default" { - return admission.Allowed("outside the retained inventory namespace") - } - if request.Resource.Group == "resourcemanager.miloapis.com" && request.Resource.Resource == "projects" && request.Operation == admissionv1.Delete { - if slices.Contains(handler.Store.Projects, request.Name) { - return admission.Denied("provider project lifetime is retained by the registration authority") - } - return admission.Allowed("outside the provider registration scope") - } - if request.DryRun != nil && *request.DryRun { - return admission.Denied("registration admission retains reservations and does not support dry-run") + if request.Operation != admissionv1.Create || request.SubResource != "" { + return admission.Denied("capacity mutation and deletion are disabled; registered and legacy capacity require operator reconciliation") } name, err := projectName(request.UserInfo) if err != nil { return admission.Denied(err.Error()) } - if !slices.Contains(handler.Store.Projects, name) { - if (request.Resource.Group == "fleet.datumapis.com" && request.Resource.Resource == "devices") || (request.Resource.Group == "" && request.Resource.Resource == "namespaces") { - return admission.Allowed("outside the configured provider identity scope") - } - return admission.Denied("project is outside the configured registration authority") - } - if request.UID == "" { - return admission.Denied("admission operation identity is required") + if !slices.Contains(handler.Projects, name) { + return admission.Denied("project is outside the configured provider registration scope") } - for attempt := 0; attempt < 6; attempt++ { - err = handler.evaluate(ctx, name, request) - if !apierrors.IsConflict(err) { - break - } - } - if err != nil { - if apierrors.IsConflict(err) { - slog.ErrorContext(ctx, "registration ledger CAS retries exhausted", "attempts", 6, "project", name, "operation", request.UID) - } + if err := handler.evaluate(ctx, name, request); err != nil { return admission.Denied(err.Error()) } return admission.Allowed("inert inventory registration only; no availability or preparation authority") } func (handler *Handler) evaluate(ctx context.Context, name string, request admission.Request) error { - if handler.VerifyFence != nil { - if err := handler.VerifyFence(ctx); err != nil { - return err - } - } - secret, ledger, err := handler.Store.Read(ctx) - if err != nil { - return fmt.Errorf("registration unavailable: %w", err) - } - if _, exists := secret.Data["routing.json"]; exists { - route, err := decodeRouting(secret) - if err != nil { - return err - } - if route.Pending != nil { - return errors.New("registration expansion is fenced") - } - } - project, err := handler.Resolve(ctx, name) - if err != nil { - return err - } - if !project.Identity.Valid() || project.Identity.RouteName != name || project.Identity.AuthorityID != ledger.Authority { - return errors.New("project lifetime unavailable") - } - if request.Resource.Group == "" && request.Resource.Resource == "namespaces" { - if request.Name == "default" && request.Operation == admissionv1.Delete { - return errors.New("the inventory namespace cannot be deleted within the registration authority") - } - return nil - } - if request.Resource.Group == "fleet.datumapis.com" && request.Resource.Resource == "devices" { - return handler.device(ctx, project, request, secret, ledger) - } - if request.Resource.Group != "metal.datumapis.com" || request.Resource.Resource != "machinecapacities" { - return errors.New("unsupported registration admission resource") - } - if request.Operation != admissionv1.Create || request.SubResource != "" { - return errors.New("capacity mutation and deletion are disabled; retained and legacy capacity require operator reconciliation") - } - if request.Namespace != "default" { + if request.Namespace != InventoryNamespace { return errors.New("registration requires the default inventory namespace") } var capacity metal.MachineCapacity if err := json.Unmarshal(request.Object.Raw, &capacity); err != nil { return err } - if capacity.UID == "" || capacity.Name == "" || capacity.Name != request.Name || capacity.Namespace != "default" || capacity.GenerateName != "" || !capacity.DeletionTimestamp.IsZero() { - return errors.New("an explicit capacity name and API-assigned incarnation are required") + if capacity.Name == "" || capacity.Name != request.Name || capacity.Namespace != InventoryNamespace || capacity.GenerateName != "" || !capacity.DeletionTimestamp.IsZero() { + return errors.New("an explicit capacity name in the default namespace is required") } if capacity.Spec.AllocationPolicy != "Disabled" || capacity.Spec.ReclaimPolicy != "Retain" || capacity.Spec.CleaningPolicyRef.Name != "" || !reflect.DeepEqual(capacity.Status, metal.MachineCapacityStatus{}) || len(capacity.OwnerReferences) != 0 || len(capacity.Finalizers) != 0 { return errors.New("only Disabled/Retain registration with an explicitly unconfigured cleaning policy and no status or ownership is supported") } annotations := capacity.Annotations if len(annotations) != 3 || annotations[DeviceUIDAnnotation] == "" || annotations[DeviceVersionAnnotation] == "" || annotations[OperationAnnotation] == "" { - return errors.New("exact Device UID/resourceVersion and a stable registration operation are required") + return errors.New("exact Device UID/resourceVersion and a client operation ID are required") } if len(annotations[OperationAnnotation]) > 128 { return errors.New("registration operation is too long") } - if err := handler.Authorize(ctx, project, request.UserInfo, "metal.datumapis.com", "machinecapacities", ""); err != nil { - return err + if capacity.Name != CapacityName(types.UID(annotations[DeviceUIDAnnotation])) { + return fmt.Errorf("capacity name must be %q, derived from the selected Device UID, so one Device can back only one capacity", CapacityName(types.UID(annotations[DeviceUIDAnnotation]))) } - if err := handler.Authorize(ctx, project, request.UserInfo, "fleet.datumapis.com", "devices", capacity.Spec.DeviceRef.Name); err != nil { - return err + project, err := handler.Resolve(ctx, name) + if err != nil { + return errors.New("provider project lifetime is unavailable") } - namespace := &corev1.Namespace{} - if err := project.Client.Get(ctx, client.ObjectKey{Name: "default"}, namespace); err != nil { + if !project.Identity.Valid() || project.Identity.RouteName != name { + return errors.New("provider project lifetime is unavailable") + } + // Authorize before reading the Device so an unauthorized caller cannot + // learn whether it exists. + if err := handler.Authorize(ctx, project, request.UserInfo, metal.GroupVersion.Group, "machinecapacities", ""); err != nil { return err } - if namespace.UID == "" || !namespace.DeletionTimestamp.IsZero() { - return errors.New("inventory namespace lifetime unavailable") + if err := handler.Authorize(ctx, project, request.UserInfo, inventory.GroupVersion.Group, "devices", capacity.Spec.DeviceRef.Name); err != nil { + return err } device := &inventory.Device{} - if err := project.Client.Get(ctx, client.ObjectKey{Namespace: "default", Name: capacity.Spec.DeviceRef.Name}, device); err != nil { + if err := project.Client.Get(ctx, client.ObjectKey{Namespace: InventoryNamespace, Name: capacity.Spec.DeviceRef.Name}, device); err != nil { + if apierrors.IsNotFound(err) { + return errors.New("selected Device does not exist in the provider project") + } return errors.New("selected Device is unavailable") } if device.UID != types.UID(annotations[DeviceUIDAnnotation]) || device.ResourceVersion != annotations[DeviceVersionAnnotation] || !device.DeletionTimestamp.IsZero() { @@ -220,72 +179,15 @@ func (handler *Handler) evaluate(ctx context.Context, name string, request admis if !eligible(device) { return errors.New("registration requires non-placeholder serial, canonical system UUID, and complete provider aliases; incomplete identity is ambiguous") } - entry := Entry{Operation: request.UID, Actor: request.UserInfo, Project: name, ProjectUID: project.Identity.UID, NamespaceUID: namespace.UID, Name: capacity.Name, CapacityUID: capacity.UID, DeviceName: device.Name, DeviceUID: device.UID, DeviceVersion: device.ResourceVersion, Aliases: aliases(device), Input: append(json.RawMessage(nil), request.Object.Raw...), Outcome: "Unknown"} - entry.AssetID = entry.Aliases[1] - for _, retained := range ledger.Entries { - if retained.Operation == entry.Operation && reflect.DeepEqual(retained, entry) { - return nil - } - if overlaps(retained.Aliases, entry.Aliases) || (retained.Project == name && (retained.Name == entry.Name || retained.DeviceUID == entry.DeviceUID)) { - return ErrConflict - } - var prior metal.MachineCapacity - if json.Unmarshal(retained.Input, &prior) != nil { - return errors.New("retained registration is corrupt") - } - if retained.Project == name && prior.Annotations[OperationAnnotation] == annotations[OperationAnnotation] { - return ErrConflict - } - } - for _, fence := range ledger.DeviceFences { - if fence.Project == name && fence.UID == device.UID { - if (fence.ProjectUID != "" && fence.ProjectUID != entry.ProjectUID) || (fence.NamespaceUID != "" && fence.NamespaceUID != entry.NamespaceUID) || (fence.Name != "" && (fence.Name != device.Name || fence.Namespace != device.Namespace)) { - return ErrConflict - } - if fence.Deleted || (fence.Version != "" && fence.Version == device.ResourceVersion) { - return ErrConflict - } - continue - } - if overlaps(fence.Aliases, entry.Aliases) { - return ErrConflict - } - } - if err := handler.scan(ctx, entry); err != nil { - return err - } - current, err := handler.Resolve(ctx, name) - if err != nil || current.Identity != project.Identity { - return errors.New("project lifetime changed") - } - if err := project.Client.Get(ctx, client.ObjectKeyFromObject(namespace), namespace); err != nil || namespace.UID != entry.NamespaceUID || !namespace.DeletionTimestamp.IsZero() { - return errors.New("namespace lifetime changed") - } - if err := project.Client.Get(ctx, client.ObjectKeyFromObject(device), device); err != nil || device.UID != entry.DeviceUID || device.ResourceVersion != entry.DeviceVersion || !device.DeletionTimestamp.IsZero() { - return errors.New("selected Device changed") - } - if err := handler.Authorize(ctx, project, request.UserInfo, "metal.datumapis.com", "machinecapacities", ""); err != nil { - return err - } - if err := handler.Authorize(ctx, project, request.UserInfo, "fleet.datumapis.com", "devices", device.Name); err != nil { - return err - } - current, err = handler.Resolve(ctx, name) - if err != nil || current.Identity != project.Identity { - return errors.New("project lifetime changed during authorization") - } - if err := project.Client.Get(ctx, client.ObjectKeyFromObject(namespace), namespace); err != nil || namespace.UID != entry.NamespaceUID || !namespace.DeletionTimestamp.IsZero() { - return errors.New("namespace lifetime changed during authorization") - } - if err := project.Client.Get(ctx, client.ObjectKeyFromObject(device), device); err != nil || device.UID != entry.DeviceUID || device.ResourceVersion != entry.DeviceVersion || !device.DeletionTimestamp.IsZero() { - return errors.New("selected Device changed during authorization") - } - ledger.Entries = append(ledger.Entries, entry) - return handler.Store.Write(ctx, secret, ledger) + return handler.scan(ctx, name, device) } -func (handler *Handler) scan(ctx context.Context, entry Entry) error { - for _, name := range handler.Store.Projects { +// scan compares the selected Device with every live Device and capacity in the +// provider scope. It is a point-in-time read: see the stage-1 contract for the +// race with a concurrently created duplicate Device. +func (handler *Handler) scan(ctx context.Context, selectedProject string, selected *inventory.Device) error { + selectedAliases := Aliases(selected) + for _, name := range handler.Projects { project, err := handler.Resolve(ctx, name) if err != nil { return errors.New("provider identity scope is unavailable") @@ -298,17 +200,18 @@ func (handler *Handler) scan(ctx context.Context, entry Entry) error { if err := project.Client.List(ctx, &capacities); err != nil { return errors.New("provider capacity inventory is unavailable") } - for _, device := range devices.Items { - if name == entry.Project && device.UID == entry.DeviceUID { + for index := range devices.Items { + device := &devices.Items[index] + if name == selectedProject && device.UID == selected.UID { continue } - if overlaps(aliases(&device), entry.Aliases) { - return errors.New("another Device shares recorded hardware identity; resolve aliases before registration") + if overlaps(Aliases(device), selectedAliases) { + return fmt.Errorf("another Device (%s) shares recorded hardware identity; resolve the duplicate before registration", describe(name, selectedProject, device.Namespace, device.Name)) } } for _, capacity := range capacities.Items { - if name == entry.Project && capacity.Namespace == "default" && capacity.Name == entry.Name { - return ErrConflict + if name == selectedProject && capacity.Namespace == selected.Namespace && (capacity.Spec.DeviceRef.Name == selected.Name || capacity.Annotations[DeviceUIDAnnotation] == string(selected.UID)) { + return fmt.Errorf("Device already backs capacity %s; one Device can back only one capacity", capacity.Name) } var matched *inventory.Device for index := range devices.Items { @@ -319,203 +222,31 @@ func (handler *Handler) scan(ctx context.Context, entry Entry) error { } } if matched == nil || inventory.CapacityBackingError(matched) != nil { - return errors.New("legacy capacity has unresolved physical identity; registration cannot establish non-conflict") + return fmt.Errorf("capacity %s has unresolved physical identity; registration cannot establish non-conflict", describe(name, selectedProject, capacity.Namespace, capacity.Name)) } - if overlaps(aliases(matched), entry.Aliases) { - return ErrConflict + if overlaps(Aliases(matched), selectedAliases) { + return fmt.Errorf("capacity %s is backed by a Device sharing recorded hardware identity", describe(name, selectedProject, capacity.Namespace, capacity.Name)) } } } return nil } -func (handler *Handler) device(ctx context.Context, project Project, request admission.Request, secret *corev1.Secret, ledger Ledger) error { - var device, old inventory.Device - if request.Operation != admissionv1.Create { - if err := json.Unmarshal(request.OldObject.Raw, &old); err != nil { - return err - } - } - if request.Operation != admissionv1.Delete { - if err := json.Unmarshal(request.Object.Raw, &device); err != nil { - return err - } - } else { - device = old - } - for _, entry := range ledger.Entries { - bound := entry.Project == project.Identity.RouteName && entry.DeviceUID == device.UID - if entry.Project == project.Identity.RouteName && device.Namespace == "default" && entry.DeviceName == device.Name && !bound { - return ErrConflict - } - if bound && (entry.ProjectUID != project.Identity.UID || request.Operation == admissionv1.Delete) { - return ErrConflict - } - if overlaps(entry.Aliases, aliases(&device)) && !bound { - return ErrConflict - } - if bound && !reflect.DeepEqual(device.Spec, old.Spec) { - return errors.New("registered Device specification is frozen") - } - } - if request.Operation == admissionv1.Update { - if device.UID != old.UID || !reflect.DeepEqual(device.Spec.Identity, old.Spec.Identity) || !reflect.DeepEqual(aliases(&device), aliases(&old)) { - return errors.New("Device incarnation and identity are immutable") - } - if old.ResourceVersion == "" { - return errors.New("Device update baseline is unavailable") - } - } - if request.Operation != admissionv1.Create && request.Operation != admissionv1.Delete && request.Operation != admissionv1.Update { - return errors.New("unsupported Device operation") - } - if device.UID == "" { - return errors.New("Device incarnation unavailable") - } - if request.Operation == admissionv1.Update && identicalObjects(request.OldObject.Raw, request.Object.Raw) { - return nil - } - // Deletes and finalizer removals are how a terminating namespace drains its - // Devices, so they must not depend on the namespace still being live. - releasing := request.Operation == admissionv1.Delete || (request.Operation == admissionv1.Update && finalizerRemoval(request.OldObject.Raw, request.Object.Raw)) - deleting := request.Operation == admissionv1.Delete || (releasing && !old.DeletionTimestamp.IsZero()) - namespaceUID, err := deviceNamespace(ctx, project, device, ledger, releasing) - if err != nil { - return err - } - fence := DeviceFence{Project: project.Identity.RouteName, ProjectUID: project.Identity.UID, Namespace: device.Namespace, NamespaceUID: namespaceUID, Name: device.Name, UID: device.UID, Deleted: deleting} - if request.Operation == admissionv1.Update { - current := &inventory.Device{} - if err := project.Client.Get(ctx, client.ObjectKeyFromObject(&old), current); err != nil { - return err - } - if current.UID != old.UID || current.ResourceVersion != old.ResourceVersion || device.ResourceVersion != old.ResourceVersion || (!current.DeletionTimestamp.IsZero() && !deleting) { - return errors.New("Device update baseline is no longer current") - } - if !deleting { - fence.Version = old.ResourceVersion - } - } - if request.Operation == admissionv1.Create { - fence.Aliases = aliases(&device) - for _, retained := range ledger.DeviceFences { - if overlaps(retained.Aliases, fence.Aliases) && !reflect.DeepEqual(retained, fence) { - return ErrConflict - } - } - } - coalesced := make([]DeviceFence, 0, len(ledger.DeviceFences)+1) - for _, retained := range ledger.DeviceFences { - if retained.Project != fence.Project || retained.UID != fence.UID { - coalesced = append(coalesced, retained) - continue - } - if (retained.Deleted && !fence.Deleted) || (request.Operation == admissionv1.Create && !reflect.DeepEqual(retained, fence)) { - return ErrConflict - } - if (retained.ProjectUID != "" && retained.ProjectUID != fence.ProjectUID) || (retained.NamespaceUID != "" && retained.NamespaceUID != fence.NamespaceUID) || (retained.Name != "" && (retained.Name != fence.Name || retained.Namespace != fence.Namespace)) { - return ErrConflict - } - for _, alias := range retained.Aliases { - if !slices.Contains(fence.Aliases, alias) { - fence.Aliases = append(fence.Aliases, alias) - } - } - } - slices.Sort(fence.Aliases) - coalesced = append(coalesced, fence) - if reflect.DeepEqual(ledger.DeviceFences, coalesced) { - return nil - } - ledger.DeviceFences = coalesced - return handler.Store.Write(ctx, secret, ledger) -} - -// deviceNamespace returns the namespace lifetime to bind into the Device fence. -// Ordinary writes require a live namespace. Releasing writes accept a -// terminating namespace, and once the namespace is gone they fall back to the -// lifetime already recorded for this Device so the tombstone never loses it. -func deviceNamespace(ctx context.Context, project Project, device inventory.Device, ledger Ledger, releasing bool) (types.UID, error) { - var namespace corev1.Namespace - err := project.Client.Get(ctx, client.ObjectKey{Name: device.Namespace}, &namespace) - if err != nil && (!releasing || !apierrors.IsNotFound(err)) { - return "", err - } - if err == nil { - if namespace.UID == "" || (!releasing && !namespace.DeletionTimestamp.IsZero()) { - return "", errors.New("Device namespace lifetime unavailable") - } - return namespace.UID, nil - } - for _, retained := range ledger.DeviceFences { - if retained.Project == project.Identity.RouteName && retained.UID == device.UID && retained.NamespaceUID != "" { - return retained.NamespaceUID, nil - } +// describe names a conflicting record for the caller. Records in other +// provider projects are not named, because the caller may not be able to read +// them. +func describe(project, selectedProject, namespace, name string) string { + if project != selectedProject { + return "in another provider project" } - // A legacy fence never recorded the namespace; the tombstone stays - // legacy-shaped rather than inventing a lifetime or denying the delete. - return "", nil + return namespace + "/" + name } -// finalizerRemoval reports whether an update only removes finalizers. Server -// managed field bookkeeping is ignored; any other change is a real edit. -func finalizerRemoval(old, current []byte) bool { - decode := func(raw []byte) (map[string]any, []string, bool) { - decoder := json.NewDecoder(bytes.NewReader(raw)) - decoder.UseNumber() - var object map[string]any - if err := decoder.Decode(&object); err != nil || object == nil || decoder.Decode(new(any)) != io.EOF { - return nil, nil, false - } - metadata, _ := object["metadata"].(map[string]any) - if metadata == nil { - return nil, nil, false - } - var finalizers []string - if values, exists := metadata["finalizers"]; exists { - list, ok := values.([]any) - if !ok { - return nil, nil, false - } - for _, value := range list { - name, ok := value.(string) - if !ok { - return nil, nil, false - } - finalizers = append(finalizers, name) - } - } - delete(metadata, "finalizers") - delete(metadata, "managedFields") - return object, finalizers, true - } - before, beforeFinalizers, beforeOK := decode(old) - after, afterFinalizers, afterOK := decode(current) - if !beforeOK || !afterOK || len(afterFinalizers) >= len(beforeFinalizers) || !reflect.DeepEqual(before, after) { - return false - } - for _, name := range afterFinalizers { - if !slices.Contains(beforeFinalizers, name) { - return false - } - } - return true -} - -func identicalObjects(old, current []byte) bool { - decode := func(raw []byte) (map[string]any, error) { - decoder := json.NewDecoder(bytes.NewReader(raw)) - decoder.UseNumber() - var object map[string]any - if err := decoder.Decode(&object); err != nil { - return nil, err - } - if err := decoder.Decode(new(any)); err != io.EOF { - return nil, errors.New("expected exactly one JSON object") +func overlaps(left, right []string) bool { + for _, first := range left { + if slices.Contains(right, first) { + return true } - return object, nil } - before, beforeErr := decode(old) - after, afterErr := decode(current) - return beforeErr == nil && afterErr == nil && before != nil && after != nil && reflect.DeepEqual(before, after) + return false } diff --git a/internal/registration/admission_regression_envtest_test.go b/internal/registration/admission_regression_envtest_test.go deleted file mode 100644 index ff65a8f7..00000000 --- a/internal/registration/admission_regression_envtest_test.go +++ /dev/null @@ -1,436 +0,0 @@ -package registration - -import ( - "context" - "encoding/json" - "fmt" - "net/http/httptest" - "os" - "path/filepath" - "strings" - "sync" - "testing" - "time" - - inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" - metal "go.datum.net/fleet/internal/api/v1alpha1" - "go.datum.net/fleet/internal/controller" - iam "go.miloapis.com/milo/pkg/apis/iam/v1alpha1" - resourcemanager "go.miloapis.com/milo/pkg/apis/resourcemanager/v1alpha1" - admissionv1 "k8s.io/api/admission/v1" - admissionregistrationv1 "k8s.io/api/admissionregistration/v1" - authorizationv1 "k8s.io/api/authorization/v1" - corev1 "k8s.io/api/core/v1" - extensions "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" - apierrors "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/client-go/rest" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/envtest" - "sigs.k8s.io/controller-runtime/pkg/webhook/admission" - "sigs.k8s.io/yaml" -) - -func TestRealNoopRegistrationAndScopedTransportFailure(t *testing.T) { - if os.Getenv("KUBEBUILDER_ASSETS") == "" { - t.Skip("KUBEBUILDER_ASSETS required") - } - ctx := context.Background() - projectCRD := &extensions.CustomResourceDefinition{ObjectMeta: metav1.ObjectMeta{Name: "projects.resourcemanager.miloapis.com"}, Spec: extensions.CustomResourceDefinitionSpec{Group: "resourcemanager.miloapis.com", Names: extensions.CustomResourceDefinitionNames{Plural: "projects", Singular: "project", Kind: "Project", ListKind: "ProjectList"}, Scope: extensions.ClusterScoped, Versions: []extensions.CustomResourceDefinitionVersion{{Name: "v1alpha1", Served: true, Storage: true, Schema: &extensions.CustomResourceValidation{OpenAPIV3Schema: &extensions.JSONSchemaProps{Type: "object"}}}}}} - environment := &envtest.Environment{CRDDirectoryPaths: []string{filepath.Join("..", "..", "config", "base", "crd"), filepath.Join("..", "..", "config", "components", "inventory", "crds")}, CRDs: []*extensions.CustomResourceDefinition{projectCRD}, ErrorIfCRDPathMissing: true} - environment.ControlPlane.GetAPIServer().Configure().Append("disable-admission-plugins", "NamespaceLifecycle") - config, err := environment.Start() - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { - if err := environment.Stop(); err != nil { - t.Error(err) - } - }) - scheme := runtime.NewScheme() - for _, add := range []func(*runtime.Scheme) error{corev1.AddToScheme, inventory.AddToScheme, metal.AddToScheme, resourcemanager.AddToScheme, admissionregistrationv1.AddToScheme, authorizationv1.AddToScheme} { - if err := add(scheme); err != nil { - t.Fatal(err) - } - } - api, err := client.New(config, client.Options{Scheme: scheme}) - if err != nil { - t.Fatal(err) - } - if err := extensions.AddToScheme(scheme); err != nil { - t.Fatal(err) - } - deviceCRD := &extensions.CustomResourceDefinition{} - if err := api.Get(ctx, client.ObjectKey{Name: "devices.fleet.datumapis.com"}, deviceCRD); err != nil { - t.Fatal(err) - } - deviceCRD.Spec.Versions[0].Schema.OpenAPIV3Schema.Properties["status"] = extensions.JSONSchemaProps{Type: "object", Properties: map[string]extensions.JSONSchemaProps{"observation": {Type: "integer"}}} - if err := api.Update(ctx, deviceCRD); err != nil { - t.Fatal(err) - } - devices := []*inventory.Device{ - {ObjectMeta: metav1.ObjectMeta{Name: "noop-hardware", Namespace: "default"}, Spec: inventory.DeviceSpec{ClaimRef: inventory.LocalReference{Name: "installation"}, Identity: inventory.DeviceIdentity{Model: "test", Serial: "noop-serial", SystemUUID: "11111111-1111-1111-1111-111111111111"}}}, - {ObjectMeta: metav1.ObjectMeta{Name: "real-edit-hardware", Namespace: "default"}, Spec: inventory.DeviceSpec{ClaimRef: inventory.LocalReference{Name: "installation"}, Identity: inventory.DeviceIdentity{Model: "test", Serial: "edit-serial", SystemUUID: "22222222-2222-2222-2222-222222222222"}}}, - {ObjectMeta: metav1.ObjectMeta{Name: "collector-hardware", Namespace: "default"}, Spec: inventory.DeviceSpec{ClaimRef: inventory.LocalReference{Name: "installation"}, Identity: inventory.DeviceIdentity{Model: "test", Serial: "collector-serial", SystemUUID: "33333333-3333-3333-3333-333333333333"}}}, - {ObjectMeta: metav1.ObjectMeta{Name: "concurrent-hardware", Namespace: "default"}, Spec: inventory.DeviceSpec{ClaimRef: inventory.LocalReference{Name: "installation"}, Identity: inventory.DeviceIdentity{Model: "test", Serial: "concurrent-serial", SystemUUID: "44444444-4444-4444-4444-444444444444"}}}, - } - for _, device := range devices { - if err := api.Create(ctx, device, client.FieldOwner("review")); err != nil { - t.Fatal(err) - } - } - for _, name := range []string{"datum-cloud", "unrelated-consumer"} { - if err := api.Create(ctx, &resourcemanager.Project{ObjectMeta: metav1.ObjectMeta{Name: name}}); err != nil { - t.Fatal(err) - } - } - if err := api.Create(ctx, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "other-namespace"}}); err != nil { - t.Fatal(err) - } - encoded, _ := json.Marshal(Ledger{Authority: "milo", Projects: []string{"datum-cloud"}}) - if err := api.Create(ctx, &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: LedgerName, Namespace: "default"}, Data: map[string][]byte{"ledger.json": encoded}}); err != nil { - t.Fatal(err) - } - handler := &Handler{Store: Store{Client: api, Namespace: "default", Authority: "milo", Projects: []string{"datum-cloud"}, AllowInactiveForTests: true}, VerifyFence: func(ctx context.Context) error { return VerifyFence(ctx, api, []string{"datum-cloud"}) }, Resolve: func(context.Context, string) (Project, error) { - return Project{Identity: controller.ProjectIdentity{AuthorityID: "milo", RouteName: "datum-cloud", UID: "project-1"}, Client: api}, nil - }, Authorize: Authorize} - type gate struct { - entered, release chan struct{} - once sync.Once - } - gates := map[string]*gate{ - "first": {entered: make(chan struct{}), release: make(chan struct{})}, - "second": {entered: make(chan struct{}), release: make(chan struct{})}, - } - server := httptest.NewTLSServer(&admission.Webhook{Handler: admission.HandlerFunc(func(ctx context.Context, request admission.Request) admission.Response { - response := handler.Handle(ctx, request) - if response.Allowed && request.Operation == admissionv1.Update && request.Resource.Resource == "devices" && request.Name == "concurrent-hardware" { - var device inventory.Device - if json.Unmarshal(request.Object.Raw, &device) == nil { - if pending := gates[device.Labels["admission-delay"]]; pending != nil { - pending.once.Do(func() { - close(pending.entered) - select { - case <-pending.release: - case <-ctx.Done(): - } - }) - } - } - } - return response - })}) - t.Cleanup(server.Close) - data, err := os.ReadFile("../../config/components/registration-admission/webhook.yaml") - if err != nil { - t.Fatal(err) - } - var webhooks admissionregistrationv1.ValidatingWebhookConfiguration - if err := yaml.UnmarshalStrict(data, &webhooks); err != nil { - t.Fatal(err) - } - url := server.URL - for index := range webhooks.Webhooks { - webhooks.Webhooks[index].ClientConfig = admissionregistrationv1.WebhookClientConfig{URL: &url, CABundle: pemCertificate(server.Certificate().Raw)} - } - if err := api.Create(ctx, &webhooks); err != nil { - t.Fatal(err) - } - actorConfig := rest.CopyConfig(config) - actorConfig.Impersonate = rest.ImpersonationConfig{UserName: "review-operator", UID: "actor-1", Groups: []string{"system:masters"}, Extra: map[string][]string{iam.ParentKindExtraKey: {"Project"}, iam.ParentAPIGroupExtraKey: {"resourcemanager.miloapis.com"}, iam.ParentNameExtraKey: {"datum-cloud"}}} - actor, err := client.New(actorConfig, client.Options{Scheme: scheme}) - if err != nil { - t.Fatal(err) - } - outsideConfig := rest.CopyConfig(actorConfig) - outsideConfig.Impersonate.Extra = map[string][]string{iam.ParentKindExtraKey: {"Project"}, iam.ParentAPIGroupExtraKey: {"resourcemanager.miloapis.com"}, iam.ParentNameExtraKey: {"unrelated-consumer"}} - outside, err := client.New(outsideConfig, client.Options{Scheme: scheme}) - if err != nil { - t.Fatal(err) - } - deadline := time.Now().Add(10 * time.Second) - for { - err := actor.Update(ctx, devices[0].DeepCopyObject().(*inventory.Device), client.DryRunAll) - if apierrors.IsForbidden(err) { - break - } - if time.Now().After(deadline) { - t.Fatalf("inventory webhook did not engage: %v", err) - } - time.Sleep(30 * time.Millisecond) - } - register := func(t *testing.T, device *inventory.Device, name string) error { - t.Helper() - request := registrationRequest(t, device, name) - var capacity metal.MachineCapacity - if err := json.Unmarshal(request.Object.Raw, &capacity); err != nil { - t.Fatal(err) - } - capacity.UID = "" - return actor.Create(ctx, &capacity) - } - t.Run("unchanged-success-retains-current-RV-and-registers", func(t *testing.T) { - device := devices[0] - unchanged := false - for attempt := 0; attempt < 3; attempt++ { - if err := actor.Get(ctx, client.ObjectKeyFromObject(device), device); err != nil { - t.Fatal(err) - } - before := device.ResourceVersion - if err := actor.Update(ctx, device, client.FieldOwner("review")); err != nil { - t.Fatal(err) - } - if before == device.ResourceVersion { - unchanged = true - break - } - } - if !unchanged { - t.Fatal("API server did not reproduce the unchanged resourceVersion") - } - if err := actor.Get(ctx, client.ObjectKeyFromObject(device), device); err != nil { - t.Fatal(err) - } - if err := register(t, device, "after-noop"); err != nil { - t.Fatalf("unchanged successful update poisoned the current selection: %v", err) - } - }) - t.Run("genuine-edit-requires-explicit-new-selection", func(t *testing.T) { - device := devices[1] - baseline := device.DeepCopyObject().(*inventory.Device) - device.Labels = map[string]string{"review-control": "real-change"} - if err := actor.Update(ctx, device, client.FieldOwner("review")); err != nil { - t.Fatal(err) - } - if baseline.ResourceVersion == device.ResourceVersion { - t.Fatal("real edit did not change the version") - } - if err := register(t, baseline, "stale-selection"); !apierrors.IsForbidden(err) { - t.Fatalf("stale selection not fenced: %v", err) - } - if err := actor.Get(ctx, client.ObjectKeyFromObject(device), device); err != nil { - t.Fatal(err) - } - if err := register(t, device, "after-real-edit"); err != nil { - t.Fatal(err) - } - }) - t.Run("repeated-status-and-metadata-writes-remain-bounded", func(t *testing.T) { - device := devices[2] - var initialSize int - for observation := 1; observation <= 120; observation++ { - if err := actor.Get(ctx, client.ObjectKeyFromObject(device), device); err != nil { - t.Fatal(err) - } - device.Labels = map[string]string{"observation": fmt.Sprint(observation)} - if err := actor.Update(ctx, device); err != nil { - t.Fatal(err) - } - current := &unstructured.Unstructured{} - current.SetAPIVersion("fleet.datumapis.com/v1alpha1") - current.SetKind("Device") - if err := actor.Get(ctx, client.ObjectKeyFromObject(device), current); err != nil { - t.Fatal(err) - } - before := current.GetResourceVersion() - current.Object["status"] = map[string]any{"observation": int64(observation)} - if err := actor.Status().Update(ctx, current, client.FieldOwner("inventory-collector")); err != nil { - t.Fatal(err) - } - if before == current.GetResourceVersion() { - t.Fatal("status observation did not persist") - } - secret, ledger, err := handler.Store.Read(ctx) - if err != nil { - t.Fatal(err) - } - count := 0 - for _, fence := range ledger.DeviceFences { - if fence.UID == device.UID { - count++ - } - } - if count != 1 { - t.Fatalf("%d fences after %d observations", count, observation) - } - if observation == 1 { - initialSize = len(secret.Data["ledger.json"]) - } - if len(secret.Data["ledger.json"]) > initialSize+20 { - t.Fatal("ledger grows with routine observations") - } - } - if err := actor.Get(ctx, client.ObjectKeyFromObject(device), device); err != nil { - t.Fatal(err) - } - if err := register(t, device, "after-collector"); err != nil { - t.Fatal(err) - } - }) - t.Run("delayed-old-write-cannot-commit-after-coalescing", func(t *testing.T) { - firstRelease := sync.OnceFunc(func() { close(gates["first"].release) }) - secondRelease := sync.OnceFunc(func() { close(gates["second"].release) }) - defer firstRelease() - defer secondRelease() - wait := func(pending *gate) { - t.Helper() - select { - case <-pending.entered: - case <-time.After(5 * time.Second): - t.Fatal("pending update did not enter admission") - } - } - device := devices[3] - first := device.DeepCopyObject().(*inventory.Device) - first.Labels = map[string]string{"admission-delay": "first"} - firstDone := make(chan error, 1) - go func() { firstDone <- actor.Update(ctx, first) }() - wait(gates["first"]) - device.Labels = map[string]string{"competing": "persisted"} - if err := actor.Update(ctx, device); err != nil { - t.Fatal(err) - } - currentVersion := device.ResourceVersion - second := device.DeepCopyObject().(*inventory.Device) - second.Labels = map[string]string{"admission-delay": "second"} - secondDone := make(chan error, 1) - go func() { secondDone <- actor.Update(ctx, second) }() - wait(gates["second"]) - firstRelease() - if err := <-firstDone; !apierrors.IsConflict(err) { - t.Fatalf("old in-flight baseline must conflict at storage: %v", err) - } - if err := actor.Get(ctx, client.ObjectKeyFromObject(device), device); err != nil { - t.Fatal(err) - } - if device.ResourceVersion != currentVersion { - t.Fatal("old in-flight write changed current version") - } - if err := register(t, device, "during-second-pending"); !apierrors.IsForbidden(err) { - t.Fatalf("coalescing lost current pending fence: %v", err) - } - _, ledger, err := handler.Store.Read(ctx) - if err != nil { - t.Fatal(err) - } - count := 0 - for _, fence := range ledger.DeviceFences { - if fence.UID == device.UID { - count++ - if fence.Version != currentVersion { - t.Fatal("retained wrong pending version") - } - } - } - if count != 1 { - t.Fatalf("concurrent versions created %d fences", count) - } - secondRelease() - if err := <-secondDone; err != nil { - t.Fatal(err) - } - if err := actor.Get(ctx, client.ObjectKeyFromObject(device), device); err != nil { - t.Fatal(err) - } - if err := register(t, device, "after-concurrent-writes"); err != nil { - t.Fatal(err) - } - }) - if err := handler.Recover(ctx); err != nil { - t.Fatal(err) - } - _, ledger, err := handler.Store.Read(ctx) - if err != nil || len(ledger.Entries) != 4 { - t.Fatalf("expected all registrations: %+v %v", ledger, err) - } - for _, entry := range ledger.Entries { - if entry.Outcome != "Recorded" || entry.CapacityUID == "" { - t.Fatalf("registration not recorded: %+v", entry) - } - } - if err := api.DeleteAllOf(ctx, &resourcemanager.Project{}); !apierrors.IsForbidden(err) || !strings.Contains(err.Error(), "collection deletion") { - t.Fatalf("healthy authority did not reject unnamed lifetime deletion: %v", err) - } - server.Close() - for _, test := range []struct { - name string - write func() error - blocked bool - }{ - {"unrelated Device create", func() error { - device := devices[0].DeepCopyObject().(*inventory.Device) - device.Name, device.UID, device.ResourceVersion, device.ManagedFields = "outside-after-outage", "", "", nil - device.Labels = map[string]string{"provider": "datum-cloud"} - return outside.Create(ctx, device) - }, false}, - {"provider Device create without opt-in labels", func() error { - device := devices[0].DeepCopyObject().(*inventory.Device) - device.Name, device.UID, device.ResourceVersion, device.ManagedFields = "inside-after-outage", "", "", nil - device.Namespace = "other-namespace" - device.Labels = map[string]string{"provider": "unrelated-consumer"} - return actor.Create(ctx, device) - }, true}, - {"provider Device update", func() error { return actor.Update(ctx, devices[0], client.DryRunAll) }, true}, - {"provider Device status update", func() error { return actor.Status().Update(ctx, devices[0], client.DryRunAll) }, true}, - {"provider Device delete", func() error { return actor.Delete(ctx, devices[0]) }, true}, - {"unrelated default namespace delete", func() error { - return outside.Delete(ctx, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "default"}}, client.DryRunAll) - }, false}, - {"provider other namespace delete", func() error { - return actor.Delete(ctx, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "other-namespace"}}) - }, false}, - {"provider default namespace delete", func() error { - return actor.Delete(ctx, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "default"}}, client.DryRunAll) - }, true}, - {"unrelated root Project delete", func() error { - return api.Delete(ctx, &resourcemanager.Project{ObjectMeta: metav1.ObjectMeta{Name: "unrelated-consumer"}}) - }, false}, - {"protected root Project delete", func() error { - return api.Delete(ctx, &resourcemanager.Project{ObjectMeta: metav1.ObjectMeta{Name: "datum-cloud"}}) - }, true}, - {"protected root Project collection delete", func() error { return api.DeleteAllOf(ctx, &resourcemanager.Project{}) }, true}, - {"global capacity create", func() error { - return outside.Create(ctx, &metal.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: "outside-capacity", Namespace: "default"}, Spec: metal.MachineCapacitySpec{DeviceRef: metal.LocalReference{Name: devices[0].Name}, AllocationPolicy: "Disabled", ReclaimPolicy: "Retain"}}) - }, true}, - } { - t.Run(test.name, func(t *testing.T) { - err := test.write() - if test.blocked { - if err == nil || !strings.Contains(err.Error(), "failed calling webhook") { - t.Fatalf("expected fail-closed transport error, got %v", err) - } - } else if err != nil { - t.Fatalf("unrelated operation depends on unavailable webhook: %v", err) - } - }) - } - for _, test := range []struct { - name string - extra map[string][]string - }{ - {"missing context", nil}, - {"nested organization context", map[string][]string{iam.ParentKindExtraKey: {"Organization"}, iam.ParentAPIGroupExtraKey: {"resourcemanager.miloapis.com"}, iam.ParentNameExtraKey: {"unrelated-consumer"}}}, - {"nested user context", map[string][]string{iam.ParentKindExtraKey: {"User"}, iam.ParentAPIGroupExtraKey: {"iam.miloapis.com"}, iam.ParentNameExtraKey: {"unrelated-consumer"}}}, - {"ambiguous context", map[string][]string{iam.ParentKindExtraKey: {"Project"}, iam.ParentAPIGroupExtraKey: {"resourcemanager.miloapis.com"}, iam.ParentNameExtraKey: {"unrelated-consumer", "datum-cloud"}}}, - {"empty context", map[string][]string{iam.ParentKindExtraKey: {"Project"}, iam.ParentAPIGroupExtraKey: {"resourcemanager.miloapis.com"}, iam.ParentNameExtraKey: {""}}}, - } { - t.Run(test.name, func(t *testing.T) { - unprovenConfig := rest.CopyConfig(actorConfig) - unprovenConfig.Impersonate.Extra = test.extra - unproven, err := client.New(unprovenConfig, client.Options{Scheme: scheme}) - if err != nil { - t.Fatal(err) - } - device := devices[0].DeepCopyObject().(*inventory.Device) - device.Name, device.UID, device.ResourceVersion, device.ManagedFields = "unproven-context", "", "", nil - for _, err := range []error{unproven.Create(ctx, device), unproven.Delete(ctx, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "default"}}, client.DryRunAll)} { - if err == nil || !strings.Contains(err.Error(), "failed calling webhook") { - t.Fatalf("ambiguous routing context bypassed fail-closed transport: %v", err) - } - } - }) - } -} diff --git a/internal/registration/admission_regression_test.go b/internal/registration/admission_regression_test.go deleted file mode 100644 index 763d9732..00000000 --- a/internal/registration/admission_regression_test.go +++ /dev/null @@ -1,75 +0,0 @@ -package registration - -import ( - "context" - "encoding/json" - "testing" - - admissionv1 "k8s.io/api/admission/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -func TestIdenticalAdmissionObjects(t *testing.T) { - for _, test := range []struct { - name, old, current string - identical bool - }{ - {"key order and whitespace", `{"metadata":{"resourceVersion":"1"},"spec":{}}`, ` {"spec":{},"metadata":{"resourceVersion":"1"}} `, true}, - {"unknown field", `{"future":1}`, `{"future":2}`, false}, - {"large exact integers", `{"future":9007199254740992}`, `{"future":9007199254740993}`, false}, - {"managed fields", `{"metadata":{"managedFields":[]}}`, `{"metadata":{"managedFields":[{"manager":"new"}]}}`, false}, - {"status", `{"status":{}}`, `{"status":{"ready":true}}`, false}, - {"null versus absent", `{}`, `{"future":null}`, false}, - {"array order", `{"future":[1,2]}`, `{"future":[2,1]}`, false}, - {"null objects", `null`, `null`, false}, - {"malformed", `{`, `{`, false}, - {"trailing document", `{} {}`, `{}`, false}, - } { - t.Run(test.name, func(t *testing.T) { - if identicalObjects([]byte(test.old), []byte(test.current)) != test.identical { - t.Fatal("unexpected whole-object comparison") - } - }) - } -} - -func TestNoopCannotClearPendingRealUpdateFence(t *testing.T) { - handler, device := fixture(t) - ctx := context.Background() - registration := registrationRequest(t, device, "record") - update := registration - update.Resource = metav1.GroupVersionResource{Group: "fleet.datumapis.com", Version: "v1alpha1", Resource: "devices"} - update.Operation = admissionv1.Update - update.OldObject.Raw, _ = json.Marshal(device) - changed := device.DeepCopyObject() - raw, _ := json.Marshal(changed) - var object map[string]any - _ = json.Unmarshal(raw, &object) - object["futureField"] = "changed" - update.Object.Raw, _ = json.Marshal(object) - if !handler.Handle(ctx, update).Allowed { - t.Fatal("real update rejected") - } - update.Object.Raw = update.OldObject.Raw - if !handler.Handle(ctx, update).Allowed { - t.Fatal("no-op rejected") - } - if handler.Handle(ctx, registration).Allowed { - t.Fatal("no-op cleared the pending real-update reservation") - } -} - -func TestLifetimeCollectionDeletionDenied(t *testing.T) { - for _, resource := range []metav1.GroupVersionResource{{Version: "v1", Resource: "namespaces"}, {Group: "resourcemanager.miloapis.com", Version: "v1alpha1", Resource: "projects"}} { - t.Run(resource.Resource, func(t *testing.T) { - handler, device := fixture(t) - request := registrationRequest(t, device, "unused") - request.Operation = admissionv1.Delete - request.Name = "" - request.Resource = resource - if handler.Handle(context.Background(), request).Allowed { - t.Fatal("unnamed deletion cannot exclude a protected lifetime") - } - }) - } -} diff --git a/internal/registration/admission_test.go b/internal/registration/admission_test.go index 14ac05b5..cfde8b47 100644 --- a/internal/registration/admission_test.go +++ b/internal/registration/admission_test.go @@ -4,9 +4,8 @@ import ( "context" "encoding/json" "errors" - "fmt" + "strings" "sync" - "sync/atomic" "testing" inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" @@ -24,7 +23,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/webhook/admission" ) -func fixture(t *testing.T) (*Handler, *inventory.Device) { +func testScheme(t *testing.T) *runtime.Scheme { t.Helper() scheme := runtime.NewScheme() for _, add := range []func(*runtime.Scheme) error{corev1.AddToScheme, metal.AddToScheme, inventory.AddToScheme} { @@ -32,18 +31,21 @@ func fixture(t *testing.T) (*Handler, *inventory.Device) { t.Fatal(err) } } + return scheme +} + +func fixture(t *testing.T) (*Handler, *inventory.Device) { + t.Helper() device := &inventory.Device{ObjectMeta: metav1.ObjectMeta{Name: "server", Namespace: "default", UID: "device-1", ResourceVersion: "1"}, Spec: inventory.DeviceSpec{Identity: inventory.DeviceIdentity{Serial: "SERIAL-1", SystemUUID: "11111111-1111-1111-1111-111111111111", Model: "test"}}} - namespace := &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "default", UID: "namespace-1"}} - api := fake.NewClientBuilder().WithScheme(scheme).WithObjects(device, namespace).Build() - encoded, _ := json.Marshal(Ledger{Authority: "milo", Projects: []string{"provider"}}) - private := fake.NewClientBuilder().WithScheme(scheme).WithObjects(&corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: LedgerName, Namespace: "private", UID: "ledger-1"}, Data: map[string][]byte{"ledger.json": encoded}}).Build() - return &Handler{Store: Store{Client: private, Namespace: "private", Authority: "milo", Projects: []string{"provider"}, AllowInactiveForTests: true}, Resolve: func(context.Context, string) (Project, error) { + api := fake.NewClientBuilder().WithScheme(testScheme(t)).WithObjects(device).Build() + return &Handler{Projects: []string{"provider"}, Resolve: func(context.Context, string) (Project, error) { return Project{Identity: controller.ProjectIdentity{AuthorityID: "milo", RouteName: "provider", UID: "project-1"}, Client: api}, nil }, Authorize: func(context.Context, Project, authenticationv1.UserInfo, string, string, string) error { return nil }}, device } -func registrationRequest(t *testing.T, device *inventory.Device, name string) admission.Request { +func registrationRequest(t *testing.T, device *inventory.Device) admission.Request { t.Helper() + name := CapacityName(device.UID) capacity := metal.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: "default", UID: types.UID("capacity-" + name), Annotations: map[string]string{DeviceUIDAnnotation: string(device.UID), DeviceVersionAnnotation: device.ResourceVersion, OperationAnnotation: "client-" + name}}, Spec: metal.MachineCapacitySpec{DeviceRef: metal.LocalReference{Name: device.Name}, AllocationPolicy: "Disabled", ReclaimPolicy: "Retain"}} raw, err := json.Marshal(capacity) if err != nil { @@ -52,47 +54,51 @@ func registrationRequest(t *testing.T, device *inventory.Device, name string) ad return admission.Request{AdmissionRequest: admissionv1.AdmissionRequest{UID: types.UID("request-" + name), Name: name, Namespace: "default", Operation: admissionv1.Create, Resource: metav1.GroupVersionResource{Group: "metal.datumapis.com", Version: "v1alpha1", Resource: "machinecapacities"}, UserInfo: authenticationv1.UserInfo{Username: "operator", UID: "actor-1", Extra: map[string]authenticationv1.ExtraValue{iam.ParentKindExtraKey: {"Project"}, iam.ParentAPIGroupExtraKey: {"resourcemanager.miloapis.com"}, iam.ParentNameExtraKey: {"provider"}}}, Object: runtime.RawExtension{Raw: raw}}} } -func TestConcurrentRegistrationReservesOnce(t *testing.T) { - handler, device := fixture(t) - var allowed atomic.Int32 - var workers sync.WaitGroup - for index := 0; index < 20; index++ { - request := registrationRequest(t, device, fmt.Sprintf("capacity-%d", index)) - workers.Add(1) - go func() { - defer workers.Done() - if handler.Handle(context.Background(), request).Allowed { - allowed.Add(1) - } - }() - } - workers.Wait() - if allowed.Load() != 1 { - t.Fatalf("allowed %d registrations", allowed.Load()) - } - _, ledger, err := handler.Store.Read(context.Background()) - if err != nil || len(ledger.Entries) != 1 { - t.Fatalf("ledger: %+v %v", ledger, err) +func changeCapacity(request *admission.Request, mutate func(*metal.MachineCapacity)) { + var capacity metal.MachineCapacity + _ = json.Unmarshal(request.Object.Raw, &capacity) + mutate(&capacity) + request.Name = capacity.Name + request.Object.Raw, _ = json.Marshal(capacity) +} + +func providerClient(t *testing.T, handler *Handler) client.Client { + t.Helper() + project, err := handler.Resolve(context.Background(), "provider") + if err != nil { + t.Fatal(err) } - entry := ledger.Entries[0] - if entry.Actor.UID != "actor-1" || entry.DeviceUID != device.UID || entry.DeviceVersion != device.ResourceVersion || entry.ProjectUID != "project-1" || entry.NamespaceUID != "namespace-1" || entry.Outcome != "Unknown" { - t.Fatalf("authority not retained: %+v", entry) + return project.Client +} + +func TestRegistrationAllowsLiveEligibleDeviceWithoutEffects(t *testing.T) { + handler, device := fixture(t) + request := registrationRequest(t, device) + dryRun := true + request.DryRun = &dryRun + if response := handler.Handle(context.Background(), request); !response.Allowed { + t.Fatalf("eligible registration denied: %s", response.Result.Message) } - project, _ := handler.Resolve(context.Background(), "provider") var capacities metal.MachineCapacityList - if err := project.Client.List(context.Background(), &capacities); err != nil || len(capacities.Items) != 0 { - t.Fatal("admission caused public effects") + if err := providerClient(t, handler).List(context.Background(), &capacities); err != nil || len(capacities.Items) != 0 { + t.Fatal("admission caused public effects", err) } } func TestRegistrationNegatives(t *testing.T) { tests := map[string]func(*Handler, *inventory.Device, *admission.Request){ "stale UID": func(_ *Handler, _ *inventory.Device, request *admission.Request) { - changeCapacity(request, func(capacity *metal.MachineCapacity) { capacity.Annotations[DeviceUIDAnnotation] = "old" }) + changeCapacity(request, func(capacity *metal.MachineCapacity) { + capacity.Annotations[DeviceUIDAnnotation] = "old" + capacity.Name = CapacityName("old") + }) }, "stale RV": func(_ *Handler, _ *inventory.Device, request *admission.Request) { changeCapacity(request, func(capacity *metal.MachineCapacity) { capacity.Annotations[DeviceVersionAnnotation] = "old" }) }, + "authored name": func(_ *Handler, _ *inventory.Device, request *admission.Request) { + changeCapacity(request, func(capacity *metal.MachineCapacity) { capacity.Name = "authored-name" }) + }, "enabled": func(_ *Handler, _ *inventory.Device, request *admission.Request) { changeCapacity(request, func(capacity *metal.MachineCapacity) { capacity.Spec.AllocationPolicy = "Enabled" }) }, @@ -101,6 +107,11 @@ func TestRegistrationNegatives(t *testing.T) { capacity.Spec.CleaningPolicyRef.Name = "synthetic-tenant-reuse-v1" }) }, + "owner reference": func(_ *Handler, device *inventory.Device, request *admission.Request) { + changeCapacity(request, func(capacity *metal.MachineCapacity) { + capacity.OwnerReferences = []metav1.OwnerReference{{APIVersion: inventory.GroupVersion.String(), Kind: "Device", Name: device.Name, UID: device.UID}} + }) + }, "no baseline": func(_ *Handler, _ *inventory.Device, request *admission.Request) { changeCapacity(request, func(capacity *metal.MachineCapacity) { capacity.Annotations = nil }) }, @@ -110,28 +121,52 @@ func TestRegistrationNegatives(t *testing.T) { "direct delete": func(_ *Handler, _ *inventory.Device, request *admission.Request) { request.Operation = admissionv1.Delete }, - "status": func(_ *Handler, _ *inventory.Device, request *admission.Request) { request.SubResource = "status" }, + "status": func(_ *Handler, _ *inventory.Device, request *admission.Request) { request.SubResource = "status" }, + "other resource": func(_ *Handler, _ *inventory.Device, request *admission.Request) { + request.Resource.Resource = "devices" + }, "missing project": func(_ *Handler, _ *inventory.Device, request *admission.Request) { request.UserInfo.Extra = nil }, + "missing actor": func(_ *Handler, _ *inventory.Device, request *admission.Request) { request.UserInfo.UID = "" }, + "organization context": func(_ *Handler, _ *inventory.Device, request *admission.Request) { + request.UserInfo.Extra[iam.ParentKindExtraKey] = authenticationv1.ExtraValue{"Organization"} + }, "wrong project": func(_ *Handler, _ *inventory.Device, request *admission.Request) { request.UserInfo.Extra[iam.ParentNameExtraKey] = authenticationv1.ExtraValue{"consumer"} }, "namespace": func(_ *Handler, _ *inventory.Device, request *admission.Request) { request.Namespace = "other" }, - "permission revoked": func(handler *Handler, _ *inventory.Device, _ *admission.Request) { - handler.Authorize = func(context.Context, Project, authenticationv1.UserInfo, string, string, string) error { - return errors.New("denied") + "project lifetime unavailable": func(handler *Handler, _ *inventory.Device, _ *admission.Request) { + handler.Resolve = func(context.Context, string) (Project, error) { return Project{}, errors.New("deleting") } + }, + "capacity permission revoked": func(handler *Handler, _ *inventory.Device, _ *admission.Request) { + handler.Authorize = func(_ context.Context, _ Project, _ authenticationv1.UserInfo, _, resource, _ string) error { + if resource == "machinecapacities" { + return errors.New("denied") + } + return nil + } + }, + "device permission revoked": func(handler *Handler, _ *inventory.Device, _ *admission.Request) { + handler.Authorize = func(_ context.Context, _ Project, _ authenticationv1.UserInfo, _, resource, _ string) error { + if resource == "devices" { + return errors.New("denied") + } + return nil + } + }, + "missing device": func(handler *Handler, device *inventory.Device, _ *admission.Request) { + if err := providerClient(t, handler).Delete(context.Background(), device); err != nil { + t.Fatal(err) } }, "partial identity": func(handler *Handler, device *inventory.Device, request *admission.Request) { - project, _ := handler.Resolve(context.Background(), "provider") device.Spec.Identity.SystemUUID = "" - if err := project.Client.Update(context.Background(), device); err != nil { + if err := providerClient(t, handler).Update(context.Background(), device); err != nil { t.Fatal(err) } - *request = registrationRequest(t, device, request.Name) + *request = registrationRequest(t, device) }, "unresolved legacy": func(handler *Handler, _ *inventory.Device, _ *admission.Request) { - project, _ := handler.Resolve(context.Background(), "provider") - if err := project.Client.Create(context.Background(), &metal.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: "legacy", Namespace: "default"}, Spec: metal.MachineCapacitySpec{DeviceRef: metal.LocalReference{Name: "missing"}, AllocationPolicy: "Enabled"}}); err != nil { + if err := providerClient(t, handler).Create(context.Background(), &metal.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: "legacy", Namespace: "default"}, Spec: metal.MachineCapacitySpec{DeviceRef: metal.LocalReference{Name: "missing"}, AllocationPolicy: "Enabled"}}); err != nil { t.Fatal(err) } }, @@ -139,144 +174,83 @@ func TestRegistrationNegatives(t *testing.T) { for name, mutate := range tests { t.Run(name, func(t *testing.T) { handler, device := fixture(t) - request := registrationRequest(t, device, "record") + request := registrationRequest(t, device) mutate(handler, device, &request) if response := handler.Handle(context.Background(), request); response.Allowed { t.Fatal("unsafe registration allowed") } - _, ledger, err := handler.Store.Read(context.Background()) - if err != nil || len(ledger.Entries) != 0 { - t.Fatal("negative modified registration ledger", err) - } }) } } -func changeCapacity(request *admission.Request, mutate func(*metal.MachineCapacity)) { - var capacity metal.MachineCapacity - _ = json.Unmarshal(request.Object.Raw, &capacity) - mutate(&capacity) - request.Object.Raw, _ = json.Marshal(capacity) -} - -func TestUnknownRecoveryDoesNotAdoptCopiedAnnotation(t *testing.T) { +func TestMissingDeviceIsNamed(t *testing.T) { handler, device := fixture(t) - request := registrationRequest(t, device, "record") - if !handler.Handle(context.Background(), request).Allowed { - t.Fatal("registration denied") - } - restarted := *handler - if err := restarted.Recover(context.Background()); err != nil { + if err := providerClient(t, handler).Delete(context.Background(), device); err != nil { t.Fatal(err) } - if handler.Handle(context.Background(), registrationRequest(t, device, "different-name")).Allowed { - t.Fatal("unknown reservation was released") + response := handler.Handle(context.Background(), registrationRequest(t, device)) + if response.Allowed || !strings.Contains(response.Result.Message, "does not exist") { + t.Fatalf("missing Device not reported: %+v", response.Result) } - var recreated metal.MachineCapacity - _ = json.Unmarshal(request.Object.Raw, &recreated) - recreated.UID = "recreated-with-copied-annotations" - project, _ := handler.Resolve(context.Background(), "provider") - if err := project.Client.Create(context.Background(), &recreated); err != nil { +} + +func TestUnauthorizedCallerCannotProbeDeviceExistence(t *testing.T) { + handler, device := fixture(t) + if err := providerClient(t, handler).Delete(context.Background(), device); err != nil { t.Fatal(err) } - if err := restarted.Recover(context.Background()); err != nil { - t.Fatal(err) + handler.Authorize = func(context.Context, Project, authenticationv1.UserInfo, string, string, string) error { + return errors.New("current get permission on devices is required") } - _, ledger, _ := handler.Store.Read(context.Background()) - if ledger.Entries[0].Outcome != "IncarnationConflict" { - t.Fatal("recreated capacity was adopted") + response := handler.Handle(context.Background(), registrationRequest(t, device)) + if response.Allowed || strings.Contains(response.Result.Message, "does not exist") { + t.Fatalf("unauthorized caller learned Device existence: %+v", response.Result) } } -func TestSharedAliasesAndProjectScope(t *testing.T) { - for _, alias := range []string{"serial", "uuid"} { +func TestSharedAliasesAcrossLiveDevices(t *testing.T) { + for _, alias := range []string{"serial", "uuid", "normalized serial", "provider"} { t.Run(alias, func(t *testing.T) { handler, device := fixture(t) - project, _ := handler.Resolve(context.Background(), "provider") + api := providerClient(t, handler) duplicate := device.DeepCopyObject().(*inventory.Device) duplicate.Name, duplicate.UID, duplicate.ResourceVersion = "alias", "alias-uid", "" - if alias == "serial" { - duplicate.Spec.Identity.SystemUUID = "22222222-2222-2222-2222-222222222222" - } else { - duplicate.Spec.Identity.Serial = "other" + duplicate.Spec.Identity.Serial = "other" + duplicate.Spec.Identity.SystemUUID = "22222222-2222-2222-2222-222222222222" + switch alias { + case "serial": + duplicate.Spec.Identity.Serial = device.Spec.Identity.Serial + case "normalized serial": + duplicate.Spec.Identity.Serial = " serial-1 " + case "uuid": + duplicate.Spec.Identity.SystemUUID = device.Spec.Identity.SystemUUID + case "provider": + device.Spec.ProviderHostRef = &inventory.ExternalReference{System: "Provider", Type: "server", ID: "shared-asset"} + duplicate.Spec.ProviderHostRef = &inventory.ExternalReference{System: "provider", Type: " SERVER", ID: "shared-asset"} + if err := api.Update(context.Background(), device); err != nil { + t.Fatal(err) + } } - if err := project.Client.Create(context.Background(), duplicate); err != nil { + if err := api.Create(context.Background(), duplicate); err != nil { t.Fatal(err) } - if handler.Handle(context.Background(), registrationRequest(t, device, "record")).Allowed { - t.Fatal("ambiguous alias accepted") - } - }) - } -} - -func TestDeviceDeleteRaceRetainsFence(t *testing.T) { - handler, device := fixture(t) - request := registrationRequest(t, device, "record") - deletion := request - deletion.Resource = metav1.GroupVersionResource{Group: "fleet.datumapis.com", Version: "v1alpha1", Resource: "devices"} - deletion.Operation = admissionv1.Delete - deletion.OldObject.Raw, _ = json.Marshal(device) - if !handler.Handle(context.Background(), deletion).Allowed { - t.Fatal("unbound deletion denied") - } - if handler.Handle(context.Background(), request).Allowed { - t.Fatal("registration raced a pending Device deletion") - } - other, selected := fixture(t) - if !other.Handle(context.Background(), registrationRequest(t, selected, "record")).Allowed { - t.Fatal("registration denied") - } - if other.Handle(context.Background(), deletion).Allowed { - t.Fatal("bound Device deletion allowed") - } -} - -func TestProjectLifetimeRecheck(t *testing.T) { - handler, device := fixture(t) - resolve := handler.Resolve - var calls int - handler.Resolve = func(ctx context.Context, name string) (Project, error) { - project, err := resolve(ctx, name) - calls++ - if calls > 1 { - project.Identity.UID = "recreated" - } - return project, err - } - if handler.Handle(context.Background(), registrationRequest(t, device, "record")).Allowed { - t.Fatal("project recreation accepted") - } -} - -func TestNamespaceRecreationAndPermissionRevocationDuringAdmission(t *testing.T) { - for _, mode := range []string{"namespace", "permission"} { - t.Run(mode, func(t *testing.T) { - handler, device := fixture(t) - var calls int - handler.Authorize = func(ctx context.Context, project Project, _ authenticationv1.UserInfo, _, _, _ string) error { - calls++ - if calls == 3 { - if mode == "permission" { - return errors.New("revoked") - } - var namespace corev1.Namespace - if err := project.Client.Get(ctx, client.ObjectKey{Name: "default"}, &namespace); err != nil { - return err - } - if err := project.Client.Delete(ctx, &namespace); err != nil { - return err - } - return project.Client.Create(ctx, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "default", UID: "recreated"}}) + for _, selected := range []*inventory.Device{device, duplicate} { + if err := api.Get(context.Background(), client.ObjectKeyFromObject(selected), selected); err != nil { + t.Fatal(err) } - return nil + response := handler.Handle(context.Background(), registrationRequest(t, selected)) + if response.Allowed || !strings.Contains(response.Result.Message, "shares recorded hardware identity") { + t.Fatalf("duplicate identity accepted for %s: %+v", selected.Name, response.Result) + } + } + if err := api.Delete(context.Background(), duplicate); err != nil { + t.Fatal(err) } - response := handler.Handle(context.Background(), registrationRequest(t, device, "record")) - if mode == "permission" && response.Allowed { - t.Fatal("revocation accepted") + if err := api.Get(context.Background(), client.ObjectKeyFromObject(device), device); err != nil { + t.Fatal(err) } - if mode == "namespace" && response.Allowed { - t.Fatal("namespace recreation admitted") + if response := handler.Handle(context.Background(), registrationRequest(t, device)); !response.Allowed { + t.Fatalf("resolved duplicate still blocks registration: %s", response.Result.Message) } }) } @@ -303,30 +277,29 @@ func TestCrossProjectAmbiguityAndSharedProviderAlias(t *testing.T) { t.Fatal(err) } } - second := fake.NewClientBuilder().WithScheme(first.Client.Scheme()).WithObjects(other, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "default", UID: "namespace-2"}}).Build() - secret, ledger, _ := handler.Store.Read(context.Background()) - ledger.Projects = []string{"provider", "second"} - if err := handler.Store.Write(context.Background(), secret, ledger); err != nil { - t.Fatal(err) - } - handler.Store.Projects = ledger.Projects + second := fake.NewClientBuilder().WithScheme(first.Client.Scheme()).WithObjects(other).Build() + handler.Projects = []string{"provider", "second"} handler.Resolve = func(_ context.Context, name string) (Project, error) { if name == "provider" { return first, nil } return Project{Identity: controller.ProjectIdentity{AuthorityID: "milo", RouteName: "second", UID: "project-2"}, Client: second}, nil } - firstRequest := registrationRequest(t, device, "one") - secondRequest := registrationRequest(t, other, "two") + firstRequest := registrationRequest(t, device) + secondRequest := registrationRequest(t, other) secondRequest.UserInfo.Extra[iam.ParentNameExtraKey] = authenticationv1.ExtraValue{"second"} var workers sync.WaitGroup for _, request := range []admission.Request{firstRequest, secondRequest} { workers.Add(1) go func() { defer workers.Done() - if handler.Handle(context.Background(), request).Allowed { + response := handler.Handle(context.Background(), request) + if response.Allowed { t.Error("cross-project alias ambiguity accepted") } + if strings.Contains(response.Result.Message, "second/") || strings.Contains(response.Result.Message, "default/server") { + t.Errorf("conflict in another provider project was named: %s", response.Result.Message) + } }() } workers.Wait() @@ -334,99 +307,77 @@ func TestCrossProjectAmbiguityAndSharedProviderAlias(t *testing.T) { } } -type timeoutAfterWrite struct{ client.Client } - -func (api timeoutAfterWrite) Update(ctx context.Context, object client.Object, options ...client.UpdateOption) error { - if err := api.Client.Update(ctx, object, options...); err != nil { - return err +func TestDeviceAlreadyBackingCapacity(t *testing.T) { + for _, binding := range []string{"device reference", "device UID annotation"} { + t.Run(binding, func(t *testing.T) { + handler, device := fixture(t) + existing := &metal.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: "earlier-record", Namespace: "default"}, Spec: metal.MachineCapacitySpec{DeviceRef: metal.LocalReference{Name: device.Name}, AllocationPolicy: "Disabled", ReclaimPolicy: "Retain"}} + if binding == "device UID annotation" { + // A capacity whose Device was renamed away still binds the UID. + other := device.DeepCopyObject().(*inventory.Device) + other.Name, other.UID, other.ResourceVersion = "renamed", "device-renamed", "" + other.Spec.Identity.Serial, other.Spec.Identity.SystemUUID = "renamed-serial", "33333333-3333-3333-3333-333333333333" + if err := providerClient(t, handler).Create(context.Background(), other); err != nil { + t.Fatal(err) + } + existing.Spec.DeviceRef.Name = other.Name + existing.Annotations = map[string]string{DeviceUIDAnnotation: string(device.UID)} + } + if err := providerClient(t, handler).Create(context.Background(), existing); err != nil { + t.Fatal(err) + } + response := handler.Handle(context.Background(), registrationRequest(t, device)) + if response.Allowed || !strings.Contains(response.Result.Message, "already backs capacity earlier-record") { + t.Fatalf("second capacity for one Device accepted: %+v", response.Result) + } + }) } - return errors.New("timeout after commit") } -func TestLedgerWriteTimeoutRetainsReservationAcrossRestart(t *testing.T) { +func TestReplacementDeviceUnderSameNameCannotRegister(t *testing.T) { handler, device := fixture(t) - private := handler.Store.Client - handler.Store.Client = timeoutAfterWrite{private} - if handler.Handle(context.Background(), registrationRequest(t, device, "record")).Allowed { - t.Fatal("timeout became success") - } - handler.Store.Client = private - restarted := *handler - if err := restarted.Recover(context.Background()); err != nil { + api := providerClient(t, handler) + registered := &metal.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: CapacityName(device.UID), Namespace: "default", Annotations: map[string]string{DeviceUIDAnnotation: string(device.UID)}}, Spec: metal.MachineCapacitySpec{DeviceRef: metal.LocalReference{Name: device.Name}, AllocationPolicy: "Disabled", ReclaimPolicy: "Retain"}} + if err := api.Create(context.Background(), registered); err != nil { t.Fatal(err) } - if restarted.Handle(context.Background(), registrationRequest(t, device, "new-name")).Allowed { - t.Fatal("unknown reservation was reused") - } - _, ledger, _ := restarted.Store.Read(context.Background()) - if len(ledger.Entries) != 1 || ledger.Entries[0].Outcome != "Unknown" { - t.Fatal("unknown reservation lost") - } -} - -func TestDeviceCreatedThroughAdmissionCanRegister(t *testing.T) { - handler, device := fixture(t) - request := registrationRequest(t, device, "record") - creation := request - creation.Resource = metav1.GroupVersionResource{Group: "fleet.datumapis.com", Resource: "devices", Version: "v1alpha1"} - creation.Object.Raw, _ = json.Marshal(device) - if !handler.Handle(context.Background(), creation).Allowed { - t.Fatal("Device create admission denied") - } - if !handler.Handle(context.Background(), request).Allowed { - t.Fatal("own Device creation fence prevented registration") - } -} - -func TestRootProjectDeletionAndDeviceNameReuseAreFenced(t *testing.T) { - handler, device := fixture(t) - request := registrationRequest(t, device, "record") - if !handler.Handle(context.Background(), request).Allowed { - t.Fatal("registration denied") - } - deletion := request - deletion.Name = "provider" - deletion.Operation = admissionv1.Delete - deletion.Resource = metav1.GroupVersionResource{Group: "resourcemanager.miloapis.com", Version: "v1alpha1", Resource: "projects"} - deletion.UserInfo.Extra = nil - if handler.Handle(context.Background(), deletion).Allowed { - t.Fatal("root Project deletion bypass") + if err := api.Delete(context.Background(), device); err != nil { + t.Fatal(err) } replacement := device.DeepCopyObject().(*inventory.Device) - replacement.UID = "recreated" - replacement.Spec.Identity.Serial = "new-serial" - replacement.Spec.Identity.SystemUUID = "22222222-2222-2222-2222-222222222222" - creation := registrationRequest(t, device, "record") - creation.Resource = metav1.GroupVersionResource{Group: "fleet.datumapis.com", Version: "v1alpha1", Resource: "devices"} - creation.Object.Raw, _ = json.Marshal(replacement) - if handler.Handle(context.Background(), creation).Allowed { - t.Fatal("registered Device name was reused by a new incarnation") + replacement.UID, replacement.ResourceVersion = "device-replacement", "" + replacement.Spec.Identity.Serial, replacement.Spec.Identity.SystemUUID = "replacement-serial", "44444444-4444-4444-4444-444444444444" + if err := api.Create(context.Background(), replacement); err != nil { + t.Fatal(err) + } + if handler.Handle(context.Background(), registrationRequest(t, replacement)).Allowed { + t.Fatal("replacement Device adopted capacity that names its predecessor") } } func TestNonConflictingLegacyCapacityAndAllocationRemainUntouched(t *testing.T) { handler, device := fixture(t) ctx := context.Background() - project, _ := handler.Resolve(ctx, "provider") + api := providerClient(t, handler) legacyDevice := device.DeepCopyObject().(*inventory.Device) legacyDevice.Name, legacyDevice.UID, legacyDevice.ResourceVersion = "legacy-device", "legacy-device-uid", "" legacyDevice.Spec.Identity.Serial, legacyDevice.Spec.Identity.SystemUUID = "legacy-serial", "22222222-2222-2222-2222-222222222222" legacy := &metal.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: "legacy", Namespace: "default", UID: "legacy-uid"}, Spec: metal.MachineCapacitySpec{DeviceRef: metal.LocalReference{Name: legacyDevice.Name}, AllocationPolicy: "Enabled", ReclaimPolicy: "Retain", CleaningPolicyRef: metal.LocalReference{Name: "synthetic-tenant-reuse-v1"}}, Status: metal.MachineCapacityStatus{Conditions: []metav1.Condition{{Type: "Available", Status: metav1.ConditionFalse, Reason: "Occupied"}}}} allocation := &metal.MachineAllocation{ObjectMeta: metav1.ObjectMeta{Name: "occupied", Namespace: "default", UID: "allocation-uid"}} for _, object := range []client.Object{legacyDevice, legacy, allocation} { - if err := project.Client.Create(ctx, object); err != nil { + if err := api.Create(ctx, object); err != nil { t.Fatal(err) } } beforeCapacity, _ := json.Marshal(legacy) beforeAllocation, _ := json.Marshal(allocation) - if !handler.Handle(ctx, registrationRequest(t, device, "record")).Allowed { - t.Fatal("non-conflicting legacy capacity blocked registration") + if response := handler.Handle(ctx, registrationRequest(t, device)); !response.Allowed { + t.Fatalf("non-conflicting legacy capacity blocked registration: %s", response.Result.Message) } - if err := project.Client.Get(ctx, client.ObjectKeyFromObject(legacy), legacy); err != nil { + if err := api.Get(ctx, client.ObjectKeyFromObject(legacy), legacy); err != nil { t.Fatal(err) } - if err := project.Client.Get(ctx, client.ObjectKeyFromObject(allocation), allocation); err != nil { + if err := api.Get(ctx, client.ObjectKeyFromObject(allocation), allocation); err != nil { t.Fatal(err) } afterCapacity, _ := json.Marshal(legacy) @@ -434,69 +385,17 @@ func TestNonConflictingLegacyCapacityAndAllocationRemainUntouched(t *testing.T) if string(beforeCapacity) != string(afterCapacity) || string(beforeAllocation) != string(afterAllocation) { t.Fatal("registration modified legacy state") } - if handler.Handle(ctx, registrationRequest(t, legacyDevice, "conflicting")).Allowed { - t.Fatal("occupied legacy asset was registered") - } -} - -func TestRecoveryReadFailureBecomesUnknownWithoutReleasing(t *testing.T) { - handler, device := fixture(t) - ctx := context.Background() - request := registrationRequest(t, device, "record") - if !handler.Handle(ctx, request).Allowed { - t.Fatal("registration denied") - } - var capacity metal.MachineCapacity - if err := json.Unmarshal(request.Object.Raw, &capacity); err != nil { + if err := api.Get(ctx, client.ObjectKeyFromObject(legacyDevice), legacyDevice); err != nil { t.Fatal(err) } - project, _ := handler.Resolve(ctx, "provider") - if err := project.Client.Create(ctx, &capacity); err != nil { - t.Fatal(err) - } - if err := handler.Recover(ctx); err != nil { - t.Fatal(err) - } - _, before, _ := handler.Store.Read(ctx) - if before.Entries[0].Outcome != "Recorded" { - t.Fatal("exact completion not recovered") - } - handler.Resolve = func(context.Context, string) (Project, error) { - return Project{}, errors.New("read authority unavailable") - } - if err := handler.Recover(ctx); err == nil { - t.Fatal("read failure became success") - } - _, after, _ := handler.Store.Read(ctx) - if len(after.Entries) != 1 || after.Entries[0].Outcome != "Unknown" || after.Entries[0].CapacityUID != before.Entries[0].CapacityUID { - t.Fatal("uncertain recovery lost its reservation or retained a positive observation") + if handler.Handle(ctx, registrationRequest(t, legacyDevice)).Allowed { + t.Fatal("occupied legacy asset was registered") } } -func TestPendingDeviceUpdateCannotRaceSelectedVersion(t *testing.T) { - handler, device := fixture(t) - ctx := context.Background() - registration := registrationRequest(t, device, "record") - update := registration - update.Resource = metav1.GroupVersionResource{Group: "fleet.datumapis.com", Version: "v1alpha1", Resource: "devices"} - update.Operation = admissionv1.Update - update.OldObject.Raw, _ = json.Marshal(device) - device.Labels = map[string]string{"display": "changed"} - update.Object.Raw, _ = json.Marshal(device) - if !handler.Handle(ctx, update).Allowed { - t.Fatal("unbound Device update rejected") - } - if handler.Handle(ctx, registration).Allowed { - t.Fatal("registration raced an admitted but uncompleted Device update") - } - project, _ := handler.Resolve(ctx, "provider") - if err := project.Client.Update(ctx, device); err != nil { - t.Fatal(err) - } - if handler.Handle(ctx, registration).Allowed { - t.Fatal("stale UI selection silently refreshed") - } - if !handler.Handle(ctx, registrationRequest(t, device, "explicit-new-selection")).Allowed { - t.Fatal("explicit new persisted baseline rejected") +func TestCapacityNameIsDerivedFromDeviceUID(t *testing.T) { + name := CapacityName("0b1f0a52-6f0e-4f43-9c1e-4c8b7f3d2a10") + if name != "device-0b1f0a52-6f0e-4f43-9c1e-4c8b7f3d2a10" || len(name) > 63 { + t.Fatalf("unexpected capacity name %q", name) } } diff --git a/internal/registration/bounded_fences_test.go b/internal/registration/bounded_fences_test.go deleted file mode 100644 index 8121d7f0..00000000 --- a/internal/registration/bounded_fences_test.go +++ /dev/null @@ -1,200 +0,0 @@ -package registration - -import ( - "context" - "encoding/json" - "strings" - "testing" - - inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" - admissionv1 "k8s.io/api/admission/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/webhook/admission" -) - -func deviceUpdate(t *testing.T, device *inventory.Device) admission.Request { - t.Helper() - request := registrationRequest(t, device, "unused") - request.Resource = metav1.GroupVersionResource{Group: "fleet.datumapis.com", Version: "v1alpha1", Resource: "devices"} - request.Name = device.Name - request.Operation = admissionv1.Update - request.OldObject.Raw, _ = json.Marshal(device) - changed := device.DeepCopyObject().(*inventory.Device) - changed.Labels = map[string]string{"observation": "changed"} - request.Object.Raw, _ = json.Marshal(changed) - return request -} - -func TestCoalescingRetainsPendingAndUnknownVersions(t *testing.T) { - ctx := context.Background() - handler, device := fixture(t) - project, _ := handler.Resolve(ctx, "provider") - oldRequest := deviceUpdate(t, device) - for attempt := 0; attempt < 10; attempt++ { - if response := handler.Handle(ctx, oldRequest); !response.Allowed { - t.Fatal(response.Result) - } - } - if handler.Handle(ctx, registrationRequest(t, device, "pending-first")).Allowed { - t.Fatal("pending concurrent updates did not fence current version") - } - device.Labels = map[string]string{"committed": "first"} - if err := project.Client.Update(ctx, device); err != nil { - t.Fatal(err) - } - newRequest := deviceUpdate(t, device) - if response := handler.Handle(ctx, newRequest); !response.Allowed { - t.Fatal(response.Result) - } - if handler.Handle(ctx, oldRequest).Allowed { - t.Fatal("late stale admission replaced the current pending fence") - } - _, ledger, err := handler.Store.Read(ctx) - if err != nil || len(ledger.DeviceFences) != 1 || ledger.DeviceFences[0].Version != device.ResourceVersion { - t.Fatalf("not coalesced at current pending baseline: %+v %v", ledger, err) - } - restarted := *handler - if restarted.Handle(ctx, registrationRequest(t, device, "unknown-second")).Allowed { - t.Fatal("unknown or rejected write released after restart") - } - noop := newRequest - noop.Object = noop.OldObject - if !restarted.Handle(ctx, noop).Allowed || restarted.Handle(ctx, registrationRequest(t, device, "after-noop")).Allowed { - t.Fatal("no-op must neither fail nor release a pending baseline") - } - device.Labels["committed"] = "second" - if err := project.Client.Update(ctx, device); err != nil { - t.Fatal(err) - } - if response := restarted.Handle(ctx, registrationRequest(t, device, "fresh")); !response.Allowed { - t.Fatal(response.Result) - } -} - -func TestCoalescingLegacyFencesPreservesAliasesAndTombstones(t *testing.T) { - ctx := context.Background() - handler, device := fixture(t) - secret, ledger, _ := handler.Store.Read(ctx) - ledger.DeviceFences = []DeviceFence{ - {Project: "provider", UID: device.UID, Aliases: aliases(device)}, - {Project: "provider", UID: device.UID, Version: "older"}, - {Project: "provider", UID: device.UID, Version: device.ResourceVersion}, - {Project: "other", UID: device.UID, Version: "unrelated"}, - } - if err := handler.Store.Write(ctx, secret, ledger); err != nil { - t.Fatal(err) - } - update := deviceUpdate(t, device) - if response := handler.Handle(ctx, update); !response.Allowed { - t.Fatal(response.Result) - } - _, ledger, _ = handler.Store.Read(ctx) - if len(ledger.DeviceFences) != 2 || len(ledger.DeviceFences[1].Aliases) != len(aliases(device)) || ledger.DeviceFences[0].Project != "other" { - t.Fatalf("lost aliases or unrelated fences: %+v", ledger) - } - deletion := update - deletion.Operation = admissionv1.Delete - if !handler.Handle(ctx, deletion).Allowed || handler.Handle(ctx, update).Allowed { - t.Fatal("delete must permanently dominate pending update fences") - } - create := update - create.Operation = admissionv1.Create - recreated := device.DeepCopyObject().(*inventory.Device) - recreated.UID = "recreated" - create.Object.Raw, _ = json.Marshal(recreated) - if handler.Handle(ctx, create).Allowed { - t.Fatal("never-registered deleted hardware aliases were released") - } - _, ledger, _ = handler.Store.Read(ctx) - if len(ledger.DeviceFences) != 2 || !ledger.DeviceFences[1].Deleted || ledger.DeviceFences[1].Version != "" { - t.Fatalf("delete did not coalesce into permanent tombstone: %+v", ledger) - } -} - -func TestLedgerExactSizeCap(t *testing.T) { - ctx := context.Background() - handler, _ := fixture(t) - secret, ledger, _ := handler.Store.Read(ctx) - ledger.DeviceFences = []DeviceFence{{Project: "provider", UID: "device", Aliases: []string{""}}} - encoded, _ := json.Marshal(ledger) - ledger.DeviceFences[0].Aliases[0] = strings.Repeat("x", TailBudget-len(encoded)) - if err := handler.Store.Write(ctx, secret, ledger); err != nil { - t.Fatalf("exact tail budget must fit: %v", err) - } - before := secret.ResourceVersion - ledger.DeviceFences[0].Aliases[0] += "x" - if err := handler.Store.Write(ctx, secret, ledger); err == nil || !strings.Contains(err.Error(), "ledger is full") { - t.Fatalf("tail budget plus one must fail closed: %v", err) - } - current, _, err := handler.Store.Read(ctx) - if err != nil || current.ResourceVersion != before || len(current.Data["ledger.json"]) != TailBudget { - t.Fatal("oversized write changed durable reservations") - } -} - -func TestDryRunCannotReserve(t *testing.T) { - ctx := context.Background() - handler, device := fixture(t) - before, _, _ := handler.Store.Read(ctx) - for _, request := range []admission.Request{registrationRequest(t, device, "dry"), deviceUpdate(t, device)} { - dry := true - request.DryRun = &dry - if response := handler.Handle(ctx, request); response.Allowed || !strings.Contains(response.Result.Message, "dry-run") { - t.Fatalf("dry run was not explicitly denied: %+v", response) - } - } - after, ledger, _ := handler.Store.Read(ctx) - if before.ResourceVersion != after.ResourceVersion || len(ledger.Entries) != 0 || len(ledger.DeviceFences) != 0 { - t.Fatal("dry-run retained effects") - } - project, _ := handler.Resolve(ctx, "provider") - if err := project.Client.Get(ctx, client.ObjectKeyFromObject(device), device); err != nil || device.ResourceVersion != "1" { - t.Fatal("dry-run changed Device") - } -} - -type afterDeviceReadClient struct { - client.Client - after func() -} - -func (api *afterDeviceReadClient) Get(ctx context.Context, key client.ObjectKey, object client.Object, options ...client.GetOption) error { - err := api.Client.Get(ctx, key, object, options...) - if _, device := object.(*inventory.Device); err == nil && device && api.after != nil { - after := api.after - api.after = nil - after() - } - return err -} - -func TestConcurrentNewerPendingFenceForcesBaselineRecheck(t *testing.T) { - ctx := context.Background() - handler, device := fixture(t) - project, _ := handler.Resolve(ctx, "provider") - oldRequest := deviceUpdate(t, device) - interleaved := &afterDeviceReadClient{Client: project.Client} - interleaved.after = func() { - device.Labels = map[string]string{"committed": "first"} - if err := project.Client.Update(ctx, device); err != nil { - t.Fatal(err) - } - if response := handler.Handle(ctx, deviceUpdate(t, device)); !response.Allowed { - t.Fatal(response.Result) - } - } - handler.Resolve = func(context.Context, string) (Project, error) { - return Project{Identity: project.Identity, Client: interleaved}, nil - } - if handler.Handle(ctx, oldRequest).Allowed { - t.Fatal("stale admission survived newer pending fence CAS") - } - _, ledger, err := handler.Store.Read(ctx) - if err != nil || len(ledger.DeviceFences) != 1 || ledger.DeviceFences[0].Version != device.ResourceVersion { - t.Fatalf("newer pending fence lost: %+v %v", ledger, err) - } - if handler.Handle(ctx, registrationRequest(t, device, "still-pending")).Allowed { - t.Fatal("newer pending version became registrable") - } -} diff --git a/internal/registration/contention_envtest_test.go b/internal/registration/contention_envtest_test.go deleted file mode 100644 index f6862092..00000000 --- a/internal/registration/contention_envtest_test.go +++ /dev/null @@ -1,112 +0,0 @@ -package registration - -import ( - "bytes" - "context" - "fmt" - "log/slog" - "os" - "strings" - "testing" - - corev1 "k8s.io/api/core/v1" - apierrors "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/envtest" -) - -type contendedLedgerClient struct { - client.Client - remaining int - attempts int - conflicts int -} - -func (contender *contendedLedgerClient) Update(ctx context.Context, object client.Object, options ...client.UpdateOption) error { - contender.attempts++ - if contender.remaining > 0 { - contender.remaining-- - completed := make(chan error, 1) - go func() { - current := &corev1.Secret{} - if err := contender.Client.Get(ctx, client.ObjectKeyFromObject(object), current); err != nil { - completed <- err - return - } - current.Annotations = map[string]string{"competing-writer": fmt.Sprint(contender.attempts)} - completed <- contender.Client.Update(ctx, current) - }() - if err := <-completed; err != nil { - return err - } - } - err := contender.Client.Update(ctx, object, options...) - if apierrors.IsConflict(err) { - contender.conflicts++ - } - return err -} - -func TestRealLedgerCASRetryBudget(t *testing.T) { - if os.Getenv("KUBEBUILDER_ASSETS") == "" { - t.Skip("KUBEBUILDER_ASSETS required") - } - environment := &envtest.Environment{} - config, err := environment.Start() - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { - if err := environment.Stop(); err != nil { - t.Error(err) - } - }) - scheme := runtime.NewScheme() - if err := corev1.AddToScheme(scheme); err != nil { - t.Fatal(err) - } - api, err := client.New(config, client.Options{Scheme: scheme}) - if err != nil { - t.Fatal(err) - } - ctx := context.Background() - for _, conflicts := range []int{5, 6} { - t.Run(fmt.Sprintf("conflicts-%d", conflicts), func(t *testing.T) { - handler, device := fixture(t) - secret, _, err := handler.Store.Read(ctx) - if err != nil { - t.Fatal(err) - } - namespace := fmt.Sprintf("cas-%d", conflicts) - if err := api.Create(ctx, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: namespace}}); err != nil { - t.Fatal(err) - } - secret.Namespace, secret.UID, secret.ResourceVersion = namespace, "", "" - if err := api.Create(ctx, secret); err != nil { - t.Fatal(err) - } - contender := &contendedLedgerClient{Client: api, remaining: conflicts} - handler.Store.Client, handler.Store.Namespace = contender, namespace - var logs bytes.Buffer - previous := slog.Default() - slog.SetDefault(slog.New(slog.NewJSONHandler(&logs, nil))) - defer slog.SetDefault(previous) - response := handler.Handle(ctx, registrationRequest(t, device, "contended")) - if response.Allowed != (conflicts == 5) || contender.attempts != 6 || contender.conflicts != conflicts { - t.Fatalf("real CAS retry budget: allowed=%v attempts=%d conflicts=%d result=%v", response.Allowed, contender.attempts, contender.conflicts, response.Result) - } - _, ledger, err := handler.Store.Read(ctx) - if err != nil { - t.Fatal(err) - } - if conflicts == 5 && (len(ledger.Entries) != 1 || ledger.Entries[0].Outcome != "Unknown") { - t.Fatal("successful CAS did not retain unknown reservation") - } - if conflicts == 6 && (len(ledger.Entries) != 0 || !strings.Contains(logs.String(), "CAS retries exhausted") || !strings.Contains(logs.String(), `"attempts":6`)) { - t.Fatalf("exhaustion was not observable or wrote reservation: %s", logs.String()) - } - }) - } -} diff --git a/internal/registration/control.go b/internal/registration/control.go deleted file mode 100644 index 4e46d7d0..00000000 --- a/internal/registration/control.go +++ /dev/null @@ -1,235 +0,0 @@ -package registration - -import ( - "context" - "crypto/ed25519" - "encoding/json" - "errors" - "log/slog" - "reflect" - - corev1 "k8s.io/api/core/v1" - apierrors "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" - "sigs.k8s.io/controller-runtime/pkg/client" -) - -type ControlRequest struct { - Action string `json:"action"` - ID string `json:"id"` - Reason string `json:"reason"` - Authority string `json:"authority"` - Projects []string `json:"projects"` - RootUID types.UID `json:"rootUID"` - ResourceVersion string `json:"resourceVersion"` - Epoch uint64 `json:"epoch"` - FenceDigest string `json:"fenceDigest,omitempty"` -} - -type SignedControl struct { - Request ControlRequest `json:"request"` - Signature []byte `json:"signature"` -} - -func SignControl(request ControlRequest, key ed25519.PrivateKey) SignedControl { - encoded, _ := json.Marshal(request) - return SignedControl{Request: request, Signature: ed25519.Sign(key, append([]byte("fleet-registration-control-v2\n"), encoded...))} -} - -func (store Store) verifyControl(control SignedControl, uid types.UID) error { - request := control.Request - encoded, err := json.Marshal(request) - if err != nil { - return err - } - if len(store.ControlKey) != ed25519.PublicKeySize || len(encoded) > 8192 || !ed25519.Verify(store.ControlKey, append([]byte("fleet-registration-control-v2\n"), encoded...), control.Signature) { - return errors.New("registration control signature unavailable or invalid") - } - if request.RootUID != uid || request.Authority != store.Authority || !reflect.DeepEqual(request.Projects, store.Projects) || request.ResourceVersion == "" || request.ID == "" || request.Reason == "" || (request.Action != "expand" && request.Action != "activate") { - return errors.New("registration control authority or action mismatch") - } - return nil -} - -func (store Store) root(ctx context.Context) (*corev1.Secret, Routing, error) { - secret := &corev1.Secret{} - if err := store.Client.Get(ctx, client.ObjectKey{Namespace: store.Namespace, Name: LedgerName}, secret); err != nil { - return nil, Routing{}, err - } - if secret.UID == "" || !secret.DeletionTimestamp.IsZero() { - return nil, Routing{}, errors.New("ledger lifetime unavailable") - } - if _, exists := secret.Data["routing.json"]; exists { - route, err := decodeRouting(secret) - return secret, route, err - } - return secret, Routing{Version: 2, RootUID: secret.UID}, nil -} - -func encodeRoute(secret *corev1.Secret, route Routing) error { - encoded, err := json.Marshal(route) - if err != nil { - return err - } - if _, exists := secret.Data["routing.json"]; !exists { - secret.Data["tail.json"] = secret.Data["ledger.json"] - secret.Data["ledger.json"] = []byte(`{"authority":"v2-routing-required","projects":[]}`) - } - secret.Data["routing.json"] = encoded - return nil -} - -func (handler *Handler) ApplyControl(ctx context.Context, control SignedControl) error { - secret, route, err := handler.Store.root(ctx) - if err != nil { - return err - } - if err := handler.Store.verifyControl(control, secret.UID); err != nil { - return err - } - if control.Request.Action == "expand" && control.Request.Epoch < route.Epoch { - reference := route.Segments[control.Request.Epoch] - segment := &corev1.Secret{} - if err := handler.Store.Client.Get(ctx, client.ObjectKey{Namespace: handler.Store.Namespace, Name: reference.Name}, segment); err != nil { - return err - } - encoded, _ := json.Marshal(control) - if segment.UID != reference.UID || segment.Immutable == nil || !*segment.Immutable || !segment.DeletionTimestamp.IsZero() || digest(segment.Data["ledger.json"]) != reference.Digest || string(segment.Data["control.json"]) != string(encoded) { - return errors.New("stale expansion does not match retained completion") - } - return nil - } - if route.Pending != nil { - if !reflect.DeepEqual(*route.Pending, control) { - return errors.New("another signed expansion is pending") - } - return handler.Store.ResumeExpansion(ctx) - } - if route.Activation != nil && reflect.DeepEqual(*route.Activation, control) { - return nil - } - if route.Epoch != control.Request.Epoch || secret.ResourceVersion != control.Request.ResourceVersion { - return errors.New("stale control epoch or CAS baseline; inspect current root") - } - if _, _, err := handler.Store.Read(ctx); err != nil { - return err - } - switch control.Request.Action { - case "activate": - if err := handler.verifyActivation(ctx, control); err != nil { - return err - } - if route.Activation != nil { - if len(route.ActivationHistory) >= 7 { - return errors.New("activation audit budget exhausted; retained history requires a reviewed migration") - } - route.ActivationHistory = append(route.ActivationHistory, *route.Activation) - } - route.Activation = &control - case "expand": - if len(route.Segments) >= MaxSegments { - return ErrSegmentsExhausted - } - route.Pending = &control - } - if err := encodeRoute(secret, route); err != nil { - return err - } - if err := handler.Store.updateRoot(ctx, secret); err != nil { - return err - } - slog.InfoContext(ctx, "registration signed control retained", "action", control.Request.Action, "id", control.Request.ID, "rootUID", secret.UID, "epoch", route.Epoch, "signer", digest(handler.Store.ControlKey)) - if route.Pending != nil { - return handler.Store.ResumeExpansion(ctx) - } - return nil -} - -func (store Store) ResumeExpansion(ctx context.Context) error { - secret, route, err := store.root(ctx) - if err != nil || route.Pending == nil { - return err - } - if err := store.verifyControl(*route.Pending, secret.UID); err != nil { - return err - } - if route.Pending.Request.Action != "expand" || route.Pending.Request.Epoch != route.Epoch || len(route.Segments) >= MaxSegments { - return errors.New("invalid pending expansion") - } - if _, _, err := store.readSnapshot(ctx, secret); err != nil { - return err - } - tail := secret.Data["tail.json"] - if len(tail) > SegmentBudget { - return ErrGrowthStopped - } - control, _ := json.Marshal(route.Pending) - immutable := true - segment := &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Namespace: store.Namespace, Name: segmentName(secret.UID, route.Epoch)}, Immutable: &immutable, Data: map[string][]byte{"ledger.json": tail, "control.json": control, "rootUID": []byte(secret.UID)}} - if err := store.Client.Create(ctx, segment); err != nil && !apierrors.IsAlreadyExists(err) { - return err - } - stored := &corev1.Secret{} - if err := store.Client.Get(ctx, client.ObjectKeyFromObject(segment), stored); err != nil { - return err - } - if stored.UID == "" || !stored.DeletionTimestamp.IsZero() || stored.Immutable == nil || !*stored.Immutable || !reflect.DeepEqual(stored.Data, segment.Data) { - return errors.New("expansion segment identity or contents conflict; remain fenced") - } - route.Segments = append(route.Segments, Segment{Name: stored.Name, UID: stored.UID, Digest: digest(tail)}) - route.Epoch++ - route.Pending = nil - empty, _ := json.Marshal(Ledger{Authority: store.Authority, Projects: store.Projects}) - secret.Data["tail.json"] = empty - if err := encodeRoute(secret, route); err != nil { - return err - } - if err := store.updateRoot(ctx, secret); err != nil { - return err - } - slog.InfoContext(ctx, "registration expansion committed", "rootUID", secret.UID, "epoch", route.Epoch, "segmentUID", stored.UID) - return nil -} - -func (handler *Handler) verifyActivation(ctx context.Context, control SignedControl) error { - if handler.VerifyFence == nil || handler.FenceDigest == nil { - return errors.New("activation fence verification unavailable") - } - if err := handler.VerifyFence(ctx); err != nil { - return err - } - actual, err := handler.FenceDigest(ctx) - if err != nil { - return err - } - if actual == "" || actual != control.Request.FenceDigest { - return errors.New("installed fence differs from signed activation") - } - return nil -} - -func (handler *Handler) Ready(ctx context.Context) error { - secret, route, err := handler.Store.root(ctx) - if err != nil { - return err - } - return handler.readySnapshot(ctx, secret, route) -} - -func (handler *Handler) readySnapshot(ctx context.Context, secret *corev1.Secret, route Routing) error { - if route.Pending != nil || route.Activation == nil { - return errors.New("registration is non-admitting: signed activation or expansion incomplete") - } - if err := handler.Store.verifyControl(*route.Activation, secret.UID); err != nil { - return err - } - if route.Activation.Request.Action != "activate" { - return errors.New("invalid activation action") - } - if err := handler.verifyActivation(ctx, *route.Activation); err != nil { - return err - } - _, _, err := handler.Store.readSnapshot(ctx, secret) - return err -} diff --git a/internal/registration/control_test.go b/internal/registration/control_test.go deleted file mode 100644 index 4b7572d7..00000000 --- a/internal/registration/control_test.go +++ /dev/null @@ -1,150 +0,0 @@ -package registration - -import ( - "context" - "crypto/ed25519" - "crypto/rand" - "encoding/json" - "errors" - "net/http" - "net/http/httptest" - "reflect" - "testing" - - admissionv1 "k8s.io/api/admission/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -func controlFor(t *testing.T, handler *Handler, key ed25519.PrivateKey, action string) SignedControl { - t.Helper() - secret, route, err := handler.Store.root(context.Background()) - if err != nil { - t.Fatal(err) - } - return SignControl(ControlRequest{Action: action, ID: "operator-change-" + secret.ResourceVersion, Reason: "synthetic test approval", Authority: handler.Store.Authority, Projects: handler.Store.Projects, RootUID: secret.UID, ResourceVersion: secret.ResourceVersion, Epoch: route.Epoch, FenceDigest: "approved-fence"}, key) -} - -func controlFixture(t *testing.T, handler *Handler) ed25519.PrivateKey { - t.Helper() - public, private, err := ed25519.GenerateKey(rand.Reader) - if err != nil { - t.Fatal(err) - } - handler.Store.ControlKey = public - handler.Store.AllowInactiveForTests = false - handler.VerifyFence = func(context.Context) error { return nil } - handler.FenceDigest = func(context.Context) (string, error) { return "approved-fence", nil } - return private -} - -func TestBootstrapDoesNotAdmitOrInterpretCallerConfiguration(t *testing.T) { - ctx := context.Background() - handler, device := fixture(t) - private := controlFixture(t, handler) - server := httptest.NewServer(handler.Transport()) - defer server.Close() - for path, expected := range map[string]int{"/transportz": http.StatusNoContent, "/activationz": http.StatusServiceUnavailable} { - response, err := server.Client().Get(server.URL + path) - if err != nil { - t.Fatal(err) - } - response.Body.Close() - if response.StatusCode != expected { - t.Fatalf("%s: %d", path, response.StatusCode) - } - } - request := registrationRequest(t, device, "bootstrap") - for _, resource := range []metav1.GroupVersionResource{{Group: "metal.datumapis.com", Resource: "machinecapacities"}, {Group: "fleet.datumapis.com", Resource: "devices"}, {Resource: "namespaces"}, {Group: "resourcemanager.miloapis.com", Resource: "projects"}} { - request.Resource, request.Operation, request.Name = resource, admissionv1.Delete, "unrelated" - if handler.Handle(ctx, request).Allowed { - t.Fatal("bootstrap admitted a request") - } - } - control := controlFor(t, handler, private, "activate") - for name, mutate := range map[string]func(*SignedControl){ - "signature": func(control *SignedControl) { control.Signature[0] ^= 1 }, - "authority": func(control *SignedControl) { control.Request.Authority = "other" }, - "scope": func(control *SignedControl) { control.Request.Projects = []string{"other"} }, - "epoch": func(control *SignedControl) { control.Request.Epoch++ }, - "root": func(control *SignedControl) { control.Request.RootUID = "replacement" }, - "fence": func(control *SignedControl) { control.Request.FenceDigest = "relaxed" }, - } { - t.Run(name, func(t *testing.T) { - encoded, _ := json.Marshal(control) - var changed SignedControl - _ = json.Unmarshal(encoded, &changed) - mutate(&changed) - if handler.ApplyControl(ctx, changed) == nil { - t.Fatal("tampered configuration accepted") - } - if name != "signature" { - changed = SignControl(changed.Request, private) - if handler.ApplyControl(ctx, changed) == nil { - t.Fatal("wrong signed target accepted") - } - } - }) - } - handler.VerifyFence = func(context.Context) error { return errors.New("missing Fail webhook") } - if handler.ApplyControl(ctx, control) == nil { - t.Fatal("missing fence activated") - } - handler.VerifyFence = func(context.Context) error { return nil } - if err := handler.ApplyControl(ctx, control); err != nil { - t.Fatal(err) - } - if err := handler.ApplyControl(ctx, control); err != nil { - t.Fatal("activation retry", err) - } - if err := handler.Ready(ctx); err != nil { - t.Fatal(err) - } - secret, before, err := handler.Store.Read(ctx) - if err != nil { - t.Fatal(err) - } - var legacy Ledger - if err := json.Unmarshal(secret.Data["ledger.json"], &legacy); err != nil || legacy.Authority == handler.Store.Authority { - t.Fatal("old binary not fenced") - } - handler.FenceDigest = func(context.Context) (string, error) { return "changed-fence", nil } - if handler.Handle(ctx, registrationRequest(t, device, "changed-trust")).Allowed { - t.Fatal("changed fence bypassed activation") - } - _, after, _ := handler.Store.Read(ctx) - if !reflect.DeepEqual(before, after) { - t.Fatal("denial changed reservations") - } - handler.FenceDigest = func(context.Context) (string, error) { return "approved-fence", nil } - handler.VerifyFence = func(context.Context) error { return errors.New("unavailable") } - if handler.Ready(ctx) == nil { - t.Fatal("lost fence reported active") - } - handler.VerifyFence = func(context.Context) error { return nil } - for range 7 { - if err := handler.ApplyControl(ctx, controlFor(t, handler, private, "activate")); err != nil { - t.Fatal(err) - } - } - if err := handler.ApplyControl(ctx, controlFor(t, handler, private, "activate")); err == nil { - t.Fatal("activation audit history exceeded its bound") - } - current, _, err := handler.Store.root(ctx) - if err != nil { - t.Fatal(err) - } - if err := handler.Store.Client.Delete(ctx, current); err != nil { - t.Fatal(err) - } - if handler.Handle(ctx, registrationRequest(t, device, "lost-ledger")).Allowed { - t.Fatal("missing ledger admitted") - } - response, err := server.Client().Get(server.URL + "/transportz") - if err != nil { - t.Fatal(err) - } - response.Body.Close() - if response.StatusCode != http.StatusNoContent { - t.Fatal("missing ledger prevented transport inspection") - } -} diff --git a/internal/registration/envtest_test.go b/internal/registration/envtest_test.go index 8e21127f..7332f72b 100644 --- a/internal/registration/envtest_test.go +++ b/internal/registration/envtest_test.go @@ -3,14 +3,14 @@ package registration import ( "bytes" "context" - "encoding/json" "encoding/pem" + "errors" "io" "net/http/httptest" "os" "path/filepath" + "strings" "sync" - "sync/atomic" "testing" "time" @@ -19,9 +19,9 @@ import ( "go.datum.net/fleet/internal/controller" iam "go.miloapis.com/milo/pkg/apis/iam/v1alpha1" admissionregistrationv1 "k8s.io/api/admissionregistration/v1" - authenticationv1 "k8s.io/api/authentication/v1" authorizationv1 "k8s.io/api/authorization/v1" corev1 "k8s.io/api/core/v1" + rbacv1 "k8s.io/api/rbac/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" @@ -34,11 +34,15 @@ import ( "sigs.k8s.io/yaml" ) -func pemCertificate(raw []byte) []byte { - return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: raw}) +type liveAPI struct { + t *testing.T + config *rest.Config + scheme *runtime.Scheme + admin client.Client } -func TestRealAPIServerAdmissionAndCAS(t *testing.T) { +func startAPI(t *testing.T) *liveAPI { + t.Helper() if os.Getenv("KUBEBUILDER_ASSETS") == "" { t.Skip("KUBEBUILDER_ASSETS required") } @@ -53,307 +57,326 @@ func TestRealAPIServerAdmissionAndCAS(t *testing.T) { } }) scheme := runtime.NewScheme() - for _, add := range []func(*runtime.Scheme) error{corev1.AddToScheme, inventory.AddToScheme, metal.AddToScheme, admissionregistrationv1.AddToScheme, authorizationv1.AddToScheme} { + for _, add := range []func(*runtime.Scheme) error{corev1.AddToScheme, rbacv1.AddToScheme, inventory.AddToScheme, metal.AddToScheme, admissionregistrationv1.AddToScheme, authorizationv1.AddToScheme} { if err := add(scheme); err != nil { t.Fatal(err) } } - api, err := client.New(config, client.Options{Scheme: scheme}) + admin, err := client.New(config, client.Options{Scheme: scheme}) if err != nil { t.Fatal(err) } - ctx := context.Background() - if err := api.Create(ctx, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "fleet-system-private"}}); err != nil { - t.Fatal(err) - } - device := &inventory.Device{TypeMeta: metav1.TypeMeta{APIVersion: inventory.GroupVersion.String(), Kind: "Device"}, ObjectMeta: metav1.ObjectMeta{Name: "hardware", Namespace: "default"}, Spec: inventory.DeviceSpec{ClaimRef: inventory.LocalReference{Name: "installation"}, Identity: inventory.DeviceIdentity{Model: "test", Serial: "serial-1", SystemUUID: "11111111-1111-1111-1111-111111111111"}}} - if err := api.Create(ctx, device); err != nil { - t.Fatal(err) - } - encoded, _ := json.Marshal(Ledger{Authority: "milo", Projects: []string{"datum-cloud"}}) - if err := api.Create(ctx, &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: LedgerName, Namespace: "fleet-system-private"}, Data: map[string][]byte{"ledger.json": encoded}}); err != nil { - t.Fatal(err) - } - protection, err := os.ReadFile("../../config/base/registration/protection.yaml") - if err != nil { - t.Fatal(err) - } - decoder := utilyaml.NewYAMLOrJSONDecoder(bytes.NewReader(protection), 4096) - for { - var object unstructured.Unstructured - err := decoder.Decode(&object.Object) - if err == io.EOF { - break - } - if err != nil { - t.Fatal(err) - } - if err := api.Create(ctx, &object); err != nil { - t.Fatal(err) - } - } - protectionDeadline := time.Now().Add(10 * time.Second) - for { - probe := &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: LedgerName, Namespace: "fleet-system-private"}} - err := api.Delete(ctx, probe, client.DryRunAll) - if apierrors.IsInvalid(err) || apierrors.IsForbidden(err) { - break - } - if time.Now().After(protectionDeadline) { - t.Fatalf("ledger retention policy did not engage: %v", err) - } - time.Sleep(30 * time.Millisecond) - } - for { - probe := &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "fleet-system-private"}} - err := api.Delete(ctx, probe, client.DryRunAll) - if apierrors.IsInvalid(err) || apierrors.IsForbidden(err) { - break - } - if time.Now().After(protectionDeadline) { - t.Fatalf("namespace retention policy did not engage: %v", err) - } - time.Sleep(30 * time.Millisecond) - } - privateConfig := rest.CopyConfig(config) - privateConfig.Impersonate = rest.ImpersonationConfig{UserName: "system:serviceaccount:fleet-system:fleet-registration", Groups: []string{"system:masters"}} - private, err := client.New(privateConfig, client.Options{Scheme: scheme}) + return &liveAPI{t: t, config: config, scheme: scheme, admin: admin} +} + +// actor impersonates a caller routed through the provider project, as Milo's +// routing filters establish it. +func (api *liveAPI) actor(name string, groups ...string) client.Client { + api.t.Helper() + config := rest.CopyConfig(api.config) + config.Impersonate = rest.ImpersonationConfig{UserName: name, UID: name + "-uid", Groups: groups, Extra: map[string][]string{iam.ParentKindExtraKey: {"Project"}, iam.ParentAPIGroupExtraKey: {"resourcemanager.miloapis.com"}, iam.ParentNameExtraKey: {"datum-cloud"}}} + actor, err := client.New(config, client.Options{Scheme: api.scheme}) if err != nil { - t.Fatal(err) + api.t.Fatal(err) } - var denied atomic.Bool - handler := &Handler{Store: Store{Client: private, Namespace: "fleet-system-private", Authority: "milo", Projects: []string{"datum-cloud"}}, VerifyFence: func(ctx context.Context) error { return VerifyFence(ctx, api, []string{"datum-cloud"}) }, Resolve: func(context.Context, string) (Project, error) { - return Project{Identity: controller.ProjectIdentity{AuthorityID: "milo", RouteName: "datum-cloud", UID: "project-1"}, Client: api}, nil - }, Authorize: func(ctx context.Context, project Project, actor authenticationv1.UserInfo, group, resource, name string) error { - if denied.Load() { - return ErrConflict - } - return Authorize(ctx, project, actor, group, resource, name) - }} - privateKey := controlFixture(t, handler) - handler.VerifyFence = func(ctx context.Context) error { return VerifyFence(ctx, api, []string{"datum-cloud"}) } - handler.FenceDigest = func(ctx context.Context) (string, error) { - var current admissionregistrationv1.ValidatingWebhookConfiguration - if err := api.Get(ctx, client.ObjectKey{Name: "fleet-capacity-registration"}, ¤t); err != nil { - return "", err - } - encoded, err := json.Marshal(current.Webhooks) - return digest(encoded), err + return actor +} + +func (api *liveAPI) device(name, namespace, serial, uuid string) *inventory.Device { + api.t.Helper() + device := &inventory.Device{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: namespace}, Spec: inventory.DeviceSpec{ClaimRef: inventory.LocalReference{Name: "installation"}, Identity: inventory.DeviceIdentity{Model: "test", Serial: serial, SystemUUID: uuid}}} + if err := api.admin.Create(context.Background(), device); err != nil { + api.t.Fatal(err) } - lateAdmission, release := make(chan struct{}), make(chan struct{}) - server := httptest.NewTLSServer(&admission.Webhook{Handler: admission.HandlerFunc(func(ctx context.Context, request admission.Request) admission.Response { - response := handler.Handle(ctx, request) - if response.Allowed && request.Resource.Resource == "machinecapacities" && request.Name == "admitted-never-persisted" { - close(lateAdmission) - select { - case <-release: - case <-ctx.Done(): - } - return admission.Denied("synthetic later admission/storage failure") - } - return response - })}) - t.Cleanup(server.Close) - url := server.URL + return device +} + +// installWebhook serves the production handler behind the packaged webhook +// configuration and returns the server so a test can take it away. +func (api *liveAPI) installWebhook() *httptest.Server { + api.t.Helper() + handler := &Handler{Projects: []string{"datum-cloud"}, Resolve: func(context.Context, string) (Project, error) { + return Project{Identity: controller.ProjectIdentity{AuthorityID: "milo", RouteName: "datum-cloud", UID: "project-1"}, Client: api.admin}, nil + }, Authorize: Authorize} + server := httptest.NewTLSServer(&admission.Webhook{Handler: handler}) + api.t.Cleanup(server.Close) data, err := os.ReadFile("../../config/components/registration-admission/webhook.yaml") if err != nil { - t.Fatal(err) + api.t.Fatal(err) } webhooks := &admissionregistrationv1.ValidatingWebhookConfiguration{} if err := yaml.UnmarshalStrict(data, webhooks); err != nil { - t.Fatal(err) + api.t.Fatal(err) } + url := server.URL for index := range webhooks.Webhooks { - webhooks.Webhooks[index].ClientConfig = admissionregistrationv1.WebhookClientConfig{URL: &url, CABundle: pemCertificate(server.Certificate().Raw)} - } - if err := api.Create(ctx, webhooks); err != nil { - t.Fatal(err) + webhooks.Webhooks[index].ClientConfig = admissionregistrationv1.WebhookClientConfig{URL: &url, CABundle: pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: server.Certificate().Raw})} } - activation := controlFor(t, handler, privateKey, "activate").Request - activation.FenceDigest, err = handler.FenceDigest(ctx) - if err != nil { - t.Fatal(err) + if err := api.admin.Create(context.Background(), webhooks); err != nil { + api.t.Fatal(err) } - if err := handler.ApplyControl(ctx, SignControl(activation, privateKey)); err != nil { - t.Fatal(err) - } - actorConfig := rest.CopyConfig(config) - actorConfig.Impersonate = rest.ImpersonationConfig{UserName: "operator", UID: "actor-1", Groups: []string{"system:masters"}, Extra: map[string][]string{iam.ParentKindExtraKey: {"Project"}, iam.ParentAPIGroupExtraKey: {"resourcemanager.miloapis.com"}, iam.ParentNameExtraKey: {"datum-cloud"}}} - actor, err := client.New(actorConfig, client.Options{Scheme: scheme}) + operator := api.actor("operator", "system:masters") + api.eventually("registration webhook", func() bool { + probe := &metal.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: "webhook-probe", Namespace: "default"}, Spec: metal.MachineCapacitySpec{DeviceRef: metal.LocalReference{Name: "absent"}, AllocationPolicy: "Disabled", ReclaimPolicy: "Retain"}} + return apierrors.IsForbidden(operator.Create(context.Background(), probe, client.DryRunAll)) + }) + return server +} + +// installDeletionProtection applies the optional component's manifests as an +// environment that opts in would. +func (api *liveAPI) installDeletionProtection(probe *inventory.Device) { + api.t.Helper() + data, err := os.ReadFile("../../config/components/device-deletion-protection/policy.yaml") if err != nil { - t.Fatal(err) + api.t.Fatal(err) } - deadline := time.Now().Add(10 * time.Second) + decoder := utilyaml.NewYAMLOrJSONDecoder(bytes.NewReader(data), 4096) for { - probe := &metal.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: "dry-run-probe", Namespace: "default"}, Spec: metal.MachineCapacitySpec{DeviceRef: metal.LocalReference{Name: device.Name}, AllocationPolicy: "Disabled", ReclaimPolicy: "Retain"}} - err = actor.Create(ctx, probe, client.DryRunAll) - if apierrors.IsForbidden(err) { + var object unstructured.Unstructured + err := decoder.Decode(&object.Object) + if errors.Is(err, io.EOF) { break } - if time.Now().After(deadline) { - t.Fatalf("webhook did not engage: %v", err) + if err != nil { + api.t.Fatal(err) + } + if err := api.admin.Create(context.Background(), &object); err != nil { + api.t.Fatal(err) } - time.Sleep(30 * time.Millisecond) - } - var wins atomic.Int32 - var workers sync.WaitGroup - for _, name := range []string{"first", "second", "third"} { - request := registrationRequest(t, device, name) - var capacity metal.MachineCapacity - _ = json.Unmarshal(request.Object.Raw, &capacity) - capacity.UID = "forged-client-uid" - workers.Add(1) - go func() { - defer workers.Done() - if actor.Create(ctx, &capacity) == nil { - wins.Add(1) - } - }() - } - workers.Wait() - if wins.Load() != 1 { - t.Fatalf("wanted one admission, got %d", wins.Load()) - } - if err := handler.Recover(ctx); err != nil { - t.Fatal(err) - } - _, ledger, err := handler.Store.Read(ctx) - if err != nil || len(ledger.Entries) != 1 || ledger.Entries[0].Outcome != "Recorded" || ledger.Entries[0].CapacityUID == "forged-client-uid" { - t.Fatalf("incarnation not bound by real API: %+v %v", ledger, err) - } - var capacity metal.MachineCapacity - if err := actor.Get(ctx, client.ObjectKey{Namespace: "default", Name: ledger.Entries[0].Name}, &capacity); err != nil { - t.Fatal(err) - } - capacity.Spec.AllocationPolicy = "Enabled" - capacity.Spec.CleaningPolicyRef.Name = "invented-policy" - if err := actor.Update(ctx, &capacity); !apierrors.IsForbidden(err) { - t.Fatalf("direct enabling bypass: %v", err) - } - if err := actor.Get(ctx, client.ObjectKeyFromObject(&capacity), &capacity); err != nil { - t.Fatal(err) - } - capacity.Annotations[DeviceUIDAnnotation] = "copied-other-incarnation" - if err := actor.Update(ctx, &capacity); !apierrors.IsForbidden(err) { - t.Fatalf("binding annotation bypass: %v", err) - } - if err := actor.Get(ctx, client.ObjectKeyFromObject(&capacity), &capacity); err != nil { - t.Fatal(err) - } - capacity.Status.Conditions = []metav1.Condition{{Type: "Available", Status: metav1.ConditionTrue, Reason: "Fabricated", Message: "Must not be accepted", LastTransitionTime: metav1.Now()}} - if err := actor.Status().Update(ctx, &capacity); !apierrors.IsForbidden(err) { - t.Fatalf("positive readiness bypass: %v", err) - } - if err := actor.Delete(ctx, &capacity); !apierrors.IsForbidden(err) { - t.Fatalf("direct deletion bypass: %v", err) - } - if err := actor.Delete(ctx, device); !apierrors.IsForbidden(err) { - t.Fatalf("Device deletion bypass: %v", err) - } - var namespace corev1.Namespace - if err := actor.Get(ctx, client.ObjectKey{Name: "default"}, &namespace); err != nil { - t.Fatal(err) - } - if err := actor.Delete(ctx, &namespace); !apierrors.IsForbidden(err) { - t.Fatalf("inventory namespace deletion bypass: %v", err) - } - var privateNamespace corev1.Namespace - if err := api.Get(ctx, client.ObjectKey{Name: "fleet-system-private"}, &privateNamespace); err != nil { - t.Fatal(err) - } - if err := api.Delete(ctx, &privateNamespace); !apierrors.IsInvalid(err) && !apierrors.IsForbidden(err) { - t.Fatalf("private namespace deletion bypass: %v", err) - } - secret, _, err := handler.Store.Read(ctx) - if err != nil { - t.Fatal(err) - } - if err := api.Delete(ctx, secret); !apierrors.IsInvalid(err) && !apierrors.IsForbidden(err) { - t.Fatalf("ledger deletion bypass: %v", err) } - if err := api.Update(ctx, secret); !apierrors.IsInvalid(err) && !apierrors.IsForbidden(err) { - t.Fatalf("ledger overwrite bypass: %v", err) + api.eventually("Device deletion policy", func() bool { + return apierrors.IsForbidden(api.admin.Delete(context.Background(), probe, client.DryRunAll)) + }) +} + +func (api *liveAPI) eventually(what string, condition func() bool) { + api.t.Helper() + deadline := time.Now().Add(15 * time.Second) + for !condition() { + if time.Now().After(deadline) { + api.t.Fatalf("%s did not engage", what) + } + time.Sleep(50 * time.Millisecond) } - duplicate := device.DeepCopyObject().(*inventory.Device) - duplicate.Name, duplicate.UID, duplicate.ResourceVersion = "other", "", "" - if err := actor.Create(ctx, duplicate); !apierrors.IsForbidden(err) { - t.Fatalf("alias bypass: %v", err) +} + +func (api *liveAPI) exists(object client.Object) bool { + api.t.Helper() + err := api.admin.Get(context.Background(), client.ObjectKeyFromObject(object), object) + if err != nil && !apierrors.IsNotFound(err) { + api.t.Fatal(err) } - denied.Store(true) - request := registrationRequest(t, device, "denied") - var rejected metal.MachineCapacity - _ = json.Unmarshal(request.Object.Raw, &rejected) - rejected.UID = "" - if err := actor.Create(ctx, &rejected); !apierrors.IsForbidden(err) { - t.Fatalf("revoked authorization bypass: %v", err) + return err == nil +} + +// registration builds the exact create the staff portal sends for the +// Device's current incarnation. +func (api *liveAPI) registration(device *inventory.Device) *metal.MachineCapacity { + api.t.Helper() + if err := api.admin.Get(context.Background(), client.ObjectKeyFromObject(device), device); err != nil { + api.t.Fatal(err) + } + return &metal.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: CapacityName(device.UID), Namespace: "default", Annotations: map[string]string{DeviceUIDAnnotation: string(device.UID), DeviceVersionAnnotation: device.ResourceVersion, OperationAnnotation: "operation-" + device.Name}}, Spec: metal.MachineCapacitySpec{DeviceRef: metal.LocalReference{Name: device.Name}, AllocationPolicy: "Disabled", ReclaimPolicy: "Retain"}} +} + +func requireDenied(t *testing.T, err error, message string) { + t.Helper() + if !apierrors.IsForbidden(err) || !strings.Contains(err.Error(), message) { + t.Fatalf("expected denial containing %q, got %v", message, err) } - denied.Store(false) - pendingDevice := device.DeepCopyObject().(*inventory.Device) - pendingDevice.Name, pendingDevice.UID, pendingDevice.ResourceVersion = "pending-hardware", "", "" - pendingDevice.Spec.Identity.Serial = "pending-serial" - pendingDevice.Spec.Identity.SystemUUID = "22222222-2222-2222-2222-222222222222" - if err := actor.Create(ctx, pendingDevice); err != nil { +} + +func TestRegistrationAgainstLiveDevices(t *testing.T) { + api := startAPI(t) + ctx := context.Background() + server := api.device("server", "default", "serial-1", "11111111-1111-1111-1111-111111111111") + duplicateA := api.device("duplicate-a", "default", "Shared-Serial", "22222222-2222-2222-2222-222222222222") + duplicateB := api.device("duplicate-b", "default", " shared-serial", "33333333-3333-3333-3333-333333333333") + legacyBacked := api.device("legacy-backed", "default", "legacy-serial", "44444444-4444-4444-4444-444444444444") + limitedTarget := api.device("limited-target", "default", "limited-serial", "55555555-5555-5555-5555-555555555555") + // Capacity that existed before registration admission was installed. + legacy := &metal.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: "legacy-record", Namespace: "default"}, Spec: metal.MachineCapacitySpec{DeviceRef: metal.LocalReference{Name: legacyBacked.Name}, AllocationPolicy: "Disabled", ReclaimPolicy: "Retain"}} + if err := api.admin.Create(ctx, legacy); err != nil { t.Fatal(err) } - pendingRequest := registrationRequest(t, pendingDevice, "admitted-never-persisted") - var pendingCapacity metal.MachineCapacity - _ = json.Unmarshal(pendingRequest.Object.Raw, &pendingCapacity) - completed := make(chan error, 1) - go func() { completed <- actor.Create(ctx, &pendingCapacity) }() - select { - case <-lateAdmission: - case <-time.After(10 * time.Second): - t.Fatal("admission did not reach pause") - } - if err := handler.ApplyControl(ctx, controlFor(t, handler, privateKey, "expand")); err != nil { - close(release) + // The limited caller may create capacity but may not read Devices. + if err := api.admin.Create(ctx, &rbacv1.Role{ObjectMeta: metav1.ObjectMeta{Name: "capacity-creator", Namespace: "default"}, Rules: []rbacv1.PolicyRule{{APIGroups: []string{"metal.datumapis.com"}, Resources: []string{"machinecapacities"}, Verbs: []string{"create"}}}}); err != nil { t.Fatal(err) } - close(release) - if err := <-completed; !apierrors.IsForbidden(err) { - t.Fatal("expected later admission failure", err) - } - if err := handler.Recover(ctx); err != nil { + if err := api.admin.Create(ctx, &rbacv1.RoleBinding{ObjectMeta: metav1.ObjectMeta{Name: "capacity-creator", Namespace: "default"}, RoleRef: rbacv1.RoleRef{APIGroup: "rbac.authorization.k8s.io", Kind: "Role", Name: "capacity-creator"}, Subjects: []rbacv1.Subject{{APIGroup: "rbac.authorization.k8s.io", Kind: "User", Name: "limited"}}}); err != nil { t.Fatal(err) } - _, retained, err := handler.Store.Read(ctx) - if err != nil || len(retained.Entries) != 2 { - t.Fatal("lost pending public create", err) - } - for _, entry := range retained.Entries { - if entry.Name == pendingCapacity.Name && entry.Outcome != "Unknown" { - t.Fatal("absent object became free or recorded") + webhook := api.installWebhook() + operator := api.actor("operator", "system:masters") + + t.Run("duplicate alias across two live Devices is denied", func(t *testing.T) { + for _, device := range []*inventory.Device{duplicateA, duplicateB} { + requireDenied(t, operator.Create(ctx, api.registration(device)), "shares recorded hardware identity") } - } - duplicateRequest := registrationRequest(t, pendingDevice, "after-expansion") - var duplicateCapacity metal.MachineCapacity - _ = json.Unmarshal(duplicateRequest.Object.Raw, &duplicateCapacity) - if err := actor.Create(ctx, &duplicateCapacity); !apierrors.IsForbidden(err) { - t.Fatal("expansion orphaned aliases", err) - } - _, route, err := handler.Store.root(ctx) - if err != nil { + }) + t.Run("missing Device is denied", func(t *testing.T) { + missing := &metal.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: CapacityName("9d0c3c2e-1f5b-4f37-9e43-2f5c6a1b7d80"), Namespace: "default", Annotations: map[string]string{DeviceUIDAnnotation: "9d0c3c2e-1f5b-4f37-9e43-2f5c6a1b7d80", DeviceVersionAnnotation: "1", OperationAnnotation: "missing"}}, Spec: metal.MachineCapacitySpec{DeviceRef: metal.LocalReference{Name: "never-recorded"}, AllocationPolicy: "Disabled", ReclaimPolicy: "Retain"}} + requireDenied(t, operator.Create(ctx, missing), "does not exist") + }) + t.Run("unauthorized caller is denied", func(t *testing.T) { + limited := api.actor("limited") + requireDenied(t, limited.Create(ctx, api.registration(limitedTarget)), "permission on devices is required") + outsider := api.actor("outsider") + if err := outsider.Create(ctx, api.registration(limitedTarget)); !apierrors.IsForbidden(err) { + t.Fatalf("caller without capacity permission: %v", err) + } + if api.exists(api.registration(limitedTarget)) { + t.Fatal("unauthorized registration persisted") + } + }) + t.Run("authored names cannot bypass one capacity per Device", func(t *testing.T) { + authored := api.registration(server) + authored.Name = "authored-name" + requireDenied(t, operator.Create(ctx, authored), "derived from the selected Device UID") + }) + t.Run("legacy capacity already backing the Device is refused", func(t *testing.T) { + requireDenied(t, operator.Create(ctx, api.registration(legacyBacked)), "already backs capacity legacy-record") + }) + t.Run("concurrent registrations of one Device persist once", func(t *testing.T) { + var workers sync.WaitGroup + results := make(chan error, 8) + for range 8 { + capacity := api.registration(server) + workers.Add(1) + go func() { + defer workers.Done() + results <- operator.Create(ctx, capacity) + }() + } + workers.Wait() + close(results) + wins := 0 + for err := range results { + switch { + case err == nil: + wins++ + case apierrors.IsAlreadyExists(err) || (apierrors.IsForbidden(err) && strings.Contains(err.Error(), "already backs capacity")): + default: + t.Fatalf("unexpected registration failure: %v", err) + } + } + if wins != 1 { + t.Fatalf("wanted exactly one persisted registration, got %d", wins) + } + }) + t.Run("a second capacity for the same Device is refused", func(t *testing.T) { + // Admission sees the existing capacity first; if two creates race past + // it, the derived name makes the API server reject the second. + if err := operator.Create(ctx, api.registration(server)); !apierrors.IsAlreadyExists(err) && (!apierrors.IsForbidden(err) || !strings.Contains(err.Error(), "already backs capacity")) { + t.Fatalf("second capacity under the derived name: %v", err) + } + var capacities metal.MachineCapacityList + if err := api.admin.List(ctx, &capacities); err != nil { + t.Fatal(err) + } + bound := 0 + for _, capacity := range capacities.Items { + if capacity.Spec.DeviceRef.Name == server.Name { + bound++ + } + } + if bound != 1 { + t.Fatalf("Device backs %d capacities", bound) + } + }) + t.Run("without the component Device DELETE is allowed and its capacity stays Disabled", func(t *testing.T) { + registered := api.registration(server) + if err := api.admin.Get(ctx, client.ObjectKeyFromObject(registered), registered); err != nil { + t.Fatal(err) + } + if err := api.admin.Delete(ctx, server); err != nil { + t.Fatalf("Device deletion without the component: %v", err) + } + if api.exists(server) { + t.Fatal("Device survived deletion without the component") + } + if err := api.admin.Get(ctx, client.ObjectKeyFromObject(registered), registered); err != nil || registered.Spec.AllocationPolicy != "Disabled" { + t.Fatalf("orphaned capacity is not Disabled: %v", err) + } + registered.Spec.AllocationPolicy = "Enabled" + registered.Spec.CleaningPolicyRef.Name = "invented-policy" + if err := operator.Update(ctx, registered); !apierrors.IsForbidden(err) || !strings.Contains(err.Error(), "mutation and deletion are disabled") { + t.Fatalf("orphaned capacity was enabled: %v", err) + } + if err := operator.Delete(ctx, registered); !apierrors.IsForbidden(err) { + t.Fatalf("orphaned capacity was deleted: %v", err) + } + replacement := api.device("server", "default", "replacement-serial", "66666666-6666-6666-6666-666666666666") + requireDenied(t, operator.Create(ctx, api.registration(replacement)), "already backs capacity") + }) + + cascade := &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "cascade"}} + if err := api.admin.Create(ctx, cascade); err != nil { t.Fatal(err) } - segment := &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: route.Segments[0].Name, Namespace: "fleet-system-private"}} - if err := api.Delete(ctx, segment); !apierrors.IsInvalid(err) && !apierrors.IsForbidden(err) { - t.Fatal("segment deletion bypass", err) - } - if err := private.Delete(ctx, segment); !apierrors.IsInvalid(err) && !apierrors.IsForbidden(err) { - t.Fatal("service segment deletion bypass", err) - } - downgrade, _, err := handler.Store.Read(ctx) - if err != nil { + cascaded := api.device("cascaded", "cascade", "cascade-serial", "77777777-7777-7777-7777-777777777777") + sibling := &corev1.ConfigMap{ObjectMeta: metav1.ObjectMeta{Name: "sibling", Namespace: "cascade"}} + if err := api.admin.Create(ctx, sibling); err != nil { t.Fatal(err) } - delete(downgrade.Data, "routing.json") - if err := private.Update(ctx, downgrade); !apierrors.IsInvalid(err) && !apierrors.IsForbidden(err) { - t.Fatal("v2 format downgrade bypass", err) - } - for _, name := range []string{"arbitrary-credential", LedgerName, SegmentPrefix + "mutable"} { - probe := &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Namespace: "fleet-system-private", Name: name}} - if err := private.Create(ctx, probe); !apierrors.IsInvalid(err) && !apierrors.IsForbidden(err) { - t.Fatal("service create boundary bypass", name, err) + api.installDeletionProtection(duplicateA) + + t.Run("installed component denies Device DELETE for every caller", func(t *testing.T) { + for _, caller := range []client.Client{api.admin, operator} { + if err := caller.Delete(ctx, duplicateA); !apierrors.IsForbidden(err) || !strings.Contains(err.Error(), "cannot be deleted") { + t.Fatalf("Device deletion: %v", err) + } } - } + if !api.exists(duplicateA) { + t.Fatal("Device removed despite deletion protection") + } + }) + t.Run("deletecollection is denied per Device", func(t *testing.T) { + if err := api.admin.DeleteAllOf(ctx, &inventory.Device{}, client.InNamespace("default")); !apierrors.IsForbidden(err) { + t.Fatalf("deletecollection: %v", err) + } + for _, device := range []*inventory.Device{duplicateA, duplicateB, legacyBacked, limitedTarget} { + if !api.exists(device) { + t.Fatalf("deletecollection removed %s", device.Name) + } + } + }) + t.Run("namespace deletion stays Terminating with its Devices", func(t *testing.T) { + if err := api.admin.Delete(ctx, cascade); err != nil { + t.Fatal(err) + } + // envtest runs no namespace controller. Issue the same content + // deletions the controller would: deletecollection, then per item. + if err := api.admin.DeleteAllOf(ctx, &corev1.ConfigMap{}, client.InNamespace("cascade")); err != nil { + t.Fatal(err) + } + if err := api.admin.DeleteAllOf(ctx, &inventory.Device{}, client.InNamespace("cascade")); !apierrors.IsForbidden(err) { + t.Fatalf("namespace cascade deletecollection: %v", err) + } + if err := api.admin.Delete(ctx, cascaded); !apierrors.IsForbidden(err) { + t.Fatalf("namespace cascade item deletion: %v", err) + } + if !api.exists(cascaded) || api.exists(sibling) { + t.Fatal("cascade must stop at Devices while other content drains") + } + if !api.exists(cascade) || cascade.DeletionTimestamp.IsZero() { + t.Fatal("namespace must remain Terminating") + } + }) + t.Run("webhook outage blocks only capacity writes", func(t *testing.T) { + webhook.Close() + other := api.device("outage-device", "default", "outage-serial", "88888888-8888-8888-8888-888888888888") + other.Labels = map[string]string{"edited": "true"} + if err := api.admin.Update(ctx, other); err != nil { + t.Fatalf("Device update during outage: %v", err) + } + capacity := api.registration(other) + if err := operator.Create(ctx, capacity); err == nil { + t.Fatal("capacity registration admitted without the webhook") + } + if api.exists(capacity) { + t.Fatal("capacity persisted during outage") + } + }) } diff --git a/internal/registration/fence.go b/internal/registration/fence.go deleted file mode 100644 index 3cb3fa9c..00000000 --- a/internal/registration/fence.go +++ /dev/null @@ -1,75 +0,0 @@ -package registration - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "reflect" - "slices" - - iam "go.miloapis.com/milo/pkg/apis/iam/v1alpha1" - admissionv1 "k8s.io/api/admissionregistration/v1" - "sigs.k8s.io/controller-runtime/pkg/client" -) - -func requiredFences(projects []string) []admissionv1.ValidatingWebhook { - names, _ := json.Marshal(projects) - projectContext := fmt.Sprintf("has(request.userInfo.extra) && %q in request.userInfo.extra && request.userInfo.extra[%q] == ['Project'] && %q in request.userInfo.extra && request.userInfo.extra[%q] == ['resourcemanager.miloapis.com'] && %q in request.userInfo.extra && size(request.userInfo.extra[%q]) == 1 && request.userInfo.extra[%q][0] != ''", iam.ParentKindExtraKey, iam.ParentKindExtraKey, iam.ParentAPIGroupExtraKey, iam.ParentAPIGroupExtraKey, iam.ParentNameExtraKey, iam.ParentNameExtraKey, iam.ParentNameExtraKey) - protectedContext := fmt.Sprintf("!(%s) || request.userInfo.extra[%q][0] in %s", projectContext, iam.ParentNameExtraKey, names) - namespaced, cluster := admissionv1.NamespacedScope, admissionv1.ClusterScope - writes := []admissionv1.OperationType{admissionv1.Create, admissionv1.Update, admissionv1.Delete} - return []admissionv1.ValidatingWebhook{ - {Name: "registration.fleet.datumapis.com", Rules: []admissionv1.RuleWithOperations{{Operations: writes, Rule: admissionv1.Rule{APIGroups: []string{"metal.datumapis.com"}, APIVersions: []string{"v1alpha1"}, Resources: []string{"machinecapacities", "machinecapacities/status"}, Scope: &namespaced}}}}, - {Name: "inventory.registration.fleet.datumapis.com", Rules: []admissionv1.RuleWithOperations{{Operations: writes, Rule: admissionv1.Rule{APIGroups: []string{"fleet.datumapis.com"}, APIVersions: []string{"v1alpha1"}, Resources: []string{"devices", "devices/status"}, Scope: &namespaced}}}, MatchConditions: []admissionv1.MatchCondition{{Name: "provider-project-context", Expression: protectedContext}}}, - {Name: "namespace.registration.fleet.datumapis.com", Rules: []admissionv1.RuleWithOperations{{Operations: []admissionv1.OperationType{admissionv1.Delete}, Rule: admissionv1.Rule{APIGroups: []string{""}, APIVersions: []string{"v1"}, Resources: []string{"namespaces"}, Scope: &cluster}}}, MatchConditions: []admissionv1.MatchCondition{{Name: "provider-project-context", Expression: protectedContext}, {Name: "inventory-namespace", Expression: "!has(request.name) || request.name == '' || request.name == 'default'"}}}, - {Name: "project.registration.fleet.datumapis.com", Rules: []admissionv1.RuleWithOperations{{Operations: []admissionv1.OperationType{admissionv1.Delete}, Rule: admissionv1.Rule{APIGroups: []string{"resourcemanager.miloapis.com"}, APIVersions: []string{"v1alpha1"}, Resources: []string{"projects"}, Scope: &cluster}}}, MatchConditions: []admissionv1.MatchCondition{{Name: "provider-project-name", Expression: "!has(request.name) || request.name == '' || request.name in " + string(names)}}}, - } -} - -func VerifyFence(ctx context.Context, reader client.Reader, projects []string) error { - _, err := VerifiedFenceDigest(ctx, reader, projects) - return err -} - -func VerifiedFenceDigest(ctx context.Context, reader client.Reader, projects []string) (string, error) { - var configuration admissionv1.ValidatingWebhookConfiguration - if err := reader.Get(ctx, client.ObjectKey{Name: "fleet-capacity-registration"}, &configuration); err != nil { - return "", errors.New("project-plane registration admission configuration is unavailable") - } - if err := verifyFenceConfiguration(configuration, projects); err != nil { - return "", err - } - encoded, err := json.Marshal(configuration.Webhooks) - return digest(encoded), err -} - -func verifyFenceConfiguration(configuration admissionv1.ValidatingWebhookConfiguration, projects []string) error { - if len(projects) == 0 || slices.Contains(projects, "") || !slices.IsSorted(projects) || len(slices.Compact(slices.Clone(projects))) != len(projects) { - return errors.New("registration admission requires the exact sorted provider scope") - } - if !configuration.DeletionTimestamp.IsZero() { - return errors.New("registration admission configuration is deleting") - } - required := requiredFences(projects) - if len(configuration.Webhooks) != len(required) { - return errors.New("registration admission requires separate capacity, inventory, namespace and project fences") - } - for _, expected := range required { - index := slices.IndexFunc(configuration.Webhooks, func(webhook admissionv1.ValidatingWebhook) bool { return webhook.Name == expected.Name }) - if index < 0 { - return errors.New("registration admission webhook is missing") - } - webhook := configuration.Webhooks[index] - if webhook.FailurePolicy == nil || *webhook.FailurePolicy != admissionv1.Fail || webhook.SideEffects == nil || *webhook.SideEffects != admissionv1.SideEffectClassNoneOnDryRun || webhook.MatchPolicy == nil || *webhook.MatchPolicy != admissionv1.Equivalent || !slices.Contains(webhook.AdmissionReviewVersions, "v1") || (webhook.NamespaceSelector != nil && (len(webhook.NamespaceSelector.MatchLabels) != 0 || len(webhook.NamespaceSelector.MatchExpressions) != 0)) || (webhook.ObjectSelector != nil && (len(webhook.ObjectSelector.MatchLabels) != 0 || len(webhook.ObjectSelector.MatchExpressions) != 0)) || len(webhook.ClientConfig.CABundle) == 0 { - return errors.New("registration admission must be fail-closed, without label selectors, and have an explicit serving CA") - } - if !reflect.DeepEqual(webhook.Rules, expected.Rules) || !slices.Equal(webhook.MatchConditions, expected.MatchConditions) { - return errors.New("registration admission rules and trusted-context conditions must exactly match the retained provider scope") - } - if !reflect.DeepEqual(webhook.ClientConfig, configuration.Webhooks[0].ClientConfig) { - return errors.New("registration fences must use the same authenticated authority endpoint") - } - } - return nil -} diff --git a/internal/registration/fence_test.go b/internal/registration/fence_test.go deleted file mode 100644 index 6aa89617..00000000 --- a/internal/registration/fence_test.go +++ /dev/null @@ -1,113 +0,0 @@ -package registration - -import ( - "context" - "os" - "testing" - - admissionv1 "k8s.io/api/admissionregistration/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "sigs.k8s.io/controller-runtime/pkg/client/fake" - "sigs.k8s.io/yaml" -) - -func TestPackagedProjectAdmissionFence(t *testing.T) { - data, err := os.ReadFile("../../config/components/registration-admission/webhook.yaml") - if err != nil { - t.Fatal(err) - } - var configured admissionv1.ValidatingWebhookConfiguration - if err := yaml.UnmarshalStrict(data, &configured); err != nil { - t.Fatal(err) - } - for index := range configured.Webhooks { - configured.Webhooks[index].ClientConfig.CABundle = []byte("environment-owned-serving-ca") - } - for _, test := range []struct { - name string - mutate func(*admissionv1.ValidatingWebhookConfiguration) - allowed bool - }{ - {"complete", func(*admissionv1.ValidatingWebhookConfiguration) {}, true}, - {"incomplete deployment", func(configuration *admissionv1.ValidatingWebhookConfiguration) { - configuration.Webhooks = configuration.Webhooks[:1] - }, false}, - {"no serving CA", func(configuration *admissionv1.ValidatingWebhookConfiguration) { - configuration.Webhooks[0].ClientConfig.CABundle = nil - }, false}, - {"fail open", func(configuration *admissionv1.ValidatingWebhookConfiguration) { - policy := admissionv1.Ignore - configuration.Webhooks[0].FailurePolicy = &policy - }, false}, - {"missing Device protection", func(configuration *admissionv1.ValidatingWebhookConfiguration) { - configuration.Webhooks[1].Rules = nil - }, false}, - {"global inventory blast radius", func(configuration *admissionv1.ValidatingWebhookConfiguration) { - configuration.Webhooks[1].MatchConditions = nil - }, false}, - {"broadened inventory rule", func(configuration *admissionv1.ValidatingWebhookConfiguration) { - configuration.Webhooks[0].Rules = append(configuration.Webhooks[0].Rules, configuration.Webhooks[1].Rules...) - }, false}, - {"wrong retained project scope", func(configuration *admissionv1.ValidatingWebhookConfiguration) { - configuration.Webhooks[1].MatchConditions = requiredFences([]string{"different"})[1].MatchConditions - }, false}, - {"namespace name omitted", func(configuration *admissionv1.ValidatingWebhookConfiguration) { - configuration.Webhooks[2].MatchConditions = configuration.Webhooks[2].MatchConditions[:1] - }, false}, - {"global project deletion blast radius", func(configuration *admissionv1.ValidatingWebhookConfiguration) { - configuration.Webhooks[3].MatchConditions = nil - }, false}, - {"caller label condition", func(configuration *admissionv1.ValidatingWebhookConfiguration) { - configuration.Webhooks[1].MatchConditions[0].Expression = "object.metadata.labels['provider'] == 'datum-cloud'" - }, false}, - {"Device status protection omitted", func(configuration *admissionv1.ValidatingWebhookConfiguration) { - configuration.Webhooks[1].Rules[0].Resources = []string{"devices"} - }, false}, - {"inventory fail open", func(configuration *admissionv1.ValidatingWebhookConfiguration) { - policy := admissionv1.Ignore - configuration.Webhooks[1].FailurePolicy = &policy - }, false}, - {"capacity exemption", func(configuration *admissionv1.ValidatingWebhookConfiguration) { - configuration.Webhooks[0].MatchConditions = configuration.Webhooks[1].MatchConditions - }, false}, - {"split authority", func(configuration *admissionv1.ValidatingWebhookConfiguration) { - other := "https://another.invalid/webhook" - configuration.Webhooks[1].ClientConfig.URL = &other - }, false}, - {"caller annotation selector", func(configuration *admissionv1.ValidatingWebhookConfiguration) { - configuration.Webhooks[0].ObjectSelector = &metav1.LabelSelector{MatchLabels: map[string]string{"registration": "true"}} - }, false}, - } { - t.Run(test.name, func(t *testing.T) { - configuration := configured.DeepCopy() - test.mutate(configuration) - scheme := runtime.NewScheme() - if err := admissionv1.AddToScheme(scheme); err != nil { - t.Fatal(err) - } - api := fake.NewClientBuilder().WithScheme(scheme).WithObjects(configuration).Build() - if err := VerifyFence(context.Background(), api, []string{"datum-cloud"}); (err == nil) != test.allowed { - t.Fatalf("unexpected fence result: %v", err) - } - }) - } -} - -func TestIncompleteFenceDeniesRegistrationWithoutReservation(t *testing.T) { - handler, device := fixture(t) - scheme := runtime.NewScheme() - if err := admissionv1.AddToScheme(scheme); err != nil { - t.Fatal(err) - } - configuration := &admissionv1.ValidatingWebhookConfiguration{ObjectMeta: metav1.ObjectMeta{Name: "fleet-capacity-registration"}} - api := fake.NewClientBuilder().WithScheme(scheme).WithObjects(configuration).Build() - handler.VerifyFence = func(ctx context.Context) error { return VerifyFence(ctx, api, handler.Store.Projects) } - if handler.Handle(context.Background(), registrationRequest(t, device, "incomplete")).Allowed { - t.Fatal("incomplete admission deployment admitted registration") - } - _, ledger, err := handler.Store.Read(context.Background()) - if err != nil || len(ledger.Entries) != 0 { - t.Fatalf("incomplete fence changed registration state: %+v %v", ledger, err) - } -} diff --git a/internal/registration/ledger.go b/internal/registration/ledger.go deleted file mode 100644 index eec32ac5..00000000 --- a/internal/registration/ledger.go +++ /dev/null @@ -1,106 +0,0 @@ -package registration - -import ( - "context" - "crypto/ed25519" - "encoding/json" - "errors" - "reflect" - - authenticationv1 "k8s.io/api/authentication/v1" - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/types" - "sigs.k8s.io/controller-runtime/pkg/client" -) - -const LedgerName = "fleet-capacity-registration-v1" - -var ErrConflict = errors.New("registration conflicts with retained identity or an unknown operation; operator reconciliation is required") - -type Entry struct { - Operation types.UID `json:"operation"` - Actor authenticationv1.UserInfo `json:"actor"` - Project string `json:"project"` - ProjectUID types.UID `json:"projectUID"` - NamespaceUID types.UID `json:"namespaceUID"` - Name string `json:"name"` - CapacityUID types.UID `json:"capacityUID"` - DeviceName string `json:"deviceName"` - DeviceUID types.UID `json:"deviceUID"` - DeviceVersion string `json:"deviceVersion"` - Aliases []string `json:"aliases"` - AssetID string `json:"assetID"` - Input json.RawMessage `json:"input"` - Outcome string `json:"outcome"` -} - -type DeviceFence struct { - Project string `json:"project"` - ProjectUID types.UID `json:"projectUID,omitempty"` - Namespace string `json:"namespace,omitempty"` - NamespaceUID types.UID `json:"namespaceUID,omitempty"` - Name string `json:"name,omitempty"` - UID types.UID `json:"uid"` - Aliases []string `json:"aliases,omitempty"` - Deleted bool `json:"deleted,omitempty"` - Version string `json:"version,omitempty"` -} - -type Ledger struct { - Authority string `json:"authority"` - Projects []string `json:"projects"` - Entries []Entry `json:"entries"` - DeviceFences []DeviceFence `json:"deviceFences"` -} - -type Store struct { - Client client.Client - Namespace string - Authority string - Projects []string - ControlKey ed25519.PublicKey - // AllowInactiveForTests skips the signed activation gate. The zero value - // is gated; production wiring forces it off. - AllowInactiveForTests bool -} - -func (store Store) Read(ctx context.Context) (*corev1.Secret, Ledger, error) { - secret := &corev1.Secret{} - if err := store.Client.Get(ctx, client.ObjectKey{Namespace: store.Namespace, Name: LedgerName}, secret); err != nil { - return nil, Ledger{}, err - } - ledger, _, err := store.readSnapshot(ctx, secret) - if err != nil { - return nil, Ledger{}, err - } - if secret.UID == "" || !secret.DeletionTimestamp.IsZero() || ledger.Authority != store.Authority || !reflect.DeepEqual(ledger.Projects, store.Projects) { - return nil, Ledger{}, errors.New("registration ledger lifetime or configured scope is unavailable") - } - return secret, ledger, nil -} - -func (store Store) Write(ctx context.Context, secret *corev1.Secret, ledger Ledger) error { - if _, exists := secret.Data["routing.json"]; exists { - return store.writeSnapshot(ctx, secret, ledger) - } - encoded, err := json.Marshal(ledger) - if err != nil { - return err - } - if len(encoded) > TailBudget { - return errors.New("registration ledger is full; sign an expand control request to seal it losslessly, see docs/development/registration-storage-rollout.md; reservations were not released") - } - secret.Data["ledger.json"] = encoded - return store.Client.Update(ctx, secret) -} - -func overlaps(left, right []string) bool { - for _, first := range left { - for _, second := range right { - if first == second { - return true - } - } - } - return false -} diff --git a/internal/registration/manifest_test.go b/internal/registration/manifest_test.go new file mode 100644 index 00000000..8c981b23 --- /dev/null +++ b/internal/registration/manifest_test.go @@ -0,0 +1,40 @@ +package registration + +import ( + "os" + "slices" + "testing" + + admissionregistrationv1 "k8s.io/api/admissionregistration/v1" + "sigs.k8s.io/yaml" +) + +// The packaged webhook is the only gate on capacity writes, so it must stay +// fail-closed over every capacity write and must not reach anything else. +func TestPackagedWebhookFencesOnlyCapacityWrites(t *testing.T) { + data, err := os.ReadFile("../../config/components/registration-admission/webhook.yaml") + if err != nil { + t.Fatal(err) + } + var configuration admissionregistrationv1.ValidatingWebhookConfiguration + if err := yaml.UnmarshalStrict(data, &configuration); err != nil { + t.Fatal(err) + } + if len(configuration.Webhooks) != 1 { + t.Fatalf("want one capacity webhook, got %d", len(configuration.Webhooks)) + } + webhook := configuration.Webhooks[0] + if webhook.FailurePolicy == nil || *webhook.FailurePolicy != admissionregistrationv1.Fail || webhook.SideEffects == nil || *webhook.SideEffects != admissionregistrationv1.SideEffectClassNone || webhook.MatchPolicy == nil || *webhook.MatchPolicy != admissionregistrationv1.Equivalent { + t.Fatal("capacity webhook must fail closed, be side-effect free and match equivalent versions") + } + if webhook.NamespaceSelector != nil || webhook.ObjectSelector != nil || len(webhook.MatchConditions) != 0 { + t.Fatal("capacity webhook must not be narrowed by selectors or conditions") + } + if len(webhook.Rules) != 1 { + t.Fatal("capacity webhook must have exactly one rule") + } + rule := webhook.Rules[0] + if !slices.Equal(rule.APIGroups, []string{"metal.datumapis.com"}) || !slices.Equal(rule.Resources, []string{"machinecapacities", "machinecapacities/status"}) || !slices.Equal(rule.Operations, []admissionregistrationv1.OperationType{admissionregistrationv1.Create, admissionregistrationv1.Update, admissionregistrationv1.Delete}) { + t.Fatalf("capacity webhook rule drifted: %+v", rule) + } +} diff --git a/internal/registration/namespace_lifetime_test.go b/internal/registration/namespace_lifetime_test.go deleted file mode 100644 index ff2270e0..00000000 --- a/internal/registration/namespace_lifetime_test.go +++ /dev/null @@ -1,167 +0,0 @@ -package registration - -import ( - "context" - "encoding/json" - "testing" - - inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" - iam "go.miloapis.com/milo/pkg/apis/iam/v1alpha1" - admissionv1 "k8s.io/api/admission/v1" - authenticationv1 "k8s.io/api/authentication/v1" - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/types" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/webhook/admission" -) - -// terminatingDevice creates a Device in a provider-project namespace other -// than default, records its fence while the namespace is live, and then -// deletes the namespace while a finalizer still holds it in Terminating. -func terminatingDevice(t *testing.T, handler *Handler, name, uuid string) (Project, *inventory.Device) { - t.Helper() - ctx := context.Background() - project, _ := handler.Resolve(ctx, "provider") - namespace := &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "decommissioned-" + name, UID: types.UID("namespace-" + name), Finalizers: []string{"synthetic.example/hold"}}} - if err := project.Client.Create(ctx, namespace); err != nil { - t.Fatal(err) - } - device := &inventory.Device{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: namespace.Name, UID: types.UID("device-" + name)}, Spec: inventory.DeviceSpec{Identity: inventory.DeviceIdentity{Serial: "SERIAL-" + name, SystemUUID: uuid, Model: "test"}}} - if err := project.Client.Create(ctx, device); err != nil { - t.Fatal(err) - } - if response := handler.Handle(ctx, deviceRequest(t, admissionv1.Create, nil, device)); !response.Allowed { - t.Fatalf("live namespace Device create denied: %s", response.Result.Message) - } - if err := project.Client.Delete(ctx, namespace); err != nil { - t.Fatal(err) - } - if err := project.Client.Get(ctx, client.ObjectKeyFromObject(namespace), namespace); err != nil || namespace.DeletionTimestamp.IsZero() { - t.Fatalf("namespace is not terminating: %v", err) - } - return project, device -} - -func deviceRequest(t *testing.T, operation admissionv1.Operation, old, current *inventory.Device) admission.Request { - t.Helper() - request := admission.Request{AdmissionRequest: admissionv1.AdmissionRequest{UID: types.UID("device-request-" + string(operation)), Operation: operation, Resource: metav1.GroupVersionResource{Group: "fleet.datumapis.com", Version: "v1alpha1", Resource: "devices"}, UserInfo: authenticationv1.UserInfo{Username: "operator", UID: "actor-1", Extra: map[string]authenticationv1.ExtraValue{iam.ParentKindExtraKey: {"Project"}, iam.ParentAPIGroupExtraKey: {"resourcemanager.miloapis.com"}, iam.ParentNameExtraKey: {"provider"}}}}} - for _, pair := range []struct { - device *inventory.Device - raw *runtime.RawExtension - }{{old, &request.OldObject}, {current, &request.Object}} { - if pair.device == nil { - continue - } - encoded, err := json.Marshal(pair.device) - if err != nil { - t.Fatal(err) - } - pair.raw.Raw = encoded - request.Name, request.Namespace = pair.device.Name, pair.device.Namespace - } - return request -} - -func retainedFence(t *testing.T, handler *Handler, uid types.UID) DeviceFence { - t.Helper() - _, ledger, err := handler.Store.Read(context.Background()) - if err != nil { - t.Fatal(err) - } - var found []DeviceFence - for _, fence := range ledger.DeviceFences { - if fence.UID == uid { - found = append(found, fence) - } - } - if len(found) != 1 { - t.Fatalf("expected one retained fence for %s: %+v", uid, ledger.DeviceFences) - } - return found[0] -} - -func TestDeviceDeleteInTerminatingNamespaceRetainsTombstone(t *testing.T) { - ctx := context.Background() - handler, _ := fixture(t) - _, device := terminatingDevice(t, handler, "retired", "22222222-2222-2222-2222-222222222222") - created := retainedFence(t, handler, device.UID) - if created.NamespaceUID == "" || len(created.Aliases) == 0 { - t.Fatalf("create did not record namespace lifetime and aliases: %+v", created) - } - if response := handler.Handle(ctx, deviceRequest(t, admissionv1.Delete, device, nil)); !response.Allowed { - t.Fatalf("Device delete in a terminating namespace was denied, so the namespace cannot finish terminating: %s", response.Result.Message) - } - tombstone := retainedFence(t, handler, device.UID) - if !tombstone.Deleted || tombstone.NamespaceUID != created.NamespaceUID || tombstone.Version != "" || !preservesReservations(Ledger{DeviceFences: []DeviceFence{created}}, Ledger{DeviceFences: []DeviceFence{tombstone}}) { - t.Fatalf("tombstone lost retained lifetime: before %+v after %+v", created, tombstone) - } - recreated := device.DeepCopyObject().(*inventory.Device) - recreated.Namespace, recreated.UID = "default", "recreated" - if handler.Handle(ctx, deviceRequest(t, admissionv1.Create, nil, recreated)).Allowed { - t.Fatal("deleted hardware aliases were released by the terminating namespace path") - } -} - -func TestDeviceDeleteAfterNamespaceRemovalUsesRecordedLifetime(t *testing.T) { - ctx := context.Background() - handler, _ := fixture(t) - project, device := terminatingDevice(t, handler, "removed", "33333333-3333-3333-3333-333333333333") - created := retainedFence(t, handler, device.UID) - namespace := &corev1.Namespace{} - if err := project.Client.Get(ctx, client.ObjectKey{Name: device.Namespace}, namespace); err != nil { - t.Fatal(err) - } - namespace.Finalizers = nil - if err := project.Client.Update(ctx, namespace); err != nil { - t.Fatal(err) - } - if err := project.Client.Get(ctx, client.ObjectKeyFromObject(namespace), namespace); err == nil { - t.Fatal("namespace was not removed") - } - if response := handler.Handle(ctx, deviceRequest(t, admissionv1.Delete, device, nil)); !response.Allowed { - t.Fatalf("Device delete after namespace removal was denied: %s", response.Result.Message) - } - tombstone := retainedFence(t, handler, device.UID) - if !tombstone.Deleted || tombstone.NamespaceUID != created.NamespaceUID || !preservesReservations(Ledger{DeviceFences: []DeviceFence{created}}, Ledger{DeviceFences: []DeviceFence{tombstone}}) { - t.Fatalf("tombstone did not keep the recorded namespace lifetime: before %+v after %+v", created, tombstone) - } -} - -func TestDeviceFinalizerRemovalInTerminatingNamespaceRetainsTombstone(t *testing.T) { - ctx := context.Background() - handler, _ := fixture(t) - project, device := terminatingDevice(t, handler, "finalized", "44444444-4444-4444-4444-444444444444") - if err := project.Client.Get(ctx, client.ObjectKeyFromObject(device), device); err != nil { - t.Fatal(err) - } - device.Finalizers = []string{"synthetic.example/drain"} - if err := project.Client.Update(ctx, device); err != nil { - t.Fatal(err) - } - if err := project.Client.Delete(ctx, device); err != nil { - t.Fatal(err) - } - deleting := &inventory.Device{} - if err := project.Client.Get(ctx, client.ObjectKeyFromObject(device), deleting); err != nil || deleting.DeletionTimestamp.IsZero() { - t.Fatalf("Device is not deleting: %v", err) - } - if response := handler.Handle(ctx, deviceRequest(t, admissionv1.Delete, deleting, nil)); !response.Allowed { - t.Fatalf("Device delete in a terminating namespace was denied: %s", response.Result.Message) - } - released := deleting.DeepCopyObject().(*inventory.Device) - released.Finalizers = nil - if response := handler.Handle(ctx, deviceRequest(t, admissionv1.Update, deleting, released)); !response.Allowed { - t.Fatalf("finalizer removal in a terminating namespace was denied: %s", response.Result.Message) - } - tombstone := retainedFence(t, handler, device.UID) - if !tombstone.Deleted || tombstone.NamespaceUID == "" || len(tombstone.Aliases) == 0 { - t.Fatalf("finalizer removal lost the tombstone: %+v", tombstone) - } - edited := deleting.DeepCopyObject().(*inventory.Device) - edited.Finalizers, edited.Labels = nil, map[string]string{"edited": "true"} - if handler.Handle(ctx, deviceRequest(t, admissionv1.Update, deleting, edited)).Allowed { - t.Fatal("a non-finalizer edit was admitted without a live namespace") - } -} diff --git a/internal/registration/runtime.go b/internal/registration/runtime.go index 26ce2bff..f92434bf 100644 --- a/internal/registration/runtime.go +++ b/internal/registration/runtime.go @@ -2,28 +2,24 @@ package registration import ( "context" - "encoding/json" "errors" "fmt" - "reflect" - inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" - metal "go.datum.net/fleet/internal/api/v1alpha1" "go.datum.net/fleet/internal/manager" "go.datum.net/fleet/internal/projectdiscovery" authenticationv1 "k8s.io/api/authentication/v1" authorizationv1 "k8s.io/api/authorization/v1" - corev1 "k8s.io/api/core/v1" - apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/runtime" "k8s.io/client-go/rest" "sigs.k8s.io/controller-runtime/pkg/client" ) -func NewHandler(store Store, root client.Client, template *rest.Config, scheme *runtime.Scheme) *Handler { - store.AllowInactiveForTests = false - return &Handler{Store: store, VerifyFence: func(ctx context.Context) error { return VerifyFence(ctx, root, store.Projects) }, Resolve: func(ctx context.Context, name string) (Project, error) { - identity, err := manager.ResolveProjectIdentity(ctx, root, store.Authority, name) +// NewHandler wires the handler to Milo. The root client resolves Project +// lifetimes; the template is re-addressed to each provider project's control +// plane for uncached Device and capacity reads and SubjectAccessReviews. +func NewHandler(authority string, projects []string, root client.Client, template *rest.Config, scheme *runtime.Scheme) *Handler { + return &Handler{Projects: projects, Resolve: func(ctx context.Context, name string) (Project, error) { + identity, err := manager.ResolveProjectIdentity(ctx, root, authority, name) if err != nil { return Project{}, err } @@ -33,11 +29,12 @@ func NewHandler(store Store, root client.Client, template *rest.Config, scheme * } api, err := client.New(config, client.Options{Scheme: scheme}) return Project{Identity: identity, Client: api}, err - }, Authorize: Authorize, FenceDigest: func(ctx context.Context) (string, error) { - return VerifiedFenceDigest(ctx, root, store.Projects) - }} + }, Authorize: Authorize} } +// Authorize evaluates the caller's own permission with a SubjectAccessReview +// carrying the caller's username, UID, groups and extras. The service's +// credentials evaluate the review; they never stand in for the caller. func Authorize(ctx context.Context, project Project, actor authenticationv1.UserInfo, group, resource, name string) error { verb := "get" if resource == "machinecapacities" { @@ -47,7 +44,7 @@ func Authorize(ctx context.Context, project Project, actor authenticationv1.User for key, values := range actor.Extra { extra[key] = authorizationv1.ExtraValue(append([]string(nil), values...)) } - review := &authorizationv1.SubjectAccessReview{Spec: authorizationv1.SubjectAccessReviewSpec{User: actor.Username, UID: actor.UID, Groups: append([]string(nil), actor.Groups...), Extra: extra, ResourceAttributes: &authorizationv1.ResourceAttributes{Group: group, Resource: resource, Version: "v1alpha1", Namespace: "default", Verb: verb, Name: name}}} + review := &authorizationv1.SubjectAccessReview{Spec: authorizationv1.SubjectAccessReviewSpec{User: actor.Username, UID: actor.UID, Groups: append([]string(nil), actor.Groups...), Extra: extra, ResourceAttributes: &authorizationv1.ResourceAttributes{Group: group, Resource: resource, Version: "v1alpha1", Namespace: InventoryNamespace, Verb: verb, Name: name}}} if err := project.Client.Create(ctx, review); err != nil { return errors.New("current registration authorization is unavailable") } @@ -56,62 +53,3 @@ func Authorize(ctx context.Context, project Project, actor authenticationv1.User } return nil } - -func (handler *Handler) Recover(ctx context.Context) error { - secret, ledger, err := handler.Store.Read(ctx) - if err != nil { - return err - } - changed := false - var failures error - for index := range ledger.Entries { - entry := &ledger.Entries[index] - outcome, err := handler.observe(ctx, *entry) - failures = errors.Join(failures, err) - if entry.Outcome != outcome { - entry.Outcome = outcome - changed = true - } - } - if changed { - failures = errors.Join(failures, handler.Store.Write(ctx, secret, ledger)) - } - return failures -} - -func (handler *Handler) observe(ctx context.Context, entry Entry) (string, error) { - project, err := handler.Resolve(ctx, entry.Project) - if err != nil { - return "Unknown", err - } - if project.Identity.UID != entry.ProjectUID { - return "LifetimeLost", nil - } - var namespace corev1.Namespace - if err := project.Client.Get(ctx, client.ObjectKey{Name: "default"}, &namespace); err != nil && !apierrors.IsNotFound(err) { - return "Unknown", err - } - var device inventory.Device - if err := project.Client.Get(ctx, client.ObjectKey{Namespace: "default", Name: entry.DeviceName}, &device); err != nil && !apierrors.IsNotFound(err) { - return "Unknown", err - } - if namespace.UID != entry.NamespaceUID || !namespace.DeletionTimestamp.IsZero() || device.UID != entry.DeviceUID || !device.DeletionTimestamp.IsZero() || !reflect.DeepEqual(aliases(&device), entry.Aliases) { - return "LifetimeLost", nil - } - var current metal.MachineCapacity - err = project.Client.Get(ctx, client.ObjectKey{Namespace: "default", Name: entry.Name}, ¤t) - if apierrors.IsNotFound(err) { - return "Unknown", nil - } - if err != nil { - return "Unknown", err - } - var input metal.MachineCapacity - if err := json.Unmarshal(entry.Input, &input); err != nil { - return "Unknown", err - } - if current.UID != entry.CapacityUID || !reflect.DeepEqual(current.Spec, input.Spec) || !reflect.DeepEqual(current.Annotations, input.Annotations) || !reflect.DeepEqual(current.Labels, input.Labels) || !current.DeletionTimestamp.IsZero() { - return "IncarnationConflict", nil - } - return "Recorded", nil -} diff --git a/internal/registration/segments.go b/internal/registration/segments.go deleted file mode 100644 index 710c85fe..00000000 --- a/internal/registration/segments.go +++ /dev/null @@ -1,269 +0,0 @@ -package registration - -import ( - "context" - "crypto/sha256" - "encoding/hex" - "encoding/json" - "errors" - "fmt" - "reflect" - "slices" - - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/types" - "sigs.k8s.io/controller-runtime/pkg/client" -) - -const ( - TailBudget = 650000 - SegmentBudget = 750000 - MaxSegments = 16 - RootBudget = 850000 - SegmentPrefix = "fleet-registration-segment-" -) - -var ErrGrowthStopped = errors.New("registration growth stopped; signed lossless expansion required, reservations remain retained") - -// ErrSegmentsExhausted is the terminal growth stop: every sealed segment is in -// use, so expansion itself is refused. It still matches ErrGrowthStopped for -// callers that only distinguish stopped growth. -var ErrSegmentsExhausted error = segmentsExhausted{} - -type segmentsExhausted struct{} - -func (segmentsExhausted) Error() string { - return fmt.Sprintf("registration segments exhausted (%d of %d sealed); expansion is refused and a reviewed storage migration is required, see docs/development/registration-storage-rollout.md; reservations remain retained, do not raise caps or delete records", MaxSegments, MaxSegments) -} - -func (segmentsExhausted) Is(target error) bool { return target == ErrGrowthStopped } - -type Segment struct { - Name string `json:"name"` - UID types.UID `json:"uid"` - Digest string `json:"digest"` -} - -type Routing struct { - Version int `json:"version"` - Epoch uint64 `json:"epoch"` - RootUID types.UID `json:"rootUID"` - Segments []Segment `json:"segments"` - Pending *SignedControl `json:"pending,omitempty"` - Activation *SignedControl `json:"activation,omitempty"` - ActivationHistory []SignedControl `json:"activationHistory,omitempty"` -} - -func digest(data []byte) string { - value := sha256.Sum256(data) - return hex.EncodeToString(value[:]) -} - -func decodeRouting(secret *corev1.Secret) (Routing, error) { - var route Routing - if err := json.Unmarshal(secret.Data["routing.json"], &route); err != nil { - return route, err - } - if route.Version != 2 || route.RootUID != secret.UID || route.Epoch != uint64(len(route.Segments)) || len(route.Segments) > MaxSegments || len(route.ActivationHistory) > 7 { - return route, errors.New("invalid registration routing identity or epoch") - } - return route, nil -} - -func (store Store) readSnapshot(ctx context.Context, secret *corev1.Secret) (Ledger, Ledger, error) { - base := Ledger{Authority: store.Authority, Projects: store.Projects} - key := "ledger.json" - if _, exists := secret.Data["routing.json"]; exists { - route, err := decodeRouting(secret) - if err != nil { - return Ledger{}, Ledger{}, err - } - key = "tail.json" - for index, reference := range route.Segments { - if reference.Name != segmentName(secret.UID, uint64(index)) || reference.UID == "" { - return Ledger{}, Ledger{}, errors.New("invalid segment identity") - } - segment := &corev1.Secret{} - if err := store.Client.Get(ctx, client.ObjectKey{Namespace: store.Namespace, Name: reference.Name}, segment); err != nil { - return Ledger{}, Ledger{}, err - } - if segment.UID != reference.UID || segment.Immutable == nil || !*segment.Immutable || !segment.DeletionTimestamp.IsZero() || digest(segment.Data["ledger.json"]) != reference.Digest { - return Ledger{}, Ledger{}, errors.New("segment lifetime or integrity unavailable") - } - var delta Ledger - if err := json.Unmarshal(segment.Data["ledger.json"], &delta); err != nil { - return Ledger{}, Ledger{}, err - } - if delta.Authority != store.Authority || !reflect.DeepEqual(delta.Projects, store.Projects) { - return Ledger{}, Ledger{}, errors.New("segment scope mismatch") - } - base = overlay(base, delta) - } - } - var tail Ledger - if err := json.Unmarshal(secret.Data[key], &tail); err != nil { - return Ledger{}, Ledger{}, err - } - if tail.Authority != store.Authority || !reflect.DeepEqual(tail.Projects, store.Projects) { - return Ledger{}, Ledger{}, errors.New("ledger scope mismatch") - } - return overlay(base, tail), base, nil -} - -func fenceKey(fence DeviceFence) string { - encoded, _ := json.Marshal([]string{fence.Project, string(fence.UID)}) - return string(encoded) -} - -func overlay(base, tail Ledger) Ledger { - result := Ledger{Authority: base.Authority, Projects: base.Projects} - entries := map[types.UID]bool{} - fences := map[string]bool{} - for _, entry := range tail.Entries { - entries[entry.Operation] = true - } - for _, fence := range tail.DeviceFences { - fences[fenceKey(fence)] = true - } - for _, entry := range base.Entries { - if !entries[entry.Operation] { - result.Entries = append(result.Entries, entry) - } - } - for _, fence := range base.DeviceFences { - if !fences[fenceKey(fence)] { - result.DeviceFences = append(result.DeviceFences, fence) - } - } - result.Entries = append(result.Entries, tail.Entries...) - result.DeviceFences = append(result.DeviceFences, tail.DeviceFences...) - return result -} - -func deltaFrom(base, current Ledger) Ledger { - delta := Ledger{Authority: current.Authority, Projects: current.Projects} - baseEntries := map[types.UID][]Entry{} - currentEntries := map[types.UID][]Entry{} - baseFences := map[string][]DeviceFence{} - currentFences := map[string][]DeviceFence{} - for _, entry := range base.Entries { - baseEntries[entry.Operation] = append(baseEntries[entry.Operation], entry) - } - for _, entry := range current.Entries { - currentEntries[entry.Operation] = append(currentEntries[entry.Operation], entry) - } - for _, fence := range base.DeviceFences { - baseFences[fenceKey(fence)] = append(baseFences[fenceKey(fence)], fence) - } - for _, fence := range current.DeviceFences { - currentFences[fenceKey(fence)] = append(currentFences[fenceKey(fence)], fence) - } - for _, entry := range current.Entries { - if !reflect.DeepEqual(baseEntries[entry.Operation], currentEntries[entry.Operation]) { - delta.Entries = append(delta.Entries, entry) - } - } - for _, fence := range current.DeviceFences { - if !reflect.DeepEqual(baseFences[fenceKey(fence)], currentFences[fenceKey(fence)]) { - delta.DeviceFences = append(delta.DeviceFences, fence) - } - } - return delta -} - -func preservesReservations(before, after Ledger) bool { - if before.Authority != after.Authority || !reflect.DeepEqual(before.Projects, after.Projects) { - return false - } - entries := map[types.UID][]Entry{} - fences := map[string][]DeviceFence{} - for _, entry := range after.Entries { - entries[entry.Operation] = append(entries[entry.Operation], entry) - } - for _, fence := range after.DeviceFences { - fences[fenceKey(fence)] = append(fences[fenceKey(fence)], fence) - } - for _, previous := range before.Entries { - found := false - for _, next := range entries[previous.Operation] { - next.Outcome = previous.Outcome - if reflect.DeepEqual(previous, next) { - found = true - break - } - } - if !found { - return false - } - } - for _, previous := range before.DeviceFences { - found := false - for _, next := range fences[fenceKey(previous)] { - if fenceKey(previous) != fenceKey(next) || (previous.Deleted && !next.Deleted) { - continue - } - if previous.ProjectUID != "" && previous.ProjectUID != next.ProjectUID { - continue - } - if previous.NamespaceUID != "" && previous.NamespaceUID != next.NamespaceUID { - continue - } - if previous.Name != "" && (previous.Name != next.Name || previous.Namespace != next.Namespace) { - continue - } - if slices.ContainsFunc(previous.Aliases, func(alias string) bool { return !slices.Contains(next.Aliases, alias) }) { - continue - } - found = true - } - if !found { - return false - } - } - return true -} - -func (store Store) writeSnapshot(ctx context.Context, secret *corev1.Secret, current Ledger) error { - route, err := decodeRouting(secret) - if err != nil { - return err - } - if route.Pending != nil { - return errors.New("registration expansion is fenced") - } - previous, base, err := store.readSnapshot(ctx, secret) - if err != nil { - return err - } - if !preservesReservations(previous, current) { - return errors.New("registration write would discard retained authority") - } - encoded, err := json.Marshal(deltaFrom(base, current)) - if err != nil { - return err - } - if len(encoded) > TailBudget { - if len(route.Segments) >= MaxSegments { - return ErrSegmentsExhausted - } - return ErrGrowthStopped - } - updated := secret.DeepCopy() - updated.Data["tail.json"] = encoded - return store.updateRoot(ctx, updated) -} - -func (store Store) updateRoot(ctx context.Context, secret *corev1.Secret) error { - size := 0 - for key, value := range secret.Data { - size += len(key) + len(value) - } - if size > RootBudget { - return ErrGrowthStopped - } - return store.Client.Update(ctx, secret) -} - -func segmentName(uid types.UID, epoch uint64) string { - return fmt.Sprintf("%s%s-%02d", SegmentPrefix, digest([]byte(uid))[:24], epoch) -} diff --git a/internal/registration/segments_envtest_test.go b/internal/registration/segments_envtest_test.go deleted file mode 100644 index a5eb8168..00000000 --- a/internal/registration/segments_envtest_test.go +++ /dev/null @@ -1,382 +0,0 @@ -package registration - -import ( - "context" - "crypto/ed25519" - "crypto/x509" - "encoding/json" - "encoding/pem" - "errors" - "fmt" - "os" - "os/exec" - "path/filepath" - "reflect" - "strings" - "sync" - "testing" - - corev1 "k8s.io/api/core/v1" - rbacv1 "k8s.io/api/rbac/v1" - apierrors "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/types" - "k8s.io/client-go/rest" - "k8s.io/client-go/tools/clientcmd" - clientcmdapi "k8s.io/client-go/tools/clientcmd/api" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/envtest" -) - -type faultClient struct { - client.Client - createAfter bool - createBefore bool - updateAt int - updates int - updateAfter bool - crash bool -} - -func (fault *faultClient) fail() error { - if fault.crash { - os.Exit(23) - } - return context.DeadlineExceeded -} - -func (fault *faultClient) Create(ctx context.Context, object client.Object, options ...client.CreateOption) error { - if fault.createBefore { - return fault.fail() - } - if err := fault.Client.Create(ctx, object, options...); err != nil { - return err - } - if fault.createAfter { - return fault.fail() - } - return nil -} - -func (fault *faultClient) Update(ctx context.Context, object client.Object, options ...client.UpdateOption) error { - fault.updates++ - if fault.updates == fault.updateAt && !fault.updateAfter { - return fault.fail() - } - if err := fault.Client.Update(ctx, object, options...); err != nil { - return err - } - if fault.updates == fault.updateAt && fault.updateAfter { - return fault.fail() - } - return nil -} - -func TestRegistrationExpansionWorker(t *testing.T) { - configPath := os.Getenv("FLEET_TEST_CONFIG") - if configPath == "" { - return - } - config, err := clientcmd.BuildConfigFromFlags("", configPath) - if err != nil { - t.Fatal(err) - } - scheme := runtime.NewScheme() - _ = corev1.AddToScheme(scheme) - _ = rbacv1.AddToScheme(scheme) - api, err := client.New(config, client.Options{Scheme: scheme}) - if err != nil { - t.Fatal(err) - } - encoded, err := os.ReadFile(os.Getenv("FLEET_TEST_PUBLIC")) - if err != nil { - t.Fatal(err) - } - public, err := ParseControlKey(encoded) - if err != nil { - t.Fatal(err) - } - store := Store{Client: api, Namespace: os.Getenv("FLEET_TEST_NAMESPACE"), Authority: "milo", Projects: []string{"provider"}, ControlKey: public} - fault := &faultClient{Client: api, crash: true} - switch os.Getenv("FLEET_TEST_CRASH") { - case "freeze": - fault.updateAt, fault.updateAfter = 1, true - case "segment-before": - fault.createBefore = true - case "segment-after": - fault.createAfter = true - case "switch-before": - fault.updateAt = 2 - case "switch-after": - fault.updateAt, fault.updateAfter = 2, true - default: - if err := store.ResumeExpansion(context.Background()); err != nil { - t.Fatal(err) - } - return - } - store.Client = fault - encoded, err = os.ReadFile(os.Getenv("FLEET_TEST_REQUEST")) - if err != nil { - t.Fatal(err) - } - control, err := ParseControl(encoded) - if err != nil { - t.Fatal(err) - } - handler := &Handler{Store: store} - if err := handler.ApplyControl(context.Background(), control); err != nil { - t.Fatal(err) - } - t.Fatal("fault boundary was not reached") -} - -func TestRealLosslessExpansionAndProcessRecovery(t *testing.T) { - if os.Getenv("KUBEBUILDER_ASSETS") == "" { - t.Skip("KUBEBUILDER_ASSETS required") - } - environment := &envtest.Environment{} - config, err := environment.Start() - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { - if err := environment.Stop(); err != nil { - t.Error(err) - } - }) - scheme := runtime.NewScheme() - _ = corev1.AddToScheme(scheme) - _ = rbacv1.AddToScheme(scheme) - api, err := client.New(config, client.Options{Scheme: scheme}) - if err != nil { - t.Fatal(err) - } - ctx := context.Background() - newHandler := func(t *testing.T, namespace string) (*Handler, ed25519.PrivateKey) { - handler, _ := fixture(t) - secret, ledger, err := handler.Store.Read(ctx) - if err != nil { - t.Fatal(err) - } - ledger.Entries = []Entry{{Operation: "admitted-not-persisted", Project: "provider", ProjectUID: "project-1", NamespaceUID: "namespace-1", CapacityUID: "public-uid", DeviceUID: "device-1", DeviceVersion: "v1", Aliases: []string{"uuid:reserved"}, Input: json.RawMessage(`{"spec":{"allocationPolicy":"Disabled","reclaimPolicy":"Retain"}}`), Outcome: "Unknown"}} - ledger.DeviceFences = []DeviceFence{{Project: "provider", UID: "legacy", Version: "old", Aliases: []string{"legacy-alias"}}, {Project: "provider", UID: "legacy", Version: "pending"}, {Project: "provider", UID: "deleted", Deleted: true, Aliases: []string{"never-release"}}} - secret.Data["ledger.json"], _ = json.Marshal(ledger) - secret.Namespace, secret.UID, secret.ResourceVersion = namespace, "", "" - if err := api.Create(ctx, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: namespace}}); err != nil { - t.Fatal(err) - } - if err := api.Create(ctx, secret); err != nil { - t.Fatal(err) - } - handler.Store.Client, handler.Store.Namespace = api, namespace - return handler, controlFixture(t, handler) - } - kubeconfig := clientcmdapi.Config{Clusters: map[string]*clientcmdapi.Cluster{"test": {Server: config.Host, CertificateAuthorityData: config.CAData}}, AuthInfos: map[string]*clientcmdapi.AuthInfo{"test": {ClientCertificateData: config.CertData, ClientKeyData: config.KeyData}}, Contexts: map[string]*clientcmdapi.Context{"test": {Cluster: "test", AuthInfo: "test"}}, CurrentContext: "test"} - kubeBytes, err := clientcmd.Write(kubeconfig) - if err != nil { - t.Fatal(err) - } - kubePath := filepath.Join(t.TempDir(), "config") - if err := os.WriteFile(kubePath, kubeBytes, 0600); err != nil { - t.Fatal(err) - } - for _, boundary := range []string{"freeze", "segment-before", "segment-after", "switch-before", "switch-after"} { - t.Run(boundary, func(t *testing.T) { - handler, key := newHandler(t, boundary) - stale, before, err := handler.Store.Read(ctx) - if err != nil { - t.Fatal(err) - } - control := controlFor(t, handler, key, "expand") - encoded, _ := json.Marshal(control) - requestPath := filepath.Join(t.TempDir(), "request") - if err := os.WriteFile(requestPath, encoded, 0600); err != nil { - t.Fatal(err) - } - publicDER, _ := x509.MarshalPKIXPublicKey(handler.Store.ControlKey) - publicPath := filepath.Join(t.TempDir(), "public") - if err := os.WriteFile(publicPath, pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: publicDER}), 0600); err != nil { - t.Fatal(err) - } - runWorker := func(crash string) error { - command := exec.Command(os.Args[0], "-test.run=^TestRegistrationExpansionWorker$") - command.Env = append(os.Environ(), "FLEET_TEST_CONFIG="+kubePath, "FLEET_TEST_NAMESPACE="+handler.Store.Namespace, "FLEET_TEST_PUBLIC="+publicPath, "FLEET_TEST_REQUEST="+requestPath, "FLEET_TEST_CRASH="+crash) - output, err := command.CombinedOutput() - if err != nil && crash == "" { - t.Log(string(output)) - } - return err - } - var exit *exec.ExitError - if err := runWorker(boundary); !errors.As(err, &exit) || exit.ExitCode() != 23 { - t.Fatalf("expected injected process crash: %v", err) - } - if handler.Store.Write(ctx, stale, before) == nil { - t.Fatal("pre-freeze writer committed") - } - if err := runWorker(""); err != nil { - t.Fatal("restart", err) - } - _, after, err := handler.Store.Read(ctx) - if err != nil || !reflect.DeepEqual(before, after) { - t.Fatalf("restart lost reservations: %v\n%+v", err, after) - } - _, route, err := handler.Store.root(ctx) - if err != nil || route.Pending != nil || route.Epoch != 1 || len(route.Segments) != 1 { - t.Fatalf("unfinished expansion: %+v %v", route, err) - } - var segments corev1.SecretList - if err := api.List(ctx, &segments, client.InNamespace(handler.Store.Namespace)); err != nil || len(segments.Items) != 2 { - t.Fatalf("orphan segments: %d %v", len(segments.Items), err) - } - }) - } - t.Run("full-legacy-sealing", func(t *testing.T) { - handler, key := newHandler(t, "full-legacy") - secret, before, err := handler.Store.Read(ctx) - if err != nil { - t.Fatal(err) - } - before.DeviceFences = append(before.DeviceFences, DeviceFence{Project: "provider", UID: "large", Aliases: []string{""}}) - encoded, _ := json.Marshal(before) - before.DeviceFences[len(before.DeviceFences)-1].Aliases[0] = strings.Repeat("x", SegmentBudget-len(encoded)) - secret.Data["ledger.json"], _ = json.Marshal(before) - if err := api.Update(ctx, secret); err != nil { - t.Fatal(err) - } - if err := handler.ApplyControl(ctx, controlFor(t, handler, key, "expand")); err != nil { - t.Fatal(err) - } - _, after, err := handler.Store.Read(ctx) - if err != nil || !reflect.DeepEqual(before, after) { - t.Fatal("full legacy data lost", err) - } - status, err := handler.Status(ctx) - if err != nil || status.HeadroomBytes < TailBudget-1000 || status.Epoch != 1 || status.ActivationVerified { - t.Fatalf("bad expanded bootstrap status: %+v %v", status, err) - } - }) - t.Run("multi-replica-and-growth", func(t *testing.T) { - handler, key := newHandler(t, "replicas") - _, before, _ := handler.Store.Read(ctx) - control := controlFor(t, handler, key, "expand") - var workers sync.WaitGroup - for range 8 { - workers.Add(1) - go func() { defer workers.Done(); replica := *handler; _ = replica.ApplyControl(ctx, control) }() - } - workers.Wait() - if err := handler.Store.ResumeExpansion(ctx); err != nil { - t.Fatal(err) - } - if err := handler.ApplyControl(ctx, control); err != nil { - t.Fatal("lost completion response cannot be reconciled", err) - } - secret, after, err := handler.Store.Read(ctx) - if err != nil || !reflect.DeepEqual(before, after) { - t.Fatal("concurrent migration lost history", err) - } - for attempt := 1; attempt < MaxSegments; attempt++ { - after.DeviceFences = append(after.DeviceFences, DeviceFence{Project: "provider", UID: types.UID(fmt.Sprint("new-", attempt)), Aliases: []string{strings.Repeat("a", TailBudget-1000)}}) - if err := handler.Store.Write(ctx, secret, after); err != nil { - t.Fatal(err) - } - secret, after, _ = handler.Store.Read(ctx) - tooLarge := after - tooLarge.DeviceFences = append(append([]DeviceFence(nil), after.DeviceFences...), DeviceFence{Project: "provider", UID: "oversize", Aliases: []string{strings.Repeat("b", 2000)}}) - if !errors.Is(handler.Store.Write(ctx, secret, tooLarge), ErrGrowthStopped) { - t.Fatal("tail headroom not enforced") - } - if err := handler.ApplyControl(ctx, controlFor(t, handler, key, "expand")); err != nil { - t.Fatal(err) - } - secret, after, err = handler.Store.Read(ctx) - if err != nil { - t.Fatal(err) - } - } - if !errors.Is(handler.ApplyControl(ctx, controlFor(t, handler, key, "expand")), ErrGrowthStopped) { - t.Fatal("unbounded expansion") - } - if after.Entries[0].Outcome != "Unknown" || len(after.DeviceFences) != len(before.DeviceFences)+MaxSegments-1 { - t.Fatal("growth changed custody") - } - _, route, _ := handler.Store.root(ctx) - segment := &corev1.Secret{} - if err := api.Get(ctx, client.ObjectKey{Namespace: handler.Store.Namespace, Name: route.Segments[0].Name}, segment); err != nil { - t.Fatal(err) - } - segment.Data["ledger.json"] = []byte("{}") - if err := api.Update(ctx, segment); !apierrors.IsInvalid(err) { - t.Fatal("segment mutable", err) - } - if err := api.Delete(ctx, segment); err != nil { - t.Fatal(err) - } - if _, _, err := handler.Store.Read(ctx); err == nil { - t.Fatal("missing segment treated as free") - } - segment.UID, segment.ResourceVersion = "", "" - if err := api.Create(ctx, segment); err != nil { - t.Fatal(err) - } - if _, _, err := handler.Store.Read(ctx); err == nil { - t.Fatal("replacement segment adopted") - } - }) - t.Run("uncertain-write-and-read-only", func(t *testing.T) { - handler, key := newHandler(t, "uncertain") - if err := handler.ApplyControl(ctx, controlFor(t, handler, key, "expand")); err != nil { - t.Fatal(err) - } - secret, ledger, _ := handler.Store.Read(ctx) - ledger.DeviceFences = append(ledger.DeviceFences, DeviceFence{Project: "provider", UID: "uncertain", Aliases: []string{"retained"}}) - store := handler.Store - store.Client = &faultClient{Client: api, updateAt: 1, updateAfter: true} - if !errors.Is(store.Write(ctx, secret, ledger), context.DeadlineExceeded) { - t.Fatal("write should be uncertain") - } - secret, observed, err := handler.Store.Read(ctx) - if err != nil || !reflect.DeepEqual(ledger, observed) { - t.Fatal("persist timeout released state", err) - } - store.Client = &faultClient{Client: api, updateAt: 1} - observed.DeviceFences = append(observed.DeviceFences, DeviceFence{Project: "provider", UID: "denied"}) - if store.Write(ctx, secret, observed) == nil { - t.Fatal("read-only storage admitted") - } - _, retained, err := handler.Store.Read(ctx) - if err != nil || !reflect.DeepEqual(ledger, retained) { - t.Fatal("read-only failure changed history", err) - } - retained.DeviceFences = nil - if handler.Store.Write(ctx, secret, retained) == nil { - t.Fatal("alias removal accepted") - } - role := &rbacv1.Role{ObjectMeta: metav1.ObjectMeta{Name: "reader", Namespace: handler.Store.Namespace}, Rules: []rbacv1.PolicyRule{{APIGroups: []string{""}, Resources: []string{"secrets"}, Verbs: []string{"get"}}}} - if err := api.Create(ctx, role); err != nil { - t.Fatal(err) - } - binding := &rbacv1.RoleBinding{ObjectMeta: metav1.ObjectMeta{Name: "reader", Namespace: handler.Store.Namespace}, Subjects: []rbacv1.Subject{{Kind: "User", Name: "ledger-reader"}}, RoleRef: rbacv1.RoleRef{APIGroup: "rbac.authorization.k8s.io", Kind: "Role", Name: "reader"}} - if err := api.Create(ctx, binding); err != nil { - t.Fatal(err) - } - readOnlyConfig := rest.CopyConfig(config) - readOnlyConfig.Impersonate = rest.ImpersonationConfig{UserName: "ledger-reader", Groups: []string{"system:authenticated"}} - readOnly, err := client.New(readOnlyConfig, client.Options{Scheme: scheme}) - if err != nil { - t.Fatal(err) - } - store.Client = readOnly - secret, observed, err = store.Read(ctx) - if err != nil { - t.Fatal("read-only observation should work", err) - } - observed.DeviceFences = append(observed.DeviceFences, DeviceFence{Project: "provider", UID: "forbidden"}) - if err := store.Write(ctx, secret, observed); !apierrors.IsForbidden(err) { - t.Fatal("read-only storage wrote", err) - } - }) -} diff --git a/internal/registration/terminal_errors_test.go b/internal/registration/terminal_errors_test.go deleted file mode 100644 index 7d6d9932..00000000 --- a/internal/registration/terminal_errors_test.go +++ /dev/null @@ -1,121 +0,0 @@ -package registration - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "strings" - "testing" - - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/types" - "k8s.io/client-go/rest" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/client/fake" -) - -const runbook = "docs/development/registration-storage-rollout.md" - -// sealedRoot converts the fixture root to v2 routing with the given number of -// sealed segments, each a valid immutable overlay of the configured scope. -func sealedRoot(t *testing.T, handler *Handler, sealed int) { - t.Helper() - ctx := context.Background() - store := handler.Store - secret := &corev1.Secret{} - if err := store.Client.Get(ctx, client.ObjectKey{Namespace: store.Namespace, Name: LedgerName}, secret); err != nil { - t.Fatal(err) - } - empty, _ := json.Marshal(Ledger{Authority: store.Authority, Projects: store.Projects}) - route := Routing{Version: 2, RootUID: secret.UID, Epoch: uint64(sealed)} - immutable := true - for epoch := 0; epoch < sealed; epoch++ { - segment := &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Namespace: store.Namespace, Name: segmentName(secret.UID, uint64(epoch)), UID: types.UID(fmt.Sprint("segment-", epoch))}, Immutable: &immutable, Data: map[string][]byte{"ledger.json": empty}} - if err := store.Client.Create(ctx, segment); err != nil { - t.Fatal(err) - } - if segment.UID == "" { - t.Fatal("segment UID not retained") - } - route.Segments = append(route.Segments, Segment{Name: segment.Name, UID: segment.UID, Digest: digest(empty)}) - } - encoded, _ := json.Marshal(route) - secret.Data = map[string][]byte{"ledger.json": []byte(`{"authority":"v2-routing-required","projects":[]}`), "tail.json": empty, "routing.json": encoded} - if err := store.Client.Update(ctx, secret); err != nil { - t.Fatal(err) - } -} - -func oversizedWrite(t *testing.T, handler *Handler) error { - t.Helper() - secret, ledger, err := handler.Store.Read(context.Background()) - if err != nil { - t.Fatal(err) - } - ledger.DeviceFences = append(ledger.DeviceFences, DeviceFence{Project: "provider", UID: "oversize", Aliases: []string{strings.Repeat("x", TailBudget)}}) - return handler.Store.Write(context.Background(), secret, ledger) -} - -func TestSegmentExhaustionIsDistinctAndActionable(t *testing.T) { - ctx := context.Background() - handler, _ := fixture(t) - key := controlFixture(t, handler) - sealedRoot(t, handler, MaxSegments) - for name, err := range map[string]error{ - "expand": handler.ApplyControl(ctx, controlFor(t, handler, key, "expand")), - "write": oversizedWrite(t, handler), - } { - if !errors.Is(err, ErrSegmentsExhausted) || !errors.Is(err, ErrGrowthStopped) { - t.Fatalf("%s: terminal growth stop not distinct: %v", name, err) - } - message := err.Error() - if strings.Contains(message, "expansion required") || !strings.Contains(message, "segments exhausted") || !strings.Contains(message, "reviewed storage migration") || !strings.Contains(message, runbook) { - t.Fatalf("%s: terminal error is not operator-actionable: %s", name, message) - } - } - _, route, err := handler.Store.root(ctx) - if err != nil || route.Pending != nil || len(route.Segments) != MaxSegments { - t.Fatalf("refused expansion changed routing: %+v %v", route, err) - } -} - -func TestGrowthStopBelowSegmentCapStillAsksForExpansion(t *testing.T) { - handler, _ := fixture(t) - controlFixture(t, handler) - sealedRoot(t, handler, MaxSegments-1) - err := oversizedWrite(t, handler) - if !errors.Is(err, ErrGrowthStopped) || errors.Is(err, ErrSegmentsExhausted) { - t.Fatalf("expandable root reported terminal exhaustion: %v", err) - } -} - -func TestFullLegacyLedgerNamesExpandRequest(t *testing.T) { - handler, _ := fixture(t) - err := oversizedWrite(t, handler) - if err == nil || !strings.Contains(err.Error(), "sign an expand") || !strings.Contains(err.Error(), runbook) { - t.Fatalf("full v1 ledger does not say how to proceed: %v", err) - } -} - -func TestActivationGateIsDefaultAndProductionForcesIt(t *testing.T) { - ctx := context.Background() - handler, device := fixture(t) - handler.Store.AllowInactiveForTests = false - if handler.Handle(ctx, registrationRequest(t, device, "zero-value")).Allowed { - t.Fatal("zero-value store admitted without signed activation") - } - if _, ledger, err := handler.Store.Read(ctx); err != nil || len(ledger.Entries) != 0 { - t.Fatalf("gated admission retained a reservation: %+v %v", ledger, err) - } - scheme := runtime.NewScheme() - if err := corev1.AddToScheme(scheme); err != nil { - t.Fatal(err) - } - production := NewHandler(Store{Client: handler.Store.Client, Namespace: "private", Authority: "milo", Projects: []string{"provider"}, AllowInactiveForTests: true}, fake.NewClientBuilder().WithScheme(scheme).Build(), &rest.Config{Host: "https://synthetic.invalid"}, scheme) - if production.Store.AllowInactiveForTests { - t.Fatal("production wiring kept the test-only activation opt-out") - } -} diff --git a/internal/registration/testdata/review_adversarial_test.go.txt b/internal/registration/testdata/review_adversarial_test.go.txt deleted file mode 100644 index fefd78ba..00000000 --- a/internal/registration/testdata/review_adversarial_test.go.txt +++ /dev/null @@ -1,172 +0,0 @@ -package registration - -import ( - "context" - "encoding/json" - "net/http/httptest" - "os" - "path/filepath" - "testing" - "time" - - inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" - metal "go.datum.net/fleet/internal/api/v1alpha1" - "go.datum.net/fleet/internal/controller" - iam "go.miloapis.com/milo/pkg/apis/iam/v1alpha1" - admissionregistrationv1 "k8s.io/api/admissionregistration/v1" - authorizationv1 "k8s.io/api/authorization/v1" - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/client-go/rest" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/envtest" - "sigs.k8s.io/controller-runtime/pkg/webhook/admission" - "sigs.k8s.io/yaml" -) - -func TestReviewRealNoopAndOutage(t *testing.T) { - if os.Getenv("KUBEBUILDER_ASSETS") == "" { - t.Skip("KUBEBUILDER_ASSETS required") - } - ctx := context.Background() - environment := &envtest.Environment{CRDDirectoryPaths: []string{filepath.Join("..", "..", "config", "base", "crd"), filepath.Join("..", "..", "config", "components", "inventory", "crds")}, ErrorIfCRDPathMissing: true} - config, err := environment.Start() - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { - if err := environment.Stop(); err != nil { - t.Error(err) - } - }) - scheme := runtime.NewScheme() - for _, add := range []func(*runtime.Scheme) error{corev1.AddToScheme, inventory.AddToScheme, metal.AddToScheme, admissionregistrationv1.AddToScheme, authorizationv1.AddToScheme} { - if err := add(scheme); err != nil { - t.Fatal(err) - } - } - api, err := client.New(config, client.Options{Scheme: scheme}) - if err != nil { - t.Fatal(err) - } - device := &inventory.Device{ObjectMeta: metav1.ObjectMeta{Name: "noop-hardware", Namespace: "default"}, Spec: inventory.DeviceSpec{ClaimRef: inventory.LocalReference{Name: "installation"}, Identity: inventory.DeviceIdentity{Model: "test", Serial: "noop-serial", SystemUUID: "11111111-1111-1111-1111-111111111111"}}} - if err := api.Create(ctx, device, client.FieldOwner("review")); err != nil { - t.Fatal(err) - } - encoded, _ := json.Marshal(Ledger{Authority: "milo", Projects: []string{"provider"}}) - if err := api.Create(ctx, &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: LedgerName, Namespace: "default"}, Data: map[string][]byte{"ledger.json": encoded}}); err != nil { - t.Fatal(err) - } - handler := &Handler{Store: Store{Client: api, Namespace: "default", Authority: "milo", Projects: []string{"provider"}}, VerifyFence: func(ctx context.Context) error { return VerifyFence(ctx, api) }, Resolve: func(context.Context, string) (Project, error) { - return Project{Identity: controller.ProjectIdentity{AuthorityID: "milo", RouteName: "provider", UID: "project-1"}, Client: api}, nil - }, Authorize: Authorize} - server := httptest.NewTLSServer(&admission.Webhook{Handler: handler}) - t.Cleanup(server.Close) - data, err := os.ReadFile("../../config/components/registration-admission/webhook.yaml") - if err != nil { - t.Fatal(err) - } - var webhooks admissionregistrationv1.ValidatingWebhookConfiguration - if err := yaml.UnmarshalStrict(data, &webhooks); err != nil { - t.Fatal(err) - } - url := server.URL - webhooks.Webhooks[0].ClientConfig = admissionregistrationv1.WebhookClientConfig{URL: &url, CABundle: pemCertificate(server.Certificate().Raw)} - if err := api.Create(ctx, &webhooks); err != nil { - t.Fatal(err) - } - actorConfig := rest.CopyConfig(config) - actorConfig.Impersonate = rest.ImpersonationConfig{UserName: "review-operator", UID: "actor-1", Groups: []string{"system:masters"}, Extra: map[string][]string{iam.ParentKindExtraKey: {"Project"}, iam.ParentAPIGroupExtraKey: {"resourcemanager.miloapis.com"}, iam.ParentNameExtraKey: {"provider"}}} - actor, err := client.New(actorConfig, client.Options{Scheme: scheme}) - if err != nil { - t.Fatal(err) - } - deadline := time.Now().Add(10 * time.Second) - for { - if err := actor.Update(ctx, device.DeepCopyObject().(*inventory.Device), client.DryRunAll); err != nil { - break - } - if time.Now().After(deadline) { - t.Fatal("webhook did not engage") - } - time.Sleep(30 * time.Millisecond) - } - t.Run("successful-noop-must-not-poison-current-device", func(t *testing.T) { - unchanged := false - for attempt := 0; attempt < 3; attempt++ { - if err := actor.Get(ctx, client.ObjectKeyFromObject(device), device); err != nil { - t.Fatal(err) - } - before := device.ResourceVersion - if err := actor.Update(ctx, device, client.FieldOwner("review")); err != nil { - t.Fatal(err) - } - if before == device.ResourceVersion { - unchanged = true - break - } - } - if !unchanged { - t.Fatal("could not reproduce a no-op update") - } - request := registrationRequest(t, device, "after-noop") - var capacity metal.MachineCapacity - if err := json.Unmarshal(request.Object.Raw, &capacity); err != nil { - t.Fatal(err) - } - capacity.UID = "" - if err := actor.Create(ctx, &capacity); err != nil { - t.Errorf("completed no-op left current RV %s ineligible: %v", device.ResourceVersion, err) - } - }) - t.Run("explicit-real-edit-control-restores-registration", func(t *testing.T) { - if err := actor.Get(ctx, client.ObjectKeyFromObject(device), device); err != nil { - t.Fatal(err) - } - before := device.ResourceVersion - device.Labels = map[string]string{"review-control": "real-change"} - if err := actor.Update(ctx, device, client.FieldOwner("review")); err != nil { - t.Fatal(err) - } - if device.ResourceVersion == before { - t.Fatal("control edit did not change RV") - } - request := registrationRequest(t, device, "after-real-edit") - var capacity metal.MachineCapacity - if err := json.Unmarshal(request.Object.Raw, &capacity); err != nil { - t.Fatal(err) - } - capacity.UID = "" - if err := actor.Create(ctx, &capacity); err != nil { - t.Fatalf("explicitly reselected changed Device should register: %v", err) - } - if err := handler.Recover(ctx); err != nil { - t.Fatal(err) - } - _, ledger, err := handler.Store.Read(ctx) - if err != nil || len(ledger.Entries) != 1 || ledger.Entries[0].Outcome != "Recorded" { - t.Fatalf("control failed: %+v %v", ledger, err) - } - }) - t.Run("out-of-scope-inventory-outage-blast-radius", func(t *testing.T) { - outsideConfig := rest.CopyConfig(actorConfig) - outsideConfig.Impersonate.Extra = map[string][]string{iam.ParentKindExtraKey: {"Project"}, iam.ParentAPIGroupExtraKey: {"resourcemanager.miloapis.com"}, iam.ParentNameExtraKey: {"unrelated-consumer"}} - outside, err := client.New(outsideConfig, client.Options{Scheme: scheme}) - if err != nil { - t.Fatal(err) - } - other := device.DeepCopyObject().(*inventory.Device) - other.Name, other.UID, other.ResourceVersion, other.ManagedFields = "outside-before-outage", "", "", nil - if err := outside.Create(ctx, other); err != nil { - t.Fatal(err) - } - server.Close() - other.Name, other.UID, other.ResourceVersion, other.ManagedFields = "outside-after-outage", "", "", nil - if err := outside.Create(ctx, other); err == nil { - t.Fatal("expected packaged fail-closed webhook to block unrelated inventory too") - } else { - t.Logf("confirmed unrelated project inventory outage: %v", err) - } - }) -} diff --git a/internal/registration/transport.go b/internal/registration/transport.go index 1113fe89..da35f813 100644 --- a/internal/registration/transport.go +++ b/internal/registration/transport.go @@ -1,104 +1,18 @@ package registration import ( - "context" - "crypto/ed25519" - "crypto/x509" - "encoding/json" - "encoding/pem" - "errors" "net/http" - "time" - - "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/webhook/admission" ) -func ParseControlKey(encoded []byte) (ed25519.PublicKey, error) { - block, rest := pem.Decode(encoded) - if block == nil || len(rest) != 0 { - return nil, errors.New("expected one PKIX public key") - } - parsed, err := x509.ParsePKIXPublicKey(block.Bytes) - if err != nil { - return nil, err - } - key, ok := parsed.(ed25519.PublicKey) - if !ok { - return nil, errors.New("control key must be Ed25519") - } - return key, nil -} - -func ParseControl(encoded []byte) (SignedControl, error) { - var control SignedControl - if len(encoded) > 16384 { - return control, errors.New("control request exceeds budget") - } - err := json.Unmarshal(encoded, &control) - return control, err -} - +// Transport serves the validating webhook and a transport probe. Both sit +// behind the same mutually authenticated TLS listener. func (handler *Handler) Transport() http.Handler { mux := http.NewServeMux() mux.Handle("/validate-registration", &admission.Webhook{Handler: handler}) - mux.HandleFunc("/transportz", func(writer http.ResponseWriter, request *http.Request) { - writer.WriteHeader(http.StatusNoContent) - }) - mux.HandleFunc("/activationz", func(writer http.ResponseWriter, request *http.Request) { - ctx, cancel := context.WithTimeout(request.Context(), 5*time.Second) - defer cancel() - if err := handler.Ready(ctx); err != nil { - http.Error(writer, "registration non-admitting or dependencies unavailable", http.StatusServiceUnavailable) - return - } + mux.HandleFunc("/transportz", func(writer http.ResponseWriter, _ *http.Request) { writer.WriteHeader(http.StatusNoContent) }) - mux.HandleFunc("/status", func(writer http.ResponseWriter, request *http.Request) { - ctx, cancel := context.WithTimeout(request.Context(), 5*time.Second) - defer cancel() - status, err := handler.Status(ctx) - if err != nil { - http.Error(writer, "registration ledger unavailable", http.StatusServiceUnavailable) - return - } - writer.Header().Set("Content-Type", "application/json") - _ = json.NewEncoder(writer).Encode(status) - }) return mux } - -type Status struct { - Authority string `json:"authority"` - Projects []string `json:"projects"` - RootUID types.UID `json:"rootUID"` - ResourceVersion string `json:"resourceVersion"` - Epoch uint64 `json:"epoch"` - TailBytes int `json:"tailBytes"` - HeadroomBytes int `json:"headroomBytes"` - RemainingSegments int `json:"remainingSegments"` - Pending bool `json:"pending"` - ActivationVerified bool `json:"activationVerified"` - FenceDigest string `json:"fenceDigest,omitempty"` -} - -func (handler *Handler) Status(ctx context.Context) (Status, error) { - secret, route, err := handler.Store.root(ctx) - if err != nil { - return Status{}, err - } - if _, _, err := handler.Store.readSnapshot(ctx, secret); err != nil { - return Status{}, err - } - tail := secret.Data["tail.json"] - if _, exists := secret.Data["routing.json"]; !exists { - tail = secret.Data["ledger.json"] - } - status := Status{Authority: handler.Store.Authority, Projects: handler.Store.Projects, RootUID: secret.UID, ResourceVersion: secret.ResourceVersion, Epoch: route.Epoch, TailBytes: len(tail), HeadroomBytes: max(0, TailBudget-len(tail)), RemainingSegments: MaxSegments - len(route.Segments), Pending: route.Pending != nil} - status.ActivationVerified = handler.readySnapshot(ctx, secret, route) == nil - if handler.FenceDigest != nil { - status.FenceDigest, _ = handler.FenceDigest(ctx) - } - return status, nil -} From ebf574557483a6a7a5bb1e862ed32e4e0eb6ae6d Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sun, 22 Nov 2026 16:22:46 -0600 Subject: [PATCH 073/518] feat(config): add Device deletion protection Add config/components/device-deletion-protection, a ValidatingAdmissionPolicy and binding that deny every Device DELETE with no exemptions. config/milo-production is config/milo plus the component. config/milo, config/milo-synthetic and every other root leave it out, so test and staging control planes can still delete Devices. The overlay isolation validator now fails when a production-style root lacks the component or any other root renders it. CI builds the new root. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 1 + .../kustomization.yaml | 7 ++ .../device-deletion-protection/policy.yaml | 34 +++++++ config/milo-production/kustomization.yaml | 9 ++ hack/overlay-isolation-validator.go | 98 +++++++++++++++++++ hack/test-overlay-isolation.sh | 38 +++++++ 6 files changed, 187 insertions(+) create mode 100644 config/components/device-deletion-protection/kustomization.yaml create mode 100644 config/components/device-deletion-protection/policy.yaml create mode 100644 config/milo-production/kustomization.yaml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d537961b..0fbf0da4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -24,6 +24,7 @@ jobs: - run: go run ./test/acceptance/milo/cmd validate --root . - run: kustomize build config/base/crd >/dev/null - run: kustomize build config/milo >/dev/null + - run: kustomize build config/milo-production >/dev/null - run: kustomize build config/milo-synthetic >/dev/null - run: kustomize build config/overlays/management-plane >/dev/null - run: kustomize build config/overlays/synthetic-staging >/dev/null diff --git a/config/components/device-deletion-protection/kustomization.yaml b/config/components/device-deletion-protection/kustomization.yaml new file mode 100644 index 00000000..03bc082f --- /dev/null +++ b/config/components/device-deletion-protection/kustomization.yaml @@ -0,0 +1,7 @@ +# Optional: install wherever Device objects are admitted (the Milo control +# plane) in environments that must never lose a Device. See +# docs/development/inventory-capacity-registration.md#device-deletion-protection. +apiVersion: kustomize.config.k8s.io/v1alpha1 +kind: Component +resources: + - policy.yaml diff --git a/config/components/device-deletion-protection/policy.yaml b/config/components/device-deletion-protection/policy.yaml new file mode 100644 index 00000000..bc69125e --- /dev/null +++ b/config/components/device-deletion-protection/policy.yaml @@ -0,0 +1,34 @@ +# Devices are never deleted where this component is installed. Retire a +# machine through its capacity staying Disabled instead. The API server runs +# admission once per object for deletecollection, garbage collection and +# namespace or project cleanup, so every one of those paths is denied too. +# There are no exemptions: an environment that needs Device deletion does not +# install this component. +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicy +metadata: + name: fleet-device-deletion-protection +spec: + failurePolicy: Fail + matchConstraints: + matchPolicy: Equivalent + resourceRules: + - apiGroups: [fleet.datumapis.com] + apiVersions: ['*'] + operations: [DELETE] + resources: [devices] + validations: + - expression: 'false' + reason: Forbidden + message: >- + Devices cannot be deleted in this environment. Their identity must stay + visible to duplicate-hardware checks. Leave the Device in place and + keep its capacity Disabled. +--- +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicyBinding +metadata: + name: fleet-device-deletion-protection +spec: + policyName: fleet-device-deletion-protection + validationActions: [Deny] diff --git a/config/milo-production/kustomization.yaml b/config/milo-production/kustomization.yaml new file mode 100644 index 00000000..c3a66020 --- /dev/null +++ b/config/milo-production/kustomization.yaml @@ -0,0 +1,9 @@ +# Production-style Milo root: config/milo plus Device deletion protection. +# Environments that need Device deletions, such as test and staging control +# planes, consume config/milo instead. +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - ../milo +components: + - ../components/device-deletion-protection diff --git a/hack/overlay-isolation-validator.go b/hack/overlay-isolation-validator.go index 8d1ea9f6..6ffe60eb 100644 --- a/hack/overlay-isolation-validator.go +++ b/hack/overlay-isolation-validator.go @@ -26,8 +26,15 @@ const ( marker = "fleet.datumapis.com/standalone-only" localProjectStandIn = "fleet.datumapis.com/local-project-stand-in" sharedNamespace = "fleet.datumapis.com/shared-with-standalone" + + // Device deletion protection is optional per environment. Only the + // production-style roots below may render it, and they must. + deletionProtection = "fleet-device-deletion-protection" + deletionProtectionComponent = "components/device-deletion-protection" ) +var deletionProtectedRoots = []string{"milo-production"} + type kustomization struct { Resources []string `json:"resources"` Components []string `json:"components"` @@ -78,6 +85,16 @@ func main() { } } v.indexStandalone(standaloneObjects) + if err := checkDeletionProtection("standalone", standaloneObjects, false); err != nil { + fatalf("render %s: %v", standaloneRoot, err) + } + if _, err := os.Stat(filepath.Join(configRoot, filepath.FromSlash(deletionProtectionComponent))); err == nil { + for _, root := range deletionProtectedRoots { + if _, err := os.Stat(filepath.Join(configRoot, root)); err != nil { + fatalf("production-style root %s must exist and install Device deletion protection: %v", root, err) + } + } + } entries, err := discover(configRoot) check(err) @@ -103,6 +120,16 @@ func main() { fatalf("render %s: %v", root, err) } } + relative, err := filepath.Rel(configRoot, root) + check(err) + relative = filepath.ToSlash(relative) + required := relative == deletionProtectionComponent + for _, protected := range deletionProtectedRoots { + required = required || relative == protected + } + if err := checkDeletionProtection(relative, objects, required); err != nil { + fatalf("render %s: %v", root, err) + } } if checked == 0 { fatalf("no non-standalone Kustomize entry point was validated") @@ -260,6 +287,77 @@ func (v *validator) checkObject(object *unstructured.Unstructured) error { return nil } +// checkDeletionProtection requires the exact deny-all Device DELETE policy and +// its binding in production-style roots, and forbids either object anywhere +// else, so test and synthetic roots keep Device deletion available. +func checkDeletionProtection(root string, objects []*unstructured.Unstructured, required bool) error { + var policy, binding *unstructured.Unstructured + for _, object := range objects { + if object.GetAPIVersion() != "admissionregistration.k8s.io/v1" { + continue + } + switch object.GetKind() { + case "ValidatingAdmissionPolicy": + if object.GetName() == deletionProtection || policyMatchesDeviceDelete(object) { + policy = object + } + case "ValidatingAdmissionPolicyBinding": + if name, _, _ := unstructured.NestedString(object.Object, "spec", "policyName"); object.GetName() == deletionProtection || name == deletionProtection { + binding = object + } + } + } + if !required { + if policy != nil || binding != nil { + return fmt.Errorf("%s renders Device deletion protection; only %v may install %s", root, deletionProtectedRoots, deletionProtectionComponent) + } + return nil + } + if policy == nil || binding == nil { + return fmt.Errorf("production-style root %s must install the Device deletion policy and its binding", root) + } + failurePolicy, _, _ := unstructured.NestedString(policy.Object, "spec", "failurePolicy") + validations, _, _ := unstructured.NestedSlice(policy.Object, "spec", "validations") + _, hasConditions := policy.Object["spec"].(map[string]any)["matchConditions"] + if policy.GetName() != deletionProtection || failurePolicy != "Fail" || !policyMatchesDeviceDelete(policy) || hasConditions || len(validations) != 1 { + return fmt.Errorf("%s: Device deletion policy must fail closed, match DELETE on devices and have no exemptions", root) + } + if expression, _, _ := unstructured.NestedString(validations[0].(map[string]any), "expression"); expression != "false" { + return fmt.Errorf("%s: Device deletion policy must deny every DELETE", root) + } + actions, _, _ := unstructured.NestedStringSlice(binding.Object, "spec", "validationActions") + _, hasMatch := binding.Object["spec"].(map[string]any)["matchResources"] + _, hasParams := binding.Object["spec"].(map[string]any)["paramRef"] + if len(actions) != 1 || actions[0] != "Deny" || hasMatch || hasParams { + return fmt.Errorf("%s: Device deletion binding must Deny in every namespace", root) + } + return nil +} + +func policyMatchesDeviceDelete(policy *unstructured.Unstructured) bool { + rules, _, _ := unstructured.NestedSlice(policy.Object, "spec", "matchConstraints", "resourceRules") + for _, raw := range rules { + rule, ok := raw.(map[string]any) + if !ok { + continue + } + groups, resources, operations := stringsFrom(rule["apiGroups"]), stringsFrom(rule["resources"]), stringsFrom(rule["operations"]) + if (contains(groups, "fleet.datumapis.com") || contains(groups, "*")) && (contains(resources, "devices") || contains(resources, "*")) && (contains(operations, "DELETE") || contains(operations, "*")) { + return true + } + } + return false +} + +func contains(values []string, value string) bool { + for _, candidate := range values { + if candidate == value { + return true + } + } + return false +} + func isCoreNamespace(object *unstructured.Unstructured) bool { return object.GetAPIVersion() == "v1" && object.GetKind() == "Namespace" } diff --git a/hack/test-overlay-isolation.sh b/hack/test-overlay-isolation.sh index e8564d36..6d0ec68f 100755 --- a/hack/test-overlay-isolation.sh +++ b/hack/test-overlay-isolation.sh @@ -417,4 +417,42 @@ EOF expect_failure "intentional Kustomize build failure" "missing.yaml" rm -rf "$fixture_root/config/overlays/broken" +# Device deletion protection is per environment: only production-style roots +# may render it, and once the component exists they must. +mkdir -p "$fixture_root/config/components/device-deletion-protection" +cp "$repo_root/config/components/device-deletion-protection/kustomization.yaml" "$repo_root/config/components/device-deletion-protection/policy.yaml" "$fixture_root/config/components/device-deletion-protection/" +expect_failure "deletion component without a production-style root" "production-style root milo-production must exist" +mkdir -p "$fixture_root/config/milo-production" +cat >"$fixture_root/config/milo-production/kustomization.yaml" <<'EOF' +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: [../base/safe] +EOF +expect_failure "production-style root without deletion protection" "must install the Device deletion policy and its binding" +cat >>"$fixture_root/config/milo-production/kustomization.yaml" <<'EOF' +components: [../components/device-deletion-protection] +EOF +"$repo_root/hack/validate-overlay-isolation.sh" "$fixture_root/config" "$fixture_root/config/standalone" +mkdir -p "$fixture_root/config/overlays/synthetic-with-protection" +cat >"$fixture_root/config/overlays/synthetic-with-protection/kustomization.yaml" <<'EOF' +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: [../../base/safe] +components: [../../components/device-deletion-protection] +EOF +expect_failure "test or synthetic root installing deletion protection" "renders Device deletion protection" +rm -rf "$fixture_root/config/overlays/synthetic-with-protection" +mkdir -p "$fixture_root/config/overlays/renamed-protection" +sed 's/name: fleet-device-deletion-protection/name: renamed-device-guard/; s/policyName: fleet-device-deletion-protection/policyName: renamed-device-guard/' "$repo_root/config/components/device-deletion-protection/policy.yaml" >"$fixture_root/config/overlays/renamed-protection/policy.yaml" +cat >"$fixture_root/config/overlays/renamed-protection/kustomization.yaml" <<'EOF' +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: [policy.yaml] +EOF +expect_failure "renamed Device deletion policy outside production roots" "renders Device deletion protection" +rm -rf "$fixture_root/config/overlays/renamed-protection" +sed 's/validationActions: \[Deny\]/validationActions: [Audit]/' "$repo_root/config/components/device-deletion-protection/policy.yaml" >"$fixture_root/config/components/device-deletion-protection/policy.yaml" +expect_failure "audit-only Device deletion binding" "must Deny in every namespace" +cp "$repo_root/config/components/device-deletion-protection/policy.yaml" "$fixture_root/config/components/device-deletion-protection/policy.yaml" + "$repo_root/hack/validate-overlay-isolation.sh" "$fixture_root/config" "$fixture_root/config/standalone" From 00a33dc774678697e678e70bdfd46dcac6e81491 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sun, 22 Nov 2026 16:22:46 -0600 Subject: [PATCH 074/518] feat(ui): derive capacity name from the Device The registration form no longer asks for a capacity name. It shows device-, which is what admission now requires, and marks every Device that shares a normalized serial, system UUID or provider host reference with another Device as Conflicting. Co-Authored-By: Claude Opus 5.5 --- ui/provider/README.md | 10 +++--- .../src/components/create-capacity-dialog.tsx | 21 ++++++------ .../src/lib/capacity-registration.test.ts | 26 +++++++++++---- ui/provider/src/lib/capacity-registration.ts | 32 ++++++++++++++++--- .../src/pages/capacity-registration.test.tsx | 9 +++--- ui/shared/fleet-api.ts | 2 +- 6 files changed, 67 insertions(+), 33 deletions(-) diff --git a/ui/provider/README.md b/ui/provider/README.md index ef4567c8..f55063c8 100644 --- a/ui/provider/README.md +++ b/ui/provider/README.md @@ -8,13 +8,15 @@ Operations in the navigation. The page has four tabs: - **Capacity** (the mount root, where the nav item points) lists the provider's MachineCapacities in every namespace. A verified host session can - register an existing `default` Device under an independently authored name. + register an existing `default` Device as `device-` capacity. Selection retains the exact Device UID/resourceVersion; the named reference is immutable. Registration is Disabled/Retain with cleaning explicitly unconfigured, without class assignment, allocation, preparation or positive - readiness. The server enforces permissions, physical-alias reservations and - lifetime fences. Unknown completion blocks retries and never deletes capacity - to roll back. See the [registration contract](../../docs/development/inventory-capacity-registration.md). + readiness. The capacity name is derived from the Device UID, so a Device + backs at most one capacity. Devices sharing a hardware alias are marked + Conflicting. The server enforces permissions and checks live Devices for + duplicates. Unknown completion blocks retries in the form and never deletes + capacity to roll back. See the [registration contract](../../docs/development/inventory-capacity-registration.md). - **Profiles** (`profiles`) lists MachineProfiles and creates new ones. A profile can't be changed after it is created, so there is no edit. - **Classes** (`classes`) lists MachineClasses and creates new ones: the diff --git a/ui/provider/src/components/create-capacity-dialog.tsx b/ui/provider/src/components/create-capacity-dialog.tsx index df50a62b..12c6c18c 100644 --- a/ui/provider/src/components/create-capacity-dialog.tsx +++ b/ui/provider/src/components/create-capacity-dialog.tsx @@ -1,10 +1,9 @@ import { Button } from '@datum-cloud/datum-ui/button'; -import { Input } from '@datum-cloud/datum-ui/input'; import { Label } from '@datum-cloud/datum-ui/label'; import { useQuery } from '@tanstack/react-query'; import { useContext, useLayoutEffect, useRef, useState, type FormEvent } from 'react'; import type { Device } from '../../../shared/fleet-api'; -import { ineligibleReason, registerCapacity, registrationDevices, registrationPermission, RegistrationUnknown } from '../lib/capacity-registration'; +import { capacityNameFor, ineligibleReason, registerCapacity, registrationDevices, registrationPermission, RegistrationUnknown } from '../lib/capacity-registration'; import { InventoryOperationContext, InventoryOperationReadyContext, InventoryOperationScope, type InventoryOperation } from '../lib/inventory-operation'; import { useInventoryRead } from '../lib/inventory-read'; import { confirmInventoryDismissal, InventoryDraftGuard, InventoryForm, InventoryFormSurface } from './inventory-form-surface'; @@ -21,7 +20,6 @@ export function CapacityRegistrationForm({ onRegistered }: { onRegistered?: () = const operation = useRef(undefined); const operationID = useRef(''); const [open, setOpen] = useState(false); - const [name, setName] = useState(''); const [selected, setSelected] = useState(); const [pending, setPending] = useState(false); const [unknown, setUnknown] = useState(false); @@ -33,16 +31,16 @@ export function CapacityRegistrationForm({ onRegistered }: { onRegistered?: () = useLayoutEffect(() => { scope.startLifecycle(); return () => scope.invalidate(); }, [scope]); const available = ready && !!parent && permission.data === true; const dismiss = () => { - if (confirmInventoryDismissal(!!name || !!selected, pending, unknown)) { scope.invalidate(); setOpen(false); } + if (confirmInventoryDismissal(!!selected, pending, unknown)) { scope.invalidate(); setOpen(false); } }; async function submit(event: FormEvent) { event.preventDefault(); if (!available || pending || unknown || !selected || !operation.current) return; setPending(true); setMessage(''); try { - await registerCapacity(name, selected, operationID.current, operation.current); - setMessage(`Registered ${name} as Disabled/Retain. Cleaning is unconfigured; readiness and availability remain unknown.`); - setName(''); setSelected(undefined); setOpen(false); onRegistered?.(); + const result = await registerCapacity(selected, operationID.current, operation.current); + setMessage(`Registered ${result.metadata.name} as Disabled/Retain. Cleaning is unconfigured; readiness and availability remain unknown.`); + setSelected(undefined); setOpen(false); onRegistered?.(); } catch (error) { setUnknown(error instanceof RegistrationUnknown); setMessage(error instanceof Error ? error.message : 'Registration unavailable.'); @@ -50,23 +48,22 @@ export function CapacityRegistrationForm({ onRegistered }: { onRegistered?: () = } const status = <>{message &&

        {message}

        }{!available &&

        {permission.isPending ? 'Checking registration permission…' : permission.error ? 'Registration unavailable: authorization could not be checked.' : 'Registration denied or unavailable for this session. Synthetic previews cannot register capacity.'}

        }; return <> - + { scope.startLifecycle(); operation.current = scope.begin(parent); operationID.current = crypto.randomUUID(); - setName(''); setSelected(undefined); setUnknown(false); setMessage(''); setOpen(true); + setSelected(undefined); setUnknown(false); setMessage(''); setOpen(true); }}>Register capacity}> void submit(event)} message={message}>

        Choose a Device in default. This creates an inert Disabled/Retain record, not usable capacity. Cleaning remains explicitly unconfigured. No hardware is prepared or changed.

        - + }}>{devices.data?.map(device => )} {devices.isPending &&

        Loading Devices…

        } {devices.error &&

        Devices are unavailable or access is denied. Registration is blocked.

        } {devices.data?.length === 0 &&

        No Devices are available in default.

        } - {selected &&

        The authored Device reference {selected.metadata.name} is immutable. This selection retains its exact incarnation and version; it is never silently refreshed.

        } + {selected &&

        Capacity name: {capacityNameFor(selected)}. It is derived from this Device, so the Device can back only one capacity. The Device reference {selected.metadata.name} is immutable. This selection retains its exact incarnation and version; it is never silently refreshed.

        }
        diff --git a/ui/provider/src/lib/capacity-registration.test.ts b/ui/provider/src/lib/capacity-registration.test.ts index a3713191..52ea1963 100644 --- a/ui/provider/src/lib/capacity-registration.test.ts +++ b/ui/provider/src/lib/capacity-registration.test.ts @@ -1,6 +1,6 @@ import { beforeEach, expect, it, vi } from 'vitest'; import type { Device } from '../../../shared/fleet-api'; -import { registerCapacity, ineligibleReason, REGISTRATION_DEVICE_UID, REGISTRATION_DEVICE_VERSION, RegistrationUnknown } from './capacity-registration'; +import { capacityNameFor, registerCapacity, ineligibleReason, REGISTRATION_DEVICE_UID, REGISTRATION_DEVICE_VERSION, RegistrationUnknown } from './capacity-registration'; import { InventoryOperationScope } from './inventory-operation'; const device: Device = { metadata: { name: 'chosen-hardware', namespace: 'default', uid: 'device-1', resourceVersion: '7' }, spec: { claimRef: { name: 'installation' }, identity: { model: 'test', serial: 'serial-1', systemUUID: '11111111-1111-1111-1111-111111111111' } } }; @@ -14,8 +14,9 @@ beforeEach(() => { }); }); -it('uses the exact selected Device, authored name, Disabled/Retain and no synthetic policy', async () => { - const result = await registerCapacity('authored-name', device, 'operation-1', new InventoryOperationScope().begin()); +it('uses the exact selected Device, the Device-derived name, Disabled/Retain and no synthetic policy', async () => { + const result = await registerCapacity(device, 'operation-1', new InventoryOperationScope().begin()); + expect(result.metadata.name).toBe('device-device-1'); expect(result.spec).toEqual({ deviceRef: { name: 'chosen-hardware' }, allocationPolicy: 'Disabled', reclaimPolicy: 'Retain', cleaningPolicyRef: { name: '' } }); expect(result.metadata.annotations).toMatchObject({ [REGISTRATION_DEVICE_UID]: 'device-1', [REGISTRATION_DEVICE_VERSION]: '7' }); expect(result.status).toBeUndefined(); @@ -26,20 +27,20 @@ it('uses the exact selected Device, authored name, Disabled/Retain and no synthe it.each(['uid', 'resourceVersion'] as const)('rejects stale selected %s without refreshing or dispatching', async field => { transport.mockImplementation(async input => String(input).includes('selfsubjectaccessreviews') ? Response.json({ data: { status: { allowed: true } } }) : Response.json({ data: { ...device, metadata: { ...device.metadata, [field]: 'changed' } } })); - await expect(registerCapacity('record', device, 'operation', new InventoryOperationScope().begin())).rejects.toThrow('selected Device changed'); + await expect(registerCapacity(device, 'operation', new InventoryOperationScope().begin())).rejects.toThrow('selected Device changed'); expect(transport.mock.calls.some(([url]) => String(url).includes('machinecapacities?'))).toBe(false); }); it('does not dispatch on permission revocation', async () => { transport.mockResolvedValue(Response.json({ data: { status: { allowed: false } } })); - await expect(registerCapacity('record', device, 'operation', new InventoryOperationScope().begin())).rejects.toThrow('permission is denied'); + await expect(registerCapacity(device, 'operation', new InventoryOperationScope().begin())).rejects.toThrow('permission is denied'); expect(transport).toHaveBeenCalledTimes(1); }); it('fences a session change before dispatch', async () => { const scope = new InventoryOperationScope(); transport.mockImplementation(async () => { scope.invalidate(); return Response.json({ data: { status: { allowed: true } } }); }); - await expect(registerCapacity('record', device, 'operation', scope.begin())).rejects.toThrow('No write was dispatched'); + await expect(registerCapacity(device, 'operation', scope.begin())).rejects.toThrow('No write was dispatched'); expect(transport).toHaveBeenCalledTimes(1); }); @@ -53,10 +54,21 @@ it.each(['network', 'timeout', 'session', 'bad receipt'])('retains an unknown ou if (failure === 'session') scope.invalidate(); return Response.json({ data: { metadata: {} } }); }); - await expect(registerCapacity('record', device, 'operation', scope.begin())).rejects.toBeInstanceOf(RegistrationUnknown); + await expect(registerCapacity(device, 'operation', scope.begin())).rejects.toBeInstanceOf(RegistrationUnknown); expect(transport.mock.calls.some(([, init]) => init?.method === 'DELETE')).toBe(false); }); +it('marks every Device sharing a normalized hardware alias as conflicting', () => { + const twin: Device = { metadata: { name: 'twin', namespace: 'default', uid: 'device-2', resourceVersion: '1' }, spec: { claimRef: { name: 'installation' }, identity: { model: 'test', serial: ' SERIAL-1 ', systemUUID: '22222222-2222-2222-2222-222222222222' } } }; + const unrelated: Device = { ...twin, metadata: { ...twin.metadata, name: 'unrelated', uid: 'device-3' }, spec: { ...twin.spec, identity: { model: 'test', serial: 'serial-3', systemUUID: '33333333-3333-3333-3333-333333333333' } } }; + expect(ineligibleReason(device, [device, twin, unrelated])).toContain('Conflicting'); + expect(ineligibleReason(twin, [device, twin, unrelated])).toContain('Conflicting'); + expect(ineligibleReason(unrelated, [device, twin, unrelated])).toBeUndefined(); + const hosted = (uid: string, id: string): Device => ({ ...unrelated, metadata: { ...unrelated.metadata, uid }, spec: { ...unrelated.spec, identity: { model: 'test', serial: `serial-${uid}`, systemUUID: uid === 'a' ? '44444444-4444-4444-4444-444444444444' : '55555555-5555-5555-5555-555555555555' }, providerHostRef: { system: 'Provider', type: 'server', id } } }); + expect(ineligibleReason(hosted('a', 'host-1'), [hosted('a', 'host-1'), hosted('b', ' HOST-1')])).toContain('Conflicting'); + expect(capacityNameFor(device)).toBe('device-device-1'); +}); + it('rejects partial and unidentified identity and non-default inventory', () => { expect(ineligibleReason({ ...device, spec: { ...device.spec, identity: { model: 'test', serial: 'only-serial' } } })).toContain('ambiguous'); expect(ineligibleReason({ ...device, metadata: { ...device.metadata, namespace: 'other' } })).toContain('unavailable'); diff --git a/ui/provider/src/lib/capacity-registration.ts b/ui/provider/src/lib/capacity-registration.ts index 8fbcc619..cbe5aff1 100644 --- a/ui/provider/src/lib/capacity-registration.ts +++ b/ui/provider/src/lib/capacity-registration.ts @@ -8,10 +8,33 @@ export const REGISTRATION_OPERATION = 'fleet.datumapis.com/registration-operatio const devicesPath = '/apis/fleet.datumapis.com/v1alpha1/namespaces/default/devices'; const capacitiesPath = '/apis/metal.datumapis.com/v1alpha1/namespaces/default/machinecapacities'; -export function ineligibleReason(device: Device): string | undefined { +// capacityNameFor mirrors the admission contract: one capacity per Device, +// named from the Device UID, so the API server rejects a second one. +export function capacityNameFor(device: Device): string { + return `device-${device.metadata.uid ?? ''}`; +} + +// aliases mirrors the server's normalization of serial, system UUID and +// provider host reference. +function aliases(device: Device): string[] { + const normalize = (value?: string) => (value ?? '').trim().toLowerCase(); + const result: string[] = []; + if (normalize(device.spec.identity.serial)) result.push(`serial:${normalize(device.spec.identity.serial)}`); + if (normalize(device.spec.identity.systemUUID)) result.push(`uuid:${normalize(device.spec.identity.systemUUID)}`); + const host = device.spec.providerHostRef; + if (host) result.push(`provider:${JSON.stringify([normalize(host.system), normalize(host.type), normalize(host.id)])}`); + return result; +} + +// ineligibleReason explains why a Device cannot be registered. Passing the +// listed Devices also marks every Device that shares a hardware alias with +// another one as conflicting until a person resolves the duplicate. +export function ineligibleReason(device: Device, listed: Device[] = []): string | undefined { if (device.metadata.namespace !== 'default' || !device.metadata.uid || !device.metadata.resourceVersion || device.metadata.deletionTimestamp) return 'Device incarnation is unavailable or deleting'; if (device.spec.identity.unidentified || !device.spec.identity.serial?.trim() || !device.spec.identity.systemUUID) return 'Both serial and system UUID are required; partial identity is ambiguous'; if (['unknown', 'none', 'n/a', 'default string', 'to be filled by o.e.m.'].includes(device.spec.identity.serial.trim().toLowerCase()) || ['00000000-0000-0000-0000-000000000000', 'ffffffff-ffff-ffff-ffff-ffffffffffff'].includes(device.spec.identity.systemUUID)) return 'Placeholder identity is ineligible'; + const own = aliases(device); + if (listed.some(other => other.metadata.uid !== device.metadata.uid && aliases(other).some(alias => own.includes(alias)))) return 'Conflicting: another Device shares this hardware identity; resolve the duplicate first'; return undefined; } @@ -31,13 +54,14 @@ export async function registrationDevices(): Promise { export class RegistrationUnknown extends Error { constructor(name: string, readonly operationID: string, detail: string) { - super(`Registration of ${name} is not confirmed. ${detail} Reservations may be retained. Do not retry under another name or delete capacity to roll back; ask an operator to reconcile operation ${operationID}.`); + super(`Registration of ${name} is not confirmed. ${detail} Check whether capacity ${name} exists before registering again; its name is derived from the Device, so a repeat cannot create a second record. Do not delete capacity to roll back. Client operation ${operationID}.`); } } -export async function registerCapacity(name: string, selected: Device, operationID: string, operation: InventoryOperation): Promise { +export async function registerCapacity(selected: Device, operationID: string, operation: InventoryOperation): Promise { operation.assertCurrent(); - if (!/^[a-z0-9]([-a-z0-9]*[a-z0-9])?$/.test(name) || name.length > 63 || !operationID) throw new Error('Enter a valid authored capacity name.'); + const name = capacityNameFor(selected); + if (!selected.metadata.uid || !operationID) throw new Error('The selected Device has no incarnation to register.'); if (ineligibleReason(selected)) throw new Error(ineligibleReason(selected)); if (!await registrationPermission()) throw new ApiError(403, 'Capacity registration permission is denied or unavailable.'); operation.assertCurrent(); diff --git a/ui/provider/src/pages/capacity-registration.test.tsx b/ui/provider/src/pages/capacity-registration.test.tsx index 10769010..589f5138 100644 --- a/ui/provider/src/pages/capacity-registration.test.tsx +++ b/ui/provider/src/pages/capacity-registration.test.tsx @@ -21,7 +21,6 @@ async function openForm() { const trigger = await screen.findByRole('button', { name: 'Register capacity' }); await waitFor(() => expect(trigger).toBeEnabled()); fireEvent.click(trigger); await screen.findByRole('option', { name: 'server-a' }); - fireEvent.change(screen.getByLabelText('Capacity name'), { target: { value: 'authored-record' } }); fireEvent.change(screen.getByLabelText('Device'), { target: { value: 'device-1' } }); return router; } @@ -29,7 +28,7 @@ async function openForm() { it('registers the selected incarnation through a real host session fence', async () => { await openForm(); fireEvent.click(screen.getByRole('button', { name: 'Register Disabled capacity' })); - expect(await screen.findByText(/Registered authored-record as Disabled\/Retain/)).toBeInTheDocument(); + expect(await screen.findByText(/Registered device-device-1 as Disabled\/Retain/)).toBeInTheDocument(); expect(fetcher.mock.calls.filter(([url, init]) => String(url).includes('machinecapacities?') && init?.method === 'POST')).toHaveLength(1); expect(screen.queryByRole('checkbox')).toBeNull(); }); @@ -38,7 +37,7 @@ it('visible blur/focus is a no-op for the selected baseline and draft', async () await openForm(); const before = fetcher.mock.calls.length; fireEvent(window, new Event('blur')); fireEvent(window, new Event('focus')); - expect(screen.getByLabelText('Capacity name')).toHaveValue('authored-record'); + expect(screen.getByText('device-device-1')).toBeInTheDocument(); expect(screen.getByLabelText('Device')).toHaveValue('device-1'); expect(fetcher.mock.calls).toHaveLength(before); }); @@ -51,8 +50,8 @@ it('keeps unknown completion in the form and prevents retry and rollback', async return Response.json({ data: device }); }); fireEvent.click(screen.getByRole('button', { name: 'Register Disabled capacity' })); - expect(await screen.findByText(/Reservations may be retained/)).toBeInTheDocument(); + expect(await screen.findByText(/Check whether capacity device-device-1 exists/)).toBeInTheDocument(); expect(screen.getByRole('button', { name: 'Register Disabled capacity' })).toBeDisabled(); - expect(screen.getByLabelText('Capacity name')).toHaveValue('authored-record'); + expect(screen.getByLabelText('Device')).toHaveValue('device-1'); expect(fetcher.mock.calls.some(([, init]) => init?.method === 'DELETE')).toBe(false); }); diff --git a/ui/shared/fleet-api.ts b/ui/shared/fleet-api.ts index 7baf6b96..3e4e65c9 100644 --- a/ui/shared/fleet-api.ts +++ b/ui/shared/fleet-api.ts @@ -143,7 +143,7 @@ export type AllocationPolicy = 'Enabled' | 'Disabled'; export interface MachineCapacity { metadata: ObjectMeta; spec: { - /** Immutable authored name. Registration retains incarnation evidence privately. */ + /** Immutable Device name. Registration records the Device UID and version in annotations. */ deviceRef: LocalReference; /** Defaults to Disabled. */ allocationPolicy: AllocationPolicy; From ef65a81109c7a2d9ab773648fa7062d902cbab52 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sun, 22 Nov 2026 16:22:46 -0600 Subject: [PATCH 075/518] docs(registration): record the no-ledger decision Rewrite the stage-1 contract around the decision to drop the ledger and signed activation: live-Device checks, Device-derived capacity names, the documented duplicate race, and optional Device deletion protection, including deletecollection, namespace and project cascades, remediation and retirement. Remove the storage rollout runbook, which only described the ledger. Co-Authored-By: Claude Opus 5.5 --- config/README.md | 52 +- docs/architecture/design.md | 4 +- docs/development/README.md | 6 +- .../inventory-capacity-registration.md | 639 ++++++++---------- docs/operations/physical-inventory.md | 9 +- 5 files changed, 337 insertions(+), 373 deletions(-) diff --git a/config/README.md b/config/README.md index 8a36c5e2..55020bb5 100644 --- a/config/README.md +++ b/config/README.md @@ -9,42 +9,45 @@ entitlements, ServiceAvailability resources, and publication rules must referenc `metal`. See the [API architecture](../docs/architecture/README.md) for group separation and breaking alpha rename constraints. -The repository publishes two production manifest roots. They target different -API servers and must be reconciled independently. +The repository publishes Milo and management-cluster manifest roots. They +target different API servers and must be reconciled independently. | Root | Destination | Contents | | --- | --- | --- | -| `config/milo` | Milo root control plane | Fleet CRDs (including the `fleet.datumapis.com` inventory kinds), IAM protected resources and roles, service/quota registration, and the mandatory capacity-registration webhook | +| `config/milo` | Milo root control plane | Fleet CRDs (including the `fleet.datumapis.com` inventory kinds), IAM protected resources and roles, service/quota registration, and the mandatory capacity-registration webhook. Devices can be deleted. | +| `config/milo-production` | Milo root control plane (production-style) | `config/milo` plus Device deletion protection | | `config/overlays/management-plane` | Fleet management cluster | Fleet CRDs, manager and inert-registration workloads and RBAC, private-record namespaces, and admission fences | | `config/overlays/synthetic-staging` | Fleet management cluster (non-production only) | Management-plane resources plus an explicit synthetic allocator/provider integration | -The synthetic staging overlay explicitly excludes the inert-registration -service and its retention policies. Pair it with `config/milo-synthetic` in a -**separate non-production Milo control plane**, not production `config/milo`. -That root preserves the pre-registration synthetic API contract. There is no -request field, actor exemption, or runtime switch that bypasses production -registration admission. Never point synthetic lifecycle handlers at the -production registration authority or its private ledger. +`config/components/device-deletion-protection` is an optional component: a +ValidatingAdmissionPolicy and binding that deny every Device `DELETE`, with no +exemptions. Each environment chooses whether to install it. Production-style +Milo control planes use `config/milo-production`; test, staging and synthetic +control planes that need Device deletions use `config/milo` or +`config/milo-synthetic`. `hack/validate-overlay-isolation.sh` rejects any other +root that renders the policy. Namespace and project deletions that reach a +protected Device stay stuck rather than deleting it; see +[Device deletion protection](../docs/development/inventory-capacity-registration.md#device-deletion-protection). + +The synthetic staging overlay excludes the inert-registration service. Pair it +with `config/milo-synthetic` in a **separate non-production Milo control +plane**, not production `config/milo`. That root preserves the +pre-registration synthetic API contract. There is no request field, actor +exemption, or runtime switch that bypasses production registration admission. The one `fleet-manager` Deployment serves every Milo project that consumes the `metal` service; see [project discovery](#project-discovery). -The [signed expansion and transport-first contract](../docs/development/registration-storage-rollout.md) -defines the required operator public-key ConfigMap, retained segments, activation -gate, byte budgets and ordered parent infrastructure work. Pod TCP readiness is -transport-only; it must not enable UI registration. - The separate `fleet-registration` Deployment serves inert inventory-backed -capacity admission only. Its TLS trust, read/SAR credentials, webhook serving CA -and one-time private ledger bootstrap are environment-owned. Read the +capacity admission only. It keeps no state: each capacity create is checked +against live Devices and capacities in the provider projects. Its TLS trust, +read/SAR credentials and webhook serving CA are environment-owned; it has no +host RBAC and mounts no service account token. Read the [registration rollout contract](../docs/development/inventory-capacity-registration.md#production-packaging-and-rollout) -before applying either root: an unavailable authority blocks capacity writes -globally, and fences Device writes and protected lifetime deletions in provider -or ambiguous inventory contexts. Admission-time trusted-context conditions keep -proven unrelated Project inventory independent of webhook availability. All four webhook -entries require the same serving CA and endpoint; their scope must match the -private ledger, which must never be reset by GitOps. This does not enable -production allocation or provisioning. +before applying either root: an unavailable service blocks capacity writes +globally, and nothing else. Pod TCP readiness is transport-only; it must not +enable UI registration. This does not enable production allocation or +provisioning. `config/components/service-catalog-staging` is a Kustomize component with staging's Bare Metal prices: committed servers and server setup, which @@ -122,6 +125,7 @@ Render both production roots before publishing the Kustomize bundle: ```sh kustomize build config/milo >/dev/null +kustomize build config/milo-production >/dev/null kustomize build config/milo-synthetic >/dev/null kustomize build config/overlays/management-plane >/dev/null kustomize build config/overlays/synthetic-staging >/dev/null diff --git a/docs/architecture/design.md b/docs/architecture/design.md index f44765d7..7ee559f7 100644 --- a/docs/architecture/design.md +++ b/docs/architecture/design.md @@ -20,8 +20,8 @@ preserves provenance and outstanding review points; the original discussions rem The implemented [stage-1 registration decision](../development/inventory-capacity-registration.md) allows explicitly unconfigured cleaning only for inert Disabled/Retain records. -It uses a separate private CAS ledger and project-plane admission, not allocation -custody or provider enrollment. Enabling and preparation remain forbidden until +It uses stateless project-plane admission against live Devices, plus optional +Device deletion protection, not allocation custody or provider enrollment. Enabling and preparation remain forbidden until their policy resolution and authorization contracts are implemented. ## Problem and intended outcome diff --git a/docs/development/README.md b/docs/development/README.md index e486d2bb..d4ccb76d 100644 --- a/docs/development/README.md +++ b/docs/development/README.md @@ -20,9 +20,9 @@ event-driven Machine allocation, contention, cleanup, and reuse through the public project API. Production caller-preserving allocation admission, replayable Milo event adapters, and production provider integration are not implemented. Inert [inventory-backed capacity registration](inventory-capacity-registration.md) -now has a caller-preserving admission service, a separate CAS registration -ledger, exact-incarnation recovery, and a session-fenced default-namespace Device -picker. It admits only Disabled/Retain records with cleaning explicitly +now has a stateless caller-preserving admission service that checks live +Devices, one capacity per Device through a Device-derived name, optional Device +deletion protection, and a session-fenced default-namespace Device picker. It admits only Disabled/Retain records with cleaning explicitly unconfigured; deployment trust inputs and live Milo acceptance remain required. An opt-in [local KVM installation harness](../operations/local-vm.md) implements a bounded libvirt executor and guest installer using the same lifecycle library. diff --git a/docs/development/inventory-capacity-registration.md b/docs/development/inventory-capacity-registration.md index 976716fd..5278d81c 100644 --- a/docs/development/inventory-capacity-registration.md +++ b/docs/development/inventory-capacity-registration.md @@ -9,18 +9,48 @@ name-derived Device reference, invented cleaning default, allocation checkbox, and unrestricted frontend create helper remain removed. Existing capacity listing and legacy values remain visible; no existing object is migrated. -## Public contract and authority +## Decision: no registration ledger + +An earlier revision kept a private ledger in host-cluster Secrets. Its job was +to remember Device identities after a Device was deleted, and it grew into +tombstones, incarnation fences, permanent alias retention, `Unknown` outcomes, +a mutable tail with sealed segments, signed expansion and activation, epochs +and growth limits. The user decided this was overengineering and replaced it +with the following: + +1. **Devices are not deleted.** An optional ValidatingAdmissionPolicy denies + every Device `DELETE`. An environment decides whether to install it; see + [Device deletion protection](#device-deletion-protection). +2. **No signed activation.** The bootstrap/activation gate, `/activationz`, + `/status`, the operator control key and ConfigMap, + `cmd/fleet-registration-control` and signed controls are gone. The + registration webhook is an ordinary fail-closed webhook (`failurePolicy: + Fail`) with mutual TLS, scoped credentials and least privilege. +3. **Registration checks live objects.** The webhook keeps no state. It + checks the live Device and capacities through the API server on every + request. + +Rationale: when Devices are never deleted, the live Device list already holds +every identity the ledger used to remember, so a second store adds failure +modes without adding information. Environments that need to delete Devices, +such as test and synthetic environments, do not hold real machines and do not +need permanent identity retention. -The staff form selects an existing `Device` in `default`, retains its UID and -resourceVersion as an immutable selection baseline, and authors an independent -capacity name. It POSTs to the existing provider project's `MachineCapacity` -API using the staff portal's caller-preserving proxy. `spec.deviceRef` remains -a name-only reference. It must not be a generated capacity name masquerading as -a Device name. +## Public contract and authority -The only admitted new capacity contract is: +The staff form selects an existing `Device` in `default` and keeps its UID and +resourceVersion as an immutable selection baseline. It POSTs to the provider +project's `MachineCapacity` API through the staff portal's caller-preserving +proxy. The admitted create is: ```yaml +metadata: + name: device- + namespace: default + annotations: + fleet.datumapis.com/registration-device-uid: + fleet.datumapis.com/registration-device-version: + fleet.datumapis.com/registration-operation: spec: deviceRef: {name: selected-device} allocationPolicy: Disabled @@ -28,348 +58,273 @@ spec: cleaningPolicyRef: {name: ""} ``` +`spec.deviceRef` remains a name-only reference. The capacity name is no longer +authored: it is `device-` followed by the Device UID (43 characters). This +changes the earlier contract, where staff typed an independent name. All other +fields and the three annotations are unchanged. The annotations are request +preconditions and traceability, not authentication or ownership proofs. The +operation ID is no longer used for deduplication. + An empty cleaning-policy name explicitly means **unconfigured**, not a policy -named `default`, synthetic cleaning, or authorization to prepare. The CRD permits -it only while Disabled. The production admission handler rejects *all* capacity -updates, status updates and deletes, including setting a nonempty policy and -enabling in the same request. Real policy resolution and policy-use authorization +named `default`, synthetic cleaning, or authorization to prepare. The CRD +permits it only while Disabled. The webhook rejects *all* capacity updates, +status updates and deletes. Real policy resolution and policy-use authorization are future prerequisites for a separately designed transition; there is no -stage-1 preparation endpoint. Legacy nonempty cleaning references remain valid -in the schema and synthetic lifecycle environments remain separate. - -Three protected request-precondition annotations carry the selected UID, -selected resourceVersion and stable client operation ID: -`fleet.datumapis.com/registration-device-uid`, -`fleet.datumapis.com/registration-device-version`, and -`fleet.datumapis.com/registration-operation`. They are not authentication or -ownership proofs. A create with copied annotations still goes through the full -admission protocol; updates and deletion cannot remove or replace them. The -private ledger, not these public annotations, binds the exact capacity UID. - -`cmd/fleet-registration` serves a validating admission webhook. Its production -implementation uses Milo's authenticated `iam.miloapis.com/parent-*` extras, -requires a single Project context and an actor UID, and resolves the current -Project UID through the root Milo client. It does not use a project, actor or -permission bypass from request annotations. Separate SubjectAccessReviews pass -through the caller's username, UID, groups and extras for current -`machinecapacities.create` and named `devices.get` in `default`. Permission errors, -denials, missing identity and incomplete evaluations fail closed. Both checks -are repeated before reservation, alongside uncached Device and namespace -lifetime/version reads. Controller credentials supply reads and SAR evaluation, -not the caller's registration authority. +stage-1 preparation endpoint. + +`cmd/fleet-registration` serves the validating webhook. For each create it: + +1. requires Milo's authenticated `iam.miloapis.com/parent-*` extras naming a + single Project in the configured provider scope, and an actor UID; +2. requires the `default` namespace, the exact shape above, and a name equal + to `device-`; +3. resolves the current Project lifetime through the root Milo client; +4. runs SubjectAccessReviews with the caller's username, UID, groups and + extras for `machinecapacities.create` and named `devices.get` in + `default`. Denials, errors and incomplete evaluations fail closed. This + happens before the Device is read, so an unauthorized caller cannot learn + whether a Device exists; +5. reads the Device uncached. A missing Device is denied. Its UID and + resourceVersion must equal the annotations, and it must not be deleting; +6. requires both a non-placeholder serial and a canonical system UUID, and a + complete provider host reference when one is present; +7. lists Devices and capacities in **all namespaces of every configured + provider project** and denies when: + - another Device shares a normalized alias (below); + - any capacity already references this Device by name or by its UID + annotation; + - any capacity has unresolved physical identity, so non-conflict cannot be + established; or + - any capacity is backed by a Device that shares an alias. + +The webhook writes nothing. Dry-run requests are evaluated like real ones +(`sideEffects: None`). Controller credentials supply reads and SAR evaluation, +not the caller's registration authority. Errors about records in another +provider project do not name them. The webhook accepts only mutually authenticated TLS from a dedicated API-server client CA. Do not use a broad tenant/client CA: an AdmissionReview received from -an untrusted client is not evidence of an authenticated actor. The server also -checks the installed root webhook configuration at signed activation and before admission: -the exact write rules, explicit serving CA, Fail policy, common authority -endpoint, and the restricted match conditions described below. Label selectors, -missing fences, expanded rules, and conditions differing from the configured -provider scope are rejected. Scope changes require an operator-coordinated -manifest and ledger migration, not caller-selected labels or annotations. - -## Physical identity and bounded deduplication - -The complete operator-configured provider-project list and Milo authority are -fixed in one private ledger. All replicas, names and projects in that scope use -the same resourceVersion CAS. Configuration must match the retained scope -exactly; changing the list requires an explicit ledger migration, not a restart -with a smaller list. The packaged UI and deployment use `datum-cloud`. - -Eligible Devices must have **both** a recorded non-placeholder serial and a -canonical non-placeholder system UUID. The canonical asset key is the digest of -`uuid:` plus that UUID. Known reservation aliases include the digests of the -normalized serial, UUID, and, when present, provider host system/type/ID tuple. -Normalization trims and lowercases values; conservative false-positive -collisions require operator investigation rather than choosing a winner. -MAC addresses, BMC endpoints, installation claims, rack placement and asset tags -are not canonical chassis identifiers in this stage. - -Every known alias is claimed in the same CAS transaction. A second Device with -any shared alias, including inconsistent serial/UUID pairs or a shared provider -host reference, is ambiguous and is rejected rather than merged or adopted. -Before reservation the handler reads Devices and capacities in **all namespaces -of every configured provider project**. Existing unresolved legacy capacity -blocks new registration because non-conflict cannot be established. Existing -capacity bound to a conflicting asset blocks it regardless of allocation -policy or reported readiness. None of these records or allocations is changed. +an untrusted client is not evidence of an authenticated actor. + +## Physical identity and duplicates + +Aliases are the digests of the normalized serial, system UUID and, when +present, provider host system/type/ID tuple. Normalization trims and lowercases +values. A shared alias between two Devices, including inconsistent +serial/UUID pairs, is ambiguous: registration is denied for both until a person +resolves the duplicate. Neither is merged or adopted. MAC addresses, BMC +endpoints, installation claims, rack placement and asset tags are not chassis +identifiers in this stage. This is **not universal physical deduplication** or proof of real hardware -identity. Serial-only and UUID-only records cannot prove the same hardware in -the absence of shared evidence; neither can be selected for registration. -Different fabricated or incomplete identifiers, assets outside the configured -provider scope, and physical equipment absent from inventory cannot be compared -reliably. Recording identity does not establish physical verification or -ownership. Production allocation remains disabled independently. - -## Serialization and recovery - -`fleet-capacity-registration-v1` is a separate host-cluster Secret in -`fleet-system-private`; it is **not** allocation custody. The service updates only -that root and can create/read immutable retained segments under the host policy. -The [storage and bootstrap protocol](registration-storage-rollout.md) adds signed -lossless expansion and deny-only transport startup. Its JSON retains the actor, exact -API-normalized create object, admission request UID, client operation ID, -Project/namespace lifetimes, Device UID/resourceVersion, aliases, canonical key, -and API-assigned capacity UID **before allowing the public create**. Kubernetes -assigns that UID before validating admission; envtest verifies a caller-supplied -UID is replaced and the retained UID matches the actual result. - -CAS conflicts repeat authorization and observation before another reservation -attempt. No public object, allocation, status, provider, networking, or cleaning -write is performed by the registration service. Capacity persistence is the -original caller's API-server operation. All new entries start `Unknown` because -another admission plugin, API storage failure, timeout or crash can still prevent -the create. A failed CAS response may itself have committed: it is not released. - -Device creation also reserves its known aliases before admission completes. -Device deletion retains a permanent UID tombstone before admission completes. -Both use the same ledger CAS, closing the registration-versus-pending-create or -delete race. Potentially changing Device updates retain their old resourceVersion -before admission completes. Registration rejects a selected version with such an update fence; -only an explicitly selected newer persisted version can pass it. This serializes -pending metadata/spec updates with registration without silently refreshing the -selection. The sole exception is a provably unchanged update: the complete old -and new admission JSON objects are equal, including metadata, managed fields, -status and any fields unknown to Fleet's typed Device. JSON key order and -whitespace are immaterial; numbers are compared without floating-point rounding. -An unchanged Kubernetes update can keep its existing resourceVersion, and must -not permanently fence that still-current version. This exception adds no new -reservation and **never removes an existing pending-update fence**. It does not -infer success from a later read, refresh a selected version, or relax identity -and registered-spec checks. Any differing field still takes the conservative -fencing path. An uncertain potentially changing update can therefore leave its -old version ineligible even if storage ultimately made no change. Failed Device -creates can likewise retain an alias reservation. -Update fences are coalesced to one record per provider Project and Device UID, -not one per observation. Before replacing a retained version, admission reads -the Device directly through the uncached project client and requires the current -UID and resourceVersion to equal both incoming update incarnations/baselines. -It rejects stale admissions rather than replacing a newer pending fence. The -ledger snapshot precedes that authoritative read; a competing ledger write -forces a full CAS retry and another Device read. All concurrent updates at the -same baseline share its fence. Once the API server has persisted a newer version, -optimistic concurrency prevents an older-baseline write from subsequently -committing; an API-server storage retry must re-enter admission at its new -baseline. Thus superseded fences can be compacted without allowing an unfinished -current-baseline update to race registration. ResourceVersions are compared only -for equality, never ordered numerically. - -Coalescing unions creation aliases and never clears a deletion tombstone. -A deletion replaces update history with a permanent all-version tombstone; -later changing updates for that UID are rejected. Older-build multiple-version -records are compacted only when this same authoritative update check succeeds, -or when deletion installs a stronger permanent tombstone. Unrelated incarnations -are untouched. An unknown/rejected write at the still-current version stays -fenced, including after restart and no-op updates. Recovery still requires a -genuine persisted change and explicit new selection, not automatic ledger cleanup. -The selected Device's own successful creation reservation is not a conflict. -Identity/provider-alias changes are forbidden; registered Device specs are -frozen, and its deletion and same-name replacement are forbidden. The default -provider namespace and configured provider Project deletions are denied. - -Recovery observes the exact retained capacity UID, namespace and Project -lifetimes, Device incarnation, aliases and authored input. An exact observed -object becomes `Recorded`, which means only that the inert record exists. -Absence remains `Unknown`; replacement or lifetime loss is a conflict/tombstone, -never adoption. Recovery never creates, deletes, retries under a different name, -or publishes positive readiness. It runs every 30 seconds and after restart; -CAS conflicts leave evidence retained for a later observation. Repeating POST -is not the recovery mechanism: inspect the original name and retained operation. - -Reservations and tombstones have no automatic expiry or release path in stage 1. -This deliberately includes create attempts that never persisted and deleted -Devices that were never registered: their known hardware aliases remain reserved, -and recreating that hardware under a new UID fails closed. Stage 1 has no safe -operator release command. Future reconciliation must prove the original outcome, -all competing operations and lifetime ownership before designing a fenced release; -neither manual Secret editing nor speculative expiry is an accepted workaround. - -Routine updates to an incarnation use one record with at most one pending -resourceVersion, retained aliases and a deletion bit. This bounds growth by -distinct incarnations/aliases and registration operations, **not** by elapsed -collector observations. It is not an unlimited-inventory or universal deduplication -guarantee: retained incarnations and reservations can still fill the pilot ledger. -The mutable tail refuses growth past 650,000 encoded bytes (the boundary fits), -leaving sealing headroom. Signed expansion seals up to sixteen immutable segments; -existing v1 tails up to 750,000 bytes can migrate losslessly. This is bounded growth, -not unlimited capacity, alias expiry, or permission to increase caps. -Admission makes at most six CAS attempts with complete reevaluation after conflicts; -exhaustion emits a structured error with project, operation identity and attempt -count, without actor credentials or ledger contents. Lost or corrupt -ledger state, scope changes, uncertain operations and full ledgers require -operator-led reconciliation/migration; deleting or recreating the ledger is not -a repair. Ledger update protection and private-namespace deletion protection -are installed in the host cluster. Cluster administrators who can remove those -fences or restore arbitrary storage remain outside the guarantee. +identity. Hardware outside the provider scope or absent from inventory cannot +be compared. Recording identity does not establish physical verification or +ownership. + +### One capacity per Device + +Two creates for the same Device carry the same derived name, so the API server +rejects the second with `AlreadyExists` even when both pass admission +concurrently. The webhook also refuses a Device that a legacy capacity already +references under another name. A replacement Device created under a deleted +Device's name is refused too, because the old capacity still references that +name. + +### The documented duplicate race + +The duplicate check is a point-in-time list. It does not close this race: + +- Device A is being registered while Device B, which shares A's serial, is + being created. If B is not yet visible when A's registration lists Devices, + A's capacity is admitted. + +No reservation store closes this, by decision. The consequences are bounded: + +- B can never be registered, because A now exists and shares its alias. +- A's capacity is `Disabled`, and the webhook denies every capacity update, so + it can never become available in stage 1. +- The staff registration form lists every Device and marks each one that + shares an alias with another as **Conflicting**, so both A and B show the + conflict until a person resolves it. +- Any future transition that enables capacity must recheck duplicates against + live Devices at that time. + +Two registrations racing for two already-existing Devices that share an alias +both fail, because each sees the other Device. Device status has no writer +today, so there is no server-side eligibility condition to set; reporting +conflicts through Device status is a follow-up. + +## Device deletion protection + +`config/components/device-deletion-protection` is a Kustomize component with a +ValidatingAdmissionPolicy and binding named `fleet-device-deletion-protection`. +It denies every `DELETE` on `devices.fleet.datumapis.com` (all versions, all +namespaces) with `failurePolicy: Fail` and reason `Forbidden`. + +- **Where it is installed.** Devices are stored and admitted by the Milo + control plane: `config/components/inventory` registers the CRD there, and + records live in provider projects. The component therefore belongs with the + Milo root, not the management-cluster host overlays, which have no Device + CRD. Like the registration webhook, it is installed at the Milo root and + relies on Milo running its root admission policies for project-routed + requests (pinned Milo `v0.36.9` enables the `ValidatingAdmissionPolicy` + plugin). Confirm this on the deployed Milo before relying on it. +- **Which roots include it.** `config/milo-production` is `config/milo` plus + the component, and is the production-style root. `config/milo` (consumed by + staging and test control planes that need Device deletion), + `config/milo-synthetic`, `config/inventory`, `config/standalone` and every + host overlay leave it out. `hack/validate-overlay-isolation.sh` fails if a + production-style root lacks it, or if any other root renders it. +- **No exemptions.** No user, group or service account is exempt, including + cluster administrators. The escape hatch is an environment not installing + the component. Anyone able to delete the binding is outside the guarantee. +- **deletecollection.** The API server admits each object of a collection + delete individually as a `DELETE`, so a collection delete that includes a + Device fails and leaves Devices in place. Other objects in the same call may + already be gone. +- **Garbage collection and finalizers.** Owner-reference cascades issue the + same `DELETE` and are denied. Because the `DELETE` is denied, a Device never + gets a deletion timestamp, so finalizers never run. +- **Namespace and project deletion (fail-closed: stays stuck).** A policy + cannot see what a namespace contains, so it does not block the namespace + `DELETE`. The namespace becomes `Terminating`, the namespace controller + deletes the other contents, and its Device deletions are denied. The + namespace stays `Terminating` with its Devices intact and readable; it + accepts no new objects. Milo keeps `default` undeletable, and Milo's project + purge drains `default` in place and reports remaining Devices as blockers on + the Project. So deleting a provider project stops with its Devices in place. + Other inventory in that namespace or project (for example DeviceClaims) is + still deleted before the cascade stops. Capacity is not, because the + registration webhook denies capacity deletes. Do not delete namespaces or + projects that hold Devices. +- **Remediation for a stuck namespace or project.** Kubernetes cannot cancel + a namespace deletion. Either leave it `Terminating`, which keeps every + Device, or have the environment owner deliberately decide to give up those + identities: remove the binding, let the cascade finish, and reinstall the + component. The second option loses the Device records and their duplicate + protection, so it is an explicit ownership decision, not routine repair. +- **Retirement.** A machine leaving service keeps its Device. Its capacity is + already `Disabled` and cannot be changed, which is the only retirement state + stage 1 has. Devices have no lifecycle or retirement field (see + [Planning and registering physical devices](../operations/physical-inventory.md)). + A Device retirement state is a follow-up. + +### Deleting a Device where deletion is allowed + +Without the component, deleting a Device that backs capacity leaves the +capacity in place, still `Disabled`. The webhook denies every update and +delete of it, so it cannot become available. No owner reference links the two: +the webhook rejects owner references on registration, and garbage collection +would be denied anyway because capacity deletes are fenced. The orphaned +capacity keeps its Device UID annotation and name, which also prevents a +replacement Device with the same name from registering. Clean it up only in +environments where capacity writes are not fenced, such as synthetic ones. ## Production packaging and rollout -- `config/milo` includes the mandatory Fail-closed registration webhook on the - **actual project resource path**, not just a manager-side helper. Four separate - admission entries use the same endpoint. Capacity create/update/delete/status - remains globally fenced. Device create/update/delete/status excludes only - proven unrelated Project contexts (in **all namespaces**, because alias scans - cover all of them). Namespace deletion matches only `default` in protected or - ambiguous contexts. Project deletion matches only exact configured provider Project - names, including root requests without parent extras. Unnamed collection - deletion cannot prove exclusion of protected lifetimes and is explicitly - denied (including when transport is healthy); delete unrelated lifetimes by - exact name instead. No object-label opt-in or opt-out exists. -- `config/overlays/management-plane` includes a separate two-replica registration - Deployment, TLS Service, narrowly scoped host RBAC, and private retention - policies. It does not enable production lifecycle handlers. -- The webhook consumes parent context from Milo's standard admission extras. - The API server evaluates the inventory/lifetime CEL match conditions **before - webhook transport**. An unreachable service or incomplete certificate rollout - therefore cannot block unrelated consumers' Device writes, other namespaces, - or unrelated Project deletions through these entries. In-scope writes remain - Fail-closed during transport failure; capacity writes remain globally blocked. - Handler-side exemptions alone are not an outage-isolation boundary. -- These conditions rely on **server-established routing context**, not arbitrary - identity-provider claims. In pinned Milo `v0.36.9`, - `ProjectRouterWithRequestInfo` establishes the project from the routed path; - `ProjectContextAuthorizationDecorator` overwrites all three parent extras - after authentication/impersonation and before authorization/admission - (`cmd/milo/apiserver/config.go`). The pinned filter regression verifies that - conflicting caller extras are overwritten while actor identity is preserved. - Only a singleton `Project` / `resourcemanager.miloapis.com` / nonempty name - outside the protected list proves that inventory is unrelated and skips the - webhook. Missing, malformed, root, Organization and User inventory contexts - remain fail-closed. This conservative fallback matters: pinned Milo's later - Organization/User decorators can obscure the Project extras for nested paths; - a non-Project context must not be mistaken for proof of unrelated storage. - Regression tests exercise those actual pinned decorators and the resulting - admission matching. Root Project deletion still uses only exact protected - names; other namespace names remain outside the namespace fence. - This scope is **not safe on a server that lets caller-supplied extras replace - its actual routing context**, or exposes an alternate provider-storage path - appearing as a different valid Project. Confirm these properties on the - deployed Milo path before enabling use. Unscoped/root Device writes are not - supported by this pilot; that is an explicit fail-closed limit, not universal - outage isolation for every possible inventory route. -- Legacy capacity writes in configured production scope fail closed; legacy - records remain readable and unchanged. Outside configured provider scope, - ordinary inventory writes are unaffected, but new capacity writes are denied. - The synthetic/standalone test APIs do not install this production webhook. - Pair the synthetic staging overlay with `config/milo-synthetic` on a separate - non-production API server; that overlay excludes registration workloads and - retention policies. Never use these synthetic roots in production or share - the registration authority's ledger. This is deployment isolation, not a - caller-selected bypass. - -Environment-owned inputs are required, just as for the existing manager. No -real credentials or certificates are supplied by this repository: - -1. Preserve the existing `fleet-manager-config` authority and discovery paths. - Supply separate `fleet-registration-milo-kubeconfig` and - `fleet-registration-project-kubeconfig` Secrets at the mounted paths. The root - credential needs Project reads and registration webhook-configuration reads; - the project credential needs Device and capacity get/list across the complete - scope, namespace get, and SubjectAccessReview create. It needs **no public - capacity or Device writes**, allocation permissions or provider credentials. -2. Supply `fleet-registration-tls` with `tls.crt`, `tls.key`, and a dedicated - `client-ca.crt`. Configure Milo's admission webhook client kubeconfig with an - API-server client certificate signed by that CA. Patch the webhook URL for - actual cross-cluster reachability and set every entry's - `clientConfig.caBundle` to the serving CA. All four entries must have the same - client configuration. No empty or guessed trust defaults are accepted. -3. Install the host retention policies. Bootstrap the ledger **once**, using - create, never apply/upsert, with environment-matching authority and sorted - projects. Its initial JSON has `authority`, `projects`, `entries: []` and - `deviceFences: []`. It is intentionally absent from GitOps resources so a - later reconcile cannot overwrite accumulated reservations. Do not label it - as legacy allocation custody (`fleet.datumapis.com/private-record`). -4. Quiesce provider inventory/capacity writes while installing the root webhook - and service. Validate the complete provider scope and legacy inventory before - reopening writes. Unavailable TLS, credentials, ledger or service leave - in-scope writes blocked. The API server must support webhook CEL match - conditions; preserve the packaged conditions, including the exact sorted - provider-name lists matching `--provider-projects` and the private ledger. - Do not replace them with namespace/object label selectors. A missing or - mismatched fence also prevents registration startup/admission; this does not - authorize unquiesced partial installation or deletion of admission policy. - Readiness is process reachability, not asset eligibility. +- `config/milo` includes the mandatory fail-closed registration webhook + (`config/components/registration-admission`). Its one entry matches + capacity create/update/delete and status in every namespace, with no + selectors or match conditions. An unreachable service blocks capacity + writes globally and nothing else: Device, namespace and Project writes do + not pass through the registration webhook. +- `config/milo-production` adds Device deletion protection. +- `config/overlays/management-plane` includes a separate two-replica + registration Deployment and TLS Service. The pod does not mount a service + account token and has no host RBAC. It does not enable production lifecycle + handlers. +- The synthetic staging overlay excludes the registration workload; pair it + with `config/milo-synthetic`, which installs neither the webhook nor the + deletion policy. Never use synthetic roots in production. +- The handler trusts parent context from Milo's admission extras. In pinned + Milo `v0.36.9`, `ProjectRouterWithRequestInfo` establishes the project from + the routed path and `ProjectContextAuthorizationDecorator` overwrites the + parent extras before authorization and admission. The pinned filter + regression verifies that conflicting caller extras are overwritten while + actor identity is preserved, and that nested Organization/User contexts do + not present as a Project. Only a singleton + `Project`/`resourcemanager.miloapis.com` context is accepted. +- Legacy capacity writes fail closed; legacy records remain readable and + unchanged. + +Environment-owned inputs, none of which this repository supplies: + +1. Keep the existing `fleet-manager-config` authority and discovery paths. + Supply `fleet-registration-milo-kubeconfig` (Project reads) and + `fleet-registration-project-kubeconfig` (Device and capacity get/list + across the complete provider scope, and SubjectAccessReview create). It + needs no public writes, allocation permissions or provider credentials. +2. Supply `fleet-registration-tls` with `tls.crt`, `tls.key` and a dedicated + `client-ca.crt`. Configure Milo's admission webhook client with an + API-server client certificate signed by that CA, patch the webhook URL for + reachability, and set `clientConfig.caBundle` to the serving CA. +3. Keep `--provider-projects` equal to the complete provider scope. +4. Choose the Milo root: `config/milo-production` to forbid Device deletion, + or `config/milo` to allow it. 5. Before rolling out the UI, verify caller-preserving project routing, named - Device read denial, registration denial, direct write/status/delete fences, - TLS rejection, and duplicate concurrency in the target environment. This - change performs **no live writes or deployment**, so it does not claim those - environment-specific checks have been performed. - -## UI and verification - -The Datum dialog uses the existing real host-session boundary and isolated read -cache. Missing host authority, denied registration, unavailable Devices and -partial identity have explicit explanations. Selecting a Device snapshots its -baseline; neither refetch nor visible browser-chrome blur/focus changes it. A -named current read immediately precedes dispatch. Session changes fence pending -work. After dispatch, uncertain results retain the authored name and disable -retry; the existing unfenced legacy deletion helper is never used for rollback. - -Tests cover concurrent CAS, serial/UUID/provider aliases and provider projects, -stale UID/RV, Device deletion fences, namespace/Project recreation, permission -revocation, unknown commit and restart, copied-annotation incarnation conflicts, -real API-assigned UID binding, direct mutation fences and no public effects. -Regression coverage also includes real successful unchanged updates retaining -their RV followed by `Recorded` registration, genuine-edit/stale-selection -controls, preservation of pending real-update fences, and transport-outage -isolation for Device writes and namespace/Project deletion. The original reviewer -reproduction is retained byte-for-byte in -`internal/registration/testdata/review_adversarial_test.go.txt`; it is evidence, -not an executable regression because it asserts the former outage failure and -assumes the no-op registration failed before its same-asset control. Derived -regressions use separate assets and assert the corrected behavior. -Envtest exercises the production authorization function against real SARs, -the packaged validating webhook, and the host retention policies against a -disposable API server. The outage regression uses a minimal Project CRD solely -to exercise root deletion admission and disables envtest's built-in -NamespaceLifecycle plugin so its independent ban on deleting `default` cannot -mask the webhook test. It uses dry-run deletion for shared `default`, and actual -deletion for unrelated namespaces/Projects. This does not alter production -admission plugins. The trust-boundary test imports the pinned Milo routing -filters (their test-build transitive dependencies are now recorded in `go.mod`). -TLS tests reject unauthenticated webhook transport. It is not a live Milo -deployment or independent security review. Frontend tests use real session -components and mocked transport. Run the existing Go/envtest, race, vet, -provider/consumer test/typecheck/build, manifest-isolation and documentation -checks described in the [development guide](README.md#build-test-and-run). - -Boundedness regressions perform 120 successive persisted collector observations -and 120 metadata updates through the packaged webhook, assert one incarnation -fence and stable ledger size, then register the current selection and recover it -to `Recorded`. The disposable Device CRD adds a test-only integer status observation -because the current production `DeviceStatus` is empty; this exercises real -`/status` storage and admission without inventing a production collector API. -Deterministic interleavings retain a newer pending fence while stale admission -retries, and keep unknown/rejected baselines fenced across restart/no-op requests. -An envtest race pauses two admitted updates at successive resourceVersions: after -coalescing, the older in-flight update conflicts at actual API-server storage, -the newer pending version remains unregistrable, and only its persisted successor -can be explicitly selected and recorded. -Real API-server Secret conflicts exercise success after five conflicts and six-conflict -exhaustion/logging. Separate tests assert the exact size boundary and effect-free -dry-run denial. - -The publishing workflow applies the server build tag to `config/base/registration`, -as it does to the manager. A regression reads the workflow's image transforms, -applies them to a temporary config tree, and renders the management-plane bundle -to assert that `/fleet-registration` uses the published server image tag rather -than `latest`. It also verifies registration remains absent from synthetic staging. -Raw source manifests still contain template `latest` references: direct deployment -must supply equivalent immutable build-tag or digest transforms, plus the required -trust/credential configuration. No published bundle or live deployment was tested. - -### Review-fix validation, November 22, 2026 - -- Full `go test -race ./...` with Kubernetes 1.37.0 envtest assets, `go vet ./...`, - and `go build ./cmd/...` pass locally. -- Provider tests: 693 pass; consumer tests: 44 pass. Both typechecks and builds - pass. One initial provider timing failure under concurrent validation load - passed on a full rerun without modifying UI code or reviewer tests. -- Production and synthetic manifest renders, overlay isolation tests, - standalone/synthetic render checks, documentation links and whitespace pass. -- The bounded-fencing rework adds real delayed-update and Secret-contention races, - exact-size/dry-run guards, repeated status-write bounds, and rendered publishing - image-transform checks. The original reviewer reproduction remains byte-identical. -- These are local checks, not live Milo acceptance or independent re-review. - No deployment, merge, live resource mutation, or ledger migration was performed. + Device read denial, registration denial, capacity mutation denial, TLS + rejection, Device deletion denial where installed, and duplicate handling + in the target environment. This change performs **no live writes or + deployment**, so it does not claim those checks. + +Removing the ledger deletes nothing live. An environment that bootstrapped the +old `fleet-capacity-registration-v1` Secret, its segments, the +`fleet-registration-control` ConfigMap, or the old retention policies keeps +those objects until its owner removes them; the new service ignores them. + +## UI + +The Datum dialog uses the existing host-session boundary and isolated read +cache. It shows the derived capacity name instead of a name field. Missing +host authority, denied registration, unavailable Devices, partial identity and +conflicting identities have explicit explanations. Selecting a Device +snapshots its baseline; neither refetch nor browser blur/focus changes it. A +named current read immediately precedes dispatch. Session changes fence +pending work. After dispatch, an uncertain result keeps the selection, disables +retry in that form, and asks the operator to check whether the derived capacity +exists. A repeat cannot create a second record. The unfenced legacy deletion +helper is never used for rollback. + +## Verification + +Run with Kubernetes 1.37.0 envtest assets: + +```sh +KUBEBUILDER_ASSETS="$(go run sigs.k8s.io/controller-runtime/tools/setup-envtest@v0.25.2 use 1.37.0 -p path)" go test -race -count=1 ./... +./hack/validate-overlay-isolation.sh Date: Sun, 22 Nov 2026 16:49:08 -0600 Subject: [PATCH 076/518] feat(api): add a Device lifecycle field Add spec.lifecycle to Device with Active (the CRD default), Decommissioning and Retired. CRD transition rules on spec allow Active and Decommissioning to move between each other and Decommissioning to move to Retired. Active to Retired is rejected and nothing leaves Retired, including by removing the field, which defaults back to Active. Creation in any lifecycle is allowed. The CRD is hand-maintained YAML; this repository has no CRD generator, so the schema and its offline tests change together. Co-Authored-By: Claude Opus 5.5 --- .../inventory/crds/fleet.datumapis.com.yaml | 13 ++++ .../api/inventory/v1alpha1/lifecycle_test.go | 78 +++++++++++++++++++ internal/api/inventory/v1alpha1/types.go | 23 ++++++ 3 files changed, 114 insertions(+) create mode 100644 internal/api/inventory/v1alpha1/lifecycle_test.go diff --git a/config/components/inventory/crds/fleet.datumapis.com.yaml b/config/components/inventory/crds/fleet.datumapis.com.yaml index d020afd6..f4e942ee 100644 --- a/config/components/inventory/crds/fleet.datumapis.com.yaml +++ b/config/components/inventory/crds/fleet.datumapis.com.yaml @@ -219,6 +219,9 @@ spec: - name: Serial type: string jsonPath: .spec.identity.serial + - name: Lifecycle + type: string + jsonPath: .spec.lifecycle - name: System UUID type: string priority: 1 @@ -289,7 +292,17 @@ spec: - rule: '!has(self.serviceAssociations) || (has(self.components) && self.serviceAssociations.all(a, self.components.exists(c, c.id == a.componentID)))' message: service associations must reference present components + - rule: '!has(oldSelf.lifecycle) || oldSelf.lifecycle != ''Retired'' || (has(self.lifecycle) && self.lifecycle + == ''Retired'')' + message: Retired is terminal; a Retired Device cannot change lifecycle + - rule: '!has(self.lifecycle) || self.lifecycle != ''Retired'' || (has(oldSelf.lifecycle) && oldSelf.lifecycle + in [''Decommissioning'', ''Retired''])' + message: move an Active Device to Decommissioning before Retired properties: + lifecycle: + type: string + enum: [Active, Decommissioning, Retired] + default: Active deviceTypeRef: type: object required: diff --git a/internal/api/inventory/v1alpha1/lifecycle_test.go b/internal/api/inventory/v1alpha1/lifecycle_test.go new file mode 100644 index 00000000..c6413816 --- /dev/null +++ b/internal/api/inventory/v1alpha1/lifecycle_test.go @@ -0,0 +1,78 @@ +package v1alpha1 + +import "testing" + +func lifecycleDevice(t *testing.T, lifecycle DeviceLifecycle) map[string]any { + t.Helper() + device := syntheticDevice() + device.Spec.Lifecycle = lifecycle + return object(t, device) +} + +func TestDeviceLifecycleDefaultsToActive(t *testing.T) { + device := lifecycleDevice(t, "") + if errs := admit(t, "Device", device, nil); len(errs) > 0 { + t.Fatal(errs) + } + if got := device["spec"].(map[string]any)["lifecycle"]; got != string(DeviceActive) { + t.Fatalf("unset lifecycle defaulted to %v, want Active", got) + } + if got := LifecycleOf(&Device{}); got != DeviceActive { + t.Fatalf("LifecycleOf(unset) = %q, want Active", got) + } + if errs := admit(t, "Device", lifecycleDevice(t, "Unknown"), nil); len(errs) == 0 { + t.Fatal("an unknown lifecycle value was accepted") + } +} + +func TestDeviceLifecycleTransitions(t *testing.T) { + for _, test := range []struct { + from, to DeviceLifecycle + allowed bool + }{ + {DeviceActive, DeviceActive, true}, + {DeviceActive, DeviceDecommissioning, true}, + {DeviceDecommissioning, DeviceActive, true}, + {DeviceDecommissioning, DeviceDecommissioning, true}, + {DeviceDecommissioning, DeviceRetired, true}, + {DeviceRetired, DeviceRetired, true}, + // An unset value is Active, before and after. + {"", DeviceDecommissioning, true}, + {DeviceDecommissioning, "", true}, + {DeviceActive, DeviceRetired, false}, + {"", DeviceRetired, false}, + {DeviceRetired, DeviceActive, false}, + {DeviceRetired, DeviceDecommissioning, false}, + // Removing the field defaults it to Active, so it is not a way out. + {DeviceRetired, "", false}, + } { + errs := admit(t, "Device", lifecycleDevice(t, test.to), lifecycleDevice(t, test.from)) + if allowed := len(errs) == 0; allowed != test.allowed { + t.Errorf("%q -> %q: allowed = %v, want %v (%v)", test.from, test.to, allowed, test.allowed, errs) + } + } +} + +// TestRetiredDeviceStillAcceptsOtherEdits pins that the terminal rule only +// freezes lifecycle, so a Retired record can still be corrected. +func TestRetiredDeviceStillAcceptsOtherEdits(t *testing.T) { + old := syntheticDevice() + old.Spec.Lifecycle = DeviceRetired + edited := syntheticDevice() + edited.Spec.Lifecycle = DeviceRetired + edited.Spec.AssetTag = "asset-0001" + if errs := admit(t, "Device", object(t, edited), object(t, old)); len(errs) > 0 { + t.Fatalf("edit of a Retired Device rejected: %v", errs) + } +} + +// TestDeviceMayBeCreatedInAnyLifecycle pins that transition rules apply to +// updates only: a record of hardware already out of service may be created +// as such. +func TestDeviceMayBeCreatedInAnyLifecycle(t *testing.T) { + for _, lifecycle := range []DeviceLifecycle{DeviceActive, DeviceDecommissioning, DeviceRetired} { + if errs := admit(t, "Device", lifecycleDevice(t, lifecycle), nil); len(errs) > 0 { + t.Errorf("create as %s rejected: %v", lifecycle, errs) + } + } +} diff --git a/internal/api/inventory/v1alpha1/types.go b/internal/api/inventory/v1alpha1/types.go index 4b34b5bb..651ae98e 100644 --- a/internal/api/inventory/v1alpha1/types.go +++ b/internal/api/inventory/v1alpha1/types.go @@ -102,6 +102,29 @@ type DeviceSpec struct { // UnmappedMACAddresses are MACs detected on the asset that the registrar // could not attribute to a named interface. UnmappedMACAddresses []string `json:"unmappedMACAddresses,omitempty"` + // Lifecycle is the asset's service state. The CRD defaults it to Active and + // allows Active and Decommissioning to move between each other and + // Decommissioning to move to Retired, which is terminal. Only an Active + // Device can back new capacity. + Lifecycle DeviceLifecycle `json:"lifecycle,omitempty"` +} + +// DeviceLifecycle is the service state of a Device. +type DeviceLifecycle string + +const ( + DeviceActive DeviceLifecycle = "Active" + DeviceDecommissioning DeviceLifecycle = "Decommissioning" + DeviceRetired DeviceLifecycle = "Retired" +) + +// LifecycleOf returns the Device's lifecycle, treating an unset value as +// Active, which is the CRD default. +func LifecycleOf(device *Device) DeviceLifecycle { + if device.Spec.Lifecycle == "" { + return DeviceActive + } + return device.Spec.Lifecycle } type ReportedPlacement struct { From 671ddb170c9beed2278fd0cec6ecf9186cfada9f Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sun, 22 Nov 2026 16:49:14 -0600 Subject: [PATCH 077/518] feat(registration): require an Active Device Registration admits new capacity only for an Active Device. A capacity update that would leave Disabled while its Device is Decommissioning or Retired is denied for that reason, after checking that the caller can read the Device; every other update keeps the stage-1 denial. Retired Devices still take part in the duplicate-identity scan while they exist. Co-Authored-By: Claude Opus 5.5 --- internal/registration/admission.go | 47 +++++++++- internal/registration/envtest_test.go | 104 ++++++++++++---------- internal/registration/lifecycle_test.go | 113 ++++++++++++++++++++++++ 3 files changed, 213 insertions(+), 51 deletions(-) create mode 100644 internal/registration/lifecycle_test.go diff --git a/internal/registration/admission.go b/internal/registration/admission.go index 0982a8b8..526cdf25 100644 --- a/internal/registration/admission.go +++ b/internal/registration/admission.go @@ -111,8 +111,8 @@ func (handler *Handler) Handle(ctx context.Context, request admission.Request) a if request.Resource.Group != metal.GroupVersion.Group || request.Resource.Resource != "machinecapacities" { return admission.Denied("unsupported registration admission resource") } - if request.Operation != admissionv1.Create || request.SubResource != "" { - return admission.Denied("capacity mutation and deletion are disabled; registered and legacy capacity require operator reconciliation") + if request.SubResource != "" || (request.Operation != admissionv1.Create && request.Operation != admissionv1.Update) { + return admission.Denied(mutationDisabled) } name, err := projectName(request.UserInfo) if err != nil { @@ -121,12 +121,52 @@ func (handler *Handler) Handle(ctx context.Context, request admission.Request) a if !slices.Contains(handler.Projects, name) { return admission.Denied("project is outside the configured provider registration scope") } + if request.Operation == admissionv1.Update { + return admission.Denied(handler.evaluateUpdate(ctx, name, request).Error()) + } if err := handler.evaluate(ctx, name, request); err != nil { return admission.Denied(err.Error()) } return admission.Allowed("inert inventory registration only; no availability or preparation authority") } +const mutationDisabled = "capacity mutation and deletion are disabled; registered and legacy capacity require operator reconciliation" + +// evaluateUpdate explains why a capacity update is denied. Stage 1 denies +// every update. An update that would move capacity out of Disabled for a +// Device that is not Active is denied for that reason first, so the rule +// already holds when a future stage allows enabling capacity. It always +// returns an error. +func (handler *Handler) evaluateUpdate(ctx context.Context, name string, request admission.Request) error { + var capacity metal.MachineCapacity + if err := json.Unmarshal(request.Object.Raw, &capacity); err != nil { + return err + } + if capacity.Spec.AllocationPolicy == "Disabled" { + return errors.New(mutationDisabled) + } + project, err := handler.Resolve(ctx, name) + if err != nil || !project.Identity.Valid() || project.Identity.RouteName != name { + return errors.New("provider project lifetime is unavailable") + } + // The API server has authorized the capacity update itself. Reading the + // backing Device additionally requires the caller to be able to read it. + if err := handler.Authorize(ctx, project, request.UserInfo, inventory.GroupVersion.Group, "devices", capacity.Spec.DeviceRef.Name); err != nil { + return err + } + device := &inventory.Device{} + if err := project.Client.Get(ctx, client.ObjectKey{Namespace: request.Namespace, Name: capacity.Spec.DeviceRef.Name}, device); err != nil { + if apierrors.IsNotFound(err) { + return errors.New("capacity cannot leave Disabled: its Device does not exist") + } + return errors.New("capacity cannot leave Disabled: its Device is unavailable") + } + if lifecycle := inventory.LifecycleOf(device); lifecycle != inventory.DeviceActive { + return fmt.Errorf("capacity cannot leave Disabled: its Device is %s; only an Active Device can back available capacity", lifecycle) + } + return errors.New(mutationDisabled) +} + func (handler *Handler) evaluate(ctx context.Context, name string, request admission.Request) error { if request.Namespace != InventoryNamespace { return errors.New("registration requires the default inventory namespace") @@ -176,6 +216,9 @@ func (handler *Handler) evaluate(ctx context.Context, name string, request admis if device.UID != types.UID(annotations[DeviceUIDAnnotation]) || device.ResourceVersion != annotations[DeviceVersionAnnotation] || !device.DeletionTimestamp.IsZero() { return errors.New("selected Device incarnation or version changed; do not silently refresh the selection") } + if lifecycle := inventory.LifecycleOf(device); lifecycle != inventory.DeviceActive { + return fmt.Errorf("selected Device is %s; only an Active Device can be registered as capacity", lifecycle) + } if !eligible(device) { return errors.New("registration requires non-placeholder serial, canonical system UUID, and complete provider aliases; incomplete identity is ambiguous") } diff --git a/internal/registration/envtest_test.go b/internal/registration/envtest_test.go index 7332f72b..734161ed 100644 --- a/internal/registration/envtest_test.go +++ b/internal/registration/envtest_test.go @@ -91,6 +91,29 @@ func (api *liveAPI) device(name, namespace, serial, uuid string) *inventory.Devi return device } +func (api *liveAPI) updateLifecycle(device *inventory.Device, lifecycle inventory.DeviceLifecycle) error { + api.t.Helper() + if err := api.admin.Get(context.Background(), client.ObjectKeyFromObject(device), device); err != nil { + api.t.Fatal(err) + } + device.Spec.Lifecycle = lifecycle + return api.admin.Update(context.Background(), device) +} + +func (api *liveAPI) setLifecycle(device *inventory.Device, lifecycle inventory.DeviceLifecycle) { + api.t.Helper() + if err := api.updateLifecycle(device, lifecycle); err != nil { + api.t.Fatal(err) + } +} + +// retire takes a Device through the only allowed path to Retired. +func (api *liveAPI) retire(device *inventory.Device) { + api.t.Helper() + api.setLifecycle(device, inventory.DeviceDecommissioning) + api.setLifecycle(device, inventory.DeviceRetired) +} + // installWebhook serves the production handler behind the packaged webhook // configuration and returns the server so a test can take it away. func (api *liveAPI) installWebhook() *httptest.Server { @@ -301,7 +324,7 @@ func TestRegistrationAgainstLiveDevices(t *testing.T) { } registered.Spec.AllocationPolicy = "Enabled" registered.Spec.CleaningPolicyRef.Name = "invented-policy" - if err := operator.Update(ctx, registered); !apierrors.IsForbidden(err) || !strings.Contains(err.Error(), "mutation and deletion are disabled") { + if err := operator.Update(ctx, registered); !apierrors.IsForbidden(err) || !strings.Contains(err.Error(), "cannot leave Disabled: its Device does not exist") { t.Fatalf("orphaned capacity was enabled: %v", err) } if err := operator.Delete(ctx, registered); !apierrors.IsForbidden(err) { @@ -311,57 +334,40 @@ func TestRegistrationAgainstLiveDevices(t *testing.T) { requireDenied(t, operator.Create(ctx, api.registration(replacement)), "already backs capacity") }) - cascade := &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "cascade"}} - if err := api.admin.Create(ctx, cascade); err != nil { - t.Fatal(err) - } - cascaded := api.device("cascaded", "cascade", "cascade-serial", "77777777-7777-7777-7777-777777777777") - sibling := &corev1.ConfigMap{ObjectMeta: metav1.ObjectMeta{Name: "sibling", Namespace: "cascade"}} - if err := api.admin.Create(ctx, sibling); err != nil { - t.Fatal(err) - } - api.installDeletionProtection(duplicateA) - - t.Run("installed component denies Device DELETE for every caller", func(t *testing.T) { - for _, caller := range []client.Client{api.admin, operator} { - if err := caller.Delete(ctx, duplicateA); !apierrors.IsForbidden(err) || !strings.Contains(err.Error(), "cannot be deleted") { - t.Fatalf("Device deletion: %v", err) - } - } - if !api.exists(duplicateA) { - t.Fatal("Device removed despite deletion protection") - } - }) - t.Run("deletecollection is denied per Device", func(t *testing.T) { - if err := api.admin.DeleteAllOf(ctx, &inventory.Device{}, client.InNamespace("default")); !apierrors.IsForbidden(err) { - t.Fatalf("deletecollection: %v", err) - } - for _, device := range []*inventory.Device{duplicateA, duplicateB, legacyBacked, limitedTarget} { - if !api.exists(device) { - t.Fatalf("deletecollection removed %s", device.Name) - } - } + t.Run("only an Active Device can be registered", func(t *testing.T) { + decommissioning := api.device("decommissioning", "default", "decommissioning-serial", "99999999-9999-9999-9999-999999999991") + api.setLifecycle(decommissioning, inventory.DeviceDecommissioning) + requireDenied(t, operator.Create(ctx, api.registration(decommissioning)), "selected Device is Decommissioning") + retired := api.device("retired", "default", "retired-serial", "99999999-9999-9999-9999-999999999992") + api.retire(retired) + requireDenied(t, operator.Create(ctx, api.registration(retired)), "selected Device is Retired") + // A Retired Device still holds its identity while it exists. + twin := api.device("retired-twin", "default", "RETIRED-SERIAL", "99999999-9999-9999-9999-999999999993") + requireDenied(t, operator.Create(ctx, api.registration(twin)), "shares recorded hardware identity") }) - t.Run("namespace deletion stays Terminating with its Devices", func(t *testing.T) { - if err := api.admin.Delete(ctx, cascade); err != nil { - t.Fatal(err) - } - // envtest runs no namespace controller. Issue the same content - // deletions the controller would: deletecollection, then per item. - if err := api.admin.DeleteAllOf(ctx, &corev1.ConfigMap{}, client.InNamespace("cascade")); err != nil { + t.Run("capacity of a Decommissioning or Retired Device cannot leave Disabled", func(t *testing.T) { + device := api.device("leaving-service", "default", "leaving-serial", "99999999-9999-9999-9999-999999999994") + registered := api.registration(device) + if err := operator.Create(ctx, registered); err != nil { t.Fatal(err) } - if err := api.admin.DeleteAllOf(ctx, &inventory.Device{}, client.InNamespace("cascade")); !apierrors.IsForbidden(err) { - t.Fatalf("namespace cascade deletecollection: %v", err) - } - if err := api.admin.Delete(ctx, cascaded); !apierrors.IsForbidden(err) { - t.Fatalf("namespace cascade item deletion: %v", err) - } - if !api.exists(cascaded) || api.exists(sibling) { - t.Fatal("cascade must stop at Devices while other content drains") - } - if !api.exists(cascade) || cascade.DeletionTimestamp.IsZero() { - t.Fatal("namespace must remain Terminating") + enable := func() error { + current := &metal.MachineCapacity{} + if err := api.admin.Get(ctx, client.ObjectKeyFromObject(registered), current); err != nil { + t.Fatal(err) + } + current.Spec.AllocationPolicy = "Enabled" + current.Spec.CleaningPolicyRef.Name = "invented-policy" + return operator.Update(ctx, current) + } + requireDenied(t, enable(), "mutation and deletion are disabled") + api.setLifecycle(device, inventory.DeviceDecommissioning) + requireDenied(t, enable(), "its Device is Decommissioning") + api.setLifecycle(device, inventory.DeviceRetired) + requireDenied(t, enable(), "its Device is Retired") + current := &metal.MachineCapacity{} + if err := api.admin.Get(ctx, client.ObjectKeyFromObject(registered), current); err != nil || current.Spec.AllocationPolicy != "Disabled" { + t.Fatalf("capacity left Disabled: %v %q", err, current.Spec.AllocationPolicy) } }) t.Run("webhook outage blocks only capacity writes", func(t *testing.T) { diff --git a/internal/registration/lifecycle_test.go b/internal/registration/lifecycle_test.go new file mode 100644 index 00000000..c4b1e6f8 --- /dev/null +++ b/internal/registration/lifecycle_test.go @@ -0,0 +1,113 @@ +package registration + +import ( + "context" + "errors" + "strings" + "testing" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + metal "go.datum.net/fleet/internal/api/v1alpha1" + admissionv1 "k8s.io/api/admission/v1" + authenticationv1 "k8s.io/api/authentication/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/controller-runtime/pkg/webhook/admission" +) + +func setLifecycle(t *testing.T, handler *Handler, device *inventory.Device, lifecycle inventory.DeviceLifecycle) { + t.Helper() + device.Spec.Lifecycle = lifecycle + if err := providerClient(t, handler).Update(context.Background(), device); err != nil { + t.Fatal(err) + } +} + +func TestRegistrationRequiresAnActiveDevice(t *testing.T) { + for _, lifecycle := range []inventory.DeviceLifecycle{inventory.DeviceDecommissioning, inventory.DeviceRetired} { + t.Run(string(lifecycle), func(t *testing.T) { + handler, device := fixture(t) + setLifecycle(t, handler, device, lifecycle) + response := handler.Handle(context.Background(), registrationRequest(t, device)) + if response.Allowed || !strings.Contains(response.Result.Message, "selected Device is "+string(lifecycle)) { + t.Fatalf("registration of a %s Device: %+v", lifecycle, response.Result) + } + }) + } + t.Run("explicit Active", func(t *testing.T) { + handler, device := fixture(t) + setLifecycle(t, handler, device, inventory.DeviceActive) + if response := handler.Handle(context.Background(), registrationRequest(t, device)); !response.Allowed { + t.Fatalf("registration of an Active Device denied: %s", response.Result.Message) + } + }) +} + +// TestRetiredDeviceStillBlocksDuplicates pins that a Retired Device keeps its +// identity in the duplicate check for as long as it exists. +func TestRetiredDeviceStillBlocksDuplicates(t *testing.T) { + handler, device := fixture(t) + retired := &inventory.Device{ObjectMeta: metav1.ObjectMeta{Name: "retired", Namespace: "default", UID: "device-2"}, Spec: inventory.DeviceSpec{Lifecycle: inventory.DeviceRetired, Identity: inventory.DeviceIdentity{Serial: " serial-1", SystemUUID: "22222222-2222-2222-2222-222222222222", Model: "test"}}} + if err := providerClient(t, handler).Create(context.Background(), retired); err != nil { + t.Fatal(err) + } + response := handler.Handle(context.Background(), registrationRequest(t, device)) + if response.Allowed || !strings.Contains(response.Result.Message, "shares recorded hardware identity") { + t.Fatalf("registration beside a Retired duplicate: %+v", response.Result) + } +} + +func capacityUpdate(t *testing.T, device *inventory.Device, policy string) admission.Request { + t.Helper() + request := registrationRequest(t, device) + old := request.Object + changeCapacity(&request, func(capacity *metal.MachineCapacity) { capacity.Spec.AllocationPolicy = policy }) + request.Operation = admissionv1.Update + request.OldObject = old + return request +} + +func TestCapacityCannotLeaveDisabledForInactiveDevice(t *testing.T) { + for _, lifecycle := range []inventory.DeviceLifecycle{inventory.DeviceDecommissioning, inventory.DeviceRetired} { + t.Run(string(lifecycle), func(t *testing.T) { + handler, device := fixture(t) + setLifecycle(t, handler, device, lifecycle) + response := handler.Handle(context.Background(), capacityUpdate(t, device, "Enabled")) + if response.Allowed || !strings.Contains(response.Result.Message, "its Device is "+string(lifecycle)) { + t.Fatalf("enabling capacity of a %s Device: %+v", lifecycle, response.Result) + } + }) + } + // Stage 1 still denies every update, so an Active Device, or an update that + // stays Disabled, gets the general denial. + for name, test := range map[string]struct { + lifecycle inventory.DeviceLifecycle + policy string + }{ + "Active enabled": {inventory.DeviceActive, "Enabled"}, + "Retired staying Disabled": {inventory.DeviceRetired, "Disabled"}, + "Decommissioning unchanged": {inventory.DeviceDecommissioning, "Disabled"}, + } { + t.Run(name, func(t *testing.T) { + handler, device := fixture(t) + setLifecycle(t, handler, device, test.lifecycle) + response := handler.Handle(context.Background(), capacityUpdate(t, device, test.policy)) + if response.Allowed || response.Result.Message != mutationDisabled { + t.Fatalf("capacity update: %+v", response.Result) + } + }) + } + t.Run("caller without Device read learns nothing", func(t *testing.T) { + handler, device := fixture(t) + setLifecycle(t, handler, device, inventory.DeviceRetired) + handler.Authorize = func(_ context.Context, _ Project, _ authenticationv1.UserInfo, _, resource, _ string) error { + if resource == "devices" { + return errors.New("get permission on devices is required") + } + return nil + } + response := handler.Handle(context.Background(), capacityUpdate(t, device, "Enabled")) + if response.Allowed || strings.Contains(response.Result.Message, "Retired") { + t.Fatalf("capacity update without Device read: %+v", response.Result) + } + }) +} From a84a15c03aa48cd7dae35beb0f4baf26946f7eb2 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sun, 22 Nov 2026 16:49:24 -0600 Subject: [PATCH 078/518] feat(config): opt-in delete policy for Retired Production-specific configuration belongs to the deploying repository, so remove the config/milo-production root. The device-deletion-protection component stays as a reusable component that no root here includes. The policy now admits a Device DELETE only when namespaceObject has a deletion timestamp (null-guarded, so a missing namespace denies) or the deleted Device is Retired. Everything else is denied with a message to move the Device to Decommissioning, then Retired. It keeps failurePolicy Fail, Deny only, and no subject checks or exemptions. The overlay isolation validator renders the component on its own and requires that exact policy and binding, fails if any root here renders the policy under any name, and fails if the inventory component exists without the deletion component. Fixtures cover a root including the component and the policy renamed, audit-only, warn-only, fail-open, scoped, exempted or given a weaker rule. envtest applies the component and checks Active and Decommissioning deletes are denied, Retired deletes pass, deletecollection over mixed Devices denies the non-retired ones, and Devices of a deleting namespace can be deleted. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 1 - .../kustomization.yaml | 5 +- .../device-deletion-protection/policy.yaml | 31 ++-- config/milo-production/kustomization.yaml | 9 - hack/overlay-isolation-validator.go | 99 ++++++++--- hack/test-overlay-isolation.sh | 63 +++++-- .../registration/deletion_envtest_test.go | 160 ++++++++++++++++++ 7 files changed, 307 insertions(+), 61 deletions(-) delete mode 100644 config/milo-production/kustomization.yaml create mode 100644 internal/registration/deletion_envtest_test.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0fbf0da4..d537961b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -24,7 +24,6 @@ jobs: - run: go run ./test/acceptance/milo/cmd validate --root . - run: kustomize build config/base/crd >/dev/null - run: kustomize build config/milo >/dev/null - - run: kustomize build config/milo-production >/dev/null - run: kustomize build config/milo-synthetic >/dev/null - run: kustomize build config/overlays/management-plane >/dev/null - run: kustomize build config/overlays/synthetic-staging >/dev/null diff --git a/config/components/device-deletion-protection/kustomization.yaml b/config/components/device-deletion-protection/kustomization.yaml index 03bc082f..a0d79d9e 100644 --- a/config/components/device-deletion-protection/kustomization.yaml +++ b/config/components/device-deletion-protection/kustomization.yaml @@ -1,5 +1,6 @@ -# Optional: install wherever Device objects are admitted (the Milo control -# plane) in environments that must never lose a Device. See +# Reusable and opt-in: no root in this repository includes it. A deploying +# repository that must keep in-service Devices adds it to the root it applies +# to the Milo control plane, where Devices are admitted. See # docs/development/inventory-capacity-registration.md#device-deletion-protection. apiVersion: kustomize.config.k8s.io/v1alpha1 kind: Component diff --git a/config/components/device-deletion-protection/policy.yaml b/config/components/device-deletion-protection/policy.yaml index bc69125e..0de29e95 100644 --- a/config/components/device-deletion-protection/policy.yaml +++ b/config/components/device-deletion-protection/policy.yaml @@ -1,9 +1,16 @@ -# Devices are never deleted where this component is installed. Retire a -# machine through its capacity staying Disabled instead. The API server runs -# admission once per object for deletecollection, garbage collection and -# namespace or project cleanup, so every one of those paths is denied too. -# There are no exemptions: an environment that needs Device deletion does not -# install this component. +# A Device is deleted only after it is Retired, so a Device in service stays +# visible to duplicate-hardware checks. Retire a Device by moving +# spec.lifecycle to Decommissioning and then Retired; the CRD rejects every +# other path to Retired, and Retired is terminal. +# +# The one other exception is a Device whose namespace is being deleted +# (namespaceObject.metadata.deletionTimestamp is set). Deleting a namespace is +# the privileged escape hatch: it lets the namespace controller finish and +# takes its Devices with it. Nothing keys off who makes the request, and there +# are no exemptions. The API server runs admission once per object for +# deletecollection, garbage collection and namespace cleanup, so each of those +# paths is held to the same rule. A missing namespace object or an evaluation +# error denies the request (failurePolicy: Fail). apiVersion: admissionregistration.k8s.io/v1 kind: ValidatingAdmissionPolicy metadata: @@ -18,12 +25,16 @@ spec: operations: [DELETE] resources: [devices] validations: - - expression: 'false' + - expression: >- + (namespaceObject != null && has(namespaceObject.metadata) && + has(namespaceObject.metadata.deletionTimestamp)) || + (oldObject != null && has(oldObject.spec) && has(oldObject.spec.lifecycle) && + oldObject.spec.lifecycle == 'Retired') reason: Forbidden message: >- - Devices cannot be deleted in this environment. Their identity must stay - visible to duplicate-hardware checks. Leave the Device in place and - keep its capacity Disabled. + Only a Retired Device can be deleted. Move the Device to Decommissioning, + then Retired, first; its identity must stay visible to duplicate-hardware + checks while it is in service. --- apiVersion: admissionregistration.k8s.io/v1 kind: ValidatingAdmissionPolicyBinding diff --git a/config/milo-production/kustomization.yaml b/config/milo-production/kustomization.yaml deleted file mode 100644 index c3a66020..00000000 --- a/config/milo-production/kustomization.yaml +++ /dev/null @@ -1,9 +0,0 @@ -# Production-style Milo root: config/milo plus Device deletion protection. -# Environments that need Device deletions, such as test and staging control -# planes, consume config/milo instead. -apiVersion: kustomize.config.k8s.io/v1beta1 -kind: Kustomization -resources: - - ../milo -components: - - ../components/device-deletion-protection diff --git a/hack/overlay-isolation-validator.go b/hack/overlay-isolation-validator.go index 6ffe60eb..e524df59 100644 --- a/hack/overlay-isolation-validator.go +++ b/hack/overlay-isolation-validator.go @@ -27,14 +27,24 @@ const ( localProjectStandIn = "fleet.datumapis.com/local-project-stand-in" sharedNamespace = "fleet.datumapis.com/shared-with-standalone" - // Device deletion protection is optional per environment. Only the - // production-style roots below may render it, and they must. + // Device deletion protection is a reusable component that deploying + // repositories opt into. No root in this repository may render it, and the + // component rendered alone must be the exact fail-closed policy. deletionProtection = "fleet-device-deletion-protection" deletionProtectionComponent = "components/device-deletion-protection" + // inventoryComponent defines the Device CRD. A config tree that has it + // must also ship the deletion protection component. + inventoryComponent = "components/inventory" + + // deletionProtectionExpression is the only admitted rule: a Device DELETE + // passes when its namespace is being deleted or it is Retired. It is + // compared with whitespace normalized. + deletionProtectionExpression = `(namespaceObject != null && has(namespaceObject.metadata) && +has(namespaceObject.metadata.deletionTimestamp)) || +(oldObject != null && has(oldObject.spec) && has(oldObject.spec.lifecycle) && +oldObject.spec.lifecycle == 'Retired')` ) -var deletionProtectedRoots = []string{"milo-production"} - type kustomization struct { Resources []string `json:"resources"` Components []string `json:"components"` @@ -88,12 +98,11 @@ func main() { if err := checkDeletionProtection("standalone", standaloneObjects, false); err != nil { fatalf("render %s: %v", standaloneRoot, err) } + componentPresent := false if _, err := os.Stat(filepath.Join(configRoot, filepath.FromSlash(deletionProtectionComponent))); err == nil { - for _, root := range deletionProtectedRoots { - if _, err := os.Stat(filepath.Join(configRoot, root)); err != nil { - fatalf("production-style root %s must exist and install Device deletion protection: %v", root, err) - } - } + componentPresent = true + } else if _, err := os.Stat(filepath.Join(configRoot, filepath.FromSlash(inventoryComponent))); err == nil { + fatalf("%s defines Devices, so %s must exist for deploying repositories to opt into", inventoryComponent, deletionProtectionComponent) } entries, err := discover(configRoot) @@ -101,7 +110,7 @@ func main() { if len(entries) == 0 { fatalf("no Kustomize entry points found below %s", configRoot) } - checked := 0 + checked, componentChecked := 0, false for _, entry := range entries { root := filepath.Dir(entry) if v.definitionRoot(root) { @@ -124,9 +133,7 @@ func main() { check(err) relative = filepath.ToSlash(relative) required := relative == deletionProtectionComponent - for _, protected := range deletionProtectedRoots { - required = required || relative == protected - } + componentChecked = componentChecked || required if err := checkDeletionProtection(relative, objects, required); err != nil { fatalf("render %s: %v", root, err) } @@ -134,6 +141,9 @@ func main() { if checked == 0 { fatalf("no non-standalone Kustomize entry point was validated") } + if componentPresent && !componentChecked { + fatalf("%s was not rendered on its own", deletionProtectionComponent) + } } func (v *validator) definitionRoot(path string) bool { @@ -287,9 +297,9 @@ func (v *validator) checkObject(object *unstructured.Unstructured) error { return nil } -// checkDeletionProtection requires the exact deny-all Device DELETE policy and -// its binding in production-style roots, and forbids either object anywhere -// else, so test and synthetic roots keep Device deletion available. +// checkDeletionProtection requires the exact Device DELETE policy and its +// binding when the component is rendered alone, and forbids either object in +// every other root: deploying repositories opt in, this repository does not. func checkDeletionProtection(root string, objects []*unstructured.Unstructured, required bool) error { var policy, binding *unstructured.Unstructured for _, object := range objects { @@ -309,26 +319,29 @@ func checkDeletionProtection(root string, objects []*unstructured.Unstructured, } if !required { if policy != nil || binding != nil { - return fmt.Errorf("%s renders Device deletion protection; only %v may install %s", root, deletionProtectedRoots, deletionProtectionComponent) + return fmt.Errorf("%s renders Device deletion protection; no root in this repository may include %s, deploying repositories opt in", root, deletionProtectionComponent) } return nil } if policy == nil || binding == nil { - return fmt.Errorf("production-style root %s must install the Device deletion policy and its binding", root) + return fmt.Errorf("%s must render the Device deletion policy and its binding", root) } failurePolicy, _, _ := unstructured.NestedString(policy.Object, "spec", "failurePolicy") validations, _, _ := unstructured.NestedSlice(policy.Object, "spec", "validations") - _, hasConditions := policy.Object["spec"].(map[string]any)["matchConditions"] - if policy.GetName() != deletionProtection || failurePolicy != "Fail" || !policyMatchesDeviceDelete(policy) || hasConditions || len(validations) != 1 { + spec := policy.Object["spec"].(map[string]any) + _, hasConditions := spec["matchConditions"] + _, hasVariables := spec["variables"] + _, hasParams := spec["paramKind"] + if policy.GetName() != deletionProtection || failurePolicy != "Fail" || !policyMatchesDeviceDelete(policy) || !unscopedConstraints(policy) || hasConditions || hasVariables || hasParams || len(validations) != 1 { return fmt.Errorf("%s: Device deletion policy must fail closed, match DELETE on devices and have no exemptions", root) } - if expression, _, _ := unstructured.NestedString(validations[0].(map[string]any), "expression"); expression != "false" { - return fmt.Errorf("%s: Device deletion policy must deny every DELETE", root) + if expression, _, _ := unstructured.NestedString(validations[0].(map[string]any), "expression"); strings.Join(strings.Fields(expression), " ") != strings.Join(strings.Fields(deletionProtectionExpression), " ") { + return fmt.Errorf("%s: Device deletion policy must allow DELETE only for a Retired Device or a deleting namespace", root) } actions, _, _ := unstructured.NestedStringSlice(binding.Object, "spec", "validationActions") _, hasMatch := binding.Object["spec"].(map[string]any)["matchResources"] - _, hasParams := binding.Object["spec"].(map[string]any)["paramRef"] - if len(actions) != 1 || actions[0] != "Deny" || hasMatch || hasParams { + _, hasParamRef := binding.Object["spec"].(map[string]any)["paramRef"] + if len(actions) != 1 || actions[0] != "Deny" || hasMatch || hasParamRef { return fmt.Errorf("%s: Device deletion binding must Deny in every namespace", root) } return nil @@ -349,6 +362,44 @@ func policyMatchesDeviceDelete(policy *unstructured.Unstructured) bool { return false } +// unscopedConstraints reports whether the policy's match constraints apply to +// every namespace and object, with no exclusions or name restrictions. +func unscopedConstraints(policy *unstructured.Unstructured) bool { + constraints, _, _ := unstructured.NestedMap(policy.Object, "spec", "matchConstraints") + for _, key := range []string{"namespaceSelector", "objectSelector", "excludeResourceRules"} { + if value, found := constraints[key]; found && !emptyValue(value) { + return false + } + } + rules, _, _ := unstructured.NestedSlice(policy.Object, "spec", "matchConstraints", "resourceRules") + for _, raw := range rules { + rule, ok := raw.(map[string]any) + if !ok { + return false + } + if names, found := rule["resourceNames"]; found && !emptyValue(names) { + return false + } + if scope, found := rule["scope"]; found && scope != "*" && scope != "Namespaced" { + return false + } + } + return true +} + +func emptyValue(value any) bool { + switch typed := value.(type) { + case nil: + return true + case map[string]any: + return len(typed) == 0 + case []any: + return len(typed) == 0 + default: + return false + } +} + func contains(values []string, value string) bool { for _, candidate := range values { if candidate == value { diff --git a/hack/test-overlay-isolation.sh b/hack/test-overlay-isolation.sh index 6d0ec68f..95211c24 100755 --- a/hack/test-overlay-isolation.sh +++ b/hack/test-overlay-isolation.sh @@ -417,22 +417,31 @@ EOF expect_failure "intentional Kustomize build failure" "missing.yaml" rm -rf "$fixture_root/config/overlays/broken" -# Device deletion protection is per environment: only production-style roots -# may render it, and once the component exists they must. -mkdir -p "$fixture_root/config/components/device-deletion-protection" -cp "$repo_root/config/components/device-deletion-protection/kustomization.yaml" "$repo_root/config/components/device-deletion-protection/policy.yaml" "$fixture_root/config/components/device-deletion-protection/" -expect_failure "deletion component without a production-style root" "production-style root milo-production must exist" +# Device deletion protection is a reusable component that deploying +# repositories opt into. No root in this repository may render it, and the +# component rendered alone must be the exact fail-closed policy. +component="$fixture_root/config/components/device-deletion-protection" +policy="$repo_root/config/components/device-deletion-protection/policy.yaml" +mkdir -p "$fixture_root/config/components/inventory" +cat >"$fixture_root/config/components/inventory/kustomization.yaml" <<'EOF' +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: [../../base/safe] +EOF +expect_failure "Device inventory without the deletion component" "must exist for deploying repositories to opt into" +mkdir -p "$component" +cp "$repo_root/config/components/device-deletion-protection/kustomization.yaml" "$policy" "$component/" +"$repo_root/hack/validate-overlay-isolation.sh" "$fixture_root/config" "$fixture_root/config/standalone" + mkdir -p "$fixture_root/config/milo-production" cat >"$fixture_root/config/milo-production/kustomization.yaml" <<'EOF' apiVersion: kustomize.config.k8s.io/v1beta1 kind: Kustomization resources: [../base/safe] -EOF -expect_failure "production-style root without deletion protection" "must install the Device deletion policy and its binding" -cat >>"$fixture_root/config/milo-production/kustomization.yaml" <<'EOF' components: [../components/device-deletion-protection] EOF -"$repo_root/hack/validate-overlay-isolation.sh" "$fixture_root/config" "$fixture_root/config/standalone" +expect_failure "fleet root including the deletion component" "milo-production renders Device deletion protection" +rm -rf "$fixture_root/config/milo-production" mkdir -p "$fixture_root/config/overlays/synthetic-with-protection" cat >"$fixture_root/config/overlays/synthetic-with-protection/kustomization.yaml" <<'EOF' apiVersion: kustomize.config.k8s.io/v1beta1 @@ -440,19 +449,43 @@ kind: Kustomization resources: [../../base/safe] components: [../../components/device-deletion-protection] EOF -expect_failure "test or synthetic root installing deletion protection" "renders Device deletion protection" +expect_failure "nested fleet root including the deletion component" "renders Device deletion protection" rm -rf "$fixture_root/config/overlays/synthetic-with-protection" mkdir -p "$fixture_root/config/overlays/renamed-protection" -sed 's/name: fleet-device-deletion-protection/name: renamed-device-guard/; s/policyName: fleet-device-deletion-protection/policyName: renamed-device-guard/' "$repo_root/config/components/device-deletion-protection/policy.yaml" >"$fixture_root/config/overlays/renamed-protection/policy.yaml" +sed 's/name: fleet-device-deletion-protection/name: renamed-device-guard/; s/policyName: fleet-device-deletion-protection/policyName: renamed-device-guard/' "$policy" >"$fixture_root/config/overlays/renamed-protection/policy.yaml" cat >"$fixture_root/config/overlays/renamed-protection/kustomization.yaml" <<'EOF' apiVersion: kustomize.config.k8s.io/v1beta1 kind: Kustomization resources: [policy.yaml] EOF -expect_failure "renamed Device deletion policy outside production roots" "renders Device deletion protection" +expect_failure "renamed Device deletion policy copied into a fleet root" "renders Device deletion protection" rm -rf "$fixture_root/config/overlays/renamed-protection" -sed 's/validationActions: \[Deny\]/validationActions: [Audit]/' "$repo_root/config/components/device-deletion-protection/policy.yaml" >"$fixture_root/config/components/device-deletion-protection/policy.yaml" -expect_failure "audit-only Device deletion binding" "must Deny in every namespace" -cp "$repo_root/config/components/device-deletion-protection/policy.yaml" "$fixture_root/config/components/device-deletion-protection/policy.yaml" + +# Each weakening below is rendered through the component itself. +weakened() { + description=$1 + expected=$2 + shift 2 + sed "$@" "$policy" >"$component/policy.yaml" + if cmp -s "$policy" "$component/policy.yaml"; then + echo "$description fixture did not change the policy" >&2 + exit 1 + fi + expect_failure "$description" "$expected" + cp "$policy" "$component/policy.yaml" +} +weakened "renamed Device deletion policy" "components/device-deletion-protection: Device deletion policy must fail closed" -e '1,/kind: ValidatingAdmissionPolicyBinding/s/name: fleet-device-deletion-protection/name: renamed-device-guard/' +weakened "renamed Device deletion policy and binding" "components/device-deletion-protection must render the Device deletion policy and its binding" -e 's/name: fleet-device-deletion-protection/name: renamed-device-guard/' -e 's/policyName: fleet-device-deletion-protection/policyName: renamed-device-guard/' +weakened "audit-only Device deletion binding" "must Deny in every namespace" -e 's/validationActions: \[Deny\]/validationActions: [Audit]/' +weakened "warn-only Device deletion binding" "must Deny in every namespace" -e 's/validationActions: \[Deny\]/validationActions: [Warn]/' +weakened "fail-open Device deletion policy" "must fail closed" -e 's/failurePolicy: Fail/failurePolicy: Ignore/' +weakened "always-true Device deletion expression" "allow DELETE only for a Retired Device or a deleting namespace" -e "s/oldObject.spec.lifecycle == 'Retired')/oldObject.spec.lifecycle == 'Retired') || true/" +weakened "Decommissioning Device deletion allowed" "allow DELETE only for a Retired Device or a deleting namespace" -e "s/== 'Retired')/!= 'Active')/" +weakened "namespace-scoped Device deletion policy" "must fail closed" -e 's/ matchPolicy: Equivalent/ matchPolicy: Equivalent\ + namespaceSelector: {matchLabels: {protected: "true"}}/' +weakened "subject exemption in Device deletion policy" "must fail closed" -e 's/^ validations:/ matchConditions:\ + - name: not-admin\ + expression: "request.userInfo.username != '\''admin'\''"\ + validations:/' "$repo_root/hack/validate-overlay-isolation.sh" "$fixture_root/config" "$fixture_root/config/standalone" diff --git a/internal/registration/deletion_envtest_test.go b/internal/registration/deletion_envtest_test.go new file mode 100644 index 00000000..9a2dbbca --- /dev/null +++ b/internal/registration/deletion_envtest_test.go @@ -0,0 +1,160 @@ +package registration + +import ( + "context" + "fmt" + "strings" + "testing" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/controller-runtime/pkg/client" +) + +const deletionDenied = "Only a Retired Device can be deleted" + +func (api *liveAPI) namespace(name string) *corev1.Namespace { + api.t.Helper() + namespace := &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: name}} + if err := api.admin.Create(context.Background(), namespace); err != nil { + api.t.Fatal(err) + } + return namespace +} + +// TestDeviceLifecycleTransitionsAgainstLiveAPI runs the CRD transition rules +// in a real API server. +func TestDeviceLifecycleTransitionsAgainstLiveAPI(t *testing.T) { + api := startAPI(t) + device := api.device("lifecycle", "default", "lifecycle-serial", "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaa1") + if device.Spec.Lifecycle != inventory.DeviceActive { + t.Fatalf("created Device lifecycle = %q, want the Active default", device.Spec.Lifecycle) + } + rejected := func(to inventory.DeviceLifecycle, message string) { + t.Helper() + if err := api.updateLifecycle(device, to); !apierrors.IsInvalid(err) || !strings.Contains(err.Error(), message) { + t.Fatalf("transition to %s: %v", to, err) + } + } + rejected(inventory.DeviceRetired, "move an Active Device to Decommissioning before Retired") + api.setLifecycle(device, inventory.DeviceDecommissioning) + api.setLifecycle(device, inventory.DeviceActive) + api.setLifecycle(device, inventory.DeviceDecommissioning) + api.setLifecycle(device, inventory.DeviceRetired) + rejected(inventory.DeviceActive, "Retired is terminal") + rejected(inventory.DeviceDecommissioning, "Retired is terminal") + rejected("", "Retired is terminal") + api.setLifecycle(device, inventory.DeviceRetired) +} + +// TestDeviceDeletionProtection applies the component's manifests as a +// deploying repository that opts in would, and checks every deletion path. +func TestDeviceDeletionProtection(t *testing.T) { + api := startAPI(t) + ctx := context.Background() + active := api.device("active", "default", "active-serial", "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbb1") + decommissioning := api.device("decommissioning", "default", "decommissioning-serial", "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbb2") + api.setLifecycle(decommissioning, inventory.DeviceDecommissioning) + retired := api.device("retired", "default", "retired-serial", "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbb3") + api.retire(retired) + + api.namespace("mixed") + mixed := map[string]inventory.DeviceLifecycle{"mixed-active": inventory.DeviceActive, "mixed-decommissioning": inventory.DeviceDecommissioning, "mixed-retired-a": inventory.DeviceRetired, "mixed-retired-b": inventory.DeviceRetired} + mixedDevices := map[string]*inventory.Device{} + suffix := 0 + for name, lifecycle := range mixed { + suffix++ + device := api.device(name, "mixed", name+"-serial", fmt.Sprintf("cccccccc-cccc-4ccc-8ccc-%012d", suffix)) + switch lifecycle { + case inventory.DeviceDecommissioning: + api.setLifecycle(device, lifecycle) + case inventory.DeviceRetired: + api.retire(device) + } + mixedDevices[name] = device + } + + teardown := api.namespace("teardown") + teardownActive := api.device("teardown-active", "teardown", "teardown-active-serial", "dddddddd-dddd-4ddd-8ddd-ddddddddddd1") + teardownDecommissioning := api.device("teardown-decommissioning", "teardown", "teardown-decommissioning-serial", "dddddddd-dddd-4ddd-8ddd-ddddddddddd2") + api.setLifecycle(teardownDecommissioning, inventory.DeviceDecommissioning) + + api.installDeletionProtection(active) + operator := api.actor("operator", "system:masters") + + t.Run("Active and Decommissioning Devices cannot be deleted by any caller", func(t *testing.T) { + for _, device := range []*inventory.Device{active, decommissioning} { + for _, caller := range []client.Client{api.admin, operator} { + if err := caller.Delete(ctx, device); !apierrors.IsForbidden(err) || !strings.Contains(err.Error(), deletionDenied) || !strings.Contains(err.Error(), "Decommissioning, then Retired") { + t.Fatalf("deleting %s: %v", device.Name, err) + } + } + if !api.exists(device) { + t.Fatalf("%s removed despite deletion protection", device.Name) + } + } + }) + t.Run("a Retired Device can be deleted", func(t *testing.T) { + if err := operator.Delete(ctx, retired); err != nil { + t.Fatalf("deleting a Retired Device: %v", err) + } + if api.exists(retired) { + t.Fatal("Retired Device survived deletion") + } + }) + t.Run("deletecollection denies the Devices that are not Retired", func(t *testing.T) { + if err := api.admin.DeleteAllOf(ctx, &inventory.Device{}, client.InNamespace("mixed")); !apierrors.IsForbidden(err) || !strings.Contains(err.Error(), deletionDenied) { + t.Fatalf("deletecollection over mixed Devices: %v", err) + } + // The API server stops a collection delete at its first denial, so + // each Retired Device is either already gone or deletable now. + for name, lifecycle := range mixed { + device := mixedDevices[name] + err := api.admin.Delete(ctx, device) + switch { + case lifecycle == inventory.DeviceRetired && err != nil && !apierrors.IsNotFound(err): + t.Fatalf("deleting Retired %s after deletecollection: %v", name, err) + case lifecycle != inventory.DeviceRetired && (!apierrors.IsForbidden(err) || !api.exists(device)): + t.Fatalf("%s (%s) is not protected after deletecollection: %v", name, lifecycle, err) + case lifecycle == inventory.DeviceRetired && api.exists(device): + t.Fatalf("Retired %s survived", name) + } + } + }) + t.Run("deleting the namespace lets its Devices be deleted", func(t *testing.T) { + if err := api.admin.Delete(ctx, teardownActive); !apierrors.IsForbidden(err) { + t.Fatalf("Device deletion before namespace deletion: %v", err) + } + if err := api.admin.Delete(ctx, teardown); err != nil { + t.Fatal(err) + } + if !api.exists(teardown) || teardown.DeletionTimestamp.IsZero() { + t.Fatal("namespace is not marked for deletion") + } + // The policy reads namespaceObject from the API server's namespace + // cache, which observes the deletion mark shortly after it is set. + api.eventually("namespace deletion mark", func() bool { + return api.admin.Delete(ctx, teardownActive, client.DryRunAll) == nil + }) + // envtest runs no namespace controller. Issue the content deletions + // the controller would: deletecollection, then per item. + if err := api.admin.DeleteAllOf(ctx, &inventory.Device{}, client.InNamespace("teardown")); err != nil { + t.Fatalf("namespace cleanup deletecollection: %v", err) + } + for _, device := range []*inventory.Device{teardownActive, teardownDecommissioning} { + if err := api.admin.Delete(ctx, device); err != nil && !apierrors.IsNotFound(err) { + t.Fatalf("namespace cleanup of %s: %v", device.Name, err) + } + if api.exists(device) { + t.Fatalf("%s survived namespace cleanup", device.Name) + } + } + }) + t.Run("Devices in other namespaces stay protected", func(t *testing.T) { + if err := api.admin.Delete(ctx, active); !apierrors.IsForbidden(err) || !api.exists(active) { + t.Fatalf("Active Device outside the deleting namespace: %v", err) + } + }) +} From 0537866c1f0c00ef28925c316bcaaf8802b9be24 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sun, 22 Nov 2026 16:49:31 -0600 Subject: [PATCH 079/518] feat(ui): honor Device lifecycle in registration The registration picker refuses Devices that are Decommissioning or Retired with an explicit reason, and still marks an Active Device that shares identity with a Retired one as conflicting. The inventory detail panel shows the lifecycle, defaulting to Active. The UI does not edit lifecycle. Co-Authored-By: Claude Opus 5.5 --- ui/provider/src/components/physical-inventory.tsx | 1 + ui/provider/src/lib/capacity-registration.test.ts | 10 ++++++++++ ui/provider/src/lib/capacity-registration.ts | 9 ++++++--- ui/shared/fleet-api.ts | 5 +++++ 4 files changed, 22 insertions(+), 3 deletions(-) diff --git a/ui/provider/src/components/physical-inventory.tsx b/ui/provider/src/components/physical-inventory.tsx index 31a3d2fe..003d9452 100644 --- a/ui/provider/src/components/physical-inventory.tsx +++ b/ui/provider/src/components/physical-inventory.tsx @@ -345,6 +345,7 @@ export function PhysicalInventory({ inventory: source, onRetry, showNavigation = {modelLabel(device.spec.identity)} {catalog ? reference('DeviceType', namespace, catalog.model.metadata.name) : device.spec.deviceTypeRef ? 'Catalog unavailable · showing recorded observation' : 'Not assigned · showing recorded observation'} {catalog?.model.spec.modelShape?.heightUnits === undefined ? 'Unknown' : `${catalog.model.spec.modelShape.heightUnits}U · not measured or used for occupancy`} + {device.spec.lifecycle ?? 'Active'} {device.spec.identity.serial} {device.spec.assetTag} {device.spec.identity.systemUUID} diff --git a/ui/provider/src/lib/capacity-registration.test.ts b/ui/provider/src/lib/capacity-registration.test.ts index 52ea1963..8a218155 100644 --- a/ui/provider/src/lib/capacity-registration.test.ts +++ b/ui/provider/src/lib/capacity-registration.test.ts @@ -73,3 +73,13 @@ it('rejects partial and unidentified identity and non-default inventory', () => expect(ineligibleReason({ ...device, spec: { ...device.spec, identity: { model: 'test', serial: 'only-serial' } } })).toContain('ambiguous'); expect(ineligibleReason({ ...device, metadata: { ...device.metadata, namespace: 'other' } })).toContain('unavailable'); }); + +it('registers only Active Devices and still counts Retired ones as conflicts', async () => { + expect(ineligibleReason({ ...device, spec: { ...device.spec, lifecycle: 'Active' } })).toBeUndefined(); + expect(ineligibleReason({ ...device, spec: { ...device.spec, lifecycle: 'Decommissioning' } })).toBe('Device is Decommissioning; only an Active Device can be registered'); + expect(ineligibleReason({ ...device, spec: { ...device.spec, lifecycle: 'Retired' } })).toBe('Device is Retired; only an Active Device can be registered'); + const retiredTwin: Device = { metadata: { name: 'retired-twin', namespace: 'default', uid: 'device-9', resourceVersion: '1' }, spec: { claimRef: { name: 'installation' }, lifecycle: 'Retired', identity: { model: 'test', serial: 'SERIAL-1', systemUUID: '99999999-9999-9999-9999-999999999999' } } }; + expect(ineligibleReason(device, [device, retiredTwin])).toContain('Conflicting'); + await expect(registerCapacity({ ...device, spec: { ...device.spec, lifecycle: 'Decommissioning' } }, 'operation', new InventoryOperationScope().begin())).rejects.toThrow('only an Active Device'); + expect(transport).not.toHaveBeenCalled(); +}); diff --git a/ui/provider/src/lib/capacity-registration.ts b/ui/provider/src/lib/capacity-registration.ts index cbe5aff1..6139d6b5 100644 --- a/ui/provider/src/lib/capacity-registration.ts +++ b/ui/provider/src/lib/capacity-registration.ts @@ -26,11 +26,14 @@ function aliases(device: Device): string[] { return result; } -// ineligibleReason explains why a Device cannot be registered. Passing the -// listed Devices also marks every Device that shares a hardware alias with -// another one as conflicting until a person resolves the duplicate. +// ineligibleReason explains why a Device cannot be registered. Only an Active +// Device can be. Passing the listed Devices also marks every Device that +// shares a hardware alias with another one, including a Retired one, as +// conflicting until a person resolves the duplicate. export function ineligibleReason(device: Device, listed: Device[] = []): string | undefined { if (device.metadata.namespace !== 'default' || !device.metadata.uid || !device.metadata.resourceVersion || device.metadata.deletionTimestamp) return 'Device incarnation is unavailable or deleting'; + const lifecycle = device.spec.lifecycle ?? 'Active'; + if (lifecycle !== 'Active') return `Device is ${lifecycle}; only an Active Device can be registered`; if (device.spec.identity.unidentified || !device.spec.identity.serial?.trim() || !device.spec.identity.systemUUID) return 'Both serial and system UUID are required; partial identity is ambiguous'; if (['unknown', 'none', 'n/a', 'default string', 'to be filled by o.e.m.'].includes(device.spec.identity.serial.trim().toLowerCase()) || ['00000000-0000-0000-0000-000000000000', 'ffffffff-ffff-ffff-ffff-ffffffffffff'].includes(device.spec.identity.systemUUID)) return 'Placeholder identity is ineligible'; const own = aliases(device); diff --git a/ui/shared/fleet-api.ts b/ui/shared/fleet-api.ts index 3e4e65c9..7abb2f2d 100644 --- a/ui/shared/fleet-api.ts +++ b/ui/shared/fleet-api.ts @@ -278,9 +278,14 @@ export interface Device { bmc?: { endpoint: string }; interfaces?: { name: string; macAddress?: string; peer?: PortPeer }[]; unmappedMACAddresses?: string[]; + // lifecycle defaults to Active. Active and Decommissioning move between + // each other, Decommissioning moves to Retired, and Retired is terminal. + lifecycle?: DeviceLifecycle; }; } +export type DeviceLifecycle = 'Active' | 'Decommissioning' | 'Retired'; + export interface ReportedPlacement { revision: number; observedAt: string; From a561597629d17449c659d3a75c2c4c9aa51a54ad Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sun, 22 Nov 2026 16:49:32 -0600 Subject: [PATCH 080/518] docs: describe Device lifecycle and opt-in delete Document the lifecycle values and transitions, the registration rules, and the deletion policy's two exceptions. Deploying repositories opt into the component; this repository no longer has a production Milo root. Namespace deletion is the privileged escape hatch and now completes with its Devices. The earlier stays-Terminating remediation is removed. Record that pinned Milo project purge issues collection deletes in every namespace before marking any, and never deletes default, so a project that holds Devices that are not Retired does not finish purging while the component is installed. Co-Authored-By: Claude Opus 5.5 --- config/README.md | 19 +- docs/development/README.md | 6 +- .../inventory-capacity-registration.md | 249 ++++++++++++------ docs/operations/physical-inventory.md | 18 +- 4 files changed, 186 insertions(+), 106 deletions(-) diff --git a/config/README.md b/config/README.md index 55020bb5..3c6187d1 100644 --- a/config/README.md +++ b/config/README.md @@ -15,18 +15,16 @@ target different API servers and must be reconciled independently. | Root | Destination | Contents | | --- | --- | --- | | `config/milo` | Milo root control plane | Fleet CRDs (including the `fleet.datumapis.com` inventory kinds), IAM protected resources and roles, service/quota registration, and the mandatory capacity-registration webhook. Devices can be deleted. | -| `config/milo-production` | Milo root control plane (production-style) | `config/milo` plus Device deletion protection | | `config/overlays/management-plane` | Fleet management cluster | Fleet CRDs, manager and inert-registration workloads and RBAC, private-record namespaces, and admission fences | | `config/overlays/synthetic-staging` | Fleet management cluster (non-production only) | Management-plane resources plus an explicit synthetic allocator/provider integration | -`config/components/device-deletion-protection` is an optional component: a -ValidatingAdmissionPolicy and binding that deny every Device `DELETE`, with no -exemptions. Each environment chooses whether to install it. Production-style -Milo control planes use `config/milo-production`; test, staging and synthetic -control planes that need Device deletions use `config/milo` or -`config/milo-synthetic`. `hack/validate-overlay-isolation.sh` rejects any other -root that renders the policy. Namespace and project deletions that reach a -protected Device stay stuck rather than deleting it; see +`config/components/device-deletion-protection` is a reusable component: a +ValidatingAdmissionPolicy and binding that deny a Device `DELETE` unless the +Device is `Retired` or its namespace is being deleted, with no exemptions. +Production-specific configuration lives in the deploying repository, which +opts in by adding the component to the root it applies to Milo. No root in this +repository includes it, and `hack/validate-overlay-isolation.sh` fails if one +does or if the component's policy is weakened. See [Device deletion protection](../docs/development/inventory-capacity-registration.md#device-deletion-protection). The synthetic staging overlay excludes the inert-registration service. Pair it @@ -121,11 +119,10 @@ synthetic claim before treating persistent-state recovery as verified in staging Do not delete the PVC as a recovery shortcut. -Render both production roots before publishing the Kustomize bundle: +Render the Milo and management-cluster roots before publishing the Kustomize bundle: ```sh kustomize build config/milo >/dev/null -kustomize build config/milo-production >/dev/null kustomize build config/milo-synthetic >/dev/null kustomize build config/overlays/management-plane >/dev/null kustomize build config/overlays/synthetic-staging >/dev/null diff --git a/docs/development/README.md b/docs/development/README.md index d4ccb76d..364bf6c8 100644 --- a/docs/development/README.md +++ b/docs/development/README.md @@ -21,8 +21,10 @@ public project API. Production caller-preserving allocation admission, replayable Milo event adapters, and production provider integration are not implemented. Inert [inventory-backed capacity registration](inventory-capacity-registration.md) now has a stateless caller-preserving admission service that checks live -Devices, one capacity per Device through a Device-derived name, optional Device -deletion protection, and a session-fenced default-namespace Device picker. It admits only Disabled/Retain records with cleaning explicitly +Devices, one capacity per Device through a Device-derived name, a Device +lifecycle (`Active`, `Decommissioning`, terminal `Retired`), an opt-in Device +deletion protection component that admits deletes only for Retired Devices or +a deleting namespace, and a session-fenced default-namespace Device picker. It admits only Disabled/Retain records with cleaning explicitly unconfigured; deployment trust inputs and live Milo acceptance remain required. An opt-in [local KVM installation harness](../operations/local-vm.md) implements a bounded libvirt executor and guest installer using the same lifecycle library. diff --git a/docs/development/inventory-capacity-registration.md b/docs/development/inventory-capacity-registration.md index 5278d81c..e7cfe5c0 100644 --- a/docs/development/inventory-capacity-registration.md +++ b/docs/development/inventory-capacity-registration.md @@ -18,8 +18,11 @@ a mutable tail with sealed segments, signed expansion and activation, epochs and growth limits. The user decided this was overengineering and replaced it with the following: -1. **Devices are not deleted.** An optional ValidatingAdmissionPolicy denies - every Device `DELETE`. An environment decides whether to install it; see +1. **In-service Devices are not deleted.** A reusable ValidatingAdmissionPolicy + component denies a Device `DELETE` unless the Device is `Retired` or its + namespace is being deleted. No root in this repository includes it; + deploying repositories opt in. See + [Device lifecycle](#device-lifecycle) and [Device deletion protection](#device-deletion-protection). 2. **No signed activation.** The bootstrap/activation gate, `/activationz`, `/status`, the operator control key and ConfigMap, @@ -30,11 +33,12 @@ with the following: checks the live Device and capacities through the API server on every request. -Rationale: when Devices are never deleted, the live Device list already holds -every identity the ledger used to remember, so a second store adds failure -modes without adding information. Environments that need to delete Devices, -such as test and synthetic environments, do not hold real machines and do not -need permanent identity retention. +Rationale: when in-service Devices are never deleted, the live Device list +already holds every identity the ledger used to remember, so a second store +adds failure modes without adding information. A Device leaves the list only +after someone has retired it on purpose, or deleted its namespace. Environments +that do not include the component, such as test and synthetic environments, do +not hold real machines and do not need identity retention. ## Public contract and authority @@ -68,7 +72,9 @@ operation ID is no longer used for deduplication. An empty cleaning-policy name explicitly means **unconfigured**, not a policy named `default`, synthetic cleaning, or authorization to prepare. The CRD permits it only while Disabled. The webhook rejects *all* capacity updates, -status updates and deletes. Real policy resolution and policy-use authorization +status updates and deletes. An update that would move capacity out of +`Disabled` while its Device is `Decommissioning` or `Retired` is denied for +that reason; the webhook first checks that the caller can read the Device. Real policy resolution and policy-use authorization are future prerequisites for a separately designed transition; there is no stage-1 preparation endpoint. @@ -85,7 +91,8 @@ stage-1 preparation endpoint. happens before the Device is read, so an unauthorized caller cannot learn whether a Device exists; 5. reads the Device uncached. A missing Device is denied. Its UID and - resourceVersion must equal the annotations, and it must not be deleting; + resourceVersion must equal the annotations, it must not be deleting, and + its [lifecycle](#device-lifecycle) must be `Active`; 6. requires both a non-placeholder serial and a canonical system UUID, and a complete provider host reference when one is present; 7. lists Devices and capacities in **all namespaces of every configured @@ -154,71 +161,119 @@ both fail, because each sees the other Device. Device status has no writer today, so there is no server-side eligibility condition to set; reporting conflicts through Device status is a follow-up. +## Device lifecycle + +`Device.spec.lifecycle` records whether the asset is in service. It is part of +spec, so the inventory editor role, which can update Devices, can set it; no +extra RBAC exists. + +| Value | Meaning | +| --- | --- | +| `Active` | In service. The CRD default when the field is unset. | +| `Decommissioning` | Leaving service. Can return to `Active`. | +| `Retired` | Out of service. Terminal. | + +The CRD enforces transitions with transition rules (`oldSelf`) on `spec`: + +- `Active` to `Decommissioning`, `Decommissioning` to `Active`, and + `Decommissioning` to `Retired` are allowed. Leaving the value unchanged is + always allowed. +- `Active` to `Retired` is rejected: move the Device to `Decommissioning` + first. +- Nothing leaves `Retired`. Removing the field defaults it to `Active`, so + that is rejected too. + +The rules apply to updates only; a Device may be created in any lifecycle, for +example to record hardware that is already out of service. Other spec edits to +a Retired Device are still subject only to the existing rules. + +Registration semantics, enforced by the registration webhook: + +- Only an `Active` Device can get new capacity. +- Capacity whose Device is `Decommissioning` or `Retired` cannot leave + `Disabled`. Stage 1 already denies every capacity update, so this states the + rule a future enabling transition must keep. +- A Retired Device still takes part in the duplicate-identity check for as + long as it exists. Deleting it removes its identity from that check. + +Lifecycle is a record, not an effect. Moving a Device changes no capacity, +allocation, provider or network state. + ## Device deletion protection -`config/components/device-deletion-protection` is a Kustomize component with a -ValidatingAdmissionPolicy and binding named `fleet-device-deletion-protection`. -It denies every `DELETE` on `devices.fleet.datumapis.com` (all versions, all -namespaces) with `failurePolicy: Fail` and reason `Forbidden`. - -- **Where it is installed.** Devices are stored and admitted by the Milo - control plane: `config/components/inventory` registers the CRD there, and - records live in provider projects. The component therefore belongs with the - Milo root, not the management-cluster host overlays, which have no Device - CRD. Like the registration webhook, it is installed at the Milo root and - relies on Milo running its root admission policies for project-routed - requests (pinned Milo `v0.36.9` enables the `ValidatingAdmissionPolicy` - plugin). Confirm this on the deployed Milo before relying on it. -- **Which roots include it.** `config/milo-production` is `config/milo` plus - the component, and is the production-style root. `config/milo` (consumed by - staging and test control planes that need Device deletion), - `config/milo-synthetic`, `config/inventory`, `config/standalone` and every - host overlay leave it out. `hack/validate-overlay-isolation.sh` fails if a - production-style root lacks it, or if any other root renders it. -- **No exemptions.** No user, group or service account is exempt, including - cluster administrators. The escape hatch is an environment not installing - the component. Anyone able to delete the binding is outside the guarantee. -- **deletecollection.** The API server admits each object of a collection - delete individually as a `DELETE`, so a collection delete that includes a - Device fails and leaves Devices in place. Other objects in the same call may - already be gone. -- **Garbage collection and finalizers.** Owner-reference cascades issue the - same `DELETE` and are denied. Because the `DELETE` is denied, a Device never - gets a deletion timestamp, so finalizers never run. -- **Namespace and project deletion (fail-closed: stays stuck).** A policy - cannot see what a namespace contains, so it does not block the namespace - `DELETE`. The namespace becomes `Terminating`, the namespace controller - deletes the other contents, and its Device deletions are denied. The - namespace stays `Terminating` with its Devices intact and readable; it - accepts no new objects. Milo keeps `default` undeletable, and Milo's project - purge drains `default` in place and reports remaining Devices as blockers on - the Project. So deleting a provider project stops with its Devices in place. - Other inventory in that namespace or project (for example DeviceClaims) is - still deleted before the cascade stops. Capacity is not, because the - registration webhook denies capacity deletes. Do not delete namespaces or - projects that hold Devices. -- **Remediation for a stuck namespace or project.** Kubernetes cannot cancel - a namespace deletion. Either leave it `Terminating`, which keeps every - Device, or have the environment owner deliberately decide to give up those - identities: remove the binding, let the cascade finish, and reinstall the - component. The second option loses the Device records and their duplicate - protection, so it is an explicit ownership decision, not routine repair. -- **Retirement.** A machine leaving service keeps its Device. Its capacity is - already `Disabled` and cannot be changed, which is the only retirement state - stage 1 has. Devices have no lifecycle or retirement field (see - [Planning and registering physical devices](../operations/physical-inventory.md)). - A Device retirement state is a follow-up. - -### Deleting a Device where deletion is allowed - -Without the component, deleting a Device that backs capacity leaves the -capacity in place, still `Disabled`. The webhook denies every update and -delete of it, so it cannot become available. No owner reference links the two: -the webhook rejects owner references on registration, and garbage collection -would be denied anyway because capacity deletes are fenced. The orphaned -capacity keeps its Device UID annotation and name, which also prevents a -replacement Device with the same name from registering. Clean it up only in -environments where capacity writes are not fenced, such as synthetic ones. +`config/components/device-deletion-protection` is a reusable Kustomize +component with a ValidatingAdmissionPolicy and binding named +`fleet-device-deletion-protection`. It matches every `DELETE` on +`devices.fleet.datumapis.com` (all versions, all namespaces) and admits it only +when: + +1. the Device's namespace is being deleted: the policy's `namespaceObject` + has `metadata.deletionTimestamp` set. A missing namespace object does not + match; or +2. the Device being deleted (`oldObject`) has `spec.lifecycle: Retired`. + +Every other `DELETE` is denied with reason `Forbidden` and a message to move +the Device to `Decommissioning`, then `Retired`, first. The policy uses +`failurePolicy: Fail` and the binding `validationActions: [Deny]`, so an +evaluation error also denies. + +- **Who includes it.** No root in this repository renders the policy. + Production-specific configuration lives in the deploying repository, which + adds the component to the root it applies to the Milo control plane. Devices + are stored and admitted there: `config/components/inventory` registers the + CRD in Milo, and records live in provider projects. Management-cluster host + overlays have no Device CRD. Like the registration webhook, the policy relies + on Milo running its root admission policies for project-routed requests + (pinned Milo `v0.36.9` enables the `ValidatingAdmissionPolicy` plugin). + Confirm this on the deployed Milo before relying on it. +- **Validation.** `hack/validate-overlay-isolation.sh` renders the component + on its own and fails unless it is exactly this policy: the same name, + expression, `failurePolicy: Fail`, `Deny` only, and no match conditions, + selectors, exclusions, variables or parameters. It also fails if any root in + this repository renders the policy, under its own name or another, and if + the inventory component exists without this component. +- **No exemptions.** The policy does not look at the request's user, group or + service account. Cluster administrators are held to the same rule. Anyone + able to delete the binding is outside the guarantee. +- **deletecollection, garbage collection and finalizers.** The API server + admits each object of a collection delete individually as a `DELETE`, so a + collection delete that reaches a Device that is not Retired is denied and + leaves that Device in place. Retired Devices and other objects it reached + first may already be gone; it may also stop before reaching every Retired + Device, so repeat the delete per Device. Owner-reference cascades issue + the same `DELETE`. A denied Device gets no deletion timestamp, so its + finalizers never run. +- **Namespace deletion is the escape hatch.** Deleting a namespace is a + privileged act. Once the namespace has a deletion timestamp, the namespace + controller's Device deletions are admitted, so the namespace finishes + terminating and takes its Devices with it, whatever their lifecycle. Their + identities leave the duplicate check. The policy reads the namespace from the + API server's namespace cache, which observes the deletion mark shortly after + it is set. +- **Project deletion.** In pinned Milo `v0.36.9`, project purge first issues a + collection delete for every namespaced resource in every namespace, and only + then deletes the namespaces. It never deletes `default`, which it drains in + place. In that first phase no namespace is marked yet, so a Device that is + not Retired stops the purge's collection delete. Registered Devices live in + `default`, which is never marked. A project that holds Devices that are not + Retired therefore does not finish purging while the component is installed: + retire its Devices first. This is from reading the pinned Milo source, not a + live test. +- **Capacity is not deleted with its Device.** The registration webhook denies + capacity deletes, so a namespace or project teardown that removes Devices + still stops at their capacity; see the next section. + +### Deleting a Device + +Deleting a Device that backs capacity, whether it is Retired, its namespace is +being deleted, or the component is not installed, leaves the capacity in +place, still `Disabled`. The webhook denies every update and delete of it, so +it cannot become available. No owner reference links the two: the webhook +rejects owner references on registration, and garbage collection would be +denied anyway because capacity deletes are fenced. The orphaned capacity keeps +its Device UID annotation and name, which also prevents a replacement Device +with the same name from registering. Clean it up only in environments where +capacity writes are not fenced, such as synthetic ones. ## Production packaging and rollout @@ -228,7 +283,9 @@ environments where capacity writes are not fenced, such as synthetic ones. selectors or match conditions. An unreachable service blocks capacity writes globally and nothing else: Device, namespace and Project writes do not pass through the registration webhook. -- `config/milo-production` adds Device deletion protection. +- No root in this repository includes Device deletion protection. A + deploying repository adds `config/components/device-deletion-protection` to + the root it applies to Milo when it must keep in-service Devices. - `config/overlays/management-plane` includes a separate two-replica registration Deployment and TLS Service. The pod does not mount a service account token and has no host RBAC. It does not enable production lifecycle @@ -259,11 +316,13 @@ Environment-owned inputs, none of which this repository supplies: API-server client certificate signed by that CA, patch the webhook URL for reachability, and set `clientConfig.caBundle` to the serving CA. 3. Keep `--provider-projects` equal to the complete provider scope. -4. Choose the Milo root: `config/milo-production` to forbid Device deletion, - or `config/milo` to allow it. +4. Decide whether the Milo root you apply includes + `config/components/device-deletion-protection`. With it, only Retired + Devices and Devices in a deleting namespace can be deleted; without it, + any authorized caller can delete a Device. 5. Before rolling out the UI, verify caller-preserving project routing, named Device read denial, registration denial, capacity mutation denial, TLS - rejection, Device deletion denial where installed, and duplicate handling + rejection, Device deletion denial where installed, lifecycle transitions, and duplicate handling in the target environment. This change performs **no live writes or deployment**, so it does not claim those checks. @@ -276,8 +335,10 @@ those objects until its owner removes them; the new service ignores them. The Datum dialog uses the existing host-session boundary and isolated read cache. It shows the derived capacity name instead of a name field. Missing -host authority, denied registration, unavailable Devices, partial identity and -conflicting identities have explicit explanations. Selecting a Device +host authority, denied registration, unavailable Devices, Devices that are not +Active, partial identity and conflicting identities, including a conflict with +a Retired Device, have explicit explanations. The inventory detail panel shows +a Device's lifecycle; the UI does not edit it. Selecting a Device snapshots its baseline; neither refetch nor browser blur/focus changes it. A named current read immediately precedes dispatch. Session changes fence pending work. After dispatch, an uncertain result keeps the selection, disables @@ -309,19 +370,35 @@ packaged webhook against a real API server and checks that: - without the component, Device `DELETE` succeeds and the backing capacity stays `Disabled` and cannot be updated, deleted or re-registered by a same-name replacement; -- with the component applied from its manifest, Device `DELETE` is denied for - every caller, `deletecollection` is denied, and namespace deletion stays - `Terminating` with its Devices while other content drains. envtest has no - namespace controller, so the test issues the controller's content deletions - itself; +- a Decommissioning or Retired Device cannot be registered, a Retired Device + still blocks a duplicate, and capacity cannot leave `Disabled` once its + Device is Decommissioning or Retired; - a webhook outage blocks capacity writes but not Device writes. +`internal/registration/deletion_envtest_test.go` applies the component from +its manifest and checks that: + +- the CRD transition rules accept `Active`/`Decommissioning` moves and + `Decommissioning` to `Retired`, and reject `Active` to `Retired` and every + move out of `Retired`; +- deleting an Active or Decommissioning Device is denied for every caller, + and deleting a Retired Device is allowed; +- `deletecollection` over mixed Devices denies those that are not Retired; +- after the namespace is deleted, its Devices can be deleted. envtest has no + namespace controller, so the test issues the controller's deletions itself + and they are admitted because `namespaceObject` has a deletion timestamp; +- Devices in other namespaces stay protected. + Unit tests cover the remaining negative cases, normalization, cross-project duplicates, project lifetime and the packaged webhook shape. `cmd/fleet-registration` tests reject unauthenticated and untrusted webhook -transport. The overlay isolation tests cover where the deletion component may -and must appear. Frontend tests cover the derived name and conflict marking -with mocked transport. None of this is a live Milo deployment or an independent +transport. `internal/api/inventory/v1alpha1/lifecycle_test.go` runs the +lifecycle default and transition rules through the CRD schema offline. The +overlay isolation tests fail when a root includes the deletion component and +when the component's policy is renamed, made audit-only, fail-open, scoped, +exempted or given a weaker expression. Frontend tests cover the derived name, +conflict marking including Retired Devices, and refusal of Devices that are not +Active, with mocked transport. None of this is a live Milo deployment or an independent security review. The publishing workflow applies the server build tag to diff --git a/docs/operations/physical-inventory.md b/docs/operations/physical-inventory.md index d009eb89..79234491 100644 --- a/docs/operations/physical-inventory.md +++ b/docs/operations/physical-inventory.md @@ -143,6 +143,7 @@ in the provider project. The plugin never writes. | Port and interface names are unique; MACs are lowercase and colon-separated, appear at most once per Device, and are either mapped to an interface or listed in `unmappedMACAddresses`, not both | Both | Malformed or ambiguous facts are rejected. | | The system UUID is in lowercase canonical form | Device | One spelling per identity. | | `bmc.endpoint` is an `https` URL without credentials | Device | Credentials never live in inventory records. | +| `lifecycle` is `Active` (default), `Decommissioning` or `Retired`; `Active` and `Decommissioning` move between each other, only `Decommissioning` moves to `Retired`, and `Retired` is terminal | Device | Retirement is deliberate and one-way. Only an Active Device can be registered as capacity. See [Device lifecycle](../development/inventory-capacity-registration.md#device-lifecycle). | | `status` is a separate subresource that declares no fields | All six | Reserved for future collectors and verifiers to report drift and mismatch. Status never carries identity, and nothing writes it yet. | The CRDs cannot check that `claimRef` names an existing DeviceClaim, because @@ -328,10 +329,13 @@ spec: ``` To replace the hardware, create a new Device with its own name and identity -that names the same claim. Leave the old Device in place until its retirement -is settled. This package does not model retirement. Environments with +that names the same claim. Leave the old Device in place and move its +`spec.lifecycle` from `Active` to `Decommissioning`, then to `Retired`; see +[Device lifecycle](../development/inventory-capacity-registration.md#device-lifecycle). +Retired is terminal and still counts in the duplicate-identity check while the +Device exists. Environments with [Device deletion protection](../development/inventory-capacity-registration.md#device-deletion-protection) -never delete a Device. +delete a Device only once it is Retired, or with its namespace. ## Relationship to the inventory proposal @@ -354,8 +358,8 @@ Still deferred to #63: adjudication and duplicate detection; and the protected ledger. - Trust roots, qualification profiles, enrollment challenges, technician and collector attestation, and evidence freshness. -- Component incarnations and lineage, maintenance, moves, retirement, and - adopted custody. +- Component incarnations and lineage, maintenance, moves, a retirement + workflow beyond the recorded Device lifecycle, and adopted custody. - The `Accepted`, `Bound`, `IdentityVerified`, `PlacementVerified`, `NetworkPathVerified`, and `PowerPathVerified` predicates and any eligibility publication. @@ -416,8 +420,8 @@ Two kinds of stored record no longer validate once pruned: serial or system UUID. Because `identity` is immutable, delete it and create a new Device with a serial or system UUID. Where [Device deletion protection](../development/inventory-capacity-registration.md#device-deletion-protection) - is installed the record cannot be deleted; leave it in place and create the - new Device alongside it. + is installed, retire it (`Decommissioning`, then `Retired`) before deleting + it, or leave it in place and create the new Device alongside it. - A Device whose `reportedPlacement` lacks `reason` or `reference` must gain both the next time its report changes. From 3e41e9e23ead4cb1afa568ed8ef6b64a4d275ac8 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sun, 22 Nov 2026 17:14:13 -0600 Subject: [PATCH 081/518] feat(config): allow cleanup identity Device delete Milo project purge drains every namespace, default included, with DeleteCollection before it deletes any namespace, so the deleting-namespace exception never applies and a denied Device aborts the purge. Add a third exception: the request's username is listed exactly in the cleanupUsernames key of a ConfigMap parameter. The policy gains paramKind core/v1 ConfigMap. The shipped binding has no paramRef, so params is null and the exception is off; deploying repositories add the ConfigMap and a paramRef with parameterNotFoundAction Deny. Entries are trimmed, empty entries and an empty username never match, and groups, prefixes and wildcards are not consulted. failurePolicy Fail and validationActions Deny stay. The overlay validator requires the exact rendered policy, including paramKind, and rejects wildcard, prefix, group-based, null-params-allows-all, empty-username and always-true variants, a different or missing paramKind, and any paramRef in the component. Envtest on Kubernetes 1.37.0 covers the null-params binding, listed, unlisted, prefix and superset users, deletecollection, a Milo-style purge of default and another namespace, and fail-closed denial (422 Invalid) when the referenced ConfigMap is missing. An offline test runs the expression through the admission CEL compiler for an empty username. Co-Authored-By: Claude Opus 5.5 --- .../device-deletion-protection/policy.yaml | 47 +++- hack/overlay-isolation-validator.go | 37 ++- hack/test-overlay-isolation.sh | 27 +- .../registration/deletion_envtest_test.go | 230 +++++++++++++++++- internal/registration/deletion_policy_test.go | 139 +++++++++++ 5 files changed, 457 insertions(+), 23 deletions(-) create mode 100644 internal/registration/deletion_policy_test.go diff --git a/config/components/device-deletion-protection/policy.yaml b/config/components/device-deletion-protection/policy.yaml index 0de29e95..870d7fa6 100644 --- a/config/components/device-deletion-protection/policy.yaml +++ b/config/components/device-deletion-protection/policy.yaml @@ -3,20 +3,36 @@ # spec.lifecycle to Decommissioning and then Retired; the CRD rejects every # other path to Retired, and Retired is terminal. # -# The one other exception is a Device whose namespace is being deleted -# (namespaceObject.metadata.deletionTimestamp is set). Deleting a namespace is -# the privileged escape hatch: it lets the namespace controller finish and -# takes its Devices with it. Nothing keys off who makes the request, and there -# are no exemptions. The API server runs admission once per object for -# deletecollection, garbage collection and namespace cleanup, so each of those -# paths is held to the same rule. A missing namespace object or an evaluation -# error denies the request (failurePolicy: Fail). +# Three exceptions admit a DELETE: +# +# 1. The Device's namespace is being deleted +# (namespaceObject.metadata.deletionTimestamp is set). Deleting a namespace +# is the privileged escape hatch: it lets the namespace controller finish +# and takes its Devices with it. +# 2. The Device is Retired. +# 3. The request's username is listed, exactly, in the cleanupUsernames key of +# the binding's parameter ConfigMap. This lets a project cleanup controller +# drain Devices in place, which namespace deletion cannot do for `default`. +# Entries are separated by commas or newlines and trimmed; empty entries +# and an empty username never match. Groups, prefixes and wildcards are not +# consulted. +# +# The binding below has no paramRef, so params is null and exception 3 is off. +# A deploying repository turns it on by adding the ConfigMap and patching the +# binding with a paramRef that sets parameterNotFoundAction: Deny; a missing +# ConfigMap then denies every Device DELETE. The API server runs admission once +# per object for deletecollection, garbage collection and namespace cleanup, so +# each of those paths is held to the same rule. A missing namespace object or +# an evaluation error denies the request (failurePolicy: Fail). apiVersion: admissionregistration.k8s.io/v1 kind: ValidatingAdmissionPolicy metadata: name: fleet-device-deletion-protection spec: failurePolicy: Fail + paramKind: + apiVersion: v1 + kind: ConfigMap matchConstraints: matchPolicy: Equivalent resourceRules: @@ -29,13 +45,20 @@ spec: (namespaceObject != null && has(namespaceObject.metadata) && has(namespaceObject.metadata.deletionTimestamp)) || (oldObject != null && has(oldObject.spec) && has(oldObject.spec.lifecycle) && - oldObject.spec.lifecycle == 'Retired') + oldObject.spec.lifecycle == 'Retired') || + (params != null && has(params.data) && 'cleanupUsernames' in params.data && + request.userInfo.username != '' && + params.data.cleanupUsernames.replace('\n', ',').split(',').exists(entry, + entry.trim() != '' && entry.trim() == request.userInfo.username)) reason: Forbidden message: >- - Only a Retired Device can be deleted. Move the Device to Decommissioning, - then Retired, first; its identity must stay visible to duplicate-hardware - checks while it is in service. + A Device can be deleted only when it is Retired, when its namespace is + being deleted, or by a configured cleanup identity. Move the Device to + Decommissioning, then Retired, first; its identity must stay visible to + duplicate-hardware checks while it is in service. --- +# No paramRef: params is null and only the namespace and Retired exceptions +# apply. See docs/development/inventory-capacity-registration.md#cleanup-identity. apiVersion: admissionregistration.k8s.io/v1 kind: ValidatingAdmissionPolicyBinding metadata: diff --git a/hack/overlay-isolation-validator.go b/hack/overlay-isolation-validator.go index e524df59..79e111f0 100644 --- a/hack/overlay-isolation-validator.go +++ b/hack/overlay-isolation-validator.go @@ -37,12 +37,18 @@ const ( inventoryComponent = "components/inventory" // deletionProtectionExpression is the only admitted rule: a Device DELETE - // passes when its namespace is being deleted or it is Retired. It is - // compared with whitespace normalized. + // passes when its namespace is being deleted, it is Retired, or the + // request's username is listed exactly in the parameter ConfigMap's + // cleanupUsernames. It is compared with whitespace normalized, so wildcard, + // prefix, group-based or null-params-allows-all variants are rejected. deletionProtectionExpression = `(namespaceObject != null && has(namespaceObject.metadata) && has(namespaceObject.metadata.deletionTimestamp)) || (oldObject != null && has(oldObject.spec) && has(oldObject.spec.lifecycle) && -oldObject.spec.lifecycle == 'Retired')` +oldObject.spec.lifecycle == 'Retired') || +(params != null && has(params.data) && 'cleanupUsernames' in params.data && +request.userInfo.username != '' && +params.data.cleanupUsernames.replace('\n', ',').split(',').exists(entry, +entry.trim() != '' && entry.trim() == request.userInfo.username))` ) type kustomization struct { @@ -331,22 +337,37 @@ func checkDeletionProtection(root string, objects []*unstructured.Unstructured, spec := policy.Object["spec"].(map[string]any) _, hasConditions := spec["matchConditions"] _, hasVariables := spec["variables"] - _, hasParams := spec["paramKind"] - if policy.GetName() != deletionProtection || failurePolicy != "Fail" || !policyMatchesDeviceDelete(policy) || !unscopedConstraints(policy) || hasConditions || hasVariables || hasParams || len(validations) != 1 { + if policy.GetName() != deletionProtection || failurePolicy != "Fail" || !policyMatchesDeviceDelete(policy) || !unscopedConstraints(policy) || hasConditions || hasVariables || len(validations) != 1 { return fmt.Errorf("%s: Device deletion policy must fail closed, match DELETE on devices and have no exemptions", root) } + if !configMapParamKind(spec["paramKind"]) { + return fmt.Errorf("%s: Device deletion policy paramKind must be exactly core/v1 ConfigMap", root) + } if expression, _, _ := unstructured.NestedString(validations[0].(map[string]any), "expression"); strings.Join(strings.Fields(expression), " ") != strings.Join(strings.Fields(deletionProtectionExpression), " ") { - return fmt.Errorf("%s: Device deletion policy must allow DELETE only for a Retired Device or a deleting namespace", root) + return fmt.Errorf("%s: Device deletion policy must allow DELETE only for a Retired Device, a deleting namespace or an exactly listed cleanup username", root) } actions, _, _ := unstructured.NestedStringSlice(binding.Object, "spec", "validationActions") _, hasMatch := binding.Object["spec"].(map[string]any)["matchResources"] - _, hasParamRef := binding.Object["spec"].(map[string]any)["paramRef"] - if len(actions) != 1 || actions[0] != "Deny" || hasMatch || hasParamRef { + if len(actions) != 1 || actions[0] != "Deny" || hasMatch { return fmt.Errorf("%s: Device deletion binding must Deny in every namespace", root) } + // The component ships the cleanup identity off. A deploying repository + // adds the paramRef, with parameterNotFoundAction: Deny, alongside its own + // ConfigMap; a paramRef here, and above all one that Allows a missing + // parameter (which skips the policy), is rejected. + if _, hasParamRef := binding.Object["spec"].(map[string]any)["paramRef"]; hasParamRef { + return fmt.Errorf("%s: Device deletion binding must not set paramRef; deploying repositories enable the cleanup identity", root) + } return nil } +// configMapParamKind reports whether a policy paramKind is exactly core/v1 +// ConfigMap, the only parameter the cleanup identity reads. +func configMapParamKind(value any) bool { + paramKind, ok := value.(map[string]any) + return ok && len(paramKind) == 2 && paramKind["apiVersion"] == "v1" && paramKind["kind"] == "ConfigMap" +} + func policyMatchesDeviceDelete(policy *unstructured.Unstructured) bool { rules, _, _ := unstructured.NestedSlice(policy.Object, "spec", "matchConstraints", "resourceRules") for _, raw := range rules { diff --git a/hack/test-overlay-isolation.sh b/hack/test-overlay-isolation.sh index 95211c24..ee163d01 100755 --- a/hack/test-overlay-isolation.sh +++ b/hack/test-overlay-isolation.sh @@ -479,8 +479,8 @@ weakened "renamed Device deletion policy and binding" "components/device-deletio weakened "audit-only Device deletion binding" "must Deny in every namespace" -e 's/validationActions: \[Deny\]/validationActions: [Audit]/' weakened "warn-only Device deletion binding" "must Deny in every namespace" -e 's/validationActions: \[Deny\]/validationActions: [Warn]/' weakened "fail-open Device deletion policy" "must fail closed" -e 's/failurePolicy: Fail/failurePolicy: Ignore/' -weakened "always-true Device deletion expression" "allow DELETE only for a Retired Device or a deleting namespace" -e "s/oldObject.spec.lifecycle == 'Retired')/oldObject.spec.lifecycle == 'Retired') || true/" -weakened "Decommissioning Device deletion allowed" "allow DELETE only for a Retired Device or a deleting namespace" -e "s/== 'Retired')/!= 'Active')/" +weakened "always-true Device deletion expression" "allow DELETE only for a Retired Device, a deleting namespace or an exactly listed cleanup username" -e "s/oldObject.spec.lifecycle == 'Retired')/oldObject.spec.lifecycle == 'Retired') || true/" +weakened "Decommissioning Device deletion allowed" "allow DELETE only for a Retired Device, a deleting namespace or an exactly listed cleanup username" -e "s/== 'Retired')/!= 'Active')/" weakened "namespace-scoped Device deletion policy" "must fail closed" -e 's/ matchPolicy: Equivalent/ matchPolicy: Equivalent\ namespaceSelector: {matchLabels: {protected: "true"}}/' weakened "subject exemption in Device deletion policy" "must fail closed" -e 's/^ validations:/ matchConditions:\ @@ -488,4 +488,27 @@ weakened "subject exemption in Device deletion policy" "must fail closed" -e 's/ expression: "request.userInfo.username != '\''admin'\''"\ validations:/' +# The cleanup identity clause admits only an exactly listed, non-empty +# username from a ConfigMap parameter, and the component ships it off. +allowed="allow DELETE only for a Retired Device, a deleting namespace or an exactly listed cleanup username" +weakened "always-true cleanup identity clause" "$allowed" -e "s/entry.trim() != '' && entry.trim() == request.userInfo.username/true/" +weakened "wildcard cleanup username" "$allowed" -e "s/entry.trim() == request.userInfo.username/(entry.trim() == '*' || entry.trim() == request.userInfo.username)/" +weakened "prefix cleanup username" "$allowed" -e "s/entry.trim() == request.userInfo.username/request.userInfo.username.startsWith(entry.trim())/" +weakened "group-based cleanup exemption" "$allowed" -e "s/entry.trim() == request.userInfo.username))/entry.trim() == request.userInfo.username)) ||\\ + (params != null \&\& request.userInfo.groups.exists(group, group in params.data.cleanupUsernames.split(',')))/" +weakened "absent params allowing every Device deletion" "$allowed" -e "s/(params != null && has(params.data)/(params == null || has(params.data)/" +weakened "empty username matching an empty entry" "$allowed" -e "s/entry.trim() != '' && entry.trim() == request.userInfo.username/entry.trim() == request.userInfo.username/" -e "/request.userInfo.username != '' &&\$/d" +weakened "Secret paramKind" "paramKind must be exactly core/v1 ConfigMap" -e 's/^ kind: ConfigMap$/ kind: Secret/' +weakened "missing paramKind" "paramKind must be exactly core/v1 ConfigMap" -e '/^ paramKind:$/d' -e '/^ apiVersion: v1$/d' -e '/^ kind: ConfigMap$/d' +weakened "Allow parameterNotFoundAction in the component" "must not set paramRef" -e 's/^ validationActions: \[Deny\]/ validationActions: [Deny]\ + paramRef:\ + name: synthetic-device-cleanup\ + namespace: synthetic-device-cleanup\ + parameterNotFoundAction: Allow/' +weakened "cleanup identity enabled in the component" "must not set paramRef" -e 's/^ validationActions: \[Deny\]/ validationActions: [Deny]\ + paramRef:\ + name: synthetic-device-cleanup\ + namespace: synthetic-device-cleanup\ + parameterNotFoundAction: Deny/' + "$repo_root/hack/validate-overlay-isolation.sh" "$fixture_root/config" "$fixture_root/config/standalone" diff --git a/internal/registration/deletion_envtest_test.go b/internal/registration/deletion_envtest_test.go index 9a2dbbca..1e3693cf 100644 --- a/internal/registration/deletion_envtest_test.go +++ b/internal/registration/deletion_envtest_test.go @@ -7,13 +7,22 @@ import ( "testing" inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + admissionregistrationv1 "k8s.io/api/admissionregistration/v1" corev1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/controller-runtime/pkg/client" ) -const deletionDenied = "Only a Retired Device can be deleted" +const ( + deletionDenied = "A Device can be deleted only when it is Retired, when its namespace is being deleted, or by a configured cleanup identity" + // Synthetic identities. The policy compares usernames only, so each actor + // also holds system:masters to pass RBAC and prove groups do not matter. + syntheticCleanupUser = "synthetic-cleanup" + syntheticPurgeUser = "system:synthetic-purger" + cleanupConfig = "synthetic-device-cleanup" + missingParamsDenied = "no params found for policy binding with `Deny` parameterNotFoundAction" +) func (api *liveAPI) namespace(name string) *corev1.Namespace { api.t.Helper() @@ -96,6 +105,18 @@ func TestDeviceDeletionProtection(t *testing.T) { } } }) + t.Run("without a paramRef the cleanup username is not exempt", func(t *testing.T) { + // The shipped binding has no paramRef, so params is null. A null + // params must evaluate, not error: the denial carries the policy's + // own message, and the Retired subtest below is admitted. + cleanup := api.actor(syntheticCleanupUser, "system:masters") + if err := cleanup.Delete(ctx, active); !apierrors.IsForbidden(err) || !strings.Contains(err.Error(), deletionDenied) { + t.Fatalf("cleanup username deleting an Active Device without a paramRef: %v", err) + } + if !api.exists(active) { + t.Fatal("Active Device removed without a paramRef") + } + }) t.Run("a Retired Device can be deleted", func(t *testing.T) { if err := operator.Delete(ctx, retired); err != nil { t.Fatalf("deleting a Retired Device: %v", err) @@ -158,3 +179,210 @@ func TestDeviceDeletionProtection(t *testing.T) { } }) } + +// setParamRef does what a deploying repository does to turn on the cleanup +// identity: it points the binding at a ConfigMap in a fixed namespace with +// parameterNotFoundAction: Deny. The ConfigMap is created separately, so a +// test can also point the binding at one that does not exist. +func (api *liveAPI) setParamRef(name string) { + api.t.Helper() + ctx := context.Background() + binding := &admissionregistrationv1.ValidatingAdmissionPolicyBinding{} + if err := api.admin.Get(ctx, client.ObjectKey{Name: "fleet-device-deletion-protection"}, binding); err != nil { + api.t.Fatal(err) + } + deny := admissionregistrationv1.DenyAction + binding.Spec.ParamRef = &admissionregistrationv1.ParamRef{Name: name, Namespace: cleanupConfig, ParameterNotFoundAction: &deny} + if err := api.admin.Update(ctx, binding); err != nil { + api.t.Fatal(err) + } +} + +// missingParams reports whether err is the API server's denial for a binding +// whose parameter is missing under parameterNotFoundAction: Deny. +func missingParams(err error) bool { + return apierrors.IsInvalid(err) && strings.Contains(err.Error(), missingParamsDenied) +} + +func requireDeletionDenied(t *testing.T, err error, message string) { + t.Helper() + if !apierrors.IsForbidden(err) || !strings.Contains(err.Error(), message) { + t.Fatalf("expected a Device deletion denial containing %q, got %v", message, err) + } +} + +// TestDeviceDeletionCleanupIdentity enables the cleanup identity as a +// deploying repository would and checks who it admits, that the other two +// exceptions still hold, that it lets a Milo-style purge drain `default`, and +// that a missing ConfigMap fails closed. +func TestDeviceDeletionCleanupIdentity(t *testing.T) { + api := startAPI(t) + ctx := context.Background() + suffix := 0 + lifecycled := func(name, namespace string, lifecycle inventory.DeviceLifecycle) *inventory.Device { + suffix++ + device := api.device(name, namespace, fmt.Sprintf("%s-serial-%d", name, suffix), fmt.Sprintf("eeeeeeee-eeee-4eee-8eee-%012d", suffix)) + switch lifecycle { + case inventory.DeviceDecommissioning: + api.setLifecycle(device, lifecycle) + case inventory.DeviceRetired: + api.retire(device) + } + return device + } + active := lifecycled("cleanup-active", "default", inventory.DeviceActive) + decommissioning := lifecycled("cleanup-decommissioning", "default", inventory.DeviceDecommissioning) + guarded := lifecycled("guarded-active", "default", inventory.DeviceActive) + retired := lifecycled("cleanup-retired", "default", inventory.DeviceRetired) + api.namespace("collection") + collection := []*inventory.Device{ + lifecycled("collection-active", "collection", inventory.DeviceActive), + lifecycled("collection-decommissioning", "collection", inventory.DeviceDecommissioning), + lifecycled("collection-retired", "collection", inventory.DeviceRetired), + } + api.namespace("workloads") + purged := []*inventory.Device{ + lifecycled("purge-default-active", "default", inventory.DeviceActive), + lifecycled("purge-default-decommissioning", "default", inventory.DeviceDecommissioning), + lifecycled("purge-default-retired", "default", inventory.DeviceRetired), + lifecycled("purge-workloads-active", "workloads", inventory.DeviceActive), + lifecycled("purge-workloads-decommissioning", "workloads", inventory.DeviceDecommissioning), + lifecycled("purge-workloads-retired", "workloads", inventory.DeviceRetired), + } + teardown := api.namespace("teardown") + teardownFirst := lifecycled("teardown-first", "teardown", inventory.DeviceActive) + teardownSecond := lifecycled("teardown-second", "teardown", inventory.DeviceActive) + + api.installDeletionProtection(guarded) + cleanup := api.actor(syntheticCleanupUser, "system:masters") + purger := api.actor(syntheticPurgeUser, "system:masters") + operator := api.actor("synthetic-operator", "system:masters") + + t.Run("without a paramRef the cleanup username is denied", func(t *testing.T) { + requireDeletionDenied(t, cleanup.Delete(ctx, active), deletionDenied) + if !api.exists(active) { + t.Fatal("Active Device removed without a paramRef") + } + }) + + // Entries are padded and separated by commas, newlines and CRLF, with + // blank entries in between. Only exact, trimmed names match. + api.namespace(cleanupConfig) + config := &corev1.ConfigMap{ObjectMeta: metav1.ObjectMeta{Name: cleanupConfig, Namespace: cleanupConfig}, Data: map[string]string{"cleanupUsernames": " " + syntheticCleanupUser + " ,\n\n , \r\n" + syntheticPurgeUser + "\r\n,"}} + if err := api.admin.Create(ctx, config); err != nil { + t.Fatal(err) + } + api.setParamRef(cleanupConfig) + api.eventually("cleanup identity", func() bool { + return cleanup.Delete(ctx, guarded, client.DryRunAll) == nil + }) + + t.Run("the listed username deletes Active and Decommissioning Devices", func(t *testing.T) { + for _, device := range []*inventory.Device{active, decommissioning} { + if err := cleanup.Delete(ctx, device); err != nil { + t.Fatalf("cleanup identity deleting %s: %v", device.Name, err) + } + if api.exists(device) { + t.Fatalf("%s survived the cleanup identity's delete", device.Name) + } + } + }) + t.Run("the listed username deletes a mixed collection", func(t *testing.T) { + if err := cleanup.DeleteAllOf(ctx, &inventory.Device{}, client.InNamespace("collection")); err != nil { + t.Fatalf("cleanup identity deletecollection: %v", err) + } + for _, device := range collection { + if api.exists(device) { + t.Fatalf("%s survived the cleanup identity's deletecollection", device.Name) + } + } + }) + t.Run("other usernames stay denied", func(t *testing.T) { + callers := map[string]client.Client{ + "admin": api.admin, + "unlisted": operator, + "prefix": api.actor("synthetic-clean", "system:masters"), + "superset": api.actor(syntheticCleanupUser+"-extra", "system:masters"), + "embedded": api.actor("x"+syntheticCleanupUser, "system:masters"), + "case": api.actor("Synthetic-Cleanup", "system:masters"), + "listed name as a group": api.actor("synthetic-grouped", "system:masters", syntheticCleanupUser), + "suffix of a listed name": api.actor("synthetic-purger", "system:masters"), + } + for name, caller := range callers { + if err := caller.Delete(ctx, guarded); !apierrors.IsForbidden(err) || !strings.Contains(err.Error(), deletionDenied) { + t.Fatalf("%s deleting an Active Device: %v", name, err) + } + } + if !api.exists(guarded) { + t.Fatal("Active Device removed by an unlisted caller") + } + }) + t.Run("the Retired exception still holds", func(t *testing.T) { + if err := operator.Delete(ctx, retired); err != nil { + t.Fatalf("unlisted caller deleting a Retired Device: %v", err) + } + }) + t.Run("the deleting-namespace exception still holds", func(t *testing.T) { + requireDeletionDenied(t, operator.Delete(ctx, teardownFirst), deletionDenied) + if err := api.admin.Delete(ctx, teardown); err != nil { + t.Fatal(err) + } + api.eventually("namespace deletion mark", func() bool { + return operator.Delete(ctx, teardownFirst, client.DryRunAll) == nil + }) + if err := operator.Delete(ctx, teardownFirst); err != nil { + t.Fatalf("unlisted caller deleting a Device in a deleting namespace: %v", err) + } + // teardownSecond stays behind for the fail-closed check below. + }) + t.Run("a Milo-style purge drains default and other namespaces", func(t *testing.T) { + // Milo v0.36.9 project purge issues DeleteCollection per namespace, + // `default` included, before any namespace is marked for deletion. + for _, namespace := range []string{"default", "workloads"} { + if err := purger.DeleteAllOf(ctx, &inventory.Device{}, client.InNamespace(namespace)); err != nil { + t.Fatalf("purge deletecollection in %s: %v", namespace, err) + } + } + for _, device := range append(purged, guarded) { + if api.exists(device) { + t.Fatalf("%s survived the purge", device.Name) + } + } + }) + + // Fail closed: a paramRef to a ConfigMap that does not exist, under + // parameterNotFoundAction: Deny, denies every Device DELETE, including a + // Retired Device, the listed username and a deleting namespace. The API + // server reports this binding configuration error as 422 Invalid, not as + // the policy's 403 Forbidden. + failClosedRetired := lifecycled("fail-closed-retired", "default", inventory.DeviceRetired) + failClosedActive := lifecycled("fail-closed-active", "default", inventory.DeviceActive) + api.setParamRef("absent-" + cleanupConfig) + api.eventually("missing parameter denial", func() bool { + return missingParams(operator.Delete(ctx, failClosedRetired, client.DryRunAll)) + }) + t.Run("a missing ConfigMap denies every delete", func(t *testing.T) { + attempts := []struct { + name string + attempt func() error + }{ + {"Retired by an unlisted caller", func() error { return operator.Delete(ctx, failClosedRetired) }}, + {"Retired by the cleanup user", func() error { return cleanup.Delete(ctx, failClosedRetired) }}, + {"Active by the cleanup user", func() error { return cleanup.Delete(ctx, failClosedActive) }}, + {"Device in a deleting namespace", func() error { return api.admin.Delete(ctx, teardownSecond) }}, + {"purge deletecollection", func() error { + return purger.DeleteAllOf(ctx, &inventory.Device{}, client.InNamespace("default")) + }}, + } + for _, test := range attempts { + if err := test.attempt(); !missingParams(err) { + t.Fatalf("%s: %v", test.name, err) + } + } + for _, device := range []*inventory.Device{failClosedRetired, failClosedActive, teardownSecond} { + if !api.exists(device) { + t.Fatalf("%s removed while the parameter is missing", device.Name) + } + } + }) +} diff --git a/internal/registration/deletion_policy_test.go b/internal/registration/deletion_policy_test.go new file mode 100644 index 00000000..40d84390 --- /dev/null +++ b/internal/registration/deletion_policy_test.go @@ -0,0 +1,139 @@ +package registration + +import ( + "bytes" + "context" + "errors" + "io" + "os" + "testing" + + admissionv1 "k8s.io/api/admission/v1" + admissionregistrationv1 "k8s.io/api/admissionregistration/v1" + authenticationv1 "k8s.io/api/authentication/v1" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + utilyaml "k8s.io/apimachinery/pkg/util/yaml" + "k8s.io/apiserver/pkg/admission" + plugincel "k8s.io/apiserver/pkg/admission/plugin/cel" + "k8s.io/apiserver/pkg/admission/plugin/policy/validating" + celconfig "k8s.io/apiserver/pkg/apis/cel" + "k8s.io/apiserver/pkg/authentication/user" + "k8s.io/apiserver/pkg/cel/environment" +) + +// deletionPolicy reads the component's ValidatingAdmissionPolicy. +func deletionPolicy(t *testing.T) *admissionregistrationv1.ValidatingAdmissionPolicy { + t.Helper() + data, err := os.ReadFile("../../config/components/device-deletion-protection/policy.yaml") + if err != nil { + t.Fatal(err) + } + decoder := utilyaml.NewYAMLOrJSONDecoder(bytes.NewReader(data), 4096) + for { + var policy admissionregistrationv1.ValidatingAdmissionPolicy + err := decoder.Decode(&policy) + if errors.Is(err, io.EOF) { + t.Fatal("component has no ValidatingAdmissionPolicy") + } + if err != nil { + t.Fatal(err) + } + if policy.Kind == "ValidatingAdmissionPolicy" { + return &policy + } + } +} + +type deletionInput struct { + username string + groups []string + lifecycle string + namespaceDeleted bool + params *corev1.ConfigMap +} + +// TestDeletionPolicyCleanupIdentityOffline evaluates the policy's expression +// with the API server's admission CEL compiler, for inputs envtest cannot +// produce, such as an empty username. +func TestDeletionPolicyCleanupIdentityOffline(t *testing.T) { + policy := deletionPolicy(t) + if policy.Spec.ParamKind == nil || policy.Spec.ParamKind.APIVersion != "v1" || policy.Spec.ParamKind.Kind != "ConfigMap" { + t.Fatalf("paramKind = %+v, want core/v1 ConfigMap", policy.Spec.ParamKind) + } + if len(policy.Spec.Validations) != 1 { + t.Fatalf("validations = %d, want 1", len(policy.Spec.Validations)) + } + compiler := plugincel.NewConditionCompiler(environment.MustBaseEnvSet(environment.DefaultCompatibilityVersion())) + evaluator := compiler.CompileCondition([]plugincel.ExpressionAccessor{&validating.ValidationCondition{Expression: policy.Spec.Validations[0].Expression}}, plugincel.OptionalVariableDeclarations{HasParams: true}, environment.StoredExpressions) + + listed := func(value string) *corev1.ConfigMap { + return &corev1.ConfigMap{ObjectMeta: metav1.ObjectMeta{Name: "synthetic-device-cleanup", Namespace: "synthetic-device-cleanup"}, Data: map[string]string{"cleanupUsernames": value}} + } + list := listed(" synthetic-cleanup ,\n\n , \r\nsystem:synthetic-purger\r\n,") + for _, test := range []struct { + name string + input deletionInput + want bool + }{ + {"no params: listed name is not exempt", deletionInput{username: "synthetic-cleanup", lifecycle: "Active"}, false}, + {"no params: Retired is deletable", deletionInput{username: "synthetic-operator", lifecycle: "Retired"}, true}, + {"no params: deleting namespace", deletionInput{username: "synthetic-operator", lifecycle: "Active", namespaceDeleted: true}, true}, + {"listed name with padding", deletionInput{username: "synthetic-cleanup", lifecycle: "Active", params: list}, true}, + {"listed name after CRLF and blank entries", deletionInput{username: "system:synthetic-purger", lifecycle: "Decommissioning", params: list}, true}, + {"unlisted name", deletionInput{username: "synthetic-operator", lifecycle: "Active", params: list}, false}, + {"prefix of a listed name", deletionInput{username: "synthetic-clean", lifecycle: "Active", params: list}, false}, + {"superset of a listed name", deletionInput{username: "synthetic-cleanup-extra", lifecycle: "Active", params: list}, false}, + {"listed name embedded", deletionInput{username: "xsynthetic-cleanup", lifecycle: "Active", params: list}, false}, + {"case differs", deletionInput{username: "Synthetic-Cleanup", lifecycle: "Active", params: list}, false}, + {"listed name as a group only", deletionInput{username: "synthetic-operator", groups: []string{"synthetic-cleanup"}, lifecycle: "Active", params: list}, false}, + {"empty username against empty entries", deletionInput{username: "", lifecycle: "Active", params: listed(",\n , \n")}, false}, + {"empty username against an empty value", deletionInput{username: "", lifecycle: "Active", params: listed("")}, false}, + {"wildcard entry is literal", deletionInput{username: "synthetic-operator", lifecycle: "Active", params: listed("*")}, false}, + {"ConfigMap without the key", deletionInput{username: "synthetic-cleanup", lifecycle: "Active", params: &corev1.ConfigMap{Data: map[string]string{"other": "synthetic-cleanup"}}}, false}, + {"ConfigMap without data", deletionInput{username: "synthetic-cleanup", lifecycle: "Active", params: &corev1.ConfigMap{}}, false}, + {"params set: Retired still deletable", deletionInput{username: "synthetic-operator", lifecycle: "Retired", params: list}, true}, + {"params set: deleting namespace still deletable", deletionInput{username: "synthetic-operator", lifecycle: "Active", namespaceDeleted: true, params: list}, true}, + } { + t.Run(test.name, func(t *testing.T) { + if got := evaluateDeletion(t, evaluator, test.input); got != test.want { + t.Fatalf("admitted = %v, want %v", got, test.want) + } + }) + } +} + +func evaluateDeletion(t *testing.T, evaluator plugincel.ConditionEvaluator, input deletionInput) bool { + t.Helper() + gvk := schema.GroupVersionKind{Group: "fleet.datumapis.com", Version: "v1alpha1", Kind: "Device"} + gvr := schema.GroupVersionResource{Group: "fleet.datumapis.com", Version: "v1alpha1", Resource: "devices"} + old := &unstructured.Unstructured{Object: map[string]any{"apiVersion": gvk.GroupVersion().String(), "kind": gvk.Kind, "metadata": map[string]any{"name": "synthetic-device", "namespace": "default"}, "spec": map[string]any{"lifecycle": input.lifecycle}}} + caller := &user.DefaultInfo{Name: input.username, Groups: input.groups} + attributes := admission.NewAttributesRecord(nil, old, gvk, "default", "synthetic-device", gvr, "", admission.Delete, &metav1.DeleteOptions{}, false, caller) + versioned := &admission.VersionedAttributes{Attributes: attributes, VersionedOldObject: admission.NewLazyObject(old), VersionedKind: gvk} + request := &admissionv1.AdmissionRequest{Kind: metav1.GroupVersionKind(gvk), Resource: metav1.GroupVersionResource(gvr), Name: "synthetic-device", Namespace: "default", Operation: admissionv1.Delete, UserInfo: authenticationv1.UserInfo{Username: input.username, Groups: input.groups}} + namespace := &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "default"}} + if input.namespaceDeleted { + now := metav1.Now() + namespace.DeletionTimestamp = &now + } + var params runtime.Object + if input.params != nil { + params = input.params + } + results, _, err := evaluator.ForInput(context.Background(), versioned, request, plugincel.OptionalVariableBindings{VersionedParams: params}, namespace, celconfig.RuntimeCELCostBudget) + if err != nil { + t.Fatal(err) + } + if len(results) != 1 || results[0].Error != nil { + t.Fatalf("evaluation failed: %+v", results) + } + admitted, ok := results[0].EvalResult.Value().(bool) + if !ok { + t.Fatalf("expression returned %v, want a bool", results[0].EvalResult) + } + return admitted +} From c0f59d82b333f1cd20a3e4aa1f5fdb7246d66ca2 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sun, 22 Nov 2026 17:14:14 -0600 Subject: [PATCH 082/518] docs: describe the Device cleanup identity Document the third Device deletion exception, how a deploying repository enables it with a ConfigMap and a paramRef that sets parameterNotFoundAction Deny, and that a missing ConfigMap then denies every Device delete. Note that impersonating a listed identity grants the exemption. Project deletion now completes when the cleanup identity is configured and stays blocked otherwise, unless every Device is Retired. Co-Authored-By: Claude Opus 5.5 --- .../inventory-capacity-registration.md | 186 +++++++++++++++--- docs/operations/physical-inventory.md | 7 +- 2 files changed, 164 insertions(+), 29 deletions(-) diff --git a/docs/development/inventory-capacity-registration.md b/docs/development/inventory-capacity-registration.md index e7cfe5c0..e5808df2 100644 --- a/docs/development/inventory-capacity-registration.md +++ b/docs/development/inventory-capacity-registration.md @@ -19,8 +19,9 @@ and growth limits. The user decided this was overengineering and replaced it with the following: 1. **In-service Devices are not deleted.** A reusable ValidatingAdmissionPolicy - component denies a Device `DELETE` unless the Device is `Retired` or its - namespace is being deleted. No root in this repository includes it; + component denies a Device `DELETE` unless the Device is `Retired`, its + namespace is being deleted, or the caller is a cleanup identity that the + deploying repository lists. No root in this repository includes it; deploying repositories opt in. See [Device lifecycle](#device-lifecycle) and [Device deletion protection](#device-deletion-protection). @@ -36,7 +37,8 @@ with the following: Rationale: when in-service Devices are never deleted, the live Device list already holds every identity the ledger used to remember, so a second store adds failure modes without adding information. A Device leaves the list only -after someone has retired it on purpose, or deleted its namespace. Environments +after someone has retired it on purpose, deleted its namespace, or deleted its +project through a configured cleanup identity. Environments that do not include the component, such as test and synthetic environments, do not hold real machines and do not need identity retention. @@ -209,11 +211,16 @@ when: 1. the Device's namespace is being deleted: the policy's `namespaceObject` has `metadata.deletionTimestamp` set. A missing namespace object does not - match; or -2. the Device being deleted (`oldObject`) has `spec.lifecycle: Retired`. - -Every other `DELETE` is denied with reason `Forbidden` and a message to move -the Device to `Decommissioning`, then `Retired`, first. The policy uses + match; +2. the Device being deleted (`oldObject`) has `spec.lifecycle: Retired`; or +3. the request's `userInfo.username` is listed exactly in the + `cleanupUsernames` key of the binding's parameter ConfigMap. The policy's + `paramKind` is core `v1` `ConfigMap`. This exception is off as shipped; see + [Cleanup identity](#cleanup-identity). + +Every other `DELETE` is denied with reason `Forbidden` (HTTP 403). The message +lists the three ways a delete is allowed and says to move the Device to +`Decommissioning`, then `Retired`, first. The policy uses `failurePolicy: Fail` and the binding `validationActions: [Deny]`, so an evaluation error also denies. @@ -228,13 +235,22 @@ evaluation error also denies. Confirm this on the deployed Milo before relying on it. - **Validation.** `hack/validate-overlay-isolation.sh` renders the component on its own and fails unless it is exactly this policy: the same name, - expression, `failurePolicy: Fail`, `Deny` only, and no match conditions, - selectors, exclusions, variables or parameters. It also fails if any root in - this repository renders the policy, under its own name or another, and if - the inventory component exists without this component. -- **No exemptions.** The policy does not look at the request's user, group or - service account. Cluster administrators are held to the same rule. Anyone - able to delete the binding is outside the guarantee. + expression, a `paramKind` of exactly core `v1` `ConfigMap`, + `failurePolicy: Fail`, `Deny` only, no `paramRef` on the binding, and no + match conditions, selectors, exclusions or variables. Because the expression + is compared exactly, the validator rejects wildcard or prefix username + matching, a group-based exemption, a null `params` treated as allow-all, a + dropped empty-username guard and an always-true clause. It also rejects a + `paramRef` in the component, including one with + `parameterNotFoundAction: Allow`: deploying repositories add the `paramRef`. + It fails if any root in this repository renders the policy, under its own + name or another, and if the inventory component exists without this + component. +- **The cleanup identity is the only subject exemption.** Apart from exact + usernames in the deploying repository's ConfigMap, the policy does not look + at the request's user, group or service account. Cluster administrators are + held to the same rule. Anyone able to delete or edit the binding, or to write + the parameter ConfigMap, is outside the guarantee. - **deletecollection, garbage collection and finalizers.** The API server admits each object of a collection delete individually as a `DELETE`, so a collection delete that reaches a Device that is not Retired is denied and @@ -250,19 +266,108 @@ evaluation error also denies. identities leave the duplicate check. The policy reads the namespace from the API server's namespace cache, which observes the deletion mark shortly after it is set. -- **Project deletion.** In pinned Milo `v0.36.9`, project purge first issues a - collection delete for every namespaced resource in every namespace, and only +- **Project deletion.** In pinned Milo `v0.36.9`, project purge + (`internal/controllers/projectpurge`) first issues a collection delete for + every namespaced resource in every namespace, `default` included, and only then deletes the namespaces. It never deletes `default`, which it drains in - place. In that first phase no namespace is marked yet, so a Device that is - not Retired stops the purge's collection delete. Registered Devices live in - `default`, which is never marked. A project that holds Devices that are not - Retired therefore does not finish purging while the component is installed: - retire its Devices first. This is from reading the pinned Milo source, not a - live test. + place. In that first phase no namespace is marked yet, so the + deleting-namespace exception never applies, and a denied collection delete + aborts the purge before it deletes any namespace. The purge runs as the Milo + controller-manager's own identity against the project's control plane. + - With the [cleanup identity](#cleanup-identity) configured to list that + username, the purge's collection deletes are admitted whatever the + Devices' lifecycle, and project teardown completes. + - Without it, a project that holds a Device that is not Retired does not + finish purging while the component is installed. Retire every Device + first. + + This comes from reading the pinned Milo source and from the envtest + simulation below, not from a live Milo test. - **Capacity is not deleted with its Device.** The registration webhook denies capacity deletes, so a namespace or project teardown that removes Devices still stops at their capacity; see the next section. +### Cleanup identity + +The binding ships without a `paramRef`. The policy then evaluates with +`params == null`, the third exception is off, and only the namespace and +Retired exceptions apply. A policy that declares `paramKind` does not need a +`paramRef` on its binding: Kubernetes evaluates such a binding with a null +`params` and no error. The envtest suite confirms this on Kubernetes 1.37.0. + +A deploying repository turns the exception on in the root it applies to Milo: + +1. Add a ConfigMap with a `cleanupUsernames` key that lists the usernames, one + per line or separated by commas. Entries are trimmed and empty entries are + ignored. Matching is exact and case-sensitive. Groups, prefixes and + wildcards never match, and an empty username never matches. List only the + identity that runs project cleanup: in pinned Milo, the controller-manager's + base identity. +2. Patch the binding with a `paramRef` that names that ConfigMap, sets its + `namespace` explicitly, and sets `parameterNotFoundAction: Deny`. Without + an explicit namespace, the API server looks for the ConfigMap in the + Device's own namespace. + +A synthetic example, rendered with `kustomize build`: + +```yaml +# kustomization.yaml in the deploying repository's Milo root. The component +# path stands in for however that repository vendors or references Fleet. +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +components: + - ../fleet/config/components/device-deletion-protection +resources: + - device-cleanup-identity.yaml +patches: + - target: + group: admissionregistration.k8s.io + kind: ValidatingAdmissionPolicyBinding + name: fleet-device-deletion-protection + patch: |- + - op: add + path: /spec/paramRef + value: + name: fleet-device-cleanup + namespace: example-system + parameterNotFoundAction: Deny +--- +# device-cleanup-identity.yaml +apiVersion: v1 +kind: ConfigMap +metadata: + name: fleet-device-cleanup + namespace: example-system +data: + cleanupUsernames: | + system:serviceaccount:example-system:example-controller-manager +``` + +Consequences to plan for: + +- **A missing ConfigMap denies every Device delete.** With + `parameterNotFoundAction: Deny`, a `paramRef` whose ConfigMap does not exist + denies every Device `DELETE`. That includes a Retired Device, a Device in a + deleting namespace and the listed identity's deletes, so namespace and + project teardown stop until the ConfigMap exists. This is the fail-closed + behaviour: an absent or deleted ConfigMap never widens who may delete. The + API server reports it as `422 Invalid` with the message ``no params found + for policy binding with `Deny` parameterNotFoundAction``, not as the + policy's 403. Apply the ConfigMap with the patch, or before it. Never use + `parameterNotFoundAction: Allow`: a missing ConfigMap would then skip the + policy and admit every Device `DELETE`. +- **Impersonation grants the exemption.** Anyone allowed to impersonate a + listed username is admitted as that username and can delete any Device. + Ordinary RBAC on `impersonate` applies. List only the cleanup controller's + identity, and restrict impersonation of it, and writes to the ConfigMap and + the binding, as tightly as the controller itself. +- **Where the ConfigMap lives in Milo.** The admission plugin reads the + ConfigMap through its informers. In pinned Milo `v0.36.9` those informers + run against the root control plane, not a project, so the ConfigMap belongs + in the root. This is inferred from the Milo source, as is the policy's use of + Milo's root admission for project-routed requests. Confirm on the deployed + Milo that the cleanup identity admits a project purge before relying on it. + ### Deleting a Device Deleting a Device that backs capacity, whether it is Retired, its namespace is @@ -317,9 +422,12 @@ Environment-owned inputs, none of which this repository supplies: reachability, and set `clientConfig.caBundle` to the serving CA. 3. Keep `--provider-projects` equal to the complete provider scope. 4. Decide whether the Milo root you apply includes - `config/components/device-deletion-protection`. With it, only Retired - Devices and Devices in a deleting namespace can be deleted; without it, - any authorized caller can delete a Device. + `config/components/device-deletion-protection`. With it, the only Device + deletes admitted are of Retired Devices, of Devices in a deleting namespace, + and by a configured [cleanup identity](#cleanup-identity); without it, any + authorized caller can delete a Device. If you include it, configure the + cleanup identity, or project deletion stays blocked until every Device in + the project is Retired. 5. Before rolling out the UI, verify caller-preserving project routing, named Device read denial, registration denial, capacity mutation denial, TLS rejection, Device deletion denial where installed, lifecycle transitions, and duplicate handling @@ -383,11 +491,29 @@ its manifest and checks that: move out of `Retired`; - deleting an Active or Decommissioning Device is denied for every caller, and deleting a Retired Device is allowed; +- with the shipped binding, which has no `paramRef`, the policy evaluates with + a null `params` and no error, and a would-be cleanup username is denied; - `deletecollection` over mixed Devices denies those that are not Retired; - after the namespace is deleted, its Devices can be deleted. envtest has no namespace controller, so the test issues the controller's deletions itself and they are admitted because `namespaceObject` has a deletion timestamp; -- Devices in other namespaces stay protected. +- Devices in other namespaces stay protected; +- with the ConfigMap and a `paramRef` set as a deploying repository sets them, + a listed username deletes Active and Decommissioning Devices and a mixed + collection. The admin, an unlisted user, and usernames that are a prefix, + superset, embedding, suffix or different case of a listed name are denied, + as is a user who holds a listed name only as a group. The Retired and + deleting-namespace exceptions still admit unlisted callers; +- a Milo-style purge, the listed user's collection delete in `default` and in + another namespace with mixed lifecycles, removes every Device; +- a `paramRef` to a missing ConfigMap under `parameterNotFoundAction: Deny` + denies every delete with `422 Invalid`, including a Retired Device, the + listed user, a Device in a deleting namespace and the purge. + +`internal/registration/deletion_policy_test.go` evaluates the component's +expression offline with the API server's admission CEL compiler, for cases +envtest cannot produce, such as an empty username: it never matches empty +entries, and padded, CRLF-separated entries match only exactly. Unit tests cover the remaining negative cases, normalization, cross-project duplicates, project lifetime and the packaged webhook shape. @@ -396,7 +522,11 @@ transport. `internal/api/inventory/v1alpha1/lifecycle_test.go` runs the lifecycle default and transition rules through the CRD schema offline. The overlay isolation tests fail when a root includes the deletion component and when the component's policy is renamed, made audit-only, fail-open, scoped, -exempted or given a weaker expression. Frontend tests cover the derived name, +exempted or given a weaker expression. The weaker expressions include +wildcard, prefix, group-based, null-params-allows-all, empty-username and +always-true cleanup clauses. The tests also fail on a different or missing +`paramKind`, and on a `paramRef` in the component with either +`parameterNotFoundAction`. Frontend tests cover the derived name, conflict marking including Retired Devices, and refusal of Devices that are not Active, with mocked transport. None of this is a live Milo deployment or an independent security review. diff --git a/docs/operations/physical-inventory.md b/docs/operations/physical-inventory.md index 79234491..9b172c73 100644 --- a/docs/operations/physical-inventory.md +++ b/docs/operations/physical-inventory.md @@ -335,7 +335,12 @@ that names the same claim. Leave the old Device in place and move its Retired is terminal and still counts in the duplicate-identity check while the Device exists. Environments with [Device deletion protection](../development/inventory-capacity-registration.md#device-deletion-protection) -delete a Device only once it is Retired, or with its namespace. +delete a Device only once it is Retired, or with its namespace. The one other +path is project teardown: when the deploying repository configures the +[cleanup identity](../development/inventory-capacity-registration.md#cleanup-identity), +that identity, and anyone allowed to impersonate it, can delete Devices +whatever their lifecycle, so a project purge completes. Without it, a project +that holds a Device that is not Retired cannot finish deleting. ## Relationship to the inventory proposal From 06be8efd6f396f73c4b6d9b3b17c6c89ecf3eca4 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sun, 22 Nov 2026 17:59:41 -0600 Subject: [PATCH 083/518] docs: note Milo should purge namespaces first Mark the cleanup identity exemption as a stopgap. Once Milo marks each namespace it purges, default included, before deleting its contents, the deletion policy can rely on the namespace signal alone. Co-Authored-By: Claude Opus 5.5 --- config/components/device-deletion-protection/policy.yaml | 7 +++++++ docs/development/inventory-capacity-registration.md | 7 +++++++ 2 files changed, 14 insertions(+) diff --git a/config/components/device-deletion-protection/policy.yaml b/config/components/device-deletion-protection/policy.yaml index 870d7fa6..7f96fa87 100644 --- a/config/components/device-deletion-protection/policy.yaml +++ b/config/components/device-deletion-protection/policy.yaml @@ -17,6 +17,13 @@ # and an empty username never match. Groups, prefixes and wildcards are not # consulted. # +# Exception 3 is a stopgap. Milo's project cleanup deletes namespaced +# resources before it marks any namespace for deletion, and it never deletes +# `default`, so exception 1 cannot cover project teardown today. Milo should +# mark every namespace it purges, `default` included, before deleting its +# contents. This policy can then rely on that namespace signal and drop the +# subject exemption. +# # The binding below has no paramRef, so params is null and exception 3 is off. # A deploying repository turns it on by adding the ConfigMap and patching the # binding with a paramRef that sets parameterNotFoundAction: Deny; a missing diff --git a/docs/development/inventory-capacity-registration.md b/docs/development/inventory-capacity-registration.md index e5808df2..adda25c1 100644 --- a/docs/development/inventory-capacity-registration.md +++ b/docs/development/inventory-capacity-registration.md @@ -289,6 +289,13 @@ evaluation error also denies. ### Cleanup identity +The cleanup identity is a stopgap. Milo's project cleanup deletes namespaced +resources before it marks any namespace for deletion, and it never deletes +`default`, so the namespace exception cannot cover project teardown. Milo +should mark every namespace it purges, `default` included, before deleting +its contents. The policy can then rely on that namespace signal and drop the +subject exemption. + The binding ships without a `paramRef`. The policy then evaluates with `params == null`, the third exception is off, and only the namespace and Retired exceptions apply. A policy that declares `paramKind` does not need a From b3dc951361708c5728c51ca556b84ac5b0e4facc Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sun, 22 Nov 2026 18:18:55 -0600 Subject: [PATCH 084/518] Scope registration webhook to marked capacity The capacity registration webhook matched every MachineCapacity create, update and delete, and every status write, in every namespace, and denied all but gated creates. That blocked synthetic capacity a GitOps controller re-applies, a synthetic provider's status writes, and hand-made capacity. The webhook now governs only inventory-backed capacity: capacity carrying a fleet.datumapis.com/registration-* annotation on the new or old object, or a create under the derived device- name. A match condition routes only those requests, so adding, changing or removing the marker is still denied. Status writes are no longer routed; the status subresource cannot change metadata or spec, so they cannot strip the marker or enable capacity. The handler allows unmarked requests without reading Devices. failurePolicy Fail, sideEffects None and the timeout are unchanged. Co-Authored-By: Claude Opus 5.5 --- .../registration-admission/webhook.yaml | 21 +- docs/development/README.md | 4 +- .../inventory-capacity-registration.md | 134 +++++++++++-- internal/registration/admission.go | 64 ++++++- internal/registration/envtest_test.go | 3 +- internal/registration/manifest_test.go | 42 +++- internal/registration/scope_envtest_test.go | 180 ++++++++++++++++++ internal/registration/scope_test.go | 114 +++++++++++ 8 files changed, 533 insertions(+), 29 deletions(-) create mode 100644 internal/registration/scope_envtest_test.go create mode 100644 internal/registration/scope_test.go diff --git a/config/components/registration-admission/webhook.yaml b/config/components/registration-admission/webhook.yaml index b75500a9..ae5a2a30 100644 --- a/config/components/registration-admission/webhook.yaml +++ b/config/components/registration-admission/webhook.yaml @@ -3,8 +3,14 @@ kind: ValidatingWebhookConfiguration metadata: name: fleet-capacity-registration webhooks: - # Every capacity write is fail-closed. Creates are checked against live - # Devices; updates, status writes and deletes are always denied. + # Only inventory-backed capacity is routed here, and it is fail-closed. + # Creates are checked against live Devices; updates and deletes are always + # denied. Capacity is inventory-backed when it carries a registration + # annotation (fleet.datumapis.com/registration-*) on the new or old object, + # or when a create uses the derived device- name. Adding, changing or + # removing a registration annotation is therefore always routed. Capacity + # without the marker, such as synthetic or hand-made capacity, and every + # status write are not routed and are governed by RBAC alone. - name: registration.fleet.datumapis.com admissionReviewVersions: [v1] failurePolicy: Fail @@ -17,5 +23,14 @@ webhooks: - apiGroups: [metal.datumapis.com] apiVersions: [v1alpha1] operations: [CREATE, UPDATE, DELETE] - resources: [machinecapacities, machinecapacities/status] + resources: [machinecapacities] scope: Namespaced + matchConditions: + - name: inventory-backed-capacity + expression: >- + (request.operation == 'CREATE' && object != null + && has(object.metadata.name) && object.metadata.name.startsWith('device-')) + || (object != null && has(object.metadata.annotations) + && object.metadata.annotations.exists(key, key.startsWith('fleet.datumapis.com/registration-'))) + || (oldObject != null && has(oldObject.metadata.annotations) + && oldObject.metadata.annotations.exists(key, key.startsWith('fleet.datumapis.com/registration-'))) diff --git a/docs/development/README.md b/docs/development/README.md index 364bf6c8..f3c19b7d 100644 --- a/docs/development/README.md +++ b/docs/development/README.md @@ -25,7 +25,9 @@ Devices, one capacity per Device through a Device-derived name, a Device lifecycle (`Active`, `Decommissioning`, terminal `Retired`), an opt-in Device deletion protection component that admits deletes only for Retired Devices or a deleting namespace, and a session-fenced default-namespace Device picker. It admits only Disabled/Retain records with cleaning explicitly -unconfigured; deployment trust inputs and live Milo acceptance remain required. +unconfigured, and governs only capacity that carries the registration marker; +synthetic, hand-made and legacy capacity and all capacity status writes are not +routed to it. Deployment trust inputs and live Milo acceptance remain required. An opt-in [local KVM installation harness](../operations/local-vm.md) implements a bounded libvirt executor and guest installer using the same lifecycle library. It uses a disposable Kubernetes API and explicit local authority fixtures; it is diff --git a/docs/development/inventory-capacity-registration.md b/docs/development/inventory-capacity-registration.md index adda25c1..c07d418c 100644 --- a/docs/development/inventory-capacity-registration.md +++ b/docs/development/inventory-capacity-registration.md @@ -73,14 +73,16 @@ operation ID is no longer used for deduplication. An empty cleaning-policy name explicitly means **unconfigured**, not a policy named `default`, synthetic cleaning, or authorization to prepare. The CRD -permits it only while Disabled. The webhook rejects *all* capacity updates, -status updates and deletes. An update that would move capacity out of +permits it only while Disabled. The webhook rejects every update and delete +of [inventory-backed capacity](#scope-inventory-backed-capacity-only). An +update that would move capacity out of `Disabled` while its Device is `Decommissioning` or `Retired` is denied for that reason; the webhook first checks that the caller can read the Device. Real policy resolution and policy-use authorization are future prerequisites for a separately designed transition; there is no stage-1 preparation endpoint. -`cmd/fleet-registration` serves the validating webhook. For each create it: +`cmd/fleet-registration` serves the validating webhook. For each create of +inventory-backed capacity it: 1. requires Milo's authenticated `iam.miloapis.com/parent-*` extras naming a single Project in the configured provider scope, and an actor UID; @@ -106,6 +108,84 @@ stage-1 preparation endpoint. established; or - any capacity is backed by a Device that shares an alias. +## Scope: inventory-backed capacity only + +The webhook governs only **inventory-backed** capacity, meaning capacity that +registration creates from a Device. Other capacity, such as synthetic +capacity that a GitOps controller applies, capacity whose status a synthetic +provider writes, and hand-made capacity, is not routed to it at all. + +The marker is registration's own metadata: + +- any annotation whose key starts with `fleet.datumapis.com/registration-` + (the three annotations above), on the new or the old object; or +- on create only, a name starting with `device-`, the derived name. + +The marker is reliable because the webhook admits no create of +inventory-backed capacity without all three annotations and the derived +name, and admits no later update or delete of it, so the annotations cannot +be removed or changed after creation. A label was not used: registration +sets none, adding one would change the portal's wire contract, and a match +condition can read annotations directly. The name is part of the marker only +on create, so that the derived name space is reserved for registration and +no unannotated create can occupy a Device's derived name. Capacity is not +renamed, so the annotations alone identify it afterwards. + +The packaged webhook routes requests with one rule and one match condition: + +```yaml +rules: + - apiGroups: [metal.datumapis.com] + apiVersions: [v1alpha1] + operations: [CREATE, UPDATE, DELETE] + resources: [machinecapacities] + scope: Namespaced +matchConditions: + - name: inventory-backed-capacity + expression: >- + (request.operation == 'CREATE' && object != null + && has(object.metadata.name) && object.metadata.name.startsWith('device-')) + || (object != null && has(object.metadata.annotations) + && object.metadata.annotations.exists(key, key.startsWith('fleet.datumapis.com/registration-'))) + || (oldObject != null && has(oldObject.metadata.annotations) + && oldObject.metadata.annotations.exists(key, key.startsWith('fleet.datumapis.com/registration-'))) +``` + +`object` is null for a delete and `oldObject` is null for a create. Checking +both objects routes, and so denies, an update that adds a registration +annotation to unmarked capacity, which would make it look inventory-backed, +and an update or delete that removes or changes the annotation on marked +capacity, which would let it escape the gate. `failurePolicy: Fail` applies +to a match condition that fails to evaluate. + +The handler applies the same test as defence in depth: a request for capacity +without the marker that reaches it anyway is allowed without reading Devices +or the provider project. A marked request is handled as before: creates are +gated in full, and updates, deletes and any routed subresource are denied. + +**Status writes are not routed.** `machinecapacities/status` is not in the +rule. Stage 1 has no status writer for inventory-backed capacity, but a +provider may need one later, and the webhook would then have to be changed +first. Status writes are governed by RBAC alone; in the packaged IAM roles +only the controller role holds `machinecapacities.updateStatus`. This is +acceptable because a status write cannot widen what capacity offers: + +- the CRD's status subresource ignores changes to `metadata` and `spec`, so a + status write cannot strip the marker or move capacity out of `Disabled`; +- allocation requires `spec.allocationPolicy: Enabled`, which status cannot + set. + +The envtest suite confirms the first point on Kubernetes 1.37.0. A future +stage that lets status influence availability must revisit this. + +**Unmarked capacity is not gated.** Capacity without the marker, including +legacy capacity created before registration admission, can again be created, +updated and deleted by any caller RBAC allows, with no Device check and no +Disabled requirement. It is not inventory-backed and makes no claim about a +Device. Registration still reads it: a create of inventory-backed capacity is +denied while any capacity in the provider scope references the Device, or has +unresolved physical identity. + The webhook writes nothing. Dry-run requests are evaluated like real ones (`sideEffects: None`). Controller credentials supply reads and SAR evaluation, not the caller's registration authority. Errors about records in another @@ -150,8 +230,8 @@ The duplicate check is a point-in-time list. It does not close this race: No reservation store closes this, by decision. The consequences are bounded: - B can never be registered, because A now exists and shares its alias. -- A's capacity is `Disabled`, and the webhook denies every capacity update, so - it can never become available in stage 1. +- A's capacity is `Disabled`, and the webhook denies every update of + inventory-backed capacity, so it can never become available in stage 1. - The staff registration form lists every Device and marks each one that shares an alias with another as **Conflicting**, so both A and B show the conflict until a person resolves it. @@ -193,8 +273,8 @@ Registration semantics, enforced by the registration webhook: - Only an `Active` Device can get new capacity. - Capacity whose Device is `Decommissioning` or `Retired` cannot leave - `Disabled`. Stage 1 already denies every capacity update, so this states the - rule a future enabling transition must keep. + `Disabled`. Stage 1 already denies every update of inventory-backed + capacity, so this states the rule a future enabling transition must keep. - A Retired Device still takes part in the duplicate-identity check for as long as it exists. Deleting it removes its identity from that check. @@ -284,7 +364,7 @@ evaluation error also denies. This comes from reading the pinned Milo source and from the envtest simulation below, not from a live Milo test. - **Capacity is not deleted with its Device.** The registration webhook denies - capacity deletes, so a namespace or project teardown that removes Devices + deletes of inventory-backed capacity, so a namespace or project teardown that removes Devices still stops at their capacity; see the next section. ### Cleanup identity @@ -382,18 +462,20 @@ being deleted, or the component is not installed, leaves the capacity in place, still `Disabled`. The webhook denies every update and delete of it, so it cannot become available. No owner reference links the two: the webhook rejects owner references on registration, and garbage collection would be -denied anyway because capacity deletes are fenced. The orphaned capacity keeps +denied anyway because deletes of inventory-backed capacity are fenced. The orphaned capacity keeps its Device UID annotation and name, which also prevents a replacement Device with the same name from registering. Clean it up only in environments where -capacity writes are not fenced, such as synthetic ones. +the registration webhook is not installed, such as synthetic ones. ## Production packaging and rollout - `config/milo` includes the mandatory fail-closed registration webhook (`config/components/registration-admission`). Its one entry matches - capacity create/update/delete and status in every namespace, with no - selectors or match conditions. An unreachable service blocks capacity - writes globally and nothing else: Device, namespace and Project writes do + capacity create, update and delete in every namespace, narrowed by the + [inventory-backed match condition](#scope-inventory-backed-capacity-only) + and with no selectors. Status writes are not matched. An unreachable + service blocks writes to inventory-backed capacity and nothing else: + unmarked capacity, capacity status, Device, namespace and Project writes do not pass through the registration webhook. - No root in this repository includes Device deletion protection. A deploying repository adds `config/components/device-deletion-protection` to @@ -413,8 +495,9 @@ capacity writes are not fenced, such as synthetic ones. actor identity is preserved, and that nested Organization/User contexts do not present as a Project. Only a singleton `Project`/`resourcemanager.miloapis.com` context is accepted. -- Legacy capacity writes fail closed; legacy records remain readable and - unchanged. +- Writes to inventory-backed capacity fail closed. Legacy and other unmarked + capacity is not governed by the webhook; its writes are subject to RBAC + alone. Environment-owned inputs, none of which this repository supplies: @@ -488,7 +571,22 @@ packaged webhook against a real API server and checks that: - a Decommissioning or Retired Device cannot be registered, a Retired Device still blocks a duplicate, and capacity cannot leave `Disabled` once its Device is Decommissioning or Retired; -- a webhook outage blocks capacity writes but not Device writes. +- a webhook outage blocks capacity registration but not Device writes. + +`internal/registration/scope_envtest_test.go` installs the same packaged +webhook and checks that: + +- updates and deletes of registered capacity are denied, including by the + admin; +- removing all or one registration annotation, or changing one, is denied by + update and by merge patch, and adding one to unmarked capacity is denied; +- an unannotated create under a `device-` name is denied; +- with the webhook backend closed, a synthetic capacity's server-side-apply + create and spec update, its status write, and the update and delete of + hand-made capacity in `default` all succeed, so they are not routed; +- with the backend closed, a status write on registered capacity succeeds but + leaves its annotations and spec unchanged, while its update and delete, and + adding the marker to unmarked capacity, fail closed. `internal/registration/deletion_envtest_test.go` applies the component from its manifest and checks that: @@ -522,7 +620,9 @@ expression offline with the API server's admission CEL compiler, for cases envtest cannot produce, such as an empty username: it never matches empty entries, and padded, CRLF-separated entries match only exactly. -Unit tests cover the remaining negative cases, normalization, cross-project +Unit tests cover the remaining negative cases, the handler's own scope test +(unmarked create, update, status and delete are allowed without reading +Devices; marker additions, removals and changes are denied), normalization, cross-project duplicates, project lifetime and the packaged webhook shape. `cmd/fleet-registration` tests reject unauthenticated and untrusted webhook transport. `internal/api/inventory/v1alpha1/lifecycle_test.go` runs the diff --git a/internal/registration/admission.go b/internal/registration/admission.go index 526cdf25..3accfd7b 100644 --- a/internal/registration/admission.go +++ b/internal/registration/admission.go @@ -1,5 +1,10 @@ // Package registration admits inert, inventory-backed MachineCapacity records. // +// Only inventory-backed capacity is governed: capacity that carries a +// registration annotation, or a create under the derived device- name. +// Other capacity, such as synthetic or hand-made capacity, is allowed without +// reading Devices, and the packaged webhook does not route it at all. +// // The webhook keeps no state of its own. Every decision is made against live // Devices and capacities in the configured provider projects, so the API // server remains the only store. One capacity per Device is enforced by the @@ -26,6 +31,7 @@ import ( admissionv1 "k8s.io/api/admission/v1" authenticationv1 "k8s.io/api/authentication/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/webhook/admission" @@ -36,6 +42,11 @@ const ( DeviceVersionAnnotation = "fleet.datumapis.com/registration-device-version" OperationAnnotation = "fleet.datumapis.com/registration-operation" + // RegistrationAnnotationPrefix starts every annotation registration sets. + // Any annotation with this prefix marks capacity as inventory-backed, so + // adding, changing or removing one is always gated. + RegistrationAnnotationPrefix = "fleet.datumapis.com/registration-" + // CapacityNamePrefix starts every registered capacity name. The rest of // the name is the backing Device's UID. CapacityNamePrefix = "device-" @@ -111,6 +122,14 @@ func (handler *Handler) Handle(ctx context.Context, request admission.Request) a if request.Resource.Group != metal.GroupVersion.Group || request.Resource.Resource != "machinecapacities" { return admission.Denied("unsupported registration admission resource") } + backed, err := inventoryBacked(request) + if err != nil { + return admission.Denied("capacity could not be decoded: " + err.Error()) + } + if !backed { + // Defence in depth: the packaged webhook does not route this request. + return admission.Allowed("capacity is not inventory-backed; registration admission does not govern it") + } if request.SubResource != "" || (request.Operation != admissionv1.Create && request.Operation != admissionv1.Update) { return admission.Denied(mutationDisabled) } @@ -130,7 +149,50 @@ func (handler *Handler) Handle(ctx context.Context, request admission.Request) a return admission.Allowed("inert inventory registration only; no availability or preparation authority") } -const mutationDisabled = "capacity mutation and deletion are disabled; registered and legacy capacity require operator reconciliation" +// inventoryBacked reports whether a request concerns inventory-backed +// capacity. It matches the packaged webhook's match condition: a create +// under the derived name, or a registration annotation on the new or the old +// object. Checking both objects means an update that adds the marker, and an +// update or delete that removes or changes it, are both governed. +func inventoryBacked(request admission.Request) (bool, error) { + newObject, err := registrationMetadata(request.Object.Raw) + if err != nil { + return false, err + } + oldObject, err := registrationMetadata(request.OldObject.Raw) + if err != nil { + return false, err + } + if request.Operation == admissionv1.Create && (strings.HasPrefix(request.Name, CapacityNamePrefix) || (newObject != nil && strings.HasPrefix(newObject.Name, CapacityNamePrefix))) { + return true, nil + } + return marked(newObject) || marked(oldObject), nil +} + +func registrationMetadata(raw []byte) (*metav1.PartialObjectMetadata, error) { + if len(raw) == 0 { + return nil, nil + } + object := &metav1.PartialObjectMetadata{} + if err := json.Unmarshal(raw, object); err != nil { + return nil, err + } + return object, nil +} + +func marked(object *metav1.PartialObjectMetadata) bool { + if object == nil { + return false + } + for key := range object.Annotations { + if strings.HasPrefix(key, RegistrationAnnotationPrefix) { + return true + } + } + return false +} + +const mutationDisabled = "capacity mutation and deletion are disabled for inventory-backed capacity; registration annotations cannot be added, changed or removed" // evaluateUpdate explains why a capacity update is denied. Stage 1 denies // every update. An update that would move capacity out of Disabled for a diff --git a/internal/registration/envtest_test.go b/internal/registration/envtest_test.go index 734161ed..ed002f52 100644 --- a/internal/registration/envtest_test.go +++ b/internal/registration/envtest_test.go @@ -140,7 +140,8 @@ func (api *liveAPI) installWebhook() *httptest.Server { } operator := api.actor("operator", "system:masters") api.eventually("registration webhook", func() bool { - probe := &metal.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: "webhook-probe", Namespace: "default"}, Spec: metal.MachineCapacitySpec{DeviceRef: metal.LocalReference{Name: "absent"}, AllocationPolicy: "Disabled", ReclaimPolicy: "Retain"}} + // Only marked capacity is routed, so the probe carries the marker. + probe := &metal.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: CapacityName("webhook-probe"), Namespace: "default", Annotations: map[string]string{DeviceUIDAnnotation: "webhook-probe", DeviceVersionAnnotation: "1", OperationAnnotation: "webhook-probe"}}, Spec: metal.MachineCapacitySpec{DeviceRef: metal.LocalReference{Name: "absent"}, AllocationPolicy: "Disabled", ReclaimPolicy: "Retain"}} return apierrors.IsForbidden(operator.Create(context.Background(), probe, client.DryRunAll)) }) return server diff --git a/internal/registration/manifest_test.go b/internal/registration/manifest_test.go index 8c981b23..5bd181e2 100644 --- a/internal/registration/manifest_test.go +++ b/internal/registration/manifest_test.go @@ -3,15 +3,28 @@ package registration import ( "os" "slices" + "strings" "testing" admissionregistrationv1 "k8s.io/api/admissionregistration/v1" "sigs.k8s.io/yaml" ) -// The packaged webhook is the only gate on capacity writes, so it must stay -// fail-closed over every capacity write and must not reach anything else. -func TestPackagedWebhookFencesOnlyCapacityWrites(t *testing.T) { +// inventoryBackedCondition is the packaged webhook's only match condition. It +// routes a create under the derived name and any request whose new or old +// object carries a registration annotation, so adding, changing or removing +// the marker is always gated. +const inventoryBackedCondition = "(request.operation == 'CREATE' && object != null" + + " && has(object.metadata.name) && object.metadata.name.startsWith('device-'))" + + " || (object != null && has(object.metadata.annotations)" + + " && object.metadata.annotations.exists(key, key.startsWith('fleet.datumapis.com/registration-')))" + + " || (oldObject != null && has(oldObject.metadata.annotations)" + + " && oldObject.metadata.annotations.exists(key, key.startsWith('fleet.datumapis.com/registration-')))" + +// The packaged webhook is fail-closed over writes to inventory-backed +// capacity only. It must not route status writes, other capacity or any +// other resource. +func TestPackagedWebhookFencesOnlyInventoryBackedCapacity(t *testing.T) { data, err := os.ReadFile("../../config/components/registration-admission/webhook.yaml") if err != nil { t.Fatal(err) @@ -27,14 +40,31 @@ func TestPackagedWebhookFencesOnlyCapacityWrites(t *testing.T) { if webhook.FailurePolicy == nil || *webhook.FailurePolicy != admissionregistrationv1.Fail || webhook.SideEffects == nil || *webhook.SideEffects != admissionregistrationv1.SideEffectClassNone || webhook.MatchPolicy == nil || *webhook.MatchPolicy != admissionregistrationv1.Equivalent { t.Fatal("capacity webhook must fail closed, be side-effect free and match equivalent versions") } - if webhook.NamespaceSelector != nil || webhook.ObjectSelector != nil || len(webhook.MatchConditions) != 0 { - t.Fatal("capacity webhook must not be narrowed by selectors or conditions") + if webhook.TimeoutSeconds == nil || *webhook.TimeoutSeconds != 20 { + t.Fatal("capacity webhook timeout drifted") + } + if webhook.NamespaceSelector != nil || webhook.ObjectSelector != nil { + t.Fatal("capacity webhook must not be narrowed by selectors") + } + if len(webhook.MatchConditions) != 1 || webhook.MatchConditions[0].Name != "inventory-backed-capacity" || webhook.MatchConditions[0].Expression != inventoryBackedCondition { + t.Fatalf("capacity webhook match conditions drifted: %+v", webhook.MatchConditions) } if len(webhook.Rules) != 1 { t.Fatal("capacity webhook must have exactly one rule") } rule := webhook.Rules[0] - if !slices.Equal(rule.APIGroups, []string{"metal.datumapis.com"}) || !slices.Equal(rule.Resources, []string{"machinecapacities", "machinecapacities/status"}) || !slices.Equal(rule.Operations, []admissionregistrationv1.OperationType{admissionregistrationv1.Create, admissionregistrationv1.Update, admissionregistrationv1.Delete}) { + if !slices.Equal(rule.APIGroups, []string{"metal.datumapis.com"}) || !slices.Equal(rule.APIVersions, []string{"v1alpha1"}) || !slices.Equal(rule.Resources, []string{"machinecapacities"}) || !slices.Equal(rule.Operations, []admissionregistrationv1.OperationType{admissionregistrationv1.Create, admissionregistrationv1.Update, admissionregistrationv1.Delete}) || rule.Scope == nil || *rule.Scope != admissionregistrationv1.NamespacedScope { t.Fatalf("capacity webhook rule drifted: %+v", rule) } + // The condition's literals must stay in step with the handler's marker. + for _, literal := range []string{"'" + CapacityNamePrefix + "'", "'" + RegistrationAnnotationPrefix + "'"} { + if !strings.Contains(inventoryBackedCondition, literal) { + t.Fatalf("match condition does not use the handler's marker %s", literal) + } + } + for _, annotation := range []string{DeviceUIDAnnotation, DeviceVersionAnnotation, OperationAnnotation} { + if !strings.HasPrefix(annotation, RegistrationAnnotationPrefix) { + t.Fatalf("registration annotation %s is outside the marker prefix", annotation) + } + } } diff --git a/internal/registration/scope_envtest_test.go b/internal/registration/scope_envtest_test.go new file mode 100644 index 00000000..57ac1ed5 --- /dev/null +++ b/internal/registration/scope_envtest_test.go @@ -0,0 +1,180 @@ +package registration + +import ( + "context" + "testing" + + metal "go.datum.net/fleet/internal/api/v1alpha1" + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "sigs.k8s.io/controller-runtime/pkg/client" +) + +// syntheticCapacity is a non-inventory capacity as a GitOps controller +// applies it with server-side apply. +func syntheticCapacity(policy, cleaning string) *unstructured.Unstructured { + return &unstructured.Unstructured{Object: map[string]any{ + "apiVersion": "metal.datumapis.com/v1alpha1", + "kind": "MachineCapacity", + "metadata": map[string]any{ + "name": "synthetic-01", + "namespace": "synthetic-provider", + "labels": map[string]any{"fleet.datumapis.com/capacity-pool": "synthetic"}, + }, + "spec": map[string]any{ + "deviceRef": map[string]any{"name": "synthetic-device-01"}, + "allocationPolicy": policy, + "cleaningPolicyRef": map[string]any{"name": cleaning}, + "reclaimPolicy": "Retain", + }, + }} +} + +// TestWebhookGovernsOnlyInventoryBackedCapacity runs the packaged webhook +// configuration against a real API server. Capacity without the registration +// marker is never routed, so its writes succeed even with the backend gone. +// Marked capacity stays fenced, and the marker cannot be added, changed or +// removed. +func TestWebhookGovernsOnlyInventoryBackedCapacity(t *testing.T) { + api := startAPI(t) + ctx := context.Background() + if err := api.admin.Create(ctx, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "synthetic-provider"}}); err != nil { + t.Fatal(err) + } + device := api.device("scoped", "default", "scoped-serial", "77777777-7777-7777-7777-777777777771") + webhook := api.installWebhook() + operator := api.actor("operator", "system:masters") + + registered := api.registration(device) + if err := operator.Create(ctx, registered); err != nil { + t.Fatalf("eligible registration denied: %v", err) + } + current := func() *metal.MachineCapacity { + t.Helper() + capacity := &metal.MachineCapacity{} + if err := api.admin.Get(ctx, client.ObjectKeyFromObject(registered), capacity); err != nil { + t.Fatal(err) + } + return capacity + } + + // Hand-made capacity in the inventory namespace, created while the + // webhook is serving. + handMade := &metal.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: "hand-made", Namespace: "default"}, Spec: metal.MachineCapacitySpec{DeviceRef: metal.LocalReference{Name: device.Name}, AllocationPolicy: "Disabled", ReclaimPolicy: "Retain"}} + if err := operator.Create(ctx, handMade); err != nil { + t.Fatalf("hand-made capacity denied: %v", err) + } + + t.Run("marked capacity cannot be updated or deleted", func(t *testing.T) { + capacity := current() + capacity.Labels = map[string]string{"edited": "true"} + requireDenied(t, operator.Update(ctx, capacity), "mutation and deletion are disabled") + requireDenied(t, operator.Delete(ctx, current()), "mutation and deletion are disabled") + requireDenied(t, api.admin.Delete(ctx, current()), "mutation and deletion are disabled") + }) + t.Run("the marker cannot be removed or changed", func(t *testing.T) { + stripped := current() + stripped.Annotations = nil + requireDenied(t, operator.Update(ctx, stripped), "mutation and deletion are disabled") + partial := current() + delete(partial.Annotations, DeviceUIDAnnotation) + requireDenied(t, operator.Update(ctx, partial), "mutation and deletion are disabled") + changed := current() + changed.Annotations[DeviceUIDAnnotation] = "another-device" + requireDenied(t, operator.Update(ctx, changed), "mutation and deletion are disabled") + patch := client.RawPatch("application/merge-patch+json", []byte(`{"metadata":{"annotations":{"`+DeviceUIDAnnotation+`":null,"`+DeviceVersionAnnotation+`":null,"`+OperationAnnotation+`":null}}}`)) + requireDenied(t, operator.Patch(ctx, current(), patch), "mutation and deletion are disabled") + if annotations := current().Annotations; annotations[DeviceUIDAnnotation] != string(device.UID) || len(annotations) != 3 { + t.Fatalf("marker changed: %v", annotations) + } + }) + t.Run("the marker cannot be added to unmarked capacity", func(t *testing.T) { + adopted := &metal.MachineCapacity{} + if err := api.admin.Get(ctx, client.ObjectKeyFromObject(handMade), adopted); err != nil { + t.Fatal(err) + } + adopted.Annotations = map[string]string{DeviceUIDAnnotation: string(device.UID)} + requireDenied(t, operator.Update(ctx, adopted), "mutation and deletion are disabled") + patch := client.RawPatch("application/merge-patch+json", []byte(`{"metadata":{"annotations":{"`+OperationAnnotation+`":"adopt"}}}`)) + requireDenied(t, operator.Patch(ctx, handMade, patch), "mutation and deletion are disabled") + }) + t.Run("an unmarked create under the derived name is gated", func(t *testing.T) { + squatter := &metal.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: CapacityName("77777777-0000-0000-0000-000000000000"), Namespace: "default"}, Spec: metal.MachineCapacitySpec{DeviceRef: metal.LocalReference{Name: "squatted"}, AllocationPolicy: "Disabled", ReclaimPolicy: "Retain"}} + requireDenied(t, operator.Create(ctx, squatter), "exact Device UID/resourceVersion") + }) + + // From here on the backend is unreachable. Only routed requests fail. + webhook.Close() + + t.Run("unmarked capacity is not routed", func(t *testing.T) { + owner := []client.ApplyOption{client.FieldOwner("synthetic-gitops"), client.ForceOwnership} + if err := api.admin.Apply(ctx, client.ApplyConfigurationFromUnstructured(syntheticCapacity("Enabled", "synthetic-tenant-reuse-v1")), owner...); err != nil { + t.Fatalf("synthetic create by apply: %v", err) + } + if err := api.admin.Apply(ctx, client.ApplyConfigurationFromUnstructured(syntheticCapacity("Disabled", "synthetic-tenant-reuse-v2")), owner...); err != nil { + t.Fatalf("synthetic spec update by apply: %v", err) + } + synthetic := &metal.MachineCapacity{} + if err := api.admin.Get(ctx, client.ObjectKey{Namespace: "synthetic-provider", Name: "synthetic-01"}, synthetic); err != nil { + t.Fatal(err) + } + if synthetic.Spec.AllocationPolicy != "Disabled" || synthetic.Spec.CleaningPolicyRef.Name != "synthetic-tenant-reuse-v2" { + t.Fatalf("synthetic apply did not persist: %+v", synthetic.Spec) + } + synthetic.Status.Conditions = []metav1.Condition{{Type: "Available", Status: metav1.ConditionTrue, Reason: "SyntheticProvider", LastTransitionTime: metav1.Now()}} + if err := api.admin.Status().Update(ctx, synthetic); err != nil { + t.Fatalf("synthetic provider status write: %v", err) + } + if err := api.admin.Get(ctx, client.ObjectKeyFromObject(handMade), handMade); err != nil { + t.Fatal(err) + } + handMade.Labels = map[string]string{"edited": "true"} + if err := operator.Update(ctx, handMade); err != nil { + t.Fatalf("hand-made capacity update: %v", err) + } + for _, capacity := range []client.Object{synthetic, handMade} { + if err := api.admin.Delete(ctx, capacity); err != nil { + t.Fatalf("unmarked capacity delete: %v", err) + } + if api.exists(capacity) { + t.Fatal("unmarked capacity survived deletion") + } + } + }) + t.Run("marked capacity status writes are not routed", func(t *testing.T) { + // Status is governed by RBAC alone. The status subresource cannot + // change metadata, so it cannot strip the marker or touch spec. + capacity := current() + capacity.Annotations = nil + capacity.Spec.AllocationPolicy = "Enabled" + capacity.Spec.CleaningPolicyRef.Name = "invented-policy" + capacity.Status.Conditions = []metav1.Condition{{Type: "Observed", Status: metav1.ConditionUnknown, Reason: "Synthetic", LastTransitionTime: metav1.Now()}} + if err := api.admin.Status().Update(ctx, capacity); err != nil { + t.Fatalf("status write on marked capacity: %v", err) + } + after := current() + if len(after.Annotations) != 3 || after.Annotations[DeviceUIDAnnotation] != string(device.UID) || after.Spec.AllocationPolicy != "Disabled" || after.Spec.CleaningPolicyRef.Name != "" || len(after.Status.Conditions) != 1 { + t.Fatalf("status write changed more than status: %+v %+v", after.Annotations, after.Spec) + } + }) + t.Run("marked capacity writes fail closed without the backend", func(t *testing.T) { + capacity := current() + capacity.Labels = map[string]string{"edited": "true"} + if err := operator.Update(ctx, capacity); err == nil { + t.Fatal("marked capacity updated without the webhook") + } + if err := api.admin.Delete(ctx, current()); err == nil { + t.Fatal("marked capacity deleted without the webhook") + } + unmarked := &metal.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: "late-hand-made", Namespace: "default"}, Spec: metal.MachineCapacitySpec{DeviceRef: metal.LocalReference{Name: "late"}, AllocationPolicy: "Disabled", ReclaimPolicy: "Retain"}} + if err := api.admin.Create(ctx, unmarked); err != nil { + t.Fatalf("unmarked create without the webhook: %v", err) + } + unmarked.Annotations = map[string]string{DeviceUIDAnnotation: "adopted"} + if err := api.admin.Update(ctx, unmarked); err == nil || apierrors.IsConflict(err) { + t.Fatalf("marker added without the webhook: %v", err) + } + }) +} diff --git a/internal/registration/scope_test.go b/internal/registration/scope_test.go new file mode 100644 index 00000000..3d568722 --- /dev/null +++ b/internal/registration/scope_test.go @@ -0,0 +1,114 @@ +package registration + +import ( + "context" + "encoding/json" + "errors" + "testing" + + metal "go.datum.net/fleet/internal/api/v1alpha1" + admissionv1 "k8s.io/api/admission/v1" + authenticationv1 "k8s.io/api/authentication/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "sigs.k8s.io/controller-runtime/pkg/webhook/admission" +) + +func capacityRaw(t *testing.T, capacity *metal.MachineCapacity) runtime.RawExtension { + t.Helper() + raw, err := json.Marshal(capacity) + if err != nil { + t.Fatal(err) + } + return runtime.RawExtension{Raw: raw} +} + +func clone(capacity *metal.MachineCapacity) *metal.MachineCapacity { + return capacity.DeepCopyObject().(*metal.MachineCapacity) +} + +// Capacity without the registration marker is not inventory-backed. The +// handler allows it without touching Devices or the provider project, even +// when both are unavailable. +func TestUnmarkedCapacityIsNotGoverned(t *testing.T) { + handler := &Handler{Projects: []string{"provider"}, Resolve: func(context.Context, string) (Project, error) { + t.Error("unmarked capacity resolved the provider project") + return Project{}, errors.New("unavailable") + }, Authorize: func(context.Context, Project, authenticationv1.UserInfo, string, string, string) error { + t.Error("unmarked capacity was authorized against Devices") + return errors.New("unavailable") + }} + synthetic := &metal.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: "synthetic-01", Namespace: "fleet-provider", Labels: map[string]string{"fleet.datumapis.com/capacity-pool": "synthetic"}, Annotations: map[string]string{"example.com/note": "synthetic"}}, Spec: metal.MachineCapacitySpec{DeviceRef: metal.LocalReference{Name: "synthetic-device"}, AllocationPolicy: "Enabled", ReclaimPolicy: "Retain", CleaningPolicyRef: metal.LocalReference{Name: "synthetic-tenant-reuse-v1"}}} + changed := clone(synthetic) + changed.Spec.AllocationPolicy = "Disabled" + resource := metav1.GroupVersionResource{Group: "metal.datumapis.com", Version: "v1alpha1", Resource: "machinecapacities"} + requests := map[string]admissionv1.AdmissionRequest{ + "create": {Operation: admissionv1.Create, Object: capacityRaw(t, synthetic)}, + "spec update": {Operation: admissionv1.Update, Object: capacityRaw(t, changed), OldObject: capacityRaw(t, synthetic)}, + "status update": {Operation: admissionv1.Update, SubResource: "status", Object: capacityRaw(t, changed), OldObject: capacityRaw(t, synthetic)}, + "delete": {Operation: admissionv1.Delete, OldObject: capacityRaw(t, synthetic)}, + } + for name, request := range requests { + t.Run(name, func(t *testing.T) { + request.Name, request.Namespace, request.Resource = synthetic.Name, synthetic.Namespace, resource + if response := handler.Handle(context.Background(), admission.Request{AdmissionRequest: request}); !response.Allowed { + t.Fatalf("unmarked capacity denied: %s", response.Result.Message) + } + }) + } +} + +// Marked capacity stays fenced, and the marker cannot be added, changed or +// removed to move capacity into or out of the gate. +func TestMarkerTransitionsAreDenied(t *testing.T) { + handler, device := fixture(t) + registration := registrationRequest(t, device) + var registered metal.MachineCapacity + if err := json.Unmarshal(registration.Object.Raw, ®istered); err != nil { + t.Fatal(err) + } + unmarked := &metal.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: "hand-made", Namespace: "default"}, Spec: metal.MachineCapacitySpec{DeviceRef: metal.LocalReference{Name: device.Name}, AllocationPolicy: "Disabled", ReclaimPolicy: "Retain"}} + adopted := clone(unmarked) + adopted.Annotations = map[string]string{DeviceUIDAnnotation: string(device.UID)} + enabledAdoption := clone(adopted) + enabledAdoption.Spec.AllocationPolicy = "Enabled" + stripped := clone(®istered) + stripped.Annotations = nil + changed := clone(®istered) + changed.Annotations[DeviceUIDAnnotation] = "other" + partial := clone(®istered) + delete(partial.Annotations, DeviceUIDAnnotation) + squatted := clone(unmarked) + squatted.Name = CapacityName("squatted") + cases := map[string]struct { + operation admissionv1.Operation + subresource string + object, old *metal.MachineCapacity + }{ + "marker added": {operation: admissionv1.Update, object: adopted, old: unmarked}, + "marker added while enabling": {operation: admissionv1.Update, object: enabledAdoption, old: unmarked}, + "marker removed": {operation: admissionv1.Update, object: stripped, old: ®istered}, + "marker changed": {operation: admissionv1.Update, object: changed, old: ®istered}, + "one marker removed": {operation: admissionv1.Update, object: partial, old: ®istered}, + "marked update": {operation: admissionv1.Update, object: ®istered, old: ®istered}, + "marked delete": {operation: admissionv1.Delete, old: ®istered}, + "marked status when routed": {operation: admissionv1.Update, subresource: "status", object: ®istered, old: ®istered}, + "derived name without marker": {operation: admissionv1.Create, object: squatted}, + } + for name, test := range cases { + t.Run(name, func(t *testing.T) { + request := registration + request.Operation, request.SubResource = test.operation, test.subresource + request.Object, request.OldObject = runtime.RawExtension{}, runtime.RawExtension{} + if test.object != nil { + request.Object, request.Name = capacityRaw(t, test.object), test.object.Name + } + if test.old != nil { + request.OldObject, request.Name = capacityRaw(t, test.old), test.old.Name + } + if response := handler.Handle(context.Background(), request); response.Allowed { + t.Fatal("inventory-backed capacity escaped the gate") + } + }) + } +} From a5e39ba77ea76eabc85dc9fce8aa3b6e65a424d3 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sun, 22 Nov 2026 18:25:32 -0600 Subject: [PATCH 085/518] feat(ui): join Device components to Cable lanes Add a pure deviceConnections() join that maps each component position to the Cable lanes naming it and classifies the result as cable recorded, no cable recorded, records disagree, peer unavailable or catalog only. It covers breakouts, PowerFeed outlets and traces through PDU and patch-panel internal mappings. Denied peers expose no identity and denied Cables classify nothing. Co-Authored-By: Claude Opus 5.5 --- .../src/lib/device-connections.test.ts | 189 ++++++++++ ui/provider/src/lib/device-connections.ts | 323 ++++++++++++++++++ 2 files changed, 512 insertions(+) create mode 100644 ui/provider/src/lib/device-connections.test.ts create mode 100644 ui/provider/src/lib/device-connections.ts diff --git a/ui/provider/src/lib/device-connections.test.ts b/ui/provider/src/lib/device-connections.test.ts new file mode 100644 index 00000000..2e6eccf1 --- /dev/null +++ b/ui/provider/src/lib/device-connections.test.ts @@ -0,0 +1,189 @@ +import { describe, expect, it } from 'vitest'; +import type { CableEndpoint, Device, PhysicalComponent, PhysicalRecord } from '../../../shared/fleet-api'; +import { toInventory, type Inventory } from '../inventory'; +import { deviceConnections, localLabel, peerLabel, remotePortLabel, stateCounts, type ConnectionLink } from './device-connections'; + +// Synthetic records only. +const NS = 'default'; +const C = (id: string, type: PhysicalComponent['type'], positions?: number, name = id): PhysicalComponent => ({ id, name, type, ...(positions ? { positions } : {}) }); +const device = (name: string, components: PhysicalComponent[], extra: Partial = {}): Device => ({ + metadata: { name, namespace: NS }, + spec: { claimRef: { name: `${name}-claim` }, identity: { model: 'example-model', serial: `SYNTH-${name}` }, displayName: `Example ${name}`, topologyAuthority: 'Cable', components, ...extra }, +}); +const feed = (name: string, outlets: number): PhysicalRecord => ({ + kind: 'PowerFeed', metadata: { name, namespace: NS }, + spec: { displayName: `Feed ${name}`, supply: { type: 'AC', voltageV: 208, currentA: 30 }, terminations: Array.from({ length: outlets }, (_, index) => C(`outlet-${index + 1}`, 'PowerOutlet', undefined, `Outlet ${index + 1}`)) }, +}); +const D = (name: string, componentID: string, position = 1): CableEndpoint => ({ deviceRef: { name }, componentID, position }); +const P = (name: string, componentID: string, position = 1): CableEndpoint => ({ powerFeedRef: { name }, componentID, position }); +const cable = (name: string, medium: string, lanes: [string, CableEndpoint, CableEndpoint][]): PhysicalRecord => ({ + kind: 'Cable', metadata: { name, namespace: NS }, spec: { displayName: name, medium, lanes: lanes.map(([id, a, b]) => ({ id, a, b })) }, +}); +const inv = (devices: Device[], physical: PhysicalRecord[], issues?: Inventory['issues']): Inventory => ({ ...toInventory([], devices, physical), issues }); + +const server = device('server-01', [C('psu-1', 'PowerInlet', undefined, 'PSU 1'), C('psu-2', 'PowerInlet', undefined, 'PSU 2'), C('eth0', 'NetworkPort', undefined, 'Ethernet 0'), C('boot-ssd', 'InventoryItem')]); +const leaf = device('leaf-01', [C('swp1', 'NetworkPort'), C('swp2', 'NetworkPort'), C('swp49', 'NetworkPort', 4)]); +const link = (links: ConnectionLink[], componentID: string, position = 1) => links.filter(item => item.componentID === componentID && item.position === position); + +describe('deviceConnections', () => { + it('classifies a single recorded cable as cable recorded, with both ports', () => { + const result = deviceConnections(server, inv([server, leaf], [cable('dac-01', 'Copper', [['l1', D('server-01', 'eth0'), D('leaf-01', 'swp1')]])])); + const [eth0] = link(result.links, 'eth0'); + expect(eth0).toMatchObject({ state: 'cabled', group: 'network', cable: { name: 'dac-01', medium: 'Copper', laneID: 'l1' }, peer: { kind: 'Device', access: 'readable', name: 'leaf-01', componentID: 'swp1' } }); + expect(peerLabel(eth0.peer)).toBe('Example leaf-01 · swp1'); + expect(remotePortLabel(eth0.peer)).toBe('swp1'); + }); + + it('classifies an uncabled port as no cable recorded, never free', () => { + const result = deviceConnections(server, inv([server], [])); + const [eth0] = link(result.links, 'eth0'); + expect(eth0.state).toBe('none'); + expect(eth0.cable).toBeUndefined(); + expect(Object.keys(stateCounts(result.links))).not.toContain('free'); + // Items that do not terminate cables are left out unless a Cable names them. + expect(link(result.links, 'boot-ssd')).toEqual([]); + }); + + it('marks two Cables claiming the same port as records disagree, keeping both', () => { + const result = deviceConnections(server, inv([server, leaf], [ + cable('dac-01', 'Copper', [['l1', D('server-01', 'eth0'), D('leaf-01', 'swp1')]]), + cable('dac-02', 'Copper', [['l1', D('server-01', 'eth0'), D('leaf-01', 'swp2')]]), + ])); + const claims = link(result.links, 'eth0'); + expect(claims.map(item => [item.state, item.cable?.name])).toEqual([['conflict', 'dac-01'], ['conflict', 'dac-02']]); + expect(claims[0].reasons.join(' ')).toMatch(/2 Cable lanes name this position/); + }); + + it('marks a far port claimed by another Cable as records disagree', () => { + const other = device('server-02', [C('eth0', 'NetworkPort')]); + const result = deviceConnections(server, inv([server, other, leaf], [ + cable('dac-01', 'Copper', [['l1', D('server-01', 'eth0'), D('leaf-01', 'swp1')]]), + cable('dac-02', 'Copper', [['l1', D('server-02', 'eth0'), D('leaf-01', 'swp1')]]), + ])); + const [eth0] = link(result.links, 'eth0'); + expect(eth0.state).toBe('conflict'); + expect(eth0.reasons.join(' ')).toMatch(/peer port is named by 2 Cable lanes: dac-01, dac-02/); + }); + + it('marks a Cable naming a component the Device does not record as records disagree', () => { + const result = deviceConnections(server, inv([server, leaf], [cable('dac-legacy', 'Copper', [['l1', D('server-01', 'eth9'), D('leaf-01', 'swp2')]])])); + const [orphan] = link(result.links, 'eth9'); + expect(orphan).toMatchObject({ state: 'conflict', group: 'unrecorded', component: undefined }); + expect(orphan.reasons[0]).toMatch(/names component "eth9", which this Device does not record/); + }); + + it('marks a Cable naming a position above the recorded count as records disagree', () => { + const result = deviceConnections(server, inv([server, leaf], [cable('dac-03', 'Copper', [['l1', D('server-01', 'eth0', 2), D('leaf-01', 'swp2')]])])); + expect(link(result.links, 'eth0', 1)[0].state).toBe('none'); + const [orphan] = link(result.links, 'eth0', 2); + expect(orphan).toMatchObject({ state: 'conflict', group: 'network' }); + expect(orphan.reasons[0]).toMatch(/position 2; this Device records 1/); + }); + + it('marks a peer component the peer does not record as records disagree', () => { + const result = deviceConnections(server, inv([server, leaf], [cable('dac-01', 'Copper', [['l1', D('server-01', 'eth0'), D('leaf-01', 'swp99')]])])); + expect(link(result.links, 'eth0')[0]).toMatchObject({ state: 'conflict', reasons: ['The peer does not record component "swp99".'] }); + }); + + it('marks a missing peer record as peer unavailable, naming only what the Cable records', () => { + const result = deviceConnections(server, inv([server], [cable('dac-01', 'Copper', [['l1', D('server-01', 'eth0'), D('leaf-02', 'swp1')]])])); + const [eth0] = link(result.links, 'eth0'); + expect(eth0.state).toBe('unavailable'); + expect(eth0.peer).toMatchObject({ access: 'missing', name: 'leaf-02' }); + expect(peerLabel(eth0.peer)).toBe('leaf-02 · swp1 (record not found)'); + }); + + it('marks a denied peer collection as peer unavailable without leaking its identity', () => { + const result = deviceConnections(server, inv([server], [ + feed('feed-a', 8), + cable('pwr-01', 'Power', [['power', P('feed-a', 'outlet-7'), D('server-01', 'psu-1')]]), + ], { PowerFeed: { status: 403 } })); + const [psu] = link(result.links, 'psu-1'); + expect(psu.state).toBe('unavailable'); + expect(psu.peer).toEqual({ kind: 'PowerFeed', access: 'denied' }); + expect(JSON.stringify(psu.peer)).not.toMatch(/feed-a|outlet-7/); + expect(peerLabel(psu.peer)).toBe('Power feed unavailable'); + expect(remotePortLabel(psu.peer)).toBe('Port unavailable'); + }); + + it('treats denied Cable reads as unknown connections, not as no cable recorded', () => { + const result = deviceConnections(server, inv([server], [], { Cable: { status: 403 } })); + expect(result).toMatchObject({ cableAccess: 'denied', links: [] }); + }); + + it('lists DeviceType templates the Device does not record as catalog only', () => { + const typed = device('server-03', [C('eth0', 'NetworkPort')], { deviceTypeRef: { name: 'example-type' } }); + const physical: PhysicalRecord[] = [ + { kind: 'Manufacturer', metadata: { name: 'example-maker', namespace: NS }, spec: { displayName: 'Example maker', canonicalName: 'Example maker' } }, + { kind: 'DeviceType', metadata: { name: 'example-type', namespace: NS }, spec: { displayName: 'Example type', manufacturerRef: { name: 'example-maker' }, model: 'example-model', componentTemplates: [C('eth0', 'NetworkPort'), C('eth1', 'NetworkPort'), C('psu-1', 'PowerInlet')] } }, + ]; + const result = deviceConnections(typed, inv([typed], physical)); + expect(result.catalog).toBe('compared'); + expect(result.links.filter(item => item.state === 'catalog').map(item => [item.componentID, item.group])).toEqual([['eth1', 'network'], ['psu-1', 'power']]); + expect(deviceConnections(typed, inv([typed], physical, { DeviceType: { status: 403 } })).catalog).toBe('unavailable'); + }); + + it('maps each breakout lane to its own position and peer', () => { + const servers = [1, 2, 3, 4].map(n => device(`server-1${n}`, [C('eth0', 'NetworkPort')])); + const breakout = cable('brk-49', 'Copper', [1, 2, 3, 4].map(n => [`lane-${n}`, D('leaf-01', 'swp49', n), D(`server-1${n}`, 'eth0')])); + const data = inv([leaf, ...servers], [breakout]); + const result = deviceConnections(leaf, data); + expect([1, 2, 3, 4].map(n => link(result.links, 'swp49', n)[0]).map(item => [item.state, item.cable?.laneID, item.cable?.laneCount, item.peer?.name])).toEqual([ + ['cabled', 'lane-1', 4, 'server-11'], ['cabled', 'lane-2', 4, 'server-12'], ['cabled', 'lane-3', 4, 'server-13'], ['cabled', 'lane-4', 4, 'server-14'], + ]); + expect(localLabel(link(result.links, 'swp49', 3)[0])).toBe('swp49 · position 3'); + const [fromServer] = link(deviceConnections(servers[2], data).links, 'eth0'); + expect(fromServer.peer).toMatchObject({ name: 'leaf-01', componentID: 'swp49', position: 3, multiPosition: true }); + expect(remotePortLabel(fromServer.peer)).toBe('swp49 · position 3'); + }); + + it('joins PSU inlets to PowerFeed outlets with the recorded rating, leaving other inlets unknown', () => { + const result = deviceConnections(server, inv([server], [feed('feed-a', 8), cable('pwr-01', 'Power', [['power', P('feed-a', 'outlet-7'), D('server-01', 'psu-1')]])])); + const [psu1] = link(result.links, 'psu-1'); + expect(psu1).toMatchObject({ state: 'cabled', group: 'power', peer: { kind: 'PowerFeed', componentName: 'Outlet 7', supply: 'AC · 208 V · 30 A' } }); + expect(link(result.links, 'psu-2')[0].state).toBe('none'); + }); + + it('marks a PowerFeed outlet the feed does not record as records disagree', () => { + const result = deviceConnections(server, inv([server], [feed('feed-a', 2), cable('pwr-01', 'Power', [['power', P('feed-a', 'outlet-7'), D('server-01', 'psu-1')]])])); + expect(link(result.links, 'psu-1')[0].state).toBe('conflict'); + }); + + it('traces a PSU through a PDU outlet-to-inlet path to its feed', () => { + const pdu = device('pdu-01', [C('inlet', 'PowerInlet', undefined, 'Inlet'), C('out-3', 'PowerOutlet', undefined, 'Outlet 3')], { internalMappings: [{ from: { componentID: 'out-3', position: 1 }, to: { componentID: 'inlet', position: 1 } }] }); + const data = inv([server, pdu], [ + feed('feed-a', 8), + cable('pwr-srv', 'Power', [['power', D('pdu-01', 'out-3'), D('server-01', 'psu-1')]]), + cable('pwr-pdu', 'Power', [['power', P('feed-a', 'outlet-1'), D('pdu-01', 'inlet')]]), + ]); + const [psu1] = link(deviceConnections(server, data).links, 'psu-1'); + expect(psu1.peer).toMatchObject({ name: 'pdu-01', componentName: 'Outlet 3' }); + expect(psu1.trace).toEqual([expect.objectContaining({ via: { componentID: 'inlet', componentName: 'Inlet', position: 1 }, state: 'cabled', cable: expect.objectContaining({ name: 'pwr-pdu' }), peer: expect.objectContaining({ kind: 'PowerFeed', name: 'feed-a', componentName: 'Outlet 1' }) })]); + // From the PDU itself, the outlet shows its own internal path. + const [outlet] = link(deviceConnections(pdu, data).links, 'out-3'); + expect(outlet.internal).toEqual({ componentID: 'inlet', componentName: 'Inlet', position: 1 }); + }); + + it('traces a pass-through path and stops with no cable recorded beyond the panel', () => { + const panel = device('panel-01', [C('front-1', 'FrontPort'), C('rear-1', 'RearPort', 2)], { internalMappings: [{ from: { componentID: 'front-1', position: 1 }, to: { componentID: 'rear-1', position: 2 } }] }); + const data = inv([server, panel], [cable('cat6-01', 'Copper', [['l1', D('server-01', 'eth0'), D('panel-01', 'front-1')]])]); + const [eth0] = link(deviceConnections(server, data).links, 'eth0'); + expect(eth0.state).toBe('cabled'); + expect(eth0.trace).toEqual([{ via: { componentID: 'rear-1', componentName: 'rear-1', position: 2 }, state: 'none', reasons: [] }]); + }); + + it('stops a trace at an unreadable hop without naming it', () => { + const pdu = device('pdu-01', [C('inlet', 'PowerInlet'), C('out-3', 'PowerOutlet')], { internalMappings: [{ from: { componentID: 'out-3', position: 1 }, to: { componentID: 'inlet', position: 1 } }] }); + const data = inv([server, pdu], [ + cable('pwr-srv', 'Power', [['power', D('pdu-01', 'out-3'), D('server-01', 'psu-1')]]), + cable('pwr-pdu', 'Power', [['power', P('feed-hidden', 'outlet-1'), D('pdu-01', 'inlet')]]), + ], { PowerFeed: { status: 403 } }); + const [psu1] = link(deviceConnections(server, data).links, 'psu-1'); + expect(psu1.trace).toEqual([expect.objectContaining({ state: 'unavailable', peer: { kind: 'PowerFeed', access: 'denied' } })]); + }); + + it('ignores Cables in other namespaces', () => { + const foreign = { ...cable('dac-x', 'Copper', [['l1', D('server-01', 'eth0'), D('leaf-01', 'swp1')]]), metadata: { name: 'dac-x', namespace: 'other' } }; + expect(link(deviceConnections(server, inv([server, leaf], [foreign])).links, 'eth0')[0].state).toBe('none'); + }); +}); diff --git a/ui/provider/src/lib/device-connections.ts b/ui/provider/src/lib/device-connections.ts new file mode 100644 index 00000000..dc8df807 --- /dev/null +++ b/ui/provider/src/lib/device-connections.ts @@ -0,0 +1,323 @@ +// Joins a Device's typed components to the Cable lanes that name them. +// +// Everything here is derived from records, not from the wire. Status is +// empty on every inventory kind, so a link can be "cable recorded" at best; +// nothing is ever verified. "No cable recorded" means unknown, never free. +// A denied collection read is never treated as an absent record. + +import type { CableEndpoint, ComponentPosition, Device, PhysicalComponent, PhysicalRecord } from '../../../shared/fleet-api'; +import type { Inventory } from '../inventory'; +import { deviceCatalog } from './hardware-catalog'; + +export type LinkState = 'cabled' | 'none' | 'conflict' | 'unavailable' | 'catalog'; +export type ConnectionGroup = 'power' | 'network' | 'console' | 'passthrough' | 'other' | 'unrecorded'; + +export const linkStateWords: Record = { + cabled: 'Cable recorded', + none: 'No cable recorded', + conflict: 'Records disagree', + unavailable: 'Peer unavailable', + catalog: 'Catalog only', +}; + +// Each state has a symbol as well as words and a line style, so colour is +// never the only signal. +export const linkStateGlyph: Record = { + cabled: '●', + none: '○', + conflict: '!', + unavailable: '?', + catalog: '◇', +}; + +export const connectionGroups: { group: ConnectionGroup; title: string }[] = [ + { group: 'power', title: 'Power' }, + { group: 'network', title: 'Network' }, + { group: 'console', title: 'Console' }, + { group: 'passthrough', title: 'Pass-through' }, + { group: 'other', title: 'Modules and items' }, + { group: 'unrecorded', title: 'Not on this Device' }, +]; + +const groupOf: Record = { + PowerInlet: 'power', PowerOutlet: 'power', + NetworkPort: 'network', + ConsolePort: 'console', ConsoleServerPort: 'console', + FrontPort: 'passthrough', RearPort: 'passthrough', + Module: 'other', InventoryItem: 'other', DeviceBay: 'other', +}; + +// Modules, items and bays rarely terminate cables. They join the view only +// when a Cable names them. +const UNCABLED_TYPES = new Set(['Module', 'InventoryItem', 'DeviceBay']); + +// Above this many links the diagram stops being readable, so the view +// defaults to the list and collapses the diagram by group. +export const DIAGRAM_LINK_LIMIT = 32; + +// Internal-path traces (patch panels, PDUs) stop after this many hops. +export const MAX_TRACE_HOPS = 4; + +type PeerKind = 'Device' | 'PowerFeed'; + +/** + * The far end of a Cable lane. When the peer collection is denied, only the + * kind and access are kept: no name, component or position is exposed. + */ +export interface PeerEnd { + kind: PeerKind; + access: 'readable' | 'denied' | 'missing'; + name?: string; + label?: string; + componentID?: string; + componentName?: string; + position?: number; + /** True when the peer component records more than one position. */ + multiPosition?: boolean; + /** Recorded supply rating, for PowerFeed peers. */ + supply?: string; +} + +export interface CableRef { + name: string; + label: string; + medium?: string; + laneID: string; + laneCount: number; +} + +/** One hop beyond a peer, through that peer's recorded internal mapping. */ +export interface TraceHop { + /** The peer component and position the internal mapping leads to. */ + via: { componentID: string; componentName?: string; position: number }; + state: Exclude; + cable?: CableRef; + peer?: PeerEnd; + reasons: string[]; +} + +export interface ConnectionLink { + key: string; + group: ConnectionGroup; + state: LinkState; + componentID: string; + component?: PhysicalComponent; + template?: Omit; + position: number; + positions: number; + /** This Device's own internal mapping from this position, if recorded. */ + internal?: { componentID: string; componentName?: string; position: number }; + cable?: CableRef; + peer?: PeerEnd; + trace: TraceHop[]; + reasons: string[]; +} + +export interface DeviceConnections { + /** When Cables are denied, connections are unknown and links is empty. */ + cableAccess: 'readable' | 'denied'; + catalog: 'compared' | 'unassigned' | 'unavailable'; + links: ConnectionLink[]; +} + +interface Termination { + cable: PhysicalRecord; + laneID: string; + mine: CableEndpoint; + far: CableEndpoint; +} + +const positionsOf = (component?: { positions?: number }) => component?.positions ?? 1; +const recordLabel = (record: { metadata: { name: string }; spec: { displayName?: string } }) => record.spec.displayName || record.metadata.name; + +function endKey(endpoint: CableEndpoint) { + const kind = endpoint.deviceRef ? 'Device' : endpoint.powerFeedRef ? 'PowerFeed' : ''; + return `${kind}/${endpoint.deviceRef?.name ?? endpoint.powerFeedRef?.name ?? ''}/${endpoint.componentID}/${endpoint.position}`; +} + +function inventoryDevices(inventory: Inventory): Device[] { + return [...inventory.slots.flatMap(slot => slot.devices), ...inventory.unboundDevices]; +} + +function cableRef(cable: PhysicalRecord, laneID: string): CableRef { + return { name: cable.metadata.name, label: recordLabel(cable), medium: cable.spec.medium, laneID, laneCount: cable.spec.lanes?.length ?? 0 }; +} + +function findMapping(device: Device, componentID: string, position: number) { + for (const mapping of device.spec.internalMappings ?? []) { + if (mapping.from.componentID === componentID && mapping.from.position === position) return mapping.to; + if (mapping.to.componentID === componentID && mapping.to.position === position) return mapping.from; + } +} + +class Join { + private readonly devices = new Map(); + private readonly feeds = new Map(); + // Every recorded termination in the namespace, so claims on the far port + // are visible as well as claims on this Device's ports. + private readonly index = new Map(); + + constructor(private readonly inventory: Inventory, namespace: string | undefined) { + for (const device of inventoryDevices(inventory)) if (device.metadata.namespace === namespace) this.devices.set(device.metadata.name, device); + for (const record of inventory.physical) { + if (record.metadata.namespace !== namespace) continue; + if (record.kind === 'PowerFeed') this.feeds.set(record.metadata.name, record); + if (record.kind !== 'Cable') continue; + for (const lane of record.spec.lanes ?? []) + for (const [mine, far] of [[lane.a, lane.b], [lane.b, lane.a]] as const) { + const key = endKey(mine); + this.index.set(key, [...(this.index.get(key) ?? []), { cable: record, laneID: lane.id, mine, far }]); + } + } + } + + terminationsAt(kind: PeerKind, name: string, componentID: string, position: number) { + return this.index.get(`${kind}/${name}/${componentID}/${position}`) ?? []; + } + + terminationsOn(device: Device) { + const prefix = `Device/${device.metadata.name}/`; + return [...this.index.entries()].filter(([key]) => key.startsWith(prefix)).flatMap(([, value]) => value); + } + + /** Resolves a far end and lists any way the records contradict it. */ + peer(far: CableEndpoint): { peer: PeerEnd; reasons: string[]; device?: Device } { + const kind: PeerKind = far.deviceRef ? 'Device' : 'PowerFeed'; + const name = far.deviceRef?.name ?? far.powerFeedRef?.name ?? ''; + if (this.inventory.issues?.[kind]) return { peer: { kind, access: 'denied' }, reasons: [] }; + const record = kind === 'Device' ? this.devices.get(name) : this.feeds.get(name); + if (!record) return { peer: { kind, access: 'missing', name, componentID: far.componentID, position: far.position }, reasons: [] }; + const components = kind === 'Device' ? (record as Device).spec.components : (record as PhysicalRecord).spec.terminations; + const component = components?.find(item => item.id === far.componentID); + const supply = kind === 'PowerFeed' ? (record as PhysicalRecord).spec.supply : undefined; + const peer: PeerEnd = { + kind, access: 'readable', name, label: recordLabel(record), componentID: far.componentID, componentName: component?.name, + position: far.position, multiPosition: positionsOf(component) > 1 || far.position > 1, + supply: supply && `${supply.type} · ${supply.voltageV ?? 'unknown'} V · ${supply.currentA ?? 'unknown'} A`, + }; + const reasons: string[] = []; + if (!component) reasons.push(`The peer does not record component "${far.componentID}".`); + else if (far.position > positionsOf(component)) reasons.push(`The Cable names position ${far.position}; the peer component records ${positionsOf(component)}.`); + const claims = this.terminationsAt(kind, name, far.componentID, far.position); + if (claims.length > 1) reasons.push(`The peer port is named by ${claims.length} Cable lanes: ${[...new Set(claims.map(claim => claim.cable.metadata.name))].join(', ')}.`); + return { peer, reasons, device: kind === 'Device' ? record as Device : undefined }; + } + + /** Follows a peer Device's internal mapping (patch panel or PDU) onward. */ + trace(device: Device | undefined, far: CableEndpoint, seen: Set): TraceHop[] { + const hops: TraceHop[] = []; + let current = device; + let at: ComponentPosition = far; + while (current && hops.length < MAX_TRACE_HOPS) { + const mapped = findMapping(current, at.componentID, at.position); + if (!mapped) break; + const visit = `${current.metadata.name}/${mapped.componentID}/${mapped.position}`; + if (seen.has(visit)) break; + seen.add(visit); + const via = { componentID: mapped.componentID, componentName: current.spec.components?.find(item => item.id === mapped.componentID)?.name, position: mapped.position }; + const onward = this.terminationsAt('Device', current.metadata.name, mapped.componentID, mapped.position); + if (!onward.length) { hops.push({ via, state: 'none', reasons: [] }); break; } + if (onward.length > 1) { hops.push({ via, state: 'conflict', reasons: [`${onward.length} Cable lanes name this position: ${[...new Set(onward.map(item => item.cable.metadata.name))].join(', ')}.`] }); break; } + const next = this.peer(onward[0].far); + hops.push({ via, state: next.peer.access !== 'readable' ? 'unavailable' : next.reasons.length ? 'conflict' : 'cabled', cable: cableRef(onward[0].cable, onward[0].laneID), peer: next.peer, reasons: next.reasons }); + if (next.peer.access !== 'readable' || next.reasons.length) break; + current = next.device; + at = onward[0].far; + } + return hops; + } +} + +/** + * Maps a Device's components to the Cable lanes that name them. Returns one + * link per component position and claiming lane, plus links for Cables that + * name a component or position the Device does not record, and DeviceType + * templates the Device does not record. + */ +export function deviceConnections(device: Device, inventory: Inventory): DeviceConnections { + const catalogState: DeviceConnections['catalog'] = !device.spec.deviceTypeRef ? 'unassigned' : deviceCatalog(device, inventory) ? 'compared' : 'unavailable'; + if (inventory.issues?.Cable) return { cableAccess: 'denied', catalog: catalogState, links: [] }; + const join = new Join(inventory, device.metadata.namespace); + const components = device.spec.components ?? []; + const byID = new Map(components.map(component => [component.id, component])); + const templates = deviceCatalog(device, inventory)?.model.spec.componentTemplates ?? []; + const links: ConnectionLink[] = []; + + const internalFor = (componentID: string, position: number) => { + const mapped = findMapping(device, componentID, position); + return mapped && { componentID: mapped.componentID, componentName: byID.get(mapped.componentID)?.name, position: mapped.position }; + }; + + const linkFor = (base: Omit, termination: Termination, claims: number, localReasons: string[], index: number): ConnectionLink => { + const resolved = join.peer(termination.far); + const reasons = [...localReasons]; + if (claims > 1) reasons.push(`${claims} Cable lanes name this position. Neither is treated as current.`); + reasons.push(...resolved.reasons); + const unavailable = resolved.peer.access !== 'readable'; + const state: LinkState = localReasons.length || claims > 1 ? 'conflict' : unavailable ? 'unavailable' : resolved.reasons.length ? 'conflict' : 'cabled'; + const trace = state === 'cabled' ? join.trace(resolved.device, termination.far, new Set([`${device.metadata.name}/${base.componentID}/${base.position}`])) : []; + return { ...base, key: `${base.componentID}/${base.position}/${termination.cable.metadata.name}/${termination.laneID}/${index}`, state, cable: cableRef(termination.cable, termination.laneID), peer: resolved.peer, trace, reasons }; + }; + + for (const component of components) { + const positions = positionsOf(component); + for (let position = 1; position <= positions; position++) { + const claims = join.terminationsAt('Device', device.metadata.name, component.id, position); + const base = { group: groupOf[component.type], componentID: component.id, component, position, positions, internal: internalFor(component.id, position) }; + if (!claims.length) { + if (!UNCABLED_TYPES.has(component.type)) links.push({ ...base, key: `${component.id}/${position}`, state: 'none', trace: [], reasons: [] }); + continue; + } + claims.forEach((claim, index) => links.push(linkFor(base, claim, claims.length, [], index))); + } + } + + // Cables that name a component this Device lacks, or a position above the + // component's recorded count. + const orphans = join.terminationsOn(device).filter(termination => { + const component = byID.get(termination.mine.componentID); + return !component || termination.mine.position > positionsOf(component); + }); + orphans.forEach((termination, index) => { + const component = byID.get(termination.mine.componentID); + const template = templates.find(item => item.id === termination.mine.componentID); + const reason = component + ? `The Cable names position ${termination.mine.position}; this Device records ${positionsOf(component)} for "${component.id}".` + : `The Cable names component "${termination.mine.componentID}", which this Device does not record${template ? ' (it appears only in the catalog)' : ''}.`; + links.push(linkFor({ group: component ? groupOf[component.type] : 'unrecorded', componentID: termination.mine.componentID, component, template, position: termination.mine.position, positions: positionsOf(component) }, termination, 1, [reason], index)); + }); + + const orphanIDs = new Set(orphans.map(termination => termination.mine.componentID)); + for (const template of templates) { + if (byID.has(template.id) || orphanIDs.has(template.id)) continue; + links.push({ key: `catalog/${template.id}`, group: groupOf[template.type], state: 'catalog', componentID: template.id, template, position: 1, positions: positionsOf(template), trace: [], reasons: [] }); + } + + return { cableAccess: 'readable', catalog: catalogState, links }; +} + +export function stateCounts(links: ConnectionLink[]) { + const counts: Record = { cabled: 0, none: 0, conflict: 0, unavailable: 0, catalog: 0 }; + for (const link of links) counts[link.state]++; + return counts; +} + +export function localLabel(link: Pick) { + const name = link.component?.name ?? link.template?.name ?? link.componentID; + return link.positions > 1 || link.position > 1 ? `${name} · position ${link.position}` : name; +} + +/** The far end in words. A denied peer yields no identifying detail. */ +export function peerLabel(peer: PeerEnd | undefined) { + if (!peer) return 'Unknown'; + if (peer.access === 'denied') return peer.kind === 'PowerFeed' ? 'Power feed unavailable' : 'Device unavailable'; + const port = peer.componentName ?? peer.componentID; + const position = peer.multiPosition ? ` · position ${peer.position}` : ''; + if (peer.access === 'missing') return `${peer.name} · ${peer.componentID}${position} (record not found)`; + return `${peer.label} · ${port}${position}`; +} + +export function remotePortLabel(peer: PeerEnd | undefined) { + if (!peer || peer.access === 'denied') return 'Port unavailable'; + return `${peer.componentName ?? peer.componentID}${peer.multiPosition || (peer.position ?? 1) > 1 ? ` · position ${peer.position}` : ''}`; +} From 2c604030fb0fabcab7763b29a3329e60d7a5ea73 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sun, 22 Nov 2026 18:25:35 -0600 Subject: [PATCH 086/518] feat(ui): add Device connection view Show the Device's Cable records as a diagram with the Device in the centre and power and network peers either side, or as a table per group. Each state has a glyph, line style and words. The diagram is a nested list with one tab stop and arrow-key movement. Devices with more than 32 links open on the list and collapse the diagram by group. Co-Authored-By: Claude Opus 5.5 --- .../components/device-connections.test.tsx | 167 +++++++++++ .../src/components/device-connections.tsx | 274 ++++++++++++++++++ .../src/components/physical-inventory.css | 58 ++++ .../src/components/physical-inventory.tsx | 2 + 4 files changed, 501 insertions(+) create mode 100644 ui/provider/src/components/device-connections.test.tsx create mode 100644 ui/provider/src/components/device-connections.tsx diff --git a/ui/provider/src/components/device-connections.test.tsx b/ui/provider/src/components/device-connections.test.tsx new file mode 100644 index 00000000..d1ab13a7 --- /dev/null +++ b/ui/provider/src/components/device-connections.test.tsx @@ -0,0 +1,167 @@ +import { fireEvent, render, screen, within } from '@testing-library/react'; +import { describe, expect, it } from 'vitest'; +import { MemoryRouter, useLocation } from 'react-router'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import type { CableEndpoint, Device, PhysicalComponent, PhysicalRecord } from '../../../shared/fleet-api'; +import { toInventory, type Inventory } from '../inventory'; +import { DeviceConnections } from './device-connections'; +import { inventoryHref } from './inventory-location'; +import { PhysicalInventory } from './physical-inventory'; +import { fixturePhysicalClaims, fixturePhysicalDevices, fixturePhysicalRecords } from '../lib/fixtures'; +import { DIAGRAM_LINK_LIMIT } from '../lib/device-connections'; + +// Synthetic records only. +const NS = 'default'; +const C = (id: string, type: PhysicalComponent['type'], name = id, positions?: number): PhysicalComponent => ({ id, name, type, ...(positions ? { positions } : {}) }); +const device = (name: string, components: PhysicalComponent[]): Device => ({ + metadata: { name, namespace: NS }, + spec: { claimRef: { name: `${name}-claim` }, identity: { model: 'example-model', serial: `SYNTH-${name}` }, displayName: `Example ${name}`, topologyAuthority: 'Cable', components }, +}); +const D = (name: string, componentID: string, position = 1): CableEndpoint => ({ deviceRef: { name }, componentID, position }); +const P = (name: string, componentID: string): CableEndpoint => ({ powerFeedRef: { name }, componentID, position: 1 }); +const cable = (name: string, medium: string, a: CableEndpoint, b: CableEndpoint): PhysicalRecord => ({ kind: 'Cable', metadata: { name, namespace: NS }, spec: { displayName: name, medium, lanes: [{ id: 'l1', a, b }] } }); +const feed: PhysicalRecord = { kind: 'PowerFeed', metadata: { name: 'feed-hidden', namespace: NS }, spec: { displayName: 'Hidden feed', supply: { type: 'AC', voltageV: 208, currentA: 30 }, terminations: [C('outlet-7', 'PowerOutlet', 'Outlet 7')] } }; + +const server = device('server-01', [C('psu-1', 'PowerInlet', 'PSU 1'), C('psu-2', 'PowerInlet', 'PSU 2'), C('eth0', 'NetworkPort', 'Ethernet 0'), C('eth1', 'NetworkPort', 'Ethernet 1')]); +const leaf = device('leaf-01', [C('swp1', 'NetworkPort'), C('swp2', 'NetworkPort')]); +const serverRecords = [feed, cable('pwr-01', 'Power', P('feed-hidden', 'outlet-7'), D('server-01', 'psu-1')), cable('dac-01', 'Copper', D('server-01', 'eth0'), D('leaf-01', 'swp1'))]; +const data = (issues?: Inventory['issues'], devices = [server, leaf], physical = serverRecords): Inventory => ({ ...toInventory([], devices, physical), issues }); + +function Location() { + const { search } = useLocation(); + return {search}; +} + +function show(target: Device, inventory: Inventory) { + return render( + + + + , + ); +} + +const diagram = () => screen.getByRole('group', { name: /Connection diagram/ }); + +describe('DeviceConnections', () => { + it('labels the view as records, not live state, and toggles between diagram and list', () => { + show(server, data()); + expect(screen.getByText('Cable records, not live link state')).toBeInTheDocument(); + expect(screen.getByText(/Nothing here is verified/)).toBeInTheDocument(); + expect(screen.queryByText(/^Verified$/)).not.toBeInTheDocument(); + const toggle = screen.getByRole('group', { name: 'Connection view' }); + expect(within(toggle).getByRole('button', { name: 'Diagram' })).toHaveAttribute('aria-pressed', 'true'); + expect(within(diagram()).getByRole('list', { name: 'Power links' })).toBeInTheDocument(); + expect(screen.queryByRole('table')).not.toBeInTheDocument(); + + fireEvent.click(within(toggle).getByRole('button', { name: 'List' })); + expect(within(toggle).getByRole('button', { name: 'List' })).toHaveAttribute('aria-pressed', 'true'); + expect(screen.queryByRole('group', { name: /Connection diagram/ })).not.toBeInTheDocument(); + const network = screen.getByRole('table', { name: /Network · 2 links/ }); + const rows = within(network).getAllByRole('row').slice(1); + expect(rows.map(row => within(row).getAllByRole('cell')[1].textContent)).toEqual(['● Cable recorded', '○ No cable recorded']); + expect(within(rows[0]).getByRole('link', { name: 'dac-01' })).toHaveAttribute('href', '/inventory?kind=Cable&record=dac-01&namespace=default'); + expect(within(rows[0]).getByRole('link', { name: 'Example leaf-01 · swp1' })).toHaveAttribute('href', '/inventory?kind=Device&record=leaf-01&namespace=default'); + expect(within(rows[1]).getByText('Unknown · not free')).toBeInTheDocument(); + }); + + it('shows every state with a symbol and words in the legend', () => { + show(server, data()); + const legend = screen.getByRole('list', { name: 'Record states' }); + expect(within(legend).getAllByRole('listitem').map(item => item.textContent)).toEqual(['● Cable recorded', '○ No cable recorded', '! Records disagree', '? Peer unavailable', '◇ Catalog only']); + }); + + it('moves through cables and peers with arrow keys using one tab stop, and opens the focused link', () => { + show(server, data()); + const items = [...diagram().querySelectorAll('[data-connection-roving]')]; + expect(items.map(item => item.getAttribute('tabindex'))).toEqual(['0', '-1', '-1', '-1']); + items[0].focus(); + fireEvent.keyDown(items[0], { key: 'ArrowDown' }); + expect(document.activeElement).toBe(items[1]); + expect(items[1]).toHaveAttribute('tabindex', '0'); + expect(items[0]).toHaveAttribute('tabindex', '-1'); + fireEvent.keyDown(items[1], { key: 'End' }); + expect(document.activeElement).toBe(items[3]); + fireEvent.keyDown(items[3], { key: 'Home' }); + expect(document.activeElement).toBe(items[0]); + fireEvent.keyDown(items[0], { key: 'ArrowUp' }); + expect(document.activeElement).toBe(items[0]); + // The roving items are anchors, so Enter follows them natively. + const focused = document.activeElement as HTMLAnchorElement; + expect(focused.tagName).toBe('A'); + expect(focused).toHaveAccessibleName('PSU 1 to Hidden feed · Outlet 7 via cable pwr-01, Power: Cable recorded'); + fireEvent.click(focused); + expect(screen.getByTestId('location')).toHaveTextContent('?kind=Cable&record=pwr-01&namespace=default'); + fireEvent.click(within(diagram()).getByRole('link', { name: 'Peer Example leaf-01 · swp1' })); + expect(screen.getByTestId('location')).toHaveTextContent('?kind=Device&record=leaf-01&namespace=default'); + }); + + it('shows an unreadable peer as peer unavailable without leaking its identity', () => { + const view = show(server, data({ PowerFeed: { status: 403 } })); + const power = within(diagram()).getByRole('list', { name: 'Power links' }); + const [psu1] = within(power).getAllByRole('listitem'); + expect(psu1).toHaveAttribute('data-state', 'unavailable'); + expect(within(psu1).getByText('Power feed unavailable')).toBeInTheDocument(); + expect(within(psu1).getByText('You cannot read this peer')).toBeInTheDocument(); + expect(within(psu1).getAllByRole('link')).toHaveLength(1); + expect(within(psu1).getByRole('link', { name: /PSU 1 to Power feed unavailable via cable pwr-01/ })).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: 'List' })); + expect(view.container.textContent).not.toMatch(/feed-hidden|Hidden feed|outlet-7|Outlet 7|208 V/); + }); + + it('treats unreadable Cables as unknown connections, never as uncabled', () => { + show(server, data({ Cable: { status: 403 } })); + expect(screen.getByText(/Cable records are unavailable to you/)).toBeInTheDocument(); + expect(screen.queryByText('No cable recorded')).not.toBeInTheDocument(); + expect(screen.queryByRole('group', { name: 'Connection view' })).not.toBeInTheDocument(); + }); + + it('defaults a large device to the list and collapses the diagram by group with counts', () => { + const ports = DIAGRAM_LINK_LIMIT + 16; + const switchDevice = device('switch-01', Array.from({ length: ports }, (_, index) => C(`swp${index + 1}`, 'NetworkPort'))); + const hosts = Array.from({ length: 10 }, (_, index) => device(`host-${index + 1}`, [C('eth0', 'NetworkPort')])); + const cables = hosts.map((host, index) => cable(`dac-${index + 1}`, 'Copper', D('switch-01', `swp${index + 1}`), D(host.metadata.name, 'eth0'))); + show(switchDevice, data(undefined, [switchDevice, ...hosts], cables)); + expect(screen.getByRole('button', { name: 'List' })).toHaveAttribute('aria-pressed', 'true'); + expect(screen.getByText(new RegExp(`${ports} links is too many to draw clearly`))).toBeInTheDocument(); + expect(screen.getByRole('table', { name: new RegExp(`Network · ${ports} links`) })).toBeInTheDocument(); + + fireEvent.click(screen.getByRole('button', { name: 'Diagram' })); + const group = diagram().querySelector('details')!; + expect(group).not.toHaveAttribute('open'); + expect(group.querySelector('summary')).toHaveTextContent(`Network · ${ports} links 10 cable recorded, ${ports - 10} no cable recorded`); + // Collapsed links are not tab stops. + expect(diagram().querySelectorAll('[data-connection-roving][tabindex="0"]')).toHaveLength(0); + group.open = true; + fireEvent(group, new Event('toggle')); + expect(diagram().querySelectorAll('[data-connection-roving][tabindex="0"]')).toHaveLength(1); + }); + + it('keeps a small device in the diagram by default', () => { + show(leaf, data()); + expect(screen.getByRole('button', { name: 'Diagram' })).toHaveAttribute('aria-pressed', 'true'); + expect(diagram().querySelector('details')).toBeNull(); + expect(diagram()).not.toHaveAttribute('data-left'); + }); + + it('shows disagreeing records as two lines into one port, with the reason', () => { + const records = [...serverRecords, cable('dac-02', 'Copper', D('server-01', 'eth0'), D('leaf-01', 'swp2'))]; + show(server, data(undefined, [server, leaf], records)); + const network = within(diagram()).getByRole('list', { name: 'Network links' }); + const conflicts = within(network).getAllByRole('listitem').filter(item => item.getAttribute('data-state') === 'conflict'); + expect(conflicts).toHaveLength(2); + expect(conflicts[0]).toHaveTextContent('2 Cable lanes name this position. Neither is treated as current.'); + expect(conflicts[0]).toHaveTextContent('! dac-01'); + }); +}); + +describe('Device detail connection view', () => { + it('appears on the Device page and links the recorded power cable', () => { + const inventory = toInventory(fixturePhysicalClaims, fixturePhysicalDevices, fixturePhysicalRecords); + render(); + const section = screen.getByRole('region', { name: 'Connections' }); + expect(within(section).getByText('Cable records, not live link state')).toBeInTheDocument(); + fireEvent.click(within(section).getByRole('link', { name: /Power supply 1 to Feed A · Outlet 1 via cable Server power cable/ })); + expect(screen.getByRole('heading', { name: 'Server power cable' })).toBeInTheDocument(); + }); +}); diff --git a/ui/provider/src/components/device-connections.tsx b/ui/provider/src/components/device-connections.tsx new file mode 100644 index 00000000..a788db46 --- /dev/null +++ b/ui/provider/src/components/device-connections.tsx @@ -0,0 +1,274 @@ +import { Button } from '@datum-cloud/datum-ui/button'; +import { Table, TableBody, TableCaption, TableCell, TableHead, TableHeader, TableRow } from '@datum-cloud/datum-ui/table'; +import { useId, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent, type ReactNode } from 'react'; +import { Link } from 'react-router'; +import type { Device } from '../../../shared/fleet-api'; +import type { Inventory } from '../inventory'; +import { + connectionGroups, deviceConnections, DIAGRAM_LINK_LIMIT, linkStateGlyph, linkStateWords, localLabel, peerLabel, remotePortLabel, stateCounts, + type ConnectionGroup, type ConnectionLink, type LinkState, type PeerEnd, type TraceHop, +} from '../lib/device-connections'; + +type Href = (kind: string, namespace?: string, name?: string) => string; +type View = 'diagram' | 'list'; + +const STATES: LinkState[] = ['cabled', 'none', 'conflict', 'unavailable', 'catalog']; +const LEFT: ConnectionGroup[] = ['power']; + +function Glyph({ state }: { state: LinkState }) { + return ; +} + +function StateText({ state }: { state: LinkState }) { + return {linkStateWords[state]}; +} + +function countsText(links: ConnectionLink[]) { + const counts = stateCounts(links); + return STATES.filter(state => counts[state]).map(state => `${counts[state]} ${linkStateWords[state].toLowerCase()}`).join(', '); +} + +function linksWord(count: number) { + return `${count} ${count === 1 ? 'link' : 'links'}`; +} + +function cableText(link: ConnectionLink) { + if (!link.cable) return link.state === 'catalog' ? 'Not recorded on this Device' : 'No cable recorded'; + const lane = link.cable.laneCount > 1 ? ` · lane ${link.cable.laneID} of ${link.cable.laneCount}` : ''; + return `${link.cable.medium ?? 'Medium not recorded'}${lane}`; +} + +function PeerTarget({ peer, namespace, href, roving, label }: { peer?: PeerEnd; namespace?: string; href: Href; roving?: boolean; label?: string }) { + if (!peer) return Unknown; + if (peer.access !== 'readable') return {peerLabel(peer)}; + return {peerLabel(peer)}; +} + +function Trace({ hops, namespace, href, roving }: { hops: TraceHop[]; namespace?: string; href: Href; roving?: boolean }) { + if (!hops.length) return null; + return ( +
          + {hops.map((hop, index) => ( +
        1. + via internal path to {hop.via.componentName ?? hop.via.componentID}{hop.via.position > 1 ? ` · position ${hop.via.position}` : ''} + {hop.cable ? <>, then {hop.cable.label} to : `: ${linkStateWords[hop.state].toLowerCase()}`} + {hop.reasons.length > 0 && {hop.reasons.join(' ')}} +
        2. + ))} +
        + ); +} + +function LocalDetail({ link }: { link: ConnectionLink }) { + const type = link.component?.type ?? link.template?.type; + const connector = link.component?.connector ?? link.template?.connector; + return {[type ?? 'Not on this Device', connector ?? 'Connector not recorded'].join(' · ')}{link.internal ? ` · internal path to ${link.internal.componentName ?? link.internal.componentID}${link.internal.position > 1 ? ` position ${link.internal.position}` : ''}` : ''}; +} + +function peerDetail(link: ConnectionLink) { + if (link.state === 'none') return 'Unknown · not free'; + if (link.state === 'catalog') return 'Not recorded'; + if (!link.peer) return undefined; + if (link.peer.access === 'denied') return 'You cannot read this peer'; + if (link.peer.access === 'missing') return `${link.peer.kind} record not found`; + return link.peer.supply ? `Power feed · recorded rating ${link.peer.supply}` : link.peer.kind === 'PowerFeed' ? 'Power feed' : 'Device'; +} + +function linkLabel(link: ConnectionLink) { + const cable = link.cable ? ` via cable ${link.cable.label}, ${cableText(link)}` : ''; + return `${localLabel(link)} to ${link.peer ? peerLabel(link.peer) : 'unknown peer'}${cable}: ${linkStateWords[link.state]}`; +} + +function DiagramRow({ link, namespace, href }: { link: ConnectionLink; namespace?: string; href: Href }) { + return ( +
      • +
        + + {localLabel(link)} + {link.cable ? remotePortLabel(link.peer) : ''} + +
        +
        + {link.cable ? : {link.state === 'catalog' ? 'Catalog only' : 'Unknown'}} + {peerDetail(link)} + + {link.reasons.length > 0 && {link.reasons.join(' ')}} +
        +
      • + ); +} + +function DiagramGroup({ group, title, links, collapsed, namespace, href, onToggle }: { group: ConnectionGroup; title: string; links: ConnectionLink[]; collapsed: boolean; namespace?: string; href: Href; onToggle: () => void }) { + const rows =
          {links.map(link => )}
        ; + const summary = `${title} · ${linksWord(links.length)}`; + return ( +
      • + {collapsed ? ( +
        + {summary} {countsText(links)} + {rows} +
        + ) : ( + <> +

        {summary} {countsText(links)}

        + {rows} + + )} + {group === 'power' &&

        Power redundancy unknown. Separate inlets or feeds do not prove independent supply.

        } +
      • + ); +} + +function Diagram({ device, groups, collapsed, namespace, href }: { device: Device; groups: { group: ConnectionGroup; title: string; links: ConnectionLink[] }[]; collapsed: boolean; namespace?: string; href: Href }) { + const container = useRef(null); + const active = useRef(null); + const [, setRevision] = useState(0); + const visible = () => [...(container.current?.querySelectorAll('[data-connection-roving]') ?? [])].filter(element => !element.closest('details:not([open])')); + // One tab stop for the whole drawing; arrow keys move between its links. + useLayoutEffect(() => { + const items = visible(); + const current = items.find(item => item === active.current) ?? items[0]; + for (const item of items) item.tabIndex = item === current ? 0 : -1; + for (const summary of container.current?.querySelectorAll('details:not([open]) [data-connection-roving]') ?? []) summary.tabIndex = -1; + }); + const onKeyDown = (event: KeyboardEvent) => { + const items = visible(); + const index = items.indexOf(document.activeElement as HTMLElement); + if (index === -1) return; + const next = event.key === 'ArrowDown' || event.key === 'ArrowRight' ? index + 1 : event.key === 'ArrowUp' || event.key === 'ArrowLeft' ? index - 1 : event.key === 'Home' ? 0 : event.key === 'End' ? items.length - 1 : undefined; + if (next === undefined) return; + event.preventDefault(); + const target = items[Math.max(0, Math.min(items.length - 1, next))]; + for (const item of items) item.tabIndex = item === target ? 0 : -1; + active.current = target; + target.focus(); + }; + const side = (left: boolean) => groups.filter(item => LEFT.includes(item.group) === left); + const all = groups.flatMap(item => item.links); + const renderSide = (left: boolean, label: string) => { + const items = side(left); + return items.length ? ( +
          + {items.map(item => setRevision(value => value + 1)} />)} +
        + ) : ; } -function RackFace({ rack, slots, side }: { rack: PhysicalRecord; slots: EquipmentPlacement[]; side: 'front' | 'rear' }) { - const height = rack.spec.heightUnits!; - const plans = slots.map(slot => ({ slot, ...equipmentGeometry(slot, rack)! })) - .filter(plan => plan.face === side || plan.fullDepth === true) - .sort((first, second) => first.position - second.position || first.slot.key.localeCompare(second.slot.key)); +function RackFace({ occupants, height, side }: { occupants: RackOccupant[]; height: number; side: RackFaceName }) { + const plans = faceOccupancy(occupants, side) + .sort((first, second) => first.position - second.position || first.entry.key.localeCompare(second.entry.key)); const laneEnds: number[] = []; const placed = plans.map(plan => { let lane = laneEnds.findIndex(end => end < plan.position); @@ -43,12 +43,16 @@ function RackFace({ rack, slots, side }: { rack: PhysicalRecord; slots: Equipmen })} {placed.map(plan => { const top = plan.position + plan.height - 1; - const overlap = plans.some(other => other.slot.key !== plan.slot.key && other.position <= top && other.position + other.height > plan.position); - const name = plan.slot.record.spec.displayName || plan.slot.record.metadata.name; + const overlap = plan.conflicts.length > 0; + const record = plan.entry.record; + const recordName = record.spec.displayName || record.metadata.name; + // The far face of a full-depth (or unknown-depth) device shows its + // chassis rear, whichever rack face it is mounted on. + const name = plan.far ? `Rear of ${recordName}` : recordName; const range = plan.height === 1 ? `U${plan.position}` : `U${plan.position}–U${top}`; - const label = `${name} · ${range} · ${plan.height}U · ${plan.slot.basis}${overlap ? ' · overlapping placements, review required' : ''}`; - return
      • - {overlap && }{name}{plan.height > 1 && {range} · {plan.height}U} + const label = [name, range, `${plan.height}U`, plan.entry.basis, plan.far ? `mounted ${plan.mounted}` : undefined, depthLabel(plan.depth), overlap ? 'records disagree: overlapping placements on this face' : undefined].filter(Boolean).join(' · '); + return
      • + {overlap && }{plan.far ? rear of : null}{recordName}{(plan.height > 1 || plan.depth.source === 'unknown') && {[plan.height > 1 ? `${range} · ${plan.height}U` : undefined, plan.depth.source === 'unknown' ? 'depth unknown' : undefined].filter(Boolean).join(' · ')}}
      • ; })} @@ -59,6 +63,7 @@ export function RackOverview({ rack, inventory }: { rack: PhysicalRecord; invent const [face, setFace] = useState<'both' | 'front' | 'rear'>('both'); const slots = equipmentPlacements(inventory).filter(slot => slot.record.metadata.namespace === rack.metadata.namespace && slot.placement.rackRef?.name === rack.metadata.name); const positioned = slots.filter(slot => equipmentGeometry(slot, rack)); + const occupants = rackOccupants(positioned, rack, inventory); const nonRacked = slots.filter(slot => slot.placement.scope === 'NonRackUnitMount'); const unpositioned = slots.filter(slot => !equipmentGeometry(slot, rack) && slot.placement.scope !== 'NonRackUnitMount'); const denied = !!inventory.issues?.DeviceClaim && !slots.length; @@ -68,8 +73,8 @@ export function RackOverview({ rack, inventory }: { rack: PhysicalRecord; invent
        Equipment & registration history diff --git a/ui/provider/src/components/physical-inventory.css b/ui/provider/src/components/physical-inventory.css index cdcc815a..d16e8352 100644 --- a/ui/provider/src/components/physical-inventory.css +++ b/ui/provider/src/components/physical-inventory.css @@ -82,6 +82,10 @@ .inventory-rack-overlap { flex:none; font-weight:700; } .inventory-rack-plan a:focus-visible { outline:2px solid var(--ring); outline-offset:-2px; } .inventory-rack-plan small { flex:none; overflow:hidden; text-overflow:ellipsis; font-size:8px; line-height:12px; } +.inventory-rack-plan-far { border-style:dashed; background:repeating-linear-gradient(135deg,transparent 0 5px,var(--muted) 5px 7px); color:var(--muted-foreground); } +.inventory-rack-plan-far a { color:var(--muted-foreground); } +.inventory-rack-plan-side { font-style:italic; } +.inventory-rack-plan[data-depth="unknown"]:not(.inventory-rack-plan-far) { border-style:dotted; } .inventory-face-switch { display:flex; gap:4px; } .inventory-face-switch button { flex:1; } .inventory-equipment-sections { display:grid; gap:16px; min-width:0; } @@ -154,6 +158,11 @@ [data-state="none"] > .inventory-connection-peer { border-style:dotted; color:var(--muted-foreground); background:transparent; } [data-state="catalog"] > .inventory-connection-peer { border-style:dashed; color:var(--muted-foreground); background:repeating-linear-gradient(135deg,transparent 0 6px,var(--muted) 6px 9px); } .fleet-inventory .inventory-connection-reason { color:var(--foreground); } +.inventory-connection-ports:has(.inventory-connection-face) { flex-wrap:wrap; row-gap:0; } +.inventory-connection-face { order:3; flex-basis:100%; font-size:11px; color:var(--muted-foreground); } +[data-side="left"] .inventory-connection-face { text-align:right; } +.inventory-connection-face-title { font-size:11px; font-weight:600; color:var(--muted-foreground); text-transform:uppercase; letter-spacing:.04em; margin:6px 0 2px!important; padding:0 8px; } +.fleet-inventory .inventory-connection-check { display:block; color:var(--foreground); font-style:italic; } .inventory-connection-trace { margin-top:4px; font-size:11px; display:grid; gap:2px; } .inventory-connection-tables { display:grid; gap:12px; } .fleet-inventory .inventory-connection-tables caption { caption-side:top; } diff --git a/ui/provider/src/components/physical-inventory.tsx b/ui/provider/src/components/physical-inventory.tsx index 88bdbfbd..c335dd06 100644 --- a/ui/provider/src/components/physical-inventory.tsx +++ b/ui/provider/src/components/physical-inventory.tsx @@ -31,6 +31,7 @@ import { INVENTORY_NAMESPACE } from '../lib/inventory-namespace'; import { InventoryDirectoryHeading, InventoryToolbar } from './inventory-directory-heading'; import { InventoryPageTitle, inventoryDirectoryPath, inventoryReturnSearch } from './inventory-page-title'; import { DeviceConnections } from './device-connections'; +import { depthLabel, deviceDepth } from '../lib/device-depth'; type Kind = 'Site' | 'Device' | 'Facility' | 'Rack' | 'DeviceClaim' | 'Cable' | 'PowerFeed' | 'Manufacturer' | 'DeviceType'; type RecordEntry = { kind: Kind; record: RawDevice | RawDeviceClaim | PhysicalRecord }; @@ -330,9 +331,9 @@ export function PhysicalInventory({ inventory: source, onRetry, showNavigation = {kind === 'DeviceType' && <> {physical?.spec.manufacturerRef && reference('Manufacturer', namespace, physical.spec.manufacturerRef.name)} {physical?.spec.model} - {physical?.spec.modelShape ? `${physical.spec.modelShape.heightUnits ?? 'Unknown'}U · ${physical.spec.modelShape.fullDepth === undefined ? 'Depth unknown' : physical.spec.modelShape.fullDepth ? 'Full depth' : 'Partial depth'}` : 'Unknown'} - {physical?.spec.componentTemplates?.map(template =>
        {template.name} · {template.type} · {template.connector ?? 'Connector unknown'} · {template.positions ?? 1} position(s)
        ) ?? 'Not recorded'}
        - Reference defaults only. No installed assets, measured geometry, observed occupancy, or automatic materialization. + {`${physical?.spec.modelShape?.heightUnits ?? 'Unknown'}U · ${physical?.spec.modelShape?.fullDepth === false ? 'Half depth' : physical?.spec.modelShape?.fullDepth ? 'Full depth' : 'Depth unknown'}`} + {physical?.spec.componentTemplates?.map(template =>
        {template.name} · {template.type} · {template.connector ?? 'Connector unknown'} · {template.positions ?? 1} position(s) · {template.face ? `chassis ${template.face.toLowerCase()}` : 'chassis face unknown'}
        ) ?? 'Not recorded'}
        + Reference defaults only. No installed assets, measured geometry, observed occupancy, or automatic materialization. Template faces are relative to the chassis; a Device component with the same id inherits its face. } {kind === 'Facility' && <> {facilityIdentifiers(record as PhysicalRecord)} @@ -346,6 +347,7 @@ export function PhysicalInventory({ inventory: source, onRetry, showNavigation = {modelLabel(device.spec.identity)} {catalog ? reference('DeviceType', namespace, catalog.model.metadata.name) : device.spec.deviceTypeRef ? 'Catalog unavailable · showing recorded observation' : 'Not assigned · showing recorded observation'} {catalog?.model.spec.modelShape?.heightUnits === undefined ? 'Unknown' : `${catalog.model.spec.modelShape.heightUnits}U · not measured or used for occupancy`} + {`${depthLabel(deviceDepth(device, inventory))} · ${deviceDepth(device, inventory).full ? 'occupies both rack faces' : 'occupies its mounted face only'} · not measured`} {device.spec.lifecycle ?? 'Active'} {device.spec.identity.serial} {device.spec.assetTag} diff --git a/ui/provider/src/lib/depth-fixtures.ts b/ui/provider/src/lib/depth-fixtures.ts new file mode 100644 index 00000000..8c8b7c80 --- /dev/null +++ b/ui/provider/src/lib/depth-fixtures.ts @@ -0,0 +1,99 @@ +// Synthetic rack, catalog and cabling records that exercise device depth and +// component faces. Used by tests and by the local fixture preview. Every name, +// serial and identifier is invented. + +import type { RawDevice, RawDeviceClaim } from '../inventory'; +import type { CableEndpoint, ComponentTemplate, PhysicalComponent, PhysicalRecord, RackFace } from '../../../shared/fleet-api'; + +const NS = 'default'; +export const DEPTH_RACK = 'rack-02'; + +type Template = ComponentTemplate; +const T = (id: string, name: string, type: Template['type'], face?: Template['face'], extra: Partial