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 /// Round 33 (#823) — human-readable label for the OpenAPI spec
120 /// this run is exercising. Stamped on every `CaseCapture` so the
121 /// per-endpoint summary can attribute rows back to a spec in
122 /// multi-spec / multi-target benches. `None` when the bench didn't
123 /// track a spec path.
124 pub spec_label: Option<String>,
125 /// Round 47 (#79) — Srikanth on 0.3.191: "I did not see network
126 /// logs in the mockforge bench and conformance traffic if used
127 /// the [self-test] command". The r46 wire-level event sink only
128 /// existed on the native conformance executor; this matches it on
129 /// the self-test side. When `Some`, every `reqwest::Error` from
130 /// `send().await` is classified and pushed to this sink; caller
131 /// drains it into `conformance-network-events.json` next to the
132 /// JSONL capture. None → no extra allocations on the hot path.
133 pub network_events: Option<Arc<Mutex<Vec<NetworkEvent>>>>,
134 /// Round 49 (#79) — current iteration number (1-indexed). The
135 /// runner stamps it on every CaseCapture so the JSONL line and
136 /// violation rows carry the iteration counter. Defaults to 1
137 /// for non-looping runs.
138 pub current_iteration: u32,
139}
140
141/// Round 47 (#79) — wire-level network event captured by the self-test
142/// driver. Same shape as the native executor's `NetworkEvent` so
143/// downstream tooling can consume one file across executor variants.
144#[derive(Debug, Clone, serde::Serialize)]
145pub struct NetworkEvent {
146 pub timestamp: chrono::DateTime<chrono::Utc>,
147 pub check: String,
148 pub method: String,
149 pub url: String,
150 pub kind: String,
151 pub message: String,
152}
153
154/// Round 23 (c-iii) — one captured request/response pair, one per
155/// probe (positive or negative). Serialised as a JSON line in
156/// `conformance-self-test-requests.jsonl`. Headers are kept as
157/// `BTreeMap` for stable ordering. Bodies are truncated to
158/// `CAPTURE_BODY_CAP_BYTES`; `*_truncated` flags whether more was
159/// dropped.
160#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
161pub struct CaseCapture {
162 pub label: String,
163 pub method: String,
164 pub url: String,
165 pub request_headers: BTreeMap<String, String>,
166 pub request_body: Option<String>,
167 pub request_body_truncated: bool,
168 pub response_status: u16,
169 pub response_headers: BTreeMap<String, String>,
170 pub response_body: Option<String>,
171 pub response_body_truncated: bool,
172 pub error: Option<String>,
173 /// Round 25 — when `validate_response_schemas` is on and the spec
174 /// declares a schema for `response_status`, this carries the
175 /// validation message (or None when the body matched, or no schema
176 /// was declared for that status). Serialised verbatim in the JSONL
177 /// and rendered in the HTML viewer.
178 #[serde(default, skip_serializing_if = "Option::is_none")]
179 pub response_schema_error: Option<String>,
180 /// Round 28 — Srikanth's "Is it possible to put expected response
181 /// code status in both jsonl and jsonl report" ask. Human-readable
182 /// expected status range: `"2xx-3xx"` for positive probes,
183 /// `"4xx"` for negatives. Lets users `jq` for misses
184 /// (`.response_status as $s | .expected_status_range == "4xx"
185 /// and ($s < 400 or $s >= 500)`) and powers the HTML viewer's
186 /// "show mismatches only" filter.
187 #[serde(default)]
188 pub expected_status_range: String,
189 /// Round 33 (#823) — the spec's path template (e.g.
190 /// `/users/{id}`) before path-param substitution. Lets the
191 /// per-endpoint summary collapse `/users/X` and `/users/Y` into
192 /// one row. Empty string when the call site predates this field
193 /// (older `CaseCapture` payloads on disk also deserialise OK).
194 #[serde(default)]
195 pub path_template: String,
196 /// Round 33 (#823) — basename (or fallback to full path) of the
197 /// OpenAPI spec file this probe came from. Lets multi-spec runs
198 /// attribute rows back to the spec they came from. `None` when
199 /// the bench didn't track a spec path.
200 #[serde(default, skip_serializing_if = "Option::is_none")]
201 pub spec_label: Option<String>,
202 /// Round 36 (#876) — mockforge version that ran the probe.
203 /// Stamped from `CARGO_PKG_VERSION` at compile time. Also sent
204 /// as the `X-Mockforge-Client-Version` request header so a
205 /// matching `ServerConformanceViolation.client_mockforge_version`
206 /// can be cross-correlated. Empty string when the capture
207 /// pre-dates this field.
208 #[serde(default)]
209 pub mockforge_version: String,
210 /// Round 36 (#876) — wall-clock moment the bench driver sent the
211 /// request, as RFC3339 / ISO-8601. Also sent as the
212 /// `X-Mockforge-Client-Sent-At` request header so the server-side
213 /// `ServerConformanceViolation.client_sent_at` carries the same
214 /// value. Empty string when the capture pre-dates this field.
215 #[serde(default)]
216 pub client_sent_at: String,
217 /// Round 49 (#79) — Srikanth on 0.3.193: "Is it possible to
218 /// differentiate in the logs what is the iteration count that
219 /// way I will know how many requests are sent with that
220 /// violation." Stamped from the
221 /// `SelfTestConfig::current_iteration` field by the outer loop
222 /// in command.rs before each call to `run_self_test_with_deadline`.
223 /// 1-indexed; defaults to 1 for single-iteration runs so an older
224 /// JSONL that didn't carry the field deserialises as iteration 1.
225 #[serde(default = "default_iteration")]
226 pub iteration: u32,
227}
228
229fn default_iteration() -> u32 {
230 1
231}
232
233impl Default for SelfTestConfig {
234 fn default() -> Self {
235 Self {
236 target_url: "http://localhost:3000".into(),
237 skip_tls_verify: false,
238 timeout: Duration::from_secs(15),
239 extra_headers: Vec::new(),
240 delay_between_requests: Duration::from_millis(0),
241 base_path: None,
242 source_ips: Vec::new(),
243 geo_source_ips: Vec::new(),
244 geo_source_headers: default_geo_source_headers(),
245 capture: None,
246 validate_response_schemas: false,
247 spec_label: None,
248 network_events: None,
249 current_iteration: 1,
250 }
251 }
252}
253
254/// Truncate `body` to `CAPTURE_BODY_CAP_BYTES` on a UTF-8 boundary,
255/// returning the trimmed string and whether truncation occurred. Used
256/// for both request and response bodies in the capture sink.
257fn truncate_body_for_capture(body: &str) -> (String, bool) {
258 if body.len() <= CAPTURE_BODY_CAP_BYTES {
259 return (body.to_string(), false);
260 }
261 let mut end = CAPTURE_BODY_CAP_BYTES;
262 while end > 0 && !body.is_char_boundary(end) {
263 end -= 1;
264 }
265 (body[..end].to_string(), true)
266}
267
268/// Default forwarded-IP header set. Covers the three conventions a
269/// real GEODB front-end is likely to read in this order of
270/// preference: Cloudflare (`CF-Connecting-IP`), Akamai/CloudFront
271/// (`True-Client-IP`), then the de-facto standard
272/// `X-Forwarded-For`. Override via `--geo-source-header` to test a
273/// specific stack.
274pub fn default_geo_source_headers() -> Vec<String> {
275 vec![
276 "X-Forwarded-For".to_string(),
277 "True-Client-IP".to_string(),
278 "CF-Connecting-IP".to_string(),
279 ]
280}
281
282/// Outcome of a single test case (positive or negative).
283#[derive(Debug, Clone, serde::Serialize)]
284pub struct CaseOutcome {
285 pub label: String,
286 pub expected_4xx: bool,
287 pub actual_status: u16,
288 /// True when the response status matches expectation
289 /// (positive → 2xx-3xx, negative → 4xx).
290 pub passed: bool,
291}
292
293/// All cases run against one annotated operation.
294#[derive(Debug, Clone, serde::Serialize)]
295pub struct OperationResult {
296 pub method: String,
297 pub path: String,
298 pub positive: Option<CaseOutcome>,
299 pub negatives: Vec<CaseOutcome>,
300}
301
302/// Summary report rolled up across all operations.
303#[derive(Debug, Default, Clone, serde::Serialize)]
304pub struct SelfTestReport {
305 pub positive_pass: usize,
306 pub positive_fail: usize,
307 /// Per category: count of negative cases the server correctly
308 /// rejected with a 4xx (we caught the spec violation).
309 pub negative_caught: BTreeMap<String, usize>,
310 /// Per category: count of negative cases that should have been
311 /// rejected but came back with a non-4xx (validator gap).
312 pub negative_missed: BTreeMap<String, usize>,
313 pub operations: Vec<OperationResult>,
314}
315
316/// Round 58 (#79) — an unambiguous, no-analysis-needed problem surfaced by the
317/// self-test. Srikanth on 0.3.205: "Is it possible to give another option ...
318/// that should say for sure this is an issue. Currently both caught and missed
319/// needs manual intervention and deep analysis ... very time consuming."
320#[derive(Debug, Clone, serde::Serialize)]
321pub struct DefiniteIssue {
322 pub method: String,
323 pub path: String,
324 /// `valid_request_rejected` (target refused a spec-valid request) or
325 /// `server_error` (target returned 5xx / crashed instead of a clean reply).
326 pub kind: String,
327 pub status: u16,
328 pub detail: String,
329}
330
331impl SelfTestReport {
332 /// All-pass means every positive case got 2xx-3xx and every
333 /// negative case got 4xx.
334 pub fn all_passed(&self) -> bool {
335 self.positive_fail == 0 && self.negative_missed.values().sum::<usize>() == 0
336 }
337
338 /// Round 58 (#79) — the subset of findings that are unambiguously wrong, so
339 /// a user does not have to eyeball every caught/missed row across every API.
340 /// Two classes need no judgement:
341 /// 1. a POSITIVE (spec-valid) request the target REJECTED (4xx) — it broke
342 /// a legitimate call;
343 /// 2. ANY probe, positive or negative, that drew a 5xx — the target
344 /// crashed instead of replying cleanly (a bad request should get a
345 /// clean 4xx, never a 500).
346 /// Deliberately EXCLUDES "missed" negatives on spec-valid probes: those are
347 /// the ones that genuinely need per-probe analysis (see the caught/missed
348 /// legend), so keeping them out is the whole point of this view.
349 pub fn definite_issues(&self) -> Vec<DefiniteIssue> {
350 let mut issues = Vec::new();
351 for op in &self.operations {
352 if let Some(pos) = &op.positive {
353 if !pos.passed {
354 let (kind, detail) = if pos.actual_status >= 500 {
355 (
356 "server_error",
357 "target returned 5xx for a spec-valid request (crashed instead of serving it)"
358 .to_string(),
359 )
360 } else {
361 (
362 "valid_request_rejected",
363 "target refused a spec-valid request (a legitimate call it should accept)"
364 .to_string(),
365 )
366 };
367 issues.push(DefiniteIssue {
368 method: op.method.clone(),
369 path: op.path.clone(),
370 kind: kind.to_string(),
371 status: pos.actual_status,
372 detail,
373 });
374 }
375 }
376 for neg in &op.negatives {
377 if neg.actual_status >= 500 {
378 issues.push(DefiniteIssue {
379 method: op.method.clone(),
380 path: op.path.clone(),
381 kind: "server_error".to_string(),
382 status: neg.actual_status,
383 detail: format!(
384 "target returned 5xx for the '{}' negative probe (should reject a bad request with a clean 4xx, not crash)",
385 neg.label
386 ),
387 });
388 }
389 }
390 }
391 issues
392 }
393
394 /// Round 18.1 — detect the "self-test target is misconfigured"
395 /// case where every positive failed with the *same* status code.
396 /// The classic example: `--base-path /api` was forgotten so every
397 /// request hits a path the server doesn't know and returns 404.
398 /// Pre-warning, the user saw all-green negative buckets (because
399 /// "missing route" 404s look like "validator rejected") and no
400 /// indication that the run was meaningless. Returns Some(status)
401 /// when ≥10 positives all failed with the same status, else None.
402 pub fn detect_target_misconfiguration(&self) -> Option<u16> {
403 if self.positive_pass > 0 || self.positive_fail < 10 {
404 return None;
405 }
406 let mut seen: Option<u16> = None;
407 for op in &self.operations {
408 let Some(p) = &op.positive else {
409 continue;
410 };
411 if p.passed {
412 return None;
413 }
414 match seen {
415 None => seen = Some(p.actual_status),
416 Some(s) if s != p.actual_status => return None,
417 _ => {}
418 }
419 }
420 seen
421 }
422
423 /// Round 47 (#79) — fold a second iteration of the self-test into
424 /// this report so multi-iteration runs aggregate counters across
425 /// passes. Per-category caught / missed counters sum; positive
426 /// counters sum; the `operations` vec records every probe outcome
427 /// so the iteration-N misconfiguration detector still works. Used
428 /// by command.rs's `--conformance-self-test-iterations` /
429 /// `--conformance-self-test-duration` loop.
430 pub fn merge_iteration(&mut self, other: SelfTestReport) {
431 self.positive_pass = self.positive_pass.saturating_add(other.positive_pass);
432 self.positive_fail = self.positive_fail.saturating_add(other.positive_fail);
433 for (k, v) in other.negative_caught {
434 let slot = self.negative_caught.entry(k).or_insert(0);
435 *slot = slot.saturating_add(v);
436 }
437 for (k, v) in other.negative_missed {
438 let slot = self.negative_missed.entry(k).or_insert(0);
439 *slot = slot.saturating_add(v);
440 }
441 self.operations.extend(other.operations);
442 }
443
444 /// Human-readable summary string. One line for positives, one per
445 /// category for negatives. Designed to slot into existing
446 /// `TerminalReporter` output.
447 pub fn render_summary(&self) -> String {
448 let mut out = String::new();
449 out.push_str(&format!(
450 "Positives: {} pass / {} fail\n",
451 self.positive_pass, self.positive_fail
452 ));
453 let mut keys: Vec<&String> =
454 self.negative_caught.keys().chain(self.negative_missed.keys()).collect();
455 keys.sort();
456 keys.dedup();
457 // Round 57 (#79) — Srikanth asked what "caught" vs "missed" mean.
458 // Spell it out once, inline, so the console output is self-explanatory.
459 if !keys.is_empty() {
460 out.push_str(
461 " (negatives are deliberately-bad requests that SHOULD draw a 4xx from the TARGET: \
462 \"caught\" = the target rejected it, \"missed\" = the target accepted it. \
463 A high \"missed\" is not automatically a target bug: many probes are spec-valid by \
464 construction, e.g. a string field accepts any string or an optional query param can \
465 be dropped, so the contract permits them; those are the parameter_negative_probe / \
466 informational rows in conformance-request-violations.json.)\n",
467 );
468 }
469 for cat in keys {
470 let caught = self.negative_caught.get(cat).copied().unwrap_or(0);
471 let missed = self.negative_missed.get(cat).copied().unwrap_or(0);
472 let mark = if missed == 0 { "✓" } else { "⚠" };
473 out.push_str(&format!(
474 "Negatives [{}]: {} caught / {} missed {}\n",
475 cat, caught, missed, mark
476 ));
477 }
478 // Round 58 (#79) — surface the unambiguous problems up front so they
479 // don't have to be dug out of the caught/missed rollup. Capped in the
480 // console; the full set is in conformance-definite-issues.json.
481 let issues = self.definite_issues();
482 if issues.is_empty() {
483 out.push_str(
484 "Definite issues: none (no spec-valid request was rejected and no probe drew a 5xx)\n",
485 );
486 } else {
487 out.push_str(&format!(
488 "Definite issues ({}) — unambiguous, no per-probe analysis needed (full list in conformance-definite-issues.json):\n",
489 issues.len()
490 ));
491 const CAP: usize = 20;
492 for iss in issues.iter().take(CAP) {
493 out.push_str(&format!(
494 " {} {} -> {} [{}]: {}\n",
495 iss.method, iss.path, iss.status, iss.kind, iss.detail
496 ));
497 }
498 if issues.len() > CAP {
499 out.push_str(&format!(" ... and {} more\n", issues.len() - CAP));
500 }
501 }
502 out
503 }
504}
505
506/// Execute the self-test plan against `config.target_url` for every
507/// `AnnotatedOperation`. Returns the aggregated report; callers
508/// decide how to display it (e.g. via `render_summary` or by writing
509/// the JSON serialisation to disk).
510pub async fn run_self_test(
511 operations: &[AnnotatedOperation],
512 config: &SelfTestConfig,
513) -> Result<SelfTestReport, reqwest::Error> {
514 run_self_test_with_deadline(operations, config, None).await
515}
516
517/// Round 49 (#79) — Srikanth on 0.3.193: `--conformance-self-test-
518/// duration 5m` ran 5:46 because the outer iteration loop in
519/// command.rs only checks the deadline AFTER a full matrix pass
520/// completes. For long iterations this can overshoot by minutes,
521/// which breaks automation that relies on a fixed wall-clock budget.
522/// New optional `deadline` parameter lets the runner break out
523/// mid-iteration once the deadline elapses; returns the partial
524/// report with whatever operations finished before the deadline.
525pub async fn run_self_test_with_deadline(
526 operations: &[AnnotatedOperation],
527 config: &SelfTestConfig,
528 deadline: Option<std::time::Instant>,
529) -> Result<SelfTestReport, reqwest::Error> {
530 // Round 18.5 — build a client pool when `source_ips` is set,
531 // one reqwest::Client per IP, each bound to its local address.
532 // Operations round-robin through the pool. Empty pool → single
533 // default client (the pre-18.5 behaviour).
534 let clients = build_client_pool(config)?;
535 let client_cursor = AtomicUsize::new(0);
536 let geo_cursor = AtomicUsize::new(0);
537
538 let mut report = SelfTestReport::default();
539 for op in operations {
540 // Round 49 — mid-iteration deadline check. Breaks out of the
541 // per-operation loop the moment the wall-clock budget
542 // elapses, so a 5m budget never overshoots by more than one
543 // probe's round-trip.
544 if let Some(d) = deadline {
545 if std::time::Instant::now() >= d {
546 break;
547 }
548 }
549 let client_idx = client_cursor.fetch_add(1, Ordering::Relaxed) % clients.len();
550 let client = &clients[client_idx];
551 let geo_ip = if config.geo_source_ips.is_empty() {
552 None
553 } else {
554 let idx = geo_cursor.fetch_add(1, Ordering::Relaxed) % config.geo_source_ips.len();
555 Some(config.geo_source_ips[idx])
556 };
557 let result = test_operation(client, config, op, geo_ip).await;
558 if let Some(p) = &result.positive {
559 if p.passed {
560 report.positive_pass += 1;
561 } else {
562 report.positive_fail += 1;
563 }
564 }
565 for neg in &result.negatives {
566 let cat = neg.label.split(':').next().unwrap_or("other").to_string();
567 if neg.passed {
568 *report.negative_caught.entry(cat).or_insert(0) += 1;
569 } else {
570 *report.negative_missed.entry(cat).or_insert(0) += 1;
571 }
572 }
573 report.operations.push(result);
574 if !config.delay_between_requests.is_zero() {
575 tokio::time::sleep(config.delay_between_requests).await;
576 }
577 }
578 Ok(report)
579}
580
581/// Round 18.5 — append GEODB forwarded-IP headers to the
582/// operation's declared headers. Returns the original vec untouched
583/// when `geo_ip` is None or `geo_headers` is empty.
584///
585/// If the operation already declares one of the geo headers (rare
586/// but legal), we keep the operation's value — the caller's spec
587/// wins.
588fn effective_op_headers(
589 base: &[(String, String)],
590 geo_ip: Option<IpAddr>,
591 geo_headers: &[String],
592) -> Vec<(String, String)> {
593 let mut out = base.to_vec();
594 let Some(ip) = geo_ip else {
595 return out;
596 };
597 let value = ip.to_string();
598 for h in geo_headers {
599 // Case-insensitive duplicate check: don't override the
600 // spec's own declared value for the header.
601 if out.iter().any(|(k, _)| k.eq_ignore_ascii_case(h)) {
602 continue;
603 }
604 out.push((h.clone(), value.clone()));
605 }
606 out
607}
608
609/// Round 18.5 — build a pool of reqwest clients, one per declared
610/// source IP. Empty `source_ips` → a single default client.
611///
612/// The OS must already have each `source_ip` assigned to an
613/// interface; reqwest's `.local_address()` issues a `bind()` syscall
614/// at connect time, so an IP the kernel doesn't recognise surfaces
615/// as `EADDRNOTAVAIL` at request time, not at builder time.
616fn build_client_pool(config: &SelfTestConfig) -> Result<Vec<Client>, reqwest::Error> {
617 let make = |bind: Option<IpAddr>| -> Result<Client, reqwest::Error> {
618 let mut builder = Client::builder().timeout(config.timeout);
619 if config.skip_tls_verify {
620 builder = builder.danger_accept_invalid_certs(true);
621 }
622 if let Some(addr) = bind {
623 builder = builder.local_address(addr);
624 }
625 builder.build()
626 };
627 if config.source_ips.is_empty() {
628 Ok(vec![make(None)?])
629 } else {
630 config.source_ips.iter().map(|ip| make(Some(*ip))).collect()
631 }
632}
633
634async fn test_operation(
635 client: &Client,
636 config: &SelfTestConfig,
637 op: &AnnotatedOperation,
638 geo_ip: Option<IpAddr>,
639) -> OperationResult {
640 // Round 25 — track the sink length BEFORE we run any probes for
641 // this operation, so that after the probes finish we can mutate
642 // exactly the entries that belong to this op (the capture sink is
643 // shared but `run_self_test` iterates operations sequentially).
644 // Used by the response-schema validation pass below.
645 let sink_start = config.capture.as_ref().and_then(|s| s.lock().ok().map(|g| g.len()));
646
647 let url = build_url_with_base(
648 &config.target_url,
649 config.base_path.as_deref(),
650 &op.path,
651 &op.path_params,
652 );
653 let method = Method::from_bytes(op.method.to_uppercase().as_bytes()).unwrap_or(Method::GET);
654
655 // Round 34 (#828) — stamp every `CaseCapture` with the spec
656 // template PREFIXED by `--base-path`, so the per-endpoint
657 // summary's `path` column matches what the user sees in URLs
658 // and logs. Srikanth searched for `/api/appliance/access/...`
659 // and didn't find it because round 33 stored just `/appliance/
660 // access/...`. Same normalization as `build_url_with_base`:
661 // leading `/` auto-added, trailing `/` stripped, empty
662 // base_path → no prefix at all.
663 let path_template = {
664 // Round 55 — shared with build_url_with_base so `--base-path /`
665 // resolves to no prefix instead of a `//path` double slash.
666 let prefix = base_path_prefix(config.base_path.as_deref());
667 let path = if op.path.starts_with('/') {
668 op.path.clone()
669 } else {
670 format!("/{}", op.path)
671 };
672 format!("{prefix}{path}")
673 };
674
675 // Round 18.5 — pre-compute the operation's effective headers
676 // with the geo source IP baked in. Doing it once here keeps the
677 // per-case `send_case` calls below unchanged. When `geo_ip` is
678 // None the result equals `op.header_params`.
679 let op_headers = effective_op_headers(&op.header_params, geo_ip, &config.geo_source_headers);
680
681 // ── Positive case ────────────────────────────────────────────
682 let positive = send_case(
683 client,
684 config,
685 method.clone(),
686 &url,
687 "positive",
688 ExpectedOutcome::Success,
689 op.sample_body.as_deref(),
690 op.query_params.clone(),
691 op_headers.clone(),
692 &path_template,
693 )
694 .await;
695
696 // ── Negative cases ───────────────────────────────────────────
697 let mut negatives = Vec::new();
698
699 // (a) empty body when one is required.
700 //
701 // Round 16 — drop the `sample_body.is_some()` precondition. Operations
702 // whose body annotator couldn't synthesize a sample previously got
703 // zero negatives (so the self-test reported "all passing" even on
704 // POST /resource with a required body). The spec saying the operation
705 // *has* a request body is enough — an empty object is a valid
706 // negative regardless of whether we have a positive sample.
707 if op.request_body_content_type.is_some() {
708 negatives.push(
709 send_case(
710 client,
711 config,
712 method.clone(),
713 &url,
714 "request-body:empty",
715 ExpectedOutcome::ClientError,
716 Some("{}"),
717 op.query_params.clone(),
718 op_headers.clone(),
719 &path_template,
720 )
721 .await,
722 );
723
724 // (b) wrong-shaped body (array instead of object) — exercises
725 // top-level type validation independently of which fields are
726 // required.
727 negatives.push(
728 send_case(
729 client,
730 config,
731 method.clone(),
732 &url,
733 "request-body:wrong-type",
734 ExpectedOutcome::ClientError,
735 Some("[]"),
736 op.query_params.clone(),
737 op_headers.clone(),
738 &path_template,
739 )
740 .await,
741 );
742
743 // Round 25 (k) — content-type swap probes.
744 //
745 // For operations declaring `application/json` request bodies, send
746 // the SAME json payload (or a synthesised one) under four other
747 // content types: `application/xml`, `application/yaml`,
748 // `multipart/form-data`, `application/x-www-form-urlencoded`.
749 // The spec says the endpoint accepts only JSON, so a strict server
750 // should respond 415 Unsupported Media Type (or 400 if it tries
751 // to parse and fails). A 2xx means the server is accepting
752 // payloads outside its declared content negotiation, which is the
753 // failure mode behind a lot of "we crashed on a malformed XML
754 // upload" incidents.
755 //
756 // Variant (a) of Srikanth's round-23 g ask: lie about the
757 // Content-Type header. The body shape is honest JSON; only the
758 // header is swapped. Variant (b) (JSON envelope with embedded
759 // non-JSON field values) is deferred to round 26 because it
760 // requires a schema-aware field walker.
761 if op
762 .request_body_content_type
763 .as_deref()
764 .map(|ct| ct.contains("json"))
765 .unwrap_or(false)
766 {
767 let payload = op.sample_body.as_deref().unwrap_or("{}");
768 for (ct, label) in CONTENT_TYPE_SWAP_VARIANTS {
769 negatives.push(
770 send_case_with_extra(
771 client,
772 config,
773 method.clone(),
774 &url,
775 label,
776 ExpectedOutcome::ClientError,
777 Some(payload),
778 op.query_params.clone(),
779 // Strip any Content-Type already on the operation
780 // headers (the spec's positive value) so the
781 // probe's value is the only one the server sees.
782 op_headers
783 .iter()
784 .filter(|(k, _)| !k.eq_ignore_ascii_case("content-type"))
785 .cloned()
786 .collect(),
787 // The wrong Content-Type rides on `extra_headers`
788 // so it lands AFTER `send_case_with_extra`'s
789 // unconditional `application/json` insertion in
790 // request-body mode. Actually `send_case_with_extra`
791 // only sets Content-Type when a body is present
792 // AND there's no manual override; passing the
793 // override here wins because reqwest preserves
794 // the last-set header value.
795 vec![("Content-Type".to_string(), (*ct).to_string())],
796 &path_template,
797 )
798 .await,
799 );
800 }
801
802 // Round 27 (k variant b) — embedded non-JSON content
803 // inside a valid JSON envelope. Content-Type stays
804 // application/json (honest) and the body parses as JSON;
805 // only the string-valued payload changes. We expect 2xx-3xx
806 // because the envelope is spec-shape, so the probe surfaces
807 // servers that crash (5xx) trying to parse the embedded
808 // snippet as XML/YAML/etc. A 4xx is also a finding because
809 // it usually means the server's pattern/format validator
810 // tripped on the payload contents, but the user can decide
811 // from the JSONL whether that's a bug or correct narrow-
812 // string-field behaviour.
813 for (label, snippet) in EMBEDDED_CONTENT_VARIANTS {
814 let payload = op.sample_body.as_deref().unwrap_or("{}");
815 // Round 34 (#829) — skip the probe entirely when the
816 // positive sample has no string leaf we can mutate.
817 // The previous round-27 fallback `{"data": <snippet>}`
818 // produced a body that doesn't match the spec's actual
819 // schema for endpoints like vCenter's `consolecli` PUT
820 // (which wants `{enabled: bool}`), so the server
821 // correctly 400'd and the bench misreported the
822 // mismatch as an expectation failure.
823 let Some(body) = embed_payload_in_first_string_field(payload, snippet) else {
824 continue;
825 };
826 negatives.push(
827 send_case(
828 client,
829 config,
830 method.clone(),
831 &url,
832 label,
833 // expected_4xx=false: any non-2xx is a probe
834 // failure. 5xx in particular is "server panicked
835 // on the embedded content".
836 ExpectedOutcome::NotServerError,
837 Some(&body),
838 op.query_params.clone(),
839 op_headers.clone(),
840 &path_template,
841 )
842 .await,
843 );
844 }
845 }
846
847 // Round 17.2 — schema-aware negatives.
848 //
849 // When both a positive sample AND the resolved body schema are
850 // available, mutate the sample per-field (type mismatch,
851 // min/max bounds, pattern, enum out-of-range, required-field
852 // removal) and assert each is rejected with 4xx. Capped at
853 // SCHEMA_MUTATION_CAP per operation so a 100-property body
854 // doesn't explode the test matrix.
855 if let (Some(sample_str), Some(schema)) =
856 (op.sample_body.as_deref(), op.request_body_schema.as_ref())
857 {
858 if let Ok(sample) = serde_json::from_str::<serde_json::Value>(sample_str) {
859 let mutations = super::schema_mutator::mutate_body(&sample, schema);
860 for m in mutations.into_iter().take(SCHEMA_MUTATION_CAP) {
861 let body_str = serde_json::to_string(&m.body).unwrap_or_default();
862 negatives.push(
863 send_case(
864 client,
865 config,
866 method.clone(),
867 &url,
868 &m.label,
869 ExpectedOutcome::ClientError,
870 Some(&body_str),
871 op.query_params.clone(),
872 // Round 24 (f) — was `op.header_params`, which
873 // skipped the geo-IP header. Use `op_headers`
874 // so the geo IP rides with the negative probe
875 // too (positive vs negative coverage must be
876 // symmetric, otherwise a GEODB front-end sees
877 // the rotating IP only on positives).
878 op_headers.clone(),
879 &path_template,
880 )
881 .await,
882 );
883 }
884 }
885 }
886 }
887
888 // Round 17.2 — URI-length probe. Spec-agnostic but schema-aware in
889 // spirit: most servers cap URIs at 8 KB or so. Append a 9 KB query
890 // string to the URL and expect 414 URI Too Long (or 400). Skipped
891 // for operations that already have a heavy positive query.
892 {
893 let pad = "p=".to_string() + &"x".repeat(9_000);
894 let bad_url = if url.contains('?') {
895 format!("{url}&{pad}")
896 } else {
897 format!("{url}?{pad}")
898 };
899 negatives.push(
900 send_case(
901 client,
902 config,
903 method.clone(),
904 &bad_url,
905 "parameters:uri-too-long",
906 ExpectedOutcome::ClientError,
907 op.sample_body.as_deref(),
908 op.query_params.clone(),
909 // Round 24 (f) — see schema-mutation note above. Use
910 // `op_headers` (carries geo IP) instead of bare
911 // `op.header_params`.
912 op_headers.clone(),
913 &path_template,
914 )
915 .await,
916 );
917 }
918
919 // (e) Round 16 — path-param type probe. Send the first path
920 // parameter as a literal `"self-test-invalid-id"`: a string that
921 // contains hyphens, won't parse as an integer, won't parse as a
922 // UUID, and won't match any typical regex pattern. Operations
923 // whose spec types the param as `integer` or `string` with a
924 // `format`/`pattern` will catch this (caught: server returned
925 // 4xx); operations whose spec lets path params be free-form
926 // strings will let it through (missed: server returned 2xx).
927 // Either outcome is informative: a category that's all "missed"
928 // tells the user their spec is loose on path-param types, which
929 // is itself worth knowing. Addresses Srikanth's "always all
930 // passing" report — operations with a path param now produce at
931 // least one probe instead of zero.
932 if !op.path_params.is_empty() {
933 let mut url_with_placeholder = op.path.clone();
934 if let Some((first_name, _)) = op.path_params.first() {
935 // Substitute every other path-param with its sample so the
936 // route shape stays intact and only the first param is bad.
937 for (name, value) in op.path_params.iter().skip(1) {
938 if !value.is_empty() {
939 url_with_placeholder =
940 url_with_placeholder.replace(&format!("{{{name}}}"), value);
941 }
942 }
943 // Substitute the first param with a guaranteed-invalid
944 // sentinel that's unlikely to match any reasonable schema:
945 // contains characters disallowed in numeric IDs *and* UUIDs.
946 url_with_placeholder =
947 url_with_placeholder.replace(&format!("{{{first_name}}}"), "self-test-invalid-id");
948 // Round 18.1 — honour `base_path` here too, otherwise the
949 // probe URL differs from the positive case and the
950 // resulting 404 is misattributed to "bad path param".
951 let bad_url = build_url_with_base(
952 &config.target_url,
953 config.base_path.as_deref(),
954 &url_with_placeholder,
955 &[],
956 );
957 negatives.push(
958 send_case(
959 client,
960 config,
961 method.clone(),
962 &bad_url,
963 "parameters:bad-path-param",
964 ExpectedOutcome::ClientError,
965 op.sample_body.as_deref(),
966 op.query_params.clone(),
967 op_headers.clone(),
968 &path_template,
969 )
970 .await,
971 );
972 }
973 }
974
975 // (c) drop the first required query param
976 if !op.query_params.is_empty() {
977 let mut q = op.query_params.clone();
978 q.remove(0);
979 negatives.push(
980 send_case(
981 client,
982 config,
983 method.clone(),
984 &url,
985 "parameters:missing-query",
986 ExpectedOutcome::ClientError,
987 op.sample_body.as_deref(),
988 q,
989 op_headers.clone(),
990 &path_template,
991 )
992 .await,
993 );
994 }
995
996 // (s) Round 17.3 — security probes.
997 //
998 // Operations whose spec declares a security requirement get a
999 // dedicated set of negatives. The point isn't to test whether the
1000 // server's *real* auth works (the positive case already does that
1001 // via `extra_headers`) — it's to check whether deliberately-bad
1002 // credentials are still rejected, which is exactly the failure
1003 // mode that lets an attacker through a half-wired validator.
1004 //
1005 // Each probe replaces or omits the relevant auth credential and
1006 // expects 401 / 403. A 2xx here is a hard finding: "spec says
1007 // this endpoint is protected, server let unauthenticated /
1008 // wrong-credential traffic through".
1009 //
1010 // Bounded: at most one probe per declared scheme kind, so an
1011 // operation with 3 security requirements doesn't 4× the request
1012 // volume. Skips entirely when `op.security_schemes` is empty.
1013 for probe in build_security_probes(&op.security_schemes) {
1014 // Strip any pre-existing Authorization or known API-key
1015 // header from extra_headers + header_params so the probe
1016 // value is the *only* credential the server sees.
1017 let stripped_extra = strip_auth(&config.extra_headers, &op.security_schemes);
1018 let stripped_headers = strip_auth(&op.header_params, &op.security_schemes);
1019 let stripped_query = strip_auth_query(&op.query_params, &op.security_schemes);
1020 let mut req_headers = stripped_headers;
1021 for (k, v) in &probe.headers {
1022 req_headers.push((k.clone(), v.clone()));
1023 }
1024 // Round 24 (f) — security probes build req_headers from
1025 // `op.header_params` directly (we need the stripped-auth
1026 // variant), so the geo-IP header doesn't ride along
1027 // automatically. Append it here so a GEODB / WAF in front
1028 // of the auth layer still sees the rotating source IP.
1029 if let Some(ip) = geo_ip {
1030 let ip_str = ip.to_string();
1031 for h in &config.geo_source_headers {
1032 let already = req_headers.iter().any(|(k, _)| k.eq_ignore_ascii_case(h));
1033 if !already {
1034 req_headers.push((h.clone(), ip_str.clone()));
1035 }
1036 }
1037 }
1038 let mut req_query = stripped_query;
1039 for (k, v) in &probe.query {
1040 req_query.push((k.clone(), v.clone()));
1041 }
1042 negatives.push(
1043 send_case_with_extra(
1044 client,
1045 config,
1046 method.clone(),
1047 &url,
1048 &probe.label,
1049 ExpectedOutcome::ClientError,
1050 op.sample_body.as_deref(),
1051 req_query,
1052 req_headers,
1053 stripped_extra,
1054 &path_template,
1055 )
1056 .await,
1057 );
1058 }
1059
1060 // (d) drop the first required header
1061 if !op.header_params.is_empty() {
1062 // Round 24 (f) — start from `op_headers` (so the geo IP rides
1063 // along) and only strip the first OPERATION-declared header.
1064 // Slicing past `op.header_params.len()` would otherwise risk
1065 // dropping the geo header itself; `op_headers` is built as
1066 // `op.header_params ++ geo` so index 0 is always operational.
1067 let mut h = op_headers.clone();
1068 if !h.is_empty() {
1069 h.remove(0);
1070 }
1071 negatives.push(
1072 send_case(
1073 client,
1074 config,
1075 method.clone(),
1076 &url,
1077 "parameters:missing-header",
1078 ExpectedOutcome::ClientError,
1079 op.sample_body.as_deref(),
1080 op.query_params.clone(),
1081 h,
1082 &path_template,
1083 )
1084 .await,
1085 );
1086 }
1087
1088 // (w) Round 17.5 — OWASP/WAF unification.
1089 //
1090 // Pull one canonical payload per OWASP category from the existing
1091 // `SecurityPayloads` library and emit an injection probe per
1092 // category. Targets in priority order: (1) substitute the first
1093 // query param's value, (2) substitute the first string field of
1094 // the positive JSON body, (3) skip if neither is available.
1095 //
1096 // Label format `owasp:<category>`, so the existing
1097 // `negative_caught` / `negative_missed` rollup groups all OWASP
1098 // findings under one `owasp` bucket. Expected 4xx (server should
1099 // reject malicious input). A 5xx is a hard finding (server
1100 // crashed on the payload); a 2xx is a soft finding (input passed
1101 // through unfiltered — may or may not be a real vuln).
1102 //
1103 // Bounded: at most one probe per category (7 categories total).
1104 // Skips the operation entirely if no injection target is
1105 // available — open GET endpoints with no params get zero OWASP
1106 // probes, no false signal.
1107 for probe in build_owasp_probes(op) {
1108 negatives.push(
1109 send_case(
1110 client,
1111 config,
1112 method.clone(),
1113 &url,
1114 &probe.label,
1115 ExpectedOutcome::ClientError,
1116 probe.body.as_deref(),
1117 probe.query,
1118 // Round 24 (f) — OWASP injection probes must also
1119 // carry the geo IP, otherwise a WAF / GEODB rule
1120 // tuned to a specific source IP would silently let
1121 // them through.
1122 op_headers.clone(),
1123 &path_template,
1124 )
1125 .await,
1126 );
1127 }
1128
1129 // Round 25 — response-body shape validation pass. For each capture
1130 // this op pushed onto the sink, look up the spec's schema for the
1131 // actual response status and validate. Result lands in
1132 // `response_schema_error` (Some(message) on failure, None on
1133 // pass or no-schema-for-this-status). Runs only when the user
1134 // opted in AND capture is on (we need the body).
1135 if config.validate_response_schemas {
1136 if let (Some(sink), Some(start)) = (config.capture.as_ref(), sink_start) {
1137 if !op.response_schemas.is_empty() {
1138 if let Ok(mut guard) = sink.lock() {
1139 let end = guard.len();
1140 for i in start..end {
1141 let Some(entry) = guard.get_mut(i) else {
1142 continue;
1143 };
1144 let Some(body) = entry.response_body.as_deref() else {
1145 continue;
1146 };
1147 let Some(schema) = op.response_schemas.get(&entry.response_status) else {
1148 continue;
1149 };
1150 entry.response_schema_error = validate_body_against_schema(body, schema);
1151 }
1152 }
1153 }
1154 }
1155 }
1156
1157 OperationResult {
1158 method: op.method.clone(),
1159 path: op.path.clone(),
1160 positive: Some(positive),
1161 negatives,
1162 }
1163}
1164
1165/// Round 25 — validate a JSON body string against an OpenAPI response
1166/// schema (already converted to a `serde_json::Value`). Returns
1167/// `Some(message)` describing the first violation, or `None` on a
1168/// clean pass / non-JSON body / schema-build failure (in which case
1169/// the absence of an error means "we didn't have anything to compare
1170/// against", not "passed"; the caller-side semantics treat absence as
1171/// success because that's what the user sees as silence).
1172/// Round 27 (k variant b) — return a JSON body string identical to
1173/// `sample` except that the first string-valued leaf has been
1174/// replaced with `snippet`. Walks objects depth-first and stops at
1175/// the first string. Returns `None` when `sample` is not parseable
1176/// JSON or has no string field anywhere; the caller skips emitting
1177/// a probe in that case (Round 34 #829: Srikanth on 0.3.178 found
1178/// that the previous `{"data": <snippet>}` fallback envelope didn't
1179/// match real-API schemas like vCenter's `{enabled: bool}` and the
1180/// server correctly 400'd, which the bench then misreported as a
1181/// `2xx-3xx` expectation miss).
1182fn embed_payload_in_first_string_field(sample: &str, snippet: &str) -> Option<String> {
1183 let mut parsed: serde_json::Value = serde_json::from_str(sample).ok()?;
1184 if !replace_first_string(&mut parsed, snippet) {
1185 return None;
1186 }
1187 serde_json::to_string(&parsed).ok()
1188}
1189
1190/// Helper for `embed_payload_in_first_string_field`: recursively
1191/// walk the value and replace the FIRST string leaf encountered.
1192/// Returns true when a replacement happened. Honors document order
1193/// for objects (BTreeMap-backed `serde_json::Map` iterates in
1194/// insertion order) so the choice of which field to mutate is
1195/// stable across runs.
1196fn replace_first_string(v: &mut serde_json::Value, snippet: &str) -> bool {
1197 match v {
1198 serde_json::Value::String(s) => {
1199 *s = snippet.to_string();
1200 true
1201 }
1202 serde_json::Value::Object(map) => {
1203 for (_k, child) in map.iter_mut() {
1204 if replace_first_string(child, snippet) {
1205 return true;
1206 }
1207 }
1208 false
1209 }
1210 serde_json::Value::Array(arr) => {
1211 for child in arr.iter_mut() {
1212 if replace_first_string(child, snippet) {
1213 return true;
1214 }
1215 }
1216 false
1217 }
1218 _ => false,
1219 }
1220}
1221
1222fn validate_body_against_schema(body: &str, schema: &serde_json::Value) -> Option<String> {
1223 let parsed: serde_json::Value = serde_json::from_str(body).ok()?;
1224 let validator = jsonschema::validator_for(schema).ok()?;
1225 let mut errors = validator.iter_errors(&parsed);
1226 let first = errors.next()?;
1227 // Round 28 — Srikanth on 0.3.170 wanted the message to show the
1228 // actual expected schema alongside the kind label so it reads as
1229 // "expected schema {...} but got <kind>". We emit a compact JSON
1230 // serialisation of the schema as a suffix; the kind label still
1231 // names what went wrong in plain English for quick scanning.
1232 // Round 26 — Srikanth on 0.3.169: the prior `format!("{:?}", first.kind)
1233 // .split('(').next()` produced "Type { kind: Single" (broken Rust
1234 // syntax, mismatched braces). Switch to the human-readable mapping
1235 // already used in executor.rs: handle the common kinds (Type,
1236 // Required, AdditionalProperties, Enum, MinLength, MaxLength,
1237 // Minimum, Maximum, Pattern) explicitly; fall back to the
1238 // jsonschema crate's Display impl on the error (which produces
1239 // something like "{...} is not of type \"string\"") for the long
1240 // tail. Combined with `at <instance-path>` for the field location.
1241 let path = first.instance_path.to_string();
1242 let path = if path.is_empty() { "/" } else { path.as_str() };
1243 // Round 31 — Srikanth on 0.3.174 hit the vCenter case where the
1244 // error is "required field missing: comment" but the printed
1245 // schema was the WHOLE parent object schema (with descriptions of
1246 // every property), not just the missing field's sub-schema. The
1247 // jsonschema crate emits `Required` errors with
1248 // `instance_path == /` (the parent), so the round-30 sub-schema
1249 // walker had no extra info to focus the suffix. Carry the missing
1250 // property name out of the kind match so we can descend one more
1251 // step into `properties[property]` for the printed schema.
1252 let mut required_property: Option<String> = None;
1253 let kind_msg: String = match &first.kind {
1254 jsonschema::error::ValidationErrorKind::Type { kind } => {
1255 // `kind` is `TypeKind::Single(JsonType)` or
1256 // `TypeKind::Multiple(JsonTypeSet)`. `JsonType` has its
1257 // own `Display` impl ("string", "object", etc.).
1258 match kind {
1259 jsonschema::error::TypeKind::Single(t) => format!("expected type {t}"),
1260 jsonschema::error::TypeKind::Multiple(_) => "expected one of multiple types".into(),
1261 }
1262 }
1263 jsonschema::error::ValidationErrorKind::Required { property } => {
1264 // `property.to_string()` returns the Display of the JSON
1265 // value, which for a string is `"name"` (with quotes).
1266 // Strip them for the lookup; keep them in the human message.
1267 let raw = property.to_string();
1268 let unquoted = raw
1269 .strip_prefix('"')
1270 .and_then(|s| s.strip_suffix('"'))
1271 .unwrap_or(&raw)
1272 .to_string();
1273 required_property = Some(unquoted);
1274 format!("required field missing: {property}")
1275 }
1276 jsonschema::error::ValidationErrorKind::AdditionalProperties { unexpected } => {
1277 format!("unexpected additional properties: {unexpected:?}")
1278 }
1279 jsonschema::error::ValidationErrorKind::Enum { options } => {
1280 format!("value not in allowed enum: {options}")
1281 }
1282 jsonschema::error::ValidationErrorKind::MinLength { limit } => {
1283 format!("string shorter than min length ({limit})")
1284 }
1285 jsonschema::error::ValidationErrorKind::MaxLength { limit } => {
1286 format!("string longer than max length ({limit})")
1287 }
1288 jsonschema::error::ValidationErrorKind::Minimum { limit } => {
1289 format!("value below minimum ({limit})")
1290 }
1291 jsonschema::error::ValidationErrorKind::Maximum { limit } => {
1292 format!("value above maximum ({limit})")
1293 }
1294 jsonschema::error::ValidationErrorKind::Pattern { pattern } => {
1295 format!("value did not match pattern {pattern}")
1296 }
1297 // Long tail: lean on jsonschema's Display impl, which is the
1298 // built-in human-readable error message ("X is not of type Y").
1299 // Strip trailing newlines so the JSONL line stays one line.
1300 _ => first.to_string().trim().to_string(),
1301 };
1302 // Round 30 — Srikanth on 0.3.173 asked how a deeper nested mismatch
1303 // reads. The prior output printed the WHOLE top-level schema even for
1304 // a single-field mismatch, which buried the actual constraint that
1305 // failed. Walk the instance pointer through the schema's properties
1306 // chain and print the most specific sub-schema we can find. Falls
1307 // back to the full schema for paths the walker can't resolve
1308 // (additionalProperties, oneOf, allOf, $ref un-resolved, etc.).
1309 let mut focused_schema = sub_schema_at_pointer(schema, path).unwrap_or_else(|| schema.clone());
1310 // Round 31 — for Required errors, descend one more step into
1311 // `properties[<missing>]` so the printed schema is the missing
1312 // field's own constraint, not the whole parent.
1313 if let Some(prop_name) = required_property.as_ref() {
1314 if let Some(prop_schema) =
1315 focused_schema.get("properties").and_then(|p| p.get(prop_name.as_str()))
1316 {
1317 focused_schema = prop_schema.clone();
1318 }
1319 }
1320 // Round 34 (#827) — Srikanth on 0.3.178 hit the vCenter
1321 // `enabled: boolean` case where the schema's multi-paragraph
1322 // `description` (and other prose fields) ate the 300-char budget
1323 // before the actually-useful `type` keyword could appear. Strip
1324 // the noise-fields recursively before serializing so the type
1325 // signal survives truncation; constraint keywords (`type`,
1326 // `properties`, `required`, `format`, `items`, etc.) stay.
1327 let focused_schema = strip_schema_noise(&focused_schema);
1328 let schema_str = serde_json::to_string(&focused_schema).unwrap_or_else(|_| "<schema>".into());
1329 let schema_str = if schema_str.len() > 300 {
1330 format!("{}...", &schema_str[..300])
1331 } else {
1332 schema_str
1333 };
1334 // Round 29 — Srikanth on 0.3.172 was confused by `at /:` thinking
1335 // it referenced the URL path; it's actually a JSON pointer into
1336 // the RESPONSE BODY. Reword so that's unambiguous: explicit
1337 // "response body" prefix and a human label for the root case.
1338 let location = if path == "/" {
1339 "response body root".to_string()
1340 } else {
1341 format!("response body at {path}")
1342 };
1343 Some(format!("{location}: {kind_msg}; expected schema {schema_str}"))
1344}
1345
1346/// Round 34 (#827) — drop the human-readable / documentation-only
1347/// fields from a JSON Schema before printing it inside a
1348/// `response_schema_error` message. The validator only cares about
1349/// constraint keywords (`type`, `required`, `properties`, `items`,
1350/// `format`, `enum`, `min*`/`max*`, `pattern`, `oneOf`/`anyOf`/
1351/// `allOf`/`not`); the prose fields can be paragraphs long for real-
1352/// world specs (vCenter's `enabled: bool` field has a multi-paragraph
1353/// description) and were eating the 300-char truncation budget before
1354/// the actually-useful type info could appear. Stripped fields:
1355/// `description`, `example`, `examples`, `summary`, `title`,
1356/// `externalDocs`, `xml`, `discriminator.description`.
1357fn strip_schema_noise(schema: &serde_json::Value) -> serde_json::Value {
1358 const NOISE_KEYS: &[&str] = &[
1359 "description",
1360 "example",
1361 "examples",
1362 "summary",
1363 "title",
1364 "externalDocs",
1365 "xml",
1366 ];
1367 match schema {
1368 serde_json::Value::Object(map) => {
1369 let mut out = serde_json::Map::with_capacity(map.len());
1370 for (k, v) in map {
1371 if NOISE_KEYS.contains(&k.as_str()) {
1372 continue;
1373 }
1374 out.insert(k.clone(), strip_schema_noise(v));
1375 }
1376 serde_json::Value::Object(out)
1377 }
1378 serde_json::Value::Array(items) => {
1379 serde_json::Value::Array(items.iter().map(strip_schema_noise).collect())
1380 }
1381 other => other.clone(),
1382 }
1383}
1384
1385/// Round 30 — walk a JSON-Pointer-style instance path through a JSON
1386/// Schema and return the sub-schema describing the value at that
1387/// position. For path `/name/age` on
1388/// `{"properties":{"name":{"properties":{"age":{"type":"integer"}}}}}`
1389/// returns `{"type":"integer"}`. Returns `None` for paths the walker
1390/// can't follow (array indices into `items` with no per-index schema,
1391/// `additionalProperties`, `oneOf`/`allOf`, unresolved `$ref`); callers
1392/// should fall back to the full schema in that case.
1393fn sub_schema_at_pointer(schema: &serde_json::Value, pointer: &str) -> Option<serde_json::Value> {
1394 if pointer.is_empty() || pointer == "/" {
1395 return Some(schema.clone());
1396 }
1397 let mut current = schema;
1398 for seg in pointer.trim_start_matches('/').split('/') {
1399 let unescaped = seg.replace("~1", "/").replace("~0", "~");
1400 if let Some(props) = current.get("properties") {
1401 if let Some(sub) = props.get(&unescaped) {
1402 current = sub;
1403 continue;
1404 }
1405 }
1406 if let Some(items) = current.get("items") {
1407 if items.is_object() {
1408 current = items;
1409 continue;
1410 }
1411 }
1412 return None;
1413 }
1414 Some(current.clone())
1415}
1416
1417/// Round 17.5 — one OWASP injection probe to send.
1418#[derive(Debug, Clone)]
1419struct OwaspProbe {
1420 label: String,
1421 body: Option<String>,
1422 query: Vec<(String, String)>,
1423}
1424
1425/// Build one OWASP probe per `SecurityCategory` for `op`. Targets the
1426/// first query param if any, else the first string field of the
1427/// positive JSON body. Returns empty if neither target is available.
1428fn build_owasp_probes(op: &AnnotatedOperation) -> Vec<OwaspProbe> {
1429 use crate::security_payloads::{SecurityCategory, SecurityPayloads};
1430
1431 let categories = [
1432 SecurityCategory::SqlInjection,
1433 SecurityCategory::Xss,
1434 SecurityCategory::CommandInjection,
1435 SecurityCategory::PathTraversal,
1436 SecurityCategory::Ssti,
1437 SecurityCategory::LdapInjection,
1438 SecurityCategory::Xxe,
1439 ];
1440
1441 // Pick an injection target ONCE per operation; reuse it across
1442 // categories. (A single op gets up to 7 probes — one per category
1443 // — all attacking the same field.)
1444 let injection_target = pick_injection_target(op);
1445 let Some(target) = injection_target else {
1446 return Vec::new();
1447 };
1448
1449 let mut probes = Vec::new();
1450 for cat in categories {
1451 // Take the *first* payload from each category. The
1452 // collection's first entry is the canonical low-risk
1453 // representative; later entries include time-based / blind
1454 // probes that aren't useful as a one-shot rejection test.
1455 let Some(payload) = SecurityPayloads::get_by_category(cat).into_iter().next() else {
1456 continue;
1457 };
1458 let mut query = op.query_params.clone();
1459 let mut body = op.sample_body.clone();
1460 match &target {
1461 InjectionTarget::Query(idx) => {
1462 if let Some(slot) = query.get_mut(*idx) {
1463 slot.1 = payload.payload.clone();
1464 }
1465 }
1466 InjectionTarget::BodyStringField(field) => {
1467 body = inject_into_body_field(body.as_deref(), field, &payload.payload);
1468 }
1469 }
1470 probes.push(OwaspProbe {
1471 label: format!("owasp:{}", cat),
1472 body,
1473 query,
1474 });
1475 }
1476 probes
1477}
1478
1479#[derive(Debug, Clone)]
1480enum InjectionTarget {
1481 Query(usize),
1482 BodyStringField(String),
1483}
1484
1485fn pick_injection_target(op: &AnnotatedOperation) -> Option<InjectionTarget> {
1486 if !op.query_params.is_empty() {
1487 return Some(InjectionTarget::Query(0));
1488 }
1489 let sample = op.sample_body.as_deref()?;
1490 let parsed: serde_json::Value = serde_json::from_str(sample).ok()?;
1491 let obj = parsed.as_object()?;
1492 for (k, v) in obj {
1493 if v.is_string() {
1494 return Some(InjectionTarget::BodyStringField(k.clone()));
1495 }
1496 }
1497 None
1498}
1499
1500/// Replace the value of `field` in a JSON-object body with `payload`.
1501/// Returns the mutated body as a JSON string. Returns `None` if the
1502/// body doesn't parse as a JSON object.
1503fn inject_into_body_field(body: Option<&str>, field: &str, payload: &str) -> Option<String> {
1504 let raw = body?;
1505 let mut parsed: serde_json::Value = serde_json::from_str(raw).ok()?;
1506 let obj = parsed.as_object_mut()?;
1507 obj.insert(field.to_string(), serde_json::json!(payload));
1508 serde_json::to_string(&parsed).ok()
1509}
1510
1511#[allow(clippy::too_many_arguments)]
1512/// Round 17.3 — one synthesised bad credential to send.
1513#[derive(Debug, Clone)]
1514struct SecurityProbe {
1515 /// Self-test label, e.g. `security:bad-bearer`.
1516 label: String,
1517 /// Headers to attach to the probe request.
1518 headers: Vec<(String, String)>,
1519 /// Query parameters to attach (API key in query case).
1520 query: Vec<(String, String)>,
1521}
1522
1523/// For each declared security scheme, produce one bad-credential
1524/// probe plus a single "no auth at all" probe that exercises the
1525/// missing-credential code path. Deduplicates by scheme kind so an
1526/// operation declaring `[bearer, bearer]` only yields one Bearer
1527/// probe.
1528fn build_security_probes(schemes: &[SecuritySchemeInfo]) -> Vec<SecurityProbe> {
1529 if schemes.is_empty() {
1530 return Vec::new();
1531 }
1532 let mut probes: Vec<SecurityProbe> = Vec::new();
1533 let mut seen_bearer = false;
1534 let mut seen_basic = false;
1535 // `(loc_tag, name)` — ApiKeyLocation doesn't implement Ord, so
1536 // we tag it with a short discriminant string for dedup.
1537 let mut seen_apikey: std::collections::BTreeSet<(&'static str, String)> = Default::default();
1538 for s in schemes {
1539 match s {
1540 SecuritySchemeInfo::Bearer if !seen_bearer => {
1541 seen_bearer = true;
1542 probes.push(SecurityProbe {
1543 label: "security:bad-bearer".into(),
1544 headers: vec![(
1545 "Authorization".into(),
1546 "Bearer self-test-invalid-token".into(),
1547 )],
1548 query: Vec::new(),
1549 });
1550 }
1551 SecuritySchemeInfo::Basic if !seen_basic => {
1552 seen_basic = true;
1553 // base64("self-test:invalid") — valid base64, wrong creds.
1554 probes.push(SecurityProbe {
1555 label: "security:bad-basic".into(),
1556 headers: vec![(
1557 "Authorization".into(),
1558 "Basic c2VsZi10ZXN0OmludmFsaWQ=".into(),
1559 )],
1560 query: Vec::new(),
1561 });
1562 }
1563 SecuritySchemeInfo::ApiKey { location, name } => {
1564 let loc_tag = match location {
1565 ApiKeyLocation::Header => "header",
1566 ApiKeyLocation::Query => "query",
1567 ApiKeyLocation::Cookie => "cookie",
1568 };
1569 if seen_apikey.contains(&(loc_tag, name.clone())) {
1570 continue;
1571 }
1572 seen_apikey.insert((loc_tag, name.clone()));
1573 let label = format!("security:bad-apikey:{}", name);
1574 let bad = "self-test-invalid-key".to_string();
1575 match location {
1576 ApiKeyLocation::Header => probes.push(SecurityProbe {
1577 label,
1578 headers: vec![(name.clone(), bad)],
1579 query: Vec::new(),
1580 }),
1581 ApiKeyLocation::Query => probes.push(SecurityProbe {
1582 label,
1583 headers: Vec::new(),
1584 query: vec![(name.clone(), bad)],
1585 }),
1586 ApiKeyLocation::Cookie => probes.push(SecurityProbe {
1587 label,
1588 headers: vec![("Cookie".into(), format!("{}={}", name, bad))],
1589 query: Vec::new(),
1590 }),
1591 }
1592 }
1593 _ => {}
1594 }
1595 }
1596 // Always add a "no auth at all" probe when *any* security scheme
1597 // is declared — useful even if all schemes failed to resolve to a
1598 // testable kind, because it surfaces validators that aren't
1599 // checking auth presence at all.
1600 probes.push(SecurityProbe {
1601 label: "security:no-auth".into(),
1602 headers: Vec::new(),
1603 query: Vec::new(),
1604 });
1605 probes
1606}
1607
1608/// Remove Authorization and any API-key headers declared by the
1609/// operation's security schemes from `headers`, so a security probe
1610/// can supply its own credential (or none) cleanly.
1611fn strip_auth(
1612 headers: &[(String, String)],
1613 schemes: &[SecuritySchemeInfo],
1614) -> Vec<(String, String)> {
1615 let mut apikey_headers: std::collections::BTreeSet<String> = Default::default();
1616 for s in schemes {
1617 if let SecuritySchemeInfo::ApiKey {
1618 location: ApiKeyLocation::Header,
1619 name,
1620 } = s
1621 {
1622 apikey_headers.insert(name.to_lowercase());
1623 }
1624 if let SecuritySchemeInfo::ApiKey {
1625 location: ApiKeyLocation::Cookie,
1626 ..
1627 } = s
1628 {
1629 apikey_headers.insert("cookie".into());
1630 }
1631 }
1632 headers
1633 .iter()
1634 .filter(|(k, _)| {
1635 let lk = k.to_lowercase();
1636 lk != "authorization" && !apikey_headers.contains(&lk)
1637 })
1638 .cloned()
1639 .collect()
1640}
1641
1642/// Remove API-key query parameters declared by the operation's
1643/// security schemes from `query`, so a probe can supply its own.
1644fn strip_auth_query(
1645 query: &[(String, String)],
1646 schemes: &[SecuritySchemeInfo],
1647) -> Vec<(String, String)> {
1648 let mut apikey_query: std::collections::BTreeSet<String> = Default::default();
1649 for s in schemes {
1650 if let SecuritySchemeInfo::ApiKey {
1651 location: ApiKeyLocation::Query,
1652 name,
1653 } = s
1654 {
1655 apikey_query.insert(name.clone());
1656 }
1657 }
1658 query.iter().filter(|(k, _)| !apikey_query.contains(k)).cloned().collect()
1659}
1660
1661/// Round 35 (#859) — Srikanth on 0.3.179: embedded-content variant-b
1662/// probes were flagging well-behaved 4xx responses as mismatches when
1663/// in reality only a 5xx (server CRASHED trying to parse the embedded
1664/// XML/YAML/multipart/urlencoded payload) is the bug the probe was
1665/// designed to find. Tristate replaces the older `expected_4xx: bool`
1666/// so variant-b probes can opt into "anything but 5xx is fine".
1667#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1668pub(crate) enum ExpectedOutcome {
1669 /// Positive probe: spec-compliant request, expect 2xx or 3xx.
1670 Success,
1671 /// Negative probe: invalid request, expect 4xx.
1672 ClientError,
1673 /// Embedded-content variant-b probe: spec-shape envelope with a
1674 /// non-JSON payload embedded in the first string field. Any
1675 /// response that isn't a 5xx is fine; the probe is here to catch
1676 /// server crashes on the embedded payload.
1677 NotServerError,
1678}
1679
1680impl ExpectedOutcome {
1681 /// Whether `actual_status` counts as a pass for this outcome.
1682 fn passes(self, actual_status: u16) -> bool {
1683 match self {
1684 ExpectedOutcome::Success => (200..400).contains(&actual_status),
1685 ExpectedOutcome::ClientError => (400..500).contains(&actual_status),
1686 ExpectedOutcome::NotServerError => {
1687 actual_status >= 200 && !(500..600).contains(&actual_status)
1688 }
1689 }
1690 }
1691
1692 /// Human-readable hint persisted in the JSONL capture + HTML
1693 /// viewer's "show mismatches only" filter; also what users `jq`
1694 /// against.
1695 fn as_str(self) -> &'static str {
1696 match self {
1697 ExpectedOutcome::Success => "2xx-3xx",
1698 ExpectedOutcome::ClientError => "4xx",
1699 ExpectedOutcome::NotServerError => "2xx-4xx",
1700 }
1701 }
1702}
1703
1704/// Variant of `send_case` that takes an explicit `extra_headers`
1705/// (rather than reading them from `config`). Used by security probes
1706/// to substitute or strip the configured Authorization header.
1707#[allow(clippy::too_many_arguments)]
1708async fn send_case_with_extra(
1709 client: &Client,
1710 config: &SelfTestConfig,
1711 method: Method,
1712 url: &str,
1713 label: &str,
1714 expected: ExpectedOutcome,
1715 body: Option<&str>,
1716 query: Vec<(String, String)>,
1717 headers: Vec<(String, String)>,
1718 extra_headers: Vec<(String, String)>,
1719 // Round 33 (#823) — spec path template (e.g. `/users/{id}`)
1720 // for the operation this probe belongs to. Stamped on the
1721 // capture so the per-endpoint summary can group by template.
1722 path_template: &str,
1723) -> CaseOutcome {
1724 let mut req = client.request(method.clone(), url);
1725 let mut capture_headers: BTreeMap<String, String> = BTreeMap::new();
1726 for (k, v) in &query {
1727 req = req.query(&[(k.as_str(), v.as_str())]);
1728 }
1729 // Round 36 (#876) — stamp the client side first so the same
1730 // `client_sent_at` string flows into both the request headers
1731 // (so the server-side `ServerConformanceViolation` records it
1732 // verbatim) and the on-disk `CaseCapture` JSONL line. Don't
1733 // re-call `Utc::now()` after `req.send()` — that would record
1734 // a different timestamp than the server sees.
1735 let mockforge_version = env!("CARGO_PKG_VERSION").to_string();
1736 let client_sent_at = chrono::Utc::now().to_rfc3339();
1737 // Round 28 — reqwest's `.header(k, v)` APPENDS rather than replaces
1738 // (.headers().insert() would replace but isn't on the builder).
1739 // The previous round-25 fix relied on "last-write-wins" semantics
1740 // that don't exist; for content-type-swap probes the request went
1741 // out with BOTH `Content-Type: application/json` AND `Content-Type:
1742 // application/xml`, and axum's `Json<>` extractor picked the JSON
1743 // one and accepted, so the server-side validator never saw the
1744 // mismatch. Build a `HeaderMap` ourselves so the override
1745 // replaces the body-block default exactly once.
1746 let mut final_headers: reqwest::header::HeaderMap = reqwest::header::HeaderMap::new();
1747 if let Some(_b) = body {
1748 if let Ok(v) = reqwest::header::HeaderValue::from_str("application/json") {
1749 final_headers.insert(reqwest::header::CONTENT_TYPE, v);
1750 }
1751 capture_headers.insert("Content-Type".to_string(), "application/json".to_string());
1752 }
1753 for (k, v) in &headers {
1754 if let (Ok(hn), Ok(hv)) = (
1755 reqwest::header::HeaderName::from_bytes(k.as_bytes()),
1756 reqwest::header::HeaderValue::from_str(v),
1757 ) {
1758 final_headers.insert(hn, hv);
1759 }
1760 capture_headers.insert(k.clone(), v.clone());
1761 }
1762 for (k, v) in &extra_headers {
1763 if let (Ok(hn), Ok(hv)) = (
1764 reqwest::header::HeaderName::from_bytes(k.as_bytes()),
1765 reqwest::header::HeaderValue::from_str(v),
1766 ) {
1767 final_headers.insert(hn, hv);
1768 }
1769 capture_headers.insert(k.clone(), v.clone());
1770 }
1771 // Round 36 (#876) — outbound client stamps. Inserted last so
1772 // they can't be clobbered by user-supplied extra-headers, and
1773 // recorded in `capture_headers` so the JSONL line shows the
1774 // exact bytes that went on the wire.
1775 {
1776 let v_header = mockforge_foundation::conformance_violations::CLIENT_VERSION_HEADER;
1777 let s_header = mockforge_foundation::conformance_violations::CLIENT_SENT_AT_HEADER;
1778 if let (Ok(hn), Ok(hv)) = (
1779 reqwest::header::HeaderName::from_bytes(v_header.as_bytes()),
1780 reqwest::header::HeaderValue::from_str(&mockforge_version),
1781 ) {
1782 final_headers.insert(hn, hv);
1783 }
1784 if let (Ok(hn), Ok(hv)) = (
1785 reqwest::header::HeaderName::from_bytes(s_header.as_bytes()),
1786 reqwest::header::HeaderValue::from_str(&client_sent_at),
1787 ) {
1788 final_headers.insert(hn, hv);
1789 }
1790 capture_headers.insert(v_header.to_string(), mockforge_version.clone());
1791 capture_headers.insert(s_header.to_string(), client_sent_at.clone());
1792 }
1793 if let Some(b) = body {
1794 req = req.body(b.to_string());
1795 }
1796 req = req.headers(final_headers);
1797 let (actual_status, response_capture) = match req.send().await {
1798 Ok(resp) => {
1799 let status = resp.status().as_u16();
1800 if let Some(sink) = &config.capture {
1801 let resp_headers: BTreeMap<String, String> = resp
1802 .headers()
1803 .iter()
1804 .map(|(k, v)| (k.as_str().to_string(), v.to_str().unwrap_or("").to_string()))
1805 .collect();
1806 let text = resp.text().await.unwrap_or_default();
1807 let (rb, truncated) = truncate_body_for_capture(&text);
1808 (status, Some((Some((rb, truncated)), resp_headers, None, sink.clone())))
1809 } else {
1810 (status, None)
1811 }
1812 }
1813 Err(e) => {
1814 let err_str = e.to_string();
1815 // Round 47 (#79) — classify + push to the wire-level
1816 // network-events sink (when present) so the user has a
1817 // grep-able log of connect/timeout/tls failures during
1818 // self-test, matching the r46 native-executor behaviour.
1819 if let Some(sink) = &config.network_events {
1820 let kind = if e.is_connect() {
1821 "connect"
1822 } else if e.is_timeout() {
1823 "timeout"
1824 } else if e.is_request() {
1825 "request"
1826 } else if e.is_body() {
1827 "body"
1828 } else if e.is_decode() {
1829 "decode"
1830 } else if err_str.to_ascii_lowercase().contains("tls") {
1831 "tls"
1832 } else {
1833 "other"
1834 };
1835 if let Ok(mut guard) = sink.lock() {
1836 guard.push(NetworkEvent {
1837 timestamp: chrono::Utc::now(),
1838 check: label.to_string(),
1839 method: method.to_string(),
1840 url: build_query_url(url, &query),
1841 kind: kind.to_string(),
1842 message: err_str.clone(),
1843 });
1844 }
1845 }
1846 if let Some(sink) = &config.capture {
1847 (0, Some((None, BTreeMap::new(), Some(err_str), sink.clone())))
1848 } else {
1849 (0, None)
1850 }
1851 }
1852 };
1853 let passed = expected.passes(actual_status);
1854 if let Some((resp_body, resp_headers, error, sink)) = response_capture {
1855 let (request_body, request_body_truncated) = match body {
1856 Some(b) => {
1857 let (rb, t) = truncate_body_for_capture(b);
1858 (Some(rb), t)
1859 }
1860 None => (None, false),
1861 };
1862 let (response_body, response_body_truncated) = match resp_body {
1863 Some((rb, t)) => (Some(rb), t),
1864 None => (None, false),
1865 };
1866 let entry = CaseCapture {
1867 label: label.to_string(),
1868 method: method.to_string(),
1869 url: build_query_url(url, &query),
1870 request_headers: capture_headers,
1871 request_body,
1872 request_body_truncated,
1873 response_status: actual_status,
1874 response_headers: resp_headers,
1875 response_body,
1876 response_body_truncated,
1877 error,
1878 // Filled in by the per-operation validation pass after
1879 // every probe finishes; the capture itself is unaware of
1880 // the schema map.
1881 response_schema_error: None,
1882 // Round 28 — derive the expected range from the probe's
1883 // outcome shape so the JSONL line and HTML viewer can
1884 // filter mismatches without re-deriving on the read side.
1885 // Round 35 (#859) — add a third value `"2xx-4xx"` for
1886 // embedded-content variant-b probes whose only failure
1887 // mode is a 5xx server crash.
1888 expected_status_range: expected.as_str().to_string(),
1889 // Round 33 (#823) — path_template carries the spec's
1890 // pre-substitution path so the per-endpoint summary can
1891 // collapse `/users/X` and `/users/Y` into one row.
1892 // spec_label is constant per run, read from the config.
1893 path_template: path_template.to_string(),
1894 spec_label: config.spec_label.clone(),
1895 // Round 36 (#876) — same values that went on the wire as
1896 // request headers, so a server-side
1897 // `ServerConformanceViolation` recorded with
1898 // `client_mockforge_version` + `client_sent_at` matches
1899 // the JSONL line byte-for-byte.
1900 mockforge_version: mockforge_version.clone(),
1901 client_sent_at: client_sent_at.clone(),
1902 iteration: config.current_iteration.max(1),
1903 };
1904 if let Ok(mut guard) = sink.lock() {
1905 guard.push(entry);
1906 }
1907 }
1908 // Round 35 (#859) — keep the `expected_4xx` field on `CaseOutcome`
1909 // semantically tied to "negative probe expecting 400-class", so
1910 // downstream code in `report_html.rs` doesn't have to learn about
1911 // the new tristate. `NotServerError` reports as `expected_4xx:
1912 // false` (it's a positive probe in spirit) and instead carries
1913 // its outcome through the per-capture `expected_status_range`.
1914 let expected_4xx = matches!(expected, ExpectedOutcome::ClientError);
1915 CaseOutcome {
1916 label: label.to_string(),
1917 expected_4xx,
1918 actual_status,
1919 passed,
1920 }
1921}
1922
1923// HTTP request shape needs all of these: client, config (for capture
1924// sink + extra headers), method, url, label (probe id), expected_4xx
1925// (pass/fail decision), body, query, headers. A struct wrapper would
1926// just move the arity from positional to field access without making
1927// the call sites clearer.
1928#[allow(clippy::too_many_arguments)]
1929async fn send_case(
1930 client: &Client,
1931 config: &SelfTestConfig,
1932 method: Method,
1933 url: &str,
1934 label: &str,
1935 expected: ExpectedOutcome,
1936 body: Option<&str>,
1937 query: Vec<(String, String)>,
1938 headers: Vec<(String, String)>,
1939 path_template: &str,
1940) -> CaseOutcome {
1941 // Forwarding to `send_case_with_extra` keeps the capture logic in
1942 // one place so request/response tracing can't drift between the
1943 // two entrypoints.
1944 send_case_with_extra(
1945 client,
1946 config,
1947 method,
1948 url,
1949 label,
1950 expected,
1951 body,
1952 query,
1953 headers,
1954 config.extra_headers.clone(),
1955 path_template,
1956 )
1957 .await
1958}
1959
1960/// Round 23 (c-iii) — rebuild the query-stringified URL for capture so
1961/// the JSONL trace shows the URL that actually went over the wire
1962/// (reqwest applies `.query(..)` after the request URL string is
1963/// rendered, so capturing the raw `url` argument alone loses the
1964/// query params).
1965fn build_query_url(base: &str, query: &[(String, String)]) -> String {
1966 if query.is_empty() {
1967 return base.to_string();
1968 }
1969 let qs: String = query
1970 .iter()
1971 .map(|(k, v)| format!("{}={}", urlencoding::encode(k), urlencoding::encode(v)))
1972 .collect::<Vec<_>>()
1973 .join("&");
1974 if base.contains('?') {
1975 format!("{base}&{qs}")
1976 } else {
1977 format!("{base}?{qs}")
1978 }
1979}
1980
1981/// Substitute `{param}` placeholders in the spec path with their
1982/// sample values from `path_params`, then prepend `target_url`. Empty
1983/// values are kept as `{param}` so an upstream router still matches
1984/// the template — useful when `path_params` is empty and we want to
1985/// hit the same route the spec defines.
1986///
1987/// All current call sites went through `build_url_with_base` after
1988/// round 18.1, so this no-base-path helper is unused; keep it as the
1989/// documented shim for future external callers (one-arg simplification).
1990#[allow(dead_code)]
1991fn build_url(target: &str, path_template: &str, path_params: &[(String, String)]) -> String {
1992 build_url_with_base(target, None, path_template, path_params)
1993}
1994
1995/// Round 55 (#79) — normalise a `--base-path` into a URL path prefix.
1996///
1997/// `Some("/api")` / `Some("api")` / `Some("/api/")` all become `/api`;
1998/// `Some("/")`, `Some("")`, and `None` all become `""` (root, no prefix).
1999///
2000/// Srikanth on 0.3.202 ran with `--base-path /` and got ZERO violations even
2001/// though the console reported thousands of misses. The old logic did
2002/// `"/".trim_end_matches('/')` = `""`, decided `"".starts_with('/')` was
2003/// false, and produced the prefix `"/"`. Combined with the leading `/` on the
2004/// spec path that yielded `<target>//v1/organizations` (double slash), which
2005/// never matched the spec's `/v1/organizations`, so every emitted request was
2006/// skipped by the validator and no violations were logged. Trimming slashes
2007/// from BOTH ends and treating the empty result as "no prefix" fixes it.
2008fn base_path_prefix(base_path: Option<&str>) -> String {
2009 match base_path {
2010 Some(bp) => {
2011 let trimmed = bp.trim_matches('/');
2012 if trimmed.is_empty() {
2013 String::new()
2014 } else {
2015 format!("/{trimmed}")
2016 }
2017 }
2018 None => String::new(),
2019 }
2020}
2021
2022/// Round 18.1 — variant of `build_url` that takes a `base_path`
2023/// (e.g. `Some("/api")`). When set, prepends it to the spec path so a
2024/// spec declaring `/users` against a target served behind `/api`
2025/// resolves to `<target>/api/users`. `base_path` is normalised via
2026/// [`base_path_prefix`] (both ends trimmed; `/` means root/no prefix).
2027fn build_url_with_base(
2028 target: &str,
2029 base_path: Option<&str>,
2030 path_template: &str,
2031 path_params: &[(String, String)],
2032) -> String {
2033 let mut url = path_template.to_string();
2034 for (name, value) in path_params {
2035 let placeholder = format!("{{{}}}", name);
2036 if !value.is_empty() {
2037 url = url.replace(&placeholder, value);
2038 }
2039 }
2040 let target = target.trim_end_matches('/');
2041 let prefix = base_path_prefix(base_path);
2042 let path = if url.starts_with('/') {
2043 url
2044 } else {
2045 format!("/{url}")
2046 };
2047 format!("{target}{prefix}{path}")
2048}
2049
2050#[cfg(test)]
2051mod tests {
2052 use super::*;
2053
2054 fn op(
2055 method: &str,
2056 path: &str,
2057 body: Option<&str>,
2058 query: Vec<(&str, &str)>,
2059 headers: Vec<(&str, &str)>,
2060 path_params: Vec<(&str, &str)>,
2061 ) -> AnnotatedOperation {
2062 AnnotatedOperation {
2063 method: method.into(),
2064 path: path.into(),
2065 features: Vec::new(),
2066 request_body_content_type: body.map(|_| "application/json".into()),
2067 sample_body: body.map(|s| s.to_string()),
2068 query_params: query.into_iter().map(|(a, b)| (a.into(), b.into())).collect(),
2069 header_params: headers.into_iter().map(|(a, b)| (a.into(), b.into())).collect(),
2070 path_params: path_params.into_iter().map(|(a, b)| (a.into(), b.into())).collect(),
2071 response_schema: None,
2072 response_schemas: std::collections::BTreeMap::new(),
2073 request_body_schema: None,
2074 security_schemes: Vec::new(),
2075 }
2076 }
2077
2078 /// Round 36 (#876) — older JSONL lines (written before the stamp
2079 /// fields existed) must still deserialise without error and
2080 /// default to empty strings. Prevents a back-compat regression
2081 /// the next time we extend `CaseCapture`.
2082 #[test]
2083 fn case_capture_back_compat_when_stamp_fields_missing() {
2084 let pre_r36 = serde_json::json!({
2085 "label": "positive",
2086 "method": "GET",
2087 "url": "http://api/users",
2088 "request_headers": {},
2089 "request_body_truncated": false,
2090 "response_status": 200,
2091 "response_headers": {},
2092 "response_body_truncated": false,
2093 });
2094 let capture: CaseCapture =
2095 serde_json::from_value(pre_r36).expect("pre-r36 payload must deserialise");
2096 assert!(capture.mockforge_version.is_empty(), "default to empty");
2097 assert!(capture.client_sent_at.is_empty(), "default to empty");
2098 }
2099
2100 /// Round 36 (#876) — when the bench stamps fields itself (the
2101 /// happy path), they round-trip through serde unchanged. Pins
2102 /// the on-wire shape so tooling that grep's `mockforge_version`
2103 /// out of the JSONL stays valid.
2104 #[test]
2105 fn case_capture_stamps_round_trip_through_serde() {
2106 let stamped = CaseCapture {
2107 label: "positive".into(),
2108 method: "GET".into(),
2109 url: "http://api/users".into(),
2110 request_headers: BTreeMap::new(),
2111 request_body: None,
2112 request_body_truncated: false,
2113 response_status: 200,
2114 response_headers: BTreeMap::new(),
2115 response_body: None,
2116 response_body_truncated: false,
2117 error: None,
2118 response_schema_error: None,
2119 expected_status_range: "2xx-3xx".into(),
2120 path_template: "/users".into(),
2121 spec_label: None,
2122 mockforge_version: "0.3.183".into(),
2123 client_sent_at: "2026-06-17T12:34:56+00:00".into(),
2124 iteration: 1,
2125 };
2126 let json = serde_json::to_string(&stamped).unwrap();
2127 assert!(json.contains("\"mockforge_version\":\"0.3.183\""));
2128 assert!(json.contains("\"client_sent_at\":\"2026-06-17T12:34:56+00:00\""));
2129 let back: CaseCapture = serde_json::from_str(&json).unwrap();
2130 assert_eq!(back.mockforge_version, "0.3.183");
2131 assert_eq!(back.client_sent_at, "2026-06-17T12:34:56+00:00");
2132 }
2133
2134 #[test]
2135 fn build_url_substitutes_path_params() {
2136 let url = build_url(
2137 "https://api.test/",
2138 "/users/{id}/posts/{pid}",
2139 &[("id".into(), "42".into()), ("pid".into(), "7".into())],
2140 );
2141 assert_eq!(url, "https://api.test/users/42/posts/7");
2142 }
2143
2144 /// Round 18.1 — a run where every positive 404s should be flagged
2145 /// as a likely target misconfiguration, not silently treated as a
2146 /// successful conformance run.
2147 #[test]
2148 fn detect_target_misconfiguration_when_all_positives_share_status() {
2149 let mut report = SelfTestReport {
2150 positive_pass: 0,
2151 positive_fail: 50,
2152 ..Default::default()
2153 };
2154 for i in 0..50 {
2155 report.operations.push(OperationResult {
2156 method: "GET".into(),
2157 path: format!("/r/{i}"),
2158 positive: Some(CaseOutcome {
2159 label: "positive".into(),
2160 expected_4xx: false,
2161 actual_status: 404,
2162 passed: false,
2163 }),
2164 negatives: Vec::new(),
2165 });
2166 }
2167 assert_eq!(report.detect_target_misconfiguration(), Some(404));
2168 }
2169
2170 #[test]
2171 fn detect_target_misconfiguration_returns_none_when_some_pass() {
2172 let mut report = SelfTestReport {
2173 positive_pass: 5,
2174 positive_fail: 50,
2175 ..Default::default()
2176 };
2177 for i in 0..55 {
2178 report.operations.push(OperationResult {
2179 method: "GET".into(),
2180 path: format!("/r/{i}"),
2181 positive: Some(CaseOutcome {
2182 label: "positive".into(),
2183 expected_4xx: false,
2184 actual_status: if i < 5 { 200 } else { 404 },
2185 passed: i < 5,
2186 }),
2187 negatives: Vec::new(),
2188 });
2189 }
2190 assert_eq!(report.detect_target_misconfiguration(), None);
2191 }
2192
2193 /// Round 18.1 — `--base-path /api` should prepend `/api` to
2194 /// every spec path. Pre-fix, the self-test ignored base_path and
2195 /// 404'd every positive when the deployed API was behind a path
2196 /// prefix.
2197 #[test]
2198 fn build_url_applies_base_path_when_present() {
2199 let url = build_url_with_base(
2200 "https://api.example.com",
2201 Some("/api"),
2202 "/users/{id}",
2203 &[("id".into(), "42".into())],
2204 );
2205 assert_eq!(url, "https://api.example.com/api/users/42");
2206 }
2207
2208 /// Round 18.1 — base_path is normalised: missing leading slash
2209 /// gets one added, trailing slash is stripped, empty string is
2210 /// the same as None.
2211 #[test]
2212 fn build_url_normalises_base_path() {
2213 let no_slash = build_url_with_base("https://t", Some("api"), "/x", &[]);
2214 assert_eq!(no_slash, "https://t/api/x");
2215 let trailing = build_url_with_base("https://t", Some("/api/"), "/x", &[]);
2216 assert_eq!(trailing, "https://t/api/x");
2217 let empty = build_url_with_base("https://t", Some(""), "/x", &[]);
2218 assert_eq!(empty, "https://t/x");
2219 let none = build_url_with_base("https://t", None, "/x", &[]);
2220 assert_eq!(none, "https://t/x");
2221 }
2222
2223 /// Round 55 (#79) — Srikanth on 0.3.202 passed `--base-path /` and got a
2224 /// `//v1/organizations` double slash, which broke all validation. `/`
2225 /// (and `//`) must be treated as root, i.e. no prefix.
2226 #[test]
2227 fn base_path_slash_is_root_no_double_slash() {
2228 assert_eq!(base_path_prefix(Some("/")), "");
2229 assert_eq!(base_path_prefix(Some("//")), "");
2230 assert_eq!(base_path_prefix(Some("")), "");
2231 assert_eq!(base_path_prefix(None), "");
2232 assert_eq!(base_path_prefix(Some("/api")), "/api");
2233 assert_eq!(base_path_prefix(Some("api/")), "/api");
2234 assert_eq!(base_path_prefix(Some("/api/v1")), "/api/v1");
2235 // The end-to-end URL no longer double-slashes.
2236 assert_eq!(
2237 build_url_with_base("https://t", Some("/"), "/v1/organizations", &[]),
2238 "https://t/v1/organizations"
2239 );
2240 }
2241
2242 #[test]
2243 fn build_url_keeps_placeholders_when_no_sample() {
2244 let url = build_url("https://api.test", "/users/{id}", &[]);
2245 assert_eq!(url, "https://api.test/users/{id}");
2246 }
2247
2248 #[test]
2249 fn report_summary_calls_out_misses() {
2250 let r = SelfTestReport {
2251 positive_pass: 3,
2252 positive_fail: 0,
2253 negative_caught: BTreeMap::from([("request-body".into(), 2)]),
2254 negative_missed: BTreeMap::from([("request-body".into(), 1)]),
2255 operations: Vec::new(),
2256 };
2257 let summary = r.render_summary();
2258 assert!(summary.contains("Positives: 3 pass / 0 fail"));
2259 assert!(summary.contains("Negatives [request-body]: 2 caught / 1 missed"));
2260 assert!(summary.contains("⚠"));
2261 // Round 57 (#79) — the caught/missed legend is printed once when there
2262 // are negatives, so the console explains the terms inline.
2263 assert!(summary.contains("\"caught\" = the target rejected it"));
2264 assert!(summary.contains("spec-valid by construction"));
2265 assert!(!r.all_passed());
2266 }
2267
2268 #[test]
2269 fn report_summary_omits_legend_when_no_negatives() {
2270 // Round 57 (#79) — a positives-only report has no Negatives lines, so
2271 // the legend would be noise; it must not appear.
2272 let r = SelfTestReport {
2273 positive_pass: 1,
2274 positive_fail: 0,
2275 negative_caught: BTreeMap::new(),
2276 negative_missed: BTreeMap::new(),
2277 operations: Vec::new(),
2278 };
2279 let summary = r.render_summary();
2280 assert!(!summary.contains("deliberately-bad requests"));
2281 }
2282
2283 #[test]
2284 fn definite_issues_flags_rejected_positives_and_5xx_but_not_spec_valid_misses() {
2285 // Round 58 (#79) — the "for sure this is an issue" view.
2286 let mut r = SelfTestReport::default();
2287 // (1) valid request the target rejected with 4xx -> definite issue.
2288 r.operations.push(OperationResult {
2289 method: "POST".into(),
2290 path: "/v1/organizations".into(),
2291 positive: Some(CaseOutcome {
2292 label: "positive".into(),
2293 expected_4xx: false,
2294 actual_status: 400,
2295 passed: false,
2296 }),
2297 negatives: vec![],
2298 });
2299 // (2) negative probe that crashed the target with 5xx -> definite issue.
2300 r.operations.push(OperationResult {
2301 method: "GET".into(),
2302 path: "/v1/items".into(),
2303 positive: Some(CaseOutcome {
2304 label: "positive".into(),
2305 expected_4xx: false,
2306 actual_status: 200,
2307 passed: true,
2308 }),
2309 negatives: vec![CaseOutcome {
2310 label: "owasp:sqli".into(),
2311 expected_4xx: true,
2312 actual_status: 500,
2313 passed: false,
2314 }],
2315 });
2316 // (3) spec-valid negative the target accepted (2xx) -> NOT a definite
2317 // issue (this is a "missed" that needs judgement, must be excluded).
2318 r.operations.push(OperationResult {
2319 method: "GET".into(),
2320 path: "/v1/ok".into(),
2321 positive: Some(CaseOutcome {
2322 label: "positive".into(),
2323 expected_4xx: false,
2324 actual_status: 200,
2325 passed: true,
2326 }),
2327 negatives: vec![CaseOutcome {
2328 label: "parameters:missing-query".into(),
2329 expected_4xx: true,
2330 actual_status: 200,
2331 passed: false,
2332 }],
2333 });
2334
2335 let issues = r.definite_issues();
2336 assert_eq!(issues.len(), 2, "only the rejected-positive and the 5xx");
2337 assert!(issues.iter().any(|i| i.kind == "valid_request_rejected"
2338 && i.path == "/v1/organizations"
2339 && i.status == 400));
2340 assert!(issues
2341 .iter()
2342 .any(|i| i.kind == "server_error" && i.path == "/v1/items" && i.status == 500));
2343 // The spec-valid missed negative is not present.
2344 assert!(!issues.iter().any(|i| i.path == "/v1/ok"));
2345
2346 let summary = r.render_summary();
2347 assert!(summary.contains("Definite issues (2)"));
2348 }
2349
2350 #[test]
2351 fn definite_issues_empty_renders_none_line() {
2352 let r = SelfTestReport {
2353 positive_pass: 1,
2354 positive_fail: 0,
2355 negative_caught: BTreeMap::from([("owasp".into(), 3)]),
2356 negative_missed: BTreeMap::new(),
2357 operations: vec![OperationResult {
2358 method: "GET".into(),
2359 path: "/v1/ok".into(),
2360 positive: Some(CaseOutcome {
2361 label: "positive".into(),
2362 expected_4xx: false,
2363 actual_status: 200,
2364 passed: true,
2365 }),
2366 negatives: vec![],
2367 }],
2368 };
2369 assert!(r.definite_issues().is_empty());
2370 assert!(r.render_summary().contains("Definite issues: none"));
2371 }
2372
2373 #[test]
2374 fn report_all_passed_when_no_miss() {
2375 let r = SelfTestReport {
2376 positive_pass: 5,
2377 positive_fail: 0,
2378 negative_caught: BTreeMap::from([("parameters".into(), 3)]),
2379 negative_missed: BTreeMap::new(),
2380 operations: Vec::new(),
2381 };
2382 assert!(r.all_passed());
2383 assert!(r.render_summary().contains("✓"));
2384 }
2385
2386 #[tokio::test]
2387 async fn run_self_test_against_unreachable_target_marks_all_failed() {
2388 // Use an obviously-dead port so we exercise the timeout/error
2389 // path without needing a live server in tests.
2390 let cfg = SelfTestConfig {
2391 target_url: "http://127.0.0.1:1".into(),
2392 timeout: Duration::from_millis(200),
2393 ..Default::default()
2394 };
2395 let ops = vec![op(
2396 "POST",
2397 "/users",
2398 Some("{\"name\":\"a\"}"),
2399 vec![],
2400 vec![],
2401 vec![],
2402 )];
2403 let report = run_self_test(&ops, &cfg).await.expect("client builds");
2404 // All cases hit the connect-error path → actual_status=0.
2405 // Positive expects 2xx-3xx → 0 is fail. Negatives expect 4xx
2406 // → 0 is also fail (we missed catching).
2407 assert_eq!(report.positive_fail, 1);
2408 assert!(report.negative_missed.values().sum::<usize>() >= 1);
2409 assert!(!report.all_passed());
2410 }
2411
2412 /// Round 17.2 — operations with both a positive sample AND a
2413 /// resolved request-body schema produce schema-driven negatives
2414 /// in addition to the spec-agnostic empty/wrong-type ones. The
2415 /// labels carry the field path so a per-category report can tell
2416 /// you exactly which field caught.
2417 #[tokio::test]
2418 async fn schema_driven_negatives_fire_when_schema_present() {
2419 use openapiv3::{ObjectType, ReferenceOr, Schema, SchemaData, SchemaKind, Type};
2420 let cfg = SelfTestConfig {
2421 target_url: "http://127.0.0.1:1".into(),
2422 timeout: Duration::from_millis(200),
2423 ..Default::default()
2424 };
2425 // Build an operation whose schema has a required `name` string
2426 // and an `age` integer. The mutator should produce, at
2427 // minimum: required-removed:name, required-removed:age,
2428 // type-mismatch:name, type-mismatch:age, integer-as-float:age,
2429 // plus the root-level type-mismatch.
2430 let mut obj = ObjectType::default();
2431 obj.properties.insert(
2432 "name".to_string(),
2433 ReferenceOr::Item(Box::new(Schema {
2434 schema_data: SchemaData::default(),
2435 schema_kind: SchemaKind::Type(Type::String(Default::default())),
2436 })),
2437 );
2438 obj.properties.insert(
2439 "age".to_string(),
2440 ReferenceOr::Item(Box::new(Schema {
2441 schema_data: SchemaData::default(),
2442 schema_kind: SchemaKind::Type(Type::Integer(Default::default())),
2443 })),
2444 );
2445 obj.required = vec!["name".into(), "age".into()];
2446 let schema = Schema {
2447 schema_data: SchemaData::default(),
2448 schema_kind: SchemaKind::Type(Type::Object(obj)),
2449 };
2450
2451 let mut o =
2452 op("POST", "/users", Some(r#"{"name":"Ada","age":30}"#), vec![], vec![], vec![]);
2453 o.request_body_schema = Some(schema);
2454 let report = run_self_test(&[o], &cfg).await.expect("client builds");
2455 // Bucket labels from the operation result.
2456 let labels: std::collections::BTreeSet<String> = report
2457 .operations
2458 .iter()
2459 .flat_map(|op| op.negatives.iter().map(|n| n.label.clone()))
2460 .collect();
2461 assert!(
2462 labels.iter().any(|l| l.starts_with("request-body:type-mismatch:")),
2463 "missing type-mismatch negative; got {labels:?}"
2464 );
2465 assert!(
2466 labels.iter().any(|l| l.starts_with("request-body:required-removed:")),
2467 "missing required-removed negative; got {labels:?}"
2468 );
2469 assert!(
2470 labels.iter().any(|l| l == "parameters:uri-too-long"),
2471 "missing URI-length negative; got {labels:?}"
2472 );
2473 }
2474
2475 /// Round 16 — operations with a body OR a path-param now produce
2476 /// negatives even without a sample body. Previously a POST whose
2477 /// body annotator failed produced *zero* negatives, so the self-test
2478 /// always reported "all passing" for that endpoint.
2479 #[tokio::test]
2480 async fn no_sample_body_still_produces_request_body_negatives() {
2481 let cfg = SelfTestConfig {
2482 target_url: "http://127.0.0.1:1".into(),
2483 timeout: Duration::from_millis(200),
2484 ..Default::default()
2485 };
2486 // POST with a body content type but no sample (annotator gap).
2487 let ops = vec![op("POST", "/x", None, vec![], vec![], vec![])];
2488 // No sample_body but request_body_content_type set:
2489 let mut ops_fixed = ops;
2490 ops_fixed[0].request_body_content_type = Some("application/json".into());
2491 let report = run_self_test(&ops_fixed, &cfg).await.expect("client builds");
2492 // Both request-body negatives (empty + wrong-type) should fire,
2493 // landing in `negative_missed` because the unreachable target
2494 // returns no 4xx. The point: count > 0.
2495 assert!(
2496 report.negative_missed.values().sum::<usize>() >= 2,
2497 "expected ≥2 request-body negatives, got {:?}",
2498 report.negative_missed
2499 );
2500 }
2501
2502 /// Round 16 — operations with a path-param now get a probe even
2503 /// when there's no body / required query / required header.
2504 /// Previously `/teams/{team-id}` with no other required fields
2505 /// produced zero negatives → always "all passing".
2506 #[tokio::test]
2507 async fn path_param_only_endpoint_produces_a_probe() {
2508 let cfg = SelfTestConfig {
2509 target_url: "http://127.0.0.1:1".into(),
2510 timeout: Duration::from_millis(200),
2511 ..Default::default()
2512 };
2513 let ops = vec![op(
2514 "GET",
2515 "/teams/{team-id}",
2516 None,
2517 vec![],
2518 vec![],
2519 vec![("team-id", "1")],
2520 )];
2521 let report = run_self_test(&ops, &cfg).await.expect("client builds");
2522 let total: usize = report.negative_caught.values().sum::<usize>()
2523 + report.negative_missed.values().sum::<usize>();
2524 assert!(total >= 1, "expected ≥1 path-param probe, got {:?}", report);
2525 }
2526
2527 /// Round 18.5 — when `geo_ip` is set, every default forwarded-
2528 /// IP header gets the IP appended (X-Forwarded-For,
2529 /// True-Client-IP, CF-Connecting-IP).
2530 #[test]
2531 fn effective_op_headers_appends_geo_ip_to_default_headers() {
2532 let ip: IpAddr = "203.0.113.42".parse().unwrap();
2533 let headers = effective_op_headers(
2534 &[("Accept".into(), "application/json".into())],
2535 Some(ip),
2536 &default_geo_source_headers(),
2537 );
2538 let names: Vec<&str> = headers.iter().map(|(k, _)| k.as_str()).collect();
2539 assert!(names.contains(&"Accept"));
2540 assert!(names.contains(&"X-Forwarded-For"));
2541 assert!(names.contains(&"True-Client-IP"));
2542 assert!(names.contains(&"CF-Connecting-IP"));
2543 // Every geo header carries the same IP value.
2544 let geo_values: Vec<&str> =
2545 headers.iter().filter(|(k, _)| k != "Accept").map(|(_, v)| v.as_str()).collect();
2546 for v in geo_values {
2547 assert_eq!(v, "203.0.113.42");
2548 }
2549 }
2550
2551 /// Round 18.5 — operations that already declare a forwarded-IP
2552 /// header (rare but legal — some specs hard-code one) keep their
2553 /// declared value; we don't clobber the spec.
2554 #[test]
2555 fn effective_op_headers_respects_spec_declared_header() {
2556 let ip: IpAddr = "203.0.113.99".parse().unwrap();
2557 let headers = effective_op_headers(
2558 &[("x-forwarded-for".into(), "10.0.0.1".into())],
2559 Some(ip),
2560 &["X-Forwarded-For".to_string()],
2561 );
2562 // The spec's lower-case value wins; we shouldn't add a
2563 // second X-Forwarded-For row that overrides it.
2564 let xff: Vec<&str> = headers
2565 .iter()
2566 .filter(|(k, _)| k.eq_ignore_ascii_case("x-forwarded-for"))
2567 .map(|(_, v)| v.as_str())
2568 .collect();
2569 assert_eq!(xff, vec!["10.0.0.1"]);
2570 }
2571
2572 /// Round 18.5 — None geo_ip and/or empty header list is a no-op.
2573 #[test]
2574 fn effective_op_headers_is_a_noop_without_geo_ip() {
2575 let base = vec![("Accept".into(), "json".into())];
2576 let h1 = effective_op_headers(&base, None, &default_geo_source_headers());
2577 assert_eq!(h1, base);
2578 let ip: IpAddr = "10.0.0.1".parse().unwrap();
2579 let h2 = effective_op_headers(&base, Some(ip), &[]);
2580 assert_eq!(h2, base);
2581 }
2582
2583 /// Round 18.5 — empty `source_ips` builds a single default
2584 /// client; a non-empty list builds N clients each attempting to
2585 /// bind. We can't reliably test the actual bind on CI (no
2586 /// loopback aliases), but a loopback IP is always bind-able.
2587 #[test]
2588 fn build_client_pool_one_per_source_ip() {
2589 let mut cfg = SelfTestConfig {
2590 target_url: "http://127.0.0.1:1".into(),
2591 timeout: Duration::from_millis(200),
2592 ..Default::default()
2593 };
2594 // Empty → one default client.
2595 assert_eq!(build_client_pool(&cfg).expect("default builds").len(), 1);
2596 // Non-empty → one per IP. Loopback bind is portable.
2597 cfg.source_ips = vec!["127.0.0.1".parse().unwrap()];
2598 assert_eq!(build_client_pool(&cfg).expect("bind loopback").len(), 1);
2599 }
2600
2601 /// Round 18.5 — geo IPs round-robin across operations. Hits an
2602 /// unreachable target so we can inspect the case outcomes; the
2603 /// point is to confirm `op_headers` carried the geo IP through
2604 /// (CaseOutcome doesn't surface headers directly, so we just
2605 /// verify the run completes without panicking and the result
2606 /// shape is correct when source_ips is non-empty too).
2607 #[tokio::test]
2608 async fn run_self_test_with_geo_source_completes() {
2609 let cfg = SelfTestConfig {
2610 target_url: "http://127.0.0.1:1".into(),
2611 timeout: Duration::from_millis(200),
2612 geo_source_ips: vec![
2613 "203.0.113.1".parse().unwrap(),
2614 "203.0.113.2".parse().unwrap(),
2615 ],
2616 ..Default::default()
2617 };
2618 let ops = vec![
2619 op("GET", "/a", None, vec![], vec![], vec![]),
2620 op("GET", "/b", None, vec![], vec![], vec![]),
2621 op("GET", "/c", None, vec![], vec![], vec![]),
2622 ];
2623 let report = run_self_test(&ops, &cfg).await.expect("client builds");
2624 assert_eq!(report.operations.len(), 3);
2625 }
2626
2627 /// Round 24 (f) — Srikanth saw the geo header on positive probes
2628 /// only; the four negative-probe call sites were passing
2629 /// `op.header_params` directly instead of `op_headers`, so the
2630 /// geo IP got dropped. This test runs a self-test that includes
2631 /// negative probes (uri-too-long, missing-query, etc.) under
2632 /// `--conformance-self-test-capture`, then asserts that EVERY
2633 /// captured probe (positive AND negative) carries one of the
2634 /// configured forwarded-IP headers.
2635 #[tokio::test]
2636 async fn geo_headers_present_on_every_probe_with_capture() {
2637 let sink: Arc<Mutex<Vec<CaseCapture>>> = Arc::new(Mutex::new(Vec::new()));
2638 let cfg = SelfTestConfig {
2639 target_url: "http://127.0.0.1:1".into(),
2640 timeout: Duration::from_millis(50),
2641 geo_source_ips: vec!["203.0.113.5".parse().unwrap()],
2642 capture: Some(sink.clone()),
2643 ..Default::default()
2644 };
2645 // An operation rich enough to trip several negative-probe
2646 // branches: header param (→ missing-header), query param
2647 // (→ missing-query), and a sample body (→ schema mutations
2648 // wouldn't fire without a schema, but uri-too-long always
2649 // does).
2650 let ops = vec![op(
2651 "GET",
2652 "/items",
2653 Some("{}"),
2654 vec![("id", "1")],
2655 vec![("X-Trace", "x")],
2656 vec![],
2657 )];
2658 let _ = run_self_test(&ops, &cfg).await.expect("client builds");
2659 let captures = sink.lock().unwrap();
2660 assert!(!captures.is_empty(), "self-test should record probes");
2661 // For every captured probe, at least one of the default geo
2662 // headers must be present and equal to the configured IP.
2663 let geo_headers: std::collections::HashSet<&str> =
2664 ["X-Forwarded-For", "True-Client-IP", "CF-Connecting-IP"].into_iter().collect();
2665 for c in captures.iter() {
2666 let has_geo = c
2667 .request_headers
2668 .iter()
2669 .any(|(k, v)| geo_headers.contains(k.as_str()) && v == "203.0.113.5");
2670 assert!(
2671 has_geo,
2672 "probe `{}` is missing the geo IP header; got headers: {:?}",
2673 c.label, c.request_headers
2674 );
2675 }
2676 }
2677
2678 /// Round 25 (k) — operations with a JSON request body now get four
2679 /// content-type-swap probes (xml / yaml / multipart / urlencoded).
2680 /// Verify they:
2681 /// 1. fire only when the operation declares a JSON body
2682 /// 2. carry the wrong Content-Type the probe is testing for
2683 /// 3. don't fire on body-less operations
2684 #[tokio::test]
2685 async fn content_type_swap_probes_fire_for_json_bodies() {
2686 let sink: Arc<Mutex<Vec<CaseCapture>>> = Arc::new(Mutex::new(Vec::new()));
2687 let cfg = SelfTestConfig {
2688 target_url: "http://127.0.0.1:1".into(),
2689 timeout: Duration::from_millis(50),
2690 capture: Some(sink.clone()),
2691 ..Default::default()
2692 };
2693 let ops = vec![
2694 op("POST", "/users", Some("{\"name\":\"a\"}"), vec![], vec![], vec![]),
2695 op("GET", "/ping", None, vec![], vec![], vec![]),
2696 ];
2697 let _ = run_self_test(&ops, &cfg).await.expect("client builds");
2698 let captures = sink.lock().unwrap();
2699
2700 let swap_labels: Vec<&str> = captures
2701 .iter()
2702 .filter(|c| c.label.starts_with("request-body:content-type-mismatch:"))
2703 .map(|c| c.label.as_str())
2704 .collect();
2705 assert_eq!(
2706 swap_labels.len(),
2707 4,
2708 "expected 4 content-type-swap probes (one per variant), got: {swap_labels:?}"
2709 );
2710 let expected_labels = [
2711 "request-body:content-type-mismatch:xml",
2712 "request-body:content-type-mismatch:yaml",
2713 "request-body:content-type-mismatch:multipart",
2714 "request-body:content-type-mismatch:urlencoded",
2715 ];
2716 for want in expected_labels {
2717 assert!(swap_labels.contains(&want), "missing swap probe `{want}`");
2718 }
2719
2720 // Each swap probe must carry the wrong Content-Type it's
2721 // testing for — that's the whole point.
2722 for c in captures.iter() {
2723 let Some(suffix) = c.label.strip_prefix("request-body:content-type-mismatch:") else {
2724 continue;
2725 };
2726 let want_ct = match suffix {
2727 "xml" => "application/xml",
2728 "yaml" => "application/yaml",
2729 "multipart" => "multipart/form-data",
2730 "urlencoded" => "application/x-www-form-urlencoded",
2731 _ => continue,
2732 };
2733 let got_ct = c
2734 .request_headers
2735 .iter()
2736 .find(|(k, _)| k.eq_ignore_ascii_case("content-type"))
2737 .map(|(_, v)| v.as_str())
2738 .unwrap_or("");
2739 assert_eq!(got_ct, want_ct, "swap probe `{}` sent wrong CT", c.label);
2740 }
2741
2742 // The body-less operation must NOT produce content-type-swap
2743 // probes (no body → no content type to lie about).
2744 let body_less_swaps = captures
2745 .iter()
2746 .filter(|c| {
2747 c.label.starts_with("request-body:content-type-mismatch:")
2748 && c.url.ends_with("/ping")
2749 })
2750 .count();
2751 assert_eq!(
2752 body_less_swaps, 0,
2753 "GET /ping has no request body; should not produce content-type-swap probes"
2754 );
2755 }
2756
2757 /// Round 27 (k variant b) — Srikanth's round-23 follow-up on (k):
2758 /// JSON envelope with embedded non-JSON field values. For each
2759 /// JSON-body operation, four extra probes fire that send valid
2760 /// JSON with an XML/YAML/multipart/urlencoded snippet stuffed
2761 /// into a string field. Content-Type stays `application/json`;
2762 /// expected is 2xx-3xx (the body parses); a 5xx flags a server
2763 /// that crashed on the embedded content.
2764 #[tokio::test]
2765 async fn embedded_content_probes_fire_with_honest_content_type() {
2766 let sink: Arc<Mutex<Vec<CaseCapture>>> = Arc::new(Mutex::new(Vec::new()));
2767 let cfg = SelfTestConfig {
2768 target_url: "http://127.0.0.1:1".into(),
2769 timeout: Duration::from_millis(50),
2770 capture: Some(sink.clone()),
2771 ..Default::default()
2772 };
2773 let ops = vec![op(
2774 "POST",
2775 "/users",
2776 Some("{\"name\":\"alice\",\"age\":30}"),
2777 vec![],
2778 vec![],
2779 vec![],
2780 )];
2781 let _ = run_self_test(&ops, &cfg).await.expect("client builds");
2782 let captures = sink.lock().unwrap();
2783 let embedded: Vec<&CaseCapture> = captures
2784 .iter()
2785 .filter(|c| c.label.starts_with("request-body:embedded-content:"))
2786 .collect();
2787 assert_eq!(
2788 embedded.len(),
2789 4,
2790 "expected 4 embedded-content probes, got: {:?}",
2791 embedded.iter().map(|c| &c.label).collect::<Vec<_>>()
2792 );
2793 // Every embedded probe must carry the honest application/json
2794 // Content-Type (NOT lie like the variant-a content-type-swap
2795 // probes do) and a request body that still parses as JSON.
2796 for c in &embedded {
2797 let ct = c
2798 .request_headers
2799 .iter()
2800 .find(|(k, _)| k.eq_ignore_ascii_case("content-type"))
2801 .map(|(_, v)| v.as_str())
2802 .unwrap_or("");
2803 assert!(
2804 ct.contains("application/json"),
2805 "embedded probe `{}` should keep Content-Type honest, got {ct}",
2806 c.label
2807 );
2808 let body = c.request_body.as_deref().unwrap_or("");
2809 assert!(
2810 serde_json::from_str::<serde_json::Value>(body).is_ok(),
2811 "embedded probe `{}` body should still be valid JSON, got: {body}",
2812 c.label
2813 );
2814 }
2815 }
2816
2817 /// `embed_payload_in_first_string_field` walks objects depth-first
2818 /// and replaces only the FIRST string-valued leaf, leaving the
2819 /// surrounding structure intact.
2820 #[test]
2821 fn embed_payload_replaces_first_string_only() {
2822 let sample = r#"{"name":"alice","age":30,"tags":["admin","user"]}"#;
2823 let mutated = embed_payload_in_first_string_field(sample, "<x/>")
2824 .expect("string field present so probe constructed");
2825 let v: serde_json::Value = serde_json::from_str(&mutated).unwrap();
2826 assert_eq!(v["name"], serde_json::json!("<x/>"));
2827 // age stays an integer (not stringified by the mutation).
2828 assert_eq!(v["age"], serde_json::json!(30));
2829 // tags array's strings stay untouched (we only replace the
2830 // first encountered string leaf, depth-first).
2831 assert_eq!(v["tags"][0], serde_json::json!("admin"));
2832 assert_eq!(v["tags"][1], serde_json::json!("user"));
2833 }
2834
2835 /// Round 34 (#829) — Srikanth on 0.3.178: when the positive
2836 /// sample has NO string field, the previous `{"data": <snippet>}`
2837 /// fallback produced an envelope that doesn't match real-API
2838 /// schemas (e.g. vCenter's `consolecli` PUT wants
2839 /// `{enabled: bool}`), so the server correctly 400'd and the
2840 /// bench misreported the 2xx-3xx expectation. Now we return None
2841 /// and the caller skips the probe.
2842 #[test]
2843 fn embed_payload_returns_none_when_no_string_field() {
2844 let no_strings = r#"{"a":1,"b":[2,3]}"#;
2845 assert!(embed_payload_in_first_string_field(no_strings, "<x><y></y></x>").is_none());
2846 // The exact vCenter-style case Srikanth hit.
2847 let bool_only = r#"{"enabled":true}"#;
2848 assert!(embed_payload_in_first_string_field(bool_only, "<x/>").is_none());
2849 }
2850
2851 #[test]
2852 fn embed_payload_returns_none_for_invalid_json_sample() {
2853 assert!(embed_payload_in_first_string_field("garbage", "a=1&b=2").is_none());
2854 }
2855
2856 /// Round 35 (#859) — Srikanth on 0.3.179 saw variant-b probes flag
2857 /// every 4xx as a mismatch when the spec field had a `pattern` /
2858 /// `format` validator that correctly rejected the embedded
2859 /// payload. The probe was only ever meant to catch 5xx (server
2860 /// crashed parsing the embedded content); 4xx is the well-behaved
2861 /// outcome. Tristate `ExpectedOutcome::NotServerError` lets a
2862 /// variant-b probe pass on 2xx-4xx and fail only on 5xx.
2863 #[test]
2864 fn expected_outcome_pass_rules() {
2865 // Success (positive): 2xx-3xx pass, 4xx + 5xx fail.
2866 assert!(ExpectedOutcome::Success.passes(200));
2867 assert!(ExpectedOutcome::Success.passes(201));
2868 assert!(ExpectedOutcome::Success.passes(204));
2869 assert!(ExpectedOutcome::Success.passes(301));
2870 assert!(!ExpectedOutcome::Success.passes(400));
2871 assert!(!ExpectedOutcome::Success.passes(415));
2872 assert!(!ExpectedOutcome::Success.passes(500));
2873 assert!(!ExpectedOutcome::Success.passes(0));
2874
2875 // ClientError (negative): only 4xx pass.
2876 assert!(!ExpectedOutcome::ClientError.passes(200));
2877 assert!(ExpectedOutcome::ClientError.passes(400));
2878 assert!(ExpectedOutcome::ClientError.passes(404));
2879 assert!(ExpectedOutcome::ClientError.passes(422));
2880 assert!(!ExpectedOutcome::ClientError.passes(500));
2881
2882 // NotServerError (variant-b): 2xx-4xx pass, 5xx fails.
2883 assert!(ExpectedOutcome::NotServerError.passes(200));
2884 assert!(ExpectedOutcome::NotServerError.passes(204));
2885 assert!(ExpectedOutcome::NotServerError.passes(400), "Srikanth's vCenter consolecli case: 400 from a pattern validator should NOT be a probe failure");
2886 assert!(ExpectedOutcome::NotServerError.passes(415));
2887 assert!(ExpectedOutcome::NotServerError.passes(422));
2888 assert!(
2889 !ExpectedOutcome::NotServerError.passes(500),
2890 "Server CRASH on embedded content is the only real failure"
2891 );
2892 assert!(!ExpectedOutcome::NotServerError.passes(502));
2893 assert!(!ExpectedOutcome::NotServerError.passes(503));
2894 // status 0 (network error / probe never reached the server) does not pass either
2895 assert!(!ExpectedOutcome::NotServerError.passes(0));
2896 }
2897
2898 /// Round 35 (#859) — the per-capture `expected_status_range`
2899 /// string is what the HTML viewer's "show mismatches only"
2900 /// filter and Srikanth's `jq` pipelines key off, so the new
2901 /// tristate must surface a third distinct value.
2902 #[test]
2903 fn expected_outcome_string_labels() {
2904 assert_eq!(ExpectedOutcome::Success.as_str(), "2xx-3xx");
2905 assert_eq!(ExpectedOutcome::ClientError.as_str(), "4xx");
2906 assert_eq!(ExpectedOutcome::NotServerError.as_str(), "2xx-4xx");
2907 }
2908
2909 /// Round 26 — Srikanth saw `at /: Type { kind: Single` in his
2910 /// 0.3.169 capture for the vCenter `infraprofile/configs` 202
2911 /// response (spec promised `type: string`, server returned a
2912 /// JSON object). The output was a broken-syntax debug string.
2913 /// This test reproduces his exact spec+body and asserts the
2914 /// message is readable.
2915 #[test]
2916 fn response_schema_error_message_is_readable() {
2917 let schema = serde_json::json!({"type": "string"});
2918 let body = r#"{"data":{},"id":"generated_id","status":"created"}"#;
2919 let err = validate_body_against_schema(body, &schema).expect("type-mismatch fires");
2920 // The message must NOT contain Rust debug syntax leftovers
2921 // ("Type { kind:", trailing "{" or "(" tokens). It SHOULD say
2922 // what type was expected.
2923 assert!(!err.contains("Type { kind"), "stale debug output: {err}");
2924 assert!(!err.contains("{ kind:"), "stale debug output: {err}");
2925 assert!(err.contains("string"), "should name expected type: {err}");
2926 // Round 29 — Srikanth on 0.3.172 was confused by `at /:`,
2927 // thinking it pointed to the URL path. The new format
2928 // explicitly says "response body root" for the root case
2929 // (and "response body at /<pointer>" for nested fields).
2930 assert!(
2931 err.contains("response body root"),
2932 "should label root explicitly so reader knows it's not the URL: {err}"
2933 );
2934 // Round 28 — Srikanth wanted the expected schema embedded
2935 // in the message so it reads as 'expected schema {"type":"string"}'.
2936 assert!(
2937 err.contains("expected schema") && err.contains("\"type\":\"string\""),
2938 "should include expected schema JSON: {err}"
2939 );
2940 }
2941
2942 /// Round 29 — for non-root paths the format reads
2943 /// "response body at /name: ...". Catches the case where the
2944 /// root rewording accidentally dropped the JSON-pointer for
2945 /// nested fields.
2946 #[test]
2947 fn response_schema_error_uses_response_body_prefix_for_nested_paths() {
2948 let schema = serde_json::json!({
2949 "type": "object",
2950 "required": ["name"],
2951 "properties": {"name": {"type": "string"}}
2952 });
2953 let body = r#"{"name": 123}"#;
2954 let err = validate_body_against_schema(body, &schema).expect("type-mismatch fires");
2955 assert!(
2956 err.contains("response body at /name"),
2957 "nested path should read 'response body at /name': {err}"
2958 );
2959 assert!(!err.contains("response body root"), "wrong label for nested: {err}");
2960 // Round 30 — the "expected schema" suffix should be the
2961 // sub-schema at /name, not the entire object schema. Reader
2962 // shouldn't have to scan a 300-char object to find the
2963 // constraint that failed.
2964 assert!(
2965 err.contains(r#"expected schema {"type":"string"}"#),
2966 "should show only the /name sub-schema, not the full object: {err}"
2967 );
2968 }
2969
2970 /// Round 30 — Srikanth asked how a deeper nested mismatch reads.
2971 /// Schema: `name.type` should be a string; body has it as a number.
2972 /// JSON pointer is `/name/type`.
2973 #[test]
2974 fn response_schema_error_uses_response_body_prefix_for_deep_nested_paths() {
2975 let schema = serde_json::json!({
2976 "type": "object",
2977 "properties": {
2978 "name": {
2979 "type": "object",
2980 "properties": {"type": {"type": "string"}}
2981 }
2982 }
2983 });
2984 let body = r#"{"name": {"type": 123}}"#;
2985 let err = validate_body_against_schema(body, &schema).expect("type-mismatch fires");
2986 assert!(
2987 err.contains("response body at /name/type"),
2988 "deep nested path should read 'response body at /name/type': {err}"
2989 );
2990 // Round 30 — for deep paths the sub-schema is the leaf
2991 // {"type":"string"}, not the wrapping object schemas.
2992 assert!(
2993 err.contains(r#"expected schema {"type":"string"}"#),
2994 "should show only the /name/type leaf sub-schema: {err}"
2995 );
2996 }
2997
2998 /// Round 30 — when the instance pointer can't be resolved through
2999 /// the schema's `properties` chain (e.g. additionalProperties hit),
3000 /// `sub_schema_at_pointer` returns None and the message falls back
3001 /// to the full schema. Verifies the fallback path is wired.
3002 #[test]
3003 fn sub_schema_at_pointer_falls_back_for_unresolvable_paths() {
3004 let schema = serde_json::json!({"type":"object","additionalProperties":true});
3005 // Walker can't resolve /unknown, so we get the full schema back.
3006 assert_eq!(
3007 sub_schema_at_pointer(&schema, "/unknown"),
3008 None,
3009 "unresolvable path should return None to trigger fallback"
3010 );
3011 // Root path returns the whole schema.
3012 assert_eq!(sub_schema_at_pointer(&schema, "/"), Some(schema.clone()));
3013 assert_eq!(sub_schema_at_pointer(&schema, ""), Some(schema));
3014 }
3015
3016 #[test]
3017 fn response_schema_error_required_field_is_readable() {
3018 let schema = serde_json::json!({
3019 "type": "object",
3020 "required": ["id"],
3021 "properties": {"id": {"type": "integer"}}
3022 });
3023 let body = r#"{"other": 1}"#;
3024 let err = validate_body_against_schema(body, &schema).expect("required-missing fires");
3025 assert!(err.contains("required field missing"), "{err}");
3026 assert!(err.contains("id"), "{err}");
3027 }
3028
3029 /// Round 31 — Srikanth's vCenter case on 0.3.174: the
3030 /// `Appliance.Recovery.Backup.SystemName.Archive.Info` schema has
3031 /// a multi-paragraph description and ~6 required fields, of which
3032 /// `comment` was missing in the response. Before this fix the
3033 /// printed schema was the WHOLE parent object schema (parent's
3034 /// description bleeding in, all sibling property schemas dumped)
3035 /// truncated to 300 chars; after the fix it's the missing field's
3036 /// own schema. Verifies (a) parent description is gone and
3037 /// (b) sibling property names don't appear in the message.
3038 #[test]
3039 fn response_schema_error_required_focuses_on_missing_field_only() {
3040 let schema = serde_json::json!({
3041 "description": "The Appliance.Recovery.Backup.SystemName.Archive.Info schema represents backup archive information.\n\nThis schema was added in vSphere API 6.7.",
3042 "type": "object",
3043 "required": ["comment", "location", "parts", "system_name", "timestamp", "version"],
3044 "properties": {
3045 "comment": {
3046 "type": "string",
3047 "description": "Custom comment added by the user for this backup."
3048 },
3049 "location": {"type": "string", "description": "Backup location URL."},
3050 "parts": {"type": "array", "items": {"type": "string"}},
3051 "system_name": {"type": "string"},
3052 "timestamp": {"type": "string", "format": "date-time"},
3053 "version": {"type": "string"}
3054 }
3055 });
3056 let body = r#"{"location":"x","parts":[],"system_name":"y","timestamp":"z","version":"v"}"#;
3057 let err = validate_body_against_schema(body, &schema).expect("required-missing fires");
3058 assert!(err.contains("required field missing: \"comment\""), "{err}");
3059 // Parent's description should not appear; only the `comment`
3060 // field's own description (if any) may.
3061 assert!(
3062 !err.contains("Appliance.Recovery.Backup"),
3063 "parent description should not bleed into focused schema: {err}"
3064 );
3065 // No sibling property names should appear in the focused schema
3066 // suffix.
3067 for sibling in ["location", "parts", "system_name", "timestamp", "version"] {
3068 assert!(
3069 !err.contains(&format!("\"{sibling}\"")),
3070 "sibling field {sibling} should not appear in focused schema: {err}"
3071 );
3072 }
3073 }
3074
3075 #[test]
3076 fn response_schema_error_none_on_match() {
3077 let schema = serde_json::json!({"type": "string"});
3078 assert_eq!(validate_body_against_schema("\"hello\"", &schema), None);
3079 }
3080
3081 /// Round 34 (#827) — Srikanth on 0.3.178 hit the vCenter
3082 /// `consolecli` PUT where the `enabled: boolean` property has a
3083 /// multi-paragraph description. The schema printout truncated
3084 /// mid-description, hiding `type: boolean` past the 300-char cap.
3085 /// Stripping `description` (and friends) before serializing must
3086 /// keep the type info visible.
3087 #[test]
3088 fn response_schema_error_strips_description_so_type_survives_truncation() {
3089 // Schema crafted so without stripping, `description` would
3090 // push `type` past the 300-char truncation cap. The
3091 // description we use here is intentionally close to the
3092 // vCenter-spec wording Srikanth quoted.
3093 let big_desc = "In the result of the #get and #list operations this property indicates whether proxying is enabled for a particular protocol. In the input to the test and set operations this property specifies whether proxying should be enabled for a particular protocol. This property was added in vSphere API 6.7. Defaults to enabled if both this field and the value field are unset.";
3094 let schema = serde_json::json!({
3095 "type": "object",
3096 "required": ["enabled"],
3097 "properties": {
3098 "enabled": {
3099 "type": "boolean",
3100 "description": big_desc,
3101 "example": true,
3102 }
3103 }
3104 });
3105 let body = r#"{}"#;
3106 let err = validate_body_against_schema(body, &schema).expect("required-missing fires");
3107 assert!(err.contains("required field missing: \"enabled\""), "{err}");
3108 assert!(
3109 err.contains(r#""type":"boolean""#),
3110 "the `type: boolean` keyword must survive truncation: {err}"
3111 );
3112 // Description should NOT appear (we stripped it) so the
3113 // suffix is type-focused, not prose.
3114 assert!(
3115 !err.contains("proxying is enabled"),
3116 "description should be stripped from the printed schema: {err}"
3117 );
3118 assert!(
3119 !err.contains("\"example\""),
3120 "`example` field should be stripped from the printed schema: {err}"
3121 );
3122 }
3123
3124 /// Round 34 (#827) — strip_schema_noise should keep all
3125 /// constraint keywords intact; only the prose noise goes.
3126 #[test]
3127 fn strip_schema_noise_preserves_constraint_keywords() {
3128 let schema = serde_json::json!({
3129 "type": "object",
3130 "required": ["a", "b"],
3131 "description": "should be stripped",
3132 "title": "should be stripped",
3133 "example": {"a": 1, "b": 2},
3134 "properties": {
3135 "a": {"type": "string", "format": "uri", "minLength": 1, "description": "drop"},
3136 "b": {"type": "integer", "minimum": 0, "maximum": 100, "summary": "drop"},
3137 },
3138 });
3139 let stripped = strip_schema_noise(&schema);
3140 let s = serde_json::to_string(&stripped).unwrap();
3141 // Constraint keywords survive.
3142 for keep in [
3143 "\"type\"",
3144 "\"required\"",
3145 "\"properties\"",
3146 "\"format\"",
3147 "\"minLength\"",
3148 "\"minimum\"",
3149 "\"maximum\"",
3150 ] {
3151 assert!(s.contains(keep), "should keep {keep}: {s}");
3152 }
3153 // Noise fields are gone.
3154 for drop in ["description", "title", "example", "summary"] {
3155 assert!(!s.contains(&format!("\"{drop}\"")), "should strip {drop}: {s}");
3156 }
3157 }
3158
3159 #[test]
3160 fn json_serialises_report() {
3161 let r = SelfTestReport {
3162 positive_pass: 1,
3163 positive_fail: 0,
3164 negative_caught: BTreeMap::new(),
3165 negative_missed: BTreeMap::new(),
3166 operations: vec![OperationResult {
3167 method: "GET".into(),
3168 path: "/x".into(),
3169 positive: Some(CaseOutcome {
3170 label: "positive".into(),
3171 expected_4xx: false,
3172 actual_status: 200,
3173 passed: true,
3174 }),
3175 negatives: Vec::new(),
3176 }],
3177 };
3178 let json = serde_json::to_value(&r).expect("serialises");
3179 assert_eq!(json["positive_pass"], serde_json::json!(1));
3180 assert_eq!(json["operations"][0]["positive"]["actual_status"], serde_json::json!(200));
3181 }
3182}