rustango 0.58.0

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
//! Pre-built auth flows — password reset + email verification.
//!
//! Lightweight helpers that compose the existing `signed_url` + `email`
//! layers into the canonical signed-token-via-email pattern. You wire the
//! routes / templates yourself; these handle the token generation +
//! verification cycle.
//!
//! ## Password reset flow
//!
//! 1. User requests a reset → call [`PasswordReset::issue`] with their
//!    email + a callback URL → emit the email yourself with the returned URL.
//! 2. User clicks link → axum handler parses the URL → call
//!    [`PasswordReset::verify`] → if Ok, render the "set new password" form.
//! 3. User submits form → validate + write new hashed password to DB.
//!
//! ```ignore
//! use rustango::auth_flows::{PasswordReset, AuthFlowError};
//! use std::time::Duration;
//!
//! let secret: &[u8] = b"32-byte-app-secret-...";
//!
//! // Step 1: issue
//! let url = PasswordReset::issue(
//!     "https://app.example.com/auth/reset",
//!     user_id,
//!     secret,
//!     Duration::from_secs(3600),
//! );
//! mailer.send(&Email::new()
//!     .to(&user.email)
//!     .subject("Reset your password")
//!     .body(&format!("Click here: {url}"))
//! ).await?;
//!
//! // Step 2: verify (in the callback handler)
//! match PasswordReset::verify(&incoming_url, secret) {
//!     Ok(user_id) => { /* render form to capture new password */ }
//!     Err(AuthFlowError::Expired) => { /* "link expired, request a new one" */ }
//!     Err(_) => { /* tampered or malformed */ }
//! }
//! ```
//!
//! ## Email verification flow
//!
//! Same pattern with [`EmailVerification`] — issue the URL after signup,
//! verify on the callback, mark the user's `email_verified_at` column.
//!
//! [`EmailVerification`]: crate::auth_flows::EmailVerification
//! [`PasswordReset::issue`]: crate::auth_flows::PasswordReset::issue
//! [`PasswordReset::verify`]: crate::auth_flows::PasswordReset::verify

use std::time::Duration;

use crate::signed_url::{sign, verify, SignedUrlError};

/// Errors from auth-flow helpers.
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum AuthFlowError {
    #[error("token is missing or malformed")]
    Malformed,
    #[error("token signature does not match")]
    InvalidSignature,
    #[error("token has expired")]
    Expired,
    #[error("token is for the wrong purpose ({0})")]
    WrongPurpose(String),
    /// `confirm_password_reset_pool` rejected the new password — too
    /// short, too common, or otherwise out-of-spec. Message is the
    /// validator's complaint, suitable for surfacing to the user.
    /// Issue #391.
    #[error("password rejected: {0}")]
    WeakPassword(String),
    /// Driver / SQL failure during the password UPDATE. The message
    /// carries the underlying driver error; callers typically log it
    /// and surface a generic "try again" message to the operator.
    /// Issue #391.
    #[error("database error: {0}")]
    Database(String),
    /// The token was already redeemed (audit N1). Returned by the
    /// `verify_single_use` variants when the signature has been seen
    /// before within its lifetime — defeats replay of a leaked
    /// magic-link / reset link.
    #[error("token already used")]
    AlreadyUsed,
}

impl From<SignedUrlError> for AuthFlowError {
    fn from(e: SignedUrlError) -> Self {
        match e {
            SignedUrlError::MissingSignature | SignedUrlError::MalformedSignature => {
                Self::Malformed
            }
            SignedUrlError::InvalidSignature => Self::InvalidSignature,
            SignedUrlError::Expired => Self::Expired,
        }
    }
}

// ------------------------------------------------------------------ Password reset

/// Password reset flow helpers.
pub struct PasswordReset;

impl PasswordReset {
    const PURPOSE: &'static str = "pwreset";

