Skip to content

Self-hosted homelab infrastructure visualizer — interactive network diagram with live status monitoring

fix: keep the security fixes, revert the install-breaking changes, add tests

Pouzor5edc9c7e7e84
diff --git a/.dockerignore b/.dockerignore
index 0d7b5f9..4a46fa1 100644
--- a/.dockerignore
+++ b/.dockerignore
@@ -4,14 +4,18 @@
.env.*
**/.env
**/.env.*
-*.db
-*.sqlite
-*.sqlite3
+# Patterns match from the build-context root; **/ reaches into subfolders.
+# Do not use **/data/: backend/app/data and frontend/src/data are source.
+**/*.db
+**/*.sqlite
+**/*.sqlite3
data/
-uploads/
-node_modules/
-__pycache__/
-*.py[cod]
-.pytest_cache/
-.mypy_cache/
-.ruff_cache/
\ No newline at end of file
+backend/data/
+**/uploads/
+**/node_modules/
+**/__pycache__/
+**/*.py[cod]
+**/.pytest_cache/
+**/.mypy_cache/
+**/.ruff_cache/
+**/.venv/
diff --git a/.env.example b/.env.example
index b61ceb5..da5b10c 100644
--- a/.env.example
+++ b/.env.example
@@ -1,6 +1,6 @@
# Backend - server-side only (NEVER commit .env)
# Generate: python3 -c "import secrets; print(secrets.token_hex(32))"
-SECRET_KEY=
+SECRET_KEY=change_me_in_production
SQLITE_PATH=./data/homelab.db
# Uploaded media (floor plans) folder. Optional — defaults to <SQLITE_PATH dir>/uploads,
# which sits on the same persistent volume as the DB.
@@ -15,13 +15,14 @@ CORS_ORIGINS=["http://localhost:5173","http://localhost:3000"]
# Auth — local mode is the backward-compatible default.
AUTH_MODE=local
-# Local credentials: set both values before starting the backend.
+# Local credentials: admin / admin by default.
+# ⚠️ Change before exposing on a network.
# 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.
# podman-compose does not strip those quotes the way Docker Compose does, so the
# backend unwraps one matched pair itself — quoted or not, both work everywhere.
-AUTH_USERNAME=
-AUTH_PASSWORD_HASH=
+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
@@ -57,8 +58,8 @@ STATUS_CHECKER_INTERVAL=60
# MCP_API_KEY: authenticates AI clients (Claude Code, etc.) → MCP server
# MCP_SERVICE_KEY: authenticates MCP server → backend (never exposed externally)
# Generate keys: python3 -c "import secrets; print(secrets.token_hex(32))"
-MCP_API_KEY=
-MCP_SERVICE_KEY=
+MCP_API_KEY=mcp_sk_changeme
+MCP_SERVICE_KEY=svc_changeme
# Live view — read-only public canvas at /view?key=<value>
# Off by default. Set to a random secret to enable.
diff --git a/Dockerfile.backend b/Dockerfile.backend
index dc7c299..82bb73f 100644
--- a/Dockerfile.backend
+++ b/Dockerfile.backend
@@ -14,12 +14,6 @@ COPY VERSION /app/VERSION
# Create data directory (volume mount point)
RUN mkdir -p /app/data
-# The application does not need root after image setup. Running as a dedicated
-# user also prevents a backend compromise from writing over the application code.
-RUN useradd --system --create-home --uid 10001 app \
- && chown -R app:app /app
-USER app
-
EXPOSE 8000
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
diff --git a/INSTALLATION.md b/INSTALLATION.md
index 7d2cbb9..ac4e7ea 100644
--- a/INSTALLATION.md
+++ b/INSTALLATION.md
@@ -388,11 +388,11 @@ All configuration is done via `.env` (copied from `.env.example`):
```env
# Generate with: python3 -c "import secrets; print(secrets.token_hex(32))"
-SECRET_KEY=<random-secret-at-least-32-bytes>
+SECRET_KEY=change_me_in_production
-# Auth — set a username and a bcrypt hash for your own password.
-AUTH_USERNAME=<your-username>
-AUTH_PASSWORD_HASH='<bcrypt-hash>' # keep single quotes
+# Auth — default: admin / admin
+AUTH_USERNAME=admin
+AUTH_PASSWORD_HASH='$2b$12$...' # bcrypt hash — keep single quotes
# CIDR ranges to scan
SCANNER_RANGES=["192.168.1.0/24"]
diff --git a/backend/tests/scan/test_scan_routes.py b/backend/tests/scan/test_scan_routes.py
index 9d63153..29afbfc 100644
--- a/backend/tests/scan/test_scan_routes.py
+++ b/backend/tests/scan/test_scan_routes.py
@@ -636,3 +636,33 @@ async def test_clear_pending_keeps_documents_of_a_device_approved_mid_clear(clie
).scalar_one()
assert status == "approved"
assert (await db_session.get(Document, doc_id)).device_id == device_id
+
+
+async def test_rescan_device_targets_first_valid_ip(client: AsyncClient, headers, db_session):
+ """A multi-address row scans one validated host, never the raw field."""
+ device = InventoryDevice(
+ id=str(uuid.uuid4()), ip="not-an-ip, 192.168.1.50, 192.168.1.51", status="pending"
+ )
+ db_session.add(device)
+ await db_session.commit()
+ with patch("app.api.routes.scan._background_device_scan", new_callable=AsyncMock):
+ res = await client.post(f"/api/v1/scan/pending/{device.id}/rescan", headers=headers)
+ assert res.status_code == 200, res.text
+ assert res.json()["ranges"] == ["192.168.1.50/32"]
+
+
+async def test_rescan_device_rejects_ip_field_with_no_valid_address(
+ client: AsyncClient, headers, db_session
+):
+ """Regression: the raw ip field went to nmap as the target, so a value shaped
+ like an nmap option reached the command line."""
+ device = InventoryDevice(id=str(uuid.uuid4()), ip="-iL /etc/passwd", status="pending")
+ db_session.add(device)
+ await db_session.commit()
+ with patch("app.api.routes.scan._background_device_scan", new_callable=AsyncMock) as bg:
+ res = await client.post(f"/api/v1/scan/pending/{device.id}/rescan", headers=headers)
+ assert res.status_code == 409
+ assert res.json()["detail"] == "Device has no valid IP address to scan"
+ bg.assert_not_called()
diff --git a/backend/tests/test_proxmox_router.py b/backend/tests/test_proxmox_router.py
index 465f76f..3b405c1 100644
--- a/backend/tests/test_proxmox_router.py
+++ b/backend/tests/test_proxmox_router.py
@@ -700,3 +700,85 @@ async def test_canvas_import_points_at_the_row_matched_by_ip(
)
).scalars().all()
assert len(rows) == 1
+
+
+# --- credential binding: the env token only goes to the configured host ------
+
+def _env_proxmox():
+ """Configure an env token for pve:8006 (TLS on); restore afterwards."""
+ saved = (settings.proxmox_host, settings.proxmox_port, settings.proxmox_verify_tls)
+ settings.proxmox_host = "pve.lan"
+ settings.proxmox_port = 8006
+ settings.proxmox_verify_tls = True
+ settings.proxmox_token_id = "env@pam!t"
+ settings.proxmox_token_secret = "env-secret"
+ yield
+ settings.proxmox_host, settings.proxmox_port, settings.proxmox_verify_tls = saved
+
+
[email protected]("_env_proxmox")
+async def test_env_token_used_for_configured_host(client: AsyncClient, headers: dict) -> None:
+ probe = AsyncMock(return_value=(True, "ok"))
+ with patch("app.api.routes.proxmox.test_proxmox_connection", new=probe):
+ res = await client.post(
+ "/api/v1/proxmox/test-connection",
+ # Case and a trailing dot name the same host.
+ json={"host": "PVE.lan.", "port": 8006, "verify_tls": True},
+ headers=headers,
+ )
+ assert res.status_code == 200, res.text
+ assert probe.call_args.kwargs["token_id"] == "env@pam!t"
+ assert probe.call_args.kwargs["token_secret"] == "env-secret"
+
+
[email protected]("_env_proxmox")
[email protected]("override", [
+ {"host": "attacker.example"},
+ {"port": 443},
+ {"verify_tls": False},
+])
+async def test_env_token_never_sent_to_another_endpoint(
+ client: AsyncClient, headers: dict, override: dict
+) -> None:
+ """Regression: a caller-chosen host received the server's env token."""
+ body = {"host": "pve.lan", "port": 8006, "verify_tls": True, **override}
+ probe = AsyncMock(return_value=(True, "ok"))
+ with patch("app.api.routes.proxmox.test_proxmox_connection", new=probe):
+ res = await client.post("/api/v1/proxmox/test-connection", json=body, headers=headers)
+ assert res.status_code == 400
+ assert res.json()["detail"] == "Custom Proxmox hosts require an explicit API token"
+ probe.assert_not_called()
+
+
[email protected]("_env_proxmox")
+async def test_body_token_allowed_for_any_host(client: AsyncClient, headers: dict) -> None:
+ probe = AsyncMock(return_value=(True, "ok"))
+ with patch("app.api.routes.proxmox.test_proxmox_connection", new=probe):
+ res = await client.post(
+ "/api/v1/proxmox/test-connection",
+ json={"host": "other", "port": 8006, "token_id": "u@pam!t", "token_secret": "s"},
+ headers=headers,
+ )
+ assert res.status_code == 200
+ assert probe.call_args.kwargs["token_id"] == "u@pam!t"
+ assert probe.call_args.kwargs["token_secret"] == "s"
+
+
[email protected]("_env_proxmox")
[email protected]("partial", [{"token_id": "u@pam!t"}, {"token_secret": "s"}])
+async def test_half_a_body_token_is_rejected(
+ client: AsyncClient, headers: dict, partial: dict
+) -> None:
+ """Half a token is never completed from the env one."""
+ res = await client.post(
+ "/api/v1/proxmox/test-connection",
+ json={"host": "pve.lan", "port": 8006, **partial},
+ headers=headers,
+ )
+ assert res.status_code == 400
+ assert res.json()["detail"] == "Provide both Proxmox token fields"
diff --git a/backend/tests/test_scanner.py b/backend/tests/test_scanner.py
index 8ab0a95..0fd52e7 100644
--- a/backend/tests/test_scanner.py
+++ b/backend/tests/test_scanner.py
@@ -1774,3 +1774,59 @@ async def test_process_host_never_deletes_a_second_approved_row(mem_db):
assert sorted(d.id for d in devices) == ["a", "b"]
# The oldest approved row is the merge target.
assert oldest is not None and oldest.hostname == "claimed.lan"
+
+
+async def test_run_device_scan_scans_the_first_valid_ip(mem_db):
+ from app.services.scanner import run_device_scan
+
+ run_id = _make_run_id()
+ async with mem_db() as session:
+ session.add(ScanRun(id=run_id, status="running", kind="device", ranges=["192.168.1.9/32"]))
+ session.add(InventoryDevice(id="d1", ip="bogus, 192.168.1.9 , 192.168.1.10", status="pending", services=[]))
+ await session.commit()
+
+ seen_ips = []
+
+ def _scanned(host_dict, port_spec, bounded=False):
+ seen_ips.append(host_dict["ip"])
+ return host_dict
+
+ async with mem_db() as session:
+ with patch("app.services.scanner._nmap_scan_single", side_effect=_scanned), \
+ patch("app.api.routes.status.broadcast_scan_update", new_callable=AsyncMock):
+ await run_device_scan("d1", session, run_id, ports="22")
+
+ assert seen_ips == ["192.168.1.9"]
+
+
+async def test_run_device_scan_errors_when_no_ip_is_valid(mem_db):
+ from app.services.scanner import run_device_scan
+
+ run_id = _make_run_id()
+ async with mem_db() as session:
+ session.add(ScanRun(id=run_id, status="running", kind="device", ranges=[]))
+ session.add(InventoryDevice(id="d1", ip="-oN /tmp/x", status="pending", services=[]))
+ await session.commit()
+
+ async with mem_db() as session:
+ with patch("app.services.scanner._nmap_scan_single") as scan, \
+ patch("app.api.routes.status.broadcast_scan_update", new_callable=AsyncMock):
+ await run_device_scan("d1", session, run_id)
+
+ async with mem_db() as session:
+ run = await session.get(ScanRun, run_id)
+ scan.assert_not_called()
+ assert run is not None and run.status == "error"
+ assert run.error == "Device has no valid IP to scan"
+
+
[email protected]("bad", ["-iL /etc/passwd", "192.168.1.0/24", "", None, 42])
+def test_nmap_scan_single_refuses_non_ip_target(bad):
+ from app.services.scanner import _nmap_scan_single
+
+ host = {"ip": bad, "open_ports": []}
+ with patch("app.services.scanner.nmap.PortScanner") as scanner:
+ assert _nmap_scan_single(host) is host
+ scanner.assert_not_called()
diff --git a/install.sh b/install.sh
index 27aa185..7cbf5ae 100755
--- a/install.sh
+++ b/install.sh
@@ -35,28 +35,6 @@ else
curl -fsSL "${RAW}/.env.example" -o .env.example
fi
-if [ "${STANDALONE}" -eq 0 ]; then
- if [ ! -f .env ]; then
- cp .env.example .env
- fi
- missing=0
- for key in SECRET_KEY AUTH_PASSWORD_HASH MCP_API_KEY MCP_SERVICE_KEY; do
- value=$(grep -E "^${key}=" .env | head -n 1 | cut -d= -f2- || true)
- if [ -z "${value}" ]; then
- echo " Missing required security setting: ${key}"
- missing=1
- fi
- done
- if grep -Eq 'change_me_in_production|mcp_sk_changeme|svc_changeme|RtMbyw17l4N5UGzeXMNAWuzCaVV.XFBY7ZetWheQhxcBDcxahapkG' .env; then
- echo " Refusing to start with a known default credential."
- missing=1
- fi
- if [ "${missing}" -ne 0 ]; then
- echo " Configure .env and rerun this installer. No services were started."
- exit 1
- fi
-fi
-
if [ "${IS_UPDATE}" -eq 1 ]; then
echo ""
echo " docker-compose.yml updated."
@@ -70,8 +48,13 @@ else
echo " Run:"
echo " cd ${INSTALL_DIR} && docker compose up -d"
else
+ if [ ! -f .env ]; then
+ cp .env.example .env
+ fi
echo ""
- echo " Security settings loaded from .env."
+ echo " Edit .env if needed (default login: admin / admin):"
+ echo " - Set SECRET_KEY to a random string"
+ echo " - Change AUTH_PASSWORD_HASH before exposing on a network"
echo ""
echo " Run:"
echo " cd ${INSTALL_DIR} && docker compose up -d"
diff --git a/mcp/.env.example b/mcp/.env.example
index 1bf5963..104ba2e 100644
--- a/mcp/.env.example
+++ b/mcp/.env.example
@@ -2,11 +2,11 @@
# Authenticates AI clients (Claude Code, Claude Desktop, etc.) → MCP server
# Generate: python3 -c "import secrets; print('mcp_sk_' + secrets.token_hex(24))"
-MCP_API_KEY=
+MCP_API_KEY=mcp_sk_changeme
# Authenticates MCP server → backend (must match MCP_SERVICE_KEY in backend .env)
# Generate: python3 -c "import secrets; print('svc_' + secrets.token_hex(24))"
-MCP_SERVICE_KEY=
+MCP_SERVICE_KEY=svc_changeme
# Backend URL — use http://backend:8000 in Docker, http://localhost:8000 for local dev
BACKEND_URL=http://localhost:8000
diff --git a/mcp/Dockerfile.mcp b/mcp/Dockerfile.mcp
index 5b73c73..6065594 100644
--- a/mcp/Dockerfile.mcp
+++ b/mcp/Dockerfile.mcp
@@ -7,8 +7,4 @@ RUN pip install --no-cache-dir -r requirements.txt
COPY app/ ./app/
-RUN useradd --system --create-home --uid 10001 app \
- && chown -R app:app /app
-USER app
-
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8001"]
diff --git a/mcp/app/config.py b/mcp/app/config.py
index c370409..f6adf81 100644
--- a/mcp/app/config.py
+++ b/mcp/app/config.py
@@ -2,8 +2,8 @@ from pydantic_settings import BaseSettings
class Settings(BaseSettings):
- mcp_api_key: str = "" # AI client → MCP server
- mcp_service_key: str = "" # MCP server → backend
+ mcp_api_key: str = "mcp_sk_changeme" # AI client → MCP server
+ mcp_service_key: str = "svc_changeme" # MCP server → backend
backend_url: str = "http://backend:8000"
model_config = {"env_file": ".env", "extra": "ignore"}
diff --git a/mcp/app/tools.py b/mcp/app/tools.py
index 0711836..90d2e75 100644
--- a/mcp/app/tools.py
+++ b/mcp/app/tools.py
@@ -421,7 +421,7 @@ async def _dispatch(name: str, args: dict) -> dict:
if name == "update_node":
node_id = safe_id(args.pop("id"), field="node id")
- return await backend.patch(f"/api/v1/nodes/{safe_id(node_id, field='node id')}", args)
+ return await backend.patch(f"/api/v1/nodes/{node_id}", args)
if name == "delete_node":
return await backend.delete(f"/api/v1/nodes/{safe_id(args['id'], field='node id')}")
diff --git a/mcp/tests/test_safe_id.py b/mcp/tests/test_safe_id.py
new file mode 100644
index 0000000..ee81533
--- /dev/null
+++ b/mcp/tests/test_safe_id.py
@@ -0,0 +1,112 @@
+"""Identifiers from an AI client never leave their own path segment.
+
+Tool arguments are model output, so a prompt-injected id such as
+``../designs/x`` or ``x?design_id=y`` used to be spliced into the backend URL
+as is and reach a different route than the tool names.
+"""
+
+from unittest.mock import AsyncMock, patch
+
+import pytest
+from app.backend_client import safe_id
+from app.devices import dispatch_device
+from app.documents import dispatch_document
+from app.racks import dispatch_rack
+from app.resources import read_resource
+from app.tools import _dispatch
+
+HOSTILE_IDS = ["../designs/x", "a/b", "x?design_id=y", "x#frag", "%2e%2e", "a b", "", "é"]
+
+
[email protected]("value", ["1", "42", "3f2a9c1e-7b4d-4e8a-9c0f-1a2b3c4d5e6f", "pve-node_1"])
+def test_safe_id_accepts_backend_ids(value):
+ assert safe_id(value) == value
+
+
[email protected]("value", HOSTILE_IDS + [None, 42])
+def test_safe_id_rejects_anything_else(value):
+ with pytest.raises(ValueError, match="Invalid node id"):
+ safe_id(value, field="node id") # type: ignore[arg-type]
+
+
+def _backend(module: str):
+ mock = patch(f"app.{module}.backend")
+ m = mock.start()
+ for verb in ("get", "post", "patch", "delete"):
+ setattr(m, verb, AsyncMock(return_value={}))
+ return mock, m
+
+
+def backends():
+ patches = {name: _backend(name) for name in ("tools", "devices", "documents", "racks", "resources")}
+ yield {name: m for name, (_, m) in patches.items()}
+ for p, _ in patches.values():
+ p.stop()
+
+
+def _no_backend_call(m) -> bool:
+ return not any(getattr(m, verb).called for verb in ("get", "post", "patch", "delete"))
+
+
[email protected]("bad", HOSTILE_IDS)
[email protected]("tool,args", [
+ ("update_node", lambda v: {"id": v, "label": "x"}),
+ ("delete_node", lambda v: {"id": v}),
+ ("get_node", lambda v: {"id": v}),
+ ("update_edge", lambda v: {"id": v}),
+ ("delete_edge", lambda v: {"id": v}),
+ ("approve_device", lambda v: {"id": v}),
+ ("hide_device", lambda v: {"id": v}),
+ ("get_canvas", lambda v: {"design_id": v}),
+])
+async def test_tools_refuse_hostile_ids(backends, tool, args, bad):
+ if tool in ("get_canvas", "get_node") and bad == "":
+ pytest.skip("an empty optional id means 'not given', not a path segment")
+ with pytest.raises(ValueError, match="Invalid"):
+ await _dispatch(tool, args(bad))
+ assert _no_backend_call(backends["tools"])
+
+
[email protected]("tool", ["update_device", "delete_device", "rescan_device", "list_proxmox_children"])
+async def test_device_tools_refuse_hostile_ids(backends, tool):
+ with pytest.raises(ValueError, match="Invalid device id"):
+ await dispatch_device(tool, {"id": "../../nodes/1"})
+ assert _no_backend_call(backends["devices"])
+
+
[email protected]("tool,args", [
+ ("read_document", {"id": "../x"}),
+ ("list_document_revisions", {"document_id": "../x"}),
+ ("read_document_revision", {"revision_id": "../x"}),
+ ("document_backlinks", {"document_id": "../x"}),
+ ("restore_document_revision", {"document_id": "d1", "revision_id": "../x"}),
+])
+async def test_document_tools_refuse_hostile_ids(backends, tool, args):
+ with pytest.raises(ValueError, match="Invalid"):
+ await dispatch_document(tool, args)
+ assert _no_backend_call(backends["documents"])
+
+
+async def test_rack_tools_refuse_hostile_design_id(backends):
+ with pytest.raises(ValueError, match="Invalid design id"):
+ await dispatch_rack("list_rack_inventory", {"design_id": "x&design_id=y"})
+ assert _no_backend_call(backends["racks"])
+
+
[email protected]("uri", ["homelable://nodes/x%2F..", "homelable://documents/x?y=1"])
+async def test_resources_refuse_hostile_ids(backends, uri):
+ with pytest.raises(ValueError, match="Invalid"):
+ await read_resource(uri)
+ assert _no_backend_call(backends["resources"])
+
+
+async def test_update_node_validates_once_and_keeps_the_path(backends):
+ await _dispatch("update_node", {"id": "n-1", "label": "x"})
+ backends["tools"].patch.assert_called_once_with("/api/v1/nodes/n-1", {"label": "x"})