Skip to content

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

fix(auth): harden OIDC callback validation

ypso4d2284dc37ed
diff --git a/backend/app/api/routes/auth.py b/backend/app/api/routes/auth.py
index 2468c37..6f091c6 100644
--- a/backend/app/api/routes/auth.py
+++ b/backend/app/api/routes/auth.py
@@ -4,6 +4,7 @@ from collections.abc import Mapping
from typing import cast
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
@@ -86,7 +87,7 @@ async def oidc_callback(request: Request) -> Response:
client = get_oidc_client()
try:
token = await client.authorize_access_token(request)
- except OAuthError as exc:
+ 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
diff --git a/backend/app/core/config.py b/backend/app/core/config.py
index ec47043..192137c 100644
--- a/backend/app/core/config.py
+++ b/backend/app/core/config.py
@@ -79,8 +79,13 @@ class Settings(BaseSettings):
}.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 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
diff --git a/backend/tests/test_auth.py b/backend/tests/test_auth.py
index 76823b7..d41c1de 100644
--- a/backend/tests/test_auth.py
+++ b/backend/tests/test_auth.py
@@ -4,6 +4,7 @@ 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
@@ -11,7 +12,7 @@ from starlette.testclient import TestClient
class FakeOIDCClient:
- def __init__(self, token=None, error: OAuthError | None = None):
+ def __init__(self, token=None, error: OAuthError | JoseError | None = None):
self.token = token or {}
self.error = error
self.redirect_uri: str | None = None
@@ -290,6 +291,15 @@ async def test_oidc_callback_hides_protocol_error_details(client: AsyncClient, o
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
diff --git a/backend/tests/test_settings.py b/backend/tests/test_settings.py
index de68e07..8d1d7b0 100644
--- a/backend/tests/test_settings.py
+++ b/backend/tests/test_settings.py
@@ -203,6 +203,22 @@ def test_oidc_secure_cookie_requires_https_callback():
_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=["*"])