    /// Build a signed reset URL valid for `ttl`. `base_url` should be your
    /// public callback (e.g. `"https://app.example.com/auth/reset"`).
    /// `user_id` is encoded as a query param so the verifier can identify
    /// the account.
    #[must_use]
    pub fn issue(base_url: &str, user_id: i64, secret: &[u8], ttl: Duration) -> String {
        let url = format!(
            "{}?user_id={}&purpose={}",
            base_url.trim_end_matches('?'),
            user_id,
            Self::PURPOSE,
        );
        sign(&url, secret, Some(ttl))
    }

    /// Verify a reset URL. On success returns the `user_id` extracted from
    /// the URL — caller writes the new password against this id.
    ///
    /// # Errors
    /// [`AuthFlowError`] variants describe the failure mode.
    pub fn verify(url: &str, secret: &[u8]) -> Result<i64, AuthFlowError> {
        verify(url, secret)?;
        let purpose = extract_query(url, "purpose").ok_or(AuthFlowError::Malformed)?;
        if purpose != Self::PURPOSE {
            return Err(AuthFlowError::WrongPurpose(purpose));
        }
        let user_id_str = extract_query(url, "user_id").ok_or(AuthFlowError::Malformed)?;
        user_id_str
            .parse::<i64>()
            .map_err(|_| AuthFlowError::Malformed)
    }

    /// Like [`Self::verify`] but enforces **single use** (audit N1):
    /// records the token as consumed in `cache` so a replay returns
    /// [`AuthFlowError::AlreadyUsed`]. Prefer this for reset links, or
    /// enforce single-use yourself by deleting the reset record after a
    /// successful password change.
    ///
    /// # Errors
    /// As [`Self::verify`], plus [`AuthFlowError::AlreadyUsed`].
    #[cfg(feature = "cache")]
    pub async fn verify_single_use(
        url: &str,
        secret: &[u8],
        cache: &std::sync::Arc<dyn crate::cache::Cache>,
    ) -> Result<i64, AuthFlowError> {
        let user_id = Self::verify(url, secret)?;
        consume_single_use(url, cache).await?;
        Ok(user_id)
    }
}

/// Finish a password reset: verify the reset URL, validate the new
/// password, hash it, and update the named user row. Returns the
/// `user_id` on success.
///
/// Sensible defaults:
/// - `user_table` = `"rustango_users"`
/// - `pk_column` = `"id"`
/// - `password_column` = `"password_hash"`
///
/// The new password must pass [`crate::passwords::strength_score`] —
/// the same policy `docs/auth-passwords.md` documents, so a password
/// refused at registration can no longer be set by resetting (#1399).
///
/// **This link is replayable for its full TTL.** A copy of the email —
/// forwarded, archived, in a shared inbox, pasted into a support ticket —
/// still works after the legitimate reset completes. Use
/// [`confirm_password_reset_single_use`] instead wherever you have a
/// cache.
///
/// Stamps `password_changed_at`, so sessions issued before the reset stop
/// validating (#1449) — a reset is what someone does when they think
/// their account is compromised, and leaving the attacker's session alive
/// defeats the point. [`confirm_password_reset_pool_into`] does **not**,
/// because a caller-named table may have no such column; prefer this form
/// for `rustango_users`.
///
/// Pairs with [`PasswordReset::issue`] — issue the URL, email it,
/// and call this helper from your POST `/password-reset/confirm`
/// endpoint to land the new password.
///
/// # Errors
/// - [`AuthFlowError`] from `PasswordReset::verify` (Malformed,
///   InvalidSignature, Expired, WrongPurpose).
/// - [`AuthFlowError::WeakPassword`] when the password fails the policy.
/// - [`AuthFlowError::Database`] for SQL / driver failures.
#[cfg(feature = "passwords")]
pub async fn confirm_password_reset_pool(
    pool: &crate::sql::Pool,
    url: &str,
    new_password: &str,
    secret: &[u8],
) -> Result<i64, AuthFlowError> {
    let user_id = PasswordReset::verify(url, secret)?;
    check_password_strength(new_password)?;
    // Not a delegation to `_into`: this form owns `rustango_users`, so it
    // also stamps `password_changed_at` and ends existing sessions (#1449).
    write_password_hash(
        pool,
        user_id,
        new_password,
        "rustango_users",
        "id",
        "password_hash",
        Some("password_changed_at"),
    )
    .await
}

