Skip to main content

rlsparity

Status: early alpha (0.1.0). The library works and is usable from git, but this is not a 1.0: the API may still change. Nothing is on PyPI. 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

rlsparity is not on PyPI. Install it from this repository, plus pytest-django and a PostgreSQL test database:

pip install "git+https://github.com/driftwright/rlsparity.git"
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.

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 write endpoint, set method="POST" (or PUT, PATCH, DELETE) and pass optional data={...}; non-GET requests are rolled back.

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

  • The view probe can issue GET, POST, PUT, PATCH and DELETE (Case.method, with optional Case.data); non-GET requests are rolled back. The policy side is still SELECT visibility of the named row, not WITH CHECK or insert, update and delete policies, so write-policy coverage is not claimed.
  • 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.1.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.1.0
File Size Uploaded Provenance Actions
rlsparity-0.1.0.tar.gz 26.3 kB Without provenance Details for rlsparity-0.1.0.tar.gz

Built distribution (wheel)

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

Total release size: 42.4 kB

Release files / rlsparity-0.1.0.tar.gz

Download URL rlsparity-0.1.0.tar.gz
Size 26.3 kB
Tags Source
SHA-256 checksum
How to use checksums
c361e351fd8fb54a4851b4c2802c91eb37e352f3930693092cc86824c24c31a1
BLAKE2b-256 checksum
How to use checksums
21aab0a56c0272102e0f96ed14b997c171ea5a6b3b67167b30fed6e68853d0ef
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.1.0-py3-none-any.whl

Download URL rlsparity-0.1.0-py3-none-any.whl
Size 16.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
b6c8ec7125788719388be8fc4c53035cc812b266a10275d1f8cc7841b5e8190c
BLAKE2b-256 checksum
How to use checksums
9d06f61315bb0ad888886659dbf776944018f7ae551336f6847d5daac96bbbef
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.1.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