Tenant isolation for invoices and invoice lines with RLS policies
Database · PostgreSQL · advanced · modification
Moves tenant isolation for invoices into Postgres as a backstop. `migrations/0031_invoices_tenant_policies.sql` (new) enables and forces Postgres RLS on `invoices` and `invoice_lines` and adds one policy per table 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/invoices.py` switches its four endpoints to it. `tests/test_invoice_isolation.py` (new) covers the endpoints and the policies.
Invoicing app for agencies, about 1,200 tenants: 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 schema (earlier migrations): `invoices` (`id bigint GENERATED ALWAYS AS IDENTITY` primary key, `tenant_id bigint NOT NULL`, `customer_name text NOT NULL`, `status text NOT NULL DEFAULT 'open'` with a CHECK for `open`, `paid`, `void`, `created_at timestamptz NOT NULL DEFAULT now()`, `UNIQUE (tenant_id, id)`, index on `(tenant_id, created_at DESC, id DESC)`) and `invoice_lines` (`id bigint GENERATED ALWAYS AS IDENTITY` primary key, `tenant_id bigint NOT NULL`, `invoice_id bigint NOT NULL`, `description text NOT NULL`, `amount_cents bigint NOT NULL CHECK (amount_cents >= 0)`, foreign key `(tenant_id, invoice_id)` referencing `invoices (tenant_id, id)`, index on `(tenant_id, invoice_id)`). Only `app/invoices.py` reads or writes them. Roles: `billing_owner` owns the database, the schema and every table, and is used only by the migration runner; the API's pool connects as `billing_api` (`DATABASE_URL`; LOGIN, not a superuser, no BYPASSRLS, owns nothing), which has USAGE on the schema and SELECT, INSERT, UPDATE and DELETE on both tables from an earlier migration. No job or migration writes invoice rows as `billing_owner`; cross-tenant data fixes are done by the on-call DBA as a superuser. Migrations are plain SQL files in `migrations/`, applied in order as `billing_owner` by the existing runner, each file in its own transaction. A deploy stops the API, runs the pending migrations and then starts the new release, so no previous-release code runs against the new schema. `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, a positive `int`. Tests run with pytest against a fresh test database built from `migrations/` as `billing_owner`, with the API's pool connected as `billing_api` like production; `tests/conftest.py` provides `db` (a `billing_owner` connection, with both tables emptied before each test) and `client_for(tenant_id)` (a FastAPI `TestClient` signed in as a user of that tenant).
Requirements
- Row-level security on `invoices` and `invoice_lines`: every query the API runs reads, updates and deletes only rows of the request's tenant, including a query whose own `WHERE` has no `tenant_id` condition. This is a second line of defence behind the queries' own filters.
- An `INSERT` or `UPDATE` that would leave a row in a tenant other than the transaction's is rejected by the database, and an invoice line cannot point at another tenant's invoice.
- Fail closed: a transaction with no tenant set sees no rows and can write none, whether the setting was never set on the connection or was set by an earlier transaction on it.
- The request's tenant reaches the database per transaction: the invoice endpoints take their connection from a dependency that sets `app.tenant_id` for the current transaction only, so a pooled connection never carries one request's tenant into the next request.
- The policies also bind the tables' owner, so a service or script that connects with the migration credentials (`billing_owner`) is held to them too. Superuser sessions (the on-call DBA's runbook) are out of scope.
- Unchanged: the queries keep their own `tenant_id` filter, and `GET /api/invoices`, `GET /api/invoices/{id}` (404 for another tenant's invoice), `POST /api/invoices` and `POST /api/invoices/{id}/void` behave as before.
Files touched
- migrations/0031_invoices_tenant_policies.sql
- app/db.py
- app/invoices.py
- tests/test_invoice_isolation.py