diff --git a/config/components/inventory/roles/kustomization.yaml b/config/components/inventory/roles/kustomization.yaml index aa7b7182..1e1fc5d3 100644 --- a/config/components/inventory/roles/kustomization.yaml +++ b/config/components/inventory/roles/kustomization.yaml @@ -3,3 +3,4 @@ kind: Kustomization resources: - viewer.yaml - editor.yaml + - manager.yaml diff --git a/config/components/inventory/roles/manager.yaml b/config/components/inventory/roles/manager.yaml new file mode 100644 index 00000000..0d3a4970 --- /dev/null +++ b/config/components/inventory/roles/manager.yaml @@ -0,0 +1,30 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: Role +metadata: + name: fleet.datumapis.com-inventory-manager + annotations: + kubernetes.io/display-name: Fleet Inventory Manager + kubernetes.io/description: Create and maintain physical inventory records without deletion or operational control +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/devices.create + - fleet.datumapis.com/devices.update + - fleet.datumapis.com/devices.patch + - fleet.datumapis.com/facilities.create + - fleet.datumapis.com/facilities.update + - fleet.datumapis.com/facilities.patch + - fleet.datumapis.com/racks.create + - fleet.datumapis.com/racks.update + - fleet.datumapis.com/racks.patch + - fleet.datumapis.com/cables.create + - fleet.datumapis.com/cables.update + - fleet.datumapis.com/cables.patch + - fleet.datumapis.com/powerfeeds.create + - fleet.datumapis.com/powerfeeds.update + - fleet.datumapis.com/powerfeeds.patch diff --git a/docs/development/staff-inventory-ui.md b/docs/development/staff-inventory-ui.md new file mode 100644 index 00000000..bad4b16f --- /dev/null +++ b/docs/development/staff-inventory-ui.md @@ -0,0 +1,251 @@ +# 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 +`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 | +| --- | --- | +| 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. diff --git a/docs/operations/netbox-physical-import.md b/docs/operations/netbox-physical-import.md index 150e0401..b7de9fae 100644 --- a/docs/operations/netbox-physical-import.md +++ b/docs/operations/netbox-physical-import.md @@ -4,7 +4,9 @@ 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. +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 @@ -191,7 +193,7 @@ source comparison when separately requested and authorized by the operator. 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. + 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, @@ -200,17 +202,20 @@ source comparison when separately requested and authorized by the operator. 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 +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. Alternatively, + if Flux ownership is chosen for those new records, stage them additively in the + 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. diff --git a/docs/operations/physical-inventory.md b/docs/operations/physical-inventory.md index edab0661..3123c6b0 100644 --- a/docs/operations/physical-inventory.md +++ b/docs/operations/physical-inventory.md @@ -11,14 +11,16 @@ 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 primary workflow is **manual entry, operator review, and explicit GitOps -ownership**. NetBox, bulk conversion, and a source reconciliation service are not +The primary workflow is **manual entry, operator review, and explicit record +ownership**. Authorized direct API creation is supported for new/imported 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. | 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 existing GitOps 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) | | `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 | @@ -28,8 +30,8 @@ describes a separately invoked review aid, not an automated migration. | Aspect | State | | --- | --- | | CRDs and Go types | Implemented in `config/components/inventory` and `internal/api/inventory/v1alpha1`. | -| 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. | +| 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. | | Hardware qualification | None. Records hold operator-entered facts, not verified hardware state. | @@ -66,13 +68,37 @@ project control plane serves the kinds. Access is what keeps consumers out: | --- | --- | | `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` | +| `fleet.datumapis.com-inventory-manager` | The viewer role plus `create`, `update`, `patch`; no deletion or status writes | -No `metal.datumapis.com` role includes or inherits either. The consumer, +No `metal.datumapis.com` role includes or inherits any inventory role. 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 manager is a separate least-privilege role for explicitly authorized inventory +staff; it does not change the existing editor or give staff viewers write access. +It grants only the six physical kinds, never hardware operations, allocation, +installation, Metal, networking, billing, or IAM administration. Fleet owns this +role and its tests; environment-specific groups and project bindings belong in +the infrastructure repository. The role ships through `config/milo`; shipping a +role does not bind it or add members in any environment. + +A Project resource selector is project-wide, not a namespace filter. These +ProtectedResources have Project parents, and a binding's `metadata.namespace` +locates the IAM object, not the inventory it authorizes. Choosing `default` in a +portal request is a convention, not isolation from other namespaces in that +project. Require a separately supported and tested authorization boundary before +promising namespace-only access. + +The manager contract is validated offline with +`go test ./internal/api/inventory/v1alpha1`. That checks manifests, not deployed +authorization. Before adding named members, an environment owner must validate +the deployed role and binding, and explicitly decide record-writer ownership. +IAM capability does not transfer ownership away from Flux or permit two writers +for the same records. Existing GitOps-owned records remain GitOps-owned until a +separate reviewed transition; this role does not perform that transition. + 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 @@ -274,9 +300,12 @@ 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 -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, +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 +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. +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/iam_test.go b/internal/api/inventory/v1alpha1/iam_test.go index 716d54ee..0c969000 100644 --- a/internal/api/inventory/v1alpha1/iam_test.go +++ b/internal/api/inventory/v1alpha1/iam_test.go @@ -103,22 +103,45 @@ func TestInventoryRolesSplitReadFromWrite(t *testing.T) { 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) + wantVerbs := map[string][]string{ + "fleet.datumapis.com-inventory-viewer": {"get", "list", "watch"}, + "fleet.datumapis.com-inventory-editor": {"create", "update", "patch", "delete"}, + "fleet.datumapis.com-inventory-manager": {"create", "update", "patch"}, } - 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(roles) != len(wantVerbs) { + t.Fatalf("want exactly viewer, editor and manager roles, got %v", roles) } - if len(editor.Spec.Inherited) != 1 || editor.Spec.Inherited[0].Name != viewer.Metadata.Name { - t.Fatal("editor must inherit the viewer role") + for name, verbs := range wantVerbs { + t.Run(name, func(t *testing.T) { + current, ok := roles[name] + if !ok { + t.Fatalf("missing role %s", name) + } + var expected []string + for _, resource := range []string{"deviceclaims", "devices", "facilities", "racks", "cables", "powerfeeds"} { + for _, verb := range verbs { + expected = append(expected, GroupVersion.Group+"/"+resource+"."+verb) + } + } + actual := slices.Clone(current.Spec.Included) + slices.Sort(expected) + slices.Sort(actual) + if !slices.Equal(actual, expected) { + t.Fatalf("%s permissions = %v, want %v", name, actual, expected) + } + for _, permission := range actual { + if !declared[permission] { + t.Fatalf("role permission %s has no ProtectedResource", permission) + } + } + if name == "fleet.datumapis.com-inventory-viewer" { + if len(current.Spec.Inherited) != 0 { + t.Fatal("viewer must not inherit additional permissions") + } + } else if len(current.Spec.Inherited) != 1 || current.Spec.Inherited[0].Name != "fleet.datumapis.com-inventory-viewer" { + t.Fatal("editor and manager must inherit only the viewer role") + } + }) } } diff --git a/ui/provider/README.md b/ui/provider/README.md index fe7f6b4e..d280c50e 100644 --- a/ui/provider/README.md +++ b/ui/provider/README.md @@ -4,7 +4,7 @@ A [staff-portal](https://github.com/datum-cloud/staff-portal) plugin for the provider project's Bare Metal resources (`metal.datumapis.com`). It is a Module Federation remote: the portal fetches `plugin-manifest.json` and `remoteEntry.js` server-side and mounts its pages under `/plugins//`, with a **Bare Metal** item under -Operations in the navigation. The page has three tabs: +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 @@ -20,16 +20,17 @@ 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, 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. +- **Inventory** (`inventory`) is a read-only hardware directory, starting with + Devices rather than installation claims. Six searchable categories cover + Devices, Facilities, Racks, Claims, Cables, and Power feeds. Query-string detail + 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` + route remains available for existing links. The plugin never writes inventory; + this is a UI limitation, not a requirement to manage inventory through Git. The portal proxy forwards the staff member's own token, so creating capacity, profiles and classes needs a Bare Metal role with `machinecapacities.create`, @@ -87,15 +88,27 @@ 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 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 -[optional source-comparison guide](../../docs/operations/netbox-physical-import.md) -for the offline Flux handoff and the distinction between records and readiness. +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 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 +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 +theme with Tailwind. That stylesheet is not imported by federated pages; the host +still supplies its design system. Inventory-specific CSS is scoped under +`.fleet-inventory` and shipped with the existing remote. No second app or host +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`. diff --git a/ui/provider/package.json b/ui/provider/package.json index eed856c4..fa534863 100644 --- a/ui/provider/package.json +++ b/ui/provider/package.json @@ -34,6 +34,7 @@ }, "devDependencies": { "@module-federation/vite": "^1.16.16", + "@tailwindcss/vite": "4.2.1", "@testing-library/jest-dom": "^6.6.3", "@testing-library/react": "^16.1.0", "@types/node": "^26.6.5", @@ -41,6 +42,7 @@ "@types/react-dom": "^19.2.3", "@vitejs/plugin-react": "^5.2.0", "jsdom": "^25.0.1", + "tailwindcss": "4.2.1", "typescript": "^6.0.3", "vite": "^7.3.5", "vitest": "^4.1.12" diff --git a/ui/provider/pnpm-lock.yaml b/ui/provider/pnpm-lock.yaml index a0e268a0..d94caf2f 100644 --- a/ui/provider/pnpm-lock.yaml +++ b/ui/provider/pnpm-lock.yaml @@ -70,7 +70,10 @@ importers: devDependencies: '@module-federation/vite': specifier: ^1.16.16 - version: 1.23.7(typescript@6.0.3)(vite@7.3.7(@types/node@26.6.6)) + version: 1.23.7(typescript@6.0.3)(vite@7.3.7(@types/node@26.6.6)(jiti@2.7.0)(lightningcss@1.31.1)) + '@tailwindcss/vite': + specifier: 4.2.1 + version: 4.2.1(vite@7.3.7(@types/node@26.6.6)(jiti@2.7.0)(lightningcss@1.31.1)) '@testing-library/jest-dom': specifier: ^6.6.3 version: 6.9.1 @@ -88,19 +91,22 @@ importers: version: 19.3.0(@types/react@19.3.0) '@vitejs/plugin-react': specifier: ^5.2.0 - version: 5.2.0(vite@7.3.7(@types/node@26.6.6)) + version: 5.2.0(vite@7.3.7(@types/node@26.6.6)(jiti@2.7.0)(lightningcss@1.31.1)) jsdom: specifier: ^25.0.1 version: 25.0.1 + tailwindcss: + specifier: 4.2.1 + version: 4.2.1 typescript: specifier: ^6.0.3 version: 6.0.3 vite: specifier: ^7.3.5 - version: 7.3.7(@types/node@26.6.6) + version: 7.3.7(@types/node@26.6.6)(jiti@2.7.0)(lightningcss@1.31.1) vitest: specifier: ^4.1.12 - version: 4.1.12(@types/node@26.6.6)(jsdom@25.0.1)(vite@7.3.7(@types/node@26.6.6)) + version: 4.1.12(@types/node@26.6.6)(jsdom@25.0.1)(vite@7.3.7(@types/node@26.6.6)(jiti@2.7.0)(lightningcss@1.31.1)) packages: @@ -1269,6 +1275,100 @@ packages: '@standard-schema/spec@1.1.0': resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==} + '@tailwindcss/node@4.2.1': + resolution: {integrity: sha512-jlx6sLk4EOwO6hHe1oCGm1Q4AN/s0rSrTTPBGPM0/RQ6Uylwq17FuU8IeJJKEjtc6K6O07zsvP+gDO6MMWo7pg==} + + '@tailwindcss/oxide-android-arm64@4.2.1': + resolution: {integrity: sha512-eZ7G1Zm5EC8OOKaesIKuw77jw++QJ2lL9N+dDpdQiAB/c/B2wDh0QPFHbkBVrXnwNugvrbJFk1gK2SsVjwWReg==} + engines: {node: '>= 20'} + cpu: [arm64] + os: [android] + + '@tailwindcss/oxide-darwin-arm64@4.2.1': + resolution: {integrity: sha512-q/LHkOstoJ7pI1J0q6djesLzRvQSIfEto148ppAd+BVQK0JYjQIFSK3JgYZJa+Yzi0DDa52ZsQx2rqytBnf8Hw==} + engines: {node: '>= 20'} + cpu: [arm64] + os: [darwin] + + '@tailwindcss/oxide-darwin-x64@4.2.1': + resolution: {integrity: sha512-/f/ozlaXGY6QLbpvd/kFTro2l18f7dHKpB+ieXz+Cijl4Mt9AI2rTrpq7V+t04nK+j9XBQHnSMdeQRhbGyt6fw==} + engines: {node: '>= 20'} + cpu: [x64] + os: [darwin] + + '@tailwindcss/oxide-freebsd-x64@4.2.1': + resolution: {integrity: sha512-5e/AkgYJT/cpbkys/OU2Ei2jdETCLlifwm7ogMC7/hksI2fC3iiq6OcXwjibcIjPung0kRtR3TxEITkqgn0TcA==} + engines: {node: '>= 20'} + cpu: [x64] + os: [freebsd] + + '@tailwindcss/oxide-linux-arm-gnueabihf@4.2.1': + resolution: {integrity: sha512-Uny1EcVTTmerCKt/1ZuKTkb0x8ZaiuYucg2/kImO5A5Y/kBz41/+j0gxUZl+hTF3xkWpDmHX+TaWhOtba2Fyuw==} + engines: {node: '>= 20'} + cpu: [arm] + os: [linux] + + '@tailwindcss/oxide-linux-arm64-gnu@4.2.1': + resolution: {integrity: sha512-CTrwomI+c7n6aSSQlsPL0roRiNMDQ/YzMD9EjcR+H4f0I1SQ8QqIuPnsVp7QgMkC1Qi8rtkekLkOFjo7OlEFRQ==} + engines: {node: '>= 20'} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@tailwindcss/oxide-linux-arm64-musl@4.2.1': + resolution: {integrity: sha512-WZA0CHRL/SP1TRbA5mp9htsppSEkWuQ4KsSUumYQnyl8ZdT39ntwqmz4IUHGN6p4XdSlYfJwM4rRzZLShHsGAQ==} + engines: {node: '>= 20'} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@tailwindcss/oxide-linux-x64-gnu@4.2.1': + resolution: {integrity: sha512-qMFzxI2YlBOLW5PhblzuSWlWfwLHaneBE0xHzLrBgNtqN6mWfs+qYbhryGSXQjFYB1Dzf5w+LN5qbUTPhW7Y5g==} + engines: {node: '>= 20'} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@tailwindcss/oxide-linux-x64-musl@4.2.1': + resolution: {integrity: sha512-5r1X2FKnCMUPlXTWRYpHdPYUY6a1Ar/t7P24OuiEdEOmms5lyqjDRvVY1yy9Rmioh+AunQ0rWiOTPE8F9A3v5g==} + engines: {node: '>= 20'} + cpu: [x64] + os: [linux] + libc: [musl] + + '@tailwindcss/oxide-wasm32-wasi@4.2.1': + resolution: {integrity: sha512-MGFB5cVPvshR85MTJkEvqDUnuNoysrsRxd6vnk1Lf2tbiqNlXpHYZqkqOQalydienEWOHHFyyuTSYRsLfxFJ2Q==} + engines: {node: '>=14.0.0'} + cpu: [wasm32] + bundledDependencies: + - '@napi-rs/wasm-runtime' + - '@emnapi/core' + - '@emnapi/runtime' + - '@tybys/wasm-util' + - '@emnapi/wasi-threads' + - tslib + + '@tailwindcss/oxide-win32-arm64-msvc@4.2.1': + resolution: {integrity: sha512-YlUEHRHBGnCMh4Nj4GnqQyBtsshUPdiNroZj8VPkvTZSoHsilRCwXcVKnG9kyi0ZFAS/3u+qKHBdDc81SADTRA==} + engines: {node: '>= 20'} + cpu: [arm64] + os: [win32] + + '@tailwindcss/oxide-win32-x64-msvc@4.2.1': + resolution: {integrity: sha512-rbO34G5sMWWyrN/idLeVxAZgAKWrn5LiR3/I90Q9MkA67s6T1oB0xtTe+0heoBvHSpbU9Mk7i6uwJnpo4u21XQ==} + engines: {node: '>= 20'} + cpu: [x64] + os: [win32] + + '@tailwindcss/oxide@4.2.1': + resolution: {integrity: sha512-yv9jeEFWnjKCI6/T3Oq50yQEOqmpmpfzG1hcZsAOaXFQPfzWprWrlHSdGPEF3WQTi8zu8ohC9Mh9J470nT5pUw==} + engines: {node: '>= 20'} + + '@tailwindcss/vite@4.2.1': + resolution: {integrity: sha512-TBf2sJjYeb28jD2U/OhwdW0bbOsxkWPwQ7SrqGf9sVcoYwZj7rkXljroBO9wKBut9XnmQLXanuDUeqQK0lGg/w==} + peerDependencies: + vite: ^5.2.0 || ^6 || ^7 + '@tanstack/query-core@5.101.4': resolution: {integrity: sha512-gNwcvOJcRbLWPOLG/2OBm+zM+Yv+MKsXKEOWC57USuZDEsI71hEErQsiEGx5wX9rzWWkfwM0fVSPoiIFSsxfiw==} @@ -1542,6 +1642,10 @@ packages: resolution: {integrity: sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==} engines: {node: '>=6'} + detect-libc@2.1.2: + resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} + engines: {node: '>=8'} + detect-node-es@1.1.0: resolution: {integrity: sha512-ypdmJU/TbBby2Dxibuv7ZLW3Bs1QEmM7nHjEANfohJLvE0XVujisn1qPJcZxg+qDucsr+bP6fLD1rPS3AhJ7EQ==} @@ -1561,6 +1665,10 @@ packages: electron-to-chromium@1.5.468: resolution: {integrity: sha512-8XdEp3sIqO+PzmVPxhzqHq/3+yCxp44m27cm2WY1sRn3ZhwKyKmqSi2hx6gEhmnOXmh8NUuYE00z6Onzn5m6DA==} + enhanced-resolve@5.27.0: + resolution: {integrity: sha512-Do6BB2xzlcc/odFg+XEYyneAx4T/WfywO71yw9ePS2tVfRsf7JVR4mUeELadIeHzixkzbG5DpluiEFPi2WGfYQ==} + engines: {node: '>=10.13.0'} + entities@6.0.1: resolution: {integrity: sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==} engines: {node: '>=0.12'} @@ -1660,6 +1768,9 @@ packages: resolution: {integrity: sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==} engines: {node: '>= 0.4'} + graceful-fs@4.2.12: + resolution: {integrity: sha512-iuyGF2E4oafQfPsRrG2wtY2ILupMhvtdrhzrxB+0VcjsPpSPttpfYdjnGFGsTi5MaJFjI1jOKHPQ6UTbTj9TAw==} + has-symbols@1.1.0: resolution: {integrity: sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==} engines: {node: '>= 0.4'} @@ -1709,6 +1820,10 @@ packages: peerDependencies: ws: '*' + jiti@2.7.0: + resolution: {integrity: sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==} + hasBin: true + js-tokens@4.0.0: resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==} @@ -1743,6 +1858,80 @@ packages: engines: {node: '>=6'} hasBin: true + lightningcss-android-arm64@1.31.1: + resolution: {integrity: sha512-HXJF3x8w9nQ4jbXRiNppBCqeZPIAfUo8zE/kOEGbW5NZvGc/K7nMxbhIr+YlFlHW5mpbg/YFPdbnCh1wAXCKFg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [android] + + lightningcss-darwin-arm64@1.31.1: + resolution: {integrity: sha512-02uTEqf3vIfNMq3h/z2cJfcOXnQ0GRwQrkmPafhueLb2h7mqEidiCzkE4gBMEH65abHRiQvhdcQ+aP0D0g67sg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [darwin] + + lightningcss-darwin-x64@1.31.1: + resolution: {integrity: sha512-1ObhyoCY+tGxtsz1lSx5NXCj3nirk0Y0kB/g8B8DT+sSx4G9djitg9ejFnjb3gJNWo7qXH4DIy2SUHvpoFwfTA==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [darwin] + + lightningcss-freebsd-x64@1.31.1: + resolution: {integrity: sha512-1RINmQKAItO6ISxYgPwszQE1BrsVU5aB45ho6O42mu96UiZBxEXsuQ7cJW4zs4CEodPUioj/QrXW1r9pLUM74A==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [freebsd] + + lightningcss-linux-arm-gnueabihf@1.31.1: + resolution: {integrity: sha512-OOCm2//MZJ87CdDK62rZIu+aw9gBv4azMJuA8/KB74wmfS3lnC4yoPHm0uXZ/dvNNHmnZnB8XLAZzObeG0nS1g==} + engines: {node: '>= 12.0.0'} + cpu: [arm] + os: [linux] + + lightningcss-linux-arm64-gnu@1.31.1: + resolution: {integrity: sha512-WKyLWztD71rTnou4xAD5kQT+982wvca7E6QoLpoawZ1gP9JM0GJj4Tp5jMUh9B3AitHbRZ2/H3W5xQmdEOUlLg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [linux] + libc: [glibc] + + lightningcss-linux-arm64-musl@1.31.1: + resolution: {integrity: sha512-mVZ7Pg2zIbe3XlNbZJdjs86YViQFoJSpc41CbVmKBPiGmC4YrfeOyz65ms2qpAobVd7WQsbW4PdsSJEMymyIMg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [linux] + libc: [musl] + + lightningcss-linux-x64-gnu@1.31.1: + resolution: {integrity: sha512-xGlFWRMl+0KvUhgySdIaReQdB4FNudfUTARn7q0hh/V67PVGCs3ADFjw+6++kG1RNd0zdGRlEKa+T13/tQjPMA==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [linux] + libc: [glibc] + + lightningcss-linux-x64-musl@1.31.1: + resolution: {integrity: sha512-eowF8PrKHw9LpoZii5tdZwnBcYDxRw2rRCyvAXLi34iyeYfqCQNA9rmUM0ce62NlPhCvof1+9ivRaTY6pSKDaA==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [linux] + libc: [musl] + + lightningcss-win32-arm64-msvc@1.31.1: + resolution: {integrity: sha512-aJReEbSEQzx1uBlQizAOBSjcmr9dCdL3XuC/6HLXAxmtErsj2ICo5yYggg1qOODQMtnjNQv2UHb9NpOuFtYe4w==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [win32] + + lightningcss-win32-x64-msvc@1.31.1: + resolution: {integrity: sha512-I9aiFrbd7oYHwlnQDqr1Roz+fTz61oDDJX7n9tYF9FJymH1cIN1DtKw3iYt6b8WZgEjoNwVSncwF4wx/ZedMhw==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [win32] + + lightningcss@1.31.1: + resolution: {integrity: sha512-l51N2r93WmGUye3WuFoN5k10zyvrVs0qfKBhyC5ogUQ6Ew6JUSswh78mbSO+IU3nTWsyOArqPCcShdQSadghBQ==} + engines: {node: '>= 12.0.0'} + lru-cache@10.4.3: resolution: {integrity: sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==} @@ -2014,6 +2203,13 @@ packages: tailwind-merge@3.7.0: resolution: {integrity: sha512-XPPUyAc+cvspz3lHTcR/QgPfW2A0lv/xQNIjX3HGhLR+Nq2lHaLq5MtTesHn8GUr3W3DguT2KT5x3NVgRtYwmA==} + tailwindcss@4.2.1: + resolution: {integrity: sha512-/tBrSQ36vCleJkAOsy9kbNTgaxvGbyOamC30PRePTQe/o1MFwEKHQk4Cn7BNGaPtjp+PuUrByJehM1hgxfq4sw==} + + tapable@2.3.4: + resolution: {integrity: sha512-NHFiWnAbMJxNNpBwiO7jJVGDuqMxT9/oV8v57RR+fgBQShkJil5inGD8/xWy0hjLyHQyX1tu27QANhlz3KBqCg==} + engines: {node: '>=6'} + tinybench@2.9.0: resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==} @@ -2689,12 +2885,12 @@ snapshots: '@module-federation/third-party-dts-extractor@2.9.2': {} - '@module-federation/vite@1.23.7(typescript@6.0.3)(vite@7.3.7(@types/node@26.6.6))': + '@module-federation/vite@1.23.7(typescript@6.0.3)(vite@7.3.7(@types/node@26.6.6)(jiti@2.7.0)(lightningcss@1.31.1))': dependencies: '@module-federation/dts-plugin': 2.9.2(typescript@6.0.3) '@module-federation/runtime': 2.9.2 '@module-federation/sdk': 2.9.2 - vite: 7.3.7(@types/node@26.6.6) + vite: 7.3.7(@types/node@26.6.6)(jiti@2.7.0)(lightningcss@1.31.1) transitivePeerDependencies: - bufferutil - typescript @@ -3266,6 +3462,74 @@ snapshots: '@standard-schema/spec@1.1.0': {} + '@tailwindcss/node@4.2.1': + dependencies: + '@jridgewell/remapping': 2.3.5 + enhanced-resolve: 5.27.0 + jiti: 2.7.0 + lightningcss: 1.31.1 + magic-string: 0.30.21 + source-map-js: 1.2.2 + tailwindcss: 4.2.1 + + '@tailwindcss/oxide-android-arm64@4.2.1': + optional: true + + '@tailwindcss/oxide-darwin-arm64@4.2.1': + optional: true + + '@tailwindcss/oxide-darwin-x64@4.2.1': + optional: true + + '@tailwindcss/oxide-freebsd-x64@4.2.1': + optional: true + + '@tailwindcss/oxide-linux-arm-gnueabihf@4.2.1': + optional: true + + '@tailwindcss/oxide-linux-arm64-gnu@4.2.1': + optional: true + + '@tailwindcss/oxide-linux-arm64-musl@4.2.1': + optional: true + + '@tailwindcss/oxide-linux-x64-gnu@4.2.1': + optional: true + + '@tailwindcss/oxide-linux-x64-musl@4.2.1': + optional: true + + '@tailwindcss/oxide-wasm32-wasi@4.2.1': + optional: true + + '@tailwindcss/oxide-win32-arm64-msvc@4.2.1': + optional: true + + '@tailwindcss/oxide-win32-x64-msvc@4.2.1': + optional: true + + '@tailwindcss/oxide@4.2.1': + optionalDependencies: + '@tailwindcss/oxide-android-arm64': 4.2.1 + '@tailwindcss/oxide-darwin-arm64': 4.2.1 + '@tailwindcss/oxide-darwin-x64': 4.2.1 + '@tailwindcss/oxide-freebsd-x64': 4.2.1 + '@tailwindcss/oxide-linux-arm-gnueabihf': 4.2.1 + '@tailwindcss/oxide-linux-arm64-gnu': 4.2.1 + '@tailwindcss/oxide-linux-arm64-musl': 4.2.1 + '@tailwindcss/oxide-linux-x64-gnu': 4.2.1 + '@tailwindcss/oxide-linux-x64-musl': 4.2.1 + '@tailwindcss/oxide-wasm32-wasi': 4.2.1 + '@tailwindcss/oxide-win32-arm64-msvc': 4.2.1 + '@tailwindcss/oxide-win32-x64-msvc': 4.2.1 + + '@tailwindcss/vite@4.2.1(vite@7.3.7(@types/node@26.6.6)(jiti@2.7.0)(lightningcss@1.31.1))': + dependencies: + '@tailwindcss/node': 4.2.1 + '@tailwindcss/oxide': 4.2.1 + tailwindcss: 4.2.1 + vite: 7.3.7(@types/node@26.6.6)(jiti@2.7.0)(lightningcss@1.31.1) + '@tanstack/query-core@5.101.4': {} '@tanstack/react-query@5.101.4(react@19.2.8)': @@ -3381,7 +3645,7 @@ snapshots: '@vercel/oidc@3.2.0': {} - '@vitejs/plugin-react@5.2.0(vite@7.3.7(@types/node@26.6.6))': + '@vitejs/plugin-react@5.2.0(vite@7.3.7(@types/node@26.6.6)(jiti@2.7.0)(lightningcss@1.31.1))': dependencies: '@babel/core': 7.29.7 '@babel/plugin-transform-react-jsx-self': 7.29.7(@babel/core@7.29.7) @@ -3389,7 +3653,7 @@ snapshots: '@rolldown/pluginutils': 1.0.0-rc.3 '@types/babel__core': 7.20.5 react-refresh: 0.18.0 - vite: 7.3.7(@types/node@26.6.6) + vite: 7.3.7(@types/node@26.6.6)(jiti@2.7.0)(lightningcss@1.31.1) transitivePeerDependencies: - supports-color @@ -3402,13 +3666,13 @@ snapshots: chai: 6.3.0 tinyrainbow: 3.2.0 - '@vitest/mocker@4.1.12(vite@7.3.7(@types/node@26.6.6))': + '@vitest/mocker@4.1.12(vite@7.3.7(@types/node@26.6.6)(jiti@2.7.0)(lightningcss@1.31.1))': dependencies: '@vitest/spy': 4.1.12 estree-walker: 3.0.3 magic-string: 0.30.21 optionalDependencies: - vite: 7.3.7(@types/node@26.6.6) + vite: 7.3.7(@types/node@26.6.6)(jiti@2.7.0)(lightningcss@1.31.1) '@vitest/pretty-format@4.1.12': dependencies: @@ -3554,6 +3818,8 @@ snapshots: dequal@2.0.3: {} + detect-libc@2.1.2: {} + detect-node-es@1.1.0: {} dom-accessibility-api@0.5.16: {} @@ -3572,6 +3838,11 @@ snapshots: electron-to-chromium@1.5.468: {} + enhanced-resolve@5.27.0: + dependencies: + graceful-fs: 4.2.12 + tapable: 2.3.4 + entities@6.0.1: {} entities@8.1.0: {} @@ -3682,6 +3953,8 @@ snapshots: gopd@1.2.0: {} + graceful-fs@4.2.12: {} + has-symbols@1.1.0: {} has-tostringtag@1.0.2: @@ -3736,6 +4009,8 @@ snapshots: dependencies: ws: 8.21.3 + jiti@2.7.0: {} + js-tokens@4.0.0: {} jsdom@25.0.1: @@ -3797,6 +4072,55 @@ snapshots: json5@2.2.3: {} + lightningcss-android-arm64@1.31.1: + optional: true + + lightningcss-darwin-arm64@1.31.1: + optional: true + + lightningcss-darwin-x64@1.31.1: + optional: true + + lightningcss-freebsd-x64@1.31.1: + optional: true + + lightningcss-linux-arm-gnueabihf@1.31.1: + optional: true + + lightningcss-linux-arm64-gnu@1.31.1: + optional: true + + lightningcss-linux-arm64-musl@1.31.1: + optional: true + + lightningcss-linux-x64-gnu@1.31.1: + optional: true + + lightningcss-linux-x64-musl@1.31.1: + optional: true + + lightningcss-win32-arm64-msvc@1.31.1: + optional: true + + lightningcss-win32-x64-msvc@1.31.1: + optional: true + + lightningcss@1.31.1: + dependencies: + detect-libc: 2.1.2 + optionalDependencies: + lightningcss-android-arm64: 1.31.1 + lightningcss-darwin-arm64: 1.31.1 + lightningcss-darwin-x64: 1.31.1 + lightningcss-freebsd-x64: 1.31.1 + lightningcss-linux-arm-gnueabihf: 1.31.1 + lightningcss-linux-arm64-gnu: 1.31.1 + lightningcss-linux-arm64-musl: 1.31.1 + lightningcss-linux-x64-gnu: 1.31.1 + lightningcss-linux-x64-musl: 1.31.1 + lightningcss-win32-arm64-msvc: 1.31.1 + lightningcss-win32-x64-msvc: 1.31.1 + lru-cache@10.4.3: {} lru-cache@11.5.3: {} @@ -4026,6 +4350,10 @@ snapshots: tailwind-merge@3.7.0: {} + tailwindcss@4.2.1: {} + + tapable@2.3.4: {} + tinybench@2.9.0: {} tinyexec@1.3.1: {} @@ -4102,7 +4430,7 @@ snapshots: dependencies: react: 19.2.8 - vite@7.3.7(@types/node@26.6.6): + vite@7.3.7(@types/node@26.6.6)(jiti@2.7.0)(lightningcss@1.31.1): dependencies: esbuild: 0.28.2 fdir: 6.5.0(picomatch@4.0.7) @@ -4113,11 +4441,13 @@ snapshots: optionalDependencies: '@types/node': 26.6.6 fsevents: 2.3.3 + jiti: 2.7.0 + lightningcss: 1.31.1 - vitest@4.1.12(@types/node@26.6.6)(jsdom@25.0.1)(vite@7.3.7(@types/node@26.6.6)): + vitest@4.1.12(@types/node@26.6.6)(jsdom@25.0.1)(vite@7.3.7(@types/node@26.6.6)(jiti@2.7.0)(lightningcss@1.31.1)): dependencies: '@vitest/expect': 4.1.12 - '@vitest/mocker': 4.1.12(vite@7.3.7(@types/node@26.6.6)) + '@vitest/mocker': 4.1.12(vite@7.3.7(@types/node@26.6.6)(jiti@2.7.0)(lightningcss@1.31.1)) '@vitest/pretty-format': 4.1.12 '@vitest/runner': 4.1.12 '@vitest/snapshot': 4.1.12 @@ -4134,7 +4464,7 @@ snapshots: tinyexec: 1.3.1 tinyglobby: 0.2.17 tinyrainbow: 3.2.0 - vite: 7.3.7(@types/node@26.6.6) + vite: 7.3.7(@types/node@26.6.6)(jiti@2.7.0)(lightningcss@1.31.1) why-is-node-running: 2.3.0 optionalDependencies: '@types/node': 26.6.6 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-access-state.tsx b/ui/provider/src/components/inventory-access-state.tsx new file mode 100644 index 00000000..2541c768 --- /dev/null +++ b/ui/provider/src/components/inventory-access-state.tsx @@ -0,0 +1,23 @@ +import { Link, useParams } from 'react-router'; +import { Button } from '@datum-cloud/datum-ui/button'; + +export function InventoryAccessState({ status, onRetry }: { status: number; onRetry?: () => void }) { + const { slug } = useParams(); + const title = status === 401 ? 'Your session has expired' : status === 403 ? 'Inventory access needed' : status === 404 ? 'Inventory section unavailable' : 'Inventory is temporarily unavailable'; + const message = status === 401 + ? 'Sign in again through the staff portal, then return to inventory.' + : status === 403 + ? 'Ask your administrator for inventory viewing access in the provider project. Staff portal access alone does not grant inventory access.' + : 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}

