audit_report/trend.py
257 lines · 9571 bytes
12 symbols in this file
1"""Trend mode — track each rule across a series of dated packages.
2
3Given a folder of audit-tools packages for the same platform and subject
4(``aws_audit_prod_2026-01-01/``, ``…_2026-02-01/``, …), this evaluates every
5package with the same ruleset and lays the results out as a timeline: one row
6per rule, one column per package date, so you can see a control drift in and out
7of compliance over time.
8"""
9
10from __future__ import annotations
11
12from dataclasses import dataclass
13from datetime import datetime, timezone
14from html import escape
15from pathlib import Path
16
17from .engine import FAIL, NOT_APPLICABLE, PASS, Finding
18from .loader import Package, detect_platform, package_date
19from .reporters.html import CSS as _CSS
20
21_STATUS_SYMBOL = {PASS: "✓", FAIL: "✗", NOT_APPLICABLE: "·"}
22_STATUS_CLASS = {PASS: "pass", FAIL: "fail", NOT_APPLICABLE: "na"}
23_SEVERITY_ORDER = {"high": 0, "medium": 1, "low": 2}
24
25
26def discover(parent: str | Path, subject: str | None = None) -> tuple[str, str, list[Path]]:
27 """Find a single series of packages under *parent*.
28
29 Returns ``(platform, subject, [paths sorted by date])``. Raises ``ValueError``
30 if no packages are found, if fewer than two share a platform/subject, or if
31 several distinct series are present and *subject* does not narrow it to one.
32 """
33 directory = Path(parent)
34 if not directory.is_dir():
35 raise ValueError(f"not a directory: {directory}")
36
37 groups = _group_packages(directory, subject)
38 if not groups:
39 raise ValueError(
40 f"no audit-tools packages found under {directory}"
41 + (f" for subject '{subject}'" if subject else "")
42 )
43 if len(groups) > 1:
44 listed = ", ".join(f"{p}/{s}" for p, s in sorted(groups))
45 raise ValueError(
46 f"multiple series found ({listed}); narrow with --subject and a "
47 "directory that holds one platform"
48 )
49
50 (platform, subj), paths = next(iter(groups.items()))
51 if len(paths) < 2:
52 raise ValueError("a trend needs at least two packages in the series")
53
54 paths.sort(key=lambda p: (package_date(p.name), p.name))
55 return platform, subj, paths
56
57
58def _group_packages(directory: Path, subject: str | None) -> dict[tuple[str, str], list[Path]]:
59 """Group the package folders under *directory* by (platform, subject)."""
60 groups: dict[tuple[str, str], list[Path]] = {}
61 for child in sorted(directory.iterdir()):
62 if not child.is_dir() or not any(child.glob("*.csv")):
63 continue
64 platform, subj = detect_platform(child.name)
65 if platform == "unknown" or (subject and subj != subject):
66 continue
67 groups.setdefault((platform, subj), []).append(child)
68 return groups
69
70
71@dataclass
72class TrendRow:
73 """One rule's status across the timeline."""
74
75 rule: object # audit_report.rules.Rule
76 statuses: list[str]
77
78 @property
79 def transitions(self) -> int:
80 """How many times the status changed along the timeline."""
81 return sum(1 for a, b in zip(self.statuses, self.statuses[1:]) if a != b)
82
83
84@dataclass
85class TrendReport:
86 """Rules-over-time view of a package series."""
87
88 platform: str
89 subject: str
90 dates: list[str] # column labels (package date or dir name)
91 rows: list[TrendRow]
92 generated_at: str
93
94 def fails_per_date(self) -> list[int]:
95 return [
96 sum(1 for row in self.rows if row.statuses[i] == FAIL)
97 for i in range(len(self.dates))
98 ]
99
100
101def build_trend(
102 packages: list[Package], findings_per_package: list[list[Finding]]
103) -> TrendReport:
104 """Assemble a :class:`TrendReport` from aligned packages and findings."""
105 dates = [pkg.date or pkg.path.name for pkg in packages]
106
107 # Preserve rule order from the first package; align by rule id across dates.
108 order = [f.rule for f in findings_per_package[0]]
109 by_date = [{f.rule.id: f for f in findings} for findings in findings_per_package]
110
111 rows = [
112 TrendRow(
113 rule=rule,
114 statuses=[
115 col.get(rule.id).status if col.get(rule.id) else NOT_APPLICABLE
116 for col in by_date
117 ],
118 )
119 for rule in order
120 ]
121 stamp = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")
122 return TrendReport(
123 platform=packages[0].platform,
124 subject=packages[0].subject,
125 dates=dates,
126 rows=rows,
127 generated_at=stamp,
128 )
129
130
131def latest_findings(findings_per_package: list[list[Finding]]) -> list[Finding]:
132 """The findings of the most recent package (for --fail-on gating)."""
133 return findings_per_package[-1]
134
135
136# --------------------------------------------------------------------------- #
137# Rendering
138# --------------------------------------------------------------------------- #
139
140
141def _render_md(trend: TrendReport) -> str:
142 out: list[str] = []
143 out.append(f"# Evidence Trend — {trend.subject} ({trend.platform})")
144 out.append("")
145 out.append(f"- **Packages:** {len(trend.dates)}")
146 out.append(f"- **Timeline:** {trend.dates[0]} → {trend.dates[-1]}")
147 out.append(f"- **Generated:** {trend.generated_at}")
148 out.append("")
149 out.append("Legend: ✓ pass · ✗ fail · · not applicable")
150 out.append("")
151
152 header = "| Rule | Sev | " + " | ".join(trend.dates) + " |"
153 sep = "| --- | --- | " + " | ".join("---" for _ in trend.dates) + " |"
154 out.append(header)
155 out.append(sep)
156 for row in sorted(trend.rows, key=lambda r: _SEVERITY_ORDER.get(r.rule.severity, 1)):
157 cells = " | ".join(_STATUS_SYMBOL.get(s, "?") for s in row.statuses)
158 out.append(f"| {row.rule.title} | {row.rule.severity} | {cells} |")
159
160 fails = trend.fails_per_date()
161 out.append("| **Failing total** | | " + " | ".join(str(n) for n in fails) + " |")
162 return "\n".join(out).rstrip() + "\n"
163
164
165_TREND_CSS = (
166 _CSS
167 + """
168.trend { border-collapse: collapse; }
169.trend th.date { font-size: .78rem; white-space: nowrap; }
170.trend td.cell { text-align: center; font-weight: 700; width: 2.4rem; }
171.trend td.cell.pass { background: #e5f6ea; color: #1a7f37; }
172.trend td.cell.fail { background: #fdeaea; color: #c1272d; }
173.trend td.cell.na { background: #f4f4f6; color: #999; }
174.trend tr.totals td { font-weight: 700; background: #fafafa; }
175.rulecol { max-width: 22rem; }
176.legend { font-size: .85rem; color: #555; margin: .25rem 0 1rem; }
177@media (prefers-color-scheme: dark) {
178 .trend td.cell.pass { background: #12321d; color: #4ac36a; }
179 .trend td.cell.fail { background: #3a1416; color: #ff6b70; }
180 .trend td.cell.na { background: #202126; color: #888; }
181 .trend tr.totals td { background: #1c1d21; }
182 .legend { color: #aaa; }
183}
184"""
185)
186
187
188def _render_html(trend: TrendReport) -> str:
189 date_heads = "".join(f"<th class='date'>{escape(d)}</th>" for d in trend.dates)
190 body_rows: list[str] = []
191 for row in sorted(trend.rows, key=lambda r: _SEVERITY_ORDER.get(r.rule.severity, 1)):
192 cells = "".join(
193 f"<td class='cell {_STATUS_CLASS.get(s, 'na')}' title='{escape(s)}'>"
194 f"{_STATUS_SYMBOL.get(s, '?')}</td>"
195 for s in row.statuses
196 )
197 body_rows.append(
198 f"<tr><td class='rulecol'>{escape(row.rule.title)}"
199 f"<br><code>{escape(row.rule.id)}</code></td>"
200 f"<td>{escape(row.rule.severity)}</td>{cells}</tr>"
201 )
202 totals = "".join(f"<td class='cell'>{n}</td>" for n in trend.fails_per_date())
203
204 table = (
205 "<table class='trend'><thead><tr><th class='rulecol'>Rule</th><th>Sev</th>"
206 f"{date_heads}</tr></thead><tbody>{''.join(body_rows)}"
207 f"<tr class='totals'><td>Failing total</td><td></td>{totals}</tr>"
208 "</tbody></table>"
209 )
210 return (
211 "<!doctype html><html lang='en'><head><meta charset='utf-8'>"
212 "<meta name='viewport' content='width=device-width, initial-scale=1'>"
213 f"<title>Evidence Trend — {escape(trend.subject)}</title>"
214 f"<style>{_TREND_CSS}</style></head><body><main>"
215 f"<h1>Evidence Trend — {escape(trend.subject)} ({escape(trend.platform)})</h1>"
216 f"<p class='meta'>{len(trend.dates)} packages · {escape(trend.dates[0])} → "
217 f"{escape(trend.dates[-1])} · Generated {escape(trend.generated_at)}</p>"
218 "<p class='legend'>✓ pass · ✗ fail · · not applicable — cell colour tracks "
219 "each control over time.</p>"
220 f"{table}"
221 "<footer>Generated by audit-report · Audit Labs · evidence, not a verdict.</footer>"
222 "</main></body></html>\n"
223 )
224
225
226def _render_json(trend: TrendReport) -> str:
227 import json as _json
228
229 payload = {
230 "subject": trend.subject,
231 "platform": trend.platform,
232 "dates": trend.dates,
233 "generated_at": trend.generated_at,
234 "fails_per_date": trend.fails_per_date(),
235 "rules": [
236 {
237 "id": row.rule.id,
238 "title": row.rule.title,
239 "severity": row.rule.severity,
240 "controls": row.rule.controls,
241 "statuses": row.statuses,
242 }
243 for row in trend.rows
244 ],
245 }
246 return _json.dumps(payload, indent=2) + "\n"
247
248
249_RENDERERS = {"md": _render_md, "html": _render_html, "json": _render_json}
250
251
252def render(trend: TrendReport, fmt: str) -> str:
253 """Render a trend in the named format ('md', 'html', or 'json')."""
254 try:
255 return _RENDERERS[fmt](trend)
256 except KeyError:
257 raise ValueError(f"unknown format: {fmt!r}") from None