forgelib 1.1.0

The standard library for agent-built SaaS: hardened infra primitives on Postgres
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
use super::{
    ApiKey, ApiKeyInfo, ApiKeyOpts, ApiKeySecret, Auth, MAX_API_KEY_METADATA_BYTES,
    MAX_API_KEY_SCOPES, MAX_ID_BYTES, MAX_LABEL_BYTES, MAX_PASSWORD_BYTES, MAX_PHC_BYTES,
    MAX_PURPOSE_BYTES, MAX_TOKEN_PAYLOAD_BYTES, OneTimeToken, PhcString, Session, SessionOpts,
    SessionToken, TokenConsumption,
};
use crate::backend::{BackendLifecycle, Primitive};
use crate::clock::{Clock, RandomSource};
use crate::error::{ForgeError, Result};
use crate::util::{hex, namespaced, sha256_hex};
use argon2::password_hash::SaltString;
use argon2::{Argon2, Params, PasswordHash, PasswordHasher, PasswordVerifier};
use async_trait::async_trait;
use bytes::Bytes;
use std::collections::HashMap;
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::time::{Duration, SystemTime};
use uuid::Uuid;

// Forge-owned argon2id parameters, duplicated from `super::PgAuth`'s pinned constants
// (those helpers are module-private and unreachable here) and kept identical so both
// backends hash at the same cost and agree on `needs_rehash`. Divergence would silently
// mark every Postgres-minted hash as stale (or vice versa) when an app moved backends.
const ARGON2_M_COST: u32 = 19_456; // KiB (19 MiB)
const ARGON2_T_COST: u32 = 2;
const ARGON2_P_COST: u32 = 1;

/// An argon2id hasher built from Forge's pinned parameters.
fn forge_argon2() -> Result<Argon2<'static>> {
    let params = Params::new(ARGON2_M_COST, ARGON2_T_COST, ARGON2_P_COST, None)
        .map_err(|e| ForgeError::backend(format!("invalid argon2 params: {e}")))?;
    Ok(Argon2::new(
        argon2::Algorithm::Argon2id,
        argon2::Version::V0x13,
        params,
    ))
}

/// Random token entropy: 32 bytes = 256 bits.
const TOKEN_BYTES: usize = 32;
/// Absolute-timeout ceiling (~10 years). Over => `Limit`.
const MAX_ABSOLUTE_SECS: f64 = 10.0 * 365.0 * 24.0 * 60.0 * 60.0;
/// API-key prefix (Stripe/GitHub convention), for greppability + secret scanning.
const KEY_PREFIX: &str = "fk_";

/// A fresh 256-bit random token rendered as hex.
fn random_token(random: &dyn RandomSource) -> String {
    let mut buf = [0u8; TOKEN_BYTES];
    random.fill(&mut buf);
    hex(&buf)
}

fn random_salt(random: &dyn RandomSource) -> Result<SaltString> {
    let mut bytes = [0u8; 16];
    random.fill(&mut bytes);
    SaltString::encode_b64(&bytes)
        .map_err(|error| ForgeError::backend(format!("salt generation failed: {error}")))
}

fn check_id(id: &str) -> Result<()> {
    if id.is_empty() {
        return Err(ForgeError::invalid("user/owner id must not be empty"));
    }
    if id.len() > MAX_ID_BYTES {
        return Err(ForgeError::limit(format!(
            "id is {} bytes; max is {MAX_ID_BYTES}",
            id.len()
        )));
    }
    Ok(())
}

fn check_label(label: &str) -> Result<()> {
    if label.len() > MAX_LABEL_BYTES {
        return Err(ForgeError::limit(format!(
            "label is {} bytes; max is {MAX_LABEL_BYTES}",
            label.len()
        )));
    }
    Ok(())
}

fn check_password(plain: &str) -> Result<()> {
    if plain.is_empty() {
        return Err(ForgeError::invalid("password must not be empty"));
    }
    if plain.len() > MAX_PASSWORD_BYTES {
        return Err(ForgeError::limit(format!(
            "password is {} bytes; max is {MAX_PASSWORD_BYTES}",
            plain.len()
        )));
    }
    Ok(())
}

