Skip to main content

rustio_admin/auth/
recovery.rs

1//! Self-service password recovery (R1).
2//!
3//! See `DESIGN_RECOVERY.md` for the canonical contract this module
4//! implements. R1 ships in 0.5.0; this commit lands the schema, the
5//! [`PasswordPolicy`] surface, and the [`RecoveryPolicy`] surface.
6//! The issue + consume flow, the mailer wiring, the routes, and the
7//! templates land in subsequent atomic commits per
8//! `DESIGN_RECOVERY.md` §16.
9//!
10//! ## What lives here today
11//!
12//! - [`init_recovery_tables`] — creates `rustio_password_reset_tokens`
13//!   with the partial unique index that makes the consume path's
14//!   atomic `UPDATE … RETURNING` an index seek
15//!   (`DESIGN_RECOVERY.md` §9.1).
16//! - [`migrate_user_recovery_schema`] — adds the additive
17//!   `must_change_password` and `password_changed_at` columns on
18//!   `rustio_users` (§9.2). R1's `set_password` populates
19//!   `password_changed_at`; R2 enforces `must_change_password`.
20//! - [`PasswordPolicy`] / [`DefaultPasswordPolicy`] /
21//!   [`PasswordPolicyError`] / [`SharedPasswordPolicy`] — the
22//!   password-policy surface (§13).
23//! - [`RecoveryPolicy`] / [`DefaultRecoveryPolicy`] /
24//!   [`SharedRecoveryPolicy`] — the recovery-flow tunables (§10.2,
25//!   §12.3). Reset-token TTL, rate-limit shape, strict-mailer boot
26//!   guard, and the public-site-URL derivation rule.
27//!
28//! `Admin::password_policy(...)` and `Admin::recovery_policy(...)`
29//! live in `admin::types`; the traits and default impls live here so
30//! the recovery module owns its vocabulary.
31//!
32//! The migration functions are idempotent and safe to call on every
33//! boot. `auth::init_tables` invokes them after the existing user /
34//! session migrations. The policy surface is data-only at this
35//! commit; no handler reads either policy yet.
36
37use std::sync::Arc;
38use std::time::Duration as StdDuration;
39
40use chrono::Duration as ChronoDuration;
41
42use crate::admin::audit::{record as audit_record, ActionType, AuditEvent, LogEntry};
43use crate::admin::redact::redact_token;
44use crate::admin::Admin;
45use crate::auth::sessions::{hash_token_for_storage, random_token};
46use crate::auth::users::{find_user_by_email, Identity};
47use crate::auth::{invalidate_sessions, set_password, SessionInvalidationReason, SessionTarget};
48use crate::email::Mail;
49use crate::error::Result;
50use crate::http::Request;
51use crate::middleware::RateLimiter;
52use crate::orm::Db;
53
54/// Create the `rustio_password_reset_tokens` table and its indexes.
55///
56/// Schema (see `DESIGN_RECOVERY.md` §9.1 for the contract):
57///
58/// - `token_hash` is `sha256(token)` URL-safe-base64 — the plaintext
59///   token never lands in this row.
60/// - `mail_status` is one of `'pending' | 'sent' | 'failed'`; the state
61///   evolves in the issue handler (one row per request).
62/// - `correlation_id` mirrors the request's audit `correlation_id` so
63///   an operator can pivot from token row → audit chain.
64/// - The partial unique index `WHERE consumed_at IS NULL` is the index
65///   the atomic consume statement seeks on.
66///
67/// Idempotent. Safe to call on every boot. Depends on `rustio_users`
68/// existing first.
69pub(crate) async fn init_recovery_tables(db: &Db) -> Result<()> {
70    sqlx::query(
71        "CREATE TABLE IF NOT EXISTS rustio_password_reset_tokens (
72            id                    BIGSERIAL   PRIMARY KEY,
73            user_id               BIGINT      NOT NULL REFERENCES rustio_users(id) ON DELETE CASCADE,
74            token_hash            TEXT        NOT NULL,
75            requested_ip          TEXT,
76            requested_user_agent  TEXT,
77            requested_at          TIMESTAMPTZ NOT NULL DEFAULT NOW(),
78            expires_at            TIMESTAMPTZ NOT NULL,
79            consumed_at           TIMESTAMPTZ,
80            mail_status           TEXT        NOT NULL DEFAULT 'pending'
81                                  CHECK (mail_status IN ('pending', 'sent', 'failed')),
82            correlation_id        TEXT
83        )",
84    )
85    .execute(db.pool())
86    .await?;
87
88    // Partial unique on the active-token lookup. Guarantees the
89    // consume statement (`UPDATE … WHERE token_hash = $1 AND
90    // consumed_at IS NULL RETURNING …`) is an index seek even after
91    // the table accumulates consumed/expired rows for forensic
92    // retention.
93    sqlx::query(
94        "CREATE UNIQUE INDEX IF NOT EXISTS rustio_password_reset_tokens_active_uq \
95         ON rustio_password_reset_tokens (token_hash) \
96         WHERE consumed_at IS NULL",
97    )
98    .execute(db.pool())
99    .await?;
100
101    sqlx::query(
102        "CREATE INDEX IF NOT EXISTS rustio_password_reset_tokens_user_idx \
103         ON rustio_password_reset_tokens (user_id)",
104    )
105    .execute(db.pool())
106    .await?;
107
108    sqlx::query(
109        "CREATE INDEX IF NOT EXISTS rustio_password_reset_tokens_expires_idx \
110         ON rustio_password_reset_tokens (expires_at) \
111         WHERE consumed_at IS NULL",
112    )
113    .execute(db.pool())
114    .await?;
115
116    Ok(())
117}
118
119/// Add the additive recovery columns on `rustio_users`.
120///
121/// - `must_change_password BOOLEAN NOT NULL DEFAULT FALSE` — R2 will
122///   read this on login to force a password reset on the next sign-in.
123///   R1 introduces the column because R2's commit set stays narrower
124///   when the column already exists.
125/// - `password_changed_at TIMESTAMPTZ` (nullable) — populated by
126///   `auth::set_password` from R1 onwards. NULL for users created
127///   before the upgrade; the active-sessions UI renders "(unknown)" or
128///   omits the row when NULL.
129///
130/// Idempotent. Safe to call on every boot. Depends on `rustio_users`
131/// existing first.
132pub(crate) async fn migrate_user_recovery_schema(db: &Db) -> Result<()> {
133    sqlx::query(
134        "ALTER TABLE rustio_users \
135         ADD COLUMN IF NOT EXISTS must_change_password BOOLEAN NOT NULL DEFAULT FALSE",
136    )
137    .execute(db.pool())
138    .await?;
139
140    sqlx::query(
141        "ALTER TABLE rustio_users ADD COLUMN IF NOT EXISTS password_changed_at TIMESTAMPTZ",
142    )
143    .execute(db.pool())
144    .await?;
145
146    Ok(())
147}
148
149// ---- Password policy -------------------------------------------------------
150
151// public:
152/// Validates a candidate password against project-defined rules.
153///
154/// The framework ships [`DefaultPasswordPolicy`] (length-only floor)
155/// as the secure-by-default baseline. Projects layer a stronger
156/// policy via [`crate::admin::Admin::password_policy`] when
157/// regulation or risk requires it. The trait is `Send + Sync` so the
158/// `Arc<dyn PasswordPolicy>` lives on `Admin` and is cheap to clone
159/// into async futures.
160///
161/// ## Implementing a custom policy
162///
163/// ```ignore
164/// use rustio_admin::auth::{PasswordPolicy, PasswordPolicyError};
165///
166/// struct OrgPolicy;
167/// impl PasswordPolicy for OrgPolicy {
168///     fn validate(&self, candidate: &str) -> Result<(), PasswordPolicyError> {
169///         let len = candidate.chars().count();
170///         if len < 16 {
171///             return Err(PasswordPolicyError::TooShort { min: 16, actual: len });
172///         }
173///         if !candidate.chars().any(|c| c.is_ascii_digit()) {
174///             return Err(PasswordPolicyError::Custom(
175///                 "Password must contain at least one digit.".into(),
176///             ));
177///         }
178///         Ok(())
179///     }
180///     fn min_length(&self) -> usize { 16 }
181/// }
182/// ```
183///
184/// Implementations MUST treat the borrowed candidate as a secret:
185/// no logging, no panic-with-the-plaintext, no inclusion in the
186/// returned error. The framework's audit + log helpers redact
187/// passwords (`audit::redact_password()`); custom policies that
188/// want to surface a project-specific message use
189/// [`PasswordPolicyError::Custom`] with a user-safe string.
190pub trait PasswordPolicy: Send + Sync {
191    /// Approve or reject the candidate.
192    fn validate(&self, candidate: &str) -> std::result::Result<(), PasswordPolicyError>;
193
194    /// The minimum length the policy enforces, in Unicode `char`s.
195    /// Templates display this on the new-password form so users see
196    /// the floor before submitting.
197    fn min_length(&self) -> usize;
198}
199
200// public:
201/// Type-erased shared password-policy reference, mirroring
202/// [`crate::email::SharedMailer`]. The framework's `Admin` holds one
203/// of these; defaults to `Arc::new(DefaultPasswordPolicy::new())`
204/// until a project overrides via
205/// `Admin::password_policy(Arc::new(...))`.
206pub type SharedPasswordPolicy = Arc<dyn PasswordPolicy>;
207
208// public:
209/// Reasons a candidate password fails policy validation.
210///
211/// Variants intentionally omit the candidate plaintext — none of the
212/// fields carry the rejected password, so a `Display` / `Debug`
213/// rendering of any error value is safe to log, audit, or pass to a
214/// form-field renderer. Project-supplied policies that emit
215/// [`PasswordPolicyError::Custom`] are responsible for keeping their
216/// message free of the plaintext as well.
217#[derive(Debug, Clone, PartialEq, Eq)]
218#[non_exhaustive]
219pub enum PasswordPolicyError {
220    /// Length floor not met. Both fields are character counts (not
221    /// bytes), matching `min_length()`.
222    TooShort { min: usize, actual: usize },
223    /// Project-defined rejection. The string renders to the user
224    /// verbatim and lands in logs verbatim — keep it free of secrets.
225    Custom(String),
226}
227
228impl std::fmt::Display for PasswordPolicyError {
229    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
230        match self {
231            Self::TooShort { min, actual } => write!(
232                f,
233                "This password is too short. It must contain at least {min} characters \
234                 (you entered {actual})."
235            ),
236            Self::Custom(msg) => f.write_str(msg),
237        }
238    }
239}
240
241impl std::error::Error for PasswordPolicyError {}
242
243// public:
244/// Length-only password policy. Default `min_len` is **10** — the
245/// secure-by-default baseline R1 ships with: long enough to defeat
246/// trivial guessing under Argon2id + per-IP rate-limiting (NIST SP
247/// 800-63B's recommended length floor is 8, with longer being
248/// preferable), short enough not to drive operators toward sticky-
249/// note workarounds. Production / regulated deployments are
250/// encouraged to override to 12+ via
251/// [`crate::admin::Admin::password_policy`]; high-sensitivity
252/// deployments may want 16+ paired with an organisational
253/// complexity rule or breach blocklist.
254///
255/// The framework deliberately ships **no complexity-class rules**
256/// ("must contain a symbol", "must include uppercase") in the
257/// default — they demonstrably push humans toward predictable
258/// patterns without improving entropy meaningfully (NIST SP
259/// 800-63B Appendix A). Projects that need them implement a
260/// custom `PasswordPolicy`.
261#[derive(Debug, Clone, Copy)]
262pub struct DefaultPasswordPolicy {
263    pub min_len: usize,
264}
265
266impl DefaultPasswordPolicy {
267    // public:
268    /// New policy with the framework's default floor (`min_len = 10`).
269    pub const fn new() -> Self {
270        Self { min_len: 10 }
271    }
272
273    // public:
274    /// New policy with an explicit floor. Useful for projects that
275    /// want a stronger length baseline without authoring a full
276    /// `PasswordPolicy` impl.
277    pub const fn with_min_len(min_len: usize) -> Self {
278        Self { min_len }
279    }
280}
281
282impl Default for DefaultPasswordPolicy {
283    fn default() -> Self {
284        Self::new()
285    }
286}
287
288impl PasswordPolicy for DefaultPasswordPolicy {
289    fn validate(&self, candidate: &str) -> std::result::Result<(), PasswordPolicyError> {
290        // Count Unicode `char`s, not bytes — a 10-char password is
291        // 10 user-visible characters regardless of UTF-8 byte width.
292        // Grapheme-cluster counting is left to project policies that
293        // need it.
294        let actual = candidate.chars().count();
295        if actual < self.min_len {
296            return Err(PasswordPolicyError::TooShort {
297                min: self.min_len,
298                actual,
299            });
300        }
301        Ok(())
302    }
303
304    fn min_length(&self) -> usize {
305        self.min_len
306    }
307}
308
309// ---- Login throttle (R2) ---------------------------------------------------
310
311// public:
312/// Auto-throttle parameters for the login flow
313/// (`DESIGN_R2_ORGANISATIONAL.md` §3.3 + §12 locked decisions).
314///
315/// All three knobs are exposed via [`RecoveryPolicy::login_throttle`]
316/// so projects override the threshold without authoring a full trait
317/// impl. The locked default matches `DESIGN_R2_ORGANISATIONAL.md` §12:
318/// 5 failed attempts within a 10-minute sliding window trigger a
319/// 15-minute soft lock. Soft locks do NOT revoke sessions
320/// (Doctrine 22 + §13 locked-decision: only manual lock revokes).
321///
322/// Field semantics:
323///
324/// - `max_attempts` — failure count that trips the soft lock when
325///   reached within `window_minutes`. The counter is anchored on
326///   `rustio_users.last_failed_login_at` (R2 commit #1 schema) and
327///   logically resets when the window elapses.
328/// - `window_minutes` — sliding window over which `max_attempts` is
329///   measured. Failures older than this are ignored when evaluating
330///   the threshold.
331/// - `lock_minutes` — duration of the soft lock written to
332///   `rustio_users.locked_until` when the threshold trips.
333///
334/// Setting `max_attempts = 0` is valid and disables the auto-throttle
335/// entirely (no failure ever trips a soft lock). Manual lock via
336/// `/admin/users/:id/lock` (R2 commit #16) is independent of this
337/// struct.
338#[derive(Debug, Clone, Copy, PartialEq, Eq)]
339pub struct LoginThrottle {
340    /// Failure threshold within `window_minutes` that trips a soft
341    /// lock. Default `5`.
342    pub max_attempts: u32,
343    /// Sliding-window length, in minutes. Default `10`.
344    pub window_minutes: i64,
345    /// Soft-lock duration, in minutes. Default `15`.
346    pub lock_minutes: i64,
347}
348
349impl LoginThrottle {
350    // public:
351    /// The framework's locked default
352    /// (`DESIGN_R2_ORGANISATIONAL.md` §12): **5 failures /
353    /// 10-minute window / 15-minute soft lock**. `const`-constructible
354    /// so projects use it in `static` recovery-policy builders.
355    pub const DEFAULT: Self = Self {
356        max_attempts: 5,
357        window_minutes: 10,
358        lock_minutes: 15,
359    };
360}
361
362impl Default for LoginThrottle {
363    fn default() -> Self {
364        Self::DEFAULT
365    }
366}
367
368// ---- Recovery policy -------------------------------------------------------
369
370// public:
371/// Tunables for the R1 recovery flow: token TTL, rate-limit shape,
372/// strict-mailer boot guard, and public-site-URL derivation.
373///
374/// `Admin::new()` seeds [`DefaultRecoveryPolicy`]; projects override
375/// via [`crate::admin::Admin::recovery_policy`]. The trait is `Send +
376/// Sync` so the `Arc<dyn RecoveryPolicy>` lives on `Admin` and is
377/// cheap to clone into async futures.
378///
379/// The trait method `public_site_url` has a provided default that
380/// derives the URL from request headers via [`derive_public_site_url`]
381/// per `DESIGN_RECOVERY.md` §12.3. Projects whose deployment can't
382/// rely on the standard Forwarded / X-Forwarded-* / Host headers
383/// override this method and return their own absolute URL (e.g.
384/// stamped at deployment time from a config secret).
385///
386/// ## Trust boundary for forwarded headers
387///
388/// The default `public_site_url` honours these client-supplied
389/// inputs in priority order:
390///
391/// 1. RFC 7239 `Forwarded` header (`for / proto / host` of the first
392///    hop)
393/// 2. `X-Forwarded-Proto` + `X-Forwarded-Host` (first CSV entry of
394///    each)
395/// 3. `Host` header (assumes `http://`)
396///
397/// **The operator's reverse proxy MUST strip incoming versions of
398/// these headers before adding its own.** The framework cannot know
399/// the deployment topology; if a hostile client can reach the
400/// process directly with a chosen `Forwarded: …` header set, the
401/// reset link in the dispatched email will point wherever they ask.
402/// `proto` is whitelisted to `{http, https}` (case-insensitive) and
403/// `host` is rejected when it contains whitespace, control bytes, or
404/// CRLF — so direct injection of `\r\n`-style header smuggling
405/// fails — but a malicious yet shape-conformant value still needs
406/// to be filtered upstream.
407///
408/// Projects that need a stricter trust posture: override
409/// `public_site_url` to return a fixed string (e.g. read from
410/// project config at startup) and the framework will use that
411/// regardless of headers.
412pub trait RecoveryPolicy: Send + Sync {
413    /// How long a freshly-issued reset token stays valid. Default
414    /// 1 hour. Locked-decision per `DESIGN_RECOVERY.md` §17.
415    fn reset_token_ttl(&self) -> ChronoDuration;
416
417    /// Per-IP rate-limit on `POST /admin/forgot-password`. Returned
418    /// as `(capacity, window)`: at most `capacity` requests within
419    /// `window`. Default `(5, 15min)`.
420    fn request_rate_limit(&self) -> (u32, StdDuration);
421
422    /// Per-IP rate-limit on `POST /admin/reset-password/<token>`.
423    /// Tighter than the request limit since the consume path is the
424    /// brute-force surface. Default `(10, 5min)`.
425    fn consume_rate_limit(&self) -> (u32, StdDuration);
426
427    /// When `true`, the framework refuses to start at boot if the
428    /// registered mailer is still the default [`crate::email::LogMailer`]
429    /// (production deployments must opt in to a real mailer).
430    /// Default `false`. Enforcement lands when the recovery handlers
431    /// ship (R1 commit #7+); this commit ships the declaration only.
432    fn strict_mailer_required(&self) -> bool;
433
434    /// Derive the absolute base URL the reset email's link should
435    /// point at. Default: see [`derive_public_site_url`] +
436    /// trust-boundary docs on this trait. Projects override this
437    /// method to return a fixed string (e.g. read from config) when
438    /// header derivation isn't appropriate for their topology.
439    ///
440    /// Returns `None` when nothing resolves; the caller (R1 issue
441    /// handler, commit #7) treats `None` as a hard failure and
442    /// records `metadata.email_send_status = "failed"` with a clear
443    /// log line.
444    fn public_site_url(&self, req: &Request) -> Option<String> {
445        derive_public_site_url(|name| req.header(name).map(|s| s.to_string()))
446    }
447
448    // ---- R2 organisational-recovery extensions -----------------------------
449    //
450    // All three methods below have provided defaults so existing R1
451    // impls keep compiling. See `DESIGN_R2_ORGANISATIONAL.md` §6.3
452    // and §8.1 for the contract.
453
454    /// Auto-throttle parameters for the login flow. Default
455    /// [`LoginThrottle::DEFAULT`] (5 / 10min / 15min).
456    /// Projects override to relax for development environments
457    /// (`max_attempts: 100`) or tighten for high-sensitivity
458    /// deployments (`max_attempts: 3, lock_minutes: 60`).
459    ///
460    /// Setting `max_attempts = 0` disables the auto-throttle
461    /// entirely; manual lock via `/admin/users/:id/lock` (R2
462    /// commit #16) remains available.
463    fn login_throttle(&self) -> LoginThrottle {
464        LoginThrottle::default()
465    }
466
467    /// Window during which a session that has cleared the re-auth
468    /// wall (`/admin/reauth`) is considered *elevated* and may
469    /// access destructive admin-recovery surfaces (admin-driven
470    /// password reset, lock, unlock, revoke-sessions). Default
471    /// 15 minutes (`DESIGN_R2_ORGANISATIONAL.md` §12 locked-decision).
472    ///
473    /// Re-auth state lives on the session row's `elevated_until`
474    /// column (R0 schema, runtime lands in R2 commit #10). Returning
475    /// a duration of zero or negative is a no-op promotion: every
476    /// admin-recovery action will require a fresh re-auth.
477    fn reauth_window(&self) -> ChronoDuration {
478        ChronoDuration::minutes(15)
479    }
480
481    /// TOTP step interval in seconds. Locked at 30 per
482    /// `DESIGN_R3_MFA.md` Appendix B — RFC 6238 industry
483    /// standard for interop with every common authenticator app
484    /// (Google Authenticator, Authy, 1Password, Bitwarden,
485    /// Aegis, Raivo, etc.). Returning a different value would
486    /// break the QR provisioning URL's implicit period; the
487    /// design treats this as a major-version concern.
488    ///
489    /// The runtime consults this via
490    /// `auth::mfa::verify_totp_for_user` and
491    /// `auth::mfa::confirm_enrolment` (R3 commits #6, #7).
492    fn mfa_step_seconds(&self) -> u64 {
493        30
494    }
495
496    /// TOTP step skew tolerance, in steps. Locked at 1 per
497    /// `DESIGN_R3_MFA.md` Appendix B — gives a 90-second total
498    /// acceptance window at the canonical 30-second step
499    /// (`current ± 1` ≡ `[current - 1, current + 1]`). The
500    /// design treats wider skew as a security regression:
501    /// 2-step skew would accept a code generated 60 seconds
502    /// ago, which extends the network-replay window without
503    /// improving UX for users with reasonable clock drift.
504    ///
505    /// The runtime consults this via
506    /// `auth::mfa::verify_totp_for_user` and
507    /// `auth::mfa::confirm_enrolment` (R3 commits #6, #7).
508    fn mfa_skew_steps(&self) -> u32 {
509        1
510    }
511
512    /// Multi-tenant readiness hook. Returns `Some(scoped_policy)` to
513    /// scope rate-limits / TTLs / lockout windows per tenant when an
514    /// authenticated identity is in scope; returns `None` to mean
515    /// "no scoping, the caller continues to use the
516    /// `Admin`-bound recovery policy unchanged".
517    ///
518    /// Default returns `None` — single-tenant deployments see no
519    /// change. Multi-tenant projects override to look up the
520    /// tenant from `identity.user_id` (or a project-specific
521    /// claim) and return a fresh `Arc<dyn RecoveryPolicy>`
522    /// with that tenant's tunables. Per
523    /// `DESIGN_R2_ORGANISATIONAL.md` §6.3 the framework call site
524    /// is:
525    ///
526    /// ```ignore
527    /// let policy = admin
528    ///     .recovery_policy
529    ///     .scope_for(&identity)
530    ///     .unwrap_or_else(|| Arc::clone(&admin.recovery_policy));
531    /// ```
532    ///
533    /// Why `Option<SharedRecoveryPolicy>` and not
534    /// `SharedRecoveryPolicy` (as the design doc's first sketch
535    /// suggested): returning a fresh `Arc<Self>` from `&self`
536    /// requires the trait method to either receive the policy's own
537    /// `Arc` as a parameter (awkward at every call site) or rely on
538    /// `dyn-clone` (extra dependency). `Option::None` expresses
539    /// "no override" without either. Multi-tenant impls return
540    /// `Some(Arc::new(per_tenant_policy))`, which is cheap and
541    /// idiomatic.
542    fn scope_for(&self, _identity: &Identity) -> Option<SharedRecoveryPolicy> {
543        None
544    }
545}
546
547// public:
548/// Type-erased shared recovery-policy reference, mirroring
549/// [`SharedPasswordPolicy`] / [`crate::email::SharedMailer`].
550pub type SharedRecoveryPolicy = Arc<dyn RecoveryPolicy>;
551
552// public:
553/// Length-only / rate-limit-only baseline policy. Public fields plus
554/// chainable `with_*` setters so projects that want to tweak one knob
555/// don't need to author a full trait impl.
556#[derive(Debug, Clone)]
557pub struct DefaultRecoveryPolicy {
558    pub reset_token_ttl: ChronoDuration,
559    pub request_rate_limit: (u32, StdDuration),
560    pub consume_rate_limit: (u32, StdDuration),
561    pub strict_mailer_required: bool,
562}
563
564impl DefaultRecoveryPolicy {
565    // public:
566    /// New policy with the framework's locked defaults
567    /// (`DESIGN_RECOVERY.md` §17): TTL 1h, request 5/15min, consume
568    /// 10/5min, strict-mailer guard off.
569    pub fn new() -> Self {
570        Self {
571            reset_token_ttl: ChronoDuration::hours(1),
572            request_rate_limit: (5, StdDuration::from_secs(15 * 60)),
573            consume_rate_limit: (10, StdDuration::from_secs(5 * 60)),
574            strict_mailer_required: false,
575        }
576    }
577
578    // public:
579    /// Override the reset-token TTL. Projects that want shorter
580    /// blast-radius windows pass `Duration::minutes(30)`; projects
581    /// that need user-friendlier deadlines pass `Duration::hours(2)`.
582    pub fn with_reset_token_ttl(mut self, ttl: ChronoDuration) -> Self {
583        self.reset_token_ttl = ttl;
584        self
585    }
586
587    // public:
588    /// Override the request-endpoint rate-limit shape.
589    pub fn with_request_rate_limit(mut self, capacity: u32, window: StdDuration) -> Self {
590        self.request_rate_limit = (capacity, window);
591        self
592    }
593
594    // public:
595    /// Override the consume-endpoint rate-limit shape.
596    pub fn with_consume_rate_limit(mut self, capacity: u32, window: StdDuration) -> Self {
597        self.consume_rate_limit = (capacity, window);
598        self
599    }
600
601    // public:
602    /// Toggle the strict-mailer boot guard. When `true`, R1's boot
603    /// sequence (commits #7+) refuses to start with the default
604    /// `LogMailer`. Default `false`.
605    pub fn with_strict_mailer_required(mut self, required: bool) -> Self {
606        self.strict_mailer_required = required;
607        self
608    }
609}
610
611impl Default for DefaultRecoveryPolicy {
612    fn default() -> Self {
613        Self::new()
614    }
615}
616
617impl RecoveryPolicy for DefaultRecoveryPolicy {
618    fn reset_token_ttl(&self) -> ChronoDuration {
619        self.reset_token_ttl
620    }
621
622    fn request_rate_limit(&self) -> (u32, StdDuration) {
623        self.request_rate_limit
624    }
625
626    fn consume_rate_limit(&self) -> (u32, StdDuration) {
627        self.consume_rate_limit
628    }
629
630    fn strict_mailer_required(&self) -> bool {
631        self.strict_mailer_required
632    }
633
634    // public_site_url uses the trait's provided default.
635}
636
637/// Pure helper for the default `RecoveryPolicy::public_site_url`
638/// implementation, factored out so the parser can be unit-tested
639/// without constructing a full [`Request`].
640///
641/// `header` is a closure that returns the named header's value (case-
642/// insensitive name match, owned `String` because the default
643/// closure copies out of the request's borrowed buffer).
644///
645/// Priority order — first source that resolves to a safe
646/// `(proto, host)` pair wins:
647///
648/// 1. RFC 7239 `Forwarded` — first comma-separated entry's
649///    `proto=` + `host=` pairs.
650/// 2. `X-Forwarded-Proto` + `X-Forwarded-Host` — first CSV entry of
651///    each, both required to fall through if either's missing.
652/// 3. `Host` header alone — assumes `http://` (no HTTPS guesswork).
653///
654/// Returns `None` when nothing resolves. Never panics on malformed
655/// input — see the test suite's `malformed_forwarded_inputs_never_panic`
656/// for the property check.
657///
658/// **Trust:** see the `RecoveryPolicy` trait's "Trust boundary"
659/// section. The operator's reverse proxy is responsible for
660/// stripping incoming versions of these headers before its own
661/// hop appends them.
662pub(crate) fn derive_public_site_url<F>(header: F) -> Option<String>
663where
664    F: Fn(&str) -> Option<String>,
665{
666    // 1. RFC 7239 Forwarded — first hop
667    if let Some(value) = header("forwarded") {
668        if let Some(url) = parse_forwarded_first_hop(&value) {
669            return Some(url);
670        }
671    }
672
673    // 2. X-Forwarded-Proto + X-Forwarded-Host
674    let xfp = header("x-forwarded-proto").and_then(|s| first_csv(&s).map(|v| v.to_string()));
675    let xfh = header("x-forwarded-host").and_then(|s| first_csv(&s).map(|v| v.to_string()));
676    if let (Some(proto), Some(host)) = (xfp, xfh) {
677        if is_safe_proto(&proto) && is_safe_host(&host) {
678            return Some(format!("{}://{}", proto.to_ascii_lowercase(), host));
679        }
680    }
681
682    // 3. Host header — assume http
683    if let Some(host) = header("host") {
684        if is_safe_host(&host) {
685            return Some(format!("http://{host}"));
686        }
687    }
688
689    None
690}
691
692/// Take the first comma-separated, trimmed, non-empty token of `s`.
693fn first_csv(s: &str) -> Option<&str> {
694    let trimmed = s.split(',').next()?.trim();
695    if trimmed.is_empty() {
696        None
697    } else {
698        Some(trimmed)
699    }
700}
701
702/// Whitelist: only `http` and `https` are accepted. Case-insensitive.
703fn is_safe_proto(p: &str) -> bool {
704    p.eq_ignore_ascii_case("http") || p.eq_ignore_ascii_case("https")
705}
706
707/// Reject empty / over-long / control-char / whitespace hosts. Allows
708/// alphanumerics, the dot/dash/underscore separators, the colon for
709/// the `host:port` shape, and `[` / `]` for IPv6 literals.
710fn is_safe_host(h: &str) -> bool {
711    if h.is_empty() || h.len() > 253 {
712        return false;
713    }
714    h.chars()
715        .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | ':' | '-' | '_' | '[' | ']'))
716}
717
718/// Parse `proto=` and `host=` from the FIRST comma-separated entry
719/// of an RFC 7239 `Forwarded` header value. Returns the canonical
720/// `proto://host` URL, or `None` if either is missing or fails the
721/// safety check.
722fn parse_forwarded_first_hop(value: &str) -> Option<String> {
723    let first = value.split(',').next()?;
724    let mut proto: Option<&str> = None;
725    let mut host: Option<&str> = None;
726
727    for pair in first.split(';') {
728        let pair = pair.trim();
729        if pair.is_empty() {
730            continue;
731        }
732        let (key, val) = match pair.split_once('=') {
733            Some(p) => p,
734            None => continue,
735        };
736        let key = key.trim();
737        // Strip surrounding quotes if present (RFC 7239 allows
738        // quoted-string syntax for values containing special chars).
739        let val = val.trim().trim_matches('"');
740        if val.is_empty() {
741            continue;
742        }
743        if key.eq_ignore_ascii_case("proto") {
744            proto = Some(val);
745        } else if key.eq_ignore_ascii_case("host") {
746            host = Some(val);
747        }
748    }
749
750    let proto = proto?;
751    let host = host?;
752    if !is_safe_proto(proto) || !is_safe_host(host) {
753        return None;
754    }
755    Some(format!("{}://{}", proto.to_ascii_lowercase(), host))
756}
757
758// ---- Runtime: token issuance + consumption -------------------------------
759
760/// Outcome of [`issue_reset_token`]. Variants exist for
761/// observability and testability — the user-facing handler renders
762/// the same uniform "if that email has an account, we just sent a
763/// link" page across every variant per the disclosure rule
764/// (`DESIGN_RECOVERY.md` §2.3).
765#[derive(Debug, Clone, PartialEq, Eq)]
766pub(crate) enum IssueOutcome {
767    /// A token row was inserted; the mailer dispatch attempt
768    /// finished (see `email_status` for whether the message
769    /// actually went out). One audit row written
770    /// (`AuditEvent::PasswordResetSelfRequest`).
771    Issued {
772        token_id: i64,
773        email_status: MailerEmailStatus,
774    },
775    /// Email didn't match an active user — either unknown OR
776    /// deactivated. The two sub-cases are deliberately
777    /// indistinguishable from outside (doctrine 9, §2.3 disclosure
778    /// rule). No DB row, no audit, no mail. A `log::info!` line is
779    /// written for operator-side visibility, but it never carries
780    /// a token, password, or anything that could be used for
781    /// enumeration analysis later.
782    UnknownOrInactive,
783    /// Per-IP rate-limit on the request endpoint exhausted. No DB
784    /// row. Renderer treats this identically to `Issued` /
785    /// `UnknownOrInactive` (uniform-response invariant).
786    RateLimited,
787}
788
789// internal:
790/// Whether the mailer's `send` call returned `Ok` or a typed
791/// `MailerError`. Persisted on the token row's `mail_status` column
792/// and into the audit row's `metadata.email_send_status`.
793#[derive(Debug, Clone, Copy, PartialEq, Eq)]
794pub enum MailerEmailStatus {
795    Sent,
796    Failed,
797}
798
799/// Outcome of [`consume_reset_token`]. The user-facing handler
800/// renders `Invalid` and `RateLimited` identically (the "this link
801/// is no longer valid" page) per disclosure rule §2.3 — the variant
802/// distinction exists for observability + tests, not for branching
803/// the UI.
804#[derive(Debug, Clone, PartialEq, Eq)]
805pub(crate) enum ConsumeOutcome {
806    /// Token consumed atomically; password updated; every session
807    /// for the affected user revoked through
808    /// `invalidate_sessions(SessionTarget::User { user_id },
809    /// SessionInvalidationReason::PasswordReset)`. One audit row
810    /// written (`AuditEvent::PasswordResetSelfConsume`).
811    Consumed {
812        user_id: i64,
813        revoked_session_count: usize,
814    },
815    /// Token unknown / expired / already consumed (the three are
816    /// deliberately indistinguishable per §2.3). No password
817    /// change, no session revocation, no audit row written. A
818    /// `log::info!` line carries the token's redacted fingerprint
819    /// for cross-row pivoting if the operator needs to investigate.
820    Invalid,
821    /// `PasswordPolicy::validate` rejected the candidate password.
822    /// No DB mutation: the token stays valid for retry; the form
823    /// re-renders with the policy error. The error itself is safe
824    /// to render — `PasswordPolicyError` variants do not carry the
825    /// candidate plaintext (see commit #4's leak-prevention test).
826    PolicyRejected(PasswordPolicyError),
827    /// Per-IP rate-limit on the consume endpoint exhausted. No DB
828    /// mutation. Renderer treats this identically to `Invalid`.
829    RateLimited,
830}
831
832/// Issue a password-reset token for `email` — or pretend to,
833/// preserving the uniform-response invariant.
834///
835/// See `DESIGN_RECOVERY.md` §4.2 for the canonical contract this
836/// implements. The function is `pub(crate)` because the framework
837/// owns the route shape (CSRF, rate-limit middleware, render
838/// pipeline). External projects compose recovery via the trait
839/// surfaces ([`PasswordPolicy`], [`RecoveryPolicy`],
840/// [`crate::email::Mailer`]) rather than calling this directly.
841///
842/// ## Security properties (LOCKED)
843///
844/// - The plaintext token leaves this function only as part of the
845///   email body dispatched through [`crate::email::Mailer`]. The DB
846///   row stores `token_hash = sha256(token)` only.
847/// - Outward result is uniform: `IssueOutcome::Issued`,
848///   `UnknownOrInactive`, and `RateLimited` all map to the same
849///   user-facing page in the handler (commit #8). The variant
850///   distinction is for audit + tests only.
851/// - No `log::info!` / `log::error!` / audit row contains the
852///   plaintext token. Logs use [`redact_token`] (8-char SHA-256
853///   fingerprint); audit metadata stores `token_fingerprint`.
854/// - On mailer failure (transient OR permanent OR `public_site_url`
855///   derivation returning None), the outward result is still
856///   `IssueOutcome::Issued { email_status: Failed }` — the row
857///   exists with `mail_status = 'failed'` and the audit row carries
858///   `email_send_status = "failed"`. The user sees the uniform
859///   response.
860pub(crate) async fn issue_reset_token(
861    db: &Db,
862    admin: &Admin,
863    request_limiter: &RateLimiter,
864    request: &Request,
865    email: &str,
866    correlation_id: Option<&str>,
867) -> Result<IssueOutcome> {
868    let ip = extract_request_ip(request);
869
870    // 1. Per-IP rate-limit — bucket exhaustion → uniform response.
871    if !request_limiter.allow(&ip) {
872        log::info!(
873            target: "rustio_admin::recovery::issue",
874            "rate-limit exhausted ip={} correlation_id={:?}",
875            ip,
876            correlation_id,
877        );
878        return Ok(IssueOutcome::RateLimited);
879    }
880
881    // 2. Normalise email input.
882    let email_input = email.trim().to_ascii_lowercase();
883    if email_input.is_empty() {
884        log::info!(
885            target: "rustio_admin::recovery::issue",
886            "empty-email submission ip={} correlation_id={:?}",
887            ip,
888            correlation_id,
889        );
890        return Ok(IssueOutcome::UnknownOrInactive);
891    }
892
893    // 3. User lookup. Both unknown-email and inactive-user collapse
894    //    into UnknownOrInactive — leaking either creates an
895    //    enumeration channel.
896    let user = match find_user_by_email(db, &email_input).await? {
897        Some(u) if u.is_active => u,
898        Some(u) => {
899            log::info!(
900                target: "rustio_admin::recovery::issue",
901                "inactive-user submission user_id={} ip={} correlation_id={:?}",
902                u.id,
903                ip,
904                correlation_id,
905            );
906            return Ok(IssueOutcome::UnknownOrInactive);
907        }
908        None => {
909            log::info!(
910                target: "rustio_admin::recovery::issue",
911                "unknown-email submission ip={} correlation_id={:?}",
912                ip,
913                correlation_id,
914            );
915            return Ok(IssueOutcome::UnknownOrInactive);
916        }
917    };
918
919    // 4. Generate token. 256-bit URL-safe-base64. Plaintext lives
920    //    only here, in the email body, and in the user's mailbox —
921    //    NEVER in the DB, NEVER in any log line.
922    let token = random_token();
923    let token_hash = hash_token_for_storage(&token);
924
925    // 5. Insert the token row with mail_status = 'pending'.
926    let policy = admin.active_recovery_policy();
927    let ttl = policy.reset_token_ttl();
928    let expires_at = chrono::Utc::now() + ttl;
929    let user_agent_owned = request.header("user-agent").map(|s| s.to_string());
930
931    let token_id: i64 = sqlx::query_scalar(
932        "INSERT INTO rustio_password_reset_tokens
933            (user_id, token_hash, requested_ip, requested_user_agent,
934             expires_at, mail_status, correlation_id)
935         VALUES ($1, $2, $3, $4, $5, 'pending', $6)
936       RETURNING id",
937    )
938    .bind(user.id)
939    .bind(&token_hash)
940    .bind(&ip)
941    .bind(user_agent_owned.as_deref())
942    .bind(expires_at)
943    .bind(correlation_id)
944    .fetch_one(db.pool())
945    .await?;
946
947    // 6. Compose + dispatch mail. If site-URL derivation fails or
948    //    the mailer returns an error, mark mail_status = 'failed'
949    //    and continue — the user-facing response stays uniform.
950    let mail_status = match policy.public_site_url(request) {
951        Some(public_site_url) => {
952            let reset_link = format!(
953                "{}/admin/reset-password/{}",
954                public_site_url.trim_end_matches('/'),
955                token,
956            );
957            let when = chrono::Utc::now();
958            let ttl_human = humanize_ttl(ttl);
959            let branding = admin.branding();
960            let app_name = branding.app_name.clone();
961            let app_tagline = branding.app_tagline.clone();
962            let support_email = branding.support_email.clone();
963            let show_powered_by = branding.show_powered_by;
964            let greeting = user.greeting_name();
965            let (sig_primary, sig_title) = user.signature_lines();
966            let body = format!(
967                "Hello {greeting},\n\n\
968                 We received a request to reset the password for your \
969                 {app_name} account.\n\n\
970                 Open the link below to set a new password:\n\n\
971                 {reset_link}\n\n\
972                 This link expires {ttl_human}. If you didn't request \
973                 this, you can safely ignore this email — your password \
974                 stays unchanged.\n",
975            );
976            let intro = format!(
977                "We received a request to reset the password for your \
978                 {app_name} account. Choose a new password to continue."
979            );
980            let fine_print = format!("This link expires {ttl_human}.");
981            let html = crate::email::render_recovery_html(crate::email::RecoveryEmailParts {
982                app_name: &app_name,
983                app_tagline: app_tagline.as_deref(),
984                title: "Reset your password",
985                greeting_name: &greeting,
986                intro: &intro,
987                cta_label: "Set a new password",
988                cta_url: &reset_link,
989                fine_print: &fine_print,
990                when,
991                request_ip: Some(&ip),
992                ua_summary: user_agent_owned.as_deref(),
993                correlation_id,
994                signature_primary: Some(&sig_primary),
995                signature_title: sig_title.as_deref(),
996                support_email: support_email.as_deref(),
997                show_powered_by,
998            });
999            let mail = Mail::framework_envelope(
1000                user.email.clone(),
1001                format!("Reset your password — {app_name}"),
1002                body,
1003                &app_name,
1004                Some(&ip),
1005                user_agent_owned.as_deref(),
1006                when,
1007            )
1008            .with_html(html);
1009            match admin.active_mailer().send(mail).await {
1010                Ok(()) => {
1011                    set_token_mail_status(db, token_id, "sent").await?;
1012                    MailerEmailStatus::Sent
1013                }
1014                Err(e) => {
1015                    log::error!(
1016                        target: "rustio_admin::recovery::issue",
1017                        "mailer send failed user_id={} fingerprint={} correlation_id={:?}: {}",
1018                        user.id,
1019                        redact_token(&token),
1020                        correlation_id,
1021                        e,
1022                    );
1023                    set_token_mail_status(db, token_id, "failed").await?;
1024                    MailerEmailStatus::Failed
1025                }
1026            }
1027        }
1028        None => {
1029            log::error!(
1030                target: "rustio_admin::recovery::issue",
1031                "public_site_url derivation returned None — reset link cannot be built. \
1032                 user_id={} fingerprint={} correlation_id={:?}",
1033                user.id,
1034                redact_token(&token),
1035                correlation_id,
1036            );
1037            set_token_mail_status(db, token_id, "failed").await?;
1038            MailerEmailStatus::Failed
1039        }
1040    };
1041
1042    // 7. Audit row. Token fingerprint, NEVER the plaintext.
1043    let metadata = serde_json::json!({
1044        "token_fingerprint": redact_token(&token),
1045        "email_send_status": match mail_status {
1046            MailerEmailStatus::Sent => "sent",
1047            MailerEmailStatus::Failed => "failed",
1048        },
1049        "requested_ip": ip,
1050        "requested_user_agent": user_agent_owned,
1051        "expires_at": expires_at.to_rfc3339(),
1052    });
1053    let mut entry = LogEntry::new(user.id, ActionType::Update, "users", user.id)
1054        .with_event(AuditEvent::PasswordResetSelfRequest);
1055    entry.correlation_id = correlation_id;
1056    entry.ip_address = Some(&ip);
1057    entry.metadata = Some(metadata);
1058    entry.summary = format!(
1059        "password reset requested; mail {}",
1060        match mail_status {
1061            MailerEmailStatus::Sent => "sent",
1062            MailerEmailStatus::Failed => "failed",
1063        }
1064    );
1065    audit_record(db, entry).await?;
1066
1067    Ok(IssueOutcome::Issued {
1068        token_id,
1069        email_status: mail_status,
1070    })
1071}
1072
1073/// Consume a reset token, set the new password, revoke every
1074/// session for the affected user.
1075///
1076/// See `DESIGN_RECOVERY.md` §4.3 for the canonical contract this
1077/// implements. The function is `pub(crate)` for the same reason
1078/// [`issue_reset_token`] is.
1079///
1080/// ## Security properties (LOCKED)
1081///
1082/// - **Atomic consume.** The single SQL statement
1083///   `UPDATE … SET consumed_at = NOW() WHERE token_hash = $1 AND
1084///    consumed_at IS NULL AND expires_at > NOW() RETURNING user_id`
1085///   is the only place a token's `consumed_at` flips. The partial
1086///   unique index `WHERE consumed_at IS NULL` (commit #1) makes
1087///   concurrent consumes resolve as one Consumed + one Invalid —
1088///   never two of either.
1089/// - **Policy first, consume second.** A bad password fails
1090///   validation BEFORE the atomic UPDATE, so the user can fix the
1091///   form and retry without burning a token.
1092/// - **Doctrine 22.** Session revocation goes through
1093///   `invalidate_sessions(SessionTarget::User, …PasswordReset)` —
1094///   the framework's only `revoked_at` writer.
1095/// - No log / audit row contains the plaintext token. Token
1096///   fingerprints (8-char SHA-256) are used for cross-row pivoting
1097///   when an operator needs to trace activity.
1098/// - The handler MUST NOT auto-log-in the user on success — they
1099///   go through `/admin/login` so MFA (R3+) gets exercised.
1100pub(crate) async fn consume_reset_token(
1101    db: &Db,
1102    admin: &Admin,
1103    consume_limiter: &RateLimiter,
1104    request: &Request,
1105    token: &str,
1106    new_password: &str,
1107    correlation_id: Option<&str>,
1108) -> Result<ConsumeOutcome> {
1109    let ip = extract_request_ip(request);
1110
1111    // 1. Per-IP rate-limit — bucket exhaustion → render Invalid.
1112    if !consume_limiter.allow(&ip) {
1113        log::info!(
1114            target: "rustio_admin::recovery::consume",
1115            "rate-limit exhausted ip={} correlation_id={:?}",
1116            ip,
1117            correlation_id,
1118        );
1119        return Ok(ConsumeOutcome::RateLimited);
1120    }
1121
1122    // 2. Validate password against policy. A bad password does NOT
1123    //    burn the token; the user re-tries the form.
1124    if let Err(e) = admin.active_password_policy().validate(new_password) {
1125        return Ok(ConsumeOutcome::PolicyRejected(e));
1126    }
1127
1128    // 3. Atomic consume — see "Atomic consume" doctrine in the
1129    //    function-level docs above.
1130    let token_hash = hash_token_for_storage(token);
1131    let user_id: Option<i64> = sqlx::query_scalar(
1132        "UPDATE rustio_password_reset_tokens
1133            SET consumed_at = NOW()
1134          WHERE token_hash = $1
1135            AND consumed_at IS NULL
1136            AND expires_at > NOW()
1137        RETURNING user_id",
1138    )
1139    .bind(&token_hash)
1140    .fetch_optional(db.pool())
1141    .await?;
1142
1143    let user_id = match user_id {
1144        Some(uid) => uid,
1145        None => {
1146            log::info!(
1147                target: "rustio_admin::recovery::consume",
1148                "consume on invalid/expired/consumed token ip={} fingerprint={} correlation_id={:?}",
1149                ip,
1150                redact_token(token),
1151                correlation_id,
1152            );
1153            return Ok(ConsumeOutcome::Invalid);
1154        }
1155    };
1156
1157    // 4. Set new password. `set_password` stamps
1158    //    `password_changed_at` (commit #2). If this fails the
1159    //    token is consumed but password unchanged — rare DB-error
1160    //    mode, surfaces in logs; the user re-runs the request flow.
1161    set_password(db, user_id, new_password).await?;
1162
1163    // 5. Doctrine 22: every session for the user goes through
1164    //    `invalidate_sessions`. Single writer of `revoked_at`.
1165    let outcome = invalidate_sessions(
1166        db,
1167        SessionTarget::User { user_id },
1168        SessionInvalidationReason::PasswordReset,
1169    )
1170    .await?;
1171    let revoked_session_count = outcome.revoked_session_ids.len();
1172
1173    // 6. Audit row. Token fingerprint only.
1174    let user_agent_owned = request.header("user-agent").map(|s| s.to_string());
1175    let metadata = serde_json::json!({
1176        "token_fingerprint": redact_token(token),
1177        "invalidated_session_count": revoked_session_count,
1178        "ip": ip,
1179        "user_agent": user_agent_owned,
1180    });
1181    let mut entry = LogEntry::new(user_id, ActionType::Update, "users", user_id)
1182        .with_event(AuditEvent::PasswordResetSelfConsume);
1183    entry.correlation_id = correlation_id;
1184    entry.ip_address = Some(&ip);
1185    entry.metadata = Some(metadata);
1186    entry.summary =
1187        format!("password reset self-consumed; {revoked_session_count} session(s) revoked");
1188    audit_record(db, entry).await?;
1189
1190    Ok(ConsumeOutcome::Consumed {
1191        user_id,
1192        revoked_session_count,
1193    })
1194}
1195
1196/// Non-mutating check used by the `GET /admin/reset-password/<token>`
1197/// handler (R1 commit #8) to decide whether to render the new-
1198/// password form or the "this link is no longer valid" card. The
1199/// `POST` path still performs the atomic consume regardless — the
1200/// GET-time check is purely a UX courtesy so a user clicking a
1201/// stale link doesn't fill in the form before being told it's
1202/// invalid.
1203///
1204/// Disclosure-equivalent to the consume path: returns `false` for
1205/// unknown / expired / already-consumed tokens. The three sub-cases
1206/// are deliberately indistinguishable to the caller so the renderer
1207/// can't accidentally branch on them (`DESIGN_RECOVERY.md` §2.3).
1208pub(crate) async fn check_reset_token_valid(db: &Db, token: &str) -> Result<bool> {
1209    // Postgres treats `SELECT 1` as INT4; binding the result to
1210    // `Option<i64>` produces a runtime decode mismatch that lands
1211    // as a 500 (downstream validation pass caught it before
1212    // 0.5.0 publish). We `SELECT id` instead — the `id` column is
1213    // BIGSERIAL → INT8, matching `Option<i64>` cleanly, and the
1214    // semantics of "does any row match" are identical. A mistaken
1215    // `Option<i32>` would also work but would drift from the
1216    // sibling `consume_reset_token` query that returns the same
1217    // column shape.
1218    let token_hash = hash_token_for_storage(token);
1219    let exists: Option<i64> = sqlx::query_scalar(
1220        "SELECT id FROM rustio_password_reset_tokens
1221          WHERE token_hash = $1
1222            AND consumed_at IS NULL
1223            AND expires_at > NOW()
1224          LIMIT 1",
1225    )
1226    .bind(&token_hash)
1227    .fetch_optional(db.pool())
1228    .await?;
1229    Ok(exists.is_some())
1230}
1231
1232/// Retention window after a reset-token row's `expires_at` before
1233/// the periodic sweeper purges it. Locked at 7 days
1234/// (`DESIGN_RECOVERY.md` §4.4): the recently-expired window keeps
1235/// the row available for audit correlation, operational debugging,
1236/// and abuse investigations; after 7 days the row's forensic value
1237/// is gone and it disappears.
1238///
1239/// Applies to BOTH consumed and unconsumed rows — once the
1240/// `expires_at` is more than 7 days in the past, neither
1241/// classification carries operational value worth retaining.
1242const RESET_TOKEN_RETENTION_DAYS: i64 = 7;
1243
1244/// Periodically-callable purge of stale reset-token rows. Wired
1245/// into `background::spawn_session_sweeper` (R1 commit #12) on a
1246/// 10-minute tick alongside the session sweeper.
1247///
1248/// **Deletion criterion:** `expires_at < NOW() - INTERVAL '7 days'`.
1249/// One single `DELETE` statement; no per-row loop. The framework's
1250/// partial expires-at index from commit #1 covers the unconsumed-
1251/// row hot path; consumed rows fall to a heap scan over a small
1252/// portion of the table (admin-tier scale, acceptable).
1253///
1254/// **Idempotency:** the predicate is purely time-based against
1255/// `NOW()`; running the function twice in quick succession
1256/// deletes the same rows the first time and returns 0 the second.
1257/// Safe to call from any number of concurrent ticks.
1258///
1259/// **What this function does NOT do:**
1260///
1261/// - Does NOT touch `rustio_users`, `rustio_sessions`, or
1262///   `rustio_admin_actions`. Cleanup is scoped to the recovery
1263///   table; no auth / session / audit behaviour is affected.
1264/// - Does NOT emit audit rows for the deletions — the cleaned-up
1265///   rows themselves carry the forensic record (token_fingerprint,
1266///   correlation_id), and the sweep is operational rather than
1267///   user-facing.
1268/// - Does NOT write to `revoked_at` (Doctrine 22 — the only
1269///   `revoked_at` writer remains `auth::sessions::invalidate_sessions`).
1270/// - Does NOT log any token identifier, user identifier, or
1271///   correlation id. The single info-level line on success records
1272///   only the deleted-row count.
1273pub(crate) async fn purge_expired_reset_tokens(db: &Db) -> Result<u64> {
1274    // The retention window is embedded as a literal in the SQL
1275    // (Postgres INTERVAL doesn't bind cleanly via sqlx). The
1276    // constant + the test below pin the value; a drift would
1277    // surface mechanically.
1278    let query = format!(
1279        "DELETE FROM rustio_password_reset_tokens \
1280          WHERE expires_at < NOW() - INTERVAL '{RESET_TOKEN_RETENTION_DAYS} days'"
1281    );
1282    let result = sqlx::query(&query).execute(db.pool()).await?;
1283    Ok(result.rows_affected())
1284}
1285
1286/// Update an issued token's `mail_status` column. Only the values
1287/// `'pending' | 'sent' | 'failed'` are valid (CHECK constraint
1288/// added in commit #1).
1289async fn set_token_mail_status(db: &Db, token_id: i64, status: &str) -> Result<()> {
1290    sqlx::query(
1291        "UPDATE rustio_password_reset_tokens
1292            SET mail_status = $1
1293          WHERE id = $2",
1294    )
1295    .bind(status)
1296    .bind(token_id)
1297    .execute(db.pool())
1298    .await?;
1299    Ok(())
1300}
1301
1302/// Best-effort client-IP extraction from the `X-Forwarded-For`
1303/// header — first comma-separated entry, trimmed. Falls back to
1304/// `"anon"` when no proxy header is present; rate-limit buckets
1305/// all anonymous requests under one key in that case (acceptable
1306/// for single-tenant deployments; multi-tenant deployments behind
1307/// an unconfigured proxy get noisy and should set the header
1308/// upstream).
1309fn extract_request_ip(request: &Request) -> String {
1310    request
1311        .header("x-forwarded-for")
1312        .and_then(|v| v.split(',').next())
1313        .map(|s| s.trim().to_string())
1314        .filter(|s| !s.is_empty())
1315        .unwrap_or_else(|| "anon".to_string())
1316}
1317
1318/// Render a `chrono::Duration` as a human-readable email-body
1319/// string (e.g. `"in 1 hour"`, `"in 30 minutes"`). Boundary cases
1320/// fall back gracefully — never returns an empty / grammatically
1321/// broken string.
1322fn humanize_ttl(ttl: ChronoDuration) -> String {
1323    let secs = ttl.num_seconds();
1324    if secs <= 0 {
1325        return "very soon".to_string();
1326    }
1327    if ttl.num_hours() >= 1 {
1328        let h = ttl.num_hours();
1329        return if h == 1 {
1330            "in 1 hour".to_string()
1331        } else {
1332            format!("in {h} hours")
1333        };
1334    }
1335    if ttl.num_minutes() >= 1 {
1336        let m = ttl.num_minutes();
1337        return if m == 1 {
1338            "in 1 minute".to_string()
1339        } else {
1340            format!("in {m} minutes")
1341        };
1342    }
1343    if secs == 1 {
1344        "in 1 second".to_string()
1345    } else {
1346        format!("in {secs} seconds")
1347    }
1348}
1349
1350#[cfg(test)]
1351mod tests {
1352    use super::*;
1353
1354    #[test]
1355    fn default_policy_floor_is_ten() {
1356        assert_eq!(DefaultPasswordPolicy::new().min_length(), 10);
1357        assert_eq!(DefaultPasswordPolicy::default().min_length(), 10);
1358    }
1359
1360    #[test]
1361    fn default_policy_accepts_password_at_floor() {
1362        let p = DefaultPasswordPolicy::new();
1363        // Exactly 10 chars — the doctrine-locked default floor.
1364        assert!(p.validate("aaaaaaaaaa").is_ok());
1365        // Comfortable margin.
1366        assert!(p.validate("correct horse battery staple").is_ok());
1367    }
1368
1369    #[test]
1370    fn default_policy_rejects_short_password() {
1371        let p = DefaultPasswordPolicy::new();
1372        let err = p.validate("nine_char").unwrap_err();
1373        assert_eq!(err, PasswordPolicyError::TooShort { min: 10, actual: 9 });
1374    }
1375
1376    #[test]
1377    fn default_policy_rejects_empty_password() {
1378        let p = DefaultPasswordPolicy::new();
1379        let err = p.validate("").unwrap_err();
1380        assert_eq!(err, PasswordPolicyError::TooShort { min: 10, actual: 0 });
1381    }
1382
1383    #[test]
1384    fn default_policy_with_min_len_overrides_floor() {
1385        let p = DefaultPasswordPolicy::with_min_len(16);
1386        assert_eq!(p.min_length(), 16);
1387        assert!(p.validate("fifteen_chars__").is_err()); // 15 chars
1388        assert!(p.validate("sixteen_chars___").is_ok()); //  16 chars
1389    }
1390
1391    #[test]
1392    fn default_policy_counts_chars_not_bytes() {
1393        let p = DefaultPasswordPolicy::new();
1394        // 10 Cyrillic chars = 20 bytes. Char count passes the floor.
1395        let pw = "пароль1234";
1396        assert_eq!(pw.chars().count(), 10);
1397        assert!(pw.len() > 10);
1398        assert!(p.validate(pw).is_ok());
1399
1400        // 9 Cyrillic chars must fail with the char count, not the
1401        // byte count.
1402        let pw = "пароль123";
1403        let err = p.validate(pw).unwrap_err();
1404        assert_eq!(err, PasswordPolicyError::TooShort { min: 10, actual: 9 });
1405    }
1406
1407    #[test]
1408    fn error_renderings_do_not_leak_plaintext() {
1409        // Property: neither Display nor Debug formatting of a
1410        // policy error rendered for a rejected candidate leaks the
1411        // candidate string. Picked plaintext is unlikely to collide
1412        // with English words in the default error message.
1413        let p = DefaultPasswordPolicy::new();
1414        let plaintext = "Pwn4Ge#xy"; // 9 chars — fails the 10-char floor
1415        let err = p.validate(plaintext).unwrap_err();
1416        let display = format!("{err}");
1417        let debug = format!("{err:?}");
1418        assert!(
1419            !display.contains(plaintext),
1420            "Display leaked plaintext: {display}"
1421        );
1422        assert!(
1423            !debug.contains(plaintext),
1424            "Debug leaked plaintext: {debug}"
1425        );
1426    }
1427
1428    #[test]
1429    fn custom_error_renders_message_verbatim() {
1430        let err = PasswordPolicyError::Custom("breached password rejected".into());
1431        assert_eq!(format!("{err}"), "breached password rejected");
1432    }
1433
1434    #[test]
1435    fn shared_password_policy_is_send_sync() {
1436        // Compile-time guarantee that the trait-object alias retains
1437        // the bounds the framework relies on.
1438        fn assert_send_sync<T: Send + Sync>() {}
1439        assert_send_sync::<SharedPasswordPolicy>();
1440    }
1441
1442    // ---- recovery policy ---------------------------------------------------
1443
1444    #[test]
1445    fn default_recovery_policy_ttl_is_one_hour() {
1446        let p = DefaultRecoveryPolicy::new();
1447        assert_eq!(p.reset_token_ttl(), ChronoDuration::hours(1));
1448    }
1449
1450    #[test]
1451    fn default_recovery_policy_request_rate_limit_is_five_per_fifteen_min() {
1452        let p = DefaultRecoveryPolicy::new();
1453        assert_eq!(p.request_rate_limit(), (5, StdDuration::from_secs(15 * 60)));
1454    }
1455
1456    #[test]
1457    fn default_recovery_policy_consume_rate_limit_is_ten_per_five_min() {
1458        let p = DefaultRecoveryPolicy::new();
1459        assert_eq!(p.consume_rate_limit(), (10, StdDuration::from_secs(5 * 60)));
1460    }
1461
1462    #[test]
1463    fn default_recovery_policy_strict_mailer_required_is_false() {
1464        // Locked-decision: project opts in via with_strict_mailer_required(true).
1465        // R1 commit #5 ships the field; enforcement is deferred to commit #7+.
1466        let p = DefaultRecoveryPolicy::new();
1467        assert!(!p.strict_mailer_required());
1468    }
1469
1470    #[test]
1471    fn default_recovery_policy_with_overrides_apply_field_by_field() {
1472        let p = DefaultRecoveryPolicy::new()
1473            .with_reset_token_ttl(ChronoDuration::hours(2))
1474            .with_request_rate_limit(3, StdDuration::from_secs(60))
1475            .with_consume_rate_limit(20, StdDuration::from_secs(30))
1476            .with_strict_mailer_required(true);
1477        assert_eq!(p.reset_token_ttl(), ChronoDuration::hours(2));
1478        assert_eq!(p.request_rate_limit(), (3, StdDuration::from_secs(60)));
1479        assert_eq!(p.consume_rate_limit(), (20, StdDuration::from_secs(30)));
1480        assert!(p.strict_mailer_required());
1481    }
1482
1483    #[test]
1484    fn shared_recovery_policy_is_send_sync() {
1485        fn assert_send_sync<T: Send + Sync>() {}
1486        assert_send_sync::<SharedRecoveryPolicy>();
1487    }
1488
1489    // ---- R2 trait extensions -----------------------------------------------
1490
1491    #[test]
1492    fn login_throttle_default_is_five_ten_fifteen() {
1493        // Locked-decision per DESIGN_R2_ORGANISATIONAL.md §12.
1494        let t = LoginThrottle::default();
1495        assert_eq!(t.max_attempts, 5);
1496        assert_eq!(t.window_minutes, 10);
1497        assert_eq!(t.lock_minutes, 15);
1498        // The const surface and the Default impl agree.
1499        assert_eq!(t, LoginThrottle::DEFAULT);
1500    }
1501
1502    #[test]
1503    fn default_recovery_policy_login_throttle_is_default() {
1504        let p = DefaultRecoveryPolicy::new();
1505        assert_eq!(p.login_throttle(), LoginThrottle::DEFAULT);
1506    }
1507
1508    #[test]
1509    fn default_recovery_policy_reauth_window_is_fifteen_minutes() {
1510        // Locked-decision per DESIGN_R2_ORGANISATIONAL.md §12.
1511        let p = DefaultRecoveryPolicy::new();
1512        assert_eq!(p.reauth_window(), ChronoDuration::minutes(15));
1513    }
1514
1515    // ---- R3 trait extensions -----------------------------------------------
1516
1517    #[test]
1518    fn default_recovery_policy_mfa_step_seconds_is_thirty() {
1519        // Locked per DESIGN_R3_MFA.md Appendix B — RFC 6238
1520        // industry standard for authenticator-app interop.
1521        let p = DefaultRecoveryPolicy::new();
1522        assert_eq!(p.mfa_step_seconds(), 30);
1523    }
1524
1525    #[test]
1526    fn default_recovery_policy_mfa_skew_steps_is_one() {
1527        // Locked per DESIGN_R3_MFA.md Appendix B — 90-second
1528        // total acceptance window at the canonical 30-second
1529        // step. Wider skew = network-replay regression.
1530        let p = DefaultRecoveryPolicy::new();
1531        assert_eq!(p.mfa_skew_steps(), 1);
1532    }
1533
1534    #[test]
1535    fn default_recovery_policy_scope_for_returns_none() {
1536        // Default impl signals "no per-tenant scoping". Multi-tenant
1537        // projects override to return Some(scoped_arc); the framework
1538        // call site (`admin.recovery_policy.scope_for(&identity)
1539        // .unwrap_or_else(|| Arc::clone(&admin.recovery_policy))`)
1540        // collapses None back to the original Arc.
1541        use crate::auth::Role;
1542        let identity = Identity {
1543            user_id: 42,
1544            email: "test@example.com".into(),
1545            role: Role::User,
1546            is_active: true,
1547            is_demo: false,
1548            demo_label: None,
1549            must_change_password: false,
1550            mfa_enabled: false,
1551            trust_level: crate::auth::SessionTrust::Authenticated,
1552        };
1553        let p = DefaultRecoveryPolicy::new();
1554        assert!(p.scope_for(&identity).is_none());
1555    }
1556
1557    #[test]
1558    fn login_throttle_is_send_sync_copy() {
1559        fn assert_send_sync_copy<T: Send + Sync + Copy>() {}
1560        assert_send_sync_copy::<LoginThrottle>();
1561    }
1562
1563    // ---- public_site_url derivation ----------------------------------------
1564
1565    fn header_lookup(
1566        pairs: &'static [(&'static str, &'static str)],
1567    ) -> impl Fn(&str) -> Option<String> + 'static {
1568        move |name| {
1569            pairs
1570                .iter()
1571                .find(|(k, _)| k.eq_ignore_ascii_case(name))
1572                .map(|(_, v)| (*v).to_string())
1573        }
1574    }
1575
1576    #[test]
1577    fn site_url_prefers_rfc7239_forwarded_first_hop() {
1578        let h = header_lookup(&[
1579            (
1580                "forwarded",
1581                "for=1.2.3.4;proto=https;host=admin.example.com",
1582            ),
1583            ("x-forwarded-proto", "http"),
1584            ("x-forwarded-host", "wrong.example.com"),
1585            ("host", "internal.local"),
1586        ]);
1587        assert_eq!(
1588            derive_public_site_url(&h),
1589            Some("https://admin.example.com".to_string())
1590        );
1591    }
1592
1593    #[test]
1594    fn site_url_falls_through_to_x_forwarded_pair() {
1595        let h = header_lookup(&[
1596            ("x-forwarded-proto", "https"),
1597            ("x-forwarded-host", "admin.example.com"),
1598            ("host", "internal.local"),
1599        ]);
1600        assert_eq!(
1601            derive_public_site_url(&h),
1602            Some("https://admin.example.com".to_string())
1603        );
1604    }
1605
1606    #[test]
1607    fn site_url_x_forwarded_takes_first_csv_entry() {
1608        // Multiple proxy hops — outermost (closest to client) is first.
1609        let h = header_lookup(&[
1610            ("x-forwarded-proto", "https, http"),
1611            ("x-forwarded-host", "admin.example.com, internal.local"),
1612        ]);
1613        assert_eq!(
1614            derive_public_site_url(&h),
1615            Some("https://admin.example.com".to_string())
1616        );
1617    }
1618
1619    #[test]
1620    fn site_url_falls_back_to_host_header_with_http() {
1621        let h = header_lookup(&[("host", "admin.example.com")]);
1622        assert_eq!(
1623            derive_public_site_url(&h),
1624            Some("http://admin.example.com".to_string())
1625        );
1626    }
1627
1628    #[test]
1629    fn site_url_returns_none_when_no_headers_resolve() {
1630        let h = header_lookup(&[]);
1631        assert_eq!(derive_public_site_url(&h), None);
1632    }
1633
1634    #[test]
1635    fn site_url_rejects_non_http_proto() {
1636        // A malicious client setting `Forwarded: proto=javascript`
1637        // must NOT poison the reset link. We refuse anything outside
1638        // {http, https} and fall through to the next source.
1639        let h = header_lookup(&[
1640            (
1641                "forwarded",
1642                "for=1.2.3.4;proto=javascript;host=evil.example.com",
1643            ),
1644            ("host", "fallback.example.com"),
1645        ]);
1646        assert_eq!(
1647            derive_public_site_url(&h),
1648            Some("http://fallback.example.com".to_string())
1649        );
1650    }
1651
1652    #[test]
1653    fn site_url_rejects_host_with_whitespace_or_control() {
1654        let h = header_lookup(&[("host", "example.com\r\nX-Injected: yes")]);
1655        assert_eq!(derive_public_site_url(&h), None);
1656    }
1657
1658    #[test]
1659    fn site_url_handles_quoted_forwarded_values() {
1660        let h = header_lookup(&[(
1661            "forwarded",
1662            "for=\"_obfuscated\";proto=\"https\";host=\"admin.example.com\"",
1663        )]);
1664        assert_eq!(
1665            derive_public_site_url(&h),
1666            Some("https://admin.example.com".to_string())
1667        );
1668    }
1669
1670    #[test]
1671    fn site_url_handles_ipv6_bracketed_host() {
1672        let h = header_lookup(&[
1673            ("x-forwarded-proto", "https"),
1674            ("x-forwarded-host", "[2001:db8::1]:8443"),
1675        ]);
1676        assert_eq!(
1677            derive_public_site_url(&h),
1678            Some("https://[2001:db8::1]:8443".to_string())
1679        );
1680    }
1681
1682    // ---- humanize_ttl ----
1683
1684    #[test]
1685    fn humanize_ttl_one_hour_default() {
1686        assert_eq!(humanize_ttl(ChronoDuration::hours(1)), "in 1 hour");
1687    }
1688
1689    #[test]
1690    fn humanize_ttl_two_hours_pluralises() {
1691        assert_eq!(humanize_ttl(ChronoDuration::hours(2)), "in 2 hours");
1692    }
1693
1694    #[test]
1695    fn humanize_ttl_minutes() {
1696        assert_eq!(humanize_ttl(ChronoDuration::minutes(30)), "in 30 minutes");
1697        assert_eq!(humanize_ttl(ChronoDuration::minutes(1)), "in 1 minute");
1698    }
1699
1700    #[test]
1701    fn humanize_ttl_seconds_for_short_windows() {
1702        assert_eq!(humanize_ttl(ChronoDuration::seconds(45)), "in 45 seconds");
1703        assert_eq!(humanize_ttl(ChronoDuration::seconds(1)), "in 1 second");
1704    }
1705
1706    // ---- purge_expired_reset_tokens ----------------------------------------
1707
1708    /// Locked retention doctrine — DESIGN_RECOVERY.md §4.4.
1709    /// Changing this constant is a behaviour change requiring a
1710    /// CHANGELOG entry under `Behaviour change`.
1711    #[test]
1712    fn reset_token_retention_window_is_seven_days() {
1713        assert_eq!(RESET_TOKEN_RETENTION_DAYS, 7);
1714    }
1715
1716    /// The DELETE statement targets the recovery table only,
1717    /// embeds the retention window as a literal `INTERVAL` (since
1718    /// sqlx can't bind interval params cleanly), and applies the
1719    /// same predicate to consumed AND unconsumed rows — no
1720    /// `consumed_at` filter on the WHERE clause. Pins the SQL
1721    /// shape so a future drift surfaces here.
1722    #[test]
1723    fn purge_query_includes_retention_window_and_table() {
1724        let query = format!(
1725            "DELETE FROM rustio_password_reset_tokens \
1726              WHERE expires_at < NOW() - INTERVAL '{RESET_TOKEN_RETENTION_DAYS} days'"
1727        );
1728        assert!(
1729            query.contains("rustio_password_reset_tokens"),
1730            "purge must target the recovery table"
1731        );
1732        assert!(
1733            query.contains("INTERVAL '7 days'"),
1734            "purge must use the locked 7-day retention window"
1735        );
1736        assert!(
1737            !query.contains("consumed_at"),
1738            "purge must apply to BOTH consumed and unconsumed expired rows; \
1739             a `consumed_at` filter would leak old consumed rows indefinitely"
1740        );
1741        // Defense-in-depth — the query is a DELETE, not a SELECT
1742        // / UPDATE. A copy-paste accident that turned this into an
1743        // UPDATE would silently leave rows in place; an accidental
1744        // SELECT would do nothing.
1745        assert!(
1746            query.starts_with("DELETE FROM"),
1747            "purge must be a DELETE statement"
1748        );
1749    }
1750
1751    #[test]
1752    fn humanize_ttl_zero_or_negative_returns_safe_string() {
1753        // Boundary: a TTL that's already in the past renders as a
1754        // grammatically safe placeholder. Never empty, never broken.
1755        assert_eq!(humanize_ttl(ChronoDuration::zero()), "very soon");
1756        assert_eq!(humanize_ttl(ChronoDuration::seconds(-30)), "very soon");
1757    }
1758
1759    // ---- IssueOutcome / ConsumeOutcome leak prevention ----
1760
1761    #[test]
1762    fn issue_outcome_debug_never_carries_plaintext_token() {
1763        // Variants are designed without a token field; this test
1764        // pins that property — a future change that adds one would
1765        // fail this. Synthetic plaintext is unlikely to collide
1766        // with the structural form-fields ("Issued", "token_id",
1767        // numbers, etc.).
1768        let synthetic = "Pwn4Ge_ZZ_token_plaintext_1234567890";
1769        for outcome in [
1770            IssueOutcome::Issued {
1771                token_id: 42,
1772                email_status: MailerEmailStatus::Sent,
1773            },
1774            IssueOutcome::Issued {
1775                token_id: 7,
1776                email_status: MailerEmailStatus::Failed,
1777            },
1778            IssueOutcome::UnknownOrInactive,
1779            IssueOutcome::RateLimited,
1780        ] {
1781            let debug = format!("{outcome:?}");
1782            assert!(
1783                !debug.contains(synthetic),
1784                "IssueOutcome Debug leaked plaintext: {debug}",
1785            );
1786        }
1787    }
1788
1789    #[test]
1790    fn consume_outcome_debug_never_carries_plaintext_token() {
1791        let synthetic = "Pwn4Ge_ZZ_token_plaintext_1234567890";
1792        for outcome in [
1793            ConsumeOutcome::Consumed {
1794                user_id: 1,
1795                revoked_session_count: 3,
1796            },
1797            ConsumeOutcome::Invalid,
1798            ConsumeOutcome::PolicyRejected(PasswordPolicyError::TooShort { min: 10, actual: 4 }),
1799            ConsumeOutcome::PolicyRejected(PasswordPolicyError::Custom("stub rejected".into())),
1800            ConsumeOutcome::RateLimited,
1801        ] {
1802            let debug = format!("{outcome:?}");
1803            assert!(
1804                !debug.contains(synthetic),
1805                "ConsumeOutcome Debug leaked plaintext: {debug}",
1806            );
1807        }
1808    }
1809
1810    #[test]
1811    fn mailer_email_status_round_trip_strings() {
1812        // Locked-in for the audit metadata field
1813        // `email_send_status` — values are 'sent' / 'failed'.
1814        assert_eq!(format!("{:?}", MailerEmailStatus::Sent), "Sent");
1815        assert_eq!(format!("{:?}", MailerEmailStatus::Failed), "Failed");
1816    }
1817
1818    #[test]
1819    fn malformed_forwarded_inputs_never_panic() {
1820        for input in &[
1821            "",
1822            "garbage",
1823            "for=",
1824            "proto=;host=",
1825            "proto=javascript:alert(1);host=evil",
1826            "host=example com",
1827            "proto=https;host=",
1828            ";;;",
1829            ",,,",
1830            "proto=https",
1831            "host=example.com",
1832            "for=\"unterminated",
1833            "=value",
1834            "key=",
1835            "key==value=",
1836        ] {
1837            let value = (*input).to_string();
1838            // The lookup returns the test input for "forwarded" and
1839            // a safe host fallback so we exercise the "fall through"
1840            // path too.
1841            let h = move |name: &str| match name {
1842                "forwarded" => Some(value.clone()),
1843                "host" => Some("fallback.example.com".to_string()),
1844                _ => None,
1845            };
1846            // Property: never panics. The result is acceptable as
1847            // long as the fall-through landed somewhere safe.
1848            let result = derive_public_site_url(h);
1849            assert!(
1850                result.is_none()
1851                    || result.as_deref() == Some("http://fallback.example.com")
1852                    || result.as_deref().map(|s| s.starts_with("https://")) == Some(true)
1853                    || result.as_deref().map(|s| s.starts_with("http://")) == Some(true),
1854                "input {input:?} produced unexpected url {result:?}"
1855            );
1856        }
1857    }
1858}