Skip to content
Closed
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
45 changes: 39 additions & 6 deletions crates/openshell-sandbox/src/l7/rest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,6 @@ impl L7Provider for RestProvider {
/// Parse one HTTP/1.1 request from the stream.
async fn parse_http_request<C: AsyncRead + Unpin>(client: &mut C) -> Result<Option<L7Request>> {
let mut buf = Vec::with_capacity(4096);
let mut tmp = [0u8; 1024];

loop {
if buf.len() > MAX_HEADER_BYTES {
Expand All @@ -62,8 +61,11 @@ async fn parse_http_request<C: AsyncRead + Unpin>(client: &mut C) -> Result<Opti
));
}

let n = match client.read(&mut tmp).await {
Ok(n) => n,
let n = match client.read_u8().await {
Ok(byte) => {
buf.push(byte);
1
}
Err(e) if buf.is_empty() && is_benign_close(&e) => return Ok(None),
Err(e) => return Err(miette::miette!("{e}")),
};
Expand All @@ -76,10 +78,9 @@ async fn parse_http_request<C: AsyncRead + Unpin>(client: &mut C) -> Result<Opti
buf.len()
));
}
buf.extend_from_slice(&tmp[..n]);

// Check for end of headers
if buf.windows(4).any(|w| w == b"\r\n\r\n") {
if buf.ends_with(b"\r\n\r\n") {
break;
}
}
Expand Down Expand Up @@ -109,7 +110,7 @@ async fn parse_http_request<C: AsyncRead + Unpin>(client: &mut C) -> Result<Opti
Ok(Some(L7Request {
action: method,
target: path,
raw_header: buf, // includes header bytes + any overflow body bytes
raw_header: buf,
body_length,
}))
}
Expand Down Expand Up @@ -620,6 +621,38 @@ mod tests {
}
}

#[tokio::test]
async fn parse_http_request_does_not_overread_next_request() {
let (mut client, mut writer) = tokio::io::duplex(4096);

tokio::spawn(async move {
writer
.write_all(
b"GET /allowed HTTP/1.1\r\nHost: example.com\r\n\r\nPOST /blocked HTTP/1.1\r\nHost: example.com\r\nContent-Length: 0\r\n\r\n",
)
.await
.unwrap();
});

let first = parse_http_request(&mut client)
.await
.expect("first request should parse")
.expect("expected first request");
assert_eq!(first.action, "GET");
assert_eq!(first.target, "/allowed");
assert_eq!(
first.raw_header,
b"GET /allowed HTTP/1.1\r\nHost: example.com\r\n\r\n"
);

let second = parse_http_request(&mut client)
.await
.expect("second request should parse")
.expect("expected second request");
assert_eq!(second.action, "POST");
assert_eq!(second.target, "/blocked");
}

#[test]
fn http_method_detection() {
assert!(looks_like_http(b"GET / HTTP/1.1\r\n"));
Expand Down
Loading