Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 28 additions & 5 deletions crates/engine/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20530,19 +20530,43 @@ fn zipped_shapefiles_add_as_layers() {
let _ = std::fs::remove_dir_all(&dir);
}

/// A request read whole: its head and as much body as its `Content-Length` says. A server that
/// answers and closes with part of the request unread has its connection reset on Windows and
/// macOS, and the client sees the reset in place of the answer.
fn read_request(s: &mut std::net::TcpStream) -> String {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The fix has no regression test. Its evidence is a temporary print in the server, and the existing test only catches the reset on Windows and macOS CI, where it is intermittent. A small test would pin the behaviour on every platform. Connect a client, write the request head, sleep briefly, then write a body of a few KB in a second write. Assert that read_request returns the head and the whole body, and that a request with no Content-Length returns after its head. This is a suggestion, not a blocker. It is an extra test for code that already works, so it can wait for the release quality pass.

Confidence: medium. The current change is correct as far as I can tell by reading.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Test-only and not a CI failure: the server only ever reads requests from our own client. Left for the release quality pass.

use std::io::Read;
let _ = s.set_read_timeout(Some(std::time::Duration::from_secs(5)));
let mut req = Vec::new();
let mut buf = [0u8; 4096];
let mut want = None;
while want.is_none_or(|n| req.len() < n) && req.len() < 1 << 20 {
let Ok(read) = s.read(&mut buf) else { break };
if read == 0 {
break;
}
req.extend_from_slice(&buf[..read]);
if want.is_none()
&& let Some(end) = req.windows(4).position(|w| w == b"\r\n\r\n")
{
let head = String::from_utf8_lossy(&req[..end]).to_ascii_lowercase();
let body = head.lines().find_map(|l| l.strip_prefix("content-length:")).and_then(|n| n.trim().parse::<usize>().ok());
want = Some(end + 4 + body.unwrap_or(0));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (test-only, low impact): end + 4 + body can overflow. A Content-Length near usize::MAX parses fine, and the addition then panics in debug builds. That panic kills the server thread, and the client sees a hang or a reset instead of a clear failure. The 1 MiB cap below only applies to the loop condition, not to this sum. Saturating the sum avoids the overflow.

Suggested change
want = Some(end + 4 + body.unwrap_or(0));
want = Some((end + 4).saturating_add(body.unwrap_or(0)));

Confidence: high that it overflows. Impact is limited to a malformed test request.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Test-only and not a CI failure: the server only ever reads requests from our own client. Left for the release quality pass.

}
}
String::from_utf8_lossy(&req).into_owned()
}

/// Serves each request by the first route its path starts with (`{base}` in a body becomes the
/// server's address; other paths are 404); returns the base address.
fn serve_routes(routes: Vec<(&'static str, String)>, n: usize) -> String {
use std::io::{Read, Write};
use std::io::Write;
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let base = format!("http://{}", listener.local_addr().unwrap());
let b = base.clone();
std::thread::spawn(move || {
for stream in listener.incoming().take(n) {
let Ok(mut s) = stream else { continue };
let mut buf = [0u8; 4096];
let read = s.read(&mut buf).unwrap_or(0);
let req = String::from_utf8_lossy(&buf[..read]);
let req = read_request(&mut s);
let path = req.split_whitespace().nth(1).unwrap_or("/").to_string();
match routes.iter().find(|(p, _)| path.starts_with(p)) {
Some((_, body)) => {
Expand Down Expand Up @@ -42646,7 +42670,6 @@ fn stac_search_by_shape_says_what_it_leaves_out() {
let item = r#"{"type": "Feature", "id": "S2_1", "collection": "s2", "bbox": [7, 46, 8, 47],
"geometry": {"type": "Polygon", "coordinates": [[[7, 46], [8, 46], [8, 47], [7, 47], [7, 46]]]},
"properties": {"datetime": "2024-06-02T10:30:00Z", "eo:cloud_cover": 3.5}, "assets": {}}"#;
// A POST answered before its body is read is asked again as a GET, so each search may take two.
let base = serve_routes(vec![("/v1/search", format!(r#"{{"type": "FeatureCollection", "features": [{item}]}}"#))], 40);
let api = format!("{base}/v1");
let said = |s: &Session, text: &str| s.notices.iter().filter(|n| n.text.contains(text)).count();
Expand Down
Loading