Skip to main content

Auth

Struct Auth 

Source
pub struct Auth { /* private fields */ }
Expand description

Explicit authentication and session service backed by slabs_sessions, slabs_magic_links, and slabs_access_tokens.

Supports async Argon2id password hashing, single-use 6-character magic links bound to (email, purpose), HttpOnly browser session cookies, SHA-256 hashed Authorization: Bearer tokens, and domain-separated HMAC-SHA256 signing.

Implementations§

Source§

impl Auth

Source

pub fn new(db: Db, secret_key: impl Into<String>, cookie_secure: bool) -> Self

Create an Auth service backed by db, using secret_key for HMAC signing and cookie_secure for the cookie Secure flag.

Source

pub fn for_signing(secret_key: impl Into<String>, cookie_secure: bool) -> Self

Create a stateless Auth handle for HMAC signing, token verification, and signed cookies without a database connection.

Source

pub fn cookie_secure(&self) -> bool

Return whether cookies emitted by this Auth instance should set the Secure attribute.

Return the active session cookie name ("__Host-slabs_session" when cookie_secure is true, or "slabs_session" when false).

Source

pub async fn hash_password(&self, password: &str) -> SlabResult<String>

Hash a plaintext password asynchronously with Argon2id and a random OS salt, returning a PHC string.

Rejects passwords exceeding 1024 bytes and runs hashing inside tokio::task::spawn_blocking guarded by a bounded concurrency semaphore so CPU-heavy hashing cannot starve the async runtime.

Source

pub async fn verify_password( &self, password: &str, encoded_hash: &str, ) -> SlabResult<bool>

Verify a plaintext password asynchronously against a stored Argon2id PHC hash string.

Rejects passwords exceeding 1024 bytes, requires the parsed PHC hash to use argon2::Algorithm::Argon2id, and executes verification inside tokio::task::spawn_blocking guarded by the password semaphore.

Source

pub async fn verify_password_constant_time( &self, password: &str, encoded_hash: Option<&str>, ) -> SlabResult<bool>

Verify a plaintext password against an optional stored Argon2id hash in constant time with respect to user existence.

When encoded_hash is None, still runs an Argon2id verification against a precomputed dummy hash and returns Ok(false) to prevent login timing enumeration.

Source

pub fn hash_token(&self, raw_token: &str) -> String

Compute the hex-encoded SHA-256 digest of a raw token.

Source

pub fn generate_token(&self) -> String

Generate a cryptographically random 32-byte hex-encoded token.

Source

pub fn generate_short_code(&self, len: usize) -> String

Generate a random alphanumeric code of length len, omitting ambiguous 0, O, 1, and I characters.

Source

pub fn sign_with_domain(&self, domain: &str, payload: &str) -> String

Compute a domain-separated hex-encoded HMAC-SHA256 signature over "slabs:v1:{domain}\0{payload}".

Source

pub fn verify_with_domain( &self, domain: &str, payload: &str, signature_hex: &str, ) -> bool

Verify a domain-separated hex-encoded HMAC-SHA256 signature in constant time.

Source

pub fn sign(&self, payload: &str) -> String

Compute a hex-encoded HMAC-SHA256 signature for payload under the "raw" domain.

Source

pub fn verify_signature(&self, payload: &str, signature_hex: &str) -> bool

Verify a hex-encoded HMAC-SHA256 signature for payload under the "raw" domain in constant time.

Source

pub fn sign_token<T: Serialize>( &self, purpose: &str, payload: &T, ttl: StdDuration, ) -> SlabResult<String>

Mint a purpose-bound, expiring HMAC-signed token carrying payload.

Encodes {"p": purpose, "exp": unix_ts, "d": payload} as URL-safe base64 without padding and appends .<hex_hmac_sig> signed under the "token" domain.

Source

pub fn verify_token<T: DeserializeOwned>( &self, purpose: &str, token: &str, ) -> SlabResult<T>

Verify a signed token produced by Auth::sign_token, enforcing purpose and expiration.

