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