Files
romm/backend/utils/context.py
T
Georges-Antoine AssiandClaude Opus 5.5 c75437cc01 refactor(adapters): send provider requests through httpx2 (#5851)
* refactor(adapters): send provider requests through httpx2

The metadata provider adapters (IGDB, ScreenScraper, MobyGames,
RetroAchievements, Steam, SteamGridDB, libretro thumbnails) used aiohttp
while the rest of the backend used httpx2. They now share the request's
httpx2 client through `send_request` in provider_http.py, which bounds
the whole exchange with one timeout and follows redirects, as aiohttp
did. Each provider's auth middleware becomes an httpx2.Auth flow.

aiohttp was adopted because httpx logged request URLs carrying API
keys at INFO. The log formatter now masks every credential parameter
those URLs carry, so that reason no longer holds.

Behavior changes:
- Provider requests go through the SSRF-guarded client. Only tests
  ever pointed a provider at a custom base URL.
- A dropped connection is no longer resent once by the client; it
  surfaces as the existing 503.
- SteamGridDB's default base URL is www.steamgriddb.com. The bare
  domain answers with a cross-host 301, and httpx2 drops the
  Authorization header on that hop.

aiohttp, its OpenTelemetry instrumentation, and the packages only
aiohttp needed (aiohappyeyeballs, aiosignal, attrs, frozenlist) leave
the lockfile. The scripted test server becomes an httpx2.MockTransport,
and the aiohttp-recorded cassettes are adapted to what httpx2 sends:
masked credentials in the query, empty bodies as "", and no stale gzip
Content-Encoding headers on already-decompressed bodies.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(logging): keep provider API keys out of Sentry

The log formatter masks credential query parameters on stdout, but
Sentry's logging integration reads the raw record before any handler
formats it. Two paths sent provider keys to Sentry when SENTRY_DSN is
set:

- httpx2's INFO request line, which carries the authenticated URL, as a
  breadcrumb in the web process.
- An adapter's `log.error(exc)` on an error status, since an
  HTTPStatusError's message carries the same URL, as an event in the
  web and worker processes.

The `romm` logger now masks the record itself in a filter, which runs
before handlers and Sentry's hook. httpx2's request lines are no longer
emitted. Sentry's before_send and before_breadcrumb mask every string in
a payload, which covers exceptions captured directly, including their
messages and stack locals. The masking regex also stops at a single
quote, so httpx2's quoted URLs keep their closing quote.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* pr-ready: code-review

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* pr-ready: simplify

Set the RomM user agent and convert httpx2 timeouts to TimeoutError in send_request, so adapters drop their copies and send_with_retries catches a single timeout type. Read the ScreenScraper status code once in _handle_client_error.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* pr-ready: review-polish

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* pr-ready: prose

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* pr-ready: prose (code-review follow-up)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(logging): keep the log template when redacting a record

RedactFilter replaced msg with the formatted text and dropped args, so
Sentry grouped each redacted URL or game id as its own issue. It now
redacts the template and each argument in place, and falls back to the
flat text only when a secret spans the template and an argument.
pprint records keep their structured msg.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(screenscraper): pin dev credentials for the cassette tests

The cassettes now record devid and devpassword, since httpx2's auth flow
runs before VCR sees the request. CI has no developer credentials, so the
requests carried a blank devid= that VCR drops when matching, and all
seven integration tests failed to find their recording.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 20:43:32 -05:00

91 lines
2.6 KiB
Python

import ssl
from collections.abc import AsyncGenerator, Awaitable, Callable
from contextlib import asynccontextmanager
from contextvars import ContextVar, Token
from functools import partial
from typing import TYPE_CHECKING, TypeVar
import httpx2
from config import has_proxy_env
from utils.ssrf import (
INTERNAL_ORIGIN_ALLOWLIST,
install_async_ssrf_protection,
install_sync_ssrf_protection,
validate_url_for_http_request,
)
if TYPE_CHECKING:
from fastapi import Request, Response
_T = TypeVar("_T")
ctx_httpx_client: ContextVar[httpx2.AsyncClient] = ContextVar("httpx_client")
def _validate_request_url_sync(request: httpx2.Request) -> None:
validate_url_for_http_request(str(request.url))
async def _validate_request_url_async(
request: httpx2.Request, allowlist: frozenset[tuple[str, int]]
) -> None:
validate_url_for_http_request(str(request.url), allowlist=allowlist)
def create_httpx_async_client(
allowlist: frozenset[tuple[str, int]] = INTERNAL_ORIGIN_ALLOWLIST,
verify: ssl.SSLContext | bool = True,
) -> httpx2.AsyncClient:
"""An SSRF-guarded client that lets only `allowlist` origins reach private addresses."""
client = httpx2.AsyncClient(
trust_env=has_proxy_env(),
verify=verify,
event_hooks={
"request": [partial(_validate_request_url_async, allowlist=allowlist)]
},
)
install_async_ssrf_protection(client, allowlist=allowlist)
return client
def create_httpx_client() -> httpx2.Client:
client = httpx2.Client(
trust_env=has_proxy_env(),
event_hooks={"request": [_validate_request_url_sync]},
)
install_sync_ssrf_protection(client)
return client
@asynccontextmanager
async def set_context_var(var: ContextVar[_T], value: _T) -> AsyncGenerator[Token[_T]]:
"""Temporarily set a context variables."""
token = var.set(value)
try:
yield token
finally:
var.reset(token)
@asynccontextmanager
async def initialize_context() -> AsyncGenerator[None]:
"""Initialize context variables."""
async with (
create_httpx_async_client() as httpx_client,
set_context_var(ctx_httpx_client, httpx_client),
):
yield
async def set_context_middleware(
request: Request, call_next: Callable[[Request], Awaitable[Response]]
) -> Response:
"""Initialize context variables in FastAPI request-response cycle.
This middleware is needed because the context initialized during the lifespan
process is not available in the request-response cycle.
"""
async with set_context_var(ctx_httpx_client, request.app.state.httpx_client):
return await call_next(request)