diff --git a/backend/common/core/deps.py b/backend/common/core/deps.py index 0dcef442..1b12070f 100644 --- a/backend/common/core/deps.py +++ b/backend/common/core/deps.py @@ -2,7 +2,7 @@ from typing import Annotated from urllib.parse import unquote -from fastapi import Depends, Request +from fastapi import Depends, HTTPException, Request from sqlmodel import Session from apps.system.schemas.system_schema import AssistantHeader, UserInfoDTO from common.core.db import get_session @@ -21,13 +21,23 @@ async def get_current_user(request: Request) -> UserInfoDTO: CurrentUser = Annotated[UserInfoDTO, Depends(get_current_user)] async def get_current_assistant(request: Request) -> AssistantHeader | None: - base_assistant = request.state.assistant if hasattr(request.state, "assistant") else None - if request.headers.get("X-SQLBOT-ASSISTANT-CERTIFICATE"): - entry_certificate = request.headers['X-SQLBOT-ASSISTANT-CERTIFICATE'] - base_assistant.certificate = unquote(base64.b64decode(entry_certificate).decode('utf-8')) - if request.headers.get("X-SQLBOT-ASSISTANT-ONLINE"): - entry_online = request.headers['X-SQLBOT-ASSISTANT-ONLINE'] - base_assistant.online = str(entry_online).lower() == 'true' if entry_online else False + base_assistant = getattr(request.state, "assistant", None) + if base_assistant is None: + # The certificate/online headers only describe an assistant identity that + # the middleware has already resolved. Without it they used to be written + # onto None and turn the request into a 500. + return None + entry_certificate = request.headers.get("X-SQLBOT-ASSISTANT-CERTIFICATE") + if entry_certificate: + try: + decoded_certificate = base64.b64decode(entry_certificate).decode("utf-8") + except ValueError: + # binascii.Error and UnicodeDecodeError both subclass ValueError. + raise HTTPException(status_code=400, detail="invalid assistant certificate") + base_assistant.certificate = unquote(decoded_certificate) + entry_online = request.headers.get("X-SQLBOT-ASSISTANT-ONLINE") + if entry_online: + base_assistant.online = str(entry_online).lower() == "true" return base_assistant CurrentAssistant = Annotated[AssistantHeader, Depends(get_current_assistant)] diff --git a/backend/tests/test_assistant_request_headers.py b/backend/tests/test_assistant_request_headers.py new file mode 100644 index 00000000..9e802f14 --- /dev/null +++ b/backend/tests/test_assistant_request_headers.py @@ -0,0 +1,86 @@ +"""Guard: assistant request headers must not turn a request into a 500. + +``get_current_assistant`` reads two optional headers. They describe an assistant +identity that the auth middleware resolves, so before this guard the header +values were written onto whatever ``request.state`` held: a request carrying the +header without an assistant identity raised ``AttributeError``, and a malformed +certificate raised a decoding error. Both surfaced as 500 instead of a usable +answer or a 400. +""" + +import asyncio +import base64 +from types import SimpleNamespace +from urllib.parse import quote + +import pytest +from fastapi import HTTPException +from starlette.requests import Request + +from common.core.deps import get_current_assistant + +_MISSING = object() + + +def _request(headers: dict[str, str], assistant=_MISSING) -> Request: + encoded = [(key.lower().encode(), value.encode()) for key, value in headers.items()] + request = Request( + { + "type": "http", + "method": "GET", + "path": "/", + "query_string": b"", + "headers": encoded, + } + ) + if assistant is not _MISSING: + request.state.assistant = assistant + return request + + +def test_header_without_assistant_identity_returns_none(): + request = _request({"X-SQLBOT-ASSISTANT-CERTIFICATE": "YWJj"}) + + assert asyncio.run(get_current_assistant(request)) is None + + +def test_online_header_without_assistant_identity_returns_none(): + request = _request({"X-SQLBOT-ASSISTANT-ONLINE": "true"}) + + assert asyncio.run(get_current_assistant(request)) is None + + +def test_certificate_header_is_decoded_and_unquoted(): + assistant = SimpleNamespace(certificate=None, online=None) + payload = '{"token":"a b"}' + header = quote(base64.b64encode(payload.encode()).decode()) + + result = asyncio.run( + get_current_assistant(_request({"X-SQLBOT-ASSISTANT-CERTIFICATE": header}, assistant)) + ) + + assert result is assistant + assert assistant.certificate == payload + + +def test_online_header_sets_the_flag(): + assistant = SimpleNamespace(certificate=None, online=None) + + result = asyncio.run( + get_current_assistant(_request({"X-SQLBOT-ASSISTANT-ONLINE": "TRUE"}, assistant)) + ) + + assert result.online is True + + +@pytest.mark.parametrize("header", ["A", "//4="]) +def test_unreadable_certificate_is_rejected(header): + assistant = SimpleNamespace(certificate=None, online=None) + + with pytest.raises(HTTPException) as excinfo: + asyncio.run( + get_current_assistant(_request({"X-SQLBOT-ASSISTANT-CERTIFICATE": header}, assistant)) + ) + + assert excinfo.value.status_code == 400 + assert assistant.certificate is None \ No newline at end of file