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    // Round 29 — Srikanth on 0.3.172 was confused by `at /:` thinking
1025    // it referenced the URL path; it's actually a JSON pointer into
1026    // the RESPONSE BODY. Reword so that's unambiguous: explicit
1027    // "response body" prefix and a human label for the root case.
1028    let location = if path == "/" {
1029        "response body root".to_string()
1030    } else {
1031        format!("response body at {path}")
1032    };
1033    Some(format!("{location}: {kind_msg}; expected schema {schema_str}"))
1034}
1035
1036/// Round 17.5 — one OWASP injection probe to send.
1037#[derive(Debug, Clone)]
1038struct OwaspProbe {
1039    label: String,
1040    body: Option<String>,
1041    query: Vec<(String, String)>,
1042}
1043
1044/// Build one OWASP probe per `SecurityCategory` for `op`. Targets the
1045/// first query param if any, else the first string field of the
1046/// positive JSON body. Returns empty if neither target is available.
1047fn build_owasp_probes(op: &AnnotatedOperation) -> Vec<OwaspProbe> {
1048    use crate::security_payloads::{SecurityCategory, SecurityPayloads};
1049
1050    let categories = [
1051        SecurityCategory::SqlInjection,
1052        SecurityCategory::Xss,
1053        SecurityCategory::CommandInjection,
1054        SecurityCategory::PathTraversal,
1055        SecurityCategory::Ssti,
1056        SecurityCategory::LdapInjection,
1057        SecurityCategory::Xxe,
1058    ];
1059
1060    // Pick an injection target ONCE per operation; reuse it across
1061    // categories. (A single op gets up to 7 probes — one per category
1062    // — all attacking the same field.)
1063    let injection_target = pick_injection_target(op);
1064    let Some(target) = injection_target else {
1065        return Vec::new();
1066    };
1067
1068    let mut probes = Vec::new();
1069    for cat in categories {
1070        // Take the *first* payload from each category. The
1071        // collection's first entry is the canonical low-risk
1072        // representative; later entries include time-based / blind
1073        // probes that aren't useful as a one-shot rejection test.
1074        let Some(payload) = SecurityPayloads::get_by_category(cat).into_iter().next() else {
1075            continue;
1076        };
1077        let mut query = op.query_params.clone();
1078        let mut body = op.sample_body.clone();
1079        match &target {
1080            InjectionTarget::Query(idx) => {
1081                if let Some(slot) = query.get_mut(*idx) {
1082                    slot.1 = payload.payload.clone();
1083                }
1084            }
1085            InjectionTarget::BodyStringField(field) => {
1086                body = inject_into_body_field(body.as_deref(), field, &payload.payload);
1087            }
1088        }
1089        probes.push(OwaspProbe {
1090            label: format!("owasp:{}", cat),
1091            body,
1092            query,
1093        });
1094    }
1095    probes
1096}
1097
1098#[derive(Debug, Clone)]
1099enum InjectionTarget {
1100    Query(usize),
1101    BodyStringField(String),
1102}
1103
1104fn pick_injection_target(op: &AnnotatedOperation) -> Option<InjectionTarget> {
1105    if !op.query_params.is_empty() {
1106        return Some(InjectionTarget::Query(0));
1107    }
1108    let sample = op.sample_body.as_deref()?;
1109    let parsed: serde_json::Value = serde_json::from_str(sample).ok()?;
1110    let obj = parsed.as_object()?;
1111    for (k, v) in obj {
1112        if v.is_string() {
1113            return Some(InjectionTarget::BodyStringField(k.clone()));
1114        }
1115    }
1116    None
1117}
1118
1119/// Replace the value of `field` in a JSON-object body with `payload`.
1120/// Returns the mutated body as a JSON string. Returns `None` if the
1121/// body doesn't parse as a JSON object.
1122fn inject_into_body_field(body: Option<&str>, field: &str, payload: &str) -> Option<String> {
1123    let raw = body?;
1124    let mut parsed: serde_json::Value = serde_json::from_str(raw).ok()?;
1125    let obj = parsed.as_object_mut()?;
1126    obj.insert(field.to_string(), serde_json::json!(payload));
1127    serde_json::to_string(&parsed).ok()
1128}
1129
1130#[allow(clippy::too_many_arguments)]
1131/// Round 17.3 — one synthesised bad credential to send.
1132#[derive(Debug, Clone)]
1133struct SecurityProbe {
1134    /// Self-test label, e.g. `security:bad-bearer`.
1135    label: String,
1136    /// Headers to attach to the probe request.
1137    headers: Vec<(String, String)>,
1138    /// Query parameters to attach (API key in query case).
1139    query: Vec<(String, String)>,
1140}
1141
1142/// For each declared security scheme, produce one bad-credential
1143/// probe plus a single "no auth at all" probe that exercises the
1144/// missing-credential code path. Deduplicates by scheme kind so an
1145/// operation declaring `[bearer, bearer]` only yields one Bearer
1146/// probe.
1147fn build_security_probes(schemes: &[SecuritySchemeInfo]) -> Vec<SecurityProbe> {
1148    if schemes.is_empty() {
1149        return Vec::new();
1150    }
1151    let mut probes: Vec<SecurityProbe> = Vec::new();
1152    let mut seen_bearer = false;
1153    let mut seen_basic = false;
1154    // `(loc_tag, name)` — ApiKeyLocation doesn't implement Ord, so
1155    // we tag it with a short discriminant string for dedup.
1156    let mut seen_apikey: std::collections::BTreeSet<(&'static str, String)> = Default::default();
1157    for s in schemes {
1158        match s {
1159            SecuritySchemeInfo::Bearer if !seen_bearer => {
1160                seen_bearer = true;
1161                probes.push(SecurityProbe {
1162                    label: "security:bad-bearer".into(),
1163                    headers: vec![(
1164                        "Authorization".into(),
1165                        "Bearer self-test-invalid-token".into(),
1166                    )],
1167                    query: Vec::new(),
1168                });
1169            }
1170            SecuritySchemeInfo::Basic if !seen_basic => {
1171                seen_basic = true;
1172                // base64("self-test:invalid") — valid base64, wrong creds.
1173                probes.push(SecurityProbe {
1174                    label: "security:bad-basic".into(),
1175                    headers: vec![(
1176                        "Authorization".into(),
1177                        "Basic c2VsZi10ZXN0OmludmFsaWQ=".into(),
1178                    )],
1179                    query: Vec::new(),
1180                });
1181            }
1182            SecuritySchemeInfo::ApiKey { location, name } => {
1183                let loc_tag = match location {
1184                    ApiKeyLocation::Header => "header",
1185                    ApiKeyLocation::Query => "query",
1186                    ApiKeyLocation::Cookie => "cookie",
1187                };
1188                if seen_apikey.contains(&(loc_tag, name.clone())) {
1189                    continue;
1190                }
1191                seen_apikey.insert((loc_tag, name.clone()));
1192                let label = format!("security:bad-apikey:{}", name);
1193                let bad = "self-test-invalid-key".to_string();
1194                match location {
1195                    ApiKeyLocation::Header => probes.push(SecurityProbe {
1196                        label,
1197                        headers: vec![(name.clone(), bad)],
1198                        query: Vec::new(),
1199                    }),
1200                    ApiKeyLocation::Query => probes.push(SecurityProbe {
1201                        label,
1202                        headers: Vec::new(),
1203                        query: vec![(name.clone(), bad)],
1204                    }),
1205                    ApiKeyLocation::Cookie => probes.push(SecurityProbe {
1206                        label,
1207                        headers: vec![("Cookie".into(), format!("{}={}", name, bad))],
1208                        query: Vec::new(),
1209                    }),
1210                }
1211            }
1212            _ => {}
1213        }
1214    }
1215    // Always add a "no auth at all" probe when *any* security scheme
1216    // is declared — useful even if all schemes failed to resolve to a
1217    // testable kind, because it surfaces validators that aren't
1218    // checking auth presence at all.
1219    probes.push(SecurityProbe {
1220        label: "security:no-auth".into(),
1221        headers: Vec::new(),
1222        query: Vec::new(),
1223    });
1224    probes
1225}
1226
1227/// Remove Authorization and any API-key headers declared by the
1228/// operation's security schemes from `headers`, so a security probe
1229/// can supply its own credential (or none) cleanly.
1230fn strip_auth(
1231    headers: &[(String, String)],
1232    schemes: &[SecuritySchemeInfo],
1233) -> Vec<(String, String)> {
1234    let mut apikey_headers: std::collections::BTreeSet<String> = Default::default();
1235    for s in schemes {
1236        if let SecuritySchemeInfo::ApiKey {
1237            location: ApiKeyLocation::Header,
1238            name,
1239        } = s
1240        {
1241            apikey_headers.insert(name.to_lowercase());
1242        }
1243        if let SecuritySchemeInfo::ApiKey {
1244            location: ApiKeyLocation::Cookie,
1245            ..
1246        } = s
1247        {
1248            apikey_headers.insert("cookie".into());
1249        }
1250    }
1251    headers
1252        .iter()
1253        .filter(|(k, _)| {
1254            let lk = k.to_lowercase();
1255            lk != "authorization" && !apikey_headers.contains(&lk)
1256        })
1257        .cloned()
1258        .collect()
1259}
1260
1261/// Remove API-key query parameters declared by the operation's
1262/// security schemes from `query`, so a probe can supply its own.
1263fn strip_auth_query(
1264    query: &[(String, String)],
1265    schemes: &[SecuritySchemeInfo],
1266) -> Vec<(String, String)> {
1267    let mut apikey_query: std::collections::BTreeSet<String> = Default::default();
1268    for s in schemes {
1269        if let SecuritySchemeInfo::ApiKey {
1270            location: ApiKeyLocation::Query,
1271            name,
1272        } = s
1273        {
1274            apikey_query.insert(name.clone());
1275        }
1276    }
1277    query.iter().filter(|(k, _)| !apikey_query.contains(k)).cloned().collect()
1278}
1279
1280/// Variant of `send_case` that takes an explicit `extra_headers`
1281/// (rather than reading them from `config`). Used by security probes
1282/// to substitute or strip the configured Authorization header.
1283#[allow(clippy::too_many_arguments)]
1284async fn send_case_with_extra(
1285    client: &Client,
1286    config: &SelfTestConfig,
1287    method: Method,
1288    url: &str,
1289    label: &str,
1290    expected_4xx: bool,
1291    body: Option<&str>,
1292    query: Vec<(String, String)>,
1293    headers: Vec<(String, String)>,
1294    extra_headers: Vec<(String, String)>,
1295) -> CaseOutcome {
1296    let mut req = client.request(method.clone(), url);
1297    let mut capture_headers: BTreeMap<String, String> = BTreeMap::new();
1298    for (k, v) in &query {
1299        req = req.query(&[(k.as_str(), v.as_str())]);
1300    }
1301    // Round 28 — reqwest's `.header(k, v)` APPENDS rather than replaces
1302    // (.headers().insert() would replace but isn't on the builder).
1303    // The previous round-25 fix relied on "last-write-wins" semantics
1304    // that don't exist; for content-type-swap probes the request went
1305    // out with BOTH `Content-Type: application/json` AND `Content-Type:
1306    // application/xml`, and axum's `Json<>` extractor picked the JSON
1307    // one and accepted, so the server-side validator never saw the
1308    // mismatch. Build a `HeaderMap` ourselves so the override
1309    // replaces the body-block default exactly once.
1310    let mut final_headers: reqwest::header::HeaderMap = reqwest::header::HeaderMap::new();
1311    if let Some(_b) = body {
1312        if let Ok(v) = reqwest::header::HeaderValue::from_str("application/json") {
1313            final_headers.insert(reqwest::header::CONTENT_TYPE, v);
1314        }
1315        capture_headers.insert("Content-Type".to_string(), "application/json".to_string());
1316    }
1317    for (k, v) in &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    for (k, v) in &extra_headers {
1327        if let (Ok(hn), Ok(hv)) = (
1328            reqwest::header::HeaderName::from_bytes(k.as_bytes()),
1329            reqwest::header::HeaderValue::from_str(v),
1330        ) {
1331            final_headers.insert(hn, hv);
1332        }
1333        capture_headers.insert(k.clone(), v.clone());
1334    }
1335    if let Some(b) = body {
1336        req = req.body(b.to_string());
1337    }
1338    req = req.headers(final_headers);
1339    let (actual_status, response_capture) = match req.send().await {
1340        Ok(resp) => {
1341            let status = resp.status().as_u16();
1342            if let Some(sink) = &config.capture {
1343                let resp_headers: BTreeMap<String, String> = resp
1344                    .headers()
1345                    .iter()
1346                    .map(|(k, v)| (k.as_str().to_string(), v.to_str().unwrap_or("").to_string()))
1347                    .collect();
1348                let text = resp.text().await.unwrap_or_default();
1349                let (rb, truncated) = truncate_body_for_capture(&text);
1350                (status, Some((Some((rb, truncated)), resp_headers, None, sink.clone())))
1351            } else {
1352                (status, None)
1353            }
1354        }
1355        Err(e) => {
1356            let err_str = e.to_string();
1357            if let Some(sink) = &config.capture {
1358                (0, Some((None, BTreeMap::new(), Some(err_str), sink.clone())))
1359            } else {
1360                (0, None)
1361            }
1362        }
1363    };
1364    let passed = if expected_4xx {
1365        (400..500).contains(&actual_status)
1366    } else {
1367        (200..400).contains(&actual_status)
1368    };
1369    if let Some((resp_body, resp_headers, error, sink)) = response_capture {
1370        let (request_body, request_body_truncated) = match body {
1371            Some(b) => {
1372                let (rb, t) = truncate_body_for_capture(b);
1373                (Some(rb), t)
1374            }
1375            None => (None, false),
1376        };
1377        let (response_body, response_body_truncated) = match resp_body {
1378            Some((rb, t)) => (Some(rb), t),
1379            None => (None, false),
1380        };
1381        let entry = CaseCapture {
1382            label: label.to_string(),
1383            method: method.to_string(),
1384            url: build_query_url(url, &query),
1385            request_headers: capture_headers,
1386            request_body,
1387            request_body_truncated,
1388            response_status: actual_status,
1389            response_headers: resp_headers,
1390            response_body,
1391            response_body_truncated,
1392            error,
1393            // Filled in by the per-operation validation pass after
1394            // every probe finishes; the capture itself is unaware of
1395            // the schema map.
1396            response_schema_error: None,
1397            // Round 28 — derive the expected range from the probe's
1398            // `expected_4xx` flag so the JSONL line and HTML viewer
1399            // can show mismatches without re-deriving on the read side.
1400            expected_status_range: if expected_4xx {
1401                "4xx".into()
1402            } else {
1403                "2xx-3xx".into()
1404            },
1405        };
1406        if let Ok(mut guard) = sink.lock() {
1407            guard.push(entry);
1408        }
1409    }
1410    CaseOutcome {
1411        label: label.to_string(),
1412        expected_4xx,
1413        actual_status,
1414        passed,
1415    }
1416}
1417
1418// HTTP request shape needs all of these: client, config (for capture
1419// sink + extra headers), method, url, label (probe id), expected_4xx
1420// (pass/fail decision), body, query, headers. A struct wrapper would
1421// just move the arity from positional to field access without making
1422// the call sites clearer.
1423#[allow(clippy::too_many_arguments)]
1424async fn send_case(
1425    client: &Client,
1426    config: &SelfTestConfig,
1427    method: Method,
1428    url: &str,
1429    label: &str,
1430    expected_4xx: bool,
1431    body: Option<&str>,
1432    query: Vec<(String, String)>,
1433    headers: Vec<(String, String)>,
1434) -> CaseOutcome {
1435    // Forwarding to `send_case_with_extra` keeps the capture logic in
1436    // one place so request/response tracing can't drift between the
1437    // two entrypoints.
1438    send_case_with_extra(
1439        client,
1440        config,
1441        method,
1442        url,
1443        label,
1444        expected_4xx,
1445        body,
1446        query,
1447        headers,
1448        config.extra_headers.clone(),
1449    )
1450    .await
1451}
1452
1453/// Round 23 (c-iii) — rebuild the query-stringified URL for capture so
1454/// the JSONL trace shows the URL that actually went over the wire
1455/// (reqwest applies `.query(..)` after the request URL string is
1456/// rendered, so capturing the raw `url` argument alone loses the
1457/// query params).
1458fn build_query_url(base: &str, query: &[(String, String)]) -> String {
1459    if query.is_empty() {
1460        return base.to_string();
1461    }
1462    let qs: String = query
1463        .iter()
1464        .map(|(k, v)| format!("{}={}", urlencoding::encode(k), urlencoding::encode(v)))
1465        .collect::<Vec<_>>()
1466        .join("&");
1467    if base.contains('?') {
1468        format!("{base}&{qs}")
1469    } else {
1470        format!("{base}?{qs}")
1471    }
1472}
1473
1474/// Substitute `{param}` placeholders in the spec path with their
1475/// sample values from `path_params`, then prepend `target_url`. Empty
1476/// values are kept as `{param}` so an upstream router still matches
1477/// the template — useful when `path_params` is empty and we want to
1478/// hit the same route the spec defines.
1479///
1480/// All current call sites went through `build_url_with_base` after
1481/// round 18.1, so this no-base-path helper is unused; keep it as the
1482/// documented shim for future external callers (one-arg simplification).
1483#[allow(dead_code)]
1484fn build_url(target: &str, path_template: &str, path_params: &[(String, String)]) -> String {
1485    build_url_with_base(target, None, path_template, path_params)
1486}
1487
1488/// Round 18.1 — variant of `build_url` that takes a `base_path`
1489/// (e.g. `Some("/api")`). When set, prepends it to the spec path so a
1490/// spec declaring `/users` against a target served behind `/api`
1491/// resolves to `<target>/api/users`. `base_path` is normalised: leading
1492/// `/` is auto-added, trailing `/` is stripped.
1493fn build_url_with_base(
1494    target: &str,
1495    base_path: Option<&str>,
1496    path_template: &str,
1497    path_params: &[(String, String)],
1498) -> String {
1499    let mut url = path_template.to_string();
1500    for (name, value) in path_params {
1501        let placeholder = format!("{{{}}}", name);
1502        if !value.is_empty() {
1503            url = url.replace(&placeholder, value);
1504        }
1505    }
1506    let target = target.trim_end_matches('/');
1507    let prefix = match base_path {
1508        Some(bp) if !bp.is_empty() => {
1509            let trimmed = bp.trim_end_matches('/');
1510            if trimmed.starts_with('/') {
1511                trimmed.to_string()
1512            } else {
1513                format!("/{}", trimmed)
1514            }
1515        }
1516        _ => String::new(),
1517    };
1518    let path = if url.starts_with('/') {
1519        url
1520    } else {
1521        format!("/{url}")
1522    };
1523    format!("{target}{prefix}{path}")
1524}
1525
1526#[cfg(test)]
1527mod tests {
1528    use super::*;
1529
1530    fn op(
1531        method: &str,
1532        path: &str,
1533        body: Option<&str>,
1534        query: Vec<(&str, &str)>,
1535        headers: Vec<(&str, &str)>,
1536        path_params: Vec<(&str, &str)>,
1537    ) -> AnnotatedOperation {
1538        AnnotatedOperation {
1539            method: method.into(),
1540            path: path.into(),
1541            features: Vec::new(),
1542            request_body_content_type: body.map(|_| "application/json".into()),
1543            sample_body: body.map(|s| s.to_string()),
1544            query_params: query.into_iter().map(|(a, b)| (a.into(), b.into())).collect(),
1545            header_params: headers.into_iter().map(|(a, b)| (a.into(), b.into())).collect(),
1546            path_params: path_params.into_iter().map(|(a, b)| (a.into(), b.into())).collect(),
1547            response_schema: None,
1548            response_schemas: std::collections::BTreeMap::new(),
1549            request_body_schema: None,
1550            security_schemes: Vec::new(),
1551        }
1552    }
1553
1554    #[test]
1555    fn build_url_substitutes_path_params() {
1556        let url = build_url(
1557            "https://api.test/",
1558            "/users/{id}/posts/{pid}",
1559            &[("id".into(), "42".into()), ("pid".into(), "7".into())],
1560        );
1561        assert_eq!(url, "https://api.test/users/42/posts/7");
1562    }
1563
1564    /// Round 18.1 — a run where every positive 404s should be flagged
1565    /// as a likely target misconfiguration, not silently treated as a
1566    /// successful conformance run.
1567    #[test]
1568    fn detect_target_misconfiguration_when_all_positives_share_status() {
1569        let mut report = SelfTestReport {
1570            positive_pass: 0,
1571            positive_fail: 50,
1572            ..Default::default()
1573        };
1574        for i in 0..50 {
1575            report.operations.push(OperationResult {
1576                method: "GET".into(),
1577                path: format!("/r/{i}"),
1578                positive: Some(CaseOutcome {
1579                    label: "positive".into(),
1580                    expected_4xx: false,
1581                    actual_status: 404,
1582                    passed: false,
1583                }),
1584                negatives: Vec::new(),
1585            });
1586        }
1587        assert_eq!(report.detect_target_misconfiguration(), Some(404));
1588    }
1589
1590    #[test]
1591    fn detect_target_misconfiguration_returns_none_when_some_pass() {
1592        let mut report = SelfTestReport {
1593            positive_pass: 5,
1594            positive_fail: 50,
1595            ..Default::default()
1596        };
1597        for i in 0..55 {
1598            report.operations.push(OperationResult {
1599                method: "GET".into(),
1600                path: format!("/r/{i}"),
1601                positive: Some(CaseOutcome {
1602                    label: "positive".into(),
1603                    expected_4xx: false,
1604                    actual_status: if i < 5 { 200 } else { 404 },
1605                    passed: i < 5,
1606                }),
1607                negatives: Vec::new(),
1608            });
1609        }
1610        assert_eq!(report.detect_target_misconfiguration(), None);
1611    }
1612
1613    /// Round 18.1 — `--base-path /api` should prepend `/api` to
1614    /// every spec path. Pre-fix, the self-test ignored base_path and
1615    /// 404'd every positive when the deployed API was behind a path
1616    /// prefix.
1617    #[test]
1618    fn build_url_applies_base_path_when_present() {
1619        let url = build_url_with_base(
1620            "https://api.example.com",
1621            Some("/api"),
1622            "/users/{id}",
1623            &[("id".into(), "42".into())],
1624        );
1625        assert_eq!(url, "https://api.example.com/api/users/42");
1626    }
1627
1628    /// Round 18.1 — base_path is normalised: missing leading slash
1629    /// gets one added, trailing slash is stripped, empty string is
1630    /// the same as None.
1631    #[test]
1632    fn build_url_normalises_base_path() {
1633        let no_slash = build_url_with_base("https://t", Some("api"), "/x", &[]);
1634        assert_eq!(no_slash, "https://t/api/x");
1635        let trailing = build_url_with_base("https://t", Some("/api/"), "/x", &[]);
1636        assert_eq!(trailing, "https://t/api/x");
1637        let empty = build_url_with_base("https://t", Some(""), "/x", &[]);
1638        assert_eq!(empty, "https://t/x");
1639        let none = build_url_with_base("https://t", None, "/x", &[]);
1640        assert_eq!(none, "https://t/x");
1641    }
1642
1643    #[test]
1644    fn build_url_keeps_placeholders_when_no_sample() {
1645        let url = build_url("https://api.test", "/users/{id}", &[]);
1646        assert_eq!(url, "https://api.test/users/{id}");
1647    }
1648
1649    #[test]
1650    fn report_summary_calls_out_misses() {
1651        let r = SelfTestReport {
1652            positive_pass: 3,
1653            positive_fail: 0,
1654            negative_caught: BTreeMap::from([("request-body".into(), 2)]),
1655            negative_missed: BTreeMap::from([("request-body".into(), 1)]),
1656            operations: Vec::new(),
1657        };
1658        let summary = r.render_summary();
1659        assert!(summary.contains("Positives: 3 pass / 0 fail"));
1660        assert!(summary.contains("Negatives [request-body]: 2 caught / 1 missed"));
1661        assert!(summary.contains("⚠"));
1662        assert!(!r.all_passed());
1663    }
1664
1665    #[test]
1666    fn report_all_passed_when_no_miss() {
1667        let r = SelfTestReport {
1668            positive_pass: 5,
1669            positive_fail: 0,
1670            negative_caught: BTreeMap::from([("parameters".into(), 3)]),
1671            negative_missed: BTreeMap::new(),
1672            operations: Vec::new(),
1673        };
1674        assert!(r.all_passed());
1675        assert!(r.render_summary().contains("✓"));
1676    }
1677
1678    #[tokio::test]
1679    async fn run_self_test_against_unreachable_target_marks_all_failed() {
1680        // Use an obviously-dead port so we exercise the timeout/error
1681        // path without needing a live server in tests.
1682        let cfg = SelfTestConfig {
1683            target_url: "http://127.0.0.1:1".into(),
1684            timeout: Duration::from_millis(200),
1685            ..Default::default()
1686        };
1687        let ops = vec![op(
1688            "POST",
1689            "/users",
1690            Some("{\"name\":\"a\"}"),
1691            vec![],
1692            vec![],
1693            vec![],
1694        )];
1695        let report = run_self_test(&ops, &cfg).await.expect("client builds");
1696        // All cases hit the connect-error path → actual_status=0.
1697        // Positive expects 2xx-3xx → 0 is fail. Negatives expect 4xx
1698        // → 0 is also fail (we missed catching).
1699        assert_eq!(report.positive_fail, 1);
1700        assert!(report.negative_missed.values().sum::<usize>() >= 1);
1701        assert!(!report.all_passed());
1702    }
1703
1704    /// Round 17.2 — operations with both a positive sample AND a
1705    /// resolved request-body schema produce schema-driven negatives
1706    /// in addition to the spec-agnostic empty/wrong-type ones. The
1707    /// labels carry the field path so a per-category report can tell
1708    /// you exactly which field caught.
1709    #[tokio::test]
1710    async fn schema_driven_negatives_fire_when_schema_present() {
1711        use openapiv3::{ObjectType, ReferenceOr, Schema, SchemaData, SchemaKind, Type};
1712        let cfg = SelfTestConfig {
1713            target_url: "http://127.0.0.1:1".into(),
1714            timeout: Duration::from_millis(200),
1715            ..Default::default()
1716        };
1717        // Build an operation whose schema has a required `name` string
1718        // and an `age` integer. The mutator should produce, at
1719        // minimum: required-removed:name, required-removed:age,
1720        // type-mismatch:name, type-mismatch:age, integer-as-float:age,
1721        // plus the root-level type-mismatch.
1722        let mut obj = ObjectType::default();
1723        obj.properties.insert(
1724            "name".to_string(),
1725            ReferenceOr::Item(Box::new(Schema {
1726                schema_data: SchemaData::default(),
1727                schema_kind: SchemaKind::Type(Type::String(Default::default())),
1728            })),
1729        );
1730        obj.properties.insert(
1731            "age".to_string(),
1732            ReferenceOr::Item(Box::new(Schema {
1733                schema_data: SchemaData::default(),
1734                schema_kind: SchemaKind::Type(Type::Integer(Default::default())),
1735            })),
1736        );
1737        obj.required = vec!["name".into(), "age".into()];
1738        let schema = Schema {
1739            schema_data: SchemaData::default(),
1740            schema_kind: SchemaKind::Type(Type::Object(obj)),
1741        };
1742
1743        let mut o =
1744            op("POST", "/users", Some(r#"{"name":"Ada","age":30}"#), vec![], vec![], vec![]);
1745        o.request_body_schema = Some(schema);
1746        let report = run_self_test(&[o], &cfg).await.expect("client builds");
1747        // Bucket labels from the operation result.
1748        let labels: std::collections::BTreeSet<String> = report
1749            .operations
1750            .iter()
1751            .flat_map(|op| op.negatives.iter().map(|n| n.label.clone()))
1752            .collect();
1753        assert!(
1754            labels.iter().any(|l| l.starts_with("request-body:type-mismatch:")),
1755            "missing type-mismatch negative; got {labels:?}"
1756        );
1757        assert!(
1758            labels.iter().any(|l| l.starts_with("request-body:required-removed:")),
1759            "missing required-removed negative; got {labels:?}"
1760        );
1761        assert!(
1762            labels.iter().any(|l| l == "parameters:uri-too-long"),
1763            "missing URI-length negative; got {labels:?}"
1764        );
1765    }
1766
1767    /// Round 16 — operations with a body OR a path-param now produce
1768    /// negatives even without a sample body. Previously a POST whose
1769    /// body annotator failed produced *zero* negatives, so the self-test
1770    /// always reported "all passing" for that endpoint.
1771    #[tokio::test]
1772    async fn no_sample_body_still_produces_request_body_negatives() {
1773        let cfg = SelfTestConfig {
1774            target_url: "http://127.0.0.1:1".into(),
1775            timeout: Duration::from_millis(200),
1776            ..Default::default()
1777        };
1778        // POST with a body content type but no sample (annotator gap).
1779        let ops = vec![op("POST", "/x", None, vec![], vec![], vec![])];
1780        // No sample_body but request_body_content_type set:
1781        let mut ops_fixed = ops;
1782        ops_fixed[0].request_body_content_type = Some("application/json".into());
1783        let report = run_self_test(&ops_fixed, &cfg).await.expect("client builds");
1784        // Both request-body negatives (empty + wrong-type) should fire,
1785        // landing in `negative_missed` because the unreachable target
1786        // returns no 4xx. The point: count > 0.
1787        assert!(
1788            report.negative_missed.values().sum::<usize>() >= 2,
1789            "expected ≥2 request-body negatives, got {:?}",
1790            report.negative_missed
1791        );
1792    }
1793
1794    /// Round 16 — operations with a path-param now get a probe even
1795    /// when there's no body / required query / required header.
1796    /// Previously `/teams/{team-id}` with no other required fields
1797    /// produced zero negatives → always "all passing".
1798    #[tokio::test]
1799    async fn path_param_only_endpoint_produces_a_probe() {
1800        let cfg = SelfTestConfig {
1801            target_url: "http://127.0.0.1:1".into(),
1802            timeout: Duration::from_millis(200),
1803            ..Default::default()
1804        };
1805        let ops = vec![op(
1806            "GET",
1807            "/teams/{team-id}",
1808            None,
1809            vec![],
1810            vec![],
1811            vec![("team-id", "1")],
1812        )];
1813        let report = run_self_test(&ops, &cfg).await.expect("client builds");
1814        let total: usize = report.negative_caught.values().sum::<usize>()
1815            + report.negative_missed.values().sum::<usize>();
1816        assert!(total >= 1, "expected ≥1 path-param probe, got {:?}", report);
1817    }
1818
1819    /// Round 18.5 — when `geo_ip` is set, every default forwarded-
1820    /// IP header gets the IP appended (X-Forwarded-For,
1821    /// True-Client-IP, CF-Connecting-IP).
1822    #[test]
1823    fn effective_op_headers_appends_geo_ip_to_default_headers() {
1824        let ip: IpAddr = "203.0.113.42".parse().unwrap();
1825        let headers = effective_op_headers(
1826            &[("Accept".into(), "application/json".into())],
1827            Some(ip),
1828            &default_geo_source_headers(),
1829        );
1830        let names: Vec<&str> = headers.iter().map(|(k, _)| k.as_str()).collect();
1831        assert!(names.contains(&"Accept"));
1832        assert!(names.contains(&"X-Forwarded-For"));
1833        assert!(names.contains(&"True-Client-IP"));
1834        assert!(names.contains(&"CF-Connecting-IP"));
1835        // Every geo header carries the same IP value.
1836        let geo_values: Vec<&str> =
1837            headers.iter().filter(|(k, _)| k != "Accept").map(|(_, v)| v.as_str()).collect();
1838        for v in geo_values {
1839            assert_eq!(v, "203.0.113.42");
1840        }
1841    }
1842
1843    /// Round 18.5 — operations that already declare a forwarded-IP
1844    /// header (rare but legal — some specs hard-code one) keep their
1845    /// declared value; we don't clobber the spec.
1846    #[test]
1847    fn effective_op_headers_respects_spec_declared_header() {
1848        let ip: IpAddr = "203.0.113.99".parse().unwrap();
1849        let headers = effective_op_headers(
1850            &[("x-forwarded-for".into(), "10.0.0.1".into())],
1851            Some(ip),
1852            &["X-Forwarded-For".to_string()],
1853        );
1854        // The spec's lower-case value wins; we shouldn't add a
1855        // second X-Forwarded-For row that overrides it.
1856        let xff: Vec<&str> = headers
1857            .iter()
1858            .filter(|(k, _)| k.eq_ignore_ascii_case("x-forwarded-for"))
1859            .map(|(_, v)| v.as_str())
1860            .collect();
1861        assert_eq!(xff, vec!["10.0.0.1"]);
1862    }
1863
1864    /// Round 18.5 — None geo_ip and/or empty header list is a no-op.
1865    #[test]
1866    fn effective_op_headers_is_a_noop_without_geo_ip() {
1867        let base = vec![("Accept".into(), "json".into())];
1868        let h1 = effective_op_headers(&base, None, &default_geo_source_headers());
1869        assert_eq!(h1, base);
1870        let ip: IpAddr = "10.0.0.1".parse().unwrap();
1871        let h2 = effective_op_headers(&base, Some(ip), &[]);
1872        assert_eq!(h2, base);
1873    }
1874
1875    /// Round 18.5 — empty `source_ips` builds a single default
1876    /// client; a non-empty list builds N clients each attempting to
1877    /// bind. We can't reliably test the actual bind on CI (no
1878    /// loopback aliases), but a loopback IP is always bind-able.
1879    #[test]
1880    fn build_client_pool_one_per_source_ip() {
1881        let mut cfg = SelfTestConfig {
1882            target_url: "http://127.0.0.1:1".into(),
1883            timeout: Duration::from_millis(200),
1884            ..Default::default()
1885        };
1886        // Empty → one default client.
1887        assert_eq!(build_client_pool(&cfg).expect("default builds").len(), 1);
1888        // Non-empty → one per IP. Loopback bind is portable.
1889        cfg.source_ips = vec!["127.0.0.1".parse().unwrap()];
1890        assert_eq!(build_client_pool(&cfg).expect("bind loopback").len(), 1);
1891    }
1892
1893    /// Round 18.5 — geo IPs round-robin across operations. Hits an
1894    /// unreachable target so we can inspect the case outcomes; the
1895    /// point is to confirm `op_headers` carried the geo IP through
1896    /// (CaseOutcome doesn't surface headers directly, so we just
1897    /// verify the run completes without panicking and the result
1898    /// shape is correct when source_ips is non-empty too).
1899    #[tokio::test]
1900    async fn run_self_test_with_geo_source_completes() {
1901        let cfg = SelfTestConfig {
1902            target_url: "http://127.0.0.1:1".into(),
1903            timeout: Duration::from_millis(200),
1904            geo_source_ips: vec![
1905                "203.0.113.1".parse().unwrap(),
1906                "203.0.113.2".parse().unwrap(),
1907            ],
1908            ..Default::default()
1909        };
1910        let ops = vec![
1911            op("GET", "/a", None, vec![], vec![], vec![]),
1912            op("GET", "/b", None, vec![], vec![], vec![]),
1913            op("GET", "/c", None, vec![], vec![], vec![]),
1914        ];
1915        let report = run_self_test(&ops, &cfg).await.expect("client builds");
1916        assert_eq!(report.operations.len(), 3);
1917    }
1918
1919    /// Round 24 (f) — Srikanth saw the geo header on positive probes
1920    /// only; the four negative-probe call sites were passing
1921    /// `op.header_params` directly instead of `op_headers`, so the
1922    /// geo IP got dropped. This test runs a self-test that includes
1923    /// negative probes (uri-too-long, missing-query, etc.) under
1924    /// `--conformance-self-test-capture`, then asserts that EVERY
1925    /// captured probe (positive AND negative) carries one of the
1926    /// configured forwarded-IP headers.
1927    #[tokio::test]
1928    async fn geo_headers_present_on_every_probe_with_capture() {
1929        let sink: Arc<Mutex<Vec<CaseCapture>>> = Arc::new(Mutex::new(Vec::new()));
1930        let cfg = SelfTestConfig {
1931            target_url: "http://127.0.0.1:1".into(),
1932            timeout: Duration::from_millis(50),
1933            geo_source_ips: vec!["203.0.113.5".parse().unwrap()],
1934            capture: Some(sink.clone()),
1935            ..Default::default()
1936        };
1937        // An operation rich enough to trip several negative-probe
1938        // branches: header param (→ missing-header), query param
1939        // (→ missing-query), and a sample body (→ schema mutations
1940        // wouldn't fire without a schema, but uri-too-long always
1941        // does).
1942        let ops = vec![op(
1943            "GET",
1944            "/items",
1945            Some("{}"),
1946            vec![("id", "1")],
1947            vec![("X-Trace", "x")],
1948            vec![],
1949        )];
1950        let _ = run_self_test(&ops, &cfg).await.expect("client builds");
1951        let captures = sink.lock().unwrap();
1952        assert!(!captures.is_empty(), "self-test should record probes");
1953        // For every captured probe, at least one of the default geo
1954        // headers must be present and equal to the configured IP.
1955        let geo_headers: std::collections::HashSet<&str> =
1956            ["X-Forwarded-For", "True-Client-IP", "CF-Connecting-IP"].into_iter().collect();
1957        for c in captures.iter() {
1958            let has_geo = c
1959                .request_headers
1960                .iter()
1961                .any(|(k, v)| geo_headers.contains(k.as_str()) && v == "203.0.113.5");
1962            assert!(
1963                has_geo,
1964                "probe `{}` is missing the geo IP header; got headers: {:?}",
1965                c.label, c.request_headers
1966            );
1967        }
1968    }
1969
1970    /// Round 25 (k) — operations with a JSON request body now get four
1971    /// content-type-swap probes (xml / yaml / multipart / urlencoded).
1972    /// Verify they:
1973    ///   1. fire only when the operation declares a JSON body
1974    ///   2. carry the wrong Content-Type the probe is testing for
1975    ///   3. don't fire on body-less operations
1976    #[tokio::test]
1977    async fn content_type_swap_probes_fire_for_json_bodies() {
1978        let sink: Arc<Mutex<Vec<CaseCapture>>> = Arc::new(Mutex::new(Vec::new()));
1979        let cfg = SelfTestConfig {
1980            target_url: "http://127.0.0.1:1".into(),
1981            timeout: Duration::from_millis(50),
1982            capture: Some(sink.clone()),
1983            ..Default::default()
1984        };
1985        let ops = vec![
1986            op("POST", "/users", Some("{\"name\":\"a\"}"), vec![], vec![], vec![]),
1987            op("GET", "/ping", None, vec![], vec![], vec![]),
1988        ];
1989        let _ = run_self_test(&ops, &cfg).await.expect("client builds");
1990        let captures = sink.lock().unwrap();
1991
1992        let swap_labels: Vec<&str> = captures
1993            .iter()
1994            .filter(|c| c.label.starts_with("request-body:content-type-mismatch:"))
1995            .map(|c| c.label.as_str())
1996            .collect();
1997        assert_eq!(
1998            swap_labels.len(),
1999            4,
2000            "expected 4 content-type-swap probes (one per variant), got: {swap_labels:?}"
2001        );
2002        let expected_labels = [
2003            "request-body:content-type-mismatch:xml",
2004            "request-body:content-type-mismatch:yaml",
2005            "request-body:content-type-mismatch:multipart",
2006            "request-body:content-type-mismatch:urlencoded",
2007        ];
2008        for want in expected_labels {
2009            assert!(swap_labels.contains(&want), "missing swap probe `{want}`");
2010        }
2011
2012        // Each swap probe must carry the wrong Content-Type it's
2013        // testing for — that's the whole point.
2014        for c in captures.iter() {
2015            let Some(suffix) = c.label.strip_prefix("request-body:content-type-mismatch:") else {
2016                continue;
2017            };
2018            let want_ct = match suffix {
2019                "xml" => "application/xml",
2020                "yaml" => "application/yaml",
2021                "multipart" => "multipart/form-data",
2022                "urlencoded" => "application/x-www-form-urlencoded",
2023                _ => continue,
2024            };
2025            let got_ct = c
2026                .request_headers
2027                .iter()
2028                .find(|(k, _)| k.eq_ignore_ascii_case("content-type"))
2029                .map(|(_, v)| v.as_str())
2030                .unwrap_or("");
2031            assert_eq!(got_ct, want_ct, "swap probe `{}` sent wrong CT", c.label);
2032        }
2033
2034        // The body-less operation must NOT produce content-type-swap
2035        // probes (no body → no content type to lie about).
2036        let body_less_swaps = captures
2037            .iter()
2038            .filter(|c| {
2039                c.label.starts_with("request-body:content-type-mismatch:")
2040                    && c.url.ends_with("/ping")
2041            })
2042            .count();
2043        assert_eq!(
2044            body_less_swaps, 0,
2045            "GET /ping has no request body; should not produce content-type-swap probes"
2046        );
2047    }
2048
2049    /// Round 27 (k variant b) — Srikanth's round-23 follow-up on (k):
2050    /// JSON envelope with embedded non-JSON field values. For each
2051    /// JSON-body operation, four extra probes fire that send valid
2052    /// JSON with an XML/YAML/multipart/urlencoded snippet stuffed
2053    /// into a string field. Content-Type stays `application/json`;
2054    /// expected is 2xx-3xx (the body parses); a 5xx flags a server
2055    /// that crashed on the embedded content.
2056    #[tokio::test]
2057    async fn embedded_content_probes_fire_with_honest_content_type() {
2058        let sink: Arc<Mutex<Vec<CaseCapture>>> = Arc::new(Mutex::new(Vec::new()));
2059        let cfg = SelfTestConfig {
2060            target_url: "http://127.0.0.1:1".into(),
2061            timeout: Duration::from_millis(50),
2062            capture: Some(sink.clone()),
2063            ..Default::default()
2064        };
2065        let ops = vec![op(
2066            "POST",
2067            "/users",
2068            Some("{\"name\":\"alice\",\"age\":30}"),
2069            vec![],
2070            vec![],
2071            vec![],
2072        )];
2073        let _ = run_self_test(&ops, &cfg).await.expect("client builds");
2074        let captures = sink.lock().unwrap();
2075        let embedded: Vec<&CaseCapture> = captures
2076            .iter()
2077            .filter(|c| c.label.starts_with("request-body:embedded-content:"))
2078            .collect();
2079        assert_eq!(
2080            embedded.len(),
2081            4,
2082            "expected 4 embedded-content probes, got: {:?}",
2083            embedded.iter().map(|c| &c.label).collect::<Vec<_>>()
2084        );
2085        // Every embedded probe must carry the honest application/json
2086        // Content-Type (NOT lie like the variant-a content-type-swap
2087        // probes do) and a request body that still parses as JSON.
2088        for c in &embedded {
2089            let ct = c
2090                .request_headers
2091                .iter()
2092                .find(|(k, _)| k.eq_ignore_ascii_case("content-type"))
2093                .map(|(_, v)| v.as_str())
2094                .unwrap_or("");
2095            assert!(
2096                ct.contains("application/json"),
2097                "embedded probe `{}` should keep Content-Type honest, got {ct}",
2098                c.label
2099            );
2100            let body = c.request_body.as_deref().unwrap_or("");
2101            assert!(
2102                serde_json::from_str::<serde_json::Value>(body).is_ok(),
2103                "embedded probe `{}` body should still be valid JSON, got: {body}",
2104                c.label
2105            );
2106        }
2107    }
2108
2109    /// `embed_payload_in_first_string_field` walks objects depth-first
2110    /// and replaces only the FIRST string-valued leaf, leaving the
2111    /// surrounding structure intact.
2112    #[test]
2113    fn embed_payload_replaces_first_string_only() {
2114        let sample = r#"{"name":"alice","age":30,"tags":["admin","user"]}"#;
2115        let mutated = embed_payload_in_first_string_field(sample, "<x/>");
2116        let v: serde_json::Value = serde_json::from_str(&mutated).unwrap();
2117        assert_eq!(v["name"], serde_json::json!("<x/>"));
2118        // age stays an integer (not stringified by the mutation).
2119        assert_eq!(v["age"], serde_json::json!(30));
2120        // tags array's strings stay untouched (we only replace the
2121        // first encountered string leaf, depth-first).
2122        assert_eq!(v["tags"][0], serde_json::json!("admin"));
2123        assert_eq!(v["tags"][1], serde_json::json!("user"));
2124    }
2125
2126    /// When the sample has NO string field, the helper falls back to
2127    /// `{"data": "<snippet>"}` so the probe still has something to
2128    /// POST. The fallback must produce valid JSON regardless of what
2129    /// characters the snippet contains.
2130    #[test]
2131    fn embed_payload_falls_back_when_no_string_field() {
2132        let no_strings = r#"{"a":1,"b":[2,3]}"#;
2133        let mutated = embed_payload_in_first_string_field(no_strings, "<x><y></y></x>");
2134        let v: serde_json::Value = serde_json::from_str(&mutated).unwrap();
2135        assert_eq!(v["data"], serde_json::json!("<x><y></y></x>"));
2136    }
2137
2138    #[test]
2139    fn embed_payload_handles_invalid_json_sample() {
2140        let not_json = "garbage";
2141        let mutated = embed_payload_in_first_string_field(not_json, "a=1&b=2");
2142        let v: serde_json::Value = serde_json::from_str(&mutated).unwrap();
2143        assert_eq!(v["data"], serde_json::json!("a=1&b=2"));
2144    }
2145
2146    /// Round 26 — Srikanth saw `at /: Type { kind: Single` in his
2147    /// 0.3.169 capture for the vCenter `infraprofile/configs` 202
2148    /// response (spec promised `type: string`, server returned a
2149    /// JSON object). The output was a broken-syntax debug string.
2150    /// This test reproduces his exact spec+body and asserts the
2151    /// message is readable.
2152    #[test]
2153    fn response_schema_error_message_is_readable() {
2154        let schema = serde_json::json!({"type": "string"});
2155        let body = r#"{"data":{},"id":"generated_id","status":"created"}"#;
2156        let err = validate_body_against_schema(body, &schema).expect("type-mismatch fires");
2157        // The message must NOT contain Rust debug syntax leftovers
2158        // ("Type { kind:", trailing "{" or "(" tokens). It SHOULD say
2159        // what type was expected.
2160        assert!(!err.contains("Type { kind"), "stale debug output: {err}");
2161        assert!(!err.contains("{ kind:"), "stale debug output: {err}");
2162        assert!(err.contains("string"), "should name expected type: {err}");
2163        // Round 29 — Srikanth on 0.3.172 was confused by `at /:`,
2164        // thinking it pointed to the URL path. The new format
2165        // explicitly says "response body root" for the root case
2166        // (and "response body at /<pointer>" for nested fields).
2167        assert!(
2168            err.contains("response body root"),
2169            "should label root explicitly so reader knows it's not the URL: {err}"
2170        );
2171        // Round 28 — Srikanth wanted the expected schema embedded
2172        // in the message so it reads as 'expected schema {"type":"string"}'.
2173        assert!(
2174            err.contains("expected schema") && err.contains("\"type\":\"string\""),
2175            "should include expected schema JSON: {err}"
2176        );
2177    }
2178
2179    /// Round 29 — for non-root paths the format reads
2180    /// "response body at /name: ...". Catches the case where the
2181    /// root rewording accidentally dropped the JSON-pointer for
2182    /// nested fields.
2183    #[test]
2184    fn response_schema_error_uses_response_body_prefix_for_nested_paths() {
2185        let schema = serde_json::json!({
2186            "type": "object",
2187            "required": ["name"],
2188            "properties": {"name": {"type": "string"}}
2189        });
2190        let body = r#"{"name": 123}"#;
2191        let err = validate_body_against_schema(body, &schema).expect("type-mismatch fires");
2192        assert!(
2193            err.contains("response body at /name"),
2194            "nested path should read 'response body at /name': {err}"
2195        );
2196        assert!(!err.contains("response body root"), "wrong label for nested: {err}");
2197    }
2198
2199    #[test]
2200    fn response_schema_error_required_field_is_readable() {
2201        let schema = serde_json::json!({
2202            "type": "object",
2203            "required": ["id"],
2204            "properties": {"id": {"type": "integer"}}
2205        });
2206        let body = r#"{"other": 1}"#;
2207        let err = validate_body_against_schema(body, &schema).expect("required-missing fires");
2208        assert!(err.contains("required field missing"), "{err}");
2209        assert!(err.contains("id"), "{err}");
2210    }
2211
2212    #[test]
2213    fn response_schema_error_none_on_match() {
2214        let schema = serde_json::json!({"type": "string"});
2215        assert_eq!(validate_body_against_schema("\"hello\"", &schema), None);
2216    }
2217
2218    #[test]
2219    fn json_serialises_report() {
2220        let r = SelfTestReport {
2221            positive_pass: 1,
2222            positive_fail: 0,
2223            negative_caught: BTreeMap::new(),
2224            negative_missed: BTreeMap::new(),
2225            operations: vec![OperationResult {
2226                method: "GET".into(),
2227                path: "/x".into(),
2228                positive: Some(CaseOutcome {
2229                    label: "positive".into(),
2230                    expected_4xx: false,
2231                    actual_status: 200,
2232                    passed: true,
2233                }),
2234                negatives: Vec::new(),
2235            }],
2236        };
2237        let json = serde_json::to_value(&r).expect("serialises");
2238        assert_eq!(json["positive_pass"], serde_json::json!(1));
2239        assert_eq!(json["operations"][0]["positive"]["actual_status"], serde_json::json!(200));
2240    }
2241}