1 //! The transport contract of the web: parse under limits, refuse what this2 //! server does not speak, frame the reply, serve one request per connection.3 4 use std::io::{BufReader, Read, Write};5 use std::net::{SocketAddr, TcpListener, TcpStream};6 use std::sync::Arc;7 use std::sync::atomic::{AtomicBool, Ordering};8 use std::thread;9 use std::time::Duration;10 11 use inf3r_server::{12 Body, Limits, Method, ParseError, Request, Response, Status, parse_request, serve,13 };14 15 /// The time limits that the ordinary framing tests use. A test that needs to16 /// observe a timeout makes its own copy and shortens one field.17 const TIMEOUT: Duration = Duration::from_secs(5);18 const CONNECTIONS: usize = 64;19 20 const fn wire(max_head_bytes: usize, max_body_bytes: usize, max_upload_bytes: usize) -> Limits {21 Limits {22 max_head_bytes,23 max_body_bytes,24 max_upload_bytes,25 read_timeout: TIMEOUT,26 head_timeout: TIMEOUT,27 write_timeout: TIMEOUT,28 max_connections: CONNECTIONS,29 }30 }31 32 const HEADROOM: Limits = wire(4096, 4096, 4096);33 34 /// Starts `serve` on a loopback port this process was given, and returns the35 /// address. The server thread lives until the test process exits.36 fn spawn_server(37 limits: Limits,38 handler: impl Fn(Request) -> Response + Send + Sync + 'static,39 ) -> SocketAddr {40 let listener = TcpListener::bind("127.0.0.1:0").expect("loopback listener");41 let addr = listener.local_addr().expect("listener address");42 thread::spawn(move || {43 serve(listener, limits, handler).expect("serve");44 });45 addr46 }47 48 /// Writes the whole request and reads until the server closes the connection.49 /// A server that closes early can reset the socket after its reply, so an50 /// error is the end of the reply, not a failure.51 fn exchange(addr: SocketAddr, request: &[u8]) -> Vec<u8> {52 let mut stream = TcpStream::connect(addr).expect("connect");53 stream.write_all(request).expect("write request");54 stream.flush().expect("flush request");55 let mut reply = Vec::new();56 let mut buf = [0u8; 4096];57 loop {58 match stream.read(&mut buf) {59 Ok(0) | Err(_) => break,60 Ok(n) => reply.extend_from_slice(&buf[..n]),61 }62 }63 reply64 }65 66 /// The reply split at the blank line that ends the head.67 fn split(reply: &[u8]) -> (&[u8], &[u8]) {68 let marker = b"\r\n\r\n";69 let at = reply70 .windows(marker.len())71 .position(|w| w == marker)72 .expect("head end");73 (74 reply.split_at(at + marker.len()).0,75 &reply[at + marker.len()..],76 )77 }78 79 /// Reads one HTTP head, byte for byte, and stops at its blank line. The80 /// interim response and the final response can then be observed separately.81 fn read_head(stream: &mut TcpStream) -> Vec<u8> {82 let mut head = Vec::new();83 let mut byte = [0u8; 1];84 loop {85 stream.read_exact(&mut byte).expect("read head");86 head.push(byte[0]);87 if head.ends_with(b"\r\n\r\n") {88 return head;89 }90 }91 }92 93 fn upload_sizes(mut request: Request) -> Response {94 let (declared, bytes) = match request.upload.take() {95 Some(mut upload) => {96 let mut bytes = Vec::new();97 upload.file.read_to_end(&mut bytes).unwrap();98 (upload.len, bytes.len())99 }100 None => (request.body.len() as u64, request.body.len()),101 };102 Response::text(Status::OK, &format!("{declared} {bytes}"))103 }104 105 fn echo(request: Request) -> Response {106 let body = format!(107 "{} {} {} {}",108 match request.method {109 Method::Get => "GET",110 Method::Post => "POST",111 Method::Delete => "DELETE",112 Method::Other(ref m) => m,113 },114 request.target,115 request.headers.get("x-token").unwrap_or("-"),116 request.body.len()117 );118 Response::text(Status::OK, &body)119 }120 121 fn get(addr: SocketAddr, target: &str) -> Vec<u8> {122 exchange(addr, format!("GET {target} HTTP/1.1\r\n\r\n").as_bytes())123 }124 125 #[test]126 fn a_get_is_served() {127 let addr = spawn_server(HEADROOM, echo);128 let reply = get(addr, "/healthz");129 let (head, body) = split(&reply);130 assert_eq!(head, b"HTTP/1.1 200 OK\r\ncontent-type: text/plain; charset=utf-8\r\nContent-Length: 16\r\nConnection: close\r\n\r\n");131 assert_eq!(body, b"GET /healthz - 0");132 }133 134 #[test]135 fn a_post_body_arrives_exactly() {136 let addr = spawn_server(HEADROOM, echo);137 let reply = exchange(138 addr,139 b"POST /jobs HTTP/1.1\r\nContent-Length: 5\r\n\r\nhello",140 );141 let body = split(&reply).1;142 assert_eq!(body, b"POST /jobs - 5");143 }144 145 #[test]146 fn a_header_lookup_ignores_case() {147 let addr = spawn_server(HEADROOM, echo);148 let reply = exchange(149 addr,150 b"GET / HTTP/1.1\r\nX-Token: up-first\r\nx-token: down-second\r\n\r\n",151 );152 // `get` returns the first value in arrival order.153 assert_eq!(split(&reply).1, b"GET / up-first 0");154 }155 156 #[test]157 fn a_body_over_the_buffer_is_read_from_the_start_of_its_file() {158 let limits = wire(4096, 4, 2 << 20);159 let addr = spawn_server(limits, upload_sizes);160 let mut request = format!(161 "POST /blobs HTTP/1.1\r\nContent-Length: {}\r\n\r\n",162 1 << 20163 )164 .into_bytes();165 request.extend_from_slice(&vec![b'x'; 1 << 20]);166 let reply = exchange(addr, &request);167 assert_eq!(split(&reply).1, b"1048576 1048576");168 }169 170 #[test]171 fn an_upload_over_its_limit_is_too_large() {172 let limits = wire(4096, 4, 8);173 let addr = spawn_server(limits, upload_sizes);174 let reply = exchange(175 addr,176 b"POST /blobs HTTP/1.1\r\nContent-Length: 10\r\n\r\n0123456789",177 );178 let (head, body) = split(&reply);179 assert!(180 head.starts_with(b"HTTP/1.1 413"),181 "{}",182 String::from_utf8_lossy(head)183 );184 assert_eq!(body, b"too large\n");185 }186 187 #[test]188 fn a_head_over_the_limit_is_too_large() {189 let limits = wire(60, 4096, 4096);190 let addr = spawn_server(limits, echo);191 let mut request = b"GET / HTTP/1.1\r\nX-Filler: ".to_vec();192 request.extend_from_slice(&vec![b'a'; 500]);193 request.extend_from_slice(b"\r\n\r\n");194 let reply = exchange(addr, &request);195 let (head, body) = split(&reply);196 assert_eq!(197 head,198 b"HTTP/1.1 413 Content Too Large\r\ncontent-type: text/plain; charset=utf-8\r\nContent-Length: 10\r\nConnection: close\r\n\r\n"199 );200 assert_eq!(body, b"too large\n");201 }202 203 #[test]204 fn a_body_over_the_limit_is_too_large() {205 let limits = wire(4096, 5, 5);206 let addr = spawn_server(limits, echo);207 let reply = exchange(208 addr,209 b"POST /blobs HTTP/1.1\r\nContent-Length: 10\r\n\r\n0123456789",210 );211 let (head, body) = split(&reply);212 assert_eq!(213 head,214 b"HTTP/1.1 413 Content Too Large\r\ncontent-type: text/plain; charset=utf-8\r\nContent-Length: 10\r\nConnection: close\r\n\r\n"215 );216 assert_eq!(body, b"too large\n");217 }218 219 #[test]220 fn a_chunked_request_body_is_refused() {221 let addr = spawn_server(HEADROOM, echo);222 let reply = exchange(223 addr,224 b"POST /jobs HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n",225 );226 let (head, body) = split(&reply);227 assert_eq!(228 head,229 b"HTTP/1.1 400 Bad Request\r\ncontent-type: text/plain; charset=utf-8\r\nContent-Length: 12\r\nConnection: close\r\n\r\n"230 );231 assert_eq!(body, b"unsupported\n");232 }233 234 #[test]235 fn two_conflicting_content_lengths_are_bad_request() {236 let addr = spawn_server(HEADROOM, echo);237 let reply = exchange(238 addr,239 b"POST /jobs HTTP/1.1\r\nContent-Length: 2\r\nContent-Length: 3\r\n\r\n",240 );241 let (head, body) = split(&reply);242 assert!(243 head.starts_with(b"HTTP/1.1 400 Bad Request\r\n"),244 "{}",245 String::from_utf8_lossy(head)246 );247 assert_eq!(body, b"bad request\n");248 }249 250 #[test]251 fn a_malformed_request_line_is_bad_request() {252 let addr = spawn_server(HEADROOM, echo);253 for request in [254 "GET / HTTP/1.0\r\n\r\n",255 "GARBLED\r\n",256 "GET http://evil.example/ HTTP/1.1\r\n\r\n",257 "GET / two HTTP/1.1\r\n\r\n",258 "GE T / HTTP/1.1\r\n\r\n",259 ] {260 let reply = exchange(addr, request.as_bytes());261 let (head, body) = split(&reply);262 assert!(263 head.starts_with(b"HTTP/1.1 400 Bad Request\r\n"),264 "request {request:?}: {}",265 String::from_utf8_lossy(head)266 );267 assert_eq!(body, b"bad request\n");268 }269 }270 271 #[test]272 fn a_chunked_response_arrives_in_order_with_the_terminator() {273 let addr = spawn_server(HEADROOM, |_| Response {274 status: Status::OK,275 headers: vec![("content-type".to_string(), "text/event-stream".to_string())],276 body: Body::Chunks(Box::new(277 vec![278 Ok(b"first".to_vec()),279 Ok(b"second".to_vec()),280 Ok(b"third".to_vec()),281 ]282 .into_iter(),283 )),284 });285 let reply = get(addr, "/events");286 let (head, body) = split(&reply);287 assert_eq!(288 head,289 b"HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\nTransfer-Encoding: chunked\r\nConnection: close\r\n\r\n"290 );291 assert_eq!(292 body,293 b"5\r\nfirst\r\n6\r\nsecond\r\n5\r\nthird\r\n0\r\n\r\n"294 );295 }296 297 #[test]298 fn a_failing_chunk_ends_the_stream_without_the_terminator() {299 let addr = spawn_server(HEADROOM, |_| Response {300 status: Status::OK,301 headers: Vec::new(),302 body: Body::Chunks(Box::new(303 vec![304 Ok(b"whole".to_vec()),305 Ok(b"partial".to_vec()),306 Err(std::io::Error::other("the producer died")),307 ]308 .into_iter(),309 )),310 });311 let reply = get(addr, "/stream");312 let (head, body) = split(&reply);313 assert!(314 head.starts_with(b"HTTP/1.1 200 OK\r\n"),315 "{}",316 String::from_utf8_lossy(head)317 );318 assert!(319 body.starts_with(b"5\r\nwhole\r\n7\r\npartial\r\n"),320 "{}",321 String::from_utf8_lossy(body)322 );323 assert!(324 !body.windows(5).any(|w| w == b"0\r\n\r\n"),325 "the terminator must be absent: {}",326 String::from_utf8_lossy(body)327 );328 }329 330 #[test]331 fn a_full_response_reads_back_byte_for_byte() {332 let addr = spawn_server(HEADROOM, |_| {333 Response::json(Status::ACCEPTED, "{\"id\":\"j1\"}")334 });335 let reply = exchange(addr, b"POST /jobs HTTP/1.1\r\nContent-Length: 2\r\n\r\n{}");336 assert_eq!(337 reply,338 b"HTTP/1.1 202 Accepted\r\ncontent-type: application/json\r\nContent-Length: 11\r\nConnection: close\r\n\r\n{\"id\":\"j1\"}"339 );340 }341 342 #[test]343 fn an_idle_client_is_closed_with_408_at_the_read_timeout() {344 let mut limits = wire(4096, 4096, 4096);345 limits.read_timeout = Duration::from_millis(100);346 limits.head_timeout = Duration::from_secs(2);347 let addr = spawn_server(limits, echo);348 349 let mut stream = TcpStream::connect(addr).expect("connect");350 stream351 .set_read_timeout(Some(Duration::from_secs(2)))352 .expect("read timeout");353 let mut reply = String::new();354 stream355 .read_to_string(&mut reply)356 .expect("the timeout reply");357 assert!(358 reply.starts_with("HTTP/1.1 408 Request Timeout\r\n"),359 "{reply}"360 );361 assert!(reply.ends_with("request timeout\n"), "{reply}");362 }363 364 struct Drip {365 left: usize,366 }367 368 impl Read for Drip {369 fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {370 if self.left == 0 || buf.is_empty() {371 return Ok(0);372 }373 self.left -= 1;374 thread::sleep(Duration::from_millis(5));375 buf[0] = b'A';376 Ok(1)377 }378 }379 380 #[test]381 fn a_head_deadline_stops_a_drip_even_when_each_read_is_fresh() {382 let mut limits = wire(4096, 4096, 4096);383 limits.head_timeout = Duration::from_millis(30);384 limits.read_timeout = Duration::from_secs(1);385 386 // The reader never stalls for the socket timeout. Only the absolute head387 // deadline can end the request.388 let mut reader = BufReader::new(Drip { left: 1000 });389 let why = parse_request(&mut reader, &limits).expect_err("the drip must time out");390 assert!(matches!(why, ParseError::Timeout), "{why:?}");391 }392 393 #[test]394 fn expect_continue_sends_the_interim_response_before_the_body() {395 let addr = spawn_server(HEADROOM, echo);396 let mut stream = TcpStream::connect(addr).expect("connect");397 stream398 .set_read_timeout(Some(Duration::from_secs(2)))399 .expect("read timeout");400 let body = "x".repeat(2048);401 stream402 .write_all(403 format!(404 "POST /jobs HTTP/1.1\r\nExpect: 100-continue\r\nContent-Length: {}\r\n\r\n",405 body.len()406 )407 .as_bytes(),408 )409 .expect("write head");410 411 let interim = read_head(&mut stream);412 assert_eq!(interim, b"HTTP/1.1 100 Continue\r\n\r\n");413 414 stream.write_all(body.as_bytes()).expect("write body");415 let mut reply = String::new();416 stream.read_to_string(&mut reply).expect("read reply");417 assert!(reply.starts_with("HTTP/1.1 200 OK\r\n"), "{reply}");418 assert!(reply.ends_with("POST /jobs - 2048"), "{reply}");419 }420 421 #[test]422 fn an_unknown_expectation_is_417_without_a_body_read() {423 let addr = spawn_server(HEADROOM, echo);424 let reply = exchange(425 addr,426 b"POST /jobs HTTP/1.1\r\nExpect: a-pony\r\nContent-Length: 5\r\n\r\n",427 );428 let (head, body) = split(&reply);429 assert!(430 head.starts_with(b"HTTP/1.1 417 Expectation Failed\r\n"),431 "{:?}",432 String::from_utf8_lossy(head)433 );434 assert_eq!(body, b"expectation failed\n");435 }436 437 #[test]438 fn a_connection_above_the_cap_gets_503() {439 let mut limits = wire(4096, 4096, 4096);440 limits.max_connections = 1;441 let entered = Arc::new(AtomicBool::new(false));442 let release = Arc::new(AtomicBool::new(false));443 let handler = {444 let entered = Arc::clone(&entered);445 let release = Arc::clone(&release);446 move |_request: Request| {447 entered.store(true, Ordering::SeqCst);448 while !release.load(Ordering::SeqCst) {449 thread::sleep(Duration::from_millis(1));450 }451 Response::text(Status::OK, "slow\n")452 }453 };454 let addr = spawn_server(limits, handler);455 456 let mut first = TcpStream::connect(addr).expect("first connect");457 first458 .set_read_timeout(Some(Duration::from_secs(2)))459 .expect("first timeout");460 first461 .write_all(b"GET / HTTP/1.1\r\n\r\n")462 .expect("first request");463 while !entered.load(Ordering::SeqCst) {464 thread::sleep(Duration::from_millis(1));465 }466 467 let mut second = TcpStream::connect(addr).expect("second connect");468 second469 .set_read_timeout(Some(Duration::from_secs(2)))470 .expect("second timeout");471 let _ = second.write_all(b"GET / HTTP/1.1\r\n\r\n");472 let mut busy = String::new();473 second.read_to_string(&mut busy).expect("busy reply");474 release.store(true, Ordering::SeqCst);475 476 let mut served = String::new();477 first.read_to_string(&mut served).expect("first reply");478 assert!(served.starts_with("HTTP/1.1 200 OK\r\n"), "{served}");479 assert!(480 busy.starts_with("HTTP/1.1 503 Service Unavailable\r\n"),481 "{busy}"482 );483 assert!(busy.ends_with("busy\n"), "{busy}");484 }