rustango 0.60.7

Batteries-included web framework for Rust: ORM + migrations + auto-admin + multi-tenancy + audit log + auth (sessions, JWT, OAuth2/OIDC, HMAC) + APIs (ViewSet, OpenAPI auto-derive, JSON:API) + jobs (in-mem + Postgres) + email + media (S3 / R2 / B2 / MinIO + presigned uploads + collections + tags) + production middleware (CSRF, CSP, rate-limiting, compression, idempotency, etc.).
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
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
//! Pluggable authentication backends.
//!
//! Register one or more backends with the server builder or tenant admin;
//! requests are authenticated by trying each backend in registration order.
//! First `Ok(Some(user))` wins; all `Ok(None)` → anonymous.
//!
//! # Built-in backends
//!
//! | Backend | How it reads the identity |
//! |---|---|
//! | [`ModelBackend`] | `Authorization: Basic <b64(user:pass)>` — or form fields `username` / `password` |
//! | [`ApiKeyBackend`] | `Authorization: Bearer <key>` against `rustango_api_keys` |
//! | [`JwtBackend`] | `Authorization: Bearer <jwt>` — HMAC-SHA256 signed, user id in `sub` |
//!
//! # Custom backend
//!
//! ```ignore
//! use rustango::tenancy::auth_backends::{AuthBackend, AuthUser, AuthError};
//! use async_trait::async_trait;
//!
//! pub struct MyBackend;
//!
//! #[async_trait]
//! impl AuthBackend for MyBackend {
//!     async fn authenticate(
//!         &self,
//!         parts: &axum::http::request::Parts,
//!         pool: &rustango::sql::sqlx::PgPool,
//!     ) -> Result<Option<AuthUser>, AuthError> {
//!         // read a custom header, verify, return Some(AuthUser { .. })
//!         Ok(None)
//!     }
//! }
//! ```

use std::sync::Arc;

use async_trait::async_trait;
use axum::http::request::Parts;

use crate::sql::sqlx;
use crate::sql::Pool;

use super::auth::parse_basic_auth;
use super::password;
use super::password::HashLane;
use crate::login_throttle::{ClientIp, LoginAttempt, LoginScope};

// ------------------------------------------------------------------ AuthUser

/// Authenticated identity returned by a successful backend.
#[derive(Debug, Clone)]
pub struct AuthUser {
    /// `rustango_users.id`
    pub id: i64,
    /// Login handle.
    pub username: String,
    /// Org-admin within this tenant.
    pub is_superuser: bool,
}

// ------------------------------------------------------------------ AuthError

