Skip to main content

brep_plm/api/
mod.rs

1//! The HTTP surface: the router, the session cookie, and the helpers every
2//! handler shares.
3//!
4//! Two families of route live here and they answer different callers:
5//!
6//! * `/api/...` — the PLM itself: accounts, part types, the catalog, parts,
7//!   revisions, uses lists, BOMs and where-used, families and templates,
8//!   the bake queue, sourcing and settings.
9//!   The browser page in `web/` is its only client today.
10//! * `/api/store/...` — the DOCUMENT surface, shaped to what the CAD app's
11//!   `StoreBackend` needs from a remote backend (see [`store`]).
12//!
13//! Every handler that changes anything returns the new `seq`, so a client
14//! never has to ask a second question to find out whether its cache is stale.
15
16pub mod accounts;
17pub mod attachments;
18pub mod audit_log;
19pub mod backups;
20pub mod bake_worker;
21pub mod bom;
22mod bom_config;
23mod frontend;
24pub mod cad;
25pub mod catalog;
26pub mod family;
27pub mod parts;
28pub mod preferences;
29pub mod review;
30pub mod scripts;
31pub mod credentials;
32pub mod settings;
33pub mod setup;
34pub mod workflow;
35pub mod thumbnails;
36pub mod sourcing;
37pub mod store;
38pub mod workspace;
39pub mod native_import;
40
41use std::sync::Arc;
42
43use std::net::SocketAddr;
44
45use axum::extract::{ConnectInfo, Request, State};
46use axum::http::{header, HeaderMap, Method, StatusCode};
47use axum::middleware::Next;
48use axum::response::{IntoResponse, Response};
49use axum::routing::{delete, get, patch, post, put};
50use axum::Router;
51
52use crate::db::{self, Db};
53use crate::audit;
54use crate::model::{Actor, TokenScope, User};
55use crate::security::{self, Credential};
56use crate::Error;
57
58/// The cookie the browser session rides in.
59pub const SESSION_COOKIE: &str = "plm_session";
60
61/// The header a browser request that changes anything carries its session's
62/// CSRF token in ([`crate::security`]).
63pub const CSRF_HEADER: &str = "x-csrf-token";
64
65/// Shared handler state.
66pub type Shared = Arc<Db>;
67
68/// Build the whole router.
69pub fn router(db: Shared) -> Router {
70    Router::new()
71        // -- the page ------------------------------------------------------
72        .route("/", get(frontend::index))
73        .route("/*path", get(frontend::file))
74        // -- the hosted CAD app and the server describing itself -----------
75        .route("/cad", get(cad::entry))
76        .route("/cad/", get(cad::entry))
77        .route("/cad/app", get(cad::entry))
78        .route("/cad/app/", get(cad::entry))
79        .route("/cad/app/*path", get(cad::file))
80        .route("/cad/config", get(cad::config))
81        .route("/api/setup/import", post(setup::import))
82        .route("/api/setup/kicad-libraries", get(setup::kicad_libraries))
83        .route("/api/setup/kicad-part-type", post(setup::kicad_part_type))
84        .route("/api/setup/kicad-taxonomy", post(setup::kicad_taxonomy))
85        .route("/api/workflows", get(workflow::definitions).post(workflow::save))
86        .route("/api/workflow-runs", get(workflow::runs).post(workflow::start))
87        .route("/api/workflow-runs/:id", get(workflow::detail))
88        .route("/api/workflow-runs/:id/actions", post(workflow::act))
89        .route("/api/workflow-runs/:id/control", post(workflow::control))
90        // -- accounts ------------------------------------------------------
91        .route("/api/login", post(accounts::login))
92        .route("/api/logout", post(accounts::logout))
93        .route("/api/me", get(accounts::me))
94        .route("/api/me/preferences", get(preferences::list))
95        .route(
96            "/api/me/preferences/:key",
97            get(preferences::read).put(preferences::write).delete(preferences::remove),
98        )
99        .route("/api/users", get(accounts::list_users).post(accounts::create_user))
100        .route("/api/users/:id", patch(accounts::update_user))
101        .route("/api/users/:id/sign-out", post(credentials::sign_out_user))
102        // -- credentials ---------------------------------------------------
103        .route("/api/me/password", post(credentials::change_password))
104        .route("/api/logout-all", post(credentials::logout_all))
105        .route("/api/tokens", get(credentials::list_tokens).post(credentials::create_token))
106        .route("/api/tokens/:id", delete(credentials::revoke_token))
107        .route(
108            "/api/security/lockouts",
109            get(credentials::list_lockouts).delete(credentials::clear_lockouts),
110        )
111        .route(
112            "/api/part-types",
113            get(accounts::list_part_types).post(accounts::create_part_type),
114        )
115        .route("/api/part-types/:id", patch(accounts::update_part_type))
116        .route("/api/part-types/:id/fields", get(bom_config::type_fields).put(bom_config::set_type_fields))
117        .route("/api/bom/configuration", get(bom_config::configuration))
118        .route("/api/bom/occurrence-fields", axum::routing::put(bom_config::set_occurrence_fields))
119        .route("/api/bom/layouts", post(bom_config::save_layout))
120        .route("/api/bom/layouts/:id", delete(bom_config::delete_layout))
121        .route("/api/bom/selection", axum::routing::put(bom_config::select_layout))
122        .route("/api/parts/:id/revisions/:rev/attributes", get(bom_config::revision_attributes).patch(bom_config::patch_revision_attributes))
123        .route("/api/parts/:id/revisions/:rev/occurrences", patch(bom_config::patch_occurrences))
124        // -- parts and revisions -------------------------------------------
125        .route("/api/parts", get(parts::list_parts).post(parts::create_part))
126        .route("/api/parts/:id", get(parts::get_part).patch(parts::update_part))
127        .route("/api/parts/:id/revisions", post(parts::create_revision))
128        .route("/api/parts/:id/revisions/:rev/checkout", post(parts::checkout))
129        .route("/api/parts/:id/revisions/:rev/checkin", post(parts::checkin))
130        .route("/api/parts/:id/revisions/:rev/state", post(parts::set_state))
131        .route("/api/parts/:id/revisions/:rev", delete(parts::delete_revision))
132        // -- review and approval -------------------------------------------
133        .route("/api/parts/:id/revisions/:rev/submit", post(review::submit))
134        .route(
135            "/api/parts/:id/revisions/:rev/review",
136            get(review::get_review).patch(review::change),
137        )
138        .route("/api/parts/:id/revisions/:rev/review/decision", post(review::decide))
139        .route("/api/parts/:id/revisions/:rev/comments", post(review::comment))
140        .route("/api/inbox", get(review::inbox))
141        // -- assembly structure: uses lists, BOMs and where-used -----------
142        .route(
143            "/api/parts/:id/revisions/:rev/uses",
144            get(bom::get_uses).put(bom::put_uses),
145        )
146        .route("/api/parts/:id/revisions/:rev/bom", get(bom::get_bom))
147        .route("/api/parts/:id/revisions/:rev/import", put(native_import::write))
148        .route("/api/import/validate", post(native_import::validate))
149        .route("/api/parts/:id/bom/diff", get(bom::diff))
150        .route("/api/parts/:id/where-used", get(bom::where_used))
151        .route("/api/parts/:id/replace", post(bom::replace))
152        // -- attachments ------------------------------------------------------
153        .route(
154            "/api/parts/:id/attachments",
155            get(attachments::list).post(attachments::upload_to_part),
156        )
157        .route("/api/parts/:id/revisions/:rev/attachments", post(attachments::upload_to_revision))
158        // -- thumbnails -------------------------------------------------------
159        .route(
160            "/api/parts/:id/revisions/:rev/thumbnail",
161            get(thumbnails::get_revision).put(thumbnails::put),
162        )
163        .route("/api/parts/:id/thumbnail", get(thumbnails::get_part))
164        .route(
165            "/api/attachments/:id",
166            get(attachments::download).put(attachments::replace).delete(attachments::remove),
167        )
168        .route("/api/attachments/:id/info", get(attachments::info))
169        // -- backups and exports (administrators) ---------------------------
170        .route("/api/admin/backups", get(backups::status).post(backups::run))
171        .route("/api/admin/backups/file/:name", get(backups::saved_file))
172        .route("/api/admin/backup", get(backups::download))
173        .route("/api/admin/export", get(backups::export))
174        // -- families, templates and the bake queue ------------------------
175        .route("/api/parts/:id/family", get(family::family))
176        .route("/api/parts/:id/family/import", post(family::import))
177        .route("/api/parts/:id/generate", post(family::generate))
178        .route("/api/parts/:id/template", get(family::template))
179        .route("/api/parts/:id/spin-out", post(family::spin_out))
180        .route("/api/bake/jobs", get(family::jobs))
181        .route("/api/bake/jobs/progress", post(family::progress))
182        .route("/api/bake/worker", get(bake_worker::status))
183        .route("/api/bake/worker/start", post(bake_worker::start))
184        .route("/api/bake/worker/stop", post(bake_worker::stop))
185        .route("/api/bake/resave", post(family::resave))
186        .route("/api/bake/next", post(family::next))
187        .route("/api/bake/jobs/:id/claim", post(family::claim))
188        .route("/api/bake/jobs/:id/renew", post(family::renew))
189        .route("/api/bake/jobs/:id/result", put(family::result))
190        .route("/api/bake/jobs/:id/fail", post(family::fail))
191        .route("/api/bake/jobs/:id/retry", post(family::retry))
192        .route("/api/parts/:id/sourcing", post(sourcing::add_manufacturer_part))
193        .route(
194            "/api/parts/:id/sourcing/:mp",
195            patch(sourcing::update_manufacturer_part).delete(sourcing::delete_manufacturer_part),
196        )
197        .route("/api/parts/:id/sourcing/:mp/offers", post(sourcing::add_offer))
198        .route(
199            "/api/parts/:id/sourcing/:mp/offers/:offer",
200            patch(sourcing::update_offer).delete(sourcing::delete_offer),
201        )
202        // -- sourcing: who makes parts and who sells them -----------------
203        .route(
204            "/api/manufacturers",
205            get(sourcing::list_manufacturers).post(sourcing::create_manufacturer),
206        )
207        .route(
208            "/api/manufacturers/:id",
209            patch(sourcing::update_manufacturer).delete(sourcing::delete_manufacturer),
210        )
211        .route("/api/suppliers", get(sourcing::list_suppliers).post(sourcing::create_supplier))
212        .route(
213            "/api/suppliers/:id",
214            patch(sourcing::update_supplier).delete(sourcing::delete_supplier),
215        )
216        // -- the catalog ---------------------------------------------------
217        .route("/api/categories", get(catalog::list).post(catalog::create))
218        .route(
219            "/api/categories/:id",
220            patch(catalog::update).delete(catalog::remove),
221        )
222        .route("/api/categories/:id/schema", get(catalog::schema))
223        // -- the administrator's settings ----------------------------------
224        .route("/api/settings", get(settings::get).patch(settings::update))
225        // -- the administrator's scripts -----------------------------------
226        .route("/api/scripts", get(scripts::list))
227        .route("/api/scripts/run", post(scripts::run))
228        .route(
229            "/api/scripts/file/*path",
230            get(scripts::read).put(scripts::write).delete(scripts::remove),
231        )
232        // -- the document surface the CAD app will consume -----------------
233        .route("/api/store/index", get(store::index))
234        .route("/api/store/changes", get(store::changes))
235        .route("/api/store/doc/*key", get(store::read_doc))
236        .route("/api/store/doc/*key", put(store::write_doc))
237        .route("/api/store/doc/*key", delete(store::delete_doc))
238        // -- the audit log -------------------------------------------------
239        .route("/api/audit", get(audit_log::query))
240        .route("/api/parts/:id/history", get(audit_log::part_history))
241        // -- workspaces: each user's folders of links and files -------------
242        .route("/api/workspaces", get(workspace::list_workspaces))
243        .route("/api/workspace/entries", get(workspace::list_folder))
244        .route("/api/workspace/folders", post(workspace::create_folder))
245        .route("/api/workspace/links", post(workspace::create_link))
246        .route("/api/workspace/files", post(workspace::create_file))
247        .route(
248            "/api/workspace/entries/:id",
249            get(workspace::get_entry).patch(workspace::update_entry).delete(workspace::delete_entry),
250        )
251        .route(
252            "/api/workspace/entries/:id/content",
253            get(workspace::download).put(workspace::replace_file),
254        )
255        .route("/api/workspace/entries/:id/versions", get(workspace::versions))
256        .route("/api/workspace/entries/:id/versions/:version/restore", post(workspace::restore))
257        .route("/api/workspace/entries/:id/promote", post(workspace::promote))
258        .layer(axum::middleware::from_fn_with_state(Arc::clone(&db), guard))
259        .with_state(db)
260}
261
262// ===========================================================================
263// Sessions
264// ===========================================================================
265
266/// The session token the request carries, if any.
267pub fn session_token(headers: &HeaderMap) -> Option<String> {
268    let raw = headers.get(header::COOKIE)?.to_str().ok()?;
269    raw.split(';').find_map(|pair| {
270        let (name, value) = pair.split_once('=')?;
271        (name.trim() == SESSION_COOKIE).then(|| value.trim().to_string())
272    })
273}
274
275/// Who a request is, once its credential has been checked.
276#[derive(Debug, Clone)]
277pub struct Identity {
278    pub user: User,
279    /// The session token, for a browser.
280    pub session: Option<String>,
281    /// The API token's id and scope, for anything else.
282    pub token: Option<(String, TokenScope)>,
283}
284
285/// The signed-in user, or a 401. A browser session or an API token
286/// ([`crate::security`]) — the handler does not care which.
287pub fn require_user(db: &Db, headers: &HeaderMap) -> Result<User, Error> {
288    identify(db, headers).map(|identity| identity.user)
289}
290
291/// Check the request's credential and say who it is.
292///
293/// A session expires after [`crate::model::Settings::session_idle_minutes`]
294/// without a request, and [`crate::model::Settings::session_max_hours`] after
295/// sign-in however busy it is. Both are checked on every request, so nothing
296/// has to sweep. Touching `last_seen` costs a metadata write, so it is
297/// re-stamped at most once a minute.
298pub fn identify(db: &Db, headers: &HeaderMap) -> Result<Identity, Error> {
299    match security::credential(headers) {
300        None => Err(Error::unauthorized("not signed in")),
301        Some(Credential::Bearer(secret)) => identify_token(db, &secret),
302        Some(Credential::Session(token)) => identify_session(db, &token),
303    }
304}
305
306fn identify_session(db: &Db, token: &str) -> Result<Identity, Error> {
307    let now = db::now();
308    let outcome = db.read(|state| {
309        let session = state.sessions.get(token)?;
310        let user = state.user(&session.user_id)?;
311        Some((session.last_seen, db::session_expired(&state.settings, session, now), user.clone()))
312    });
313    let Some((last_seen, expired, user)) = outcome else {
314        return Err(Error::unauthorized("session has expired"));
315    };
316    if expired {
317        let token = token.to_string();
318        let _ = db.mutate(move |state| {
319            state.sessions.retain(|s| s.token != token);
320            Ok(())
321        });
322        return Err(Error::unauthorized("session has expired"));
323    }
324    if !user.active {
325        return Err(Error::forbidden("this account is disabled"));
326    }
327    if now.saturating_sub(last_seen) > 60 {
328        let token = token.to_string();
329        let _ = db.mutate(move |state| {
330            if let Some(session) = state.sessions.get_mut(&token) {
331                session.last_seen = now;
332            }
333            Ok(())
334        });
335    }
336    Ok(Identity { user, session: Some(token.to_string()), token: None })
337}
338
339fn identify_token(db: &Db, secret: &str) -> Result<Identity, Error> {
340    let hash = security::token_hash(secret);
341    let found = db.read(|state| {
342        let token = state.api_tokens.iter().find(|t| security::same_secret(&t.hash, &hash))?;
343        let user = state.user(&token.user_id)?;
344        Some((token.clone(), user.clone()))
345    });
346    let Some((token, user)) = found else {
347        return Err(Error::unauthorized("that API token is not valid"));
348    };
349    let now = db::now();
350    if token.expires_at.is_some_and(|at| at <= now) {
351        return Err(Error::unauthorized("that API token has expired"));
352    }
353    if !user.active {
354        return Err(Error::forbidden("this account is disabled"));
355    }
356    if token.last_used_at.is_none_or(|at| now.saturating_sub(at) > 60) {
357        let id = token.id.clone();
358        let _ = db.mutate(move |state| {
359            if let Some(t) = state.api_tokens.iter_mut().find(|t| t.id == id) {
360                t.last_used_at = Some(now);
361            }
362            Ok(())
363        });
364    }
365    Ok(Identity { user, session: None, token: Some((token.id, token.scope)) })
366}
367
368/// The `Set-Cookie` value that starts a browser session.
369pub fn session_cookie(db: &Db, headers: &HeaderMap, token: &str) -> String {
370    let settings = db.settings();
371    let max_age = if settings.session_max_hours > 0 {
372        settings.session_max_hours * 3600
373    } else {
374        settings.session_idle_minutes * 60
375    };
376    let secure = if db.security().config.cookie_is_secure(headers) { "; Secure" } else { "" };
377    // HttpOnly so script cannot read it; SameSite=Lax so another site's form
378    // post does not carry it. Secure per `--secure-cookies`.
379    format!("{SESSION_COOKIE}={token}; HttpOnly; SameSite=Lax; Path=/; Max-Age={max_age}{secure}")
380}
381
382/// The `Set-Cookie` value that ends one.
383pub fn clear_cookie(db: &Db, headers: &HeaderMap) -> String {
384    let secure = if db.security().config.cookie_is_secure(headers) { "; Secure" } else { "" };
385    format!("{SESSION_COOKIE}=; HttpOnly; SameSite=Lax; Path=/; Max-Age=0{secure}")
386}
387
388/// Every request passes through here before its handler.
389///
390/// * A request with an API token is refused if the token is not valid, or if
391///   its scope does not allow the request ([`security::scope_refusal`]).
392/// * A request that changes anything and rides a session cookie must carry the
393///   session's CSRF token in `X-CSRF-Token`. `/api/login` is exempt — there is
394///   no session yet, and it only takes a JSON body, which another site's form
395///   cannot send.
396/// * Every response gets the security headers ([`security::security_headers`]).
397///
398/// The request then runs as its [`Actor`], so the audit log can say who made
399/// every change it causes ([`crate::audit`]).
400pub async fn guard(State(db): State<Shared>, request: Request, next: Next) -> Response {
401    let path = request.uri().path().to_string();
402    let api = path.starts_with("/api/");
403    let secure = db.security().config.is_secure_request(request.headers());
404    if api {
405        if let Err(error) = check_request(&db, request.method(), &path, request.headers()) {
406            let mut response = error.into_response();
407            security::security_headers(response.headers_mut(), secure, true);
408            return response;
409        }
410    }
411    let peer = request.extensions().get::<ConnectInfo<SocketAddr>>().map(|ConnectInfo(addr)| addr.ip());
412    let actor = actor_of(&db, request.headers(), peer);
413    let mut response = audit::scope(actor, next.run(request)).await;
414    // The hosted CAD app answers with its own policy ([`crate::cad`]); every
415    // other response gets the PLM's, whatever its handler set.
416    let own_policy = if path.starts_with(crate::cad::PREFIX) {
417        response.headers_mut().remove(header::CONTENT_SECURITY_POLICY)
418    } else {
419        None
420    };
421    let inline_document = response.status().is_success()
422        && (path.starts_with("/api/attachments/") || path.starts_with("/api/workspace/entries/"))
423        && response.headers().get(header::CONTENT_DISPOSITION).and_then(|v| v.to_str().ok()).is_some_and(|v| v.starts_with("inline;"))
424        && response.headers().get(header::CONTENT_TYPE).and_then(|v| v.to_str().ok()).is_some_and(|mime| mime == "application/pdf");
425    security::security_headers(response.headers_mut(), secure, api);
426    if inline_document {
427        response.headers_mut().insert(header::CONTENT_SECURITY_POLICY, axum::http::HeaderValue::from_static("default-src 'none'; frame-ancestors 'self'; base-uri 'none'"));
428        response.headers_mut().insert("x-frame-options", axum::http::HeaderValue::from_static("SAMEORIGIN"));
429    }
430    if let Some(policy) = own_policy {
431        response.headers_mut().insert(header::CONTENT_SECURITY_POLICY, policy);
432    }
433    response
434}
435
436/// Who a request is, for the audit log: read-only, and without the expiry
437/// checks — the handler still decides whether the credential is good, and a
438/// session that expires during this request is logged as ended by its owner.
439pub fn actor_of(db: &Db, headers: &HeaderMap, peer: Option<std::net::IpAddr>) -> Actor {
440    let ip = db.security().config.client_ip(headers, peer).map(|ip| ip.to_string()).unwrap_or_default();
441    let found = match security::credential(headers) {
442        Some(Credential::Session(token)) => db.read(|state| {
443            let session = state.sessions.iter().find(|s| s.token == token)?;
444            let user = state.user(&session.user_id)?;
445            Some((user.id.clone(), user.username.clone(), "session"))
446        }),
447        Some(Credential::Bearer(secret)) => {
448            let hash = security::token_hash(&secret);
449            db.read(|state| {
450                let token = state.api_tokens.iter().find(|t| security::same_secret(&t.hash, &hash))?;
451                let user = state.user(&token.user_id)?;
452                Some((user.id.clone(), user.username.clone(), "token"))
453            })
454        }
455        None => None,
456    };
457    match found {
458        Some((user_id, username, via)) => Actor { user_id, username, via: via.into(), ip },
459        None => Actor { ip, ..Actor::system() },
460    }
461}
462
463fn check_request(db: &Db, method: &Method, path: &str, headers: &HeaderMap) -> Result<(), Error> {
464    match security::credential(headers) {
465        Some(Credential::Bearer(secret)) => {
466            let identity = identify_token(db, &secret)?;
467            if let Some((_, scope)) = identity.token {
468                if let Some(refusal) = security::scope_refusal(scope, method, path) {
469                    return Err(Error::forbidden(refusal));
470                }
471            }
472            Ok(())
473        }
474        Some(Credential::Session(token)) if security::is_mutating(method) && path != "/api/login" => {
475            let expected = db.read(|state| {
476                state.sessions.iter().find(|s| s.token == token).map(|s| s.csrf.clone())
477            });
478            // No such session: the handler answers 401 as it always has.
479            let Some(expected) = expected else { return Ok(()) };
480            let sent = headers.get(CSRF_HEADER).and_then(|v| v.to_str().ok()).unwrap_or("");
481            if expected.is_empty() || !security::same_secret(&expected, sent) {
482                return Err(Error::forbidden(
483                    "this request is missing its CSRF token — reload the page and try again",
484                ));
485            }
486            Ok(())
487        }
488        _ => Ok(()),
489    }
490}
491
492/// The signed-in user, who must be an administrator.
493pub fn require_admin(db: &Db, headers: &HeaderMap) -> Result<User, Error> {
494    let user = require_user(db, headers)?;
495    if !user.is_admin() {
496        return Err(Error::forbidden("this needs the admin group"));
497    }
498    Ok(user)
499}
500
501/// The signed-in user, who must be able to create and edit work.
502pub fn require_author(db: &Db, headers: &HeaderMap) -> Result<User, Error> {
503    let user = require_user(db, headers)?;
504    if !user.can_author() {
505        return Err(Error::forbidden("this needs the author group"));
506    }
507    Ok(user)
508}
509
510/// Run `work` on the blocking pool. Anything that may call a script goes
511/// through here: a hook can wait on the network or a child process, and that
512/// wait must not stall the async runtime's worker threads.
513///
514/// The request's actor goes with the work, so a change made on the blocking
515/// pool is logged as the caller's.
516pub async fn blocking<R: Send + 'static>(
517    work: impl FnOnce() -> Result<R, Error> + Send + 'static,
518) -> Result<R, Error> {
519    let actor = audit::current_actor();
520    tokio::task::spawn_blocking(move || audit::as_actor(actor, work))
521        .await
522        .map_err(Error::internal)?
523}
524
525/// `{ "ok": true, "seq": n }` — the shape every mutating handler answers with.
526pub fn ok_seq(db: &Db) -> Response {
527    let seq = db.read(|state| state.seq);
528    axum::Json(serde_json::json!({ "ok": true, "seq": seq })).into_response()
529}
530
531/// A tiny health probe, useful before the page exists.
532pub async fn health(State(db): State<Shared>) -> Response {
533    let (users, parts, seq) = db.read(|s| (s.users.len(), s.parts.len(), s.seq));
534    (
535        StatusCode::OK,
536        axum::Json(serde_json::json!({
537            "ok": true, "users": users, "parts": parts, "seq": seq,
538        })),
539    )
540        .into_response()
541}