/// As [`confirm_password_reset_pool`] but writes the new hash into a
/// caller-named table / columns. Use when the user model lives in a
/// custom table (e.g. tenant `app_users`) rather than the framework's
/// default `rustango_users`. Issue #391.
///
/// **Writes only the password column.** A caller-named table may have no
/// rotation timestamp, so this form cannot stamp one — which means it
/// does not end sessions issued before the reset (#1449). If your table
/// has an equivalent of `password_changed_at`, update it yourself in the
/// same transaction, or use [`confirm_password_reset_pool`] when the
/// table really is `rustango_users`.
///
/// # Errors
/// Same shape as [`confirm_password_reset_pool`].
#[cfg(feature = "passwords")]
pub async fn confirm_password_reset_pool_into(
    pool: &crate::sql::Pool,
    url: &str,
    new_password: &str,
    secret: &[u8],
    user_table: &str,
    pk_column: &str,
    password_column: &str,
) -> Result<i64, AuthFlowError> {
    let user_id = PasswordReset::verify(url, secret)?;
    check_password_strength(new_password)?;
    write_password_hash(
        pool,
        user_id,
        new_password,
        user_table,
        pk_column,
        password_column,
        None,
    )
    .await
}

/// As [`confirm_password_reset_pool`] but the link is **single-use**: the
/// token is recorded in `cache` and a replay returns
/// [`AuthFlowError::AlreadyUsed`] (#1399).
///
/// `docs/auth-flows.md` recommends single-use for reset links; this is
/// the helper that can honour it. Without it a leaked copy of the reset
/// email is a working account takeover for the rest of the TTL, *after*
/// the legitimate user has completed their reset.
///
/// The password policy is checked before the token is consumed, so a
/// rejected password does not burn the user's link.
///
/// # Errors
/// As [`confirm_password_reset_pool`], plus [`AuthFlowError::AlreadyUsed`].
#[cfg(all(feature = "passwords", feature = "cache"))]
pub async fn confirm_password_reset_single_use(
    pool: &crate::sql::Pool,
    url: &str,
    new_password: &str,
    secret: &[u8],
    cache: &std::sync::Arc<dyn crate::cache::Cache>,
) -> Result<i64, AuthFlowError> {
    let user_id = PasswordReset::verify(url, secret)?;
    check_password_strength(new_password)?;
    consume_single_use(url, cache).await?;
    // As with the non-single-use form: this one owns `rustango_users`,
    // so it stamps `password_changed_at` too (#1449).
    write_password_hash(
        pool,
        user_id,
        new_password,
        "rustango_users",
        "id",
        "password_hash",
        Some("password_changed_at"),
    )
    .await
}

/// As [`confirm_password_reset_single_use`] but writes into a
/// caller-named table / columns.
///
/// # Errors
/// Same shape as [`confirm_password_reset_single_use`].
#[cfg(all(feature = "passwords", feature = "cache"))]
#[allow(clippy::too_many_arguments)]
pub async fn confirm_password_reset_single_use_into(
    pool: &crate::sql::Pool,
    url: &str,
    new_password: &str,
    secret: &[u8],
    cache: &std::sync::Arc<dyn crate::cache::Cache>,
    user_table: &str,
    pk_column: &str,
    password_column: &str,
) -> Result<i64, AuthFlowError> {
    let user_id = PasswordReset::verify(url, secret)?;
    // Policy before consumption: a weak password must not cost the user
    // their link, but a replay must not reach the write.
    check_password_strength(new_password)?;
    consume_single_use(url, cache).await?;
    write_password_hash(
        pool,
        user_id,
        new_password,
        user_table,
        pk_column,
        password_column,
        None,
    )
    .await
}