/// Error returned by a backend that hard-fails (as opposed to `Ok(None)`
/// which means "I can't handle this request, try the next backend").
#[derive(Debug, thiserror::Error)]
pub enum AuthError {
    #[error("database error: {0}")]
    Database(#[from] sqlx::Error),
    #[error("database error: {0}")]
    Exec(#[from] crate::sql::ExecError),
    #[error("token is malformed or expired")]
    InvalidToken,
    #[error("account is inactive")]
    Inactive,
    /// Locked out or password hashing busy; answer with its response.
    #[error("login refused: {0:?}")]
    Refused(crate::login_throttle::LoginRefused),
}

impl AuthError {
    /// A hashing error: busy is [`LoginRefused::Busy`], anything else an
    /// invalid credential.
    ///
    /// [`LoginRefused::Busy`]: crate::login_throttle::LoginRefused::Busy
    fn from_hash(e: super::TenancyError) -> Self {
        match e {
            super::TenancyError::Busy => Self::Refused(crate::login_throttle::LoginRefused::Busy),
            _ => Self::InvalidToken,
        }
    }
}

/// Admit one per-request credential check for this request's tenant and
/// client. Refuses without a tenant, so tenants never share limits.
async fn begin(
    parts: &Parts,
    scope: fn(String) -> LoginScope,
    username: &str,
) -> Result<LoginAttempt, AuthError> {
    let slug = tenant_slug(parts)?;
    crate::login_throttle::shared()
        .begin(&scope(slug.to_owned()), &client_ip(parts), username)
        .await
        .map_err(AuthError::Refused)
}

fn client_ip(parts: &Parts) -> ClientIp {
    parts
        .extensions
        .get::<ClientIp>()
        .cloned()
        .unwrap_or_else(|| ClientIp::from_parts(&parts.extensions, &parts.headers))
}

fn tenant_slug(parts: &Parts) -> Result<&str, AuthError> {
    match parts.extensions.get::<super::TenantSlug>() {
        Some(slug) => Ok(&slug.0),
        None => {
            tracing::error!(
                "auth backend ran without a TenantSlug; use require_auth / optional_auth"
            );
            Err(AuthError::InvalidToken)
        }
    }
}

/// How long a verified Basic credential skips argon2 (#2617).
const BASIC_CACHE_TTL: std::time::Duration = std::time::Duration::from_secs(30);
/// Entries the Basic cache holds before it evicts.
const BASIC_CACHE_CAP: usize = 1024;

type BasicCache = std::collections::HashMap<[u8; 32], (i64, std::time::Instant)>;

fn basic_cache() -> &'static std::sync::Mutex<BasicCache> {
    static CACHE: std::sync::OnceLock<std::sync::Mutex<BasicCache>> = std::sync::OnceLock::new();
    CACHE.get_or_init(|| std::sync::Mutex::new(BasicCache::new()))
}

/// SHA-256 over the tenant, the credential and the stored hash. A password
/// change rewrites the hash, so it misses; `active` is read per request.
fn basic_cache_key(slug: &str, username: &str, password: &str, stored_hash: &str) -> [u8; 32] {
    use sha2::Digest as _;
    let mut hasher = sha2::Sha256::new();
    for part in [slug, username, password, stored_hash] {
        hasher.update((part.len() as u64).to_le_bytes());
        hasher.update(part.as_bytes());
    }
    hasher.finalize().into()
}

fn basic_cache_hit(key: &[u8; 32], user_id: i64) -> bool {
    let Ok(cache) = basic_cache().lock() else {
        return false;
    };
    cache
        .get(key)
        .is_some_and(|(id, at)| *id == user_id && at.elapsed() < BASIC_CACHE_TTL)
}

fn basic_cache_put(key: [u8; 32], user_id: i64) {
    let Ok(mut cache) = basic_cache().lock() else {
        return;
    };
    if cache.len() >= BASIC_CACHE_CAP && !cache.contains_key(&key) {
        cache.retain(|_, (_, at)| at.elapsed() < BASIC_CACHE_TTL);
        if cache.len() >= BASIC_CACHE_CAP {
            let oldest = cache.iter().min_by_key(|(_, (_, at))| *at).map(|(k, _)| *k);
            if let Some(oldest) = oldest {
                cache.remove(&oldest);
            }
        }
    }
    cache.insert(key, (user_id, std::time::Instant::now()));
}

// ------------------------------------------------------------------ Trait

/// An authentication backend. Implement this to add custom auth strategies.
///
/// Each backend is called in registration order. Return:
/// - `Ok(Some(user))` — authentication succeeded.
/// - `Ok(None)` — this backend doesn't handle the request; try the next one.
/// - `Err(_)` — hard failure (wrong password, expired token, DB error).
#[async_trait]
pub trait AuthBackend: Send + Sync {
    async fn authenticate(&self, parts: &Parts, pool: &Pool)
        -> Result<Option<AuthUser>, AuthError>;
}

/// Heap-allocated dyn backend.
pub type BoxedBackend = Arc<dyn AuthBackend>;

// ------------------------------------------------------------------ ModelBackend

/// Username + password backend. Reads `Authorization: Basic <b64>` and
/// verifies against `rustango_users` with argon2id.
///
/// This is the default backend.
pub struct ModelBackend;

#[async_trait]
impl AuthBackend for ModelBackend {
    async fn authenticate(
        &self,
        parts: &Parts,
        pool: &Pool,
    ) -> Result<Option<AuthUser>, AuthError> {
        use crate::core::Column as _;
        use crate::sql::FetcherPool as _;

        let auth_header = parts
            .headers
            .get(axum::http::header::AUTHORIZATION)
            .and_then(|v| v.to_str().ok());

        let (username, password) = match parse_basic_auth(auth_header) {
            Some(pair) => pair,
            None => return Ok(None),
        };

        // Own lock scope, apart from the login forms; only failures count.
        // A locked or spent caller is refused before the lookup.
        let slug = tenant_slug(parts)?;
        let scope = LoginScope::TenantBasic(slug.to_owned());
        let ip = client_ip(parts);
        let throttle = crate::login_throttle::shared();
        let refused = AuthError::Refused;
        throttle
            .check(&scope, &ip, &username)
            .await
            .map_err(refused)?;
        let users = super::auth::User::objects()
            .where_(super::auth::User::username.eq(username.clone()))
            .fetch(pool)
            .await?;
        let user = users.into_iter().next();

        // A credential verified moments ago against this same stored hash
        // skips argon2 and the limits: it is not a guess (#2617).
        let cache_key = user
            .as_ref()
            .map(|u| basic_cache_key(slug, &username, &password, &u.password_hash));
        let cached = |u: &super::auth::User| {
            let uid = u.id.get().copied().unwrap_or(0);
            let key = cache_key.as_ref()?;
            (u.active && uid != 0 && basic_cache_hit(key, uid)).then(|| AuthUser {
                id: uid,
                username: u.username.clone(),
                is_superuser: u.is_superuser,
            })
        };
        if let Some(hit) = user.as_ref().and_then(cached) {
            // The stored name's lock too, when the submitted one differs.
            if hit.username != username {
                throttle
                    .check(&scope, &ip, &hit.username)
                    .await
                    .map_err(refused)?;
            }
            return Ok(Some(hit));
        }

        let mut attempt = throttle
            .begin(&scope, &ip, &username)
            .await
            .map_err(refused)?;

        let Some(user) = user else {
            // Audit H1/N4 — spend a verify's worth of work on the
            // unknown-user path so timing doesn't reveal whether the
            // username exists.
            password::verify_dummy_async_in(HashLane::Credential, &password)
                .await
                .map_err(AuthError::from_hash)?;
            attempt.failed().await;
            return Ok(None);
        };
        attempt
            .resolve(&user.username)
            .await
            .map_err(AuthError::Refused)?;
        // A parallel request may have verified it while this one waited.
        if let Some(hit) = cached(&user) {
            attempt.succeeded().await;
            return Ok(Some(hit));
        }

        // Verify before the active check so active vs inactive accounts
        // take the same time (audit H1/N4).
        let ok = password::verify_async_in(HashLane::Credential, &password, &user.password_hash)
            .await
            .map_err(AuthError::from_hash)?;
        if !user.active || !ok {
            attempt.failed().await;
            // Audit N4 — an inactive account must look identical to a
            // wrong password at this (username-keyed, pre-credential)
            // boundary: same `Ok(None)`, not a distinguishable
            // `Err(Inactive)`, so the backend can't be used to enumerate
            // accounts. (Inactive is still enforced after a *valid* API
            // key / JWT below, where the caller already proved ownership.)
            return Ok(None);
        }

        attempt.succeeded().await;
        let id = user.id.get().copied().unwrap_or(0);
        if let (Some(key), true) = (cache_key, id != 0) {
            basic_cache_put(key, id);
        }
        Ok(Some(AuthUser {
            id,
            username: user.username,
            is_superuser: user.is_superuser,
        }))
    }
}

// ------------------------------------------------------------------ ApiKey model + backend

/// An API key for a tenant user. Keys are stored hashed; the full
/// token is only returned at creation time.
///
/// Query with the ORM:
/// ```ignore
/// let keys = ApiKey::objects()
///     .where_(ApiKey::user_id.eq(alice_id))
///     .fetch(&pool)
///     .await?;
/// ```
#[derive(crate::Model, Debug, Clone)]
#[rustango(
    table = "rustango_api_keys",
    admin(
        list_display = "user_id, key_prefix, label, expires_at, created_at",
        ordering = "-created_at",
        readonly_fields = "key_prefix, key_hash, created_at",
    )
)]
pub struct ApiKey {
    #[rustango(primary_key)]
    pub id: crate::sql::Auto<i64>,
    /// `rustango_users.id`
    #[rustango(fk = "rustango_users", on = "id", on_delete = "cascade")]
    pub user_id: i64,
    /// 8-char hex prefix — public, used to look up the row. Stored in
    /// plaintext by design (it's the lookup index). Audit L4: this is an
    /// accepted, minor exposure — a DB leak reveals which prefixes exist
    /// but NOT the secret (only its keyed MAC is in `key_hash`), so a
    /// stolen prefix can't authenticate on its own.
    ///
    /// Indexed: every Bearer request looks the row up by this column,
    /// so without one it is a sequential scan on the hit path — 5.9 ms
    /// at 100k keys against 0.025 ms indexed, growing with every key
    /// ever issued (#1647).
    #[rustango(max_length = 8, index)]
    pub key_prefix: String,
    /// `hmac-sha256$<hex>` keyed by the server secret (#2617); keys made
    /// before that hold argon2id until first used. Never returned to callers.
    #[rustango(max_length = 255)]
    pub key_hash: String,
    /// Human-readable label (e.g. "CI pipeline key").
    #[rustango(max_length = 100)]
    pub label: String,
    /// Optional expiry. `None` = never expires.
    pub expires_at: Option<chrono::DateTime<chrono::Utc>>,
    /// Set on INSERT via `DEFAULT NOW()`.
    #[rustango(auto_now_add)]
    pub created_at: crate::sql::Auto<chrono::DateTime<chrono::Utc>>,
}

