Skip to main content

larust_sanctum/
lib.rs

1//! Laravel's `laravel/sanctum` - narrowed to its bearer-token half, the
2//! part with no existing Larust equivalent at all. `larust_auth::Auth<U>`
3//! already covers Sanctum's other job (a first-party frontend
4//! authenticating via session cookie) natively, so this crate doesn't
5//! touch that path - it only adds what's missing: a plain API client (no
6//! cookie jar, no browser) authenticating via `Authorization: Bearer
7//! {token}`.
8//!
9//! **A separate crate from `larust-auth`, deliberately.** `larust-auth`
10//! currently has zero direct dependency on `larust-orm`/`sqlx` - every bit
11//! of persistence is delegated to the app's own
12//! [`Authenticatable::find_for_auth`] impl, keeping the auth *logic*
13//! storage-agnostic. A `personal_access_tokens` table is new storage this
14//! functionality has to own, so it lives here instead, the same way
15//! `larust-permissions`/`larust-notifications`/`larust-cache` each own
16//! their own table rather than being folded into a crate that otherwise
17//! has none. This crate depends on `larust-auth` (for
18//! [`Authenticatable`]/`AppError` conventions), never the other way round.
19//!
20//! Re-exported through `larust_support::sanctum` (see `crates/
21//! larust-support/src/lib.rs`) so generated apps depend only on
22//! `larust-support`, never on this crate directly.
23//!
24//! ## Deliberately out of scope for this version
25//!
26//! - **No token abilities/scopes** (Sanctum's `can()`/ability-string
27//!   gating). A real separate feature layering on top of the existing
28//!   `larust_auth::Policy` trait - not attempted here.
29//! - **No SPA/stateful cookie mode.** See this doc comment's own opening
30//!   paragraph - `Auth<U>` already covers it.
31//! - **No `auth:sanctum` middleware-string recognition in `xr convert`.**
32//!   `crates/larust-convert/src/routes.rs` already blanket-defers every
33//!   `Route::middleware(...)->group(...)` call, deliberately - this crate
34//!   doesn't special-case Sanctum's own alias within that existing
35//!   boundary, the same choice `larust-permissions`'s own doc comment
36//!   already made for `role:`/`permission:` middleware strings.
37
38use axum::extract::FromRequestParts;
39use axum::http::request::Parts;
40use axum::http::{header, HeaderMap, StatusCode};
41use larust_auth::Authenticatable;
42use larust_core::AppError;
43use larust_orm::Backend;
44use rand::Rng;
45use sha2::{Digest, Sha256};
46use sqlx::AnyPool;
47use std::fmt::Write as _;
48use std::time::{Duration, SystemTime, UNIX_EPOCH};
49
50/// Extracts the user identified by a valid `Authorization: Bearer {token}`
51/// header, or rejects with `401` - the bearer-token sibling to
52/// `larust_auth::Auth<U>`, never a replacement for it. A route picks
53/// whichever extractor matches how it's actually authenticated, the same
54/// way a Laravel route explicitly chooses `auth:sanctum` vs `auth:web`
55/// middleware; `Auth<U>` gains no branch point for "no session, try a
56/// header instead."
57pub struct ApiAuth<U>(pub U);
58
59// GOTCHAS.md: axum-core declares `FromRequestParts` via `#[async_trait]`,
60// not native async-fn-in-traits - an impl written as a plain `async fn`
61// fails with a confusing E0195 lifetime error instead of a clear message
62// about the mismatch. Same note `larust_auth::Auth<U>`'s own impl carries.
63#[axum::async_trait]
64impl<S, U> FromRequestParts<S> for ApiAuth<U>
65where
66    S: Send + Sync,
67    U: Authenticatable,
68{
69    type Rejection = AppError;
70
71    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
72        let user_id = authenticate(&parts.headers).await?;
73        U::find_for_auth(user_id)
74            .await?
75            .map(ApiAuth)
76            .ok_or_else(unauthorized)
77    }
78}
79
80/// One generic message for every failure mode below (missing header,
81/// malformed token, unknown id, hash mismatch, expired, deleted user) -
82/// never reveals *which* check failed, the same instinct a password check
83/// already follows.
84fn unauthorized() -> AppError {
85    AppError::Http {
86        status: StatusCode::UNAUTHORIZED,
87        message: "invalid or missing API token".to_string(),
88    }
89}
90
91async fn authenticate(headers: &HeaderMap) -> Result<i64, AppError> {
92    let raw = headers
93        .get(header::AUTHORIZATION)
94        .and_then(|value| value.to_str().ok())
95        .ok_or_else(unauthorized)?;
96    let token = raw.strip_prefix("Bearer ").ok_or_else(unauthorized)?;
97    // The row id is embedded ahead of the plaintext (`"{id}|{plaintext}"`,
98    // matching real Sanctum's own token shape) so lookup below is a single
99    // O(1) primary-key read - never a full-table scan hashing every stored
100    // token looking for a match.
101    let (id_part, plaintext) = token.split_once('|').ok_or_else(unauthorized)?;
102    let id: i64 = id_part.parse().map_err(|_| unauthorized())?;
103
104    let pool = larust_orm::pool()?;
105    ensure_table(pool).await?;
106
107    let backend = larust_orm::backend();
108    let select_sql = format!(
109        "SELECT user_id, token_hash, expires_at FROM personal_access_tokens WHERE id = {}",
110        larust_orm::placeholder(backend, 1)
111    );
112    let row: Option<(i64, String, Option<i64>)> = sqlx::query_as(&select_sql)
113        .bind(id)
114        .fetch_optional(pool)
115        .await
116        .map_err(|source| AppError::Internal(Box::new(source)))?;
117    let Some((user_id, token_hash, expires_at)) = row else {
118        return Err(unauthorized());
119    };
120
121    if !hashes_match(&hash_token(plaintext), &token_hash) {
122        return Err(unauthorized());
123    }
124    if expires_at.is_some_and(|expires_at| expires_at <= now_unix_secs()) {
125        return Err(unauthorized());
126    }
127
128    // Best-effort - a bookkeeping write failing here is never a reason to
129    // fail the request itself, same tolerance `larust-cache`'s own expiry
130    // sweep applies to its background cleanup.
131    let update_sql = format!(
132        "UPDATE personal_access_tokens SET last_used_at = {} WHERE id = {}",
133        larust_orm::placeholder(backend, 1),
134        larust_orm::placeholder(backend, 2),
135    );
136    if let Err(error) = sqlx::query(&update_sql)
137        .bind(now_unix_secs())
138        .bind(id)
139        .execute(pool)
140        .await
141    {
142        tracing::warn!(%error, "failed to record API token last_used_at");
143    }
144
145    Ok(user_id)
146}
147
148/// SHA-256, not `larust_auth::hash_password`'s Argon2id - a deliberate
149/// choice, matching real Sanctum's own: the token itself is already 32
150/// bytes of CSPRNG output, not a user-chosen secret that needs a slow KDF
151/// to resist brute-forcing. Argon2 on every single API request would add
152/// real, unnecessary latency for no security benefit here.
153fn hash_token(plaintext: &str) -> String {
154    let digest = Sha256::digest(plaintext.as_bytes());
155    let mut hex = String::with_capacity(digest.len() * 2);
156    for byte in digest {
157        let _ = write!(hex, "{byte:02x}");
158    }
159    hex
160}
161
162/// Constant-time comparison of two fixed-length hex digests - a plain
163/// `==` short-circuits on the first differing byte, leaking timing
164/// information proportional to how much of the token an attacker guessed
165/// correctly. Both inputs here are always 64-char SHA-256 hex digests, so
166/// a hand-written fixed-width XOR-fold is enough; no new dependency
167/// needed for it.
168fn hashes_match(a: &str, b: &str) -> bool {
169    let (a, b) = (a.as_bytes(), b.as_bytes());
170    if a.len() != b.len() {
171        return false;
172    }
173    let mut diff = 0u8;
174    for (x, y) in a.iter().zip(b.iter()) {
175        diff |= x ^ y;
176    }
177    diff == 0
178}
179
180fn now_unix_secs() -> i64 {
181    SystemTime::now()
182        .duration_since(UNIX_EPOCH)
183        .expect("system clock is before the Unix epoch")
184        .as_secs() as i64
185}
186
187/// `byte_len` cryptographically-strong random bytes, hex-encoded. A small
188/// local duplicate of `larust_http::random_hex`'s own few lines rather
189/// than adding `larust-http` as a dependency of this crate for one
190/// utility fn - the same "just call the primitive directly, don't share a
191/// bespoke wrapper" style every shim crate here already follows for
192/// `larust_orm::pool()`.
193fn random_hex(byte_len: usize) -> String {
194    let mut bytes = vec![0u8; byte_len];
195    rand::thread_rng().fill(&mut bytes[..]);
196    let mut hex = String::with_capacity(byte_len * 2);
197    for byte in bytes {
198        let _ = write!(hex, "{byte:02x}");
199    }
200    hex
201}
202
203/// Same lazy self-bootstrap idiom `larust-notifications`'s `ensure_table`
204/// establishes - plain `CREATE TABLE IF NOT EXISTS`, no migration file and
205/// no explicit startup call needed anywhere. Deliberately **not** memoized
206/// behind a `OnceCell`: `larust_testing::test_transaction`/a fresh
207/// per-test database means a process-wide completion flag can point at a
208/// since-discarded database - the exact regression that crate's own doc
209/// comment documents hitting once already. `IF NOT EXISTS` makes
210/// re-running this on every call cheap enough that giving up the
211/// memoization is the better trade.
212///
213/// `user_id` is a plain `INTEGER`, not a typed foreign key into an
214/// app-owned `users` table this crate has no visibility into - the same
215/// reasoning `larust-notifications`'s own `notifiable_id` column and
216/// `larust-permissions`'s own `user_id` columns already use.
217async fn ensure_table(pool: &AnyPool) -> Result<(), AppError> {
218    let create_table = match larust_orm::backend() {
219        Backend::Sqlite => {
220            "CREATE TABLE IF NOT EXISTS personal_access_tokens (\
221                id INTEGER PRIMARY KEY AUTOINCREMENT, \
222                user_id INTEGER NOT NULL, \
223                name TEXT NOT NULL, \
224                token_hash TEXT NOT NULL UNIQUE, \
225                expires_at INTEGER, \
226                last_used_at INTEGER, \
227                created_at INTEGER NOT NULL\
228             )"
229        }
230        // `VARCHAR`, not MySQL's own `TEXT` - confirmed empirically (a
231        // real, live MySQL server) that `sqlx`'s `Any` driver maps every
232        // MySQL `TEXT`-family column to its own generic `Blob` kind
233        // unconditionally, and `Decode<Any> for String` only accepts
234        // `Text`-kind values (only `CHAR`/`VARCHAR` map to `Any`'s `Text`
235        // kind; see `larust-http::session`'s own `AnySessionStore::migrate`
236        // for the same finding in more detail) - `name` is a short,
237        // caller-chosen token label, comfortably bounded.
238        Backend::MySql => {
239            "CREATE TABLE IF NOT EXISTS personal_access_tokens (\
240                id INTEGER PRIMARY KEY AUTO_INCREMENT, \
241                user_id INTEGER NOT NULL, \
242                name VARCHAR(255) NOT NULL, \
243                token_hash VARCHAR(255) NOT NULL UNIQUE, \
244                expires_at INTEGER, \
245                last_used_at INTEGER, \
246                created_at INTEGER NOT NULL\
247             )"
248        }
249        // Postgres has native, unbounded `TEXT` - same shape as SQLite's
250        // own arm.
251        Backend::Postgres => {
252            "CREATE TABLE IF NOT EXISTS personal_access_tokens (\
253                id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY, \
254                user_id INTEGER NOT NULL, \
255                name TEXT NOT NULL, \
256                token_hash TEXT NOT NULL UNIQUE, \
257                expires_at INTEGER, \
258                last_used_at INTEGER, \
259                created_at INTEGER NOT NULL\
260             )"
261        }
262    };
263    sqlx::query(create_table)
264        .execute(pool)
265        .await
266        .map_err(|source| AppError::Internal(Box::new(source)))?;
267    Ok(())
268}
269
270/// Issues a new token for `user`, returning the plaintext value
271/// (`"{id}|{plaintext}"`) - Laravel's `$user->createToken('name')`. This
272/// exact string is the only time the plaintext is ever available; only its
273/// hash is stored, so it can't be recovered from the database later (a
274/// stolen DB dump hands out no usable tokens). `ttl` mirrors
275/// `larust_cache::put`'s own optional-expiry convention - `None` for a
276/// token that never expires, matching Sanctum's own default.
277pub async fn create_token(
278    user: &impl Authenticatable,
279    name: &str,
280    ttl: Option<Duration>,
281) -> Result<String, AppError> {
282    let pool = larust_orm::pool()?;
283    ensure_table(pool).await?;
284
285    let plaintext = random_hex(32);
286    let token_hash = hash_token(&plaintext);
287    let created_at = now_unix_secs();
288    let expires_at = ttl.map(|ttl| created_at + ttl.as_secs() as i64);
289
290    let backend = larust_orm::backend();
291    let id: i64 = match backend {
292        // `AnyQueryResult::last_insert_id()` is unconditionally `None` for
293        // SQLite through sqlx's `Any` driver (confirmed by reading
294        // `sqlx-sqlite`'s own source - MySQL's `Any` adapter does populate
295        // it, so this is a SQLite-specific gap) - a portable `SELECT
296        // last_insert_rowid()`/`SELECT LAST_INSERT_ID()` follow-up query
297        // works on both backends instead. That value is connection-local
298        // session state, not something a query result carries, so the
299        // `INSERT` and this follow-up `SELECT` must share one acquired
300        // connection rather than two independent pool-level calls (which
301        // aren't guaranteed to land on the same physical connection).
302        Backend::Sqlite | Backend::MySql => {
303            let mut conn = pool
304                .acquire()
305                .await
306                .map_err(|source| AppError::Internal(Box::new(source)))?;
307            let insert_sql = format!(
308                "INSERT INTO personal_access_tokens \
309                 (user_id, name, token_hash, expires_at, created_at) VALUES \
310                 ({}, {}, {}, {}, {})",
311                larust_orm::placeholder(backend, 1),
312                larust_orm::placeholder(backend, 2),
313                larust_orm::placeholder(backend, 3),
314                larust_orm::placeholder(backend, 4),
315                larust_orm::placeholder(backend, 5),
316            );
317            sqlx::query(&insert_sql)
318                .bind(user.auth_id())
319                .bind(name)
320                .bind(&token_hash)
321                .bind(expires_at)
322                .bind(created_at)
323                .execute(&mut *conn)
324                .await
325                .map_err(|source| AppError::Internal(Box::new(source)))?;
326
327            let last_id_sql = match backend {
328                Backend::Sqlite => "SELECT last_insert_rowid()",
329                Backend::MySql => "SELECT LAST_INSERT_ID()",
330                Backend::Postgres => unreachable!(),
331            };
332            let (id,): (i64,) = sqlx::query_as(last_id_sql)
333                .fetch_one(&mut *conn)
334                .await
335                .map_err(|source| AppError::Internal(Box::new(source)))?;
336            id
337        }
338        // Postgres has neither `last_insert_rowid()` nor
339        // `LAST_INSERT_ID()` - its own idiomatic way to get a just-
340        // inserted row's generated key is `INSERT ... RETURNING id`
341        // directly, one statement instead of two, with no connection-
342        // affinity concern to manage at all.
343        Backend::Postgres => {
344            let (id,): (i64,) = sqlx::query_as(
345                "INSERT INTO personal_access_tokens \
346                 (user_id, name, token_hash, expires_at, created_at) VALUES \
347                 ($1, $2, $3, $4, $5) RETURNING id",
348            )
349            .bind(user.auth_id())
350            .bind(name)
351            .bind(&token_hash)
352            .bind(expires_at)
353            .bind(created_at)
354            .fetch_one(pool)
355            .await
356            .map_err(|source| AppError::Internal(Box::new(source)))?;
357            id
358        }
359    };
360
361    Ok(format!("{id}|{plaintext}"))
362}
363
364/// Revokes one token by its row id (the `id` portion of the token string
365/// returned by [`create_token`]) - Laravel's
366/// `$user->tokens()->where('id', $id)->delete()`. Not an error to revoke
367/// an id that doesn't exist or was already revoked, same "no meaningful
368/// double-removal error" reasoning `larust-notifications`'s `mark_as_read`
369/// already applies.
370pub async fn revoke_token(id: i64) -> Result<(), AppError> {
371    let pool = larust_orm::pool()?;
372    ensure_table(pool).await?;
373    let sql = format!(
374        "DELETE FROM personal_access_tokens WHERE id = {}",
375        larust_orm::placeholder(larust_orm::backend(), 1)
376    );
377    sqlx::query(&sql)
378        .bind(id)
379        .execute(pool)
380        .await
381        .map_err(|source| AppError::Internal(Box::new(source)))?;
382    Ok(())
383}
384
385/// Revokes every token `user` currently holds - Laravel's
386/// `$user->tokens()->delete()`, commonly used for a "log out everywhere"
387/// action.
388pub async fn revoke_all_tokens_for(user: &impl Authenticatable) -> Result<(), AppError> {
389    let pool = larust_orm::pool()?;
390    ensure_table(pool).await?;
391    let sql = format!(
392        "DELETE FROM personal_access_tokens WHERE user_id = {}",
393        larust_orm::placeholder(larust_orm::backend(), 1)
394    );
395    sqlx::query(&sql)
396        .bind(user.auth_id())
397        .execute(pool)
398        .await
399        .map_err(|source| AppError::Internal(Box::new(source)))?;
400    Ok(())
401}
402
403#[cfg(test)]
404mod tests {
405    use super::*;
406    use axum::routing::get;
407    use axum::Router;
408    use tower::ServiceExt;
409
410    #[derive(Clone)]
411    struct TestUser {
412        id: i64,
413    }
414
415    impl Authenticatable for TestUser {
416        fn auth_id(&self) -> i64 {
417            self.id
418        }
419
420        async fn find_for_auth(id: i64) -> Result<Option<Self>, AppError> {
421            // Mirrors a real `#[derive(Model)]`-backed lookup closely enough
422            // for these tests: id `1` exists, everything else doesn't -
423            // exercising the "token valid but the user is gone" rejection
424            // path without needing a real `users` table.
425            Ok((id == 1).then_some(TestUser { id }))
426        }
427    }
428
429    async fn connect_test_db() {
430        let dir = tempfile::tempdir().unwrap().keep();
431        let database_url = format!("sqlite://{}/test.sqlite", dir.display());
432        larust_orm::connect(&database_url).await.unwrap();
433    }
434
435    fn router() -> Router {
436        Router::new().route(
437            "/me",
438            get(|ApiAuth(user): ApiAuth<TestUser>| async move { user.id.to_string() }),
439        )
440    }
441
442    async fn get_with_auth_header(router: &Router, header: Option<&str>) -> (StatusCode, String) {
443        let mut request = axum::http::Request::get("/me");
444        if let Some(header) = header {
445            request = request.header(header::AUTHORIZATION, header);
446        }
447        let response = router
448            .clone()
449            .oneshot(request.body(axum::body::Body::empty()).unwrap())
450            .await
451            .unwrap();
452        let status = response.status();
453        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
454            .await
455            .unwrap();
456        (status, String::from_utf8(body.to_vec()).unwrap())
457    }
458
459    /// All scenarios share one test function, not several - `larust_orm::
460    /// connect()` sets a process-wide pool exactly once, the same
461    /// constraint `larust-permissions`'/`larust-notifications`'s own test
462    /// suites document and work around.
463    #[tokio::test]
464    async fn sanctum_crate_behaves_correctly_across_every_scenario() {
465        connect_test_db().await;
466        let router = router();
467        let alice = TestUser { id: 1 };
468
469        // No header at all, a header missing the `Bearer ` prefix, and a
470        // malformed token (no `|` separator) are all rejected before ever
471        // touching the database.
472        let (status, _) = get_with_auth_header(&router, None).await;
473        assert_eq!(status, StatusCode::UNAUTHORIZED);
474        let (status, _) = get_with_auth_header(&router, Some("not-bearer-shaped")).await;
475        assert_eq!(status, StatusCode::UNAUTHORIZED);
476        let (status, _) = get_with_auth_header(&router, Some("Bearer no-pipe-here")).await;
477        assert_eq!(status, StatusCode::UNAUTHORIZED);
478
479        // A freshly created token authenticates successfully.
480        let token = create_token(&alice, "test-token", None).await.unwrap();
481        let (status, body) = get_with_auth_header(&router, Some(&format!("Bearer {token}"))).await;
482        assert_eq!(status, StatusCode::OK);
483        assert_eq!(body, "1");
484
485        // A well-formed-but-wrong token (right id, wrong plaintext) fails.
486        let (id_part, _) = token.split_once('|').unwrap();
487        let wrong = format!(
488            "Bearer {id_part}|0000000000000000000000000000000000000000000000000000000000000000"
489        );
490        let (status, _) = get_with_auth_header(&router, Some(&wrong)).await;
491        assert_eq!(status, StatusCode::UNAUTHORIZED);
492
493        // An unknown row id fails too (never created, or already deleted).
494        let (status, _) = get_with_auth_header(&router, Some("Bearer 999999|whatever")).await;
495        assert_eq!(status, StatusCode::UNAUTHORIZED);
496
497        // last_used_at was populated by the successful auth above.
498        let pool = larust_orm::pool().unwrap();
499        let (id_num,): (i64,) =
500            sqlx::query_as("SELECT id FROM personal_access_tokens WHERE user_id = ? AND name = ?")
501                .bind(alice.id)
502                .bind("test-token")
503                .fetch_one(pool)
504                .await
505                .unwrap();
506        let (last_used,): (Option<i64>,) =
507            sqlx::query_as("SELECT last_used_at FROM personal_access_tokens WHERE id = ?")
508                .bind(id_num)
509                .fetch_one(pool)
510                .await
511                .unwrap();
512        assert!(last_used.is_some());
513
514        // A token issued with a TTL in the past is rejected as expired.
515        let expired = create_token(&alice, "expired", Some(Duration::from_secs(0)))
516            .await
517            .unwrap();
518        // `now_unix_secs() + 0` can equal "now" exactly, and the expiry
519        // check is `<=` - give it a moment so the clock has definitely
520        // moved past `expires_at`.
521        tokio::time::sleep(Duration::from_millis(1100)).await;
522        let (status, _) = get_with_auth_header(&router, Some(&format!("Bearer {expired}"))).await;
523        assert_eq!(status, StatusCode::UNAUTHORIZED);
524
525        // Revoking a token invalidates it immediately.
526        revoke_token(id_num).await.unwrap();
527        let (status, _) = get_with_auth_header(&router, Some(&format!("Bearer {token}"))).await;
528        assert_eq!(status, StatusCode::UNAUTHORIZED);
529
530        // revoke_all_tokens_for revokes every token a user holds, not just
531        // one - bob has two, alice (id 1) is untouched.
532        let bob = TestUser { id: 2 };
533        let bob_token_a = create_token(&bob, "a", None).await.unwrap();
534        let bob_token_b = create_token(&bob, "b", None).await.unwrap();
535        revoke_all_tokens_for(&bob).await.unwrap();
536        for token in [bob_token_a, bob_token_b] {
537            let (status, _) = get_with_auth_header(&router, Some(&format!("Bearer {token}"))).await;
538            assert_eq!(status, StatusCode::UNAUTHORIZED);
539        }
540
541        // A token for a user id `find_for_auth` can't resolve (deleted
542        // after issuance) fails at the final step, not the lookup itself.
543        let ghost = TestUser { id: 404 };
544        let ghost_token = create_token(&ghost, "ghost", None).await.unwrap();
545        let (status, _) =
546            get_with_auth_header(&router, Some(&format!("Bearer {ghost_token}"))).await;
547        assert_eq!(status, StatusCode::UNAUTHORIZED);
548    }
549}