Skip to main content

Crate session_guard

Crate session_guard 

Source
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, the AuthSession and Sessions extractors and response impls (see the axum module). Enables tokio.
  • aide: OpenAPI docs through aide and rovo: the session_cookie security scheme (see the aide module).
  • tokio: Guard::spawn_purge, a background task that purges expired sessions.
  • postgres: a SessionStore on sqlx with embedded migrations.
  • valkey: a SessionStore on Valkey or Redis.
  • maxmind: IpIntel backed by MaxMind GeoLite2/GeoIP2 databases, reloaded when geoipupdate replaces the files.
  • metrics: counters through the metrics facade.
  • testing: the store_conformance! suite for custom stores.

Re-exports§

pub use crate::axum::GuardLayer;axum
pub use crate::axum::GuardService;axum
pub use crate::axum::Sessions;axum
pub 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;maxmind
pub use intel::MaxMindError;maxmind
pub use intel::MaxMindIntel;maxmind
pub use risk::Assessment;
pub use risk::assess;
pub use store::PgStore;postgres
pub use store::ValkeyStore;valkey
pub 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§

aideaide
OpenAPI support through aide, and so through rovo.
axumaxum
axum 0.8 integration: a tower layer that authenticates requests, the AuthSession extractor, 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-Age decision.
config
Guard configuration.
cookie
The session cookie: configuration, Set-Cookie rendering and Cookie parsing.
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.
testingtesting
Conformance suite for SessionStore implementations.
token
Opaque session tokens and their stored hashes.

Macros§

store_conformancetesting
Generates one #[tokio::test] per conformance check. $make is a closure returning a future that resolves to a fresh store handle.

Structs§

AuthSession
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.
GuardBuilder
Builds a Guard. Start with Guard::builder.
IssuedToken
A freshly issued token and the Set-Cookie value that delivers it.
NewSession
Result of Guard::login.
PurgeReport
Result of Guard::purge_expired.
SessionInfo
A session as listed by Guard::list_sessions or returned by Guard::peek, for “your devices” pages.

Enums§

Outcome
Result of Guard::authenticate.
Rejection
Why a request was rejected. Every variant maps to 401.
StepUpOutcome
Result of Guard::complete_step_up.