// A key is minted by `create-api-key`, which shows the secret once; an admin
// form could only store a row nobody can use (#1763).
#[cfg(feature = "admin")]
crate::register_admin_object_permission!("rustango_api_keys", "add", |_, _| false);
// The owner decides who the credential signs in as (#2520).
#[cfg(feature = "admin")]
crate::register_admin_superuser_fields!(ApiKey, Change, [user_id]);

/// Create the `rustango_api_keys` table if it doesn't exist.
///
/// PG-typed back-compat for legacy callers; new code should use
/// [`ensure_api_keys_table_pool`] which picks the right per-dialect
/// DDL constant via `pool.dialect().name()`.
///
/// #562 — delegates to [`ensure_api_keys_table_pool`] so the
/// statement-splitting loop lives in one place.
///
/// # Errors
/// Driver failures.
#[cfg(feature = "postgres")]
pub async fn ensure_api_keys_table(pool: &crate::sql::sqlx::PgPool) -> Result<(), sqlx::Error> {
    ensure_api_keys_table_pool(&crate::sql::Pool::from(pool.clone())).await
}

/// v0.38 — tri-dialect counterpart of [`ensure_api_keys_table`].
/// Picks the per-dialect DDL constant based on `pool.dialect().name()`
/// and runs each statement separately (sqlx's simple-prepare rejects
/// multi-statement strings).
///
/// # Errors
/// Driver / SQL failures from `CREATE TABLE IF NOT EXISTS`.
pub async fn ensure_api_keys_table_pool(pool: &Pool) -> Result<(), sqlx::Error> {
    // Drift-free (v0.47): emit `rustango_api_keys` from `ApiKey::SCHEMA`
    // via the migration render path instead of hand-written per-dialect
    // DDL. Idempotent (swallows "already exists").
    use crate::core::Model as _;
    let snapshot = crate::migrate::SchemaSnapshot::from_models(&[ApiKey::SCHEMA]);
    crate::migrate::apply_idempotent(pool, &snapshot).await?;
    Ok(())
}

