Metadata-Version: 2.5
Name: rlsparity
Version: 0.1.0
Summary: Pytest plugin that checks Django views against PostgreSQL row-level security: finds endpoints that would leak rows if RLS were off.
Project-URL: Homepage, https://github.com/driftwright/rlsparity
Project-URL: Issues, https://github.com/driftwright/rlsparity/issues
Author: driftwright
License: MIT
License-File: LICENSE
Keywords: authorization,django,postgresql,pytest,rls,row-level-security
Classifier: Development Status :: 3 - Alpha
Classifier: Framework :: Django
Classifier: Framework :: Pytest
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Security
Classifier: Topic :: Software Development :: Testing
Requires-Python: >=3.10
Requires-Dist: django>=4.2
Requires-Dist: psycopg[binary]>=3.1
Requires-Dist: pytest>=7
Provides-Extra: dev
Requires-Dist: pytest-django>=4.5; extra == 'dev'
Requires-Dist: ruff==0.17.6; extra == 'dev'
Description-Content-Type: text/markdown

# 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](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](https://github.com/pgrls/pgrls) and
  [Supabase splinter](https://github.com/supabase/splinter).
- Not a policy generator. See [django-rls](https://github.com/kdpisda/django-rls) and
  [django-boundary](https://github.com/icvoss/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](https://pytest-django.readthedocs.io/) and a PostgreSQL test
database:

```bash
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`:

```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:

```python
# 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:

```python
# 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:

```python
# 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`](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:

```python
# 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:

```python
# 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](DESIGN.md) for the approach, scope and planned milestones.

## License

MIT
