rlsparity
Status: early alpha (0.3.0). 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.
- 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. Follow Install and
Settings and roles to point the plugin at your test
database, then copy the shape of the example's
CaseandListCasetests.
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},
}
See tests/demo/conftest.py for a complete fixture,
including the table, policy and grants.
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 [1, 2] from model contenttypes.Note to bob under RLS
This output comes from the leaky list view in
tests/demo/views.py. 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 /notes/partial/ as alice
view returned 200 with RLS bypassed; policy allows omitted ids [2] to alice under RLS
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. This is the leaky_update view in
tests/demo/views.py: bob updates alice's note, and the
update policy hides that row from him.
GAP PATCH /notes/1/leaky-update/ as bob
view returned 204 with RLS bypassed; policy rejects the update of contenttypes.Note.1 for bob under RLS
A create is a GAP in the same way when WITH CHECK rejects the new row. In this
example, bob creates a note with alice as the owner through the leaky_create
view:
GAP POST /notes/create/2/leaky/ as bob
view returned 201 with RLS bypassed; policy rejects the insert for bob under RLS
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.
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 demo run of a leaky paginated viewset. Alice owns the first three
visible rows and the leaked row is on page 2. Following next finds it. The demo
model is labelled contenttypes.Note because it borrows that app label.
GAP GET /api/notes-leaky/ as alice
view returned 200 with RLS bypassed; leaked ids [3] from model contenttypes.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 a leak on page 2 is missed.
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
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 the report from a demo run of tests/demo, using the correct detail view,
the correct list view and the leaky update. The ids depend on the database. The demo
model is labelled contenttypes.Note because it borrows that app label.
{
"version": 1,
"summary": {
"cases": 3,
"gap": 1,
"stricter": 0,
"ok": 2,
"errored": 0
},
"cases": [
{
"kind": "detail",
"verdict": "OK",
"method": "GET",
"url": "/notes/1/correct/",
"principal": "bob",
"model": "contenttypes.Note",
"view_status": 404,
"message": "",
"pk": 1,
"view_allowed": false,
"row_visible": false
},
{
"kind": "list",
"verdict": "OK",
"method": "GET",
"url": "/notes/own/",
"principal": "bob",
"model": "contenttypes.Note",
"view_status": 200,
"message": "",
"view_ids": [
3
],
"visible_ids": [
3
],
"leaked": [],
"omitted": []
},
{
"kind": "write",
"verdict": "GAP",
"method": "PATCH",
"url": "/notes/1/leaky-update/",
"principal": "bob",
"model": "contenttypes.Note",
"view_status": 204,
"message": "GAP PATCH /notes/1/leaky-update/ as bob\n view returned 204 with RLS bypassed; policy rejects the update of contenttypes.Note.1 for bob under RLS",
"operation": "update",
"pk": 1,
"view_allowed": true,
"row_visible": false
}
],
"mismatches": [
{
"index": 2,
"verdict": "GAP",
"message": "GAP PATCH /notes/1/leaky-update/ as bob\n view returned 204 with RLS bypassed; policy rejects the update of contenttypes.Note.1 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. |
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.
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 to list OK cases in the table too.
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.
- PostgreSQL, Django >= 4.2 and pytest are required.
Design
See DESIGN.md for the approach, scope and planned milestones.
License
MIT
Metadata
Release files for rlsparity 0.3.0
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.0.tar.gz | 97.2 kB | Without provenance | Details for rlsparity-0.3.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| rlsparity-0.3.0-py3-none-any.whl | Python 3 | none | any | Details for rlsparity-0.3.0-py3-none-any.whl |
Total release size: 139.5 kB
Release files / rlsparity-0.3.0.tar.gz
| Download URL | rlsparity-0.3.0.tar.gz |
|---|---|
| Size | 97.2 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
32907b726b36717ce12c3199cb856796e0f5cdfe03ec9b22113ead8d3205c193
|
|
BLAKE2b-256 checksum How to use checksums |
0ef152b1e9335ffce6383a1f6fd48949e874743b18488c9b4c5bb823988c5027
|
| 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.0-py3-none-any.whl
| Download URL | rlsparity-0.3.0-py3-none-any.whl |
|---|---|
| Size | 42.3 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
a98f2b73a3dea5e81caffd830689b66dabb1d056d77eb1d50f0625346c14bfc7
|
|
BLAKE2b-256 checksum How to use checksums |
6caaa5ef986a51c15b1adce4d8e6bcfda32aa51dad84ded1556995767ccfe804
|
| 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.0
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.