From ff1388c6d92ac180e31d66165f08c24dcc0abbe8 Mon Sep 17 00:00:00 2001 From: Marco Allegretti Date: Fri, 9 Oct 2026 18:59:01 +0000 Subject: [PATCH] test(portal): make the link-swap race test exercise both states, and fix limits The race test could finish before its swapping thread first ran, so in some runs nothing was exercised and the test failed. The link now exists from the start. The test runs until it has seen both reads that stay inside and reads refused for leading out, and it also swaps in a relative link that climbs out. Other fixes: - A request line ending in CRLF is measured without the CRLF. - Responses that the client stops reading time out like requests do. - Temporary file names include the portal's start time, so a file left by an earlier instance cannot collide with a new one. The test binary passed 30 runs in a row. --- crates/weft-file-portal/src/main.rs | 67 ++++++++++++++++++++--------- docs/security.md | 2 +- 2 files changed, 47 insertions(+), 22 deletions(-) diff --git a/crates/weft-file-portal/src/main.rs b/crates/weft-file-portal/src/main.rs index 2bf09c9..ecbace2 100644 --- a/crates/weft-file-portal/src/main.rs +++ b/crates/weft-file-portal/src/main.rs @@ -267,18 +267,20 @@ fn handle_connection(stream: std::os::unix::net::UnixStream, roots: &[Root]) { } }; let _ = stream.set_read_timeout(Some(IDLE_TIMEOUT)); + let _ = stream.set_write_timeout(Some(IDLE_TIMEOUT)); let mut reader = BufReader::new(stream); let mut line = Vec::new(); loop { line.clear(); match (&mut reader) - .take(MAX_LINE as u64 + 2) + .take(MAX_LINE as u64 + 3) .read_until(b'\n', &mut line) { Ok(0) | Err(_) => break, Ok(_) => {} } - if line.strip_suffix(b"\n").unwrap_or(&line).len() > MAX_LINE { + let content = line.strip_suffix(b"\n").unwrap_or(&line); + if content.strip_suffix(b"\r").unwrap_or(content).len() > MAX_LINE { let _ = writer.write_all(b"{\"error\":\"request too long\"}\n"); break; } @@ -382,8 +384,16 @@ fn write(root: &Root, rest: &Path, data: &[u8]) -> Result { ) .map_err(Response::err)?; static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + // Unique within this portal by the counter, and across restarts by the + // start time, so a file left by an earlier instance does not collide. + static STARTED: std::sync::OnceLock = std::sync::OnceLock::new(); + let started = STARTED.get_or_init(|| { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_nanos()) + }); let temporary = format!( - "{TEMPORARY_PREFIX}{}-{}", + "{TEMPORARY_PREFIX}{}-{started}-{}", std::process::id(), NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) ); @@ -603,37 +613,52 @@ mod tests { fs::create_dir(granted.join("real")).unwrap(); fs::write(granted.join("real/f"), b"inside").unwrap(); let roots = grant(&granted, true); + // `swap` is a link, replaced in a loop, alternately to the inside + // directory and out of the granted one, absolute and relative. + std::os::unix::fs::symlink("real", granted.join("swap")).unwrap(); let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); let swapper = { let (granted, outside, stop) = (granted.clone(), dir.join("outside"), stop.clone()); std::thread::spawn(move || { - // `swap` is alternately a link to the inside directory and - // a link out. - while !stop.load(std::sync::atomic::Ordering::Relaxed) { - let _ = std::os::unix::fs::symlink("real", granted.join("next")); - let _ = fs::rename(granted.join("next"), granted.join("swap")); - let _ = std::os::unix::fs::symlink(&outside, granted.join("next")); + let targets = [ + PathBuf::from("real"), + outside, + PathBuf::from("../../outside"), + ]; + for target in targets.iter().cycle() { + if stop.load(std::sync::atomic::Ordering::Relaxed) { + break; + } + let _ = std::os::unix::fs::symlink(target, granted.join("next")); let _ = fs::rename(granted.join("next"), granted.join("swap")); } }) }; - let mut inside = 0; - for _ in 0..2000 { - if let Response::OkData { data_b64 } = - handle_request(read_req(&granted.join("swap/f")), &roots) - { - let data = - base64::Engine::decode(&base64::engine::general_purpose::STANDARD, data_b64) - .unwrap(); - assert_eq!(data, b"inside", "a read left the directory"); - inside += 1; + let (mut inside, mut refused) = (0, 0); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20); + while (inside < 50 || refused < 50) && std::time::Instant::now() < deadline { + match handle_request(read_req(&granted.join("swap/f")), &roots) { + Response::OkData { data_b64 } => { + let data = base64::Engine::decode( + &base64::engine::general_purpose::STANDARD, + data_b64, + ) + .unwrap(); + assert_eq!(data, b"inside", "a read left the directory"); + inside += 1; + } + Response::Err { error } if error.contains("leads out") => refused += 1, + _ => {} } let _ = handle_request(write_req(&granted.join("swap/f"), b"inside"), &roots); } stop.store(true, std::sync::atomic::Ordering::Relaxed); swapper.join().unwrap(); assert_eq!(fs::read(dir.join("outside/f")).unwrap(), b"secret"); - assert!(inside > 0, "the race never resolved inside"); + assert!( + inside >= 50 && refused >= 50, + "the race was not exercised: {inside} reads inside, {refused} refused" + ); let _ = fs::remove_dir_all(&dir); } @@ -720,7 +745,7 @@ mod tests { let serve = std::thread::spawn(move || handle_connection(server, &roots)); let mut writer = client.try_clone().unwrap(); let sent = std::thread::spawn(move || { - let _ = writer.write_all(&vec![b'x'; MAX_LINE + 2]); + let _ = writer.write_all(&vec![b'x'; MAX_LINE + 64]); }); let mut reply = String::new(); BufReader::new(client).read_line(&mut reply).unwrap(); diff --git a/docs/security.md b/docs/security.md index ca04299..a69ddde 100644 --- a/docs/security.md +++ b/docs/security.md @@ -16,7 +16,7 @@ Each app session runs as a separate OS process (`weft-runtime`). When systemd is ## Filesystem Isolation -Apps access the filesystem only through WASI preopened directories. Each capability maps to a specific host path preopened at a fixed guest path. The `weft-file-portal` process applies the same directory grants and access modes. It opens each granted directory once and resolves every request beneath that descriptor with `openat2(RESOLVE_BENEATH)`, so the kernel keeps the operation inside the directory: `..` and links pointing outside are refused, also when a link is swapped in while the operation runs; links that stay inside are followed. This needs Linux 5.6 or later; without `openat2` every operation fails. Requests must name an absolute path without `.`, `..` or empty components; files are limited to 16 MiB, listings to 10,000 entries, requests to one line of about 22 MiB, and the portal to 4 connections at a time, each closed after 60 seconds without a request. Writes replace a file atomically, keeping its permission bits but not its owner, extended attributes or hard links (a write to a name that is a link replaces the link), and never create directories. A granted directory that cannot be opened when the portal starts is not served. Components cannot currently reach its socket, since the runtime grants them no socket access, and the socket's path is not passed to them. +Apps access the filesystem only through WASI preopened directories. Each capability maps to a specific host path preopened at a fixed guest path. The `weft-file-portal` process applies the same directory grants and access modes. It opens each granted directory once and resolves every request beneath that descriptor with `openat2(RESOLVE_BENEATH)`, so the kernel keeps the operation inside the directory: `..` and links pointing outside are refused, also when a link is swapped in while the operation runs; links that stay inside are followed. This needs Linux 5.6 or later; without `openat2` every operation fails. Requests must name an absolute path without `.`, `..` or empty components; files are limited to 16 MiB, listings to 10,000 entries, requests to one line of about 22 MiB, and the portal to 4 connections at a time, each closed when it sends or accepts no data for 60 seconds. Writes replace a file atomically, keeping its permission bits but not its owner, extended attributes or hard links (a write to a name that is a link replaces the link), and never create directories. A granted directory that cannot be opened when the portal starts is not served. Components cannot currently reach its socket, since the runtime grants them no socket access, and the socket's path is not passed to them. ## Package Signing