pub struct Guard<St, S = Uuid> { /* private fields */ }Expand description
Issues, checks, rotates and revokes sessions. Cheap to clone; clones share state.
St is the SessionStore; S is your subject type (default Uuid), stored opaquely.
Implementations§
Source§impl<St: SessionStore, S: Subject> Guard<St, S>
impl<St: SessionStore, S: Subject> Guard<St, S>
Sourcepub fn layer(&self) -> GuardLayer<St, S>
Available on crate feature axum only.
pub fn layer(&self) -> GuardLayer<St, S>
axum only.A tower layer that authenticates every request through this guard.
See GuardLayer for what it does per request and how to configure it.
use std::{net::SocketAddr, time::Duration};
use axum::{Router, http::HeaderMap, routing::post};
use session_guard::{AuthSession, Checks, Guard, MemoryStore};
use uuid::Uuid;
async fn transfer(session: AuthSession<Uuid>) -> &'static str {
"done"
}
let guard = Guard::new(MemoryStore::new());
let layer = guard
.layer()
.with(Checks::strict())
.require_recent_auth(Duration::from_mins(15))
.bypass_bearer_prefixes(["pat_", "svc_"])
.bypass_when(|headers: &HeaderMap| headers.contains_key("x-internal-probe"));
let app = Router::new().route("/transfer", post(transfer)).layer(layer);
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await?;
axum::serve(listener, app.into_make_service_with_connect_info::<SocketAddr>()).awaitSource§impl<St: SessionStore> Guard<St>
impl<St: SessionStore> Guard<St>
Sourcepub fn builder(store: St, config: GuardConfig) -> GuardBuilder<St>
pub fn builder(store: St, config: GuardConfig) -> GuardBuilder<St>
Starts building a guard. Subjects are Uuid unless changed with
GuardBuilder::subject.
Source§impl<St: SessionStore, S: Subject> Guard<St, S>
impl<St: SessionStore, S: Subject> Guard<St, S>
Sourcepub async fn login(
&self,
subject: &S,
ctx: &ClientContext,
previous_token: Option<&str>,
) -> Result<NewSession, GuardError>
pub async fn login( &self, subject: &S, ctx: &ClientContext, previous_token: Option<&str>, ) -> Result<NewSession, GuardError>
Creates a session for subject and returns its first token.
Pass the token the client presented, if any: that session is revoked first, so a token planted before login (session fixation) never becomes authenticated. Call this only after verifying the subject’s credentials, and rate-limit that endpoint yourself.
§Errors
Store failures, an unavailable RNG, or a subject that does not serialize.
Sourcepub async fn authenticate(
&self,
token: &str,
ctx: &ClientContext,
) -> Result<Outcome<S>, GuardError>
pub async fn authenticate( &self, token: &str, ctx: &ClientContext, ) -> Result<Outcome<S>, GuardError>
Checks a request’s token with the configured checks.
On success the request may proceed; send Authenticated::rotated back as
Set-Cookie when present. Every Rejection maps to 401.
§Errors
Store failures only. Bad tokens and risky clients are Outcome::Rejected.
Sourcepub async fn authenticate_with(
&self,
token: &str,
ctx: &ClientContext,
checks: &Checks,
) -> Result<Outcome<S>, GuardError>
pub async fn authenticate_with( &self, token: &str, ctx: &ClientContext, checks: &Checks, ) -> Result<Outcome<S>, GuardError>
Like authenticate with other checks, for routes that need
stricter (or looser) treatment. The baseline learns only the signals checks scored.
§Errors
Store failures only.
Sourcepub async fn peek(
&self,
token: &str,
) -> Result<Option<SessionInfo<S>>, GuardError>
pub async fn peek( &self, token: &str, ) -> Result<Option<SessionInfo<S>>, GuardError>
Looks a token up without changing anything: no rotation, no last_seen write, no
checks. None unless the token is current (or within its grace period) and the session
is live.
§Errors
Store failures only.
Sourcepub async fn complete_step_up(
&self,
token: &str,
ctx: &ClientContext,
verified_subject: &S,
) -> Result<StepUpOutcome, GuardError>
pub async fn complete_step_up( &self, token: &str, ctx: &ClientContext, verified_subject: &S, ) -> Result<StepUpOutcome, GuardError>
Clears a pending step-up after the app has re-verified the subject (password, passkey,
OTP…). The current client becomes the new baseline, authenticated_at resets and a new
token is issued.
verified_subject must be the subject the app just verified; a mismatch changes
nothing. Rate-limit the verification yourself.
§Errors
Store failures or an unavailable RNG.
Sourcepub async fn logout(
&self,
token: &str,
ctx: &ClientContext,
) -> Result<bool, GuardError>
pub async fn logout( &self, token: &str, ctx: &ClientContext, ) -> Result<bool, GuardError>
Sourcepub async fn revoke_session(
&self,
subject: &S,
session_id: Uuid,
ctx: &ClientContext,
) -> Result<bool, GuardError>
pub async fn revoke_session( &self, subject: &S, session_id: Uuid, ctx: &ClientContext, ) -> Result<bool, GuardError>
Deletes one session of subject by id, e.g. from a “your devices” page. Returns whether
it existed; a session of another subject is left alone. ctx is whoever asked; it goes
into the EventKind::Revoked event.
§Errors
Store failures or a subject that does not serialize.
Sourcepub async fn revoke_all_for_subject(
&self,
subject: &S,
ctx: &ClientContext,
) -> Result<u64, GuardError>
pub async fn revoke_all_for_subject( &self, subject: &S, ctx: &ClientContext, ) -> Result<u64, GuardError>
Deletes every session of subject, e.g. after a password change. Returns how many.
ctx is whoever asked; each session gets an EventKind::Revoked event.
§Errors
Store failures or a subject that does not serialize.
Sourcepub async fn list_sessions(
&self,
subject: &S,
) -> Result<Vec<SessionInfo<S>>, GuardError>
pub async fn list_sessions( &self, subject: &S, ) -> Result<Vec<SessionInfo<S>>, GuardError>
Sourcepub async fn purge_expired(&self) -> Result<PurgeReport, GuardError>
pub async fn purge_expired(&self) -> Result<PurgeReport, GuardError>
Deletes expired sessions and events older than the retention period. Run it periodically (hourly is plenty).
§Errors
Store failures only.
Sourcepub fn spawn_purge(&self, every: Duration) -> JoinHandle<()> ⓘ
Available on crate feature tokio only.
pub fn spawn_purge(&self, every: Duration) -> JoinHandle<()> ⓘ
tokio only.Runs purge_expired now and then every every on the tokio
runtime, logging each report (info) or failure (warn) with tracing. A failed run
does not stop the task; abort the handle to stop it.
§Panics
Outside a tokio runtime, or if every is zero.
Sourcepub fn client_context<H: HeaderSource + ?Sized>(
&self,
peer: IpAddr,
headers: &H,
) -> ClientContext
pub fn client_context<H: HeaderSource + ?Sized>( &self, peer: IpAddr, headers: &H, ) -> ClientContext
Builds the ClientContext for a request from the TCP peer address and the request
headers.
X-Forwarded-For is honoured only when peer is a configured trusted proxy, walking
right to left past trusted hops. Header values are capped at the configured length.
The session cookie’s value from the request’s Cookie headers, if present.
A Set-Cookie value that deletes the session cookie.
Sourcepub fn requires_reauth(
&self,
session: &AuthSession<S>,
max_age: Duration,
) -> bool
pub fn requires_reauth( &self, session: &AuthSession<S>, max_age: Duration, ) -> bool
Whether the subject last proved who they are more than max_age ago. Use it to demand
a fresh login before sensitive actions.
With a zero max_age it is true as soon as any time has passed since the login or
step-up, so it is true for practically every request.
Sourcepub fn is_session_token(&self, value: &str) -> bool
pub fn is_session_token(&self, value: &str) -> bool
Whether value has the shape of this guard’s tokens (configured prefix, then 43
base64url characters). Does not touch the store.
Trait Implementations§
Auto Trait Implementations§
impl<St, S = Uuid> !RefUnwindSafe for Guard<St, S>
impl<St, S = Uuid> !UnwindSafe for Guard<St, S>
impl<St, S> Freeze for Guard<St, S>
impl<St, S> Send for Guard<St, S>
impl<St, S> Sync for Guard<St, S>
impl<St, S> Unpin for Guard<St, S>
impl<St, S> UnsafeUnpin for Guard<St, S>
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
Source§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read more