fn check_purpose(purpose: &str) -> Result<()> {
    if purpose.is_empty() {
        return Err(ForgeError::invalid("purpose must not be empty"));
    }
    if purpose.len() > MAX_PURPOSE_BYTES {
        return Err(ForgeError::limit(format!(
            "purpose is {} bytes; max is {MAX_PURPOSE_BYTES}",
            purpose.len()
        )));
    }
    Ok(())
}

fn check_token_ttl(ttl: Duration) -> Result<()> {
    if ttl.is_zero() {
        return Err(ForgeError::invalid("token ttl must be positive"));
    }
    if ttl.as_secs_f64() > MAX_ABSOLUTE_SECS {
        return Err(ForgeError::limit("token ttl exceeds the maximum"));
    }
    Ok(())
}

fn check_session_opts(opts: &SessionOpts) -> Result<()> {
    if opts.idle_timeout.is_zero() || opts.absolute_timeout.is_zero() {
        return Err(ForgeError::invalid("session timeouts must be positive"));
    }
    if opts.idle_timeout > opts.absolute_timeout {
        return Err(ForgeError::invalid(
            "idle_timeout must be <= absolute_timeout",
        ));
    }
    if opts.absolute_timeout.as_secs_f64() > MAX_ABSOLUTE_SECS {
        return Err(ForgeError::limit("absolute_timeout exceeds the maximum"));
    }
    Ok(())
}

/// Take a map lock, recovering the guard if a previous holder panicked. The critical
/// sections are short and synchronous (no `await` held across the lock), so a poisoned
/// lock never reflects a half-updated invariant worth aborting for.
fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
    m.lock().unwrap_or_else(PoisonError::into_inner)
}

/// A stored session. Only the token's SHA-256 is the map key; the plaintext is never kept.
struct SessionRecord {
    user_id: String,
    created_at: SystemTime,
    /// The configured sliding window, re-applied on each successful validate.
    idle: Duration,
    /// Sliding idle deadline; advanced on validate, capped at `abs_deadline`.
    idle_deadline: SystemTime,
    /// Hard ceiling from creation; never extended.
    abs_deadline: SystemTime,
}

impl SessionRecord {
    /// Live iff both deadlines are still in the future, matching `PgAuth`'s
    /// `idle_deadline > now() AND abs_deadline > now()`.
    fn is_live(&self, now: SystemTime) -> bool {
        self.idle_deadline > now && self.abs_deadline > now
    }
}

/// A stored API key. The map key is the secret's SHA-256; the secret itself is never kept.
struct ApiKeyRecord {
    id: String,
    owner_id: String,
    label: String,
    expires_at: Option<SystemTime>,
    scopes: Vec<String>,
    metadata: HashMap<String, String>,
}

/// A stored one-time token. The map key is the token's SHA-256; the plaintext is never kept.
struct TokenRecord {
    user_id: String,
    purpose: String,
    expires_at: SystemTime,
    payload: Bytes,
}

/// In-process [`Auth`]. Passwords are stateless; sessions and API keys are held as
/// digest-keyed maps. Not durable.
pub(crate) struct MemAuth {
    sessions: Mutex<HashMap<String, SessionRecord>>,
    api_keys: Mutex<HashMap<String, ApiKeyRecord>>,
    tokens: Mutex<HashMap<String, TokenRecord>>,
    /// App namespace, the in-process analog of `PgAuth`'s `app` column: it scopes every
    /// stored digest so an app sharing a process can neither validate nor revoke another
    /// app's sessions or keys. Empty = the unnamespaced app.
    namespace: String,
    clock: Arc<dyn Clock>,
    random: Arc<dyn RandomSource>,
}

impl MemAuth {
    #[cfg(test)]
    pub(crate) fn new(namespace: String) -> Self {
        Self::with_dependencies(
            namespace,
            Arc::new(crate::clock::SystemClock::new()),
            Arc::new(crate::clock::SystemRandom),
        )
    }

