Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7eec0b3f9a | ||
|
|
b76519b0dd | ||
|
|
a2870a6e29 | ||
|
|
d6308a5573 | ||
|
|
fafbaeffcd | ||
|
|
824aa5d044 | ||
|
|
416b5fd1cb | ||
|
|
fcc2927b69 | ||
|
|
be46c21dd4 | ||
|
|
1c9d5791b7 | ||
|
|
0c7fd3c127 | ||
|
|
19758b2ba1 | ||
|
|
1f6812ef2a | ||
|
|
9db8b2a7a9 | ||
|
|
d40f73b85c | ||
|
|
71e29362aa | ||
|
|
7a5762e1a0 | ||
|
|
be2c5ce7e2 | ||
|
|
b4b22cc68f | ||
|
|
21465eee65 | ||
|
|
9b77e43ca1 | ||
|
|
e53197d2cb | ||
|
|
4393ac92c6 | ||
|
|
59079d90ca | ||
|
|
26e18dafdd | ||
|
|
c796cb39bd | ||
|
|
a93b0408b8 | ||
|
|
e40ac25b20 | ||
|
|
e93aef3871 | ||
|
|
79b682148e | ||
|
|
5040b70073 | ||
|
|
1343391b0d | ||
|
|
ecc3cb8364 | ||
|
|
9954fccf75 | ||
|
|
c263f839a8 | ||
|
|
e22152d2d3 | ||
|
|
57df3b9198 | ||
|
|
5617f0800f | ||
|
|
cd6402a680 | ||
|
|
4d2128c494 | ||
|
|
84360ffc50 | ||
|
|
56df462a8f | ||
|
|
06ccd354c5 | ||
|
|
c63bfd3859 | ||
|
|
2af6f728d7 | ||
|
|
b1186bd7dd | ||
|
|
a70fc248bf | ||
|
|
ff740f7466 | ||
|
|
3138cda378 | ||
|
|
0640704678 | ||
|
|
b129200929 | ||
|
|
e1f8850d1f | ||
|
|
9bf90cbbed | ||
|
|
7067bd76d4 | ||
|
|
8cafeee743 | ||
|
|
cfa296ef87 | ||
|
|
c6c7624084 | ||
|
|
e2da642554 | ||
|
|
a0d16e1454 | ||
|
|
33df37b691 | ||
|
|
f07f43686e | ||
|
|
3bde741fd2 | ||
|
|
e8ea6857bc | ||
|
|
42774fc138 | ||
|
|
8f273e0201 | ||
|
|
3c8e463dd9 | ||
|
|
c4017c7634 | ||
|
|
a88688170a | ||
|
|
aaccb50b00 | ||
|
|
34758c9850 | ||
|
|
4d2284dc37 | ||
|
|
9f974f2fcf | ||
|
|
37ad9c6933 | ||
|
|
99e7b9a343 | ||
|
|
f061db645b | ||
|
|
fd96b7d6ae | ||
|
|
0e95d99868 | ||
|
|
d9f3b4c18a | ||
|
|
80ebbca804 | ||
|
|
959cd4a3ae | ||
|
|
084a8e23e7 | ||
|
|
f5dd46a729 | ||
|
|
121873f41c | ||
|
|
16d6348cec | ||
|
|
28fc4d8a7f | ||
|
|
5726289b18 | ||
|
|
e85dab8cfc | ||
|
|
deccff15cf | ||
|
|
a1bf54c417 | ||
|
|
8c56921375 | ||
|
|
bf8551015c | ||
|
|
3f030959be | ||
|
|
0b8b9760bc | ||
|
|
f1fe82646d | ||
|
|
b7e03142e9 | ||
|
|
af3dc018c7 | ||
|
|
79bd0d4efb | ||
|
|
a364a95cb5 | ||
|
|
5b0c064e68 | ||
|
|
6f01d5550d | ||
|
|
9000f82213 | ||
|
|
587f7f3e61 | ||
|
|
2f91ca3dfd | ||
|
|
93e9b68821 | ||
|
|
d63c9e6451 | ||
|
|
71ab3bf391 | ||
|
|
9c0ed32485 | ||
|
|
8d752e0bd8 | ||
|
|
310b9cb3fd | ||
|
|
fceefe6d4d | ||
|
|
ba4f8b0be4 | ||
|
|
a7b7327ce5 | ||
|
|
6ae8b91934 | ||
|
|
3cab115a80 | ||
|
|
9e088ca7ac | ||
|
|
6cc8399dca | ||
|
|
4956e8ab90 | ||
|
|
d5cbdce870 | ||
|
|
15b7ce4481 | ||
|
|
8df7f682e0 | ||
|
|
30619caf0f | ||
|
|
47e144ac1f | ||
|
|
5fada99e25 | ||
|
|
2e4b353fcd | ||
|
|
d0e5c105ec | ||
|
|
9a03097f80 |
+20
-2
@@ -1,4 +1,5 @@
|
||||
# Backend - server-side only (NEVER commit .env)
|
||||
# Generate: python3 -c "import secrets; print(secrets.token_hex(32))"
|
||||
SECRET_KEY=change_me_in_production
|
||||
SQLITE_PATH=./data/homelab.db
|
||||
# Uploaded media (floor plans) folder. Optional — defaults to <SQLITE_PATH dir>/uploads,
|
||||
@@ -7,13 +8,30 @@ SQLITE_PATH=./data/homelab.db
|
||||
# Set this to the URL(s) you use to access Homelable in your browser.
|
||||
CORS_ORIGINS=["http://localhost:5173","http://localhost:3000"]
|
||||
|
||||
# Auth — default credentials: admin / admin
|
||||
# Auth — local mode is the backward-compatible default.
|
||||
AUTH_MODE=local
|
||||
# Local credentials: admin / admin by default.
|
||||
# ⚠️ Change before exposing on a network.
|
||||
# Generate a new hash: python3 -c "from passlib.context import CryptContext; print(CryptContext(schemes=['bcrypt']).hash('yourpassword'))"
|
||||
# Generate a new hash: python3 -c "import bcrypt; print(bcrypt.hashpw(b'yourpassword', bcrypt.gensalt()).decode())"
|
||||
# ⚠️ Keep the single quotes around the hash — bcrypt hashes contain \$ which Docker misinterprets without them.
|
||||
AUTH_USERNAME=admin
|
||||
AUTH_PASSWORD_HASH='$2b$12$RtMbyw17l4N5UGzeXMNAWuzCaVV.XFBY7ZetWheQhxcBDcxahapkG'
|
||||
|
||||
# OpenID Connect (optional alternative to local auth).
|
||||
# Set AUTH_MODE=oidc and configure every value below. The callback must be
|
||||
# registered exactly at the identity provider. Keep CORS_ORIGINS restricted to
|
||||
# the Homelable browser origin; wildcard CORS is rejected in OIDC mode. OIDC
|
||||
# also requires SECRET_KEY to contain at least 32 bytes.
|
||||
# AUTH_MODE=oidc
|
||||
# OIDC_DISCOVERY_URL=https://idp.example/application/o/homelable/.well-known/openid-configuration
|
||||
# OIDC_CLIENT_ID=homelable
|
||||
# OIDC_CLIENT_SECRET=replace-with-a-secret
|
||||
# OIDC_REDIRECT_URI=https://homelable.example/api/v1/auth/oidc/callback
|
||||
# OIDC_SCOPES="openid profile email"
|
||||
# OIDC_COOKIE_SECURE=true
|
||||
# OIDC_SESSION_EXPIRE_MINUTES=480
|
||||
# OIDC_TRANSACTION_EXPIRE_SECONDS=600
|
||||
|
||||
# Scanner — JSON array of CIDR ranges to scan
|
||||
SCANNER_RANGES=["192.168.1.0/24"]
|
||||
|
||||
|
||||
@@ -60,3 +60,20 @@ jobs:
|
||||
- run: ruff check .
|
||||
- run: mypy app/
|
||||
- run: pytest
|
||||
|
||||
# Also guards the NODE_TYPES / EDGE_TYPES enums in mcp/app/tools.py against
|
||||
# drift from frontend/src/types/index.ts (test_node_types_sync.py,
|
||||
# test_edge_types_sync.py) — those tests need the frontend sources, so this
|
||||
# job runs from a full checkout rather than the mcp Docker context.
|
||||
mcp:
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: mcp
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.13'
|
||||
- run: pip install -r requirements.txt
|
||||
- run: pytest
|
||||
|
||||
@@ -22,6 +22,12 @@ jobs:
|
||||
uses: trufflesecurity/trufflehog@main
|
||||
with:
|
||||
path: ./
|
||||
# Lob (a direct-mail API this project does not use) matches any
|
||||
# `test_`-prefixed identifier of ~35 chars and reports it verified,
|
||||
# because Lob test keys authenticate unconditionally. Every pytest
|
||||
# function named at that length trips it — the first was
|
||||
# `test_updates_an_existing_device_in_place`.
|
||||
extra_args: --exclude-detectors=Lob
|
||||
|
||||
dependency-audit:
|
||||
runs-on: ubuntu-latest
|
||||
@@ -31,11 +37,12 @@ jobs:
|
||||
with:
|
||||
node-version: '20'
|
||||
- name: NPM Audit
|
||||
run: cd frontend && npm audit --audit-level=high
|
||||
# --omit=dev: only ship-time deps gate the build. Dev-only tooling
|
||||
# (shadcn CLI and its transitive tree: hono, fast-uri, …) is never
|
||||
# bundled or served, so its advisories must not fail release CI.
|
||||
run: cd frontend && npm audit --omit=dev --audit-level=high
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.11'
|
||||
- name: Pip audit
|
||||
# CVE-2024-23342 (ecdsa): timing attack on ECDSA — not exploitable (app uses HS256/HMAC only).
|
||||
# python-jose forces ecdsa as a dependency with no fixed version available.
|
||||
run: pip install pip-audit && pip-audit -r backend/requirements.txt --ignore-vuln CVE-2024-23342
|
||||
run: pip install pip-audit && pip-audit -r backend/requirements.txt
|
||||
|
||||
+113
@@ -5,6 +5,119 @@ All notable changes to **Homelable** are documented here.
|
||||
The format is loosely based on [Keep a Changelog](https://keepachangelog.com/),
|
||||
and this project adheres to [Semantic Versioning](https://semver.org/).
|
||||
|
||||
## [3.3.1] - 2026-08-17
|
||||
|
||||
### Fixes
|
||||
|
||||
- Approving a device no longer fails after an upgrade from 3.2.0: a node the 3.3.0 inventory backfill could not link kept the old device columns on `nodes`, and their NOT NULL constraint rejected every new node. (#352)
|
||||
|
||||
## [3.3.0] - 2026-08-15
|
||||
|
||||
### Features
|
||||
|
||||
- The Device Inventory is now the source of truth for device data: a node reads and edits its facts from its inventory row, and the device sheet is grouped by what a reader is after. (#339)
|
||||
- Per-service host override, so a service can point at a host other than the node's own. (#338)
|
||||
- A zone now parents the nodes dropped inside it. (#343)
|
||||
- Node properties accept an empty value. (#345)
|
||||
- Nodes can be given 0 connection points on top and bottom. (#336)
|
||||
- KVM switch added as a device type. (#335)
|
||||
- The sidebar version row links to the public changelog.
|
||||
|
||||
### Fixes
|
||||
|
||||
- Alignment guides show for nodes inside groups and containers. (#337)
|
||||
- The status check interval is applied to the running scheduler. Thanks @JaG-v2. (#319)
|
||||
- Bumped undici and ip-address to patch high severity advisories. (#342)
|
||||
|
||||
### Docs
|
||||
|
||||
- The pre-built GHCR images are documented in the install guide.
|
||||
|
||||
## [3.2.0] - 2026-08-10
|
||||
|
||||
### Features
|
||||
|
||||
- Rack canvas: a third design type, next to network and electrical, with racks, mounted devices and port-to-port patching. (#315)
|
||||
- Declarative SVG faceplates picked from a visual catalog, including desktop NAS enclosures in 2, 4 and 5 bays. (#315)
|
||||
- Rack gear is filed in the Device Inventory, and a mount can be picked from the rackable entries. (#315)
|
||||
- Cables carry a type, colour, label and properties, printed on the canvas at the midpoint of the run. (#315)
|
||||
- Mounted devices follow the status check of the logical node they match, and links can be imported from the logical canvas. (#315)
|
||||
- Getting Started walkthrough covers the rack canvas. (#315)
|
||||
- Show the logical view of a mounted device, and link a mount to any Device Inventory entry. (#323)
|
||||
|
||||
### Fixes
|
||||
|
||||
- Guard rack rows against cross-design saves and half-applied faceplates. (#315)
|
||||
- A rack height edit no longer orphans its mounts; height and colour commit on blur, and a blanked field no longer shrinks the rack. (#315)
|
||||
- Import links is idempotent, and stays usable after a run that matched nothing. (#315)
|
||||
- Stop the device modal losing cables, status and inventory rows. (#315)
|
||||
- Name rack inventory entries the way the Device Inventory does. (#315)
|
||||
- Stamp the linked node's last-seen with an offset. (#323)
|
||||
- Bump js-yaml to 4.3.1 for CVE-2026-59870. (#315)
|
||||
- CI: stop the secret scan reporting pytest names as Lob keys. (#315)
|
||||
|
||||
### Docs
|
||||
|
||||
- Document the rack canvas for users. (#315)
|
||||
|
||||
## [3.1.2] - 2026-08-01
|
||||
|
||||
### Features
|
||||
|
||||
- Generic OIDC authentication: backend sessions and browser login flow. Thanks @autogpt-elendir. (#306)
|
||||
- Brand icon picker for services, in a dedicated add/edit modal. (#313)
|
||||
- MCP: lightweight node lookup tools. Thanks @Nebesz. (#312)
|
||||
|
||||
### Fixes
|
||||
|
||||
- Sync the MCP node and edge type enums with the frontend, gated in CI against drift. Thanks @Nebesz. (#311)
|
||||
- Harden OIDC callback validation. (#306)
|
||||
- Use the official Homelable logo on the login page. (#306)
|
||||
- Clear the seven open dependabot alerts and refresh vulnerable frontend packages. (#317, #306)
|
||||
|
||||
### Docs
|
||||
|
||||
- Document OIDC setup and configuration. (#306)
|
||||
|
||||
## [3.1.1] - 2026-07-19
|
||||
|
||||
### Features
|
||||
|
||||
- Drag to reorder services in the node detail panel. Thanks @Isilla. (#302)
|
||||
- Getting Started walkthrough tour with first-run canvas detection. (#300)
|
||||
|
||||
### Fixes
|
||||
|
||||
- Round-trip Show Port Numbers on YAML export/import. (#301)
|
||||
- Render error toasts on a red surface. (#300)
|
||||
|
||||
### Docs
|
||||
|
||||
- Rework README header with logo, badges, and nav links. (#300)
|
||||
|
||||
## [3.1.0] - 2026-07-18
|
||||
|
||||
### Features
|
||||
|
||||
- Drag to reorder node properties. (#296)
|
||||
- Search for nodes and properties. Thanks @Floyddotnet. (#294)
|
||||
- Widen zone modal into two columns. (#293)
|
||||
- Autosave canvas after a configurable inactivity delay (opt-in). Thanks @nicolabottini. (#289)
|
||||
- MCP: `design_id` on approve_device + `delete_design` tool. Thanks @nicolabottini. (#281)
|
||||
|
||||
### Fixes
|
||||
|
||||
- Scanner: decouple port discovery from version detection. (#295, #277)
|
||||
- Allow undo after Auto Layout and YAML import. (#290)
|
||||
- Move edge waypoints when the connected node or its container is dragged. (#288)
|
||||
- Keep container host height when editing an unrelated field. (#287)
|
||||
- Keep container children in place when editing a host node. Thanks @nicolabottini. (#286)
|
||||
- `list_pending_devices` MCP tool leaked approved/hidden inventory rows. Thanks @MikeSviblov. (#273)
|
||||
|
||||
### Docs
|
||||
|
||||
- Fix MCP client transport to http (was sse). (#275)
|
||||
|
||||
## [3.0.0] - 2026-07-10
|
||||
|
||||
### Added
|
||||
|
||||
+64
-26
@@ -16,19 +16,21 @@ Here's what Homelable can do. One line on what each feature is, then how to swit
|
||||
2. [Groups & Nesting](#2-groups--nesting)
|
||||
3. [Text Annotations](#3-text-annotations)
|
||||
4. [Multiple Canvases](#4-multiple-canvases)
|
||||
5. [Customize Style](#5-customize-style)
|
||||
6. [Floor Plan](#6-floor-plan-)
|
||||
7. [Network Scanner (IP import)](#7-network-scanner-ip-import-)
|
||||
8. [Zigbee Import](#8-zigbee-import-)
|
||||
9. [Z-Wave Import](#9-z-wave-import-)
|
||||
10. [Proxmox VE Import](#10-proxmox-ve-import-)
|
||||
11. [Device Inventory](#11-device-inventory-)
|
||||
12. [Live Status Monitoring](#12-live-status-monitoring-)
|
||||
13. [Export (PNG / SVG / YAML / Markdown)](#13-export)
|
||||
14. [Live View (read-only public canvas)](#14-live-view-)
|
||||
15. [Gethomepage Widget](#15-gethomepage-widget-)
|
||||
16. [MCP Server (AI integration)](#16-mcp-server-)
|
||||
17. [Settings & Shortcuts](#17-settings--shortcuts)
|
||||
5. [Rack Canvas](#5-rack-canvas)
|
||||
6. [Customize Style](#6-customize-style)
|
||||
7. [Floor Plan](#7-floor-plan-)
|
||||
8. [Network Scanner (IP import)](#8-network-scanner-ip-import-)
|
||||
9. [Zigbee Import](#9-zigbee-import-)
|
||||
10. [Z-Wave Import](#10-z-wave-import-)
|
||||
11. [Proxmox VE Import](#11-proxmox-ve-import-)
|
||||
12. [Device Inventory](#12-device-inventory-)
|
||||
13. [Live Status Monitoring](#13-live-status-monitoring-)
|
||||
14. [Export (PNG / SVG / YAML / Markdown)](#14-export)
|
||||
15. [Live View (read-only public canvas)](#15-live-view-)
|
||||
16. [Gethomepage Widget](#16-gethomepage-widget-)
|
||||
17. [MCP Server (AI integration)](#17-mcp-server-)
|
||||
18. [Settings & Shortcuts](#18-settings--shortcuts)
|
||||
19. [Authentication (Local / OpenID Connect)](#19-authentication-local--openid-connect-)
|
||||
|
||||
---
|
||||
|
||||
@@ -73,7 +75,26 @@ Here's what Homelable can do. One line on what each feature is, then how to swit
|
||||
|
||||
---
|
||||
|
||||
## 5. Customize Style
|
||||
## 5. Rack Canvas
|
||||
|
||||
**What:** The physical side of the lab, as its own kind of canvas: racks, the gear mounted in them, and the patch cables between their ports. Where a diagram says what talks to what, a rack says what sits in which U, and which switch port the uplink lands on.
|
||||
|
||||
**Use:**
|
||||
- **Canvas switcher** → **New Canvas** → Kind **Rack**. A canvas cannot change kind afterwards.
|
||||
- **Add Rack** in the header drops a rack; double-click its frame for U height, 19"/10" width, numbering direction, colours and the enclosed/open look.
|
||||
- **+ Device** in the sidebar mounts something: an entry from your **Device Inventory** 🔒, a **new device** (which joins the inventory tagged *Rack devices*), or a rack-only **accessory** (blank, shelf, cable manager). Double-click a plate to edit it, and **Unmount** to take it out — the device itself stays in the inventory.
|
||||
- Gear occupies a U range and part of a 12-column width grid, so half- and third-width machines share a U. A drop snaps to the nearest free slot, an impossible one previews red, and growing a device relocates it to the nearest slot that fits.
|
||||
- The **Faceplate** field opens a visual catalog — servers, switches, routers, patch panels, UPS and PDUs, desktop NAS towers, shelves and blanks — drawn as vector artwork that scales with the rack and follows your theme.
|
||||
- **Patch**: drag from one port to another (or click both in turn) to cable them, across racks if you need to. Click a cable to select it, then **Delete** or **Unplug**. A header select controls whether cables show on hover, always, or not at all.
|
||||
- **Status**: pin a mount's colour, or set **Check device** 🔒 so it follows the status check already configured on the matching diagram node.
|
||||
- **Import links** 🔒 derives patches from the physical links already drawn on your diagrams. Run it again after racking more gear — pairs already cabled are left alone.
|
||||
- Saving is explicit — **Save Rack** — like any other canvas.
|
||||
|
||||
> **Full documentation:** [docs/rack-canvas.md](./docs/rack-canvas.md)
|
||||
|
||||
---
|
||||
|
||||
## 6. Customize Style
|
||||
|
||||
**What:** Repaint the whole thing with a preset theme, or roll your own node and edge colors.
|
||||
|
||||
@@ -84,7 +105,7 @@ Here's what Homelable can do. One line on what each feature is, then how to swit
|
||||
|
||||
---
|
||||
|
||||
## 6. Floor Plan 🔒
|
||||
## 7. Floor Plan 🔒
|
||||
|
||||
**What:** Put a background image (a house plan, an office layout, a rack diagram) behind a canvas and lay your devices out on top of it.
|
||||
|
||||
@@ -95,7 +116,7 @@ Here's what Homelable can do. One line on what each feature is, then how to swit
|
||||
|
||||
---
|
||||
|
||||
## 7. Network Scanner (IP import) 🔒
|
||||
## 8. Network Scanner (IP import) 🔒
|
||||
|
||||
**What:** Point `nmap` at your network, fingerprint the services it finds, and turn hosts into nodes.
|
||||
|
||||
@@ -115,7 +136,7 @@ SCANNER_HTTP_VERIFY_TLS=false
|
||||
|
||||
---
|
||||
|
||||
## 8. Zigbee Import 🔒
|
||||
## 9. Zigbee Import 🔒
|
||||
|
||||
**What:** Pull your **Zigbee2MQTT** topology in over MQTT and drop every device on the canvas as a typed node.
|
||||
|
||||
@@ -128,7 +149,7 @@ Nodes come in as `zigbee_coordinator` / `zigbee_router` / `zigbee_enddevice`. Th
|
||||
|
||||
---
|
||||
|
||||
## 9. Z-Wave Import 🔒
|
||||
## 10. Z-Wave Import 🔒
|
||||
|
||||
**What:** Same idea for **Z-Wave JS UI**, over the same MQTT broker.
|
||||
|
||||
@@ -141,7 +162,7 @@ Nodes: `zwave_coordinator` / `zwave_router` / `zwave_enddevice`. The hierarchy c
|
||||
|
||||
---
|
||||
|
||||
## 10. Proxmox VE Import 🔒
|
||||
## 11. Proxmox VE Import 🔒
|
||||
|
||||
**What:** Pull your **Proxmox VE** inventory (hosts, VMs, LXC) in over the Proxmox REST API — typed, named nodes with run state and hardware specs. Optional scheduled **auto-sync**; guest IPs already found by a scan are merged, not duplicated.
|
||||
|
||||
@@ -155,7 +176,7 @@ Nodes: `proxmox` (host) / `vm` / `lxc`, linked host→guest by a `virtual` edge.
|
||||
|
||||
---
|
||||
|
||||
## 11. Device Inventory 🔒
|
||||
## 12. Device Inventory 🔒
|
||||
|
||||
**What:** The holding pen for everything found by a scan or import that isn't on the canvas yet, plus a separate **Hidden Devices** list.
|
||||
|
||||
@@ -166,7 +187,7 @@ Nodes: `proxmox` (host) / `vm` / `lxc`, linked host→guest by a `virtual` edge.
|
||||
|
||||
---
|
||||
|
||||
## 12. Live Status Monitoring 🔒
|
||||
## 13. Live Status Monitoring 🔒
|
||||
|
||||
**What:** Keeps checking each node and shows its status (🟢 online / 🔴 offline / ⚫ unknown) right on the canvas.
|
||||
|
||||
@@ -187,7 +208,7 @@ Nodes: `proxmox` (host) / `vm` / `lxc`, linked host→guest by a `virtual` edge.
|
||||
|
||||
---
|
||||
|
||||
## 13. Export
|
||||
## 14. Export
|
||||
|
||||
**What:** Get your canvas out as a picture or as structured data.
|
||||
|
||||
@@ -199,7 +220,7 @@ Nodes: `proxmox` (host) / `vm` / `lxc`, linked host→guest by a `virtual` edge.
|
||||
|
||||
---
|
||||
|
||||
## 14. Live View 🔒
|
||||
## 15. Live View 🔒
|
||||
|
||||
**What:** A read-only, no-login snapshot of a canvas you can share on your LAN. Off by default.
|
||||
|
||||
@@ -211,7 +232,7 @@ Pan and zoom only, no editing. Click a node with an IP and it opens in a new tab
|
||||
|
||||
---
|
||||
|
||||
## 15. Gethomepage Widget 🔒
|
||||
## 16. Gethomepage Widget 🔒
|
||||
|
||||
**What:** A tiny JSON stats endpoint for [gethomepage](https://gethomepage.dev)'s `customapi` widget. Off by default.
|
||||
|
||||
@@ -223,7 +244,7 @@ Widget snippet lives in the [README](./README.md#gethomepage-widget-read-only-st
|
||||
|
||||
---
|
||||
|
||||
## 16. MCP Server 🔒
|
||||
## 17. MCP Server 🔒
|
||||
|
||||
**What:** A [Model Context Protocol](https://modelcontextprotocol.io) server so an MCP client (Claude Code, Claude Desktop, Open WebUI…) can read and change your topology. Optional, runs as its own service.
|
||||
|
||||
@@ -241,7 +262,7 @@ The AI can list nodes/edges/canvas/pending/scans, add/update/delete nodes and ed
|
||||
|
||||
---
|
||||
|
||||
## 17. Settings & Shortcuts
|
||||
## 18. Settings & Shortcuts
|
||||
|
||||
**What:** App config and keyboard shortcuts.
|
||||
|
||||
@@ -252,4 +273,21 @@ The AI can list nodes/edges/canvas/pending/scans, add/update/delete nodes and ed
|
||||
|
||||
---
|
||||
|
||||
## 19. Authentication (Local / OpenID Connect) 🔒
|
||||
|
||||
**What:** Homelable protects the app behind a login. Two exclusive modes, set once in `.env` with `AUTH_MODE`:
|
||||
- **`local`** (default) — a single username + bcrypt-hashed password. Nothing changes for existing installs.
|
||||
- **`oidc`** — sign in through your own identity provider (Authentik, Keycloak, Authelia, Google, …) via **Authorization Code + PKCE**. Good for SSO, per-user accounts at the IdP, MFA, and central account management.
|
||||
|
||||
**Use (OIDC):**
|
||||
1. Register Homelable as a **confidential** client at your IdP and set the redirect URI to `https://<your-host>/api/v1/auth/oidc/callback`.
|
||||
2. In `.env` set `AUTH_MODE=oidc` and the `OIDC_*` values (discovery URL, client id/secret, redirect URI, scopes), keep `CORS_ORIGINS` pinned to your browser origin, and give `SECRET_KEY` at least 32 bytes.
|
||||
3. Restart the backend. The login screen now shows **Sign in with OpenID Connect**.
|
||||
|
||||
**How it protects you:** provider tokens are exchanged server-side and never touch the browser — Homelable issues its own short-lived, `__Host-`, HttpOnly, `SameSite=Lax` session cookie. Discovery metadata, issuer, audience, signature, expiry, nonce, state and PKCE are all validated; cookie-authenticated writes require a CSRF token and an allowed `Origin`; the status WebSocket authenticates from the cookie and validates `Origin`. Local Bearer auth and the MCP service key keep working unchanged. Full config, provider examples and troubleshooting: [docs/oidc-auth.md](./docs/oidc-auth.md).
|
||||
|
||||
> OIDC is Full-mode only — the no-backend standalone build has no login.
|
||||
|
||||
---
|
||||
|
||||
*Installing (Docker, Proxmox LXC, source) is covered in [INSTALLATION.md](./INSTALLATION.md). Running Home Assistant? See [homelable-hacs](https://github.com/Pouzor/homelable-hacs).*
|
||||
|
||||
+51
-2
@@ -13,7 +13,7 @@ Open **http://localhost:3000** — login with `admin` / `admin`.
|
||||
>
|
||||
Generate a new hash:
|
||||
```bash
|
||||
docker compose exec backend python -c "from passlib.context import CryptContext; print(CryptContext(schemes=['bcrypt']).hash('yourpassword'))"
|
||||
docker compose exec backend python -c 'import bcrypt; print(bcrypt.hashpw(b"yourpassword", bcrypt.gensalt()).decode())'
|
||||
```
|
||||
|
||||
|
||||
@@ -21,7 +21,7 @@ docker compose exec backend python -c "from passlib.context import CryptContext;
|
||||
- **`.env` file** (recommended): wrap the hash in single quotes → `AUTH_PASSWORD_HASH='$2b$12$...'`
|
||||
- **`docker-compose.yml` `environment:` block**: escape every `$` as `$$` — use this command to generate a pre-escaped hash:
|
||||
```bash
|
||||
docker compose exec backend python -c "from passlib.context import CryptContext; print(CryptContext(schemes=['bcrypt']).hash('yourpassword').replace('\$', '\$\$'))"
|
||||
docker compose exec backend python -c 'import bcrypt; print(bcrypt.hashpw(b"yourpassword", bcrypt.gensalt()).decode().replace("$", "$$"))'
|
||||
```
|
||||
|
||||
## Quick Start — Frontend only
|
||||
@@ -40,8 +40,33 @@ curl -fsSL https://raw.githubusercontent.com/Pouzor/homelable/main/install.sh |
|
||||
cd homelable && docker compose pull && docker compose up -d
|
||||
```
|
||||
|
||||
## Pre-built Docker images
|
||||
|
||||
The quick starts above never build anything — `install.sh` writes `docker-compose.prebuilt.yml` (or `docker-compose.standalone.yml` with `--standalone`) as your `docker-compose.yml`, and both pull ready-made images. They are published to the GitHub Container Registry on every push to `main` and every `v*` tag, for `linux/amd64` and `linux/arm64`:
|
||||
|
||||
| Image | Contents |
|
||||
|---|---|
|
||||
| [`ghcr.io/pouzor/homelable-backend`](https://github.com/Pouzor/homelable/pkgs/container/homelable-backend) | FastAPI API, scanner, status checker |
|
||||
| [`ghcr.io/pouzor/homelable-frontend`](https://github.com/Pouzor/homelable/pkgs/container/homelable-frontend) | React SPA behind nginx, proxying `/api` to the backend |
|
||||
| [`ghcr.io/pouzor/homelable-frontend-standalone`](https://github.com/Pouzor/homelable/pkgs/container/homelable-frontend-standalone) | Same SPA built with `VITE_STANDALONE=true` — no backend, canvases in `localStorage` |
|
||||
| [`ghcr.io/pouzor/homelable-mcp`](https://github.com/Pouzor/homelable/pkgs/container/homelable-mcp) | MCP server exposing the canvas to AI clients |
|
||||
|
||||
Tags: `latest` (tip of `main`), plus `X.Y.Z` and `X.Y` for releases.
|
||||
|
||||
To wire it up by hand instead of using `install.sh`:
|
||||
|
||||
```bash
|
||||
curl -fsSLO https://raw.githubusercontent.com/Pouzor/homelable/main/docker-compose.prebuilt.yml
|
||||
curl -fsSL https://raw.githubusercontent.com/Pouzor/homelable/main/.env.example -o .env
|
||||
docker compose -f docker-compose.prebuilt.yml up -d
|
||||
```
|
||||
|
||||
Update the same way: `docker compose -f docker-compose.prebuilt.yml pull && … up -d`.
|
||||
|
||||
## Build from source
|
||||
|
||||
`docker-compose.yml` at the repo root builds the images locally instead of pulling them — use it for development, or to run a patched tree.
|
||||
|
||||
```bash
|
||||
git clone https://github.com/Pouzor/homelable.git
|
||||
cd homelable
|
||||
@@ -69,6 +94,7 @@ bash -c "$(curl -fsSL https://raw.githubusercontent.com/community-scripts/Proxmo
|
||||
All configuration is done via `.env` (copied from `.env.example`):
|
||||
|
||||
```env
|
||||
# Generate with: python3 -c "import secrets; print(secrets.token_hex(32))"
|
||||
SECRET_KEY=change_me_in_production
|
||||
|
||||
# Auth — default: admin / admin
|
||||
@@ -82,6 +108,29 @@ SCANNER_RANGES=["192.168.1.0/24"]
|
||||
STATUS_CHECKER_INTERVAL=60
|
||||
```
|
||||
|
||||
### OpenID Connect (optional)
|
||||
|
||||
OIDC is an exclusive alternative to the local password. Existing installs stay
|
||||
in `AUTH_MODE=local` unless explicitly changed.
|
||||
|
||||
```env
|
||||
AUTH_MODE=oidc
|
||||
CORS_ORIGINS=["https://homelable.example"]
|
||||
OIDC_DISCOVERY_URL=https://idp.example/application/o/homelable/.well-known/openid-configuration
|
||||
OIDC_CLIENT_ID=homelable
|
||||
OIDC_CLIENT_SECRET=replace-with-a-secret
|
||||
OIDC_REDIRECT_URI=https://homelable.example/api/v1/auth/oidc/callback
|
||||
OIDC_SCOPES="openid profile email"
|
||||
OIDC_COOKIE_SECURE=true
|
||||
OIDC_SESSION_EXPIRE_MINUTES=480
|
||||
```
|
||||
|
||||
Register `OIDC_REDIRECT_URI` exactly at the identity provider. Production OIDC
|
||||
requires HTTPS, a non-wildcard `CORS_ORIGINS`, and a confidential client. The
|
||||
backend uses Authorization Code with PKCE and keeps provider tokens out of the
|
||||
browser. `SECRET_KEY` must contain at least 32 bytes in OIDC mode. Do not expose
|
||||
`OIDC_CLIENT_SECRET` in Compose YAML or commit it to Git.
|
||||
|
||||
All settings are also editable in-app via the **Scan Network** button.
|
||||
|
||||
---
|
||||
|
||||
@@ -1,4 +1,35 @@
|
||||
# Homelable
|
||||
<h1 align="center"><img src="docs/logo/icon-inline.svg" alt="Homelable" width="58" align="middle" /> Homelable</h1>
|
||||
|
||||
<p align="center">
|
||||
<strong>Self-hosted homelab infrastructure visualization, scanning & live monitoring</strong>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/Pouzor/homelable/releases/latest"><img src="https://img.shields.io/github/v/release/Pouzor/homelable" alt="Latest release" /></a>
|
||||
<a href="https://github.com/Pouzor/homelable/actions/workflows/docker-ci.yml"><img src="https://img.shields.io/github/actions/workflow/status/Pouzor/homelable/docker-ci.yml?branch=main&label=build" alt="Build status" /></a>
|
||||
<a href="https://github.com/Pouzor/homelable/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-MIT-blue.svg" alt="License" /></a>
|
||||
<a href="https://github.com/Pouzor/homelable/issues"><img src="https://img.shields.io/github/issues/Pouzor/homelable" alt="Issues" /></a>
|
||||
<a href="https://github.com/Pouzor/homelable/stargazers"><img src="https://img.shields.io/github/stars/Pouzor/homelable?style=social" alt="Stars" /></a>
|
||||
<a href="https://github.com/Pouzor/homelable/network/members"><img src="https://img.shields.io/github/forks/Pouzor/homelable?style=social" alt="Forks" /></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://trendshift.io/repositories/24461?utm_source=trendshift-badge&utm_medium=badge&utm_campaign=badge-trendshift-24461" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/trendshift/repositories/24461/daily?language=TypeScript" alt="Pouzor%2Fhomelable | Trendshift" width="130" /></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="#screenshots">Screenshots</a> ·
|
||||
<a href="#features">Features</a> ·
|
||||
<a href="#installation">Installation</a> ·
|
||||
<a href="#rack-canvas">Rack Canvas</a> ·
|
||||
<a href="#network-scanner">Network Scanner</a> ·
|
||||
<a href="#zigbee2mqtt-import">Zigbee / Z-Wave</a> ·
|
||||
<a href="#proxmox-ve-import">Proxmox</a> ·
|
||||
<a href="#live-view-read-only-public-canvas">Live View</a> ·
|
||||
<a href="#mcp-server-ai-integration-optional">MCP Server</a>
|
||||
</p>
|
||||
|
||||
## About
|
||||
|
||||
Homelable is a self-hosted infrastructure visualization solution. It provides a network/zigbee scanning feature to accelerate the identification of machines, devices and services deployed on your local infrastructure.
|
||||
|
||||
@@ -10,7 +41,6 @@ If you just like the design, you can only run the frontend and export your desig
|
||||
|
||||
If you are running <img width="22" height="22" align="top" alt="New_Home_Assistant_logo" src="https://github.com/user-attachments/assets/3bb17686-c706-40ce-a2d3-57e02378f37c" /> Homeassistant, check the [Homelable HA version](https://github.com/Pouzor/homelable-hacs) (via HACS)
|
||||
|
||||
<a href="https://trendshift.io/repositories/24461?utm_source=trendshift-badge&utm_medium=badge&utm_campaign=badge-trendshift-24461" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/trendshift/repositories/24461/daily?language=TypeScript" alt="Pouzor%2Fhomelable | Trendshift" width="250" height="55"/></a>
|
||||
---
|
||||
|
||||
## Screenshots
|
||||
@@ -27,7 +57,7 @@ If you are running <img width="22" height="22" align="top" alt="New_Home_Assist
|
||||
|
||||
## Features
|
||||
|
||||
From one-click **network scans** and **Proxmox / Zigbee / Z-Wave** imports to **live status monitoring**, floor plans, multi-canvas layouts and an **MCP server** for AI assistants — Homelable maps and watches your whole homelab.
|
||||
From one-click **network scans** and **Proxmox / Zigbee / Z-Wave** imports to **live status monitoring**, floor plans, **rack canvases** with port-to-port patching, multi-canvas layouts and an **MCP server** for AI assistants — Homelable maps and watches your whole homelab.
|
||||
|
||||
Every feature, with how to turn it on and use it, is described in **[FEATURES.md](./FEATURES.md)**.
|
||||
|
||||
@@ -35,7 +65,25 @@ Every feature, with how to turn it on and use it, is described in **[FEATURES.md
|
||||
|
||||
## Installation
|
||||
|
||||
Docker, Proxmox LXC, build from source, configuration, and development setup are all covered in **[INSTALLATION.md](./INSTALLATION.md)**.
|
||||
Docker (from the **[pre-built GHCR images](./INSTALLATION.md#pre-built-docker-images)**), Proxmox LXC, build from source, configuration, and development setup are all covered in **[INSTALLATION.md](./INSTALLATION.md)**.
|
||||
|
||||
---
|
||||
|
||||
## Rack Canvas
|
||||
|
||||
Next to the network diagram, Homelable draws the **physical** side of your lab: racks, the gear mounted in them, and the patch cables between their ports. It is a canvas kind of its own — create it from the canvas switcher, **New Canvas → Kind → Rack**.
|
||||
|
||||
### Usage
|
||||
|
||||
1. **Add Rack** in the header drops a rack; double-click its frame to set U height, 19"/10" width, numbering direction and colours
|
||||
2. **+ Device** in the sidebar mounts something — an entry from your Device Inventory, a new device (which joins the inventory), or an accessory (blank, shelf, cable manager)
|
||||
3. Pick a **faceplate** from the visual catalog: servers, switches, routers, patch panels, UPS and PDUs, desktop NAS towers, shelves and blanks
|
||||
4. Click **Patch**, then drag from one port to another to cable them — across racks if you need to. Click a cable and press Delete to unplug it
|
||||
5. **Save Rack** when you're happy; nothing is written behind your back
|
||||
|
||||
Gear sits in a U range and part of a 12-column width grid, so half- and third-width machines share a U; a drop snaps to the nearest free slot. A mount can follow the status check of its matching diagram node, and **Import links** derives patches from the links already drawn on your diagrams.
|
||||
|
||||
> **Full documentation:** [docs/rack-canvas.md](./docs/rack-canvas.md)
|
||||
|
||||
---
|
||||
|
||||
@@ -317,7 +365,7 @@ docker compose up -d mcp
|
||||
|
||||
**Claude Code** — run this command in your terminal:
|
||||
```bash
|
||||
claude mcp add --transport sse homelable http://<your-homelab-ip>:8001/mcp \
|
||||
claude mcp add --transport http homelable http://<your-homelab-ip>:8001/mcp/ \
|
||||
--header "X-API-Key: mcp_sk_yourkey"
|
||||
```
|
||||
|
||||
@@ -326,8 +374,8 @@ Or add it manually to `~/.claude.json`:
|
||||
{
|
||||
"mcpServers": {
|
||||
"homelable": {
|
||||
"type": "sse",
|
||||
"url": "http://<your-homelab-ip>:8001/mcp",
|
||||
"type": "http",
|
||||
"url": "http://<your-homelab-ip>:8001/mcp/",
|
||||
"headers": {
|
||||
"X-API-Key": "mcp_sk_yourkey"
|
||||
}
|
||||
@@ -341,8 +389,8 @@ Or add it manually to `~/.claude.json`:
|
||||
{
|
||||
"mcpServers": {
|
||||
"homelable": {
|
||||
"type": "sse",
|
||||
"url": "http://<your-homelab-ip>:8001/mcp",
|
||||
"type": "http",
|
||||
"url": "http://<your-homelab-ip>:8001/mcp/",
|
||||
"headers": {
|
||||
"X-API-Key": "mcp_sk_yourkey"
|
||||
}
|
||||
|
||||
+45
-10
@@ -1,31 +1,66 @@
|
||||
import hmac
|
||||
from dataclasses import dataclass
|
||||
|
||||
from fastapi import Depends, Header, HTTPException, Request, status
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||
|
||||
from app.core.config import settings
|
||||
from app.core.security import decode_token
|
||||
from app.core.security import decode_token, get_oidc_session
|
||||
|
||||
bearer = HTTPBearer(auto_error=False)
|
||||
|
||||
|
||||
def get_current_user(
|
||||
@dataclass(frozen=True)
|
||||
class AuthContext:
|
||||
subject: str
|
||||
display_name: str
|
||||
auth_method: str
|
||||
issuer: str | None = None
|
||||
csrf_token: str | None = None
|
||||
|
||||
|
||||
def get_auth_context(
|
||||
request: Request,
|
||||
credentials: HTTPAuthorizationCredentials | None = Depends(bearer),
|
||||
x_mcp_service_key: str | None = Header(default=None),
|
||||
) -> str:
|
||||
) -> AuthContext:
|
||||
# 1. MCP service key (Docker-internal only — backend port is not externally exposed)
|
||||
if x_mcp_service_key is not None:
|
||||
if not settings.mcp_service_key:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="MCP service key not configured")
|
||||
if not hmac.compare_digest(x_mcp_service_key.encode(), settings.mcp_service_key.encode()):
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid MCP service key")
|
||||
return "__mcp_service__"
|
||||
return AuthContext(
|
||||
subject="__mcp_service__",
|
||||
display_name="MCP service",
|
||||
auth_method="mcp",
|
||||
)
|
||||
|
||||
# 2. Standard JWT bearer token
|
||||
if credentials is None:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Not authenticated")
|
||||
username = decode_token(credentials.credentials)
|
||||
if not username:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
|
||||
return username
|
||||
if credentials is not None:
|
||||
username = decode_token(credentials.credentials)
|
||||
if not username:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
|
||||
return AuthContext(
|
||||
subject=username,
|
||||
display_name=username,
|
||||
auth_method="local",
|
||||
)
|
||||
|
||||
# 3. OIDC session cookie (only active in exclusive OIDC mode)
|
||||
if settings.auth_mode == "oidc":
|
||||
oidc_session = get_oidc_session(request)
|
||||
if oidc_session is not None:
|
||||
return AuthContext(
|
||||
subject=oidc_session.subject,
|
||||
display_name=oidc_session.display_name,
|
||||
auth_method="oidc",
|
||||
issuer=oidc_session.issuer,
|
||||
csrf_token=oidc_session.csrf_token,
|
||||
)
|
||||
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Not authenticated")
|
||||
|
||||
|
||||
def get_current_user(context: AuthContext = Depends(get_auth_context)) -> str:
|
||||
return context.subject
|
||||
|
||||
@@ -1,12 +1,27 @@
|
||||
import hmac
|
||||
import logging
|
||||
from collections.abc import Mapping
|
||||
from typing import cast
|
||||
|
||||
from fastapi import APIRouter, HTTPException, status
|
||||
from authlib.integrations.base_client.errors import OAuthError
|
||||
from authlib.jose.errors import JoseError
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request, Response, status
|
||||
from pydantic import BaseModel
|
||||
from starlette.responses import RedirectResponse
|
||||
|
||||
from app.api.deps import AuthContext, get_auth_context
|
||||
from app.core.config import settings
|
||||
from app.core.security import create_access_token, verify_password
|
||||
from app.core.security import (
|
||||
clear_oidc_session_cookie,
|
||||
create_access_token,
|
||||
create_oidc_session_token,
|
||||
get_oidc_client,
|
||||
set_oidc_session_cookie,
|
||||
verify_password,
|
||||
)
|
||||
|
||||
router = APIRouter()
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class LoginRequest(BaseModel):
|
||||
@@ -19,8 +34,36 @@ class TokenResponse(BaseModel):
|
||||
token_type: str = "bearer"
|
||||
|
||||
|
||||
class AuthConfigResponse(BaseModel):
|
||||
mode: str
|
||||
oidc_login_url: str | None = None
|
||||
|
||||
|
||||
class CurrentUserResponse(BaseModel):
|
||||
subject: str
|
||||
display_name: str
|
||||
auth_method: str
|
||||
issuer: str | None = None
|
||||
csrf_token: str | None = None
|
||||
|
||||
|
||||
def _require_oidc_mode() -> None:
|
||||
if settings.auth_mode != "oidc":
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="OIDC login is disabled")
|
||||
|
||||
|
||||
@router.get("/config", response_model=AuthConfigResponse)
|
||||
async def auth_config() -> AuthConfigResponse:
|
||||
return AuthConfigResponse(
|
||||
mode=settings.auth_mode,
|
||||
oidc_login_url="/api/v1/auth/oidc/login" if settings.auth_mode == "oidc" else None,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/login", response_model=TokenResponse)
|
||||
async def login(body: LoginRequest) -> TokenResponse:
|
||||
if settings.auth_mode != "local":
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Local login is disabled")
|
||||
# Always run both checks to prevent timing-based username enumeration.
|
||||
# hmac.compare_digest is constant-time; verify_password (bcrypt) always runs.
|
||||
username_ok = hmac.compare_digest(body.username, settings.auth_username)
|
||||
@@ -29,3 +72,55 @@ async def login(body: LoginRequest) -> TokenResponse:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid credentials")
|
||||
token = create_access_token(body.username)
|
||||
return TokenResponse(access_token=token)
|
||||
|
||||
|
||||
@router.get("/oidc/login")
|
||||
async def oidc_login(request: Request) -> Response:
|
||||
_require_oidc_mode()
|
||||
client = get_oidc_client()
|
||||
return cast(Response, await client.authorize_redirect(request, settings.oidc_redirect_uri))
|
||||
|
||||
|
||||
@router.get("/oidc/callback")
|
||||
async def oidc_callback(request: Request) -> Response:
|
||||
_require_oidc_mode()
|
||||
client = get_oidc_client()
|
||||
try:
|
||||
token = await client.authorize_access_token(request)
|
||||
except (OAuthError, JoseError) as exc:
|
||||
logger.warning("OIDC callback rejected: %s", exc.error)
|
||||
request.session.clear()
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="OIDC authentication failed") from None
|
||||
|
||||
userinfo = token.get("userinfo")
|
||||
if not isinstance(userinfo, Mapping):
|
||||
request.session.clear()
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="OIDC authentication failed")
|
||||
try:
|
||||
session_token = create_oidc_session_token(userinfo)
|
||||
except ValueError:
|
||||
request.session.clear()
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="OIDC authentication failed") from None
|
||||
|
||||
request.session.clear()
|
||||
response = RedirectResponse(url="/", status_code=status.HTTP_303_SEE_OTHER)
|
||||
set_oidc_session_cookie(response, session_token)
|
||||
return response
|
||||
|
||||
|
||||
@router.get("/me", response_model=CurrentUserResponse)
|
||||
async def current_user(context: AuthContext = Depends(get_auth_context)) -> CurrentUserResponse:
|
||||
return CurrentUserResponse(
|
||||
subject=context.subject,
|
||||
display_name=context.display_name,
|
||||
auth_method=context.auth_method,
|
||||
issuer=context.issuer,
|
||||
csrf_token=context.csrf_token,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/logout", status_code=status.HTTP_204_NO_CONTENT)
|
||||
async def logout(_: AuthContext = Depends(get_auth_context)) -> Response:
|
||||
response = Response(status_code=status.HTTP_204_NO_CONTENT)
|
||||
clear_oidc_session_cookie(response)
|
||||
return response
|
||||
|
||||
@@ -12,6 +12,13 @@ from app.db.models import CanvasState, Design, Edge, Node
|
||||
from app.schemas.canvas import CanvasSaveRequest, CanvasStateResponse
|
||||
from app.schemas.edges import EdgeResponse
|
||||
from app.schemas.nodes import NodeResponse
|
||||
from app.services.inventory_sync import (
|
||||
facts_from_payload,
|
||||
hydrated_node,
|
||||
link_facts,
|
||||
load_devices_for,
|
||||
node_columns,
|
||||
)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -28,15 +35,21 @@ async def load_canvas(
|
||||
if design_id is None:
|
||||
return CanvasStateResponse(nodes=[], edges=[], viewport={"x": 0, "y": 0, "zoom": 1}, custom_style=None)
|
||||
|
||||
nodes = (await db.execute(select(Node).where(Node.design_id == design_id))).scalars().all()
|
||||
nodes = list((await db.execute(select(Node).where(Node.design_id == design_id))).scalars().all())
|
||||
edges = (await db.execute(select(Edge).where(Edge.design_id == design_id))).scalars().all()
|
||||
state = await db.get(CanvasState, design_id)
|
||||
viewport: dict[str, Any] = state.viewport if state else {"x": 0, "y": 0, "zoom": 1}
|
||||
# The device facts live on the inventory row now; hydrate them back into the
|
||||
# node so the wire shape the canvas consumes is unchanged.
|
||||
devices = await load_devices_for(db, nodes)
|
||||
return CanvasStateResponse(
|
||||
nodes=[NodeResponse.model_validate(n) for n in nodes],
|
||||
nodes=[NodeResponse.model_validate(hydrated_node(n, devices.get(n.device_id or ""))) for n in nodes],
|
||||
edges=[EdgeResponse.model_validate(e) for e in edges],
|
||||
viewport=viewport,
|
||||
custom_style=state.custom_style if state else None,
|
||||
# A CanvasState row exists only after a save (or explicit design create),
|
||||
# so its presence marks an intentional canvas vs. a never-touched one.
|
||||
initialized=state is not None,
|
||||
)
|
||||
|
||||
|
||||
@@ -71,16 +84,41 @@ async def save_canvas(
|
||||
|
||||
await db.flush()
|
||||
|
||||
# Upsert nodes
|
||||
# Upsert nodes, then route their device facts to the inventory row that owns
|
||||
# them — an edit made on this canvas is an edit to the device itself, and
|
||||
# every other canvas showing it follows.
|
||||
saved: list[tuple[Node, dict[str, Any], list[str] | None]] = []
|
||||
for node_data in body.nodes:
|
||||
db_node = await db.get(Node, node_data.id)
|
||||
payload = node_data.model_dump()
|
||||
payload["design_id"] = design_id
|
||||
facts = facts_from_payload(payload, label=node_data.label, node_type=node_data.type)
|
||||
columns = node_columns(payload)
|
||||
if db_node:
|
||||
for field, value in payload.items():
|
||||
for field, value in columns.items():
|
||||
setattr(db_node, field, value)
|
||||
else:
|
||||
db.add(Node(**payload))
|
||||
db_node = Node(**columns)
|
||||
db.add(db_node)
|
||||
saved.append((db_node, facts, node_data.changed_facts))
|
||||
|
||||
await db.flush()
|
||||
for node, facts, changed in saved:
|
||||
# The payload carries a full copy of each device, hydrated when this
|
||||
# canvas loaded. Routing all of it back would rewrite the row from a
|
||||
# stale snapshot — a save made for nothing but a moved node could revert
|
||||
# an edit meanwhile in the inventory modal. `changed_facts` (when the
|
||||
# client tracked it) plus the row diff narrow the write to this canvas'
|
||||
# actual edit.
|
||||
await link_facts(
|
||||
db,
|
||||
node,
|
||||
facts,
|
||||
overwrite_scalars=True,
|
||||
replace_lists=True,
|
||||
only_changed=True,
|
||||
changed_fields=changed,
|
||||
)
|
||||
|
||||
# Upsert edges
|
||||
for edge_data in body.edges:
|
||||
|
||||
@@ -6,7 +6,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.api.deps import get_current_user
|
||||
from app.db.database import get_db
|
||||
from app.db.models import CanvasState, Design, Edge, Node
|
||||
from app.db.models import CanvasState, Design, Edge, Node, Rack, RackCable, RackDevice
|
||||
from app.schemas.designs import DesignCopy, DesignCreate, DesignResponse, DesignUpdate
|
||||
|
||||
router = APIRouter()
|
||||
@@ -118,6 +118,56 @@ async def copy_design(
|
||||
)
|
||||
)
|
||||
|
||||
# Copy the rack canvas, if the source has one. Racks, mounted gear and patches
|
||||
# all get new ids; the inventory / node links are carried over untouched, since
|
||||
# a copy documents the same hardware.
|
||||
src_racks = (await db.execute(select(Rack).where(Rack.design_id == source_id))).scalars().all()
|
||||
rack_id_map = {r.id: str(uuid.uuid4()) for r in src_racks}
|
||||
rack_skip = {"id", "design_id", "created_at", "updated_at"}
|
||||
for r in src_racks:
|
||||
cols = {c.name: getattr(r, c.name) for c in Rack.__table__.columns if c.name not in rack_skip}
|
||||
db.add(Rack(id=rack_id_map[r.id], design_id=new_design.id, **cols))
|
||||
|
||||
src_rack_devices = (
|
||||
await db.execute(select(RackDevice).where(RackDevice.design_id == source_id))
|
||||
).scalars().all()
|
||||
rack_device_id_map = {d.id: str(uuid.uuid4()) for d in src_rack_devices}
|
||||
rack_device_skip = {"id", "design_id", "rack_id", "created_at", "updated_at"}
|
||||
for d in src_rack_devices:
|
||||
if d.rack_id not in rack_id_map:
|
||||
continue
|
||||
cols = {
|
||||
c.name: getattr(d, c.name)
|
||||
for c in RackDevice.__table__.columns
|
||||
if c.name not in rack_device_skip
|
||||
}
|
||||
db.add(
|
||||
RackDevice(
|
||||
id=rack_device_id_map[d.id],
|
||||
design_id=new_design.id,
|
||||
rack_id=rack_id_map[d.rack_id],
|
||||
**cols,
|
||||
)
|
||||
)
|
||||
|
||||
src_cables = (await db.execute(select(RackCable).where(RackCable.design_id == source_id))).scalars().all()
|
||||
cable_skip = {"id", "design_id", "from_device_id", "to_device_id", "created_at"}
|
||||
for c_row in src_cables:
|
||||
if c_row.from_device_id not in rack_device_id_map or c_row.to_device_id not in rack_device_id_map:
|
||||
continue
|
||||
cols = {
|
||||
c.name: getattr(c_row, c.name) for c in RackCable.__table__.columns if c.name not in cable_skip
|
||||
}
|
||||
db.add(
|
||||
RackCable(
|
||||
id=str(uuid.uuid4()),
|
||||
design_id=new_design.id,
|
||||
from_device_id=rack_device_id_map[c_row.from_device_id],
|
||||
to_device_id=rack_device_id_map[c_row.to_device_id],
|
||||
**cols,
|
||||
)
|
||||
)
|
||||
|
||||
# Copy canvas state (viewport, custom style, and the floor plan carried in viewport).
|
||||
src_state = await db.get(CanvasState, source_id)
|
||||
db.add(
|
||||
@@ -165,10 +215,20 @@ async def delete_design(
|
||||
count = (await db.execute(select(Design))).scalars().all()
|
||||
if len(count) <= 1:
|
||||
raise HTTPException(400, "Cannot delete the only design")
|
||||
# Delete associated canvas state, edges, nodes
|
||||
# Delete associated canvas state, rack rows, edges, nodes. SQLite does not
|
||||
# always enforce the ON DELETE CASCADE, so unwind by hand — cables before
|
||||
# devices before racks.
|
||||
cs = await db.get(CanvasState, design_id)
|
||||
if cs:
|
||||
await db.delete(cs)
|
||||
for cable in (await db.execute(select(RackCable).where(RackCable.design_id == design_id))).scalars().all():
|
||||
await db.delete(cable)
|
||||
for rack_device in (
|
||||
await db.execute(select(RackDevice).where(RackDevice.design_id == design_id))
|
||||
).scalars().all():
|
||||
await db.delete(rack_device)
|
||||
for rack in (await db.execute(select(Rack).where(Rack.design_id == design_id))).scalars().all():
|
||||
await db.delete(rack)
|
||||
edges = (await db.execute(select(Edge).where(Edge.design_id == design_id))).scalars().all()
|
||||
for e in edges:
|
||||
await db.delete(e)
|
||||
|
||||
@@ -13,6 +13,7 @@ from app.db.models import CanvasState, Design, Edge, Node
|
||||
from app.schemas.canvas import CanvasStateResponse
|
||||
from app.schemas.edges import EdgeResponse
|
||||
from app.schemas.nodes import NodeResponse
|
||||
from app.services.inventory_sync import hydrated_node, load_devices_for
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -59,13 +60,15 @@ async def liveview_canvas(
|
||||
if design_id is None:
|
||||
return CanvasStateResponse(nodes=[], edges=[], viewport={"x": 0, "y": 0, "zoom": 1}, custom_style=None)
|
||||
|
||||
nodes = (await db.execute(select(Node).where(Node.design_id == design_id))).scalars().all()
|
||||
nodes = list((await db.execute(select(Node).where(Node.design_id == design_id))).scalars().all())
|
||||
edges = (await db.execute(select(Edge).where(Edge.design_id == design_id))).scalars().all()
|
||||
state = await db.get(CanvasState, design_id)
|
||||
viewport: dict[str, Any] = state.viewport if state else {"x": 0, "y": 0, "zoom": 1}
|
||||
custom_style: dict[str, Any] | None = state.custom_style if state else None
|
||||
# Device facts come off the inventory row, same as the editable canvas.
|
||||
devices = await load_devices_for(db, nodes)
|
||||
return CanvasStateResponse(
|
||||
nodes=[NodeResponse.model_validate(n) for n in nodes],
|
||||
nodes=[NodeResponse.model_validate(hydrated_node(n, devices.get(n.device_id or ""))) for n in nodes],
|
||||
edges=[EdgeResponse.model_validate(e) for e in edges],
|
||||
viewport=viewport,
|
||||
custom_style=custom_style,
|
||||
|
||||
@@ -1,11 +1,21 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.api.deps import get_current_user
|
||||
from app.db.database import get_db
|
||||
from app.db.models import Design, Node
|
||||
from app.db.models import Design, InventoryDevice, Node
|
||||
from app.schemas.nodes import NodeCreate, NodeResponse, NodeUpdate
|
||||
from app.services.inventory_sync import (
|
||||
facts_from_payload,
|
||||
facts_from_update,
|
||||
hydrated_node,
|
||||
link_facts,
|
||||
load_devices_for,
|
||||
node_columns,
|
||||
)
|
||||
from app.services.node_dedupe import find_duplicate_node
|
||||
|
||||
router = APIRouter()
|
||||
@@ -55,13 +65,21 @@ async def _find_free_position(db: AsyncSession, design_id: str | None) -> tuple[
|
||||
|
||||
|
||||
@router.get("", response_model=list[NodeResponse])
|
||||
async def list_nodes(db: AsyncSession = Depends(get_db), _: str = Depends(get_current_user)) -> list[Node]:
|
||||
result = await db.execute(select(Node))
|
||||
return list(result.scalars().all())
|
||||
async def list_nodes(
|
||||
label: str | None = Query(None, description="Case-insensitive substring filter on node label"),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
_: str = Depends(get_current_user),
|
||||
) -> list[Any]:
|
||||
query = select(Node)
|
||||
if label:
|
||||
query = query.where(Node.label.ilike(f"%{label}%"))
|
||||
nodes = list((await db.execute(query)).scalars().all())
|
||||
devices = await load_devices_for(db, nodes)
|
||||
return [hydrated_node(n, devices.get(n.device_id or "")) for n in nodes]
|
||||
|
||||
|
||||
@router.post("", response_model=NodeResponse, status_code=status.HTTP_201_CREATED)
|
||||
async def create_node(body: NodeCreate, db: AsyncSession = Depends(get_db), _: str = Depends(get_current_user)) -> Node:
|
||||
async def create_node(body: NodeCreate, db: AsyncSession = Depends(get_db), _: str = Depends(get_current_user)) -> Any:
|
||||
data = body.model_dump()
|
||||
# `force` bypasses the duplicate guard below; it is not a Node column.
|
||||
force = data.pop("force", False)
|
||||
@@ -97,33 +115,57 @@ async def create_node(body: NodeCreate, db: AsyncSession = Depends(get_db), _: s
|
||||
if data["pos_y"] is None:
|
||||
data["pos_y"] = 0.0
|
||||
|
||||
node = Node(**data)
|
||||
node = Node(**node_columns(data))
|
||||
db.add(node)
|
||||
await db.flush()
|
||||
# A new device node gets (or joins) its Device Inventory row — the canvas is
|
||||
# one more way to document hardware, not a parallel store.
|
||||
await link_facts(
|
||||
db, node, facts_from_payload(data, label=data["label"], node_type=data["type"])
|
||||
)
|
||||
await db.commit()
|
||||
await db.refresh(node)
|
||||
return node
|
||||
return await _hydrate(db, node)
|
||||
|
||||
|
||||
async def _hydrate(db: AsyncSession, node: Node) -> dict[str, Any]:
|
||||
"""Node as the API reports it, with the device facts read off its row."""
|
||||
device = await db.get(InventoryDevice, node.device_id) if node.device_id else None
|
||||
return hydrated_node(node, device)
|
||||
|
||||
|
||||
@router.get("/{node_id}", response_model=NodeResponse)
|
||||
async def get_node(node_id: str, db: AsyncSession = Depends(get_db), _: str = Depends(get_current_user)) -> Node:
|
||||
async def get_node(node_id: str, db: AsyncSession = Depends(get_db), _: str = Depends(get_current_user)) -> Any:
|
||||
node = await db.get(Node, node_id)
|
||||
if not node:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Node not found")
|
||||
return node
|
||||
return await _hydrate(db, node)
|
||||
|
||||
|
||||
@router.patch("/{node_id}", response_model=NodeResponse)
|
||||
async def update_node(
|
||||
node_id: str, body: NodeUpdate, db: AsyncSession = Depends(get_db), _: str = Depends(get_current_user)
|
||||
) -> Node:
|
||||
) -> Any:
|
||||
node = await db.get(Node, node_id)
|
||||
if not node:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Node not found")
|
||||
for field, value in body.model_dump(exclude_unset=True).items():
|
||||
sent = body.model_dump(exclude_unset=True)
|
||||
for field, value in node_columns(sent).items():
|
||||
setattr(node, field, value)
|
||||
# The user edited the device, not just its drawing: push the facts down.
|
||||
# Only what was sent counts — an omitted field must not clear the row, and
|
||||
# lists are replaced only when the client actually sent them.
|
||||
facts = facts_from_update(sent)
|
||||
await link_facts(
|
||||
db,
|
||||
node,
|
||||
facts,
|
||||
overwrite_scalars=True,
|
||||
replace_lists="properties" in sent or "services" in sent,
|
||||
)
|
||||
await db.commit()
|
||||
await db.refresh(node)
|
||||
return node
|
||||
return await _hydrate(db, node)
|
||||
|
||||
|
||||
@router.delete("/{node_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
|
||||
@@ -21,7 +21,7 @@ from app.api.deps import get_current_user
|
||||
from app.core.config import settings
|
||||
from app.core.scheduler import reschedule_proxmox_sync, set_proxmox_sync_enabled
|
||||
from app.db.database import AsyncSessionLocal, get_db
|
||||
from app.db.models import Node, PendingDevice, PendingDeviceLink, ScanRun
|
||||
from app.db.models import InventoryDevice, InventoryDeviceLink, Node, ScanRun
|
||||
from app.schemas.proxmox import (
|
||||
ProxmoxConfig,
|
||||
ProxmoxConnectionRequest,
|
||||
@@ -35,7 +35,7 @@ from app.schemas.proxmox import (
|
||||
from app.schemas.scan import ScanRunResponse
|
||||
from app.services.discovery_sources import add_source
|
||||
from app.services.mac_utils import normalize_mac
|
||||
from app.services.node_dedupe import dedupe_nodes_by_ieee
|
||||
from app.services.node_dedupe import dedupe_nodes_by_device
|
||||
from app.services.proxmox_service import (
|
||||
build_proxmox_cluster_links,
|
||||
build_proxmox_properties,
|
||||
@@ -245,7 +245,7 @@ async def _persist_pending_import(
|
||||
nodes_raw: list[dict[str, Any]],
|
||||
edges_raw: list[dict[str, Any]],
|
||||
) -> ProxmoxImportPendingResponse:
|
||||
"""Upsert Proxmox nodes/edges into pending_devices + pending_device_links.
|
||||
"""Upsert Proxmox nodes/edges into device_inventory + device_inventory_links.
|
||||
|
||||
Two-tier identity (order matters):
|
||||
1. Match an existing canvas Node or pending row by **IP** (merge into a
|
||||
@@ -254,7 +254,7 @@ async def _persist_pending_import(
|
||||
|
||||
Update-in-place only. Nothing is ever deleted; hidden rows stay hidden.
|
||||
"""
|
||||
await dedupe_nodes_by_ieee(db)
|
||||
await dedupe_nodes_by_device(db)
|
||||
|
||||
cluster_pairs = build_proxmox_cluster_links(nodes_raw)
|
||||
cluster_members = {ieee for pair in cluster_pairs for ieee in pair}
|
||||
@@ -270,51 +270,44 @@ async def _persist_pending_import(
|
||||
mac = normalize_mac(n.get("mac"))
|
||||
props = build_proxmox_properties(n)
|
||||
|
||||
# 1) Already on a canvas? Match by ieee OR ip OR mac (the cross-source
|
||||
# dedup key — a stopped VM has no IP but its configured NIC MAC still
|
||||
# matches an ARP-scanned node). Refresh in place: merge properties, adopt
|
||||
# the pve identity onto a scanned node, backfill blank specs/hostname/mac.
|
||||
# Do NOT stomp user-set type/status.
|
||||
node_filter = [Node.ieee_address == ieee]
|
||||
if ip:
|
||||
node_filter.append(Node.ip == ip)
|
||||
if mac:
|
||||
node_filter.append(Node.mac == mac)
|
||||
existing_nodes = (
|
||||
await db.execute(select(Node).where(or_(*node_filter)).order_by(Node.id))
|
||||
).scalars().all()
|
||||
|
||||
if existing_nodes:
|
||||
for en in existing_nodes:
|
||||
en.properties = merge_proxmox_properties(en.properties, props)
|
||||
if not en.ieee_address:
|
||||
en.ieee_address = ieee
|
||||
if ip and not en.ip:
|
||||
en.ip = ip
|
||||
if mac and not en.mac:
|
||||
en.mac = mac
|
||||
en.hostname = en.hostname or n.get("hostname")
|
||||
en.cpu_count = en.cpu_count or n.get("cpu_count")
|
||||
en.ram_gb = en.ram_gb or n.get("ram_gb")
|
||||
en.disk_gb = en.disk_gb or n.get("disk_gb")
|
||||
# A cluster host needs one left + one right handle for the
|
||||
# cluster edge endpoints (both default to 0).
|
||||
if ieee in cluster_members:
|
||||
en.left_handles = max(en.left_handles or 0, 1)
|
||||
en.right_handles = max(en.right_handles or 0, 1)
|
||||
await _ensure_inventory_row(db, ieee, ip, mac, n, props, approved=True)
|
||||
pending_updated += 1
|
||||
continue
|
||||
|
||||
# 2) Not on canvas — upsert the pending inventory row.
|
||||
# Match by ieee OR ip OR mac (the cross-source dedup key — a stopped VM
|
||||
# has no IP but its configured NIC MAC still matches an ARP-scanned
|
||||
# device). The inventory row owns the facts, so the import merges into
|
||||
# it whether or not the device is drawn anywhere; a node only needs its
|
||||
# cluster handles adjusted. Do NOT stomp user-set type/status.
|
||||
pending = await _find_pending(db, ieee, ip, mac)
|
||||
drawn = bool(
|
||||
pending
|
||||
and (
|
||||
await db.execute(select(Node.id).where(Node.device_id == pending.id).limit(1))
|
||||
).scalar_one_or_none()
|
||||
)
|
||||
|
||||
if pending is None:
|
||||
db.add(_new_pending(ieee, ip, mac, n, props, status="pending"))
|
||||
pending_created += 1
|
||||
else:
|
||||
_refresh_pending(pending, ieee, ip, mac, n, props)
|
||||
if drawn:
|
||||
# Already on a canvas: refresh the facts but leave the lifecycle
|
||||
# alone (_refresh_pending would revive it as pending).
|
||||
await _ensure_inventory_row(db, ieee, ip, mac, n, props, approved=True)
|
||||
else:
|
||||
_refresh_pending(pending, ieee, ip, mac, n, props)
|
||||
pending.cpu_count = pending.cpu_count or n.get("cpu_count")
|
||||
pending.ram_gb = pending.ram_gb or n.get("ram_gb")
|
||||
pending.disk_gb = pending.disk_gb or n.get("disk_gb")
|
||||
pending_updated += 1
|
||||
|
||||
# A cluster host needs one left + one right handle for the cluster
|
||||
# edge endpoints (both default to 0) — the one piece of this that is
|
||||
# genuinely about how the node is drawn.
|
||||
if ieee in cluster_members:
|
||||
for en in (
|
||||
await db.execute(select(Node).where(Node.device_id == pending.id))
|
||||
).scalars().all():
|
||||
en.left_handles = max(en.left_handles or 0, 1)
|
||||
en.right_handles = max(en.right_handles or 0, 1)
|
||||
|
||||
links_recorded = await _replace_links(db, edges_raw, cluster_pairs)
|
||||
await db.commit()
|
||||
|
||||
@@ -328,14 +321,14 @@ async def _persist_pending_import(
|
||||
|
||||
async def _find_pending(
|
||||
db: AsyncSession, ieee: str, ip: str | None, mac: str | None
|
||||
) -> PendingDevice | None:
|
||||
filters = [PendingDevice.ieee_address == ieee]
|
||||
) -> InventoryDevice | None:
|
||||
filters = [InventoryDevice.ieee_address == ieee]
|
||||
if ip:
|
||||
filters.append(PendingDevice.ip == ip)
|
||||
filters.append(InventoryDevice.ip == ip)
|
||||
if mac:
|
||||
filters.append(PendingDevice.mac == mac)
|
||||
filters.append(InventoryDevice.mac == mac)
|
||||
return (
|
||||
await db.execute(select(PendingDevice).where(or_(*filters)))
|
||||
await db.execute(select(InventoryDevice).where(or_(*filters)))
|
||||
).scalars().first()
|
||||
|
||||
|
||||
@@ -346,8 +339,8 @@ def _new_pending(
|
||||
n: dict[str, Any],
|
||||
props: list[dict[str, Any]],
|
||||
status: str,
|
||||
) -> PendingDevice:
|
||||
return PendingDevice(
|
||||
) -> InventoryDevice:
|
||||
return InventoryDevice(
|
||||
ieee_address=ieee,
|
||||
ip=ip,
|
||||
mac=mac,
|
||||
@@ -357,13 +350,18 @@ def _new_pending(
|
||||
vendor=n.get("vendor"),
|
||||
model=n.get("model"),
|
||||
properties=props,
|
||||
# Specs the guest reports. They used to land only on the canvas node;
|
||||
# the inventory row owns them now.
|
||||
cpu_count=n.get("cpu_count"),
|
||||
ram_gb=n.get("ram_gb"),
|
||||
disk_gb=n.get("disk_gb"),
|
||||
status=status,
|
||||
discovery_source=_PROXMOX_GUEST_SOURCE,
|
||||
discovery_sources=[_PROXMOX_GUEST_SOURCE],
|
||||
)
|
||||
|
||||
|
||||
def _sources_after_merge(row: PendingDevice) -> list[str]:
|
||||
def _sources_after_merge(row: InventoryDevice) -> list[str]:
|
||||
"""Discovery sources for an inventory row after a Proxmox import merges in.
|
||||
|
||||
Must run BEFORE the ``pve-`` ieee is adopted onto the row, so it can tell
|
||||
@@ -381,7 +379,7 @@ def _sources_after_merge(row: PendingDevice) -> list[str]:
|
||||
|
||||
|
||||
def _refresh_pending(
|
||||
pending: PendingDevice,
|
||||
pending: InventoryDevice,
|
||||
ieee: str,
|
||||
ip: str | None,
|
||||
mac: str | None,
|
||||
@@ -441,8 +439,8 @@ async def _replace_links(
|
||||
(``proxmox_cluster`` → 'cluster' edges).
|
||||
"""
|
||||
await db.execute(
|
||||
sa_delete(PendingDeviceLink).where(
|
||||
PendingDeviceLink.discovery_source.in_([_PROXMOX_GUEST_SOURCE, _PROXMOX_CLUSTER_SOURCE])
|
||||
sa_delete(InventoryDeviceLink).where(
|
||||
InventoryDeviceLink.discovery_source.in_([_PROXMOX_GUEST_SOURCE, _PROXMOX_CLUSTER_SOURCE])
|
||||
)
|
||||
)
|
||||
recorded = 0
|
||||
@@ -453,7 +451,7 @@ async def _replace_links(
|
||||
if not src or not tgt or (src, tgt) in seen:
|
||||
return
|
||||
seen.add((src, tgt))
|
||||
db.add(PendingDeviceLink(source_ieee=src, target_ieee=tgt, discovery_source=source))
|
||||
db.add(InventoryDeviceLink(source_ieee=src, target_ieee=tgt, discovery_source=source))
|
||||
recorded += 1
|
||||
|
||||
for e in edges_raw:
|
||||
|
||||
@@ -0,0 +1,354 @@
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, TypeVar
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.api.deps import get_current_user
|
||||
from app.db.database import get_db
|
||||
from app.db.models import CanvasState, Design, InventoryDevice, Node, Rack, RackCable, RackDevice
|
||||
from app.schemas.racks import (
|
||||
RackCableResponse,
|
||||
RackDeviceResponse,
|
||||
RackInventoryItem,
|
||||
RackInventoryResponse,
|
||||
RackResponse,
|
||||
RackSaveRequest,
|
||||
RackServiceInfo,
|
||||
RackStateResponse,
|
||||
)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
# Device kinds that cannot be racked. An exclusion list rather than an allow list:
|
||||
# new hardware types should show up in the tray by default, and only the obviously
|
||||
# virtual / mesh / annotation kinds need to opt out.
|
||||
_UNRACKABLE_TYPES = {
|
||||
"vm",
|
||||
"lxc",
|
||||
"docker_container",
|
||||
"mobile",
|
||||
"laptop",
|
||||
"light",
|
||||
"socket",
|
||||
"load",
|
||||
"groupRect",
|
||||
"group",
|
||||
"text",
|
||||
"zigbee_coordinator",
|
||||
"zigbee_router",
|
||||
"zigbee_enddevice",
|
||||
"zwave_coordinator",
|
||||
"zwave_router",
|
||||
"zwave_enddevice",
|
||||
}
|
||||
|
||||
|
||||
_COMMON_PORTS = {22, 80, 443}
|
||||
|
||||
|
||||
def _service_name(device: InventoryDevice) -> str | None:
|
||||
"""Name a device after the app it runs, the way the Device Inventory does.
|
||||
|
||||
Ports everyone exposes (ssh, http, https) say nothing, and the generic web
|
||||
category loses to a real match, so "jellyfin" wins over "http".
|
||||
"""
|
||||
candidates = [
|
||||
s
|
||||
for s in (device.services or [])
|
||||
if isinstance(s, dict)
|
||||
and s.get("category")
|
||||
and s.get("service_name")
|
||||
# A service with no port is not a fingerprint the inventory names a
|
||||
# device after either — and `None not in _COMMON_PORTS` is True.
|
||||
and s.get("port") is not None
|
||||
and s.get("port") not in _COMMON_PORTS
|
||||
]
|
||||
if not candidates:
|
||||
return None
|
||||
named = next((s for s in candidates if str(s["category"]).lower() != "web"), candidates[0])
|
||||
name = named.get("service_name")
|
||||
return str(name) if name else None
|
||||
|
||||
|
||||
def _device_label(device: InventoryDevice) -> str:
|
||||
"""Inventory naming, mirrored: friendly name, host, app, IP, IEEE, id.
|
||||
|
||||
Must stay in step with `deviceLabel` in `InventoryDevicesModal.tsx` — a device
|
||||
the user picked out of the inventory by one name should not turn up in the
|
||||
rack picker under another.
|
||||
"""
|
||||
return (
|
||||
device.friendly_name
|
||||
or device.hostname
|
||||
or _service_name(device)
|
||||
or device.ip
|
||||
or device.ieee_address
|
||||
or device.id
|
||||
)
|
||||
|
||||
|
||||
# A mount prints its services as a short list, not a port scan dump.
|
||||
_MAX_SERVICES = 12
|
||||
|
||||
|
||||
def _services(raw: Any) -> list[RackServiceInfo]:
|
||||
"""Fingerprinted services, deduped and trimmed for the rack's info panel."""
|
||||
out: list[RackServiceInfo] = []
|
||||
seen: set[tuple[int | None, str | None]] = set()
|
||||
for entry in raw or []:
|
||||
if not isinstance(entry, dict):
|
||||
continue
|
||||
raw_port = entry.get("port")
|
||||
port = raw_port if isinstance(raw_port, int) else None
|
||||
raw_name = entry.get("service_name") or entry.get("name")
|
||||
name = str(raw_name) if raw_name else None
|
||||
if port is None and name is None:
|
||||
continue
|
||||
if (port, name) in seen:
|
||||
continue
|
||||
seen.add((port, name))
|
||||
out.append(RackServiceInfo(port=port, name=name))
|
||||
if len(out) == _MAX_SERVICES:
|
||||
break
|
||||
return out
|
||||
|
||||
|
||||
def _ip_tokens(ip: str | None) -> list[str]:
|
||||
"""Split a device ``ip`` field into individual addresses.
|
||||
|
||||
Mirrors the scan routes: the canvas stores multiple addresses in one
|
||||
comma-separated string, so matching must compare per-address.
|
||||
"""
|
||||
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:
|
||||
raise HTTPException(404, "Design not found")
|
||||
return design
|
||||
|
||||
|
||||
@router.get("", response_model=RackStateResponse)
|
||||
async def load_racks(
|
||||
design_id: str = Query(..., description="Rack design to load"),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
_: str = Depends(get_current_user),
|
||||
) -> RackStateResponse:
|
||||
await _require_design(db, design_id)
|
||||
|
||||
racks = (await db.execute(select(Rack).where(Rack.design_id == design_id))).scalars().all()
|
||||
devices = (
|
||||
await db.execute(select(RackDevice).where(RackDevice.design_id == design_id))
|
||||
).scalars().all()
|
||||
cables = (await db.execute(select(RackCable).where(RackCable.design_id == design_id))).scalars().all()
|
||||
state = await db.get(CanvasState, design_id)
|
||||
|
||||
return RackStateResponse(
|
||||
racks=[RackResponse.model_validate(r) for r in racks],
|
||||
devices=[RackDeviceResponse.model_validate(d) for d in devices],
|
||||
cables=[RackCableResponse.model_validate(c) for c in cables],
|
||||
viewport=state.viewport if state else {"x": 0, "y": 0, "zoom": 1},
|
||||
)
|
||||
|
||||
|
||||
@router.post("/save")
|
||||
async def save_racks(
|
||||
body: RackSaveRequest,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
_: str = Depends(get_current_user),
|
||||
) -> dict[str, bool]:
|
||||
"""Persist the full rack state of one design: upsert what is sent, prune the rest."""
|
||||
await _require_design(db, body.design_id)
|
||||
|
||||
rack_ids = {r.id for r in body.racks}
|
||||
device_ids = {d.id for d in body.devices}
|
||||
|
||||
# A device must land in a rack that is part of the same payload, and a cable
|
||||
# must join two devices in it — otherwise the prune below would orphan them.
|
||||
for device in body.devices:
|
||||
if device.rack_id not in rack_ids:
|
||||
raise HTTPException(400, f"Device {device.id} references unknown rack {device.rack_id}")
|
||||
for cable in body.cables:
|
||||
if cable.from_device_id not in device_ids or cable.to_device_id not in device_ids:
|
||||
raise HTTPException(400, f"Cable {cable.id} references a device outside this payload")
|
||||
|
||||
# Prune first (cables, then devices, then racks) so freed rows never collide
|
||||
# with an upsert that reuses their geometry.
|
||||
for existing_cable in (
|
||||
await db.execute(select(RackCable).where(RackCable.design_id == body.design_id))
|
||||
).scalars().all():
|
||||
if existing_cable.id not in {c.id for c in body.cables}:
|
||||
await db.delete(existing_cable)
|
||||
for existing_device in (
|
||||
await db.execute(select(RackDevice).where(RackDevice.design_id == body.design_id))
|
||||
).scalars().all():
|
||||
if existing_device.id not in device_ids:
|
||||
await db.delete(existing_device)
|
||||
for existing_rack in (
|
||||
await db.execute(select(Rack).where(Rack.design_id == body.design_id))
|
||||
).scalars().all():
|
||||
if existing_rack.id not in rack_ids:
|
||||
await db.delete(existing_rack)
|
||||
await db.flush()
|
||||
|
||||
for rack_data in body.racks:
|
||||
payload: dict[str, Any] = rack_data.model_dump()
|
||||
payload["design_id"] = body.design_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)
|
||||
else:
|
||||
db.add(Rack(**payload))
|
||||
await db.flush() # racks must exist before devices point at them
|
||||
|
||||
for device_data in body.devices:
|
||||
payload = device_data.model_dump()
|
||||
payload["design_id"] = body.design_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)
|
||||
else:
|
||||
db.add(RackDevice(**payload))
|
||||
await db.flush() # devices must exist before cables point at them
|
||||
|
||||
for cable_data in body.cables:
|
||||
payload = cable_data.model_dump()
|
||||
payload["design_id"] = body.design_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)
|
||||
else:
|
||||
db.add(RackCable(**payload))
|
||||
|
||||
# Viewport lives on the design's shared CanvasState row, like the logical canvas.
|
||||
state = await db.get(CanvasState, body.design_id)
|
||||
if state:
|
||||
state.viewport = body.viewport
|
||||
state.saved_at = datetime.now(timezone.utc)
|
||||
else:
|
||||
db.add(CanvasState(design_id=body.design_id, viewport=body.viewport))
|
||||
|
||||
await db.commit()
|
||||
return {"saved": True}
|
||||
|
||||
|
||||
@router.get("/inventory", response_model=RackInventoryResponse)
|
||||
async def rack_inventory(
|
||||
design_id: str = Query(..., description="Rack design the tray is for"),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
_: str = Depends(get_current_user),
|
||||
) -> RackInventoryResponse:
|
||||
"""Device Inventory entries that can be racked, flagged with what is already mounted.
|
||||
|
||||
Reads `device_inventory` — the inventory survives approval and node deletion,
|
||||
so unracking or deleting a canvas node never removes the entry here.
|
||||
"""
|
||||
await _require_design(db, design_id)
|
||||
|
||||
devices = (
|
||||
await db.execute(select(InventoryDevice).where(InventoryDevice.status != "hidden"))
|
||||
).scalars().all()
|
||||
mounts = (
|
||||
await db.execute(
|
||||
select(RackDevice.device_id, RackDevice.node_id).where(
|
||||
RackDevice.design_id == design_id
|
||||
)
|
||||
)
|
||||
).all()
|
||||
mounted = {device_id for device_id, _ in mounts if device_id}
|
||||
# A mount can name its canvas node itself, when the user linked one by hand
|
||||
# in the rack. That beats the IEEE/IP guess below: the guess is what failed
|
||||
# to find anything in the first place.
|
||||
pinned = {device_id: node_id for device_id, node_id in mounts if device_id and node_id}
|
||||
|
||||
# Correlate against canvas nodes: a node names the inventory row it draws,
|
||||
# so the IEEE/IP guessing this used to do is gone — the link is explicit.
|
||||
nodes = (await db.execute(select(Node))).scalars().all()
|
||||
by_id = {n.id: n for n in nodes}
|
||||
by_device: dict[str, Node] = {}
|
||||
for node in nodes:
|
||||
if node.device_id:
|
||||
by_device.setdefault(node.device_id, node)
|
||||
# Which canvas the matched node lives on — the rack prints it so the user
|
||||
# knows where the logical twin of a mount is drawn.
|
||||
design_names = {
|
||||
d.id: d.name for d in (await db.execute(select(Design))).scalars().all()
|
||||
}
|
||||
|
||||
# A pinned node may draw a *different* device than the mount names, so its
|
||||
# view is read off its own row.
|
||||
devices_by_id = {d.id: d for d in devices}
|
||||
|
||||
items = []
|
||||
for device in devices:
|
||||
if device.suggested_type in _UNRACKABLE_TYPES:
|
||||
continue
|
||||
# A node the user linked by hand wins; a deleted one falls back to the
|
||||
# node that draws this device, if any.
|
||||
linked: Node | None = by_id.get(pinned.get(device.id) or "") or by_device.get(device.id)
|
||||
# The logical view is whatever the linked node actually draws. Usually
|
||||
# that is this same row — the node_* fields then simply mirror it.
|
||||
node_device = None
|
||||
if linked is not None:
|
||||
node_device = devices_by_id.get(linked.device_id or "")
|
||||
if node_device is None and linked.device_id:
|
||||
node_device = await db.get(InventoryDevice, linked.device_id)
|
||||
items.append(
|
||||
RackInventoryItem(
|
||||
id=device.id,
|
||||
label=_device_label(device),
|
||||
suggested_type=device.suggested_type,
|
||||
ip=device.ip,
|
||||
status=device.status,
|
||||
discovery_source=device.discovery_source,
|
||||
mac=device.mac or device.ieee_address,
|
||||
hostname=device.hostname,
|
||||
os=device.os,
|
||||
services=_services(device.services),
|
||||
node_id=linked.id if linked else None,
|
||||
node_status=node_device.status_live if node_device else None,
|
||||
node_label=(
|
||||
(node_device.label if node_device else None) or linked.label
|
||||
) if linked else None,
|
||||
node_type=(
|
||||
(node_device.type if node_device else None) or linked.type
|
||||
) if linked else None,
|
||||
node_ip=node_device.ip if node_device else None,
|
||||
node_mac=(node_device.mac or node_device.ieee_address) if node_device else None,
|
||||
node_hostname=node_device.hostname if node_device else None,
|
||||
node_os=node_device.os if node_device else None,
|
||||
node_check_method=node_device.check_method if node_device else None,
|
||||
node_design_id=linked.design_id if linked else None,
|
||||
node_design_name=(
|
||||
design_names.get(linked.design_id) if linked and linked.design_id else None
|
||||
),
|
||||
node_last_seen=node_device.last_seen if node_device else None,
|
||||
racked=device.id in mounted,
|
||||
)
|
||||
)
|
||||
return RackInventoryResponse(items=items)
|
||||
+304
-148
@@ -12,10 +12,26 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from app.api.deps import get_current_user
|
||||
from app.core.config import settings
|
||||
from app.db.database import AsyncSessionLocal, get_db
|
||||
from app.db.models import Design, Edge, Node, PendingDevice, PendingDeviceLink, ScanRun
|
||||
from app.db.models import (
|
||||
Design,
|
||||
Edge,
|
||||
InventoryDevice,
|
||||
InventoryDeviceLink,
|
||||
Node,
|
||||
RackDevice,
|
||||
ScanRun,
|
||||
)
|
||||
from app.schemas.nodes import NodeCreate
|
||||
from app.schemas.scan import PendingDeviceResponse, ScanRunResponse
|
||||
from app.services.node_dedupe import dedupe_nodes_by_ieee, find_duplicate_node
|
||||
from app.schemas.scan import (
|
||||
InventoryDeviceCreate,
|
||||
InventoryDeviceResponse,
|
||||
InventoryDeviceUpdate,
|
||||
ScanRunResponse,
|
||||
)
|
||||
from app.services.discovery_sources import add_source
|
||||
from app.services.inventory_sync import find_device_for, merge_properties, merge_services
|
||||
from app.services.mac_utils import normalize_mac
|
||||
from app.services.node_dedupe import dedupe_nodes_by_device, find_duplicate_node
|
||||
from app.services.scanner import DeepScanOptions, _valid_port_range, request_cancel, run_scan
|
||||
from app.services.zigbee_service import (
|
||||
build_zigbee_properties,
|
||||
@@ -38,6 +54,15 @@ def _ip_tokens(ip: str | None) -> list[str]:
|
||||
return [t.strip() for t in ip.split(",") if t.strip()] if ip else []
|
||||
|
||||
|
||||
def _is_rack_only(device: InventoryDevice) -> bool:
|
||||
"""True for inventory entries created from a rack canvas.
|
||||
|
||||
They describe a mount — a patch panel, a shelf, a chassis — not a host to
|
||||
document on a logical canvas, so they are never approved onto one.
|
||||
"""
|
||||
return device.discovery_source == "rack" or "rack" in (device.discovery_sources or [])
|
||||
|
||||
|
||||
def _is_wireless(node_type: str | None) -> bool:
|
||||
"""Zigbee + Z-Wave mesh devices share online status / no ICMP check."""
|
||||
return node_type in _ZIGBEE_TYPES or node_type in _ZWAVE_TYPES
|
||||
@@ -224,74 +249,47 @@ def _agg(values: list[datetime], *, newest: bool) -> datetime | None:
|
||||
|
||||
|
||||
async def _canvas_correlation(
|
||||
db: AsyncSession, devices: list[PendingDevice]
|
||||
db: AsyncSession, devices: list[InventoryDevice]
|
||||
) -> dict[str, dict[str, Any]]:
|
||||
"""Correlate each device to existing canvas nodes by ``ieee_address``, ``mac``
|
||||
or ``ip``.
|
||||
"""Correlate each device to the canvas nodes drawing it.
|
||||
|
||||
Returns, per device id: the number of distinct canvases (designs) it appears
|
||||
on, plus aggregated timestamps from every matching node — created_at (oldest),
|
||||
last_scan / updated_at / last_seen (newest). One node query, grouped in Python
|
||||
(node counts are small for a homelab), so no N+1 per device.
|
||||
on, plus aggregated node timestamps — created_at (oldest) and updated_at
|
||||
(newest). A node names the inventory row it draws, so this is a group-by on
|
||||
``device_id`` rather than the ieee/mac/ip guesswork it used to be.
|
||||
|
||||
IP matching is per-address: a node's ``ip`` may hold several comma-separated
|
||||
addresses (e.g. an IPv6 added before the IPv4), so we index each token, not
|
||||
the raw string. MAC is a stable identifier immune to such IP edits, so it is
|
||||
matched too — cumulatively with ieee/ip (issue #258).
|
||||
``last_scan`` and ``last_seen`` come off the device row itself now: they are
|
||||
observations of the device, not of any one drawing of it.
|
||||
"""
|
||||
if not devices:
|
||||
return {}
|
||||
rows = (
|
||||
await db.execute(
|
||||
select(
|
||||
Node.ip,
|
||||
Node.mac,
|
||||
Node.ieee_address,
|
||||
Node.design_id,
|
||||
Node.created_at,
|
||||
Node.last_scan,
|
||||
Node.updated_at,
|
||||
Node.last_seen,
|
||||
).where(Node.design_id.isnot(None))
|
||||
select(Node.device_id, Node.design_id, Node.created_at, Node.updated_at)
|
||||
.where(Node.design_id.isnot(None), Node.device_id.isnot(None))
|
||||
)
|
||||
).all()
|
||||
# Index matching nodes by ip token, mac and ieee so a device can look up any.
|
||||
by_ip: dict[str, list[Any]] = {}
|
||||
by_mac: dict[str, list[Any]] = {}
|
||||
by_ieee: dict[str, list[Any]] = {}
|
||||
by_device: dict[str, list[Any]] = {}
|
||||
for row in rows:
|
||||
for tok in _ip_tokens(row.ip):
|
||||
by_ip.setdefault(tok, []).append(row)
|
||||
if row.mac:
|
||||
by_mac.setdefault(row.mac, []).append(row)
|
||||
if row.ieee_address:
|
||||
by_ieee.setdefault(row.ieee_address, []).append(row)
|
||||
by_device.setdefault(row.device_id, []).append(row)
|
||||
|
||||
info: dict[str, dict[str, Any]] = {}
|
||||
for d in devices:
|
||||
matched = []
|
||||
if d.ieee_address:
|
||||
matched += by_ieee.get(d.ieee_address, [])
|
||||
if d.mac:
|
||||
matched += by_mac.get(d.mac, [])
|
||||
for tok in _ip_tokens(d.ip):
|
||||
matched += by_ip.get(tok, [])
|
||||
# De-duplicate nodes matched by more than one identifier.
|
||||
matched = list({id(m): m for m in matched}.values())
|
||||
matched = by_device.get(d.id, [])
|
||||
designs = {m.design_id for m in matched}
|
||||
info[d.id] = {
|
||||
"canvas_count": len(designs),
|
||||
"node_created_at": _agg([m.created_at for m in matched], newest=False),
|
||||
"node_last_scan": _agg([m.last_scan for m in matched], newest=True),
|
||||
"node_last_scan": d.last_scan,
|
||||
"node_last_modified": _agg([m.updated_at for m in matched], newest=True),
|
||||
"node_last_seen": _agg([m.last_seen for m in matched], newest=True),
|
||||
"node_last_seen": d.last_seen,
|
||||
}
|
||||
return info
|
||||
|
||||
|
||||
async def _with_canvas_counts(
|
||||
db: AsyncSession, devices: list[PendingDevice]
|
||||
) -> list[PendingDevice]:
|
||||
db: AsyncSession, devices: list[InventoryDevice]
|
||||
) -> list[InventoryDevice]:
|
||||
"""Attach transient canvas count + linked-node timestamps for the response."""
|
||||
info = await _canvas_correlation(db, devices)
|
||||
for d in devices:
|
||||
@@ -304,28 +302,164 @@ async def _with_canvas_counts(
|
||||
return devices
|
||||
|
||||
|
||||
@router.get("/pending", response_model=list[PendingDeviceResponse])
|
||||
async def list_pending(db: AsyncSession = Depends(get_db), _: str = Depends(get_current_user)) -> list[PendingDevice]:
|
||||
@router.get("/pending", response_model=list[InventoryDeviceResponse])
|
||||
async def list_pending(db: AsyncSession = Depends(get_db), _: str = Depends(get_current_user)) -> list[InventoryDevice]:
|
||||
# Inventory: every scanned device except the user-hidden ones. Approved devices
|
||||
# stay listed so they keep showing with a canvas-presence badge.
|
||||
result = await db.execute(select(PendingDevice).where(PendingDevice.status != "hidden"))
|
||||
result = await db.execute(select(InventoryDevice).where(InventoryDevice.status != "hidden"))
|
||||
return await _with_canvas_counts(db, list(result.scalars().all()))
|
||||
|
||||
|
||||
@router.post("/pending", response_model=InventoryDeviceResponse, status_code=201)
|
||||
async def create_pending(
|
||||
body: InventoryDeviceCreate,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
_: str = Depends(get_current_user),
|
||||
) -> InventoryDevice:
|
||||
"""Add an inventory entry by hand, for hardware no scan can discover.
|
||||
|
||||
Lands as ``status="pending"`` like a discovery would, so the existing approve
|
||||
/ hide / restore flows apply unchanged.
|
||||
"""
|
||||
# One device is one row. If this host is already known — by ieee, ip or mac —
|
||||
# the user is documenting the device they already have, so fill in what the
|
||||
# row is missing rather than splitting it in two.
|
||||
mac = normalize_mac(body.mac)
|
||||
existing = await find_device_for(db, ip=body.ip, mac=mac, ieee=None)
|
||||
if existing is not None:
|
||||
for field in (
|
||||
"hostname", "ip", "os", "suggested_type", "model", "vendor", "label", "type",
|
||||
"notes", "cpu_count", "cpu_model", "ram_gb", "disk_gb", "check_method",
|
||||
"check_target", "friendly_name", "device_subtype",
|
||||
):
|
||||
value = getattr(body, field, None)
|
||||
if value not in (None, "") and getattr(existing, field, None) in (None, ""):
|
||||
setattr(existing, field, value)
|
||||
existing.mac = existing.mac or mac
|
||||
existing.properties = merge_properties(existing.properties, body.properties)
|
||||
existing.services = merge_services(existing.services, body.services)
|
||||
existing.discovery_sources = add_source(existing.discovery_sources, body.discovery_source)
|
||||
# A hidden row is still that device, so it is the one to fill in — but
|
||||
# adding a device by hand is asking for it, and returning it still hidden
|
||||
# would leave the user with a 201 and nothing in the inventory. The
|
||||
# explicit add outranks the earlier hide, exactly like restore.
|
||||
if existing.status == "hidden":
|
||||
existing.status = "pending"
|
||||
await db.commit()
|
||||
await db.refresh(existing)
|
||||
return (await _with_canvas_counts(db, [existing]))[0]
|
||||
|
||||
device = InventoryDevice(
|
||||
hostname=body.hostname,
|
||||
ip=body.ip,
|
||||
# Canonical form, like every other write path: dedup compares MACs by
|
||||
# equality, so a hand-typed "AA-BB-CC-11-22-33" would never match the
|
||||
# scanned "aa:bb:cc:11:22:33" and approve would build a duplicate node.
|
||||
mac=mac,
|
||||
suggested_type=body.suggested_type,
|
||||
model=body.model,
|
||||
vendor=body.vendor,
|
||||
properties=body.properties,
|
||||
status="pending",
|
||||
discovery_source=body.discovery_source,
|
||||
discovery_sources=[body.discovery_source],
|
||||
os=body.os,
|
||||
services=body.services,
|
||||
friendly_name=body.friendly_name,
|
||||
device_subtype=body.device_subtype,
|
||||
label=body.label,
|
||||
type=body.type,
|
||||
notes=body.notes,
|
||||
cpu_count=body.cpu_count,
|
||||
cpu_model=body.cpu_model,
|
||||
ram_gb=body.ram_gb,
|
||||
disk_gb=body.disk_gb,
|
||||
show_hardware=body.show_hardware,
|
||||
check_method=body.check_method,
|
||||
check_target=body.check_target,
|
||||
)
|
||||
db.add(device)
|
||||
await db.commit()
|
||||
await db.refresh(device)
|
||||
return (await _with_canvas_counts(db, [device]))[0]
|
||||
|
||||
|
||||
@router.patch("/pending/{device_id}", response_model=InventoryDeviceResponse)
|
||||
async def update_pending(
|
||||
device_id: str,
|
||||
body: InventoryDeviceUpdate,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
_: str = Depends(get_current_user),
|
||||
) -> InventoryDevice:
|
||||
"""Edit an inventory row — the device facts, not its lifecycle.
|
||||
|
||||
The inventory row owns what a device *is*; a canvas node only owns how it is
|
||||
drawn. This is the write path behind the device detail modal, and applies
|
||||
only the fields the client actually sent.
|
||||
"""
|
||||
device = (
|
||||
await db.execute(select(InventoryDevice).where(InventoryDevice.id == device_id))
|
||||
).scalar_one_or_none()
|
||||
if not device:
|
||||
raise HTTPException(status_code=404, detail="Device not found")
|
||||
|
||||
data = body.model_dump(exclude_unset=True)
|
||||
if "mac" in data:
|
||||
# Same reason as create_pending: dedup matches MACs by equality.
|
||||
data["mac"] = normalize_mac(data["mac"])
|
||||
for field, value in data.items():
|
||||
setattr(device, field, value)
|
||||
|
||||
await db.commit()
|
||||
await db.refresh(device)
|
||||
return (await _with_canvas_counts(db, [device]))[0]
|
||||
|
||||
|
||||
@router.delete("/pending", response_model=dict)
|
||||
async def clear_pending(
|
||||
db: AsyncSession = Depends(get_db),
|
||||
_: str = Depends(get_current_user),
|
||||
) -> dict[str, int]:
|
||||
from sqlalchemy import delete as sa_delete
|
||||
result = await db.execute(sa_delete(PendingDevice).where(PendingDevice.status == "pending"))
|
||||
result = await db.execute(sa_delete(InventoryDevice).where(InventoryDevice.status == "pending"))
|
||||
await db.commit()
|
||||
return {"deleted": result.rowcount}
|
||||
|
||||
|
||||
@router.get("/hidden", response_model=list[PendingDeviceResponse])
|
||||
async def list_hidden(db: AsyncSession = Depends(get_db), _: str = Depends(get_current_user)) -> list[PendingDevice]:
|
||||
result = await db.execute(select(PendingDevice).where(PendingDevice.status == "hidden"))
|
||||
@router.delete("/pending/{device_id}", response_model=dict)
|
||||
async def delete_pending(
|
||||
device_id: str,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
_: str = Depends(get_current_user),
|
||||
) -> dict[str, bool]:
|
||||
"""Remove one inventory entry.
|
||||
|
||||
Used by the rack canvas to drop the placeholder it created for a plate once
|
||||
that plate is pointed at a real inventory row. Refuses while a rack still
|
||||
mounts the device: SQLite runs with foreign keys off here, so the mount's
|
||||
``device_id`` would be left naming a row that no longer exists rather than
|
||||
being cleared by the ``ON DELETE SET NULL`` the schema declares.
|
||||
"""
|
||||
device = (
|
||||
await db.execute(select(InventoryDevice).where(InventoryDevice.id == device_id))
|
||||
).scalar_one_or_none()
|
||||
if not device:
|
||||
raise HTTPException(status_code=404, detail="Device not found")
|
||||
|
||||
mounted = (
|
||||
await db.execute(select(RackDevice.id).where(RackDevice.device_id == device_id).limit(1))
|
||||
).scalar_one_or_none()
|
||||
if mounted:
|
||||
raise HTTPException(status_code=409, detail="Device is mounted in a rack")
|
||||
|
||||
await db.delete(device)
|
||||
await db.commit()
|
||||
return {"deleted": True}
|
||||
|
||||
|
||||
@router.get("/hidden", response_model=list[InventoryDeviceResponse])
|
||||
async def list_hidden(db: AsyncSession = Depends(get_db), _: str = Depends(get_current_user)) -> list[InventoryDevice]:
|
||||
result = await db.execute(select(InventoryDevice).where(InventoryDevice.status == "hidden"))
|
||||
return await _with_canvas_counts(db, list(result.scalars().all()))
|
||||
|
||||
|
||||
@@ -336,7 +470,7 @@ async def bulk_approve_devices(
|
||||
_: str = Depends(get_current_user),
|
||||
) -> dict[str, Any]:
|
||||
# Repair any legacy same-canvas duplicate nodes before placing more.
|
||||
await dedupe_nodes_by_ieee(db)
|
||||
await dedupe_nodes_by_device(db)
|
||||
|
||||
# Target the design the user is on; fall back to the first design.
|
||||
default_design_id = payload.design_id
|
||||
@@ -350,97 +484,90 @@ async def bulk_approve_devices(
|
||||
# node was later deleted) must still be placeable on THIS design. Duplicates
|
||||
# are guarded per-design below, not by the global status flag.
|
||||
result = await db.execute(
|
||||
select(PendingDevice).where(
|
||||
PendingDevice.id.in_(payload.device_ids),
|
||||
PendingDevice.status != "hidden",
|
||||
select(InventoryDevice).where(
|
||||
InventoryDevice.id.in_(payload.device_ids),
|
||||
InventoryDevice.status != "hidden",
|
||||
)
|
||||
)
|
||||
devices = result.scalars().all()
|
||||
|
||||
# What already sits on the target canvas, so we skip devices already placed
|
||||
# here (by ip, mac or ieee_address) instead of creating duplicate nodes. We
|
||||
# map to the existing node id so the skip report can point the user at it. A
|
||||
# value may be a Node still pending flush (in-batch duplicate) — resolved to
|
||||
# its id after the flush below. IPs are indexed per comma-separated token so
|
||||
# a node whose ip is "fe80::1, 192.168.1.5" still matches a device scanned as
|
||||
# 192.168.1.5 (issue #258).
|
||||
# What already sits on the target canvas. A node names the inventory row it
|
||||
# draws, so "already placed" is now a device-id lookup rather than a guess
|
||||
# across ip/mac/ieee. The value may be a Node still pending flush (in-batch
|
||||
# duplicate) — resolved to its id after the flush below.
|
||||
existing = (
|
||||
await db.execute(
|
||||
select(Node.id, Node.ip, Node.mac, Node.ieee_address).where(
|
||||
Node.design_id == default_design_id
|
||||
select(Node.id, Node.device_id).where(
|
||||
Node.design_id == default_design_id, Node.device_id.isnot(None)
|
||||
)
|
||||
)
|
||||
).all()
|
||||
placed_ips: dict[str, Any] = {
|
||||
tok: nid for nid, ip, _, _ in existing for tok in _ip_tokens(ip)
|
||||
}
|
||||
placed_mac: dict[str, Any] = {mac: nid for nid, _, mac, _ in existing if mac}
|
||||
placed_ieee: dict[str, Any] = {ieee: nid for nid, _, _, ieee in existing if ieee}
|
||||
placed: dict[str, Any] = {device_id: nid for nid, device_id in existing}
|
||||
|
||||
created_nodes: list[Node] = []
|
||||
approved_devices: list[PendingDevice] = []
|
||||
approved_devices: list[InventoryDevice] = []
|
||||
skipped_devices: list[dict[str, Any]] = []
|
||||
for device in devices:
|
||||
# Record which identifier collided so the caller can explain each skip
|
||||
# (and, for existing on-canvas nodes, link to the node already there).
|
||||
ip_hit = next((t for t in _ip_tokens(device.ip) if t in placed_ips), None)
|
||||
if ip_hit is not None:
|
||||
# Rack-only gear belongs to a rack canvas, never to a logical one.
|
||||
if _is_rack_only(device):
|
||||
skipped_devices.append({
|
||||
"device_id": device.id,
|
||||
"label": device.hostname or device.friendly_name or device.ip or "device",
|
||||
"match": "ip", "value": ip_hit, "_ref": placed_ips[ip_hit],
|
||||
"label": device.hostname or device.friendly_name or "device",
|
||||
"match": "rack", "value": "rack device", "_ref": None,
|
||||
})
|
||||
continue
|
||||
if device.ieee_address is not None and device.ieee_address in placed_ieee:
|
||||
# Report which identifier names the device, so the caller can explain
|
||||
# the skip and link to the node already drawing it.
|
||||
if device.id in placed:
|
||||
match, value = (
|
||||
("ip", device.ip) if device.ip
|
||||
else ("ieee", device.ieee_address) if device.ieee_address
|
||||
else ("mac", device.mac)
|
||||
)
|
||||
skipped_devices.append({
|
||||
"device_id": device.id,
|
||||
"label": device.hostname or device.friendly_name or device.ieee_address or "device",
|
||||
"match": "ieee", "value": device.ieee_address, "_ref": placed_ieee[device.ieee_address],
|
||||
})
|
||||
continue
|
||||
if device.mac is not None and device.mac in placed_mac:
|
||||
skipped_devices.append({
|
||||
"device_id": device.id,
|
||||
"label": device.hostname or device.friendly_name or device.mac or "device",
|
||||
"match": "mac", "value": device.mac, "_ref": placed_mac[device.mac],
|
||||
"label": device.hostname or device.friendly_name or value or "device",
|
||||
"match": match, "value": value, "_ref": placed[device.id],
|
||||
})
|
||||
continue
|
||||
device.status = "approved"
|
||||
node_type = device.suggested_type or "generic"
|
||||
is_wireless = _is_wireless(node_type)
|
||||
cluster_host = await _is_proxmox_cluster_member(db, device.ieee_address)
|
||||
# Enrich the row, not the node: a mesh device's radio properties and the
|
||||
# default check method describe the device itself.
|
||||
device.type = device.type or node_type
|
||||
device.label = device.label or device.hostname or device.friendly_name or device.ip or "device"
|
||||
device.properties = (
|
||||
_wireless_properties(node_type, device.ieee_address, device.vendor, device.model, device.lqi)
|
||||
if is_wireless
|
||||
else merge_mac_property(list(device.properties or []), device.mac)
|
||||
)
|
||||
if is_wireless:
|
||||
# A mesh device answers no ICMP; being in the mesh is the liveness.
|
||||
device.check_method = "none"
|
||||
device.status_live = "online"
|
||||
elif not device.check_method:
|
||||
# Default to ping so the status checker actually polls it. Without
|
||||
# this the scheduler skips it (check_method NULL -> no check).
|
||||
device.check_method = "ping" if device.ip else None
|
||||
node = Node(
|
||||
label=device.hostname or device.friendly_name or device.ip or "device",
|
||||
type=node_type,
|
||||
ip=device.ip,
|
||||
mac=device.mac,
|
||||
hostname=device.hostname,
|
||||
status="online" if is_wireless else "unknown",
|
||||
services=device.services or [],
|
||||
ieee_address=device.ieee_address,
|
||||
properties=_wireless_properties(
|
||||
node_type, device.ieee_address, device.vendor, device.model, device.lqi
|
||||
) if is_wireless else merge_mac_property(list(device.properties or []), device.mac),
|
||||
# Default to ping so the status checker actually polls the new node.
|
||||
# Without this the scheduler skips it (check_method NULL → no check).
|
||||
check_method="none" if is_wireless else ("ping" if device.ip else None),
|
||||
# Cluster hosts get side handles for their host↔host cluster edge.
|
||||
label=device.label,
|
||||
type=device.type,
|
||||
# Cluster hosts get side handles for their host<->host cluster edge.
|
||||
left_handles=1 if cluster_host else 0,
|
||||
right_handles=1 if cluster_host else 0,
|
||||
design_id=default_design_id,
|
||||
# The node draws this inventory row; the row owns the facts.
|
||||
device_id=device.id,
|
||||
)
|
||||
db.add(node)
|
||||
created_nodes.append(node)
|
||||
approved_devices.append(device)
|
||||
# Track within this batch so a duplicate selection (same ip/mac/ieee) is
|
||||
# not placed twice on the same canvas. Store the Node so a later in-batch
|
||||
# skip can resolve to its id after flush.
|
||||
for tok in _ip_tokens(device.ip):
|
||||
placed_ips[tok] = node
|
||||
if device.mac:
|
||||
placed_mac[device.mac] = node
|
||||
if device.ieee_address:
|
||||
placed_ieee[device.ieee_address] = node
|
||||
# Track within this batch so a duplicate selection is not placed twice
|
||||
# on the same canvas. Stores the Node so a later in-batch skip can
|
||||
# resolve to its id after flush.
|
||||
placed[device.id] = node
|
||||
await db.flush() # populates node.id from Python-side default before reading
|
||||
# node_ids and approved_device_ids stay index-aligned for the client's mapping.
|
||||
node_ids = [n.id for n in created_nodes]
|
||||
@@ -477,9 +604,9 @@ async def bulk_hide_devices(
|
||||
_: str = Depends(get_current_user),
|
||||
) -> dict[str, Any]:
|
||||
result = await db.execute(
|
||||
select(PendingDevice).where(
|
||||
PendingDevice.id.in_(payload.device_ids),
|
||||
PendingDevice.status == "pending",
|
||||
select(InventoryDevice).where(
|
||||
InventoryDevice.id.in_(payload.device_ids),
|
||||
InventoryDevice.status == "pending",
|
||||
)
|
||||
)
|
||||
devices = result.scalars().all()
|
||||
@@ -495,7 +622,7 @@ async def restore_device(
|
||||
db: AsyncSession = Depends(get_db),
|
||||
_: str = Depends(get_current_user),
|
||||
) -> dict[str, Any]:
|
||||
device = await db.get(PendingDevice, device_id)
|
||||
device = await db.get(InventoryDevice, device_id)
|
||||
if not device:
|
||||
raise HTTPException(status_code=404, detail="Device not found")
|
||||
if device.status != "hidden":
|
||||
@@ -512,9 +639,9 @@ async def bulk_restore_devices(
|
||||
_: str = Depends(get_current_user),
|
||||
) -> dict[str, Any]:
|
||||
result = await db.execute(
|
||||
select(PendingDevice).where(
|
||||
PendingDevice.id.in_(payload.device_ids),
|
||||
PendingDevice.status == "hidden",
|
||||
select(InventoryDevice).where(
|
||||
InventoryDevice.id.in_(payload.device_ids),
|
||||
InventoryDevice.status == "hidden",
|
||||
)
|
||||
)
|
||||
devices = result.scalars().all()
|
||||
@@ -537,7 +664,7 @@ async def approve_device(
|
||||
first = (await db.execute(select(Design).order_by(Design.created_at).limit(1))).scalar()
|
||||
node_design_id = first.id if first else None
|
||||
|
||||
device = await db.get(PendingDevice, device_id)
|
||||
device = await db.get(InventoryDevice, device_id)
|
||||
if not device:
|
||||
raise HTTPException(status_code=404, detail="Device not found")
|
||||
# A device's status is GLOBAL — it flips to "approved" the moment it lands on
|
||||
@@ -549,6 +676,11 @@ async def approve_device(
|
||||
# device is off-limits here.
|
||||
if device.status == "hidden":
|
||||
raise HTTPException(status_code=409, detail="Device is hidden")
|
||||
if _is_rack_only(device):
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
detail="Rack devices cannot be placed on a logical canvas",
|
||||
)
|
||||
wireless = _is_wireless(node_data.type)
|
||||
|
||||
# A device already on THIS design (matched by ieee, ip OR mac) is NOT placed
|
||||
@@ -569,31 +701,52 @@ async def approve_device(
|
||||
raise HTTPException(status_code=409, detail=conflict)
|
||||
|
||||
device.status = "approved"
|
||||
# Prefer the MAC discovered during the scan (stored on the pending device);
|
||||
# Prefer the MAC discovered during the scan (stored on the inventory row);
|
||||
# fall back to whatever the approve payload carried.
|
||||
_mac = device.mac or node_data.mac
|
||||
cluster_host = await _is_proxmox_cluster_member(db, device.ieee_address)
|
||||
node = Node(
|
||||
label=node_data.label,
|
||||
type=node_data.type,
|
||||
ip=node_data.ip,
|
||||
mac=_mac,
|
||||
hostname=node_data.hostname,
|
||||
status="online" if wireless else node_data.status,
|
||||
services=node_data.services or [],
|
||||
ieee_address=device.ieee_address,
|
||||
properties=_wireless_properties(
|
||||
|
||||
# The approve dialog is an edit of the device, so its values land on the row
|
||||
# — the node that follows only says where it is drawn. A blank field in the
|
||||
# payload never clears what discovery already found.
|
||||
device.label = node_data.label or device.label
|
||||
device.type = node_data.type or device.type
|
||||
device.ip = node_data.ip or device.ip
|
||||
device.mac = _mac
|
||||
device.hostname = node_data.hostname or device.hostname
|
||||
device.services = merge_services(device.services, node_data.services)
|
||||
device.properties = (
|
||||
_wireless_properties(
|
||||
node_data.type, device.ieee_address, device.vendor, device.model, device.lqi
|
||||
) if wireless else merge_mac_property(
|
||||
)
|
||||
if wireless
|
||||
else merge_mac_property(
|
||||
merge_zigbee_properties(list(device.properties or []), node_data.properties or []),
|
||||
_mac,
|
||||
),
|
||||
check_method="none" if wireless else (node_data.check_method or ("ping" if node_data.ip else None)),
|
||||
check_target=None if wireless else node_data.check_target,
|
||||
# Cluster hosts get side handles for their host↔host cluster edge.
|
||||
)
|
||||
)
|
||||
if wireless:
|
||||
# A mesh device answers no ICMP; being in the mesh is the liveness.
|
||||
device.check_method = "none"
|
||||
device.check_target = None
|
||||
device.status_live = "online"
|
||||
else:
|
||||
device.check_method = node_data.check_method or device.check_method or (
|
||||
"ping" if device.ip else None
|
||||
)
|
||||
device.check_target = node_data.check_target or device.check_target
|
||||
if node_data.status:
|
||||
device.status_live = node_data.status
|
||||
|
||||
node = Node(
|
||||
label=device.label or node_data.label,
|
||||
type=device.type or node_data.type,
|
||||
# Cluster hosts get side handles for their host<->host cluster edge.
|
||||
left_handles=1 if cluster_host else 0,
|
||||
right_handles=1 if cluster_host else 0,
|
||||
design_id=node_design_id,
|
||||
# The node draws this inventory row; the row owns the facts.
|
||||
device_id=device.id,
|
||||
)
|
||||
db.add(node)
|
||||
await db.flush()
|
||||
@@ -621,10 +774,10 @@ async def _is_proxmox_cluster_member(db: AsyncSession, ieee: str | None) -> bool
|
||||
return False
|
||||
found = (
|
||||
await db.execute(
|
||||
select(PendingDeviceLink.id)
|
||||
select(InventoryDeviceLink.id)
|
||||
.where(
|
||||
PendingDeviceLink.discovery_source == "proxmox_cluster",
|
||||
(PendingDeviceLink.source_ieee == ieee) | (PendingDeviceLink.target_ieee == ieee),
|
||||
InventoryDeviceLink.discovery_source == "proxmox_cluster",
|
||||
(InventoryDeviceLink.source_ieee == ieee) | (InventoryDeviceLink.target_ieee == ieee),
|
||||
)
|
||||
.limit(1)
|
||||
)
|
||||
@@ -635,7 +788,7 @@ async def _is_proxmox_cluster_member(db: AsyncSession, ieee: str | None) -> bool
|
||||
async def _resolve_pending_links_for_ieee(
|
||||
db: AsyncSession, ieee: str | None, design_id: str | None
|
||||
) -> list[dict[str, str]]:
|
||||
"""Materialize edges for any pending_device_links involving ``ieee`` on the
|
||||
"""Materialize edges for any device_inventory_links involving ``ieee`` on the
|
||||
canvas identified by ``design_id``.
|
||||
|
||||
For each link where the other endpoint already exists as a Node *on this
|
||||
@@ -649,9 +802,9 @@ async def _resolve_pending_links_for_ieee(
|
||||
return []
|
||||
|
||||
links_q = await db.execute(
|
||||
select(PendingDeviceLink).where(
|
||||
(PendingDeviceLink.source_ieee == ieee)
|
||||
| (PendingDeviceLink.target_ieee == ieee)
|
||||
select(InventoryDeviceLink).where(
|
||||
(InventoryDeviceLink.source_ieee == ieee)
|
||||
| (InventoryDeviceLink.target_ieee == ieee)
|
||||
)
|
||||
)
|
||||
links = list(links_q.scalars().all())
|
||||
@@ -666,13 +819,16 @@ async def _resolve_pending_links_for_ieee(
|
||||
for link in links
|
||||
}
|
||||
other_ieees.add(ieee)
|
||||
# A node reaches its ieee through the inventory row it draws.
|
||||
nodes_q = await db.execute(
|
||||
select(Node).where(
|
||||
Node.ieee_address.in_(other_ieees),
|
||||
select(InventoryDevice.ieee_address, Node)
|
||||
.join(Node, Node.device_id == InventoryDevice.id)
|
||||
.where(
|
||||
InventoryDevice.ieee_address.in_(other_ieees),
|
||||
Node.design_id == design_id,
|
||||
)
|
||||
)
|
||||
by_ieee = {n.ieee_address: n for n in nodes_q.scalars().all() if n.ieee_address}
|
||||
by_ieee = {row_ieee: node for row_ieee, node in nodes_q.all() if row_ieee}
|
||||
|
||||
self_node = by_ieee.get(ieee)
|
||||
if self_node is None:
|
||||
@@ -751,7 +907,7 @@ async def _resolve_pending_links_for_ieee(
|
||||
async def hide_device(
|
||||
device_id: str, db: AsyncSession = Depends(get_db), _: str = Depends(get_current_user)
|
||||
) -> dict[str, bool]:
|
||||
device = await db.get(PendingDevice, device_id)
|
||||
device = await db.get(InventoryDevice, device_id)
|
||||
if not device:
|
||||
raise HTTPException(status_code=404, detail="Device not found")
|
||||
device.status = "hidden"
|
||||
@@ -763,7 +919,7 @@ async def hide_device(
|
||||
async def ignore_device(
|
||||
device_id: str, db: AsyncSession = Depends(get_db), _: str = Depends(get_current_user)
|
||||
) -> dict[str, bool]:
|
||||
device = await db.get(PendingDevice, device_id)
|
||||
device = await db.get(InventoryDevice, device_id)
|
||||
if not device:
|
||||
raise HTTPException(status_code=404, detail="Device not found")
|
||||
await db.delete(device)
|
||||
|
||||
@@ -4,13 +4,19 @@ from pydantic import BaseModel, Field
|
||||
|
||||
from app.api.deps import get_current_user
|
||||
from app.core.config import settings
|
||||
from app.core.scheduler import reschedule_service_checks, set_service_checks_enabled
|
||||
from app.core.scheduler import (
|
||||
reschedule_service_checks,
|
||||
reschedule_status_checks,
|
||||
set_service_checks_enabled,
|
||||
)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
class AppSettings(BaseModel):
|
||||
interval_seconds: int
|
||||
# Mirrors the floor enforced by reschedule_status_checks(): rejecting here
|
||||
# returns 422 instead of persisting the value and then failing with a 500.
|
||||
interval_seconds: int = Field(ge=10)
|
||||
service_check_enabled: bool = False
|
||||
service_check_interval: int = Field(default=300, ge=30)
|
||||
|
||||
@@ -33,6 +39,10 @@ async def update_settings(
|
||||
settings.service_check_enabled = payload.service_check_enabled
|
||||
settings.service_check_interval = payload.service_check_interval
|
||||
settings.save_overrides()
|
||||
# Apply the status-check schedule live. Without this the new interval is
|
||||
# persisted and shown in the UI, but the running job keeps the old one
|
||||
# until the backend restarts.
|
||||
reschedule_status_checks(payload.interval_seconds)
|
||||
# Apply the service-check schedule live.
|
||||
set_service_checks_enabled(payload.service_check_enabled)
|
||||
if payload.service_check_enabled:
|
||||
|
||||
@@ -6,7 +6,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.config import settings
|
||||
from app.db.database import get_db
|
||||
from app.db.models import Node, PendingDevice, ScanRun
|
||||
from app.db.models import InventoryDevice, Node, ScanRun
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -30,22 +30,38 @@ async def summary(
|
||||
"""
|
||||
_check_key(x_api_key)
|
||||
|
||||
# A node's reachability lives on the Device Inventory row it draws, so the
|
||||
# per-canvas counts come from the join. A node with no row (canvas
|
||||
# furniture) counts as unknown.
|
||||
status_rows = (
|
||||
await db.execute(select(Node.status, func.count()).group_by(Node.status))
|
||||
await db.execute(
|
||||
select(InventoryDevice.status_live, func.count())
|
||||
.select_from(Node)
|
||||
.join(InventoryDevice, Node.device_id == InventoryDevice.id)
|
||||
.group_by(InventoryDevice.status_live)
|
||||
)
|
||||
).all()
|
||||
counts = {row[0]: row[1] for row in status_rows}
|
||||
counts = {(row[0] or "unknown"): row[1] for row in status_rows}
|
||||
unlinked = (
|
||||
await db.execute(select(func.count()).select_from(Node).where(Node.device_id.is_(None)))
|
||||
).scalar_one()
|
||||
if unlinked:
|
||||
counts["unknown"] = counts.get("unknown", 0) + unlinked
|
||||
|
||||
pending = (
|
||||
await db.execute(
|
||||
select(func.count())
|
||||
.select_from(PendingDevice)
|
||||
.where(PendingDevice.status == "pending")
|
||||
.select_from(InventoryDevice)
|
||||
.where(InventoryDevice.status == "pending")
|
||||
)
|
||||
).scalar_one()
|
||||
|
||||
zigbee = (
|
||||
await db.execute(
|
||||
select(func.count()).select_from(Node).where(Node.ieee_address.isnot(None))
|
||||
select(func.count())
|
||||
.select_from(Node)
|
||||
.join(InventoryDevice, Node.device_id == InventoryDevice.id)
|
||||
.where(InventoryDevice.ieee_address.isnot(None))
|
||||
)
|
||||
).scalar_one()
|
||||
|
||||
@@ -58,6 +74,8 @@ async def summary(
|
||||
"online": counts.get("online", 0),
|
||||
"offline": counts.get("offline", 0),
|
||||
"unknown": counts.get("unknown", 0),
|
||||
# Wire key kept from before the table was renamed to `device_inventory`:
|
||||
# the stats payload is a published contract, and the MCP server reads it.
|
||||
"pending_devices": pending,
|
||||
"zigbee_devices": zigbee,
|
||||
"last_scan_at": last_scan_at.isoformat() if last_scan_at else None,
|
||||
|
||||
@@ -3,7 +3,13 @@ import json
|
||||
|
||||
from fastapi import APIRouter, WebSocket, WebSocketDisconnect
|
||||
|
||||
from app.core.security import decode_token
|
||||
from app.core.config import settings
|
||||
from app.core.security import (
|
||||
decode_oidc_session_token,
|
||||
decode_token,
|
||||
oidc_session_cookie_name,
|
||||
origin_is_allowed,
|
||||
)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -21,19 +27,29 @@ def _drop(websocket: WebSocket) -> None:
|
||||
async def ws_status(websocket: WebSocket) -> None:
|
||||
# Accept first so we can send a close frame with a reason code
|
||||
await websocket.accept()
|
||||
try:
|
||||
# Expect the first message to be a JSON auth payload: {"token": "<jwt>"}
|
||||
raw = await websocket.receive_text()
|
||||
try:
|
||||
payload = json.loads(raw)
|
||||
token = payload.get("token", "")
|
||||
except (json.JSONDecodeError, AttributeError):
|
||||
token = ""
|
||||
if not token or not decode_token(token):
|
||||
if not origin_is_allowed(websocket.headers.get("origin")):
|
||||
await websocket.close(code=1008) # Policy Violation
|
||||
return
|
||||
|
||||
if settings.auth_mode == "oidc":
|
||||
cookie_token = websocket.cookies.get(oidc_session_cookie_name(), "")
|
||||
if not cookie_token or decode_oidc_session_token(cookie_token) is None:
|
||||
await websocket.close(code=1008) # Policy Violation
|
||||
return
|
||||
except WebSocketDisconnect:
|
||||
return
|
||||
else:
|
||||
# Local mode keeps the existing first-message bearer protocol.
|
||||
try:
|
||||
raw = await websocket.receive_text()
|
||||
try:
|
||||
payload = json.loads(raw)
|
||||
token = payload.get("token", "")
|
||||
except (json.JSONDecodeError, AttributeError):
|
||||
token = ""
|
||||
if not token or not decode_token(token):
|
||||
await websocket.close(code=1008) # Policy Violation
|
||||
return
|
||||
except WebSocketDisconnect:
|
||||
return
|
||||
|
||||
_connections.append(websocket)
|
||||
try:
|
||||
@@ -55,20 +71,36 @@ async def _broadcast(payload: str) -> None:
|
||||
_drop(conn)
|
||||
|
||||
|
||||
async def broadcast_status(node_id: str, status: str, checked_at: str, response_time_ms: int | None = None) -> None:
|
||||
async def broadcast_status(
|
||||
device_id: str,
|
||||
node_ids: list[str],
|
||||
status: str,
|
||||
checked_at: str,
|
||||
response_time_ms: int | None = None,
|
||||
) -> None:
|
||||
"""Report one device's reachability to every canvas drawing it.
|
||||
|
||||
A device is checked once, not once per canvas, so the result is addressed by
|
||||
device and carries the nodes it lights up. ``node_ids`` is empty for a
|
||||
device that is in the inventory but on no canvas.
|
||||
"""
|
||||
await _broadcast(json.dumps({
|
||||
"type": "status",
|
||||
"node_id": node_id,
|
||||
"device_id": device_id,
|
||||
"node_ids": node_ids,
|
||||
"status": status,
|
||||
"checked_at": checked_at,
|
||||
"response_time_ms": response_time_ms,
|
||||
}))
|
||||
|
||||
|
||||
async def broadcast_service_status(node_id: str, services: list[dict[str, object]], checked_at: str) -> None:
|
||||
async def broadcast_service_status(
|
||||
device_id: str, node_ids: list[str], services: list[dict[str, object]], checked_at: str
|
||||
) -> None:
|
||||
await _broadcast(json.dumps({
|
||||
"type": "service_status",
|
||||
"node_id": node_id,
|
||||
"device_id": device_id,
|
||||
"node_ids": node_ids,
|
||||
"services": services,
|
||||
"checked_at": checked_at,
|
||||
}))
|
||||
|
||||
@@ -13,7 +13,7 @@ from app.api.deps import get_current_user
|
||||
from app.core.config import settings
|
||||
from app.core.scheduler import reschedule_zigbee_sync, set_zigbee_sync_enabled
|
||||
from app.db.database import AsyncSessionLocal, get_db
|
||||
from app.db.models import Node, PendingDevice, PendingDeviceLink, ScanRun
|
||||
from app.db.models import InventoryDevice, InventoryDeviceLink, Node, ScanRun
|
||||
from app.schemas.scan import ScanRunResponse
|
||||
from app.schemas.zigbee import (
|
||||
ZigbeeConfig,
|
||||
@@ -27,7 +27,7 @@ from app.schemas.zigbee import (
|
||||
ZigbeeTestConnectionRequest,
|
||||
ZigbeeTestConnectionResponse,
|
||||
)
|
||||
from app.services.node_dedupe import dedupe_nodes_by_ieee
|
||||
from app.services.node_dedupe import dedupe_nodes_by_device
|
||||
from app.services.zigbee_service import (
|
||||
build_zigbee_properties,
|
||||
fetch_networkmap,
|
||||
@@ -36,6 +36,15 @@ from app.services.zigbee_service import (
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def _is_drawn(db: AsyncSession, device_id: str) -> bool:
|
||||
"""True while at least one canvas node still draws this device."""
|
||||
return (
|
||||
await db.execute(select(Node.id).where(Node.device_id == device_id).limit(1))
|
||||
).scalar_one_or_none() is not None
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@@ -185,14 +194,14 @@ async def _persist_pending_import(
|
||||
nodes_raw: list[dict[str, Any]],
|
||||
edges_raw: list[dict[str, Any]],
|
||||
) -> ZigbeeImportPendingResponse:
|
||||
"""Upsert nodes/edges into pending_devices + pending_device_links.
|
||||
"""Upsert nodes/edges into device_inventory + device_inventory_links.
|
||||
|
||||
Coordinator auto-approves to a canvas Node. Other devices upsert by IEEE.
|
||||
All zigbee-source links are wiped and re-inserted from the new map.
|
||||
"""
|
||||
# Repair any pre-existing duplicate nodes (same IEEE) before upserting, so
|
||||
# the by-IEEE lookups below resolve to a single row.
|
||||
await dedupe_nodes_by_ieee(db)
|
||||
await dedupe_nodes_by_device(db)
|
||||
|
||||
# Coordinator is no longer auto-placed, so the response's coordinator fields
|
||||
# stay unset — retained for backward-compatible response shape.
|
||||
@@ -213,62 +222,17 @@ async def _persist_pending_import(
|
||||
# the pending inventory like every other device, so the user approves it
|
||||
# explicitly. Only the shared paths below run for it.
|
||||
|
||||
# If the device has already been approved as a canvas Node, refresh its
|
||||
# properties on every canvas it sits on. Still ensure the discovery
|
||||
# inventory carries a row for it (status="approved") so it shows in the
|
||||
# inventory list with an "In N canvas" badge — legacy auto-placed
|
||||
# coordinators never got a pending row, which is why they went missing.
|
||||
existing_nodes = (
|
||||
await db.execute(
|
||||
select(Node).where(Node.ieee_address == ieee).order_by(Node.id)
|
||||
)
|
||||
).scalars().all()
|
||||
if existing_nodes:
|
||||
for existing_node in existing_nodes:
|
||||
existing_node.properties = merge_zigbee_properties(
|
||||
existing_node.properties, props
|
||||
)
|
||||
inv = (
|
||||
await db.execute(
|
||||
select(PendingDevice).where(PendingDevice.ieee_address == ieee)
|
||||
)
|
||||
).scalar_one_or_none()
|
||||
if inv is None:
|
||||
db.add(
|
||||
PendingDevice(
|
||||
ieee_address=ieee,
|
||||
friendly_name=n.get("friendly_name"),
|
||||
hostname=n.get("friendly_name"),
|
||||
suggested_type=n.get("type"),
|
||||
device_subtype=n.get("device_type"),
|
||||
model=n.get("model"),
|
||||
vendor=n.get("vendor"),
|
||||
lqi=n.get("lqi"),
|
||||
status="approved",
|
||||
discovery_source="zigbee",
|
||||
)
|
||||
)
|
||||
pending_created += 1
|
||||
else:
|
||||
# Refresh metadata but never change the row's status (an approved
|
||||
# device stays approved; a hidden one stays hidden).
|
||||
inv.friendly_name = n.get("friendly_name") or inv.friendly_name
|
||||
inv.suggested_type = n.get("type") or inv.suggested_type
|
||||
inv.device_subtype = n.get("device_type") or inv.device_subtype
|
||||
inv.model = n.get("model") or inv.model
|
||||
inv.vendor = n.get("vendor") or inv.vendor
|
||||
if n.get("lqi") is not None:
|
||||
inv.lqi = n.get("lqi")
|
||||
pending_updated += 1
|
||||
continue
|
||||
|
||||
# Properties belong to the inventory row now, so one upsert serves
|
||||
# every canvas drawing this device — there is no per-node refresh left
|
||||
# to do. The row's status is never touched here: an approved device
|
||||
# stays approved, a hidden one stays hidden.
|
||||
result = await db.execute(
|
||||
select(PendingDevice).where(PendingDevice.ieee_address == ieee)
|
||||
select(InventoryDevice).where(InventoryDevice.ieee_address == ieee)
|
||||
)
|
||||
pending = result.scalar_one_or_none()
|
||||
if pending is None:
|
||||
db.add(
|
||||
PendingDevice(
|
||||
InventoryDevice(
|
||||
ieee_address=ieee,
|
||||
friendly_name=n.get("friendly_name"),
|
||||
hostname=n.get("friendly_name"),
|
||||
@@ -277,6 +241,7 @@ async def _persist_pending_import(
|
||||
model=n.get("model"),
|
||||
vendor=n.get("vendor"),
|
||||
lqi=n.get("lqi"),
|
||||
properties=props,
|
||||
status="pending",
|
||||
discovery_source="zigbee",
|
||||
)
|
||||
@@ -290,11 +255,11 @@ async def _persist_pending_import(
|
||||
pending.vendor = n.get("vendor") or pending.vendor
|
||||
if n.get("lqi") is not None:
|
||||
pending.lqi = n.get("lqi")
|
||||
if pending.status == "approved":
|
||||
# The device was approved earlier but its canvas Node no longer
|
||||
# exists (no Node matched the IEEE above) — it was deleted. Revive
|
||||
# the row to "pending" so it reappears in the Pending list on
|
||||
# re-import instead of being silently swallowed. (Issue #167)
|
||||
pending.properties = merge_zigbee_properties(list(pending.properties or []), props)
|
||||
if pending.status == "approved" and not await _is_drawn(db, pending.id):
|
||||
# Approved earlier but no canvas draws it any more — the node was
|
||||
# deleted. Revive the row to "pending" so it reappears in the list
|
||||
# on re-import instead of being silently swallowed. (Issue #167)
|
||||
pending.status = "pending"
|
||||
elif pending.status == "hidden":
|
||||
# Re-imported a hidden device → leave it hidden, just refresh fields.
|
||||
@@ -303,7 +268,7 @@ async def _persist_pending_import(
|
||||
|
||||
# Replace all zigbee-source links with the freshly discovered set.
|
||||
await db.execute(
|
||||
sa_delete(PendingDeviceLink).where(PendingDeviceLink.discovery_source == "zigbee")
|
||||
sa_delete(InventoryDeviceLink).where(InventoryDeviceLink.discovery_source == "zigbee")
|
||||
)
|
||||
|
||||
links_recorded = 0
|
||||
@@ -315,7 +280,7 @@ async def _persist_pending_import(
|
||||
continue
|
||||
seen.add((src, tgt))
|
||||
db.add(
|
||||
PendingDeviceLink(
|
||||
InventoryDeviceLink(
|
||||
source_ieee=src,
|
||||
target_ieee=tgt,
|
||||
discovery_source="zigbee",
|
||||
|
||||
@@ -13,7 +13,7 @@ from app.api.deps import get_current_user
|
||||
from app.core.config import settings
|
||||
from app.core.scheduler import reschedule_zwave_sync, set_zwave_sync_enabled
|
||||
from app.db.database import AsyncSessionLocal, get_db
|
||||
from app.db.models import Node, PendingDevice, PendingDeviceLink, ScanRun
|
||||
from app.db.models import InventoryDevice, InventoryDeviceLink, Node, ScanRun
|
||||
from app.schemas.scan import ScanRunResponse
|
||||
from app.schemas.zwave import (
|
||||
ZwaveConfig,
|
||||
@@ -27,7 +27,7 @@ from app.schemas.zwave import (
|
||||
ZwaveTestConnectionRequest,
|
||||
ZwaveTestConnectionResponse,
|
||||
)
|
||||
from app.services.node_dedupe import dedupe_nodes_by_ieee
|
||||
from app.services.node_dedupe import dedupe_nodes_by_device
|
||||
from app.services.zwave_service import (
|
||||
build_zwave_properties,
|
||||
fetch_zwave_network,
|
||||
@@ -36,6 +36,15 @@ from app.services.zwave_service import (
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def _is_drawn(db: AsyncSession, device_id: str) -> bool:
|
||||
"""True while at least one canvas node still draws this device."""
|
||||
return (
|
||||
await db.execute(select(Node.id).where(Node.device_id == device_id).limit(1))
|
||||
).scalar_one_or_none() is not None
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@@ -182,14 +191,14 @@ async def _persist_pending_import(
|
||||
nodes_raw: list[dict[str, Any]],
|
||||
edges_raw: list[dict[str, Any]],
|
||||
) -> ZwaveImportPendingResponse:
|
||||
"""Upsert nodes/edges into pending_devices + pending_device_links.
|
||||
"""Upsert nodes/edges into device_inventory + device_inventory_links.
|
||||
|
||||
Coordinator auto-approves to a canvas Node. Other devices upsert by Z-Wave
|
||||
identity. All zwave-source links are wiped and re-inserted from the new map.
|
||||
"""
|
||||
# Repair any pre-existing same-canvas duplicate nodes before upserting, so
|
||||
# the by-IEEE lookups below resolve cleanly.
|
||||
await dedupe_nodes_by_ieee(db)
|
||||
await dedupe_nodes_by_device(db)
|
||||
|
||||
# Coordinator is no longer auto-placed, so the response's coordinator fields
|
||||
# stay unset — retained for backward-compatible response shape.
|
||||
@@ -208,61 +217,17 @@ async def _persist_pending_import(
|
||||
# the pending inventory like every other device, so the user approves it
|
||||
# explicitly. Only the shared paths below run for it.
|
||||
|
||||
# Already approved as a canvas Node → refresh props on every canvas it
|
||||
# sits on. Still ensure the discovery inventory carries a row for it
|
||||
# (status="approved") so it shows in the inventory list with an
|
||||
# "In N canvas" badge — legacy auto-placed coordinators never got a
|
||||
# pending row, which is why they went missing.
|
||||
existing_nodes = (
|
||||
await db.execute(
|
||||
select(Node).where(Node.ieee_address == ieee).order_by(Node.id)
|
||||
)
|
||||
).scalars().all()
|
||||
if existing_nodes:
|
||||
for existing_node in existing_nodes:
|
||||
existing_node.properties = merge_zwave_properties(
|
||||
existing_node.properties, props
|
||||
)
|
||||
inv = (
|
||||
await db.execute(
|
||||
select(PendingDevice).where(PendingDevice.ieee_address == ieee)
|
||||
)
|
||||
).scalar_one_or_none()
|
||||
if inv is None:
|
||||
db.add(
|
||||
PendingDevice(
|
||||
ieee_address=ieee,
|
||||
friendly_name=n.get("friendly_name"),
|
||||
hostname=n.get("friendly_name"),
|
||||
suggested_type=n.get("type"),
|
||||
device_subtype=n.get("device_type"),
|
||||
model=n.get("model"),
|
||||
vendor=n.get("vendor"),
|
||||
lqi=n.get("lqi"),
|
||||
status="approved",
|
||||
discovery_source="zwave",
|
||||
)
|
||||
)
|
||||
pending_created += 1
|
||||
else:
|
||||
# Refresh metadata but never change the row's status.
|
||||
inv.friendly_name = n.get("friendly_name") or inv.friendly_name
|
||||
inv.suggested_type = n.get("type") or inv.suggested_type
|
||||
inv.device_subtype = n.get("device_type") or inv.device_subtype
|
||||
inv.model = n.get("model") or inv.model
|
||||
inv.vendor = n.get("vendor") or inv.vendor
|
||||
if n.get("lqi") is not None:
|
||||
inv.lqi = n.get("lqi")
|
||||
pending_updated += 1
|
||||
continue
|
||||
|
||||
# Properties belong to the inventory row now, so one upsert serves
|
||||
# every canvas drawing this device — there is no per-node refresh left
|
||||
# to do. The row's status is never touched here: an approved device
|
||||
# stays approved, a hidden one stays hidden.
|
||||
result = await db.execute(
|
||||
select(PendingDevice).where(PendingDevice.ieee_address == ieee)
|
||||
select(InventoryDevice).where(InventoryDevice.ieee_address == ieee)
|
||||
)
|
||||
pending = result.scalar_one_or_none()
|
||||
if pending is None:
|
||||
db.add(
|
||||
PendingDevice(
|
||||
InventoryDevice(
|
||||
ieee_address=ieee,
|
||||
friendly_name=n.get("friendly_name"),
|
||||
hostname=n.get("friendly_name"),
|
||||
@@ -271,6 +236,7 @@ async def _persist_pending_import(
|
||||
model=n.get("model"),
|
||||
vendor=n.get("vendor"),
|
||||
lqi=n.get("lqi"),
|
||||
properties=props,
|
||||
status="pending",
|
||||
discovery_source="zwave",
|
||||
)
|
||||
@@ -282,9 +248,10 @@ async def _persist_pending_import(
|
||||
pending.device_subtype = n.get("device_type") or pending.device_subtype
|
||||
pending.model = n.get("model") or pending.model
|
||||
pending.vendor = n.get("vendor") or pending.vendor
|
||||
if pending.status == "approved":
|
||||
# Approved earlier but the canvas Node is gone (deleted) — revive
|
||||
# to "pending" so it reappears in the list instead of vanishing.
|
||||
pending.properties = merge_zwave_properties(list(pending.properties or []), props)
|
||||
if pending.status == "approved" and not await _is_drawn(db, pending.id):
|
||||
# Approved earlier but no canvas draws it any more (the node was
|
||||
# deleted) — revive to "pending" so it reappears in the list.
|
||||
pending.status = "pending"
|
||||
elif pending.status == "hidden":
|
||||
pass
|
||||
@@ -292,7 +259,7 @@ async def _persist_pending_import(
|
||||
|
||||
# Replace all zwave-source links with the freshly discovered set.
|
||||
await db.execute(
|
||||
sa_delete(PendingDeviceLink).where(PendingDeviceLink.discovery_source == "zwave")
|
||||
sa_delete(InventoryDeviceLink).where(InventoryDeviceLink.discovery_source == "zwave")
|
||||
)
|
||||
|
||||
links_recorded = 0
|
||||
@@ -304,7 +271,7 @@ async def _persist_pending_import(
|
||||
continue
|
||||
seen.add((src, tgt))
|
||||
db.add(
|
||||
PendingDeviceLink(
|
||||
InventoryDeviceLink(
|
||||
source_ieee=src,
|
||||
target_ieee=tgt,
|
||||
discovery_source="zwave",
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import json
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import model_validator
|
||||
from pydantic import Field, model_validator
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -35,11 +36,22 @@ class Settings(BaseSettings):
|
||||
access_token_expire_minutes: int = 1440 # 24h
|
||||
|
||||
# Auth — set AUTH_USERNAME and AUTH_PASSWORD_HASH in .env
|
||||
auth_mode: Literal["local", "oidc"] = "local"
|
||||
auth_username: str = "admin"
|
||||
auth_password_hash: str = ""
|
||||
|
||||
# OpenID Connect — required only when AUTH_MODE=oidc.
|
||||
oidc_discovery_url: str = ""
|
||||
oidc_client_id: str = ""
|
||||
oidc_client_secret: str = ""
|
||||
oidc_redirect_uri: str = ""
|
||||
oidc_scopes: str = "openid profile email"
|
||||
oidc_cookie_secure: bool = True
|
||||
oidc_session_expire_minutes: int = Field(default=480, ge=5, le=1440)
|
||||
oidc_transaction_expire_seconds: int = Field(default=600, ge=60, le=3600)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def check_password_hash(self) -> "Settings":
|
||||
def validate_auth_settings(self) -> "Settings":
|
||||
h = self.auth_password_hash
|
||||
if h and not h.startswith("$2"):
|
||||
logger.error(
|
||||
@@ -47,11 +59,45 @@ class Settings(BaseSettings):
|
||||
"bcrypt hashes contain '$' signs — wrap the value in single quotes "
|
||||
"in your .env file: AUTH_PASSWORD_HASH='$2b$12$...'"
|
||||
)
|
||||
if self.auth_mode == "oidc":
|
||||
required = {
|
||||
"OIDC_DISCOVERY_URL": self.oidc_discovery_url,
|
||||
"OIDC_CLIENT_ID": self.oidc_client_id,
|
||||
"OIDC_CLIENT_SECRET": self.oidc_client_secret,
|
||||
"OIDC_REDIRECT_URI": self.oidc_redirect_uri,
|
||||
}
|
||||
missing = [name for name, value in required.items() if not value]
|
||||
if missing:
|
||||
raise ValueError(f"AUTH_MODE=oidc requires: {', '.join(missing)}")
|
||||
if len(self.secret_key.encode("utf-8")) < 32:
|
||||
raise ValueError("SECRET_KEY must be at least 32 bytes when AUTH_MODE=oidc")
|
||||
if "openid" not in self.oidc_scopes.split():
|
||||
raise ValueError("OIDC_SCOPES must contain 'openid'")
|
||||
for name, value in {
|
||||
"OIDC_DISCOVERY_URL": self.oidc_discovery_url,
|
||||
"OIDC_REDIRECT_URI": self.oidc_redirect_uri,
|
||||
}.items():
|
||||
if not value.startswith(("https://", "http://")):
|
||||
raise ValueError(f"{name} must be an HTTP(S) URL")
|
||||
if self.oidc_cookie_secure:
|
||||
for name, value in {
|
||||
"OIDC_DISCOVERY_URL": self.oidc_discovery_url,
|
||||
"OIDC_REDIRECT_URI": self.oidc_redirect_uri,
|
||||
}.items():
|
||||
if not value.startswith("https://"):
|
||||
raise ValueError(f"{name} must use HTTPS when OIDC_COOKIE_SECURE=true")
|
||||
if "*" in self.cors_origins:
|
||||
raise ValueError("CORS_ORIGINS cannot contain '*' when AUTH_MODE=oidc")
|
||||
return self
|
||||
|
||||
# Scanner
|
||||
scanner_ranges: list[str] = ["192.168.1.0/24"]
|
||||
|
||||
# Phase-2 version-detection (-sV) host timeout, seconds. Bounds the version
|
||||
# pass so a stalling TLS port (e.g. Proxmox 8006) can't hang it. Discovered
|
||||
# ports survive a timeout regardless; raise this on slow/overlay networks.
|
||||
scanner_version_host_timeout: int = 60
|
||||
|
||||
# Deep scan — persisted defaults (overridable per-scan from the scan dialog).
|
||||
# http_ranges: extra nmap port ranges, opt-in, no default. Probe + TLS off by default.
|
||||
scanner_http_ranges: list[str] = []
|
||||
|
||||
@@ -7,10 +7,11 @@ from typing import TYPE_CHECKING, Any
|
||||
|
||||
from apscheduler.schedulers.asyncio import AsyncIOScheduler
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.config import settings
|
||||
from app.db.database import AsyncSessionLocal
|
||||
from app.db.models import Node
|
||||
from app.db.models import InventoryDevice, Node
|
||||
from app.services.status_checker import check_node, check_services
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -22,13 +23,23 @@ logger = logging.getLogger(__name__)
|
||||
scheduler: AsyncIOScheduler = AsyncIOScheduler()
|
||||
|
||||
|
||||
async def _check_single_node(
|
||||
node_id: str,
|
||||
async def _nodes_by_device(db: AsyncSession) -> dict[str, list[str]]:
|
||||
"""Map each device id to the nodes drawing it, across every canvas."""
|
||||
rows = (await db.execute(select(Node.id, Node.device_id).where(Node.device_id.is_not(None)))).all()
|
||||
out: dict[str, list[str]] = {}
|
||||
for node_id, device_id in rows:
|
||||
out.setdefault(device_id, []).append(node_id)
|
||||
return out
|
||||
|
||||
|
||||
async def _check_single_device(
|
||||
device_id: str,
|
||||
node_ids: list[str],
|
||||
check_method: str,
|
||||
check_target: str | None,
|
||||
ip: str | None,
|
||||
) -> tuple[str, dict[str, object] | None]:
|
||||
"""Run a single node check; returns (node_id, result_or_None).
|
||||
"""Run a single device check; returns (device_id, result_or_None).
|
||||
|
||||
Accepts plain scalars — not an ORM object — so there is no risk of
|
||||
DetachedInstanceError when the originating session has already closed.
|
||||
@@ -37,45 +48,67 @@ async def _check_single_node(
|
||||
|
||||
try:
|
||||
check_result = await check_node(check_method, check_target, ip)
|
||||
raw_ms = check_result["response_time_ms"]
|
||||
response_ms = raw_ms if isinstance(raw_ms, int) else None
|
||||
now = datetime.now(timezone.utc)
|
||||
async with AsyncSessionLocal() as db:
|
||||
n = await db.get(Node, node_id)
|
||||
if n:
|
||||
n.status = check_result["status"]
|
||||
n.response_time_ms = check_result["response_time_ms"]
|
||||
device = await db.get(InventoryDevice, device_id)
|
||||
if device:
|
||||
device.status_live = str(check_result["status"])
|
||||
device.response_time_ms = response_ms
|
||||
if check_result["status"] == "online":
|
||||
n.last_seen = now
|
||||
device.last_seen = now
|
||||
await db.commit()
|
||||
await broadcast_status(
|
||||
node_id=node_id,
|
||||
status=check_result["status"],
|
||||
device_id=device_id,
|
||||
node_ids=node_ids,
|
||||
status=str(check_result["status"]),
|
||||
checked_at=now.isoformat(),
|
||||
response_time_ms=check_result["response_time_ms"],
|
||||
response_time_ms=response_ms,
|
||||
)
|
||||
return node_id, check_result
|
||||
return device_id, check_result
|
||||
except Exception as exc:
|
||||
logger.error("Status check failed for node %s: %s", node_id, exc)
|
||||
return node_id, None
|
||||
logger.error("Status check failed for device %s: %s", device_id, exc)
|
||||
return device_id, None
|
||||
|
||||
|
||||
async def _run_status_checks() -> None:
|
||||
"""Check all nodes concurrently and broadcast results via WebSocket."""
|
||||
"""Check every device once and broadcast the result to every canvas.
|
||||
|
||||
Device-scoped, not node-scoped: a host drawn on three canvases used to be
|
||||
pinged three times and could report three different states. Hidden devices
|
||||
are skipped — hiding one is how a user says "stop showing me this".
|
||||
|
||||
A device with no node at all is still checked, deliberately. The inventory
|
||||
row owns the device and shows its live status in the list and the detail
|
||||
modal, so a rack mount or an inventory-only entry reports state without
|
||||
being drawn anywhere — and deleting a node no longer silently stops
|
||||
monitoring the host. `hide` (or clearing the check method) is what ends the
|
||||
checks; the broadcast simply carries an empty `node_ids`.
|
||||
"""
|
||||
async with AsyncSessionLocal() as db:
|
||||
result = await db.execute(select(Node))
|
||||
nodes = result.scalars().all()
|
||||
devices = (
|
||||
await db.execute(
|
||||
select(InventoryDevice).where(
|
||||
InventoryDevice.check_method.is_not(None),
|
||||
InventoryDevice.check_method != "",
|
||||
InventoryDevice.status != "hidden",
|
||||
)
|
||||
)
|
||||
).scalars().all()
|
||||
node_map = await _nodes_by_device(db)
|
||||
# Extract scalars while the session is open to avoid DetachedInstanceError
|
||||
checkable = [
|
||||
(n.id, n.check_method, n.check_target, n.ip)
|
||||
for n in nodes
|
||||
if n.check_method
|
||||
(d.id, node_map.get(d.id, []), d.check_method or "ping", d.check_target, d.ip)
|
||||
for d in devices
|
||||
]
|
||||
|
||||
if not checkable:
|
||||
return
|
||||
|
||||
await asyncio.gather(*[
|
||||
_check_single_node(node_id, method, target, ip)
|
||||
for node_id, method, target, ip in checkable
|
||||
_check_single_device(device_id, node_ids, method, target, ip)
|
||||
for device_id, node_ids, method, target, ip in checkable
|
||||
])
|
||||
|
||||
|
||||
@@ -89,27 +122,35 @@ def _node_host(ip: str | None, hostname: str | None) -> str | None:
|
||||
|
||||
|
||||
async def _run_service_checks() -> None:
|
||||
"""Check every service of every node and broadcast per-service results."""
|
||||
"""Check every service of every device and broadcast per-service results.
|
||||
|
||||
Device-scoped for the same reason as the status check: the services belong
|
||||
to the device, so one pass serves every canvas showing it.
|
||||
"""
|
||||
if not settings.service_check_enabled:
|
||||
return
|
||||
from app.api.routes.status import broadcast_service_status # avoid circular import
|
||||
|
||||
async with AsyncSessionLocal() as db:
|
||||
result = await db.execute(select(Node))
|
||||
nodes = result.scalars().all()
|
||||
devices = (
|
||||
await db.execute(select(InventoryDevice).where(InventoryDevice.status != "hidden"))
|
||||
).scalars().all()
|
||||
node_map = await _nodes_by_device(db)
|
||||
checkable = [
|
||||
(n.id, _node_host(n.ip, n.hostname), list(n.services or []))
|
||||
for n in nodes
|
||||
if n.services
|
||||
(d.id, node_map.get(d.id, []), _node_host(d.ip, d.hostname), list(d.services or []))
|
||||
for d in devices
|
||||
if d.services
|
||||
]
|
||||
|
||||
now = datetime.now(timezone.utc).isoformat()
|
||||
for node_id, host, services in checkable:
|
||||
for device_id, node_ids, host, services in checkable:
|
||||
try:
|
||||
statuses = await check_services(host, services)
|
||||
await broadcast_service_status(node_id=node_id, services=statuses, checked_at=now)
|
||||
await broadcast_service_status(
|
||||
device_id=device_id, node_ids=node_ids, services=statuses, checked_at=now
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.error("Service checks failed for node %s: %s", node_id, exc)
|
||||
logger.error("Service checks failed for device %s: %s", device_id, exc)
|
||||
|
||||
|
||||
async def _run_proxmox_sync() -> None:
|
||||
|
||||
@@ -1,10 +1,33 @@
|
||||
import hmac
|
||||
import secrets
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from functools import lru_cache
|
||||
from typing import Any
|
||||
|
||||
import bcrypt
|
||||
from jose import JWTError, jwt
|
||||
import jwt
|
||||
from authlib.integrations.starlette_client import OAuth, StarletteOAuth2App
|
||||
from fastapi import Request, Response, status
|
||||
from jwt import InvalidTokenError
|
||||
from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
|
||||
from starlette.responses import JSONResponse
|
||||
|
||||
from app.core.config import settings
|
||||
|
||||
ACCESS_TOKEN_USE = "access"
|
||||
OIDC_SESSION_TOKEN_USE = "oidc_session"
|
||||
SAFE_METHODS = frozenset({"GET", "HEAD", "OPTIONS", "TRACE"})
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class OIDCSession:
|
||||
subject: str
|
||||
issuer: str
|
||||
display_name: str
|
||||
csrf_token: str
|
||||
|
||||
|
||||
def verify_password(plain: str, hashed: str) -> bool:
|
||||
if not plain or not hashed:
|
||||
@@ -21,14 +44,169 @@ def hash_password(password: str) -> str:
|
||||
|
||||
def create_access_token(subject: str) -> str:
|
||||
expire = datetime.now(timezone.utc) + timedelta(minutes=settings.access_token_expire_minutes)
|
||||
payload = {"sub": subject, "exp": expire}
|
||||
payload = {"sub": subject, "exp": expire, "token_use": ACCESS_TOKEN_USE}
|
||||
return str(jwt.encode(payload, settings.secret_key, algorithm=settings.algorithm))
|
||||
|
||||
|
||||
def decode_token(token: str) -> str | None:
|
||||
try:
|
||||
payload = jwt.decode(token, settings.secret_key, algorithms=[settings.algorithm])
|
||||
if payload.get("token_use") not in (None, ACCESS_TOKEN_USE):
|
||||
return None
|
||||
sub = payload.get("sub")
|
||||
return str(sub) if sub is not None else None
|
||||
except JWTError:
|
||||
except InvalidTokenError:
|
||||
return None
|
||||
|
||||
|
||||
def create_oidc_session_token(userinfo: Mapping[str, Any]) -> str:
|
||||
subject = userinfo.get("sub")
|
||||
issuer = userinfo.get("iss")
|
||||
if not isinstance(subject, str) or not subject or not isinstance(issuer, str) or not issuer:
|
||||
raise ValueError("OIDC userinfo must contain non-empty 'sub' and 'iss' claims")
|
||||
|
||||
display_name = next(
|
||||
(
|
||||
value
|
||||
for value in (
|
||||
userinfo.get("preferred_username"),
|
||||
userinfo.get("name"),
|
||||
userinfo.get("email"),
|
||||
subject,
|
||||
)
|
||||
if isinstance(value, str) and value
|
||||
),
|
||||
subject,
|
||||
)
|
||||
now = datetime.now(timezone.utc)
|
||||
payload = {
|
||||
"sub": subject,
|
||||
"oidc_issuer": issuer,
|
||||
"name": display_name,
|
||||
"csrf": secrets.token_urlsafe(32),
|
||||
"iat": now,
|
||||
"exp": now + timedelta(minutes=settings.oidc_session_expire_minutes),
|
||||
"token_use": OIDC_SESSION_TOKEN_USE,
|
||||
}
|
||||
return str(jwt.encode(payload, settings.secret_key, algorithm=settings.algorithm))
|
||||
|
||||
|
||||
def decode_oidc_session_token(token: str) -> OIDCSession | None:
|
||||
try:
|
||||
payload = jwt.decode(token, settings.secret_key, algorithms=[settings.algorithm])
|
||||
if payload.get("token_use") != OIDC_SESSION_TOKEN_USE:
|
||||
return None
|
||||
subject = payload.get("sub")
|
||||
issuer = payload.get("oidc_issuer")
|
||||
display_name = payload.get("name")
|
||||
csrf_token = payload.get("csrf")
|
||||
if not isinstance(subject, str) or not subject:
|
||||
return None
|
||||
if not isinstance(issuer, str) or not issuer:
|
||||
return None
|
||||
if not isinstance(display_name, str) or not display_name:
|
||||
return None
|
||||
if not isinstance(csrf_token, str) or not csrf_token:
|
||||
return None
|
||||
return OIDCSession(
|
||||
subject=subject,
|
||||
issuer=issuer,
|
||||
display_name=display_name,
|
||||
csrf_token=csrf_token,
|
||||
)
|
||||
except InvalidTokenError:
|
||||
return None
|
||||
|
||||
|
||||
def oidc_session_cookie_name() -> str:
|
||||
return "__Host-homelable-session" if settings.oidc_cookie_secure else "homelable-session"
|
||||
|
||||
|
||||
def set_oidc_session_cookie(response: Response, token: str) -> None:
|
||||
response.set_cookie(
|
||||
key=oidc_session_cookie_name(),
|
||||
value=token,
|
||||
max_age=settings.oidc_session_expire_minutes * 60,
|
||||
secure=settings.oidc_cookie_secure,
|
||||
httponly=True,
|
||||
samesite="lax",
|
||||
path="/",
|
||||
)
|
||||
|
||||
|
||||
def clear_oidc_session_cookie(response: Response) -> None:
|
||||
response.delete_cookie(
|
||||
key=oidc_session_cookie_name(),
|
||||
secure=settings.oidc_cookie_secure,
|
||||
httponly=True,
|
||||
samesite="lax",
|
||||
path="/",
|
||||
)
|
||||
|
||||
|
||||
def get_oidc_session(request: Request) -> OIDCSession | None:
|
||||
token = request.cookies.get(oidc_session_cookie_name())
|
||||
return decode_oidc_session_token(token) if token else None
|
||||
|
||||
|
||||
def origin_is_allowed(origin: str | None) -> bool:
|
||||
if not origin:
|
||||
return False
|
||||
allowed_origins = {value.rstrip("/") for value in settings.cors_origins}
|
||||
return origin.rstrip("/") in allowed_origins
|
||||
|
||||
|
||||
class OIDCCSRFMiddleware(BaseHTTPMiddleware):
|
||||
async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response:
|
||||
if settings.auth_mode != "oidc" or request.method in SAFE_METHODS:
|
||||
return await call_next(request)
|
||||
|
||||
# Explicit non-cookie credentials take precedence in get_current_user,
|
||||
# so their requests keep the existing CSRF-free API behavior.
|
||||
if request.headers.get("Authorization") or request.headers.get("X-MCP-Service-Key"):
|
||||
return await call_next(request)
|
||||
|
||||
oidc_session = get_oidc_session(request)
|
||||
if oidc_session is None:
|
||||
return await call_next(request)
|
||||
|
||||
csrf_token = request.headers.get("X-Homelable-CSRF", "")
|
||||
csrf_valid = hmac.compare_digest(csrf_token.encode(), oidc_session.csrf_token.encode())
|
||||
if not csrf_valid or not origin_is_allowed(request.headers.get("Origin")):
|
||||
return JSONResponse(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
content={"detail": "CSRF validation failed"},
|
||||
)
|
||||
return await call_next(request)
|
||||
|
||||
|
||||
@lru_cache(maxsize=8)
|
||||
def _build_oidc_client(
|
||||
discovery_url: str,
|
||||
client_id: str,
|
||||
client_secret: str,
|
||||
scopes: str,
|
||||
) -> StarletteOAuth2App:
|
||||
oauth = OAuth()
|
||||
client = oauth.register(
|
||||
name="oidc",
|
||||
client_id=client_id,
|
||||
client_secret=client_secret,
|
||||
server_metadata_url=discovery_url,
|
||||
client_kwargs={
|
||||
"scope": scopes,
|
||||
"code_challenge_method": "S256",
|
||||
},
|
||||
)
|
||||
if client is None:
|
||||
raise RuntimeError("Failed to register OIDC client")
|
||||
return client
|
||||
|
||||
|
||||
def get_oidc_client() -> StarletteOAuth2App:
|
||||
return _build_oidc_client(
|
||||
settings.oidc_discovery_url,
|
||||
settings.oidc_client_id,
|
||||
settings.oidc_client_secret,
|
||||
settings.oidc_scopes,
|
||||
)
|
||||
|
||||
@@ -204,6 +204,11 @@
|
||||
{"port": null, "protocol": "tcp", "banner_regex": null, "http_regex": "Syncthing", "service_name": "Syncthing", "icon": "refresh-cw", "category": "storage", "suggested_node_type": "server"},
|
||||
{"port": null, "protocol": "tcp", "banner_regex": null, "http_regex": "Gitea", "service_name": "Gitea", "icon": "git-branch", "category": "dev", "suggested_node_type": "server"},
|
||||
|
||||
{"port": null, "protocol": "tcp", "banner_regex": null, "http_regex": "[Pp]i[Kk]VM", "service_name": "PiKVM", "icon": "monitorcog", "category": "kvm", "suggested_node_type": "kvm"},
|
||||
{"port": null, "protocol": "tcp", "banner_regex": null, "http_regex": "TinyPilot", "service_name": "TinyPilot", "icon": "monitorcog", "category": "kvm", "suggested_node_type": "kvm"},
|
||||
{"port": null, "protocol": "tcp", "banner_regex": null, "http_regex": "JetKVM", "service_name": "JetKVM", "icon": "monitorcog", "category": "kvm", "suggested_node_type": "kvm"},
|
||||
{"port": null, "protocol": "tcp", "banner_regex": null, "http_regex": "NanoKVM", "service_name": "NanoKVM", "icon": "monitorcog", "category": "kvm", "suggested_node_type": "kvm"},
|
||||
|
||||
{"port": null, "protocol": "tcp", "banner_regex": null, "http_regex": "openmediavault", "service_name": "OpenMediaVault", "icon": "hard-drive", "category": "nas", "suggested_node_type": "nas"},
|
||||
{"port": null, "protocol": "tcp", "banner_regex": null, "http_regex": "Unraid", "service_name": "Unraid", "icon": "hard-drive", "category": "nas", "suggested_node_type": "nas"},
|
||||
{"port": null, "protocol": "tcp", "banner_regex": null, "http_regex": "Cockpit", "service_name": "Cockpit", "icon": "monitor", "category": "nas", "suggested_node_type": "server"}
|
||||
|
||||
+326
-29
@@ -5,8 +5,9 @@ import uuid as _uuid_mod
|
||||
from collections.abc import AsyncGenerator
|
||||
from contextlib import suppress
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy.exc import OperationalError
|
||||
from sqlalchemy.exc import IntegrityError, OperationalError
|
||||
from sqlalchemy.ext.asyncio import AsyncConnection, AsyncSession, async_sessionmaker, create_async_engine
|
||||
from sqlalchemy.orm import DeclarativeBase
|
||||
|
||||
@@ -60,9 +61,67 @@ def _backup_db() -> None:
|
||||
logger.warning("Could not create DB backup at %s", backup_path)
|
||||
|
||||
|
||||
# Tables renamed in 3.2.0. "Pending devices" was the scanner's word for a queue
|
||||
# of finds awaiting approval; the same rows outlive approval, are edited by hand
|
||||
# and are what a rack mounts, so the product calls them the Device Inventory.
|
||||
# Only the names moved — every column, every row and every route is unchanged.
|
||||
_RENAMED_TABLES: list[tuple[str, str]] = [
|
||||
("pending_devices", "device_inventory"),
|
||||
("pending_device_links", "device_inventory_links"),
|
||||
]
|
||||
|
||||
|
||||
async def _rename_legacy_tables(conn: AsyncConnection) -> None:
|
||||
"""Rename the pre-3.2.0 inventory tables. Must run before `create_all`.
|
||||
|
||||
Order matters: `create_all` would otherwise create an empty
|
||||
`device_inventory` beside the populated `pending_devices`, and every device
|
||||
the user ever scanned would look lost.
|
||||
|
||||
Foreign keys are switched on for the rename so SQLite rewrites the
|
||||
``REFERENCES pending_devices`` clause in `rack_devices` too; enforcement is
|
||||
off at runtime, so a missed rewrite costs nothing today, but it would leave
|
||||
the schema naming a table that no longer exists.
|
||||
"""
|
||||
for old, new in _RENAMED_TABLES:
|
||||
rows = (
|
||||
await conn.exec_driver_sql(
|
||||
"SELECT name FROM sqlite_master WHERE type='table' AND name IN (?, ?)",
|
||||
(old, new),
|
||||
)
|
||||
).fetchall()
|
||||
names = {r[0] for r in rows}
|
||||
if old not in names:
|
||||
continue # Fresh install, or already migrated.
|
||||
if new in names:
|
||||
# A start that ran `create_all` before this migration existed left an
|
||||
# empty new table beside the populated old one, and the app read the
|
||||
# empty one. Clear it out of the way rather than stranding the data;
|
||||
# a new table with rows in it means the rename already happened and
|
||||
# something re-created the old one, which is not ours to resolve.
|
||||
count = (await conn.exec_driver_sql(f"SELECT COUNT(*) FROM {new}")).scalar()
|
||||
if count:
|
||||
logger.warning(
|
||||
"Both %s and %s hold rows; leaving them alone. Merge them by hand.", old, new
|
||||
)
|
||||
continue
|
||||
logger.info("Dropping the empty %s left by an earlier start", new)
|
||||
await _try_migrate(conn, f"DROP TABLE {new}", label=f"{new}.drop_empty")
|
||||
logger.info("Migrating table %s -> %s", old, new)
|
||||
with suppress(OperationalError):
|
||||
await conn.exec_driver_sql("PRAGMA foreign_keys = ON")
|
||||
await _try_migrate(conn, f"ALTER TABLE {old} RENAME TO {new}", label=f"{new}.rename")
|
||||
# The index rides the rename under its old name; the model asks for the new
|
||||
# one, so drop the stale duplicate rather than carrying both.
|
||||
await _try_migrate(
|
||||
conn, "DROP INDEX IF EXISTS ix_pending_devices_ieee_address", label="device_inventory.index",
|
||||
)
|
||||
|
||||
|
||||
async def init_db() -> None:
|
||||
_backup_db()
|
||||
async with engine.begin() as conn:
|
||||
await _rename_legacy_tables(conn)
|
||||
await conn.run_sync(Base.metadata.create_all)
|
||||
# Add columns introduced after initial schema (idempotent)
|
||||
with suppress(OperationalError):
|
||||
@@ -114,11 +173,11 @@ async def init_db() -> None:
|
||||
with suppress(OperationalError):
|
||||
await conn.exec_driver_sql("ALTER TABLE nodes ADD COLUMN right_handles INTEGER NOT NULL DEFAULT 0")
|
||||
with suppress(OperationalError):
|
||||
await conn.exec_driver_sql("ALTER TABLE pending_devices ADD COLUMN discovery_source TEXT")
|
||||
await conn.exec_driver_sql("ALTER TABLE device_inventory ADD COLUMN discovery_source TEXT")
|
||||
with suppress(OperationalError):
|
||||
await conn.exec_driver_sql("ALTER TABLE pending_devices ADD COLUMN properties JSON")
|
||||
await conn.exec_driver_sql("ALTER TABLE device_inventory ADD COLUMN properties JSON")
|
||||
with suppress(OperationalError):
|
||||
await conn.exec_driver_sql("UPDATE pending_devices SET properties = '[]' WHERE properties IS NULL")
|
||||
await conn.exec_driver_sql("UPDATE device_inventory SET properties = '[]' WHERE properties IS NULL")
|
||||
with suppress(OperationalError):
|
||||
await conn.exec_driver_sql("ALTER TABLE scan_runs ADD COLUMN kind TEXT NOT NULL DEFAULT 'ip'")
|
||||
# --- Zigbee schema migrations (logged variant per CLAUDE.md feedback) ---
|
||||
@@ -128,32 +187,32 @@ async def init_db() -> None:
|
||||
"nodes.ieee_address.index",
|
||||
"CREATE INDEX IF NOT EXISTS ix_nodes_ieee_address ON nodes(ieee_address)",
|
||||
),
|
||||
("pending_devices.ieee_address", "ALTER TABLE pending_devices ADD COLUMN ieee_address TEXT"),
|
||||
("device_inventory.ieee_address", "ALTER TABLE device_inventory ADD COLUMN ieee_address TEXT"),
|
||||
(
|
||||
"pending_devices.ieee_address.index",
|
||||
"CREATE INDEX IF NOT EXISTS ix_pending_devices_ieee_address "
|
||||
"ON pending_devices(ieee_address)",
|
||||
"device_inventory.ieee_address.index",
|
||||
"CREATE INDEX IF NOT EXISTS ix_device_inventory_ieee_address "
|
||||
"ON device_inventory(ieee_address)",
|
||||
),
|
||||
("pending_devices.friendly_name", "ALTER TABLE pending_devices ADD COLUMN friendly_name TEXT"),
|
||||
("pending_devices.device_subtype", "ALTER TABLE pending_devices ADD COLUMN device_subtype TEXT"),
|
||||
("pending_devices.model", "ALTER TABLE pending_devices ADD COLUMN model TEXT"),
|
||||
("pending_devices.vendor", "ALTER TABLE pending_devices ADD COLUMN vendor TEXT"),
|
||||
("pending_devices.lqi", "ALTER TABLE pending_devices ADD COLUMN lqi INTEGER"),
|
||||
("device_inventory.friendly_name", "ALTER TABLE device_inventory ADD COLUMN friendly_name TEXT"),
|
||||
("device_inventory.device_subtype", "ALTER TABLE device_inventory ADD COLUMN device_subtype TEXT"),
|
||||
("device_inventory.model", "ALTER TABLE device_inventory ADD COLUMN model TEXT"),
|
||||
("device_inventory.vendor", "ALTER TABLE device_inventory ADD COLUMN vendor TEXT"),
|
||||
("device_inventory.lqi", "ALTER TABLE device_inventory ADD COLUMN lqi INTEGER"),
|
||||
]
|
||||
for label, sql in zigbee_migrations:
|
||||
await _try_migrate(conn, sql, label=label)
|
||||
# Drop NOT NULL on pending_devices.ip (Zigbee devices have no IP).
|
||||
# Drop NOT NULL on device_inventory.ip (Zigbee devices have no IP).
|
||||
# SQLite can't ALTER column nullability — rebuild the table if needed.
|
||||
try:
|
||||
info = await conn.exec_driver_sql("PRAGMA table_info(pending_devices)")
|
||||
info = await conn.exec_driver_sql("PRAGMA table_info(device_inventory)")
|
||||
cols = info.fetchall()
|
||||
ip_col = next((c for c in cols if c[1] == "ip"), None)
|
||||
# PRAGMA table_info row layout: (cid, name, type, notnull, dflt, pk)
|
||||
if ip_col and ip_col[3] == 1:
|
||||
logger.info("Migrating pending_devices: dropping NOT NULL on ip column")
|
||||
logger.info("Migrating device_inventory: dropping NOT NULL on ip column")
|
||||
await conn.exec_driver_sql("PRAGMA foreign_keys = OFF")
|
||||
await conn.exec_driver_sql(
|
||||
"CREATE TABLE pending_devices_new ("
|
||||
"CREATE TABLE device_inventory_new ("
|
||||
"id VARCHAR PRIMARY KEY,"
|
||||
"ip VARCHAR,"
|
||||
"mac VARCHAR, hostname VARCHAR, os VARCHAR, services JSON,"
|
||||
@@ -171,25 +230,25 @@ async def init_db() -> None:
|
||||
")"
|
||||
)
|
||||
await conn.exec_driver_sql(
|
||||
"INSERT INTO pending_devices_new "
|
||||
"INSERT INTO device_inventory_new "
|
||||
"(id, ip, mac, hostname, os, services, suggested_type, status, "
|
||||
"discovery_source, ieee_address, friendly_name, device_subtype, "
|
||||
"model, vendor, lqi, discovered_at) "
|
||||
"SELECT id, ip, mac, hostname, os, services, suggested_type, status, "
|
||||
"discovery_source, ieee_address, friendly_name, device_subtype, "
|
||||
"model, vendor, lqi, discovered_at FROM pending_devices"
|
||||
"model, vendor, lqi, discovered_at FROM device_inventory"
|
||||
)
|
||||
await conn.exec_driver_sql("DROP TABLE pending_devices")
|
||||
await conn.exec_driver_sql("DROP TABLE device_inventory")
|
||||
await conn.exec_driver_sql(
|
||||
"ALTER TABLE pending_devices_new RENAME TO pending_devices"
|
||||
"ALTER TABLE device_inventory_new RENAME TO device_inventory"
|
||||
)
|
||||
await conn.exec_driver_sql(
|
||||
"CREATE INDEX IF NOT EXISTS ix_pending_devices_ieee_address "
|
||||
"ON pending_devices(ieee_address)"
|
||||
"CREATE INDEX IF NOT EXISTS ix_device_inventory_ieee_address "
|
||||
"ON device_inventory(ieee_address)"
|
||||
)
|
||||
await conn.exec_driver_sql("PRAGMA foreign_keys = ON")
|
||||
except OperationalError as exc:
|
||||
logger.warning("pending_devices ip-nullable rebuild failed: %s", exc)
|
||||
logger.warning("device_inventory ip-nullable rebuild failed: %s", exc)
|
||||
# --- end Zigbee schema migrations -------------------------------------
|
||||
# --- Electrical designs schema migrations -----------------------------
|
||||
# Create designs table (idempotent)
|
||||
@@ -286,6 +345,22 @@ async def init_db() -> None:
|
||||
logger.warning("canvas_state migration failed: %s", exc)
|
||||
# --- end Electrical designs schema migrations --------------------------
|
||||
|
||||
# Rack cables gained editable annotations: a label the user can print on
|
||||
# the canvas, plus the same free-form property records nodes carry.
|
||||
rack_cable_migrations: list[tuple[str, str]] = [
|
||||
(
|
||||
"rack_cables.label_visible",
|
||||
"ALTER TABLE rack_cables ADD COLUMN label_visible BOOLEAN NOT NULL DEFAULT 0",
|
||||
),
|
||||
("rack_cables.properties", "ALTER TABLE rack_cables ADD COLUMN properties JSON"),
|
||||
]
|
||||
for label, sql in rack_cable_migrations:
|
||||
await _try_migrate(conn, sql, label=label)
|
||||
with suppress(OperationalError):
|
||||
await conn.exec_driver_sql(
|
||||
"UPDATE rack_cables SET properties = '[]' WHERE properties IS NULL"
|
||||
)
|
||||
|
||||
with suppress(OperationalError):
|
||||
await conn.exec_driver_sql("ALTER TABLE edges ADD COLUMN waypoints JSON")
|
||||
with suppress(OperationalError):
|
||||
@@ -325,33 +400,255 @@ async def init_db() -> None:
|
||||
# Proxmox import carries every source. Backfill from the legacy single
|
||||
# discovery_source so existing rows show under their filter.
|
||||
with suppress(OperationalError):
|
||||
await conn.exec_driver_sql("ALTER TABLE pending_devices ADD COLUMN discovery_sources JSON")
|
||||
await conn.exec_driver_sql("ALTER TABLE device_inventory ADD COLUMN discovery_sources JSON")
|
||||
with suppress(OperationalError):
|
||||
await conn.exec_driver_sql(
|
||||
"UPDATE pending_devices SET discovery_sources = json_array(discovery_source) "
|
||||
"UPDATE device_inventory SET discovery_sources = json_array(discovery_source) "
|
||||
"WHERE discovery_sources IS NULL AND discovery_source IS NOT NULL"
|
||||
)
|
||||
# Legacy IP-scanned rows predating discovery_source have a NULL scalar
|
||||
# but a real IP — treat them as an ARP scan so they keep the IP tag.
|
||||
with suppress(OperationalError):
|
||||
await conn.exec_driver_sql(
|
||||
"UPDATE pending_devices SET discovery_sources = json_array('arp') "
|
||||
"UPDATE device_inventory SET discovery_sources = json_array('arp') "
|
||||
"WHERE discovery_sources IS NULL AND discovery_source IS NULL AND ip IS NOT NULL"
|
||||
)
|
||||
with suppress(OperationalError):
|
||||
await conn.exec_driver_sql(
|
||||
"UPDATE pending_devices SET discovery_sources = '[]' WHERE discovery_sources IS NULL"
|
||||
"UPDATE device_inventory SET discovery_sources = '[]' WHERE discovery_sources IS NULL"
|
||||
)
|
||||
# Canonicalize stored MACs (lowercase, ':' separators) so cross-source
|
||||
# dedup can match a Proxmox NIC MAC against an ARP-scanned one by equality.
|
||||
with suppress(OperationalError):
|
||||
await conn.exec_driver_sql(
|
||||
"UPDATE pending_devices SET mac = lower(replace(mac, '-', ':')) WHERE mac IS NOT NULL"
|
||||
"UPDATE device_inventory SET mac = lower(replace(mac, '-', ':')) WHERE mac IS NOT NULL"
|
||||
)
|
||||
with suppress(OperationalError):
|
||||
await conn.exec_driver_sql(
|
||||
"UPDATE nodes SET mac = lower(replace(mac, '-', ':')) WHERE mac IS NOT NULL"
|
||||
)
|
||||
# 3.3.0 — the inventory row owns the device facts, the canvas node only
|
||||
# owns how it is drawn. These columns receive what used to live solely on
|
||||
# `nodes`. Additive here; `nodes` keeps its copies until the backfill has
|
||||
# run and been verified.
|
||||
inventory_device_migrations: list[tuple[str, str]] = [
|
||||
("device_inventory.label", "ALTER TABLE device_inventory ADD COLUMN label TEXT"),
|
||||
("device_inventory.type", "ALTER TABLE device_inventory ADD COLUMN type TEXT"),
|
||||
("device_inventory.notes", "ALTER TABLE device_inventory ADD COLUMN notes TEXT"),
|
||||
("device_inventory.cpu_count", "ALTER TABLE device_inventory ADD COLUMN cpu_count INTEGER"),
|
||||
("device_inventory.cpu_model", "ALTER TABLE device_inventory ADD COLUMN cpu_model TEXT"),
|
||||
("device_inventory.ram_gb", "ALTER TABLE device_inventory ADD COLUMN ram_gb FLOAT"),
|
||||
("device_inventory.disk_gb", "ALTER TABLE device_inventory ADD COLUMN disk_gb FLOAT"),
|
||||
(
|
||||
"device_inventory.show_hardware",
|
||||
"ALTER TABLE device_inventory ADD COLUMN show_hardware BOOLEAN DEFAULT 0",
|
||||
),
|
||||
("device_inventory.check_method", "ALTER TABLE device_inventory ADD COLUMN check_method TEXT"),
|
||||
("device_inventory.check_target", "ALTER TABLE device_inventory ADD COLUMN check_target TEXT"),
|
||||
(
|
||||
"device_inventory.status_live",
|
||||
"ALTER TABLE device_inventory ADD COLUMN status_live TEXT DEFAULT 'unknown'",
|
||||
),
|
||||
("device_inventory.last_seen", "ALTER TABLE device_inventory ADD COLUMN last_seen DATETIME"),
|
||||
("device_inventory.last_scan", "ALTER TABLE device_inventory ADD COLUMN last_scan DATETIME"),
|
||||
(
|
||||
"device_inventory.response_time_ms",
|
||||
"ALTER TABLE device_inventory ADD COLUMN response_time_ms INTEGER",
|
||||
),
|
||||
("device_inventory.updated_at", "ALTER TABLE device_inventory ADD COLUMN updated_at DATETIME"),
|
||||
]
|
||||
for label, sql in inventory_device_migrations:
|
||||
await _try_migrate(conn, sql, label=label)
|
||||
# Backfill the columns that carry a non-NULL default in the model, so a
|
||||
# legacy row round-trips through Pydantic without tripping the validators.
|
||||
# The link itself: a node points at the inventory row it draws.
|
||||
for label, sql in (
|
||||
("nodes.device_id", "ALTER TABLE nodes ADD COLUMN device_id TEXT"),
|
||||
(
|
||||
"nodes.device_id.index",
|
||||
"CREATE INDEX IF NOT EXISTS ix_nodes_device_id ON nodes(device_id)",
|
||||
),
|
||||
):
|
||||
await _try_migrate(conn, sql, label=label)
|
||||
for label, sql in (
|
||||
(
|
||||
"device_inventory.status_live.backfill",
|
||||
"UPDATE device_inventory SET status_live = 'unknown' WHERE status_live IS NULL",
|
||||
),
|
||||
(
|
||||
"device_inventory.show_hardware.backfill",
|
||||
"UPDATE device_inventory SET show_hardware = 0 WHERE show_hardware IS NULL",
|
||||
),
|
||||
(
|
||||
"device_inventory.updated_at.backfill",
|
||||
"UPDATE device_inventory SET updated_at = discovered_at WHERE updated_at IS NULL",
|
||||
),
|
||||
):
|
||||
await _try_migrate(conn, sql, label=label)
|
||||
|
||||
await _backfill_node_devices()
|
||||
await _drop_legacy_node_columns()
|
||||
|
||||
|
||||
|
||||
# Columns `nodes` carried before 3.3.0, when a node owned the device facts. They
|
||||
# belong to `device_inventory` now; the backfill above copies them across, and
|
||||
# this rebuild removes them.
|
||||
_LEGACY_NODE_COLUMNS = (
|
||||
"hostname", "ip", "mac", "os", "status", "check_method", "check_target",
|
||||
"services", "notes", "cpu_count", "cpu_model", "ram_gb", "disk_gb",
|
||||
"show_hardware", "properties", "ieee_address", "last_seen", "last_scan",
|
||||
"response_time_ms",
|
||||
)
|
||||
|
||||
# What a node keeps: how the device is drawn on one canvas.
|
||||
_NODE_COLUMNS_SQL = (
|
||||
"id VARCHAR PRIMARY KEY,"
|
||||
"type VARCHAR NOT NULL,"
|
||||
"label VARCHAR NOT NULL,"
|
||||
"design_id VARCHAR REFERENCES designs(id) ON DELETE SET NULL,"
|
||||
"device_id VARCHAR REFERENCES device_inventory(id) ON DELETE SET NULL,"
|
||||
"pos_x FLOAT,"
|
||||
"pos_y FLOAT,"
|
||||
"parent_id VARCHAR REFERENCES nodes(id) ON DELETE CASCADE,"
|
||||
"container_mode BOOLEAN,"
|
||||
"custom_colors JSON,"
|
||||
"custom_icon VARCHAR,"
|
||||
"show_port_numbers BOOLEAN,"
|
||||
"width FLOAT,"
|
||||
"height FLOAT,"
|
||||
"bottom_handles INTEGER,"
|
||||
"top_handles INTEGER,"
|
||||
"left_handles INTEGER,"
|
||||
"right_handles INTEGER,"
|
||||
"created_at DATETIME,"
|
||||
"updated_at DATETIME"
|
||||
)
|
||||
|
||||
_NODE_KEPT = (
|
||||
"id, type, label, design_id, device_id, pos_x, pos_y, parent_id, container_mode, "
|
||||
"custom_colors, custom_icon, show_port_numbers, width, height, bottom_handles, "
|
||||
"top_handles, left_handles, right_handles, created_at, updated_at"
|
||||
)
|
||||
|
||||
|
||||
async def _relax_legacy_node_columns(conn: AsyncConnection, info: list[Any]) -> None:
|
||||
"""Make the retained legacy `nodes` columns nullable — SQLite table rebuild.
|
||||
|
||||
The 3.2.0 schema declares `status`, `services`, `properties` and
|
||||
`show_hardware` NOT NULL with no server-side default. The 3.3.0 model no
|
||||
longer maps them, so every INSERT omits them and SQLite rejects the row —
|
||||
approving a device, creating a node, importing a canvas all fail with
|
||||
``NOT NULL constraint failed: nodes.status``. Dropping the columns is the
|
||||
real fix, but it waits on a complete backfill; until then they have to stop
|
||||
blocking writes. Values are preserved: only the constraint goes.
|
||||
"""
|
||||
kept = [row for row in info if row[1] in _LEGACY_NODE_COLUMNS]
|
||||
if not any(row[3] for row in kept): # PRAGMA `notnull`
|
||||
return # Already relaxed, or never constrained.
|
||||
|
||||
logger.info("Relaxing NOT NULL on the retained legacy node columns")
|
||||
legacy_defs = ",".join(f"{row[1]} {row[2] or 'VARCHAR'}" for row in kept)
|
||||
legacy_names = ", ".join(row[1] for row in kept)
|
||||
await _rebuild_nodes(
|
||||
conn,
|
||||
columns_sql=f"{_NODE_COLUMNS_SQL},{legacy_defs}",
|
||||
copied=f"{_NODE_KEPT}, {legacy_names}",
|
||||
what="nodes legacy-column relax",
|
||||
)
|
||||
|
||||
|
||||
async def _rebuild_nodes(conn: AsyncConnection, *, columns_sql: str, copied: str, what: str) -> None:
|
||||
"""Recreate `nodes` with a new column list — SQLite cannot alter constraints.
|
||||
|
||||
Never fatal: a rebuild that fails leaves the table it could not replace, and
|
||||
the boot carries on. Foreign keys go off for the swap, because `edges` and
|
||||
`rack_devices` point at `nodes`, and back on in every case — the pragma is
|
||||
per connection and this one returns to the pool.
|
||||
"""
|
||||
try:
|
||||
await conn.exec_driver_sql("PRAGMA foreign_keys = OFF")
|
||||
# A previous attempt that failed after the create would block this one.
|
||||
await conn.exec_driver_sql("DROP TABLE IF EXISTS nodes_new")
|
||||
await conn.exec_driver_sql(f"CREATE TABLE nodes_new ({columns_sql})")
|
||||
await conn.exec_driver_sql(f"INSERT INTO nodes_new ({copied}) SELECT {copied} FROM nodes")
|
||||
await conn.exec_driver_sql("DROP TABLE nodes")
|
||||
await conn.exec_driver_sql("ALTER TABLE nodes_new RENAME TO nodes")
|
||||
await conn.exec_driver_sql("CREATE INDEX IF NOT EXISTS ix_nodes_device_id ON nodes(device_id)")
|
||||
except (OperationalError, IntegrityError) as exc:
|
||||
logger.warning("%s failed: %s", what, exc)
|
||||
finally:
|
||||
await conn.exec_driver_sql("PRAGMA foreign_keys = ON")
|
||||
|
||||
|
||||
async def _drop_legacy_node_columns() -> None:
|
||||
"""Remove the device columns from `nodes` (3.3.0) — SQLite table rebuild.
|
||||
|
||||
Runs only after the backfill has linked every device node to its inventory
|
||||
row. If any non-furniture node is still unlinked the drop is skipped and
|
||||
logged: the columns are the only remaining copy of that node's facts, and
|
||||
losing them is not recoverable. The skip then relaxes their NOT NULL instead,
|
||||
because the 3.3.0 model no longer writes them and the database must stay
|
||||
insertable while the backfill is retried on later boots.
|
||||
"""
|
||||
async with engine.begin() as conn:
|
||||
info = (await conn.exec_driver_sql("PRAGMA table_info(nodes)")).fetchall()
|
||||
present = {row[1] for row in info}
|
||||
if not (present & set(_LEGACY_NODE_COLUMNS)):
|
||||
return # Already migrated.
|
||||
|
||||
unlinked = (
|
||||
await conn.exec_driver_sql(
|
||||
"SELECT COUNT(*) FROM nodes WHERE device_id IS NULL "
|
||||
"AND type NOT IN ('group', 'groupRect', 'text')"
|
||||
)
|
||||
).scalar()
|
||||
if unlinked:
|
||||
logger.warning(
|
||||
"Keeping the legacy node columns: %d node(s) have no inventory row. "
|
||||
"The backfill must link every device node before they can be dropped.",
|
||||
unlinked,
|
||||
)
|
||||
await _relax_legacy_node_columns(conn, list(info))
|
||||
return
|
||||
|
||||
logger.info("Migrating nodes: the device columns move to device_inventory")
|
||||
await _rebuild_nodes(
|
||||
conn,
|
||||
columns_sql=_NODE_COLUMNS_SQL,
|
||||
copied=_NODE_KEPT,
|
||||
what="nodes device-column drop",
|
||||
)
|
||||
|
||||
|
||||
async def _backfill_node_devices() -> None:
|
||||
"""Link existing canvas nodes to their Device Inventory rows (3.3.0).
|
||||
|
||||
Runs outside the DDL connection because the merge is Python-side, not SQL.
|
||||
Self-limiting: it only looks at nodes with no ``device_id``, so a second boot
|
||||
finds nothing to do. Never fatal — a failure here leaves the canvas working
|
||||
off its own columns, which still carry the data at this point.
|
||||
"""
|
||||
# Imported here: app.services imports app.db.models, which imports this module.
|
||||
from app.services.inventory_sync import backfill_node_devices
|
||||
|
||||
try:
|
||||
async with AsyncSessionLocal() as session:
|
||||
stats = await backfill_node_devices(session)
|
||||
if stats["linked"]:
|
||||
await session.commit()
|
||||
logger.info(
|
||||
"Inventory backfill: linked %d node(s) — %d device(s) created, %d merged",
|
||||
stats["linked"], stats["created"], stats["merged"],
|
||||
)
|
||||
if stats.get("skipped"):
|
||||
logger.warning(
|
||||
"Inventory backfill: %d node(s) could not be linked; they keep their "
|
||||
"legacy columns and are retried on the next start.",
|
||||
stats["skipped"],
|
||||
)
|
||||
except Exception as exc: # pragma: no cover - defensive, boot must not die
|
||||
logger.warning("Inventory backfill failed: %s", exc)
|
||||
|
||||
|
||||
async def get_db() -> AsyncGenerator[AsyncSession, None]:
|
||||
|
||||
+144
-24
@@ -28,44 +28,40 @@ class Design(Base):
|
||||
|
||||
|
||||
class Node(Base):
|
||||
"""How a device is drawn on one canvas.
|
||||
|
||||
A node owns presentation only — position, size, colours, icon, handles,
|
||||
nesting. What the device *is* (addresses, services, properties, notes,
|
||||
hardware, check method, live status) belongs to the `device_inventory` row
|
||||
named by `device_id`, so one device reads the same on every canvas. The API
|
||||
still reports both together: see `services/inventory_sync.hydrated_node`.
|
||||
"""
|
||||
|
||||
__tablename__ = "nodes"
|
||||
|
||||
id: Mapped[str] = mapped_column(String, primary_key=True, default=_uuid)
|
||||
type: Mapped[str] = mapped_column(String, nullable=False)
|
||||
label: Mapped[str] = mapped_column(String, nullable=False)
|
||||
design_id: Mapped[str | None] = mapped_column(String, ForeignKey("designs.id", ondelete="SET NULL"), nullable=True)
|
||||
hostname: Mapped[str | None] = mapped_column(String)
|
||||
ip: Mapped[str | None] = mapped_column(String)
|
||||
mac: Mapped[str | None] = mapped_column(String)
|
||||
os: Mapped[str | None] = mapped_column(String)
|
||||
status: Mapped[str] = mapped_column(String, default="unknown")
|
||||
check_method: Mapped[str | None] = mapped_column(String)
|
||||
check_target: Mapped[str | None] = mapped_column(String)
|
||||
services: Mapped[list[Any]] = mapped_column(JSON, default=list)
|
||||
notes: Mapped[str | None] = mapped_column(Text)
|
||||
# The Device Inventory row this node draws. NULL for canvas furniture
|
||||
# (group / groupRect / text), which represents nothing physical. Deleting a
|
||||
# node never deletes the device — the inventory outlives every canvas.
|
||||
device_id: Mapped[str | None] = mapped_column(
|
||||
String, ForeignKey("device_inventory.id", ondelete="SET NULL"), index=True, nullable=True
|
||||
)
|
||||
pos_x: Mapped[float] = mapped_column(Float, default=0)
|
||||
pos_y: Mapped[float] = mapped_column(Float, default=0)
|
||||
parent_id: Mapped[str | None] = mapped_column(String, ForeignKey("nodes.id", ondelete="CASCADE"))
|
||||
container_mode: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
custom_colors: Mapped[dict[str, Any] | None] = mapped_column(JSON, nullable=True)
|
||||
custom_icon: Mapped[str | None] = mapped_column(String, nullable=True)
|
||||
cpu_count: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||
cpu_model: Mapped[str | None] = mapped_column(String, nullable=True)
|
||||
ram_gb: Mapped[float | None] = mapped_column(Float, nullable=True)
|
||||
disk_gb: Mapped[float | None] = mapped_column(Float, nullable=True)
|
||||
show_hardware: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
show_port_numbers: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
properties: Mapped[list[Any]] = mapped_column(JSON, default=list)
|
||||
width: Mapped[float | None] = mapped_column(Float, nullable=True)
|
||||
height: Mapped[float | None] = mapped_column(Float, nullable=True)
|
||||
bottom_handles: Mapped[int] = mapped_column(Integer, default=1)
|
||||
top_handles: Mapped[int] = mapped_column(Integer, default=1)
|
||||
left_handles: Mapped[int] = mapped_column(Integer, default=0)
|
||||
right_handles: Mapped[int] = mapped_column(Integer, default=0)
|
||||
ieee_address: Mapped[str | None] = mapped_column(String, index=True, nullable=True)
|
||||
last_seen: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
||||
last_scan: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
||||
response_time_ms: Mapped[int | None] = mapped_column(Integer)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_now)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_now, onupdate=_now)
|
||||
children: Mapped[list["Node"]] = relationship("Node", back_populates="parent")
|
||||
@@ -105,8 +101,106 @@ class CanvasState(Base):
|
||||
saved_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_now)
|
||||
|
||||
|
||||
class PendingDevice(Base):
|
||||
__tablename__ = "pending_devices"
|
||||
class Rack(Base):
|
||||
"""A physical rack on a `design_type='rack'` canvas.
|
||||
|
||||
Racks live per design, like nodes and edges. Geometry is expressed in rack
|
||||
units: `u_height` is the number of mountable U, and a device's `u_start` is
|
||||
always counted from the bottom rail — `numbering` only changes the printed
|
||||
labels.
|
||||
"""
|
||||
|
||||
__tablename__ = "racks"
|
||||
|
||||
id: Mapped[str] = mapped_column(String, primary_key=True, default=_uuid)
|
||||
design_id: Mapped[str] = mapped_column(String, ForeignKey("designs.id", ondelete="CASCADE"), nullable=False)
|
||||
name: Mapped[str] = mapped_column(String, nullable=False)
|
||||
u_height: Mapped[int] = mapped_column(Integer, default=42)
|
||||
# "19" or "10" (inches). Drives the drawn inner width.
|
||||
width_standard: Mapped[str] = mapped_column(String, default="19")
|
||||
# "bottom-up" or "top-down" — printed U labels only, never storage order.
|
||||
numbering: Mapped[str] = mapped_column(String, default="bottom-up")
|
||||
location: Mapped[str | None] = mapped_column(String, nullable=True)
|
||||
# Frame/rail/interior colours + showNumbers/enclosed flags.
|
||||
style: Mapped[dict[str, Any]] = mapped_column(JSON, default=dict)
|
||||
pos_x: Mapped[float] = mapped_column(Float, default=0)
|
||||
pos_y: Mapped[float] = mapped_column(Float, default=0)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_now)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_now, onupdate=_now)
|
||||
|
||||
|
||||
class RackDevice(Base):
|
||||
"""A piece of gear mounted in a rack.
|
||||
|
||||
Two independent, both-optional links back to the rest of the app:
|
||||
|
||||
* `device_id` — the Device Inventory entry (`device_inventory`). This is the
|
||||
primary link: inventory rows survive approval *and* node deletion, so
|
||||
unracking or deleting a canvas node never removes the inventory entry.
|
||||
* `node_id` — the logical-canvas node, when one exists. Only used to resolve
|
||||
live status and to seed cables from the network design's edges.
|
||||
|
||||
Both are ``SET NULL`` on delete and `label` is denormalized, so a rack keeps
|
||||
rendering after an inventory purge.
|
||||
"""
|
||||
|
||||
__tablename__ = "rack_devices"
|
||||
|
||||
id: Mapped[str] = mapped_column(String, primary_key=True, default=_uuid)
|
||||
design_id: Mapped[str] = mapped_column(String, ForeignKey("designs.id", ondelete="CASCADE"), nullable=False)
|
||||
rack_id: Mapped[str] = mapped_column(String, ForeignKey("racks.id", ondelete="CASCADE"), nullable=False)
|
||||
device_id: Mapped[str | None] = mapped_column(
|
||||
String, ForeignKey("device_inventory.id", ondelete="SET NULL"), nullable=True
|
||||
)
|
||||
node_id: Mapped[str | None] = mapped_column(String, ForeignKey("nodes.id", ondelete="SET NULL"), nullable=True)
|
||||
label: Mapped[str] = mapped_column(String, nullable=False)
|
||||
# 1-based, counted from the bottom rail.
|
||||
u_start: Mapped[int] = mapped_column(Integer, default=1)
|
||||
u_height: Mapped[int] = mapped_column(Integer, default=1)
|
||||
# 12-column horizontal grid: full = 12, half = 6, third = 4, quarter = 3.
|
||||
col_start: Mapped[int] = mapped_column(Integer, default=0)
|
||||
col_span: Mapped[int] = mapped_column(Integer, default=12)
|
||||
faceplate_id: Mapped[str] = mapped_column(String, nullable=False, default="blank-1u")
|
||||
color: Mapped[str | None] = mapped_column(String, nullable=True)
|
||||
status: Mapped[str] = mapped_column(String, default="unknown")
|
||||
# [{id, label, type, x, y}] — positions are unit coordinates on the plate.
|
||||
ports: Mapped[list[Any]] = mapped_column(JSON, default=list)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_now)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_now, onupdate=_now)
|
||||
|
||||
|
||||
class RackCable(Base):
|
||||
"""A patch between two rack device ports.
|
||||
|
||||
Not an `Edge`: rack cables are port-to-port and may cross racks, so they are
|
||||
their own relation rather than a canvas edge.
|
||||
"""
|
||||
|
||||
__tablename__ = "rack_cables"
|
||||
|
||||
id: Mapped[str] = mapped_column(String, primary_key=True, default=_uuid)
|
||||
design_id: Mapped[str] = mapped_column(String, ForeignKey("designs.id", ondelete="CASCADE"), nullable=False)
|
||||
from_device_id: Mapped[str] = mapped_column(
|
||||
String, ForeignKey("rack_devices.id", ondelete="CASCADE"), nullable=False
|
||||
)
|
||||
from_port_id: Mapped[str] = mapped_column(String, nullable=False)
|
||||
to_device_id: Mapped[str] = mapped_column(
|
||||
String, ForeignKey("rack_devices.id", ondelete="CASCADE"), nullable=False
|
||||
)
|
||||
to_port_id: Mapped[str] = mapped_column(String, nullable=False)
|
||||
type: Mapped[str] = mapped_column(String, default="ethernet")
|
||||
color: Mapped[str] = mapped_column(String, default="#39d353")
|
||||
label: Mapped[str | None] = mapped_column(String, nullable=True)
|
||||
# Print the label next to the run on the canvas.
|
||||
label_visible: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
# [{key, value, icon, visible}] — same records nodes carry; the visible ones
|
||||
# are drawn beside the cable.
|
||||
properties: Mapped[list[Any]] = mapped_column(JSON, default=list)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_now)
|
||||
|
||||
|
||||
class InventoryDevice(Base):
|
||||
__tablename__ = "device_inventory"
|
||||
# Permit the plain (non-Mapped[]) annotations on the transient request-only
|
||||
# attributes below; without this SQLAlchemy 2.0 tries to map them as columns.
|
||||
__allow_unmapped__ = True
|
||||
@@ -138,6 +232,32 @@ class PendingDevice(Base):
|
||||
properties: Mapped[list[Any]] = mapped_column(JSON, default=list)
|
||||
discovered_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_now)
|
||||
|
||||
# --- Curated device facts (3.3.0) -------------------------------------
|
||||
# The inventory row, not the canvas node, owns what the device *is*. A node
|
||||
# only says how it is drawn. `label`/`type` supersede friendly_name/
|
||||
# suggested_type for a device that reached a canvas; the older pair is kept
|
||||
# so discovery imports and the source filters keep working unchanged.
|
||||
label: Mapped[str | None] = mapped_column(String, nullable=True)
|
||||
type: Mapped[str | None] = mapped_column(String, nullable=True)
|
||||
notes: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||
cpu_count: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||
cpu_model: Mapped[str | None] = mapped_column(String, nullable=True)
|
||||
ram_gb: Mapped[float | None] = mapped_column(Float, nullable=True)
|
||||
disk_gb: Mapped[float | None] = mapped_column(Float, nullable=True)
|
||||
show_hardware: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
check_method: Mapped[str | None] = mapped_column(String, nullable=True)
|
||||
check_target: Mapped[str | None] = mapped_column(String, nullable=True)
|
||||
# Live reachability from the status checker. NOT `status` — that column holds
|
||||
# the inventory lifecycle (pending/approved/hidden) and the two must not be
|
||||
# conflated.
|
||||
status_live: Mapped[str] = mapped_column(String, default="unknown")
|
||||
last_seen: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||
last_scan: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||
response_time_ms: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), default=_now, onupdate=_now
|
||||
)
|
||||
|
||||
# Transient (not persisted): populated per-request by the scan routes to report
|
||||
# how many canvases this device already appears on. Not a mapped column.
|
||||
canvas_count: int = 0
|
||||
@@ -149,16 +269,16 @@ class PendingDevice(Base):
|
||||
node_last_seen: datetime | None = None
|
||||
|
||||
|
||||
class PendingDeviceLink(Base):
|
||||
class InventoryDeviceLink(Base):
|
||||
"""Link between two Zigbee endpoints discovered during import.
|
||||
|
||||
Endpoints are addressed by IEEE (stable across re-imports). Either side may
|
||||
already exist as a canvas Node (resolved via Node.ieee_address) or still be
|
||||
a PendingDevice. On approval, the matching Edge is auto-created when both
|
||||
a InventoryDevice. On approval, the matching Edge is auto-created when both
|
||||
endpoints exist as canvas Nodes.
|
||||
"""
|
||||
|
||||
__tablename__ = "pending_device_links"
|
||||
__tablename__ = "device_inventory_links"
|
||||
|
||||
id: Mapped[str] = mapped_column(String, primary_key=True, default=_uuid)
|
||||
source_ieee: Mapped[str] = mapped_column(String, nullable=False, index=True)
|
||||
|
||||
+14
-1
@@ -6,6 +6,7 @@ from typing import Any
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from starlette.middleware.sessions import SessionMiddleware
|
||||
|
||||
from app.api.routes import (
|
||||
auth,
|
||||
@@ -16,6 +17,7 @@ from app.api.routes import (
|
||||
media,
|
||||
nodes,
|
||||
proxmox,
|
||||
racks,
|
||||
scan,
|
||||
stats,
|
||||
status,
|
||||
@@ -25,6 +27,7 @@ from app.api.routes import (
|
||||
from app.api.routes import settings as settings_routes
|
||||
from app.core.config import settings
|
||||
from app.core.scheduler import start_scheduler, stop_scheduler
|
||||
from app.core.security import OIDCCSRFMiddleware
|
||||
from app.db.database import init_db
|
||||
|
||||
|
||||
@@ -53,12 +56,21 @@ app = FastAPI(
|
||||
lifespan=lifespan,
|
||||
)
|
||||
|
||||
app.add_middleware(OIDCCSRFMiddleware)
|
||||
app.add_middleware(
|
||||
SessionMiddleware,
|
||||
secret_key=settings.secret_key,
|
||||
session_cookie=("__Host-homelable-oidc-flow" if settings.oidc_cookie_secure else "homelable-oidc-flow"),
|
||||
max_age=settings.oidc_transaction_expire_seconds,
|
||||
same_site="lax",
|
||||
https_only=settings.oidc_cookie_secure,
|
||||
)
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=settings.cors_origins,
|
||||
allow_credentials=True,
|
||||
allow_methods=["GET", "POST", "PUT", "PATCH", "DELETE"],
|
||||
allow_headers=["Authorization", "Content-Type"],
|
||||
allow_headers=["Authorization", "Content-Type", "X-Homelable-CSRF", "X-MCP-Service-Key"],
|
||||
)
|
||||
|
||||
app.include_router(auth.router, prefix="/api/v1/auth", tags=["auth"])
|
||||
@@ -66,6 +78,7 @@ app.include_router(nodes.router, prefix="/api/v1/nodes", tags=["nodes"])
|
||||
app.include_router(edges.router, prefix="/api/v1/edges", tags=["edges"])
|
||||
app.include_router(canvas.router, prefix="/api/v1/canvas", tags=["canvas"])
|
||||
app.include_router(designs.router, prefix="/api/v1/designs", tags=["designs"])
|
||||
app.include_router(racks.router, prefix="/api/v1/racks", tags=["racks"])
|
||||
app.include_router(scan.router, prefix="/api/v1/scan", tags=["scan"])
|
||||
app.include_router(status.router, prefix="/api/v1/status", tags=["status"])
|
||||
app.include_router(settings_routes.router, prefix="/api/v1/settings", tags=["settings"])
|
||||
|
||||
@@ -11,6 +11,17 @@ class NodeSave(BaseModel):
|
||||
id: str
|
||||
type: str
|
||||
label: str
|
||||
# Round-tripped so a save keeps the node pointed at its inventory row. The
|
||||
# device fields below are still accepted at their canvas values and routed
|
||||
# to that row server-side.
|
||||
device_id: str | None = None
|
||||
# Which device facts this canvas edited since it loaded them, if the client
|
||||
# tracked that. The payload always carries a *full* copy of the device — it
|
||||
# was hydrated from the inventory row on load — so without this a save made
|
||||
# for nothing but a moved node would rewrite the row from a snapshot that may
|
||||
# be hours old. `None` (an older client, an import, the MCP server) keeps the
|
||||
# previous behaviour: every fact is a candidate write.
|
||||
changed_facts: list[str] | None = None
|
||||
hostname: str | None = None
|
||||
ip: str | None = None
|
||||
mac: str | None = None
|
||||
@@ -84,3 +95,8 @@ class CanvasStateResponse(BaseModel):
|
||||
edges: list[EdgeResponse]
|
||||
viewport: dict[str, Any]
|
||||
custom_style: dict[str, Any] | None = None
|
||||
# True once this design's canvas has ever been persisted (a CanvasState row
|
||||
# exists). Lets the frontend tell a brand-new user (show demo) apart from one
|
||||
# who intentionally cleared their canvas (keep it empty). False also for a
|
||||
# missing/uninitialized design.
|
||||
initialized: bool = False
|
||||
|
||||
@@ -1,15 +1,27 @@
|
||||
from datetime import datetime
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic import BaseModel, field_validator
|
||||
|
||||
# Kept in sync with DesignType in frontend/src/types.
|
||||
# "network" and "electrical" render the same React Flow canvas and differ only by
|
||||
# palette and node set — the icon drives their presentation. "rack" is a genuinely
|
||||
# different renderer (racks, mounted gear, port-to-port cables), so the frontend
|
||||
# does branch on this field.
|
||||
DESIGN_TYPES = {"network", "electrical", "rack"}
|
||||
|
||||
|
||||
class DesignCreate(BaseModel):
|
||||
name: str
|
||||
icon: str = "dashboard"
|
||||
# Vestigial: kept for backward compatibility. The UI no longer branches on it;
|
||||
# the chosen icon now drives presentation. Defaults to a generic canvas.
|
||||
design_type: str = "network"
|
||||
|
||||
@field_validator("design_type")
|
||||
@classmethod
|
||||
def _known_type(cls, v: str) -> str:
|
||||
if v not in DESIGN_TYPES:
|
||||
raise ValueError(f"design_type must be one of {sorted(DESIGN_TYPES)}")
|
||||
return v
|
||||
|
||||
|
||||
class DesignUpdate(BaseModel):
|
||||
name: str | None = None
|
||||
|
||||
@@ -85,6 +85,10 @@ class NodeUpdate(BaseModel):
|
||||
class NodeResponse(NodeBase):
|
||||
id: str
|
||||
design_id: str | None = None
|
||||
# The Device Inventory row this node draws; None for canvas furniture. The
|
||||
# device fields above are hydrated from that row on read, so the wire shape
|
||||
# is unchanged even though the row, not the node, owns them.
|
||||
device_id: str | None = None
|
||||
ieee_address: str | None = None
|
||||
last_seen: datetime | None = None
|
||||
last_scan: datetime | None = None
|
||||
|
||||
@@ -0,0 +1,302 @@
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
from pydantic import BaseModel, field_validator, model_validator
|
||||
|
||||
# Kept in sync with the frontend rack model (frontend/src/types).
|
||||
WIDTH_STANDARDS = {"19", "10"}
|
||||
NUMBERINGS = {"bottom-up", "top-down"}
|
||||
CABLE_TYPES = {"ethernet", "fiber"}
|
||||
# 12-column horizontal grid: full = 12, half = 6, third = 4, quarter = 3.
|
||||
RACK_COLUMNS = 12
|
||||
|
||||
|
||||
class RackSave(BaseModel):
|
||||
id: str
|
||||
name: str
|
||||
u_height: int = 42
|
||||
width_standard: str = "19"
|
||||
numbering: str = "bottom-up"
|
||||
location: str | None = None
|
||||
style: dict[str, Any] = {}
|
||||
pos_x: float = 0
|
||||
pos_y: float = 0
|
||||
|
||||
@field_validator("u_height")
|
||||
@classmethod
|
||||
def _positive_height(cls, v: int) -> int:
|
||||
if not 1 <= v <= 100:
|
||||
raise ValueError("u_height must be between 1 and 100")
|
||||
return v
|
||||
|
||||
@field_validator("width_standard")
|
||||
@classmethod
|
||||
def _known_width(cls, v: str) -> str:
|
||||
if v not in WIDTH_STANDARDS:
|
||||
raise ValueError(f"width_standard must be one of {sorted(WIDTH_STANDARDS)}")
|
||||
return v
|
||||
|
||||
@field_validator("numbering")
|
||||
@classmethod
|
||||
def _known_numbering(cls, v: str) -> str:
|
||||
if v not in NUMBERINGS:
|
||||
raise ValueError(f"numbering must be one of {sorted(NUMBERINGS)}")
|
||||
return v
|
||||
|
||||
|
||||
class RackDeviceSave(BaseModel):
|
||||
id: str
|
||||
rack_id: str
|
||||
device_id: str | None = None
|
||||
node_id: str | None = None
|
||||
label: str
|
||||
u_start: int = 1
|
||||
u_height: int = 1
|
||||
col_start: int = 0
|
||||
col_span: int = RACK_COLUMNS
|
||||
faceplate_id: str = "blank-1u"
|
||||
color: str | None = None
|
||||
status: str = "unknown"
|
||||
ports: list[Any] = []
|
||||
|
||||
@field_validator("u_start", "u_height")
|
||||
@classmethod
|
||||
def _positive(cls, v: int) -> int:
|
||||
if v < 1:
|
||||
raise ValueError("u_start and u_height are 1-based and must be >= 1")
|
||||
return v
|
||||
|
||||
@field_validator("col_start")
|
||||
@classmethod
|
||||
def _column_in_grid(cls, v: int) -> int:
|
||||
if not 0 <= v < RACK_COLUMNS:
|
||||
raise ValueError(f"col_start must be within the {RACK_COLUMNS}-column grid")
|
||||
return v
|
||||
|
||||
@field_validator("col_span")
|
||||
@classmethod
|
||||
def _span_in_grid(cls, v: int) -> int:
|
||||
if not 1 <= v <= RACK_COLUMNS:
|
||||
raise ValueError(f"col_span must be between 1 and {RACK_COLUMNS}")
|
||||
return v
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _fits_the_column_grid(self) -> "RackDeviceSave":
|
||||
"""`col_start` and `col_span` are legal apart and still illegal together.
|
||||
|
||||
11 + 12 spans to column 23 of a 12-column grid — each field passes its
|
||||
own check, and the frontend serializer clamps them independently, so
|
||||
nothing caught it before this.
|
||||
"""
|
||||
if self.col_start + self.col_span > RACK_COLUMNS:
|
||||
raise ValueError(
|
||||
f"col_start + col_span must not exceed the {RACK_COLUMNS}-column grid"
|
||||
)
|
||||
return self
|
||||
|
||||
|
||||
class RackCableSave(BaseModel):
|
||||
id: str
|
||||
from_device_id: str
|
||||
from_port_id: str
|
||||
to_device_id: str
|
||||
to_port_id: str
|
||||
type: str = "ethernet"
|
||||
color: str = "#39d353"
|
||||
label: str | None = None
|
||||
label_visible: bool = False
|
||||
# [{key, value, icon, visible}] — free-form, same shape as node properties.
|
||||
properties: list[dict[str, Any]] = []
|
||||
|
||||
@field_validator("type")
|
||||
@classmethod
|
||||
def _known_type(cls, v: str) -> str:
|
||||
if v not in CABLE_TYPES:
|
||||
raise ValueError(f"type must be one of {sorted(CABLE_TYPES)}")
|
||||
return v
|
||||
|
||||
@field_validator("properties", mode="before")
|
||||
@classmethod
|
||||
def _clean_properties(cls, v: Any) -> list[dict[str, Any]]:
|
||||
"""Keep only usable records — a property with no key draws an empty badge."""
|
||||
if not isinstance(v, list):
|
||||
return []
|
||||
return [p for p in v if isinstance(p, dict) and str(p.get("key", "")).strip()]
|
||||
|
||||
|
||||
class RackSaveRequest(BaseModel):
|
||||
"""Full rack state for one design — upserted, with anything missing pruned.
|
||||
|
||||
Same contract as ``POST /api/v1/canvas/save``: the client owns the state and
|
||||
sends all of it on an explicit Save.
|
||||
"""
|
||||
|
||||
design_id: str
|
||||
racks: list[RackSave] = []
|
||||
devices: list[RackDeviceSave] = []
|
||||
cables: list[RackCableSave] = []
|
||||
# Pan/zoom, stored on the design's shared CanvasState row like the logical canvas.
|
||||
viewport: dict[str, Any] = {}
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _devices_fit_their_rack(self) -> "RackSaveRequest":
|
||||
"""A mount must fit inside the rack it names.
|
||||
|
||||
`RackDeviceSave` validates each field in isolation and never sees the
|
||||
rack, so `u_start: 40` in a 12U rack passed. A mount above the top rail
|
||||
draws outside the chassis and nothing in the UI can drag it back, so the
|
||||
server refuses to store it. Rack membership itself is checked in the
|
||||
route, which knows what is already persisted.
|
||||
"""
|
||||
heights = {r.id: r.u_height for r in self.racks}
|
||||
for device in self.devices:
|
||||
u_height = heights.get(device.rack_id)
|
||||
if u_height is None:
|
||||
continue # unknown rack — the route reports that with a 400
|
||||
if device.u_start + device.u_height - 1 > u_height:
|
||||
raise ValueError(
|
||||
f"Device {device.id} does not fit in rack {device.rack_id}: "
|
||||
f"U {device.u_start}–{device.u_start + device.u_height - 1} "
|
||||
f"of {u_height}U"
|
||||
)
|
||||
return self
|
||||
|
||||
|
||||
class RackResponse(BaseModel):
|
||||
id: str
|
||||
design_id: str
|
||||
name: str
|
||||
u_height: int
|
||||
width_standard: str
|
||||
numbering: str
|
||||
location: str | None = None
|
||||
style: dict[str, Any] = {}
|
||||
pos_x: float
|
||||
pos_y: float
|
||||
|
||||
@field_validator("style", mode="before")
|
||||
@classmethod
|
||||
def _coerce_style(cls, v: Any) -> dict[str, Any]:
|
||||
return v if isinstance(v, dict) else {}
|
||||
|
||||
model_config = {"from_attributes": True}
|
||||
|
||||
|
||||
class RackDeviceResponse(BaseModel):
|
||||
id: str
|
||||
design_id: str
|
||||
rack_id: str
|
||||
device_id: str | None = None
|
||||
node_id: str | None = None
|
||||
label: str
|
||||
u_start: int
|
||||
u_height: int
|
||||
col_start: int
|
||||
col_span: int
|
||||
faceplate_id: str
|
||||
color: str | None = None
|
||||
status: str
|
||||
ports: list[Any] = []
|
||||
|
||||
@field_validator("ports", mode="before")
|
||||
@classmethod
|
||||
def _coerce_ports(cls, v: Any) -> list[Any]:
|
||||
return v if isinstance(v, list) else []
|
||||
|
||||
model_config = {"from_attributes": True}
|
||||
|
||||
|
||||
class RackCableResponse(BaseModel):
|
||||
id: str
|
||||
design_id: str
|
||||
from_device_id: str
|
||||
from_port_id: str
|
||||
to_device_id: str
|
||||
to_port_id: str
|
||||
type: str
|
||||
color: str
|
||||
label: str | None = None
|
||||
label_visible: bool = False
|
||||
properties: list[dict[str, Any]] = []
|
||||
|
||||
@field_validator("properties", mode="before")
|
||||
@classmethod
|
||||
def _list_properties(cls, v: Any) -> list[dict[str, Any]]:
|
||||
"""Rows written before the column existed read back as NULL."""
|
||||
return v if isinstance(v, list) else []
|
||||
|
||||
@field_validator("label_visible", mode="before")
|
||||
@classmethod
|
||||
def _bool_label_visible(cls, v: Any) -> bool:
|
||||
return bool(v)
|
||||
|
||||
model_config = {"from_attributes": True}
|
||||
|
||||
|
||||
class RackStateResponse(BaseModel):
|
||||
racks: list[RackResponse]
|
||||
devices: list[RackDeviceResponse]
|
||||
cables: list[RackCableResponse]
|
||||
viewport: dict[str, Any] = {}
|
||||
|
||||
|
||||
class RackServiceInfo(BaseModel):
|
||||
"""One service fingerprinted on a device, as the rack view prints it."""
|
||||
|
||||
port: int | None = None
|
||||
name: str | None = None
|
||||
|
||||
|
||||
class RackInventoryItem(BaseModel):
|
||||
"""A Device Inventory entry offered to the rack tray.
|
||||
|
||||
Carries the technical facts the logical canvas already knows about the same
|
||||
hardware (`node_*`), so a mount can print them without the user leaving the
|
||||
rack. Everything node-side is read-only here: the logical canvas owns it.
|
||||
"""
|
||||
|
||||
id: str
|
||||
label: str
|
||||
suggested_type: str | None = None
|
||||
ip: str | None = None
|
||||
status: str
|
||||
discovery_source: str | None = None
|
||||
# Inventory-side technical detail, from discovery.
|
||||
mac: str | None = None
|
||||
hostname: str | None = None
|
||||
os: str | None = None
|
||||
services: list[RackServiceInfo] = []
|
||||
# Live status of the matching canvas node, when the device is on one.
|
||||
node_id: str | None = None
|
||||
node_status: str | None = None
|
||||
# What that node holds — the logical view of the same box.
|
||||
node_label: str | None = None
|
||||
node_type: str | None = None
|
||||
node_ip: str | None = None
|
||||
node_mac: str | None = None
|
||||
node_hostname: str | None = None
|
||||
node_os: str | None = None
|
||||
node_check_method: str | None = None
|
||||
node_design_id: str | None = None
|
||||
node_design_name: str | None = None
|
||||
node_last_seen: datetime | None = None
|
||||
# True when this device is already mounted somewhere in this design.
|
||||
racked: bool = False
|
||||
|
||||
@field_validator("node_last_seen")
|
||||
@classmethod
|
||||
def _utc(cls, v: datetime | None) -> datetime | None:
|
||||
"""Stamp UTC on a naive timestamp before it goes on the wire.
|
||||
|
||||
SQLite has no timezone type: an aware datetime written to `last_seen`
|
||||
reads back naive, and Pydantic then serializes it without an offset.
|
||||
`new Date("2026-08-08T10:00:00")` in the browser is *local* time, so the
|
||||
rack printed a last-seen shifted by the viewer's offset.
|
||||
"""
|
||||
if v is not None and v.tzinfo is None:
|
||||
return v.replace(tzinfo=timezone.utc)
|
||||
return v
|
||||
|
||||
|
||||
class RackInventoryResponse(BaseModel):
|
||||
items: list[RackInventoryItem]
|
||||
+116
-2
@@ -4,7 +4,7 @@ from typing import Any
|
||||
from pydantic import BaseModel, field_validator
|
||||
|
||||
|
||||
class PendingDeviceResponse(BaseModel):
|
||||
class InventoryDeviceResponse(BaseModel):
|
||||
id: str
|
||||
ip: str | None
|
||||
mac: str | None
|
||||
@@ -27,6 +27,26 @@ class PendingDeviceResponse(BaseModel):
|
||||
# the node on approve; empty for scan/mesh sources that don't set them.
|
||||
properties: list[Any] = []
|
||||
discovered_at: datetime
|
||||
# Curated device facts (3.3.0). `label`/`type` supersede friendly_name/
|
||||
# suggested_type once the user has named the device; the older pair stays for
|
||||
# discovery imports and the source filters.
|
||||
label: str | None = None
|
||||
type: str | None = None
|
||||
notes: str | None = None
|
||||
cpu_count: int | None = None
|
||||
cpu_model: str | None = None
|
||||
ram_gb: float | None = None
|
||||
disk_gb: float | None = None
|
||||
show_hardware: bool = False
|
||||
check_method: str | None = None
|
||||
check_target: str | None = None
|
||||
# Live reachability, distinct from `status` (the pending/approved/hidden
|
||||
# lifecycle).
|
||||
status_live: str = "unknown"
|
||||
last_seen: datetime | None = None
|
||||
last_scan: datetime | None = None
|
||||
response_time_ms: int | None = None
|
||||
updated_at: datetime | None = None
|
||||
# Number of distinct canvases (designs) this device already appears on,
|
||||
# correlated by ip / ieee_address against existing nodes. Computed per-request.
|
||||
canvas_count: int = 0
|
||||
@@ -38,15 +58,109 @@ class PendingDeviceResponse(BaseModel):
|
||||
node_last_modified: datetime | None = None
|
||||
node_last_seen: datetime | None = None
|
||||
|
||||
@field_validator("properties", "discovery_sources", mode="before")
|
||||
@field_validator("properties", "discovery_sources", "services", mode="before")
|
||||
@classmethod
|
||||
def _coerce_list(cls, v: Any) -> list[Any]:
|
||||
# Legacy rows (columns added by migration) have these = NULL.
|
||||
return v if isinstance(v, list) else []
|
||||
|
||||
@field_validator("status_live", mode="before")
|
||||
@classmethod
|
||||
def _coerce_status_live(cls, v: Any) -> str:
|
||||
return v if isinstance(v, str) and v else "unknown"
|
||||
|
||||
@field_validator("show_hardware", mode="before")
|
||||
@classmethod
|
||||
def _coerce_show_hardware(cls, v: Any) -> bool:
|
||||
return bool(v)
|
||||
|
||||
model_config = {"from_attributes": True}
|
||||
|
||||
|
||||
"""Sources a hand-made inventory entry may claim.
|
||||
|
||||
``rack`` marks gear created from a rack canvas. Those rows live in the Device
|
||||
Inventory like any other, but they describe a physical mount rather than a host
|
||||
on the network, so they are never placed on a logical canvas.
|
||||
"""
|
||||
MANUAL_SOURCES = {"manual", "rack"}
|
||||
|
||||
|
||||
class InventoryDeviceCreate(BaseModel):
|
||||
"""Manually add an entry to the Device Inventory.
|
||||
|
||||
Used when the user documents hardware no scan can find — a dumb switch, a
|
||||
patch panel, a machine that is powered off. Lands with
|
||||
`discovery_source="manual"` (or `"rack"`) so the inventory filters can tell
|
||||
it apart.
|
||||
"""
|
||||
|
||||
hostname: str
|
||||
ip: str | None = None
|
||||
mac: str | None = None
|
||||
suggested_type: str | None = None
|
||||
model: str | None = None
|
||||
vendor: str | None = None
|
||||
properties: list[Any] = []
|
||||
discovery_source: str = "manual"
|
||||
# Curated fields, so a hand-made entry can carry everything the edit modal
|
||||
# shows rather than needing a create-then-PATCH round trip.
|
||||
os: str | None = None
|
||||
services: list[Any] = []
|
||||
friendly_name: str | None = None
|
||||
device_subtype: str | None = None
|
||||
label: str | None = None
|
||||
type: str | None = None
|
||||
notes: str | None = None
|
||||
cpu_count: int | None = None
|
||||
cpu_model: str | None = None
|
||||
ram_gb: float | None = None
|
||||
disk_gb: float | None = None
|
||||
show_hardware: bool = False
|
||||
check_method: str | None = None
|
||||
check_target: str | None = None
|
||||
|
||||
@field_validator("discovery_source")
|
||||
@classmethod
|
||||
def _known_source(cls, v: str) -> str:
|
||||
if v not in MANUAL_SOURCES:
|
||||
raise ValueError(f"discovery_source must be one of {sorted(MANUAL_SOURCES)}")
|
||||
return v
|
||||
|
||||
|
||||
class InventoryDeviceUpdate(BaseModel):
|
||||
"""Partial edit of an inventory row — the write half of the detail modal.
|
||||
|
||||
Every field is optional and only what the client sends is applied
|
||||
(`exclude_unset`), so a caller editing one field never clears the rest.
|
||||
Lifecycle (`status`) and discovery bookkeeping (`discovery_source(s)`,
|
||||
`discovered_at`, `ieee_address`) are deliberately not editable here: those
|
||||
are owned by the approve/hide routes and the importers.
|
||||
"""
|
||||
|
||||
ip: str | None = None
|
||||
mac: str | None = None
|
||||
hostname: str | None = None
|
||||
os: str | None = None
|
||||
label: str | None = None
|
||||
type: str | None = None
|
||||
suggested_type: str | None = None
|
||||
friendly_name: str | None = None
|
||||
device_subtype: str | None = None
|
||||
model: str | None = None
|
||||
vendor: str | None = None
|
||||
services: list[Any] | None = None
|
||||
properties: list[Any] | None = None
|
||||
notes: str | None = None
|
||||
cpu_count: int | None = None
|
||||
cpu_model: str | None = None
|
||||
ram_gb: float | None = None
|
||||
disk_gb: float | None = None
|
||||
show_hardware: bool | None = None
|
||||
check_method: str | None = None
|
||||
check_target: str | None = None
|
||||
|
||||
|
||||
class ScanRunResponse(BaseModel):
|
||||
id: str
|
||||
status: str
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Helpers for the multi-valued ``PendingDevice.discovery_sources`` set.
|
||||
"""Helpers for the multi-valued ``InventoryDevice.discovery_sources`` set.
|
||||
|
||||
A device discovered by more than one path (e.g. an IP scan *and* a Proxmox
|
||||
import) accumulates every source that has seen it, so it surfaces under each
|
||||
|
||||
@@ -213,12 +213,16 @@ def suggest_node_type(open_ports: list[dict[str, Any]], mac: str | None = None)
|
||||
if mac_type == "iot":
|
||||
return "iot"
|
||||
|
||||
priority = ["proxmox", "nas", "router", "lxc", "vm", "ap", "camera", "iot", "server", "switch"]
|
||||
priority = [
|
||||
"proxmox", "nas", "kvm", "router", "lxc", "vm", "ap", "camera", "iot", "server", "switch",
|
||||
]
|
||||
found: set[str] = set()
|
||||
for p in open_ports:
|
||||
port = p["port"]
|
||||
proto = p.get("protocol", "tcp")
|
||||
sig = match_port(port, proto)
|
||||
# Pass the HTTP-probe signals through: port-agnostic signatures (port: null,
|
||||
# e.g. PiKVM, Unraid) match on title/headers alone and are invisible otherwise.
|
||||
sig = match_service(port, proto, p.get("banner"), p.get("http_signals"))
|
||||
if sig and sig.get("suggested_node_type"):
|
||||
found.add(sig["suggested_node_type"])
|
||||
if port in _PORT_TYPE_HINTS:
|
||||
|
||||
@@ -0,0 +1,631 @@
|
||||
"""Keep a canvas :class:`Node` and its Device Inventory row in step.
|
||||
|
||||
The inventory row owns what a device *is* — addresses, services, properties,
|
||||
notes, hardware, check method. A node owns only how that device is drawn on one
|
||||
canvas. This module holds the matching and merging rules shared by:
|
||||
|
||||
* the one-off backfill that links pre-3.3.0 nodes to inventory rows,
|
||||
* the approve / node-create paths, which link instead of copying,
|
||||
* the canvas save write-through, which pushes a node edit back to the row.
|
||||
|
||||
Nothing here commits — the caller owns the transaction.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
from collections.abc import Mapping
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import func, or_, select, text
|
||||
from sqlalchemy.exc import IntegrityError, OperationalError
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.db.models import InventoryDevice, Node
|
||||
from app.services.discovery_sources import add_source
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Canvas furniture: annotations, not hardware. These never get an inventory row.
|
||||
FURNITURE_TYPES = frozenset({"group", "groupRect", "text"})
|
||||
|
||||
# Source tag for a device that only ever existed as a canvas node — the backfill
|
||||
# mints its inventory row.
|
||||
CANVAS_SOURCE = "canvas"
|
||||
|
||||
# Scalar facts the inventory row owns. Order matters only for readability.
|
||||
DEVICE_SCALARS = (
|
||||
"hostname",
|
||||
"ip",
|
||||
"mac",
|
||||
"os",
|
||||
"notes",
|
||||
"cpu_count",
|
||||
"cpu_model",
|
||||
"ram_gb",
|
||||
"disk_gb",
|
||||
"check_method",
|
||||
"check_target",
|
||||
)
|
||||
|
||||
|
||||
def is_furniture(node_type: str | None) -> bool:
|
||||
return (node_type or "") in FURNITURE_TYPES
|
||||
|
||||
|
||||
def _ip_tokens(ip: str | None) -> list[str]:
|
||||
"""Split an ``ip`` field into individual addresses.
|
||||
|
||||
A node or device may carry several comma-separated addresses, so identity
|
||||
matching compares per token — same rule as ``node_dedupe._ip_tokens``.
|
||||
"""
|
||||
return [t.strip() for t in ip.split(",") if t.strip()] if ip else []
|
||||
|
||||
|
||||
def _blank(value: Any) -> bool:
|
||||
return value is None or value == ""
|
||||
|
||||
|
||||
def _same_ieee(left: str | None, right: str | None) -> bool:
|
||||
"""IEEE addresses compare case-insensitively — the same radio either way."""
|
||||
if _blank(left) or _blank(right):
|
||||
return False
|
||||
return str(left).lower() == str(right).lower()
|
||||
|
||||
|
||||
async def _ieee_owner(db: AsyncSession, ieee: str, *, other_than: str | None) -> InventoryDevice | None:
|
||||
"""The row already holding ``ieee``, if it is not ``other_than``.
|
||||
|
||||
``device_inventory.ieee_address`` is UNIQUE, so writing an address a second
|
||||
row owns raises. Callers ask first and leave the address where it is.
|
||||
"""
|
||||
stmt = select(InventoryDevice).where(func.lower(InventoryDevice.ieee_address) == ieee.lower())
|
||||
if other_than is not None:
|
||||
# `id != NULL` is NULL in SQL and would match nothing — only narrow when
|
||||
# there is a row to exclude.
|
||||
stmt = stmt.where(InventoryDevice.id != other_than)
|
||||
return (await db.execute(stmt)).scalars().first()
|
||||
|
||||
|
||||
async def _drop_taken_ieee(
|
||||
db: AsyncSession, facts: Mapping[str, Any], device: InventoryDevice | None
|
||||
) -> Mapping[str, Any]:
|
||||
"""``facts`` without an ``ieee_address`` another inventory row already owns.
|
||||
|
||||
Returned unchanged in the common case. The column is UNIQUE, so writing a
|
||||
duplicate raises mid-merge — and during the backfill that would cost the node
|
||||
its link. The address belongs to whichever row holds it; identity for *this*
|
||||
device was established by ip or mac.
|
||||
"""
|
||||
ieee = facts.get("ieee_address")
|
||||
if _blank(ieee) or (device is not None and _same_ieee(device.ieee_address, ieee)):
|
||||
return facts
|
||||
owner = await _ieee_owner(db, str(ieee), other_than=device.id if device else None)
|
||||
if owner is None:
|
||||
return facts
|
||||
logger.warning(
|
||||
"IEEE %s is already held by device %s — leaving it off %s",
|
||||
ieee, owner.id, device.id if device else "the new row",
|
||||
)
|
||||
return {k: v for k, v in facts.items() if k != "ieee_address"}
|
||||
|
||||
|
||||
async def find_device_for(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
ip: str | None,
|
||||
mac: str | None,
|
||||
ieee: str | None,
|
||||
) -> InventoryDevice | None:
|
||||
"""Find the inventory row describing this host, or ``None``.
|
||||
|
||||
Precedence is ieee > ip > mac, matching ``find_duplicate_node`` and the
|
||||
bulk-approve skip order so a device is identified the same way everywhere.
|
||||
Hidden rows are eligible: a hidden device is still that device, and silently
|
||||
minting a second row for it would resurrect the duplicate the user hid.
|
||||
"""
|
||||
ip_toks = _ip_tokens(ip)
|
||||
conds = []
|
||||
if ieee:
|
||||
# Case-insensitive: `0x00124B00…` and `0x00124b00…` are the same radio,
|
||||
# and an exact comparison here would mint a second row for it — one the
|
||||
# UNIQUE index then refuses.
|
||||
conds.append(func.lower(InventoryDevice.ieee_address) == ieee.lower())
|
||||
for tok in ip_toks:
|
||||
# Narrow with a substring match, then confirm per token below — an exact
|
||||
# comparison misses rows holding several addresses.
|
||||
conds.append(InventoryDevice.ip.contains(tok))
|
||||
if mac:
|
||||
conds.append(InventoryDevice.mac == mac)
|
||||
if not conds:
|
||||
return None
|
||||
|
||||
candidates = (
|
||||
await db.execute(select(InventoryDevice).where(or_(*conds)).order_by(InventoryDevice.discovered_at))
|
||||
).scalars().all()
|
||||
|
||||
for device in candidates:
|
||||
if ieee and _same_ieee(device.ieee_address, ieee):
|
||||
return device
|
||||
for device in candidates:
|
||||
# "1.2.3.4" must not match "1.2.3.40" — confirm the token, don't trust
|
||||
# the SQL `contains`.
|
||||
if ip_toks and set(_ip_tokens(device.ip)) & set(ip_toks):
|
||||
return device
|
||||
for device in candidates:
|
||||
if mac and device.mac == mac:
|
||||
return device
|
||||
return None
|
||||
|
||||
|
||||
def merge_properties(base: list[Any] | None, incoming: list[Any] | None) -> list[Any]:
|
||||
"""Union two property lists on ``key`` (case-insensitive); incoming wins.
|
||||
|
||||
Order-stable: existing keys keep their position, new ones are appended, so a
|
||||
user's arrangement survives a merge.
|
||||
"""
|
||||
out: list[Any] = [dict(p) if isinstance(p, dict) else p for p in (base or [])]
|
||||
index: dict[str, int] = {}
|
||||
for i, prop in enumerate(out):
|
||||
if isinstance(prop, dict) and prop.get("key") is not None:
|
||||
index[str(prop["key"]).lower()] = i
|
||||
|
||||
for prop in incoming or []:
|
||||
if not isinstance(prop, dict) or prop.get("key") is None:
|
||||
if prop not in out:
|
||||
out.append(prop)
|
||||
continue
|
||||
key = str(prop["key"]).lower()
|
||||
pos = index.get(key)
|
||||
if pos is None:
|
||||
out.append(dict(prop))
|
||||
index[key] = len(out) - 1
|
||||
continue
|
||||
current = out[pos]
|
||||
if not isinstance(current, dict):
|
||||
out[pos] = dict(prop)
|
||||
continue
|
||||
merged = {**current, **{k: v for k, v in prop.items() if not _blank(v)}}
|
||||
# Keys match case-insensitively but the display spelling is the user's —
|
||||
# "rack" arriving must not rewrite their "Rack".
|
||||
merged["key"] = current.get("key", prop["key"])
|
||||
# `visible` is a real False, not an empty value — carry it explicitly.
|
||||
if "visible" in prop:
|
||||
merged["visible"] = prop["visible"]
|
||||
out[pos] = merged
|
||||
return out
|
||||
|
||||
|
||||
def _service_key(svc: Any) -> Any:
|
||||
if not isinstance(svc, dict):
|
||||
return repr(svc)
|
||||
return (svc.get("port"), svc.get("protocol"), (svc.get("service_name") or "").lower())
|
||||
|
||||
|
||||
def merge_services(base: list[Any] | None, incoming: list[Any] | None) -> list[Any]:
|
||||
"""Union two service lists on (port, protocol, name); incoming wins."""
|
||||
out: list[Any] = [dict(s) if isinstance(s, dict) else s for s in (base or [])]
|
||||
index = {_service_key(s): i for i, s in enumerate(out)}
|
||||
for svc in incoming or []:
|
||||
key = _service_key(svc)
|
||||
pos = index.get(key)
|
||||
if pos is None:
|
||||
out.append(dict(svc) if isinstance(svc, dict) else svc)
|
||||
index[key] = len(out) - 1
|
||||
elif isinstance(svc, dict) and isinstance(out[pos], dict):
|
||||
out[pos] = {**out[pos], **svc}
|
||||
else:
|
||||
out[pos] = svc
|
||||
return out
|
||||
|
||||
|
||||
# Observations rather than edits: the checker and the scanner write these, so a
|
||||
# client never lists them as changed and they survive a `changed_fields` filter.
|
||||
_LIVE_FACT_FIELDS = frozenset({"status", "last_seen", "last_scan", "response_time_ms"})
|
||||
|
||||
|
||||
def changed_facts(device: InventoryDevice, facts: Mapping[str, Any]) -> dict[str, Any]:
|
||||
"""The subset of ``facts`` that actually differs from the row.
|
||||
|
||||
A canvas save sends a *full* copy of the device — the facts were hydrated
|
||||
into the node when the canvas loaded — so a save triggered by nothing but a
|
||||
node being dragged would otherwise rewrite the row from a snapshot that may
|
||||
be minutes or hours old, silently reverting an edit made meanwhile in the
|
||||
inventory modal, on another canvas, or by the scanner. Narrowing to what the
|
||||
sender changed turns the write-through from "push my whole snapshot" into
|
||||
"push my edit", so two writers only collide on the same field.
|
||||
|
||||
The comparison mirrors :func:`merge_facts_into_device`: a blank incoming
|
||||
value is not a change (it never clears an established one), and a list
|
||||
counts as changed only when it would actually be replaced by a different
|
||||
one. Ambiguity is resolved toward reporting a change — a false positive is
|
||||
the old behaviour for that field, a false negative would drop a real edit.
|
||||
"""
|
||||
out: dict[str, Any] = {}
|
||||
for field in (*DEVICE_SCALARS, "label", "type"):
|
||||
incoming = facts.get(field)
|
||||
if _blank(incoming) or incoming == getattr(device, field, None):
|
||||
continue
|
||||
out[field] = incoming
|
||||
|
||||
if not _blank(facts.get("ieee_address")) and _blank(device.ieee_address):
|
||||
out["ieee_address"] = facts["ieee_address"]
|
||||
if facts.get("show_hardware") and not device.show_hardware:
|
||||
out["show_hardware"] = facts["show_hardware"]
|
||||
|
||||
if "properties" in facts and list(facts["properties"] or []) != list(device.properties or []):
|
||||
out["properties"] = facts["properties"]
|
||||
if "services" in facts and list(facts["services"] or []) != list(device.services or []):
|
||||
out["services"] = facts["services"]
|
||||
|
||||
# Live observations, not edits: carried through only where the merge would
|
||||
# have used them — filling a row that has never been checked.
|
||||
if facts.get("status") and device.status_live in (None, "", "unknown"):
|
||||
out["status"] = facts["status"]
|
||||
for field in ("last_seen", "last_scan", "response_time_ms"):
|
||||
if facts.get(field) is not None:
|
||||
out[field] = facts[field]
|
||||
return out
|
||||
|
||||
|
||||
def merge_facts_into_device(
|
||||
device: InventoryDevice,
|
||||
facts: Mapping[str, Any],
|
||||
*,
|
||||
overwrite_scalars: bool,
|
||||
replace_lists: bool,
|
||||
) -> None:
|
||||
"""Fold one view of a device into its inventory row, in place.
|
||||
|
||||
``facts`` is a plain mapping — what a canvas save sent, or what a legacy
|
||||
node's columns held — so this rule lives in one place regardless of where
|
||||
the view came from.
|
||||
|
||||
Two independent knobs, because the callers need three combinations:
|
||||
|
||||
* ``overwrite_scalars`` — a non-blank incoming value replaces the row's.
|
||||
True for the backfill (nodes are visited oldest-edit-first, so the most
|
||||
recently edited canvas is the last writer and wins) and for a user's save.
|
||||
False on approve, where the row was just discovered and the node is only a
|
||||
placement. A blank *never* clears an established value in either mode.
|
||||
* ``replace_lists`` — properties/services are taken wholesale rather than
|
||||
unioned. True only for a user's save: otherwise a property they deleted
|
||||
would come straight back on the next one. The backfill unions, so nothing
|
||||
any canvas recorded is lost. It applies list by list: a list absent from
|
||||
``facts`` is left alone even in replace mode, so a partial update never
|
||||
clears the one it did not send.
|
||||
"""
|
||||
for field in (*DEVICE_SCALARS, "label", "type"):
|
||||
incoming = facts.get(field)
|
||||
if _blank(incoming):
|
||||
continue
|
||||
if overwrite_scalars or _blank(getattr(device, field, None)):
|
||||
setattr(device, field, incoming)
|
||||
|
||||
if not _blank(facts.get("ieee_address")) and _blank(device.ieee_address):
|
||||
# Identity, never overwritten — two IEEEs mean two devices.
|
||||
device.ieee_address = facts["ieee_address"]
|
||||
if facts.get("show_hardware") and not device.show_hardware:
|
||||
device.show_hardware = True
|
||||
|
||||
# Per list, and only for one the caller actually sent: a partial update
|
||||
# carrying properties alone must leave services as they were, not blank them.
|
||||
if replace_lists and "properties" in facts:
|
||||
device.properties = list(facts["properties"] or [])
|
||||
else:
|
||||
device.properties = merge_properties(device.properties, facts.get("properties"))
|
||||
if replace_lists and "services" in facts:
|
||||
device.services = list(facts["services"] or [])
|
||||
else:
|
||||
device.services = merge_services(device.services, facts.get("services"))
|
||||
|
||||
# Live status: keep the freshest observation rather than the last writer.
|
||||
last_seen, status, last_scan = facts.get("last_seen"), facts.get("status"), facts.get("last_scan")
|
||||
if last_seen and (device.last_seen is None or last_seen > device.last_seen):
|
||||
device.last_seen = last_seen
|
||||
device.status_live = status or device.status_live
|
||||
device.response_time_ms = facts.get("response_time_ms")
|
||||
elif device.status_live in (None, "", "unknown") and status:
|
||||
device.status_live = status
|
||||
if last_scan and (device.last_scan is None or last_scan > device.last_scan):
|
||||
device.last_scan = last_scan
|
||||
|
||||
|
||||
def device_from_facts(facts: Mapping[str, Any]) -> InventoryDevice:
|
||||
"""Mint the inventory row for a device that has none.
|
||||
|
||||
Tagged ``canvas`` so the inventory filters can tell hand-drawn gear apart
|
||||
from anything a scan or import found.
|
||||
"""
|
||||
return InventoryDevice(
|
||||
label=facts.get("label"),
|
||||
type=facts.get("type"),
|
||||
hostname=facts.get("hostname"),
|
||||
ip=facts.get("ip"),
|
||||
mac=facts.get("mac"),
|
||||
os=facts.get("os"),
|
||||
ieee_address=facts.get("ieee_address"),
|
||||
services=list(facts.get("services") or []),
|
||||
properties=list(facts.get("properties") or []),
|
||||
notes=facts.get("notes"),
|
||||
cpu_count=facts.get("cpu_count"),
|
||||
cpu_model=facts.get("cpu_model"),
|
||||
ram_gb=facts.get("ram_gb"),
|
||||
disk_gb=facts.get("disk_gb"),
|
||||
show_hardware=bool(facts.get("show_hardware")),
|
||||
check_method=facts.get("check_method"),
|
||||
check_target=facts.get("check_target"),
|
||||
suggested_type=facts.get("type"),
|
||||
friendly_name=facts.get("label"),
|
||||
# On a canvas already, so it is past the pending queue.
|
||||
status="approved",
|
||||
status_live=facts.get("status") or "unknown",
|
||||
last_seen=facts.get("last_seen"),
|
||||
last_scan=facts.get("last_scan"),
|
||||
response_time_ms=facts.get("response_time_ms"),
|
||||
discovery_source=CANVAS_SOURCE,
|
||||
discovery_sources=[CANVAS_SOURCE],
|
||||
)
|
||||
|
||||
|
||||
async def link_facts(
|
||||
db: AsyncSession,
|
||||
node: Node,
|
||||
facts: Mapping[str, Any],
|
||||
*,
|
||||
overwrite_scalars: bool = False,
|
||||
replace_lists: bool = False,
|
||||
only_changed: bool = False,
|
||||
changed_fields: list[str] | None = None,
|
||||
) -> InventoryDevice | None:
|
||||
"""Point one node at its inventory row, creating or merging as needed.
|
||||
|
||||
``facts`` is this node's view of the device — the fields a canvas save sent,
|
||||
or a legacy node's columns during the backfill. Returns the row, or ``None``
|
||||
for canvas furniture. Flushes so a freshly minted row has an id to link to,
|
||||
but does not commit.
|
||||
|
||||
Two narrowings turn a save from "push my whole snapshot" into "push my edit",
|
||||
and they compose. Identity matching always uses the full ``facts`` — the row
|
||||
has to be found before it can be narrowed against.
|
||||
|
||||
* ``changed_fields`` — what the sender says it edited since it loaded the
|
||||
device. Authoritative: a fact absent from the list is not written even when
|
||||
it differs, because the difference means the *row* moved on, not the sender.
|
||||
* ``only_changed`` — drop facts already equal to the row (see
|
||||
:func:`changed_facts`), so a no-op save writes nothing at all.
|
||||
"""
|
||||
if is_furniture(node.type):
|
||||
node.device_id = None
|
||||
return None
|
||||
|
||||
device = None
|
||||
if node.device_id:
|
||||
device = await db.get(InventoryDevice, node.device_id)
|
||||
if device is None:
|
||||
device = await find_device_for(
|
||||
db, ip=facts.get("ip"), mac=facts.get("mac"), ieee=facts.get("ieee_address")
|
||||
)
|
||||
|
||||
# The IEEE is UNIQUE across the inventory. Where another row already owns the
|
||||
# one these facts carry, drop it rather than write a duplicate: identity has
|
||||
# been resolved to *this* device by ip or mac, and the address stays with the
|
||||
# row holding it.
|
||||
facts = await _drop_taken_ieee(db, facts, device)
|
||||
|
||||
if device is None:
|
||||
device = device_from_facts(facts)
|
||||
db.add(device)
|
||||
await db.flush()
|
||||
else:
|
||||
merged = dict(facts)
|
||||
if changed_fields is not None:
|
||||
keep = set(changed_fields) | _LIVE_FACT_FIELDS
|
||||
merged = {k: v for k, v in merged.items() if k in keep}
|
||||
if only_changed:
|
||||
merged = changed_facts(device, merged)
|
||||
merge_facts_into_device(
|
||||
device,
|
||||
merged,
|
||||
overwrite_scalars=overwrite_scalars,
|
||||
replace_lists=replace_lists,
|
||||
)
|
||||
device.discovery_sources = add_source(device.discovery_sources, CANVAS_SOURCE)
|
||||
|
||||
node.device_id = device.id
|
||||
return device
|
||||
|
||||
|
||||
def node_columns(payload: Mapping[str, Any]) -> dict[str, Any]:
|
||||
"""The subset of a node payload that is still a `nodes` column.
|
||||
|
||||
The wire shape carries the device facts flat on the node; they belong to the
|
||||
inventory row now, so they are dropped here and applied through
|
||||
:func:`link_facts` instead.
|
||||
"""
|
||||
allowed = {c.name for c in Node.__table__.columns}
|
||||
return {k: v for k, v in payload.items() if k in allowed}
|
||||
|
||||
|
||||
# Fields that are both a node column and a device fact: the node keeps a copy so
|
||||
# a half-migrated database still renders, but the row is the truth.
|
||||
_SHARED_FIELDS = ("label", "type")
|
||||
|
||||
# Everything the inventory row owns, as it appears in a node payload.
|
||||
DEVICE_FACT_FIELDS = (
|
||||
*DEVICE_SCALARS, "services", "properties", "show_hardware", "status", *_SHARED_FIELDS,
|
||||
)
|
||||
|
||||
|
||||
def facts_from_update(sent: Mapping[str, Any]) -> dict[str, Any]:
|
||||
"""The device facts inside a partial node update — only what was sent.
|
||||
|
||||
An omitted field must not clear the row, so unsent keys are simply absent.
|
||||
"""
|
||||
return {k: v for k, v in sent.items() if k in DEVICE_FACT_FIELDS}
|
||||
|
||||
|
||||
def facts_from_payload(payload: Mapping[str, Any], *, label: str, node_type: str) -> dict[str, Any]:
|
||||
"""The device facts inside a node save/create payload.
|
||||
|
||||
The wire shape still carries them flat on the node, so this is where they
|
||||
are separated from the presentation fields the node itself keeps.
|
||||
"""
|
||||
facts: dict[str, Any] = {
|
||||
field: payload.get(field)
|
||||
for field in (*DEVICE_SCALARS, "services", "properties", "show_hardware", "status")
|
||||
}
|
||||
facts["label"] = label
|
||||
facts["type"] = node_type
|
||||
return facts
|
||||
|
||||
|
||||
async def load_devices_for(db: AsyncSession, nodes: list[Node]) -> dict[str, InventoryDevice]:
|
||||
"""Fetch the inventory rows a batch of nodes points at, keyed by device id."""
|
||||
ids = {n.device_id for n in nodes if n.device_id}
|
||||
if not ids:
|
||||
return {}
|
||||
rows = (
|
||||
await db.execute(select(InventoryDevice).where(InventoryDevice.id.in_(ids)))
|
||||
).scalars().all()
|
||||
return {d.id: d for d in rows}
|
||||
|
||||
|
||||
def hydrated_node(node: Node, device: InventoryDevice | None) -> dict[str, Any]:
|
||||
"""A node as the API reports it: presentation from the node, facts from the row.
|
||||
|
||||
The device fields stay on the wire exactly where they have always been, so
|
||||
every reader — the canvas, the live view, the MCP server — is unaffected by
|
||||
the split. Canvas furniture has no row and simply reports the defaults.
|
||||
"""
|
||||
payload: dict[str, Any] = {
|
||||
c.name: getattr(node, c.name) for c in node.__table__.columns
|
||||
}
|
||||
if device is None:
|
||||
return payload
|
||||
|
||||
for field in DEVICE_SCALARS:
|
||||
payload[field] = getattr(device, field, None)
|
||||
payload["label"] = device.label or node.label
|
||||
payload["type"] = device.type or node.type
|
||||
payload["services"] = device.services or []
|
||||
payload["properties"] = device.properties or []
|
||||
payload["show_hardware"] = bool(device.show_hardware)
|
||||
payload["ieee_address"] = device.ieee_address
|
||||
payload["status"] = device.status_live or "unknown"
|
||||
payload["last_seen"] = device.last_seen
|
||||
payload["last_scan"] = device.last_scan
|
||||
payload["response_time_ms"] = device.response_time_ms
|
||||
return payload
|
||||
|
||||
|
||||
# The device columns `nodes` carried before 3.3.0. They are read once, by the
|
||||
# backfill, and then dropped — so they are named here as raw SQL rather than as
|
||||
# model attributes that no longer exist.
|
||||
_LEGACY_NODE_COLUMNS = (
|
||||
"hostname", "ip", "mac", "os", "status", "check_method", "check_target",
|
||||
"services", "notes", "cpu_count", "cpu_model", "ram_gb", "disk_gb",
|
||||
"show_hardware", "properties", "ieee_address", "last_seen", "last_scan",
|
||||
"response_time_ms",
|
||||
)
|
||||
|
||||
|
||||
async def _legacy_columns_present(db: AsyncSession) -> list[str]:
|
||||
"""Which pre-3.3.0 device columns still exist on `nodes`."""
|
||||
rows = (await db.execute(text("PRAGMA table_info(nodes)"))).all()
|
||||
present = {r[1] for r in rows}
|
||||
return [c for c in _LEGACY_NODE_COLUMNS if c in present]
|
||||
|
||||
|
||||
def _decode_json(value: Any) -> Any:
|
||||
"""Raw SQL hands back JSON columns as text; the ORM would have decoded them."""
|
||||
if isinstance(value, str):
|
||||
try:
|
||||
return json.loads(value)
|
||||
except json.JSONDecodeError:
|
||||
return []
|
||||
return value
|
||||
|
||||
|
||||
async def backfill_node_devices(db: AsyncSession) -> dict[str, int]:
|
||||
"""Link every pre-3.3.0 canvas node to a Device Inventory row.
|
||||
|
||||
Non-destructive: it writes ``nodes.device_id`` and fills the inventory row,
|
||||
and never deletes a node or a row. Two nodes on two canvases describing the
|
||||
same host converge on one row — that convergence is the point.
|
||||
|
||||
Nodes are processed oldest-edit-first so that, where two canvases disagree
|
||||
on a scalar, the most recently edited node is the last writer and wins;
|
||||
properties and services are unioned, so nothing any canvas recorded is lost.
|
||||
|
||||
Reads the legacy columns with raw SQL because the model no longer declares
|
||||
them — this runs on the boot that drops them, once. Returns counts for the
|
||||
boot log, ``skipped`` among them: a node whose merge violates a constraint is
|
||||
left unlinked instead of aborting the run. Does not commit.
|
||||
"""
|
||||
legacy = await _legacy_columns_present(db)
|
||||
if not legacy:
|
||||
# Already migrated: the columns are gone, so nothing can be left to read.
|
||||
return {"linked": 0, "created": 0, "merged": 0, "skipped": 0}
|
||||
|
||||
placeholders = ", ".join(legacy)
|
||||
furniture = ", ".join(f"'{t}'" for t in sorted(FURNITURE_TYPES))
|
||||
rows = (
|
||||
await db.execute(
|
||||
text(
|
||||
f"SELECT id, label, type, design_id, {placeholders} FROM nodes "
|
||||
f"WHERE device_id IS NULL AND type NOT IN ({furniture}) "
|
||||
"ORDER BY updated_at, created_at, id"
|
||||
)
|
||||
)
|
||||
).mappings().all()
|
||||
if not rows:
|
||||
return {"linked": 0, "created": 0, "merged": 0, "skipped": 0}
|
||||
|
||||
linked = created = merged = skipped = 0
|
||||
for row in rows:
|
||||
facts: dict[str, Any] = {c: row[c] for c in legacy}
|
||||
facts["services"] = _decode_json(facts.get("services")) or []
|
||||
facts["properties"] = _decode_json(facts.get("properties")) or []
|
||||
facts["label"] = row["label"]
|
||||
facts["type"] = row["type"]
|
||||
|
||||
# One savepoint per node: a row the merge cannot write — a duplicate
|
||||
# IEEE, a constraint no longer met — is dropped on its own rather than
|
||||
# taking the whole backfill with it. Every node it does not link keeps
|
||||
# its legacy columns, so nothing is lost and the next boot retries.
|
||||
try:
|
||||
async with db.begin_nested():
|
||||
existing = await find_device_for(
|
||||
db, ip=facts.get("ip"), mac=facts.get("mac"), ieee=facts.get("ieee_address")
|
||||
)
|
||||
node = await db.get(Node, row["id"])
|
||||
if node is None: # pragma: no cover - the row was just read
|
||||
continue
|
||||
device = await link_facts(db, node, facts, overwrite_scalars=True)
|
||||
if device is None:
|
||||
continue
|
||||
await db.flush()
|
||||
except (IntegrityError, OperationalError) as exc:
|
||||
skipped += 1
|
||||
logger.warning(
|
||||
"Inventory backfill: node %s (%s) skipped — %s", row["id"], row["label"], exc
|
||||
)
|
||||
continue
|
||||
|
||||
linked += 1
|
||||
if existing is None:
|
||||
created += 1
|
||||
logger.info(
|
||||
"Inventory backfill: node %s (%s) created device %s", node.id, row["label"], device.id
|
||||
)
|
||||
else:
|
||||
merged += 1
|
||||
logger.info(
|
||||
"Inventory backfill: node %s (%s, design %s) merged into device %s",
|
||||
node.id, row["label"], row["design_id"], device.id,
|
||||
)
|
||||
|
||||
await db.flush()
|
||||
return {"linked": linked, "created": created, "merged": merged, "skipped": skipped}
|
||||
@@ -1,43 +1,29 @@
|
||||
"""Collapse *true* duplicate canvas nodes: same ``ieee_address`` **and** same
|
||||
``design_id`` (i.e. the same device placed twice on the *same* canvas).
|
||||
"""Duplicate canvas nodes: the same device drawn twice on the *same* canvas.
|
||||
|
||||
The same device legitimately appears on multiple canvases — placing a device on
|
||||
another design creates a second :class:`Node` for that IEEE by design (see the
|
||||
per-design guard in ``bulk_approve_devices``). Those cross-design rows are NOT
|
||||
duplicates and must be preserved. Only two rows sharing both the IEEE *and* the
|
||||
design are corrupt, and only those are collapsed here.
|
||||
A device legitimately appears on several canvases — one :class:`Node` per
|
||||
design, all pointing at one ``device_inventory`` row. Two nodes drawing that row
|
||||
on the *same* design are the corrupt case, and the only one collapsed here.
|
||||
|
||||
This module provides an idempotent, **loss-free** repair: per ``(ieee,
|
||||
design_id)`` group with >1 node it keeps the oldest as canonical, merges the
|
||||
extras' data into it (properties, missing scalar fields, services), re-points
|
||||
every edge and ``parent_id`` reference onto the canonical node, then deletes the
|
||||
extras. Edges are de-duplicated and self-loops dropped after re-pointing so no
|
||||
dangling or redundant links remain.
|
||||
Identity is the device link, not the addresses: a node names the row it draws,
|
||||
so "same device" is an id comparison rather than a guess across ieee/ip/mac.
|
||||
The repair is idempotent — the oldest node stays, edges and ``parent_id``
|
||||
references are re-pointed onto it, then the extras go. No device data is lost in
|
||||
the process because none of it lives on the node any more.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import or_, select
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.db.models import Edge, Node
|
||||
from app.services.zigbee_service import merge_zigbee_properties
|
||||
from app.services.inventory_sync import find_device_for
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _ip_tokens(ip: str | None) -> list[str]:
|
||||
"""Split a Node ``ip`` field into individual, whitespace-trimmed addresses.
|
||||
|
||||
The canvas stores several addresses in one comma-separated string once a
|
||||
user adds e.g. an IPv6 address, so identity matching must compare per token.
|
||||
"""
|
||||
return [t.strip() for t in ip.split(",") if t.strip()] if ip else []
|
||||
|
||||
|
||||
async def find_duplicate_node(
|
||||
db: AsyncSession,
|
||||
design_id: str | None,
|
||||
@@ -45,153 +31,84 @@ async def find_duplicate_node(
|
||||
mac: str | None,
|
||||
ieee: str | None = None,
|
||||
) -> dict[str, Any] | None:
|
||||
"""Return conflict details if an equivalent node (same ieee, ip OR mac)
|
||||
already sits on ``design_id``, else ``None``.
|
||||
"""Return conflict details if this device is already drawn on ``design_id``.
|
||||
|
||||
Scoped to a single design on purpose: the same device may legitimately
|
||||
appear on several canvases (one :class:`Node` per design). Only a second
|
||||
node for the same ieee/ip/mac on the *same* design is a duplicate — which
|
||||
the create/approve endpoints turn into a 409 so the UI can offer "go to
|
||||
existing" vs "add duplicate anyway", uniformly for IEEE (Zigbee/Z-Wave) and
|
||||
plain IP/ARP hosts.
|
||||
Identity is resolved once, by the inventory row the addresses point at
|
||||
(``find_device_for``: ieee > ip > mac), and a duplicate is simply a second
|
||||
node on the same design drawing that row. Scoped to one design on purpose:
|
||||
the same device may legitimately appear on several canvases.
|
||||
|
||||
(:func:`dedupe_nodes_by_ieee` still repairs *pre-existing* same-canvas IEEE
|
||||
duplicates; this guard prevents new ones unless the user forces them.)
|
||||
The create/approve endpoints turn this into a 409 so the UI can offer "go to
|
||||
existing" vs "add duplicate anyway".
|
||||
"""
|
||||
ip_toks = _ip_tokens(ip)
|
||||
conds = []
|
||||
if ieee:
|
||||
conds.append(Node.ieee_address == ieee)
|
||||
# A node's ip may hold several comma-separated addresses (e.g. an IPv6 added
|
||||
# before the IPv4), so narrow with a substring match then confirm per-token
|
||||
# in Python — exact ``Node.ip == ip`` would miss those rows (issue #258).
|
||||
for tok in ip_toks:
|
||||
conds.append(Node.ip.contains(tok))
|
||||
if mac:
|
||||
conds.append(Node.mac == mac)
|
||||
if not conds:
|
||||
device = await find_device_for(db, ip=ip, mac=mac, ieee=ieee)
|
||||
if device is None:
|
||||
return None
|
||||
candidates = (
|
||||
existing = (
|
||||
await db.execute(
|
||||
select(Node).where(Node.design_id == design_id, or_(*conds))
|
||||
select(Node)
|
||||
.where(Node.design_id == design_id, Node.device_id == device.id)
|
||||
.order_by(Node.created_at, Node.id)
|
||||
)
|
||||
).scalars().all()
|
||||
|
||||
# Confirm a real match (the ip ``contains`` above can false-positive, e.g.
|
||||
# "1.2.3.4" inside "1.2.3.40"), preferring ieee > ip > mac.
|
||||
def _matches(node: Node) -> tuple[str, str | None] | None:
|
||||
if ieee and node.ieee_address == ieee:
|
||||
return "ieee", node.ieee_address
|
||||
node_toks = set(_ip_tokens(node.ip))
|
||||
hit = next((t for t in ip_toks if t in node_toks), None)
|
||||
if hit is not None:
|
||||
return "ip", hit
|
||||
if mac and node.mac == mac:
|
||||
return "mac", mac
|
||||
).scalars().first()
|
||||
if existing is None:
|
||||
return None
|
||||
|
||||
existing = None
|
||||
matched: tuple[str, str | None] | None = None
|
||||
for node in candidates:
|
||||
m = _matches(node)
|
||||
if m is not None:
|
||||
existing, matched = node, m
|
||||
break
|
||||
if existing is None or matched is None:
|
||||
return None
|
||||
match, value = matched
|
||||
# Report which address identified the device, as the UI prints it, in the
|
||||
# same precedence find_device_for used: ieee > ip > mac.
|
||||
match: str
|
||||
value: str | None
|
||||
device_ips = {t.strip() for t in (device.ip or "").split(",") if t.strip()}
|
||||
shared_ip = next((t.strip() for t in (ip or "").split(",") if t.strip() in device_ips), None)
|
||||
if ieee and device.ieee_address == ieee:
|
||||
match, value = "ieee", ieee
|
||||
elif shared_ip:
|
||||
match, value = "ip", shared_ip
|
||||
elif mac and device.mac == mac:
|
||||
match, value = "mac", mac
|
||||
else:
|
||||
match, value = "ip", ip
|
||||
return {
|
||||
"duplicate": True,
|
||||
"existing_node_id": existing.id,
|
||||
"existing_label": existing.label,
|
||||
"existing_label": device.label or existing.label,
|
||||
"match": match,
|
||||
"value": value,
|
||||
}
|
||||
|
||||
# Scalar Node fields worth carrying over from a duplicate when the canonical
|
||||
# node has no value. Positions, design, parent and identity fields are left on
|
||||
# the canonical node untouched (that's the row the user actually placed).
|
||||
_FILLABLE_FIELDS = (
|
||||
"hostname",
|
||||
"ip",
|
||||
"mac",
|
||||
"os",
|
||||
"check_method",
|
||||
"check_target",
|
||||
"notes",
|
||||
"cpu_count",
|
||||
"cpu_model",
|
||||
"ram_gb",
|
||||
"disk_gb",
|
||||
"custom_icon",
|
||||
"last_seen",
|
||||
"last_scan",
|
||||
)
|
||||
|
||||
async def dedupe_nodes_by_device(db: AsyncSession) -> int:
|
||||
"""Merge duplicate nodes drawing the same device on the same canvas.
|
||||
|
||||
def _merge_services(
|
||||
a: list[Any] | None, b: list[Any] | None
|
||||
) -> list[Any]:
|
||||
"""Union two service lists, de-duplicated, order-stable."""
|
||||
out: list[Any] = list(a or [])
|
||||
seen = {repr(s) for s in out}
|
||||
for s in b or []:
|
||||
if repr(s) not in seen:
|
||||
out.append(s)
|
||||
seen.add(repr(s))
|
||||
return out
|
||||
|
||||
|
||||
def _merge_into_canonical(canonical: Node, dup: Node) -> None:
|
||||
"""Fold ``dup``'s data into ``canonical`` in place (no field lost)."""
|
||||
canonical.properties = merge_zigbee_properties(
|
||||
canonical.properties, dup.properties or []
|
||||
)
|
||||
canonical.services = _merge_services(canonical.services, dup.services)
|
||||
for field in _FILLABLE_FIELDS:
|
||||
if getattr(canonical, field, None) in (None, "") and getattr(dup, field, None) not in (None, ""):
|
||||
setattr(canonical, field, getattr(dup, field))
|
||||
# Prefer a human label over a bare IEEE/hex fallback.
|
||||
if (not canonical.label or canonical.label == canonical.ieee_address) and dup.label:
|
||||
canonical.label = dup.label
|
||||
|
||||
|
||||
async def dedupe_nodes_by_ieee(db: AsyncSession) -> int:
|
||||
"""Merge duplicate nodes sharing an ``ieee_address`` AND ``design_id``.
|
||||
|
||||
Returns the number of nodes removed. Idempotent: a no-op when every
|
||||
``(ieee, design)`` pair maps to at most one node. Nodes with the same IEEE
|
||||
on *different* designs are left untouched (valid cross-canvas placement).
|
||||
Returns the number of nodes removed. Idempotent. Nodes drawing one device on
|
||||
*different* designs are left alone — that is valid cross-canvas placement.
|
||||
The device facts live on the inventory row, so nothing has to be merged out
|
||||
of the extras: only edges and parent links are re-pointed before they go.
|
||||
Does not commit — the caller owns the transaction.
|
||||
"""
|
||||
rows = (
|
||||
await db.execute(
|
||||
select(Node)
|
||||
.where(Node.ieee_address.is_not(None))
|
||||
.order_by(Node.ieee_address, Node.created_at, Node.id)
|
||||
.where(Node.device_id.is_not(None))
|
||||
.order_by(Node.device_id, Node.created_at, Node.id)
|
||||
)
|
||||
).scalars().all()
|
||||
|
||||
groups: dict[tuple[str, str | None], list[Node]] = {}
|
||||
for node in rows:
|
||||
groups.setdefault((node.ieee_address, node.design_id), []).append(node) # type: ignore[arg-type]
|
||||
groups.setdefault((node.device_id, node.design_id), []).append(node) # type: ignore[arg-type]
|
||||
|
||||
removed = 0
|
||||
for (ieee, _design), nodes in groups.items():
|
||||
for (device_id, _design), nodes in groups.items():
|
||||
if len(nodes) < 2:
|
||||
continue
|
||||
canonical, *dups = nodes # oldest first (ordered above)
|
||||
dup_ids = {d.id for d in dups}
|
||||
|
||||
for dup in dups:
|
||||
_merge_into_canonical(canonical, dup)
|
||||
|
||||
# Re-point edges + parents, then drop self-loops / duplicates.
|
||||
edges = (
|
||||
await db.execute(
|
||||
select(Edge).where(
|
||||
Edge.source.in_(dup_ids) | Edge.target.in_(dup_ids)
|
||||
)
|
||||
select(Edge).where(Edge.source.in_(dup_ids) | Edge.target.in_(dup_ids))
|
||||
)
|
||||
).scalars().all()
|
||||
for edge in edges:
|
||||
@@ -200,19 +117,15 @@ async def dedupe_nodes_by_ieee(db: AsyncSession) -> int:
|
||||
if edge.target in dup_ids:
|
||||
edge.target = canonical.id
|
||||
|
||||
# Re-point children whose parent was a duplicate.
|
||||
children = (
|
||||
await db.execute(select(Node).where(Node.parent_id.in_(dup_ids)))
|
||||
).scalars().all()
|
||||
for child in children:
|
||||
child.parent_id = canonical.id
|
||||
|
||||
# Collapse self-loops and now-redundant parallel edges.
|
||||
all_edges = (
|
||||
await db.execute(
|
||||
select(Edge).where(
|
||||
(Edge.source == canonical.id) | (Edge.target == canonical.id)
|
||||
)
|
||||
select(Edge).where((Edge.source == canonical.id) | (Edge.target == canonical.id))
|
||||
)
|
||||
).scalars().all()
|
||||
seen_pairs: set[tuple[str, str, str]] = set()
|
||||
@@ -232,8 +145,8 @@ async def dedupe_nodes_by_ieee(db: AsyncSession) -> int:
|
||||
removed += 1
|
||||
|
||||
logger.info(
|
||||
"Deduped IEEE %s: merged %d duplicate node(s) into %s",
|
||||
ieee, len(dups), canonical.id,
|
||||
"Deduped device %s: merged %d duplicate node(s) into %s",
|
||||
device_id, len(dups), canonical.id,
|
||||
)
|
||||
|
||||
if removed:
|
||||
|
||||
@@ -14,7 +14,8 @@ from typing import Any
|
||||
from sqlalchemy import or_, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.db.models import Node, PendingDevice, ScanRun
|
||||
from app.core.config import settings
|
||||
from app.db.models import InventoryDevice, ScanRun
|
||||
from app.services.discovery_sources import add_source
|
||||
from app.services.fingerprint import fingerprint_ports, suggest_node_type
|
||||
from app.services.http_probe import probe_open_ports
|
||||
@@ -240,6 +241,14 @@ def _nmap_scan_single(host_dict: dict[str, Any], port_spec: str = _EXTRA_PORTS)
|
||||
"""
|
||||
Phase 2 — single-IP port scan with service detection.
|
||||
Runs in a thread (blocking). Returns the host dict enriched with open_ports.
|
||||
|
||||
Two decoupled nmap passes (issue #277):
|
||||
Pass A — port discovery only (``--open``, no ``-sV``). Fast and reliable;
|
||||
its open ports are authoritative and are never discarded.
|
||||
Pass B — version detection (``-sV``) scoped to the ports Pass A found,
|
||||
bounded by ``--host-timeout``. Best-effort: if it times out or
|
||||
fails (e.g. a TLS port stalls plaintext probes), the Pass A ports
|
||||
are kept with empty banners instead of the whole host being lost.
|
||||
"""
|
||||
ip = host_dict["ip"]
|
||||
logger.info("[Phase 2] Scanning %s ...", ip)
|
||||
@@ -248,48 +257,76 @@ def _nmap_scan_single(host_dict: dict[str, Any], port_spec: str = _EXTRA_PORTS)
|
||||
logger.warning("[Phase 2] nmap not available, skipping %s", ip)
|
||||
return host_dict
|
||||
|
||||
is_root = os.geteuid() == 0
|
||||
if is_root:
|
||||
# SYN scan + version detection (fastest, most accurate)
|
||||
scan_args = f"-sS -sV --open -T4 -Pn --host-timeout 60s -p {port_spec}"
|
||||
else:
|
||||
# TCP connect scan (-sT) — no raw sockets needed, works without root.
|
||||
# nmap auto-selects -sT without root but being explicit avoids edge cases.
|
||||
scan_args = f"-sT -sV --open -T4 -Pn --host-timeout 60s -p {port_spec}"
|
||||
# -sS (SYN) needs root; -sT (connect) works without it. nmap auto-selects
|
||||
# -sT without root but being explicit avoids edge cases.
|
||||
scan_type = "-sS" if os.geteuid() == 0 else "-sT"
|
||||
|
||||
logger.debug("[Phase 2] %s args: %s", ip, scan_args)
|
||||
nm = nmap.PortScanner()
|
||||
# --- Pass A: port discovery (no -sV, no host-timeout) ---
|
||||
discovery_args = f"{scan_type} --open -T4 -Pn -p {port_spec}"
|
||||
logger.debug("[Phase 2] %s discovery args: %s", ip, discovery_args)
|
||||
nm_disc = nmap.PortScanner()
|
||||
try:
|
||||
nm.scan(hosts=ip, arguments=scan_args)
|
||||
nm_disc.scan(hosts=ip, arguments=discovery_args)
|
||||
except Exception as exc:
|
||||
logger.warning("[Phase 2] nmap FAILED for %s (%s: %s) — skipping port scan", ip, type(exc).__name__, exc)
|
||||
logger.warning("[Phase 2] nmap discovery FAILED for %s (%s: %s) — skipping port scan",
|
||||
ip, type(exc).__name__, exc)
|
||||
return host_dict
|
||||
|
||||
all_scanned = nm.all_hosts()
|
||||
logger.debug("[Phase 2] %s — nmap returned %d host(s) in results", ip, len(all_scanned))
|
||||
if ip not in all_scanned:
|
||||
if ip not in nm_disc.all_hosts():
|
||||
logger.info("[Phase 2] %s — no open ports found (all closed/filtered or nmap had no results)", ip)
|
||||
return host_dict
|
||||
|
||||
open_ports = []
|
||||
for proto in nm[ip].all_protocols():
|
||||
for port, info in nm[ip][proto].items():
|
||||
for proto in nm_disc[ip].all_protocols():
|
||||
for port, info in nm_disc[ip][proto].items():
|
||||
if info["state"] == "open":
|
||||
banner = (info.get("product", "") + " " + info.get("version", "")).strip()
|
||||
open_ports.append({"port": port, "protocol": proto, "banner": banner})
|
||||
open_ports.append({"port": port, "protocol": proto, "banner": ""})
|
||||
|
||||
if open_ports:
|
||||
port_summary = ", ".join(
|
||||
f"{p['port']}/{p['protocol']} ({p['banner'] or 'unknown'})" for p in open_ports
|
||||
)
|
||||
logger.info("[Phase 2] %s — %d open port(s): %s", ip, len(open_ports), port_summary)
|
||||
else:
|
||||
if not open_ports:
|
||||
logger.info("[Phase 2] %s — 0 open ports detected", ip)
|
||||
host_dict["open_ports"] = []
|
||||
if not host_dict["mac"]:
|
||||
host_dict["mac"] = nm_disc[ip].get("addresses", {}).get("mac")
|
||||
return host_dict
|
||||
|
||||
# --- Pass B: version detection on the discovered ports (best-effort) ---
|
||||
port_list = ",".join(str(p["port"]) for p in open_ports)
|
||||
timeout = settings.scanner_version_host_timeout
|
||||
version_args = f"{scan_type} -sV -T4 -Pn --host-timeout {timeout}s -p {port_list}"
|
||||
logger.debug("[Phase 2] %s version args: %s", ip, version_args)
|
||||
nm_ver = nmap.PortScanner()
|
||||
banners: dict[tuple[str, int], str] = {}
|
||||
ver_os = None
|
||||
ver_mac = None
|
||||
try:
|
||||
nm_ver.scan(hosts=ip, arguments=version_args)
|
||||
if ip in nm_ver.all_hosts():
|
||||
for proto in nm_ver[ip].all_protocols():
|
||||
for port, info in nm_ver[ip][proto].items():
|
||||
banner = (info.get("product", "") + " " + info.get("version", "")).strip()
|
||||
if banner:
|
||||
banners[(proto, port)] = banner
|
||||
ver_os = _extract_os(nm_ver, ip)
|
||||
ver_mac = nm_ver[ip].get("addresses", {}).get("mac")
|
||||
else:
|
||||
logger.info("[Phase 2] %s — version detection returned no results, keeping %d port(s) without banners",
|
||||
ip, len(open_ports))
|
||||
except Exception as exc:
|
||||
logger.info("[Phase 2] %s — version detection failed (%s: %s), keeping %d port(s) without banners",
|
||||
ip, type(exc).__name__, exc, len(open_ports))
|
||||
|
||||
for p in open_ports:
|
||||
p["banner"] = banners.get((p["protocol"], p["port"]), "")
|
||||
|
||||
port_summary = ", ".join(
|
||||
f"{p['port']}/{p['protocol']} ({p['banner'] or 'unknown'})" for p in open_ports
|
||||
)
|
||||
logger.info("[Phase 2] %s — %d open port(s): %s", ip, len(open_ports), port_summary)
|
||||
|
||||
host_dict["open_ports"] = open_ports
|
||||
if not host_dict["mac"]:
|
||||
host_dict["mac"] = nm[ip].get("addresses", {}).get("mac")
|
||||
host_dict["os"] = _extract_os(nm, ip)
|
||||
host_dict["mac"] = ver_mac or nm_disc[ip].get("addresses", {}).get("mac")
|
||||
host_dict["os"] = ver_os
|
||||
return host_dict
|
||||
|
||||
|
||||
@@ -439,12 +476,12 @@ async def _dedupe_pending_by_ip(db: AsyncSession) -> int:
|
||||
otherwise the oldest row, and deletes the rest. Returns the number deleted.
|
||||
"""
|
||||
rows = (await db.execute(
|
||||
select(PendingDevice)
|
||||
.where(PendingDevice.status != "hidden", PendingDevice.ip.isnot(None))
|
||||
.order_by(PendingDevice.discovered_at)
|
||||
select(InventoryDevice)
|
||||
.where(InventoryDevice.status != "hidden", InventoryDevice.ip.isnot(None))
|
||||
.order_by(InventoryDevice.discovered_at)
|
||||
)).scalars().all()
|
||||
|
||||
by_ip: dict[str, list[PendingDevice]] = {}
|
||||
by_ip: dict[str, list[InventoryDevice]] = {}
|
||||
for row in rows:
|
||||
if row.ip is None: # guarded by the query, but keeps the type checker happy
|
||||
continue
|
||||
@@ -470,7 +507,7 @@ async def run_scan(
|
||||
run_id: str,
|
||||
deep_scan: DeepScanOptions | None = None,
|
||||
) -> None:
|
||||
"""Execute scan for given CIDR ranges and populate pending_devices."""
|
||||
"""Execute scan for given CIDR ranges and populate device_inventory."""
|
||||
from app.api.routes.status import broadcast_scan_update
|
||||
|
||||
deep_scan = deep_scan or DeepScanOptions()
|
||||
@@ -490,7 +527,7 @@ async def run_scan(
|
||||
# Devices already on a canvas are intentionally NOT suppressed: they stay
|
||||
# in the inventory and are badged "In N canvas" via per-request correlation.
|
||||
hidden_ips_result = await db.execute(
|
||||
select(PendingDevice.ip).where(PendingDevice.status == "hidden")
|
||||
select(InventoryDevice.ip).where(InventoryDevice.status == "hidden")
|
||||
)
|
||||
hidden_ips: set[str] = {row[0] for row in hidden_ips_result.fetchall()}
|
||||
|
||||
@@ -533,13 +570,13 @@ async def run_scan(
|
||||
# a duplicate — and so a device previously imported from Proxmox (which
|
||||
# may have no IP but a known NIC MAC) reconciles with this scan instead
|
||||
# of doubling up. Hidden rows are already skipped above.
|
||||
match_cond = [PendingDevice.ip == ip]
|
||||
match_cond = [InventoryDevice.ip == ip]
|
||||
if norm_mac:
|
||||
match_cond.append(PendingDevice.mac == norm_mac)
|
||||
match_cond.append(InventoryDevice.mac == norm_mac)
|
||||
existing_rows = (await db.execute(
|
||||
select(PendingDevice)
|
||||
.where(or_(*match_cond), PendingDevice.status != "hidden")
|
||||
.order_by(PendingDevice.discovered_at)
|
||||
select(InventoryDevice)
|
||||
.where(or_(*match_cond), InventoryDevice.status != "hidden")
|
||||
.order_by(InventoryDevice.discovered_at)
|
||||
)).scalars().all()
|
||||
|
||||
if existing_rows:
|
||||
@@ -562,8 +599,12 @@ async def run_scan(
|
||||
# Merged row carries both sources (e.g. ["proxmox", "arp"]).
|
||||
keep.discovery_sources = add_source(keep.discovery_sources, discovery_source)
|
||||
# status preserved — an approved device stays approved.
|
||||
# Stamp last_scan on the row so every canvas drawing the device
|
||||
# shows when the scanner last observed it. The row is the one
|
||||
# place that fact belongs; a node only draws it.
|
||||
keep.last_scan = datetime.now(timezone.utc)
|
||||
else:
|
||||
db.add(PendingDevice(
|
||||
db.add(InventoryDevice(
|
||||
ip=ip,
|
||||
mac=norm_mac,
|
||||
hostname=host.get("hostname"),
|
||||
@@ -573,25 +614,10 @@ async def run_scan(
|
||||
status="pending",
|
||||
discovery_source=discovery_source,
|
||||
discovery_sources=[discovery_source],
|
||||
last_scan=datetime.now(timezone.utc),
|
||||
))
|
||||
devices_found += 1
|
||||
|
||||
# Stamp last_scan on any canvas node that matches this device by IP
|
||||
# (or MAC, when known) so the inventory shows when the scanner last
|
||||
# observed it. Match both the normalized and raw MAC so a legacy
|
||||
# canvas node whose mac predates normalization still matches. Across
|
||||
# designs.
|
||||
node_match = [Node.ip == ip]
|
||||
for m in {norm_mac, host.get("mac")}:
|
||||
if m:
|
||||
node_match.append(Node.mac == m)
|
||||
matching_nodes = (await db.execute(
|
||||
select(Node).where(or_(*node_match))
|
||||
)).scalars().all()
|
||||
scanned_at = datetime.now(timezone.utc)
|
||||
for node in matching_nodes:
|
||||
node.last_scan = scanned_at
|
||||
|
||||
await db.commit()
|
||||
await broadcast_scan_update(run_id=run_id, devices_found=devices_found)
|
||||
|
||||
|
||||
@@ -138,6 +138,41 @@ def _service_host(svc: dict[str, Any], host: str) -> str:
|
||||
return f"[{host}]" if _is_ipv6(host) else host
|
||||
|
||||
|
||||
def _parse_override(raw: str) -> tuple[str, str | None, int | None]:
|
||||
"""Split a service `host` override into (hostname, scheme, port).
|
||||
|
||||
Mirrors the frontend `parseHostParts`: a node can serve several domains, so
|
||||
a service may carry its own host, optionally with a scheme and a port
|
||||
(`blog.example.com`, `blog.example.com:8443`, `https://blog.example.com`).
|
||||
"""
|
||||
# Like a node ip, an override may list several hosts — the first one wins,
|
||||
# same as the frontend's `splitFirstHost`.
|
||||
rest = raw.split(",")[0].strip()
|
||||
scheme: str | None = None
|
||||
for prefix in ("https://", "http://"):
|
||||
if rest.lower().startswith(prefix):
|
||||
scheme = prefix[:-3]
|
||||
rest = rest[len(prefix):]
|
||||
break
|
||||
rest = rest.split("/", 1)[0]
|
||||
|
||||
if rest.startswith("["):
|
||||
closing = rest.find("]")
|
||||
if closing == -1:
|
||||
return rest, scheme, None
|
||||
hostname = rest[1:closing]
|
||||
remainder = rest[closing + 1:]
|
||||
port = remainder[1:] if remainder.startswith(":") else ""
|
||||
return hostname, scheme, int(port) if port.isdigit() else None
|
||||
|
||||
if rest.count(":") == 1:
|
||||
hostname, _, port = rest.partition(":")
|
||||
if hostname and port.isdigit():
|
||||
return hostname, scheme, int(port)
|
||||
|
||||
return rest, scheme, None
|
||||
|
||||
|
||||
async def check_service(svc: dict[str, Any], host: str | None) -> str:
|
||||
"""Check a single service. Returns 'online' | 'offline' | 'unknown'.
|
||||
|
||||
@@ -146,6 +181,12 @@ async def check_service(svc: dict[str, Any], host: str | None) -> str:
|
||||
so it keeps its category colour instead of flashing red. An open TCP socket
|
||||
doesn't prove a non-web service is healthy, so we don't pretend it does.
|
||||
"""
|
||||
override = str(svc.get("host") or "").strip()
|
||||
override_scheme: str | None = None
|
||||
override_port: int | None = None
|
||||
if override:
|
||||
host, override_scheme, override_port = _parse_override(override)
|
||||
|
||||
if not host or host.startswith("-"):
|
||||
return "unknown"
|
||||
if str(svc.get("protocol", "")).lower() == "udp":
|
||||
@@ -153,20 +194,22 @@ async def check_service(svc: dict[str, Any], host: str | None) -> str:
|
||||
|
||||
port = svc.get("port")
|
||||
port = int(port) if isinstance(port, int) or (isinstance(port, str) and port.isdigit()) else None
|
||||
if port is None:
|
||||
port = override_port
|
||||
|
||||
# Non-HTTP ports (SSH 22, DB, mail, …) are never checked — keep them grey.
|
||||
if port is not None and port in _NON_HTTP_PORTS:
|
||||
return "unknown"
|
||||
|
||||
name = str(svc.get("service_name", "")).lower()
|
||||
is_web = port is not None or "http" in name
|
||||
is_web = port is not None or "http" in name or override_scheme is not None
|
||||
if not is_web:
|
||||
return "unknown"
|
||||
|
||||
try:
|
||||
scheme = "https" if (
|
||||
scheme = override_scheme or ("https" if (
|
||||
port in _HTTPS_PORTS or "https" in name or "ssl" in name or "tls" in name
|
||||
) else "http"
|
||||
) else "http")
|
||||
url_host = _service_host(svc, host)
|
||||
url = f"{scheme}://{url_host}" + (f":{port}" if port is not None else "")
|
||||
return "online" if await _http_get(url, verify=False) else "offline"
|
||||
@@ -187,6 +230,13 @@ async def check_services(
|
||||
async def _one(svc: dict[str, Any]) -> dict[str, Any]:
|
||||
async with sem:
|
||||
status = await check_service(svc, host)
|
||||
return {"port": svc.get("port"), "protocol": svc.get("protocol"), "status": status}
|
||||
# `host` rides along: several vhosts can share one port on one node, so
|
||||
# port+protocol alone no longer identifies a service on the client side.
|
||||
return {
|
||||
"port": svc.get("port"),
|
||||
"protocol": svc.get("protocol"),
|
||||
"host": svc.get("host"),
|
||||
"status": status,
|
||||
}
|
||||
|
||||
return await asyncio.gather(*[_one(s) for s in services]) if services else []
|
||||
|
||||
@@ -6,8 +6,10 @@ aiosqlite==0.20.0
|
||||
alembic==1.13.3
|
||||
pydantic==2.9.2
|
||||
pydantic-settings==2.5.2
|
||||
python-jose[cryptography]==3.5.0
|
||||
PyJWT==2.13.0
|
||||
bcrypt==4.2.1
|
||||
authlib==1.7.2
|
||||
itsdangerous==2.2.0
|
||||
python-multipart==0.0.31
|
||||
apscheduler==3.10.4
|
||||
python-nmap==0.7.1
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
"""The 3.2.0 → 3.3.0 upgrade of the `nodes` table.
|
||||
|
||||
3.3.0 moved the device facts off `nodes` onto `device_inventory` and dropped the
|
||||
columns. A real 3.2.0 database declares several of them NOT NULL with no
|
||||
server-side default (`status`, `services`, `properties`, `show_hardware`) — the
|
||||
schema here is `create_all`'s output at tag v3.2.0, not a hand-simplified copy,
|
||||
because that constraint is exactly what breaks: the 3.3.0 model no longer writes
|
||||
those columns, so if they survive the upgrade every INSERT fails with
|
||||
``NOT NULL constraint failed: nodes.status`` and approving a device is dead.
|
||||
"""
|
||||
import os
|
||||
|
||||
os.environ.setdefault("SECRET_KEY", "test-only-secret-key-not-for-production")
|
||||
|
||||
import pytest
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.ext.asyncio import create_async_engine
|
||||
|
||||
import app.db.database as database
|
||||
import app.services.inventory_sync as inventory_sync
|
||||
|
||||
# `create_all` under v3.2.0. NOT NULL is reproduced exactly where it was.
|
||||
_NODES_320 = (
|
||||
"CREATE TABLE nodes ("
|
||||
"id VARCHAR NOT NULL PRIMARY KEY, type VARCHAR NOT NULL, label VARCHAR NOT NULL, "
|
||||
"design_id VARCHAR, hostname VARCHAR, ip VARCHAR, mac VARCHAR, os VARCHAR, "
|
||||
"status VARCHAR NOT NULL, check_method VARCHAR, check_target VARCHAR, "
|
||||
"services JSON NOT NULL, notes TEXT, pos_x FLOAT NOT NULL, pos_y FLOAT NOT NULL, "
|
||||
"parent_id VARCHAR, container_mode BOOLEAN NOT NULL, custom_colors JSON, "
|
||||
"custom_icon VARCHAR, cpu_count INTEGER, cpu_model VARCHAR, ram_gb FLOAT, "
|
||||
"disk_gb FLOAT, show_hardware BOOLEAN NOT NULL, show_port_numbers BOOLEAN NOT NULL, "
|
||||
"properties JSON NOT NULL, width FLOAT, height FLOAT, "
|
||||
"bottom_handles INTEGER NOT NULL, top_handles INTEGER NOT NULL, "
|
||||
"left_handles INTEGER NOT NULL, right_handles INTEGER NOT NULL, "
|
||||
"ieee_address VARCHAR, last_seen DATETIME, last_scan DATETIME, "
|
||||
"response_time_ms INTEGER, created_at DATETIME NOT NULL, updated_at DATETIME NOT NULL)"
|
||||
)
|
||||
|
||||
_DESIGNS_320 = (
|
||||
"CREATE TABLE designs (id VARCHAR NOT NULL PRIMARY KEY, name VARCHAR NOT NULL, "
|
||||
"design_type VARCHAR NOT NULL, icon VARCHAR, created_at DATETIME NOT NULL, "
|
||||
"updated_at DATETIME NOT NULL)"
|
||||
)
|
||||
|
||||
|
||||
def _node_sql(node_id: str, label: str, node_type: str, ip: str | None) -> str:
|
||||
ip_sql = f"'{ip}'" if ip else "NULL"
|
||||
return (
|
||||
"INSERT INTO nodes (id, type, label, design_id, ip, status, services, pos_x, pos_y, "
|
||||
"container_mode, show_hardware, show_port_numbers, properties, bottom_handles, "
|
||||
"top_handles, left_handles, right_handles, created_at, updated_at) VALUES "
|
||||
f"('{node_id}', '{node_type}', '{label}', 'd1', {ip_sql}, 'online', '[]', 0, 0, "
|
||||
"0, 0, 0, '[]', 1, 1, 0, 0, '2026-01-01 00:00:00', '2026-01-01 00:00:00')"
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def db_320(tmp_path, monkeypatch):
|
||||
"""A v3.2.0 database, with the module-global engine pointed at it."""
|
||||
db_path = tmp_path / "v320.db"
|
||||
monkeypatch.setattr(database.settings, "sqlite_path", str(db_path))
|
||||
engine = create_async_engine(f"sqlite+aiosqlite:///{db_path}")
|
||||
monkeypatch.setattr(database, "engine", engine)
|
||||
monkeypatch.setattr(
|
||||
database, "AsyncSessionLocal", database.async_sessionmaker(engine, expire_on_commit=False)
|
||||
)
|
||||
return db_path, engine
|
||||
|
||||
|
||||
async def _build_320(engine) -> None:
|
||||
async with engine.begin() as conn:
|
||||
await conn.exec_driver_sql(_DESIGNS_320)
|
||||
await conn.exec_driver_sql(_NODES_320)
|
||||
await conn.exec_driver_sql(
|
||||
"INSERT INTO designs (id, name, design_type, icon, created_at, updated_at) "
|
||||
"VALUES ('d1', 'Network Topology', 'network', 'dashboard', "
|
||||
"'2026-01-01 00:00:00', '2026-01-01 00:00:00')"
|
||||
)
|
||||
await conn.exec_driver_sql(_node_sql("n1", "OpnSense", "firewall", "192.168.1.1"))
|
||||
await conn.exec_driver_sql(_node_sql("n2", "NAS", "nas", "192.168.1.2"))
|
||||
await conn.exec_driver_sql(_node_sql("n3", "a note", "text", None))
|
||||
|
||||
|
||||
async def _insert_node(engine) -> None:
|
||||
"""What approve does: insert a node the way the 3.3.0 model writes one."""
|
||||
from app.db.models import Node
|
||||
|
||||
session_factory = database.async_sessionmaker(engine, expire_on_commit=False)
|
||||
async with session_factory() as session:
|
||||
session.add(Node(id="new", type="firewall", label="Approved", design_id="d1"))
|
||||
await session.commit()
|
||||
|
||||
|
||||
async def test_upgrade_drops_the_device_columns_and_leaves_nodes_insertable(db_320):
|
||||
db_path, engine = db_320
|
||||
await _build_320(engine)
|
||||
|
||||
await database.init_db()
|
||||
|
||||
check = create_async_engine(f"sqlite+aiosqlite:///{db_path}")
|
||||
try:
|
||||
async with check.begin() as conn:
|
||||
cols = {c[1] for c in (await conn.exec_driver_sql("PRAGMA table_info(nodes)")).fetchall()}
|
||||
assert "status" not in cols
|
||||
assert "ip" not in cols
|
||||
assert "device_id" in cols
|
||||
# Every device node linked; the facts moved to the inventory row.
|
||||
linked = (await conn.exec_driver_sql(
|
||||
"SELECT label, device_id FROM nodes ORDER BY id"
|
||||
)).fetchall()
|
||||
assert [row[0] for row in linked] == ["OpnSense", "NAS", "a note"]
|
||||
assert linked[0][1] and linked[1][1]
|
||||
assert linked[2][1] is None # canvas furniture keeps no row
|
||||
ips = (await conn.exec_driver_sql(
|
||||
"SELECT ip FROM device_inventory ORDER BY ip"
|
||||
)).fetchall()
|
||||
assert [row[0] for row in ips] == ["192.168.1.1", "192.168.1.2"]
|
||||
|
||||
await _insert_node(engine)
|
||||
finally:
|
||||
await check.dispose()
|
||||
await engine.dispose()
|
||||
|
||||
|
||||
async def test_a_node_the_backfill_cannot_link_still_leaves_nodes_insertable(db_320, monkeypatch):
|
||||
"""The regression: a failed backfill must not brick every later INSERT.
|
||||
|
||||
Before the fix, one unlinkable node kept `nodes.status` NOT NULL while the
|
||||
3.3.0 model stopped writing it, so approving *any* device raised
|
||||
``NOT NULL constraint failed: nodes.status`` (issue #351).
|
||||
"""
|
||||
db_path, engine = db_320
|
||||
await _build_320(engine)
|
||||
|
||||
real_link_facts = inventory_sync.link_facts
|
||||
|
||||
async def link_facts(db, node, facts, **kwargs):
|
||||
if node.id == "n2":
|
||||
raise IntegrityError("boom", None, Exception("UNIQUE constraint failed"))
|
||||
return await real_link_facts(db, node, facts, **kwargs)
|
||||
|
||||
monkeypatch.setattr(inventory_sync, "link_facts", link_facts)
|
||||
|
||||
await database.init_db()
|
||||
|
||||
check = create_async_engine(f"sqlite+aiosqlite:///{db_path}")
|
||||
try:
|
||||
async with check.begin() as conn:
|
||||
info = (await conn.exec_driver_sql("PRAGMA table_info(nodes)")).fetchall()
|
||||
cols = {c[1]: c for c in info}
|
||||
# The columns stay — they are the only remaining copy of n2's facts.
|
||||
assert "status" in cols
|
||||
# But nothing is NOT NULL any more, so the model can insert again.
|
||||
assert not any(c[3] for name, c in cols.items() if name in database._LEGACY_NODE_COLUMNS)
|
||||
# Values preserved by the rebuild.
|
||||
kept = (await conn.exec_driver_sql(
|
||||
"SELECT status, ip FROM nodes WHERE id='n2'"
|
||||
)).fetchone()
|
||||
assert kept == ("online", "192.168.1.2")
|
||||
# The node that did link is linked; the failed one is not.
|
||||
linked = dict((await conn.exec_driver_sql(
|
||||
"SELECT id, device_id FROM nodes"
|
||||
)).fetchall())
|
||||
assert linked["n1"] is not None
|
||||
assert linked["n2"] is None
|
||||
|
||||
await _insert_node(engine)
|
||||
|
||||
# A boot where the failure persists changes nothing further: the relax is
|
||||
# a one-off, not a rebuild on every start.
|
||||
await database.init_db()
|
||||
async with check.begin() as conn:
|
||||
kept = (await conn.exec_driver_sql(
|
||||
"SELECT status, ip FROM nodes WHERE id='n2'"
|
||||
)).fetchone()
|
||||
assert kept == ("online", "192.168.1.2")
|
||||
assert (await conn.exec_driver_sql(
|
||||
"SELECT COUNT(*) FROM nodes"
|
||||
)).scalar() == 4 # the three seeded, plus the one just approved
|
||||
|
||||
# A later boot retries the backfill: with the failure gone, n2 links and
|
||||
# the columns finally drop.
|
||||
monkeypatch.setattr(inventory_sync, "link_facts", real_link_facts)
|
||||
await database.init_db()
|
||||
async with check.begin() as conn:
|
||||
cols = {c[1] for c in (await conn.exec_driver_sql("PRAGMA table_info(nodes)")).fetchall()}
|
||||
assert "status" not in cols
|
||||
finally:
|
||||
await check.dispose()
|
||||
await engine.dispose()
|
||||
@@ -3,13 +3,13 @@ import uuid
|
||||
|
||||
import pytest
|
||||
|
||||
from app.db.models import PendingDevice
|
||||
from app.db.models import InventoryDevice
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def pending_device(db_session):
|
||||
import uuid
|
||||
device = PendingDevice(
|
||||
device = InventoryDevice(
|
||||
id=str(uuid.uuid4()),
|
||||
ip="192.168.1.100",
|
||||
mac="aa:bb:cc:dd:ee:ff",
|
||||
@@ -39,10 +39,10 @@ async def mem_db():
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def two_pending_devices(db_session):
|
||||
async def two_device_inventory(db_session):
|
||||
devices = []
|
||||
for i in range(2):
|
||||
d = PendingDevice(
|
||||
d = InventoryDevice(
|
||||
id=str(uuid.uuid4()),
|
||||
ip=f"192.168.1.{10 + i}",
|
||||
mac=None,
|
||||
@@ -62,7 +62,7 @@ async def two_pending_devices(db_session):
|
||||
|
||||
@pytest.fixture
|
||||
async def zigbee_pending_device(db_session):
|
||||
device = PendingDevice(
|
||||
device = InventoryDevice(
|
||||
id=str(uuid.uuid4()),
|
||||
ip=None,
|
||||
mac=None,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""Shared builders for scan test suite (pure helpers, no fixtures)."""
|
||||
import uuid
|
||||
|
||||
from app.db.models import Design, Node, PendingDevice
|
||||
from app.db.models import Design, InventoryDevice, Node
|
||||
|
||||
|
||||
async def _add_design(db_session, name: str) -> str:
|
||||
@@ -11,27 +11,58 @@ async def _add_design(db_session, name: str) -> str:
|
||||
return design.id
|
||||
|
||||
|
||||
def _node(design_id: str, *, ip=None, ieee=None, mac=None) -> Node:
|
||||
def _node(design_id: str, *, ip=None, ieee=None, mac=None, device_id=None) -> Node:
|
||||
"""A canvas node. Addresses belong to the inventory row it draws, so pass
|
||||
`device_id`, or let `_node_for` mint the row from the addresses."""
|
||||
return Node(
|
||||
id=str(uuid.uuid4()), label="n", type="server", status="online",
|
||||
ip=ip, mac=mac, ieee_address=ieee, services=[], pos_x=0.0, pos_y=0.0,
|
||||
design_id=design_id,
|
||||
id=str(uuid.uuid4()), label="n", type="server", pos_x=0.0, pos_y=0.0,
|
||||
design_id=design_id, device_id=device_id,
|
||||
)
|
||||
|
||||
|
||||
async def _node_for(db_session, design_id: str, *, ip=None, ieee=None, mac=None, **device_kwargs) -> Node:
|
||||
"""A node plus the inventory row carrying its addresses, linked.
|
||||
|
||||
Reuses a row that already describes these addresses — one device is one row,
|
||||
so a test placing the same host on a second canvas gets a second node, not a
|
||||
second device.
|
||||
"""
|
||||
from app.services.inventory_sync import find_device_for
|
||||
|
||||
device = await find_device_for(db_session, ip=ip, mac=mac, ieee=ieee)
|
||||
if device is None:
|
||||
device = InventoryDevice(
|
||||
id=str(uuid.uuid4()), ip=ip, mac=mac, ieee_address=ieee,
|
||||
status="approved", status_live="online", **device_kwargs,
|
||||
)
|
||||
db_session.add(device)
|
||||
await db_session.flush()
|
||||
node = _node(design_id, device_id=device.id)
|
||||
db_session.add(node)
|
||||
await db_session.commit()
|
||||
return node
|
||||
|
||||
|
||||
async def _seed_zigbee_pending_pair(db_session):
|
||||
"""Create a coordinator Node + a pending device + a link between them."""
|
||||
from app.db.models import Node, PendingDeviceLink
|
||||
from app.db.models import InventoryDeviceLink, Node
|
||||
|
||||
coord_device = InventoryDevice(
|
||||
ieee_address="0xCOORD",
|
||||
friendly_name="Coordinator",
|
||||
suggested_type="zigbee_coordinator",
|
||||
status="approved",
|
||||
)
|
||||
db_session.add(coord_device)
|
||||
await db_session.flush()
|
||||
coord = Node(
|
||||
label="Coordinator",
|
||||
type="zigbee_coordinator",
|
||||
status="unknown",
|
||||
ieee_address="0xCOORD",
|
||||
device_id=coord_device.id,
|
||||
)
|
||||
db_session.add(coord)
|
||||
|
||||
pending = PendingDevice(
|
||||
pending = InventoryDevice(
|
||||
ieee_address="0xR1",
|
||||
friendly_name="router_1",
|
||||
suggested_type="zigbee_router",
|
||||
@@ -42,7 +73,7 @@ async def _seed_zigbee_pending_pair(db_session):
|
||||
db_session.add(pending)
|
||||
|
||||
db_session.add(
|
||||
PendingDeviceLink(
|
||||
InventoryDeviceLink(
|
||||
source_ieee="0xCOORD",
|
||||
target_ieee="0xR1",
|
||||
discovery_source="zigbee",
|
||||
|
||||
@@ -5,14 +5,14 @@ import pytest
|
||||
from httpx import AsyncClient
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.db.models import Design, Node, PendingDevice
|
||||
from tests.scan.helpers import _add_design, _node
|
||||
from app.db.models import Design, InventoryDevice, Node
|
||||
from tests.scan.helpers import _add_design, _node_for
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_canvas_count_ignores_nodes_without_design(client, headers, db_session, pending_device):
|
||||
# A node with no design_id is not "on a canvas".
|
||||
db_session.add(_node(None, ip="192.168.1.100"))
|
||||
await _node_for(db_session, None, ip="192.168.1.100")
|
||||
await db_session.commit()
|
||||
|
||||
res = await client.get("/api/v1/scan/pending", headers=headers)
|
||||
@@ -57,16 +57,17 @@ async def test_approve_device_conflicts_on_existing_ieee_same_design(
|
||||
design = Design(name="d1")
|
||||
db_session.add(design)
|
||||
await db_session.flush()
|
||||
existing = Node(
|
||||
label="sensor", type="zigbee_enddevice", ieee_address="0xZZZ",
|
||||
services=[], design_id=design.id,
|
||||
)
|
||||
db_session.add(existing)
|
||||
device = PendingDevice(
|
||||
device = InventoryDevice(
|
||||
id=str(uuid.uuid4()), ieee_address="0xZZZ", suggested_type="zigbee_enddevice",
|
||||
status="pending", discovery_source="zigbee",
|
||||
)
|
||||
db_session.add(device)
|
||||
await db_session.flush()
|
||||
# The node already on this design draws that very row.
|
||||
existing = Node(
|
||||
label="sensor", type="zigbee_enddevice", device_id=device.id, design_id=design.id,
|
||||
)
|
||||
db_session.add(existing)
|
||||
await db_session.commit()
|
||||
|
||||
res = await client.post(
|
||||
@@ -86,7 +87,7 @@ async def test_approve_device_conflicts_on_existing_ieee_same_design(
|
||||
|
||||
# No second node created; device stays pending until the user decides.
|
||||
nodes = (
|
||||
await db_session.execute(select(Node).where(Node.ieee_address == "0xZZZ"))
|
||||
await db_session.execute(select(Node).join(InventoryDevice, Node.device_id == InventoryDevice.id).where(InventoryDevice.ieee_address == "0xZZZ"))
|
||||
).scalars().all()
|
||||
assert len(nodes) == 1
|
||||
|
||||
@@ -99,15 +100,15 @@ async def test_approve_device_force_creates_duplicate_ieee(
|
||||
design = Design(name="d1")
|
||||
db_session.add(design)
|
||||
await db_session.flush()
|
||||
db_session.add(Node(
|
||||
label="sensor", type="zigbee_enddevice", ieee_address="0xZZZ",
|
||||
services=[], design_id=design.id,
|
||||
))
|
||||
device = PendingDevice(
|
||||
device = InventoryDevice(
|
||||
id=str(uuid.uuid4()), ieee_address="0xZZZ", suggested_type="zigbee_enddevice",
|
||||
status="pending", discovery_source="zigbee",
|
||||
)
|
||||
db_session.add(device)
|
||||
await db_session.flush()
|
||||
db_session.add(Node(
|
||||
label="sensor", type="zigbee_enddevice", device_id=device.id, design_id=design.id,
|
||||
))
|
||||
await db_session.commit()
|
||||
|
||||
res = await client.post(
|
||||
@@ -120,7 +121,7 @@ async def test_approve_device_force_creates_duplicate_ieee(
|
||||
)
|
||||
assert res.status_code == 200
|
||||
nodes = (
|
||||
await db_session.execute(select(Node).where(Node.ieee_address == "0xZZZ"))
|
||||
await db_session.execute(select(Node).join(InventoryDevice, Node.device_id == InventoryDevice.id).where(InventoryDevice.ieee_address == "0xZZZ"))
|
||||
).scalars().all()
|
||||
assert len(nodes) == 2
|
||||
|
||||
@@ -133,8 +134,7 @@ async def test_approve_device_conflicts_on_existing_ip(
|
||||
silently duplicated: the approve returns 409 with the existing node so the
|
||||
UI can ask the user."""
|
||||
design = await _add_design(db_session, "Home")
|
||||
existing = _node(design, ip="192.168.1.100")
|
||||
db_session.add(existing)
|
||||
existing = await _node_for(db_session, design, ip="192.168.1.100")
|
||||
await db_session.commit()
|
||||
|
||||
res = await client.post(
|
||||
@@ -163,10 +163,8 @@ async def test_approve_device_conflicts_on_existing_mac(
|
||||
):
|
||||
"""MAC match (device re-IP'd via DHCP) also triggers the duplicate guard."""
|
||||
design = await _add_design(db_session, "Home")
|
||||
existing = Node(id=str(uuid.uuid4()), label="n", type="server", status="online",
|
||||
ip="10.0.0.9", mac="aa:bb:cc:dd:ee:ff", services=[], design_id=design)
|
||||
db_session.add(existing)
|
||||
await db_session.commit()
|
||||
# The node already on this design draws a row carrying that MAC.
|
||||
await _node_for(db_session, design, ip="10.0.0.9", mac="aa:bb:cc:dd:ee:ff")
|
||||
|
||||
# pending_device carries mac aa:bb:cc:dd:ee:ff but a different ip.
|
||||
res = await client.post(
|
||||
@@ -188,8 +186,7 @@ async def test_approve_device_conflicts_on_ip_in_comma_list(
|
||||
as. Exact-string matching missed it (issue #258); per-token matching catches
|
||||
the duplicate."""
|
||||
design = await _add_design(db_session, "Home")
|
||||
existing = _node(design, ip="fe80::1, 192.168.1.100")
|
||||
db_session.add(existing)
|
||||
existing = await _node_for(db_session, design, ip="fe80::1, 192.168.1.100")
|
||||
await db_session.commit()
|
||||
|
||||
res = await client.post(
|
||||
@@ -212,7 +209,7 @@ async def test_approve_device_no_conflict_on_ip_substring(
|
||||
"""The ip guard must match whole addresses, not substrings: a node at
|
||||
10.0.0.40 is not a duplicate of a device at 10.0.0.4."""
|
||||
design = await _add_design(db_session, "Home")
|
||||
db_session.add(_node(design, ip="10.0.0.40"))
|
||||
await _node_for(db_session, design, ip="10.0.0.40")
|
||||
await db_session.commit()
|
||||
|
||||
res = await client.post(
|
||||
@@ -230,7 +227,7 @@ async def test_approve_device_force_creates_duplicate(
|
||||
):
|
||||
"""force=True (user confirmed) bypasses the guard and creates the node."""
|
||||
design = await _add_design(db_session, "Home")
|
||||
db_session.add(_node(design, ip="192.168.1.100"))
|
||||
await _node_for(db_session, design, ip="192.168.1.100")
|
||||
await db_session.commit()
|
||||
|
||||
res = await client.post(
|
||||
@@ -251,7 +248,7 @@ async def test_approve_device_allows_same_ip_on_other_design(
|
||||
"""The guard is per-design: the same host on a different canvas is fine."""
|
||||
other = await _add_design(db_session, "Lab")
|
||||
target = await _add_design(db_session, "Home")
|
||||
db_session.add(_node(other, ip="192.168.1.100")) # exists on a DIFFERENT design
|
||||
await _node_for(db_session, other, ip="192.168.1.100") # exists on a DIFFERENT design
|
||||
await db_session.commit()
|
||||
|
||||
res = await client.post(
|
||||
@@ -273,13 +270,16 @@ async def test_approve_device_places_already_approved_on_another_design(
|
||||
other = await _add_design(db_session, "Other")
|
||||
target = await _add_design(db_session, "Network Topology")
|
||||
# Device is on `other` already (its global status is "approved").
|
||||
db_session.add(_node(other, ieee="0x00158d0005292b83"))
|
||||
device = PendingDevice(
|
||||
device = InventoryDevice(
|
||||
id=str(uuid.uuid4()), ieee_address="0x00158d0005292b83",
|
||||
suggested_type="zigbee_enddevice", status="approved",
|
||||
discovery_source="zigbee",
|
||||
)
|
||||
db_session.add(device)
|
||||
await db_session.flush()
|
||||
db_session.add(Node(
|
||||
label="sensor", type="zigbee_enddevice", device_id=device.id, design_id=other,
|
||||
))
|
||||
await db_session.commit()
|
||||
|
||||
res = await client.post(
|
||||
@@ -292,7 +292,7 @@ async def test_approve_device_places_already_approved_on_another_design(
|
||||
# A node now exists on the target design too (one per canvas).
|
||||
nodes = (
|
||||
await db_session.execute(
|
||||
select(Node).where(Node.ieee_address == "0x00158d0005292b83")
|
||||
select(Node).join(InventoryDevice, Node.device_id == InventoryDevice.id).where(InventoryDevice.ieee_address == "0x00158d0005292b83")
|
||||
)
|
||||
).scalars().all()
|
||||
assert {n.design_id for n in nodes} == {other, target}
|
||||
@@ -399,8 +399,8 @@ async def test_ignore_device(client: AsyncClient, headers, pending_device):
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_bulk_approve_approves_devices(client: AsyncClient, headers, two_pending_devices):
|
||||
ids = [d.id for d in two_pending_devices]
|
||||
async def test_bulk_approve_approves_devices(client: AsyncClient, headers, two_device_inventory):
|
||||
ids = [d.id for d in two_device_inventory]
|
||||
res = await client.post("/api/v1/scan/pending/bulk-approve", json={"device_ids": ids}, headers=headers)
|
||||
assert res.status_code == 200
|
||||
data = res.json()
|
||||
@@ -418,7 +418,7 @@ async def test_bulk_approve_approves_devices(client: AsyncClient, headers, two_p
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_bulk_approve_places_already_approved_device_on_another_design(
|
||||
client: AsyncClient, headers, db_session, two_pending_devices
|
||||
client: AsyncClient, headers, db_session, two_device_inventory
|
||||
):
|
||||
"""Regression: a device already approved (status='approved', e.g. placed on
|
||||
another canvas) must still get a node on the design being approved onto.
|
||||
@@ -426,7 +426,7 @@ async def test_bulk_approve_places_already_approved_device_on_another_design(
|
||||
Previously bulk-approve filtered status=='pending', so selecting an
|
||||
already-approved device created no node — the user saw fewer nodes than
|
||||
they selected."""
|
||||
ids = [d.id for d in two_pending_devices]
|
||||
ids = [d.id for d in two_device_inventory]
|
||||
design_a = await _add_design(db_session, "Canvas A")
|
||||
design_b = await _add_design(db_session, "Canvas B")
|
||||
|
||||
@@ -458,13 +458,13 @@ async def test_bulk_approve_places_already_approved_device_on_another_design(
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_bulk_approve_skips_device_already_on_target_design(
|
||||
client: AsyncClient, headers, db_session, two_pending_devices
|
||||
client: AsyncClient, headers, db_session, two_device_inventory
|
||||
):
|
||||
"""A device already on the target canvas (same ip) is not placed twice."""
|
||||
ids = [d.id for d in two_pending_devices]
|
||||
ids = [d.id for d in two_device_inventory]
|
||||
design = await _add_design(db_session, "Canvas")
|
||||
# First device already sits on the canvas (matched by ip).
|
||||
db_session.add(_node(design, ip="192.168.1.10"))
|
||||
await _node_for(db_session, design, ip="192.168.1.10")
|
||||
await db_session.commit()
|
||||
|
||||
res = await client.post(
|
||||
@@ -480,20 +480,21 @@ async def test_bulk_approve_skips_device_already_on_target_design(
|
||||
nodes = (
|
||||
await db_session.execute(select(NodeModel).where(NodeModel.design_id == design))
|
||||
).scalars().all()
|
||||
devices = [await db_session.get(InventoryDevice, n.device_id) for n in nodes]
|
||||
# The pre-existing node plus the one newly approved — no duplicate for .10.
|
||||
assert len(nodes) == 2
|
||||
assert sorted(n.ip for n in nodes) == ["192.168.1.10", "192.168.1.11"]
|
||||
assert sorted(d.ip for d in devices) == ["192.168.1.10", "192.168.1.11"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_bulk_approve_skips_device_matching_ip_in_comma_list(
|
||||
client: AsyncClient, headers, db_session, two_pending_devices
|
||||
client: AsyncClient, headers, db_session, two_device_inventory
|
||||
):
|
||||
"""The on-canvas node's ip holds an IPv6 before the IPv4; the device scanned
|
||||
as the plain IPv4 is still recognised as already placed (issue #258)."""
|
||||
ids = [d.id for d in two_pending_devices]
|
||||
ids = [d.id for d in two_device_inventory]
|
||||
design = await _add_design(db_session, "Canvas")
|
||||
db_session.add(_node(design, ip="fe80::1, 192.168.1.10"))
|
||||
await _node_for(db_session, design, ip="fe80::1, 192.168.1.10")
|
||||
await db_session.commit()
|
||||
|
||||
res = await client.post(
|
||||
@@ -509,14 +510,13 @@ async def test_bulk_approve_skips_device_matching_ip_in_comma_list(
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_bulk_approve_reports_skipped_devices(
|
||||
client: AsyncClient, headers, db_session, two_pending_devices
|
||||
client: AsyncClient, headers, db_session, two_device_inventory
|
||||
):
|
||||
"""Bulk can't prompt per-device, so it reports each duplicate it skipped
|
||||
(with the existing node id) instead of silently dropping it."""
|
||||
ids = [d.id for d in two_pending_devices]
|
||||
ids = [d.id for d in two_device_inventory]
|
||||
design = await _add_design(db_session, "Canvas")
|
||||
existing = _node(design, ip="192.168.1.10")
|
||||
db_session.add(existing)
|
||||
existing = await _node_for(db_session, design, ip="192.168.1.10")
|
||||
await db_session.commit()
|
||||
|
||||
res = await client.post(
|
||||
@@ -551,10 +551,14 @@ async def test_approve_device_copies_mac_to_node_and_properties(
|
||||
)
|
||||
assert res.status_code == 200
|
||||
node = (
|
||||
await db_session.execute(select(NodeModel).where(NodeModel.ip == "192.168.1.100"))
|
||||
).scalar_one()
|
||||
assert node.mac == "aa:bb:cc:dd:ee:ff"
|
||||
mac_props = [p for p in node.properties if p["key"] == "MAC"]
|
||||
await db_session.execute(select(NodeModel).where(NodeModel.device_id.is_not(None)))
|
||||
).scalars().first()
|
||||
assert node is not None
|
||||
# The device facts belong to the inventory row the node draws.
|
||||
device = await db_session.get(InventoryDevice, node.device_id)
|
||||
assert device is not None
|
||||
assert device.mac == "aa:bb:cc:dd:ee:ff"
|
||||
mac_props = [p for p in device.properties if p["key"] == "MAC"]
|
||||
assert mac_props == [
|
||||
{"key": "MAC", "value": "aa:bb:cc:dd:ee:ff", "icon": None, "visible": False}
|
||||
]
|
||||
@@ -568,7 +572,7 @@ async def test_bulk_approve_copies_mac_to_node_and_properties(
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.db.models import Node as NodeModel
|
||||
device = PendingDevice(
|
||||
device = InventoryDevice(
|
||||
id=str(uuid.uuid4()),
|
||||
ip="192.168.1.55",
|
||||
mac="11:22:33:44:55:66",
|
||||
@@ -587,28 +591,34 @@ async def test_bulk_approve_copies_mac_to_node_and_properties(
|
||||
)
|
||||
assert res.status_code == 200
|
||||
node = (
|
||||
await db_session.execute(select(NodeModel).where(NodeModel.ip == "192.168.1.55"))
|
||||
).scalar_one()
|
||||
assert node.mac == "11:22:33:44:55:66"
|
||||
mac_props = [p for p in node.properties if p["key"] == "MAC"]
|
||||
await db_session.execute(select(NodeModel).where(NodeModel.device_id.is_not(None)))
|
||||
).scalars().first()
|
||||
assert node is not None
|
||||
# The device facts belong to the inventory row the node draws.
|
||||
device = await db_session.get(InventoryDevice, node.device_id)
|
||||
assert device is not None
|
||||
assert device.mac == "11:22:33:44:55:66"
|
||||
mac_props = [p for p in device.properties if p["key"] == "MAC"]
|
||||
assert mac_props == [
|
||||
{"key": "MAC", "value": "11:22:33:44:55:66", "icon": None, "visible": False}
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_bulk_approve_sets_default_check_method(client: AsyncClient, headers, two_pending_devices, db_session):
|
||||
async def test_bulk_approve_sets_default_check_method(client: AsyncClient, headers, two_device_inventory, db_session):
|
||||
"""Approved devices with an IP must default to ping; otherwise scheduler skips them."""
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.db.models import Node as NodeModel
|
||||
ids = [d.id for d in two_pending_devices]
|
||||
ids = [d.id for d in two_device_inventory]
|
||||
res = await client.post("/api/v1/scan/pending/bulk-approve", json={"device_ids": ids}, headers=headers)
|
||||
assert res.status_code == 200
|
||||
nodes = (await db_session.execute(select(NodeModel))).scalars().all()
|
||||
for n in nodes:
|
||||
if n.ip:
|
||||
assert n.check_method == "ping", f"node {n.id} created without check_method"
|
||||
device = await db_session.get(InventoryDevice, n.device_id)
|
||||
assert device is not None
|
||||
if device.ip:
|
||||
assert device.check_method == "ping", f"device {device.id} has no check_method"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -624,12 +634,14 @@ async def test_approve_device_sets_default_check_method(client: AsyncClient, hea
|
||||
assert res.status_code == 200
|
||||
node = (await db_session.execute(select(NodeModel))).scalars().first()
|
||||
assert node is not None
|
||||
assert node.check_method == "ping"
|
||||
device = await db_session.get(InventoryDevice, node.device_id)
|
||||
assert device is not None
|
||||
assert device.check_method == "ping"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_bulk_approve_skips_already_approved(client: AsyncClient, headers, two_pending_devices):
|
||||
ids = [d.id for d in two_pending_devices]
|
||||
async def test_bulk_approve_skips_already_approved(client: AsyncClient, headers, two_device_inventory):
|
||||
ids = [d.id for d in two_device_inventory]
|
||||
# Approve first device individually first
|
||||
await client.post(
|
||||
f"/api/v1/scan/pending/{ids[0]}/approve",
|
||||
@@ -645,15 +657,15 @@ async def test_bulk_approve_skips_already_approved(client: AsyncClient, headers,
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_bulk_approve_requires_auth(client: AsyncClient, two_pending_devices):
|
||||
ids = [d.id for d in two_pending_devices]
|
||||
async def test_bulk_approve_requires_auth(client: AsyncClient, two_device_inventory):
|
||||
ids = [d.id for d in two_device_inventory]
|
||||
res = await client.post("/api/v1/scan/pending/bulk-approve", json={"device_ids": ids})
|
||||
assert res.status_code == 401
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_bulk_hide_hides_devices(client: AsyncClient, headers, two_pending_devices):
|
||||
ids = [d.id for d in two_pending_devices]
|
||||
async def test_bulk_hide_hides_devices(client: AsyncClient, headers, two_device_inventory):
|
||||
ids = [d.id for d in two_device_inventory]
|
||||
res = await client.post("/api/v1/scan/pending/bulk-hide", json={"device_ids": ids}, headers=headers)
|
||||
assert res.status_code == 200
|
||||
data = res.json()
|
||||
@@ -665,8 +677,8 @@ async def test_bulk_hide_hides_devices(client: AsyncClient, headers, two_pending
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_bulk_hide_skips_non_pending(client: AsyncClient, headers, two_pending_devices):
|
||||
ids = [d.id for d in two_pending_devices]
|
||||
async def test_bulk_hide_skips_non_pending(client: AsyncClient, headers, two_device_inventory):
|
||||
ids = [d.id for d in two_device_inventory]
|
||||
# Hide first device individually first
|
||||
await client.post(f"/api/v1/scan/pending/{ids[0]}/hide", headers=headers)
|
||||
# Bulk hide both — first is already hidden (not pending anymore)
|
||||
@@ -678,8 +690,8 @@ async def test_bulk_hide_skips_non_pending(client: AsyncClient, headers, two_pen
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_bulk_hide_requires_auth(client: AsyncClient, two_pending_devices):
|
||||
ids = [d.id for d in two_pending_devices]
|
||||
async def test_bulk_hide_requires_auth(client: AsyncClient, two_device_inventory):
|
||||
ids = [d.id for d in two_device_inventory]
|
||||
res = await client.post("/api/v1/scan/pending/bulk-hide", json={"device_ids": ids})
|
||||
assert res.status_code == 401
|
||||
|
||||
@@ -690,7 +702,7 @@ async def test_bulk_approve_targets_requested_design(client, headers, db_session
|
||||
first design — otherwise approved devices land on the wrong canvas."""
|
||||
first = await _add_design(db_session, "Default") # first design (fallback)
|
||||
active = await _add_design(db_session, "zwave") # the design the user is on
|
||||
dev = PendingDevice(
|
||||
dev = InventoryDevice(
|
||||
id=str(uuid.uuid4()),
|
||||
ieee_address="zwave-H-2",
|
||||
friendly_name="Living Room Plug",
|
||||
@@ -713,11 +725,14 @@ async def test_bulk_approve_targets_requested_design(client, headers, db_session
|
||||
assert res.json()["approved"] == 1
|
||||
|
||||
node = (
|
||||
await db_session.execute(select(Node).where(Node.ieee_address == "zwave-H-2"))
|
||||
await db_session.execute(select(Node).join(InventoryDevice, Node.device_id == InventoryDevice.id).where(InventoryDevice.ieee_address == "zwave-H-2"))
|
||||
).scalar_one()
|
||||
assert node.design_id == active
|
||||
assert node.design_id != first
|
||||
# Z-Wave device → online + Z-Wave property rows, no ICMP check.
|
||||
assert node.status == "online"
|
||||
assert node.check_method == "none"
|
||||
assert {p["key"] for p in node.properties} == {"Z-Wave ID", "Vendor", "Model"}
|
||||
# Z-Wave device → online + Z-Wave property rows, no ICMP check. All of that
|
||||
# is the device's, so it is read off the row the node draws.
|
||||
device = await db_session.get(InventoryDevice, node.device_id)
|
||||
assert device is not None
|
||||
assert device.status_live == "online"
|
||||
assert device.check_method == "none"
|
||||
assert {p["key"] for p in device.properties} == {"Z-Wave ID", "Vendor", "Model"}
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
"""Editing an inventory row: PATCH /scan/pending/{id} and the widened create.
|
||||
|
||||
The inventory row owns the device facts, so it has to be editable on its own —
|
||||
not only through a canvas node.
|
||||
"""
|
||||
import pytest
|
||||
from httpx import AsyncClient
|
||||
|
||||
from app.db.models import InventoryDevice
|
||||
|
||||
|
||||
async def _seed(db_session, **kwargs) -> InventoryDevice:
|
||||
device = InventoryDevice(
|
||||
ip="192.168.1.10",
|
||||
mac="aa:bb:cc:11:22:33",
|
||||
hostname="nas",
|
||||
services=[{"port": 22, "protocol": "tcp", "service_name": "ssh"}],
|
||||
suggested_type="nas",
|
||||
status="pending",
|
||||
discovery_source="arp",
|
||||
discovery_sources=["arp"],
|
||||
properties=[{"key": "Rack", "value": "A1", "icon": None, "visible": True}],
|
||||
**kwargs,
|
||||
)
|
||||
db_session.add(device)
|
||||
await db_session.commit()
|
||||
return device
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_update_pending_requires_auth(client: AsyncClient, db_session):
|
||||
device = await _seed(db_session)
|
||||
res = await client.patch(f"/api/v1/scan/pending/{device.id}", json={"hostname": "x"})
|
||||
assert res.status_code == 401
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_update_pending_edits_curated_fields(client: AsyncClient, headers, db_session):
|
||||
device = await _seed(db_session)
|
||||
res = await client.patch(
|
||||
f"/api/v1/scan/pending/{device.id}",
|
||||
headers=headers,
|
||||
json={
|
||||
"label": "Big NAS",
|
||||
"type": "nas",
|
||||
"notes": "in the garage rack",
|
||||
"cpu_count": 4,
|
||||
"cpu_model": "N5105",
|
||||
"ram_gb": 16.0,
|
||||
"disk_gb": 4000.0,
|
||||
"show_hardware": True,
|
||||
"check_method": "http",
|
||||
"check_target": "http://192.168.1.10:5000",
|
||||
"properties": [
|
||||
{"key": "Rack", "value": "B2", "icon": None, "visible": True},
|
||||
{"key": "Owner", "value": "me", "icon": None, "visible": False},
|
||||
],
|
||||
"services": [
|
||||
{"port": 22, "protocol": "tcp", "service_name": "ssh"},
|
||||
{"port": 5000, "protocol": "tcp", "service_name": "http"},
|
||||
],
|
||||
},
|
||||
)
|
||||
assert res.status_code == 200
|
||||
data = res.json()
|
||||
assert data["label"] == "Big NAS"
|
||||
assert data["notes"] == "in the garage rack"
|
||||
assert data["cpu_count"] == 4
|
||||
assert data["ram_gb"] == 16.0
|
||||
assert data["show_hardware"] is True
|
||||
assert data["check_method"] == "http"
|
||||
assert len(data["properties"]) == 2
|
||||
assert len(data["services"]) == 2
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_update_pending_is_partial(client: AsyncClient, headers, db_session):
|
||||
"""Sending one field must not clear the others."""
|
||||
device = await _seed(db_session)
|
||||
res = await client.patch(
|
||||
f"/api/v1/scan/pending/{device.id}", headers=headers, json={"notes": "only this"}
|
||||
)
|
||||
assert res.status_code == 200
|
||||
data = res.json()
|
||||
assert data["notes"] == "only this"
|
||||
assert data["hostname"] == "nas"
|
||||
assert data["ip"] == "192.168.1.10"
|
||||
assert data["mac"] == "aa:bb:cc:11:22:33"
|
||||
assert data["suggested_type"] == "nas"
|
||||
assert len(data["services"]) == 1
|
||||
assert data["properties"][0]["key"] == "Rack"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_update_pending_normalizes_mac(client: AsyncClient, headers, db_session):
|
||||
device = await _seed(db_session)
|
||||
res = await client.patch(
|
||||
f"/api/v1/scan/pending/{device.id}", headers=headers, json={"mac": "AA-BB-CC-99-88-77"}
|
||||
)
|
||||
assert res.status_code == 200
|
||||
assert res.json()["mac"] == "aa:bb:cc:99:88:77"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_update_pending_leaves_lifecycle_alone(client: AsyncClient, headers, db_session):
|
||||
"""`status` is owned by approve/hide, not by the edit modal."""
|
||||
device = await _seed(db_session)
|
||||
res = await client.patch(
|
||||
f"/api/v1/scan/pending/{device.id}",
|
||||
headers=headers,
|
||||
json={"label": "x", "status": "approved", "discovery_source": "manual"},
|
||||
)
|
||||
assert res.status_code == 200
|
||||
data = res.json()
|
||||
assert data["label"] == "x"
|
||||
assert data["status"] == "pending"
|
||||
assert data["discovery_source"] == "arp"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_update_pending_unknown_id(client: AsyncClient, headers):
|
||||
res = await client.patch("/api/v1/scan/pending/nope", headers=headers, json={"notes": "x"})
|
||||
assert res.status_code == 404
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_pending_accepts_curated_fields(client: AsyncClient, headers):
|
||||
"""A hand-made entry carries everything the modal shows, no PATCH round trip."""
|
||||
res = await client.post(
|
||||
"/api/v1/scan/pending",
|
||||
headers=headers,
|
||||
json={
|
||||
"hostname": "patch-panel",
|
||||
"os": "n/a",
|
||||
"label": "Patch panel 24p",
|
||||
"type": "switch",
|
||||
"notes": "passive",
|
||||
"services": [{"port": 80, "protocol": "tcp", "service_name": "http"}],
|
||||
"friendly_name": "PP-1",
|
||||
"device_subtype": "passive",
|
||||
"check_method": "none",
|
||||
"discovery_source": "manual",
|
||||
},
|
||||
)
|
||||
assert res.status_code == 201
|
||||
data = res.json()
|
||||
assert data["label"] == "Patch panel 24p"
|
||||
assert data["type"] == "switch"
|
||||
assert data["os"] == "n/a"
|
||||
assert data["notes"] == "passive"
|
||||
assert data["friendly_name"] == "PP-1"
|
||||
assert data["services"][0]["port"] == 80
|
||||
assert data["status"] == "pending"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_legacy_row_defaults_are_coerced(client: AsyncClient, headers, db_session):
|
||||
"""Rows predating the 3.3.0 columns read back with defaults, not nulls."""
|
||||
device = await _seed(db_session)
|
||||
res = await client.get("/api/v1/scan/pending", headers=headers)
|
||||
assert res.status_code == 200
|
||||
row = next(d for d in res.json() if d["id"] == device.id)
|
||||
assert row["status_live"] == "unknown"
|
||||
assert row["show_hardware"] is False
|
||||
assert row["label"] is None
|
||||
@@ -5,7 +5,7 @@ import pytest
|
||||
from httpx import AsyncClient
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.db.models import Node, PendingDevice
|
||||
from app.db.models import InventoryDevice, Node
|
||||
from tests.scan.helpers import _add_design, _seed_zigbee_pending_pair
|
||||
|
||||
|
||||
@@ -31,9 +31,13 @@ async def test_approve_zigbee_device_populates_properties(
|
||||
)
|
||||
assert res.status_code == 200
|
||||
node = (
|
||||
await db_session.execute(select(NodeModel).where(NodeModel.ieee_address == "0xABCDEF"))
|
||||
).scalar_one()
|
||||
keys = {p["key"]: p["value"] for p in node.properties}
|
||||
await db_session.execute(select(NodeModel).where(NodeModel.device_id.is_not(None)))
|
||||
).scalars().first()
|
||||
assert node is not None
|
||||
# The device facts belong to the inventory row the node draws.
|
||||
device = await db_session.get(InventoryDevice, node.device_id)
|
||||
assert device is not None
|
||||
keys = {p["key"]: p["value"] for p in device.properties}
|
||||
assert keys == {
|
||||
"IEEE": "0xABCDEF",
|
||||
"Vendor": "IKEA",
|
||||
@@ -56,14 +60,18 @@ async def test_bulk_approve_zigbee_populates_properties(
|
||||
)
|
||||
assert res.status_code == 200
|
||||
node = (
|
||||
await db_session.execute(select(NodeModel).where(NodeModel.ieee_address == "0xABCDEF"))
|
||||
).scalar_one()
|
||||
keys = {p["key"]: p["value"] for p in node.properties}
|
||||
await db_session.execute(select(NodeModel).where(NodeModel.device_id.is_not(None)))
|
||||
).scalars().first()
|
||||
assert node is not None
|
||||
# The device facts belong to the inventory row the node draws.
|
||||
device = await db_session.get(InventoryDevice, node.device_id)
|
||||
assert device is not None
|
||||
keys = {p["key"]: p["value"] for p in device.properties}
|
||||
assert keys["IEEE"] == "0xABCDEF"
|
||||
assert keys["Vendor"] == "IKEA"
|
||||
assert keys["Model"] == "TRADFRI"
|
||||
assert keys["LQI"] == "180"
|
||||
assert node.check_method == "none"
|
||||
assert device.check_method == "none"
|
||||
|
||||
|
||||
def test_build_mac_property_returns_hidden_row():
|
||||
@@ -133,9 +141,13 @@ async def test_approve_device_does_not_duplicate_mac_property(
|
||||
)
|
||||
assert res.status_code == 200
|
||||
node = (
|
||||
await db_session.execute(select(NodeModel).where(NodeModel.ip == "192.168.1.100"))
|
||||
).scalar_one()
|
||||
mac_props = [p for p in node.properties if p["key"] == "MAC"]
|
||||
await db_session.execute(select(NodeModel).where(NodeModel.device_id.is_not(None)))
|
||||
).scalars().first()
|
||||
assert node is not None
|
||||
# The device facts belong to the inventory row the node draws.
|
||||
device = await db_session.get(InventoryDevice, node.device_id)
|
||||
assert device is not None
|
||||
mac_props = [p for p in device.properties if p["key"] == "MAC"]
|
||||
assert len(mac_props) == 1
|
||||
# User's visibility choice is preserved.
|
||||
assert mac_props[0]["visible"] is True
|
||||
@@ -184,7 +196,7 @@ async def test_approve_zigbee_skips_duplicate_edge(
|
||||
"""Re-running the resolution does not create a second edge for the same pair."""
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.db.models import Edge, PendingDevice, PendingDeviceLink
|
||||
from app.db.models import Edge, InventoryDevice, InventoryDeviceLink
|
||||
|
||||
coord, pending = await _seed_zigbee_pending_pair(db_session)
|
||||
body = {"label": "router_1", "type": "zigbee_router", "ip": None, "status": "unknown", "services": []}
|
||||
@@ -193,7 +205,7 @@ async def test_approve_zigbee_skips_duplicate_edge(
|
||||
# Simulate a second pending row + link between same coord and a new device,
|
||||
# but keep an existing edge in place to verify dedupe also handles
|
||||
# the swapped-direction case.
|
||||
new_pending = PendingDevice(
|
||||
new_pending = InventoryDevice(
|
||||
ieee_address="0xR1B",
|
||||
friendly_name="r1b",
|
||||
suggested_type="zigbee_router",
|
||||
@@ -202,7 +214,7 @@ async def test_approve_zigbee_skips_duplicate_edge(
|
||||
)
|
||||
db_session.add(new_pending)
|
||||
db_session.add(
|
||||
PendingDeviceLink(source_ieee="0xCOORD", target_ieee="0xR1B", discovery_source="zigbee")
|
||||
InventoryDeviceLink(source_ieee="0xCOORD", target_ieee="0xR1B", discovery_source="zigbee")
|
||||
)
|
||||
await db_session.commit()
|
||||
res = await client.post(
|
||||
@@ -220,16 +232,16 @@ async def test_approve_zigbee_skips_when_other_endpoint_still_pending(
|
||||
"""Both endpoints pending → no edge yet, link row preserved for later."""
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.db.models import Edge, PendingDevice, PendingDeviceLink
|
||||
from app.db.models import Edge, InventoryDevice, InventoryDeviceLink
|
||||
|
||||
a = PendingDevice(
|
||||
a = InventoryDevice(
|
||||
ieee_address="0xA",
|
||||
friendly_name="a",
|
||||
suggested_type="zigbee_router",
|
||||
status="pending",
|
||||
discovery_source="zigbee",
|
||||
)
|
||||
b = PendingDevice(
|
||||
b = InventoryDevice(
|
||||
ieee_address="0xB",
|
||||
friendly_name="b",
|
||||
suggested_type="zigbee_enddevice",
|
||||
@@ -238,7 +250,7 @@ async def test_approve_zigbee_skips_when_other_endpoint_still_pending(
|
||||
)
|
||||
db_session.add_all([a, b])
|
||||
db_session.add(
|
||||
PendingDeviceLink(source_ieee="0xA", target_ieee="0xB", discovery_source="zigbee")
|
||||
InventoryDeviceLink(source_ieee="0xA", target_ieee="0xB", discovery_source="zigbee")
|
||||
)
|
||||
await db_session.commit()
|
||||
|
||||
@@ -258,7 +270,7 @@ async def test_approve_zigbee_skips_when_other_endpoint_still_pending(
|
||||
|
||||
edges = (await db_session.execute(select(Edge))).scalars().all()
|
||||
assert edges == []
|
||||
links = (await db_session.execute(select(PendingDeviceLink))).scalars().all()
|
||||
links = (await db_session.execute(select(InventoryDeviceLink))).scalars().all()
|
||||
assert len(links) == 1 # preserved for later resolution
|
||||
|
||||
|
||||
@@ -271,16 +283,16 @@ async def test_approve_zigbee_resolves_link_after_second_approval(
|
||||
be re-approved onto another canvas — it's topology, wiped only on reimport."""
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.db.models import Edge, PendingDevice, PendingDeviceLink
|
||||
from app.db.models import Edge, InventoryDevice, InventoryDeviceLink
|
||||
|
||||
a = PendingDevice(
|
||||
a = InventoryDevice(
|
||||
ieee_address="0xA",
|
||||
friendly_name="a",
|
||||
suggested_type="zigbee_router",
|
||||
status="pending",
|
||||
discovery_source="zigbee",
|
||||
)
|
||||
b = PendingDevice(
|
||||
b = InventoryDevice(
|
||||
ieee_address="0xB",
|
||||
friendly_name="b",
|
||||
suggested_type="zigbee_enddevice",
|
||||
@@ -289,7 +301,7 @@ async def test_approve_zigbee_resolves_link_after_second_approval(
|
||||
)
|
||||
db_session.add_all([a, b])
|
||||
db_session.add(
|
||||
PendingDeviceLink(source_ieee="0xA", target_ieee="0xB", discovery_source="zigbee")
|
||||
InventoryDeviceLink(source_ieee="0xA", target_ieee="0xB", discovery_source="zigbee")
|
||||
)
|
||||
await db_session.commit()
|
||||
|
||||
@@ -300,14 +312,14 @@ async def test_approve_zigbee_resolves_link_after_second_approval(
|
||||
|
||||
edges = (await db_session.execute(select(Edge))).scalars().all()
|
||||
assert len(edges) == 1
|
||||
links = (await db_session.execute(select(PendingDeviceLink))).scalars().all()
|
||||
links = (await db_session.execute(select(InventoryDeviceLink))).scalars().all()
|
||||
assert len(links) == 1 # retained for re-approval onto other canvases
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_single_approve_zwave_sets_wireless_fields(client, headers, db_session):
|
||||
active = await _add_design(db_session, "zwave")
|
||||
dev = PendingDevice(
|
||||
dev = InventoryDevice(
|
||||
id=str(uuid.uuid4()),
|
||||
ieee_address="zwave-H-9",
|
||||
friendly_name="Door Sensor",
|
||||
@@ -328,9 +340,13 @@ async def test_single_approve_zwave_sets_wireless_fields(client, headers, db_ses
|
||||
assert res.status_code == 200
|
||||
|
||||
node = (
|
||||
await db_session.execute(select(Node).where(Node.ieee_address == "zwave-H-9"))
|
||||
await db_session.execute(select(Node).join(InventoryDevice, Node.device_id == InventoryDevice.id).where(InventoryDevice.ieee_address == "zwave-H-9"))
|
||||
).scalar_one()
|
||||
assert node.design_id == active
|
||||
assert node.status == "online"
|
||||
assert node.check_method == "none"
|
||||
assert any(p["key"] == "Z-Wave ID" for p in node.properties)
|
||||
node = (await db_session.execute(select(Node))).scalars().first()
|
||||
assert node is not None
|
||||
device = await db_session.get(InventoryDevice, node.device_id)
|
||||
assert device is not None
|
||||
assert device.status_live == "online"
|
||||
assert device.check_method == "none"
|
||||
assert any(p["key"] == "Z-Wave ID" for p in device.properties)
|
||||
|
||||
@@ -6,8 +6,8 @@ from unittest.mock import AsyncMock, patch
|
||||
import pytest
|
||||
from httpx import AsyncClient
|
||||
|
||||
from app.db.models import PendingDevice
|
||||
from tests.scan.helpers import _add_design, _node
|
||||
from app.db.models import InventoryDevice
|
||||
from tests.scan.helpers import _add_design, _node_for
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -55,7 +55,7 @@ async def test_canvas_count_matches_ip_in_comma_list(client, headers, db_session
|
||||
# Node.ip holds several comma-separated addresses (IPv6 added first). The
|
||||
# device scanned as the plain IPv4 must still correlate (issue #258).
|
||||
d1 = await _add_design(db_session, "Home")
|
||||
db_session.add(_node(d1, ip="fe80::1, 192.168.1.100"))
|
||||
await _node_for(db_session, d1, ip="fe80::1, 192.168.1.100")
|
||||
await db_session.commit()
|
||||
|
||||
data = (await client.get("/api/v1/scan/pending", headers=headers)).json()
|
||||
@@ -67,7 +67,7 @@ async def test_canvas_count_correlates_by_mac(client, headers, db_session, pendi
|
||||
# Node's ip differs entirely (user edited it) but the MAC still matches:
|
||||
# the device is on the canvas (issue #258, MAC is the stable identifier).
|
||||
d1 = await _add_design(db_session, "Home")
|
||||
db_session.add(_node(d1, ip="10.9.9.9", mac="aa:bb:cc:dd:ee:ff"))
|
||||
await _node_for(db_session, d1, ip="10.9.9.9", mac="aa:bb:cc:dd:ee:ff")
|
||||
await db_session.commit()
|
||||
|
||||
data = (await client.get("/api/v1/scan/pending", headers=headers)).json()
|
||||
@@ -79,8 +79,8 @@ async def test_canvas_count_counts_distinct_designs_by_ip(client, headers, db_se
|
||||
# Same IP placed on two different canvases → canvas_count == 2.
|
||||
d1 = await _add_design(db_session, "Home")
|
||||
d2 = await _add_design(db_session, "Lab")
|
||||
db_session.add(_node(d1, ip="192.168.1.100"))
|
||||
db_session.add(_node(d2, ip="192.168.1.100"))
|
||||
await _node_for(db_session, d1, ip="192.168.1.100")
|
||||
await _node_for(db_session, d2, ip="192.168.1.100")
|
||||
await db_session.commit()
|
||||
|
||||
res = await client.get("/api/v1/scan/pending", headers=headers)
|
||||
@@ -91,13 +91,13 @@ async def test_canvas_count_counts_distinct_designs_by_ip(client, headers, db_se
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_canvas_count_correlates_by_ieee(client, headers, db_session):
|
||||
device = PendingDevice(
|
||||
device = InventoryDevice(
|
||||
id=str(uuid.uuid4()), ieee_address="0x00124b001", discovery_source="zigbee",
|
||||
suggested_type="zigbee_enddevice", services=[], status="pending",
|
||||
)
|
||||
db_session.add(device)
|
||||
d1 = await _add_design(db_session, "Zigbee")
|
||||
db_session.add(_node(d1, ieee="0x00124b001"))
|
||||
await _node_for(db_session, d1, ieee="0x00124b001")
|
||||
await db_session.commit()
|
||||
|
||||
res = await client.get("/api/v1/scan/pending", headers=headers)
|
||||
@@ -120,10 +120,13 @@ async def test_pending_device_without_node_has_null_node_timestamps(client, head
|
||||
@pytest.mark.asyncio
|
||||
async def test_pending_device_exposes_linked_node_timestamps(client, headers, db_session, pending_device):
|
||||
d1 = await _add_design(db_session, "Home")
|
||||
node = _node(d1, ip="192.168.1.100")
|
||||
node.last_scan = datetime(2026, 6, 1, 8, 30, tzinfo=timezone.utc)
|
||||
node.last_seen = datetime(2026, 6, 25, 9, 15, tzinfo=timezone.utc)
|
||||
db_session.add(node)
|
||||
node = await _node_for(db_session, d1, ip="192.168.1.100")
|
||||
# When the scanner last saw the device, and when it last answered, are facts
|
||||
# about the device — they live on its row, not on any one drawing of it.
|
||||
device = await db_session.get(InventoryDevice, node.device_id)
|
||||
assert device is not None
|
||||
device.last_scan = datetime(2026, 6, 1, 8, 30, tzinfo=timezone.utc)
|
||||
device.last_seen = datetime(2026, 6, 25, 9, 15, tzinfo=timezone.utc)
|
||||
await db_session.commit()
|
||||
|
||||
data = (await client.get("/api/v1/scan/pending", headers=headers)).json()[0]
|
||||
@@ -139,18 +142,21 @@ async def test_node_timestamps_aggregate_across_matches(client, headers, db_sess
|
||||
# last_scan takes the NEWEST.
|
||||
d1 = await _add_design(db_session, "Home")
|
||||
d2 = await _add_design(db_session, "Lab")
|
||||
older = _node(d1, ip="192.168.1.100")
|
||||
older = await _node_for(db_session, d1, ip="192.168.1.100")
|
||||
older.created_at = datetime(2026, 1, 1, 0, 0, tzinfo=timezone.utc)
|
||||
older.last_scan = datetime(2026, 3, 1, 0, 0, tzinfo=timezone.utc)
|
||||
newer = _node(d2, ip="192.168.1.100")
|
||||
newer = await _node_for(db_session, d2, ip="192.168.1.100")
|
||||
newer.created_at = datetime(2026, 5, 1, 0, 0, tzinfo=timezone.utc)
|
||||
newer.last_scan = datetime(2026, 6, 1, 0, 0, tzinfo=timezone.utc)
|
||||
# Both nodes draw the one row, which carries the scan observation.
|
||||
assert older.device_id == newer.device_id
|
||||
device = await db_session.get(InventoryDevice, older.device_id)
|
||||
assert device is not None
|
||||
device.last_scan = datetime(2026, 6, 1, 0, 0, tzinfo=timezone.utc)
|
||||
db_session.add_all([older, newer])
|
||||
await db_session.commit()
|
||||
|
||||
data = (await client.get("/api/v1/scan/pending", headers=headers)).json()[0]
|
||||
assert data["node_created_at"].startswith("2026-01-01") # oldest
|
||||
assert data["node_last_scan"].startswith("2026-06-01") # newest
|
||||
assert data["node_created_at"].startswith("2026-01-01") # oldest node
|
||||
assert data["node_last_scan"].startswith("2026-06-01") # off the device row
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -260,3 +266,151 @@ async def test_update_scan_config_persists_deep_scan(client: AsyncClient, header
|
||||
)
|
||||
assert res.status_code == 200
|
||||
assert saved == {"http_ranges": ["9000-9100"], "probe": True}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_pending_normalizes_the_mac(client: AsyncClient, headers):
|
||||
# Dedup compares MACs by equality, so a hand-typed entry in any other
|
||||
# notation would never match the scanned row and approve would build a
|
||||
# duplicate node.
|
||||
res = await client.post(
|
||||
"/api/v1/scan/pending",
|
||||
json={
|
||||
"hostname": "printer",
|
||||
"mac": "AA-BB-CC-11-22-33",
|
||||
"discovery_source": "manual",
|
||||
},
|
||||
headers=headers,
|
||||
)
|
||||
assert res.status_code == 201, res.text
|
||||
assert res.json()["mac"] == "aa:bb:cc:11:22:33"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_pending_keeps_a_missing_mac_null(client: AsyncClient, headers):
|
||||
res = await client.post(
|
||||
"/api/v1/scan/pending",
|
||||
json={"hostname": "no-mac", "discovery_source": "manual"},
|
||||
headers=headers,
|
||||
)
|
||||
assert res.status_code == 201, res.text
|
||||
assert res.json()["mac"] is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_pending_unhides_the_row_it_merges_into(client: AsyncClient, headers, db_session):
|
||||
"""Adding a device by hand outranks an earlier hide of the same host.
|
||||
|
||||
One device is one row, hidden ones included — but merging into a hidden row
|
||||
and leaving it hidden answers 201 while nothing appears in the inventory, so
|
||||
the add reads as a no-op.
|
||||
"""
|
||||
db_session.add(InventoryDevice(id="d-1", ip="192.168.1.50", status="hidden"))
|
||||
await db_session.commit()
|
||||
|
||||
res = await client.post(
|
||||
"/api/v1/scan/pending",
|
||||
json={"ip": "192.168.1.50", "hostname": "printer", "discovery_source": "manual"},
|
||||
headers=headers,
|
||||
)
|
||||
assert res.status_code == 201, res.text
|
||||
assert res.json()["id"] == "d-1"
|
||||
assert res.json()["status"] == "pending"
|
||||
|
||||
listed = (await client.get("/api/v1/scan/pending", headers=headers)).json()
|
||||
assert [d["id"] for d in listed] == ["d-1"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_pending_leaves_an_approved_row_approved(client: AsyncClient, headers, db_session):
|
||||
"""Only `hidden` is lifted — a merge must not walk a device back down the
|
||||
lifecycle and re-queue something already on a canvas."""
|
||||
db_session.add(InventoryDevice(id="d-1", ip="192.168.1.51", status="approved"))
|
||||
await db_session.commit()
|
||||
|
||||
res = await client.post(
|
||||
"/api/v1/scan/pending",
|
||||
json={"ip": "192.168.1.51", "hostname": "nas", "discovery_source": "manual"},
|
||||
headers=headers,
|
||||
)
|
||||
assert res.status_code == 201, res.text
|
||||
assert res.json()["status"] == "approved"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_delete_pending_removes_one_entry(client: AsyncClient, headers, pending_device):
|
||||
# The rack canvas drops the placeholder it created for a plate once that
|
||||
# plate is pointed at a real inventory row.
|
||||
res = await client.delete(f"/api/v1/scan/pending/{pending_device.id}", headers=headers)
|
||||
assert res.status_code == 200, res.text
|
||||
assert res.json() == {"deleted": True}
|
||||
|
||||
listed = (await client.get("/api/v1/scan/pending", headers=headers)).json()
|
||||
assert listed == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_delete_pending_unknown_is_404(client: AsyncClient, headers):
|
||||
res = await client.delete(f"/api/v1/scan/pending/{uuid.uuid4()}", headers=headers)
|
||||
assert res.status_code == 404
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_delete_pending_requires_auth(client: AsyncClient, pending_device):
|
||||
res = await client.delete(f"/api/v1/scan/pending/{pending_device.id}")
|
||||
assert res.status_code == 401
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_delete_pending_refuses_a_mounted_device(client: AsyncClient, headers, pending_device):
|
||||
# `rack_devices.device_id` is ON DELETE SET NULL: without this guard the
|
||||
# delete would strip the mount of its device instead of erroring.
|
||||
design = (
|
||||
await client.post(
|
||||
"/api/v1/designs",
|
||||
json={"name": "Rack Room", "icon": "server", "design_type": "rack"},
|
||||
headers=headers,
|
||||
)
|
||||
).json()["id"]
|
||||
saved = await client.post(
|
||||
"/api/v1/racks/save",
|
||||
json={
|
||||
"design_id": design,
|
||||
"racks": [
|
||||
{
|
||||
"id": "rack-1",
|
||||
"name": "Main",
|
||||
"u_height": 12,
|
||||
"width_standard": "19",
|
||||
"numbering": "bottom-up",
|
||||
"style": {},
|
||||
"pos_x": 0,
|
||||
"pos_y": 0,
|
||||
}
|
||||
],
|
||||
"devices": [
|
||||
{
|
||||
"id": "dev-1",
|
||||
"rack_id": "rack-1",
|
||||
"device_id": pending_device.id,
|
||||
"label": "my-server",
|
||||
"u_start": 1,
|
||||
"u_height": 1,
|
||||
"col_start": 0,
|
||||
"col_span": 12,
|
||||
"faceplate_id": "server-1u",
|
||||
"status": "unknown",
|
||||
"ports": [],
|
||||
}
|
||||
],
|
||||
"cables": [],
|
||||
"viewport": {"x": 0, "y": 0, "zoom": 1},
|
||||
},
|
||||
headers=headers,
|
||||
)
|
||||
assert saved.status_code == 200, saved.text
|
||||
|
||||
res = await client.delete(f"/api/v1/scan/pending/{pending_device.id}", headers=headers)
|
||||
assert res.status_code == 409
|
||||
listed = (await client.get("/api/v1/scan/pending", headers=headers)).json()
|
||||
assert [d["id"] for d in listed] == [pending_device.id]
|
||||
|
||||
@@ -7,7 +7,7 @@ from httpx import AsyncClient
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.db.models import Node, PendingDevice, ScanRun
|
||||
from app.db.models import InventoryDevice, Node, ScanRun
|
||||
from app.services.scanner import _cancelled_runs, request_cancel, run_scan
|
||||
|
||||
|
||||
@@ -118,7 +118,7 @@ async def test_run_scan_creates_new_pending_device(db_session: AsyncSession):
|
||||
await run_scan(["192.168.1.0/24"], db_session, run_id)
|
||||
|
||||
result = await db_session.execute(
|
||||
select(PendingDevice).where(PendingDevice.ip == "192.168.1.50")
|
||||
select(InventoryDevice).where(InventoryDevice.ip == "192.168.1.50")
|
||||
)
|
||||
device = result.scalar_one_or_none()
|
||||
assert device is not None
|
||||
@@ -131,17 +131,7 @@ async def test_run_scan_creates_new_pending_device(db_session: AsyncSession):
|
||||
async def test_run_scan_keeps_stale_pending_for_canvas_nodes(db_session: AsyncSession):
|
||||
"""Pending devices whose IP is already on a canvas are NOT purged — they stay
|
||||
in the inventory and are surfaced with an "In N canvas" badge."""
|
||||
node = Node(
|
||||
id=str(uuid.uuid4()),
|
||||
label="Existing Server",
|
||||
type="server",
|
||||
ip="192.168.1.50",
|
||||
status="online",
|
||||
services=[],
|
||||
pos_x=0.0,
|
||||
pos_y=0.0,
|
||||
)
|
||||
stale = PendingDevice(
|
||||
stale = InventoryDevice(
|
||||
id=str(uuid.uuid4()),
|
||||
ip="192.168.1.50",
|
||||
mac=None,
|
||||
@@ -151,8 +141,17 @@ async def test_run_scan_keeps_stale_pending_for_canvas_nodes(db_session: AsyncSe
|
||||
suggested_type="generic",
|
||||
status="pending",
|
||||
)
|
||||
db_session.add(node)
|
||||
db_session.add(stale)
|
||||
await db_session.flush()
|
||||
# A canvas already draws that device.
|
||||
db_session.add(Node(
|
||||
id=str(uuid.uuid4()),
|
||||
label="Existing Server",
|
||||
type="server",
|
||||
device_id=stale.id,
|
||||
pos_x=0.0,
|
||||
pos_y=0.0,
|
||||
))
|
||||
await db_session.commit()
|
||||
|
||||
run_id = str(uuid.uuid4())
|
||||
@@ -167,26 +166,30 @@ async def test_run_scan_keeps_stale_pending_for_canvas_nodes(db_session: AsyncSe
|
||||
await run_scan(["192.168.1.0/24"], db_session, run_id)
|
||||
|
||||
result = await db_session.execute(
|
||||
select(PendingDevice).where(PendingDevice.ip == "192.168.1.50")
|
||||
select(InventoryDevice).where(InventoryDevice.ip == "192.168.1.50")
|
||||
)
|
||||
assert result.scalar_one_or_none() is not None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_run_scan_records_ip_already_in_canvas(db_session: AsyncSession):
|
||||
"""A scanned IP that already exists as a canvas Node still produces a pending
|
||||
device (no longer suppressed)."""
|
||||
node = Node(
|
||||
"""A scanned IP already drawn on a canvas refreshes the one inventory row.
|
||||
|
||||
The device is never suppressed, and never duplicated: the node draws that
|
||||
row, so a second row for the same host would split the device in two.
|
||||
"""
|
||||
existing = InventoryDevice(id=str(uuid.uuid4()), ip="192.168.1.50", status="approved")
|
||||
db_session.add(existing)
|
||||
await db_session.flush()
|
||||
existing_id = existing.id
|
||||
db_session.add(Node(
|
||||
id=str(uuid.uuid4()),
|
||||
label="Existing Server",
|
||||
type="server",
|
||||
ip="192.168.1.50",
|
||||
status="online",
|
||||
services=[],
|
||||
device_id=existing.id,
|
||||
pos_x=0.0,
|
||||
pos_y=0.0,
|
||||
)
|
||||
db_session.add(node)
|
||||
))
|
||||
await db_session.commit()
|
||||
|
||||
run_id = str(uuid.uuid4())
|
||||
@@ -200,19 +203,23 @@ async def test_run_scan_records_ip_already_in_canvas(db_session: AsyncSession):
|
||||
):
|
||||
await run_scan(["192.168.1.0/24"], db_session, run_id)
|
||||
|
||||
result = await db_session.execute(
|
||||
select(PendingDevice).where(PendingDevice.ip == "192.168.1.50")
|
||||
)
|
||||
device = result.scalar_one_or_none()
|
||||
assert device is not None
|
||||
assert device.status == "pending"
|
||||
rows = (
|
||||
await db_session.execute(
|
||||
select(InventoryDevice).where(InventoryDevice.ip == "192.168.1.50")
|
||||
)
|
||||
).scalars().all()
|
||||
assert len(rows) == 1
|
||||
assert rows[0].id == existing_id
|
||||
# The scan refreshed it; it did not reset the lifecycle.
|
||||
assert rows[0].status == "approved"
|
||||
assert rows[0].hostname == MOCK_HOST["hostname"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_run_scan_refreshes_approved_device_without_duplicating(db_session: AsyncSession):
|
||||
"""Re-scanning an already-approved device updates its row in place instead of
|
||||
spawning a fresh pending duplicate, and keeps it approved."""
|
||||
approved = PendingDevice(
|
||||
approved = InventoryDevice(
|
||||
id=str(uuid.uuid4()), ip="192.168.1.50", mac=None, hostname="old",
|
||||
os=None, services=[], suggested_type="server", status="approved",
|
||||
)
|
||||
@@ -228,7 +235,7 @@ async def test_run_scan_refreshes_approved_device_without_duplicating(db_session
|
||||
await run_scan(["192.168.1.0/24"], db_session, run_id)
|
||||
|
||||
rows = (await db_session.execute(
|
||||
select(PendingDevice).where(PendingDevice.ip == "192.168.1.50")
|
||||
select(InventoryDevice).where(InventoryDevice.ip == "192.168.1.50")
|
||||
)).scalars().all()
|
||||
assert len(rows) == 1
|
||||
assert rows[0].status == "approved"
|
||||
@@ -240,7 +247,7 @@ async def test_run_scan_collapses_existing_duplicate_rows(db_session: AsyncSessi
|
||||
"""Pre-existing duplicate inventory rows for one IP are collapsed to a single
|
||||
row at scan start, even if the device is not re-discovered."""
|
||||
for status in ("approved", "pending", "pending"):
|
||||
db_session.add(PendingDevice(
|
||||
db_session.add(InventoryDevice(
|
||||
id=str(uuid.uuid4()), ip="192.168.1.77", mac=None, hostname=None,
|
||||
os=None, services=[], suggested_type="server", status=status,
|
||||
))
|
||||
@@ -255,7 +262,7 @@ async def test_run_scan_collapses_existing_duplicate_rows(db_session: AsyncSessi
|
||||
await run_scan(["192.168.1.0/24"], db_session, run_id)
|
||||
|
||||
rows = (await db_session.execute(
|
||||
select(PendingDevice).where(PendingDevice.ip == "192.168.1.77")
|
||||
select(InventoryDevice).where(InventoryDevice.ip == "192.168.1.77")
|
||||
)).scalars().all()
|
||||
assert len(rows) == 1
|
||||
assert rows[0].status == "approved" # approved row is the one kept
|
||||
@@ -264,7 +271,7 @@ async def test_run_scan_collapses_existing_duplicate_rows(db_session: AsyncSessi
|
||||
@pytest.mark.asyncio
|
||||
async def test_run_scan_skips_hidden_device(db_session: AsyncSession):
|
||||
"""Devices previously hidden by the user must not re-appear in pending on re-scan."""
|
||||
hidden = PendingDevice(
|
||||
hidden = InventoryDevice(
|
||||
id=str(uuid.uuid4()),
|
||||
ip="192.168.1.50",
|
||||
mac=None,
|
||||
@@ -289,9 +296,9 @@ async def test_run_scan_skips_hidden_device(db_session: AsyncSession):
|
||||
await run_scan(["192.168.1.0/24"], db_session, run_id)
|
||||
|
||||
result = await db_session.execute(
|
||||
select(PendingDevice).where(
|
||||
PendingDevice.ip == "192.168.1.50",
|
||||
PendingDevice.status == "pending",
|
||||
select(InventoryDevice).where(
|
||||
InventoryDevice.ip == "192.168.1.50",
|
||||
InventoryDevice.status == "pending",
|
||||
)
|
||||
)
|
||||
assert result.scalar_one_or_none() is None
|
||||
@@ -395,7 +402,7 @@ async def test_run_scan_cancelled_mid_scan_skips_remaining_cidrs(db_session: Asy
|
||||
async def test_run_scan_updates_existing_pending_device(db_session: AsyncSession):
|
||||
"""Re-scanning the same IP updates services instead of creating a duplicate."""
|
||||
# Pre-existing pending device with no services
|
||||
existing = PendingDevice(
|
||||
existing = InventoryDevice(
|
||||
id=str(uuid.uuid4()),
|
||||
ip="192.168.1.50",
|
||||
mac=None,
|
||||
@@ -421,7 +428,7 @@ async def test_run_scan_updates_existing_pending_device(db_session: AsyncSession
|
||||
|
||||
# Should still be only one device
|
||||
result = await db_session.execute(
|
||||
select(PendingDevice).where(PendingDevice.ip == "192.168.1.50")
|
||||
select(InventoryDevice).where(InventoryDevice.ip == "192.168.1.50")
|
||||
)
|
||||
devices = list(result.scalars().all())
|
||||
assert len(devices) == 1
|
||||
|
||||
+288
-3
@@ -1,5 +1,56 @@
|
||||
import time
|
||||
from unittest.mock import AsyncMock, patch
|
||||
from urllib.parse import parse_qs, urlparse
|
||||
|
||||
import pytest
|
||||
from authlib.integrations.base_client.errors import OAuthError
|
||||
from authlib.jose.errors import ExpiredTokenError, JoseError
|
||||
from fastapi import WebSocketDisconnect
|
||||
from httpx import AsyncClient
|
||||
from starlette.responses import RedirectResponse
|
||||
from starlette.testclient import TestClient
|
||||
|
||||
|
||||
class FakeOIDCClient:
|
||||
def __init__(self, token=None, error: OAuthError | JoseError | None = None):
|
||||
self.token = token or {}
|
||||
self.error = error
|
||||
self.redirect_uri: str | None = None
|
||||
|
||||
async def authorize_redirect(self, _request, redirect_uri: str):
|
||||
self.redirect_uri = redirect_uri
|
||||
return RedirectResponse("https://idp.example/application/o/authorize/?state=test", status_code=302)
|
||||
|
||||
async def authorize_access_token(self, _request):
|
||||
if self.error is not None:
|
||||
raise self.error
|
||||
return self.token
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def oidc_settings():
|
||||
from app.core.config import settings
|
||||
from app.core.security import _build_oidc_client
|
||||
|
||||
values = {
|
||||
"auth_mode": "oidc",
|
||||
"oidc_discovery_url": "https://idp.example/application/o/homelable/.well-known/openid-configuration",
|
||||
"oidc_client_id": "homelable",
|
||||
"oidc_client_secret": "test-client-secret",
|
||||
"oidc_redirect_uri": "http://test/api/v1/auth/oidc/callback",
|
||||
"oidc_scopes": "openid profile email",
|
||||
"oidc_cookie_secure": False,
|
||||
"oidc_session_expire_minutes": 60,
|
||||
"cors_origins": ["http://test"],
|
||||
}
|
||||
original = {name: getattr(settings, name) for name in values}
|
||||
for name, value in values.items():
|
||||
setattr(settings, name, value)
|
||||
_build_oidc_client.cache_clear()
|
||||
yield settings
|
||||
for name, value in original.items():
|
||||
setattr(settings, name, value)
|
||||
_build_oidc_client.cache_clear()
|
||||
|
||||
|
||||
async def test_login_success(client: AsyncClient):
|
||||
@@ -10,6 +61,12 @@ async def test_login_success(client: AsyncClient):
|
||||
assert data["token_type"] == "bearer"
|
||||
|
||||
|
||||
async def test_auth_config_defaults_to_local(client: AsyncClient):
|
||||
res = await client.get("/api/v1/auth/config")
|
||||
assert res.status_code == 200
|
||||
assert res.json() == {"mode": "local", "oidc_login_url": None}
|
||||
|
||||
|
||||
async def test_login_wrong_password(client: AsyncClient):
|
||||
res = await client.post("/api/v1/auth/login", json={"username": "admin", "password": "wrong"})
|
||||
assert res.status_code == 401
|
||||
@@ -76,7 +133,7 @@ async def test_expired_token_rejected(client: AsyncClient):
|
||||
"""A JWT whose `exp` is in the past must be refused."""
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from jose import jwt
|
||||
import jwt
|
||||
|
||||
from app.core.config import settings
|
||||
payload = {
|
||||
@@ -97,14 +154,14 @@ async def test_token_signed_with_wrong_secret_rejected(client: AsyncClient):
|
||||
"""A token signed with a different key must not be accepted."""
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from jose import jwt
|
||||
import jwt
|
||||
|
||||
from app.core.config import settings
|
||||
payload = {
|
||||
"sub": "admin",
|
||||
"exp": datetime.now(timezone.utc) + timedelta(minutes=5),
|
||||
}
|
||||
forged = jwt.encode(payload, "different-secret", algorithm=settings.algorithm)
|
||||
forged = jwt.encode(payload, "different-secret-that-is-at-least-32-bytes", algorithm=settings.algorithm)
|
||||
res = await client.get("/api/v1/nodes", headers={"Authorization": f"Bearer {forged}"})
|
||||
assert res.status_code == 401
|
||||
|
||||
@@ -136,3 +193,231 @@ def test_verify_password_handles_empty_inputs():
|
||||
assert verify_password("", h) is False
|
||||
assert verify_password("hunter2", "") is False
|
||||
assert verify_password("", "") is False
|
||||
|
||||
|
||||
# --- OpenID Connect ---
|
||||
|
||||
async def test_oidc_config_exposes_login_url(client: AsyncClient, oidc_settings):
|
||||
res = await client.get("/api/v1/auth/config")
|
||||
assert res.status_code == 200
|
||||
assert res.json() == {
|
||||
"mode": "oidc",
|
||||
"oidc_login_url": "/api/v1/auth/oidc/login",
|
||||
}
|
||||
|
||||
|
||||
async def test_local_login_is_disabled_in_oidc_mode(client: AsyncClient, oidc_settings):
|
||||
res = await client.post("/api/v1/auth/login", json={"username": "admin", "password": "admin"})
|
||||
assert res.status_code == 404
|
||||
|
||||
|
||||
async def test_oidc_login_is_hidden_in_local_mode(client: AsyncClient):
|
||||
res = await client.get("/api/v1/auth/oidc/login")
|
||||
assert res.status_code == 404
|
||||
|
||||
|
||||
async def test_oidc_login_uses_configured_callback(client: AsyncClient, oidc_settings):
|
||||
fake_client = FakeOIDCClient()
|
||||
with patch("app.api.routes.auth.get_oidc_client", return_value=fake_client):
|
||||
res = await client.get("/api/v1/auth/oidc/login")
|
||||
assert res.status_code == 302
|
||||
assert res.headers["location"].startswith("https://idp.example/")
|
||||
assert fake_client.redirect_uri == "http://test/api/v1/auth/oidc/callback"
|
||||
|
||||
|
||||
async def test_oidc_client_enables_pkce_s256_and_nonce(oidc_settings):
|
||||
from app.core.security import get_oidc_client
|
||||
|
||||
oidc_client = get_oidc_client()
|
||||
metadata = {"authorization_endpoint": "https://idp.example/application/o/authorize/"}
|
||||
with patch.object(oidc_client, "load_server_metadata", AsyncMock(return_value=metadata)):
|
||||
authorization = await oidc_client.create_authorization_url(oidc_settings.oidc_redirect_uri)
|
||||
|
||||
query = parse_qs(urlparse(authorization["url"]).query)
|
||||
assert query["response_type"] == ["code"]
|
||||
assert query["code_challenge_method"] == ["S256"]
|
||||
assert "code_challenge" in query
|
||||
assert "code_verifier" not in query
|
||||
assert query["nonce"] == [authorization["nonce"]]
|
||||
assert authorization["code_verifier"]
|
||||
|
||||
|
||||
async def test_oidc_callback_creates_session_for_api(client: AsyncClient, oidc_settings):
|
||||
fake_client = FakeOIDCClient(token={
|
||||
"userinfo": {
|
||||
"iss": "https://idp.example/application/o/homelable/",
|
||||
"sub": "user-123",
|
||||
"preferred_username": "alice",
|
||||
},
|
||||
})
|
||||
with patch("app.api.routes.auth.get_oidc_client", return_value=fake_client):
|
||||
callback = await client.get("/api/v1/auth/oidc/callback")
|
||||
|
||||
assert callback.status_code == 303
|
||||
assert callback.headers["location"] == "/"
|
||||
cookie = callback.headers["set-cookie"]
|
||||
assert "homelable-session=" in cookie
|
||||
assert "HttpOnly" in cookie
|
||||
assert "SameSite=lax" in cookie
|
||||
|
||||
me = await client.get("/api/v1/auth/me")
|
||||
assert me.status_code == 200
|
||||
assert me.json()["subject"] == "user-123"
|
||||
assert me.json()["display_name"] == "alice"
|
||||
assert me.json()["auth_method"] == "oidc"
|
||||
assert me.json()["issuer"] == "https://idp.example/application/o/homelable/"
|
||||
assert me.json()["csrf_token"]
|
||||
|
||||
protected = await client.get("/api/v1/nodes")
|
||||
assert protected.status_code == 200
|
||||
|
||||
|
||||
@pytest.mark.parametrize("userinfo", [None, {}, {"sub": "user-123"}, {"iss": "https://idp.example/"}])
|
||||
async def test_oidc_callback_rejects_missing_identity_claims(client: AsyncClient, oidc_settings, userinfo):
|
||||
token = {} if userinfo is None else {"userinfo": userinfo}
|
||||
fake_client = FakeOIDCClient(token=token)
|
||||
with patch("app.api.routes.auth.get_oidc_client", return_value=fake_client):
|
||||
res = await client.get("/api/v1/auth/oidc/callback")
|
||||
assert res.status_code == 401
|
||||
assert res.json() == {"detail": "OIDC authentication failed"}
|
||||
|
||||
|
||||
async def test_oidc_callback_hides_protocol_error_details(client: AsyncClient, oidc_settings):
|
||||
fake_client = FakeOIDCClient(error=OAuthError(error="invalid_grant", description="sensitive detail"))
|
||||
with patch("app.api.routes.auth.get_oidc_client", return_value=fake_client):
|
||||
res = await client.get("/api/v1/auth/oidc/callback")
|
||||
assert res.status_code == 401
|
||||
assert res.json() == {"detail": "OIDC authentication failed"}
|
||||
assert "sensitive detail" not in res.text
|
||||
|
||||
|
||||
async def test_oidc_callback_hides_claim_validation_error_details(client: AsyncClient, oidc_settings):
|
||||
fake_client = FakeOIDCClient(error=ExpiredTokenError())
|
||||
with patch("app.api.routes.auth.get_oidc_client", return_value=fake_client):
|
||||
res = await client.get("/api/v1/auth/oidc/callback")
|
||||
assert res.status_code == 401
|
||||
assert res.json() == {"detail": "OIDC authentication failed"}
|
||||
assert "expired" not in res.text.lower()
|
||||
|
||||
|
||||
async def test_oidc_session_token_cannot_be_used_as_bearer(client: AsyncClient, oidc_settings):
|
||||
from app.core.security import create_oidc_session_token
|
||||
|
||||
token = create_oidc_session_token({"iss": "https://idp.example/", "sub": "user-123"})
|
||||
res = await client.get("/api/v1/nodes", headers={"Authorization": f"Bearer {token}"})
|
||||
assert res.status_code == 401
|
||||
|
||||
|
||||
async def test_oidc_cookie_mutations_require_csrf_and_allowed_origin(client: AsyncClient, oidc_settings):
|
||||
fake_client = FakeOIDCClient(token={
|
||||
"userinfo": {
|
||||
"iss": "https://idp.example/application/o/homelable/",
|
||||
"sub": "user-123",
|
||||
"preferred_username": "alice",
|
||||
},
|
||||
})
|
||||
with patch("app.api.routes.auth.get_oidc_client", return_value=fake_client):
|
||||
await client.get("/api/v1/auth/oidc/callback")
|
||||
csrf_token = (await client.get("/api/v1/auth/me")).json()["csrf_token"]
|
||||
|
||||
missing = await client.post("/api/v1/auth/logout")
|
||||
assert missing.status_code == 403
|
||||
wrong_origin = await client.post(
|
||||
"/api/v1/auth/logout",
|
||||
headers={"Origin": "https://evil.example", "X-Homelable-CSRF": csrf_token},
|
||||
)
|
||||
assert wrong_origin.status_code == 403
|
||||
valid = await client.post(
|
||||
"/api/v1/auth/logout",
|
||||
headers={"Origin": "http://test", "X-Homelable-CSRF": csrf_token},
|
||||
)
|
||||
assert valid.status_code == 204
|
||||
assert "Max-Age=0" in valid.headers["set-cookie"]
|
||||
assert (await client.get("/api/v1/auth/me")).status_code == 401
|
||||
|
||||
|
||||
async def test_local_bearer_logout_does_not_require_csrf(client: AsyncClient, headers):
|
||||
res = await client.post("/api/v1/auth/logout", headers=headers)
|
||||
assert res.status_code == 204
|
||||
|
||||
|
||||
# --- WebSocket authentication ---
|
||||
|
||||
def _wait_for_connection_count(expected: int) -> None:
|
||||
from app.api.routes import status as status_routes
|
||||
|
||||
deadline = time.monotonic() + 1
|
||||
while len(status_routes._connections) != expected and time.monotonic() < deadline:
|
||||
time.sleep(0.01)
|
||||
assert len(status_routes._connections) == expected
|
||||
|
||||
|
||||
def test_local_websocket_keeps_first_message_bearer_flow():
|
||||
from app.core.security import create_access_token
|
||||
from app.main import app
|
||||
|
||||
test_client = TestClient(app)
|
||||
try:
|
||||
with test_client.websocket_connect(
|
||||
"/api/v1/status/ws/status",
|
||||
headers={"Origin": "http://localhost:3000"},
|
||||
) as websocket:
|
||||
websocket.send_json({"token": create_access_token("admin")})
|
||||
_wait_for_connection_count(1)
|
||||
_wait_for_connection_count(0)
|
||||
finally:
|
||||
test_client.close()
|
||||
|
||||
|
||||
def test_websocket_rejects_untrusted_origin_before_auth():
|
||||
from app.main import app
|
||||
|
||||
test_client = TestClient(app)
|
||||
try:
|
||||
with (
|
||||
pytest.raises(WebSocketDisconnect) as caught,
|
||||
test_client.websocket_connect(
|
||||
"/api/v1/status/ws/status",
|
||||
headers={"Origin": "https://evil.example"},
|
||||
) as websocket,
|
||||
):
|
||||
websocket.receive_text()
|
||||
assert caught.value.code == 1008
|
||||
finally:
|
||||
test_client.close()
|
||||
|
||||
|
||||
def test_oidc_websocket_uses_session_cookie_without_javascript_token(oidc_settings):
|
||||
from app.core.security import create_oidc_session_token, oidc_session_cookie_name
|
||||
from app.main import app
|
||||
|
||||
session_token = create_oidc_session_token({"iss": "https://idp.example/", "sub": "user-123"})
|
||||
test_client = TestClient(app)
|
||||
test_client.cookies.set(oidc_session_cookie_name(), session_token)
|
||||
try:
|
||||
with test_client.websocket_connect(
|
||||
"/api/v1/status/ws/status",
|
||||
headers={"Origin": "http://test"},
|
||||
):
|
||||
_wait_for_connection_count(1)
|
||||
_wait_for_connection_count(0)
|
||||
finally:
|
||||
test_client.close()
|
||||
|
||||
|
||||
def test_oidc_websocket_rejects_missing_session_cookie(oidc_settings):
|
||||
from app.main import app
|
||||
|
||||
test_client = TestClient(app)
|
||||
try:
|
||||
with (
|
||||
pytest.raises(WebSocketDisconnect) as caught,
|
||||
test_client.websocket_connect(
|
||||
"/api/v1/status/ws/status",
|
||||
headers={"Origin": "http://test"},
|
||||
) as websocket,
|
||||
):
|
||||
websocket.receive_text()
|
||||
assert caught.value.code == 1008
|
||||
finally:
|
||||
test_client.close()
|
||||
|
||||
@@ -22,6 +22,23 @@ async def test_load_canvas_empty(client: AsyncClient, headers: dict):
|
||||
assert data["viewport"] == {"x": 0, "y": 0, "zoom": 1}
|
||||
|
||||
|
||||
async def test_load_canvas_uninitialized_reports_initialized_false(client: AsyncClient, headers: dict):
|
||||
# A never-saved canvas has no CanvasState row → initialized False. The frontend
|
||||
# uses this to show the demo canvas only to genuinely new users.
|
||||
data = (await client.get("/api/v1/canvas", headers=headers)).json()
|
||||
assert data["initialized"] is False
|
||||
|
||||
|
||||
async def test_load_canvas_initialized_true_after_save(client: AsyncClient, headers: dict):
|
||||
# Saving an EMPTY canvas still creates a CanvasState row, so a subsequently
|
||||
# loaded empty canvas is reported initialized — the user cleared it on purpose
|
||||
# and must not get the demo re-seeded.
|
||||
await client.post("/api/v1/canvas/save", json={"nodes": [], "edges": [], "viewport": {}}, headers=headers)
|
||||
data = (await client.get("/api/v1/canvas", headers=headers)).json()
|
||||
assert data["nodes"] == []
|
||||
assert data["initialized"] is True
|
||||
|
||||
|
||||
async def test_load_canvas_requires_auth(client: AsyncClient):
|
||||
res = await client.get("/api/v1/canvas")
|
||||
assert res.status_code == 401
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
"""The pending_devices -> device_inventory rename, run at startup.
|
||||
|
||||
It is the one migration that must happen *before* `create_all`, so it gets its
|
||||
own suite: get the order wrong and every device a user ever scanned reads as
|
||||
gone, because the app looks at a freshly created empty table.
|
||||
"""
|
||||
import pytest
|
||||
from sqlalchemy.ext.asyncio import create_async_engine
|
||||
|
||||
from app.db.database import _rename_legacy_tables
|
||||
|
||||
pytestmark = pytest.mark.asyncio
|
||||
|
||||
|
||||
def _legacy_ddl(table: str) -> str:
|
||||
return f"CREATE TABLE {table} (id VARCHAR PRIMARY KEY, hostname VARCHAR)"
|
||||
|
||||
|
||||
async def _engine(tmp_path, *, statements: list[str]):
|
||||
engine = create_async_engine(f"sqlite+aiosqlite:///{tmp_path / 'test.db'}")
|
||||
async with engine.begin() as conn:
|
||||
for sql in statements:
|
||||
await conn.exec_driver_sql(sql)
|
||||
return engine
|
||||
|
||||
|
||||
async def _tables(engine) -> set[str]:
|
||||
async with engine.begin() as conn:
|
||||
rows = (
|
||||
await conn.exec_driver_sql("SELECT name FROM sqlite_master WHERE type='table'")
|
||||
).fetchall()
|
||||
return {r[0] for r in rows}
|
||||
|
||||
|
||||
async def _rename(engine) -> None:
|
||||
async with engine.begin() as conn:
|
||||
await _rename_legacy_tables(conn)
|
||||
|
||||
|
||||
async def test_renames_the_legacy_tables_keeping_their_rows(tmp_path):
|
||||
engine = await _engine(
|
||||
tmp_path,
|
||||
statements=[
|
||||
_legacy_ddl("pending_devices"),
|
||||
_legacy_ddl("pending_device_links"),
|
||||
"INSERT INTO pending_devices (id, hostname) VALUES ('d1', 'nas')",
|
||||
],
|
||||
)
|
||||
|
||||
await _rename(engine)
|
||||
|
||||
assert await _tables(engine) == {"device_inventory", "device_inventory_links"}
|
||||
async with engine.begin() as conn:
|
||||
rows = (await conn.exec_driver_sql("SELECT hostname FROM device_inventory")).fetchall()
|
||||
assert [r[0] for r in rows] == ["nas"]
|
||||
await engine.dispose()
|
||||
|
||||
|
||||
async def test_rewrites_the_reference_from_rack_devices(tmp_path):
|
||||
# `rack_devices.device_id` names the inventory table. Left pointing at the
|
||||
# old name, the schema references a table that no longer exists.
|
||||
engine = await _engine(
|
||||
tmp_path,
|
||||
statements=[
|
||||
_legacy_ddl("pending_devices"),
|
||||
"CREATE TABLE rack_devices (id VARCHAR PRIMARY KEY, device_id VARCHAR "
|
||||
"REFERENCES pending_devices(id) ON DELETE SET NULL)",
|
||||
],
|
||||
)
|
||||
|
||||
await _rename(engine)
|
||||
|
||||
async with engine.begin() as conn:
|
||||
ddl = (
|
||||
await conn.exec_driver_sql(
|
||||
"SELECT sql FROM sqlite_master WHERE name='rack_devices'"
|
||||
)
|
||||
).scalar()
|
||||
assert "device_inventory" in ddl
|
||||
assert "pending_devices" not in ddl
|
||||
await engine.dispose()
|
||||
|
||||
|
||||
async def test_replaces_an_empty_table_left_by_an_earlier_start(tmp_path):
|
||||
# A start that ran `create_all` before this migration existed created the new
|
||||
# table empty, and the app read that one instead of the user's devices.
|
||||
engine = await _engine(
|
||||
tmp_path,
|
||||
statements=[
|
||||
_legacy_ddl("pending_devices"),
|
||||
_legacy_ddl("device_inventory"),
|
||||
"INSERT INTO pending_devices (id, hostname) VALUES ('d1', 'nas')",
|
||||
],
|
||||
)
|
||||
|
||||
await _rename(engine)
|
||||
|
||||
assert await _tables(engine) == {"device_inventory"}
|
||||
async with engine.begin() as conn:
|
||||
count = (await conn.exec_driver_sql("SELECT COUNT(*) FROM device_inventory")).scalar()
|
||||
assert count == 1
|
||||
await engine.dispose()
|
||||
|
||||
|
||||
async def test_leaves_two_populated_tables_alone(tmp_path):
|
||||
# Rows on both sides is not a state this migration created, and dropping
|
||||
# either one would lose data.
|
||||
engine = await _engine(
|
||||
tmp_path,
|
||||
statements=[
|
||||
_legacy_ddl("pending_devices"),
|
||||
_legacy_ddl("device_inventory"),
|
||||
"INSERT INTO pending_devices (id, hostname) VALUES ('d1', 'old')",
|
||||
"INSERT INTO device_inventory (id, hostname) VALUES ('d2', 'new')",
|
||||
],
|
||||
)
|
||||
|
||||
await _rename(engine)
|
||||
|
||||
assert await _tables(engine) == {"pending_devices", "device_inventory"}
|
||||
await engine.dispose()
|
||||
|
||||
|
||||
async def test_is_a_no_op_on_a_fresh_database(tmp_path):
|
||||
engine = await _engine(tmp_path, statements=[_legacy_ddl("device_inventory")])
|
||||
|
||||
await _rename(engine)
|
||||
await _rename(engine) # And still a no-op the second time round.
|
||||
|
||||
assert await _tables(engine) == {"device_inventory"}
|
||||
await engine.dispose()
|
||||
@@ -124,6 +124,41 @@ def test_suggest_node_type_priority_proxmox_over_server():
|
||||
assert result == "proxmox"
|
||||
|
||||
|
||||
# A port-agnostic signature: only an HTTP probe can ever match it.
|
||||
KVM_SIGNATURE = {
|
||||
"port": None, "protocol": "tcp", "banner_regex": None, "http_regex": "PiKVM",
|
||||
"service_name": "PiKVM", "icon": "monitorcog", "category": "kvm",
|
||||
"suggested_node_type": "kvm",
|
||||
}
|
||||
|
||||
|
||||
def test_suggest_node_type_kvm_from_http_title():
|
||||
# An IP-KVM answers on 443 like any web app; only the probed title identifies it.
|
||||
with patch("app.services.fingerprint._load", return_value=[*MOCK_SIGNATURES, KVM_SIGNATURE]):
|
||||
result = suggest_node_type([
|
||||
{"port": 443, "protocol": "tcp", "http_signals": {"title": "PiKVM", "headers": {}}},
|
||||
])
|
||||
assert result == "kvm"
|
||||
|
||||
|
||||
def test_suggest_node_type_priority_kvm_over_server():
|
||||
# The same host also answers on 80 (→ server); the KVM signal outranks it.
|
||||
with patch("app.services.fingerprint._load", return_value=[*MOCK_SIGNATURES, KVM_SIGNATURE]):
|
||||
result = suggest_node_type([
|
||||
{"port": 80, "protocol": "tcp"},
|
||||
{"port": 443, "protocol": "tcp", "http_signals": {"title": "PiKVM", "headers": {}}},
|
||||
])
|
||||
assert result == "kvm"
|
||||
|
||||
|
||||
def test_suggest_node_type_ignores_port_agnostic_sig_without_probe():
|
||||
# No http_signals (probe disabled) → port-agnostic entries can't match and the
|
||||
# port-only guess stands, unchanged from pre-probe behaviour.
|
||||
with patch("app.services.fingerprint._load", return_value=[*MOCK_SIGNATURES, KVM_SIGNATURE]):
|
||||
result = suggest_node_type([{"port": 443, "protocol": "tcp"}])
|
||||
assert result == "server"
|
||||
|
||||
|
||||
def test_suggest_node_type_camera_from_rtsp_port():
|
||||
# RTSP port 554 → camera (via _PORT_TYPE_HINTS)
|
||||
result = suggest_node_type([{"port": 554, "protocol": "tcp"}])
|
||||
|
||||
@@ -0,0 +1,855 @@
|
||||
"""The node ↔ Device Inventory link: matching, merging, and the 3.3.0 backfill.
|
||||
|
||||
The inventory row owns the device facts; a node owns how the device is drawn.
|
||||
These tests pin the rules that make one device end up as one row even when it
|
||||
was drawn on several canvases.
|
||||
"""
|
||||
import json
|
||||
import uuid
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
import pytest
|
||||
from httpx import AsyncClient
|
||||
from sqlalchemy import select, text
|
||||
|
||||
from app.db.models import Design, InventoryDevice, Node
|
||||
from app.services.inventory_sync import (
|
||||
backfill_node_devices,
|
||||
changed_facts,
|
||||
find_device_for,
|
||||
link_facts,
|
||||
merge_properties,
|
||||
merge_services,
|
||||
)
|
||||
|
||||
|
||||
def _now(offset_minutes: int = 0) -> datetime:
|
||||
return datetime(2026, 1, 1, 12, 0, tzinfo=timezone.utc) + timedelta(minutes=offset_minutes)
|
||||
|
||||
|
||||
async def _design(db_session, name="Net") -> str:
|
||||
design = Design(id=str(uuid.uuid4()), name=name)
|
||||
db_session.add(design)
|
||||
await db_session.commit()
|
||||
return design.id
|
||||
|
||||
|
||||
def _node(design_id: str, **kwargs) -> Node:
|
||||
payload = {
|
||||
"id": str(uuid.uuid4()),
|
||||
"label": "n",
|
||||
"type": "server",
|
||||
"pos_x": 0.0,
|
||||
"pos_y": 0.0,
|
||||
"design_id": design_id,
|
||||
}
|
||||
payload.update(kwargs)
|
||||
return Node(**payload)
|
||||
|
||||
|
||||
# --- pure merge rules -------------------------------------------------------
|
||||
|
||||
|
||||
class TestMergeRules:
|
||||
def test_properties_union_on_key_with_incoming_winning(self):
|
||||
base = [{"key": "Rack", "value": "A1", "icon": None, "visible": True}]
|
||||
incoming = [
|
||||
{"key": "rack", "value": "B2", "icon": None, "visible": False},
|
||||
{"key": "Owner", "value": "me", "icon": None, "visible": True},
|
||||
]
|
||||
out = merge_properties(base, incoming)
|
||||
assert [p["value"] for p in out] == ["B2", "me"]
|
||||
# Existing keys keep their position — a user's ordering survives.
|
||||
assert out[0]["key"] == "Rack"
|
||||
assert out[0]["visible"] is False
|
||||
|
||||
def test_properties_keep_established_value_when_incoming_is_blank(self):
|
||||
out = merge_properties(
|
||||
[{"key": "Rack", "value": "A1", "icon": "Server", "visible": True}],
|
||||
[{"key": "Rack", "value": "", "icon": None, "visible": True}],
|
||||
)
|
||||
assert out[0]["value"] == "A1"
|
||||
assert out[0]["icon"] == "Server"
|
||||
|
||||
def test_services_union_on_port_protocol_and_name(self):
|
||||
base = [{"port": 22, "protocol": "tcp", "service_name": "ssh"}]
|
||||
incoming = [
|
||||
{"port": 22, "protocol": "tcp", "service_name": "SSH", "icon": "Terminal"},
|
||||
{"port": 80, "protocol": "tcp", "service_name": "http"},
|
||||
]
|
||||
out = merge_services(base, incoming)
|
||||
assert len(out) == 2
|
||||
assert out[0]["icon"] == "Terminal"
|
||||
assert out[1]["port"] == 80
|
||||
|
||||
|
||||
class TestChangedFacts:
|
||||
"""What a save is allowed to write: its edit, not its whole snapshot."""
|
||||
|
||||
def test_an_unchanged_snapshot_writes_nothing(self):
|
||||
device = InventoryDevice(
|
||||
id="d-1",
|
||||
label="NAS",
|
||||
type="nas",
|
||||
hostname="nas.lan",
|
||||
ip="10.0.0.5",
|
||||
notes="in the garage",
|
||||
status_live="online",
|
||||
properties=[{"key": "Rack", "value": "A1", "icon": None, "visible": True}],
|
||||
services=[{"port": 22, "protocol": "tcp", "service_name": "ssh"}],
|
||||
)
|
||||
facts = {
|
||||
"label": "NAS",
|
||||
"type": "nas",
|
||||
"hostname": "nas.lan",
|
||||
"ip": "10.0.0.5",
|
||||
"notes": "in the garage",
|
||||
"status": "online",
|
||||
"properties": [{"key": "Rack", "value": "A1", "icon": None, "visible": True}],
|
||||
"services": [{"port": 22, "protocol": "tcp", "service_name": "ssh"}],
|
||||
}
|
||||
assert changed_facts(device, facts) == {}
|
||||
|
||||
def test_only_the_edited_field_survives(self):
|
||||
device = InventoryDevice(id="d-1", hostname="nas.lan", ip="10.0.0.5", notes="old")
|
||||
facts = {"hostname": "nas.lan", "ip": "10.0.0.5", "notes": "new"}
|
||||
assert changed_facts(device, facts) == {"notes": "new"}
|
||||
|
||||
def test_a_blank_incoming_value_is_not_a_change(self):
|
||||
# A blank never clears an established value, so it is not an edit either.
|
||||
device = InventoryDevice(id="d-1", hostname="nas.lan", notes="keep me")
|
||||
assert changed_facts(device, {"hostname": "", "notes": None}) == {}
|
||||
|
||||
def test_a_changed_list_is_sent_whole(self):
|
||||
device = InventoryDevice(
|
||||
id="d-1",
|
||||
properties=[{"key": "Rack", "value": "A1", "icon": None, "visible": True}],
|
||||
services=[{"port": 22, "protocol": "tcp", "service_name": "ssh"}],
|
||||
)
|
||||
facts = {
|
||||
"properties": [],
|
||||
"services": [{"port": 22, "protocol": "tcp", "service_name": "ssh"}],
|
||||
}
|
||||
# Replace semantics need the full list, and the untouched one stays out.
|
||||
assert changed_facts(device, facts) == {"properties": []}
|
||||
|
||||
def test_live_status_only_fills_a_row_never_checked(self):
|
||||
unknown = InventoryDevice(id="d-1", status_live="unknown")
|
||||
assert changed_facts(unknown, {"status": "online"}) == {"status": "online"}
|
||||
checked = InventoryDevice(id="d-2", status_live="offline")
|
||||
# The status checker owns reachability; a stale canvas must not reset it.
|
||||
assert changed_facts(checked, {"status": "online"}) == {}
|
||||
|
||||
|
||||
# --- matching ---------------------------------------------------------------
|
||||
|
||||
|
||||
class TestFindDeviceFor:
|
||||
@pytest.mark.asyncio
|
||||
async def test_prefers_ieee_over_ip_and_mac(self, db_session):
|
||||
by_ip = InventoryDevice(id="d-ip", ip="10.0.0.5")
|
||||
by_ieee = InventoryDevice(id="d-ieee", ieee_address="0xAAA")
|
||||
db_session.add_all([by_ip, by_ieee])
|
||||
await db_session.commit()
|
||||
|
||||
found = await find_device_for(db_session, ip="10.0.0.5", mac=None, ieee="0xAAA")
|
||||
assert found is not None and found.id == "d-ieee"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_matches_one_address_out_of_a_comma_list(self, db_session):
|
||||
device = InventoryDevice(id="d-1", ip="10.0.0.5, fd00::1")
|
||||
db_session.add(device)
|
||||
await db_session.commit()
|
||||
|
||||
found = await find_device_for(db_session, ip="fd00::1", mac=None, ieee=None)
|
||||
assert found is not None and found.id == "d-1"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_does_not_match_a_longer_address_with_the_same_prefix(self, db_session):
|
||||
db_session.add(InventoryDevice(id="d-1", ip="10.0.0.40"))
|
||||
await db_session.commit()
|
||||
|
||||
assert await find_device_for(db_session, ip="10.0.0.4", mac=None, ieee=None) is None
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_matches_a_hidden_row_rather_than_minting_a_second(self, db_session):
|
||||
db_session.add(InventoryDevice(id="d-hidden", ip="10.0.0.5", status="hidden"))
|
||||
await db_session.commit()
|
||||
|
||||
found = await find_device_for(db_session, ip="10.0.0.5", mac=None, ieee=None)
|
||||
assert found is not None and found.id == "d-hidden"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_matches_an_ieee_written_in_another_case(self, db_session):
|
||||
"""One radio, one row: `ieee_address` is UNIQUE, so a case-sensitive
|
||||
match here would mint a second row the index then refuses."""
|
||||
db_session.add(InventoryDevice(id="d-1", ieee_address="0x00124b0022334455"))
|
||||
await db_session.commit()
|
||||
|
||||
found = await find_device_for(
|
||||
db_session, ip=None, mac=None, ieee="0x00124B0022334455"
|
||||
)
|
||||
assert found is not None and found.id == "d-1"
|
||||
|
||||
|
||||
class TestIeeeCollisions:
|
||||
"""`device_inventory.ieee_address` is UNIQUE — a merge must never duplicate it."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_an_address_another_row_owns_is_left_where_it_is(self, db_session):
|
||||
"""The node is already linked, so identity is settled — the IEEE is not
|
||||
a reason to move it, and writing it here would violate the index."""
|
||||
design = await _design(db_session)
|
||||
db_session.add_all([
|
||||
InventoryDevice(id="d-radio", ieee_address="0xAAA"),
|
||||
InventoryDevice(id="d-host", ip="10.0.0.5"),
|
||||
])
|
||||
node = _node(design, device_id="d-host")
|
||||
db_session.add(node)
|
||||
await db_session.commit()
|
||||
|
||||
device = await link_facts(
|
||||
db_session, node, {"ip": "10.0.0.5", "ieee_address": "0xAAA"}, overwrite_scalars=True
|
||||
)
|
||||
await db_session.commit()
|
||||
|
||||
assert device is not None and device.id == "d-host"
|
||||
assert device.ieee_address is None
|
||||
radio = await db_session.get(InventoryDevice, "d-radio")
|
||||
assert radio is not None and radio.ieee_address == "0xAAA"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_the_row_that_already_holds_it_keeps_writing_it(self, db_session):
|
||||
design = await _design(db_session)
|
||||
db_session.add(InventoryDevice(id="d-1", ip="10.0.0.5", ieee_address="0xAAA"))
|
||||
node = _node(design)
|
||||
db_session.add(node)
|
||||
await db_session.commit()
|
||||
|
||||
device = await link_facts(
|
||||
db_session, node, {"ip": "10.0.0.5", "ieee_address": "0xAAA"}, overwrite_scalars=True
|
||||
)
|
||||
await db_session.commit()
|
||||
|
||||
assert device is not None and device.ieee_address == "0xAAA"
|
||||
|
||||
|
||||
# --- the backfill -----------------------------------------------------------
|
||||
|
||||
|
||||
class TestBackfill:
|
||||
"""The 3.3.0 migration path.
|
||||
|
||||
A pre-3.3.0 database still has the device columns on `nodes`; the backfill
|
||||
reads them with raw SQL (the model no longer declares them) and folds each
|
||||
node's view into an inventory row. These tests recreate that shape.
|
||||
"""
|
||||
|
||||
async def _legacy_nodes_table(self, db_session) -> None:
|
||||
"""Re-add the pre-3.3.0 device columns to `nodes`."""
|
||||
for column, sql_type in (
|
||||
("hostname", "VARCHAR"), ("ip", "VARCHAR"), ("mac", "VARCHAR"), ("os", "VARCHAR"),
|
||||
("status", "VARCHAR"), ("check_method", "VARCHAR"), ("check_target", "VARCHAR"),
|
||||
("services", "JSON"), ("notes", "TEXT"), ("cpu_count", "INTEGER"),
|
||||
("cpu_model", "VARCHAR"), ("ram_gb", "FLOAT"), ("disk_gb", "FLOAT"),
|
||||
("show_hardware", "BOOLEAN"), ("properties", "JSON"), ("ieee_address", "VARCHAR"),
|
||||
("last_seen", "DATETIME"), ("last_scan", "DATETIME"), ("response_time_ms", "INTEGER"),
|
||||
):
|
||||
await db_session.execute(text(f"ALTER TABLE nodes ADD COLUMN {column} {sql_type}"))
|
||||
await db_session.commit()
|
||||
|
||||
async def _legacy_node(self, db_session, design_id: str, *, updated_at=None, **facts) -> str:
|
||||
node_id = str(uuid.uuid4())
|
||||
columns = {
|
||||
"id": node_id,
|
||||
"label": facts.pop("label", "n"),
|
||||
"type": facts.pop("type", "server"),
|
||||
"design_id": design_id,
|
||||
"pos_x": 0.0,
|
||||
"pos_y": 0.0,
|
||||
"container_mode": 0,
|
||||
"show_port_numbers": 0,
|
||||
"bottom_handles": 1,
|
||||
"top_handles": 1,
|
||||
"left_handles": 0,
|
||||
"right_handles": 0,
|
||||
"created_at": _now(0),
|
||||
"updated_at": updated_at or _now(0),
|
||||
}
|
||||
for key in ("services", "properties"):
|
||||
if key in facts:
|
||||
facts[key] = json.dumps(facts[key])
|
||||
columns.update(facts)
|
||||
names = ", ".join(columns)
|
||||
binds = ", ".join(f":{c}" for c in columns)
|
||||
await db_session.execute(text(f"INSERT INTO nodes ({names}) VALUES ({binds})"), columns)
|
||||
await db_session.commit()
|
||||
return node_id
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_does_nothing_when_the_columns_are_already_gone(self, db_session):
|
||||
"""A second boot: there is no legacy data left to read."""
|
||||
design = await _design(db_session)
|
||||
db_session.add(_node(design))
|
||||
await db_session.commit()
|
||||
|
||||
assert await backfill_node_devices(db_session) == {"linked": 0, "created": 0, "merged": 0, "skipped": 0}
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_links_a_node_to_its_existing_row(self, db_session):
|
||||
await self._legacy_nodes_table(db_session)
|
||||
design = await _design(db_session)
|
||||
db_session.add(InventoryDevice(id="d-1", ip="10.0.0.5", hostname="nas"))
|
||||
await db_session.commit()
|
||||
node_id = await self._legacy_node(db_session, design, ip="10.0.0.5", label="NAS")
|
||||
|
||||
stats = await backfill_node_devices(db_session)
|
||||
await db_session.commit()
|
||||
|
||||
assert stats == {"linked": 1, "created": 0, "merged": 1, "skipped": 0}
|
||||
node = await db_session.get(Node, node_id)
|
||||
assert node is not None and node.device_id == "d-1"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_creates_a_row_for_a_node_no_scan_ever_saw(self, db_session):
|
||||
await self._legacy_nodes_table(db_session)
|
||||
design = await _design(db_session)
|
||||
node_id = await self._legacy_node(
|
||||
db_session, design, label="Dumb switch", type="switch", notes="under the desk"
|
||||
)
|
||||
|
||||
stats = await backfill_node_devices(db_session)
|
||||
await db_session.commit()
|
||||
|
||||
assert stats == {"linked": 1, "created": 1, "merged": 0, "skipped": 0}
|
||||
node = await db_session.get(Node, node_id)
|
||||
assert node is not None
|
||||
device = await db_session.get(InventoryDevice, node.device_id)
|
||||
assert device is not None
|
||||
assert device.label == "Dumb switch"
|
||||
assert device.type == "switch"
|
||||
assert device.notes == "under the desk"
|
||||
assert device.status == "approved"
|
||||
assert device.discovery_sources == ["canvas"]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_two_canvases_one_device_merge_into_one_row(self, db_session):
|
||||
"""The whole point: the same host drawn twice becomes one inventory row."""
|
||||
await self._legacy_nodes_table(db_session)
|
||||
design_a = await _design(db_session, "A")
|
||||
design_b = await _design(db_session, "B")
|
||||
older = await self._legacy_node(
|
||||
db_session, design_a,
|
||||
ip="10.0.0.5", label="nas-old", hostname="nas.lan", notes="older note",
|
||||
properties=[{"key": "Rack", "value": "A1", "icon": None, "visible": True}],
|
||||
services=[{"port": 22, "protocol": "tcp", "service_name": "ssh"}],
|
||||
updated_at=_now(0),
|
||||
)
|
||||
newer = await self._legacy_node(
|
||||
db_session, design_b,
|
||||
ip="10.0.0.5", label="nas-new", os="TrueNAS",
|
||||
properties=[{"key": "Owner", "value": "me", "icon": None, "visible": True}],
|
||||
services=[{"port": 80, "protocol": "tcp", "service_name": "http"}],
|
||||
updated_at=_now(30),
|
||||
)
|
||||
|
||||
stats = await backfill_node_devices(db_session)
|
||||
await db_session.commit()
|
||||
|
||||
assert stats["linked"] == 2
|
||||
node_a = await db_session.get(Node, older)
|
||||
node_b = await db_session.get(Node, newer)
|
||||
assert node_a is not None and node_b is not None
|
||||
assert node_a.device_id == node_b.device_id
|
||||
device = await db_session.get(InventoryDevice, node_a.device_id)
|
||||
assert device is not None
|
||||
# Scalars: most recent edit wins, blanks never wipe an established value.
|
||||
assert device.label == "nas-new"
|
||||
assert device.hostname == "nas.lan"
|
||||
assert device.os == "TrueNAS"
|
||||
assert device.notes == "older note"
|
||||
# Cumulative fields: union of both canvases.
|
||||
assert {p["key"] for p in device.properties} == {"Rack", "Owner"}
|
||||
assert {s["port"] for s in device.services} == {22, 80}
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_leaves_canvas_furniture_alone(self, db_session):
|
||||
await self._legacy_nodes_table(db_session)
|
||||
design = await _design(db_session)
|
||||
for kind in ("group", "groupRect", "text"):
|
||||
await self._legacy_node(db_session, design, type=kind, label=kind)
|
||||
|
||||
stats = await backfill_node_devices(db_session)
|
||||
await db_session.commit()
|
||||
|
||||
assert stats["linked"] == 0
|
||||
assert (await db_session.execute(select(InventoryDevice))).scalars().all() == []
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_is_a_no_op_on_a_second_run(self, db_session):
|
||||
await self._legacy_nodes_table(db_session)
|
||||
design = await _design(db_session)
|
||||
await self._legacy_node(db_session, design, ip="10.0.0.5")
|
||||
|
||||
first = await backfill_node_devices(db_session)
|
||||
await db_session.commit()
|
||||
second = await backfill_node_devices(db_session)
|
||||
await db_session.commit()
|
||||
|
||||
assert first["linked"] == 1
|
||||
assert second == {"linked": 0, "created": 0, "merged": 0, "skipped": 0}
|
||||
rows = (await db_session.execute(select(InventoryDevice))).scalars().all()
|
||||
assert len(rows) == 1
|
||||
|
||||
|
||||
# --- routes -----------------------------------------------------------------
|
||||
|
||||
|
||||
class TestRoutesKeepTheLinkInStep:
|
||||
@pytest.mark.asyncio
|
||||
async def test_creating_a_node_joins_the_matching_row(self, client: AsyncClient, headers, db_session):
|
||||
db_session.add(InventoryDevice(id="d-1", ip="10.0.0.5", hostname="nas", os="TrueNAS"))
|
||||
await db_session.commit()
|
||||
|
||||
res = await client.post(
|
||||
"/api/v1/nodes",
|
||||
json={"type": "nas", "label": "NAS", "ip": "10.0.0.5", "force": True},
|
||||
headers=headers,
|
||||
)
|
||||
assert res.status_code == 201
|
||||
body = res.json()
|
||||
assert body["device_id"] == "d-1"
|
||||
# Hydrated from the row: the node never carried an OS.
|
||||
assert body["os"] == "TrueNAS"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_creating_furniture_creates_no_row(self, client: AsyncClient, headers, db_session):
|
||||
res = await client.post(
|
||||
"/api/v1/nodes", json={"type": "groupRect", "label": "Zone"}, headers=headers
|
||||
)
|
||||
assert res.status_code == 201
|
||||
assert res.json()["device_id"] is None
|
||||
rows = (await db_session.execute(select(InventoryDevice))).scalars().all()
|
||||
assert rows == []
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_editing_a_node_writes_through_to_the_row(self, client: AsyncClient, headers, db_session):
|
||||
db_session.add(InventoryDevice(id="d-1", ip="10.0.0.5", hostname="nas"))
|
||||
await db_session.commit()
|
||||
node_id = (
|
||||
await client.post(
|
||||
"/api/v1/nodes",
|
||||
json={"type": "nas", "label": "NAS", "ip": "10.0.0.5", "force": True},
|
||||
headers=headers,
|
||||
)
|
||||
).json()["id"]
|
||||
|
||||
res = await client.patch(
|
||||
f"/api/v1/nodes/{node_id}",
|
||||
json={"hostname": "nas2.lan", "notes": "moved to the garage"},
|
||||
headers=headers,
|
||||
)
|
||||
assert res.status_code == 200
|
||||
|
||||
device = await db_session.get(InventoryDevice, "d-1")
|
||||
await db_session.refresh(device)
|
||||
assert device.hostname == "nas2.lan"
|
||||
assert device.notes == "moved to the garage"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_patching_one_list_leaves_the_other_alone(self, client: AsyncClient, headers, db_session):
|
||||
"""Replace applies list by list — an unsent list is not blanked."""
|
||||
db_session.add(
|
||||
InventoryDevice(
|
||||
id="d-1",
|
||||
ip="10.0.0.5",
|
||||
services=[{"port": 22, "protocol": "tcp", "service_name": "ssh"}],
|
||||
properties=[{"key": "Rack", "value": "A1", "icon": None, "visible": True}],
|
||||
)
|
||||
)
|
||||
await db_session.commit()
|
||||
node_id = (
|
||||
await client.post(
|
||||
"/api/v1/nodes",
|
||||
json={"type": "nas", "label": "NAS", "ip": "10.0.0.5", "force": True},
|
||||
headers=headers,
|
||||
)
|
||||
).json()["id"]
|
||||
|
||||
# properties only: services must survive untouched.
|
||||
res = await client.patch(
|
||||
f"/api/v1/nodes/{node_id}",
|
||||
json={"properties": [{"key": "Owner", "value": "me", "icon": None, "visible": True}]},
|
||||
headers=headers,
|
||||
)
|
||||
assert res.status_code == 200
|
||||
device = await db_session.get(InventoryDevice, "d-1")
|
||||
await db_session.refresh(device)
|
||||
assert [p["key"] for p in device.properties] == ["Owner"]
|
||||
assert [s["port"] for s in device.services] == [22]
|
||||
|
||||
# services only: the properties just written must survive in turn.
|
||||
res = await client.patch(
|
||||
f"/api/v1/nodes/{node_id}",
|
||||
json={"services": [{"port": 443, "protocol": "tcp", "service_name": "https"}]},
|
||||
headers=headers,
|
||||
)
|
||||
assert res.status_code == 200
|
||||
await db_session.refresh(device)
|
||||
assert [s["port"] for s in device.services] == [443]
|
||||
assert [p["key"] for p in device.properties] == ["Owner"]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_patching_a_list_empty_still_clears_it(self, client: AsyncClient, headers, db_session):
|
||||
"""An explicit empty list is a deletion, not an omission."""
|
||||
db_session.add(
|
||||
InventoryDevice(
|
||||
id="d-1",
|
||||
ip="10.0.0.5",
|
||||
properties=[{"key": "Rack", "value": "A1", "icon": None, "visible": True}],
|
||||
)
|
||||
)
|
||||
await db_session.commit()
|
||||
node_id = (
|
||||
await client.post(
|
||||
"/api/v1/nodes",
|
||||
json={"type": "nas", "label": "NAS", "ip": "10.0.0.5", "force": True},
|
||||
headers=headers,
|
||||
)
|
||||
).json()["id"]
|
||||
|
||||
res = await client.patch(f"/api/v1/nodes/{node_id}", json={"properties": []}, headers=headers)
|
||||
assert res.status_code == 200
|
||||
device = await db_session.get(InventoryDevice, "d-1")
|
||||
await db_session.refresh(device)
|
||||
assert device.properties == []
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_canvas_save_does_not_revert_an_inventory_edit(
|
||||
self, client: AsyncClient, headers, db_session
|
||||
):
|
||||
"""Regression: a save carries this canvas' edit, not its stale snapshot.
|
||||
|
||||
The canvas payload holds a full copy of the device, hydrated when it
|
||||
loaded. Editing the device elsewhere and then saving the still-open
|
||||
canvas — for nothing but a moved node — must not roll the row back.
|
||||
"""
|
||||
db_session.add(
|
||||
InventoryDevice(
|
||||
id="d-1",
|
||||
ip="10.0.0.5",
|
||||
label="NAS",
|
||||
type="nas",
|
||||
notes="old note",
|
||||
status="approved",
|
||||
properties=[{"key": "Rack", "value": "A1", "icon": None, "visible": True}],
|
||||
)
|
||||
)
|
||||
await db_session.commit()
|
||||
design_id = (await client.post("/api/v1/designs", json={"name": "A"}, headers=headers)).json()["id"]
|
||||
|
||||
# What the canvas loaded and still holds in memory.
|
||||
stale = {
|
||||
"id": str(uuid.uuid4()),
|
||||
"type": "nas",
|
||||
"label": "NAS",
|
||||
"status": "unknown",
|
||||
"pos_x": 0,
|
||||
"pos_y": 0,
|
||||
"ip": "10.0.0.5",
|
||||
"notes": "old note",
|
||||
"properties": [{"key": "Rack", "value": "A1", "icon": None, "visible": True}],
|
||||
}
|
||||
res = await client.post(
|
||||
"/api/v1/canvas/save",
|
||||
json={"design_id": design_id, "nodes": [stale], "edges": [], "viewport": {}},
|
||||
headers=headers,
|
||||
)
|
||||
assert res.status_code == 200
|
||||
|
||||
# Meanwhile, in the Device Inventory modal.
|
||||
res = await client.patch(
|
||||
"/api/v1/scan/pending/d-1",
|
||||
json={
|
||||
"notes": "moved to the loft",
|
||||
"properties": [
|
||||
{"key": "Rack", "value": "A1", "icon": None, "visible": True},
|
||||
{"key": "Owner", "value": "me", "icon": None, "visible": True},
|
||||
],
|
||||
},
|
||||
headers=headers,
|
||||
)
|
||||
assert res.status_code == 200
|
||||
|
||||
# The canvas saves again — only the node position changed, so it claims
|
||||
# no device edit at all.
|
||||
res = await client.post(
|
||||
"/api/v1/canvas/save",
|
||||
json={
|
||||
"design_id": design_id,
|
||||
"nodes": [{**stale, "pos_x": 240, "changed_facts": []}],
|
||||
"edges": [],
|
||||
"viewport": {},
|
||||
},
|
||||
headers=headers,
|
||||
)
|
||||
assert res.status_code == 200
|
||||
|
||||
device = await db_session.get(InventoryDevice, "d-1")
|
||||
await db_session.refresh(device)
|
||||
assert device.notes == "moved to the loft"
|
||||
assert [p["key"] for p in device.properties] == ["Rack", "Owner"]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_canvas_save_still_writes_what_that_canvas_changed(
|
||||
self, client: AsyncClient, headers, db_session
|
||||
):
|
||||
"""The narrowing must not cost the write-through: an edit still lands."""
|
||||
db_session.add(InventoryDevice(id="d-1", ip="10.0.0.5", label="NAS", type="nas", notes="old note"))
|
||||
await db_session.commit()
|
||||
design_id = (await client.post("/api/v1/designs", json={"name": "A"}, headers=headers)).json()["id"]
|
||||
node = {
|
||||
"id": str(uuid.uuid4()),
|
||||
"type": "nas",
|
||||
"label": "NAS",
|
||||
"status": "unknown",
|
||||
"pos_x": 0,
|
||||
"pos_y": 0,
|
||||
"ip": "10.0.0.5",
|
||||
"notes": "old note",
|
||||
}
|
||||
await client.post(
|
||||
"/api/v1/canvas/save",
|
||||
json={"design_id": design_id, "nodes": [node], "edges": [], "viewport": {}},
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
res = await client.post(
|
||||
"/api/v1/canvas/save",
|
||||
json={
|
||||
"design_id": design_id,
|
||||
"nodes": [
|
||||
{
|
||||
**node,
|
||||
"notes": "edited on the canvas",
|
||||
"hostname": "nas.lan",
|
||||
"changed_facts": ["notes", "hostname"],
|
||||
}
|
||||
],
|
||||
"edges": [],
|
||||
"viewport": {},
|
||||
},
|
||||
headers=headers,
|
||||
)
|
||||
assert res.status_code == 200
|
||||
|
||||
device = await db_session.get(InventoryDevice, "d-1")
|
||||
await db_session.refresh(device)
|
||||
assert device.notes == "edited on the canvas"
|
||||
assert device.hostname == "nas.lan"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_an_edit_writes_without_dragging_the_rest_of_the_snapshot(
|
||||
self, client: AsyncClient, headers, db_session
|
||||
):
|
||||
"""One edited fact lands; the stale fields beside it stay out of the write."""
|
||||
db_session.add(
|
||||
InventoryDevice(id="d-1", ip="10.0.0.5", label="NAS", type="nas", notes="old note")
|
||||
)
|
||||
await db_session.commit()
|
||||
design_id = (await client.post("/api/v1/designs", json={"name": "A"}, headers=headers)).json()["id"]
|
||||
node = {
|
||||
"id": str(uuid.uuid4()),
|
||||
"type": "nas",
|
||||
"label": "NAS",
|
||||
"status": "unknown",
|
||||
"pos_x": 0,
|
||||
"pos_y": 0,
|
||||
"ip": "10.0.0.5",
|
||||
"notes": "old note",
|
||||
}
|
||||
await client.post(
|
||||
"/api/v1/canvas/save",
|
||||
json={"design_id": design_id, "nodes": [node], "edges": [], "viewport": {}},
|
||||
headers=headers,
|
||||
)
|
||||
await client.patch("/api/v1/scan/pending/d-1", json={"notes": "moved to the loft"}, headers=headers)
|
||||
|
||||
# The canvas renames the node; its `notes` copy is stale but unedited.
|
||||
await client.post(
|
||||
"/api/v1/canvas/save",
|
||||
json={
|
||||
"design_id": design_id,
|
||||
"nodes": [{**node, "label": "Big NAS", "changed_facts": ["label"]}],
|
||||
"edges": [],
|
||||
"viewport": {},
|
||||
},
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
device = await db_session.get(InventoryDevice, "d-1")
|
||||
await db_session.refresh(device)
|
||||
assert device.label == "Big NAS"
|
||||
assert device.notes == "moved to the loft"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_client_that_tracks_no_changes_still_writes_its_facts(
|
||||
self, client: AsyncClient, headers, db_session
|
||||
):
|
||||
"""Backward compatible: an import or older client omits the field entirely."""
|
||||
db_session.add(InventoryDevice(id="d-1", ip="10.0.0.5", notes="old note"))
|
||||
await db_session.commit()
|
||||
design_id = (await client.post("/api/v1/designs", json={"name": "A"}, headers=headers)).json()["id"]
|
||||
|
||||
await client.post(
|
||||
"/api/v1/canvas/save",
|
||||
json={
|
||||
"design_id": design_id,
|
||||
"nodes": [
|
||||
{
|
||||
"id": str(uuid.uuid4()),
|
||||
"type": "nas",
|
||||
"label": "NAS",
|
||||
"status": "unknown",
|
||||
"pos_x": 0,
|
||||
"pos_y": 0,
|
||||
"ip": "10.0.0.5",
|
||||
"notes": "from the import",
|
||||
}
|
||||
],
|
||||
"edges": [],
|
||||
"viewport": {},
|
||||
},
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
device = await db_session.get(InventoryDevice, "d-1")
|
||||
await db_session.refresh(device)
|
||||
assert device.notes == "from the import"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_the_second_canvas_sees_the_first_canvas_edit(self, client: AsyncClient, headers, db_session):
|
||||
"""No per-node overrides: one device, one set of facts, every canvas."""
|
||||
db_session.add(InventoryDevice(id="d-1", ip="10.0.0.5"))
|
||||
await db_session.commit()
|
||||
design_a = (await client.post("/api/v1/designs", json={"name": "A"}, headers=headers)).json()["id"]
|
||||
design_b = (await client.post("/api/v1/designs", json={"name": "B"}, headers=headers)).json()["id"]
|
||||
node_a = (
|
||||
await client.post(
|
||||
"/api/v1/nodes",
|
||||
json={"type": "nas", "label": "NAS", "ip": "10.0.0.5", "design_id": design_a, "force": True},
|
||||
headers=headers,
|
||||
)
|
||||
).json()["id"]
|
||||
await client.post(
|
||||
"/api/v1/nodes",
|
||||
json={"type": "nas", "label": "NAS", "ip": "10.0.0.5", "design_id": design_b, "force": True},
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
await client.patch(f"/api/v1/nodes/{node_a}", json={"ip": "10.0.0.9"}, headers=headers)
|
||||
|
||||
canvas_b = (await client.get(f"/api/v1/canvas?design_id={design_b}", headers=headers)).json()
|
||||
assert canvas_b["nodes"][0]["ip"] == "10.0.0.9"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_the_wire_shape_the_mcp_server_reads_is_unchanged(
|
||||
self, client: AsyncClient, headers, db_session
|
||||
):
|
||||
"""`mcp/app/tools.py` reads the facts flat on the node — keep it that way.
|
||||
|
||||
The MCP server is a thin proxy over these routes: `_slim_canvas` keeps
|
||||
`NODE_KEEP`, `_slim_node_summary` keeps label/type/status, and `get_node`
|
||||
looks a node up by label. None of it knows the inventory row exists, so
|
||||
the split must not show on the wire.
|
||||
"""
|
||||
db_session.add(
|
||||
InventoryDevice(
|
||||
id="d-1",
|
||||
ip="10.0.0.5",
|
||||
hostname="nas.lan",
|
||||
mac="aa:bb:cc:dd:ee:ff",
|
||||
os="TrueNAS",
|
||||
notes="in the garage",
|
||||
cpu_count=8,
|
||||
cpu_model="Xeon",
|
||||
ram_gb=32.0,
|
||||
disk_gb=4000.0,
|
||||
services=[{"port": 22, "protocol": "tcp", "service_name": "ssh"}],
|
||||
properties=[{"key": "Rack", "value": "A1", "icon": None, "visible": True}],
|
||||
status_live="online",
|
||||
)
|
||||
)
|
||||
await db_session.commit()
|
||||
design_id = (await client.post("/api/v1/designs", json={"name": "Net"}, headers=headers)).json()["id"]
|
||||
created = (
|
||||
await client.post(
|
||||
"/api/v1/nodes",
|
||||
json={
|
||||
"type": "nas", "label": "NAS", "ip": "10.0.0.5",
|
||||
"design_id": design_id, "force": True,
|
||||
},
|
||||
headers=headers,
|
||||
)
|
||||
).json()
|
||||
|
||||
# mcp `_slim_canvas` NODE_KEEP, plus what `_slim_node_summary` reads.
|
||||
expected = {
|
||||
"type": "nas",
|
||||
"label": "NAS",
|
||||
"ip": "10.0.0.5",
|
||||
"hostname": "nas.lan",
|
||||
"mac": "aa:bb:cc:dd:ee:ff",
|
||||
"os": "TrueNAS",
|
||||
"status": "online",
|
||||
"notes": "in the garage",
|
||||
"cpu_count": 8,
|
||||
"cpu_model": "Xeon",
|
||||
"ram_gb": 32.0,
|
||||
"disk_gb": 4000.0,
|
||||
}
|
||||
for source in (
|
||||
created,
|
||||
(await client.get(f"/api/v1/nodes/{created['id']}", headers=headers)).json(),
|
||||
(await client.get("/api/v1/nodes", headers=headers)).json()[0],
|
||||
(await client.get("/api/v1/canvas", headers=headers)).json()["nodes"][0],
|
||||
# mcp `get_node` falls back to a label lookup when given no id.
|
||||
(await client.get("/api/v1/nodes?label=NAS", headers=headers)).json()[0],
|
||||
):
|
||||
assert {k: source[k] for k in expected} == expected
|
||||
assert source["services"] == [{"port": 22, "protocol": "tcp", "service_name": "ssh"}]
|
||||
assert source["properties"] == [
|
||||
{"key": "Rack", "value": "A1", "icon": None, "visible": True}
|
||||
]
|
||||
assert "parent_id" in source
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_deleting_a_node_keeps_the_device(self, client: AsyncClient, headers, db_session):
|
||||
db_session.add(InventoryDevice(id="d-1", ip="10.0.0.5"))
|
||||
await db_session.commit()
|
||||
node_id = (
|
||||
await client.post(
|
||||
"/api/v1/nodes",
|
||||
json={"type": "nas", "label": "NAS", "ip": "10.0.0.5", "force": True},
|
||||
headers=headers,
|
||||
)
|
||||
).json()["id"]
|
||||
|
||||
assert (await client.delete(f"/api/v1/nodes/{node_id}", headers=headers)).status_code == 204
|
||||
assert await db_session.get(InventoryDevice, "d-1") is not None
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_approving_a_device_links_instead_of_copying(self, client: AsyncClient, headers, db_session):
|
||||
db_session.add(
|
||||
InventoryDevice(id="d-1", ip="10.0.0.5", hostname="nas", suggested_type="nas", status="pending")
|
||||
)
|
||||
await db_session.commit()
|
||||
|
||||
res = await client.post(
|
||||
"/api/v1/scan/pending/d-1/approve",
|
||||
json={"type": "nas", "label": "NAS", "ip": "10.0.0.5", "status": "unknown"},
|
||||
headers=headers,
|
||||
)
|
||||
assert res.status_code == 200
|
||||
node = await db_session.get(Node, res.json()["node_id"])
|
||||
assert node is not None and node.device_id == "d-1"
|
||||
@@ -1,10 +1,16 @@
|
||||
"""Tests for the same-canvas node dedupe repair (app.services.node_dedupe)."""
|
||||
"""Tests for the same-canvas node dedupe repair (app.services.node_dedupe).
|
||||
|
||||
Identity is the device link now: two nodes are duplicates when they draw the
|
||||
same `device_inventory` row on the same design. The device facts live on that
|
||||
row, so nothing has to be merged out of the extras before they go — only edges
|
||||
and parent links are re-pointed.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.db.models import Design, Edge, Node
|
||||
from app.services.node_dedupe import dedupe_nodes_by_ieee
|
||||
from app.db.models import Design, Edge, InventoryDevice, Node
|
||||
from app.services.node_dedupe import dedupe_nodes_by_device
|
||||
|
||||
|
||||
async def _design(db, name="d1"):
|
||||
@@ -14,61 +20,80 @@ async def _design(db, name="d1"):
|
||||
return d
|
||||
|
||||
|
||||
async def _device(db, ieee="0xAAA", **kwargs):
|
||||
device = InventoryDevice(ieee_address=ieee, status="approved", **kwargs)
|
||||
db.add(device)
|
||||
await db.flush()
|
||||
return device
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_collapses_same_ieee_same_design(db_session):
|
||||
async def test_collapses_same_device_same_design(db_session):
|
||||
d = await _design(db_session)
|
||||
device = await _device(db_session)
|
||||
keep = Node(
|
||||
label="Sensor", type="zigbee_enddevice", design_id=d.id,
|
||||
ieee_address="0xAAA", properties=[{"key": "IEEE", "value": "0xAAA", "visible": True}],
|
||||
pos_x=100, pos_y=200,
|
||||
device_id=device.id, pos_x=100, pos_y=200,
|
||||
)
|
||||
db_session.add(keep)
|
||||
await db_session.flush()
|
||||
dup = Node(
|
||||
label="Sensor", type="zigbee_enddevice", design_id=d.id,
|
||||
ieee_address="0xAAA", ip="10.0.0.5",
|
||||
properties=[{"key": "LQI", "value": "88", "visible": False}],
|
||||
)
|
||||
dup = Node(label="Sensor", type="zigbee_enddevice", design_id=d.id, device_id=device.id)
|
||||
db_session.add(dup)
|
||||
await db_session.flush()
|
||||
|
||||
removed = await dedupe_nodes_by_ieee(db_session)
|
||||
removed = await dedupe_nodes_by_device(db_session)
|
||||
assert removed == 1
|
||||
|
||||
nodes = (await db_session.execute(select(Node).where(Node.ieee_address == "0xAAA"))).scalars().all()
|
||||
nodes = (
|
||||
await db_session.execute(select(Node).where(Node.device_id == device.id))
|
||||
).scalars().all()
|
||||
assert len(nodes) == 1
|
||||
survivor = nodes[0]
|
||||
assert survivor.id == keep.id # oldest kept
|
||||
assert survivor.pos_x == 100 # canvas position preserved
|
||||
assert survivor.ip == "10.0.0.5" # missing field filled from dup
|
||||
keys = {p["key"] for p in survivor.properties}
|
||||
assert keys == {"IEEE", "LQI"} # properties merged
|
||||
# The device facts were never on the node, so none can be lost here.
|
||||
assert await db_session.get(InventoryDevice, device.id) is not None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_preserves_same_ieee_across_designs(db_session):
|
||||
async def test_preserves_same_device_across_designs(db_session):
|
||||
"""Same device on two canvases is valid — must NOT be merged."""
|
||||
d1 = await _design(db_session, "d1")
|
||||
d2 = await _design(db_session, "d2")
|
||||
device = await _device(db_session, ieee="0xBBB")
|
||||
for d in (d1, d2):
|
||||
db_session.add(Node(label="S", type="zigbee_enddevice", design_id=d.id, ieee_address="0xBBB"))
|
||||
db_session.add(Node(label="S", type="zigbee_enddevice", design_id=d.id, device_id=device.id))
|
||||
await db_session.flush()
|
||||
|
||||
removed = await dedupe_nodes_by_ieee(db_session)
|
||||
removed = await dedupe_nodes_by_device(db_session)
|
||||
assert removed == 0
|
||||
|
||||
nodes = (await db_session.execute(select(Node).where(Node.ieee_address == "0xBBB"))).scalars().all()
|
||||
nodes = (
|
||||
await db_session.execute(select(Node).where(Node.device_id == device.id))
|
||||
).scalars().all()
|
||||
assert len(nodes) == 2
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_leaves_furniture_alone(db_session):
|
||||
"""Zones and text carry no device link, so they are never duplicates."""
|
||||
d = await _design(db_session)
|
||||
for _ in range(2):
|
||||
db_session.add(Node(label="Zone", type="groupRect", design_id=d.id))
|
||||
await db_session.flush()
|
||||
|
||||
assert await dedupe_nodes_by_device(db_session) == 0
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_repoints_edges_and_drops_dupes(db_session):
|
||||
d = await _design(db_session)
|
||||
keep = Node(label="A", type="server", design_id=d.id, ieee_address="0xCCC")
|
||||
dup = Node(label="A", type="server", design_id=d.id, ieee_address="0xCCC")
|
||||
device = await _device(db_session, ieee="0xCCC")
|
||||
keep = Node(label="A", type="server", design_id=d.id, device_id=device.id)
|
||||
other = Node(label="B", type="server", design_id=d.id)
|
||||
db_session.add_all([keep, other])
|
||||
await db_session.flush()
|
||||
dup = Node(label="A", type="server", design_id=d.id, device_id=device.id)
|
||||
db_session.add(dup)
|
||||
await db_session.flush()
|
||||
|
||||
@@ -80,7 +105,7 @@ async def test_repoints_edges_and_drops_dupes(db_session):
|
||||
])
|
||||
await db_session.flush()
|
||||
|
||||
removed = await dedupe_nodes_by_ieee(db_session)
|
||||
removed = await dedupe_nodes_by_device(db_session)
|
||||
assert removed == 1
|
||||
|
||||
edges = (await db_session.execute(select(Edge))).scalars().all()
|
||||
@@ -93,17 +118,18 @@ async def test_repoints_edges_and_drops_dupes(db_session):
|
||||
@pytest.mark.asyncio
|
||||
async def test_repoints_child_parent(db_session):
|
||||
d = await _design(db_session)
|
||||
keep = Node(label="Host", type="proxmox", design_id=d.id, ieee_address="0xDDD")
|
||||
dup = Node(label="Host", type="proxmox", design_id=d.id, ieee_address="0xDDD")
|
||||
device = await _device(db_session, ieee="0xDDD")
|
||||
keep = Node(label="Host", type="proxmox", design_id=d.id, device_id=device.id)
|
||||
db_session.add(keep)
|
||||
await db_session.flush()
|
||||
dup = Node(label="Host", type="proxmox", design_id=d.id, device_id=device.id)
|
||||
db_session.add(dup)
|
||||
await db_session.flush()
|
||||
child = Node(label="VM", type="vm", design_id=d.id, parent_id=dup.id)
|
||||
db_session.add(child)
|
||||
await db_session.flush()
|
||||
|
||||
await dedupe_nodes_by_ieee(db_session)
|
||||
await dedupe_nodes_by_device(db_session)
|
||||
await db_session.refresh(child)
|
||||
assert child.parent_id == keep.id
|
||||
|
||||
@@ -111,7 +137,8 @@ async def test_repoints_child_parent(db_session):
|
||||
@pytest.mark.asyncio
|
||||
async def test_idempotent_noop_when_unique(db_session):
|
||||
d = await _design(db_session)
|
||||
db_session.add(Node(label="X", type="server", design_id=d.id, ieee_address="0xEEE"))
|
||||
device = await _device(db_session, ieee="0xEEE")
|
||||
db_session.add(Node(label="X", type="server", design_id=d.id, device_id=device.id))
|
||||
await db_session.flush()
|
||||
assert await dedupe_nodes_by_ieee(db_session) == 0
|
||||
assert await dedupe_nodes_by_ieee(db_session) == 0
|
||||
assert await dedupe_nodes_by_device(db_session) == 0
|
||||
assert await dedupe_nodes_by_device(db_session) == 0
|
||||
|
||||
@@ -363,3 +363,43 @@ async def test_create_node_explicit_zero_position_preserved(client: AsyncClient,
|
||||
)
|
||||
assert res.status_code == 201
|
||||
assert (res.json()["pos_x"], res.json()["pos_y"]) == (0.0, 0.0)
|
||||
|
||||
|
||||
async def test_list_nodes_filters_by_label_exact(client: AsyncClient, headers: dict):
|
||||
await client.post("/api/v1/nodes", json={"type": "server", "label": "Proxmox", "status": "unknown"}, headers=headers)
|
||||
await client.post("/api/v1/nodes", json={"type": "router", "label": "Router", "status": "unknown"}, headers=headers)
|
||||
res = await client.get("/api/v1/nodes?label=Proxmox", headers=headers)
|
||||
assert res.status_code == 200
|
||||
assert [n["label"] for n in res.json()] == ["Proxmox"]
|
||||
|
||||
|
||||
async def test_list_nodes_filters_by_label_substring(client: AsyncClient, headers: dict):
|
||||
await client.post("/api/v1/nodes", json={"type": "server", "label": "pve1-node", "status": "unknown"}, headers=headers)
|
||||
await client.post("/api/v1/nodes", json={"type": "server", "label": "pve2-node", "status": "unknown"}, headers=headers)
|
||||
await client.post("/api/v1/nodes", json={"type": "router", "label": "Router", "status": "unknown"}, headers=headers)
|
||||
res = await client.get("/api/v1/nodes?label=pve", headers=headers)
|
||||
assert res.status_code == 200
|
||||
assert sorted(n["label"] for n in res.json()) == ["pve1-node", "pve2-node"]
|
||||
|
||||
|
||||
async def test_list_nodes_filters_by_label_case_insensitive(client: AsyncClient, headers: dict):
|
||||
await client.post("/api/v1/nodes", json={"type": "server", "label": "Proxmox", "status": "unknown"}, headers=headers)
|
||||
res = await client.get("/api/v1/nodes?label=PROXMOX", headers=headers)
|
||||
assert res.status_code == 200
|
||||
assert [n["label"] for n in res.json()] == ["Proxmox"]
|
||||
|
||||
|
||||
async def test_list_nodes_filters_by_label_no_match(client: AsyncClient, headers: dict):
|
||||
await client.post("/api/v1/nodes", json={"type": "server", "label": "Proxmox", "status": "unknown"}, headers=headers)
|
||||
res = await client.get("/api/v1/nodes?label=nonexistent", headers=headers)
|
||||
assert res.status_code == 200
|
||||
assert res.json() == []
|
||||
|
||||
|
||||
async def test_list_nodes_without_label_param_returns_all(client: AsyncClient, headers: dict):
|
||||
"""Omitting label is fully backward compatible with the old unfiltered behavior."""
|
||||
for label in ("A", "B", "C"):
|
||||
await client.post("/api/v1/nodes", json={"type": "generic", "label": label, "status": "unknown"}, headers=headers)
|
||||
res = await client.get("/api/v1/nodes", headers=headers)
|
||||
assert res.status_code == 200
|
||||
assert len(res.json()) == 3
|
||||
|
||||
@@ -17,7 +17,7 @@ from app.api.routes.proxmox import (
|
||||
)
|
||||
from app.api.routes.scan import _is_proxmox_cluster_member, _resolve_pending_links_for_ieee
|
||||
from app.core.config import settings
|
||||
from app.db.models import Design, Edge, Node, PendingDevice, PendingDeviceLink
|
||||
from app.db.models import Design, Edge, InventoryDevice, InventoryDeviceLink, Node
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
@@ -212,7 +212,7 @@ async def test_persist_creates_pending(db_session) -> None:
|
||||
result = await _persist_pending_import(db_session, nodes, edges)
|
||||
assert result.pending_created == 2
|
||||
assert result.links_recorded == 1
|
||||
rows = (await db_session.execute(select(PendingDevice))).scalars().all()
|
||||
rows = (await db_session.execute(select(InventoryDevice))).scalars().all()
|
||||
assert {r.suggested_type for r in rows} == {"proxmox", "vm"}
|
||||
# Specs carried as properties.
|
||||
vm = next(r for r in rows if r.suggested_type == "vm")
|
||||
@@ -222,31 +222,39 @@ async def test_persist_creates_pending(db_session) -> None:
|
||||
@pytest.mark.asyncio
|
||||
async def test_persist_merges_existing_scanned_node_by_ip(db_session) -> None:
|
||||
# A device previously found by an IP scan (no ieee, no specs).
|
||||
# The scanned host: one inventory row, drawn by one node.
|
||||
scanned_device = InventoryDevice(
|
||||
id=str(uuid.uuid4()), ip="10.0.0.5", suggested_type="generic",
|
||||
status="approved", discovery_source="arp", discovery_sources=["arp"],
|
||||
)
|
||||
db_session.add(scanned_device)
|
||||
await db_session.flush()
|
||||
scanned = Node(
|
||||
id=str(uuid.uuid4()), type="generic", label="10.0.0.5",
|
||||
ip="10.0.0.5", status="online", pos_x=0, pos_y=0,
|
||||
device_id=scanned_device.id, pos_x=0, pos_y=0,
|
||||
)
|
||||
db_session.add(scanned)
|
||||
await db_session.commit()
|
||||
|
||||
await _persist_pending_import(db_session, [_guest_node(101, "10.0.0.5")], [])
|
||||
|
||||
# No duplicate node; identity + specs merged onto the existing one.
|
||||
nodes = (await db_session.execute(select(Node).where(Node.ip == "10.0.0.5"))).scalars().all()
|
||||
# No duplicate node, and no second row: the import merged into the row the
|
||||
# node already draws.
|
||||
nodes = (await db_session.execute(select(Node))).scalars().all()
|
||||
assert len(nodes) == 1
|
||||
merged = nodes[0]
|
||||
merged = await db_session.get(InventoryDevice, nodes[0].device_id)
|
||||
assert merged is not None
|
||||
assert merged.ieee_address == "pve-pve1-101"
|
||||
assert merged.cpu_count == 2
|
||||
assert any(p["key"] == "CPU Cores" for p in (merged.properties or []))
|
||||
# Inventory row exists as approved (already on canvas).
|
||||
inv = (await db_session.execute(select(PendingDevice).where(PendingDevice.ieee_address == "pve-pve1-101"))).scalar_one()
|
||||
assert inv.status == "approved"
|
||||
# Still approved — it is on a canvas.
|
||||
assert merged.status == "approved"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_persist_merges_pending_scan_row_by_mac(db_session) -> None:
|
||||
# Device previously found by an IP scan: arp source, MAC known, no ieee.
|
||||
db_session.add(PendingDevice(
|
||||
db_session.add(InventoryDevice(
|
||||
id=str(uuid.uuid4()), ip="10.0.0.5", mac="bc:24:11:aa:bb:cc",
|
||||
suggested_type="generic", status="pending",
|
||||
discovery_source="arp", discovery_sources=["arp"],
|
||||
@@ -257,7 +265,7 @@ async def test_persist_merges_pending_scan_row_by_mac(db_session) -> None:
|
||||
# different casing. Must merge, not duplicate.
|
||||
await _persist_pending_import(db_session, [_guest_node(101, None, mac="BC:24:11:AA:BB:CC")], [])
|
||||
|
||||
rows = (await db_session.execute(select(PendingDevice))).scalars().all()
|
||||
rows = (await db_session.execute(select(InventoryDevice))).scalars().all()
|
||||
assert len(rows) == 1
|
||||
row = rows[0]
|
||||
assert row.ieee_address == "pve-pve1-101" # adopted proxmox identity
|
||||
@@ -269,7 +277,7 @@ async def test_persist_merges_pending_scan_row_by_mac(db_session) -> None:
|
||||
async def test_persist_preserves_ip_tag_for_legacy_null_source_row(db_session) -> None:
|
||||
# Legacy inventory row from an old IP scan, before discovery_source(s) were
|
||||
# recorded: scalar NULL, sources empty — but it has an IP + MAC.
|
||||
db_session.add(PendingDevice(
|
||||
db_session.add(InventoryDevice(
|
||||
id=str(uuid.uuid4()), ip="192.168.1.108", mac="bc:24:11:6c:96:52",
|
||||
suggested_type="lxc", status="pending",
|
||||
discovery_source=None, discovery_sources=[],
|
||||
@@ -280,7 +288,7 @@ async def test_persist_preserves_ip_tag_for_legacy_null_source_row(db_session) -
|
||||
db_session, [_guest_node(108, "192.168.1.108", mac="BC:24:11:6C:96:52")], []
|
||||
)
|
||||
|
||||
rows = (await db_session.execute(select(PendingDevice))).scalars().all()
|
||||
rows = (await db_session.execute(select(InventoryDevice))).scalars().all()
|
||||
assert len(rows) == 1
|
||||
# The IP tag must survive the proxmox merge even with no recorded origin.
|
||||
assert set(rows[0].discovery_sources) == {"arp", "proxmox"}
|
||||
@@ -290,17 +298,17 @@ async def test_persist_preserves_ip_tag_for_legacy_null_source_row(db_session) -
|
||||
async def test_persist_preserves_ip_tag_on_canvas_merge_legacy_row(db_session) -> None:
|
||||
# The immich case: an on-canvas node from an old scan, with a legacy
|
||||
# inventory row (NULL source). Merge must keep the IP tag on the row.
|
||||
node = Node(
|
||||
id=str(uuid.uuid4()), type="lxc", label="immich",
|
||||
ip="192.168.1.108", mac="bc:24:11:6c:96:52",
|
||||
status="online", pos_x=0, pos_y=0,
|
||||
)
|
||||
inv = PendingDevice(
|
||||
inv = InventoryDevice(
|
||||
id=str(uuid.uuid4()), ip="192.168.1.108", mac="bc:24:11:6c:96:52",
|
||||
suggested_type="lxc", status="approved",
|
||||
discovery_source=None, discovery_sources=[],
|
||||
)
|
||||
db_session.add_all([node, inv])
|
||||
db_session.add(inv)
|
||||
await db_session.flush()
|
||||
db_session.add(Node(
|
||||
id=str(uuid.uuid4()), type="lxc", label="immich",
|
||||
device_id=inv.id, pos_x=0, pos_y=0,
|
||||
))
|
||||
await db_session.commit()
|
||||
|
||||
await _persist_pending_import(
|
||||
@@ -308,7 +316,7 @@ async def test_persist_preserves_ip_tag_on_canvas_merge_legacy_row(db_session) -
|
||||
)
|
||||
|
||||
inv_row = (await db_session.execute(
|
||||
select(PendingDevice).where(PendingDevice.mac == "bc:24:11:6c:96:52")
|
||||
select(InventoryDevice).where(InventoryDevice.mac == "bc:24:11:6c:96:52")
|
||||
)).scalar_one()
|
||||
assert set(inv_row.discovery_sources) == {"arp", "proxmox"}
|
||||
|
||||
@@ -320,7 +328,7 @@ async def test_persist_does_not_add_ip_tag_to_pure_proxmox_guest(db_session) ->
|
||||
await _persist_pending_import(db_session, [_guest_node(101, "10.0.0.5")], [])
|
||||
await _persist_pending_import(db_session, [_guest_node(101, "10.0.0.5")], []) # re-sync
|
||||
row = (await db_session.execute(
|
||||
select(PendingDevice).where(PendingDevice.ieee_address == "pve-pve1-101")
|
||||
select(InventoryDevice).where(InventoryDevice.ieee_address == "pve-pve1-101")
|
||||
)).scalar_one()
|
||||
assert set(row.discovery_sources) == {"proxmox"}
|
||||
|
||||
@@ -328,9 +336,15 @@ async def test_persist_does_not_add_ip_tag_to_pure_proxmox_guest(db_session) ->
|
||||
@pytest.mark.asyncio
|
||||
async def test_persist_merges_canvas_node_by_mac(db_session) -> None:
|
||||
# A scanned canvas node with a MAC but no IP recorded for the guest.
|
||||
scanned_device = InventoryDevice(
|
||||
id=str(uuid.uuid4()), mac="bc:24:11:aa:bb:cc", suggested_type="generic",
|
||||
status="approved", discovery_source="arp", discovery_sources=["arp"],
|
||||
)
|
||||
db_session.add(scanned_device)
|
||||
await db_session.flush()
|
||||
scanned = Node(
|
||||
id=str(uuid.uuid4()), type="generic", label="box",
|
||||
mac="bc:24:11:aa:bb:cc", status="online", pos_x=0, pos_y=0,
|
||||
device_id=scanned_device.id, pos_x=0, pos_y=0,
|
||||
)
|
||||
db_session.add(scanned)
|
||||
await db_session.commit()
|
||||
@@ -339,7 +353,8 @@ async def test_persist_merges_canvas_node_by_mac(db_session) -> None:
|
||||
|
||||
nodes = (await db_session.execute(select(Node))).scalars().all()
|
||||
assert len(nodes) == 1 # no duplicate node
|
||||
merged = nodes[0]
|
||||
merged = await db_session.get(InventoryDevice, nodes[0].device_id)
|
||||
assert merged is not None
|
||||
assert merged.ieee_address == "pve-pve1-101"
|
||||
assert merged.mac == "bc:24:11:aa:bb:cc"
|
||||
assert merged.cpu_count == 2 # specs backfilled
|
||||
@@ -351,27 +366,27 @@ async def test_persist_resync_updates_in_place(db_session) -> None:
|
||||
await _persist_pending_import(db_session, nodes, [])
|
||||
# Second sync: same device, new IP. Should update, not duplicate.
|
||||
await _persist_pending_import(db_session, [_guest_node(101, "10.0.0.9")], [])
|
||||
rows = (await db_session.execute(select(PendingDevice).where(PendingDevice.ieee_address == "pve-pve1-101"))).scalars().all()
|
||||
rows = (await db_session.execute(select(InventoryDevice).where(InventoryDevice.ieee_address == "pve-pve1-101"))).scalars().all()
|
||||
assert len(rows) == 1
|
||||
assert rows[0].ip == "10.0.0.9"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_persist_keeps_hidden_hidden(db_session) -> None:
|
||||
db_session.add(PendingDevice(
|
||||
db_session.add(InventoryDevice(
|
||||
id=str(uuid.uuid4()), ieee_address="pve-pve1-101", ip="10.0.0.5",
|
||||
suggested_type="vm", status="hidden", discovery_source="proxmox",
|
||||
))
|
||||
await db_session.commit()
|
||||
await _persist_pending_import(db_session, [_guest_node(101, "10.0.0.5")], [])
|
||||
row = (await db_session.execute(select(PendingDevice).where(PendingDevice.ieee_address == "pve-pve1-101"))).scalar_one()
|
||||
row = (await db_session.execute(select(InventoryDevice).where(InventoryDevice.ieee_address == "pve-pve1-101"))).scalar_one()
|
||||
assert row.status == "hidden"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_pending_endpoint_tolerates_legacy_null_properties(client: AsyncClient, headers: dict, db_session) -> None:
|
||||
# Legacy row: properties column NULL (added by migration on older DBs).
|
||||
dev = PendingDevice(
|
||||
dev = InventoryDevice(
|
||||
id=str(uuid.uuid4()), ip="192.168.1.9", suggested_type="server",
|
||||
status="pending", discovery_source="arp",
|
||||
)
|
||||
@@ -396,7 +411,7 @@ async def test_persist_records_cluster_links_between_hosts(db_session) -> None:
|
||||
edges = [{"source": "pve-node-pve1", "target": "pve-pve1-101"}]
|
||||
await _persist_pending_import(db_session, nodes, edges)
|
||||
|
||||
links = (await db_session.execute(select(PendingDeviceLink))).scalars().all()
|
||||
links = (await db_session.execute(select(InventoryDeviceLink))).scalars().all()
|
||||
cluster = [ln for ln in links if ln.discovery_source == "proxmox_cluster"]
|
||||
assert len(cluster) == 1
|
||||
assert (cluster[0].source_ieee, cluster[0].target_ieee) == ("pve-node-a", "pve-node-b")
|
||||
@@ -410,7 +425,7 @@ async def test_persist_records_cluster_links_between_hosts(db_session) -> None:
|
||||
async def test_single_host_records_no_cluster_link(db_session) -> None:
|
||||
await _persist_pending_import(db_session, [_host_node()], [])
|
||||
links = (await db_session.execute(
|
||||
select(PendingDeviceLink).where(PendingDeviceLink.discovery_source == "proxmox_cluster")
|
||||
select(InventoryDeviceLink).where(InventoryDeviceLink.discovery_source == "proxmox_cluster")
|
||||
)).scalars().all()
|
||||
assert links == []
|
||||
|
||||
@@ -420,14 +435,16 @@ async def test_cluster_link_resolves_to_cluster_edge(db_session) -> None:
|
||||
# Two host nodes already on a canvas + a pending cluster link between them.
|
||||
design = Design(id=str(uuid.uuid4()), name="d")
|
||||
db_session.add(design)
|
||||
a = Node(id=str(uuid.uuid4()), type="proxmox", label="a", ieee_address="pve-node-a",
|
||||
status="online", pos_x=0, pos_y=0, design_id=design.id,
|
||||
left_handles=1, right_handles=1)
|
||||
b = Node(id=str(uuid.uuid4()), type="proxmox", label="b", ieee_address="pve-node-b",
|
||||
status="online", pos_x=0, pos_y=0, design_id=design.id,
|
||||
left_handles=1, right_handles=1)
|
||||
dev_a = InventoryDevice(id=str(uuid.uuid4()), ieee_address="pve-node-a", status="approved")
|
||||
dev_b = InventoryDevice(id=str(uuid.uuid4()), ieee_address="pve-node-b", status="approved")
|
||||
db_session.add_all([dev_a, dev_b])
|
||||
await db_session.flush()
|
||||
a = Node(id=str(uuid.uuid4()), type="proxmox", label="a", device_id=dev_a.id,
|
||||
pos_x=0, pos_y=0, design_id=design.id, left_handles=1, right_handles=1)
|
||||
b = Node(id=str(uuid.uuid4()), type="proxmox", label="b", device_id=dev_b.id,
|
||||
pos_x=0, pos_y=0, design_id=design.id, left_handles=1, right_handles=1)
|
||||
db_session.add_all([a, b])
|
||||
db_session.add(PendingDeviceLink(
|
||||
db_session.add(InventoryDeviceLink(
|
||||
id=str(uuid.uuid4()), source_ieee="pve-node-a", target_ieee="pve-node-b",
|
||||
discovery_source="proxmox_cluster",
|
||||
))
|
||||
@@ -451,15 +468,20 @@ async def test_link_survives_and_resolves_onto_second_design(db_session) -> None
|
||||
da = Design(id=str(uuid.uuid4()), name="a")
|
||||
db_ = Design(id=str(uuid.uuid4()), name="b")
|
||||
db_session.add_all([da, db_])
|
||||
# One row per device, whatever the canvas count.
|
||||
dev_x = InventoryDevice(id=str(uuid.uuid4()), ieee_address="0xAAAA", status="approved")
|
||||
dev_y = InventoryDevice(id=str(uuid.uuid4()), ieee_address="0xBBBB", status="approved")
|
||||
db_session.add_all([dev_x, dev_y])
|
||||
await db_session.flush()
|
||||
# Same two devices placed on BOTH designs (one Node per canvas).
|
||||
for d in (da, db_):
|
||||
db_session.add_all([
|
||||
Node(id=str(uuid.uuid4()), type="iot", label="x", ieee_address="0xAAAA",
|
||||
status="online", pos_x=0, pos_y=0, design_id=d.id),
|
||||
Node(id=str(uuid.uuid4()), type="iot", label="y", ieee_address="0xBBBB",
|
||||
status="online", pos_x=0, pos_y=0, design_id=d.id),
|
||||
Node(id=str(uuid.uuid4()), type="iot", label="x", device_id=dev_x.id,
|
||||
pos_x=0, pos_y=0, design_id=d.id),
|
||||
Node(id=str(uuid.uuid4()), type="iot", label="y", device_id=dev_y.id,
|
||||
pos_x=0, pos_y=0, design_id=d.id),
|
||||
])
|
||||
db_session.add(PendingDeviceLink(
|
||||
db_session.add(InventoryDeviceLink(
|
||||
id=str(uuid.uuid4()), source_ieee="0xAAAA", target_ieee="0xBBBB",
|
||||
discovery_source="zigbee",
|
||||
))
|
||||
@@ -476,7 +498,7 @@ async def test_link_survives_and_resolves_onto_second_design(db_session) -> None
|
||||
assert {e.design_id for e in edges} == {da.id, db_.id}
|
||||
assert all(e.type == "iot" for e in edges)
|
||||
# The link row is still present for any further design.
|
||||
assert (await db_session.execute(select(PendingDeviceLink))).scalars().one()
|
||||
assert (await db_session.execute(select(InventoryDeviceLink))).scalars().one()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -484,6 +506,6 @@ async def test_persist_never_deletes(db_session) -> None:
|
||||
await _persist_pending_import(db_session, [_guest_node(101, "10.0.0.5")], [])
|
||||
# A later sync that no longer includes vm101 must not remove it.
|
||||
await _persist_pending_import(db_session, [_guest_node(202, "10.0.0.6")], [])
|
||||
rows = (await db_session.execute(select(PendingDevice))).scalars().all()
|
||||
rows = (await db_session.execute(select(InventoryDevice))).scalars().all()
|
||||
ieees = {r.ieee_address for r in rows}
|
||||
assert "pve-pve1-101" in ieees and "pve-pve1-202" in ieees
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
"""The rackable exclusion list is duplicated in the frontend — keep them equal.
|
||||
|
||||
`GET /api/v1/racks/inventory` filters on `_UNRACKABLE_TYPES`, while the Device
|
||||
Inventory modal's "Rackable" filter (used as the rack picker's default) filters
|
||||
on `UNRACKABLE_TYPES` in `frontend/src/utils/rackable.ts`. If the two drift, the
|
||||
picker offers devices the rack side then refuses.
|
||||
"""
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
from app.api.routes.racks import _UNRACKABLE_TYPES
|
||||
|
||||
FRONTEND_FILE = (
|
||||
Path(__file__).resolve().parents[2] / "frontend" / "src" / "utils" / "rackable.ts"
|
||||
)
|
||||
|
||||
|
||||
def _frontend_unrackable() -> set[str]:
|
||||
src = FRONTEND_FILE.read_text()
|
||||
match = re.search(r"export const UNRACKABLE_TYPES = new Set\(\[(.*?)\]\)", src, re.S)
|
||||
assert match, (
|
||||
"Could not locate UNRACKABLE_TYPES in frontend/src/utils/rackable.ts — "
|
||||
"update this parser if the file's shape changed."
|
||||
)
|
||||
return set(re.findall(r"'([^']+)'", match.group(1)))
|
||||
|
||||
|
||||
def test_unrackable_types_in_sync_with_frontend():
|
||||
frontend = _frontend_unrackable()
|
||||
assert frontend == _UNRACKABLE_TYPES, (
|
||||
"racks.py _UNRACKABLE_TYPES is out of sync with frontend rackable.ts.\n"
|
||||
f"Missing from the backend: {sorted(frontend - _UNRACKABLE_TYPES)}\n"
|
||||
f"Missing from the frontend: {sorted(_UNRACKABLE_TYPES - frontend)}"
|
||||
)
|
||||
@@ -0,0 +1,804 @@
|
||||
import pytest
|
||||
from httpx import AsyncClient
|
||||
from sqlalchemy import text
|
||||
|
||||
from app.db.models import InventoryDevice
|
||||
|
||||
pytestmark = pytest.mark.asyncio
|
||||
|
||||
|
||||
async def _design(client: AsyncClient, headers: dict, *, name="Rack Room", design_type="rack") -> str:
|
||||
res = await client.post(
|
||||
"/api/v1/designs",
|
||||
json={"name": name, "icon": "server", "design_type": design_type},
|
||||
headers=headers,
|
||||
)
|
||||
assert res.status_code == 201, res.text
|
||||
return res.json()["id"]
|
||||
|
||||
|
||||
def _state(design_id: str, **overrides) -> dict:
|
||||
"""A minimal but complete rack payload: one rack, two devices, one patch."""
|
||||
payload = {
|
||||
"design_id": design_id,
|
||||
"racks": [
|
||||
{
|
||||
"id": "rack-1",
|
||||
"name": "Main",
|
||||
"u_height": 12,
|
||||
"width_standard": "19",
|
||||
"numbering": "bottom-up",
|
||||
"location": "garage",
|
||||
"style": {"frame": "#1c2129", "showNumbers": True},
|
||||
"pos_x": 40,
|
||||
"pos_y": 60,
|
||||
}
|
||||
],
|
||||
"devices": [
|
||||
{
|
||||
"id": "dev-sw",
|
||||
"rack_id": "rack-1",
|
||||
"label": "sw-24",
|
||||
"u_start": 10,
|
||||
"u_height": 1,
|
||||
"col_start": 0,
|
||||
"col_span": 12,
|
||||
"faceplate_id": "switch-24",
|
||||
"status": "online",
|
||||
"ports": [{"id": "p1", "label": "1", "type": "rj45", "x": 0.4, "y": 0.5}],
|
||||
},
|
||||
{
|
||||
"id": "dev-nas",
|
||||
"rack_id": "rack-1",
|
||||
"label": "nas",
|
||||
"u_start": 4,
|
||||
"u_height": 2,
|
||||
"col_start": 0,
|
||||
"col_span": 12,
|
||||
"faceplate_id": "nas-2u",
|
||||
"status": "unknown",
|
||||
"ports": [{"id": "p2", "label": "eth0", "type": "rj45", "x": 0.7, "y": 0.5}],
|
||||
},
|
||||
],
|
||||
"cables": [
|
||||
{
|
||||
"id": "cbl-1",
|
||||
"from_device_id": "dev-sw",
|
||||
"from_port_id": "p1",
|
||||
"to_device_id": "dev-nas",
|
||||
"to_port_id": "p2",
|
||||
"type": "ethernet",
|
||||
"color": "#39d353",
|
||||
}
|
||||
],
|
||||
"viewport": {"x": 10, "y": 20, "zoom": 1.5},
|
||||
}
|
||||
payload.update(overrides)
|
||||
return payload
|
||||
|
||||
|
||||
class TestDesignType:
|
||||
async def test_creates_a_rack_design(self, client: AsyncClient, headers):
|
||||
design_id = await _design(client, headers)
|
||||
res = await client.get("/api/v1/designs", headers=headers)
|
||||
design = next(d for d in res.json() if d["id"] == design_id)
|
||||
assert design["design_type"] == "rack"
|
||||
|
||||
async def test_rejects_an_unknown_design_type(self, client: AsyncClient, headers):
|
||||
res = await client.post(
|
||||
"/api/v1/designs",
|
||||
json={"name": "Nope", "design_type": "spaceship"},
|
||||
headers=headers,
|
||||
)
|
||||
assert res.status_code == 422
|
||||
|
||||
|
||||
class TestSaveAndLoad:
|
||||
async def test_round_trips_the_full_state(self, client: AsyncClient, headers):
|
||||
design_id = await _design(client, headers)
|
||||
res = await client.post("/api/v1/racks/save", json=_state(design_id), headers=headers)
|
||||
assert res.status_code == 200, res.text
|
||||
|
||||
loaded = (await client.get(f"/api/v1/racks?design_id={design_id}", headers=headers)).json()
|
||||
assert [r["name"] for r in loaded["racks"]] == ["Main"]
|
||||
assert loaded["racks"][0]["u_height"] == 12
|
||||
assert loaded["racks"][0]["style"]["showNumbers"] is True
|
||||
assert {d["id"] for d in loaded["devices"]} == {"dev-sw", "dev-nas"}
|
||||
assert loaded["devices"][0]["ports"][0]["type"] == "rj45"
|
||||
assert loaded["cables"][0]["from_port_id"] == "p1"
|
||||
assert loaded["viewport"] == {"x": 10, "y": 20, "zoom": 1.5}
|
||||
|
||||
async def test_keeps_a_mount_that_follows_its_node_check(
|
||||
self, client: AsyncClient, headers
|
||||
):
|
||||
# "Check device" is stored as `auto` on the mount: the rack has no
|
||||
# checker, it reads the linked node's live status at render time. The
|
||||
# status column is free-form, so this only guards it staying that way.
|
||||
design_id = await _design(client, headers)
|
||||
state = _state(design_id)
|
||||
state["devices"][0]["status"] = "auto"
|
||||
res = await client.post("/api/v1/racks/save", json=state, headers=headers)
|
||||
assert res.status_code == 200, res.text
|
||||
|
||||
loaded = (await client.get(f"/api/v1/racks?design_id={design_id}", headers=headers)).json()
|
||||
mount = next(d for d in loaded["devices"] if d["id"] == "dev-sw")
|
||||
assert mount["status"] == "auto"
|
||||
|
||||
async def test_prunes_what_the_client_dropped(self, client: AsyncClient, headers):
|
||||
design_id = await _design(client, headers)
|
||||
await client.post("/api/v1/racks/save", json=_state(design_id), headers=headers)
|
||||
|
||||
trimmed = _state(design_id)
|
||||
trimmed["devices"] = [d for d in trimmed["devices"] if d["id"] == "dev-sw"]
|
||||
trimmed["cables"] = []
|
||||
await client.post("/api/v1/racks/save", json=trimmed, headers=headers)
|
||||
|
||||
loaded = (await client.get(f"/api/v1/racks?design_id={design_id}", headers=headers)).json()
|
||||
assert {d["id"] for d in loaded["devices"]} == {"dev-sw"}
|
||||
assert loaded["cables"] == []
|
||||
|
||||
async def test_updates_an_existing_device_in_place(self, client: AsyncClient, headers):
|
||||
design_id = await _design(client, headers)
|
||||
await client.post("/api/v1/racks/save", json=_state(design_id), headers=headers)
|
||||
|
||||
moved = _state(design_id)
|
||||
moved["devices"][1]["u_start"] = 1
|
||||
moved["devices"][1]["label"] = "nas-renamed"
|
||||
await client.post("/api/v1/racks/save", json=moved, headers=headers)
|
||||
|
||||
loaded = (await client.get(f"/api/v1/racks?design_id={design_id}", headers=headers)).json()
|
||||
nas = next(d for d in loaded["devices"] if d["id"] == "dev-nas")
|
||||
assert (nas["u_start"], nas["label"]) == (1, "nas-renamed")
|
||||
|
||||
async def test_keeps_designs_isolated(self, client: AsyncClient, headers):
|
||||
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)
|
||||
|
||||
loaded = (await client.get(f"/api/v1/racks?design_id={second}", headers=headers)).json()
|
||||
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 == 404
|
||||
|
||||
async def test_rejects_a_device_pointing_outside_the_payload(self, client: AsyncClient, headers):
|
||||
design_id = await _design(client, headers)
|
||||
broken = _state(design_id)
|
||||
broken["devices"][0]["rack_id"] = "rack-ghost"
|
||||
res = await client.post("/api/v1/racks/save", json=broken, headers=headers)
|
||||
assert res.status_code == 400
|
||||
|
||||
async def test_rejects_a_cable_pointing_outside_the_payload(self, client: AsyncClient, headers):
|
||||
design_id = await _design(client, headers)
|
||||
broken = _state(design_id)
|
||||
broken["cables"][0]["to_device_id"] = "dev-ghost"
|
||||
res = await client.post("/api/v1/racks/save", json=broken, headers=headers)
|
||||
assert res.status_code == 400
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"patch",
|
||||
[
|
||||
{"u_height": 0},
|
||||
{"width_standard": "23"},
|
||||
{"numbering": "sideways"},
|
||||
],
|
||||
)
|
||||
async def test_rejects_invalid_rack_geometry(self, client: AsyncClient, headers, patch):
|
||||
design_id = await _design(client, headers)
|
||||
payload = _state(design_id)
|
||||
payload["racks"][0].update(patch)
|
||||
res = await client.post("/api/v1/racks/save", json=payload, headers=headers)
|
||||
assert res.status_code == 422
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"patch",
|
||||
[
|
||||
{"u_start": 0},
|
||||
{"col_start": 12},
|
||||
{"col_span": 13},
|
||||
],
|
||||
)
|
||||
async def test_rejects_invalid_device_geometry(self, client: AsyncClient, headers, patch):
|
||||
design_id = await _design(client, headers)
|
||||
payload = _state(design_id)
|
||||
payload["devices"][0].update(patch)
|
||||
res = await client.post("/api/v1/racks/save", json=payload, headers=headers)
|
||||
assert res.status_code == 422
|
||||
|
||||
async def test_rejects_a_device_taller_than_its_rack(self, client: AsyncClient, headers):
|
||||
# Each field is legal on its own; only the rack says otherwise. A mount
|
||||
# above the top rail draws outside the chassis with no way to drag it back.
|
||||
design_id = await _design(client, headers)
|
||||
payload = _state(design_id)
|
||||
payload["devices"][0]["u_start"] = 40 # rack is 12U
|
||||
res = await client.post("/api/v1/racks/save", json=payload, headers=headers)
|
||||
assert res.status_code == 422
|
||||
|
||||
async def test_rejects_a_device_whose_height_overruns_the_rack(
|
||||
self, client: AsyncClient, headers
|
||||
):
|
||||
design_id = await _design(client, headers)
|
||||
payload = _state(design_id)
|
||||
payload["devices"][0].update({"u_start": 11, "u_height": 4}) # 11..14 of 12U
|
||||
res = await client.post("/api/v1/racks/save", json=payload, headers=headers)
|
||||
assert res.status_code == 422
|
||||
|
||||
async def test_accepts_a_device_that_ends_on_the_top_rail(
|
||||
self, client: AsyncClient, headers
|
||||
):
|
||||
design_id = await _design(client, headers)
|
||||
payload = _state(design_id)
|
||||
payload["devices"][0].update({"u_start": 11, "u_height": 2}) # 11..12 of 12U
|
||||
res = await client.post("/api/v1/racks/save", json=payload, headers=headers)
|
||||
assert res.status_code == 200, res.text
|
||||
|
||||
async def test_rejects_a_span_that_overruns_the_column_grid(
|
||||
self, client: AsyncClient, headers
|
||||
):
|
||||
design_id = await _design(client, headers)
|
||||
payload = _state(design_id)
|
||||
payload["devices"][0].update({"col_start": 11, "col_span": 12})
|
||||
res = await client.post("/api/v1/racks/save", json=payload, headers=headers)
|
||||
assert res.status_code == 422
|
||||
|
||||
async def test_accepts_a_half_width_pair_sharing_one_u(
|
||||
self, client: AsyncClient, headers
|
||||
):
|
||||
design_id = await _design(client, headers)
|
||||
payload = _state(design_id)
|
||||
payload["devices"][0].update({"col_start": 0, "col_span": 6})
|
||||
payload["devices"][1].update({"col_start": 6, "col_span": 6})
|
||||
res = await client.post("/api/v1/racks/save", json=payload, headers=headers)
|
||||
assert res.status_code == 200, res.text
|
||||
|
||||
async def test_rejects_an_unknown_cable_type(self, client: AsyncClient, headers):
|
||||
design_id = await _design(client, headers)
|
||||
payload = _state(design_id)
|
||||
payload["cables"][0]["type"] = "power"
|
||||
res = await client.post("/api/v1/racks/save", json=payload, headers=headers)
|
||||
assert res.status_code == 422
|
||||
|
||||
async def test_round_trips_cable_annotations(self, client: AsyncClient, headers):
|
||||
design_id = await _design(client, headers)
|
||||
payload = _state(design_id)
|
||||
payload["cables"][0].update(
|
||||
{
|
||||
"label": "Uplink to core",
|
||||
"label_visible": True,
|
||||
"properties": [
|
||||
{"key": "Length", "value": "2 m", "icon": None, "visible": True},
|
||||
{"key": "VLAN", "value": "20", "icon": None, "visible": False},
|
||||
],
|
||||
}
|
||||
)
|
||||
assert (
|
||||
await client.post("/api/v1/racks/save", json=payload, headers=headers)
|
||||
).status_code == 200
|
||||
|
||||
cable = (
|
||||
await client.get(f"/api/v1/racks?design_id={design_id}", headers=headers)
|
||||
).json()["cables"][0]
|
||||
assert cable["label"] == "Uplink to core"
|
||||
assert cable["label_visible"] is True
|
||||
assert [p["key"] for p in cable["properties"]] == ["Length", "VLAN"]
|
||||
assert cable["properties"][1]["visible"] is False
|
||||
|
||||
async def test_defaults_cable_annotations_when_absent(
|
||||
self, client: AsyncClient, headers
|
||||
):
|
||||
# A client that predates the feature sends neither key; the response must
|
||||
# still carry usable values rather than nulls.
|
||||
design_id = await _design(client, headers)
|
||||
assert (
|
||||
await client.post("/api/v1/racks/save", json=_state(design_id), headers=headers)
|
||||
).status_code == 200
|
||||
|
||||
cable = (
|
||||
await client.get(f"/api/v1/racks?design_id={design_id}", headers=headers)
|
||||
).json()["cables"][0]
|
||||
assert cable["label_visible"] is False
|
||||
assert cable["properties"] == []
|
||||
|
||||
async def test_drops_cable_properties_with_no_key(self, client: AsyncClient, headers):
|
||||
design_id = await _design(client, headers)
|
||||
payload = _state(design_id)
|
||||
payload["cables"][0]["properties"] = [
|
||||
{"key": " ", "value": "orphan", "icon": None, "visible": True},
|
||||
{"key": "Length", "value": "2 m", "icon": None, "visible": True},
|
||||
]
|
||||
assert (
|
||||
await client.post("/api/v1/racks/save", json=payload, headers=headers)
|
||||
).status_code == 200
|
||||
|
||||
cable = (
|
||||
await client.get(f"/api/v1/racks?design_id={design_id}", headers=headers)
|
||||
).json()["cables"][0]
|
||||
assert [p["key"] for p in cable["properties"]] == ["Length"]
|
||||
|
||||
async def test_updates_cable_annotations_on_a_second_save(
|
||||
self, client: AsyncClient, headers
|
||||
):
|
||||
design_id = await _design(client, headers)
|
||||
payload = _state(design_id)
|
||||
payload["cables"][0]["properties"] = [
|
||||
{"key": "Length", "value": "2 m", "icon": None, "visible": True}
|
||||
]
|
||||
await client.post("/api/v1/racks/save", json=payload, headers=headers)
|
||||
|
||||
payload["cables"][0]["properties"] = []
|
||||
payload["cables"][0]["label_visible"] = True
|
||||
await client.post("/api/v1/racks/save", json=payload, headers=headers)
|
||||
|
||||
cable = (
|
||||
await client.get(f"/api/v1/racks?design_id={design_id}", headers=headers)
|
||||
).json()["cables"][0]
|
||||
assert cable["properties"] == []
|
||||
assert cable["label_visible"] is True
|
||||
|
||||
async def test_requires_auth(self, client: AsyncClient):
|
||||
assert (await client.get("/api/v1/racks?design_id=any")).status_code == 401
|
||||
|
||||
|
||||
class TestInventory:
|
||||
async def test_lists_rackable_devices_only(self, client: AsyncClient, headers):
|
||||
design_id = await _design(client, headers)
|
||||
await client.post(
|
||||
"/api/v1/scan/pending",
|
||||
json={"hostname": "pve-01", "suggested_type": "proxmox"},
|
||||
headers=headers,
|
||||
)
|
||||
await client.post(
|
||||
"/api/v1/scan/pending",
|
||||
json={"hostname": "phone", "suggested_type": "mobile"},
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
res = await client.get(f"/api/v1/racks/inventory?design_id={design_id}", headers=headers)
|
||||
labels = [i["label"] for i in res.json()["items"]]
|
||||
assert "pve-01" in labels
|
||||
assert "phone" not in labels
|
||||
|
||||
async def test_names_a_device_the_way_the_inventory_does(
|
||||
self, client: AsyncClient, headers, db_session
|
||||
):
|
||||
"""A scan find with no hostname is named after the app it runs, not its IP.
|
||||
|
||||
The rack picker used to show "192.168.1.63 · 192.168.1.63" where the
|
||||
Device Inventory showed "jellyfin".
|
||||
"""
|
||||
design_id = await _design(client, headers)
|
||||
db_session.add(
|
||||
InventoryDevice(
|
||||
id="pd-services",
|
||||
ip="192.168.1.63",
|
||||
services=[
|
||||
{"port": 443, "category": "web", "service_name": "https"},
|
||||
{"port": 8096, "category": "media", "service_name": "jellyfin"},
|
||||
],
|
||||
suggested_type="server",
|
||||
)
|
||||
)
|
||||
db_session.add(InventoryDevice(id="pd-bare", ip="192.168.1.64", suggested_type="server"))
|
||||
# A portless service is no fingerprint: the inventory skips it, so must
|
||||
# this — `None not in _COMMON_PORTS` is True and used to let it through.
|
||||
db_session.add(
|
||||
InventoryDevice(
|
||||
id="pd-portless",
|
||||
ip="192.168.1.65",
|
||||
services=[{"port": None, "category": "media", "service_name": "jellyfin"}],
|
||||
suggested_type="server",
|
||||
)
|
||||
)
|
||||
await db_session.commit()
|
||||
|
||||
items = (
|
||||
await client.get(f"/api/v1/racks/inventory?design_id={design_id}", headers=headers)
|
||||
).json()["items"]
|
||||
assert next(i for i in items if i["id"] == "pd-services")["label"] == "jellyfin"
|
||||
# Nothing better to say: the IP stays the label, and the UI stops doubling it.
|
||||
assert next(i for i in items if i["id"] == "pd-bare")["label"] == "192.168.1.64"
|
||||
assert next(i for i in items if i["id"] == "pd-portless")["label"] == "192.168.1.65"
|
||||
|
||||
async def test_flags_devices_already_mounted(self, client: AsyncClient, headers):
|
||||
design_id = await _design(client, headers)
|
||||
created = (
|
||||
await client.post(
|
||||
"/api/v1/scan/pending",
|
||||
json={"hostname": "sw-24", "suggested_type": "switch"},
|
||||
headers=headers,
|
||||
)
|
||||
).json()
|
||||
|
||||
payload = _state(design_id)
|
||||
payload["devices"][0]["device_id"] = created["id"]
|
||||
await client.post("/api/v1/racks/save", json=payload, headers=headers)
|
||||
|
||||
items = (
|
||||
await client.get(f"/api/v1/racks/inventory?design_id={design_id}", headers=headers)
|
||||
).json()["items"]
|
||||
assert next(i for i in items if i["id"] == created["id"])["racked"] is True
|
||||
|
||||
async def test_resolves_the_canvas_node_for_live_status(self, client: AsyncClient, headers):
|
||||
design_id = await _design(client, headers)
|
||||
node = (
|
||||
await client.post(
|
||||
"/api/v1/nodes",
|
||||
json={"type": "server", "label": "nas", "ip": "192.168.1.9", "status": "online"},
|
||||
headers=headers,
|
||||
)
|
||||
).json()
|
||||
await client.post(
|
||||
"/api/v1/scan/pending",
|
||||
json={"hostname": "nas", "ip": "192.168.1.9", "suggested_type": "nas"},
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
items = (
|
||||
await client.get(f"/api/v1/racks/inventory?design_id={design_id}", headers=headers)
|
||||
).json()["items"]
|
||||
entry = next(i for i in items if i["label"] == "nas")
|
||||
assert entry["node_id"] == node["id"]
|
||||
assert entry["node_status"] == "online"
|
||||
|
||||
async def test_reports_what_the_canvas_node_knows(
|
||||
self, client: AsyncClient, headers, db_session
|
||||
):
|
||||
"""The rack prints the logical view's facts, so the endpoint must ship them."""
|
||||
rack_design = await _design(client, headers)
|
||||
network = await _design(client, headers, name="Network", design_type="network")
|
||||
# Straight to the table: the manual-create schema carries no os/services,
|
||||
# and a scan find does. Seeded before the node so the node links to this
|
||||
# row rather than minting a second one for the same host.
|
||||
db_session.add(
|
||||
InventoryDevice(
|
||||
id="pd-nas",
|
||||
hostname="nas",
|
||||
ip="192.168.1.9",
|
||||
mac="aa:bb:cc:dd:ee:ff",
|
||||
os="TrueNAS",
|
||||
suggested_type="nas",
|
||||
services=[{"port": 445, "service_name": "smb", "category": "storage"}],
|
||||
)
|
||||
)
|
||||
await db_session.commit()
|
||||
await client.post(
|
||||
"/api/v1/nodes",
|
||||
json={
|
||||
"type": "nas",
|
||||
"label": "nas-truenas",
|
||||
"design_id": network,
|
||||
"ip": "192.168.1.9",
|
||||
"mac": "aa:bb:cc:dd:ee:ff",
|
||||
"hostname": "nas.lan",
|
||||
"os": "TrueNAS SCALE",
|
||||
"status": "online",
|
||||
"check_method": "http",
|
||||
},
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
items = (
|
||||
await client.get(f"/api/v1/racks/inventory?design_id={rack_design}", headers=headers)
|
||||
).json()["items"]
|
||||
entry = next(i for i in items if i["ip"] == "192.168.1.9")
|
||||
assert entry["mac"] == "aa:bb:cc:dd:ee:ff"
|
||||
assert entry["os"] == "TrueNAS"
|
||||
assert entry["services"] == [{"port": 445, "name": "smb"}]
|
||||
assert entry["node_label"] == "nas-truenas"
|
||||
assert entry["node_type"] == "nas"
|
||||
# The node no longer keeps its own copy: both views read the row, which
|
||||
# the node create filled in without overwriting what the scan found.
|
||||
assert entry["node_hostname"] == "nas"
|
||||
assert entry["node_os"] == "TrueNAS"
|
||||
assert entry["node_check_method"] == "http"
|
||||
assert entry["node_design_id"] == network
|
||||
assert entry["node_design_name"] == "Network"
|
||||
|
||||
async def test_stamps_last_seen_with_an_offset(self, client: AsyncClient, headers, db_session):
|
||||
"""SQLite reads `last_seen` back naive, and a naive ISO string is *local*
|
||||
time to `new Date()` — the panel printed it shifted by the viewer's offset.
|
||||
"""
|
||||
design_id = await _design(client, headers)
|
||||
node = (
|
||||
await client.post(
|
||||
"/api/v1/nodes",
|
||||
json={"type": "server", "label": "seen", "ip": "192.168.1.77"},
|
||||
headers=headers,
|
||||
)
|
||||
).json()
|
||||
await db_session.execute(
|
||||
text("UPDATE device_inventory SET last_seen = :ts WHERE id = :id"),
|
||||
{"ts": "2026-08-08 10:00:00.000000", "id": node["device_id"]},
|
||||
)
|
||||
await db_session.commit()
|
||||
|
||||
items = (
|
||||
await client.get(f"/api/v1/racks/inventory?design_id={design_id}", headers=headers)
|
||||
).json()["items"]
|
||||
entry = next(i for i in items if i["id"] == node["device_id"])
|
||||
assert entry["node_last_seen"].endswith(("Z", "+00:00"))
|
||||
|
||||
async def test_prefers_the_node_the_mount_names(self, client: AsyncClient, headers):
|
||||
"""A link the user picked in the rack beats the IEEE/IP guess.
|
||||
|
||||
The guess is what failed on gear with no MAC and no address, and it is
|
||||
wrong — not merely absent — when two hosts have swapped IPs.
|
||||
"""
|
||||
design_id = await _design(client, headers)
|
||||
picked = (
|
||||
await client.post(
|
||||
"/api/v1/nodes",
|
||||
json={"type": "pdu", "label": "pdu-main", "status": "online"},
|
||||
headers=headers,
|
||||
)
|
||||
).json()
|
||||
guessed = (
|
||||
await client.post(
|
||||
"/api/v1/nodes",
|
||||
json={"type": "server", "label": "someone-else", "ip": "192.168.1.90"},
|
||||
headers=headers,
|
||||
)
|
||||
).json()
|
||||
device = (
|
||||
await client.post(
|
||||
"/api/v1/scan/pending",
|
||||
json={"hostname": "pdu", "ip": "192.168.1.90", "suggested_type": "generic"},
|
||||
headers=headers,
|
||||
)
|
||||
).json()
|
||||
|
||||
payload = _state(design_id)
|
||||
payload["devices"][0]["device_id"] = device["id"]
|
||||
payload["devices"][0]["node_id"] = picked["id"]
|
||||
await client.post("/api/v1/racks/save", json=payload, headers=headers)
|
||||
|
||||
items = (
|
||||
await client.get(f"/api/v1/racks/inventory?design_id={design_id}", headers=headers)
|
||||
).json()["items"]
|
||||
entry = next(i for i in items if i["id"] == device["id"])
|
||||
assert entry["node_id"] == picked["id"] != guessed["id"]
|
||||
assert entry["node_label"] == "pdu-main"
|
||||
assert entry["node_status"] == "online"
|
||||
|
||||
async def test_falls_back_when_the_named_node_is_gone(self, client: AsyncClient, headers):
|
||||
"""A mount keeps its `node_id` in the payload the client last sent, so a
|
||||
node deleted meanwhile must not report a node that no longer exists.
|
||||
"""
|
||||
design_id = await _design(client, headers)
|
||||
guessed = (
|
||||
await client.post(
|
||||
"/api/v1/nodes",
|
||||
json={"type": "server", "label": "nas", "ip": "192.168.1.91"},
|
||||
headers=headers,
|
||||
)
|
||||
).json()
|
||||
device = (
|
||||
await client.post(
|
||||
"/api/v1/scan/pending",
|
||||
json={"hostname": "nas", "ip": "192.168.1.91", "suggested_type": "nas"},
|
||||
headers=headers,
|
||||
)
|
||||
).json()
|
||||
|
||||
payload = _state(design_id)
|
||||
payload["devices"][0]["device_id"] = device["id"]
|
||||
payload["devices"][0]["node_id"] = "node-that-was-deleted"
|
||||
await client.post("/api/v1/racks/save", json=payload, headers=headers)
|
||||
|
||||
items = (
|
||||
await client.get(f"/api/v1/racks/inventory?design_id={design_id}", headers=headers)
|
||||
).json()["items"]
|
||||
entry = next(i for i in items if i["id"] == device["id"])
|
||||
assert entry["node_id"] == guessed["id"]
|
||||
|
||||
async def test_leaves_the_node_fields_empty_without_a_match(
|
||||
self, client: AsyncClient, headers
|
||||
):
|
||||
design_id = await _design(client, headers)
|
||||
await client.post(
|
||||
"/api/v1/scan/pending",
|
||||
json={"hostname": "pdu-main", "suggested_type": "generic"},
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
items = (
|
||||
await client.get(f"/api/v1/racks/inventory?design_id={design_id}", headers=headers)
|
||||
).json()["items"]
|
||||
entry = next(i for i in items if i["label"] == "pdu-main")
|
||||
assert entry["node_id"] is None
|
||||
assert entry["node_label"] is None
|
||||
assert entry["node_design_name"] is None
|
||||
assert entry["services"] == []
|
||||
|
||||
async def test_reports_the_services_a_canvas_added(self, client: AsyncClient, headers, db_session):
|
||||
"""Services documented on a canvas reach the rack — they are the device's.
|
||||
|
||||
The scan found the host but no services; the user typed one on the
|
||||
logical canvas, and the rack prints it without the node being consulted.
|
||||
"""
|
||||
design_id = await _design(client, headers)
|
||||
db_session.add(
|
||||
InventoryDevice(id="pd-noservices", ip="192.168.1.63", suggested_type="server")
|
||||
)
|
||||
await db_session.commit()
|
||||
await client.post(
|
||||
"/api/v1/nodes",
|
||||
json={
|
||||
"type": "server",
|
||||
"label": "media",
|
||||
"ip": "192.168.1.63",
|
||||
"services": [{"port": 8096, "service_name": "jellyfin", "category": "media"}],
|
||||
},
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
items = (
|
||||
await client.get(f"/api/v1/racks/inventory?design_id={design_id}", headers=headers)
|
||||
).json()["items"]
|
||||
entry = next(i for i in items if i["id"] == "pd-noservices")
|
||||
assert entry["services"] == [{"port": 8096, "name": "jellyfin"}]
|
||||
|
||||
async def test_manual_entry_is_tagged_as_such(self, client: AsyncClient, headers):
|
||||
created = (
|
||||
await client.post(
|
||||
"/api/v1/scan/pending",
|
||||
json={"hostname": "patch-panel", "suggested_type": "generic"},
|
||||
headers=headers,
|
||||
)
|
||||
).json()
|
||||
assert created["discovery_source"] == "manual"
|
||||
assert created["status"] == "pending"
|
||||
|
||||
listed = (await client.get("/api/v1/scan/pending", headers=headers)).json()
|
||||
assert any(d["id"] == created["id"] for d in listed)
|
||||
|
||||
|
||||
class TestRackSourcedInventory:
|
||||
"""Gear created from a rack canvas shares the Device Inventory, but never a
|
||||
logical canvas: it documents a mount, not a host."""
|
||||
|
||||
async def _rack_device(self, client: AsyncClient, headers, hostname: str = "patch-house"):
|
||||
return (
|
||||
await client.post(
|
||||
"/api/v1/scan/pending",
|
||||
json={"hostname": hostname, "discovery_source": "rack"},
|
||||
headers=headers,
|
||||
)
|
||||
).json()
|
||||
|
||||
async def test_records_the_rack_source(self, client: AsyncClient, headers):
|
||||
created = await self._rack_device(client, headers)
|
||||
assert created["discovery_source"] == "rack"
|
||||
assert created["discovery_sources"] == ["rack"]
|
||||
|
||||
async def test_rejects_an_unknown_source(self, client: AsyncClient, headers):
|
||||
res = await client.post(
|
||||
"/api/v1/scan/pending",
|
||||
json={"hostname": "spoof", "discovery_source": "zigbee"},
|
||||
headers=headers,
|
||||
)
|
||||
assert res.status_code == 422
|
||||
|
||||
async def test_approve_refuses_rack_gear(self, client: AsyncClient, headers):
|
||||
created = await self._rack_device(client, headers)
|
||||
res = await client.post(
|
||||
f"/api/v1/scan/pending/{created['id']}/approve",
|
||||
json={"type": "generic", "label": "patch-house"},
|
||||
headers=headers,
|
||||
)
|
||||
assert res.status_code == 409
|
||||
assert "rack" in res.json()["detail"].lower()
|
||||
|
||||
async def test_bulk_approve_skips_rack_gear(self, client: AsyncClient, headers):
|
||||
rack_device = await self._rack_device(client, headers)
|
||||
scanned = (
|
||||
await client.post(
|
||||
"/api/v1/scan/pending",
|
||||
json={"hostname": "nuc", "ip": "192.168.1.77", "suggested_type": "server"},
|
||||
headers=headers,
|
||||
)
|
||||
).json()
|
||||
|
||||
res = await client.post(
|
||||
"/api/v1/scan/pending/bulk-approve",
|
||||
json={"device_ids": [rack_device["id"], scanned["id"]]},
|
||||
headers=headers,
|
||||
)
|
||||
body = res.json()
|
||||
assert body["approved"] == 1
|
||||
assert body["device_ids"] == [scanned["id"]]
|
||||
skipped = next(s for s in body["skipped_devices"] if s["device_id"] == rack_device["id"])
|
||||
assert skipped["match"] == "rack"
|
||||
|
||||
async def test_rack_gear_is_offered_to_the_rack_inventory(self, client: AsyncClient, headers):
|
||||
design_id = await _design(client, headers)
|
||||
created = await self._rack_device(client, headers, hostname="blank-panel")
|
||||
items = (
|
||||
await client.get(f"/api/v1/racks/inventory?design_id={design_id}", headers=headers)
|
||||
).json()["items"]
|
||||
assert any(i["id"] == created["id"] for i in items)
|
||||
|
||||
|
||||
class TestDesignLifecycle:
|
||||
async def test_deleting_a_design_removes_its_rack_rows(self, client: AsyncClient, headers):
|
||||
keeper = await _design(client, headers, name="Keeper", design_type="network")
|
||||
design_id = await _design(client, headers)
|
||||
await client.post("/api/v1/racks/save", json=_state(design_id), headers=headers)
|
||||
|
||||
assert (await client.delete(f"/api/v1/designs/{design_id}", headers=headers)).status_code == 204
|
||||
assert (await client.get(f"/api/v1/racks?design_id={design_id}", headers=headers)).status_code == 404
|
||||
# The other design is untouched.
|
||||
assert (await client.get(f"/api/v1/racks?design_id={keeper}", headers=headers)).status_code == 200
|
||||
|
||||
async def test_unmounting_keeps_the_inventory_entry(self, client: AsyncClient, headers):
|
||||
design_id = await _design(client, headers)
|
||||
created = (
|
||||
await client.post(
|
||||
"/api/v1/scan/pending",
|
||||
json={"hostname": "sw-24", "suggested_type": "switch"},
|
||||
headers=headers,
|
||||
)
|
||||
).json()
|
||||
|
||||
payload = _state(design_id)
|
||||
payload["devices"][0]["device_id"] = created["id"]
|
||||
await client.post("/api/v1/racks/save", json=payload, headers=headers)
|
||||
|
||||
# Unmount: the device disappears from the rack payload entirely.
|
||||
unmounted = _state(design_id)
|
||||
unmounted["devices"] = [d for d in unmounted["devices"] if d["id"] != "dev-sw"]
|
||||
unmounted["cables"] = []
|
||||
await client.post("/api/v1/racks/save", json=unmounted, headers=headers)
|
||||
|
||||
items = (
|
||||
await client.get(f"/api/v1/racks/inventory?design_id={design_id}", headers=headers)
|
||||
).json()["items"]
|
||||
entry = next(i for i in items if i["id"] == created["id"])
|
||||
assert entry["racked"] is False
|
||||
|
||||
async def test_copying_a_rack_design_duplicates_its_racks(self, client: AsyncClient, headers):
|
||||
design_id = await _design(client, headers)
|
||||
await client.post("/api/v1/racks/save", json=_state(design_id), headers=headers)
|
||||
|
||||
copy = (
|
||||
await client.post(
|
||||
f"/api/v1/designs/{design_id}/copy",
|
||||
json={"name": "Rack Room (copy)", "icon": "server"},
|
||||
headers=headers,
|
||||
)
|
||||
).json()
|
||||
assert copy["design_type"] == "rack"
|
||||
|
||||
loaded = (await client.get(f"/api/v1/racks?design_id={copy['id']}", headers=headers)).json()
|
||||
assert [r["name"] for r in loaded["racks"]] == ["Main"]
|
||||
assert len(loaded["devices"]) == 2
|
||||
assert len(loaded["cables"]) == 1
|
||||
# Fresh ids, so editing the copy cannot touch the original.
|
||||
assert loaded["racks"][0]["id"] != "rack-1"
|
||||
assert {d["id"] for d in loaded["devices"]}.isdisjoint({"dev-sw", "dev-nas"})
|
||||
# Cables still join the copied devices, not the originals.
|
||||
copied_ids = {d["id"] for d in loaded["devices"]}
|
||||
assert loaded["cables"][0]["from_device_id"] in copied_ids
|
||||
assert loaded["cables"][0]["to_device_id"] in copied_ids
|
||||
+167
-31
@@ -8,7 +8,7 @@ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_asyn
|
||||
from sqlalchemy.pool import StaticPool
|
||||
|
||||
from app.db.database import Base
|
||||
from app.db.models import Node, PendingDevice, ScanRun
|
||||
from app.db.models import InventoryDevice, Node, ScanRun
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
@@ -253,6 +253,128 @@ def test_nmap_scan_single_returns_host_unchanged_when_no_results():
|
||||
assert result["mac"] == "34:94:54:aa:bb:cc" # preserved from Phase 1
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# _nmap_scan_single — two-pass discovery/version split (issue #277)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _fake_scanner(ip, port_info, mac=None):
|
||||
"""Mock nmap.PortScanner whose results contain `ip` with tcp `port_info`."""
|
||||
host = MagicMock()
|
||||
host.all_protocols.return_value = ["tcp"]
|
||||
host.__getitem__ = MagicMock(return_value=port_info)
|
||||
host.get.return_value = {"mac": mac} if mac else {}
|
||||
nm = MagicMock()
|
||||
nm.all_hosts.return_value = [ip]
|
||||
nm.__getitem__ = MagicMock(return_value=host)
|
||||
return nm
|
||||
|
||||
|
||||
def _empty_scanner():
|
||||
nm = MagicMock()
|
||||
nm.all_hosts.return_value = []
|
||||
return nm
|
||||
|
||||
|
||||
def _failing_scanner(exc=Exception("host timeout")):
|
||||
nm = MagicMock()
|
||||
nm.scan.side_effect = exc
|
||||
return nm
|
||||
|
||||
|
||||
def test_nmap_scan_single_two_pass_merges_banners():
|
||||
"""Pass A discovers ports; Pass B enriches them with -sV banners."""
|
||||
from app.services.scanner import _nmap_scan_single
|
||||
|
||||
host = {"ip": "192.168.1.10", "hostname": None, "mac": None, "os": None, "open_ports": []}
|
||||
disc = _fake_scanner("192.168.1.10", {22: {"state": "open"}, 8006: {"state": "open"}})
|
||||
ver = _fake_scanner("192.168.1.10", {
|
||||
22: {"state": "open", "product": "OpenSSH", "version": "9.0"},
|
||||
8006: {"state": "open", "product": "", "version": ""},
|
||||
})
|
||||
|
||||
with patch("app.services.scanner.nmap.PortScanner", side_effect=[disc, ver]), \
|
||||
patch("app.services.scanner.os.geteuid", return_value=0), \
|
||||
patch("app.services.scanner._extract_os", return_value=None):
|
||||
result = _nmap_scan_single(host)
|
||||
|
||||
banners = {p["port"]: p["banner"] for p in result["open_ports"]}
|
||||
assert banners == {22: "OpenSSH 9.0", 8006: ""}
|
||||
|
||||
# Pass A: discovery only, no -sV / host-timeout. Pass B: -sV, bounded.
|
||||
disc_args = disc.scan.call_args.kwargs["arguments"]
|
||||
ver_args = ver.scan.call_args.kwargs["arguments"]
|
||||
assert "-sV" not in disc_args and "--host-timeout" not in disc_args
|
||||
assert "-sV" in ver_args and "--host-timeout 60s" in ver_args
|
||||
assert ver_args.endswith("-p 22,8006") # version pass scoped to found ports
|
||||
|
||||
|
||||
def test_nmap_scan_single_keeps_ports_when_version_pass_fails():
|
||||
"""Regression #277: a stalling version pass must not drop discovered ports."""
|
||||
from app.services.scanner import _nmap_scan_single
|
||||
|
||||
host = {"ip": "192.168.100.3", "hostname": None, "mac": None, "os": None, "open_ports": []}
|
||||
disc = _fake_scanner("192.168.100.3", {22: {"state": "open"}, 8006: {"state": "open"}})
|
||||
ver = _failing_scanner() # -sV blows past --host-timeout on the TLS port
|
||||
|
||||
with patch("app.services.scanner.nmap.PortScanner", side_effect=[disc, ver]), \
|
||||
patch("app.services.scanner.os.geteuid", return_value=0):
|
||||
result = _nmap_scan_single(host)
|
||||
|
||||
ports = {p["port"] for p in result["open_ports"]}
|
||||
assert ports == {22, 8006} # both survive despite the version failure
|
||||
assert all(p["banner"] == "" for p in result["open_ports"])
|
||||
|
||||
|
||||
def test_nmap_scan_single_keeps_ports_when_version_pass_empty():
|
||||
"""Version pass returns no results for the host — keep the discovered ports."""
|
||||
from app.services.scanner import _nmap_scan_single
|
||||
|
||||
host = {"ip": "192.168.1.11", "hostname": None, "mac": None, "os": None, "open_ports": []}
|
||||
disc = _fake_scanner("192.168.1.11", {443: {"state": "open"}})
|
||||
ver = _empty_scanner()
|
||||
|
||||
with patch("app.services.scanner.nmap.PortScanner", side_effect=[disc, ver]), \
|
||||
patch("app.services.scanner.os.geteuid", return_value=0):
|
||||
result = _nmap_scan_single(host)
|
||||
|
||||
assert [p["port"] for p in result["open_ports"]] == [443]
|
||||
assert result["open_ports"][0]["banner"] == ""
|
||||
|
||||
|
||||
def test_nmap_scan_single_no_open_ports_skips_version_pass():
|
||||
"""Host reachable but nothing open — no version pass, empty ports."""
|
||||
from app.services.scanner import _nmap_scan_single
|
||||
|
||||
host = {"ip": "192.168.1.12", "hostname": None, "mac": None, "os": None, "open_ports": []}
|
||||
disc = _fake_scanner("192.168.1.12", {80: {"state": "filtered"}})
|
||||
|
||||
# Only one PortScanner instance may be created (Pass B must be skipped);
|
||||
# a second would raise StopIteration from side_effect.
|
||||
with patch("app.services.scanner.nmap.PortScanner", side_effect=[disc]), \
|
||||
patch("app.services.scanner.os.geteuid", return_value=0):
|
||||
result = _nmap_scan_single(host)
|
||||
|
||||
assert result["open_ports"] == []
|
||||
|
||||
|
||||
def test_nmap_scan_single_non_root_uses_connect_scan():
|
||||
"""Without root, both passes use -sT (connect) instead of -sS (SYN)."""
|
||||
from app.services.scanner import _nmap_scan_single
|
||||
|
||||
host = {"ip": "192.168.1.13", "hostname": None, "mac": None, "os": None, "open_ports": []}
|
||||
disc = _fake_scanner("192.168.1.13", {80: {"state": "open"}})
|
||||
ver = _fake_scanner("192.168.1.13", {80: {"state": "open", "product": "nginx", "version": "1.24"}})
|
||||
|
||||
with patch("app.services.scanner.nmap.PortScanner", side_effect=[disc, ver]), \
|
||||
patch("app.services.scanner.os.geteuid", return_value=1000), \
|
||||
patch("app.services.scanner._extract_os", return_value=None):
|
||||
result = _nmap_scan_single(host)
|
||||
|
||||
assert disc.scan.call_args.kwargs["arguments"].startswith("-sT")
|
||||
assert ver.scan.call_args.kwargs["arguments"].startswith("-sT")
|
||||
assert result["open_ports"][0]["banner"] == "nginx 1.24"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# _nmap_scan
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -466,7 +588,7 @@ async def test_run_scan_adds_nmap_devices_as_pending(mem_db):
|
||||
await run_scan(["192.168.1.0/24"], session, run_id)
|
||||
|
||||
async with mem_db() as session:
|
||||
result = await session.execute(sa_select(PendingDevice))
|
||||
result = await session.execute(sa_select(InventoryDevice))
|
||||
devices = result.scalars().all()
|
||||
|
||||
assert any(d.ip == "192.168.1.5" for d in devices)
|
||||
@@ -474,13 +596,20 @@ async def test_run_scan_adds_nmap_devices_as_pending(mem_db):
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_run_scan_stamps_last_scan_on_matching_node_by_ip(mem_db):
|
||||
"""A scan that sees a device matching a canvas node (by IP) stamps last_scan."""
|
||||
"""A scan that sees a known device stamps last_scan on its inventory row.
|
||||
|
||||
The stamp is a fact about the device, so it lands once on the row every
|
||||
canvas draws — not once per node.
|
||||
"""
|
||||
from app.services.scanner import run_scan
|
||||
|
||||
run_id = _make_run_id()
|
||||
async with mem_db() as session:
|
||||
session.add(_make_scan_run(run_id))
|
||||
session.add(Node(id="n1", type="server", label="NAS", ip="192.168.1.5"))
|
||||
device = InventoryDevice(id="d1", ip="192.168.1.5", status="approved")
|
||||
session.add(device)
|
||||
await session.flush()
|
||||
session.add(Node(id="n1", type="server", label="NAS", device_id="d1"))
|
||||
await session.commit()
|
||||
|
||||
nmap_hosts = [{"ip": "192.168.1.5", "hostname": "nas.lan", "mac": None, "os": None, "open_ports": []}]
|
||||
@@ -492,21 +621,24 @@ async def test_run_scan_stamps_last_scan_on_matching_node_by_ip(mem_db):
|
||||
await run_scan(["192.168.1.0/24"], session, run_id)
|
||||
|
||||
async with mem_db() as session:
|
||||
node = await session.get(Node, "n1")
|
||||
device = await session.get(InventoryDevice, "d1")
|
||||
|
||||
assert node is not None
|
||||
assert node.last_scan is not None
|
||||
assert device is not None
|
||||
assert device.last_scan is not None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_run_scan_stamps_last_scan_on_matching_node_by_mac(mem_db):
|
||||
"""A node with no IP but a matching MAC still gets last_scan stamped."""
|
||||
"""A device with no IP but a matching MAC still gets last_scan stamped."""
|
||||
from app.services.scanner import run_scan
|
||||
|
||||
run_id = _make_run_id()
|
||||
async with mem_db() as session:
|
||||
session.add(_make_scan_run(run_id))
|
||||
session.add(Node(id="n2", type="iot", label="Sensor", mac="AA:BB:CC:DD:EE:FF"))
|
||||
device = InventoryDevice(id="d2", mac="aa:bb:cc:dd:ee:ff", status="approved")
|
||||
session.add(device)
|
||||
await session.flush()
|
||||
session.add(Node(id="n2", type="iot", label="Sensor", device_id="d2"))
|
||||
await session.commit()
|
||||
|
||||
nmap_hosts = [{"ip": "192.168.1.9", "hostname": None, "mac": "AA:BB:CC:DD:EE:FF", "os": None, "open_ports": []}]
|
||||
@@ -518,21 +650,24 @@ async def test_run_scan_stamps_last_scan_on_matching_node_by_mac(mem_db):
|
||||
await run_scan(["192.168.1.0/24"], session, run_id)
|
||||
|
||||
async with mem_db() as session:
|
||||
node = await session.get(Node, "n2")
|
||||
device = await session.get(InventoryDevice, "d2")
|
||||
|
||||
assert node is not None
|
||||
assert node.last_scan is not None
|
||||
assert device is not None
|
||||
assert device.last_scan is not None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_run_scan_leaves_last_scan_untouched_on_unmatched_node(mem_db):
|
||||
"""A node whose IP/MAC is not seen by the scan keeps last_scan = None."""
|
||||
"""A device whose IP/MAC the scan never saw keeps last_scan = None."""
|
||||
from app.services.scanner import run_scan
|
||||
|
||||
run_id = _make_run_id()
|
||||
async with mem_db() as session:
|
||||
session.add(_make_scan_run(run_id))
|
||||
session.add(Node(id="n3", type="server", label="Other", ip="10.0.0.99"))
|
||||
device = InventoryDevice(id="d3", ip="10.0.0.99", status="approved")
|
||||
session.add(device)
|
||||
await session.flush()
|
||||
session.add(Node(id="n3", type="server", label="Other", device_id="d3"))
|
||||
await session.commit()
|
||||
|
||||
nmap_hosts = [{"ip": "192.168.1.5", "hostname": None, "mac": None, "os": None, "open_ports": []}]
|
||||
@@ -544,15 +679,15 @@ async def test_run_scan_leaves_last_scan_untouched_on_unmatched_node(mem_db):
|
||||
await run_scan(["192.168.1.0/24"], session, run_id)
|
||||
|
||||
async with mem_db() as session:
|
||||
node = await session.get(Node, "n3")
|
||||
device = await session.get(InventoryDevice, "d3")
|
||||
|
||||
assert node is not None
|
||||
assert node.last_scan is None
|
||||
assert device is not None
|
||||
assert device.last_scan is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_run_scan_mdns_only_device_added(mem_db):
|
||||
"""Devices found only by mDNS (not nmap) should appear in pending_devices."""
|
||||
"""Devices found only by mDNS (not nmap) should appear in device_inventory."""
|
||||
from app.services.scanner import run_scan
|
||||
|
||||
run_id = _make_run_id()
|
||||
@@ -569,7 +704,7 @@ async def test_run_scan_mdns_only_device_added(mem_db):
|
||||
await run_scan(["192.168.1.0/24"], session, run_id)
|
||||
|
||||
async with mem_db() as session:
|
||||
result = await session.execute(sa_select(PendingDevice).where(PendingDevice.ip == "192.168.1.80"))
|
||||
result = await session.execute(sa_select(InventoryDevice).where(InventoryDevice.ip == "192.168.1.80"))
|
||||
device = result.scalar_one_or_none()
|
||||
|
||||
assert device is not None
|
||||
@@ -587,7 +722,7 @@ async def test_run_scan_merges_proxmox_row_by_mac(mem_db):
|
||||
async with mem_db() as session:
|
||||
session.add(_make_scan_run(run_id))
|
||||
# Previously imported from Proxmox: no IP, known NIC MAC, vm type.
|
||||
session.add(PendingDevice(
|
||||
session.add(InventoryDevice(
|
||||
id="pve-row", ieee_address="pve-pve1-101", ip=None,
|
||||
mac="bc:24:11:aa:bb:cc", suggested_type="vm", status="pending",
|
||||
discovery_source="proxmox", discovery_sources=["proxmox"],
|
||||
@@ -605,7 +740,7 @@ async def test_run_scan_merges_proxmox_row_by_mac(mem_db):
|
||||
await run_scan(["192.168.1.0/24"], session, run_id)
|
||||
|
||||
async with mem_db() as session:
|
||||
rows = (await session.execute(sa_select(PendingDevice))).scalars().all()
|
||||
rows = (await session.execute(sa_select(InventoryDevice))).scalars().all()
|
||||
|
||||
assert len(rows) == 1 # merged, not duplicated
|
||||
row = rows[0]
|
||||
@@ -634,7 +769,7 @@ async def test_run_scan_mdns_skipped_if_already_in_nmap(mem_db):
|
||||
await run_scan(["192.168.1.0/24"], session, run_id)
|
||||
|
||||
async with mem_db() as session:
|
||||
result = await session.execute(sa_select(PendingDevice).where(PendingDevice.ip == "192.168.1.10"))
|
||||
result = await session.execute(sa_select(InventoryDevice).where(InventoryDevice.ip == "192.168.1.10"))
|
||||
devices = result.scalars().all()
|
||||
|
||||
assert len(devices) == 1 # not duplicated
|
||||
@@ -649,11 +784,12 @@ async def test_run_scan_keeps_canvas_nodes(mem_db):
|
||||
run_id = _make_run_id()
|
||||
async with mem_db() as session:
|
||||
session.add(_make_scan_run(run_id))
|
||||
canvas_node = Node(
|
||||
id=str(uuid.uuid4()), label="PVE", type="proxmox",
|
||||
ip="192.168.1.100", status="online",
|
||||
)
|
||||
session.add(canvas_node)
|
||||
drawn = InventoryDevice(id="d-pve", ip="192.168.1.100", status="pending")
|
||||
session.add(drawn)
|
||||
await session.flush()
|
||||
session.add(Node(
|
||||
id=str(uuid.uuid4()), label="PVE", type="proxmox", device_id="d-pve",
|
||||
))
|
||||
await session.commit()
|
||||
|
||||
nmap_hosts = [{"ip": "192.168.1.100", "hostname": "pve.lan", "mac": None, "os": None, "open_ports": []}]
|
||||
@@ -665,7 +801,7 @@ async def test_run_scan_keeps_canvas_nodes(mem_db):
|
||||
await run_scan(["192.168.1.0/24"], session, run_id)
|
||||
|
||||
async with mem_db() as session:
|
||||
result = await session.execute(sa_select(PendingDevice).where(PendingDevice.ip == "192.168.1.100"))
|
||||
result = await session.execute(sa_select(InventoryDevice).where(InventoryDevice.ip == "192.168.1.100"))
|
||||
device = result.scalar_one_or_none()
|
||||
assert device is not None
|
||||
assert device.status == "pending"
|
||||
@@ -679,7 +815,7 @@ async def test_run_scan_skips_hidden_devices(mem_db):
|
||||
run_id = _make_run_id()
|
||||
async with mem_db() as session:
|
||||
session.add(_make_scan_run(run_id))
|
||||
hidden = PendingDevice(ip="192.168.1.55", status="hidden")
|
||||
hidden = InventoryDevice(ip="192.168.1.55", status="hidden")
|
||||
session.add(hidden)
|
||||
await session.commit()
|
||||
|
||||
@@ -693,7 +829,7 @@ async def test_run_scan_skips_hidden_devices(mem_db):
|
||||
|
||||
async with mem_db() as session:
|
||||
result = await session.execute(
|
||||
sa_select(PendingDevice).where(PendingDevice.ip == "192.168.1.55", PendingDevice.status == "pending")
|
||||
sa_select(InventoryDevice).where(InventoryDevice.ip == "192.168.1.55", InventoryDevice.status == "pending")
|
||||
)
|
||||
assert result.scalar_one_or_none() is None
|
||||
|
||||
@@ -821,7 +957,7 @@ async def test_run_scan_probe_enriches_services(mem_db):
|
||||
)
|
||||
|
||||
async with mem_db() as session:
|
||||
result = await session.execute(sa_select(PendingDevice).where(PendingDevice.ip == "192.168.1.50"))
|
||||
result = await session.execute(sa_select(InventoryDevice).where(InventoryDevice.ip == "192.168.1.50"))
|
||||
device = result.scalar_one_or_none()
|
||||
|
||||
assert device is not None
|
||||
|
||||
@@ -24,18 +24,25 @@ from app.core.scheduler import (
|
||||
stop_scheduler,
|
||||
)
|
||||
from app.db.database import Base
|
||||
from app.db.models import Node
|
||||
from app.db.models import InventoryDevice, Node
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _make_node(**kwargs) -> Node:
|
||||
def _make_device(**kwargs) -> InventoryDevice:
|
||||
"""An inventory row — what the checker iterates now that a device is checked
|
||||
once rather than once per canvas."""
|
||||
defaults = dict(id=str(uuid.uuid4()), status="approved", status_live="unknown")
|
||||
return InventoryDevice(**{**defaults, **kwargs})
|
||||
|
||||
|
||||
def _make_node(device_id: str | None = None, **kwargs) -> Node:
|
||||
defaults = dict(
|
||||
id=str(uuid.uuid4()),
|
||||
type="server",
|
||||
label="Test",
|
||||
status="unknown",
|
||||
device_id=device_id,
|
||||
pos_x=0.0,
|
||||
pos_y=0.0,
|
||||
)
|
||||
@@ -58,11 +65,10 @@ async def mem_db():
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_run_status_checks_skips_nodes_without_check_method(mem_db):
|
||||
"""Nodes with no check_method are skipped; check_node is never called."""
|
||||
async def test_run_status_checks_skips_devices_without_check_method(mem_db):
|
||||
"""Devices with no check_method are skipped; check_node is never called."""
|
||||
async with mem_db() as session:
|
||||
node = _make_node(check_method=None, ip="10.0.0.1")
|
||||
session.add(node)
|
||||
session.add(_make_device(check_method=None, ip="10.0.0.1"))
|
||||
await session.commit()
|
||||
|
||||
with patch("app.core.scheduler.AsyncSessionLocal", mem_db), \
|
||||
@@ -72,13 +78,16 @@ async def test_run_status_checks_skips_nodes_without_check_method(mem_db):
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_run_status_checks_updates_node_status(mem_db):
|
||||
"""check_node result is persisted to the DB and broadcast via WebSocket."""
|
||||
async def test_run_status_checks_updates_device_status(mem_db):
|
||||
"""check_node result lands on the device row and is broadcast to its nodes."""
|
||||
async with mem_db() as session:
|
||||
node = _make_node(check_method="ping", ip="10.0.0.1")
|
||||
device = _make_device(check_method="ping", ip="10.0.0.1")
|
||||
session.add(device)
|
||||
await session.flush()
|
||||
node = _make_node(device_id=device.id)
|
||||
session.add(node)
|
||||
await session.commit()
|
||||
node_id = node.id
|
||||
device_id, node_id = device.id, node.id
|
||||
|
||||
check_result = {"status": "online", "response_time_ms": 5}
|
||||
|
||||
@@ -87,28 +96,74 @@ async def test_run_status_checks_updates_node_status(mem_db):
|
||||
patch("app.api.routes.status.broadcast_status", new_callable=AsyncMock) as mock_broadcast:
|
||||
await _run_status_checks()
|
||||
|
||||
# Verify DB updated
|
||||
# Verify the row updated — `status_live` is reachability, `status` is the
|
||||
# pending/approved/hidden lifecycle and must not be touched.
|
||||
async with mem_db() as session:
|
||||
updated = await session.get(Node, node_id)
|
||||
updated = await session.get(InventoryDevice, device_id)
|
||||
assert updated is not None
|
||||
assert updated.status == "online"
|
||||
assert updated.status_live == "online"
|
||||
assert updated.status == "approved"
|
||||
assert updated.response_time_ms == 5
|
||||
|
||||
# Verify WebSocket broadcast
|
||||
# Verify WebSocket broadcast, addressed by device and carrying its nodes
|
||||
mock_broadcast.assert_awaited_once()
|
||||
_, kwargs = mock_broadcast.call_args
|
||||
assert kwargs["node_id"] == node_id
|
||||
assert kwargs["device_id"] == device_id
|
||||
assert kwargs["node_ids"] == [node_id]
|
||||
assert kwargs["status"] == "online"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_run_status_checks_covers_a_device_no_canvas_draws(mem_db):
|
||||
"""Deliberate: the inventory row, not a node, is what gets monitored.
|
||||
|
||||
A rack mount or an inventory-only entry reports live status without being
|
||||
drawn on any canvas, and deleting a node does not silently stop monitoring
|
||||
the host. `hide` (or clearing the check method) is what ends the checks.
|
||||
"""
|
||||
async with mem_db() as session:
|
||||
device = _make_device(check_method="ping", ip="10.0.0.1")
|
||||
session.add(device)
|
||||
await session.commit()
|
||||
device_id = device.id
|
||||
|
||||
with patch("app.core.scheduler.AsyncSessionLocal", mem_db), \
|
||||
patch("app.core.scheduler.check_node", new_callable=AsyncMock,
|
||||
return_value={"status": "online", "response_time_ms": 5}), \
|
||||
patch("app.api.routes.status.broadcast_status", new_callable=AsyncMock) as mock_broadcast:
|
||||
await _run_status_checks()
|
||||
|
||||
async with mem_db() as session:
|
||||
updated = await session.get(InventoryDevice, device_id)
|
||||
assert updated is not None
|
||||
assert updated.status_live == "online"
|
||||
|
||||
_, kwargs = mock_broadcast.call_args
|
||||
assert kwargs["device_id"] == device_id
|
||||
assert kwargs["node_ids"] == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_run_status_checks_skips_a_hidden_device(mem_db):
|
||||
"""Hiding a device is how a user stops the checks, node or no node."""
|
||||
async with mem_db() as session:
|
||||
session.add(_make_device(check_method="ping", ip="10.0.0.1", status="hidden"))
|
||||
await session.commit()
|
||||
|
||||
with patch("app.core.scheduler.AsyncSessionLocal", mem_db), \
|
||||
patch("app.core.scheduler.check_node", new_callable=AsyncMock) as mock_check:
|
||||
await _run_status_checks()
|
||||
mock_check.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_run_status_checks_sets_last_seen_only_when_online(mem_db):
|
||||
"""last_seen is updated only when status is 'online'."""
|
||||
async with mem_db() as session:
|
||||
node = _make_node(check_method="ping", ip="10.0.0.1", last_seen=None)
|
||||
session.add(node)
|
||||
device = _make_device(check_method="ping", ip="10.0.0.1", last_seen=None)
|
||||
session.add(device)
|
||||
await session.commit()
|
||||
node_id = node.id
|
||||
device_id = device.id
|
||||
|
||||
check_result = {"status": "offline", "response_time_ms": None}
|
||||
|
||||
@@ -118,18 +173,19 @@ async def test_run_status_checks_sets_last_seen_only_when_online(mem_db):
|
||||
await _run_status_checks()
|
||||
|
||||
async with mem_db() as session:
|
||||
updated = await session.get(Node, node_id)
|
||||
updated = await session.get(InventoryDevice, device_id)
|
||||
assert updated is not None
|
||||
assert updated.last_seen is None # not set for offline
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_run_status_checks_handles_check_error_gracefully(mem_db):
|
||||
"""An exception from check_node is logged and does not abort other nodes."""
|
||||
"""An exception from check_node is logged and does not abort other devices."""
|
||||
async with mem_db() as session:
|
||||
n1 = _make_node(check_method="ping", ip="10.0.0.1")
|
||||
n2 = _make_node(check_method="ping", ip="10.0.0.2")
|
||||
session.add_all([n1, n2])
|
||||
session.add_all([
|
||||
_make_device(check_method="ping", ip="10.0.0.1"),
|
||||
_make_device(check_method="ping", ip="10.0.0.2"),
|
||||
])
|
||||
await session.commit()
|
||||
|
||||
call_count = 0
|
||||
@@ -191,7 +247,7 @@ def test_start_and_stop_scheduler():
|
||||
@pytest.mark.asyncio
|
||||
async def test_run_service_checks_disabled_does_nothing(mem_db):
|
||||
async with mem_db() as session:
|
||||
session.add(_make_node(services=[{"port": 80, "protocol": "tcp", "service_name": "http"}]))
|
||||
session.add(_make_device(services=[{"port": 80, "protocol": "tcp", "service_name": "http"}]))
|
||||
await session.commit()
|
||||
|
||||
with patch("app.core.scheduler.settings") as mock_settings, \
|
||||
@@ -203,15 +259,18 @@ async def test_run_service_checks_disabled_does_nothing(mem_db):
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_run_service_checks_broadcasts_per_node(mem_db):
|
||||
async def test_run_service_checks_broadcasts_per_device(mem_db):
|
||||
async with mem_db() as session:
|
||||
node = _make_node(
|
||||
device = _make_device(
|
||||
ip="10.0.0.5",
|
||||
services=[{"port": 80, "protocol": "tcp", "service_name": "http"}],
|
||||
)
|
||||
session.add(device)
|
||||
await session.flush()
|
||||
node = _make_node(device_id=device.id)
|
||||
session.add(node)
|
||||
await session.commit()
|
||||
node_id = node.id
|
||||
device_id, node_id = device.id, node.id
|
||||
|
||||
statuses = [{"port": 80, "protocol": "tcp", "status": "offline"}]
|
||||
|
||||
@@ -224,14 +283,15 @@ async def test_run_service_checks_broadcasts_per_node(mem_db):
|
||||
|
||||
mock_bcast.assert_awaited_once()
|
||||
_, kwargs = mock_bcast.call_args
|
||||
assert kwargs["node_id"] == node_id
|
||||
assert kwargs["device_id"] == device_id
|
||||
assert kwargs["node_ids"] == [node_id]
|
||||
assert kwargs["services"] == statuses
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_run_service_checks_skips_nodes_without_services(mem_db):
|
||||
async def test_run_service_checks_skips_devices_without_services(mem_db):
|
||||
async with mem_db() as session:
|
||||
session.add(_make_node(ip="10.0.0.6", services=[]))
|
||||
session.add(_make_device(ip="10.0.0.6", services=[]))
|
||||
await session.commit()
|
||||
|
||||
with patch("app.core.scheduler.settings") as mock_settings, \
|
||||
|
||||
@@ -37,6 +37,33 @@ async def test_update_settings_saves_interval(client: AsyncClient, headers):
|
||||
assert res.json()["interval_seconds"] == 120
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_update_settings_reschedules_status_checks(client: AsyncClient, headers):
|
||||
"""The new interval must reach the running scheduler, not just the config
|
||||
file: otherwise the UI and scan_config.json show the new value while the
|
||||
job keeps firing at the old one until the backend restarts."""
|
||||
with patch("app.api.routes.settings.settings") as mock_settings, \
|
||||
patch("app.api.routes.settings.reschedule_status_checks") as mock_reschedule:
|
||||
mock_settings.save_overrides = lambda: None
|
||||
res = await client.post(
|
||||
"/api/v1/settings",
|
||||
json={"interval_seconds": 120},
|
||||
headers=headers,
|
||||
)
|
||||
assert res.status_code == 200
|
||||
mock_reschedule.assert_called_once_with(120)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_update_settings_rejects_too_short_status_interval(client: AsyncClient, headers):
|
||||
res = await client.post(
|
||||
"/api/v1/settings",
|
||||
json={"interval_seconds": 5},
|
||||
headers=headers,
|
||||
)
|
||||
assert res.status_code == 422
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_update_settings_requires_auth(client: AsyncClient):
|
||||
res = await client.post("/api/v1/settings", json={"interval_seconds": 30})
|
||||
@@ -167,3 +194,64 @@ def test_save_overrides_omits_mesh_credentials(tmp_path):
|
||||
assert written["zigbee_sync_enabled"] is True
|
||||
assert written["zigbee_sync_interval"] == 900
|
||||
assert written["zwave_sync_interval"] == 1200
|
||||
|
||||
|
||||
def _valid_oidc_settings(**overrides):
|
||||
values = {
|
||||
"secret_key": "test-secret-key-that-is-at-least-32-bytes",
|
||||
"auth_mode": "oidc",
|
||||
"oidc_discovery_url": "https://idp.example/application/o/homelable/.well-known/openid-configuration",
|
||||
"oidc_client_id": "homelable",
|
||||
"oidc_client_secret": "client-secret",
|
||||
"oidc_redirect_uri": "https://homelable.example/api/v1/auth/oidc/callback",
|
||||
"cors_origins": ["https://homelable.example"],
|
||||
}
|
||||
values.update(overrides)
|
||||
return Settings(_env_file=None, **values)
|
||||
|
||||
|
||||
def test_oidc_mode_requires_complete_client_configuration():
|
||||
with pytest.raises(ValueError, match="OIDC_DISCOVERY_URL.*OIDC_CLIENT_ID.*OIDC_CLIENT_SECRET.*OIDC_REDIRECT_URI"):
|
||||
Settings(secret_key="test-secret", auth_mode="oidc", _env_file=None)
|
||||
|
||||
|
||||
def test_oidc_mode_requires_openid_scope():
|
||||
with pytest.raises(ValueError, match="OIDC_SCOPES must contain 'openid'"):
|
||||
_valid_oidc_settings(oidc_scopes="profile email")
|
||||
|
||||
|
||||
def test_oidc_mode_requires_strong_session_secret():
|
||||
with pytest.raises(ValueError, match="SECRET_KEY must be at least 32 bytes"):
|
||||
_valid_oidc_settings(secret_key="too-short")
|
||||
|
||||
|
||||
def test_oidc_secure_cookie_requires_https_callback():
|
||||
with pytest.raises(ValueError, match="must use HTTPS"):
|
||||
_valid_oidc_settings(oidc_redirect_uri="http://localhost/api/v1/auth/oidc/callback")
|
||||
|
||||
|
||||
def test_oidc_secure_cookie_requires_https_discovery():
|
||||
with pytest.raises(ValueError, match="OIDC_DISCOVERY_URL must use HTTPS"):
|
||||
_valid_oidc_settings(
|
||||
oidc_discovery_url="http://idp.local/application/o/homelable/.well-known/openid-configuration"
|
||||
)
|
||||
|
||||
|
||||
def test_oidc_insecure_dev_mode_allows_http_urls():
|
||||
configured = _valid_oidc_settings(
|
||||
oidc_cookie_secure=False,
|
||||
oidc_discovery_url="http://idp.local/.well-known/openid-configuration",
|
||||
oidc_redirect_uri="http://localhost/api/v1/auth/oidc/callback",
|
||||
)
|
||||
assert configured.oidc_cookie_secure is False
|
||||
|
||||
|
||||
def test_oidc_mode_rejects_wildcard_cors():
|
||||
with pytest.raises(ValueError, match="CORS_ORIGINS cannot contain"):
|
||||
_valid_oidc_settings(cors_origins=["*"])
|
||||
|
||||
|
||||
def test_valid_oidc_configuration_is_accepted():
|
||||
configured = _valid_oidc_settings()
|
||||
assert configured.auth_mode == "oidc"
|
||||
assert configured.oidc_cookie_secure is True
|
||||
|
||||
@@ -7,7 +7,7 @@ from app.services.fingerprint import _load, match_service
|
||||
|
||||
_NODE_TYPES = {
|
||||
"isp", "router", "switch", "server", "proxmox", "vm", "lxc",
|
||||
"nas", "iot", "ap", "camera", "generic",
|
||||
"nas", "kvm", "iot", "ap", "camera", "generic",
|
||||
}
|
||||
|
||||
|
||||
@@ -43,6 +43,13 @@ def test_popular_apps_have_port_agnostic_signatures(signatures):
|
||||
assert expected in names, f"missing port-agnostic signature for {expected}"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("title", ["PiKVM", "TinyPilot", "JetKVM", "NanoKVM"])
|
||||
def test_ip_kvm_titles_suggest_kvm_node_type(title):
|
||||
sig = match_service(80, "tcp", banner=None, http_signals={"title": title, "headers": {}})
|
||||
assert sig is not None
|
||||
assert sig["suggested_node_type"] == "kvm"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("title", "expected"), [
|
||||
("Jellyfin", "Jellyfin"),
|
||||
("Home Assistant", "Home Assistant"),
|
||||
|
||||
+18
-10
@@ -9,7 +9,7 @@ from httpx import AsyncClient
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.config import settings
|
||||
from app.db.models import Node, PendingDevice, ScanRun
|
||||
from app.db.models import InventoryDevice, Node, ScanRun
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
@@ -68,16 +68,24 @@ async def test_summary_aggregates_counts(
|
||||
) -> None:
|
||||
settings.homepage_api_key = "topsecret"
|
||||
finished = datetime(2026, 5, 14, 10, 0, tzinfo=timezone.utc)
|
||||
# Reachability and the ieee live on the inventory row each node draws.
|
||||
drawn = [
|
||||
("A", "server", "online", None),
|
||||
("B", "server", "online", None),
|
||||
("C", "server", "offline", None),
|
||||
("D", "server", "unknown", None),
|
||||
("Z1", "iot", "online", "0x1"),
|
||||
("Z2", "iot", "online", "0x2"),
|
||||
]
|
||||
for label, node_type, status_live, ieee in drawn:
|
||||
device = InventoryDevice(status="approved", status_live=status_live, ieee_address=ieee)
|
||||
db_session.add(device)
|
||||
await db_session.flush()
|
||||
db_session.add(Node(type=node_type, label=label, device_id=device.id))
|
||||
db_session.add_all([
|
||||
Node(type="server", label="A", status="online"),
|
||||
Node(type="server", label="B", status="online"),
|
||||
Node(type="server", label="C", status="offline"),
|
||||
Node(type="server", label="D", status="unknown"),
|
||||
Node(type="iot", label="Z1", status="online", ieee_address="0x1"),
|
||||
Node(type="iot", label="Z2", status="online", ieee_address="0x2"),
|
||||
PendingDevice(ip="10.0.0.1", status="pending"),
|
||||
PendingDevice(ip="10.0.0.2", status="pending"),
|
||||
PendingDevice(ip="10.0.0.3", status="hidden"), # excluded
|
||||
InventoryDevice(ip="10.0.0.1", status="pending"),
|
||||
InventoryDevice(ip="10.0.0.2", status="pending"),
|
||||
InventoryDevice(ip="10.0.0.3", status="hidden"), # excluded
|
||||
ScanRun(status="success", finished_at=finished),
|
||||
ScanRun(status="success",
|
||||
finished_at=datetime(2026, 5, 13, 10, 0, tzinfo=timezone.utc)),
|
||||
|
||||
@@ -74,7 +74,8 @@ async def test_broadcast_status_sends_to_connected_clients():
|
||||
_connections.append(fake)
|
||||
try:
|
||||
await broadcast_status(
|
||||
node_id="node-1",
|
||||
device_id="dev-1",
|
||||
node_ids=["node-1", "node-2"],
|
||||
status="online",
|
||||
checked_at="2024-01-01T00:00:00",
|
||||
response_time_ms=42,
|
||||
@@ -85,7 +86,9 @@ async def test_broadcast_status_sends_to_connected_clients():
|
||||
assert len(received) == 1
|
||||
msg = json.loads(received[0])
|
||||
assert msg["type"] == "status"
|
||||
assert msg["node_id"] == "node-1"
|
||||
# One check, addressed by device, lighting up every canvas drawing it.
|
||||
assert msg["device_id"] == "dev-1"
|
||||
assert msg["node_ids"] == ["node-1", "node-2"]
|
||||
assert msg["status"] == "online"
|
||||
assert msg["response_time_ms"] == 42
|
||||
|
||||
@@ -102,7 +105,7 @@ async def test_broadcast_status_no_response_time():
|
||||
fake = FakeWS()
|
||||
_connections.append(fake)
|
||||
try:
|
||||
await broadcast_status(node_id="n", status="offline", checked_at="t")
|
||||
await broadcast_status(device_id="d", node_ids=["n"], status="offline", checked_at="t")
|
||||
finally:
|
||||
_connections.remove(fake)
|
||||
|
||||
@@ -122,7 +125,7 @@ async def test_broadcast_status_removes_dead_connection():
|
||||
_connections.append(dead)
|
||||
initial_len = len(_connections)
|
||||
|
||||
await broadcast_status(node_id="n", status="online", checked_at="t")
|
||||
await broadcast_status(device_id="d", node_ids=["n"], status="online", checked_at="t")
|
||||
|
||||
assert dead not in _connections
|
||||
assert len(_connections) == initial_len - 1
|
||||
@@ -159,7 +162,7 @@ async def test_broadcast_scan_update():
|
||||
async def test_broadcast_no_connections():
|
||||
"""broadcast_* with no connections must not raise."""
|
||||
assert len(_connections) == 0
|
||||
await broadcast_status(node_id="n", status="online", checked_at="t")
|
||||
await broadcast_status(device_id="d", node_ids=["n"], status="online", checked_at="t")
|
||||
await broadcast_scan_update(run_id="r", devices_found=0)
|
||||
|
||||
|
||||
@@ -179,7 +182,8 @@ async def test_broadcast_service_status_payload():
|
||||
_connections.append(fake)
|
||||
try:
|
||||
await broadcast_service_status(
|
||||
node_id="node-7",
|
||||
device_id="dev-7",
|
||||
node_ids=["node-7"],
|
||||
services=[{"port": 80, "protocol": "tcp", "status": "offline"}],
|
||||
checked_at="2024-01-01T00:00:00",
|
||||
)
|
||||
@@ -188,7 +192,8 @@ async def test_broadcast_service_status_payload():
|
||||
|
||||
msg = json.loads(received[0])
|
||||
assert msg["type"] == "service_status"
|
||||
assert msg["node_id"] == "node-7"
|
||||
assert msg["device_id"] == "dev-7"
|
||||
assert msg["node_ids"] == ["node-7"]
|
||||
assert msg["services"] == [{"port": 80, "protocol": "tcp", "status": "offline"}]
|
||||
|
||||
|
||||
@@ -217,7 +222,7 @@ async def test_broadcast_dead_connection_dropped_once_safely():
|
||||
|
||||
dead = DeadWS()
|
||||
_connections.append(dead)
|
||||
await broadcast_status(node_id="n", status="online", checked_at="t")
|
||||
await broadcast_status(device_id="d", node_ids=["n"], status="online", checked_at="t")
|
||||
# A second broadcast must not raise even though dead is already gone.
|
||||
await broadcast_status(node_id="n", status="online", checked_at="t")
|
||||
await broadcast_status(device_id="d", node_ids=["n"], status="online", checked_at="t")
|
||||
assert dead not in _connections
|
||||
|
||||
@@ -467,11 +467,86 @@ async def test_check_services_returns_status_per_service():
|
||||
with patch("app.services.status_checker._http_get", new_callable=AsyncMock, return_value=True):
|
||||
results = await check_services("10.0.0.1", services)
|
||||
assert results == [
|
||||
{"port": 80, "protocol": "tcp", "status": "online"},
|
||||
{"port": 5432, "protocol": "tcp", "status": "unknown"},
|
||||
{"port": 80, "protocol": "tcp", "host": None, "status": "online"},
|
||||
{"port": 5432, "protocol": "tcp", "host": None, "status": "unknown"},
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_check_services_echoes_the_host_override():
|
||||
services = [{"port": 443, "protocol": "tcp", "service_name": "blog", "host": "blog.example.com"}]
|
||||
with patch("app.services.status_checker._http_get", new_callable=AsyncMock, return_value=True):
|
||||
results = await check_services("10.0.0.1", services)
|
||||
assert results == [
|
||||
{"port": 443, "protocol": "tcp", "host": "blog.example.com", "status": "online"},
|
||||
]
|
||||
|
||||
|
||||
# --- Per-service host override ---
|
||||
|
||||
|
||||
async def _captured_url(svc, host):
|
||||
captured = {}
|
||||
|
||||
async def fake_http_get(url, verify=False):
|
||||
captured["url"] = url
|
||||
return True
|
||||
|
||||
with patch("app.services.status_checker._http_get", side_effect=fake_http_get):
|
||||
await check_service(svc, host)
|
||||
return captured.get("url")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_check_service_uses_the_host_override():
|
||||
svc = {"port": 8080, "protocol": "tcp", "service_name": "blog", "host": "blog.example.com"}
|
||||
assert await _captured_url(svc, "10.0.0.1") == "http://blog.example.com:8080"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_check_service_falls_back_to_the_node_host_when_override_is_blank():
|
||||
svc = {"port": 8080, "protocol": "tcp", "service_name": "blog", "host": " "}
|
||||
assert await _captured_url(svc, "10.0.0.1") == "http://10.0.0.1:8080"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_check_service_honours_a_scheme_in_the_override():
|
||||
svc = {"protocol": "tcp", "service_name": "blog", "host": "https://blog.example.com"}
|
||||
assert await _captured_url(svc, "10.0.0.1") == "https://blog.example.com"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_check_service_takes_the_port_from_the_override():
|
||||
svc = {"protocol": "tcp", "service_name": "blog", "host": "blog.example.com:8443"}
|
||||
assert await _captured_url(svc, "10.0.0.1") == "https://blog.example.com:8443"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_check_service_lets_the_service_port_beat_the_override_port():
|
||||
svc = {"port": 3000, "protocol": "tcp", "service_name": "blog", "host": "blog.example.com:8443"}
|
||||
assert await _captured_url(svc, "10.0.0.1") == "http://blog.example.com:3000"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_check_service_uses_the_first_host_of_a_comma_list_override():
|
||||
svc = {"port": 8080, "protocol": "tcp", "service_name": "blog", "host": "blog.example.com, alt.example.com"}
|
||||
assert await _captured_url(svc, "10.0.0.1") == "http://blog.example.com:8080"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_check_service_brackets_an_ipv6_override():
|
||||
svc = {"port": 80, "protocol": "tcp", "service_name": "http", "host": "[2001:db8::1]:8080"}
|
||||
assert await _captured_url(svc, "10.0.0.1") == "http://[2001:db8::1]:80"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_check_service_skips_a_non_http_port_behind_an_override():
|
||||
svc = {"port": 5432, "protocol": "tcp", "service_name": "postgres", "host": "db.example.com"}
|
||||
with patch("app.services.status_checker._http_get", new_callable=AsyncMock) as mock_get:
|
||||
assert await check_service(svc, "10.0.0.1") == "unknown"
|
||||
mock_get.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_check_services_empty_list():
|
||||
assert await check_services("10.0.0.1", []) == []
|
||||
|
||||
@@ -338,7 +338,7 @@ async def test_persist_pending_import_coordinator_goes_to_pending(
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.api.routes.zigbee import _persist_pending_import
|
||||
from app.db.models import Node, PendingDevice
|
||||
from app.db.models import InventoryDevice, Node
|
||||
|
||||
result = await _persist_pending_import(db_session, _PENDING_NODES, _PENDING_EDGES)
|
||||
assert result.device_count == 3
|
||||
@@ -354,7 +354,7 @@ async def test_persist_pending_import_coordinator_goes_to_pending(
|
||||
# Coordinator sits in the pending inventory.
|
||||
coord = (
|
||||
await db_session.execute(
|
||||
select(PendingDevice).where(PendingDevice.ieee_address == "0xCOORD")
|
||||
select(InventoryDevice).where(InventoryDevice.ieee_address == "0xCOORD")
|
||||
)
|
||||
).scalar_one()
|
||||
assert coord.status == "pending"
|
||||
@@ -385,14 +385,14 @@ async def test_persist_pending_import_replaces_links(db_session) -> None:
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.api.routes.zigbee import _persist_pending_import
|
||||
from app.db.models import PendingDeviceLink
|
||||
from app.db.models import InventoryDeviceLink
|
||||
|
||||
await _persist_pending_import(db_session, _PENDING_NODES, _PENDING_EDGES)
|
||||
|
||||
new_edges = [{"source": "0xCOORD", "target": "0xR1"}]
|
||||
await _persist_pending_import(db_session, _PENDING_NODES[:2], new_edges)
|
||||
|
||||
rows = (await db_session.execute(select(PendingDeviceLink))).scalars().all()
|
||||
rows = (await db_session.execute(select(InventoryDeviceLink))).scalars().all()
|
||||
assert len(rows) == 1
|
||||
assert (rows[0].source_ieee, rows[0].target_ieee) == ("0xCOORD", "0xR1")
|
||||
|
||||
@@ -403,7 +403,7 @@ async def test_persist_pending_import_sets_coordinator_pending_fields(db_session
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.api.routes.zigbee import _persist_pending_import
|
||||
from app.db.models import PendingDevice
|
||||
from app.db.models import InventoryDevice
|
||||
|
||||
nodes_with_meta = [dict(n) for n in _PENDING_NODES]
|
||||
nodes_with_meta[0]["vendor"] = "TI"
|
||||
@@ -413,7 +413,7 @@ async def test_persist_pending_import_sets_coordinator_pending_fields(db_session
|
||||
|
||||
coord = (
|
||||
await db_session.execute(
|
||||
select(PendingDevice).where(PendingDevice.ieee_address == "0xCOORD")
|
||||
select(InventoryDevice).where(InventoryDevice.ieee_address == "0xCOORD")
|
||||
)
|
||||
).scalar_one()
|
||||
assert coord.vendor == "TI"
|
||||
@@ -432,19 +432,22 @@ async def test_persist_pending_import_backfills_inventory_for_approved_node(
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.api.routes.zigbee import _persist_pending_import
|
||||
from app.db.models import Node, PendingDevice
|
||||
from app.db.models import InventoryDevice, Node
|
||||
|
||||
# Simulate: router was approved earlier → exists as a canvas Node, but with
|
||||
# no matching pending_devices row (e.g. a legacy auto-placed device).
|
||||
approved = Node(
|
||||
label="router_1",
|
||||
type="zigbee_router",
|
||||
status="online",
|
||||
check_method="none",
|
||||
# no matching device_inventory row (e.g. a legacy auto-placed device).
|
||||
device = InventoryDevice(
|
||||
ieee_address="0xR1",
|
||||
services=[],
|
||||
friendly_name="router_1",
|
||||
suggested_type="zigbee_router",
|
||||
status="approved",
|
||||
status_live="online",
|
||||
check_method="none",
|
||||
properties=[],
|
||||
)
|
||||
db_session.add(device)
|
||||
await db_session.flush()
|
||||
approved = Node(label="router_1", type="zigbee_router", device_id=device.id)
|
||||
db_session.add(approved)
|
||||
await db_session.commit()
|
||||
|
||||
@@ -455,7 +458,7 @@ async def test_persist_pending_import_backfills_inventory_for_approved_node(
|
||||
# An inventory row is backfilled as "approved" (it is on a canvas).
|
||||
inv = (
|
||||
await db_session.execute(
|
||||
select(PendingDevice).where(PendingDevice.ieee_address == "0xR1")
|
||||
select(InventoryDevice).where(InventoryDevice.ieee_address == "0xR1")
|
||||
)
|
||||
).scalar_one()
|
||||
assert inv.status == "approved"
|
||||
@@ -464,7 +467,9 @@ async def test_persist_pending_import_backfills_inventory_for_approved_node(
|
||||
|
||||
# Node properties got refreshed.
|
||||
refreshed = (
|
||||
await db_session.execute(select(Node).where(Node.ieee_address == "0xR1"))
|
||||
await db_session.execute(
|
||||
select(InventoryDevice).where(InventoryDevice.ieee_address == "0xR1")
|
||||
)
|
||||
).scalar_one()
|
||||
keys = {p["key"]: p["value"] for p in refreshed.properties}
|
||||
assert keys == {"IEEE": "0xR1", "Vendor": "TI", "Model": "CC2530", "LQI": "250"}
|
||||
@@ -481,23 +486,24 @@ async def test_persist_pending_import_preserves_hidden_inventory_for_approved_no
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.api.routes.zigbee import _persist_pending_import
|
||||
from app.db.models import Node, PendingDevice
|
||||
from app.db.models import InventoryDevice, Node
|
||||
|
||||
db_session.add(Node(
|
||||
label="router_1", type="zigbee_router", status="online",
|
||||
check_method="none", ieee_address="0xR1", services=[], properties=[],
|
||||
))
|
||||
db_session.add(PendingDevice(
|
||||
# One row, hidden by the user, and a canvas still draws it.
|
||||
drawn = InventoryDevice(
|
||||
ieee_address="0xR1", friendly_name="router_1", suggested_type="zigbee_router",
|
||||
device_subtype="Router", status="hidden", discovery_source="zigbee",
|
||||
))
|
||||
device_subtype="Router", status="hidden", status_live="online",
|
||||
check_method="none", discovery_source="zigbee",
|
||||
)
|
||||
db_session.add(drawn)
|
||||
await db_session.flush()
|
||||
db_session.add(Node(label="router_1", type="zigbee_router", device_id=drawn.id))
|
||||
await db_session.commit()
|
||||
|
||||
await _persist_pending_import(db_session, _PENDING_NODES, _PENDING_EDGES)
|
||||
|
||||
inv = (
|
||||
await db_session.execute(
|
||||
select(PendingDevice).where(PendingDevice.ieee_address == "0xR1")
|
||||
select(InventoryDevice).where(InventoryDevice.ieee_address == "0xR1")
|
||||
)
|
||||
).scalar_one()
|
||||
assert inv.status == "hidden" # stays hidden
|
||||
@@ -509,7 +515,7 @@ async def test_persist_pending_import_revives_orphaned_approved_device(
|
||||
) -> None:
|
||||
"""Regression for #167: approve → delete node → re-import must re-list device.
|
||||
|
||||
When a device was approved (PendingDevice.status="approved") and its canvas
|
||||
When a device was approved (InventoryDevice.status="approved") and its canvas
|
||||
Node was later deleted, the orphaned "approved" row must be reset to
|
||||
"pending" on re-import so it shows up in the Pending list again — instead of
|
||||
being silently swallowed (re-import reports "found" but Pending stays empty).
|
||||
@@ -517,11 +523,11 @@ async def test_persist_pending_import_revives_orphaned_approved_device(
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.api.routes.zigbee import _persist_pending_import
|
||||
from app.db.models import PendingDevice
|
||||
from app.db.models import InventoryDevice
|
||||
|
||||
# Simulate prior approve: a PendingDevice marked approved, but NO matching
|
||||
# Simulate prior approve: a InventoryDevice marked approved, but NO matching
|
||||
# Node exists (the user deleted the canvas node afterwards).
|
||||
orphan = PendingDevice(
|
||||
orphan = InventoryDevice(
|
||||
ieee_address="0xR1",
|
||||
friendly_name="router_1",
|
||||
hostname="router_1",
|
||||
@@ -541,7 +547,7 @@ async def test_persist_pending_import_revives_orphaned_approved_device(
|
||||
# No new row created for 0xR1 — the existing one was updated/revived.
|
||||
revived = (
|
||||
await db_session.execute(
|
||||
select(PendingDevice).where(PendingDevice.ieee_address == "0xR1")
|
||||
select(InventoryDevice).where(InventoryDevice.ieee_address == "0xR1")
|
||||
)
|
||||
).scalar_one()
|
||||
assert revived.status == "pending"
|
||||
@@ -552,7 +558,7 @@ async def test_persist_pending_import_revives_orphaned_approved_device(
|
||||
# It is now visible to the Pending list (status filter == "pending").
|
||||
listed = (
|
||||
await db_session.execute(
|
||||
select(PendingDevice).where(PendingDevice.status == "pending")
|
||||
select(InventoryDevice).where(InventoryDevice.status == "pending")
|
||||
)
|
||||
).scalars().all()
|
||||
assert {p.ieee_address for p in listed} == {"0xCOORD", "0xR1", "0xE1"}
|
||||
@@ -566,9 +572,9 @@ async def test_persist_pending_import_keeps_hidden_hidden_on_reimport(
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.api.routes.zigbee import _persist_pending_import
|
||||
from app.db.models import PendingDevice
|
||||
from app.db.models import InventoryDevice
|
||||
|
||||
hidden = PendingDevice(
|
||||
hidden = InventoryDevice(
|
||||
ieee_address="0xR1",
|
||||
friendly_name="router_1",
|
||||
suggested_type="zigbee_router",
|
||||
@@ -583,7 +589,7 @@ async def test_persist_pending_import_keeps_hidden_hidden_on_reimport(
|
||||
|
||||
still_hidden = (
|
||||
await db_session.execute(
|
||||
select(PendingDevice).where(PendingDevice.ieee_address == "0xR1")
|
||||
select(InventoryDevice).where(InventoryDevice.ieee_address == "0xR1")
|
||||
)
|
||||
).scalar_one()
|
||||
assert still_hidden.status == "hidden"
|
||||
@@ -595,21 +601,24 @@ async def test_persist_pending_import_preserves_user_visibility(db_session) -> N
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.api.routes.zigbee import _persist_pending_import
|
||||
from app.db.models import Node
|
||||
from app.db.models import InventoryDevice, Node
|
||||
|
||||
approved = Node(
|
||||
label="router_1",
|
||||
type="zigbee_router",
|
||||
status="online",
|
||||
check_method="none",
|
||||
device = InventoryDevice(
|
||||
ieee_address="0xR1",
|
||||
services=[],
|
||||
friendly_name="router_1",
|
||||
suggested_type="zigbee_router",
|
||||
status="approved",
|
||||
status_live="online",
|
||||
check_method="none",
|
||||
properties=[
|
||||
{"key": "IEEE", "value": "0xR1", "icon": None, "visible": True},
|
||||
{"key": "Vendor", "value": "TI", "icon": None, "visible": True},
|
||||
{"key": "Custom", "value": "kept", "icon": None, "visible": True},
|
||||
],
|
||||
)
|
||||
db_session.add(device)
|
||||
await db_session.flush()
|
||||
approved = Node(label="router_1", type="zigbee_router", device_id=device.id)
|
||||
db_session.add(approved)
|
||||
await db_session.commit()
|
||||
|
||||
@@ -619,7 +628,9 @@ async def test_persist_pending_import_preserves_user_visibility(db_session) -> N
|
||||
await _persist_pending_import(db_session, bumped, _PENDING_EDGES)
|
||||
|
||||
refreshed = (
|
||||
await db_session.execute(select(Node).where(Node.ieee_address == "0xR1"))
|
||||
await db_session.execute(
|
||||
select(InventoryDevice).where(InventoryDevice.ieee_address == "0xR1")
|
||||
)
|
||||
).scalar_one()
|
||||
by_key = {p["key"]: p for p in refreshed.properties}
|
||||
# Existing keys keep their visibility (True).
|
||||
@@ -644,13 +655,17 @@ async def test_persist_pending_import_refreshes_approved_coordinator_node(
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.api.routes.zigbee import _persist_pending_import
|
||||
from app.db.models import Node, PendingDevice
|
||||
from app.db.models import InventoryDevice, Node
|
||||
|
||||
# Legacy: coordinator auto-placed as a canvas Node, no pending_devices row.
|
||||
db_session.add(Node(
|
||||
label="Coordinator", type="zigbee_coordinator", status="online",
|
||||
check_method="none", ieee_address="0xCOORD", services=[], properties=[],
|
||||
))
|
||||
# Legacy: coordinator auto-placed as a canvas Node, no device_inventory row.
|
||||
drawn = InventoryDevice(
|
||||
ieee_address="0xCOORD", friendly_name="Coordinator",
|
||||
suggested_type="zigbee_coordinator", status="approved", status_live="online",
|
||||
check_method="none",
|
||||
)
|
||||
db_session.add(drawn)
|
||||
await db_session.flush()
|
||||
db_session.add(Node(label="Coordinator", type="zigbee_coordinator", device_id=drawn.id))
|
||||
await db_session.commit()
|
||||
|
||||
bumped = [dict(n) for n in _PENDING_NODES]
|
||||
@@ -659,7 +674,9 @@ async def test_persist_pending_import_refreshes_approved_coordinator_node(
|
||||
await _persist_pending_import(db_session, bumped, _PENDING_EDGES)
|
||||
|
||||
coord = (
|
||||
await db_session.execute(select(Node).where(Node.ieee_address == "0xCOORD"))
|
||||
await db_session.execute(
|
||||
select(InventoryDevice).where(InventoryDevice.ieee_address == "0xCOORD")
|
||||
)
|
||||
).scalar_one()
|
||||
keys = {p["key"]: p["value"] for p in coord.properties}
|
||||
assert keys["Vendor"] == "TI"
|
||||
@@ -669,7 +686,7 @@ async def test_persist_pending_import_refreshes_approved_coordinator_node(
|
||||
# Inventory row backfilled as approved → now visible in the inventory list.
|
||||
inv = (
|
||||
await db_session.execute(
|
||||
select(PendingDevice).where(PendingDevice.ieee_address == "0xCOORD")
|
||||
select(InventoryDevice).where(InventoryDevice.ieee_address == "0xCOORD")
|
||||
)
|
||||
).scalar_one()
|
||||
assert inv.status == "approved"
|
||||
@@ -685,17 +702,19 @@ async def test_persist_pending_import_device_on_multiple_canvases(
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.api.routes.zigbee import _persist_pending_import
|
||||
from app.db.models import Design, Node
|
||||
from app.db.models import Design, InventoryDevice, Node
|
||||
|
||||
d1 = Design(name="d1")
|
||||
d2 = Design(name="d2")
|
||||
db_session.add_all([d1, d2])
|
||||
drawn = InventoryDevice(
|
||||
ieee_address="0xR1", friendly_name="router_1", suggested_type="zigbee_router",
|
||||
status="approved", status_live="online", check_method="none",
|
||||
)
|
||||
db_session.add_all([d1, d2, drawn])
|
||||
await db_session.flush()
|
||||
for d in (d1, d2):
|
||||
db_session.add(Node(
|
||||
label="router_1", type="zigbee_router", status="online",
|
||||
check_method="none", ieee_address="0xR1", services=[],
|
||||
properties=[], design_id=d.id,
|
||||
label="router_1", type="zigbee_router", device_id=drawn.id, design_id=d.id,
|
||||
))
|
||||
await db_session.commit()
|
||||
|
||||
@@ -705,10 +724,12 @@ async def test_persist_pending_import_device_on_multiple_canvases(
|
||||
await _persist_pending_import(db_session, bumped, _PENDING_EDGES)
|
||||
|
||||
nodes = (
|
||||
await db_session.execute(select(Node).where(Node.ieee_address == "0xR1"))
|
||||
await db_session.execute(select(Node).where(Node.device_id == drawn.id))
|
||||
).scalars().all()
|
||||
assert len(nodes) == 2 # both canvas placements preserved
|
||||
for n in nodes:
|
||||
# One row behind them, so one refresh serves both canvases.
|
||||
await db_session.refresh(drawn)
|
||||
for n in [drawn]:
|
||||
lqi = {p["key"]: p["value"] for p in n.properties}.get("LQI")
|
||||
assert lqi == "240" # refreshed on every canvas
|
||||
|
||||
|
||||
@@ -294,7 +294,7 @@ async def test_persist_coordinator_goes_to_pending(db_session) -> None:
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.api.routes.zwave import _persist_pending_import
|
||||
from app.db.models import Node, PendingDevice
|
||||
from app.db.models import InventoryDevice, Node
|
||||
|
||||
result = await _persist_pending_import(db_session, _PENDING_NODES, _PENDING_EDGES)
|
||||
assert result.device_count == 3
|
||||
@@ -308,7 +308,7 @@ async def test_persist_coordinator_goes_to_pending(db_session) -> None:
|
||||
assert nodes == []
|
||||
coord = (
|
||||
await db_session.execute(
|
||||
select(PendingDevice).where(PendingDevice.ieee_address == "zwave-0xh-1")
|
||||
select(InventoryDevice).where(InventoryDevice.ieee_address == "zwave-0xh-1")
|
||||
)
|
||||
).scalar_one()
|
||||
assert coord.status == "pending"
|
||||
@@ -333,12 +333,12 @@ async def test_persist_replaces_links(db_session) -> None:
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.api.routes.zwave import _persist_pending_import
|
||||
from app.db.models import PendingDeviceLink
|
||||
from app.db.models import InventoryDeviceLink
|
||||
|
||||
await _persist_pending_import(db_session, _PENDING_NODES, _PENDING_EDGES)
|
||||
new_edges = [{"source": "zwave-0xh-1", "target": "zwave-0xh-2"}]
|
||||
await _persist_pending_import(db_session, _PENDING_NODES[:2], new_edges)
|
||||
rows = (await db_session.execute(select(PendingDeviceLink))).scalars().all()
|
||||
rows = (await db_session.execute(select(InventoryDeviceLink))).scalars().all()
|
||||
assert len(rows) == 1
|
||||
assert (rows[0].source_ieee, rows[0].target_ieee) == ("zwave-0xh-1", "zwave-0xh-2")
|
||||
|
||||
@@ -349,7 +349,7 @@ async def test_persist_sets_coordinator_pending_fields(db_session) -> None:
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.api.routes.zwave import _persist_pending_import
|
||||
from app.db.models import PendingDevice
|
||||
from app.db.models import InventoryDevice
|
||||
|
||||
nodes = [dict(n) for n in _PENDING_NODES]
|
||||
nodes[0]["vendor"] = "Aeotec"
|
||||
@@ -357,7 +357,7 @@ async def test_persist_sets_coordinator_pending_fields(db_session) -> None:
|
||||
await _persist_pending_import(db_session, nodes, _PENDING_EDGES)
|
||||
coord = (
|
||||
await db_session.execute(
|
||||
select(PendingDevice).where(PendingDevice.ieee_address == "zwave-0xh-1")
|
||||
select(InventoryDevice).where(InventoryDevice.ieee_address == "zwave-0xh-1")
|
||||
)
|
||||
).scalar_one()
|
||||
assert coord.vendor == "Aeotec"
|
||||
@@ -372,31 +372,31 @@ async def test_persist_backfills_inventory_for_approved_node(db_session) -> None
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.api.routes.zwave import _persist_pending_import
|
||||
from app.db.models import Node, PendingDevice
|
||||
from app.db.models import InventoryDevice, Node
|
||||
|
||||
approved = Node(
|
||||
label="Wall Plug",
|
||||
type="zwave_router",
|
||||
status="online",
|
||||
drawn = InventoryDevice(
|
||||
ieee_address="zwave-0xh-2", friendly_name="Wall Plug",
|
||||
suggested_type="zwave_router", status="approved", status_live="online",
|
||||
check_method="none",
|
||||
ieee_address="zwave-0xh-2",
|
||||
services=[],
|
||||
properties=[],
|
||||
)
|
||||
db_session.add(approved)
|
||||
db_session.add(drawn)
|
||||
await db_session.flush()
|
||||
db_session.add(Node(label="Wall Plug", type="zwave_router", device_id=drawn.id))
|
||||
await db_session.commit()
|
||||
|
||||
await _persist_pending_import(db_session, _PENDING_NODES, _PENDING_EDGES)
|
||||
|
||||
inv = (
|
||||
await db_session.execute(
|
||||
select(PendingDevice).where(PendingDevice.ieee_address == "zwave-0xh-2")
|
||||
select(InventoryDevice).where(InventoryDevice.ieee_address == "zwave-0xh-2")
|
||||
)
|
||||
).scalar_one()
|
||||
assert inv.status == "approved"
|
||||
assert inv.suggested_type == "zwave_router"
|
||||
refreshed = (
|
||||
await db_session.execute(select(Node).where(Node.ieee_address == "zwave-0xh-2"))
|
||||
await db_session.execute(
|
||||
select(InventoryDevice).where(InventoryDevice.ieee_address == "zwave-0xh-2")
|
||||
)
|
||||
).scalar_one()
|
||||
keys = {p["key"]: p["value"] for p in refreshed.properties}
|
||||
assert keys == {"Z-Wave ID": "zwave-0xh-2", "Vendor": "Aeotec", "Model": "ZW100"}
|
||||
@@ -407,9 +407,9 @@ async def test_persist_revives_orphaned_approved_device(db_session) -> None:
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.api.routes.zwave import _persist_pending_import
|
||||
from app.db.models import PendingDevice
|
||||
from app.db.models import InventoryDevice
|
||||
|
||||
orphan = PendingDevice(
|
||||
orphan = InventoryDevice(
|
||||
ieee_address="zwave-0xh-2",
|
||||
friendly_name="Wall Plug",
|
||||
suggested_type="zwave_router",
|
||||
@@ -423,7 +423,7 @@ async def test_persist_revives_orphaned_approved_device(db_session) -> None:
|
||||
result = await _persist_pending_import(db_session, _PENDING_NODES, _PENDING_EDGES)
|
||||
revived = (
|
||||
await db_session.execute(
|
||||
select(PendingDevice).where(PendingDevice.ieee_address == "zwave-0xh-2")
|
||||
select(InventoryDevice).where(InventoryDevice.ieee_address == "zwave-0xh-2")
|
||||
)
|
||||
).scalar_one()
|
||||
assert revived.status == "pending"
|
||||
@@ -437,9 +437,9 @@ async def test_persist_keeps_hidden_hidden(db_session) -> None:
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.api.routes.zwave import _persist_pending_import
|
||||
from app.db.models import PendingDevice
|
||||
from app.db.models import InventoryDevice
|
||||
|
||||
hidden = PendingDevice(
|
||||
hidden = InventoryDevice(
|
||||
ieee_address="zwave-0xh-2",
|
||||
friendly_name="Wall Plug",
|
||||
suggested_type="zwave_router",
|
||||
@@ -453,7 +453,7 @@ async def test_persist_keeps_hidden_hidden(db_session) -> None:
|
||||
await _persist_pending_import(db_session, _PENDING_NODES, _PENDING_EDGES)
|
||||
still_hidden = (
|
||||
await db_session.execute(
|
||||
select(PendingDevice).where(PendingDevice.ieee_address == "zwave-0xh-2")
|
||||
select(InventoryDevice).where(InventoryDevice.ieee_address == "zwave-0xh-2")
|
||||
)
|
||||
).scalar_one()
|
||||
assert still_hidden.status == "hidden"
|
||||
@@ -466,17 +466,20 @@ async def test_persist_device_on_multiple_canvases(db_session) -> None:
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.api.routes.zwave import _persist_pending_import
|
||||
from app.db.models import Design, Node
|
||||
from app.db.models import Design, InventoryDevice, Node
|
||||
|
||||
d1 = Design(name="d1")
|
||||
d2 = Design(name="d2")
|
||||
db_session.add_all([d1, d2])
|
||||
drawn = InventoryDevice(
|
||||
ieee_address="zwave-0xh-2", friendly_name="Wall Plug",
|
||||
suggested_type="zwave_router", status="approved", status_live="online",
|
||||
check_method="none",
|
||||
)
|
||||
db_session.add_all([d1, d2, drawn])
|
||||
await db_session.flush()
|
||||
for d in (d1, d2):
|
||||
db_session.add(Node(
|
||||
label="Wall Plug", type="zwave_router", status="online",
|
||||
check_method="none", ieee_address="zwave-0xh-2", services=[],
|
||||
properties=[], design_id=d.id,
|
||||
label="Wall Plug", type="zwave_router", device_id=drawn.id, design_id=d.id,
|
||||
))
|
||||
await db_session.commit()
|
||||
|
||||
@@ -486,12 +489,13 @@ async def test_persist_device_on_multiple_canvases(db_session) -> None:
|
||||
await _persist_pending_import(db_session, bumped, _PENDING_EDGES)
|
||||
|
||||
nodes = (
|
||||
await db_session.execute(select(Node).where(Node.ieee_address == "zwave-0xh-2"))
|
||||
await db_session.execute(select(Node).where(Node.device_id == drawn.id))
|
||||
).scalars().all()
|
||||
assert len(nodes) == 2 # both canvas placements preserved
|
||||
for n in nodes:
|
||||
model = {p["key"]: p["value"] for p in n.properties}.get("Model")
|
||||
assert model == "ZW200" # refreshed on every canvas
|
||||
# One row behind them, so one refresh serves every canvas.
|
||||
await db_session.refresh(drawn)
|
||||
model = {p["key"]: p["value"] for p in drawn.properties}.get("Model")
|
||||
assert model == "ZW200"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 82" width="64" height="82" fill="none">
|
||||
<defs>
|
||||
<radialGradient id="bg-glow" cx="50%" cy="35%" r="55%">
|
||||
<stop offset="0%" stop-color="#00d4ff" stop-opacity="0.08"/>
|
||||
<stop offset="100%" stop-color="#0d1117" stop-opacity="0"/>
|
||||
</radialGradient>
|
||||
<filter id="node-glow">
|
||||
<feGaussianBlur stdDeviation="1.5" result="blur"/>
|
||||
<feMerge><feMergeNode in="blur"/><feMergeNode in="SourceGraphic"/></feMerge>
|
||||
</filter>
|
||||
</defs>
|
||||
<circle cx="32" cy="32" r="32" fill="#0d1117"/>
|
||||
<circle cx="32" cy="32" r="32" fill="url(#bg-glow)"/>
|
||||
<path d="M32 11 L53 30 L48 30 L48 53 L16 53 L16 30 L11 30 Z"
|
||||
fill="#161b22" stroke="#00d4ff" stroke-width="1.5" stroke-linejoin="round"/>
|
||||
<line x1="16" y1="30" x2="48" y2="30" stroke="#00d4ff" stroke-width="0.5" opacity="0.25"/>
|
||||
<rect x="27" y="40" width="10" height="13" rx="1.5"
|
||||
fill="#0d1117" stroke="#00d4ff" stroke-width="1" opacity="0.9"/>
|
||||
<line x1="32" y1="23" x2="32" y2="30" stroke="#a855f7" stroke-width="1.2" opacity="0.7" stroke-linecap="round"/>
|
||||
<line x1="21" y1="38" x2="29" y2="33" stroke="#39d353" stroke-width="1.2" opacity="0.7" stroke-linecap="round"/>
|
||||
<line x1="43" y1="38" x2="35" y2="33" stroke="#39d353" stroke-width="1.2" opacity="0.7" stroke-linecap="round"/>
|
||||
<circle cx="32" cy="33" r="5" fill="#00d4ff" opacity="0.12"/>
|
||||
<circle cx="32" cy="33" r="3" fill="#00d4ff" filter="url(#node-glow)"/>
|
||||
<circle cx="21" cy="38" r="2.5" fill="#39d353" filter="url(#node-glow)"/>
|
||||
<circle cx="43" cy="38" r="2.5" fill="#39d353" filter="url(#node-glow)"/>
|
||||
<circle cx="32" cy="23" r="2" fill="#a855f7" filter="url(#node-glow)"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.7 KiB |
@@ -0,0 +1,192 @@
|
||||
# OpenID Connect (OIDC) Authentication
|
||||
|
||||
Homelable can delegate login to your own identity provider (IdP) instead of the
|
||||
built-in username/password. Sign-in uses the standard **Authorization Code flow
|
||||
with PKCE**: the browser is redirected to your IdP, and on return Homelable
|
||||
issues its own short-lived session cookie. Provider access/ID tokens are
|
||||
exchanged server-side and **never** reach the browser.
|
||||
|
||||
Use it when you want single sign-on, per-user accounts managed at the IdP, MFA,
|
||||
or central account revocation — Authentik, Keycloak, Authelia, Zitadel, Google,
|
||||
Microsoft Entra ID, Okta, or any spec-compliant OpenID Connect provider.
|
||||
|
||||
> 🔒 **Server-dependent feature** — requires the Homelable backend. It is hidden
|
||||
> in the no-backend standalone/demo build, which has no login at all.
|
||||
|
||||
---
|
||||
|
||||
## How it works
|
||||
|
||||
1. Homelable exposes its mode at `GET /api/v1/auth/config`. In OIDC mode the
|
||||
login screen shows **Sign in with OpenID Connect**.
|
||||
2. `GET /api/v1/auth/oidc/login` redirects to your IdP with `state`, `nonce`,
|
||||
and a PKCE `code_challenge` (S256).
|
||||
3. The IdP authenticates the user and redirects back to
|
||||
`GET /api/v1/auth/oidc/callback`.
|
||||
4. Homelable validates the response (signature via the IdP's JWKS, issuer,
|
||||
audience, expiry, `nonce`, `state`, PKCE) and mints its **own** session token.
|
||||
5. That token is stored in a `__Host-`, `HttpOnly`, `Secure`, `SameSite=Lax`
|
||||
cookie. The browser never sees the provider tokens.
|
||||
|
||||
The display name shown in the app is the first present of
|
||||
`preferred_username` → `name` → `email` → `sub`.
|
||||
|
||||
Local Bearer authentication and the MCP service key keep working unchanged, so
|
||||
the API and the MCP server are unaffected.
|
||||
|
||||
---
|
||||
|
||||
## Prerequisites
|
||||
|
||||
1. A reachable **OpenID Connect** provider with a discovery document
|
||||
(`.well-known/openid-configuration`).
|
||||
2. Homelable served over **HTTPS** in production (required for the secure
|
||||
session cookie).
|
||||
3. A **confidential** OIDC client (client id **and** secret) registered at the
|
||||
IdP, with Homelable's callback URL allow-listed as a redirect URI.
|
||||
|
||||
---
|
||||
|
||||
## Configuration
|
||||
|
||||
All settings live in `.env` (see `.env.example`). Switching to OIDC is
|
||||
exclusive — it replaces local login. Existing installs stay on
|
||||
`AUTH_MODE=local` until you change this.
|
||||
|
||||
```env
|
||||
AUTH_MODE=oidc
|
||||
|
||||
# Pin CORS to the exact browser origin(s). Wildcard is rejected in OIDC mode.
|
||||
CORS_ORIGINS=["https://homelable.example"]
|
||||
|
||||
# From your IdP:
|
||||
OIDC_DISCOVERY_URL=https://idp.example/application/o/homelable/.well-known/openid-configuration
|
||||
OIDC_CLIENT_ID=homelable
|
||||
OIDC_CLIENT_SECRET=replace-with-a-secret
|
||||
|
||||
# Must EXACTLY match a redirect URI registered at the IdP.
|
||||
OIDC_REDIRECT_URI=https://homelable.example/api/v1/auth/oidc/callback
|
||||
|
||||
OIDC_SCOPES="openid profile email"
|
||||
OIDC_COOKIE_SECURE=true
|
||||
OIDC_SESSION_EXPIRE_MINUTES=480
|
||||
OIDC_TRANSACTION_EXPIRE_SECONDS=600
|
||||
```
|
||||
|
||||
Then restart the backend (`docker compose restart backend`).
|
||||
|
||||
### Reference
|
||||
|
||||
| Variable | Required | Default | Notes |
|
||||
|---|---|---|---|
|
||||
| `AUTH_MODE` | yes | `local` | Set to `oidc` to enable. |
|
||||
| `OIDC_DISCOVERY_URL` | yes | — | The IdP's `.well-known/openid-configuration` URL. |
|
||||
| `OIDC_CLIENT_ID` | yes | — | Confidential client id. |
|
||||
| `OIDC_CLIENT_SECRET` | yes | — | Client secret. Keep it out of Git and Compose YAML. |
|
||||
| `OIDC_REDIRECT_URI` | yes | — | Must equal the registered redirect **exactly**, path included. |
|
||||
| `OIDC_SCOPES` | no | `openid profile email` | Must contain `openid`. |
|
||||
| `OIDC_COOKIE_SECURE` | no | `true` | `true` requires an HTTPS redirect URI and enables the `__Host-` cookie prefix. Set `false` only for local HTTP testing. |
|
||||
| `OIDC_SESSION_EXPIRE_MINUTES` | no | `480` | App session lifetime (5–1440). |
|
||||
| `OIDC_TRANSACTION_EXPIRE_SECONDS` | no | `600` | Lifetime of the short login-flow cookie holding `state`/`nonce`/PKCE (60–3600). |
|
||||
| `SECRET_KEY` | yes | — | Must be **≥ 32 bytes** in OIDC mode. Generate: `python3 -c "import secrets; print(secrets.token_hex(32))"`. |
|
||||
| `CORS_ORIGINS` | yes | — | Exact browser origin(s). `*` is rejected in OIDC mode. |
|
||||
|
||||
### Fail-closed validation
|
||||
|
||||
The backend refuses to start in OIDC mode unless the configuration is complete
|
||||
and safe. It errors if any of the following is true:
|
||||
|
||||
- any of `OIDC_DISCOVERY_URL`, `OIDC_CLIENT_ID`, `OIDC_CLIENT_SECRET`,
|
||||
`OIDC_REDIRECT_URI` is missing;
|
||||
- `SECRET_KEY` is shorter than 32 bytes;
|
||||
- `OIDC_SCOPES` does not contain `openid`;
|
||||
- `OIDC_DISCOVERY_URL` or `OIDC_REDIRECT_URI` is not an HTTP(S) URL;
|
||||
- `OIDC_COOKIE_SECURE=true` but `OIDC_REDIRECT_URI` is not HTTPS;
|
||||
- `CORS_ORIGINS` contains `*`.
|
||||
|
||||
---
|
||||
|
||||
## Provider setup
|
||||
|
||||
The callback URL to register everywhere is:
|
||||
|
||||
```
|
||||
https://<your-host>/api/v1/auth/oidc/callback
|
||||
```
|
||||
|
||||
### Authentik
|
||||
|
||||
1. **Applications → Providers → Create → OAuth2/OpenID Provider.**
|
||||
2. Client type **Confidential**; add the redirect URI above.
|
||||
3. Note the client id/secret and the discovery URL:
|
||||
`https://authentik.example/application/o/<app-slug>/.well-known/openid-configuration`.
|
||||
4. Create an **Application** bound to that provider.
|
||||
|
||||
### Keycloak
|
||||
|
||||
1. In your realm: **Clients → Create client** (OpenID Connect), **Client
|
||||
authentication ON** (confidential).
|
||||
2. Set **Valid redirect URIs** to the callback URL.
|
||||
3. Discovery URL:
|
||||
`https://kc.example/realms/<realm>/.well-known/openid-configuration`.
|
||||
4. Copy the secret from the **Credentials** tab.
|
||||
|
||||
### Authelia
|
||||
|
||||
1. Add Homelable to the `identity_providers.oidc.clients` list with a
|
||||
`client_secret`, the redirect URI, and scopes `openid profile email`.
|
||||
2. Discovery URL: `https://auth.example/.well-known/openid-configuration`.
|
||||
|
||||
### Google
|
||||
|
||||
1. **Google Cloud Console → APIs & Services → Credentials → OAuth client ID**
|
||||
(type *Web application*).
|
||||
2. Add the callback URL under **Authorized redirect URIs** (Google requires
|
||||
HTTPS).
|
||||
3. Discovery URL: `https://accounts.google.com/.well-known/openid-configuration`.
|
||||
|
||||
Any other spec-compliant provider works the same way — point
|
||||
`OIDC_DISCOVERY_URL` at its discovery document.
|
||||
|
||||
---
|
||||
|
||||
## Behind a reverse proxy
|
||||
|
||||
Homelable derives the redirect target from `OIDC_REDIRECT_URI`, so set it to the
|
||||
**public** HTTPS URL your users reach — not the internal container address. Make
|
||||
sure the proxy:
|
||||
|
||||
- terminates TLS and forwards `/api/v1/auth/oidc/*` to the backend;
|
||||
- passes the original `Host` and `X-Forwarded-Proto` headers;
|
||||
- does not strip the `Cookie` / `Set-Cookie` headers on those routes.
|
||||
|
||||
---
|
||||
|
||||
## Logout & sessions
|
||||
|
||||
- **Logout** clears the Homelable session cookie (`POST /api/v1/auth/logout`).
|
||||
- Sessions are stateless JWTs signed with `SECRET_KEY`; there is no server-side
|
||||
revocation, so a session stays valid until `OIDC_SESSION_EXPIRE_MINUTES`
|
||||
elapses. Keep the lifetime modest for sensitive deployments.
|
||||
- Logout is local to Homelable; it does not sign the user out at the IdP.
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Symptom | Likely cause / fix |
|
||||
|---|---|
|
||||
| IdP shows `redirect_uri_mismatch` | `OIDC_REDIRECT_URI` must equal the registered URI **exactly**, including scheme, host, port and the `/api/v1/auth/oidc/callback` path. |
|
||||
| `OIDC authentication failed` (401) after IdP login | Wrong client secret, `openid` missing from scopes, or clock skew breaking `nonce`/`exp` — sync server time (NTP). |
|
||||
| Logged out immediately / cookie not set | `OIDC_COOKIE_SECURE=true` while serving over HTTP. Serve HTTPS, or set `OIDC_COOKIE_SECURE=false` for local testing only. |
|
||||
| `403 CSRF validation failed` on save/actions | The request `Origin` is not in `CORS_ORIGINS`, or a stale tab is missing the CSRF token — reload the page. |
|
||||
| Backend won't start in OIDC mode | Re-read the error: a required `OIDC_*` value is missing, `SECRET_KEY` < 32 bytes, `CORS_ORIGINS` has `*`, or the redirect isn't HTTPS while the cookie is secure. |
|
||||
| Login button doesn't appear | `AUTH_MODE` is still `local`, or the frontend can't reach `/api/v1/auth/config` — check the proxy and `CORS_ORIGINS`. |
|
||||
|
||||
---
|
||||
|
||||
## Reverting to local auth
|
||||
|
||||
Set `AUTH_MODE=local` (or remove it) and restart the backend. The
|
||||
`AUTH_USERNAME` / `AUTH_PASSWORD_HASH` login is restored; the `OIDC_*` values are
|
||||
ignored while in local mode.
|
||||
@@ -0,0 +1,247 @@
|
||||
# Rack Canvas
|
||||
|
||||
A rack canvas is the **physical** counterpart to the network diagram: real racks,
|
||||
the gear mounted in them, and the patch cables between their ports. It is a
|
||||
canvas kind of its own — you create it like any other canvas, and Homelable swaps
|
||||
the renderer when you switch to it.
|
||||
|
||||
Where the diagram answers *what talks to what*, the rack answers *what is where*:
|
||||
which U a machine sits in, what plate it wears, which switch port its uplink
|
||||
lands on.
|
||||
|
||||
> Works with **and** without the backend. In the no-backend standalone/demo build
|
||||
> a rack canvas persists to your browser's local storage; the Device Inventory
|
||||
> picker and the live status check are backend-only (marked 🔒 below).
|
||||
|
||||
---
|
||||
|
||||
## Feature Overview
|
||||
|
||||
- **Racks** — any U height, 19" or 10" wide, bottom-up or top-down numbering, per-rack frame / rail / interior colours, open or enclosed.
|
||||
- **Mounted gear** — a device occupies a U range and part of a 12-column width grid, so half- and third-width machines share a U.
|
||||
- **Faceplates** — a visual catalog of plates (servers, switches, routers, patch panels, UPS, PDUs, desktop NAS towers, shelves, blanks, cable managers) drawn as vector artwork that scales with the rack.
|
||||
- **Ports & patching** — RJ45 and SFP ports per device, cabled port-to-port by dragging from one to the other, across racks if needed.
|
||||
- **Device Inventory** 🔒 — a mount points at a real inventory entry, so a rack shows the same devices your scans found, and gear you rack by hand joins that inventory.
|
||||
- **Live status** 🔒 — a mount can follow the status check already configured on the matching diagram node, and light its plate LED accordingly.
|
||||
- **Import links** 🔒 — derive patches from the physical links already drawn on your diagrams, as often as you like.
|
||||
|
||||
---
|
||||
|
||||
## Create a rack canvas
|
||||
|
||||
1. Open the **canvas switcher** at the top of the left sidebar.
|
||||
2. Click **New Canvas**.
|
||||
3. Under **Kind**, pick **Rack** (the other kind, *Diagram*, is the usual node/link canvas).
|
||||
4. Name it, pick an icon, and create.
|
||||
|
||||
A canvas cannot change kind afterwards — a diagram and a rack store different
|
||||
things. Deleting a rack canvas deletes its racks, mounts and cables with it;
|
||||
duplicating a canvas duplicates them too.
|
||||
|
||||
---
|
||||
|
||||
## Add a rack
|
||||
|
||||
**Add Rack** in the header drops a new rack on the canvas. Drag it anywhere; a
|
||||
canvas can hold as many as you like, and cables can run between them.
|
||||
|
||||
**Double-click the rack chrome** (the frame, not a device) to open its settings:
|
||||
|
||||
| Setting | What it does |
|
||||
|---|---|
|
||||
| Name / Location | Free text — "Baie salon", "Garage", … |
|
||||
| U height | How many mountable U the rack has (42 by default). |
|
||||
| Width | 19" or 10" — drives the drawn inner width. |
|
||||
| Numbering | `bottom-up` or `top-down`. **Labels only** — gear never moves. |
|
||||
| Show U numbers | Print the U scale on the rails. |
|
||||
| Enclosed | Draw side panels / a closed chassis. |
|
||||
| Colours | Frame, rails and interior. Defaults come from your app theme. |
|
||||
| Delete | Removes the rack and everything mounted in it. |
|
||||
|
||||
---
|
||||
|
||||
## Mount a device
|
||||
|
||||
Click **+ Device** in the left sidebar, or drag an accessory from the sidebar
|
||||
tray straight onto a rack. The device modal offers three sources:
|
||||
|
||||
- **Device Inventory entry** 🔒 — pick something already discovered. The field
|
||||
opens the real Device Inventory, with its search, source and type filters, and
|
||||
it opens pre-filtered to **rackable** hardware (no light bulbs, no sockets).
|
||||
A device already mounted on this canvas is refused.
|
||||
- **New device** — for hardware no scan can find (a patch panel, a PDU, an
|
||||
unmanaged switch). It is created as a normal Device Inventory entry tagged
|
||||
**Rack devices**, so you can search, filter, hide and delete it like any other.
|
||||
- **Accessory** — rack-only furniture: blanking plate, shelf, cable manager.
|
||||
These are not devices and never appear in the inventory.
|
||||
|
||||
Then set:
|
||||
|
||||
| Field | Notes |
|
||||
|---|---|
|
||||
| Label | Shown on the plate. |
|
||||
| Faceplate | Opens the visual catalog — see below. |
|
||||
| U position / height | `U` is counted **from the bottom rail**, whatever the numbering setting prints. |
|
||||
| Column / width | Full, half, third, sixth or quarter of the rack width. |
|
||||
| Status | A fixed colour, or **Check device** 🔒 — see below. |
|
||||
| Colour | Overrides the plate's default tint. |
|
||||
| Ports | The list of RJ45 / SFP ports, seeded by the faceplate and editable afterwards. |
|
||||
|
||||
**Double-click a plate** to reopen this modal on an existing mount; a single
|
||||
click only selects it. **Unmount** takes the device out of the rack — it stays in
|
||||
the Device Inventory.
|
||||
|
||||
### Linked device 🔒
|
||||
|
||||
Under the port list, a mount that stands for a real device prints what is known
|
||||
about that box: name, type, hostname, IP, MAC, OS, the status check it runs, the
|
||||
canvas it is drawn on, when it was last seen, and the services discovery
|
||||
fingerprinted on it.
|
||||
|
||||
It is read-only — edit those facts in the Device Inventory or on the logical
|
||||
canvas, not in the rack — and an accessory shows nothing at all. A device that is
|
||||
on no diagram still prints everything discovery found about it; only the
|
||||
canvas-side lines go missing, and the panel says *Not on a logical canvas.*
|
||||
|
||||
**Link to another device…** points the plate at a different Device Inventory
|
||||
entry — the whole inventory, not just the devices you approved onto a diagram.
|
||||
Use it when you created the gear from the rack (the entry starts empty, with just
|
||||
a name) or when the plate ended up on the wrong twin of two look-alike hosts. The
|
||||
plate takes the entry's IP, MAC, services, status and — unless you renamed it —
|
||||
its name, **Check device** becomes available if that device is on a diagram, and
|
||||
the link is saved with the rest of the canvas. A device already mounted elsewhere
|
||||
in the design is not offered: one entry, one plate. The empty placeholder the
|
||||
rack created for the plate is removed from the inventory once nothing uses it.
|
||||
|
||||
### Placement rules
|
||||
|
||||
- A drop **snaps to the nearest free slot**; a placement that cannot work
|
||||
previews in red.
|
||||
- Drag a mounted device inside its rack to move it — same snapping.
|
||||
- **Growing** a device, by hand or by picking a taller plate, relocates it to the
|
||||
nearest slot that takes the new size. Only a rack with no such slot refuses the
|
||||
edit, and it tells you so.
|
||||
|
||||
---
|
||||
|
||||
## Faceplates
|
||||
|
||||
The **Faceplate** field opens a catalog, not a dropdown of names: every plate is
|
||||
drawn with the real renderer, at its real relative width and U height, grouped by
|
||||
family and searchable.
|
||||
|
||||
| Family | Examples |
|
||||
|---|---|
|
||||
| Servers | 1U, 1U with drive bays, 2U with bays, 4U storage, half-width SFF, third-width mini PC |
|
||||
| Network | 8 / 24 / 48-port switches, 1U router |
|
||||
| Patch | 24-port copper panel, 12-port fibre panel |
|
||||
| Storage | 2U NAS, desktop NAS towers in 2, 4 and 5 bays |
|
||||
| Power | 2U UPS, 1U PDU |
|
||||
| Accessories | Blanking plate, shelf, cable manager |
|
||||
|
||||
Picking a plate **reseeds the ports** it comes with; your own port edits are kept
|
||||
until you change plate again. Plates are drawn as vector artwork in relative
|
||||
coordinates, so they stay correct at any rack width and U height, and their
|
||||
colours follow the active app theme.
|
||||
|
||||
---
|
||||
|
||||
## Ports and patching
|
||||
|
||||
Ports are **RJ45** or **SFP/SFP+**, drawn as real jack artwork at a fixed size so
|
||||
plates of different heights line up. Power outlets are artwork only — they are
|
||||
never a cable endpoint.
|
||||
|
||||
Patch-facing gear (switches, patch panels) shows its ports permanently;
|
||||
everything else reveals them on hover, on selection, or when cables are shown.
|
||||
|
||||
To cable:
|
||||
|
||||
1. Click **Patch** in the header.
|
||||
2. **Drag from one port to another** — a dashed rubber band follows the pointer.
|
||||
Clicking the two ports in turn works just as well. **Escape** drops a
|
||||
half-drawn patch.
|
||||
3. Repeat. One cable per port; copper or fibre follows the port you start from.
|
||||
4. Click **Exit patching** when done — the canvas returns to the cable visibility
|
||||
it had before.
|
||||
|
||||
To unplug: **click the cable** (it gets an accent halo), then press
|
||||
**Delete/Backspace** or click **Unplug** in the header. A stray click never
|
||||
destroys a patch.
|
||||
|
||||
A header select controls what you see: cables **on hover**, **always**, or
|
||||
**hidden**. Cables
|
||||
pan and zoom with the canvas and may run from one rack to another. A cable you
|
||||
have selected stays drawn whatever that select says.
|
||||
|
||||
### Documenting a cable
|
||||
|
||||
**Click a cable** — patching or not — and a panel opens on the right:
|
||||
|
||||
| Field | What it does |
|
||||
|---|---|
|
||||
| Endpoints | The two devices and ports the run connects. Read-only: move a patch by unplugging it and drawing it again. |
|
||||
| Type | Ethernet or fibre. A cable still wearing its type's default colour is recoloured to match; a colour you picked yourself is kept. |
|
||||
| Colour | The sheath colours you actually have on the shelf, plus a free hex field for anything else. |
|
||||
| Label | A name for the run — "Uplink to core", a patch-panel reference. **Show on canvas** prints it next to the cable. |
|
||||
| Properties | Anything else worth recording: length, VLAN, speed, category, patch reference. Same editor as a node's properties on a diagram — a label, a value, an optional icon, and an eye that decides whether it shows on the canvas. |
|
||||
| Unplug cable | Removes the patch. The devices and their ports stay. |
|
||||
|
||||
What you tick as visible is drawn on a small plate at the middle of the run, so a
|
||||
rack photo exports with its cable lengths and VLANs on it. Everything else stays
|
||||
in the panel, one click away.
|
||||
|
||||
### Import links 🔒
|
||||
|
||||
**Import links** derives patches from the physical links (ethernet, fibre, vlan,
|
||||
cluster) already drawn on your diagrams, matching both ends to mounts that point
|
||||
at those nodes. Run it as often as you like: a pair of devices already cabled
|
||||
is left alone, so a second run after racking more gear only adds what is
|
||||
missing.
|
||||
|
||||
---
|
||||
|
||||
## Status 🔒
|
||||
|
||||
A mount's **Status** is either pinned by hand (online / offline / unknown) or set
|
||||
to **Check device**: the plate then follows the status check already configured
|
||||
on the matching diagram node (ping, HTTP, SSH, …) and its LED lights accordingly.
|
||||
|
||||
The rack runs no checker of its own — it reads the result of the one your diagram
|
||||
already performs. So:
|
||||
|
||||
- **Check device** is only offered when the mount resolves to a diagram node.
|
||||
- Losing that link drops the mount back to `unknown`, rather than leaving it on a
|
||||
status nothing answers for.
|
||||
- The refresh polls every 60 s, and only while at least one mount is on
|
||||
**Check device**.
|
||||
|
||||
---
|
||||
|
||||
## Saving
|
||||
|
||||
Like the diagram canvas, a rack canvas is **saved explicitly** — **Save Rack** in
|
||||
the left sidebar, or the header's save button. Nothing is written behind your
|
||||
back unless you turn on **Autosave** in Settings.
|
||||
|
||||
The sidebar footer counts racks, mounts, cables and free U instead of the
|
||||
diagram's online/offline tally. **PNG export** works here too.
|
||||
|
||||
---
|
||||
|
||||
## Known limits
|
||||
|
||||
- **Front view only** — no rear view, no half-depth pairing.
|
||||
- No 0U side-mounted PDU.
|
||||
- No power draw or outlet budgeting.
|
||||
- No undo/redo on a rack canvas (the diagram canvas keeps its own).
|
||||
- Rack canvases are not shown by the read-only [Live View](../README.md#live-view-read-only-public-canvas).
|
||||
- The MCP server exposes diagram nodes and links only, not racks.
|
||||
|
||||
---
|
||||
|
||||
## See also
|
||||
|
||||
- [FEATURES.md](../FEATURES.md) — every feature, one page.
|
||||
- [Device Inventory](../FEATURES.md#12-device-inventory-) — where racked devices live.
|
||||
- `frontend/src/rack/README.md` — the developer reference for this canvas.
|
||||
Generated
+522
-128
File diff suppressed because it is too large
Load Diff
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "frontend",
|
||||
"private": true,
|
||||
"version": "3.0.0",
|
||||
"version": "3.3.1",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
@@ -27,11 +27,10 @@
|
||||
"clsx": "^2.1.1",
|
||||
"dagre": "^0.8.5",
|
||||
"html-to-image": "^1.11.13",
|
||||
"js-yaml": "^4.1.1",
|
||||
"js-yaml": "^4.3.1",
|
||||
"next-themes": "^0.4.6",
|
||||
"react": "^19.2.0",
|
||||
"react-dom": "^19.2.0",
|
||||
"shadcn": "^4.0.0",
|
||||
"sonner": "^2.0.7",
|
||||
"tailwind-merge": "^3.5.0",
|
||||
"tw-animate-css": "^1.4.0",
|
||||
@@ -60,6 +59,7 @@
|
||||
"globals": "^16.5.0",
|
||||
"jsdom": "^28.1.0",
|
||||
"lucide-react": "^1.7.0",
|
||||
"shadcn": "^4.0.0",
|
||||
"tailwindcss": "^4.2.1",
|
||||
"typescript": "~5.9.3",
|
||||
"typescript-eslint": "^8.48.0",
|
||||
|
||||
+348
-82
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useCallback, useRef, useState } from 'react'
|
||||
import { useEffect, useCallback, useMemo, useRef, useState } from 'react'
|
||||
import { ReactFlowProvider, type Connection, type Edge } from '@xyflow/react'
|
||||
import { type Node } from '@xyflow/react'
|
||||
import { applyDagreLayout } from '@/utils/layout'
|
||||
@@ -32,19 +32,30 @@ import { TextModal, type TextFormData } from '@/components/modals/TextModal'
|
||||
import { ThemeModal } from '@/components/modals/ThemeModal'
|
||||
import { CustomStyleModal } from '@/components/modals/CustomStyleModal'
|
||||
import { SearchModal } from '@/components/modals/SearchModal'
|
||||
import { PendingDevicesModal } from '@/components/modals/PendingDevicesModal'
|
||||
import { DeviceInventoryModal } from '@/components/modals/DeviceInventoryModal'
|
||||
import { ScanHistoryModal } from '@/components/modals/ScanHistoryModal'
|
||||
import { ShortcutsModal } from '@/components/modals/ShortcutsModal'
|
||||
import { ConfirmAddToGroupModal } from '@/components/modals/ConfirmAddToGroupModal'
|
||||
import { useCanvasStore } from '@/stores/canvasStore'
|
||||
import { readAutosaveSettings, subscribeAutosaveSettings, type AutosaveSettings } from '@/utils/autosaveSettings'
|
||||
import { useAutosave } from '@/hooks/useAutosave'
|
||||
import { useDesignStore } from '@/stores/designStore'
|
||||
import { useAuthStore } from '@/stores/authStore'
|
||||
import { useThemeStore } from '@/stores/themeStore'
|
||||
import { canvasApi, designsApi, liveviewApi } from '@/api/client'
|
||||
import * as standaloneStorage from '@/utils/standaloneStorage'
|
||||
import { demoNodes, demoEdges } from '@/utils/demoData'
|
||||
import { decideCanvasLoad, isNewUserCanvas } from '@/utils/canvasLoadDecision'
|
||||
import { WalkthroughActionsProvider, type WalkthroughActionApi } from '@/walkthrough/actions'
|
||||
import { WalkthroughInvite } from '@/walkthrough/WalkthroughInvite'
|
||||
import { WalkthroughOverlay } from '@/walkthrough/WalkthroughOverlay'
|
||||
import { DEMO_SCAN_RUNS, DEMO_INVENTORY_DEVICES } from '@/walkthrough/demoTourData'
|
||||
import { useStatusPolling } from '@/hooks/useStatusPolling'
|
||||
import type { NodeData, EdgeData, CustomStyleDef, FloorMapConfig, NodeType } from '@/types'
|
||||
import { bootstrapAuth } from '@/auth/bootstrap'
|
||||
import { RackCanvas } from '@/rack/components/RackCanvas'
|
||||
import { RackCablePanel } from '@/rack/components/RackCablePanel'
|
||||
import { useRackStore } from '@/rack/store'
|
||||
import type { NodeData, EdgeData, CustomStyleDef, DesignType, FloorMapConfig, NodeType } from '@/types'
|
||||
import type { ZigbeeNode, ZigbeeEdge } from '@/components/zigbee/types'
|
||||
import type { ZwaveNode, ZwaveEdge } from '@/components/zwave/types'
|
||||
import type { ProxmoxNode, ProxmoxEdge } from '@/components/proxmox/types'
|
||||
@@ -53,26 +64,66 @@ import { buildProxmoxClusterEdges } from '@/components/proxmox/clusterEdges'
|
||||
const STANDALONE = import.meta.env.VITE_STANDALONE === 'true'
|
||||
|
||||
export default function App() {
|
||||
const { loadCanvas, markSaved, markUnsaved, selectedNodeId, selectedNodeIds, addNode, updateNode, deleteNode, onConnect, updateEdge, deleteEdge, setProxmoxContainerMode, setNodeZIndex, editingGroupRectId, setEditingGroupRectId, editingTextId, setEditingTextId, nodes, edges, snapshotHistory, undo, redo, addToGroup, addToContainer, floorMap, setFloorMap } = useCanvasStore()
|
||||
const { loadCanvas, applyLayout, markSaved, markUnsaved, hasUnsavedChanges, editSeq, selectedNodeId, selectedNodeIds, addNode, updateNode, deleteNode, onConnect, updateEdge, deleteEdge, setProxmoxContainerMode, setNodeZIndex, editingGroupRectId, setEditingGroupRectId, editingTextId, setEditingTextId, nodes, edges, snapshotHistory, undo, redo, addToGroup, addToContainer, addToZone, floorMap, setFloorMap } = useCanvasStore()
|
||||
const canvasRef = useRef<HTMLDivElement>(null)
|
||||
const { isAuthenticated } = useAuthStore()
|
||||
const { isAuthenticated, isInitialized } = useAuthStore()
|
||||
const authBootstrapStarted = useRef(false)
|
||||
const { activeTheme, setTheme, customStyle, setCustomStyle } = useThemeStore()
|
||||
const { activeDesignId, setDesigns, setActiveDesign } = useDesignStore()
|
||||
const { activeDesignId, activeDesignType, setDesigns, setActiveDesign } = useDesignStore()
|
||||
const isRackDesign = activeDesignType === 'rack'
|
||||
const rackDirty = useRackStore((s) => s.hasUnsavedChanges)
|
||||
const rackEditSeq = useRackStore((s) => s.editSeq)
|
||||
|
||||
/** Kind of a design by id, read straight from the store (no stale closure). */
|
||||
const designTypeOf = useCallback(
|
||||
(id: string | null | undefined): DesignType =>
|
||||
useDesignStore.getState().designs.find((d) => d.id === id)?.design_type ?? 'network',
|
||||
[],
|
||||
)
|
||||
|
||||
useStatusPolling()
|
||||
|
||||
useEffect(() => {
|
||||
if (STANDALONE || authBootstrapStarted.current) return
|
||||
authBootstrapStarted.current = true
|
||||
void bootstrapAuth()
|
||||
}, [])
|
||||
|
||||
const [autosave, setAutosave] = useState<AutosaveSettings>(readAutosaveSettings)
|
||||
useEffect(() => subscribeAutosaveSettings(setAutosave), [])
|
||||
|
||||
// Provenance: which design the in-memory canvas was loaded as. Differs from
|
||||
// activeDesignId (the selection) during a switch, so autosave gates on this to
|
||||
// avoid writing one design's canvas under another's id. Ref mirror for the
|
||||
// fire-time guard, which must read the live value without re-arming the timer.
|
||||
const [loadedDesignId, setLoadedDesignId] = useState<string | null>(null)
|
||||
const loadedDesignIdRef = useRef<string | null>(loadedDesignId)
|
||||
useEffect(() => { loadedDesignIdRef.current = loadedDesignId }, [loadedDesignId])
|
||||
|
||||
// True while the last canvas load failed (backend down/error). Drives the error
|
||||
// banner and keeps us from masking a real failure with the demo canvas.
|
||||
const [loadError, setLoadError] = useState(false)
|
||||
// True when the loaded canvas is the demo (a brand-new user). Reserved as the
|
||||
// entry signal for the upcoming Getting Started walkthrough.
|
||||
const [isNewUser, setIsNewUser] = useState(false)
|
||||
|
||||
// Getting Started tour: when true, the corresponding modal renders injected demo
|
||||
// data instead of hitting the backend.
|
||||
const [tourScanHistoryDemo, setTourScanHistoryDemo] = useState(false)
|
||||
const [tourInventoryDemo, setTourInventoryDemo] = useState(false)
|
||||
|
||||
const [themeModalOpen, setThemeModalOpen] = useState(false)
|
||||
const [styleEditorType, setStyleEditorType] = useState<NodeType | null>(null)
|
||||
const [searchOpen, setSearchOpen] = useState(false)
|
||||
const [scanHistoryOpen, setScanHistoryOpen] = useState(false)
|
||||
const [pendingModalOpen, setPendingModalOpen] = useState(false)
|
||||
const [pendingModalStatus, setPendingModalStatus] = useState<'pending' | 'hidden'>('pending')
|
||||
const [pendingHighlightId, setPendingHighlightId] = useState<string | undefined>(undefined)
|
||||
const openPendingModal = useCallback((deviceId?: string, status: 'pending' | 'hidden' = 'pending') => {
|
||||
setPendingHighlightId(undefined)
|
||||
setPendingModalStatus(status)
|
||||
setPendingModalOpen(true)
|
||||
if (deviceId) setTimeout(() => setPendingHighlightId(deviceId), 0)
|
||||
const [inventoryModalOpen, setInventoryModalOpen] = useState(false)
|
||||
const [inventoryModalStatus, setInventoryModalStatus] = useState<'pending' | 'hidden'>('pending')
|
||||
const [inventoryHighlightId, setInventoryHighlightId] = useState<string | undefined>(undefined)
|
||||
const openInventoryModal = useCallback((deviceId?: string, status: 'pending' | 'hidden' = 'pending') => {
|
||||
setInventoryHighlightId(undefined)
|
||||
setInventoryModalStatus(status)
|
||||
setInventoryModalOpen(true)
|
||||
if (deviceId) setTimeout(() => setInventoryHighlightId(deviceId), 0)
|
||||
}, [])
|
||||
const [shortcutsOpen, setShortcutsOpen] = useState(false)
|
||||
const [addNodeOpen, setAddNodeOpen] = useState(false)
|
||||
@@ -82,6 +133,7 @@ export default function App() {
|
||||
const [pendingConnection, setPendingConnection] = useState<Connection | null>(null)
|
||||
const [pendingGroupAdd, setPendingGroupAdd] = useState<{ nodeId: string; groupId: string } | null>(null)
|
||||
const [pendingContainerAdd, setPendingContainerAdd] = useState<{ nodeId: string; containerId: string } | null>(null)
|
||||
const [pendingZoneAdd, setPendingZoneAdd] = useState<{ nodeId: string; zoneId: string } | null>(null)
|
||||
const [editEdgeId, setEditEdgeId] = useState<string | null>(null)
|
||||
const [scanConfigOpen, setScanConfigOpen] = useState(false)
|
||||
const [settingsOpen, setSettingsOpen] = useState(false)
|
||||
@@ -93,84 +145,168 @@ export default function App() {
|
||||
// Declare handleSave before the Ctrl+S effect so it is in scope.
|
||||
// Returns true on success, false on failure — the design-switch effect relies
|
||||
// on this to avoid loading (and clobbering) the canvas when a save fails.
|
||||
const handleSave = useCallback(async (designIdOverride?: string): Promise<boolean> => {
|
||||
const handleSave = useCallback(async (designIdOverride?: string, options?: { silent?: boolean }): Promise<boolean> => {
|
||||
try {
|
||||
const saveDesignId = designIdOverride ?? activeDesignId
|
||||
// Rack canvases own their own state and persistence path.
|
||||
if (designTypeOf(saveDesignId) === 'rack') {
|
||||
// Named explicitly: the design-switch flow saves the *old* design, and
|
||||
// the store refuses rather than writing under whichever one it holds.
|
||||
const ok = await useRackStore.getState().save(saveDesignId)
|
||||
if (ok) {
|
||||
if (!options?.silent) toast.success('Rack canvas saved')
|
||||
} else {
|
||||
toast.error('Save failed')
|
||||
}
|
||||
return ok
|
||||
}
|
||||
if (STANDALONE) {
|
||||
if (!saveDesignId) return false
|
||||
// Floor plans are backend-only (upload/serve), so standalone never persists one.
|
||||
standaloneStorage.saveCanvas(saveDesignId, { nodes, edges, theme_id: activeTheme, custom_style: customStyle })
|
||||
markSaved()
|
||||
toast.success('Canvas saved')
|
||||
if (!options?.silent) toast.success('Canvas saved')
|
||||
return true
|
||||
}
|
||||
const nodesToSave = nodes.map(serializeNode)
|
||||
// Read the baseline at save time (not through the render-time destructure)
|
||||
// so a device edited in the inventory a moment ago is already rebased.
|
||||
const factsBaseline = useCanvasStore.getState().factsBaseline
|
||||
const nodesToSave = nodes.map((n) => serializeNode(n, factsBaseline[n.id]))
|
||||
const edgesToSave = edges.map(serializeEdge)
|
||||
const viewport: Record<string, unknown> = { theme_id: activeTheme }
|
||||
if (floorMap) viewport.floor_map = floorMap
|
||||
await canvasApi.save({ nodes: nodesToSave, edges: edgesToSave, viewport, custom_style: customStyle, design_id: saveDesignId })
|
||||
markSaved()
|
||||
toast.success('Canvas saved')
|
||||
if (!options?.silent) toast.success('Canvas saved')
|
||||
return true
|
||||
} catch {
|
||||
toast.error('Save failed')
|
||||
return false
|
||||
}
|
||||
}, [nodes, edges, markSaved, activeTheme, customStyle, activeDesignId, floorMap])
|
||||
}, [nodes, edges, markSaved, activeTheme, customStyle, activeDesignId, floorMap, designTypeOf])
|
||||
|
||||
// Keep a ref so the keydown handler always calls the latest version
|
||||
const handleSaveRef = useRef(handleSave)
|
||||
useEffect(() => { handleSaveRef.current = handleSave }, [handleSave])
|
||||
|
||||
// Debounced, opt-in autosave. Pins the active design when armed and re-checks
|
||||
// it at fire time so a mid-switch save can't clobber the wrong design.
|
||||
useAutosave({
|
||||
enabled: autosave.enabled,
|
||||
delaySeconds: autosave.delay,
|
||||
hasUnsavedChanges: isRackDesign ? rackDirty : hasUnsavedChanges,
|
||||
designId: loadedDesignId,
|
||||
// Debounce resets on each real user edit (editSeq), not on raw nodes/edges
|
||||
// identity — live status polling churns those arrays without a user edit and
|
||||
// would otherwise keep re-arming (and starving) the timer during monitoring.
|
||||
changeSignals: [isRackDesign ? rackEditSeq : editSeq],
|
||||
getLiveDesignId: () => loadedDesignIdRef.current,
|
||||
onSave: (designId) => { void handleSaveRef.current(designId, { silent: true }) },
|
||||
})
|
||||
|
||||
const loadCanvasFromApi = useCallback(async (designId?: string) => {
|
||||
let res
|
||||
try {
|
||||
const res = await canvasApi.load(designId)
|
||||
const { nodes: apiNodes, edges: apiEdges } = res.data
|
||||
if (apiNodes.length > 0) {
|
||||
const proxmoxContainerMap = new Map<string, boolean>(
|
||||
(apiNodes as ApiNode[])
|
||||
.filter((n) => n.type === 'group' || n.container_mode === true)
|
||||
.map((n) => [n.id, true])
|
||||
)
|
||||
const { nodes: rfNodes, edges: rfEdges } = migrateClusterHandles(
|
||||
(apiNodes as ApiNode[]).map((n) => deserializeApiNode(n, proxmoxContainerMap)),
|
||||
(apiEdges as ApiEdge[]).map(deserializeApiEdge),
|
||||
)
|
||||
const savedTheme = res.data.viewport?.theme_id
|
||||
if (savedTheme) setTheme(savedTheme)
|
||||
if (res.data.custom_style) setCustomStyle(res.data.custom_style as CustomStyleDef)
|
||||
const savedFloorMap = res.data.viewport?.floor_map as FloorMapConfig | undefined
|
||||
// Clear when the target design has no floor plan, so it doesn't bleed
|
||||
// across canvases when switching designs.
|
||||
setFloorMap(savedFloorMap ?? null)
|
||||
loadCanvas(rfNodes, rfEdges)
|
||||
} else {
|
||||
setFloorMap(null)
|
||||
loadCanvas(demoNodes, demoEdges)
|
||||
}
|
||||
res = await canvasApi.load(designId)
|
||||
} catch {
|
||||
// Backend down / errored. Surface it and STOP — never fall back to the demo
|
||||
// canvas, which would hide the real error and look like a fresh account.
|
||||
// Leave the on-screen canvas and provenance untouched so an autosave can't
|
||||
// clobber real data with an empty canvas.
|
||||
setLoadError(true)
|
||||
toast.error('Could not load canvas — backend not responding')
|
||||
return
|
||||
}
|
||||
const { nodes: apiNodes, edges: apiEdges } = res.data
|
||||
const mode = decideCanvasLoad(apiNodes.length > 0, res.data.initialized === true)
|
||||
if (mode === 'real') {
|
||||
const proxmoxContainerMap = new Map<string, boolean>(
|
||||
(apiNodes as ApiNode[])
|
||||
.filter((n) => n.type === 'group' || n.container_mode === true)
|
||||
.map((n) => [n.id, true])
|
||||
)
|
||||
const zoneIds = new Set(
|
||||
(apiNodes as ApiNode[]).filter((n) => n.type === 'groupRect').map((n) => n.id)
|
||||
)
|
||||
const { nodes: rfNodes, edges: rfEdges } = migrateClusterHandles(
|
||||
(apiNodes as ApiNode[]).map((n) => deserializeApiNode(n, proxmoxContainerMap, zoneIds)),
|
||||
(apiEdges as ApiEdge[]).map(deserializeApiEdge),
|
||||
)
|
||||
const savedTheme = res.data.viewport?.theme_id
|
||||
if (savedTheme) setTheme(savedTheme)
|
||||
if (res.data.custom_style) setCustomStyle(res.data.custom_style as CustomStyleDef)
|
||||
const savedFloorMap = res.data.viewport?.floor_map as FloorMapConfig | undefined
|
||||
// Clear when the target design has no floor plan, so it doesn't bleed
|
||||
// across canvases when switching designs.
|
||||
setFloorMap(savedFloorMap ?? null)
|
||||
loadCanvas(rfNodes, rfEdges)
|
||||
} else if (mode === 'empty') {
|
||||
// Initialized but no nodes: the user cleared this canvas on purpose — respect
|
||||
// it and keep it empty instead of re-seeding the demo.
|
||||
const savedTheme = res.data.viewport?.theme_id
|
||||
if (savedTheme) setTheme(savedTheme)
|
||||
if (res.data.custom_style) setCustomStyle(res.data.custom_style as CustomStyleDef)
|
||||
setFloorMap(null)
|
||||
loadCanvas([], [])
|
||||
} else {
|
||||
// Brand-new, never-saved canvas: seed the demo.
|
||||
setFloorMap(null)
|
||||
loadCanvas(demoNodes, demoEdges)
|
||||
}
|
||||
setLoadError(false)
|
||||
setIsNewUser(isNewUserCanvas(mode))
|
||||
// Record provenance so autosave writes back under the design just loaded.
|
||||
setLoadedDesignId(designId ?? null)
|
||||
}, [loadCanvas, setTheme, setCustomStyle, setFloorMap])
|
||||
|
||||
// Standalone counterpart of loadCanvasFromApi — reads a design's canvas from
|
||||
// localStorage, falling back to the demo canvas when it has never been saved.
|
||||
const loadStandaloneCanvas = useCallback((designId: string) => {
|
||||
const saved = standaloneStorage.loadCanvas(designId)
|
||||
if (saved && saved.nodes.length > 0) {
|
||||
// A stored entry (even with zero nodes) means the user has saved this canvas,
|
||||
// so treat it as initialized and don't re-seed the demo on top of a canvas
|
||||
// they deliberately cleared.
|
||||
const mode = decideCanvasLoad((saved?.nodes.length ?? 0) > 0, saved !== null)
|
||||
if (mode === 'real' && saved) {
|
||||
if (saved.theme_id) setTheme(saved.theme_id)
|
||||
if (saved.custom_style) setCustomStyle(saved.custom_style)
|
||||
// Floor plans are backend-only; keep the store clear in standalone mode.
|
||||
setFloorMap(null)
|
||||
const migrated = migrateClusterHandles(saved.nodes, saved.edges)
|
||||
loadCanvas(migrated.nodes, migrated.edges)
|
||||
} else if (mode === 'empty' && saved) {
|
||||
if (saved.theme_id) setTheme(saved.theme_id)
|
||||
if (saved.custom_style) setCustomStyle(saved.custom_style)
|
||||
setFloorMap(null)
|
||||
loadCanvas([], [])
|
||||
} else {
|
||||
setFloorMap(null)
|
||||
loadCanvas(demoNodes, demoEdges)
|
||||
}
|
||||
setLoadError(false)
|
||||
setIsNewUser(isNewUserCanvas(mode))
|
||||
// Record provenance so autosave writes back under the design just loaded.
|
||||
setLoadedDesignId(designId)
|
||||
}, [loadCanvas, setTheme, setCustomStyle, setFloorMap])
|
||||
|
||||
/**
|
||||
* Load whichever canvas the design holds. Rack designs bypass the node/edge
|
||||
* canvas entirely — different store, different endpoints.
|
||||
*/
|
||||
const loadAnyDesign = useCallback(async (designId: string) => {
|
||||
if (designTypeOf(designId) !== 'rack') {
|
||||
if (STANDALONE) loadStandaloneCanvas(designId)
|
||||
else await loadCanvasFromApi(designId)
|
||||
return
|
||||
}
|
||||
// The rack store owns the fetch; App only records provenance afterwards, so
|
||||
// none of these run synchronously inside the calling effect.
|
||||
await useRackStore.getState().loadDesign(designId)
|
||||
setIsNewUser(false)
|
||||
setLoadError(false)
|
||||
setLoadedDesignId(designId)
|
||||
}, [designTypeOf, loadStandaloneCanvas, loadCanvasFromApi])
|
||||
|
||||
const loadDesignsAndCanvas = useCallback(async () => {
|
||||
// Prefer a design id explicitly requested via the URL (?design=<id>), so a
|
||||
// refresh or shared link opens that design. Ignore it when it doesn't match
|
||||
@@ -183,7 +319,7 @@ export default function App() {
|
||||
const targetId = fromUrl ?? activeDesignId ?? designs[0]?.id
|
||||
if (targetId) {
|
||||
setActiveDesign(targetId)
|
||||
loadStandaloneCanvas(targetId)
|
||||
void loadAnyDesign(targetId)
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -195,19 +331,76 @@ export default function App() {
|
||||
const targetId = fromUrl ?? activeDesignId ?? loadedDesigns[0]?.id
|
||||
if (targetId) {
|
||||
setActiveDesign(targetId)
|
||||
await loadCanvasFromApi(targetId)
|
||||
await loadAnyDesign(targetId)
|
||||
}
|
||||
} catch {
|
||||
// If API fails (e.g. fresh DB with no designs), fall back to demo data
|
||||
loadCanvas(demoNodes, demoEdges)
|
||||
// Backend unreachable/errored — surface it. Do NOT seed the demo: that would
|
||||
// hide a real outage behind a fake "new account" canvas.
|
||||
setLoadError(true)
|
||||
toast.error('Could not reach backend — check the server and retry')
|
||||
}
|
||||
}, [setDesigns, setActiveDesign, loadCanvasFromApi, loadStandaloneCanvas, activeDesignId, loadCanvas])
|
||||
}, [setDesigns, setActiveDesign, loadAnyDesign, activeDesignId])
|
||||
|
||||
// Keep a ref so the auth effect can call the latest loader without listing it
|
||||
// as a dependency (which would re-fire on every design switch).
|
||||
const loadDesignsAndCanvasRef = useRef(loadDesignsAndCanvas)
|
||||
useEffect(() => { loadDesignsAndCanvasRef.current = loadDesignsAndCanvas }, [loadDesignsAndCanvas])
|
||||
|
||||
// Retry a failed load from the error banner.
|
||||
const handleRetryLoad = useCallback(() => {
|
||||
setLoadError(false)
|
||||
void loadDesignsAndCanvasRef.current()
|
||||
}, [])
|
||||
|
||||
// Bridge the Getting Started tour steps to the App's modal controls. The overlay
|
||||
// calls closeAll() before each step, then the step's action to open the target.
|
||||
const walkthroughActions = useMemo<WalkthroughActionApi>(() => ({
|
||||
closeAll: () => {
|
||||
setScanConfigOpen(false)
|
||||
setScanHistoryOpen(false)
|
||||
setTourScanHistoryDemo(false)
|
||||
setInventoryModalOpen(false)
|
||||
setTourInventoryDemo(false)
|
||||
setEditNodeId(null)
|
||||
setThemeModalOpen(false)
|
||||
setZigbeeImportOpen(false)
|
||||
// Clear any tour-driven multi-selection so the DetailPanel closes.
|
||||
useCanvasStore.setState((s) => ({
|
||||
nodes: s.nodes.map((n) => (n.selected ? { ...n, selected: false } : n)),
|
||||
selectedNodeIds: [],
|
||||
selectedNodeId: null,
|
||||
}))
|
||||
},
|
||||
openScanConfig: () => setScanConfigOpen(true),
|
||||
openScanHistoryDemo: () => {
|
||||
setTourScanHistoryDemo(true)
|
||||
setScanHistoryOpen(true)
|
||||
},
|
||||
openInventoryDemo: () => {
|
||||
setTourInventoryDemo(true)
|
||||
openInventoryModal(undefined, 'pending')
|
||||
},
|
||||
editFirstNode: () => {
|
||||
const first = useCanvasStore.getState().nodes.find((n) => n.data.type !== 'groupRect' && n.data.type !== 'text')
|
||||
if (first) setEditNodeId(first.id)
|
||||
},
|
||||
selectTwoNodes: () => {
|
||||
const ids = useCanvasStore.getState().nodes
|
||||
.filter((n) => n.data.type !== 'groupRect' && n.data.type !== 'text')
|
||||
.slice(0, 2)
|
||||
.map((n) => n.id)
|
||||
if (ids.length < 2) return
|
||||
const set = new Set(ids)
|
||||
useCanvasStore.setState((s) => ({
|
||||
nodes: s.nodes.map((n) => ({ ...n, selected: set.has(n.id) })),
|
||||
selectedNodeIds: ids,
|
||||
selectedNodeId: null,
|
||||
}))
|
||||
},
|
||||
openStyle: () => setThemeModalOpen(true),
|
||||
openZigbeeImport: () => setZigbeeImportOpen(true),
|
||||
}), [openInventoryModal])
|
||||
|
||||
// Load designs + canvas on auth (or immediately in standalone mode, which has
|
||||
// no auth gate).
|
||||
useEffect(() => {
|
||||
@@ -233,7 +426,7 @@ export default function App() {
|
||||
}
|
||||
// Standalone has no auth gate; backed mode requires authentication.
|
||||
const ready = STANDALONE || isAuthenticated
|
||||
const loadForDesign = STANDALONE ? loadStandaloneCanvas : loadCanvasFromApi
|
||||
const loadForDesign = loadAnyDesign
|
||||
if (ready && activeDesignId && initialLoadDone.current) {
|
||||
const oldId = prevDesignRef.current
|
||||
// If the previous design was deleted (no longer in the list), don't try to
|
||||
@@ -247,7 +440,7 @@ export default function App() {
|
||||
const targetId = activeDesignId
|
||||
handleSave(oldId).then((ok) => {
|
||||
if (ok) {
|
||||
loadForDesign(targetId)
|
||||
void loadForDesign(targetId)
|
||||
} else {
|
||||
// Save failed: don't load the new design — that would overwrite the
|
||||
// unsaved in-memory canvas. Revert the selection back to the old
|
||||
@@ -258,7 +451,12 @@ export default function App() {
|
||||
}
|
||||
})
|
||||
} else {
|
||||
loadForDesign(activeDesignId)
|
||||
// Loading a design is exactly the "synchronize with an external system"
|
||||
// case: it fetches and then publishes the result into React state. The
|
||||
// rule can't see through the loader, so silence it here rather than
|
||||
// deferring the fetch by a tick.
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||
void loadForDesign(activeDesignId)
|
||||
}
|
||||
}
|
||||
if (activeDesignId) {
|
||||
@@ -307,7 +505,9 @@ export default function App() {
|
||||
// parent the LXC/VM stays a free node (linked by a virtual edge) — setting
|
||||
// extent:'parent' on a non-container would trap it inside the parent's tiny
|
||||
// bounding box with no way to drag it out (issue #205 follow-up).
|
||||
const nestInParent = !!parentNode?.data.container_mode
|
||||
// A visual group nests too, so it seeds its position the same way — mirrors
|
||||
// the condition in the store's addNode, which is the authority here.
|
||||
const nestInParent = !!parentNode?.data.container_mode || parentNode?.data.type === 'group'
|
||||
// Seed an ABSOLUTE position near the container's top-left; addNode converts
|
||||
// it to container-relative. addNode is the single authority for parentId /
|
||||
// extent, so we don't set them here.
|
||||
@@ -459,8 +659,13 @@ export default function App() {
|
||||
snapshotHistory()
|
||||
const existingNode = nodes.find((n) => n.id === editNodeId)
|
||||
updateNode(editNodeId, data)
|
||||
// If container_mode changed, apply structural changes (children parentId, node dimensions)
|
||||
if (typeof data.container_mode === 'boolean') {
|
||||
// Only run the structural container transition when container_mode ACTUALLY
|
||||
// changed. The modal always includes container_mode in its payload, so firing
|
||||
// on presence alone re-ran the absolute<->relative child-position conversion on
|
||||
// every edit (e.g. an icon change), corrupting nested child positions (they pile
|
||||
// up in a corner). Gate on a real toggle instead.
|
||||
const prevContainerMode = !!existingNode?.data.container_mode
|
||||
if (typeof data.container_mode === 'boolean' && data.container_mode !== prevContainerMode) {
|
||||
setProxmoxContainerMode(editNodeId, data.container_mode)
|
||||
}
|
||||
// Sync virtual edge when parent_id changes on an LXC/VM node
|
||||
@@ -493,9 +698,11 @@ export default function App() {
|
||||
|
||||
const handleAutoLayout = useCallback(() => {
|
||||
const laid = applyDagreLayout(nodes, edges)
|
||||
loadCanvas(laid, edges)
|
||||
// applyLayout keeps undo history so the user can revert an accidental
|
||||
// Auto Layout (#280); loadCanvas would wipe it.
|
||||
applyLayout(laid, edges)
|
||||
toast.success('Canvas auto-arranged')
|
||||
}, [nodes, edges, loadCanvas])
|
||||
}, [nodes, edges, applyLayout])
|
||||
|
||||
const handleExportMd = useCallback(async () => {
|
||||
const md = generateMarkdownTable(nodes)
|
||||
@@ -517,14 +724,14 @@ export default function App() {
|
||||
const handleImportYaml = useCallback((content: string) => {
|
||||
try {
|
||||
const { nodes: merged, edges: mergedEdges, imported } = parseYamlToCanvas(content, nodes, edges)
|
||||
snapshotHistory()
|
||||
loadCanvas(merged, mergedEdges)
|
||||
markUnsaved()
|
||||
// applyLayout keeps undo history so an import can be reverted; loadCanvas
|
||||
// would wipe it (#280).
|
||||
applyLayout(merged, mergedEdges)
|
||||
toast.success(`Imported ${imported} node${imported !== 1 ? 's' : ''}`)
|
||||
} catch (err) {
|
||||
toast.error(`Import failed: ${err instanceof Error ? err.message : String(err)}`)
|
||||
}
|
||||
}, [nodes, edges, snapshotHistory, loadCanvas, markUnsaved])
|
||||
}, [nodes, edges, applyLayout])
|
||||
|
||||
// Open the read-only live view of the currently active design in a new tab.
|
||||
// Standalone has no backend/key — it reads localStorage, so just open /view.
|
||||
@@ -780,12 +987,22 @@ export default function App() {
|
||||
const editNode = editNodeId ? nodes.find((n) => n.id === editNodeId) : null
|
||||
const editEdge = editEdgeId ? edges.find((e) => e.id === editEdgeId) : null
|
||||
|
||||
if (!STANDALONE && !isInitialized) {
|
||||
return (
|
||||
<div className="flex h-screen w-screen items-center justify-center bg-[#0d1117] text-sm text-muted-foreground">
|
||||
Loading authentication…
|
||||
</div>
|
||||
)
|
||||
}
|
||||
if (!STANDALONE && !isAuthenticated) return <LoginPage />
|
||||
|
||||
return (
|
||||
<WalkthroughActionsProvider value={walkthroughActions}>
|
||||
<TooltipProvider>
|
||||
<ReactFlowProvider>
|
||||
<div className="flex h-screen w-screen overflow-hidden bg-[#0d1117]">
|
||||
{/* data-new-user marks a first-time (demo) canvas — the hook the upcoming
|
||||
Getting Started walkthrough keys off. */}
|
||||
<div className="flex h-screen w-screen overflow-hidden bg-[#0d1117]" data-new-user={isNewUser}>
|
||||
<Sidebar
|
||||
onAddNode={() => setAddNodeOpen(true)}
|
||||
onAddGroupRect={() => setAddGroupRectOpen(true)}
|
||||
@@ -797,9 +1014,24 @@ export default function App() {
|
||||
onSave={handleSave}
|
||||
onOpenSettings={() => setSettingsOpen(true)}
|
||||
onOpenHistory={() => setScanHistoryOpen(true)}
|
||||
onOpenPending={openPendingModal}
|
||||
onOpenInventory={openInventoryModal}
|
||||
/>
|
||||
<div className="flex flex-col flex-1 min-w-0">
|
||||
{loadError && (
|
||||
<div
|
||||
role="alert"
|
||||
className="flex items-center justify-between gap-3 bg-[#3d1418] border-b border-[#f85149] px-4 py-2 text-sm text-[#ffa198]"
|
||||
>
|
||||
<span>Backend not responding — the canvas could not be loaded.</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleRetryLoad}
|
||||
className="rounded border border-[#f85149] px-2 py-0.5 text-[#ffa198] hover:bg-[#f85149]/20"
|
||||
>
|
||||
Retry
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
<Toolbar
|
||||
onSave={handleSave}
|
||||
onAutoLayout={handleAutoLayout}
|
||||
@@ -815,17 +1047,34 @@ export default function App() {
|
||||
/>
|
||||
<div className="flex flex-1 min-h-0">
|
||||
<div ref={canvasRef} className="flex-1 min-w-0 h-full">
|
||||
<CanvasContainer
|
||||
onConnect={handleEdgeConnect}
|
||||
onEdgeDoubleClick={handleEdgeDoubleClick}
|
||||
onNodeDoubleClick={handleNodeDoubleClick}
|
||||
onNodeDragStart={snapshotHistory}
|
||||
onRequestAddToGroup={setPendingGroupAdd}
|
||||
onRequestAddToContainer={setPendingContainerAdd}
|
||||
onOpenPending={(deviceId) => openPendingModal(deviceId)}
|
||||
/>
|
||||
{isRackDesign ? (
|
||||
<RackCanvas />
|
||||
) : (
|
||||
<CanvasContainer
|
||||
onConnect={handleEdgeConnect}
|
||||
onEdgeDoubleClick={handleEdgeDoubleClick}
|
||||
onNodeDoubleClick={handleNodeDoubleClick}
|
||||
onNodeDragStart={snapshotHistory}
|
||||
onRequestAddToGroup={setPendingGroupAdd}
|
||||
onRequestAddToContainer={setPendingContainerAdd}
|
||||
onRequestAddToZone={setPendingZoneAdd}
|
||||
onOpenInventory={(deviceId) => openInventoryModal(deviceId)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
{(selectedNodeId || selectedNodeIds.length > 1) && <DetailPanel onEdit={handleEditNode} />}
|
||||
{/* Rack designs keep the full width for mounted gear — a mount is
|
||||
edited in its own modal — but a selected cable has no plate to
|
||||
double-click, so it gets the rail. */}
|
||||
{isRackDesign
|
||||
? <RackCablePanel />
|
||||
: (selectedNodeId || selectedNodeIds.length > 1) && (
|
||||
<DetailPanel
|
||||
onEdit={handleEditNode}
|
||||
// Standalone has no Device Inventory to open (ADR-001 style
|
||||
// gate: the whole scan surface is backend-only).
|
||||
onOpenInventory={STANDALONE ? undefined : (deviceId) => openInventoryModal(deviceId)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -903,7 +1152,7 @@ export default function App() {
|
||||
open={zigbeeImportOpen}
|
||||
onClose={() => setZigbeeImportOpen(false)}
|
||||
onAddToCanvas={handleZigbeeAddToCanvas}
|
||||
onPendingImported={() => {
|
||||
onInventoryImported={() => {
|
||||
toast.success('Zigbee import started — check Scan History for results')
|
||||
}}
|
||||
/>
|
||||
@@ -914,7 +1163,7 @@ export default function App() {
|
||||
open={zwaveImportOpen}
|
||||
onClose={() => setZwaveImportOpen(false)}
|
||||
onAddToCanvas={handleZwaveAddToCanvas}
|
||||
onPendingImported={() => {
|
||||
onInventoryImported={() => {
|
||||
toast.success('Z-Wave import started — check Scan History for results')
|
||||
}}
|
||||
/>
|
||||
@@ -925,7 +1174,7 @@ export default function App() {
|
||||
open={proxmoxImportOpen}
|
||||
onClose={() => setProxmoxImportOpen(false)}
|
||||
onAddToCanvas={handleProxmoxAddToCanvas}
|
||||
onPendingImported={() => {
|
||||
onInventoryImported={() => {
|
||||
toast.success('Proxmox import started — check Scan History for results')
|
||||
}}
|
||||
/>
|
||||
@@ -935,6 +1184,7 @@ export default function App() {
|
||||
<ScanHistoryModal
|
||||
open={scanHistoryOpen}
|
||||
onClose={() => setScanHistoryOpen(false)}
|
||||
demoRuns={tourScanHistoryDemo ? DEMO_SCAN_RUNS : undefined}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -1023,7 +1273,7 @@ export default function App() {
|
||||
<SearchModal
|
||||
open={searchOpen}
|
||||
onClose={() => setSearchOpen(false)}
|
||||
onOpenPending={(deviceId) => openPendingModal(deviceId)}
|
||||
onOpenInventory={(deviceId) => openInventoryModal(deviceId)}
|
||||
/>
|
||||
<ShortcutsModal open={shortcutsOpen} onClose={() => setShortcutsOpen(false)} />
|
||||
|
||||
@@ -1050,15 +1300,28 @@ export default function App() {
|
||||
onCancel={() => setPendingContainerAdd(null)}
|
||||
/>
|
||||
|
||||
<ConfirmAddToGroupModal
|
||||
open={!!pendingZoneAdd}
|
||||
variant="zone"
|
||||
nodeLabel={pendingZoneAdd ? (nodes.find((n) => n.id === pendingZoneAdd.nodeId)?.data.label ?? '') : ''}
|
||||
targetLabel={pendingZoneAdd ? (nodes.find((n) => n.id === pendingZoneAdd.zoneId)?.data.label ?? '') : ''}
|
||||
onConfirm={() => {
|
||||
if (pendingZoneAdd) addToZone(pendingZoneAdd.zoneId, pendingZoneAdd.nodeId)
|
||||
setPendingZoneAdd(null)
|
||||
}}
|
||||
onCancel={() => setPendingZoneAdd(null)}
|
||||
/>
|
||||
|
||||
{/* Mounted in standalone too: status-check settings are hidden inside,
|
||||
but canvas prefs (snap, hide-IP) still apply. */}
|
||||
<SettingsModal open={settingsOpen} onClose={() => setSettingsOpen(false)} />
|
||||
|
||||
<PendingDevicesModal
|
||||
open={pendingModalOpen}
|
||||
onClose={() => setPendingModalOpen(false)}
|
||||
highlightId={pendingHighlightId}
|
||||
initialStatus={pendingModalStatus}
|
||||
<DeviceInventoryModal
|
||||
open={inventoryModalOpen}
|
||||
onClose={() => setInventoryModalOpen(false)}
|
||||
highlightId={inventoryHighlightId}
|
||||
initialStatus={inventoryModalStatus}
|
||||
demoDevices={tourInventoryDemo ? DEMO_INVENTORY_DEVICES : undefined}
|
||||
/>
|
||||
|
||||
<ExportModal
|
||||
@@ -1068,7 +1331,10 @@ export default function App() {
|
||||
/>
|
||||
|
||||
<Toaster theme="dark" position="bottom-right" />
|
||||
<WalkthroughInvite />
|
||||
<WalkthroughOverlay />
|
||||
</ReactFlowProvider>
|
||||
</TooltipProvider>
|
||||
</WalkthroughActionsProvider>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ type Interceptor<T> = {
|
||||
}
|
||||
|
||||
interface MockInstance {
|
||||
defaults: { baseURL?: string }
|
||||
defaults: { baseURL?: string; withCredentials?: boolean }
|
||||
interceptors: {
|
||||
request: { use: (f: Interceptor<unknown>['fulfilled'], r?: Interceptor<unknown>['rejected']) => void }
|
||||
response: { use: (f: Interceptor<unknown>['fulfilled'], r?: Interceptor<unknown>['rejected']) => void }
|
||||
@@ -25,9 +25,9 @@ const instances = hoisted.instances as MockInstance[]
|
||||
vi.mock('axios', () => {
|
||||
return {
|
||||
default: {
|
||||
create: (cfg: { baseURL?: string }) => {
|
||||
create: (cfg: { baseURL?: string; withCredentials?: boolean }) => {
|
||||
const inst: MockInstance = {
|
||||
defaults: { baseURL: cfg?.baseURL },
|
||||
defaults: { baseURL: cfg?.baseURL, withCredentials: cfg?.withCredentials },
|
||||
interceptors: {
|
||||
request: { use: (f: unknown, r?: unknown) => { inst.__req = { fulfilled: f as never, rejected: r as never } } },
|
||||
response: { use: (f: unknown, r?: unknown) => { inst.__res = { fulfilled: f as never, rejected: r as never } } },
|
||||
@@ -54,7 +54,7 @@ describe('api/client', () => {
|
||||
const [api, publicApi] = instances
|
||||
|
||||
beforeEach(() => {
|
||||
useAuthStore.setState({ token: null, isAuthenticated: false })
|
||||
useAuthStore.setState({ token: null, csrfToken: null, isAuthenticated: false })
|
||||
api.get.mockClear()
|
||||
api.post.mockClear()
|
||||
api.patch.mockClear()
|
||||
@@ -66,6 +66,7 @@ describe('api/client', () => {
|
||||
it('creates two axios instances with /api/v1 baseURL', () => {
|
||||
expect(instances).toHaveLength(2)
|
||||
expect(api.defaults.baseURL).toBe('/api/v1')
|
||||
expect(api.defaults.withCredentials).toBe(true)
|
||||
expect(publicApi.defaults.baseURL).toBe('/api/v1')
|
||||
})
|
||||
|
||||
@@ -86,6 +87,18 @@ describe('api/client', () => {
|
||||
expect((out as typeof cfg).headers.Authorization).toBeUndefined()
|
||||
})
|
||||
|
||||
it('adds the in-memory OIDC CSRF token only to unsafe requests', () => {
|
||||
useAuthStore.setState({ csrfToken: 'csrf-123' })
|
||||
const post = { method: 'post', headers: {} as Record<string, string> }
|
||||
const get = { method: 'get', headers: {} as Record<string, string> }
|
||||
|
||||
api.__req.fulfilled!(post)
|
||||
api.__req.fulfilled!(get)
|
||||
|
||||
expect(post.headers['X-Homelable-CSRF']).toBe('csrf-123')
|
||||
expect(get.headers['X-Homelable-CSRF']).toBeUndefined()
|
||||
})
|
||||
|
||||
it('response interceptor passes through 2xx responses', () => {
|
||||
const r = { status: 200, data: { ok: true } }
|
||||
expect(api.__res.fulfilled!(r)).toBe(r)
|
||||
@@ -125,6 +138,15 @@ describe('api/client', () => {
|
||||
expect(api.post).toHaveBeenCalledWith('/auth/login', { username: 'u', password: 'p' })
|
||||
})
|
||||
|
||||
it('authApi discovers auth publicly and manages the current session', () => {
|
||||
mod.authApi.config()
|
||||
expect(publicApi.get).toHaveBeenCalledWith('/auth/config')
|
||||
mod.authApi.me()
|
||||
expect(api.get).toHaveBeenCalledWith('/auth/me')
|
||||
mod.authApi.logout()
|
||||
expect(api.post).toHaveBeenCalledWith('/auth/logout')
|
||||
})
|
||||
|
||||
it('canvasApi.load GETs /canvas', () => {
|
||||
mod.canvasApi.load()
|
||||
expect(api.get).toHaveBeenCalledWith('/canvas', expect.objectContaining({}))
|
||||
|
||||
@@ -1,16 +1,23 @@
|
||||
import axios from 'axios'
|
||||
import { useAuthStore } from '@/stores/authStore'
|
||||
import type { AuthMode, AuthUser } from '@/stores/authStore'
|
||||
import type { InventoryEntry } from '@/types'
|
||||
|
||||
export const api = axios.create({
|
||||
baseURL: '/api/v1',
|
||||
withCredentials: true,
|
||||
})
|
||||
|
||||
// Unauthenticated axios instance — no JWT, no 401 redirect (used for public endpoints)
|
||||
const publicApi = axios.create({ baseURL: '/api/v1' })
|
||||
|
||||
api.interceptors.request.use((config) => {
|
||||
const token = useAuthStore.getState().token
|
||||
const { token, csrfToken } = useAuthStore.getState()
|
||||
if (token) config.headers.Authorization = `Bearer ${token}`
|
||||
const method = config.method?.toUpperCase() ?? 'GET'
|
||||
if (csrfToken && !['GET', 'HEAD', 'OPTIONS'].includes(method)) {
|
||||
config.headers['X-Homelable-CSRF'] = csrfToken
|
||||
}
|
||||
return config
|
||||
})
|
||||
|
||||
@@ -23,8 +30,11 @@ api.interceptors.response.use(
|
||||
)
|
||||
|
||||
export const authApi = {
|
||||
config: () => publicApi.get<{ mode: AuthMode; oidc_login_url: string | null }>('/auth/config'),
|
||||
login: (username: string, password: string) =>
|
||||
api.post<{ access_token: string }>('/auth/login', { username, password }),
|
||||
me: () => api.get<AuthUser>('/auth/me'),
|
||||
logout: () => api.post('/auth/logout'),
|
||||
}
|
||||
|
||||
export const canvasApi = {
|
||||
@@ -52,7 +62,29 @@ export const mediaApi = {
|
||||
delete: (filename: string) => api.delete(`/media/${filename}`),
|
||||
}
|
||||
|
||||
/**
|
||||
* A canvas node as `GET /nodes` reports it — the fields a reader needs to tell
|
||||
* two hosts apart. The canvas itself keeps its own richer React Flow shape; this
|
||||
* is only for pickers and lookups.
|
||||
*/
|
||||
export interface ApiCanvasNode {
|
||||
id: string
|
||||
design_id: string | null
|
||||
label: string
|
||||
type: string
|
||||
ip: string | null
|
||||
mac: string | null
|
||||
hostname: string | null
|
||||
os: string | null
|
||||
status: string
|
||||
check_method: string | null
|
||||
last_seen: string | null
|
||||
}
|
||||
|
||||
export const nodesApi = {
|
||||
/** Every node, across every design. `label` filters case-insensitively. */
|
||||
list: (label?: string) =>
|
||||
api.get<ApiCanvasNode[]>('/nodes', { params: label ? { label } : {} }),
|
||||
create: (data: object) => api.post('/nodes', data),
|
||||
update: (id: string, data: object) => api.patch(`/nodes/${id}`, data),
|
||||
delete: (id: string) => api.delete(`/nodes/${id}`),
|
||||
@@ -97,12 +129,40 @@ export interface DuplicateNodeConflict {
|
||||
value: string
|
||||
}
|
||||
|
||||
/**
|
||||
* The Device Inventory rides the scan routes.
|
||||
*
|
||||
* `/scan/pending/*` is what the table was called when it was a queue of finds
|
||||
* awaiting approval; the rows are the Device Inventory now, but the paths are a
|
||||
* published contract the MCP server also calls, so they stay. The method names
|
||||
* follow the paths rather than the concept, so a route is easy to find.
|
||||
*/
|
||||
export const scanApi = {
|
||||
trigger: (deepScan?: Partial<DeepScanConfig>) => api.post('/scan/trigger', deepScan ?? {}),
|
||||
pending: () => api.get('/scan/pending'),
|
||||
/** Add an inventory entry by hand, for hardware no scan can discover. */
|
||||
createPending: (data: {
|
||||
hostname: string
|
||||
ip?: string | null
|
||||
mac?: string | null
|
||||
suggested_type?: string | null
|
||||
model?: string | null
|
||||
vendor?: string | null
|
||||
/** "manual" (default) or "rack" for gear created from a rack canvas. */
|
||||
discovery_source?: 'manual' | 'rack'
|
||||
}) => api.post<{ id: string; hostname: string | null }>('/scan/pending', data),
|
||||
/**
|
||||
* Edit an inventory row. Partial: only the keys sent are applied, so a caller
|
||||
* touching one field never clears the rest. Lifecycle (`status`) and discovery
|
||||
* bookkeeping are not editable — approve/hide own those.
|
||||
*/
|
||||
updatePending: (id: string, data: Partial<Omit<InventoryEntry, 'id' | 'status' | 'discovered_at'>>) =>
|
||||
api.patch<InventoryEntry>(`/scan/pending/${id}`, data),
|
||||
hidden: () => api.get('/scan/hidden'),
|
||||
runs: () => api.get('/scan/runs'),
|
||||
clearPending: () => api.delete('/scan/pending'),
|
||||
/** Remove one inventory entry. 409 when a rack still mounts it. */
|
||||
deletePending: (id: string) => api.delete<{ deleted: boolean }>(`/scan/pending/${id}`),
|
||||
approve: (id: string, nodeData: object) =>
|
||||
api.post<{
|
||||
approved: boolean
|
||||
@@ -211,6 +271,17 @@ export const designsApi = {
|
||||
delete: (id: string) => api.delete(`/designs/${id}`),
|
||||
}
|
||||
|
||||
export const racksApi = {
|
||||
load: (designId: string) =>
|
||||
api.get<import('@/utils/rackSerializer').ApiRackState>('/racks', { params: { design_id: designId } }),
|
||||
save: (payload: import('@/utils/rackSerializer').RackSavePayload) =>
|
||||
api.post<{ saved: boolean }>('/racks/save', payload),
|
||||
inventory: (designId: string) =>
|
||||
api.get<{ items: import('@/utils/rackSerializer').ApiInventoryItem[] }>('/racks/inventory', {
|
||||
params: { design_id: designId },
|
||||
}),
|
||||
}
|
||||
|
||||
export interface ZigbeeConfigData {
|
||||
mqtt_host: string
|
||||
mqtt_port: number
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { useAuthStore } from '@/stores/authStore'
|
||||
|
||||
vi.mock('@/api/client', () => ({
|
||||
authApi: {
|
||||
config: vi.fn(),
|
||||
me: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
import { authApi } from '@/api/client'
|
||||
import { bootstrapAuth } from '../bootstrap'
|
||||
|
||||
describe('bootstrapAuth', () => {
|
||||
beforeEach(() => {
|
||||
sessionStorage.clear()
|
||||
useAuthStore.setState({
|
||||
token: null,
|
||||
isAuthenticated: false,
|
||||
isInitialized: false,
|
||||
authMode: null,
|
||||
authMethod: null,
|
||||
oidcLoginUrl: null,
|
||||
displayName: null,
|
||||
csrfToken: null,
|
||||
})
|
||||
vi.mocked(authApi.config).mockReset()
|
||||
vi.mocked(authApi.me).mockReset()
|
||||
})
|
||||
|
||||
it('restores an OIDC cookie session without storing an IdP token', async () => {
|
||||
vi.mocked(authApi.config).mockResolvedValue({
|
||||
data: { mode: 'oidc', oidc_login_url: '/api/v1/auth/oidc/login' },
|
||||
} as never)
|
||||
vi.mocked(authApi.me).mockResolvedValue({
|
||||
data: {
|
||||
subject: 'user-1',
|
||||
display_name: 'Alice',
|
||||
auth_method: 'oidc',
|
||||
issuer: 'https://id.example/application/o/homelable/',
|
||||
csrf_token: 'csrf-123',
|
||||
},
|
||||
} as never)
|
||||
|
||||
await bootstrapAuth()
|
||||
|
||||
const state = useAuthStore.getState()
|
||||
expect(authApi.me).toHaveBeenCalledOnce()
|
||||
expect(state.isAuthenticated).toBe(true)
|
||||
expect(state.authMethod).toBe('oidc')
|
||||
expect(state.token).toBeNull()
|
||||
expect(state.csrfToken).toBe('csrf-123')
|
||||
})
|
||||
|
||||
it('does not probe /auth/me for local mode without a persisted token', async () => {
|
||||
vi.mocked(authApi.config).mockResolvedValue({
|
||||
data: { mode: 'local', oidc_login_url: null },
|
||||
} as never)
|
||||
|
||||
await bootstrapAuth()
|
||||
|
||||
expect(authApi.me).not.toHaveBeenCalled()
|
||||
expect(useAuthStore.getState()).toMatchObject({
|
||||
authMode: 'local',
|
||||
isAuthenticated: false,
|
||||
isInitialized: true,
|
||||
})
|
||||
})
|
||||
|
||||
it('validates and retains a persisted local bearer token', async () => {
|
||||
useAuthStore.setState({ token: 'local-token' })
|
||||
vi.mocked(authApi.config).mockResolvedValue({
|
||||
data: { mode: 'local', oidc_login_url: null },
|
||||
} as never)
|
||||
vi.mocked(authApi.me).mockResolvedValue({
|
||||
data: {
|
||||
subject: 'admin',
|
||||
display_name: 'admin',
|
||||
auth_method: 'local',
|
||||
issuer: null,
|
||||
csrf_token: null,
|
||||
},
|
||||
} as never)
|
||||
|
||||
await bootstrapAuth()
|
||||
|
||||
expect(useAuthStore.getState()).toMatchObject({
|
||||
token: 'local-token',
|
||||
isAuthenticated: true,
|
||||
authMethod: 'local',
|
||||
})
|
||||
})
|
||||
|
||||
it('fails closed when the backend rejects the session', async () => {
|
||||
useAuthStore.setState({ token: 'expired-token', isAuthenticated: true })
|
||||
vi.mocked(authApi.config).mockResolvedValue({
|
||||
data: { mode: 'local', oidc_login_url: null },
|
||||
} as never)
|
||||
vi.mocked(authApi.me).mockRejectedValue({ response: { status: 401 } })
|
||||
|
||||
await bootstrapAuth()
|
||||
|
||||
expect(useAuthStore.getState()).toMatchObject({
|
||||
token: null,
|
||||
isAuthenticated: false,
|
||||
isInitialized: true,
|
||||
})
|
||||
})
|
||||
|
||||
it('leaves the auth mode unknown when discovery is unavailable', async () => {
|
||||
vi.mocked(authApi.config).mockRejectedValue(new Error('network down'))
|
||||
|
||||
await bootstrapAuth()
|
||||
|
||||
expect(useAuthStore.getState()).toMatchObject({
|
||||
authMode: null,
|
||||
isAuthenticated: false,
|
||||
isInitialized: true,
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,33 @@
|
||||
import { authApi } from '@/api/client'
|
||||
import { useAuthStore } from '@/stores/authStore'
|
||||
|
||||
/**
|
||||
* Discover the configured authentication mode and restore a valid session.
|
||||
* OIDC sessions are represented only by the backend's HttpOnly cookie; local
|
||||
* sessions retain their existing bearer token until /auth/me validates it.
|
||||
*/
|
||||
export async function bootstrapAuth(): Promise<void> {
|
||||
const store = useAuthStore.getState()
|
||||
|
||||
try {
|
||||
const { data: config } = await authApi.config()
|
||||
store.setAuthConfig(config.mode, config.oidc_login_url)
|
||||
|
||||
const token = useAuthStore.getState().token
|
||||
if (config.mode === 'oidc' || token) {
|
||||
try {
|
||||
const { data: user } = await authApi.me()
|
||||
useAuthStore.getState().authenticate(user)
|
||||
} catch {
|
||||
// The response interceptor clears invalid credentials on 401. Also
|
||||
// clear them for malformed/unreachable session checks, failing closed.
|
||||
useAuthStore.getState().logout()
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Keep authMode unknown when discovery is unreachable. The login screen
|
||||
// reports that state without guessing which authentication mode is active.
|
||||
} finally {
|
||||
useAuthStore.getState().finishInitialization()
|
||||
}
|
||||
}
|
||||
@@ -1,17 +1,19 @@
|
||||
import { useState } from 'react'
|
||||
import { Network, Loader2 } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import { Button, buttonVariants } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Logo } from '@/components/ui/Logo'
|
||||
import { authApi } from '@/api/client'
|
||||
import { useAuthStore } from '@/stores/authStore'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
export function LoginPage() {
|
||||
const [username, setUsername] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
const [error, setError] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
const login = useAuthStore((s) => s.login)
|
||||
const { authMode, oidcLoginUrl, login } = useAuthStore()
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
@@ -42,62 +44,92 @@ export function LoginPage() {
|
||||
<div className="relative w-full max-w-sm px-4">
|
||||
{/* Logo */}
|
||||
<div className="flex flex-col items-center gap-3 mb-8">
|
||||
<div className="flex items-center justify-center w-14 h-14 rounded-xl bg-[#00d4ff]/10 border border-[#00d4ff]/20">
|
||||
<Network size={28} className="text-[#00d4ff]" />
|
||||
</div>
|
||||
<Logo size={64} showText={false} />
|
||||
<div className="text-center">
|
||||
<h1 className="text-xl font-semibold text-foreground tracking-wide">Homelable</h1>
|
||||
<h1 className="text-xl font-semibold tracking-tight">
|
||||
<span className="text-[#e6edf3]">Home</span>
|
||||
<span className="text-[#00d4ff]">lable</span>
|
||||
</h1>
|
||||
<p className="text-xs text-muted-foreground mt-0.5">HomeLab Visualizer</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Form */}
|
||||
<form
|
||||
onSubmit={handleSubmit}
|
||||
className="flex flex-col gap-4 bg-[#161b22] border border-[#30363d] rounded-xl p-6"
|
||||
>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="username" className="text-xs text-muted-foreground">Username</Label>
|
||||
<Input
|
||||
id="username"
|
||||
autoComplete="username"
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
className="bg-[#21262d] border-[#30363d] focus-visible:ring-[#00d4ff]/50 text-sm"
|
||||
placeholder="admin"
|
||||
required
|
||||
/>
|
||||
{authMode === 'local' && (
|
||||
<>
|
||||
<form
|
||||
onSubmit={handleSubmit}
|
||||
className="flex flex-col gap-4 bg-[#161b22] border border-[#30363d] rounded-xl p-6"
|
||||
>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="username" className="text-xs text-muted-foreground">Username</Label>
|
||||
<Input
|
||||
id="username"
|
||||
autoComplete="username"
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
className="bg-[#21262d] border-[#30363d] focus-visible:ring-[#00d4ff]/50 text-sm"
|
||||
placeholder="admin"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="password" className="text-xs text-muted-foreground">Password</Label>
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
autoComplete="current-password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
className="bg-[#21262d] border-[#30363d] focus-visible:ring-[#00d4ff]/50 text-sm"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<p className="text-xs text-[#f85149] text-center">{error}</p>
|
||||
)}
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
className="mt-1 bg-[#00d4ff] text-[#0d1117] hover:bg-[#00d4ff]/90 font-medium"
|
||||
>
|
||||
{loading ? <Loader2 size={15} className="animate-spin" /> : 'Sign in'}
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
<p className="text-center text-[10px] text-muted-foreground/40 mt-4">
|
||||
Credentials configured in <span className="font-mono">.env</span>
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
|
||||
{authMode === 'oidc' && (
|
||||
<div className="flex flex-col gap-4 bg-[#161b22] border border-[#30363d] rounded-xl p-6 text-center">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Continue through the configured OpenID Connect provider.
|
||||
</p>
|
||||
<a
|
||||
href={oidcLoginUrl ?? '/api/v1/auth/oidc/login'}
|
||||
className={cn(
|
||||
buttonVariants(),
|
||||
'bg-[#00d4ff] text-[#0d1117] hover:bg-[#00d4ff]/90 font-medium',
|
||||
)}
|
||||
>
|
||||
Sign in with OpenID Connect
|
||||
</a>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="password" className="text-xs text-muted-foreground">Password</Label>
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
autoComplete="current-password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
className="bg-[#21262d] border-[#30363d] focus-visible:ring-[#00d4ff]/50 text-sm"
|
||||
required
|
||||
/>
|
||||
{authMode === null && (
|
||||
<div className="flex flex-col gap-4 bg-[#161b22] border border-[#30363d] rounded-xl p-6 text-center">
|
||||
<p className="text-sm text-[#f85149]">Could not load authentication configuration.</p>
|
||||
<Button type="button" variant="outline" onClick={() => window.location.reload()}>
|
||||
Retry
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<p className="text-xs text-[#f85149] text-center">{error}</p>
|
||||
)}
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
className="mt-1 bg-[#00d4ff] text-[#0d1117] hover:bg-[#00d4ff]/90 font-medium"
|
||||
>
|
||||
{loading ? <Loader2 size={15} className="animate-spin" /> : 'Sign in'}
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
<p className="text-center text-[10px] text-muted-foreground/40 mt-4">
|
||||
Credentials configured in <span className="font-mono">.env</span>
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
|
||||
import { act, render, screen, fireEvent, waitFor } from '@testing-library/react'
|
||||
import { LoginPage } from '../LoginPage'
|
||||
import { useAuthStore } from '@/stores/authStore'
|
||||
|
||||
@@ -13,7 +13,12 @@ import { authApi } from '@/api/client'
|
||||
|
||||
describe('LoginPage', () => {
|
||||
beforeEach(() => {
|
||||
useAuthStore.setState({ token: null, isAuthenticated: false })
|
||||
useAuthStore.setState({
|
||||
token: null,
|
||||
isAuthenticated: false,
|
||||
authMode: 'local',
|
||||
oidcLoginUrl: null,
|
||||
})
|
||||
vi.mocked(authApi.login).mockReset()
|
||||
})
|
||||
|
||||
@@ -30,6 +35,41 @@ describe('LoginPage', () => {
|
||||
expect(screen.getByRole('button', { name: /sign in/i })).toBeDefined()
|
||||
})
|
||||
|
||||
it('renders the official Homelable logo mark — not a generic lucide icon', () => {
|
||||
render(<LoginPage />)
|
||||
const svg = screen.getByTestId('logo-mark')
|
||||
// The official mark from docs/logo/icon.svg, not lucide's Network glyph
|
||||
expect(svg.querySelector('path')?.getAttribute('d'))
|
||||
.toBe('M32 11 L53 30 L48 30 L48 53 L16 53 L16 30 L11 30 Z')
|
||||
expect(svg.classList.contains('lucide')).toBe(false)
|
||||
expect(screen.getByRole('heading', { level: 1 })).toHaveTextContent('Homelable')
|
||||
expect(screen.getByText('HomeLab Visualizer')).toBeDefined()
|
||||
})
|
||||
|
||||
it('renders only the provider redirect in OIDC mode', () => {
|
||||
useAuthStore.setState({
|
||||
authMode: 'oidc',
|
||||
oidcLoginUrl: '/api/v1/auth/oidc/login',
|
||||
})
|
||||
|
||||
render(<LoginPage />)
|
||||
|
||||
expect(screen.queryByLabelText('Username')).toBeNull()
|
||||
expect(screen.queryByLabelText('Password')).toBeNull()
|
||||
expect(screen.getByRole('link', { name: 'Sign in with OpenID Connect' }))
|
||||
.toHaveAttribute('href', '/api/v1/auth/oidc/login')
|
||||
})
|
||||
|
||||
it('does not guess an auth mode when discovery failed', () => {
|
||||
useAuthStore.setState({ authMode: null })
|
||||
|
||||
render(<LoginPage />)
|
||||
|
||||
expect(screen.getByText('Could not load authentication configuration.')).toBeDefined()
|
||||
expect(screen.queryByLabelText('Username')).toBeNull()
|
||||
expect(screen.getByRole('button', { name: 'Retry' })).toBeDefined()
|
||||
})
|
||||
|
||||
// ── Security checks ──────────────────────────────────────────────────────
|
||||
|
||||
it('password field type is "password" — not rendered as plain text', () => {
|
||||
@@ -102,7 +142,9 @@ describe('LoginPage', () => {
|
||||
await waitFor(() => {
|
||||
expect((screen.getByRole('button', { name: '' }) as HTMLButtonElement).disabled).toBe(true)
|
||||
})
|
||||
resolve({ data: { access_token: 'tok' } })
|
||||
await act(async () => {
|
||||
resolve({ data: { access_token: 'tok' } })
|
||||
})
|
||||
})
|
||||
|
||||
it('calls authApi.login with credentials via POST body (not URL params)', async () => {
|
||||
|
||||
@@ -34,10 +34,11 @@ interface CanvasContainerProps {
|
||||
onNodeDragStart?: () => void
|
||||
onRequestAddToGroup?: (payload: { nodeId: string; groupId: string }) => void
|
||||
onRequestAddToContainer?: (payload: { nodeId: string; containerId: string }) => void
|
||||
onOpenPending?: (deviceId: string) => void
|
||||
onRequestAddToZone?: (payload: { nodeId: string; zoneId: string }) => void
|
||||
onOpenInventory?: (deviceId: string) => void
|
||||
}
|
||||
|
||||
export function CanvasContainer({ onConnect: onConnectProp, onEdgeDoubleClick, onNodeDoubleClick, onNodeDragStart, onRequestAddToGroup, onRequestAddToContainer, onOpenPending }: CanvasContainerProps) {
|
||||
export function CanvasContainer({ onConnect: onConnectProp, onEdgeDoubleClick, onNodeDoubleClick, onNodeDragStart, onRequestAddToGroup, onRequestAddToContainer, onRequestAddToZone, onOpenInventory }: CanvasContainerProps) {
|
||||
const [lassoMode, setLassoMode] = useState(true)
|
||||
const {
|
||||
nodes, edges,
|
||||
@@ -45,6 +46,7 @@ export function CanvasContainer({ onConnect: onConnectProp, onEdgeDoubleClick, o
|
||||
setSelectedNode, snapshotHistory,
|
||||
fitViewPending, clearFitViewPending,
|
||||
copySelectedNodes, pasteNodes,
|
||||
removeFromGroup,
|
||||
} = useCanvasStore()
|
||||
const { fitView, screenToFlowPosition, getIntersectingNodes } = useReactFlow<Node<NodeData>>()
|
||||
|
||||
@@ -146,20 +148,35 @@ export function CanvasContainer({ onConnect: onConnectProp, onEdgeDoubleClick, o
|
||||
// Drop a top-level node onto a group → ask App to confirm adding it. Runs
|
||||
// before the alignment snap so detection uses the dropped position.
|
||||
const handleNodeDragStop = useCallback<NonNullable<typeof onNodeDragStop>>((event, dragNode, dragNodes) => {
|
||||
if (dragNode && !dragNode.parentId &&
|
||||
dragNode.data.type !== 'group' && dragNode.data.type !== 'groupRect') {
|
||||
if (dragNode && dragNode.data.type !== 'group' && dragNode.data.type !== 'groupRect') {
|
||||
const intersecting = getIntersectingNodes(dragNode)
|
||||
const group = intersecting.find((n) => n.data.type === 'group')
|
||||
if (group) {
|
||||
onRequestAddToGroup?.({ nodeId: dragNode.id, groupId: group.id })
|
||||
} else {
|
||||
// Any node in container_mode (proxmox, docker_host, …) accepts children.
|
||||
const zoneParent = dragNode.parentId
|
||||
? nodes.find((n) => n.id === dragNode.parentId && n.data.type === 'groupRect')
|
||||
: undefined
|
||||
if (zoneParent) {
|
||||
// Zone children are not extent-clamped, so a drop outside the zone is
|
||||
// how the user takes a node back out of it.
|
||||
if (!intersecting.some((n) => n.id === zoneParent.id)) {
|
||||
removeFromGroup(zoneParent.id, dragNode.id)
|
||||
}
|
||||
} else if (!dragNode.parentId) {
|
||||
const group = intersecting.find((n) => n.data.type === 'group')
|
||||
const container = intersecting.find((n) => n.id !== dragNode.id && n.data.container_mode === true)
|
||||
if (container) onRequestAddToContainer?.({ nodeId: dragNode.id, containerId: container.id })
|
||||
if (group) {
|
||||
onRequestAddToGroup?.({ nodeId: dragNode.id, groupId: group.id })
|
||||
} else if (container) {
|
||||
// Any node in container_mode (proxmox, docker_host, …) accepts children.
|
||||
onRequestAddToContainer?.({ nodeId: dragNode.id, containerId: container.id })
|
||||
} else {
|
||||
// Zones come last: they are the loosest container and the largest, so
|
||||
// a group/container inside one still wins the drop.
|
||||
const zone = intersecting.find((n) => n.data.type === 'groupRect')
|
||||
if (zone) onRequestAddToZone?.({ nodeId: dragNode.id, zoneId: zone.id })
|
||||
}
|
||||
}
|
||||
}
|
||||
onNodeDragStop(event, dragNode, dragNodes)
|
||||
}, [onRequestAddToGroup, onRequestAddToContainer, getIntersectingNodes, onNodeDragStop])
|
||||
}, [onRequestAddToGroup, onRequestAddToContainer, onRequestAddToZone, removeFromGroup, nodes, getIntersectingNodes, onNodeDragStop])
|
||||
|
||||
return (
|
||||
<div ref={wrapperRef} className="w-full h-full" style={{ background: theme.colors.canvasBackground }} onMouseMove={onMouseMove}>
|
||||
@@ -202,7 +219,7 @@ export function CanvasContainer({ onConnect: onConnectProp, onEdgeDoubleClick, o
|
||||
color={theme.colors.canvasDotColor}
|
||||
/>
|
||||
<FloorMapLayer />
|
||||
<SearchBar onOpenPending={onOpenPending} />
|
||||
<SearchBar onOpenInventory={onOpenInventory} />
|
||||
<AlignmentGuides guides={guides} />
|
||||
<Controls>
|
||||
<ControlButton
|
||||
|
||||
@@ -4,23 +4,23 @@ import { Search, X } from 'lucide-react'
|
||||
import { useCanvasStore } from '@/stores/canvasStore'
|
||||
import { scanApi } from '@/api/client'
|
||||
import { NODE_TYPE_LABELS } from '@/types'
|
||||
import type { PendingDevice } from '@/components/modals/PendingDeviceModal'
|
||||
import type { InventoryEntry } from '@/components/modals/InventoryDeviceModal'
|
||||
|
||||
interface SearchBarProps {
|
||||
onOpenPending?: (deviceId: string) => void
|
||||
onOpenInventory?: (deviceId: string) => void
|
||||
}
|
||||
|
||||
export function SearchBar({ onOpenPending }: SearchBarProps) {
|
||||
export function SearchBar({ onOpenInventory }: SearchBarProps) {
|
||||
const [open, setOpen] = useState(false)
|
||||
const [query, setQuery] = useState('')
|
||||
const [pendingDevices, setPendingDevices] = useState<PendingDevice[]>([])
|
||||
const [inventoryDevices, setInventoryEntrys] = useState<InventoryEntry[]>([])
|
||||
const inputRef = useRef<HTMLInputElement>(null)
|
||||
const { nodes, setSelectedNode } = useCanvasStore()
|
||||
const { setCenter } = useReactFlow()
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
scanApi.pending().then((res) => setPendingDevices(res.data)).catch(() => {})
|
||||
scanApi.pending().then((res) => setInventoryEntrys(res.data)).catch(() => {})
|
||||
}, [open])
|
||||
|
||||
useEffect(() => {
|
||||
@@ -43,20 +43,50 @@ export function SearchBar({ onOpenPending }: SearchBarProps) {
|
||||
}, [open])
|
||||
|
||||
const q = query.toLowerCase().trim()
|
||||
|
||||
const nodeResults = q
|
||||
? nodes.filter((n) => {
|
||||
if (n.data.type === 'groupRect') return false
|
||||
return (
|
||||
n.data.label?.toLowerCase().includes(q) ||
|
||||
n.data.ip?.toLowerCase().includes(q) ||
|
||||
n.data.hostname?.toLowerCase().includes(q) ||
|
||||
(n.data.services ?? []).some((s) => s.service_name?.toLowerCase().includes(q))
|
||||
)
|
||||
? nodes.flatMap((n) => {
|
||||
if (n.data.type === 'groupRect') return []
|
||||
|
||||
const contains = (v?: string | null) => v?.toLowerCase().includes(q)
|
||||
|
||||
const matches: Array<{ key: string; display_value: string }> = []
|
||||
|
||||
// Label matches make the node a result, but it is already shown in the
|
||||
// header — don't repeat it in the matched-values column.
|
||||
const labelMatch = contains(n.data.label)
|
||||
|
||||
for (const [key, value] of [
|
||||
['notes', n.data.notes],
|
||||
['ip', n.data.ip],
|
||||
['hostname', n.data.hostname],
|
||||
] as const) {
|
||||
if (contains(value)) {
|
||||
matches.push({ key, display_value: value ?? '' })
|
||||
}
|
||||
}
|
||||
|
||||
for (const s of n.data.services ?? []) {
|
||||
if (contains(s.service_name)) {
|
||||
matches.push({ key: 'services', display_value: s.service_name ?? '' })
|
||||
}
|
||||
}
|
||||
|
||||
for (const p of (n.data.properties ?? []).filter((p) => p.visible)) {
|
||||
if (contains(p.key) || contains(p.value)) {
|
||||
matches.push({
|
||||
key: 'properties',
|
||||
display_value: `${p.key ?? ''} = ${p.value ?? ''}`,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return labelMatch || matches.length > 0 ? [{ node: n, matches }] : []
|
||||
})
|
||||
: []
|
||||
|
||||
const pendingResults = q
|
||||
? pendingDevices.filter((d) =>
|
||||
? inventoryDevices.filter((d) =>
|
||||
d.ip?.toLowerCase().includes(q) ||
|
||||
d.hostname?.toLowerCase().includes(q) ||
|
||||
d.friendly_name?.toLowerCase().includes(q) ||
|
||||
@@ -142,10 +172,10 @@ export function SearchBar({ onOpenPending }: SearchBarProps) {
|
||||
|
||||
{totalResults > 0 && (
|
||||
<div style={{ borderTop: '1px solid #30363d', maxHeight: 260, overflowY: 'auto' }}>
|
||||
{nodeResults.map((n) => (
|
||||
{nodeResults.map((n, idx) => (
|
||||
<button
|
||||
key={n.id}
|
||||
onClick={() => goToNode(n.id)}
|
||||
key={`${n.node.id}-${idx}`}
|
||||
onClick={() => goToNode(n.node.id)}
|
||||
style={{
|
||||
width: '100%',
|
||||
display: 'flex',
|
||||
@@ -161,15 +191,19 @@ export function SearchBar({ onOpenPending }: SearchBarProps) {
|
||||
onMouseLeave={(e) => (e.currentTarget.style.background = 'none')}
|
||||
>
|
||||
<span style={{ fontSize: 12, fontWeight: 600, color: '#e6edf3', flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
||||
{n.data.label}
|
||||
{n.node.data.label}
|
||||
</span>
|
||||
{n.data.ip && (
|
||||
<span style={{ fontSize: 11, color: '#8b949e', fontFamily: 'JetBrains Mono, monospace', flexShrink: 0 }}>
|
||||
{n.data.ip}
|
||||
{n.matches.length > 0 && (
|
||||
<span style={{ maxWidth: "50%", display: 'flex', flexDirection: 'column', gap: 2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
||||
{n.matches.map((m, mIdx) => (
|
||||
<span key={`${m.key}-${mIdx}`} style={{ fontSize: 11, color: '#8b949e', fontFamily: 'JetBrains Mono, monospace', flexShrink: 0, display: 'inline-block' }}>
|
||||
{m.display_value}
|
||||
</span>
|
||||
))}
|
||||
</span>
|
||||
)}
|
||||
<span style={{ fontSize: 10, color: '#6e7681', flexShrink: 0 }}>
|
||||
{NODE_TYPE_LABELS[n.data.type] ?? n.data.type}
|
||||
{NODE_TYPE_LABELS[n.node.data.type] ?? n.node.data.type}
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
@@ -181,7 +215,7 @@ export function SearchBar({ onOpenPending }: SearchBarProps) {
|
||||
return (
|
||||
<button
|
||||
key={d.id}
|
||||
onClick={() => { onOpenPending?.(d.id); setOpen(false); setQuery('') }}
|
||||
onClick={() => { onOpenInventory?.(d.id); setOpen(false); setQuery('') }}
|
||||
style={{
|
||||
width: '100%',
|
||||
display: 'flex',
|
||||
|
||||
@@ -44,9 +44,11 @@ vi.mock('@/utils/nodeColors', () => ({
|
||||
resolveNodeColors: () => ({ background: '#161b22', border: '#30363d', icon: '#00d4ff' }),
|
||||
}))
|
||||
|
||||
vi.mock('@/utils/nodeIcons', () => ({
|
||||
// Partial mock: node-type icon resolution is stubbed, but the brand/lucide
|
||||
// resolver stays real so service icons render as they do in the app.
|
||||
vi.mock('@/utils/nodeIcons', async (importActual) => ({
|
||||
...(await importActual<typeof import('@/utils/nodeIcons')>()),
|
||||
resolveNodeIcon: (_typeIcon: unknown) => _typeIcon,
|
||||
isBrandIconKey: (k: string | undefined) => !!k && k.startsWith('brand:'),
|
||||
}))
|
||||
|
||||
vi.mock('@/utils/maskIp', () => ({
|
||||
@@ -252,6 +254,27 @@ describe('BaseNode — services visibility toggle', () => {
|
||||
|
||||
expect(screen.queryByRole('link', { name: /ssh/i })).toBeNull()
|
||||
})
|
||||
|
||||
it('renders the brand icon of a service that has one', () => {
|
||||
renderBaseNode({
|
||||
ip: '192.168.1.10',
|
||||
custom_colors: { show_services: true },
|
||||
services: [{ service_name: 'plex', port: 32400, protocol: 'tcp', icon: 'brand:plex' }],
|
||||
})
|
||||
|
||||
const img = screen.getByAltText('plex') as HTMLImageElement
|
||||
expect(img.src).toContain('dashboard-icons/svg/plex.svg')
|
||||
})
|
||||
|
||||
it('renders no service icon when the service has none', () => {
|
||||
renderBaseNode({
|
||||
ip: '192.168.1.10',
|
||||
custom_colors: { show_services: true },
|
||||
services: [{ service_name: 'ssh', port: 22, protocol: 'tcp' }],
|
||||
})
|
||||
|
||||
expect(screen.queryByRole('img')).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('BaseNode — legacy hardware fallback', () => {
|
||||
|
||||
@@ -251,6 +251,63 @@ describe('CanvasContainer', () => {
|
||||
expect(onRequestAddToContainer).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
// ── Drag onto a zone → onRequestAddToZone / detach ────────────────────────
|
||||
|
||||
function zoneNode(id: string): Node<NodeData> {
|
||||
return { id, type: 'groupRect', position: { x: 0, y: 0 }, data: { label: id, type: 'groupRect', status: 'unknown', services: [] } }
|
||||
}
|
||||
|
||||
it('fires onRequestAddToZone when a node is dropped over a zone', () => {
|
||||
const onRequestAddToZone = vi.fn()
|
||||
const node = makeNode('n1')
|
||||
rf.intersecting = [zoneNode('z1')]
|
||||
render(<CanvasContainer onRequestAddToZone={onRequestAddToZone} />)
|
||||
;(rfProps.onNodeDragStop as (...args: unknown[]) => unknown)({} as MouseEvent, node, [node])
|
||||
expect(onRequestAddToZone).toHaveBeenCalledWith({ nodeId: 'n1', zoneId: 'z1' })
|
||||
})
|
||||
|
||||
it('prefers a group and a container over a zone when they overlap', () => {
|
||||
const onRequestAddToZone = vi.fn()
|
||||
const onRequestAddToContainer = vi.fn()
|
||||
const node = makeNode('n1')
|
||||
rf.intersecting = [zoneNode('z1'), containerNode('px1')]
|
||||
render(<CanvasContainer onRequestAddToZone={onRequestAddToZone} onRequestAddToContainer={onRequestAddToContainer} />)
|
||||
;(rfProps.onNodeDragStop as (...args: unknown[]) => unknown)({} as MouseEvent, node, [node])
|
||||
expect(onRequestAddToContainer).toHaveBeenCalledWith({ nodeId: 'n1', containerId: 'px1' })
|
||||
expect(onRequestAddToZone).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does not fire onRequestAddToZone when the dragged node is a zone itself', () => {
|
||||
const onRequestAddToZone = vi.fn()
|
||||
const node = zoneNode('z2')
|
||||
rf.intersecting = [zoneNode('z1')]
|
||||
render(<CanvasContainer onRequestAddToZone={onRequestAddToZone} />)
|
||||
;(rfProps.onNodeDragStop as (...args: unknown[]) => unknown)({} as MouseEvent, node, [node])
|
||||
expect(onRequestAddToZone).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('detaches a zone child dropped outside its zone', () => {
|
||||
const zone = { ...zoneNode('z1'), position: { x: 100, y: 100 } }
|
||||
const child = { ...makeNode('n1'), parentId: 'z1', position: { x: 20, y: 20 } }
|
||||
useCanvasStore.setState({ nodes: [zone, child] })
|
||||
rf.intersecting = []
|
||||
render(<CanvasContainer />)
|
||||
;(rfProps.onNodeDragStop as (...args: unknown[]) => unknown)({} as MouseEvent, child, [child])
|
||||
const after = useCanvasStore.getState().nodes.find((n) => n.id === 'n1')!
|
||||
expect(after.parentId).toBeUndefined()
|
||||
expect(after.position).toEqual({ x: 120, y: 120 })
|
||||
})
|
||||
|
||||
it('keeps a zone child parented when it is dropped inside its zone', () => {
|
||||
const zone = zoneNode('z1')
|
||||
const child = { ...makeNode('n1'), parentId: 'z1' }
|
||||
useCanvasStore.setState({ nodes: [zone, child] })
|
||||
rf.intersecting = [zone]
|
||||
render(<CanvasContainer />)
|
||||
;(rfProps.onNodeDragStop as (...args: unknown[]) => unknown)({} as MouseEvent, child, [child])
|
||||
expect(useCanvasStore.getState().nodes.find((n) => n.id === 'n1')?.parentId).toBe('z1')
|
||||
})
|
||||
|
||||
// ── Canvas settings ───────────────────────────────────────────────────────
|
||||
|
||||
it('enables snapToGrid', () => {
|
||||
|
||||
@@ -103,6 +103,50 @@ describe('SearchBar', () => {
|
||||
expect(screen.queryByText('DB Server')).toBeNull()
|
||||
})
|
||||
|
||||
it('filters by notes', () => {
|
||||
setupStore([
|
||||
makeNode('n1', { data: { label: 'Server A', type: 'server', status: 'online', services: [], ip: null, hostname: null, notes: 'backup target every night' } }),
|
||||
makeNode('n2', { data: { label: 'Server B', type: 'server', status: 'online', services: [], ip: null, hostname: null, notes: 'primary web host' } }),
|
||||
])
|
||||
render(<SearchBar />)
|
||||
openSearch()
|
||||
fireEvent.change(screen.getByPlaceholderText(/search/i), { target: { value: 'backup' } })
|
||||
expect(screen.getByText('Server A')).toBeDefined()
|
||||
expect(screen.queryByText('Server B')).toBeNull()
|
||||
})
|
||||
|
||||
it('filters by visible property key or value', () => {
|
||||
setupStore([
|
||||
makeNode('n1', { data: { label: 'Server A', type: 'server', status: 'online', services: [], ip: null, hostname: null, properties: [{ key: 'rack', value: 'B12', icon: null, visible: true }] } }),
|
||||
makeNode('n2', { data: { label: 'Server B', type: 'server', status: 'online', services: [], ip: null, hostname: null, properties: [{ key: 'rack', value: 'A01', icon: null, visible: true }] } }),
|
||||
])
|
||||
render(<SearchBar />)
|
||||
openSearch()
|
||||
fireEvent.change(screen.getByPlaceholderText(/search/i), { target: { value: 'b12' } })
|
||||
expect(screen.getByText('Server A')).toBeDefined()
|
||||
expect(screen.queryByText('Server B')).toBeNull()
|
||||
})
|
||||
|
||||
it('ignores hidden properties', () => {
|
||||
setupStore([
|
||||
makeNode('n1', { data: { label: 'Server A', type: 'server', status: 'online', services: [], ip: null, hostname: null, properties: [{ key: 'secret', value: 'hidden-val', icon: null, visible: false }] } }),
|
||||
])
|
||||
render(<SearchBar />)
|
||||
openSearch()
|
||||
fireEvent.change(screen.getByPlaceholderText(/search/i), { target: { value: 'hidden-val' } })
|
||||
expect(screen.queryByText('Server A')).toBeNull()
|
||||
})
|
||||
|
||||
it('shows the matched value alongside the node label', () => {
|
||||
setupStore([
|
||||
makeNode('n1', { data: { label: 'Server A', type: 'server', status: 'online', services: [], ip: null, hostname: null, properties: [{ key: 'rack', value: 'B12', icon: null, visible: true }] } }),
|
||||
])
|
||||
render(<SearchBar />)
|
||||
openSearch()
|
||||
fireEvent.change(screen.getByPlaceholderText(/search/i), { target: { value: 'b12' } })
|
||||
expect(screen.getByText('rack = B12')).toBeDefined()
|
||||
})
|
||||
|
||||
it('excludes groupRect nodes from results', () => {
|
||||
setupStore([
|
||||
makeNode('gr1', { data: { label: 'DMZ Zone', type: 'groupRect', status: 'unknown', services: [], ip: null, hostname: null } }),
|
||||
|
||||
@@ -5,6 +5,7 @@ import type { NodeData } from '@/types'
|
||||
import { resolveNodeColors } from '@/utils/nodeColors'
|
||||
import { resolveNodeIcon, isBrandIconKey } from '@/utils/nodeIcons'
|
||||
import { NodeIcon } from '@/components/ui/NodeIcon'
|
||||
import { ServiceIcon } from '@/components/ui/ServiceIcon'
|
||||
import { resolvePropertyIcon } from '@/utils/propertyIcons'
|
||||
import { useThemeStore } from '@/stores/themeStore'
|
||||
import { THEMES } from '@/utils/themes'
|
||||
@@ -147,7 +148,9 @@ export function BaseNode({ id, data, selected, icon: typeIcon, width, height }:
|
||||
<div key={prop.key} className="flex items-center gap-1 font-mono text-[10px] min-w-0 overflow-hidden" style={{ color: theme.colors.nodeSubtextColor }}>
|
||||
{Icon && <Icon size={9} className="shrink-0" />}
|
||||
<span className="truncate max-w-15 shrink-0" title={prop.key}>{prop.key}</span>
|
||||
<span className="truncate min-w-0" title={prop.value}>· {prop.value}</span>
|
||||
{prop.value.trim() && (
|
||||
<span className="truncate min-w-0" title={prop.value}>· {prop.value}</span>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
@@ -161,7 +164,7 @@ export function BaseNode({ id, data, selected, icon: typeIcon, width, height }:
|
||||
<div className="flex flex-col gap-1 px-2.5 py-1.5 overflow-hidden">
|
||||
{services.map((svc, idx) => {
|
||||
const url = getServiceUrl(svc, serviceHost)
|
||||
const svcOffline = serviceStatuses[serviceStatusKey(id, svc.port, svc.protocol)] === 'offline'
|
||||
const svcOffline = serviceStatuses[serviceStatusKey(id, svc.port, svc.protocol, svc.host)] === 'offline'
|
||||
const row = (
|
||||
<div
|
||||
className="nodrag flex items-center justify-between gap-2 px-1.5 py-1 rounded text-[10px] min-w-0 overflow-hidden"
|
||||
@@ -172,13 +175,16 @@ export function BaseNode({ id, data, selected, icon: typeIcon, width, height }:
|
||||
>
|
||||
|
||||
<div className="flex items-center justify-between gap-2 w-full min-w-0">
|
||||
{/* LEFT: service name */}
|
||||
<span
|
||||
className="font-medium truncate"
|
||||
style={{ minWidth: 0, color: svcOffline ? '#f85149' : undefined }}
|
||||
title={svc.service_name}
|
||||
>
|
||||
{svc.service_name}
|
||||
{/* LEFT: icon + service name */}
|
||||
<span className="flex items-center gap-1 min-w-0">
|
||||
<ServiceIcon iconKey={svc.icon} size={11} />
|
||||
<span
|
||||
className="font-medium truncate"
|
||||
style={{ minWidth: 0, color: svcOffline ? '#f85149' : undefined }}
|
||||
title={svc.service_name}
|
||||
>
|
||||
{svc.service_name}
|
||||
</span>
|
||||
</span>
|
||||
|
||||
{/* RIGHT: path + port */}
|
||||
|
||||
@@ -2,7 +2,7 @@ import { useState } from 'react'
|
||||
import { Handle, Position, NodeResizer, type NodeProps, type Node } from '@xyflow/react'
|
||||
import { ChevronDown } from 'lucide-react'
|
||||
import { useCanvasStore } from '@/stores/canvasStore'
|
||||
import { getZoneSpatialChildren } from '@/utils/collapseFilter'
|
||||
import { getZoneChildren } from '@/utils/collapseFilter'
|
||||
import type { NodeData, TextPosition } from '@/types'
|
||||
|
||||
const FONT_FAMILIES: Record<string, string> = {
|
||||
@@ -55,11 +55,11 @@ export function GroupRectNode({ id, data, selected }: NodeProps<Node<NodeData>>)
|
||||
const textPos = (rc.text_position ?? 'top-left') as TextPosition
|
||||
const posStyle = POSITION_STYLES[textPos]
|
||||
|
||||
// Count children for collapse badge — groupRect zones don't parent their
|
||||
// contents via React Flow parentId, so we hit-test by spatial containment.
|
||||
// Count children for collapse badge — a zone holds both real parentId
|
||||
// children (dropped inside) and top-level nodes merely overlapping it.
|
||||
const selfNode = (nodes ?? []).find((n) => n.id === id)
|
||||
const childrenCount = selfNode
|
||||
? getZoneSpatialChildren(selfNode, nodes ?? []).length
|
||||
? getZoneChildren(selfNode, nodes ?? []).length
|
||||
: 0
|
||||
|
||||
const outsideJustify = textPos.includes('right') ? 'flex-end'
|
||||
|
||||
@@ -120,7 +120,9 @@ export function ProxmoxGroupNode(props: NodeProps<Node<NodeData>>) {
|
||||
>
|
||||
{Icon && <Icon size={9} className="shrink-0" />}
|
||||
<span className="truncate max-w-15 shrink-0" title={prop.key}>{prop.key}</span>
|
||||
<span className="truncate min-w-0" title={prop.value}>· {prop.value}</span>
|
||||
{prop.value.trim() && (
|
||||
<span className="truncate min-w-0" title={prop.value}>· {prop.value}</span>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
|
||||
@@ -1,7 +1,23 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { nodeTypes } from '../nodeTypes'
|
||||
import { NODE_TYPE_LABELS, type NodeType } from '@/types'
|
||||
import { NODE_TYPE_DEFAULT_ICONS } from '@/utils/nodeIcons'
|
||||
|
||||
describe('nodeTypes registry', () => {
|
||||
it('registers a component for every declared node type', () => {
|
||||
// Adding a NodeType touches several hand-written maps; the Record<NodeType, …>
|
||||
// ones fail typecheck when one is missed, this registry does not.
|
||||
for (const t of Object.keys(NODE_TYPE_LABELS) as NodeType[]) {
|
||||
expect(nodeTypes[t as keyof typeof nodeTypes], `missing nodeType: ${t}`).toBeDefined()
|
||||
}
|
||||
})
|
||||
|
||||
it('gives the KVM type a label, an icon and a component', () => {
|
||||
expect(NODE_TYPE_LABELS.kvm).toBe('KVM Switch')
|
||||
expect(NODE_TYPE_DEFAULT_ICONS.kvm).toBeDefined()
|
||||
expect(nodeTypes.kvm).toBeDefined()
|
||||
})
|
||||
|
||||
it('registers a component for every wireless mesh node type', () => {
|
||||
// Regression: zwave_* types were missing, so React Flow fell back to the
|
||||
// default (unstyled) node — no icon, no accent. (Zigbee covered too.)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { type NodeProps, type Node } from '@xyflow/react'
|
||||
import {
|
||||
Globe, Router, Network, Server, Layers, Box, Container,
|
||||
HardDrive, Cpu, Wifi, Circle, Cctv, Printer, Monitor, Laptop, Smartphone, PlugZap, Anchor, Package, Flame, Radio, Antenna, RadioTower, Share2,
|
||||
HardDrive, Cpu, Wifi, Circle, Cctv, Printer, Monitor, MonitorCog, Laptop, Smartphone, PlugZap, Anchor, Package, Flame, Radio, Antenna, RadioTower, Share2,
|
||||
Grid3x3, Battery, Fuel, Sun, Repeat2, Split, ToggleLeft, Lightbulb, Gauge, Combine, Cable, Zap,
|
||||
} from 'lucide-react'
|
||||
import { BaseNode } from './BaseNode'
|
||||
@@ -18,6 +18,7 @@ export const ProxmoxNode = (props: N) => <BaseNode {...props} icon={Layers} />
|
||||
export const VmNode = (props: N) => <BaseNode {...props} icon={Box} />
|
||||
export const LxcNode = (props: N) => <BaseNode {...props} icon={Container} />
|
||||
export const NasNode = (props: N) => <BaseNode {...props} icon={HardDrive} />
|
||||
export const KvmNode = (props: N) => <BaseNode {...props} icon={MonitorCog} />
|
||||
export const IotNode = (props: N) => <BaseNode {...props} icon={Cpu} />
|
||||
export const ApNode = (props: N) => <BaseNode {...props} icon={Wifi} />
|
||||
export const CameraNode = (props: N) => <BaseNode {...props} icon={Cctv} />
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import {
|
||||
IspNode, RouterNode, FirewallNode, SwitchNode, ServerNode, VmNode, LxcNode,
|
||||
NasNode, IotNode, ApNode, CameraNode, PrinterNode, ComputerNode, LaptopNode,
|
||||
NasNode, KvmNode, IotNode, ApNode, CameraNode, PrinterNode, ComputerNode, LaptopNode,
|
||||
MobileNode, CplNode, DockerHostNode, DockerContainerNode, GenericNode,
|
||||
ZigbeeCoordinatorNode, ZigbeeRouterNode, ZigbeeEndDeviceNode,
|
||||
ZwaveCoordinatorNode, ZwaveRouterNode, ZwaveEndDeviceNode,
|
||||
@@ -23,6 +23,7 @@ export const nodeTypes = {
|
||||
vm: VmNode,
|
||||
lxc: LxcNode,
|
||||
nas: NasNode,
|
||||
kvm: KvmNode,
|
||||
iot: IotNode,
|
||||
ap: ApNode,
|
||||
camera: CameraNode,
|
||||
|
||||
@@ -0,0 +1,332 @@
|
||||
/**
|
||||
* Editable list of `NodeProperty` records — key, value, optional icon, and a
|
||||
* per-property "show it on the canvas" toggle.
|
||||
*
|
||||
* Extracted from `DetailPanel` so the rack cable panel gets the same editor
|
||||
* rather than a second implementation of it. The component owns only its form
|
||||
* and drag state; the array itself belongs to the caller, which receives every
|
||||
* mutation as a whole new array through `onChange`.
|
||||
*/
|
||||
import { createElement, useState } from 'react'
|
||||
import { Eye, EyeOff, GripVertical, Pencil, Plus, X } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { PROPERTY_ICONS, PROPERTY_ICON_NAMES, resolvePropertyIcon } from '@/utils/propertyIcons'
|
||||
import type { NodeProperty } from '@/types'
|
||||
|
||||
export type PropForm = { key: string; value: string; icon: string | null; visible: boolean }
|
||||
const EMPTY_PROP: PropForm = { key: '', value: '', icon: null, visible: true }
|
||||
|
||||
interface PropertyListProps {
|
||||
properties: NodeProperty[]
|
||||
/** Receives the full next array — the caller decides how to persist it. */
|
||||
onChange: (next: NodeProperty[]) => void
|
||||
/** Wording of the per-property visibility toggle ("Show on node" by default). */
|
||||
visibleLabel?: string
|
||||
/** Placeholder examples, so a cable does not suggest "CPU Model". */
|
||||
keyPlaceholder?: string
|
||||
valuePlaceholder?: string
|
||||
/** One-click keys pre-filling the add form (e.g. Length, VLAN). */
|
||||
suggestions?: string[]
|
||||
/** Section heading. */
|
||||
title?: string
|
||||
emptyHint?: string
|
||||
}
|
||||
|
||||
export function PropertyList({
|
||||
properties,
|
||||
onChange,
|
||||
visibleLabel = 'Show on node',
|
||||
keyPlaceholder = 'Label (e.g. CPU Model)',
|
||||
valuePlaceholder = 'Value — optional (e.g. i7-12700K)',
|
||||
suggestions,
|
||||
title = 'Properties',
|
||||
emptyHint = 'No properties — click Add to define one.',
|
||||
}: PropertyListProps) {
|
||||
const [adding, setAdding] = useState(false)
|
||||
const [newProp, setNewProp] = useState<PropForm>(EMPTY_PROP)
|
||||
const [editingIndex, setEditingIndex] = useState<number | null>(null)
|
||||
const [editProp, setEditProp] = useState<PropForm>(EMPTY_PROP)
|
||||
const [dragIndex, setDragIndex] = useState<number | null>(null)
|
||||
const [dragOverIndex, setDragOverIndex] = useState<number | null>(null)
|
||||
|
||||
const handleAdd = () => {
|
||||
// Only the key is required — a property may carry a label alone.
|
||||
if (!newProp.key.trim()) return
|
||||
onChange([
|
||||
...properties,
|
||||
{ key: newProp.key.trim(), value: newProp.value.trim(), icon: newProp.icon, visible: newProp.visible },
|
||||
])
|
||||
setNewProp(EMPTY_PROP)
|
||||
setAdding(false)
|
||||
}
|
||||
|
||||
const handleRemove = (index: number) => {
|
||||
onChange(properties.filter((_, i) => i !== index))
|
||||
// `editingIndex` is a position into an array the caller owns, so any
|
||||
// mutation from outside the form invalidates it: removing an earlier row
|
||||
// shifted the open form onto its neighbour, and Save then overwrote the
|
||||
// wrong property. Close the form rather than try to track the move.
|
||||
setEditingIndex(null)
|
||||
}
|
||||
|
||||
const handleToggleVisible = (index: number) => {
|
||||
onChange(properties.map((p, i) => (i === index ? { ...p, visible: !p.visible } : p)))
|
||||
}
|
||||
|
||||
const handleStartEdit = (index: number) => {
|
||||
const p = properties[index]
|
||||
if (!p) return
|
||||
setEditProp({ key: p.key, value: p.value, icon: p.icon, visible: p.visible })
|
||||
setEditingIndex(index)
|
||||
setAdding(false)
|
||||
}
|
||||
|
||||
const handleSaveEdit = () => {
|
||||
if (editingIndex === null || !editProp.key.trim()) return
|
||||
onChange(
|
||||
properties.map((p, i) =>
|
||||
i === editingIndex
|
||||
? { key: editProp.key.trim(), value: editProp.value.trim(), icon: editProp.icon, visible: editProp.visible }
|
||||
: p
|
||||
)
|
||||
)
|
||||
setEditingIndex(null)
|
||||
}
|
||||
|
||||
const handleReorder = (from: number, to: number) => {
|
||||
if (from === to || from < 0 || to < 0 || from >= properties.length || to >= properties.length) return
|
||||
const reordered = [...properties]
|
||||
const [moved] = reordered.splice(from, 1)
|
||||
reordered.splice(to, 0, moved)
|
||||
onChange(reordered)
|
||||
// Same positional hazard as a remove — see handleRemove.
|
||||
setEditingIndex(null)
|
||||
}
|
||||
|
||||
const startAddWith = (key: string) => {
|
||||
setEditingIndex(null)
|
||||
setNewProp({ ...EMPTY_PROP, key })
|
||||
setAdding(true)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="px-4 py-3 border-t border-border">
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<span className="text-xs text-muted-foreground">{title}{properties.length > 0 ? ` (${properties.length})` : ''}</span>
|
||||
<button
|
||||
onClick={() => { setAdding((v) => !v); setEditingIndex(null) }}
|
||||
className="flex items-center gap-1 text-[10px] text-[#00d4ff] hover:text-[#00d4ff]/80 transition-colors cursor-pointer"
|
||||
>
|
||||
<Plus size={10} /> Add
|
||||
</button>
|
||||
</div>
|
||||
{suggestions && suggestions.length > 0 && !adding && (
|
||||
<div className="flex flex-wrap gap-1 mb-2">
|
||||
{suggestions.map((key) => (
|
||||
<button
|
||||
key={key}
|
||||
onClick={() => startAddWith(key)}
|
||||
title={`Add a ${key} property`}
|
||||
className="rounded border border-[#30363d] px-1.5 py-0.5 text-[10px] text-muted-foreground hover:border-[#00d4ff] hover:text-[#00d4ff] transition-colors cursor-pointer"
|
||||
>
|
||||
+ {key}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{adding && (
|
||||
<PropertyForm
|
||||
form={newProp}
|
||||
onChange={setNewProp}
|
||||
onConfirm={handleAdd}
|
||||
onCancel={() => { setAdding(false); setNewProp(EMPTY_PROP) }}
|
||||
confirmLabel="Add"
|
||||
visibleLabel={visibleLabel}
|
||||
keyPlaceholder={keyPlaceholder}
|
||||
valuePlaceholder={valuePlaceholder}
|
||||
/>
|
||||
)}
|
||||
{properties.length > 0 && (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
{properties.map((prop, i) =>
|
||||
editingIndex === i ? (
|
||||
<PropertyForm
|
||||
key={`edit-${i}`}
|
||||
form={editProp}
|
||||
onChange={setEditProp}
|
||||
onConfirm={handleSaveEdit}
|
||||
onCancel={() => setEditingIndex(null)}
|
||||
confirmLabel="Save"
|
||||
visibleLabel={visibleLabel}
|
||||
keyPlaceholder={keyPlaceholder}
|
||||
valuePlaceholder={valuePlaceholder}
|
||||
/>
|
||||
) : (
|
||||
<PropertyBadge
|
||||
key={`${prop.key}-${i}`}
|
||||
prop={prop}
|
||||
visibleLabel={visibleLabel}
|
||||
draggable={properties.length > 1}
|
||||
isDragging={dragIndex === i}
|
||||
isDragOver={dragOverIndex === i && dragIndex !== i}
|
||||
onDragStart={() => setDragIndex(i)}
|
||||
onDragEnter={() => { if (dragIndex !== null) setDragOverIndex(i) }}
|
||||
onDragEnd={() => { setDragIndex(null); setDragOverIndex(null) }}
|
||||
onDrop={() => {
|
||||
if (dragIndex !== null) handleReorder(dragIndex, i)
|
||||
setDragIndex(null)
|
||||
setDragOverIndex(null)
|
||||
}}
|
||||
onToggleVisible={() => handleToggleVisible(i)}
|
||||
onEdit={() => handleStartEdit(i)}
|
||||
onRemove={() => handleRemove(i)}
|
||||
/>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{properties.length === 0 && !adding && (
|
||||
<p className="text-[10px] text-muted-foreground/50">{emptyHint}</p>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function PropertyForm({ form, onChange, onConfirm, onCancel, confirmLabel, visibleLabel = 'Show on node', keyPlaceholder = 'Label (e.g. CPU Model)', valuePlaceholder = 'Value — optional (e.g. i7-12700K)' }: {
|
||||
form: PropForm
|
||||
onChange: (f: PropForm) => void
|
||||
onConfirm: () => void
|
||||
onCancel: () => void
|
||||
confirmLabel: string
|
||||
visibleLabel?: string
|
||||
keyPlaceholder?: string
|
||||
valuePlaceholder?: string
|
||||
}) {
|
||||
return (
|
||||
<div className="flex flex-col gap-1.5 mb-1 p-2 rounded-md bg-[#0d1117] border border-[#30363d]">
|
||||
<Input
|
||||
value={form.key}
|
||||
onChange={(e) => onChange({ ...form, key: e.target.value })}
|
||||
placeholder={keyPlaceholder}
|
||||
className="bg-[#21262d] border-[#30363d] text-xs h-7"
|
||||
autoFocus
|
||||
onKeyDown={(e) => e.key === 'Enter' && onConfirm()}
|
||||
/>
|
||||
<Input
|
||||
value={form.value}
|
||||
onChange={(e) => onChange({ ...form, value: e.target.value })}
|
||||
placeholder={valuePlaceholder}
|
||||
className="bg-[#21262d] border-[#30363d] text-xs h-7"
|
||||
onKeyDown={(e) => e.key === 'Enter' && onConfirm()}
|
||||
/>
|
||||
{/* Icon picker */}
|
||||
<div className="flex flex-wrap gap-1 pt-0.5">
|
||||
<button
|
||||
onClick={() => onChange({ ...form, icon: null })}
|
||||
title="No icon"
|
||||
className={`w-6 h-6 rounded flex items-center justify-center text-[10px] border transition-colors ${
|
||||
form.icon === null ? 'border-[#00d4ff] bg-[#00d4ff]/10 text-[#00d4ff]' : 'border-[#30363d] text-muted-foreground hover:border-[#8b949e]'
|
||||
}`}
|
||||
>
|
||||
–
|
||||
</button>
|
||||
{PROPERTY_ICON_NAMES.map((name) => {
|
||||
const Icon = PROPERTY_ICONS[name]
|
||||
const active = form.icon === name
|
||||
return (
|
||||
<button
|
||||
key={name}
|
||||
onClick={() => onChange({ ...form, icon: name })}
|
||||
title={name}
|
||||
className={`w-6 h-6 rounded flex items-center justify-center border transition-colors ${
|
||||
active ? 'border-[#00d4ff] bg-[#00d4ff]/10 text-[#00d4ff]' : 'border-[#30363d] text-muted-foreground hover:border-[#8b949e]'
|
||||
}`}
|
||||
>
|
||||
{createElement(Icon, { size: 11 })}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
{/* Visible toggle */}
|
||||
<label className="flex items-center gap-2 cursor-pointer pt-0.5">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={form.visible}
|
||||
onChange={(e) => onChange({ ...form, visible: e.target.checked })}
|
||||
className="accent-[#00d4ff] w-3 h-3"
|
||||
/>
|
||||
<span className="text-[10px] text-muted-foreground">{visibleLabel}</span>
|
||||
</label>
|
||||
<div className="flex gap-1.5">
|
||||
<Button size="sm" className="flex-1 h-6 text-[10px] bg-[#00d4ff] text-[#0d1117] hover:bg-[#00d4ff]/90" onClick={onConfirm}>
|
||||
{confirmLabel}
|
||||
</Button>
|
||||
<Button size="sm" variant="ghost" className="h-6 text-[10px]" onClick={onCancel}>Cancel</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function PropertyBadge({ prop, visibleLabel = 'node', draggable, isDragging, isDragOver, onDragStart, onDragEnter, onDragEnd, onDrop, onToggleVisible, onEdit, onRemove }: {
|
||||
prop: NodeProperty
|
||||
/** Used to word the eye tooltip — "Show on node" / "Show on canvas". */
|
||||
visibleLabel?: string
|
||||
draggable: boolean
|
||||
isDragging: boolean
|
||||
isDragOver: boolean
|
||||
onDragStart: () => void
|
||||
onDragEnter: () => void
|
||||
onDragEnd: () => void
|
||||
onDrop: () => void
|
||||
onToggleVisible: () => void
|
||||
onEdit: () => void
|
||||
onRemove: () => void
|
||||
}) {
|
||||
const Icon = resolvePropertyIcon(prop.icon)
|
||||
const where = visibleLabel.replace(/^Show on /i, '')
|
||||
return (
|
||||
<div
|
||||
draggable={draggable}
|
||||
onDragStart={onDragStart}
|
||||
onDragEnter={onDragEnter}
|
||||
onDragOver={(e) => e.preventDefault()}
|
||||
onDragEnd={onDragEnd}
|
||||
onDrop={(e) => { e.preventDefault(); onDrop() }}
|
||||
className="group flex items-center justify-between gap-2 px-2 py-1.5 rounded-md border text-xs transition-colors"
|
||||
style={{
|
||||
background: '#21262d',
|
||||
borderColor: isDragOver ? '#00d4ff' : '#30363d',
|
||||
opacity: isDragging ? 0.4 : 1,
|
||||
}}
|
||||
>
|
||||
<div className="flex items-center gap-1.5 min-w-0">
|
||||
{draggable && (
|
||||
<span className="shrink-0 cursor-grab active:cursor-grabbing text-[#8b949e] hover:text-[#00d4ff]" title="Drag to reorder">
|
||||
{createElement(GripVertical, { size: 11 })}
|
||||
</span>
|
||||
)}
|
||||
{Icon && createElement(Icon, { size: 11, className: 'shrink-0 text-muted-foreground' })}
|
||||
<span className="font-medium truncate text-foreground" title={prop.key}>{prop.key}</span>
|
||||
{prop.value.trim() && (
|
||||
<span className="text-muted-foreground truncate" title={prop.value}>· {prop.value}</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-1 shrink-0">
|
||||
<button
|
||||
onClick={onToggleVisible}
|
||||
title={prop.visible ? `Hide on ${where}` : `Show on ${where}`}
|
||||
className="text-[#8b949e] hover:text-[#00d4ff] transition-colors"
|
||||
>
|
||||
{prop.visible ? <Eye size={10} /> : <EyeOff size={10} />}
|
||||
</button>
|
||||
<button onClick={onEdit} className="opacity-0 group-hover:opacity-100 transition-opacity text-[#8b949e] hover:text-[#00d4ff]" title="Edit property">
|
||||
<Pencil size={10} />
|
||||
</button>
|
||||
<button onClick={onRemove} className="opacity-0 group-hover:opacity-100 transition-opacity text-[#8b949e] hover:text-[#f85149]" title="Remove property">
|
||||
<X size={10} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
/**
|
||||
* Shared property editor — used by the node DetailPanel and the rack cable
|
||||
* panel, so a positional bug here lands on both canvases.
|
||||
*/
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { render, screen, fireEvent } from '@testing-library/react'
|
||||
import { PropertyList } from '../PropertyList'
|
||||
import type { NodeProperty } from '@/types'
|
||||
|
||||
const props = (): NodeProperty[] => [
|
||||
{ key: 'A', value: '1', icon: null, visible: true },
|
||||
{ key: 'B', value: '2', icon: null, visible: true },
|
||||
{ key: 'C', value: '3', icon: null, visible: true },
|
||||
]
|
||||
|
||||
/** The form's confirm button; the section header carries an "Add" too. */
|
||||
const confirm = (name: string) => {
|
||||
const buttons = screen.getAllByRole('button', { name })
|
||||
return buttons[buttons.length - 1]
|
||||
}
|
||||
|
||||
describe('PropertyList', () => {
|
||||
it('renders each property with its key and value', () => {
|
||||
render(<PropertyList properties={props()} onChange={vi.fn()} />)
|
||||
expect(screen.getByTitle('A')).toBeInTheDocument()
|
||||
expect(screen.getByTitle('3')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('adds a property', () => {
|
||||
const onChange = vi.fn()
|
||||
render(<PropertyList properties={[]} onChange={onChange} />)
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Add' }))
|
||||
fireEvent.change(screen.getByPlaceholderText(/^Label/), { target: { value: 'GPU' } })
|
||||
fireEvent.change(screen.getByPlaceholderText(/^Value/), { target: { value: 'RTX' } })
|
||||
fireEvent.click(confirm('Add'))
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith([
|
||||
{ key: 'GPU', value: 'RTX', icon: null, visible: true },
|
||||
])
|
||||
})
|
||||
|
||||
it('adds a property with a label and no value', () => {
|
||||
const onChange = vi.fn()
|
||||
render(<PropertyList properties={[]} onChange={onChange} />)
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Add' }))
|
||||
fireEvent.change(screen.getByPlaceholderText(/^Label/), { target: { value: 'GPU' } })
|
||||
fireEvent.click(confirm('Add'))
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith([{ key: 'GPU', value: '', icon: null, visible: true }])
|
||||
})
|
||||
|
||||
it('refuses a property with no key', () => {
|
||||
const onChange = vi.fn()
|
||||
render(<PropertyList properties={[]} onChange={onChange} />)
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Add' }))
|
||||
fireEvent.change(screen.getByPlaceholderText(/^Value/), { target: { value: 'RTX' } })
|
||||
fireEvent.click(confirm('Add'))
|
||||
|
||||
expect(onChange).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('prints a value-less property as a bare label', () => {
|
||||
render(<PropertyList properties={[{ key: 'Rented', value: '', icon: null, visible: true }]} onChange={vi.fn()} />)
|
||||
|
||||
expect(screen.getByTitle('Rented')).toBeInTheDocument()
|
||||
expect(screen.queryByText(/^·/)).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('toggles a property between shown and hidden', () => {
|
||||
const onChange = vi.fn()
|
||||
render(<PropertyList properties={props()} onChange={onChange} />)
|
||||
|
||||
fireEvent.click(screen.getAllByTitle('Hide on node')[1])
|
||||
expect(onChange.mock.calls[0][0][1].visible).toBe(false)
|
||||
})
|
||||
|
||||
it('closes the open edit form when another property is removed', () => {
|
||||
// The form index is a position into an array the caller owns. Removing an
|
||||
// earlier row shifted the open form onto its neighbour, and Save then
|
||||
// overwrote the wrong property.
|
||||
const onChange = vi.fn()
|
||||
const { rerender } = render(<PropertyList properties={props()} onChange={onChange} />)
|
||||
|
||||
fireEvent.click(screen.getAllByTitle('Edit property')[1]) // editing B
|
||||
expect(screen.getByDisplayValue('B')).toBeInTheDocument()
|
||||
|
||||
fireEvent.click(screen.getAllByTitle('Remove property')[0]) // remove A
|
||||
const next = onChange.mock.calls[0][0]
|
||||
rerender(<PropertyList properties={next} onChange={onChange} />)
|
||||
|
||||
// No form at all — index 1 now points at C, so a surviving form would sit
|
||||
// on the wrong property and Save would overwrite it.
|
||||
expect(screen.queryByRole('button', { name: 'Save' })).toBeNull()
|
||||
expect(next.map((p: NodeProperty) => p.key)).toEqual(['B', 'C'])
|
||||
})
|
||||
|
||||
it('closes the open edit form when the list is reordered', () => {
|
||||
const onChange = vi.fn()
|
||||
const { rerender } = render(<PropertyList properties={props()} onChange={onChange} />)
|
||||
|
||||
fireEvent.click(screen.getAllByTitle('Edit property')[2]) // editing C
|
||||
expect(screen.getByDisplayValue('C')).toBeInTheDocument()
|
||||
|
||||
const rows = screen.getAllByTitle('Drag to reorder')
|
||||
fireEvent.dragStart(rows[0])
|
||||
fireEvent.dragEnter(rows[1])
|
||||
fireEvent.drop(rows[1])
|
||||
|
||||
rerender(<PropertyList properties={onChange.mock.calls[0][0]} onChange={onChange} />)
|
||||
expect(screen.queryByRole('button', { name: 'Save' })).toBeNull()
|
||||
})
|
||||
|
||||
it('saves an edit onto the property it was opened on', () => {
|
||||
const onChange = vi.fn()
|
||||
render(<PropertyList properties={props()} onChange={onChange} />)
|
||||
|
||||
fireEvent.click(screen.getAllByTitle('Edit property')[1])
|
||||
fireEvent.change(screen.getByDisplayValue('2'), { target: { value: '22' } })
|
||||
fireEvent.click(confirm('Save'))
|
||||
|
||||
expect(onChange.mock.calls[0][0]).toEqual([
|
||||
{ key: 'A', value: '1', icon: null, visible: true },
|
||||
{ key: 'B', value: '22', icon: null, visible: true },
|
||||
{ key: 'C', value: '3', icon: null, visible: true },
|
||||
])
|
||||
})
|
||||
|
||||
it('saves an edit that clears the value', () => {
|
||||
const onChange = vi.fn()
|
||||
render(<PropertyList properties={props()} onChange={onChange} />)
|
||||
|
||||
fireEvent.click(screen.getAllByTitle('Edit property')[1])
|
||||
fireEvent.change(screen.getByDisplayValue('2'), { target: { value: '' } })
|
||||
fireEvent.click(confirm('Save'))
|
||||
|
||||
expect(onChange.mock.calls[0][0][1]).toEqual({ key: 'B', value: '', icon: null, visible: true })
|
||||
})
|
||||
|
||||
it('words the visibility toggle for the surface it edits', () => {
|
||||
render(<PropertyList properties={props()} onChange={vi.fn()} visibleLabel="Show on canvas" />)
|
||||
expect(screen.getAllByTitle('Hide on canvas')).toHaveLength(3)
|
||||
})
|
||||
|
||||
it('pre-fills the add form from a suggestion', () => {
|
||||
render(<PropertyList properties={[]} onChange={vi.fn()} suggestions={['Length']} />)
|
||||
fireEvent.click(screen.getByText('+ Length'))
|
||||
expect(screen.getByDisplayValue('Length')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -15,7 +15,7 @@ interface ConfirmAddToGroupModalProps {
|
||||
/** Label of the destination group/container. */
|
||||
targetLabel: string
|
||||
/** Destination kind — drives the wording. Defaults to 'group'. */
|
||||
variant?: 'group' | 'container'
|
||||
variant?: 'group' | 'container' | 'zone'
|
||||
onConfirm: () => void
|
||||
onCancel: () => void
|
||||
}
|
||||
@@ -28,8 +28,8 @@ export function ConfirmAddToGroupModal({
|
||||
onConfirm,
|
||||
onCancel,
|
||||
}: ConfirmAddToGroupModalProps) {
|
||||
const action = variant === 'container' ? 'Add to container' : 'Add to group'
|
||||
const noun = variant === 'container' ? 'container' : 'group'
|
||||
const noun = variant === 'container' ? 'container' : variant === 'zone' ? 'zone' : 'group'
|
||||
const action = `Add to ${noun}`
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={(o) => { if (!o) onCancel() }}>
|
||||
<DialogContent className="max-w-sm">
|
||||
|
||||
@@ -10,7 +10,7 @@ import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/u
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { useThemeStore } from '@/stores/themeStore'
|
||||
import { useCanvasStore } from '@/stores/canvasStore'
|
||||
import { clampHandles, sideDefault } from '@/utils/handleUtils'
|
||||
import { MIN_HANDLES, clampHandles, sideDefault } from '@/utils/handleUtils'
|
||||
import { THEMES } from '@/utils/themes'
|
||||
import { applyOpacity } from '@/utils/colorUtils'
|
||||
import type {
|
||||
@@ -26,7 +26,7 @@ import { MarkerShapePicker } from './MarkerShapePicker'
|
||||
// ── Node types exposed for custom style, grouped by category (skip groupRect/group) ──
|
||||
|
||||
const NODE_TYPE_GROUPS: { label: string; types: NodeType[] }[] = [
|
||||
{ label: 'Hardware', types: ['isp', 'router', 'firewall', 'switch', 'server', 'nas', 'ap', 'printer'] },
|
||||
{ label: 'Hardware', types: ['isp', 'router', 'firewall', 'switch', 'server', 'nas', 'kvm', 'ap', 'printer'] },
|
||||
{ label: 'Virtualization', types: ['proxmox', 'vm', 'lxc', 'docker_host', 'docker_container'] },
|
||||
{ label: 'IoT', types: ['iot', 'camera', 'cpl'] },
|
||||
{ label: 'Zigbee', types: ['zigbee_coordinator', 'zigbee_router', 'zigbee_enddevice'] },
|
||||
@@ -229,7 +229,7 @@ function NodeEditor({ nodeType, style, onChange, onApplyToExisting }: NodeEditor
|
||||
<span className="text-xs text-[#8b949e] w-12">{label}</span>
|
||||
<input
|
||||
type="number"
|
||||
min={sideDefault(side)}
|
||||
min={MIN_HANDLES}
|
||||
max={64}
|
||||
step={1}
|
||||
value={style[key] ?? sideDefault(side)}
|
||||
|
||||
@@ -4,11 +4,22 @@ import { Button } from '@/components/ui/button'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { DESIGN_ICONS, DEFAULT_DESIGN_ICON, resolveDesignIcon } from '@/utils/designIcons'
|
||||
import type { Design, FloorMapConfig } from '@/types'
|
||||
import type { Design, DesignType, FloorMapConfig } from '@/types'
|
||||
|
||||
/** Canvas kinds offered on create. `electrical` shares the network renderer. */
|
||||
const CANVAS_KINDS: { value: DesignType; label: string; hint: string }[] = [
|
||||
{ value: 'network', label: 'Diagram', hint: 'Nodes and links on a free canvas' },
|
||||
{ value: 'rack', label: 'Rack', hint: 'Racks, mounted gear and patching' },
|
||||
]
|
||||
|
||||
export interface DesignFormData {
|
||||
name: string
|
||||
icon: string
|
||||
/**
|
||||
* Kind of canvas to create. Only offered in create mode — a canvas cannot
|
||||
* change kind afterwards, since network and rack store different things.
|
||||
*/
|
||||
designType?: DesignType
|
||||
/**
|
||||
* Floor plan for THIS canvas. Only present when the floor-plan section is
|
||||
* shown (edit mode on the active canvas). `null` means "remove the floor
|
||||
@@ -60,9 +71,12 @@ export function DesignModal({
|
||||
}: DesignModalProps) {
|
||||
const [name, setName] = useState(initial?.name ?? '')
|
||||
const [icon, setIcon] = useState(initial?.icon ?? DEFAULT_DESIGN_ICON)
|
||||
const [designType, setDesignType] = useState<DesignType>(initial?.designType ?? 'network')
|
||||
|
||||
// "Copy from existing" is create-mode only (no floor-plan section shown).
|
||||
const canCopy = !showFloorMap && sourceDesigns.length > 0
|
||||
// Editing never changes the kind; `initial` is only passed in edit mode.
|
||||
const canPickKind = !initial && !showFloorMap
|
||||
const [fromExisting, setFromExisting] = useState(false)
|
||||
const [sourceId, setSourceId] = useState<string>(sourceDesigns[0]?.id ?? '')
|
||||
|
||||
@@ -103,6 +117,7 @@ export function DesignModal({
|
||||
if (!trimmed) return
|
||||
if (canCopy && fromExisting && !sourceId) return
|
||||
const data: DesignFormData = { name: trimmed, icon }
|
||||
if (canPickKind) data.designType = designType
|
||||
if (canCopy && fromExisting && sourceId) {
|
||||
data.sourceId = sourceId
|
||||
}
|
||||
@@ -146,6 +161,35 @@ export function DesignModal({
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* A copy inherits the source's kind, so the picker would be a lie. */}
|
||||
{canPickKind && !fromExisting && (
|
||||
<div className="space-y-1.5">
|
||||
<Label>Kind</Label>
|
||||
<div className="grid grid-cols-2 gap-1.5">
|
||||
{CANVAS_KINDS.map((kind) => {
|
||||
const selected = kind.value === designType
|
||||
return (
|
||||
<button
|
||||
key={kind.value}
|
||||
type="button"
|
||||
aria-pressed={selected}
|
||||
title={kind.hint}
|
||||
onClick={() => setDesignType(kind.value)}
|
||||
className={`rounded-md border px-2 py-2 text-left transition-colors cursor-pointer ${
|
||||
selected
|
||||
? 'border-[#00d4ff] bg-[#00d4ff]/10 text-[#00d4ff]'
|
||||
: 'border-border text-muted-foreground hover:text-foreground hover:border-[#30363d]'
|
||||
}`}
|
||||
>
|
||||
<span className="block text-xs font-medium">{kind.label}</span>
|
||||
<span className="block text-[10px] leading-tight opacity-70">{kind.hint}</span>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<Label>Icon</Label>
|
||||
<div className="grid grid-cols-8 gap-1.5">
|
||||
|
||||
+116
-48
@@ -1,6 +1,6 @@
|
||||
import { useState, useEffect, useCallback, useRef, useMemo } from 'react'
|
||||
import {
|
||||
Globe, Router, Server, Layers, Box, Container, HardDrive, Cpu, Wifi, Circle, Network,
|
||||
Server, Layers,
|
||||
Search, RefreshCw, X, CheckCircle2, EyeOff, Trash2, Loader2, ServerCog,
|
||||
} from 'lucide-react'
|
||||
import { Dialog, DialogClose, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
@@ -9,8 +9,9 @@ import { useCanvasStore } from '@/stores/canvasStore'
|
||||
import { useDesignStore } from '@/stores/designStore'
|
||||
import { useThemeStore } from '@/stores/themeStore'
|
||||
import { resolveNodeColors } from '@/utils/nodeColors'
|
||||
import { NODE_TYPE_DEFAULT_ICONS } from '@/utils/nodeIcons'
|
||||
import { toast } from 'sonner'
|
||||
import { PendingDeviceModal, type PendingDevice } from '@/components/modals/PendingDeviceModal'
|
||||
import { InventoryDeviceModal, type InventoryEntry } from '@/components/modals/InventoryDeviceModal'
|
||||
import type { NodeType, ServiceInfo } from '@/types'
|
||||
import { applyAutoEdges, type AutoEdge } from '@/utils/autoEdges'
|
||||
import { buildZigbeeProperties, isZigbeeType } from '@/utils/zigbeeProperties'
|
||||
@@ -18,13 +19,24 @@ import { buildZwaveProperties, isZwaveType } from '@/utils/zwaveProperties'
|
||||
import { buildMacProperty } from '@/utils/macProperty'
|
||||
import { formatRelative, formatTimestamp } from '@/utils/timeFormat'
|
||||
import { getCenteredPosition } from '@/utils/viewportCenter'
|
||||
import { sourceBuckets, orderedSources, SOURCE_META, type SourceBucket } from '@/utils/pendingSources'
|
||||
import { sourceBuckets, orderedSources, isRackDevice, SOURCE_META, type SourceBucket } from '@/utils/deviceSources'
|
||||
import { isRackable } from '@/utils/rackable'
|
||||
|
||||
interface PendingDevicesModalProps {
|
||||
interface DeviceInventoryModalProps {
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
highlightId?: string
|
||||
initialStatus?: 'pending' | 'hidden'
|
||||
/** Getting Started tour: render these canned devices and skip the backend fetch. */
|
||||
demoDevices?: InventoryEntry[]
|
||||
/**
|
||||
* Picker mode. Clicking a card hands the device back instead of opening its
|
||||
* detail modal, so another feature (the rack canvas) can reuse this list —
|
||||
* search, filters, badges and all — rather than reimplementing a `<select>`.
|
||||
*/
|
||||
onPick?: (device: InventoryEntry) => void
|
||||
/** Start with the Rackable filter on (what the rack picker wants). */
|
||||
initialRackableOnly?: boolean
|
||||
}
|
||||
|
||||
const PORT_COLORS: Record<number, string> = {
|
||||
@@ -61,26 +73,21 @@ function serviceColor(port: number | null | undefined, category?: string | null)
|
||||
return '#8b949e'
|
||||
}
|
||||
|
||||
const TYPE_ICONS: Record<string, React.ElementType> = {
|
||||
isp: Globe,
|
||||
router: Router,
|
||||
server: Server,
|
||||
proxmox: Layers,
|
||||
vm: Box,
|
||||
lxc: Container,
|
||||
nas: HardDrive,
|
||||
iot: Cpu,
|
||||
ap: Wifi,
|
||||
switch: Network,
|
||||
generic: Circle,
|
||||
}
|
||||
|
||||
type SourceFilter = 'all' | SourceBucket
|
||||
type StatusFilter = 'pending' | 'hidden'
|
||||
|
||||
const COMMON_PORTS = new Set([22, 80, 443])
|
||||
|
||||
function specialServiceName(d: PendingDevice): string | undefined {
|
||||
/**
|
||||
* What the device is. The curated `type` wins over the discovery guess: a
|
||||
* device drawn on a canvas only ever has the former, and an edit that retypes a
|
||||
* scanned row must not keep reading the scanner's opinion.
|
||||
*/
|
||||
function deviceType(d: InventoryEntry): NodeType | null {
|
||||
return ((d.type ?? d.suggested_type) as NodeType) ?? null
|
||||
}
|
||||
|
||||
function specialServiceName(d: InventoryEntry): string | undefined {
|
||||
const candidates = (d.services ?? []).filter(
|
||||
(s) => s.category != null && s.port != null && !COMMON_PORTS.has(s.port) && s.service_name,
|
||||
)
|
||||
@@ -89,8 +96,9 @@ function specialServiceName(d: PendingDevice): string | undefined {
|
||||
return (nonWeb ?? candidates[0])?.service_name ?? undefined
|
||||
}
|
||||
|
||||
function deviceLabel(d: PendingDevice): string {
|
||||
return d.friendly_name ?? d.hostname ?? specialServiceName(d) ?? d.ip ?? d.ieee_address ?? 'device'
|
||||
function deviceLabel(d: InventoryEntry): string {
|
||||
// Same precedence as the detail modal — the name the user gave it first.
|
||||
return d.label ?? d.friendly_name ?? d.hostname ?? specialServiceName(d) ?? d.ip ?? d.ieee_address ?? 'device'
|
||||
}
|
||||
|
||||
// Pull the duplicate-conflict payload out of a 409 approve response, if that's
|
||||
@@ -113,10 +121,10 @@ function injectAutoEdges(edges: AutoEdge[] | undefined) {
|
||||
}))
|
||||
}
|
||||
|
||||
export function PendingDevicesModal({ open, onClose, highlightId, initialStatus = 'pending' }: PendingDevicesModalProps) {
|
||||
const [devices, setDevices] = useState<PendingDevice[]>([])
|
||||
export function DeviceInventoryModal({ open, onClose, highlightId, initialStatus = 'pending', demoDevices, onPick, initialRackableOnly = false }: DeviceInventoryModalProps) {
|
||||
const [devices, setDevices] = useState<InventoryEntry[]>([])
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [selected, setSelected] = useState<PendingDevice | null>(null)
|
||||
const [selected, setSelected] = useState<InventoryEntry | null>(null)
|
||||
const [selectMode, setSelectMode] = useState(false)
|
||||
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set())
|
||||
const [search, setSearch] = useState('')
|
||||
@@ -127,15 +135,20 @@ export function PendingDevicesModal({ open, onClose, highlightId, initialStatus
|
||||
const [showOnCanvas, setShowOnCanvas] = useState(true)
|
||||
// Optionally restrict to devices that have at least one detected service.
|
||||
const [withServicesOnly, setWithServicesOnly] = useState(false)
|
||||
// Hardware only — what a rack can hold. On by default when the rack canvas
|
||||
// opens the inventory to pick a mount.
|
||||
const [rackableOnly, setRackableOnly] = useState(initialRackableOnly)
|
||||
const { addNode, scanEventTs } = useCanvasStore()
|
||||
const setSelectedNode = useCanvasStore((s) => s.setSelectedNode)
|
||||
const activeDesignId = useDesignStore((s) => s.activeDesignId)
|
||||
const highlightRef = useRef<HTMLButtonElement>(null)
|
||||
// Set when a single approve is refused because the same host is already on
|
||||
// this design — the user decides: link to the existing node or duplicate.
|
||||
const [dupPrompt, setDupPrompt] = useState<{ device: PendingDevice; conflict: DuplicateNodeConflict } | null>(null)
|
||||
const [dupPrompt, setDupPrompt] = useState<{ device: InventoryEntry; conflict: DuplicateNodeConflict } | null>(null)
|
||||
|
||||
const load = useCallback(async () => {
|
||||
// Tour/demo mode: show injected devices, never touch the backend.
|
||||
if (demoDevices) { setDevices(statusFilter === 'pending' ? demoDevices : []); return }
|
||||
setLoading(true)
|
||||
try {
|
||||
const res = statusFilter === 'pending' ? await scanApi.pending() : await scanApi.hidden()
|
||||
@@ -145,7 +158,7 @@ export function PendingDevicesModal({ open, onClose, highlightId, initialStatus
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [statusFilter])
|
||||
}, [statusFilter, demoDevices])
|
||||
|
||||
useEffect(() => { if (open) load() }, [open, load])
|
||||
useEffect(() => { if (open && scanEventTs > 0) load() }, [scanEventTs, open, load])
|
||||
@@ -158,12 +171,15 @@ export function PendingDevicesModal({ open, onClose, highlightId, initialStatus
|
||||
setSearch('')
|
||||
} else {
|
||||
setStatusFilter(initialStatus)
|
||||
// Reopening from the rack picker must re-arm the filter even if the user
|
||||
// turned it off during the previous visit.
|
||||
setRackableOnly(initialRackableOnly)
|
||||
}
|
||||
}, [open, initialStatus])
|
||||
}, [open, initialStatus, initialRackableOnly])
|
||||
|
||||
const distinctTypes = useMemo(() => {
|
||||
const set = new Set<string>()
|
||||
devices.forEach((d) => { if (d.suggested_type) set.add(d.suggested_type) })
|
||||
devices.forEach((d) => { const t = deviceType(d); if (t) set.add(t) })
|
||||
return [...set].sort()
|
||||
}, [devices])
|
||||
|
||||
@@ -171,10 +187,11 @@ export function PendingDevicesModal({ open, onClose, highlightId, initialStatus
|
||||
const q = search.trim().toLowerCase()
|
||||
return devices.filter((d) => {
|
||||
if (sourceFilter !== 'all' && !sourceBuckets(d).has(sourceFilter)) return false
|
||||
if (typeFilter !== 'all' && d.suggested_type !== typeFilter) return false
|
||||
if (typeFilter !== 'all' && deviceType(d) !== typeFilter) return false
|
||||
// Inventory-only: optionally hide devices already placed on a canvas.
|
||||
if (statusFilter === 'pending' && !showOnCanvas && (d.canvas_count ?? 0) > 0) return false
|
||||
if (withServicesOnly && (d.services?.length ?? 0) === 0) return false
|
||||
if (rackableOnly && !isRackable(d)) return false
|
||||
if (q) {
|
||||
const hay = [
|
||||
d.friendly_name, d.hostname, d.ip, d.mac, d.ieee_address, d.vendor, d.model,
|
||||
@@ -184,7 +201,7 @@ export function PendingDevicesModal({ open, onClose, highlightId, initialStatus
|
||||
}
|
||||
return true
|
||||
})
|
||||
}, [devices, search, sourceFilter, typeFilter, statusFilter, showOnCanvas, withServicesOnly])
|
||||
}, [devices, search, sourceFilter, typeFilter, statusFilter, showOnCanvas, withServicesOnly, rackableOnly])
|
||||
|
||||
useEffect(() => {
|
||||
if (!highlightId || loading || !open) return
|
||||
@@ -199,13 +216,16 @@ export function PendingDevicesModal({ open, onClose, highlightId, initialStatus
|
||||
})
|
||||
}
|
||||
|
||||
const handleCardClick = (d: PendingDevice) => {
|
||||
const handleCardClick = (d: InventoryEntry) => {
|
||||
// Picker mode wins over everything else: the caller opened this list to get
|
||||
// one device back, not to approve or hide anything.
|
||||
if (onPick) { onPick(d); return }
|
||||
if (selectMode) { toggleSelect(d.id); return }
|
||||
if (statusFilter === 'hidden') { handleRestore(d); return }
|
||||
setSelected(d)
|
||||
}
|
||||
|
||||
const handleRestore = async (device: PendingDevice) => {
|
||||
const handleRestore = async (device: InventoryEntry) => {
|
||||
try {
|
||||
await scanApi.restore(device.id)
|
||||
setDevices((prev) => prev.filter((d) => d.id !== device.id))
|
||||
@@ -271,9 +291,15 @@ export function PendingDevicesModal({ open, onClose, highlightId, initialStatus
|
||||
|
||||
// force=true is sent only after the user confirms they want a duplicate node
|
||||
// on this design (the backend otherwise 409s to let us ask).
|
||||
const approveDevice = async (device: PendingDevice, force = false) => {
|
||||
const approveDevice = async (device: InventoryEntry, force = false) => {
|
||||
// Rack gear documents a mount, not a host: it stays out of logical canvases.
|
||||
// The backend refuses it too — this is the friendly half of the guard.
|
||||
if (isRackDevice(device)) {
|
||||
toast.error('Rack devices belong to a rack canvas, not a logical one')
|
||||
return
|
||||
}
|
||||
const fallbackLabel = deviceLabel(device)
|
||||
const type = (device.suggested_type ?? 'generic') as NodeType
|
||||
const type = deviceType(device) ?? 'generic'
|
||||
const zwave = isZwaveType(type)
|
||||
const wireless = isZigbeeType(type) || zwave
|
||||
const properties = zwave
|
||||
@@ -325,7 +351,7 @@ export function PendingDevicesModal({ open, onClose, highlightId, initialStatus
|
||||
}
|
||||
}
|
||||
|
||||
const handleApprove = (device: PendingDevice) => approveDevice(device, false)
|
||||
const handleApprove = (device: InventoryEntry) => approveDevice(device, false)
|
||||
|
||||
const goToExistingNode = (nodeId: string) => {
|
||||
setSelectedNode(nodeId)
|
||||
@@ -334,7 +360,7 @@ export function PendingDevicesModal({ open, onClose, highlightId, initialStatus
|
||||
onClose()
|
||||
}
|
||||
|
||||
const handleHide = async (device: PendingDevice) => {
|
||||
const handleHide = async (device: InventoryEntry) => {
|
||||
try {
|
||||
await scanApi.hide(device.id)
|
||||
setDevices((prev) => prev.filter((d) => d.id !== device.id))
|
||||
@@ -345,7 +371,7 @@ export function PendingDevicesModal({ open, onClose, highlightId, initialStatus
|
||||
}
|
||||
}
|
||||
|
||||
const handleIgnore = async (device: PendingDevice) => {
|
||||
const handleIgnore = async (device: InventoryEntry) => {
|
||||
try {
|
||||
await scanApi.ignore(device.id)
|
||||
setDevices((prev) => prev.filter((d) => d.id !== device.id))
|
||||
@@ -356,7 +382,14 @@ export function PendingDevicesModal({ open, onClose, highlightId, initialStatus
|
||||
}
|
||||
|
||||
const handleBulkApprove = async () => {
|
||||
const ids = [...selectedIds]
|
||||
const rackIds = new Set(devices.filter(isRackDevice).map((d) => d.id))
|
||||
const ids = [...selectedIds].filter((id) => !rackIds.has(id))
|
||||
const skippedRack = selectedIds.size - ids.length
|
||||
if (skippedRack > 0) {
|
||||
toast.error(
|
||||
`${skippedRack} rack device${skippedRack > 1 ? 's' : ''} skipped — they belong to a rack canvas`,
|
||||
)
|
||||
}
|
||||
if (ids.length === 0) return
|
||||
try {
|
||||
const res = await scanApi.bulkApprove(ids, activeDesignId)
|
||||
@@ -369,7 +402,7 @@ export function PendingDevicesModal({ open, onClose, highlightId, initialStatus
|
||||
approvedDevices.forEach((d, i) => {
|
||||
const nodeId = deviceToNode[d.id]
|
||||
if (!nodeId) return
|
||||
const type = (d.suggested_type ?? 'generic') as NodeType
|
||||
const type = deviceType(d) ?? 'generic'
|
||||
const zwave = isZwaveType(type)
|
||||
const wireless = isZigbeeType(type) || zwave
|
||||
addNode({
|
||||
@@ -442,6 +475,9 @@ export function PendingDevicesModal({ open, onClose, highlightId, initialStatus
|
||||
}
|
||||
if (inField) return
|
||||
if (e.key === '/') { e.preventDefault(); searchRef.current?.focus() }
|
||||
// Bulk actions are meaningless in picker mode — the card click returns a
|
||||
// device, so select mode must stay unreachable from the keyboard too.
|
||||
else if (onPick) return
|
||||
else if (e.key.toLowerCase() === 's') { e.preventDefault(); if (selectMode) exitSelectMode(); else enterSelectMode() }
|
||||
else if (e.key.toLowerCase() === 'a' && selectMode) { e.preventDefault(); selectAllVisible() }
|
||||
else if (e.key === 'Enter' && selectMode && selectedIds.size > 0) {
|
||||
@@ -457,7 +493,7 @@ export function PendingDevicesModal({ open, onClose, highlightId, initialStatus
|
||||
// statusFilter is included so Enter dispatches the correct bulk action
|
||||
// (approve vs restore) even if the device list doesn't change on switch.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [open, selectMode, selectedIds, filtered, statusFilter])
|
||||
}, [open, selectMode, selectedIds, filtered, statusFilter, onPick])
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -469,7 +505,7 @@ export function PendingDevicesModal({ open, onClose, highlightId, initialStatus
|
||||
<DialogHeader className="px-4 py-3 border-b border-border shrink-0">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<DialogTitle className="text-base font-semibold flex items-center gap-2">
|
||||
{statusFilter === 'pending' ? 'Device Inventory' : 'Hidden Devices'}
|
||||
{onPick ? 'Pick a Device' : statusFilter === 'pending' ? 'Device Inventory' : 'Hidden Devices'}
|
||||
<span className="text-muted-foreground font-normal text-xs">
|
||||
({filtered.length}{filtered.length !== devices.length && ` of ${devices.length}`})
|
||||
</span>
|
||||
@@ -478,7 +514,8 @@ export function PendingDevicesModal({ open, onClose, highlightId, initialStatus
|
||||
<button onClick={load} className="text-muted-foreground hover:text-foreground p-1.5 rounded transition-colors" title="Refresh">
|
||||
<RefreshCw size={14} />
|
||||
</button>
|
||||
{statusFilter === 'pending' && devices.length > 0 && (
|
||||
{/* Never offer a destructive bulk clear from a picker. */}
|
||||
{!onPick && statusFilter === 'pending' && devices.length > 0 && (
|
||||
<button
|
||||
onClick={handleClearAll}
|
||||
className="text-muted-foreground hover:text-[#f85149] p-1.5 rounded transition-colors"
|
||||
@@ -547,6 +584,20 @@ export function PendingDevicesModal({ open, onClose, highlightId, initialStatus
|
||||
>
|
||||
Proxmox
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setSourceFilter('rack')}
|
||||
className={`px-2.5 py-1.5 transition-colors border-l border-border ${sourceFilter === 'rack' ? 'bg-[#39d353]/20 text-[#39d353]' : 'bg-[#0d1117] text-muted-foreground hover:text-foreground'}`}
|
||||
title="Gear created from a rack canvas"
|
||||
>
|
||||
Rack devices
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setSourceFilter('canvas')}
|
||||
className={`px-2.5 py-1.5 transition-colors border-l border-border ${sourceFilter === 'canvas' ? 'bg-[#8b949e]/20 text-foreground' : 'bg-[#0d1117] text-muted-foreground hover:text-foreground'}`}
|
||||
title="Documented directly on a canvas — no scan ever saw it"
|
||||
>
|
||||
Canvas
|
||||
</button>
|
||||
</div>
|
||||
<select
|
||||
value={typeFilter}
|
||||
@@ -591,6 +642,16 @@ export function PendingDevicesModal({ open, onClose, highlightId, initialStatus
|
||||
<ServerCog size={12} />
|
||||
With services
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setRackableOnly((v) => !v)}
|
||||
className={`flex items-center gap-1.5 text-xs px-2.5 py-1.5 rounded border transition-colors ${rackableOnly ? 'bg-[#39d353]/20 text-[#39d353] border-[#39d353]/50' : 'bg-[#0d1117] text-muted-foreground border-border hover:text-foreground'}`}
|
||||
title="Only show hardware you could mount in a rack (no VMs, containers or mesh devices)"
|
||||
aria-pressed={rackableOnly}
|
||||
>
|
||||
<Server size={12} />
|
||||
Rackable
|
||||
</button>
|
||||
{!onPick && (
|
||||
<button
|
||||
onClick={() => selectMode ? exitSelectMode() : enterSelectMode()}
|
||||
className={`text-xs px-2.5 py-1.5 rounded border transition-colors ${selectMode ? 'bg-[#00d4ff]/20 text-[#00d4ff] border-[#00d4ff]/50' : 'bg-[#0d1117] text-muted-foreground border-border hover:text-foreground'}`}
|
||||
@@ -598,6 +659,7 @@ export function PendingDevicesModal({ open, onClose, highlightId, initialStatus
|
||||
>
|
||||
{selectMode ? 'Exit select' : 'Select mode'}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Body */}
|
||||
@@ -734,19 +796,25 @@ export function PendingDevicesModal({ open, onClose, highlightId, initialStatus
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<PendingDeviceModal
|
||||
<InventoryDeviceModal
|
||||
device={selected}
|
||||
onClose={() => setSelected(null)}
|
||||
onApprove={handleApprove}
|
||||
onHide={handleHide}
|
||||
onIgnore={handleIgnore}
|
||||
onSaved={(saved) => {
|
||||
// Patch in place rather than refetch: the grid keeps its scroll
|
||||
// position and the open detail modal keeps showing the same device.
|
||||
setDevices((prev) => prev.map((d) => (d.id === saved.id ? saved : d)))
|
||||
setSelected(saved)
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
interface DeviceCardProps {
|
||||
device: PendingDevice
|
||||
device: InventoryEntry
|
||||
selected: boolean
|
||||
selectMode: boolean
|
||||
highlighted: boolean
|
||||
@@ -756,8 +824,8 @@ interface DeviceCardProps {
|
||||
|
||||
function DeviceCard({ device, selected, selectMode, highlighted, onClick, cardRef }: DeviceCardProps) {
|
||||
const sources = orderedSources(device)
|
||||
const roleType = (device.suggested_type ?? 'generic') as NodeType
|
||||
const Icon = TYPE_ICONS[roleType] ?? Circle
|
||||
const roleType = deviceType(device) ?? 'generic'
|
||||
const Icon = NODE_TYPE_DEFAULT_ICONS[roleType] ?? NODE_TYPE_DEFAULT_ICONS.generic
|
||||
const activeTheme = useThemeStore((s) => s.activeTheme)
|
||||
// Colour the role badge with the same accent the node uses on the canvas
|
||||
// (from the active theme / style section), instead of a flat grey.
|
||||
@@ -835,12 +903,12 @@ function DeviceCard({ device, selected, selectMode, highlighted, onClick, cardRe
|
||||
{SOURCE_META[s].label}
|
||||
</span>
|
||||
))}
|
||||
{device.suggested_type && (
|
||||
{roleType !== 'generic' && (
|
||||
<span
|
||||
className="text-[9px] font-mono px-1.5 py-0.5 rounded uppercase tracking-wider"
|
||||
style={{ background: `${roleColor}22`, color: roleColor }}
|
||||
>
|
||||
{device.suggested_type}
|
||||
{roleType}
|
||||
</span>
|
||||
)}
|
||||
{device.lqi != null && (
|
||||
@@ -120,12 +120,17 @@ export function GroupRectModal({ open, onClose, onSubmit, onDelete, initial, tit
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={(o) => !o && onClose()}>
|
||||
<DialogContent className="bg-[#161b22] border-[#30363d] text-foreground max-w-sm">
|
||||
<DialogContent className="bg-[#161b22] border-[#30363d] text-foreground max-w-[calc(100%-2rem)] sm:max-w-3xl max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-sm font-semibold">{title}</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<form onSubmit={handleSubmit} className="flex flex-col gap-4 mt-2">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-x-6 gap-y-4">
|
||||
{/* ── LEFT column: content & text ── */}
|
||||
<div className="flex flex-col gap-4 min-w-0">
|
||||
<div className="text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/70 pb-1 border-b border-[#30363d]">Content</div>
|
||||
|
||||
{/* Label */}
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label className="text-xs text-muted-foreground">Label</Label>
|
||||
@@ -209,6 +214,38 @@ export function GroupRectModal({ open, onClose, onSubmit, onDelete, initial, tit
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Text size */}
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label className="text-xs text-muted-foreground">Text Size</Label>
|
||||
<div className="grid grid-cols-6 gap-1">
|
||||
{TEXT_SIZES.map(({ value, label }) => {
|
||||
const isSelected = form.text_size === value
|
||||
return (
|
||||
<button
|
||||
key={value}
|
||||
type="button"
|
||||
onClick={() => set('text_size', value)}
|
||||
className={`flex items-center justify-center h-8 rounded transition-colors cursor-pointer ${modalStyles['modal-interactive']}`}
|
||||
aria-label={`Text size ${label}`}
|
||||
style={{
|
||||
background: isSelected ? '#00d4ff22' : '#21262d',
|
||||
border: `1px solid ${isSelected ? '#00d4ff88' : '#30363d'}`,
|
||||
color: isSelected ? '#00d4ff' : '#8b949e',
|
||||
fontSize: value,
|
||||
}}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>{/* ── end LEFT column ── */}
|
||||
|
||||
{/* ── RIGHT column: style ── */}
|
||||
<div className="flex flex-col gap-4 min-w-0">
|
||||
<div className="text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/70 pb-1 border-b border-[#30363d]">Style</div>
|
||||
|
||||
{/* Colors */}
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label className="text-xs text-muted-foreground">Colors</Label>
|
||||
@@ -245,33 +282,6 @@ export function GroupRectModal({ open, onClose, onSubmit, onDelete, initial, tit
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Text size */}
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label className="text-xs text-muted-foreground">Text Size</Label>
|
||||
<div className="grid grid-cols-6 gap-1">
|
||||
{TEXT_SIZES.map(({ value, label }) => {
|
||||
const isSelected = form.text_size === value
|
||||
return (
|
||||
<button
|
||||
key={value}
|
||||
type="button"
|
||||
onClick={() => set('text_size', value)}
|
||||
className={`flex items-center justify-center h-8 rounded transition-colors cursor-pointer ${modalStyles['modal-interactive']}`}
|
||||
aria-label={`Text size ${label}`}
|
||||
style={{
|
||||
background: isSelected ? '#00d4ff22' : '#21262d',
|
||||
border: `1px solid ${isSelected ? '#00d4ff88' : '#30363d'}`,
|
||||
color: isSelected ? '#00d4ff' : '#8b949e',
|
||||
fontSize: value,
|
||||
}}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Border style */}
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label className="text-xs text-muted-foreground">Border Style</Label>
|
||||
@@ -342,6 +352,8 @@ export function GroupRectModal({ open, onClose, onSubmit, onDelete, initial, tit
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>{/* ── end RIGHT column ── */}
|
||||
</div>{/* ── end 2-column grid ── */}
|
||||
|
||||
<div className="flex justify-between gap-2 pt-1">
|
||||
{onDelete && (
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
import { createElement, useState } from 'react'
|
||||
import modalStyles from './modal-interactive.module.css'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { ICON_REGISTRY, ICON_CATEGORIES, isBrandIconKey } from '@/utils/nodeIcons'
|
||||
import { BrandIconPicker } from './BrandIconPicker'
|
||||
|
||||
interface IconPickerPanelProps {
|
||||
/** Current icon key — a lucide registry key or `brand:<slug>`. */
|
||||
value?: string
|
||||
/** Called with the new key, or `undefined` when the current generic icon is toggled off. */
|
||||
onSelect: (key: string | undefined) => void
|
||||
/** Focus the generic-icon search field on mount. */
|
||||
autoFocus?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared Generic/Brand icon picker body. Used by NodeModal and ServiceModal so
|
||||
* both surfaces offer the same lucide registry + dashboard-icons brand catalog.
|
||||
*/
|
||||
export function IconPickerPanel({ value, onSelect, autoFocus }: IconPickerPanelProps) {
|
||||
const [search, setSearch] = useState('')
|
||||
const [tab, setTab] = useState<'generic' | 'brand'>(isBrandIconKey(value) ? 'brand' : 'generic')
|
||||
|
||||
const tabClass = (active: boolean) =>
|
||||
`text-[11px] px-2 py-1 rounded transition-colors cursor-pointer ${
|
||||
active ? 'bg-[#21262d] text-foreground border border-[#30363d]' : 'text-muted-foreground hover:text-foreground'
|
||||
}`
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-2 p-2.5 rounded-md bg-[#0d1117] border border-[#30363d]">
|
||||
<div className="flex gap-1 mb-1" role="tablist" aria-label="Icon source">
|
||||
<button type="button" role="tab" aria-selected={tab === 'generic'} onClick={() => setTab('generic')} className={tabClass(tab === 'generic')}>
|
||||
Generic
|
||||
</button>
|
||||
<button type="button" role="tab" aria-selected={tab === 'brand'} onClick={() => setTab('brand')} className={tabClass(tab === 'brand')}>
|
||||
Brand
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{tab === 'brand' ? (
|
||||
<BrandIconPicker value={value} onSelect={onSelect} />
|
||||
) : (
|
||||
<>
|
||||
<Input
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
placeholder="Search icons…"
|
||||
className={`bg-[#21262d] border-[#30363d] text-xs h-7 ${modalStyles['modal-radius']}`}
|
||||
autoFocus={autoFocus}
|
||||
/>
|
||||
<div className="flex flex-col gap-2 max-h-52 overflow-y-auto">
|
||||
{ICON_CATEGORIES.map((cat) => {
|
||||
const q = search.toLowerCase()
|
||||
const entries = ICON_REGISTRY.filter(
|
||||
(e) => e.category === cat && (search === '' || e.label.toLowerCase().includes(q) || e.key.includes(q))
|
||||
)
|
||||
if (entries.length === 0) return null
|
||||
return (
|
||||
<div key={cat}>
|
||||
<p className="text-[9px] font-semibold text-muted-foreground/50 uppercase tracking-wider mb-1">{cat}</p>
|
||||
<div className="grid grid-cols-7 gap-1">
|
||||
{entries.map((entry) => {
|
||||
const isSelected = value === entry.key
|
||||
return (
|
||||
<button
|
||||
key={entry.key}
|
||||
type="button"
|
||||
title={entry.label}
|
||||
onClick={() => onSelect(isSelected ? undefined : entry.key)}
|
||||
className={`flex items-center justify-center w-7 h-7 rounded transition-colors cursor-pointer ${modalStyles['modal-interactive']}`}
|
||||
aria-label={`Select icon ${entry.label}`}
|
||||
style={{
|
||||
background: isSelected ? '#00d4ff22' : 'transparent',
|
||||
border: isSelected ? '1px solid #00d4ff88' : '1px solid transparent',
|
||||
color: isSelected ? '#00d4ff' : '#8b949e',
|
||||
}}
|
||||
onMouseEnter={(e) => { if (!isSelected) (e.currentTarget as HTMLButtonElement).style.background = '#21262d' }}
|
||||
onMouseLeave={(e) => { if (!isSelected) (e.currentTarget as HTMLButtonElement).style.background = 'transparent' }}
|
||||
>
|
||||
{createElement(entry.icon, { size: 13 })}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,770 @@
|
||||
/**
|
||||
* Device Inventory detail — show *and* edit.
|
||||
*
|
||||
* The inventory row owns what a device is; a canvas node only owns how it is
|
||||
* drawn. So everything a user can curate on a node — properties, services,
|
||||
* notes, check method — is editable here too, through the same editors the
|
||||
* canvas uses (`PropertyList`, `ServiceModal`).
|
||||
*
|
||||
* Hardware specs are properties like any other: `cpu_*` / `ram_gb` / `disk_gb`
|
||||
* still carry what Proxmox and the YAML import record, but nothing draws them,
|
||||
* so they are not edited here — CPU / RAM / Disk are property suggestions.
|
||||
*
|
||||
* Layout mirrors `NodeModal`: one wide dialog, a header carrying identity and
|
||||
* badges, then three columns — identity / operations / curation — so a device
|
||||
* reads in one screen instead of a scrolling column of key-value pairs.
|
||||
*/
|
||||
import { useEffect, useState } from 'react'
|
||||
import {
|
||||
Check,
|
||||
Copy,
|
||||
Factory,
|
||||
Fingerprint,
|
||||
HeartPulse,
|
||||
History,
|
||||
Layers,
|
||||
Network,
|
||||
Pencil,
|
||||
Plus,
|
||||
StickyNote,
|
||||
Tags,
|
||||
X,
|
||||
type LucideIcon,
|
||||
} from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectSeparator, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import { PropertyList } from '@/components/common/PropertyList'
|
||||
import { ServiceModal } from './ServiceModal'
|
||||
import { scanApi } from '@/api/client'
|
||||
import { useCanvasStore } from '@/stores/canvasStore'
|
||||
import { useThemeStore } from '@/stores/themeStore'
|
||||
import { deviceFactsToNodeData } from '@/utils/deviceFacts'
|
||||
import { resolveNodeColors } from '@/utils/nodeColors'
|
||||
import { NODE_TYPE_DEFAULT_ICONS } from '@/utils/nodeIcons'
|
||||
import { isRackDevice, orderedSources, SOURCE_META } from '@/utils/deviceSources'
|
||||
import { DEVICE_TYPE_GROUPS } from '@/utils/nodeTypeGroups'
|
||||
import { formatRelative, formatTimestamp } from '@/utils/timeFormat'
|
||||
import { serviceToForm, type ServiceFormData, type ServiceSubmitData } from '@/utils/serviceForm'
|
||||
import { NODE_TYPE_LABELS, type CheckMethod, type InventoryEntry, type NodeProperty, type NodeType, type ServiceInfo } from '@/types'
|
||||
import modalStyles from './modal-interactive.module.css'
|
||||
|
||||
// Home is `@/types` now — re-exported because most call sites import it here.
|
||||
export type { InventoryEntry } from '@/types'
|
||||
|
||||
interface InventoryDeviceModalProps {
|
||||
device: InventoryEntry | null
|
||||
onClose: () => void
|
||||
onApprove: (device: InventoryEntry) => void
|
||||
onHide: (device: InventoryEntry) => void
|
||||
onIgnore: (device: InventoryEntry) => void
|
||||
/** Called with the saved row after an edit, so the list can refresh in place. */
|
||||
onSaved?: (device: InventoryEntry) => void
|
||||
}
|
||||
|
||||
const CATEGORY_COLORS: Record<string, string> = {
|
||||
hypervisor: '#ff6e00',
|
||||
nas: '#39d353',
|
||||
automation: '#a855f7',
|
||||
containers: '#00d4ff',
|
||||
network: '#39d353',
|
||||
security: '#f85149',
|
||||
monitoring: '#e3b341',
|
||||
database: '#a855f7',
|
||||
web: '#00d4ff',
|
||||
media: '#ff6e00',
|
||||
iot: '#e3b341',
|
||||
}
|
||||
|
||||
const CHECK_METHODS: CheckMethod[] = ['ping', 'http', 'https', 'tcp', 'ssh', 'prometheus', 'health', 'none']
|
||||
|
||||
const CHECK_METHOD_LABELS: Record<CheckMethod, string> = {
|
||||
none: 'None',
|
||||
ping: 'Ping',
|
||||
http: 'HTTP',
|
||||
https: 'HTTPS',
|
||||
tcp: 'TCP',
|
||||
ssh: 'SSH',
|
||||
prometheus: 'Prometheus',
|
||||
health: 'Health',
|
||||
}
|
||||
|
||||
/** Live reachability — not the pending/approved/hidden lifecycle. */
|
||||
const LIVE_META: Record<string, { color: string; label: string }> = {
|
||||
online: { color: '#39d353', label: 'Online' },
|
||||
offline: { color: '#f85149', label: 'Offline' },
|
||||
pending: { color: '#e3b341', label: 'Checking' },
|
||||
unknown: { color: '#8b949e', label: 'Unknown' },
|
||||
}
|
||||
|
||||
const INPUT = 'bg-[#21262d] border-[#30363d] text-sm h-8'
|
||||
|
||||
function categoryColor(category: string | null | undefined) {
|
||||
if (!category) return '#8b949e'
|
||||
return CATEGORY_COLORS[category.toLowerCase()] ?? '#8b949e'
|
||||
}
|
||||
|
||||
/** A section card: heading bar with its icon, optional action, body. */
|
||||
function Section({
|
||||
title,
|
||||
icon: Icon,
|
||||
action,
|
||||
children,
|
||||
}: {
|
||||
title: string
|
||||
icon: LucideIcon
|
||||
action?: React.ReactNode
|
||||
children: React.ReactNode
|
||||
}) {
|
||||
return (
|
||||
<section className="rounded-lg border border-[#30363d] bg-[#161b22] overflow-hidden">
|
||||
<header className="flex items-center justify-between gap-2 px-3 py-2 border-b border-[#30363d] bg-[#0d1117]/50">
|
||||
<span className="flex items-center gap-1.5 text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">
|
||||
<Icon size={12} className="text-muted-foreground/70" aria-hidden />
|
||||
{title}
|
||||
</span>
|
||||
{action}
|
||||
</header>
|
||||
<div className="p-3">{children}</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
function Chip({ color, children, title }: { color: string; children: React.ReactNode; title?: string }) {
|
||||
return (
|
||||
<span
|
||||
title={title}
|
||||
className="text-[9px] font-mono px-1.5 py-0.5 rounded uppercase tracking-wider"
|
||||
style={{ background: `${color}22`, color }}
|
||||
>
|
||||
{children}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
/** Copies a technical value; the row keeps its own confirmation state. */
|
||||
function CopyButton({ label, value }: { label: string; value: string }) {
|
||||
const [copied, setCopied] = useState(false)
|
||||
const copy = () => {
|
||||
// `clipboard` is absent outside a secure context (and in jsdom), so the
|
||||
// promise itself is optional, not just the API.
|
||||
const written = navigator.clipboard?.writeText(value)
|
||||
if (!written) return
|
||||
written
|
||||
.then(() => {
|
||||
setCopied(true)
|
||||
setTimeout(() => setCopied(false), 1200)
|
||||
})
|
||||
.catch(() => toast.error('Could not copy'))
|
||||
}
|
||||
return (
|
||||
<button
|
||||
onClick={copy}
|
||||
aria-label={`Copy ${label}`}
|
||||
className="ml-auto shrink-0 text-muted-foreground/50 opacity-0 group-hover:opacity-100 focus-visible:opacity-100 hover:text-[#00d4ff] transition-opacity cursor-pointer"
|
||||
>
|
||||
{copied ? <Check size={11} className="text-[#39d353]" /> : <Copy size={11} />}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
function InfoRow({ label, value, copyable }: { label: string; value: string; copyable?: boolean }) {
|
||||
return (
|
||||
<div className="group flex items-baseline gap-3 py-1 border-b border-[#30363d]/40 last:border-b-0 text-xs">
|
||||
<span className="w-20 shrink-0 text-[11px] text-muted-foreground">{label}</span>
|
||||
<span className="min-w-0 font-mono text-foreground break-all">{value}</span>
|
||||
{copyable && <CopyButton label={label} value={value} />}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** A timestamp reads relative, with the exact value on hover. */
|
||||
function TimeRow({ label, iso }: { label: string; iso: string }) {
|
||||
return (
|
||||
<div className="flex items-baseline gap-3 py-1 border-b border-[#30363d]/40 last:border-b-0 text-xs" title={formatTimestamp(iso)}>
|
||||
<span className="w-20 shrink-0 text-[11px] text-muted-foreground">{label}</span>
|
||||
<span className="font-mono text-foreground/80">{formatRelative(iso)}</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function Empty({ children }: { children: React.ReactNode }) {
|
||||
return <p className="text-xs text-muted-foreground italic">{children}</p>
|
||||
}
|
||||
|
||||
function Field({ label, hint, children, className = '' }: { label: string; hint?: string; children: React.ReactNode; className?: string }) {
|
||||
return (
|
||||
<div className={`flex flex-col gap-1.5 min-w-0 ${className}`}>
|
||||
<Label className="text-xs text-muted-foreground">{label}</Label>
|
||||
{children}
|
||||
{hint && <span className="text-[10px] text-muted-foreground/50">{hint}</span>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** The editable subset of an inventory row, as strings for the form inputs. */
|
||||
interface EditForm {
|
||||
label: string
|
||||
type: string
|
||||
hostname: string
|
||||
ip: string
|
||||
mac: string
|
||||
os: string
|
||||
vendor: string
|
||||
model: string
|
||||
friendly_name: string
|
||||
device_subtype: string
|
||||
notes: string
|
||||
cpu_count: string
|
||||
cpu_model: string
|
||||
ram_gb: string
|
||||
disk_gb: string
|
||||
show_hardware: boolean
|
||||
check_method: string
|
||||
check_target: string
|
||||
}
|
||||
|
||||
function toForm(d: InventoryEntry): EditForm {
|
||||
return {
|
||||
label: d.label ?? '',
|
||||
// Falls back to the discovery guess, so a first edit adopts it rather than
|
||||
// silently clearing what the scanner suggested.
|
||||
type: d.type ?? d.suggested_type ?? '',
|
||||
hostname: d.hostname ?? '',
|
||||
ip: d.ip ?? '',
|
||||
mac: d.mac ?? '',
|
||||
os: d.os ?? '',
|
||||
vendor: d.vendor ?? '',
|
||||
model: d.model ?? '',
|
||||
friendly_name: d.friendly_name ?? '',
|
||||
device_subtype: d.device_subtype ?? '',
|
||||
notes: d.notes ?? '',
|
||||
cpu_count: d.cpu_count != null ? String(d.cpu_count) : '',
|
||||
cpu_model: d.cpu_model ?? '',
|
||||
ram_gb: d.ram_gb != null ? String(d.ram_gb) : '',
|
||||
disk_gb: d.disk_gb != null ? String(d.disk_gb) : '',
|
||||
show_hardware: d.show_hardware ?? false,
|
||||
check_method: d.check_method ?? '',
|
||||
check_target: d.check_target ?? '',
|
||||
}
|
||||
}
|
||||
|
||||
const nullable = (v: string) => (v.trim() === '' ? null : v.trim())
|
||||
const numeric = (v: string) => (v.trim() === '' ? null : Number(v))
|
||||
|
||||
export function InventoryDeviceModal({ device, onClose, onApprove, onHide, onIgnore, onSaved }: InventoryDeviceModalProps) {
|
||||
const [editing, setEditing] = useState(false)
|
||||
const [form, setForm] = useState<EditForm>(() => (device ? toForm(device) : toForm({} as InventoryEntry)))
|
||||
const [properties, setProperties] = useState<NodeProperty[]>(device?.properties ?? [])
|
||||
const [services, setServices] = useState<ServiceInfo[]>(device?.services ?? [])
|
||||
const [svcModal, setSvcModal] = useState<{ index: number | null; form?: ServiceFormData } | null>(null)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const activeTheme = useThemeStore((s) => s.activeTheme)
|
||||
|
||||
// Reset the form whenever the modal is pointed at another device — the
|
||||
// component stays mounted across card clicks in the inventory grid.
|
||||
useEffect(() => {
|
||||
if (!device) return
|
||||
setForm(toForm(device))
|
||||
setProperties(device.properties ?? [])
|
||||
setServices(device.services ?? [])
|
||||
setEditing(false)
|
||||
setSvcModal(null)
|
||||
}, [device])
|
||||
|
||||
if (!device) return null
|
||||
|
||||
const resolvedType = (device.type ?? device.suggested_type ?? 'generic') as NodeType
|
||||
const TypeIcon = NODE_TYPE_DEFAULT_ICONS[resolvedType] ?? NODE_TYPE_DEFAULT_ICONS.generic
|
||||
// Same accent the node wears on the canvas, so a device looks like itself.
|
||||
const roleColor = resolveNodeColors({ type: resolvedType, custom_colors: undefined }, activeTheme).border
|
||||
const isZigbee = device.discovery_source === 'zigbee'
|
||||
const rackOnly = isRackDevice(device)
|
||||
const sources = orderedSources(device)
|
||||
const live = LIVE_META[device.status_live ?? 'unknown'] ?? LIVE_META.unknown
|
||||
const titleLabel = device.label ?? device.friendly_name ?? device.hostname ?? device.ip ?? device.ieee_address ?? 'Pending device'
|
||||
|
||||
const set = <K extends keyof EditForm>(key: K, value: EditForm[K]) => setForm((f) => ({ ...f, [key]: value }))
|
||||
|
||||
const handleApprove = () => { onApprove(device) }
|
||||
const handleHide = () => { onHide(device); onClose() }
|
||||
const handleIgnore = () => { onIgnore(device); onClose() }
|
||||
|
||||
const handleCancel = () => {
|
||||
setEditing(false)
|
||||
setForm(toForm(device))
|
||||
setProperties(device.properties ?? [])
|
||||
setServices(device.services ?? [])
|
||||
}
|
||||
|
||||
const handleSubmitService = (data: ServiceSubmitData) => {
|
||||
const svc: ServiceInfo = {
|
||||
...(data.port != null ? { port: data.port } : {}),
|
||||
protocol: data.protocol,
|
||||
service_name: data.service_name,
|
||||
...(data.path ? { path: data.path } : {}),
|
||||
...(data.host ? { host: data.host } : {}),
|
||||
...(data.icon ? { icon: data.icon } : {}),
|
||||
}
|
||||
setServices((prev) =>
|
||||
svcModal?.index == null ? [...prev, svc] : prev.map((s, i) => (i === svcModal.index ? { ...s, ...svc } : s))
|
||||
)
|
||||
}
|
||||
|
||||
const handleSave = async () => {
|
||||
setSaving(true)
|
||||
try {
|
||||
const res = await scanApi.updatePending(device.id, {
|
||||
label: nullable(form.label),
|
||||
type: nullable(form.type),
|
||||
hostname: nullable(form.hostname),
|
||||
ip: nullable(form.ip),
|
||||
mac: nullable(form.mac),
|
||||
os: nullable(form.os),
|
||||
vendor: nullable(form.vendor),
|
||||
model: nullable(form.model),
|
||||
friendly_name: nullable(form.friendly_name),
|
||||
device_subtype: nullable(form.device_subtype),
|
||||
notes: nullable(form.notes),
|
||||
// Hardware is curated as properties, like every other spec — these five
|
||||
// are no longer editable here. They still carry Proxmox and YAML data,
|
||||
// so they go back untouched rather than being silently cleared.
|
||||
cpu_count: numeric(form.cpu_count),
|
||||
cpu_model: nullable(form.cpu_model),
|
||||
ram_gb: numeric(form.ram_gb),
|
||||
disk_gb: numeric(form.disk_gb),
|
||||
show_hardware: form.show_hardware,
|
||||
check_method: nullable(form.check_method) as CheckMethod | null,
|
||||
check_target: nullable(form.check_target),
|
||||
properties,
|
||||
services,
|
||||
})
|
||||
// Push the row straight into the canvas on screen. Its nodes carry a copy
|
||||
// of these facts, loaded before this edit — left stale, the next canvas
|
||||
// save (even one for a moved node) would report them as an edit and roll
|
||||
// the row back.
|
||||
useCanvasStore.getState().applyDeviceFacts(device.id, deviceFactsToNodeData(res.data))
|
||||
toast.success('Device updated')
|
||||
setEditing(false)
|
||||
onSaved?.(res.data)
|
||||
} catch {
|
||||
toast.error('Could not update device')
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const timestamps: { label: string; iso: string }[] = []
|
||||
if (device.discovered_at) timestamps.push({ label: 'Discovered', iso: device.discovered_at })
|
||||
if (device.node_created_at) timestamps.push({ label: 'On canvas', iso: device.node_created_at })
|
||||
if (device.node_last_scan) timestamps.push({ label: 'Last scan', iso: device.node_last_scan })
|
||||
if (device.node_last_seen) timestamps.push({ label: 'Last seen', iso: device.node_last_seen })
|
||||
if (device.node_last_modified) timestamps.push({ label: 'Modified', iso: device.node_last_modified })
|
||||
|
||||
return (
|
||||
<Dialog open={!!device} onOpenChange={(o) => !o && onClose()}>
|
||||
<DialogContent className="!max-w-none w-[min(1180px,95vw)] max-h-[90vh] p-0 gap-0 flex flex-col overflow-hidden bg-[#0d1117] border-[#30363d] text-foreground">
|
||||
{/* ── Header: who this device is, at a glance ── */}
|
||||
<DialogHeader className="shrink-0 px-5 py-4 border-b border-[#30363d] bg-[#161b22]">
|
||||
<div className="flex items-start gap-3 pr-10">
|
||||
<div
|
||||
className="w-11 h-11 shrink-0 rounded-lg border flex items-center justify-center"
|
||||
style={{ background: `${roleColor}18`, borderColor: `${roleColor}55`, color: roleColor }}
|
||||
>
|
||||
<TypeIcon size={20} />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<DialogTitle className="text-base font-semibold leading-tight break-all">{titleLabel}</DialogTitle>
|
||||
<div className="mt-1.5 flex flex-wrap items-center gap-1.5">
|
||||
{sources.map((s) => (
|
||||
<Chip key={s} color={SOURCE_META[s].color}>{SOURCE_META[s].label}</Chip>
|
||||
))}
|
||||
{(device.type ?? device.suggested_type) && (
|
||||
<Chip color={roleColor}>{NODE_TYPE_LABELS[resolvedType] ?? resolvedType}</Chip>
|
||||
)}
|
||||
<span
|
||||
className="flex items-center gap-1 text-[9px] font-mono px-1.5 py-0.5 rounded uppercase tracking-wider"
|
||||
style={{ background: `${live.color}22`, color: live.color }}
|
||||
title="Live reachability"
|
||||
>
|
||||
<span className="w-1.5 h-1.5 rounded-full" style={{ background: live.color }} />
|
||||
{live.label}
|
||||
</span>
|
||||
{(device.canvas_count ?? 0) > 0 && (
|
||||
<span
|
||||
className="flex items-center gap-1 text-[9px] font-mono px-1.5 py-0.5 rounded uppercase tracking-wider bg-[#00d4ff]/15 text-[#00d4ff]"
|
||||
title={`Drawn on ${device.canvas_count} canvas${device.canvas_count !== 1 ? 'es' : ''}`}
|
||||
>
|
||||
<Layers size={10} />
|
||||
{device.canvas_count}
|
||||
</span>
|
||||
)}
|
||||
{device.status === 'hidden' && <Chip color="#8b949e">Hidden</Chip>}
|
||||
{device.lqi != null && <Chip color="#8b949e">LQI {device.lqi}</Chip>}
|
||||
</div>
|
||||
</div>
|
||||
{!editing && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className={`shrink-0 gap-1.5 text-[#00d4ff] hover:text-[#00d4ff] hover:bg-[#00d4ff]/10 ${modalStyles['modal-interactive']}`}
|
||||
onClick={() => setEditing(true)}
|
||||
>
|
||||
<Pencil size={13} /> Edit
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</DialogHeader>
|
||||
|
||||
{/* ── Body: three columns — identity / operations / curation ── */}
|
||||
<div className="flex-1 min-h-0 overflow-y-auto p-5">
|
||||
{editing ? (
|
||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-4 items-start">
|
||||
<div className="flex flex-col gap-4 min-w-0">
|
||||
<Section title="Identity" icon={Fingerprint}>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<Field label="Name" className="col-span-2">
|
||||
<Input value={form.label} onChange={(e) => set('label', e.target.value)} placeholder="Display name" className={INPUT} />
|
||||
</Field>
|
||||
<Field label="Type" className="col-span-2">
|
||||
<Select value={form.type || undefined} onValueChange={(v) => set('type', (v as string | null) ?? '')}>
|
||||
<SelectTrigger className={`${INPUT} w-full cursor-pointer ${modalStyles['modal-interactive']}`} aria-label="Device type selector">
|
||||
<SelectValue placeholder="Pick a type" />
|
||||
</SelectTrigger>
|
||||
<SelectContent className="bg-[#21262d] border-[#30363d]">
|
||||
{DEVICE_TYPE_GROUPS.map((group, i) => (
|
||||
<SelectGroup key={group.label}>
|
||||
{i > 0 && <SelectSeparator className="bg-[#30363d]" />}
|
||||
<SelectLabel className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground/50 px-2 py-1">
|
||||
{group.label}
|
||||
</SelectLabel>
|
||||
{group.types.map((t) => (
|
||||
<SelectItem key={t} value={t} className="text-sm pl-4">
|
||||
{NODE_TYPE_LABELS[t] ?? t}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectGroup>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</Field>
|
||||
<Field label="Hostname">
|
||||
<Input value={form.hostname} onChange={(e) => set('hostname', e.target.value)} placeholder="server.lan" className={`${INPUT} font-mono`} />
|
||||
</Field>
|
||||
<Field label="IP" hint="comma-separated">
|
||||
<Input value={form.ip} onChange={(e) => set('ip', e.target.value)} placeholder="10.0.0.5, 10.0.1.5" className={`${INPUT} font-mono`} />
|
||||
</Field>
|
||||
<Field label="MAC">
|
||||
<Input value={form.mac} onChange={(e) => set('mac', e.target.value)} placeholder="aa:bb:cc:dd:ee:ff" className={`${INPUT} font-mono`} />
|
||||
</Field>
|
||||
<Field label="OS">
|
||||
<Input value={form.os} onChange={(e) => set('os', e.target.value)} placeholder="Debian 12" className={INPUT} />
|
||||
</Field>
|
||||
</div>
|
||||
</Section>
|
||||
|
||||
<Section title="Make & model" icon={Factory}>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<Field label="Vendor">
|
||||
<Input value={form.vendor} onChange={(e) => set('vendor', e.target.value)} className={INPUT} />
|
||||
</Field>
|
||||
<Field label="Model">
|
||||
<Input value={form.model} onChange={(e) => set('model', e.target.value)} className={INPUT} />
|
||||
</Field>
|
||||
<Field label="Friendly name">
|
||||
<Input value={form.friendly_name} onChange={(e) => set('friendly_name', e.target.value)} className={INPUT} />
|
||||
</Field>
|
||||
<Field label="Role">
|
||||
<Input value={form.device_subtype} onChange={(e) => set('device_subtype', e.target.value)} placeholder="e.g. router" className={INPUT} />
|
||||
</Field>
|
||||
</div>
|
||||
</Section>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-4 min-w-0">
|
||||
<Section title="Monitoring" icon={HeartPulse}>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<Field label="Check method">
|
||||
<Select value={form.check_method || undefined} onValueChange={(v) => set('check_method', (v as string | null) ?? '')}>
|
||||
<SelectTrigger className={`${INPUT} w-full cursor-pointer ${modalStyles['modal-interactive']}`} aria-label="Check method selector">
|
||||
<SelectValue placeholder="None" />
|
||||
</SelectTrigger>
|
||||
<SelectContent className="bg-[#21262d] border-[#30363d]">
|
||||
{CHECK_METHODS.map((m) => (
|
||||
<SelectItem key={m} value={m} className="text-sm">{CHECK_METHOD_LABELS[m]}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</Field>
|
||||
<Field label="Check target">
|
||||
<Input value={form.check_target} onChange={(e) => set('check_target', e.target.value)} placeholder="host:port or URL" className={`${INPUT} font-mono`} />
|
||||
</Field>
|
||||
</div>
|
||||
</Section>
|
||||
|
||||
<Section title="Notes" icon={StickyNote}>
|
||||
<Textarea
|
||||
value={form.notes}
|
||||
onChange={(e) => set('notes', e.target.value)}
|
||||
rows={6}
|
||||
placeholder="Anything worth remembering about this device."
|
||||
className="bg-[#21262d] border-[#30363d] text-sm"
|
||||
/>
|
||||
</Section>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-4 min-w-0">
|
||||
{/* Same editors as the canvas — one implementation, one behaviour. */}
|
||||
<section className="rounded-lg border border-[#30363d] bg-[#161b22] overflow-hidden">
|
||||
<PropertyList
|
||||
properties={properties}
|
||||
onChange={setProperties}
|
||||
visibleLabel="Show on node"
|
||||
// Hardware is a property like any other; these are the keys
|
||||
// the Proxmox import and the YAML import already mint.
|
||||
suggestions={['CPU Model', 'CPU Cores', 'RAM', 'Disk']}
|
||||
/>
|
||||
</section>
|
||||
|
||||
<Section
|
||||
title={`Services${services.length > 0 ? ` (${services.length})` : ''}`}
|
||||
icon={Network}
|
||||
action={
|
||||
<button
|
||||
onClick={() => setSvcModal({ index: null })}
|
||||
className="flex items-center gap-1 text-[10px] text-[#00d4ff] hover:text-[#00d4ff]/80 transition-colors cursor-pointer"
|
||||
>
|
||||
<Plus size={10} /> Add
|
||||
</button>
|
||||
}
|
||||
>
|
||||
{services.length === 0 ? (
|
||||
<Empty>No services — click Add to register one.</Empty>
|
||||
) : (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
{services.map((svc, i) => (
|
||||
<div key={`${svc.port ?? 'host'}-${svc.protocol}-${i}`} className="group flex items-center gap-2 px-2.5 py-1.5 rounded-md bg-[#21262d] border border-[#30363d] text-xs">
|
||||
<span className="font-mono text-[#00d4ff] w-10 shrink-0">{svc.port ?? '—'}</span>
|
||||
<span className="text-muted-foreground w-8 shrink-0">{svc.protocol}</span>
|
||||
<span className="text-foreground truncate">{svc.service_name}</span>
|
||||
<div className="ml-auto flex items-center gap-1.5 shrink-0">
|
||||
<button
|
||||
onClick={() => setSvcModal({ index: i, form: serviceToForm(svc) })}
|
||||
title="Edit service"
|
||||
className="text-[#8b949e] hover:text-[#00d4ff] cursor-pointer"
|
||||
>
|
||||
<Pencil size={11} />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setServices((prev) => prev.filter((_, j) => j !== i))}
|
||||
title="Remove service"
|
||||
className="text-[#8b949e] hover:text-[#f85149] cursor-pointer"
|
||||
>
|
||||
<X size={11} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</Section>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-4 items-start">
|
||||
{/* What the device is: how to reach it, and what answers there. */}
|
||||
<div className="flex flex-col gap-4 min-w-0" data-testid="device-column-identity">
|
||||
<Section title="Identity" icon={Fingerprint}>
|
||||
<div className="flex flex-col">
|
||||
{device.ip && <InfoRow label="IP" value={device.ip} copyable />}
|
||||
{device.hostname && <InfoRow label="Hostname" value={device.hostname} copyable />}
|
||||
{device.mac && <InfoRow label="MAC" value={device.mac} copyable />}
|
||||
{device.ieee_address && <InfoRow label="IEEE" value={device.ieee_address} copyable />}
|
||||
{device.os && <InfoRow label="OS" value={device.os} />}
|
||||
{(device.type ?? device.suggested_type) && (
|
||||
<InfoRow label="Type" value={(device.type ?? device.suggested_type) as string} />
|
||||
)}
|
||||
{device.friendly_name && device.friendly_name !== device.hostname && (
|
||||
<InfoRow label="Name" value={device.friendly_name} />
|
||||
)}
|
||||
{device.vendor && <InfoRow label="Vendor" value={device.vendor} />}
|
||||
{device.model && <InfoRow label="Model" value={device.model} />}
|
||||
{device.device_subtype && <InfoRow label="Role" value={device.device_subtype} />}
|
||||
{device.lqi != null && <InfoRow label="LQI" value={String(device.lqi)} />}
|
||||
{!device.ip && !device.hostname && !device.mac && !device.ieee_address && (
|
||||
<Empty>Nothing identifying recorded yet.</Empty>
|
||||
)}
|
||||
</div>
|
||||
</Section>
|
||||
|
||||
{/* Zigbee devices have no IP services — the section would always be empty. */}
|
||||
{!isZigbee && (
|
||||
<Section title={`Services found (${device.services.length})`} icon={Network}>
|
||||
{device.services.length === 0 ? (
|
||||
<Empty>No services detected</Empty>
|
||||
) : (
|
||||
<div className="flex flex-col gap-1.5 max-h-72 overflow-y-auto">
|
||||
{device.services.map((svc, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className="flex items-center gap-2 px-2.5 py-1.5 rounded-md bg-[#21262d] border border-[#30363d] text-xs"
|
||||
>
|
||||
<span
|
||||
className="w-1.5 h-1.5 rounded-full shrink-0"
|
||||
style={{ backgroundColor: categoryColor(svc.category) }}
|
||||
/>
|
||||
<span className="font-mono text-[#00d4ff] w-10 shrink-0">{svc.port}</span>
|
||||
<span className="text-muted-foreground w-8 shrink-0">{svc.protocol}</span>
|
||||
<span className="text-foreground truncate">{svc.service_name}</span>
|
||||
{svc.category && (
|
||||
<span className="ml-auto text-[10px] shrink-0" style={{ color: categoryColor(svc.category) }}>
|
||||
{svc.category}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</Section>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* How it is watched, and what happened to it. */}
|
||||
<div className="flex flex-col gap-4 min-w-0" data-testid="device-column-operations">
|
||||
<Section title="Monitoring" icon={HeartPulse}>
|
||||
<div className="flex flex-col">
|
||||
{device.check_method ? (
|
||||
<InfoRow
|
||||
label="Check"
|
||||
value={device.check_target ? `${device.check_method} → ${device.check_target}` : device.check_method}
|
||||
/>
|
||||
) : (
|
||||
<Empty>Not monitored — pick a check method from Edit.</Empty>
|
||||
)}
|
||||
{device.response_time_ms != null && <InfoRow label="Response" value={`${device.response_time_ms} ms`} />}
|
||||
{device.discovery_source && <InfoRow label="Source" value={device.discovery_source.toUpperCase()} />}
|
||||
{device.canvas_count != null && device.canvas_count > 0 && (
|
||||
<InfoRow label="Canvases" value={String(device.canvas_count)} />
|
||||
)}
|
||||
</div>
|
||||
</Section>
|
||||
|
||||
<Section title="Activity" icon={History}>
|
||||
<div className="flex flex-col">
|
||||
{timestamps.length === 0 ? (
|
||||
<Empty>No activity recorded.</Empty>
|
||||
) : (
|
||||
timestamps.map((t) => <TimeRow key={t.label} label={t.label} iso={t.iso} />)
|
||||
)}
|
||||
</div>
|
||||
</Section>
|
||||
|
||||
<Section title="Notes" icon={StickyNote}>
|
||||
{device.notes ? (
|
||||
<p className="text-xs text-foreground/80 whitespace-pre-wrap">{device.notes}</p>
|
||||
) : (
|
||||
<Empty>No notes.</Empty>
|
||||
)}
|
||||
</Section>
|
||||
</div>
|
||||
|
||||
{/* What the user curated. */}
|
||||
<div className="flex flex-col gap-4 min-w-0" data-testid="device-column-curation">
|
||||
<Section
|
||||
title={`Properties${device.properties && device.properties.length > 0 ? ` (${device.properties.length})` : ''}`}
|
||||
icon={Tags}
|
||||
>
|
||||
{device.properties && device.properties.length > 0 ? (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
{device.properties.map((prop, i) => (
|
||||
<div key={`${prop.key}-${i}`} className="flex items-baseline gap-2 px-2.5 py-1.5 rounded-md bg-[#21262d] border border-[#30363d] text-xs">
|
||||
<span className="text-muted-foreground shrink-0">{prop.key}</span>
|
||||
<span className="ml-auto font-mono text-foreground break-all text-right">{prop.value}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<Empty>No properties.</Empty>
|
||||
)}
|
||||
</Section>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* ── Footer: lifecycle in view, form controls in edit ── */}
|
||||
<div className="shrink-0 flex items-center justify-between gap-3 px-5 py-3 border-t border-[#30363d] bg-[#161b22]">
|
||||
<p className="text-[11px] text-muted-foreground/70 min-w-0 truncate">
|
||||
{editing
|
||||
? 'These facts belong to the device — every canvas drawing it follows.'
|
||||
: rackOnly
|
||||
? 'Rack gear — mounted from a rack canvas, never placed on a logical one.'
|
||||
: 'One device, one row. Editing here updates every canvas drawing it.'}
|
||||
</p>
|
||||
{editing ? (
|
||||
<div className="flex items-center gap-2 shrink-0">
|
||||
<Button size="sm" variant="ghost" onClick={handleCancel} className="text-muted-foreground hover:text-foreground">
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
className="bg-[#00d4ff] text-[#0d1117] hover:bg-[#00d4ff]/90 min-w-20"
|
||||
onClick={handleSave}
|
||||
disabled={saving}
|
||||
>
|
||||
{saving ? 'Saving…' : 'Save'}
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-center gap-2 shrink-0">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="text-muted-foreground hover:text-foreground hover:bg-[#30363d]"
|
||||
onClick={handleHide}
|
||||
>
|
||||
Hide
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="text-[#f85149] hover:text-[#f85149] hover:bg-[#f85149]/10"
|
||||
onClick={handleIgnore}
|
||||
>
|
||||
Delete
|
||||
</Button>
|
||||
{/* Rack gear is mounted from a rack canvas, never approved onto a
|
||||
logical one — so it gets no Approve button at all. */}
|
||||
{!rackOnly && (
|
||||
<Button
|
||||
size="sm"
|
||||
className="bg-[#39d353]/15 text-[#39d353] hover:bg-[#39d353]/25 border border-[#39d353]/30"
|
||||
onClick={handleApprove}
|
||||
>
|
||||
Approve
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{svcModal && (
|
||||
<ServiceModal
|
||||
key={`svc-${svcModal.index ?? 'new'}`}
|
||||
open
|
||||
onClose={() => setSvcModal(null)}
|
||||
onSubmit={handleSubmitService}
|
||||
initial={svcModal.form}
|
||||
title={svcModal.index === null ? 'Add Service' : 'Edit Service'}
|
||||
confirmLabel={svcModal.index === null ? 'Add' : 'Save'}
|
||||
/>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user