/// `Authorization: Bearer <key>` backend. Keys are stored hashed;
/// the bearer token format is `<8-char prefix>.<secret>`.
///
/// Generate a key with `cargo run -- create-api-key <username>`.
pub struct ApiKeyBackend;

#[async_trait]
impl AuthBackend for ApiKeyBackend {
    async fn authenticate(
        &self,
        parts: &Parts,
        pool: &Pool,
    ) -> Result<Option<AuthUser>, AuthError> {
        use crate::core::Column as _;
        use crate::sql::FetcherPool as _;

        let bearer = extract_bearer(parts)?;
        let Some(token) = bearer else {
            return Ok(None);
        };

        // Format: "<prefix>.<secret>"
        let (prefix, secret) = match token.split_once('.') {
            Some(p) => p,
            None => return Ok(None), // Not an API key format
        };

        if prefix.len() != 8 {
            return Ok(None);
        }

        // Two indexed ORM round-trips: the key by prefix, then its user.
        // Failures per IP and per tenant; no lock, the prefix is no account.
        let attempt = begin(parts, LoginScope::TenantApiKey, "").await?;
        let mac = api_key_mac(api_key_secret().map_err(AuthError::from_hash)?, secret);
        let keys = ApiKey::objects()
            .where_(ApiKey::key_prefix.eq(prefix.to_owned()))
            .fetch(pool)
            .await?;
        // The prefix is random, not unique: try every row (#2250).
        let (macs, legacy): (Vec<_>, Vec<_>) = keys
            .into_iter()
            .partition(|k| k.key_hash.starts_with(API_KEY_MAC_SCHEME));
        let key = match macs.into_iter().find(|k| mac_eq(&k.key_hash, &mac)) {
            Some(k) => Some(k),
            None if legacy.is_empty() => None,
            // Pre-#2617 argon2 rows: verify once, then store the MAC.
            None => {
                let key = password::first_verified(legacy, secret, |k| &k.key_hash)
                    .await
                    .map_err(AuthError::from_hash)?;
                if let Some(k) = &key {
                    upgrade_api_key(pool, k, &mac).await;
                }
                key
            }
        };
        let Some(key) = key else {
            attempt.failed().await;
            return Ok(None);
        };

        // Verify before judging expiry, so an expired prefix costs the
        // same as an unknown one (#1729).
        if key.expires_at.is_some_and(|exp| chrono::Utc::now() > exp) {
            return Err(AuthError::InvalidToken);
        }
        attempt.succeeded().await;

        let users = super::auth::User::objects()
            .where_(super::auth::User::id.eq(key.user_id))
            .fetch(pool)
            .await?;
        let Some(user) = users.into_iter().next() else {
            return Ok(None);
        };
        if !user.active {
            return Err(AuthError::Inactive);
        }

        Ok(Some(AuthUser {
            id: user.id.get().copied().unwrap_or(0),
            username: user.username,
            is_superuser: user.is_superuser,
        }))
    }
}

/// `key_hash` prefix of a key stored as an HMAC; anything else is argon2.
const API_KEY_MAC_SCHEME: &str = "hmac-sha256$";
/// Domain tag, so a key MAC is never a valid MAC of anything else.
const API_KEY_MAC_TAG: &[u8] = b"rustango-apikey-v1.";

static API_KEY_SECRET: std::sync::OnceLock<crate::session::SessionSecret> =
    std::sync::OnceLock::new();

/// Set the key that MACs API keys. The first call wins; returns `false` after.
/// Unset, it is `RUSTANGO_SESSION_SECRET`, or in dev the tenant session key file.
pub fn set_api_key_secret(secret: crate::session::SessionSecret) -> bool {
    API_KEY_SECRET.set(secret).is_ok()
}

/// The CLI that mints a key and the server that checks it must agree, so
/// this reads the env or the dev key file, never a per-process random key.
fn api_key_secret() -> Result<&'static crate::session::SessionSecret, super::TenancyError> {
    use crate::session::{is_prod_tier, tier_from_env, SessionSecret};
    if let Some(s) = API_KEY_SECRET.get() {
        return Ok(s);
    }
    let secret = if is_prod_tier(&tier_from_env()) {
        SessionSecret::require_from_env().map_err(|e| {
            tracing::error!(error = %e, "API keys need RUSTANGO_SESSION_SECRET on the prod tier");
            super::TenancyError::Validation(e.to_string())
        })?
    } else {
        SessionSecret::from_env_or_disk(std::path::Path::new(
            crate::session::TENANT_SESSION_KEY_PATH,
        ))
    };
    Ok(API_KEY_SECRET.get_or_init(|| secret))
}

