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