Repository navigation
Expand file tree
/
Copy pathreport_projection.py
More file actions
1056 lines (963 loc) · 40.7 KB
/
Copy pathreport_projection.py
File metadata and controls
1056 lines (963 loc) · 40.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""Project canonical Codex Security scan JSON into the standard reports."""
from __future__ import annotations
import argparse
import json
import re
from collections import Counter
from collections.abc import Iterator
from itertools import chain
from typing import Any
SEVERITY_ORDER = {"critical": 0, "high": 1, "medium": 2, "low": 3, "informational": 4}
CONFIDENCE_ORDER = {"high": 0, "medium": 1, "low": 2}
REPORTABLE_SEVERITIES = {"critical", "high", "medium", "low"}
THREAT_MODEL_SECTIONS = (
("Assets", "assets"),
("Trust Boundaries", "trustBoundaries"),
("Attacker Capabilities", "attackerCapabilities"),
("Security Objectives", "securityObjectives"),
("Assumptions", "assumptions"),
)
DISPOSITION_LABELS = {
"reported": "Reported",
"no_issue_found": "No issue found",
"rejected": "Rejected",
"not_applicable": "Not applicable",
"needs_follow_up": "Needs follow-up",
}
WRITEUP_REPORT_PATH_RE = re.compile(r"^findings/([a-z0-9][a-z0-9._-]*)/\1\.md$")
INLINE_CODE_RE = r"(?<!`)`[^`\n]+`(?!`)"
ENTITY_AMP_RE = r"&(?=(?:#[0-9]+|#[xX][0-9A-Fa-f]+|[A-Za-z][A-Za-z0-9]*);)"
WWW_LINK_RE = r"(?<![^\s*_~(])(?i:www)\.[^\s<>]+"
class ReportProjectionError(ValueError):
"""Raised when a canonical scan cannot be projected into a valid report."""
def markdown_threat_model_content(model: dict[str, Any]) -> str | None:
"""Return nonblank authored content for a Markdown model, otherwise None."""
content = model.get("content")
if model.get("format") == "markdown" and isinstance(content, str) and content.strip():
return content
return None
def _escape_markdown(value: str) -> str:
# Locate whole URLs before matching code spans: a URL can contain backticks.
urls = [match.span() for match in re.finditer(WWW_LINK_RE, value)]
# Preserve protocol-relative and fuzzy links without a domain/TLD table.
for match in re.finditer(r"[^\s<>]+", value):
token = match[0]
dot = token.split("/", 1)[0].find(".")
if "//" in token or (dot >= 0 and re.search(r"[/?#]", token[dot + 1 :])):
urls.append(match.span())
punctuation = r"[\\`*_\[\]<>]|" + ENTITY_AMP_RE
pattern = f"(?P<code>{INLINE_CODE_RE})|{punctuation}"
def escape(match: re.Match[str]) -> str:
if match.lastgroup == "code":
return match[0]
# GFM autolinks retain backslashes literally, including in query strings.
if match[0] == "&" and any(start <= match.start() < end for start, end in urls):
return "&"
return "\\" + match[0]
return re.sub(pattern, escape, value)
def _text(value: Any, fallback: str) -> str:
candidate = value if isinstance(value, str) and value.strip() else fallback
normalized = " ".join(candidate.split())
if re.match(r"^(?:#{1,6}\s|[-*+]\s|>\s|```|~~~|\d+[.)]\s|\|)", normalized):
normalized = f"Text: {normalized}"
return _escape_markdown(normalized)
def _string_values(value: Any) -> Iterator[str]:
if isinstance(value, str):
yield value
elif isinstance(value, list):
yield from (item for item in value if isinstance(item, str))
def _strings(value: Any) -> list[str]:
return [text for item in _string_values(value) if (text := _text(item, ""))]
def _path_label(value: str, *, ensure_ascii: bool = False) -> str:
if "," in value or value != " ".join(value.split()) or any(ord(c) < 32 for c in value):
quoted = json.dumps(value, ensure_ascii=ensure_ascii)
return "".join(c if c.isprintable() else json.dumps(c)[1:-1] for c in quoted)
return value
def _path_text(value: str, *, ensure_ascii: bool = False) -> str:
label = _path_label(value, ensure_ascii=ensure_ascii)
if label != value or re.search(ENTITY_AMP_RE, value):
marker = _code_fence(label, minimum=1)
padding = " " if label.startswith("`") or label.endswith("`") else ""
return f"{marker}{padding}{label}{padding}{marker}"
return re.sub(r"([\\`*_\[\]<>])", r"\\\1", value)
def _cell(value: Any) -> str:
return _text(value, "none").replace("|", "\\|").replace("\n", "<br>")
def _deep_report_id(finding: dict[str, Any]) -> str:
extensions = finding.get("extensions")
if isinstance(extensions, dict):
report_id = extensions.get("reportId")
if isinstance(report_id, str) and report_id.strip():
return report_id
ledger_row_id = extensions.get("ledgerRowId")
if isinstance(ledger_row_id, str) and ledger_row_id.strip():
return ledger_row_id
identity = finding.get("identity")
if isinstance(identity, dict):
instance = identity.get("instance")
if isinstance(instance, str) and instance.strip():
return instance
occurrence_id = finding.get("occurrenceId")
return (
occurrence_id
if isinstance(occurrence_id, str) and occurrence_id.strip()
else "Unidentified report"
)
def _deep_candidate_id(finding: dict[str, Any]) -> str:
extensions = finding.get("extensions")
if isinstance(extensions, dict):
candidate_id = extensions.get("candidateId")
if isinstance(candidate_id, str) and candidate_id.strip():
return candidate_id
return _deep_report_id(finding)
def _has_deep_child_metadata(finding: dict[str, Any]) -> bool:
extensions = finding.get("extensions")
if not isinstance(extensions, dict):
return False
return any(
isinstance(extensions.get(field), str) and extensions[field].strip()
for field in ("candidateId", "reportId")
)
def uses_deep_presentation(coverage: dict[str, Any], findings: list[dict[str, Any]]) -> bool:
"""Select deep-report formatting for repository scans in deep mode and scoped scans with deep-child metadata."""
if coverage.get("mode") == "deep_repository":
return True
if coverage.get("mode") != "scoped_path":
return False
# Scoped deep scans can arrive as scoped_path artifacts. The child ids are
# the stable deep-scan signal; ordinary scoped scans do not emit them.
return any(_has_deep_child_metadata(finding) for finding in findings)
def _deep_title_parts(finding: dict[str, Any], report_id: str) -> tuple[str, str | None]:
title = finding.get("title")
if not isinstance(title, str):
return "Untitled finding", None
normalized = " ".join(title.split())
match = re.fullmatch(r"(.+?)\s+\[([^\[\]\n]+)\]", normalized)
if match is None:
return normalized, None
annotation = match.group(2)
extensions = finding.get("extensions")
recognized_ids = [report_id]
if isinstance(extensions, dict):
ledger_row_id = extensions.get("ledgerRowId")
if isinstance(ledger_row_id, str) and ledger_row_id.strip():
recognized_ids.append(ledger_row_id)
if any(
annotation == report_id or annotation.startswith(f"{report_id};")
for report_id in recognized_ids
):
return match.group(1), annotation
return normalized, None
def _deep_group_levels(
group: list[tuple[int, dict[str, Any], str | None]],
field: str,
order: dict[str, int],
) -> str:
levels = {finding[field]["level"] for _, finding, _ in group}
return "<br>".join(sorted(levels, key=lambda level: order.get(level, len(order))))
def _deep_group_row(group: list[tuple[int, dict[str, Any], str | None]]) -> str:
report_ids = [_deep_report_id(finding) for _, finding, _ in group]
report_counts = Counter(report_ids)
titles = []
labels = []
for report_id, (_, finding, _) in zip(report_ids, group, strict=True):
title, annotation = _deep_title_parts(finding, report_id)
titles.append(_cell(title))
labels.append(annotation if report_counts[report_id] > 1 and annotation else report_id)
label_counts = Counter(labels)
report_links = []
writeup_links = []
for report_id, label, (number, finding, path) in zip(report_ids, labels, group, strict=True):
identity = finding.get("identity")
if label_counts[label] > 1 and isinstance(identity, dict):
label = identity.get("instance") or report_id
label = _cell(label)
report_links.append(f"[{label}](#finding-{number})")
writeup_links.append(f"[Open {label}]({path})" if path else f"{label}: inline below")
return (
f"| {'<br>'.join(dict.fromkeys(titles))} | {'<br>'.join(report_links)} "
f"| {_deep_group_levels(group, 'severity', SEVERITY_ORDER)} "
f"| {_deep_group_levels(group, 'confidence', CONFIDENCE_ORDER)} "
f"| {'<br>'.join(writeup_links)} |"
)
def _writeup_report_path(finding: dict[str, Any]) -> str | None:
writeup = finding.get("writeup")
if writeup is None:
return None
if not isinstance(writeup, dict):
raise ReportProjectionError("finding writeup must be an object")
report_path = writeup.get("reportPath")
if not isinstance(report_path, str) or not WRITEUP_REPORT_PATH_RE.fullmatch(report_path):
raise ReportProjectionError("finding writeup has an invalid reportPath")
return report_path
def _hardening_portfolio_path(scan: dict[str, Any]) -> str | None:
hardening = scan.get("hardening")
if hardening is None:
return None
if not isinstance(hardening, dict):
raise ReportProjectionError("scan hardening must be an object")
portfolio_path = hardening.get("portfolioPath")
if portfolio_path != "hardening/hardening.md":
raise ReportProjectionError("scan hardening has an invalid portfolioPath")
return portfolio_path
def _bullet_section(heading: str, items: list[str]) -> list[str]:
return ["", heading, *(f"- {item}" for item in items)] if items else []
def code_evidence_rows(*catalogs: Any) -> Iterator[dict[str, Any]]:
"""Yield evidence objects with nonblank code in their original order."""
for items in catalogs:
if isinstance(items, list):
yield from (
item
for item in items
if isinstance(item, dict)
and isinstance(item.get("code"), str)
and item["code"].strip()
)
def embedded_code_evidence(section: dict[str, Any]) -> Iterator[dict[str, Any]]:
"""Collect code evidence from both supported field spellings."""
return code_evidence_rows(section.get("codeEvidence"), section.get("code_evidence"))
def _code_evidence_catalog(finding: dict[str, Any]) -> dict[str, dict[str, Any]]:
catalog = {}
for item in embedded_code_evidence(finding):
if isinstance(item.get("id"), str):
catalog.setdefault(item["id"], item)
return catalog
def _section_code_evidence(
catalog: dict[str, dict[str, Any]], *sections: dict[str, Any]
) -> list[dict[str, Any]]:
unique: dict[tuple[str, str], dict[str, Any]] = {}
for section in sections:
referenced = (
catalog[ref]
for key in ("evidenceRefs", "evidence_refs")
for ref in _string_values(section.get(key))
if ref in catalog
)
for item in chain(referenced, embedded_code_evidence(section)):
unique.setdefault((str(item.get("id", "")), item["code"]), item)
return list(unique.values())
def merged_root_cause(value: dict[str, Any]) -> tuple[str | None, Any]:
"""Return the first recorded root-cause field name and its merged detail, or (None, None) if absent."""
keys = [key for key in ("rootCause", "root_cause") if key in value]
if not keys:
return None, None
if len(keys) == 1:
detail = value[keys[0]]
return keys[0], detail if isinstance(detail, (str, dict)) else None
details: list[dict[str, Any]] = []
for key in keys:
detail = value[key]
if isinstance(detail, str):
details.append({"summary": detail})
elif isinstance(detail, dict):
details.append(detail)
if not details:
return keys[0], None
merged: dict[str, Any] = {}
text_fields = {
"cause",
"code",
"description",
"detail",
"explanation",
"rationale",
"summary",
"why",
}
for detail in details:
for field, item in detail.items():
if field in (
"evidenceRefs",
"evidence_refs",
"codeEvidence",
"code_evidence",
"language",
):
continue
if field in text_fields and (not isinstance(item, str) or not item.strip()):
continue
current = merged.get(field)
if (
field not in merged
or current in (None, "", [], {})
or (isinstance(current, str) and not current.strip())
):
merged[field] = item
evidence_values = [
detail[field]
for detail in details
for field in ("evidenceRefs", "evidence_refs")
if field in detail
]
if evidence_values:
merged["evidenceRefs"] = list(
dict.fromkeys(item for evidence in evidence_values for item in _string_values(evidence))
)
embedded_evidence = [
item
for detail in details
for field in ("codeEvidence", "code_evidence")
for item in (detail.get(field, []) if isinstance(detail.get(field), list) else [])
]
if embedded_evidence:
merged["codeEvidence"] = embedded_evidence
code = merged.get("code")
matching_details = (
details
if not isinstance(code, str) or not code.strip()
else [detail for detail in details if detail.get("code") == code]
)
language = next(
(
detail["language"]
for detail in matching_details
if isinstance(detail.get("language"), str) and detail["language"].strip()
),
None,
)
if language is not None:
merged["language"] = language
return keys[0], merged
def _root_cause_code_evidence(
finding: dict[str, Any], root_cause: dict[str, Any], catalog: dict[str, dict[str, Any]]
) -> list[dict[str, Any]]:
evidence = _section_code_evidence(catalog, root_cause)
legacy_code = root_cause.get("code")
if not isinstance(legacy_code, str) or not legacy_code.strip():
return evidence
if any(item["code"] == legacy_code for item in evidence):
return evidence
root_location = next(
(
location
for location in finding.get("locations", [])
if isinstance(location, dict) and location.get("role") == "root_control"
),
{},
)
return [
*evidence,
{
"code": legacy_code,
"label": "Broken control",
"language": root_cause.get("language", ""),
"location": root_location,
},
]
def _code_evidence_location(item: dict[str, Any]) -> str:
location = item.get("location")
if isinstance(location, str):
return " ".join(location.split())
if isinstance(location, dict):
item = location
path = item.get("path")
start = item.get("startLine")
end = item.get("endLine")
if not isinstance(path, str) or not path:
return ""
path = _path_label(path)
if not isinstance(start, int) or isinstance(start, bool) or start < 1:
return path
if not isinstance(end, int) or isinstance(end, bool) or end <= start:
return f"{path}:{start}"
return f"{path}:{start}-{end}"
def _code_fence(code: str, minimum: int = 3) -> str:
longest_run = max((len(match.group(0)) for match in re.finditer(r"`+", code)), default=0)
return "`" * max(minimum, longest_run + 1)
def _code_evidence_lines(evidence: list[dict[str, Any]]) -> list[str]:
lines: list[str] = []
for index, item in enumerate(evidence):
label = _text(item.get("label"), f"Code evidence {index + 1}")
location = _code_evidence_location(item)
explanation = _text(item.get("explanation"), "")
language = item.get("language") if isinstance(item.get("language"), str) else ""
language = language if re.fullmatch(r"[A-Za-z0-9_+.-]*", language) else ""
code = item["code"]
fence = _code_fence(code)
heading = f"**{label}**"
if location:
marker = _code_fence(location, minimum=1)
padding = " " if location.startswith("`") or location.endswith("`") else ""
heading += f" — {marker}{padding}{location}{padding}{marker}"
lines.extend(["", heading])
if explanation:
lines.extend(["", explanation])
lines.extend(["", f"{fence}{language}", code, fence])
return lines
def _level_mix(findings: list[dict[str, Any]], field: str, order: dict[str, int]) -> str:
counts = Counter(finding[field]["level"] for finding in findings)
return ", ".join(f"{level}: {counts[level]}" for level in order if counts[level]) or "none"
def _locations(finding: dict[str, Any]) -> str:
rendered = []
for location in finding["locations"]:
start = location["startLine"]
end = location.get("endLine", start)
suffix = f":{start}" if end == start else f":{start}-{end}"
rendered.append(f"{_path_text(location['path'])}{suffix}")
return ", ".join(rendered)
def _finding_sort_key(finding: dict[str, Any]) -> tuple[int, str, str]:
return (
SEVERITY_ORDER.get(finding["severity"]["level"], len(SEVERITY_ORDER)),
finding.get("occurrenceId", ""),
finding["title"],
)
def _target_scope_lines(target: dict[str, Any]) -> list[str]:
lines = [
f"- Target kind: {_text(target.get('kind'), 'not recorded')}",
f"- Target ID: {_text(target.get('targetId'), 'not recorded')}",
]
base_revision = _text(target.get("baseRevision"), "")
head_revision = _text(target.get("headRevision"), "")
if base_revision or head_revision:
lines.append(
f"- Revision range: {base_revision or 'unknown'}...{head_revision or 'unknown'}"
)
revision = _text(target.get("revision"), "")
if revision:
lines.append(f"- Revision: {revision}")
snapshot_digest = _text(target.get("snapshotDigest"), "")
if snapshot_digest:
lines.append(f"- Snapshot digest: {snapshot_digest}")
return lines
def _surface_notes(surface: dict[str, Any]) -> str:
notes = surface.get("notes", "No additional canonical notes were recorded.")
receipt_refs = surface.get("receiptRefs", [])
if not isinstance(receipt_refs, list) or not receipt_refs:
return _cell(notes)
evidence = ", ".join(item for item in receipt_refs if isinstance(item, str))
if not evidence:
return _cell(notes)
return _cell(f"{notes} Evidence: {evidence}")
def _remediation_section(finding: dict[str, Any]) -> list[str]:
remediation = _text(finding.get("remediation"), "No canonical remediation was recorded.")
lines = ["", "#### Remediation", "", remediation]
seen = {remediation}
originals: list[tuple[str, dict[str, Any]]] = []
pending = [("finding", finding)]
seen_findings: set[int] = set()
while pending:
source_id, original = pending.pop()
if id(original) in seen_findings:
continue
seen_findings.add(id(original))
originals.append((source_id, original))
provenance = original.get("provenance")
if not isinstance(provenance, dict):
continue
previous = provenance.get("previousFindings")
if isinstance(previous, list):
pending.extend(
(source_id, item) for item in reversed(previous) if isinstance(item, dict)
)
sources = provenance.get("sourceFindings")
if isinstance(sources, list):
pending.extend(
(_text(source.get("id"), "finding"), source["finding"])
for source in reversed(sources)
if isinstance(source, dict) and isinstance(source.get("finding"), dict)
)
for source_id, original in originals[1:]:
text = _text(original.get("remediation"), "")
if text and text not in seen:
seen.add(text)
lines.extend(["", f"Source {source_id}: {text}"])
for field, label in (
("remediationTests", "Tests"),
("preventiveControls", "Preventive controls"),
):
values = list(
dict.fromkeys(
value for _, original in originals for value in _strings(original.get(field))
)
)
lines.extend(_bullet_section(f"{label}:", values))
return lines
def _finding_header(number: int, finding: dict[str, Any]) -> list[str]:
cwes = ", ".join(finding["taxonomy"]["cwe"]) or "none"
title = _text(finding["title"], "Untitled finding")
return [
f'<a id="finding-{number}"></a>',
"",
f"### [{number}] {title}",
"",
"| Field | Value |",
"| --- | --- |",
f"| Severity | {_cell(finding['severity']['level'])} |",
f"| Confidence | {_cell(finding['confidence']['level'])} |",
f"| Confidence rationale | {_cell(finding['confidence']['rationale'])} |",
f"| Category | {_cell(finding['taxonomy']['category'])} |",
f"| CWE | {_cell(cwes)} |",
"| Affected lines | " + _locations(finding).replace("|", "\\|") + " |",
]
def _finding_section(number: int, finding: dict[str, Any]) -> list[str]:
validation = finding.get("validation") if isinstance(finding.get("validation"), dict) else {}
_, raw_root_cause = merged_root_cause(finding)
root_cause = raw_root_cause if isinstance(raw_root_cause, dict) else {}
attack_path = finding.get("attackPath") if isinstance(finding.get("attackPath"), dict) else {}
dataflow_sections = [
{"summary": value} if isinstance(value, str) else value
for key in ("dataFlow", "dataflow", "data_flow")
if isinstance((value := attack_path.get(key)), (str, dict))
]
dataflow: dict[str, Any] = {}
for section in dataflow_sections:
for key in ("summary", "source", "sink", "outcome"):
value = section.get(key)
if isinstance(value, str) and value.strip():
dataflow.setdefault(key, value)
transformations = dict.fromkeys(
value
for section in dataflow_sections
for value in _string_values(section.get("transformations"))
if value.strip()
)
raw_reachability = attack_path.get("reachability")
reachability = (
{"summary": raw_reachability}
if isinstance(raw_reachability, str)
else raw_reachability
if isinstance(raw_reachability, dict)
else {}
)
severity = finding["severity"]
validation_outcomes = [
(label, text)
for label, key in (
("Status", "status"),
("Disposition", "disposition"),
("Result", "result"),
)
if (text := _text(validation.get(key), ""))
]
validation_summary = _text(
validation.get("summary"),
"Validation outcomes are recorded below."
if validation_outcomes
else f"{finding['confidence']['rationale']} Validation details were not recorded separately.",
)
root_cause_summary = _text(
raw_root_cause if isinstance(raw_root_cause, str) else root_cause.get("summary"),
"",
)
catalog = _code_evidence_catalog(finding)
root_cause_code_evidence = _root_cause_code_evidence(finding, root_cause, catalog)
validation_code_evidence = _section_code_evidence(catalog, validation)
dataflow_code_evidence = _section_code_evidence(catalog, attack_path, *dataflow_sections)
reachability_code_evidence = _section_code_evidence(catalog, reachability)
dataflow_summary = _text(dataflow.get("summary"), "") or (
f"The canonical finding records the affected path at {_locations(finding)}, "
"but no expanded source-to-sink narrative was recorded."
)
reachability_summary = _text(reachability.get("summary"), "") or _text(
attack_path.get("summary"),
"Reachability was not recorded beyond the canonical finding summary and affected locations.",
)
severity_rationale = _text(
severity.get("rationale"),
f"The scan assigned {severity['level']} severity; no separate canonical severity rationale was recorded.",
)
severity_change = _text(
severity.get("changeConditions"),
"Additional runtime or deployment evidence could raise or lower this severity.",
)
lines = [
*_finding_header(number, finding),
"",
"#### Summary",
"",
_text(finding["summary"], "No canonical finding summary was recorded."),
]
if root_cause_summary or root_cause_code_evidence:
lines.extend(["", "#### Root Cause", ""])
if root_cause_summary:
lines.append(root_cause_summary)
lines.extend(_code_evidence_lines(root_cause_code_evidence))
lines.extend(["", "#### Validation", "", validation_summary])
if validation.get("method"):
lines.extend(["", f"Validation method: {_text(validation['method'], 'not recorded')}"])
if validation_outcomes:
lines.extend(["", *(f"- **{label}:** {value}" for label, value in validation_outcomes)])
lines.extend(_code_evidence_lines(validation_code_evidence))
for label, key in (
("Assertions", "assertions"),
("Evidence", "evidence"),
("Counterevidence and remaining uncertainty", "counterEvidence"),
("Limitations", "limitations"),
):
lines.extend(_bullet_section(f"{label}:", _strings(validation.get(key))))
lines.extend(["", "#### Dataflow", "", dataflow_summary])
lines.extend(_bullet_section("Attack steps:", _strings(attack_path.get("steps"))))
for label, key in (("Source", "source"), ("Sink", "sink"), ("Outcome", "outcome")):
if dataflow.get(key):
lines.extend(["", f"- **{label}:** {_text(dataflow[key], 'not recorded')}"])
lines.extend(
_bullet_section("Transformations:", [_text(value, "") for value in transformations])
)
lines.extend(_code_evidence_lines(dataflow_code_evidence))
lines.extend(["", "#### Reachability", "", reachability_summary])
for label, key in (
("Attacker", "attacker"),
("Entry point", "entrypoint"),
("Source", "source"),
("Sink", "sink"),
("Outcome", "outcome"),
):
if reachability.get(key):
lines.extend(["", f"- **{label}:** {_text(reachability[key], 'not recorded')}"])
preconditions = list(
dict.fromkeys(
_strings(attack_path.get("preconditions")) + _strings(reachability.get("preconditions"))
)
)
lines.extend(_bullet_section("Preconditions:", preconditions))
for label, key in (
("Assumptions", "assumptions"),
("Existing controls", "controls"),
("Blind spots", "blindspots"),
("Limitations", "limitations"),
):
lines.extend(_bullet_section(f"{label}:", _strings(attack_path.get(key))))
lines.extend(_code_evidence_lines(reachability_code_evidence))
lines.extend(
[
"",
"#### Severity",
"",
f"**{severity['level'].capitalize()}** — {severity_rationale}",
"",
severity_change,
]
)
for label, key in (("Impact", "impact"), ("Likelihood", "likelihood")):
assessment = attack_path.get(key)
if isinstance(assessment, str):
rendered = _text(assessment, "")
if rendered:
lines.extend(["", f"**{label} assessment:** {rendered}"])
continue
if not isinstance(assessment, dict):
continue
details = [
(detail_label, text)
for detail_label, detail_key in (
("Level", "level"),
("Rationale", "rationale"),
("Why", "why"),
)
if (text := _text(assessment.get(detail_key), ""))
]
if details:
lines.extend(
["", f"{label} assessment:", *(f"- **{name}:** {value}" for name, value in details)]
)
lines.extend(_remediation_section(finding))
return lines
def _linked_finding_section(number: int, finding: dict[str, Any], report_path: str) -> list[str]:
link = f"[detailed technical write-up]({report_path})"
lines = _finding_header(number, finding)
for heading in ("Summary", "Validation", "Dataflow", "Reachability", "Severity"):
lines.extend(["", f"#### {heading}", "", f"See the {link}."])
if any(
finding.get("provenance", {}).get(field) for field in ("sourceFindings", "previousFindings")
):
lines.extend(_remediation_section(finding))
else:
lines.extend(["", "#### Remediation", "", f"See the {link}."])
return lines
def build_report_markdown(
manifest: dict[str, Any], findings_document: dict[str, Any], coverage: dict[str, Any]
) -> str:
"""Render findings and review coverage as a Markdown report ending in a newline.
Args:
manifest: Scan metadata, target, and scope.
findings_document: Canonical findings for the scan.
coverage: Review coverage for older manifests. Newer scans supply review state inline.
Raises:
ReportProjectionError: Reportable findings share a writeup path.
"""
scan = manifest["scan"]
if "review" in scan and "coverageRef" not in scan:
from review_state import review_state
coverage = review_state(scan)
target = scan["target"]
scope = scan["scope"]
threat_model = scan.get("threatModel") if isinstance(scan.get("threatModel"), dict) else {}
findings = sorted(
(
finding
for finding in findings_document["findings"]
if finding["severity"]["level"] in REPORTABLE_SEVERITIES
),
key=_finding_sort_key,
)
numbered_findings = [
(number, finding, _writeup_report_path(finding))
for number, finding in enumerate(findings, 1)
]
writeup_counts = Counter(path for _, _, path in numbered_findings if path is not None)
duplicate_writeup_paths = sorted(path for path, count in writeup_counts.items() if count > 1)
if duplicate_writeup_paths:
raise ReportProjectionError(
"reportable findings have duplicate writeup reportPath values: "
+ ", ".join(duplicate_writeup_paths)
)
deep_presentation = uses_deep_presentation(coverage, findings)
deep_finding_groups: dict[str, list[tuple[int, dict[str, Any], str | None]]] = {}
if deep_presentation:
for entry in numbered_findings:
_, finding, _ = entry
deep_finding_groups.setdefault(_deep_candidate_id(finding), []).append(entry)
hardening_portfolio_path = _hardening_portfolio_path(scan)
include_paths = [
_path_text(path) for path in coverage.get("includePaths", scope.get("includePaths", []))
]
exclude_paths = [
_path_text(path) for path in coverage.get("excludePaths", scope.get("excludePaths", []))
]
limitations = _strings(scope.get("limitations"))
explicit_exclusions = coverage.get("explicitExclusions", [])
lines = [
f"# Security Review: {_text(target['displayName'], 'Unknown target')}",
"",
"## Scope",
"",
_text(
scope.get("summary"),
"The scan was configured for the include paths and exclusions listed below.",
),
"",
f"- Scan mode: {coverage['mode']}",
*_target_scope_lines(target),
f"- Included paths: {', '.join(include_paths) or 'none'}",
f"- Excluded paths: {', '.join(exclude_paths) or 'none'}",
]
artifacts_reviewed = _strings(scope.get("artifactsReviewed"))
if artifacts_reviewed:
lines.extend(["- Artifacts reviewed: " + ", ".join(artifacts_reviewed)])
context = _text(scope.get("context"), "")
if context:
lines.extend([f"- Scan context: {context}"])
for exclusion in explicit_exclusions:
if isinstance(exclusion, dict):
limitations.append(
f"Excluded {_text(exclusion.get('pattern'), 'unspecified')}: "
f"{_text(exclusion.get('reason'), 'reason not recorded')}"
)
lines.extend(_bullet_section("Limitations and exclusions:", limitations))
summary_count_lines = (
[
f"| Reportable DSS findings | {len(deep_finding_groups)} |",
f"| Report instances | {len(findings)} |",
f"| Report severity mix | {_level_mix(findings, 'severity', SEVERITY_ORDER)} |",
f"| Report confidence mix | {_level_mix(findings, 'confidence', CONFIDENCE_ORDER)} |",
]
if deep_presentation
else [
f"| Reportable findings | {len(findings)} |",
f"| Severity mix | {_level_mix(findings, 'severity', SEVERITY_ORDER)} |",
f"| Confidence mix | {_level_mix(findings, 'confidence', CONFIDENCE_ORDER)} |",
]
)
lines.extend(
[
"",
"### Scan Summary",
"",
"| Field | Value |",
"| --- | --- |",
f"| Scan outcome | {scan.get('status', 'completed')} |",
*summary_count_lines,
f"| Validation mode | {_cell(scope.get('validationMode', 'not recorded'))} |",
"",
"Canonical artifacts: `scan-manifest.json` and `findings.json`. This report is a deterministic projection of those files.",
"",
"## Threat Model",
"",
]
)
content = markdown_threat_model_content(threat_model)
if content is not None:
lines.append(content)
else:
lines.append(
_text(
threat_model.get("summary"),
"No explicit canonical threat-model summary was recorded.",
)
)
for heading, key in THREAT_MODEL_SECTIONS:
values = _strings(threat_model.get(key))
if values:
lines.extend(["", f"### {heading}", "", *(f"- {value}" for value in values)])
reviews = scan.get("reviewState", {}).get("reviews")
if isinstance(reviews, list) and any(
isinstance(review, dict) and isinstance(review.get("threatModel"), dict)
for review in reviews
):
lines.extend(
[
"",
(
"Other reviews recorded different threat models. See the `threatModel` fields "
"in `scan.reviewState.reviews` in the [scan manifest](scan-manifest.json)."
),
]
)
lines.extend(["", "## Findings", ""])
informational_count = sum(
finding["severity"]["level"] == "informational" for finding in findings_document["findings"]
)
informational_note = ""
if informational_count:
noun = "finding" if informational_count == 1 else "findings"
informational_note = (
f"This report omits details for {informational_count} informational {noun}. "
"See `findings.json` or export the findings as SARIF or CSV."
)
if findings:
if informational_note:
lines.extend([informational_note, ""])
if deep_presentation:
lines.extend(
[
"| Findings | Reports | Severity | Confidence | Detailed write-up |",
"| --- | --- | --- | --- | --- |",
]
)
lines.extend(_deep_group_row(group) for group in deep_finding_groups.values())
else:
lines.extend(
[
"| Finding | Severity | Confidence | Detailed write-up |",
"| --- | --- | --- | --- |",
]
)
for number, finding, report_path in numbered_findings:
title = _cell(finding["title"])
finding_link = f"[{title}](#finding-{number})"
writeup_link = f"[Open report]({report_path})" if report_path else "inline below"
lines.append(
f"| {finding_link} | {finding['severity']['level']} "
f"| {finding['confidence']['level']} | {writeup_link} |"
)
lines.extend(
[
"",
"### Confidence Scale",
"",
"| Label | Meaning |",
"| --- | --- |",
"| high | Direct evidence supports the finding with no material unresolved blocker. |",
"| medium | Evidence supports a plausible issue, but material runtime or reachability proof remains. |",
"| low | Evidence is incomplete and the item is retained only for explicit follow-up. |",
]
)
for number, finding, report_path in numbered_findings:
if report_path is not None:
lines.extend(["", *_linked_finding_section(number, finding, report_path)])
else:
lines.extend(["", *_finding_section(number, finding)])
else:
stopped = manifest.get("scan", {}).get("status") in {
"failed",
"canceled",
"interrupted",
}
heading = "### No reportable findings" if informational_note else "### No findings"
message = informational_note or (
"No findings were retained before the scan stopped."
if stopped
else "No findings were reported."
)
if stopped:
message += " The scan did not complete. No vulnerability conclusion can be drawn."
lines.extend([heading, "", message])
if hardening_portfolio_path is not None:
lines.extend(
[
"",
"## Structural Hardening",
"",
"The scan also produced derived, unsealed design guidance based on the complete finding collection. These proposals describe options and tradeoffs; they do not indicate that any finding has been remediated.",
"",
f"[Open the structural hardening portfolio]({hardening_portfolio_path})",
]
)
surfaces = coverage.get("surfaces", [])
if surfaces:
lines.extend(
[
"",
"## Reviewed Surfaces",
"",
"| Surface | Risk Area | Outcome | Notes |",
"| --- | --- | --- | --- |",
]
)
for surface in surfaces:
if not isinstance(surface, dict):
continue
lines.append(
"| "
+ " | ".join(
(
_cell(surface.get("label", surface.get("id"))),
_cell(surface.get("riskArea", "not recorded")),
_cell(
DISPOSITION_LABELS.get(
surface.get("disposition"), surface.get("disposition")
)
),
_surface_notes(surface),