tablo_core/auth/password.rs
1//! The shipped credentials: the [`AdminUser`] model, its sign-up, and Argon2id hashing.
2
3use std::sync::{Arc, LazyLock};
4
5use jiff::Timestamp;
6use tokio::sync::Semaphore;
7use topcoat::context::Cx;
8use uuid::Uuid;
9
10use super::{
11 PanelUser, PasswordAccount, Registrar, SignUp,
12 account::{email_taken, normalize_email},
13 infrastructure_failure,
14};
15use crate::{FieldErrors, Lens};
16
17/// A dummy Argon2id PHC string verified against when the account does not
18/// exist, so unknown logins pay the same work as known ones (ADR-0013).
19/// Generated with `Argon2::default()` parameters (`m=19456,t=2,p=1`).
20const DUMMY_PASSWORD_HASH: &str = "$argon2id$v=19$m=19456,t=2,p=1$h3oXdPBVwhcgZ1OTO/PuzQ$zLrHLgIkwhqu4ZlLTfSyB8mPuL6mAtaswv/eXJ5ADO8";
21
22/// Shipped credential model with unique email, Argon2id PHC hash, display name,
23/// and active flag; belongs to no tenant. [`PasswordAuth`](super::PasswordAuth) stores the email,
24/// and looks it up, trimmed and lowercased, so one address holds one account whatever case it is
25/// typed in; a resource that edits the email must store it the same way.
26/// Its [`PanelModel`](crate::PanelModel) leave out the hash, so a resource over the panel's
27/// admins lists them. A resource's edit form that changes an admin's email or password hash ends
28/// that admin's sessions, pending sign-ins, reset links and pending email change in the same
29/// transaction; a custom action that changes them does not, and calls
30/// [`revoke_sessions_for_user`](super::revoke_sessions_for_user) itself; one that changes `active`
31/// to `false` ends them at the admin's next request.
32#[derive(Debug, Clone, toasty::Model, crate::PanelModel)]
33pub struct AdminUser {
34 #[key]
35 #[auto]
36 pub id: Uuid,
37 #[unique]
38 pub email: String,
39 /// Argon2id hash in PHC string format; never stores the plaintext.
40 #[columns(skip)]
41 pub password_hash: String,
42 pub display_name: String,
43 /// `false` denies login and panel access immediately.
44 pub active: bool,
45 /// When the account proved it reads `email`; `None` until it does, and again after the
46 /// email changes. Read only by a panel with
47 /// [`Auth::email_verification`](super::Auth::email_verification).
48 pub email_verified_at: Option<Timestamp>,
49 pub created_at: Timestamp,
50}
51
52impl PanelUser for AdminUser {
53 fn user_id(&self) -> String {
54 self.id.to_string()
55 }
56
57 fn display_name(&self) -> &str {
58 &self.display_name
59 }
60
61 fn email(&self) -> Option<&str> {
62 Some(&self.email)
63 }
64
65 fn can_access_panel(&self, _panel: &crate::PanelId) -> bool {
66 self.active
67 }
68}
69
70/// Ends the sessions, pending sign-ins, reset links and pending email change of the user a panel
71/// write changed the sign-in details of, through `ex`: the first mounted authenticator whose
72/// [`changed_credentials`](super::Authenticator::changed_credentials) names one, on every panel
73/// whose authenticator loads its type. A user editing their own account moves to a fresh session,
74/// as on the profile page. A write no authenticator answers for passes through.
75pub(crate) async fn end_changed_credentials(
76 cx: &Cx,
77 ex: &mut dyn toasty::Executor,
78 before: &(dyn std::any::Any + Send + Sync),
79 after: &(dyn std::any::Any + Send + Sync),
80) -> topcoat::Result<()> {
81 let Some(panel) = super::realm::current_realm(cx) else {
82 return Ok(());
83 };
84 let mut realms = super::realm::realms(cx);
85 if realms.is_empty() {
86 realms.push(Arc::clone(panel));
87 }
88 let Some((user_type, user_id)) = realms.iter().find_map(|realm| {
89 let auth = realm.auth.authenticator()?;
90 let user_id = auth.changed_credentials(before, after)?;
91 Some((auth.user_type(), user_id))
92 }) else {
93 return Ok(());
94 };
95 let panels = super::session::credential_panels(cx, user_type, panel);
96 if let Some(signed) = super::signed(cx).filter(|signed| {
97 signed.user.user_id() == user_id && panels.iter().any(|p| Arc::ptr_eq(p, &signed.realm))
98 }) {
99 let session = super::session::start(cx).await?;
100 return super::session::replace_sessions(cx, ex, signed, user_type, &session).await;
101 }
102 super::session::end_credentials(ex, &user_id, &panels, super::token::REVOCATION).await
103}
104
105/// The shipped account [`PasswordAuth`](super::PasswordAuth) signs in by default. An account
106/// whose `active` is `false` signs in nowhere and gets no reset link.
107impl PasswordAccount for AdminUser {
108 type User = Self;
109
110 fn name() -> Lens<Self, String> {
111 crate::lens!(AdminUser.display_name)
112 }
113
114 fn email() -> Lens<Self, String> {
115 crate::lens!(AdminUser.email)
116 }
117
118 fn password_hash() -> Lens<Self, String> {
119 crate::lens!(AdminUser.password_hash)
120 }
121
122 fn email_verified_at() -> Lens<Self, Option<Timestamp>> {
123 crate::lens!(AdminUser.email_verified_at)
124 }
125
126 fn account(user: &Self) -> &Self {
127 user
128 }
129
130 async fn sign_in(
131 self,
132 _cx: &Cx,
133 _ex: &mut dyn toasty::Executor,
134 ) -> topcoat::Result<Option<Self>> {
135 Ok(self.active.then_some(self))
136 }
137}
138
139/// Registers an [`AdminUser`] from a [`SignUp`], refusing a password
140/// [`new_password_errors`](super::new_password_errors) refuses and an email another account
141/// holds. Install it with [`Auth::registration`](super::Auth::registration).
142///
143/// Whether a new account may open the panel is a choice the constructor makes:
144/// [`pending`](Self::pending) stores it inactive, for an administrator to approve by setting
145/// `active`, and the sign-up lands on the login page; [`open`](Self::open) stores it active and
146/// signs it in at once, so any visitor gets the panel's access.
147///
148/// ```rust
149/// use tablo_core::{Auth, PasswordSignUp};
150///
151/// let auth = Auth::password().registration(PasswordSignUp::pending());
152/// # let _ = auth;
153/// ```
154#[derive(Debug, Clone, Copy)]
155pub struct PasswordSignUp {
156 active: bool,
157}
158
159impl PasswordSignUp {
160 /// Stores each new account inactive: it signs in once an administrator approves it.
161 #[must_use]
162 pub fn pending() -> Self {
163 Self { active: false }
164 }
165
166 /// Stores each new account active: any visitor who signs up enters the panel. Open it only
167 /// where any visitor may hold an account.
168 #[must_use]
169 pub fn open() -> Self {
170 Self { active: true }
171 }
172}
173
174impl Registrar for PasswordSignUp {
175 type Input = SignUp;
176 type User = AdminUser;
177
178 async fn validate(
179 &self,
180 _cx: &Cx,
181 sign_up: &SignUp,
182 ex: &mut dyn toasty::Executor,
183 ) -> topcoat::Result<FieldErrors> {
184 let mut errors = sign_up.password_errors();
185 let taken = AdminUser::filter(
186 AdminUser::fields()
187 .email()
188 .eq(normalize_email(&sign_up.email)),
189 )
190 .first()
191 .exec(ex)
192 .await
193 .map_err(infrastructure_failure)?;
194 if taken.is_some() {
195 errors.add_field("email", email_taken());
196 }
197 Ok(errors)
198 }
199
200 async fn register(
201 &self,
202 _cx: &Cx,
203 sign_up: SignUp,
204 ex: &mut dyn toasty::Executor,
205 ) -> topcoat::Result<AdminUser> {
206 insert_admin(
207 ex,
208 &sign_up.email,
209 &sign_up.password,
210 &sign_up.name,
211 self.active,
212 None,
213 )
214 .await
215 }
216}
217
218/// Creates an active [`AdminUser`] that signs in with `email` and `password`, storing only the
219/// password's Argon2id hash: the account a new app seeds to reach its panel. The email is stored
220/// trimmed and lowercased, and verified: whoever seeds the account vouches for the address.
221///
222/// ```rust,no_run
223/// # async fn seed(mut db: toasty::Db) -> topcoat::Result<()> {
224/// tablo_core::auth::create_admin(&mut db, "admin@example.com", "secret", "Admin").await?;
225/// # Ok(())
226/// # }
227/// ```
228///
229/// # Errors
230///
231/// Hashing fails, or the insert does: an email another account holds is refused by its unique
232/// index.
233pub async fn create_admin(
234 ex: &mut dyn toasty::Executor,
235 email: &str,
236 password: &str,
237 display_name: &str,
238) -> topcoat::Result<AdminUser> {
239 insert_admin(
240 ex,
241 email,
242 password,
243 display_name,
244 true,
245 Some(Timestamp::now()),
246 )
247 .await
248}
249
250/// Inserts an [`AdminUser`], `active` or not, verified at `verified_at`.
251async fn insert_admin(
252 ex: &mut dyn toasty::Executor,
253 email: &str,
254 password: &str,
255 display_name: &str,
256 active: bool,
257 verified_at: Option<Timestamp>,
258) -> topcoat::Result<AdminUser> {
259 let admin = toasty::create!(AdminUser {
260 email: normalize_email(email),
261 password_hash: hash_password(password).await?,
262 display_name: display_name.to_string(),
263 active,
264 email_verified_at: verified_at,
265 created_at: Timestamp::now(),
266 })
267 .exec(ex)
268 .await?;
269 Ok(admin)
270}
271
272/// Hashes a password with Argon2id into a PHC string for storage; never stores
273/// the plaintext. Runs on Tokio's blocking pool, as [`verify_password`] does, one hash per core
274/// at once.
275///
276/// # Errors
277///
278/// Argon2 refuses the password.
279pub async fn hash_password(password: &str) -> topcoat::Result<String> {
280 use argon2::password_hash::PasswordHasher;
281
282 let password = password.to_string();
283 off_executor(move || {
284 argon2::Argon2::default()
285 .hash_password(password.as_bytes())
286 .map(|hash| hash.to_string())
287 .map_err(topcoat::Error::from)
288 })
289 .await
290}
291
292/// Verifies a password against an Argon2id PHC hash, or `None` for an unknown
293/// account; unknown accounts verify against a dummy hash so response times do
294/// not reveal which accounts exist.
295///
296/// Runs on Tokio's blocking pool: a verification takes tens of milliseconds of CPU, which on
297/// an async worker would stall every request that worker serves. One verification or hash per
298/// core runs at once, and the rest wait their turn.
299///
300/// ```rust,no_run
301/// # use tablo_core::auth::verify_password;
302/// # #[derive(Debug, Clone, toasty::Model)]
303/// # struct Staff {
304/// # #[key] #[auto] id: uuid::Uuid,
305/// # #[unique]
306/// # email: String,
307/// # password_hash: String,
308/// # }
309/// # async fn sign_in(mut db: toasty::Db, login: &str, password: &str)
310/// # -> topcoat::Result<Option<Staff>> {
311/// let staff = Staff::filter_by_email(login).first().exec(&mut db).await?;
312/// if !verify_password(password, staff.as_ref().map(|s| s.password_hash.as_str())).await {
313/// return Ok(None);
314/// }
315/// # Ok(staff)
316/// # }
317/// ```
318#[must_use]
319pub async fn verify_password(password: &str, hash: Option<&str>) -> bool {
320 use argon2::password_hash::{PasswordVerifier, phc::PasswordHash};
321
322 let known = hash.is_some();
323 let password = password.to_string();
324 let hash = hash.unwrap_or(DUMMY_PASSWORD_HASH).to_string();
325 let verified = off_executor(move || match PasswordHash::new(&hash) {
326 Ok(parsed) => argon2::Argon2::default()
327 .verify_password(password.as_bytes(), &parsed)
328 .is_ok(),
329 // No password matches a hash that does not parse: the account cannot sign in until an
330 // operator resets it, so say why.
331 Err(error) => {
332 tracing::error!(error = %error, "a stored password hash does not parse");
333 false
334 }
335 })
336 .await;
337 verified && known
338}
339
340/// How many Argon2 runs the process allows at once: one per core. Each run holds about 19 MiB,
341/// so a flood of sign-ins under distinct logins, which no throttle count refuses, waits here
342/// instead of filling Tokio's blocking pool and the memory with hashes.
343static ARGON2_PERMITS: LazyLock<Arc<Semaphore>> = LazyLock::new(|| {
344 let cores = std::thread::available_parallelism().map_or(1, std::num::NonZero::get);
345 Arc::new(Semaphore::new(cores))
346});
347
348/// Runs `work` on Tokio's blocking pool once one of [`ARGON2_PERMITS`] is free, re-raising its
349/// panic here.
350async fn off_executor<T: Send + 'static>(work: impl FnOnce() -> T + Send + 'static) -> T {
351 permitted(&ARGON2_PERMITS, work).await
352}
353
354/// Runs `work` on Tokio's blocking pool while holding one of `permits`. The work keeps its permit
355/// until it ends, even when the request awaiting it is dropped.
356pub(super) async fn permitted<T: Send + 'static>(
357 permits: &Arc<Semaphore>,
358 work: impl FnOnce() -> T + Send + 'static,
359) -> T {
360 let permit = Arc::clone(permits)
361 .acquire_owned()
362 .await
363 .expect("the Argon2 semaphore is never closed");
364 let work = move || {
365 let value = work();
366 drop(permit);
367 value
368 };
369 match tokio::task::spawn_blocking(work).await {
370 Ok(value) => value,
371 Err(error) => std::panic::resume_unwind(error.into_panic()),
372 }
373}