Row-level filtering
Every read goes through Repo::scoped, which joins the ambient ability's condition_for into the SQL — no hand-written WHERE clause, no forgotten filter.
The first layer of authorization runs at the query. Repo::scoped(action)
reads the ambient Ability and joins its condition_for::<E>(action)
into the WHERE clause of every query. A member who calls
UsersService::list() never sees a row outside their org because the
SQL itself excludes it — the framework never has to remember to add
WHERE org_id = $caller_org_id. The handler cannot bypass the filter
even if it wanted to: CrudService reaches the DB exclusively through
Repo.
This is the layer that turns “did I remember to filter?” from a review checklist into a structural property.
What it looks like
Section titled “What it looks like”A service method that lists rows:
async fn list(&self) -> Result<Vec<entity::Model>, RepoError> { Repo::<entity::Entity>::all().await}Repo::all() calls scoped(Action::Read) under the hood. With an
ambient Ability granting Read on entity::Entity when
org_id = $caller_org_id, the emitted SQL is:
-- Before: a naive list querySELECT * FROM users;
-- After: with Repo::scoped(Read) and the member's abilitySELECT * FROM usersWHERE org_id = '0193c1ee-...-caller-org-id';No WHERE was written. The ability’s condition_for::<E>(Read) was
joined onto the query at build time.
How the condition is built
Section titled “How the condition is built”Ability::condition_for::<E>(action) walks the rules keyed under
(action, TypeId::of::<E>()) plus those keyed under
(Action::Manage, TypeId::of::<E>()) (the action wildcard) and folds
them into one sea_orm::Condition:
(grant_1 OR grant_2 OR ...) AND NOT (deny_1 OR deny_2 OR ...)- No grants for this (action, entity) ⇒ the condition is
1 = 0— the query returns nothing. Default-deny. - One unconstrained grant ⇒
Predicate::Alwayslowers toCondition::all()(SQLTRUE) — the filter imposes nothing. - Conditional grants ⇒ each
.when(|p| ...)lowers viaPredicate::to_condition()and isOR-ed in. - Denials ⇒ the union is
NOT-ed onto the outerAND. Action::Manageitself ⇒ every action’s condition,AND-ed: a row must pass all four. When onlyManagerules exist every action reads them alike, and the one condition above is the whole filter.
The same Predicate AST also drives the in-memory check
(Ability::can), which reads the row as the rendered SQL would: eq and
ne against None are IS NULL and IS NOT NULL, and any other
comparison with NULL matches under neither the rule nor its NOT. What
the row cannot show, a relation above all, stays SQL’s: a wire row’s
judgement trusts the read for it on a reply and refuses it on a push
(Each row is judged on its whole row),
and can grants nothing on it while a denial it cannot decide refuses:
Repo::can asks SQL instead
(Reading the ambient ability).
What Repo does
Section titled “What Repo does”Repo<E> is the single audited choke point for data access. Every
CrudService method reaches the DB through it:
Repo::all()—scoped(Read), every readable rowRepo::page(first, after, extra)—scoped(Read)+ keyset paginationRepo::find_by_id(id)—scoped(Read)+ the primary keyRepo::update(active)/Repo::delete(model)— by-id writes with the filter joined, so a denied-but-existing row is never touched.
The handler never writes WHERE org_id = …. The pipeline writes it
once, the service goes through Repo, the controller calls the
service.
The ambient ability
Section titled “The ambient ability”Repo::scoped(...) reads the ability via
nest_rs::authz::current_ability() — a value of the request’s ambient
context, attached by the AbilityGuard and by nothing else. Three install
depths cooperate:
- HTTP — the route’s guards attach it, and the class gate its posture declares reads it there.
- GraphQL and MCP — the endpoint guards an app’s modules declare attach it at the request, and every operation the request carries runs under it: the dataloader batches a resolver triggers, and a tool across rmcp’s own task.
- WebSockets — the gateway’s upgrade guards attach it, and the connection carries it into every message. A connection hook names no read, so it stays off a hook’s reads.
A handler’s reads see it where its posture names a subject:
#[authorize(Action, Subject)] or #[public(Action, Subject)], an entity or a
capability #[subject] declares, each row the answer carries judged for the
caller as it is built. Anywhere else it is withheld, a bare #[public], a
unit stating no posture: current_ability() answers None and the reads fail
closed, since no posture named them. A visitor’s ability is read
only inside a unit naming its read, so a nested GraphQL field and a relation’s
batch read nothing for one.
Outside any request (worker job, cron tick, init or shutdown hook),
current_ability() returns None — the query runs unscoped.
That is correct for system work: a cron deleting expired sessions
should not be filtered by a caller’s ability because there is no
caller. See Threat model for what that
buys you and what it does not.
with_ability(ability, body) only ever narrows. In a job it scopes the
body’s reads to ability, a principal’s or a visitor’s the job acts for, and
nothing is withheld from it there, since None in a job reads every row; inside
a unit already holding an ability, the body runs under what both allow; in a
request no ability guard authorized, it installs nothing and the reads
still fail closed. No function hands a body a wider ability than the one it
runs under — the guard is the one place an ability comes from — and work a
unit captured, re-entered inside another, runs under what that unit allows
too.
No ambient ability: unscoped for workers, denied for requests
Section titled “No ambient ability: unscoped for workers, denied for requests”Two paths reach Repo::scoped(...) without an ability, and they get
opposite treatment. Repo tells them apart by the ambient executor’s
scope (current_executor_scope()):
- Worker jobs, cron ticks and lifecycle hooks — system work, no caller, no filter. The query runs unscoped. Correct.
- A request-scoped executor with no ability — an HTTP handler
whose controller imported neither
AuthzModulenor a transport-specific authz module. This fails closed: the filter renders1 = 0, the query returns zero rows, and awarnis emitted naming the entity and action. A missing authz module shows up as an empty (and noisy) endpoint in the first manual test, never as a cross-tenant leak. Match every new controller with its authz module, and write a negative-path test that pins the behavior.
A unit naming its read with #[public(Read, Entity)] runs AbilityGuard
too: it builds the visitor’s Ability from
AbilityFactory::define_visitor, which grants nothing until you write a
rule into it — so its class gate refuses by default, and no row is read. A
bare #[public] takes the second path above whatever that branch grants.
Visitor-rule policy belongs in the factory, not in the filter. See
Public reads.
The sanctioned ability-less reads (pre-authentication credential
lookup, CrudService::access’s existence probe) stay inside Repo
through Repo::unscoped() / unscoped_by_id() — an explicit, greppable
opt-out of the row scope, never a raw find() around the choke point. They
drop the ability only: a soft-deleted row stays hidden there too, and
Repo::with_tombstones is the one read that keeps it.
No webhook ingress exists, and Repo::unscoped is not for one: its rustdoc names what
a signature-authenticated route must clear first — raw-body HMAC-SHA256 verification in
a Guard, a constant-time compare, a replay window, fail-closed secret handling and a
denial warn.
SQL injection — not the threat
Section titled “SQL injection — not the threat”Row-level filtering does not protect against SQL injection. That mitigation happens at the query layer: SeaORM uses parameterized queries throughout, and a handler that builds raw SQL is the bug.
The threat row-level filtering protects against is scope leakage
— a logic bug in a controller (forgot the org_id filter, wrong
join, copy-paste from another endpoint) that exposes rows the caller
should not see. With the filter joined at the Repo layer, that
class of bug stops compiling: the handler does not write the
predicate, so it cannot get it wrong.
// What this prevents — a hand-written list query that forgets the org filter.let everyone = user::Entity::find().all(&conn).await?;// ^^^^ no connection reaches a serviceThe framework’s posture: handlers do not write SQL. They call
services. Services go through Repo, which hands out no connection, and
Repo::scoped(...) adds the filter, on a select that hands out no statement
to rewrite. Raw SQL in a filter stays inside the condition it is part of: text
that would reach past it is refused before the query runs.
When you really do need a custom query
Section titled “When you really do need a custom query”Sometimes a read needs what CrudService does not offer — an extra condition,
an order, a limit. Write it as a service method on Repo::scoped: the select it
returns takes SeaORM’s conditions, column orders and limits through its own
methods, and runs on the ambient executor with the ability’s condition already
in it.
use nest_rs::authz::Action;use nest_rs::seaorm::{Repo, ServiceError};use sea_orm::ColumnTrait;
impl UsersService { pub async fn search(&self, q: &str) -> Result<Vec<user::Model>, ServiceError> { Ok(Repo::<Users>::scoped(Action::Read) .filter(user::Column::Name.contains(q)) .order_by_asc(user::Column::Name) .all() .await?) }}The handler calls search and never sees a connection. A condition on
another entity — a subquery over orgs — takes that entity’s own filter from
scope_for::<Orgs>(Action::Read), so every table the query reads is
filtered. The select hands out no statement, so .query() and .select_only()
do not compile on it, and a raw Expr::cust in its filter stays one operand beside
the ability’s, refused when its text would leave it
(Raw SQL in a filter).
Going further
Section titled “Going further”- Predicates — the predicates that
feed
condition_for. - By-id binding — the unscoped load that distinguishes 404 from 403.
- Authorization — engine overview.