Guards
Admit or refuse a call before the interceptors and the handler are built.
A guard decides whether a call proceeds. It runs after pre-dispatch and before any interceptor, and it sees the call's context but not a reply. The examples for this page are examples/16-http-enhancers and examples/41-one-guard-two-transports.
The trait
pub trait Guard<T: Transport>: Send + Sync + 'static {
fn can_activate(&self, cx: &T::Cx) -> impl Future<Output = Result<bool, BoxError>> + Send;
}A guard answers with one of these:
| Answer | Meaning | HTTP | gRPC |
|---|---|---|---|
Ok(true) | admit | the next stage runs | the next stage runs |
Ok(false) | a caller the guard knows and will not admit | 403 | PERMISSION_DENIED |
Err(CallError::unauthorized(..)) | a caller that has not authenticated | 401 with the challenge | UNAUTHENTICATED |
any other Err | a failure | offered to the error handlers as it stands | same |
crates/ulo-http/tests/guard_refusals.rs pins the 403 and the 401. Ok(false) reaches the error handlers as GuardRejected { guard }, so a handler can reshape the refusal per route. Unclaimed, the transport renders its forbidden status.
Writing one
A guard is a type that implements Guard<Http> and is registered like any other binding. Dep<Trace> injects the example's Trace, a provider that records what ran (Providers). HttpCx is the HTTP call's context. This one admits a call whose x-role header names the role the handler declared with #[meta(RequiresRole(..))]:
use ulo::{BoxError, Dep, Guard, injectable};
use ulo_http::{Http, HttpCx};
/// Declared on a handler with `#[meta(..)]`; a guard reads it through the handler's info.
pub struct RequiresRole(pub &'static str);
#[injectable]
pub struct RoleGuard {
trace: Dep<Trace>,
}
impl Guard<Http> for RoleGuard {
async fn can_activate(&self, cx: &HttpCx) -> Result<bool, BoxError> {
let needed = cx.exec().handler().and_then(|handler| handler.meta::<RequiresRole>()).map(|role| role.0);
let given = cx.headers().get("x-role").and_then(|value| value.to_str().ok());
let admitted = needed.is_none_or(|needed| given == Some(needed));
self.trace.push(format!("guard role: {}", if admitted { "admitted" } else { "refused" }));
Ok(admitted)
}
}cx.exec().handler() returns the information of the handler the call is dispatched to, set before the first guard runs. meta::<T>() reads declared metadata, and the most specific declaration wins: a method's #[meta(..)] overrides the impl's. A handler without the metadata reads None and the guard above admits it.
A guard passes data to later stages by writing to the execution's extensions, cx.extensions().insert(value), which a handler or a later stage reads as Ext<T>, a typed view of that bag.
Declaring guards
A global guard is an into AnyGuard<Http> entry in the module's providers. A controller or method guard is a #[guards(..)] attribute on the impl or the handler:
#[handlers]
#[guards(RoleGuard, with = |trace: Dep<Trace>| Stamp::new("controller", trace))]
impl ReportsController {
#[ulo_http::get("/reports")]
fn open(&self) -> &'static str { /* .. */ }
#[ulo_http::get("/reports/payroll")]
#[guards(with = |trace: Dep<Trace>| Stamp::new("method", trace))]
#[meta(RequiresRole("admin"))]
fn payroll(&self) -> &'static str { /* .. */ }
}
#[module(
providers = [
into AnyGuard<Http>: [with = |trace: Dep<Trace>| Stamp::new("global", trace)],
/* .. */
],
controllers = [ReportsController],
)]
pub struct AppModule;Stamp is the example's type that writes a trace line as a guard and as an interceptor. The three spellings of an entry (type, value =, with =) and the three tiers are described in Request Lifecycle.
Order and lazy construction
Guards run global, then controller, then method, and within a tier in the order written. In the example's controller, RoleGuard is written before the closure, so the trace for an admitted /reports/payroll call is:
guard global, guard role: admitted, guard controller, guard methodA guard is built only once the one before it has admitted. examples/16-http-enhancers/src/order.rs records construction as well as execution:
#[ulo_http::get("/lazy/closed")]
#[guards(with = |trace: Dep<Trace>| Gate::new("first", false, trace), with = |trace: Dep<Trace>| Gate::new("second", true, trace))]
fn closed(&self) -> &'static str { /* .. */ }For /lazy/closed the trace is built first, ran first, and then the refusal: the second guard is never built, no interceptor is built, and the handler does not run. The order is a security property: an authentication guard written before a role guard always runs first.
A refusal still goes through the error handlers. In the same example Refusals is an error handler on the controller, and it answers the 403 in its own words:
GET /reports/payroll -> 403 "RoleGuard needs role admin"One guard for several transports
A guard written impl<T: Transport> Guard<T> serves every transport whose context it can read. examples/41-one-guard-two-transports refuses any handler that declares #[meta(Shut)], on HTTP and on RPC alike:
use ulo::{BoxError, ExecutionRef, Guard, Transport, injectable};
pub struct Shut;
#[injectable]
pub struct Maintenance;
impl<T: Transport> Guard<T> for Maintenance
where
T::Cx: AsRef<ExecutionRef>,
{
async fn can_activate(&self, cx: &T::Cx) -> Result<bool, BoxError> {
let exec: &ExecutionRef = cx.as_ref();
Ok(exec.handler().and_then(|handler| handler.meta::<Shut>()).is_none())
}
}AsRef<ExecutionRef> is what every transport's context implements, so the guard names neither HTTP nor RPC. Both controllers name it with the same attribute:
#[handlers]
#[guards(Maintenance)]
impl ShopHttp {
#[ulo_http::get("/shop")]
fn open(&self) -> &'static str { "open" }
#[ulo_http::get("/shop/stocktake")]
#[meta(Shut)]
fn shut(&self) -> &'static str { "unreachable" }
}
#[handlers]
#[guards(Maintenance)]
impl ShopRpc {
#[ulo_rpc::message("shop.open")]
async fn open(&self) -> &'static str { "open" }
#[ulo_rpc::message("shop.stocktake")]
#[meta(Shut)]
async fn shut(&self) -> &'static str { "unreachable" }
}The refusal is the same event rendered by each transport's own rules. tests/guard.rs asserts both:
- HTTP: status 403,
content-type: application/problem+json,titleForbidden,detailforbidden. - RPC: an error of kind
ErrorKind::Forbiddenwith messageforbidden.
A controller-level #[guards(Maintenance)] applies to every handler on the impl, so each handler's transport must have the role. A controller that serves several transports scopes an entry with the transport-scoped form, #[guards(http = AuthGuard)], which applies to that transport's handlers alone.
A guard that needs the HTTP request, such as one reading a header, implements Guard<Http> and takes &HttpCx. Metadata declared with a transport-specific type, such as MaxBody, is HTTP metadata and fails to compile on a handler of another transport.