slabs-auth 0.2.0

Explicit low-level auth battery: Argon2id passwords, DB sessions, magic links, Bearer API tokens, and HMAC signing
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
//! Authentication, browser sessions, magic links, personal access tokens, and HMAC signing for Slabs.
//!
//! # What this crate owns
//!
//! - Types: [`Auth`], [`Session`], [`Principal`], [`MagicLinkIssued`], [`MagicLinkConsumed`],
//!   [`AccessTokenIssued`], and [`SESSION_COOKIE_NAME`] (`"slabs_session"`).
//! - Framework SQLite tables created by `slabs_db::Db::init_system_tables`:
//!   - `slabs_sessions`: SHA-256 hashed browser session tokens, `user_id`, `role`, and `expires_at`.
//!   - `slabs_magic_links`: SHA-256 hashed 6-character verification codes, normalized `email`, `purpose`, and `expires_at`.
//!   - `slabs_access_tokens`: SHA-256 hashed `Authorization: Bearer` tokens, `user_id`, `role`, `permission`, `last_used_at`, and `expires_at`.
//! - User accounts live in your application's own `users` table in your SQL migrations. This crate does not own a `users` table.
//!
//! # Agent invariants
//!
//! - Put an explicit auth guard on line 1 of every protected slab handler. Do not rely on hidden middleware or callbacks.
//!   - [`Auth::require_session`]: requires a valid `slabs_session` cookie (HTTP 401 when missing or expired).
//!   - [`Auth::require_admin`]: requires a valid session with `role == "admin"` (HTTP 401 or 403).
//!   - [`Auth::require_auth`]: accepts either `Authorization: Bearer <token>` or a `slabs_session` cookie (HTTP 401).
//!   - [`Auth::require_write_auth`]: requires [`Auth::require_auth`] with `permission == "write"` (HTTP 403 for `"read"` tokens).
//! - Hash passwords with [`Auth::hash_password`] (`Argon2id` with a random OS salt) and verify with [`Auth::verify_password`].
//! - 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.
//! - 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.
//! - 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.
//! - Use [`Auth::create_session_in_tx`] when creating a user and a browser session inside one SQLite transaction.
//!
//! # Example
//!
//! ```rust,no_run
//! use axum_extra::extract::CookieJar;
//! use http::HeaderMap;
//! use slabs_auth::Auth;
//! use slabs_core::SlabResult;
//!
//! async fn protected_handler(auth: &Auth, jar: &CookieJar, headers: &HeaderMap) -> SlabResult<()> {
//!     // Line 1 guard for browser-only endpoints:
//!     let session = auth.require_session(jar).await?;
//!
//!     // Or accept either a session cookie or a write-scoped Bearer token:
//!     let principal = auth.require_write_auth(jar, headers).await?;
//!
//!     let _ = (session.user_id, principal.user_id);
//!     Ok(())
//! }
//! ```

use argon2::{
    password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString},
    Argon2,
};
use axum_extra::extract::cookie::{Cookie, CookieJar, SameSite};
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
use chrono::{Duration, Utc};
use hmac::{Hmac, Mac};
use http::{header, HeaderMap};
use rand_core::{OsRng, RngCore};
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use sha2::{Digest, Sha256};
use slabs_core::{id, SlabError, SlabResult};
use slabs_db::Db;
use sqlx::{Sqlite, Transaction};
use std::fmt;

type HmacSha256 = Hmac<Sha256>;

#[derive(Serialize)]
struct SignedTokenEnvelopeRef<'a, T: ?Sized> {
    p: &'a str,
    exp: i64,
    d: &'a T,
}

#[derive(Deserialize)]
struct SignedTokenEnvelope<T> {
    p: String,
    exp: i64,
    d: T,
}

/// Cookie name used to store browser session tokens.
pub const SESSION_COOKIE_NAME: &str = "slabs_session";

