Files
bike-app/apps/api/README.md
T
BBergleandClaude Opus 5 ddea750792
CI / Repo hygiene (pull_request) Successful in 3s
CI / Web (lint, typecheck, build) (pull_request) Successful in 2s
CI / Migrations reversible (pull_request) Successful in 12s
CI / API (lint, types, tests) (pull_request) Successful in 1m46s
feat(api): FastAPI skeleton with two-role RLS auth foundation
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>
2026-09-21 08:14:06 -04:00

105 lines
5.2 KiB
Markdown

# apps/api
Python 3.12 / FastAPI / SQLAlchemy 2.0 async / Alembic. See `docs/PLAN.md` for the overall
design and `docs/DECISIONS.md` for why things are built this way.
## Layout
```
velodrome/
app.py FastAPI app factory
config.py Settings (env-driven, see below)
db.py Two database engines — read this first, it's the load-bearing module
ids.py UUIDv7 generation
models/ SQLAlchemy models
auth/ Password hashing, session service, FastAPI auth dependencies
api/v1/ Route handlers
schemas/ Pydantic request/response models
alembic/ Migrations. 0001_baseline.py creates the identity tables, the two
runtime DB roles, and their RLS policies — read its module docstring.
tests/ pytest, against a real Postgres, never mocked
```
## Why two database connections
The app connects to Postgres as **two different roles**, not one — this is the single most
important thing to understand before touching `auth/` or `db.py`:
- **`velodrome_app`** — `NOBYPASSRLS`. Every request that already knows who's calling uses this,
via `db.scoped_session(user_id)`, which sets `app.user_id` for the transaction so Postgres RLS
policies can key off it.
- **`velodrome_auth`** — `BYPASSRLS`. Used *only* by `auth/service.py`, and only for the narrow
set of lookups that must happen *before* identity is known: login by email, a session by its
token hash, an invite by its code hash — plus the inserts that create those rows. Every one of
those queries is an exact match on a unique key, never an unfiltered scan, which is what makes
bypassing RLS safe there.
A third connection — `VELODROME_DATABASE_URL_MIGRATE` — is used only by Alembic. It needs enough
privilege to `CREATE ROLE` and `GRANT`, so in practice it's the Postgres superuser (or a
schema-owning role); the app itself never connects with it.
If you're adding a new table with per-user data: give it a `user_id` column, enable RLS on it in
a migration, and query it only through `scoped_session`. See CLAUDE.md's invariants.
## Environment variables
| Variable | Used by | Notes |
|---|---|---|
| `VELODROME_DATABASE_URL_MIGRATE` | Alembic only | Superuser/owner DSN. Never used by the app itself. |
| `VELODROME_DB_APP_PASSWORD` | Alembic (creates the role) | No default — the migration fails loudly if unset. |
| `VELODROME_DB_AUTH_PASSWORD` | Alembic (creates the role) | Same. |
| `VELODROME_DATABASE_URL_APP` | The app | Connects as `velodrome_app`. |
| `VELODROME_DATABASE_URL_AUTH` | The app | Connects as `velodrome_auth`. |
| `VELODROME_SECRET_KEY` | The app | Not yet used (arrives with the Bryton credential encryption in a later phase); declared now so the settings shape is stable. |
| `VELODROME_ENVIRONMENT` | The app | `development` / `test` / `production`. Gates the session cookie's `Secure` flag — see the comment in `api/v1/auth.py` before changing this condition. |
| `VELODROME_PUBLIC_URL` | The app | Used for the CSRF `Origin` check on cookie-authenticated mutations. |
## Running locally
```bash
uv sync --all-extras
# a throwaway Postgres
docker run -d --name velodrome-dev-pg -e POSTGRES_PASSWORD=postgres -e POSTGRES_DB=velodrome \
-p 5432:5432 postgis/postgis:16-3.4
export VELODROME_DATABASE_URL_MIGRATE=postgresql+asyncpg://postgres:postgres@localhost:5432/velodrome
export VELODROME_DB_APP_PASSWORD=devpassword1
export VELODROME_DB_AUTH_PASSWORD=devpassword2
export VELODROME_DATABASE_URL_APP=postgresql+asyncpg://velodrome_app:devpassword1@localhost:5432/velodrome
export VELODROME_DATABASE_URL_AUTH=postgresql+asyncpg://velodrome_auth:devpassword2@localhost:5432/velodrome
uv run alembic upgrade head
uv run uvicorn velodrome.app:app --reload
```
`GET /api/v1/healthz` should return `{"status": "ok"}`; `GET /api/v1/docs` has interactive
Swagger UI outside production.
## Testing
```bash
uv run ruff check . && uv run ruff format --check .
uv run mypy --strict velodrome
uv run pytest
```
Tests run against a real Postgres (a service container in CI, or point `tests/conftest.py`'s
defaults at your own) — never mocks for DB behaviour, per CLAUDE.md. The test suite runs the real
Alembic migration at session start, not a parallel schema-creation shortcut, so it's exercising
the exact same path a real deploy uses.
The test worth reading if you're new to this codebase is
`tests/test_auth.py::test_rls_blocks_cross_user_session_reads` — it doesn't trust that the RLS
policy SQL is correct because it reads correctly; it proves it by actually trying to read another
user's row through the scoped role and asserting zero come back.
## A note on `alembic check`
CI's `migrations` job runs `alembic check` to catch drift between the ORM models and the actual
migrations. `alembic/env.py`'s `include_object` filter restricts that comparison to tables our own
metadata declares — **deliberately an allowlist, not a denylist of PostGIS/TIGER tables**, because
reflected foreign tables can come back with `schema=None` regardless of which schema they actually
live in (confirmed against a real `postgis/postgis:16-3.4` container), which makes a schema-based
denylist unreliable. If you add a new model, it's automatically covered — no filter to update.