Merge pull request #4799 from rommapp/fix/invalid-bearer-token-500

fix(auth): treat invalid bearer and basic credentials as unauthenticated
This commit is contained in:
Georges-Antoine Assi
2026-09-26 10:49:35 -04:00
committed by GitHub
4 changed files with 51 additions and 11 deletions

View File

@@ -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

View File

@@ -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
):

View File

@@ -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"

View File

@@ -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():