Preserve tenant authorization inside an atomic FastAPI update
A read-then-write authorization check has two boundaries: who can see the row, and whether the write still applies the same scope. Put tenant, owner, and pending status into the UPDATE itself. A concurrent cancellation can then change at most one pending row.
Save this requirement in Perch and check it after each agent edit. The rule gives your agent a named check to run, a finding to repair, and the same command to recheck.
Implement the FastAPI boundary
Save this illustrative integration module as orders.py.
from fastapi import HTTPException
from sqlalchemy import update
from sqlalchemy.ext.asyncio import AsyncSession
from models import Order
async def cancel_order(session: AsyncSession, actor, order_id: int):
async with session.begin():
statement = (
update(Order)
.where(Order.id == order_id,
Order.tenant_id == actor.tenant_id,
Order.owner_id == actor.id,
Order.status == "pending")
.values(status="cancelled")
.returning(Order.id)
)
result = await session.execute(statement)
cancelled_id = result.scalar_one_or_none()
if cancelled_id is None:
raise HTTPException(status_code=404, detail="Pending order not found")
return {"id": cancelled_id, "status": "cancelled"}
The order, inventory, or resource-lifetime scenario is adapted from Perch’s public order-service source at commit 4af67af. This FastAPI implementation is an illustrative adaptation.
Integrate with your application
Use an AsyncSession backed by PostgreSQL, an Order model with id, tenant_id, owner_id and status columns, and an actor derived from your verified authentication dependency. Pass a fresh session with no active transaction to this service. Mount it behind a FastAPI route using Depends for both the actor and session; never construct actor.tenant_id from the JSON request. An authentication dependency that queries with this same session may already start a transaction: either own that outer transaction in the route or use a separate session for this service.
Exercise the boundary and failure paths
| Scenario | Expected outcome |
|---|---|
| Matching tenant, owner, pending row | One cancellation and commit |
| Another tenant with the same owner id | 404 and no update |
| Already cancelled or missing row | 404 and no update |
| Two simultaneous cancellation requests | At most one changes the pending row |
Add regression tests for these cases in your existing FastAPI test project. Use separate connections or deliberately reordered completion where the case involves concurrency; a sequential happy-path test does not exercise that failure. Run the test command after creating the matching test file or suite:
python -m pytest tests/test_order_cancellation.py
The scenarios above specify tests to implement. A completed Perch source check below is separate from running these application integration tests.
Introduce the specific agent regression
In a throwaway copy, replace this source span:
Order.tenant_id == actor.tenant_id,
with:
// Remove the source span shown above.
Run the relevant negative test and the Perch command on that broken copy. Restore the corrected source before committing the application. The supplied mutation reproduces the exact regression for the rule check.
Preserve the requirement as a Perch rule
Save this in .perch/rules/perch-guide-fastapi-tenant-cancellation.yaml at the repository root, keeping your existing perch.yaml:
- name: tenant-scoped-update
where: "orders.py"
ensure: >-
The cancellation UPDATE must constrain tenant_id to actor.tenant_id before changing the order. An id-only or owner-only update breaks this requirement.
Install and authenticate the CLI once, then check the current working file:
npm install -g @lakeday/perch
perch login
perch check orders.py --rules tenant-scoped-update --json
Use Node 22 or newer. The framework can use another language; Perch’s CLI remains a Node command. A gated finding exits 3. Exits 1 or 2 mean the check did not complete and must be reported as a blocker.
Inspect the captured rule check
On 2026-10-14, Perch using jev-latest checked the exact fixed and broken source provided here. The capture records SHA-256 hashes of both sources and the requirement.
| Source control | Exit | Outcome |
|---|---|---|
| Broken | 3 | Rule finding |
| Corrected | 0 | No rule finding |
The rule distinguished these controls in this run. Raw Perch capture · Exact sources and mutation.
Install the rule pack and configure your agent
Download this rule pack ZIP · Download the YAML rules · Agent task. The pack contains the rule, its example paths and the repair/recheck instructions. Review the where selector before using it in an existing project. Keep your root perch.yaml; install this rule as a separate file under .perch/rules/.
- Install Perch using Node 22 or newer and sign in once:
npm install -g @lakeday/perch
perch login
- Download the pack, inspect it, and extract it from your repository root. The extraction preserves any existing files:
curl -fL 'https://frameworkrecipes.dev/fastapi/tenant-cancellation/rule-pack.zip' -o 'perch-guide-fastapi-tenant-cancellation.zip'
unzip -n 'perch-guide-fastapi-tenant-cancellation.zip'
The installed rule is .perch/rules/perch-guide-fastapi-tenant-cancellation.yaml. Its selector matches orders.py in this example; adapt the selector to your application file before checking an existing project.
- Configure the coding agent you use. Run one of these commands:
Claude Code:
perch setup claude-code
Codex:
perch setup codex
Cursor:
perch setup cursor
Pi:
perch setup pi
- Ask the agent to edit the implementation and check the saved requirement:
Use the installed Perch skill while editing orders.py. Preserve tenant-scoped-update. Run perch check orders.py --rules tenant-scoped-update --json after the edit. Read each finding and the affected code, fix the implementation, and run the identical check again after the fix. Keep the rule and regression tests intact. Run the application's relevant regression tests and report the commands and actual results. Exit 3 means a rule finding; exit 1 or 2 means the check did not complete. Report an unavailable or incomplete check as blocked. Do not claim the application tests ran if only the Perch check ran.
- After repairing a finding, run the same check again and inspect the result:
perch check orders.py --rules tenant-scoped-update --json
Commit the downloaded rule and the installed agent configuration with your application. The rule file adds no guarantee of correctness; keep the regression tests from this guide.
With the base reference fetched, use perch scan --since origin/main --filter type=lint in CI.
Framework references and verification scope
The dated capture records the source check shown above. Implement the adapters, schema and regression tests described in this guide in your application. Unchanged requests reuse cached answers; fresh model judgments can vary. Model analysis sends relevant source to the configured service.