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.
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            Ok(session.csrf.clone())
220        })?;
221        public.csrf = Some(csrf);
222        public.via = Some("session");
223    } else {
224        public.via = Some("token");
225    }
226    Ok(Json(public))
227}
228
229// ===========================================================================
230// Users
231// ===========================================================================
232
233pub async fn list_users(
234    State(db): State<Shared>,
235    headers: HeaderMap,
236) -> Result<Json<Vec<PublicUser>>, Error> {
237    require_admin(&db, &headers)?;
238    Ok(Json(db.read(|state| {
239        state.users.iter().map(PublicUser::from).collect()
240    })))
241}
242
243#[derive(Debug, Deserialize)]
244pub struct NewUser {
245    pub username: String,
246    pub password: String,
247    #[serde(default)]
248    pub display_name: String,
249    #[serde(default)]
250    pub email: String,
251    #[serde(default)]
252    pub groups: Vec<String>,
253}
254
255pub async fn create_user(
256    State(db): State<Shared>,
257    headers: HeaderMap,
258    Json(body): Json<NewUser>,
259) -> Result<Response, Error> {
260    require_admin(&db, &headers)?;
261    let username = body.username.trim().to_string();
262    if username.is_empty() {
263        return Err(Error::bad_request("a user needs a username"));
264    }
265    if body.password.len() < 8 {
266        return Err(Error::bad_request("a password needs at least 8 characters"));
267    }
268    let user = User {
269        id: auth::new_id(),
270        username,
271        display_name: body.display_name.trim().to_string(),
272        email: body.email.trim().to_string(),
273        password: auth::hash_password(&body.password),
274        groups: normalize_groups(body.groups),
275        active: true,
276        created_at: now(),
277    };
278    db.mutate(move |state| {
279        if state.user_by_name(&user.username).is_some() {
280            return Err(Error::conflict(format!(
281                "username '{}' is taken",
282                user.username
283            )));
284        }
285        state.users.push(user);
286        Ok(())
287    })?;
288    Ok(ok_seq(&db))
289}
290
291#[derive(Debug, Deserialize)]
292pub struct UserPatch {
293    pub display_name: Option<String>,
294    pub email: Option<String>,
295    pub groups: Option<Vec<String>>,
296    pub active: Option<bool>,
297    pub password: Option<String>,
298}
299
300pub async fn update_user(
301    State(db): State<Shared>,
302    headers: HeaderMap,
303    Path(id): Path<String>,
304    Json(body): Json<UserPatch>,
305) -> Result<Response, Error> {
306    let actor = require_admin(&db, &headers)?;
307    if let Some(password) = &body.password {
308        if password.len() < 8 {
309            return Err(Error::bad_request("a password needs at least 8 characters"));
310        }
311    }
312    let mut reset_for: Option<String> = None;
313    let reset = &mut reset_for;
314    db.mutate(move |state| {
315        let reset_for = reset;
316        // Locking yourself out of the only admin account is unrecoverable
317        // without editing the file by hand, so it is refused rather than
318        // warned about.
319        let losing_admin = body.active == Some(false)
320            || body
321                .groups
322                .as_ref()
323                .is_some_and(|g| !g.iter().any(|name| name == groups::ADMIN));
324        if id == actor.id && losing_admin {
325            return Err(Error::conflict(
326                "an administrator cannot remove their own admin access".to_string(),
327            ));
328        }
329        let user = state
330            .users
331            .iter_mut()
332            .find(|u| u.id == id)
333            .ok_or_else(|| Error::not_found("user"))?;
334        if let Some(name) = body.display_name {
335            user.display_name = name.trim().to_string();
336        }
337        if let Some(email) = body.email {
338            user.email = email.trim().to_string();
339        }
340        if let Some(list) = body.groups {
341            user.groups = normalize_groups(list);
342        }
343        if let Some(active) = body.active {
344            user.active = active;
345        }
346        if let Some(password) = body.password {
347            user.password = auth::hash_password(&password);
348            *reset_for = Some(user.username.clone());
349            // A password change ends every other session of that account.
350            let user_id = user.id.clone();
351            state.sessions.retain(|s| s.user_id != user_id);
352        }
353        Ok(())
354    })?;
355    // A reset password is a fresh start for that account's sign-in throttle.
356    if let Some(username) = reset_for {
357        db.security().throttle.clear(ThrottleKind::User, &username);
358    }
359    Ok(ok_seq(&db))
360}
361
362/// Trim, lower-case, drop blanks and duplicates. Group names are compared
363/// exactly everywhere else, so they are normalized exactly once — here.
364fn normalize_groups(list: Vec<String>) -> Vec<String> {
365    let mut out: Vec<String> = Vec::new();
366    for name in list {
367        let name = name.trim().to_ascii_lowercase();
368        if !name.is_empty() && !out.contains(&name) {
369            out.push(name);
370        }
371    }
372    out
373}
374
375// ===========================================================================
376// Part types — the numbering schemes
377// ===========================================================================
378
379pub async fn list_part_types(
380    State(db): State<Shared>,
381    headers: HeaderMap,
382) -> Result<Json<Vec<PartTypeView>>, Error> {
383    require_user(&db, &headers)?;
384    Ok(Json(db.read(|state| {
385        state.part_types.iter().map(PartTypeView::from).collect()
386    })))
387}
388
389/// A part type plus what its NEXT number would look like — the page shows it
390/// so an operator can see the scheme before committing to it.
391#[derive(Debug, Serialize)]
392pub struct PartTypeView {
393    pub id: String,
394    pub name: String,
395    pub prefix: String,
396    pub digits: u32,
397    pub next: u64,
398    /// What the counter would hand out next. Meaningful only in counter mode;
399    /// the page shows it only then.
400    pub next_number: String,
401    pub capacity: u64,
402    pub mode: NumberMode,
403}
404
405impl From<&PartType> for PartTypeView {
406    fn from(kind: &PartType) -> Self {
407        Self {
408            id: kind.id.clone(),
409            name: kind.name.clone(),
410            prefix: kind.prefix.clone(),
411            digits: kind.digits,
412            next: kind.next,
413            next_number: kind.format_number(kind.next),
414            capacity: kind.capacity(),
415            mode: kind.mode.clone(),
416        }
417    }
418}
419
420#[derive(Debug, Deserialize)]
421pub struct NewPartType {
422    pub id: String,
423    pub name: String,
424    /// Counter mode only; the other modes keep it for a later switch back.
425    #[serde(default)]
426    pub prefix: String,
427    #[serde(default = "nine")]
428    pub digits: u32,
429    #[serde(default)]
430    pub start: Option<u64>,
431    /// `{ "kind": "counter" | "free" | "pattern" | "script", ... }`. Absent is
432    /// a counter, as every type was before modes existed.
433    #[serde(default)]
434    pub mode: NumberMode,
435}
436
437fn nine() -> u32 {
438    9
439}
440
441/// A mode an administrator may save: a pattern that compiles, a script path
442/// inside the scripts directory. The script file need not exist yet — a part
443/// created before it does is refused with a message naming it.
444fn check_mode(db: &crate::db::Db, mode: &NumberMode) -> Result<(), Error> {
445    match mode {
446        NumberMode::Counter | NumberMode::Free => Ok(()),
447        NumberMode::Pattern { regex } => {
448            if regex.trim().is_empty() {
449                return Err(Error::bad_request("a pattern type needs a pattern"));
450            }
451            crate::db::full_match(regex).map(|_| ())
452        }
453        NumberMode::Script { script } => db.scripts().resolve(script).map(|_| ()),
454    }
455}
456
457/// Two COUNTER types sharing a prefix can mint the same string. (Any clash
458/// that still happens — a typed number landing in a counter's range — is
459/// caught by the store's one-number-one-part check.)
460fn prefix_clash<'a>(state: &'a crate::db::State, kind: &PartType) -> Option<&'a PartType> {
461    if kind.mode != NumberMode::Counter {
462        return None;
463    }
464    state.part_types.iter().find(|t| {
465        t.id != kind.id && t.mode == NumberMode::Counter && t.prefix.eq_ignore_ascii_case(&kind.prefix)
466    })
467}
468
469pub async fn create_part_type(
470    State(db): State<Shared>,
471    headers: HeaderMap,
472    Json(body): Json<NewPartType>,
473) -> Result<Response, Error> {
474    require_admin(&db, &headers)?;
475    let id = body.id.trim().to_ascii_lowercase();
476    if id.is_empty() || !id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') {
477        return Err(Error::bad_request(
478            "a part type id is letters, digits, '-' and '_'",
479        ));
480    }
481    // 18 digits is where u64 stops being able to count the sequence; 1 is the
482    // smallest scheme that can spell anything at all.
483    if !(1..=18).contains(&body.digits) {
484        return Err(Error::bad_request("digits must be between 1 and 18"));
485    }
486    let kind = PartType {
487        id,
488        name: body.name.trim().to_string(),
489        prefix: body.prefix.trim().to_string(),
490        digits: body.digits,
491        next: body.start.unwrap_or(1).max(1),
492        created_at: now(),
493        mode: body.mode,
494    };
495    check_mode(&db, &kind.mode)?;
496    if kind.name.is_empty() {
497        return Err(Error::bad_request("a part type needs a name"));
498    }
499    if kind.next > kind.capacity() {
500        return Err(Error::bad_request(format!(
501            "a start of {} does not fit in {} digits",
502            kind.next, kind.digits
503        )));
504    }
505    db.mutate(move |state| {
506        if state.part_type(&kind.id).is_some() {
507            return Err(Error::conflict(format!("part type '{}' exists", kind.id)));
508        }
509        if let Some(clash) = prefix_clash(state, &kind) {
510            return Err(Error::conflict(format!(
511                "prefix '{}' is already used by part type '{}'",
512                kind.prefix, clash.id
513            )));
514        }
515        state.part_types.push(kind);
516        Ok(())
517    })?;
518    Ok(ok_seq(&db))
519}
520
521#[derive(Debug, Deserialize)]
522pub struct PartTypeChange {
523    #[serde(default)]
524    pub name: Option<String>,
525    #[serde(default)]
526    pub mode: Option<NumberMode>,
527}
528
529/// Rename a part type or change how it numbers. Parts already numbered keep
530/// their numbers; the change applies to the next part created.
531pub async fn update_part_type(
532    State(db): State<Shared>,
533    headers: HeaderMap,
534    Path(id): Path<String>,
535    Json(body): Json<PartTypeChange>,
536) -> Result<Response, Error> {
537    require_admin(&db, &headers)?;
538    if let Some(mode) = &body.mode {
539        check_mode(&db, mode)?;
540    }
541    db.mutate(move |state| {
542        let index = state
543            .part_types
544            .iter()
545            .position(|t| t.id == id)
546            .ok_or_else(|| Error::not_found("part type"))?;
547        let mut kind = state.part_types[index].clone();
548        if let Some(name) = body.name {
549            let name = name.trim().to_string();
550            if name.is_empty() {
551                return Err(Error::bad_request("a part type needs a name"));
552            }
553            kind.name = name;
554        }
555        if let Some(mode) = body.mode {
556            kind.mode = mode;
557        }
558        if let Some(clash) = prefix_clash(state, &kind) {
559            return Err(Error::conflict(format!(
560                "prefix '{}' is already used by counter type '{}'",
561                kind.prefix, clash.id
562            )));
563        }
564        state.part_types[index] = kind;
565        Ok(())
566    })?;
567    Ok(ok_seq(&db))
568}