Files
romm/backend/main.py
Georges-Antoine Assi ca8efb7a11 test(api): check returned, forwarded and stale error statuses (#5715)
* test(api): check returned and forwarded error statuses too

The route error check only saw HTTPException with a literal status. It
now also counts error responses a route returns, statuses passed to a
helper, status maps, IfExp and local variables. A status it still cannot
read fails the check instead of passing silently. Routes left out of the
schema are skipped, and 422 counts as documented only when FastAPI
documents it. The API description now names the middleware errors no
route lists.

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

* test(api): fail on documented statuses a route cannot raise

Add a stale check, the reverse of the undocumented one. To keep its
false positives near zero, the analyzer now follows functions run
through asyncio.to_thread and similar offloads, and skips a try body
whose handler swallows every error (keeping the responses it returns).
A new `# route-errors: raises <codes>` marker declares what a line
raises when the analyzer cannot follow or read it.

Following offloads found an undocumented 502 on save-and-exit: a
container with no broker address fails the card wipe. search_cover
declares the SteamGridDB 401 it re-raises from a gather.

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

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: plain-prose

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

* pr-ready: code-review (best-effort broker PUT never raises)

put_binary_json looked up the broker URL outside its try, so a container
with no broker address raised a 502 from a helper documented as never
raising. Evacuation already fails first on that container, so the 502
documented on save-and-exit could not happen; drop it.

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

* pr-ready: plain-prose (code-review additions)

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

* pr-ready: review-polish (build a real container in the broker test)

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 16:37:42 -05:00

261 lines
10 KiB
Python

import asyncio
import logging.config
import re
from collections.abc import AsyncGenerator
from contextlib import asynccontextmanager, suppress
import uvicorn
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from starlette.middleware.authentication import AuthenticationMiddleware
from startup import main
import endpoints.sockets.activity # noqa
import endpoints.sockets.devices # noqa
import endpoints.sockets.logs # noqa
import endpoints.sockets.netplay # noqa
import endpoints.sockets.scan # noqa
import endpoints.sockets.sync # noqa
from config import (
DEV_HOST,
DEV_PORT,
DISABLE_CSRF_PROTECTION,
IS_PYTEST_RUN,
MAX_ASSET_UPLOAD_SIZE_BYTES,
OIDC_ENABLED,
ROMM_AUTH_SECRET_KEY,
ROMM_CORS_ALLOWED_ORIGINS,
ROMM_SESSION_SECURE_COOKIE,
cors_allow_credentials,
)
from endpoints.activity import router as activity_router
from endpoints.audit_events import router as audit_events_router
from endpoints.auth import router as auth_router
from endpoints.channels import router as channels_router
from endpoints.client_tokens import router as client_tokens_router
from endpoints.collections import router as collections_router
from endpoints.configs import router as configs_router
from endpoints.device import router as device_router
from endpoints.device.auth import router as device_auth_router
from endpoints.export import router as export_router
from endpoints.feeds import router as feeds_router
from endpoints.firmware import router as firmware_router
from endpoints.heartbeat import router as heartbeat_router
from endpoints.logs import router as logs_router
from endpoints.memory_cards import router as memory_cards_router
from endpoints.music import router as music_router
from endpoints.music_playlists import router as music_playlists_router
from endpoints.netplay import router as netplay_router
from endpoints.notification_channels import router as notification_channels_router
from endpoints.notifications import router as notifications_router
from endpoints.permissions import router as permissions_router
from endpoints.platform import router as platform_router
from endpoints.play_sessions import router as play_sessions_router
from endpoints.recommendations import router as recommendations_router
from endpoints.responses.streaming import SOCKET_PAYLOADS as STREAMING_SOCKET_PAYLOADS
from endpoints.roms import router as rom_router
from endpoints.saves import router as saves_router
from endpoints.screenshots import router as screenshots_router
from endpoints.search import router as search_router
from endpoints.snapshots import router as snapshots_router
from endpoints.states import router as states_router
from endpoints.stats import router as stats_router
from endpoints.streaming import router as streaming_router
from endpoints.sync import router as sync_router
from endpoints.tasks import router as tasks_router
from endpoints.user import router as user_router
from handler.activity_handler import activity_handler
from handler.auth.constants import SESSION_COOKIE_NAME
from handler.auth.hybrid_auth import HybridAuthBackend
from handler.auth.middleware.csrf_middleware import CSRFMiddleware
from handler.auth.middleware.redis_session_middleware import RedisSessionMiddleware
from handler.middleware.upload_size_middleware import UploadSizeLimitMiddleware
from handler.socket_handler import netplay_socket_handler, socket_handler
from handler.streaming.session_store import start_restart_grace
from logger.formatter import LOGGING_CONFIG
from utils import get_version
from utils.context import (
ctx_aiohttp_session,
ctx_httpx_client,
initialize_context,
set_context_middleware,
)
from utils.memory_cards import MEMORY_CARD_MAX_BYTES
from utils.openapi import publish_socket_payloads
from utils.sentry import init_sentry
logging.config.dictConfig(LOGGING_CONFIG)
@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncGenerator[None]:
async with initialize_context():
app.state.aiohttp_session = ctx_aiohttp_session.get()
app.state.httpx_client = ctx_httpx_client.get()
await start_restart_grace()
# Relay backend log lines to admin Socket.IO clients in real time.
log_forwarder_task: asyncio.Task[None] | None = None
if not IS_PYTEST_RUN:
from endpoints.sockets.logs import start_log_forwarder
log_forwarder_task = asyncio.create_task(start_log_forwarder())
try:
yield
finally:
await activity_handler.flush_refresh()
if log_forwarder_task is not None:
log_forwarder_task.cancel()
# Await the cancellation so the forwarder's cleanup (pubsub
# close, lock release) finishes before shutdown completes.
with suppress(asyncio.CancelledError):
await log_forwarder_task
init_sentry()
API_DESCRIPTION = """\
Each route lists the errors it can return. A few come from middleware that runs
before any route, so the routes don't list them:
- **403**: a request that changes data does not send the token from the
`romm_csrftoken` cookie in the `x-csrftoken` header. A request that signs in
with a Bearer or Basic `Authorization` header and has no signed-in session is
exempt, and so are the token routes such as `/api/token`.
- **400** or **413**: an upload to `/api/saves`, `/api/states`, `/api/screenshots`,
`/api/snapshots`, `/api/sync/retroarch` or `/api/memory-cards` has a
`Content-Length` header that is not a number (400), or a body larger than the
server allows (413).
"""
app = FastAPI(
title="RomM API",
description=API_DESCRIPTION,
version=get_version(),
lifespan=lifespan,
docs_url="/api/docs",
redoc_url="/api/redoc",
)
app.add_middleware(
CORSMiddleware,
allow_origins=ROMM_CORS_ALLOWED_ORIGINS,
allow_credentials=cors_allow_credentials(ROMM_CORS_ALLOWED_ORIGINS),
allow_methods=["*"],
allow_headers=["*"],
)
# Bounds asset upload requests before their multipart body is spooled to disk
app.add_middleware(
UploadSizeLimitMiddleware,
max_size=MAX_ASSET_UPLOAD_SIZE_BYTES,
paths=[
re.compile(r"^/api/saves"),
re.compile(r"^/api/states"),
re.compile(r"^/api/screenshots"),
re.compile(r"^/api/snapshots"),
re.compile(r"^/api/sync/retroarch"),
],
)
# Memory cards are bounded by what a broker will take, which is lower than the
# asset ceiling. Bounding them here too keeps a card the endpoint would refuse
# from being spooled to disk in full first.
app.add_middleware(
UploadSizeLimitMiddleware,
max_size=min(MEMORY_CARD_MAX_BYTES, MAX_ASSET_UPLOAD_SIZE_BYTES),
paths=[re.compile(r"^/api/memory-cards")],
)
if not IS_PYTEST_RUN and not DISABLE_CSRF_PROTECTION:
# CSRF protection (except endpoints listed in exempt_urls)
app.add_middleware(
CSRFMiddleware,
cookie_name="romm_csrftoken",
secret=ROMM_AUTH_SECRET_KEY,
cookie_secure=ROMM_SESSION_SECURE_COOKIE,
exempt_urls=[
re.compile(r"^/api/token.*"),
re.compile(r"^/api/client-tokens/exchange"),
re.compile(r"^/api/client-tokens/pair/.+/status"),
re.compile(r"^/api/auth/device/init/?$"),
re.compile(r"^/api/auth/device/token/?$"),
re.compile(r"^/ws"),
re.compile(r"^/netplay"),
],
)
# Handles both basic and oauth authentication
app.add_middleware(
AuthenticationMiddleware,
backend=HybridAuthBackend(),
)
# Enables support for sessions on requests
app.add_middleware(
RedisSessionMiddleware,
session_cookie=SESSION_COOKIE_NAME,
same_site="lax" if OIDC_ENABLED else "strict",
https_only=ROMM_SESSION_SECURE_COOKIE,
)
# Sets context vars in request-response cycle
app.middleware("http")(set_context_middleware)
app.include_router(heartbeat_router, prefix="/api")
app.include_router(auth_router, prefix="/api")
app.include_router(activity_router, prefix="/api")
app.include_router(audit_events_router, prefix="/api")
app.include_router(user_router, prefix="/api")
app.include_router(client_tokens_router, prefix="/api")
app.include_router(notifications_router, prefix="/api")
app.include_router(notification_channels_router, prefix="/api")
app.include_router(device_router, prefix="/api")
app.include_router(device_auth_router, prefix="/api")
app.include_router(play_sessions_router, prefix="/api")
app.include_router(platform_router, prefix="/api")
app.include_router(rom_router, prefix="/api")
app.include_router(recommendations_router, prefix="/api")
app.include_router(music_router, prefix="/api")
app.include_router(music_playlists_router, prefix="/api")
app.include_router(search_router, prefix="/api")
app.include_router(saves_router, prefix="/api")
app.include_router(states_router, prefix="/api")
app.include_router(snapshots_router, prefix="/api")
app.include_router(channels_router, prefix="/api")
app.include_router(sync_router, prefix="/api")
app.include_router(tasks_router, prefix="/api")
app.include_router(feeds_router, prefix="/api")
app.include_router(configs_router, prefix="/api")
app.include_router(stats_router, prefix="/api")
app.include_router(logs_router, prefix="/api")
app.include_router(screenshots_router, prefix="/api")
app.include_router(firmware_router, prefix="/api")
app.include_router(collections_router, prefix="/api")
app.include_router(export_router, prefix="/api")
app.include_router(netplay_router, prefix="/api")
app.include_router(permissions_router, prefix="/api")
app.include_router(memory_cards_router, prefix="/api")
app.include_router(streaming_router, prefix="/api")
app.mount("/ws", socket_handler.socket_app)
app.mount("/netplay", netplay_socket_handler.socket_app)
publish_socket_payloads(app, STREAMING_SOCKET_PAYLOADS)
# NOTE: This code is only executed when running the application directly,
# not by deployments using gunicorn.
if __name__ == "__main__":
import alembic.config
# Run migrations
alembic.config.main(argv=["upgrade", "head"])
# Run startup tasks
asyncio.run(main())
# Run application
uvicorn.run("main:app", host=DEV_HOST, port=DEV_PORT, reload=True, access_log=False)