Test cross-user record access with a two-user CI fixture

Build a local pytest check that permits owner reads, rejects cross-user reads, and fails when an ownership-scoped lookup becomes ID-only.

OpenThunder Editorial · 2026-11-23

Test broken object-level authorization in CI by seeding two users and two records, then requesting a known existing record as the wrong user. Exercise the real route and database query, and prove the check detects a regression by temporarily removing the ownership constraint.

For example, Alice owns record 101, and Bob owns record 202. Alice must receive her record when she requests /records/101, but changing the URL to /records/202 must not return Bob’s data. An unauthenticated request must fail separately.

A denied request proves little if the target record never existed.

Preserve the finding, not the exploratory run

In its November 13, 2026 post on AI penetration-testing orchestrators, Cloudflare describes platforms such as ARTEX as increasingly powerful tools for attacks on exposed infrastructure. That is Cloudflare’s assessment; its summary does not document the particular authorization bug demonstrated here.

For an engineer maintaining verification tooling, the useful decision comes after discovery: should every change require another exploratory run, or can the finding become a deterministic regression check?

For a reproducible read-authorization failure, I would preserve the request, identity relationship, database state, and expected response as an integration test. An exploratory tool can look for additional failures; the fixture protects one known boundary without depending on the tool finding it again.

The fixture below checks read authorization only. It does not establish that other routes, write operations, or identity flows are secure.

Define the response contract before writing the test

This example uses a concealment contract: a record belonging to another user produces the same 404 response as a nonexistent record.

Save this small read-access matrix alongside the test:

Caller Target Expected response
Alice Alice’s existing record 200, exact Alice payload
Bob Bob’s existing record 200, exact Bob payload
Alice Bob’s existing record 404, exact error body
Bob Alice’s existing record 404, exact error body
Unauthenticated An existing record 401, authentication challenge

The successful owner requests matter. Otherwise, a route that rejects everyone could pass the denial tests.

A passing denial test needs a passing owner test beside it.

Build a local API with an ownership-scoped lookup

Create an empty directory containing app.py and test_records.py. All records and credentials below are disposable local test resources.

The API uses FastAPI and SQLite. Its token-to-user mapping is deliberately limited to the fixture: it provides two distinct authenticated identities without an external identity provider. It is not production authentication code.

Put this in app.py:

import sqlite3
from contextlib import closing
from pathlib import Path

from fastapi import Depends, FastAPI, HTTPException
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer


def create_app(db_path: Path, test_tokens: dict[str, str]) -> FastAPI:
    app = FastAPI()
    bearer = HTTPBearer(auto_error=False)

    def current_user(
        credentials: HTTPAuthorizationCredentials | None = Depends(bearer),
    ) -> str:
        user_id = None
        if credentials is not None:
            user_id = test_tokens.get(credentials.credentials)
        if user_id is None:
            raise HTTPException(
                status_code=401,
                detail="Authentication required",
                headers={"WWW-Authenticate": "Bearer"},
            )
        return user_id

    @app.get("/records/{record_id}")
    def read_record(record_id: int, user_id: str = Depends(current_user)):
        with closing(sqlite3.connect(db_path)) as db:
            db.row_factory = sqlite3.Row
            row = db.execute(
                "SELECT id, owner_id, body FROM records "
                "WHERE id = ? AND owner_id = ?",
                (record_id, user_id),
            ).fetchone()

        if row is None:
            raise HTTPException(status_code=404, detail="Not found")
        return dict(row)

    return app

The important boundary is the query predicate:

WHERE id = ? AND owner_id = ?

The requested ID selects the object. The authenticated identity restricts which objects the caller can read. The owner identity comes from authentication, never from a caller-controlled owner_id parameter.

This implements one policy: each record has exactly one owner, and only that owner can read it. Shared records, administrators, and tenant-wide access require their own explicit rules and test cases.

Seed known records and assert exact responses

Put this in test_records.py:

import sqlite3
from contextlib import closing

import pytest
from fastapi.testclient import TestClient

from app import create_app


RECORDS = [
    (101, "alice", "Alice private note"),
    (202, "bob", "Bob private note"),
]
TOKENS = {
    "alice-local-token": "alice",
    "bob-local-token": "bob",
}


def auth(user: str) -> dict[str, str]:
    return {"Authorization": f"Bearer {user}-local-token"}