/// `hmac-sha256$<hex>` of the secret half; the prefix is only the lookup.
fn api_key_mac(key: &crate::session::SessionSecret, secret: &str) -> String {
    let msg = [API_KEY_MAC_TAG, secret.as_bytes()].concat();
    format!(
        "{API_KEY_MAC_SCHEME}{}",
        to_hex(&crate::session::sign(key, &msg))
    )
}

fn mac_eq(stored: &str, mac: &str) -> bool {
    use subtle::ConstantTimeEq as _;
    stored.len() == mac.len() && bool::from(stored.as_bytes().ct_eq(mac.as_bytes()))
}

/// Swap a verified argon2 hash for the MAC. A failure only costs one more
/// argon2 next time, so it is logged, not raised.
async fn upgrade_api_key(pool: &Pool, key: &ApiKey, mac: &str) {
    use crate::core::Column as _;
    use crate::sql::UpdaterPool as _;
    let Some(id) = key.id.get().copied() else {
        return;
    };
    if let Err(e) = ApiKey::objects()
        .where_(ApiKey::id.eq(id))
        .update()
        .set("key_hash", mac.to_owned())
        .execute_pool(pool)
        .await
    {
        tracing::warn!(error = %e, key_id = id, "could not upgrade an argon2 API key");
    }
}

/// Create an API key for `user_id`. Returns the full token (`prefix.secret`)
/// — this is the only time the plaintext is available.
///
/// # Errors
/// Driver errors.
pub async fn create_api_key(
    user_id: i64,
    label: &str,
    expires_at: Option<chrono::DateTime<chrono::Utc>>,
    pool: &Pool,
) -> Result<String, crate::tenancy::error::TenancyError> {
    use crate::sql::Auto;
    use rand::rngs::OsRng;
    use rand::RngCore;

    // v0.42 — API key prefix + secret source from the OS CSPRNG. The
    // 16-byte secret is the actual bearer credential; a predictable
    // RNG here would compromise every key issued by the affected
    // process.
    let mut prefix_bytes = [0u8; 4];
    OsRng.fill_bytes(&mut prefix_bytes);
    let prefix = to_hex(&prefix_bytes);
    let mut secret_bytes = [0u8; 16];
    OsRng.fill_bytes(&mut secret_bytes);
    let secret = to_hex(&secret_bytes);

    let hash = api_key_mac(api_key_secret()?, &secret);

    let mut key = ApiKey {
        id: Auto::default(),
        user_id,
        key_prefix: prefix.clone(),
        key_hash: hash,
        label: label.to_owned(),
        expires_at,
        created_at: Auto::default(),
    };
    key.save_pool(pool).await?;

    Ok(format!("{prefix}.{secret}"))
}

// ------------------------------------------------------------------ JwtBackend

/// HMAC-SHA256 signed JWT backend. The JWT payload is
/// `{"sub": <user_id>, "exp": <unix_seconds>}`. Uses the same
/// [`SessionSecret`] as the admin session cookie.
///
/// [`SessionSecret`]: super::operator_console::SessionSecret
///
/// v0.38 — `from_session_secret` + the verify/issue impls depend on
/// `operator_console::session::sign` which is PG-gated until slice 5.
/// The backend struct + `new()` stay unconditional so projects can
/// still register it (sqlite/mysql apps would build the secret bytes
/// themselves until then).
pub struct JwtBackend {
    secret: Vec<u8>,
    /// Same key, for the login-session `pwf` claim (#2247).
    pwf_secret: crate::session::SessionSecret,
    /// Token lifetime in seconds for tokens issued via [`JwtBackend::issue`].
    pub ttl_secs: i64,
    /// Revocation list consulted on every authentication (#1402).
    ///
    /// `None` means revocation is not enforced on this backend, which is
    /// the pre-0.57.3 behaviour and stays the default only because
    /// turning it on silently would change what an existing deployment's
    /// tokens do. Set it with [`JwtBackend::with_jti_store`], passing the
    /// **same** store the issuing [`JwtLifecycle`] holds — two stores
    /// mean logout writes to one and verification reads the other.
    jti_store: Option<std::sync::Arc<dyn crate::jti_store::JtiStore>>,
    /// Set once this backend has warned that revocation is not checked.
    warned_unchecked: std::sync::atomic::AtomicBool,
}

impl JwtBackend {
    /// Build a backend from raw key bytes.
    ///
    /// # Panics
    /// If `secret` is shorter than 32 bytes (audit N5). HMAC accepts any
    /// key length, but a short/empty key is guessable and would let
    /// anyone forge tokens — fail closed rather than sign/verify with a
    /// weak key. Matches the 32-byte floor on `auth_routes::build_jwt`.
    #[must_use]
    pub fn new(secret: Vec<u8>) -> Self {
        // No `secret.len()` in the message — same reason as
        // `JwtLifecycle::new`: a panic message reaches logs and crash
        // reports, and the length of a key is information about it.
        assert!(
            secret.len() >= 32,
            "JwtBackend signing key is too short; need >= 32 bytes (a shorter key is forgeable)",
        );
        Self {
            pwf_secret: crate::session::SessionSecret::from_bytes(secret.clone()),
            secret,
            ttl_secs: 3600,
            jti_store: None,
            warned_unchecked: std::sync::atomic::AtomicBool::new(false),
        }
    }

