Skip to content

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.

Terminal window
cargo add nest-rs --features authz

seaorm 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.

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”:

crates/features/src/authz/ability.rs (from the demo)
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:

crates/features/src/authz/ability.rs
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.

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:

crates/features/src/users/http/controller.rs (from the demo)
#[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.

#[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 error on nest_rs::authz names 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 when narrows — cannot(Create, E) beside can(Manage, E) — matches every row, so the action is refused here, and so is a site gated on Manage, 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: 403 naming 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.

  1. Repo::scoped(Action) — the query pre-filter. condition_for::<E>(action) lowers the grants matching this action+entity into a sea_orm::Condition, joined into every query. No matching grant ⇒ 1 = 0 ⇒ the query returns nothing. See Row-level filtering.
  2. #[authorize(A, bind = S)] — the by-id loader. Service::access(id) loads the row unscoped, then re-checks the same primary key filtered by condition_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.
  3. The wire row, judged where it is built. User::from(&row) judges the whole row under the caller’s ability at Read: a column its grants withhold reads null, 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.

  • Policies — the Subject/Action/RuleSpec/Predicate surface and a real match-on-role example.
  • Row-level filtering — what Repo::scoped does, 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 an insufficient_scope challenge 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).
  • Policies — subjects, actions, predicates and fields compiled into one Ability.
  • Row-level filtering — what Repo::scoped joins 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 null in every shape.
  • Predicates — the AST a rule’s when builds, 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.
  • Authentication — how the principal an ability reads gets attached.
  • Database — the Repo layer the query pre-filter joins into.
  • Multi-tenant SaaS — the two layers under a production tenancy model.