/// The framework's documented password policy, applied where the reset
/// path used to check only `len() < 8` (#1399).
#[cfg(feature = "passwords")]
fn check_password_strength(new_password: &str) -> Result<(), AuthFlowError> {
    use crate::passwords::StrengthIssue;

    let issues = crate::passwords::strength_score(new_password);
    if issues.is_empty() {
        return Ok(());
    }
    let reasons: Vec<&str> = issues
        .iter()
        .map(|i| match i {
            StrengthIssue::TooShort => "it must be at least 12 characters",
            StrengthIssue::NoDigitsOrSymbols => "it needs a digit or a symbol",
            StrengthIssue::NoVariety => "it needs more than lowercase letters",
            StrengthIssue::KnownWeak => "it is a well-known weak password",
        })
        .collect();
    Err(AuthFlowError::WeakPassword(format!(
        "Password rejected: {}.",
        reasons.join("; ")
    )))
}

/// Hash and store the new password. Shared by the replayable and
/// single-use confirm helpers.
///
/// `rotated_at_column`, when given, is stamped with "now" in the same
/// UPDATE so sessions issued before the reset stop validating (#1449).
/// It is `Some("password_changed_at")` for the framework's own
/// `rustango_users` and `None` for a caller-named table, which may have
/// no such column.
#[cfg(feature = "passwords")]
async fn write_password_hash(
    pool: &crate::sql::Pool,
    user_id: i64,
    new_password: &str,
    user_table: &str,
    pk_column: &str,
    password_column: &str,
    rotated_at_column: Option<&str>,
) -> Result<i64, AuthFlowError> {
    let hash = crate::passwords::hash_async(new_password)
        .await
        .map_err(|e| AuthFlowError::Database(e.to_string()))?;
    let dialect = pool.dialect();
    let t = dialect.quote_ident(user_table);
    let pw = dialect.quote_ident(password_column);
    let pk = dialect.quote_ident(pk_column);

    let mut sets = format!("{pw} = {}", dialect.placeholder(1));
    let mut args = vec![crate::core::SqlValue::String(hash)];
    if let Some(col) = rotated_at_column {
        // Same statement as the hash: a reset that rotated the password
        // but not the timestamp would leave every existing session live,
        // which is the failure this closes.
        let rot = dialect.quote_ident(col);
        sets.push_str(&format!(", {rot} = {}", dialect.placeholder(2)));
        args.push(crate::core::SqlValue::DateTime(chrono::Utc::now()));
    }
    let pk_ph = dialect.placeholder(args.len() + 1);
    args.push(crate::core::SqlValue::I64(user_id));

    let sql = format!("UPDATE {t} SET {sets} WHERE {pk} = {pk_ph}");
    crate::sql::raw_execute_pool(pool, &sql, args)
        .await
        .map_err(|e| AuthFlowError::Database(e.to_string()))?;
    Ok(user_id)
}

// ------------------------------------------------------------------ Email verification

/// Email verification flow helpers.
pub struct EmailVerification;

impl EmailVerification {
    const PURPOSE: &'static str = "verify_email";

    /// Build a signed verification URL valid for `ttl` (typically 24h+).
    /// Encodes both `user_id` and `email` so the verifier can confirm the
    /// user hasn't changed their email between issuance and click.
    #[must_use]
    pub fn issue(
        base_url: &str,
        user_id: i64,
        email: &str,
        secret: &[u8],
        ttl: Duration,
    ) -> String {
        let url = format!(
            "{}?user_id={}&email={}&purpose={}",
            base_url.trim_end_matches('?'),
            user_id,
            url_encode(email),
            Self::PURPOSE,
        );
        sign(&url, secret, Some(ttl))
    }

