From ead613e26325640db1479f79cc4b48c88959006b Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Sat, 26 Sep 2026 10:43:36 -0400 Subject: [PATCH] fix(auth): treat invalid bearer and basic credentials as unauthenticated HybridAuthBackend runs inside Starlette's AuthenticationMiddleware, so an HTTPException raised while validating a JWT bearer token (expired, bad signature, garbage) or parsing a malformed Basic header bypassed FastAPI's exception handlers and surfaced as a 500 on every endpoint, including /api/heartbeat. Return None instead, matching the rmm_ client token path: public endpoints respond normally and protected ones return 401. Fixes #4788 Co-Authored-By: Claude Opus 5.5 (1M context) --- backend/handler/auth/hybrid_auth.py | 22 ++++++++++++----- backend/tests/endpoints/test_heartbeat.py | 5 +++- backend/tests/endpoints/test_platform.py | 5 ++++ backend/tests/handler/auth/test_auth.py | 30 ++++++++++++++++++++--- 4 files changed, 51 insertions(+), 11 deletions(-) diff --git a/backend/handler/auth/hybrid_auth.py b/backend/handler/auth/hybrid_auth.py index eb38a44cd..9b5ddf9b4 100644 --- a/backend/handler/auth/hybrid_auth.py +++ b/backend/handler/auth/hybrid_auth.py @@ -1,5 +1,6 @@ from datetime import datetime, timezone +from fastapi import HTTPException from fastapi.security.http import HTTPBasic from starlette.authentication import AuthCredentials, AuthenticationBackend from starlette.requests import HTTPConnection @@ -27,7 +28,8 @@ class HybridAuthBackend(AuthenticationBackend): user.set_last_active() return (AuthCredentials(user.oauth_scopes), user) - # Check if Authorization header exists + # Errors raised here bypass FastAPI's exception handlers and surface as 500s, + # so an unusable credential leaves the request unauthenticated instead if "Authorization" in conn.headers: auth_header_parts = conn.headers["Authorization"].split() if len(auth_header_parts) != 2: @@ -37,7 +39,10 @@ class HybridAuthBackend(AuthenticationBackend): # Check if basic auth header is valid if scheme.lower() == "basic": - credentials = await HTTPBasic().__call__(conn) # type: ignore[arg-type] + try: + credentials = await HTTPBasic().__call__(conn) # type: ignore[arg-type] + except HTTPException: + return None if not credentials: return None @@ -82,10 +87,15 @@ class HybridAuthBackend(AuthenticationBackend): return (AuthCredentials(effective_scopes), user) # OAuth JWT bearer tokens - ( - user, - claims, - ) = await oauth_handler.get_current_active_user_from_bearer_token(token) + try: + ( + user, + claims, + ) = await oauth_handler.get_current_active_user_from_bearer_token( + token + ) + except HTTPException: + return None if user is None or claims is None: return None diff --git a/backend/tests/endpoints/test_heartbeat.py b/backend/tests/endpoints/test_heartbeat.py index d17c80192..e9f7417d6 100644 --- a/backend/tests/endpoints/test_heartbeat.py +++ b/backend/tests/endpoints/test_heartbeat.py @@ -64,7 +64,10 @@ def test_heartbeat(client): assert isinstance(oidc["RP_INITIATED_LOGOUT"], bool) -@pytest.mark.parametrize("authorization_header", ["Bearer ", "Foo", "a b c"]) +@pytest.mark.parametrize( + "authorization_header", + ["Bearer ", "Foo", "a b c", "Bearer bogus", "Basic not_base64"], +) def test_heartbeat_with_malformed_authorization_header( client, authorization_header: str ): diff --git a/backend/tests/endpoints/test_platform.py b/backend/tests/endpoints/test_platform.py index 6286c76a9..422dc7cd7 100644 --- a/backend/tests/endpoints/test_platform.py +++ b/backend/tests/endpoints/test_platform.py @@ -18,6 +18,11 @@ def test_get_platforms(client, access_token, platform): assert len(platforms) == 1 +def test_get_platforms_with_invalid_bearer_token(client): + response = client.get("/api/platforms", headers={"Authorization": "Bearer bogus"}) + assert response.status_code == status.HTTP_401_UNAUTHORIZED + + def test_get_filesystem_platforms(client, access_token, platform): with patch( "utils.platforms.fs_platform_handler.get_platforms" diff --git a/backend/tests/handler/auth/test_auth.py b/backend/tests/handler/auth/test_auth.py index 498a56872..c160ee676 100644 --- a/backend/tests/handler/auth/test_auth.py +++ b/backend/tests/handler/auth/test_auth.py @@ -154,8 +154,30 @@ async def test_hybrid_auth_backend_bearer_invalid_token(editor_user: User): backend = HybridAuthBackend() conn = MockConnection() - with pytest.raises(HTTPException): - await backend.authenticate(conn) + result = await backend.authenticate(conn) + assert result is None + + +async def test_hybrid_auth_backend_bearer_expired_token(editor_user: User): + expired_token = oauth_handler.create_access_token( + data={ + "sub": editor_user.username, + "iss": "romm:oauth", + "scopes": " ".join(editor_user.oauth_scopes), + }, + expires_delta=timedelta(seconds=-1), + ) + + class MockConnection(HTTPConnection): + def __init__(self): + self.scope: dict[str, dict] = {"session": {}} + self._headers = Headers({"Authorization": f"Bearer {expired_token}"}) + + backend = HybridAuthBackend() + conn = MockConnection() + + result = await backend.authenticate(conn) + assert result is None async def test_hybrid_auth_backend_basic_auth_header(editor_user: User): @@ -189,8 +211,8 @@ async def test_hybrid_auth_backend_basic_auth_header_unencoded(editor_user: User backend = HybridAuthBackend() conn = MockConnection() - with pytest.raises(HTTPException): - await backend.authenticate(conn) + result = await backend.authenticate(conn) + assert result is None async def test_hybrid_auth_backend_invalid_scheme():