/// Active browser session persisted in the `slabs_sessions` table.
#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
pub struct Session {
    /// Prefixed session identifier (`ses_...`).
    pub id: String,
    /// Authenticated user's identifier.
    pub user_id: String,
    /// Role assigned to the user when the session was created (e.g. `"member"`, `"admin"`).
    pub role: String,
    /// RFC 3339 timestamp after which the session is no longer valid.
    pub expires_at: String,
    /// RFC 3339 timestamp when the session was created.
    pub created_at: String,
}

/// Authenticated actor resolved from either a browser session cookie or an `Authorization: Bearer` token.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Principal {
    /// Authenticated user's identifier.
    pub user_id: String,
    /// Role associated with the authenticated user.
    pub role: String,
    /// Authentication mechanism used (`"session"` or `"bearer"`).
    pub auth_kind: String,
    /// Granted permission level (`"write"` or `"read"`).
    pub permission: String,
}

/// Result returned when a new one-time magic link code is issued.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MagicLinkIssued {
    /// Prefixed magic-link record identifier (`mlk_...`).
    pub id: String,
    /// Normalized lowercase email address the code was issued for.
    pub email: String,
    /// Application-defined purpose for the magic link (e.g. `"sign_in"`).
    pub purpose: String,
    /// Plaintext one-time verification code to deliver to the user.
    pub code: String,
    /// RFC 3339 timestamp when the code expires.
    pub expires_at: String,
}

/// Verified metadata returned after atomically consuming a magic link code.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MagicLinkConsumed {
    /// Prefixed magic-link record identifier (`mlk_...`).
    pub id: String,
    /// Normalized email address associated with the consumed code.
    pub email: String,
    /// Application-defined purpose associated with the consumed code.
    pub purpose: String,
}

/// Result returned when a new personal access token is issued.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AccessTokenIssued {
    /// Prefixed access-token record identifier (`pat_...`).
    pub id: String,
    /// Owner user identifier.
    pub user_id: String,
    /// Human-readable label describing the token's purpose.
    pub description: String,
    /// Permission scope granted to the token (`"write"` or `"read"`).
    pub permission: String,
    /// Plaintext bearer token shown once upon issuance (`slb_...`).
    pub token: String,
}

/// Explicit authentication and session service backed by `slabs_sessions`, `slabs_magic_links`, and `slabs_access_tokens`.
///
/// Supports `Argon2id` password hashing, single-use 6-character magic links, `HttpOnly` browser
/// session cookies, SHA-256 hashed `Authorization: Bearer` tokens, and HMAC-SHA256 signing.
#[derive(Clone)]
pub struct Auth {
    db: Option<Db>,
    secret_key: String,
    cookie_secure: bool,
}

impl fmt::Debug for Auth {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Auth")
            .field("db", &self.db)
            .field("secret_key", &"<redacted>")
            .field("cookie_secure", &self.cookie_secure)
            .finish()
    }
}

impl Auth {
    /// Create an [`Auth`] service backed by `db`, using `secret_key` for HMAC signing and `cookie_secure` for the cookie `Secure` flag.
    #[must_use]
    pub fn new(db: Db, secret_key: impl Into<String>, cookie_secure: bool) -> Self {
        Self {
            db: Some(db),
            secret_key: secret_key.into(),
            cookie_secure,
        }
    }

    /// Create a stateless [`Auth`] handle for HMAC signing, token verification, and signed cookies without a database connection.
    #[must_use]
    pub fn for_signing(secret_key: impl Into<String>, cookie_secure: bool) -> Self {
        Self {
            db: None,
            secret_key: secret_key.into(),
            cookie_secure,
        }
    }

    /// Return whether cookies emitted by this [`Auth`] instance should set the `Secure` attribute.
    #[must_use]
    pub fn cookie_secure(&self) -> bool {
        self.cookie_secure
    }

    fn db(&self) -> SlabResult<&Db> {
        self.db
            .as_ref()
            .ok_or_else(|| SlabError::internal("Auth requires a database connection"))
    }

