Skip to main content

rust_anything/
http.rs

1//! HTTP servers as a black box: start the original (or any build) on a port, send the recorded
2//! requests in order, and store or compare what it answers.
3
4use std::collections::{BTreeMap, BTreeSet};
5use std::io::{Read, Write};
6use std::net::{Ipv6Addr, SocketAddr, TcpListener, TcpStream};
7use std::path::{Path, PathBuf};
8use std::process::{Child, Command, Stdio};
9use std::time::{Duration, Instant};
10
11use anyhow::{Context, Result, bail, ensure};
12use serde::{Deserialize, Serialize};
13use serde_json::Value;
14use toml_edit::{DocumentMut, Item, Table, value};
15
16use crate::app::{
17    self, Config, Failure, Fallback, Normalizers, Problem, RecordOptions, RecordOutcome,
18    ReplayOutcome,
19};
20
21pub const HTTP_DIR: &str = "http";
22const READY: Duration = Duration::from_secs(60);
23const SKIP_HEADERS: [&str; 12] = [
24    "date",
25    "host",
26    "server",
27    "connection",
28    "keep-alive",
29    "transfer-encoding",
30    "content-length",
31    "x-powered-by",
32    "etag",
33    "last-modified",
34    "age",
35    "via",
36];
37const LOCAL_HOSTS: [&str; 4] = ["localhost", "127.0.0.1", "0.0.0.0", "[::1]"];
38
39/// `http` in `rust/app-cases/rust-anything.json`: the app is a server.
40#[derive(Debug, Clone, Default, Serialize, Deserialize)]
41pub struct HttpConfig {
42    /// A port the original always listens on. When unset, every start gets a free port through
43    /// the `PORT` environment variable and `{port}` in the command.
44    #[serde(default, skip_serializing_if = "Option::is_none")]
45    pub port: Option<u16>,
46    /// Arguments every start gets after its command: the original's and every build's.
47    #[serde(default, skip_serializing_if = "Vec::is_empty")]
48    pub args: Vec<String>,
49    /// Repository paths copied (from the snapshot in `http/files/`) into a fresh working
50    /// directory before every start, so state the server writes never leaks between runs.
51    #[serde(default, skip_serializing_if = "Vec::is_empty")]
52    pub fresh: Vec<String>,
53    /// Milliseconds to wait after each response before the next request.
54    #[serde(default, skip_serializing_if = "Option::is_none")]
55    pub pace_ms: Option<u64>,
56    /// Seconds to wait for the server to listen before giving up (`app record --ready-timeout`).
57    /// Unset keeps the default, `READY`.
58    #[serde(default, skip_serializing_if = "Option::is_none")]
59    pub ready_secs: Option<u64>,
60}
61
62/// How long a start waits for the port: the saved `--ready-timeout`, or `READY`.
63pub(crate) fn ready_timeout(http: &HttpConfig) -> Duration {
64    http.ready_secs.map_or(READY, Duration::from_secs)
65}
66
67/// The `http` config of a recording: the saved one, changed by what this record was given.
68pub(crate) fn merge_config(
69    saved: Option<HttpConfig>,
70    opts: &RecordOptions,
71) -> Result<Option<HttpConfig>> {
72    let asked = opts.http == Some(true)
73        || opts.port.is_some()
74        || opts.server_args.is_some_and(|args| !args.is_empty())
75        || opts.pace_ms.is_some()
76        || opts.ready_secs.is_some();
77    if opts.http == Some(false) {
78        ensure!(
79            !asked,
80            "--no-http cannot be combined with --http, --port, --arg, --pace or --ready-timeout"
81        );
82        return Ok(None);
83    }
84    let mut config = match (saved, asked) {
85        (Some(c), _) => c,
86        (None, true) => HttpConfig::default(),
87        (None, false) => return Ok(None),
88    };
89    if let Some(port) = opts.port {
90        config.port = (port > 0).then_some(port);
91    }
92    if let Some(args) = opts.server_args {
93        config.args = args.to_vec();
94    }
95    if let Some(fresh) = opts.fresh {
96        config.fresh = fresh.to_vec();
97    }
98    if let Some(pace) = opts.pace_ms {
99        config.pace_ms = (pace > 0).then_some(pace);
100    }
101    if let Some(secs) = opts.ready_secs {
102        config.ready_secs = (secs > 0).then_some(secs);
103    }
104    Ok(Some(config))
105}
106
107pub(crate) const FILES_DIR: &str = "files";
108
109pub(crate) fn copy_tree(from: &Path, to: &Path) -> Result<()> {
110    if from.is_dir() {
111        std::fs::create_dir_all(to)?;
112        for entry in std::fs::read_dir(from)?.flatten() {
113            copy_tree(&entry.path(), &to.join(entry.file_name()))?;
114        }
115    } else {
116        if let Some(parent) = to.parent() {
117            std::fs::create_dir_all(parent)?;
118        }
119        std::fs::copy(from, to)
120            .with_context(|| format!("copying {} to {}", from.display(), to.display()))?;
121    }
122    Ok(())
123}
124
125/// Copies the `fresh` paths from the repository into `http/files/`, replacing the last snapshot.
126fn snapshot(repo: &Path, fresh: &[String]) -> Result<Option<PathBuf>> {
127    let dir = app::cases_dir(repo).join(HTTP_DIR).join(FILES_DIR);
128    snapshot_to(repo, fresh, &dir)
129}
130
131/// Copies the `fresh` paths from the repository into `dir`, replacing the last snapshot.
132pub(crate) fn snapshot_to(repo: &Path, fresh: &[String], dir: &Path) -> Result<Option<PathBuf>> {
133    if fresh.is_empty() {
134        return Ok(None);
135    }
136    let dir = dir.to_path_buf();
137    let _ = std::fs::remove_dir_all(&dir);
138    for path in fresh {
139        let rel = Path::new(path);
140        ensure!(
141            rel.is_relative()
142                && rel
143                    .components()
144                    .all(|c| matches!(c, std::path::Component::Normal(_))),
145            "--fresh `{path}`: give a path inside the repository, relative to it"
146        );
147        let from = repo.join(rel);
148        ensure!(from.exists(), "--fresh `{path}`: no such file or folder");
149        let to = if path.ends_with('/') && from.is_dir() {
150            dir.clone()
151        } else {
152            dir.join(rel)
153        };
154        copy_tree(&from, &to)?;
155    }
156    Ok(Some(dir))
157}
158
159/// The snapshot replay starts every build from, when the recording has `fresh` paths.
160fn saved_snapshot(repo: &Path, config: &Config) -> Result<Option<PathBuf>> {
161    if config.http.as_ref().is_none_or(|h| h.fresh.is_empty()) {
162        return Ok(None);
163    }
164    let dir = app::cases_dir(repo).join(HTTP_DIR).join(FILES_DIR);
165    ensure!(
166        dir.is_dir(),
167        "no {}: record again to snapshot the fresh files",
168        dir.display()
169    );
170    Ok(Some(dir))
171}
172
173fn get() -> String {
174    "GET".to_string()
175}
176
177/// One request, as recorded and as written in an `--inputs` line.
178#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
179pub struct Req {
180    #[serde(default = "get")]
181    pub method: String,
182    pub path: String,
183    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
184    pub headers: BTreeMap<String, String>,
185    #[serde(default, skip_serializing_if = "Option::is_none")]
186    pub body: Option<String>,
187    /// Base64-encoded body for non-UTF-8 payloads (images, PDFs, protobufs, binary uploads).
188    #[serde(default, skip_serializing_if = "Option::is_none")]
189    pub body_base64: Option<String>,
190    /// Path to a file with raw request body bytes (under `http/` in `.toml` cases, or relative to
191    /// the inputs file / repo in `--inputs`).
192    #[serde(default, skip_serializing_if = "Option::is_none")]
193    pub body_file: Option<String>,
194}
195
196impl Req {
197    fn from_body_bytes(bytes: Vec<u8>) -> (Option<String>, Option<String>) {
198        match String::from_utf8(bytes) {
199            Ok(text) => (Some(text), None),
200            Err(err) => (None, Some(encode_base64(&err.into_bytes()))),
201        }
202    }
203
204    fn body_bytes(&self) -> Result<Option<Vec<u8>>> {
205        if let Some(b64) = &self.body_base64 {
206            Ok(Some(decode_base64_strict(b64)?))
207        } else if let Some(text) = &self.body {
208            Ok(Some(text.as_bytes().to_vec()))
209        } else {
210            Ok(None)
211        }
212    }
213}
214
215#[derive(Debug, Deserialize)]
216struct HttpInput {
217    #[serde(default)]
218    name: Option<String>,
219    #[serde(flatten)]
220    req: Req,
221}
222
223#[derive(Debug, Clone)]
224pub(crate) struct Resp {
225    pub(crate) status: u16,
226    pub(crate) headers: BTreeMap<String, String>,
227    pub(crate) body: Vec<u8>,
228}
229
230/// Picks an ephemeral port free on IPv4 loopback and not already bound on IPv6 loopback
231/// (on dual-stack hosts a port free on `127.0.0.1` can still be bound on `[::1]`, which
232/// `listening()` treats as in use).
233pub fn free_port() -> Result<u16> {
234    for _ in 0..16 {
235        let v4 = TcpListener::bind("127.0.0.1:0")?;
236        let port = v4.local_addr()?.port();
237        match TcpListener::bind(SocketAddr::from((Ipv6Addr::LOCALHOST, port))) {
238            Ok(_) => return Ok(port),
239            Err(e) if e.kind() == std::io::ErrorKind::AddrInUse => continue,
240            Err(_) => return Ok(port),
241        }
242    }
243    bail!("could not find a free loopback port")
244}
245
246/// The loopback addresses a server may listen on. A server that binds to `localhost` can get only
247/// `::1` (Node 17+ may pick it), so both are tried, IPv4 first.
248fn local(port: u16) -> [SocketAddr; 2] {
249    [
250        SocketAddr::from(([127, 0, 0, 1], port)),
251        SocketAddr::from((Ipv6Addr::LOCALHOST, port)),
252    ]
253}
254
255/// The first loopback address that accepts a connection on `port`.
256fn listening(port: u16, wait: Duration) -> Option<SocketAddr> {
257    local(port)
258        .into_iter()
259        .find(|addr| TcpStream::connect_timeout(addr, wait).is_ok())
260}
261
262fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
263    haystack.windows(needle.len()).position(|w| w == needle)
264}
265
266fn fill(stream: &mut impl Read, buf: &mut Vec<u8>, need: usize) -> Result<()> {
267    let mut chunk = [0u8; 8192];
268    while buf.len() < need {
269        let n = stream.read(&mut chunk)?;
270        ensure!(n > 0, "the connection closed in the middle of the response");
271        buf.extend_from_slice(&chunk[..n]);
272    }
273    Ok(())
274}
275
276fn chunk_line_end(stream: &mut impl Read, buf: &mut Vec<u8>) -> Result<usize> {
277    loop {
278        if let Some(end) = find(buf, b"\r\n") {
279            return Ok(end);
280        }
281        let need = buf.len() + 1;
282        fill(stream, buf, need)?;
283    }
284}
285
286fn read_chunked(stream: &mut impl Read, mut buf: Vec<u8>) -> Result<Vec<u8>> {
287    let mut body = Vec::new();
288    loop {
289        let line_end = chunk_line_end(stream, &mut buf)?;
290        let size_text = String::from_utf8_lossy(&buf[..line_end]).into_owned();
291        let size = usize::from_str_radix(size_text.split(';').next().unwrap_or("").trim(), 16)
292            .with_context(|| format!("bad chunk size `{size_text}`"))?;
293        buf.drain(..line_end + 2);
294        if size == 0 {
295            loop {
296                let line_end = chunk_line_end(stream, &mut buf)?;
297                if line_end == 0 {
298                    return Ok(body);
299                }
300                buf.drain(..line_end + 2);
301            }
302        }
303        let end = size.checked_add(2).context("chunk size is too large")?;
304        fill(stream, &mut buf, end)?;
305        ensure!(&buf[size..end] == b"\r\n", "bad chunk terminator");
306        body.extend_from_slice(&buf[..size]);
307        buf.drain(..end);
308    }
309}
310
311fn read_response(stream: &mut impl Read, head_only: bool) -> Result<Resp> {
312    let mut buf = Vec::new();
313    let mut chunk = [0u8; 8192];
314    let (status, head, mut rest) = loop {
315        let header_end = loop {
316            if let Some(i) = find(&buf, b"\r\n\r\n") {
317                break i;
318            }
319            let n = stream.read(&mut chunk)?;
320            ensure!(n > 0, "the connection closed before a full response");
321            buf.extend_from_slice(&chunk[..n]);
322        };
323        let head = String::from_utf8_lossy(&buf[..header_end]).into_owned();
324        let status_line = head.split("\r\n").next().unwrap_or_default();
325        let status: u16 = status_line
326            .split_whitespace()
327            .nth(1)
328            .and_then(|s| s.parse().ok())
329            .with_context(|| format!("not an HTTP response: `{status_line}`"))?;
330        let rest = buf.split_off(header_end + 4);
331        if status == 101 || !(100..200).contains(&status) {
332            break (status, head, rest);
333        }
334        buf = rest;
335    };
336    let lines = head.split("\r\n").skip(1);
337    let mut headers: BTreeMap<String, String> = BTreeMap::new();
338    for line in lines {
339        if let Some((k, v)) = line.split_once(':') {
340            let v = v.trim().to_string();
341            headers
342                .entry(k.trim().to_ascii_lowercase())
343                .and_modify(|e| {
344                    e.push_str(", ");
345                    e.push_str(&v);
346                })
347                .or_insert(v);
348        }
349    }
350    let chunked = headers
351        .get("transfer-encoding")
352        .is_some_and(|t| t.to_ascii_lowercase().contains("chunked"));
353    let body = if head_only || status == 204 || status == 304 || (100..200).contains(&status) {
354        Vec::new()
355    } else if chunked {
356        read_chunked(stream, rest)?
357    } else if let Some(lengths) = headers.get("content-length") {
358        let parse = |value: &str| -> Result<usize> {
359            let value = value.trim();
360            ensure!(
361                !value.is_empty() && value.bytes().all(|b| b.is_ascii_digit()),
362                "invalid Content-Length"
363            );
364            value.parse().context("invalid Content-Length")
365        };
366        let mut lengths = lengths.split(',');
367        let len = parse(lengths.next().unwrap_or_default())?;
368        for other in lengths {
369            ensure!(parse(other)? == len, "conflicting Content-Length headers");
370        }
371        fill(stream, &mut rest, len)?;
372        rest.truncate(len);
373        rest
374    } else {
375        stream
376            .read_to_end(&mut rest)
377            .context("reading close-delimited HTTP body")?;
378        rest
379    };
380    Ok(Resp {
381        status,
382        headers,
383        body,
384    })
385}
386
387fn connect(addr: SocketAddr, req: &Req, host: &str, timeout: Duration) -> Result<TcpStream> {
388    let mut stream = TcpStream::connect_timeout(&addr, timeout)?;
389    stream.set_read_timeout(Some(timeout))?;
390    stream.set_write_timeout(Some(timeout))?;
391    let body_opt = req.body_bytes()?;
392    let body = body_opt.as_deref().unwrap_or(&[]);
393    let mut head = format!(
394        "{} {} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n",
395        req.method, req.path
396    );
397    for (k, v) in &req.headers {
398        if !matches!(
399            k.to_ascii_lowercase().as_str(),
400            "host" | "connection" | "content-length"
401        ) {
402            head += &format!("{k}: {v}\r\n");
403        }
404    }
405    if body_opt.is_some() || matches!(req.method.as_str(), "POST" | "PUT" | "PATCH") {
406        head += &format!("Content-Length: {}\r\n", body.len());
407    }
408    head += "\r\n";
409    stream.write_all(head.as_bytes())?;
410    stream.write_all(body)?;
411    Ok(stream)
412}
413
414fn send(addr: SocketAddr, req: &Req, timeout: Duration) -> Result<Resp> {
415    let mut stream = connect(addr, req, &addr.to_string(), timeout)?;
416    read_response(&mut stream, req.method == "HEAD")
417}
418
419/// Reads through to `inner` and keeps every byte read.
420struct Tee<R> {
421    inner: R,
422    seen: Vec<u8>,
423}
424
425impl<R: Read> Read for Tee<R> {
426    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
427        let n = self.inner.read(buf)?;
428        self.seen.extend_from_slice(&buf[..n]);
429        Ok(n)
430    }
431}
432
433/// Sends `req` as `send` does, keeping the client's `Host`, and returns the parsed response with
434/// the bytes it came in, so a proxy can relay them unchanged.
435pub(crate) fn exchange(addr: SocketAddr, req: &Req, timeout: Duration) -> Result<(Resp, Vec<u8>)> {
436    let host = req
437        .headers
438        .iter()
439        .find(|(k, _)| k.eq_ignore_ascii_case("host"))
440        .map_or_else(|| addr.to_string(), |(_, v)| v.clone());
441    let stream = connect(addr, req, &host, timeout)?;
442    let mut tee = Tee {
443        inner: stream,
444        seen: Vec::new(),
445    };
446    let resp = read_response(&mut tee, req.method == "HEAD")?;
447    Ok((resp, tee.seen))
448}
449
450/// Headers of a client's request that belong to its connection, not to the request.
451const HOP_HEADERS: [&str; 5] = [
452    "connection",
453    "keep-alive",
454    "transfer-encoding",
455    "content-length",
456    "expect",
457];
458
459/// Reads one request from a client: the head, then a body framed by `Content-Length` or chunked.
460/// A client waiting on `Expect: 100-continue` is told to go on.
461pub(crate) fn read_request<S: Read + Write>(stream: &mut S) -> Result<Req> {
462    let mut buf = Vec::new();
463    let mut chunk = [0u8; 8192];
464    let header_end = loop {
465        if let Some(i) = find(&buf, b"\r\n\r\n") {
466            break i;
467        }
468        ensure!(buf.len() < 1 << 20, "the request head is too large");
469        let n = stream.read(&mut chunk)?;
470        ensure!(n > 0, "the connection closed before a full request");
471        buf.extend_from_slice(&chunk[..n]);
472    };
473    let head = String::from_utf8_lossy(&buf[..header_end]).into_owned();
474    let rest = buf.split_off(header_end + 4);
475    let mut lines = head.split("\r\n");
476    let line = lines.next().unwrap_or_default();
477    let mut parts = line.split_whitespace();
478    let (Some(method), Some(target), Some(_)) = (parts.next(), parts.next(), parts.next()) else {
479        bail!("not an HTTP request: `{line}`");
480    };
481    let path = match target.split_once("://") {
482        Some((_, rest)) => rest.find('/').map_or("/", |i| &rest[i..]),
483        None => target,
484    };
485    ensure!(path.starts_with('/'), "not an HTTP request: `{line}`");
486    let mut headers = BTreeMap::new();
487    let mut framing = BTreeMap::new();
488    for line in lines {
489        if let Some((k, v)) = line.split_once(':') {
490            let (k, v) = (k.trim(), v.trim().to_string());
491            let lower = k.to_ascii_lowercase();
492            if HOP_HEADERS.contains(&lower.as_str()) {
493                framing.insert(lower, v);
494            } else {
495                headers.insert(k.to_string(), v);
496            }
497        }
498    }
499    if framing
500        .get("expect")
501        .is_some_and(|e| e.eq_ignore_ascii_case("100-continue"))
502    {
503        stream.write_all(b"HTTP/1.1 100 Continue\r\n\r\n")?;
504    }
505    let chunked = framing
506        .get("transfer-encoding")
507        .is_some_and(|t| t.to_ascii_lowercase().contains("chunked"));
508    let body = if chunked {
509        Some(read_chunked(stream, rest)?)
510    } else if let Some(len) = framing.get("content-length") {
511        let len: usize = len.parse().context("invalid Content-Length")?;
512        let mut rest = rest;
513        fill(stream, &mut rest, len)?;
514        rest.truncate(len);
515        Some(rest)
516    } else {
517        None
518    };
519    let (body, body_base64) = match body {
520        Some(bytes) => Req::from_body_bytes(bytes),
521        None => (None, None),
522    };
523    Ok(Req {
524        method: method.to_string(),
525        path: path.to_string(),
526        headers,
527        body,
528        body_base64,
529        body_file: None,
530    })
531}
532
533/// A server process; stopped (SIGTERM, then SIGKILL) when dropped.
534pub(crate) struct Server {
535    child: Child,
536    /// The loopback address that answered while waiting for the server; requests go there.
537    pub(crate) addr: SocketAddr,
538    dir: PathBuf,
539    cwd: PathBuf,
540    log: PathBuf,
541    stopped: bool,
542    sinks: Option<crate::effects::Sinks>,
543}
544
545#[derive(Debug)]
546struct PortInUse(u16);
547
548impl std::fmt::Display for PortInUse {
549    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
550        write!(f, "port {} is already in use", self.0)
551    }
552}
553
554impl std::error::Error for PortInUse {}
555
556impl Server {
557    pub(crate) fn start(
558        command: &[String],
559        launch: &Launch,
560        repo: &Path,
561        port: u16,
562    ) -> Result<Server> {
563        if listening(port, Duration::from_millis(100)).is_some() {
564            return Err(anyhow::Error::new(PortInUse(port)));
565        }
566        let dir = app::temp_dir("server")?;
567        let words: Vec<String> = command
568            .iter()
569            .map(|w| app::resolve_word(repo, &w.replace("{port}", &port.to_string())))
570            .collect();
571        let (program, rest) = words.split_first().context("empty command")?;
572        let log = dir.join("fallback.log");
573        let cwd = match launch.files {
574            Some(files) => {
575                let cwd = dir.join("cwd");
576                copy_tree(files, &cwd)?;
577                cwd
578            }
579            None => repo.to_path_buf(),
580        };
581        let sinks = launch
582            .effects
583            .map(|config| -> Result<_> {
584                let sinks = crate::effects::Sinks::start(config)?;
585                sinks.reset(&cwd, repo)?;
586                Ok(sinks)
587            })
588            .transpose()?;
589        let mut cmd = Command::new(program);
590        cmd.args(rest)
591            .args(
592                launch
593                    .args
594                    .iter()
595                    .map(|a| a.replace("{port}", &port.to_string())),
596            )
597            .current_dir(&cwd)
598            .envs(sinks.iter().flat_map(crate::effects::Sinks::env))
599            .env("PORT", port.to_string())
600            .env(app::FALLBACK_ENV, &log)
601            .stdin(Stdio::null())
602            .stdout(std::fs::File::create(dir.join("stdout"))?)
603            .stderr(std::fs::File::create(dir.join("stderr"))?);
604        let mut child = cmd
605            .spawn()
606            .with_context(|| format!("starting `{}`", command.join(" ")))?;
607        // A huge `--ready-timeout` has no representable deadline; treat it as "no deadline" rather
608        // than panicking after the child is already running.
609        let deadline = Instant::now().checked_add(launch.ready);
610        let addr = loop {
611            let failure = if let Some(status) = child.try_wait()? {
612                Some(format!("exited ({status}) before listening"))
613            } else if let Some(addr) = listening(port, Duration::from_millis(200)) {
614                if let Some(status) = child.try_wait()? {
615                    Some(format!("exited ({status}) before listening"))
616                } else {
617                    break addr;
618                }
619            } else if deadline.is_some_and(|d| Instant::now() > d) {
620                Some(format!("did not listen within {}s", launch.ready.as_secs()))
621            } else {
622                None
623            };
624            if let Some(failure) = failure {
625                let _ = child.kill();
626                let _ = child.wait();
627                let stderr = std::fs::read_to_string(dir.join("stderr")).unwrap_or_default();
628                let tail: Vec<&str> = stderr.lines().rev().take(15).collect();
629                let tail: Vec<&str> = tail.into_iter().rev().collect();
630                let _ = std::fs::remove_dir_all(&dir);
631                bail!(
632                    "`{}` {failure} on port {port}{}",
633                    command.join(" "),
634                    if tail.is_empty() {
635                        String::new()
636                    } else {
637                        format!(":\n{}", tail.join("\n"))
638                    }
639                );
640            }
641            std::thread::sleep(Duration::from_millis(50));
642        };
643        Ok(Server {
644            child,
645            addr,
646            dir,
647            cwd,
648            log,
649            stopped: false,
650            sinks,
651        })
652    }
653
654    /// Empties the sinks, for a server whose effects are not compared.
655    pub(crate) fn drain_effects(&self, repo: &Path) {
656        if let Some(sinks) = &self.sinks {
657            sinks.take(&self.cwd, repo);
658        }
659    }
660
661    fn fallbacks(&self) -> Option<usize> {
662        std::fs::read_to_string(&self.log)
663            .ok()
664            .map(|t| t.lines().count())
665    }
666
667    fn stop(&mut self) {
668        if self.stopped {
669            return;
670        }
671        self.stopped = true;
672        // The whole process tree: the real server can be a grandchild (`npm start`, `sh -c`).
673        // The server stays in our process group, so a Ctrl-C in the terminal still reaches it.
674        #[cfg(unix)]
675        {
676            // The one we started is reaped only below, so its pid cannot go to another process
677            // while `end_tree` may still signal it.
678            end_tree(
679                self.child.id(),
680                Duration::from_secs(5),
681                processes,
682                |signal, pids| {
683                    let _ = Command::new("kill")
684                        .arg(signal)
685                        .arg("--")
686                        .args(pids.iter().map(u32::to_string))
687                        .stderr(Stdio::null())
688                        .status();
689                },
690            );
691        }
692        #[cfg(windows)]
693        {
694            let _ = Command::new("taskkill")
695                .args(["/T", "/F", "/PID", &self.child.id().to_string()])
696                .stdout(Stdio::null())
697                .stderr(Stdio::null())
698                .status();
699        }
700        let _ = self.child.kill();
701        let _ = self.child.wait();
702        let _ = std::fs::remove_dir_all(&self.dir);
703    }
704}
705
706impl Drop for Server {
707    fn drop(&mut self) {
708        self.stop();
709    }
710}
711
712/// Every process as `pid ppid stat start` lines, from `ps` (the start time is several words).
713#[cfg(unix)]
714fn processes() -> Option<String> {
715    let out = Command::new("ps")
716        .args([
717            "-A", "-o", "pid=", "-o", "ppid=", "-o", "stat=", "-o", "lstart=",
718        ])
719        .stderr(Stdio::null())
720        .output()
721        .ok()?;
722    out.status
723        .success()
724        .then(|| String::from_utf8_lossy(&out.stdout).into_owned())
725}
726
727/// Ends `root` and every process below it: TERM, a wait of up to `grace` until a listing shows
728/// none of them running (so nothing still holds the port), then KILL and the same wait. Every
729/// listing adds the processes forked since the last one below a process it tracks, and sends them
730/// the current signal too. A failed listing proves nothing: the wait goes on and KILL still
731/// follows, to `root` alone if the listing before it failed too, and to the rest of the tree
732/// once a listing shows them running as they were. A process whose parent exited
733/// before any listing saw it is reparented and can no longer be traced to the server. Returns
734/// whether a listing showed the whole tree gone.
735///
736/// A process is tracked with its start time, and is signalled only while the latest listing shows
737/// that pid with that start time, so a pid that went to another process after its own exited is
738/// left alone (two processes started in the same second on the same pid look alike, and a pid
739/// reused between a listing and the signal is not caught). `root` is the caller's child, not yet
740/// reaped, so its pid stays its own and it needs no start time.
741#[cfg(any(unix, test))]
742fn end_tree(
743    root: u32,
744    grace: Duration,
745    mut list: impl FnMut() -> Option<String>,
746    mut signal: impl FnMut(&str, &[u32]),
747) -> bool {
748    let mut tree: Vec<(u32, Option<String>)> = vec![(root, None)];
749    for sig in ["-TERM", "-KILL"] {
750        // Each stage's targets come from a listing taken now: an older one may name a pid that
751        // went to another process since. Without a listing, only `root` is surely ours, and the
752        // others get the signal once a listing shows them again.
753        let mut sent: Vec<(u32, Option<String>)> = Vec::new();
754        let fresh = list();
755        if let Some(ps) = &fresh {
756            grow(ps, &mut tree);
757        }
758        signal_due(sig, fresh.as_deref(), &tree, &mut sent, &mut signal);
759        let deadline = Instant::now() + grace;
760        loop {
761            if let Some(ps) = list() {
762                grow(&ps, &mut tree);
763                signal_due(sig, Some(&ps), &tree, &mut sent, &mut signal);
764                if running(Some(&ps), &tree).is_empty() {
765                    return true;
766                }
767            }
768            if Instant::now() > deadline {
769                break;
770            }
771            std::thread::sleep(Duration::from_millis(20));
772        }
773    }
774    false
775}
776
777/// Sends `sig` to the processes in `tree` that `ps` shows running (see `running`) and that have
778/// not had it yet, and records them in `sent`.
779#[cfg(any(unix, test))]
780fn signal_due(
781    sig: &str,
782    ps: Option<&str>,
783    tree: &[(u32, Option<String>)],
784    sent: &mut Vec<(u32, Option<String>)>,
785    signal: &mut impl FnMut(&str, &[u32]),
786) {
787    let due: Vec<_> = tree.iter().filter(|t| !sent.contains(t)).cloned().collect();
788    let pids = running(ps, &due);
789    if !pids.is_empty() {
790        signal(sig, &pids);
791        sent.extend(due.into_iter().filter(|(pid, _)| pids.contains(pid)));
792    }
793}
794
795/// A process in a `ps` line of `pid ppid stat start`.
796#[cfg(any(unix, test))]
797struct Listed<'a> {
798    pid: u32,
799    ppid: u32,
800    stat: &'a str,
801    start: String,
802}
803
804#[cfg(any(unix, test))]
805fn listed(ps: &str) -> Vec<Listed<'_>> {
806    ps.lines()
807        .filter_map(|line| {
808            let mut fields = line.split_whitespace();
809            Some(Listed {
810                pid: fields.next()?.parse().ok()?,
811                ppid: fields.next()?.parse().ok()?,
812                stat: fields.next()?,
813                start: fields.collect::<Vec<_>>().join(" "),
814            })
815        })
816        .collect()
817}
818
819/// Whether a listed process is the tracked one: the same pid, and the same start time if one was
820/// recorded.
821#[cfg(any(unix, test))]
822fn same(p: &Listed, pid: u32, start: Option<&str>) -> bool {
823    p.pid == pid && start.is_none_or(|s| s == p.start)
824}
825
826/// Adds to `tree` every process listed below one in it, with its start time.
827#[cfg(any(unix, test))]
828fn grow(ps: &str, tree: &mut Vec<(u32, Option<String>)>) {
829    let procs = listed(ps);
830    let mut i = 0;
831    while let Some((pid, start)) = tree.get(i).cloned() {
832        // A pid that went to another process has no children of ours.
833        if procs.iter().any(|p| same(p, pid, start.as_deref())) {
834            for p in procs.iter().filter(|p| p.ppid == pid) {
835                if !tree.iter().any(|(t, s)| same(p, *t, s.as_deref())) {
836                    tree.push((p.pid, Some(p.start.clone())));
837                }
838            }
839        }
840        i += 1;
841    }
842}
843
844/// The tracked processes that still run as the listing shows them: the same process (see `same`)
845/// and not a zombie, which holds no port. With no listing, only `root` (no start time) is known.
846#[cfg(any(unix, test))]
847fn running(ps: Option<&str>, tree: &[(u32, Option<String>)]) -> Vec<u32> {
848    let Some(ps) = ps else {
849        return tree
850            .iter()
851            .filter(|(_, start)| start.is_none())
852            .map(|(pid, _)| *pid)
853            .collect();
854    };
855    let procs = listed(ps);
856    tree.iter()
857        .filter(|(pid, start)| {
858            procs
859                .iter()
860                .any(|p| same(p, *pid, start.as_deref()) && !p.stat.starts_with('Z'))
861        })
862        .map(|(pid, _)| *pid)
863        .collect()
864}
865
866type Answer = (
867    std::result::Result<Resp, String>,
868    Option<bool>,
869    Option<Vec<u8>>,
870);
871
872/// What every start gets besides its command: the server's arguments and its fresh files.
873pub(crate) struct Launch<'a> {
874    pub(crate) args: &'a [String],
875    pub(crate) files: Option<&'a Path>,
876    pub(crate) pace: Option<Duration>,
877    pub(crate) effects: Option<&'a crate::effects::EffectsConfig>,
878    /// How long to wait for the port before giving up.
879    pub(crate) ready: Duration,
880}
881
882/// Starts a server on an auto-picked ephemeral port, retrying if another process claims the port
883/// in the brief window between `free_port()` and `Server::start()`.
884pub(crate) fn start_ephemeral(
885    command: &[String],
886    launch: &Launch,
887    repo: &Path,
888    mut next_port: impl FnMut() -> Result<u16>,
889) -> Result<Server> {
890    for attempt in 0..5 {
891        let port = next_port()?;
892        match Server::start(command, launch, repo, port) {
893            Ok(server) => return Ok(server),
894            Err(e) if e.downcast_ref::<PortInUse>().is_some() && attempt < 4 => continue,
895            Err(e) => return Err(e),
896        }
897    }
898    unreachable!("loop always returns on attempt 4 or earlier")
899}
900
901/// Starts the server once and sends every request in order.
902fn run_all(
903    command: &[String],
904    launch: &Launch,
905    repo: &Path,
906    fixed_port: Option<u16>,
907    reqs: &[&Req],
908    timeout: Duration,
909) -> Result<Vec<Answer>> {
910    let mut server = match fixed_port {
911        Some(port) => Server::start(command, launch, repo, port)?,
912        None => start_ephemeral(command, launch, repo, free_port)?,
913    };
914    let mut out = Vec::new();
915    for req in reqs {
916        let before = server.fallbacks().unwrap_or(0);
917        let resp = send(server.addr, req, timeout).map_err(|e| format!("{e:#}"));
918        if let Some(pace) = launch.pace {
919            std::thread::sleep(pace);
920        }
921        let fell_back = server.fallbacks().map(|after| after > before);
922        let effects = server.sinks.as_ref().map(|s| s.take(&server.cwd, repo));
923        out.push((resp, fell_back, effects));
924    }
925    server.stop();
926    Ok(out)
927}
928
929fn percent_decode(text: &str) -> String {
930    let bytes = text.as_bytes();
931    let mut out = Vec::new();
932    let mut i = 0;
933    while i < bytes.len() {
934        if bytes[i] == b'%'
935            && let Some(hex) = text.get(i + 1..i + 3)
936            // Two hex digits only: `from_str_radix` also takes a leading `+`, which would turn
937            // `%+1` into an escape for byte 1.
938            && hex.len() == 2
939            && hex.bytes().all(|b| b.is_ascii_hexdigit())
940        {
941            out.push(u8::from_str_radix(hex, 16).unwrap_or(0));
942            i += 3;
943            continue;
944        }
945        out.push(bytes[i]);
946        i += 1;
947    }
948    String::from_utf8_lossy(&out).into_owned()
949}
950
951fn percent_encode(text: &str) -> String {
952    let mut out = String::new();
953    for b in text.bytes() {
954        if b.is_ascii_alphanumeric() || b"-._~".contains(&b) {
955            out.push(char::from(b));
956        } else {
957            out += &format!("%{b:02X}");
958        }
959    }
960    out
961}
962
963struct FormPart {
964    name: String,
965    filename: Option<String>,
966    content_type: Option<String>,
967    data: Vec<u8>,
968}
969
970fn infer_mime(path: &str) -> &'static str {
971    match Path::new(path)
972        .extension()
973        .and_then(|e| e.to_str())
974        .map(str::to_ascii_lowercase)
975        .as_deref()
976    {
977        Some("png") => "image/png",
978        Some("jpg" | "jpeg") => "image/jpeg",
979        Some("gif") => "image/gif",
980        Some("webp") => "image/webp",
981        Some("pdf") => "application/pdf",
982        Some("json") => "application/json",
983        Some("xml") => "application/xml",
984        Some("html" | "htm") => "text/html",
985        Some("txt" | "csv") => "text/plain",
986        _ => "application/octet-stream",
987    }
988}
989
990fn escape_param(s: &str) -> String {
991    s.replace(['\r', '\n'], "")
992        .replace('\\', "\\\\")
993        .replace('"', "\\\"")
994}
995
996fn split_form_segments(s: &str) -> Vec<&str> {
997    let mut out = Vec::new();
998    let bytes = s.as_bytes();
999    let mut start = 0usize;
1000    let mut in_quotes = false;
1001    let mut i = 0usize;
1002    while i < bytes.len() {
1003        match bytes[i] {
1004            b'\\' if in_quotes && i + 1 < bytes.len() => i += 2,
1005            b'"' => {
1006                in_quotes = !in_quotes;
1007                i += 1;
1008            }
1009            b';' if !in_quotes => {
1010                out.push(&s[start..i]);
1011                i += 1;
1012                start = i;
1013            }
1014            _ => i += 1,
1015        }
1016    }
1017    out.push(&s[start..]);
1018    out
1019}
1020
1021fn unquote_form_value(s: &str) -> String {
1022    let Some(rest) = s.strip_prefix('"') else {
1023        return s.to_string();
1024    };
1025    let mut out = String::with_capacity(rest.len());
1026    let mut chars = rest.chars();
1027    while let Some(c) = chars.next() {
1028        match c {
1029            '\\' => match chars.next() {
1030                Some(next @ ('"' | '\\')) => out.push(next),
1031                Some(other) => {
1032                    out.push('\\');
1033                    out.push(other);
1034                }
1035                None => return s.to_string(),
1036            },
1037            '"' => {
1038                return if chars.next().is_none() {
1039                    out
1040                } else {
1041                    s.to_string()
1042                };
1043            }
1044            _ => out.push(c),
1045        }
1046    }
1047    s.to_string()
1048}
1049
1050fn with_multipart_boundary(existing: &str, boundary: &str) -> String {
1051    let mut parts = split_form_segments(existing).into_iter();
1052    let media = parts
1053        .next()
1054        .map(str::trim)
1055        .filter(|s| !s.is_empty())
1056        .unwrap_or("multipart/form-data");
1057    let mut out = String::from(media);
1058    for param in parts {
1059        let trimmed = param.trim();
1060        if trimmed.is_empty() {
1061            continue;
1062        }
1063        let is_boundary = trimmed
1064            .split_once('=')
1065            .is_some_and(|(k, _)| k.trim().eq_ignore_ascii_case("boundary"));
1066        if !is_boundary {
1067            out.push_str("; ");
1068            out.push_str(trimmed);
1069        }
1070    }
1071    out.push_str("; boundary=");
1072    out.push_str(boundary);
1073    out
1074}
1075
1076fn parse_form_part(
1077    spec: &str,
1078    literal: bool,
1079    read_bytes: &impl Fn(&str) -> Option<Vec<u8>>,
1080) -> Option<FormPart> {
1081    let (name, rest) = spec.split_once('=')?;
1082    if name.is_empty() {
1083        return None;
1084    }
1085    if literal {
1086        return Some(FormPart {
1087            name: name.to_string(),
1088            filename: None,
1089            content_type: None,
1090            data: rest.as_bytes().to_vec(),
1091        });
1092    }
1093    // Split `;type=...` and `;filename=...` parameters outside quoted strings.
1094    let mut segments = split_form_segments(rest).into_iter();
1095    let first = segments.next()?;
1096    let mut filename_override: Option<String> = None;
1097    let mut type_override: Option<String> = None;
1098    let mut trailing_literal = String::new();
1099    for seg in segments {
1100        let trimmed = seg.trim();
1101        if let Some(v) = trimmed.strip_prefix("type=") {
1102            type_override = Some(unquote_form_value(v.trim()));
1103        } else if let Some(v) = trimmed.strip_prefix("filename=") {
1104            filename_override = Some(unquote_form_value(v.trim()));
1105        } else if trimmed.starts_with("headers=") || trimmed.starts_with("encoder=") {
1106            return None;
1107        } else if let Some(ct) = type_override.as_mut() {
1108            // Curl treats parameters after `;type=` (e.g. `;charset=UTF-8`) as part of the media type.
1109            ct.push(';');
1110            ct.push_str(trimmed);
1111        } else {
1112            trailing_literal.push(';');
1113            trailing_literal.push_str(seg);
1114        }
1115    }
1116    if let Some(path) = first.strip_prefix('@') {
1117        let raw_path = if trailing_literal.is_empty() {
1118            unquote_form_value(path)
1119        } else {
1120            format!("{}{trailing_literal}", unquote_form_value(path))
1121        };
1122        let data = read_bytes(&raw_path)?;
1123        let default_name = Path::new(&raw_path)
1124            .file_name()
1125            .map(|n| n.to_string_lossy().into_owned())
1126            .unwrap_or_else(|| raw_path.clone());
1127        let ct = type_override.unwrap_or_else(|| infer_mime(&raw_path).to_string());
1128        Some(FormPart {
1129            name: name.to_string(),
1130            filename: Some(filename_override.unwrap_or(default_name)),
1131            content_type: Some(ct),
1132            data,
1133        })
1134    } else if let Some(path) = first.strip_prefix('<') {
1135        let raw_path = if trailing_literal.is_empty() {
1136            unquote_form_value(path)
1137        } else {
1138            format!("{}{trailing_literal}", unquote_form_value(path))
1139        };
1140        let data = read_bytes(&raw_path)?;
1141        Some(FormPart {
1142            name: name.to_string(),
1143            filename: None,
1144            content_type: type_override,
1145            data,
1146        })
1147    } else {
1148        let val = if trailing_literal.is_empty() {
1149            unquote_form_value(first)
1150        } else {
1151            format!("{}{trailing_literal}", unquote_form_value(first))
1152        };
1153        Some(FormPart {
1154            name: name.to_string(),
1155            filename: filename_override,
1156            content_type: type_override,
1157            data: val.into_bytes(),
1158        })
1159    }
1160}
1161
1162fn build_multipart(parts: &[FormPart]) -> (String, Vec<u8>) {
1163    let mut boundary = String::from("----RustAnythingFormBoundary7MA4YWxkTrZu0gW");
1164    let mut suffix = 0u32;
1165    while parts
1166        .iter()
1167        .any(|p| find(&p.data, boundary.as_bytes()).is_some())
1168    {
1169        suffix += 1;
1170        boundary = format!("----RustAnythingFormBoundary{suffix}");
1171    }
1172    let mut out = Vec::new();
1173    for part in parts {
1174        out.extend_from_slice(b"--");
1175        out.extend_from_slice(boundary.as_bytes());
1176        out.extend_from_slice(b"\r\nContent-Disposition: form-data; name=\"");
1177        out.extend_from_slice(escape_param(&part.name).as_bytes());
1178        out.push(b'"');
1179        if let Some(file) = &part.filename {
1180            out.extend_from_slice(b"; filename=\"");
1181            out.extend_from_slice(escape_param(file).as_bytes());
1182            out.push(b'"');
1183        }
1184        out.extend_from_slice(b"\r\n");
1185        if let Some(ct) = &part.content_type {
1186            out.extend_from_slice(b"Content-Type: ");
1187            out.extend_from_slice(ct.as_bytes());
1188            out.extend_from_slice(b"\r\n");
1189        }
1190        out.extend_from_slice(b"\r\n");
1191        out.extend_from_slice(&part.data);
1192        out.extend_from_slice(b"\r\n");
1193    }
1194    out.extend_from_slice(b"--");
1195    out.extend_from_slice(boundary.as_bytes());
1196    out.extend_from_slice(b"--\r\n");
1197    (boundary, out)
1198}
1199
1200fn parse_curl(line: &str, repo: &Path, doc_dir: &Path) -> Option<Req> {
1201    let toks = app::shell_tokens(line)?;
1202    if toks.iter().any(|t| t.op) {
1203        return None;
1204    }
1205    let words: Vec<String> = toks.into_iter().map(|t| t.text).collect();
1206    let (first, args) = words.split_first()?;
1207    if first != "curl" {
1208        return None;
1209    }
1210    let mut method: Option<String> = None;
1211    let mut headers = BTreeMap::new();
1212    let mut data: Vec<Vec<u8>> = Vec::new();
1213    let mut form_parts: Vec<FormPart> = Vec::new();
1214    let mut url: Option<String> = None;
1215    let mut i = 0;
1216    let read_file_bytes = |name: &str| -> Option<Vec<u8>> {
1217        [repo.join(name), doc_dir.join(name)]
1218            .iter()
1219            .find(|p| p.is_file())
1220            .and_then(|p| std::fs::read(p).ok())
1221    };
1222    while i < args.len() {
1223        let arg = &args[i];
1224        let mut next = || -> Option<String> {
1225            i += 1;
1226            args.get(i).cloned()
1227        };
1228        match arg.as_str() {
1229            "-X" | "--request" => method = Some(next()?),
1230            "-H" | "--header" => {
1231                let h = next()?;
1232                let (k, v) = h.split_once(':')?;
1233                headers.insert(k.trim().to_string(), v.trim().to_string());
1234            }
1235            "-d" | "--data" | "--data-raw" | "--data-binary" | "--data-ascii" => {
1236                let d = next()?;
1237                let bytes = if let Some(path) = d.strip_prefix('@')
1238                    && arg != "--data-raw"
1239                {
1240                    let mut raw = read_file_bytes(path)?;
1241                    if arg != "--data-binary" {
1242                        raw.retain(|b| !matches!(b, b'\r' | b'\n' | b'\0'));
1243                    }
1244                    raw
1245                } else {
1246                    d.into_bytes()
1247                };
1248                data.push(bytes);
1249            }
1250            "--json" => {
1251                let d = next()?;
1252                let bytes = if let Some(path) = d.strip_prefix('@') {
1253                    read_file_bytes(path)?
1254                } else {
1255                    d.into_bytes()
1256                };
1257                data.push(bytes);
1258                headers
1259                    .entry("Content-Type".to_string())
1260                    .or_insert_with(|| "application/json".to_string());
1261                headers
1262                    .entry("Accept".to_string())
1263                    .or_insert_with(|| "application/json".to_string());
1264            }
1265            "-F" | "--form" => {
1266                let spec = next()?;
1267                form_parts.push(parse_form_part(&spec, false, &read_file_bytes)?);
1268            }
1269            "--form-string" => {
1270                let spec = next()?;
1271                form_parts.push(parse_form_part(&spec, true, &read_file_bytes)?);
1272            }
1273            "-A" | "--user-agent" => {
1274                headers.insert("User-Agent".to_string(), next()?);
1275            }
1276            "-b" | "--cookie" => {
1277                headers.insert("Cookie".to_string(), next()?);
1278            }
1279            "-e" | "--referer" => {
1280                headers.insert("Referer".to_string(), next()?);
1281            }
1282            "-o" | "--output" | "-w" | "--write-out" | "-m" | "--max-time"
1283            | "--connect-timeout" => {
1284                next()?;
1285            }
1286            "--silent"
1287            | "--show-error"
1288            | "--include"
1289            | "--verbose"
1290            | "--location"
1291            | "--fail"
1292            | "--insecure"
1293            | "--no-progress-meter" => {}
1294            other if other.starts_with("-X") && other.len() > 2 => {
1295                method = Some(other[2..].to_string());
1296            }
1297            other if other.starts_with("-H") && other.len() > 2 => {
1298                let (k, v) = other[2..].split_once(':')?;
1299                headers.insert(k.trim().to_string(), v.trim().to_string());
1300            }
1301            other if other.starts_with("-F") && other.len() > 2 => {
1302                form_parts.push(parse_form_part(&other[2..], false, &read_file_bytes)?);
1303            }
1304            other
1305                if other.starts_with('-')
1306                    && other.len() > 1
1307                    && !other.starts_with("--")
1308                    && other[1..].chars().all(|c| "sSivLfk".contains(c)) => {}
1309            other if other.starts_with('-') => return None,
1310            other => url = Some(other.to_string()),
1311        }
1312        i += 1;
1313    }
1314    if !data.is_empty() && !form_parts.is_empty() {
1315        return None;
1316    }
1317    let url = url?;
1318    let (scheme, rest) = url.split_once("://").unwrap_or(("http", &url));
1319    if !matches!(scheme, "http" | "https") {
1320        return None;
1321    }
1322    let rest = rest.split('#').next()?;
1323    let (host, target) = rest.split_at(rest.find(['/', '?']).unwrap_or(rest.len()));
1324    let path = if target.starts_with('/') {
1325        target.to_string()
1326    } else {
1327        format!("/{target}")
1328    };
1329    let host = if host.starts_with('[') {
1330        host.split_inclusive(']').next().unwrap_or(host)
1331    } else {
1332        host.split(':').next().unwrap_or(host)
1333    };
1334    if !LOCAL_HOSTS.contains(&host) {
1335        return None;
1336    }
1337    let (body, body_base64) = if !form_parts.is_empty() {
1338        let (boundary, raw) = build_multipart(&form_parts);
1339        if let Some(existing_key) = headers
1340            .keys()
1341            .find(|k| k.eq_ignore_ascii_case("content-type"))
1342            .cloned()
1343        {
1344            let updated = with_multipart_boundary(&headers[&existing_key], &boundary);
1345            headers.insert(existing_key, updated);
1346        } else {
1347            headers.insert(
1348                "Content-Type".to_string(),
1349                format!("multipart/form-data; boundary={boundary}"),
1350            );
1351        }
1352        Req::from_body_bytes(raw)
1353    } else if !data.is_empty() {
1354        let mut joined = Vec::new();
1355        for (idx, chunk) in data.into_iter().enumerate() {
1356            if idx > 0 {
1357                joined.push(b'&');
1358            }
1359            joined.extend_from_slice(&chunk);
1360        }
1361        if !headers
1362            .keys()
1363            .any(|k| k.eq_ignore_ascii_case("content-type"))
1364        {
1365            headers.insert(
1366                "Content-Type".to_string(),
1367                "application/x-www-form-urlencoded".to_string(),
1368            );
1369        }
1370        Req::from_body_bytes(joined)
1371    } else {
1372        (None, None)
1373    };
1374    let has_body = body.is_some() || body_base64.is_some();
1375    let method = method.unwrap_or_else(|| if has_body { "POST" } else { "GET" }.to_string());
1376    Some(Req {
1377        method,
1378        path,
1379        headers,
1380        body,
1381        body_base64,
1382        body_file: None,
1383    })
1384}
1385
1386fn read_inputs(path: &Path, repo: &Path) -> Result<Vec<(Option<String>, Req)>> {
1387    let text =
1388        std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
1389    let inputs_dir = path.parent().unwrap_or_else(|| Path::new("."));
1390    let mut out = Vec::new();
1391    for (n, line) in text.lines().enumerate() {
1392        if line.trim().is_empty() {
1393            continue;
1394        }
1395        let mut input: HttpInput = serde_json::from_str(line).with_context(|| {
1396            format!(
1397                "{}:{}: expected {{\"method\", \"path\", \"headers\": {{...}}, \"body\"|\"body_base64\"|\"body_file\"}}",
1398                path.display(),
1399                n + 1
1400            )
1401        })?;
1402        ensure!(
1403            input.req.path.starts_with('/'),
1404            "{}:{}: `path` must start with /",
1405            path.display(),
1406            n + 1
1407        );
1408        let body_forms = usize::from(input.req.body.is_some())
1409            + usize::from(input.req.body_base64.is_some())
1410            + usize::from(input.req.body_file.is_some());
1411        ensure!(
1412            body_forms <= 1,
1413            "{}:{}: specify at most one of `body`, `body_base64`, or `body_file`",
1414            path.display(),
1415            n + 1
1416        );
1417        if let Some(b64) = &input.req.body_base64 {
1418            decode_base64_strict(b64)
1419                .with_context(|| format!("{}:{}: invalid `body_base64`", path.display(), n + 1))?;
1420        }
1421        if let Some(rel) = input.req.body_file.take() {
1422            let file = if Path::new(&rel).is_absolute() {
1423                PathBuf::from(&rel)
1424            } else {
1425                [inputs_dir.join(&rel), repo.join(&rel)]
1426                    .into_iter()
1427                    .find(|p| p.is_file())
1428                    .unwrap_or_else(|| repo.join(&rel))
1429            };
1430            let bytes = std::fs::read(&file).with_context(|| {
1431                format!(
1432                    "{}:{}: reading `body_file` `{}`",
1433                    path.display(),
1434                    n + 1,
1435                    file.display()
1436                )
1437            })?;
1438            let (body, body_base64) = Req::from_body_bytes(bytes);
1439            input.req.body = body;
1440            input.req.body_base64 = body_base64;
1441        }
1442        out.push((input.name, input.req));
1443    }
1444    Ok(out)
1445}
1446
1447fn trap_values(raw: &str) -> Vec<&'static str> {
1448    if raw.parse::<i128>().is_ok() {
1449        app::INT_TRAPS.to_vec()
1450    } else if raw.parse::<f64>().is_ok() && raw.contains(['.', 'e', 'E']) {
1451        app::FLOAT_TRAPS.to_vec()
1452    } else {
1453        app::STRING_TRAPS.to_vec()
1454    }
1455}
1456
1457fn req_key(req: &Req) -> String {
1458    serde_json::to_string(req).unwrap_or_default()
1459}
1460
1461fn traps(bases: &[Req]) -> (Vec<Req>, usize) {
1462    let mut per_base = Vec::with_capacity(bases.len());
1463    for base in bases {
1464        let mut slots: Vec<Vec<Req>> = Vec::new();
1465        let (path, query) = match base.path.split_once('?') {
1466            Some((p, q)) => (p, Some(q)),
1467            None => (base.path.as_str(), None),
1468        };
1469        let segments: Vec<&str> = path.split('/').collect();
1470        for i in 2..segments.len() {
1471            let raw = percent_decode(segments[i]);
1472            let slot: Vec<Req> = trap_values(&raw)
1473                .into_iter()
1474                .filter(|v| *v != raw)
1475                .map(|v| {
1476                    let mut parts: Vec<String> = segments.iter().map(|s| s.to_string()).collect();
1477                    parts[i] = percent_encode(v);
1478                    let mut req = base.clone();
1479                    req.path =
1480                        parts.join("/") + &query.map(|q| format!("?{q}")).unwrap_or_default();
1481                    req
1482                })
1483                .collect();
1484            if !slot.is_empty() {
1485                slots.push(slot);
1486            }
1487        }
1488        if let Some(query) = query {
1489            let pairs: Vec<&str> = query.split('&').collect();
1490            for (i, pair) in pairs.iter().enumerate() {
1491                let Some((key, raw)) = pair.split_once('=') else {
1492                    continue;
1493                };
1494                let raw = percent_decode(raw);
1495                let slot: Vec<Req> = trap_values(&raw)
1496                    .into_iter()
1497                    .filter(|v| *v != raw)
1498                    .map(|v| {
1499                        let mut new: Vec<String> = pairs.iter().map(|p| p.to_string()).collect();
1500                        new[i] = format!("{key}={}", percent_encode(v));
1501                        let mut req = base.clone();
1502                        req.path = format!("{path}?{}", new.join("&"));
1503                        req
1504                    })
1505                    .collect();
1506                if !slot.is_empty() {
1507                    slots.push(slot);
1508                }
1509            }
1510        }
1511        if base.body.is_some() || base.body_base64.is_some() {
1512            let json = base.body.as_deref().is_some_and(|body| {
1513                serde_json::from_str::<Value>(body).is_ok_and(|v| v.is_object() || v.is_array())
1514            });
1515            let values: &[&str] = if json {
1516                &app::JSON_TRAPS
1517            } else {
1518                &app::STDIN_TRAPS
1519            };
1520            slots.push(
1521                values
1522                    .iter()
1523                    .map(|v| {
1524                        let mut req = base.clone();
1525                        req.body = Some(v.to_string());
1526                        req.body_base64 = None;
1527                        req.body_file = None;
1528                        req
1529                    })
1530                    .collect(),
1531            );
1532        }
1533        per_base.push(app::interleave(slots));
1534    }
1535    let unknown_route = Req {
1536        method: "GET".to_string(),
1537        path: "/rust-anything-missing".to_string(),
1538        headers: BTreeMap::new(),
1539        body: None,
1540        body_base64: None,
1541        body_file: None,
1542    };
1543    let existing: BTreeSet<_> = bases.iter().map(req_key).collect();
1544    app::spread_traps(
1545        per_base,
1546        vec![unknown_route],
1547        &existing,
1548        req_key,
1549        app::MAX_TRAPS,
1550    )
1551}
1552
1553fn case_slug(req: &Req) -> String {
1554    let first = req
1555        .path
1556        .split(['/', '?'])
1557        .find(|s| !s.is_empty())
1558        .unwrap_or("root");
1559    app::slug(&format!("{} {first}", req.method))
1560}
1561
1562fn settle_headers(
1563    norm: &Normalizers,
1564    a: &BTreeMap<String, String>,
1565    b: &BTreeMap<String, String>,
1566) -> (BTreeMap<String, String>, bool) {
1567    let mut out = BTreeMap::new();
1568    let mut noisy = false;
1569    for (k, va) in a {
1570        if SKIP_HEADERS.contains(&k.as_str()) {
1571            continue;
1572        }
1573        let Some(vb) = b.get(k) else {
1574            noisy = true;
1575            continue;
1576        };
1577        let (va, vb) = (norm.apply(va), norm.apply(vb));
1578        if va == vb {
1579            out.insert(k.clone(), va);
1580        } else {
1581            noisy = true;
1582            out.insert(k.clone(), app::merge_line(&va, &vb));
1583        }
1584    }
1585    noisy |= b
1586        .keys()
1587        .any(|k| !a.contains_key(k) && !SKIP_HEADERS.contains(&k.as_str()));
1588    (out, noisy)
1589}
1590
1591fn table(entries: &BTreeMap<String, String>) -> Table {
1592    let mut t = Table::new();
1593    for (k, v) in entries {
1594        t[k.as_str()] = value(v.as_str());
1595    }
1596    t
1597}
1598
1599fn write_case(
1600    dir: &Path,
1601    name: &str,
1602    req: &Req,
1603    status: u16,
1604    headers: &BTreeMap<String, String>,
1605    body: &[u8],
1606    binary: bool,
1607) -> Result<()> {
1608    let mut doc = DocumentMut::new();
1609    let mut request = Table::new();
1610    request["method"] = value(req.method.as_str());
1611    request["path"] = value(req.path.as_str());
1612    if let Some(body) = &req.body {
1613        request["body"] = value(body.as_str());
1614    } else if let Some(b64) = &req.body_base64 {
1615        request["body_base64"] = value(b64.as_str());
1616    }
1617    if !req.headers.is_empty() {
1618        request.insert("headers", Item::Table(table(&req.headers)));
1619    }
1620    doc.insert("request", Item::Table(request));
1621    let mut response = Table::new();
1622    response["status"] = value(i64::from(status));
1623    if binary {
1624        response["binary"] = value(true);
1625    }
1626    if !headers.is_empty() {
1627        response.insert("headers", Item::Table(table(headers)));
1628    }
1629    doc.insert("response", Item::Table(response));
1630    std::fs::write(dir.join(format!("{name}.toml")), doc.to_string())?;
1631    std::fs::write(dir.join(format!("{name}.body")), body)?;
1632    Ok(())
1633}
1634
1635pub(crate) fn record(
1636    repo: &Path,
1637    config: &Config,
1638    norm: &Normalizers,
1639    opts: &RecordOptions,
1640) -> Result<RecordOutcome> {
1641    let examples = app::scan_examples(repo, |line, doc_dir| parse_curl(line, repo, doc_dir));
1642    let inputs = match opts.inputs {
1643        Some(path) => read_inputs(path, repo)?,
1644        None => Vec::new(),
1645    };
1646    let mut planned: Vec<(String, Req)> = Vec::new();
1647    let mut seen = BTreeSet::new();
1648    let mut taken = BTreeSet::new();
1649    let mut counts = [0usize; 3];
1650    let mut bases = Vec::new();
1651    let mut push = |kind: usize, given: Option<String>, req: Req| -> bool {
1652        if !seen.insert(req_key(&req)) {
1653            return false;
1654        }
1655        counts[kind] += 1;
1656        let prefix = ["example", "input", "trap"][kind];
1657        let name = match given.map(|g| app::given_slug(&g)).filter(|g| !g.is_empty()) {
1658            Some(g) => g,
1659            None => format!("{prefix}-{:03}-{}", counts[kind], case_slug(&req)),
1660        };
1661        let name = app::reserve_case_name(&mut taken, name, counts[kind]);
1662        planned.push((name, req));
1663        true
1664    };
1665    for req in examples {
1666        if push(0, None, req.clone()) {
1667            bases.push(req);
1668        }
1669    }
1670    for (given, req) in inputs {
1671        if push(1, given, req.clone()) {
1672            bases.push(req);
1673        }
1674    }
1675    if bases.is_empty() {
1676        let root = Req {
1677            method: "GET".to_string(),
1678            path: "/".to_string(),
1679            headers: BTreeMap::new(),
1680            body: None,
1681            body_base64: None,
1682            body_file: None,
1683        };
1684        push(0, None, root.clone());
1685        bases.push(root);
1686    }
1687    let mut traps_dropped = 0usize;
1688    if opts.traps {
1689        let (generated, dropped) = traps(&bases);
1690        traps_dropped = dropped;
1691        for req in generated {
1692            push(2, None, req);
1693        }
1694    }
1695    planned.sort_by(|a, b| a.0.cmp(&b.0));
1696
1697    let timeout = Duration::from_secs(config.timeout_secs);
1698    let fixed = config.http.as_ref().and_then(|h| h.port);
1699    let reqs: Vec<&Req> = planned.iter().map(|(_, r)| r).collect();
1700    let http = config.http.clone().unwrap_or_default();
1701    let files = snapshot(repo, &http.fresh)?;
1702    let launch = Launch {
1703        args: &http.args,
1704        files: files.as_deref(),
1705        pace: http.pace_ms.map(Duration::from_millis),
1706        effects: config.effects.as_ref(),
1707        ready: ready_timeout(&http),
1708    };
1709    let one = run_all(&config.run, &launch, repo, fixed, &reqs, timeout)?;
1710    let two = run_all(&config.run, &launch, repo, fixed, &reqs, timeout)?;
1711
1712    let dir = app::cases_dir(repo).join(HTTP_DIR);
1713    std::fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?;
1714    let mut outcome = RecordOutcome {
1715        dir: dir.clone(),
1716        run: config.run.clone(),
1717        cases: 0,
1718        examples: counts[0],
1719        inputs: counts[1],
1720        traps: counts[2],
1721        traps_dropped,
1722        noisy: Vec::new(),
1723        noise: Vec::new(),
1724        unstable: Vec::new(),
1725        timed_out: Vec::new(),
1726        recorded: Vec::new(),
1727        stale: Vec::new(),
1728        kept: Vec::new(),
1729    };
1730    for (((name, req), (a, _, fx_a)), (b, _, fx_b)) in planned.iter().zip(one).zip(two) {
1731        let (Ok(a), Ok(b)) = (a, b) else {
1732            outcome.timed_out.push(name.clone());
1733            continue;
1734        };
1735        let (body, body_noise, binary) = app::settle_text(norm, &a.body, &b.body);
1736        let (headers, header_noisy) = settle_headers(norm, &a.headers, &b.headers);
1737        write_case(&dir, name, req, a.status, &headers, &body, binary)?;
1738        let effects_file = dir.join(format!("{name}.{}", crate::effects::EXT));
1739        let _ = std::fs::remove_file(&effects_file);
1740        let mut fx_noise = None;
1741        if let (Some(fa), Some(fb)) = (&fx_a, &fx_b) {
1742            let (fx, noise, _) = app::settle_text(norm, fa, fb);
1743            std::fs::write(&effects_file, fx)?;
1744            fx_noise = noise;
1745        }
1746        outcome.cases += 1;
1747        outcome.recorded.push(name.clone());
1748        if body_noise.is_some() || header_noisy || fx_noise.is_some() {
1749            outcome.noisy.push(name.clone());
1750        }
1751        for (field, kind) in [
1752            ("body", body_noise),
1753            ("headers", header_noisy.then_some(app::NoiseKind::Values)),
1754            (crate::effects::EXT, fx_noise),
1755        ] {
1756            if let Some(kind) = kind {
1757                outcome.noise.push(app::Noise {
1758                    case: name.clone(),
1759                    field: field.to_string(),
1760                    kind,
1761                });
1762            }
1763        }
1764        if a.status != b.status || (binary && body_noise.is_some()) {
1765            outcome.unstable.push(name.clone());
1766        }
1767    }
1768    Ok(outcome)
1769}
1770
1771struct Spec {
1772    name: String,
1773    req: Req,
1774    status: u16,
1775    headers: BTreeMap<String, String>,
1776    body: Option<Vec<u8>>,
1777    binary: bool,
1778    effects: Option<Vec<u8>>,
1779}
1780
1781fn strings(item: Option<&Item>) -> BTreeMap<String, String> {
1782    item.and_then(Item::as_table_like)
1783        .map(|t| {
1784            t.iter()
1785                .map(|(k, v)| (k.to_string(), v.as_str().unwrap_or_default().to_string()))
1786                .collect()
1787        })
1788        .unwrap_or_default()
1789}
1790
1791fn load_spec(dir: &Path, path: &Path) -> Result<Spec> {
1792    let name = path
1793        .file_stem()
1794        .map(|s| s.to_string_lossy().into_owned())
1795        .unwrap_or_default();
1796    let doc: DocumentMut = std::fs::read_to_string(path)
1797        .with_context(|| format!("reading {}", path.display()))?
1798        .parse()
1799        .with_context(|| format!("parsing {}", path.display()))?;
1800    let request = doc.get("request").context("no [request]")?;
1801    let response = doc.get("response").context("no [response]")?;
1802    let body_file = dir.join(format!("{name}.body"));
1803    let effects_file = dir.join(format!("{name}.{}", crate::effects::EXT));
1804    let raw_body = request.get("body");
1805    let raw_body_base64 = request.get("body_base64");
1806    let raw_body_file = request.get("body_file");
1807    let body_forms = usize::from(raw_body.is_some())
1808        + usize::from(raw_body_base64.is_some())
1809        + usize::from(raw_body_file.is_some());
1810    ensure!(
1811        body_forms <= 1,
1812        "{}: [request] may specify at most one of body, body_base64, or body_file",
1813        path.display()
1814    );
1815    let req_body = match raw_body {
1816        Some(item) => Some(
1817            item.as_str()
1818                .with_context(|| format!("{}: request.body must be a string", path.display()))?
1819                .to_string(),
1820        ),
1821        None => None,
1822    };
1823    let req_body_base64 = match raw_body_base64 {
1824        Some(item) => Some(
1825            item.as_str()
1826                .with_context(|| {
1827                    format!("{}: request.body_base64 must be a string", path.display())
1828                })?
1829                .to_string(),
1830        ),
1831        None => None,
1832    };
1833    let req_body_file = match raw_body_file {
1834        Some(item) => Some(
1835            item.as_str()
1836                .with_context(|| format!("{}: request.body_file must be a string", path.display()))?
1837                .to_string(),
1838        ),
1839        None => None,
1840    };
1841    let (req_body, req_body_base64) = if let Some(b64) = req_body_base64 {
1842        decode_base64_strict(&b64)
1843            .with_context(|| format!("{}: invalid request.body_base64", path.display()))?;
1844        (None, Some(b64))
1845    } else if let Some(rel) = req_body_file {
1846        let rel_path = Path::new(&rel);
1847        ensure!(
1848            !rel_path.is_absolute()
1849                && rel_path.components().all(|c| matches!(
1850                    c,
1851                    std::path::Component::Normal(_) | std::path::Component::CurDir
1852                )),
1853            "{}: request.body_file `{rel}` must be a relative path under http/",
1854            path.display()
1855        );
1856        let root = std::fs::canonicalize(dir)
1857            .with_context(|| format!("{}: resolving http case directory", path.display()))?;
1858        let candidate = std::fs::canonicalize(dir.join(rel_path))
1859            .with_context(|| format!("{}: reading request.body_file `{rel}`", path.display()))?;
1860        ensure!(
1861            candidate.starts_with(&root),
1862            "{}: request.body_file `{rel}` escapes http/",
1863            path.display()
1864        );
1865        let meta = std::fs::metadata(&candidate)
1866            .with_context(|| format!("{}: reading request.body_file `{rel}`", path.display()))?;
1867        ensure!(
1868            meta.is_file(),
1869            "{}: request.body_file `{rel}` is not a regular file",
1870            path.display()
1871        );
1872        let bytes = std::fs::read(&candidate)
1873            .with_context(|| format!("{}: reading request.body_file `{rel}`", path.display()))?;
1874        Req::from_body_bytes(bytes)
1875    } else {
1876        (req_body, None)
1877    };
1878    Ok(Spec {
1879        effects: if effects_file.exists() {
1880            Some(std::fs::read(&effects_file)?)
1881        } else {
1882            None
1883        },
1884        req: Req {
1885            method: request
1886                .get("method")
1887                .and_then(Item::as_str)
1888                .unwrap_or("GET")
1889                .to_string(),
1890            path: request
1891                .get("path")
1892                .and_then(Item::as_str)
1893                .with_context(|| format!("{}: no request.path", path.display()))?
1894                .to_string(),
1895            headers: strings(request.get("headers")),
1896            body: req_body,
1897            body_base64: req_body_base64,
1898            body_file: None,
1899        },
1900        status: response
1901            .get("status")
1902            .and_then(Item::as_integer)
1903            .and_then(|s| u16::try_from(s).ok())
1904            .with_context(|| format!("{}: no response.status", path.display()))?,
1905        headers: strings(response.get("headers")),
1906        body: if body_file.exists() {
1907            Some(std::fs::read(&body_file)?)
1908        } else {
1909            None
1910        },
1911        binary: response
1912            .get("binary")
1913            .and_then(Item::as_bool)
1914            .unwrap_or(false),
1915        name,
1916    })
1917}
1918
1919/// The recorded requests, as `METHOD /path` without the query, in case order.
1920pub(crate) fn recorded_routes(repo: &Path) -> Result<Vec<String>> {
1921    let mut seen = BTreeSet::new();
1922    let mut out = Vec::new();
1923    for spec in load_specs(&app::cases_dir(repo).join(HTTP_DIR))? {
1924        let path = spec.req.path.split('?').next().unwrap_or("/").to_string();
1925        let route = format!("{} {path}", spec.req.method);
1926        if seen.insert(route.clone()) {
1927            out.push(route);
1928        }
1929    }
1930    Ok(out)
1931}
1932
1933/// The curl examples in the docs no recorded case sends, as `METHOD /path`.
1934pub(crate) fn unrecorded_examples(repo: &Path) -> Result<Vec<String>> {
1935    let recorded: BTreeSet<String> = load_specs(&app::cases_dir(repo).join(HTTP_DIR))?
1936        .iter()
1937        .map(|s| req_key(&s.req))
1938        .collect();
1939    let mut seen = BTreeSet::new();
1940    Ok(
1941        app::scan_examples(repo, |line, doc_dir| parse_curl(line, repo, doc_dir))
1942            .into_iter()
1943            .filter(|req| !recorded.contains(&req_key(req)) && seen.insert(req_key(req)))
1944            .map(|req| format!("{} {}", req.method, req.path))
1945            .collect(),
1946    )
1947}
1948
1949/// Response headers whose value differed between the original's own runs in some recorded case.
1950pub(crate) fn noisy_headers(repo: &Path) -> BTreeSet<String> {
1951    load_specs(&app::cases_dir(repo).join(HTTP_DIR))
1952        .unwrap_or_default()
1953        .iter()
1954        .flat_map(|spec| &spec.headers)
1955        .filter(|(_, v)| v.contains("[..]"))
1956        .map(|(k, _)| k.to_ascii_lowercase())
1957        .collect()
1958}
1959
1960pub(crate) fn is_skipped_header(name: &str) -> bool {
1961    SKIP_HEADERS.contains(&name)
1962}
1963
1964fn load_specs(dir: &Path) -> Result<Vec<Spec>> {
1965    let mut paths: Vec<PathBuf> = std::fs::read_dir(dir)
1966        .with_context(|| {
1967            format!(
1968                "no HTTP cases in {}: run `rust-anything app record` first",
1969                dir.display()
1970            )
1971        })?
1972        .flatten()
1973        .map(|e| e.path())
1974        .filter(|p| p.is_file() && p.extension().is_some_and(|e| e == "toml"))
1975        .collect();
1976    paths.sort();
1977    let specs = paths
1978        .iter()
1979        .map(|p| load_spec(dir, p))
1980        .collect::<Result<Vec<_>>>()?;
1981    ensure!(!specs.is_empty(), "no HTTP cases in {}", dir.display());
1982    Ok(specs)
1983}
1984
1985pub(crate) fn replay(
1986    repo: &Path,
1987    config: &Config,
1988    norm: &Normalizers,
1989    command: &[String],
1990    port: Option<u16>,
1991    case: Option<&str>,
1992    timeout: Duration,
1993) -> Result<ReplayOutcome> {
1994    let dir = app::cases_dir(repo);
1995    let specs = app::only_case(load_specs(&dir.join(HTTP_DIR))?, case, |s| &s.name)?;
1996    let fixed_port = port.or(config.http.as_ref().and_then(|h| h.port));
1997    let reqs: Vec<&Req> = specs.iter().map(|s| &s.req).collect();
1998    let files = saved_snapshot(repo, config)?;
1999    let http = config.http.clone().unwrap_or_default();
2000    let launch = Launch {
2001        args: &http.args,
2002        files: files.as_deref(),
2003        pace: http.pace_ms.map(Duration::from_millis),
2004        effects: config.effects.as_ref(),
2005        ready: ready_timeout(&http),
2006    };
2007    let answers = run_all(command, &launch, repo, fixed_port, &reqs, timeout)?;
2008    let mut outcome = ReplayOutcome {
2009        build: command.to_vec(),
2010        passed: 0,
2011        total: 0,
2012        skipped: 0,
2013        failures: Vec::new(),
2014        fallback: None,
2015        report: dir.join(app::REPORT_FILE),
2016        groups: Vec::new(),
2017    };
2018    let (mut reported, mut fell_back) = (false, Vec::new());
2019    for (spec, (answer, fallback, effects)) in specs.iter().zip(answers) {
2020        outcome.total += 1;
2021        reported |= fallback.is_some();
2022        if fallback == Some(true) {
2023            fell_back.push(spec.name.clone());
2024        }
2025        let mut problems = Vec::new();
2026        match answer {
2027            Err(e) => problems.push(
2028                Problem::new("response", format!("no response: {e}\n"))
2029                    .at(crate::mismatch::At::new("no response")),
2030            ),
2031            Ok(resp) => {
2032                if resp.status != spec.status {
2033                    problems.push(
2034                        Problem::new(
2035                            "status",
2036                            format!("expected {}, got {}\n", spec.status, resp.status),
2037                        )
2038                        .at(crate::mismatch::At::new(&format!(
2039                            "{}→{}",
2040                            spec.status, resp.status
2041                        ))),
2042                    );
2043                }
2044                for (k, expected) in &spec.headers {
2045                    let field = format!("header {k}");
2046                    let key = k.to_ascii_lowercase();
2047                    match resp.headers.get(&key) {
2048                        None => problems.push(
2049                            Problem::new(field, format!("- {expected}\n(missing)\n"))
2050                                .at(crate::mismatch::At::new("missing key")),
2051                        ),
2052                        Some(actual) => {
2053                            let (e, a) = (norm.apply(expected), norm.apply(actual));
2054                            if !app::line_matches(&e, &a) {
2055                                let literal = e.split("[..]").next().unwrap_or_default();
2056                                let at = crate::mismatch::text_at("text", literal, &a);
2057                                problems
2058                                    .push(Problem::new(field, format!("- {e}\n+ {a}\n")).at(at));
2059                            }
2060                        }
2061                    }
2062                }
2063                let unordered = norm.unordered(&spec.name, "body");
2064                if let Some(expected) = &spec.body
2065                    && let Some(detail) =
2066                        app::compare(norm, expected, &resp.body, spec.binary, unordered)
2067                {
2068                    let at = app::locate(norm, expected, &resp.body, spec.binary, unordered);
2069                    problems.push(Problem::new("body", detail).at(at));
2070                }
2071            }
2072        }
2073        let unordered = norm.unordered(&spec.name, crate::effects::EXT);
2074        let got = effects.as_deref().unwrap_or_default();
2075        if let Some(expected) = &spec.effects
2076            && let Some(detail) = app::compare(norm, expected, got, false, unordered)
2077        {
2078            let at = app::locate(norm, expected, got, false, unordered);
2079            problems.push(Problem::new(crate::effects::EXT, detail).at(at));
2080        }
2081        if problems.is_empty() {
2082            outcome.passed += 1;
2083        } else {
2084            outcome.failures.push(Failure {
2085                case: spec.name.clone(),
2086                args: vec![spec.req.method.clone(), spec.req.path.clone()],
2087                problems,
2088            });
2089        }
2090    }
2091    if reported {
2092        outcome.fallback = Some(Fallback {
2093            cases: fell_back.len(),
2094            total: outcome.total,
2095            rate: fell_back.len() as f64 / outcome.total.max(1) as f64,
2096            names: fell_back,
2097        });
2098    }
2099    Ok(outcome)
2100}
2101
2102fn encode_base64(input: &[u8]) -> String {
2103    const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
2104    let mut out = String::with_capacity(input.len().div_ceil(3) * 4);
2105    for chunk in input.chunks(3) {
2106        let b0 = chunk[0] as u32;
2107        let b1 = chunk.get(1).copied().unwrap_or(0) as u32;
2108        let b2 = chunk.get(2).copied().unwrap_or(0) as u32;
2109        let n = (b0 << 16) | (b1 << 8) | b2;
2110        out.push(TABLE[((n >> 18) & 0x3f) as usize] as char);
2111        out.push(TABLE[((n >> 12) & 0x3f) as usize] as char);
2112        out.push(if chunk.len() > 1 {
2113            TABLE[((n >> 6) & 0x3f) as usize] as char
2114        } else {
2115            '='
2116        });
2117        out.push(if chunk.len() > 2 {
2118            TABLE[(n & 0x3f) as usize] as char
2119        } else {
2120            '='
2121        });
2122    }
2123    out
2124}
2125
2126fn decode_base64_strict(input: &str) -> Result<Vec<u8>> {
2127    let cleaned: Vec<u8> = input.bytes().filter(|b| !b.is_ascii_whitespace()).collect();
2128    if cleaned.is_empty() {
2129        return Ok(Vec::new());
2130    }
2131    ensure!(
2132        cleaned.len().is_multiple_of(4),
2133        "base64 length must be a multiple of 4"
2134    );
2135    let mut out = Vec::with_capacity(cleaned.len() / 4 * 3);
2136    let (chunks, _) = cleaned.as_chunks::<4>();
2137    for (chunk_idx, chunk) in chunks.iter().enumerate() {
2138        let is_last = (chunk_idx + 1) * 4 == cleaned.len();
2139        let decode = |b: u8| -> Option<u8> {
2140            match b {
2141                b'A'..=b'Z' => Some(b - b'A'),
2142                b'a'..=b'z' => Some(b - b'a' + 26),
2143                b'0'..=b'9' => Some(b - b'0' + 52),
2144                b'+' => Some(62),
2145                b'/' => Some(63),
2146                _ => None,
2147            }
2148        };
2149        let a = decode(chunk[0]).context("invalid base64 character")?;
2150        let b = decode(chunk[1]).context("invalid base64 character")?;
2151        match (chunk[2], chunk[3]) {
2152            (b'=', b'=') => {
2153                ensure!(is_last, "unexpected base64 padding before end");
2154                out.push((a << 2) | (b >> 4));
2155            }
2156            (c, b'=') => {
2157                ensure!(is_last, "unexpected base64 padding before end");
2158                let c = decode(c).context("invalid base64 character")?;
2159                out.push((a << 2) | (b >> 4));
2160                out.push((b << 4) | (c >> 2));
2161            }
2162            (c, d) => {
2163                let c = decode(c).context("invalid base64 character")?;
2164                let d = decode(d).context("invalid base64 character")?;
2165                out.push((a << 2) | (b >> 4));
2166                out.push((b << 4) | (c >> 2));
2167                out.push((c << 6) | d);
2168            }
2169        }
2170    }
2171    Ok(out)
2172}
2173
2174#[cfg(test)]
2175mod tests {
2176    use super::*;
2177
2178    #[test]
2179    fn a_ready_timeout_is_saved_kept_and_reset() {
2180        let opts = |ready_secs| RecordOptions {
2181            repo: Path::new("."),
2182            run: &[],
2183            inputs: None,
2184            normalize: &[],
2185            name: None,
2186            traps: false,
2187            timeout_secs: None,
2188            http: None,
2189            server_args: None,
2190            fresh: None,
2191            pace_ms: None,
2192            port: None,
2193            float_tolerance: None,
2194            float_files: &[],
2195            effects: None,
2196            ready_secs,
2197        };
2198        let old: HttpConfig = serde_json::from_str(r#"{"port":8080}"#).unwrap();
2199        assert_eq!(ready_timeout(&old), READY);
2200        assert!(merge_config(None, &opts(None)).unwrap().is_none());
2201        let set = merge_config(Some(old), &opts(Some(5))).unwrap().unwrap();
2202        assert_eq!(ready_timeout(&set), Duration::from_secs(5));
2203        let kept = merge_config(Some(set), &opts(None)).unwrap().unwrap();
2204        assert_eq!(kept.ready_secs, Some(5));
2205        let reset = merge_config(Some(kept), &opts(Some(0))).unwrap().unwrap();
2206        assert_eq!(reset.ready_secs, None);
2207        assert!(!serde_json::to_string(&reset).unwrap().contains("ready"));
2208        let implied = merge_config(None, &opts(Some(90))).unwrap().unwrap();
2209        assert_eq!(implied.ready_secs, Some(90));
2210    }
2211
2212    #[test]
2213    fn the_tree_of_a_server_is_found_and_zombies_are_not_alive() {
2214        // pid ppid stat start, as `ps -A -o pid= -o ppid= -o stat= -o lstart=` prints them.
2215        let ps = "    1     0 Ss   Tue Nov 24 13:00:00 2026\n  100     1 S    Tue Nov 24 14:00:00 2026\n  200   100 Z    Tue Nov 24 14:00:01 2026\n  300   100 S    Tue Nov 24 14:00:01 2026\n  400   300 R    Tue Nov 24 14:00:02 2026\n  500     1 S    Tue Nov 24 14:00:00 2026\n  600   500 S    Tue Nov 24 14:00:01 2026\n";
2216        let tree = |root| {
2217            let mut tree = vec![(root, None)];
2218            grow(ps, &mut tree);
2219            tree
2220        };
2221        let pids =
2222            |tree: &[(u32, Option<String>)]| tree.iter().map(|(p, _)| *p).collect::<Vec<_>>();
2223        assert_eq!(pids(&tree(100)), [100, 200, 300, 400]);
2224        assert_eq!(tree(100)[2].1.as_deref(), Some("Tue Nov 24 14:00:01 2026"));
2225        assert_eq!(pids(&tree(400)), [400]);
2226        assert_eq!(pids(&tree(999)), [999]);
2227        assert_eq!(
2228            running(Some(ps), &tree(100)),
2229            [100, 300, 400],
2230            "a zombie holds no port"
2231        );
2232        assert!(running(Some(ps), &[(999, None)]).is_empty());
2233        assert_eq!(running(None, &tree(100)), [100]);
2234    }
2235
2236    /// Runs `end_tree` on these listings (`None` a failed `ps`, and failing once they run out)
2237    /// and returns the signals it sent and whether it saw the tree gone.
2238    fn ending(listings: &[Option<&str>], grace: Duration) -> (Vec<(String, Vec<u32>)>, bool) {
2239        let mut listings = listings.iter().map(|l| l.map(str::to_string));
2240        let mut sent = Vec::new();
2241        let gone = end_tree(
2242            100,
2243            grace,
2244            || listings.next().flatten(),
2245            |signal, pids| sent.push((signal.to_string(), pids.to_vec())),
2246        );
2247        (sent, gone)
2248    }
2249
2250    #[test]
2251    fn a_failed_listing_after_term_still_ends_in_kill() {
2252        // `ps` works for TERM, then fails: the wait goes on to the deadline, and KILL goes to
2253        // the started child only, since 300's pid may belong to another process by then.
2254        let (sent, gone) = ending(
2255            &[Some("  100 1 S\n  300 100 S\n")],
2256            Duration::from_millis(60),
2257        );
2258        assert!(!gone);
2259        assert_eq!(
2260            sent,
2261            [
2262                ("-TERM".to_string(), vec![100, 300]),
2263                ("-KILL".to_string(), vec![100])
2264            ]
2265        );
2266    }
2267
2268    #[test]
2269    fn a_process_forked_while_stopping_gets_the_signal_too() {
2270        let (sent, gone) = ending(
2271            &[
2272                Some("  100 1 S\n  300 100 S\n"),
2273                // 300 forked 700 after the first listing.
2274                Some("  100 1 S\n  300 100 S\n  700 300 S\n"),
2275                // 300 is gone and 700 reparented, still running: still waited for.
2276                Some("  100 1 Z\n  700 1 S\n"),
2277                Some("  100 1 Z\n"),
2278            ],
2279            Duration::from_secs(5),
2280        );
2281        assert!(gone);
2282        assert_eq!(
2283            sent,
2284            [
2285                ("-TERM".to_string(), vec![100, 300]),
2286                ("-TERM".to_string(), vec![700])
2287            ]
2288        );
2289    }
2290
2291    #[test]
2292    fn a_pid_reused_while_stopping_gets_no_kill() {
2293        // 300 exited and its pid went to another process; 100 ignores TERM. Listed so through
2294        // the TERM wait (60 ms, about 3 polls) and in the listing taken before KILL.
2295        const REUSED: &str =
2296            "  100 1 S Tue Nov 24 14:00:00 2026\n  300 1 S Tue Nov 24 14:00:05 2026\n";
2297        let (sent, gone) = ending(
2298            &[
2299                Some("  100 1 S Tue Nov 24 14:00:00 2026\n  300 100 S Tue Nov 24 14:00:01 2026\n"),
2300                Some(REUSED),
2301                Some(REUSED),
2302                Some(REUSED),
2303                Some(REUSED),
2304                Some(REUSED),
2305                Some(REUSED),
2306                Some(REUSED),
2307                Some(REUSED),
2308            ],
2309            Duration::from_millis(60),
2310        );
2311        assert!(!gone);
2312        assert_eq!(
2313            sent,
2314            [
2315                ("-TERM".to_string(), vec![100, 300]),
2316                ("-KILL".to_string(), vec![100])
2317            ]
2318        );
2319    }
2320
2321    #[test]
2322    fn a_process_the_listing_before_kill_missed_gets_kill_once_a_listing_shows_it() {
2323        // 100 and 300 ignore TERM. `ps` fails through the TERM wait and right before KILL, so
2324        // KILL first goes to 100 alone; the next listing shows 300 still running as it was.
2325        let tree = "  100 1 S Tue Nov 24 14:00:00 2026\n  300 100 S Tue Nov 24 14:00:01 2026\n";
2326        let sent = std::cell::RefCell::new(Vec::<(String, Vec<u32>)>::new());
2327        let calls = std::cell::Cell::new(0);
2328        let gone = end_tree(
2329            100,
2330            Duration::from_millis(60),
2331            || {
2332                calls.set(calls.get() + 1);
2333                let sent = sent.borrow();
2334                let killed = |pid| sent.iter().any(|(s, p)| s == "-KILL" && p.contains(&pid));
2335                if calls.get() == 1 {
2336                    Some(tree.to_string())
2337                } else if !killed(100) {
2338                    None
2339                } else if !killed(300) {
2340                    Some(tree.to_string())
2341                } else {
2342                    Some(String::new())
2343                }
2344            },
2345            |signal, pids| sent.borrow_mut().push((signal.to_string(), pids.to_vec())),
2346        );
2347        assert!(gone);
2348        assert_eq!(
2349            sent.into_inner(),
2350            [
2351                ("-TERM".to_string(), vec![100, 300]),
2352                ("-KILL".to_string(), vec![100]),
2353                ("-KILL".to_string(), vec![300])
2354            ]
2355        );
2356    }
2357
2358    #[test]
2359    fn stopping_waits_after_kill_until_the_tree_is_gone() {
2360        let killed = std::cell::Cell::new(false);
2361        let after_kill = std::cell::Cell::new(0);
2362        let gone = end_tree(
2363            100,
2364            Duration::from_millis(60),
2365            || {
2366                let alive = "  100 1 S Tue Nov 24 14:00:00 2026\n".to_string();
2367                if !killed.get() {
2368                    return Some(alive);
2369                }
2370                after_kill.set(after_kill.get() + 1);
2371                // Still running once after KILL, then gone.
2372                Some(if after_kill.get() == 1 {
2373                    alive
2374                } else {
2375                    String::new()
2376                })
2377            },
2378            |signal, _| killed.set(killed.get() || signal == "-KILL"),
2379        );
2380        assert!(gone);
2381        assert_eq!(after_kill.get(), 2, "both listings after KILL were read");
2382    }
2383
2384    #[test]
2385    fn curl_lines_become_requests() {
2386        let here = Path::new(".");
2387        let r = parse_curl(
2388            "curl -sS -X POST -H 'Content-Type: text/plain' -d 'hello world' http://localhost:8080/upper?x=1",
2389            here,
2390            here,
2391        )
2392        .unwrap();
2393        assert_eq!(r.method, "POST");
2394        assert_eq!(r.path, "/upper?x=1");
2395        assert_eq!(r.body.as_deref(), Some("hello world"));
2396        assert_eq!(r.headers["Content-Type"], "text/plain");
2397        let g = parse_curl("curl 127.0.0.1:3000", here, here).unwrap();
2398        assert_eq!((g.method.as_str(), g.path.as_str()), ("GET", "/"));
2399        let form = parse_curl("curl -d a=1 http://[::1]:80/f", here, here).unwrap();
2400        assert_eq!(form.method, "POST");
2401        assert_eq!(
2402            form.headers["Content-Type"],
2403            "application/x-www-form-urlencoded"
2404        );
2405        assert!(parse_curl("curl https://example.com/x", here, here).is_none());
2406        let query = parse_curl("curl 'http://localhost?x=y#section'", here, here).unwrap();
2407        assert_eq!(query.path, "/?x=y");
2408        let fragment = parse_curl("curl 'http://[::1]:8080/path#section'", here, here).unwrap();
2409        assert_eq!(fragment.path, "/path");
2410        assert!(parse_curl("curl ftp://localhost/file", here, here).is_none());
2411        assert!(parse_curl("curl --unknown x http://localhost/", here, here).is_none());
2412        assert!(parse_curl("curl http://localhost/ | jq .", here, here).is_none());
2413    }
2414
2415    #[test]
2416    fn a_curl_example_wrapped_over_lines_is_one_request() {
2417        let repo = std::env::temp_dir().join(format!("ra-curl-wrapped-{}", std::process::id()));
2418        let _ = std::fs::remove_dir_all(&repo);
2419        std::fs::create_dir_all(&repo).unwrap();
2420        std::fs::write(
2421            repo.join("README.md"),
2422            "```sh\ncurl -X POST http://localhost:8080/users \\\n  -H 'Content-Type: application/json' \\\n  -d '{\"name\":\"ada\"}'\n```\n",
2423        )
2424        .unwrap();
2425        let reqs = app::scan_examples(&repo, |line, doc_dir| parse_curl(line, &repo, doc_dir));
2426        std::fs::remove_dir_all(&repo).unwrap();
2427        assert_eq!(reqs.len(), 1, "{reqs:?}");
2428        assert_eq!(
2429            (reqs[0].method.as_str(), reqs[0].path.as_str()),
2430            ("POST", "/users")
2431        );
2432        assert_eq!(reqs[0].body.as_deref(), Some("{\"name\":\"ada\"}"));
2433        assert_eq!(reqs[0].headers["Content-Type"], "application/json");
2434    }
2435
2436    #[test]
2437    fn curl_data_and_binary_file_inputs_match_curl_file_semantics() {
2438        let root = app::temp_dir("curl-data").unwrap();
2439        std::fs::write(root.join("body.txt"), b"one\r\ntwo\0\nthree").unwrap();
2440        let body = |flag| {
2441            parse_curl(
2442                &format!("curl {flag} @body.txt http://localhost/upper"),
2443                &root,
2444                &root,
2445            )
2446            .unwrap()
2447            .body
2448            .unwrap()
2449        };
2450        let data = body("--data");
2451        let binary = body("--data-binary");
2452        std::fs::remove_dir_all(root).unwrap();
2453        assert_eq!(data, "onetwothree");
2454        assert_eq!(binary, "one\r\ntwo\0\nthree");
2455    }
2456
2457    #[test]
2458    fn informational_responses_do_not_replace_the_final_response() {
2459        let raw = b"HTTP/1.1 100 Continue\r\n\r\nHTTP/1.1 103 Early Hints\r\nLink: </app.js>\r\n\r\nHTTP/1.1 201 Created\r\nContent-Length: 2\r\n\r\nok";
2460        let response = read_response(&mut &raw[..], false).unwrap();
2461        assert_eq!(response.status, 201);
2462        assert_eq!(response.body, b"ok");
2463        assert!(!response.headers.contains_key("link"));
2464
2465        let switching = b"HTTP/1.1 101 Switching Protocols\r\n\r\n";
2466        assert_eq!(
2467            read_response(&mut &switching[..], false).unwrap().status,
2468            101
2469        );
2470    }
2471
2472    #[test]
2473    fn responses_parse_with_length_chunks_or_close() {
2474        let fixed =
2475            b"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 5\r\n\r\nhelloEXTRA";
2476        let r = read_response(&mut &fixed[..], false).unwrap();
2477        assert_eq!((r.status, r.body.as_slice()), (200, &b"hello"[..]));
2478        assert_eq!(r.headers["content-type"], "text/plain");
2479        let chunked = b"HTTP/1.1 404 Not Found\r\nTransfer-Encoding: chunked\r\n\r\n4\r\nnot \r\n5;x=y\r\nfound\r\n0\r\n\r\n";
2480        let r = read_response(&mut &chunked[..], false).unwrap();
2481        assert_eq!((r.status, r.body.as_slice()), (404, &b"not found"[..]));
2482        let close = b"HTTP/1.0 500 Oops\r\n\r\nbye";
2483        assert_eq!(read_response(&mut &close[..], false).unwrap().body, b"bye");
2484    }
2485
2486    struct Client {
2487        sent: std::io::Cursor<Vec<u8>>,
2488        heard: Vec<u8>,
2489    }
2490
2491    impl Read for Client {
2492        fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
2493            self.sent.read(buf)
2494        }
2495    }
2496
2497    impl Write for Client {
2498        fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
2499            self.heard.write(buf)
2500        }
2501
2502        fn flush(&mut self) -> std::io::Result<()> {
2503            Ok(())
2504        }
2505    }
2506
2507    fn client(raw: &[u8]) -> Client {
2508        Client {
2509            sent: std::io::Cursor::new(raw.to_vec()),
2510            heard: Vec::new(),
2511        }
2512    }
2513
2514    #[test]
2515    fn requests_parse_with_length_chunks_or_no_body() {
2516        let mut c = client(
2517            b"POST /upper?x=1 HTTP/1.1\r\nHost: example.test\r\nContent-Type: text/plain\r\nContent-Length: 5\r\nConnection: keep-alive\r\n\r\nhelloEXTRA",
2518        );
2519        let req = read_request(&mut c).unwrap();
2520        assert_eq!(
2521            (req.method.as_str(), req.path.as_str()),
2522            ("POST", "/upper?x=1")
2523        );
2524        assert_eq!(req.body.as_deref(), Some("hello"));
2525        assert_eq!(
2526            req.headers.keys().collect::<Vec<_>>(),
2527            ["Content-Type", "Host"]
2528        );
2529        let mut c = client(
2530            b"PUT http://example.test/a HTTP/1.1\r\nTransfer-Encoding: chunked\r\nExpect: 100-continue\r\n\r\n3\r\nab\xff\r\n0\r\n\r\n",
2531        );
2532        let req = read_request(&mut c).unwrap();
2533        assert_eq!(req.path, "/a");
2534        assert_eq!(req.body, None);
2535        assert_eq!(req.body_bytes().unwrap().unwrap(), b"ab\xff");
2536        assert!(req.headers.is_empty(), "{req:?}");
2537        assert_eq!(c.heard, b"HTTP/1.1 100 Continue\r\n\r\n");
2538        let req = read_request(&mut client(b"GET / HTTP/1.1\r\n\r\n")).unwrap();
2539        assert_eq!((req.body, req.body_base64), (None, None));
2540        assert!(read_request(&mut client(b"hello\r\n\r\n")).is_err());
2541        assert!(
2542            read_request(&mut client(
2543                b"GET / HTTP/1.1\r\nContent-Length: 9\r\n\r\nshort"
2544            ))
2545            .is_err()
2546        );
2547    }
2548
2549    #[test]
2550    fn an_exchange_keeps_the_raw_response_and_the_client_host() {
2551        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
2552        let addr = listener.local_addr().unwrap();
2553        let server = std::thread::spawn(move || {
2554            let (mut stream, _) = listener.accept().unwrap();
2555            let req = read_request(&mut stream).unwrap();
2556            stream
2557                .write_all(b"HTTP/1.1 201 Created\r\nX-Id: 7\r\nContent-Length: 2\r\n\r\nok")
2558                .unwrap();
2559            req
2560        });
2561        let mut headers = BTreeMap::new();
2562        headers.insert("Host".to_string(), "example.test".to_string());
2563        let req = Req {
2564            method: "POST".to_string(),
2565            path: "/x".to_string(),
2566            headers,
2567            body: Some("hi".to_string()),
2568            body_base64: None,
2569            body_file: None,
2570        };
2571        let (resp, raw) = exchange(addr, &req, Duration::from_secs(5)).unwrap();
2572        assert_eq!((resp.status, resp.body.as_slice()), (201, &b"ok"[..]));
2573        assert_eq!(resp.headers["x-id"], "7");
2574        assert_eq!(
2575            raw,
2576            b"HTTP/1.1 201 Created\r\nX-Id: 7\r\nContent-Length: 2\r\n\r\nok"
2577        );
2578        let seen = server.join().unwrap();
2579        assert_eq!(seen.headers["Host"], "example.test");
2580        assert_eq!(seen.body.as_deref(), Some("hi"));
2581    }
2582
2583    #[test]
2584    fn malformed_http_chunks_are_errors() {
2585        let mut bad_ending = &b"1\r\naXX0\r\n\r\n"[..];
2586        assert!(read_chunked(&mut bad_ending, Vec::new()).is_err());
2587        let max = format!("{:x}\r\n", usize::MAX);
2588        assert!(read_chunked(&mut max.as_bytes(), Vec::new()).is_err());
2589        let mut truncated = &b"1\r\na\r\n0\r\n"[..];
2590        assert!(read_chunked(&mut truncated, Vec::new()).is_err());
2591        let mut trailers = &b"1\r\na\r\n0\r\nX-Trailer: present\r\n\r\n"[..];
2592        assert_eq!(read_chunked(&mut trailers, Vec::new()).unwrap(), b"a");
2593    }
2594
2595    #[test]
2596    fn fixed_body_rejects_malformed_lengths_and_accepts_equal_duplicates() {
2597        let response = |lengths| {
2598            let msg = format!("HTTP/1.1 200 OK\r\n{lengths}\r\n\r\nabc trailing");
2599            read_response(&mut msg.as_bytes(), false)
2600        };
2601        assert!(response("Content-Length: invalid").is_err());
2602        assert!(response("Content-Length: 3\r\nContent-Length: 4").is_err());
2603        let matching = response("Content-Length: 3\r\nContent-Length: 03").unwrap();
2604        assert_eq!(matching.body, b"abc");
2605    }
2606
2607    #[test]
2608    fn interrupted_close_delimited_body_is_an_error() {
2609        struct BrokenBody;
2610
2611        impl Read for BrokenBody {
2612            fn read(&mut self, _: &mut [u8]) -> std::io::Result<usize> {
2613                Err(std::io::ErrorKind::TimedOut.into())
2614            }
2615        }
2616
2617        let response = &b"HTTP/1.0 200 OK\r\n\r\npartial"[..];
2618        assert!(read_response(&mut response.chain(BrokenBody), false).is_err());
2619    }
2620
2621    #[test]
2622    fn traps_change_path_segments_queries_and_bodies() {
2623        let base = Req {
2624            method: "POST".into(),
2625            path: "/div/7/2?name=bob".into(),
2626            headers: BTreeMap::new(),
2627            body: Some("{\"a\":1}".into()),
2628            body_base64: None,
2629            body_file: None,
2630        };
2631        let (t, dropped) = traps(&[base]);
2632        assert_eq!(dropped, 0);
2633        assert!(t.iter().any(|r| r.path == "/div/-7/2?name=bob"));
2634        assert!(t.iter().any(|r| r.path == "/div/7/0?name=bob"));
2635        assert!(
2636            t.iter()
2637                .any(|r| r.path == "/div/7/2?name=%F0%9F%91%8D%F0%9F%8F%BD%20thumbs")
2638        );
2639        assert!(
2640            t.iter()
2641                .all(|r| r.path.starts_with("/div/") || r.path == "/rust-anything-missing")
2642        );
2643        assert!(
2644            t.iter()
2645                .any(|r| r.body.as_deref() == Some(app::JSON_TRAPS[0]))
2646        );
2647        assert_eq!(percent_decode("a%20b%zz"), "a b%zz");
2648        // `from_str_radix` accepts a sign, so `%+1` and `%-1` used to decode as an escape.
2649        assert_eq!(percent_decode("%+1"), "%+1");
2650        assert_eq!(percent_decode("%-1"), "%-1");
2651        assert_eq!(percent_decode("%2b"), "+");
2652        assert_eq!(percent_decode("%2B"), "+");
2653        assert_eq!(percent_decode("%4"), "%4");
2654    }
2655
2656    #[test]
2657    fn http_traps_spread_across_all_endpoints_keep_unknown_route_and_deduplicate() {
2658        // 40 endpoints each with a numeric path segment and a query param -> > 300 unique traps.
2659        let bases: Vec<Req> = (0..40)
2660            .map(|i| Req {
2661                method: "GET".into(),
2662                path: format!("/ep{i:02}/7?name=bob"),
2663                headers: BTreeMap::new(),
2664                body: None,
2665                body_base64: None,
2666                body_file: None,
2667            })
2668            .collect();
2669        let (t, dropped) = traps(&bases);
2670        assert_eq!(t.len(), app::MAX_TRAPS);
2671        assert!(dropped > 0);
2672        // Unknown-route probe is always kept even when traps exceed MAX_TRAPS.
2673        assert!(
2674            t.iter()
2675                .any(|r| r.method == "GET" && r.path == "/rust-anything-missing"),
2676            "unknown-route trap was dropped"
2677        );
2678        // Every single endpoint gets traps round-robin (not just the first few).
2679        for i in 0..40 {
2680            let prefix = format!("/ep{i:02}/");
2681            let count = t.iter().filter(|r| r.path.starts_with(&prefix)).count();
2682            assert!(
2683                count >= 7,
2684                "{prefix} only got {count} traps out of {}",
2685                app::MAX_TRAPS
2686            );
2687        }
2688        // All emitted traps are unique and distinct from bases.
2689        let keys: BTreeSet<String> = t.iter().map(req_key).collect();
2690        assert_eq!(keys.len(), t.len());
2691        for b in &bases {
2692            assert!(!keys.contains(&req_key(b)));
2693        }
2694
2695        // Colliding traps across many bases (> 300 raw, < 300 unique) deduplicate before
2696        // truncating so nothing is dropped and later endpoints still get traps.
2697        let mut colliding: Vec<Req> = (1..=40)
2698            .map(|i| Req {
2699                method: "GET".into(),
2700                path: format!("/items/{i}"),
2701                headers: BTreeMap::new(),
2702                body: None,
2703                body_base64: None,
2704                body_file: None,
2705            })
2706            .collect();
2707        colliding.push(Req {
2708            method: "GET".into(),
2709            path: "/tail/hello".into(),
2710            headers: BTreeMap::new(),
2711            body: None,
2712            body_base64: None,
2713            body_file: None,
2714        });
2715        let (ct, cdropped) = traps(&colliding);
2716        assert_eq!(cdropped, 0);
2717        assert!(ct.iter().any(|r| r.path.starts_with("/tail/")));
2718        assert!(ct.iter().any(|r| r.path == "/rust-anything-missing"));
2719        let ckeys: BTreeSet<String> = ct.iter().map(req_key).collect();
2720        assert_eq!(ckeys.len(), ct.len());
2721    }
2722
2723    #[test]
2724    fn parse_curl_supports_binary_files_and_multipart_forms() {
2725        let root = app::temp_dir("curl-binary-multipart").unwrap();
2726        let png = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0xff];
2727        std::fs::write(root.join("photo.png"), &png).unwrap();
2728        std::fs::write(root.join("note.txt"), "hello form").unwrap();
2729
2730        let bin = parse_curl(
2731            "curl --data-binary @photo.png -H 'Content-Type: image/png' http://localhost:8080/upload",
2732            &root,
2733            &root,
2734        )
2735        .unwrap();
2736        assert_eq!(bin.method, "POST");
2737        assert!(bin.body.is_none());
2738        assert!(bin.body_base64.is_some());
2739        assert_eq!(bin.body_bytes().unwrap().as_deref(), Some(png.as_slice()));
2740
2741        let multi = parse_curl(
2742            "curl -F title=avatar -F 'file=@photo.png;type=image/png;filename=pic.png' -F 'note=<note.txt' http://localhost:8080/multipart",
2743            &root,
2744            &root,
2745        )
2746        .unwrap();
2747        assert_eq!(multi.method, "POST");
2748        let ct = multi.headers.get("Content-Type").unwrap();
2749        assert!(ct.starts_with("multipart/form-data; boundary="), "{ct}");
2750        let raw = multi.body_bytes().unwrap().unwrap();
2751        assert!(find(&raw, b"name=\"title\"\r\n\r\navatar\r\n").is_some());
2752        assert!(
2753            find(
2754                &raw,
2755                b"name=\"file\"; filename=\"pic.png\"\r\nContent-Type: image/png\r\n\r\n"
2756            )
2757            .is_some()
2758        );
2759        assert!(find(&raw, &png).is_some());
2760        assert!(find(&raw, b"name=\"note\"\r\n\r\nhello form\r\n").is_some());
2761
2762        // Quoted -F values and filenames containing `;`, plus --form-string literal preservation.
2763        std::fs::write(root.join("photo;final.png"), &png).unwrap();
2764        let quoted = parse_curl(
2765            "curl -H 'Content-Type: multipart/mixed; charset=utf-8' \
2766             -F 'colors=\"red; green; blue\";type=text/plain' \
2767             -F 'file=@\"photo;final.png\"' \
2768             --form-string 'raw=\"a; b\"' \
2769             http://localhost:8080/quoted",
2770            &root,
2771            &root,
2772        )
2773        .unwrap();
2774        let qct = quoted.headers.get("Content-Type").unwrap();
2775        assert!(
2776            qct.starts_with("multipart/mixed; charset=utf-8; boundary="),
2777            "{qct}"
2778        );
2779        let qraw = quoted.body_bytes().unwrap().unwrap();
2780        assert!(
2781            find(
2782                &qraw,
2783                b"name=\"colors\"\r\nContent-Type: text/plain\r\n\r\nred; green; blue\r\n"
2784            )
2785            .is_some()
2786        );
2787        assert!(
2788            find(
2789                &qraw,
2790                b"name=\"file\"; filename=\"photo;final.png\"\r\nContent-Type: image/png\r\n\r\n"
2791            )
2792            .is_some()
2793        );
2794        assert!(find(&qraw, b"name=\"raw\"\r\n\r\n\"a; b\"\r\n").is_some());
2795
2796        // Caller-supplied `Content-Type: multipart/form-data` still gets the generated boundary.
2797        let hdr_ct = parse_curl(
2798            "curl -H 'Content-Type: multipart/form-data' -F a=1 http://localhost:8080/m",
2799            &root,
2800            &root,
2801        )
2802        .unwrap();
2803        let hct = hdr_ct.headers.get("Content-Type").unwrap();
2804        assert!(hct.starts_with("multipart/form-data; boundary="), "{hct}");
2805
2806        // Mixing -d and -F is refused, as curl does.
2807        assert!(parse_curl("curl -d a=1 -F b=2 http://localhost:8080/mix", &root, &root).is_none());
2808
2809        std::fs::remove_dir_all(root).unwrap();
2810    }
2811
2812    #[test]
2813    fn binary_request_bodies_round_trip_through_inputs_and_toml() {
2814        let root = app::temp_dir("http-binary-spec").unwrap();
2815        let bytes = vec![0x00, 0xff, 0x80, 0xfe, b'A', b'B'];
2816        let b64 = encode_base64(&bytes);
2817        std::fs::write(root.join("blob.bin"), &bytes).unwrap();
2818        std::fs::write(
2819            root.join("inputs.jsonl"),
2820            format!(
2821                "{{\"name\":\"b64\",\"method\":\"POST\",\"path\":\"/raw\",\"body_base64\":\"{b64}\"}}\n\
2822                 {{\"name\":\"file\",\"method\":\"POST\",\"path\":\"/raw\",\"body_file\":\"blob.bin\"}}\n"
2823            ),
2824        )
2825        .unwrap();
2826
2827        let inputs = read_inputs(&root.join("inputs.jsonl"), &root).unwrap();
2828        assert_eq!(inputs.len(), 2);
2829        assert_eq!(
2830            inputs[0].1.body_bytes().unwrap().as_deref(),
2831            Some(bytes.as_slice())
2832        );
2833        assert_eq!(
2834            inputs[1].1.body_bytes().unwrap().as_deref(),
2835            Some(bytes.as_slice())
2836        );
2837
2838        // Round-trip through write_case + load_spec (body_base64) and hand-written body_file.
2839        let http_dir = root.join("http");
2840        std::fs::create_dir_all(&http_dir).unwrap();
2841        write_case(
2842            &http_dir,
2843            "b64",
2844            &inputs[0].1,
2845            200,
2846            &BTreeMap::new(),
2847            b"ok",
2848            false,
2849        )
2850        .unwrap();
2851        let loaded = load_spec(&http_dir, &http_dir.join("b64.toml")).unwrap();
2852        assert_eq!(
2853            loaded.req.body_bytes().unwrap().as_deref(),
2854            Some(bytes.as_slice())
2855        );
2856
2857        std::fs::write(http_dir.join("payload.bin"), &bytes).unwrap();
2858        std::fs::write(
2859            http_dir.join("from-file.toml"),
2860            "[request]\nmethod = \"POST\"\npath = \"/raw\"\nbody_file = \"payload.bin\"\n\n[response]\nstatus = 200\n",
2861        )
2862        .unwrap();
2863        let from_file = load_spec(&http_dir, &http_dir.join("from-file.toml")).unwrap();
2864        assert_eq!(
2865            from_file.req.body_bytes().unwrap().as_deref(),
2866            Some(bytes.as_slice())
2867        );
2868
2869        // Reject traversal in body_file and invalid base64.
2870        std::fs::write(
2871            http_dir.join("escape.toml"),
2872            "[request]\nmethod = \"POST\"\npath = \"/raw\"\nbody_file = \"../blob.bin\"\n\n[response]\nstatus = 200\n",
2873        )
2874        .unwrap();
2875        assert!(load_spec(&http_dir, &http_dir.join("escape.toml")).is_err());
2876
2877        // Reject symlink escaping http/.
2878        #[cfg(unix)]
2879        {
2880            std::os::unix::fs::symlink(root.join("blob.bin"), http_dir.join("link.bin")).unwrap();
2881            std::fs::write(
2882                http_dir.join("symlink-escape.toml"),
2883                "[request]\nmethod = \"POST\"\npath = \"/raw\"\nbody_file = \"link.bin\"\n\n[response]\nstatus = 200\n",
2884            )
2885            .unwrap();
2886            assert!(load_spec(&http_dir, &http_dir.join("symlink-escape.toml")).is_err());
2887        }
2888
2889        assert!(decode_base64_strict("not!valid!b64!").is_err());
2890
2891        // Quoted Content-Type parameters containing `;` are preserved when replacing boundary.
2892        assert_eq!(
2893            with_multipart_boundary("multipart/form-data; profile=\"a;b\"; boundary=old", "new"),
2894            "multipart/form-data; profile=\"a;b\"; boundary=new"
2895        );
2896        // Unsupported curl `-F '...;headers=...'` and `encoder=` are declined cleanly.
2897        assert!(
2898            parse_curl(
2899                "curl -F 'submit=OK;headers=\"X-Submit-Type: OK\"' http://localhost:8080/h",
2900                &root,
2901                &root,
2902            )
2903            .is_none()
2904        );
2905        assert!(
2906            parse_curl(
2907                "curl -F 'note=hello;type=text/plain;encoder=base64' http://localhost:8080/h",
2908                &root,
2909                &root,
2910            )
2911            .is_none()
2912        );
2913        // Parameters following `;type=` belong to the part Content-Type, not the field value.
2914        let typed = parse_curl(
2915            "curl -F 'note=hello;type=text/plain;charset=UTF-8' http://localhost:8080/typed",
2916            &root,
2917            &root,
2918        )
2919        .unwrap();
2920        let typed_raw = typed.body_bytes().unwrap().unwrap();
2921        assert!(
2922            find(
2923                &typed_raw,
2924                b"name=\"note\"\r\nContent-Type: text/plain;charset=UTF-8\r\n\r\nhello\r\n"
2925            )
2926            .is_some()
2927        );
2928        // Non-string TOML body declarations are rejected before exclusivity checks.
2929        std::fs::write(
2930            http_dir.join("bad-type.toml"),
2931            "[request]\nmethod = \"POST\"\npath = \"/raw\"\nbody = \"fallback\"\nbody_base64 = 42\n\n[response]\nstatus = 200\n",
2932        )
2933        .unwrap();
2934        assert!(load_spec(&http_dir, &http_dir.join("bad-type.toml")).is_err());
2935        std::fs::write(
2936            http_dir.join("bad-file-type.toml"),
2937            "[request]\nmethod = \"POST\"\npath = \"/raw\"\nbody_file = 42\n\n[response]\nstatus = 200\n",
2938        )
2939        .unwrap();
2940        assert!(load_spec(&http_dir, &http_dir.join("bad-file-type.toml")).is_err());
2941        // Non-regular body_file (e.g. directory) is rejected.
2942        std::fs::create_dir_all(http_dir.join("subdir")).unwrap();
2943        std::fs::write(
2944            http_dir.join("dir-body.toml"),
2945            "[request]\nmethod = \"POST\"\npath = \"/raw\"\nbody_file = \"subdir\"\n\n[response]\nstatus = 200\n",
2946        )
2947        .unwrap();
2948        assert!(load_spec(&http_dir, &http_dir.join("dir-body.toml")).is_err());
2949
2950        std::fs::remove_dir_all(root).unwrap();
2951    }
2952
2953    #[test]
2954    fn merge_config_drops_http_and_clears_saved_lists() {
2955        let base_opts = |http, port, server_args, fresh, pace_ms| RecordOptions {
2956            repo: Path::new("."),
2957            run: &[],
2958            inputs: None,
2959            normalize: &[],
2960            name: None,
2961            traps: false,
2962            timeout_secs: None,
2963            http,
2964            port,
2965            server_args,
2966            fresh,
2967            pace_ms,
2968            float_tolerance: None,
2969            float_files: &[],
2970            effects: None,
2971            ready_secs: None,
2972        };
2973        let saved = HttpConfig {
2974            port: Some(8080),
2975            args: vec!["db.json".into()],
2976            fresh: vec!["data".into()],
2977            pace_ms: Some(25),
2978            ready_secs: None,
2979        };
2980
2981        // `--no-http` drops the saved server configuration.
2982        let dropped = merge_config(
2983            Some(saved.clone()),
2984            &base_opts(Some(false), None, None, None, None),
2985        )
2986        .unwrap();
2987        assert!(dropped.is_none());
2988
2989        // Combining `--no-http` with server-only options fails.
2990        assert!(
2991            merge_config(
2992                Some(saved.clone()),
2993                &base_opts(Some(false), Some(8080), None, None, None)
2994            )
2995            .is_err()
2996        );
2997        let one_arg = ["db.json".to_string()];
2998        assert!(
2999            merge_config(
3000                Some(saved.clone()),
3001                &base_opts(Some(false), None, Some(&one_arg), None, None)
3002            )
3003            .is_err()
3004        );
3005        assert!(
3006            merge_config(
3007                Some(saved.clone()),
3008                &base_opts(Some(false), None, None, None, Some(10))
3009            )
3010            .is_err()
3011        );
3012
3013        // Passing `Some(&[])` clears saved `args` and `fresh`; `--port 0` clears `port`.
3014        let cleared = merge_config(
3015            Some(saved.clone()),
3016            &base_opts(None, Some(0), Some(&[]), Some(&[]), Some(0)),
3017        )
3018        .unwrap()
3019        .unwrap();
3020        assert_eq!(cleared.port, None);
3021        assert!(cleared.args.is_empty());
3022        assert!(cleared.fresh.is_empty());
3023        assert_eq!(cleared.pace_ms, None);
3024
3025        // Clearing `args` on a CLI recording (no saved `http`) does not turn it into a server.
3026        assert!(
3027            merge_config(None, &base_opts(None, None, Some(&[]), Some(&[]), None))
3028                .unwrap()
3029                .is_none()
3030        );
3031
3032        // Omitting options preserves the saved `http` settings.
3033        let kept = merge_config(Some(saved), &base_opts(None, None, None, None, None))
3034            .unwrap()
3035            .unwrap();
3036        assert_eq!(kept.port, Some(8080));
3037        assert_eq!(kept.args, ["db.json"]);
3038        assert_eq!(kept.fresh, ["data"]);
3039        assert_eq!(kept.pace_ms, Some(25));
3040    }
3041
3042    #[test]
3043    fn start_ephemeral_retries_when_an_auto_picked_port_is_snatched() {
3044        let busy = TcpListener::bind("127.0.0.1:0").unwrap();
3045        let busy_port = busy.local_addr().unwrap().port();
3046        let free = free_port().unwrap();
3047        assert_ne!(free, busy_port);
3048
3049        let launch = Launch {
3050            args: &[],
3051            files: None,
3052            pace: None,
3053            effects: None,
3054            ready: Duration::from_secs(1),
3055        };
3056        let repo = std::env::temp_dir();
3057
3058        // Explicit fixed port still fails immediately with PortInUse.
3059        let fixed_err = Server::start(&[], &launch, &repo, busy_port)
3060            .err()
3061            .expect("busy fixed port must fail");
3062        assert!(
3063            fixed_err.downcast_ref::<PortInUse>().is_some(),
3064            "{fixed_err:#}"
3065        );
3066
3067        // Ephemeral start retries past the busy port and proceeds to the next port (where empty
3068        // command fails after passing the busy-port check).
3069        let mut ports = [busy_port, free].into_iter();
3070        let err = start_ephemeral(&[], &launch, &repo, || Ok(ports.next().unwrap()))
3071            .err()
3072            .expect("empty command must fail after retrying past busy port");
3073        assert!(err.downcast_ref::<PortInUse>().is_none(), "{err:#}");
3074        assert!(format!("{err:#}").contains("empty command"), "{err:#}");
3075    }
3076}