Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

18 changes: 15 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -80,11 +80,23 @@ openssl = { version = "0.10", features = ["vendored"] }
# across the whole dep tree so cross-compiling to Linux/Windows works without a
# system sqlite3 library present on the host Mac.
rusqlite = { version = "*", features = ["bundled"] }
# Per-IP connection tracking for rate limiting (Phase 2 — C-4).
# DashMap is a concurrent hash map with fine-grained shard locking; it avoids
# the single global Mutex that would serialise every accept() call.
dashmap = "6"

[dev-dependencies]
tempfile = "3"

[profile.dev.package."*"]
opt-level = 1 # dependency builds: faster compile, smaller debug symbols

[profile.dev]
opt-level = 0
debug = true

[profile.release]
opt-level = 3
lto = true
strip = true
opt-level = 3
lto = true
strip = true
codegen-units = 1 # maximum optimisation; slower link but smaller/faster binary
52 changes: 52 additions & 0 deletions src/config/loader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,22 @@ fn validate(cfg: &Config) -> Result<()> {
));
}

// Phase 2 (C-4) — validate per-IP connection limit.
//
// max_connections_per_ip = 0 would make every connection fail immediately
// (the CAS loop can never increment past the limit of zero).
// max_connections_per_ip > max_connections means the per-IP guard can
// never be the binding constraint, making it useless.
if cfg.server.max_connections_per_ip == 0 {
errors.push("[server] max_connections_per_ip must be at least 1".into());
}
if cfg.server.max_connections_per_ip > cfg.server.max_connections {
errors.push(format!(
"[server] max_connections_per_ip ({}) must be ≤ max_connections ({})",
cfg.server.max_connections_per_ip, cfg.server.max_connections
));
}

// [site]
// `index_file` must be a bare filename, not a path.
// Use Path::components() rather than checking for MAIN_SEPARATOR:
Expand Down Expand Up @@ -154,6 +170,41 @@ mod tests {
assert!(validate(&valid()).is_ok());
}

// ── validate — [server] max_connections_per_ip ───────────────────────────

#[test]
fn validate_max_connections_per_ip_zero_is_rejected() {
let mut cfg = valid();
cfg.server.max_connections_per_ip = 0;
let result = validate(&cfg);
assert!(
matches!(&result, Err(AppError::ConfigValidation(e))
if e.iter().any(|s| s.contains("max_connections_per_ip"))),
"expected ConfigValidation error mentioning max_connections_per_ip, got: {result:?}"
);
}

#[test]
fn validate_max_connections_per_ip_exceeds_max_connections() {
let mut cfg = valid();
cfg.server.max_connections = 32;
cfg.server.max_connections_per_ip = 64; // > max_connections
let result = validate(&cfg);
assert!(
matches!(&result, Err(AppError::ConfigValidation(e))
if e.iter().any(|s| s.contains("max_connections_per_ip"))),
"expected ConfigValidation error mentioning max_connections_per_ip, got: {result:?}"
);
}

#[test]
fn validate_max_connections_per_ip_equal_to_max_connections_is_ok() {
let mut cfg = valid();
cfg.server.max_connections = 32;
cfg.server.max_connections_per_ip = 32; // equal is permitted
assert!(validate(&cfg).is_ok());
}

// ── validate — [site] directory ─────────────────────────────────────────

#[test]
Expand Down Expand Up @@ -241,6 +292,7 @@ bind = "127.0.0.1"
auto_port_fallback = true
open_browser_on_start = false
max_connections = 256
max_connections_per_ip = 16
csp_level = "off"
{extra}

Expand Down
21 changes: 21 additions & 0 deletions src/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -146,13 +146,33 @@ pub struct ServerConfig {
pub open_browser_on_start: bool,
pub max_connections: u32,

/// Maximum concurrent connections from a single IP address.
///
/// Prevents a single client from monopolising the connection pool (C-4).
/// When the limit is reached the connection is dropped at the TCP level —
/// the OS sends a RST so no HTTP overhead is incurred.
///
/// Must be ≥ 1 and ≤ `max_connections`. Validated in `loader.rs`.
/// Defaults to 16, which is generous for browsers (typically 6–8 parallel
/// connections) while preventing trivial single-client exhaustion attacks.
#[serde(default = "default_max_connections_per_ip")]
pub max_connections_per_ip: u32,

/// Content-Security-Policy preset. See [`CspLevel`] for available values
/// (`"off"`, `"relaxed"`, `"strict"`) and the header each one sends.
/// Defaults to `"off"` — no CSP header, maximum browser compatibility.
#[serde(default)]
pub csp_level: CspLevel,
}

