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>
This commit is contained in:
Georges-Antoine Assi
2026-11-21 16:37:42 -05:00
committed by GitHub
parent 38543d9bde
commit ca8efb7a11
8 changed files with 785 additions and 65 deletions

View File

@@ -395,7 +395,7 @@ async def search_cover(
isinstance(sgdb_result, HTTPException)
and sgdb_result.status_code == status.HTTP_401_UNAUTHORIZED
):
raise sgdb_result
raise sgdb_result # route-errors: raises 401
ordered_sources = get_priority_ordered_metadata_sources(
metadata_sources=list(lookups.keys()), priority_type="url_cover"

View File

@@ -261,19 +261,19 @@ def put_binary_json(
PUT a binary body to the broker and return its parsed JSON reply, or None
on failure. Best-effort, logs but never raises.
"""
req = urllib.request.Request(
broker_url(container, path),
data=content,
method="PUT",
headers={
"Content-Type": content_type,
"Content-Length": str(len(content)),
**broker_headers(container),
**(extra_headers or {}),
},
)
deadline = time.monotonic() + timeout
try:
req = urllib.request.Request(
broker_url(container, path),
data=content,
method="PUT",
headers={
"Content-Type": content_type,
"Content-Length": str(len(content)),
**broker_headers(container),
**(extra_headers or {}),
},
)
with urllib.request.urlopen(req, timeout=timeout) as resp: # nosec B310
body = json.loads(_read_bounded(resp, _BROKER_JSON_MAX_BYTES, deadline))
return body if isinstance(body, dict) else {}

View File

@@ -115,8 +115,23 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None]:
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",

View File

@@ -1,7 +1,7 @@
"""Checks that the OpenAPI document describes every operation."""
from main import app
from tools.route_errors import undocumented
from tools.route_errors import UNREADABLE_STATUS, stale, undocumented
HTTP_METHODS = ("get", "post", "put", "patch", "delete", "head")
@@ -31,8 +31,23 @@ def test_raised_statuses_are_documented():
# Assert
assert not gaps, (
"These routes raise statuses their `responses=` does not describe. Document"
" each one, or mark code whose errors never reach the client with"
" `# route-errors: ignore`:\n"
"These routes raise or return statuses their `responses=` does not describe."
" Document each one, or mark code whose errors never reach the client with"
f" `# route-errors: ignore`. A status of {UNREADABLE_STATUS} is one the"
" analyzer cannot read: use a literal status, or declare the statuses the"
" line can take with `# route-errors: raises <codes>`:\n"
+ "\n".join(f"{route} {codes}" for route, codes in gaps.items())
)
def test_documented_statuses_are_raised():
# Act
gaps = stale(app.routes)
# Assert
assert not gaps, (
"These routes document statuses they cannot raise. Remove each entry, or,"
" if the route does raise it in a way the analyzer cannot follow, declare"
" it on the line that raises it with `# route-errors: raises <codes>`:\n"
+ "\n".join(f"{route} {codes}" for route, codes in gaps.items())
)

View File

@@ -9,6 +9,7 @@ import zipfile
from collections.abc import Iterator
from concurrent.futures import ThreadPoolExecutor
from contextlib import contextmanager
from dataclasses import replace
from datetime import datetime, timedelta, timezone
from typing import Any, NamedTuple, cast
from unittest.mock import AsyncMock, MagicMock, patch
@@ -2939,6 +2940,16 @@ def test_containers_reports_a_container_that_can_never_be_claimed(client, access
assert response.json()["containers"][0]["configured"] is False
def test_put_binary_json_returns_none_without_a_broker_host():
container = replace(_resolved(_nested()), broker_host="")
assert (
broker.put_binary_json(
container, "/x", b"", "test", content_type="text/plain", timeout=1
)
is None
)
def test_containers_shows_what_is_running(client, access_token):
ps2_rom = _rom_on("ps2")
with _streaming(_nested()):

View File

@@ -1,9 +1,10 @@
"""Routes for test_route_errors, each raising at most a 409 from `refuse`."""
"""Routes for test_route_errors."""
import asyncio
from typing import Annotated
from fastapi import Depends, HTTPException, status
from fastapi import Depends, HTTPException, Response, status
from fastapi.responses import JSONResponse
def refuse() -> None:
@@ -38,3 +39,155 @@ def route_with_an_ignored_call() -> None:
def route_with_an_ignored_trailing_call() -> None:
refuse() # route-errors: ignore, the test checks that this call is left out.
def route_that_returns_an_error(found: bool) -> JSONResponse:
if found:
return JSONResponse({})
return JSONResponse({}, status_code=status.HTTP_410_GONE)
def _respond(status_code: int) -> Response:
return Response(status_code=status_code)
def route_that_forwards_a_status(locked: bool) -> Response:
return _respond(status.HTTP_423_LOCKED if locked else status.HTTP_204_NO_CONTENT)
_STATUS_BY_ERROR = {"bad": status.HTTP_400_BAD_REQUEST}
def route_with_a_status_map(error: str) -> None:
raise HTTPException(
status_code=_STATUS_BY_ERROR.get(error, status.HTTP_502_BAD_GATEWAY)
)
def route_with_a_status_variable() -> None:
code = status.HTTP_403_FORBIDDEN
raise HTTPException(status_code=code)
def route_with_an_unreadable_status(upstream: Response) -> Response:
return Response(status_code=upstream.status_code)
def route_that_refuses_input() -> None:
raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_CONTENT)
def route_with_input_that_it_refuses(name: str) -> None:
raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_CONTENT)
def refuse_in_a_thread() -> None:
raise HTTPException(status_code=status.HTTP_504_GATEWAY_TIMEOUT)
async def route_that_offloads() -> None:
await asyncio.to_thread(refuse_in_a_thread)
def route_that_swallows_errors() -> Response:
try:
refuse()
return JSONResponse({}, status_code=status.HTTP_410_GONE)
except Exception:
return Response()
def route_that_reraises() -> None:
try:
refuse()
except Exception:
raise
def route_with_a_declared_status(upstream: Response) -> Response:
return Response(status_code=upstream.status_code) # route-errors: raises 502
def route_with_a_declared_status_above(upstream: Response) -> Response:
# route-errors: raises 502, 503
return Response(status_code=upstream.status_code)
def route_with_markers_in_a_swallowing_try(upstream: Response) -> Response:
try:
refuse()
if upstream.headers:
# route-errors: ignore, the test checks that this line is left out.
return JSONResponse({}, status_code=status.HTTP_410_GONE)
return Response(status_code=upstream.status_code) # route-errors: raises 502
except Exception:
return Response()
def route_that_reraises_http_errors_first() -> None:
try:
refuse()
except HTTPException:
raise
except Exception:
return None
def route_with_a_status_from_its_input(code: int) -> Response:
return Response(status_code=code)
async def route_that_offloads_a_status() -> Response:
return await asyncio.to_thread(_respond, status.HTTP_423_LOCKED)
class Refusal(HTTPException):
def __init__(self, code: int) -> None:
super().__init__(status_code=code)
def route_that_raises_a_status_class() -> None:
raise Refusal(status.HTTP_451_UNAVAILABLE_FOR_LEGAL_REASONS)
def _refuse_with(detail: str, code: int = status.HTTP_418_IM_A_TEAPOT) -> None:
raise HTTPException(status_code=code, detail=detail)
def route_that_uses_a_default_status() -> None:
_refuse_with("no")
def _refuse_or_fail(code: int | None = None) -> None:
if code is None:
code = status.HTTP_500_INTERNAL_SERVER_ERROR
raise HTTPException(status_code=code)
def route_that_falls_back_to_a_status() -> None:
_refuse_or_fail()
def route_with_an_unpacked_status(error: str) -> None:
code = status.HTTP_400_BAD_REQUEST
if error:
code, _ = _STATUS_BY_ERROR.get(error, code), error
raise HTTPException(status_code=code)
UPSTREAM_DOWN = status.HTTP_503_SERVICE_UNAVAILABLE
def route_with_a_status_constant() -> None:
raise HTTPException(status_code=UPSTREAM_DOWN)
class GoneResponse(Response):
pass
def route_that_sets_a_status(response: Response, gone: bool) -> Response:
if gone:
return GoneResponse(status_code=status.HTTP_410_GONE)
response.status_code = status.HTTP_404_NOT_FOUND
return response

View File

@@ -1,4 +1,10 @@
from tools.route_errors import statuses
from fastapi import APIRouter, status
from tests.tools import route_errors_fixture as fixture_routes
from tools.route_errors import UNREADABLE_STATUS, stale, statuses, undocumented
from decorators.auth import SCOPE_ERRORS
FIXTURE = fixture_routes.__name__
def _raised(module: str, function: str) -> list[int]:
@@ -27,11 +33,11 @@ def test_follows_an_http_exception_subclass():
def test_follows_a_dependency_in_a_default():
assert _raised("tests.tools.route_errors_fixture", "route_with_a_default") == [409]
assert _raised(FIXTURE, "route_with_a_default") == [409]
def test_follows_a_dependency_in_an_annotated_alias():
assert _raised("tests.tools.route_errors_fixture", "route_with_an_alias") == [409]
assert _raised(FIXTURE, "route_with_an_alias") == [409]
def test_ignores_an_unrelated_function_with_the_same_name():
@@ -40,12 +46,139 @@ def test_ignores_an_unrelated_function_with_the_same_name():
def test_skips_a_gather_that_returns_exceptions():
fixture = "tests.tools.route_errors_fixture"
assert _raised(fixture, "route_that_gathers_errors") == []
assert _raised(fixture, "route_that_gathers") == [409]
assert _raised(FIXTURE, "route_that_gathers_errors") == []
assert _raised(FIXTURE, "route_that_gathers") == [409]
def test_skips_code_marked_as_ignored():
fixture = "tests.tools.route_errors_fixture"
assert _raised(fixture, "route_with_an_ignored_call") == []
assert _raised(fixture, "route_with_an_ignored_trailing_call") == []
assert _raised(FIXTURE, "route_with_an_ignored_call") == []
assert _raised(FIXTURE, "route_with_an_ignored_trailing_call") == []
def test_counts_a_returned_error_response():
assert _raised(FIXTURE, "route_that_returns_an_error") == [410]
def test_follows_a_status_passed_to_a_helper():
assert _raised(FIXTURE, "route_that_forwards_a_status") == [423]
def test_reads_every_status_of_a_status_map():
assert _raised(FIXTURE, "route_with_a_status_map") == [400, 502]
def test_reads_a_status_held_in_a_local_variable():
assert _raised(FIXTURE, "route_with_a_status_variable") == [403]
def test_flags_a_status_it_cannot_read():
assert _raised(FIXTURE, "route_with_an_unreadable_status") == [UNREADABLE_STATUS]
def test_skips_a_route_left_out_of_the_schema():
router = APIRouter()
router.get("/hidden", include_in_schema=False)(
fixture_routes.route_that_returns_an_error
)
assert undocumented(router.routes) == {}
def test_counts_422_as_documented_only_for_a_route_that_takes_input():
router = APIRouter()
router.get("/bare")(fixture_routes.route_that_refuses_input)
router.get("/input")(fixture_routes.route_with_input_that_it_refuses)
assert undocumented(router.routes) == {f"{FIXTURE}:route_that_refuses_input": [422]}
def test_follows_a_function_run_in_a_thread():
assert _raised(FIXTURE, "route_that_offloads") == [504]
def test_skips_a_try_that_swallows_errors_but_keeps_its_responses():
assert _raised(FIXTURE, "route_that_swallows_errors") == [410]
assert _raised(FIXTURE, "route_that_reraises") == [409]
def test_reads_declared_statuses_in_place_of_the_line():
assert _raised(FIXTURE, "route_with_a_declared_status") == [502]
assert _raised(FIXTURE, "route_with_a_declared_status_above") == [502, 503]
def test_flags_a_documented_status_the_route_cannot_raise():
router = APIRouter()
router.get(
"/stale",
responses={
status.HTTP_404_NOT_FOUND: {},
status.HTTP_409_CONFLICT: {"description": "Raised."},
status.HTTP_410_GONE: {"description": "No longer raised."},
},
)(fixture_routes.route_with_a_default)
assert stale(router.routes) == {f"{FIXTURE}:route_with_a_default": [404, 410]}
def test_counts_a_status_range_or_default_as_documented():
router = APIRouter()
router.get("/range", responses={"4XX": {"description": "A client error."}})(
fixture_routes.route_with_a_default
)
router.get("/default", responses={"default": {"description": "An error."}})(
fixture_routes.route_with_an_alias
)
assert undocumented(router.routes) == {}
assert stale(router.routes) == {}
def test_respects_markers_in_a_try_that_swallows_errors():
assert _raised(FIXTURE, "route_with_markers_in_a_swallowing_try") == [502]
def test_keeps_an_http_error_an_earlier_handler_reraises():
assert _raised(FIXTURE, "route_that_reraises_http_errors_first") == [409]
def test_flags_a_status_taken_from_the_request():
router = APIRouter()
router.get("/echo")(fixture_routes.route_with_a_status_from_its_input)
assert undocumented(router.routes) == {
f"{FIXTURE}:route_with_a_status_from_its_input": [UNREADABLE_STATUS]
}
def test_follows_a_status_passed_through_an_offload_or_a_class():
assert _raised(FIXTURE, "route_that_offloads_a_status") == [423]
assert _raised(FIXTURE, "route_that_raises_a_status_class") == [451]
def test_reads_the_default_of_a_status_left_out():
assert _raised(FIXTURE, "route_that_uses_a_default_status") == [418]
assert _raised(FIXTURE, "route_that_falls_back_to_a_status") == [500]
def test_flags_a_status_bound_in_a_way_it_cannot_read():
assert _raised(FIXTURE, "route_with_an_unpacked_status") == [
UNREADABLE_STATUS,
400,
]
def test_reads_a_module_level_status():
assert _raised(FIXTURE, "route_with_a_status_constant") == [503]
def test_counts_a_set_status_and_a_response_subclass():
assert _raised(FIXTURE, "route_that_sets_a_status") == [404, 410]
def test_skips_the_scope_guard_default_but_not_a_route_reason():
router = APIRouter()
router.get(
"/scoped",
responses={
status.HTTP_401_UNAUTHORIZED: {"description": SCOPE_ERRORS[401][0]},
status.HTTP_403_FORBIDDEN: {
"description": f"Not the owner. {SCOPE_ERRORS[403][1]}"
},
},
)(fixture_routes.route_with_a_default)
assert stale(router.routes) == {f"{FIXTURE}:route_with_a_default": [403]}

View File

@@ -11,13 +11,37 @@ from functools import cache
from pathlib import Path
from typing import Any
from fastapi.dependencies.utils import get_flat_params
from fastapi.routing import APIRoute
from decorators.auth import SCOPE_ERRORS
BACKEND = Path(__file__).resolve().parent.parent
STATUS_ATTR = re.compile(r"HTTP_(\d{3})_")
# Response classes a route can return instead of raising. Their status reaches the
# client.
RESPONSE_CLASSES = frozenset(
{
"FileResponse",
"HTMLResponse",
"JSONResponse",
"ORJSONResponse",
"PlainTextResponse",
"RedirectResponse",
"Response",
"StreamingResponse",
}
)
# Stands for a status the analyzer cannot read, such as one copied from an upstream
# response. A route that reaches one fails the check until that line declares its
# statuses with `RAISES_MARKER`.
UNREADABLE_STATUS = 0
# Marks code whose errors never reach the client. Put it at the end of the line, or
# on the line above, with the reason after it.
IGNORE_MARKER = "# route-errors: ignore"
# Declares the statuses a line raises when the analyzer cannot follow or read them,
# such as `# route-errors: raises 409, 423`. It replaces what the analyzer reads there.
RAISES_MARKER = re.compile(r"# route-errors: raises (\d{3}(?:, *\d{3})*)")
@dataclass
@@ -35,6 +59,8 @@ class Module:
assigns: dict[str, ast.expr] = field(default_factory=dict)
# Lines whose code `IGNORE_MARKER` leaves out of the analysis.
ignored: set[int] = field(default_factory=set)
# The statuses `RAISES_MARKER` declares, by line.
declared: dict[int, set[int]] = field(default_factory=dict)
def _module_name(path: Path) -> str:
@@ -63,8 +89,13 @@ def load(name: str) -> Module | None:
tree = ast.parse(source)
mod = Module(name, tree)
for number, line in enumerate(source.splitlines(), start=1):
if IGNORE_MARKER in line:
mod.ignored.add(number + 1 if line.lstrip().startswith("#") else number)
marked = number + 1 if line.lstrip().startswith("#") else number
match = RAISES_MARKER.search(line)
if IGNORE_MARKER in line or match:
mod.ignored.add(marked)
if match:
codes = {int(code) for code in re.findall(r"\d{3}", match.group(1))}
mod.declared.setdefault(marked, set()).update(codes)
is_package = path.name == "__init__.py"
for node in tree.body:
if isinstance(node, ast.ImportFrom):
@@ -170,6 +201,12 @@ def _resolve_expr(module: str, owner: str | None, expr: ast.expr) -> Symbol | No
return None
def _call_name(call: ast.Call) -> str | None:
"""The name a call ends in, such as `to_thread` for `asyncio.to_thread(...)`."""
func = call.func
return func.id if isinstance(func, ast.Name) else getattr(func, "attr", None)
def _status(node: ast.expr | None) -> int | None:
if isinstance(node, ast.Constant) and isinstance(node.value, int):
return node.value
@@ -180,6 +217,146 @@ def _status(node: ast.expr | None) -> int | None:
return None
@dataclass(frozen=True)
class Codes:
"""What a status expression can evaluate to."""
codes: frozenset[int] = frozenset()
# Parameters of the enclosing function that the status comes from.
params: frozenset[str] = frozenset()
# True when part of the expression cannot be read statically.
unreadable: bool = False
def __or__(self, other: Codes) -> Codes:
return Codes(
self.codes | other.codes,
self.params | other.params,
self.unreadable or other.unreadable,
)
def _params(fn: ast.AST | None) -> list[ast.arg]:
if not isinstance(fn, (ast.FunctionDef, ast.AsyncFunctionDef)):
return []
return [*fn.args.posonlyargs, *fn.args.args, *fn.args.kwonlyargs]
def _param_names(fn: ast.AST | None) -> list[str]:
return [param.arg for param in _params(fn)]
def _local_bindings(fn: ast.AST | None, name: str) -> tuple[list[ast.expr], bool]:
"""The values plain assignments give to the local `name` in `fn`, and whether any other statement binds it."""
if fn is None:
return [], False
values: list[ast.expr] = []
plain: set[int] = set()
for node in ast.walk(fn):
targets: list[ast.expr]
value: ast.expr | None
if isinstance(node, ast.Assign):
targets, value = node.targets, node.value
elif isinstance(node, ast.AnnAssign):
targets, value = [node.target], node.value
else:
continue
for target in targets:
if isinstance(target, ast.Name) and target.id == name:
plain.add(id(target))
if value is not None:
values.append(value)
# Tuple unpacking, `+=`, `for`, `with ... as` or `:=` give a value the
# analyzer does not read.
rebound = any(
isinstance(node, ast.Name)
and node.id == name
and isinstance(node.ctx, ast.Store)
and id(node) not in plain
for node in ast.walk(fn)
)
return values, rebound
def _default(callee: Symbol, param: str) -> ast.expr | None:
"""The default value of the callee's parameter `param`."""
located = _function_node(callee)
fn = located[0] if located else None
if not isinstance(fn, (ast.FunctionDef, ast.AsyncFunctionDef)):
return None
positional = [*fn.args.posonlyargs, *fn.args.args]
defaults = {
arg.arg: value
for arg, value in zip(
positional[len(positional) - len(fn.args.defaults) :],
fn.args.defaults,
strict=False,
)
}
for arg, value in zip(fn.args.kwonlyargs, fn.args.kw_defaults, strict=False):
if value is not None:
defaults[arg.arg] = value
return defaults.get(param)
def _module_dict(module: str, expr: ast.expr) -> ast.Dict | None:
"""The literal dict a module-level name holds, such as a map of errors to statuses."""
if not isinstance(expr, ast.Name):
return None
sym = resolve(module, expr.id)
mod = load(sym[1]) if sym and sym[0] == "value" else None
value = mod.assigns.get(sym[2]) if mod and sym else None
return value if isinstance(value, ast.Dict) else None
def _codes(
expr: ast.expr | None, module: str, fn: ast.AST | None, depth: int = 0
) -> Codes:
"""The statuses a `status_code` expression in `fn`, or at module level when `fn` is None, can take."""
if expr is None or depth > 10:
return Codes(unreadable=True)
def union(exprs: Iterable[ast.expr]) -> Codes:
found = Codes()
for value in exprs:
found |= _codes(value, module, fn, depth + 1)
return found
code = _status(expr)
if code is not None:
return Codes(frozenset({code}))
# A `None` default stands for a status the callee picks itself.
if isinstance(expr, ast.Constant) and expr.value is None:
return Codes()
if isinstance(expr, ast.IfExp):
return union([expr.body, expr.orelse])
lookup = None
default = None
if isinstance(expr, ast.Subscript):
lookup = _module_dict(module, expr.value)
elif (
isinstance(expr, ast.Call)
and isinstance(expr.func, ast.Attribute)
and expr.func.attr == "get"
):
lookup = _module_dict(module, expr.func.value)
default = expr.args[1] if len(expr.args) > 1 else None
if lookup is not None:
return union([*lookup.values, *([default] if default else [])])
if isinstance(expr, ast.Name):
is_param = expr.id in _param_names(fn)
values, rebound = _local_bindings(fn, expr.id)
if is_param or values or rebound:
return Codes(
params=frozenset({expr.id}) if is_param else frozenset(),
unreadable=rebound,
) | union(values)
sym = resolve(module, expr.id)
mod = load(sym[1]) if sym and sym[0] == "value" else None
if mod and sym:
return _codes(mod.assigns[sym[2]], sym[1], None, depth + 1)
return Codes(unreadable=True)
def _subclasses_http_exception(module: str, owner: str | None) -> bool:
mod = load(module)
cls = mod.classes.get(owner) if mod and owner else None
@@ -189,12 +366,37 @@ def _subclasses_http_exception(module: str, owner: str | None) -> bool:
)
def _http_exception_status(
def _subclasses_response(cls: Symbol, depth: int = 0) -> bool:
"""Whether a class derives from one of `RESPONSE_CLASSES`."""
mod = load(cls[1])
node = mod.classes.get(cls[2]) if mod else None
if node is None or depth > 10:
return False
for base in node.bases:
if (
getattr(base, "id", None) or getattr(base, "attr", None)
) in RESPONSE_CLASSES:
return True
sym = _resolve_expr(cls[1], None, base)
if sym and sym[0] == "class" and _subclasses_response(sym, depth + 1):
return True
return False
def _builds_response(call: ast.Call, module: str, owner: str | None = None) -> bool:
"""Whether `call` constructs a response, including one of the codebase's own subclasses."""
if _call_name(call) in RESPONSE_CLASSES:
return True
target = _resolve_expr(module, owner, call.func) if module else None
return bool(target and target[0] == "class" and _subclasses_response(target))
def _status_expr(
call: ast.Call, module: str = "", owner: str | None = None
) -> int | None:
"""The status of `HTTPException(...)`, or of `super().__init__(...)` in a subclass."""
) -> ast.expr | None:
"""The status argument of an `HTTPException`, a subclass's `super().__init__` or a response."""
func = call.func
name = func.id if isinstance(func, ast.Name) else getattr(func, "attr", None)
name = _call_name(call)
is_super_init = (
name == "__init__"
and isinstance(func, ast.Attribute)
@@ -202,12 +404,29 @@ def _http_exception_status(
and getattr(func.value.func, "id", None) == "super"
and _subclasses_http_exception(module, owner)
)
if name != "HTTPException" and not is_super_init:
position: int | None
if name == "HTTPException" or is_super_init:
position = 0
elif name in RESPONSE_CLASSES:
position = 1
elif _builds_response(call, module, owner):
# A subclass's own signature is unknown, so only `status_code=` is read.
position = None
else:
return None
for kw in call.keywords:
if kw.arg == "status_code":
return _status(kw.value)
return _status(call.args[0]) if call.args else None
return kw.value
if position is None or len(call.args) <= position:
return None
return call.args[position]
def _http_exception_status(call: ast.Call) -> int | None:
"""The status of a module-level `HTTPException(...)` instance."""
if _call_name(call) != "HTTPException":
return None
return _status(_status_expr(call))
def _function_node(sym: Symbol) -> tuple[ast.AST, str | None] | None:
@@ -229,12 +448,59 @@ def _function_node(sym: Symbol) -> tuple[ast.AST, str | None] | None:
return None
# Calls that run a function passed as an argument and re-raise its errors, mapped
# to the position of that argument.
OFFLOADS = {"to_thread": 0, "run_in_threadpool": 0, "run_sync": 0, "run_in_executor": 1}
def _offloaded(call: ast.Call) -> ast.Call | None:
"""The call an offload such as `asyncio.to_thread(fn, *args)` makes, as `fn(*args)`."""
name = _call_name(call)
position = OFFLOADS.get(name or "")
if position is None or len(call.args) <= position:
return None
return ast.Call(
func=call.args[position],
args=call.args[position + 1 :],
keywords=call.keywords,
)
BROAD_EXCEPTIONS = frozenset({"Exception", "BaseException", "HTTPException"})
def _swallows_errors(node: ast.AST) -> bool:
"""Whether `node` is a `try` whose first handler to catch an HTTP error never raises."""
if not isinstance(node, (ast.Try, ast.TryStar)):
return False
for handler in node.handlers:
caught = (
handler.type.elts if isinstance(handler.type, ast.Tuple) else [handler.type]
)
broad = handler.type is None or any(
(getattr(t, "id", None) or getattr(t, "attr", None)) in BROAD_EXCEPTIONS
for t in caught
)
if broad:
return not any(isinstance(n, ast.Raise) for n in ast.walk(handler))
return False
def _sets_status(node: ast.AST, module: str) -> bool:
"""Whether `node` builds a response or sets a `status_code`, which a swallowing `try` lets through."""
if isinstance(node, ast.Assign):
return any(
isinstance(target, ast.Attribute) and target.attr == "status_code"
for target in node.targets
)
return isinstance(node, ast.Call) and _builds_response(node, module)
def _returns_exceptions(node: ast.AST) -> bool:
"""Whether `node` is an `asyncio.gather(...)` that returns errors instead of raising them."""
if not isinstance(node, ast.Call):
return False
func = node.func
name = func.id if isinstance(func, ast.Name) else getattr(func, "attr", None)
name = _call_name(node)
return name == "gather" and any(
kw.arg == "return_exceptions"
and isinstance(kw.value, ast.Constant)
@@ -247,28 +513,79 @@ def _body_nodes(fn: ast.AST, module: str) -> list[ast.AST]:
"""Every node of a function except its decorators and the code whose errors never reach the caller."""
mod = load(module)
ignored = mod.ignored if mod else set()
roots: list[ast.AST] = (
[fn.args, *fn.body]
if isinstance(fn, (ast.FunctionDef, ast.AsyncFunctionDef))
else [fn]
)
# Each node to visit carries whether it sits in the body of a `try` that swallows errors.
roots: list[tuple[ast.AST, bool]] = [
(node, False)
for node in (
[fn.args, *fn.body]
if isinstance(fn, (ast.FunctionDef, ast.AsyncFunctionDef))
else [fn]
)
]
nodes: list[ast.AST] = []
while roots:
node = roots.pop()
node, swallowed = roots.pop()
if getattr(node, "lineno", None) in ignored or _returns_exceptions(node):
continue
nodes.append(node)
roots.extend(ast.iter_child_nodes(node))
# Only a status the swallowed code returns can still reach the caller.
if not swallowed or _sets_status(node, module):
nodes.append(node)
if not swallowed and _swallows_errors(node):
roots.extend((stmt, True) for stmt in node.body) # type: ignore[attr-defined]
roots.extend(
(child, False)
for child in [*node.handlers, *node.orelse, *node.finalbody] # type: ignore[attr-defined]
)
continue
roots.extend((child, swallowed) for child in ast.iter_child_nodes(node))
return nodes
_memo: dict[Symbol, frozenset[int]] = {}
# For each function, the parameters whose value becomes a raised or returned status.
_forwarded: dict[Symbol, frozenset[str]] = {}
def _argument(call: ast.Call, callee: Symbol, param: str) -> ast.expr | None:
"""The expression `call` passes to the callee's parameter `param`."""
for kw in call.keywords:
if kw.arg == param:
return kw.value
located = _function_node(callee)
names = _param_names(located[0]) if located else []
if located and located[1] is not None and names[:1] in (["self"], ["cls"]):
names = names[1:]
index = names.index(param) if param in names else len(call.args)
return call.args[index] if index < len(call.args) else None
def _passed(
call: ast.Call, callee: Symbol, param: str, module: str, fn: ast.AST
) -> Codes:
"""The statuses that `call`, made in `fn`, passes to the callee's parameter `param`."""
arg = _argument(call, callee, param)
if arg is not None:
return _codes(arg, module, fn)
if any(isinstance(a, ast.Starred) for a in call.args) or any(
kw.arg is None for kw in call.keywords
):
return Codes(unreadable=True)
default = _default(callee, param)
# A default is evaluated where the callee is defined.
return _codes(default, callee[1], None) if default is not None else Codes()
def _injected(target: Symbol, stack: frozenset[Symbol]) -> frozenset[int]:
"""The statuses of an endpoint or dependency. FastAPI fills its parameters from the request, so a status read from one is unreadable."""
found = statuses(target, stack)
if _forwarded.get(target):
return found | {UNREADABLE_STATUS}
return found
def _dependency(node: ast.Call) -> ast.expr | None:
"""The callable a `Depends(...)` or `Security(...)` call injects."""
func = node.func
name = func.id if isinstance(func, ast.Name) else getattr(func, "attr", None)
name = _call_name(node)
if name not in ("Depends", "Security"):
return None
for kw in node.keywords:
@@ -279,12 +596,9 @@ def _dependency(node: ast.Call) -> ast.expr | None:
def _annotation_names(fn: ast.AST) -> list[ast.Name]:
"""Names in a function's parameter annotations, where `Annotated` aliases sit."""
if not isinstance(fn, (ast.FunctionDef, ast.AsyncFunctionDef)):
return []
params = [*fn.args.posonlyargs, *fn.args.args, *fn.args.kwonlyargs]
return [
node
for param in params
for param in _params(fn)
if param.annotation is not None
for node in ast.walk(param.annotation)
if isinstance(node, ast.Name)
@@ -310,30 +624,49 @@ def statuses(sym: Symbol, stack: frozenset[Symbol] = frozenset()) -> frozenset[i
dependency = _dependency(node) if isinstance(node, ast.Call) else None
target = _resolve_expr(module, None, dependency) if dependency else None
if target and target[0] == "func":
found |= statuses(target, stack)
found |= _injected(target, stack)
elif kind == "class":
init = _method(sym, "__init__")
if init:
found |= statuses(init, stack)
elif kind == "func":
located = _function_node(sym)
forwarded: set[str] = set()
if located:
fn, owner = located
def add(codes: Codes) -> None:
found.update(codes.codes)
forwarded.update(codes.params)
if codes.unreadable:
found.add(UNREADABLE_STATUS)
for node in _body_nodes(fn, module):
if isinstance(node, ast.Call):
code = _http_exception_status(node, module, owner)
if code:
found.add(code)
status_expr = _status_expr(node, module, owner)
if status_expr is not None:
add(_codes(status_expr, module, fn))
continue
target = _resolve_expr(module, owner, node.func)
call = _offloaded(node) or node
target = _resolve_expr(module, owner, call.func)
if target and target[0] != "module":
found |= statuses(target, stack)
callee = (
_method(target, "__init__")
if target and target[0] == "class"
else target
)
if callee and callee[0] == "func":
for param in _forwarded.get(callee, frozenset()):
add(_passed(call, callee, param, module, fn))
dependency = _dependency(node)
target = (
_resolve_expr(module, owner, dependency) if dependency else None
)
if target and target[0] == "func":
found |= statuses(target, stack)
found |= _injected(target, stack)
elif isinstance(node, ast.Assign) and _sets_status(node, module):
add(_codes(node.value, module, fn))
elif isinstance(node, ast.Raise) and isinstance(
node.exc, (ast.Name, ast.Attribute)
):
@@ -344,7 +677,12 @@ def statuses(sym: Symbol, stack: frozenset[Symbol] = frozenset()) -> frozenset[i
target = _resolve_expr(module, owner, name_node)
if target and target[0] == "value":
found |= statuses(target, stack)
result = frozenset(c for c in found if c >= 400)
mod = load(module)
for line, codes in (mod.declared if mod else {}).items():
if fn.lineno <= line <= (fn.end_lineno or fn.lineno): # type: ignore[attr-defined]
found |= codes
_forwarded[sym] = frozenset(forwarded)
result = frozenset(c for c in found if c >= 400 or c == UNREADABLE_STATUS)
_memo[sym] = result
return result
@@ -358,25 +696,80 @@ def api_routes(routes: Iterable[Any]) -> Iterator[APIRoute]:
yield route
def _endpoint(route: APIRoute) -> tuple[str, frozenset[int]]:
"""A route's `module:function` key and the statuses its endpoint can raise."""
endpoint = inspect.unwrap(route.endpoint)
sym = ("func", endpoint.__module__, endpoint.__name__)
return f"{endpoint.__module__}:{endpoint.__name__}", _injected(sym, frozenset())
def _takes_input(route: APIRoute) -> bool:
"""Whether FastAPI validates input for the route, and so documents its 422."""
return bool(get_flat_params(route.dependant) or route.body_field)
def _documents(responses: dict[int | str, Any], code: int) -> bool:
"""Whether `responses` describes `code`, by itself or through `4XX` or `default`."""
keys = {str(key).upper() for key in responses}
return code != UNREADABLE_STATUS and (
str(code) in keys or f"{code // 100}XX" in keys or "DEFAULT" in keys
)
def undocumented(routes: Iterable[Any]) -> dict[str, list[int]]:
"""Map each route's `module:function` to the statuses it raises that its `responses` leaves out."""
gaps: dict[str, set[int]] = {}
for route in api_routes(routes):
endpoint = inspect.unwrap(route.endpoint)
documented = {int(code) for code in route.responses} | {422}
raised = statuses(("func", endpoint.__module__, endpoint.__name__))
missing = raised - documented
if not route.include_in_schema:
continue
key, raised = _endpoint(route)
takes_input = _takes_input(route)
missing = {
code
for code in raised
if not _documents(route.responses, code)
and not (code == 422 and takes_input)
}
if missing:
key = f"{endpoint.__module__}:{endpoint.__name__}"
gaps.setdefault(key, set()).update(missing)
return {key: sorted(codes) for key, codes in sorted(gaps.items())}
def stale(routes: Iterable[Any]) -> dict[str, list[int]]:
"""Map each route's `module:function` to the error statuses its `responses` lists but it cannot raise."""
scope_defaults = {code: alone for code, (alone, _) in SCOPE_ERRORS.items()}
gaps: dict[str, set[int]] = {}
for route in api_routes(routes):
if not route.include_in_schema:
continue
key, raised = _endpoint(route)
if UNREADABLE_STATUS in raised:
continue
takes_input = _takes_input(route)
for documented, entry in route.responses.items():
# A range such as `4XX`, or `default`, names no single status.
if not str(documented).isdigit():
continue
code = int(documented)
if code < 400 or code in raised or (code == 422 and takes_input):
continue
# The scope guard documents its own 401 and 403. Skip them unless the
# route added a reason to the description.
if code in scope_defaults and entry.get("description") == (
scope_defaults[code]
):
continue
gaps.setdefault(key, set()).add(code)
return {key: sorted(codes) for key, codes in sorted(gaps.items())}
def main() -> int:
from main import app # noqa: PLC0415
for key, codes in undocumented(app.routes).items():
print(key, codes)
print("undocumented", key, codes)
for key, codes in stale(app.routes).items():
print("stale", key, codes)
return 0