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

            
7
use argon2::{Argon2, PasswordHash, PasswordHasher, PasswordVerifier};
8
use sqlx::Connection;
9
use sqlx::types::Uuid;
10
use std::fmt::Debug;
11

            
12
use super::{CmdError, admin_connection};
13
use crate::config::ConfigError;
14
use 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)]
20
pub 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)]
28
pub 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`.
41
10980
pub async fn account_refusal(user_id: Uuid) -> Result<Option<Refusal>, CmdError> {
42
10980
    let mut conn = admin_connection().await?;
43

            
44
10980
    let Some(row) = sqlx::query!(
45
        "SELECT quarantined_at, verified FROM users WHERE id = $1",
46
        user_id
47
    )
48
10980
    .fetch_optional(&mut *conn)
49
10980
    .await?
50
    else {
51
180
        return Ok(Some(Refusal::Disabled));
52
    };
53

            
54
10800
    Ok(match (row.quarantined_at, row.verified) {
55
180
        (_, false) => Some(Refusal::Disabled),
56
        (Some(_), _) => Some(Refusal::Quarantined),
57
10620
        _ => None,
58
    })
59
10980
}
60

            
61
/// A directory row plus the reason it may not be served, in one read.
62
pub 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.
81
1620
pub async fn fetch_account(user_id: Uuid) -> Result<Option<Account>, CmdError> {
82
1620
    let mut conn = admin_connection().await?;
83

            
84
1620
    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
1620
    .fetch_optional(&mut *conn)
90
1620
    .await?;
91

            
92
1620
    Ok(row.map(|row| Account {
93
1620
        refusal: match (row.quarantined_at, row.verified) {
94
            (_, false) => Some(Refusal::Disabled),
95
            (Some(_), _) => Some(Refusal::Quarantined),
96
1620
            _ => None,
97
        },
98
1620
        id: row.id,
99
1620
        name: row.name,
100
1620
        email: row.email,
101
1620
        role: row.role,
102
1620
        photo: row.photo,
103
1620
        verified: row.verified,
104
1620
        created_at: row.created_at,
105
1620
        updated_at: row.updated_at,
106
1620
    }))
107
1620
}
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]
112
56544
pub fn fold_email(email: &str) -> String {
113
56544
    email.trim().to_ascii_lowercase()
114
56544
}
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.
120
21608
pub fn validate_email(email: &str) -> Result<String, ConfigError> {
121
21608
    match fold_email(email) {
122
21608
        folded if folded.is_empty() => Err(ConfigError::EmailBlank),
123
21426
        folded => Ok(folded),
124
    }
125
21608
}
126

            
127
/// Whether an email is already registered.
128
///
129
/// # Errors
130
/// [`CmdError::Server`] when the directory is unreachable.
131
10804
pub async fn email_taken(email: &str) -> Result<bool, CmdError> {
132
10804
    let mut conn = admin_connection().await?;
133

            
134
10804
    sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM users WHERE lower(email) = lower($1))")
135
10804
        .bind(fold_email(email))
136
10804
        .fetch_one(&mut *conn)
137
10804
        .await
138
10804
        .map_err(Into::into)
139
10804
}
140

            
141
/// A row to add to the directory.
142
pub 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.
163
10626
pub async fn create_user(new: NewUser<'_>) -> Result<Account, CmdError> {
164
10626
    let email = validate_email(new.email)?;
165
10625
    let mut conn = admin_connection().await?;
166

            
167
10625
    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
10625
    .fetch_one(&mut *conn)
179
10625
    .await
180
1
    .map_err(|err| match err {
181
1
        sqlx::Error::Database(db) if db.is_unique_violation() => ConfigError::EmailTaken.into(),
182
        err => CmdError::from(err),
183
1
    })?;
184

            
185
10624
    Ok(Account {
186
10624
        id: row.id,
187
10624
        name: row.name,
188
10624
        email: row.email,
189
10624
        role: row.role,
190
10624
        photo: row.photo,
191
10624
        verified: row.verified,
192
10624
        created_at: row.created_at,
193
10624
        updated_at: row.updated_at,
194
10624
        refusal: None,
195
10624
    })
196
10626
}
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.
207
12791
pub async fn verify_user_password(
208
12791
    email: &str,
209
12791
    password: &str,
210
12791
) -> Result<Option<VerifiedUser>, CmdError> {
211
12791
    let mut conn = admin_connection().await?;
212
12791
    let Some(row) = sqlx::query_file!("sql/select/users/by_email.sql", fold_email(email))
213
12791
        .fetch_optional(&mut *conn)
214
12791
        .await?
215
    else {
216
2161
        return Ok(None);
217
    };
218
10630
    let Ok(parsed_hash) = PasswordHash::new(&row.password_hash) else {
219
        return Ok(None);
220
    };
221
10630
    let is_valid = Argon2::default()
222
10630
        .verify_password(password.as_bytes(), &parsed_hash)
223
10630
        .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
10630
    if !is_valid || !row.verified {
227
4
        return Ok(None);
228
10626
    }
229
10626
    Ok(Some(VerifiedUser {
230
10626
        user_id: row.id,
231
10626
        ssh_enabled: row.ssh_enabled,
232
10626
        generation: row.session_generation,
233
10626
    }))
234
12791
}
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.
242
184
pub 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
184
    let hash = Argon2::default()
251
184
        .hash_password(new.as_bytes())
252
        .map_err(|_| CmdError::Server(ServerError::PasswordHash))?
253
        .to_string();
254

            
255
184
    let mut conn = admin_connection().await?;
256
184
    let mut tx = conn.begin().await?;
257
184
    let row = sqlx::query_file!("sql/select/users/by_id_password.sql", user_id)
258
184
        .fetch_optional(&mut *tx)
259
184
        .await?
260
        .ok_or_else(|| CmdError::Args(t!("Invalid email or password").to_string()))?;
261

            
262
184
    let verified = PasswordHash::new(&row.password_hash).is_ok_and(|parsed| {
263
184
        Argon2::default()
264
184
            .verify_password(current.as_bytes(), &parsed)
265
184
            .is_ok()
266
184
    });
267
184
    if !verified || !row.verified {
268
3
        return Err(CmdError::Args(t!("Invalid email or password").to_string()));
269
181
    }
270

            
271
181
    sqlx::query_file!("sql/update/users/set_password.sql", user_id, hash)
272
181
        .execute(&mut *tx)
273
181
        .await?;
274
181
    tx.commit().await?;
275
181
    Ok(())
276
184
}
277

            
278
#[cfg(test)]
279
#[path = "user_tests.rs"]
280
mod command_tests;