Authorization
AuthzAbility compiles your policy into an Ability per request, read by the query filter, the by-id binding and each wire row where it is built.
Authorization answers what the caller may do. You write one
AbilityFactory per app that compiles the caller’s principal into an
Ability — the per-request capability set. The framework reads that
ability from three places: the query pre-filter on every read, the
by-id binding when a route loads a row, and each wire row where
#[expose]’s conversion builds it. Each is a line on the unit: its #[authorize] or
#[public(Action, Subject)] names what it reads, and a unit naming nothing has
the ability withheld from its reads, so what it did not declare fails closed.
The engine is ability-based — grants, conditional rules, fields — but
backed by one shared Predicate AST so the SQL filter and the
in-memory check can never disagree row by row.
Install
Section titled “Install”cargo add nest-rs --features authzseaorm turns it on too. Every edge’s #[authorize] expands into this crate,
so a decorator carrying it in a build without authz is a compile error that
names the feature.
One factory, one ability per request
Section titled “One factory, one ability per request”AbilityFactory is a tiny trait you implement once. The framework
calls define per request, after the authn guard attached the
principal. The guard attaches the resulting Ability, so it is ambient
for the rest of the request, where the data layer reads it.
A minimal policy is one statement — “members read their org’s users”:
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 one line lands the class-level gate, the SQL pre-filter
(WHERE org_id = $caller_org_id), and the response-side check on
every loaded row. The next step is a role matrix — same builder,
branched on the principal:
fn define(&self, actor: &Claims, ab: &mut AbilityBuilder) { if actor.is_admin() { ab.can(Action::Manage, user::Entity) .when(|p| p.eq(user::Column::OrgId, actor.org_id)); ab.can(Action::Manage, org::Entity); } 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)); }}A RuleSpec commits on drop — ab.can(...).when(...).fields(...) is
one statement, no terminal .add() call. See
Policies for the full builder API.
The trait has a second, defaulted branch — define_visitor — that the
guard calls instead of define when what #[public(Action, Subject)] opens is reached with
no credential. It grants nothing until you write into it; see
Public reads.
Mount it on the controller
Section titled “Mount it on the controller”The AuthzModule provides AuthzGuard — a project type alias for
AbilityGuard<AuthzAbility> defined in features/authz/guard.rs, not
exported from nest_rs::authz. Import AuthzGuard from your feature crate, or
use AbilityGuard<YourAbility> directly from nest_rs::authz. Bind it
after AuthnGuard:
#[controller(path = "/users")]#[use_guards(AuthnGuard, AuthzGuard)]pub struct UsersController { #[inject] svc: Arc<UsersService>,}Order matters: AuthnGuard attaches the principal; AuthzGuard reads
it and builds the Ability. The route’s #[authorize] class gate runs
right after them, before any interceptor or filter the route declares, so
nothing the route binds answers a caller the gate refuses. A handler whose
posture names what it reads sees an ambient Ability it does not have to thread.
One class gate on every edge
Section titled “One class gate on every edge”#[authorize(Action, Entity)] means one thing wherever it is written — a
route, a GraphQL operation, a WebSocket message, an MCP tool — because every
decorator emits the same function, nest_rs::authz::class_gate::<Action, Entity>, run on the unit right after its guards:
- no ability guard in the unit’s chain or at its request: the boot refuses, naming the site and the guard to bind;
- no ability reached the unit all the same — a guard answering for one attached
none: refused opaquely, and one
erroronnest_rs::authznames the site and the remedy; - the caller is anonymous and the site is not
#[public]:401, whatever the visitor’s rules grant — a grant written for public reads never satisfies an#[authorize]; - no grant on the class:
403,forbidden; - a denial no
whennarrows —cannot(Create, E)besidecan(Manage, E)— matches every row, so the action is refused here, and so is a site gated onManage, which means every action:403,forbidden, the same answer whatever the token carries, since no scope lifts a denial; - a grant the token’s scopes withhold:
403naming the scopes to ask for (Scopes).
A grant or a denial a when narrows passes the gate: the rows decide it, in
the query pre-filter and on the loaded row. A when that holds for every row
by its shape — p.all([]), a disjunction holding one — narrows nothing, and
its denial is refused here like one with no when.
Each refusal files one warn, authorization denied, with its reason, and
reads the same on every edge, each answering in its own form: it names the unit
by host, method and the words its mounted line says, as a gate’s refusal of
the class does. The gate is no
feature of an edge: a package’s decorator emits it for its own posture as the
framework’s do.
The subject need not be a table. A capability — may transcode, may export —
is a subject #[subject] declares:
#[authorize(Manage, Transcoding)] runs this same gate, scope challenge
included, and the unit reads under the caller’s ability as one naming an entity
does, each row it answers judged for that caller. A visitor’s reads stay closed
there: a capability names no rows a visitor may read.
Three places the framework reads it
Section titled “Three places the framework reads it”Repo::scoped(Action)— the query pre-filter.condition_for::<E>(action)lowers the grants matching this action+entity into asea_orm::Condition, joined into every query. No matching grant ⇒1 = 0⇒ the query returns nothing. See Row-level filtering.#[authorize(A, bind = S)]— the by-id loader.Service::access(id)loads the row unscoped, then re-checks the same primary key filtered bycondition_for(action)— the decision is made in SQL, by the same predicate the list path joins. Missing row ⇒ 404, present but denied ⇒ 403. See By-id binding.- The wire row, judged where it is built.
User::from(&row)judges the whole row under the caller’s ability atRead: a column its grants withhold readsnull, a row they refuse answers no one, and the row answers only the caller it was judged for, on every edge and in every shape. See Response masking.
A service reads the ability too, when a decision of its own needs it: Reading the ability.
Where each piece lives
Section titled “Where each piece lives”- Policies — the
Subject/Action/RuleSpec/Predicatesurface and a real match-on-role example. - Row-level filtering
— what
Repo::scopeddoes, with before/after SQL. - By-id binding —
#[authorize(A, bind = S)]and the 404/403 distinction. - Response masking —
each wire row judged where it is built, and what
#[expose(nullable)]declares a grant may withhold. - Public reads —
define_visitor, the anonymous branch a#[public(Action, Subject)]unit reads. - OAuth scopes —
.requires_scope(...)narrows a rule to the scope a token carries, and refuses with aninsufficient_scopechallenge naming what to request. Read it when you hand tokens to third-party clients (MCP, in particular). - Endpoint guards — how GraphQL, WS, and MCP build the ambient ability at their request (explanation — useful once you add a second transport, not before).
In this section
Section titled “In this section”Basics
Section titled “Basics”- Policies — subjects, actions,
predicates and fields compiled into one
Ability. - Row-level filtering —
what
Repo::scopedjoins into the SQL, with before/after. - Route model binding —
#[authorize(A, bind = S)]turning a path id into a loaded, authorized model. - Response masking — the
row judged where it is built, a withheld column reading
nullin every shape.
All options
Section titled “All options”- Predicates — the AST a rule’s
whenbuilds, and scoping through a relation. - Field grants — the columns a reply shows and a write may set.
- Endpoint guards — the guards that build the ambient ability at each transport’s request.
- Authorizing WebSocket messages — a gateway’s guards at its upgrade, a posture per message.
- Public reads — the anonymous branch of the same policy, granting nothing until you write it.
- OAuth scopes — gate a rule on the scope a token carries, and refuse with an RFC 6750 challenge.
- Reading the ability — the ability in a service’s own check.
Going further
Section titled “Going further”- Authentication — how the principal an ability reads gets attached.
- Database — the
Repolayer the query pre-filter joins into. - Multi-tenant SaaS — the two layers under a production tenancy model.