Skip to main content

server/command/
user.rs

1//! User-centric commands that cross both the web and SSH login paths.
2//!
3//! Extracted from `web/src/handler.rs` so the SSH daemon reuses the
4//! exact same password-verification code: same Argon2 parameters,
5//! same "invalid email or password" failure mode.
6
7use argon2::{Argon2, PasswordHash, PasswordHasher, PasswordVerifier};
8use sqlx::Connection;
9use sqlx::types::Uuid;
10use std::fmt::Debug;
11
12use super::{CmdError, admin_connection};
13use crate::config::ConfigError;
14use crate::error::ServerError;
15
16/// What a successful [`verify_user_password`] returns. The daemon gates
17/// the entire password code path on `ssh_enabled = TRUE`; the web
18/// handler ignores that flag since it owns its own login surface.
19#[derive(Debug, Clone)]
20pub struct VerifiedUser {
21    pub user_id: Uuid,
22    pub ssh_enabled: bool,
23    pub generation: i32,
24}
25
26/// Why a session may not proceed, when it may not.
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub enum Refusal {
29    /// Withheld by the fleet migrator. Transient.
30    Quarantined,
31    Disabled,
32}
33
34/// Whether this user may currently be served, and if not, why.
35///
36/// Read from the global directory: a database that cannot be reached cannot
37/// record its own failure, so neither flag lives in the tenant.
38///
39/// # Errors
40/// Only on infrastructure failure. An unknown user is refused as `Disabled`.
41pub async fn account_refusal(user_id: Uuid) -> Result<Option<Refusal>, CmdError> {
42    let mut conn = admin_connection().await?;
43
44    let Some(row) = sqlx::query!(
45        "SELECT quarantined_at, verified FROM users WHERE id = $1",
46        user_id
47    )
48    .fetch_optional(&mut *conn)
49    .await?
50    else {
51        return Ok(Some(Refusal::Disabled));
52    };
53
54    Ok(match (row.quarantined_at, row.verified) {
55        (_, false) => Some(Refusal::Disabled),
56        (Some(_), _) => Some(Refusal::Quarantined),
57        _ => None,
58    })
59}
60
61/// A directory row plus the reason it may not be served, in one read.
62pub struct Account {
63    pub id: Uuid,
64    pub name: String,
65    pub email: String,
66    pub role: String,
67    pub photo: String,
68    pub verified: bool,
69    pub created_at: Option<chrono::DateTime<chrono::Utc>>,
70    pub updated_at: Option<chrono::DateTime<chrono::Utc>>,
71    pub refusal: Option<Refusal>,
72}
73
74/// Fetches an account and its serving status.
75///
76/// The one read every authenticated request already performs, kept in this
77/// crate: `web` must not open its own connection to the directory.
78///
79/// # Errors
80/// [`CmdError::Server`] when the directory is unreachable.
81pub async fn fetch_account(user_id: Uuid) -> Result<Option<Account>, CmdError> {
82    let mut conn = admin_connection().await?;
83
84    let row = sqlx::query!(
85        "SELECT id, user_name as name, email, user_role as role, photo, verified, \
86         quarantined_at, created_at, updated_at FROM users WHERE id = $1",
87        user_id
88    )
89    .fetch_optional(&mut *conn)
90    .await?;
91
92    Ok(row.map(|row| Account {
93        refusal: match (row.quarantined_at, row.verified) {
94            (_, false) => Some(Refusal::Disabled),
95            (Some(_), _) => Some(Refusal::Quarantined),
96            _ => None,
97        },
98        id: row.id,
99        name: row.name,
100        email: row.email,
101        role: row.role,
102        photo: row.photo,
103        verified: row.verified,
104        created_at: row.created_at,
105        updated_at: row.updated_at,
106    }))
107}
108
109/// The form an email is stored in: trimmed and ASCII lower-cased. Comparisons
110/// go through the database's `lower()`, the rule of the unique index.
111#[must_use]
112pub fn fold_email(email: &str) -> String {
113    email.trim().to_ascii_lowercase()
114}
115
116/// The folded email, refusing one that folds to nothing.
117///
118/// # Errors
119/// [`ConfigError::EmailBlank`] when the email is empty or only whitespace.
120pub fn validate_email(email: &str) -> Result<String, ConfigError> {
121    match fold_email(email) {
122        folded if folded.is_empty() => Err(ConfigError::EmailBlank),
123        folded => Ok(folded),
124    }
125}
126
127/// Whether an email is already registered.
128///
129/// # Errors
130/// [`CmdError::Server`] when the directory is unreachable.
131pub async fn email_taken(email: &str) -> Result<bool, CmdError> {
132    let mut conn = admin_connection().await?;
133
134    sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM users WHERE lower(email) = lower($1))")
135        .bind(fold_email(email))
136        .fetch_one(&mut *conn)
137        .await
138        .map_err(Into::into)
139}
140
141/// A row to add to the directory.
142pub struct NewUser<'a> {
143    pub id: Uuid,
144    pub name: &'a str,
145    pub email: &'a str,
146    pub password_hash: &'a str,
147    pub database_name: &'a str,
148    pub jwt_public_key: &'a str,
149}
150
151/// Inserts a directory row for a freshly provisioned tenant.
152///
153/// `verified` is set here rather than by changing `0003_users.sql`'s default:
154/// that migration is applied in the global database and in live tenants, so
155/// editing it would change its checksum and fail every boot.
156///
157/// # Errors
158/// [`ConfigError::EmailBlank`] for an empty email,
159/// [`CmdError::Server`] when the directory is unreachable,
160/// [`ConfigError::EmailTaken`] when a concurrent registration won the
161/// `UNIQUE (lower(email))` race, so the caller can drop the database it
162/// already provisioned, and the underlying sqlx error for any other failure.
163pub async fn create_user(new: NewUser<'_>) -> Result<Account, CmdError> {
164    let email = validate_email(new.email)?;
165    let mut conn = admin_connection().await?;
166
167    let row = sqlx::query!(
168        "INSERT INTO users (id,user_name,email,user_password,database_name,jwt_public_key,verified) \
169         VALUES ($1, $2, $3, $4, $5, $6, TRUE) \
170         RETURNING id, user_name as name, email, user_role as role, photo, verified, created_at, updated_at",
171        new.id,
172        new.name,
173        email,
174        new.password_hash,
175        new.database_name,
176        new.jwt_public_key
177    )
178    .fetch_one(&mut *conn)
179    .await
180    .map_err(|err| match err {
181        sqlx::Error::Database(db) if db.is_unique_violation() => ConfigError::EmailTaken.into(),
182        err => CmdError::from(err),
183    })?;
184
185    Ok(Account {
186        id: row.id,
187        name: row.name,
188        email: row.email,
189        role: row.role,
190        photo: row.photo,
191        verified: row.verified,
192        created_at: row.created_at,
193        updated_at: row.updated_at,
194        refusal: None,
195    })
196}
197
198/// Shared verification helper returning the richer `VerifiedUser`
199/// shape. The SSH daemon uses this directly so it can gate the
200/// password path on `ssh_enabled`.
201///
202/// # Errors
203///
204/// Returns `Err` only on infrastructure failure (DB unavailable).
205/// Mismatched credentials resolve to `Ok(None)` — the single failure
206/// mode the caller should pattern-match on.
207pub async fn verify_user_password(
208    email: &str,
209    password: &str,
210) -> Result<Option<VerifiedUser>, CmdError> {
211    let mut conn = admin_connection().await?;
212    let Some(row) = sqlx::query_file!("sql/select/users/by_email.sql", fold_email(email))
213        .fetch_optional(&mut *conn)
214        .await?
215    else {
216        return Ok(None);
217    };
218    let Ok(parsed_hash) = PasswordHash::new(&row.password_hash) else {
219        return Ok(None);
220    };
221    let is_valid = Argon2::default()
222        .verify_password(password.as_bytes(), &parsed_hash)
223        .is_ok();
224    // After the hash, not before: an early return would make a disabled
225    // account measurably faster to probe than a wrong password.
226    if !is_valid || !row.verified {
227        return Ok(None);
228    }
229    Ok(Some(VerifiedUser {
230        user_id: row.id,
231        ssh_enabled: row.ssh_enabled,
232        generation: row.session_generation,
233    }))
234}
235
236/// Replaces the password and revokes every outstanding session, in one
237/// statement.
238///
239/// # Errors
240/// `CmdError::Args` when the current password does not verify; otherwise only
241/// on infrastructure failure.
242pub async fn change_password(user_id: Uuid, current: &str, new: &str) -> Result<(), CmdError> {
243    // Hashed before taking a connection: Argon2 is deliberately slow and the
244    // hash does not depend on the row, so it has no business holding one of
245    // the admin pool's five connections.
246    //
247    // Not `Args`: failing to produce a hash is an infrastructure fault, and the
248    // handler turns `Args` into "invalid password", which would send the user
249    // off retyping a password that was right.
250    let hash = Argon2::default()
251        .hash_password(new.as_bytes())
252        .map_err(|_| CmdError::Server(ServerError::PasswordHash))?
253        .to_string();
254
255    let mut conn = admin_connection().await?;
256    let mut tx = conn.begin().await?;
257    let row = sqlx::query_file!("sql/select/users/by_id_password.sql", user_id)
258        .fetch_optional(&mut *tx)
259        .await?
260        .ok_or_else(|| CmdError::Args(t!("Invalid email or password").to_string()))?;
261
262    let verified = PasswordHash::new(&row.password_hash).is_ok_and(|parsed| {
263        Argon2::default()
264            .verify_password(current.as_bytes(), &parsed)
265            .is_ok()
266    });
267    if !verified || !row.verified {
268        return Err(CmdError::Args(t!("Invalid email or password").to_string()));
269    }
270
271    sqlx::query_file!("sql/update/users/set_password.sql", user_id, hash)
272        .execute(&mut *tx)
273        .await?;
274    tx.commit().await?;
275    Ok(())
276}
277
278#[cfg(test)]
279#[path = "user_tests.rs"]
280mod command_tests;