    /// Hash a plaintext password with `Argon2id` and a random OS salt, returning a PHC string.
    pub fn hash_password(&self, password: &str) -> SlabResult<String> {
        let salt = SaltString::generate(&mut OsRng);
        Argon2::default()
            .hash_password(password.as_bytes(), &salt)
            .map(|h| h.to_string())
            .map_err(|e| SlabError::internal(format!("password hashing failed: {e}")))
    }

    /// Verify a plaintext password against a stored `Argon2id` PHC hash string.
    pub fn verify_password(&self, password: &str, password_hash: &str) -> bool {
        let Ok(parsed) = PasswordHash::new(password_hash) else {
            return false;
        };
        Argon2::default()
            .verify_password(password.as_bytes(), &parsed)
            .is_ok()
    }

    /// Compute the hex-encoded SHA-256 digest of a raw token or verification code.
    pub fn hash_token(&self, raw_token: &str) -> String {
        let mut hasher = Sha256::new();
        hasher.update(raw_token.as_bytes());
        hex::encode(hasher.finalize())
    }

    /// Generate a cryptographically random 32-byte hex-encoded token.
    pub fn generate_token(&self) -> String {
        let mut bytes = [0u8; 32];
        OsRng.fill_bytes(&mut bytes);
        hex::encode(bytes)
    }

    /// Generate a random alphanumeric code of length `len`, omitting ambiguous `0`, `O`, `1`, and `I` characters.
    pub fn generate_short_code(&self, len: usize) -> String {
        const ALPHABET: &[u8] = b"23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
        let mut bytes = vec![0u8; len];
        OsRng.fill_bytes(&mut bytes);
        bytes
            .into_iter()
            .map(|b| ALPHABET[(b as usize) % ALPHABET.len()] as char)
            .collect()
    }

    /// Compute a hex-encoded HMAC-SHA256 signature for `payload` using the configured secret key.
    pub fn sign(&self, payload: &str) -> String {
        let mut mac = HmacSha256::new_from_slice(self.secret_key.as_bytes())
            .expect("HMAC accepts keys of any size");
        mac.update(payload.as_bytes());
        hex::encode(mac.finalize().into_bytes())
    }

    /// Verify a hex-encoded HMAC-SHA256 signature for `payload` in constant time.
    pub fn verify_signature(&self, payload: &str, signature_hex: &str) -> bool {
        let Ok(sig_bytes) = hex::decode(signature_hex) else {
            return false;
        };
        let Ok(mut mac) = HmacSha256::new_from_slice(self.secret_key.as_bytes()) else {
            return false;
        };
        mac.update(payload.as_bytes());
        mac.verify_slice(&sig_bytes).is_ok()
    }

    /// Mint a purpose-bound, expiring HMAC-signed token carrying `payload`.
    ///
    /// Encodes `{"p": purpose, "exp": unix_ts, "d": payload}` as URL-safe base64 without padding
    /// and appends `.<hex_hmac_sig>`.
    pub fn sign_token<T: Serialize>(
        &self,
        purpose: &str,
        payload: &T,
        ttl: std::time::Duration,
    ) -> SlabResult<String> {
        let ttl_secs = i64::try_from(ttl.as_secs())
            .map_err(|_| SlabError::bad_request("token ttl exceeds supported range"))?;
        let exp = Utc::now()
            .timestamp()
            .checked_add(ttl_secs)
            .ok_or_else(|| SlabError::bad_request("token expiration timestamp overflow"))?;
        let envelope = SignedTokenEnvelopeRef {
            p: purpose,
            exp,
            d: payload,
        };
        let json = sqlx::types::Json(&envelope)
            .encode_to_string()
            .map_err(|e| SlabError::internal(format!("failed to serialize signed token: {e}")))?;
        let encoded = URL_SAFE_NO_PAD.encode(json.as_bytes());
        let sig = self.sign(&encoded);
        Ok(format!("{encoded}.{sig}"))
    }