    pub(crate) fn with_dependencies(
        namespace: String,
        clock: Arc<dyn Clock>,
        random: Arc<dyn RandomSource>,
    ) -> Self {
        Self {
            sessions: Mutex::new(HashMap::new()),
            api_keys: Mutex::new(HashMap::new()),
            tokens: Mutex::new(HashMap::new()),
            namespace,
            clock,
            random,
        }
    }

    /// Scope a digest to this app with the same `<namespace>:<key>` rule the SQL backends
    /// share, so two apps in one process never collide on the same secret digest.
    fn physical(&self, digest: &str) -> String {
        namespaced(&self.namespace, digest)
    }

    /// Drop expired sessions and one-time tokens, mirroring `PgAuth::sweep`. Reads
    /// already treat them as absent; this reclaims the memory. Returns how many were
    /// purged.
    pub(crate) fn purge_expired(&self) -> u64 {
        let now = self.clock.now();
        let mut purged = {
            let mut sessions = lock(&self.sessions);
            let before = sessions.len();
            sessions.retain(|_, rec| rec.is_live(now));
            (before - sessions.len()) as u64
        };
        let mut api_keys = lock(&self.api_keys);
        let before = api_keys.len();
        api_keys.retain(|_, record| record.expires_at.is_none_or(|expires| expires > now));
        purged += (before - api_keys.len()) as u64;
        let mut tokens = lock(&self.tokens);
        let before = tokens.len();
        tokens.retain(|_, rec| rec.expires_at > now);
        purged += (before - tokens.len()) as u64;
        purged
    }
}

fn check_api_key_opts(opts: &ApiKeyOpts) -> Result<()> {
    if opts.expires_in.is_some_and(|duration| duration.is_zero()) {
        return Err(ForgeError::invalid("API key expiry must be positive"));
    }
    if opts.scopes.len() > MAX_API_KEY_SCOPES
        || opts
            .scopes
            .iter()
            .any(|scope| scope.is_empty() || scope.len() > 128)
    {
        return Err(ForgeError::limit("API key scopes exceed their bounds"));
    }
    let metadata_bytes = serde_json::to_vec(&opts.metadata).map_err(|error| {
        ForgeError::backend_with("API key metadata could not be encoded", false, error)
    })?;
    if metadata_bytes.len() > MAX_API_KEY_METADATA_BYTES {
        return Err(ForgeError::limit("API key metadata exceeds 4096 bytes"));
    }
    Ok(())
}

#[async_trait]
impl Auth for MemAuth {
    async fn hash_password(&self, plain: &str) -> Result<PhcString> {
        check_password(plain)?;
        let owned = plain.to_string();
        let argon = forge_argon2()?;
        let random = self.random.clone();
        // argon2 is CPU-heavy; keep it off the async runtime threads.
        let phc = tokio::task::spawn_blocking(move || -> Result<String> {
            let salt = random_salt(random.as_ref())?;
            argon
                .hash_password(owned.as_bytes(), &salt)
                .map(|h| h.to_string())
                .map_err(|error| ForgeError::backend(format!("argon2 hashing failed: {error}")))
        })
        .await
        .map_err(|e| ForgeError::backend(format!("hash task failed: {e}")))??;
        Ok(PhcString::new(phc))
    }

    async fn verify_password(&self, plain: &str, hash: &PhcString) -> Result<bool> {
        check_password(plain)?;
        if hash.as_str().len() > MAX_PHC_BYTES {
            return Err(ForgeError::limit("password hash exceeds the maximum size"));
        }
        let owned = plain.to_string();
        let hash_str = hash.as_str().to_string();
        let argon = forge_argon2()?;
        let result = tokio::task::spawn_blocking(move || {
            let parsed = PasswordHash::new(&hash_str)?;
            argon.verify_password(owned.as_bytes(), &parsed)
        })
        .await
        .map_err(|e| ForgeError::backend(format!("verify task failed: {e}")))?;
        match result {
            Ok(()) => Ok(true),
            Err(argon2::password_hash::Error::Password) => Ok(false),
            Err(argon2::password_hash::Error::Crypto) => {
                Err(ForgeError::backend("argon2 verification failed"))
            }
            Err(e) => Err(ForgeError::invalid(format!("malformed password hash: {e}"))),
        }
    }

