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 and Django REST Framework

Add one pytest test to check Django's declared login requirements and DRF's built-in permissions:

from pytest_authz_matrix.django import check_django


def test_authorization():
    check_django()

The checker uses the test project's configured Django settings. See the Django guide for supported policies and Python overrides.

YAML contracts with 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

Add one pytest test to check required FastAPI security dependencies automatically:

from pytest_authz_matrix.fastapi import check_fastapi

from app.main import app


def test_authorization():
    check_fastapi(app)

No YAML setup is required. See the FastAPI guide for permission defaults and Python overrides.

YAML contracts

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.

Executed coverage for Python checks

check_django() and check_fastapi(app) show coverage gaps by default. Add min_coverage=100 to fail your pytest run when any discovered route lacks a check. Use the result's summary() to display executed routes and actor checks.

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.5.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.5.0
File Size Uploaded Provenance Actions
pytest_authz_matrix-0.5.0.tar.gz 38.6 kB With provenance Details for pytest_authz_matrix-0.5.0.tar.gz

Built distribution (wheel)

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

Total release size: 70.7 kB

Release files / pytest_authz_matrix-0.5.0.tar.gz

Download URL pytest_authz_matrix-0.5.0.tar.gz
Size 38.6 kB
Tags Source
SHA-256 checksum
How to use checksums
aa3b329eab38bd8fb206f2567d15a0880d0b5b11336e110e8d61c0160b5df09a
BLAKE2b-256 checksum
How to use checksums
f32d48c95c81fe028a6427478ac2d6ae34f7cf30fcdceecc1fd29097057512cb
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 22, 2026.

Transparency log

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

Download URL pytest_authz_matrix-0.5.0-py3-none-any.whl
Size 32.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
4fc7403c65f0229ab38f5bd24b150d195f3f971d85bbb6a0318a4a006687f92c
BLAKE2b-256 checksum
How to use checksums
cfdbbecbfdb0efc216e4294246d3d8200e1a6066f0357f160280f524fb308498
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 22, 2026.

Transparency log

Security for pytest-authz-matrix 0.5.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.5.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 22, 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