    /// Enforce revocation on this backend (#1402).
    ///
    /// Pass the **same** store the issuing
    /// [`JwtLifecycle`](crate::tenancy::jwt_lifecycle::JwtLifecycle)
    /// holds. Without
    /// this, `revoke()` and `/api/auth/logout` write to a blacklist that
    /// nothing on the authentication path reads — a revoked token keeps
    /// authenticating until it expires, and a deployment can watch a
    /// shared Redis store fill with JTIs that all still work.
    ///
    /// Without it, a single-login logout and a refresh-replay revoke go
    /// unseen; a password change and logout-all still end the token (#2247).
    ///
    /// Off by default because turning it on changes what an existing
    /// deployment's live tokens do, which is not a thing to do silently
    /// in a patch release.
    #[must_use]
    pub fn with_jti_store(mut self, store: std::sync::Arc<dyn crate::jti_store::JtiStore>) -> Self {
        self.jti_store = Some(store);
        self
    }

    /// A revocable token met a backend with no store: say so, once (#1809).
    fn warn_unchecked_revocation(&self) {
        use std::sync::atomic::Ordering;
        if !self.warned_unchecked.swap(true, Ordering::Relaxed) {
            tracing::warn!(
                target: "rustango::tenancy",
                "JwtBackend has no JTI store, so tokens are not checked for revocation: a \
                 logged-out token works until it expires; call `with_jti_store`"
            );
        }
    }

    /// Build from the operator-console session secret (convenient for
    /// projects that don't want a separate signing key).
    #[cfg(feature = "postgres")]
    #[must_use]
    pub fn from_session_secret(s: &super::operator_console::SessionSecret) -> Self {
        Self::new(s.key().to_vec())
    }

    /// Issue a signed JWT for `user_id` valid for `self.ttl_secs`, with no
    /// tenant binding: it authenticates only where no tenant is resolved.
    #[must_use]
    pub fn issue(&self, user_id: i64) -> String {
        self.sign_payload(&serde_json::json!({"sub": user_id, "exp": self.exp()}))
    }

    /// [`Self::issue`] bound to tenant `slug`, for `require_auth` routes (#1848).
    #[must_use]
    pub fn issue_for_tenant(&self, user_id: i64, slug: &str) -> String {
        let mut payload = serde_json::json!({"sub": user_id, "exp": self.exp()});
        payload[super::jwt_lifecycle::CLAIM_TENANT] = slug.into();
        self.sign_payload(&payload)
    }

    fn exp(&self) -> i64 {
        chrono::Utc::now().timestamp() + self.ttl_secs
    }

    fn sign_payload(&self, payload: &serde_json::Value) -> String {
        use base64::Engine;
        let payload_b64 = base64::engine::general_purpose::URL_SAFE_NO_PAD
            .encode(serde_json::to_vec(payload).unwrap_or_default());
        let sig = hmac_sha256(&self.secret, payload_b64.as_bytes());
        let sig_b64 = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(sig);
        format!("{payload_b64}.{sig_b64}")
    }

    /// Verify and return `(sub, jti, login session)`.
    ///
    /// Accepts both token shapes. Three segments is what `JwtLifecycle`
    /// issues since #1397 and what any standard JWT looks like; two is
    /// what `JwtBackend::issue` still emits and what `JwtLifecycle` emitted
    /// before it. Signing input differs — `header.payload` for the former,
    /// `payload` alone for the latter — so each is checked against its own.
    ///
    /// Handling both is not politeness: `docs/auth-jwt-api.md` tells you to
    /// pair this backend with `JwtLifecycle`, and between #1397 and this
    /// change that pairing silently stopped authenticating anyone, because
    /// the caller below required exactly one dot.
    ///
    /// **Refresh tokens are refused.** They carry `typ: "refresh"` and are
    /// wire-identical to access tokens, so without this check one
    /// authenticates as a bearer credential with the refresh token's much
    /// longer life — seven days by default (#1402).
    ///
    /// The tenant binding and `kind` go through [`UserTokenScope`] (#1848).
    ///
    /// [`UserTokenScope`]: super::jwt_lifecycle::UserTokenScope
    fn verify_claims(
        &self,
        token: &str,
        scope: super::jwt_lifecycle::UserTokenScope<'_>,
    ) -> Option<(
        i64,
        Option<String>,
        Option<super::auth_routes::RefreshSession>,
    )> {
        use base64::Engine;
        use subtle::ConstantTimeEq;
        let b64 = base64::engine::general_purpose::URL_SAFE_NO_PAD;

        let parts: Vec<&str> = token.split('.').collect();
        let (signing_input, payload_b64, sig_b64) = match parts.as_slice() {
            [header, payload, sig] => {
                // Pin the algorithm. The HMAC below catches a swapped one
                // anyway, but refusing here makes `alg: none` fail as
                // itself rather than as a signature mismatch.
                let h: serde_json::Value =
                    serde_json::from_slice(&b64.decode(header).ok()?).ok()?;
                if h.get("alg").and_then(serde_json::Value::as_str) != Some("HS256") {
                    return None;
                }
                (format!("{header}.{payload}"), *payload, *sig)
            }
            [payload, sig] => ((*payload).to_owned(), *payload, *sig),
            _ => return None,
        };

        let expected = hmac_sha256(&self.secret, signing_input.as_bytes());
        let provided = b64.decode(sig_b64).ok()?;
        if expected.ct_eq(&provided[..]).unwrap_u8() == 0 {
            return None;
        }

        let payload: serde_json::Value =
            serde_json::from_slice(&b64.decode(payload_b64).ok()?).ok()?;
        let exp = payload.get("exp")?.as_i64()?;
        if chrono::Utc::now().timestamp() >= exp {
            return None; // expired
        }
        // Absent `typ` is a `JwtBackend::issue` token, which is an access
        // credential by construction. Present-and-not-"access" is refused.
        if let Some(typ) = payload.get("typ").and_then(serde_json::Value::as_str) {
            if typ != "access" {
                return None;
            }
        }
        let claims = payload.as_object()?;
        scope.admits(claims).ok()?;
        let sub = payload.get("sub")?.as_i64()?;
        let jti = payload
            .get("jti")
            .and_then(serde_json::Value::as_str)
            .map(str::to_owned);
        Some((sub, jti, super::auth_routes::RefreshSession::read(claims)))
    }
}

