[tests] Mock Authelia: record request bodies (Content-Length and chunked) so body assertions can fail
This commit is contained in:
+128
-2
@@ -3,7 +3,8 @@
|
||||
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
|
||||
//! A raw TCP HTTP/1.1 server that answers with scripted bytes: 1xx heads, truncated bodies,
|
||||
//! hangs. One request per connection, then the connection is closed.
|
||||
//! hangs. One request per connection, then the connection is closed. The request body is
|
||||
//! read and recorded (Content-Length or chunked), so tests can check what was sent.
|
||||
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::{Arc, Mutex};
|
||||
@@ -69,7 +70,13 @@ impl RawServer {
|
||||
Ok(n) => buf.extend_from_slice(&chunk[..n]),
|
||||
}
|
||||
}
|
||||
let Some(req) = parse(&buf) else { return };
|
||||
let Some(mut req) = parse(&buf) else { return };
|
||||
let end = buf.windows(4).position(|w| w == b"\r\n\r\n").unwrap_or(0) + 4;
|
||||
let rest = buf.split_off(end);
|
||||
match read_body(&mut stream, &req, rest).await {
|
||||
Some(body) => req.body = body,
|
||||
None => return,
|
||||
}
|
||||
requests.lock().unwrap().push(req.clone());
|
||||
match handler(&req) {
|
||||
Reply::Bytes(b) => {
|
||||
@@ -93,6 +100,77 @@ impl RawServer {
|
||||
}
|
||||
}
|
||||
|
||||
const MAX_BODY: usize = 16 << 20;
|
||||
|
||||
/// Read the request body that follows the head; `have` is what was read past the head.
|
||||
/// `None` when the peer breaks off or sends malformed framing.
|
||||
async fn read_body<S: AsyncReadExt + Unpin>(
|
||||
stream: &mut S,
|
||||
req: &Recorded,
|
||||
mut have: Vec<u8>,
|
||||
) -> Option<Vec<u8>> {
|
||||
let mut chunk = [0u8; 4096];
|
||||
let te = req
|
||||
.header("transfer-encoding")
|
||||
.map(|v| String::from_utf8_lossy(v).to_ascii_lowercase());
|
||||
if te.as_deref().is_some_and(|t| t.contains("chunked")) {
|
||||
let mut body = Vec::new();
|
||||
let mut pos = 0;
|
||||
loop {
|
||||
// Need a full size line.
|
||||
let line_end = loop {
|
||||
if let Some(i) = have[pos..].windows(2).position(|w| w == b"\r\n") {
|
||||
break pos + i;
|
||||
}
|
||||
let n = stream.read(&mut chunk).await.ok()?;
|
||||
if n == 0 || have.len() > MAX_BODY {
|
||||
return None;
|
||||
}
|
||||
have.extend_from_slice(&chunk[..n]);
|
||||
};
|
||||
let line = std::str::from_utf8(&have[pos..line_end]).ok()?;
|
||||
let size = usize::from_str_radix(line.split(';').next()?.trim(), 16).ok()?;
|
||||
pos = line_end + 2;
|
||||
if size == 0 {
|
||||
// Trailers (if any) end with an empty line.
|
||||
while !have[pos..].windows(2).any(|w| w == b"\r\n") {
|
||||
let n = stream.read(&mut chunk).await.ok()?;
|
||||
if n == 0 {
|
||||
return None;
|
||||
}
|
||||
have.extend_from_slice(&chunk[..n]);
|
||||
}
|
||||
return Some(body);
|
||||
}
|
||||
while have.len() < pos + size + 2 {
|
||||
let n = stream.read(&mut chunk).await.ok()?;
|
||||
if n == 0 || have.len() > MAX_BODY {
|
||||
return None;
|
||||
}
|
||||
have.extend_from_slice(&chunk[..n]);
|
||||
}
|
||||
body.extend_from_slice(&have[pos..pos + size]);
|
||||
pos += size + 2;
|
||||
}
|
||||
}
|
||||
let len: usize = match req.header("content-length") {
|
||||
Some(v) => std::str::from_utf8(v).ok()?.trim().parse().ok()?,
|
||||
None => 0,
|
||||
};
|
||||
if len > MAX_BODY {
|
||||
return None;
|
||||
}
|
||||
while have.len() < len {
|
||||
let n = stream.read(&mut chunk).await.ok()?;
|
||||
if n == 0 {
|
||||
return None;
|
||||
}
|
||||
have.extend_from_slice(&chunk[..n]);
|
||||
}
|
||||
have.truncate(len);
|
||||
Some(have)
|
||||
}
|
||||
|
||||
fn parse(buf: &[u8]) -> Option<Recorded> {
|
||||
let end = buf.windows(4).position(|w| w == b"\r\n\r\n")?;
|
||||
let head = std::str::from_utf8(&buf[..end]).ok()?;
|
||||
@@ -112,3 +190,51 @@ fn parse(buf: &[u8]) -> Option<Recorded> {
|
||||
body: Vec::new(),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used)]
|
||||
use super::*;
|
||||
use tokio::net::TcpStream;
|
||||
|
||||
async fn send(server: &RawServer, bytes: &[u8]) {
|
||||
let mut s = TcpStream::connect(server.addr).await.unwrap();
|
||||
s.write_all(bytes).await.unwrap();
|
||||
let mut out = Vec::new();
|
||||
let _ = s.read_to_end(&mut out).await;
|
||||
assert!(
|
||||
out.starts_with(b"HTTP/1.1 200"),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&out)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn records_request_bodies() {
|
||||
let server = RawServer::start(|_| Reply::Bytes(response(200, "OK", &[], b""))).await;
|
||||
send(&server, b"GET /none HTTP/1.1\r\nHost: x\r\n\r\n").await;
|
||||
send(
|
||||
&server,
|
||||
b"POST /cl HTTP/1.1\r\nHost: x\r\nContent-Length: 11\r\n\r\nLEAKED-BODY",
|
||||
)
|
||||
.await;
|
||||
send(
|
||||
&server,
|
||||
b"POST /chunked HTTP/1.1\r\nHost: x\r\nTransfer-Encoding: chunked\r\n\r\n6\r\nLEAKED\r\n5;ext=1\r\n-BODY\r\n0\r\n\r\n",
|
||||
)
|
||||
.await;
|
||||
let got: Vec<(String, Vec<u8>)> = server
|
||||
.requests()
|
||||
.into_iter()
|
||||
.map(|r| (r.path, r.body))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
got,
|
||||
[
|
||||
("/none".to_owned(), b"".to_vec()),
|
||||
("/cl".to_owned(), b"LEAKED-BODY".to_vec()),
|
||||
("/chunked".to_owned(), b"LEAKED-BODY".to_vec()),
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user