Expand description
Stolen session cookies become useless: rotating tokens with reuse detection and risk-based step-up for Rust web apps.
A Guard issues opaque session tokens, stores only their SHA-256 hashes, rotates them
every few minutes and revokes the session when a superseded token comes back after its
successor was used: the signature of a copied cookie. Every request is also scored against
the session’s client fingerprint (OS, browser, client hints, country, network, anonymizers);
a moderate change asks the app to re-verify the subject, a drastic one revokes the session.
The crate handles sessions only. Logging in, verifying passwords and rate limiting stay in the app.
use session_guard::{ClientContext, Guard, MemoryStore, Outcome};
let guard = Guard::new(MemoryStore::new());
let ctx = ClientContext::new("203.0.113.7".parse().unwrap()).with_user_agent("Mozilla/5.0 …");
// After the app has verified the user's credentials:
let user = uuid::Uuid::new_v4();
let session = guard.login(&user, &ctx, None).await?;
let set_cookie = session.token.set_cookie(); // send as `Set-Cookie`
// On every later request:
match guard.authenticate(session.token.expose(), &ctx).await? {
Outcome::Authenticated(auth) => {
assert_eq!(auth.session.subject, user);
// send `auth.rotated` as `Set-Cookie` when present
}
Outcome::Rejected(rejection) => {
// answer 401 with `{"error": rejection.as_str()}`
}
}§Features
axum: a tower layer that authenticates requests, theAuthSessionandSessionsextractors and response impls (see theaxummodule). Enablestokio.aide: OpenAPI docs throughaideandrovo: thesession_cookiesecurity scheme (see theaidemodule).tokio:Guard::spawn_purge, a background task that purges expired sessions.postgres: aSessionStoreon sqlx with embedded migrations.valkey: aSessionStoreon Valkey or Redis.maxmind:IpIntelbacked byMaxMindGeoLite2/GeoIP2databases, reloaded whengeoipupdatereplaces the files.metrics: counters through themetricsfacade.testing: thestore_conformance!suite for custom stores.
Re-exports§
pub use crate::axum::GuardLayer;axumpub use crate::axum::GuardService;axumpub use crate::axum::Sessions;axumpub use checks::Check;pub use checks::Checks;pub use checks::Decision;pub use checks::Thresholds;pub use checks::UnknownCheck;pub use client::ClientContext;pub use client::HeaderSource;pub use client::canonical_ip;pub use client::resolve_client_ip;pub use clock::Clock;pub use clock::ManualClock;pub use clock::SystemClock;pub use config::GuardConfig;pub use config::GuardConfigBuilder;pub use config::Mode;pub use config::RotationConfig;pub use config::StepUpPolicy;pub use cookie::CookieConfig;pub use cookie::SameSite;pub use error::ConfigError;pub use error::GuardError;pub use error::StoreError;pub use event::ClientSummary;pub use event::EventKind;pub use event::SessionEvent;pub use event::SessionOrigin;pub use fingerprint::Baseline;pub use fingerprint::Fingerprint;pub use fingerprint::ip_prefix;pub use intel::Anonymity;pub use intel::IpInfo;pub use intel::IpIntel;pub use intel::NoIpIntel;pub use intel::MaxMindDatabase;maxmindpub use intel::MaxMindError;maxmindpub use intel::MaxMindIntel;maxmindpub use risk::Assessment;pub use risk::assess;pub use store::PgStore;postgrespub use store::ValkeyStore;valkeypub use store::ClaimScope;pub use store::MemoryStore;pub use store::Rotation;pub use store::SessionRecord;pub use store::SessionStore;pub use store::SessionUpdate;pub use store::Supersede;pub use store::TokenLookup;pub use store::TokenRecord;pub use store::session_bucket;pub use store::token_bucket;pub use subject::Subject;pub use token::SessionToken;pub use token::TOKEN_LEN;pub use token::TokenHash;pub use token::is_well_formed;
Modules§
- aide
aide - OpenAPI support through
aide, and so throughrovo. - axum
axum - axum 0.8 integration: a tower layer that authenticates requests, the
AuthSessionextractor, and helpers for routes outside the layer. - checks
- Risk checks, their weights and the score thresholds.
- client
- What the guard knows about the client making a request.
- clock
- Time source used for every expiry, rotation and cookie
Max-Agedecision. - config
- Guard configuration.
- cookie
- The session cookie: configuration,
Set-Cookierendering andCookieparsing. - error
- Error types.
- event
- Security events: what happened to a session, recorded in the store and passed to the hook.
- fingerprint
- Normalised client signals and the per-session baseline they are compared against.
- intel
- Country, city, ASN, network name and anonymizer lookups for client IPs.
- risk
- Scores the current request against a session’s baseline.
- store
- The storage contract and the built-in stores.
- subject
- The opaque subject a session belongs to.
- testing
testing - Conformance suite for
SessionStoreimplementations. - token
- Opaque session tokens and their stored hashes.
Macros§
- store_
conformance testing - Generates one
#[tokio::test]per conformance check.$makeis a closure returning a future that resolves to a fresh store handle.
Structs§
- Auth
Session - An authenticated session, as handed to the app.
- Authenticated
- An authenticated request.
- Guard
- Issues, checks, rotates and revokes sessions. Cheap to clone; clones share state.
- Guard
Builder - Builds a
Guard. Start withGuard::builder. - Issued
Token - A freshly issued token and the
Set-Cookievalue that delivers it. - NewSession
- Result of
Guard::login. - Purge
Report - Result of
Guard::purge_expired. - Session
Info - A session as listed by
Guard::list_sessionsor returned byGuard::peek, for “your devices” pages.
Enums§
- Outcome
- Result of
Guard::authenticate. - Rejection
- Why a request was rejected. Every variant maps to 401.
- Step
UpOutcome - Result of
Guard::complete_step_up.