control_coverage/corpus.py
102 lines · 3624 bytes
1"""Load an evidence corpus from audit-report JSON reports.
2
3audit-report emits one JSON document per evidence package. Each finding carries
4the controls it maps to and a status::
5
6 {"findings": [
7 {"id": "github.org.require-2fa", "status": "pass", "severity": "high",
8 "controls": ["SOC2:CC6.1", "ISO:A.5.17", "NIST:IA-2"], ...},
9 ...
10 ]}
11
12A **corpus** is any number of these reports — typically one per platform and date
13(AWS, GitHub, GitLab…) — flattened into a list of :class:`Observation`, one per
14(finding, control) pair. Coverage is then computed by joining observations onto a
15framework catalog.
16"""
17
18from __future__ import annotations
19
20import json
21from dataclasses import dataclass
22from pathlib import Path
23
24# Statuses as emitted by audit-report's engine.
25PASS = "pass"
26FAIL = "fail"
27NOT_APPLICABLE = "not_applicable"
28
29
30@dataclass(frozen=True)
31class Observation:
32 """One finding's bearing on one control, with provenance."""
33
34 control: str # "FRAMEWORK:ID"
35 status: str # pass | fail | not_applicable
36 rule_id: str
37 title: str
38 severity: str
39 source: str # report file / package name the finding came from
40 relationship: str = "full" # how the evidence relates to the control; see RELATIONSHIPS
41 mapping: str = "" # which mapping linked them (rule, crosswalk pack, rationale)
42
43
44# Relationship of evidence (or a source control) to a target control. Following
45# NIST IR 8477 for crosswalks: `equal` and `superset` fully cover the target;
46# `subset` and `intersects` cover part of it. Rule mappings use `full` or `partial`.
47FULL_RELATIONSHIPS = {"full", "equal", "superset"}
48PARTIAL_RELATIONSHIPS = {"partial", "subset", "intersects"}
49RELATIONSHIPS = FULL_RELATIONSHIPS | PARTIAL_RELATIONSHIPS
50
51
52def _iter_report(doc: dict, source: str):
53 for f in doc.get("findings", []):
54 status = f.get("status", NOT_APPLICABLE)
55 rule_id = f.get("id", "")
56 title = f.get("title", "")
57 severity = f.get("severity", "medium")
58 mappings = f.get("control_mappings") or {}
59 for control in f.get("controls", []):
60 m = mappings.get(control) or {}
61 yield Observation(
62 control=control,
63 status=status,
64 rule_id=rule_id,
65 title=title,
66 severity=severity,
67 source=source,
68 relationship=m.get("relationship", "full"),
69 mapping=m.get("rationale", ""),
70 )
71
72
73def load_report(path: str | Path) -> list[Observation]:
74 """Load observations from a single audit-report JSON file."""
75 p = Path(path)
76 doc = json.loads(p.read_text(encoding="utf-8"))
77 # Prefer the package name audit-report records; fall back to the file name.
78 source = doc.get("source_package") or p.name
79 return list(_iter_report(doc, source))
80
81
82def _expand(paths: list[str | Path]) -> list[Path]:
83 """Resolve inputs: JSON files pass through; directories contribute their *.json."""
84 resolved: list[Path] = []
85 for raw in paths:
86 p = Path(raw)
87 if p.is_dir():
88 resolved.extend(sorted(p.glob("*.json")))
89 else:
90 resolved.append(p)
91 return resolved
92
93
94def load_corpus(paths: list[str | Path]) -> list[Observation]:
95 """Load and flatten observations from files and/or directories of reports."""
96 files = _expand(paths)
97 if not files:
98 raise ValueError("no audit-report JSON files found in the given paths")
99 observations: list[Observation] = []
100 for f in files:
101 observations.extend(load_report(f))
102 return observations