Skip to main content

brep_plm/api/
accounts.rs

1//! Sign-in, user administration and part types.
2//!
3//! Part types live here rather than with parts because they are an
4//! ADMINISTRATIVE object: they define the numbering scheme an operator
5//! configures once, and creating one is not part of designing anything.
6
7use std::net::SocketAddr;
8
9use axum::extract::{ConnectInfo, Path, State};
10use axum::http::{header, HeaderMap, StatusCode};
11use axum::response::{IntoResponse, Response};
12use axum::Json;
13use serde::{Deserialize, Serialize};
14
15use super::{ok_seq, require_admin, require_user, Shared};
16use crate::db::now;
17use crate::model::{groups, NumberMode, PartType, Session, User};
18use crate::security::ThrottleKind;
19use crate::{auth, Error};
20
21/// A user as the API reports them — never with the password verifier.
22#[derive(Debug, Serialize)]
23pub struct PublicUser {
24    pub id: String,
25    pub username: String,
26    pub display_name: String,
27    pub email: String,
28    pub groups: Vec<String>,
29    pub active: bool,
30    pub created_at: u64,
31    /// What this account may do, resolved by the server so the page does not
32    /// re-implement the group rules and drift from them.
33    pub can_author: bool,
34    pub can_checkin: bool,
35    pub is_admin: bool,
36    pub can_bake: bool,
37    /// The session's CSRF token, on `/api/login` and `/api/me` only: the page
38    /// sends it back in `X-CSRF-Token` with every change.
39    #[serde(skip_serializing_if = "Option::is_none")]
40    pub csrf: Option<String>,
41    /// How this request signed in: `session` or `token`, on `/api/me` only.
42    #[serde(skip_serializing_if = "Option::is_none")]
43    pub via: Option<&'static str>,
44    /// The version handshake, on `/api/me` only ([`crate::version`]): this
45    /// server's version and the oldest CAD app it serves. The app refuses to
46    /// connect when its own version is older than `min_client_version`.
47    #[serde(skip_serializing_if = "Option::is_none")]
48    pub server_version: Option<&'static str>,
49    #[serde(skip_serializing_if = "Option::is_none")]
50    pub min_client_version: Option<String>,
51    /// What this server can do, by name ([`crate::version::FEATURES`]).
52    #[serde(skip_serializing_if = "Option::is_none")]
53    pub features: Option<&'static [&'static str]>,
54}
55
56impl From<&User> for PublicUser {
57    fn from(user: &User) -> Self {
58        Self {
59            id: user.id.clone(),
60            username: user.username.clone(),
61            display_name: user.display_name.clone(),
62            email: user.email.clone(),
63            groups: user.groups.clone(),
64            active: user.active,
65            created_at: user.created_at,
66            can_author: user.can_author(),
67            can_checkin: user.can_checkin(),
68            is_admin: user.is_admin(),
69            can_bake: user.can_bake(),
70            csrf: None,
71            via: None,
72            server_version: None,
73            min_client_version: None,
74            features: None,
75        }
76    }
77}
78
79#[derive(Debug, Deserialize)]
80pub struct Credentials {
81    pub username: String,
82    pub password: String,
83}
84
85/// Sign in. A wrong username and a wrong password answer identically — the
86/// difference would tell an attacker which half to keep working on.
87///
88/// Failures are counted per username and per client address
89/// ([`crate::security::Throttle`]). A locked-out key is refused with `429`
90/// BEFORE the password is checked, so guessing during a lockout learns
91/// nothing; the refusal names neither which key is locked nor whether the
92/// account exists.
93pub async fn login(
94    State(db): State<Shared>,
95    headers: HeaderMap,
96    peer: Option<ConnectInfo<SocketAddr>>,
97    Json(body): Json<Credentials>,
98) -> Result<Response, Error> {
99    let security = db.security();
100    let ip = security.config.client_ip(&headers, peer.map(|ConnectInfo(addr)| addr.ip()));
101    let ip_key = ip.map(|ip| ip.to_string());
102    let username = body.username.trim().to_ascii_lowercase();
103    let t = now();
104    let locked = security
105        .throttle
106        .locked_for(ThrottleKind::User, &username, t)
107        .into_iter()
108        .chain(ip_key.as_deref().and_then(|ip| security.throttle.locked_for(ThrottleKind::Ip, ip, t)))
109        .max();
110    let failed = |db: &crate::db::Db, user_id: &str, reason: &str| {
111        let who = crate::model::EntityRef {
112            kind: "user".into(),
113            id: user_id.to_string(),
114            label: body.username.trim().to_string(),
115            part_id: String::new(),
116        };
117        db.record("sign-in-failed", who, reason);
118    };
119    if let Some(seconds) = locked {
120        failed(&db, "", "locked out by the sign-in throttle");
121        return Err(Error::too_many(format!(
122            "too many failed sign-ins — try again in {seconds} s, or ask an administrator to clear the lockout"
123        )));
124    }
125
126    let found = db.read(|state| state.user_by_name(&body.username).cloned());
127    let refusal = || {
128        security.throttle.fail(ThrottleKind::User, &username, t);
129        if let Some(ip) = &ip_key {
130            security.throttle.fail(ThrottleKind::Ip, ip, t);
131        }
132        Error::unauthorized("wrong username or password")
133    };
134
135    let user = match found {
136        Some(user) if auth::verify_password(&body.password, &user.password) => user,
137        Some(user) => {
138            failed(&db, &user.id, "wrong password");
139            return Err(refusal());
140        }
141        None => {
142            failed(&db, "", "no such username");
143            // Spend the same work on an unknown user as on a known one, so the
144            // response time does not reveal which it was.
145            static DECOY: std::sync::OnceLock<String> = std::sync::OnceLock::new();
146            let decoy = DECOY.get_or_init(|| auth::hash_password("decoy"));
147            let _ = auth::verify_password(&body.password, decoy);
148            return Err(refusal());
149        }
150    };
151    if !user.active {
152        failed(&db, &user.id, "the account is disabled");
153        return Err(Error::forbidden("this account is disabled"));
154    }
155    security.throttle.clear(ThrottleKind::User, &username);
156
157    let token = auth::random_token(32);
158    let csrf = auth::random_token(32);
159    let session = Session {
160        token: token.clone(),
161        user_id: user.id.clone(),
162        created_at: now(),
163        last_seen: now(),
164        csrf: csrf.clone(),
165    };
166    // The new session is logged as a sign-in BY this user: until now the
167    // request had no one signed in.
168    let actor = crate::model::Actor {
169        user_id: user.id.clone(),
170        username: user.username.clone(),
171        via: "session".into(),
172        ..crate::audit::current_actor()
173    };
174    crate::audit::as_actor(actor, || {
175        db.mutate(move |state| {
176            state.sessions.push(session);
177            Ok(())
178        })
179    })?;
180    // Sessions nobody can use any more go as someone signs in, so the list
181    // never grows past the ones that could still be used.
182    if let Err(error) = db.prune_sessions() {
183        eprintln!("brep-plm: could not remove expired sessions: {}", error.message);
184    }
185
186    let cookie = super::session_cookie(&db, &headers, &token);
187    let mut public = PublicUser::from(&user);
188    public.csrf = Some(csrf);
189    Ok((StatusCode::OK, [(header::SET_COOKIE, cookie)], Json(public)).into_response())
190}
191
192pub async fn logout(State(db): State<Shared>, headers: HeaderMap) -> Result<Response, Error> {
193    if let Some(token) = super::session_token(&headers) {
194        db.mutate(move |state| {
195            state.sessions.retain(|s| s.token != token);
196            Ok(())
197        })?;
198    }
199    let cookie = super::clear_cookie(&db, &headers);
200    Ok((StatusCode::OK, [(header::SET_COOKIE, cookie)], Json(serde_json::json!({"ok": true})))
201        .into_response())
202}
203
204/// Who am I, and what may I do. For a browser this also hands out the
205/// session's CSRF token, issuing one for a session from before hardening.
206pub async fn me(State(db): State<Shared>, headers: HeaderMap) -> Result<Json<PublicUser>, Error> {
207    let identity = super::identify(&db, &headers)?;
208    let mut public = PublicUser::from(&identity.user);
209    public.server_version = Some(crate::version::SERVER_VERSION);
210    public.min_client_version = Some(db.security().config.min_client_version().to_string());
211    public.features = Some(crate::version::FEATURES);
212    if let Some(token) = identity.session {
213        let csrf = db.mutate(move |state| {
214            let session = state
215                .sessions
216                .iter_mut()
217                .find(|s| s.token == token)
218                .ok_or_else(|| Error::unauthorized("session has expired"))?;
219            if session.csrf.is_empty() {
220                session.csrf = auth::random_token(32);
221            }
222            Ok(session.csrf.clone())
223        })?;
224        public.csrf = Some(csrf);
225        public.via = Some("session");
226    } else {
227        public.via = Some("token");
228    }
229    Ok(Json(public))
230}
231
232// ===========================================================================
233// Users
234// ===========================================================================
235
236pub async fn list_users(
237    State(db): State<Shared>,
238    headers: HeaderMap,
239) -> Result<Json<Vec<PublicUser>>, Error> {
240    require_admin(&db, &headers)?;
241    Ok(Json(db.read(|state| {
242        state.users.iter().map(PublicUser::from).collect()
243    })))
244}
245
246#[derive(Debug, Deserialize)]
247pub struct NewUser {
248    pub username: String,
249    pub password: String,
250    #[serde(default)]
251    pub display_name: String,
252    #[serde(default)]
253    pub email: String,
254    #[serde(default)]
255    pub groups: Vec<String>,
256}
257
258pub async fn create_user(
259    State(db): State<Shared>,
260    headers: HeaderMap,
261    Json(body): Json<NewUser>,
262) -> Result<Response, Error> {
263    require_admin(&db, &headers)?;
264    let username = body.username.trim().to_string();
265    if username.is_empty() {
266        return Err(Error::bad_request("a user needs a username"));
267    }
268    if body.password.len() < 8 {
269        return Err(Error::bad_request("a password needs at least 8 characters"));
270    }
271    let user = User {
272        id: auth::new_id(),
273        username,
274        display_name: body.display_name.trim().to_string(),
275        email: body.email.trim().to_string(),
276        password: auth::hash_password(&body.password),
277        groups: normalize_groups(body.groups),
278        active: true,
279        created_at: now(),
280    };
281    db.mutate(move |state| {
282        if state.user_by_name(&user.username).is_some() {
283            return Err(Error::conflict(format!(
284                "username '{}' is taken",
285                user.username
286            )));
287        }
288        state.users.push(user);
289        Ok(())
290    })?;
291    Ok(ok_seq(&db))
292}
293
294#[derive(Debug, Deserialize)]
295pub struct UserPatch {
296    pub display_name: Option<String>,
297    pub email: Option<String>,
298    pub groups: Option<Vec<String>>,
299    pub active: Option<bool>,
300    pub password: Option<String>,
301}
302
303pub async fn update_user(
304    State(db): State<Shared>,
305    headers: HeaderMap,
306    Path(id): Path<String>,
307    Json(body): Json<UserPatch>,
308) -> Result<Response, Error> {
309    let actor = require_admin(&db, &headers)?;
310    if let Some(password) = &body.password {
311        if password.len() < 8 {
312            return Err(Error::bad_request("a password needs at least 8 characters"));
313        }
314    }
315    let mut reset_for: Option<String> = None;
316    let reset = &mut reset_for;
317    db.mutate(move |state| {
318        let reset_for = reset;
319        // Locking yourself out of the only admin account is unrecoverable
320        // without editing the file by hand, so it is refused rather than
321        // warned about.
322        let losing_admin = body.active == Some(false)
323            || body
324                .groups
325                .as_ref()
326                .is_some_and(|g| !g.iter().any(|name| name == groups::ADMIN));
327        if id == actor.id && losing_admin {
328            return Err(Error::conflict(
329                "an administrator cannot remove their own admin access".to_string(),
330            ));
331        }
332        let user = state
333            .users
334            .iter_mut()
335            .find(|u| u.id == id)
336            .ok_or_else(|| Error::not_found("user"))?;
337        if let Some(name) = body.display_name {
338            user.display_name = name.trim().to_string();
339        }
340        if let Some(email) = body.email {
341            user.email = email.trim().to_string();
342        }
343        if let Some(list) = body.groups {
344            user.groups = normalize_groups(list);
345        }
346        if let Some(active) = body.active {
347            user.active = active;
348        }
349        if let Some(password) = body.password {
350            user.password = auth::hash_password(&password);
351            *reset_for = Some(user.username.clone());
352            // A password change ends every other session of that account.
353            let user_id = user.id.clone();
354            state.sessions.retain(|s| s.user_id != user_id);
355        }
356        Ok(())
357    })?;
358    // A reset password is a fresh start for that account's sign-in throttle.
359    if let Some(username) = reset_for {
360        db.security().throttle.clear(ThrottleKind::User, &username);
361    }
362    Ok(ok_seq(&db))
363}
364
365/// Trim, lower-case, drop blanks and duplicates. Group names are compared
366/// exactly everywhere else, so they are normalized exactly once — here.
367fn normalize_groups(list: Vec<String>) -> Vec<String> {
368    let mut out: Vec<String> = Vec::new();
369    for name in list {
370        let name = name.trim().to_ascii_lowercase();
371        if !name.is_empty() && !out.contains(&name) {
372            out.push(name);
373        }
374    }
375    out
376}
377
378// ===========================================================================
379// Part types — the numbering schemes
380// ===========================================================================
381
382pub async fn list_part_types(
383    State(db): State<Shared>,
384    headers: HeaderMap,
385) -> Result<Json<Vec<PartTypeView>>, Error> {
386    require_user(&db, &headers)?;
387    Ok(Json(db.read(|state| {
388        state.part_types.iter().map(PartTypeView::from).collect()
389    })))
390}
391
392/// A part type plus what its NEXT number would look like — the page shows it
393/// so an operator can see the scheme before committing to it.
394#[derive(Debug, Serialize)]
395pub struct PartTypeView {
396    pub id: String,
397    pub name: String,
398    pub prefix: String,
399    pub digits: u32,
400    pub next: u64,
401    /// What the counter would hand out next. Meaningful only in counter mode;
402    /// the page shows it only then.
403    pub next_number: String,
404    pub capacity: u64,
405    pub mode: NumberMode,
406}
407
408impl From<&PartType> for PartTypeView {
409    fn from(kind: &PartType) -> Self {
410        Self {
411            id: kind.id.clone(),
412            name: kind.name.clone(),
413            prefix: kind.prefix.clone(),
414            digits: kind.digits,
415            next: kind.next,
416            next_number: kind.format_number(kind.next),
417            capacity: kind.capacity(),
418            mode: kind.mode.clone(),
419        }
420    }
421}
422
423#[derive(Debug, Deserialize)]
424pub struct NewPartType {
425    pub id: String,
426    pub name: String,
427    /// Counter mode only; the other modes keep it for a later switch back.
428    #[serde(default)]
429    pub prefix: String,
430    #[serde(default = "nine")]
431    pub digits: u32,
432    #[serde(default)]
433    pub start: Option<u64>,
434    /// `{ "kind": "counter" | "free" | "pattern" | "script", ... }`. Absent is
435    /// a counter, as every type was before modes existed.
436    #[serde(default)]
437    pub mode: NumberMode,
438}
439
440fn nine() -> u32 {
441    9
442}
443
444/// A mode an administrator may save: a pattern that compiles, a script path
445/// inside the scripts directory. The script file need not exist yet — a part
446/// created before it does is refused with a message naming it.
447fn check_mode(db: &crate::db::Db, mode: &NumberMode) -> Result<(), Error> {
448    match mode {
449        NumberMode::Counter | NumberMode::Free => Ok(()),
450        NumberMode::Pattern { regex } => {
451            if regex.trim().is_empty() {
452                return Err(Error::bad_request("a pattern type needs a pattern"));
453            }
454            crate::db::full_match(regex).map(|_| ())
455        }
456        NumberMode::Script { script } => db.scripts().resolve(script).map(|_| ()),
457    }
458}
459
460/// Two COUNTER types sharing a prefix can mint the same string. (Any clash
461/// that still happens — a typed number landing in a counter's range — is
462/// caught by the store's one-number-one-part check.)
463fn prefix_clash<'a>(state: &'a crate::db::State, kind: &PartType) -> Option<&'a PartType> {
464    if kind.mode != NumberMode::Counter {
465        return None;
466    }
467    state.part_types.iter().find(|t| {
468        t.id != kind.id && t.mode == NumberMode::Counter && t.prefix.eq_ignore_ascii_case(&kind.prefix)
469    })
470}
471
472pub async fn create_part_type(
473    State(db): State<Shared>,
474    headers: HeaderMap,
475    Json(body): Json<NewPartType>,
476) -> Result<Response, Error> {
477    require_admin(&db, &headers)?;
478    let id = body.id.trim().to_ascii_lowercase();
479    if id.is_empty() || !id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') {
480        return Err(Error::bad_request(
481            "a part type id is letters, digits, '-' and '_'",
482        ));
483    }
484    // 18 digits is where u64 stops being able to count the sequence; 1 is the
485    // smallest scheme that can spell anything at all.
486    if !(1..=18).contains(&body.digits) {
487        return Err(Error::bad_request("digits must be between 1 and 18"));
488    }
489    let kind = PartType {
490        id,
491        name: body.name.trim().to_string(),
492        prefix: body.prefix.trim().to_string(),
493        digits: body.digits,
494        next: body.start.unwrap_or(1).max(1),
495        created_at: now(),
496        mode: body.mode,
497    };
498    check_mode(&db, &kind.mode)?;
499    if kind.name.is_empty() {
500        return Err(Error::bad_request("a part type needs a name"));
501    }
502    if kind.next > kind.capacity() {
503        return Err(Error::bad_request(format!(
504            "a start of {} does not fit in {} digits",
505            kind.next, kind.digits
506        )));
507    }
508    db.mutate(move |state| {
509        if state.part_type(&kind.id).is_some() {
510            return Err(Error::conflict(format!("part type '{}' exists", kind.id)));
511        }
512        if let Some(clash) = prefix_clash(state, &kind) {
513            return Err(Error::conflict(format!(
514                "prefix '{}' is already used by part type '{}'",
515                kind.prefix, clash.id
516            )));
517        }
518        state.part_types.push(kind);
519        Ok(())
520    })?;
521    Ok(ok_seq(&db))
522}
523
524#[derive(Debug, Deserialize)]
525pub struct PartTypeChange {
526    #[serde(default)]
527    pub name: Option<String>,
528    #[serde(default)]
529    pub mode: Option<NumberMode>,
530}
531
532/// Rename a part type or change how it numbers. Parts already numbered keep
533/// their numbers; the change applies to the next part created.
534pub async fn update_part_type(
535    State(db): State<Shared>,
536    headers: HeaderMap,
537    Path(id): Path<String>,
538    Json(body): Json<PartTypeChange>,
539) -> Result<Response, Error> {
540    require_admin(&db, &headers)?;
541    if let Some(mode) = &body.mode {
542        check_mode(&db, mode)?;
543    }
544    db.mutate(move |state| {
545        let index = state
546            .part_types
547            .iter()
548            .position(|t| t.id == id)
549            .ok_or_else(|| Error::not_found("part type"))?;
550        let mut kind = state.part_types[index].clone();
551        if let Some(name) = body.name {
552            let name = name.trim().to_string();
553            if name.is_empty() {
554                return Err(Error::bad_request("a part type needs a name"));
555            }
556            kind.name = name;
557        }
558        if let Some(mode) = body.mode {
559            kind.mode = mode;
560        }
561        if let Some(clash) = prefix_clash(state, &kind) {
562            return Err(Error::conflict(format!(
563                "prefix '{}' is already used by counter type '{}'",
564                kind.prefix, clash.id
565            )));
566        }
567        state.part_types[index] = kind;
568        Ok(())
569    })?;
570    Ok(ok_seq(&db))
571}