Skip to content
118 changes: 89 additions & 29 deletions crates/repo/src/http_transport.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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}");
}
Expand All @@ -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
Expand All @@ -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<Instant>),
Tls(scl_tlsio::TlsServerReadHalf),
}
enum SrvWrite {
Expand All @@ -1213,7 +1219,16 @@ enum SrvWrite {
impl Read for SrvRead {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
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),
}
}
Expand All @@ -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<Duration>) -> 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<Duration>) -> std::io::Result<()> {
match self {
SrvRead::Plain(s) => {
SrvRead::Plain(s, deadline) => {
*deadline = None;
s.set_read_timeout(d)?;
s.set_write_timeout(d)
}
Expand All @@ -1248,6 +1264,7 @@ impl SrvRead {
}
}

#[allow(clippy::too_many_arguments)]
fn handle_http_connection(
stream: TcpStream,
root: &std::path::Path,
Expand All @@ -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))
}
Expand Down Expand Up @@ -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}")))?;

Expand Down Expand Up @@ -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();
Expand Down
121 changes: 112 additions & 9 deletions crates/repo/src/reachable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

Expand All @@ -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<String>)>;

/// 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<String>) {
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)
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand All @@ -432,7 +454,7 @@ fn walk_tree_filtered(
included: &mut BTreeSet<ObjectId>,
gaps: &mut BTreeSet<ObjectId>,
filter: Option<&dyn PrefixFilter>,
expanded: &mut HashSet<(ObjectId, String)>,
expanded: &mut Expanded,
) -> Result<()> {
walk_tree_sized(src, root, included, gaps, filter, expanded, None)
}
Expand Down Expand Up @@ -474,7 +496,7 @@ fn walk_tree_sized(
included: &mut BTreeSet<ObjectId>,
gaps: &mut BTreeSet<ObjectId>,
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();
Expand All @@ -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()));
}
}
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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<Object> {
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);
}
}
Loading
Loading