    fn needs_rehash(&self, hash: &PhcString) -> bool {
        let Ok(parsed) = PasswordHash::new(hash.as_str()) else {
            return true;
        };
        if parsed.algorithm.as_str() != "argon2id" {
            return true;
        }
        let Ok(params) = Params::try_from(&parsed) else {
            return true;
        };
        params.m_cost() < ARGON2_M_COST
            || params.t_cost() < ARGON2_T_COST
            || params.p_cost() < ARGON2_P_COST
    }

    async fn create_session(&self, user_id: &str, opts: SessionOpts) -> Result<SessionToken> {
        check_id(user_id)?;
        check_session_opts(&opts)?;
        let token = random_token(self.random.as_ref());
        let token_hash = sha256_hex(token.as_bytes());
        let now = self.clock.now();
        let record = SessionRecord {
            user_id: user_id.to_string(),
            created_at: now,
            idle: opts.idle_timeout,
            idle_deadline: now + opts.idle_timeout,
            abs_deadline: now + opts.absolute_timeout,
        };
        lock(&self.sessions).insert(self.physical(&token_hash), record);
        Ok(SessionToken::new(token))
    }

    async fn validate_session(&self, token: &str) -> Result<Option<Session>> {
        let pk = self.physical(&sha256_hex(token.as_bytes()));
        let now = self.clock.now();
        let mut sessions = lock(&self.sessions);
        match sessions.get_mut(&pk) {
            Some(rec) if rec.is_live(now) => {
                // Slide the idle deadline forward, capped at the absolute ceiling.
                rec.idle_deadline = (now + rec.idle).min(rec.abs_deadline);
                Ok(Some(Session::new(
                    rec.user_id.clone(),
                    rec.created_at,
                    rec.idle_deadline,
                )))
            }
            // Unknown, expired, or revoked all read as absent (never an error). Expired
            // records linger until `purge_expired`, like the unswept SQL rows.
            _ => Ok(None),
        }
    }

    async fn revoke_session(&self, token: &str) -> Result<()> {
        let pk = self.physical(&sha256_hex(token.as_bytes()));
        lock(&self.sessions).remove(&pk);
        Ok(())
    }

    async fn revoke_all_sessions(&self, user_id: &str) -> Result<u64> {
        let mut sessions = lock(&self.sessions);
        let before = sessions.len();
        sessions.retain(|_, rec| rec.user_id != user_id);
        Ok((before - sessions.len()) as u64)
    }

    async fn create_api_key(&self, owner_id: &str, label: &str) -> Result<ApiKey> {
        self.create_api_key_with(owner_id, label, ApiKeyOpts::default())
            .await
    }

    async fn create_api_key_with(
        &self,
        owner_id: &str,
        label: &str,
        opts: ApiKeyOpts,
    ) -> Result<ApiKey> {
        check_id(owner_id)?;
        check_label(label)?;
        check_api_key_opts(&opts)?;
        let id = Uuid::new_v4().to_string();
        let secret = format!("{KEY_PREFIX}{}", random_token(self.random.as_ref()));
        let key_hash = sha256_hex(secret.as_bytes());
        let created_at = self.clock.now();
        let expires_at = opts.expires_in.map(|duration| created_at + duration);
        let record = ApiKeyRecord {
            id: id.clone(),
            owner_id: owner_id.to_string(),
            label: label.to_string(),
            expires_at,
            scopes: opts.scopes.clone(),
            metadata: opts.metadata.clone(),
        };
        lock(&self.api_keys).insert(self.physical(&key_hash), record);
        Ok(ApiKey::new(
            id,
            label.to_string(),
            ApiKeySecret::new(secret),
            created_at,
            expires_at,
            opts.scopes,
            opts.metadata,
        ))
    }

