A Row-Level Security Policy That Looked Right -- Until My Own Test Suite Proved It Wasn't
The problem A security review of a multi-tenant, payments-adjacent platform keeps showing up in the kind of work I do — row-level security correctness, ledger immutability, refund rules. So I built the subject matter f
The problem
A security review of a multi-tenant, payments-adjacent platform keeps showing up in the kind of work I do — row-level security correctness, ledger immutability, refund rules. So I built the subject matter from scratch, specifically so the review methodology itself is demonstrable instead of just described in a proposal.
What's enforced, and how
-
Tenant isolation: real PostgreSQL Row-Level Security,
FORCEd even for the table owner. Verified by connecting as an isolatedapp_userrole under different session contexts and actually trying to read another tenant's data — not by reading the policy and assuming it's correct. -
Ledger immutability: the app role was never granted
UPDATEorDELETEon the ledger table — enforced by Postgres's privilege system before a row-level policy is even evaluated. - Refund rules: a trigger rejects a refund that exceeds its charge's amount, and rejects a second refund against an already-refunded charge.
- Balance correctness: the account balance is a view computed from the ledger entries, never a stored column — there's no balance that can drift out of sync with the transactions that are supposed to explain it.
The real bug the test suite caught
The first version of the tenant-isolation policy had what looked like a reasonable admin-bypass shortcut:
USING (
current_setting('app.tenant_id', true) IS NULL
OR tenant_id = current_setting('app.tenant_id', true)::uuid
)
The intent: "no tenant context set means this must be an admin connection." The actual effect: any connection that simply forgot to set the tenant context — not an admin, just a bug — could see every tenant's data. A test written specifically to check this (test_no_tenant_context_sees_nothing) failed against it immediately.
The fix removes the special case entirely:
USING (tenant_id = current_setting('app.tenant_id', true)::uuid)
When the tenant isn't set, the comparison against NULL is UNKNOWN for every row, and Postgres RLS treats UNKNOWN as deny — so an unconfigured connection now correctly sees nothing. Admin access belongs on a separate role with BYPASSRLS, never a magic value threaded through the tenant policy.
Stack
PostgreSQL 16, Python, psycopg 3, pytest. CI runs against a real postgres:16 service container, not SQLite and not a mock.
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.