    /// Verify the URL and return the `(user_id, email)` it was issued for.
    /// Caller compares email against the user's current email to detect
    /// stale verification links.
    ///
    /// # Errors
    /// As [`PasswordReset::verify`].
    pub fn verify(url: &str, secret: &[u8]) -> Result<(i64, String), AuthFlowError> {
        verify(url, secret)?;
        let purpose = extract_query(url, "purpose").ok_or(AuthFlowError::Malformed)?;
        if purpose != Self::PURPOSE {
            return Err(AuthFlowError::WrongPurpose(purpose));
        }
        let user_id_str = extract_query(url, "user_id").ok_or(AuthFlowError::Malformed)?;
        let user_id = user_id_str
            .parse::<i64>()
            .map_err(|_| AuthFlowError::Malformed)?;
        let email = extract_query(url, "email").ok_or(AuthFlowError::Malformed)?;
        Ok((user_id, email))
    }

    /// Like [`Self::verify`] but enforces **single use** (audit N1) via
    /// `cache` — a replay returns [`AuthFlowError::AlreadyUsed`].
    ///
    /// # Errors
    /// As [`Self::verify`], plus [`AuthFlowError::AlreadyUsed`].
    #[cfg(feature = "cache")]
    pub async fn verify_single_use(
        url: &str,
        secret: &[u8],
        cache: &std::sync::Arc<dyn crate::cache::Cache>,
    ) -> Result<(i64, String), AuthFlowError> {
        let out = Self::verify(url, secret)?;
        consume_single_use(url, cache).await?;
        Ok(out)
    }
}

// ------------------------------------------------------------------ Magic-link login

/// Magic-link login flow — passwordless authentication via emailed URL.
pub struct MagicLink;

impl MagicLink {
    const PURPOSE: &'static str = "magic_link";

    /// Build a signed login URL valid for `ttl` (typically 10–30 minutes).
    /// `email` identifies the user — the verifier uses it to look up the
    /// account and issue a session.
    #[must_use]
    pub fn issue(base_url: &str, email: &str, secret: &[u8], ttl: Duration) -> String {
        let url = format!(
            "{}?email={}&purpose={}",
            base_url.trim_end_matches('?'),
            url_encode(email),
            Self::PURPOSE,
        );
        sign(&url, secret, Some(ttl))
    }

    /// Verify the URL and return the email it was issued for.
    ///
    /// **This is NOT single-use** — the signature is valid until its TTL
    /// expires, so a leaked link (Referer header, browser history, proxy
    /// logs) can be replayed to log in repeatedly. For passwordless login
    /// use [`Self::verify_single_use`] (or otherwise burn the token after
    /// first use). Audit N1.
    ///
    /// # Errors
    /// As [`PasswordReset::verify`].
    pub fn verify(url: &str, secret: &[u8]) -> Result<String, AuthFlowError> {
        verify(url, secret)?;
        let purpose = extract_query(url, "purpose").ok_or(AuthFlowError::Malformed)?;
        if purpose != Self::PURPOSE {
            return Err(AuthFlowError::WrongPurpose(purpose));
        }
        extract_query(url, "email").ok_or(AuthFlowError::Malformed)
    }

    /// Like [`Self::verify`] but enforces **single use** (audit N1):
    /// the magic link can be redeemed only once — a replay returns
    /// [`AuthFlowError::AlreadyUsed`]. Strongly recommended for
    /// passwordless login, where `verify` alone leaves a replay window.
    ///
    /// # Errors
    /// As [`Self::verify`], plus [`AuthFlowError::AlreadyUsed`].
    #[cfg(feature = "cache")]
    pub async fn verify_single_use(
        url: &str,
        secret: &[u8],
        cache: &std::sync::Arc<dyn crate::cache::Cache>,
    ) -> Result<String, AuthFlowError> {
        let email = Self::verify(url, secret)?;
        consume_single_use(url, cache).await?;
        Ok(email)
    }
}

// ------------------------------------------------------------------ Helpers

fn extract_query(url: &str, key: &str) -> Option<String> {
    let query = url.split_once('?')?.1;
    for pair in query.split('&') {
        let (k, v) = pair.split_once('=')?;
        let k = url_decode(k);
        if k == key {
            return Some(url_decode(v));
        }
    }
    None
}

