Route model binding
#[authorize(A, bind = S)] turns a path id into the loaded, authorized model — 404 when the row is absent, 403 when it exists but the caller cannot see it.
#[authorize(Action, bind = Service)] turns /posts/{id} into a loaded,
authorized model, handed to the handler’s Authorized<Action, E>
parameter. The attribute is the route’s posture: it runs the class gate
with the guards and opens the reads under the caller’s ability, as
#[authorize(Action, Entity)] does. The load then runs through the service’s access method,
which reads the row under the caller’s own grant — one SQL lookup,
filtered by the same condition a list query uses. Three outcomes, three
HTTP statuses:
- Row not in the database →
404 NOT FOUND. - Row exists but the caller cannot see it →
403 FORBIDDEN. - Row exists and the caller may act on it → the loaded
Modelis handed to the handler.
The 404-vs-403 distinction is a policy decision, not an implementation detail. nestrs’s posture is 403 leaks existence intentionally: a member trying to read a user in another tenant’s org learns that the id is real but off-limits, not that “nothing is there”.
What it looks like
Section titled “What it looks like”use nest_rs::authz::Update;// …use nest_rs::seaorm::Authorized;// …
#[post("/{id}/publish")] #[authorize(Update, bind = PostsService)] #[use_guards(PostAuthorGuard)] // … async fn publish(&self, post: Authorized<Update, PostEntity>) -> Result<Json<Post>, PostError> { Ok(Json(self.svc.publish(post.into_inner()).await?)) }#[authorize(Update, bind = PostsService)] reads as: “gate the caller for
Update on posts, load the post the path’s id names, authorize the caller
for Update on that row, refuse with 404 or 403 otherwise”. The action
comes first and the service (not the entity) after bind =; the entity
is PostsService::Entity, or written beside the action when you want it
spelled out — the service’s own: another one does not compile, since the
gate and the wire row would read it while the load reads the service’s. The service is what the framework calls access on.
Authorized<Update, PostEntity> carries the row and nothing else: it
derefs to the entity’s Model, and into_inner() takes ownership. It is
never a posture of its own — written without bind = Service beside it,
it does not compile, and neither does a bind with no such parameter to
fill. The id is the one parameter the route’s path names, its
controller’s included: a bound route’s whole path names it alone (/{id},
/{id}/publish, or /summary under #[controller(path = "/posts/{id}")]),
and any other count does not compile.
GraphQL takes the same attribute on a #[query] or #[mutation]: the
operation’s Authorized<A, E> parameter becomes an id: String argument
on the schema (id_arg = … renames it), loaded the same way, a missing row
answering NOT_FOUND.
An MCP #[resource] takes it too, reading
the id off its template’s one variable. It has one answer for what cannot be read,
so a denied row, a missing one and an id that is no v7 all answer Resource not
found, and the body never runs. A WebSocket message and an MCP tool, prompt or
listing name no id, and refuse the key.
The four outcomes
Section titled “The four outcomes”The load decides among three early returns, after the class gate and before the handler runs:
| Path id | Row | Status |
|---|---|---|
| Not a UUID v7 | — | 400 BAD REQUEST |
| Valid | Absent in DB | 404 NOT FOUND |
| Valid | Present, denied | 403 FORBIDDEN |
| Valid | Present, allowed | Handler runs with the row |
The UUID v7 check is deliberate — the framework’s id format is ordered, v7 only. A v4 id (or a malformed string) fails fast at the edge.
A bound route whose chain runs no AbilityGuard never boots, the refusal naming
the route and the guard to bind: the class gate reads the ability that guard
attaches. Neither does a bound route with no guard at all: a route no guard
covers says #[public] or refuses the boot.
How access decides
Section titled “How access decides”The load calls S::access(action, id) on the service. The
default CrudService::access is (simplified):
async fn access(&self, action: Action, id: Uuid) -> Result<Access<Model>, RepoError>{ // Scoped load: the caller's own grant for `action`, in one lookup. if let Some(model) = Repo::<E>::unscoped_by_id(id) .filter(ability_scope::<E>(action)) .one().await? { return Ok(Access::Found(model)); } // Only now, and only to tell "forbidden" from "absent". let exists = Repo::<E>::unscoped_by_id(id).exists().await?; if exists { Ok(Access::Denied) } else { Ok(Access::Missing) }}A soft-deleted row is Missing for every action: both lookups hide it, as
every Repo read does. Two things to notice:
- The authorization is decided in SQL. The scoped lookup filters the
primary key by the ability’s
condition_for(action)— the exact condition the list path joins, evaluated by the same database. One source of truth: the row a list query returns and the rowaccessgrants cannot diverge. It is also what makes relational rules enforceable here — ap.relatedscope reaches through a join no in-memory check could evaluate without loading the parent. - The authorized path costs one lookup. The second, unscoped one runs
only after the first came back empty, purely to separate
DeniedfromMissing— so the caller who is refused pays for the distinction, and the caller who is allowed does not. Collapsing the two into a singleRepo::scoped(Read).find_by_id(id)would cost the same on the happy path and returnNonefor both refusals, hiding the policy decision behind a404.
The Access outcome
Section titled “The Access outcome”pub enum Access<M> { Found(M), Denied, Missing,}A handler that binds no subject (a service that authorizes its
own load, a worker job touching one row) returns Access<M> directly
and maps it to a wire shape:
match self.svc.access(Action::Read, id).await.map_err(ServiceError::from)? { Access::Found(user) => Ok(Json(User::from(&user))), Access::Denied => Err(HttpError::from_status(StatusCode::FORBIDDEN)), Access::Missing => Err(HttpError::from_status(StatusCode::NOT_FOUND)),}bind = Service does this mapping on HTTP and on GraphQL alike.
Updates and deletes — the by-id mutation path
Section titled “Updates and deletes — the by-id mutation path”For mutating actions, #[authorize(Update, bind = S)] (or Delete)
loads the row the caller is about to touch and refuses early if the policy
says no:
#[delete("/{id}")]#[http_code(204)]#[authorize(Delete, bind = UsersService)]async fn delete(&self, user: Authorized<Delete, UserEntity>) -> Result<()> { self.svc.delete(user.into_inner()).await.map_err(ServiceError::from)?; Ok(())}The combination of the load (Action::Delete checked against the
loaded row) and the scope_for(Delete) filter inside
Deletable::delete is defense in depth:
- The bound load refuses the route if the policy denies.
- Even if the handler were called anyway,
Repo::deleteappends the ability’scondition_for(Delete)to theDELETEstatement so a denied row deletes zero rows. The service answersRepoError::NotFoundand the row stands.
Two layers, same predicate, the second catches what the first missed.
Hide existence behind a 404 — sometimes you want that
Section titled “Hide existence behind a 404 — sometimes you want that”The framework’s default — 403 when the row exists but is off-limits — is the right call for first-party APIs where org isolation is a business rule, not a secret. The id space is already large; learning “id X exists in tenant B” tells an attacker nothing they could not guess.
For a public-facing API where existence itself is sensitive (private content, draft media), collapse the 403 path into a 404 in your handler:
#[get("/{id}")]async fn get(&self, id: Path<Uuid>) -> Result<Json<Post>> { match self.svc.access(Action::Read, id.0).await.map_err(ServiceError::from)? { Access::Found(post) => Ok(Json(Post::from(&post))), Access::Denied | Access::Missing => Err(HttpError::from_status(StatusCode::NOT_FOUND)), }}bind = Service is opinionated; the underlying access is not.
Going further
Section titled “Going further”- Row-level filtering — the layer underneath the bound by-id load.
- Response masking — the layer above, after the handler returns.
- Authorization — engine overview.