control_coverage/coverage.py

186 lines · 6889 bytes

  1"""Compute control coverage: join an evidence corpus onto framework catalogs.
  2
  3For every control in a catalog we assign one **assurance state**:
  4
  5* ``supported``   — in scope, at least one fully mapped finding passes and none fail.
  6* ``partially_supported`` — in scope, findings pass and none fail, but every
  7                    passing one is only a partial mapping (``partial``,
  8                    ``subset``, ``intersects``): part of the control is shown.
  9* ``failing``     — in scope, at least one mapped finding fails.
 10* ``asserted``    — in scope, findings map here but their data was absent
 11                    (``not_applicable``): evidence was attempted, not obtained.
 12* ``unaddressed`` — in scope, *no* finding maps here at all. The blind spot.
 13* ``out_of_scope``— excluded by the scope file, with a recorded justification.
 14
 15When several findings touch one control the worst wins: a single failure makes the
 16control ``failing`` regardless of how many others pass. Coverage is then a headline
 17number the evidence-first tools cannot produce — of everything a framework
 18requires, how much the corpus even looks at, and how much it supports.
 19"""
 20
 21from __future__ import annotations
 22
 23from dataclasses import dataclass, field
 24
 25from .catalog import Catalog, Control
 26from .corpus import FAIL, PARTIAL_RELATIONSHIPS, PASS, Observation
 27
 28SUPPORTED = "supported"
 29PARTIALLY_SUPPORTED = "partially_supported"
 30FAILING = "failing"
 31ASSERTED = "asserted"
 32UNADDRESSED = "unaddressed"
 33OUT_OF_SCOPE = "out_of_scope"
 34
 35# Order states appear in reports and roll up in summaries (most urgent first).
 36STATE_ORDER = [FAILING, UNADDRESSED, ASSERTED, PARTIALLY_SUPPORTED, SUPPORTED, OUT_OF_SCOPE]
 37
 38# States that count as the control being "addressed" by the corpus at all.
 39_ADDRESSED = {SUPPORTED, PARTIALLY_SUPPORTED, FAILING, ASSERTED}
 40
 41
 42@dataclass
 43class ControlResult:
 44    """One control's assurance state and the evidence behind it."""
 45
 46    control: Control
 47    state: str
 48    observations: list[Observation] = field(default_factory=list)
 49    owner: str = ""
 50    exclusion_reason: str = ""
 51
 52    @property
 53    def addressed(self) -> bool:
 54        return self.state in _ADDRESSED
 55
 56
 57def _state_for(observations: list[Observation]) -> str:
 58    """Worst-wins resolution of a control's state from its observations."""
 59    if not observations:
 60        return UNADDRESSED
 61    statuses = {o.status for o in observations}
 62    if FAIL in statuses:
 63        return FAILING
 64    passing = [o for o in observations if o.status == PASS]
 65    if passing:
 66        if all(o.relationship in PARTIAL_RELATIONSHIPS for o in passing):
 67            return PARTIALLY_SUPPORTED
 68        return SUPPORTED
 69    return ASSERTED  # only not_applicable observations remain
 70
 71
 72@dataclass
 73class FrameworkCoverage:
 74    """Coverage of one framework catalog by the corpus."""
 75
 76    catalog: Catalog
 77    results: list[ControlResult]
 78
 79    def by_state(self, state: str) -> list[ControlResult]:
 80        return [r for r in self.results if r.state == state]
 81
 82    @property
 83    def counts(self) -> dict[str, int]:
 84        counts = dict.fromkeys(STATE_ORDER, 0)
 85        for r in self.results:
 86            counts[r.state] += 1
 87        return counts
 88
 89    @property
 90    def in_scope(self) -> int:
 91        return sum(1 for r in self.results if r.state != OUT_OF_SCOPE)
 92
 93    @property
 94    def addressed(self) -> int:
 95        return sum(1 for r in self.results if r.addressed)
 96
 97    @property
 98    def supported(self) -> int:
 99        return sum(1 for r in self.results if r.state == SUPPORTED)
100
101    @property
102    def coverage_pct(self) -> float:
103        """Share of in-scope controls the corpus touches at all (0–100)."""
104        return round(100 * self.addressed / self.in_scope, 1) if self.in_scope else 0.0
105
106    @property
107    def assured_pct(self) -> float:
108        """Share of in-scope controls that are supported and not failing (0–100)."""
109        return round(100 * self.supported / self.in_scope, 1) if self.in_scope else 0.0
110
111    @property
112    def blind_spots(self) -> list[ControlResult]:
113        """In-scope controls no finding touches — the headline gap list."""
114        return self.by_state(UNADDRESSED)
115
116
117@dataclass
118class CoverageReport:
119    """Coverage across every requested framework, plus corpus-wide diagnostics."""
120
121    subject: str
122    generated_at: str
123    frameworks: list[FrameworkCoverage]
124    # Control codes cited by the corpus that no loaded catalog defines. These are
125    # typos, renamed controls, or controls outside the bundled catalogs — either
126    # way, evidence pointing at nothing is worth surfacing.
127    orphan_codes: list[str] = field(default_factory=list)
128    source_count: int = 0
129
130
131def _observations_by_control(observations: list[Observation]) -> dict[str, list[Observation]]:
132    grouped: dict[str, list[Observation]] = {}
133    for obs in observations:
134        grouped.setdefault(obs.control, []).append(obs)
135    return grouped
136
137
138def evaluate(
139    catalogs: list[Catalog],
140    observations: list[Observation],
141    scope=None,
142    subject: str = "",
143    generated_at: str = "",
144) -> CoverageReport:
145    """Produce a :class:`CoverageReport` from catalogs, a corpus, and a scope."""
146    grouped = _observations_by_control(observations)
147    catalog_codes: set[str] = set()
148    loaded_frameworks = {cat.framework for cat in catalogs}
149
150    frameworks: list[FrameworkCoverage] = []
151    for cat in catalogs:
152        catalog_codes |= cat.codes()
153        results: list[ControlResult] = []
154        for control in cat.controls:
155            code = control.code
156            obs = grouped.get(code, [])
157            owner = scope.owner(code) if scope else ""
158            if scope and scope.excluded(code):
159                results.append(
160                    ControlResult(control, OUT_OF_SCOPE, obs, owner, scope.reason(code))
161                )
162            elif scope and scope.family_excluded(cat.framework, control.family):
163                reason = scope.family_reason(cat.framework, control.family)
164                results.append(ControlResult(control, OUT_OF_SCOPE, obs, owner, reason))
165            else:
166                results.append(ControlResult(control, _state_for(obs), obs, owner))
167        frameworks.append(FrameworkCoverage(cat, results))
168
169    # A code is an orphan only when its framework *is* loaded but the catalog
170    # does not define it — a typo or a renamed control. Codes for frameworks we
171    # did not load this run are simply out of scope, not orphans.
172    cited = {o.control for o in observations}
173    orphans = sorted(
174        code
175        for code in cited
176        if code.split(":", 1)[0] in loaded_frameworks and code not in catalog_codes
177    )
178    sources = {o.source for o in observations}
179
180    return CoverageReport(
181        subject=subject,
182        generated_at=generated_at,
183        frameworks=frameworks,
184        orphan_codes=orphans,
185        source_count=len(sources),
186    )