**The API.** Every route now lives under `/api/v1`, with `/api/...` rewritten
onto it — one route, two spellings, so they cannot drift and the OpenAPI
document describes each endpoint once. Errors carry an `error` object with a
stable code, one human sentence and, for a validation failure, the fields that
were wrong; `detail` is untouched so nothing that reads it breaks. The whole
surface — 320 routes, their parameters and their status codes — is checked in
as `backend/tests/api-contract.json`, and a test fails on any difference,
naming the routes that moved. `docs/api.md` is the contract in prose.
**Refresh tokens**, so an app can stay signed in without keeping a password.
Rows rather than signatures: listable, withdrawable, stored as hashes, rotated
on every use. A spent token coming back ends the whole session, because a theft
and a replay look identical from the server and the safe reading is the unsafe
one. A browser is not given one — it has nowhere to put it and a person to ask.
**An end-to-end stack**: `docker-compose.test.yml` with its own Postgres and
Redis, `e2e/seed.py` for the smallest world the tests name, and Playwright with
five projects — desktop, iPhone, Pixel, iPad and a browserless API project.
Devices because every bug reported this week was a phone bug found by a person
looking at a screenshot; a desktop-only suite would have passed through all of
them. Forty tests, five clean runs.
It found four things in its first hour:
- **A fresh deploy could not start.** `create_all()` ran before
`CREATE EXTENSION vector`, so any database that had never had pgvector
installed died on the first table with a vector column. Invisible here
because this one has had the extension for a year.
- **A figure in a published article was a 404 for everyone but an admin.**
Media in the library is nobody's to read by default, and nothing made an
exception for a drawing an article actually shows — so every illustration
added this week was an empty box for every real user.
- **Every rate limit was one bucket for the whole site.** The backend saw
nginx's address for every request, so ten bad passwords from anybody locked
out everybody, and no log line could say who. nginx now takes the real
address from the proxy and overwrites the header on the way in; uvicorn runs
with --proxy-headers.
- **The reading page's breakpoints disagreed** — 1150px in the component,
820px in the stylesheet. Between them the menu button claimed the contents
drawer and then toggled a class on a rail that was still in the layout: the
contents did not open and the site menu did not either. The button was dead
on every tablet.
And two smaller ones: the login limiter counted successful sign-ins, so eleven
people behind one hospital NAT locked each other out — it is cleared by a
correct password now; and `/uploads/{path}` served GET and HEAD from one route
with one operation id, which makes every OpenAPI client generator refuse the
document.
The first admin's password is generated and printed once at first start when
`DEFAULT_ADMIN_PASSWORD` is blank, rather than the account not existing:
`docker compose logs backend | grep -A3 "FIRST ADMIN"`.
CI (`.forgejo/workflows/tests.yml`) runs the backend suite, the contract, the
frontend suite and the build on every push to dev, main or master, and the
end-to-end stack on those branches and on pull requests into them.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TqXevQJhxFrM7jJg82cgZN
52 lines
2.3 KiB
Python
52 lines
2.3 KiB
Python
"""One API, addressed two ways.
|
|
|
|
Every route is mounted once, under `/api/v1`. `/api/...` is the same route
|
|
reached by its old address: the web app in this repository has thousands of
|
|
call sites written that way, and an address that has been shipped is a promise.
|
|
|
|
The alias is a path rewrite rather than a second `include_router`, for two
|
|
reasons. A second mount would double every path in the OpenAPI document, so the
|
|
contract an app is written against would describe each endpoint twice; and two
|
|
mounts can drift, while a rewrite cannot — there is only ever one route.
|
|
|
|
What this deliberately does *not* do is redirect. A 307 back to `/api/v1/...`
|
|
would break every non-browser client that does not follow redirects on POST,
|
|
and would leak the version into logs and bookmarks for no gain.
|
|
"""
|
|
from starlette.types import ASGIApp, Receive, Scope, Send
|
|
|
|
#: Anything under here is the API. `/uploads` and the docs are not.
|
|
API_ROOT = "/api"
|
|
CURRENT = "v1"
|
|
VERSIONED_ROOT = f"{API_ROOT}/{CURRENT}"
|
|
|
|
#: Addresses under /api that are not versioned routes and must pass untouched.
|
|
#: Kept explicit: a rewrite that silently swallowed one of these would be a 404
|
|
#: with no obvious cause — which is exactly what happened to /api/health the
|
|
#: first time this shipped. A liveness check is pointed at by monitoring that
|
|
#: nobody edits for a year; it does not move when the API is versioned.
|
|
PASSTHROUGH = ("/api/docs", "/api/redoc", "/api/openapi.json", "/api/health")
|
|
|
|
|
|
def is_versioned(path: str) -> bool:
|
|
return path == VERSIONED_ROOT or path.startswith(VERSIONED_ROOT + "/")
|
|
|
|
|
|
class VersionAlias:
|
|
"""Rewrite `/api/x` to `/api/v1/x` before routing sees it."""
|
|
|
|
def __init__(self, app: ASGIApp) -> None:
|
|
self.app = app
|
|
|
|
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
|
if scope["type"] == "http":
|
|
path = scope.get("path", "")
|
|
if (path.startswith(API_ROOT + "/") and not is_versioned(path)
|
|
and path not in PASSTHROUGH):
|
|
scope = dict(scope)
|
|
scope["path"] = VERSIONED_ROOT + path[len(API_ROOT):]
|
|
# Kept so a route, a log line or an error can say which address
|
|
# the caller actually used.
|
|
scope["raw_path"] = scope["path"].encode()
|
|
scope["api_alias"] = True
|
|
await self.app(scope, receive, send)
|