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