Skip to main content

Guard

Struct Guard 

Source
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>

Source

pub fn layer(&self) -> GuardLayer<St, S>

Available on crate feature 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>()).await
Source§

impl<St: SessionStore> Guard<St>

Source

pub fn new(store: St) -> Self

A guard with the default configuration and Uuid subjects.

Source

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>

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

pub async fn logout( &self, token: &str, ctx: &ClientContext, ) -> Result<bool, GuardError>

Ends the session the token belongs to. Returns whether there was one.

§Errors

Store failures only.

Source

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.

Source

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.

Source

pub async fn list_sessions( &self, subject: &S, ) -> Result<Vec<SessionInfo<S>>, GuardError>

The live sessions of subject.

§Errors

Store failures or a subject that does not serialize.

Source

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.

Source

pub fn spawn_purge(&self, every: Duration) -> JoinHandle<()> ⓘ

Available on crate feature 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.

Source

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.

Source

pub fn cookie_token<'a, H: HeaderSource + ?Sized>( &self, headers: &'a H, ) -> Option<&'a str>

The session cookie’s value from the request’s Cookie headers, if present.

A Set-Cookie value that deletes the session cookie.

Source

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.

Source

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§

Source§

impl<St, S> Clone for Guard<St, S>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<St, S> Debug for Guard<St, S>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

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>
where Arc<Inner<St>>: Freeze, PhantomData<fn() -> S>: Freeze,

§

impl<St, S> Send for Guard<St, S>
where Arc<Inner<St>>: Send, PhantomData<fn() -> S>: Send,

§

impl<St, S> Sync for Guard<St, S>
where Arc<Inner<St>>: Sync, PhantomData<fn() -> S>: Sync,

§

impl<St, S> Unpin for Guard<St, S>
where Arc<Inner<St>>: Unpin, PhantomData<fn() -> S>: Unpin,

§

impl<St, S> UnsafeUnpin for Guard<St, S>
where Arc<Inner<St>>: UnsafeUnpin, PhantomData<fn() -> S>: UnsafeUnpin,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DynClone for T
where T: Clone,

Source§

fn __clone_box(&self, _: Private) -> *mut ()

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FromRef<T> for T
where T: Clone,

Source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoApi for T

Source§

fn into_api<A>(self) -> UseApi<T, A>
where T: Sized,

into UseApi
Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts 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 more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts 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
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more