Skip to content

Guards

A guard decides whether a unit runs — write one, read the principal an earlier guard verified, and declare what it refuses with.

This page continues blog from Modules and Providers — the composed stage before you open the tutorial posts/ feature. Once PostsHttpModule mounts PostsController, guards decide who reaches each handler — and often attach the principal the handler reads back via Ambient<T>.

Terminal window
cargo add nest-rs --features guards

The http feature turns this on, and http is a default — name it explicitly only in a headless app built with default-features = false, where no transport implies it.

A guard runs before the handler. It sees the request first and either lets it through (Ok(())) or short-circuits with a typed Denial the framework maps to 401 / 403 / 429 — or 503, Denial::unavailable, when something the guard depends on did not answer and the caller did nothing wrong. A guard writes no log line for its refusals: the edge that ran it files each denial once, guard denied … on the target the guard declares (fn target, nest_rs::layers when it declares none) — at warn, at error for a 500 — naming the guard as you write it (AuthnGuard<JwtStrategy<Claims>>) and the unit by the fields of its mounted line: host and method, then verb and path on a request, kind and field on a GraphQL operation, event on a WebSocket message, tool, prompt or resource on an MCP operation. It carries the reason the denial names (Denial::forbidden("…").with_reason("banned_author")) and, when the denial keeps what failed (.with_source(err)), the whole chain as its error field, while the caller reads the condition alone. On HTTP the denial is answered as a problem document, unless the guard’s protocol fixes a refusal of its own: a token endpoint’s client is refused in RFC 6749 §5.2’s words, which ClientAuthenticationGuard writes through HttpView::respond before it returns its denial, and the edge serves that answer instead (Token endpoint). One trait, four edges — the same #[injectable] impl gates an HTTP route, a GraphQL field, a WebSocket message and an MCP operation (Guards beyond HTTP).

Guard ships in nest-rs-guards. It extends Layer so guards plug into dedup-by-TypeId and declaration-order chaining; #[derive(Layer)] writes that impl, with #[layer(priority = …)] when the guard orders itself within its site.

crates/features/src/posts/guard.rs
use nest_rs::core::{Layer, UnitContext, async_trait, injectable};
use nest_rs::guards::{Denial, Guard, GuardFor};
use nest_rs::http::HttpView;
#[injectable]
#[derive(Layer)]
pub struct RateLimitGuard;
#[async_trait]
impl Guard for RateLimitGuard {
async fn check(&self, cx: &mut UnitContext<'_>) -> Result<(), Denial> {
if over_quota(HttpView::of(cx)?.request()) {
return Err(Denial::rate_limited(60, "rate limited").with_reason("over_quota"));
}
Ok(())
}
}
impl GuardFor<HttpView> for RateLimitGuard {}

That last line declares the units your guard checks — see A guard declares the edges it checks. Without it, binding this guard on a route is a compile error.

A guard is an #[injectable] provider: a module’s providers = [...] lists it, unless the app-wide pool alone names it and registers it. The access graph (see Providers) ensures every controller / resolver / gateway that references it imports a module that builds it.

The trait carries two entries, both over the unit being dispatched, and a guard writes its decision once: check runs on every unit, and check_http runs check unless the guard overrides it. check has no default, so every guard writes its decision: RateLimitGuard reads the HTTP request in it, and binds on HTTP alone. Override check_http only where the HTTP request differs from the unit — the guard answers in its protocol’s own words, or what is missing at the request means something else than at the unit. A guard whose decision is the request’s alone admits the units that request carries with an explicit Ok(()) in check: no guard admits by default.

A guard also says what it does about the caller, through phase(): GuardPhase::Authentication establishes who it is, GuardPhase::Authorization decides what it may do, and GuardPhase::Other, the default, does neither: a rate limit, a feature gate. Only the first two cover a unit. RateLimitGuard above identifies no one, so a route under it alone says #[public], or the boot refuses it; a guard of your own that does gate declares its phase.