/// Mark a (already-verified) signed-URL token as consumed so it can't be
/// replayed (audit N1). Keys the token's `signature` in the cache for its
/// remaining lifetime; a repeat within that window returns
/// [`AuthFlowError::AlreadyUsed`].
///
/// **Fail-closed:** a cache read error is treated as "already used" — we
/// refuse rather than risk replaying a passwordless / reset link while
/// the cache is unavailable. `exists`+`set` is not atomic, so two
/// *simultaneous* redemptions of the same URL could race; that window is
/// sub-millisecond and this is defense-in-depth over the signature+TTL
/// the token already carries.
#[cfg(feature = "cache")]
async fn consume_single_use(
    url: &str,
    cache: &std::sync::Arc<dyn crate::cache::Cache>,
) -> Result<(), AuthFlowError> {
    let sig = extract_query(url, "signature").ok_or(AuthFlowError::Malformed)?;
    let key = format!("authflow_used:{sig}");
    match cache.exists(&key).await {
        Ok(true) => return Err(AuthFlowError::AlreadyUsed),
        Ok(false) => {}
        Err(_) => return Err(AuthFlowError::AlreadyUsed),
    }
    let _ = cache.set(&key, "1", Some(single_use_ttl(url))).await;
    Ok(())
}

/// Remaining lifetime of the token from its `expires` param (unix secs),
/// so the used-marker lives exactly as long as the token could be valid.
/// Falls back to 1h when `expires` is absent/unparseable/in the past.
#[cfg(feature = "cache")]
fn single_use_ttl(url: &str) -> Duration {
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_or(0, |d| d.as_secs());
    extract_query(url, "expires")
        .and_then(|s| s.parse::<u64>().ok())
        .map(|exp| Duration::from_secs(exp.saturating_sub(now)))
        .filter(|d| !d.is_zero())
        .unwrap_or(Duration::from_secs(3600))
}

