Enforce tenant isolation for documents in the database

Database · PostgreSQL · intermediate · modification

Moves tenant isolation for documents into Postgres as a backstop. `migrations/0052_documents_tenant_policy.sql` (new) turns on Postgres RLS for `documents` and adds a policy that limits reads and writes to the tenant in `app.tenant_id`. `app/db.py` adds `get_tenant_conn`, which takes a pooled connection and sets `app.tenant_id` for the request's transaction with `set_config(..., true)`, and `app/documents.py` switches its three endpoints to it. `tests/test_documents_tenant.py` (new) covers the endpoints with documents in two tenants.

Multi-tenant notes app: PostgreSQL 16, Python 3.12, FastAPI 0.115, psycopg 3.2 with dict rows and psycopg_pool 3.2 (plain SQL, no ORM). Existing and unchanged: `documents` (migration `0001`: `id bigint GENERATED ALWAYS AS IDENTITY` primary key, `tenant_id bigint NOT NULL`, `title text NOT NULL`, `body text NOT NULL DEFAULT ''`, `updated_at timestamptz NOT NULL DEFAULT now()`, index on `(tenant_id, updated_at DESC, id DESC)`) holds the documents of about 900 tenants; only `app/documents.py` reads or writes it. Roles: the API and the migration runner both connect as the `app` role (LOGIN, not a superuser, no BYPASSRLS); `app` created every table in the schema, so it owns them, and there is no other application role. Migrations are plain SQL files in `migrations/`, applied in order by the existing runner, each file in its own transaction. `pool.connection()` (psycopg_pool) hands out a connection for the block and, when the block ends, commits the open transaction (rolls it back on an exception) and returns the connection to the pool. `app.auth.current_tenant` answers 401 itself unless the request has a signed-in user and returns that user's tenant id. Tests run with pytest against a fresh test database built from `migrations/` and connected as `app`, like production; `tests/conftest.py` provides `db` (a connection with `documents` emptied before each test) and `client_for(tenant_id)` (a FastAPI `TestClient` signed in as a user of that tenant).

Requirements

Files touched

Review this PR

Database practice