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/redact.py ADDED
@@ -0,0 +1,655 @@
1
+ """Local pseudonymization of billing exports, with a verified, owner-only bundle."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import csv
7
+ import hashlib
8
+ import hmac
9
+ import io
10
+ import ipaddress
11
+ import json
12
+ import os
13
+ import re
14
+ import secrets
15
+ import shutil
16
+ import stat
17
+ import tempfile
18
+ import zipfile
19
+ from contextlib import ExitStack, contextmanager, suppress
20
+ from dataclasses import dataclass, field
21
+ from functools import lru_cache
22
+ from pathlib import Path
23
+
24
+ from cloudleak._version import __version__
25
+ from cloudleak.engine import Workspace
26
+ from cloudleak.errors import InputError, RedactionLeakError
27
+ from cloudleak.providers.base import norm, quote_ident
28
+
29
+ # ---------------------------------------------------------------- patterns
30
+ PATTERNS: dict[str, re.Pattern] = {
31
+ "arn": re.compile(r"arn:aws[a-z-]*:[a-z0-9-]*:[a-z0-9-]*:[0-9]*:[A-Za-z0-9_+=,.@:/-]+"),
32
+ "email": re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}"),
33
+ "guid": re.compile(r"(?<![0-9A-Fa-f])[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}"
34
+ r"(?![0-9A-Fa-f])"),
35
+ "ipv4": re.compile(r"(?<![0-9.])(?:(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])\.){3}"
36
+ r"(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(?![0-9]|\.[0-9])"),
37
+ "aws_account": re.compile(r"(?<![0-9A-Za-z])[0-9]{12}(?![0-9])"),
38
+ }
39
+ ALIAS_RE = re.compile(r"^[a-z]{2,6}-[a-z2-7]{16}$")
40
+ ALIAS_TOKEN_RE = re.compile(r"\b[a-z]{2,6}-[a-z2-7]{16}\b")
41
+ NUMERIC_RE = re.compile(r"^[+-]?(?:[0-9]+\.?[0-9]*|\.[0-9]+)(?:[eE][+-]?[0-9]+)?$")
42
+
43
+ # ---------------------------------------------------------------- registry
44
+ DROP_EXACT = {"additional_info", "x_additional_info", "service_info1", "service_info2", "product_comment",
45
+ "project_ancestors"} # GCP folder and organization display names
46
+ TAG_EXACT = {"tags", "resource_tags", "labels", "project_labels", "system_labels", "cost_category",
47
+ "x_tags", "resource_labels", "x_cost_categories", "cost_categories"}
48
+ TAG_PREFIXES = ("resource_tags_", "cost_category_", "user_", "tag_", "label_")
49
+ # An exact registry prevents a customer-defined column containing a word like "cost"
50
+ # from inheriting permission to publish either its header or its contents.
51
+ NUMBERS = {
52
+ "billed_cost", "effective_cost", "list_cost", "contracted_cost", "cost", "cost_at_list",
53
+ "cost_in_billing_currency", "pre_tax_cost", "cost_in_usd", "quantity", "consumed_quantity", "pricing_quantity",
54
+ "usage_quantity", "usage_amount", "usage_amount_in_pricing_units", "credits_amount", "effective_price",
55
+ "pay_g_price", "pricing_public_on_demand_cost", "pricing_public_on_demand_rate", "line_item_usage_amount",
56
+ "line_item_unblended_rate", "line_item_unblended_cost", "line_item_blended_rate", "line_item_blended_cost",
57
+ "line_item_net_unblended_cost", "line_item_net_unblended_rate", "reservation_effective_cost",
58
+ "reservation_net_effective_cost", "reservation_unused_recurring_fee",
59
+ "reservation_unused_amortized_upfront_fee_for_billing_period", "savings_plan_savings_plan_effective_cost",
60
+ "savings_plan_net_savings_plan_effective_cost", "savings_plan_total_commitment_to_date",
61
+ "savings_plan_used_commitment", "split_line_item_split_cost", "split_line_item_net_split_cost",
62
+ "contracted_unit_price", "list_unit_price", "pricing_currency_contracted_unit_price",
63
+ "pricing_currency_effective_cost", "pricing_currency_list_unit_price", "currency_conversion_rate",
64
+ "cost_at_list_consumption_model", "cost_at_effective_price_default", "amount", "invoice_total",
65
+ "invoice_detail_amount", "billed_cost_in_usd",
66
+ }
67
+ DATES = {
68
+ "date", "usage_date", "usage_date_time", "billing_period_start", "billing_period_end",
69
+ "billing_period_start_date", "billing_period_end_date", "charge_period_start", "charge_period_end",
70
+ "usage_start_time", "usage_end_time", "export_time", "bill_billing_period_start_date",
71
+ "bill_billing_period_end_date", "line_item_usage_start_date", "line_item_usage_end_date",
72
+ "identity_time_interval", "invoice_month", "invoice_issue_date",
73
+ }
74
+ CURRENCIES = {
75
+ "billing_currency", "billing_currency_code", "currency", "pricing_currency", "line_item_currency_code",
76
+ "bill_billing_currency", "invoice_currency",
77
+ }
78
+ # ISO currency codes used by billing exporters. Unknown codes are rejected, since changing
79
+ # a real currency label would alter its accounting meaning.
80
+ CODES = {
81
+ "AED", "AFN", "ALL", "AMD", "ANG", "AOA", "ARS", "AUD", "AWG", "AZN", "BAM", "BBD", "BDT", "BGN", "BHD", "BIF",
82
+ "BMD", "BND", "BOB", "BOV", "BRL", "BSD", "BTN", "BWP", "BYN", "BZD", "CAD", "CDF", "CHE", "CHF", "CHW", "CLF",
83
+ "CLP", "CNY", "COP", "COU", "CRC", "CUC", "CUP", "CVE", "CZK", "DJF", "DKK", "DOP", "DZD", "EGP", "ERN", "ETB",
84
+ "EUR", "FJD", "FKP", "GBP", "GEL", "GHS", "GIP", "GMD", "GNF", "GTQ", "GYD", "HKD", "HNL", "HTG", "HUF", "IDR",
85
+ "ILS", "INR", "IQD", "IRR", "ISK", "JMD", "JOD", "JPY", "KES", "KGS", "KHR", "KMF", "KPW", "KRW", "KWD", "KYD",
86
+ "KZT", "LAK", "LBP", "LKR", "LRD", "LSL", "LYD", "MAD", "MDL", "MGA", "MKD", "MMK", "MNT", "MOP", "MRU", "MUR",
87
+ "MVR", "MWK", "MXN", "MXV", "MYR", "MZN", "NAD", "NGN", "NIO", "NOK", "NPR", "NZD", "OMR", "PAB", "PEN", "PGK",
88
+ "PHP", "PKR", "PLN", "PYG", "QAR", "RON", "RSD", "RUB", "RWF", "SAR", "SBD", "SCR", "SDG", "SEK", "SGD", "SHP",
89
+ "SLE", "SLL", "SOS", "SRD", "SSP", "STN", "SVC", "SYP", "SZL", "THB", "TJS", "TMT", "TND", "TOP", "TRY", "TTD",
90
+ "TWD", "TZS", "UAH", "UGX", "USD", "USN", "UYI", "UYU", "UYW", "UZS", "VED", "VES", "VND", "VUV", "WST", "XAF",
91
+ "XAG", "XAU", "XBA", "XBB", "XBC", "XBD", "XCD", "XCG", "XDR", "XOF", "XPD", "XPF", "XPT", "XSU", "XTS", "XUA",
92
+ "XXX", "YER", "ZAR", "ZMW", "ZWG", "ZWL",
93
+ }
94
+ # Recognized categorical values can be published. An unrecognized label is pseudonymized,
95
+ # even if it appears in a field normally populated by a provider.
96
+ CHARGE_TYPES = {
97
+ "usage", "purchase", "tax", "credit", "adjustment", "refund", "fee", "rifee", "discount", "discountedusage",
98
+ "savingsplancoveredusage", "savingsplanrecurringfee", "savingsplanupfrontfee", "savingsplannegation",
99
+ "bundleddiscount", "edpdiscount", "privateratediscount", "distributordiscount", "sppdiscount",
100
+ "unusedreservation", "unusedsavingsplan", "roundingadjustment", "regular", "rounding_error",
101
+ }
102
+ PUBLIC = {
103
+ "charge_category": CHARGE_TYPES, "charge_type": CHARGE_TYPES, "line_item_line_item_type": CHARGE_TYPES,
104
+ "cost_type": CHARGE_TYPES, "charge_class": {"correction"}, "commitment_discount_status": {"used", "unused"},
105
+ "pricing_model": {"ondemand", "reservation", "savingsplan", "spot"},
106
+ "pricing_category": {"standard", "committed", "dynamic", "other"},
107
+ }
108
+ PROVIDERS = {"aws", "amazon web services", "amazon web services, inc.", "google", "google cloud",
109
+ "microsoft", "microsoft azure", "azure", "oracle", "oracle cloud", "gcp"}
110
+ for _column in ("provider_name", "publisher_name", "service_provider_name", "host_provider_name",
111
+ "invoice_issuer_name"):
112
+ PUBLIC[_column] = PROVIDERS
113
+
114
+ PRIVATE = {
115
+ "identity_line_item_id", "bill_payer_account_id", "bill_payer_account_name", "bill_invoice_id",
116
+ "line_item_usage_account_id", "line_item_usage_account_name", "line_item_resource_id",
117
+ "savings_plan_savings_plan_arn", "reservation_reservation_arn", "billing_account_id", "billing_account_name",
118
+ "sub_account_id", "sub_account_name", "subscription_id", "subscription_guid", "subscription_name",
119
+ "resource_group", "x_resource_group_name", "resource_id", "resource_name", "resource_global_name", "invoice_id",
120
+ "invoice", "invoice_detail_id", "invoice_section_id", "billing_profile_id", "enrollment_number", "project_id",
121
+ "project_name", "project_number", "project_ancestry_numbers", "reservation_id", "reservation_name",
122
+ "benefit_id", "benefit_name", "commitment_discount_id", "commitment_discount_name", "capacity_reservation_id",
123
+ "instance_id", "instance_name",
124
+ # Azure EA / MCA / CSP and GCP identity columns seen in real export schemas
125
+ "account_name", "account_owner_id", "invoice_section_name", "billing_profile_name", "customer_name",
126
+ "customer_tenant_id", "reseller_name", "reseller_mpn_id", "partner_name", "partner_tenant_id", "cost_center",
127
+ "cost_allocation_rule_name", "product_order_id", "product_order_name", "plan_name", "offer_id",
128
+ "previous_invoice_id", "subscription_instance_id", "adjustment_info_id",
129
+ }
130
+ TEXT = {
131
+ "service", "sku", "project", "resource", "usage", "consumption_model",
132
+ "charge_description", "line_item_line_item_description", "line_item_description", "x_sku_description",
133
+ "product", "sku_price_details", "adjustment_info_description", "service_name", "service_category",
134
+ "service_subcategory", "sku_id", "sku_meter", "sku_price_id", "region_id", "region_name", "region",
135
+ "availability_zone", "resource_location", "resource_type", "pricing_unit", "consumed_unit", "unit_of_measure",
136
+ "meter_category", "meter_sub_category", "meter_name", "meter_id", "meter_region", "product_name", "frequency",
137
+ "term", "publisher_type", "service_family", "usage_unit", "usage_pricing_unit", "location_region",
138
+ "location_location", "location_zone", "location_country", "service_description", "service_id",
139
+ "sku_description", "transaction_type", "seller_name", "consumption_model_id", "consumption_model_description",
140
+ "consumed_service", "commitment_discount_category", "commitment_discount_type", "capacity_reservation_status",
141
+ "billing_account_type", "sub_account_type", "bill_billing_entity", "bill_invoicing_entity",
142
+ "line_item_legal_entity", "bill_bill_type", "is_azure_credit_eligible", "chargeback_type", "pricing_term",
143
+ "product_servicecode", "product_region_code", "product_product_name", "product_usagetype", "product_region",
144
+ "product_location", "line_item_availability_zone", "line_item_pricing_unit", "line_item_product_code",
145
+ "line_item_usage_type", "line_item_operation", "charge_frequency", "location", "contract_applied",
146
+ "part_number", "adjustment_info_mode", "adjustment_info_type", "x_discounts",
147
+ }
148
+ REGISTERED = NUMBERS | DATES | CURRENCIES | PUBLIC.keys() | PRIVATE | TEXT | TAG_EXACT | DROP_EXACT | {"credits"}
149
+
150
+
151
+ def classify(column: str) -> str:
152
+ n = norm(column)
153
+ if n in DROP_EXACT:
154
+ return "DROP"
155
+ if n in TAG_EXACT:
156
+ return "TAGS"
157
+ if n.startswith(TAG_PREFIXES) or n in PRIVATE:
158
+ return "PSEUDO"
159
+ if n in TEXT or n in PUBLIC:
160
+ return "TEXT"
161
+ if n == "credits":
162
+ return "CREDITS"
163
+ if n in NUMBERS or n in DATES or n in CURRENCIES:
164
+ return "SAFE"
165
+ return "UNCLASSIFIED"
166
+
167
+
168
+ def kind_for(column: str) -> str:
169
+ n = norm(column)
170
+ for token, kind in (("payer_account", "acct"), ("account_id", "acct"), ("account_name", "acctn"),
171
+ ("subscription_id", "sub"), ("subscription_guid", "sub"), ("subscription", "subn"),
172
+ ("project", "proj"), ("resource_group", "rg"), ("invoice", "inv"), ("_arn", "arn"),
173
+ ("resource", "res"), ("instance", "res"), ("global_name", "res"), ("tag", "tag"),
174
+ ("label", "tag"), ("cost_category", "tag"), ("email", "email"), ("user", "user"),
175
+ ("owner", "user")):
176
+ if token in n:
177
+ return kind
178
+ return "id"
179
+
180
+
181
+ # ---------------------------------------------------------------- key
182
+ def default_key_path() -> Path:
183
+ return Path(os.environ.get("CLOUDLEAK_KEY_FILE", Path.cwd() / ".cloudleak" / "redaction.key"))
184
+
185
+
186
+ def load_key(path: Path | None, *, create: bool) -> tuple[bytes, Path]:
187
+ default_dir = path is None and not os.environ.get("CLOUDLEAK_KEY_FILE")
188
+ path = (path or default_key_path()).expanduser()
189
+ if not path.exists() and create:
190
+ path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
191
+ if default_dir:
192
+ try:
193
+ with (path.parent / ".gitignore").open("x", encoding="ascii") as fh:
194
+ fh.write("*\n")
195
+ except FileExistsError:
196
+ pass
197
+ # Publish only a complete key, including for simultaneous first-time users.
198
+ fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=".cloudleak-key-")
199
+ try:
200
+ with os.fdopen(fd, "w", encoding="ascii", newline="\n") as fh: # no CRLF translation on Windows
201
+ fh.write(secrets.token_hex(32) + "\n")
202
+ with suppress(FileExistsError):
203
+ os.link(tmp, path)
204
+ finally:
205
+ Path(tmp).unlink(missing_ok=True)
206
+ if path.is_symlink() or not path.is_file():
207
+ raise InputError("a regular redaction key file is required", hint="Check the --key-file path.")
208
+ with path.open("rb") as fh:
209
+ if os.name == "posix" and os.fstat(fh.fileno()).st_mode & 0o077:
210
+ raise InputError("redaction key permissions allow other users access", hint="Set key permissions to 0600.")
211
+ raw = fh.read(67)
212
+ if not re.fullmatch(rb"[0-9a-f]{64}(?:\r?\n)?", raw):
213
+ raise InputError("invalid redaction key (expected 64 hex characters)")
214
+ return bytes.fromhex(raw[:64].decode("ascii")), path
215
+
216
+
217
+ def key_fingerprint(key: bytes) -> str:
218
+ return hashlib.sha256(b"cloudleak-key-fingerprint:" + key).hexdigest()[:16]
219
+
220
+
221
+ class Aliaser:
222
+ def __init__(self, key: bytes, *, reverse: dict[str, str] | None = None):
223
+ self.key = key
224
+ self.reverse = reverse
225
+ self.cores: set[str] = set()
226
+ self.core = lru_cache(maxsize=1 << 20)(self._core)
227
+
228
+ def _core(self, value: str) -> str:
229
+ digest = hmac.new(self.key, value.encode("utf-8"), hashlib.sha256).digest()
230
+ return base64.b32encode(digest).decode("ascii").lower()[:16]
231
+
232
+ def alias(self, kind: str, value: str) -> str:
233
+ core = self.core(value)
234
+ self.cores.add(core)
235
+ if self.reverse is not None:
236
+ self.reverse.setdefault(core, value)
237
+ return f"{kind}-{core}"
238
+
239
+
240
+ # ---------------------------------------------------------------- transform
241
+ @dataclass
242
+ class FileReport:
243
+ output: str
244
+ source_sha256: str
245
+ rows: int
246
+ columns: dict[str, str]
247
+ dropped: list[str]
248
+
249
+ def to_dict(self) -> dict:
250
+ return {"output": self.output, "source_sha256": self.source_sha256, "rows": self.rows,
251
+ "columns": self.columns, "dropped_columns": self.dropped}
252
+
253
+
254
+ @dataclass
255
+ class RedactionReport:
256
+ files: list[FileReport] = field(default_factory=list)
257
+ key_fingerprint: str = ""
258
+ aliased_values: int = 0
259
+ scanned_cells: int = 0
260
+ output: str = ""
261
+
262
+ def to_dict(self) -> dict:
263
+ return {
264
+ "schema_version": "cloudleak.redaction.v2",
265
+ "cloudleak_version": __version__,
266
+ "key_fingerprint": self.key_fingerprint,
267
+ "gates": {"column_registry": "passed", "value_scrubbing": "applied", "residual_scan": "passed"},
268
+ "aliased_distinct_values": self.aliased_values,
269
+ "scanned_cells": self.scanned_cells,
270
+ "files": [f.to_dict() for f in self.files],
271
+ "notes": [
272
+ "Numeric amounts, dates, currency codes and recognized billing categories are retained.",
273
+ "Free text, private header names and tag keys and values are pseudonymized. "
274
+ "Credit arrays retain only the amounts.",
275
+ "Scanned cells counts CSV data cells. Member names, CSV headers and report metadata are also checked.",
276
+ "Spend patterns, dates, source fingerprints and repeated aliases can identify an organization.",
277
+ ],
278
+ }
279
+
280
+
281
+ _DATE = r"(?:[0-9]{4}-[0-9]{2}-[0-9]{2}|[0-9]{1,2}/[0-9]{1,2}/[0-9]{4}|[0-9]{8})"
282
+ _TIME = r"(?:[T ][0-9]{2}:?[0-9]{2}:?[0-9]{2}(?:\.[0-9]+)?(?:Z| UTC|[+-][0-9]{2}:?[0-9]{2}| [AP]M)?)?"
283
+ STAMP = re.compile(_DATE + _TIME)
284
+
285
+
286
+ def _structured(column: str, value: str) -> bool:
287
+ if column in NUMBERS:
288
+ return bool(NUMERIC_RE.fullmatch(value))
289
+ if column in CURRENCIES:
290
+ return value in CODES
291
+ if column == "invoice_month":
292
+ return bool(re.fullmatch(r"[0-9]{4}-?(?:0[1-9]|1[0-2])", value))
293
+ if column == "identity_time_interval":
294
+ stamps = value.split("/")
295
+ return len(stamps) == 2 and all(STAMP.fullmatch(s) for s in stamps)
296
+ return bool(STAMP.fullmatch(value))
297
+
298
+
299
+ def _tags(value: str, aliaser: Aliaser) -> str:
300
+ try:
301
+ obj = json.loads(value)
302
+ except ValueError:
303
+ try:
304
+ obj = json.loads("{" + value + "}")
305
+ except ValueError:
306
+ return aliaser.alias("tag", value)
307
+
308
+ def tag(v):
309
+ return v if v in (None, "") else aliaser.alias("tag", str(v))
310
+
311
+ if isinstance(obj, dict):
312
+ return json.dumps({aliaser.alias("key", k): tag(v) for k, v in obj.items()}, sort_keys=True)
313
+ if isinstance(obj, list) and all(isinstance(i, dict) and "key" in i for i in obj):
314
+ return json.dumps([{"key": aliaser.alias("key", str(i["key"])), "value": tag(i.get("value"))} for i in obj])
315
+ return aliaser.alias("tag", value)
316
+
317
+
318
+ def _credits(value: str) -> str:
319
+ def unique_fields(items):
320
+ obj = dict(items)
321
+ if len(obj) != len(items):
322
+ raise RedactionLeakError("ambiguous repeated field in structured credits")
323
+ return obj
324
+
325
+ try:
326
+ credits = json.loads(value, parse_int=str, parse_float=str, object_pairs_hook=unique_fields)
327
+ except ValueError:
328
+ credits = None
329
+ if not isinstance(credits, list):
330
+ raise RedactionLeakError("invalid structured credits field")
331
+ output = []
332
+ for entry in credits:
333
+ amount = entry.get("amount") if isinstance(entry, dict) else None
334
+ if not isinstance(amount, str) or not NUMERIC_RE.fullmatch(amount):
335
+ raise RedactionLeakError("a structured credit contains an unreadable amount")
336
+ output.append({"amount": amount})
337
+ return json.dumps(output, separators=(",", ":"))
338
+
339
+
340
+ def _cell(column: str, action: str, value: str | None, aliaser: Aliaser) -> str:
341
+ if value is None or value == "":
342
+ return ""
343
+ n = norm(column)
344
+ v = str(value)
345
+ if action == "SAFE":
346
+ v = v.strip()
347
+ if not _structured(n, v):
348
+ raise RedactionLeakError(f"unreadable structured value in {n}")
349
+ return v
350
+ if action == "TAGS":
351
+ return _tags(v, aliaser)
352
+ if action == "CREDITS":
353
+ return _credits(v)
354
+ if v.lower() in PUBLIC.get(n, ()):
355
+ return v
356
+ return aliaser.alias(kind_for(column) if action == "PSEUDO" else "text", v.strip())
357
+
358
+
359
+ def _header(column: str, aliaser: Aliaser) -> str:
360
+ n = norm(column)
361
+ if n in REGISTERED:
362
+ return n
363
+ # Keep the tag prefix recognized by provider adapters without retaining the user's tag name.
364
+ return "resource_tags/" + aliaser.alias("field", column)
365
+
366
+
367
+ def _overlap(left: Path, right: Path) -> bool:
368
+ return (left == right or left.is_relative_to(right) or right.is_relative_to(left)
369
+ or (left.exists() and right.exists() and left.samefile(right)))
370
+
371
+
372
+ def _check_output(out: Path, key: Path, paths, force: bool) -> None:
373
+ if out.is_symlink():
374
+ raise InputError("refusing to replace a symlink destination")
375
+ dest = out.resolve()
376
+ if any(_overlap(dest, Path(p).expanduser().resolve()) for p in paths) or _overlap(dest, key.resolve()):
377
+ raise InputError("redaction output overlaps an input or the key", hint="Choose a separate destination.")
378
+ if out.exists() and not force:
379
+ raise InputError("redaction output already exists", hint="Choose a new output path or pass --force.")
380
+ if out.exists():
381
+ if out.suffix.lower() == ".zip":
382
+ if not out.is_file():
383
+ raise InputError("the ZIP destination must be a regular file")
384
+ elif not out.is_dir() or any(out.iterdir()):
385
+ raise InputError("cannot atomically replace a nonempty directory or a file with a directory",
386
+ hint="Choose a new directory or write a .zip bundle.")
387
+
388
+
389
+ @contextmanager
390
+ def _workspace(paths, **settings):
391
+ try:
392
+ ws = Workspace(paths, **settings)
393
+ except InputError as exc:
394
+ # Source names, raw headers and DuckDB parse details can contain private text.
395
+ # Keep the actionable failure class in diagnostics without echoing the export.
396
+ message = str(exc).lower()
397
+ if "decompress" in message or "ratio limit" in message:
398
+ raise InputError("compressed input failed its integrity or decompression limit check",
399
+ hint="Check the gzip file and the --max-decompressed-gb setting.") from exc
400
+ if "invalid gcp credit" in message:
401
+ raise RedactionLeakError("invalid structured credit amount") from exc
402
+ if "memory" in message or "memory" in str(exc.hint).lower():
403
+ raise InputError("workspace memory configuration or limit prevented loading",
404
+ hint="Review --memory-limit, --threads and available memory.") from exc
405
+ raise InputError("billing inputs could not be loaded for pseudonymization",
406
+ hint="Run doctor locally to inspect source-specific diagnostics.") from exc
407
+ except OSError as exc:
408
+ raise InputError("could not open an input or workspace directory",
409
+ hint="Check that inputs are readable and the spill directory is writable.") from exc
410
+ with ws:
411
+ yield ws
412
+
413
+
414
+ def _private_file(path: Path, mode: str, **kw):
415
+ return open(path, mode, opener=lambda filename, flags: os.open(filename, flags, 0o600), **kw)
416
+
417
+
418
+ def redact(paths: list[str], output: str, *, key_file: str | None = None, drop_unclassified: bool = False,
419
+ force: bool = False, memory_limit: str = "2GB", temp_dir: str | None = None, threads: int | None = None,
420
+ max_decompressed: int = 64 << 30) -> RedactionReport:
421
+ out = Path(output).expanduser().absolute()
422
+ key_path = (Path(key_file) if key_file else default_key_path()).expanduser()
423
+ _check_output(out, key_path, paths, force)
424
+ with _workspace(paths, memory_limit=memory_limit, temp_dir=temp_dir, threads=threads,
425
+ max_decompressed=max_decompressed) as ws:
426
+ sources = [s.file.path for s in ws.sources] + [m.path for m in ws.discovery.manifests]
427
+ _check_output(out, key_path, sources, force)
428
+ if any(_overlap(key_path.resolve(), p.resolve()) for p in sources):
429
+ raise InputError("redaction key overlaps an input")
430
+ plans = []
431
+ for s in ws.sources:
432
+ plan = {c: classify(c) for c in s.columns if c != "__cl_row"}
433
+ for i, (c, action) in enumerate(plan.items(), 1):
434
+ if action == "UNCLASSIFIED":
435
+ if not drop_unclassified:
436
+ raise RedactionLeakError(
437
+ f"source {s.file.source_id}, column {i} is absent from the redaction registry",
438
+ hint="Inspect this column locally or use --drop-unclassified to omit it.")
439
+ plan[c] = "DROP"
440
+ plans.append((s, plan))
441
+ key, _ = load_key(Path(key_file) if key_file else None, create=True)
442
+ aliaser = Aliaser(key)
443
+ report = RedactionReport(key_fingerprint=key_fingerprint(key))
444
+ out.parent.mkdir(parents=True, exist_ok=True)
445
+ with tempfile.TemporaryDirectory(prefix=".cloudleak-redact-", dir=out.parent) as tmp:
446
+ stage = Path(tmp)
447
+ bundle = stage / "bundle"
448
+ bundle.mkdir(mode=0o700)
449
+ for s, plan in plans:
450
+ kept = [c for c in plan if plan[c] != "DROP"]
451
+ headers = [_header(c, aliaser) for c in kept]
452
+ if len(set(headers)) != len(headers):
453
+ raise RedactionLeakError("columns would map to duplicate published names")
454
+ name = f"export-{s.file.source_id:03d}-{s.mapping.dataset}.csv"
455
+ with _private_file(bundle / name, "x", newline="", encoding="utf-8") as fh:
456
+ w = csv.writer(fh, lineterminator="\n")
457
+ w.writerow(headers)
458
+ cur = ws.con.execute(
459
+ f"SELECT {', '.join(map(quote_ident, kept))} FROM {quote_ident(s.table)} ORDER BY __cl_row")
460
+ while batch := cur.fetchmany(5000):
461
+ for row in batch:
462
+ w.writerow([_cell(c, plan[c], v, aliaser) for c, v in zip(kept, row)])
463
+ report.scanned_cells += s.rows * len(kept)
464
+ dropped = [f"column-{i}" for i, c in enumerate(plan, 1) if plan[c] == "DROP"]
465
+ report.files.append(FileReport(name, s.file.sha256, s.rows, dict(zip(headers, (plan[c] for c in kept))),
466
+ dropped))
467
+ report.aliased_values = len(aliaser.cores)
468
+ with _private_file(bundle / "REDACTION_REPORT.json", "x", encoding="utf-8") as fh:
469
+ json.dump(report.to_dict(), fh, indent=2, sort_keys=True)
470
+ fh.write("\n")
471
+ candidate = bundle
472
+ if out.suffix.lower() == ".zip":
473
+ candidate = stage / "bundle.zip"
474
+ with _private_file(candidate, "xb") as raw, zipfile.ZipFile(raw, "w") as archive:
475
+ for child in sorted(bundle.iterdir()):
476
+ entry = zipfile.ZipInfo(child.name, date_time=(1980, 1, 1, 0, 0, 0))
477
+ entry.compress_type = zipfile.ZIP_DEFLATED
478
+ entry.external_attr = (stat.S_IFREG | 0o600) << 16
479
+ with archive.open(entry, "w", force_zip64=True) as member, child.open("rb") as src:
480
+ shutil.copyfileobj(src, member)
481
+ if scan_bundle(candidate, {}, expected=report) != report.scanned_cells:
482
+ raise RedactionLeakError("final scan disagrees with expected cell count")
483
+ _check_output(out, key_path, [*paths, *sources], force)
484
+ if candidate.is_file() and not force:
485
+ os.link(candidate, out)
486
+ else:
487
+ os.replace(candidate, out)
488
+ report.output = str(out)
489
+ return report
490
+
491
+
492
+ def _report_strings(obj):
493
+ if isinstance(obj, dict):
494
+ for k, v in obj.items():
495
+ yield k
496
+ size = {"key_fingerprint": 16, "source_sha256": 64}.get(k)
497
+ if size and isinstance(v, str) and re.fullmatch(rf"[0-9a-f]{{{size}}}", v):
498
+ continue
499
+ yield from _report_strings(v)
500
+ elif isinstance(obj, list):
501
+ for item in obj:
502
+ yield from _report_strings(item)
503
+ elif isinstance(obj, str):
504
+ yield obj
505
+
506
+
507
+ def _check_patterns(text: str, known):
508
+ probe = ALIAS_TOKEN_RE.sub(" ", text)
509
+ if any(v and v in probe for v in known):
510
+ raise RedactionLeakError("residual-identifier scan failed (known-identifier)")
511
+ for name, pat in PATTERNS.items():
512
+ if pat.search(probe):
513
+ raise RedactionLeakError(f"residual-identifier scan failed ({name})")
514
+ for match in re.finditer(r"(?<![0-9a-fA-F:])[0-9a-fA-F:]*:[0-9a-fA-F:]+(?:%[\w.-]+)?", probe):
515
+ try:
516
+ ipaddress.IPv6Address(match.group())
517
+ except ValueError:
518
+ continue
519
+ raise RedactionLeakError("residual-identifier scan failed (ipv6)")
520
+
521
+
522
+ def _valid_tags(obj) -> bool:
523
+ def tagged(value) -> bool:
524
+ return value in (None, "") or (isinstance(value, str) and bool(ALIAS_RE.fullmatch(value)))
525
+
526
+ if isinstance(obj, dict):
527
+ return all(ALIAS_RE.fullmatch(k) and tagged(v) for k, v in obj.items())
528
+ if isinstance(obj, list):
529
+ return all(isinstance(i, dict) and i.keys() == {"key", "value"} and isinstance(i["key"], str)
530
+ and ALIAS_RE.fullmatch(i["key"]) and tagged(i["value"]) for i in obj)
531
+ return False
532
+
533
+
534
+ def _verify_cell(column: str, cell: str, known) -> None:
535
+ if not cell:
536
+ return
537
+ n = norm(column)
538
+ action = classify(column)
539
+ if action == "SAFE" and _structured(n, cell):
540
+ return
541
+ if action == "CREDITS" and _credits(cell) == cell:
542
+ return
543
+ _check_patterns(cell, known)
544
+ if ALIAS_RE.fullmatch(cell) and action in {"PSEUDO", "TEXT", "TAGS"}:
545
+ return
546
+ if action == "TEXT" and cell.lower() in PUBLIC.get(n, ()):
547
+ return
548
+ if action == "TAGS":
549
+ with suppress(ValueError):
550
+ if _valid_tags(json.loads(cell)):
551
+ return
552
+ raise RedactionLeakError("residual scan found an unexpected value for the column's classification")
553
+
554
+
555
+ def _unexpected_zip_metadata(info: zipfile.ZipInfo) -> bool:
556
+ # Python adds a numeric ZIP64 extra field for large files and offsets.
557
+ extra = info.extra
558
+ zip64 = (extra[:2] == b"\x01\x00" and len(extra) - 4 in {8, 16, 24, 28}
559
+ and int.from_bytes(extra[2:4], "little") == len(extra) - 4)
560
+ return bool(info.comment or (extra and not zip64))
561
+
562
+
563
+ def scan_bundle(bundle: Path, known: dict[str, str], *, expected: RedactionReport | None = None) -> int:
564
+ """Check actual member names, headers, metadata and data. Count CSV data cells only."""
565
+ files = {f.output: f for f in expected.files} if expected else {}
566
+ with ExitStack() as stack:
567
+ if bundle.is_dir():
568
+ names = [p.name for p in bundle.iterdir()]
569
+
570
+ def read(name):
571
+ return (bundle / name).open("rb")
572
+ else:
573
+ archive = stack.enter_context(zipfile.ZipFile(bundle))
574
+ names = archive.namelist()
575
+ if archive.comment or any(_unexpected_zip_metadata(info) for info in archive.infolist()):
576
+ raise RedactionLeakError("unexpected archive metadata")
577
+ read = archive.open
578
+ if expected and (set(names) != {*files, "REDACTION_REPORT.json"} or len(names) != len(files) + 1):
579
+ raise RedactionLeakError("unexpected bundle member inventory")
580
+ cells = 0
581
+ for name in names:
582
+ _check_patterns(name, known)
583
+ with read(name) as raw, io.TextIOWrapper(raw, encoding="utf-8", newline="") as stream:
584
+ if name == "REDACTION_REPORT.json":
585
+ meta = json.load(stream)
586
+ if expected and meta != expected.to_dict():
587
+ raise RedactionLeakError("published metadata disagrees with the prepared report")
588
+ for text in _report_strings(meta):
589
+ _check_patterns(text, known)
590
+ continue
591
+ reader = csv.reader(stream, strict=True)
592
+ headers = next(reader, [])
593
+ for h in headers:
594
+ _check_patterns(h, known)
595
+ if h not in REGISTERED and not re.fullmatch(r"resource_tags/field-[a-z2-7]{16}", h):
596
+ raise RedactionLeakError("unexpected header in final bundle")
597
+ if expected and headers != list(files[name].columns):
598
+ raise RedactionLeakError("published CSV header disagrees with the prepared report")
599
+ rows = 0
600
+ for row in reader:
601
+ if len(row) != len(headers):
602
+ raise RedactionLeakError("published row width disagrees with the header")
603
+ for h, value in zip(headers, row):
604
+ _verify_cell(h, value, known)
605
+ cells += len(row)
606
+ rows += 1
607
+ if expected and rows != files[name].rows:
608
+ raise RedactionLeakError("published row count disagrees with the prepared report")
609
+ return cells
610
+
611
+
612
+ # Resolve using the identical transformation, including dynamic headers and tag keys.
613
+ def build_resolver(paths: list[str], key_file: str | None, *, memory_limit: str = "2GB", temp_dir: str | None = None,
614
+ threads: int | None = None, max_decompressed: int = 64 << 30) -> dict[str, str]:
615
+ key, _ = load_key(Path(key_file) if key_file else None, create=False)
616
+ table: dict[str, str] = {}
617
+ aliaser = Aliaser(key, reverse=table)
618
+ with _workspace(paths, memory_limit=memory_limit, temp_dir=temp_dir, threads=threads,
619
+ max_decompressed=max_decompressed) as ws:
620
+ for s in ws.sources:
621
+ for c in s.columns:
622
+ if c == "__cl_row":
623
+ continue
624
+ action = classify(c)
625
+ if action not in {"PSEUDO", "TEXT", "TAGS", "UNCLASSIFIED", "CREDITS"}:
626
+ continue
627
+ _header(c, aliaser)
628
+ cur = ws.con.execute(f"SELECT DISTINCT {quote_ident(c)} FROM {quote_ident(s.table)}")
629
+ while batch := cur.fetchmany(5000):
630
+ for (v,) in batch:
631
+ if not v:
632
+ continue
633
+ if action in {"PSEUDO", "TEXT", "TAGS"}:
634
+ _cell(c, action, v, aliaser)
635
+ # Resolve whole values and embedded pattern aliases from pre-v2 bundles as well.
636
+ table.setdefault(aliaser.core(v.strip()), v.strip())
637
+ for pattern in PATTERNS.values():
638
+ for match in pattern.finditer(v):
639
+ table.setdefault(aliaser.core(match.group()), match.group())
640
+ return table
641
+
642
+
643
+ def resolve_text(text: str, table: dict[str, str]) -> tuple[str, int, int]:
644
+ found = unresolved = 0
645
+
646
+ def sub(m: re.Match) -> str:
647
+ nonlocal found, unresolved
648
+ core = m.group(0).split("-", 1)[1]
649
+ if core in table:
650
+ found += 1
651
+ return table[core]
652
+ unresolved += 1
653
+ return m.group(0)
654
+
655
+ return ALIAS_TOKEN_RE.sub(sub, text), found, unresolved
@@ -0,0 +1 @@
1
+ """Output renderers. Each takes a cloudleak.report.v1 dict."""