    async fn verify_api_key(&self, key: &str) -> Result<Option<ApiKeyInfo>> {
        // Look the key up by the SHA-256 of the presented secret: the raw secret is never
        // compared, and the digest is high-entropy, so this leaks no timing signal about it,
        // the same property the SQL backend's indexed-digest lookup has.
        let pk = self.physical(&sha256_hex(key.as_bytes()));
        let api_keys = lock(&self.api_keys);
        Ok(api_keys.get(&pk).and_then(|record| {
            if record
                .expires_at
                .is_some_and(|expires| expires <= self.clock.now())
            {
                return None;
            }
            Some(ApiKeyInfo::new(
                record.id.clone(),
                record.owner_id.clone(),
                record.label.clone(),
                record.expires_at,
                record.scopes.clone(),
                record.metadata.clone(),
            ))
        }))
    }

    async fn revoke_api_key(&self, key_id: &str) -> Result<bool> {
        let mut api_keys = lock(&self.api_keys);
        // Revocation is keyed on the stable id, not the digest, so find the matching
        // entry first. All entries in this map already belong to this app's namespace.
        let pk = api_keys
            .iter()
            .find(|(_, r)| r.id == key_id)
            .map(|(k, _)| k.clone());
        match pk {
            Some(k) => {
                api_keys.remove(&k);
                Ok(true)
            }
            None => Ok(false),
        }
    }

    async fn create_token(
        &self,
        user_id: &str,
        purpose: &str,
        ttl: Duration,
    ) -> Result<OneTimeToken> {
        self.create_token_with_payload(user_id, purpose, ttl, Bytes::new())
            .await
    }

    async fn create_token_with_payload(
        &self,
        user_id: &str,
        purpose: &str,
        ttl: Duration,
        payload: Bytes,
    ) -> Result<OneTimeToken> {
        check_id(user_id)?;
        check_purpose(purpose)?;
        check_token_ttl(ttl)?;
        if payload.len() > MAX_TOKEN_PAYLOAD_BYTES {
            return Err(ForgeError::limit(
                "one-time token payload exceeds 4096 bytes",
            ));
        }
        let token = random_token(self.random.as_ref());
        let token_hash = sha256_hex(token.as_bytes());
        let record = TokenRecord {
            user_id: user_id.to_string(),
            purpose: purpose.to_string(),
            expires_at: self.clock.now() + ttl,
            payload,
        };
        lock(&self.tokens).insert(self.physical(&token_hash), record);
        Ok(OneTimeToken::new(token))
    }

    async fn consume_token(&self, token: &str, purpose: &str) -> Result<Option<String>> {
        Ok(self
            .consume_token_with_payload(token, purpose)
            .await?
            .map(|consumption| consumption.user_id))
    }

    async fn consume_token_with_payload(
        &self,
        token: &str,
        purpose: &str,
    ) -> Result<Option<TokenConsumption>> {
        check_purpose(purpose)?;
        let pk = self.physical(&sha256_hex(token.as_bytes()));
        let now = self.clock.now();
        let mut tokens = lock(&self.tokens);
        // Consume only a live token minted for this purpose; a purpose mismatch leaves
        // it intact, matching `PgAuth`'s conditional DELETE. Expired records linger
        // until `purge_expired`, like the unswept SQL rows.
        match tokens.get(&pk) {
            Some(rec) if rec.expires_at > now && rec.purpose == purpose => {
                Ok(tokens.remove(&pk).map(|record| TokenConsumption {
                    user_id: record.user_id,
                    payload: record.payload,
                }))
            }
            _ => Ok(None),
        }
    }
}

