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>
81 lines
3.1 KiB
Python
81 lines
3.1 KiB
Python
"""Test fixtures.
|
|
|
|
Runs the real Alembic migrations once per session against a real Postgres (never mocked — see
|
|
CLAUDE.md's test policy), then truncates the identity tables between tests for isolation. This
|
|
deliberately exercises the exact same migration path CI's `migrations` job and a real deploy use,
|
|
not a parallel test-only schema-creation shortcut.
|
|
"""
|
|
|
|
import os
|
|
from collections.abc import AsyncIterator
|
|
|
|
import pytest
|
|
from alembic.config import Config
|
|
from sqlalchemy import text
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from alembic import command
|
|
|
|
os.environ.setdefault("VELODROME_ENVIRONMENT", "test")
|
|
|
|
# Test-only role passwords. Never used outside this process; the migration requires them to be
|
|
# set explicitly (see alembic/versions/0001_baseline.py::_require_password) rather than default
|
|
# to anything, on purpose — that's the same rule for a real deploy, just satisfied differently.
|
|
_APP_PW = "test-only-app-password"
|
|
_AUTH_PW = "test-only-auth-password"
|
|
|
|
os.environ.setdefault(
|
|
"VELODROME_DATABASE_URL_MIGRATE",
|
|
"postgresql+asyncpg://postgres:postgres@localhost:5432/velodrome_test",
|
|
)
|
|
os.environ.setdefault("VELODROME_DB_APP_PASSWORD", _APP_PW)
|
|
os.environ.setdefault("VELODROME_DB_AUTH_PASSWORD", _AUTH_PW)
|
|
os.environ.setdefault(
|
|
"VELODROME_DATABASE_URL_APP",
|
|
f"postgresql+asyncpg://velodrome_app:{_APP_PW}@localhost:5432/velodrome_test",
|
|
)
|
|
os.environ.setdefault(
|
|
"VELODROME_DATABASE_URL_AUTH",
|
|
f"postgresql+asyncpg://velodrome_auth:{_AUTH_PW}@localhost:5432/velodrome_test",
|
|
)
|
|
|
|
# Settings/engines must not be constructed before the env vars above are set, so these imports
|
|
# are deliberately below the os.environ.setdefault block, not at module top.
|
|
import httpx # noqa: E402
|
|
|
|
from velodrome.app import app # noqa: E402
|
|
from velodrome.db import auth_session # noqa: E402
|
|
|
|
|
|
@pytest.fixture(scope="session", autouse=True)
|
|
def _run_migrations() -> None:
|
|
cfg = Config(os.path.join(os.path.dirname(__file__), "..", "alembic.ini"))
|
|
cfg.set_main_option("script_location", os.path.join(os.path.dirname(__file__), "..", "alembic"))
|
|
command.downgrade(cfg, "base") # clean slate even on a reused test database
|
|
command.upgrade(cfg, "head")
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
async def _clean_tables() -> AsyncIterator[None]:
|
|
yield
|
|
async with auth_session() as db:
|
|
async with db.begin():
|
|
# DELETE, not TRUNCATE — velodrome_auth deliberately isn't granted TRUNCATE in
|
|
# production (see the migration's comment), and using the same privilege level in
|
|
# tests as in prod is the point. Children before parents for the FK constraints.
|
|
for table in ("sessions", "api_tokens", "invites", "users"):
|
|
await db.execute(text(f"DELETE FROM {table}"))
|
|
|
|
|
|
@pytest.fixture
|
|
async def db_auth() -> AsyncIterator[AsyncSession]:
|
|
async with auth_session() as db:
|
|
yield db
|
|
|
|
|
|
@pytest.fixture
|
|
async def client() -> AsyncIterator[httpx.AsyncClient]:
|
|
transport = httpx.ASGITransport(app=app)
|
|
async with httpx.AsyncClient(transport=transport, base_url="http://test") as c:
|
|
yield c
|