Keep Axum’s verified tenant inside the SQLx order update
Middleware can authenticate an Axum request while the handler still writes globally. Extract the verified actor and include tenant and owner in the SQL statement that changes state. The affected-row check rejects inaccessible or already transitioned rows.
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 Axum boundary
Save this illustrative integration module as src/cancel.rs.
use axum::{extract::{Extension, Path, State}, http::StatusCode};
use sqlx::PgPool;
#[derive(Clone)]
pub struct Actor { pub tenant_id: i64, pub user_id: i64 }
pub async fn cancel(
State(pool): State<PgPool>, Extension(actor): Extension<Actor>, Path(id): Path<i64>,
) -> Result<StatusCode, StatusCode> {
let result = sqlx::query("UPDATE orders SET status='cancelled' WHERE id=$1 AND tenant_id=$2 AND owner_id=$3 AND status='pending'")
.bind(id).bind(actor.tenant_id).bind(actor.user_id)
.execute(&pool).await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
if result.rows_affected() != 1 { return Err(StatusCode::NOT_FOUND); }
Ok(StatusCode::NO_CONTENT)
}
The order, inventory, or resource-lifetime scenario is adapted from Perch’s public order-service source at commit 4af67af. This Axum implementation is an illustrative adaptation.
Integrate with your application
Use Axum 0.8 and SQLx with PostgreSQL. Authentication middleware inserts a validated Actor into extensions; register it on protected routes with route_layer. Axum 0.8 dynamic routes use /orders/{id}; older releases used a different syntax. Add database constraints and map operational errors without exposing SQL. The broken control removes the tenant predicate and its binding together, so it remains an executable query.
Exercise the boundary and failure paths
| Scenario | Expected outcome |
|---|---|
| Correct actor and pending row | 204 and one change |
| Cross-tenant order id | 404 and no change |
| Missing middleware identity | Extractor rejection |
| Two simultaneous cancellations | At most one pending update |
Add regression tests for these cases in your existing Axum 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:
cargo test tenant_cancellation
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:
use axum::{extract::{Extension, Path, State}, http::StatusCode};
use sqlx::PgPool;
#[derive(Clone)]
pub struct Actor { pub tenant_id: i64, pub user_id: i64 }
pub async fn cancel(
State(pool): State<PgPool>, Extension(actor): Extension<Actor>, Path(id): Path<i64>,
) -> Result<StatusCode, StatusCode> {
let result = sqlx::query("UPDATE orders SET status='cancelled' WHERE id=$1 AND tenant_id=$2 AND owner_id=$3 AND status='pending'")
.bind(id).bind(actor.tenant_id).bind(actor.user_id)
.execute(&pool).await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
if result.rows_affected() != 1 { return Err(StatusCode::NOT_FOUND); }
Ok(StatusCode::NO_CONTENT)
}
with:
use axum::{extract::{Extension, Path, State}, http::StatusCode};
use sqlx::PgPool;
#[derive(Clone)]
pub struct Actor { pub tenant_id: i64, pub user_id: i64 }
pub async fn cancel(
State(pool): State<PgPool>, Extension(actor): Extension<Actor>, Path(id): Path<i64>,
) -> Result<StatusCode, StatusCode> {
let result = sqlx::query("UPDATE orders SET status='cancelled' WHERE id=$1 AND owner_id=$2 AND status='pending'")
.bind(id).bind(actor.user_id)
.execute(&pool).await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
if result.rows_affected() != 1 { return Err(StatusCode::NOT_FOUND); }
Ok(StatusCode::NO_CONTENT)
}
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-axum-tenant-conditional-write.yaml at the repository root, keeping your existing perch.yaml:
- name: tenant-is-in-update
where: "src/cancel.rs"
ensure: >-
The order UPDATE must include tenant_id=$2 and bind actor.tenant_id so the write is scoped to the verified tenant.
Install and authenticate the CLI once, then check the current working file:
npm install -g @lakeday/perch
perch login
perch check src/cancel.rs --rules tenant-is-in-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/axum/tenant-conditional-write/rule-pack.zip' -o 'perch-guide-axum-tenant-conditional-write.zip'
unzip -n 'perch-guide-axum-tenant-conditional-write.zip'
The installed rule is .perch/rules/perch-guide-axum-tenant-conditional-write.yaml. Its selector matches src/cancel.rs 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 src/cancel.rs. Preserve tenant-is-in-update. Run perch check src/cancel.rs --rules tenant-is-in-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 src/cancel.rs --rules tenant-is-in-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.