Skip to content

WebSocket guards

Connection-level guards on the upgrade and per-message guards on each envelope — one Guard trait, two scopes.

A WebSocket connection has two gates a Guard can sit on, and they answer different questions. The upgrade is an HTTP GET carrying headers, cookies and a query string: the moment to ask “may this peer open a connection at all?” The dispatch loop then runs in a task on the upgraded socket: the moment to ask “may this connection fire this event?” One Guard trait covers both, and the difference is where you bind it.

nest_rs::guards::Guard is the same trait used for HTTP routes and GraphQL operations. It has two entries, both over the unit being dispatched — check_http for an HTTP request, check for every other edge’s unit — and a guard overrides the ones it cares about. WebSockets reach both:

ScopeDecorator locationEntry run
Connection#[use_guards(...)] on the gateway structcheck_http (on the upgrade request, through HttpView)
Message#[use_guards(...)] next to a #[subscribe_message]check (on each envelope, through WsView)

A guard listed at gateway scope rejects the upgrade — the response goes back as HTTP, no socket is opened, no on_connect fires. A guard listed at message scope rejects the dispatch — the connection stays open, the envelope is replaced with an error frame on the same event name, and one guard denied the message lands on the guard’s target (nest_rs::layers when it declares none) naming the guard, the gateway’s path, the event and the status — never the guard’s text, as on every edge.

A connection-level guard runs once per connection, against the upgrade request, like any HTTP guard:

crates/features/src/chat/ws/gateway.rs
use nest_rs::ws::{gateway, messages};
use crate::authn::AuthnGuard;
use std::sync::Arc;
#[gateway(path = "/ws")]
#[use_guards(AuthnGuard)]
pub struct ChatGateway {
#[inject]
svc: Arc<ChatService>,
}

AuthnGuard reads the Authorization header (or a cookie, or a query parameter — your strategy decides), verifies the token, and attaches the principal for the rest of the connection. A failed check returns the same Denial shape an HTTP route would return (401, 403, etc.) — the client receives the response, and no socket is ever opened.

A browser sends a page’s cookies with any upgrade that page asks for, and never consults CORS first, so the upgrade’s Origin is checked before the socket opens (RFC 6455 §10.2), ahead of the gateway’s guards: a refused origin never pays for authentication. With no CORS policy, a page on the server’s own origin gets its socket; any other is answered 403, with a warn on nest_rs::ws that says why by kind and names the settings that would admit it, never the origin sent or the Host it was compared to. Once <PREFIX>_HTTP__CORS_ORIGINS is set, only the origins it lists get one — the server’s own included, when it serves the page — and the CORS layer’s 403 files its one warn on nest_rs::http (CORS). A client that sends no Origin — anything but a browser — is not concerned.

Because the connection is captured after connection-level guards, anything those guards attach (the principal, an ambient ability, the tenant) is carried into every message and connection hook on the connection, the ability staying off a hook’s reads — no seam to bind — and each runs as a unit of work of its own, on an executor the gateway opens for it. Without that capture, a per-message guard like AuthzGuard — whose check reads the ambient ability and fails closed — would see None once the upgrade request had unwound.

No posture stands before a connection hook, so its reads run under no ability, as on any unit naming no subject: a Repo read or write there fails closed, while the principal stays readable. Read what a client should see in a message whose posture names it.

A per-message guard runs every time the envelope’s event matches a handler the guard is attached to. Its decision is the one a route’s guard writes:

crates/features/src/chat/ws/guard.rs
use std::sync::Arc;
use nest_rs::core::{Layer, UnitContext, async_trait, injectable};
use nest_rs::guards::{Denial, Guard, GuardFor, PrincipalClaim};
use nest_rs::ws::WsView;
use crate::Claims;
use crate::chat::ChatService;
#[injectable]
#[derive(Layer)]
pub struct MutedGuard {
#[inject]
svc: Arc<ChatService>,
}
#[async_trait]
impl Guard for MutedGuard {
async fn check(&self, cx: &mut UnitContext<'_>) -> Result<(), Denial> {
let caller = cx.require::<Claims>()?;
if self.svc.is_muted(&caller.sub).await {
return Err(Denial::forbidden("you are muted in this room").with_reason("muted"));
}
Ok(())
}
fn expected_principal(&self) -> Option<PrincipalClaim> {
Some(PrincipalClaim::of::<Claims>())
}
fn target(&self) -> &'static str {
crate::chat::TARGET
}
}
impl GuardFor<WsView> for MutedGuard {}

