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