Self-hosted homelab infrastructure visualizer — interactive network diagram with live status monitoring
TypeScript diagramhomelabhomelab-infrastructure-observabilitynetworkproxmox-veself-hostedzigbeezwavezwave-js
fix(rack): guard rack rows against cross-design saves, and half-applied plates
Pouzore1f8850d1f33
diff --git a/backend/app/api/routes/racks.py b/backend/app/api/routes/racks.pyindex 1d00d30..4b87204 100644--- a/backend/app/api/routes/racks.py+++ b/backend/app/api/routes/racks.py@@ -1,5 +1,5 @@from datetime import datetime, timezone-from typing import Any+from typing import Any, TypeVarfrom fastapi import APIRouter, Depends, HTTPException, Queryfrom sqlalchemy import select@@ -97,6 +97,25 @@ def _ip_tokens(ip: str | None) -> list[str]:return [t.strip() for t in ip.split(",") if t.strip()] if ip else []+_Row = TypeVar("_Row", Rack, RackDevice, RackCable)+++async def _owned(+ db: AsyncSession, model: type[_Row], row_id: str, design_id: str+) -> _Row | None:+ """Fetch a rack row by id, refusing one that belongs to another design.++ The upsert below sets `design_id` from the payload, so without this a save+ carrying an id from design A would quietly move A's rack — devices and+ cables included — into design B, and A would lose it with no error. Ids come+ from the client, so a copied design or a stale tab is enough to collide.+ """+ row = await db.get(model, row_id)+ if row is not None and row.design_id != design_id:+ raise HTTPException(409, f"{model.__name__} {row_id} belongs to another design")+ return row++async def _require_design(db: AsyncSession, design_id: str) -> Design:design = await db.get(Design, design_id)if not design:@@ -170,7 +189,7 @@ async def save_racks(for rack_data in body.racks:payload: dict[str, Any] = rack_data.model_dump()payload["design_id"] = body.design_id- db_rack = await db.get(Rack, rack_data.id)+ db_rack = await _owned(db, Rack, rack_data.id, body.design_id)if db_rack:for field, value in payload.items():setattr(db_rack, field, value)@@ -181,7 +200,7 @@ async def save_racks(for device_data in body.devices:payload = device_data.model_dump()payload["design_id"] = body.design_id- db_device = await db.get(RackDevice, device_data.id)+ db_device = await _owned(db, RackDevice, device_data.id, body.design_id)if db_device:for field, value in payload.items():setattr(db_device, field, value)@@ -192,7 +211,7 @@ async def save_racks(for cable_data in body.cables:payload = cable_data.model_dump()payload["design_id"] = body.design_id- db_cable = await db.get(RackCable, cable_data.id)+ db_cable = await _owned(db, RackCable, cable_data.id, body.design_id)if db_cable:for field, value in payload.items():setattr(db_cable, field, value)diff --git a/backend/tests/test_racks.py b/backend/tests/test_racks.pyindex 34911ec..79db721 100644--- a/backend/tests/test_racks.py+++ b/backend/tests/test_racks.py@@ -142,6 +142,26 @@ class TestSaveAndLoad:assert loaded["racks"] == []assert loaded["devices"] == []+ async def test_refuses_to_steal_a_row_from_another_design(+ self, client: AsyncClient, headers+ ):+ """Ids come from the client, so a stale tab or a copy can collide.++ The upsert sets `design_id` from the payload: without a guard, saving+ design B with an id owned by design A moved A's rack — devices and+ cables with it — into B, and A silently lost it.+ """+ first = await _design(client, headers, name="Rack A")+ second = await _design(client, headers, name="Rack B")+ await client.post("/api/v1/racks/save", json=_state(first), headers=headers)++ res = await client.post("/api/v1/racks/save", json=_state(second), headers=headers)+ assert res.status_code == 409++ kept = (await client.get(f"/api/v1/racks?design_id={first}", headers=headers)).json()+ assert [r["id"] for r in kept["racks"]] == ["rack-1"]+ assert len(kept["devices"]) == 2+async def test_rejects_an_unknown_design(self, client: AsyncClient, headers):res = await client.post("/api/v1/racks/save", json=_state("nope"), headers=headers)assert res.status_code == 404diff --git a/frontend/src/rack/__tests__/RackDeviceModal.test.tsx b/frontend/src/rack/__tests__/RackDeviceModal.test.tsxindex 0987d6d..b157caa 100644--- a/frontend/src/rack/__tests__/RackDeviceModal.test.tsx+++ b/frontend/src/rack/__tests__/RackDeviceModal.test.tsx@@ -117,6 +117,55 @@ describe('RackDeviceModal — adding', () => {expect(store().deviceEditor).not.toBeNull()})+ it('blames the missing entry, not the rack, when the pick is gone', async () => {+ store().openDeviceEditor()+ const picked = store().inventory.find((i) => !i.racked)!+ render(<RackDeviceModal />)++ fireEvent.change(screen.getByLabelText('Device Inventory entry'), {+ target: { value: picked.id },+ })+ // Racked from another modal, or purged from the inventory, while this one+ // was open: the mount fails, and it used to read "No free slot in this rack".+ act(() => {+ useRackStore.setState({ inventory: store().inventory.filter((i) => i.id !== picked.id) })+ })+ // The select drops back to its placeholder rather than holding a dead id…+ expect(screen.getByLabelText('Device Inventory entry')).toHaveValue('')+ await act(async () => submit())++ // …so the error names the real cause instead of the rack's capacity.+ const { toast } = await import('sonner')+ expect(toast.error).toHaveBeenCalledWith('Pick a device from the inventory')+ expect(store().deviceEditor).not.toBeNull()+ })++ it('keeps the slot the mount picked instead of dragging it back', async () => {+ store().openDeviceEditor()+ const entry = store().inventory.find((i) => !i.racked)!+ render(<RackDeviceModal />)++ fireEvent.change(screen.getByLabelText('Device Inventory entry'), {+ target: { value: entry.id },+ })+ // U 1 is taken in the demo rack, so the mount relocates. Patching the form's+ // own geometry afterwards used to undo that, silently.+ fireEvent.change(screen.getByLabelText('U position'), { target: { value: '1' } })+ submit()++ await waitFor(() => expect(store().deviceEditor).toBeNull())+ const mounted = store().devices.find((d) => d.deviceId === entry.id)!+ const others = store().devices.filter((d) => d.id !== mounted.id && d.rackId === mounted.rackId)+ for (const other of others) {+ const overlaps =+ mounted.uStart < other.uStart + other.uHeight &&+ other.uStart < mounted.uStart + mounted.uHeight &&+ mounted.colStart < other.colStart + other.colSpan &&+ other.colStart < mounted.colStart + mounted.colSpan+ expect(overlaps).toBe(false)+ }+ })+it('labels inventory options without repeating the IP', () => {store().openDeviceEditor()useRackStore.setState({@@ -284,6 +333,27 @@ describe('RackDeviceModal — editing', () => {).toHaveLength(cablesBefore.length)})+ it('refuses a plate the rack cannot take instead of half-applying it', async () => {+ const { toast } = await import('sonner')+ store().openDeviceEditor('dev-pve1')+ render(<RackDeviceModal />)++ const before = store().devices.find((d) => d.id === 'dev-pve1')!+ // The demo rack's longest free run is 3U, so the 4U plate cannot be applied.+ // Shrinking the height then let `updateDevice` succeed on its own, and the+ // device ended up wearing its old plate with the new plate's ports.+ pickFaceplate('Storage 4U — 12 bays')+ fireEvent.change(screen.getByLabelText('Height (U)'), { target: { value: '1' } })+ submit()++ await waitFor(() => expect(toast.error).toHaveBeenCalled())+ const after = store().devices.find((d) => d.id === 'dev-pve1')!+ expect(after.faceplateId).toBe(before.faceplateId)+ expect(after.ports.map((p) => p.id)).toEqual(before.ports.map((p) => p.id))+ expect(after.uHeight).toBe(before.uHeight)+ expect(store().deviceEditor).not.toBeNull()+ })+it('edits the port list and commits it on save', async () => {store().openDeviceEditor('dev-pve1')render(<RackDeviceModal />)diff --git a/frontend/src/rack/components/RackDeviceModal.tsx b/frontend/src/rack/components/RackDeviceModal.tsxindex b19c0d6..229ee1e 100644--- a/frontend/src/rack/components/RackDeviceModal.tsx+++ b/frontend/src/rack/components/RackDeviceModal.tsx@@ -119,6 +119,15 @@ function DeviceForm({ deviceId, onClose }: { deviceId: string | null; onClose: (if (!isEdit) void refreshInventory()}, [isEdit, refreshInventory])+ // That refetch can drop the preselected entry (racked from elsewhere, deleted),+ // leaving the select blank while the state still held the dead id.+ useEffect(() => {+ if (isEdit) return+ setInventoryId((current) =>+ current && !unracked.some((i) => i.id === current) ? '' : current,+ )+ }, [isEdit, unracked])+/** Swapping the plate reseeds size and ports — the old ports belong to it. */function pickFaceplate(id: string) {const plate = getFaceplate(id)@@ -171,7 +180,14 @@ function DeviceForm({ deviceId, onClose }: { deviceId: string | null; onClose: (function commitEdit(): string | null {if (!device) return null- if (plateChanged && faceplateId !== device.faceplateId) applyFaceplate(device.id, faceplateId)+ // A plate the rack has no room for changes nothing — and the caller would+ // still write the new plate's ports onto the old faceplate, silently.+ if (plateChanged && faceplateId !== device.faceplateId) {+ if (!applyFaceplate(device.id, faceplateId)) {+ toast.error('No room in the rack for that faceplate')+ return null+ }+ }const name = label.trim() || device.labelif (!updateDevice(device.id, { ...geometry, label: name, status, color })) {toast.error('No room in the rack for that size')@@ -188,9 +204,11 @@ function DeviceForm({ deviceId, onClose }: { deviceId: string | null; onClose: (const name = label.trim()if (source === 'accessory') {- const id = mountAccessory(faceplateId, rackId, { uStart, colStart })+ // Hand the mount the whole geometry: it snaps to the nearest slot that+ // fits, and patching it afterwards would drag the plate back off it.+ const id = mountAccessory(faceplateId, rackId, geometry)if (!id) return noRoom()- updateDevice(id, { ...geometry, label: name || getFaceplate(faceplateId).label, color })+ updateDevice(id, { label: name || getFaceplate(faceplateId).label, color })return id}@@ -216,12 +234,11 @@ function DeviceForm({ deviceId, onClose }: { deviceId: string | null; onClose: (toast.error('Pick a device from the inventory')return null}-const id = mountFromInventory(entryId, rackId, { ...geometry, faceplateId })if (!id) return noRoom()- // The mount takes its label and status from the inventory entry; only patch- // what the form actually overrides.- updateDevice(id, { ...geometry, status, color, ...(name ? { label: name } : {}) })+ // The mount takes its label and status from the inventory entry, and its+ // slot from `findSlot` — only patch what the form actually overrides.+ updateDevice(id, { status, color, ...(name ? { label: name } : {}) })return id}