    /// Verify a signed token produced by [`Auth::sign_token`], enforcing purpose and expiration.
    ///
    /// Returns HTTP `401 Unauthorized` when the format, HMAC signature, encoding, payload shape,
    /// purpose, or expiration check fails.
    pub fn verify_token<T: DeserializeOwned>(&self, purpose: &str, token: &str) -> SlabResult<T> {
        let Some((encoded, sig)) = token.split_once('.') else {
            return Err(SlabError::unauthorized("invalid token format"));
        };
        if encoded.is_empty() || sig.is_empty() || sig.contains('.') {
            return Err(SlabError::unauthorized("invalid token format"));
        }
        if !self.verify_signature(encoded, sig) {
            return Err(SlabError::unauthorized("invalid token signature"));
        }
        let raw = URL_SAFE_NO_PAD
            .decode(encoded)
            .map_err(|_| SlabError::unauthorized("invalid token encoding"))?;
        let envelope = sqlx::types::Json::<SignedTokenEnvelope<T>>::decode_from_bytes(&raw)
            .map_err(|_| SlabError::unauthorized("invalid token payload"))?
            .0;
        if envelope.p != purpose {
            return Err(SlabError::unauthorized("token purpose mismatch"));
        }
        if envelope.exp <= Utc::now().timestamp() {
            return Err(SlabError::unauthorized("token expired"));
        }
        Ok(envelope.d)
    }

    // ---- Browser Sessions ----

    /// Insert a new browser session inside an existing SQLite transaction and return its cookie.
    pub async fn create_session_in_tx(
        &self,
        tx: &mut Transaction<'_, Sqlite>,
        user_id: &str,
        role: &str,
        ttl_days: i64,
    ) -> SlabResult<(Session, Cookie<'static>)> {
        let session_id = id::new("ses");
        let raw_token = self.generate_token();
        let token_hash = self.hash_token(&raw_token);
        let now = Utc::now();
        let expires = now + Duration::days(ttl_days);
        let now_str = now.to_rfc3339();
        let expires_str = expires.to_rfc3339();

        sqlx::query(
            "INSERT INTO slabs_sessions (id, user_id, role, token_hash, expires_at, created_at)
             VALUES (?, ?, ?, ?, ?, ?)",
        )
        .bind(&session_id)
        .bind(user_id)
        .bind(role)
        .bind(&token_hash)
        .bind(&expires_str)
        .bind(&now_str)
        .execute(&mut **tx)
        .await?;

        let cookie = self.build_session_cookie(raw_token);
        let session = Session {
            id: session_id,
            user_id: user_id.to_string(),
            role: role.to_string(),
            expires_at: expires_str,
            created_at: now_str,
        };
        Ok((session, cookie))
    }

    /// Create and persist a new browser session in its own transaction and return its cookie.
    pub async fn create_session(
        &self,
        user_id: &str,
        role: &str,
        ttl_days: i64,
    ) -> SlabResult<(Session, Cookie<'static>)> {
        let mut tx = self.db()?.begin().await?;
        let res = self
            .create_session_in_tx(&mut tx, user_id, role, ttl_days)
            .await?;
        tx.commit().await?;
        Ok(res)
    }

    /// Look up the active, unexpired [`Session`] for the request's cookie jar, if present.
    pub async fn optional_session(&self, jar: &CookieJar) -> SlabResult<Option<Session>> {
        let Some(cookie) = jar.get(SESSION_COOKIE_NAME) else {
            return Ok(None);
        };
        let token_hash = self.hash_token(cookie.value());
        let now_str = Utc::now().to_rfc3339();

        let session: Option<Session> = sqlx::query_as(
            "SELECT id, user_id, role, expires_at, created_at
             FROM slabs_sessions
             WHERE token_hash = ? AND expires_at > ?",
        )
        .bind(&token_hash)
        .bind(&now_str)
        .fetch_optional(self.db()?.pool())
        .await?;

        Ok(session)
    }