#[async_trait]
impl BackendLifecycle for MemAuth {
    fn name(&self) -> &'static str {
        "memory"
    }
    fn primitive(&self) -> Primitive {
        Primitive::Auth
    }
    fn durable(&self) -> bool {
        false
    }
    fn caveats(&self) -> &'static str {
        "in-process, not durable"
    }
    async fn maintain(&self) -> Result<()> {
        self.purge_expired();
        Ok(())
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn password_hashes_and_verifies() {
        let auth = MemAuth::new(String::new());
        let phc = auth.hash_password("correct horse").await.unwrap();
        assert!(phc.as_str().starts_with("$argon2id$"));
        assert!(auth.verify_password("correct horse", &phc).await.unwrap());
        assert!(!auth.verify_password("wrong", &phc).await.unwrap());
    }

    #[tokio::test]
    async fn password_input_is_validated() {
        let auth = MemAuth::new(String::new());
        assert!(matches!(
            auth.hash_password("").await,
            Err(ForgeError::Invalid(_))
        ));
        let big = "a".repeat(MAX_PASSWORD_BYTES + 1);
        assert!(matches!(
            auth.hash_password(&big).await,
            Err(ForgeError::Limit(_))
        ));

        let phc = auth.hash_password("pw").await.unwrap();
        assert!(matches!(
            auth.verify_password("", &phc).await,
            Err(ForgeError::Invalid(_))
        ));
        // An over-cap hash is rejected as Limit rather than silently verified.
        let huge = PhcString::new("$argon2id$".to_string() + &"x".repeat(MAX_PHC_BYTES));
        assert!(matches!(
            auth.verify_password("pw", &huge).await,
            Err(ForgeError::Limit(_))
        ));
    }

    #[tokio::test]
    async fn verify_rejects_malformed_hash() {
        let auth = MemAuth::new(String::new());
        // A malformed (but in-size) hash is Invalid, never Ok(false).
        let bad = PhcString::new("definitely-not-a-phc-string");
        assert!(matches!(
            auth.verify_password("pw", &bad).await,
            Err(ForgeError::Invalid(_))
        ));
    }

    #[tokio::test]
    async fn needs_rehash_detects_weak_and_malformed() {
        let auth = MemAuth::new(String::new());
        let strong = auth.hash_password("pw").await.unwrap();
        assert!(!auth.needs_rehash(&strong), "current params are fine");
        assert!(
            auth.needs_rehash(&PhcString::new("garbage")),
            "garbage => rehash"
        );

        // A valid argon2id hash below the current memory cost must be flagged.
        let weak = Argon2::new(
            argon2::Algorithm::Argon2id,
            argon2::Version::V0x13,
            Params::new(8, ARGON2_T_COST, ARGON2_P_COST, None).unwrap(),
        )
        .hash_password(b"pw", &SaltString::generate(&mut rand_core::OsRng))
        .unwrap()
        .to_string();
        assert!(
            auth.needs_rehash(&PhcString::new(weak)),
            "below params => rehash"
        );
    }

    #[tokio::test]
    async fn session_create_validate_revoke() {
        let auth = MemAuth::new(String::new());
        let token = auth
            .create_session("user-1", SessionOpts::new())
            .await
            .unwrap();

        let s = auth
            .validate_session(token.as_str())
            .await
            .unwrap()
            .unwrap();
        assert_eq!(s.user_id, "user-1");
        assert!(s.expires_at > s.created_at);

        assert!(
            auth.validate_session("unknown-token")
                .await
                .unwrap()
                .is_none()
        );

        auth.revoke_session(token.as_str()).await.unwrap();
        assert!(
            auth.validate_session(token.as_str())
                .await
                .unwrap()
                .is_none()
        );
        // Revoke is idempotent.
        auth.revoke_session(token.as_str()).await.unwrap();
    }

    #[tokio::test]
    async fn sessions_expire_and_sweep_reclaims_them() {
        let auth = MemAuth::new(String::new());
        let opts = SessionOpts::new()
            .with_idle_timeout(Duration::from_millis(100))
            .with_absolute_timeout(Duration::from_millis(100));
        let token = auth.create_session("u", opts).await.unwrap();
        assert!(
            auth.validate_session(token.as_str())
                .await
                .unwrap()
                .is_some()
        );

        tokio::time::sleep(Duration::from_millis(150)).await;
        assert!(
            auth.validate_session(token.as_str())
                .await
                .unwrap()
                .is_none(),
            "past both deadlines => absent"
        );
        // The expired record lingers (validate does not delete) until a sweep reclaims it.
        assert_eq!(auth.purge_expired(), 1);
        assert_eq!(auth.purge_expired(), 0, "sweep is idempotent");
    }

    #[tokio::test]
    async fn validate_caps_slide_at_absolute_deadline() {
        let auth = MemAuth::new(String::new());
        // idle == absolute, so the slid deadline (now + idle) always overshoots the
        // ceiling (created + idle) by the elapsed time and must be clamped back to it.
        let opts = SessionOpts::new()
            .with_idle_timeout(Duration::from_secs(2))
            .with_absolute_timeout(Duration::from_secs(2));
        let token = auth.create_session("u", opts).await.unwrap();

        tokio::time::sleep(Duration::from_millis(400)).await;
        let s = auth
            .validate_session(token.as_str())
            .await
            .unwrap()
            .unwrap();
        // Sliding alone would push the deadline to ~now+2s (~created+2.4s); the absolute
        // ceiling at created+2s must clamp it instead.
        assert!(
            s.expires_at <= s.created_at + Duration::from_millis(2100),
            "idle slide is capped at the absolute deadline"
        );
    }

    #[tokio::test]
    async fn revoke_all_sessions_clears_only_that_user() {
        let auth = MemAuth::new(String::new());
        let a1 = auth.create_session("a", SessionOpts::new()).await.unwrap();
        let a2 = auth.create_session("a", SessionOpts::new()).await.unwrap();
        let b1 = auth.create_session("b", SessionOpts::new()).await.unwrap();

        assert_eq!(auth.revoke_all_sessions("a").await.unwrap(), 2);
        assert!(auth.validate_session(a1.as_str()).await.unwrap().is_none());
        assert!(auth.validate_session(a2.as_str()).await.unwrap().is_none());
        assert!(auth.validate_session(b1.as_str()).await.unwrap().is_some());
        assert_eq!(
            auth.revoke_all_sessions("a").await.unwrap(),
            0,
            "idempotent"
        );
    }

    #[tokio::test]
    async fn api_key_create_verify_revoke() {
        let auth = MemAuth::new(String::new());
        let key = auth.create_api_key("owner-9", "ci-deploy").await.unwrap();
        assert!(key.secret.as_str().starts_with("fk_"));

        let info = auth
            .verify_api_key(key.secret.as_str())
            .await
            .unwrap()
            .unwrap();
        assert_eq!(info.id, key.id);
        assert_eq!(info.owner_id, "owner-9");
        assert_eq!(info.label, "ci-deploy");

        assert!(auth.verify_api_key("fk_unknown").await.unwrap().is_none());

        assert!(auth.revoke_api_key(&key.id).await.unwrap());
        assert!(
            auth.verify_api_key(key.secret.as_str())
                .await
                .unwrap()
                .is_none()
        );
        assert!(
            !auth.revoke_api_key(&key.id).await.unwrap(),
            "revoking an unknown id => false"
        );
    }

    #[tokio::test]
    async fn token_create_consume_is_single_use() {
        let auth = MemAuth::new(String::new());
        let token = auth
            .create_token("user-1", "password-reset", Duration::from_secs(900))
            .await
            .unwrap();
        assert_eq!(token.as_str().len(), TOKEN_BYTES * 2);

        // Wrong purpose leaves the token intact.
        assert!(
            auth.consume_token(token.as_str(), "email-verify")
                .await
                .unwrap()
                .is_none()
        );

        assert_eq!(
            auth.consume_token(token.as_str(), "password-reset")
                .await
                .unwrap()
                .as_deref(),
            Some("user-1")
        );
        // Second consume finds nothing: single use.
        assert!(
            auth.consume_token(token.as_str(), "password-reset")
                .await
                .unwrap()
                .is_none()
        );

        assert!(
            auth.consume_token("unknown-token", "password-reset")
                .await
                .unwrap()
                .is_none()
        );
    }

    #[tokio::test]
    async fn tokens_expire_and_sweep_reclaims_them() {
        let auth = MemAuth::new(String::new());
        let token = auth
            .create_token("u", "magic-link", Duration::from_millis(50))
            .await
            .unwrap();
        tokio::time::sleep(Duration::from_millis(100)).await;
        assert!(
            auth.consume_token(token.as_str(), "magic-link")
                .await
                .unwrap()
                .is_none(),
            "expired => absent"
        );
        // The expired record lingers (consume does not delete it) until a sweep.
        assert_eq!(auth.purge_expired(), 1);
        assert_eq!(auth.purge_expired(), 0, "sweep is idempotent");
    }

    #[tokio::test]
    async fn token_input_is_validated() {
        let auth = MemAuth::new(String::new());
        assert!(matches!(
            auth.create_token("", "p", Duration::from_secs(60)).await,
            Err(ForgeError::Invalid(_))
        ));
        assert!(matches!(
            auth.create_token("u", "", Duration::from_secs(60)).await,
            Err(ForgeError::Invalid(_))
        ));
        assert!(matches!(
            auth.create_token("u", "p", Duration::ZERO).await,
            Err(ForgeError::Invalid(_))
        ));
        let big = "x".repeat(MAX_PURPOSE_BYTES + 1);
        assert!(matches!(
            auth.create_token("u", &big, Duration::from_secs(60)).await,
            Err(ForgeError::Limit(_))
        ));
        assert!(matches!(
            auth.create_token("u", "p", Duration::from_secs(u64::MAX / 2))
                .await,
            Err(ForgeError::Limit(_))
        ));
        assert!(matches!(
            auth.consume_token("t", "").await,
            Err(ForgeError::Invalid(_))
        ));
    }

    #[tokio::test]
    async fn namespaces_isolate_sessions_and_keys() {
        let a = MemAuth::new("app_a".to_string());
        let b = MemAuth::new("app_b".to_string());

        let token = a.create_session("u", SessionOpts::new()).await.unwrap();
        assert!(a.validate_session(token.as_str()).await.unwrap().is_some());
        assert!(
            b.validate_session(token.as_str()).await.unwrap().is_none(),
            "another app cannot validate the session"
        );

        let key = a.create_api_key("u", "k").await.unwrap();
        assert!(
            a.verify_api_key(key.secret.as_str())
                .await
                .unwrap()
                .is_some()
        );
        assert!(
            b.verify_api_key(key.secret.as_str())
                .await
                .unwrap()
                .is_none()
        );
        assert!(
            !b.revoke_api_key(&key.id).await.unwrap(),
            "another app cannot revoke the key"
        );

        let t = a
            .create_token("u", "reset", Duration::from_secs(60))
            .await
            .unwrap();
        assert!(
            b.consume_token(t.as_str(), "reset")
                .await
                .unwrap()
                .is_none(),
            "another app cannot consume the token"
        );
        assert!(
            a.consume_token(t.as_str(), "reset")
                .await
                .unwrap()
                .is_some()
        );
    }

    #[tokio::test]
    async fn rejects_bad_input() {
        let auth = MemAuth::new(String::new());
        assert!(matches!(
            auth.create_session("", SessionOpts::new()).await,
            Err(ForgeError::Invalid(_))
        ));
        let zero = SessionOpts::new().with_idle_timeout(Duration::ZERO);
        assert!(matches!(
            auth.create_session("u", zero).await,
            Err(ForgeError::Invalid(_))
        ));
        let inverted = SessionOpts::new()
            .with_idle_timeout(Duration::from_secs(100))
            .with_absolute_timeout(Duration::from_secs(10));
        assert!(matches!(
            auth.create_session("u", inverted).await,
            Err(ForgeError::Invalid(_))
        ));

        assert!(matches!(
            auth.create_api_key("", "label").await,
            Err(ForgeError::Invalid(_))
        ));
        let big_label = "x".repeat(MAX_LABEL_BYTES + 1);
        assert!(matches!(
            auth.create_api_key("owner", &big_label).await,
            Err(ForgeError::Limit(_))
        ));
    }
}