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
impl Auth
Sourcepub fn new(db: Db, secret_key: impl Into<String>, cookie_secure: bool) -> Self
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.
Sourcepub fn for_signing(secret_key: impl Into<String>, cookie_secure: bool) -> Self
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.
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).
Sourcepub async fn hash_password(&self, password: &str) -> SlabResult<String>
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.
Sourcepub async fn verify_password(
&self,
password: &str,
encoded_hash: &str,
) -> SlabResult<bool>
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.
Sourcepub async fn verify_password_constant_time(
&self,
password: &str,
encoded_hash: Option<&str>,
) -> SlabResult<bool>
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.
Sourcepub fn hash_token(&self, raw_token: &str) -> String
pub fn hash_token(&self, raw_token: &str) -> String
Compute the hex-encoded SHA-256 digest of a raw token.
Sourcepub fn generate_token(&self) -> String
pub fn generate_token(&self) -> String
Generate a cryptographically random 32-byte hex-encoded token.
Sourcepub fn generate_short_code(&self, len: usize) -> String
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.
Sourcepub fn sign_with_domain(&self, domain: &str, payload: &str) -> String
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}".
Sourcepub fn verify_with_domain(
&self,
domain: &str,
payload: &str,
signature_hex: &str,
) -> bool
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.
Sourcepub fn sign(&self, payload: &str) -> String
pub fn sign(&self, payload: &str) -> String
Compute a hex-encoded HMAC-SHA256 signature for payload under the "raw" domain.
Sourcepub fn verify_signature(&self, payload: &str, signature_hex: &str) -> bool
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.
Sourcepub fn sign_token<T: Serialize>(
&self,
purpose: &str,
payload: &T,
ttl: StdDuration,
) -> SlabResult<String>
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.
Sourcepub fn verify_token<T: DeserializeOwned>(
&self,
purpose: &str,
token: &str,
) -> SlabResult<T>
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.
Sourcepub async fn create_session_in_tx(
&self,
tx: &mut Transaction<'_, Sqlite>,
user_id: &str,
role: &str,
ttl_days: i64,
) -> SlabResult<(Session, Cookie<'static>)>
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.
Sourcepub async fn create_session(
&self,
user_id: &str,
role: &str,
ttl_days: i64,
) -> SlabResult<(Session, Cookie<'static>)>
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.
Sourcepub 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>)>
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.
Sourcepub async fn rotate_session(
&self,
old_raw_token: &str,
user_id: &str,
role: &str,
ttl_days: i64,
) -> SlabResult<(Session, Cookie<'static>)>
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.
Sourcepub async fn optional_session(
&self,
jar: &CookieJar,
) -> SlabResult<Option<Session>>
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.
Sourcepub async fn require_session(&self, jar: &CookieJar) -> SlabResult<Session>
pub async fn require_session(&self, jar: &CookieJar) -> SlabResult<Session>
Require a valid browser session from jar, failing with HTTP 401 if unauthenticated.
Sourcepub async fn require_admin(&self, jar: &CookieJar) -> SlabResult<Session>
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.
Sourcepub async fn destroy_session(
&self,
jar: &CookieJar,
) -> SlabResult<Cookie<'static>>
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.
Sourcepub async fn destroy_user_sessions(&self, user_id: &str) -> SlabResult<u64>
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.
Sourcepub async fn revoke_all_for_user_in_tx(
&self,
tx: &mut Transaction<'_, Sqlite>,
user_id: &str,
) -> SlabResult<u64>
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.
Sourcepub async fn cleanup_expired_sessions(&self) -> SlabResult<u64>
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.
Sourcepub async fn issue_magic_link(
&self,
email: &str,
purpose: &str,
ttl_minutes: i64,
) -> SlabResult<MagicLinkIssued>
pub async fn issue_magic_link( &self, email: &str, purpose: &str, ttl_minutes: i64, ) -> SlabResult<MagicLinkIssued>
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.
Sourcepub async fn consume_magic_link(
&self,
email: &str,
purpose: &str,
raw_code: &str,
) -> SlabResult<Option<MagicLinkConsumed>>
pub async fn consume_magic_link( &self, email: &str, purpose: &str, raw_code: &str, ) -> SlabResult<Option<MagicLinkConsumed>>
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.
Sourcepub async fn cleanup_expired_magic_links(&self) -> SlabResult<u64>
pub async fn cleanup_expired_magic_links(&self) -> SlabResult<u64>
Delete all expired magic link rows and return the number of rows removed.
Sourcepub async fn issue_access_token_with_expiry(
&self,
user_id: &str,
role: &str,
description: &str,
permission: &str,
ttl_days: Option<i64>,
) -> SlabResult<AccessTokenIssued>
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.
Sourcepub async fn issue_access_token(
&self,
user_id: &str,
role: &str,
description: &str,
permission: &str,
) -> SlabResult<AccessTokenIssued>
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".
Sourcepub async fn revoke_access_token(
&self,
token_id: &str,
user_id: &str,
) -> SlabResult<bool>
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.
Sourcepub async fn optional_auth(
&self,
jar: &CookieJar,
headers: &HeaderMap,
) -> SlabResult<Option<Principal>>
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.
Sourcepub async fn require_auth(
&self,
jar: &CookieJar,
headers: &HeaderMap,
) -> SlabResult<Principal>
pub async fn require_auth( &self, jar: &CookieJar, headers: &HeaderMap, ) -> SlabResult<Principal>
Require authentication via either session cookie or Authorization: Bearer token.
Sourcepub async fn require_write_auth(
&self,
jar: &CookieJar,
headers: &HeaderMap,
) -> SlabResult<Principal>
pub async fn require_write_auth( &self, jar: &CookieJar, headers: &HeaderMap, ) -> SlabResult<Principal>
Require an authenticated Principal with "write" permission.
Trait Implementations§
Auto Trait Implementations§
impl !RefUnwindSafe for Auth
impl !UnwindSafe for Auth
impl Forget for Auth
impl Freeze for Authwhere
*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
impl Sync for Auth
impl Unpin for Auth
impl UnsafeUnpin for Authwhere
*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> 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
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
impl<A, B, T> HttpServerConnExec<A, B> for Twhere
B: Body,
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