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`], and [`SESSION_COOKIE_NAME`] (`"slabs_session"`).
7//! - Framework SQLite tables created by `slabs_db::Db::init_system_tables`:
8//!   - `slabs_sessions`: SHA-256 hashed browser session tokens, `user_id`, `role`, and `expires_at`.
9//!   - `slabs_magic_links`: SHA-256 hashed 6-character verification codes, normalized `email`, `purpose`, and `expires_at`.
10//!   - `slabs_access_tokens`: SHA-256 hashed `Authorization: Bearer` tokens, `user_id`, `role`, `permission`, `last_used_at`, and `expires_at`.
11//! - User accounts live in your application's own `users` table in your SQL migrations. This crate does not own a `users` table.
12//!
13//! # Agent invariants
14//!
15//! - Put an explicit auth guard on line 1 of every protected slab handler. Do not rely on hidden middleware or callbacks.
16//!   - [`Auth::require_session`]: requires a valid `slabs_session` cookie (HTTP 401 when missing or expired).
17//!   - [`Auth::require_admin`]: requires a valid session with `role == "admin"` (HTTP 401 or 403).
18//!   - [`Auth::require_auth`]: accepts either `Authorization: Bearer <token>` or a `slabs_session` cookie (HTTP 401).
19//!   - [`Auth::require_write_auth`]: requires [`Auth::require_auth`] with `permission == "write"` (HTTP 403 for `"read"` tokens).
20//! - Hash passwords with [`Auth::hash_password`] (`Argon2id` with a random OS salt) and verify with [`Auth::verify_password`].
21//! - Magic links generate 6-character alphanumeric codes without ambiguous characters (`0`, `O`, `1`, `I`). [`Auth::consume_magic_link`] strips non-alphanumeric characters, uppercases the input, hashes with SHA-256, and runs `DELETE ... RETURNING` so every code is single-use.
22//! - 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.
23//! - 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.
24//! - Use [`Auth::create_session_in_tx`] when creating a user and a browser session inside one SQLite transaction.
25//!
26//! # Example
27//!
28//! ```rust,no_run
29//! use axum_extra::extract::CookieJar;
30//! use http::HeaderMap;
31//! use slabs_auth::Auth;
32//! use slabs_core::SlabResult;
33//!
34//! async fn protected_handler(auth: &Auth, jar: &CookieJar, headers: &HeaderMap) -> SlabResult<()> {
35//!     // Line 1 guard for browser-only endpoints:
36//!     let session = auth.require_session(jar).await?;
37//!
38//!     // Or accept either a session cookie or a write-scoped Bearer token:
39//!     let principal = auth.require_write_auth(jar, headers).await?;
40//!
41//!     let _ = (session.user_id, principal.user_id);
42//!     Ok(())
43//! }
44//! ```
45
46use argon2::{
47    password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString},
48    Argon2,
49};
50use axum_extra::extract::cookie::{Cookie, CookieJar, SameSite};
51use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
52use chrono::{Duration, Utc};
53use hmac::{Hmac, Mac};
54use http::{header, HeaderMap};
55use rand_core::{OsRng, RngCore};
56use serde::{de::DeserializeOwned, Deserialize, Serialize};
57use sha2::{Digest, Sha256};
58use slabs_core::{id, SlabError, SlabResult};
59use slabs_db::Db;
60use sqlx::{Sqlite, Transaction};
61use std::fmt;
62
63type HmacSha256 = Hmac<Sha256>;
64
65#[derive(Serialize)]
66struct SignedTokenEnvelopeRef<'a, T: ?Sized> {
67    p: &'a str,
68    exp: i64,
69    d: &'a T,
70}
71
72#[derive(Deserialize)]
73struct SignedTokenEnvelope<T> {
74    p: String,
75    exp: i64,
76    d: T,
77}
78
79/// Cookie name used to store browser session tokens.
80pub const SESSION_COOKIE_NAME: &str = "slabs_session";
81
82/// Active browser session persisted in the `slabs_sessions` table.
83#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
84pub struct Session {
85    /// Prefixed session identifier (`ses_...`).
86    pub id: String,
87    /// Authenticated user's identifier.
88    pub user_id: String,
89    /// Role assigned to the user when the session was created (e.g. `"member"`, `"admin"`).
90    pub role: String,
91    /// RFC 3339 timestamp after which the session is no longer valid.
92    pub expires_at: String,
93    /// RFC 3339 timestamp when the session was created.
94    pub created_at: String,
95}
96
97/// Authenticated actor resolved from either a browser session cookie or an `Authorization: Bearer` token.
98#[derive(Debug, Clone, Serialize, Deserialize)]
99pub struct Principal {
100    /// Authenticated user's identifier.
101    pub user_id: String,
102    /// Role associated with the authenticated user.
103    pub role: String,
104    /// Authentication mechanism used (`"session"` or `"bearer"`).
105    pub auth_kind: String,
106    /// Granted permission level (`"write"` or `"read"`).
107    pub permission: String,
108}
109
110/// Result returned when a new one-time magic link code is issued.
111#[derive(Debug, Clone, Serialize, Deserialize)]
112pub struct MagicLinkIssued {
113    /// Prefixed magic-link record identifier (`mlk_...`).
114    pub id: String,
115    /// Normalized lowercase email address the code was issued for.
116    pub email: String,
117    /// Application-defined purpose for the magic link (e.g. `"sign_in"`).
118    pub purpose: String,
119    /// Plaintext one-time verification code to deliver to the user.
120    pub code: String,
121    /// RFC 3339 timestamp when the code expires.
122    pub expires_at: String,
123}
124
125/// Verified metadata returned after atomically consuming a magic link code.
126#[derive(Debug, Clone, Serialize, Deserialize)]
127pub struct MagicLinkConsumed {
128    /// Prefixed magic-link record identifier (`mlk_...`).
129    pub id: String,
130    /// Normalized email address associated with the consumed code.
131    pub email: String,
132    /// Application-defined purpose associated with the consumed code.
133    pub purpose: String,
134}
135
136/// Result returned when a new personal access token is issued.
137#[derive(Debug, Clone, Serialize, Deserialize)]
138pub struct AccessTokenIssued {
139    /// Prefixed access-token record identifier (`pat_...`).
140    pub id: String,
141    /// Owner user identifier.
142    pub user_id: String,
143    /// Human-readable label describing the token's purpose.
144    pub description: String,
145    /// Permission scope granted to the token (`"write"` or `"read"`).
146    pub permission: String,
147    /// Plaintext bearer token shown once upon issuance (`slb_...`).
148    pub token: String,
149}
150
151/// Explicit authentication and session service backed by `slabs_sessions`, `slabs_magic_links`, and `slabs_access_tokens`.
152///
153/// Supports `Argon2id` password hashing, single-use 6-character magic links, `HttpOnly` browser
154/// session cookies, SHA-256 hashed `Authorization: Bearer` tokens, and HMAC-SHA256 signing.
155#[derive(Clone)]
156pub struct Auth {
157    db: Option<Db>,
158    secret_key: String,
159    cookie_secure: bool,
160}
161
162impl fmt::Debug for Auth {
163    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
164        f.debug_struct("Auth")
165            .field("db", &self.db)
166            .field("secret_key", &"<redacted>")
167            .field("cookie_secure", &self.cookie_secure)
168            .finish()
169    }
170}
171
172impl Auth {
173    /// Create an [`Auth`] service backed by `db`, using `secret_key` for HMAC signing and `cookie_secure` for the cookie `Secure` flag.
174    #[must_use]
175    pub fn new(db: Db, secret_key: impl Into<String>, cookie_secure: bool) -> Self {
176        Self {
177            db: Some(db),
178            secret_key: secret_key.into(),
179            cookie_secure,
180        }
181    }
182
183    /// Create a stateless [`Auth`] handle for HMAC signing, token verification, and signed cookies without a database connection.
184    #[must_use]
185    pub fn for_signing(secret_key: impl Into<String>, cookie_secure: bool) -> Self {
186        Self {
187            db: None,
188            secret_key: secret_key.into(),
189            cookie_secure,
190        }
191    }
192
193    /// Return whether cookies emitted by this [`Auth`] instance should set the `Secure` attribute.
194    #[must_use]
195    pub fn cookie_secure(&self) -> bool {
196        self.cookie_secure
197    }
198
199    fn db(&self) -> SlabResult<&Db> {
200        self.db
201            .as_ref()
202            .ok_or_else(|| SlabError::internal("Auth requires a database connection"))
203    }
204
205    /// Hash a plaintext password with `Argon2id` and a random OS salt, returning a PHC string.
206    pub fn hash_password(&self, password: &str) -> SlabResult<String> {
207        let salt = SaltString::generate(&mut OsRng);
208        Argon2::default()
209            .hash_password(password.as_bytes(), &salt)
210            .map(|h| h.to_string())
211            .map_err(|e| SlabError::internal(format!("password hashing failed: {e}")))
212    }
213
214    /// Verify a plaintext password against a stored `Argon2id` PHC hash string.
215    pub fn verify_password(&self, password: &str, password_hash: &str) -> bool {
216        let Ok(parsed) = PasswordHash::new(password_hash) else {
217            return false;
218        };
219        Argon2::default()
220            .verify_password(password.as_bytes(), &parsed)
221            .is_ok()
222    }
223
224    /// Compute the hex-encoded SHA-256 digest of a raw token or verification code.
225    pub fn hash_token(&self, raw_token: &str) -> String {
226        let mut hasher = Sha256::new();
227        hasher.update(raw_token.as_bytes());
228        hex::encode(hasher.finalize())
229    }
230
231    /// Generate a cryptographically random 32-byte hex-encoded token.
232    pub fn generate_token(&self) -> String {
233        let mut bytes = [0u8; 32];
234        OsRng.fill_bytes(&mut bytes);
235        hex::encode(bytes)
236    }
237
238    /// Generate a random alphanumeric code of length `len`, omitting ambiguous `0`, `O`, `1`, and `I` characters.
239    pub fn generate_short_code(&self, len: usize) -> String {
240        const ALPHABET: &[u8] = b"23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
241        let mut bytes = vec![0u8; len];
242        OsRng.fill_bytes(&mut bytes);
243        bytes
244            .into_iter()
245            .map(|b| ALPHABET[(b as usize) % ALPHABET.len()] as char)
246            .collect()
247    }
248
249    /// Compute a hex-encoded HMAC-SHA256 signature for `payload` using the configured secret key.
250    pub fn sign(&self, payload: &str) -> String {
251        let mut mac = HmacSha256::new_from_slice(self.secret_key.as_bytes())
252            .expect("HMAC accepts keys of any size");
253        mac.update(payload.as_bytes());
254        hex::encode(mac.finalize().into_bytes())
255    }
256
257    /// Verify a hex-encoded HMAC-SHA256 signature for `payload` in constant time.
258    pub fn verify_signature(&self, payload: &str, signature_hex: &str) -> bool {
259        let Ok(sig_bytes) = hex::decode(signature_hex) else {
260            return false;
261        };
262        let Ok(mut mac) = HmacSha256::new_from_slice(self.secret_key.as_bytes()) else {
263            return false;
264        };
265        mac.update(payload.as_bytes());
266        mac.verify_slice(&sig_bytes).is_ok()
267    }
268
269    /// Mint a purpose-bound, expiring HMAC-signed token carrying `payload`.
270    ///
271    /// Encodes `{"p": purpose, "exp": unix_ts, "d": payload}` as URL-safe base64 without padding
272    /// and appends `.<hex_hmac_sig>`.
273    pub fn sign_token<T: Serialize>(
274        &self,
275        purpose: &str,
276        payload: &T,
277        ttl: std::time::Duration,
278    ) -> SlabResult<String> {
279        let ttl_secs = i64::try_from(ttl.as_secs())
280            .map_err(|_| SlabError::bad_request("token ttl exceeds supported range"))?;
281        let exp = Utc::now()
282            .timestamp()
283            .checked_add(ttl_secs)
284            .ok_or_else(|| SlabError::bad_request("token expiration timestamp overflow"))?;
285        let envelope = SignedTokenEnvelopeRef {
286            p: purpose,
287            exp,
288            d: payload,
289        };
290        let json = sqlx::types::Json(&envelope)
291            .encode_to_string()
292            .map_err(|e| SlabError::internal(format!("failed to serialize signed token: {e}")))?;
293        let encoded = URL_SAFE_NO_PAD.encode(json.as_bytes());
294        let sig = self.sign(&encoded);
295        Ok(format!("{encoded}.{sig}"))
296    }
297
298    /// Verify a signed token produced by [`Auth::sign_token`], enforcing purpose and expiration.
299    ///
300    /// Returns HTTP `401 Unauthorized` when the format, HMAC signature, encoding, payload shape,
301    /// purpose, or expiration check fails.
302    pub fn verify_token<T: DeserializeOwned>(&self, purpose: &str, token: &str) -> SlabResult<T> {
303        let Some((encoded, sig)) = token.split_once('.') else {
304            return Err(SlabError::unauthorized("invalid token format"));
305        };
306        if encoded.is_empty() || sig.is_empty() || sig.contains('.') {
307            return Err(SlabError::unauthorized("invalid token format"));
308        }
309        if !self.verify_signature(encoded, sig) {
310            return Err(SlabError::unauthorized("invalid token signature"));
311        }
312        let raw = URL_SAFE_NO_PAD
313            .decode(encoded)
314            .map_err(|_| SlabError::unauthorized("invalid token encoding"))?;
315        let envelope = sqlx::types::Json::<SignedTokenEnvelope<T>>::decode_from_bytes(&raw)
316            .map_err(|_| SlabError::unauthorized("invalid token payload"))?
317            .0;
318        if envelope.p != purpose {
319            return Err(SlabError::unauthorized("token purpose mismatch"));
320        }
321        if envelope.exp <= Utc::now().timestamp() {
322            return Err(SlabError::unauthorized("token expired"));
323        }
324        Ok(envelope.d)
325    }
326
327    // ---- Browser Sessions ----
328
329    /// Insert a new browser session inside an existing SQLite transaction and return its cookie.
330    pub async fn create_session_in_tx(
331        &self,
332        tx: &mut Transaction<'_, Sqlite>,
333        user_id: &str,
334        role: &str,
335        ttl_days: i64,
336    ) -> SlabResult<(Session, Cookie<'static>)> {
337        let session_id = id::new("ses");
338        let raw_token = self.generate_token();
339        let token_hash = self.hash_token(&raw_token);
340        let now = Utc::now();
341        let expires = now + Duration::days(ttl_days);
342        let now_str = now.to_rfc3339();
343        let expires_str = expires.to_rfc3339();
344
345        sqlx::query(
346            "INSERT INTO slabs_sessions (id, user_id, role, token_hash, expires_at, created_at)
347             VALUES (?, ?, ?, ?, ?, ?)",
348        )
349        .bind(&session_id)
350        .bind(user_id)
351        .bind(role)
352        .bind(&token_hash)
353        .bind(&expires_str)
354        .bind(&now_str)
355        .execute(&mut **tx)
356        .await?;
357
358        let cookie = self.build_session_cookie(raw_token);
359        let session = Session {
360            id: session_id,
361            user_id: user_id.to_string(),
362            role: role.to_string(),
363            expires_at: expires_str,
364            created_at: now_str,
365        };
366        Ok((session, cookie))
367    }
368
369    /// Create and persist a new browser session in its own transaction and return its cookie.
370    pub async fn create_session(
371        &self,
372        user_id: &str,
373        role: &str,
374        ttl_days: i64,
375    ) -> SlabResult<(Session, Cookie<'static>)> {
376        let mut tx = self.db()?.begin().await?;
377        let res = self
378            .create_session_in_tx(&mut tx, user_id, role, ttl_days)
379            .await?;
380        tx.commit().await?;
381        Ok(res)
382    }
383
384    /// Look up the active, unexpired [`Session`] for the request's cookie jar, if present.
385    pub async fn optional_session(&self, jar: &CookieJar) -> SlabResult<Option<Session>> {
386        let Some(cookie) = jar.get(SESSION_COOKIE_NAME) else {
387            return Ok(None);
388        };
389        let token_hash = self.hash_token(cookie.value());
390        let now_str = Utc::now().to_rfc3339();
391
392        let session: Option<Session> = sqlx::query_as(
393            "SELECT id, user_id, role, expires_at, created_at
394             FROM slabs_sessions
395             WHERE token_hash = ? AND expires_at > ?",
396        )
397        .bind(&token_hash)
398        .bind(&now_str)
399        .fetch_optional(self.db()?.pool())
400        .await?;
401
402        Ok(session)
403    }
404
405    /// Require a valid browser session from `jar`, failing with HTTP 401 if unauthenticated.
406    pub async fn require_session(&self, jar: &CookieJar) -> SlabResult<Session> {
407        self.optional_session(jar)
408            .await?
409            .ok_or_else(|| SlabError::unauthorized("authentication required"))
410    }
411
412    /// Require a valid browser session with the `"admin"` role, failing with HTTP 401 or 403 otherwise.
413    pub async fn require_admin(&self, jar: &CookieJar) -> SlabResult<Session> {
414        let session = self.require_session(jar).await?;
415        if session.role != "admin" {
416            return Err(SlabError::forbidden("administrator role required"));
417        }
418        Ok(session)
419    }
420
421    /// Delete the current session from the database (if present) and return a removal cookie.
422    pub async fn destroy_session(&self, jar: &CookieJar) -> SlabResult<Cookie<'static>> {
423        if let Some(cookie) = jar.get(SESSION_COOKIE_NAME) {
424            let token_hash = self.hash_token(cookie.value());
425            sqlx::query("DELETE FROM slabs_sessions WHERE token_hash = ?")
426                .bind(&token_hash)
427                .execute(self.db()?.pool())
428                .await?;
429        }
430        Ok(self.clear_session_cookie())
431    }
432
433    /// Build an `HttpOnly`, `SameSite=Lax` session cookie carrying `raw_token`.
434    pub fn build_session_cookie(&self, raw_token: String) -> Cookie<'static> {
435        Cookie::build((SESSION_COOKIE_NAME, raw_token))
436            .path("/")
437            .http_only(true)
438            .same_site(SameSite::Lax)
439            .secure(self.cookie_secure)
440            .build()
441    }
442
443    /// Build an expired removal cookie that clears the browser session cookie.
444    pub fn clear_session_cookie(&self) -> Cookie<'static> {
445        let mut cookie = Cookie::build((SESSION_COOKIE_NAME, ""))
446            .path("/")
447            .http_only(true)
448            .same_site(SameSite::Lax)
449            .secure(self.cookie_secure)
450            .build();
451        cookie.make_removal();
452        cookie
453    }
454
455    // ---- Passwordless Magic Links (extracted from Fizzy) ----
456
457    /// Issue an expiring 6-character magic link code and store its SHA-256 hash in `slabs_magic_links`.
458    pub async fn issue_magic_link(
459        &self,
460        email: &str,
461        purpose: &str,
462        ttl_minutes: i64,
463    ) -> SlabResult<MagicLinkIssued> {
464        let link_id = id::new("mlk");
465        let code = self.generate_short_code(6);
466        let code_hash = self.hash_token(&code);
467        let now = Utc::now();
468        let expires_at = (now + Duration::minutes(ttl_minutes)).to_rfc3339();
469        let created_at = now.to_rfc3339();
470        let email = email.trim().to_lowercase();
471
472        sqlx::query(
473            "INSERT INTO slabs_magic_links (id, email, purpose, code_hash, expires_at, created_at)
474             VALUES (?, ?, ?, ?, ?, ?)",
475        )
476        .bind(&link_id)
477        .bind(&email)
478        .bind(purpose)
479        .bind(&code_hash)
480        .bind(&expires_at)
481        .bind(&created_at)
482        .execute(self.db()?.pool())
483        .await?;
484
485        Ok(MagicLinkIssued {
486            id: link_id,
487            email,
488            purpose: purpose.to_string(),
489            code,
490            expires_at,
491        })
492    }
493
494    /// Atomically consume a valid, unexpired magic link code via `DELETE ... RETURNING` so each code works once.
495    pub async fn consume_magic_link(&self, raw_code: &str) -> SlabResult<MagicLinkConsumed> {
496        let sanitized: String = raw_code
497            .chars()
498            .filter(char::is_ascii_alphanumeric)
499            .map(|c| c.to_ascii_uppercase())
500            .collect();
501        if sanitized.is_empty() {
502            return Err(SlabError::unauthorized(
503                "invalid or expired magic link code",
504            ));
505        }
506
507        let code_hash = self.hash_token(&sanitized);
508        let now_str = Utc::now().to_rfc3339();
509
510        let consumed: Option<(String, String, String)> = sqlx::query_as(
511            "DELETE FROM slabs_magic_links
512             WHERE code_hash = ? AND expires_at > ?
513             RETURNING id, email, purpose",
514        )
515        .bind(&code_hash)
516        .bind(&now_str)
517        .fetch_optional(self.db()?.pool())
518        .await?;
519
520        let Some((id, email, purpose)) = consumed else {
521            return Err(SlabError::unauthorized(
522                "invalid or expired magic link code",
523            ));
524        };
525
526        Ok(MagicLinkConsumed { id, email, purpose })
527    }
528
529    /// Delete all expired magic link rows and return the number of rows removed.
530    pub async fn cleanup_expired_magic_links(&self) -> SlabResult<u64> {
531        let now_str = Utc::now().to_rfc3339();
532        let res = sqlx::query("DELETE FROM slabs_magic_links WHERE expires_at <= ?")
533            .bind(&now_str)
534            .execute(self.db()?.pool())
535            .await?;
536        Ok(res.rows_affected())
537    }
538
539    // ---- Personal Access Tokens / Bearer Auth (extracted from Fizzy for CLIs & Agents) ----
540
541    /// Issue a personal access token prefixed with `slb_` and store its SHA-256 hash in `slabs_access_tokens`.
542    pub async fn issue_access_token(
543        &self,
544        user_id: &str,
545        role: &str,
546        description: &str,
547        permission: &str,
548    ) -> SlabResult<AccessTokenIssued> {
549        let token_id = id::new("pat");
550        let raw_token = format!("slb_{}", self.generate_token());
551        let token_hash = self.hash_token(&raw_token);
552        let created_at = Utc::now().to_rfc3339();
553
554        sqlx::query(
555            "INSERT INTO slabs_access_tokens (id, user_id, role, description, permission, token_hash, created_at)
556             VALUES (?, ?, ?, ?, ?, ?, ?)",
557        )
558        .bind(&token_id)
559        .bind(user_id)
560        .bind(role)
561        .bind(description)
562        .bind(permission)
563        .bind(&token_hash)
564        .bind(&created_at)
565        .execute(self.db()?.pool())
566        .await?;
567
568        Ok(AccessTokenIssued {
569            id: token_id,
570            user_id: user_id.to_string(),
571            description: description.to_string(),
572            permission: permission.to_string(),
573            token: raw_token,
574        })
575    }
576
577    /// Authenticate via `Authorization: Bearer <token>` or the `slabs_session` cookie.
578    ///
579    /// When a `Bearer` header is present, this method validates only that token and returns `Ok(None)` if it is invalid.
580    pub async fn optional_auth(
581        &self,
582        jar: &CookieJar,
583        headers: &HeaderMap,
584    ) -> SlabResult<Option<Principal>> {
585        if let Some(auth_hdr) = headers
586            .get(header::AUTHORIZATION)
587            .and_then(|v| v.to_str().ok())
588        {
589            if let Some(raw_token) = auth_hdr
590                .strip_prefix("Bearer ")
591                .or_else(|| auth_hdr.strip_prefix("bearer "))
592            {
593                let token_hash = self.hash_token(raw_token.trim());
594                let now_str = Utc::now().to_rfc3339();
595
596                let db = self.db()?;
597                let row: Option<(String, String, String, String)> = sqlx::query_as(
598                    "SELECT id, user_id, role, permission
599                     FROM slabs_access_tokens
600                     WHERE token_hash = ? AND (expires_at IS NULL OR expires_at > ?)",
601                )
602                .bind(&token_hash)
603                .bind(&now_str)
604                .fetch_optional(db.pool())
605                .await?;
606
607                if let Some((token_id, user_id, role, permission)) = row {
608                    let _ =
609                        sqlx::query("UPDATE slabs_access_tokens SET last_used_at = ? WHERE id = ?")
610                            .bind(&now_str)
611                            .bind(&token_id)
612                            .execute(db.pool())
613                            .await;
614
615                    return Ok(Some(Principal {
616                        user_id,
617                        role,
618                        auth_kind: "bearer".to_string(),
619                        permission,
620                    }));
621                }
622                return Ok(None);
623            }
624        }
625
626        if let Some(session) = self.optional_session(jar).await? {
627            return Ok(Some(Principal {
628                user_id: session.user_id,
629                role: session.role,
630                auth_kind: "session".to_string(),
631                permission: "write".to_string(),
632            }));
633        }
634
635        Ok(None)
636    }
637
638    /// Require authentication via either session cookie or `Authorization: Bearer` token.
639    pub async fn require_auth(
640        &self,
641        jar: &CookieJar,
642        headers: &HeaderMap,
643    ) -> SlabResult<Principal> {
644        self.optional_auth(jar, headers).await?.ok_or_else(|| {
645            SlabError::unauthorized("authentication required (session cookie or Bearer token)")
646        })
647    }
648
649    /// Require an authenticated [`Principal`] with `"write"` permission.
650    pub async fn require_write_auth(
651        &self,
652        jar: &CookieJar,
653        headers: &HeaderMap,
654    ) -> SlabResult<Principal> {
655        let principal = self.require_auth(jar, headers).await?;
656        if principal.permission != "write" {
657            return Err(SlabError::forbidden(
658                "access token does not have write permission",
659            ));
660        }
661        Ok(principal)
662    }
663}
664
665#[cfg(test)]
666mod tests {
667    use super::*;
668    use std::time::Duration as StdDuration;
669
670    #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
671    struct InvitePayload {
672        user_id: String,
673        org_id: String,
674    }
675
676    fn test_auth() -> Auth {
677        Auth::for_signing("unit-test-secret-key-for-signed-tokens", false)
678    }
679
680    #[test]
681    fn sign_and_verify_token_roundtrip() {
682        let auth = test_auth();
683        let payload = InvitePayload {
684            user_id: "usr_01".to_string(),
685            org_id: "org_42".to_string(),
686        };
687
688        let token = auth
689            .sign_token("invite", &payload, StdDuration::from_secs(300))
690            .unwrap();
691        let decoded: InvitePayload = auth.verify_token("invite", &token).unwrap();
692        assert_eq!(decoded, payload);
693    }
694
695    #[test]
696    fn verify_token_rejects_wrong_purpose() {
697        let auth = test_auth();
698        let token = auth
699            .sign_token(
700                "email_verify",
701                &"usr_01".to_string(),
702                StdDuration::from_secs(300),
703            )
704            .unwrap();
705
706        let err = auth
707            .verify_token::<String>("password_reset", &token)
708            .unwrap_err();
709        assert_eq!(err.status_code(), http::StatusCode::UNAUTHORIZED);
710    }
711
712    #[test]
713    fn verify_token_rejects_tampered_signature() {
714        let auth = test_auth();
715        let token = auth
716            .sign_token(
717                "download",
718                &"blb_123".to_string(),
719                StdDuration::from_secs(300),
720            )
721            .unwrap();
722        let (encoded, sig) = token.split_once('.').unwrap();
723        let flipped = if sig.starts_with('a') { 'b' } else { 'a' };
724        let tampered = format!("{encoded}.{flipped}{}", &sig[1..]);
725
726        let err = auth
727            .verify_token::<String>("download", &tampered)
728            .unwrap_err();
729        assert_eq!(err.status_code(), http::StatusCode::UNAUTHORIZED);
730    }
731
732    #[test]
733    fn verify_token_rejects_expired_token() {
734        let auth = test_auth();
735
736        let zero_ttl = auth
737            .sign_token("reset", &"usr_01".to_string(), StdDuration::ZERO)
738            .unwrap();
739        let err = auth.verify_token::<String>("reset", &zero_ttl).unwrap_err();
740        assert_eq!(err.status_code(), http::StatusCode::UNAUTHORIZED);
741
742        // Also test an explicitly past expiration timestamp (negative skew).
743        let past_envelope = SignedTokenEnvelopeRef {
744            p: "reset",
745            exp: Utc::now().timestamp() - 60,
746            d: &"usr_01",
747        };
748        let json = sqlx::types::Json(&past_envelope)
749            .encode_to_string()
750            .unwrap();
751        let encoded = URL_SAFE_NO_PAD.encode(json.as_bytes());
752        let sig = auth.sign(&encoded);
753        let expired = format!("{encoded}.{sig}");
754
755        let err = auth.verify_token::<String>("reset", &expired).unwrap_err();
756        assert_eq!(err.status_code(), http::StatusCode::UNAUTHORIZED);
757    }
758}