/// v0.38 — inline HMAC-SHA256(secret, msg) so JwtBackend signs
/// without depending on the PG-gated `operator_console::session::sign`.
/// Equivalent to the shared primitive — same `hmac` + `sha2` crates.
fn hmac_sha256(secret: &[u8], msg: &[u8]) -> [u8; 32] {
    use hmac::{Hmac, Mac};
    use sha2::Sha256;
    let mut mac = Hmac::<Sha256>::new_from_slice(secret).expect("HMAC accepts any key length");
    mac.update(msg);
    let bytes = mac.finalize().into_bytes();
    let mut out = [0u8; 32];
    out.copy_from_slice(&bytes[..32]);
    out
}

#[async_trait]
impl AuthBackend for JwtBackend {
    async fn authenticate(
        &self,
        parts: &Parts,
        pool: &Pool,
    ) -> Result<Option<AuthUser>, AuthError> {
        use crate::core::Column as _;
        use crate::sql::FetcherPool as _;

        let bearer = extract_bearer(parts)?;
        let Some(token) = bearer else {
            return Ok(None);
        };

        // A JWT is two dots (`header.payload.sig`) since #1397, or one for
        // the legacy shape `JwtBackend::issue` still emits. An API key is
        // also one dot (`prefix.secret`), distinguished by its 8-char hex
        // prefix — a base64 JWT payload is never 8 characters.
        //
        // This used to require *exactly* one dot, which meant a real JWT
        // was handed back as "not mine" before verification ran. Between
        // #1397 and #1402 that silently stopped `JwtLifecycle` tokens
        // authenticating through the backend chain the docs tell you to
        // pair them with.
        let dots = token.chars().filter(|&c| c == '.').count();
        if dots != 1 && dots != 2 {
            return Ok(None);
        }
        if dots == 1 && token.split_once('.').map(|(p, _)| p.len()) == Some(8) {
            return Ok(None);
        }

        // All tenants share one key, so a resolved tenant must match the
        // token's `tenant` claim (#1848).
        let scope = match parts.extensions.get::<super::TenantSlug>() {
            Some(slug) => super::jwt_lifecycle::UserTokenScope::Tenant(&slug.0),
            None => super::jwt_lifecycle::UserTokenScope::Unscoped,
        };
        let (user_id, jti, session) = match self.verify_claims(token, scope) {
            Some(c) => c,
            None => return Err(AuthError::InvalidToken),
        };

        // Revocation, when a store is wired (#1402). Without this the
        // blacklist is write-only: `revoke()` and `/api/auth/logout` record
        // a JTI that nothing ever reads, so a "logged out" token keeps
        // working for its full remaining life.
        match (self.jti_store.as_ref(), jti.as_deref()) {
            (Some(store), Some(jti)) if store.is_used(jti).await => {
                return Err(AuthError::InvalidToken);
            }
            (None, Some(_)) => self.warn_unchecked_revocation(),
            _ => {}
        }

        let users = super::auth::User::objects()
            .where_(super::auth::User::id.eq(user_id))
            .fetch(pool)
            .await?;

        let Some(user) = users.into_iter().next() else {
            return Ok(None);
        };

        if !user.active {
            return Err(AuthError::Inactive);
        }

        // A login token ends with its session, as on `require_bearer` (#2247).
        if let Some(session) = session {
            let check = super::auth_routes::SessionCheck {
                pwf_secret: &self.pwf_secret,
                families: self.jti_store.as_deref(),
                cap_secs: None,
            };
            if !session.admits(&check, &user).await {
                return Err(AuthError::InvalidToken);
            }
        }

        Ok(Some(AuthUser {
            id: user.id.get().copied().unwrap_or(0),
            username: user.username,
            is_superuser: user.is_superuser,
        }))
    }
}

// ------------------------------------------------------------------ helpers

fn to_hex(bytes: &[u8]) -> String {
    bytes.iter().map(|b| format!("{b:02x}")).collect()
}

