From 18de6e23d3f86534acdc35f32d334b9d3c8b2b9f Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 08:57:27 +0200 Subject: [PATCH 1/7] fix(repo): bound filtered tree walks by object count, not path count walk_tree_sized deduped expansion by (tree id, path) under a filter. A chain of N trees whose two entries name the same child is a few KB with 2^N distinct paths, so one PutObject chain made every filtered GetPack (a blob:limit clone or fetch, scope = every path) read 2^N trees. A verdict depends on the path only while a directory is a strict ancestor of a filter prefix. Once a directory matches the scope, every descendant does too, so its expansion key drops the path and it is read once by id. Path-bound keys remain only for prefix ancestors and roots. Test: on the unfixed walk a 20-level chain read 2097152 objects (9 s); the 18-level test now asserts under 2 * levels + 8 reads. --- crates/repo/src/reachable.rs | 121 ++++++++++++++++++++++++++++++++--- 1 file changed, 112 insertions(+), 9 deletions(-) diff --git a/crates/repo/src/reachable.rs b/crates/repo/src/reachable.rs index 6406add1..850d44b1 100644 --- a/crates/repo/src/reachable.rs +++ b/crates/repo/src/reachable.rs @@ -80,7 +80,7 @@ pub(crate) fn walk_tree( let mut gaps = BTreeSet::new(); // `filter = None` never consults `expanded` (see the bare-id gate below), // so a throwaway empty set is correct and harmless here. - let mut expanded = HashSet::new(); + let mut expanded = Expanded::new(); walk_tree_filtered(src, root, seen, &mut gaps, None, &mut expanded) } @@ -100,6 +100,26 @@ pub trait PrefixFilter { fn should_descend(&self, path: &str) -> bool; } +/// Trees already pushed for expansion under a filter, keyed by +/// [`expansion_key`]. +type Expanded = HashSet<(ObjectId, Option)>; + +/// The expansion identity of tree `id` at `path`. A verdict depends on the +/// path only while `path` is a strict ancestor of a filter prefix. A non-root +/// path that `matches` is wholly in scope (every descendant matches too: the +/// `/`-boundary prefix rule a [`PrefixFilter`] must keep), so its key drops +/// the path. Without that, a chain of trees whose two entries name the same +/// child has `2^depth` distinct paths for `depth` objects, and one hostile +/// `PutObject` chain would make every filtered walk exponential. Path-bound +/// keys stay few: only the ancestors of a prefix, plus roots, carry one. +fn expansion_key(f: &dyn PrefixFilter, id: ObjectId, path: &str) -> (ObjectId, Option) { + if !path.is_empty() && f.matches(path) { + (id, None) + } else { + (id, Some(path.to_owned())) + } +} + impl PrefixFilter for crate::promisor::Promisor { fn matches(&self, path: &str) -> bool { crate::promisor::Promisor::matches(self, path) @@ -186,7 +206,7 @@ pub fn reachable_objects_limited( // expanded at its own (root, "") path — see `walk_tree_filtered`'s doc // comment for why a bare-id gate on the root is wrong under a filter // (C1, P27 final review). - let mut expanded: HashSet<(ObjectId, String)> = HashSet::new(); + let mut expanded = Expanded::new(); let mut included = walk_snapshots(src, tips, |src, snapshot, root, included| { let mut gate = blob_limit.map(|limit| SizeGate { limit, @@ -410,8 +430,10 @@ pub fn filter_manifest_wants( /// in-filter content that's ONLY reachable via a second, later path (the /// first path's out-of-filter verdict wins by accident of traversal /// order). So under a filter, expansion is gated on the `(id, path)` pair -/// instead — `included` still dedups by bare id for the *result*, since an -/// id counts as held once regardless of how many paths reach it. +/// instead (see [`expansion_key`]: the path part is dropped once a directory +/// is wholly in scope, which bounds the walk by the object count rather than +/// the path count) — `included` still dedups by bare id for the *result*, +/// since an id counts as held once regardless of how many paths reach it. /// /// `expanded` is owned by the caller and spans the WHOLE reachability walk /// (every tip/snapshot in one `reachable_objects_filtered` call), not just @@ -432,7 +454,7 @@ fn walk_tree_filtered( included: &mut BTreeSet, gaps: &mut BTreeSet, filter: Option<&dyn PrefixFilter>, - expanded: &mut HashSet<(ObjectId, String)>, + expanded: &mut Expanded, ) -> Result<()> { walk_tree_sized(src, root, included, gaps, filter, expanded, None) } @@ -474,7 +496,7 @@ fn walk_tree_sized( included: &mut BTreeSet, gaps: &mut BTreeSet, filter: Option<&dyn PrefixFilter>, - expanded: &mut HashSet<(ObjectId, String)>, + expanded: &mut Expanded, mut size: Option<&mut SizeGate<'_>>, ) -> Result<()> { let mut stack: Vec<(ObjectId, String)> = Vec::new(); @@ -484,9 +506,9 @@ fn walk_tree_sized( stack.push((root, String::new())); } } - Some(_) => { + Some(f) => { included.insert(root); - if expanded.insert((root, String::new())) { + if expanded.insert(expansion_key(f, root, "")) { stack.push((root, String::new())); } } @@ -532,7 +554,7 @@ fn walk_tree_sized( Some(f) => { if f.should_descend(&child_path) { included.insert(e.id); - if expanded.insert((e.id, child_path.clone())) { + if expanded.insert(expansion_key(f, e.id, &child_path)) { stack.push((e.id, child_path)); } } else { @@ -1111,4 +1133,85 @@ mod tests { s.delete(&snap_id).unwrap(); assert!(reachable_objects_partial(&mut s, &[snap_id]).is_err()); } + + /// Counts object reads so a walk's work is observable without a test seam. + struct CountingSource { + store: Store, + gets: usize, + } + + impl ObjectSource for CountingSource { + fn get(&mut self, id: &ObjectId) -> Result { + self.gets += 1; + Ok(Store::get(&mut self.store, id)?) + } + } + + /// `levels` trees where each holds two entries ("a", "b") naming the next + /// tree: a few KB on the wire, `2^levels` distinct paths. Returns the + /// snapshot id. + fn diamond_chain(store: &mut Store, levels: usize) -> ObjectId { + let leaf = store.put(Object::blob(b"x".to_vec())).unwrap(); + let entry = |name: &str, kind, id| scl_core::TreeEntry { + name: name.into(), + kind, + id, + mode: scl_core::FileMode::FILE, + perms: 0, + }; + let mut next = store + .put(Object::Tree(scl_core::Tree::new(vec![entry( + "f", + EntryKind::Blob, + leaf, + )]))) + .unwrap(); + for _ in 0..levels { + next = store + .put(Object::Tree(scl_core::Tree::new(vec![ + entry("a", EntryKind::Tree, next), + entry("b", EntryKind::Tree, next), + ]))) + .unwrap(); + } + store + .put(Object::Snapshot(scl_core::Snapshot { + root: next, + parents: vec![], + author: "t".into(), + timestamp: 0, + message: "c".into(), + secrets: BTreeMap::new(), + protection: Default::default(), + })) + .unwrap() + } + + /// A tree whose two entries share one child, repeated, must not make a + /// filtered walk read `2^levels` trees: once a directory is wholly inside + /// the filter scope, it is expanded once by id. + #[test] + fn filtered_walk_over_a_diamond_chain_is_linear() { + const LEVELS: usize = 18; + let mut store = Store::with_budget(1 << 20); + let snap = diamond_chain(&mut store, LEVELS); + let mut src = CountingSource { store, gets: 0 }; + // Size-only scope: every path is in scope (a `blob:limit` clone/fetch). + let all = crate::promisor::Promisor::with_blob_limit("o", vec![], 1); + let r = reachable_objects_limited(&mut src, &[snap], Some(&all), Some(1), &BTreeSet::new()) + .unwrap(); + assert_eq!(r.included.len(), LEVELS + 3, "snapshot, trees, blob"); + assert!(src.gets <= 2 * LEVELS + 8, "walk read {} objects", src.gets); + + // A prefix scope: the ancestors are path-bound, the scope below is not. + src.gets = 0; + let r = reachable_objects_filtered( + &mut src, + &[snap], + Some(&crate::promisor::Promisor::new("o", vec!["a/".into()])), + ) + .unwrap(); + assert_eq!(r.included.len(), LEVELS + 3); + assert!(src.gets <= 2 * LEVELS + 8, "walk read {} objects", src.gets); + } } From 9ad732ff3dd467bdecd57e83e0b64e2a4cfe10c0 Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 09:04:26 +0200 Subject: [PATCH 2/7] fix(serve): bound the TLS handshake and HTTP opening by one deadline The 30 s opening timeout was a per-read socket timeout, so a peer sending one byte every 29 s held a connection slot for about 66 h before any token check, and 32 of them filled the default --max-connections. The TLS handshake ran under the same per-read bound. The deadline is now fixed at accept and every socket read narrows SO_RCVTIMEO to what is left, failing as timed out at zero. For TLS the narrowing happens in the socket under rustls (server_stream takes the deadline), since rustls reads a record in as many socket reads as the peer splits it into. The session timeout replaces the deadline after the 200 status. --- crates/repo/src/http_transport.rs | 118 ++++++++++++++++++++++-------- crates/tlsio/src/stream.rs | 110 ++++++++++++++++++++++++++-- crates/tlsio/src/trust.rs | 2 +- 3 files changed, 193 insertions(+), 37 deletions(-) diff --git a/crates/repo/src/http_transport.rs b/crates/repo/src/http_transport.rs index a6470087..dbe941b8 100644 --- a/crates/repo/src/http_transport.rs +++ b/crates/repo/src/http_transport.rs @@ -5,7 +5,7 @@ use std::io::{BufReader, Read, Write}; use std::net::{TcpListener, TcpStream}; -use std::time::Duration; +use std::time::{Duration, Instant}; use scl_core::ObjectId; @@ -659,17 +659,20 @@ impl Transport for HttpTransport { } } -/// Bound on how long an accepted connection may take to send its HTTP -/// opening (request line + headers + blank line) before the server gives up -/// on it. Guards the slow-loris case the Task 2 review flagged: -/// `read_client_opening` bounds the opening in BYTES (`MAX_OPENING_BYTES`) -/// but not in TIME, so a peer that trickles in under the byte cap and then -/// stalls would otherwise hold a server thread (and its socket) forever. -/// Applied only around the opening read — the opening timeout is REPLACED -/// (not cleared) by `limits.timeout_secs`'s session read+write timeouts -/// after the 200 status is written, before handing off to `wire::serve` — -/// see `handle_http_connection` for the timeout sequencing. -const OPENING_READ_TIMEOUT: Duration = Duration::from_secs(30); +/// One overall bound on how long an accepted connection may take from accept +/// to a complete HTTP opening (the TLS handshake, when there is one, plus the +/// request line, headers and blank line) before the server gives up on it. +/// Guards the slow-loris case: `read_client_opening` bounds the opening in +/// BYTES (`MAX_OPENING_BYTES`) but a per-read socket timeout does not bound +/// it in TIME, since a peer sending one byte just inside each timeout would +/// hold a connection slot (8 KiB at 29 s a byte is about 66 hours) before any +/// token check. So the budget is a deadline fixed at accept: every socket read +/// first narrows the socket timeout to what is left, and the connection fails +/// as timed out when none is. The deadline is REPLACED (not cleared) by +/// `limits.timeout_secs`'s session read+write timeouts after the 200 status is +/// written, before handing off to `wire::serve` — see `handle_http_connection` +/// for the sequencing. +const OPENING_TIMEOUT: Duration = Duration::from_secs(30); /// How long the client allows the connect, TLS handshake, opening and wire /// handshake to take before giving up on a silent or stalled peer. Matches the @@ -1165,6 +1168,7 @@ pub fn serve_http_listener( limits, tls.as_ref(), store.as_deref(), + OPENING_TIMEOUT, ) { eprintln!("sc serve --http: connection error: {e}"); } @@ -1190,8 +1194,9 @@ pub fn serve_http_listener( /// Handle one accepted connection end to end: bounded-time opening read → /// validate `root` is a repo → status line → `wire::serve`. /// -/// The read timeout is set BEFORE `read_client_opening` (closing the -/// slow-loris gap: the opening is bounded in bytes but not time) and +/// One deadline, [`OPENING_TIMEOUT`] from accept, bounds the TLS handshake and +/// `read_client_opening` together (closing the slow-loris gap: the opening is +/// bounded in bytes but a per-read timeout would not bound it in time). It is /// REPLACED (P31, not simply cleared) by `limits.timeout_secs`'s session /// timeout — on both the read and write sides — AFTER the 200 status is /// written and BEFORE handing off to `wire::serve`: a legitimate large pack @@ -1203,7 +1208,8 @@ pub fn serve_http_listener( /// `wire::serve` are all generic over Read/Write, so one enum layer at the /// seam keeps plaintext and TLS on the identical code path after wrap. enum SrvRead { - Plain(TcpStream), + /// The socket, and the opening deadline while one applies. + Plain(TcpStream, Option), Tls(scl_tlsio::TlsServerReadHalf), } enum SrvWrite { @@ -1213,7 +1219,16 @@ enum SrvWrite { impl Read for SrvRead { fn read(&mut self, buf: &mut [u8]) -> std::io::Result { match self { - SrvRead::Plain(s) => s.read(buf), + SrvRead::Plain(s, deadline) => { + if let Some(at) = *deadline { + let left = at.saturating_duration_since(Instant::now()); + if left.is_zero() { + return Err(std::io::ErrorKind::TimedOut.into()); + } + s.set_read_timeout(Some(left))?; + } + s.read(buf) + } SrvRead::Tls(r) => r.read(buf), } } @@ -1233,13 +1248,14 @@ impl Write for SrvWrite { } } impl SrvRead { - /// P31 session timeouts, below TLS when wrapped. SO_RCVTIMEO/SO_SNDTIMEO - /// live on the socket (shared across `try_clone` fds), so setting them - /// through either half governs the whole connection — the same fact the - /// plaintext path has relied on since P31. - fn set_session_timeouts(&self, d: Option) -> std::io::Result<()> { + /// P31 session timeouts, below TLS when wrapped; they replace the opening + /// deadline. SO_RCVTIMEO/SO_SNDTIMEO live on the socket (shared across + /// `try_clone` fds), so setting them through either half governs the whole + /// connection — the same fact the plaintext path has relied on since P31. + fn set_session_timeouts(&mut self, d: Option) -> std::io::Result<()> { match self { - SrvRead::Plain(s) => { + SrvRead::Plain(s, deadline) => { + *deadline = None; s.set_read_timeout(d)?; s.set_write_timeout(d) } @@ -1248,6 +1264,7 @@ impl SrvRead { } } +#[allow(clippy::too_many_arguments)] fn handle_http_connection( stream: TcpStream, root: &std::path::Path, @@ -1256,20 +1273,21 @@ fn handle_http_connection( limits: ServeLimits, tls: Option<&scl_tlsio::TlsServerConfig>, store: Option<&str>, + opening_timeout: Duration, ) -> Result<()> { - stream - .set_read_timeout(Some(OPENING_READ_TIMEOUT)) - .map_err(|e| Error::ConnectionLost(format!("sc+http set_read_timeout: {e}")))?; - + let deadline = Instant::now() + opening_timeout; let (mut reader, mut writer) = match tls { None => { let r = stream .try_clone() .map_err(|e| Error::ConnectionLost(format!("sc+http socket clone: {e}")))?; - (BufReader::new(SrvRead::Plain(r)), SrvWrite::Plain(stream)) + ( + BufReader::new(SrvRead::Plain(r, Some(deadline))), + SrvWrite::Plain(stream), + ) } Some(cfg) => { - let t = scl_tlsio::server_stream(cfg, stream)?; + let t = scl_tlsio::server_stream(cfg, stream, Some(deadline))?; let (r, w) = t.split(); (BufReader::new(SrvRead::Tls(r)), SrvWrite::Tls(w)) } @@ -1368,7 +1386,7 @@ fn handle_http_connection( Some(Duration::from_secs(limits.timeout_secs)) }; reader - .get_ref() + .get_mut() .set_session_timeouts(session) .map_err(|e| Error::ConnectionLost(format!("sc+http set session timeouts: {e}")))?; @@ -2666,6 +2684,48 @@ mod tests { addr } + /// A peer sending one byte of a never-ending header well inside any + /// per-read timeout still loses the connection at the opening deadline, + /// before any token check. + #[test] + fn a_trickled_opening_fails_at_the_overall_deadline() { + let root = tmp_served_root("trickle"); + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let deadline = Duration::from_millis(600); + let served = root.clone(); + let server = std::thread::spawn(move || { + let (stream, _) = listener.accept().unwrap(); + let t0 = Instant::now(); + let r = handle_http_connection( + stream, + &served, + false, + false, + ServeLimits::default(), + None, + None, + deadline, + ); + (r, t0.elapsed()) + }); + let mut c = TcpStream::connect(addr).unwrap(); + c.write_all(b"POST / HTTP/1.1\r\n").unwrap(); + while !server.is_finished() { + if c.write_all(b"X").is_err() { + break; + } + std::thread::sleep(Duration::from_millis(50)); + } + let (r, took) = server.join().unwrap(); + r.unwrap(); // a timed-out opening is answered 400 and closed, not an error + assert!( + took >= deadline && took < deadline + Duration::from_secs(2), + "closed after {took:?}, expected about {deadline:?}" + ); + let _ = std::fs::remove_dir_all(&root); + } + fn open_ok(addr: std::net::SocketAddr) -> TcpStream { let mut s = TcpStream::connect(addr).unwrap(); write_client_opening(&mut s, "127.0.0.1", "/", None).unwrap(); diff --git a/crates/tlsio/src/stream.rs b/crates/tlsio/src/stream.rs index a7215799..51a6281d 100644 --- a/crates/tlsio/src/stream.rs +++ b/crates/tlsio/src/stream.rs @@ -13,10 +13,11 @@ //! written, and a garbage/non-TLS peer must fail at the seam, not //! mid-protocol. +use std::cell::Cell; use std::io::{Read, Write}; use std::net::TcpStream; use std::sync::{Arc, Mutex}; -use std::time::Duration; +use std::time::{Duration, Instant}; use rustls::pki_types::ServerName; @@ -111,9 +112,54 @@ pub fn server_config(id: ServerIdentity) -> Result { }) } +/// The accepted socket under a server stream. While a deadline is set, every +/// socket read first narrows SO_RCVTIMEO to the time left, so the handshake +/// and whatever the caller reads before lifting it share ONE overall bound. +/// A per-read timeout alone does not bound a peer that sends a byte just +/// under it each time: rustls reads a record in as many socket reads as the +/// peer chooses to split it into. +struct DeadlineTcp { + tcp: TcpStream, + deadline: Cell>, +} + +impl DeadlineTcp { + /// Replace the deadline by a plain socket timeout (the session bound). + fn set_read_timeout(&self, d: Option) -> std::io::Result<()> { + self.deadline.set(None); + self.tcp.set_read_timeout(d) + } + + fn set_write_timeout(&self, d: Option) -> std::io::Result<()> { + self.tcp.set_write_timeout(d) + } +} + +impl Read for DeadlineTcp { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + if let Some(at) = self.deadline.get() { + let left = at.saturating_duration_since(Instant::now()); + if left.is_zero() { + return Err(std::io::ErrorKind::TimedOut.into()); + } + self.tcp.set_read_timeout(Some(left))?; + } + self.tcp.read(buf) + } +} + +impl Write for DeadlineTcp { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + self.tcp.write(buf) + } + fn flush(&mut self) -> std::io::Result<()> { + self.tcp.flush() + } +} + /// A completed server-side TLS connection wrapping a `TcpStream`. pub struct TlsServerStream { - inner: rustls::StreamOwned, + inner: rustls::StreamOwned, } /// A completed client-side TLS connection wrapping a `TcpStream`. @@ -136,11 +182,24 @@ impl std::fmt::Debug for TlsClientStream { } } -/// Accept-side wrap: complete the handshake (bounded by whatever socket -/// timeout the caller set on `tcp`) and return a ready stream. -pub fn server_stream(cfg: &TlsServerConfig, mut tcp: TcpStream) -> Result { +/// Accept-side wrap: complete the handshake and return a ready stream. +/// +/// With `deadline`, the handshake AND every later read on the stream fail as +/// timed out once it passes, however the peer paces its bytes; the first +/// [`TlsServerReadHalf::set_socket_timeouts`] call lifts it for the session. +/// Without one, the handshake is bounded only by a socket timeout the caller +/// set on `tcp`, which a slow trickle can outlast. +pub fn server_stream( + cfg: &TlsServerConfig, + tcp: TcpStream, + deadline: Option, +) -> Result { let mut conn = rustls::ServerConnection::new(cfg.config.clone()) .map_err(|e| Error::Handshake(e.to_string()))?; + let mut tcp = DeadlineTcp { + tcp, + deadline: Cell::new(deadline), + }; while conn.is_handshaking() { conn.complete_io(&mut tcp) .map_err(|e| Error::Handshake(format!("server handshake: {e}")))?; @@ -256,7 +315,8 @@ macro_rules! halves { /// Set read/write timeouts on the UNDERLYING socket (SO_RCVTIMEO /// / SO_SNDTIMEO apply to the socket, so they govern the TLS /// stream's blocking behavior below the record layer) — the P31 - /// session-timeout hook. + /// session-timeout hook. On a server stream it also replaces the + /// accept deadline ([`server_stream`]). pub fn set_socket_timeouts( &self, read: Option, @@ -308,7 +368,7 @@ mod tests { let (tcp, _) = listener.accept().unwrap(); // A client that aborts its handshake (mismatch/strict tests) // surfaces as Err here — that's fine, just return. - let Ok(stream) = server_stream(&cfg, tcp) else { + let Ok(stream) = server_stream(&cfg, tcp, None) else { return; }; let (mut r, mut w) = stream.split(); @@ -402,4 +462,40 @@ mod tests { std::fs::remove_dir_all(&dir).unwrap(); assert!(!dir.exists()); } + + /// A peer that keeps sending one byte of a declared 16 KiB handshake + /// record, each well inside any per-read timeout, still fails at the + /// overall deadline. + #[test] + fn a_trickled_handshake_fails_at_the_overall_deadline() { + let dir = tmp("trickle"); + let id = crate::load_or_mint(&dir, &crate::identity::tests::plain_create).unwrap(); + let cfg = server_config(id).unwrap(); + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let deadline = Duration::from_millis(600); + let server = std::thread::spawn(move || { + let (tcp, _) = listener.accept().unwrap(); + // Per-read timeout far above the byte gap: only the deadline can fire. + tcp.set_read_timeout(Some(Duration::from_secs(30))).unwrap(); + let t0 = Instant::now(); + let r = server_stream(&cfg, tcp, Some(t0 + deadline)); + (r.is_err(), t0.elapsed()) + }); + let mut c = TcpStream::connect(addr).unwrap(); + c.write_all(&[0x16, 0x03, 0x01, 0x40, 0x00]).unwrap(); + while !server.is_finished() { + if c.write_all(&[0]).is_err() { + break; + } + std::thread::sleep(Duration::from_millis(50)); + } + let (failed, took) = server.join().unwrap(); + assert!(failed, "a trickled handshake must not complete"); + assert!( + took >= deadline && took < deadline + Duration::from_secs(2), + "failed after {took:?}, expected about {deadline:?}" + ); + std::fs::remove_dir_all(&dir).unwrap(); + } } diff --git a/crates/tlsio/src/trust.rs b/crates/tlsio/src/trust.rs index 489d8cc4..6842d54b 100644 --- a/crates/tlsio/src/trust.rs +++ b/crates/tlsio/src/trust.rs @@ -206,7 +206,7 @@ mod tests { let addr = listener.local_addr().unwrap().to_string(); let h = std::thread::spawn(move || { let (tcp, _) = listener.accept().unwrap(); - let Ok(stream) = server_stream(&cfg, tcp) else { + let Ok(stream) = server_stream(&cfg, tcp, None) else { return; // a client that rejects the cert aborts the handshake }; let (mut r, mut w) = stream.split(); From d3bf7b7d0014d889a82178ec9ad575ce1db0bb3b Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 09:05:13 +0200 Subject: [PATCH 3/7] fix(wire): refuse an empty ST_PACK_CHUNK frame write_pack_stream never frames zero bytes, but read_pack_stream accepted empty chunks without limit. An empty chunk advances neither the --max-pack-size count nor the idle timeout, so a peer could hold a session on it for ever. It is now a protocol error. --- crates/repo/src/wire.rs | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/crates/repo/src/wire.rs b/crates/repo/src/wire.rs index 83eb78de..a67498f4 100644 --- a/crates/repo/src/wire.rs +++ b/crates/repo/src/wire.rs @@ -571,6 +571,12 @@ pub fn read_pack_stream( let frame = read_frame_opt(r)?.ok_or_else(|| Error::Protocol("EOF before ST_PACK_END".into()))?; match frame.split_first() { + // `write_pack_stream` never frames zero bytes. An empty chunk + // advances neither the size cap nor the idle timeout, so a peer + // could repeat it for ever. + Some((&ST_PACK_CHUNK, [])) => { + return Err(Error::Protocol("empty ST_PACK_CHUNK frame".into())) + } Some((&ST_PACK_CHUNK, rest)) => { let next = total + rest.len() as u64; if max_bytes != 0 && next > max_bytes { @@ -2203,6 +2209,26 @@ mod tests { std::fs::remove_dir_all(&root).unwrap(); } + /// `write_pack_stream` never frames zero bytes, so an empty chunk is a + /// peer making no progress: it moves neither the size cap nor the + /// idle timeout, and could be repeated for ever. + #[test] + fn read_pack_stream_refuses_an_empty_chunk() { + let mut buf = Vec::new(); + write_frame(&mut buf, &[ST_PACK_CHUNK, b'a']).unwrap(); + for _ in 0..1000 { + write_frame(&mut buf, &[ST_PACK_CHUNK]).unwrap(); + } + write_frame(&mut buf, &[ST_PACK_END]).unwrap(); + let mut sink = Vec::new(); + let err = read_pack_stream(&mut std::io::Cursor::new(buf), &mut sink, 0).unwrap_err(); + assert!( + matches!(err, Error::Protocol(_)), + "expected Protocol error, got {err:?}" + ); + assert_eq!(sink, b"a", "refused at the first empty chunk"); + } + #[test] fn read_pack_stream_rejects_missing_end() { // Chunk frames followed by EOF, no ST_PACK_END. From 0e3160a01ba39ff5102ff6de5508161c98ebea02 Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 09:05:42 +0200 Subject: [PATCH 4/7] docs: record the serve deadline, empty-chunk and filtered-walk bounds --- docs/THREAT-MODEL.md | 16 +++++++++++++++- docs/adr/0041-listener-resource-limits.md | 16 ++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/docs/THREAT-MODEL.md b/docs/THREAT-MODEL.md index 20e3baab..111670f3 100644 --- a/docs/THREAT-MODEL.md +++ b/docs/THREAT-MODEL.md @@ -394,7 +394,15 @@ too, not just the src-control-side metadata. read *and* write timeouts on the session socket for its whole lifetime — not just the opening's original 30s, which used to be cleared once the wire handoff began. A trip is connection-fatal (frame desync precludes recovery); - the spooled temp pack is guard-cleaned on the resulting unwind. + the spooled temp pack is guard-cleaned on the resulting unwind. A per-read + timeout does not bound a peer that sends a byte just inside it each time, and + before authentication that held a connection slot for hours (8 KiB of opening + at 29 s a byte), so 32 such peers filled the default `--max-connections` + before any token check. The TLS handshake and the HTTP opening now share one + 30 s deadline fixed at accept (every socket read narrows the timeout to the + time left); the session timeout replaces it after the 200 status. An empty + `ST_PACK_CHUNK` frame, which moves neither the `--max-pack-size` count nor the + idle timeout, is a protocol error; the sender never emits one. - **Accept-loop hot-spin under fd exhaustion:** a hardcoded exponential backoff (5ms doubling to a 1s cap, reset on the next successful accept — Go `net/http`'s shape) paces retries around `EMFILE`/`ENFILE` instead of @@ -689,6 +697,12 @@ too, not just the src-control-side metadata. same request scope and server cost apply per fetch; `--no-blob-limit` removes the scope and adds no plaintext access (it is an unfiltered fetch, which also receives private-branch ciphertext). +- **A filtered walk is bounded by the object count, not the path count.** A + chain of trees whose two entries name the same child is a few KB with `2^depth` + paths, and any writer can plant one with `PutObject`. The filtered reachability + walk (`blob:limit` and prefix `GetPack`) keys a directory by id alone once it is + wholly inside the filter scope, so each tree is read once; only the ancestors of + a filter prefix are keyed by path. - **Operations that need a complete closure refuse on a partial clone, fail closed:** `sc export`, `sc rewrap`, `sc grant`/`revoke`, private branches, and `sc push` to a git remote. They refuse rather than run on partial data. diff --git a/docs/adr/0041-listener-resource-limits.md b/docs/adr/0041-listener-resource-limits.md index 3ae3c1f4..62db2e53 100644 --- a/docs/adr/0041-listener-resource-limits.md +++ b/docs/adr/0041-listener-resource-limits.md @@ -209,3 +209,19 @@ before closing. Closing with unread bytes makes the OS reset the socket and can destroy the reply; the drain keeps it deliverable when the client overshoots by less than the cap. A malformed frame still tears down at once. +## Addendum: one deadline for the TLS handshake and the HTTP opening + +The 30 s opening bound was a per-read socket timeout. It bounded silence, not +time: a client sending one byte every 29 s kept the opening open for about 66 h +(8 KiB at 29 s a byte), before any token check, and 32 such connections filled +the default `--max-connections`. The TLS handshake ran under the same per-read +bound. Now the deadline (30 s) is fixed at accept and covers the handshake and +the opening together: before each socket read the timeout is set to the time +left, and at zero the read fails as timed out. For `sc+https` the narrowing sits +in the socket under rustls (`scl_tlsio::server_stream` takes the deadline), +because rustls reads one record in as many socket reads as the peer splits it +into. The session timeout (decision 2) replaces the deadline after the `200`. +The client's own connect bound is unchanged. Alongside it, `read_pack_stream` +refuses an empty `ST_PACK_CHUNK` frame as a protocol error: it advanced neither +the `--max-pack-size` count nor the idle timeout, and the sender never emits one. + From 38c04a7a56c460e55cb07d266dcb472c31037ebd Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 10:19:02 +0200 Subject: [PATCH 5/7] fix(tlsio): bound the TLS handshake writes by the accept deadline too rustls also writes during the handshake (the certificate chain), so a peer that completes ClientHello and then stops reading could hold the slot past the deadline. DeadlineTcp now narrows SO_SNDTIMEO to the time left before each write, like reads. set_socket_timeouts already replaces the deadline and sets both session timeouts at handoff; a test pins that the narrowed write timeout does not survive it. --- crates/tlsio/src/stream.rs | 119 +++++++++++++++++++++++++++++++++---- 1 file changed, 109 insertions(+), 10 deletions(-) diff --git a/crates/tlsio/src/stream.rs b/crates/tlsio/src/stream.rs index 51a6281d..f0b6b404 100644 --- a/crates/tlsio/src/stream.rs +++ b/crates/tlsio/src/stream.rs @@ -113,8 +113,9 @@ pub fn server_config(id: ServerIdentity) -> Result { } /// The accepted socket under a server stream. While a deadline is set, every -/// socket read first narrows SO_RCVTIMEO to the time left, so the handshake -/// and whatever the caller reads before lifting it share ONE overall bound. +/// socket read first narrows SO_RCVTIMEO, and every write SO_SNDTIMEO, to the +/// time left, so the handshake and whatever the caller reads before lifting it +/// share ONE overall bound. /// A per-read timeout alone does not bound a peer that sends a byte just /// under it each time: rustls reads a record in as many socket reads as the /// peer chooses to split it into. @@ -131,25 +132,39 @@ impl DeadlineTcp { } fn set_write_timeout(&self, d: Option) -> std::io::Result<()> { + self.deadline.set(None); self.tcp.set_write_timeout(d) } + + /// The time left while a deadline applies; `TimedOut` once it is spent. + fn left(&self) -> std::io::Result> { + let Some(at) = self.deadline.get() else { + return Ok(None); + }; + let left = at.saturating_duration_since(Instant::now()); + if left.is_zero() { + return Err(std::io::ErrorKind::TimedOut.into()); + } + Ok(Some(left)) + } } impl Read for DeadlineTcp { fn read(&mut self, buf: &mut [u8]) -> std::io::Result { - if let Some(at) = self.deadline.get() { - let left = at.saturating_duration_since(Instant::now()); - if left.is_zero() { - return Err(std::io::ErrorKind::TimedOut.into()); - } + if let Some(left) = self.left()? { self.tcp.set_read_timeout(Some(left))?; } self.tcp.read(buf) } } +/// Writes are bounded too: rustls sends the server flight (certificate chain) +/// inside the handshake, and a peer that stops reading would block it. impl Write for DeadlineTcp { fn write(&mut self, buf: &[u8]) -> std::io::Result { + if let Some(left) = self.left()? { + self.tcp.set_write_timeout(Some(left))?; + } self.tcp.write(buf) } fn flush(&mut self) -> std::io::Result<()> { @@ -184,9 +199,11 @@ impl std::fmt::Debug for TlsClientStream { /// Accept-side wrap: complete the handshake and return a ready stream. /// -/// With `deadline`, the handshake AND every later read on the stream fail as -/// timed out once it passes, however the peer paces its bytes; the first -/// [`TlsServerReadHalf::set_socket_timeouts`] call lifts it for the session. +/// With `deadline`, the handshake AND every later read or write on the stream +/// fail as timed out once it passes, however the peer paces its bytes or +/// whether it reads at all; the first +/// [`TlsServerReadHalf::set_socket_timeouts`] call lifts it for the session +/// and sets both session timeouts. /// Without one, the handshake is bounded only by a socket timeout the caller /// set on `tcp`, which a slow trickle can outlast. pub fn server_stream( @@ -498,4 +515,86 @@ mod tests { ); std::fs::remove_dir_all(&dir).unwrap(); } + + /// A peer that never reads stalls the write side of the deadline socket + /// (rustls writes the certificate chain during the handshake). A loopback + /// socket pair makes the block deterministic: the writer fills the send + /// and receive buffers of a peer that does not read. + #[test] + fn a_write_to_a_peer_that_never_reads_fails_at_the_deadline() { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let client = TcpStream::connect(listener.local_addr().unwrap()).unwrap(); + let (tcp, _) = listener.accept().unwrap(); + let deadline = Duration::from_millis(600); + let t0 = Instant::now(); + let mut dt = DeadlineTcp { + tcp, + deadline: Cell::new(Some(t0 + deadline)), + }; + let chunk = vec![0u8; 64 * 1024]; + // Bounded so a regression fails the assertion rather than hanging CI + // forever: 1 GiB cannot fit in loopback buffers. + let mut sent = 0usize; + let err = loop { + match dt.write(&chunk) { + Ok(n) => sent += n, + Err(e) => break e, + } + assert!(sent < 1 << 30, "the write never blocked"); + }; + let took = t0.elapsed(); + assert!( + matches!( + err.kind(), + std::io::ErrorKind::TimedOut | std::io::ErrorKind::WouldBlock + ), + "{err:?}" + ); + assert!( + took >= deadline && took < deadline + Duration::from_secs(2), + "failed after {took:?}, expected about {deadline:?}" + ); + drop(client); + } + + /// The session timeouts replace the deadline at handoff, on both sides: + /// the write timeout narrowed during the handshake must not survive. + #[test] + fn session_timeouts_replace_the_deadline_and_the_narrowed_write_timeout() { + let dir = tmp("handoff"); + let id = crate::load_or_mint(&dir, &crate::identity::tests::plain_create).unwrap(); + let cfg = server_config(id).unwrap(); + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let server = std::thread::spawn(move || { + let (tcp, _) = listener.accept().unwrap(); + server_stream(&cfg, tcp, Some(Instant::now() + Duration::from_secs(30))).unwrap() + }); + let tcp = TcpStream::connect(addr).unwrap(); + let _client = client_connect(tcp, "127.0.0.1", None, false).unwrap(); + let stream = server.join().unwrap(); + // The handshake wrote under the deadline, so a narrowed write timeout is set. + assert!(stream + .inner + .get_ref() + .tcp + .write_timeout() + .unwrap() + .is_some()); + let (r, _w) = stream.split(); + let session = Some(Duration::from_secs(300)); + r.set_socket_timeouts(session, session).unwrap(); + { + let g = r.0.lock().unwrap(); + let dt = g.inner.get_ref(); + assert_eq!(dt.deadline.get(), None); + assert_eq!(dt.tcp.read_timeout().unwrap(), session); + assert_eq!(dt.tcp.write_timeout().unwrap(), session); + } + r.set_socket_timeouts(None, None).unwrap(); // --timeout 0 + let g = r.0.lock().unwrap(); + assert_eq!(g.inner.get_ref().tcp.write_timeout().unwrap(), None); + drop(g); + std::fs::remove_dir_all(&dir).unwrap(); + } } From fb325027e8ed871731574c7b7324fc58c257998f Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 10:22:50 +0200 Subject: [PATCH 6/7] test(tlsio): bound the write-deadline test with a fallback timeout --- crates/tlsio/src/stream.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/tlsio/src/stream.rs b/crates/tlsio/src/stream.rs index f0b6b404..04471c34 100644 --- a/crates/tlsio/src/stream.rs +++ b/crates/tlsio/src/stream.rs @@ -525,6 +525,9 @@ mod tests { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let client = TcpStream::connect(listener.local_addr().unwrap()).unwrap(); let (tcp, _) = listener.accept().unwrap(); + // Fallback so a regression (no narrowing) fails the timing assertion + // instead of blocking in `write` forever. + tcp.set_write_timeout(Some(Duration::from_secs(5))).unwrap(); let deadline = Duration::from_millis(600); let t0 = Instant::now(); let mut dt = DeadlineTcp { From 46d8a8514a41aba75179227b4c3c60c911472718 Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 10:26:59 +0200 Subject: [PATCH 7/7] docs(threat-model): note the macOS send-timeout limit on large operator cert chains --- docs/THREAT-MODEL.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/docs/THREAT-MODEL.md b/docs/THREAT-MODEL.md index 111670f3..794c39e7 100644 --- a/docs/THREAT-MODEL.md +++ b/docs/THREAT-MODEL.md @@ -399,8 +399,12 @@ too, not just the src-control-side metadata. before authentication that held a connection slot for hours (8 KiB of opening at 29 s a byte), so 32 such peers filled the default `--max-connections` before any token check. The TLS handshake and the HTTP opening now share one - 30 s deadline fixed at accept (every socket read narrows the timeout to the - time left); the session timeout replaces it after the 200 status. An empty + 30 s deadline fixed at accept (every socket read and write narrows the timeout + to the time left); the session timeout replaces it after the 200 status. Known + limit: on macOS one blocking `send` can wait more than once with the same + relative timeout, so a `--tls-cert` chain larger than the socket send buffer + (over about 128 KiB) sent to a peer that reads slowly can outlast the deadline; + the minted identity is a few KiB and is not affected. An empty `ST_PACK_CHUNK` frame, which moves neither the `--max-pack-size` count nor the idle timeout, is a protocol error; the sender never emits one. - **Accept-loop hot-spin under fd exhaustion:** a hardcoded exponential backoff