Skip to main content

pytest-authz-matrix

CI Python License: MIT

Authorization contract testing for Python web APIs.

pytest-authz-matrix expands one pytest test into the complete actor x resource-relationship matrix for an endpoint. It has first-class adapters for Django REST Framework and FastAPI, with a generic fallback for custom test clients.

It is built for authorization bugs ordinary authentication tests miss:

  • a user retrieves another user's object by changing an ID;
  • a tenant administrator reaches an object belonging to another tenant;
  • a list endpoint leaks foreign rows while its detail endpoint is protected;
  • an endpoint returns 403 when policy requires concealing existence with 404;
  • a new API route ships without a corresponding authorization contract.

Status: 0.2.0 is alpha. Contracts remain explicit: the plugin discovers routes and tests declared authorization policy, but it does not guess arbitrary business authorization rules.

Installation

Core only:

pip install pytest-authz-matrix

Django REST Framework:

pip install "pytest-authz-matrix[django]"

FastAPI:

pip install "pytest-authz-matrix[fastapi]"

Quick start

Create authz-matrix.yml in the pytest root:

version: 1

actors:
  owner: owner_client
  outsider: outsider_client
  anonymous: anonymous_client

resources:
  booking:
    fixture: booking_matrix
    lookup: id

contracts:
  booking.retrieve:
    method: GET
    path: /api/bookings/{resource}
    route_name: booking-detail
    resource: booking
    matrix:
      owner:
        owned: allow
        foreign: conceal
      outsider:
        owned: conceal
        foreign: conceal
      anonymous:
        owned: unauthenticated
        foreign: unauthenticated

Bind a pytest test to that contract:

import pytest


@pytest.mark.authz_contract("booking.retrieve")
def test_booking_retrieve_authorization(authz_case):
    authz_case.run()

That single test expands into every configured actor/relationship combination with readable case IDs.

Django REST Framework

Actor fixtures can return DRF APIClient instances. Authentication remains application-owned:

import pytest
from rest_framework.test import APIClient


@pytest.fixture
def owner_client(owner):
    client = APIClient()
    client.force_authenticate(owner)
    return client

The DRF adapter preserves the existing data=..., format=..., and Django URL-resolver behavior.

FastAPI

Actor fixtures return FastAPI/Starlette TestClient instances:

import pytest
from fastapi.testclient import TestClient

from app.main import app


@pytest.fixture
def owner_client(owner_token):
    return TestClient(
        app,
        headers={"Authorization": f"Bearer {owner_token}"},
    )

The framework is detected automatically. For a normal TestClient, no framework: key and no app configuration are required. If a custom client wrapper hides the underlying application, override the optional fixture:

@pytest.fixture
def authz_app():
    return app

With format: json (the default), the FastAPI adapter sends the body through the client's json= parameter. format: form, format: data, and format: null use form/data semantics.

See docs/fastapi.md and examples/fastapi.

Resource relationships

A resource fixture maps relationship names in YAML to real objects or mappings:

@pytest.fixture
def booking_matrix(owner_booking, foreign_booking):
    return {
        "owned": owner_booking,
        "foreign": foreign_booking,
    }

lookup defaults to pk. Use id, uuid, public_id, or a nested attribute/key path when your API uses another identifier.

Outcomes

Built-in outcomes are HTTP status contracts:

Outcome Default status Meaning
allow 200 Actor may perform the operation.
deny 403 Authenticated but forbidden.
conceal 404 Resource existence must not be disclosed.
unauthenticated 401 Authentication is required.

Override defaults globally or override a single matrix cell when an endpoint legitimately returns another success/error status.

Mutating endpoints

Request bodies, query strings, and headers can come from fixtures:

contracts:
  booking.update:
    method: PATCH
    path: /api/bookings/{resource}
    route_name: booking-update
    resource: booking
    request:
      data_fixture: booking_update_payload
      query_fixture: update_query
      format: json
      headers:
        X-Test-Source: authz-matrix
    matrix:
      owner:
        owned: allow
        foreign: conceal

For side-effect assertions, split execution from the response assertion:

response = authz_case.execute()
# inspect state here
authz_case.assert_response(response)

execute() also accepts per-test data, query, and headers overrides.

Route coverage

Enable coverage reporting:

pytest --authz-report

The reporter records which framework adapter actually executed the authorization cases and then compares declared contracts against that framework's route inventory.

Example:

authorization cases: 12/12 asserted, 12 passed, 0 failed
authorization contracts: 1/1 exercised
FastAPI route coverage: 8/10 (80.0%)
  missing: DELETE delete-booking
  missing: GET health

Write a machine-readable report:

pytest --authz-report-json=authz-report.json

Report schema version 2 uses a framework-neutral route_coverage object containing the detected framework, totals, percentage, and uncovered routes.

Fail CI below a route-contract threshold:

pytest --authz-fail-under=90

Framework behavior

The authorization contract format is intentionally framework-neutral. Framework adapters are responsible for request execution and route inventory only:

  • django-rest-framework - DRF/Django clients and URL resolver discovery;
  • fastapi - Starlette TestClient execution and FastAPI APIRoute discovery;
  • generic - method/generic client execution when no first-class adapter matches.

This keeps application models, authentication backends, tenancy systems, and business policy in project fixtures rather than importing them into the plugin.

Configuration and design

License

MIT

Metadata

Release files for pytest-authz-matrix 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 pytest-authz-matrix 0.2.0
File Size Uploaded Provenance Actions
pytest_authz_matrix-0.2.0.tar.gz 27.6 kB With provenance Details for pytest_authz_matrix-0.2.0.tar.gz

Built distribution (wheel)

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

Total release size: 51.8 kB

Release files / pytest_authz_matrix-0.2.0.tar.gz

Download URL pytest_authz_matrix-0.2.0.tar.gz
Size 27.6 kB
Tags Source
SHA-256 checksum
How to use checksums
c9e3f4b4dcf6bd63b5a87b5e640f7e8e2ee3058f9fe50744eb7fc3c2deed17b3
BLAKE2b-256 checksum
How to use checksums
9a3fa3ed8f85f84426ba47cc026b03dd245cbc016816e5b9bf98f5172aeba8e1
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 21, 2026.

Transparency log

Release files / pytest_authz_matrix-0.2.0-py3-none-any.whl

Download URL pytest_authz_matrix-0.2.0-py3-none-any.whl
Size 24.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
da8f6bf3a0d2819331671dffda88ce318b96c4951941839b15d4e6d6ca9ea3d6
BLAKE2b-256 checksum
How to use checksums
22726452425bad62479f8715f129e6ec86bf7b2d06877a17f331de917e500b27
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 21, 2026.

Transparency log

Security for pytest-authz-matrix 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.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for pytest_authz_matrix-0.2.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 21, 2026.

Transparency log

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