1use super::self_test::{CaseOutcome, OperationResult, SelfTestReport};
22use std::collections::BTreeMap;
23
24pub fn render_html(report: &SelfTestReport, audit: Option<&serde_json::Value>) -> String {
31 render_html_with_options(report, audit, &RenderOptions::default())
32}
33
34#[derive(Debug, Clone)]
40pub struct RenderOptions {
41 pub missed_cap: Option<usize>,
42}
43
44impl Default for RenderOptions {
45 fn default() -> Self {
46 Self {
47 missed_cap: Some(200),
48 }
49 }
50}
51
52pub fn render_html_with_options(
55 report: &SelfTestReport,
56 audit: Option<&serde_json::Value>,
57 opts: &RenderOptions,
58) -> String {
59 let mut html = String::new();
60 html.push_str(HEAD);
61 push_header(&mut html, report);
62 push_summary_cards(&mut html, report);
63 let anchors = compute_anchor_set(report, opts);
69 push_grouped_category_table(&mut html, report, &anchors);
75 push_operations_table(&mut html, report, opts, &anchors);
76 if let Some(a) = audit {
77 push_spec_audit(&mut html, a);
78 }
79 html.push_str(FOOT);
80 html
81}
82
83fn compute_anchor_set(report: &SelfTestReport, opts: &RenderOptions) -> AnchorSet {
90 let mut missed: Vec<(&OperationResult, &CaseOutcome)> = Vec::new();
91 for op in &report.operations {
92 for neg in &op.negatives {
93 if !neg.passed {
94 missed.push((op, neg));
95 }
96 }
97 }
98 let take = opts.missed_cap.unwrap_or(usize::MAX);
99 let mut cats: std::collections::HashSet<String> = std::collections::HashSet::new();
100 let mut ops: std::collections::HashSet<String> = std::collections::HashSet::new();
101 for (op, neg) in missed.iter().take(take) {
102 let cat = neg.label.split(':').next().unwrap_or("other").to_string();
103 cats.insert(cat);
104 ops.insert(op_anchor_slug(&op.method, &op.path));
105 }
106 AnchorSet { cats, ops }
107}
108
109#[derive(Default)]
112struct AnchorSet {
113 cats: std::collections::HashSet<String>,
114 ops: std::collections::HashSet<String>,
115}
116
117const HEAD: &str = r#"<!doctype html>
119<html lang="en">
120<head>
121<meta charset="utf-8">
122<title>MockForge Conformance Report</title>
123<style>
124 body { font-family: -apple-system, system-ui, sans-serif; max-width: 1100px;
125 margin: 2rem auto; padding: 0 1rem; color: #1f2933; line-height: 1.5; }
126 h1 { font-size: 1.8rem; margin: 0 0 0.5rem; }
127 h2 { font-size: 1.3rem; margin: 2rem 0 0.5rem; border-bottom: 1px solid #d1d5db; padding-bottom: 0.3rem; }
128 .meta { color: #6b7280; font-size: 0.9rem; }
129 .cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 0.75rem; margin: 1rem 0; }
130 .card { padding: 0.75rem 1rem; border-radius: 6px; background: #f3f4f6; }
131 .card .label { font-size: 0.75rem; text-transform: uppercase; letter-spacing: 0.05em; color: #6b7280; }
132 .card .value { font-size: 1.6rem; font-weight: 600; color: #1f2933; }
133 .card.ok { background: #ecfdf5; } .card.ok .value { color: #047857; }
134 .card.warn { background: #fffbeb; } .card.warn .value { color: #b45309; }
135 .card.err { background: #fef2f2; } .card.err .value { color: #b91c1c; }
136 table { width: 100%; border-collapse: collapse; margin: 0.5rem 0 1.5rem; font-size: 0.9rem; }
137 th, td { text-align: left; padding: 0.5rem 0.75rem; border-bottom: 1px solid #e5e7eb; }
138 th { background: #f9fafb; font-weight: 600; color: #374151; }
139 tr:hover { background: #f9fafb; }
140 .badge { display: inline-block; padding: 0.1rem 0.5rem; border-radius: 999px; font-size: 0.75rem; font-weight: 500; }
141 .badge.pass { background: #d1fae5; color: #047857; }
142 .badge.fail { background: #fee2e2; color: #b91c1c; }
143 .badge.info { background: #dbeafe; color: #1d4ed8; }
144 .badge.warn { background: #fef3c7; color: #92400e; }
145 .badge.err { background: #fee2e2; color: #b91c1c; }
146 .small { color: #6b7280; font-size: 0.85rem; }
147 code { background: #f3f4f6; padding: 0.05rem 0.3rem; border-radius: 3px; font-size: 0.9em; }
148</style>
149</head>
150<body>
151"#;
152
153const FOOT: &str = "\n</body>\n</html>\n";
154
155fn push_header(out: &mut String, _report: &SelfTestReport) {
156 out.push_str("<h1>MockForge Conformance Report</h1>\n");
157 out.push_str(
163 "<p class=\"meta\">Generated by <code>mockforge bench --conformance-self-test</code>. \
164 Probe-label reference: \
165 <a href=\"https://docs.mockforge.dev/reference/conformance-self-test-probes.html\">\
166 docs.mockforge.dev/reference/conformance-self-test-probes</a>.</p>\n",
167 );
168}
169
170fn push_summary_cards(out: &mut String, report: &SelfTestReport) {
171 let positives = report.positive_pass + report.positive_fail;
172 let neg_caught: usize = report.negative_caught.values().sum();
173 let neg_missed: usize = report.negative_missed.values().sum();
174 let pos_class = if report.positive_fail == 0 {
175 "ok"
176 } else {
177 "err"
178 };
179 let miss_class = if neg_missed == 0 { "ok" } else { "warn" };
180 out.push_str("<div class=\"cards\">\n");
181 push_card(out, "Positive cases", positives, pos_class);
182 push_card(out, "Positive failures", report.positive_fail, pos_class);
183 push_card(out, "Negatives matched (4xx)", neg_caught, "ok");
184 push_card(out, "Negatives mismatched (non-4xx)", neg_missed, miss_class);
185 push_card(out, "Operations", report.operations.len(), "");
186 out.push_str("</div>\n");
187}
188
189fn push_card(out: &mut String, label: &str, value: usize, class: &str) {
190 let class_attr = if class.is_empty() {
191 String::new()
192 } else {
193 format!(" {}", class)
194 };
195 out.push_str(&format!(
196 " <div class=\"card{class_attr}\"><div class=\"label\">{}</div><div class=\"value\">{}</div></div>\n",
197 html_escape(label),
198 value
199 ));
200}
201
202fn push_grouped_category_table(out: &mut String, report: &SelfTestReport, anchors: &AnchorSet) {
212 out.push_str("<h2>Negatives by category</h2>\n");
213 let mut keys: Vec<&String> =
214 report.negative_caught.keys().chain(report.negative_missed.keys()).collect();
215 keys.sort();
216 keys.dedup();
217 if keys.is_empty() {
218 out.push_str("<p class=\"small\">No negative probes ran — typically means no operations had any injectable surface.</p>\n");
219 return;
220 }
221 let mut rows: Vec<(&'static str, &String)> =
223 keys.into_iter().map(|c| (family_for_category(c), c)).collect();
224 rows.sort_by(|a, b| a.0.cmp(b.0).then_with(|| a.1.cmp(b.1)));
225 out.push_str("<table>\n<thead><tr><th>Family</th><th>Category</th><th>Matched (4xx)</th><th>Mismatched (non-4xx)</th><th>Status</th></tr></thead>\n<tbody>\n");
226 for (family, cat) in rows {
227 let caught = report.negative_caught.get(cat).copied().unwrap_or(0);
228 let missed = report.negative_missed.get(cat).copied().unwrap_or(0);
229 let (badge_class, badge_text) = if missed == 0 {
230 ("pass", "PASS")
231 } else {
232 ("fail", "FAIL")
233 };
234 let missed_cell = if missed > 0 && anchors.cats.contains(cat) {
236 format!("<a href=\"#miss-cat-{}\">{}</a>", html_escape(cat), missed)
237 } else {
238 missed.to_string()
239 };
240 out.push_str(&format!(
241 "<tr><td>{}</td><td><code>{}</code></td><td>{}</td><td>{}</td><td><span class=\"badge {}\">{}</span></td></tr>\n",
242 html_escape(family),
243 html_escape(cat),
244 caught,
245 missed_cell,
246 badge_class,
247 badge_text
248 ));
249 }
250 out.push_str("</tbody></table>\n");
251}
252
253fn family_for_category(cat: &str) -> &'static str {
258 match cat {
259 "request-body" => "Request body",
260 "parameters" => "Parameters",
261 "security" | "owasp" => "Security",
262 _ => "other",
263 }
264}
265
266fn push_operations_table(
267 out: &mut String,
268 report: &SelfTestReport,
269 opts: &RenderOptions,
270 anchors: &AnchorSet,
271) {
272 out.push_str("<h2>Per-operation results</h2>\n");
273 if report.operations.is_empty() {
274 out.push_str("<p class=\"small\">No operations.</p>\n");
275 return;
276 }
277 out.push_str("<table>\n<thead><tr><th>Method</th><th>Path</th><th>Positive</th><th>Matched / Mismatched</th><th>By category</th></tr></thead>\n<tbody>\n");
282 for op in &report.operations {
283 let pos_badge = match &op.positive {
284 Some(p) if p.passed => "<span class=\"badge pass\">2xx ✓</span>".to_string(),
285 Some(p) => format!("<span class=\"badge fail\">{} ✗</span>", p.actual_status),
286 None => "<span class=\"badge info\">none</span>".into(),
287 };
288 let (caught, missed) = op.negatives.iter().partition::<Vec<&CaseOutcome>, _>(|n| n.passed);
289 let op_slug = op_anchor_slug(&op.method, &op.path);
295 let missed_cell = if missed.is_empty() {
296 "0".to_string()
297 } else if anchors.ops.contains(&op_slug) {
298 format!("<a href=\"#miss-op-{}\">{}</a>", op_slug, missed.len())
299 } else {
300 missed.len().to_string()
301 };
302 let mut by_cat: BTreeMap<&str, usize> = BTreeMap::new();
306 for m in &missed {
307 let cat = m.label.split(':').next().unwrap_or("other");
308 *by_cat.entry(cat).or_insert(0) += 1;
309 }
310 let by_cat_cell = if by_cat.is_empty() {
311 String::new()
312 } else {
313 by_cat
314 .iter()
315 .map(|(cat, n)| format!("<code>{}:{}</code>", html_escape(cat), n))
316 .collect::<Vec<_>>()
317 .join(" ")
318 };
319 out.push_str(&format!(
320 "<tr><td><code>{}</code></td><td><code>{}</code></td><td>{}</td><td>{} / {}</td><td>{}</td></tr>\n",
321 html_escape(&op.method),
322 html_escape(&op.path),
323 pos_badge,
324 caught.len(),
325 missed_cell,
326 by_cat_cell
327 ));
328 }
329 out.push_str("</tbody></table>\n");
330 push_missed_detail(out, report, opts);
331}
332
333fn op_anchor_slug(method: &str, path: &str) -> String {
340 let mut s = format!("{method}_{path}");
341 s = s.to_ascii_lowercase();
342 s = s.chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '_' }).collect();
343 s
344}
345
346fn expected_status_label(case: &CaseOutcome) -> &'static str {
350 if case.expected_4xx {
351 "4xx (reject)"
352 } else {
353 "2xx-3xx (accept)"
354 }
355}
356
357fn push_missed_detail(out: &mut String, report: &SelfTestReport, opts: &RenderOptions) {
358 let mut missed: Vec<(&OperationResult, &CaseOutcome)> = Vec::new();
363 for op in &report.operations {
364 for neg in &op.negatives {
365 if !neg.passed {
366 missed.push((op, neg));
367 }
368 }
369 }
370 if missed.is_empty() {
371 return;
372 }
373 out.push_str(
374 "<h2>Mismatched negatives (server returned non-4xx to a probe expecting 4xx)</h2>\n",
375 );
376 let total = missed.len();
379 let cap_msg = match opts.missed_cap {
380 Some(cap) if total > cap => format!(
381 "{} mismatched negative(s). Showing first {} (raise with <code>--report-missed-cap N</code>, or <code>0</code> for no cap); full set in <code>conformance-self-test.json</code>.",
382 total, cap
383 ),
384 Some(_) => format!("{} mismatched negative(s). All shown.", total),
385 None => format!("{} mismatched negative(s). All shown (no cap).", total),
386 };
387 out.push_str(&format!("<p class=\"small\">{cap_msg}</p>\n"));
388 out.push_str("<table>\n<thead><tr><th>Method</th><th>Path</th><th>Label</th><th>Expected</th><th>Actual</th></tr></thead>\n<tbody>\n");
389 let take = opts.missed_cap.unwrap_or(usize::MAX);
390 let mut seen_cat: std::collections::HashSet<String> = std::collections::HashSet::new();
399 let mut seen_op: std::collections::HashSet<String> = std::collections::HashSet::new();
400 for (op, neg) in missed.iter().take(take) {
401 let cat = neg.label.split(':').next().unwrap_or("other").to_string();
402 let op_slug = op_anchor_slug(&op.method, &op.path);
403 let tr_id = if seen_cat.insert(cat.clone()) {
404 format!(" id=\"miss-cat-{}\"", html_escape(&cat))
405 } else {
406 String::new()
407 };
408 let op_anchor = if seen_op.insert(op_slug.clone()) {
409 format!("<span id=\"miss-op-{op_slug}\"></span>")
410 } else {
411 String::new()
412 };
413 out.push_str(&format!(
414 "<tr{}><td>{}<code>{}</code></td><td><code>{}</code></td><td><code>{}</code></td><td><span class=\"badge info\">{}</span></td><td>{}</td></tr>\n",
415 tr_id,
416 op_anchor,
417 html_escape(&op.method),
418 html_escape(&op.path),
419 html_escape(&neg.label),
420 expected_status_label(neg),
421 neg.actual_status
422 ));
423 }
424 out.push_str("</tbody></table>\n");
425}
426
427fn push_spec_audit(out: &mut String, audit: &serde_json::Value) {
428 out.push_str("<h2>Spec audit</h2>\n");
429 let findings = audit.get("findings").and_then(|v| v.as_array());
430 let coverage = audit.get("datatype_coverage").and_then(|v| v.as_object());
431 let ops = audit.get("operations_audited").and_then(|v| v.as_u64()).unwrap_or(0);
432 out.push_str(&format!(
433 "<p class=\"small\">Audited {ops} operation(s). Coverage map: {} datatype kind(s).</p>\n",
434 coverage.map(|c| c.len()).unwrap_or(0)
435 ));
436 if let Some(findings) = findings {
437 if findings.is_empty() {
438 out.push_str("<p class=\"small\">No findings.</p>\n");
439 } else {
440 let mut by_sev: BTreeMap<String, Vec<&serde_json::Value>> = BTreeMap::new();
442 for f in findings {
443 let sev = f.get("severity").and_then(|v| v.as_str()).unwrap_or("info").to_string();
444 by_sev.entry(sev).or_default().push(f);
445 }
446 out.push_str("<table>\n<thead><tr><th>Severity</th><th>Category</th><th>Location</th><th>Message</th></tr></thead>\n<tbody>\n");
447 for (sev, items) in by_sev {
448 let badge_class = match sev.as_str() {
449 "error" => "err",
450 "warning" => "warn",
451 _ => "info",
452 };
453 for item in items {
454 let cat = item.get("category").and_then(|v| v.as_str()).unwrap_or("");
455 let loc = item.get("location").and_then(|v| v.as_str()).unwrap_or("");
456 let msg = item.get("message").and_then(|v| v.as_str()).unwrap_or("");
457 out.push_str(&format!(
458 "<tr><td><span class=\"badge {}\">{}</span></td><td><code>{}</code></td><td><code>{}</code></td><td>{}</td></tr>\n",
459 badge_class,
460 html_escape(&sev),
461 html_escape(cat),
462 html_escape(loc),
463 html_escape(msg)
464 ));
465 }
466 }
467 out.push_str("</tbody></table>\n");
468 }
469 }
470 if let Some(coverage) = coverage {
471 let mut entries: Vec<(&String, u64)> =
472 coverage.iter().filter_map(|(k, v)| v.as_u64().map(|c| (k, c))).collect();
473 entries.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(b.0)));
474 if !entries.is_empty() {
475 out.push_str("<h2>Datatype coverage</h2>\n");
476 out.push_str("<table>\n<thead><tr><th>Type</th><th>Count</th></tr></thead>\n<tbody>\n");
477 for (kind, count) in entries.iter().take(40) {
478 out.push_str(&format!(
479 "<tr><td><code>{}</code></td><td>{}</td></tr>\n",
480 html_escape(kind),
481 count
482 ));
483 }
484 out.push_str("</tbody></table>\n");
485 }
486 }
487}
488
489fn html_escape(s: &str) -> String {
490 let mut out = String::with_capacity(s.len());
491 for c in s.chars() {
492 match c {
493 '&' => out.push_str("&"),
494 '<' => out.push_str("<"),
495 '>' => out.push_str(">"),
496 '"' => out.push_str("""),
497 '\'' => out.push_str("'"),
498 _ => out.push(c),
499 }
500 }
501 out
502}
503
504#[cfg(test)]
505mod tests {
506 use super::*;
507 use crate::conformance::self_test::{CaseOutcome, OperationResult, SelfTestReport};
508
509 fn sample_report() -> SelfTestReport {
510 SelfTestReport {
511 positive_pass: 3,
512 positive_fail: 1,
513 negative_caught: BTreeMap::from([("request-body".into(), 4), ("parameters".into(), 2)]),
514 negative_missed: BTreeMap::from([("owasp".into(), 1)]),
515 operations: vec![OperationResult {
516 method: "POST".into(),
517 path: "/users".into(),
518 positive: Some(CaseOutcome {
519 label: "positive".into(),
520 expected_4xx: false,
521 actual_status: 201,
522 passed: true,
523 }),
524 negatives: vec![CaseOutcome {
525 label: "owasp:sqli".into(),
526 expected_4xx: true,
527 actual_status: 200,
528 passed: false,
529 }],
530 }],
531 }
532 }
533
534 #[test]
535 fn html_contains_expected_sections() {
536 let html = render_html(&sample_report(), None);
537 assert!(html.contains("<title>MockForge Conformance Report</title>"));
538 assert!(html.contains("Positive cases"));
539 assert!(html.contains("Negatives by category"));
540 assert!(html.contains("Per-operation results"));
541 assert!(html.contains("Mismatched negatives"));
543 assert!(html.contains("request-body"));
545 assert!(html.contains("owasp:sqli"));
546 assert!(html.contains("/users"));
547 assert!(!html.contains("Negatives by category family"));
550 assert!(html.contains("<th>Family</th>"));
551 }
552
553 #[test]
558 fn html_category_table_assigns_each_category_to_a_family() {
559 let mut report = SelfTestReport::default();
560 report.negative_caught.insert("request-body".into(), 3);
561 report.negative_missed.insert("parameters".into(), 1);
562 report.negative_missed.insert("security".into(), 2);
563 report.negative_caught.insert("owasp".into(), 4);
564 let html = render_html(&report, None);
565 assert!(html.contains(">Request body</td>"));
566 assert!(html.contains(">Parameters</td>"));
567 assert_eq!(html.matches(">Security</td>").count(), 2);
569 assert!(!html.contains(">other</td>"));
571 }
572
573 #[test]
574 fn html_renders_audit_section_when_present() {
575 let audit = serde_json::json!({
576 "findings": [
577 {"category": "servers", "severity": "warning",
578 "location": "#/servers", "message": "no servers declared"}
579 ],
580 "datatype_coverage": {"string": 5, "integer": 3},
581 "operations_audited": 7
582 });
583 let html = render_html(&sample_report(), Some(&audit));
584 assert!(html.contains("Spec audit"));
585 assert!(html.contains("no servers declared"));
586 assert!(html.contains("Datatype coverage"));
587 assert!(html.contains("string"));
588 assert!(html.contains("Audited 7 operation"));
589 }
590
591 #[test]
592 fn html_escapes_special_chars_in_labels() {
593 let mut report = sample_report();
594 report.operations[0].path = "/items/<script>".into();
595 report.operations[0].negatives[0].label = "owasp:xss:<>\"&".into();
596 let html = render_html(&report, None);
597 assert!(!html.contains("/items/<script>"));
599 assert!(html.contains("<script>"));
600 assert!(html.contains("""));
601 }
602
603 #[test]
604 fn html_handles_empty_report() {
605 let html = render_html(&SelfTestReport::default(), None);
606 assert!(html.contains("No negative probes ran"));
607 assert!(html.contains("No operations."));
608 }
609
610 #[test]
611 fn html_caps_missed_detail_at_default_200_rows() {
612 let mut report = SelfTestReport::default();
613 for i in 0..250 {
614 report.operations.push(OperationResult {
615 method: "GET".into(),
616 path: format!("/r/{i}"),
617 positive: None,
618 negatives: vec![CaseOutcome {
619 label: "parameters:missing-query".into(),
620 expected_4xx: true,
621 actual_status: 200,
622 passed: false,
623 }],
624 });
625 }
626 report.negative_missed.insert("parameters".into(), 250);
627 let html = render_html(&report, None);
628 assert!(html.contains("250 mismatched negative"));
630 assert!(html.contains("Showing first 200"));
631 assert!(html.contains("--report-missed-cap"));
632 }
633
634 #[test]
638 fn html_no_cap_shows_all_rows() {
639 let mut report = SelfTestReport::default();
640 for i in 0..50 {
641 report.operations.push(OperationResult {
642 method: "GET".into(),
643 path: format!("/r/{i}"),
644 positive: None,
645 negatives: vec![CaseOutcome {
646 label: "parameters:missing-query".into(),
647 expected_4xx: true,
648 actual_status: 200,
649 passed: false,
650 }],
651 });
652 }
653 let opts = RenderOptions { missed_cap: None };
654 let html = render_html_with_options(&report, None, &opts);
655 assert!(html.contains("50 mismatched negative"));
656 assert!(html.contains("All shown (no cap)"));
657 assert!(!html.contains("Showing first"));
658 }
659
660 #[test]
663 fn html_missed_table_has_expected_column() {
664 let mut report = sample_report();
665 report.operations[0].negatives = vec![CaseOutcome {
668 label: "security:bad-bearer".into(),
669 expected_4xx: true,
670 actual_status: 200,
671 passed: false,
672 }];
673 let html = render_html(&report, None);
674 assert!(html.contains("Expected"), "Expected column header missing");
675 assert!(
676 html.contains("4xx (reject)"),
677 "expected-status badge for negative probe missing"
678 );
679 }
680
681 #[test]
687 fn html_count_links_only_emit_for_visible_anchors() {
688 let mut report = SelfTestReport::default();
689 let cats = ["cat-a", "cat-b", "cat-a", "cat-b"];
695 for (i, c) in cats.iter().enumerate() {
696 report.operations.push(OperationResult {
697 method: "GET".into(),
698 path: format!("/r/{i}"),
699 positive: None,
700 negatives: vec![CaseOutcome {
701 label: format!("{c}:fail-{i}"),
702 expected_4xx: true,
703 actual_status: 200,
704 passed: false,
705 }],
706 });
707 *report.negative_missed.entry((*c).to_string()).or_insert(0) += 1;
708 }
709 let opts = RenderOptions {
710 missed_cap: Some(1),
711 };
712 let html = render_html_with_options(&report, None, &opts);
713 assert!(html.contains("id=\"miss-cat-cat-a\""));
716 assert!(!html.contains("id=\"miss-cat-cat-b\""));
717 assert!(html.contains("<a href=\"#miss-cat-cat-a\">"));
720 assert!(!html.contains("<a href=\"#miss-cat-cat-b\">"));
721 assert!(html.contains("<a href=\"#miss-op-get__r_0\">"));
724 assert!(!html.contains("<a href=\"#miss-op-get__r_2\">"));
725 }
726}