cloudleak-cli 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,229 @@
1
+ """Terminal text, Markdown, CSV, SARIF 2.1.0 and JUnit XML renderers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import csv
6
+ import io
7
+ import re
8
+ from decimal import Decimal
9
+ from xml.sax.saxutils import escape as xml_escape
10
+
11
+ from cloudleak.analysis import totals_finality
12
+ from cloudleak.money import display
13
+
14
+ NUMERIC = re.compile(r"^[+-]?(?:[0-9]+\.?[0-9]*|\.[0-9]+)(?:[eE][+-]?[0-9]+)?$")
15
+ STATUS_ORDER = {"FAIL": 0, "WARN": 1, "INFO": 2, "PASS": 3, "SKIP": 4}
16
+
17
+
18
+ def D(v) -> Decimal:
19
+ return Decimal(0) if v is None else v if isinstance(v, Decimal) else Decimal(str(v))
20
+
21
+
22
+ def owner_label(owner: dict | None) -> str:
23
+ """Never present an account name as if it were a confirmed owner."""
24
+ owner = owner or {}
25
+ if owner.get("status") == "tag":
26
+ return f"{owner.get('key')}={owner.get('value')}"
27
+ if owner.get("status") == "account":
28
+ return f"unattributed (route via account {owner.get('value')})"
29
+ return "unattributed"
30
+
31
+
32
+ def safe_cell(value: object) -> str:
33
+ """OWASP CSV injection: prefix text that a spreadsheet would execute as a formula."""
34
+ text = "" if value is None else str(value)
35
+ if text and text[0] in "=+-@\t\r" and not NUMERIC.match(text):
36
+ return "'" + text
37
+ return text
38
+
39
+
40
+ # ------------------------------------------------------------------ text
41
+ def doctor_text(report: dict, *, verbose: bool = False, color: bool = False) -> str:
42
+ d = report["doctor"]
43
+ colors = {"FAIL": "31", "WARN": "33", "PASS": "32", "INFO": "36", "SKIP": "90"}
44
+
45
+ def tag(s: str) -> str:
46
+ return f"\x1b[{colors[s]}m{s:<4}\x1b[0m" if color else f"{s:<4}"
47
+
48
+ lines = [f"CloudLeak doctor · {len(report['inputs'])} file(s) · run {report['run']['report_run_id']}", ""]
49
+ results = sorted(d["results"], key=lambda r: (STATUS_ORDER[r["status"]], r["check_id"]))
50
+ for r in results:
51
+ if not verbose and r["status"] in ("PASS", "SKIP"):
52
+ continue
53
+ scope = "" if r["scope"] == "all inputs" else f" [{r['scope']}]"
54
+ lines.append(f"{tag(r['status'])} {r['check_id']}{scope}: {r['message']}")
55
+ if r.get("remediation") and r["status"] in ("WARN", "FAIL"):
56
+ lines.append(f" fix: {r['remediation']}")
57
+ c = d["counts"]
58
+ lines += ["", f"Result: {d['status']} ({c['FAIL']} fail, {c['WARN']} warn, {c['INFO']} info, "
59
+ f"{c['PASS']} pass, {c['SKIP']} skip)"]
60
+ if not verbose and c["PASS"]:
61
+ lines.append("Passing checks hidden; use --verbose to list them.")
62
+ return "\n".join(lines) + "\n"
63
+
64
+
65
+ def audit_text(report: dict) -> str:
66
+ lines = [f"CloudLeak audit · {len(report['inputs'])} file(s) · run {report['run']['report_run_id']}"]
67
+ if report.get("synthetic_data"):
68
+ lines.append("SYNTHETIC TEST DATA")
69
+ if report.get("doctor") and report["doctor"]["counts"]["FAIL"]:
70
+ lines.append(f"TOTALS MAY BE WRONG: {report['doctor']['counts']['FAIL']} data-quality check(s) failed; "
71
+ "run `cloudleak doctor` and fix the inputs first.")
72
+ for p in report["periods"]:
73
+ if p["finality"] == "preliminary_estimate":
74
+ lines.append(f"PRELIMINARY: {p['provider']} {p['billing_period']}: {p['reason']}")
75
+ lines.append("")
76
+ lines.append(f"{'provider':<16} {'period':<8} {'basis':<10} {'total':>18}")
77
+ for t in report["totals"]:
78
+ lines.append(f"{t['provider'][:16]:<16} {t['billing_period'] or '-':<8} {t['cost_basis']:<10} "
79
+ f"{display(D(t['total']), t['currency']):>18}")
80
+ for br in report.get("variance") or []:
81
+ lines += ["", br["narrative"]]
82
+ sig = [f for f in report["findings"] if f["classification"] == "billing_signature_candidate"]
83
+ lines += ["", f"{len(sig)} billing-signature finding(s) (Level 2; observed cost, not savings):"]
84
+ for f in sig[:25]:
85
+ where = f.get("resource_id") or f.get("sub_account_id") or "-"
86
+ lines.append(f" {f['rule_id']} {display(D(f['financials']['observed_cost']), f['currency']):>14} "
87
+ f"{f['financials']['cost_basis']} {f['provider']} {f['billing_period']} {where[:70]}")
88
+ if len(sig) > 25:
89
+ lines.append(f" ... {len(sig) - 25} more in the HTML/JSON output")
90
+ if report.get("doctor"):
91
+ c = report["doctor"]["counts"]
92
+ lines += ["", f"Data quality: {report['doctor']['status']} ({c['FAIL']} fail, {c['WARN']} warn). "
93
+ "Run `cloudleak doctor` for details."]
94
+ return "\n".join(lines) + "\n"
95
+
96
+
97
+ # -------------------------------------------------------------- markdown
98
+ def markdown(report: dict) -> str:
99
+ out = ["# CloudLeak audit brief", "",
100
+ f"Run `{report['run']['report_run_id']}` · CloudLeak {report['tool']['version']} · processed offline", ""]
101
+ if report.get("synthetic_data"):
102
+ out += ["> **Synthetic test data.**", ""]
103
+ pre = [p for p in report["periods"] if p["finality"] == "preliminary_estimate"]
104
+ if pre:
105
+ out += ["> **Preliminary estimate:** " + ", ".join(f"{p['provider']} {p['billing_period']}" for p in pre)
106
+ + " not finalized.", ""]
107
+ out += ["## Totals", "", "| Provider | Period | Basis | Finality | Total |", "|---|---|---|---|---:|"]
108
+ fin = totals_finality(report["periods"])
109
+ for t in report["totals"]:
110
+ f = fin.get((t["provider"], t["billing_period"], t["currency"], t["cost_basis"]), "unknown")
111
+ out.append(f"| {md(t['provider'])} | {t['billing_period']} | {t['cost_basis']} | {f} | "
112
+ f"{display(D(t['total']), t['currency'])} |")
113
+ for br in report.get("variance") or []:
114
+ out += ["", f"## {br['base_period']} → {br['current_period']} ({br['currency']}, {br['cost_basis']})", "",
115
+ md(br["narrative"]), "", "| Driver | Amount |", "|---|---:|"]
116
+ out += [f"| {b['label']} | {display(D(b['amount']), br['currency'])} |" for b in br["bridge"]
117
+ if D(b["amount"]) != 0]
118
+ sig = [f for f in report["findings"] if f["classification"] == "billing_signature_candidate"]
119
+ out += ["", "## Billing-signature findings (Level 2)", "",
120
+ "Each amount uses the cost basis shown. Verify the billing signal before acting.", "",
121
+ "| Rule | Provider | Period | Resource / scope | Observed | Owner |", "|---|---|---|---|---:|---|"]
122
+ for f in sig[:100]:
123
+ owner = owner_label(f.get("owner_routing"))
124
+ out.append(f"| {f['rule_id']} {md(f['title'])} | {f['provider']} | {f['billing_period']} | "
125
+ f"`{md(f.get('resource_id') or f.get('sub_account_id') or '-')}` | "
126
+ f"{display(D(f['financials']['observed_cost']), f['currency'])} "
127
+ f"{f['financials']['cost_basis']} | {md(owner)} |")
128
+ if report.get("doctor"):
129
+ bad = [c for c in report["doctor"]["results"] if c["status"] in ("WARN", "FAIL")]
130
+ out += ["", f"## Data quality: {report['doctor']['status']}", ""]
131
+ out += [f"- **{c['status']}** `{c['check_id']}` {md(c['scope'])}: {md(c['message'])}" for c in bad]
132
+ out += ["", "## Limitations", ""] + [f"- {md(x)}" for x in report.get("limitations", [])]
133
+ return "\n".join(out) + "\n"
134
+
135
+
136
+ def md(text: object) -> str:
137
+ return str(text or "").replace("|", "\\|").replace("\n", " ").replace("<", "&lt;")
138
+
139
+
140
+ # ------------------------------------------------------------------- csv
141
+ FINDING_COLUMNS = ["finding_id", "rule_id", "title", "evidence_level", "classification", "severity", "provider",
142
+ "billing_account_id", "sub_account_id", "resource_id", "region", "service", "billing_period",
143
+ "period_finality", "currency", "cost_basis", "observed_cost", "verified_savings", "owner",
144
+ "summary", "verification_commands", "observed_billed_cost", "observed_effective_cost"]
145
+
146
+
147
+ def findings_csv(report: dict) -> str:
148
+ buf = io.StringIO()
149
+ w = csv.writer(buf, lineterminator="\n")
150
+ w.writerow(FINDING_COLUMNS)
151
+ for f in report["findings"]:
152
+ owner = f.get("owner_routing") or {}
153
+ cmds = " && ".join(s["command"] for s in f.get("required_verification_steps", []) if s.get("command"))
154
+ row = [f["finding_id"], f["rule_id"], f["title"], f["evidence_level"], f["classification"], f["severity"],
155
+ f["provider"], f["billing_account_id"], f["sub_account_id"], f["resource_id"], f["region"],
156
+ f["service"], f["billing_period"], f["period_finality"], f["currency"],
157
+ f["financials"]["cost_basis"], f["financials"]["observed_cost"], "", owner.get("value") or "",
158
+ f["summary"], cmds, f["financials"].get("observed_billed_cost"),
159
+ f["financials"].get("observed_effective_cost")]
160
+ w.writerow([safe_cell(c) for c in row])
161
+ return buf.getvalue()
162
+
163
+
164
+ # ----------------------------------------------------------------- sarif
165
+ def sarif(report: dict) -> dict:
166
+ level = {"high": "error", "medium": "warning", "low": "note", "info": "note"}
167
+ rules: dict[str, dict] = {}
168
+ results = []
169
+ names = {i["source_id"]: i["name"] for i in report["inputs"]}
170
+ for f in report["findings"]:
171
+ rules.setdefault(f["rule_id"], {"id": f["rule_id"], "name": f["title"],
172
+ "shortDescription": {"text": f["title"]},
173
+ "properties": {"evidence_level": f["evidence_level"]}})
174
+ locs = [{"physicalLocation": {"artifactLocation": {"uri": names.get(s["source_id"], "export")},
175
+ "region": {"startLine": int(s["row"]) + 1}}}
176
+ for s in f["exact_evidence"].get("sample_rows", [])[:1]]
177
+ results.append({
178
+ "ruleId": f["rule_id"], "level": level.get(f["severity"], "note"),
179
+ "message": {"text": f["summary"] + " Observed cost is not a saving; verify before acting."},
180
+ "partialFingerprints": {"cloudleakFindingId": f["finding_id"]},
181
+ "locations": locs or [{"physicalLocation": {"artifactLocation": {"uri": "billing-export"}}}],
182
+ "properties": {**f["financials"], "currency": f["currency"],
183
+ "period_finality": f["period_finality"], "evidence_level": f["evidence_level"]},
184
+ })
185
+ for c in (report.get("doctor") or {}).get("results", []):
186
+ if c["status"] not in ("WARN", "FAIL"):
187
+ continue
188
+ rules.setdefault(c["check_id"], {"id": c["check_id"], "name": c["title"],
189
+ "shortDescription": {"text": c["title"]}})
190
+ results.append({"ruleId": c["check_id"], "level": "error" if c["status"] == "FAIL" else "warning",
191
+ "message": {"text": f"{c['scope']}: {c['message']}"},
192
+ "locations": [{"physicalLocation": {"artifactLocation": {"uri": c["scope"]
193
+ if c["scope"] != "all inputs" else "billing-export"}}}]})
194
+ return {
195
+ "$schema": "https://json.schemastore.org/sarif-2.1.0.json", "version": "2.1.0",
196
+ "runs": [{"tool": {"driver": {"name": "CloudLeak", "version": report["tool"]["version"],
197
+ "informationUri": "https://github.com/pranavg21/cloudleak",
198
+ "rules": sorted(rules.values(), key=lambda r: r["id"])}},
199
+ "results": results}],
200
+ }
201
+
202
+
203
+ # ----------------------------------------------------------------- junit
204
+ def junit(report: dict) -> str:
205
+ d = report["doctor"]
206
+ results = d["results"]
207
+ fails = sum(1 for r in results if r["status"] == "FAIL")
208
+ warns = sum(1 for r in results if r["status"] == "WARN")
209
+ skips = sum(1 for r in results if r["status"] == "SKIP")
210
+ out = ['<?xml version="1.0" encoding="UTF-8"?>',
211
+ f'<testsuites name="cloudleak doctor" tests="{len(results)}" failures="{fails}" errors="0">',
212
+ f'<testsuite name="cloudleak.doctor" tests="{len(results)}" failures="{fails}" errors="0" '
213
+ f'skipped="{skips}">',
214
+ f'<properties><property name="warnings" value="{warns}"/>'
215
+ f'<property name="run_id" value="{xml_escape(report["run"]["report_run_id"])}"/></properties>']
216
+ for i, r in enumerate(results):
217
+ name = xml_escape(f"{r['check_id']} {r['title']} [{r['scope']}]", {'"': "&quot;"})
218
+ out.append(f'<testcase classname="cloudleak.{r["category"]}" name="{name}" time="0">')
219
+ msg = xml_escape(r["message"], {'"': "&quot;"})
220
+ if r["status"] == "FAIL":
221
+ out.append(f'<failure message="{msg}" type="FAIL">{xml_escape(r.get("remediation") or "")}</failure>')
222
+ elif r["status"] == "SKIP":
223
+ out.append(f'<skipped message="{msg}"/>')
224
+ elif r["status"] == "WARN":
225
+ out.append(f"<system-out>WARN: {xml_escape(r['message'])}</system-out>")
226
+ out.append("</testcase>")
227
+ del i
228
+ out += ["</testsuite>", "</testsuites>"]
229
+ return "\n".join(out) + "\n"
@@ -0,0 +1,390 @@
1
+ """Self-contained offline HTML brief.
2
+
3
+ One file, no JavaScript, no external requests (enforced by a Content
4
+ Security Policy), readable in light and dark mode, and printable to PDF.
5
+ Every value from the export is HTML-escaped.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from decimal import Decimal
11
+ from html import escape
12
+
13
+ from cloudleak.analysis import totals_finality
14
+ from cloudleak.money import display, money_context
15
+ from cloudleak.render.formats import owner_label
16
+ from cloudleak.report import CAN_CANNOT, ISSUES_URL
17
+
18
+ CSS = """
19
+ :root{--bg:#fbfbfa;--panel:#fff;--ink:#1b1d21;--muted:#5d636f;--line:#e3e4e8;--accent:#1d5fd1;
20
+ --good:#1f7a4d;--warn:#9a6200;--bad:#b42318;--info:#4a5568;--bar:#2f6fde;--bar2:#9db6e8;--pos:#c2410c;--neg:#15803d;
21
+ --chip:#f1f2f5;--code:#f4f5f7}
22
+ @media (prefers-color-scheme:dark){:root:not([data-theme=light]){--bg:#121317;--panel:#1a1c21;--ink:#e8e9ec;
23
+ --muted:#a0a5b1;--line:#2c2f37;--accent:#7aa7ff;--good:#4cc38a;--warn:#f0b44c;--bad:#ff7b72;--info:#a0aec0;
24
+ --bar:#5b8ef0;--bar2:#33456b;--pos:#fb923c;--neg:#4ade80;--chip:#24272e;--code:#202329}}
25
+ *{box-sizing:border-box}html{-webkit-text-size-adjust:100%}
26
+ body{margin:0;background:var(--bg);color:var(--ink);font:15px/1.55 system-ui,-apple-system,"Segoe UI",Roboto,
27
+ sans-serif}
28
+ main{max-width:1040px;margin:0 auto;padding:28px 16px 64px}
29
+ h1{font-size:26px;margin:0 0 4px;letter-spacing:-.01em}h2{font-size:19px;margin:40px 0 10px;
30
+ padding-top:8px;border-top:1px solid var(--line)}h3{font-size:16px;margin:22px 0 8px}
31
+ p{margin:6px 0 10px}.muted{color:var(--muted)}small,.small{font-size:13px}
32
+ a{color:var(--accent)}code,pre{font:12.5px/1.5 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}
33
+ pre{background:var(--code);border:1px solid var(--line);border-radius:6px;padding:8px 10px;overflow-x:auto;
34
+ white-space:pre-wrap;word-break:break-all;margin:4px 0 10px}
35
+ .banner{border:1px solid;border-radius:8px;padding:10px 14px;margin:12px 0;font-weight:500}
36
+ .banner.warn{border-color:var(--warn);color:var(--warn)}.banner.bad{border-color:var(--bad);color:var(--bad)}
37
+ .banner.info{border-color:var(--line);color:var(--muted)}
38
+ .kpis{display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:10px;margin:16px 0}
39
+ .kpi{background:var(--panel);border:1px solid var(--line);border-radius:10px;padding:12px 14px}
40
+ .kpi .v{font-size:22px;font-weight:650;font-variant-numeric:tabular-nums;margin-top:2px}
41
+ .kpi .l{font-size:12.5px;color:var(--muted);text-transform:uppercase;letter-spacing:.04em}
42
+ .table-wrap{overflow-x:auto;margin:8px 0 14px;border:1px solid var(--line);border-radius:8px;background:var(--panel)}
43
+ table{border-collapse:collapse;width:100%;font-size:13.5px}th,td{padding:7px 10px;text-align:left;
44
+ border-bottom:1px solid var(--line);vertical-align:top}th{font-weight:600;color:var(--muted);font-size:12.5px;
45
+ white-space:nowrap}tr:last-child td{border-bottom:0}td.n,th.n{text-align:right;font-variant-numeric:tabular-nums;
46
+ white-space:nowrap}
47
+ .chip{display:inline-block;border-radius:999px;padding:1px 8px;font-size:12px;font-weight:600;
48
+ background:var(--chip);white-space:nowrap}
49
+ .s-PASS{color:var(--good)}.s-WARN{color:var(--warn)}.s-FAIL{color:var(--bad)}.s-INFO,.s-SKIP{color:var(--info)}
50
+ .fin-finalized{color:var(--good)}.fin-preliminary_estimate{color:var(--warn)}.fin-unknown{color:var(--info)}
51
+ details{background:var(--panel);border:1px solid var(--line);border-radius:8px;margin:8px 0}
52
+ summary{cursor:pointer;padding:10px 12px;list-style-position:outside;overflow-wrap:anywhere}
53
+ p,li,.banner{overflow-wrap:anywhere}td{overflow-wrap:break-word}
54
+ .chart{overflow-x:auto;margin:8px 0}.chart svg{min-width:620px}.chart .note{font-size:12px;color:var(--muted)}
55
+ details>div{padding:0 14px 12px}
56
+ summary .amt{float:right;font-variant-numeric:tabular-nums;font-weight:600;margin-left:12px}
57
+ ul{margin:4px 0 10px;padding-left:22px}li{margin:2px 0}
58
+ .grid2{display:grid;grid-template-columns:1fr 1fr;gap:16px}@media (max-width:760px){.grid2{grid-template-columns:1fr}
59
+ summary .amt{float:none;display:block;margin:2px 0 0}}
60
+ svg text{fill:var(--ink);font:12px system-ui,sans-serif}svg .muted{fill:var(--muted)}
61
+ .bar{fill:var(--bar)}.bar2{fill:var(--bar2)}.pos{fill:var(--pos)}.neg{fill:var(--neg)}.axis{stroke:var(--line)}
62
+ footer{margin-top:48px;color:var(--muted);font-size:13px;border-top:1px solid var(--line);padding-top:14px}
63
+ @media print{body{background:#fff}details{break-inside:avoid}details:not([open])>div{display:block}
64
+ .banner{break-inside:avoid}a{color:inherit}}
65
+ """
66
+
67
+
68
+ DRIVER_LABELS = {"volume_and_rate": "volume / rate", "new": "new", "discontinued": "discontinued",
69
+ "unquantified": "unquantified", "credits": "credits", "tax": "tax", "purchases": "purchases",
70
+ "adjustments": "adjustments", "volume": "volume", "rate": "rate"}
71
+
72
+
73
+ def e(v: object) -> str:
74
+ return escape("" if v is None else str(v), quote=True)
75
+
76
+
77
+ def D(v: object) -> Decimal:
78
+ if v is None:
79
+ return Decimal(0)
80
+ return v if isinstance(v, Decimal) else Decimal(str(v))
81
+
82
+
83
+ def money(v: object, cur: str | None = None) -> str:
84
+ return e(display(D(v), cur))
85
+
86
+
87
+ def chip(text: str, cls: str = "") -> str:
88
+ return f'<span class="chip {e(cls)}">{e(text)}</span>'
89
+
90
+
91
+ def table(headers: list[str], rows: list[list[str]], numeric: set[int] | None = None) -> str:
92
+ numeric = numeric or set()
93
+ th = "".join(f'<th class="{"n" if i in numeric else ""}">{e(h)}</th>' for i, h in enumerate(headers))
94
+ body = "".join("<tr>" + "".join(f'<td class="{"n" if i in numeric else ""}">{c}</td>'
95
+ for i, c in enumerate(r)) + "</tr>" for r in rows)
96
+ return f'<div class="table-wrap"><table><thead><tr>{th}</tr></thead><tbody>{body}</tbody></table></div>'
97
+
98
+
99
+ def hbars(items: list[tuple[str, Decimal]], cur: str | None, width: int = 480) -> str:
100
+ """Horizontal bar chart of positive amounts (negatives are shown as zero-length with a label)."""
101
+ if not items:
102
+ return ""
103
+ top = max((v for _, v in items), default=Decimal(0))
104
+ rowh, label_w, pad = 24, 190, 8
105
+ h = rowh * len(items) + pad
106
+ parts = [f'<svg viewBox="0 0 {width} {h}" width="100%" role="img" aria-label="Spend by category">']
107
+ for i, (label, v) in enumerate(items):
108
+ y = i * rowh + 4
109
+ w = 0 if top <= 0 or v <= 0 else float(v / top) * (width - label_w - 110)
110
+ short = label if len(label) <= 28 else label[:27] + "…"
111
+ parts.append(f'<text x="0" y="{y + 13}"><title>{e(label)}</title>{e(short)}</text>')
112
+ parts.append(f'<rect class="bar" x="{label_w}" y="{y + 2}" width="{w:.1f}" height="14" rx="2"/>')
113
+ parts.append(f'<text class="muted" x="{label_w + w + 6:.1f}" y="{y + 13}">{money(v)}</text>')
114
+ parts.append("</svg>")
115
+ return "".join(parts)
116
+
117
+
118
+ def waterfall(bridge: dict, width: int = 900) -> str:
119
+ steps = [("start", bridge["base_period"], D(bridge["base_total"]))]
120
+ for b in bridge["bridge"]:
121
+ if display(D(b["amount"])) not in ("0.00", "-0.00"):
122
+ steps.append(("delta", b["label"], D(b["amount"])))
123
+ steps.append(("end", bridge["current_period"], D(bridge["current_total"])))
124
+ running, lo, hi, bars = Decimal(0), Decimal(0), Decimal(0), []
125
+ for kind, label, amt in steps:
126
+ if kind == "delta":
127
+ a, b = running, running + amt
128
+ running = b
129
+ else:
130
+ a, b = Decimal(0), amt
131
+ running = amt
132
+ bars.append((kind, label, amt, min(a, b), max(a, b)))
133
+ lo, hi = min(lo, a, b), max(hi, a, b)
134
+ levels = [x for _, _, _, a, b in bars for x in (a, b) if x != 0]
135
+ moves = sum((abs(amt) for kind, _, amt, _, _ in bars if kind == "delta"), Decimal(0))
136
+ broken = bool(levels) and min(levels) > 0 and moves < min(levels) * Decimal("0.5")
137
+ if broken: # small drivers on large totals: zoom in and say so
138
+ lo = min(levels) - (max(levels) - min(levels)) * Decimal("0.6") - moves * Decimal("0.2")
139
+ span = (hi - lo) or Decimal(1)
140
+ n = len(bars)
141
+ top, bottom, left = 18, 200, 8
142
+ slot = (width - left) / n
143
+ bw = min(70.0, slot * 0.62)
144
+
145
+ def y(v: Decimal) -> float:
146
+ return top + float((hi - v) / span) * (bottom - top)
147
+
148
+ out = [f'<svg viewBox="0 0 {width} 250" width="100%" role="img" aria-label="Month-over-month bridge">',
149
+ f'<line class="axis" x1="0" x2="{width}" y1="{y(Decimal(0)):.1f}" y2="{y(Decimal(0)):.1f}"/>']
150
+ for i, (kind, label, amt, a, b) in enumerate(bars):
151
+ a, b = max(a, lo), max(b, lo)
152
+ x = left + i * slot + (slot - bw) / 2
153
+ cls = "bar" if kind != "delta" else ("pos" if amt > 0 else "neg")
154
+ hgt = max(1.0, y(a) - y(b))
155
+ out.append(f'<rect class="{cls}" x="{x:.1f}" y="{y(b):.1f}" width="{bw:.1f}" height="{hgt:.1f}" rx="2">'
156
+ f'<title>{e(label)}: {money(amt)}</title></rect>')
157
+ val = ("+" if kind == "delta" and amt > 0 else "") + display(amt, None, 0)
158
+ out.append(f'<text x="{x + bw / 2:.1f}" y="{y(b) - 4:.1f}" text-anchor="middle">{e(val)}</text>')
159
+ words = label.split()
160
+ line1 = " ".join(words[:2])
161
+ line2 = " ".join(words[2:4])
162
+ out.append(f'<text class="muted" x="{x + bw / 2:.1f}" y="222" text-anchor="middle">{e(line1)}</text>')
163
+ if line2:
164
+ out.append(f'<text class="muted" x="{x + bw / 2:.1f}" y="237" text-anchor="middle">{e(line2)}</text>')
165
+ out.append("</svg>")
166
+ note = '<div class="note">Vertical axis does not start at zero.</div>' if broken else ""
167
+ return f'<div class="chart">{"".join(out)}{note}</div>'
168
+
169
+
170
+ @money_context
171
+ def render(report: dict) -> str:
172
+ r = report
173
+ title = "CloudLeak audit brief"
174
+ sections: list[str] = []
175
+ periods = r.get("periods") or []
176
+ prelim = [p for p in periods if p["finality"] == "preliminary_estimate"]
177
+ doctor = r.get("doctor")
178
+
179
+ head = [f"<h1>{e(title)}</h1>",
180
+ f'<p class="muted small">Run {e(r["run"]["report_run_id"])} · generated {e(r["run"]["generated_at"])} · '
181
+ f'CloudLeak {e(r["tool"]["version"])} · DuckDB {e(r["tool"]["duckdb_version"])} · processed offline, '
182
+ "no cloud credentials</p>"]
183
+ if r.get("synthetic_data"):
184
+ head.append('<div class="banner info">SYNTHETIC TEST DATA: these inputs are generated fixtures, not a '
185
+ "real bill.</div>")
186
+ if prelim:
187
+ names = ", ".join(sorted({f"{p['provider']} {p['billing_period']}" for p in prelim}))
188
+ head.append(f'<div class="banner warn">PRELIMINARY ESTIMATE: {e(names)} not finalized. Amounts can '
189
+ "still change as late charges, credits and refunds post.</div>")
190
+ if doctor and doctor["counts"]["FAIL"]:
191
+ fails = [c for c in doctor["results"] if c["status"] == "FAIL"]
192
+ items = "".join(f"<li>{e(c['check_id'])} {e(c['title'])}: {e(c['message'])}</li>" for c in fails[:6])
193
+ head.append(f'<div class="banner bad">TOTALS MAY BE WRONG: {len(fails)} data-quality check(s) failed. '
194
+ f"Fix the inputs before relying on any number in this report.<ul>{items}</ul></div>")
195
+ sections.append("".join(head))
196
+
197
+ # KPIs
198
+ kpis = []
199
+ totals = r.get("totals") or []
200
+ principal = {(p["currency"], p["cost_basis"], p["billing_period"]) for p in periods if p["days_covered"] > 0}
201
+ agg: dict[tuple, Decimal] = {}
202
+ for t in totals:
203
+ if (t["currency"], t["cost_basis"], t["billing_period"]) not in principal:
204
+ continue
205
+ k = (t["currency"], t["cost_basis"], t["billing_period"])
206
+ agg[k] = agg.get(k, Decimal(0)) + D(t["total"])
207
+ shown = set()
208
+ for (cur, basis, period), amount in sorted(agg.items(), key=lambda kv: (str(kv[0][0]), kv[0][1], kv[0][2]),
209
+ reverse=True):
210
+ if (cur, basis) in shown:
211
+ continue
212
+ shown.add((cur, basis))
213
+ kpis.append(f'<div class="kpi"><div class="l">{e(basis)} spend · {e(period)}</div>'
214
+ f'<div class="v">{money(amount, cur)}</div></div>')
215
+ l2 = [f for f in r.get("findings", []) if f["evidence_level"] == "L2"]
216
+ kpis.append(f'<div class="kpi"><div class="l">Billing-signature findings</div><div class="v">{len(l2)}</div>'
217
+ '</div>')
218
+ if doctor:
219
+ c = doctor["counts"]
220
+ kpis.append(f'<div class="kpi"><div class="l">Data quality</div><div class="v s-{e(doctor["status"])}">'
221
+ f'{e(doctor["status"])}</div><div class="small muted">{c["FAIL"]} fail · {c["WARN"]} warn · '
222
+ f'{c["PASS"]} pass</div></div>')
223
+ sections.append(f'<div class="kpis">{"".join(kpis)}</div>')
224
+
225
+ sections.append("<h2 id=\"proof\">What this report can and cannot prove</h2>" + table(
226
+ ["Question", "Status"], [[e(q), e(a)] for q, a in CAN_CANNOT]))
227
+
228
+ # Variance
229
+ for br in r.get("variance") or []:
230
+ cur = br["currency"]
231
+ rows = [[e(d["label"]), money(d["amount"], cur)] for d in br["bridge"]
232
+ if display(D(d["amount"])) not in ("0.00", "-0.00")]
233
+ changes = [[e(c["service"]), e(c["sku"]), e(c.get("sub_account_name") or c.get("sub_account_id") or ""),
234
+ money(c["base_cost"]), money(c["current_cost"]), money(c["delta"]),
235
+ e(DRIVER_LABELS.get(c["driver"], c["driver"])),
236
+ e(owner_label(c.get("owner_routing")))]
237
+ for c in br["top_line_changes"][:15]]
238
+ cats = [[e(c["service_category"]), money(c["base_cost"]), money(c["current_cost"]), money(c["delta"])]
239
+ for c in br["by_service_category"]]
240
+ notes = "".join(f'<p class="small muted">{e(n)}</p>' for n in br.get("notes", []))
241
+ sections.append(
242
+ f'<h2 id="variance-{e(cur)}-{e(br["cost_basis"])}">Month over month: {e(br["base_period"])} → '
243
+ f'{e(br["current_period"])} ({e(cur)}, {e(br["cost_basis"])})</h2>'
244
+ f"<p>{e(br['narrative'])}</p>{notes}{waterfall(br)}"
245
+ '<div class="grid2"><div><h3>Bridge</h3>' + table(["Driver", "Amount"], rows, {1}) + "</div>"
246
+ "<div><h3>By service category</h3>" + table(["Category", br["base_period"], br["current_period"], "Δ"],
247
+ cats, {1, 2, 3}) + "</div></div>"
248
+ "<h3>Largest SKU group changes</h3>" + table(
249
+ ["Service", "SKU", "Account", "Before", "After", "Δ", "Driver", "Owner"], changes, {3, 4, 5}))
250
+
251
+ # Spend
252
+ spend = ['<h2 id="spend">Spend</h2>']
253
+ trows = []
254
+ finality = totals_finality(periods)
255
+ for t in totals:
256
+ cur = t["currency"]
257
+ comp = []
258
+ for k in ("purchase", "fee", "tax", "credit", "refund", "discount", "adjustment", "embedded_credits"):
259
+ if t.get(k) not in (None, "0.00") and D(t.get(k)) != 0:
260
+ comp.append(f"{k.replace('_', ' ')} {display(D(t[k]))}")
261
+ fin = finality.get((t["provider"], t["billing_period"], cur, t["cost_basis"]), "unknown")
262
+ trows.append([e(t["provider"]), e(t["billing_period"]), e(t["cost_basis"]),
263
+ f'<span class="fin-{e(fin)}">{e(fin.replace("_", " "))}</span>', money(t["total"], cur),
264
+ money(t.get("usage"), cur), e("; ".join(comp))])
265
+ spend.append(table(["Provider", "Period", "Basis", "Finality", "Total", "Usage", "Other components"],
266
+ trows, {4, 5}))
267
+ bd = r.get("breakdowns") or {}
268
+ charts = []
269
+ for dim, label in (("service_category", "By service category"), ("service", "Top services"),
270
+ ("sub_account_id", "Top accounts / subscriptions / projects")):
271
+ rows = bd.get(dim) or []
272
+ groups: dict[tuple, list] = {}
273
+ for row in rows:
274
+ groups.setdefault((row["currency"], row["cost_basis"]), []).append(row)
275
+ for (cur, basis), items in groups.items():
276
+ charts.append(f"<div><h3>{e(label)} <span class=\"muted small\">{e(cur)} · {e(basis)}, all periods"
277
+ f"</span></h3>{hbars([(i['key'], D(i['cost'])) for i in items], cur)}</div>")
278
+ if charts:
279
+ spend.append('<div class="grid2">' + "".join(charts) + "</div>")
280
+ sections.append("".join(spend))
281
+
282
+ # Findings
283
+ fs = r.get("findings") or []
284
+ sig = [f for f in fs if f["classification"] == "billing_signature_candidate"]
285
+ other = [f for f in fs if f["classification"] in ("reconciliation_delta",)]
286
+ fsec = ['<h2 id="findings">Billing-signature findings (Level 2)</h2>',
287
+ '<p class="muted small">Each amount uses the cost basis shown on its finding. '
288
+ "Verify the billing signal with the read-only steps before making a change."
289
+ "</p>"]
290
+ if not sig:
291
+ fsec.append("<p>No billing signatures matched.</p>")
292
+ by_rule: dict[str, list] = {}
293
+ for f in sig:
294
+ by_rule.setdefault(f["rule_id"], []).append(f)
295
+ for rid, items in by_rule.items():
296
+ subtotals: dict[tuple, Decimal] = {}
297
+ for f in items:
298
+ key = (f["currency"], f["financials"]["cost_basis"])
299
+ subtotals[key] = subtotals.get(key, Decimal(0)) + D(f["financials"]["observed_cost"])
300
+ tot = " · ".join(f"{display(v, c)} {basis}" for (c, basis), v in
301
+ sorted(subtotals.items(), key=lambda kv: tuple(map(str, kv[0]))))
302
+ fsec.append(f"<h3>{e(items[0]['title'])} <span class=\"muted small\">{e(rid)} · {len(items)} item(s) · "
303
+ f"{e(tot)} observed</span></h3>")
304
+ fsec.append(f'<p class="small muted">{e(items[0]["details"].get("rationale", ""))}</p>')
305
+ for f in items[:40]:
306
+ fsec.append(_finding_html(f))
307
+ if len(items) > 40:
308
+ fsec.append(f'<p class="small muted">{len(items) - 40} more in the JSON output.</p>')
309
+ for f in other:
310
+ fsec.append(_finding_html(f))
311
+ sections.append("".join(fsec))
312
+
313
+ # Data quality
314
+ if doctor:
315
+ rows = []
316
+ for c in doctor["results"]:
317
+ if c["status"] in ("WARN", "FAIL"):
318
+ rows.append([f'<span class="chip s-{e(c["status"])}">{e(c["status"])}</span>', e(c["check_id"]),
319
+ e(c["scope"]), e(c["message"]) + (f'<br><span class="small muted">Fix: '
320
+ f'{e(c["remediation"])}</span>' if c["remediation"]
321
+ else "")])
322
+ quiet = [c for c in doctor["results"] if c["status"] not in ("WARN", "FAIL")]
323
+ qrows = [[f'<span class="s-{e(c["status"])}">{e(c["status"])}</span>', e(c["check_id"]), e(c["scope"]),
324
+ e(c["message"])] for c in quiet]
325
+ sections.append(
326
+ '<h2 id="quality">Data quality</h2>'
327
+ + (table(["Status", "Check", "Scope", "Finding"], rows) if rows else "<p>No warnings or failures.</p>")
328
+ + f"<details><summary>{len(quiet)} passing and informational checks</summary><div>"
329
+ + table(["Status", "Check", "Scope", "Detail"], qrows) + "</div></details>")
330
+
331
+ # Provenance
332
+ inputs = [[e(i["name"]), e(i["format"]), e(i.get("dataset") or "unrecognized"), f'{i.get("rows", 0):,}',
333
+ f'<code>{e(i["sha256"][:16])}…</code>'] for i in r.get("inputs", [])]
334
+ t = r["tool"]
335
+ sections.append(
336
+ '<h2 id="provenance">Provenance and method</h2>'
337
+ + table(["File", "Format", "Detected as", "Rows", "SHA-256"], inputs, {3})
338
+ + f'<p class="small">CloudLeak {e(t["version"])}, DuckDB {e(t["duckdb_version"])}, Python '
339
+ f'{e(t["python_version"])}, rule pack {e(t["rule_pack_version"])} ({e(t["rule_pack_hash"])}). '
340
+ "Amounts are exact decimals (no floating point); totals are never summed across currencies or across "
341
+ "actual and amortized bases. Identical rows are kept, not de-duplicated.</p>"
342
+ + "<ul>" + "".join(f"<li class=\"small\">{e(x)}</li>" for x in r.get("limitations", [])) + "</ul>")
343
+
344
+ footer = (f'<footer>Generated locally by CloudLeak. This file contains identifiers and costs from the source '
345
+ f'export; share it within the same access boundary as the export, or run '
346
+ f'<code>cloudleak redact</code> first. · <a href="{e(ISSUES_URL)}">Report a provider schema quirk '
347
+ "(use synthetic headers)</a></footer>")
348
+ csp = ("default-src 'none'; style-src 'unsafe-inline'; img-src data:; base-uri 'none'; form-action 'none'")
349
+ return (
350
+ "<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\">"
351
+ f'<meta http-equiv="Content-Security-Policy" content="{csp}">'
352
+ '<meta name="viewport" content="width=device-width,initial-scale=1">'
353
+ '<meta name="referrer" content="no-referrer">'
354
+ f"<title>CloudLeak audit brief</title><style>{CSS}</style></head><body><main>"
355
+ + "".join(sections) + footer + "</main></body></html>\n"
356
+ )
357
+
358
+
359
+ def _finding_html(f: dict) -> str:
360
+ fin = f["period_finality"]
361
+ cur = f["currency"]
362
+ owner = f.get("owner_routing") or {}
363
+ owner_txt = owner_label(owner)
364
+ where = f.get("resource_id") or f.get("sub_account_id") or ""
365
+ steps = []
366
+ for s in f.get("required_verification_steps", []):
367
+ steps.append(f"<li>{e(s['description'])}" + (f"<pre>{e(s['command'])}</pre>" if s.get("command") else "")
368
+ + "</li>")
369
+ ev = f["exact_evidence"]
370
+ sample = ", ".join(f"source {x['source_id']} row {x['row']}" for x in ev.get("sample_rows", [])[:5])
371
+ billed = f["financials"].get("observed_billed_cost")
372
+ billed_detail = f"<p>Billed cost of matched rows: {money(billed, cur)}</p>" if billed is not None else ""
373
+ return (
374
+ f"<details><summary><span class=\"amt\">{money(f['financials']['observed_cost'], cur)} "
375
+ f"{e(f['financials']['cost_basis'])}</span>"
376
+ f"<strong>{e(f['provider'])}</strong> · {e(where)} · {e(f['billing_period'])} "
377
+ f'<span class="chip fin-{e(fin)}">{e(fin.replace("_", " "))}</span> '
378
+ f'<span class="chip">{e(f["evidence_level"])}</span> '
379
+ f'<span class="small muted">owner: {e(owner_txt)}</span></summary><div>'
380
+ f"<p>{e(f['summary'])}</p>{billed_detail}"
381
+ f'<p class="small"><strong>Evidence:</strong> {ev["matched_rows"]:,} line item(s) matching '
382
+ f'{e(", ".join(ev.get("matched_values", [])[:5]))}; {e(sample)}. Finding <code>{e(f["finding_id"])}</code>.</p>'
383
+ f'<div class="grid2"><div><strong class="small">Unknown from billing data</strong><ul>'
384
+ + "".join(f"<li class=\"small\">{e(x)}</li>" for x in f.get("unknown_information", []))
385
+ + '</ul></div><div><strong class="small">Could be legitimate when</strong><ul>'
386
+ + "".join(f"<li class=\"small\">{e(x)}</li>" for x in f.get("potential_false_positives", []))
387
+ + "</ul></div></div>"
388
+ + (f'<strong class="small">Read-only verification</strong><ol>{"".join(steps)}</ol>' if steps else "")
389
+ + "</div></details>"
390
+ )