+
+ {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-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.test.tsx b/ui/provider/src/components/inventory-management.test.tsx new file mode 100644 index 00000000..6d3cc3d8 --- /dev/null +++ b/ui/provider/src/components/inventory-management.test.tsx @@ -0,0 +1,53 @@ +import { fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { InventoryManagement } from './inventory-management'; +import * as management from '../lib/inventory-management'; +import { ApiError } from '../lib/api'; + +vi.mock('../lib/inventory-management', async () => ({ ...await vi.importActual('../lib/inventory-management'), useInventoryPermission: vi.fn(), createInventoryRecord: vi.fn() })); +const permission = vi.mocked(management.useInventoryPermission); +const create = vi.mocked(management.createInventoryRecord); +function renderManagement() { return render(); } +beforeEach(() => { vi.clearAllMocks(); permission.mockReturnValue({ data: true, isFetching: false, error: null } as never); }); + +describe('management affordances', () => { + it('explains session expiry during the permission check without exposing raw errors', () => { + 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.queryByText(/private upstream error/)).not.toBeInTheDocument(); + }); + it('hides create from 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(create).not.toHaveBeenCalled(); + }); + it('permits an authorized manager to create and confirms only an acknowledged result', async () => { + create.mockResolvedValue({ metadata: { name: 'example', uid: 'synthetic' } } as never); + renderManagement(); + fireEvent.click(screen.getByText('Manage facilities')); + 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.')); + }); + it.each([401, 403, 500])('retains safe input without false success on submit failure %s', async status => { + create.mockRejectedValue(new ApiError(status, 'Raw server error with private information')); + renderManagement(); + fireEvent.click(screen.getByText('Manage facilities')); + 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'); + expect(screen.getByRole('button', { name: 'Create facility record' })).toBeDisabled(); + expect(screen.queryByText(/Raw server error|record created/)).not.toBeInTheDocument(); + }); +}); diff --git a/ui/provider/src/components/inventory-management.tsx b/ui/provider/src/components/inventory-management.tsx new file mode 100644 index 00000000..7de8de6a --- /dev/null +++ b/ui/provider/src/components/inventory-management.tsx @@ -0,0 +1,88 @@ +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); + const allowed = permission.data === true && !permission.isFetching && !permission.error && editable; + 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 })); + async function save(event: FormEvent) { + event.preventDefault(); + if (!allowed || pending || blocked) return; + setPending(true); setMessage(''); + const operation = scope.current.begin(sessionScope); + try { + 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 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.'); + 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'}`} + {!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 && } + {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 === '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/inventory-navigation-safety.test.tsx b/ui/provider/src/components/inventory-navigation-safety.test.tsx new file mode 100644 index 00000000..82a973a4 --- /dev/null +++ b/ui/provider/src/components/inventory-navigation-safety.test.tsx @@ -0,0 +1,169 @@ +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].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[] = []; + 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 () => { + 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([]); + 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-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.test.tsx b/ui/provider/src/components/inventory-session-boundary.test.tsx new file mode 100644 index 00000000..d90b4648 --- /dev/null +++ b/ui/provider/src/components/inventory-session-boundary.test.tsx @@ -0,0 +1,87 @@ +import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { createMemoryRouter, MemoryRouter, Outlet, RouterProvider } from 'react-router'; +import { useQuery } from '@tanstack/react-query'; +import { describe, expect, it, vi } from 'vitest'; +import { InventorySessionBoundary } from './inventory-session-boundary'; + +function mountHost(loader: () => unknown, content: React.ReactNode) { + const router = createMemoryRouter([{ + id: 'layouts/milo.layout', + path: '/', + loader, + element: , + children: [{ index: true, element: {content} }], + }]); + render(); + return router; +} + +describe('host inventory session isolation', () => { + it('fails closed outside the authenticated host unless explicitly previewing', () => { + render(Restricted inventory); + expect(screen.queryByText('Restricted inventory')).not.toBeInTheDocument(); + expect(screen.getByText('Your session has expired')).toBeInTheDocument(); + }); + + it('does not read inventory without an authenticated loader identity', async () => { + mountHost(() => ({ user: null }), 'Restricted inventory'); + await screen.findByText('Your session has expired'); + expect(screen.queryByText('Restricted inventory')).not.toBeInTheDocument(); + }); + + it('isolates identical query keys across principal changes and pending revalidation', async () => { + let principal = 'staff-a'; + let release: (() => void) | undefined; + const read = vi.fn(async () => `Inventory for ${principal}`); + function Records() { + const query = useQuery({ queryKey: ['inventory'], queryFn: read }); + return

{query.data}

; + } + const router = mountHost(async () => { + if (principal === 'staff-b') await new Promise(resolve => { release = resolve; }); + return { user: { metadata: { uid: principal } } }; + }, ); + await screen.findByText('Inventory for staff-a'); + principal = 'staff-b'; + let completion: Promise; + act(() => { completion = router.revalidate(); }); + await waitFor(() => expect(screen.queryByText('Inventory for staff-a')).not.toBeInTheDocument()); + await act(async () => { release?.(); await completion; }); + await screen.findByText('Inventory for staff-b'); + expect(read).toHaveBeenCalledTimes(2); + expect(screen.queryByText('Inventory for staff-a')).not.toBeInTheDocument(); + }); + + 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 screen.findByText('Restricted inventory'); + fireEvent(window, new Event('blur')); + expect(screen.queryByText('Restricted inventory')).not.toBeInTheDocument(); + loader.mockReturnValue({ user: null } as never); + fireEvent(window, new Event('focus')); + await screen.findByText('Your session has expired'); + 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 new file mode 100644 index 00000000..aa7d63ea --- /dev/null +++ b/ui/provider/src/components/inventory-session-boundary.tsx @@ -0,0 +1,100 @@ +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 { InventoryAccessState } from './inventory-access-state'; +import { LoadingState } from './states'; +import { InventoryOperationContext, InventoryOperationScope } from '../lib/inventory-operation'; + +export const InventoryPreviewContext = createContext(false); + +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}; +} + +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(); + const navigation = useNavigation(); + const revalidator = useRevalidator(); + const revalidate = useRef(revalidator.revalidate); + revalidate.current = revalidator.revalidate; + const [checking, setChecking] = useState(() => typeof document !== 'undefined' && document.visibilityState === 'hidden'); + const [failed, setFailed] = useState(false); + const generation = useRef(0); + const foreground = useRef(true); + useEffect(() => { + let active = true; + const hide = () => { + generation.current++; + foreground.current = false; + setChecking(true); + }; + const verify = () => { + if (document.visibilityState === 'hidden') return; + foreground.current = true; + const attempt = ++generation.current; + setChecking(true); + setFailed(false); + void revalidate.current().catch(() => { + if (active && attempt === generation.current && foreground.current) setFailed(true); + }).finally(() => { + if (active && attempt === generation.current && foreground.current && document.visibilityState !== 'hidden') setChecking(false); + }); + }; + const visibility = () => document.visibilityState === 'hidden' ? hide() : verify(); + const restore = (event: PageTransitionEvent) => { if (event.persisted) verify(); }; + window.addEventListener('blur', hide); + window.addEventListener('focus', verify); + window.addEventListener('pagehide', hide); + window.addEventListener('pageshow', restore); + document.addEventListener('visibilitychange', visibility); + return () => { + active = false; + generation.current++; + window.removeEventListener('blur', hide); + window.removeEventListener('focus', verify); + window.removeEventListener('pagehide', hide); + window.removeEventListener('pageshow', restore); + document.removeEventListener('visibilitychange', visibility); + }; + }, []); + if (checking || revalidator.state !== 'idle' || navigation.state !== 'idle') return ; + if (failed) return ; + if (!principal) return ; + return {children}; +} + +export function InventorySessionBoundary({ children }: { children: ReactNode }) { + const router = useContext(UNSAFE_DataRouterStateContext); + const preview = useContext(InventoryPreviewContext); + if (preview) return <>{children}; + if (!router) return ; + return {children}; +} diff --git a/ui/provider/src/components/physical-inventory.css b/ui/provider/src/components/physical-inventory.css new file mode 100644 index 00000000..bee1b3ce --- /dev/null +++ b/ui/provider/src/components/physical-inventory.css @@ -0,0 +1,51 @@ +.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 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: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 a[aria-current] { border-color:var(--primary,#264b42); background:var(--accent,#eaf1ed); } +.inventory-sections strong { margin-left:auto; font-size:18px; } +.inventory-sections svg { flex-shrink:0; } +.inventory-body { display:flex; flex-direction:column; gap:20px; padding:24px; 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-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 tr:last-child td { border-bottom:0; } +.fleet-inventory tbody tr:hover { background:var(--muted,#f8faf8); } +.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 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-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-management { display:block; max-width:680px; } +.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; } +@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 a3e454fc..4e754261 100644 --- a/ui/provider/src/components/physical-inventory.test.tsx +++ b/ui/provider/src/components/physical-inventory.test.tsx @@ -1,48 +1,134 @@ -import { fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { fireEvent, render, screen, within } from '@testing-library/react'; import { describe, expect, it } from 'vitest'; +import { MemoryRouter } from 'react-router'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { PhysicalInventory } from './physical-inventory'; -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'); - 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(); - 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(); - 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(); +import { toInventory } from '../inventory'; +import { fixturePhysicalClaims, fixturePhysicalDevices, fixturePhysicalRecords } from '../lib/fixtures'; + +const inventory = toInventory(fixturePhysicalClaims, fixturePhysicalDevices, fixturePhysicalRecords); + +function browse(query = '', data = inventory) { + return render(); +} + +describe('hardware directory', () => { + it('does not turn no-read permission into empty inventory or zero counts', () => { + browse('', { ...inventory, issues: { 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(); + expect(screen.queryByRole('link', { name: /Devices 0/ })).not.toBeInTheDocument(); + expect(screen.queryByRole('button', { name: /retry|try again/i })).not.toBeInTheDocument(); + }); + + it('preserves permitted facilities and handles a denied device deep link without echoing identity', () => { + browse('?kind=Device&record=private-device&namespace=private', { ...inventory, issues: { Device: { status: 403 } } }); + 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/ })); + expect(screen.getByRole('link', { name: 'Example facility' })).toBeInTheDocument(); + }); + + it('removes previously visible identities when a permission result changes', () => { + const client = new QueryClient(); + const view = (data: typeof inventory) => ; + const result = render(view(inventory)); + expect(screen.getByText('SYNTHETIC-0001')).toBeInTheDocument(); + result.rerender(view({ ...inventory, issues: { Device: { status: 403 } } })); + expect(screen.queryByText('SYNTHETIC-0001')).not.toBeInTheDocument(); + expect(screen.queryByText('Example compute server')).not.toBeInTheDocument(); + expect(screen.getByText('Inventory access needed')).toBeInTheDocument(); + }); + + it.each([[404, 'Inventory section unavailable'], [503, 'Inventory is temporarily unavailable']])('distinguishes collection failure %s', (status, title) => { + browse('?kind=Device', { ...inventory, issues: { Device: { status: Number(status) } } }); + expect(screen.getByRole('heading', { name: String(title) })).toBeInTheDocument(); + expect(screen.queryByText('No devices recorded')).not.toBeInTheDocument(); + }); + + 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(); + 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(); + }); + + it('searches identity and resets the filter when navigating categories', () => { + browse(); + fireEvent.change(screen.getByRole('searchbox'), { target: { value: 'EXAMPLE-001' } }); + expect(screen.getByRole('link', { name: 'Example compute server' })).toBeInTheDocument(); + expect(screen.queryByRole('link', { name: 'orphan-synthetic-0009' })).not.toBeInTheDocument(); + 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/ })); + expect(screen.getByRole('searchbox')).toHaveValue(''); + expect(screen.getByRole('link', { name: 'Example facility' })).toBeInTheDocument(); + }); + + it('drills from facility through rack and claim to hardware without claiming free units', () => { + browse('?kind=Facility&record=example-facility&namespace=default'); + fireEvent.click(screen.getByRole('link', { name: 'Rack 01' })); + expect(screen.getByText(/recorded placement is not verified occupancy/)).toBeInTheDocument(); + fireEvent.click(screen.getByRole('link', { name: 'Server installation · U12' })); + fireEvent.click(screen.getByRole('link', { name: 'Example compute server' })); + expect(screen.getByText('SYNTHETIC-0001')).toBeInTheDocument(); + expect(screen.getByText('NetworkPort')).toBeInTheDocument(); + expect(screen.getByText('PowerInlet')).toBeInTheDocument(); + expect(screen.getByRole('link', { name: 'Server power cable' })).toBeInTheDocument(); + }); + + it('follows typed cable endpoints to the supply and retains power uncertainty', () => { + browse('?kind=Cable&record=power-01&namespace=default'); + expect(screen.getByText('psu-1 · position 1')).toBeInTheDocument(); + fireEvent.click(screen.getByRole('link', { name: 'Feed A' })); + expect(screen.getByText('PowerOutlet')).toBeInTheDocument(); + expect(screen.getByText(/supply ratings do not establish available power/)).toBeInTheDocument(); + expect(screen.getByText('example-provider/Supply/synthetic-supply-a')).toBeInTheDocument(); + }); + + it('retains replacements without choosing an active registration', () => { + const original = fixturePhysicalDevices[0]; + const replacement = { ...original, metadata: { ...original.metadata, name: 'replacement' }, spec: { ...original.spec, displayName: 'Replacement server' } }; + browse('?kind=DeviceClaim&record=rack-01-u12&namespace=default', toInventory(fixturePhysicalClaims, [original, replacement])); + expect(screen.getByText(/the active device and its placement are unknown/)).toBeInTheDocument(); + expect(screen.getByRole('link', { name: 'Example compute server' })).toBeInTheDocument(); + expect(screen.getByRole('link', { name: 'Replacement server' })).toBeInTheDocument(); + }); + + it('does not resolve relationships across namespaces or infer typed refs from legacy names', () => { + const foreignRack = { ...fixturePhysicalRecords[1], metadata: { name: 'rack-01', namespace: 'other' } }; + browse('?kind=DeviceClaim&record=rack-01-u12&namespace=default', toInventory(fixturePhysicalClaims, [], [foreignRack])); + expect(screen.getByText('(record not found)')).toBeInTheDocument(); + expect(screen.queryByRole('link', { name: 'Rack 01' })).not.toBeInTheDocument(); + }); + + it('handles category emptiness and deleted deep links explicitly', () => { + const result = browse('?kind=Rack', toInventory([], [])); + expect(screen.getByText('No racks recorded')).toBeInTheDocument(); + result.unmount(); + browse('?kind=Device&record=missing&namespace=default'); + expect(screen.getByRole('heading', { name: 'Record not found' })).toBeInTheDocument(); + }); + + it('keeps same-named assets in different namespaces independently navigable', () => { + const original = fixturePhysicalDevices[0]; + const other = { ...original, metadata: { ...original.metadata, namespace: 'other' }, spec: { ...original.spec, displayName: 'Other namespace server', identity: { ...original.spec.identity, serial: 'OTHER-SYNTHETIC-001' } } }; + browse('?kind=Device', toInventory(fixturePhysicalClaims, [original, other])); + fireEvent.click(screen.getByRole('link', { name: 'Other namespace server' })); + expect(screen.getByText('OTHER-SYNTHETIC-001')).toBeInTheDocument(); + expect(screen.queryByText('SYNTHETIC-0001')).not.toBeInTheDocument(); + expect(screen.getByText('Claim record not found')).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]])); + expect(screen.queryByRole('link', { name: /Server installation/ })).not.toBeInTheDocument(); + expect(screen.getByText(/No related records found/)).toBeInTheDocument(); }); }); diff --git a/ui/provider/src/components/physical-inventory.tsx b/ui/provider/src/components/physical-inventory.tsx index e7e790f0..e92c2d1e 100644 --- a/ui/provider/src/components/physical-inventory.tsx +++ b/ui/provider/src/components/physical-inventory.tsx @@ -1,60 +1,729 @@ -import type { Inventory } from '../inventory'; -import type { CableEndpoint } from '../../../shared/fleet-api'; -import { useState } from 'react'; +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, + placementLabel, + slotKey, + type Inventory, + type RawDevice, + type RawDeviceClaim, +} from '../inventory'; +import type { CableEndpoint, PhysicalComponent, PhysicalRecord } from '../../../shared/fleet-api'; +import './physical-inventory.css'; +import { InventoryAccessState } from './inventory-access-state'; +import { InventoryManagement } from './inventory-management'; + +type Kind = '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: '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 planned equipment placement.', + }, + { + kind: 'DeviceClaim', + title: 'Claims', + icon: ClipboardList, + description: 'Installation plans, kept separate from physical hardware.', + }, + { + 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 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[] }>(); +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 ( +
+
{label}
+
{children ?? 'Not recorded'}
+
+ ); +} + +function Components({ components }: { components: PhysicalComponent[] }) { + return components.length ? ( +
+ + + + + + + + + + + + {components.map((component) => ( + + + + + + + ))} + +
Physical components
Name / IDTypeConnector / positionsIdentity
+ {component.name} + {component.id} + {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'} + + {component.sourceRef && ( + + {component.sourceRef.system}/{component.sourceRef.type}/{component.sourceRef.id} + + )} +
+
+ ) : ( +

No components recorded.

+ ); +} + +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 [params] = useSearchParams(); 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.

-

Operators enter and review records in the private inventory Git source. Flux is the staging writer. NetBox and import reports are not required; this page never applies or synchronizes inventory.

- - {error &&

{error}

} - {summary &&

Optional source comparison — 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
  • )}
