From d81432f3867f2ab3e3292665c460707b1f2d29e1 Mon Sep 17 00:00:00 2001 From: RAHMAT AL ZAMI <112936589+zamibd@users.noreply.github.com> Date: Sat, 5 Dec 2026 00:22:09 +0000 Subject: [PATCH 1/5] fix(tls): serve renewed certificates without a restart Certificates were cached forever after their first use, so a certificate renewed by Let's Encrypt (30 days before expiry) was not served until the process restarted; without a restart, clients got an expired certificate. Cached certificates are now re-read from disk after 5 minutes, which also stops serving certificates whose files were deleted. SNI names that could leave the certificate directory ("..", "/") are rejected. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0114BeX74hMZZpCUvVg5iyti --- src/constants.rs | 4 +- src/tls_manager.rs | 272 +++++++++++++++++++++++++++++++-------------- 2 files changed, 189 insertions(+), 87 deletions(-) diff --git a/src/constants.rs b/src/constants.rs index 4dbf0a8..ebed0be 100644 --- a/src/constants.rs +++ b/src/constants.rs @@ -7,7 +7,6 @@ pub mod http { pub const NOT_FOUND: u16 = StatusCode::NOT_FOUND.as_u16(); pub const INTERNAL_ERROR: u16 = StatusCode::INTERNAL_SERVER_ERROR.as_u16(); pub const UNAUTHORIZED: u16 = StatusCode::UNAUTHORIZED.as_u16(); - pub const CREATED: u16 = StatusCode::CREATED.as_u16(); pub const PAYLOAD_TOO_LARGE: u16 = StatusCode::PAYLOAD_TOO_LARGE.as_u16(); } @@ -23,7 +22,8 @@ pub mod network { pub mod cert { pub const RSA_BITS: u32 = 2048; pub const VALIDITY_DAYS: u32 = 3650; // 10 years - pub const RENEWAL_THRESHOLD_DAYS: u64 = 30; + /// Seconds a loaded certificate is cached before being re-read from disk. + pub const CACHE_TTL_SECS: u64 = 300; } /// Timeouts (milliseconds/seconds) diff --git a/src/tls_manager.rs b/src/tls_manager.rs index 7364448..911a7e3 100644 --- a/src/tls_manager.rs +++ b/src/tls_manager.rs @@ -12,25 +12,55 @@ use std::collections::HashMap; use std::fs; use std::path::Path; use std::sync::Arc; +use std::time::{Duration, Instant}; use tokio::fs as tokio_fs; +/// How long a cached certificate is served before it is re-read from disk. +/// Renewed certificates are picked up within this time, without a restart. +const CERT_CACHE_TTL: Duration = Duration::from_secs(constants::cert::CACHE_TTL_SECS); + /// TLS manager that dynamically loads per-domain certificates. /// Selects the right certificate based on SNI (Server Name Indication). pub struct DynamicCertManager { - /// Certificate cache: domain -> (certificate PEM, key PEM) - cert_cache: Arc>>, + /// Certificate cache: domain -> (certificate PEM, key PEM, load time) + cert_cache: Arc>>, /// Certificate directory path cert_dir: String, /// Default certificate (used when there is no SNI or no matching certificate) default_cert: CertKeyPair, + /// How long a cached certificate is served before being re-read from disk + cache_ttl: Duration, } -#[derive(Clone)] +#[derive(Clone, PartialEq)] struct CertKeyPair { cert_pem: Vec, key_pem: Vec, } +struct CachedCert { + pair: CertKeyPair, + loaded_at: Instant, +} + +impl CachedCert { + fn new(pair: CertKeyPair) -> Self { + Self { + pair, + loaded_at: Instant::now(), + } + } + + fn is_fresh(&self, ttl: Duration) -> bool { + self.loaded_at.elapsed() < ttl + } +} + +/// Rejects names that could escape the certificate directory (SNI is client input). +fn is_safe_cert_name(name: &str) -> bool { + !name.is_empty() && !name.contains(['/', '\\']) && !name.contains("..") +} + /// Checks that the default certificate exists and generates one if it does not. fn ensure_default_cert(cert_path: &str, key_path: &str) -> Result<(), Box> { let cert_path = Path::new(cert_path); @@ -107,6 +137,7 @@ impl DynamicCertManager { cert_cache: Arc::new(RwLock::new(HashMap::new())), cert_dir: cert_dir.to_string(), default_cert, + cache_ttl: CERT_CACHE_TTL, }) } @@ -141,7 +172,10 @@ impl DynamicCertManager { if key_path.exists() { match (fs::read(&path), fs::read(&key_path)) { (Ok(cert_pem), Ok(key_pem)) => { - cache.insert(domain.clone(), CertKeyPair { cert_pem, key_pem }); + cache.insert( + domain.clone(), + CachedCert::new(CertKeyPair { cert_pem, key_pem }), + ); tracing::info!("🔐 Loaded certificate for: {}", domain); count += 1; } @@ -160,75 +194,18 @@ impl DynamicCertManager { Ok(count) } - /// Gets a domain's certificate from the cache, or loads it from disk. + /// Gets a domain's certificate: exact match, then wildcard, then the default. async fn get_cert_for_domain(&self, domain: &str) -> CertKeyPair { - // 1. Look in the cache first - { - let cache = self.cert_cache.read(); - if let Some(pair) = cache.get(domain) { - return pair.clone(); - } - } - - // 2. Try loading from disk - let cert_path = Path::new(&self.cert_dir).join(format!("{}.crt", domain)); - let key_path = Path::new(&self.cert_dir).join(format!("{}.key", domain)); - - if tokio_fs::try_exists(&cert_path).await.unwrap_or(false) - && tokio_fs::try_exists(&key_path).await.unwrap_or(false) - && let (Ok(cert_pem), Ok(key_pem)) = ( - tokio_fs::read(&cert_path).await, - tokio_fs::read(&key_path).await, - ) - { - let pair = CertKeyPair { - cert_pem: cert_pem.clone(), - key_pem: key_pem.clone(), - }; - - // Store in the cache - { - let mut cache = self.cert_cache.write(); - cache.insert(domain.to_string(), CertKeyPair { cert_pem, key_pem }); - } - - tracing::info!("🔐 Dynamically loaded certificate for: {}", domain); + if let Some(pair) = self.cached_or_load(domain).await { return pair; } - // 3. Look for a wildcard certificate (e.g. *.example.com) - if let Some(parent_domain) = domain.split_once('.').map(|(_, parent)| parent) { + // Look for a wildcard certificate (e.g. *.example.com) + if let Some((_, parent_domain)) = domain.split_once('.') { let wildcard = format!("*.{}", parent_domain); - - { - let cache = self.cert_cache.read(); - if let Some(pair) = cache.get(&wildcard) { - return pair.clone(); - } - } - - let cert_path = Path::new(&self.cert_dir).join(format!("{}.crt", wildcard)); - let key_path = Path::new(&self.cert_dir).join(format!("{}.key", wildcard)); - - if tokio_fs::try_exists(&cert_path).await.unwrap_or(false) - && tokio_fs::try_exists(&key_path).await.unwrap_or(false) - && let (Ok(cert_pem), Ok(key_pem)) = ( - tokio_fs::read(&cert_path).await, - tokio_fs::read(&key_path).await, - ) - { - let pair = CertKeyPair { - cert_pem: cert_pem.clone(), - key_pem: key_pem.clone(), - }; - - { - let mut cache = self.cert_cache.write(); - cache.insert(wildcard.clone(), CertKeyPair { cert_pem, key_pem }); - } - - tracing::info!( - "🔐 Loaded wildcard certificate for: {} -> {}", + if let Some(pair) = self.cached_or_load(&wildcard).await { + tracing::debug!( + "🔐 Using wildcard certificate for: {} -> {}", domain, wildcard ); @@ -236,24 +213,54 @@ impl DynamicCertManager { } } - // 4. Return the default certificate tracing::debug!("🔒 Using default certificate for: {}", domain); self.default_cert.clone() } - /// Invalidates the cached certificate for a domain. - /// Must be called after a certificate is renewed. - pub fn invalidate_cert(&self, domain: &str) { - let mut cache = self.cert_cache.write(); - cache.remove(domain); - tracing::info!("🔄 Certificate cache invalidated for: {}", domain); - } + /// Returns the certificate stored under `name` (a domain or `*.domain`). + /// Cache entries older than [`CERT_CACHE_TTL`] are re-read from disk, so + /// renewed certificates are served and deleted ones stop being served. + async fn cached_or_load(&self, name: &str) -> Option { + if !is_safe_cert_name(name) { + return None; + } - /// Clears the whole certificate cache. - pub fn clear_cache(&self) { - let mut cache = self.cert_cache.write(); - cache.clear(); - tracing::info!("🔄 All certificate cache cleared"); + let previous = { + let cache = self.cert_cache.read(); + match cache.get(name) { + Some(entry) if entry.is_fresh(self.cache_ttl) => return Some(entry.pair.clone()), + Some(entry) => Some(entry.pair.clone()), + None => None, + } + }; + + let cert_path = Path::new(&self.cert_dir).join(format!("{}.crt", name)); + let key_path = Path::new(&self.cert_dir).join(format!("{}.key", name)); + + let (Ok(cert_pem), Ok(key_pem)) = ( + tokio_fs::read(&cert_path).await, + tokio_fs::read(&key_path).await, + ) else { + if previous.is_some() { + self.cert_cache.write().remove(name); + tracing::info!("🗑️ Certificate files removed, no longer serving: {}", name); + } + return None; + }; + + let pair = CertKeyPair { cert_pem, key_pem }; + match &previous { + None => tracing::info!("🔐 Dynamically loaded certificate for: {}", name), + Some(old) if *old != pair => { + tracing::info!("🔄 Reloaded updated certificate for: {}", name) + } + Some(_) => {} + } + + self.cert_cache + .write() + .insert(name.to_string(), CachedCert::new(pair.clone())); + Some(pair) } } @@ -303,10 +310,6 @@ impl SharedCertManager { pub fn new(manager: DynamicCertManager) -> Self { Self(Arc::new(manager)) } - - pub fn inner(&self) -> &Arc { - &self.0 - } } impl Clone for SharedCertManager { @@ -321,3 +324,102 @@ impl TlsAccept for SharedCertManager { self.0.certificate_callback(ssl).await } } + +#[cfg(test)] +mod tests { + use super::*; + + fn manager(dir: &Path, ttl: Duration) -> DynamicCertManager { + let certs = dir.join("certs"); + fs::create_dir_all(&certs).unwrap(); + let mut manager = DynamicCertManager::new( + certs.to_str().unwrap(), + dir.join("default.crt").to_str().unwrap(), + dir.join("default.key").to_str().unwrap(), + ) + .unwrap(); + manager.cache_ttl = ttl; + manager + } + + fn write_cert(dir: &Path, name: &str, contents: &str) { + let certs = dir.join("certs"); + fs::write( + certs.join(format!("{name}.crt")), + format!("{contents}-cert"), + ) + .unwrap(); + fs::write(certs.join(format!("{name}.key")), format!("{contents}-key")).unwrap(); + } + + #[tokio::test] + async fn serves_renewed_certificate_after_ttl() { + let dir = tempfile::tempdir().unwrap(); + let manager = manager(dir.path(), Duration::ZERO); + + write_cert(dir.path(), "example.com", "old"); + assert_eq!( + manager.get_cert_for_domain("example.com").await.cert_pem, + b"old-cert" + ); + + write_cert(dir.path(), "example.com", "new"); + assert_eq!( + manager.get_cert_for_domain("example.com").await.cert_pem, + b"new-cert" + ); + } + + #[tokio::test] + async fn keeps_cached_certificate_within_ttl() { + let dir = tempfile::tempdir().unwrap(); + let manager = manager(dir.path(), Duration::from_secs(3600)); + + write_cert(dir.path(), "example.com", "old"); + manager.get_cert_for_domain("example.com").await; + + write_cert(dir.path(), "example.com", "new"); + assert_eq!( + manager.get_cert_for_domain("example.com").await.cert_pem, + b"old-cert" + ); + } + + #[tokio::test] + async fn stops_serving_deleted_certificate() { + let dir = tempfile::tempdir().unwrap(); + let manager = manager(dir.path(), Duration::ZERO); + + write_cert(dir.path(), "example.com", "old"); + manager.get_cert_for_domain("example.com").await; + + fs::remove_file(dir.path().join("certs/example.com.crt")).unwrap(); + let pair = manager.get_cert_for_domain("example.com").await; + assert!(pair == manager.default_cert); + } + + #[tokio::test] + async fn falls_back_to_wildcard_certificate() { + let dir = tempfile::tempdir().unwrap(); + let manager = manager(dir.path(), Duration::ZERO); + + write_cert(dir.path(), "*.example.com", "wild"); + assert_eq!( + manager + .get_cert_for_domain("api.example.com") + .await + .cert_pem, + b"wild-cert" + ); + } + + #[test] + fn rejects_unsafe_sni_names() { + assert!(is_safe_cert_name("example.com")); + assert!(is_safe_cert_name("*.example.com")); + assert!(!is_safe_cert_name("")); + assert!(!is_safe_cert_name("../../etc/passwd")); + assert!(!is_safe_cert_name("a/b")); + assert!(!is_safe_cert_name("a\\b")); + } +} From b96cf890480512af84ebc3852d1dac776c3ef1b0 Mon Sep 17 00:00:00 2001 From: RAHMAT AL ZAMI <112936589+zamibd@users.noreply.github.com> Date: Sat, 5 Dec 2026 00:22:09 +0000 Subject: [PATCH 2/5] fix(settings): saving the error page failed on fresh installs data/templates/ is never created, so saving the custom error page returned 500 on every new installation. The directory is now created on save, and the editor shows the error page actually in use instead of an empty box. The settings page now loads through React Query. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0114BeX74hMZZpCUvVg5iyti --- src/api/handlers/stats.rs | 13 ++- web/src/components/dashboard/SettingsTab.tsx | 111 ++++++++++--------- 2 files changed, 71 insertions(+), 53 deletions(-) diff --git a/src/api/handlers/stats.rs b/src/api/handlers/stats.rs index be952ba..2da52c4 100644 --- a/src/api/handlers/stats.rs +++ b/src/api/handlers/stats.rs @@ -66,8 +66,11 @@ pub async fn get_logs( Ok(Json(lines)) } -pub async fn get_error_page(_: Claims) -> String { - fs::read_to_string("data/templates/error.html").unwrap_or_default() +const ERROR_PAGE_PATH: &str = "data/templates/error.html"; + +/// Returns the error page currently in use (the built-in default until one is saved). +pub async fn get_error_page(_: Claims, State(state): State) -> String { + state.app_state.error_template.load().as_ref().clone() } pub async fn update_error_page( @@ -82,7 +85,11 @@ pub async fn update_error_page( )); } - fs::write("data/templates/error.html", &payload.html)?; + // data/templates/ does not exist on a fresh install. + if let Some(dir) = Path::new(ERROR_PAGE_PATH).parent() { + fs::create_dir_all(dir)?; + } + fs::write(ERROR_PAGE_PATH, &payload.html)?; // Audit log let _ = db::insert_audit_log( diff --git a/web/src/components/dashboard/SettingsTab.tsx b/web/src/components/dashboard/SettingsTab.tsx index c63b869..a79a358 100644 --- a/web/src/components/dashboard/SettingsTab.tsx +++ b/web/src/components/dashboard/SettingsTab.tsx @@ -1,5 +1,6 @@ -import { useState, useEffect } from "react"; +import { useEffect, useState } from "react"; import { useTranslation } from "react-i18next"; +import { useMutation, useQuery } from "@tanstack/react-query"; import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card"; import { Button } from "@/components/ui/button"; import { Textarea } from "@/components/ui/textarea"; @@ -7,41 +8,18 @@ import { toast } from "sonner"; import { RefreshCw, Save } from "lucide-react"; import { api } from "@/lib/api"; +const ERROR_PAGE_PATH = "/settings/error-page"; + export function SettingsTab() { const { t } = useTranslation(); - const [html, setHtml] = useState(""); - const [loading, setLoading] = useState(false); + const { data, dataUpdatedAt, isError, isFetching, refetch } = useQuery({ + queryKey: ["settings", "error-page"], + queryFn: async () => (await api.request(ERROR_PAGE_PATH)) || "", + }); useEffect(() => { - fetchErrorPage(); - }, []); - - const fetchErrorPage = async () => { - setLoading(true); - try { - const content = await api.request("/settings/error-page"); - setHtml(content || ""); - } catch { - toast.error(t('settings.loadError')); - } finally { - setLoading(false); - } - }; - - const handleSave = async () => { - setLoading(true); - try { - await api.request("/settings/error-page", { - method: "POST", - body: JSON.stringify({ html }), - }); - toast.success(t('settings.updateSuccess')); - } catch { - toast.error(t('settings.updateError')); - } finally { - setLoading(false); - } - }; + if (isError) toast.error(t('settings.loadError')); + }, [isError, t]); return (
@@ -53,26 +31,59 @@ export function SettingsTab() { -
-