Policies
AbilityBuilder turns subjects, actions, predicates, and fields into one Ability — the same AST renders SQL and runs in memory.
A policy is a function from a principal to an Ability. The function
runs per request — AbilityFactory::define is called once after
authn, and the guard attaches the returned Ability, ambient for the
rest of the request. This page covers the builder API: subjects, actions,
conditional rules, restricted fields, denials.
Predicates compile through a single Predicate AST that lowers to
SeaORM’s Condition for the SQL filter
and matches in-memory for the by-id check and each wire row’s judgement.
One AST, two interpreters — the rows the query returns and the rows
a reply may answer cannot diverge.
A minimal policy
Section titled “A minimal policy”use nest_rs::authz::{AbilityBuilder, AbilityFactory, Action};use nest_rs::core::injectable;
#[injectable]pub struct AuthzAbility;
impl AbilityFactory for AuthzAbility { type Actor = Claims;
fn define(&self, actor: &Claims, ab: &mut AbilityBuilder) { ab.can(Action::Read, user::Entity) .when(|p| p.eq(user::Column::OrgId, actor.org_id)); }}That is the whole surface for “members read their org’s users”. Three
things land at once: the class-level gate (can a member read users?),
the SQL pre-filter (WHERE org_id = $caller_org_id), and the
response-side check on every loaded row.
Subjects
Section titled “Subjects”A subject is any type that implements nest_rs::authz::Subject. The
crate ships a blanket impl for every sea_orm::EntityTrait:
pub trait Subject: 'static {}impl<E: sea_orm::EntityTrait> Subject for E {}So a SeaORM entity (user::Entity, org::Entity) is the canonical
subject — the bridge isolates the ORM coupling to one impl block.
Introducing a second data layer moves one impl, not the engine. A
capability no table holds is the other kind, which #[subject] declares
(below).
Subject is used as a type-system guardrail in a posture’s
#[authorize(A, S)] and #[public(A, S)] and in the condition_for::<E> calls. Subjects are keyed by TypeId
under the hood; Action::Manage on a subject acts as a wildcard for
every other action on that same subject.
Subjects no table holds
Section titled “Subjects no table holds”Some decisions are about a capability, not rows: may this caller transcode
audio, export the org’s reports, trigger a reindex? Declare the capability
with #[subject] on a unit struct, beside the feature that owns it:
use nest_rs::authz::subject;
#[subject]pub struct Transcoding;A rule grants it whole, with the scope a token must carry when the capability is delegated:
if actor.is_admin() { ab.can(Action::Manage, Transcoding) .requires_scope(AUDIO_TRANSCODE);}and every operation that exercises it declares the posture on it —
#[authorize(Manage, Transcoding)] on an HTTP route, an #[sse] stream,
a GraphQL field, a WebSocket message or an MCP tool alike. It is the
same class gate
as on an entity, with the same refusals and the same RFC 6750 scope
challenge. The subject has no model, so the reply goes out as written, and
the unit reads under the caller’s ability as one naming an entity does: what
its body reads through Repo is filtered by the caller’s grants, and each wire
row it answers is judged for that caller where it is built. A visitor’s reads
stay closed there, since a capability names no rows a visitor may read.
The type system keeps the two kinds apart. when and fields narrow an
entity’s rows and columns, so a subject no table holds refuses them; so
does cannot, because the class gate is that subject’s one layer and a
grant you do not write is already the denial. Each is bounded on
RowSubject, which every entity is, and a capability is told why:
error[E0277]: `Exporting` has no rows to deny or narrow: `cannot`, `when` and `fields` take a SeaORM entity = note: a capability `#[subject]` declares has no rows: a grant covers it whole, and a grant not written is its denialDon’t borrow an entity for a capability (Manage on org::Entity to mean
“may transcode”): a rule on the entity then grants or withholds the
capability by accident, and a grep for the capability finds nothing.
Actions
Section titled “Actions”Five variants, four typed markers:
pub enum Action { Read, Create, Update, Delete, Manage }Manage is the action wildcard — a grant on Manage matches every
other action on the same subject. Each variant has a type marker
(Read, Create, Update, Delete, Manage) implementing
ActionMarker, so a posture can name an action as a type
(#[authorize(Read, user::Entity)]).
A grant on Read does not imply Update. A grant on Manage does.
ab.can(Action::Manage, org::Entity); // covers Read, Create, Update, DeleteA site gated on Manage asks for all of it: #[authorize(Manage, E)] passes only
where Read, Create, Update and Delete would each pass. So cannot(Read, E)
beside can(Manage, E) refuses a site gated on Read and a site gated on Manage,
and leaves the other three open; four separate grants pass it; cannot(Manage, E)
refuses all five. A caller barred from reading a thing does not manage it.
The rows follow the same reading: condition_for::<E>(Action::Manage) and
Ability::can hold a row to every action’s rules. What such a site answers shows what
the caller may Read, and a write in its body reads the write’s own action.
Rules — grant, condition, fields
Section titled “Rules — grant, condition, fields”AbilityBuilder has two starters: can (grant) and cannot
(denial). Each returns a RuleSpec that commits on drop — bind it
to a variable only if you want to defer the commit:
ab.can(Action::Read, user::Entity) .when(|p| p.eq(user::Column::OrgId, actor.org_id)) .fields([user::Column::Id, user::Column::Name]);| Method | What it does |
|---|---|
.can(action, subject) | Begin a grant |
.cannot(action, subject) | Begin a denial — a matching denial overrides a matching grant |
.when(|p| ...) | Constrain the rule to rows matching the predicate |
.fields([col, ...]) | Restrict a grant to these columns: what a reply shows, and what a write sets |
.requires_scope(scope) | Withhold a grant from a token without the scope (Scopes) |
Skip .when and the rule is unconditional. Skip .fields and every
field is permitted. A denial takes .when alone: it hides rows, never
columns, and holds whatever the token carries, so
cannot(..).fields(..) and cannot(..).requires_scope(..) do not
compile.
The closure handed to when receives a PredicateBuilder<E> typed
to the rule’s entity, so column references are type-checked at compile
time. A rule scoped to user::Entity cannot accidentally reference
org::Column::Id.
What when takes is on Predicates,
and what fields grants, to a reply and to a write, on
Field grants.
A real match-on-role example
Section titled “A real match-on-role example”The exemplar in crates/features/src/authz/ability.rs:
impl AbilityFactory for AuthzAbility { type Actor = Claims;
fn define(&self, actor: &Claims, ab: &mut AbilityBuilder) { if actor.is_admin() { ab.can(Action::Read, user::Entity) .when(|p| p.eq(user::Column::OrgId, actor.org_id)); ab.can(Action::Manage, user::Entity) .when(|p| p.eq(user::Column::OrgId, actor.org_id)); ab.can(Action::Manage, org::Entity); ab.can(Action::Manage, Transcoding) .requires_scope(constants::AUDIO_TRANSCODE); // … } else { ab.can(Action::Read, user::Entity) .when(|p| p.eq(user::Column::OrgId, actor.org_id)) .fields([user::Column::Id, user::Column::Name]); ab.can(Action::Create, user::Entity) .when(|p| p.eq(user::Column::OrgId, actor.org_id)); ab.can(Action::Read, org::Entity) .when(|p| p.eq(org::Column::Id, actor.org_id)); // … } // … }}What this buys:
- Admin reads and manages every user in their org; reads and
manages every org unconditionally; may transcode audio when the token
carries
audio:transcode(a subject no table holds). - Member reads users in their org but only
idandname; can create users in their org; reads their own org only. - No role at all (or unknown role) falls into the member branch
— the test
empty_roles_behave_as_a_non_admin_memberpins this so a degraded token cannot silently grant admin powers.
Denials override grants
Section titled “Denials override grants”A cannot rule that matches a row overrides every matching grant on
the same action+subject. Use it sparingly — the common case is a
narrow grant, not a broad grant clawed back.
ab.can(Action::Read, user::Entity);ab.cannot(Action::Read, user::Entity) .when(|p| p.eq(user::Column::Status, "banned"));The SQL pre-filter for Read becomes
(OR of grant conditions) AND NOT (OR of deny conditions). The
in-memory check refuses if any denial matches even when grants do.
A denial with no .when — or with one that holds for every row by its
shape, such as p.all([]) — matches every row, so the class gate refuses
the action outright, on every edge, before a handler, a query or an entity
hook runs:
ab.can(Action::Manage, user::Entity) .when(|p| p.eq(user::Column::OrgId, actor.org_id));ab.cannot(Action::Create, user::Entity);This caller reads, updates and deletes the users of their org, and a
POST /users answers a plain 403 — the same answer whatever the
token’s scopes, since no scope lifts a denial.
Where the policy lives
Section titled “Where the policy lives”Always in crates/features/src/authz/ability.rs. The factory is the
single source of truth for the app’s authorization rules — HTTP,
GraphQL, WS, and MCP transports all build the same AuthzAbility.
Spreading policy across handlers is the drift the framework prevents.
Going further
Section titled “Going further”- Predicates — the AST a rule’s
whenbuilds, and scoping through a relation. - Field grants — what
.fields(...)shows a reply and lets a write set. - Row-level filtering — how the predicate lowers to SQL.
- Authorization — the engine overview.