@pytest.fixture
def client(tmp_path):
    db_path = tmp_path / "records.sqlite3"
    with closing(sqlite3.connect(db_path)) as db:
        db.execute(
            "CREATE TABLE records ("
            "id INTEGER PRIMARY KEY, "
            "owner_id TEXT NOT NULL, "
            "body TEXT NOT NULL)"
        )
        db.executemany("INSERT INTO records VALUES (?, ?, ?)", RECORDS)
        db.commit()
        assert db.execute(
            "SELECT id, owner_id, body FROM records ORDER BY id"
        ).fetchall() == RECORDS

    with TestClient(create_app(db_path, TOKENS)) as test_client:
        yield test_client


@pytest.mark.parametrize("record_id,owner,body", RECORDS)
def test_owner_can_read(client, record_id, owner, body):
    response = client.get(f"/records/{record_id}", headers=auth(owner))

    assert response.status_code == 200
    assert response.json() == {
        "id": record_id,
        "owner_id": owner,
        "body": body,
    }


@pytest.mark.parametrize(
    "caller,target_id",
    [("alice", 202), ("bob", 101)],
)
def test_cannot_read_other_users_record(client, caller, target_id):
    response = client.get(f"/records/{target_id}", headers=auth(caller))

    assert response.status_code == 404
    assert response.json() == {"detail": "Not found"}


def test_authentication_is_required(client):
    response = client.get("/records/101")

    assert response.status_code == 401
    assert response.headers["www-authenticate"] == "Bearer"
    assert response.json() == {"detail": "Authentication required"}

The fixture checks the seeded rows directly, so an absent target cannot masquerade as correct authorization. Each test gets its own database file under pytest’s temporary directory.

The requests pass through the application’s routing, bearer-token handling, endpoint, and SQLite lookup. Nothing mocks the authorization result. TestClient runs the application in-process, so this check does not cover a deployed proxy or network path.

The denied response assertion checks more than status. An exact error body also rejects a response that includes Bob’s record data alongside an error message. This does not check unrelated disclosure channels such as logs or timing.

Run the check as a CI gate

Using Python 3.10 or newer, create an isolated environment and install the example’s dependencies:

python -m venv .venv
. .venv/bin/activate
python -m pip install fastapi httpx pytest
python -m pytest -q

These commands are a starting point, not a reported test run. For a reproducible CI job, commit the dependency versions resolved by your chosen lockfile workflow and install from that lockfile. Use the same supported Python version locally and in CI.

The CI job should run pytest as a required command and preserve its exit status. Do not append || true or otherwise turn a failing security test into a successful job.

Prove the test catches the ID-only regression

A test can look relevant while exercising the wrong path. Use a negative control to establish that this check detects the intended defect.

In the disposable example, replace the scoped query and its parameters with this vulnerable lookup:

row = db.execute(
    "SELECT id, owner_id, body FROM records WHERE id = ?",
    (record_id,),
).fetchone()

Then run only the cross-user cases:

python -m pytest -q -k cannot_read_other_users_record

With that mutation, the route retrieves the other user’s seeded record and returns 200. The assertion requiring 404 should fail. If it does not, investigate whether the test is importing the changed app, reaching this query, and using the expected database.

Restore the ownership-scoped query and rerun the full file before committing. Keep the passing regression check, not the vulnerable mutation.

A negative control checks whether the test notices the bug you intend to prevent.

Adapt the contract without weakening the boundary

If your application deliberately returns 403 for an authenticated caller without access, assert 403 and the exact documented error payload instead. Also assert that the forbidden response contains no record data. Do not accept either 403 or 404 merely to make the test pass; choose the behavior your route promises.

For an existing application, keep its real route and authorization logic. Seed two isolated test accounts through your normal fixture mechanism, authenticate them through the appropriate test-supported path, and create records through migrations or factories that match the actual schema. Avoid replacing the authorization dependency with a stub that simply returns “allowed” or “denied.”

If the reported failure depends on token claims or middleware, the regression test must preserve those inputs. The local token map above intentionally does not verify those layers.

For a five-minute first pass, write down one route’s read-access matrix and locate the fixtures that can create both owners. Its limit is narrow but useful: you are preserving one object-access rule, not certifying the application. When that check is ready, put a verification gate on your pipeline.