Security
Guards and the principal
Who made a request is its principal (smeltery::auth::Principal): the user's id (user_id), the guard that proved
it (guard), the credential (credential: Credential::Session { binding } for a signed-in session,
Credential::Token { id, abilities } for a token a guard issued) and when that credential stops working
(expires_at, None for sessions). A guard (smeltery::auth::Guard) reads a request's head and answers with the
principal it proves, or None. .auth::<User>() registers the guard web: the signed-in session, whose principal
the session stack stores on every web request of a signed-in user. AppBuilder::guard(g) registers another; two
guards with one name, a name other than lowercase ASCII letters, digits, _ and -, or a guard named web, stop
the app at boot. A guard returns a new principal for every request. A guard that reads only headers (a bearer
token) says so with stateless(): stateless guards never run on web routes, so a bearer credential never stands in
for the session and its CSRF check there.
| Call | Does |
|---|---|
.middleware("auth:web") |
the plain auth middleware |
.middleware("auth:<g1>,<g2>") |
runs the guards in order and stores the first principal found; without one, an API route whose list names a stateless guard answers 401 {"error":"Unauthenticated."} with WWW-Authenticate: Bearer and Cache-Control: no-store, and every other route what auth answers (on web routes the session is the only credential). An unknown guard name stops the app at boot |
Authenticated (handler argument) |
the principal (it derefs to Principal): the one the session stack or an auth: alias stored, else on API routes the first a stateless guard finds; 401 without one. Option<Authenticated> gives None instead |
principal.user::<User>(&app).await? / principal.auth_user(&app).await? |
the principal's user (loaded once per principal), typed or as an AuthUser |
principal.can("orders:read") |
sessions hold every ability; a token the abilities it lists, by exact name, or all with * |
principal.key() |
<guard>:session:<binding> or <guard>:token:<id> (web:session:3f…, hallmark:token:12): the name of the credential in grants and revocation events, unique across guards |
auth::authenticate(&app, &mut parts, GuardSet::Stateless).await? |
the first principal of the stateless guards for a request head, stored nowhere; None on web requests |
principal.with_user(user)? |
the principal with its user already loaded (a guard that read it), an error for another user's id |
session.binding() |
24 hex characters naming the session (the first 12 bytes of the SHA-256 of its CSRF secret): the <binding> of web:session:<binding> |
auth::credential_key(guard, kind, id) |
the key format of principal.key() (<guard>:<kind>:<id>), for code that names credentials it revokes |
Guard::first_party(app, parts) |
a guard's answer to "does this API request come from the app's own pages?" (default false); when a listed guard says yes, the auth: alias runs the whole web session stack around the request (smeltery::session::run_web_stack: session, remember-me, password-hash binding, the CSRF check on every state-changing method), lets a signed-in session through and otherwise runs the guards inside it |
auth::unauthenticated_bearer() |
the response of a bearer endpoint without a valid credential: 401 {"error":"Unauthenticated."}, WWW-Authenticate: Bearer, Cache-Control: no-store (what auth: answers on API routes) |
app.has_stateless_guard() |
whether a stateless guard is registered |
app.find_user(id).await? |
the user with that id as an AuthUser: id(), downcast::<User>(), binding(purpose) |
auth.auth_user().await? |
the signed-in user of a web request as an AuthUser |
AuthUser::binding(purpose) is the SHA-256 of smeltery-<purpose>|<password hash> (purpose: lowercase ASCII
letters, digits, ., _, -, else an error): a credential that stores it when issued and compares it on use
stops working after any password change. Signed-in sessions are bound this way
with the purpose session. The throttle: and verified middleware read the principal, so put auth:<guards>
before them on a route. verified checks the principal's user (session or token) and answers 403 {"error": "Your
email address is not verified."} on API routes and to JSON clients, and 401 when a guard's principal has no user
row any more.
use smeltery::auth::{Authenticated, Credential, Guard, Principal};
use smeltery::http::request::Parts;
use smeltery::prelude::*;
use smeltery::BoxFuture;
/// Accepts `X-Demo-User: <id>` (a stand-in for a real token check).
struct DemoGuard;
impl Guard for DemoGuard {
fn name(&self) -> &'static str { "demo" }
fn stateless(&self) -> bool { true }
fn authenticate<'a>(&'a self, _app: &'a App, parts: &'a mut Parts)
-> BoxFuture<'a, Result<Option<Principal>>> {
Box::pin(async move {
let id = parts.headers.get("x-demo-user")
.and_then(|v| v.to_str().ok())
.and_then(|v| v.parse::<i64>().ok());
Ok(id.map(|id| Principal::new(id, "demo", Credential::token(0, ["orders:read"]))))
})
}
}
async fn orders(who: Authenticated) -> Result<String> {
if !who.can("orders:read") {
return Err(Error::http(smeltery::http::StatusCode::FORBIDDEN, "Forbidden"));
}
Ok(format!("orders of user {}", who.user_id))
}
fn build(app: AppBuilder) -> AppBuilder {
app.guard(DemoGuard).api_routes(|r| {
r.get("/orders", orders).middleware("auth:demo").middleware("throttle:60,1");
})
}