Skip to main content

rlsparity

Status: early alpha (0.2.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:

  1. What does the view return when the database does not enforce RLS?
  2. 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.

Usage

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.

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.

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.

Case defaults to method="GET". For a create, update or delete endpoint, use WriteCase (see below). Non-GET requests are rolled back.

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

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.

  1. Grant the writes to both roles. missing_grants covers 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;
  1. Add the statuses the endpoint returns to allowed_statuses. Writes often answer 201, 204 or 302, which are not in the default {200}:
RLSPARITY = {
    "context": set_context,
    "allowed_statuses": {200, 201, 204, 302},
    "denied_statuses": {403, 404},
}
  1. Declare a WriteCase. pk names the row for update and delete and is None for insert. values maps database column names to the values the write sets. data is forwarded to the view like Case.data. operation defaults 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",
)
  1. Run check, or check_all with 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

  1. 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]"
  1. Use the rlsparity_api fixture instead of rlsparity. It returns the same ParityChecker built on an APIClient. The context callable and the rest of RLSPARITY work as before.

  2. Declare the cases. A paginated list passes drf_ids() and drf_next_url. drf_ids() reads a top-level JSON list or a results list. drf_next_url reads next and keeps only the path and query, so a proxy or the testserver host 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"
  1. Set the request body format. data goes to APIClient, so the body follows REST_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"}
  1. Optional statuses. Under rlsparity_api the defaults are allowed {200, 201, 202, 204} and denied {401, 403, 404}. DRF answers 401 when the first authentication class sends an authenticate_header, for example Token, JWT or Basic. Explicit RLSPARITY settings 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_authenticate skips the real authentication classes. A bug in token or JWT parsing is not found.
  • drf_ids reads only a top-level list or a results envelope. A custom paginator needs its own ids and next_url callables, the same way as a plain Django view.
  • Page following stops after 100 pages and raises a clear error, so a broken next link 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 data is wrong. A 429 means turn throttling off in the test settings.
  • For writes, values must 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

  1. Add --rlsparity-report=PATH to the pytest command. Without the option nothing is written and nothing changes.
  2. Run pytest as usual. The file is written once at the end of the session, also when tests failed. Parent directories are created.
  3. 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.

Current limits

  • Write checks replay one declared statement. Multi-statement writes, triggers and side effects are not covered. values must 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 returns None (the DRF helper drf_next_url does this). Without next_url the view must return every row on one response.
  • Policies must be keyed on session settings applied through context, not on current_user or session_user (SET ROLE does not change session_user). A policy that uses either raises a PolicyUsesDatabaseUser precondition 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.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for rlsparity 0.2.0
File Size Uploaded Provenance Actions
rlsparity-0.2.0.tar.gz 57.3 kB Without provenance Details for rlsparity-0.2.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for rlsparity 0.2.0
File Interpreter ABI Platform Actions
rlsparity-0.2.0-py3-none-any.whl Python 3 none any Details for rlsparity-0.2.0-py3-none-any.whl

Total release size: 89.2 kB

Release files / rlsparity-0.2.0.tar.gz

Download URL rlsparity-0.2.0.tar.gz
Size 57.3 kB
Tags Source
SHA-256 checksum
How to use checksums
b4c62eaa46f32c0444d06e67ddc9b15daaf4f097df11d9c34aff4cfe20b5233f
BLAKE2b-256 checksum
How to use checksums
c528d635c5b174a4b8f19658e2f0406731643ee4a92cf9ff62576065ee337576
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.2.0-py3-none-any.whl

Download URL rlsparity-0.2.0-py3-none-any.whl
Size 31.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
d595e5dcad02e9f6acc106445212b6c7331ff9cfd68ba69d567e914c898dfd52
BLAKE2b-256 checksum
How to use checksums
beac0d741fa3b869b5bd7c710a750dcd13f454d433858fde01f8f89889dd0c87
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.2.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.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page