From c76bde615e7ee1acc1623c763725498577549345 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Tue, 24 Nov 2026 08:49:08 -0600 Subject: [PATCH] feat(ui): Show BMC discovery on the Device page The Device page showed nothing BMC discovery writes to Device.status. Hardware & management now compares spec identity with the observed System, lists host and BMC NICs with link state, and shows discovery health: the five conditions, last attempt, TLS key, expiry and approval. The header strip gains one BMC chip. Comparisons mirror internal/bmcdiscovery so the page marks what IdentityMatched does. When the retained inventory was read from an endpoint other than spec.bmc.endpoint, or spec records none, discovery reports IdentityMatched Unknown with StaleObservation. The page then compares nothing: observed values and a TLS key read from another endpoint are amber, with the endpoints in the tooltip. Co-Authored-By: Claude Opus 5.5 --- docs/development/staff-inventory-ui.md | 75 +++++- ui/provider/scripts/screenshot-pages.ts | 5 + .../src/components/device-connections.tsx | 7 +- .../src/components/device-discovery.test.tsx | 163 +++++++++++++ .../src/components/device-discovery.tsx | 153 ++++++++++++ .../components/inventory-record-detail.tsx | 23 +- .../inventory-record-layout.test.tsx | 7 +- .../src/components/physical-inventory.css | 14 ++ ui/provider/src/lib/device-discovery.test.ts | 143 +++++++++++ ui/provider/src/lib/device-discovery.ts | 222 ++++++++++++++++++ ui/provider/src/lib/inventory-fixtures.ts | 85 ++++++- ui/shared/fleet-api.ts | 71 +++++- 12 files changed, 956 insertions(+), 12 deletions(-) create mode 100644 ui/provider/src/components/device-discovery.test.tsx create mode 100644 ui/provider/src/components/device-discovery.tsx create mode 100644 ui/provider/src/lib/device-discovery.test.ts create mode 100644 ui/provider/src/lib/device-discovery.ts diff --git a/docs/development/staff-inventory-ui.md b/docs/development/staff-inventory-ui.md index 270beaff..6dc2aa2d 100644 --- a/docs/development/staff-inventory-ui.md +++ b/docs/development/staff-inventory-ui.md @@ -713,7 +713,9 @@ picture of the device and a dense table of its components. Top to bottom: component's name or id puts its MAC address in a **MAC address** column, shown only when some row has one (`interfaceAddresses()` in `lib/device-connections.ts`). Interfaces that match no component are listed -in Hardware & management. +in Hardware & management. Once BMC discovery has read the host NICs, a +recorded MAC that no host NIC reports is amber, with "No host NIC reports +this MAC address" as its tooltip and accessible text. **Highlight.** Hovering or focusing a row outlines that component in the picture, and hovering or focusing a picture port (or hovering a drawn @@ -755,6 +757,77 @@ for **Internal paths** and **Service references** when recorded. Empty facts and sections are hidden. The model is stated once, in the header strip. +### Device page: BMC discovery status + +BMC discovery is the only writer of `Device.status` (see +[BMC discovery](../operations/bmc-discovery.md)). The UI reads it from the +same Device list as spec; it has no other request. `lib/device-discovery.ts` +derives what the page shows and mirrors the comparisons in +`internal/bmcdiscovery/status.go`; `components/device-discovery.tsx` draws +it. Red is a disagreement or failure, amber needs checking, and OK stays +plain: there is no green. Every reason is a tooltip and accessible text. + +- **Header chip.** One chip ends the identity strip once status exists: + "BMC ✓" when all five conditions are True; else the first False condition + in discovery order, red ("BMC unreachable", "BMC key not approved", "BMC + key changed", "BMC auth failed", "BMC not read", "Identity mismatch", + "BMC key shared"); else "BMC ?" in amber. +- **Hardware: expected next to observed.** When discovery has read a + System, a Field | Expected | Observed table replaces the reported model + and system UUID facts: Serial, Model, Manufacturer, System UUID, SKU and + Power (Redfish `powerState` as a short word). Expected is `spec.identity` + and is blank where spec does not record the field. The compared System is + the one reporting the spec system UUID, else the spec serial (as serial + number or SKU), else the only System; with several candidates the table is + hidden and the IdentityMatched chip carries the reason. An observed value + is red when IdentityMatched is False with SerialMismatch, ModelMismatch or + SystemUUIDMismatch for that field (the condition message is the tooltip), + or when it differs by discovery's rule (a vendor prefix on the model is + allowed). Manufacturer is shown but, as in discovery, not compared. The + page never calls identity verified. +- **Observation from another endpoint.** When the retained inventory was + read from an endpoint other than `spec.bmc.endpoint` (or spec records no + endpoint), discovery reports + IdentityMatched Unknown with StaleObservation, so the page compares + nothing: observed values are amber with "Read from … ; spec.bmc.endpoint + is …" as the tooltip, no spec MAC is marked unobserved, and a TLS key + read from another endpoint is amber before anyone approves it. +- **Host NICs.** `systems[].networkInterfaces` of the compared System, one + row each: NIC, MAC address, Link, and Speed when reported. A link that is + not up (LinkDown, NoLink or not reported) is amber with the raw + `linkStatus` as its tooltip. An observed MAC that `spec.interfaces` + records is followed by that interface's name; matching is by MAC address + only, never by name. When spec interfaces match no component, their table + sits beside the host NICs, with a spec MAC no NIC reports in amber. + Interfaces that match a component keep their MAC in the component table, + so no MAC is listed twice. +- **Management.** The five conditions as one line of chips (Reachable, Auth, + Inventory, Identity, Key unique), each with type, status, reason and + message as its tooltip: red ✕ for False, amber ? for Unknown or absent, + plain for True. Then **Last attempt** (relative, absolute time as the + tooltip; the attempt endpoint is added in amber only when it differs from + `spec.bmc.endpoint`), **TLS key** (the SHA-256 shortened, full value as + the tooltip, with Copy), **Key expiry** (amber within 30 days, red once + expired), and **Key approval**: Approved when Authenticated is True, "Not + approved" in amber for PinNotApproved, red for PinMismatch, and hidden for + other reasons. Then a BMC table (Manager, Model, Firmware, and the service + root's Redfish version, Vendor and Product; empty columns hidden) and the + manager NICs in the same NIC table form. +- **Before discovery.** A Device with a BMC endpoint and no status adds one + muted "Not discovered" fact under Management and nothing else. +- **Unreadable Devices.** Status arrives only inside a readable Device. A + denied or redacted Device collection shows the access state, never a + Device or its status. + +The preview fixtures carry discovery status on three servers: a01-01 +(matched, powered on, NICs up, key approved), a01-02 (serial mismatch, a +spec MAC not observed, an interface outside the component list) and a01-05 +(key not approved, certificate expiring in 12 days, one host NIC down). +`device-discovery.test.ts` and `device-discovery.test.tsx` cover the +comparison and mismatch marking, condition chips and tooltips, +PinNotApproved, expiry tones, link states, MAC matching without name +mapping, the no-status case and denied Devices. + `device-connections.test.tsx` covers the picture with no toggle, the table columns and rows (unmatched lanes included), conditional serial and asset columns, the single count line, the absence of a legend and a diagram diff --git a/ui/provider/scripts/screenshot-pages.ts b/ui/provider/scripts/screenshot-pages.ts index 796138ac..874b8cf3 100644 --- a/ui/provider/scripts/screenshot-pages.ts +++ b/ui/provider/scripts/screenshot-pages.ts @@ -66,6 +66,11 @@ export const PAGES: CapturePage[] = [ { name: 'server-detail', path: record('Device', 'example-srv-a01-01'), ready: '.inventory-connections' }, // The secondary tab and the Record section that closes every record page. { name: 'device-hardware', path: record('Device', 'example-srv-a01-01', '&tab=hardware'), ready: '[data-tab="hardware"] .inventory-fact-section', element: '.inventory-record-tabs', viewports: ['desktop-light', 'desktop-dark', 'phone'] }, + // BMC discovery in the Hardware & management tab: matched, identity mismatch, key not approved. + { name: 'device-discovery-matched', path: record('Device', 'example-srv-a01-01', '&tab=hardware'), ready: '[data-tab="hardware"] .inventory-discovery-chips', viewports: ['desktop-light', 'desktop-dark', 'phone'] }, + { name: 'device-discovery-mismatch', path: record('Device', 'example-srv-a01-02', '&tab=hardware'), ready: '[data-tab="hardware"] .inventory-discovery-chips', element: '.inventory-record-tabs', viewports: ['desktop-light', 'phone'] }, + { name: 'device-discovery-pin', path: record('Device', 'example-srv-a01-05', '&tab=hardware'), ready: '[data-tab="hardware"] .inventory-discovery-chips', viewports: ['desktop-light', 'phone'] }, + { name: 'device-discovery-none', path: record('Device', 'example-srv-a02-02', '&tab=hardware'), ready: '[data-tab="hardware"] .inventory-fact-section', element: '.inventory-record-tabs', viewports: ['desktop-light', 'phone'] }, { name: 'device-location', path: record('Device', 'example-srv-a01-01', '&tab=location'), ready: '[data-tab="location"] .inventory-fields', element: '.inventory-record-tabs', viewports: ['desktop-light', 'phone'] }, { name: 'record-footer', path: record('Device', 'example-srv-a01-01'), ready: '.inventory-record-footer', element: '.inventory-record-footer', viewports: ['desktop-light', 'phone'] }, // Device detail for a model without a layout (grouped tiles), and the one component table. diff --git a/ui/provider/src/components/device-connections.tsx b/ui/provider/src/components/device-connections.tsx index 76046938..8d87685e 100644 --- a/ui/provider/src/components/device-connections.tsx +++ b/ui/provider/src/components/device-connections.tsx @@ -14,6 +14,7 @@ import { type ConnectionGroup, type ConnectionLink, type DeviceConnections as JoinResult, type LinkState, type TraceHop, type ViewNames, } from '../lib/device-connections'; import { faceplate } from '../lib/device-faceplate'; +import { unobservedMacs } from '../lib/device-discovery'; import { componentChassisFace, componentRackFace, deviceMountedFace } from '../lib/rack-faces'; import { cableText, peerDetail, PeerTarget, peerText, portsWord, StateText, TileSummary, type Href } from './connection-parts'; import { PortFaceplate, type ComponentHighlight } from './device-faceplate'; @@ -41,6 +42,8 @@ interface ComponentRow { assetTag?: string; /** The recorded interface MAC address for a port of the same name. */ mac?: string; + /** Why the MAC needs checking: discovery read the host NICs and none reports it. */ + macNote?: string; /** The position the Cable names, for a lane end that matches no recorded position. */ unmatched?: { position?: number }; } @@ -56,6 +59,7 @@ const GROUP_ORDER = connectionGroups.map(item => item.group); function componentRows(device: Device, inventory: Inventory, join: JoinResult, unmatched: ConnectionLink[]): ComponentRow[] { const tiles = new Map(portTiles(join.links).map(tile => [tile.key, tile])); const macs = interfaceAddresses(device).byComponent; + const unobserved = unobservedMacs(device); const mounted = deviceMountedFace(device, inventory); const used = new Set(); const rows: (ComponentRow & { group: ConnectionGroup })[] = (device.spec.components ?? []).map((component, index) => { @@ -67,6 +71,7 @@ function componentRows(device: Device, inventory: Inventory, join: JoinResult, u key: `component/${index}`, group, name: component.name, id: component.id, type: component.type, connector: component.connector, chassisFace, rackFace: componentRackFace(mounted, chassisFace), positions: component.positions ?? 1, state: tile?.state, links: tile?.links ?? [], serial: component.serial, assetTag: component.assetTag, mac: macs.get(component.id), + macNote: (device.spec.interfaces ?? []).filter(iface => iface.name === component.name || iface.name === component.id).map(iface => unobserved.get(iface.name)).find(Boolean), }; }); for (const tile of tiles.values()) { @@ -192,7 +197,7 @@ function ComponentTable({ rows, cablesDenied, namespace, href, names, highlight, } - {macs && {row.mac}} + {macs && {row.macNote ? {row.mac}. Check: {row.macNote} : row.mac}} {serials && {row.serial}} {tags && {row.assetTag}} diff --git a/ui/provider/src/components/device-discovery.test.tsx b/ui/provider/src/components/device-discovery.test.tsx new file mode 100644 index 00000000..30d7dc1d --- /dev/null +++ b/ui/provider/src/components/device-discovery.test.tsx @@ -0,0 +1,163 @@ +import { render, screen, within } from '@testing-library/react'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { MemoryRouter } from 'react-router'; +import { describe, expect, it } from 'vitest'; +import { PhysicalInventory } from './physical-inventory'; +import { fixtureInventory, FIXTURE_NAMES } from '../lib/inventory-fixtures'; +import { redactInventory } from '../lib/inventory-read-access'; +import type { Inventory } from '../inventory'; + +function show(name: string, inventory: Inventory = fixtureInventory()) { + return render( + + ); +} +const MATCHED = FIXTURE_NAMES.server; +const MISMATCHED = 'example-srv-a01-02'; +const PENDING = FIXTURE_NAMES.singleFeedServer; +const hardware = () => screen.getByRole('region', { name: 'Hardware & management' }); +const table = (label: string) => within(hardware()).getByRole('table', { name: label }); +const rowOf = (label: string, first: string) => within(table(label)).getAllByRole('row').find(row => within(row).queryAllByRole('cell')[0]?.textContent === first)!; +const cells = (label: string, first: string) => within(rowOf(label, first)).getAllByRole('cell'); +const chips = () => within(within(hardware()).getByRole('list', { name: 'Discovery conditions' })).getAllByRole('listitem'); +const fact = (label: string) => within(hardware()).getByText(label, { selector: 'dt' }).nextElementSibling as HTMLElement; +const header = (container: HTMLElement) => container.querySelector('.inventory-fact-strip')!; + +describe('Device page: expected next to observed identity', () => { + it('shows spec and discovery side by side, plain when they agree', () => { + show(MATCHED); + expect(within(table('Identity')).getAllByRole('columnheader').map(cell => cell.textContent)).toEqual(['Field', 'Expected', 'Observed']); + expect(cells('Identity', 'Serial').map(cell => cell.textContent)).toEqual(['Serial', 'SYNTH-EX-01', 'SYNTH-EX-01']); + expect(cells('Identity', 'Model').map(cell => cell.textContent)).toEqual(['Model', 'EX-C1', 'Example EX-C1']); + // Spec records no SKU or power state: the expected cell is blank. + expect(cells('Identity', 'SKU').map(cell => cell.textContent)).toEqual(['SKU', '', 'SYNTH-SKU-1']); + expect(cells('Identity', 'Power')[2]).toHaveTextContent(/^On$/); + expect(table('Identity').querySelector('[data-tone]')).toBeNull(); + expect(hardware()).not.toHaveTextContent(/verified/i); + // The table states the system UUID; the plain fact is not repeated. + expect(within(hardware()).queryByText('System UUID', { selector: 'dt' })).toBeNull(); + }); + + it('marks a serial IdentityMatched rejects red, with the condition message as its tooltip and accessible text', () => { + show(MISMATCHED); + const observed = cells('Identity', 'Serial')[2]; + const mark = observed.querySelector('[data-tone="danger"]')!; + expect(mark).toHaveTextContent('SYNTH-OTHER-99'); + expect(mark).toHaveAttribute('title', 'the System with spec.identity.systemUUID reports another serial; spec is not changed'); + expect(observed).toHaveTextContent('Records disagree: the System with spec.identity.systemUUID reports another serial'); + expect(cells('Identity', 'Model')[2].querySelector('[data-tone]')).toBeNull(); + expect(chips().find(chip => chip.textContent?.includes('Identity'))).toHaveAttribute('data-tone', 'danger'); + }); +}); + +describe('Device page: discovery health', () => { + it('shows the five conditions as short chips with reason and message in the tooltip', () => { + show(MATCHED); + expect(chips().map(chip => chip.firstChild?.nextSibling?.textContent)).toEqual(['Reachable', 'Auth', 'Inventory', 'Identity', 'Key unique']); + for (const chip of chips()) expect(chip).not.toHaveAttribute('data-tone'); + expect(chips()[0]).toHaveAttribute('title', 'Reachable: True · ServiceRootRead · TLS handshake completed and the anonymous service root was read'); + expect(chips()[0]).toHaveTextContent('Reachable: True · ServiceRootRead'); + expect(fact('Last attempt')).toHaveTextContent(/^2 min ago$/); + expect(fact('Last attempt').querySelector('time')!.getAttribute('title')).toMatch(/^\d{4}-\d{2}-\d{2}T/); + expect(fact('Key approval')).toHaveTextContent(/^Approved/); + }); + + it('shows a shortened TLS fingerprint with the full value in the tooltip and a copy button', () => { + show(MATCHED); + const code = fact('TLS key').querySelector('code')!; + expect(code).toHaveTextContent(/^3f3f3f3f…3f3f$/); + expect(code).toHaveAttribute('title', '3f'.repeat(32)); + expect(within(fact('TLS key')).getByRole('button', { name: 'Copy TLS key fingerprint' })).toBeInTheDocument(); + expect(fact('Key expiry').querySelector('[data-tone]')).toBeNull(); + }); + + it('shows PinNotApproved as not approved, amber, with the reason in the tooltip, and an expiring key amber', () => { + const { container } = show(PENDING); + const approval = fact('Key approval').querySelector('[data-tone="warning"]')!; + expect(approval).toHaveTextContent(/^Not approved/); + expect(approval.getAttribute('title')).toMatch(/^PinNotApproved · the observed public key is in status.discovery.tls/); + expect(fact('Key expiry').querySelector('[data-tone="warning"]')).toHaveTextContent(/ · 1[12] d/); + expect(chips().find(chip => chip.textContent?.startsWith('✕ Auth'))).toHaveAttribute('data-tone', 'danger'); + // One chip in the header strip. + const chip = header(container).querySelectorAll('.inventory-discovery-chip'); + expect(chip).toHaveLength(1); + expect(chip[0]).toHaveTextContent(/^BMC key not approved/); + expect(chip[0]).toHaveAttribute('data-tone', 'danger'); + }); +}); + +describe('Device page: NICs and MAC addresses', () => { + it('shows each host NIC with its link, amber when it is not up', () => { + show(PENDING); + expect(cells('Host NICs', 'EthernetInterface0')[2]).toHaveTextContent(/^Up$/); + expect(cells('Host NICs', 'EthernetInterface0')[2].querySelector('[data-tone]')).toBeNull(); + const down = cells('Host NICs', 'EthernetInterface1')[2].querySelector('[data-tone="warning"]')!; + expect(down).toHaveTextContent(/^Down/); + expect(down).toHaveAttribute('title', 'LinkDown'); + }); + + it('lists the BMC with its firmware, Redfish service root and NICs', () => { + show(MATCHED); + expect(within(table('BMC')).getAllByRole('columnheader').map(cell => cell.textContent)).toEqual(['Manager', 'Model', 'Firmware', 'Redfish', 'Vendor', 'Product']); + expect(cells('BMC', 'BMC').map(cell => cell.textContent)).toEqual(['BMC', 'Example BMC 9', '7.10.30', '1.11.0', 'Example Compute', 'Example Integrated BMC']); + expect(cells('BMC NICs', 'eth0').map(cell => cell.textContent)).toEqual(['eth0', '00:00:5e:00:53:a1', 'Up', '1 Gb/s']); + }); + + it('puts spec interfaces beside observed NICs, matched by MAC address and never by name', () => { + const { container } = show(MISMATCHED); + // eth0 and eth1 are components, so their MACs stay in the component table; eth2 is not. + expect(within(table('Interfaces not in the component list')).getAllByRole('row').slice(1).map(row => row.textContent)).toEqual(['eth200:00:5e:00:53:23']); + expect(table('Host NICs').closest('.inventory-discovery-pair')).toBe(table('Interfaces not in the component list').closest('.inventory-discovery-pair')); + // An observed MAC the spec records names that interface; EthernetInterface1 reports another MAC and names none. + expect(cells('Host NICs', 'EthernetInterface0')[1]).toHaveTextContent(/^00:00:5e:00:53:21 · eth0$/); + expect(cells('Host NICs', 'EthernetInterface2')[1]).toHaveTextContent(/^00:00:5e:00:53:23 · eth2$/); + expect(cells('Host NICs', 'EthernetInterface1')[1]).toHaveTextContent(/^00:00:5e:00:53:29$/); + // The spec MAC no NIC reports is amber in the component table, where it is listed. + const components = within(container).getByRole('table', { name: /Components/ }); + const unseen = within(components).getByText('00:00:5e:00:53:22'); + expect(unseen).toHaveAttribute('data-tone', 'warning'); + expect(unseen).toHaveAttribute('title', 'No host NIC reports this MAC address'); + expect(within(components).getByText('00:00:5e:00:53:21')).not.toHaveAttribute('data-tone'); + }); + + it('shows only the observed NICs when spec records no interfaces', () => { + show(PENDING); + expect(within(hardware()).queryByRole('table', { name: 'Interfaces not in the component list' })).toBeNull(); + expect(table('Host NICs').closest('.inventory-discovery-pair')).toBeNull(); + }); +}); + +describe('Device page before discovery and when Devices are unreadable', () => { + it('adds only a muted "Not discovered" when status is empty', () => { + const { container } = show('example-srv-a02-02'); + expect(fact('Discovery')).toHaveTextContent(/^Not discovered$/); + expect(fact('Discovery').firstElementChild).toHaveClass('inventory-muted'); + expect(within(hardware()).queryByRole('list', { name: 'Discovery conditions' })).toBeNull(); + expect(within(hardware()).queryByRole('table', { name: /Identity|Host NICs|BMC/ })).toBeNull(); + expect(header(container).querySelector('.inventory-discovery-chip')).toBeNull(); + }); + + it.each([ + ['answers 403', { ...fixtureInventory(), issues: { Device: { status: 403 } } }], + ['is redacted after a later denial', redactInventory(fixtureInventory(), { Device: { status: 403 } })], + ])('shows no status when the Device collection %s', (_, inventory) => { + const { container } = show(MATCHED, inventory as Inventory); + expect(container.textContent).not.toMatch(/3f3f3f3f|SYNTH-SKU-1|EthernetInterface|BMC ✓|Key approval/); + expect(container.querySelector('.inventory-discovery-chip')).toBeNull(); + }); +}); + +describe('Device page: an observation from another endpoint', () => { + it('marks the retained key and observed identity amber, with no red disagreement', () => { + const inventory = structuredClone(fixtureInventory()); + const device = [...inventory.slots.flatMap(slot => slot.devices), ...inventory.unboundDevices].find(item => item.metadata.name === MISMATCHED)!; + device.spec.bmc = { endpoint: 'https://192.0.2.250' }; + device.status!.conditions = device.status!.conditions!.map(condition => condition.type === 'IdentityMatched' ? { ...condition, status: 'Unknown', reason: 'StaleObservation', message: 'the retained inventory was read from another endpoint' } : condition); + show(MISMATCHED, inventory); + const serial = cells('Identity', 'Serial')[2].querySelector('[data-tone]')!; + expect(serial).toHaveAttribute('data-tone', 'warning'); + expect(serial.getAttribute('title')).toMatch(/^Read from .*; spec.bmc.endpoint is https:\/\/192.0.2.250$/); + expect(within(table('Identity')).queryAllByText((_, element) => element?.getAttribute('data-tone') === 'danger')).toHaveLength(0); + expect(fact('TLS key').querySelector('[data-tone="warning"] code')).not.toBeNull(); + }); +}); diff --git a/ui/provider/src/components/device-discovery.tsx b/ui/provider/src/components/device-discovery.tsx new file mode 100644 index 00000000..74ab08ff --- /dev/null +++ b/ui/provider/src/components/device-discovery.tsx @@ -0,0 +1,153 @@ +// The Device page's view of BMC discovery: Device.status, next to the spec it +// is compared with. See "Device page" in docs/development/staff-inventory-ui.md. +// Red is a disagreement or failure, amber needs checking, and OK stays plain. +import { useState, type ReactNode } from 'react'; +import type { Device } from '../../../shared/fleet-api'; +import { + bmcChip, conditionChips, hostNics, identityRows, keyApproval, linkState, shortFingerprint, specNamesFor, speedWords, staleReason, tlsExpiry, unobservedMacs, type Tone, +} from '../lib/device-discovery'; +import { interfaceAddresses } from '../lib/device-connections'; +import { formatAge } from '../lib/telemetry'; +import { Facts, SmallTable } from './inventory-record-layout'; + +/** A value that carries its reason in the tooltip and in its accessible text. */ +function Marked({ tone, reason, children }: { tone: Tone; reason?: string; children: ReactNode }) { + if (!tone) return {children}; + return + {children} + {reason && . {tone === 'danger' ? 'Records disagree' : 'Check'}: {reason}} + ; +} + +/** The header's one BMC chip; nothing before discovery has run. */ +export function BmcChip({ device }: { device: Device }) { + const chip = bmcChip(device); + if (!chip) return null; + return
BMC
+ {chip.label}. {chip.reason} +
; +} + +/** The five conditions as one line of chips; the reason and message are each chip's tooltip. */ +export function ConditionChips({ device }: { device: Device }) { + return
    + {conditionChips(device).map(chip =>
  • + {chip.word} + . {chip.reason} +
  • )} +
; +} + +function CopyValue({ value, label }: { value: string; label: string }) { + const [copied, setCopied] = useState(false); + return ; +} + +/** Discovery health: conditions, last attempt, TLS key, expiry and approval. */ +export function DiscoveryHealth({ device, now }: { device: Device; now: number }) { + const discovery = device.status?.discovery; + const attempt = discovery?.lastAttemptAt ? Date.parse(discovery.lastAttemptAt) : NaN; + const tls = discovery?.tls; + const expiry = tlsExpiry(tls?.notAfter, now); + const approval = keyApproval(device); + // The endpoint is spec.bmc.endpoint's row unless the last attempt went elsewhere. + const otherEndpoint = discovery?.lastAttemptEndpoint && discovery.lastAttemptEndpoint !== device.spec.bmc?.endpoint ? discovery.lastAttemptEndpoint : undefined; + return <> + + + + {otherEndpoint && <> · {otherEndpoint}} + }, + { label: 'TLS key', value: tls && + {/* A key read from another endpoint is not this BMC's: mark it before anyone approves it. */} + {shortFingerprint(tls.publicKeySHA256)} + SHA-256 {tls.publicKeySHA256} + + }, + { label: 'Key expiry', value: expiry && {expiry.label} }, + { label: 'Key approval', value: approval && {approval.label} }, + ]} /> + ; +} + +/** Field | Expected (spec) | Observed (discovery); a disagreement is red with its reason. */ +export function IdentityComparison({ device }: { device: Device }) { + const rows = identityRows(device); + if (!rows.length) return null; + return
[ + row.field, + {row.expected}, + {row.observed}, + ])} />
; +} + +function nicRows(nics: ReturnType, mark?: (macAddress?: string) => ReactNode) { + const speed = nics.some(nic => nic.speedMbps); + const system = nics.some(nic => nic.system); + const head = [...(system ? ['System'] : []), 'NIC', 'MAC address', 'Link', ...(speed ? ['Speed'] : [])]; + const rows = nics.map(nic => { + const link = linkState(nic); + return [ + ...(system ? [nic.system] : []), + nic.id, + {nic.macAddress}{mark?.(nic.macAddress)}, + {link.label}, + ...(speed ? [{speedWords(nic.speedMbps)}] : []), + ]; + }); + return { head, rows }; +} + +/** + * Spec interfaces next to observed host NICs. Names are never matched: a MAC + * address an observed NIC shares with a spec interface names that interface, + * and a spec MAC no NIC reports is amber. Spec interfaces that match a + * component keep their MAC in the component table, so only the others are + * listed here; with none, only the observed NICs show. + */ +export function NicComparison({ device }: { device: Device }) { + const nics = hostNics(device); + const spec = interfaceAddresses(device).unplaced; + if (!device.status?.discovery?.inventory || (!nics.length && !spec.length)) return null; + const unseen = unobservedMacs(device); + const observed = nicRows(nics, address => { + const names = specNamesFor(device, address); + return names.length ? · {names.join(', ')} : null; + }); + const observedTable = nics.length ? :

No host NICs reported

; + if (!spec.length) return observedTable; + return
+ [ + iface.name, + iface.macAddress ? {iface.macAddress} : Not recorded, + ])} /> + {observedTable} +
; +} + +/** The BMC: each manager with the service root's Redfish facts, then its NICs. */ +export function BmcComparison({ device }: { device: Device }) { + const managers = device.status?.discovery?.inventory?.managers ?? []; + const root = device.status?.discovery?.serviceRoot; + if (!managers.length && !root) return null; + const columns: [string, (manager?: typeof managers[number]) => string | undefined][] = [ + ['Manager', manager => manager?.id], + ['Model', manager => manager?.model], + ['Firmware', manager => manager?.firmwareVersion], + ['Redfish', () => root?.redfishVersion], + ['Vendor', () => root?.vendor], + ['Product', () => root?.product], + ]; + const rowsFor = managers.length ? managers : [undefined]; + const shown = columns.filter(([, value]) => rowsFor.some(manager => value(manager))); + const nics = managers.flatMap(manager => (manager.networkInterfaces ?? []).map(nic => ({ ...nic, system: managers.length > 1 ? manager.id : undefined }))); + const nicTable = nicRows(nics); + return <> + {!!shown.length && head)} rows={rowsFor.map(manager => shown.map(([, value]) => value(manager)))} />} + {!!nics.length && head === 'System' ? 'Manager' : head)} rows={nicTable.rows} />} + ; +} diff --git a/ui/provider/src/components/inventory-record-detail.tsx b/ui/provider/src/components/inventory-record-detail.tsx index 9555ba25..a854a684 100644 --- a/ui/provider/src/components/inventory-record-detail.tsx +++ b/ui/provider/src/components/inventory-record-detail.tsx @@ -23,6 +23,8 @@ import { observedDisagrees, type TelemetryContextValue } from '../lib/telemetry' import { feedPath } from '../lib/power-paths'; import { DeviceDrawFact, PowerFeedPath, UPSTREAM_INLINE_LIMIT, upstreamWords } from './power-feed-path'; import { CapacityBar, useTelemetry } from './power-telemetry'; +import { BmcChip, BmcComparison, DiscoveryHealth, IdentityComparison, NicComparison } from './device-discovery'; +import { discovered, identityRows } from '../lib/device-discovery'; export type DetailKind = 'Site' | 'Device' | 'Facility' | 'Rack' | 'DeviceClaim' | 'Cable' | 'PowerFeed' | 'Manufacturer' | 'DeviceType'; export type DetailEntry = { kind: DetailKind; record: RawDevice | RawDeviceClaim | PhysicalRecord }; @@ -113,6 +115,7 @@ export function deviceDetail(device: RawDevice, helpers: DetailHelpers, location {device.spec.identity.serial &&
Serial
{device.spec.identity.serial}
} {device.spec.assetTag &&
Asset tag
{device.spec.assetTag}
} {components.some(component => component.type === 'PowerInlet') && } + ; @@ -132,6 +135,10 @@ export function deviceDetail(device: RawDevice, helpers: DetailHelpers, location ].filter(Boolean).join(' · ') : helpers.placement({ kind: 'Device', record: device }); const unplaced = interfaceAddresses(device).unplaced; + // Discovery's observations sit next to the spec facts they are compared with. + const observed = discovered(device); + const compared = identityRows(device).length > 0; + const nicsObserved = !!device.status?.discovery?.inventory; const tabs: RecordTab[] = [ { id: 'location', label: 'Location', content: <> @@ -150,18 +157,24 @@ export function deviceDetail(device: RawDevice, helpers: DetailHelpers, location id: 'hardware', label: 'Hardware & management', content: <> - {/* Interfaces that match a component show their MAC in the component table. */} - {!!unplaced.length && [iface.name, iface.macAddress ?? 'Not recorded'])} />} + + {/* Interfaces that match a component show their MAC in the component table; the NIC comparison lists every spec interface. */} + {nicsObserved ? + : !!unplaced.length && [iface.name, iface.macAddress ?? 'Not recorded'])} />} - {(device.spec.bmc || device.spec.providerHostRef) && + {(device.spec.bmc || device.spec.providerHostRef || observed) && Not discovered }, ]} /> + {observed && } + } {!!device.spec.internalMappings?.length && [`${mapping.from.componentID}:${mapping.from.position}`, `${mapping.to.componentID}:${mapping.to.position}`])} /> diff --git a/ui/provider/src/components/inventory-record-layout.test.tsx b/ui/provider/src/components/inventory-record-layout.test.tsx index ed02953a..d58bf0f8 100644 --- a/ui/provider/src/components/inventory-record-layout.test.tsx +++ b/ui/provider/src/components/inventory-record-layout.test.tsx @@ -136,7 +136,7 @@ describe('Device page states each fact once', () => { const { container } = show(record('Device', 'example-srv-a01-01')); const header = container.querySelector('.inventory-record-header')!; expect(header.querySelector('dl.inventory-fact-strip')).toHaveAttribute('aria-label', 'Identity'); - expect(facts(header)).toEqual(['ModelExample 1U compute', 'SerialSYNTH-EX-01', 'Asset tagEX-ASSET-01']); + expect(facts(header)).toEqual(['ModelExample 1U compute', 'SerialSYNTH-EX-01', 'Asset tagEX-ASSET-01', expect.stringMatching(/^BMCBMC ✓/)]); // The old Identity row and its separate draw line are gone from the body. expect(container.querySelector('.inventory-primary .inventory-fields')).toBeNull(); expect(container.querySelector('.inventory-primary .inventory-device-draw')).toBeNull(); @@ -159,7 +159,10 @@ describe('Device page states each fact once', () => { const table = screen.getByRole('table', { name: /Components/ }); expect(within(table).getByRole('columnheader', { name: 'MAC address' })).toBeInTheDocument(); expect(within(table).getByText('00:00:5e:00:53:11')).toBeInTheDocument(); - expect(container.querySelector('[data-tab="hardware"]')!.textContent).not.toMatch(/00:00:5e:00:53:11/); + // The tab lists the recorded MAC only where discovery observed it, on the host NIC that reports it. + const hardware = container.querySelector('[data-tab="hardware"]')!; + expect(within(hardware).queryByRole('table', { name: 'Interfaces not in the component list' })).toBeNull(); + expect(within(hardware).getAllByText('00:00:5e:00:53:11').map(cell => cell.closest('table')?.getAttribute('aria-label'))).toEqual(['Host NICs']); expect(within(location).getByText('Depth for rack conflicts')).toBeInTheDocument(); // Placement states units, height and face; the header has the facility and rack, and depth has its own fact. const placement = within(location).getByText('Placement').nextElementSibling as HTMLElement; diff --git a/ui/provider/src/components/physical-inventory.css b/ui/provider/src/components/physical-inventory.css index 330a41be..9702a712 100644 --- a/ui/provider/src/components/physical-inventory.css +++ b/ui/provider/src/components/physical-inventory.css @@ -594,3 +594,17 @@ .inventory-form .inventory-editor-table input,.inventory-form .inventory-editor-table select { height:30px; min-width:72px; padding:2px 8px; font-size:13px; } .inventory-endpoint-picker { display:grid; grid-template-columns:minmax(120px,1fr) minmax(96px,1fr); gap:4px; } .inventory-lane-table td:first-child { width:110px; } + +/* BMC discovery on the Device page: red disagrees or failed, amber needs checking, OK is plain. */ +.inventory-discovery-chips { display:flex; flex-wrap:wrap; gap:4px; margin:0; padding:0; list-style:none; } +.inventory-discovery-chip { display:inline-flex; align-items:center; gap:3px; padding:0 6px; border:1px solid var(--border); border-radius:4px; font-size:12px; line-height:20px; white-space:nowrap; } +.inventory-discovery-chip[data-tone="danger"] { border-color:var(--destructive); color:var(--destructive); font-weight:500; } +.inventory-discovery-chip[data-tone="warning"] { border-color:var(--warning,#d97706); } +.inventory-fact-strip .inventory-discovery-chip { line-height:18px; } +.inventory-discovery-mark[data-tone="danger"] { color:var(--destructive); font-weight:500; } +.inventory-discovery-key { display:inline-flex; flex-wrap:wrap; align-items:baseline; gap:6px; min-width:0; } +.inventory-copy { padding:0 6px; border:1px solid var(--border); border-radius:4px; background:transparent; color:var(--muted-foreground); font-size:11px; line-height:18px; cursor:pointer; } +.inventory-copy:hover,.inventory-copy:focus-visible { color:var(--foreground); } +.inventory-discovery-pair { display:flex; flex-wrap:wrap; align-items:flex-start; gap:8px 24px; min-width:0; } +.inventory-discovery-pair > * { min-width:0; } +.inventory-discovery-identity .inventory-dense-table td:not(:first-child) { white-space:normal; overflow-wrap:anywhere; } diff --git a/ui/provider/src/lib/device-discovery.test.ts b/ui/provider/src/lib/device-discovery.test.ts new file mode 100644 index 00000000..5e3e6ef9 --- /dev/null +++ b/ui/provider/src/lib/device-discovery.test.ts @@ -0,0 +1,143 @@ +import { describe, expect, it } from 'vitest'; +import type { Device, ObservedSystem } from '../../../shared/fleet-api'; +import { bmcChip, comparedSystem, conditionChips, identityRows, keyApproval, linkState, powerWord, shortFingerprint, specNamesFor, staleReason, tlsExpiry, unobservedMacs } from './device-discovery'; + +const NOW = Date.parse('2026-06-01T00:00:00Z'); +const DAY = 86_400_000; + +function device(status?: Device['status'], spec: Partial = {}): Device { + return { + metadata: { name: 'example-host' }, + spec: { claimRef: { name: 'example-claim' }, identity: { model: 'X1', serial: 'SYNTH-1', systemUUID: '00000000-0000-4000-8000-000000000001' }, bmc: { endpoint: 'https://192.0.2.1' }, ...spec }, + status, + }; +} +const system: ObservedSystem = { id: 'System.1', uuid: '00000000-0000-4000-8000-000000000001', model: 'Vendor X1', serialNumber: 'SYNTH-1', powerState: 'On' }; +const inventory = (systems = [system]) => ({ discovery: { inventory: { observedAt: '2026-06-01T00:00:00Z', endpoint: 'https://192.0.2.1', systems } } }); +const cond = (type: string, status: 'True' | 'False' | 'Unknown', reason: string, message = `${reason} message`) => ({ type, status, reason, message }); + +describe('condition chips', () => { + it('is red for False, amber for Unknown or absent, plain for True, with type, status, reason and message in the tooltip', () => { + const chips = conditionChips(device({ conditions: [cond('Reachable', 'True', 'ServiceRootRead'), cond('Authenticated', 'False', 'CredentialRejected'), cond('Discovered', 'Unknown', 'ReadFailed')] })); + expect(chips.map(chip => [chip.word, chip.tone])).toEqual([['Reachable', undefined], ['Auth', 'danger'], ['Inventory', 'warning'], ['Identity', 'warning'], ['Key unique', 'warning']]); + expect(chips[1].reason).toBe('Authenticated: False · CredentialRejected · CredentialRejected message'); + expect(chips[3].reason).toBe('IdentityMatched: Unknown · not reported'); + }); + + it('summarises as one header chip, naming the first failure', () => { + expect(bmcChip(device())).toBeUndefined(); + expect(bmcChip(device({ conditions: [cond('Reachable', 'False', 'ConnectFailed')] }))).toMatchObject({ label: 'BMC unreachable', tone: 'danger' }); + expect(bmcChip(device({ conditions: [cond('Reachable', 'True', 'ServiceRootRead'), cond('Authenticated', 'False', 'PinNotApproved')] }))).toMatchObject({ label: 'BMC key not approved', tone: 'danger' }); + expect(bmcChip(device({ conditions: [cond('Reachable', 'True', 'ServiceRootRead')] }))).toMatchObject({ label: 'BMC ?', tone: 'warning' }); + const ok = ['Reachable', 'Authenticated', 'Discovered', 'IdentityMatched', 'PublicKeyUnique'].map(type => cond(type, 'True', 'Fine')); + expect(bmcChip(device({ conditions: ok }))).toMatchObject({ label: 'BMC ✓', tone: undefined }); + }); +}); + +describe('key approval', () => { + it('reads PinNotApproved as not approved and CredentialAccepted as approved', () => { + expect(keyApproval(device({ conditions: [cond('Authenticated', 'False', 'PinNotApproved', 'verify it out of band')] }))).toEqual({ label: 'Not approved', tone: 'warning', reason: 'PinNotApproved · verify it out of band' }); + expect(keyApproval(device({ conditions: [cond('Authenticated', 'True', 'CredentialAccepted')] }))).toMatchObject({ label: 'Approved', tone: undefined }); + expect(keyApproval(device({ conditions: [cond('Authenticated', 'False', 'PinMismatch')] }))).toMatchObject({ tone: 'danger' }); + // Other reasons say nothing about the pin. + expect(keyApproval(device({ conditions: [cond('Authenticated', 'Unknown', 'NotAttempted')] }))).toBeUndefined(); + }); +}); + +describe('TLS expiry', () => { + it('is red once expired, amber within 30 days and plain after', () => { + expect(tlsExpiry(new Date(NOW - DAY).toISOString(), NOW)).toMatchObject({ tone: 'danger', label: 'Expired 2026-05-31' }); + expect(tlsExpiry(new Date(NOW + 12 * DAY).toISOString(), NOW)).toMatchObject({ tone: 'warning', label: '2026-06-13 · 12 d' }); + expect(tlsExpiry(new Date(NOW + 30 * DAY).toISOString(), NOW)?.tone).toBe('warning'); + expect(tlsExpiry(new Date(NOW + 31 * DAY).toISOString(), NOW)).toMatchObject({ tone: undefined, label: '2026-07-02' }); + expect(tlsExpiry(undefined, NOW)).toBeUndefined(); + }); + + it('shortens the fingerprint', () => expect(shortFingerprint('ab'.repeat(32))).toBe('abababab…abab')); +}); + +describe('identity rows', () => { + it('compares serial, model and system UUID by the rules discovery uses', () => { + const rows = identityRows(device({ ...inventory([{ ...system, sku: 'SKU-9' }]), conditions: [cond('IdentityMatched', 'True', 'Matched')] })); + expect(rows.map(row => [row.field, row.expected, row.observed, row.mismatch])).toEqual([ + ['Serial', 'SYNTH-1', 'SYNTH-1', undefined], + // A vendor family prefix is not a mismatch. + ['Model', 'X1', 'Vendor X1', undefined], + ['System UUID', '00000000-0000-4000-8000-000000000001', '00000000-0000-4000-8000-000000000001', undefined], + ['SKU', undefined, 'SKU-9', undefined], + ['Power', undefined, 'On', undefined], + ]); + }); + + it('marks the field IdentityMatched names, with its message', () => { + const rows = identityRows(device({ ...inventory([{ ...system, serialNumber: 'SYNTH-OTHER' }]), conditions: [cond('IdentityMatched', 'False', 'SerialMismatch', 'reports another serial')] })); + expect(rows.find(row => row.field === 'Serial')?.mismatch).toBe('reports another serial'); + expect(rows.find(row => row.field === 'Model')?.mismatch).toBeUndefined(); + }); + + it('accepts the spec serial as the SKU, and marks a different model without a condition', () => { + const rows = identityRows(device(inventory([{ ...system, serialNumber: 'BOARD-7', sku: 'synth-1', model: 'Y2' }]))); + expect(rows.find(row => row.field === 'Serial')?.mismatch).toBeUndefined(); + expect(rows.find(row => row.field === 'Model')?.mismatch).toBe('Discovery reports Y2; spec records X1'); + }); + + it('leaves the expected cell blank where spec does not record the field', () => { + const rows = identityRows(device(inventory(), { identity: { model: 'X1', serial: 'SYNTH-1' } })); + expect(rows.find(row => row.field === 'System UUID')).toMatchObject({ expected: undefined, mismatch: undefined }); + }); + + it('compares no System when more than one could be this Device', () => { + const many = device(inventory([{ ...system, uuid: undefined }, { ...system, id: 'System.2', uuid: undefined }]), { identity: { model: 'X1' } }); + expect(comparedSystem(many)).toBeUndefined(); + expect(identityRows(many)).toEqual([]); + }); + + it('shows power state as a short word', () => { + expect(powerWord('PoweringOn')).toBe('Starting'); + expect(powerWord('Off')).toBe('Off'); + }); +}); + +describe('NICs and MAC addresses', () => { + it('is amber unless the link is up', () => { + expect(linkState({ id: 'n', linkStatus: 'LinkUp' })).toEqual({ label: 'Up', tone: undefined }); + expect(linkState({ id: 'n', linkStatus: 'LinkDown' })).toEqual({ label: 'Down', tone: 'warning' }); + expect(linkState({ id: 'n', linkStatus: 'NoLink' })).toEqual({ label: 'No link', tone: 'warning' }); + expect(linkState({ id: 'n' })).toEqual({ label: 'Not reported', tone: 'warning' }); + }); + + it('matches spec interfaces to host NICs by MAC address only, never by name', () => { + const nics = [{ id: 'EthernetInterface0', macAddress: '00:00:5E:00:53:01' }, { id: 'EthernetInterface1', macAddress: '00:00:5e:00:53:09' }]; + const host = device(inventory([{ ...system, networkInterfaces: nics }]), { interfaces: [{ name: 'ETH0', macAddress: '00:00:5e:00:53:01' }, { name: 'ETH1', macAddress: '00:00:5e:00:53:02' }, { name: 'ETH2' }] }); + expect(specNamesFor(host, nics[0].macAddress)).toEqual(['ETH0']); + expect(specNamesFor(host, nics[1].macAddress)).toEqual([]); + expect([...unobservedMacs(host).keys()]).toEqual(['ETH1']); + }); + + it('marks nothing unobserved before an inventory read', () => { + expect(unobservedMacs(device({ conditions: [] }, { interfaces: [{ name: 'ETH0', macAddress: '00:00:5e:00:53:01' }] })).size).toBe(0); + }); +}); + +describe('observation from another endpoint', () => { + // Discovery reports IdentityMatched Unknown (StaleObservation) when the retained inventory came from another endpoint. + const moved = (systems = [{ ...system, serialNumber: 'SYNTH-OTHER' }]) => device({ ...inventory(systems), conditions: [cond('IdentityMatched', 'Unknown', 'StaleObservation')] }, { bmc: { endpoint: 'https://192.0.2.9' }, interfaces: [{ name: 'ETH0', macAddress: '00:00:5e:00:53:99' }] }); + + it('compares nothing and marks every observed value stale instead of red', () => { + const rows = identityRows(moved()); + expect(rows.every(row => !row.mismatch)).toBe(true); + expect(rows.find(row => row.field === 'Serial')).toMatchObject({ observed: 'SYNTH-OTHER', stale: 'Read from https://192.0.2.1; spec.bmc.endpoint is https://192.0.2.9' }); + }); + + it('marks no spec MAC as unobserved, since the NICs are another BMC\'s', () => { + expect(unobservedMacs(moved()).size).toBe(0); + }); + + it('names the endpoint only when it differs from spec', () => { + expect(staleReason({ endpoint: 'https://192.0.2.1' }, device())).toBeUndefined(); + expect(staleReason({ endpoint: 'https://192.0.2.7' }, device())).toBe('Read from https://192.0.2.7; spec.bmc.endpoint is https://192.0.2.1'); + expect(staleReason(undefined, device())).toBeUndefined(); + // Discovery treats a Device with no BMC endpoint in spec as stale too. + expect(staleReason({ endpoint: 'https://192.0.2.1' }, device(undefined, { bmc: undefined }))).toBe('Read from https://192.0.2.1; spec.bmc.endpoint is not set'); + }); +}); diff --git a/ui/provider/src/lib/device-discovery.ts b/ui/provider/src/lib/device-discovery.ts new file mode 100644 index 00000000..42394034 --- /dev/null +++ b/ui/provider/src/lib/device-discovery.ts @@ -0,0 +1,222 @@ +// What BMC discovery wrote to Device.status, shaped for the Device page. +// Discovery is the only writer of status (internal/bmcdiscovery); this module +// only reads it. The comparisons mirror internal/bmcdiscovery/status.go so the +// page marks the same fields the IdentityMatched condition does. +import type { Condition } from '../../../shared/conditions'; +import type { Device, ObservedNetworkInterface, ObservedSystem } from '../../../shared/fleet-api'; + +export type Tone = 'danger' | 'warning' | undefined; + +/** The five Device status conditions, in the order discovery evaluates them. */ +export const DISCOVERY_CONDITIONS = [ + { type: 'Reachable', word: 'Reachable' }, + { type: 'Authenticated', word: 'Auth' }, + { type: 'Discovered', word: 'Inventory' }, + { type: 'IdentityMatched', word: 'Identity' }, + { type: 'PublicKeyUnique', word: 'Key unique' }, +] as const; + +export interface ConditionChip { + type: string; + word: string; + status: Condition['status']; + tone: Tone; + /** "Reachable: False · ConnectFailed · no TLS handshake completed …" */ + reason: string; +} + +/** True when discovery has written anything for this Device. */ +export const discovered = (device: Device) => !!device.status?.discovery || !!device.status?.conditions?.length; + +const find = (device: Device, type: string) => device.status?.conditions?.find(condition => condition.type === type); + +/** One chip per condition. False is red, Unknown (or absent) amber, True plain. */ +export function conditionChips(device: Device): ConditionChip[] { + return DISCOVERY_CONDITIONS.map(({ type, word }) => { + const condition = find(device, type); + const status = condition?.status ?? 'Unknown'; + const reason = [`${type}: ${status}`, condition ? condition.reason : 'not reported', condition?.message].filter(Boolean).join(' · '); + return { type, word, status, tone: status === 'False' ? 'danger' : status === 'Unknown' ? 'warning' : undefined, reason }; + }); +} + +/** + * The one header chip: the first failing condition in discovery order, else + * the first unknown one, else "BMC ✓". Undefined before discovery has run. + */ +export function bmcChip(device: Device): { label: string; tone: Tone; reason: string } | undefined { + if (!discovered(device)) return undefined; + const chips = conditionChips(device); + const failed = chips.find(chip => chip.tone === 'danger'); + if (failed) { + const reason = find(device, failed.type)?.reason; + const label = failed.type === 'Reachable' ? 'BMC unreachable' + : failed.type === 'Authenticated' ? reason === 'PinNotApproved' ? 'BMC key not approved' : reason === 'PinMismatch' ? 'BMC key changed' : 'BMC auth failed' + : failed.type === 'Discovered' ? 'BMC not read' + : failed.type === 'IdentityMatched' ? 'Identity mismatch' + : 'BMC key shared'; + return { label, tone: 'danger', reason: failed.reason }; + } + const unknown = chips.find(chip => chip.tone === 'warning'); + if (unknown) return { label: 'BMC ?', tone: 'warning', reason: unknown.reason }; + return { label: 'BMC ✓', tone: undefined, reason: chips.map(chip => chip.reason).join('\n') }; +} + +/** + * Whether the observed TLS key is approved as the credential pin. Only the + * Authenticated condition says so: True means the pinned connection worked. + */ +export function keyApproval(device: Device): { label: string; tone: Tone; reason: string } | undefined { + const condition = find(device, 'Authenticated'); + if (!condition) return undefined; + const reason = [condition.reason, condition.message].filter(Boolean).join(' · '); + if (condition.status === 'True') return { label: 'Approved', tone: undefined, reason }; + if (condition.reason === 'PinNotApproved') return { label: 'Not approved', tone: 'warning', reason }; + if (condition.reason === 'PinMismatch') return { label: 'Does not match the approved key', tone: 'danger', reason }; + return undefined; +} + +const DAY = 86_400_000; + +/** TLS certificate expiry: red once expired, amber within 30 days. */ +export function tlsExpiry(notAfter: string | undefined, now: number): { label: string; tone: Tone; title: string } | undefined { + const at = notAfter ? Date.parse(notAfter) : NaN; + if (!Number.isFinite(at)) return undefined; + const days = Math.floor((at - now) / DAY); + const date = notAfter!.slice(0, 10); + if (at <= now) return { label: `Expired ${date}`, tone: 'danger', title: notAfter! }; + if (at - now <= 30 * DAY) return { label: `${date} · ${days < 1 ? 'under a day' : `${days} d`}`, tone: 'warning', title: `Expires ${notAfter}` }; + return { label: date, tone: undefined, title: `Expires ${notAfter}` }; +} + +/** "3f9a1c2e…77ab": the start and end of a fingerprint. */ +export const shortFingerprint = (value: string) => value.length > 16 ? `${value.slice(0, 8)}…${value.slice(-4)}` : value; + +const POWER_WORDS: Record = { On: 'On', Off: 'Off', PoweringOn: 'Starting', PoweringOff: 'Stopping', Paused: 'Paused' }; +export const powerWord = (state?: string) => state ? POWER_WORDS[state] ?? state : undefined; + +/** Redfish LinkStatus as a word, amber unless the link is up. */ +export function linkState(nic: ObservedNetworkInterface): { label: string; tone: Tone } { + const status = nic.linkStatus ?? ''; + if (/^(linkup|up)$/i.test(status)) return { label: 'Up', tone: undefined }; + if (/^(linkdown|down)$/i.test(status)) return { label: 'Down', tone: 'warning' }; + if (/^nolink$/i.test(status)) return { label: 'No link', tone: 'warning' }; + return { label: status || 'Not reported', tone: 'warning' }; +} + +export const speedWords = (mbps?: number) => !mbps ? undefined : mbps >= 1000 ? `${mbps / 1000} Gb/s` : `${mbps} Mb/s`; + +// ---- Identity: expected (spec) next to observed (discovery) ---- + +const normalize = (value?: string) => (value ?? '').toLowerCase().split(/\s+/).filter(Boolean).join(' '); +/** A vendor family prefix is allowed on either side, as in modelMatches. */ +const modelMatches = (expected?: string, observed?: string) => { + const e = normalize(expected), o = normalize(observed); + return e === o || (!!e && o.endsWith(` ${e}`)) || (!!o && e.endsWith(` ${o}`)); +}; +/** Some vendors report the chassis service tag as the SKU, as in serialMatches. */ +const serialMatches = (expected: string | undefined, system: ObservedSystem) => { + const e = normalize(expected); + return !!e && (e === normalize(system.serialNumber) || e === normalize(system.sku)); +}; + +/** + * The System discovery compares with spec: the one reporting the spec system + * UUID, else the spec serial, else the only System. Undefined when none or + * more than one could be this Device. + */ +export function comparedSystem(device: Device): ObservedSystem | undefined { + const systems = device.status?.discovery?.inventory?.systems ?? []; + const want = device.spec.identity; + const candidates = want.systemUUID ? systems.filter(system => system.uuid === want.systemUUID) + : want.serial ? systems.filter(system => serialMatches(want.serial, system)) + : systems; + if (candidates.length === 1) return candidates[0]; + return systems.length === 1 ? systems[0] : undefined; +} + +/** + * Why an observation can't be compared with spec: it was read from an endpoint + * other than spec.bmc.endpoint, or spec records no endpoint. Discovery reports + * IdentityMatched Unknown with reason StaleObservation then, so the page marks + * nothing as a disagreement. + */ +export function staleReason(observation: { endpoint: string } | undefined, device: Device): string | undefined { + const expected = device.spec.bmc?.endpoint; + if (!observation || observation.endpoint === expected) return undefined; + return `Read from ${observation.endpoint}; spec.bmc.endpoint is ${expected ?? 'not set'}`; +} + +export interface IdentityRow { + field: string; + expected?: string; + observed?: string; + /** Set when the two disagree; the reason is the tooltip. */ + mismatch?: string; + /** Set when the observation came from another endpoint: nothing is compared, and the reason is the tooltip. */ + stale?: string; +} + +const FIELD_REASON: Record = { SerialMismatch: 'Serial', ModelMismatch: 'Model', SystemUUIDMismatch: 'System UUID' }; + +/** + * Serial, model, manufacturer, system UUID, SKU and power. A field is red when + * IdentityMatched names it in a False reason, or when the two values differ by + * the rule discovery uses. Manufacturer is shown but not compared, as in + * discovery. Rows with neither value are left out. + */ +export function identityRows(device: Device): IdentityRow[] { + const system = comparedSystem(device); + if (!system) return []; + const want = device.spec.identity; + const matched = find(device, 'IdentityMatched'); + const flagged = matched?.status === 'False' && matched.reason ? FIELD_REASON[matched.reason] : undefined; + const stale = staleReason(device.status?.discovery?.inventory, device); + const differs = (field: string, expected: string | undefined, observed: string | undefined, same: boolean) => { + if (flagged === field) return matched?.message ?? matched?.reason; + if (stale) return undefined; + if (!expected || same) return undefined; + return observed ? `Discovery reports ${observed}; spec records ${expected}` : `Discovery reports no ${field.toLowerCase()}; spec records ${expected}`; + }; + const rows: IdentityRow[] = [ + { field: 'Serial', expected: want.serial, observed: system.serialNumber, mismatch: differs('Serial', want.serial, system.serialNumber, serialMatches(want.serial, system)) }, + { field: 'Model', expected: want.model, observed: system.model, mismatch: differs('Model', want.model, system.model, modelMatches(want.model, system.model)) }, + { field: 'Manufacturer', expected: want.manufacturer, observed: system.manufacturer }, + { field: 'System UUID', expected: want.systemUUID, observed: system.uuid, mismatch: differs('System UUID', want.systemUUID, system.uuid, want.systemUUID === system.uuid) }, + { field: 'SKU', observed: system.sku }, + { field: 'Power', observed: powerWord(system.powerState) }, + ]; + return rows.filter(row => row.expected || row.observed).map(row => stale && row.observed ? { ...row, stale } : row); +} + +// ---- MAC addresses ---- + +const mac = (value?: string) => (value ?? '').toLowerCase().replace(/[^0-9a-f]/g, ''); + +/** Host NICs: the compared System's, or every System's when none is singled out. */ +export function hostNics(device: Device): (ObservedNetworkInterface & { system?: string })[] { + const systems = device.status?.discovery?.inventory?.systems ?? []; + const system = comparedSystem(device); + if (system) return system.networkInterfaces ?? []; + return systems.flatMap(item => (item.networkInterfaces ?? []).map(nic => ({ ...nic, system: item.id }))); +} + +/** + * Spec interfaces whose MAC no host NIC reports, keyed by interface name, with + * the reason. Empty before an inventory read, so nothing is marked unobserved + * until discovery has looked. + */ +export function unobservedMacs(device: Device): Map { + const out = new Map(); + const inventory = device.status?.discovery?.inventory; + if (!inventory || staleReason(inventory, device)) return out; + const seen = new Set(hostNics(device).map(nic => mac(nic.macAddress)).filter(Boolean)); + for (const iface of device.spec.interfaces ?? []) if (iface.macAddress && !seen.has(mac(iface.macAddress))) out.set(iface.name, 'No host NIC reports this MAC address'); + return out; +} + +/** The spec interface names recording an observed MAC address. Matching is by address only, never by name. */ +export function specNamesFor(device: Device, macAddress?: string): string[] { + const key = mac(macAddress); + return key ? (device.spec.interfaces ?? []).filter(iface => mac(iface.macAddress) === key).map(iface => iface.name) : []; +} diff --git a/ui/provider/src/lib/inventory-fixtures.ts b/ui/provider/src/lib/inventory-fixtures.ts index 6ae51c0e..6aef8f83 100644 --- a/ui/provider/src/lib/inventory-fixtures.ts +++ b/ui/provider/src/lib/inventory-fixtures.ts @@ -23,7 +23,8 @@ // one, otherwise from the DeviceType. One model leaves fullDepth unset, so its // Device's depth is unknown. -import type { Device, DeviceClaim, DeviceLifecycle, PhysicalComponent, PhysicalRecord, ReportedPlacement } from '../../../shared/fleet-api'; +import type { Condition } from '../../../shared/conditions'; +import type { Device, DeviceClaim, DeviceStatus, DeviceLifecycle, PhysicalComponent, PhysicalRecord, ReportedPlacement } from '../../../shared/fleet-api'; import { toInventory, type Inventory, type InventoryKind } from '../inventory'; const NS = 'default'; @@ -312,7 +313,13 @@ const devices: Device[] = [ providerHostRef: { system: 'example-provider', type: 'Host', id: 'synthetic-host-0001' }, }, }), - server('example-srv-a01-02', 'example-rack-a01', 3), + server('example-srv-a01-02', 'example-rack-a01', 3, { + extra: { + bmc: { endpoint: 'https://192.0.2.100:443' }, + // eth1 records a MAC no host NIC reports; eth2 is not in the component list. + interfaces: [{ name: 'eth0', macAddress: '00:00:5e:00:53:21' }, { name: 'eth1', macAddress: '00:00:5e:00:53:22' }, { name: 'eth2', macAddress: '00:00:5e:00:53:23' }], + }, + }), // Both PSUs are cabled to the same PDU, so both reach Feed A: a single feed in the records. server(FIXTURE_NAMES.singleFeedServer, 'example-rack-a01', 4, { displayName: 'Compute a01-05' }), storage('example-sto-a01-03', 'example-rack-a01', 5), @@ -368,6 +375,80 @@ const devices: Device[] = [ }), ]; +// ---- BMC discovery status ---- +// +// Synthetic Device.status as BMC discovery writes it, relative to page load +// so ages and certificate expiry read the same on every capture: +// example-srv-a01-01 matched, powered on, every NIC up, key approved +// example-srv-a01-02 IdentityMatched False: the System reports another serial +// example-srv-a01-05 key not approved (PinNotApproved), certificate expiring +// soon, one host NIC down; inventory retained from an +// earlier read +// Every other Device has no status: discovery has not run. + +const LOADED = Date.now(); +const at = (offsetMs: number) => new Date(LOADED + offsetMs).toISOString().replace(/\.\d{3}Z$/, 'Z'); +const MINUTE = 60_000; +const DAY = 86_400_000; +const condition = (type: string, status: Condition['status'], reason: string, message: string): Condition => ({ type, status, reason, message, observedGeneration: 1, lastTransitionTime: at(-2 * MINUTE) }); +const nic = (id: string, macAddress: string, linkStatus = 'LinkUp', speedMbps = 25000) => ({ id, macAddress, linkStatus, speedMbps }); +const key = (byte: string) => byte.repeat(32); + +function discovery(device: Device, { serial, key: publicKeySHA256, notAfter, nics, managerNic, conditions }: { serial: string; key: string; notAfter: string; nics: ReturnType[]; managerNic: ReturnType; conditions: Condition[] }): DeviceStatus { + const endpoint = device.spec.bmc!.endpoint; + return { + observedGeneration: 1, + discovery: { + lastAttemptAt: at(-2 * MINUTE), lastAttemptEndpoint: endpoint, + tls: { observedAt: at(-2 * MINUTE), endpoint, publicKeySHA256, notAfter, selfSigned: true }, + serviceRoot: { observedAt: at(-2 * MINUTE), endpoint, redfishVersion: '1.11.0', uuid: device.spec.identity.systemUUID, vendor: 'Example Compute', product: 'Example Integrated BMC' }, + inventory: { + observedAt: at(-2 * MINUTE), endpoint, + managers: [{ id: 'BMC', model: 'Example BMC 9', firmwareVersion: '7.10.30', networkInterfaces: [managerNic] }], + systems: [{ + id: 'System.Embedded.1', uuid: device.spec.identity.systemUUID, manufacturer: 'Example Compute', model: `Example ${device.spec.identity.model}`, + serialNumber: serial, sku: 'SYNTH-SKU-1', powerState: 'On', networkInterfaces: nics, + }], + }, + }, + conditions, + }; +} + +const reachable = condition('Reachable', 'True', 'ServiceRootRead', 'TLS handshake completed and the anonymous service root was read'); +const accepted = condition('Authenticated', 'True', 'CredentialAccepted', 'the BMC accepted the credential over the pinned connection'); +const read = condition('Discovered', 'True', 'InventoryRead', 'managers, systems and their Ethernet interfaces were read'); +const unique = condition('PublicKeyUnique', 'True', 'Unique', 'no other discovered Device presents this TLS public key'); +const matched = condition('IdentityMatched', 'True', 'Matched', 'System System.Embedded.1 matches spec.identity (systemUUID, serial, model)'); + +const DISCOVERED: Record DeviceStatus> = { + [FIXTURE_NAMES.server]: device => discovery(device, { + serial: device.spec.identity.serial!, key: key('3f'), notAfter: at(400 * DAY), + nics: [nic('EthernetInterface0', '00:00:5e:00:53:11'), nic('EthernetInterface1', '00:00:5e:00:53:12'), nic('EthernetInterface2', '00:00:5e:00:53:13', 'LinkUp', 1000)], + managerNic: nic('eth0', '00:00:5e:00:53:a1', 'LinkUp', 1000), + conditions: [reachable, accepted, read, matched, unique], + }), + 'example-srv-a01-02': device => discovery(device, { + serial: 'SYNTH-OTHER-99', key: key('5c'), notAfter: at(200 * DAY), + nics: [nic('EthernetInterface0', '00:00:5e:00:53:21'), nic('EthernetInterface1', '00:00:5e:00:53:29'), nic('EthernetInterface2', '00:00:5e:00:53:23')], + managerNic: nic('eth0', '00:00:5e:00:53:a2', 'LinkUp', 1000), + conditions: [reachable, accepted, read, condition('IdentityMatched', 'False', 'SerialMismatch', 'the System with spec.identity.systemUUID reports another serial; spec is not changed'), unique], + }), + [FIXTURE_NAMES.singleFeedServer]: device => discovery(device, { + serial: device.spec.identity.serial!, key: key('9d'), notAfter: at(12 * DAY), + nics: [nic('EthernetInterface0', '00:00:5e:00:53:31'), nic('EthernetInterface1', '00:00:5e:00:53:32', 'LinkDown', 0)], + managerNic: nic('eth0', '00:00:5e:00:53:a3', 'LinkUp', 1000), + conditions: [reachable, + condition('Authenticated', 'False', 'PinNotApproved', 'the observed public key is in status.discovery.tls; verify it out of band and approve it as tlsPublicKeySHA256 in the credential Secret'), + condition('Discovered', 'False', 'PinNotApproved', 'the observed public key is in status.discovery.tls; verify it out of band and approve it as tlsPublicKeySHA256 in the credential Secret'), + matched, unique], + }), +}; +for (const item of devices) { + const status = DISCOVERED[item.metadata.name]; + if (status) item.status = status(item); +} + // Claims for the racked equipment. Devices with a reported placement use it; // the claim is the installation plan and history. function claim(name: string, rack: RackName, position: number, height: number, face: 'front' | 'rear', manufacturer: string, model: string): DeviceClaim { diff --git a/ui/shared/fleet-api.ts b/ui/shared/fleet-api.ts index d0904eac..3951e8aa 100644 --- a/ui/shared/fleet-api.ts +++ b/ui/shared/fleet-api.ts @@ -232,7 +232,8 @@ export const MACHINE_FINALIZER = 'fleet.datumapis.com/machine-protection'; // Physical inventory: fleet.datumapis.com/v1alpha1 DeviceClaim and Device, // transcribed from internal/api/inventory/v1alpha1/types.go and // config/components/inventory/crds/fleet.datumapis.com.yaml. Operators write -// both; status is reserved and has no fields yet. +// both specs. DeviceClaim status is reserved; Device status is written only by +// BMC discovery, through the status subresource. export const INVENTORY_API_GROUP = 'fleet.datumapis.com'; export const INVENTORY_API_VERSION = 'v1alpha1'; @@ -276,6 +277,74 @@ export interface Device { // each other, Decommissioning moves to Retired, and Retired is terminal. lifecycle?: DeviceLifecycle; }; + status?: DeviceStatus; +} + +/** What read-only BMC discovery observed. spec.identity stays authoritative. */ +export interface DeviceStatus { + observedGeneration?: number; + /** A failed attempt never clears it: each observation keeps its own time and endpoint. */ + discovery?: DeviceDiscovery; + /** Reachable, Authenticated, Discovered, IdentityMatched and PublicKeyUnique. */ + conditions?: Condition[]; +} + +export interface DeviceDiscovery { + lastAttemptAt?: string; + lastAttemptEndpoint?: string; + tls?: ObservedTLS; + serviceRoot?: ObservedServiceRoot; + inventory?: ObservedInventory; +} + +export interface ObservedTLS { + observedAt: string; + endpoint: string; + /** Lowercase hex SHA-256 of the leaf public key. */ + publicKeySHA256: string; + notAfter?: string; + selfSigned?: boolean; +} + +export interface ObservedServiceRoot { + observedAt: string; + endpoint: string; + redfishVersion?: string; + uuid?: string; + vendor?: string; + product?: string; +} + +export interface ObservedInventory { + observedAt: string; + endpoint: string; + managers?: ObservedManager[]; + systems?: ObservedSystem[]; +} + +export interface ObservedManager { + id: string; + model?: string; + firmwareVersion?: string; + networkInterfaces?: ObservedNetworkInterface[]; +} + +export interface ObservedSystem { + id: string; + uuid?: string; + manufacturer?: string; + model?: string; + serialNumber?: string; + sku?: string; + powerState?: string; + networkInterfaces?: ObservedNetworkInterface[]; +} + +export interface ObservedNetworkInterface { + id: string; + macAddress?: string; + linkStatus?: string; + speedMbps?: number; } export type DeviceLifecycle = 'Active' | 'Decommissioning' | 'Retired';