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/report.py ADDED
@@ -0,0 +1,138 @@
1
+ """Assemble the ``cloudleak.report.v1`` envelope shared by every output format."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import datetime as dt
6
+ import hashlib
7
+ import json
8
+ import os
9
+ import platform
10
+ from decimal import Decimal
11
+ from typing import Any
12
+
13
+ from cloudleak._version import __version__
14
+ from cloudleak.analysis import breakdown, period_statuses, totals
15
+ from cloudleak.doctor import DoctorReport
16
+ from cloudleak.engine import Workspace
17
+ from cloudleak.findings import Finding, _jsonable, sort_key
18
+ from cloudleak.rules import RULE_PACK_VERSION, RULES, rule_pack_hash
19
+ from cloudleak.variance import Bridge
20
+
21
+ REPORT_SCHEMA = "cloudleak.report.v1"
22
+ ISSUES_URL = "https://github.com/pranavg21/cloudleak/issues/new?template=schema-quirk.yml"
23
+ SYNTHETIC_MARK = "SYNTHETIC_TEST_FIXTURE_ONLY"
24
+
25
+ LIMITATIONS = [
26
+ "Billing exports are historical ledgers. They cannot show whether a resource exists today, is attached, "
27
+ "serves traffic, or is safe to change.",
28
+ "Each observed cost uses the basis shown on its finding. Verified savings require separate evidence.",
29
+ "Findings stop at evidence Level 2 (billing-supported hypothesis). Levels 3-5 need inventory snapshots, "
30
+ "owner decisions and a later finalized bill.",
31
+ "Owners are taken from tags or account names only; CloudLeak never guesses an owner.",
32
+ ]
33
+
34
+ CAN_CANNOT = [
35
+ ("Costs recorded in the export by period, currency, account, service and SKU, with available finality evidence",
36
+ "Proven by the export (Level 1)"),
37
+ ("Charges whose billing line names a pattern: idle IPv4, NAT processing, unused commitment, "
38
+ "extended support, gp2, snapshots, log ingestion",
39
+ "Supported hypothesis (Level 2): verify with the read-only commands listed"),
40
+ ("Whether a resource is unused, orphaned or safe to delete; how much can be saved",
41
+ "Not provable from billing data. CloudLeak does not claim it"),
42
+ ]
43
+
44
+
45
+ def generated_at() -> str:
46
+ epoch = os.environ.get("SOURCE_DATE_EPOCH")
47
+ when = (dt.datetime.fromtimestamp(int(epoch), tz=dt.timezone.utc) if epoch and epoch.isdigit()
48
+ else dt.datetime.now(tz=dt.timezone.utc))
49
+ return when.replace(microsecond=0).isoformat().replace("+00:00", "Z")
50
+
51
+
52
+ def tool_info(ws: Workspace | None = None) -> dict:
53
+ import duckdb
54
+ return {
55
+ "name": "cloudleak", "version": __version__, "duckdb_version": duckdb.__version__,
56
+ "python_version": platform.python_version(), "rule_pack_version": RULE_PACK_VERSION,
57
+ "rule_pack_hash": rule_pack_hash(),
58
+ }
59
+
60
+
61
+ def run_id(ws: Workspace, command: str, args: dict, *, after: Workspace | None = None) -> str:
62
+ def identity(snapshot: Workspace) -> dict:
63
+ return {"files": [s.to_dict() for s in snapshot.sources],
64
+ "manifests": [m.sha256 for m in snapshot.discovery.manifests],
65
+ "skipped": snapshot.discovery.skipped}
66
+
67
+ inputs = {"before": identity(ws), "after": identity(after)} if after else identity(ws)
68
+ blob = json.dumps({"inputs": inputs, "tool": tool_info(), "command": command, "args": _jsonable(args)},
69
+ sort_keys=True, default=str)
70
+ return "clr_" + hashlib.sha256(blob.encode()).hexdigest()[:20]
71
+
72
+
73
+ def is_synthetic(ws: Workspace) -> bool:
74
+ if any(SYNTHETIC_MARK in str(s.file.path) for s in ws.sources):
75
+ return True
76
+ try:
77
+ return bool(ws.scalar(
78
+ "SELECT count(*) FROM items WHERE billing_account_id LIKE ? OR sub_account_name LIKE ?",
79
+ [f"%{SYNTHETIC_MARK}%", f"%{SYNTHETIC_MARK}%"]))
80
+ except Exception: # pragma: no cover - defensive
81
+ return False
82
+
83
+
84
+ def build(ws: Workspace, *, command: str, args: dict, doctor: DoctorReport | None = None,
85
+ findings: list[Finding] | None = None, bridges: list[Bridge] | None = None,
86
+ extra: dict[str, Any] | None = None, where: str = "TRUE") -> dict:
87
+ rid = run_id(ws, command, args)
88
+ tool = tool_info(ws)
89
+ repro = {"cloudleak_version": tool["version"], "duckdb_version": tool["duckdb_version"],
90
+ "rule_pack_hash": tool["rule_pack_hash"]}
91
+ findings = sorted(findings or [], key=sort_key)
92
+ statuses = period_statuses(ws, where=where)
93
+ by_rule: dict[str, int] = {}
94
+ for f in findings:
95
+ by_rule[f.rule_id] = by_rule.get(f.rule_id, 0) + 1
96
+ report: dict[str, Any] = {
97
+ "schema_version": REPORT_SCHEMA,
98
+ "tool": tool,
99
+ "run": {"report_run_id": rid, "command": command, "arguments": _jsonable(args),
100
+ "generated_at": generated_at()},
101
+ "trust_boundary": {"network_access": "none", "cloud_credentials": "none",
102
+ "evidence_ceiling": "L2", "verified_savings": "never emitted"},
103
+ "synthetic_data": is_synthetic(ws),
104
+ "inputs": [s.to_dict() for s in ws.sources],
105
+ "manifests": [m.to_dict() for m in ws.discovery.manifests],
106
+ "skipped_files": [{"name": n, "reason": r} for n, r in ws.discovery.skipped],
107
+ "periods": [s.to_dict() for s in statuses],
108
+ "totals": _jsonable(totals(ws, where=where)),
109
+ "breakdowns": {
110
+ "service_category": _jsonable(breakdown(ws, "service_category", limit=12, where=where)),
111
+ "service": _jsonable(breakdown(ws, "service", limit=12, where=where)),
112
+ "sub_account_id": _jsonable(breakdown(ws, "sub_account_id", limit=12, where=where)),
113
+ "region": _jsonable(breakdown(ws, "region", limit=10, where=where)),
114
+ },
115
+ "doctor": None,
116
+ "variance": [b.to_dict() | {"narrative": b.narrative()} for b in bridges] if bridges else None,
117
+ "findings": [f.to_dict(report_run_id=rid, reproducibility=repro) for f in findings],
118
+ "findings_by_rule": dict(sorted(by_rule.items())),
119
+ "rules": [{"rule_id": r.rule_id, "slug": r.slug, "title": r.title} for r in RULES],
120
+ "limitations": LIMITATIONS,
121
+ }
122
+ if doctor is not None:
123
+ report["doctor"] = {"status": doctor.worst, "counts": doctor.counts(),
124
+ "results": [r.to_dict() for r in doctor.results]}
125
+ if extra:
126
+ report.update(_jsonable(extra))
127
+ return report
128
+
129
+
130
+ def dumps(report: dict) -> str:
131
+ def default(o: Any) -> Any:
132
+ if isinstance(o, Decimal):
133
+ from cloudleak.money import fmt
134
+ return fmt(o)
135
+ if hasattr(o, "isoformat"):
136
+ return o.isoformat()
137
+ raise TypeError(type(o).__name__)
138
+ return json.dumps(report, indent=2, sort_keys=True, ensure_ascii=False, default=default) + "\n"
cloudleak/rules.py ADDED
@@ -0,0 +1,403 @@
1
+ """Level-2 billing signatures: charges whose *billing line itself* names a pattern.
2
+
3
+ A rule here fires only on provider-explicit evidence in the bill: an AWS usage
4
+ type that literally says ``IdleAddress``, a meter that says ``Data
5
+ Processed`` by a NAT gateway, a charge type that says ``UnusedReservation``.
6
+ Billing data never proves a resource is unused, unattached or safe to remove,
7
+ so no rule emits a savings figure or a mutating command, and there is
8
+ deliberately no rule for "expensive disk", "large GPU" or "idle load
9
+ balancer": those cannot be distinguished from legitimate production use in a
10
+ bill.
11
+
12
+ Every verification command is read-only and every interpolated value is
13
+ shell-quoted.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import hashlib
19
+ import json
20
+ import re
21
+ import shlex
22
+ from collections.abc import Callable
23
+ from dataclasses import dataclass, field
24
+ from decimal import Decimal
25
+
26
+ from cloudleak.analysis import finality_lookup, owner_routing, period_statuses
27
+ from cloudleak.engine import Workspace
28
+ from cloudleak.findings import Finding, VerificationStep
29
+
30
+ RULE_PACK_VERSION = "2026.11.1"
31
+ Q = shlex.quote
32
+
33
+
34
+ @dataclass(frozen=True)
35
+ class Rule:
36
+ rule_id: str
37
+ slug: str
38
+ title: str
39
+ where: str # SQL predicate over the `valid` view
40
+ group: str # resource | scope
41
+ rationale: str
42
+ unknowns: tuple[str, ...]
43
+ false_positives: tuple[str, ...]
44
+ verify: Callable[[dict], list[VerificationStep]]
45
+ amount: str = "cost" # SQL for the observed amount
46
+ amount_basis: str = "cost_basis"
47
+ severity: str = "medium"
48
+ providers: tuple[str, ...] = ("aws", "azure", "gcp", "focus")
49
+ docs: tuple[str, ...] = field(default_factory=tuple)
50
+ # When one scope has both actual and amortized exports, evaluate this basis only.
51
+ prefer_basis: str = "billed"
52
+
53
+ def fingerprint(self) -> dict:
54
+ return {"id": self.rule_id, "where": " ".join(self.where.split()), "group": self.group,
55
+ "amount": self.amount, "amount_basis": self.amount_basis, "prefer_basis": self.prefer_basis}
56
+
57
+
58
+ def _region(r: dict) -> str:
59
+ return f" --region {Q(r['region'])}" if r.get("region") and re.fullmatch(r"[a-z0-9-]+", r["region"]) else ""
60
+
61
+
62
+ def _console(text: str) -> VerificationStep:
63
+ return VerificationStep(description=text, tool="console")
64
+
65
+
66
+ def _verify_ipv4(r: dict) -> list[VerificationStep]:
67
+ rid = r.get("resource_id") or ""
68
+ if rid.startswith("eipalloc-"):
69
+ sel = f" --allocation-ids {Q(rid)}"
70
+ elif re.fullmatch(r"\d{1,3}(\.\d{1,3}){3}", rid):
71
+ sel = f" --public-ips {Q(rid)}"
72
+ else:
73
+ sel = ""
74
+ return [
75
+ VerificationStep("Check whether the address is associated right now (AssociationId empty means idle).",
76
+ f"aws ec2 describe-addresses{_region(r)}{sel} --query "
77
+ "'Addresses[].[AllocationId,PublicIp,AssociationId,Tags]' --output table", "aws"),
78
+ _console("Ask the owner whether the address is allowlisted by a partner or held for failover; "
79
+ "a released Elastic IP cannot be recovered."),
80
+ ]
81
+
82
+
83
+ def _verify_nat(r: dict) -> list[VerificationStep]:
84
+ p, rid = r.get("provider"), r.get("resource_id") or ""
85
+ if p == "aws":
86
+ sel = f" --nat-gateway-ids {Q(rid)}" if rid.startswith("nat-") else ""
87
+ return [
88
+ VerificationStep("Identify the NAT gateway and its VPC.",
89
+ f"aws ec2 describe-nat-gateways{_region(r)}{sel} --query "
90
+ "'NatGateways[].[NatGatewayId,VpcId,SubnetId,State]' --output table", "aws"),
91
+ VerificationStep("Check whether S3/DynamoDB traffic already uses gateway endpoints in that VPC.",
92
+ f"aws ec2 describe-vpc-endpoints{_region(r)} --filters "
93
+ "Name=vpc-endpoint-type,Values=Gateway --query "
94
+ "'VpcEndpoints[].[VpcId,ServiceName,State]' --output table", "aws"),
95
+ _console("Use VPC Flow Logs on the NAT gateway ENI to see which destinations drive the bytes."),
96
+ ]
97
+ if p == "azure":
98
+ cmd = (f"az network nat gateway show --ids {Q(rid)} --query '{{name:name,subnets:subnets[].id}}'"
99
+ if rid.startswith("/subscriptions/") else None)
100
+ return [VerificationStep("Inspect the NAT gateway and the subnets routed through it.", cmd, "az"),
101
+ _console("Check whether Azure services are reached via Private Endpoints or Service Endpoints.")]
102
+ if p == "gcp":
103
+ proj = r.get("sub_account_id")
104
+ cmd = f"gcloud compute routers list --project {Q(proj)}" if proj else None
105
+ return [VerificationStep("List Cloud Routers carrying Cloud NAT configurations.", cmd, "gcloud"),
106
+ _console("Check Private Google Access on the subnets that send traffic through Cloud NAT.")]
107
+ return [_console("Identify the NAT resource and the workloads routing through it.")]
108
+
109
+
110
+ def _verify_cross_zone(r: dict) -> list[VerificationStep]:
111
+ if r.get("provider") == "aws":
112
+ return [VerificationStep(
113
+ "List instances by Availability Zone to find chatty services split across zones.",
114
+ f"aws ec2 describe-instances{_region(r)} --query "
115
+ "'Reservations[].Instances[].[InstanceId,Placement.AvailabilityZone,Tags[?Key==`Name`].Value|[0]]' "
116
+ "--output table", "aws"),
117
+ _console("Enable VPC Flow Logs to attribute inter-zone bytes to source/destination pairs.")]
118
+ proj = r.get("sub_account_id")
119
+ if r.get("provider") == "gcp" and proj:
120
+ return [VerificationStep("List instances by zone.",
121
+ f"gcloud compute instances list --project {Q(proj)} --format='table(name,zone)'",
122
+ "gcloud")]
123
+ return [_console("Map which services talk across zones before changing placement; "
124
+ "multi-zone traffic is often required for availability.")]
125
+
126
+
127
+ def _verify_logs(r: dict) -> list[VerificationStep]:
128
+ p = r.get("provider")
129
+ if p == "aws":
130
+ return [VerificationStep(
131
+ "Rank log groups by stored bytes and check retention.",
132
+ f"aws logs describe-log-groups{_region(r)} --query "
133
+ "'reverse(sort_by(logGroups,&storedBytes))[:20].[logGroupName,storedBytes,retentionInDays]' "
134
+ "--output table", "aws")]
135
+ if p == "azure":
136
+ rid = r.get("resource_id") or ""
137
+ cmd = f"az monitor log-analytics workspace show --ids {Q(rid)}" if rid.startswith("/subscriptions/") else None
138
+ return [VerificationStep("Inspect the workspace's retention and daily cap.", cmd, "az"),
139
+ _console("Query the Usage table to rank data types by billable ingestion volume.")]
140
+ if p == "gcp":
141
+ proj = r.get("sub_account_id")
142
+ cmd = f"gcloud logging sinks list --project {Q(proj)}" if proj else None
143
+ return [VerificationStep("List log sinks and exclusion filters.", cmd, "gcloud")]
144
+ return [_console("Identify the top log sources by ingested volume.")]
145
+
146
+
147
+ def _verify_snapshot(r: dict) -> list[VerificationStep]:
148
+ p, rid = r.get("provider"), r.get("resource_id") or ""
149
+ if p == "aws":
150
+ sel = f" --snapshot-ids {Q(rid)}" if rid.startswith("snap-") else " --owner-ids self"
151
+ return [VerificationStep("Check snapshot age, source volume and tags.",
152
+ f"aws ec2 describe-snapshots{_region(r)}{sel} --query "
153
+ "'Snapshots[].[SnapshotId,VolumeId,StartTime,VolumeSize,Tags]' --output table",
154
+ "aws"),
155
+ _console("Confirm the retention policy (backup plan, compliance requirement) that covers it.")]
156
+ if p == "azure" and rid.startswith("/subscriptions/"):
157
+ return [VerificationStep("Check the snapshot's creation time and source disk.",
158
+ f"az snapshot show --ids {Q(rid)} --query "
159
+ "'{created:timeCreated,source:creationData.sourceResourceId,sizeGb:diskSizeGb}'",
160
+ "az"),
161
+ _console("Confirm the retention policy that covers it.")]
162
+ if p == "gcp":
163
+ name, proj = rid.rsplit("/", 1)[-1], r.get("sub_account_id")
164
+ cmd = (f"gcloud compute snapshots describe {Q(name)} --project {Q(proj)}"
165
+ if name and proj else None)
166
+ return [VerificationStep("Check the snapshot's creation time and source disk.", cmd, "gcloud"),
167
+ _console("Confirm the snapshot schedule's retention policy.")]
168
+ return [_console("Confirm retention requirements before changing snapshot policy.")]
169
+
170
+
171
+ def _verify_commitment(r: dict) -> list[VerificationStep]:
172
+ p = r.get("provider")
173
+ if p == "aws":
174
+ return [VerificationStep("List active reservations and their remaining term.",
175
+ f"aws ec2 describe-reserved-instances{_region(r)} --filters Name=state,Values=active "
176
+ "--query 'ReservedInstances[].[ReservedInstancesId,InstanceType,InstanceCount,End]' "
177
+ "--output table", "aws"),
178
+ _console("Check whether instance-size flexibility or an exchange could absorb the unused share.")]
179
+ if p == "azure":
180
+ return [VerificationStep("List reservations and utilization.",
181
+ "az reservations reservation-order list --query "
182
+ "'[].{order:name,display:displayName,term:term}' --output table", "az"),
183
+ _console("Review utilization under Reservations in the Azure portal before exchanging.")]
184
+ return [_console("Review commitment utilization in the provider console before acting.")]
185
+
186
+
187
+ def _verify_gp2(r: dict) -> list[VerificationStep]:
188
+ rid = r.get("resource_id") or ""
189
+ sel = f" --volume-ids {Q(rid)}" if rid.startswith("vol-") else " --filters Name=volume-type,Values=gp2"
190
+ return [VerificationStep("Check size, IOPS, throughput and attachment of the gp2 volume.",
191
+ f"aws ec2 describe-volumes{_region(r)}{sel} --query "
192
+ "'Volumes[].[VolumeId,Size,Iops,State,Attachments[0].InstanceId]' --output table",
193
+ "aws"),
194
+ _console("Compare the volume's peak IOPS/throughput in CloudWatch with gp3 baselines "
195
+ "before changing type.")]
196
+
197
+
198
+ def _verify_extended_support(r: dict) -> list[VerificationStep]:
199
+ rid, svc = r.get("resource_id") or "", (r.get("service") or "").lower()
200
+ if "rds" in svc:
201
+ ident = rid.rsplit(":", 1)[-1] if rid.startswith("arn:") else rid
202
+ sel = f" --db-instance-identifier {Q(ident)}" if ident else ""
203
+ return [VerificationStep("Confirm the engine version that is incurring extended support.",
204
+ f"aws rds describe-db-instances{_region(r)}{sel} --query "
205
+ "'DBInstances[].[DBInstanceIdentifier,Engine,EngineVersion]' --output table",
206
+ "aws"),
207
+ _console("Plan an engine upgrade with the owning team; extended support exists for workloads "
208
+ "that cannot upgrade yet.")]
209
+ if "eks" in svc:
210
+ name = rid.rsplit("/", 1)[-1] if rid else ""
211
+ cmd = f"aws eks describe-cluster{_region(r)} --name {Q(name)} --query 'cluster.version'" if name else None
212
+ return [VerificationStep("Confirm the cluster's Kubernetes version.", cmd, "aws")]
213
+ return [_console("Identify the resource running an end-of-standard-support version.")]
214
+
215
+
216
+ RULES: list[Rule] = [
217
+ Rule(
218
+ "CL-SIG-001", "aws-idle-public-ipv4", "Idle public IPv4 address charges",
219
+ "provider = 'aws' AND (sku ILIKE '%PublicIPv4:IdleAddress%' OR sku ILIKE '%ElasticIP:IdleAddress%')",
220
+ "resource",
221
+ "AWS bills idle addresses under an explicit IdleAddress usage type; the charge itself records that "
222
+ "the address was allocated but not associated during the billed hours.",
223
+ ("Whether the address is still idle today", "Whether it is allowlisted by a customer, partner or firewall",
224
+ "Whether it is reserved for disaster-recovery failover"),
225
+ ("Addresses held for DR failover or blue/green cutover",
226
+ "Addresses allowlisted by third parties that cannot be re-issued"),
227
+ _verify_ipv4, severity="low", providers=("aws",),
228
+ docs=("https://docs.aws.amazon.com/vpc/latest/userguide/vpc-billing-usage-reports.html",),
229
+ ),
230
+ Rule(
231
+ "CL-SIG-002", "nat-gateway-data-processing", "NAT gateway data-processing charges",
232
+ """(provider = 'aws' AND sku ILIKE '%NatGateway-Bytes%')
233
+ OR (provider = 'azure' AND service ILIKE '%NAT Gateway%' AND sku ILIKE '%Data Processed%')
234
+ OR (provider = 'gcp' AND sku ILIKE '%NAT%Data Processing%')
235
+ OR (provider NOT IN ('aws','azure','gcp') AND signature_text LIKE '%nat%'
236
+ AND signature_text LIKE '%process%')""",
237
+ "resource",
238
+ "Per-GB NAT processing is billed on every byte routed through the gateway, including traffic to the "
239
+ "provider's own storage and database services that could use private endpoints instead.",
240
+ ("Which workloads and destinations generate the bytes",
241
+ "Whether gateway or private endpoints already exist for the main destinations"),
242
+ ("Internet egress that genuinely requires NAT", "Traffic patterns that were temporary (migrations, backfills)"),
243
+ _verify_nat,
244
+ ),
245
+ Rule(
246
+ "CL-SIG-003", "cross-zone-transfer", "Regional (inter-zone) data transfer charges",
247
+ """(provider = 'aws' AND sku ILIKE '%DataTransfer-Regional-Bytes%')
248
+ OR (provider = 'gcp' AND sku ILIKE '%Inter Zone%')""",
249
+ "scope",
250
+ "AWS bills DataTransfer-Regional-Bytes for traffic between availability zones (in each direction) and "
251
+ "for same-region traffic over public or Elastic IPs; GCP bills inter-zone egress. Chatty services split "
252
+ "across zones generate this cost silently.",
253
+ ("Which services exchange the traffic", "Whether the cross-zone traffic is required for availability"),
254
+ ("Replication or quorum traffic that exists for high availability",),
255
+ _verify_cross_zone, severity="low", providers=("aws", "gcp"),
256
+ ),
257
+ Rule(
258
+ "CL-SIG-004", "log-ingestion", "Log ingestion charges",
259
+ """(provider = 'aws' AND service ILIKE 'AmazonCloudWatch'
260
+ AND (sku ILIKE '%DataProcessing-Bytes%' OR sku ILIKE '%VendedLog-Bytes%'))
261
+ OR (provider = 'azure' AND service ILIKE '%Log Analytics%' AND sku ILIKE '%Ingestion%')
262
+ OR (provider = 'gcp' AND service ILIKE '%Logging%' AND sku ILIKE '%Log Volume%')""",
263
+ "scope",
264
+ "Log ingestion is billed per GB written, independent of whether anyone queries the logs.",
265
+ ("Which log sources produce the volume", "Retention and regulatory requirements for those logs"),
266
+ ("Audit or security logs that must be retained", "Temporary debug logging during an incident"),
267
+ _verify_logs, severity="low",
268
+ ),
269
+ Rule(
270
+ "CL-SIG-005", "snapshot-storage", "Snapshot storage charges",
271
+ """(provider = 'aws' AND sku ILIKE '%SnapshotUsage%')
272
+ OR (provider = 'azure' AND sku ILIKE '%Snapshot%')
273
+ OR (provider = 'gcp' AND sku ILIKE '%Snapshot%')
274
+ OR (provider NOT IN ('aws','azure','gcp') AND signature_text LIKE '%snapshot%')""",
275
+ "resource",
276
+ "Snapshot storage accumulates silently; the bill shows how much is retained, not whether it is needed.",
277
+ ("The retention policy that created the snapshots", "Whether the source volume still exists",
278
+ "Legal, regulatory or backup obligations attached to them"),
279
+ ("Compliance retention (HIPAA, PCI DSS, SOC 2, legal hold)", "Disaster-recovery restore points"),
280
+ _verify_snapshot, severity="low",
281
+ ),
282
+ Rule(
283
+ "CL-SIG-006", "unused-commitment", "Unused commitment charges",
284
+ """(starts_with(dataset, 'focus') AND commitment_status = 'unused')
285
+ OR (starts_with(dataset, 'aws_cur') AND charge_raw = 'RIFee' AND commitment_status = 'unused')
286
+ OR (starts_with(dataset, 'azure_') AND lower(charge_raw) IN ('unusedreservation', 'unusedsavingsplan'))""",
287
+ "resource",
288
+ "The bill explicitly attributes this amount to commitment capacity that no usage consumed.",
289
+ ("Planned usage that will absorb the commitment later in its term",
290
+ "Exchange, instance-size-flexibility or resale options"),
291
+ ("Commitments bought ahead of a planned ramp-up", "Temporary dips in covered usage"),
292
+ _verify_commitment, severity="medium", prefer_basis="amortized",
293
+ amount="CASE WHEN starts_with(dataset, 'aws_cur') THEN effective_cost "
294
+ "WHEN starts_with(dataset, 'focus') THEN COALESCE(effective_cost, cost) ELSE cost END",
295
+ amount_basis="CASE WHEN starts_with(dataset, 'aws_cur') "
296
+ "OR (starts_with(dataset, 'focus') AND effective_cost IS NOT NULL) "
297
+ "THEN 'effective' ELSE cost_basis END",
298
+ ),
299
+ Rule(
300
+ "CL-SIG-007", "aws-ebs-gp2", "EBS gp2 volume charges (storage-tier review)",
301
+ "provider = 'aws' AND sku ILIKE '%EBS:VolumeUsage.gp2%'",
302
+ "resource",
303
+ "The usage type records gp2 volumes. gp3 has a lower list price per GB with independently provisioned "
304
+ "IOPS and throughput, so gp2 volumes are worth a tier review.",
305
+ ("The volume's IOPS and throughput profile", "Whether the volume is still attached and in use"),
306
+ ("Volumes whose burst profile depends on gp2 size-based IOPS", "Volumes scheduled for deletion anyway"),
307
+ _verify_gp2, severity="low", providers=("aws",),
308
+ ),
309
+ Rule(
310
+ "CL-SIG-008", "aws-extended-support", "Extended support surcharges",
311
+ "provider = 'aws' AND sku ILIKE '%ExtendedSupport%'",
312
+ "resource",
313
+ "AWS bills an explicit surcharge for running engine or Kubernetes versions past standard support.",
314
+ ("Why the version has not been upgraded", "Upgrade testing effort and risk"),
315
+ ("Workloads intentionally pinned while an upgrade is scheduled",),
316
+ _verify_extended_support, severity="medium", providers=("aws",),
317
+ ),
318
+ ]
319
+
320
+
321
+ def rule_pack_hash() -> str:
322
+ blob = json.dumps({"version": RULE_PACK_VERSION, "rules": [r.fingerprint() for r in RULES]},
323
+ sort_keys=True).encode()
324
+ return hashlib.sha256(blob).hexdigest()[:16]
325
+
326
+
327
+ def run_rules(ws: Workspace, *, min_cost: Decimal = Decimal("1"), max_per_rule: int = 200) -> list[Finding]:
328
+ finality = finality_lookup(period_statuses(ws))
329
+ sha = {s.file.source_id: s.file.sha256 for s in ws.sources}
330
+ out: list[Finding] = []
331
+ for rule in RULES:
332
+ if rule.group == "resource":
333
+ key = "COALESCE(resource_id, '')"
334
+ else:
335
+ key = "''"
336
+ rows = ws.rows(f"""
337
+ WITH matched AS (
338
+ SELECT *, {key} AS rkey, {rule.amount} AS observed, {rule.amount_basis} AS observed_basis
339
+ FROM valid WHERE ({rule.where})
340
+ )
341
+ SELECT provider, billing_account_id, sub_account_id, any_value(sub_account_name) AS sub_account_name,
342
+ billing_period, currency, cost_basis, observed_basis, region, any_value(service) AS service,
343
+ rkey, NULLIF(rkey, '') AS resource_id,
344
+ sum(observed) AS amount, sum(cost) FILTER (WHERE cost_basis = 'billed') AS billed,
345
+ CASE WHEN count(effective_cost) = count(*) THEN sum(effective_cost) END AS effective,
346
+ sum(usage_quantity) AS quantity, any_value(usage_unit) AS unit,
347
+ count(*) AS n,
348
+ list(DISTINCT source_id ORDER BY source_id) AS sources,
349
+ list(DISTINCT sku ORDER BY sku)[1:20] AS skus,
350
+ (list(struct_pack(s := source_id, r := source_row) ORDER BY source_id, source_row))[1:5]
351
+ AS samples,
352
+ arg_max(tags, cost) AS tags
353
+ FROM matched v
354
+ WHERE (cost_basis = ? OR NOT EXISTS (
355
+ SELECT 1 FROM matched o
356
+ WHERE o.cost_basis = ? AND o.provider = v.provider
357
+ AND o.billing_account_id IS NOT DISTINCT FROM v.billing_account_id
358
+ AND o.sub_account_id IS NOT DISTINCT FROM v.sub_account_id
359
+ AND o.currency IS NOT DISTINCT FROM v.currency
360
+ AND o.region IS NOT DISTINCT FROM v.region AND o.rkey = v.rkey
361
+ AND o.billing_period IS NOT DISTINCT FROM v.billing_period))
362
+ GROUP BY provider, billing_account_id, sub_account_id, billing_period, currency, cost_basis,
363
+ observed_basis, region, rkey
364
+ HAVING count(observed) = count(*) AND sum(observed) >= ?
365
+ ORDER BY amount DESC, rkey, billing_period
366
+ """, [rule.prefer_basis, rule.prefer_basis, min_cost])
367
+ for r in rows[:max_per_rule]:
368
+ fin = finality.get((r["provider"], r["billing_account_id"], r["billing_period"]), "unknown")
369
+ where = r["resource_id"] or ", ".join(x for x in (r["sub_account_id"], r["region"]) if x) or "the export"
370
+ out.append(Finding(
371
+ rule_id=rule.rule_id,
372
+ title=rule.title,
373
+ summary=f"{rule.title} on {where} in {r['billing_period']}.",
374
+ classification="billing_signature_candidate",
375
+ evidence_level="L2",
376
+ severity=rule.severity,
377
+ provider=r["provider"], currency=r["currency"], billing_period=r["billing_period"],
378
+ period_finality=fin,
379
+ observed_cost=r["amount"],
380
+ observed_billed_cost=r["billed"],
381
+ observed_effective_cost=r["effective"],
382
+ cost_basis=r["observed_basis"],
383
+ billing_account_id=r["billing_account_id"], sub_account_id=r["sub_account_id"],
384
+ resource_id=r["resource_id"],
385
+ resource_id_source="billing_line_item" if r["resource_id"] else None,
386
+ region=r["region"], service=r["service"],
387
+ matched_rows=r["n"],
388
+ source_sha256=[sha[i] for i in r["sources"]],
389
+ sample_rows=[{"source_id": x["s"], "row": x["r"]} for x in r["samples"]],
390
+ matched_values=[x for x in r["skus"] if x],
391
+ unknown_information=list(rule.unknowns),
392
+ potential_false_positives=list(rule.false_positives),
393
+ verification_steps=rule.verify(r),
394
+ owner_routing=owner_routing(r["tags"], r["sub_account_id"], r["sub_account_name"]),
395
+ action_risk="unknown",
396
+ details={"key": r["rkey"], "rationale": rule.rationale, "slug": rule.slug,
397
+ "usage_quantity": r["quantity"], "usage_unit": r["unit"], "docs": list(rule.docs),
398
+ "billed_cost_of_matched_rows": r["billed"]},
399
+ ))
400
+ if len(rows) > max_per_rule:
401
+ rest = rows[max_per_rule:]
402
+ out[-1].details["truncated_groups"] = len(rest)
403
+ return out
@@ -0,0 +1 @@
1
+ """JSON Schemas for CloudLeak output contracts."""