Skip to content

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

fix(auth): accept the app's own origin in the OIDC CSRF check

Pouzor21a64e52ab9c
diff --git a/backend/app/core/config.py b/backend/app/core/config.py
index 192137c..f2dd09f 100644
--- a/backend/app/core/config.py
+++ b/backend/app/core/config.py
@@ -2,12 +2,21 @@ import json
import logging
from pathlib import Path
from typing import Literal
+from urllib.parse import urlsplit
from pydantic import Field, model_validator
from pydantic_settings import BaseSettings, SettingsConfigDict
logger = logging.getLogger(__name__)
+
+def origin_of(url: str) -> str:
+ """`scheme://host[:port]` of an absolute URL, or "" when it has none."""
+ parts = urlsplit(url)
+ if not parts.scheme or not parts.netloc:
+ return ""
+ return f"{parts.scheme}://{parts.netloc}"
+
def _read_version() -> str:
for candidate in [
Path(__file__).parent.parent.parent.parent / "VERSION", # repo root (dev)
@@ -88,6 +97,16 @@ class Settings(BaseSettings):
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")
+ app_origin = origin_of(self.oidc_redirect_uri)
+ allowed = {value.rstrip("/") for value in self.cors_origins}
+ if app_origin and app_origin not in allowed:
+ logger.warning(
+ "CORS_ORIGINS does not list %s (the origin of OIDC_REDIRECT_URI). "
+ "The CSRF check accepts that origin anyway, but add it to CORS_ORIGINS "
+ "so browser requests are not rejected: CORS_ORIGINS=[\"%s\"]",
+ app_origin,
+ app_origin,
+ )
return self
# Scanner
diff --git a/backend/app/core/security.py b/backend/app/core/security.py
index d893ad9..1f5f59e 100644
--- a/backend/app/core/security.py
+++ b/backend/app/core/security.py
@@ -14,7 +14,7 @@ from jwt import InvalidTokenError
from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
from starlette.responses import JSONResponse
-from app.core.config import settings
+from app.core.config import origin_of, settings
ACCESS_TOKEN_USE = "access"
OIDC_SESSION_TOKEN_USE = "oidc_session"
@@ -153,6 +153,13 @@ def origin_is_allowed(origin: str | None) -> bool:
if not origin:
return False
allowed_origins = {value.rstrip("/") for value in settings.cors_origins}
+ # A same-origin deployment behind a reverse proxy needs no CORS, so
+ # CORS_ORIGINS is often left at its localhost default — yet browsers still
+ # send Origin on unsafe methods. The OIDC callback URL is served by this app,
+ # so its origin is the app's own and is always a legitimate CSRF origin.
+ app_origin = origin_of(settings.oidc_redirect_uri)
+ if app_origin:
+ allowed_origins.add(app_origin)
return origin.rstrip("/") in allowed_origins
diff --git a/backend/tests/test_auth.py b/backend/tests/test_auth.py
index d41c1de..6571112 100644
--- a/backend/tests/test_auth.py
+++ b/backend/tests/test_auth.py
@@ -336,6 +336,80 @@ async def test_oidc_cookie_mutations_require_csrf_and_allowed_origin(client: Asy
assert (await client.get("/api/v1/auth/me")).status_code == 401
+async def test_oidc_mutation_allows_app_origin_missing_from_cors_origins(
+ client: AsyncClient, oidc_settings
+):
+ """Regression for #356: a same-origin reverse-proxy deploy needs no CORS, so
+ CORS_ORIGINS is left at its localhost default while the browser still sends
+ Origin — every POST used to 403."""
+ oidc_settings.cors_origins = ["http://localhost:5173", "http://localhost:3000"]
+ 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"]
+
+ created = await client.post(
+ "/api/v1/designs",
+ json={"name": "From OIDC", "design_type": "network"},
+ headers={"Origin": "http://test", "X-Homelable-CSRF": csrf_token},
+ )
+ assert created.status_code == 201
+
+ # The fallback widens the allowlist by exactly one origin, nothing more.
+ evil = await client.post(
+ "/api/v1/designs",
+ json={"name": "Nope", "design_type": "network"},
+ headers={"Origin": "https://evil.example", "X-Homelable-CSRF": csrf_token},
+ )
+ assert evil.status_code == 403
+
+
+def test_origin_is_allowed_falls_back_to_the_oidc_redirect_origin(oidc_settings):
+ from app.core.security import origin_is_allowed
+
+ oidc_settings.cors_origins = ["http://localhost:3000"]
+ oidc_settings.oidc_redirect_uri = "https://homelable.example.com/api/v1/auth/oidc/callback"
+
+ assert origin_is_allowed("https://homelable.example.com") is True
+ assert origin_is_allowed("https://homelable.example.com/") is True
+ assert origin_is_allowed("http://localhost:3000") is True
+ assert origin_is_allowed("https://evil.example") is False
+ assert origin_is_allowed(None) is False
+
+ # A redirect URI that is not an absolute URL contributes no origin.
+ oidc_settings.oidc_redirect_uri = "/api/v1/auth/oidc/callback"
+ assert origin_is_allowed("https://homelable.example.com") is False
+
+
+def test_oidc_settings_warn_when_cors_origins_omits_the_app_origin(caplog):
+ from app.core.config import Settings
+
+ base = {
+ "secret_key": "x" * 32,
+ "auth_mode": "oidc",
+ "oidc_discovery_url": "https://idp.example/.well-known/openid-configuration",
+ "oidc_client_id": "homelable",
+ "oidc_client_secret": "secret",
+ "oidc_redirect_uri": "https://homelable.example.com/api/v1/auth/oidc/callback",
+ }
+
+ with caplog.at_level("WARNING"):
+ Settings(**base, cors_origins=["http://localhost:3000"])
+ assert "https://homelable.example.com" in caplog.text
+ assert "CORS_ORIGINS" in caplog.text
+
+ caplog.clear()
+ with caplog.at_level("WARNING"):
+ Settings(**base, cors_origins=["https://homelable.example.com/"])
+ assert caplog.text == ""
+
+
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