1use 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#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
43pub enum CookieSecurity {
44 #[default]
46 Off,
47 On,
49 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#[derive(Debug, Clone, Default)]
69pub struct ServerConfig {
70 pub bake_worker: Option<crate::bake_worker::Config>,
72 pub secure_cookies: CookieSecurity,
73 pub trust_proxy: bool,
77 pub tls: bool,
79 pub lock_script_editor: bool,
82 pub max_attachment_bytes: u64,
85 pub max_document_bytes: u64,
89 pub min_client_version: Option<String>,
94 pub backup_dir: Option<std::path::PathBuf>,
97 pub backup_every_minutes: u64,
99 pub backup_keep: usize,
101 pub cad_app_dir: Option<std::path::PathBuf>,
104 pub web_dir: Option<std::path::PathBuf>,
106 pub cad_connect_src: Vec<String>,
109}
110
111pub const DEFAULT_MAX_ATTACHMENT: u64 = 100 * 1024 * 1024;
113
114pub const DEFAULT_MAX_DOCUMENT: u64 = 64 * 1024 * 1024;
117
118impl ServerConfig {
119 pub fn attachment_limit(&self) -> u64 {
121 if self.max_attachment_bytes == 0 { DEFAULT_MAX_ATTACHMENT } else { self.max_attachment_bytes }
122 }
123
124 pub fn min_client_version(&self) -> &str {
127 self.min_client_version.as_deref().unwrap_or(crate::version::MIN_CLIENT_VERSION)
128 }
129
130 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 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 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 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
174pub const USER_THRESHOLD: u32 = 5;
180pub const IP_THRESHOLD: u32 = 20;
183pub const FIRST_LOCKOUT: u64 = 30;
185pub const MAX_LOCKOUT: u64 = 15 * 60;
187pub const FORGET_AFTER: u64 = 60 * 60;
189const MAX_KEYS: usize = 10_000;
192
193#[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#[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 pub locked_until: Timestamp,
226 pub locked: bool,
227}
228
229#[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 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 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 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 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 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 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#[derive(Debug, Default)]
307pub struct Security {
308 pub config: ServerConfig,
309 pub throttle: Throttle,
310 pub desktop_links: crate::desktop_link::DesktopLinks,
312}
313
314pub const TOKEN_PREFIX: &str = "plm_";
321
322pub fn new_token_secret() -> String {
324 format!("{TOKEN_PREFIX}{}", crate::auth::random_token(32))
325}
326
327pub 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
333pub 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#[derive(Debug, Clone, PartialEq, Eq)]
340pub enum Credential {
341 Session(String),
342 Bearer(String),
343}
344
345pub 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
357pub fn is_mutating(method: &Method) -> bool {
359 !matches!(*method, Method::GET | Method::HEAD | Method::OPTIONS)
360}
361
362pub fn is_credential_route(path: &str) -> bool {
366 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
375fn 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
382pub 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
402pub 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
413pub 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 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