Returns a uniform HTTP 401 Unauthorized ("invalid or expired token") when the format, HMAC signature, encoding, payload shape, purpose, or expiration check fails.

Source

pub async fn create_session_in_tx( &self, tx: &mut Transaction<'_, Sqlite>, user_id: &str, role: &str, ttl_days: i64, ) -> SlabResult<(Session, Cookie<'static>)>

Insert a new browser session inside an existing SQLite transaction and return its cookie.

Rejects ttl_days outside 1..=365.

Source

pub async fn create_session( &self, user_id: &str, role: &str, ttl_days: i64, ) -> SlabResult<(Session, Cookie<'static>)>

Create and persist a new browser session in its own transaction and return its cookie.

Source

pub async fn rotate_session_in_tx( &self, tx: &mut Transaction<'_, Sqlite>, jar: &CookieJar, user_id: &str, role: &str, ttl_days: i64, ) -> SlabResult<(Session, Cookie<'static>)>

Atomically revoke any existing session cookie in jar (checking both __Host-slabs_session and slabs_session) and create a new session inside an open SQLite transaction.

Use this on sign-in, sign-up, password reset, or role changes to prevent session fixation while keeping session rotation atomic with surrounding domain writes.

Source

pub async fn rotate_session( &self, old_raw_token: &str, user_id: &str, role: &str, ttl_days: i64, ) -> SlabResult<(Session, Cookie<'static>)>

Atomically revoke an existing session token (if present) and create a new session in a single transaction.

Use this on authentication or privilege changes to prevent session fixation.

Source

pub async fn optional_session( &self, jar: &CookieJar, ) -> SlabResult<Option<Session>>

Look up the active, unexpired Session for the request’s cookie jar, if present.

Source

pub async fn require_session(&self, jar: &CookieJar) -> SlabResult<Session>

Require a valid browser session from jar, failing with HTTP 401 if unauthenticated.

Source

pub async fn require_admin(&self, jar: &CookieJar) -> SlabResult<Session>

Require a valid browser session with the "admin" role, failing with HTTP 401 or 403 otherwise.

Source

pub async fn destroy_session( &self, jar: &CookieJar, ) -> SlabResult<Cookie<'static>>

Delete the current session from the database (if present) and return a removal cookie.

Source

pub async fn destroy_user_sessions(&self, user_id: &str) -> SlabResult<u64>

Delete all active browser sessions belonging to user_id and return the number of sessions removed.

Source

pub async fn revoke_all_for_user_in_tx( &self, tx: &mut Transaction<'_, Sqlite>, user_id: &str, ) -> SlabResult<u64>

Delete all browser sessions (slabs_sessions) and personal access tokens (slabs_access_tokens) belonging to user_id inside an open SQLite transaction.

Returns the total number of revoked session and access-token rows. Use this on password changes, account deactivation, or privilege revocation so every active credential is invalidated atomically with the user update.

Source

pub async fn cleanup_expired_sessions(&self) -> SlabResult<u64>

Delete all expired session rows from slabs_sessions and return the number of rows removed.

Build an HttpOnly, SameSite=Lax session cookie carrying raw_token with an explicit Max-Age in days (clamped to 1..=365).

Build an HttpOnly, SameSite=Lax session cookie carrying raw_token with a default 30-day Max-Age.

Build an expired removal cookie that clears the browser session cookie.

Issue an expiring 6-character magic link code bound to (email, purpose) and store its keyed HMAC digest in slabs_magic_links.

Deletes any prior pending codes for (email, purpose) in the same transaction. Rejects ttl_minutes outside 1..=1440.

Atomically consume a valid, unexpired magic link code bound to email and purpose.

Returns Ok(Some(MagicLinkConsumed)) on success, or Ok(None) if the code is invalid, expired, mismatched, or locked out. After 5 failed attempts within 15 minutes for a given (email, purpose), any pending magic links for that pair are deleted.

Delete all expired magic link rows and return the number of rows removed.

Source

pub async fn issue_access_token_with_expiry( &self, user_id: &str, role: &str, description: &str, permission: &str, ttl_days: Option<i64>, ) -> SlabResult<AccessTokenIssued>

Issue a personal access token prefixed with slb_ and optional expiration in days.

Validates that permission is "read" or "write", and stores only the SHA-256 hex digest.

Source

pub async fn issue_access_token( &self, user_id: &str, role: &str, description: &str, permission: &str, ) -> SlabResult<AccessTokenIssued>

Issue a non-expiring personal access token prefixed with slb_ and store its SHA-256 hash in slabs_access_tokens.

Validates that permission is "read" or "write".

Source

pub async fn revoke_access_token( &self, token_id: &str, user_id: &str, ) -> SlabResult<bool>

Revoke a personal access token owned by user_id, returning Ok(true) if a row was deleted.

Source

pub async fn optional_auth( &self, jar: &CookieJar, headers: &HeaderMap, ) -> SlabResult<Option<Principal>>

Authenticate via Authorization: Bearer <token> or the session cookie.

When a Bearer header is present, this method validates only that token on the read pool, debounces last_used_at writes to at most once every 5 minutes, and returns Ok(None) if invalid.

Source

pub async fn require_auth( &self, jar: &CookieJar, headers: &HeaderMap, ) -> SlabResult<Principal>

Require authentication via either session cookie or Authorization: Bearer token.

Source

pub async fn require_write_auth( &self, jar: &CookieJar, headers: &HeaderMap, ) -> SlabResult<Principal>

Require an authenticated Principal with "write" permission.

Trait Implementations§

Source§

impl Clone for Auth

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 Debug for Auth

Source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl !RefUnwindSafe for Auth

§

impl !UnwindSafe for Auth

§

impl Forget for Auth

§

impl Freeze for Auth
where *const ArcInner<PoolInner<Sqlite>> is !null: Freeze, PhantomData<ArcInner<PoolInner<Sqlite>>>: Freeze, *const u8 is !null: Freeze, PhantomData<u8>: Freeze, *const ArcInner<Semaphore> is !null: Freeze, PhantomData<ArcInner<Semaphore>>: Freeze, *const ArcInner<Mutex<HashMap<String, (u32, Instant)>>> is !null: Freeze, PhantomData<ArcInner<Mutex<HashMap<String, (u32, Instant)>>>>: Freeze,

§

impl Move for Auth

§

impl Send for Auth
where Arc<PoolInner<Sqlite>>: Send, RawVecInner: Send, Arc<Semaphore>: Send, Arc<Mutex<HashMap<String, (u32, Instant)>>>: Send,

§

impl Sync for Auth
where Arc<PoolInner<Sqlite>>: Sync, RawVecInner: Sync, Arc<Semaphore>: Sync, Arc<Mutex<HashMap<String, (u32, Instant)>>>: Sync,

§

impl Unpin for Auth
where Arc<PoolInner<Sqlite>>: Unpin, *const u8 is !null: Unpin, Arc<Semaphore>: Unpin, Arc<Mutex<HashMap<String, (u32, Instant)>>>: Unpin,

§

impl UnsafeUnpin for Auth
where *const ArcInner<PoolInner<Sqlite>> is !null: UnsafeUnpin, PhantomData<ArcInner<PoolInner<Sqlite>>>: UnsafeUnpin, *const u8 is !null: UnsafeUnpin, PhantomData<u8>: UnsafeUnpin, *const ArcInner<Semaphore> is !null: UnsafeUnpin, PhantomData<ArcInner<Semaphore>>: UnsafeUnpin, *const ArcInner<Mutex<HashMap<String, (u32, Instant)>>> is !null: UnsafeUnpin, PhantomData<ArcInner<Mutex<HashMap<String, (u32, Instant)>>>>: 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<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

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> 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<A, B, T> HttpServerConnExec<A, B> for T
where B: Body,

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> 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> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

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<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

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