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.
- cloudleak/__init__.py +49 -0
- cloudleak/__main__.py +3 -0
- cloudleak/_version.py +1 -0
- cloudleak/analysis.py +199 -0
- cloudleak/cli.py +503 -0
- cloudleak/diff.py +99 -0
- cloudleak/doctor.py +611 -0
- cloudleak/engine.py +487 -0
- cloudleak/errors.py +25 -0
- cloudleak/findings.py +223 -0
- cloudleak/fixtures.py +411 -0
- cloudleak/money.py +78 -0
- cloudleak/providers/__init__.py +19 -0
- cloudleak/providers/aws.py +133 -0
- cloudleak/providers/azure.py +163 -0
- cloudleak/providers/base.py +244 -0
- cloudleak/providers/focus.py +144 -0
- cloudleak/providers/gcp.py +147 -0
- cloudleak/publication.py +171 -0
- cloudleak/py.typed +0 -0
- cloudleak/reconcile.py +334 -0
- cloudleak/redact.py +655 -0
- cloudleak/render/__init__.py +1 -0
- cloudleak/render/formats.py +229 -0
- cloudleak/render/html.py +390 -0
- cloudleak/report.py +138 -0
- cloudleak/rules.py +403 -0
- cloudleak/schemas/__init__.py +1 -0
- cloudleak/schemas/finding.v1.schema.json +122 -0
- cloudleak/schemas/report.v1.schema.json +47 -0
- cloudleak/sources.py +298 -0
- cloudleak/variance.py +426 -0
- cloudleak_cli-0.1.0.dist-info/METADATA +284 -0
- cloudleak_cli-0.1.0.dist-info/RECORD +38 -0
- cloudleak_cli-0.1.0.dist-info/WHEEL +4 -0
- cloudleak_cli-0.1.0.dist-info/entry_points.txt +2 -0
- cloudleak_cli-0.1.0.dist-info/licenses/LICENSE +201 -0
- cloudleak_cli-0.1.0.dist-info/licenses/NOTICE +30 -0
cloudleak/cli.py
ADDED
|
@@ -0,0 +1,503 @@
|
|
|
1
|
+
"""Command-line interface.
|
|
2
|
+
|
|
3
|
+
Exit codes: 0 success · 1 completed, and the result meets the --fail-on policy
|
|
4
|
+
(failed checks, a reconciliation difference, findings) · 2 input cannot be
|
|
5
|
+
processed safely (fail closed) or usage error.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import argparse
|
|
11
|
+
import json
|
|
12
|
+
import math
|
|
13
|
+
import os
|
|
14
|
+
import sys
|
|
15
|
+
import traceback
|
|
16
|
+
from decimal import Decimal
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
from cloudleak._version import __version__
|
|
20
|
+
from cloudleak.errors import EXIT_FINDINGS, EXIT_INPUT, EXIT_OK, CloudLeakError, InputError
|
|
21
|
+
|
|
22
|
+
EPILOG = ("Runs entirely offline. No cloud credentials, no telemetry, no network access.\n"
|
|
23
|
+
"Report a provider schema quirk using synthetic headers: "
|
|
24
|
+
"https://github.com/pranavg21/cloudleak/issues")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
# ---------------------------------------------------------------- helpers
|
|
28
|
+
def _workspace(args, paths, **kw):
|
|
29
|
+
from cloudleak.engine import Workspace
|
|
30
|
+
return Workspace(paths, memory_limit=args.memory_limit, threads=args.threads, temp_dir=args.temp_dir,
|
|
31
|
+
max_decompressed=int(args.max_decompressed_gb * (1 << 30)), **kw)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _kind(path: str) -> str:
|
|
35
|
+
low = path.lower()
|
|
36
|
+
if low.endswith((".sarif", ".sarif.json")):
|
|
37
|
+
return "sarif"
|
|
38
|
+
for ext, kind in ((".html", "html"), (".htm", "html"), (".json", "json"), (".md", "md"),
|
|
39
|
+
(".markdown", "md"), (".csv", "csv"), (".xml", "junit")):
|
|
40
|
+
if low.endswith(ext):
|
|
41
|
+
return kind
|
|
42
|
+
raise InputError(f"cannot tell the output format of {path!r}",
|
|
43
|
+
hint="Use .html, .json, .md, .csv, .sarif or .xml (JUnit, doctor only).")
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _render(kind: str, report: dict) -> str:
|
|
47
|
+
from cloudleak.render import formats
|
|
48
|
+
from cloudleak.report import dumps
|
|
49
|
+
if kind == "html":
|
|
50
|
+
from cloudleak.render.html import render
|
|
51
|
+
return render(report)
|
|
52
|
+
if kind == "json":
|
|
53
|
+
return dumps(report)
|
|
54
|
+
if kind == "md":
|
|
55
|
+
return formats.markdown(report)
|
|
56
|
+
if kind == "csv":
|
|
57
|
+
return formats.findings_csv(report)
|
|
58
|
+
if kind == "sarif":
|
|
59
|
+
return json.dumps(formats.sarif(report), indent=2, sort_keys=True) + "\n"
|
|
60
|
+
if kind == "junit":
|
|
61
|
+
if not report.get("doctor"):
|
|
62
|
+
raise InputError("JUnit output is available for doctor results only")
|
|
63
|
+
return formats.junit(report)
|
|
64
|
+
raise InputError(f"unknown format {kind}")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _emit_outputs(args, report: dict, *workspaces) -> None:
|
|
68
|
+
from cloudleak.publication import publish_reports
|
|
69
|
+
|
|
70
|
+
paths = args.output or []
|
|
71
|
+
inputs = [s.file.path for ws in workspaces for s in ws.sources]
|
|
72
|
+
inputs.extend(m.path for ws in workspaces for m in ws.discovery.manifests)
|
|
73
|
+
if getattr(args, "invoices", None):
|
|
74
|
+
inputs.append(Path(args.invoices))
|
|
75
|
+
|
|
76
|
+
def render(path: str) -> str:
|
|
77
|
+
kind = _kind(path)
|
|
78
|
+
if args.command == "diff" and kind != "json":
|
|
79
|
+
raise InputError("diff writes JSON output only")
|
|
80
|
+
if kind == "junit" and args.command != "doctor":
|
|
81
|
+
raise InputError("JUnit output is available for doctor results only")
|
|
82
|
+
return _render(kind, report)
|
|
83
|
+
|
|
84
|
+
publish_reports(paths, inputs, render)
|
|
85
|
+
for out in paths:
|
|
86
|
+
_say(args, f"wrote {out}")
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _say(args, msg: str) -> None:
|
|
90
|
+
if not getattr(args, "quiet", False):
|
|
91
|
+
print(msg, file=sys.stderr)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _color(args) -> bool:
|
|
95
|
+
return not args.no_color and sys.stdout.isatty() and "NO_COLOR" not in os.environ
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _stdout(args, report: dict, default_text) -> None:
|
|
99
|
+
fmt = getattr(args, "format", "text")
|
|
100
|
+
if fmt == "text":
|
|
101
|
+
if not args.quiet:
|
|
102
|
+
sys.stdout.write(default_text(report))
|
|
103
|
+
else:
|
|
104
|
+
sys.stdout.write(_render(fmt, report))
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
# ---------------------------------------------------------------- commands
|
|
108
|
+
def cmd_doctor(args) -> int:
|
|
109
|
+
from cloudleak import report as rpt
|
|
110
|
+
from cloudleak.doctor import run_doctor
|
|
111
|
+
from cloudleak.render.formats import doctor_text
|
|
112
|
+
with _workspace(args, args.paths, allow_unknown=True) as ws:
|
|
113
|
+
doc = run_doctor(ws)
|
|
114
|
+
report = rpt.build(ws, command="doctor", args={"fail_on": args.fail_on}, doctor=doc)
|
|
115
|
+
_emit_outputs(args, report, ws)
|
|
116
|
+
_stdout(args, report, lambda r: doctor_text(r, verbose=args.verbose, color=_color(args)))
|
|
117
|
+
return _policy(args.fail_on, doc.worst)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _policy(fail_on: str, worst: str, findings: int = 0) -> int:
|
|
121
|
+
if fail_on == "never":
|
|
122
|
+
return EXIT_OK
|
|
123
|
+
if fail_on == "findings":
|
|
124
|
+
return EXIT_FINDINGS if findings or worst == "FAIL" else EXIT_OK
|
|
125
|
+
if fail_on == "warn":
|
|
126
|
+
return EXIT_FINDINGS if worst in ("WARN", "FAIL") else EXIT_OK
|
|
127
|
+
return EXIT_FINDINGS if worst == "FAIL" else EXIT_OK
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def cmd_audit(args) -> int:
|
|
131
|
+
from cloudleak import report as rpt
|
|
132
|
+
from cloudleak import variance as var
|
|
133
|
+
from cloudleak.doctor import run_doctor
|
|
134
|
+
from cloudleak.render.formats import audit_text
|
|
135
|
+
from cloudleak.rules import run_rules
|
|
136
|
+
with _workspace(args, args.paths) as ws:
|
|
137
|
+
doc = run_doctor(ws)
|
|
138
|
+
findings = run_rules(ws, min_cost=Decimal(args.min_cost))
|
|
139
|
+
bridges = None
|
|
140
|
+
if len(var.principal_periods(ws)) >= 2 and not args.no_variance:
|
|
141
|
+
base, cur = var.choose_periods(ws, None, None)
|
|
142
|
+
bridges = var.compute(ws, base, cur)
|
|
143
|
+
findings += var.variance_findings(bridges)
|
|
144
|
+
report = rpt.build(ws, command="audit", args={"min_cost": Decimal(args.min_cost),
|
|
145
|
+
"no_variance": args.no_variance, "fail_on": args.fail_on}, doctor=doc,
|
|
146
|
+
findings=findings, bridges=bridges)
|
|
147
|
+
_emit_outputs(args, report, ws)
|
|
148
|
+
_stdout(args, report, audit_text)
|
|
149
|
+
sig = sum(1 for f in findings if f.evidence_level == "L2")
|
|
150
|
+
return _policy(args.fail_on, doc.worst, sig)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def cmd_variance(args) -> int:
|
|
154
|
+
from cloudleak import report as rpt
|
|
155
|
+
from cloudleak import variance as var
|
|
156
|
+
paths = [args.base_path] + ([args.current_path] if args.current_path else [])
|
|
157
|
+
if args.top < 1:
|
|
158
|
+
raise InputError("--top must be positive")
|
|
159
|
+
with _workspace(args, paths, independent_inputs=bool(args.current_path)) as ws:
|
|
160
|
+
base_ids = ws.source_ids_for(args.base_path)
|
|
161
|
+
cur_ids = ws.source_ids_for(args.current_path) if args.current_path else base_ids
|
|
162
|
+
base, cur = var.choose_periods(ws, args.base, args.current,
|
|
163
|
+
base_ids if args.current_path else None,
|
|
164
|
+
cur_ids if args.current_path else None)
|
|
165
|
+
where = var.comparison_filter(base, cur, base_ids, cur_ids)
|
|
166
|
+
bridges = var.compute(ws, base, cur, top=args.top, base_sources=base_ids, current_sources=cur_ids)
|
|
167
|
+
findings = var.variance_findings(bridges)
|
|
168
|
+
arguments = {"base": base, "current": cur, "base_source_ids": base_ids, "current_source_ids": cur_ids,
|
|
169
|
+
"top": args.top}
|
|
170
|
+
report = rpt.build(ws, command="variance", args=arguments, findings=findings, bridges=bridges, where=where)
|
|
171
|
+
_emit_outputs(args, report, ws)
|
|
172
|
+
_stdout(args, report, lambda r: "\n\n".join(b["narrative"] for b in r["variance"]) + "\n")
|
|
173
|
+
return EXIT_OK
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def cmd_reconcile(args) -> int:
|
|
177
|
+
from dataclasses import asdict
|
|
178
|
+
|
|
179
|
+
from cloudleak import report as rpt
|
|
180
|
+
from cloudleak.reconcile import (
|
|
181
|
+
Expectation,
|
|
182
|
+
load_invoices,
|
|
183
|
+
parse_amount,
|
|
184
|
+
reconcile,
|
|
185
|
+
reconciliation_findings,
|
|
186
|
+
)
|
|
187
|
+
|
|
188
|
+
if args.invoices:
|
|
189
|
+
if any((args.total is not None, args.currency, args.invoice_id, args.period, args.provider,
|
|
190
|
+
args.issuer, args.billing_account)):
|
|
191
|
+
raise InputError("With --invoices, put the invoice totals and scope selectors in the CSV.")
|
|
192
|
+
exps = load_invoices(args.invoices)
|
|
193
|
+
else:
|
|
194
|
+
if args.total is None or not args.currency:
|
|
195
|
+
raise InputError("give --total and --currency (with --invoice-id or --period), or --invoices FILE")
|
|
196
|
+
exps = [Expectation(parse_amount(args.total, "--total"), args.currency, args.invoice_id, args.period,
|
|
197
|
+
args.provider, issuer=args.issuer, billing_account=args.billing_account)]
|
|
198
|
+
tol = parse_amount(args.tolerance, "--tolerance")
|
|
199
|
+
if tol < 0:
|
|
200
|
+
raise InputError("--tolerance cannot be negative")
|
|
201
|
+
with _workspace(args, args.paths) as ws:
|
|
202
|
+
results = reconcile(ws, exps, tol)
|
|
203
|
+
report = rpt.build(ws, command="reconcile", args={"tolerance": tol, "cost_basis": "billed",
|
|
204
|
+
"expectations": [asdict(e) for e in exps]},
|
|
205
|
+
findings=reconciliation_findings(results),
|
|
206
|
+
extra={"reconciliation": [r.to_dict() for r in results]})
|
|
207
|
+
_emit_outputs(args, report, ws)
|
|
208
|
+
|
|
209
|
+
def text(rep):
|
|
210
|
+
lines = []
|
|
211
|
+
for r in rep["reconciliation"]:
|
|
212
|
+
inv = r["invoice"]
|
|
213
|
+
name = inv["invoice_id"] or f"{inv['provider'] or ''} {inv['period']}".strip()
|
|
214
|
+
lines.append(f"{r['status'].upper():<14} {name}: export {r['export_total']} vs invoice "
|
|
215
|
+
f"{inv['total']} {inv['currency']} -> difference {r['difference']} "
|
|
216
|
+
f"(export minus invoice; {r['rows']:,} rows; period {r['period_finality']})")
|
|
217
|
+
for k, v in r["components"].items():
|
|
218
|
+
lines.append(f" {k:<28} {v:>20}")
|
|
219
|
+
for n in r["notes"]:
|
|
220
|
+
lines.append(f" note: {n}")
|
|
221
|
+
return "\n".join(lines) + "\n"
|
|
222
|
+
_stdout(args, report, text)
|
|
223
|
+
return EXIT_FINDINGS if any(r.status in ("difference", "no_rows") for r in results) else EXIT_OK
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def cmd_diff(args) -> int:
|
|
227
|
+
from cloudleak import diff as d
|
|
228
|
+
from cloudleak.report import dumps, generated_at, run_id, tool_info
|
|
229
|
+
with _workspace(args, [args.before]) as before, _workspace(args, [args.after]) as after:
|
|
230
|
+
result = d.diff(before, after)
|
|
231
|
+
arguments = {"fail_on_change": args.fail_on_change}
|
|
232
|
+
report = {"schema_version": "cloudleak.diff.v1", "tool": tool_info(),
|
|
233
|
+
"run": {"command": "diff", "generated_at": generated_at(), "arguments": arguments,
|
|
234
|
+
"report_run_id": run_id(before, "diff", arguments, after=after)},
|
|
235
|
+
"before": [s.to_dict() for s in before.sources], "after": [s.to_dict() for s in after.sources],
|
|
236
|
+
**result}
|
|
237
|
+
_emit_outputs(args, report, before, after)
|
|
238
|
+
if args.format == "json":
|
|
239
|
+
sys.stdout.write(dumps(report))
|
|
240
|
+
elif not args.quiet:
|
|
241
|
+
for s in result["scopes"]:
|
|
242
|
+
if s["status"] == "unchanged":
|
|
243
|
+
continue
|
|
244
|
+
print(f"{s['status'].upper():<9} {s['provider']} {s['billing_period']} {s['currency']} "
|
|
245
|
+
f"({s['cost_basis']}): {s['before_total']} -> {s['after_total']} (delta {s['delta']}; rows "
|
|
246
|
+
f"{s['before_rows']:,} -> {s['after_rows']:,}; finality {s['before_finality']} -> "
|
|
247
|
+
f"{s['after_finality']})")
|
|
248
|
+
for dim in ("by_charge_category", "by_service", "by_account"):
|
|
249
|
+
for change in s[dim][:6]:
|
|
250
|
+
print(f" {dim[3:]} {change['item']}: {change['before']} -> {change['after']} "
|
|
251
|
+
f"({change['delta']})")
|
|
252
|
+
if s.get("note"):
|
|
253
|
+
print(f" note: {s['note']}")
|
|
254
|
+
if not result["changed_scopes"]:
|
|
255
|
+
print("No changes to the compared aggregates or invoice coverage.")
|
|
256
|
+
return EXIT_FINDINGS if result["changed_scopes"] and args.fail_on_change else EXIT_OK
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def cmd_redact(args) -> int:
|
|
260
|
+
from cloudleak.redact import redact
|
|
261
|
+
rep = redact(args.paths, args.output_path, key_file=args.key_file, drop_unclassified=args.drop_unclassified,
|
|
262
|
+
force=args.force, memory_limit=args.memory_limit, temp_dir=args.temp_dir, threads=args.threads,
|
|
263
|
+
max_decompressed=int(args.max_decompressed_gb * (1 << 30)))
|
|
264
|
+
_say(args, f"wrote {rep.output}: {len(rep.files)} file(s), {rep.aliased_values:,} distinct identifiers "
|
|
265
|
+
f"aliased, {rep.scanned_cells:,} cells passed the residual-identifier scan.")
|
|
266
|
+
_say(args, f"key fingerprint {rep.key_fingerprint}. Keep the key private; `cloudleak resolve` needs it.")
|
|
267
|
+
return EXIT_OK
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def cmd_resolve(args) -> int:
|
|
271
|
+
from cloudleak.redact import build_resolver, resolve_text
|
|
272
|
+
table = build_resolver(args.source, args.key_file, memory_limit=args.memory_limit, temp_dir=args.temp_dir,
|
|
273
|
+
threads=args.threads, max_decompressed=int(args.max_decompressed_gb * (1 << 30)))
|
|
274
|
+
if args.input:
|
|
275
|
+
text = Path(args.input).read_text(encoding="utf-8") if args.input != "-" else sys.stdin.read()
|
|
276
|
+
elif args.aliases:
|
|
277
|
+
text = "\n".join(args.aliases) + "\n"
|
|
278
|
+
else:
|
|
279
|
+
raise InputError("give aliases to resolve or --in FILE")
|
|
280
|
+
out, found, missing = resolve_text(text, table)
|
|
281
|
+
sys.stdout.write(out)
|
|
282
|
+
_say(args, f"resolved {found} alias(es)" + (f"; {missing} not found in the given sources" if missing else ""))
|
|
283
|
+
return EXIT_OK if not missing else EXIT_FINDINGS
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def cmd_demo(args) -> int:
|
|
287
|
+
from cloudleak.fixtures import generate
|
|
288
|
+
from cloudleak.publication import staged_demo
|
|
289
|
+
from cloudleak.render.formats import audit_text
|
|
290
|
+
|
|
291
|
+
target = Path(args.directory).expanduser()
|
|
292
|
+
summary = ""
|
|
293
|
+
with staged_demo(target, args.force) as stage:
|
|
294
|
+
generate(stage, scale=args.scale)
|
|
295
|
+
audit = argparse.Namespace(**vars(args))
|
|
296
|
+
audit.paths = [str(stage / "m1"), str(stage / "m2")]
|
|
297
|
+
audit.output = [str(stage / "report.html"), str(stage / "report.json")]
|
|
298
|
+
audit.min_cost, audit.no_variance, audit.fail_on = "1", False, "never"
|
|
299
|
+
audit.quiet, audit.format = True, "text"
|
|
300
|
+
cmd_audit(audit)
|
|
301
|
+
if not args.quiet or args.format != "text":
|
|
302
|
+
report = json.loads((stage / "report.json").read_text(encoding="utf-8"))
|
|
303
|
+
summary = audit_text(report) if args.format == "text" else _render(args.format, report)
|
|
304
|
+
_say(args, f"wrote synthetic exports to {target}/m1 and {target}/m2 and invoices to {target}/invoices.csv")
|
|
305
|
+
sys.stdout.write(summary)
|
|
306
|
+
_say(args, f"\nOpen {target / 'report.html'} for the audit or {target / 'README.md'} for the invoice comparison.")
|
|
307
|
+
return EXIT_OK
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def cmd_checks(args) -> int:
|
|
311
|
+
from cloudleak.doctor import CATALOG
|
|
312
|
+
for c in CATALOG:
|
|
313
|
+
print(f"{c.check_id:<11} {c.category:<13} {c.title}\n{'':<25}{c.description}")
|
|
314
|
+
return EXIT_OK
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def cmd_rules(args) -> int:
|
|
318
|
+
from cloudleak.rules import RULE_PACK_VERSION, RULES, rule_pack_hash
|
|
319
|
+
print(f"rule pack {RULE_PACK_VERSION} ({rule_pack_hash()}); every rule is Level 2 and read-only\n")
|
|
320
|
+
for r in RULES:
|
|
321
|
+
print(f"{r.rule_id} {r.title} [{', '.join(r.providers)}]\n{'':<12}{r.rationale}\n")
|
|
322
|
+
return EXIT_OK
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def cmd_schema(args) -> int:
|
|
326
|
+
from importlib import resources
|
|
327
|
+
name = {"finding": "finding.v1.schema.json", "report": "report.v1.schema.json"}[args.which]
|
|
328
|
+
sys.stdout.write(resources.files("cloudleak.schemas").joinpath(name).read_text(encoding="utf-8"))
|
|
329
|
+
return EXIT_OK
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
# ---------------------------------------------------------------- parser
|
|
333
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
334
|
+
common = argparse.ArgumentParser(add_help=False)
|
|
335
|
+
g = common.add_argument_group("engine")
|
|
336
|
+
g.add_argument("--memory-limit", default=os.environ.get("CLOUDLEAK_MEMORY_LIMIT", "2GB"),
|
|
337
|
+
help="DuckDB managed-buffer limit (default 2GB). Process RSS can be higher.")
|
|
338
|
+
g.add_argument("--threads", type=int, default=None, help="worker threads (default: all cores)")
|
|
339
|
+
g.add_argument("--temp-dir", default=os.environ.get("CLOUDLEAK_TEMP_DIR"),
|
|
340
|
+
help="spill directory; point at an encrypted or RAM-backed path for sensitive data")
|
|
341
|
+
g.add_argument("--max-decompressed-gb", type=float, default=64.0,
|
|
342
|
+
help="refuse .gz inputs that expand beyond this (default 64)")
|
|
343
|
+
g.add_argument("-q", "--quiet", action="store_true", help="no progress or summary on the terminal")
|
|
344
|
+
g.add_argument("--no-color", action="store_true", help="disable colored output (also: NO_COLOR)")
|
|
345
|
+
|
|
346
|
+
p = argparse.ArgumentParser(
|
|
347
|
+
prog="cloudleak",
|
|
348
|
+
description="Offline audit for cloud billing exports (AWS CUR, Azure, GCP, FOCUS): data-quality doctor, "
|
|
349
|
+
"invoice reconciliation, month-over-month variance, evidence-graded findings and fail-closed "
|
|
350
|
+
"redaction.",
|
|
351
|
+
epilog=EPILOG, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
352
|
+
p.add_argument("--version", action="version", version=f"cloudleak {__version__}")
|
|
353
|
+
sub = p.add_subparsers(dest="command", metavar="COMMAND")
|
|
354
|
+
|
|
355
|
+
def out_opt(sp, kinds: str):
|
|
356
|
+
sp.add_argument("-o", "--output", action="append", metavar="FILE",
|
|
357
|
+
help=f"write a report; format from extension ({kinds}); repeatable")
|
|
358
|
+
|
|
359
|
+
sp = sub.add_parser("doctor", parents=[common], help="check exports for completeness, finality and defects",
|
|
360
|
+
description="Deterministic data-quality, finality and FOCUS conformance-gap checks.")
|
|
361
|
+
sp.add_argument("paths", nargs="+", help="export files or directories")
|
|
362
|
+
sp.add_argument("--format", choices=["text", "json", "junit", "sarif", "md"], default="text")
|
|
363
|
+
sp.add_argument("--fail-on", choices=["fail", "warn", "never"], default="fail",
|
|
364
|
+
help="exit 1 when any check reaches this status (default: fail)")
|
|
365
|
+
sp.add_argument("-v", "--verbose", action="store_true", help="also list passing checks")
|
|
366
|
+
out_opt(sp, ".json .xml .sarif .md .html")
|
|
367
|
+
sp.set_defaults(func=cmd_doctor)
|
|
368
|
+
|
|
369
|
+
sp = sub.add_parser("audit", parents=[common], help="full brief: totals, variance, findings, quality",
|
|
370
|
+
description="Totals, month-over-month bridge, Level-2 billing-signature findings and "
|
|
371
|
+
"data-quality results in one report.")
|
|
372
|
+
sp.add_argument("paths", nargs="+")
|
|
373
|
+
sp.add_argument("--format", choices=["text", "json", "md", "sarif"], default="text")
|
|
374
|
+
sp.add_argument("--min-cost", default="1", help="ignore finding groups below this observed cost (default 1)")
|
|
375
|
+
sp.add_argument("--no-variance", action="store_true", help="skip the month-over-month bridge")
|
|
376
|
+
sp.add_argument("--fail-on", choices=["fail", "warn", "findings", "never"], default="fail",
|
|
377
|
+
help="exit 1 on doctor failures (default), warnings, or any Level-2 finding")
|
|
378
|
+
out_opt(sp, ".html .json .md .csv .sarif")
|
|
379
|
+
sp.set_defaults(func=cmd_audit)
|
|
380
|
+
|
|
381
|
+
sp = sub.add_parser("variance", parents=[common], help="explain what changed between two billing periods",
|
|
382
|
+
description="Deterministic month-over-month bridge. Give two exports (BASE CURRENT), or "
|
|
383
|
+
"one path containing at least two billing periods.")
|
|
384
|
+
sp.add_argument("base_path", metavar="BASE")
|
|
385
|
+
sp.add_argument("current_path", metavar="CURRENT", nargs="?")
|
|
386
|
+
sp.add_argument("--base", help="base billing period YYYY-MM")
|
|
387
|
+
sp.add_argument("--current", help="current billing period YYYY-MM")
|
|
388
|
+
sp.add_argument("--top", type=int, default=12)
|
|
389
|
+
sp.add_argument("--format", choices=["text", "json", "md"], default="text")
|
|
390
|
+
out_opt(sp, ".html .json .md .csv")
|
|
391
|
+
sp.set_defaults(func=cmd_variance)
|
|
392
|
+
|
|
393
|
+
sp = sub.add_parser("reconcile", parents=[common], help="compare an export with an invoice total",
|
|
394
|
+
description="Compare billed cost against invoice totals. Exit 0 when the arithmetic "
|
|
395
|
+
"agrees within tolerance (check status and finality), 1 for a difference "
|
|
396
|
+
"or no matching rows, and 2 for invalid or ambiguous input.")
|
|
397
|
+
sp.add_argument("paths", nargs="+")
|
|
398
|
+
sp.add_argument("--total", help="invoice total as a plain decimal")
|
|
399
|
+
sp.add_argument("--currency", help="ISO 4217 currency of the invoice")
|
|
400
|
+
sp.add_argument("--invoice-id")
|
|
401
|
+
sp.add_argument("--period", help="billing period YYYY-MM")
|
|
402
|
+
sp.add_argument("--provider", help="restrict to one normalized service provider")
|
|
403
|
+
sp.add_argument("--issuer", help="restrict to one invoice issuer name")
|
|
404
|
+
sp.add_argument("--billing-account", help="restrict to one billing account ID")
|
|
405
|
+
sp.add_argument("--invoices", help="CSV of invoices: total,currency,invoice_id|period"
|
|
406
|
+
"[,provider,issuer,billing_account,label]")
|
|
407
|
+
sp.add_argument("--tolerance", default="0", help="accepted absolute difference (default 0)")
|
|
408
|
+
sp.add_argument("--format", choices=["text", "json"], default="text")
|
|
409
|
+
out_opt(sp, ".json .html .md .csv")
|
|
410
|
+
sp.set_defaults(func=cmd_reconcile)
|
|
411
|
+
|
|
412
|
+
sp = sub.add_parser("diff", parents=[common], help="what changed between two snapshots of a period",
|
|
413
|
+
description="Compare an earlier and a later delivery of the same billing period.")
|
|
414
|
+
sp.add_argument("before")
|
|
415
|
+
sp.add_argument("after")
|
|
416
|
+
sp.add_argument("--format", choices=["text", "json"], default="text")
|
|
417
|
+
sp.add_argument("--fail-on-change", action="store_true",
|
|
418
|
+
help="exit 1 when compared aggregates or invoice coverage changed")
|
|
419
|
+
out_opt(sp, ".json")
|
|
420
|
+
sp.set_defaults(func=cmd_diff)
|
|
421
|
+
|
|
422
|
+
sp = sub.add_parser("redact", parents=[common], help="pseudonymize exports for sharing (fail-closed)",
|
|
423
|
+
description="Keyed, deterministic pseudonymization with a residual-identifier gate. "
|
|
424
|
+
"Output is a directory, or a .zip when the path ends in .zip.")
|
|
425
|
+
sp.add_argument("paths", nargs="+")
|
|
426
|
+
sp.add_argument("-o", "--output", dest="output_path", required=True, help="output directory or .zip")
|
|
427
|
+
sp.add_argument("--key-file", help="redaction key (default .cloudleak/redaction.key; created if missing)")
|
|
428
|
+
sp.add_argument("--drop-unclassified", action="store_true",
|
|
429
|
+
help="drop columns missing from the registry instead of stopping")
|
|
430
|
+
sp.add_argument("--force", action="store_true", help="replace an existing output")
|
|
431
|
+
sp.set_defaults(func=cmd_redact)
|
|
432
|
+
|
|
433
|
+
sp = sub.add_parser("resolve", parents=[common], help="translate aliases back using the original exports",
|
|
434
|
+
description="Resolve aliases locally. Needs the key and the original exports.")
|
|
435
|
+
sp.add_argument("aliases", nargs="*")
|
|
436
|
+
sp.add_argument("--source", nargs="+", required=True, help="the original (unredacted) exports")
|
|
437
|
+
sp.add_argument("--key-file")
|
|
438
|
+
sp.add_argument("--in", dest="input", help="resolve every alias in this text file ('-' for stdin)")
|
|
439
|
+
sp.set_defaults(func=cmd_resolve)
|
|
440
|
+
|
|
441
|
+
sp = sub.add_parser("demo", parents=[common], help="generate synthetic exports and a sample report",
|
|
442
|
+
description="Write a two-month synthetic AWS/Azure/GCP/FOCUS corpus and audit it.")
|
|
443
|
+
sp.add_argument("directory", nargs="?", default="cloudleak-demo")
|
|
444
|
+
sp.add_argument("--scale", type=int, default=1, help="multiply resources (for benchmarking)")
|
|
445
|
+
sp.add_argument("--force", action="store_true")
|
|
446
|
+
sp.add_argument("--format", default="text", help=argparse.SUPPRESS)
|
|
447
|
+
sp.set_defaults(func=cmd_demo)
|
|
448
|
+
|
|
449
|
+
sub.add_parser("checks", help="list doctor checks").set_defaults(func=cmd_checks)
|
|
450
|
+
sub.add_parser("rules", help="list billing-signature rules").set_defaults(func=cmd_rules)
|
|
451
|
+
sp = sub.add_parser("schema", help="print a JSON schema")
|
|
452
|
+
sp.add_argument("which", choices=["finding", "report"])
|
|
453
|
+
sp.set_defaults(func=cmd_schema)
|
|
454
|
+
return p
|
|
455
|
+
|
|
456
|
+
|
|
457
|
+
def main(argv: list[str] | None = None) -> int:
|
|
458
|
+
parser = build_parser()
|
|
459
|
+
args = parser.parse_args(argv)
|
|
460
|
+
if not getattr(args, "command", None):
|
|
461
|
+
parser.print_help()
|
|
462
|
+
return EXIT_INPUT
|
|
463
|
+
try:
|
|
464
|
+
if hasattr(args, "max_decompressed_gb"):
|
|
465
|
+
budget = args.max_decompressed_gb * (1 << 30)
|
|
466
|
+
if not math.isfinite(budget) or budget < 1:
|
|
467
|
+
raise InputError("--max-decompressed-gb must give a finite budget of at least one byte")
|
|
468
|
+
if getattr(args, "threads", None) is not None and args.threads < 1:
|
|
469
|
+
raise InputError("--threads must be a positive integer")
|
|
470
|
+
return int(args.func(args))
|
|
471
|
+
except CloudLeakError as exc:
|
|
472
|
+
print(f"cloudleak: error: {exc}", file=sys.stderr)
|
|
473
|
+
if exc.hint:
|
|
474
|
+
print(f" hint: {exc.hint}", file=sys.stderr)
|
|
475
|
+
return exc.exit_code
|
|
476
|
+
except OSError as exc:
|
|
477
|
+
where = f" {exc.filename}" if getattr(exc, "filename", None) else ""
|
|
478
|
+
print(f"cloudleak: error: cannot access{where}: {exc.strerror or exc}", file=sys.stderr)
|
|
479
|
+
print(" hint: check the path exists and that you can read the inputs and write the output location.",
|
|
480
|
+
file=sys.stderr)
|
|
481
|
+
return EXIT_INPUT
|
|
482
|
+
except KeyboardInterrupt:
|
|
483
|
+
return 130
|
|
484
|
+
except BrokenPipeError:
|
|
485
|
+
return EXIT_OK
|
|
486
|
+
except Exception as exc:
|
|
487
|
+
import duckdb
|
|
488
|
+
if isinstance(exc, (duckdb.OutOfMemoryException, duckdb.IOException)):
|
|
489
|
+
print(f"cloudleak: error: the query engine ran out of memory or spill space ({str(exc)[:200]})",
|
|
490
|
+
file=sys.stderr)
|
|
491
|
+
print(" hint: raise --memory-limit, or point --temp-dir at a disk with more free space.",
|
|
492
|
+
file=sys.stderr)
|
|
493
|
+
return EXIT_INPUT
|
|
494
|
+
if os.environ.get("CLOUDLEAK_DEBUG"):
|
|
495
|
+
traceback.print_exc()
|
|
496
|
+
print(f"cloudleak: internal error: {type(exc).__name__}: {str(exc)[:300]}", file=sys.stderr)
|
|
497
|
+
print(" This is a bug. Re-run with CLOUDLEAK_DEBUG=1 and report the traceback (no data rows).",
|
|
498
|
+
file=sys.stderr)
|
|
499
|
+
return EXIT_INPUT
|
|
500
|
+
|
|
501
|
+
|
|
502
|
+
if __name__ == "__main__": # pragma: no cover
|
|
503
|
+
raise SystemExit(main())
|
cloudleak/diff.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
"""``cloudleak diff``: what changed between two snapshots of the same billing period.
|
|
2
|
+
|
|
3
|
+
Providers restate open periods: AWS refreshes the CUR daily and posts support
|
|
4
|
+
fees and credits after month end; GCP posts late usage; corrections arrive as
|
|
5
|
+
new rows. The comparison measures aggregate cost changes by charge category, service
|
|
6
|
+
and account, plus changes in row counts and invoice coverage.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from collections import defaultdict
|
|
12
|
+
from decimal import Decimal
|
|
13
|
+
|
|
14
|
+
from cloudleak.analysis import period_statuses
|
|
15
|
+
from cloudleak.engine import Workspace
|
|
16
|
+
from cloudleak.money import ZERO, fmt, money_context
|
|
17
|
+
|
|
18
|
+
KEYS = ("provider", "billing_account_id", "billing_period", "currency", "cost_basis")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _snapshot(ws: Workspace) -> dict:
|
|
22
|
+
rows = ws.rows("""SELECT provider, billing_account_id, billing_period, currency, cost_basis, charge_category,
|
|
23
|
+
COALESCE(service, '(none)') AS service, COALESCE(sub_account_id, '(none)') AS account,
|
|
24
|
+
sum(cost) AS cost, count(*) AS n, count(invoice_id) AS invoiced
|
|
25
|
+
FROM valid GROUP BY ALL""")
|
|
26
|
+
data: dict[tuple, dict] = defaultdict(lambda: {"total": ZERO, "rows": 0, "invoiced": 0,
|
|
27
|
+
"by_category": defaultdict(lambda: ZERO),
|
|
28
|
+
"by_service": defaultdict(lambda: ZERO),
|
|
29
|
+
"by_account": defaultdict(lambda: ZERO)})
|
|
30
|
+
for r in rows:
|
|
31
|
+
d = data[tuple(r[k] for k in KEYS)]
|
|
32
|
+
d["total"] += r["cost"]
|
|
33
|
+
d["rows"] += r["n"]
|
|
34
|
+
d["invoiced"] += r["invoiced"]
|
|
35
|
+
d["by_category"][r["charge_category"]] += r["cost"]
|
|
36
|
+
d["by_service"][r["service"]] += r["cost"]
|
|
37
|
+
d["by_account"][r["account"]] += r["cost"]
|
|
38
|
+
fin = {(s.provider, s.billing_account_id, s.billing_period, s.currency, s.cost_basis): s.finality
|
|
39
|
+
for s in period_statuses(ws)}
|
|
40
|
+
for k, d in data.items():
|
|
41
|
+
d["finality"] = fin.get(k, "unknown")
|
|
42
|
+
return data
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _changes(before: dict, after: dict) -> list[dict]:
|
|
46
|
+
out = []
|
|
47
|
+
for k in sorted(set(before) | set(after)):
|
|
48
|
+
b, a = before.get(k, ZERO), after.get(k, ZERO)
|
|
49
|
+
if a != b:
|
|
50
|
+
out.append({"item": k, "before": fmt(b), "after": fmt(a), "delta": fmt(a - b), "_d": a - b})
|
|
51
|
+
out.sort(key=lambda x: (-abs(x["_d"]), x["item"]))
|
|
52
|
+
for x in out:
|
|
53
|
+
del x["_d"]
|
|
54
|
+
return out
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@money_context
|
|
58
|
+
def diff(before: Workspace, after: Workspace) -> dict:
|
|
59
|
+
b, a = _snapshot(before), _snapshot(after)
|
|
60
|
+
scopes = []
|
|
61
|
+
for key in sorted(set(b) | set(a), key=lambda k: tuple(str(x) for x in k)):
|
|
62
|
+
sb, sa = b.get(key), a.get(key)
|
|
63
|
+
tb = sb["total"] if sb else ZERO
|
|
64
|
+
ta = sa["total"] if sa else ZERO
|
|
65
|
+
changes = {name: _changes(sb[name] if sb else {}, sa[name] if sa else {})
|
|
66
|
+
for name in ("by_category", "by_service", "by_account")}
|
|
67
|
+
if sb is None or sa is None:
|
|
68
|
+
status = "added" if sb is None else "removed"
|
|
69
|
+
else:
|
|
70
|
+
changed = any(changes.values()) or any(sb[k] != sa[k] for k in ("total", "rows", "invoiced", "finality"))
|
|
71
|
+
status = "changed" if changed else "unchanged"
|
|
72
|
+
entry = dict(zip(KEYS, key))
|
|
73
|
+
entry.update({
|
|
74
|
+
"status": status,
|
|
75
|
+
"before_total": fmt(tb), "after_total": fmt(ta), "delta": fmt(ta - tb),
|
|
76
|
+
"before_rows": sb["rows"] if sb else 0, "after_rows": sa["rows"] if sa else 0,
|
|
77
|
+
"before_invoiced_rows": sb["invoiced"] if sb else 0, "after_invoiced_rows": sa["invoiced"] if sa else 0,
|
|
78
|
+
"before_finality": sb["finality"] if sb else None, "after_finality": sa["finality"] if sa else None,
|
|
79
|
+
"by_charge_category": changes["by_category"],
|
|
80
|
+
"by_service": changes["by_service"][:15],
|
|
81
|
+
"by_account": changes["by_account"][:15],
|
|
82
|
+
})
|
|
83
|
+
if sb and sa:
|
|
84
|
+
if sb["finality"] != "finalized" and sa["finality"] == "finalized":
|
|
85
|
+
entry["note"] = "The later snapshot carries evidence of a finalized invoice for this scope."
|
|
86
|
+
elif sb["invoiced"] != sa["invoiced"]:
|
|
87
|
+
entry["note"] = (f"Rows with invoice identifiers changed from {sb['invoiced']} of {sb['rows']} "
|
|
88
|
+
f"to {sa['invoiced']} of {sa['rows']}.")
|
|
89
|
+
scopes.append(entry)
|
|
90
|
+
changed = [s for s in scopes if s["status"] != "unchanged"]
|
|
91
|
+
net: dict[tuple, Decimal] = defaultdict(lambda: ZERO)
|
|
92
|
+
for s in scopes:
|
|
93
|
+
net[(s["currency"], s["cost_basis"])] += Decimal(s["delta"])
|
|
94
|
+
return {
|
|
95
|
+
"scopes": scopes,
|
|
96
|
+
"changed_scopes": len(changed),
|
|
97
|
+
"net_delta": [{"currency": c, "cost_basis": b, "delta": fmt(v)} for (c, b), v in
|
|
98
|
+
sorted(net.items(), key=lambda kv: (str(kv[0][0]), kv[0][1]))],
|
|
99
|
+
}
|