diff --git a/pkgs/fleet/Cargo.lock b/pkgs/fleet/Cargo.lock index d6aaf008d1..b53840e5c0 100644 --- a/pkgs/fleet/Cargo.lock +++ b/pkgs/fleet/Cargo.lock @@ -565,6 +565,7 @@ version = "0.1.0" dependencies = [ "fleet-config", "fleet-secrets", + "libc", "proptest", "serde", "serde_json", diff --git a/pkgs/fleet/crates/fleet-queue/Cargo.toml b/pkgs/fleet/crates/fleet-queue/Cargo.toml index d6d9e976d3..d36e0c22aa 100644 --- a/pkgs/fleet/crates/fleet-queue/Cargo.toml +++ b/pkgs/fleet/crates/fleet-queue/Cargo.toml @@ -13,8 +13,8 @@ description = "The fleet queue domain: the repo-queue client surface plus the qu # standalone artifact. [features] client = ["dep:fleet-config"] -queue-broker = ["client", "dep:tiny_http", "dep:ureq", "dep:fleet-config"] -secrets-broker = ["dep:tiny_http", "dep:fleet-config"] +queue-broker = ["client", "dep:tiny_http", "dep:ureq", "dep:fleet-config", "dep:libc"] +secrets-broker = ["dep:tiny_http", "dep:fleet-config", "dep:libc"] [dependencies] fleet-secrets = { workspace = true } @@ -25,6 +25,8 @@ serde = { workspace = true } # built serde_json the same way). serde_json = { version = "1", features = ["preserve_order"] } tiny_http = { version = "0.12", optional = true } +# uds_http's bind lock (flock) — #6515. +libc = { version = "0.2", optional = true } ureq = { version = "3", features = ["rustls", "json"], optional = true } # Standalone artifacts — the migration's rollback inventory (design diff --git a/pkgs/fleet/crates/fleet-queue/src/queue_broker.rs b/pkgs/fleet/crates/fleet-queue/src/queue_broker.rs index 46d770979e..a5cf201164 100644 --- a/pkgs/fleet/crates/fleet-queue/src/queue_broker.rs +++ b/pkgs/fleet/crates/fleet-queue/src/queue_broker.rs @@ -895,6 +895,36 @@ fn token_matches(provided: Option<&str>, expected: &str) -> bool { provided.map(|v| v == expected).unwrap_or(false) } +/// Pre-body gate for the broker transports (#6515, PR #6514 thread +/// 4492609604). Oracle: an unauthorized or oversized request is +/// refused from its headers alone, before a single body byte is +/// read — an unauthenticated client can no longer stream a large or +/// unfinished body and hold the connection until the handler's 401. +/// Returns the refusal to send, or `None` to proceed to the body. +/// The only unauthenticated route is the health probe, mirroring +/// `handle_request`. +fn pre_body_refusal( + method: &str, + target: &str, + provided_token: Option<&str>, + token: &str, + content_length: Option, +) -> Option<(u16, Value)> { + let path = target.split('?').next().unwrap_or(""); + if method == "GET" && path == "/healthz" { + return None; + } + if !token_matches(provided_token, token) { + return Some((401, json!({"error": "unauthorized"}))); + } + if let Some(n) = content_length { + if n > crate::uds_http::MAX_BODY_BYTES as u64 { + return Some((413, json!({"error": "request body too large"}))); + } + } + None +} + /// Transport-agnostic request handling (#6216): the TCP loop adapts /// tiny_http requests to this function and the UDS loop adapts /// Unix-socket requests; routes and auth are identical on both @@ -929,6 +959,7 @@ fn handle_request( } pub fn run() -> i32 { + use std::io::Read as _; let bind = std::env::var("QUEUE_BROKER_BIND").unwrap_or_else(|_| "100.99.113.103:4801".to_string()); let home = crate::home::from_env().unwrap_or_else(|error| { @@ -1047,20 +1078,43 @@ pub fn run() -> i32 { &format!("listening on uds {}", socket_path.display()), ); std::thread::spawn(move || { - crate::uds_http::serve(listener, move |req| { - let (status, value) = handle_request( - &st, - &tok, - &req.method, - &req.target, - req.header("X-Agent-Token"), - &req.body, - ); - ( - status, - serde_json::to_vec(&value).unwrap_or_else(|_| b"{}".to_vec()), - ) - }); + let pre_tok = tok.clone(); + crate::uds_http::serve_with_precheck( + listener, + move |head| { + // #6515: same pre-body gate as the TCP loop. + let content_length = head + .header("Content-Length") + .and_then(|v| v.parse::().ok()); + pre_body_refusal( + &head.method, + &head.target, + head.header("X-Agent-Token"), + &pre_tok, + content_length, + ) + .map(|(status, value)| { + ( + status, + serde_json::to_vec(&value).unwrap_or_else(|_| b"{}".to_vec()), + ) + }) + }, + move |req| { + let (status, value) = handle_request( + &st, + &tok, + &req.method, + &req.target, + req.header("X-Agent-Token"), + &req.body, + ); + ( + status, + serde_json::to_vec(&value).unwrap_or_else(|_| b"{}".to_vec()), + ) + }, + ); }); } Ok(None) => crate::log::info( @@ -1087,9 +1141,40 @@ pub fn run() -> i32 { .iter() .find(|h| h.field.as_str().to_ascii_lowercase() == "x-agent-token") .map(|h| h.value.as_str().to_string()); + // #6515: authenticate and size-check from the headers + // before reading any body byte. tiny_http 0.12 exposes + // no per-connection read timeout, so the residual TCP + // slow-body risk is bounded by this gate plus the capped + // read below and thread-per-connection isolation; the + // UDS transport carries real read timeouts (uds_http). + let content_length = req + .headers() + .iter() + .find(|h| h.field.as_str().to_ascii_lowercase() == "content-length") + .and_then(|h| h.value.as_str().parse::().ok()); + if let Some((status, value)) = pre_body_refusal( + &method, + &target, + provided.as_deref(), + &token, + content_length, + ) { + let _ = req.respond(json_response(status, value)); + return; + } let mut body = Vec::new(); if method == "POST" { - let _ = req.as_reader().read_to_end(&mut body); + // Capped read: cap+1 bytes detect an overrun that + // the declared length hid (or never declared). + let cap = (crate::uds_http::MAX_BODY_BYTES + 1) as u64; + let _ = req.as_reader().take(cap).read_to_end(&mut body); + if body.len() > crate::uds_http::MAX_BODY_BYTES { + let _ = req.respond(json_response( + 413, + json!({"error": "request body too large"}), + )); + return; + } } let (status, value) = handle_request(&state, &token, &method, &target, provided.as_deref(), &body); @@ -1104,6 +1189,40 @@ pub fn run() -> i32 { mod tests { use super::*; + #[test] + fn pre_body_refusal_decides_from_headers_alone() { + // #6515 oracle (thread 4492609604): the gate's answer + // depends only on method/target/token/declared length — + // never on body bytes — so an unauthorized or oversized + // request is refused before its body is read. + let over = crate::uds_http::MAX_BODY_BYTES as u64 + 1; + // Unauthorized: refused even with an enormous declared body. + assert_eq!( + pre_body_refusal("POST", "/claim", None, "tok", Some(over)).map(|r| r.0), + Some(401) + ); + assert_eq!( + pre_body_refusal("POST", "/claim", Some("wrong"), "tok", None).map(|r| r.0), + Some(401) + ); + // Authorized but oversized: 413. + assert_eq!( + pre_body_refusal("POST", "/claim", Some("tok"), "tok", Some(over)).map(|r| r.0), + Some(413) + ); + // Authorized and within cap (or undeclared): proceeds. + assert_eq!( + pre_body_refusal("POST", "/claim", Some("tok"), "tok", Some(2)), + None + ); + assert_eq!( + pre_body_refusal("POST", "/claim", Some("tok"), "tok", None), + None + ); + // The health probe stays unauthenticated, as in handle_request. + assert_eq!(pre_body_refusal("GET", "/healthz", None, "tok", None), None); + } + #[test] fn secrets_url_explicit_wins_and_default_is_a_known_endpoint() { // #6218: QUEUE_BROKER_SECRETS_URL beats probe selection in diff --git a/pkgs/fleet/crates/fleet-queue/src/secrets_broker.rs b/pkgs/fleet/crates/fleet-queue/src/secrets_broker.rs index e75223e3a1..35f3f9378d 100644 --- a/pkgs/fleet/crates/fleet-queue/src/secrets_broker.rs +++ b/pkgs/fleet/crates/fleet-queue/src/secrets_broker.rs @@ -332,6 +332,34 @@ fn token_matches(provided: Option<&str>, expected: &str) -> bool { provided.map(|v| v == expected).unwrap_or(false) } +/// Pre-body gate for the broker transports (#6515, PR #6514 thread +/// 4492609604). Oracle: an unauthorized or oversized request is +/// refused from its headers alone, before a single body byte is +/// read. Returns the refusal to send, or `None` to proceed to the +/// body. The only unauthenticated route is the health probe, +/// mirroring `handle_request`. +fn pre_body_refusal( + method: &str, + target: &str, + provided_token: Option<&str>, + token: &str, + content_length: Option, +) -> Option<(u16, Value)> { + let path = target.split('?').next().unwrap_or(""); + if method == "GET" && path == "/health" { + return None; + } + if !token_matches(provided_token, token) { + return Some((401, json!({"error": "unauthorized"}))); + } + if let Some(n) = content_length { + if n > crate::uds_http::MAX_BODY_BYTES as u64 { + return Some((413, json!({"error": "request body too large"}))); + } + } + None +} + /// Transport-agnostic request handling (#6216): the TCP loop adapts /// tiny_http requests to this function and the UDS loop adapts /// Unix-socket requests; routes and auth are identical on both @@ -398,6 +426,7 @@ fn handle_request( } pub fn run() -> i32 { + use std::io::Read as _; let bind = std::env::var("SECRETS_BROKER_BIND").unwrap_or_else(|_| "100.99.113.103:4800".to_string()); let home = crate::home::from_env().unwrap_or_else(|error| { @@ -427,14 +456,12 @@ pub fn run() -> i32 { // and a failed refresh keeps the old values). { let state = Arc::clone(&state); - std::thread::spawn(move || { - loop { - match refresh(&state) { - Ok(n) => crate::log::info("secrets-broker", &format!("refreshed {n} secrets")), - Err(e) => crate::log::info("secrets-broker", &format!("refresh failed: {e}")), - } - std::thread::sleep(Duration::from_secs(ttl_s)); + std::thread::spawn(move || loop { + match refresh(&state) { + Ok(n) => crate::log::info("secrets-broker", &format!("refreshed {n} secrets")), + Err(e) => crate::log::info("secrets-broker", &format!("refresh failed: {e}")), } + std::thread::sleep(Duration::from_secs(ttl_s)); }); } @@ -459,19 +486,42 @@ pub fn run() -> i32 { &format!("listening on uds {}", socket_path.display()), ); std::thread::spawn(move || { - crate::uds_http::serve(listener, move |req| { - let (status, value) = handle_request( - &st, - &tok, - &req.method, - &req.target, - req.header("X-Agent-Token"), - ); - ( - status, - serde_json::to_vec(&value).unwrap_or_else(|_| b"{}".to_vec()), - ) - }); + let pre_tok = tok.clone(); + crate::uds_http::serve_with_precheck( + listener, + move |head| { + // #6515: same pre-body gate as the TCP loop. + let content_length = head + .header("Content-Length") + .and_then(|v| v.parse::().ok()); + pre_body_refusal( + &head.method, + &head.target, + head.header("X-Agent-Token"), + &pre_tok, + content_length, + ) + .map(|(status, value)| { + ( + status, + serde_json::to_vec(&value).unwrap_or_else(|_| b"{}".to_vec()), + ) + }) + }, + move |req| { + let (status, value) = handle_request( + &st, + &tok, + &req.method, + &req.target, + req.header("X-Agent-Token"), + ); + ( + status, + serde_json::to_vec(&value).unwrap_or_else(|_| b"{}".to_vec()), + ) + }, + ); }); } Ok(None) => crate::log::info( @@ -497,11 +547,37 @@ pub fn run() -> i32 { .iter() .find(|h| h.field.as_str().to_ascii_lowercase() == "x-agent-token") .map(|h| h.value.as_str().to_string()); + // #6515: authenticate and size-check from the headers + // before draining any body byte (tiny_http 0.12 exposes + // no per-connection read timeout; see queue_broker). + let content_length = req + .headers() + .iter() + .find(|h| h.field.as_str().to_ascii_lowercase() == "content-length") + .and_then(|h| h.value.as_str().parse::().ok()); + if let Some((status, value)) = pre_body_refusal( + req.method().as_str(), + &url, + provided.as_deref(), + &token, + content_length, + ) { + let _ = req.respond(json_response(status, value)); + return; + } if req.method().as_str() == "POST" { // POST /refresh's body is ignored by the handler; - // drain it as the pre-#6216 loop did. - let mut buf = String::new(); - let _ = req.as_reader().read_to_string(&mut buf); + // drain it (capped, #6515) as the pre-#6216 loop did. + let cap = (crate::uds_http::MAX_BODY_BYTES + 1) as u64; + let mut buf = Vec::new(); + let _ = req.as_reader().take(cap).read_to_end(&mut buf); + if buf.len() > crate::uds_http::MAX_BODY_BYTES { + let _ = req.respond(json_response( + 413, + json!({"error": "request body too large"}), + )); + return; + } } let (status, value) = handle_request( &state, @@ -541,7 +617,33 @@ fn url_decode(s: &str) -> String { #[cfg(test)] mod tests { - use super::{State, fetch_through_with, parse_list_entries, resolve_list_id, url_decode}; + use super::{ + fetch_through_with, parse_list_entries, pre_body_refusal, resolve_list_id, url_decode, + State, + }; + + #[test] + fn pre_body_refusal_decides_from_headers_alone() { + // #6515 oracle (thread 4492609604): the gate's answer + // depends only on method/target/token/declared length — + // never on body bytes — so an unauthorized or oversized + // request is refused before its body is read. + let over = crate::uds_http::MAX_BODY_BYTES as u64 + 1; + assert_eq!( + pre_body_refusal("POST", "/refresh", None, "tok", Some(over)).map(|r| r.0), + Some(401) + ); + assert_eq!( + pre_body_refusal("POST", "/refresh", Some("tok"), "tok", Some(over)).map(|r| r.0), + Some(413) + ); + assert_eq!( + pre_body_refusal("POST", "/refresh", Some("tok"), "tok", Some(0)), + None + ); + // The health probe stays unauthenticated, as in handle_request. + assert_eq!(pre_body_refusal("GET", "/health", None, "tok", None), None); + } use proptest::prelude::*; use std::collections::HashMap; use std::sync::atomic::{AtomicUsize, Ordering}; diff --git a/pkgs/fleet/crates/fleet-queue/src/uds_http.rs b/pkgs/fleet/crates/fleet-queue/src/uds_http.rs index b4f5c94b9d..e3bedc08ab 100644 --- a/pkgs/fleet/crates/fleet-queue/src/uds_http.rs +++ b/pkgs/fleet/crates/fleet-queue/src/uds_http.rs @@ -22,13 +22,32 @@ //! no meaningful request body. use std::io::{Read, Write}; -use std::os::unix::fs::PermissionsExt; +use std::os::unix::fs::{FileTypeExt, PermissionsExt}; use std::os::unix::net::{UnixListener, UnixStream}; use std::path::Path; +use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; +use std::time::Duration; const MAX_HEAD_BYTES: usize = 64 * 1024; -const MAX_BODY_BYTES: usize = 16 * 1024 * 1024; +/// Largest request body either broker accepts, on any transport +/// (#6515). A declared Content-Length above this is rejected before +/// the body is read — never clamped, which would dispatch a silently +/// truncated request (PR #6514 thread 4492609738). +pub(crate) const MAX_BODY_BYTES: usize = 16 * 1024 * 1024; +/// Per-connection read/write timeout (#6515, PR #6514 thread +/// 4492609760): a peer that stalls mid-request loses its connection +/// instead of holding a serve thread forever. +pub(crate) const READ_TIMEOUT: Duration = Duration::from_secs(30); +/// Bound on simultaneous UDS connections (#6515, thread 4492609760): +/// past this, new connections are dropped until a slot frees. +const MAX_CONNECTIONS: usize = 128; +/// How long the stale-socket probe waits for a connect to resolve +/// before assuming a live owner (#6515, thread 4492609644). A unix +/// connect to a live listener completes immediately; a full backlog +/// can block indefinitely, and an uncertain probe must never steal +/// the socket — timeout reads as "live". +const PROBE_TIMEOUT: Duration = Duration::from_secs(2); /// One parsed HTTP request, transport-agnostic. pub struct HttpRequest { @@ -49,24 +68,91 @@ impl HttpRequest { } } +/// RAII guard for the bind lock file: flock held until drop. +struct BindLock(std::fs::File); + +fn bind_lock(path: &Path) -> std::io::Result { + // Serialize probe/unlink/bind across concurrent starters (#6515, + // PR #6514 thread 4492609657): without this, two starters can both + // probe a stale socket, and the second one's unlink can remove + // the socket the first one just bound live. + let lock_path = path.with_file_name(format!( + "{}.bind-lock", + path.file_name().unwrap_or_default().to_string_lossy() + )); + let file = std::fs::OpenOptions::new() + .create(true) + .write(true) + .truncate(false) + .open(&lock_path)?; + let rc = unsafe { libc::flock(std::os::unix::io::AsRawFd::as_raw_fd(&file), libc::LOCK_EX) }; + if rc != 0 { + return Err(std::io::Error::last_os_error()); + } + Ok(BindLock(file)) +} + +fn probe_live(path: &Path) -> bool { + // Bound the live-owner probe (#6515, thread 4492609644): run the + // connect on a side thread and wait at most PROBE_TIMEOUT. A + // timeout (or a dead probe thread) reads as a live owner — the + // safe direction, since stealing is the destructive outcome. + let (tx, rx) = std::sync::mpsc::channel(); + let probe_path = path.to_path_buf(); + std::thread::spawn(move || { + let _ = tx.send(UnixStream::connect(&probe_path).is_ok()); + }); + rx.recv_timeout(PROBE_TIMEOUT).unwrap_or(true) +} + /// Bind `path` as a Unix listener with the fleet-proxy stale-socket /// discipline. `Ok(None)` means a live process already owns the /// socket (connect probe succeeded) — not an error. pub fn bind_socket(path: &Path) -> std::io::Result> { if let Some(parent) = path.parent() { + let parent_existed = parent.exists(); std::fs::create_dir_all(parent)?; - let _ = std::fs::set_permissions(parent, std::fs::Permissions::from_mode(0o700)); + if !parent_existed { + // Only a directory this call created gets its mode set + // (#6515, PR #6514 thread 4492609622): chmod on a + // pre-existing, possibly shared directory would silently + // rewrite the owner's chosen permissions. + let _ = std::fs::set_permissions(parent, std::fs::Permissions::from_mode(0o700)); + } } + let _lock = bind_lock(path)?; if path.exists() { - match UnixStream::connect(path) { - Ok(_) => return Ok(None), - Err(_) => { - let _ = std::fs::remove_file(path); + if probe_live(path) { + return Ok(None); + } + // Stale: unlink only an actual socket file (#6515, PR #6514 + // thread 4492609635). A non-socket file at the socket path is + // someone else's data (e.g. a mispointed override) — refuse, + // never delete it. + match std::fs::symlink_metadata(path) { + Ok(md) if md.file_type().is_socket() => { + std::fs::remove_file(path)?; + } + Ok(_) => { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidInput, + format!( + "{} exists and is not a socket; refusing to remove it", + path.display() + ), + )); } + Err(e) => return Err(e), } } let listener = UnixListener::bind(path)?; - let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)); + // A socket we cannot restrict to owner-only must not be served + // (#6515, PR #6514 thread 4492609673): fail the bind (the caller + // degrades to TCP only) instead of ignoring the chmod error. + if let Err(e) = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)) { + let _ = std::fs::remove_file(path); + return Err(e); + } Ok(Some(listener)) } @@ -78,6 +164,7 @@ fn reason(status: u16) -> &'static str { 401 => "Unauthorized", 404 => "Not Found", 405 => "Method Not Allowed", + 413 => "Payload Too Large", 500 => "Internal Server Error", 502 => "Bad Gateway", 503 => "Service Unavailable", @@ -85,12 +172,24 @@ fn reason(status: u16) -> &'static str { } } -fn read_request(stream: &mut UnixStream) -> Option { - // Read until the header terminator, capping the head size. +/// Read and parse only the request head (request line + headers). +/// Returns the request — with any body bytes that arrived in the +/// same reads parked in `body` — and the declared Content-Length. +/// Splitting head from body is what lets `serve_with_precheck` +/// refuse a request (e.g. unauthenticated, #6515) before a single +/// body byte is consumed. +fn read_head(stream: &mut UnixStream) -> Option<(HttpRequest, usize)> { + // Read until the header terminator, capping the head size. The + // cap applies to the complete header (#6515, PR #6514 thread + // 4492609689): a terminator that only appears past the cap does + // not rescue an oversized head. let mut buf: Vec = Vec::with_capacity(8192); let mut chunk = [0u8; 8192]; let head_end = loop { if let Some(pos) = find(&buf, b"\r\n\r\n") { + if pos + 4 > MAX_HEAD_BYTES { + return None; + } break pos + 4; } if buf.len() > MAX_HEAD_BYTES { @@ -113,9 +212,8 @@ fn read_request(stream: &mut UnixStream) -> Option { // malformed — never "no body", which would dispatch the request // with its body silently dropped — and duplicate headers must // agree. Rejection is `None`: no request, no handler dispatch. - // The oversized-length clamp below is unchanged (#6515 owns the - // clamp semantics); duplicates are compared before clamping. let mut declared_length: Option = None; + let mut has_transfer_encoding = false; for line in lines { if let Some((k, v)) = line.split_once(':') { let (k, v) = (k.trim().to_string(), v.trim().to_string()); @@ -130,62 +228,161 @@ fn read_request(stream: &mut UnixStream) -> Option { } declared_length = Some(parsed); } + if k.eq_ignore_ascii_case("transfer-encoding") { + has_transfer_encoding = true; + } headers.push((k, v)); } } - let content_length = declared_length.map(|n| n.min(MAX_BODY_BYTES)).unwrap_or(0); - let mut body = buf[head_end..].to_vec(); - while body.len() < content_length { + // Chunked (or any) Transfer-Encoding is not decoded on this + // transport (#6515, PR #6514 thread 4492609728): the brokers' + // clients always send Content-Length, so an encoded body is + // rejected outright instead of being misparsed as length-less. + if has_transfer_encoding { + return None; + } + let content_length = declared_length.unwrap_or(0); + // An oversized body is rejected from its declared length, before + // a byte of it is read (#6515, thread 4492609738) — the previous + // clamp dispatched the handler with a silently truncated body. + if content_length > MAX_BODY_BYTES { + return None; + } + let body = buf[head_end..].to_vec(); + Some(( + HttpRequest { + method, + target, + headers, + body, + }, + content_length, + )) +} + +/// Read the rest of the body declared by `read_head`. An incomplete +/// body — the peer closes before the declared length arrives — is +/// rejected, never dispatched truncated (#6515, PR #6514 thread +/// 4492609747). +fn read_body( + stream: &mut UnixStream, + mut req: HttpRequest, + content_length: usize, +) -> Option { + let mut chunk = [0u8; 8192]; + while req.body.len() < content_length { match stream.read(&mut chunk) { - Ok(0) => break, - Ok(n) => body.extend_from_slice(&chunk[..n]), - Err(_) => break, + Ok(0) => return None, + Ok(n) => req.body.extend_from_slice(&chunk[..n]), + Err(_) => return None, } } - body.truncate(content_length); - Some(HttpRequest { - method, - target, - headers, - body, - }) + req.body.truncate(content_length); + Some(req) +} + +fn read_request(stream: &mut UnixStream) -> Option { + let (req, content_length) = read_head(stream)?; + read_body(stream, req, content_length) } fn find(haystack: &[u8], needle: &[u8]) -> Option { haystack.windows(needle.len()).position(|w| w == needle) } -/// Serve `listener` forever: one thread per connection, one request -/// per connection. `handler` returns (status, JSON body bytes) — the -/// same handler the broker's TCP loop adapts tiny_http requests to. +fn write_response(stream: &mut UnixStream, status: u16, body: &[u8]) { + let resp = format!( + "HTTP/1.1 {} {}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + status, + reason(status), + body.len() + ); + let _ = stream.write_all(resp.as_bytes()); + let _ = stream.write_all(body); + let _ = stream.flush(); +} + +/// Serve `listener` forever: one thread per connection (bounded by +/// MAX_CONNECTIONS), one request per connection. `handler` returns +/// (status, JSON body bytes) — the same handler the broker's TCP +/// loop adapts tiny_http requests to. pub fn serve(listener: UnixListener, handler: F) where F: Fn(&HttpRequest) -> (u16, Vec) + Send + Sync + 'static, +{ + serve_inner( + listener, + None:: Option<(u16, Vec)> + Send + Sync>>, + handler, + ); +} + +/// Like `serve`, but `precheck` runs on the parsed head — method, +/// target, headers, no body yet — before the body is read (#6515). +/// `Some((status, body))` from the precheck is the response, sent +/// without consuming the request body; `None` proceeds to body read +/// and the handler. This is how the brokers reject unauthorized +/// UDS requests before reading their bodies. +pub fn serve_with_precheck(listener: UnixListener, precheck: G, handler: F) +where + F: Fn(&HttpRequest) -> (u16, Vec) + Send + Sync + 'static, + G: Fn(&HttpRequest) -> Option<(u16, Vec)> + Send + Sync + 'static, +{ + serve_inner( + listener, + Some(Arc::new(precheck) + as Arc< + dyn Fn(&HttpRequest) -> Option<(u16, Vec)> + Send + Sync, + >), + handler, + ); +} + +fn serve_inner( + listener: UnixListener, + precheck: Option Option<(u16, Vec)> + Send + Sync>>, + handler: F, +) where + F: Fn(&HttpRequest) -> (u16, Vec) + Send + Sync + 'static, { let handler = Arc::new(handler); + let in_flight = Arc::new(AtomicUsize::new(0)); for stream in listener.incoming() { let Ok(mut stream) = stream else { continue }; + // Bound connection resources (#6515, thread 4492609760): + // past the cap the connection is dropped unaccepted-work + // style — closed immediately, no thread spawned. + if in_flight.fetch_add(1, Ordering::SeqCst) >= MAX_CONNECTIONS { + in_flight.fetch_sub(1, Ordering::SeqCst); + continue; + } let handler = Arc::clone(&handler); + let precheck = precheck.clone(); + let in_flight = Arc::clone(&in_flight); std::thread::spawn(move || { - if let Some(req) = read_request(&mut stream) { - let (status, body) = handler(&req); - let resp = format!( - "HTTP/1.1 {} {}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", - status, - reason(status), - body.len() - ); - let _ = stream.write_all(resp.as_bytes()); - let _ = stream.write_all(&body); - let _ = stream.flush(); + let _ = stream.set_read_timeout(Some(READ_TIMEOUT)); + let _ = stream.set_write_timeout(Some(READ_TIMEOUT)); + let outcome = (|| -> Option<(u16, Vec)> { + let (head, content_length) = read_head(&mut stream)?; + if let Some(pre) = &precheck { + if let Some(resp) = pre(&head) { + return Some(resp); + } + } + let req = read_body(&mut stream, head, content_length)?; + Some(handler(&req)) + })(); + if let Some((status, body)) = outcome { + write_response(&mut stream, status, &body); } + in_flight.fetch_sub(1, Ordering::SeqCst); }); } } #[cfg(test)] mod tests { - use super::{bind_socket, serve}; + use super::{bind_socket, serve, serve_with_precheck}; use std::io::{Read, Write}; use std::os::unix::fs::PermissionsExt; use std::os::unix::net::UnixStream; @@ -200,10 +397,12 @@ mod tests { #[test] fn stale_socket_file_does_not_block_bind() { let path = temp_socket("stale"); - std::fs::create_dir_all(path.parent().unwrap()).unwrap(); - // A regular file where the socket would go: the connect probe - // fails, the file is unlinked, and the bind succeeds. - std::fs::write(&path, b"not a socket").unwrap(); + // A dead socket file where the socket would go: bind once + // (which also creates the parent dir), drop the listener — + // the file remains, the connect probe fails, the file is + // unlinked, and the re-bind succeeds. + let first = bind_socket(&path).unwrap().unwrap(); + drop(first); let listener = bind_socket(&path).unwrap(); assert!(listener.is_some()); // Socket 0600, parent dir 0700. @@ -218,6 +417,21 @@ mod tests { let _ = std::fs::remove_dir_all(path.parent().unwrap()); } + #[test] + fn non_socket_file_is_preserved_and_bind_refused() { + // #6515 (PR #6514 thread 4492609635): a regular file at the + // socket path is someone else's data. Oracle: after the bind + // attempt the file's contents are byte-identical and the + // bind failed instead of deleting it. + let path = temp_socket("not-a-socket"); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(&path, b"not a socket").unwrap(); + let result = bind_socket(&path); + assert!(result.is_err(), "bind over a regular file must fail"); + assert_eq!(std::fs::read(&path).unwrap(), b"not a socket"); + let _ = std::fs::remove_dir_all(path.parent().unwrap()); + } + #[test] fn live_socket_is_reported_not_stolen() { let path = temp_socket("live"); @@ -363,6 +577,103 @@ mod tests { let _ = std::fs::remove_dir_all(path.parent().unwrap()); } + // #6515 hardening (PR #6514 threads 4492609738 / 4492609747 / + // 4492609728). Oracle, same shape as the #6527 tests: a rejected + // request gets no response and the handler runs zero times. + + #[test] + fn oversized_content_length_is_rejected_before_the_handler() { + use std::sync::atomic::Ordering; + let (path, calls) = serve_counting("cl-oversized"); + let request = format!( + "POST /healthz HTTP/1.1\r\nHost: uds\r\nContent-Length: {}\r\n\r\n", + super::MAX_BODY_BYTES + 1 + ); + let resp = roundtrip(&path, request.as_bytes()); + assert_eq!(resp, "", "oversized body must get no response, got: {resp}"); + assert_eq!(calls.load(Ordering::SeqCst), 0); + let _ = std::fs::remove_dir_all(path.parent().unwrap()); + } + + #[test] + fn incomplete_body_is_rejected_before_the_handler() { + use std::sync::atomic::Ordering; + let (path, calls) = serve_counting("cl-incomplete"); + // Declare 10 body bytes, send 2, then close the write side: + // the server sees EOF mid-body and must not dispatch the + // truncated request. + let mut stream = UnixStream::connect(&path).unwrap(); + stream + .write_all(b"POST /healthz HTTP/1.1\r\nHost: uds\r\nContent-Length: 10\r\n\r\n{}") + .unwrap(); + stream.shutdown(std::net::Shutdown::Write).unwrap(); + let mut resp = String::new(); + stream.read_to_string(&mut resp).unwrap(); + assert_eq!( + resp, "", + "incomplete body must get no response, got: {resp}" + ); + assert_eq!(calls.load(Ordering::SeqCst), 0); + let _ = std::fs::remove_dir_all(path.parent().unwrap()); + } + + #[test] + fn chunked_transfer_encoding_is_rejected_before_the_handler() { + use std::sync::atomic::Ordering; + let (path, calls) = serve_counting("te-chunked"); + let resp = roundtrip( + &path, + b"POST /healthz HTTP/1.1\r\nHost: uds\r\nTransfer-Encoding: chunked\r\n\r\n2\r\n{}\r\n0\r\n\r\n", + ); + assert_eq!(resp, "", "chunked body must get no response, got: {resp}"); + assert_eq!(calls.load(Ordering::SeqCst), 0); + let _ = std::fs::remove_dir_all(path.parent().unwrap()); + } + + #[test] + fn precheck_refuses_before_the_body_is_consumed() { + // #6515, the TCP finding's UDS twin (thread 4492609604). + // Oracle: the client sends headers declaring a 100-byte body + // and then sends NOTHING — a 401 response still arrives + // promptly, which is only possible if the refusal was made + // from the head alone, before the body was read. + use std::sync::atomic::{AtomicUsize, Ordering}; + let path = temp_socket("precheck-auth"); + let listener = bind_socket(&path).unwrap().unwrap(); + let calls = std::sync::Arc::new(AtomicUsize::new(0)); + let counter = std::sync::Arc::clone(&calls); + std::thread::spawn(move || { + serve_with_precheck( + listener, + |head| { + if head.header("X-Agent-Token") == Some("t0ken") { + None + } else { + Some((401, br#"{"error":"unauthorized"}"#.to_vec())) + } + }, + move |req| { + counter.fetch_add(1, Ordering::SeqCst); + (200, req.body.clone()) + }, + ); + }); + let mut stream = UnixStream::connect(&path).unwrap(); + stream + .set_read_timeout(Some(std::time::Duration::from_secs(5))) + .unwrap(); + stream + .write_all(b"POST /claim HTTP/1.1\r\nHost: uds\r\nContent-Length: 100\r\n\r\n") + .unwrap(); + // No body bytes are ever sent. The 401 must arrive anyway. + let mut buf = [0u8; 512]; + let n = stream.read(&mut buf).expect("401 arrives without a body"); + let resp = String::from_utf8_lossy(&buf[..n]).into_owned(); + assert!(resp.starts_with("HTTP/1.1 401"), "resp: {resp}"); + assert_eq!(calls.load(Ordering::SeqCst), 0); + let _ = std::fs::remove_dir_all(path.parent().unwrap()); + } + // Property-based coverage of the #6527 Content-Length invariants // (Codex review on PR #6529; the oracle is the invariant itself, // per the repo testing doctrine — the fixed examples above stay