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::{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}
57
58/// The `http` config of a recording: the saved one, changed by what this record was given.
59pub(crate) fn merge_config(saved: Option<HttpConfig>, opts: &RecordOptions) -> Option<HttpConfig> {
60    let asked = opts.http
61        || opts.port.is_some()
62        || !opts.server_args.is_empty()
63        || !opts.fresh.is_empty()
64        || opts.pace_ms.is_some();
65    let mut config = match (saved, asked) {
66        (Some(c), _) => c,
67        (None, true) => HttpConfig::default(),
68        (None, false) => return None,
69    };
70    if opts.port.is_some() {
71        config.port = opts.port;
72    }
73    if !opts.server_args.is_empty() {
74        config.args = opts.server_args.to_vec();
75    }
76    if !opts.fresh.is_empty() {
77        config.fresh = opts.fresh.to_vec();
78    }
79    if let Some(pace) = opts.pace_ms {
80        config.pace_ms = (pace > 0).then_some(pace);
81    }
82    Some(config)
83}
84
85pub(crate) const FILES_DIR: &str = "files";
86
87fn copy_tree(from: &Path, to: &Path) -> Result<()> {
88    if from.is_dir() {
89        std::fs::create_dir_all(to)?;
90        for entry in std::fs::read_dir(from)?.flatten() {
91            copy_tree(&entry.path(), &to.join(entry.file_name()))?;
92        }
93    } else {
94        if let Some(parent) = to.parent() {
95            std::fs::create_dir_all(parent)?;
96        }
97        std::fs::copy(from, to)
98            .with_context(|| format!("copying {} to {}", from.display(), to.display()))?;
99    }
100    Ok(())
101}
102
103/// Copies the `fresh` paths from the repository into `http/files/`, replacing the last snapshot.
104fn snapshot(repo: &Path, fresh: &[String]) -> Result<Option<PathBuf>> {
105    if fresh.is_empty() {
106        return Ok(None);
107    }
108    let dir = app::cases_dir(repo).join(HTTP_DIR).join(FILES_DIR);
109    let _ = std::fs::remove_dir_all(&dir);
110    for path in fresh {
111        let rel = Path::new(path);
112        ensure!(
113            rel.is_relative()
114                && rel
115                    .components()
116                    .all(|c| matches!(c, std::path::Component::Normal(_))),
117            "--fresh `{path}`: give a path inside the repository, relative to it"
118        );
119        let from = repo.join(rel);
120        ensure!(from.exists(), "--fresh `{path}`: no such file or folder");
121        copy_tree(&from, &dir.join(rel))?;
122    }
123    Ok(Some(dir))
124}
125
126/// The snapshot replay starts every build from, when the recording has `fresh` paths.
127fn saved_snapshot(repo: &Path, config: &Config) -> Result<Option<PathBuf>> {
128    if config.http.as_ref().is_none_or(|h| h.fresh.is_empty()) {
129        return Ok(None);
130    }
131    let dir = app::cases_dir(repo).join(HTTP_DIR).join(FILES_DIR);
132    ensure!(
133        dir.is_dir(),
134        "no {}: record again to snapshot the fresh files",
135        dir.display()
136    );
137    Ok(Some(dir))
138}
139
140fn get() -> String {
141    "GET".to_string()
142}
143
144/// One request, as recorded and as written in an `--inputs` line.
145#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
146pub struct Req {
147    #[serde(default = "get")]
148    pub method: String,
149    pub path: String,
150    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
151    pub headers: BTreeMap<String, String>,
152    #[serde(default, skip_serializing_if = "Option::is_none")]
153    pub body: Option<String>,
154}
155
156#[derive(Debug, Deserialize)]
157struct HttpInput {
158    #[serde(default)]
159    name: Option<String>,
160    #[serde(flatten)]
161    req: Req,
162}
163
164#[derive(Debug, Clone)]
165struct Resp {
166    status: u16,
167    headers: BTreeMap<String, String>,
168    body: Vec<u8>,
169}
170
171pub fn free_port() -> Result<u16> {
172    Ok(TcpListener::bind("127.0.0.1:0")?.local_addr()?.port())
173}
174
175fn local(port: u16) -> SocketAddr {
176    SocketAddr::from(([127, 0, 0, 1], port))
177}
178
179fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
180    haystack.windows(needle.len()).position(|w| w == needle)
181}
182
183fn fill(stream: &mut impl Read, buf: &mut Vec<u8>, need: usize) -> Result<()> {
184    let mut chunk = [0u8; 8192];
185    while buf.len() < need {
186        let n = stream.read(&mut chunk)?;
187        ensure!(n > 0, "the connection closed in the middle of the response");
188        buf.extend_from_slice(&chunk[..n]);
189    }
190    Ok(())
191}
192
193fn chunk_line_end(stream: &mut impl Read, buf: &mut Vec<u8>) -> Result<usize> {
194    loop {
195        if let Some(end) = find(buf, b"\r\n") {
196            return Ok(end);
197        }
198        let need = buf.len() + 1;
199        fill(stream, buf, need)?;
200    }
201}
202
203fn read_chunked(stream: &mut impl Read, mut buf: Vec<u8>) -> Result<Vec<u8>> {
204    let mut body = Vec::new();
205    loop {
206        let line_end = chunk_line_end(stream, &mut buf)?;
207        let size_text = String::from_utf8_lossy(&buf[..line_end]).into_owned();
208        let size = usize::from_str_radix(size_text.split(';').next().unwrap_or("").trim(), 16)
209            .with_context(|| format!("bad chunk size `{size_text}`"))?;
210        buf.drain(..line_end + 2);
211        if size == 0 {
212            loop {
213                let line_end = chunk_line_end(stream, &mut buf)?;
214                if line_end == 0 {
215                    return Ok(body);
216                }
217                buf.drain(..line_end + 2);
218            }
219        }
220        let end = size.checked_add(2).context("chunk size is too large")?;
221        fill(stream, &mut buf, end)?;
222        ensure!(&buf[size..end] == b"\r\n", "bad chunk terminator");
223        body.extend_from_slice(&buf[..size]);
224        buf.drain(..end);
225    }
226}
227
228fn read_response(stream: &mut impl Read, head_only: bool) -> Result<Resp> {
229    let mut buf = Vec::new();
230    let mut chunk = [0u8; 8192];
231    let (status, head, mut rest) = loop {
232        let header_end = loop {
233            if let Some(i) = find(&buf, b"\r\n\r\n") {
234                break i;
235            }
236            let n = stream.read(&mut chunk)?;
237            ensure!(n > 0, "the connection closed before a full response");
238            buf.extend_from_slice(&chunk[..n]);
239        };
240        let head = String::from_utf8_lossy(&buf[..header_end]).into_owned();
241        let status_line = head.split("\r\n").next().unwrap_or_default();
242        let status: u16 = status_line
243            .split_whitespace()
244            .nth(1)
245            .and_then(|s| s.parse().ok())
246            .with_context(|| format!("not an HTTP response: `{status_line}`"))?;
247        let rest = buf.split_off(header_end + 4);
248        if status == 101 || !(100..200).contains(&status) {
249            break (status, head, rest);
250        }
251        buf = rest;
252    };
253    let lines = head.split("\r\n").skip(1);
254    let mut headers: BTreeMap<String, String> = BTreeMap::new();
255    for line in lines {
256        if let Some((k, v)) = line.split_once(':') {
257            let v = v.trim().to_string();
258            headers
259                .entry(k.trim().to_ascii_lowercase())
260                .and_modify(|e| {
261                    e.push_str(", ");
262                    e.push_str(&v);
263                })
264                .or_insert(v);
265        }
266    }
267    let chunked = headers
268        .get("transfer-encoding")
269        .is_some_and(|t| t.to_ascii_lowercase().contains("chunked"));
270    let body = if head_only || status == 204 || status == 304 || (100..200).contains(&status) {
271        Vec::new()
272    } else if chunked {
273        read_chunked(stream, rest)?
274    } else if let Some(lengths) = headers.get("content-length") {
275        let parse = |value: &str| -> Result<usize> {
276            let value = value.trim();
277            ensure!(
278                !value.is_empty() && value.bytes().all(|b| b.is_ascii_digit()),
279                "invalid Content-Length"
280            );
281            value.parse().context("invalid Content-Length")
282        };
283        let mut lengths = lengths.split(',');
284        let len = parse(lengths.next().unwrap_or_default())?;
285        for other in lengths {
286            ensure!(parse(other)? == len, "conflicting Content-Length headers");
287        }
288        fill(stream, &mut rest, len)?;
289        rest.truncate(len);
290        rest
291    } else {
292        stream
293            .read_to_end(&mut rest)
294            .context("reading close-delimited HTTP body")?;
295        rest
296    };
297    Ok(Resp {
298        status,
299        headers,
300        body,
301    })
302}
303
304fn send(port: u16, req: &Req, timeout: Duration) -> Result<Resp> {
305    let mut stream = TcpStream::connect_timeout(&local(port), timeout)?;
306    stream.set_read_timeout(Some(timeout))?;
307    stream.set_write_timeout(Some(timeout))?;
308    let body = req.body.as_deref().unwrap_or("").as_bytes();
309    let mut head = format!(
310        "{} {} HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nConnection: close\r\n",
311        req.method, req.path
312    );
313    for (k, v) in &req.headers {
314        if !matches!(
315            k.to_ascii_lowercase().as_str(),
316            "host" | "connection" | "content-length"
317        ) {
318            head += &format!("{k}: {v}\r\n");
319        }
320    }
321    if req.body.is_some() || matches!(req.method.as_str(), "POST" | "PUT" | "PATCH") {
322        head += &format!("Content-Length: {}\r\n", body.len());
323    }
324    head += "\r\n";
325    stream.write_all(head.as_bytes())?;
326    stream.write_all(body)?;
327    read_response(&mut stream, req.method == "HEAD")
328}
329
330/// A server process; stopped (SIGTERM, then SIGKILL) when dropped.
331struct Server {
332    child: Child,
333    port: u16,
334    dir: PathBuf,
335    cwd: PathBuf,
336    log: PathBuf,
337    stopped: bool,
338    sinks: Option<crate::effects::Sinks>,
339}
340
341impl Server {
342    fn start(command: &[String], launch: &Launch, repo: &Path, port: u16) -> Result<Server> {
343        let dir = app::temp_dir("server")?;
344        let words: Vec<String> = command
345            .iter()
346            .map(|w| app::resolve_word(repo, &w.replace("{port}", &port.to_string())))
347            .collect();
348        let (program, rest) = words.split_first().context("empty command")?;
349        let log = dir.join("fallback.log");
350        let cwd = match launch.files {
351            Some(files) => {
352                let cwd = dir.join("cwd");
353                copy_tree(files, &cwd)?;
354                cwd
355            }
356            None => repo.to_path_buf(),
357        };
358        let sinks = launch
359            .effects
360            .map(|config| -> Result<_> {
361                let sinks = crate::effects::Sinks::start(config)?;
362                sinks.reset(&cwd)?;
363                Ok(sinks)
364            })
365            .transpose()?;
366        let mut child = Command::new(program)
367            .args(rest)
368            .args(
369                launch
370                    .args
371                    .iter()
372                    .map(|a| a.replace("{port}", &port.to_string())),
373            )
374            .current_dir(&cwd)
375            .envs(sinks.iter().flat_map(crate::effects::Sinks::env))
376            .env("PORT", port.to_string())
377            .env(app::FALLBACK_ENV, &log)
378            .stdin(Stdio::null())
379            .stdout(std::fs::File::create(dir.join("stdout"))?)
380            .stderr(std::fs::File::create(dir.join("stderr"))?)
381            .spawn()
382            .with_context(|| format!("starting `{}`", command.join(" ")))?;
383        let deadline = Instant::now() + READY;
384        loop {
385            if TcpStream::connect_timeout(&local(port), Duration::from_millis(200)).is_ok() {
386                break;
387            }
388            let failure = if let Some(status) = child.try_wait()? {
389                Some(format!("exited ({status}) before listening"))
390            } else if Instant::now() > deadline {
391                Some(format!("did not listen within {}s", READY.as_secs()))
392            } else {
393                None
394            };
395            if let Some(failure) = failure {
396                let _ = child.kill();
397                let _ = child.wait();
398                let stderr = std::fs::read_to_string(dir.join("stderr")).unwrap_or_default();
399                let tail: Vec<&str> = stderr.lines().rev().take(15).collect();
400                let tail: Vec<&str> = tail.into_iter().rev().collect();
401                let _ = std::fs::remove_dir_all(&dir);
402                bail!(
403                    "`{}` {failure} on port {port}{}",
404                    command.join(" "),
405                    if tail.is_empty() {
406                        String::new()
407                    } else {
408                        format!(":\n{}", tail.join("\n"))
409                    }
410                );
411            }
412            std::thread::sleep(Duration::from_millis(50));
413        }
414        Ok(Server {
415            child,
416            port,
417            dir,
418            cwd,
419            log,
420            stopped: false,
421            sinks,
422        })
423    }
424
425    fn fallbacks(&self) -> Option<usize> {
426        std::fs::read_to_string(&self.log)
427            .ok()
428            .map(|t| t.lines().count())
429    }
430
431    fn stop(&mut self) {
432        if self.stopped {
433            return;
434        }
435        self.stopped = true;
436        #[cfg(unix)]
437        {
438            let _ = Command::new("kill")
439                .args(["-TERM", &self.child.id().to_string()])
440                .stderr(Stdio::null())
441                .status();
442            let deadline = Instant::now() + Duration::from_secs(5);
443            while Instant::now() < deadline {
444                if let Ok(Some(_)) = self.child.try_wait() {
445                    break;
446                }
447                std::thread::sleep(Duration::from_millis(20));
448            }
449        }
450        let _ = self.child.kill();
451        let _ = self.child.wait();
452        let _ = std::fs::remove_dir_all(&self.dir);
453    }
454}
455
456impl Drop for Server {
457    fn drop(&mut self) {
458        self.stop();
459    }
460}
461
462type Answer = (
463    std::result::Result<Resp, String>,
464    Option<bool>,
465    Option<Vec<u8>>,
466);
467
468/// What every start gets besides its command: the server's arguments and its fresh files.
469struct Launch<'a> {
470    args: &'a [String],
471    files: Option<&'a Path>,
472    pace: Option<Duration>,
473    effects: Option<&'a crate::effects::EffectsConfig>,
474}
475
476/// Starts the server once and sends every request in order.
477fn run_all(
478    command: &[String],
479    launch: &Launch,
480    repo: &Path,
481    port: u16,
482    reqs: &[&Req],
483    timeout: Duration,
484) -> Result<Vec<Answer>> {
485    let mut server = Server::start(command, launch, repo, port)?;
486    let mut out = Vec::new();
487    for req in reqs {
488        let before = server.fallbacks().unwrap_or(0);
489        let resp = send(server.port, req, timeout).map_err(|e| format!("{e:#}"));
490        if let Some(pace) = launch.pace {
491            std::thread::sleep(pace);
492        }
493        let fell_back = server.fallbacks().map(|after| after > before);
494        let effects = server.sinks.as_ref().map(|s| s.take(&server.cwd));
495        out.push((resp, fell_back, effects));
496    }
497    server.stop();
498    Ok(out)
499}
500
501fn percent_decode(text: &str) -> String {
502    let bytes = text.as_bytes();
503    let mut out = Vec::new();
504    let mut i = 0;
505    while i < bytes.len() {
506        if bytes[i] == b'%'
507            && let Some(hex) = text.get(i + 1..i + 3)
508            && let Ok(b) = u8::from_str_radix(hex, 16)
509        {
510            out.push(b);
511            i += 3;
512            continue;
513        }
514        out.push(bytes[i]);
515        i += 1;
516    }
517    String::from_utf8_lossy(&out).into_owned()
518}
519
520fn percent_encode(text: &str) -> String {
521    let mut out = String::new();
522    for b in text.bytes() {
523        if b.is_ascii_alphanumeric() || b"-._~".contains(&b) {
524            out.push(char::from(b));
525        } else {
526            out += &format!("%{b:02X}");
527        }
528    }
529    out
530}
531
532fn parse_curl(line: &str, repo: &Path, doc_dir: &Path) -> Option<Req> {
533    let toks = app::shell_tokens(line)?;
534    if toks.iter().any(|t| t.op) {
535        return None;
536    }
537    let words: Vec<String> = toks.into_iter().map(|t| t.text).collect();
538    let (first, args) = words.split_first()?;
539    if first != "curl" {
540        return None;
541    }
542    let mut method: Option<String> = None;
543    let mut headers = BTreeMap::new();
544    let mut data: Vec<String> = Vec::new();
545    let mut url: Option<String> = None;
546    let mut i = 0;
547    let read_file = |name: &str| -> Option<String> {
548        let name = name.strip_prefix('@')?;
549        [repo.join(name), doc_dir.join(name)]
550            .iter()
551            .find(|p| p.is_file())
552            .and_then(|p| std::fs::read_to_string(p).ok())
553    };
554    while i < args.len() {
555        let arg = &args[i];
556        let mut next = || -> Option<String> {
557            i += 1;
558            args.get(i).cloned()
559        };
560        match arg.as_str() {
561            "-X" | "--request" => method = Some(next()?),
562            "-H" | "--header" => {
563                let h = next()?;
564                let (k, v) = h.split_once(':')?;
565                headers.insert(k.trim().to_string(), v.trim().to_string());
566            }
567            "-d" | "--data" | "--data-raw" | "--data-binary" | "--data-ascii" => {
568                let d = next()?;
569                data.push(if d.starts_with('@') && arg != "--data-raw" {
570                    let mut contents = read_file(&d)?;
571                    if arg != "--data-binary" {
572                        contents.retain(|c| !matches!(c, '\r' | '\n' | '\0'));
573                    }
574                    contents
575                } else {
576                    d
577                });
578            }
579            "--json" => {
580                let d = next()?;
581                data.push(if d.starts_with('@') {
582                    read_file(&d)?
583                } else {
584                    d
585                });
586                headers
587                    .entry("Content-Type".to_string())
588                    .or_insert_with(|| "application/json".to_string());
589                headers
590                    .entry("Accept".to_string())
591                    .or_insert_with(|| "application/json".to_string());
592            }
593            "-A" | "--user-agent" => {
594                headers.insert("User-Agent".to_string(), next()?);
595            }
596            "-b" | "--cookie" => {
597                headers.insert("Cookie".to_string(), next()?);
598            }
599            "-e" | "--referer" => {
600                headers.insert("Referer".to_string(), next()?);
601            }
602            "-o" | "--output" | "-w" | "--write-out" | "-m" | "--max-time"
603            | "--connect-timeout" => {
604                next()?;
605            }
606            "--silent"
607            | "--show-error"
608            | "--include"
609            | "--verbose"
610            | "--location"
611            | "--fail"
612            | "--insecure"
613            | "--no-progress-meter" => {}
614            other if other.starts_with("-X") && other.len() > 2 => {
615                method = Some(other[2..].to_string());
616            }
617            other if other.starts_with("-H") && other.len() > 2 => {
618                let (k, v) = other[2..].split_once(':')?;
619                headers.insert(k.trim().to_string(), v.trim().to_string());
620            }
621            other
622                if other.starts_with('-')
623                    && other.len() > 1
624                    && !other.starts_with("--")
625                    && other[1..].chars().all(|c| "sSivLfk".contains(c)) => {}
626            other if other.starts_with('-') => return None,
627            other => url = Some(other.to_string()),
628        }
629        i += 1;
630    }
631    let url = url?;
632    let (scheme, rest) = url.split_once("://").unwrap_or(("http", &url));
633    if !matches!(scheme, "http" | "https") {
634        return None;
635    }
636    let rest = rest.split('#').next()?;
637    let (host, target) = rest.split_at(rest.find(['/', '?']).unwrap_or(rest.len()));
638    let path = if target.starts_with('/') {
639        target.to_string()
640    } else {
641        format!("/{target}")
642    };
643    let host = if host.starts_with('[') {
644        host.split_inclusive(']').next().unwrap_or(host)
645    } else {
646        host.split(':').next().unwrap_or(host)
647    };
648    if !LOCAL_HOSTS.contains(&host) {
649        return None;
650    }
651    let body = (!data.is_empty()).then(|| data.join("&"));
652    if body.is_some()
653        && !headers
654            .keys()
655            .any(|k| k.eq_ignore_ascii_case("content-type"))
656    {
657        headers.insert(
658            "Content-Type".to_string(),
659            "application/x-www-form-urlencoded".to_string(),
660        );
661    }
662    let method = method.unwrap_or_else(|| if body.is_some() { "POST" } else { "GET" }.to_string());
663    Some(Req {
664        method,
665        path,
666        headers,
667        body,
668    })
669}
670
671fn read_inputs(path: &Path) -> Result<Vec<(Option<String>, Req)>> {
672    let text =
673        std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
674    let mut out = Vec::new();
675    for (n, line) in text.lines().enumerate() {
676        if line.trim().is_empty() {
677            continue;
678        }
679        let input: HttpInput = serde_json::from_str(line).with_context(|| {
680            format!(
681                "{}:{}: expected {{\"method\", \"path\", \"headers\": {{...}}, \"body\"}}",
682                path.display(),
683                n + 1
684            )
685        })?;
686        ensure!(
687            input.req.path.starts_with('/'),
688            "{}:{}: `path` must start with /",
689            path.display(),
690            n + 1
691        );
692        out.push((input.name, input.req));
693    }
694    Ok(out)
695}
696
697fn trap_values(raw: &str) -> Vec<&'static str> {
698    if raw.parse::<i128>().is_ok() {
699        app::INT_TRAPS.to_vec()
700    } else if raw.parse::<f64>().is_ok() && raw.contains(['.', 'e', 'E']) {
701        app::FLOAT_TRAPS.to_vec()
702    } else {
703        app::STRING_TRAPS.to_vec()
704    }
705}
706
707fn traps(bases: &[Req]) -> Vec<Req> {
708    let mut out = Vec::new();
709    for base in bases {
710        let (path, query) = match base.path.split_once('?') {
711            Some((p, q)) => (p, Some(q)),
712            None => (base.path.as_str(), None),
713        };
714        let segments: Vec<&str> = path.split('/').collect();
715        for i in 2..segments.len() {
716            let raw = percent_decode(segments[i]);
717            for v in trap_values(&raw).into_iter().filter(|v| *v != raw) {
718                let mut parts: Vec<String> = segments.iter().map(|s| s.to_string()).collect();
719                parts[i] = percent_encode(v);
720                let mut req = base.clone();
721                req.path = parts.join("/") + &query.map(|q| format!("?{q}")).unwrap_or_default();
722                out.push(req);
723            }
724        }
725        if let Some(query) = query {
726            let pairs: Vec<&str> = query.split('&').collect();
727            for (i, pair) in pairs.iter().enumerate() {
728                let Some((key, raw)) = pair.split_once('=') else {
729                    continue;
730                };
731                let raw = percent_decode(raw);
732                for v in trap_values(&raw).into_iter().filter(|v| *v != raw) {
733                    let mut new: Vec<String> = pairs.iter().map(|p| p.to_string()).collect();
734                    new[i] = format!("{key}={}", percent_encode(v));
735                    let mut req = base.clone();
736                    req.path = format!("{path}?{}", new.join("&"));
737                    out.push(req);
738                }
739            }
740        }
741        if let Some(body) = &base.body {
742            let json =
743                serde_json::from_str::<Value>(body).is_ok_and(|v| v.is_object() || v.is_array());
744            let values: &[&str] = if json {
745                &app::JSON_TRAPS
746            } else {
747                &app::STDIN_TRAPS
748            };
749            for v in values {
750                let mut req = base.clone();
751                req.body = Some(v.to_string());
752                out.push(req);
753            }
754        }
755    }
756    out.push(Req {
757        method: "GET".to_string(),
758        path: "/rust-anything-missing".to_string(),
759        headers: BTreeMap::new(),
760        body: None,
761    });
762    out.truncate(app::MAX_TRAPS);
763    out
764}
765
766fn case_slug(req: &Req) -> String {
767    let first = req
768        .path
769        .split(['/', '?'])
770        .find(|s| !s.is_empty())
771        .unwrap_or("root");
772    app::slug(&format!("{} {first}", req.method))
773}
774
775fn settle_headers(
776    norm: &Normalizers,
777    a: &BTreeMap<String, String>,
778    b: &BTreeMap<String, String>,
779) -> (BTreeMap<String, String>, bool) {
780    let mut out = BTreeMap::new();
781    let mut noisy = false;
782    for (k, va) in a {
783        if SKIP_HEADERS.contains(&k.as_str()) {
784            continue;
785        }
786        let Some(vb) = b.get(k) else {
787            noisy = true;
788            continue;
789        };
790        let (va, vb) = (norm.apply(va), norm.apply(vb));
791        if va == vb {
792            out.insert(k.clone(), va);
793        } else {
794            noisy = true;
795            out.insert(k.clone(), app::merge_line(&va, &vb));
796        }
797    }
798    noisy |= b
799        .keys()
800        .any(|k| !a.contains_key(k) && !SKIP_HEADERS.contains(&k.as_str()));
801    (out, noisy)
802}
803
804fn table(entries: &BTreeMap<String, String>) -> Table {
805    let mut t = Table::new();
806    for (k, v) in entries {
807        t[k.as_str()] = value(v.as_str());
808    }
809    t
810}
811
812fn write_case(
813    dir: &Path,
814    name: &str,
815    req: &Req,
816    status: u16,
817    headers: &BTreeMap<String, String>,
818    body: &[u8],
819    binary: bool,
820) -> Result<()> {
821    let mut doc = DocumentMut::new();
822    let mut request = Table::new();
823    request["method"] = value(req.method.as_str());
824    request["path"] = value(req.path.as_str());
825    if let Some(body) = &req.body {
826        request["body"] = value(body.as_str());
827    }
828    if !req.headers.is_empty() {
829        request.insert("headers", Item::Table(table(&req.headers)));
830    }
831    doc.insert("request", Item::Table(request));
832    let mut response = Table::new();
833    response["status"] = value(i64::from(status));
834    if binary {
835        response["binary"] = value(true);
836    }
837    if !headers.is_empty() {
838        response.insert("headers", Item::Table(table(headers)));
839    }
840    doc.insert("response", Item::Table(response));
841    std::fs::write(dir.join(format!("{name}.toml")), doc.to_string())?;
842    std::fs::write(dir.join(format!("{name}.body")), body)?;
843    Ok(())
844}
845
846pub(crate) fn record(
847    repo: &Path,
848    config: &Config,
849    norm: &Normalizers,
850    opts: &RecordOptions,
851) -> Result<RecordOutcome> {
852    let examples = app::scan_examples(repo, |line, doc_dir| parse_curl(line, repo, doc_dir));
853    let inputs = match opts.inputs {
854        Some(path) => read_inputs(path)?,
855        None => Vec::new(),
856    };
857    let mut planned: Vec<(String, Req)> = Vec::new();
858    let mut seen = BTreeSet::new();
859    let mut taken = BTreeSet::new();
860    let mut counts = [0usize; 3];
861    let mut bases = Vec::new();
862    let mut push = |kind: usize, given: Option<String>, req: Req| -> bool {
863        let key = serde_json::to_string(&req).unwrap_or_default();
864        if !seen.insert(key) {
865            return false;
866        }
867        counts[kind] += 1;
868        let prefix = ["example", "input", "trap"][kind];
869        let name = match given.map(|g| app::given_slug(&g)).filter(|g| !g.is_empty()) {
870            Some(g) => g,
871            None => format!("{prefix}-{:03}-{}", counts[kind], case_slug(&req)),
872        };
873        let name = app::reserve_case_name(&mut taken, name, counts[kind]);
874        planned.push((name, req));
875        true
876    };
877    for req in examples {
878        if push(0, None, req.clone()) {
879            bases.push(req);
880        }
881    }
882    for (given, req) in inputs {
883        if push(1, given, req.clone()) {
884            bases.push(req);
885        }
886    }
887    if bases.is_empty() {
888        let root = Req {
889            method: "GET".to_string(),
890            path: "/".to_string(),
891            headers: BTreeMap::new(),
892            body: None,
893        };
894        push(0, None, root.clone());
895        bases.push(root);
896    }
897    if opts.traps {
898        for req in traps(&bases) {
899            push(2, None, req);
900        }
901    }
902    planned.sort_by(|a, b| a.0.cmp(&b.0));
903
904    let timeout = Duration::from_secs(config.timeout_secs);
905    let fixed = config.http.as_ref().and_then(|h| h.port);
906    let reqs: Vec<&Req> = planned.iter().map(|(_, r)| r).collect();
907    let http = config.http.clone().unwrap_or_default();
908    let files = snapshot(repo, &http.fresh)?;
909    let launch = Launch {
910        args: &http.args,
911        files: files.as_deref(),
912        pace: http.pace_ms.map(Duration::from_millis),
913        effects: config.effects.as_ref(),
914    };
915    let one = run_all(
916        &config.run,
917        &launch,
918        repo,
919        fixed.map_or_else(free_port, Ok)?,
920        &reqs,
921        timeout,
922    )?;
923    let two = run_all(
924        &config.run,
925        &launch,
926        repo,
927        fixed.map_or_else(free_port, Ok)?,
928        &reqs,
929        timeout,
930    )?;
931
932    let dir = app::cases_dir(repo).join(HTTP_DIR);
933    std::fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?;
934    let mut outcome = RecordOutcome {
935        dir: dir.clone(),
936        run: config.run.clone(),
937        cases: 0,
938        examples: counts[0],
939        inputs: counts[1],
940        traps: counts[2],
941        noisy: Vec::new(),
942        noise: Vec::new(),
943        unstable: Vec::new(),
944        timed_out: Vec::new(),
945    };
946    for (((name, req), (a, _, fx_a)), (b, _, fx_b)) in planned.iter().zip(one).zip(two) {
947        let (Ok(a), Ok(b)) = (a, b) else {
948            outcome.timed_out.push(name.clone());
949            continue;
950        };
951        let (body, body_noise, binary) = app::settle_text(norm, &a.body, &b.body);
952        let (headers, header_noisy) = settle_headers(norm, &a.headers, &b.headers);
953        write_case(&dir, name, req, a.status, &headers, &body, binary)?;
954        let effects_file = dir.join(format!("{name}.{}", crate::effects::EXT));
955        let _ = std::fs::remove_file(&effects_file);
956        let mut fx_noise = None;
957        if let (Some(fa), Some(fb)) = (&fx_a, &fx_b) {
958            let (fx, noise, _) = app::settle_text(norm, fa, fb);
959            std::fs::write(&effects_file, fx)?;
960            fx_noise = noise;
961        }
962        outcome.cases += 1;
963        if body_noise.is_some() || header_noisy || fx_noise.is_some() {
964            outcome.noisy.push(name.clone());
965        }
966        for (field, kind) in [
967            ("body", body_noise),
968            ("headers", header_noisy.then_some(app::NoiseKind::Values)),
969            (crate::effects::EXT, fx_noise),
970        ] {
971            if let Some(kind) = kind {
972                outcome.noise.push(app::Noise {
973                    case: name.clone(),
974                    field: field.to_string(),
975                    kind,
976                });
977            }
978        }
979        if a.status != b.status || (binary && body_noise.is_some()) {
980            outcome.unstable.push(name.clone());
981        }
982    }
983    Ok(outcome)
984}
985
986struct Spec {
987    name: String,
988    req: Req,
989    status: u16,
990    headers: BTreeMap<String, String>,
991    body: Option<Vec<u8>>,
992    binary: bool,
993    effects: Option<Vec<u8>>,
994}
995
996fn strings(item: Option<&Item>) -> BTreeMap<String, String> {
997    item.and_then(Item::as_table_like)
998        .map(|t| {
999            t.iter()
1000                .map(|(k, v)| (k.to_string(), v.as_str().unwrap_or_default().to_string()))
1001                .collect()
1002        })
1003        .unwrap_or_default()
1004}
1005
1006fn load_spec(dir: &Path, path: &Path) -> Result<Spec> {
1007    let name = path
1008        .file_stem()
1009        .map(|s| s.to_string_lossy().into_owned())
1010        .unwrap_or_default();
1011    let doc: DocumentMut = std::fs::read_to_string(path)
1012        .with_context(|| format!("reading {}", path.display()))?
1013        .parse()
1014        .with_context(|| format!("parsing {}", path.display()))?;
1015    let request = doc.get("request").context("no [request]")?;
1016    let response = doc.get("response").context("no [response]")?;
1017    let body_file = dir.join(format!("{name}.body"));
1018    let effects_file = dir.join(format!("{name}.{}", crate::effects::EXT));
1019    Ok(Spec {
1020        effects: if effects_file.exists() {
1021            Some(std::fs::read(&effects_file)?)
1022        } else {
1023            None
1024        },
1025        req: Req {
1026            method: request
1027                .get("method")
1028                .and_then(Item::as_str)
1029                .unwrap_or("GET")
1030                .to_string(),
1031            path: request
1032                .get("path")
1033                .and_then(Item::as_str)
1034                .with_context(|| format!("{}: no request.path", path.display()))?
1035                .to_string(),
1036            headers: strings(request.get("headers")),
1037            body: request
1038                .get("body")
1039                .and_then(Item::as_str)
1040                .map(str::to_string),
1041        },
1042        status: response
1043            .get("status")
1044            .and_then(Item::as_integer)
1045            .and_then(|s| u16::try_from(s).ok())
1046            .with_context(|| format!("{}: no response.status", path.display()))?,
1047        headers: strings(response.get("headers")),
1048        body: if body_file.exists() {
1049            Some(std::fs::read(&body_file)?)
1050        } else {
1051            None
1052        },
1053        binary: response
1054            .get("binary")
1055            .and_then(Item::as_bool)
1056            .unwrap_or(false),
1057        name,
1058    })
1059}
1060
1061/// The recorded requests, as `METHOD /path` without the query, in case order.
1062pub(crate) fn recorded_routes(repo: &Path) -> Result<Vec<String>> {
1063    let mut seen = BTreeSet::new();
1064    let mut out = Vec::new();
1065    for spec in load_specs(&app::cases_dir(repo).join(HTTP_DIR))? {
1066        let path = spec.req.path.split('?').next().unwrap_or("/").to_string();
1067        let route = format!("{} {path}", spec.req.method);
1068        if seen.insert(route.clone()) {
1069            out.push(route);
1070        }
1071    }
1072    Ok(out)
1073}
1074
1075fn load_specs(dir: &Path) -> Result<Vec<Spec>> {
1076    let mut paths: Vec<PathBuf> = std::fs::read_dir(dir)
1077        .with_context(|| {
1078            format!(
1079                "no HTTP cases in {}: run `rust-anything app record` first",
1080                dir.display()
1081            )
1082        })?
1083        .flatten()
1084        .map(|e| e.path())
1085        .filter(|p| p.is_file() && p.extension().is_some_and(|e| e == "toml"))
1086        .collect();
1087    paths.sort();
1088    let specs = paths
1089        .iter()
1090        .map(|p| load_spec(dir, p))
1091        .collect::<Result<Vec<_>>>()?;
1092    ensure!(!specs.is_empty(), "no HTTP cases in {}", dir.display());
1093    Ok(specs)
1094}
1095
1096pub(crate) fn replay(
1097    repo: &Path,
1098    config: &Config,
1099    norm: &Normalizers,
1100    command: &[String],
1101    port: Option<u16>,
1102    case: Option<&str>,
1103    timeout: Duration,
1104) -> Result<ReplayOutcome> {
1105    let dir = app::cases_dir(repo);
1106    let specs = app::only_case(load_specs(&dir.join(HTTP_DIR))?, case, |s| &s.name)?;
1107    let port = match port.or(config.http.as_ref().and_then(|h| h.port)) {
1108        Some(p) => p,
1109        None => free_port()?,
1110    };
1111    let reqs: Vec<&Req> = specs.iter().map(|s| &s.req).collect();
1112    let files = saved_snapshot(repo, config)?;
1113    let http = config.http.clone().unwrap_or_default();
1114    let launch = Launch {
1115        args: &http.args,
1116        files: files.as_deref(),
1117        pace: http.pace_ms.map(Duration::from_millis),
1118        effects: config.effects.as_ref(),
1119    };
1120    let answers = run_all(command, &launch, repo, port, &reqs, timeout)?;
1121    let mut outcome = ReplayOutcome {
1122        build: command.to_vec(),
1123        passed: 0,
1124        total: 0,
1125        skipped: 0,
1126        failures: Vec::new(),
1127        fallback: None,
1128        report: dir.join(app::REPORT_FILE),
1129    };
1130    let (mut reported, mut fell_back) = (false, Vec::new());
1131    for (spec, (answer, fallback, effects)) in specs.iter().zip(answers) {
1132        outcome.total += 1;
1133        reported |= fallback.is_some();
1134        if fallback == Some(true) {
1135            fell_back.push(spec.name.clone());
1136        }
1137        let mut problems = Vec::new();
1138        match answer {
1139            Err(e) => problems.push(Problem {
1140                field: "response".to_string(),
1141                detail: format!("no response: {e}\n"),
1142            }),
1143            Ok(resp) => {
1144                if resp.status != spec.status {
1145                    problems.push(Problem {
1146                        field: "status".to_string(),
1147                        detail: format!("expected {}, got {}\n", spec.status, resp.status),
1148                    });
1149                }
1150                for (k, expected) in &spec.headers {
1151                    let field = format!("header {k}");
1152                    let key = k.to_ascii_lowercase();
1153                    match resp.headers.get(&key) {
1154                        None => problems.push(Problem {
1155                            field,
1156                            detail: format!("- {expected}\n(missing)\n"),
1157                        }),
1158                        Some(actual) => {
1159                            let (e, a) = (norm.apply(expected), norm.apply(actual));
1160                            if !app::line_matches(&e, &a) {
1161                                problems.push(Problem {
1162                                    field,
1163                                    detail: format!("- {e}\n+ {a}\n"),
1164                                });
1165                            }
1166                        }
1167                    }
1168                }
1169                if let Some(expected) = &spec.body
1170                    && let Some(detail) = app::compare(
1171                        norm,
1172                        expected,
1173                        &resp.body,
1174                        spec.binary,
1175                        norm.unordered(&spec.name, "body"),
1176                    )
1177                {
1178                    problems.push(Problem {
1179                        field: "body".to_string(),
1180                        detail,
1181                    });
1182                }
1183            }
1184        }
1185        if let Some(expected) = &spec.effects
1186            && let Some(detail) = app::compare(
1187                norm,
1188                expected,
1189                effects.as_deref().unwrap_or_default(),
1190                false,
1191                norm.unordered(&spec.name, crate::effects::EXT),
1192            )
1193        {
1194            problems.push(Problem {
1195                field: crate::effects::EXT.to_string(),
1196                detail,
1197            });
1198        }
1199        if problems.is_empty() {
1200            outcome.passed += 1;
1201        } else {
1202            outcome.failures.push(Failure {
1203                case: spec.name.clone(),
1204                args: vec![spec.req.method.clone(), spec.req.path.clone()],
1205                problems,
1206            });
1207        }
1208    }
1209    if reported {
1210        outcome.fallback = Some(Fallback {
1211            cases: fell_back.len(),
1212            total: outcome.total,
1213            rate: fell_back.len() as f64 / outcome.total.max(1) as f64,
1214            names: fell_back,
1215        });
1216    }
1217    std::fs::write(&outcome.report, app::report_markdown(&outcome))
1218        .with_context(|| format!("writing {}", outcome.report.display()))?;
1219    Ok(outcome)
1220}
1221
1222#[cfg(test)]
1223mod tests {
1224    use super::*;
1225
1226    #[test]
1227    fn curl_lines_become_requests() {
1228        let here = Path::new(".");
1229        let r = parse_curl(
1230            "curl -sS -X POST -H 'Content-Type: text/plain' -d 'hello world' http://localhost:8080/upper?x=1",
1231            here,
1232            here,
1233        )
1234        .unwrap();
1235        assert_eq!(r.method, "POST");
1236        assert_eq!(r.path, "/upper?x=1");
1237        assert_eq!(r.body.as_deref(), Some("hello world"));
1238        assert_eq!(r.headers["Content-Type"], "text/plain");
1239        let g = parse_curl("curl 127.0.0.1:3000", here, here).unwrap();
1240        assert_eq!((g.method.as_str(), g.path.as_str()), ("GET", "/"));
1241        let form = parse_curl("curl -d a=1 http://[::1]:80/f", here, here).unwrap();
1242        assert_eq!(form.method, "POST");
1243        assert_eq!(
1244            form.headers["Content-Type"],
1245            "application/x-www-form-urlencoded"
1246        );
1247        assert!(parse_curl("curl https://example.com/x", here, here).is_none());
1248        let query = parse_curl("curl 'http://localhost?x=y#section'", here, here).unwrap();
1249        assert_eq!(query.path, "/?x=y");
1250        let fragment = parse_curl("curl 'http://[::1]:8080/path#section'", here, here).unwrap();
1251        assert_eq!(fragment.path, "/path");
1252        assert!(parse_curl("curl ftp://localhost/file", here, here).is_none());
1253        assert!(parse_curl("curl --unknown x http://localhost/", here, here).is_none());
1254        assert!(parse_curl("curl http://localhost/ | jq .", here, here).is_none());
1255    }
1256
1257    #[test]
1258    fn curl_data_and_binary_file_inputs_match_curl_file_semantics() {
1259        let root = app::temp_dir("curl-data").unwrap();
1260        std::fs::write(root.join("body.txt"), b"one\r\ntwo\0\nthree").unwrap();
1261        let body = |flag| {
1262            parse_curl(
1263                &format!("curl {flag} @body.txt http://localhost/upper"),
1264                &root,
1265                &root,
1266            )
1267            .unwrap()
1268            .body
1269            .unwrap()
1270        };
1271        let data = body("--data");
1272        let binary = body("--data-binary");
1273        std::fs::remove_dir_all(root).unwrap();
1274        assert_eq!(data, "onetwothree");
1275        assert_eq!(binary, "one\r\ntwo\0\nthree");
1276    }
1277
1278    #[test]
1279    fn informational_responses_do_not_replace_the_final_response() {
1280        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";
1281        let response = read_response(&mut &raw[..], false).unwrap();
1282        assert_eq!(response.status, 201);
1283        assert_eq!(response.body, b"ok");
1284        assert!(!response.headers.contains_key("link"));
1285
1286        let switching = b"HTTP/1.1 101 Switching Protocols\r\n\r\n";
1287        assert_eq!(
1288            read_response(&mut &switching[..], false).unwrap().status,
1289            101
1290        );
1291    }
1292
1293    #[test]
1294    fn responses_parse_with_length_chunks_or_close() {
1295        let fixed =
1296            b"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 5\r\n\r\nhelloEXTRA";
1297        let r = read_response(&mut &fixed[..], false).unwrap();
1298        assert_eq!((r.status, r.body.as_slice()), (200, &b"hello"[..]));
1299        assert_eq!(r.headers["content-type"], "text/plain");
1300        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";
1301        let r = read_response(&mut &chunked[..], false).unwrap();
1302        assert_eq!((r.status, r.body.as_slice()), (404, &b"not found"[..]));
1303        let close = b"HTTP/1.0 500 Oops\r\n\r\nbye";
1304        assert_eq!(read_response(&mut &close[..], false).unwrap().body, b"bye");
1305    }
1306
1307    #[test]
1308    fn malformed_http_chunks_are_errors() {
1309        let mut bad_ending = &b"1\r\naXX0\r\n\r\n"[..];
1310        assert!(read_chunked(&mut bad_ending, Vec::new()).is_err());
1311        let max = format!("{:x}\r\n", usize::MAX);
1312        assert!(read_chunked(&mut max.as_bytes(), Vec::new()).is_err());
1313        let mut truncated = &b"1\r\na\r\n0\r\n"[..];
1314        assert!(read_chunked(&mut truncated, Vec::new()).is_err());
1315        let mut trailers = &b"1\r\na\r\n0\r\nX-Trailer: present\r\n\r\n"[..];
1316        assert_eq!(read_chunked(&mut trailers, Vec::new()).unwrap(), b"a");
1317    }
1318
1319    #[test]
1320    fn fixed_body_rejects_malformed_lengths_and_accepts_equal_duplicates() {
1321        let response = |lengths| {
1322            let msg = format!("HTTP/1.1 200 OK\r\n{lengths}\r\n\r\nabc trailing");
1323            read_response(&mut msg.as_bytes(), false)
1324        };
1325        assert!(response("Content-Length: invalid").is_err());
1326        assert!(response("Content-Length: 3\r\nContent-Length: 4").is_err());
1327        let matching = response("Content-Length: 3\r\nContent-Length: 03").unwrap();
1328        assert_eq!(matching.body, b"abc");
1329    }
1330
1331    #[test]
1332    fn interrupted_close_delimited_body_is_an_error() {
1333        struct BrokenBody;
1334
1335        impl Read for BrokenBody {
1336            fn read(&mut self, _: &mut [u8]) -> std::io::Result<usize> {
1337                Err(std::io::ErrorKind::TimedOut.into())
1338            }
1339        }
1340
1341        let response = &b"HTTP/1.0 200 OK\r\n\r\npartial"[..];
1342        assert!(read_response(&mut response.chain(BrokenBody), false).is_err());
1343    }
1344
1345    #[test]
1346    fn traps_change_path_segments_queries_and_bodies() {
1347        let base = Req {
1348            method: "POST".into(),
1349            path: "/div/7/2?name=bob".into(),
1350            headers: BTreeMap::new(),
1351            body: Some("{\"a\":1}".into()),
1352        };
1353        let t = traps(&[base]);
1354        assert!(t.iter().any(|r| r.path == "/div/-7/2?name=bob"));
1355        assert!(t.iter().any(|r| r.path == "/div/7/0?name=bob"));
1356        assert!(
1357            t.iter()
1358                .any(|r| r.path == "/div/7/2?name=%F0%9F%91%8D%F0%9F%8F%BD%20thumbs")
1359        );
1360        assert!(
1361            t.iter()
1362                .all(|r| r.path.starts_with("/div/") || r.path == "/rust-anything-missing")
1363        );
1364        assert!(
1365            t.iter()
1366                .any(|r| r.body.as_deref() == Some(app::JSON_TRAPS[0]))
1367        );
1368        assert_eq!(percent_decode("a%20b%zz"), "a b%zz");
1369    }
1370}