Phase 0's API half: a working FastAPI app with register/login/me/logout, backed by a Postgres schema where row-level security is real and independently proven, not just declared. The core design decision, and the reason this lands as one PR instead of several: request-scoped queries run as `velodrome_app` (NOBYPASSRLS), but looking up identity in the first place — login by email, a session by its token hash — has to happen *before* app.user_id can be set, so those specific lookups run as a second role, `velodrome_auth` (BYPASSRLS), used nowhere else in the codebase. See velodrome/db.py's module docstring and apps/api/README.md for the full rationale. This is genuinely one reviewable unit: the migration, the models, and the auth service only make sense evaluated together, since they're three views of the same invariant. tests/test_auth.py::test_rls_blocks_cross_user_session_reads is the test worth reading first — it doesn't trust the RLS policy SQL because it reads correctly, it proves isolation by registering two users and confirming a scoped read of `sessions` for user A returns exactly one row, never two. Bugs found and fixed while actually running this against real Postgres (everything below was verified against a live postgis/postgis:16-3.4 container and a built Docker image, not just read for correctness): - CREATE ROLE's PASSWORD clause is DDL, not DML — it doesn't accept bind parameters (`PASSWORD $1` is a syntax error). Fixed with dollar-quoting. - Postgres roles are cluster-wide, not per-database — a second database in the same cluster hit "role already exists" on a plain CREATE ROLE. Fixed with a DO block catching duplicate_object. - A bare `Mapped[datetime]` on the ORM models infers a naive timestamp, silently disagreeing with the migration's correct `DateTime(timezone=True)` — asyncpg rejected the mismatch at insert time. Fixed once, at the declarative Base level via type_annotation_map, rather than per-column. - The session cookie's `secure` flag was gated on `!= "development"`, so anything else — including local testing and a real deploy running temporarily without TLS in front — got a Secure cookie no HTTP client will ever send back, breaking every authenticated request after login with no visible error. Gated on `== "production"` instead. - `alembic check` initially flagged every PostGIS/TIGER-installed table (dozens of them) as drift, because they're not in our metadata. A schema-based denylist doesn't work — reflected foreign tables come back with schema=None regardless of their real schema. Fixed with an allowlist keyed on target_metadata.tables instead, which is also more robust against future PostGIS versions adding more tables. - The migration itself was missing `nullable=False` on three timestamp columns that the ORM model assumed were never null — a genuine model/migration drift that alembic check caught once the PostGIS noise above was filtered out. Fixed in 0001 directly, since it's never shipped. - Two indexes the migration creates explicitly weren't declared on the ORM models, causing the same kind of drift. Added index=True to match. Deliberately deferred, not forgotten: per-IP/per-account login rate limiting (docs/PLAN.md mentions it; Phase 0's bar is a working skeleton, and this needs its own design pass) and the procrastinate job runner / worker container (nothing to run yet — arrives with the ingestion pipeline). ci.yml updated to match: the api and migrations jobs now provision the same two runtime roles this code actually needs, replacing the single placeholder DATABASE_URL from before any code existed. Verified: ruff check, ruff format --check, and mypy --strict all clean. 12/12 pytest passing against a real Postgres. Full alembic upgrade -> downgrade -1 -> upgrade cycle run twice (once standalone, once inside a two-database cluster to specifically catch the role-collision bug). alembic check clean. Docker image builds and serves real traffic — register and an authenticated GET /me both exercised against the actual built container, not just the test suite. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
57 lines
2.4 KiB
Python
57 lines
2.4 KiB
Python
"""FastAPI dependencies for authenticating a request.
|
|
|
|
One verification path for two transports, per docs/PLAN.md "Auth": a bearer token in the
|
|
Authorization header takes priority (that's how a non-browser client, or a future native app,
|
|
would authenticate), falling back to the session cookie the PWA uses. The cookie is HttpOnly —
|
|
JavaScript never touches it — so it's read here purely server-side; the web client gets no
|
|
capability a bearer-authenticated client wouldn't also have.
|
|
|
|
CSRF: a cookie-authenticated request that MUTATES state must have an Origin header matching the
|
|
configured public URL. A bearer-authenticated request skips this check, because a cross-origin
|
|
attacker's page cannot set an Authorization header on a request it tricks the browser into
|
|
sending — that's the whole CSRF attack surface, and it doesn't exist for bearer auth.
|
|
"""
|
|
|
|
from fastapi import Cookie, Header, HTTPException, Request, status
|
|
|
|
from velodrome.auth.service import AuthenticatedSession, SessionInvalid, validate_session
|
|
from velodrome.config import get_settings
|
|
|
|
_UNAUTHORIZED = HTTPException(status.HTTP_401_UNAUTHORIZED, detail="not authenticated")
|
|
|
|
|
|
def _extract_bearer(authorization: str | None) -> str | None:
|
|
if authorization is None:
|
|
return None
|
|
scheme, _, token = authorization.partition(" ")
|
|
if scheme.lower() != "bearer" or not token:
|
|
return None
|
|
return token
|
|
|
|
|
|
async def get_current_user(
|
|
authorization: str | None = Header(default=None),
|
|
session_cookie: str | None = Cookie(default=None, alias="vd_session"),
|
|
) -> AuthenticatedSession:
|
|
raw_token = _extract_bearer(authorization) or session_cookie
|
|
if raw_token is None:
|
|
raise _UNAUTHORIZED
|
|
try:
|
|
return await validate_session(raw_token)
|
|
except SessionInvalid as exc:
|
|
raise _UNAUTHORIZED from exc
|
|
|
|
|
|
async def require_same_origin_for_cookie_auth(
|
|
request: Request,
|
|
authorization: str | None = Header(default=None),
|
|
) -> None:
|
|
"""Apply to every mutating route. No-ops for bearer auth; enforces Origin for cookie auth."""
|
|
if _extract_bearer(authorization) is not None:
|
|
return # bearer-authenticated; CSRF doesn't apply, see module docstring.
|
|
|
|
origin = request.headers.get("origin")
|
|
expected = get_settings().public_url.rstrip("/")
|
|
if origin is None or origin.rstrip("/") != expected:
|
|
raise HTTPException(status.HTTP_403_FORBIDDEN, detail="cross-origin request rejected")
|