Self-hosted homelab infrastructure visualizer — interactive network diagram with live status monitoring
TypeScript diagramhomelabhomelab-infrastructure-observabilitynetworkproxmox-veself-hostedzigbeezwavezwave-js
fix: say why a UniFi login failed instead of one catch-all error (#554)
Pouzor - Rémy Jardientd96aecb84342
diff --git a/backend/app/schemas/unifi.py b/backend/app/schemas/unifi.pyindex 53e769b..aa11150 100644--- a/backend/app/schemas/unifi.py+++ b/backend/app/schemas/unifi.py@@ -29,7 +29,7 @@ def _default_modes() -> UnifiImportModes:class UnifiConnectionRequest(BaseModel):host: str = Field(..., description="UniFi controller host or IP")- port: int = Field(8443, ge=1, le=65535, description="Controller port (8443 legacy, 443 UDM)")+ port: int = Field(443, ge=1, le=65535, description="Controller port (443 UniFi OS, 8443 legacy)")site: str = Field("default", description="UniFi site name")username: str | None = Field(None, description="Controller username (falls back to server env)")password: str | None = Field(None, description="Controller password (falls back to server env)")diff --git a/backend/app/services/unifi_service.py b/backend/app/services/unifi_service.pyindex 0a45112..9840acc 100644--- a/backend/app/services/unifi_service.py+++ b/backend/app/services/unifi_service.py@@ -28,6 +28,24 @@ class UnifiApiError(ConnectionError):"""+class UnifiLoginError(ConnectionError):+ """The controller refused or never answered the login, with the reason.++ One catch-all "invalid credentials or unreachable host" made a closed port,+ a UI.com account with MFA and a wrong password indistinguishable (#551).+ """+++# UniFi OS answers a cloud (UI.com) account with MFA enabled with this+# non-standard status and code; only a local admin can log in over the API.+_MFA_STATUS = 499+_MFA_CODE = "MFA_AUTH_REQUIRED"+_PORT_HINT = "UniFi OS gateways (UDM, UCG) listen on 443, a self-hosted controller on 8443"+_ACCOUNT_HINT = (+ "use a local admin account of the controller — a UI.com cloud account is not accepted"+)++# discovery_source values. Infrastructure and clients are told apart in the# data; the UI buckets both under one UniFi filter.SOURCE_INFRA = "unifi"@@ -163,20 +181,72 @@ async def _login(port: int,username: str,password: str,-) -> dict[str, str] | None:- """Try both UniFi OS and legacy controller login paths."""+) -> dict[str, str]:+ """Try both UniFi OS and legacy controller login paths.++ Returns the session cookies, or raises UnifiLoginError naming why it+ failed: unreachable host, timeout, MFA, rate limit or rejected credentials.+ """+ hostname = host.lower().rstrip(".")+ if hostname == "ui.com" or hostname.endswith(".ui.com"):+ raise UnifiLoginError(+ f"Login failed: {host} is Ubiquiti's cloud portal, not a controller — "+ "enter the LAN IP of your gateway or controller"+ )+base = f"https://{host}:{port}"payload = {"username": username, "password": password}+ failures: list[str] = []+ rejected = False# UniFi OS (Dream Machine series) uses /api/auth/loginfor path in ["/api/auth/login", "/api/login"]:try:r = await client.post(f"{base}{path}", json=payload, follow_redirects=True)- if r.status_code in (200, 201):- return dict(r.cookies)- except Exception:+ except httpx.ConnectError as exc:+ # Same host and port for both paths: the next one cannot do better.+ raise UnifiLoginError(f"Cannot reach {host}:{port} ({exc}) — {_PORT_HINT}") from exc+ except httpx.TimeoutException as exc:+ raise UnifiLoginError(+ f"Login failed: {host}:{port} did not answer in time — {_PORT_HINT}"+ ) from exc+ except httpx.HTTPError as exc:+ failures.append(f"{path} → {exc}")continue- return None++ detail = _error_detail(r)+ if r.status_code in (200, 201):+ if r.cookies:+ return dict(r.cookies)+ failures.append(f"{path} → HTTP {r.status_code} without a session cookie")+ elif r.status_code == _MFA_STATUS or _MFA_CODE in detail:+ raise UnifiLoginError(f"Login failed: this account has MFA enabled — {_ACCOUNT_HINT}")+ elif r.status_code == 429:+ raise UnifiLoginError(+ "Login failed: the controller is rate-limiting logins after too many "+ "attempts — wait a few minutes before retrying"+ )+ else:+ rejected = rejected or r.status_code in (400, 401, 403)+ failures.append(f"{path} → HTTP {r.status_code}" + (f" {detail}" if detail else ""))++ tried = "; ".join(failures)+ if rejected:+ raise UnifiLoginError(f"Login failed: credentials rejected ({tried}) — {_ACCOUNT_HINT}")+ raise UnifiLoginError(f"Login failed: no UniFi login endpoint answered ({tried}) — {_PORT_HINT}")+++def _error_detail(r: httpx.Response) -> str:+ """The controller's own error code, from either API dialect, or ''."""+ try:+ body = r.json()+ except ValueError:+ return ""+ if not isinstance(body, dict):+ return ""+ meta = body.get("meta")+ legacy = meta.get("msg") if isinstance(meta, dict) else None+ return str(body.get("code") or body.get("message") or legacy or "")async def _get_list(diff --git a/backend/tests/test_unifi_service.py b/backend/tests/test_unifi_service.pyindex a4e8368..24df2f4 100644--- a/backend/tests/test_unifi_service.py+++ b/backend/tests/test_unifi_service.py@@ -400,3 +400,112 @@ async def test_every_icon_is_one_the_front_end_can_render() -> None:)used = {p["icon"] for d in devices for p in d["properties"] if p["icon"]}assert used and used <= known, f"unknown icon(s): {used - known}"+++# ── login failures say why (#551) ───────────────────────────────────────────+# One catch-all "invalid credentials or unreachable host" hid every cause.+++async def _login_failure(handler, host: str = "unifi.local", port: int = 443) -> str:+ ctx, _ = _patch(handler)+ with ctx:+ connected, message, _ = await check_connection(host, port, "default", "admin", "pw")+ assert connected is False+ return message+++async def test_mfa_account_is_named_as_the_cause() -> None:+ """UniFi OS answers a UI.com account with MFA with a 499."""++ def handler(request: httpx.Request) -> httpx.Response:+ return httpx.Response(499, json={"code": "MFA_AUTH_REQUIRED", "message": "MFA required"})++ message = await _login_failure(handler)+ assert "MFA" in message+ assert "local admin" in message+++async def test_rejected_credentials_point_at_a_local_account() -> None:+ def handler(request: httpx.Request) -> httpx.Response:+ if request.url.path == _LOGIN_OS:+ return httpx.Response(+ 401, json={"code": "AUTHENTICATION_FAILED_INVALID_CREDENTIALS"}+ )+ return httpx.Response(404, text="<html>Not Found</html>")++ message = await _login_failure(handler)+ assert "credentials rejected" in message+ assert "AUTHENTICATION_FAILED_INVALID_CREDENTIALS" in message+ assert "local admin" in message+++async def test_closed_port_reports_unreachable_with_a_port_hint() -> None:+ def handler(request: httpx.Request) -> httpx.Response:+ raise httpx.ConnectError("Connection refused", request=request)++ message = await _login_failure(handler, port=8443)+ assert message.startswith("Cannot reach unifi.local:8443")+ assert "443" in message+++async def test_timeout_is_reported_as_such() -> None:+ def handler(request: httpx.Request) -> httpx.Response:+ raise httpx.ConnectTimeout("timed out", request=request)++ message = await _login_failure(handler)+ assert "did not answer in time" in message+++async def test_rate_limit_is_reported_as_such() -> None:+ def handler(request: httpx.Request) -> httpx.Response:+ return httpx.Response(429, json={"code": "TOO_MANY_REQUESTS"})++ message = await _login_failure(handler)+ assert "rate-limiting" in message+++async def test_no_login_endpoint_is_not_blamed_on_credentials() -> None:+ def handler(request: httpx.Request) -> httpx.Response:+ return httpx.Response(404, text="<html>Not Found</html>")++ message = await _login_failure(handler)+ assert "no UniFi login endpoint answered" in message+ assert "credentials" not in message+++async def test_cloud_portal_host_is_refused_without_a_request() -> None:+ ctx, factory = _patch(lambda request: httpx.Response(200))+ with ctx:+ connected, message, _ = await check_connection(+ "unifi.ui.com", 443, "default", "admin", "pw"+ )+ assert connected is False+ assert "cloud portal" in message+ assert factory.requests == []+++async def test_login_failure_reason_reaches_the_import() -> None:+ def handler(request: httpx.Request) -> httpx.Response:+ return httpx.Response(499, json={"code": "MFA_AUTH_REQUIRED"})++ ctx, _ = _patch(handler)+ with ctx, pytest.raises(ConnectionError, match="MFA"):+ await fetch_unifi_inventory("unifi.local", 443, "default", "admin", "pw")+++async def test_a_host_merely_ending_in_ui_com_is_not_the_cloud_portal() -> None:+ """Only ui.com and its subdomains are refused — not e.g. ``myui.com``."""+ ctx, factory = _patch(_self_hosted(_DEVICES))+ with ctx:+ connected, _, _ = await check_connection("myui.com", 8443, "default", "admin", "pw")+ assert connected is True+ assert factory.requestsdiff --git a/frontend/src/components/unifi/UnifiImportModal.tsx b/frontend/src/components/unifi/UnifiImportModal.tsxindex ddada01..58c4f88 100644--- a/frontend/src/components/unifi/UnifiImportModal.tsx+++ b/frontend/src/components/unifi/UnifiImportModal.tsx@@ -26,7 +26,7 @@ interface ConnectionForm {const DEFAULT_FORM: ConnectionForm = {host: '',- port: '8443',+ port: '443',site: 'default',username: '',password: '',@@ -87,7 +87,7 @@ export function UnifiImportModal({ open, onClose, onInventoryImported }: UnifiImconst buildPayload = () => ({host: form.host.trim(),- port: Number(form.port) || 8443,+ port: Number(form.port) || 443,site: form.site.trim() || 'default',// Blank falls back to the server env, like every other import.username: form.username.trim() || undefined,@@ -167,10 +167,13 @@ export function UnifiImportModal({ open, onClose, onInventoryImported }: UnifiIm<Inputvalue={form.port}onChange={(e) => updateField('port', e.target.value)}- placeholder="8443"+ placeholder="443"type="number"className="font-mono text-sm bg-[#0d1117] border-border"/>+ <p className="text-[11px] text-muted-foreground/60">+ 443 for UniFi OS (UDM, UCG), 8443 for a self-hosted controller+ </p></div><div className="space-y-1"><Label className="text-xs text-muted-foreground">Site</Label>@@ -201,6 +204,10 @@ export function UnifiImportModal({ open, onClose, onInventoryImported }: UnifiImclassName="text-sm bg-[#0d1117] border-border"/></div>+ <p className="col-span-2 text-[11px] text-muted-foreground/60">+ Use a local admin account of the controller. A UI.com cloud account with MFA+ cannot log in over the API, and unifi.ui.com is not a controller address.+ </p><div className="col-span-2 flex flex-wrap items-center gap-x-6 gap-y-2 pt-1"><label className="flex items-center gap-1.5 text-xs text-muted-foreground cursor-pointer"><inputdiff --git a/frontend/src/components/unifi/__tests__/UnifiImportModal.test.tsx b/frontend/src/components/unifi/__tests__/UnifiImportModal.test.tsxindex 6ec21ed..73737dc 100644--- a/frontend/src/components/unifi/__tests__/UnifiImportModal.test.tsx+++ b/frontend/src/components/unifi/__tests__/UnifiImportModal.test.tsx@@ -53,7 +53,7 @@ describe('UnifiImportModal', () => {active_clients: false,})expect(payload.site).toBe('default')- expect(payload.port).toBe(8443)+ expect(payload.port).toBe(443)})it('sends the sources the user ticked', async () => {@@ -176,4 +176,20 @@ describe('UnifiImportModal', () => {expect(unifiApi.importToPending).not.toHaveBeenCalled()expect(toast.error).toHaveBeenCalledWith('Enter a controller host')})++ it('tells the user a local admin account is required', () => {+ render(<UnifiImportModal {...defaultProps} />)+ expect(screen.getByText(/local admin account/i)).toBeInTheDocument()+ expect(screen.getByText(/443 for UniFi OS/i)).toBeInTheDocument()+ })++ it('falls back to 443 when the port is cleared', async () => {+ render(<UnifiImportModal {...defaultProps} />)+ typeHost()+ fireEvent.change(screen.getByPlaceholderText('443'), { target: { value: '' } })+ fireEvent.click(screen.getByRole('button', { name: /import to inventory/i }))++ await waitFor(() => expect(unifiApi.importToPending).toHaveBeenCalled())+ expect(vi.mocked(unifiApi.importToPending).mock.calls[0][0].port).toBe(443)+ })})