    /// Require a valid browser session from `jar`, failing with HTTP 401 if unauthenticated.
    pub async fn require_session(&self, jar: &CookieJar) -> SlabResult<Session> {
        self.optional_session(jar)
            .await?
            .ok_or_else(|| SlabError::unauthorized("authentication required"))
    }

    /// Require a valid browser session with the `"admin"` role, failing with HTTP 401 or 403 otherwise.
    pub async fn require_admin(&self, jar: &CookieJar) -> SlabResult<Session> {
        let session = self.require_session(jar).await?;
        if session.role != "admin" {
            return Err(SlabError::forbidden("administrator role required"));
        }
        Ok(session)
    }

    /// Delete the current session from the database (if present) and return a removal cookie.
    pub async fn destroy_session(&self, jar: &CookieJar) -> SlabResult<Cookie<'static>> {
        if let Some(cookie) = jar.get(SESSION_COOKIE_NAME) {
            let token_hash = self.hash_token(cookie.value());
            sqlx::query("DELETE FROM slabs_sessions WHERE token_hash = ?")
                .bind(&token_hash)
                .execute(self.db()?.pool())
                .await?;
        }
        Ok(self.clear_session_cookie())
    }

    /// Build an `HttpOnly`, `SameSite=Lax` session cookie carrying `raw_token`.
    pub fn build_session_cookie(&self, raw_token: String) -> Cookie<'static> {
        Cookie::build((SESSION_COOKIE_NAME, raw_token))
            .path("/")
            .http_only(true)
            .same_site(SameSite::Lax)
            .secure(self.cookie_secure)
            .build()
    }

    /// Build an expired removal cookie that clears the browser session cookie.
    pub fn clear_session_cookie(&self) -> Cookie<'static> {
        let mut cookie = Cookie::build((SESSION_COOKIE_NAME, ""))
            .path("/")
            .http_only(true)
            .same_site(SameSite::Lax)
            .secure(self.cookie_secure)
            .build();
        cookie.make_removal();
        cookie
    }

    // ---- Passwordless Magic Links (extracted from Fizzy) ----

    /// Issue an expiring 6-character magic link code and store its SHA-256 hash in `slabs_magic_links`.
    pub async fn issue_magic_link(
        &self,
        email: &str,
        purpose: &str,
        ttl_minutes: i64,
    ) -> SlabResult<MagicLinkIssued> {
        let link_id = id::new("mlk");
        let code = self.generate_short_code(6);
        let code_hash = self.hash_token(&code);
        let now = Utc::now();
        let expires_at = (now + Duration::minutes(ttl_minutes)).to_rfc3339();
        let created_at = now.to_rfc3339();
        let email = email.trim().to_lowercase();

        sqlx::query(
            "INSERT INTO slabs_magic_links (id, email, purpose, code_hash, expires_at, created_at)
             VALUES (?, ?, ?, ?, ?, ?)",
        )
        .bind(&link_id)
        .bind(&email)
        .bind(purpose)
        .bind(&code_hash)
        .bind(&expires_at)
        .bind(&created_at)
        .execute(self.db()?.pool())
        .await?;

        Ok(MagicLinkIssued {
            id: link_id,
            email,
            purpose: purpose.to_string(),
            code,
            expires_at,
        })
    }

    /// Atomically consume a valid, unexpired magic link code via `DELETE ... RETURNING` so each code works once.
    pub async fn consume_magic_link(&self, raw_code: &str) -> SlabResult<MagicLinkConsumed> {
        let sanitized: String = raw_code
            .chars()
            .filter(char::is_ascii_alphanumeric)
            .map(|c| c.to_ascii_uppercase())
            .collect();
        if sanitized.is_empty() {
            return Err(SlabError::unauthorized(
                "invalid or expired magic link code",
            ));
        }

        let code_hash = self.hash_token(&sanitized);
        let now_str = Utc::now().to_rfc3339();

        let consumed: Option<(String, String, String)> = sqlx::query_as(
            "DELETE FROM slabs_magic_links
             WHERE code_hash = ? AND expires_at > ?
             RETURNING id, email, purpose",
        )
        .bind(&code_hash)
        .bind(&now_str)
        .fetch_optional(self.db()?.pool())
        .await?;

        let Some((id, email, purpose)) = consumed else {
            return Err(SlabError::unauthorized(
                "invalid or expired magic link code",
            ));
        };

        Ok(MagicLinkConsumed { id, email, purpose })
    }

    /// Delete all expired magic link rows and return the number of rows removed.
    pub async fn cleanup_expired_magic_links(&self) -> SlabResult<u64> {
        let now_str = Utc::now().to_rfc3339();
        let res = sqlx::query("DELETE FROM slabs_magic_links WHERE expires_at <= ?")
            .bind(&now_str)
            .execute(self.db()?.pool())
            .await?;
        Ok(res.rows_affected())
    }

    // ---- Personal Access Tokens / Bearer Auth (extracted from Fizzy for CLIs & Agents) ----

    /// Issue a personal access token prefixed with `slb_` and store its SHA-256 hash in `slabs_access_tokens`.
    pub async fn issue_access_token(
        &self,
        user_id: &str,
        role: &str,
        description: &str,
        permission: &str,
    ) -> SlabResult<AccessTokenIssued> {
        let token_id = id::new("pat");
        let raw_token = format!("slb_{}", self.generate_token());
        let token_hash = self.hash_token(&raw_token);
        let created_at = Utc::now().to_rfc3339();

        sqlx::query(
            "INSERT INTO slabs_access_tokens (id, user_id, role, description, permission, token_hash, created_at)
             VALUES (?, ?, ?, ?, ?, ?, ?)",
        )
        .bind(&token_id)
        .bind(user_id)
        .bind(role)
        .bind(description)
        .bind(permission)
        .bind(&token_hash)
        .bind(&created_at)
        .execute(self.db()?.pool())
        .await?;

        Ok(AccessTokenIssued {
            id: token_id,
            user_id: user_id.to_string(),
            description: description.to_string(),
            permission: permission.to_string(),
            token: raw_token,
        })
    }

    /// Authenticate via `Authorization: Bearer <token>` or the `slabs_session` cookie.
    ///
    /// When a `Bearer` header is present, this method validates only that token and returns `Ok(None)` if it is invalid.
    pub async fn optional_auth(
        &self,
        jar: &CookieJar,
        headers: &HeaderMap,
    ) -> SlabResult<Option<Principal>> {
        if let Some(auth_hdr) = headers
            .get(header::AUTHORIZATION)
            .and_then(|v| v.to_str().ok())
        {
            if let Some(raw_token) = auth_hdr
                .strip_prefix("Bearer ")
                .or_else(|| auth_hdr.strip_prefix("bearer "))
            {
                let token_hash = self.hash_token(raw_token.trim());
                let now_str = Utc::now().to_rfc3339();

                let db = self.db()?;
                let row: Option<(String, String, String, String)> = sqlx::query_as(
                    "SELECT id, user_id, role, permission
                     FROM slabs_access_tokens
                     WHERE token_hash = ? AND (expires_at IS NULL OR expires_at > ?)",
                )
                .bind(&token_hash)
                .bind(&now_str)
                .fetch_optional(db.pool())
                .await?;

                if let Some((token_id, user_id, role, permission)) = row {
                    let _ =
                        sqlx::query("UPDATE slabs_access_tokens SET last_used_at = ? WHERE id = ?")
                            .bind(&now_str)
                            .bind(&token_id)
                            .execute(db.pool())
                            .await;

                    return Ok(Some(Principal {
                        user_id,
                        role,
                        auth_kind: "bearer".to_string(),
                        permission,
                    }));
                }
                return Ok(None);
            }
        }

        if let Some(session) = self.optional_session(jar).await? {
            return Ok(Some(Principal {
                user_id: session.user_id,
                role: session.role,
                auth_kind: "session".to_string(),
                permission: "write".to_string(),
            }));
        }

        Ok(None)
    }

    /// Require authentication via either session cookie or `Authorization: Bearer` token.
    pub async fn require_auth(
        &self,
        jar: &CookieJar,
        headers: &HeaderMap,
    ) -> SlabResult<Principal> {
        self.optional_auth(jar, headers).await?.ok_or_else(|| {
            SlabError::unauthorized("authentication required (session cookie or Bearer token)")
        })
    }

    /// Require an authenticated [`Principal`] with `"write"` permission.
    pub async fn require_write_auth(
        &self,
        jar: &CookieJar,
        headers: &HeaderMap,
    ) -> SlabResult<Principal> {
        let principal = self.require_auth(jar, headers).await?;
        if principal.permission != "write" {
            return Err(SlabError::forbidden(
                "access token does not have write permission",
            ));
        }
        Ok(principal)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::time::Duration as StdDuration;

    #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
    struct InvitePayload {
        user_id: String,
        org_id: String,
    }

    fn test_auth() -> Auth {
        Auth::for_signing("unit-test-secret-key-for-signed-tokens", false)
    }

    #[test]
    fn sign_and_verify_token_roundtrip() {
        let auth = test_auth();
        let payload = InvitePayload {
            user_id: "usr_01".to_string(),
            org_id: "org_42".to_string(),
        };

        let token = auth
            .sign_token("invite", &payload, StdDuration::from_secs(300))
            .unwrap();
        let decoded: InvitePayload = auth.verify_token("invite", &token).unwrap();
        assert_eq!(decoded, payload);
    }

    #[test]
    fn verify_token_rejects_wrong_purpose() {
        let auth = test_auth();
        let token = auth
            .sign_token(
                "email_verify",
                &"usr_01".to_string(),
                StdDuration::from_secs(300),
            )
            .unwrap();

        let err = auth
            .verify_token::<String>("password_reset", &token)
            .unwrap_err();
        assert_eq!(err.status_code(), http::StatusCode::UNAUTHORIZED);
    }

    #[test]
    fn verify_token_rejects_tampered_signature() {
        let auth = test_auth();
        let token = auth
            .sign_token(
                "download",
                &"blb_123".to_string(),
                StdDuration::from_secs(300),
            )
            .unwrap();
        let (encoded, sig) = token.split_once('.').unwrap();
        let flipped = if sig.starts_with('a') { 'b' } else { 'a' };
        let tampered = format!("{encoded}.{flipped}{}", &sig[1..]);

        let err = auth
            .verify_token::<String>("download", &tampered)
            .unwrap_err();
        assert_eq!(err.status_code(), http::StatusCode::UNAUTHORIZED);
    }

    #[test]
    fn verify_token_rejects_expired_token() {
        let auth = test_auth();

        let zero_ttl = auth
            .sign_token("reset", &"usr_01".to_string(), StdDuration::ZERO)
            .unwrap();
        let err = auth.verify_token::<String>("reset", &zero_ttl).unwrap_err();
        assert_eq!(err.status_code(), http::StatusCode::UNAUTHORIZED);

        // Also test an explicitly past expiration timestamp (negative skew).
        let past_envelope = SignedTokenEnvelopeRef {
            p: "reset",
            exp: Utc::now().timestamp() - 60,
            d: &"usr_01",
        };
        let json = sqlx::types::Json(&past_envelope)
            .encode_to_string()
            .unwrap();
        let encoded = URL_SAFE_NO_PAD.encode(json.as_bytes());
        let sig = auth.sign(&encoded);
        let expired = format!("{encoded}.{sig}");

        let err = auth.verify_token::<String>("reset", &expired).unwrap_err();
        assert_eq!(err.status_code(), http::StatusCode::UNAUTHORIZED);
    }
}