// #806 — was byte-identical to `crate::url_codec::url_encode`
// (RFC 3986 unreserved set — the right alphabet for OAuth-style
// `?next=...` redirect targets). Route through the canonical codec.
// Percent-decoder consolidated into [`crate::url_codec`] — see the
// note in [`crate::signed_url`]. Re-imported under the `url_decode`
// name to keep the local call sites unchanged.
use crate::url_codec::{url_decode, url_encode};

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

    const SECRET: &[u8] = b"my-test-secret";

    // -------------------------------- Password reset

    #[test]
    fn password_reset_issue_and_verify_roundtrip() {
        let url = PasswordReset::issue(
            "https://app.example.com/reset",
            42,
            SECRET,
            Duration::from_secs(3600),
        );
        let user_id = PasswordReset::verify(&url, SECRET).unwrap();
        assert_eq!(user_id, 42);
    }

    #[test]
    fn password_reset_wrong_secret_fails() {
        let url = PasswordReset::issue("https://x/r", 42, SECRET, Duration::from_secs(3600));
        let r = PasswordReset::verify(&url, b"different");
        assert_eq!(r.unwrap_err(), AuthFlowError::InvalidSignature);
    }

    #[test]
    fn password_reset_tampered_user_id_fails() {
        let url = PasswordReset::issue("https://x/r", 42, SECRET, Duration::from_secs(3600));
        let tampered = url.replace("user_id=42", "user_id=99");
        let r = PasswordReset::verify(&tampered, SECRET);
        assert_eq!(r.unwrap_err(), AuthFlowError::InvalidSignature);
    }

    #[test]
    fn password_reset_rejects_email_verification_token() {
        // Same URL shape but issued for a different purpose
        let url = EmailVerification::issue(
            "https://x/r",
            42,
            "alice@x.com",
            SECRET,
            Duration::from_secs(3600),
        );
        let r = PasswordReset::verify(&url, SECRET);
        assert!(matches!(r, Err(AuthFlowError::WrongPurpose(_))));
    }

    // -------------------------------- Email verification

    #[test]
    fn email_verification_roundtrip() {
        let url = EmailVerification::issue(
            "https://x/v",
            42,
            "alice@example.com",
            SECRET,
            Duration::from_secs(86_400),
        );
        let (uid, email) = EmailVerification::verify(&url, SECRET).unwrap();
        assert_eq!(uid, 42);
        assert_eq!(email, "alice@example.com");
    }

    #[test]
    fn email_verification_handles_special_chars() {
        let url = EmailVerification::issue(
            "https://x/v",
            42,
            "a+b@example.com",
            SECRET,
            Duration::from_secs(86_400),
        );
        let (_, email) = EmailVerification::verify(&url, SECRET).unwrap();
        assert_eq!(email, "a+b@example.com");
    }

    #[test]
    fn email_verification_rejects_password_reset_token() {
        let url = PasswordReset::issue("https://x/v", 42, SECRET, Duration::from_secs(3600));
        let r = EmailVerification::verify(&url, SECRET);
        assert!(matches!(r, Err(AuthFlowError::WrongPurpose(_))));
    }

    // -------------------------------- Magic link

    #[test]
    fn magic_link_roundtrip() {
        let url = MagicLink::issue(
            "https://x/login",
            "alice@example.com",
            SECRET,
            Duration::from_secs(900),
        );
        let email = MagicLink::verify(&url, SECRET).unwrap();
        assert_eq!(email, "alice@example.com");
    }

    #[test]
    fn magic_link_rejects_password_reset_token() {
        let url = PasswordReset::issue("https://x/r", 42, SECRET, Duration::from_secs(3600));
        let r = MagicLink::verify(&url, SECRET);
        assert!(matches!(r, Err(AuthFlowError::WrongPurpose(_))));
    }

    #[cfg(feature = "cache")]
    #[tokio::test]
    async fn magic_link_single_use_rejects_replay() {
        use crate::cache::InMemoryCache;
        let cache: std::sync::Arc<dyn crate::cache::Cache> =
            std::sync::Arc::new(InMemoryCache::new());
        let url = MagicLink::issue(
            "https://x/login",
            "alice@example.com",
            SECRET,
            Duration::from_secs(900),
        );
        // First redemption succeeds.
        let email = MagicLink::verify_single_use(&url, SECRET, &cache)
            .await
            .unwrap();
        assert_eq!(email, "alice@example.com");
        // Audit N1 — replaying the same link is rejected.
        let replay = MagicLink::verify_single_use(&url, SECRET, &cache).await;
        assert!(
            matches!(replay, Err(AuthFlowError::AlreadyUsed)),
            "{replay:?}"
        );
        // A *different* link (fresh signature) is unaffected.
        let other = MagicLink::issue(
            "https://x/login",
            "bob@example.com",
            SECRET,
            Duration::from_secs(900),
        );
        assert!(MagicLink::verify_single_use(&other, SECRET, &cache)
            .await
            .is_ok());
    }

    // -------------------------------- query string handling

    #[test]
    fn extract_query_picks_right_param() {
        let url = "https://x/path?a=1&b=2&c=3";
        assert_eq!(extract_query(url, "b"), Some("2".to_owned()));
        assert_eq!(extract_query(url, "missing"), None);
    }

    #[test]
    fn extract_query_handles_url_encoded_value() {
        let url = "https://x/path?email=alice%40x.com";
        assert_eq!(extract_query(url, "email"), Some("alice@x.com".to_owned()));
    }

    #[test]
    fn missing_purpose_param_treated_as_malformed() {
        // Hand-crafted signed URL without purpose
        let url = sign(
            "https://x/r?user_id=42",
            SECRET,
            Some(Duration::from_secs(60)),
        );
        let r = PasswordReset::verify(&url, SECRET);
        assert_eq!(r.unwrap_err(), AuthFlowError::Malformed);
    }
}