The verified claims are the principal the guard requires, and declares (expected_principal): the boot refuses a gateway whose upgrade attaches none, so it never meets one at a message. The guard writes no log line: the edge files its refusal, guard denied the message on features::chat, with reason = "muted". A guard that needs the message itself switches to WsView: event(), data() and the client() that sent it, whose connection cx.peer() names too.

A rule about the caller alone — a token naming a user may post — needs no guard at all. It is a capability, granted beside every other rule and gated by the posture, which is what the demo’s chat does below.

Bind a guard beside the message it gates, with #[use_guards(MutedGuard)]. The demo’s chat needs none: its rule is a capability, granted only under a token naming a user, and the posture gates on it:

crates/features/src/chat/ws/gateway.rs
#[gateway(path = "/ws")]
#[use_guards(AuthnGuard, AuthzGuard)]
pub struct ChatGateway {
#[inject]
svc: Arc<ChatService>,
}
#[messages]
impl ChatGateway {
#[subscribe_message("message")]
#[authorize(Create, Posting)]
async fn on_message(&self, caller: Ambient<Claims>, msg: SendMessageDto) -> Result<(), WsError> {
self.svc.record(caller.into_inner().sub, msg).opaque()?;
Ok(())
}
}

The handler names the author from the same principal, the Ambient<Claims> parameter the upgrade’s AuthnGuard attached, so SendMessageDto carries the text alone: it is an #[input], and a payload naming an author is refused as an unknown field before the handler runs.

A denial surfaces as a wire-shaped error frame on the rejected event, the class a client branches on beside its sentence — code, the member a Problem answers under too, and the same class as reason. Here a service token, which names no user, tries to post:

Terminal window
> {"event":"message","data":{"text":"hi"}}
< {"event":"message","data":{"error":"forbidden","code":"FORBIDDEN","reason":"forbidden"}}

The connection stays open; the client can fire other events.

A refusal reads the same here as on HTTP, GraphQL and MCP. A 4xx denial carries its own sentence, and its frame adds beside its code what the client acts on: retryAfterSeconds for a rate limit, requiredScopes for a token too narrow. A 5xx never carries the guard’s text: an internal denial answers the opaque frame every unexplained failure answers, "internal error" (nest_rs_core::OPAQUE_CLIENT_MESSAGE) with code: "INTERNAL", and an unavailable dependency "service unavailable" (UNAVAILABLE_CLIENT_MESSAGE) with code: "UNAVAILABLE" and, when known, retryAfterSeconds.

Each message is a site of the pipeline, whose guard stage is composed once, at boot, from two sources: app-global guards and the guards listed on the message itself, then the class gate its posture declares. Guards bound on the gateway struct are not in this chain — they run once at the upgrade (check_http), never per message. Duplicates are removed by TypeId, so a guard registered globally and also listed on a specific message runs once per dispatch. Redeclaring on a provider therefore costs nothing, and a feature crate moved to an app that does not share the same globals still carries its own.

ConnUpgrade ── check_http ── on_connect
│
├── Envelope ── check (global ∪ message, dedup) ── gate ── layers ── handler
└── Envelope ── check (...) ── gate ── layers ── handler
└── on_disconnect ── close

A guard chain that returns Err(Denial) short-circuits at the first denial — later guards do not run, nor the class gate, nor any exception filter or handler-stage interceptor, the handler is skipped, and the error frame is sent. A unit-stage interceptor still reads that frame, as it reads a route’s 403.

WebSockets reuse the HTTP pair directly — there is no WS-specific guard type. The gateway struct binds #[use_guards(AuthnGuard, AuthzGuard)]; both run once on the upgrade (an HTTP GET) and are access-graph-validated like any HTTP binding: omit AuthzModule from the adapter’s imports and those guards are unreachable, so boot fails. Because the upgrade has returned before message handlers run, the connection carries the ability those guards attached — with every other value the upgrade carried — into each message, and the gateway opens each message’s unit of work itself. Binding AuthzGuard beside a #[subscribe_message] adds a per-message check through check: it reads the ability the upgrade attached, and builds one for a #[public] message alone — the rules of the actor a guard ahead of it identified, or those define_visitor writes. A gated message whose upgrade attaches no ability would answer 401 to every caller, so the boot refuses it, naming the remedy: bind AuthzGuard at the upgrade, in the gateway’s #[use_guards] or GlobalGuards, or declare an #[authorize] message #[public(Action, Subject)], which keeps its gate.

See Security for the strategy + ability composition, and Endpoint guards for AuthzModule beside its GraphQL and MCP siblings.

  • Security — the authn + authz wiring story across HTTP, GraphQL, and WS.
  • Replies and error frames — the wire shape of a denial reply and the return contract.