-
)} -
; + 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[] = [ + ...inventory.slots.flatMap((slot) => slot.devices.map((record) => ({ kind: 'Device' as const, record }))), + ...inventory.unboundDevices.map((record) => ({ kind: 'Device' as const, record })), + ...inventory.slots.map((slot) => ({ kind: 'DeviceClaim' as const, record: slot.claim })), + ...inventory.physical.map((record) => ({ kind: record.kind, record })), + ]; + const selectedName = params.get('record'); + const selectedNamespace = params.get('namespace') ?? ''; + const selected = entries.find( + (entry) => + entry.kind === section.kind && + entry.record.metadata.name === selectedName && + (entry.record.metadata.namespace ?? '') === selectedNamespace, + ); + useEffect(() => { + setSearch(''); + if (selectedName !== null) heading.current?.focus(); + }, [section.kind, selectedName, selectedNamespace]); + const find = (kind: Kind, namespace: string | undefined, name: string) => + entries.find( + (entry) => + entry.kind === kind && + slotKey(entry.record.metadata.namespace, entry.record.metadata.name) === slotKey(namespace, name), + ); + const reference = (kind: Kind, namespace: string | undefined, name: string) => { + if (inventory.issues?.[kind]) return Related record unavailable; + const target = find(kind, namespace, name); + return target ? ( + {recordName(target)} + ) : ( + + {name} (record not found) + + ); + }; + const claimFor = (device: RawDevice) => + inventory.slots.find( + (slot) => slot.key === slotKey(device.metadata.namespace, device.spec.claimRef.name), + ); + const plannedPlacement = (claim: RawDeviceClaim) => { + const location = claim.spec.placement; + if (!location.scope) return placementLabel(claim); + 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; + const facility = facilityName ? find('Facility', claim.metadata.namespace, facilityName) : undefined; + const parts = [ + facility ? recordName(facility) : facilityName, + rack ? recordName(rack) : location.rackRef?.name, + ]; + if (location.scope === 'Facility') parts.push('Rack not recorded'); + if (location.scope === 'RackMembership') parts.push('Position not recorded'); + if (location.scope === 'NonRackUnitMount') parts.push(`Mount: ${location.mount ?? 'Not recorded'}`); + if (location.scope === 'RackUnits') + parts.push( + location.position === undefined + ? 'Position not recorded' + : `U${location.position}${(location.height ?? 1) > 1 ? `–U${location.position + (location.height ?? 1) - 1}` : ''} · ${location.face ?? 'Face not recorded'}`, + ); + return parts.filter(Boolean).join(' · '); + }; + const placement = (entry: RecordEntry): string => { + if (entry.kind === 'DeviceClaim') return plannedPlacement(entry.record as RawDeviceClaim); + if (entry.kind === 'Device') { + 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' : ''}` + : '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' + ); + }; + const summary = (entry: RecordEntry): string => { + if (entry.kind === 'Device') return modelLabel((entry.record as RawDevice).spec.identity); + if (entry.kind === 'DeviceClaim') + return modelLabel((entry.record as RawDeviceClaim).spec.expectedIdentity); + const record = entry.record as PhysicalRecord; + if (entry.kind === 'Rack') + return record.spec.heightUnits ? `${record.spec.heightUnits}U rack` : 'Height not recorded'; + if (entry.kind === 'Cable') + return `${record.spec.medium ?? 'Medium not recorded'} · ${record.spec.lanes?.length ?? 0} recorded lanes`; + if (entry.kind === 'PowerFeed') + return record.spec.supply + ? `${record.spec.supply.type} · ${record.spec.supply.voltageV ?? 'Unknown'} V · ${record.spec.supply.currentA ?? 'Unknown'} A` + : 'Supply not recorded'; + return 'Physical premises'; + }; + const records = entries.filter((entry) => entry.kind === section.kind); + const matching = records + .filter((entry) => + `${JSON.stringify(entry.record)} ${placement(entry)}` + .toLowerCase() + .includes(search.trim().toLowerCase()), + ) + .sort( + (left, right) => + recordName(left).localeCompare(recordName(right)) || + slotKey(left.record.metadata.namespace, left.record.metadata.name).localeCompare( + slotKey(right.record.metadata.namespace, right.record.metadata.name), + ), + ); + + function Endpoint({ endpoint, namespace }: { endpoint: CableEndpoint; namespace?: string }) { + return ( + + {endpoint.deviceRef + ? reference('Device', namespace, endpoint.deviceRef.name) + : endpoint.powerFeedRef + ? reference('PowerFeed', namespace, endpoint.powerFeedRef.name) + : 'Endpoint not recorded'} + + {endpoint.componentID} · position {endpoint.position} + + + ); + } + + 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; + const slot = device + ? claimFor(device) + : claim + ? inventory.slots.find((item) => item.key === slotKey(namespace, claim.metadata.name)) + : undefined; + const sameNamespace = (candidate: RecordEntry) => + (candidate.record.metadata.namespace ?? '') === (namespace ?? ''); + const related = entries.filter((candidate) => { + if (!sameNamespace(candidate)) return false; + if (candidate.kind === 'DeviceClaim') { + if (kind === 'Cable') + return (candidate.record as RawDeviceClaim).spec.cableRefs?.some( + (cable) => cable.name === record.metadata.name, + ); + const location = (candidate.record as RawDeviceClaim).spec.placement; + const rack = location.rackRef + ? (find('Rack', namespace, location.rackRef.name)?.record as PhysicalRecord | undefined) + : undefined; + return kind === 'Rack' + ? location.rackRef?.name === record.metadata.name + : kind === 'Facility' && + (location.facilityRef?.name === record.metadata.name || + rack?.spec.facilityRef?.name === record.metadata.name); + } + if (candidate.kind === 'Device') + return ( + kind === 'DeviceClaim' && + (candidate.record as RawDevice).spec.claimRef.name === record.metadata.name + ); + const target = candidate.record as PhysicalRecord; + if (target.kind === 'Cable') + return target.spec.lanes?.some((lane) => + [lane.a, lane.b].some((endpoint) => + kind === 'Device' + ? endpoint.deviceRef?.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; + }); + return ( + <> +
+ {record.metadata.name} + {namespace || 'Not recorded'} + {device && ( + <> + {modelLabel(device.spec.identity)} + {device.spec.identity.serial} + {device.spec.assetTag} + {device.spec.identity.systemUUID} + + {reference('DeviceClaim', namespace, device.spec.claimRef.name)} + + {placement(entry)} + + {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} + + {device.spec.bmc?.endpoint} + + {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 && ( + <> + {modelLabel(claim.spec.expectedIdentity)} + {claim.spec.expectedIdentity.serial} + {plannedPlacement(claim)} + {inventory.issues?.Device ? 'Device details unavailable' : slot?.devices.length ?? 0} + {claim.spec.placement.facilityRef && ( + + {reference('Facility', namespace, claim.spec.placement.facilityRef.name)} + + )} + {claim.spec.placement.rackRef && ( + {reference('Rack', namespace, claim.spec.placement.rackRef.name)} + )} + + )} + {physical?.spec.facilityRef && ( + {reference('Facility', namespace, physical.spec.facilityRef.name)} + )} + {physical?.spec.rackRef && ( + {reference('Rack', namespace, physical.spec.rackRef.name)} + )} + {physical?.spec.locationRef && ( + {physical.spec.locationRef.name} + )} + {kind === 'Rack' && ( + <> + + {physical?.spec.heightUnits === undefined ? 'Not recorded' : `${physical.spec.heightUnits}U`} + + Unknown — recorded placement is not verified occupancy. + + )} + {kind === 'Cable' && {physical?.spec.medium}} + {kind === 'PowerFeed' && ( + <> + {summary(entry)} + {physical?.spec.supply?.phase} + + Unknown — supply ratings do not establish available power. + + + )} +
+ {slot && slot.devices.length > 1 && ( +

+ Multiple devices reference this claim. All registrations are retained; the active device and its + placement are unknown. +

+ )} + {device && ( + <> +

Components & connections

+ + {!!device.spec.internalMappings?.length && ( + <> +

Internal paths

+
    + {device.spec.internalMappings.map((mapping, index) => ( +
  • + {mapping.from.componentID}:{mapping.from.position} → {mapping.to.componentID}: + {mapping.to.position} +
  • + ))} +
+ + )} + {!!device.spec.serviceAssociations?.length && ( + <> +

Service references

+
    + {device.spec.serviceAssociations.map((association, index) => ( +
  • + {association.componentID} → {association.serviceRef.system}/ + {association.serviceRef.type}/{association.serviceRef.id} +
  • + ))} +
+ + )} +
+ Recorded network interfaces & legacy peers +

+ Legacy peers are retained as history. Cable records describe typed physical connections; + neither verifies a live link. +

+
    + {device.spec.interfaces?.map((iface) => ( +
  • + {iface.name} · {iface.macAddress ?? 'MAC not recorded'} + {iface.peer && ` · legacy peer ${iface.peer.device}/${iface.peer.port}`} +
  • + ))} +
+

Unmapped MAC addresses

+

{device.spec.unmappedMACAddresses?.join(', ') || 'None recorded'}

+
+ + )} + {claim && ( + <> +

Planned connections

+
    + {claim.spec.cableRefs?.map((cable) => ( +
  • {reference('Cable', namespace, cable.name)}
  • + ))} +
+ {!claim.spec.cableRefs?.length && ( +

No cable references recorded.

+ )} +
+ Legacy expected ports +
    + {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}`} +
  • + ))} +
+ {!claim.spec.ports?.length &&

No expected ports recorded.

} +
+ + )} + {kind === 'Cable' && ( + <> +

Cable lanes

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

No lanes recorded.

+ )} + + )} + {kind === 'PowerFeed' && ( + <> +

Terminations

+ +

Upstream sources

+
    + {physical?.spec.upstreamSources?.map((source, index) => ( +
  • + {source.system}/{source.type}/{source.id} +
  • + ))} +
+ {!physical?.spec.upstreamSources?.length && ( +

No upstream sources recorded.

+ )} + + )} +

+ {kind === 'Rack' || kind === 'Facility' + ? 'Recorded contents & installation plans' + : 'Related records'} +

+ {related.length ? ( +
    + {related.map((item) => ( +
  • + + {sections.find((section) => section.kind === item.kind)?.title} + + {recordName(item)} + {placement(item)} +
  • + ))} +
+ ) : ( +

+ No related records found in this namespace. This does not establish that equipment or connections + are absent. +

+ )} +
+ 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} + + )} +
+
+ + ); + } + + return ( +
+
+
+

HARDWARE DIRECTORY

+

Physical inventory

+

Explore facilities, equipment, and physical connections.

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

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

+ {selected ? ( + <> +

+ {section.title} / {selected.record.metadata.namespace || 'No namespace'} /{' '} + {selected.record.metadata.name} +

+ + + ) : ( +

+ This {section.title.toLowerCase()} record is not in the loaded inventory. It may have been + removed or the link may be out of date. +

+ )} + + ) : ( + <> +
+
+

{section.title}

+

{section.description}

+
+ + {matching.length} of {records.length} records + +
+ + {matching.length ? ( +
+ + + + + + + + + + + {matching.map((entry) => ( + + + + + + + ))} + +
Name + {section.kind === 'Device' || section.kind === 'DeviceClaim' + ? 'Hardware' + : 'Details'} + + {section.kind === 'Device' || section.kind === 'DeviceClaim' + ? 'Planned location' + : 'Location / reference'} + {section.kind === 'Device' ? 'Serial / asset tag' : 'Namespace'}
+ + {recordName(entry)} + + + {entry.record.metadata.namespace || 'No namespace'} + {entry.record.spec.displayName && ` · ${entry.record.metadata.name}`} + + {summary(entry)}{placement(entry)} + {entry.kind === 'Device' ? ( + <> + {(entry.record as RawDevice).spec.identity.serial ?? 'Serial not recorded'} + + {(entry.record as RawDevice).spec.assetTag ?? 'Asset tag not recorded'} + + + ) : ( + entry.record.metadata.namespace || 'Not recorded' + )} +
+
+ ) : ( +
+
+ )} + + )} +
+
+ {!inventory.issues?.[section.kind] && (section.kind === 'Facility' || section.kind === 'Rack') && (selectedName === null || selected) && record.kind === 'Facility')} />} +
+ About this inventory +

+ These are recorded facts and installation plans, not live hardware status. A record does not + 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 + explicit ownership review. Nothing here synchronizes external systems or provisions hardware. +

+

+ Claims retain every registered device. Multiple registrations do not identify which device is + active. Missing values mean not recorded, not absent. +

+
+
+ ); } diff --git a/ui/provider/src/inventory.ts b/ui/provider/src/inventory.ts index 54b8efc5..0f920fa6 100644 --- a/ui/provider/src/inventory.ts +++ b/ui/provider/src/inventory.ts @@ -7,6 +7,10 @@ import type { Device as RawDevice, DeviceClaim as RawDeviceClaim, List, Physical export type { RawDevice, RawDeviceClaim }; export type RawDeviceList = List; export type RawDeviceClaimList = List; +export type InventoryKind = 'Device' | 'DeviceClaim' | 'Facility' | 'Rack' | 'Cable' | 'PowerFeed'; +export const inventoryResources: Record = { + Device: 'devices', DeviceClaim: 'deviceclaims', Facility: 'facilities', Rack: 'racks', Cable: 'cables', PowerFeed: 'powerfeeds', +}; export interface InventorySlot { key: string; @@ -18,6 +22,7 @@ export interface Inventory { slots: InventorySlot[]; unboundDevices: RawDevice[]; physical: PhysicalRecord[]; + issues?: Partial>; } export function slotKey(namespace: string | undefined, name: string): string { diff --git a/ui/provider/src/lib/api.ts b/ui/provider/src/lib/api.ts index 9e8cf42f..4356bedd 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 { 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 type { List, PhysicalRecord } from '../../../shared/fleet-api'; import { toMachineCapacity, @@ -58,17 +59,17 @@ interface ProxyEnvelope { error?: string; } -async function proxyFetch( +export async function proxyFetch( projectName: string, path: string, - init: { method?: string; body?: unknown } = {} + init: { method?: string; body?: unknown; contentType?: string } = {} ): Promise { const url = `/api/internal${getProjectScopedBase(projectName)}${path}`; const res = await fetch(url, { method: init.method ?? 'GET', headers: { Accept: 'application/json', - ...(init.body !== undefined && { 'Content-Type': 'application/json' }), + ...(init.body !== undefined && { 'Content-Type': init.contentType ?? 'application/json' }), }, body: init.body !== undefined ? JSON.stringify(init.body) : undefined, }); @@ -258,16 +259,22 @@ export function useDeleteMachineClass(): UseMutationResult { - if (USE_FIXTURES) return toInventory(fixtureDeviceClaims, fixtureDevices); - const [claims, devices, ...physical] = await Promise.all([ - fetchInventoryCollection[number]>('deviceclaims'), - fetchInventoryCollection[number]>('devices'), - ...['facilities', 'racks', 'cables', 'powerfeeds'].map((kind) => fetchInventoryCollection(kind)), - ]); - return toInventory(claims, devices, physical.flat()); + if (USE_FIXTURES) return toInventory(fixturePhysicalClaims, fixturePhysicalDevices, fixturePhysicalRecords); + const issues: Inventory['issues'] = {}; + const results = await Promise.all(Object.entries(inventoryResources).map(async ([kind, plural]) => { + try { return { kind, records: await fetchInventoryCollection(plural) }; } + catch (error) { + if (error instanceof ApiError && error.status === 401) throw error; + issues[kind as InventoryKind] = { status: error instanceof ApiError ? error.status : 0 }; + return { kind, records: [] }; + } + })); + const claims = results.find(result => result.kind === 'DeviceClaim')!.records as unknown as NonNullable; + const devices = results.find(result => result.kind === 'Device')!.records as unknown as NonNullable; + return { ...toInventory(claims, devices, results.filter(result => result.kind !== 'Device' && result.kind !== 'DeviceClaim').flatMap(result => result.records)), issues }; } export async function fetchInventoryCollection(plural: string): Promise { @@ -285,10 +292,13 @@ export async function fetchInventoryCollection(plural: string): Promise } export function useInventory(): UseQueryResult { + const view = useId(); return useQuery({ - queryKey: [PLUGIN_ID, 'inventory', PROVIDER_PROJECT], + queryKey: [PLUGIN_ID, 'inventory', PROVIDER_PROJECT, view], queryFn: fetchInventory, - refetchInterval: REFETCH_INTERVAL_MS, + refetchInterval: false, + refetchOnWindowFocus: 'always', + gcTime: 0, retry: false, }); } diff --git a/ui/provider/src/lib/fixtures.ts b/ui/provider/src/lib/fixtures.ts index ee4577ee..1ff1f017 100644 --- a/ui/provider/src/lib/fixtures.ts +++ b/ui/provider/src/lib/fixtures.ts @@ -1,5 +1,6 @@ import { ApiError } from './api'; import type { RawDevice, RawDeviceClaim } from '../inventory'; +import type { PhysicalRecord } from '../../../shared/fleet-api'; import type { RawMachineCapacity, RawMachineClass, RawMachineProfile } from '../types'; // Synthetic MachineCapacities used while the Fleet API cannot be read @@ -198,3 +199,16 @@ export const fixtureDevices: RawDevice[] = [ }, }, ]; + +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 }, spec: { displayName: 'Example facility', provenance: inventoryProvenance, locationRef: { name: 'example-region' } } }, + { 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 } }] } }, +]; + +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' } } })); + +export const fixturePhysicalDevices: RawDevice[] = fixtureDevices.map((record, index) => index ? record : ({ ...record, spec: { ...record.spec, displayName: 'Example compute server', assetTag: 'EXAMPLE-001', topologyAuthority: 'Cable', modelShape: { heightUnits: 1, fullDepth: true }, components: [{ id: 'psu-1', name: 'Power supply 1', type: 'PowerInlet', connector: 'IEC C14', positions: 1 }, { id: 'eth0', name: 'Ethernet 0', type: 'NetworkPort', connector: 'SFP28', positions: 1 }] } })); diff --git a/ui/provider/src/lib/inventory-api.test.ts b/ui/provider/src/lib/inventory-api.test.ts index 16e68802..6cd6ad72 100644 --- a/ui/provider/src/lib/inventory-api.test.ts +++ b/ui/provider/src/lib/inventory-api.test.ts @@ -22,12 +22,35 @@ describe('physical inventory reads', () => { await expect(fetchInventoryCollection('racks')).rejects.toThrow('completeness Unknown'); }); - it('requires all six collections and propagates restricted errors', async () => { + it('reads all six collections and retains per-kind denial without fake inventory', 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 }); + const inventory = await fetchInventory(); + expect(Object.values(inventory.issues ?? {})).toEqual(Array.from({ length: 6 }, () => ({ status: 403 }))); + expect(inventory.physical).toEqual([]); + }); + + it('preserves accessible collections when another kind is denied', async () => { + const facility = { kind: 'Facility', metadata: { name: 'example' }, spec: { displayName: 'Example' } }; + vi.stubGlobal('fetch', vi.fn((url: string) => Promise.resolve(url.includes('/facilities?') ? response({ items: [facility] }) : response(undefined, 403)))); + const inventory = await fetchInventory(); + expect(inventory.physical).toEqual([facility]); + expect(inventory.issues?.Device).toEqual({ status: 403 }); + expect(inventory.issues?.Facility).toBeUndefined(); + }); + + it('treats any session expiry as a global failure, never partial success', async () => { + vi.stubGlobal('fetch', vi.fn((url: string) => Promise.resolve(url.includes('/devices?') ? response(undefined, 401) : response({ items: [] })))); + await expect(fetchInventory()).rejects.toMatchObject({ status: 401 }); + }); + + it('distinguishes unavailable APIs and transient failures from empty collections', async () => { + vi.stubGlobal('fetch', vi.fn((url: string) => Promise.resolve(response(undefined, url.includes('/racks?') ? 404 : 503)))); + const inventory = await fetchInventory(); + expect(inventory.issues?.Rack?.status).toBe(404); + expect(inventory.issues?.Device?.status).toBe(503); }); }); diff --git a/ui/provider/src/lib/inventory-management.test.ts b/ui/provider/src/lib/inventory-management.test.ts new file mode 100644 index 00000000..eb63c180 --- /dev/null +++ b/ui/provider/src/lib/inventory-management.test.ts @@ -0,0 +1,82 @@ +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'; + +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 response = (data: unknown, status = 200) => ({ ok: status >= 200 && status < 300, status, json: async () => ({ data }) }); +afterEach(() => vi.unstubAllGlobals()); + +describe('inventory management authority', () => { + it.each([{ allowed: false }, { allowed: true, denied: true }, { allowed: true, evaluationError: 'Unavailable' }, {}])('fails closed for incomplete or denied review %j', async status => { + vi.stubGlobal('fetch', vi.fn().mockResolvedValue(response({ status }))); + expect(await inventoryPermission('Facility', 'default', 'create')).toBe(false); + }); + + it('reviews the exact provider-project, namespace, resource, verb and name', async () => { + const fetch = vi.fn().mockResolvedValue(response({ status: { allowed: true } })); + vi.stubGlobal('fetch', fetch); + expect(await inventoryPermission('Rack', 'operator-space', 'patch', 'rack-01')).toBe(true); + expect(fetch.mock.calls[0][0]).toContain('/projects/datum-cloud/control-plane/apis/authorization.k8s.io/v1/selfsubjectaccessreviews'); + expect(JSON.parse(fetch.mock.calls[0][1].body).spec.resourceAttributes).toEqual({ namespace: 'operator-space', name: 'rack-01', resource: 'racks', group: 'fleet.datumapis.com', version: 'v1alpha1', verb: 'patch' }); + }); + + 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, 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, 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'); + const payload = JSON.parse(init.body); + expect(payload.status).toBeUndefined(); + expect(payload.spec.provenance.method).toBe('Manual'); + expect(payload.metadata).toEqual({ name: values.name, namespace: 'default' }); + }); + + it('keeps unknown geometry absent and rejects invalid heights', () => { + expect(inventoryPayload('Rack', { ...values, facility: 'example-facility' }).spec.heightUnits).toBeUndefined(); + 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', () => { + 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 () => { + 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']); + }); + + 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, 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, 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, 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 new file mode 100644 index 00000000..3df70a73 --- /dev/null +++ b/ui/provider/src/lib/inventory-management.ts @@ -0,0 +1,98 @@ +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'; +const resources = { Facility: 'facilities', Rack: 'racks' } as const; +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]}`; + +export async function inventoryPermission(kind: ManagedKind, namespace: string, verb: 'create' | 'patch', name?: string): Promise { + if (!namespace || fixtures) return false; + const review = 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: 'fleet.datumapis.com', version: 'v1alpha1', resource: resources[kind], namespace, verb, ...(name && { name }) } } }, + }); + return review?.status?.allowed === true && review.status.denied !== true && !review.status.evaluationError; +} + +export function useInventoryPermission(kind: ManagedKind, namespace: string, verb: 'create' | 'patch', name?: string) { + 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 { + const { metadata, spec } = record; + return (record.kind === 'Facility' || record.kind === 'Rack') && !!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 { + name: string; + namespace: string; + displayName: string; + recordedBy: string; + reference: string; + facility: string; + height: string; +} + +export function inventoryPayload(kind: ManagedKind, 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 (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() }) }, + ...(kind === 'Rack' && { facilityRef: { name: values.facility }, ...(values.height && { heightUnits: Number(values.height) }) }), + } }; +} + +async function requirePermission(kind: ManagedKind, namespace: string, verb: 'create' | 'patch', name?: string) { + 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, 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.'); + } + 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, 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; + } +} diff --git a/ui/provider/src/main.tsx b/ui/provider/src/main.tsx index 29b9ace1..009317f4 100644 --- a/ui/provider/src/main.tsx +++ b/ui/provider/src/main.tsx @@ -3,6 +3,8 @@ 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 './preview.css'; +import { InventoryPreviewContext } from './components/inventory-session-boundary'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { StrictMode } from 'react'; import { createRoot } from 'react-dom/client'; @@ -13,14 +15,10 @@ const queryClient = new QueryClient(); createRoot(document.getElementById('root')!).render( -
-

- Standalone preview. staff-portal loads this plugin through - /plugin-manifest.json and /remoteEntry.js, not this page. - Without the staff-portal proxy the list shows its error state unless - VITE_FLEET_FIXTURES=true. -

+
+

Local plugin preview · {import.meta.env.VITE_FLEET_FIXTURES === 'true' ? 'Synthetic example data — not live inventory' : 'Requires the staff-portal API proxy'}

+ } /> } /> @@ -28,6 +26,7 @@ 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 index bd00eda0..0cead55f 100644 --- a/ui/provider/src/pages/device-claim-detail.tsx +++ b/ui/provider/src/pages/device-claim-detail.tsx @@ -1,8 +1,10 @@ import { FleetPage } from '../components/fleet-page'; import { endpointLabel } from '../components/physical-inventory'; -import { ErrorOrRestrictedState, LoadingState } from '../components/states'; +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 { PROVIDER_PROJECT, useInventory } from '../lib/api'; +import { 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'; @@ -90,10 +92,15 @@ function DeviceSection({ device, current }: { device: RawDevice; current: boolea } export default function DeviceClaimDetail() { + return ; +} + +function ClaimDetailContent() { 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); + const accessIssue = error?.status ?? data?.issues?.DeviceClaim?.status; + const slot = !error && !isLoading && accessIssue === undefined ? data?.slots.find((s) => s.key === slotKey(namespace, claimName)) : undefined; + const current = slot && !data?.issues?.Device && currentDevice(slot); return ( @@ -103,15 +110,9 @@ export default function DeviceClaimDetail() { {isLoading && } - {!isLoading && error && ( - void refetch()} - /> - )} + {!isLoading && (error || accessIssue !== undefined) && void refetch()} />} - {!isLoading && !error && data && !slot && ( + {!isLoading && !error && accessIssue === undefined && data && !slot && ( No DeviceClaim {claimName} in namespace {namespace}. @@ -126,7 +127,7 @@ export default function DeviceClaimDetail() { {slot.claim.spec.expectedIdentity.serial ?? '—'} {slot.claim.metadata.namespace ?? '—'} - {current ? current.metadata.name : {slot.devices.length > 1 ? 'Multiple records; active binding Unknown' : 'Not registered'}} + {data?.issues?.Device ? 'Device details unavailable' : current ? current.metadata.name : {slot.devices.length > 1 ? 'Multiple records; active binding Unknown' : 'Not registered'}}
{(slot.claim.spec.ports ?? []).length > 0 && ( @@ -143,11 +144,12 @@ export default function DeviceClaimDetail() { )} - {[...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[]; }