# Keep Actix order reads scoped by ReqData identity

ReqData carries identity inserted by request middleware. That proves the source of the identity, while the SQL predicate enforces which record can be returned. Omitting a tenant predicate during a query refactor can leak data despite correct authentication.

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 Actix Web boundary

Save this illustrative integration module as `src/order.rs`.

```rust
use actix_web::{web, HttpResponse, Error};
use sqlx::PgPool;

#[derive(Clone)]
pub struct Actor { pub tenant_id:i64, pub user_id:i64 }

pub async fn order(actor:web::ReqData<Actor>, pool:web::Data<PgPool>, id:web::Path<i64>) -> Result<HttpResponse,Error> {
    let status = sqlx::query_scalar::<_, String>(
        "SELECT status FROM orders WHERE id=$1 AND tenant_id=$2 AND owner_id=$3"
    ).bind(id.into_inner()).bind(actor.tenant_id).bind(actor.user_id)
     .fetch_optional(pool.get_ref()).await
     .map_err(actix_web::error::ErrorInternalServerError)?;
    match status {
        Some(status) => Ok(HttpResponse::Ok().json(status)),
        None => Ok(HttpResponse::NotFound().finish()),
    }
}
```

The order, inventory, or resource-lifetime scenario is adapted from Perch’s public [order-service source at commit 4af67af](https://github.com/lakeday-org/perch/blob/4af67af46d76ac99398d61c7ad0a45441760d4dc/test/fixtures/order-service/auth.py). This Actix Web implementation is an illustrative adaptation.

## Integrate with your application

Use Actix Web 4, SQLx and PostgreSQL. Insert Actor after verifying authentication in middleware on the protected scope. Do not place per-user identity in web::Data, which is shared application data. The supplied broken control adjusts SQL placeholders and bindings together, isolating the missing tenant predicate in an executable query.



## Exercise the boundary and failure paths

| Scenario | Expected outcome |
| --- | --- |
| Owned order | Status response |
| Order in another tenant | 404 |
| Missing identity extension | Request extraction fails |
| Concurrent requests from different users | ReqData remains request-local |

Add regression tests for these cases in your existing Actix Web 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:

```sh
cargo test scoped_order_lookup
```

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:

```rust
use actix_web::{web, HttpResponse, Error};
use sqlx::PgPool;

#[derive(Clone)]
pub struct Actor { pub tenant_id:i64, pub user_id:i64 }

pub async fn order(actor:web::ReqData<Actor>, pool:web::Data<PgPool>, id:web::Path<i64>) -> Result<HttpResponse,Error> {
    let status = sqlx::query_scalar::<_, String>(
        "SELECT status FROM orders WHERE id=$1 AND tenant_id=$2 AND owner_id=$3"
    ).bind(id.into_inner()).bind(actor.tenant_id).bind(actor.user_id)
     .fetch_optional(pool.get_ref()).await
     .map_err(actix_web::error::ErrorInternalServerError)?;
    match status {
        Some(status) => Ok(HttpResponse::Ok().json(status)),
        None => Ok(HttpResponse::NotFound().finish()),
    }
}
```

with:

```rust
use actix_web::{web, HttpResponse, Error};
use sqlx::PgPool;

#[derive(Clone)]
pub struct Actor { pub tenant_id:i64, pub user_id:i64 }

pub async fn order(actor:web::ReqData<Actor>, pool:web::Data<PgPool>, id:web::Path<i64>) -> Result<HttpResponse,Error> {
    let status = sqlx::query_scalar::<_, String>(
        "SELECT status FROM orders WHERE id=$1 AND owner_id=$2"
    ).bind(id.into_inner()).bind(actor.user_id)
     .fetch_optional(pool.get_ref()).await
     .map_err(actix_web::error::ErrorInternalServerError)?;
    match status {
        Some(status) => Ok(HttpResponse::Ok().json(status)),
        None => Ok(HttpResponse::NotFound().finish()),
    }
}
```

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-actix-web-request-scoped-identity.yaml` at the repository root, keeping your existing `perch.yaml`:

```yaml
- name: reqdata-tenant-predicate
  where: "src/order.rs"
  each: method
  ensure: >-
    The SELECT SQL string contains a tenant_id predicate. Removing tenant_id from its WHERE clause violates the required tenant isolation.
```

Install and authenticate the CLI once, then check the current working file:

```sh
npm install -g @lakeday/perch
perch login
perch check src/order.rs::order --rules reqdata-tenant-predicate --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](/request-scoped-identity/capture.json) · [Exact sources and mutation](/request-scoped-identity/source.json).

## Install the rule pack and configure your agent

[Download this rule pack ZIP](/request-scoped-identity/rule-pack.zip) · [Download the YAML rules](/request-scoped-identity/rules.yaml) · [Agent task](/request-scoped-identity/agent-task.txt). 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/`.

1. Install Perch using Node 22 or newer and sign in once:

```sh
npm install -g @lakeday/perch
perch login
```

2. Download the pack, inspect it, and extract it from your repository root. The extraction preserves any existing files:

```sh
curl -fL 'https://reporules.fyi/actix-web/request-scoped-identity/rule-pack.zip' -o 'perch-guide-actix-web-request-scoped-identity.zip'
unzip -n 'perch-guide-actix-web-request-scoped-identity.zip'
```

The installed rule is `.perch/rules/perch-guide-actix-web-request-scoped-identity.yaml`. Its selector matches `src/order.rs` in this example; adapt the selector to your application file before checking an existing project.

3. Configure the coding agent you use. Run one of these commands:

Claude Code:

```sh
perch setup claude-code
```

Codex:

```sh
perch setup codex
```

Cursor:

```sh
perch setup cursor
```

Pi:

```sh
perch setup pi
```

4. Ask the agent to edit the implementation and check the saved requirement:

> Use the installed Perch skill while editing src/order.rs. Preserve reqdata-tenant-predicate. Run perch check src/order.rs::order --rules reqdata-tenant-predicate --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.

5. After repairing a finding, run the same check again and inspect the result:

```sh
perch check src/order.rs::order --rules reqdata-tenant-predicate --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

- [docs.rs reference](https://docs.rs/actix-web/latest/actix_web/web/struct.ReqData.html)

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.
