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