control_coverage/reporters/html.py

265 lines · 10425 bytes

  1"""HTML renderer — a self-contained, printable coverage report.
  2
  3No external assets: all CSS is inlined so the file can be attached to an audit
  4workpaper and opened anywhere, including offline.
  5"""
  6
  7from __future__ import annotations
  8
  9from html import escape
 10from typing import TYPE_CHECKING
 11
 12from .. import __version__
 13from ..coverage import (
 14    ASSERTED,
 15    FAILING,
 16    OUT_OF_SCOPE,
 17    PARTIALLY_SUPPORTED,
 18    SUPPORTED,
 19    UNADDRESSED,
 20)
 21
 22if TYPE_CHECKING:
 23    from ..coverage import CoverageReport, FrameworkCoverage
 24
 25_STATE_LABEL = {
 26    SUPPORTED: "supported",
 27    PARTIALLY_SUPPORTED: "partially supported",
 28    FAILING: "failing",
 29    ASSERTED: "asserted",
 30    UNADDRESSED: "unaddressed",
 31    OUT_OF_SCOPE: "out of scope",
 32}
 33_STATE_CLASS = {
 34    SUPPORTED: "supported",
 35    PARTIALLY_SUPPORTED: "partial",
 36    FAILING: "failing",
 37    ASSERTED: "asserted",
 38    UNADDRESSED: "unaddressed",
 39    OUT_OF_SCOPE: "oos",
 40}
 41
 42CSS = """
 43:root { color-scheme: light dark; }
 44* { box-sizing: border-box; }
 45body { font-family: -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif;
 46  margin: 0; padding: 2rem; line-height: 1.5; color: #1a1a1a; background: #fff; }
 47main { max-width: 64rem; margin: 0 auto; }
 48h1 { margin: 0 0 .25rem; font-size: 1.6rem; }
 49h2 { margin: 2rem 0 .75rem; font-size: 1.25rem; border-bottom: 2px solid #e5e5e5; padding-bottom: .25rem; }
 50h3 { margin: 1.4rem 0 .5rem; font-size: 1.02rem; }
 51.meta { color: #555; font-size: .9rem; margin: 0 0 1rem; }
 52.meta code { background: #f2f2f2; padding: .05rem .3rem; border-radius: 3px; }
 53.note { background: #f7f7f9; border-left: 3px solid #b9b9c6; padding: .6rem .9rem;
 54  font-size: .9rem; color: #444; border-radius: 0 4px 4px 0; }
 55table { border-collapse: collapse; width: 100%; font-size: .85rem; margin: .5rem 0; }
 56th, td { border: 1px solid #e0e0e0; padding: .35rem .5rem; text-align: left; vertical-align: top; }
 57th { background: #f5f5f7; }
 58td.num, th.num { text-align: right; }
 59.badge { display: inline-block; font-weight: 700; font-size: .72rem; letter-spacing: .02em;
 60  padding: .12rem .5rem; border-radius: 999px; white-space: nowrap; }
 61.badge.supported { background: #e5f6ea; color: #1a7f37; }
 62.badge.partial { background: #eef7f0; color: #3d7a4d; }
 63.badge.failing { background: #fdeaea; color: #c1272d; }
 64.badge.asserted { background: #fff4e0; color: #a8620a; }
 65.badge.unaddressed { background: #eceaf6; color: #5b4bb0; }
 66.badge.oos { background: #eee; color: #666; }
 67.bar { display: flex; height: 1.1rem; border-radius: 4px; overflow: hidden; margin: .4rem 0 .2rem;
 68  border: 1px solid #ddd; }
 69.bar > span { display: block; }
 70.bar .supported { background: #35b866; }
 71.bar .partial { background: #8fcf9f; }
 72.bar .failing { background: #e2565b; }
 73.bar .asserted { background: #eaa53c; }
 74.bar .unaddressed { background: #8877d8; }
 75.bar .oos { background: #cfcfcf; }
 76.headline { font-size: 1.5rem; font-weight: 700; }
 77.headline small { font-size: .85rem; font-weight: 500; color: #666; }
 78.legend { font-size: .78rem; color: #666; display: flex; flex-wrap: wrap; gap: .8rem; margin: .2rem 0 1rem; }
 79.legend i { display: inline-block; width: .8rem; height: .8rem; border-radius: 2px; vertical-align: -1px; margin-right: .25rem; }
 80footer { margin-top: 3rem; font-size: .8rem; color: #888; border-top: 1px solid #eee; padding-top: .75rem; }
 81@media (prefers-color-scheme: dark) {
 82  body { color: #e6e6e6; background: #16171a; }
 83  h2 { border-color: #333; }
 84  .meta { color: #aaa; } .meta code { background: #26272b; }
 85  .note { background: #1e1f24; border-color: #444; color: #bbb; }
 86  th, td { border-color: #333; } th { background: #202126; }
 87  .headline small, .legend { color: #999; }
 88  .badge.supported { background: #12321d; color: #4ac36a; }
 89  .badge.partial { background: #1b2c20; color: #8fcf9f; }
 90  .badge.failing { background: #3a1416; color: #ff6b70; }
 91  .badge.asserted { background: #33260f; color: #e6a94e; }
 92  .badge.unaddressed { background: #211d3a; color: #9d8ef0; }
 93  .badge.oos { background: #26272b; color: #999; }
 94  .bar { border-color: #333; }
 95  footer { border-color: #2a2b30; }
 96}
 97"""
 98
 99_LEGEND_COLORS = {
100    SUPPORTED: "#35b866",
101    PARTIALLY_SUPPORTED: "#8fcf9f",
102    FAILING: "#e2565b",
103    ASSERTED: "#eaa53c",
104    UNADDRESSED: "#8877d8",
105    OUT_OF_SCOPE: "#cfcfcf",
106}
107
108
109def _badge(state: str) -> str:
110    return f'<span class="badge {_STATE_CLASS[state]}">{_STATE_LABEL[state]}</span>'
111
112
113def _bar(fc: FrameworkCoverage) -> str:
114    counts = fc.counts
115    total = sum(counts.values()) or 1
116    segments = []
117    for state in [SUPPORTED, PARTIALLY_SUPPORTED, FAILING, ASSERTED, UNADDRESSED, OUT_OF_SCOPE]:
118        n = counts[state]
119        if not n:
120            continue
121        pct = 100 * n / total
122        segments.append(
123            f'<span class="{_STATE_CLASS[state]}" style="width:{pct:.2f}%" '
124            f'title="{n} {_STATE_LABEL[state]}"></span>'
125        )
126    return '<div class="bar">' + "".join(segments) + "</div>"
127
128
129def _legend() -> str:
130    items = []
131    for state in [SUPPORTED, PARTIALLY_SUPPORTED, FAILING, ASSERTED, UNADDRESSED, OUT_OF_SCOPE]:
132        items.append(
133            f'<span><i style="background:{_LEGEND_COLORS[state]}"></i>{_STATE_LABEL[state]}</span>'
134        )
135    return '<div class="legend">' + "".join(items) + "</div>"
136
137
138def _checked_by(result) -> str:
139    if result.state == OUT_OF_SCOPE:
140        return f"<em>excluded: {escape(result.exclusion_reason)}</em>"
141    rules = sorted({o.rule_id for o in result.observations if o.rule_id})
142    return ", ".join(f"<code>{escape(r)}</code>" for r in rules)
143
144
145def _framework_section(fc: FrameworkCoverage) -> str:
146    cat = fc.catalog
147    partial = "" if cat.complete else (
148        ' <small>(partial catalog — coverage is of the shipped subset)</small>'
149    )
150    rows = []
151    for r in fc.results:
152        rows.append(
153            "<tr>"
154            f"<td><strong>{escape(r.control.id)}</strong></td>"
155            f"<td>{_badge(r.state)}</td>"
156            f"<td>{escape(r.control.title)}</td>"
157            f"<td>{_checked_by(r)}</td>"
158            "</tr>"
159        )
160    return (
161        f"<h2>{escape(cat.name)}{partial}</h2>"
162        f'<p class="headline">{fc.coverage_pct}% <small>coverage · {fc.addressed}/{fc.in_scope} '
163        f"in-scope controls addressed · {fc.assured_pct}% assured</small></p>"
164        f"{_bar(fc)}{_legend()}"
165        "<table><thead><tr><th>Control</th><th>Status</th><th>Description</th>"
166        "<th>Checked by</th></tr></thead><tbody>"
167        + "".join(rows)
168        + "</tbody></table>"
169    )
170
171
172def _summary_table(report: CoverageReport) -> str:
173    rows = []
174    for fc in report.frameworks:
175        c = fc.counts
176        rows.append(
177            "<tr>"
178            f"<td>{escape(fc.catalog.name)}</td>"
179            f'<td class="num">{fc.in_scope}</td>'
180            f'<td class="num">{fc.addressed}</td>'
181            f'<td class="num">{fc.supported}</td>'
182            f'<td class="num">{c[FAILING]}</td>'
183            f'<td class="num">{len(fc.blind_spots)}</td>'
184            f'<td class="num">{fc.coverage_pct}%</td>'
185            f'<td class="num">{fc.assured_pct}%</td>'
186            "</tr>"
187        )
188    return (
189        "<table><thead><tr><th>Framework</th><th class='num'>In scope</th>"
190        "<th class='num'>Addressed</th><th class='num'>Supported</th>"
191        "<th class='num'>Failing</th><th class='num'>Blind spots</th>"
192        "<th class='num'>Coverage</th><th class='num'>Assured</th></tr></thead><tbody>"
193        + "".join(rows)
194        + "</tbody></table>"
195    )
196
197
198def _blind_spots(report: CoverageReport) -> str:
199    total = sum(len(fc.blind_spots) for fc in report.frameworks)
200    if total == 0:
201        return "<h2>Blind spots</h2><p>No in-scope control is left unaddressed by the corpus.</p>"
202    parts = [
203        "<h2>Blind spots</h2>",
204        (
205            f"<p>{total} in-scope control(s) are <strong>unaddressed</strong> — no finding "
206            "in the corpus maps to them.</p>"
207        ),
208    ]
209    for fc in report.frameworks:
210        spots = fc.blind_spots
211        if not spots:
212            continue
213        parts.append(f"<h3>{escape(fc.catalog.name)} ({len(spots)})</h3><ul>")
214        for r in spots:
215            fam = f" <em>· {escape(r.control.family)}</em>" if r.control.family else ""
216            parts.append(
217                f"<li><strong>{escape(r.control.id)}</strong> — {escape(r.control.title)}{fam}</li>"
218            )
219        parts.append("</ul>")
220    return "".join(parts)
221
222
223def render(report: CoverageReport) -> str:
224    title = report.subject or "Evidence corpus"
225    frameworks = ", ".join(
226        f"{fc.catalog.framework} {fc.catalog.version} "
227        f"(sha256:{fc.catalog.sha256[:12]})"
228        for fc in report.frameworks
229    )
230    body = [
231        "<!doctype html><html lang='en'><head><meta charset='utf-8'>",
232        "<meta name='viewport' content='width=device-width, initial-scale=1'>",
233        f"<title>Control Coverage — {escape(title)}</title>",
234        f"<style>{CSS}</style></head><body><main>",
235        f"<h1>Control Coverage — {escape(title)}</h1>",
236        (
237            f'<p class="meta">Generated {escape(report.generated_at)} · '
238            f"Tool control-coverage {escape(__version__)} · "
239            f"{report.source_count} evidence source(s) · frameworks: {escape(frameworks)}</p>"
240        ),
241        (
242            '<p class="note">Coverage measures how much of a framework the evidence corpus '
243            "addresses — not whether the organization is compliant. An unaddressed control is "
244            "a gap in <em>evidence</em>, which may reflect a real control gap or simply a signal "
245            "not yet collected. The final judgment belongs to the organization and its auditor.</p>"
246        ),
247        "<h2>Summary</h2>",
248        _summary_table(report),
249        _blind_spots(report),
250    ]
251    for fc in report.frameworks:
252        body.append(_framework_section(fc))
253
254    if report.orphan_codes:
255        codes = "".join(f"<li><code>{escape(c)}</code></li>" for c in report.orphan_codes)
256        body.append(
257            "<h2>Unmatched control codes</h2><p>The corpus cites these codes, but no loaded "
258            f"catalog defines them (typos, renamed, or out-of-catalog):</p><ul>{codes}</ul>"
259        )
260
261    body.append(
262        "<footer>Generated by control-coverage · Audit Labs. Evidence, not a verdict.</footer>"
263    )
264    body.append("</main></body></html>")
265    return "".join(body)