Skip to main content

umbral_auth/
lib.rs

1//! umbral-auth — the built-in authentication plugin.
2//!
3//! The first crate under `plugins/` and the proof of the M7 plugin
4//! contract: a real built-in expressed through `umbral::prelude::Plugin`
5//! with no special-casing inside `umbral-core`. Auth is the most common
6//! plugin, so getting it right here also pressure-tests the
7//! contract for the rest.
8//!
9//! ## M9 v1 scope
10//!
11//! - [`AuthUser`] model: the canonical User model (username,
12//!   email, password hash, `is_active` / `is_staff` / `is_superuser`,
13//!   `date_joined`, `last_login`).
14//! - [`UserModel`] trait: the minimum surface a custom user model must
15//!   satisfy so `AuthPlugin<U>` can swap in any user type. Default impls
16//!   cover the optional flag methods so a minimal custom user struct
17//!   only has to implement the load-bearing four.
18//! - argon2 password hashing via [`hash_password`] / [`verify_password`].
19//! - [`create_user`], [`authenticate`], [`set_password`] helpers.
20//!   `authenticate` and `set_password` are generic over any `U: UserModel`.
21//! - [`AuthPlugin`] registers the user model (which becomes a migration)
22//!   plus the `/auth` routes and management commands. The type parameter
23//!   defaults to [`AuthUser`] so existing apps need no changes.
24//! - [`login_required`] module: `LoginRequired` config, `LoggedIn<U>`
25//!   extractor, `LoginRequiredLayer` middleware, and the
26//!   `login_required()` / `login_required_html()` convenience
27//!   constructors. A login-required gate in two shapes.
28//!
29//! ## Custom user models
30//!
31//! ```ignore
32//! // 1. Declare a custom user struct.
33//! #[derive(Debug, Clone, sqlx::FromRow, Serialize, Deserialize, umbral::orm::Model)]
34//! pub struct TenantUser {
35//!     pub id: i64,
36//!     pub username: String,
37//!     pub password_hash: String,
38//!     pub tenant_id: i64,
39//!     pub is_active: bool,
40//! }
41//!
42//! // 2. Implement UserModel (only the four required methods).
43//! impl umbral_auth::UserModel for TenantUser {
44//!     fn id(&self) -> i64               { self.id }
45//!     fn username(&self) -> &str        { &self.username }
46//!     fn password_hash(&self) -> &str   { &self.password_hash }
47//!     fn set_password_hash(&mut self, h: String) { self.password_hash = h; }
48//! }
49//!
50//! // 3. Wire the plugin with your type.
51//! App::builder()
52//!     .plugin(AuthPlugin::<TenantUser>::default())
53//!     .build()?
54//! ```
55//!
56//! ## Deferred (per `docs/specs/outlines/auth-and-sessions.md`)
57//!
58//! - Permissions, groups, the auth-backend chain.
59//! - The `Auth<U>` request extractor + `#[login_required]`
60//!   middleware. Needs `Plugin::middleware()` lifted (M7 deferral).
61//! - Login / logout / password-reset HTTP flows. Needs the full
62//!   `umbral-sessions` session middleware wired end-to-end.
63//! - Periodic session cleanup via `umbral-tasks`.
64
65pub mod auth_routes;
66pub mod bearer_auth;
67pub mod challenge;
68pub mod extractors;
69pub mod form_routes;
70pub mod login_required;
71pub mod mailer;
72pub mod password_validation;
73pub mod session_user;
74pub mod throttle;
75pub mod token;
76
77pub use mailer::{AuthMailError, AuthMailer, ConsoleMailer, MailKind, OutgoingMail};
78pub use password_validation::{
79    CommonPasswordValidator, MinLengthValidator, NumericPasswordValidator, PasswordContext,
80    PasswordPolicy, PasswordValidator, UserAttributeSimilarityValidator, validate_password,
81};
82
83pub use bearer_auth::{BearerAuthentication, parse_bearer_header};
84pub use challenge::{
85    AuthChallenge, change_password, reset_password, start_email_verification, start_password_reset,
86    verify_email,
87};
88pub use extractors::{
89    CurrentIdentity, OptionalIdentity, RequireAuth, RequireStaff, resolve_identity,
90};
91pub use login_required::{
92    LoggedIn, LoginRequired, LoginRequiredLayer, current_session_user_id, current_session_user_pk,
93    login_required, login_required_html, resolve_user as current_user_as,
94};
95pub use session_user::{
96    OptionalUser, SessionAuthentication, User, current_user, db_session_var_layer, login,
97    login_with_request, user_context_layer,
98};
99pub use throttle::{
100    Throttle, ThrottleConfig, email_action_throttle_check, login_throttle_check,
101    login_throttle_clear, register_throttle_check,
102};
103pub use token::{AuthToken, PlaintextToken, TOKEN_PREFIX, digest_token};
104
105/// Test shim: thin wrapper over `auth_routes::openapi_paths` so test binaries
106/// (which can't reach into `pub(crate)`) can assert the full path list.
107#[doc(hidden)]
108pub fn auth_routes_openapi_for_test(prefix: &str) -> Vec<(String, serde_json::Value)> {
109    auth_routes::openapi_paths(prefix)
110}
111
112use std::marker::PhantomData;
113
114use argon2::password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString};
115use argon2::{Algorithm, Argon2, Params, Version, password_hash::rand_core::OsRng};
116use chrono::{DateTime, Utc};
117use serde::{Deserialize, Serialize};
118use umbral::prelude::*;
119
120// =========================================================================
121// UserModel trait
122// =========================================================================
123
124/// The minimum surface a user model must expose so `AuthPlugin<U>` can
125/// operate on it generically.
126///
127/// All four required methods map directly to columns that auth ACTUALLY
128/// reads or writes. Optional flag methods (`is_active`, `is_staff`,
129/// `is_superuser`) have default impls that return the safe defaults so a
130/// minimal custom user struct doesn't have to repeat them.
131///
132/// `AuthUser` implements this trait unchanged, so existing code that
133/// calls the auth helpers directly keeps working.
134///
135/// ## Required methods
136///
137/// | Method | Column | Used by |
138/// |---|---|---|
139/// | `id()` | `id` | `set_password` WHERE clause; session storage |
140/// | `username()` | `username` | `authenticate` SELECT, `createsuperuser` output |
141/// | `password_hash()` | `password_hash` | `authenticate` verify step |
142/// | `set_password_hash()` | `password_hash` | `set_password` in-place update |
143///
144/// ## Default methods
145///
146/// | Method | Default | Used by |
147/// |---|---|---|
148/// | `id_string()` | `self.id().to_string()` | `Identity::user_id`, session row |
149/// | `is_active()` | `true` | `authenticate` active-user gate |
150/// | `is_staff()` | `false` | admin require_staff check |
151/// | `is_superuser()` | `false` | permission gates |
152///
153/// ## Polymorphic primary key
154///
155/// `id()` returns the model's typed primary key via the existing
156/// `Model::PrimaryKey` associated type — the framework no longer
157/// hardcodes `i64`. A custom user model keyed by `uuid::Uuid`
158/// works as-is:
159///
160/// ```ignore
161/// #[derive(Debug, Clone, sqlx::FromRow, Serialize, Deserialize,
162///          umbral::orm::Model)]
163/// pub struct UuidUser {
164///     pub id: uuid::Uuid,
165///     pub username: String,
166///     pub password_hash: String,
167///     pub is_active: bool,
168///     pub is_staff: bool,
169/// }
170/// impl umbral_auth::UserModel for UuidUser {
171///     fn id(&self) -> uuid::Uuid { self.id }
172///     fn username(&self) -> &str { &self.username }
173///     fn password_hash(&self) -> &str { &self.password_hash }
174///     fn set_password_hash(&mut self, h: String) { self.password_hash = h; }
175///     fn is_active(&self) -> bool { self.is_active }
176///     fn is_staff(&self) -> bool { self.is_staff }
177/// }
178/// ```
179///
180/// The session-row text column, [`Identity::user_id`], and the
181/// permissions plugin all speak strings (via `id_string()`); the
182/// ORM-side WHERE clauses use the typed PK directly (via the
183/// `PrimaryKey: Into<sea_query::Value>` bound). Nothing in the
184/// framework parses `id()` back to `i64`.
185pub trait UserModel: Model + Send + Sync + 'static {
186    /// The row's typed primary key. `set_password` uses this in the
187    /// UPDATE WHERE clause; bearer-token / session backends use it
188    /// to filter on `auth_user::ID.eq(user.id())` style predicates.
189    ///
190    /// The return type is `<Self as Model>::PrimaryKey`, which the
191    /// `#[derive(Model)]` macro derives from the `id` field's type
192    /// (`i64`, `uuid::Uuid`, `String`, etc.). All `PrimaryKey`
193    /// types implement `Display`, so [`id_string`](Self::id_string)
194    /// can stringify without an explicit per-impl override.
195    fn id(&self) -> <Self as Model>::PrimaryKey;
196
197    /// The PK as a string. Used by [`umbral_sessions`] (which stores
198    /// `user_id` as text) and by the REST identity contract's
199    /// [`Identity::user_id`](umbral::auth::Identity) (which is
200    /// uniform across user models).
201    ///
202    /// Default uses the typed PK's `Display` impl — override only
203    /// when the stringification needs to differ from `Display`
204    /// (e.g. a base64-encoded ULID).
205    fn id_string(&self) -> String {
206        self.id().to_string()
207    }
208
209    /// The unique login handle. Matched against the username column in
210    /// `authenticate`'s SELECT query.
211    fn username(&self) -> &str;
212
213    /// The columns a login identifier is matched against in [`authenticate`],
214    /// OR-combined — so a user can sign in with any of them. Default is
215    /// `["username"]` (username-only, the historical behavior). A model with an
216    /// `email` column overrides this to `["username", "email"]` so either
217    /// works. Every listed column must exist on the table and hold a value the
218    /// identifier is normalized to match (see [`normalize_username`]); the
219    /// built-in `AuthUser` stores both `username` and `email` trimmed +
220    /// lowercased, so a case-insensitive login lands on the right row.
221    fn login_columns() -> &'static [&'static str] {
222        &["username"]
223    }
224
225    /// The argon2 PHC-encoded password hash stored in the DB column.
226    /// `authenticate` reads this, verifies it, and moves on.
227    fn password_hash(&self) -> &str;
228
229    /// Replace the in-memory password hash. Called by `set_password`
230    /// after writing the new hash to the database, so the caller's
231    /// `&mut U` reflects the update without a re-fetch.
232    fn set_password_hash(&mut self, hash: String);
233
234    /// Whether this account is active. `authenticate` rejects inactive
235    /// users with `InvalidCredentials` (same error as wrong password -
236    /// no account enumeration). Default: `true`.
237    fn is_active(&self) -> bool {
238        true
239    }
240
241    /// Whether this account has staff-level access to the admin
242    /// interface. Default: `false`.
243    fn is_staff(&self) -> bool {
244        false
245    }
246
247    /// Whether this account has superuser rights. Default: `false`.
248    fn is_superuser(&self) -> bool {
249        false
250    }
251}
252
253// =========================================================================
254// Built-in AuthUser model
255// =========================================================================
256
257/// The canonical authentication user. `#[derive(Model)]` snake_cases
258/// the struct name into the table name `auth_user`; the M3 derive
259/// doesn't yet accept `#[umbral(table = ...)]` so the snake_case
260/// round-trip is the only way to get a plugin-prefixed table name
261/// until the attribute lands.
262#[derive(Debug, Clone, sqlx::FromRow, Serialize, Deserialize, umbral::orm::Model)]
263pub struct AuthUser {
264    pub id: i64,
265    /// `trim` + `lowercase` (gaps3 #34) canonicalize the username on the
266    /// dynamic write path (admin form-submit, REST create/update) so it's
267    /// case-insensitively unique there too — the typed `create_user` path
268    /// normalizes explicitly via `normalize_username` (gaps3 #33). Together
269    /// they close every write surface.
270    #[umbral(unique, trim, lowercase)]
271    pub username: String,
272    /// Shown read-only on edit forms; never on create forms (use the
273    /// admin's password field mechanism for changes). `trim` + `lowercase`
274    /// canonicalize on the dynamic write path — see `username`.
275    #[umbral(noedit, unique, trim, lowercase)]
276    pub email: String,
277    /// Never shown on any form — password management goes through the
278    /// dedicated Change Password flow in the admin. `signal_skip` keeps the
279    /// hash out of every ORM signal payload (audit_2 core-app-config #10), so
280    /// an audit-log subscriber can't copy password hashes into its logs.
281    #[umbral(noform, signal_skip)]
282    pub password_hash: String,
283    pub is_active: bool,
284    /// Staff flag — grants admin-site access. Privileged: the untrusted JSON
285    /// write path (REST create/update, admin form-submit) refuses to set it
286    /// unless the caller authorizes it via `DynQuerySet::allow_privileged`
287    /// (audit_2 H3). Prevents a self-service `POST /users {is_staff: true}`
288    /// privilege escalation. An admin acting as a superuser still toggles it.
289    /// `default = "false"` so a create that had the field stripped fills the
290    /// safe value at the DB rather than tripping NOT NULL.
291    #[umbral(privileged, default = "false")]
292    pub is_staff: bool,
293    /// Superuser flag — full authority. Privileged for the same reason as
294    /// `is_staff`; this is the field a mass-assignment attack most wants.
295    #[umbral(privileged, default = "false")]
296    pub is_superuser: bool,
297    pub date_joined: DateTime<Utc>,
298    pub last_login: Option<DateTime<Utc>>,
299    /// When this user's email was verified, NULL until they complete the
300    /// verification flow. Tracked always; only enforced when the plugin is
301    /// built with `require_verified_email()`.
302    pub email_verified_at: Option<DateTime<Utc>>,
303}
304
305impl UserModel for AuthUser {
306    // `<AuthUser as Model>::PrimaryKey` is `i64` — the derive picks
307    // it up from the `id: i64` field. Returning `self.id` directly
308    // satisfies `fn id(&self) -> <Self as Model>::PrimaryKey` for
309    // the default AuthUser shape; a custom user model with a
310    // `uuid::Uuid` PK would return `self.id` of that type, and the
311    // default `id_string()` would stringify via `Display` for free.
312    fn id(&self) -> <Self as umbral::orm::Model>::PrimaryKey {
313        self.id
314    }
315
316    fn username(&self) -> &str {
317        &self.username
318    }
319
320    /// `AuthUser` accepts either the username or the email as the login
321    /// identifier — both columns are UNIQUE and stored trimmed + lowercased,
322    /// so a case-insensitive match lands on exactly one row.
323    fn login_columns() -> &'static [&'static str] {
324        &["username", "email"]
325    }
326
327    fn password_hash(&self) -> &str {
328        &self.password_hash
329    }
330
331    fn set_password_hash(&mut self, hash: String) {
332        self.password_hash = hash;
333    }
334
335    fn is_active(&self) -> bool {
336        self.is_active
337    }
338
339    fn is_staff(&self) -> bool {
340        self.is_staff
341    }
342
343    fn is_superuser(&self) -> bool {
344        self.is_superuser
345    }
346}
347
348// =========================================================================
349// AuthPlugin<U>
350// =========================================================================
351
352/// A `Mutex`-wrapped optional mailer slot that implements `Debug` manually so
353/// `#[derive(Debug)]` on `AuthPlugin` keeps working even though
354/// `Arc<dyn AuthMailer>` is not `Debug`.
355struct MailerSlot(std::sync::Mutex<Option<std::sync::Arc<dyn mailer::AuthMailer>>>);
356impl std::fmt::Debug for MailerSlot {
357    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
358        f.write_str("MailerSlot(..)")
359    }
360}
361
362/// The built-in authentication plugin, generic over the user model.
363///
364/// `U` defaults to [`AuthUser`] so `AuthPlugin::default()` continues to
365/// work in all existing code unchanged. Apps that need a custom user type
366/// opt in with one line:
367///
368/// ```ignore
369/// .plugin(AuthPlugin::<CustomUser>::default())
370/// ```
371///
372/// ## `user_model_name`
373///
374/// An optional informational string surfaced in OpenAPI schemas and the
375/// admin nav. Default `None` (resolved from `U::NAME` by the plugin
376/// itself when left empty). Set it explicitly when the type name is
377/// insufficient:
378///
379/// ```ignore
380/// AuthPlugin::<TenantUser>::default().user_model_name("tenant_user")
381/// ```
382#[derive(Debug)]
383pub struct AuthPlugin<U: UserModel = AuthUser> {
384    /// Documentation-only: the human-readable name of the active user
385    /// model. Consumed by admin / OpenAPI when surfacing the user table.
386    /// The actual dispatch is entirely through the type parameter `U`.
387    pub user_model_name: Option<String>,
388    /// When `Some`, mount the four built-in routes (register / login /
389    /// logout / me) under this prefix. `None` skips them — the user
390    /// either doesn't want them or is rolling their own surface. Only
391    /// settable on `AuthPlugin<AuthUser>` (the handlers FK into
392    /// `AuthToken` → `AuthUser`); custom user models bring their own.
393    pub default_routes_prefix: Option<String>,
394    /// When `Some`, mount the 7 POST form-action routes (login, logout,
395    /// signup, verify-email, resend, password-forgot, password-reset)
396    /// under this prefix. Default `None` — opt in via
397    /// [`AuthPlugin::with_form_routes`] / [`AuthPlugin::with_form_routes_at`].
398    /// Only settable on `AuthPlugin<AuthUser>`.
399    pub form_routes_prefix: Option<String>,
400    /// When true, wrap the app router with [`user_context_layer`] so
401    /// every template render has `user` in its global context:
402    /// `{ is_authenticated, is_staff, username, ... }`. Opt-in because
403    /// it costs one DB read per request (cookie → session → user); a
404    /// REST-only service has nothing to gain from it. Set via
405    /// [`AuthPlugin::with_user_in_templates`].
406    pub user_in_templates: bool,
407    /// When `Some(name)`, publish the authenticated user's id to the database
408    /// connection as the Postgres session variable `name` on every request, so
409    /// a row-level-security policy can read it via `current_setting(name)`.
410    /// `None` (the default) mounts no layer at all. Set via
411    /// [`AuthPlugin::with_db_session_var`]. gaps3 #45.
412    pub db_session_var: Option<String>,
413    /// The password-strength policy this plugin installs at boot. `None`
414    /// here is NOT "no validation" — `on_ready` installs
415    /// [`PasswordPolicy::default`] (the full secure set) when this is left
416    /// unset, so the plugin is secure by default. The only way to get an
417    /// empty policy is to call [`AuthPlugin::disable_password_validation`],
418    /// which stores an explicit [`PasswordPolicy::empty`].
419    ///
420    /// Wrapped in a `Mutex` because `Plugin::on_ready` only borrows `&self`
421    /// yet needs to MOVE the policy into the ambient `OnceLock`
422    /// ([`PasswordPolicy`] is not `Clone` — it holds boxed trait objects).
423    /// The mutex lets `on_ready` `.take()` it; the first boot wins.
424    password_policy: std::sync::Mutex<Option<PasswordPolicy>>,
425    /// The login/register rate-limit configuration this plugin installs at
426    /// boot. Secure by default ([`ThrottleConfig::default`]: login 5 / 5 min
427    /// per IP+username, register 10 / hour per IP, `enabled = true`). Builder
428    /// methods ([`AuthPlugin::login_throttle`], [`AuthPlugin::register_throttle`])
429    /// tune the budgets; [`AuthPlugin::disable_throttle`] flips `enabled` off
430    /// as an explicit opt-out. `Copy`, so no `Mutex`/`take` dance is needed —
431    /// `on_ready` reads it directly.
432    throttle_config: throttle::ThrottleConfig,
433    /// The mailer sealed into the ambient `OnceLock` on `on_ready`. Wrapped
434    /// in a `Mutex` (via `MailerSlot`) so `on_ready`'s `&self` can `.take()`
435    /// the value. First boot wins; subsequent calls are no-ops.
436    mailer: MailerSlot,
437    /// When `true`, the `register` route auto-sends a verification code and the
438    /// `login` route returns 403 until `email_verified_at` is stamped. Off by
439    /// default — the column is tracked and the endpoints exist regardless; only
440    /// the enforcement gate is toggled here. Set via
441    /// [`AuthPlugin::require_verified_email`] (available on
442    /// `AuthPlugin<AuthUser>` only, since it gates the built-in routes).
443    require_verified: bool,
444    /// Optional override for the argon2 concurrency cap (audit_2 plugin-auth
445    /// #4). `None` uses the framework default — machine parallelism (min 2),
446    /// or the `UMBRAL_AUTH_HASH_CONCURRENCY` env var. Sealed at `on_ready`.
447    hash_concurrency: Option<usize>,
448    _u: PhantomData<U>,
449}
450
451impl<U: UserModel> Default for AuthPlugin<U> {
452    fn default() -> Self {
453        Self {
454            user_model_name: None,
455            default_routes_prefix: None,
456            form_routes_prefix: None,
457            user_in_templates: false,
458            db_session_var: None,
459            // SECURE BY DEFAULT: an unconfigured AuthPlugin enforces the
460            // full validator set. `None` defers to PasswordPolicy::default()
461            // (the secure set) at install time; it does NOT mean "off".
462            password_policy: std::sync::Mutex::new(None),
463            // SECURE BY DEFAULT: throttling is ON for login + register with
464            // the credential-stuffing-resistant budgets above. `disable_throttle`
465            // is the only path that turns it off.
466            throttle_config: throttle::ThrottleConfig::default(),
467            mailer: MailerSlot(std::sync::Mutex::new(None)),
468            require_verified: false,
469            hash_concurrency: None,
470            _u: PhantomData,
471        }
472    }
473}
474
475impl<U: UserModel> AuthPlugin<U> {
476    /// Override the informational user-model name shown in admin / OpenAPI.
477    /// Fluent builder method; the return type is `Self` so it chains.
478    pub fn user_model_name(mut self, name: impl Into<String>) -> Self {
479        self.user_model_name = Some(name.into());
480        self
481    }
482
483    /// Mount the [`user_context_layer`] middleware globally so every
484    /// HTML template gets `user` in its render context — anonymous
485    /// requests see `{ is_authenticated: false }`, authenticated
486    /// requests see the full serialized [`AuthUser`] merged with
487    /// `is_authenticated: true`. Lets templates write
488    /// `{% if user.is_staff %}` without the consumer having to thread
489    /// a user value into every handler's context manually.
490    ///
491    /// One DB read per request (cookie → session → user row). Off by
492    /// default because REST-only services have no templates and the
493    /// cost would be pure overhead. Turn it on for HTML-heavy apps:
494    ///
495    /// ```ignore
496    /// AuthPlugin::<AuthUser>::default()
497    ///     .with_default_routes()
498    ///     .with_user_in_templates()   // ← here
499    /// ```
500    ///
501    /// Implemented via [`Plugin::wrap_router`]; the wrapper wraps the
502    /// merged app router (including every other plugin's routes), so
503    /// admin / REST / playground / your own handlers all see the
504    /// populated context with one builder call.
505    pub fn with_user_in_templates(mut self) -> Self {
506        self.user_in_templates = true;
507        self
508    }
509
510    /// Publish the authenticated user's id to the database connection as a
511    /// Postgres session variable, so a row-level-security policy can read it.
512    ///
513    /// This is the wiring that makes `umbral-rls` usable. RLS is the only
514    /// permission layer in umbral that cannot be bypassed by application code —
515    /// the database itself refuses the row — and a policy expresses "who is
516    /// asking?" as `current_setting('app.user_id')`. Something has to set that.
517    ///
518    /// ```ignore
519    /// App::builder()
520    ///     .plugin(SessionsPlugin::default())
521    ///     .plugin(AuthPlugin::<AuthUser>::default().with_db_session_var("app.user_id"))
522    ///     .plugin(RlsPlugin::new().policy(
523    ///         "post", "own_rows", Action::All,
524    ///         "user_id = NULLIF(current_setting('app.user_id'), '')::bigint",
525    ///     ))
526    /// ```
527    ///
528    /// The variable is set on **every** request, to the empty string when the
529    /// caller is anonymous. That is deliberate: Postgres raises
530    /// `unrecognized configuration parameter` when `current_setting` names a GUC
531    /// that was never set on the connection, so skipping it for logged-out users
532    /// would turn each of their requests into a 500 instead of a clean "you see
533    /// no rows". Write policies against `NULLIF(current_setting(...), '')`.
534    ///
535    /// Identity comes from the session, never from a client-supplied header, and
536    /// a deactivated account resolves to anonymous (the lookup filters on
537    /// `is_active`).
538    ///
539    /// **Costs one session + one user read per request**, and unlike
540    /// [`Self::with_user_in_templates`] it cannot be lazy: the value has to be on
541    /// the connection before the handler's first query, not after something asks
542    /// for it. Off by default for that reason.
543    ///
544    /// **Do not enable RLS on `auth_user` or `session`.** This layer reads them
545    /// to discover who the caller is, before any variable has been set.
546    pub fn with_db_session_var(mut self, name: impl Into<String>) -> Self {
547        self.db_session_var = Some(name.into());
548        self
549    }
550
551    /// Replace the default password-strength policy with a custom one.
552    /// The full [`PasswordPolicy`] you pass becomes the active set at boot;
553    /// the default validators are NOT merged in. Build the policy
554    /// you want from scratch:
555    ///
556    /// ```ignore
557    /// use umbral_auth::{AuthPlugin, PasswordPolicy, MinLengthValidator, CommonPasswordValidator};
558    /// AuthPlugin::<AuthUser>::default().password_validators(
559    ///     PasswordPolicy::empty()
560    ///         .with(Box::new(MinLengthValidator(12)))
561    ///         .with(Box::new(CommonPasswordValidator)),
562    /// )
563    /// ```
564    pub fn password_validators(mut self, policy: PasswordPolicy) -> Self {
565        self.password_policy = std::sync::Mutex::new(Some(policy));
566        self
567    }
568
569    /// Convenience: keep the four default validators but change the minimum
570    /// password length. Equivalent to building a [`PasswordPolicy`] with a
571    /// [`MinLengthValidator`] of `n` plus the other three defaults.
572    pub fn min_password_length(self, n: usize) -> Self {
573        self.password_validators(PasswordPolicy::new(vec![
574            Box::new(MinLengthValidator(n)),
575            Box::new(CommonPasswordValidator),
576            Box::new(NumericPasswordValidator),
577            Box::new(UserAttributeSimilarityValidator::default()),
578        ]))
579    }
580
581    /// Explicit opt-OUT: install an empty policy so NO password validation
582    /// runs. Secure-by-default means an app that genuinely wants to accept
583    /// any password — a throwaway demo, a migration importing legacy hashes
584    /// with externally-validated plaintext — has to ask for it by name.
585    /// Don't reach for this to silence a failing test; fix the fixture's
586    /// password instead.
587    pub fn disable_password_validation(mut self) -> Self {
588        self.password_policy = std::sync::Mutex::new(Some(PasswordPolicy::empty()));
589        self
590    }
591
592    /// Tune the login rate limit: `max` failed-or-not attempts per trailing
593    /// `window`, keyed per IP + username. The default is 5 / 5 min — a budget
594    /// that stops credential-stuffing dead while leaving room for a human who
595    /// fat-fingers their password a couple of times (a successful login also
596    /// clears the counter). Lower it for a high-security surface; raise it for
597    /// a shared-NAT office where many users hit login from one IP.
598    ///
599    /// ```ignore
600    /// AuthPlugin::<AuthUser>::default().login_throttle(10, Duration::from_secs(300))
601    /// ```
602    pub fn login_throttle(mut self, max: usize, window: std::time::Duration) -> Self {
603        self.throttle_config.login_max = max;
604        self.throttle_config.login_window = window;
605        self
606    }
607
608    /// Tune the register rate limit: `max` account-creation attempts per
609    /// trailing `window`, keyed per IP. The default is 10 / hour, which brakes
610    /// mass automated signups without blocking a legitimate burst from one
611    /// office.
612    pub fn register_throttle(mut self, max: usize, window: std::time::Duration) -> Self {
613        self.throttle_config.register_max = max;
614        self.throttle_config.register_window = window;
615        self
616    }
617
618    /// Tune the email-action rate limit: `max` attempts per trailing `window`,
619    /// keyed per IP + email. Covers verify-email, resend-verification, and
620    /// password-forgot. The default is 5 / hour — enough for a user who needs
621    /// a couple of resends, but low enough to stop email-bombing / online
622    /// code-guessing scripts dead.
623    pub fn email_action_throttle(mut self, max: usize, window: std::time::Duration) -> Self {
624        self.throttle_config.email_action_max = max;
625        self.throttle_config.email_action_window = window;
626        self
627    }
628
629    /// Explicit opt-OUT: turn login, register, and email-action throttling OFF
630    /// entirely. Secure-by-default means an app that genuinely wants no rate
631    /// limit — a load test, an internal tool behind its own gateway limiter —
632    /// has to ask for it by name. Don't reach for this to silence a throttled
633    /// test; use a distinct IP/username per attempt or generous budget methods
634    /// instead.
635    pub fn disable_throttle(mut self) -> Self {
636        self.throttle_config.enabled = false;
637        self
638    }
639
640    /// Cap how many argon2 hash/verify operations may run concurrently
641    /// (audit_2 plugin-auth #4). Each argon2id op allocates ~19 MiB and pins a
642    /// CPU, so without a bound a login/register/reset flood can spawn hundreds
643    /// at once and OOM the process. The default is the machine's parallelism
644    /// (min 2) — more concurrent hashes than cores only thrashes and multiplies
645    /// peak memory. Requests past `cap × 8` in-flight (running + waiting) are
646    /// shed with HTTP 503 so clients back off. Override only if you have a
647    /// specific reason (e.g. reserving cores for request handling).
648    ///
649    /// `UMBRAL_AUTH_HASH_CONCURRENCY` overrides this at runtime; a `0` here is
650    /// ignored (the default applies).
651    pub fn hash_concurrency(mut self, cap: usize) -> Self {
652        self.hash_concurrency = Some(cap);
653        self
654    }
655
656    /// Wire the mailer used by the verification + password-reset flows.
657    /// Pass a type implementing [`AuthMailer`] or an async closure
658    /// `|mail| async { ... }`. Unset → [`ConsoleMailer`] (stderr in dev).
659    ///
660    /// ```ignore
661    /// AuthPlugin::<AuthUser>::default().mailer(|m: OutgoingMail| async move {
662    ///     umbral_email::send(&umbral_email::EmailMessage::new(m.subject, vec![m.to])
663    ///         .html_body(m.html).text_body(m.text)).await
664    ///         .map(|_| ()).map_err(|e| AuthMailError::Send(e.to_string()))
665    /// })
666    /// ```
667    pub fn mailer(self, m: impl mailer::AuthMailer + 'static) -> Self {
668        *self.mailer.0.lock().expect("mailer slot poisoned") = Some(std::sync::Arc::new(m));
669        self
670    }
671
672    /// Resolve the JSON route prefix.
673    ///
674    /// Returns `None` when `with_default_routes[_at]` was not called (no
675    /// routes mounted). When the stored value equals `JSON_PREFIX_SENTINEL`
676    /// (set by `with_default_routes()`), returns `{api_base()}/auth` —
677    /// resolved at call-time, after `App::build` has had a chance to set the
678    /// base. A literal prefix stored by `with_default_routes_at` is returned
679    /// as-is.
680    ///
681    /// Private: called from the `Plugin` trait impl (`routes`,
682    /// `route_paths`, `openapi_paths`). Not part of the public API.
683    fn json_prefix(&self) -> Option<String> {
684        self.default_routes_prefix.as_ref().map(|p| {
685            if p == JSON_PREFIX_SENTINEL {
686                format!("{}/auth", umbral::web::api_base())
687            } else {
688                p.clone()
689            }
690        })
691    }
692}
693
694// =========================================================================
695// Default route opt-in. Only exposed on AuthPlugin<AuthUser> because the
696// handlers FK into AuthUser via AuthToken. Custom user models would need a
697// different token model + different handlers; they bring their own surface.
698// The concrete impl block (no <U>) is the compile-time witness: calling
699// `.with_default_routes()` on `AuthPlugin::<CustomUser>` is an error at
700// the call site, not a silent no-op at runtime.
701// =========================================================================
702
703// =========================================================================
704// Ambient require_verified seal — mirrors the password policy / mailer pattern.
705// =========================================================================
706
707/// Process-global flag set once in `on_ready`. Handlers read it as a free
708/// function so they don't need a handle to `AuthPlugin<U>`.
709static REQUIRE_VERIFIED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
710
711/// Whether the `require_verified_email()` builder was called on the active
712/// `AuthPlugin`. `false` until `on_ready` seals it; `false` as the fallback
713/// if `on_ready` was somehow skipped (should never happen in a well-formed
714/// `App::build`, but safe-default matters here — off = permissive).
715pub(crate) fn verified_email_required() -> bool {
716    *REQUIRE_VERIFIED.get().unwrap_or(&false)
717}
718
719/// Stored by `with_default_routes()` so the JSON prefix can be resolved at
720/// build time (when `api_base()` is already set by `App::build`) rather than
721/// when the builder method is called (before `App::build` has set the base).
722/// An internal null-byte sentinel that no real path can equal.
723const JSON_PREFIX_SENTINEL: &str = "\0auto-api-base\0";
724
725impl AuthPlugin<AuthUser> {
726    /// Mount the built-in `/api/auth/{register,login,logout,me,…}`
727    /// surface. Same handlers that lived in the derive-demo example
728    /// app, promoted to the framework so every app gets them with one
729    /// line. JSON-only; UNIQUE-violation → 409; login returns both a
730    /// Set-Cookie and a bearer token in one response so browsers and
731    /// CLI clients share an endpoint.
732    ///
733    /// The prefix resolves at build time: `{api_base()}/auth`, so it
734    /// follows whatever base the REST plugin set (default `/api/auth`).
735    /// Use [`Self::with_default_routes_at`] to fix a literal prefix.
736    pub fn with_default_routes(mut self) -> Self {
737        // Store the sentinel; `json_prefix()` resolves it at call-time
738        // (which is during `App::build` → `Plugin::routes`), after the
739        // REST plugin has had a chance to call `set_api_base`.
740        self.default_routes_prefix = Some(JSON_PREFIX_SENTINEL.to_string());
741        self
742    }
743
744    /// Same as [`Self::with_default_routes`] but the prefix is yours
745    /// to pick. Useful when `/api/auth` collides with an existing
746    /// surface or you want versioning (`/v1/auth`).
747    pub fn with_default_routes_at(mut self, prefix: impl Into<String>) -> Self {
748        self.default_routes_prefix = Some(prefix.into());
749        self
750    }
751
752    /// Block login until the user's `email_verified_at` column is stamped, and
753    /// auto-send a verification code immediately on `register`. Off by default
754    /// — the `email_verified_at` column is always tracked and the
755    /// `/verify-email` + `/resend-verification` endpoints are always mounted;
756    /// this flag only controls enforcement:
757    ///
758    /// - **register**: after a successful `create_user`, fires
759    ///   `start_email_verification` best-effort (a mail failure does NOT fail
760    ///   registration; it is logged at `warn` level). The `201` response is
761    ///   unchanged.
762    /// - **login**: after `authenticate` succeeds and before minting the
763    ///   bearer token / session, checks `email_verified_at IS NULL`; returns
764    ///   `403 {error: "email_not_verified"}` if so.
765    ///
766    /// Available only on `AuthPlugin<AuthUser>` because enforcement is
767    /// implemented inside the built-in handlers (which are `AuthUser`-only).
768    /// Custom user models bring their own routes and their own enforcement.
769    ///
770    /// Requires a working mailer in production — wire
771    /// [`AuthPlugin::mailer`] alongside this builder, or users won't receive
772    /// the verification code and will be permanently locked out:
773    ///
774    /// ```ignore
775    /// AuthPlugin::<AuthUser>::default()
776    ///     .with_default_routes()
777    ///     .mailer(my_smtp_mailer)
778    ///     .require_verified_email()
779    /// ```
780    pub fn require_verified_email(mut self) -> Self {
781        self.require_verified = true;
782        self
783    }
784
785    /// Mount the 7 POST form-action auth routes (login, logout, signup,
786    /// verify-email, resend, password-forgot, password-reset) under the
787    /// default `/auth` prefix.
788    ///
789    /// These are the form-action **endpoints** that developer-written HTML
790    /// forms POST to: `<form method="POST" action="/auth/login">`. The
791    /// framework never ships the pages themselves — the developer writes
792    /// those with their own brand and design.
793    ///
794    /// Each handler receives a form-encoded body, runs the same auth logic
795    /// as the JSON surface (including throttle and enumeration-safe guards),
796    /// sets a flash message via the session, then returns a 303 redirect.
797    ///
798    /// Use [`Self::with_form_routes_at`] to mount under a custom prefix.
799    pub fn with_form_routes(mut self) -> Self {
800        self.form_routes_prefix = Some("/auth".into());
801        self
802    }
803
804    /// Same as [`Self::with_form_routes`] but you choose the prefix.
805    ///
806    /// ```ignore
807    /// AuthPlugin::<AuthUser>::default().with_form_routes_at("/accounts")
808    /// ```
809    pub fn with_form_routes_at(mut self, prefix: impl Into<String>) -> Self {
810        self.form_routes_prefix = Some(prefix.into());
811        self
812    }
813}
814
815// The extra bounds beyond `UserModel` are what `resolve_user::<U>` needs to load
816// the row — the same set `LoggedIn<U>` already requires. They are stated here so
817// `wrap_router` can mount `db_session_var_layer::<U>` (gaps3 #45). Any user model
818// that couldn't satisfy them was already unusable with the `LoggedIn` extractor.
819impl<U> Plugin for AuthPlugin<U>
820where
821    U: UserModel
822        + for<'r> sqlx::FromRow<'r, sqlx::sqlite::SqliteRow>
823        + for<'r> sqlx::FromRow<'r, sqlx::postgres::PgRow>
824        + umbral::orm::HydrateRelated
825        + Unpin
826        + Send,
827    <U as umbral::orm::Model>::PrimaryKey: std::str::FromStr,
828{
829    fn name(&self) -> &'static str {
830        "auth"
831    }
832
833    fn models(&self) -> Vec<umbral::migrate::ModelMeta> {
834        // AuthToken FKs against AuthUser specifically (FK target is
835        // a concrete `Model` type, not a `UserModel`). Apps wiring
836        // `AuthPlugin::<CustomUser>` get the user table migrated but
837        // NOT the token table — they bring their own token model
838        // and their own bearer-auth backend.
839        let mut models = vec![umbral::migrate::ModelMeta::for_::<U>()];
840        if std::any::TypeId::of::<U>() == std::any::TypeId::of::<AuthUser>() {
841            models.push(umbral::migrate::ModelMeta::for_::<AuthToken>());
842            models.push(umbral::migrate::ModelMeta::for_::<AuthChallenge>());
843        }
844        models
845    }
846
847    fn templates_dirs(&self) -> Vec<std::path::PathBuf> {
848        // The auth plugin ships its own templates (email bodies, future
849        // HTML auth forms). They live under `plugins/umbral-auth/templates/`
850        // in the repo, and `CARGO_MANIFEST_DIR` resolves to that crate root
851        // at compile time so the path stays correct regardless of where the
852        // binary is invoked from.
853        vec![std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("templates")]
854    }
855
856    fn commands(&self) -> Vec<Box<dyn umbral::cli::PluginCommand>> {
857        vec![Box::new(CreateSuperuserCommand)]
858    }
859
860    fn routes(&self) -> umbral::web::Router {
861        // `default_routes_prefix` is only ever Some when U = AuthUser
862        // (the only impl block that sets it is `impl AuthPlugin<AuthUser>`).
863        // So the prefix-guarded branch is dead code for any custom user
864        // model — both at compile time (the builder method isn't
865        // visible) and at runtime (the field stays None).
866        //
867        // `json_prefix()` resolves the sentinel stored by `with_default_routes()`
868        // to `{api_base()}/auth` at build time, after `App::build` has
869        // had a chance to set the REST base path.
870        let mut r = match self.json_prefix() {
871            Some(prefix) => auth_routes::build_router(&prefix),
872            None => umbral::web::Router::new(),
873        };
874        if let Some(p) = &self.form_routes_prefix {
875            r = r.merge(form_routes::build_router(p));
876        }
877        r
878    }
879
880    fn route_paths(&self) -> Vec<umbral::routes::RouteSpec> {
881        let mut paths = match self.json_prefix() {
882            Some(prefix) => auth_routes::declared_routes(&prefix),
883            None => Vec::new(),
884        };
885        if let Some(p) = &self.form_routes_prefix {
886            paths.extend(form_routes::declared_routes(p));
887        }
888        paths
889    }
890
891    fn openapi_paths(&self) -> Vec<(String, serde_json::Value)> {
892        match self.json_prefix() {
893            Some(prefix) => auth_routes::openapi_paths(&prefix),
894            None => Vec::new(),
895        }
896    }
897
898    /// Mount [`user_context_layer`] on the full merged router when the
899    /// `user_in_templates` flag is on (see
900    /// [`AuthPlugin::with_user_in_templates`]). The layer reads the
901    /// session cookie, hydrates the [`AuthUser`], and pushes a
902    /// `serde_json` representation into [`umbral::templates::CURRENT_USER`]
903    /// for the duration of the request — every template render
904    /// downstream gets `user` in its global context with no per-handler
905    /// plumbing.
906    ///
907    /// Off by default — see the builder method's docstring for the
908    /// "why" (one DB read per request, pointless for REST-only apps).
909    fn wrap_router(&self, router: umbral::web::Router) -> umbral::web::Router {
910        let mut router = router;
911        if self.user_in_templates {
912            router = router.layer(axum::middleware::from_fn(user_context_layer));
913        }
914        if let Some(name) = &self.db_session_var {
915            // Applied last, so it is the OUTERMOST of this plugin's layers: the
916            // session variable has to be on the RouteContext before any inner
917            // layer or handler acquires a connection (gaps3 #45).
918            let name: std::sync::Arc<str> = std::sync::Arc::from(name.as_str());
919            router = router.layer(axum::middleware::from_fn_with_state(
920                name,
921                db_session_var_layer::<U>,
922            ));
923        }
924        router
925    }
926
927    /// Seal the password-strength policy into the ambient `OnceLock` so the
928    /// free-function helpers (`create_user`, `set_password`) can read it
929    /// without a handle to `Self`. Mirrors the sessions plugin's
930    /// `SLIDING_EXPIRY_ENABLED` install.
931    ///
932    /// A `None` configured policy means "use the secure default" — NOT
933    /// "off" — so we install [`PasswordPolicy::default`] in that case.
934    /// `disable_password_validation` is the only path that installs an
935    /// empty policy. The install is idempotent (first boot wins), matching
936    /// the ambient-pool contract.
937    fn on_ready(
938        &self,
939        _ctx: &umbral::plugin::AppContext,
940    ) -> Result<(), umbral::plugin::PluginError> {
941        let policy = self
942            .password_policy
943            .lock()
944            .ok()
945            .and_then(|mut guard| guard.take())
946            .unwrap_or_default();
947        password_validation::install_policy(policy);
948        // Install the rate limiter the same way: the route handlers are free
949        // functions, so they read the limiter ambiently via the `throttle`
950        // free helpers. First boot wins (idempotent set), matching the
951        // password-policy / ambient-pool contract.
952        throttle::install(throttle::AuthThrottle::from_config(self.throttle_config));
953        // Seal the mailer into the ambient OnceLock. If None (not configured
954        // by the builder), the active_mailer() fallback supplies ConsoleMailer.
955        if let Ok(mut guard) = self.mailer.0.lock() {
956            if let Some(m) = guard.take() {
957                crate::mailer::install_mailer(m);
958            }
959        }
960        // Seal the verified-email enforcement flag. First boot wins (idempotent),
961        // matching the password-policy / mailer / ambient-pool contract.
962        let _ = REQUIRE_VERIFIED.set(self.require_verified);
963        // Seal the argon2 concurrency cap BEFORE any request hashing runs, so
964        // the gate's semaphore is sized from it (audit_2 plugin-auth #4). Only
965        // when the builder set an explicit value; otherwise the lazy default
966        // (machine parallelism / env var) applies.
967        if let Some(n) = self.hash_concurrency.filter(|&n| n > 0) {
968            let _ = HASH_CONCURRENCY.set(n);
969        }
970        Ok(())
971    }
972}
973
974// =========================================================================
975// AuthError
976// =========================================================================
977
978/// Errors the auth helpers can produce. Kept narrow at M9 v1 so the
979/// surface is easy to handle in one match arm.
980#[derive(Debug)]
981pub enum AuthError {
982    /// argon2 produced or failed to parse a password hash. Carries the
983    /// raw error so the diagnostic includes argon2's own message.
984    PasswordHash(argon2::password_hash::Error),
985    /// sqlx error executing one of the helper queries.
986    Sqlx(sqlx::Error),
987    /// ORM write error — `create`, `update_values`, etc.
988    Write(umbral::orm::write::WriteError),
989    /// `authenticate` was called with credentials that don't match any
990    /// active user. Returned for both "no such user" and "wrong
991    /// password" so a caller can't tell which from the error alone.
992    InvalidCredentials,
993    /// The plaintext password failed one or more password-strength
994    /// validators (see [`crate::password_validation`]). Carries every
995    /// human-readable reason so the route / form can show the full list.
996    ///
997    /// This is NOT produced by the low-level creation helpers anymore
998    /// (`create_user` / `create_user_with_flags` / `create_superuser` /
999    /// `set_password` are all low-level and do not validate). It is
1000    /// constructed at the **registration boundary** — the `register` route
1001    /// calls [`crate::validate_password`] up front and wraps any failure in
1002    /// this variant, which the route layer then maps to 400. A custom signup
1003    /// flow that wants the same behaviour follows the same pattern.
1004    WeakPassword(Vec<String>),
1005    /// A blocking task offloaded to the tokio blocking pool (argon2
1006    /// hashing / verification via [`hash_password_async`] /
1007    /// [`verify_password_async`]) failed to join — i.e. the task panicked
1008    /// or was cancelled. Carries the `JoinError`'s message. A panic in the
1009    /// hash worker is a real error, surfaced rather than swallowed.
1010    Runtime(String),
1011    /// A session-layer error surfaced through one of the auth helpers
1012    /// (`logout`, etc.). Carries the session error's display string so
1013    /// callers match a single `AuthError` type without importing
1014    /// `umbral_sessions::SessionError`.
1015    Session(String),
1016    /// Template rendering failed (e.g. a missing template file or a
1017    /// syntax error). Carries the minijinja error message.
1018    Template(String),
1019    /// The ambient mailer failed to accept the message for delivery.
1020    /// Carries the `AuthMailError` display string.
1021    Mail(String),
1022    /// A challenge lookup or verification failed. Returned for ALL failure
1023    /// arms in the verification flows (no such user, no active challenge,
1024    /// attempt cap reached, wrong code) so a caller can't distinguish
1025    /// which arm fired — prevents account enumeration.
1026    InvalidChallenge,
1027    /// The argon2 concurrency gate shed this request: too much password
1028    /// hashing/verification is already in flight (audit_2 plugin-auth #4).
1029    /// Route handlers map this to HTTP 503 so clients back off rather than
1030    /// the process ballooning memory under a login/register flood.
1031    Overloaded,
1032}
1033
1034impl std::fmt::Display for AuthError {
1035    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1036        match self {
1037            AuthError::PasswordHash(e) => write!(f, "umbral-auth: password hash: {e}"),
1038            AuthError::Sqlx(e) => write!(f, "umbral-auth: sqlx: {e}"),
1039            AuthError::Write(e) => write!(f, "umbral-auth: write: {e:?}"),
1040            AuthError::InvalidCredentials => write!(f, "umbral-auth: invalid credentials"),
1041            AuthError::WeakPassword(reasons) => {
1042                write!(f, "umbral-auth: password rejected: {}", reasons.join(" "))
1043            }
1044            AuthError::Runtime(msg) => write!(f, "umbral-auth: blocking task failed: {msg}"),
1045            AuthError::Session(msg) => write!(f, "umbral-auth: session: {msg}"),
1046            AuthError::Template(msg) => write!(f, "umbral-auth: template: {msg}"),
1047            AuthError::Mail(msg) => write!(f, "umbral-auth: mail: {msg}"),
1048            AuthError::InvalidChallenge => write!(f, "umbral-auth: invalid or expired challenge"),
1049            AuthError::Overloaded => {
1050                write!(
1051                    f,
1052                    "umbral-auth: password-hashing capacity exceeded (try again)"
1053                )
1054            }
1055        }
1056    }
1057}
1058
1059impl std::error::Error for AuthError {}
1060
1061impl From<argon2::password_hash::Error> for AuthError {
1062    fn from(e: argon2::password_hash::Error) -> Self {
1063        Self::PasswordHash(e)
1064    }
1065}
1066
1067impl From<sqlx::Error> for AuthError {
1068    fn from(e: sqlx::Error) -> Self {
1069        Self::Sqlx(e)
1070    }
1071}
1072
1073impl From<umbral::orm::write::WriteError> for AuthError {
1074    fn from(e: umbral::orm::write::WriteError) -> Self {
1075        Self::Write(e)
1076    }
1077}
1078
1079// =========================================================================
1080// Logout helper — single reusable logout for both built-in surfaces and
1081// any custom handler.
1082// =========================================================================
1083
1084/// Log the current request's user out: destroy the session row and emit a
1085/// clearing Set-Cookie on `resp`.
1086///
1087/// This is the single reusable logout — both built-in surfaces (the JSON
1088/// `/auth/logout` route, the HTML auth forms) and any custom handler call
1089/// this rather than reaching for `umbral_sessions::logout` directly.
1090///
1091/// Does NOT revoke bearer tokens (those are explicit-revoke; use
1092/// [`crate::token::AuthToken::revoke`]).
1093///
1094/// # Errors
1095///
1096/// Returns [`AuthError::Session`] if the underlying session destruction
1097/// fails (e.g. DB unreachable). The clearing Set-Cookie is still written
1098/// to `resp` by `umbral_sessions::logout` before the error is returned, so
1099/// the client-side cookie is cleared even on failure.
1100pub async fn logout(
1101    req: &umbral::web::HeaderMap,
1102    resp: &mut umbral::web::HeaderMap,
1103) -> Result<(), AuthError> {
1104    umbral_sessions::logout(req, resp)
1105        .await
1106        .map_err(|e| AuthError::Session(e.to_string()))
1107}
1108
1109// =========================================================================
1110// Password helpers - pure, no DB.
1111// =========================================================================
1112
1113/// Hash a plaintext password with argon2's framework-chosen
1114/// parameters. Returns the PHC-encoded string ready to store in
1115/// the password_hash column. The hash is self-describing so future
1116/// parameter upgrades stay transparent: a verified hash with old
1117/// parameters can be re-hashed on next login.
1118pub fn hash_password(plaintext: &str) -> Result<String, AuthError> {
1119    let salt = SaltString::generate(&mut OsRng);
1120    let hash = password_hasher()
1121        .hash_password(plaintext.as_bytes(), &salt)?
1122        .to_string();
1123    Ok(hash)
1124}
1125
1126/// Verify a plaintext password against an argon2 PHC-encoded hash.
1127/// Returns `Ok(true)` on match, `Ok(false)` on mismatch, and an error
1128/// only when the hash itself is malformed. Callers that just want a
1129/// bool can use `.unwrap_or(false)`.
1130pub fn verify_password(plaintext: &str, hash: &str) -> Result<bool, AuthError> {
1131    let parsed = PasswordHash::new(hash)?;
1132    match password_hasher().verify_password(plaintext.as_bytes(), &parsed) {
1133        Ok(()) => Ok(true),
1134        Err(argon2::password_hash::Error::Password) => Ok(false),
1135        Err(e) => Err(AuthError::PasswordHash(e)),
1136    }
1137}
1138
1139// ── Argon2 concurrency gate (audit_2 plugin-auth #4) ─────────────────────────
1140//
1141// Each argon2id hash/verify allocates ~19 MiB and pins a CPU for ~100 ms.
1142// `spawn_blocking` alone bounds nothing: tokio's blocking pool defaults to 512
1143// threads, so a login/register/reset flood (e.g. distinct usernames that slip
1144// past the per-IP throttle) can run hundreds of hashes at once — 512 × 19 MiB
1145// ≈ 10 GB — and OOM the process. The gate caps CONCURRENT argon2 work so peak
1146// memory is bounded to `cap × 19 MiB`.
1147//
1148// The permit is acquired BEFORE `spawn_blocking`, so a waiting request holds
1149// only its plaintext `String`, not the 19-MiB argon2 buffer — waiting is cheap
1150// and memory stays bounded no matter how deep the queue. To also bound LATENCY
1151// (and stop connections piling up without limit) a second cap on total
1152// in-flight work (`cap × HASH_QUEUE_MULT`, running + waiting) sheds load past
1153// that point with [`AuthError::Overloaded`] → HTTP 503, so clients back off
1154// instead of hanging.
1155
1156/// How many waiters-per-running-slot to admit before shedding load with 503.
1157/// `cap` running + `cap × (MULT-1)` waiting are admitted; the rest get 503.
1158const HASH_QUEUE_MULT: usize = 8;
1159
1160static HASH_CONCURRENCY: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
1161static HASH_GATE: std::sync::OnceLock<tokio::sync::Semaphore> = std::sync::OnceLock::new();
1162static HASH_IN_FLIGHT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
1163
1164/// The maximum number of argon2 operations that may run at once. Defaults to
1165/// the machine's parallelism (min 2) — running more concurrent hashes than
1166/// cores only thrashes and multiplies peak memory for no throughput. Override
1167/// with the `UMBRAL_AUTH_HASH_CONCURRENCY` env var (a positive integer);
1168/// [`AuthPlugin::hash_concurrency`] seals a programmatic value at boot.
1169fn hash_concurrency() -> usize {
1170    *HASH_CONCURRENCY.get_or_init(|| {
1171        std::env::var("UMBRAL_AUTH_HASH_CONCURRENCY")
1172            .ok()
1173            .and_then(|v| v.trim().parse::<usize>().ok())
1174            .filter(|&n| n > 0)
1175            .unwrap_or_else(|| {
1176                std::thread::available_parallelism()
1177                    .map(|n| n.get())
1178                    .unwrap_or(4)
1179                    .max(2)
1180            })
1181    })
1182}
1183
1184fn hash_gate() -> &'static tokio::sync::Semaphore {
1185    HASH_GATE.get_or_init(|| tokio::sync::Semaphore::new(hash_concurrency()))
1186}
1187
1188/// Run one CPU-bound argon2 closure on the blocking pool under the concurrency
1189/// gate. Sheds load with [`AuthError::Overloaded`] once total in-flight work
1190/// exceeds `cap × HASH_QUEUE_MULT`; otherwise waits for a permit (cheaply) and
1191/// runs `f` on `spawn_blocking`.
1192async fn with_hash_gate<F, T>(f: F) -> Result<T, AuthError>
1193where
1194    F: FnOnce() -> T + Send + 'static,
1195    T: Send + 'static,
1196{
1197    use std::sync::atomic::Ordering;
1198
1199    let max_in_flight = hash_concurrency().saturating_mul(HASH_QUEUE_MULT);
1200    // Reserve a slot; reject immediately if the bounded queue is full.
1201    let prev = HASH_IN_FLIGHT.fetch_add(1, Ordering::SeqCst);
1202    if prev >= max_in_flight {
1203        HASH_IN_FLIGHT.fetch_sub(1, Ordering::SeqCst);
1204        return Err(AuthError::Overloaded);
1205    }
1206    // Ensure the counter is decremented on every exit path.
1207    struct Guard;
1208    impl Drop for Guard {
1209        fn drop(&mut self) {
1210            HASH_IN_FLIGHT.fetch_sub(1, Ordering::SeqCst);
1211        }
1212    }
1213    let _guard = Guard;
1214
1215    // Wait for one of `cap` permits — cheap: only a String is held meanwhile.
1216    let _permit = hash_gate()
1217        .acquire()
1218        .await
1219        .map_err(|e| AuthError::Runtime(e.to_string()))?;
1220    tokio::task::spawn_blocking(f)
1221        .await
1222        .map_err(|e| AuthError::Runtime(e.to_string()))
1223}
1224
1225/// Async wrapper around [`hash_password`] that runs the CPU-bound argon2
1226/// work on tokio's blocking pool via `spawn_blocking`, under the concurrency
1227/// gate (see above). argon2id with the framework parameters takes ~100ms of
1228/// CPU; calling it directly from a request handler pins an async worker thread
1229/// for that whole time, so a login/registration burst starves the runtime and
1230/// HTTP/1.1 connections hang. Offloading keeps the async workers free to drive
1231/// other tasks. **Async request handlers must use this**; the sync
1232/// [`hash_password`] remains for non-async / CLI / test callers.
1233pub async fn hash_password_async(plaintext: &str) -> Result<String, AuthError> {
1234    let p = plaintext.to_owned();
1235    with_hash_gate(move || hash_password(&p)).await?
1236}
1237
1238/// Argon2 hash of a fresh, random, un-recoverable password.
1239///
1240/// For accounts created without a user-chosen password — social login, some
1241/// admin-provisioned users — so `password_hash` holds a **real, valid PHC
1242/// hash** instead of an empty string or a `"!"`-style sentinel. Nobody knows
1243/// the plaintext, so [`verify_password`] cleanly returns `false` for any login
1244/// attempt (rather than erroring on an unparseable marker), and the account can
1245/// still adopt a known password later through the email password-reset flow.
1246pub async fn random_password_hash() -> Result<String, AuthError> {
1247    use base64::Engine;
1248    use rand::RngCore;
1249    let mut buf = [0u8; 32];
1250    rand::rngs::OsRng.fill_bytes(&mut buf);
1251    let random = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(buf);
1252    hash_password_async(&random).await
1253}
1254
1255/// Async wrapper around [`verify_password`] that runs the CPU-bound argon2
1256/// verification on tokio's blocking pool via `spawn_blocking`, under the same
1257/// concurrency gate. See [`hash_password_async`] for the starvation rationale.
1258/// **Async request handlers must use this**; the sync [`verify_password`]
1259/// remains for non-async / CLI / test callers.
1260pub async fn verify_password_async(plaintext: &str, hash: &str) -> Result<bool, AuthError> {
1261    let p = plaintext.to_owned();
1262    let h = hash.to_owned();
1263    with_hash_gate(move || verify_password(&p, &h)).await?
1264}
1265
1266fn password_hasher() -> Argon2<'static> {
1267    Argon2::new(
1268        Algorithm::Argon2id,
1269        Version::V0x13,
1270        Params::new(19_456, 2, 1, None).expect("hard-coded argon2 params are valid"),
1271    )
1272}
1273
1274/// A fixed, valid Argon2id hash used purely to spend the same CPU on the
1275/// user-lookup-miss / inactive-user paths of [`authenticate`] as a real
1276/// verify would. Without this, a login for an existing active username costs
1277/// one ~30-50 ms Argon2 verify while a login for a non-existent (or inactive)
1278/// username returns right after the DB SELECT — a measurable timing side
1279/// channel that enumerates valid usernames. Computed once, lazily.
1280///
1281/// The plaintext hashed here is irrelevant; it is never compared against a
1282/// real password. What matters is that the string is a well-formed PHC hash
1283/// so `verify_password` runs the full Argon2 KDF against it.
1284fn dummy_password_hash() -> &'static str {
1285    static DUMMY: std::sync::OnceLock<String> = std::sync::OnceLock::new();
1286    DUMMY.get_or_init(|| {
1287        hash_password("umbral-timing-dummy-*").expect("hard-coded dummy hash is valid")
1288    })
1289}
1290
1291/// Spend one Argon2 verify against [`dummy_password_hash`] so a lookup-miss
1292/// path costs the same wall-clock time as a real credential check. The result
1293/// is intentionally discarded; only the CPU cost matters.
1294async fn burn_password_verify() {
1295    let _ = verify_password_async("umbral-timing-burn", dummy_password_hash()).await;
1296}
1297
1298// =========================================================================
1299// Identifier normalization.
1300//
1301// Usernames and emails are stored and matched case-insensitively: a user
1302// who registered `Dalmasonto` / `Dalmas@Gmail.com` must not be able to
1303// register a second account as `dalmasonto` / `dalmas@gmail.com`, and must
1304// be able to log in typing either case. We enforce this by normalizing to a
1305// canonical (trimmed + lowercased) form at BOTH the write boundary
1306// (`insert_user`) and every lookup boundary (`authenticate`, `verify_email`,
1307// `start_password_reset`, the resend-verification routes). Because every row
1308// is written lowercased, the existing `#[umbral(unique)]` constraint on
1309// `username` / `email` then enforces case-insensitive uniqueness for free —
1310// no case-insensitive index needed.
1311//
1312// Custom user models / signup forms that bypass these helpers should call
1313// `normalize_username` / `normalize_email` themselves at their own write and
1314// lookup sites to stay consistent.
1315// =========================================================================
1316
1317/// Canonicalize a username for storage and lookup: trim surrounding
1318/// whitespace, then lowercase. `"  Dalmasonto "` → `"dalmasonto"`.
1319///
1320/// Applied by [`create_user`] / [`create_user_with_flags`] /
1321/// [`create_superuser`] on write and by [`authenticate`] on lookup, so a
1322/// username is case-insensitively unique and case-insensitively matched.
1323pub fn normalize_username(raw: &str) -> String {
1324    raw.trim().to_lowercase()
1325}
1326
1327/// Canonicalize an email for storage and lookup: trim then lowercase.
1328/// Emails are treated case-insensitively (the pragmatic standard — no real
1329/// deployment relies on a case-sensitive local part), so `Dalmas@Gmail.com`
1330/// and `dalmas@gmail.com` are the same account.
1331pub fn normalize_email(raw: &str) -> String {
1332    raw.trim().to_lowercase()
1333}
1334
1335// =========================================================================
1336// AuthUser-specific creation helpers.
1337//
1338// These functions are intentionally tied to `AuthUser` because they
1339// construct the struct from a fixed set of columns. A custom user model
1340// that wants equivalent creation helpers should provide its own, using
1341// `hash_password` for the password column. See the docs for the
1342// recommended pattern.
1343// =========================================================================
1344
1345/// Create a new active user with the given username, email, and
1346/// plaintext password. The password is hashed before insert; the
1347/// plaintext never touches the database. `date_joined` is set to
1348/// `Utc::now()`; `last_login` is `None`; `is_active = true`,
1349/// `is_staff = false`, `is_superuser = false`.
1350pub async fn create_user(
1351    username: &str,
1352    email: &str,
1353    plaintext: &str,
1354) -> Result<AuthUser, AuthError> {
1355    create_user_with_flags(username, email, plaintext, false, false).await
1356}
1357
1358/// Create a superuser - `is_staff = true`, `is_superuser = true`,
1359/// `is_active = true`. Used by the `createsuperuser` management
1360/// command and available directly for tests / seed scripts.
1361pub async fn create_superuser(
1362    username: &str,
1363    email: &str,
1364    plaintext: &str,
1365) -> Result<AuthUser, AuthError> {
1366    // Low-level, like every other creation helper: it inserts a row and
1367    // does NOT run the password-strength policy. By design, the low-level
1368    // create_superuser doesn't validate; only the
1369    // registration boundary (the `register` route) and any custom signup
1370    // form do. A trusted operator path (the `createsuperuser` command, a
1371    // seed script, a test) chooses the password deliberately, so there's
1372    // nothing to gate here.
1373    insert_user(username, email, plaintext, true, true).await
1374}
1375
1376/// Insert a new user with arbitrary `is_staff` / `is_superuser`
1377/// flags. Used by `create_user` (flags = false, false) and
1378/// `create_superuser` (flags = true, true); exposed publicly so
1379/// custom seed paths can pick a specific shape (e.g. a staff-but-
1380/// not-superuser editor account).
1381pub async fn create_user_with_flags(
1382    username: &str,
1383    email: &str,
1384    plaintext: &str,
1385    is_staff: bool,
1386    is_superuser: bool,
1387) -> Result<AuthUser, AuthError> {
1388    insert_user(username, email, plaintext, is_staff, is_superuser).await
1389}
1390
1391/// The shared insert path behind [`create_user`], [`create_user_with_flags`]
1392/// and [`create_superuser`].
1393///
1394/// This is the **low-level** creation primitive: it hashes the plaintext and
1395/// writes the row, but it does NOT run the password-strength policy. That's
1396/// deliberate: by design the low-level `create_user` doesn't validate;
1397/// the registration boundary does (in umbral, the `register` route, which calls
1398/// [`validate_password`] itself before reaching here). Keeping validation out
1399/// of the insert path means seed scripts, bulk imports, and the workspace test
1400/// suite can create users with deliberately-chosen passwords without tripping
1401/// the policy. An untrusted signup surface must gate on `validate_password`
1402/// up front; the helper trusts its caller.
1403async fn insert_user(
1404    username: &str,
1405    email: &str,
1406    plaintext: &str,
1407    is_staff: bool,
1408    is_superuser: bool,
1409) -> Result<AuthUser, AuthError> {
1410    let now = chrono::Utc::now();
1411    let hash = hash_password_async(plaintext).await?;
1412    // Canonicalize before insert so the `#[umbral(unique)]` constraint enforces
1413    // case-insensitive uniqueness (every stored row is already lowercased).
1414    let username = normalize_username(username);
1415    let email = normalize_email(email);
1416    let row = AuthUser::objects()
1417        .create(AuthUser {
1418            id: 0,
1419            username,
1420            email,
1421            password_hash: hash,
1422            is_active: true,
1423            is_staff,
1424            is_superuser,
1425            date_joined: now,
1426            last_login: None,
1427            email_verified_at: None,
1428        })
1429        .await?;
1430    Ok(row)
1431}
1432
1433// =========================================================================
1434// Generic auth helpers - work against any UserModel.
1435// =========================================================================
1436
1437/// Verify a username + plaintext password against the user table for
1438/// user model `U`. Returns the user on success; returns
1439/// `AuthError::InvalidCredentials` for both "no such user" and "wrong
1440/// password" (the same shape, so a caller can't enumerate accounts).
1441///
1442/// The query uses `U::TABLE` for the table name. The WHERE clause
1443/// filters on `username = ?` and `is_active = 1` (the standard column
1444/// name for the active flag). Custom models that store the active flag
1445/// under a different column name should filter directly and call
1446/// `verify_password` themselves.
1447///
1448/// Does not update `last_login`; that is the login-flow's job once the
1449/// HTTP layer is wired end-to-end.
1450pub async fn authenticate<U>(username: &str, plaintext: &str) -> Result<U, AuthError>
1451where
1452    U: UserModel
1453        + for<'r> sqlx::FromRow<'r, sqlx::sqlite::SqliteRow>
1454        + for<'r> sqlx::FromRow<'r, sqlx::postgres::PgRow>
1455        + umbral::orm::HydrateRelated
1456        + Unpin,
1457{
1458    // Match the canonical (trimmed + lowercased) form written at signup, so a
1459    // login typed as `Dalmasonto` finds the row stored as `dalmasonto`.
1460    let ident = normalize_username(username);
1461    // OR-combine every login column (`["username"]` by default; AuthUser adds
1462    // `email`) so a user can sign in with any of them, then AND the active-flag
1463    // guard. `login_columns()` is never empty.
1464    let mut ident_match: Option<umbral::orm::Predicate<U>> = None;
1465    for col in U::login_columns() {
1466        let p = umbral::orm::Predicate::<U>::col_eq(col, ident.as_str());
1467        ident_match = Some(match ident_match {
1468            Some(acc) => acc | p,
1469            None => p,
1470        });
1471    }
1472    let ident_match = ident_match.expect("UserModel::login_columns() must be non-empty");
1473    let user: Option<U> = umbral::orm::Manager::<U>::default()
1474        .filter(ident_match & umbral::orm::Predicate::<U>::col_eq("is_active", true))
1475        .first()
1476        .await?;
1477
1478    let Some(user) = user else {
1479        // Constant-work miss path: run one Argon2 verify against a dummy hash so
1480        // an unknown username costs the same wall-clock time as a real one. Skips
1481        // the username-enumeration timing oracle (audit plugin-auth #2).
1482        burn_password_verify().await;
1483        return Err(AuthError::InvalidCredentials);
1484    };
1485
1486    // Defence-in-depth: also check the trait method so custom types
1487    // that compute is_active dynamically (e.g. checking a TTL field)
1488    // are still respected even if the SQL filter passed.
1489    if !user.is_active() {
1490        // Same constant-work reasoning as the lookup-miss branch above: an
1491        // inactive account must not be distinguishable by response latency.
1492        burn_password_verify().await;
1493        return Err(AuthError::InvalidCredentials);
1494    }
1495
1496    if verify_password_async(plaintext, user.password_hash()).await? {
1497        Ok(user)
1498    } else {
1499        Err(AuthError::InvalidCredentials)
1500    }
1501}
1502
1503/// Replace a user's password with a fresh hash of the given plaintext.
1504/// Writes through to the database using `U::TABLE`. `user.password_hash`
1505/// is updated in place on success so the caller can keep using the same
1506/// value.
1507pub async fn set_password<U>(user: &mut U, plaintext: &str) -> Result<(), AuthError>
1508where
1509    U: UserModel,
1510{
1511    // Low-level, like `create_user`: this rotates the stored hash and does
1512    // NOT run the password-strength policy. Validation belongs at the
1513    // boundary — a password-change route or form should call
1514    // `validate_password` (with whatever user context it has) BEFORE invoking
1515    // `set_password`, exactly as the `register` route gates `create_user`.
1516    // Keeping the helper non-validating makes `set_password` a pure setter;
1517    // the form is what validates.
1518    let hash = hash_password_async(plaintext).await?;
1519    let mut patch = serde_json::Map::new();
1520    patch.insert(
1521        "password_hash".to_string(),
1522        serde_json::Value::String(hash.clone()),
1523    );
1524    umbral::orm::Manager::<U>::default()
1525        .filter(umbral::orm::Predicate::<U>::col_eq("id", user.id()))
1526        .update_values(patch)
1527        .await?;
1528    user.set_password_hash(hash);
1529    Ok(())
1530}
1531
1532// =========================================================================
1533// Management command: createsuperuser
1534// =========================================================================
1535
1536/// `createsuperuser` - interactive superuser creation,
1537/// dispatched via `cargo run -- createsuperuser` from any umbral
1538/// project that registers [`AuthPlugin`].
1539///
1540/// Prompts for username, email, and password (the password input
1541/// is read without terminal echo via `rpassword`). The new user
1542/// lands with `is_active = true`, `is_staff = true`, `is_superuser =
1543/// true` - the standard shape for the bootstrap admin account.
1544///
1545/// Flags:
1546///
1547/// - `--username <name>` - skip the username prompt.
1548/// - `--email <addr>` - skip the email prompt.
1549/// - `--noinput` - fail if any required value is missing instead of
1550///   prompting. Useful in CI / containers / declarative seed paths.
1551///   Reads password from `UMBRAL_SUPERUSER_PASSWORD` when set.
1552#[derive(Debug, Default)]
1553pub struct CreateSuperuserCommand;
1554
1555#[async_trait::async_trait]
1556impl umbral::cli::PluginCommand for CreateSuperuserCommand {
1557    fn command(&self) -> clap::Command {
1558        clap::Command::new("createsuperuser")
1559            .about("Create a superuser account (is_staff = is_superuser = true)")
1560            .arg(
1561                clap::Arg::new("username")
1562                    .long("username")
1563                    .help("Skip the interactive username prompt")
1564                    .value_name("NAME"),
1565            )
1566            .arg(
1567                clap::Arg::new("email")
1568                    .long("email")
1569                    .help("Skip the interactive email prompt")
1570                    .value_name("ADDR"),
1571            )
1572            .arg(
1573                clap::Arg::new("noinput")
1574                    .long("noinput")
1575                    .help(
1576                        "Fail rather than prompt for any missing value. \
1577                         Reads password from UMBRAL_SUPERUSER_PASSWORD env var.",
1578                    )
1579                    .action(clap::ArgAction::SetTrue),
1580            )
1581    }
1582
1583    async fn run(&self, matches: &clap::ArgMatches) -> Result<(), umbral::cli::CliError> {
1584        let noinput = matches.get_flag("noinput");
1585        let username = resolve_or_prompt(
1586            matches.get_one::<String>("username").cloned(),
1587            "Username",
1588            noinput,
1589            None,
1590        )?;
1591        let email = resolve_or_prompt(
1592            matches.get_one::<String>("email").cloned(),
1593            "Email",
1594            noinput,
1595            None,
1596        )?;
1597        let password = resolve_password(noinput)?;
1598
1599        let user = create_superuser(&username, &email, &password)
1600            .await
1601            .map_err(|e| -> umbral::cli::CliError { Box::new(e) })?;
1602        println!(
1603            "Created superuser `{}` (id = {}) - is_staff = true, is_superuser = true",
1604            user.username, user.id,
1605        );
1606        Ok(())
1607    }
1608}
1609
1610/// Get a value from the CLI flag, the env var, or the interactive
1611/// prompt. The `noinput` flag fails the CLI call rather than
1612/// prompting when no value is available.
1613fn resolve_or_prompt(
1614    cli_value: Option<String>,
1615    label: &str,
1616    noinput: bool,
1617    env_var: Option<&str>,
1618) -> Result<String, umbral::cli::CliError> {
1619    if let Some(v) = cli_value
1620        && !v.is_empty()
1621    {
1622        return Ok(v);
1623    }
1624    if let Some(key) = env_var
1625        && let Ok(v) = std::env::var(key)
1626        && !v.is_empty()
1627    {
1628        return Ok(v);
1629    }
1630    if noinput {
1631        return Err(
1632            format!("umbral createsuperuser: {label} not provided and --noinput is set").into(),
1633        );
1634    }
1635    print!("{label}: ");
1636    use std::io::Write;
1637    std::io::stdout().flush().ok();
1638    let mut s = String::new();
1639    std::io::stdin().read_line(&mut s)?;
1640    let v = s.trim().to_string();
1641    if v.is_empty() {
1642        return Err(format!("umbral createsuperuser: {label} cannot be empty").into());
1643    }
1644    Ok(v)
1645}
1646
1647/// Get the password - env var -> confirm-prompt with no-echo. Refuses
1648/// to proceed when the two confirmation entries don't match.
1649fn resolve_password(noinput: bool) -> Result<String, umbral::cli::CliError> {
1650    if let Ok(v) = std::env::var("UMBRAL_SUPERUSER_PASSWORD")
1651        && !v.is_empty()
1652    {
1653        return Ok(v);
1654    }
1655    if noinput {
1656        return Err(
1657            "umbral createsuperuser: password not provided (set UMBRAL_SUPERUSER_PASSWORD) \
1658             and --noinput is set"
1659                .into(),
1660        );
1661    }
1662    let first = rpassword::prompt_password("Password: ")?;
1663    if first.is_empty() {
1664        return Err("umbral createsuperuser: password cannot be empty".into());
1665    }
1666    let second = rpassword::prompt_password("Password (again): ")?;
1667    if first != second {
1668        return Err("umbral createsuperuser: passwords do not match".into());
1669    }
1670    Ok(first)
1671}
1672
1673#[cfg(test)]
1674mod timing_tests {
1675    use super::*;
1676
1677    /// The constant-work miss path (audit plugin-auth #2) is only real if the
1678    /// dummy hash is a well-formed Argon2id PHC string — otherwise
1679    /// `verify_password` errors out early instead of spending the KDF cost,
1680    /// re-opening the timing oracle. Assert the dummy is a valid hash and that a
1681    /// verify against it actually runs the KDF (returns Ok(false), not Err).
1682    #[test]
1683    fn dummy_hash_is_valid_argon2id_so_miss_path_spends_kdf() {
1684        let h = dummy_password_hash();
1685        assert!(
1686            h.starts_with("$argon2id$"),
1687            "dummy hash must be Argon2id PHC, got {h}"
1688        );
1689        // A real verify runs against it; a wrong password yields Ok(false),
1690        // which means the full KDF executed (an invalid hash would be Err).
1691        assert!(!verify_password("not-the-dummy", h).unwrap());
1692    }
1693}