rlsparity
Status: early alpha (0.3.3). The library works and is on PyPI, but this is not a 1.0: the API may still change. See CHANGELOG.md for release notes.
Many Django apps use PostgreSQL row-level security (RLS) as a second layer behind their own permission checks. That works until the two layers disagree: a view checks "logged in and owner", the RLS policy also checks a visibility flag and a relationship, and nobody notices because RLS quietly hides the difference. Turn RLS off (a superuser connection in a script, a misconfigured role, a migration) and the view serves rows it never should have.
rlsparity is a pytest plugin that makes that gap visible. For each
(user, endpoint, row) you declare, it asks the same question two ways:
- What does the view return when the database does not enforce RLS?
- Can that user see the row when the database does enforce RLS?
If the view says yes where the policy says no, that endpoint depends on RLS to be safe. The test fails and names the endpoint, the user and the row.
It runs inside your existing test database and transactions. It does not parse policies or view code, so it works with whatever your policies and views actually do.
What it is not
- Not a policy linter. For static checks of the policies themselves, see pgrls and Supabase splinter.
- Not a policy generator. See django-rls and django-boundary.
- Not a black-box scanner. It needs your Django project and a PostgreSQL test database.
Quickstart in 5 minutes
Run the same check on a small two-tenant notes app, then point it at your own project.
The example has two tenants: alice in acme and bob in bravo. Each user has a note they may see and a note they must not. Two views are deliberately leaky and serve the other tenant's note; two filter correctly and hide it. The fixture therefore includes rows that must be rejected as well as rows that must be accepted.
- Clone the repository, create a virtual environment and install the plugin with pytest-django:
git clone https://github.com/driftwright/rlsparity.git
cd rlsparity
python -m venv .venv
source .venv/bin/activate
pip install -e . pytest-django
- Start PostgreSQL with Compose from the repository root:
docker compose -f examples/notes/compose.yaml up -d --wait
Then export the connection variables:
export RLSPARITY_DB_NAME=rlsparity_test
export RLSPARITY_DB_USER=postgres
export RLSPARITY_DB_PASSWORD=postgres
export RLSPARITY_DB_HOST=127.0.0.1
export RLSPARITY_DB_PORT=54321
An existing PostgreSQL server works too. For password authentication, set the
same variables. For peer authentication, leave USER, PASSWORD, HOST and
PORT unset and set only RLSPARITY_DB_NAME when the database is not
rlsparity_test. The test connection must be a superuser, because
ensure_roles creates the two parity roles. The
example README covers those details.
On Windows, use PowerShell. The python -m venv .venv and
pip install -e . pytest-django commands are the same; activate with
.venv\Scripts\Activate.ps1. Docker Desktop runs the same Compose command from
the repository root. Set the Compose connection values with $env: assignments:
python -m venv .venv
.venv\Scripts\Activate.ps1
pip install -e . pytest-django
docker compose -f examples/notes/compose.yaml up -d --wait
$env:RLSPARITY_DB_NAME = "rlsparity_test"
$env:RLSPARITY_DB_USER = "postgres"
$env:RLSPARITY_DB_PASSWORD = "postgres"
$env:RLSPARITY_DB_HOST = "127.0.0.1"
$env:RLSPARITY_DB_PORT = "54321"
Peer authentication is a Unix-only option. On Windows, set all five variables, whether you use the Compose database or a local password-authenticated server. See the example README for existing-server detail.
- Run the example tests from
examples/notes:
cd examples/notes
python -m pytest -v
The run ends like this (note ids can differ on a reused test database):
12 cases checked: 4 gap, 0 stricter, 8 ok, 0 errored
RESULT KIND METHOD URL PRINCIPAL VIEW POLICY
GAP detail GET /notes/1/leaky/ bob allowed (200) hidden
OK detail GET /notes/3/correct/ bob denied (404) hidden
OK detail GET /notes/5/leaky/ alice allowed (200) visible
GAP detail GET /notes/6/leaky/ alice allowed (200) hidden
GAP detail GET /notes/5/leaky/ bob allowed (200) hidden
OK detail GET /notes/6/leaky/ bob allowed (200) visible
OK detail GET /notes/7/correct/ alice allowed (200) visible
OK detail GET /notes/8/correct/ alice denied (404) hidden
OK detail GET /notes/7/correct/ bob denied (404) hidden
OK detail GET /notes/8/correct/ bob allowed (200) visible
GAP list GET /notes/leaky/ bob 2 ids 1 id
OK list GET /notes/correct/ bob 1 id 1 id
6 passed in 0.50s
Four cases are GAP: the leaky views serve a forbidden row, and the leaky list returns the other tenant's id. Eight are OK, including the correct views that hide the other tenant's note. The six tests pass because the example asserts the GAPs.
- Now do this in your app. Start with your own project
goes from install through one hand-written
Caseto--rlsparity-unused.
Start with your own project
The notes example shows the shape; this is the shortest path to a first check in your own app.
-
Install.
pip install rlsparityandpip install pytest-django. Install covers pointingDATABASESat PostgreSQL and settingDJANGO_SETTINGS_MODULEinpytest.ini. -
Roles. Follow Settings and roles to call
ensure_rolesand grant the two parity roles access. The test connection must be a superuser, becauseensure_rolescreates those roles. -
Write one
Case. Therlsparityfixture and the publicCase/PrincipalAPI are enough; nothing registers cases for you. This is the "correct view is OK" shape from A minimal check:
# tests/test_notes.py
from notes.models import Note
from rlsparity import Case, Principal
def test_own_note_matches_the_policy(rlsparity, rls_roles, bob, note_of_bob):
finding = rlsparity.check(
Case(
principal=Principal(bob, label="bob"),
url=f"/notes/{note_of_bob.pk}/correct/",
model=Note,
pk=note_of_bob.pk,
)
)
assert finding.verdict == "OK"
discover_paths lists URL-conf candidates without registering cases.
cases_from_paths turns them into Case / ListCase objects once you supply
the principals, models and pks or ids; you still pass the list to check_all.
See Candidates from a URL conf.
- See what's left. Run the tests with the unused-candidate report:
python -m pytest --rlsparity-unused=myproject.urls
Or set rlsparity_unused = myproject.urls in pytest.ini /
[tool.pytest.ini_options]. The report is opt-in and silent without the flag; it
does not register cases or request URLs. It fails the run on leftover candidates
only with --rlsparity-fail-on-unused or rlsparity_fail_on_unused = true, and
only while the report is on. Admin and static prefixes
are ignored by default; add more with --rlsparity-unused-ignore /
rlsparity_unused_ignore. The header is Unused URL-conf candidates (N):, so a
covered URL conf ends with:
Unused URL-conf candidates (0):
A non-empty report lists each candidate's kind, route, name and dotted view path. See Candidates from a URL conf for details.
To turn that same report into copy-paste stubs, add
--rlsparity-unused-stubs or set rlsparity_unused_stubs = true. Stubs print
only after the unused report is already on: list
candidates become ListCase, detail and other candidates become Case, and the
Principal, model and pk / ids placeholders are left for you to fill in.
Each stub has its kind, URL name and dotted view path in a comment above it. The
stubs are not registered or run. Failing the run on unused routes needs
--rlsparity-fail-on-unused or rlsparity_fail_on_unused = true.
Usage
A condensed checklist for setting up and fixing checks is in AGENTS.md.
Install
Install rlsparity from PyPI, plus
pytest-django and a PostgreSQL test
database:
pip install rlsparity
pip install pytest-django
In your test settings, point DATABASES at PostgreSQL, and tell pytest which
settings module to use, for example in pytest.ini:
[pytest]
DJANGO_SETTINGS_MODULE = myproject.settings_test
Settings and roles
The checks run as two PostgreSQL roles that ensure_roles creates:
rlsparity_enforced (no BYPASSRLS) and rlsparity_bypass (BYPASSRLS). Call
it from a fixture with an open transaction and a superuser connection:
# conftest.py
import pytest
from django.db import connection
from rlsparity import ensure_roles
@pytest.fixture
def rls_roles(db):
ensure_roles(connection)
with connection.cursor() as cursor:
# Enforced needs SELECT on the checked table. Bypass needs SELECT on
# that table and on every other table the view reads, e.g. auth_user.
cursor.execute(
"GRANT USAGE ON SCHEMA public "
"TO rlsparity_enforced, rlsparity_bypass"
)
cursor.execute("GRANT SELECT ON notes_note TO rlsparity_enforced")
cursor.execute(
"GRANT SELECT ON notes_note, auth_user TO rlsparity_bypass"
)
The roles and grants are transactional, so they disappear when the test
transaction rolls back. Depend on this fixture from each parity test, or make it
autouse=True.
These roles are cluster-wide: every test database in the cluster uses the same
two roles, and locks taken inside one test database cannot serialise setup
across workers. When a correct, committed setup already exists, ensure_roles
only reads pg_roles and pg_auth_members and issues no CREATE, ALTER or
GRANT, so parallel workers do not block each other.
To get that state, create the roles once in a committed setup, for example with
a session-scoped fixture (outside django_db, connections are in autocommit
mode):
@pytest.fixture(scope="session")
def committed_roles(django_db_setup, django_db_blocker):
from django.db import connections
with django_db_blocker.unblock():
ensure_roles(connections["default"])
Run the equivalent CREATE ROLE and GRANT statements once with psql
instead if you prefer. Do not mark that fixture with
@pytest.mark.django_db: its changes must commit. Per-test ensure_roles
calls then only read the roles.
Without a committed setup, each test transaction creates and rolls back the
roles. Parallel workers can then block on the role rows or race on CREATE ROLE, so keep the parity tests on one worker:
@pytest.mark.xdist_group("rlsparity")
def test_notes_list(rlsparity, rls_roles, alice):
...
pytest -n auto --dist loadgroup
--dist loadgroup sends every test carrying the same xdist_group value to the
same worker; it does not choose a particular worker. Tests without the marker
are still distributed normally.
This grant block is the manual fallback. missing_grants writes the same
statements from your cases, see the next section.
Find the missing grants
A run needs grants for both roles on every table the cases touch. When one is
missing, the check stops at the first one. missing_grants reports every missing
grant in one go. It inspects the declared cases and asks PostgreSQL which
privileges the two roles lack. It reports only. It does not execute anything.
Call it with the superuser connection and the cases you are about to check:
from django.db import connection
from rlsparity import missing_grants
cases = [detail_case, list_case]
for grant in missing_grants(connection, cases):
print(grant.sql)
The output is ready to paste into your fixture:
GRANT SELECT ON "auth_user" TO "rlsparity_bypass"
GRANT SELECT ON "notes_note" TO "rlsparity_enforced"
GRANT SELECT ON "notes_note" TO "rlsparity_bypass"
Each line is a Grant. Its .sql is the statement. It also has role,
privilege, kind ("schema", "table" or "sequence") and name.
Statements for schemas and sequences appear when they are missing too. The list
is deduplicated and in a stable order: schemas first, then tables, then
sequences, with the enforced role before the bypass role.
To fail with the whole list at once, use check_grants:
from rlsparity import check_grants
check_grants(connection, cases)
It raises MissingGrants, a PreconditionError, with every statement on its
own line. When you already have a checker, call checker.missing_grants(cases).
Some views read tables beyond their model, for example a join or a lookup. Add
those tables with extra_tables. The bypass role gets SELECT on each one,
because the view runs as bypass:
missing_grants(connection, cases, extra_tables=("notes_tag",))
The helper does not parse views or SQL. It knows the declared model table, the
user model table when a case has a logged-in principal, and extra_tables. A
view that reads another table needs that table in extra_tables. The manual
GRANT block above still works when you need it.
A test connection that is not a superuser
Real projects often connect their tests as the application role, so the app's
tests exercise RLS. ensure_roles needs a superuser to create the roles, so that
connection cannot call it. Use a second superuser connection to the same test
database once per session, in autocommit, and grant the parity roles to the app:
DATABASES["admin"] = {
**DATABASES["default"],
"USER": "postgres", # a superuser; set its PASSWORD too if it needs one
"PASSWORD": "...",
"TEST": {"MIRROR": "default"},
}
# conftest.py
import pytest
from django.db import connections
from rlsparity import BYPASS_ROLE, ENFORCED_ROLE, ensure_roles
@pytest.fixture(scope="session")
def rls_roles(django_db_setup, django_db_blocker):
# pytest-django blocks database access outside tests; open it for setup.
with django_db_blocker.unblock():
admin = connections["admin"]
ensure_roles(admin)
with admin.cursor() as cursor:
cursor.execute(f"GRANT {ENFORCED_ROLE}, {BYPASS_ROLE} TO notes_app")
cursor.execute(
f"GRANT USAGE ON SCHEMA public TO {ENFORCED_ROLE}, {BYPASS_ROLE}"
)
cursor.execute(f"GRANT SELECT ON notes_note TO {ENFORCED_ROLE}")
cursor.execute(
f"GRANT SELECT ON notes_note, auth_user TO {BYPASS_ROLE}"
)
yield
# Close the admin connection, or dropping the test database fails with
# "being accessed by other users".
with django_db_blocker.unblock():
connections["admin"].close()
The TEST mirror makes admin use the default test database. A plain
psycopg.connect(...) works too. The fixture runs outside django_db, so its
writes commit. Request rls_roles from your parity tests, or set
autouse=True. The normal rlsparity fixtures then work on the application
connection.
To build the checker without the shipped fixture:
import pytest
from django.conf import settings
from django.db import connection
from rlsparity import ParityChecker
@pytest.fixture
def checker(db, client):
return ParityChecker(client, connection, settings.RLSPARITY)
Without pytest-django's db fixture, wrap each check in transaction.atomic();
SET LOCAL ROLE needs an open transaction.
The roles persist in the cluster after the session, which is harmless: the next
run converges them. To remove them from a throwaway cluster, revoke their grants
first. DROP ROLE fails while grants in the database still depend on the role:
with django_db_blocker.unblock():
with connections["admin"].cursor() as cursor:
cursor.execute(f"DROP OWNED BY {ENFORCED_ROLE}, {BYPASS_ROLE}")
cursor.execute(f"DROP ROLE IF EXISTS {ENFORCED_ROLE}, {BYPASS_ROLE}")
Put it in the fixture above, before close(). DROP OWNED only touches the
database the connection uses, so repeat it for any other database you granted in.
Real application privileges
Instead of listing table grants by hand, grant the application role to both parity roles. They inherit the privileges your migrations already gave it:
@pytest.fixture
def rls_roles(db):
ensure_roles(connection)
with connection.cursor() as cursor:
cursor.execute("GRANT notes_app TO rlsparity_enforced, rlsparity_bypass")
This uses a superuser test connection. A role inherits table privileges from the
roles granted to it, but not SUPERUSER or BYPASSRLS, so the enforced role
stays enforced. If the granted role owns the table, its members count as the
owner and RLS is not applied to them (row_security_active is false). Grant a
runtime role that does not own the tables, or use FORCE ROW LEVEL SECURITY.
This shows up as an RLSNotActive error that names the owner membership.
Do not grant the same two roles in both directions: PostgreSQL rejects a membership loop. Use this direction with a superuser test connection, and the application-role direction above for a non-superuser one.
Policies must key on a session setting that your context callable applies. It
is called as context(cursor, user) after switching to each role, and user is
None for an anonymous principal:
# myproject/rls.py
def set_context(cursor, user):
cursor.execute(
"SELECT set_config('app.user_id', %s, true)",
["" if user is None else str(user.pk)],
)
Configure the plugin in your test settings:
# myproject/settings_test.py
from myproject.rls import set_context
RLSPARITY = {
"context": set_context,
# Optional; these are the defaults.
"allowed_statuses": {200},
"denied_statuses": {403, 404},
}
The public examples show a complete fixture setup, including the table, policy
and grants: examples/notes/tests/conftest.py
and examples/drf/tests/conftest.py. They key
the policy on app.tenant_id, not the app.user_id shown above, because each
example serves several tenants.
A minimal check
Assume a Note model with an owner field and two detail views:
# notes/views.py
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from .models import Note
@login_required
def leaky_note(request, pk):
# GAP: relies on RLS to hide other users' notes.
note = get_object_or_404(Note, pk=pk)
return HttpResponse(note.title)
@login_required
def correct_note(request, pk):
note = get_object_or_404(Note, pk=pk, owner=request.user)
return HttpResponse(note.title)
With URLs /notes/<pk>/leaky/ and /notes/<pk>/correct/, and fixtures bob
and note_of_alice, the checks look like this:
# tests/test_notes.py
import pytest
from notes.models import Note
from rlsparity import Case, ParityFailure, Principal
def test_leaky_view_is_reported_as_a_gap(rlsparity, rls_roles, bob, note_of_alice):
url = f"/notes/{note_of_alice.pk}/leaky/"
with pytest.raises(ParityFailure) as info:
rlsparity.check(
Case(principal=Principal(bob, label="bob"), url=url,
model=Note, pk=note_of_alice.pk)
)
message = str(info.value)
assert "GAP" in message
assert url in message
assert "bob" in message
def test_correct_view_matches_the_policy(rlsparity, rls_roles, bob, note_of_alice):
finding = rlsparity.check(
Case(
principal=Principal(bob, label="bob"),
url=f"/notes/{note_of_alice.pk}/correct/",
model=Note,
pk=note_of_alice.pk,
)
)
assert finding.verdict == "OK"
check returns a Finding and raises ParityFailure for a failing case.
check_all([...]) runs several cases and raises once at the end.
To check every principal against every row, build the cases with case_matrix
instead of writing each one by hand. This catches cross-tenant reads that a
hand-picked case would miss:
from rlsparity import Principal, case_matrix
findings = rlsparity.check_all(
case_matrix(
[Principal(alice, label="alice"), Principal(bob, label="bob")],
model=Note,
pks=[note_of_alice.pk, note_of_bob.pk],
url="/notes/{pk}/",
)
)
Case defaults to method="GET". For a create, update or delete endpoint, use
WriteCase (see below). Non-GET requests are rolled back.
Multiple databases
The rlsparity and rlsparity_api fixtures always use Django's default
database connection. To check a model on another alias, build a ParityChecker
with that connection:
import pytest
from django.conf import settings
from django.db import connections
from django.test import Client
from rlsparity import Case, ParityChecker, Principal
@pytest.mark.django_db(databases=["default", "other"])
def test_note_on_the_other_database(alice, note_of_alice):
checker = ParityChecker(Client(), connections["other"], settings.RLSPARITY)
finding = checker.check(
Case(
principal=Principal(alice, label="alice"),
url=f"/notes/{note_of_alice.pk}/",
model=Note,
pk=note_of_alice.pk,
)
)
assert finding.verdict == "OK"
List both aliases in databases so Django wraps each one in the test
transaction and rolls it back. The checker uses the connection you pass for its
preconditions and policy probes. The view still reads whichever database your
router sends it to, so point the model at the same alias in the router.
List endpoints
A detail check names one row. A list check compares the set of ids a list endpoint returns with the set of ids the policy allows for the principal.
Declare a ListCase with the URL, the model and an ids extractor. The
extractor is a dotted path into the JSON response or a callable:
# tests/test_notes_list.py
from notes.models import Note
from rlsparity import ListCase, Principal
def test_own_list_matches_the_policy(rlsparity, rls_roles, bob):
finding = rlsparity.check(
ListCase(
principal=Principal(bob, label="bob"),
url="/notes/own/",
model=Note,
ids="results.*.id",
)
)
assert finding.verdict == "OK"
The path results.*.id reads the results key, iterates the list and reads
id from each entry. Pass a callable when the response needs other handling:
def ids_from_response(response):
return [row["id"] for row in response.json()["results"]]
ListCase(principal=Principal(bob, label="bob"), url="/notes/own/",
model=Note, ids=ids_from_response)
By default the checker reads one response. Pass next_url to follow pages. It
receives a response and returns the next URL or None. The probe requests each
page as the same principal and merges the ids. The DRF helper drf_next_url
reads a next field, see "Django REST framework" below.
The checker requests the URL with RLS bypassed. It then reads the ids the policy
allows with RLS enforced. Every view id goes through the model's primary key
type, so the JSON string "3" and the database value 3 compare as equal. A
value that cannot be converted is a case error and is reported like any other
error.
A view id the policy hides, or an id that is not in the table, is a GAP.
check raises ParityFailure and the message names the method, URL, principal,
model and the leaked ids:
GAP GET /notes/leaky/ as bob
view returned 200 with RLS bypassed; leaked ids [9] from model notes.Note to bob under RLS
This output comes from the leaky list view in
examples/notes. Ids can differ on a reused
database; run with --create-db to see the same id. A view id the policy allows
but the view omits is STRICTER. The end-of-run summary reports it and the test
does not fail:
STRICTER GET /api/notes-leaky/ as alice
view returned 200 with RLS bypassed; policy allows omitted ids [7] to alice under RLS; those ids may be on a later page; pass next_url to check them
This is the leaky api.Note list in examples/drf,
checked without next_url, so page 1 omits alice's third note. Ids can differ on
a reused database; run with --create-db to see the same id.
Candidates from a URL conf
rlsparity.discover is an opt-in helper for listing the patterns a Django URL
conf already knows. Import it from your tests:
from rlsparity.discover import discover_paths
for candidate in discover_paths("myproject.urls"):
print(candidate.route, candidate.name, candidate.kind)
Each candidate has the pattern route (converters such as <int:pk> kept), the
namespaced name (or None), a rough kind: list, detail or other, and
view, the dotted path of the callback. A class-based view reports the class,
for example notes.views.NoteDetail, not ...as_view. Filter by it to pick a
candidate by the view it points at:
candidate = next(
c for c in discover_paths("myproject.urls")
if c.view == "notes.views.leaky_note"
)
The caller still supplies the principal, model and pk, and still constructs the
case. Build a detail case with reverse:
from django.urls import reverse
from notes.models import Note
from rlsparity import Case, Principal
candidate = next(
c for c in discover_paths("myproject.urls")
if c.name == "notes:note-detail"
)
case = Case(
principal=Principal(bob, label="bob"),
url=reverse(candidate.name, args=[note.pk]),
model=Note,
pk=note.pk,
)
It does not register cases, does not request any URL, and is not run by the
pytest plugin unless the test imports it. Version 1 covers path() and nested
include() (including namespaces). Anchors are stripped from joined
re_path() / router patterns, and named groups such as (?P<pk>[^/.]+) are
shown as <pk>. Other converters, including rewritten named groups, match one
path segment; <path:...> matches one or more path segments. This lets
unused-candidate matching work with the concrete URLs tests already use.
DefaultRouter-style format-suffix
routes (\.(?P<format>...) on the last segment) are shown as .<format> and
count as used when the unsuffixed base URL was checked. Under i18n_patterns,
candidates are listed without a language prefix, and a used URL whose first
segment is a language in settings.LANGUAGES covers that unprefixed candidate;
format-suffix matching still applies on the remainder. kind follows the same
path-shape rules as path(), while -list / -detail name suffixes still win.
It does not infer models, methods or concrete object URLs, does not walk the
Django admin specially, does not expand one candidate per language, and does
not invent custom converter behaviour beyond the re_path() and format-suffix
handling above.
cases_from_paths turns candidates into Case / ListCase objects once you
supply the principals, models and pks or ids. It does not request URLs or
register tests; you still pass the list to check_all.
from notes.models import Note
from rlsparity import Principal
from rlsparity.discover import cases_from_paths
cases = cases_from_paths(
"myproject.urls",
[Principal(bob, label="bob"), Principal(alice, label="alice")],
models={"notes:note-detail": Note, "notes:note-list": Note},
pks=[alice_note.pk, bob_note.pk],
ids="results.*.id",
)
findings = rlsparity.check_all(cases)
Unmapped or incomplete candidates are skipped; WriteCase is not built.
Format-suffix and other routes are left for hand-written cases.
Opt in to an end-of-run list of candidates that no checked case used with
pytest --rlsparity-unused=myproject.urls, or set
rlsparity_unused = myproject.urls in pytest.ini / [tool.pytest.ini_options].
Add ignore prefixes with --rlsparity-unused-ignore=PREFIX or the
rlsparity_unused_ignore linelist; they stack with the defaults for /admin/,
/static/, admin: and the admin/static view prefixes. The report does not
register cases or request URLs, and is silent unless opted in. It fails the run
on leftover candidates only when --rlsparity-fail-on-unused or
rlsparity_fail_on_unused = true is set.
A non-empty report shows each candidate's kind, route, name and dotted view
path. When a JSON report is also written, it includes the same list under
unused. Add --rlsparity-unused-stubs / rlsparity_unused_stubs to print
copy-paste ListCase / Case stubs for those candidates; they are not
registered or run.
Search and filter views
A search or list view that filters more strictly than the policy (a text query, a status filter, a tenant filter) hides rows the policy allows. Those rows are STRICTER findings. They do not fail and do not change the exit code, but they add noise to the summary.
Scope the case to the URL that returns everything the policy allows. Use no search text, every status, and one case per filter-free URL:
ListCase(principal=Principal(bob, label="bob"), url="/notes/?status=all",
model=Note, ids="results.*.id")
If you only care about one property, point the case at a narrower model or table. STRICTER alone is not a failure; the exit code is unchanged.
A denied response gives an empty set of view ids. If the policy also allows
nothing, the case is OK. check_all accepts Case, ListCase and WriteCase
in one list.
Write endpoints
A write check compares what a create, update or delete endpoint does with what the write policy allows for the principal. The view runs with RLS bypassed. The policy side replays the same single statement under the enforced role.
- Grant the writes to both roles.
missing_grantscovers the write privilege and the id sequence for a create, so add the write cases to the call in "Find the missing grants". The manual fallback is below. The view runs as the bypass role, the policy as the enforced role, and a create also needs the id sequence:
GRANT INSERT, UPDATE, DELETE ON notes_note TO rlsparity_enforced, rlsparity_bypass;
GRANT USAGE ON SEQUENCE notes_note_id_seq TO rlsparity_enforced, rlsparity_bypass;
- Add the statuses the endpoint returns to
allowed_statuses. Writes often answer201,204or302, which are not in the default{200}:
RLSPARITY = {
"context": set_context,
"allowed_statuses": {200, 201, 204, 302},
"denied_statuses": {403, 404},
}
- Declare a
WriteCase.pknames the row for update and delete and isNonefor insert.valuesmaps database column names to the values the write sets.datais forwarded to the view likeCase.data.operationdefaults from the method: POST is insert, PUT and PATCH are update, DELETE is delete.
from notes.models import Note
from rlsparity import Principal, WriteCase
WriteCase(
principal=Principal(bob, label="bob"),
url=f"/notes/{note_of_alice.pk}/update/",
model=Note,
pk=note_of_alice.pk,
values={"title": "x"},
method="PATCH",
data={"title": "x"},
operation="update",
)
- Run
check, orcheck_allwith any mix of case types.
The view write and the policy write both run in savepoints that are always rolled back. The database is not changed.
If the view allows a write that the policy rejects, the case is a GAP and the
test fails. In examples/drf, alice updates bob's note
through the leaky viewset, and the update policy hides that row from her:
GAP PATCH /api/notes-leaky/24/ as alice
view returned 200 with RLS bypassed; policy rejects the update of api.Note.24 for alice under RLS
A create is a GAP in the same way when WITH CHECK rejects the new row. In the
same example, bob inserts a note into alice's tenant through the leaky viewset:
GAP POST /api/notes-leaky/ as bob
view returned 201 with RLS bypassed; policy rejects the insert for bob under RLS
The .24 id comes from a fresh --create-db run of the DRF example suite; on a
reused database the id can differ.
If the view refuses a write that the policy allows, the case is STRICTER. It is
reported and the test does not fail. The line is built like a GAP line, with the
same view, status and row, but it says policy allows where the GAP line says
policy rejects.
A matching allow or deny is OK. Writes go through the same verdict table as reads.
Django REST framework
rlsparity ships an adapter for Django REST framework. It uses
rest_framework.test.APIClient, authenticates each principal with
force_authenticate, treats a 401 as denied by default and follows paginated
lists so a leak on a later page is still a GAP. Core never imports
rest_framework.
For a complete project you can run locally, see
examples/drf. It has two tenants, a leaky and a
correct viewset, paginated list checks and write checks. Start PostgreSQL with
examples/drf/compose.yaml, or use an existing server; the example README has
the commands.
Set up
- Install the extra. It needs
djangorestframework>=3.14. DRF 3.17 and later need Django 5.2, so a Django 4.2 project stays on DRF 3.16.
pip install "rlsparity[drf]"
-
Use the
rlsparity_apifixture instead ofrlsparity. It returns the sameParityCheckerbuilt on anAPIClient. Thecontextcallable and the rest ofRLSPARITYwork as before. -
Declare the cases. A paginated list passes
drf_ids()anddrf_next_url.drf_ids()reads a top-level JSON list or aresultslist.drf_next_urlreadsnextand keeps only the path and query, so a proxy or thetestserverhost does not matter.
from notes.models import Note
from rlsparity import Case, ListCase, Principal, WriteCase
from rlsparity.drf import drf_ids, drf_next_url
def test_notes_list(rlsparity_api, rls_roles, alice):
finding = rlsparity_api.check(
ListCase(
principal=Principal(alice, label="alice"),
url="/api/notes/",
model=Note,
ids=drf_ids(),
next_url=drf_next_url,
)
)
assert finding.verdict == "OK"
def test_notes_detail(rlsparity_api, rls_roles, alice, note_of_alice):
finding = rlsparity_api.check(
Case(
principal=Principal(alice, label="alice"),
url=f"/api/notes/{note_of_alice.pk}/",
model=Note,
pk=note_of_alice.pk,
)
)
assert finding.verdict == "OK"
def test_notes_create(rlsparity_api, rls_roles, bob):
finding = rlsparity_api.check(
WriteCase(
principal=Principal(bob, label="bob"),
url="/api/notes/",
model=Note,
values={"owner_id": bob.pk, "title": "new"},
method="POST",
data={"title": "new"},
)
)
assert finding.verdict == "OK"
- Set the request body format.
datagoes toAPIClient, so the body followsREST_FRAMEWORK["TEST_REQUEST_DEFAULT_FORMAT"]. Set it to"json"when the views expect JSON.
# myproject/settings_test.py
REST_FRAMEWORK = {"TEST_REQUEST_DEFAULT_FORMAT": "json"}
- Optional statuses. Under
rlsparity_apithe defaults are allowed{200, 201, 202, 204}and denied{401, 403, 404}. DRF answers 401 when the first authentication class sends anauthenticate_header, for example Token, JWT or Basic. ExplicitRLSPARITYsettings always win.
RLSPARITY = {
"context": set_context,
"allowed_statuses": {200, 201, 202, 204},
"denied_statuses": {401, 403, 404},
}
What you see
This is a real run of the leaky paginated viewset in
examples/drf. Alice has three notes and bob has one;
with page_size set to 2, page 1 holds alice's first two notes and page 2 starts
with her third and includes bob's. Following next finds the leak:
GAP GET /api/notes-leaky/ as alice
view returned 200 with RLS bypassed; leaked ids [4] from model api.Note to alice under RLS
Without next_url the same check reads page 1 only. It reports STRICTER when
the paginator hides rows the policy allows, so the leak on page 2 is missed:
STRICTER GET /api/notes-leaky/ as alice
view returned 200 with RLS bypassed; policy allows omitted ids [7] to alice under RLS; those ids may be on a later page; pass next_url to check them
Hyperlinked serializers
A HyperlinkedModelSerializer returns a url and no id. Pass your own
callable to ids and read the primary key from the URL:
def ids_from_url(response):
rows = response.json()["results"]
return [row["url"].rstrip("/").rsplit("/", 1)[-1] for row in rows]
ListCase(principal=Principal(bob, label="bob"), url="/api/notes/",
model=Note, ids=ids_from_url, next_url=drf_next_url)
DRF limits
force_authenticateskips the real authentication classes. A bug in token or JWT parsing is not found.drf_idsreads only a top-level list or aresultsenvelope. A custom paginator needs its ownidsandnext_urlcallables, the same way as a plain Django view.- Page following stops after 100 pages and raises a clear error, so a broken
nextlink cannot loop forever. - A later page that returns a status outside the allowed set raises an error. The first page decides whether the view is denied.
- Throttling and serializer validation are not checked. A 400 means the declared
datais wrong. A 429 means turn throttling off in the test settings. - For writes,
valuesmust still match what the serializer writes. - ADRF and async views are out of scope.
- DRF 3.14 is the minimum. DRF 3.17 and later need Django 5.2.
JSON report and CI
The terminal summary is for people. When CI or a dashboard needs the same result, ask for the JSON report.
Write the report
- Add
--rlsparity-report=PATHto the pytest command. Without the option nothing is written and nothing changes. - Run pytest as usual. The file is written once at the end of the session, also when tests failed. Parent directories are created.
- Read the file with any JSON tool. It is UTF-8, indented by two spaces, with a fixed key order and one trailing newline.
python -m pytest --rlsparity-report=reports/rlsparity.json
Instead of the flag, set rlsparity_report = PATH in pytest.ini or under
[tool.pytest.ini_options]; the --rlsparity-report flag wins when both are set.
When a report is written, the end-of-run summary names the file.
The report records the cases that ran through check or check_all on the
checker, in the order checked, including errors between findings. missing_grants
lists grants reported by checker.missing_grants or by a MissingGrants error
from check_all, deduplicated and in the same stable order as the helper.
What you see
This is a real report from a run of examples/drf on a
fresh test database (python -m pytest -v --create-db --rlsparity-report=...
from that directory). The model is api.Note. Ids depend on test order and can
differ on a reused database; --create-db is how to see the same ids.
{
"version": 1,
"summary": {
"cases": 10,
"gap": 4,
"stricter": 1,
"ok": 5,
"errored": 0
},
"cases": [
{
"kind": "list",
"verdict": "GAP",
"method": "GET",
"url": "/api/notes-leaky/",
"principal": "alice",
"model": "api.Note",
"view_status": 200,
"message": "GAP GET /api/notes-leaky/ as alice\n view returned 200 with RLS bypassed; leaked ids [4] from model api.Note to alice under RLS",
"view_ids": [
1,
2,
3,
4
],
"visible_ids": [
1,
2,
3
],
"leaked": [
4
],
"omitted": []
},
{
"kind": "list",
"verdict": "STRICTER",
"method": "GET",
"url": "/api/notes-leaky/",
"principal": "alice",
"model": "api.Note",
"view_status": 200,
"message": "STRICTER GET /api/notes-leaky/ as alice\n view returned 200 with RLS bypassed; policy allows omitted ids [7] to alice under RLS; those ids may be on a later page; pass next_url to check them",
"view_ids": [
5,
6
],
"visible_ids": [
5,
6,
7
],
"leaked": [],
"omitted": [
7
]
},
{
"kind": "list",
"verdict": "OK",
"method": "GET",
"url": "/api/notes-correct/",
"principal": "alice",
"model": "api.Note",
"view_status": 200,
"message": "",
"view_ids": [
9,
10,
11
],
"visible_ids": [
9,
10,
11
],
"leaked": [],
"omitted": []
},
{
"kind": "detail",
"verdict": "GAP",
"method": "GET",
"url": "/api/notes-leaky/16/",
"principal": "alice",
"model": "api.Note",
"view_status": 200,
"message": "GAP GET /api/notes-leaky/16/ as alice\n view returned 200 with RLS bypassed; policy hides api.Note.16 from alice under RLS",
"pk": 16,
"view_allowed": true,
"row_visible": false
},
{
"kind": "detail",
"verdict": "OK",
"method": "GET",
"url": "/api/notes-correct/20/",
"principal": "alice",
"model": "api.Note",
"view_status": 404,
"message": "",
"pk": 20,
"view_allowed": false,
"row_visible": false
},
{
"kind": "detail",
"verdict": "OK",
"method": "GET",
"url": "/api/notes-correct/17/",
"principal": "alice",
"model": "api.Note",
"view_status": 200,
"message": "",
"pk": 17,
"view_allowed": true,
"row_visible": true
},
{
"kind": "write",
"verdict": "GAP",
"method": "PATCH",
"url": "/api/notes-leaky/24/",
"principal": "alice",
"model": "api.Note",
"view_status": 200,
"message": "GAP PATCH /api/notes-leaky/24/ as alice\n view returned 200 with RLS bypassed; policy rejects the update of api.Note.24 for alice under RLS",
"operation": "update",
"pk": 24,
"view_allowed": true,
"row_visible": false
},
{
"kind": "write",
"verdict": "OK",
"method": "PATCH",
"url": "/api/notes-correct/25/",
"principal": "alice",
"model": "api.Note",
"view_status": 200,
"message": "",
"operation": "update",
"pk": 25,
"view_allowed": true,
"row_visible": true
},
{
"kind": "write",
"verdict": "GAP",
"method": "POST",
"url": "/api/notes-leaky/",
"principal": "bob",
"model": "api.Note",
"view_status": 201,
"message": "GAP POST /api/notes-leaky/ as bob\n view returned 201 with RLS bypassed; policy rejects the insert for bob under RLS",
"operation": "insert",
"pk": null,
"view_allowed": true,
"row_visible": false
},
{
"kind": "write",
"verdict": "OK",
"method": "POST",
"url": "/api/notes-correct/",
"principal": "bob",
"model": "api.Note",
"view_status": 201,
"message": "",
"operation": "insert",
"pk": null,
"view_allowed": true,
"row_visible": true
}
],
"mismatches": [
{
"index": 0,
"verdict": "GAP",
"message": "GAP GET /api/notes-leaky/ as alice\n view returned 200 with RLS bypassed; leaked ids [4] from model api.Note to alice under RLS"
},
{
"index": 1,
"verdict": "STRICTER",
"message": "STRICTER GET /api/notes-leaky/ as alice\n view returned 200 with RLS bypassed; policy allows omitted ids [7] to alice under RLS; those ids may be on a later page; pass next_url to check them"
},
{
"index": 3,
"verdict": "GAP",
"message": "GAP GET /api/notes-leaky/16/ as alice\n view returned 200 with RLS bypassed; policy hides api.Note.16 from alice under RLS"
},
{
"index": 6,
"verdict": "GAP",
"message": "GAP PATCH /api/notes-leaky/24/ as alice\n view returned 200 with RLS bypassed; policy rejects the update of api.Note.24 for alice under RLS"
},
{
"index": 8,
"verdict": "GAP",
"message": "GAP POST /api/notes-leaky/ as bob\n view returned 201 with RLS bypassed; policy rejects the insert for bob under RLS"
}
],
"missing_grants": []
}
| key | kinds | meaning |
|---|---|---|
version |
top level | Schema version, currently 1. |
summary |
top level | cases, gap, stricter, ok and errored counts, the same as the terminal line. |
cases |
top level | One object per checked case, in the order checked, including errors between findings. |
mismatches |
top level | The GAP and STRICTER cases as index (position in cases), verdict and message. |
missing_grants |
top level | role, privilege, kind, name and ready-to-run sql, or an empty list. |
unused |
top level | The unused URL-conf candidates as route, name, kind and view, or an empty list. Absent when the unused check is off. |
kind |
case | detail, list or write. |
verdict |
case | GAP, STRICTER, OK or ERROR. |
method, url, principal, model |
case | The checked request, principal and model. |
view_status |
case | The status the view returned, null when it was never computed. |
message |
case | The terminal message, "" for OK. |
pk, view_allowed, row_visible |
detail and write | The row, what the view allowed and what the policy allowed. For write cases row_visible is the policy outcome. |
operation |
write | insert, update or delete. For an ERROR case it is the value set on the case, or null. |
view_ids, visible_ids, leaked, omitted |
list | The ids the view returned and the ids the policy allows. leaked are returned but hidden by the policy. omitted are allowed by the policy but not returned. |
error |
ERROR | type and message, always the last key. Fields the run never computed are null. |
The schema version changes only on a breaking change. New keys may be added without a version bump, so ignore keys you do not know. A session that checked no case writes a valid report with zero counts and empty lists.
GitHub Actions
This workflow runs the checks against a Postgres service and uploads the report. It is a starting point for your project, not for this repository.
name: rlsparity
on: [push, pull_request]
permissions:
contents: read
jobs:
parity:
runs-on: ubuntu-latest
services:
postgres:
image: postgres:17
env:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: app_test
ports:
- 5432:5432
options: >-
--health-cmd "pg_isready -U postgres -d app_test"
--health-interval 10s
--health-timeout 5s
--health-retries 5
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with:
python-version: "3.12"
# Point your Django test settings at this service, for example through
# environment variables that your settings module reads: host localhost,
# port 5432, user postgres, password postgres.
- name: Install the project
run: |
python -m pip install --upgrade pip
pip install -r requirements.txt rlsparity pytest-django
- name: Run the RLS parity checks
run: python -m pytest --rlsparity-report=rlsparity-report.json
- name: Upload the JSON report
if: always()
uses: actions/upload-artifact@v7
with:
name: rlsparity-report
path: rlsparity-report.json
if-no-files-found: warn
It assumes a Postgres service with a health check, Django test settings that read
the service's host, port, user and password from the environment, and a superuser
connection role so ensure_roles can create the two parity roles. Set
DJANGO_SETTINGS_MODULE for your project as usual.
Reusable workflow
Projects that only want to call this repository can save the workflow below as
.github/workflows/rlsparity.yml. It starts Postgres, runs the shell command in
install, runs pytest, and uploads the JSON report.
name: rlsparity
on: [push, pull_request]
permissions:
contents: read
jobs:
parity:
uses: driftwright/rlsparity/.github/workflows/rlsparity.yml@v0.3.1
with:
install: pip install -r requirements.txt rlsparity pytest-django
Django settings should read RLSPARITY_DB_NAME, RLSPARITY_DB_USER,
RLSPARITY_DB_PASSWORD, RLSPARITY_DB_HOST and RLSPARITY_DB_PORT, or map
those to the project's own names. The workflow passes
--rlsparity-report at the repository root (default rlsparity-report.json) and
uploads that file even when the tests fail.
Useful inputs are working-directory, pytest-args, report-path,
python-version, django-settings-module, and the postgres-* inputs
(postgres-image, postgres-db, postgres-user, postgres-password). A project
that uses the DRF extra can pass
install: pip install -r requirements.txt "rlsparity[drf]" pytest-django. Pin @v0.3.1 to use the workflow shipped in that release, or @main to
follow the latest revision. This repository
calls the same workflow for examples/notes and examples/drf.
GAP and STRICTER
- GAP — the view returns the row with RLS bypassed, but the policy hides it.
The test fails with
ParityFailure. This is the dangerous case: the view is relying on RLS. - STRICTER — the view hides a row the policy would allow. It is reported, including in the end-of-run summary, but does not fail the test.
- A matching allow or deny is OK.
The end-of-run summary lists the non-OK cases in a table:
RESULT KIND METHOD URL PRINCIPAL VIEW POLICY
GAP detail GET /notes/1/ bob allowed (200) hidden
STRICTER detail GET /notes/2/ alice denied (403) visible
STRICTER list GET /notes/ bob 1 id 2 ids
ERROR write:update PATCH /notes/3/ bob - -
Run pytest with -v, or pass --rlsparity-all, to list OK cases in the table too.
--rlsparity-all does this without enabling pytest's verbose test listing. Set
rlsparity_all = true in pytest.ini, or under [tool.pytest.ini_options], for
the same effect. STRICTER is reported and does not fail the run unless you pass
--rlsparity-fail-on-stricter, or set rlsparity_fail_on_stricter = true in
pytest.ini / [tool.pytest.ini_options].
Current limits
- Write checks replay one declared statement. Multi-statement writes, triggers
and side effects are not covered.
valuesmust match what the view really writes, or the answer describes the declared write instead. - List checks read a single response unless you pass
next_url, which follows pages until the callable returnsNone(the DRF helperdrf_next_urldoes this). Withoutnext_urlthe view must return every row on one response. - Policies must be keyed on session settings applied through
context, not oncurrent_userorsession_user(SET ROLEdoes not changesession_user). A policy that uses either raises aPolicyUsesDatabaseUserprecondition error; this is a hard error, not a supported mode. The check looks at the policy expression itself, not at functions the policy calls. - Only explicitly declared cases are checked. It proves nothing about cases you
do not declare.
discover_pathscan list URL patterns from a conf but does not register or run them. The opt-in unused-candidate report is a listing, not a complete inventory.cases_from_pathsonly builds objects from a mapping you supply and does not register or run them by itself. - PostgreSQL, Django >= 4.2 and pytest are required. CI tests Python 3.10–3.13 with Django 4.2, 5.2 and 6.1; Django 6.1 needs Python 3.12 or later.
Design
See DESIGN.md for the approach, scope and planned milestones.
License
MIT
Metadata
Release files for rlsparity 0.3.3
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| rlsparity-0.3.3.tar.gz | 127.6 kB | Without provenance | Details for rlsparity-0.3.3.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| rlsparity-0.3.3-py3-none-any.whl | Python 3 | none | any | Details for rlsparity-0.3.3-py3-none-any.whl |
Total release size: 179.8 kB
Release files / rlsparity-0.3.3.tar.gz
| Download URL | rlsparity-0.3.3.tar.gz |
|---|---|
| Size | 127.6 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
24877693fee84c3bbf44cd3c765e871f36c17cfb75a2287ca3d827a214934379
|
|
BLAKE2b-256 checksum How to use checksums |
ca3a63641274b8e2b6b052033dfeb1bf0fa11023273ec654b9b32b7d11e64c46
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.5
|
Release files / rlsparity-0.3.3-py3-none-any.whl
| Download URL | rlsparity-0.3.3-py3-none-any.whl |
|---|---|
| Size | 52.2 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
53a105dd02ccb77609cb9cc85f1541273586329c6099543796c05dc0e925dc4a
|
|
BLAKE2b-256 checksum How to use checksums |
3aa1b0d23eceed5d32c300007080d928652c22d3fa1e048a3407874973968a5c
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.5
|
Security for rlsparity 0.3.3
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.