Authorization bugs return. A one-time pentest finds them; a matrix test in CI keeps them from coming back. Here is how to build one that is fast, isolated, and trustworthy.
Most teams test authentication. Far fewer test authorization — the part that decides whether an authenticated user may touch a specific object or perform a specific action.
That gap is why BOLA (Broken Object Level Authorization) remains the most common serious API flaw. A login test confirms that user A can log in. It says nothing about whether user A can read user B's invoice.
This article is a practical guide to the test that does: an identity matrix that runs against a real API in CI.
1. What the matrix tests
For every endpoint and method, test four perspectives:
| Caller | Target object | Expected |
|---|---|---|
| Anonymous | Tenant A's object | 401 |
| Tenant A user | Tenant A's object |
200 / 201 / 204
|
| Tenant A user | Tenant B's object |
403 or 404
|
| Tenant A admin | Tenant B's object |
403 or 404 (unless cross-tenant admin is a designed feature) |
| Tenant B user | Tenant A's object |
403 or 404
|
The core assertion is the cross-tenant one: a valid user from tenant A must not be able to read, modify, or delete tenant B's object.
The admin row is deliberate. “Admin can see everything” is often an implicit assumption that turns into a tenancy bypass when support tools or shared dashboards are added. If cross-tenant access is a feature, test it explicitly and require an audit trail.
2. Why this belongs in CI, not in a document
Authorization logic changes constantly:
- a new endpoint copies an older handler,
- a refactor moves the ownership check out of the query,
- a new field becomes writable (mass assignment),
- a cache key loses the tenant prefix,
- a background job starts trusting a payload ID.
Unit tests mock the database and the auth layer, so they rarely catch a missing filter in a real query. End-to-end tests against a running API do.
The matrix is also cheap to run once the fixtures exist. It is deterministic, fast enough for a PR, and produces a clear failure: “A read B's object at GET /invoices/1042.”
3. Fixture design
You need two isolated tenants with realistic data. Keep the fixtures in code.
tests/security/
├── conftest.py
├── seed.py
├── test_authz_matrix.py
├── test_mass_assignment.py
└── test_tenant_isolation.py
Create the data explicitly
# tests/security/seed.py
def seed(api):
tenant_a = api.create_tenant("tenant-a")
tenant_b = api.create_tenant("tenant-b")
user_a = api.create_user(tenant_a, role="member")
user_b = api.create_user(tenant_b, role="member")
admin_a = api.create_user(tenant_a, role="admin")
invoice_a = api.create_invoice(tenant_a, owner=user_a, amount=100)
invoice_b = api.create_invoice(tenant_b, owner=user_b, amount=200)
return {
"tenants": {"a": tenant_a, "b": tenant_b},
"users": {"a": user_a, "b": user_b, "admin_a": admin_a},
"objects": {"invoice_a": invoice_a, "invoice_b": invoice_b},
}
Rules for fixtures
- Two tenants minimum. One tenant cannot test isolation.
- Realistic roles. A member, an admin, and an anonymous caller. Add a service account if you have them.
- One object per important type. Invoice, document, project, file, order — whichever your API exposes.
- Edge states. A soft-deleted object, an archived object, and an object transferred between tenants.
- Deterministic IDs where possible. Sequential IDs make enumeration tests trivial to write.
- No production data. Ever.
4. The test harness
Use any HTTP client. The pattern matters more than the framework.
# tests/security/test_authz_matrix.py
import pytest
ENDPOINTS = [
("GET", "/api/invoices/{id}"),
("PATCH", "/api/invoices/{id}"),
("DELETE", "/api/invoices/{id}"),
]
@pytest.mark.parametrize("method,path", ENDPOINTS)
def test_anonymous_denied(client, fixtures, method, path):
url = path.format(id=fixtures["objects"]["invoice_a"])
response = client.request(method, url, token=None)
assert response.status_code in (401, 403), response.text
@pytest.mark.parametrize("method,path", ENDPOINTS)
def test_owner_allowed(client, fixtures, method, path):
url = path.format(id=fixtures["objects"]["invoice_a"])
response = client.request(method, url, token=fixtures["users"]["a"].token)
assert response.status_code < 400, response.text
@pytest.mark.parametrize("method,path", ENDPOINTS)
def test_cross_tenant_denied(client, fixtures, method, path):
url = path.format(id=fixtures["objects"]["invoice_a"])
response = client.request(method, url, token=fixtures["users"]["b"].token)
assert response.status_code in (403, 404), (
f"BOLA: tenant B accessed tenant A's object via {method} {url}"
)
Assertions that go beyond the status code
A 403 is good, but the response body can still leak data:
- does the error include the object's name or owner?
- does
404for a foreign object differ from404for a non-existent one? - does the
PATCHreturn the object even though it was not modified? - did the
DELETEactually delete something?
Add response-shape assertions:
def test_cross_tenant_error_does_not_leak(client, fixtures):
response = client.get(
f"/api/invoices/{fixtures['objects']['invoice_b']}",
token=fixtures["users"]["a"].token,
)
assert response.status_code in (403, 404)
body = response.text.lower()
for needle in ("tenant-b", "invoice_b", "customer name"):
assert needle not in body
Test the write side, not just reads
BOLA on PATCH and DELETE is more damaging than on GET. Also test:
-
POSTwith a foreign parent ID (/projects/{foreign_id}/tasks), - bulk operations mixing owned and foreign IDs,
- nested resources at every level,
- exports and file downloads,
- GraphQL resolvers and field-level access.
5. Isolation between test runs
Stateful security tests flake when runs share data. Fix the root cause, not the symptom.
Options, from simplest to strongest
-
Unique identifiers per run. Create tenants with a run ID (
tenant-a-<sha>), so parallel runs never collide. - Transaction rollback. Wrap each test in a transaction and roll back. Works for database-only tests, not for HTTP calls.
- Schema or database per run. Create a disposable schema or database, run migrations, seed, test, drop.
-
Ephemeral environment per pipeline. The cleanest option:
docker compose up, seed, test,down -v.
For most teams, option 1 plus option 4 is enough.
Cleanup in finally
@pytest.fixture
def tenant_pair(api):
a = api.create_tenant(unique_name("a"))
b = api.create_tenant(unique_name("b"))
try:
yield a, b
finally:
api.delete_tenant(a.id)
api.delete_tenant(b.id)
Do not run stateful tests in parallel with themselves
Parallelize across endpoints or test files, but keep tests that mutate shared state in a single worker. Otherwise you will spend more time debugging the harness than the API.
6. Caches, jobs, and other layers
The request path is only the first layer. Add tests for:
- Cache: prime as tenant A, request as tenant B, assert no cross-tenant hit.
- Search: query for a term that exists only in B, authenticated as A, assert no results.
- Background jobs: enqueue work for a foreign object and assert it is rejected or ignored.
- Files: request a signed URL for a foreign file and assert denial.
-
Exports: pass a foreign
account_idand assert denial. - WebSockets: subscribe to a foreign channel and assert rejection.
These are slower and more setup-heavy. Put them in the nightly job if they push the PR path over budget.
7. Running against different targets
Ephemeral stack (recommended for PRs)
Start the API and its dependencies, seed, test, tear down. Full control, no shared state, no production risk.
Preview environment (good for larger systems)
Deploy the branch to an isolated preview, run the matrix against it. Requires seed and cleanup endpoints or a dedicated test tenant.
Production (read-only only)
You can run read-only authorization checks against production with dedicated test accounts — for example, verifying that tenant B cannot read tenant A's object. Never run destructive tests, mass assignment writes, or rate-limit bursts against production without explicit approval and scoped test data.
8. Reporting and triage
A failure should tell a reviewer exactly what to fix:
FAILED test_cross_tenant_denied[DELETE-/api/invoices/{id}]
BOLA: tenant B accessed tenant A's object
request: DELETE /api/invoices/1042
caller: tenant-b / user-b
status: 204
expected: 403 or 404
Include:
- the endpoint and method,
- the caller identity (tenant, role),
- the object owner,
- the observed status and a short body excerpt,
- the expected behavior.
Upload JUnit XML as an artifact so results appear in the PR checks. A test that fails silently in a log is a test that gets ignored.
9. Scaling the suite
Start small:
- Week 1: the 10 endpoints that handle the most sensitive data.
- Week 2: every endpoint that accepts an object ID.
- Week 3: nested resources, bulk operations, exports.
- Week 4: caches, jobs, files, search, WebSockets.
Then keep it proportional:
- run the full matrix on
mainand nightly, - run only the affected endpoints on PRs (map changed files to routes),
- keep a smoke subset that runs in under two minutes on every push.
A matrix that covers every endpoint but takes an hour will be moved to “nightly” and then forgotten.
10. Common mistakes
-
Only testing
GET. Writes are where the damage is. - Only testing one tenant. You cannot detect cross-tenant access with one tenant.
- Using an admin token for everything. It hides authorization bugs by design.
-
Asserting only “not 200.”
500is also “not 200,” and it is not a pass. -
Ignoring response bodies. A
403can still leak data. - Shared mutable fixtures. Flaky tests get muted.
- Testing against a stale environment. You are testing last week's code.
- No cleanup. Data accumulates; behavior changes; tests start failing for the wrong reason.
- No mapping from failure to owner. A red check with no context is noise.
11. Where continuous testing fits
The matrix is the right test. The hard part is keeping it complete as the API grows: new endpoints, new versions, new nested resources, new exports.
LiveAPISec runs differential authorization checks with A/B/anonymous identities as part of its OWASP API Top 10 core, on demand or continuously. That complements a hand-written matrix: the in-repo tests encode your business rules and fixtures, while the continuous scan covers the full reachable surface and flags endpoints that were added since the last run.
pipx install liveapisec
liveapisec scan --help
Use both. The in-repo matrix is precise and fast; the continuous scan is broad and current.
12. Checklist
Fixtures
- [ ] Two tenants with realistic objects exist in code.
- [ ] Roles include member, admin, and anonymous.
- [ ] Edge objects: soft-deleted, archived, transferred.
- [ ] Test data is created per run with unique identifiers.
- [ ] Cleanup runs even on failure.
Tests
- [ ] Anonymous, owner, stranger, and admin perspectives.
- [ ]
GET,POST,PATCH,PUT,DELETE, and bulk operations. - [ ] Nested resources at every level.
- [ ] Response bodies checked for leaks, not just status codes.
- [ ] Caches, search, jobs, files, exports, and WebSockets covered.
CI
- [ ] Runs against the deployed build, not mocks.
- [ ] Fails fast on changed endpoints; full matrix nightly.
- [ ] Results uploaded as JUnit XML and visible in the PR.
- [ ] Failures include endpoint, identity, object, and expected result.
- [ ] Flaky tests are fixed, not retried forever.
Key takeaways
- Authentication tests do not test authorization.
- The A/B/anonymous matrix is the highest-value security test you can put in CI.
- Two tenants and explicit fixtures are non-negotiable.
- Test writes, nested resources, and response bodies — not just
GETand status codes. - Isolate state per run or the suite will flake and get ignored.
- Keep the PR subset fast and run the full matrix on
mainand nightly. - Pair the in-repo matrix with continuous scanning so new endpoints do not escape coverage.
Tags: API Security, CI/CD, Testing, Authorization, DevSecOps
Top comments (0)