Skip to main content

mockforge_bench/conformance/
self_test.rs

1//! Positive + per-category negative request driver against a live server.
2//!
3//! Issue #79 round 13 (4) — Srikanth's (e) ask: a way to test both
4//! positive and negative compliance scenarios separately, where the
5//! positive cases should pass and the negative cases should be
6//! rejected.
7//!
8//! This module sits *alongside* the existing conformance executor
9//! (which drives k6 / native checks on a single positive call per
10//! operation). The self-test driver synthesises per-category
11//! deliberately-bad requests and asserts that the server actually
12//! rejects them with a 4xx — useful when verifying that
13//! `validate_request_with_all` is wired correctly for the user's spec
14//! (the exact gap that round-13 (3) fixed).
15//!
16//! Scope of the initial MVP: covers the highest-signal negatives —
17//! empty body when one is required, missing required query/header
18//! params, and wrong-type path params. Doesn't try to mutate every
19//! field of a JSON-Schema-validated body; that's a follow-up.
20
21use super::spec_driven::{AnnotatedOperation, ApiKeyLocation, SecuritySchemeInfo};
22use reqwest::{Client, Method};
23use std::collections::BTreeMap;
24use std::net::IpAddr;
25use std::sync::atomic::{AtomicUsize, Ordering};
26use std::sync::{Arc, Mutex};
27use std::time::Duration;
28
29/// Round 23 (c-iii) — per-direction body cap when capturing
30/// request/response payloads to `conformance-self-test-requests.jsonl`.
31/// 16 KiB keeps a 1000-case run under ~32 MB even if every payload
32/// fills the cap, while still preserving enough of a typical JSON body
33/// (or a stack-trace error response) to debug from.
34const CAPTURE_BODY_CAP_BYTES: usize = 16 * 1024;
35
36/// Round 17.2 — cap on schema-driven negatives per operation. A spec
37/// with 100 properties per body could produce hundreds of mutations
38/// for a single operation; combined with thousands of operations
39/// that's a runaway test matrix. 12 covers the highest-signal
40/// mutations (type mismatch + required-removed + a few constraint
41/// breaks) without exploding wall time on large specs.
42const SCHEMA_MUTATION_CAP: usize = 12;
43
44/// Round 25 (k) — content-type swap probes. For operations declaring a
45/// JSON request body, each entry below produces one probe that lies
46/// about Content-Type while keeping the JSON payload. A spec-compliant
47/// server should respond 415 (or 400). Order matches the order
48/// Srikanth listed in his round-23 reply: XML, YAML, multipart, and
49/// the URL-encoded variant he added in round 24.
50const CONTENT_TYPE_SWAP_VARIANTS: &[(&str, &str)] = &[
51    ("application/xml", "request-body:content-type-mismatch:xml"),
52    ("application/yaml", "request-body:content-type-mismatch:yaml"),
53    ("multipart/form-data", "request-body:content-type-mismatch:multipart"),
54    (
55        "application/x-www-form-urlencoded",
56        "request-body:content-type-mismatch:urlencoded",
57    ),
58];
59
60/// Round 27 (k variant b) — embedded content payloads. Content-Type
61/// stays `application/json` and the envelope IS valid JSON; we just
62/// stuff a non-JSON snippet into a string field's value. The test
63/// surfaces servers that try to parse string field contents (e.g.
64/// XML-EE expanders, YAML loaders, urlencoded parsers) and crash on
65/// the payload — a 5xx here is the finding. Label, payload pairs:
66const EMBEDDED_CONTENT_VARIANTS: &[(&str, &str)] = &[
67    ("request-body:embedded-content:xml", "<root><cmd>execute()</cmd></root>"),
68    ("request-body:embedded-content:yaml", "key: value\n- item1\n- item2"),
69    (
70        "request-body:embedded-content:multipart",
71        "--boundary\r\nContent-Disposition: form-data; name=\"x\"\r\n\r\nval\r\n--boundary--",
72    ),
73    ("request-body:embedded-content:urlencoded", "a=1&b=2&c=hello%20world"),
74];
75
76/// Configuration for a self-test run.
77#[derive(Debug, Clone)]
78pub struct SelfTestConfig {
79    pub target_url: String,
80    pub skip_tls_verify: bool,
81    pub timeout: Duration,
82    /// Optional extra headers to attach to every request (e.g. auth).
83    pub extra_headers: Vec<(String, String)>,
84    /// Delay between requests to avoid hammering the server.
85    pub delay_between_requests: Duration,
86    /// Round 18.1 — base path to prepend to every spec path. When the
87    /// spec declares `/users` and the deployed API is served under
88    /// `/api`, `--base-path /api` should make the self-test hit
89    /// `https://target/api/users` instead of `https://target/users`.
90    /// Pre-fix this was ignored entirely and every operation 404'd
91    /// (Srikanth's vCenter run on 0.3.152: 1275 positives, 1275 4xx).
92    pub base_path: Option<String>,
93    /// Round 18.5 — local source IPs to bind outgoing requests to.
94    /// Each IP must already be assigned to an interface on the host.
95    /// Operations round-robin through the resulting client pool.
96    pub source_ips: Vec<IpAddr>,
97    /// Round 18.5 — fake source IPs to advertise via forwarded-IP
98    /// headers (used to exercise GEODB lookup at the destination).
99    /// Rotated per operation.
100    pub geo_source_ips: Vec<IpAddr>,
101    /// Which forwarded-IP header(s) to populate when `geo_source_ips`
102    /// is non-empty. Empty → no-op; default below sets the standard
103    /// three-header set.
104    pub geo_source_headers: Vec<String>,
105    /// Round 23 (c-iii) — when `Some`, every probe captures method, URL,
106    /// request headers/body and response status/headers/body into this
107    /// sink. Caller drains it after `run_self_test` and writes
108    /// `conformance-self-test-requests.jsonl`. None → no capture (zero
109    /// extra allocations on the hot path).
110    pub capture: Option<Arc<Mutex<Vec<CaseCapture>>>>,
111    /// Round 25 — when true, validate every probe's response body
112    /// against the spec's response schema for the actual status
113    /// returned (closes round 21.3 / Srikanth's a2 / a3 ask). The
114    /// validation result lands in `CaseCapture::response_schema_error`
115    /// (None → matched, or no schema for that status). Default false:
116    /// JSON-Schema validation of large response bodies adds wall-clock
117    /// time and the user has to opt in.
118    pub validate_response_schemas: bool,
119}
120
121/// Round 23 (c-iii) — one captured request/response pair, one per
122/// probe (positive or negative). Serialised as a JSON line in
123/// `conformance-self-test-requests.jsonl`. Headers are kept as
124/// `BTreeMap` for stable ordering. Bodies are truncated to
125/// `CAPTURE_BODY_CAP_BYTES`; `*_truncated` flags whether more was
126/// dropped.
127#[derive(Debug, Clone, serde::Serialize)]
128pub struct CaseCapture {
129    pub label: String,
130    pub method: String,
131    pub url: String,
132    pub request_headers: BTreeMap<String, String>,
133    pub request_body: Option<String>,
134    pub request_body_truncated: bool,
135    pub response_status: u16,
136    pub response_headers: BTreeMap<String, String>,
137    pub response_body: Option<String>,
138    pub response_body_truncated: bool,
139    pub error: Option<String>,
140    /// Round 25 — when `validate_response_schemas` is on and the spec
141    /// declares a schema for `response_status`, this carries the
142    /// validation message (or None when the body matched, or no schema
143    /// was declared for that status). Serialised verbatim in the JSONL
144    /// and rendered in the HTML viewer.
145    #[serde(default, skip_serializing_if = "Option::is_none")]
146    pub response_schema_error: Option<String>,
147    /// Round 28 — Srikanth's "Is it possible to put expected response
148    /// code status in both jsonl and jsonl report" ask. Human-readable
149    /// expected status range: `"2xx-3xx"` for positive probes,
150    /// `"4xx"` for negatives. Lets users `jq` for misses
151    /// (`.response_status as $s | .expected_status_range == "4xx"
152    /// and ($s < 400 or $s >= 500)`) and powers the HTML viewer's
153    /// "show mismatches only" filter.
154    #[serde(default)]
155    pub expected_status_range: String,
156}
157
158impl Default for SelfTestConfig {
159    fn default() -> Self {
160        Self {
161            target_url: "http://localhost:3000".into(),
162            skip_tls_verify: false,
163            timeout: Duration::from_secs(15),
164            extra_headers: Vec::new(),
165            delay_between_requests: Duration::from_millis(0),
166            base_path: None,
167            source_ips: Vec::new(),
168            geo_source_ips: Vec::new(),
169            geo_source_headers: default_geo_source_headers(),
170            capture: None,
171            validate_response_schemas: false,
172        }
173    }
174}
175
176/// Truncate `body` to `CAPTURE_BODY_CAP_BYTES` on a UTF-8 boundary,
177/// returning the trimmed string and whether truncation occurred. Used
178/// for both request and response bodies in the capture sink.
179fn truncate_body_for_capture(body: &str) -> (String, bool) {
180    if body.len() <= CAPTURE_BODY_CAP_BYTES {
181        return (body.to_string(), false);
182    }
183    let mut end = CAPTURE_BODY_CAP_BYTES;
184    while end > 0 && !body.is_char_boundary(end) {
185        end -= 1;
186    }
187    (body[..end].to_string(), true)
188}
189
190/// Default forwarded-IP header set. Covers the three conventions a
191/// real GEODB front-end is likely to read in this order of
192/// preference: Cloudflare (`CF-Connecting-IP`), Akamai/CloudFront
193/// (`True-Client-IP`), then the de-facto standard
194/// `X-Forwarded-For`. Override via `--geo-source-header` to test a
195/// specific stack.
196pub fn default_geo_source_headers() -> Vec<String> {
197    vec![
198        "X-Forwarded-For".to_string(),
199        "True-Client-IP".to_string(),
200        "CF-Connecting-IP".to_string(),
201    ]
202}
203
204/// Outcome of a single test case (positive or negative).
205#[derive(Debug, Clone, serde::Serialize)]
206pub struct CaseOutcome {
207    pub label: String,
208    pub expected_4xx: bool,
209    pub actual_status: u16,
210    /// True when the response status matches expectation
211    /// (positive → 2xx-3xx, negative → 4xx).
212    pub passed: bool,
213}
214
215/// All cases run against one annotated operation.
216#[derive(Debug, Clone, serde::Serialize)]
217pub struct OperationResult {
218    pub method: String,
219    pub path: String,
220    pub positive: Option<CaseOutcome>,
221    pub negatives: Vec<CaseOutcome>,
222}
223
224/// Summary report rolled up across all operations.
225#[derive(Debug, Default, Clone, serde::Serialize)]
226pub struct SelfTestReport {
227    pub positive_pass: usize,
228    pub positive_fail: usize,
229    /// Per category: count of negative cases the server correctly
230    /// rejected with a 4xx (we caught the spec violation).
231    pub negative_caught: BTreeMap<String, usize>,
232    /// Per category: count of negative cases that should have been
233    /// rejected but came back with a non-4xx (validator gap).
234    pub negative_missed: BTreeMap<String, usize>,
235    pub operations: Vec<OperationResult>,
236}
237
238impl SelfTestReport {
239    /// All-pass means every positive case got 2xx-3xx and every
240    /// negative case got 4xx.
241    pub fn all_passed(&self) -> bool {
242        self.positive_fail == 0 && self.negative_missed.values().sum::<usize>() == 0
243    }
244
245    /// Round 18.1 — detect the "self-test target is misconfigured"
246    /// case where every positive failed with the *same* status code.
247    /// The classic example: `--base-path /api` was forgotten so every
248    /// request hits a path the server doesn't know and returns 404.
249    /// Pre-warning, the user saw all-green negative buckets (because
250    /// "missing route" 404s look like "validator rejected") and no
251    /// indication that the run was meaningless. Returns Some(status)
252    /// when ≥10 positives all failed with the same status, else None.
253    pub fn detect_target_misconfiguration(&self) -> Option<u16> {
254        if self.positive_pass > 0 || self.positive_fail < 10 {
255            return None;
256        }
257        let mut seen: Option<u16> = None;
258        for op in &self.operations {
259            let Some(p) = &op.positive else {
260                continue;
261            };
262            if p.passed {
263                return None;
264            }
265            match seen {
266                None => seen = Some(p.actual_status),
267                Some(s) if s != p.actual_status => return None,
268                _ => {}
269            }
270        }
271        seen
272    }
273
274    /// Human-readable summary string. One line for positives, one per
275    /// category for negatives. Designed to slot into existing
276    /// `TerminalReporter` output.
277    pub fn render_summary(&self) -> String {
278        let mut out = String::new();
279        out.push_str(&format!(
280            "Positives: {} pass / {} fail\n",
281            self.positive_pass, self.positive_fail
282        ));
283        let mut keys: Vec<&String> =
284            self.negative_caught.keys().chain(self.negative_missed.keys()).collect();
285        keys.sort();
286        keys.dedup();
287        for cat in keys {
288            let caught = self.negative_caught.get(cat).copied().unwrap_or(0);
289            let missed = self.negative_missed.get(cat).copied().unwrap_or(0);
290            let mark = if missed == 0 { "✓" } else { "⚠" };
291            out.push_str(&format!(
292                "Negatives [{}]: {} caught / {} missed  {}\n",
293                cat, caught, missed, mark
294            ));
295        }
296        out
297    }
298}
299
300/// Execute the self-test plan against `config.target_url` for every
301/// `AnnotatedOperation`. Returns the aggregated report; callers
302/// decide how to display it (e.g. via `render_summary` or by writing
303/// the JSON serialisation to disk).
304pub async fn run_self_test(
305    operations: &[AnnotatedOperation],
306    config: &SelfTestConfig,
307) -> Result<SelfTestReport, reqwest::Error> {
308    // Round 18.5 — build a client pool when `source_ips` is set,
309    // one reqwest::Client per IP, each bound to its local address.
310    // Operations round-robin through the pool. Empty pool → single
311    // default client (the pre-18.5 behaviour).
312    let clients = build_client_pool(config)?;
313    let client_cursor = AtomicUsize::new(0);
314    let geo_cursor = AtomicUsize::new(0);
315
316    let mut report = SelfTestReport::default();
317    for op in operations {
318        let client_idx = client_cursor.fetch_add(1, Ordering::Relaxed) % clients.len();
319        let client = &clients[client_idx];
320        let geo_ip = if config.geo_source_ips.is_empty() {
321            None
322        } else {
323            let idx = geo_cursor.fetch_add(1, Ordering::Relaxed) % config.geo_source_ips.len();
324            Some(config.geo_source_ips[idx])
325        };
326        let result = test_operation(client, config, op, geo_ip).await;
327        if let Some(p) = &result.positive {
328            if p.passed {
329                report.positive_pass += 1;
330            } else {
331                report.positive_fail += 1;
332            }
333        }
334        for neg in &result.negatives {
335            let cat = neg.label.split(':').next().unwrap_or("other").to_string();
336            if neg.passed {
337                *report.negative_caught.entry(cat).or_insert(0) += 1;
338            } else {
339                *report.negative_missed.entry(cat).or_insert(0) += 1;
340            }
341        }
342        report.operations.push(result);
343        if !config.delay_between_requests.is_zero() {
344            tokio::time::sleep(config.delay_between_requests).await;
345        }
346    }
347    Ok(report)
348}
349
350/// Round 18.5 — append GEODB forwarded-IP headers to the
351/// operation's declared headers. Returns the original vec untouched
352/// when `geo_ip` is None or `geo_headers` is empty.
353///
354/// If the operation already declares one of the geo headers (rare
355/// but legal), we keep the operation's value — the caller's spec
356/// wins.
357fn effective_op_headers(
358    base: &[(String, String)],
359    geo_ip: Option<IpAddr>,
360    geo_headers: &[String],
361) -> Vec<(String, String)> {
362    let mut out = base.to_vec();
363    let Some(ip) = geo_ip else {
364        return out;
365    };
366    let value = ip.to_string();
367    for h in geo_headers {
368        // Case-insensitive duplicate check: don't override the
369        // spec's own declared value for the header.
370        if out.iter().any(|(k, _)| k.eq_ignore_ascii_case(h)) {
371            continue;
372        }
373        out.push((h.clone(), value.clone()));
374    }
375    out
376}
377
378/// Round 18.5 — build a pool of reqwest clients, one per declared
379/// source IP. Empty `source_ips` → a single default client.
380///
381/// The OS must already have each `source_ip` assigned to an
382/// interface; reqwest's `.local_address()` issues a `bind()` syscall
383/// at connect time, so an IP the kernel doesn't recognise surfaces
384/// as `EADDRNOTAVAIL` at request time, not at builder time.
385fn build_client_pool(config: &SelfTestConfig) -> Result<Vec<Client>, reqwest::Error> {
386    let make = |bind: Option<IpAddr>| -> Result<Client, reqwest::Error> {
387        let mut builder = Client::builder().timeout(config.timeout);
388        if config.skip_tls_verify {
389            builder = builder.danger_accept_invalid_certs(true);
390        }
391        if let Some(addr) = bind {
392            builder = builder.local_address(addr);
393        }
394        builder.build()
395    };
396    if config.source_ips.is_empty() {
397        Ok(vec![make(None)?])
398    } else {
399        config.source_ips.iter().map(|ip| make(Some(*ip))).collect()
400    }
401}
402
403async fn test_operation(
404    client: &Client,
405    config: &SelfTestConfig,
406    op: &AnnotatedOperation,
407    geo_ip: Option<IpAddr>,
408) -> OperationResult {
409    // Round 25 — track the sink length BEFORE we run any probes for
410    // this operation, so that after the probes finish we can mutate
411    // exactly the entries that belong to this op (the capture sink is
412    // shared but `run_self_test` iterates operations sequentially).
413    // Used by the response-schema validation pass below.
414    let sink_start = config.capture.as_ref().and_then(|s| s.lock().ok().map(|g| g.len()));
415
416    let url = build_url_with_base(
417        &config.target_url,
418        config.base_path.as_deref(),
419        &op.path,
420        &op.path_params,
421    );
422    let method = Method::from_bytes(op.method.to_uppercase().as_bytes()).unwrap_or(Method::GET);
423
424    // Round 18.5 — pre-compute the operation's effective headers
425    // with the geo source IP baked in. Doing it once here keeps the
426    // per-case `send_case` calls below unchanged. When `geo_ip` is
427    // None the result equals `op.header_params`.
428    let op_headers = effective_op_headers(&op.header_params, geo_ip, &config.geo_source_headers);
429
430    // ── Positive case ────────────────────────────────────────────
431    let positive = send_case(
432        client,
433        config,
434        method.clone(),
435        &url,
436        "positive",
437        false,
438        op.sample_body.as_deref(),
439        op.query_params.clone(),
440        op_headers.clone(),
441    )
442    .await;
443
444    // ── Negative cases ───────────────────────────────────────────
445    let mut negatives = Vec::new();
446
447    // (a) empty body when one is required.
448    //
449    // Round 16 — drop the `sample_body.is_some()` precondition. Operations
450    // whose body annotator couldn't synthesize a sample previously got
451    // zero negatives (so the self-test reported "all passing" even on
452    // POST /resource with a required body). The spec saying the operation
453    // *has* a request body is enough — an empty object is a valid
454    // negative regardless of whether we have a positive sample.
455    if op.request_body_content_type.is_some() {
456        negatives.push(
457            send_case(
458                client,
459                config,
460                method.clone(),
461                &url,
462                "request-body:empty",
463                true,
464                Some("{}"),
465                op.query_params.clone(),
466                op_headers.clone(),
467            )
468            .await,
469        );
470
471        // (b) wrong-shaped body (array instead of object) — exercises
472        // top-level type validation independently of which fields are
473        // required.
474        negatives.push(
475            send_case(
476                client,
477                config,
478                method.clone(),
479                &url,
480                "request-body:wrong-type",
481                true,
482                Some("[]"),
483                op.query_params.clone(),
484                op_headers.clone(),
485            )
486            .await,
487        );
488
489        // Round 25 (k) — content-type swap probes.
490        //
491        // For operations declaring `application/json` request bodies, send
492        // the SAME json payload (or a synthesised one) under four other
493        // content types: `application/xml`, `application/yaml`,
494        // `multipart/form-data`, `application/x-www-form-urlencoded`.
495        // The spec says the endpoint accepts only JSON, so a strict server
496        // should respond 415 Unsupported Media Type (or 400 if it tries
497        // to parse and fails). A 2xx means the server is accepting
498        // payloads outside its declared content negotiation, which is the
499        // failure mode behind a lot of "we crashed on a malformed XML
500        // upload" incidents.
501        //
502        // Variant (a) of Srikanth's round-23 g ask: lie about the
503        // Content-Type header. The body shape is honest JSON; only the
504        // header is swapped. Variant (b) (JSON envelope with embedded
505        // non-JSON field values) is deferred to round 26 because it
506        // requires a schema-aware field walker.
507        if op
508            .request_body_content_type
509            .as_deref()
510            .map(|ct| ct.contains("json"))
511            .unwrap_or(false)
512        {
513            let payload = op.sample_body.as_deref().unwrap_or("{}");
514            for (ct, label) in CONTENT_TYPE_SWAP_VARIANTS {
515                negatives.push(
516                    send_case_with_extra(
517                        client,
518                        config,
519                        method.clone(),
520                        &url,
521                        label,
522                        true,
523                        Some(payload),
524                        op.query_params.clone(),
525                        // Strip any Content-Type already on the operation
526                        // headers (the spec's positive value) so the
527                        // probe's value is the only one the server sees.
528                        op_headers
529                            .iter()
530                            .filter(|(k, _)| !k.eq_ignore_ascii_case("content-type"))
531                            .cloned()
532                            .collect(),
533                        // The wrong Content-Type rides on `extra_headers`
534                        // so it lands AFTER `send_case_with_extra`'s
535                        // unconditional `application/json` insertion in
536                        // request-body mode. Actually `send_case_with_extra`
537                        // only sets Content-Type when a body is present
538                        // AND there's no manual override; passing the
539                        // override here wins because reqwest preserves
540                        // the last-set header value.
541                        vec![("Content-Type".to_string(), (*ct).to_string())],
542                    )
543                    .await,
544                );
545            }
546
547            // Round 27 (k variant b) — embedded non-JSON content
548            // inside a valid JSON envelope. Content-Type stays
549            // application/json (honest) and the body parses as JSON;
550            // only the string-valued payload changes. We expect 2xx-3xx
551            // because the envelope is spec-shape, so the probe surfaces
552            // servers that crash (5xx) trying to parse the embedded
553            // snippet as XML/YAML/etc. A 4xx is also a finding because
554            // it usually means the server's pattern/format validator
555            // tripped on the payload contents, but the user can decide
556            // from the JSONL whether that's a bug or correct narrow-
557            // string-field behaviour.
558            for (label, snippet) in EMBEDDED_CONTENT_VARIANTS {
559                let payload = op.sample_body.as_deref().unwrap_or("{}");
560                let body = embed_payload_in_first_string_field(payload, snippet);
561                negatives.push(
562                    send_case(
563                        client,
564                        config,
565                        method.clone(),
566                        &url,
567                        label,
568                        // expected_4xx=false: any non-2xx is a probe
569                        // failure. 5xx in particular is "server panicked
570                        // on the embedded content".
571                        false,
572                        Some(&body),
573                        op.query_params.clone(),
574                        op_headers.clone(),
575                    )
576                    .await,
577                );
578            }
579        }
580
581        // Round 17.2 — schema-aware negatives.
582        //
583        // When both a positive sample AND the resolved body schema are
584        // available, mutate the sample per-field (type mismatch,
585        // min/max bounds, pattern, enum out-of-range, required-field
586        // removal) and assert each is rejected with 4xx. Capped at
587        // SCHEMA_MUTATION_CAP per operation so a 100-property body
588        // doesn't explode the test matrix.
589        if let (Some(sample_str), Some(schema)) =
590            (op.sample_body.as_deref(), op.request_body_schema.as_ref())
591        {
592            if let Ok(sample) = serde_json::from_str::<serde_json::Value>(sample_str) {
593                let mutations = super::schema_mutator::mutate_body(&sample, schema);
594                for m in mutations.into_iter().take(SCHEMA_MUTATION_CAP) {
595                    let body_str = serde_json::to_string(&m.body).unwrap_or_default();
596                    negatives.push(
597                        send_case(
598                            client,
599                            config,
600                            method.clone(),
601                            &url,
602                            &m.label,
603                            true,
604                            Some(&body_str),
605                            op.query_params.clone(),
606                            // Round 24 (f) — was `op.header_params`, which
607                            // skipped the geo-IP header. Use `op_headers`
608                            // so the geo IP rides with the negative probe
609                            // too (positive vs negative coverage must be
610                            // symmetric, otherwise a GEODB front-end sees
611                            // the rotating IP only on positives).
612                            op_headers.clone(),
613                        )
614                        .await,
615                    );
616                }
617            }
618        }
619    }
620
621    // Round 17.2 — URI-length probe. Spec-agnostic but schema-aware in
622    // spirit: most servers cap URIs at 8 KB or so. Append a 9 KB query
623    // string to the URL and expect 414 URI Too Long (or 400). Skipped
624    // for operations that already have a heavy positive query.
625    {
626        let pad = "p=".to_string() + &"x".repeat(9_000);
627        let bad_url = if url.contains('?') {
628            format!("{url}&{pad}")
629        } else {
630            format!("{url}?{pad}")
631        };
632        negatives.push(
633            send_case(
634                client,
635                config,
636                method.clone(),
637                &bad_url,
638                "parameters:uri-too-long",
639                true,
640                op.sample_body.as_deref(),
641                op.query_params.clone(),
642                // Round 24 (f) — see schema-mutation note above. Use
643                // `op_headers` (carries geo IP) instead of bare
644                // `op.header_params`.
645                op_headers.clone(),
646            )
647            .await,
648        );
649    }
650
651    // (e) Round 16 — path-param type probe. Send the first path
652    // parameter as a literal `"self-test-invalid-id"`: a string that
653    // contains hyphens, won't parse as an integer, won't parse as a
654    // UUID, and won't match any typical regex pattern. Operations
655    // whose spec types the param as `integer` or `string` with a
656    // `format`/`pattern` will catch this (caught: server returned
657    // 4xx); operations whose spec lets path params be free-form
658    // strings will let it through (missed: server returned 2xx).
659    // Either outcome is informative: a category that's all "missed"
660    // tells the user their spec is loose on path-param types, which
661    // is itself worth knowing. Addresses Srikanth's "always all
662    // passing" report — operations with a path param now produce at
663    // least one probe instead of zero.
664    if !op.path_params.is_empty() {
665        let mut url_with_placeholder = op.path.clone();
666        if let Some((first_name, _)) = op.path_params.first() {
667            // Substitute every other path-param with its sample so the
668            // route shape stays intact and only the first param is bad.
669            for (name, value) in op.path_params.iter().skip(1) {
670                if !value.is_empty() {
671                    url_with_placeholder =
672                        url_with_placeholder.replace(&format!("{{{name}}}"), value);
673                }
674            }
675            // Substitute the first param with a guaranteed-invalid
676            // sentinel that's unlikely to match any reasonable schema:
677            // contains characters disallowed in numeric IDs *and* UUIDs.
678            url_with_placeholder =
679                url_with_placeholder.replace(&format!("{{{first_name}}}"), "self-test-invalid-id");
680            // Round 18.1 — honour `base_path` here too, otherwise the
681            // probe URL differs from the positive case and the
682            // resulting 404 is misattributed to "bad path param".
683            let bad_url = build_url_with_base(
684                &config.target_url,
685                config.base_path.as_deref(),
686                &url_with_placeholder,
687                &[],
688            );
689            negatives.push(
690                send_case(
691                    client,
692                    config,
693                    method.clone(),
694                    &bad_url,
695                    "parameters:bad-path-param",
696                    true,
697                    op.sample_body.as_deref(),
698                    op.query_params.clone(),
699                    op_headers.clone(),
700                )
701                .await,
702            );
703        }
704    }
705
706    // (c) drop the first required query param
707    if !op.query_params.is_empty() {
708        let mut q = op.query_params.clone();
709        q.remove(0);
710        negatives.push(
711            send_case(
712                client,
713                config,
714                method.clone(),
715                &url,
716                "parameters:missing-query",
717                true,
718                op.sample_body.as_deref(),
719                q,
720                op_headers.clone(),
721            )
722            .await,
723        );
724    }
725
726    // (s) Round 17.3 — security probes.
727    //
728    // Operations whose spec declares a security requirement get a
729    // dedicated set of negatives. The point isn't to test whether the
730    // server's *real* auth works (the positive case already does that
731    // via `extra_headers`) — it's to check whether deliberately-bad
732    // credentials are still rejected, which is exactly the failure
733    // mode that lets an attacker through a half-wired validator.
734    //
735    // Each probe replaces or omits the relevant auth credential and
736    // expects 401 / 403. A 2xx here is a hard finding: "spec says
737    // this endpoint is protected, server let unauthenticated /
738    // wrong-credential traffic through".
739    //
740    // Bounded: at most one probe per declared scheme kind, so an
741    // operation with 3 security requirements doesn't 4× the request
742    // volume. Skips entirely when `op.security_schemes` is empty.
743    for probe in build_security_probes(&op.security_schemes) {
744        // Strip any pre-existing Authorization or known API-key
745        // header from extra_headers + header_params so the probe
746        // value is the *only* credential the server sees.
747        let stripped_extra = strip_auth(&config.extra_headers, &op.security_schemes);
748        let stripped_headers = strip_auth(&op.header_params, &op.security_schemes);
749        let stripped_query = strip_auth_query(&op.query_params, &op.security_schemes);
750        let mut req_headers = stripped_headers;
751        for (k, v) in &probe.headers {
752            req_headers.push((k.clone(), v.clone()));
753        }
754        // Round 24 (f) — security probes build req_headers from
755        // `op.header_params` directly (we need the stripped-auth
756        // variant), so the geo-IP header doesn't ride along
757        // automatically. Append it here so a GEODB / WAF in front
758        // of the auth layer still sees the rotating source IP.
759        if let Some(ip) = geo_ip {
760            let ip_str = ip.to_string();
761            for h in &config.geo_source_headers {
762                let already = req_headers.iter().any(|(k, _)| k.eq_ignore_ascii_case(h));
763                if !already {
764                    req_headers.push((h.clone(), ip_str.clone()));
765                }
766            }
767        }
768        let mut req_query = stripped_query;
769        for (k, v) in &probe.query {
770            req_query.push((k.clone(), v.clone()));
771        }
772        negatives.push(
773            send_case_with_extra(
774                client,
775                config,
776                method.clone(),
777                &url,
778                &probe.label,
779                true,
780                op.sample_body.as_deref(),
781                req_query,
782                req_headers,
783                stripped_extra,
784            )
785            .await,
786        );
787    }
788
789    // (d) drop the first required header
790    if !op.header_params.is_empty() {
791        // Round 24 (f) — start from `op_headers` (so the geo IP rides
792        // along) and only strip the first OPERATION-declared header.
793        // Slicing past `op.header_params.len()` would otherwise risk
794        // dropping the geo header itself; `op_headers` is built as
795        // `op.header_params ++ geo` so index 0 is always operational.
796        let mut h = op_headers.clone();
797        if !h.is_empty() {
798            h.remove(0);
799        }
800        negatives.push(
801            send_case(
802                client,
803                config,
804                method.clone(),
805                &url,
806                "parameters:missing-header",
807                true,
808                op.sample_body.as_deref(),
809                op.query_params.clone(),
810                h,
811            )
812            .await,
813        );
814    }
815
816    // (w) Round 17.5 — OWASP/WAF unification.
817    //
818    // Pull one canonical payload per OWASP category from the existing
819    // `SecurityPayloads` library and emit an injection probe per
820    // category. Targets in priority order: (1) substitute the first
821    // query param's value, (2) substitute the first string field of
822    // the positive JSON body, (3) skip if neither is available.
823    //
824    // Label format `owasp:<category>`, so the existing
825    // `negative_caught` / `negative_missed` rollup groups all OWASP
826    // findings under one `owasp` bucket. Expected 4xx (server should
827    // reject malicious input). A 5xx is a hard finding (server
828    // crashed on the payload); a 2xx is a soft finding (input passed
829    // through unfiltered — may or may not be a real vuln).
830    //
831    // Bounded: at most one probe per category (7 categories total).
832    // Skips the operation entirely if no injection target is
833    // available — open GET endpoints with no params get zero OWASP
834    // probes, no false signal.
835    for probe in build_owasp_probes(op) {
836        negatives.push(
837            send_case(
838                client,
839                config,
840                method.clone(),
841                &url,
842                &probe.label,
843                true,
844                probe.body.as_deref(),
845                probe.query,
846                // Round 24 (f) — OWASP injection probes must also
847                // carry the geo IP, otherwise a WAF / GEODB rule
848                // tuned to a specific source IP would silently let
849                // them through.
850                op_headers.clone(),
851            )
852            .await,
853        );
854    }
855
856    // Round 25 — response-body shape validation pass. For each capture
857    // this op pushed onto the sink, look up the spec's schema for the
858    // actual response status and validate. Result lands in
859    // `response_schema_error` (Some(message) on failure, None on
860    // pass or no-schema-for-this-status). Runs only when the user
861    // opted in AND capture is on (we need the body).
862    if config.validate_response_schemas {
863        if let (Some(sink), Some(start)) = (config.capture.as_ref(), sink_start) {
864            if !op.response_schemas.is_empty() {
865                if let Ok(mut guard) = sink.lock() {
866                    let end = guard.len();
867                    for i in start..end {
868                        let Some(entry) = guard.get_mut(i) else {
869                            continue;
870                        };
871                        let Some(body) = entry.response_body.as_deref() else {
872                            continue;
873                        };
874                        let Some(schema) = op.response_schemas.get(&entry.response_status) else {
875                            continue;
876                        };
877                        entry.response_schema_error = validate_body_against_schema(body, schema);
878                    }
879                }
880            }
881        }
882    }
883
884    OperationResult {
885        method: op.method.clone(),
886        path: op.path.clone(),
887        positive: Some(positive),
888        negatives,
889    }
890}
891
892/// Round 25 — validate a JSON body string against an OpenAPI response
893/// schema (already converted to a `serde_json::Value`). Returns
894/// `Some(message)` describing the first violation, or `None` on a
895/// clean pass / non-JSON body / schema-build failure (in which case
896/// the absence of an error means "we didn't have anything to compare
897/// against", not "passed"; the caller-side semantics treat absence as
898/// success because that's what the user sees as silence).
899/// Round 27 (k variant b) — return a JSON body string identical to
900/// `sample` except that the first string-valued leaf has been
901/// replaced with `snippet`. Walks objects depth-first and stops at
902/// the first string. If `sample` is not parseable JSON, or has no
903/// string fields, falls back to wrapping the snippet under a `data`
904/// key so the probe still has a body to send: `{"data": <snippet>}`.
905/// The result is always valid JSON ready for `application/json`.
906fn embed_payload_in_first_string_field(sample: &str, snippet: &str) -> String {
907    let mut parsed: serde_json::Value = match serde_json::from_str(sample) {
908        Ok(v) => v,
909        Err(_) => return format!(r#"{{"data":{}}}"#, json_quote(snippet)),
910    };
911    if !replace_first_string(&mut parsed, snippet) {
912        return format!(r#"{{"data":{}}}"#, json_quote(snippet));
913    }
914    serde_json::to_string(&parsed)
915        .unwrap_or_else(|_| format!(r#"{{"data":{}}}"#, json_quote(snippet)))
916}
917
918/// Helper for `embed_payload_in_first_string_field`: recursively
919/// walk the value and replace the FIRST string leaf encountered.
920/// Returns true when a replacement happened. Honors document order
921/// for objects (BTreeMap-backed `serde_json::Map` iterates in
922/// insertion order) so the choice of which field to mutate is
923/// stable across runs.
924fn replace_first_string(v: &mut serde_json::Value, snippet: &str) -> bool {
925    match v {
926        serde_json::Value::String(s) => {
927            *s = snippet.to_string();
928            true
929        }
930        serde_json::Value::Object(map) => {
931            for (_k, child) in map.iter_mut() {
932                if replace_first_string(child, snippet) {
933                    return true;
934                }
935            }
936            false
937        }
938        serde_json::Value::Array(arr) => {
939            for child in arr.iter_mut() {
940                if replace_first_string(child, snippet) {
941                    return true;
942                }
943            }
944            false
945        }
946        _ => false,
947    }
948}
949
950/// Helper for `embed_payload_in_first_string_field`'s fallback: take
951/// an arbitrary string and quote it for embedding inside a JSON
952/// literal. `serde_json::to_string(&value)` handles escaping
953/// correctly for unicode + control chars + quotes.
954fn json_quote(s: &str) -> String {
955    serde_json::to_string(s).unwrap_or_else(|_| "\"\"".to_string())
956}
957
958fn validate_body_against_schema(body: &str, schema: &serde_json::Value) -> Option<String> {
959    let parsed: serde_json::Value = serde_json::from_str(body).ok()?;
960    let validator = jsonschema::validator_for(schema).ok()?;
961    let mut errors = validator.iter_errors(&parsed);
962    let first = errors.next()?;
963    // Round 28 — Srikanth on 0.3.170 wanted the message to show the
964    // actual expected schema alongside the kind label so it reads as
965    // "expected schema {...} but got <kind>". We emit a compact JSON
966    // serialisation of the schema as a suffix; the kind label still
967    // names what went wrong in plain English for quick scanning.
968    // Round 26 — Srikanth on 0.3.169: the prior `format!("{:?}", first.kind)
969    // .split('(').next()` produced "Type { kind: Single" (broken Rust
970    // syntax, mismatched braces). Switch to the human-readable mapping
971    // already used in executor.rs: handle the common kinds (Type,
972    // Required, AdditionalProperties, Enum, MinLength, MaxLength,
973    // Minimum, Maximum, Pattern) explicitly; fall back to the
974    // jsonschema crate's Display impl on the error (which produces
975    // something like "{...} is not of type \"string\"") for the long
976    // tail. Combined with `at <instance-path>` for the field location.
977    let path = first.instance_path.to_string();
978    let path = if path.is_empty() { "/" } else { path.as_str() };
979    let kind_msg: String = match &first.kind {
980        jsonschema::error::ValidationErrorKind::Type { kind } => {
981            // `kind` is `TypeKind::Single(JsonType)` or
982            // `TypeKind::Multiple(JsonTypeSet)`. `JsonType` has its
983            // own `Display` impl ("string", "object", etc.).
984            match kind {
985                jsonschema::error::TypeKind::Single(t) => format!("expected type {t}"),
986                jsonschema::error::TypeKind::Multiple(_) => "expected one of multiple types".into(),
987            }
988        }
989        jsonschema::error::ValidationErrorKind::Required { property } => {
990            format!("required field missing: {property}")
991        }
992        jsonschema::error::ValidationErrorKind::AdditionalProperties { unexpected } => {
993            format!("unexpected additional properties: {unexpected:?}")
994        }
995        jsonschema::error::ValidationErrorKind::Enum { options } => {
996            format!("value not in allowed enum: {options}")
997        }
998        jsonschema::error::ValidationErrorKind::MinLength { limit } => {
999            format!("string shorter than min length ({limit})")
1000        }
1001        jsonschema::error::ValidationErrorKind::MaxLength { limit } => {
1002            format!("string longer than max length ({limit})")
1003        }
1004        jsonschema::error::ValidationErrorKind::Minimum { limit } => {
1005            format!("value below minimum ({limit})")
1006        }
1007        jsonschema::error::ValidationErrorKind::Maximum { limit } => {
1008            format!("value above maximum ({limit})")
1009        }
1010        jsonschema::error::ValidationErrorKind::Pattern { pattern } => {
1011            format!("value did not match pattern {pattern}")
1012        }
1013        // Long tail: lean on jsonschema's Display impl, which is the
1014        // built-in human-readable error message ("X is not of type Y").
1015        // Strip trailing newlines so the JSONL line stays one line.
1016        _ => first.to_string().trim().to_string(),
1017    };
1018    let schema_str = serde_json::to_string(schema).unwrap_or_else(|_| "<schema>".into());
1019    let schema_str = if schema_str.len() > 300 {
1020        format!("{}...", &schema_str[..300])
1021    } else {
1022        schema_str
1023    };
1024    Some(format!("at {path}: {kind_msg}; expected schema {schema_str}"))
1025}
1026
1027/// Round 17.5 — one OWASP injection probe to send.
1028#[derive(Debug, Clone)]
1029struct OwaspProbe {
1030    label: String,
1031    body: Option<String>,
1032    query: Vec<(String, String)>,
1033}
1034
1035/// Build one OWASP probe per `SecurityCategory` for `op`. Targets the
1036/// first query param if any, else the first string field of the
1037/// positive JSON body. Returns empty if neither target is available.
1038fn build_owasp_probes(op: &AnnotatedOperation) -> Vec<OwaspProbe> {
1039    use crate::security_payloads::{SecurityCategory, SecurityPayloads};
1040
1041    let categories = [
1042        SecurityCategory::SqlInjection,
1043        SecurityCategory::Xss,
1044        SecurityCategory::CommandInjection,
1045        SecurityCategory::PathTraversal,
1046        SecurityCategory::Ssti,
1047        SecurityCategory::LdapInjection,
1048        SecurityCategory::Xxe,
1049    ];
1050
1051    // Pick an injection target ONCE per operation; reuse it across
1052    // categories. (A single op gets up to 7 probes — one per category
1053    // — all attacking the same field.)
1054    let injection_target = pick_injection_target(op);
1055    let Some(target) = injection_target else {
1056        return Vec::new();
1057    };
1058
1059    let mut probes = Vec::new();
1060    for cat in categories {
1061        // Take the *first* payload from each category. The
1062        // collection's first entry is the canonical low-risk
1063        // representative; later entries include time-based / blind
1064        // probes that aren't useful as a one-shot rejection test.
1065        let Some(payload) = SecurityPayloads::get_by_category(cat).into_iter().next() else {
1066            continue;
1067        };
1068        let mut query = op.query_params.clone();
1069        let mut body = op.sample_body.clone();
1070        match &target {
1071            InjectionTarget::Query(idx) => {
1072                if let Some(slot) = query.get_mut(*idx) {
1073                    slot.1 = payload.payload.clone();
1074                }
1075            }
1076            InjectionTarget::BodyStringField(field) => {
1077                body = inject_into_body_field(body.as_deref(), field, &payload.payload);
1078            }
1079        }
1080        probes.push(OwaspProbe {
1081            label: format!("owasp:{}", cat),
1082            body,
1083            query,
1084        });
1085    }
1086    probes
1087}
1088
1089#[derive(Debug, Clone)]
1090enum InjectionTarget {
1091    Query(usize),
1092    BodyStringField(String),
1093}
1094
1095fn pick_injection_target(op: &AnnotatedOperation) -> Option<InjectionTarget> {
1096    if !op.query_params.is_empty() {
1097        return Some(InjectionTarget::Query(0));
1098    }
1099    let sample = op.sample_body.as_deref()?;
1100    let parsed: serde_json::Value = serde_json::from_str(sample).ok()?;
1101    let obj = parsed.as_object()?;
1102    for (k, v) in obj {
1103        if v.is_string() {
1104            return Some(InjectionTarget::BodyStringField(k.clone()));
1105        }
1106    }
1107    None
1108}
1109
1110/// Replace the value of `field` in a JSON-object body with `payload`.
1111/// Returns the mutated body as a JSON string. Returns `None` if the
1112/// body doesn't parse as a JSON object.
1113fn inject_into_body_field(body: Option<&str>, field: &str, payload: &str) -> Option<String> {
1114    let raw = body?;
1115    let mut parsed: serde_json::Value = serde_json::from_str(raw).ok()?;
1116    let obj = parsed.as_object_mut()?;
1117    obj.insert(field.to_string(), serde_json::json!(payload));
1118    serde_json::to_string(&parsed).ok()
1119}
1120
1121#[allow(clippy::too_many_arguments)]
1122/// Round 17.3 — one synthesised bad credential to send.
1123#[derive(Debug, Clone)]
1124struct SecurityProbe {
1125    /// Self-test label, e.g. `security:bad-bearer`.
1126    label: String,
1127    /// Headers to attach to the probe request.
1128    headers: Vec<(String, String)>,
1129    /// Query parameters to attach (API key in query case).
1130    query: Vec<(String, String)>,
1131}
1132
1133/// For each declared security scheme, produce one bad-credential
1134/// probe plus a single "no auth at all" probe that exercises the
1135/// missing-credential code path. Deduplicates by scheme kind so an
1136/// operation declaring `[bearer, bearer]` only yields one Bearer
1137/// probe.
1138fn build_security_probes(schemes: &[SecuritySchemeInfo]) -> Vec<SecurityProbe> {
1139    if schemes.is_empty() {
1140        return Vec::new();
1141    }
1142    let mut probes: Vec<SecurityProbe> = Vec::new();
1143    let mut seen_bearer = false;
1144    let mut seen_basic = false;
1145    // `(loc_tag, name)` — ApiKeyLocation doesn't implement Ord, so
1146    // we tag it with a short discriminant string for dedup.
1147    let mut seen_apikey: std::collections::BTreeSet<(&'static str, String)> = Default::default();
1148    for s in schemes {
1149        match s {
1150            SecuritySchemeInfo::Bearer if !seen_bearer => {
1151                seen_bearer = true;
1152                probes.push(SecurityProbe {
1153                    label: "security:bad-bearer".into(),
1154                    headers: vec![(
1155                        "Authorization".into(),
1156                        "Bearer self-test-invalid-token".into(),
1157                    )],
1158                    query: Vec::new(),
1159                });
1160            }
1161            SecuritySchemeInfo::Basic if !seen_basic => {
1162                seen_basic = true;
1163                // base64("self-test:invalid") — valid base64, wrong creds.
1164                probes.push(SecurityProbe {
1165                    label: "security:bad-basic".into(),
1166                    headers: vec![(
1167                        "Authorization".into(),
1168                        "Basic c2VsZi10ZXN0OmludmFsaWQ=".into(),
1169                    )],
1170                    query: Vec::new(),
1171                });
1172            }
1173            SecuritySchemeInfo::ApiKey { location, name } => {
1174                let loc_tag = match location {
1175                    ApiKeyLocation::Header => "header",
1176                    ApiKeyLocation::Query => "query",
1177                    ApiKeyLocation::Cookie => "cookie",
1178                };
1179                if seen_apikey.contains(&(loc_tag, name.clone())) {
1180                    continue;
1181                }
1182                seen_apikey.insert((loc_tag, name.clone()));
1183                let label = format!("security:bad-apikey:{}", name);
1184                let bad = "self-test-invalid-key".to_string();
1185                match location {
1186                    ApiKeyLocation::Header => probes.push(SecurityProbe {
1187                        label,
1188                        headers: vec![(name.clone(), bad)],
1189                        query: Vec::new(),
1190                    }),
1191                    ApiKeyLocation::Query => probes.push(SecurityProbe {
1192                        label,
1193                        headers: Vec::new(),
1194                        query: vec![(name.clone(), bad)],
1195                    }),
1196                    ApiKeyLocation::Cookie => probes.push(SecurityProbe {
1197                        label,
1198                        headers: vec![("Cookie".into(), format!("{}={}", name, bad))],
1199                        query: Vec::new(),
1200                    }),
1201                }
1202            }
1203            _ => {}
1204        }
1205    }
1206    // Always add a "no auth at all" probe when *any* security scheme
1207    // is declared — useful even if all schemes failed to resolve to a
1208    // testable kind, because it surfaces validators that aren't
1209    // checking auth presence at all.
1210    probes.push(SecurityProbe {
1211        label: "security:no-auth".into(),
1212        headers: Vec::new(),
1213        query: Vec::new(),
1214    });
1215    probes
1216}
1217
1218/// Remove Authorization and any API-key headers declared by the
1219/// operation's security schemes from `headers`, so a security probe
1220/// can supply its own credential (or none) cleanly.
1221fn strip_auth(
1222    headers: &[(String, String)],
1223    schemes: &[SecuritySchemeInfo],
1224) -> Vec<(String, String)> {
1225    let mut apikey_headers: std::collections::BTreeSet<String> = Default::default();
1226    for s in schemes {
1227        if let SecuritySchemeInfo::ApiKey {
1228            location: ApiKeyLocation::Header,
1229            name,
1230        } = s
1231        {
1232            apikey_headers.insert(name.to_lowercase());
1233        }
1234        if let SecuritySchemeInfo::ApiKey {
1235            location: ApiKeyLocation::Cookie,
1236            ..
1237        } = s
1238        {
1239            apikey_headers.insert("cookie".into());
1240        }
1241    }
1242    headers
1243        .iter()
1244        .filter(|(k, _)| {
1245            let lk = k.to_lowercase();
1246            lk != "authorization" && !apikey_headers.contains(&lk)
1247        })
1248        .cloned()
1249        .collect()
1250}
1251
1252/// Remove API-key query parameters declared by the operation's
1253/// security schemes from `query`, so a probe can supply its own.
1254fn strip_auth_query(
1255    query: &[(String, String)],
1256    schemes: &[SecuritySchemeInfo],
1257) -> Vec<(String, String)> {
1258    let mut apikey_query: std::collections::BTreeSet<String> = Default::default();
1259    for s in schemes {
1260        if let SecuritySchemeInfo::ApiKey {
1261            location: ApiKeyLocation::Query,
1262            name,
1263        } = s
1264        {
1265            apikey_query.insert(name.clone());
1266        }
1267    }
1268    query.iter().filter(|(k, _)| !apikey_query.contains(k)).cloned().collect()
1269}
1270
1271/// Variant of `send_case` that takes an explicit `extra_headers`
1272/// (rather than reading them from `config`). Used by security probes
1273/// to substitute or strip the configured Authorization header.
1274#[allow(clippy::too_many_arguments)]
1275async fn send_case_with_extra(
1276    client: &Client,
1277    config: &SelfTestConfig,
1278    method: Method,
1279    url: &str,
1280    label: &str,
1281    expected_4xx: bool,
1282    body: Option<&str>,
1283    query: Vec<(String, String)>,
1284    headers: Vec<(String, String)>,
1285    extra_headers: Vec<(String, String)>,
1286) -> CaseOutcome {
1287    let mut req = client.request(method.clone(), url);
1288    let mut capture_headers: BTreeMap<String, String> = BTreeMap::new();
1289    for (k, v) in &query {
1290        req = req.query(&[(k.as_str(), v.as_str())]);
1291    }
1292    // Round 28 — reqwest's `.header(k, v)` APPENDS rather than replaces
1293    // (.headers().insert() would replace but isn't on the builder).
1294    // The previous round-25 fix relied on "last-write-wins" semantics
1295    // that don't exist; for content-type-swap probes the request went
1296    // out with BOTH `Content-Type: application/json` AND `Content-Type:
1297    // application/xml`, and axum's `Json<>` extractor picked the JSON
1298    // one and accepted, so the server-side validator never saw the
1299    // mismatch. Build a `HeaderMap` ourselves so the override
1300    // replaces the body-block default exactly once.
1301    let mut final_headers: reqwest::header::HeaderMap = reqwest::header::HeaderMap::new();
1302    if let Some(_b) = body {
1303        if let Ok(v) = reqwest::header::HeaderValue::from_str("application/json") {
1304            final_headers.insert(reqwest::header::CONTENT_TYPE, v);
1305        }
1306        capture_headers.insert("Content-Type".to_string(), "application/json".to_string());
1307    }
1308    for (k, v) in &headers {
1309        if let (Ok(hn), Ok(hv)) = (
1310            reqwest::header::HeaderName::from_bytes(k.as_bytes()),
1311            reqwest::header::HeaderValue::from_str(v),
1312        ) {
1313            final_headers.insert(hn, hv);
1314        }
1315        capture_headers.insert(k.clone(), v.clone());
1316    }
1317    for (k, v) in &extra_headers {
1318        if let (Ok(hn), Ok(hv)) = (
1319            reqwest::header::HeaderName::from_bytes(k.as_bytes()),
1320            reqwest::header::HeaderValue::from_str(v),
1321        ) {
1322            final_headers.insert(hn, hv);
1323        }
1324        capture_headers.insert(k.clone(), v.clone());
1325    }
1326    if let Some(b) = body {
1327        req = req.body(b.to_string());
1328    }
1329    req = req.headers(final_headers);
1330    let (actual_status, response_capture) = match req.send().await {
1331        Ok(resp) => {
1332            let status = resp.status().as_u16();
1333            if let Some(sink) = &config.capture {
1334                let resp_headers: BTreeMap<String, String> = resp
1335                    .headers()
1336                    .iter()
1337                    .map(|(k, v)| (k.as_str().to_string(), v.to_str().unwrap_or("").to_string()))
1338                    .collect();
1339                let text = resp.text().await.unwrap_or_default();
1340                let (rb, truncated) = truncate_body_for_capture(&text);
1341                (status, Some((Some((rb, truncated)), resp_headers, None, sink.clone())))
1342            } else {
1343                (status, None)
1344            }
1345        }
1346        Err(e) => {
1347            let err_str = e.to_string();
1348            if let Some(sink) = &config.capture {
1349                (0, Some((None, BTreeMap::new(), Some(err_str), sink.clone())))
1350            } else {
1351                (0, None)
1352            }
1353        }
1354    };
1355    let passed = if expected_4xx {
1356        (400..500).contains(&actual_status)
1357    } else {
1358        (200..400).contains(&actual_status)
1359    };
1360    if let Some((resp_body, resp_headers, error, sink)) = response_capture {
1361        let (request_body, request_body_truncated) = match body {
1362            Some(b) => {
1363                let (rb, t) = truncate_body_for_capture(b);
1364                (Some(rb), t)
1365            }
1366            None => (None, false),
1367        };
1368        let (response_body, response_body_truncated) = match resp_body {
1369            Some((rb, t)) => (Some(rb), t),
1370            None => (None, false),
1371        };
1372        let entry = CaseCapture {
1373            label: label.to_string(),
1374            method: method.to_string(),
1375            url: build_query_url(url, &query),
1376            request_headers: capture_headers,
1377            request_body,
1378            request_body_truncated,
1379            response_status: actual_status,
1380            response_headers: resp_headers,
1381            response_body,
1382            response_body_truncated,
1383            error,
1384            // Filled in by the per-operation validation pass after
1385            // every probe finishes; the capture itself is unaware of
1386            // the schema map.
1387            response_schema_error: None,
1388            // Round 28 — derive the expected range from the probe's
1389            // `expected_4xx` flag so the JSONL line and HTML viewer
1390            // can show mismatches without re-deriving on the read side.
1391            expected_status_range: if expected_4xx {
1392                "4xx".into()
1393            } else {
1394                "2xx-3xx".into()
1395            },
1396        };
1397        if let Ok(mut guard) = sink.lock() {
1398            guard.push(entry);
1399        }
1400    }
1401    CaseOutcome {
1402        label: label.to_string(),
1403        expected_4xx,
1404        actual_status,
1405        passed,
1406    }
1407}
1408
1409// HTTP request shape needs all of these: client, config (for capture
1410// sink + extra headers), method, url, label (probe id), expected_4xx
1411// (pass/fail decision), body, query, headers. A struct wrapper would
1412// just move the arity from positional to field access without making
1413// the call sites clearer.
1414#[allow(clippy::too_many_arguments)]
1415async fn send_case(
1416    client: &Client,
1417    config: &SelfTestConfig,
1418    method: Method,
1419    url: &str,
1420    label: &str,
1421    expected_4xx: bool,
1422    body: Option<&str>,
1423    query: Vec<(String, String)>,
1424    headers: Vec<(String, String)>,
1425) -> CaseOutcome {
1426    // Forwarding to `send_case_with_extra` keeps the capture logic in
1427    // one place so request/response tracing can't drift between the
1428    // two entrypoints.
1429    send_case_with_extra(
1430        client,
1431        config,
1432        method,
1433        url,
1434        label,
1435        expected_4xx,
1436        body,
1437        query,
1438        headers,
1439        config.extra_headers.clone(),
1440    )
1441    .await
1442}
1443
1444/// Round 23 (c-iii) — rebuild the query-stringified URL for capture so
1445/// the JSONL trace shows the URL that actually went over the wire
1446/// (reqwest applies `.query(..)` after the request URL string is
1447/// rendered, so capturing the raw `url` argument alone loses the
1448/// query params).
1449fn build_query_url(base: &str, query: &[(String, String)]) -> String {
1450    if query.is_empty() {
1451        return base.to_string();
1452    }
1453    let qs: String = query
1454        .iter()
1455        .map(|(k, v)| format!("{}={}", urlencoding::encode(k), urlencoding::encode(v)))
1456        .collect::<Vec<_>>()
1457        .join("&");
1458    if base.contains('?') {
1459        format!("{base}&{qs}")
1460    } else {
1461        format!("{base}?{qs}")
1462    }
1463}
1464
1465/// Substitute `{param}` placeholders in the spec path with their
1466/// sample values from `path_params`, then prepend `target_url`. Empty
1467/// values are kept as `{param}` so an upstream router still matches
1468/// the template — useful when `path_params` is empty and we want to
1469/// hit the same route the spec defines.
1470///
1471/// All current call sites went through `build_url_with_base` after
1472/// round 18.1, so this no-base-path helper is unused; keep it as the
1473/// documented shim for future external callers (one-arg simplification).
1474#[allow(dead_code)]
1475fn build_url(target: &str, path_template: &str, path_params: &[(String, String)]) -> String {
1476    build_url_with_base(target, None, path_template, path_params)
1477}
1478
1479/// Round 18.1 — variant of `build_url` that takes a `base_path`
1480/// (e.g. `Some("/api")`). When set, prepends it to the spec path so a
1481/// spec declaring `/users` against a target served behind `/api`
1482/// resolves to `<target>/api/users`. `base_path` is normalised: leading
1483/// `/` is auto-added, trailing `/` is stripped.
1484fn build_url_with_base(
1485    target: &str,
1486    base_path: Option<&str>,
1487    path_template: &str,
1488    path_params: &[(String, String)],
1489) -> String {
1490    let mut url = path_template.to_string();
1491    for (name, value) in path_params {
1492        let placeholder = format!("{{{}}}", name);
1493        if !value.is_empty() {
1494            url = url.replace(&placeholder, value);
1495        }
1496    }
1497    let target = target.trim_end_matches('/');
1498    let prefix = match base_path {
1499        Some(bp) if !bp.is_empty() => {
1500            let trimmed = bp.trim_end_matches('/');
1501            if trimmed.starts_with('/') {
1502                trimmed.to_string()
1503            } else {
1504                format!("/{}", trimmed)
1505            }
1506        }
1507        _ => String::new(),
1508    };
1509    let path = if url.starts_with('/') {
1510        url
1511    } else {
1512        format!("/{url}")
1513    };
1514    format!("{target}{prefix}{path}")
1515}
1516
1517#[cfg(test)]
1518mod tests {
1519    use super::*;
1520
1521    fn op(
1522        method: &str,
1523        path: &str,
1524        body: Option<&str>,
1525        query: Vec<(&str, &str)>,
1526        headers: Vec<(&str, &str)>,
1527        path_params: Vec<(&str, &str)>,
1528    ) -> AnnotatedOperation {
1529        AnnotatedOperation {
1530            method: method.into(),
1531            path: path.into(),
1532            features: Vec::new(),
1533            request_body_content_type: body.map(|_| "application/json".into()),
1534            sample_body: body.map(|s| s.to_string()),
1535            query_params: query.into_iter().map(|(a, b)| (a.into(), b.into())).collect(),
1536            header_params: headers.into_iter().map(|(a, b)| (a.into(), b.into())).collect(),
1537            path_params: path_params.into_iter().map(|(a, b)| (a.into(), b.into())).collect(),
1538            response_schema: None,
1539            response_schemas: std::collections::BTreeMap::new(),
1540            request_body_schema: None,
1541            security_schemes: Vec::new(),
1542        }
1543    }
1544
1545    #[test]
1546    fn build_url_substitutes_path_params() {
1547        let url = build_url(
1548            "https://api.test/",
1549            "/users/{id}/posts/{pid}",
1550            &[("id".into(), "42".into()), ("pid".into(), "7".into())],
1551        );
1552        assert_eq!(url, "https://api.test/users/42/posts/7");
1553    }
1554
1555    /// Round 18.1 — a run where every positive 404s should be flagged
1556    /// as a likely target misconfiguration, not silently treated as a
1557    /// successful conformance run.
1558    #[test]
1559    fn detect_target_misconfiguration_when_all_positives_share_status() {
1560        let mut report = SelfTestReport {
1561            positive_pass: 0,
1562            positive_fail: 50,
1563            ..Default::default()
1564        };
1565        for i in 0..50 {
1566            report.operations.push(OperationResult {
1567                method: "GET".into(),
1568                path: format!("/r/{i}"),
1569                positive: Some(CaseOutcome {
1570                    label: "positive".into(),
1571                    expected_4xx: false,
1572                    actual_status: 404,
1573                    passed: false,
1574                }),
1575                negatives: Vec::new(),
1576            });
1577        }
1578        assert_eq!(report.detect_target_misconfiguration(), Some(404));
1579    }
1580
1581    #[test]
1582    fn detect_target_misconfiguration_returns_none_when_some_pass() {
1583        let mut report = SelfTestReport {
1584            positive_pass: 5,
1585            positive_fail: 50,
1586            ..Default::default()
1587        };
1588        for i in 0..55 {
1589            report.operations.push(OperationResult {
1590                method: "GET".into(),
1591                path: format!("/r/{i}"),
1592                positive: Some(CaseOutcome {
1593                    label: "positive".into(),
1594                    expected_4xx: false,
1595                    actual_status: if i < 5 { 200 } else { 404 },
1596                    passed: i < 5,
1597                }),
1598                negatives: Vec::new(),
1599            });
1600        }
1601        assert_eq!(report.detect_target_misconfiguration(), None);
1602    }
1603
1604    /// Round 18.1 — `--base-path /api` should prepend `/api` to
1605    /// every spec path. Pre-fix, the self-test ignored base_path and
1606    /// 404'd every positive when the deployed API was behind a path
1607    /// prefix.
1608    #[test]
1609    fn build_url_applies_base_path_when_present() {
1610        let url = build_url_with_base(
1611            "https://api.example.com",
1612            Some("/api"),
1613            "/users/{id}",
1614            &[("id".into(), "42".into())],
1615        );
1616        assert_eq!(url, "https://api.example.com/api/users/42");
1617    }
1618
1619    /// Round 18.1 — base_path is normalised: missing leading slash
1620    /// gets one added, trailing slash is stripped, empty string is
1621    /// the same as None.
1622    #[test]
1623    fn build_url_normalises_base_path() {
1624        let no_slash = build_url_with_base("https://t", Some("api"), "/x", &[]);
1625        assert_eq!(no_slash, "https://t/api/x");
1626        let trailing = build_url_with_base("https://t", Some("/api/"), "/x", &[]);
1627        assert_eq!(trailing, "https://t/api/x");
1628        let empty = build_url_with_base("https://t", Some(""), "/x", &[]);
1629        assert_eq!(empty, "https://t/x");
1630        let none = build_url_with_base("https://t", None, "/x", &[]);
1631        assert_eq!(none, "https://t/x");
1632    }
1633
1634    #[test]
1635    fn build_url_keeps_placeholders_when_no_sample() {
1636        let url = build_url("https://api.test", "/users/{id}", &[]);
1637        assert_eq!(url, "https://api.test/users/{id}");
1638    }
1639
1640    #[test]
1641    fn report_summary_calls_out_misses() {
1642        let r = SelfTestReport {
1643            positive_pass: 3,
1644            positive_fail: 0,
1645            negative_caught: BTreeMap::from([("request-body".into(), 2)]),
1646            negative_missed: BTreeMap::from([("request-body".into(), 1)]),
1647            operations: Vec::new(),
1648        };
1649        let summary = r.render_summary();
1650        assert!(summary.contains("Positives: 3 pass / 0 fail"));
1651        assert!(summary.contains("Negatives [request-body]: 2 caught / 1 missed"));
1652        assert!(summary.contains("⚠"));
1653        assert!(!r.all_passed());
1654    }
1655
1656    #[test]
1657    fn report_all_passed_when_no_miss() {
1658        let r = SelfTestReport {
1659            positive_pass: 5,
1660            positive_fail: 0,
1661            negative_caught: BTreeMap::from([("parameters".into(), 3)]),
1662            negative_missed: BTreeMap::new(),
1663            operations: Vec::new(),
1664        };
1665        assert!(r.all_passed());
1666        assert!(r.render_summary().contains("✓"));
1667    }
1668
1669    #[tokio::test]
1670    async fn run_self_test_against_unreachable_target_marks_all_failed() {
1671        // Use an obviously-dead port so we exercise the timeout/error
1672        // path without needing a live server in tests.
1673        let cfg = SelfTestConfig {
1674            target_url: "http://127.0.0.1:1".into(),
1675            timeout: Duration::from_millis(200),
1676            ..Default::default()
1677        };
1678        let ops = vec![op(
1679            "POST",
1680            "/users",
1681            Some("{\"name\":\"a\"}"),
1682            vec![],
1683            vec![],
1684            vec![],
1685        )];
1686        let report = run_self_test(&ops, &cfg).await.expect("client builds");
1687        // All cases hit the connect-error path → actual_status=0.
1688        // Positive expects 2xx-3xx → 0 is fail. Negatives expect 4xx
1689        // → 0 is also fail (we missed catching).
1690        assert_eq!(report.positive_fail, 1);
1691        assert!(report.negative_missed.values().sum::<usize>() >= 1);
1692        assert!(!report.all_passed());
1693    }
1694
1695    /// Round 17.2 — operations with both a positive sample AND a
1696    /// resolved request-body schema produce schema-driven negatives
1697    /// in addition to the spec-agnostic empty/wrong-type ones. The
1698    /// labels carry the field path so a per-category report can tell
1699    /// you exactly which field caught.
1700    #[tokio::test]
1701    async fn schema_driven_negatives_fire_when_schema_present() {
1702        use openapiv3::{ObjectType, ReferenceOr, Schema, SchemaData, SchemaKind, Type};
1703        let cfg = SelfTestConfig {
1704            target_url: "http://127.0.0.1:1".into(),
1705            timeout: Duration::from_millis(200),
1706            ..Default::default()
1707        };
1708        // Build an operation whose schema has a required `name` string
1709        // and an `age` integer. The mutator should produce, at
1710        // minimum: required-removed:name, required-removed:age,
1711        // type-mismatch:name, type-mismatch:age, integer-as-float:age,
1712        // plus the root-level type-mismatch.
1713        let mut obj = ObjectType::default();
1714        obj.properties.insert(
1715            "name".to_string(),
1716            ReferenceOr::Item(Box::new(Schema {
1717                schema_data: SchemaData::default(),
1718                schema_kind: SchemaKind::Type(Type::String(Default::default())),
1719            })),
1720        );
1721        obj.properties.insert(
1722            "age".to_string(),
1723            ReferenceOr::Item(Box::new(Schema {
1724                schema_data: SchemaData::default(),
1725                schema_kind: SchemaKind::Type(Type::Integer(Default::default())),
1726            })),
1727        );
1728        obj.required = vec!["name".into(), "age".into()];
1729        let schema = Schema {
1730            schema_data: SchemaData::default(),
1731            schema_kind: SchemaKind::Type(Type::Object(obj)),
1732        };
1733
1734        let mut o =
1735            op("POST", "/users", Some(r#"{"name":"Ada","age":30}"#), vec![], vec![], vec![]);
1736        o.request_body_schema = Some(schema);
1737        let report = run_self_test(&[o], &cfg).await.expect("client builds");
1738        // Bucket labels from the operation result.
1739        let labels: std::collections::BTreeSet<String> = report
1740            .operations
1741            .iter()
1742            .flat_map(|op| op.negatives.iter().map(|n| n.label.clone()))
1743            .collect();
1744        assert!(
1745            labels.iter().any(|l| l.starts_with("request-body:type-mismatch:")),
1746            "missing type-mismatch negative; got {labels:?}"
1747        );
1748        assert!(
1749            labels.iter().any(|l| l.starts_with("request-body:required-removed:")),
1750            "missing required-removed negative; got {labels:?}"
1751        );
1752        assert!(
1753            labels.iter().any(|l| l == "parameters:uri-too-long"),
1754            "missing URI-length negative; got {labels:?}"
1755        );
1756    }
1757
1758    /// Round 16 — operations with a body OR a path-param now produce
1759    /// negatives even without a sample body. Previously a POST whose
1760    /// body annotator failed produced *zero* negatives, so the self-test
1761    /// always reported "all passing" for that endpoint.
1762    #[tokio::test]
1763    async fn no_sample_body_still_produces_request_body_negatives() {
1764        let cfg = SelfTestConfig {
1765            target_url: "http://127.0.0.1:1".into(),
1766            timeout: Duration::from_millis(200),
1767            ..Default::default()
1768        };
1769        // POST with a body content type but no sample (annotator gap).
1770        let ops = vec![op("POST", "/x", None, vec![], vec![], vec![])];
1771        // No sample_body but request_body_content_type set:
1772        let mut ops_fixed = ops;
1773        ops_fixed[0].request_body_content_type = Some("application/json".into());
1774        let report = run_self_test(&ops_fixed, &cfg).await.expect("client builds");
1775        // Both request-body negatives (empty + wrong-type) should fire,
1776        // landing in `negative_missed` because the unreachable target
1777        // returns no 4xx. The point: count > 0.
1778        assert!(
1779            report.negative_missed.values().sum::<usize>() >= 2,
1780            "expected ≥2 request-body negatives, got {:?}",
1781            report.negative_missed
1782        );
1783    }
1784
1785    /// Round 16 — operations with a path-param now get a probe even
1786    /// when there's no body / required query / required header.
1787    /// Previously `/teams/{team-id}` with no other required fields
1788    /// produced zero negatives → always "all passing".
1789    #[tokio::test]
1790    async fn path_param_only_endpoint_produces_a_probe() {
1791        let cfg = SelfTestConfig {
1792            target_url: "http://127.0.0.1:1".into(),
1793            timeout: Duration::from_millis(200),
1794            ..Default::default()
1795        };
1796        let ops = vec![op(
1797            "GET",
1798            "/teams/{team-id}",
1799            None,
1800            vec![],
1801            vec![],
1802            vec![("team-id", "1")],
1803        )];
1804        let report = run_self_test(&ops, &cfg).await.expect("client builds");
1805        let total: usize = report.negative_caught.values().sum::<usize>()
1806            + report.negative_missed.values().sum::<usize>();
1807        assert!(total >= 1, "expected ≥1 path-param probe, got {:?}", report);
1808    }
1809
1810    /// Round 18.5 — when `geo_ip` is set, every default forwarded-
1811    /// IP header gets the IP appended (X-Forwarded-For,
1812    /// True-Client-IP, CF-Connecting-IP).
1813    #[test]
1814    fn effective_op_headers_appends_geo_ip_to_default_headers() {
1815        let ip: IpAddr = "203.0.113.42".parse().unwrap();
1816        let headers = effective_op_headers(
1817            &[("Accept".into(), "application/json".into())],
1818            Some(ip),
1819            &default_geo_source_headers(),
1820        );
1821        let names: Vec<&str> = headers.iter().map(|(k, _)| k.as_str()).collect();
1822        assert!(names.contains(&"Accept"));
1823        assert!(names.contains(&"X-Forwarded-For"));
1824        assert!(names.contains(&"True-Client-IP"));
1825        assert!(names.contains(&"CF-Connecting-IP"));
1826        // Every geo header carries the same IP value.
1827        let geo_values: Vec<&str> =
1828            headers.iter().filter(|(k, _)| k != "Accept").map(|(_, v)| v.as_str()).collect();
1829        for v in geo_values {
1830            assert_eq!(v, "203.0.113.42");
1831        }
1832    }
1833
1834    /// Round 18.5 — operations that already declare a forwarded-IP
1835    /// header (rare but legal — some specs hard-code one) keep their
1836    /// declared value; we don't clobber the spec.
1837    #[test]
1838    fn effective_op_headers_respects_spec_declared_header() {
1839        let ip: IpAddr = "203.0.113.99".parse().unwrap();
1840        let headers = effective_op_headers(
1841            &[("x-forwarded-for".into(), "10.0.0.1".into())],
1842            Some(ip),
1843            &["X-Forwarded-For".to_string()],
1844        );
1845        // The spec's lower-case value wins; we shouldn't add a
1846        // second X-Forwarded-For row that overrides it.
1847        let xff: Vec<&str> = headers
1848            .iter()
1849            .filter(|(k, _)| k.eq_ignore_ascii_case("x-forwarded-for"))
1850            .map(|(_, v)| v.as_str())
1851            .collect();
1852        assert_eq!(xff, vec!["10.0.0.1"]);
1853    }
1854
1855    /// Round 18.5 — None geo_ip and/or empty header list is a no-op.
1856    #[test]
1857    fn effective_op_headers_is_a_noop_without_geo_ip() {
1858        let base = vec![("Accept".into(), "json".into())];
1859        let h1 = effective_op_headers(&base, None, &default_geo_source_headers());
1860        assert_eq!(h1, base);
1861        let ip: IpAddr = "10.0.0.1".parse().unwrap();
1862        let h2 = effective_op_headers(&base, Some(ip), &[]);
1863        assert_eq!(h2, base);
1864    }
1865
1866    /// Round 18.5 — empty `source_ips` builds a single default
1867    /// client; a non-empty list builds N clients each attempting to
1868    /// bind. We can't reliably test the actual bind on CI (no
1869    /// loopback aliases), but a loopback IP is always bind-able.
1870    #[test]
1871    fn build_client_pool_one_per_source_ip() {
1872        let mut cfg = SelfTestConfig {
1873            target_url: "http://127.0.0.1:1".into(),
1874            timeout: Duration::from_millis(200),
1875            ..Default::default()
1876        };
1877        // Empty → one default client.
1878        assert_eq!(build_client_pool(&cfg).expect("default builds").len(), 1);
1879        // Non-empty → one per IP. Loopback bind is portable.
1880        cfg.source_ips = vec!["127.0.0.1".parse().unwrap()];
1881        assert_eq!(build_client_pool(&cfg).expect("bind loopback").len(), 1);
1882    }
1883
1884    /// Round 18.5 — geo IPs round-robin across operations. Hits an
1885    /// unreachable target so we can inspect the case outcomes; the
1886    /// point is to confirm `op_headers` carried the geo IP through
1887    /// (CaseOutcome doesn't surface headers directly, so we just
1888    /// verify the run completes without panicking and the result
1889    /// shape is correct when source_ips is non-empty too).
1890    #[tokio::test]
1891    async fn run_self_test_with_geo_source_completes() {
1892        let cfg = SelfTestConfig {
1893            target_url: "http://127.0.0.1:1".into(),
1894            timeout: Duration::from_millis(200),
1895            geo_source_ips: vec![
1896                "203.0.113.1".parse().unwrap(),
1897                "203.0.113.2".parse().unwrap(),
1898            ],
1899            ..Default::default()
1900        };
1901        let ops = vec![
1902            op("GET", "/a", None, vec![], vec![], vec![]),
1903            op("GET", "/b", None, vec![], vec![], vec![]),
1904            op("GET", "/c", None, vec![], vec![], vec![]),
1905        ];
1906        let report = run_self_test(&ops, &cfg).await.expect("client builds");
1907        assert_eq!(report.operations.len(), 3);
1908    }
1909
1910    /// Round 24 (f) — Srikanth saw the geo header on positive probes
1911    /// only; the four negative-probe call sites were passing
1912    /// `op.header_params` directly instead of `op_headers`, so the
1913    /// geo IP got dropped. This test runs a self-test that includes
1914    /// negative probes (uri-too-long, missing-query, etc.) under
1915    /// `--conformance-self-test-capture`, then asserts that EVERY
1916    /// captured probe (positive AND negative) carries one of the
1917    /// configured forwarded-IP headers.
1918    #[tokio::test]
1919    async fn geo_headers_present_on_every_probe_with_capture() {
1920        let sink: Arc<Mutex<Vec<CaseCapture>>> = Arc::new(Mutex::new(Vec::new()));
1921        let cfg = SelfTestConfig {
1922            target_url: "http://127.0.0.1:1".into(),
1923            timeout: Duration::from_millis(50),
1924            geo_source_ips: vec!["203.0.113.5".parse().unwrap()],
1925            capture: Some(sink.clone()),
1926            ..Default::default()
1927        };
1928        // An operation rich enough to trip several negative-probe
1929        // branches: header param (→ missing-header), query param
1930        // (→ missing-query), and a sample body (→ schema mutations
1931        // wouldn't fire without a schema, but uri-too-long always
1932        // does).
1933        let ops = vec![op(
1934            "GET",
1935            "/items",
1936            Some("{}"),
1937            vec![("id", "1")],
1938            vec![("X-Trace", "x")],
1939            vec![],
1940        )];
1941        let _ = run_self_test(&ops, &cfg).await.expect("client builds");
1942        let captures = sink.lock().unwrap();
1943        assert!(!captures.is_empty(), "self-test should record probes");
1944        // For every captured probe, at least one of the default geo
1945        // headers must be present and equal to the configured IP.
1946        let geo_headers: std::collections::HashSet<&str> =
1947            ["X-Forwarded-For", "True-Client-IP", "CF-Connecting-IP"].into_iter().collect();
1948        for c in captures.iter() {
1949            let has_geo = c
1950                .request_headers
1951                .iter()
1952                .any(|(k, v)| geo_headers.contains(k.as_str()) && v == "203.0.113.5");
1953            assert!(
1954                has_geo,
1955                "probe `{}` is missing the geo IP header; got headers: {:?}",
1956                c.label, c.request_headers
1957            );
1958        }
1959    }
1960
1961    /// Round 25 (k) — operations with a JSON request body now get four
1962    /// content-type-swap probes (xml / yaml / multipart / urlencoded).
1963    /// Verify they:
1964    ///   1. fire only when the operation declares a JSON body
1965    ///   2. carry the wrong Content-Type the probe is testing for
1966    ///   3. don't fire on body-less operations
1967    #[tokio::test]
1968    async fn content_type_swap_probes_fire_for_json_bodies() {
1969        let sink: Arc<Mutex<Vec<CaseCapture>>> = Arc::new(Mutex::new(Vec::new()));
1970        let cfg = SelfTestConfig {
1971            target_url: "http://127.0.0.1:1".into(),
1972            timeout: Duration::from_millis(50),
1973            capture: Some(sink.clone()),
1974            ..Default::default()
1975        };
1976        let ops = vec![
1977            op("POST", "/users", Some("{\"name\":\"a\"}"), vec![], vec![], vec![]),
1978            op("GET", "/ping", None, vec![], vec![], vec![]),
1979        ];
1980        let _ = run_self_test(&ops, &cfg).await.expect("client builds");
1981        let captures = sink.lock().unwrap();
1982
1983        let swap_labels: Vec<&str> = captures
1984            .iter()
1985            .filter(|c| c.label.starts_with("request-body:content-type-mismatch:"))
1986            .map(|c| c.label.as_str())
1987            .collect();
1988        assert_eq!(
1989            swap_labels.len(),
1990            4,
1991            "expected 4 content-type-swap probes (one per variant), got: {swap_labels:?}"
1992        );
1993        let expected_labels = [
1994            "request-body:content-type-mismatch:xml",
1995            "request-body:content-type-mismatch:yaml",
1996            "request-body:content-type-mismatch:multipart",
1997            "request-body:content-type-mismatch:urlencoded",
1998        ];
1999        for want in expected_labels {
2000            assert!(swap_labels.contains(&want), "missing swap probe `{want}`");
2001        }
2002
2003        // Each swap probe must carry the wrong Content-Type it's
2004        // testing for — that's the whole point.
2005        for c in captures.iter() {
2006            let Some(suffix) = c.label.strip_prefix("request-body:content-type-mismatch:") else {
2007                continue;
2008            };
2009            let want_ct = match suffix {
2010                "xml" => "application/xml",
2011                "yaml" => "application/yaml",
2012                "multipart" => "multipart/form-data",
2013                "urlencoded" => "application/x-www-form-urlencoded",
2014                _ => continue,
2015            };
2016            let got_ct = c
2017                .request_headers
2018                .iter()
2019                .find(|(k, _)| k.eq_ignore_ascii_case("content-type"))
2020                .map(|(_, v)| v.as_str())
2021                .unwrap_or("");
2022            assert_eq!(got_ct, want_ct, "swap probe `{}` sent wrong CT", c.label);
2023        }
2024
2025        // The body-less operation must NOT produce content-type-swap
2026        // probes (no body → no content type to lie about).
2027        let body_less_swaps = captures
2028            .iter()
2029            .filter(|c| {
2030                c.label.starts_with("request-body:content-type-mismatch:")
2031                    && c.url.ends_with("/ping")
2032            })
2033            .count();
2034        assert_eq!(
2035            body_less_swaps, 0,
2036            "GET /ping has no request body; should not produce content-type-swap probes"
2037        );
2038    }
2039
2040    /// Round 27 (k variant b) — Srikanth's round-23 follow-up on (k):
2041    /// JSON envelope with embedded non-JSON field values. For each
2042    /// JSON-body operation, four extra probes fire that send valid
2043    /// JSON with an XML/YAML/multipart/urlencoded snippet stuffed
2044    /// into a string field. Content-Type stays `application/json`;
2045    /// expected is 2xx-3xx (the body parses); a 5xx flags a server
2046    /// that crashed on the embedded content.
2047    #[tokio::test]
2048    async fn embedded_content_probes_fire_with_honest_content_type() {
2049        let sink: Arc<Mutex<Vec<CaseCapture>>> = Arc::new(Mutex::new(Vec::new()));
2050        let cfg = SelfTestConfig {
2051            target_url: "http://127.0.0.1:1".into(),
2052            timeout: Duration::from_millis(50),
2053            capture: Some(sink.clone()),
2054            ..Default::default()
2055        };
2056        let ops = vec![op(
2057            "POST",
2058            "/users",
2059            Some("{\"name\":\"alice\",\"age\":30}"),
2060            vec![],
2061            vec![],
2062            vec![],
2063        )];
2064        let _ = run_self_test(&ops, &cfg).await.expect("client builds");
2065        let captures = sink.lock().unwrap();
2066        let embedded: Vec<&CaseCapture> = captures
2067            .iter()
2068            .filter(|c| c.label.starts_with("request-body:embedded-content:"))
2069            .collect();
2070        assert_eq!(
2071            embedded.len(),
2072            4,
2073            "expected 4 embedded-content probes, got: {:?}",
2074            embedded.iter().map(|c| &c.label).collect::<Vec<_>>()
2075        );
2076        // Every embedded probe must carry the honest application/json
2077        // Content-Type (NOT lie like the variant-a content-type-swap
2078        // probes do) and a request body that still parses as JSON.
2079        for c in &embedded {
2080            let ct = c
2081                .request_headers
2082                .iter()
2083                .find(|(k, _)| k.eq_ignore_ascii_case("content-type"))
2084                .map(|(_, v)| v.as_str())
2085                .unwrap_or("");
2086            assert!(
2087                ct.contains("application/json"),
2088                "embedded probe `{}` should keep Content-Type honest, got {ct}",
2089                c.label
2090            );
2091            let body = c.request_body.as_deref().unwrap_or("");
2092            assert!(
2093                serde_json::from_str::<serde_json::Value>(body).is_ok(),
2094                "embedded probe `{}` body should still be valid JSON, got: {body}",
2095                c.label
2096            );
2097        }
2098    }
2099
2100    /// `embed_payload_in_first_string_field` walks objects depth-first
2101    /// and replaces only the FIRST string-valued leaf, leaving the
2102    /// surrounding structure intact.
2103    #[test]
2104    fn embed_payload_replaces_first_string_only() {
2105        let sample = r#"{"name":"alice","age":30,"tags":["admin","user"]}"#;
2106        let mutated = embed_payload_in_first_string_field(sample, "<x/>");
2107        let v: serde_json::Value = serde_json::from_str(&mutated).unwrap();
2108        assert_eq!(v["name"], serde_json::json!("<x/>"));
2109        // age stays an integer (not stringified by the mutation).
2110        assert_eq!(v["age"], serde_json::json!(30));
2111        // tags array's strings stay untouched (we only replace the
2112        // first encountered string leaf, depth-first).
2113        assert_eq!(v["tags"][0], serde_json::json!("admin"));
2114        assert_eq!(v["tags"][1], serde_json::json!("user"));
2115    }
2116
2117    /// When the sample has NO string field, the helper falls back to
2118    /// `{"data": "<snippet>"}` so the probe still has something to
2119    /// POST. The fallback must produce valid JSON regardless of what
2120    /// characters the snippet contains.
2121    #[test]
2122    fn embed_payload_falls_back_when_no_string_field() {
2123        let no_strings = r#"{"a":1,"b":[2,3]}"#;
2124        let mutated = embed_payload_in_first_string_field(no_strings, "<x><y></y></x>");
2125        let v: serde_json::Value = serde_json::from_str(&mutated).unwrap();
2126        assert_eq!(v["data"], serde_json::json!("<x><y></y></x>"));
2127    }
2128
2129    #[test]
2130    fn embed_payload_handles_invalid_json_sample() {
2131        let not_json = "garbage";
2132        let mutated = embed_payload_in_first_string_field(not_json, "a=1&b=2");
2133        let v: serde_json::Value = serde_json::from_str(&mutated).unwrap();
2134        assert_eq!(v["data"], serde_json::json!("a=1&b=2"));
2135    }
2136
2137    /// Round 26 — Srikanth saw `at /: Type { kind: Single` in his
2138    /// 0.3.169 capture for the vCenter `infraprofile/configs` 202
2139    /// response (spec promised `type: string`, server returned a
2140    /// JSON object). The output was a broken-syntax debug string.
2141    /// This test reproduces his exact spec+body and asserts the
2142    /// message is readable.
2143    #[test]
2144    fn response_schema_error_message_is_readable() {
2145        let schema = serde_json::json!({"type": "string"});
2146        let body = r#"{"data":{},"id":"generated_id","status":"created"}"#;
2147        let err = validate_body_against_schema(body, &schema).expect("type-mismatch fires");
2148        // The message must NOT contain Rust debug syntax leftovers
2149        // ("Type { kind:", trailing "{" or "(" tokens). It SHOULD say
2150        // what type was expected and at which location.
2151        assert!(!err.contains("Type { kind"), "stale debug output: {err}");
2152        assert!(!err.contains("{ kind:"), "stale debug output: {err}");
2153        assert!(err.contains("string"), "should name expected type: {err}");
2154        assert!(err.contains("at /"), "should include instance path: {err}");
2155        // Round 28 — Srikanth wanted the expected schema embedded
2156        // in the message so it reads as 'expected schema {"type":"string"}'.
2157        assert!(
2158            err.contains("expected schema") && err.contains("\"type\":\"string\""),
2159            "should include expected schema JSON: {err}"
2160        );
2161    }
2162
2163    #[test]
2164    fn response_schema_error_required_field_is_readable() {
2165        let schema = serde_json::json!({
2166            "type": "object",
2167            "required": ["id"],
2168            "properties": {"id": {"type": "integer"}}
2169        });
2170        let body = r#"{"other": 1}"#;
2171        let err = validate_body_against_schema(body, &schema).expect("required-missing fires");
2172        assert!(err.contains("required field missing"), "{err}");
2173        assert!(err.contains("id"), "{err}");
2174    }
2175
2176    #[test]
2177    fn response_schema_error_none_on_match() {
2178        let schema = serde_json::json!({"type": "string"});
2179        assert_eq!(validate_body_against_schema("\"hello\"", &schema), None);
2180    }
2181
2182    #[test]
2183    fn json_serialises_report() {
2184        let r = SelfTestReport {
2185            positive_pass: 1,
2186            positive_fail: 0,
2187            negative_caught: BTreeMap::new(),
2188            negative_missed: BTreeMap::new(),
2189            operations: vec![OperationResult {
2190                method: "GET".into(),
2191                path: "/x".into(),
2192                positive: Some(CaseOutcome {
2193                    label: "positive".into(),
2194                    expected_4xx: false,
2195                    actual_status: 200,
2196                    passed: true,
2197                }),
2198                negatives: Vec::new(),
2199            }],
2200        };
2201        let json = serde_json::to_value(&r).expect("serialises");
2202        assert_eq!(json["positive_pass"], serde_json::json!(1));
2203        assert_eq!(json["operations"][0]["positive"]["actual_status"], serde_json::json!(200));
2204    }
2205}