EntryRuns onReads it through
check_httpan HTTP request: a route, a WS upgrade, the /graphql and /mcp requests; check unless overriddenHttpView::of(cx) — the request, head and body, and the route it matched
checkevery unit: a GraphQL field, a WS message, an MCP operation — and the request, through check_httpcx.switch_to::<GraphqlView>(), WsView, McpView
nest_rs::guards::Guard
#[async_trait]
pub trait Guard: Layer {
async fn check_http(&self, cx: &mut UnitContext<'_>) -> Result<(), Denial> { self.check(cx).await }
async fn check(&self, cx: &mut UnitContext<'_>) -> Result<(), Denial>;
fn phase(&self) -> GuardPhase { GuardPhase::Other }
fn produced_principal(&self) -> Option<PrincipalClaim> { None }
fn expected_principal(&self) -> Option<PrincipalClaim> { None }
fn denial_statuses(&self, public: bool) -> &'static [u16] { /* … */ }
fn denial_document(&self) -> DenialDocument { DenialDocument::PROBLEM }
fn target(&self) -> &'static str { "nest_rs::layers" }
}

Whatever the edge, the execution context answers the same questions: cx.reflector() reads what the site declared (#[meta], its posture), cx.ambient::<T>() what an earlier guard attached, cx.attach(value) hands a value to everything after the guard, and cx.edge() and cx.handler() say which unit this is.

A guard that needs an earlier one’s work

Section titled “A guard that needs an earlier one’s work”

A value an earlier guard attaches — the principal AuthnGuard verified — is a precondition, not a decision. cx.require::<Claims>()? reads it, and a guard declaring that principal through expected_principal writes one decision for every edge, because its absence answers by cause:

crates/features/src/posts/guard.rs (from the demo)
#[injectable]
#[derive(Layer)]
pub struct PostAuthorGuard;
#[async_trait]
impl Guard for PostAuthorGuard {
async fn check(&self, cx: &mut UnitContext<'_>) -> Result<(), Denial> {
let claims = cx.require::<Claims>()?;
match claims.sub.user_id() {
Some(_) => Ok(()),
None => Err(
Denial::forbidden("writing a post takes a token naming a user")
.with_reason("not_a_user"),
),
}
}
fn phase(&self) -> GuardPhase {
GuardPhase::Authorization
}
fn expected_principal(&self) -> Option<PrincipalClaim> {
Some(PrincipalClaim::of::<Claims>())
}
fn target(&self) -> &'static str {
crate::posts::TARGET
}
}
impl<V: UnitView> GuardFor<V> for PostAuthorGuard {}

Nothing in the chain attaches it, the guard that does declaring produced_principal as AuthnGuard does: the boot refuses the route, the field, the message or the operation, naming the guard and the type, so the wiring gap never reaches a caller. The guard attaching it ran and admitted a caller with none — /graphql lets a visitor through to each field’s own gate, a #[public] route lets one in: the caller’s 401, on every edge, and on a #[public] route the invalid_token answer a credential it set aside earned, as an Ambient<T> parameter reads it. Any other value’s absence stays what it always was, a 500 the edge files once at error, naming the guard and the type. A guard that does without the principal, and decides a visitor itself, reads it with cx.ambient::<T>() and declares PrincipalClaim::of::<T>().or_visitor().

A route’s OpenAPI document lists the statuses its guards can refuse it with — the app’s pool, its controller’s and its own, the chain the route runs — whatever each guard is named or aliased. A guard declares them in denial_statuses, read off its Err paths; the default is 401 and 403 on a route that is not #[public] and nothing on one that is. The rate limit above answers neither:

crates/features/src/posts/guard.rs
impl Guard for RateLimitGuard {
// …
fn denial_statuses(&self, _public: bool) -> &'static [u16] {
&[429]
}
}

The framework’s guards declare theirs: AuthnGuard a 503 on every route and a 401 off a #[public] one, ClientAuthenticationGuard a 400, a 401 and a 503 on every route, ThrottlerGuard a 429, the ability guard none — the 403 an ability earns is answered where it is read, and a masked route lists it. A 500 is never declared: every route lists it. A refusal answers an error, so a status outside 400 to 599 fails the boot, naming the guard: its document would otherwise read a refusal as the route’s success.

A refusal through Denial reads as a problem document, its 401 challenged Bearer, and that is what the document says unless the guard answers in another protocol’s words. denial_document says which, in nest_rs::core’s DenialDocument: ClientAuthenticationGuard declares the Basic challenge and RFC 6749 §5.2’s body, so a token endpoint’s route requires basicAuth and lists that body on each status the guard declares, beside the problem document of a status the edge answers too: a Json<T> body it cannot decode, on the same 400.

nest_rs::oauth::server::ClientAuthenticationGuard
fn denial_document(&self) -> DenialDocument {
DenialDocument::answering(ChallengeScheme::Basic, |generator| {
generator.subschema_for::<TokenError>()
})
}
  • Guard scopes — bind a guard on a controller, a route or the app’s pool, and declare it on the provider.
  • Guard context — attach a value the handler reads, read route metadata and the posture, read the body.
  • Guards beyond HTTP — the two entries on GraphQL, WebSockets and MCP, and the GuardFor declaration.
  • Security — AuthnGuard, AbilityGuard, and the chain they compose into.