Public reads
A resource anyone may read is declared in AbilityFactory::define_visitor — the anonymous branch of the same policy, granting nothing until you write it.
A blog needs published posts readable without a login. The rules for
that caller live in the same AbilityFactory as everything else, in a
second branch: define_visitor. It receives no actor because there is
none, and it grants nothing until you write a rule into it.
use nest_rs::authz::{AbilityBuilder, AbilityFactory, Action};
impl AbilityFactory for AuthzAbility { type Actor = Claims;
fn define(&self, actor: &Claims, ab: &mut AbilityBuilder) { /* … */ }
fn define_visitor(&self, ab: &mut AbilityBuilder) { ab.can(Action::Read, post::Entity) .when(|p| p.eq(post::Column::Status, PostStatus::Published)); }}Everything downstream is the machinery you already have: the grant
becomes the WHERE clause on the visitor’s query, the class-level gate
on the unit, and the columns each wire row built under it holds.
Wire it in
Section titled “Wire it in”The route says what it reads, in one line:
#[get("/")]#[public(Read, post::Entity)]async fn list(&self) -> Result<Json<Vec<Post>>> { Ok(Json(self.svc.feed().await?))}feed is the service method, and it is where the boundary work belongs:
CrudService::list yields the entity’s Model and a RepoError, neither of which
crosses the wire, so the service returns Result<Vec<Post>, ServiceError> and
the handler stays a delegation.
pub async fn feed(&self) -> Result<Vec<Post>, ServiceError> { Ok(self.list().await?.iter().map(Post::from).collect())}#[public(Read, post::Entity)] takes #[authorize]’s arguments and does what it
does, for a caller with no credential as well: AuthnGuard admits that caller,
AuthzGuard builds the ability from define_visitor, the class gate runs against
it right after the guards, and each wire row the unit builds holds the fields it
grants; with no
AuthzGuard to build it, the boot refuses. Every edge
reads the line the same way, so a #[query], a #[subscribe_message] and a
#[tool] serve the same rows and the same fields:
#[query]#[public(Read, post::Entity)]async fn feed(&self) -> GqlResult<Vec<Post>> { /* … */ }
#[subscribe_message("feed")]#[public(Read, post::Entity)]#[use_guards(AuthzGuard)]async fn feed(&self) -> Result<Vec<Post>, WsError> { /* … */ }
#[tool(description = "The published posts.")]#[public(Read, post::Entity)]async fn feed(&self) -> Result<Json<Vec<Post>>, McpError> { /* … */ }A detail route loads its row by id the way an #[authorize] one does: the same
key, the same parameter, the same 404 and 403
(by-id binding).
#[get("/{id}")]#[public(Read, bind = PostsService)]async fn show(&self, post: Authorized<Read, post::Entity>) -> Result<Json<Post>> { Ok(Json(Post::from(&post.into_inner())))}An opening that reads nothing
Section titled “An opening that reads nothing”A sign-in, a health check or a ticker reads no row, and keeps the bare word:
#[post("/login")]#[public]async fn login(&self, Json(body): Json<LoginDto>) -> Result<Json<TokenDto>> { /* … */ }A bare #[public] reads nothing a grant guards, on every edge. It names no
subject its reads are for, so the ability is withheld from them: Repo renders
1 = 0, the route answers 200 [], and the warn on nest_rs::orm names the
entity, the action and the line to write.
WARN nest_rs::orm: no ambient Ability outside a worker job — denying all rows entity="posts" action="read" scope="request" hint="bind #[use_guards(AuthnGuard, AuthzGuard)], and declare what this unit reads: #[authorize(Read, Entity)], or #[public(Read, Entity)] where a caller with no credential is admitted"Grep that target the first time a route returns an empty collection you did not expect. The bare word costs a route that reads nothing nothing.
A token still takes the authenticated branch
Section titled “A token still takes the authenticated branch”define_visitor answers for the anonymous caller only. On a #[public]
route reached with a valid token, AuthnGuard attaches the principal
and AbilityGuard calls define, as it does on a #[public] operation whose
/graphql request an AuthnGuard ran with no AuthzGuard beside it — the visitor
rules are not a floor added under every caller.
That is what makes one route serve both audiences without a branch in
the handler: a visitor sees published posts because define_visitor
grants them, and a signed-in author sees their drafts too because
define grants those. The handler calls self.svc.feed() either way.
Reviewing a #[public] route
Section titled “Reviewing a #[public] route”Reading the diff that adds an opening tells you what it exposes, from a pair:
- the
#[public(Read, post::Entity)]line on the route, and - what
define_visitorgrants for that entity.
Both are greppable, both stay in one file each, and neither is inferred.
A route that says #[public(Read, post::Entity)] while define_visitor stays
empty exposes nothing — it answers 403. A grant added to define_visitor
reaches only the units naming that entity in their #[public(...)]. Review the
two together, and treat an edit to define_visitor with the weight of a
route-exposure change, because that is what it is.
Limits
Section titled “Limits”The default grants nothing, on every transport. An app that never
implements define_visitor behaves exactly as it did before the method
existed: an anonymous caller on a #[public(Read, post::Entity)] route gets an
ability with no rules, and the class gate answers 403, or the edge’s rendering
of it.
On GraphQL the operation’s posture, not the endpoint, holds the
line. /graphql is one in-band endpoint (Posture::InBand), so a caller
with no credential always reaches the resolvers carrying the visitor
ability, and one whose bearer does not verify is refused at the request. An
operation declared #[authorize(...)] refuses it for want of a
principal (UNAUTHENTICATED) before consulting a single grant — which
is what keeps the sentence above true on that transport: a visitor grant
opens the operations naming that entity in their #[public(...)] and no others.
A nested GraphQL field reads nothing for a visitor. A #[field_resolver] or a
relation’s loader runs off the operation that named the read, and no line on it
names one, so a visitor’s ability is withheld there and its read answers nothing,
with a warn of its own saying so: a relation reads null or an empty page, even of
the entity its root names. A batch loader reads
nothing for a visitor either, even from the root field naming the read: a batch
carries the request’s values, and the ability the field’s own guards attached where
its request carried none, never the license the field’s posture gave its own reads,
so a visitor’s rows are read in the field’s own body. A caller a token backs reads in all of these by define, its
rows filtered and each field masked by its grants,
under an #[authorize] operation as under a #[public] one.
A gated /mcp refuses anonymous callers. It carries no
Posture::InBand (its requests read Gated), so an unauthenticated tool
call is denied before the factory is consulted. define_visitor does not open it.
McpModule::for_root(McpAccess::Public) does, and there an AuthzGuard the
operation’s chain runs — the pool’s included — gives a #[public(Read, Entity)]
tool these grants, as it does such a WebSocket message under an upgrade no guard
identifying a caller runs. An #[authorize] tool there would read an ability no guard
at the request attaches, so it fails the boot, and the refusal names what lifts it:
#[public(Read, Entity)], which keeps the gate on these grants, or not opening the
endpoint.
A socket and an opened /mcp serve no token. A gateway whose upgrade
authenticates admits no visitor, and an opened /mcp reads no bearer at its
request, so on those edges a #[public(...)] unit answers by define_visitor
alone. One app serving both audiences on one operation does it on HTTP or GraphQL.
An #[sse] stream takes a subject no table holds, as #[authorize] there
does: its events are written after the route’s unit ended, where no ability is left
to judge a row.
A malformed visitor rule denies the request. A rule whose relation
predicate cannot be lowered fails ability construction, and the guard
answers 500 rather than installing a degraded ability — the same
fail-closed behavior the authenticated branch has.
Going further
Section titled “Going further”- Policies — the builder API both branches share.
- Row-level filtering — what the visitor’s grant becomes in SQL.
- Response masking — how
.fields([...])narrows a visitor’s response. - By-id binding — the
bind = Servicea detail route takes.