/// Default per-IP connection limit.
///
/// 16 is generous for browsers (6–8 parallel connections per origin) while
/// making single-client `DoS` impractical without cooperation from many IPs.
const fn default_max_connections_per_ip() -> u32 {
16
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SiteConfig {
Expand Down Expand Up @@ -229,6 +249,7 @@ impl Default for Config {
auto_port_fallback: true,
open_browser_on_start: false,
max_connections: 256,
max_connections_per_ip: default_max_connections_per_ip(),
csp_level: CspLevel::Strict,
},
site: SiteConfig {
Expand Down
22 changes: 22 additions & 0 deletions src/logging/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,28 @@ pub fn init(config: &LoggingConfig, data_dir: &Path) -> Result<()> {
use std::os::unix::fs::PermissionsExt;
let _ = std::fs::set_permissions(parent, std::fs::Permissions::from_mode(0o700));
}
// Phase 2 (H-5) — enforce owner-only access on Windows as well.
// Default directory creation on Windows inherits the parent ACL,
// which is typically world-readable on consumer machines.
// `icacls /inheritance:r` removes inherited ACEs; the `/grant:r`
// grants Full Control only to the current user.
#[cfg(windows)]
{
if let Ok(whoami_out) = std::process::Command::new("whoami").output() {
let user = String::from_utf8_lossy(&whoami_out.stdout)
.trim()
.to_owned();
let path_str = parent.to_string_lossy();
let _ = std::process::Command::new("icacls")
.args([
path_str.as_ref(),
"/inheritance:r",
"/grant:r",
&format!("{user}:(OI)(CI)F"),
])
.output();
}
}
}

// fix G-1 — open with explicit 0o600 mode (owner read/write only).
Expand Down
45 changes: 31 additions & 14 deletions src/runtime/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,19 +18,36 @@ pub mod state;
/// Single canonical definition extracted from `lifecycle.rs` and `events.rs`
/// to eliminate the duplicated function (fix 2.4). Any future fix — URL
/// sanitisation, logging, sandboxing — needs to be applied here only.
///
/// Phase 2 (H-7): spawn errors are now logged at `warn` level rather than
/// silently discarded. A missing `open`/`xdg-open`/`cmd` binary is a
/// recoverable condition (the server continues to run), but swallowing the
/// error made it impossible to diagnose why the browser never appeared.
pub fn open_browser(url: &str) {
#[cfg(target_os = "macos")]
let _ = std::process::Command::new("open").arg(url).spawn();
// `explorer.exe <url>` is unreliable — on some Windows configurations it
// opens File Explorer instead of the default browser. `cmd /c start`
// delegates to the Windows shell association table, which always picks the
// correct handler. The empty-string third argument is required to prevent
// `start` from treating the URL (which may contain special chars) as the
// window title.
#[cfg(target_os = "windows")]
let _ = std::process::Command::new("cmd")
.args(["/c", "start", "", url])
.spawn();
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
let _ = std::process::Command::new("xdg-open").arg(url).spawn();
let result = {
#[cfg(target_os = "macos")]
{
std::process::Command::new("open").arg(url).spawn()
}
// `explorer.exe <url>` is unreliable — on some Windows configurations it
// opens File Explorer instead of the default browser. `cmd /c start`
// delegates to the Windows shell association table, which always picks the
// correct handler. The empty-string third argument is required to prevent
// `start` from treating the URL (which may contain special chars) as the
// window title.
#[cfg(target_os = "windows")]
{
std::process::Command::new("cmd")
.args(["/c", "start", "", url])
.spawn()
}
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
{
std::process::Command::new("xdg-open").arg(url).spawn()
}
};

if let Err(e) = result {
log::warn!("Could not open browser at {url}: {e}");
}
}
Loading