Lines
93.97 %
Functions
73.68 %
Branches
100 %
//! User-centric commands that cross both the web and SSH login paths.
//!
//! Extracted from `web/src/handler.rs` so the SSH daemon reuses the
//! exact same password-verification code: same Argon2 parameters,
//! same "invalid email or password" failure mode.
use argon2::{Argon2, PasswordHash, PasswordHasher, PasswordVerifier};
use sqlx::Connection;
use sqlx::types::Uuid;
use std::fmt::Debug;
use super::{CmdError, admin_connection};
use crate::config::ConfigError;
use crate::error::ServerError;
/// What a successful [`verify_user_password`] returns. The daemon gates
/// the entire password code path on `ssh_enabled = TRUE`; the web
/// handler ignores that flag since it owns its own login surface.
#[derive(Debug, Clone)]
pub struct VerifiedUser {
pub user_id: Uuid,
pub ssh_enabled: bool,
pub generation: i32,
}
/// Why a session may not proceed, when it may not.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Refusal {
/// Withheld by the fleet migrator. Transient.
Quarantined,
Disabled,
/// Whether this user may currently be served, and if not, why.
///
/// Read from the global directory: a database that cannot be reached cannot
/// record its own failure, so neither flag lives in the tenant.
/// # Errors
/// Only on infrastructure failure. An unknown user is refused as `Disabled`.
pub async fn account_refusal(user_id: Uuid) -> Result<Option<Refusal>, CmdError> {
let mut conn = admin_connection().await?;
let Some(row) = sqlx::query!(
"SELECT quarantined_at, verified FROM users WHERE id = $1",
user_id
)
.fetch_optional(&mut *conn)
.await?
else {
return Ok(Some(Refusal::Disabled));
};
Ok(match (row.quarantined_at, row.verified) {
(_, false) => Some(Refusal::Disabled),
(Some(_), _) => Some(Refusal::Quarantined),
_ => None,
})
/// A directory row plus the reason it may not be served, in one read.
pub struct Account {
pub id: Uuid,
pub name: String,
pub email: String,
pub role: String,
pub photo: String,
pub verified: bool,
pub created_at: Option<chrono::DateTime<chrono::Utc>>,
pub updated_at: Option<chrono::DateTime<chrono::Utc>>,
pub refusal: Option<Refusal>,
/// Fetches an account and its serving status.
/// The one read every authenticated request already performs, kept in this
/// crate: `web` must not open its own connection to the directory.
/// [`CmdError::Server`] when the directory is unreachable.
pub async fn fetch_account(user_id: Uuid) -> Result<Option<Account>, CmdError> {
let row = sqlx::query!(
"SELECT id, user_name as name, email, user_role as role, photo, verified, \
quarantined_at, created_at, updated_at FROM users WHERE id = $1",
.await?;
Ok(row.map(|row| Account {
refusal: match (row.quarantined_at, row.verified) {
},
id: row.id,
name: row.name,
email: row.email,
role: row.role,
photo: row.photo,
verified: row.verified,
created_at: row.created_at,
updated_at: row.updated_at,
}))
/// The form an email is stored in: trimmed and ASCII lower-cased. Comparisons
/// go through the database's `lower()`, the rule of the unique index.
#[must_use]
pub fn fold_email(email: &str) -> String {
email.trim().to_ascii_lowercase()
/// The folded email, refusing one that folds to nothing.
/// [`ConfigError::EmailBlank`] when the email is empty or only whitespace.
pub fn validate_email(email: &str) -> Result<String, ConfigError> {
match fold_email(email) {
folded if folded.is_empty() => Err(ConfigError::EmailBlank),
folded => Ok(folded),
/// Whether an email is already registered.
pub async fn email_taken(email: &str) -> Result<bool, CmdError> {
sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM users WHERE lower(email) = lower($1))")
.bind(fold_email(email))
.fetch_one(&mut *conn)
.await
.map_err(Into::into)
/// A row to add to the directory.
pub struct NewUser<'a> {
pub name: &'a str,
pub email: &'a str,
pub password_hash: &'a str,
pub database_name: &'a str,
pub jwt_public_key: &'a str,
/// Inserts a directory row for a freshly provisioned tenant.
/// `verified` is set here rather than by changing `0003_users.sql`'s default:
/// that migration is applied in the global database and in live tenants, so
/// editing it would change its checksum and fail every boot.
/// [`ConfigError::EmailBlank`] for an empty email,
/// [`CmdError::Server`] when the directory is unreachable,
/// [`ConfigError::EmailTaken`] when a concurrent registration won the
/// `UNIQUE (lower(email))` race, so the caller can drop the database it
/// already provisioned, and the underlying sqlx error for any other failure.
pub async fn create_user(new: NewUser<'_>) -> Result<Account, CmdError> {
let email = validate_email(new.email)?;
"INSERT INTO users (id,user_name,email,user_password,database_name,jwt_public_key,verified) \
VALUES ($1, $2, $3, $4, $5, $6, TRUE) \
RETURNING id, user_name as name, email, user_role as role, photo, verified, created_at, updated_at",
new.id,
new.name,
email,
new.password_hash,
new.database_name,
new.jwt_public_key
.map_err(|err| match err {
sqlx::Error::Database(db) if db.is_unique_violation() => ConfigError::EmailTaken.into(),
err => CmdError::from(err),
})?;
Ok(Account {
refusal: None,
/// Shared verification helper returning the richer `VerifiedUser`
/// shape. The SSH daemon uses this directly so it can gate the
/// password path on `ssh_enabled`.
/// Returns `Err` only on infrastructure failure (DB unavailable).
/// Mismatched credentials resolve to `Ok(None)` — the single failure
/// mode the caller should pattern-match on.
pub async fn verify_user_password(
email: &str,
password: &str,
) -> Result<Option<VerifiedUser>, CmdError> {
let Some(row) = sqlx::query_file!("sql/select/users/by_email.sql", fold_email(email))
return Ok(None);
let Ok(parsed_hash) = PasswordHash::new(&row.password_hash) else {
let is_valid = Argon2::default()
.verify_password(password.as_bytes(), &parsed_hash)
.is_ok();
// After the hash, not before: an early return would make a disabled
// account measurably faster to probe than a wrong password.
if !is_valid || !row.verified {
Ok(Some(VerifiedUser {
user_id: row.id,
ssh_enabled: row.ssh_enabled,
generation: row.session_generation,
/// Replaces the password and revokes every outstanding session, in one
/// statement.
/// `CmdError::Args` when the current password does not verify; otherwise only
/// on infrastructure failure.
pub async fn change_password(user_id: Uuid, current: &str, new: &str) -> Result<(), CmdError> {
// Hashed before taking a connection: Argon2 is deliberately slow and the
// hash does not depend on the row, so it has no business holding one of
// the admin pool's five connections.
//
// Not `Args`: failing to produce a hash is an infrastructure fault, and the
// handler turns `Args` into "invalid password", which would send the user
// off retyping a password that was right.
let hash = Argon2::default()
.hash_password(new.as_bytes())
.map_err(|_| CmdError::Server(ServerError::PasswordHash))?
.to_string();
let mut tx = conn.begin().await?;
let row = sqlx::query_file!("sql/select/users/by_id_password.sql", user_id)
.fetch_optional(&mut *tx)
.ok_or_else(|| CmdError::Args(t!("Invalid email or password").to_string()))?;
let verified = PasswordHash::new(&row.password_hash).is_ok_and(|parsed| {
Argon2::default()
.verify_password(current.as_bytes(), &parsed)
.is_ok()
});
if !verified || !row.verified {
return Err(CmdError::Args(t!("Invalid email or password").to_string()));
sqlx::query_file!("sql/update/users/set_password.sql", user_id, hash)
.execute(&mut *tx)
tx.commit().await?;
Ok(())
#[cfg(test)]
#[path = "user_tests.rs"]
mod command_tests;