fn extract_bearer(parts: &Parts) -> Result<Option<&str>, AuthError> {
    let Some(value) = parts.headers.get(axum::http::header::AUTHORIZATION) else {
        return Ok(None);
    };
    let s = value.to_str().unwrap_or("");
    Ok(s.strip_prefix("Bearer ").map(str::trim))
}

#[cfg(all(test, feature = "sqlite"))]
mod tests {
    use super::*;

    /// The MAC depends on the server key and the secret.
    #[test]
    fn api_key_mac_binds_key_and_secret() {
        use crate::session::SessionSecret;
        let (a, b) = (
            SessionSecret::from_bytes(vec![1; 32]),
            SessionSecret::from_bytes(vec![2; 32]),
        );
        let mac = api_key_mac(&a, "s3cret");
        assert!(mac.starts_with(API_KEY_MAC_SCHEME) && mac.len() < 255);
        assert!(mac_eq(&mac, &api_key_mac(&a, "s3cret")));
        assert_ne!(mac, api_key_mac(&b, "s3cret"));
        assert_ne!(mac, api_key_mac(&a, "s3creu"));
    }

    /// Authenticate `token` twice on `backend`; count revocation warnings.
    async fn revocation_warnings(backend: &JwtBackend, token: &str) -> usize {
        let buf = crate::testkit::CaptureWriter::default();
        let subscriber = tracing_subscriber::fmt()
            .with_writer(buf.clone())
            .with_ansi(false)
            .finish();
        let _g = tracing::subscriber::set_default(subscriber);
        let pool = Pool::connect("sqlite::memory:").await.unwrap();
        for _ in 0..2 {
            let (parts, ()) = axum::http::Request::builder()
                .header("authorization", format!("Bearer {token}"))
                .body(())
                .unwrap()
                .into_parts();
            let _ = backend.authenticate(&parts, &pool).await;
        }
        buf.contents().matches("not checked for revocation").count()
    }

    /// #1809 — a revocable token on a backend without a JTI store is not silent.
    #[tokio::test]
    async fn a_revocable_token_without_a_jti_store_warns_once() {
        let token = super::super::jwt_lifecycle::JwtLifecycle::new(vec![7u8; 32])
            .issue_pair(42)
            .access;
        let backend = JwtBackend::new(vec![7u8; 32]);
        assert_eq!(revocation_warnings(&backend, &token).await, 1);
    }

    /// #2617 — the Basic cache key changes with the stored hash and the
    /// tenant, so a password change or another tenant never hits.
    #[test]
    fn basic_cache_key_binds_hash_and_tenant() {
        let k = basic_cache_key("t", "alice", "pw", "$argon2id$a");
        assert_eq!(k, basic_cache_key("t", "alice", "pw", "$argon2id$a"));
        assert_ne!(k, basic_cache_key("t", "alice", "pw", "$argon2id$b"));
        assert_ne!(k, basic_cache_key("u", "alice", "pw", "$argon2id$a"));
        assert_ne!(k, basic_cache_key("t", "alice", "pw2", "$argon2id$a"));
        assert_ne!(
            basic_cache_key("t", "ab", "c", "h"),
            basic_cache_key("t", "a", "bc", "h")
        );
    }

    #[test]
    fn basic_cache_hit_needs_the_same_user() {
        let key = basic_cache_key("t-hit", "bob", "pw", "h");
        assert!(!basic_cache_hit(&key, 7));
        basic_cache_put(key, 7);
        assert!(basic_cache_hit(&key, 7));
        assert!(!basic_cache_hit(&key, 8));
    }

    /// performance-001 / security-003 — a locked Basic account is refused
    /// before the user lookup: here there is no user table to look in.
    #[tokio::test]
    async fn a_locked_basic_account_is_refused_before_the_lookup() {
        use crate::login_throttle::LoginRefused;
        use base64::Engine as _;
        let scope = LoginScope::TenantBasic("t-prelock".into());
        for _ in 0..crate::account_lockout::DEFAULT_MAX_ATTEMPTS {
            let a = crate::login_throttle::shared()
                .begin(&scope, &ClientIp::default(), "locked-user")
                .await
                .unwrap();
            a.failed().await;
        }
        let pool = Pool::connect("sqlite::memory:").await.unwrap();
        let creds = base64::engine::general_purpose::STANDARD.encode("locked-user:pw");
        let (parts, ()) = axum::http::Request::builder()
            .header("authorization", format!("Basic {creds}"))
            .extension(super::super::TenantSlug("t-prelock".into()))
            .body(())
            .unwrap()
            .into_parts();
        let r = ModelBackend.authenticate(&parts, &pool).await;
        assert!(
            matches!(r, Err(AuthError::Refused(LoginRefused::Throttled { .. }))),
            "{r:?}"
        );
    }

    /// A token with no `jti` can't be revoked, so there is nothing to warn about.
    #[tokio::test]
    async fn a_token_without_a_jti_stays_silent() {
        let backend = JwtBackend::new(vec![7u8; 32]);
        let token = backend.issue(42);
        assert_eq!(revocation_warnings(&backend, &token).await, 0);
    }
}