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/engine.py
ADDED
|
@@ -0,0 +1,487 @@
|
|
|
1
|
+
"""Zone 2 of the trust boundary: an embedded, sandboxed DuckDB workspace.
|
|
2
|
+
|
|
3
|
+
The connection is locked down before any file is read:
|
|
4
|
+
|
|
5
|
+
* extension auto-install and auto-load are off (no network fetches),
|
|
6
|
+
* file access is restricted to the input directories and the spill directory,
|
|
7
|
+
* DuckDB limits its managed buffers and spills eligible queries to a temporary directory,
|
|
8
|
+
* the session time zone is UTC, so no laptop time zone shifts a period,
|
|
9
|
+
* configuration is locked once loading finishes.
|
|
10
|
+
|
|
11
|
+
Every source column is loaded as VARCHAR. Monetary columns are parsed with
|
|
12
|
+
an explicit DECIMAL cast; a value that does not parse is counted and
|
|
13
|
+
reported, never coerced to zero or dropped.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import csv
|
|
19
|
+
import gzip
|
|
20
|
+
import io
|
|
21
|
+
import os
|
|
22
|
+
import tempfile
|
|
23
|
+
from contextlib import ExitStack
|
|
24
|
+
from dataclasses import dataclass, field
|
|
25
|
+
from pathlib import Path
|
|
26
|
+
from typing import Any
|
|
27
|
+
|
|
28
|
+
import duckdb
|
|
29
|
+
|
|
30
|
+
from cloudleak.errors import InputError
|
|
31
|
+
from cloudleak.money import SQL_MONEY
|
|
32
|
+
from cloudleak.providers import ADAPTERS, detect
|
|
33
|
+
from cloudleak.providers import azure as azure_adapter
|
|
34
|
+
from cloudleak.providers import gcp as gcp_adapter
|
|
35
|
+
from cloudleak.providers.base import CANONICAL_TYPES, Columns, Mapping, norm, quote_ident, sql_str
|
|
36
|
+
from cloudleak.sources import Discovery, SourceFile, discover
|
|
37
|
+
|
|
38
|
+
_RESOURCE_ERRORS = (duckdb.OutOfMemoryException, duckdb.PermissionException, duckdb.IOException)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _resource_error(exc: duckdb.Error) -> InputError:
|
|
42
|
+
reason = str(exc).splitlines()[0][:400]
|
|
43
|
+
if isinstance(exc, duckdb.OutOfMemoryException):
|
|
44
|
+
return InputError(reason, hint="Increase --memory-limit or reduce --threads and ensure --temp-dir has space.")
|
|
45
|
+
return InputError(reason, hint="Check file access, permissions and space in --temp-dir.")
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
MACROS = [
|
|
49
|
+
gcp_adapter.CREDIT_JSON_MACRO,
|
|
50
|
+
# Place the decimal point in a bounded significant-digit string. This
|
|
51
|
+
# handles a large mantissa with a negative exponent without overflowing
|
|
52
|
+
# an intermediate DECIMAL cast or rounding through a floating type.
|
|
53
|
+
"""CREATE MACRO cl_shift_decimal(digits, power) AS CASE
|
|
54
|
+
WHEN digits = '' THEN '0'
|
|
55
|
+
WHEN power >= -12 AND length(digits) + power <= 26 THEN
|
|
56
|
+
CASE WHEN power >= 0 THEN digits || repeat('0', power)
|
|
57
|
+
WHEN length(digits) + power <= 0
|
|
58
|
+
THEN '0.' || repeat('0', -(length(digits) + power)) || digits
|
|
59
|
+
ELSE left(digits, length(digits) + power) || '.' || right(digits, -power) END END""",
|
|
60
|
+
"""CREATE MACRO cl_scientific_digits(digits, power) AS
|
|
61
|
+
cl_shift_decimal(trim(digits, '0'), power + length(digits) - length(rtrim(digits, '0')))""",
|
|
62
|
+
"""CREATE MACRO cl_scientific_parts(mantissa, exponent) AS
|
|
63
|
+
cl_scientific_digits(replace(mantissa, '.', ''), exponent - length(split_part(mantissa, '.', 2)))""",
|
|
64
|
+
"""CREATE MACRO cl_scientific_money(x) AS
|
|
65
|
+
(CASE WHEN left(x, 1) = '-' THEN '-' ELSE '' END) ||
|
|
66
|
+
cl_scientific_parts(ltrim(split_part(lower(x), 'e', 1), '+-'), try_cast(split_part(lower(x), 'e', 2)
|
|
67
|
+
AS INTEGER)::BIGINT)""",
|
|
68
|
+
# DuckDB's DECIMAL cast rounds excess scale. Only cast when no nonzero
|
|
69
|
+
# digits will be discarded. Expand scientific notation exactly first.
|
|
70
|
+
f"""CREATE OR REPLACE MACRO cl_money(x) AS CASE
|
|
71
|
+
WHEN regexp_full_match(x, '[+-]?([0-9]+([.][0-9]{{0,12}}0*)?|[.][0-9]{{1,12}}0*)')
|
|
72
|
+
THEN TRY_CAST(x AS {SQL_MONEY})
|
|
73
|
+
WHEN regexp_full_match(x, '[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)[eE][+-]?[0-9]+')
|
|
74
|
+
THEN TRY_CAST(cl_scientific_money(x) AS {SQL_MONEY}) END""",
|
|
75
|
+
# Timestamps: ISO 8601 (with or without zone), BigQuery's '... UTC',
|
|
76
|
+
# Azure's MM/DD/YYYY, and compact YYYYMMDD. Zoned values become UTC.
|
|
77
|
+
"""CREATE OR REPLACE MACRO cl_ts(x) AS COALESCE(
|
|
78
|
+
CAST(TRY_CAST(x AS TIMESTAMPTZ) AS TIMESTAMP),
|
|
79
|
+
TRY_STRPTIME(x, '%m/%d/%Y'),
|
|
80
|
+
TRY_STRPTIME(x, '%m/%d/%Y %H:%M:%S'),
|
|
81
|
+
TRY_STRPTIME(x, '%m/%d/%Y %I:%M:%S %p'),
|
|
82
|
+
TRY_STRPTIME(x, '%Y%m%d'),
|
|
83
|
+
TRY_STRPTIME(x, '%Y%m%dT%H%M%S.%gZ'),
|
|
84
|
+
TRY_STRPTIME(x, '%Y%m%dT%H%M%SZ'))""",
|
|
85
|
+
]
|
|
86
|
+
|
|
87
|
+
SERVICE_CATEGORY_SQL = """CASE
|
|
88
|
+
WHEN t LIKE '%support%' AND (t LIKE '%awssupport%' OR t LIKE '%support plan%' OR t LIKE 'support%')
|
|
89
|
+
THEN 'support'
|
|
90
|
+
WHEN t LIKE '%bedrock%' OR t LIKE '%sagemaker%' OR t LIKE '%openai%' OR t LIKE '%vertex ai%'
|
|
91
|
+
OR t LIKE '%cognitive%' OR t LIKE '%machine learning%' OR t LIKE '%gemini%' OR t LIKE '%claude%'
|
|
92
|
+
THEN 'ai_ml'
|
|
93
|
+
WHEN t LIKE '%cloudwatch%' OR t LIKE '%log analytics%' OR t LIKE '%logging%' OR t LIKE '%monitor%'
|
|
94
|
+
OR t LIKE '%insights%' OR t LIKE '%x-ray%' OR t LIKE '%log ingest%' THEN 'observability'
|
|
95
|
+
WHEN t LIKE '%natgateway%' OR t LIKE '%nat gateway%' OR t LIKE '%cloud nat%' OR t LIKE '%datatransfer%'
|
|
96
|
+
OR t LIKE '%data transfer%' OR t LIKE '%bandwidth%' OR t LIKE '%egress%' OR t LIKE '%network%'
|
|
97
|
+
OR t LIKE '%vpc%' OR t LIKE '%load balanc%' OR t LIKE '%elb%' OR t LIKE '%cloudfront%'
|
|
98
|
+
OR t LIKE '%cdn%' OR t LIKE '%dns%' OR t LIKE '%route53%' OR t LIKE '%ipv4%' OR t LIKE '%ip address%'
|
|
99
|
+
THEN 'network'
|
|
100
|
+
WHEN t LIKE '%rds%' OR t LIKE '%dynamodb%' OR t LIKE '%sql%' OR t LIKE '%cosmos%' OR t LIKE '%spanner%'
|
|
101
|
+
OR t LIKE '%bigtable%' OR t LIKE '%aurora%' OR t LIKE '%elasticache%' OR t LIKE '%database%'
|
|
102
|
+
OR t LIKE '%redis%' THEN 'database'
|
|
103
|
+
WHEN t LIKE '%bigquery%' OR t LIKE '%athena%' OR t LIKE '%glue%' OR t LIKE '%emr%' OR t LIKE '%synapse%'
|
|
104
|
+
OR t LIKE '%databricks%' OR t LIKE '%redshift%' OR t LIKE '%kinesis%' OR t LIKE '%data factory%'
|
|
105
|
+
OR t LIKE '%dataflow%' THEN 'analytics'
|
|
106
|
+
WHEN t LIKE '%snapshot%' OR t LIKE '%storage%' OR t LIKE '%ebs:%' OR t LIKE '%disk%' OR t LIKE '%s3%'
|
|
107
|
+
OR t LIKE '%blob%' OR t LIKE '%glacier%' OR t LIKE '%backup%' OR t LIKE '%efs%' OR t LIKE '%fsx%'
|
|
108
|
+
OR t LIKE '%filestore%' OR t LIKE '%timedstorage%' THEN 'storage'
|
|
109
|
+
WHEN t LIKE '%boxusage%' OR t LIKE '%virtual machine%' OR t LIKE '%compute%' OR t LIKE '%instance%'
|
|
110
|
+
OR t LIKE '%lambda%' OR t LIKE '%function%' OR t LIKE '%fargate%' OR t LIKE '%container%'
|
|
111
|
+
OR t LIKE '%kubernetes%' OR t LIKE '%eks%' OR t LIKE '%aks%' OR t LIKE '%gke%' OR t LIKE '%ec2%'
|
|
112
|
+
THEN 'compute'
|
|
113
|
+
ELSE 'other' END"""
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
@dataclass
|
|
117
|
+
class LoadedSource:
|
|
118
|
+
file: SourceFile
|
|
119
|
+
table: str
|
|
120
|
+
rows: int
|
|
121
|
+
columns: list[str]
|
|
122
|
+
detected: str | None
|
|
123
|
+
confidence: float
|
|
124
|
+
mapping: Mapping | None
|
|
125
|
+
basis_evidence: str | None = None
|
|
126
|
+
header_issues: list[str] = field(default_factory=list)
|
|
127
|
+
|
|
128
|
+
@property
|
|
129
|
+
def provider(self) -> str | None:
|
|
130
|
+
return self.mapping.provider if self.mapping else None
|
|
131
|
+
|
|
132
|
+
def to_dict(self, *, redact_paths: bool = False) -> dict:
|
|
133
|
+
m = self.mapping
|
|
134
|
+
return {
|
|
135
|
+
**self.file.to_dict(redact_paths=redact_paths),
|
|
136
|
+
"rows": self.rows,
|
|
137
|
+
"columns": len(self.columns),
|
|
138
|
+
"adapter": self.detected,
|
|
139
|
+
"dataset": m.dataset if m else None,
|
|
140
|
+
"cost_basis": m.cost_basis if m else None,
|
|
141
|
+
"focus_version": m.focus_version if m else None,
|
|
142
|
+
"focus_version_evidence": "column-derived lower bound" if m and m.focus_version else None,
|
|
143
|
+
"detection_score": self.confidence,
|
|
144
|
+
"basis_evidence": self.basis_evidence,
|
|
145
|
+
"capabilities": dict(sorted((m.capabilities if m else {}).items())),
|
|
146
|
+
"notes": list(m.notes) if m else [],
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _read_header(src: SourceFile) -> tuple[list[str], str]:
|
|
151
|
+
"""Parse the header row in Python and pick the delimiter that splits it into the most fields.
|
|
152
|
+
|
|
153
|
+
DuckDB's dialect sniffer is deliberately not used: on a malformed file it can
|
|
154
|
+
choose a dialect under which every row parses "successfully" into the wrong
|
|
155
|
+
columns. CloudLeak declares the dialect and the columns, so a ragged row is
|
|
156
|
+
an error with a line number instead.
|
|
157
|
+
"""
|
|
158
|
+
opener = gzip.open if src.fmt == "csv.gz" else open
|
|
159
|
+
with opener(src.path, "rb") as fh: # type: ignore[operator]
|
|
160
|
+
head = fh.read(1 << 20)
|
|
161
|
+
enc = "utf-16" if src.encoding == "utf-16" else "utf-8-sig"
|
|
162
|
+
try:
|
|
163
|
+
text = head.decode(enc)
|
|
164
|
+
except UnicodeDecodeError:
|
|
165
|
+
cut = head.rfind(b"\n")
|
|
166
|
+
try:
|
|
167
|
+
text = head[: cut if cut > 0 else len(head)].decode(enc)
|
|
168
|
+
except UnicodeDecodeError as exc:
|
|
169
|
+
raise InputError(f"{src.display_name}: not UTF-8 or UTF-16 text ({exc.reason})",
|
|
170
|
+
hint="Re-export the file as UTF-8 CSV.") from exc
|
|
171
|
+
if "\x00" in text:
|
|
172
|
+
raise InputError(f"{src.display_name}: contains NUL bytes; not a text CSV export")
|
|
173
|
+
first_line = text.split("\n", 1)[0].rstrip("\r")
|
|
174
|
+
best: tuple[list[str], str] = ([], ",")
|
|
175
|
+
for delim in (",", ";", "\t", "|"):
|
|
176
|
+
fields = next(csv.reader(io.StringIO(first_line), delimiter=delim), [])
|
|
177
|
+
if len(fields) > len(best[0]):
|
|
178
|
+
best = (fields, delim)
|
|
179
|
+
return best
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def _parquet_projection(description: list) -> str:
|
|
183
|
+
"""Expose known nested GCP fields and serialize repeated records without rounding amounts."""
|
|
184
|
+
names = {norm(name) for name, *_ in description}
|
|
185
|
+
gcp = "cost" in names and bool({"service", "service_description", "sku", "sku_description"} & names)
|
|
186
|
+
exprs = []
|
|
187
|
+
for name, typ, *_ in description:
|
|
188
|
+
key, q = norm(name), quote_ident(name)
|
|
189
|
+
expr = q
|
|
190
|
+
if gcp and typ.id == "struct" and key in gcp_adapter.STRUCT_FIELDS:
|
|
191
|
+
for child, _ in typ.children:
|
|
192
|
+
if child not in gcp_adapter.STRUCT_FIELDS[key]:
|
|
193
|
+
continue
|
|
194
|
+
alias = f"{key}.{child}"
|
|
195
|
+
if norm(alias) in names:
|
|
196
|
+
raise InputError(f"Ambiguous GCP field {alias} in both nested and flat columns")
|
|
197
|
+
names.add(norm(alias))
|
|
198
|
+
field = f"struct_extract({q}, {sql_str(child)})"
|
|
199
|
+
exprs.append(f"CAST({field} AS VARCHAR) AS {quote_ident(alias)}")
|
|
200
|
+
if typ.id in {"map", "struct", "list", "array"}:
|
|
201
|
+
expr = f"to_json({expr})"
|
|
202
|
+
exprs.append(f"CAST({expr} AS VARCHAR) AS {q}")
|
|
203
|
+
return ", ".join(exprs)
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _parquet_money_precision(description: list, mapping: Mapping) -> None:
|
|
207
|
+
"""Preserve the source precision of amounts used in a billed comparison."""
|
|
208
|
+
limits = {"float": 2**17, "double": 2**46}
|
|
209
|
+
coarse, approximate = [], []
|
|
210
|
+
approximate_secondary = False
|
|
211
|
+
for name, typ, *_ in description:
|
|
212
|
+
ref = quote_ident(name)
|
|
213
|
+
if typ.id in limits and (ref in mapping.effective_cost or ref in mapping.list_cost):
|
|
214
|
+
approximate_secondary = True
|
|
215
|
+
if ref not in mapping.cost:
|
|
216
|
+
continue
|
|
217
|
+
if typ.id in limits:
|
|
218
|
+
coarse.append(f"abs(try_cast({ref} AS DOUBLE)) >= {limits[typ.id]}")
|
|
219
|
+
approximate.append(f"{ref} IS NOT NULL")
|
|
220
|
+
elif norm(name) == "credits" and typ.id == "list" and typ.children[0][1].id == "struct":
|
|
221
|
+
for child, amount_type in typ.children[0][1].children:
|
|
222
|
+
if child == "amount" and amount_type.id in limits:
|
|
223
|
+
values = f"json_extract_string({ref}, '$[*].amount')"
|
|
224
|
+
coarse.append(f"list_max(list_transform({values}, lambda v: abs(try_cast(v AS DOUBLE)))) "
|
|
225
|
+
f">= {limits[amount_type.id]}")
|
|
226
|
+
approximate.append(f"len({values}) > 0")
|
|
227
|
+
if approximate:
|
|
228
|
+
mapping.billed_precision = (f"CASE WHEN {' OR '.join(coarse)} THEN 'cent_resolution_lost' "
|
|
229
|
+
f"WHEN {' OR '.join(approximate)} THEN 'binary_float' ELSE 'decimal' END")
|
|
230
|
+
mapping.notes.append("Parquet stores a billed amount or credit as binary floating point. "
|
|
231
|
+
"Decimal totals compare the stored values and can differ from producer amounts.")
|
|
232
|
+
if approximate_secondary:
|
|
233
|
+
mapping.notes.append("A Parquet input to effective or list cost uses binary floating-point precision.")
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
class Workspace:
|
|
237
|
+
"""Load, normalize and query billing exports inside a locked DuckDB session."""
|
|
238
|
+
|
|
239
|
+
def __init__(
|
|
240
|
+
self,
|
|
241
|
+
paths: list[str | os.PathLike],
|
|
242
|
+
*,
|
|
243
|
+
memory_limit: str = "2GB",
|
|
244
|
+
threads: int | None = None,
|
|
245
|
+
temp_dir: str | None = None,
|
|
246
|
+
allow_unknown: bool = False,
|
|
247
|
+
independent_inputs: bool = False,
|
|
248
|
+
max_decompressed: int = 64 << 30,
|
|
249
|
+
):
|
|
250
|
+
self.discovery: Discovery = discover(paths, max_decompressed=max_decompressed)
|
|
251
|
+
if threads is not None and threads < 1:
|
|
252
|
+
raise InputError("--threads must be a positive integer")
|
|
253
|
+
with ExitStack() as cleanup:
|
|
254
|
+
self._tmp = tempfile.TemporaryDirectory(prefix="cloudleak-", dir=temp_dir)
|
|
255
|
+
cleanup.callback(self._tmp.cleanup)
|
|
256
|
+
spill = Path(self._tmp.name)
|
|
257
|
+
config: dict[str, Any] = {
|
|
258
|
+
"autoinstall_known_extensions": False,
|
|
259
|
+
"autoload_known_extensions": False,
|
|
260
|
+
"memory_limit": memory_limit,
|
|
261
|
+
"temp_directory": str(spill),
|
|
262
|
+
}
|
|
263
|
+
if threads is not None:
|
|
264
|
+
config["threads"] = threads
|
|
265
|
+
try:
|
|
266
|
+
self.con = duckdb.connect(":memory:", config=config)
|
|
267
|
+
except _RESOURCE_ERRORS as exc:
|
|
268
|
+
raise _resource_error(exc) from exc
|
|
269
|
+
except duckdb.Error as exc:
|
|
270
|
+
raise InputError(f"invalid DuckDB configuration: {exc}",
|
|
271
|
+
hint="Check --memory-limit (for example 2GB) and --threads.") from exc
|
|
272
|
+
cleanup.callback(self.con.close)
|
|
273
|
+
try:
|
|
274
|
+
self._initialize(spill, allow_unknown, paths if independent_inputs else [])
|
|
275
|
+
except _RESOURCE_ERRORS as exc:
|
|
276
|
+
raise _resource_error(exc) from exc
|
|
277
|
+
cleanup.pop_all()
|
|
278
|
+
|
|
279
|
+
def _initialize(self, spill: Path, allow_unknown: bool, independent_paths: list[str | os.PathLike]) -> None:
|
|
280
|
+
allowed = sorted({str(r) for r in self.discovery.roots} | {str(spill)})
|
|
281
|
+
self.con.execute(f"SET allowed_directories = [{', '.join(sql_str(a) for a in allowed)}]")
|
|
282
|
+
self.con.execute("SET enable_external_access = false")
|
|
283
|
+
self.con.execute("SET TimeZone = 'UTC'")
|
|
284
|
+
for macro in MACROS:
|
|
285
|
+
self.con.execute(macro)
|
|
286
|
+
self.sources: list[LoadedSource] = []
|
|
287
|
+
for src in self.discovery.files:
|
|
288
|
+
self.sources.append(self._load(src))
|
|
289
|
+
unknown = [s for s in self.sources if s.mapping is None]
|
|
290
|
+
if unknown and not allow_unknown:
|
|
291
|
+
names = ", ".join(s.file.display_name for s in unknown)
|
|
292
|
+
raise InputError(
|
|
293
|
+
f"could not recognize the billing format of: {names}",
|
|
294
|
+
hint="Run `cloudleak doctor` for details. Supported: AWS CUR (legacy and 2.0), "
|
|
295
|
+
"Azure cost exports (EA/MCA, actual and amortized), GCP billing exports, FOCUS 1.0-1.4.",
|
|
296
|
+
)
|
|
297
|
+
self._build_canonical()
|
|
298
|
+
if independent_paths:
|
|
299
|
+
for path in independent_paths:
|
|
300
|
+
self._check_dataset_overlap(self.source_ids_for(path))
|
|
301
|
+
else:
|
|
302
|
+
self._check_dataset_overlap([s.file.source_id for s in self.recognized])
|
|
303
|
+
self.con.execute("SET lock_configuration = true")
|
|
304
|
+
|
|
305
|
+
# -- loading -----------------------------------------------------------
|
|
306
|
+
def _load(self, src: SourceFile) -> LoadedSource:
|
|
307
|
+
table = f"raw_{src.source_id:04d}"
|
|
308
|
+
path = sql_str(str(src.path))
|
|
309
|
+
issues: list[str] = []
|
|
310
|
+
try:
|
|
311
|
+
if src.fmt == "parquet":
|
|
312
|
+
relation = self.con.sql(f"SELECT * FROM read_parquet({path}) LIMIT 0")
|
|
313
|
+
description = list(zip(relation.columns, relation.types))
|
|
314
|
+
select = _parquet_projection(description)
|
|
315
|
+
self.con.execute(
|
|
316
|
+
f"CREATE TABLE {table} AS SELECT row_number() OVER () AS __cl_row, {select} "
|
|
317
|
+
f"FROM read_parquet({path})"
|
|
318
|
+
)
|
|
319
|
+
else:
|
|
320
|
+
header, delim = _read_header(src)
|
|
321
|
+
blank = [i + 1 for i, h in enumerate(header) if not h.strip()]
|
|
322
|
+
if blank:
|
|
323
|
+
raise InputError(f"{src.display_name}: header has blank column name(s) at position {blank}")
|
|
324
|
+
folded = [h.casefold() for h in header]
|
|
325
|
+
dupes = sorted({h for h in header if folded.count(h.casefold()) > 1})
|
|
326
|
+
if dupes:
|
|
327
|
+
raise InputError(
|
|
328
|
+
f"{src.display_name}: duplicate column names {dupes[:5]}; the cost column is ambiguous"
|
|
329
|
+
)
|
|
330
|
+
enc = sql_str("utf-16" if src.encoding == "utf-16" else "utf-8")
|
|
331
|
+
columns = ", ".join(f"{sql_str(h)}: 'VARCHAR'" for h in header)
|
|
332
|
+
self.con.execute(
|
|
333
|
+
f"CREATE TABLE {table} AS SELECT row_number() OVER () AS __cl_row, * FROM read_csv("
|
|
334
|
+
f"{path}, auto_detect=false, header=true, delim={sql_str(delim)}, quote='\"', escape='\"', "
|
|
335
|
+
f"columns={{{columns}}}, strict_mode=true, null_padding=false, encoding={enc}, "
|
|
336
|
+
f"ignore_errors=false)"
|
|
337
|
+
)
|
|
338
|
+
except _RESOURCE_ERRORS:
|
|
339
|
+
raise
|
|
340
|
+
except duckdb.Error as exc:
|
|
341
|
+
msg = str(exc).splitlines()[0][:400]
|
|
342
|
+
raise InputError(
|
|
343
|
+
f"{src.display_name}: could not be read completely ({msg})",
|
|
344
|
+
hint="CloudLeak never skips malformed rows. Re-export the file or fix the reported line.",
|
|
345
|
+
) from exc
|
|
346
|
+
names = [r[0] for r in self.con.execute(f"DESCRIBE {table}").fetchall()]
|
|
347
|
+
rows = self.con.execute(f"SELECT count(*) FROM {table}").fetchone()[0]
|
|
348
|
+
cols = Columns.from_names(names)
|
|
349
|
+
if cols.collisions:
|
|
350
|
+
issues.extend(f"columns {a!r} and {b!r} normalize to the same name" for a, b in cols.collisions)
|
|
351
|
+
name, score = detect(cols)
|
|
352
|
+
mapping = None
|
|
353
|
+
basis_evidence = None
|
|
354
|
+
if name == "azure":
|
|
355
|
+
root = self._root_of(src.path)
|
|
356
|
+
# Include the basename of the discovery root: explicit file arguments
|
|
357
|
+
# have their parent as root. Do not use unrelated absolute ancestors.
|
|
358
|
+
hint = azure_adapter.basis_from_name(str(Path(root.name) / src.path.relative_to(root)))
|
|
359
|
+
q = azure_adapter.infer_basis_sql(table, cols)
|
|
360
|
+
data_hint = self.con.execute(q).fetchone()[0] if q else None
|
|
361
|
+
if "conflict" in (hint, data_hint) or (hint and data_hint and hint != data_hint):
|
|
362
|
+
hint, basis_evidence = None, "conflicting file name or charge type evidence"
|
|
363
|
+
elif hint:
|
|
364
|
+
basis_evidence = "file or folder name"
|
|
365
|
+
elif data_hint:
|
|
366
|
+
hint, basis_evidence = data_hint, "charge types in the data"
|
|
367
|
+
mapping = azure_adapter.build(cols, basis_hint=hint)
|
|
368
|
+
elif name is not None:
|
|
369
|
+
mapping = ADAPTERS[name].build(cols)
|
|
370
|
+
if mapping is not None and src.fmt == "parquet":
|
|
371
|
+
_parquet_money_precision(description, mapping)
|
|
372
|
+
return LoadedSource(src, table, rows, cols.original, name, score, mapping, basis_evidence, issues)
|
|
373
|
+
|
|
374
|
+
def _root_of(self, path: Path) -> Path:
|
|
375
|
+
for root in sorted(self.discovery.roots, key=lambda r: len(str(r)), reverse=True):
|
|
376
|
+
if root == path or root in path.parents:
|
|
377
|
+
return root
|
|
378
|
+
return path.parent
|
|
379
|
+
|
|
380
|
+
def source_ids_for(self, path: str | os.PathLike) -> list[int]:
|
|
381
|
+
resolved = Path(path).expanduser().resolve()
|
|
382
|
+
return [s.file.source_id for s in self.sources if s.file.path == resolved or resolved in s.file.path.parents]
|
|
383
|
+
|
|
384
|
+
def _check_dataset_overlap(self, source_ids: list[int]) -> None:
|
|
385
|
+
"""A detailed GCP export, native bill, or FOCUS export may describe the same charges."""
|
|
386
|
+
adapters = {s.mapping.dataset for s in self.recognized if s.file.source_id in source_ids}
|
|
387
|
+
gcp_pair = {"gcp_standard", "gcp_detailed"} <= adapters
|
|
388
|
+
focus_pair = any(d.startswith("focus_") for d in adapters) and any(not d.startswith("focus_") for d in adapters)
|
|
389
|
+
if not (gcp_pair or focus_pair):
|
|
390
|
+
return
|
|
391
|
+
overlap = self.rows("""
|
|
392
|
+
WITH scopes AS (
|
|
393
|
+
SELECT DISTINCT provider, dataset, billing_account_id, billing_period_start
|
|
394
|
+
FROM li WHERE source_id IN (SELECT unnest(?)) AND cost_basis = 'billed'
|
|
395
|
+
)
|
|
396
|
+
SELECT a.dataset AS left_view, b.dataset AS right_view
|
|
397
|
+
FROM scopes a JOIN scopes b ON a.dataset < b.dataset
|
|
398
|
+
AND (a.provider = b.provider OR a.provider = 'focus' OR b.provider = 'focus')
|
|
399
|
+
AND (a.billing_account_id = b.billing_account_id OR a.billing_account_id IS NULL
|
|
400
|
+
OR b.billing_account_id IS NULL)
|
|
401
|
+
AND (a.billing_period_start = b.billing_period_start OR a.billing_period_start IS NULL
|
|
402
|
+
OR b.billing_period_start IS NULL)
|
|
403
|
+
WHERE (a.dataset = 'gcp_detailed' AND b.dataset = 'gcp_standard')
|
|
404
|
+
OR (starts_with(a.dataset, 'focus_') <> starts_with(b.dataset, 'focus_'))
|
|
405
|
+
LIMIT 1
|
|
406
|
+
""", [source_ids])
|
|
407
|
+
if overlap:
|
|
408
|
+
row = overlap[0]
|
|
409
|
+
raise InputError(f"Overlapping billing scopes in {row['left_view']} and {row['right_view']}",
|
|
410
|
+
hint="Supply one export view per provider, billing account and invoice month.")
|
|
411
|
+
|
|
412
|
+
def _build_canonical(self) -> None:
|
|
413
|
+
selects = []
|
|
414
|
+
for s in self.sources:
|
|
415
|
+
if s.mapping is None:
|
|
416
|
+
continue
|
|
417
|
+
inner = s.mapping.select_sql(s.table, s.file.source_id)
|
|
418
|
+
casts = ", ".join(f"CAST({quote_ident(k)} AS {t}) AS {quote_ident(k)}"
|
|
419
|
+
for k, t in CANONICAL_TYPES.items())
|
|
420
|
+
selects.append(f"SELECT {casts} FROM ({inner})")
|
|
421
|
+
if not selects:
|
|
422
|
+
cols = ", ".join(f"CAST(NULL AS {t}) AS {quote_ident(k)}" for k, t in CANONICAL_TYPES.items())
|
|
423
|
+
self.con.execute(f"CREATE TABLE li AS SELECT {cols} WHERE false")
|
|
424
|
+
else:
|
|
425
|
+
try:
|
|
426
|
+
self.con.execute("CREATE TABLE li AS " + "\nUNION ALL\n".join(selects))
|
|
427
|
+
except _RESOURCE_ERRORS:
|
|
428
|
+
raise
|
|
429
|
+
except duckdb.Error as exc:
|
|
430
|
+
raise InputError(f"normalization failed: {str(exc).splitlines()[0][:400]}") from exc
|
|
431
|
+
aws = {s.file.source_id: s.mapping for s in self.recognized if s.detected == "aws"}
|
|
432
|
+
if aws:
|
|
433
|
+
coverage = self.con.execute("""
|
|
434
|
+
SELECT source_id, count(effective_cost) = count(*) FROM li
|
|
435
|
+
WHERE source_id IN (SELECT unnest(?)) GROUP BY source_id
|
|
436
|
+
""", [list(aws)]).fetchall()
|
|
437
|
+
for source_id, complete in coverage:
|
|
438
|
+
aws[source_id].capabilities["effective_cost"] = complete
|
|
439
|
+
category_sql = SERVICE_CATEGORY_SQL.replace(" t LIKE", " signature_text LIKE").replace(
|
|
440
|
+
"(t LIKE", "(signature_text LIKE")
|
|
441
|
+
self.con.execute(f"""
|
|
442
|
+
CREATE VIEW items AS
|
|
443
|
+
SELECT *,
|
|
444
|
+
strftime(billing_period_start, '%Y-%m') AS billing_period,
|
|
445
|
+
CAST(charge_start AS DATE) AS charge_date,
|
|
446
|
+
(cost_raw IS NOT NULL AND cost IS NULL) AS cost_parse_error,
|
|
447
|
+
lower(concat_ws(' ', service, sku, sku_detail)) AS signature_text,
|
|
448
|
+
CASE WHEN charge_category IN ('tax', 'credit', 'refund', 'discount', 'adjustment')
|
|
449
|
+
THEN charge_category
|
|
450
|
+
ELSE {category_sql}
|
|
451
|
+
END AS service_category
|
|
452
|
+
FROM li
|
|
453
|
+
""")
|
|
454
|
+
self.con.execute(
|
|
455
|
+
"CREATE VIEW valid AS SELECT * FROM items WHERE NOT cost_parse_error AND cost IS NOT NULL"
|
|
456
|
+
)
|
|
457
|
+
|
|
458
|
+
# -- querying ----------------------------------------------------------
|
|
459
|
+
def rows(self, sql: str, params: list | None = None) -> list[dict]:
|
|
460
|
+
cur = self.con.execute(sql, params or [])
|
|
461
|
+
names = [d[0] for d in cur.description]
|
|
462
|
+
return [dict(zip(names, r)) for r in cur.fetchall()]
|
|
463
|
+
|
|
464
|
+
def scalar(self, sql: str, params: list | None = None) -> Any:
|
|
465
|
+
row = self.con.execute(sql, params or []).fetchone()
|
|
466
|
+
return row[0] if row else None
|
|
467
|
+
|
|
468
|
+
@property
|
|
469
|
+
def recognized(self) -> list[LoadedSource]:
|
|
470
|
+
return [s for s in self.sources if s.mapping is not None]
|
|
471
|
+
|
|
472
|
+
def close(self) -> None:
|
|
473
|
+
try:
|
|
474
|
+
self.con.close()
|
|
475
|
+
finally:
|
|
476
|
+
self._tmp.cleanup()
|
|
477
|
+
|
|
478
|
+
def __enter__(self) -> Workspace:
|
|
479
|
+
return self
|
|
480
|
+
|
|
481
|
+
def __exit__(self, exc_type, exc, tb) -> None:
|
|
482
|
+
self.close()
|
|
483
|
+
if isinstance(exc, _RESOURCE_ERRORS):
|
|
484
|
+
raise _resource_error(exc) from exc
|
|
485
|
+
|
|
486
|
+
def duckdb_version(self) -> str:
|
|
487
|
+
return duckdb.__version__
|
cloudleak/errors.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""Error types. Every user-facing failure carries an exit code."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
EXIT_OK = 0
|
|
6
|
+
EXIT_FINDINGS = 1 # command succeeded and found something the policy treats as a failure
|
|
7
|
+
EXIT_INPUT = 2 # fail closed: input cannot support the requested analysis
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class CloudLeakError(Exception):
|
|
11
|
+
"""A failure the user can act on. Never shown with a traceback."""
|
|
12
|
+
|
|
13
|
+
exit_code = EXIT_INPUT
|
|
14
|
+
|
|
15
|
+
def __init__(self, message: str, *, hint: str | None = None):
|
|
16
|
+
super().__init__(message)
|
|
17
|
+
self.hint = hint
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class InputError(CloudLeakError):
|
|
21
|
+
"""The input files cannot be read safely or completely."""
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class RedactionLeakError(CloudLeakError):
|
|
25
|
+
"""The residual-identifier gate found something that must not leave the machine."""
|