Skip to main content

kasl_server/
admin.rs

1//! Managing people and the agents that report for them.
2//!
3//! Everything here is behind a session (ADR 0007) and a role. Two rules shape
4//! the routes, both settled before they were written (ADR 0008):
5//!
6//! * **A manager reads, an administrator writes.** Until departments exist
7//!   there is nothing to scope a manager's authority to, and handing out the
8//!   power to issue agent tokens company-wide - with no audit log yet to notice
9//!   - is not a default worth shipping.
10//! * **A token is shown once.** The server keeps its SHA-256 and nothing else,
11//!   so an issued token that was not written down is replaced, not recovered.
12
13use axum::{
14    Json,
15    extract::{Path, State},
16    http::StatusCode,
17    response::IntoResponse,
18};
19use chrono::{DateTime, Utc};
20use serde::{Deserialize, Serialize};
21use uuid::Uuid;
22
23use crate::{app::AppState, auth::hash_token, error::ApiError, login::CurrentUser, model::UserRole, session};
24
25/// The shortest password the server will store.
26///
27/// A floor, not a policy: complexity rules belong where they can be explained
28/// to the person typing, and a server that refuses `hunter2` while accepting
29/// `Passw0rd!` has chosen theatre over arithmetic.
30const MIN_PASSWORD_LENGTH: usize = 8;
31
32/// A person as the admin screens list them.
33#[derive(Debug, Serialize, sqlx::FromRow)]
34pub struct UserRow {
35    pub id: Uuid,
36    pub email: String,
37    pub display_name: String,
38    pub role: UserRole,
39    pub active: bool,
40    /// Whether they can sign in at all. Accounts created for an agent have no
41    /// password, and the UI needs to show that rather than imply a login that
42    /// does not exist.
43    pub has_password: bool,
44    /// Agents currently able to report for them.
45    pub agents: i64,
46    /// The most recent moment any of their agents was heard from.
47    pub last_seen_at: Option<DateTime<Utc>>,
48    pub department_id: Option<Uuid>,
49    /// Carried alongside the id so a list can be rendered without a second
50    /// request per row.
51    pub department: Option<String>,
52    pub created_at: DateTime<Utc>,
53}
54
55#[derive(Debug, Deserialize)]
56pub struct NewUser {
57    pub email: String,
58    pub display_name: Option<String>,
59    #[serde(default = "default_role")]
60    pub role: UserRole,
61    /// Initial password. Optional: an account that only owns an agent's data
62    /// has no reason to be signed into.
63    pub password: Option<String>,
64}
65
66fn default_role() -> UserRole {
67    UserRole::Employee
68}
69
70/// A change to an existing person. Every field is optional; absent means
71/// "leave it alone" rather than "clear it".
72#[derive(Debug, Deserialize)]
73pub struct UserPatch {
74    pub display_name: Option<String>,
75    pub role: Option<UserRole>,
76    pub active: Option<bool>,
77    /// Sets or replaces the password. There is no way to remove one here: an
78    /// account that could be signed into yesterday and silently cannot today is
79    /// a support call, not a feature.
80    pub password: Option<String>,
81}
82
83/// An agent as the admin screens list it. Never the token.
84#[derive(Debug, Serialize, sqlx::FromRow)]
85pub struct AgentRow {
86    pub id: Uuid,
87    pub name: String,
88    pub revoked_at: Option<DateTime<Utc>>,
89    pub last_seen_at: Option<DateTime<Utc>>,
90    pub created_at: DateTime<Utc>,
91}
92
93#[derive(Debug, Deserialize)]
94pub struct NewAgent {
95    /// Human label, typically the machine the agent runs on.
96    pub name: String,
97}
98
99/// The one response that carries a token, and the only time it exists.
100#[derive(Debug, Serialize)]
101pub struct IssuedAgent {
102    pub id: Uuid,
103    pub name: String,
104    pub token: String,
105    /// Said plainly in the payload, because the UI that forgets to say it is
106    /// the reason someone loses a token they never wrote down.
107    pub notice: &'static str,
108}
109
110/// Lists everyone. The one route a manager may call.
111/// Lists the people the caller may see.
112///
113/// An administrator sees everyone. A manager sees the departments they run,
114/// plus themselves - a manager who could not find their own row would think
115/// the page was broken. Someone with no department is visible to the admin
116/// alone: an unfiled person is noticed at once because they are missing from
117/// every manager's list, whereas showing them to every manager would be a leak
118/// nobody sees happening (ADR 0009).
119pub async fn list_users(State(state): State<AppState>, user: CurrentUser) -> Result<impl IntoResponse, ApiError> {
120    require_manager_or_admin(&user)?;
121
122    let users: Vec<UserRow> = sqlx::query_as(
123        "SELECT u.id, u.email, u.display_name, u.role, u.active,
124                (u.password_hash IS NOT NULL) AS has_password,
125                (SELECT count(*) FROM agents a WHERE a.user_id = u.id AND a.revoked_at IS NULL) AS agents,
126                (SELECT max(a.last_seen_at) FROM agents a WHERE a.user_id = u.id) AS last_seen_at,
127                u.department_id,
128                d.name AS department,
129                u.created_at
130         FROM users u
131         LEFT JOIN departments d ON d.id = u.department_id
132         WHERE $1
133            OR u.id = $2
134            OR u.department_id IN (SELECT id FROM departments WHERE manager_id = $2)
135         ORDER BY u.display_name, u.email",
136    )
137    .bind(user.role == UserRole::Admin)
138    .bind(user.user_id)
139    .fetch_all(&state.pool)
140    .await?;
141
142    Ok(Json(users))
143}
144
145/// Creates a person.
146pub async fn create_user(State(state): State<AppState>, user: CurrentUser, Json(new): Json<NewUser>) -> Result<impl IntoResponse, ApiError> {
147    user.require_admin()?;
148
149    let email = new.email.trim();
150    if !looks_like_an_email(email) {
151        return Err(ApiError::bad_request("that does not look like an email address"));
152    }
153    let password_hash = match new.password.as_deref() {
154        Some(password) => Some(hash_new_password(password)?),
155        None => None,
156    };
157    // The local part until someone sets a real one - the same default the
158    // environment-seeded accounts get, so the two look alike in a list.
159    let display_name = new
160        .display_name
161        .as_deref()
162        .map(str::trim)
163        .filter(|name| !name.is_empty())
164        .unwrap_or_else(|| email.split('@').next().unwrap_or(email));
165
166    let created: Result<Uuid, sqlx::Error> =
167        sqlx::query_scalar("INSERT INTO users (email, display_name, role, password_hash) VALUES ($1, $2, $3, $4) RETURNING id")
168            .bind(email)
169            .bind(display_name)
170            .bind(new.role)
171            .bind(password_hash.as_deref())
172            .fetch_one(&state.pool)
173            .await;
174
175    let id = match created {
176        Ok(id) => id,
177        // The unique index on lower(email). Answered as a conflict rather than
178        // a 500: the admin typed an address that is already here, which is
179        // something they can act on.
180        Err(sqlx::Error::Database(error)) if error.is_unique_violation() => {
181            return Err(ApiError::new(StatusCode::CONFLICT, "someone with that email address already exists"));
182        }
183        Err(error) => return Err(error.into()),
184    };
185
186    tracing::info!(%id, by = %user.user_id, "created a user");
187    Ok((StatusCode::CREATED, Json(serde_json::json!({"id": id}))))
188}
189
190/// Changes a person: their name, role, password, or whether they are active.
191pub async fn update_user(
192    State(state): State<AppState>,
193    user: CurrentUser,
194    Path(target): Path<Uuid>,
195    Json(patch): Json<UserPatch>,
196) -> Result<impl IntoResponse, ApiError> {
197    user.require_admin()?;
198
199    // The last administrator cannot be demoted or deactivated. Both would leave
200    // an installation nobody can administer, recoverable only by running the
201    // `admin` subcommand on the host - which is not where an admin who just
202    // clicked a toggle in a browser will think to look.
203    let losing_admin = patch.role.is_some_and(|role| role != UserRole::Admin) || patch.active == Some(false);
204    if losing_admin && is_last_admin(&state.pool, target).await? {
205        return Err(ApiError::new(
206            StatusCode::CONFLICT,
207            "this is the only administrator; promote someone else first",
208        ));
209    }
210
211    let password_hash = match patch.password.as_deref() {
212        Some(password) => Some(hash_new_password(password)?),
213        None => None,
214    };
215
216    let updated = sqlx::query(
217        "UPDATE users SET
218             display_name = coalesce($2, display_name),
219             role = coalesce($3, role),
220             active = coalesce($4, active),
221             password_hash = coalesce($5, password_hash)
222         WHERE id = $1",
223    )
224    .bind(target)
225    .bind(patch.display_name.as_deref().map(str::trim).filter(|name| !name.is_empty()))
226    .bind(patch.role)
227    .bind(patch.active)
228    .bind(password_hash.as_deref())
229    .execute(&state.pool)
230    .await?
231    .rows_affected();
232
233    if updated == 0 {
234        return Err(ApiError::new(StatusCode::NOT_FOUND, "no such user"));
235    }
236
237    // Deactivation and a password change both mean the old sessions should not
238    // survive: one is someone leaving, the other is usually a suspicion that
239    // someone else has been signing in.
240    if patch.active == Some(false) || patch.password.is_some() {
241        let ended = session::revoke_all(&state.pool, target).await?;
242        tracing::info!(%target, ended, "ended sessions after a change to the account");
243    }
244
245    tracing::info!(%target, by = %user.user_id, "updated a user");
246    Ok(StatusCode::NO_CONTENT)
247}
248
249/// Lists someone's agents, revoked ones included - a withdrawn token is part of
250/// the record of what happened.
251pub async fn list_agents(State(state): State<AppState>, user: CurrentUser, Path(target): Path<Uuid>) -> Result<impl IntoResponse, ApiError> {
252    require_manager_or_admin(&user)?;
253
254    let agents: Vec<AgentRow> = sqlx::query_as("SELECT id, name, revoked_at, last_seen_at, created_at FROM agents WHERE user_id = $1 ORDER BY created_at")
255        .bind(target)
256        .fetch_all(&state.pool)
257        .await?;
258
259    Ok(Json(agents))
260}
261
262/// Issues an agent token, shown once.
263pub async fn create_agent(
264    State(state): State<AppState>,
265    user: CurrentUser,
266    Path(target): Path<Uuid>,
267    Json(new): Json<NewAgent>,
268) -> Result<impl IntoResponse, ApiError> {
269    user.require_admin()?;
270
271    let name = new.name.trim();
272    if name.is_empty() {
273        return Err(ApiError::bad_request("an agent needs a name; the machine it runs on is the usual one"));
274    }
275
276    // An agent for a deactivated person would be refused on its first upload
277    // anyway; saying so here saves someone installing kasl on a laptop to find
278    // out.
279    let active: Option<bool> = sqlx::query_scalar("SELECT active FROM users WHERE id = $1")
280        .bind(target)
281        .fetch_optional(&state.pool)
282        .await?;
283    match active {
284        None => return Err(ApiError::new(StatusCode::NOT_FOUND, "no such user")),
285        Some(false) => return Err(ApiError::new(StatusCode::CONFLICT, "that account is deactivated")),
286        Some(true) => {}
287    }
288
289    let token = generate_token();
290    let id: Uuid = sqlx::query_scalar("INSERT INTO agents (user_id, name, token_hash) VALUES ($1, $2, $3) RETURNING id")
291        .bind(target)
292        .bind(name)
293        .bind(hash_token(&token))
294        .fetch_one(&state.pool)
295        .await?;
296
297    tracing::info!(%id, %target, by = %user.user_id, "issued an agent token");
298    Ok((
299        StatusCode::CREATED,
300        Json(IssuedAgent {
301            id,
302            name: name.to_string(),
303            token,
304            notice: "this token is shown once; the server keeps only its hash",
305        }),
306    ))
307}
308
309/// Withdraws an agent's token. The row stays, so its uploads keep an owner.
310pub async fn revoke_agent(State(state): State<AppState>, user: CurrentUser, Path(agent): Path<Uuid>) -> Result<impl IntoResponse, ApiError> {
311    user.require_admin()?;
312
313    // `revoked_at IS NULL` in the filter makes this idempotent without pretending
314    // it succeeded twice: revoking an already-revoked agent must not move the
315    // timestamp of when access actually ended.
316    let revoked = sqlx::query("UPDATE agents SET revoked_at = now() WHERE id = $1 AND revoked_at IS NULL")
317        .bind(agent)
318        .execute(&state.pool)
319        .await?
320        .rows_affected();
321
322    if revoked == 0 {
323        // Either it does not exist or it was already revoked; both mean the
324        // token does not work, which is what the caller wanted.
325        let exists: Option<Uuid> = sqlx::query_scalar("SELECT id FROM agents WHERE id = $1")
326            .bind(agent)
327            .fetch_optional(&state.pool)
328            .await?;
329        if exists.is_none() {
330            return Err(ApiError::new(StatusCode::NOT_FOUND, "no such agent"));
331        }
332    }
333
334    tracing::info!(%agent, by = %user.user_id, "revoked an agent token");
335    Ok(StatusCode::NO_CONTENT)
336}
337
338/// Changes one's own password.
339///
340/// Not an admin route: this is how someone stops the admin who set their
341/// initial password from knowing it.
342#[derive(Debug, Deserialize)]
343pub struct PasswordChange {
344    pub current: String,
345    pub new: String,
346}
347
348pub async fn change_own_password(State(state): State<AppState>, user: CurrentUser, Json(change): Json<PasswordChange>) -> Result<impl IntoResponse, ApiError> {
349    let stored: Option<String> = sqlx::query_scalar("SELECT password_hash FROM users WHERE id = $1")
350        .bind(user.user_id)
351        .fetch_one(&state.pool)
352        .await?;
353
354    // Proving the current password is what stops a borrowed unlocked laptop
355    // from becoming a permanent one.
356    let Some(stored) = stored else {
357        return Err(ApiError::new(StatusCode::CONFLICT, "this account has no password to change"));
358    };
359    if !session::verify_password(&change.current, &stored) {
360        return Err(ApiError::new(StatusCode::UNAUTHORIZED, "the current password is wrong"));
361    }
362
363    let hash = hash_new_password(&change.new)?;
364    sqlx::query("UPDATE users SET password_hash = $1 WHERE id = $2")
365        .bind(&hash)
366        .bind(user.user_id)
367        .execute(&state.pool)
368        .await?;
369
370    // Every other session ends, and this one survives: changing a password is
371    // how someone reacts to a suspicion, and being logged out of the browser
372    // they just did it in would be a poor reward.
373    sqlx::query("DELETE FROM sessions WHERE user_id = $1 AND id <> $2")
374        .bind(user.user_id)
375        .bind(user.session_id)
376        .execute(&state.pool)
377        .await?;
378
379    tracing::info!(user_id = %user.user_id, "changed their password");
380    Ok(StatusCode::NO_CONTENT)
381}
382
383/// Both roles that may read the team.
384fn require_manager_or_admin(user: &CurrentUser) -> Result<(), ApiError> {
385    match user.role {
386        UserRole::Admin | UserRole::Manager => Ok(()),
387        UserRole::Employee => Err(ApiError::new(StatusCode::FORBIDDEN, "not allowed")),
388    }
389}
390
391/// Hashes a password after checking it is long enough to be one.
392fn hash_new_password(password: &str) -> Result<String, ApiError> {
393    if password.chars().count() < MIN_PASSWORD_LENGTH {
394        return Err(ApiError::bad_request(format!("the password must be at least {MIN_PASSWORD_LENGTH} characters")));
395    }
396    session::hash_password(password).map_err(Into::into)
397}
398
399/// A new agent token: 32 bytes of entropy, hex.
400///
401/// Prefixed so that a token found in a log or a config file is recognisable as
402/// one, and so a leaked-secret scanner has something to match on.
403fn generate_token() -> String {
404    use rand::RngExt;
405
406    let bytes: [u8; 32] = rand::rng().random();
407    bytes.iter().fold(String::from("kasl_"), |mut acc, byte| {
408        use std::fmt::Write;
409        let _ = write!(acc, "{byte:02x}");
410        acc
411    })
412}
413
414/// The shallowest possible check: an `@` with something either side.
415///
416/// Deliberately not a full grammar. The addresses here are typed by an admin
417/// who knows their own team, and a regex strict enough to be interesting is
418/// strict enough to reject somebody's real address.
419fn looks_like_an_email(candidate: &str) -> bool {
420    match candidate.split_once('@') {
421        Some((local, domain)) => !local.is_empty() && domain.contains('.') && !domain.starts_with('.') && !domain.ends_with('.'),
422        None => false,
423    }
424}
425
426/// Whether this user is the only administrator left standing.
427async fn is_last_admin(pool: &sqlx::PgPool, target: Uuid) -> Result<bool, ApiError> {
428    let others: i64 = sqlx::query_scalar("SELECT count(*) FROM users WHERE role = 'admin' AND active AND id <> $1")
429        .bind(target)
430        .fetch_one(pool)
431        .await?;
432
433    // Only matters if the target is an active admin themselves; demoting an
434    // employee while zero admins exist is a different problem and not this
435    // check's business.
436    let is_admin: Option<bool> = sqlx::query_scalar("SELECT (role = 'admin' AND active) FROM users WHERE id = $1")
437        .bind(target)
438        .fetch_optional(pool)
439        .await?;
440
441    Ok(is_admin.unwrap_or(false) && others == 0)
442}
443
444#[cfg(test)]
445mod tests {
446    use super::*;
447
448    #[test]
449    fn a_token_is_long_random_and_recognisable() {
450        let token = generate_token();
451        assert!(token.starts_with("kasl_"), "a token in a log should be identifiable: {token}");
452        assert_eq!(token.len(), 5 + 64, "32 bytes as hex");
453        assert_ne!(token, generate_token(), "two tokens must never be the same");
454    }
455
456    #[test]
457    fn a_short_password_is_refused_before_it_is_hashed() {
458        let error = hash_new_password("short").expect_err("seven characters is not a password");
459        assert!(error.to_string().contains("at least 8"), "{error}");
460        assert!(hash_new_password("just long enough").is_ok());
461    }
462
463    #[test]
464    fn the_email_check_admits_addresses_and_refuses_obvious_mistakes() {
465        for good in ["a@b.co", "first.last@example.com", "kirill+kasl@example.co.uk"] {
466            assert!(looks_like_an_email(good), "{good} should be accepted");
467        }
468        // What an admin actually mistypes: a name, a missing domain, a stray
469        // trailing dot from a copied sentence.
470        for bad in ["kirill", "kirill@", "@example.com", "kirill@example", "kirill@example.com."] {
471            assert!(!looks_like_an_email(bad), "{bad} should be refused");
472        }
473    }
474
475    #[test]
476    fn a_manager_reads_and_an_employee_does_not() {
477        let user = |role| CurrentUser {
478            session_id: Uuid::nil(),
479            user_id: Uuid::nil(),
480            role,
481        };
482        assert!(require_manager_or_admin(&user(UserRole::Admin)).is_ok());
483        assert!(require_manager_or_admin(&user(UserRole::Manager)).is_ok());
484        assert!(require_manager_or_admin(&user(UserRole::Employee)).is_err());
485
486        // And reading is all a manager gets in this version.
487        assert!(user(UserRole::Manager).require_admin().is_err());
488    }
489
490    #[test]
491    fn an_absent_patch_field_means_leave_it_alone() {
492        // `coalesce($n, column)` in the UPDATE relies on this: a field the admin
493        // did not send must arrive as None, not as a default that clears it.
494        let patch: UserPatch = serde_json::from_value(serde_json::json!({"display_name": "Kirill"})).unwrap();
495        assert_eq!(patch.display_name.as_deref(), Some("Kirill"));
496        assert!(patch.role.is_none() && patch.active.is_none() && patch.password.is_none());
497    }
498
499    #[test]
500    fn a_new_user_defaults_to_the_least_authority() {
501        let new: NewUser = serde_json::from_value(serde_json::json!({"email": "a@b.co"})).unwrap();
502        assert_eq!(new.role, UserRole::Employee, "a role must be asked for, never assumed");
503        assert!(new.password.is_none(), "an account for an agent needs no password");
504    }
505}