use std::collections::HashMap;
use std::net::IpAddr;
use std::sync::Mutex;
use axum::http::{HeaderMap, Method};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use subtle::ConstantTimeEq;
use crate::model::{Timestamp, TokenScope};
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum CookieSecurity {
#[default]
Off,
On,
Auto,
}
impl std::str::FromStr for CookieSecurity {
type Err = String;
fn from_str(text: &str) -> Result<Self, String> {
match text {
"off" => Ok(Self::Off),
"on" => Ok(Self::On),
"auto" => Ok(Self::Auto),
other => Err(format!("'{other}' is not off, on or auto")),
}
}
}
#[derive(Debug, Clone, Default)]
pub struct ServerConfig {
pub bake_worker: Option<crate::bake_worker::Config>,
pub secure_cookies: CookieSecurity,
pub trust_proxy: bool,
pub tls: bool,
pub lock_script_editor: bool,
pub max_attachment_bytes: u64,
pub max_document_bytes: u64,
pub min_client_version: Option<String>,
pub backup_dir: Option<std::path::PathBuf>,
pub backup_every_minutes: u64,
pub backup_keep: usize,
pub cad_app_dir: Option<std::path::PathBuf>,
pub web_dir: Option<std::path::PathBuf>,
pub cad_connect_src: Vec<String>,
}
pub const DEFAULT_MAX_ATTACHMENT: u64 = 100 * 1024 * 1024;
pub const DEFAULT_MAX_DOCUMENT: u64 = 64 * 1024 * 1024;
impl ServerConfig {
pub fn attachment_limit(&self) -> u64 {
if self.max_attachment_bytes == 0 { DEFAULT_MAX_ATTACHMENT } else { self.max_attachment_bytes }
}
pub fn min_client_version(&self) -> &str {
self.min_client_version.as_deref().unwrap_or(crate::version::MIN_CLIENT_VERSION)
}
pub fn document_limit(&self) -> u64 {
if self.max_document_bytes == 0 { DEFAULT_MAX_DOCUMENT } else { self.max_document_bytes }
}
}
impl ServerConfig {
pub fn is_secure_request(&self, headers: &HeaderMap) -> bool {
self.tls
|| (self.trust_proxy
&& headers
.get("x-forwarded-proto")
.and_then(|v| v.to_str().ok())
.is_some_and(|v| v.split(',').next().unwrap_or("").trim().eq_ignore_ascii_case("https")))
}
pub fn cookie_is_secure(&self, headers: &HeaderMap) -> bool {
match self.secure_cookies {
CookieSecurity::Off => false,
CookieSecurity::On => true,
CookieSecurity::Auto => self.is_secure_request(headers),
}
}
pub fn client_ip(&self, headers: &HeaderMap, peer: Option<IpAddr>) -> Option<IpAddr> {
if self.trust_proxy {
let forwarded = headers
.get("x-forwarded-for")
.and_then(|v| v.to_str().ok())
.and_then(|v| v.split(',').next())
.and_then(|v| v.trim().parse().ok());
if forwarded.is_some() {
return forwarded;
}
}
peer
}
}
pub const USER_THRESHOLD: u32 = 5;
pub const IP_THRESHOLD: u32 = 20;
pub const FIRST_LOCKOUT: u64 = 30;
pub const MAX_LOCKOUT: u64 = 15 * 60;
pub const FORGET_AFTER: u64 = 60 * 60;
const MAX_KEYS: usize = 10_000;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ThrottleKind {
User,
Ip,
}
impl ThrottleKind {
fn threshold(self) -> u32 {
match self {
ThrottleKind::User => USER_THRESHOLD,
ThrottleKind::Ip => IP_THRESHOLD,
}
}
}
#[derive(Debug, Clone, Default)]
struct Count {
failures: u32,
last_failure: Timestamp,
locked_until: Timestamp,
}
#[derive(Debug, Clone, Serialize)]
pub struct Lockout {
pub kind: ThrottleKind,
pub key: String,
pub failures: u32,
pub last_failure: Timestamp,
pub locked_until: Timestamp,
pub locked: bool,
}
#[derive(Debug, Default)]
pub struct Throttle {
counts: Mutex<HashMap<(ThrottleKind, String), Count>>,
}
impl Throttle {
fn key(kind: ThrottleKind, key: &str) -> (ThrottleKind, String) {
(kind, key.trim().to_ascii_lowercase())
}
pub fn locked_for(&self, kind: ThrottleKind, key: &str, now: Timestamp) -> Option<u64> {
let counts = self.counts.lock().unwrap_or_else(|e| e.into_inner());
let count = counts.get(&Self::key(kind, key))?;
(count.locked_until > now).then(|| count.locked_until - now)
}
pub fn fail(&self, kind: ThrottleKind, key: &str, now: Timestamp) {
let mut counts = self.counts.lock().unwrap_or_else(|e| e.into_inner());
if counts.len() >= MAX_KEYS {
let mut ages: Vec<_> = counts.iter().map(|(k, c)| (c.last_failure, k.clone())).collect();
ages.sort();
for (_, stale) in ages.into_iter().take(MAX_KEYS / 10) {
counts.remove(&stale);
}
}
let count = counts.entry(Self::key(kind, key)).or_default();
if now.saturating_sub(count.last_failure) > FORGET_AFTER {
*count = Count::default();
}
count.failures += 1;
count.last_failure = now;
let threshold = kind.threshold();
if count.failures >= threshold {
let doublings = (count.failures - threshold).min(16);
count.locked_until = now + (FIRST_LOCKOUT << doublings).min(MAX_LOCKOUT);
}
}
pub fn clear(&self, kind: ThrottleKind, key: &str) -> bool {
let mut counts = self.counts.lock().unwrap_or_else(|e| e.into_inner());
counts.remove(&Self::key(kind, key)).is_some()
}
pub fn clear_all(&self) -> usize {
let mut counts = self.counts.lock().unwrap_or_else(|e| e.into_inner());
let n = counts.len();
counts.clear();
n
}
pub fn list(&self, now: Timestamp) -> Vec<Lockout> {
let counts = self.counts.lock().unwrap_or_else(|e| e.into_inner());
let mut out: Vec<Lockout> = counts
.iter()
.filter(|(_, c)| now.saturating_sub(c.last_failure) <= FORGET_AFTER)
.map(|((kind, key), c)| Lockout {
kind: *kind,
key: key.clone(),
failures: c.failures,
last_failure: c.last_failure,
locked_until: c.locked_until,
locked: c.locked_until > now,
})
.collect();
out.sort_by(|a, b| b.locked.cmp(&a.locked).then(b.last_failure.cmp(&a.last_failure)));
out
}
}
#[derive(Debug, Default)]
pub struct Security {
pub config: ServerConfig,
pub throttle: Throttle,
}
pub const TOKEN_PREFIX: &str = "plm_";
pub fn new_token_secret() -> String {
format!("{TOKEN_PREFIX}{}", crate::auth::random_token(32))
}
pub fn token_hash(secret: &str) -> String {
let digest = Sha256::digest(secret.as_bytes());
digest.iter().map(|b| format!("{b:02x}")).collect()
}
pub fn same_secret(a: &str, b: &str) -> bool {
a.len() == b.len() && bool::from(a.as_bytes().ct_eq(b.as_bytes()))
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Credential {
Session(String),
Bearer(String),
}
pub fn credential(headers: &HeaderMap) -> Option<Credential> {
if let Some(value) = headers.get(axum::http::header::AUTHORIZATION).and_then(|v| v.to_str().ok()) {
let value = value.trim();
if let Some(rest) = value.strip_prefix("Bearer ").or_else(|| value.strip_prefix("bearer ")) {
return Some(Credential::Bearer(rest.trim().to_string()));
}
}
crate::api::session_token(headers).map(Credential::Session)
}
pub fn is_mutating(method: &Method) -> bool {
!matches!(*method, Method::GET | Method::HEAD | Method::OPTIONS)
}
pub fn is_credential_route(path: &str) -> bool {
path == "/api/tokens"
|| path.starts_with("/api/tokens/")
|| path == "/api/me/password"
|| path == "/api/logout-all"
}
fn is_thumbnail_route(path: &str) -> bool {
let parts: Vec<&str> = path.split('/').collect();
matches!(parts.as_slice(), ["", "api", "parts", p, "revisions", r, "thumbnail"] if !p.is_empty() && !r.is_empty())
}
pub fn scope_refusal(scope: TokenScope, method: &Method, path: &str) -> Option<String> {
if is_credential_route(path) {
return Some("an API token cannot manage tokens or passwords — sign in with a password".into());
}
if !is_mutating(method) {
return None;
}
match scope {
TokenScope::Full => None,
TokenScope::Read => Some("this API token may only read".into()),
TokenScope::Worker => {
let allowed = (path.starts_with("/api/bake/") && !path.starts_with("/api/bake/worker"))
|| path.starts_with("/api/store/doc/")
|| (*method == Method::PUT && is_thumbnail_route(path));
(!allowed).then(|| "this worker token may only read, work the bake queue, write documents and their thumbnails".into())
}
}
}
pub const CONTENT_SECURITY_POLICY: &str = "default-src 'none'; script-src 'self'; style-src 'self'; \
img-src 'self' data:; connect-src 'self'; font-src 'self'; frame-src 'self'; form-action 'self'; \
frame-ancestors 'none'; base-uri 'none'";
pub fn security_headers(headers: &mut HeaderMap, secure: bool, api: bool) {
use axum::http::HeaderValue;
let chose_private = headers.get("cache-control").and_then(|v| v.to_str().ok()).is_some_and(|v| v.starts_with("private"));
let mut set = |name: &'static str, value: &'static str| {
headers.insert(name, HeaderValue::from_static(value));
};
set("content-security-policy", CONTENT_SECURITY_POLICY);
set("x-frame-options", "DENY");
set("x-content-type-options", "nosniff");
set("referrer-policy", "no-referrer");
set("cross-origin-opener-policy", "same-origin");
set("permissions-policy", "camera=(), microphone=(), geolocation=()");
if api && !chose_private {
set("cache-control", "no-store");
}
if secure {
set("strict-transport-security", "max-age=31536000");
}
}