Skip to content

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

feat(auth): add generic OIDC backend sessions

ypso0e95d9986808
diff --git a/.env.example b/.env.example
index 0ddb255..0eb0a5f 100644
--- a/.env.example
+++ b/.env.example
@@ -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"]
diff --git a/INSTALLATION.md b/INSTALLATION.md
index 7837f96..739eb7a 100644
--- a/INSTALLATION.md
+++ b/INSTALLATION.md
@@ -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
@@ -69,6 +69,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 +83,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.
---
diff --git a/backend/app/api/deps.py b/backend/app/api/deps.py
index 260c5d4..d09d757 100644
--- a/backend/app/api/deps.py
+++ b/backend/app/api/deps.py
@@ -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
diff --git a/backend/app/api/routes/auth.py b/backend/app/api/routes/auth.py
index adead57..2468c37 100644
--- a/backend/app/api/routes/auth.py
+++ b/backend/app/api/routes/auth.py
@@ -1,12 +1,26 @@
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 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 +33,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")
+
+
[email protected]("/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 +71,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)
+
+
[email protected]("/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))
+
+
[email protected]("/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 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
+
+
[email protected]("/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,
+ )
+
+
[email protected]("/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
diff --git a/backend/app/api/routes/status.py b/backend/app/api/routes/status.py
index 26c5c4f..27db337 100644
--- a/backend/app/api/routes/status.py
+++ b/backend/app/api/routes/status.py
@@ -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:
diff --git a/backend/app/core/config.py b/backend/app/core/config.py
index 7c24d01..ec47043 100644
--- a/backend/app/core/config.py
+++ b/backend/app/core/config.py
@@ -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,6 +59,30 @@ 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 and not self.oidc_redirect_uri.startswith("https://"):
+ raise ValueError("OIDC_REDIRECT_URI 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
diff --git a/backend/app/core/security.py b/backend/app/core/security.py
index 957b1aa..d893ad9 100644
--- a/backend/app/core/security.py
+++ b/backend/app/core/security.py
@@ -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,
+ )
diff --git a/backend/app/main.py b/backend/app/main.py
index 368a490..709231e 100644
--- a/backend/app/main.py
+++ b/backend/app/main.py
@@ -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,
@@ -25,6 +26,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 +55,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"])
diff --git a/backend/requirements.txt b/backend/requirements.txt
index 0b02927..7837f7b 100644
--- a/backend/requirements.txt
+++ b/backend/requirements.txt
@@ -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
diff --git a/backend/tests/test_auth.py b/backend/tests/test_auth.py
index 09b569d..76823b7 100644
--- a/backend/tests/test_auth.py
+++ b/backend/tests/test_auth.py
@@ -1,5 +1,55 @@
+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 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 | 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
+
+
+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 +60,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 +132,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 +153,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 +192,222 @@ 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
+
+
[email protected]("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_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()
diff --git a/backend/tests/test_settings.py b/backend/tests/test_settings.py
index 963b321..de68e07 100644
--- a/backend/tests/test_settings.py
+++ b/backend/tests/test_settings.py
@@ -167,3 +167,48 @@ 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_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