Skip to main content

slabs_auth/
lib.rs

1//! Authentication, browser sessions, magic links, personal access tokens, and HMAC signing for Slabs.
2//!
3//! # What this crate owns
4//!
5//! - Types: [`Auth`], [`Session`], [`Principal`], [`MagicLinkIssued`], [`MagicLinkConsumed`],
6//!   [`AccessTokenIssued`], [`SESSION_COOKIE_NAME`] (`"slabs_session"`), and
7//!   [`HOST_SESSION_COOKIE_NAME`] (`"__Host-slabs_session"`).
8//! - Framework SQLite tables created by `slabs_db::Db::init_system_tables`:
9//!   - `slabs_sessions`: SHA-256 hashed browser session tokens, `user_id`, `role`, and `expires_at`.
10//!   - `slabs_magic_links`: domain-separated HMAC-SHA256 hashed 6-character verification codes bound to
11//!     normalized `email` and `purpose`, plus `expires_at`.
12//!   - `slabs_access_tokens`: SHA-256 hashed `Authorization: Bearer` tokens, `user_id`, `role`, `permission`, `last_used_at`, and `expires_at`.
13//! - User accounts live in your application's own `users` table in your SQL migrations. This crate does not own a `users` table.
14//!
15//! # Agent invariants
16//!
17//! - Put an explicit auth guard on line 1 of every protected slab handler. Do not rely on hidden middleware or callbacks.
18//!   - [`Auth::require_session`]: requires a valid session cookie (HTTP 401 when missing or expired).
19//!   - [`Auth::require_admin`]: requires a valid session with `role == "admin"` (HTTP 401 or 403).
20//!   - [`Auth::require_auth`]: accepts either `Authorization: Bearer <token>` or a session cookie (HTTP 401).
21//!   - [`Auth::require_write_auth`]: requires [`Auth::require_auth`] with `permission == "write"` (HTTP 403 for `"read"` tokens).
22//! - Hash passwords asynchronously with [`Auth::hash_password`] (`Argon2id` offloaded to `spawn_blocking` with a concurrency semaphore and 1024-byte cap) and verify with [`Auth::verify_password`] or [`Auth::verify_password_constant_time`].
23//! - Magic links generate 6-character alphanumeric codes without ambiguous characters (`0`, `O`, `1`, `I`), hashed with a keyed domain-separated HMAC bound to `(email, purpose)`. [`Auth::consume_magic_link`] requires matching `email`, `purpose`, and code, locks out after 5 failed attempts in 15 minutes, and runs `DELETE ... RETURNING` so every code is single-use.
24//! - Personal access tokens start with `slb_` and are stored only as SHA-256 hex digests. Return [`AccessTokenIssued::token`] once at issuance because plaintext tokens cannot be recovered later.
25//! - If an `Authorization: Bearer` header is present, [`Auth::optional_auth`] checks only the bearer token and does not fall back to a session cookie on failure.
26//! - Use [`Auth::create_session_in_tx`] when creating a user and a browser session inside one SQLite transaction, and [`Auth::rotate_session`] on login or privilege escalation.
27//!
28//! # Example
29//!
30//! ```rust,no_run
31//! use axum_extra::extract::CookieJar;
32//! use http::HeaderMap;
33//! use slabs_auth::Auth;
34//! use slabs_core::SlabResult;
35//!
36//! async fn protected_handler(auth: &Auth, jar: &CookieJar, headers: &HeaderMap) -> SlabResult<()> {
37//!     // Line 1 guard for browser-only endpoints:
38//!     let session = auth.require_session(jar).await?;
39//!
40//!     // Or accept either a session cookie or a write-scoped Bearer token:
41//!     let principal = auth.require_write_auth(jar, headers).await?;
42//!
43//!     let _ = (session.user_id, principal.user_id);
44//!     Ok(())
45//! }
46//! ```
47
48use argon2::{
49    password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString},
50    Algorithm, Argon2,
51};
52use axum_extra::extract::cookie::{Cookie, CookieJar, SameSite};
53use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
54use chrono::{DateTime, Duration, SecondsFormat, Utc};
55use hmac::{Hmac, Mac};
56use http::{header, HeaderMap};
57use rand_core::{OsRng, RngCore};
58use serde::{de::DeserializeOwned, Deserialize, Serialize};
59use sha2::{Digest, Sha256};
60use slabs_core::{id, SlabError, SlabResult};
61use slabs_db::Db;
62use sqlx::{Sqlite, Transaction};
63use std::collections::HashMap;
64use std::fmt;
65use std::sync::{Arc, Mutex, OnceLock};
66use std::time::{Duration as StdDuration, Instant};
67use tokio::sync::Semaphore;
68
69type HmacSha256 = Hmac<Sha256>;
70
71const MAX_PASSWORD_BYTES: usize = 1024;
72const DEFAULT_SESSION_TTL_DAYS: i64 = 30;
73const MAGIC_LINK_MAX_ATTEMPTS: u32 = 5;
74const MAGIC_LINK_LOCKOUT_WINDOW: StdDuration = StdDuration::from_secs(15 * 60);
75const ACCESS_TOKEN_LAST_USED_DEBOUNCE_SECS: i64 = 5 * 60;
76
77static DUMMY_PASSWORD_HASH: OnceLock<String> = OnceLock::new();
78
79fn dummy_password_hash() -> &'static str {
80    DUMMY_PASSWORD_HASH.get_or_init(|| {
81        let salt = SaltString::generate(&mut OsRng);
82        Argon2::default()
83            .hash_password(b"slabs-dummy-password-for-constant-time-verify", &salt)
84            .expect("dummy Argon2id hash generation must succeed")
85            .to_string()
86    })
87}
88
89fn utc_timestamp(dt: DateTime<Utc>) -> String {
90    dt.to_rfc3339_opts(SecondsFormat::Micros, true)
91}
92
93#[derive(Serialize)]
94struct SignedTokenEnvelopeRef<'a, T: ?Sized> {
95    p: &'a str,
96    exp: i64,
97    d: &'a T,
98}
99
100#[derive(Deserialize)]
101struct SignedTokenEnvelope<T> {
102    p: String,
103    exp: i64,
104    d: T,
105}
106
107/// Cookie name used to store browser session tokens when `cookie_secure` is `false`.
108pub const SESSION_COOKIE_NAME: &str = "slabs_session";
109
110/// Host-prefixed cookie name used when `cookie_secure` is `true` (`__Host-` prefix prevents subdomain injection).
111pub const HOST_SESSION_COOKIE_NAME: &str = "__Host-slabs_session";
112
113/// Active browser session persisted in the `slabs_sessions` table.
114#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
115pub struct Session {
116    /// Prefixed session identifier (`ses_...`).
117    pub id: String,
118    /// Authenticated user's identifier.
119    pub user_id: String,
120    /// Role assigned to the user when the session was created (e.g. `"member"`, `"admin"`).
121    pub role: String,
122    /// RFC 3339 UTC timestamp after which the session is no longer valid.
123    pub expires_at: String,
124    /// RFC 3339 UTC timestamp when the session was created.
125    pub created_at: String,
126}
127
128/// Authenticated actor resolved from either a browser session cookie or an `Authorization: Bearer` token.
129#[derive(Debug, Clone, Serialize, Deserialize)]
130pub struct Principal {
131    /// Authenticated user's identifier.
132    pub user_id: String,
133    /// Role associated with the authenticated user.
134    pub role: String,
135    /// Authentication mechanism used (`"session"` or `"bearer"`).
136    pub auth_kind: String,
137    /// Granted permission level (`"write"` or `"read"`).
138    pub permission: String,
139}
140
141/// Result returned when a new one-time magic link code is issued.
142#[derive(Clone, Serialize, Deserialize)]
143pub struct MagicLinkIssued {
144    /// Prefixed magic-link record identifier (`mlk_...`).
145    pub id: String,
146    /// Normalized lowercase email address the code was issued for.
147    pub email: String,
148    /// Application-defined purpose for the magic link (e.g. `"sign_in"`).
149    pub purpose: String,
150    /// Plaintext one-time verification code to deliver to the user.
151    pub code: String,
152    /// RFC 3339 UTC timestamp when the code expires.
153    pub expires_at: String,
154}
155
156impl fmt::Debug for MagicLinkIssued {
157    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
158        f.debug_struct("MagicLinkIssued")
159            .field("id", &self.id)
160            .field("email", &self.email)
161            .field("purpose", &self.purpose)
162            .field("code", &"[REDACTED]")
163            .field("expires_at", &self.expires_at)
164            .finish()
165    }
166}
167
168/// Verified metadata returned after atomically consuming a magic link code.
169#[derive(Debug, Clone, Serialize, Deserialize)]
170pub struct MagicLinkConsumed {
171    /// Prefixed magic-link record identifier (`mlk_...`).
172    pub id: String,
173    /// Normalized email address associated with the consumed code.
174    pub email: String,
175    /// Application-defined purpose associated with the consumed code.
176    pub purpose: String,
177}
178
179/// Result returned when a new personal access token is issued.
180#[derive(Clone, Serialize, Deserialize)]
181pub struct AccessTokenIssued {
182    /// Prefixed access-token record identifier (`pat_...`).
183    pub id: String,
184    /// Owner user identifier.
185    pub user_id: String,
186    /// Human-readable label describing the token's purpose.
187    pub description: String,
188    /// Permission scope granted to the token (`"write"` or `"read"`).
189    pub permission: String,
190    /// Plaintext bearer token shown once upon issuance (`slb_...`).
191    pub token: String,
192}
193
194impl fmt::Debug for AccessTokenIssued {
195    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
196        f.debug_struct("AccessTokenIssued")
197            .field("id", &self.id)
198            .field("user_id", &self.user_id)
199            .field("description", &self.description)
200            .field("permission", &self.permission)
201            .field("token", &"[REDACTED]")
202            .finish()
203    }
204}
205
206/// Explicit authentication and session service backed by `slabs_sessions`, `slabs_magic_links`, and `slabs_access_tokens`.
207///
208/// Supports async `Argon2id` password hashing, single-use 6-character magic links bound to
209/// `(email, purpose)`, `HttpOnly` browser session cookies, SHA-256 hashed `Authorization: Bearer`
210/// tokens, and domain-separated HMAC-SHA256 signing.
211#[derive(Clone)]
212pub struct Auth {
213    db: Option<Db>,
214    secret_key: String,
215    cookie_secure: bool,
216    password_permits: Arc<Semaphore>,
217    magic_link_failures: Arc<Mutex<HashMap<String, (u32, Instant)>>>,
218}
219
220impl fmt::Debug for Auth {
221    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
222        f.debug_struct("Auth")
223            .field("db", &self.db)
224            .field("secret_key", &"<redacted>")
225            .field("cookie_secure", &self.cookie_secure)
226            .finish_non_exhaustive()
227    }
228}
229
230impl Auth {
231    fn default_password_permits() -> Arc<Semaphore> {
232        let permits = std::thread::available_parallelism().map_or(4, |n| n.get().clamp(2, 16));
233        Arc::new(Semaphore::new(permits))
234    }
235
236    /// Create an [`Auth`] service backed by `db`, using `secret_key` for HMAC signing and `cookie_secure` for the cookie `Secure` flag.
237    #[must_use]
238    pub fn new(db: Db, secret_key: impl Into<String>, cookie_secure: bool) -> Self {
239        Self {
240            db: Some(db),
241            secret_key: secret_key.into(),
242            cookie_secure,
243            password_permits: Self::default_password_permits(),
244            magic_link_failures: Arc::new(Mutex::new(HashMap::new())),
245        }
246    }
247
248    /// Create a stateless [`Auth`] handle for HMAC signing, token verification, and signed cookies without a database connection.
249    #[must_use]
250    pub fn for_signing(secret_key: impl Into<String>, cookie_secure: bool) -> Self {
251        Self {
252            db: None,
253            secret_key: secret_key.into(),
254            cookie_secure,
255            password_permits: Self::default_password_permits(),
256            magic_link_failures: Arc::new(Mutex::new(HashMap::new())),
257        }
258    }
259
260    /// Return whether cookies emitted by this [`Auth`] instance should set the `Secure` attribute.
261    #[must_use]
262    pub fn cookie_secure(&self) -> bool {
263        self.cookie_secure
264    }
265
266    /// Return the active session cookie name (`"__Host-slabs_session"` when `cookie_secure` is `true`,
267    /// or `"slabs_session"` when `false`).
268    #[must_use]
269    pub fn session_cookie_name(&self) -> &'static str {
270        if self.cookie_secure {
271            HOST_SESSION_COOKIE_NAME
272        } else {
273            SESSION_COOKIE_NAME
274        }
275    }
276
277    fn db(&self) -> SlabResult<&Db> {
278        self.db
279            .as_ref()
280            .ok_or_else(|| SlabError::internal("Auth requires a database connection"))
281    }
282
283    /// Hash a plaintext password asynchronously with `Argon2id` and a random OS salt, returning a PHC string.
284    ///
285    /// Rejects passwords exceeding 1024 bytes and runs hashing inside `tokio::task::spawn_blocking`
286    /// guarded by a bounded concurrency semaphore so CPU-heavy hashing cannot starve the async runtime.
287    pub async fn hash_password(&self, password: &str) -> SlabResult<String> {
288        if password.len() > MAX_PASSWORD_BYTES {
289            return Err(SlabError::bad_request("password exceeds maximum length"));
290        }
291        let _permit = self
292            .password_permits
293            .acquire()
294            .await
295            .map_err(|_| SlabError::internal("password hashing semaphore closed"))?;
296        let password_owned = password.to_owned();
297        tokio::task::spawn_blocking(move || {
298            let salt = SaltString::generate(&mut OsRng);
299            Argon2::default()
300                .hash_password(password_owned.as_bytes(), &salt)
301                .map(|h| h.to_string())
302                .map_err(|e| SlabError::internal(format!("password hashing failed: {e}")))
303        })
304        .await
305        .map_err(|e| SlabError::internal(format!("password hashing task failed: {e}")))?
306    }
307
308    /// Verify a plaintext password asynchronously against a stored `Argon2id` PHC hash string.
309    ///
310    /// Rejects passwords exceeding 1024 bytes, requires the parsed PHC hash to use
311    /// [`argon2::Algorithm::Argon2id`], and executes verification inside `tokio::task::spawn_blocking`
312    /// guarded by the password semaphore.
313    pub async fn verify_password(&self, password: &str, encoded_hash: &str) -> SlabResult<bool> {
314        if password.len() > MAX_PASSWORD_BYTES {
315            return Err(SlabError::bad_request("password exceeds maximum length"));
316        }
317        let _permit = self
318            .password_permits
319            .acquire()
320            .await
321            .map_err(|_| SlabError::internal("password verification semaphore closed"))?;
322        let password_owned = password.to_owned();
323        let hash_owned = encoded_hash.to_owned();
324        tokio::task::spawn_blocking(move || {
325            let Ok(parsed) = PasswordHash::new(&hash_owned) else {
326                return false;
327            };
328            let Ok(alg) = Algorithm::try_from(parsed.algorithm) else {
329                return false;
330            };
331            if alg != Algorithm::Argon2id {
332                return false;
333            }
334            Argon2::default()
335                .verify_password(password_owned.as_bytes(), &parsed)
336                .is_ok()
337        })
338        .await
339        .map_err(|e| SlabError::internal(format!("password verification task failed: {e}")))
340    }
341
342    /// Verify a plaintext password against an optional stored `Argon2id` hash in constant time
343    /// with respect to user existence.
344    ///
345    /// When `encoded_hash` is `None`, still runs an `Argon2id` verification against a precomputed
346    /// dummy hash and returns `Ok(false)` to prevent login timing enumeration.
347    pub async fn verify_password_constant_time(
348        &self,
349        password: &str,
350        encoded_hash: Option<&str>,
351    ) -> SlabResult<bool> {
352        if password.len() > MAX_PASSWORD_BYTES {
353            return Err(SlabError::bad_request("password exceeds maximum length"));
354        }
355        if let Some(hash) = encoded_hash {
356            self.verify_password(password, hash).await
357        } else {
358            let _ = self
359                .verify_password(password, dummy_password_hash())
360                .await?;
361            Ok(false)
362        }
363    }
364
365    /// Compute the hex-encoded SHA-256 digest of a raw token.
366    pub fn hash_token(&self, raw_token: &str) -> String {
367        let mut hasher = Sha256::new();
368        hasher.update(raw_token.as_bytes());
369        hex::encode(hasher.finalize())
370    }
371
372    /// Generate a cryptographically random 32-byte hex-encoded token.
373    pub fn generate_token(&self) -> String {
374        let mut bytes = [0u8; 32];
375        OsRng.fill_bytes(&mut bytes);
376        hex::encode(bytes)
377    }
378
379    /// Generate a random alphanumeric code of length `len`, omitting ambiguous `0`, `O`, `1`, and `I` characters.
380    pub fn generate_short_code(&self, len: usize) -> String {
381        const ALPHABET: &[u8] = b"23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
382        let mut bytes = vec![0u8; len];
383        OsRng.fill_bytes(&mut bytes);
384        bytes
385            .into_iter()
386            .map(|b| ALPHABET[(b as usize) % ALPHABET.len()] as char)
387            .collect()
388    }
389
390    /// Compute a domain-separated hex-encoded HMAC-SHA256 signature over `"slabs:v1:{domain}\0{payload}"`.
391    pub fn sign_with_domain(&self, domain: &str, payload: &str) -> String {
392        let mut mac = HmacSha256::new_from_slice(self.secret_key.as_bytes())
393            .expect("HMAC accepts keys of any size");
394        mac.update(b"slabs:v1:");
395        mac.update(domain.as_bytes());
396        mac.update(b"\0");
397        mac.update(payload.as_bytes());
398        hex::encode(mac.finalize().into_bytes())
399    }
400
401    /// Verify a domain-separated hex-encoded HMAC-SHA256 signature in constant time.
402    pub fn verify_with_domain(&self, domain: &str, payload: &str, signature_hex: &str) -> bool {
403        let Ok(sig_bytes) = hex::decode(signature_hex) else {
404            return false;
405        };
406        let Ok(mut mac) = HmacSha256::new_from_slice(self.secret_key.as_bytes()) else {
407            return false;
408        };
409        mac.update(b"slabs:v1:");
410        mac.update(domain.as_bytes());
411        mac.update(b"\0");
412        mac.update(payload.as_bytes());
413        mac.verify_slice(&sig_bytes).is_ok()
414    }
415
416    /// Compute a hex-encoded HMAC-SHA256 signature for `payload` under the `"raw"` domain.
417    pub fn sign(&self, payload: &str) -> String {
418        self.sign_with_domain("raw", payload)
419    }
420
421    /// Verify a hex-encoded HMAC-SHA256 signature for `payload` under the `"raw"` domain in constant time.
422    pub fn verify_signature(&self, payload: &str, signature_hex: &str) -> bool {
423        self.verify_with_domain("raw", payload, signature_hex)
424    }
425
426    /// Mint a purpose-bound, expiring HMAC-signed token carrying `payload`.
427    ///
428    /// Encodes `{"p": purpose, "exp": unix_ts, "d": payload}` as URL-safe base64 without padding
429    /// and appends `.<hex_hmac_sig>` signed under the `"token"` domain.
430    pub fn sign_token<T: Serialize>(
431        &self,
432        purpose: &str,
433        payload: &T,
434        ttl: StdDuration,
435    ) -> SlabResult<String> {
436        let ttl_secs = i64::try_from(ttl.as_secs())
437            .map_err(|_| SlabError::bad_request("token ttl exceeds supported range"))?;
438        let exp = Utc::now()
439            .timestamp()
440            .checked_add(ttl_secs)
441            .ok_or_else(|| SlabError::bad_request("token expiration timestamp overflow"))?;
442        let envelope = SignedTokenEnvelopeRef {
443            p: purpose,
444            exp,
445            d: payload,
446        };
447        let json = sqlx::types::Json(&envelope)
448            .encode_to_string()
449            .map_err(|e| SlabError::internal(format!("failed to serialize signed token: {e}")))?;
450        let encoded = URL_SAFE_NO_PAD.encode(json.as_bytes());
451        let sig = self.sign_with_domain("token", &encoded);
452        Ok(format!("{encoded}.{sig}"))
453    }
454
455    /// Verify a signed token produced by [`Auth::sign_token`], enforcing purpose and expiration.
456    ///
457    /// Returns a uniform HTTP `401 Unauthorized` (`"invalid or expired token"`) when the format,
458    /// HMAC signature, encoding, payload shape, purpose, or expiration check fails.
459    pub fn verify_token<T: DeserializeOwned>(&self, purpose: &str, token: &str) -> SlabResult<T> {
460        let invalid = || SlabError::unauthorized("invalid or expired token");
461
462        let Some((encoded, sig)) = token.split_once('.') else {
463            return Err(invalid());
464        };
465        if encoded.is_empty() || sig.is_empty() || sig.contains('.') {
466            return Err(invalid());
467        }
468        if !self.verify_with_domain("token", encoded, sig) {
469            return Err(invalid());
470        }
471        let raw = URL_SAFE_NO_PAD.decode(encoded).map_err(|_| invalid())?;
472        let envelope = sqlx::types::Json::<SignedTokenEnvelope<T>>::decode_from_bytes(&raw)
473            .map_err(|_| invalid())?
474            .0;
475        if envelope.p != purpose || envelope.exp <= Utc::now().timestamp() {
476            return Err(invalid());
477        }
478        Ok(envelope.d)
479    }
480
481    // ---- Browser Sessions ----
482
483    /// Insert a new browser session inside an existing SQLite transaction and return its cookie.
484    ///
485    /// Rejects `ttl_days` outside `1..=365`.
486    pub async fn create_session_in_tx(
487        &self,
488        tx: &mut Transaction<'_, Sqlite>,
489        user_id: &str,
490        role: &str,
491        ttl_days: i64,
492    ) -> SlabResult<(Session, Cookie<'static>)> {
493        if !(1..=365).contains(&ttl_days) {
494            return Err(SlabError::bad_request(
495                "session ttl_days must be between 1 and 365",
496            ));
497        }
498
499        let session_id = id::new("ses");
500        let raw_token = self.generate_token();
501        let token_hash = self.hash_token(&raw_token);
502        let now = Utc::now();
503        let expires = now
504            .checked_add_signed(Duration::days(ttl_days))
505            .ok_or_else(|| SlabError::bad_request("session expiration timestamp overflow"))?;
506        let now_str = utc_timestamp(now);
507        let expires_str = utc_timestamp(expires);
508
509        sqlx::query(
510            "INSERT INTO slabs_sessions (id, user_id, role, token_hash, expires_at, created_at)
511             VALUES (?, ?, ?, ?, ?, ?)",
512        )
513        .bind(&session_id)
514        .bind(user_id)
515        .bind(role)
516        .bind(&token_hash)
517        .bind(&expires_str)
518        .bind(&now_str)
519        .execute(&mut **tx)
520        .await?;
521
522        let cookie = self.build_session_cookie_with_ttl(raw_token, ttl_days);
523        let session = Session {
524            id: session_id,
525            user_id: user_id.to_string(),
526            role: role.to_string(),
527            expires_at: expires_str,
528            created_at: now_str,
529        };
530        Ok((session, cookie))
531    }
532
533    /// Create and persist a new browser session in its own transaction and return its cookie.
534    pub async fn create_session(
535        &self,
536        user_id: &str,
537        role: &str,
538        ttl_days: i64,
539    ) -> SlabResult<(Session, Cookie<'static>)> {
540        let mut tx = self.db()?.begin().await?;
541        let res = self
542            .create_session_in_tx(&mut tx, user_id, role, ttl_days)
543            .await?;
544        tx.commit().await?;
545        Ok(res)
546    }
547
548    /// Atomically revoke any existing session cookie in `jar` (checking both `__Host-slabs_session`
549    /// and `slabs_session`) and create a new session inside an open `SQLite` transaction.
550    ///
551    /// Use this on sign-in, sign-up, password reset, or role changes to prevent session fixation
552    /// while keeping session rotation atomic with surrounding domain writes.
553    pub async fn rotate_session_in_tx(
554        &self,
555        tx: &mut Transaction<'_, Sqlite>,
556        jar: &CookieJar,
557        user_id: &str,
558        role: &str,
559        ttl_days: i64,
560    ) -> SlabResult<(Session, Cookie<'static>)> {
561        if !(1..=365).contains(&ttl_days) {
562            return Err(SlabError::bad_request(
563                "session ttl_days must be between 1 and 365",
564            ));
565        }
566
567        for cookie_name in [HOST_SESSION_COOKIE_NAME, SESSION_COOKIE_NAME] {
568            if let Some(cookie) = jar.get(cookie_name) {
569                let old_raw = cookie.value();
570                if !old_raw.is_empty() {
571                    let old_hash = self.hash_token(old_raw);
572                    sqlx::query("DELETE FROM slabs_sessions WHERE token_hash = ?")
573                        .bind(&old_hash)
574                        .execute(&mut **tx)
575                        .await?;
576                }
577            }
578        }
579
580        self.create_session_in_tx(tx, user_id, role, ttl_days).await
581    }
582
583    /// Atomically revoke an existing session token (if present) and create a new session in a single transaction.
584    ///
585    /// Use this on authentication or privilege changes to prevent session fixation.
586    pub async fn rotate_session(
587        &self,
588        old_raw_token: &str,
589        user_id: &str,
590        role: &str,
591        ttl_days: i64,
592    ) -> SlabResult<(Session, Cookie<'static>)> {
593        let mut tx = self.db()?.begin().await?;
594        if !old_raw_token.is_empty() {
595            let old_hash = self.hash_token(old_raw_token);
596            sqlx::query("DELETE FROM slabs_sessions WHERE token_hash = ?")
597                .bind(&old_hash)
598                .execute(&mut *tx)
599                .await?;
600        }
601        let res = self
602            .create_session_in_tx(&mut tx, user_id, role, ttl_days)
603            .await?;
604        tx.commit().await?;
605        Ok(res)
606    }
607
608    /// Look up the active, unexpired [`Session`] for the request's cookie jar, if present.
609    pub async fn optional_session(&self, jar: &CookieJar) -> SlabResult<Option<Session>> {
610        let Some(cookie) = jar.get(self.session_cookie_name()) else {
611            return Ok(None);
612        };
613        let token_hash = self.hash_token(cookie.value());
614        let now_str = utc_timestamp(Utc::now());
615
616        let session: Option<Session> = sqlx::query_as(
617            "SELECT id, user_id, role, expires_at, created_at
618             FROM slabs_sessions
619             WHERE token_hash = ? AND expires_at > ?",
620        )
621        .bind(&token_hash)
622        .bind(&now_str)
623        .fetch_optional(self.db()?.reader())
624        .await?;
625
626        Ok(session)
627    }
628
629    /// Require a valid browser session from `jar`, failing with HTTP 401 if unauthenticated.
630    pub async fn require_session(&self, jar: &CookieJar) -> SlabResult<Session> {
631        self.optional_session(jar)
632            .await?
633            .ok_or_else(|| SlabError::unauthorized("authentication required"))
634    }
635
636    /// Require a valid browser session with the `"admin"` role, failing with HTTP 401 or 403 otherwise.
637    pub async fn require_admin(&self, jar: &CookieJar) -> SlabResult<Session> {
638        let session = self.require_session(jar).await?;
639        if session.role != "admin" {
640            return Err(SlabError::forbidden("administrator role required"));
641        }
642        Ok(session)
643    }
644
645    /// Delete the current session from the database (if present) and return a removal cookie.
646    pub async fn destroy_session(&self, jar: &CookieJar) -> SlabResult<Cookie<'static>> {
647        if let Some(cookie) = jar.get(self.session_cookie_name()) {
648            let token_hash = self.hash_token(cookie.value());
649            sqlx::query("DELETE FROM slabs_sessions WHERE token_hash = ?")
650                .bind(&token_hash)
651                .execute(self.db()?.pool())
652                .await?;
653        }
654        Ok(self.clear_session_cookie())
655    }
656
657    /// Delete all active browser sessions belonging to `user_id` and return the number of sessions removed.
658    pub async fn destroy_user_sessions(&self, user_id: &str) -> SlabResult<u64> {
659        let res = sqlx::query("DELETE FROM slabs_sessions WHERE user_id = ?")
660            .bind(user_id)
661            .execute(self.db()?.pool())
662            .await?;
663        Ok(res.rows_affected())
664    }
665
666    /// Delete all browser sessions (`slabs_sessions`) and personal access tokens
667    /// (`slabs_access_tokens`) belonging to `user_id` inside an open `SQLite` transaction.
668    ///
669    /// Returns the total number of revoked session and access-token rows. Use this on password
670    /// changes, account deactivation, or privilege revocation so every active credential is
671    /// invalidated atomically with the user update.
672    pub async fn revoke_all_for_user_in_tx(
673        &self,
674        tx: &mut Transaction<'_, Sqlite>,
675        user_id: &str,
676    ) -> SlabResult<u64> {
677        let sessions = sqlx::query("DELETE FROM slabs_sessions WHERE user_id = ?")
678            .bind(user_id)
679            .execute(&mut **tx)
680            .await?;
681        let tokens = sqlx::query("DELETE FROM slabs_access_tokens WHERE user_id = ?")
682            .bind(user_id)
683            .execute(&mut **tx)
684            .await?;
685        Ok(sessions
686            .rows_affected()
687            .saturating_add(tokens.rows_affected()))
688    }
689
690    /// Delete all expired session rows from `slabs_sessions` and return the number of rows removed.
691    pub async fn cleanup_expired_sessions(&self) -> SlabResult<u64> {
692        let now_str = utc_timestamp(Utc::now());
693        let res = sqlx::query("DELETE FROM slabs_sessions WHERE expires_at <= ?")
694            .bind(&now_str)
695            .execute(self.db()?.pool())
696            .await?;
697        Ok(res.rows_affected())
698    }
699
700    /// Build an `HttpOnly`, `SameSite=Lax` session cookie carrying `raw_token` with an explicit `Max-Age` in days (clamped to `1..=365`).
701    pub fn build_session_cookie_with_ttl(
702        &self,
703        raw_token: impl Into<String>,
704        ttl_days: i64,
705    ) -> Cookie<'static> {
706        let clamped_days = ttl_days.clamp(1, 365);
707        Cookie::build((self.session_cookie_name(), raw_token.into()))
708            .path("/")
709            .http_only(true)
710            .same_site(SameSite::Lax)
711            .secure(self.cookie_secure)
712            .max_age(time::Duration::days(clamped_days))
713            .build()
714    }
715
716    /// Build an `HttpOnly`, `SameSite=Lax` session cookie carrying `raw_token` with a default 30-day `Max-Age`.
717    pub fn build_session_cookie(&self, raw_token: impl Into<String>) -> Cookie<'static> {
718        self.build_session_cookie_with_ttl(raw_token, DEFAULT_SESSION_TTL_DAYS)
719    }
720
721    /// Build an expired removal cookie that clears the browser session cookie.
722    pub fn clear_session_cookie(&self) -> Cookie<'static> {
723        let mut cookie = Cookie::build((self.session_cookie_name(), ""))
724            .path("/")
725            .http_only(true)
726            .same_site(SameSite::Lax)
727            .secure(self.cookie_secure)
728            .build();
729        cookie.make_removal();
730        cookie
731    }
732
733    // ---- Passwordless Magic Links (extracted from Fizzy) ----
734
735    fn hash_magic_link_code(&self, email_lower: &str, purpose: &str, code: &str) -> String {
736        self.sign_with_domain("magic_link", &format!("{email_lower}\0{purpose}\0{code}"))
737    }
738
739    /// Issue an expiring 6-character magic link code bound to `(email, purpose)` and store its keyed HMAC digest in `slabs_magic_links`.
740    ///
741    /// Deletes any prior pending codes for `(email, purpose)` in the same transaction.
742    /// Rejects `ttl_minutes` outside `1..=1440`.
743    pub async fn issue_magic_link(
744        &self,
745        email: &str,
746        purpose: &str,
747        ttl_minutes: i64,
748    ) -> SlabResult<MagicLinkIssued> {
749        if !(1..=1440).contains(&ttl_minutes) {
750            return Err(SlabError::bad_request(
751                "magic link ttl_minutes must be between 1 and 1440",
752            ));
753        }
754
755        let link_id = id::new("mlk");
756        let code = self.generate_short_code(6);
757        let email = email.trim().to_lowercase();
758        let code_hash = self.hash_magic_link_code(&email, purpose, &code);
759        let now = Utc::now();
760        let expires = now
761            .checked_add_signed(Duration::minutes(ttl_minutes))
762            .ok_or_else(|| SlabError::bad_request("magic link expiration timestamp overflow"))?;
763        let expires_at = utc_timestamp(expires);
764        let created_at = utc_timestamp(now);
765
766        let mut tx = self.db()?.begin().await?;
767        sqlx::query("DELETE FROM slabs_magic_links WHERE email = ? AND purpose = ?")
768            .bind(&email)
769            .bind(purpose)
770            .execute(&mut *tx)
771            .await?;
772
773        sqlx::query(
774            "INSERT INTO slabs_magic_links (id, email, purpose, code_hash, expires_at, created_at)
775             VALUES (?, ?, ?, ?, ?, ?)",
776        )
777        .bind(&link_id)
778        .bind(&email)
779        .bind(purpose)
780        .bind(&code_hash)
781        .bind(&expires_at)
782        .bind(&created_at)
783        .execute(&mut *tx)
784        .await?;
785        tx.commit().await?;
786
787        Ok(MagicLinkIssued {
788            id: link_id,
789            email,
790            purpose: purpose.to_string(),
791            code,
792            expires_at,
793        })
794    }
795
796    fn record_magic_link_failure(&self, fail_key: &str) -> u32 {
797        let now = Instant::now();
798        let mut guard = self
799            .magic_link_failures
800            .lock()
801            .expect("magic link failure tracker mutex poisoned");
802        if guard.len() > 10_000 {
803            guard.retain(|_, (_, first_failed)| {
804                now.saturating_duration_since(*first_failed) < MAGIC_LINK_LOCKOUT_WINDOW
805            });
806        }
807        let entry = guard.entry(fail_key.to_string()).or_insert((0, now));
808        if now.saturating_duration_since(entry.1) >= MAGIC_LINK_LOCKOUT_WINDOW {
809            entry.0 = 0;
810            entry.1 = now;
811        }
812        entry.0 = entry.0.saturating_add(1);
813        entry.0
814    }
815
816    fn is_magic_link_locked_out(&self, fail_key: &str) -> bool {
817        let now = Instant::now();
818        let mut guard = self
819            .magic_link_failures
820            .lock()
821            .expect("magic link failure tracker mutex poisoned");
822        if let Some((count, first_failed)) = guard.get(fail_key).copied() {
823            if now.saturating_duration_since(first_failed) >= MAGIC_LINK_LOCKOUT_WINDOW {
824                guard.remove(fail_key);
825                return false;
826            }
827            return count >= MAGIC_LINK_MAX_ATTEMPTS;
828        }
829        false
830    }
831
832    fn clear_magic_link_failures(&self, fail_key: &str) {
833        let mut guard = self
834            .magic_link_failures
835            .lock()
836            .expect("magic link failure tracker mutex poisoned");
837        guard.remove(fail_key);
838    }
839
840    /// Atomically consume a valid, unexpired magic link code bound to `email` and `purpose`.
841    ///
842    /// Returns `Ok(Some(MagicLinkConsumed))` on success, or `Ok(None)` if the code is invalid,
843    /// expired, mismatched, or locked out. After 5 failed attempts within 15 minutes for a given
844    /// `(email, purpose)`, any pending magic links for that pair are deleted.
845    pub async fn consume_magic_link(
846        &self,
847        email: &str,
848        purpose: &str,
849        raw_code: &str,
850    ) -> SlabResult<Option<MagicLinkConsumed>> {
851        let email_lower = email.trim().to_lowercase();
852        let fail_key = format!("{email_lower}\0{purpose}");
853
854        if self.is_magic_link_locked_out(&fail_key) {
855            sqlx::query("DELETE FROM slabs_magic_links WHERE email = ? AND purpose = ?")
856                .bind(&email_lower)
857                .bind(purpose)
858                .execute(self.db()?.pool())
859                .await?;
860            return Ok(None);
861        }
862
863        let sanitized: String = raw_code
864            .chars()
865            .filter(char::is_ascii_alphanumeric)
866            .map(|c| c.to_ascii_uppercase())
867            .collect();
868
869        if sanitized.is_empty() {
870            if self.record_magic_link_failure(&fail_key) >= MAGIC_LINK_MAX_ATTEMPTS {
871                sqlx::query("DELETE FROM slabs_magic_links WHERE email = ? AND purpose = ?")
872                    .bind(&email_lower)
873                    .bind(purpose)
874                    .execute(self.db()?.pool())
875                    .await?;
876            }
877            return Ok(None);
878        }
879
880        let code_hash = self.hash_magic_link_code(&email_lower, purpose, &sanitized);
881        let now_str = utc_timestamp(Utc::now());
882
883        let consumed: Option<(String, String, String)> = sqlx::query_as(
884            "DELETE FROM slabs_magic_links
885             WHERE email = ? AND purpose = ? AND code_hash = ? AND expires_at > ?
886             RETURNING id, email, purpose",
887        )
888        .bind(&email_lower)
889        .bind(purpose)
890        .bind(&code_hash)
891        .bind(&now_str)
892        .fetch_optional(self.db()?.pool())
893        .await?;
894
895        let Some((id, email, purpose)) = consumed else {
896            if self.record_magic_link_failure(&fail_key) >= MAGIC_LINK_MAX_ATTEMPTS {
897                sqlx::query("DELETE FROM slabs_magic_links WHERE email = ? AND purpose = ?")
898                    .bind(&email_lower)
899                    .bind(purpose)
900                    .execute(self.db()?.pool())
901                    .await?;
902            }
903            return Ok(None);
904        };
905
906        self.clear_magic_link_failures(&fail_key);
907        Ok(Some(MagicLinkConsumed { id, email, purpose }))
908    }
909
910    /// Delete all expired magic link rows and return the number of rows removed.
911    pub async fn cleanup_expired_magic_links(&self) -> SlabResult<u64> {
912        let now_str = utc_timestamp(Utc::now());
913        let res = sqlx::query("DELETE FROM slabs_magic_links WHERE expires_at <= ?")
914            .bind(&now_str)
915            .execute(self.db()?.pool())
916            .await?;
917        Ok(res.rows_affected())
918    }
919
920    // ---- Personal Access Tokens / Bearer Auth (extracted from Fizzy for CLIs & Agents) ----
921
922    /// Issue a personal access token prefixed with `slb_` and optional expiration in days.
923    ///
924    /// Validates that `permission` is `"read"` or `"write"`, and stores only the SHA-256 hex digest.
925    pub async fn issue_access_token_with_expiry(
926        &self,
927        user_id: &str,
928        role: &str,
929        description: &str,
930        permission: &str,
931        ttl_days: Option<i64>,
932    ) -> SlabResult<AccessTokenIssued> {
933        if permission != "read" && permission != "write" {
934            return Err(SlabError::validation(
935                "permission",
936                "must be \"read\" or \"write\"",
937            ));
938        }
939
940        let now = Utc::now();
941        let expires_at = match ttl_days {
942            Some(days) => {
943                if !(1..=3650).contains(&days) {
944                    return Err(SlabError::bad_request(
945                        "access token ttl_days must be between 1 and 3650",
946                    ));
947                }
948                let exp = now
949                    .checked_add_signed(Duration::days(days))
950                    .ok_or_else(|| {
951                        SlabError::bad_request("access token expiration timestamp overflow")
952                    })?;
953                Some(utc_timestamp(exp))
954            }
955            None => None,
956        };
957
958        let token_id = id::new("pat");
959        let raw_token = format!("slb_{}", self.generate_token());
960        let token_hash = self.hash_token(&raw_token);
961        let created_at = utc_timestamp(now);
962
963        sqlx::query(
964            "INSERT INTO slabs_access_tokens (id, user_id, role, description, permission, token_hash, expires_at, created_at)
965             VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
966        )
967        .bind(&token_id)
968        .bind(user_id)
969        .bind(role)
970        .bind(description)
971        .bind(permission)
972        .bind(&token_hash)
973        .bind(&expires_at)
974        .bind(&created_at)
975        .execute(self.db()?.pool())
976        .await?;
977
978        Ok(AccessTokenIssued {
979            id: token_id,
980            user_id: user_id.to_string(),
981            description: description.to_string(),
982            permission: permission.to_string(),
983            token: raw_token,
984        })
985    }
986
987    /// Issue a non-expiring personal access token prefixed with `slb_` and store its SHA-256 hash in `slabs_access_tokens`.
988    ///
989    /// Validates that `permission` is `"read"` or `"write"`.
990    pub async fn issue_access_token(
991        &self,
992        user_id: &str,
993        role: &str,
994        description: &str,
995        permission: &str,
996    ) -> SlabResult<AccessTokenIssued> {
997        self.issue_access_token_with_expiry(user_id, role, description, permission, None)
998            .await
999    }
1000
1001    /// Revoke a personal access token owned by `user_id`, returning `Ok(true)` if a row was deleted.
1002    pub async fn revoke_access_token(&self, token_id: &str, user_id: &str) -> SlabResult<bool> {
1003        let res = sqlx::query("DELETE FROM slabs_access_tokens WHERE id = ? AND user_id = ?")
1004            .bind(token_id)
1005            .bind(user_id)
1006            .execute(self.db()?.pool())
1007            .await?;
1008        Ok(res.rows_affected() > 0)
1009    }
1010
1011    /// Authenticate via `Authorization: Bearer <token>` or the session cookie.
1012    ///
1013    /// When a `Bearer` header is present, this method validates only that token on the read pool,
1014    /// debounces `last_used_at` writes to at most once every 5 minutes, and returns `Ok(None)` if invalid.
1015    pub async fn optional_auth(
1016        &self,
1017        jar: &CookieJar,
1018        headers: &HeaderMap,
1019    ) -> SlabResult<Option<Principal>> {
1020        if let Some(auth_hdr) = headers
1021            .get(header::AUTHORIZATION)
1022            .and_then(|v| v.to_str().ok())
1023        {
1024            if let Some(raw_token) = auth_hdr
1025                .strip_prefix("Bearer ")
1026                .or_else(|| auth_hdr.strip_prefix("bearer "))
1027            {
1028                let token_hash = self.hash_token(raw_token.trim());
1029                let now = Utc::now();
1030                let now_str = utc_timestamp(now);
1031
1032                let db = self.db()?;
1033                let row: Option<(String, String, String, String, Option<String>)> = sqlx::query_as(
1034                    "SELECT id, user_id, role, permission, last_used_at
1035                     FROM slabs_access_tokens
1036                     WHERE token_hash = ? AND (expires_at IS NULL OR expires_at > ?)",
1037                )
1038                .bind(&token_hash)
1039                .bind(&now_str)
1040                .fetch_optional(db.reader())
1041                .await?;
1042
1043                if let Some((token_id, user_id, role, permission, last_used_at)) = row {
1044                    let should_update_last_used = match last_used_at.as_deref() {
1045                        None => true,
1046                        Some(ts) => DateTime::parse_from_rfc3339(ts).map_or(true, |parsed| {
1047                            now.signed_duration_since(parsed.with_timezone(&Utc))
1048                                .num_seconds()
1049                                >= ACCESS_TOKEN_LAST_USED_DEBOUNCE_SECS
1050                        }),
1051                    };
1052
1053                    if should_update_last_used {
1054                        let _ = sqlx::query(
1055                            "UPDATE slabs_access_tokens SET last_used_at = ? WHERE id = ?",
1056                        )
1057                        .bind(&now_str)
1058                        .bind(&token_id)
1059                        .execute(db.pool())
1060                        .await;
1061                    }
1062
1063                    return Ok(Some(Principal {
1064                        user_id,
1065                        role,
1066                        auth_kind: "bearer".to_string(),
1067                        permission,
1068                    }));
1069                }
1070                return Ok(None);
1071            }
1072        }
1073
1074        if let Some(session) = self.optional_session(jar).await? {
1075            return Ok(Some(Principal {
1076                user_id: session.user_id,
1077                role: session.role,
1078                auth_kind: "session".to_string(),
1079                permission: "write".to_string(),
1080            }));
1081        }
1082
1083        Ok(None)
1084    }
1085
1086    /// Require authentication via either session cookie or `Authorization: Bearer` token.
1087    pub async fn require_auth(
1088        &self,
1089        jar: &CookieJar,
1090        headers: &HeaderMap,
1091    ) -> SlabResult<Principal> {
1092        self.optional_auth(jar, headers).await?.ok_or_else(|| {
1093            SlabError::unauthorized("authentication required (session cookie or Bearer token)")
1094        })
1095    }
1096
1097    /// Require an authenticated [`Principal`] with `"write"` permission.
1098    pub async fn require_write_auth(
1099        &self,
1100        jar: &CookieJar,
1101        headers: &HeaderMap,
1102    ) -> SlabResult<Principal> {
1103        let principal = self.require_auth(jar, headers).await?;
1104        if principal.permission != "write" {
1105            return Err(SlabError::forbidden(
1106                "access token does not have write permission",
1107            ));
1108        }
1109        Ok(principal)
1110    }
1111}
1112
1113#[cfg(test)]
1114mod tests {
1115    use super::*;
1116
1117    #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1118    struct InvitePayload {
1119        user_id: String,
1120        org_id: String,
1121    }
1122
1123    fn test_auth() -> Auth {
1124        Auth::for_signing("unit-test-secret-key-for-signed-tokens", false)
1125    }
1126
1127    async fn db_auth(cookie_secure: bool) -> (Db, Auth) {
1128        let db = Db::connect("sqlite::memory:").await.unwrap();
1129        db.init_system_tables().await.unwrap();
1130        let auth = Auth::new(
1131            db.clone(),
1132            "unit-test-secret-key-for-db-auth",
1133            cookie_secure,
1134        );
1135        (db, auth)
1136    }
1137
1138    #[tokio::test]
1139    async fn async_argon2id_hashes_verifies_and_enforces_limits() {
1140        let auth = test_auth();
1141        let hash = auth.hash_password("correct-horse-battery").await.unwrap();
1142        assert!(hash.starts_with("$argon2id$"));
1143
1144        assert!(auth
1145            .verify_password("correct-horse-battery", &hash)
1146            .await
1147            .unwrap());
1148        assert!(!auth.verify_password("wrong-password", &hash).await.unwrap());
1149
1150        // Constant-time verify handles both Some and None without erroring.
1151        assert!(auth
1152            .verify_password_constant_time("correct-horse-battery", Some(&hash))
1153            .await
1154            .unwrap());
1155        assert!(!auth
1156            .verify_password_constant_time("correct-horse-battery", None)
1157            .await
1158            .unwrap());
1159
1160        // Non-Argon2id algorithm string must be rejected.
1161        let argon2i_hash = hash.replacen("$argon2id$", "$argon2i$", 1);
1162        assert!(!auth
1163            .verify_password("correct-horse-battery", &argon2i_hash)
1164            .await
1165            .unwrap());
1166
1167        // Passwords over 1024 bytes are rejected with 400 Bad Request.
1168        let oversized = "a".repeat(1025);
1169        assert_eq!(
1170            auth.hash_password(&oversized)
1171                .await
1172                .unwrap_err()
1173                .status_code(),
1174            http::StatusCode::BAD_REQUEST
1175        );
1176        assert_eq!(
1177            auth.verify_password(&oversized, &hash)
1178                .await
1179                .unwrap_err()
1180                .status_code(),
1181            http::StatusCode::BAD_REQUEST
1182        );
1183        assert_eq!(
1184            auth.verify_password_constant_time(&oversized, None)
1185                .await
1186                .unwrap_err()
1187                .status_code(),
1188            http::StatusCode::BAD_REQUEST
1189        );
1190    }
1191
1192    #[test]
1193    fn domain_separated_hmac_prevents_cross_domain_reuse() {
1194        let auth = test_auth();
1195        let raw_sig = auth.sign("payload");
1196        assert!(auth.verify_signature("payload", &raw_sig));
1197        assert!(auth.verify_with_domain("raw", "payload", &raw_sig));
1198        assert!(!auth.verify_with_domain("token", "payload", &raw_sig));
1199        assert!(!auth.verify_with_domain("magic_link", "payload", &raw_sig));
1200
1201        let token_sig = auth.sign_with_domain("token", "payload");
1202        assert_ne!(raw_sig, token_sig);
1203        assert!(auth.verify_with_domain("token", "payload", &token_sig));
1204        assert!(!auth.verify_signature("payload", &token_sig));
1205    }
1206
1207    #[test]
1208    fn sign_and_verify_token_roundtrip_and_uniform_errors() {
1209        let auth = test_auth();
1210        let payload = InvitePayload {
1211            user_id: "usr_01".to_string(),
1212            org_id: "org_42".to_string(),
1213        };
1214
1215        let token = auth
1216            .sign_token("invite", &payload, StdDuration::from_secs(300))
1217            .unwrap();
1218        let decoded: InvitePayload = auth.verify_token("invite", &token).unwrap();
1219        assert_eq!(decoded, payload);
1220
1221        // Wrong purpose, tampered signature, bad format, and expired tokens all return uniform 401.
1222        let wrong_purpose = auth
1223            .verify_token::<InvitePayload>("other", &token)
1224            .unwrap_err();
1225        let (encoded, sig) = token.split_once('.').unwrap();
1226        let flipped = if sig.starts_with('a') { 'b' } else { 'a' };
1227        let tampered_tok = format!("{encoded}.{flipped}{}", &sig[1..]);
1228        let tampered = auth
1229            .verify_token::<InvitePayload>("invite", &tampered_tok)
1230            .unwrap_err();
1231        let bad_fmt = auth
1232            .verify_token::<InvitePayload>("invite", "not-a-token")
1233            .unwrap_err();
1234        let expired_tok = auth
1235            .sign_token("invite", &payload, StdDuration::ZERO)
1236            .unwrap();
1237        let expired = auth
1238            .verify_token::<InvitePayload>("invite", &expired_tok)
1239            .unwrap_err();
1240
1241        for err in [wrong_purpose, tampered, bad_fmt, expired] {
1242            assert_eq!(err.status_code(), http::StatusCode::UNAUTHORIZED);
1243            assert_eq!(err.to_string(), "unauthorized: invalid or expired token");
1244        }
1245    }
1246
1247    #[tokio::test]
1248    async fn session_cookie_prefix_rotation_and_cleanup() {
1249        let (_db, secure_auth) = db_auth(true).await;
1250        assert_eq!(secure_auth.session_cookie_name(), "__Host-slabs_session");
1251
1252        let (ses1, cookie1) = secure_auth
1253            .create_session("usr_1", "member", 7)
1254            .await
1255            .unwrap();
1256        assert_eq!(cookie1.name(), "__Host-slabs_session");
1257        assert_eq!(cookie1.secure(), Some(true));
1258        assert_eq!(cookie1.max_age(), Some(time::Duration::days(7)));
1259
1260        let jar1 = CookieJar::new().add(cookie1.clone());
1261        let fetched = secure_auth.optional_session(&jar1).await.unwrap().unwrap();
1262        assert_eq!(fetched.id, ses1.id);
1263
1264        // Rotate invalidates old session and creates a new one atomically.
1265        let (ses2, cookie2) = secure_auth
1266            .rotate_session(cookie1.value(), "usr_1", "admin", 14)
1267            .await
1268            .unwrap();
1269        assert_ne!(ses1.id, ses2.id);
1270        assert!(secure_auth.optional_session(&jar1).await.unwrap().is_none());
1271
1272        let jar2 = CookieJar::new().add(cookie2);
1273        let fetched2 = secure_auth.optional_session(&jar2).await.unwrap().unwrap();
1274        assert_eq!(fetched2.role, "admin");
1275
1276        // Reject invalid TTLs.
1277        assert!(secure_auth
1278            .create_session("usr_1", "member", 0)
1279            .await
1280            .is_err());
1281        assert!(secure_auth
1282            .create_session("usr_1", "member", 366)
1283            .await
1284            .is_err());
1285
1286        // Destroy all sessions for user.
1287        let removed = secure_auth.destroy_user_sessions("usr_1").await.unwrap();
1288        assert_eq!(removed, 1);
1289        assert!(secure_auth.optional_session(&jar2).await.unwrap().is_none());
1290    }
1291
1292    #[tokio::test]
1293    async fn magic_link_binds_email_purpose_and_locks_out_after_five_failures() {
1294        let (_db, auth) = db_auth(false).await;
1295        let issued = auth
1296            .issue_magic_link("Alice@Example.com", "sign_in", 15)
1297            .await
1298            .unwrap();
1299
1300        // Debug redacts the code.
1301        let dbg = format!("{issued:?}");
1302        assert!(!dbg.contains(&issued.code));
1303        assert!(dbg.contains("[REDACTED]"));
1304
1305        // Wrong email or wrong purpose fails to consume the valid code.
1306        assert!(auth
1307            .consume_magic_link("bob@example.com", "sign_in", &issued.code)
1308            .await
1309            .unwrap()
1310            .is_none());
1311        assert!(auth
1312            .consume_magic_link("alice@example.com", "reset_password", &issued.code)
1313            .await
1314            .unwrap()
1315            .is_none());
1316
1317        // 5 failed attempts for (alice@example.com, sign_in) lock out and delete the pending code.
1318        for _ in 0..5 {
1319            assert!(auth
1320                .consume_magic_link("alice@example.com", "sign_in", "ZZZZZZ")
1321                .await
1322                .unwrap()
1323                .is_none());
1324        }
1325        // Now even the real code is rejected because the lockout deleted it.
1326        assert!(auth
1327            .consume_magic_link("alice@example.com", "sign_in", &issued.code)
1328            .await
1329            .unwrap()
1330            .is_none());
1331
1332        // A separate email/purpose still succeeds when matching email, purpose, and code.
1333        let issued2 = auth
1334            .issue_magic_link("charlie@example.com", "sign_in", 15)
1335            .await
1336            .unwrap();
1337        let consumed = auth
1338            .consume_magic_link("CHARLIE@example.com", "sign_in", &issued2.code)
1339            .await
1340            .unwrap()
1341            .expect("valid code should consume");
1342        assert_eq!(consumed.email, "charlie@example.com");
1343        assert_eq!(consumed.purpose, "sign_in");
1344
1345        // Replaying the same code fails (single-use).
1346        assert!(auth
1347            .consume_magic_link("charlie@example.com", "sign_in", &issued2.code)
1348            .await
1349            .unwrap()
1350            .is_none());
1351    }
1352
1353    #[tokio::test]
1354    async fn access_token_validates_permission_expiry_revocation_and_debug_redaction() {
1355        let (_db, auth) = db_auth(false).await;
1356
1357        assert!(auth
1358            .issue_access_token("usr_1", "member", "bad", "admin")
1359            .await
1360            .is_err());
1361
1362        let issued = auth
1363            .issue_access_token_with_expiry("usr_1", "member", "cli", "read", Some(7))
1364            .await
1365            .unwrap();
1366        let dbg = format!("{issued:?}");
1367        assert!(!dbg.contains(&issued.token));
1368        assert!(dbg.contains("[REDACTED]"));
1369
1370        let mut headers = HeaderMap::new();
1371        headers.insert(
1372            header::AUTHORIZATION,
1373            format!("Bearer {}", issued.token).parse().unwrap(),
1374        );
1375        let jar = CookieJar::new();
1376        let principal = auth.optional_auth(&jar, &headers).await.unwrap().unwrap();
1377        assert_eq!(principal.user_id, "usr_1");
1378        assert_eq!(principal.permission, "read");
1379
1380        // Wrong owner cannot revoke token.
1381        assert!(!auth.revoke_access_token(&issued.id, "usr_2").await.unwrap());
1382        assert!(auth.revoke_access_token(&issued.id, "usr_1").await.unwrap());
1383        assert!(auth.optional_auth(&jar, &headers).await.unwrap().is_none());
1384    }
1385
1386    #[tokio::test]
1387    async fn rotate_session_in_tx_replaces_host_and_plain_cookies_atomically() {
1388        let (db, secure_auth) = db_auth(true).await;
1389        let plain_auth = Auth::new(db.clone(), "unit-test-secret-key-for-db-auth", false);
1390
1391        let (host_ses, host_cookie) = secure_auth
1392            .create_session("usr_1", "member", 7)
1393            .await
1394            .unwrap();
1395        let (plain_ses, plain_cookie) = plain_auth
1396            .create_session("usr_1", "member", 7)
1397            .await
1398            .unwrap();
1399
1400        let jar_both = CookieJar::new()
1401            .add(host_cookie.clone())
1402            .add(plain_cookie.clone());
1403
1404        // Rolled-back rotation keeps old sessions alive.
1405        let mut rollback_tx = db.begin().await.unwrap();
1406        let _ = secure_auth
1407            .rotate_session_in_tx(&mut rollback_tx, &jar_both, "usr_1", "admin", 14)
1408            .await
1409            .unwrap();
1410        rollback_tx.rollback().await.unwrap();
1411        assert!(secure_auth
1412            .optional_session(&CookieJar::new().add(host_cookie.clone()))
1413            .await
1414            .unwrap()
1415            .is_some());
1416        assert!(plain_auth
1417            .optional_session(&CookieJar::new().add(plain_cookie.clone()))
1418            .await
1419            .unwrap()
1420            .is_some());
1421
1422        // Committed rotation deletes both old cookies and activates the new session.
1423        let mut tx = db.begin().await.unwrap();
1424        let (new_ses, new_cookie) = secure_auth
1425            .rotate_session_in_tx(&mut tx, &jar_both, "usr_1", "admin", 14)
1426            .await
1427            .unwrap();
1428        tx.commit().await.unwrap();
1429
1430        assert_ne!(new_ses.id, host_ses.id);
1431        assert_ne!(new_ses.id, plain_ses.id);
1432        assert!(secure_auth
1433            .optional_session(&CookieJar::new().add(host_cookie))
1434            .await
1435            .unwrap()
1436            .is_none());
1437        assert!(plain_auth
1438            .optional_session(&CookieJar::new().add(plain_cookie))
1439            .await
1440            .unwrap()
1441            .is_none());
1442
1443        let new_jar = CookieJar::new().add(new_cookie);
1444        let active = secure_auth
1445            .optional_session(&new_jar)
1446            .await
1447            .unwrap()
1448            .unwrap();
1449        assert_eq!(active.id, new_ses.id);
1450        assert_eq!(active.role, "admin");
1451    }
1452
1453    #[tokio::test]
1454    async fn revoke_all_for_user_in_tx_deletes_sessions_and_access_tokens_only_for_target_user() {
1455        let (db, auth) = db_auth(false).await;
1456
1457        let (_, c1) = auth
1458            .create_session("usr_target", "member", 7)
1459            .await
1460            .unwrap();
1461        let (_, c2) = auth
1462            .create_session("usr_target", "member", 7)
1463            .await
1464            .unwrap();
1465        let pat = auth
1466            .issue_access_token("usr_target", "member", "cli", "write")
1467            .await
1468            .unwrap();
1469
1470        let (_, other_cookie) = auth.create_session("usr_other", "member", 7).await.unwrap();
1471        let other_pat = auth
1472            .issue_access_token("usr_other", "member", "cli", "write")
1473            .await
1474            .unwrap();
1475
1476        let mut tx = db.begin().await.unwrap();
1477        let revoked = auth
1478            .revoke_all_for_user_in_tx(&mut tx, "usr_target")
1479            .await
1480            .unwrap();
1481        tx.commit().await.unwrap();
1482        assert_eq!(revoked, 3);
1483
1484        // Target user's sessions and bearer tokens are all revoked.
1485        assert!(auth
1486            .optional_session(&CookieJar::new().add(c1))
1487            .await
1488            .unwrap()
1489            .is_none());
1490        assert!(auth
1491            .optional_session(&CookieJar::new().add(c2))
1492            .await
1493            .unwrap()
1494            .is_none());
1495        let mut target_headers = HeaderMap::new();
1496        target_headers.insert(
1497            header::AUTHORIZATION,
1498            format!("Bearer {}", pat.token).parse().unwrap(),
1499        );
1500        assert!(auth
1501            .optional_auth(&CookieJar::new(), &target_headers)
1502            .await
1503            .unwrap()
1504            .is_none());
1505
1506        // Other user's session and bearer token remain valid.
1507        assert!(auth
1508            .optional_session(&CookieJar::new().add(other_cookie))
1509            .await
1510            .unwrap()
1511            .is_some());
1512        let mut other_headers = HeaderMap::new();
1513        other_headers.insert(
1514            header::AUTHORIZATION,
1515            format!("Bearer {}", other_pat.token).parse().unwrap(),
1516        );
1517        assert!(auth
1518            .optional_auth(&CookieJar::new(), &other_headers)
1519            .await
1520            .unwrap()
1521            .is_some());
1522    }
1523}