Cotton code
311 lines · 11.6 KB · RustRaw
//! HTTP/1.1 over a real loopback socket.//!//! A REAL socket, not a byte buffer: the whole reason this module exists//! rather than a client crate is the socket's own timeouts, and a test over a//! `Cursor` would prove the parser and nothing else. The port is the OS's//! (`127.0.0.1:0`) — a test never invents one.use std::io::{Read, Write};use std::net::TcpListener;use std::time::Duration;use super::*;use crate::transport::wire::{dial, Origin};/// A server that reads one request and answers with exactly these bytes.////// Returns the origin to dial and a handle carrying what the request looked/// like on the wire, so the head this module wrote is asserted rather than/// assumed.fn canned(response: &'static [u8]) -> (Origin, std::sync::mpsc::Receiver<String>) {    let listener = TcpListener::bind("127.0.0.1:0").expect("the OS hands out a port");    let port = listener.local_addr().expect("an address").port();    let (sent, seen) = std::sync::mpsc::channel();    std::thread::spawn(move || {        let Ok((mut socket, _)) = listener.accept() else {            return;        };        let mut head = Vec::new();        let mut byte = [0u8; 1];        while socket.read(&mut byte).unwrap_or(0) == 1 {            head.push(byte[0]);            if head.ends_with(b"\r\n\r\n") {                break;            }        }        // Whatever body the request declared, so a POST's bytes are read off        // the socket before the answer goes back.        let text = String::from_utf8_lossy(&head).to_string();        let length: usize = text            .lines()            .find_map(|line| {                line.strip_prefix("Content-Length: ")                    .and_then(|value| value.trim().parse().ok())            })            .unwrap_or(0);        let mut body = vec![0u8; length];        if length > 0 {            let _ = socket.read_exact(&mut body);        }        let _ = sent.send(format!("{text}{}", String::from_utf8_lossy(&body)));        let _ = socket.write_all(response);        let _ = socket.flush();    });    (        Origin::parse(&format!("http://127.0.0.1:{port}")).expect("an origin"),        seen,    )}fn get(origin: &Origin, path: &str) -> Http1Response {    let wire = dial(origin, Duration::from_secs(5)).expect("a socket");    send(        wire,        &Http1Request {            method: "GET",            path,            authority: &origin.authority(),            headers: Vec::new(),            body: None,        },    )    .expect("an answer")}fn whole(mut answer: Http1Response) -> String {    let mut body = String::new();    answer.read_to_string(&mut body).expect("the body");    body}#[test]fn a_sized_body_comes_back_whole_and_the_head_says_what_it_said() {    let (origin, _seen) = canned(        b"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: 13\r\n\r\n{\"ok\":true}!!",    );    let answer = get(&origin, "/v1/me");    assert_eq!(answer.status, 200);    assert_eq!(answer.header("content-type"), Some("application/json"));    assert_eq!(answer.content_length(), Some(13));    assert_eq!(whole(answer), "{\"ok\":true}!!");}#[test]fn a_chunked_body_is_reassembled() {    let (origin, _seen) = canned(        b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n6\r\n world\r\n0\r\n\r\n",    );    assert_eq!(whole(get(&origin, "/v1/me")), "hello world");}#[test]fn a_body_that_ends_with_the_connection_is_read_to_the_close() {    let (origin, _seen) = canned(b"HTTP/1.1 200 OK\r\n\r\nno length here");    assert_eq!(whole(get(&origin, "/v1/me")), "no length here");}#[test]fn a_204_carries_no_body_whatever_it_says() {    let (origin, _seen) = canned(b"HTTP/1.1 204 No Content\r\nContent-Length: 9\r\n\r\nignore me");    let answer = get(&origin, "/v1/me");    assert_eq!(answer.status, 204);    assert_eq!(whole(answer), "");}#[test]fn a_truncated_sized_body_is_a_loud_failure_and_never_a_short_answer() {    // For a snapshot this is a database with its tail missing, and a client    // that returned what arrived would open it.    let (origin, _seen) = canned(b"HTTP/1.1 200 OK\r\nContent-Length: 40\r\n\r\nshort");    let mut answer = get(&origin, "/v1/sync/snapshot");    let mut body = Vec::new();    let error = answer.read_to_end(&mut body).expect_err("a failure");    assert_eq!(error.kind(), std::io::ErrorKind::UnexpectedEof);}#[test]fn the_request_head_names_the_host_closes_the_connection_and_carries_the_headers_given() {    let (origin, seen) = canned(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n");    let wire = dial(&origin, Duration::from_secs(5)).expect("a socket");    let _ = send(        wire,        &Http1Request {            method: "GET",            path: "/v1/sync/pull?since=3",            authority: &origin.authority(),            headers: vec![("x-cotton-device".to_string(), "abc".to_string())],            body: None,        },    )    .expect("an answer");    let head = seen.recv_timeout(Duration::from_secs(5)).expect("the head");    assert!(        head.starts_with("GET /v1/sync/pull?since=3 HTTP/1.1\r\n"),        "{head}"    );    assert!(head.contains(&format!("Host: {}\r\n", origin.authority())));    assert!(head.contains("Connection: close\r\n"));    assert!(head.contains("x-cotton-device: abc\r\n"));    assert!(        !head.to_ascii_lowercase().contains("content-length"),        "a GET declares no body length"    );}#[test]fn a_post_declares_its_length_even_when_the_body_is_empty() {    // The signature already committed to the empty-body hash; a POST with no    // length is one a server may read as having no body at all.    let (origin, seen) = canned(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n");    let wire = dial(&origin, Duration::from_secs(5)).expect("a socket");    let _ = send(        wire,        &Http1Request {            method: "POST",            path: "/v1/me",            authority: &origin.authority(),            headers: Vec::new(),            body: None,        },    )    .expect("an answer");    let head = seen.recv_timeout(Duration::from_secs(5)).expect("the head");    assert!(head.contains("Content-Length: 0\r\n"), "{head}");}#[test]fn the_body_goes_out_exactly_as_the_signature_hashed_it() {    let (origin, seen) = canned(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n");    let body = br#"{"ops":[]}"#;    let wire = dial(&origin, Duration::from_secs(5)).expect("a socket");    let _ = send(        wire,        &Http1Request {            method: "POST",            path: "/v1/sync/push",            authority: &origin.authority(),            headers: vec![("Content-Type".to_string(), "application/json".to_string())],            body: Some(body),        },    )    .expect("an answer");    let seen = seen.recv_timeout(Duration::from_secs(5)).expect("the head");    assert!(seen.ends_with(r#"{"ops":[]}"#), "{seen}");    assert!(seen.contains("Content-Length: 10\r\n"));}#[test]fn a_socket_that_says_nothing_is_a_timeout_rather_than_a_wait_with_no_end() {    // The 2026-09-07 wedge, in miniature: a server that accepts and then says    // nothing at all. The READ times out, so the caller gets a failure instead    // of a request that never settles.    let listener = TcpListener::bind("127.0.0.1:0").expect("the OS hands out a port");    let port = listener.local_addr().expect("an address").port();    // The socket is held until THIS test says it is finished with it, never for    // a span off the clock. A `sleep(5s)` stood here and cost five seconds of    // every run — the thread is joined, so the whole five were real — to prove    // a timeout that has already fired by then.    let (release, released) = std::sync::mpsc::channel::<()>();    let held = std::thread::spawn(move || {        let accepted = listener.accept();        // Ends when the sender is dropped, which is after the assertion below:        // so what this test proves is the TIMEOUT and never a server that hung        // up first.        let _ = released.recv();        drop(accepted);    });    let origin = Origin::parse(&format!("http://127.0.0.1:{port}")).expect("an origin");    // Half a second, not eighty milliseconds. `dial` sets the connect budget    // AND the read timeout from one number, and a loaded runner can miss an    // eighty-millisecond connect to this machine's own loopback and fail here    // for a reason that has nothing to do with the rule under test. The server    // above holds its end until this one has finished asserting, so the read    // really does time out rather than meeting a hang-up.    let wire = dial(&origin, Duration::from_millis(500)).expect("a socket");    let error = send(        wire,        &Http1Request {            method: "GET",            path: "/v1/me",            authority: &origin.authority(),            headers: Vec::new(),            body: None,        },    )    .expect_err("a timeout");    assert!(        matches!(            error.kind(),            std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut        ),        "{error:?}"    );    // The proof is made; the server may let go.    drop(release);    let _ = held.join();}#[test]fn an_answer_that_is_not_http_is_refused_by_name() {    let (origin, _seen) = canned(b"<html>this is a captive portal</html>");    let wire = dial(&origin, Duration::from_secs(5)).expect("a socket");    let error = send(        wire,        &Http1Request {            method: "GET",            path: "/v1/me",            authority: &origin.authority(),            headers: Vec::new(),            body: None,        },    )    .expect_err("a refusal");    assert!(error.to_string().contains("not HTTP"), "{error}");}// ── the inflating arm ───────────────────────────────────────────────────────#[test]fn passes_an_uncompressed_body_straight_through() {    let plain = b"SQLite format 3\0 and then some".to_vec();    let mut reader = Inflating::new(&plain[..], false);    let mut out = Vec::new();    std::io::copy(&mut reader, &mut out).expect("it reads");    assert_eq!(out, plain);}#[test]fn inflates_a_gzipped_body_in_small_reads() {    // The whole point: the caller's loop is unchanged and nothing ever holds a    // database. Read in 7-byte bites so the decoder's own window is exercised    // rather than a single `copy` hiding it.    let plain: Vec<u8> = (0..40_000u32).map(|n| (n % 251) as u8).collect();    let mut encoder =        flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());    std::io::Write::write_all(&mut encoder, &plain).expect("it compresses");    let body = encoder.finish().expect("the gzip closes");    assert!(body.len() < plain.len(), "the fixture should compress");    let mut reader = Inflating::new(&body[..], true);    let mut out = Vec::new();    let mut bite = [0u8; 7];    loop {        match std::io::Read::read(&mut reader, &mut bite).expect("it reads") {            0 => break,            n => out.extend_from_slice(&bite[..n]),        }    }    assert_eq!(out, plain);}#[test]fn only_the_word_gzip_means_gzip() {    assert!(Inflating::<&[u8]>::is_gzip(Some("gzip")));    assert!(Inflating::<&[u8]>::is_gzip(Some(" GZIP ")));    // A server answering with a coding this client never asked for is not    // something to guess at.    assert!(!Inflating::<&[u8]>::is_gzip(Some("identity")));    assert!(!Inflating::<&[u8]>::is_gzip(Some("br")));    assert!(!Inflating::<&[u8]>::is_gzip(Some("gzip, br")));    assert!(!Inflating::<&[u8]>::is_gzip(None));}