Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 18 additions & 8 deletions backend/common/core/deps.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)]
Expand Down
86 changes: 86 additions & 0 deletions backend/tests/test_assistant_request_headers.py
Original file line number Diff line number Diff line change
@@ -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
Loading