Skip to main content

brep_plm/
security.rs

1//! Hardening: how the server is configured to face a network, the sign-in
2//! throttle, API tokens, and the pieces of request checking every route shares
3//! (CSRF, token scopes, response headers).
4//!
5//! # Two ways to sign in
6//!
7//! * **A browser** signs in with a password and gets a session cookie
8//!   (`HttpOnly`, `SameSite=Lax`, `Secure` when [`ServerConfig`] says so). A
9//!   cookie is sent by the browser on its own, so every request that changes
10//!   anything must ALSO carry the session's CSRF token in `X-CSRF-Token`. That
11//!   is the synchronizer-token pattern: the token lives in the session record
12//!   on the server, the page receives it from `/api/login` and `/api/me`, and
13//!   another site's page can neither read it nor guess it.
14//! * **Anything else** — the CAD app, a headless bake worker, an organization's
15//!   own tooling — sends `Authorization: Bearer plm_…`, an API token its owner
16//!   created. A bearer header is never sent by a browser on its own, so a token
17//!   request needs no CSRF token. A token acts as its owner, narrowed by its
18//!   [`TokenScope`].
19//!
20//! # The sign-in throttle
21//!
22//! Failed sign-ins are counted per username and per client address, in memory.
23//! Past a threshold the key is locked out for a period that doubles with each
24//! further failure, up to a cap; while locked out the server refuses without
25//! even checking the password, so a guesser learns nothing. A success clears
26//! the username's count. An administrator can see and clear every lockout. The
27//! counts live in memory on purpose: a restart forgets them, and nothing an
28//! attacker does can lock an account out permanently.
29
30use std::collections::HashMap;
31use std::net::IpAddr;
32use std::sync::Mutex;
33
34use axum::http::{HeaderMap, Method};
35use serde::{Deserialize, Serialize};
36use sha2::{Digest, Sha256};
37use subtle::ConstantTimeEq;
38
39use crate::model::{Timestamp, TokenScope};
40
41/// When the session cookie carries the `Secure` flag.
42#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
43pub enum CookieSecurity {
44    /// Never. The default, so plain-HTTP loopback development works.
45    #[default]
46    Off,
47    /// Always. Right when every client reaches the server over HTTPS.
48    On,
49    /// When the request arrived over TLS: natively, or through a trusted
50    /// proxy that says `X-Forwarded-Proto: https`.
51    Auto,
52}
53
54impl std::str::FromStr for CookieSecurity {
55    type Err = String;
56    fn from_str(text: &str) -> Result<Self, String> {
57        match text {
58            "off" => Ok(Self::Off),
59            "on" => Ok(Self::On),
60            "auto" => Ok(Self::Auto),
61            other => Err(format!("'{other}' is not off, on or auto")),
62        }
63    }
64}
65
66/// How the server faces the network. Set from the command line at start-up;
67/// nothing in the browser can change it.
68#[derive(Debug, Clone, Default)]
69pub struct ServerConfig {
70    /// Native worker pinned by the server operator, controlled by admins.
71    pub bake_worker: Option<crate::bake_worker::Config>,
72    pub secure_cookies: CookieSecurity,
73    /// Believe `X-Forwarded-For` and `X-Forwarded-Proto`. Only right behind a
74    /// reverse proxy that sets them; otherwise any client could claim any
75    /// address and dodge the per-address throttle.
76    pub trust_proxy: bool,
77    /// The server terminates TLS itself (`--tls-cert` / `--tls-key`).
78    pub tls: bool,
79    /// `--lock-script-editor`: the in-browser script editor is off whatever
80    /// the settings say. The one protection an admin login cannot undo.
81    pub lock_script_editor: bool,
82    /// `--max-attachment-mb`: the largest attachment an upload may carry, in
83    /// bytes. 0 means [`DEFAULT_MAX_ATTACHMENT`].
84    pub max_attachment_bytes: u64,
85    /// `--max-document-mb`: the largest body a document write — a revision's
86    /// document, or the `@recovery` preference that mirrors unsaved ones — may
87    /// carry, in bytes. 0 means [`DEFAULT_MAX_DOCUMENT`].
88    pub max_document_bytes: u64,
89    /// `--min-client-version`: a floor on the CAD app's version ABOVE
90    /// [`crate::version::MIN_CLIENT_VERSION`], for an administrator retiring
91    /// old installs — and for a test runner provoking the app's refusal. None
92    /// means the built-in floor.
93    pub min_client_version: Option<String>,
94    /// `--backup-dir`: where scheduled and "Back up now" backups are saved.
95    /// None: backups are only downloaded.
96    pub backup_dir: Option<std::path::PathBuf>,
97    /// `--backup-every`: minutes between scheduled backups; 0 is none.
98    pub backup_every_minutes: u64,
99    /// `--backup-keep`: how many saved backups to keep; 0 means 7.
100    pub backup_keep: usize,
101    /// `--cad-app`: the directory the wasm CAD app is served from
102    /// ([`crate::cad`]). None: no app is hosted.
103    pub cad_app_dir: Option<std::path::PathBuf>,
104    /// `--web-dir`: live PLM frontend files overriding the embedded bundle.
105    pub web_dir: Option<std::path::PathBuf>,
106    /// `--cad-connect-src`: origins the hosted CAD app may call besides this
107    /// server ([`crate::cad::policy`]).
108    pub cad_connect_src: Vec<String>,
109}
110
111/// 100 MB: a scanned drawing set or a long datasheet, not a video.
112pub const DEFAULT_MAX_ATTACHMENT: u64 = 100 * 1024 * 1024;
113
114/// 64 MB: a large assembly's history JSON, with room. Far above axum's 2 MB
115/// default for a buffered body, which real model documents exceed.
116pub const DEFAULT_MAX_DOCUMENT: u64 = 64 * 1024 * 1024;
117
118impl ServerConfig {
119    /// The upload limit in force.
120    pub fn attachment_limit(&self) -> u64 {
121        if self.max_attachment_bytes == 0 { DEFAULT_MAX_ATTACHMENT } else { self.max_attachment_bytes }
122    }
123
124    /// The oldest CAD app this server serves: `--min-client-version` when
125    /// given, else the built-in [`crate::version::MIN_CLIENT_VERSION`].
126    pub fn min_client_version(&self) -> &str {
127        self.min_client_version.as_deref().unwrap_or(crate::version::MIN_CLIENT_VERSION)
128    }
129
130    /// The document body limit in force.
131    pub fn document_limit(&self) -> u64 {
132        if self.max_document_bytes == 0 { DEFAULT_MAX_DOCUMENT } else { self.max_document_bytes }
133    }
134}
135
136impl ServerConfig {
137    /// Whether this request reached the server over TLS, as far as the server
138    /// can know.
139    pub fn is_secure_request(&self, headers: &HeaderMap) -> bool {
140        self.tls
141            || (self.trust_proxy
142                && headers
143                    .get("x-forwarded-proto")
144                    .and_then(|v| v.to_str().ok())
145                    .is_some_and(|v| v.split(',').next().unwrap_or("").trim().eq_ignore_ascii_case("https")))
146    }
147
148    /// Whether a cookie set in answer to this request is `Secure`.
149    pub fn cookie_is_secure(&self, headers: &HeaderMap) -> bool {
150        match self.secure_cookies {
151            CookieSecurity::Off => false,
152            CookieSecurity::On => true,
153            CookieSecurity::Auto => self.is_secure_request(headers),
154        }
155    }
156
157    /// The client address: the socket peer, or with [`Self::trust_proxy`] the
158    /// first address in `X-Forwarded-For`.
159    pub fn client_ip(&self, headers: &HeaderMap, peer: Option<IpAddr>) -> Option<IpAddr> {
160        if self.trust_proxy {
161            let forwarded = headers
162                .get("x-forwarded-for")
163                .and_then(|v| v.to_str().ok())
164                .and_then(|v| v.split(',').next())
165                .and_then(|v| v.trim().parse().ok());
166            if forwarded.is_some() {
167                return forwarded;
168            }
169        }
170        peer
171    }
172}
173
174// ===========================================================================
175// The sign-in throttle
176// ===========================================================================
177
178/// Failures on one username before it is locked out.
179pub const USER_THRESHOLD: u32 = 5;
180/// Failures from one address before it is locked out. Higher, because one
181/// address may be a whole office behind NAT.
182pub const IP_THRESHOLD: u32 = 20;
183/// The first lockout; each further failure doubles it.
184pub const FIRST_LOCKOUT: u64 = 30;
185/// The longest lockout.
186pub const MAX_LOCKOUT: u64 = 15 * 60;
187/// A count with no failure for this long starts again from zero.
188pub const FORGET_AFTER: u64 = 60 * 60;
189/// The most keys remembered; past it the stalest are forgotten, so a flood of
190/// made-up usernames cannot grow memory without bound.
191const MAX_KEYS: usize = 10_000;
192
193/// Which kind of key a throttle entry counts.
194#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
195#[serde(rename_all = "lowercase")]
196pub enum ThrottleKind {
197    User,
198    Ip,
199}
200
201impl ThrottleKind {
202    fn threshold(self) -> u32 {
203        match self {
204            ThrottleKind::User => USER_THRESHOLD,
205            ThrottleKind::Ip => IP_THRESHOLD,
206        }
207    }
208}
209
210#[derive(Debug, Clone, Default)]
211struct Count {
212    failures: u32,
213    last_failure: Timestamp,
214    locked_until: Timestamp,
215}
216
217/// One entry as an administrator sees it.
218#[derive(Debug, Clone, Serialize)]
219pub struct Lockout {
220    pub kind: ThrottleKind,
221    pub key: String,
222    pub failures: u32,
223    pub last_failure: Timestamp,
224    /// When the lockout ends; 0 or in the past when the key is only counting.
225    pub locked_until: Timestamp,
226    pub locked: bool,
227}
228
229/// Failed sign-ins per username and per address.
230#[derive(Debug, Default)]
231pub struct Throttle {
232    counts: Mutex<HashMap<(ThrottleKind, String), Count>>,
233}
234
235impl Throttle {
236    fn key(kind: ThrottleKind, key: &str) -> (ThrottleKind, String) {
237        (kind, key.trim().to_ascii_lowercase())
238    }
239
240    /// How many seconds `key` is still locked out for, if it is.
241    pub fn locked_for(&self, kind: ThrottleKind, key: &str, now: Timestamp) -> Option<u64> {
242        let counts = self.counts.lock().unwrap_or_else(|e| e.into_inner());
243        let count = counts.get(&Self::key(kind, key))?;
244        (count.locked_until > now).then(|| count.locked_until - now)
245    }
246
247    /// Count a failure against `key`.
248    pub fn fail(&self, kind: ThrottleKind, key: &str, now: Timestamp) {
249        let mut counts = self.counts.lock().unwrap_or_else(|e| e.into_inner());
250        if counts.len() >= MAX_KEYS {
251            // Forget the stalest tenth rather than one at a time.
252            let mut ages: Vec<_> = counts.iter().map(|(k, c)| (c.last_failure, k.clone())).collect();
253            ages.sort();
254            for (_, stale) in ages.into_iter().take(MAX_KEYS / 10) {
255                counts.remove(&stale);
256            }
257        }
258        let count = counts.entry(Self::key(kind, key)).or_default();
259        if now.saturating_sub(count.last_failure) > FORGET_AFTER {
260            *count = Count::default();
261        }
262        count.failures += 1;
263        count.last_failure = now;
264        let threshold = kind.threshold();
265        if count.failures >= threshold {
266            let doublings = (count.failures - threshold).min(16);
267            count.locked_until = now + (FIRST_LOCKOUT << doublings).min(MAX_LOCKOUT);
268        }
269    }
270
271    /// Forget `key` — a successful sign-in, or an administrator's clear.
272    pub fn clear(&self, kind: ThrottleKind, key: &str) -> bool {
273        let mut counts = self.counts.lock().unwrap_or_else(|e| e.into_inner());
274        counts.remove(&Self::key(kind, key)).is_some()
275    }
276
277    /// Forget everything.
278    pub fn clear_all(&self) -> usize {
279        let mut counts = self.counts.lock().unwrap_or_else(|e| e.into_inner());
280        let n = counts.len();
281        counts.clear();
282        n
283    }
284
285    /// Every key with a failure on record, locked-out ones first.
286    pub fn list(&self, now: Timestamp) -> Vec<Lockout> {
287        let counts = self.counts.lock().unwrap_or_else(|e| e.into_inner());
288        let mut out: Vec<Lockout> = counts
289            .iter()
290            .filter(|(_, c)| now.saturating_sub(c.last_failure) <= FORGET_AFTER)
291            .map(|((kind, key), c)| Lockout {
292                kind: *kind,
293                key: key.clone(),
294                failures: c.failures,
295                last_failure: c.last_failure,
296                locked_until: c.locked_until,
297                locked: c.locked_until > now,
298            })
299            .collect();
300        out.sort_by(|a, b| b.locked.cmp(&a.locked).then(b.last_failure.cmp(&a.last_failure)));
301        out
302    }
303}
304
305/// Everything the hardening layer keeps for the life of the process.
306#[derive(Debug, Default)]
307pub struct Security {
308    pub config: ServerConfig,
309    pub throttle: Throttle,
310    /// Desktop sign-ins waiting for a browser ([`crate::desktop_link`]).
311    pub desktop_links: crate::desktop_link::DesktopLinks,
312}
313
314// ===========================================================================
315// API tokens
316// ===========================================================================
317
318/// Every token secret starts with this, so a leaked one is recognizable in a
319/// log or a repository scan.
320pub const TOKEN_PREFIX: &str = "plm_";
321
322/// A fresh token secret: the prefix and 256 random bits.
323pub fn new_token_secret() -> String {
324    format!("{TOKEN_PREFIX}{}", crate::auth::random_token(32))
325}
326
327/// The stored form of a secret: hex SHA-256.
328pub fn token_hash(secret: &str) -> String {
329    let digest = Sha256::digest(secret.as_bytes());
330    digest.iter().map(|b| format!("{b:02x}")).collect()
331}
332
333/// Whether two secrets are equal, in constant time.
334pub fn same_secret(a: &str, b: &str) -> bool {
335    a.len() == b.len() && bool::from(a.as_bytes().ct_eq(b.as_bytes()))
336}
337
338/// How a request says who it is.
339#[derive(Debug, Clone, PartialEq, Eq)]
340pub enum Credential {
341    Session(String),
342    Bearer(String),
343}
344
345/// The credential a request carries. A bearer header wins over a cookie: a
346/// tool that sends one means it.
347pub fn credential(headers: &HeaderMap) -> Option<Credential> {
348    if let Some(value) = headers.get(axum::http::header::AUTHORIZATION).and_then(|v| v.to_str().ok()) {
349        let value = value.trim();
350        if let Some(rest) = value.strip_prefix("Bearer ").or_else(|| value.strip_prefix("bearer ")) {
351            return Some(Credential::Bearer(rest.trim().to_string()));
352        }
353    }
354    crate::api::session_token(headers).map(Credential::Session)
355}
356
357/// Whether a method changes anything. Everything but a read does.
358pub fn is_mutating(method: &Method) -> bool {
359    !matches!(*method, Method::GET | Method::HEAD | Method::OPTIONS)
360}
361
362/// Routes a token may never call, whatever its scope: the ones that mint or
363/// revoke credentials. A leaked token must not be able to make itself a new
364/// one, change its owner's password, or hide by revoking the others.
365pub fn is_credential_route(path: &str) -> bool {
366    // Deciding a desktop sign-in mints a token for the decider.
367    let desktop_decision = matches!(path, "/api/desktop/link/inspect" | "/api/desktop/link/approve" | "/api/desktop/link/deny");
368    desktop_decision
369        || path == "/api/tokens"
370        || path.starts_with("/api/tokens/")
371        || path == "/api/me/password"
372        || path == "/api/logout-all"
373}
374
375/// `/api/parts/<id>/revisions/<rev>/thumbnail`: the bake worker pictures
376/// what it bakes ([`crate::thumbnail`]).
377fn is_thumbnail_route(path: &str) -> bool {
378    let parts: Vec<&str> = path.split('/').collect();
379    matches!(parts.as_slice(), ["", "api", "parts", p, "revisions", r, "thumbnail"] if !p.is_empty() && !r.is_empty())
380}
381
382/// Why a token of `scope` may not make this request, or `None` when it may.
383pub fn scope_refusal(scope: TokenScope, method: &Method, path: &str) -> Option<String> {
384    if is_credential_route(path) {
385        return Some("an API token cannot manage tokens or passwords — sign in with a password".into());
386    }
387    if !is_mutating(method) {
388        return None;
389    }
390    match scope {
391        TokenScope::Full => None,
392        TokenScope::Read => Some("this API token may only read".into()),
393        TokenScope::Worker => {
394            let allowed = (path.starts_with("/api/bake/") && !path.starts_with("/api/bake/worker"))
395                || path.starts_with("/api/store/doc/")
396                || (*method == Method::PUT && is_thumbnail_route(path));
397            (!allowed).then(|| "this worker token may only read, work the bake queue, write documents and their thumbnails".into())
398        }
399    }
400}
401
402// ===========================================================================
403// Response headers
404// ===========================================================================
405
406/// The page's Content Security Policy. The page is three same-origin files
407/// with no inline script or style and no third-party anything, so everything
408/// is `'self'` and nothing may frame it.
409pub const CONTENT_SECURITY_POLICY: &str = "default-src 'none'; script-src 'self'; style-src 'self'; \
410img-src 'self' data:; connect-src 'self'; font-src 'self'; frame-src 'self'; form-action 'self'; \
411frame-ancestors 'none'; base-uri 'none'";
412
413/// Headers every response carries.
414pub fn security_headers(headers: &mut HeaderMap, secure: bool, api: bool) {
415    use axum::http::HeaderValue;
416    let chose_private = headers.get("cache-control").and_then(|v| v.to_str().ok()).is_some_and(|v| v.starts_with("private"));
417    let mut set = |name: &'static str, value: &'static str| {
418        headers.insert(name, HeaderValue::from_static(value));
419    };
420    set("content-security-policy", CONTENT_SECURITY_POLICY);
421    set("x-frame-options", "DENY");
422    set("x-content-type-options", "nosniff");
423    set("referrer-policy", "no-referrer");
424    set("cross-origin-opener-policy", "same-origin");
425    set("permissions-policy", "camera=(), microphone=(), geolocation=()");
426    // Part data, documents and tokens must not sit in a shared cache. A
427    // handler that chose a `private` policy itself keeps it: a thumbnail
428    // (`api::thumbnails`) is revalidated by its ETag, or cached for good at a
429    // URL versioned by its hash.
430    if api && !chose_private {
431        set("cache-control", "no-store");
432    }
433    if secure {
434        set("strict-transport-security", "max-age=31536000");
435    }
436}
437