cloudg 0.3.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.
Files changed (75) hide show
  1. cloudg/__init__.py +21 -0
  2. cloudg/api.py +613 -0
  3. cloudg/cli.py +934 -0
  4. cloudg/collectors/__init__.py +5 -0
  5. cloudg/collectors/aws.py +830 -0
  6. cloudg/collectors/azure.py +362 -0
  7. cloudg/collectors/base.py +44 -0
  8. cloudg/collectors/gcp.py +170 -0
  9. cloudg/collectors/multi.py +329 -0
  10. cloudg/config.py +261 -0
  11. cloudg/coverage.py +93 -0
  12. cloudg/credentials.py +451 -0
  13. cloudg/graph/__init__.py +6 -0
  14. cloudg/graph/builder.py +336 -0
  15. cloudg/graph/ontology.py +914 -0
  16. cloudg/graph/rag_export.py +533 -0
  17. cloudg/graph/reachability.py +237 -0
  18. cloudg/normaliser.py +390 -0
  19. cloudg/policies/custodian-aws-security.yml +139 -0
  20. cloudg/policies/custodian-azure.yml +95 -0
  21. cloudg/policies/custodian-gcp.yml +87 -0
  22. cloudg/policies/custodian.yml +131 -0
  23. cloudg/region_discovery.py +330 -0
  24. cloudg/registry.py +142 -0
  25. cloudg/renderers/__init__.py +1 -0
  26. cloudg/renderers/html_report.py +430 -0
  27. cloudg/renderers/json_export.py +65 -0
  28. cloudg/renderers/svg.py +689 -0
  29. cloudg/renderers/terraform_export.py +666 -0
  30. cloudg/retry.py +103 -0
  31. cloudg/rules/cis_aws_v3.yaml +148 -0
  32. cloudg/rules/cis_azure_v2.yaml +142 -0
  33. cloudg/rules/cis_gcp_v3.yaml +133 -0
  34. cloudg/rules/frameworks/aws_foundational_security_best_practices_aws.yaml +1286 -0
  35. cloudg/rules/frameworks/cis_5.0_aws.yaml +280 -0
  36. cloudg/rules/frameworks/cis_5.0_azure.yaml +475 -0
  37. cloudg/rules/frameworks/cis_5.0_gcp.yaml +327 -0
  38. cloudg/rules/frameworks/gdpr_aws.yaml +95 -0
  39. cloudg/rules/frameworks/hipaa_aws.yaml +461 -0
  40. cloudg/rules/frameworks/hipaa_azure.yaml +504 -0
  41. cloudg/rules/frameworks/hipaa_gcp.yaml +211 -0
  42. cloudg/rules/frameworks/iso27001_2022_aws.yaml +789 -0
  43. cloudg/rules/frameworks/iso27001_2022_azure.yaml +477 -0
  44. cloudg/rules/frameworks/iso27001_2022_gcp.yaml +240 -0
  45. cloudg/rules/frameworks/mitre_attack_aws.yaml +596 -0
  46. cloudg/rules/frameworks/mitre_attack_azure.yaml +418 -0
  47. cloudg/rules/frameworks/mitre_attack_gcp.yaml +300 -0
  48. cloudg/rules/frameworks/nist_800_53_revision_5_aws.yaml +3234 -0
  49. cloudg/rules/frameworks/nist_csf_2.0_aws.yaml +828 -0
  50. cloudg/rules/frameworks/pci_4.0_aws.yaml +7108 -0
  51. cloudg/rules/frameworks/pci_4.0_azure.yaml +4696 -0
  52. cloudg/rules/frameworks/pci_4.0_gcp.yaml +5405 -0
  53. cloudg/rules/frameworks/soc2_aws.yaml +421 -0
  54. cloudg/rules/frameworks/soc2_azure.yaml +477 -0
  55. cloudg/rules/frameworks/soc2_gcp.yaml +342 -0
  56. cloudg/rules/gdpr.yaml +56 -0
  57. cloudg/rules/hipaa_security_rule.yaml +83 -0
  58. cloudg/rules/iso_27001_2022.yaml +88 -0
  59. cloudg/rules/nist_800_53.yaml +134 -0
  60. cloudg/rules/pci_dss_v4.yaml +108 -0
  61. cloudg/rules/soc2_tsc.yaml +93 -0
  62. cloudg/scanners/__init__.py +1 -0
  63. cloudg/scanners/checkov.py +174 -0
  64. cloudg/scanners/iam_linter.py +200 -0
  65. cloudg/scanners/prowler.py +237 -0
  66. cloudg/scanners/scoutsuite.py +163 -0
  67. cloudg/scanners/trivy.py +339 -0
  68. cloudg/schema/__init__.py +25 -0
  69. cloudg/schema/models.py +260 -0
  70. cloudg/templates/report.html.j2 +828 -0
  71. cloudg-0.3.0.dist-info/METADATA +330 -0
  72. cloudg-0.3.0.dist-info/RECORD +75 -0
  73. cloudg-0.3.0.dist-info/WHEEL +4 -0
  74. cloudg-0.3.0.dist-info/entry_points.txt +14 -0
  75. cloudg-0.3.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,430 @@
1
+ """HTML interactive report generator using Jinja2."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import logging
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ from jinja2 import Environment, FileSystemLoader, select_autoescape
11
+
12
+ from cloudg.schema.models import ScanResult
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+ # Template directory candidates — the packaged directory ships in the
17
+ # wheel, the rest keep old checkouts and Docker layouts working
18
+ _TEMPLATE_DIR_CANDIDATES = [
19
+ Path(__file__).parent.parent / "templates", # packaged: cloudg/templates
20
+ Path(__file__).parent.parent.parent / "templates", # legacy repo-root layout
21
+ Path("/app/templates"), # legacy Docker runtime
22
+ Path("./templates"), # CWD fallback
23
+ ]
24
+
25
+
26
+ def _resolve_template_dir() -> Path:
27
+ """Find the first template directory that contains report.html.j2."""
28
+ for candidate in _TEMPLATE_DIR_CANDIDATES:
29
+ if (candidate / "report.html.j2").exists():
30
+ return candidate
31
+ # Fall back to first candidate (will trigger fallback report)
32
+ return _TEMPLATE_DIR_CANDIDATES[0]
33
+
34
+
35
+ class HTMLReportGenerator:
36
+ """Generates a self-contained interactive HTML report.
37
+
38
+ Features:
39
+ - D3.js force-directed topology map
40
+ - Filterable findings table
41
+ - Chart.js severity and resource charts
42
+ - Compliance scorecard
43
+ - Per-finding detail panels
44
+ """
45
+
46
+ def __init__(
47
+ self,
48
+ template_dir: str | None = None,
49
+ output_dir: str = ".",
50
+ ) -> None:
51
+ self._template_dir = Path(template_dir) if template_dir else _resolve_template_dir()
52
+ self._output_dir = Path(output_dir)
53
+
54
+ def generate(
55
+ self,
56
+ scan_result: ScanResult,
57
+ graph_json: dict[str, Any] | None = None,
58
+ filename: str = "report.html",
59
+ ) -> Path:
60
+ """Generate the HTML report.
61
+
62
+ Args:
63
+ scan_result: Normalised scan results.
64
+ graph_json: D3.js graph data for topology visualisation.
65
+ filename: Output filename.
66
+
67
+ Returns:
68
+ Path to the generated HTML file.
69
+ """
70
+ self._output_dir.mkdir(parents=True, exist_ok=True)
71
+ output_path = self._output_dir / filename
72
+
73
+ # Prepare template data
74
+ template_data = self._prepare_data(scan_result, graph_json)
75
+
76
+ # Render template
77
+ if self._template_dir.exists():
78
+ env = Environment(
79
+ loader=FileSystemLoader(str(self._template_dir)),
80
+ autoescape=select_autoescape(["html"]),
81
+ )
82
+ try:
83
+ template = env.get_template("report.html.j2")
84
+ html = template.render(**template_data)
85
+ except Exception as exc:
86
+ logger.warning("Template rendering failed, using fallback: %s", exc)
87
+ html = self._fallback_report(template_data)
88
+ else:
89
+ logger.warning("Template directory not found, using fallback report")
90
+ html = self._fallback_report(template_data)
91
+
92
+ with open(output_path, "w") as f:
93
+ f.write(html)
94
+
95
+ logger.info("Generated HTML report at %s", output_path)
96
+ return output_path
97
+
98
+ def _prepare_data(
99
+ self,
100
+ scan_result: ScanResult,
101
+ graph_json: dict[str, Any] | None,
102
+ ) -> dict[str, Any]:
103
+ """Prepare data for template rendering."""
104
+ # Severity breakdown
105
+ severity_counts: dict[str, int] = {
106
+ "CRITICAL": 0,
107
+ "HIGH": 0,
108
+ "MEDIUM": 0,
109
+ "LOW": 0,
110
+ "INFO": 0,
111
+ }
112
+ for finding in scan_result.findings:
113
+ severity_counts[finding.severity.value] = (
114
+ severity_counts.get(finding.severity.value, 0) + 1
115
+ )
116
+
117
+ # Resource type breakdown
118
+ resource_types: dict[str, int] = {}
119
+ for asset in scan_result.assets:
120
+ resource_types[asset.asset_type.value] = (
121
+ resource_types.get(asset.asset_type.value, 0) + 1
122
+ )
123
+
124
+ # Source tool breakdown
125
+ source_tools: dict[str, int] = {}
126
+ for finding in scan_result.findings:
127
+ source_tools[finding.source_tool] = source_tools.get(finding.source_tool, 0) + 1
128
+
129
+ # Compliance framework summary
130
+ compliance_summary: dict[str, dict[str, int]] = {}
131
+ for result in scan_result.compliance:
132
+ if result.framework not in compliance_summary:
133
+ compliance_summary[result.framework] = {"pass": 0, "fail": 0}
134
+ if result.status.value == "PASS":
135
+ compliance_summary[result.framework]["pass"] += 1
136
+ else:
137
+ compliance_summary[result.framework]["fail"] += 1
138
+
139
+ # Findings per resource (for topology badges)
140
+ findings_per_resource: dict[str, dict[str, int]] = {}
141
+ for finding in scan_result.findings:
142
+ rid = finding.resource_id or finding.resource_arn or ""
143
+ if rid not in findings_per_resource:
144
+ findings_per_resource[rid] = {
145
+ "total": 0,
146
+ "CRITICAL": 0,
147
+ "HIGH": 0,
148
+ "MEDIUM": 0,
149
+ "LOW": 0,
150
+ "INFO": 0,
151
+ }
152
+ findings_per_resource[rid]["total"] += 1
153
+ findings_per_resource[rid][finding.severity.value] += 1
154
+
155
+ # Build hierarchical topology data
156
+ hierarchy = self._build_hierarchy(scan_result, findings_per_resource)
157
+
158
+ # Enrich graph with findings as nodes + ontology edges
159
+ enriched_graph = self._enrich_graph_with_findings(
160
+ graph_json or {"nodes": [], "links": []},
161
+ scan_result,
162
+ )
163
+
164
+ return {
165
+ "scan_id": scan_result.scan_id,
166
+ "provider": scan_result.provider.value if scan_result.provider else "Multi-Cloud",
167
+ "account_id": scan_result.account_id or "N/A",
168
+ "started_at": str(scan_result.started_at),
169
+ "completed_at": str(scan_result.completed_at),
170
+ "total_assets": len(scan_result.assets),
171
+ "total_findings": len(scan_result.findings),
172
+ "severity_counts": severity_counts,
173
+ "severity_counts_json": json.dumps(severity_counts),
174
+ "resource_types": resource_types,
175
+ "resource_types_json": json.dumps(resource_types),
176
+ "source_tools": source_tools,
177
+ "source_tools_json": json.dumps(source_tools),
178
+ "compliance_summary": compliance_summary,
179
+ "compliance_summary_json": json.dumps(compliance_summary),
180
+ "findings": [f.model_dump(mode="json") for f in scan_result.findings],
181
+ "findings_json": json.dumps(
182
+ [f.model_dump(mode="json") for f in scan_result.findings],
183
+ default=str,
184
+ ),
185
+ "assets": [a.model_dump(exclude={"raw_data"}, mode="json") for a in scan_result.assets],
186
+ "assets_json": json.dumps(
187
+ [a.model_dump(exclude={"raw_data"}, mode="json") for a in scan_result.assets],
188
+ default=str,
189
+ ),
190
+ "graph_json": json.dumps(enriched_graph, default=str),
191
+ "hierarchy_json": json.dumps(hierarchy, default=str),
192
+ "findings_per_resource_json": json.dumps(findings_per_resource, default=str),
193
+ }
194
+
195
+ def _build_hierarchy(
196
+ self,
197
+ scan_result: ScanResult,
198
+ findings_per_resource: dict[str, dict[str, int]],
199
+ ) -> dict[str, Any]:
200
+ """Build hierarchical tree: Account → Region → VPC → Subnet → Resources."""
201
+ from collections import defaultdict
202
+
203
+ # Group assets by region → VPC → subnet
204
+ regions: dict[str, dict[str, dict[str, list[dict[str, Any]]]]] = defaultdict(
205
+ lambda: defaultdict(lambda: defaultdict(list))
206
+ )
207
+ ungrouped: list[dict[str, Any]] = []
208
+
209
+ for asset in scan_result.assets:
210
+ asset_data = {
211
+ "id": asset.id,
212
+ "name": asset.name,
213
+ "type": asset.asset_type.value,
214
+ "arn": asset.arn or "",
215
+ "internet_exposed": asset.is_internet_exposed,
216
+ "findings": findings_per_resource.get(
217
+ asset.id, findings_per_resource.get(asset.arn or "", {})
218
+ ),
219
+ }
220
+ region = asset.region or "global"
221
+ vpc_id = asset.metadata.get("vpc_id", "")
222
+ subnet_id = asset.metadata.get("subnet_id", "")
223
+
224
+ if asset.asset_type.value in ("VPC", "VNET"):
225
+ vpc_id = asset.metadata.get("vpc_id", asset.name)
226
+ regions[region][vpc_id]["_vpc_meta"] = [] # type: ignore[assignment]
227
+ regions[region][vpc_id]["_vpc_meta"].append(asset_data)
228
+ elif asset.asset_type.value == "SUBNET":
229
+ regions[region][vpc_id or "_no_vpc"][subnet_id or asset.name].append(asset_data)
230
+ elif vpc_id or subnet_id:
231
+ regions[region][vpc_id or "_no_vpc"][subnet_id or "_no_subnet"].append(asset_data)
232
+ else:
233
+ ungrouped.append(asset_data)
234
+
235
+ # Build tree structure
236
+ tree: dict[str, Any] = {
237
+ "name": scan_result.account_id or "Cloud Account",
238
+ "type": "account",
239
+ "children": [],
240
+ }
241
+ for region_name, vpcs in sorted(regions.items()):
242
+ region_node: dict[str, Any] = {"name": region_name, "type": "region", "children": []}
243
+ for vpc_name, subnets in sorted(vpcs.items()):
244
+ vpc_node: dict[str, Any] = {"name": vpc_name, "type": "vpc", "children": []}
245
+ for subnet_name, resources in sorted(subnets.items()):
246
+ if subnet_name == "_vpc_meta":
247
+ continue
248
+ subnet_node: dict[str, Any] = {
249
+ "name": subnet_name,
250
+ "type": "subnet",
251
+ "children": resources,
252
+ }
253
+ vpc_node["children"].append(subnet_node)
254
+ region_node["children"].append(vpc_node)
255
+ tree["children"].append(region_node)
256
+
257
+ if ungrouped:
258
+ tree["children"].append(
259
+ {"name": "Global / Ungrouped", "type": "global", "children": ungrouped}
260
+ )
261
+
262
+ return tree
263
+
264
+ def _enrich_graph_with_findings(
265
+ self,
266
+ graph: dict[str, Any],
267
+ scan_result: ScanResult,
268
+ ) -> dict[str, Any]:
269
+ """Inject findings + compliance frameworks as visible nodes in the D3 graph.
270
+
271
+ - Each finding becomes a SecurityFinding node linked to its resource via FINDING_AFFECTS
272
+ - Each compliance framework becomes a ComplianceFramework node linked via COMPLIANCE_GOVERNS
273
+ """
274
+ nodes = list(graph.get("nodes", []))
275
+ links = list(graph.get("links", []))
276
+ existing_ids = {n.get("id") for n in nodes}
277
+
278
+ # Map resource ARNs → node IDs for connecting findings
279
+ arn_to_node_id: dict[str, str] = {}
280
+ for n in nodes:
281
+ if n.get("arn"):
282
+ arn_to_node_id[n["arn"]] = n["id"]
283
+ arn_to_node_id[n.get("id", "")] = n["id"]
284
+
285
+ # Track compliance frameworks for dedup
286
+ fw_nodes_added: set[str] = set()
287
+
288
+ for finding in scan_result.findings:
289
+ finding_id = f"finding_{finding.id}"
290
+ if finding_id in existing_ids:
291
+ continue
292
+
293
+ # Finding node
294
+ nodes.append(
295
+ {
296
+ "id": finding_id,
297
+ "name": (finding.title or "")[:60],
298
+ "type": "SECURITY_FINDING",
299
+ "severity": finding.severity.value,
300
+ "source_tool": finding.source_tool,
301
+ "risk_score": finding.risk_score,
302
+ "is_external": False,
303
+ "is_internet_exposed": False,
304
+ "region": "",
305
+ "arn": "",
306
+ }
307
+ )
308
+ existing_ids.add(finding_id)
309
+
310
+ # FINDING_AFFECTS edge → resource
311
+ target_id = arn_to_node_id.get(finding.resource_arn or "") or arn_to_node_id.get(
312
+ finding.resource_id or ""
313
+ )
314
+ if target_id:
315
+ links.append(
316
+ {
317
+ "source": finding_id,
318
+ "target": target_id,
319
+ "relation": "FINDING_AFFECTS",
320
+ "severity": finding.severity.value,
321
+ }
322
+ )
323
+
324
+ # Compliance framework nodes + COMPLIANCE_GOVERNS edges
325
+ for fw in finding.compliance_frameworks or []:
326
+ fw_id = f"compliance_{fw}"
327
+ if fw_id not in fw_nodes_added:
328
+ nodes.append(
329
+ {
330
+ "id": fw_id,
331
+ "name": fw,
332
+ "type": "COMPLIANCE_FRAMEWORK",
333
+ "severity": "",
334
+ "source_tool": "",
335
+ "risk_score": 0,
336
+ "is_external": False,
337
+ "is_internet_exposed": False,
338
+ "region": "",
339
+ "arn": "",
340
+ }
341
+ )
342
+ fw_nodes_added.add(fw_id)
343
+ existing_ids.add(fw_id)
344
+
345
+ # COMPLIANCE_GOVERNS → finding
346
+ links.append(
347
+ {
348
+ "source": fw_id,
349
+ "target": finding_id,
350
+ "relation": "COMPLIANCE_GOVERNS",
351
+ }
352
+ )
353
+
354
+ return {"nodes": nodes, "links": links}
355
+
356
+ def _fallback_report(self, data: dict[str, Any]) -> str:
357
+ """Generate a simple fallback HTML report if Jinja2 template is missing."""
358
+ findings_rows = ""
359
+ for f in data["findings"]:
360
+ sev = f.get("severity", "INFO")
361
+ sev_class = {
362
+ "CRITICAL": "color:#E74C3C;font-weight:bold",
363
+ "HIGH": "color:#E67E22;font-weight:bold",
364
+ "MEDIUM": "color:#F1C40F",
365
+ "LOW": "color:#3498DB",
366
+ "INFO": "color:#95A5A6",
367
+ }.get(sev, "")
368
+ findings_rows += f"""
369
+ <tr>
370
+ <td style="{sev_class}">{sev}</td>
371
+ <td>{f.get("title", "")}</td>
372
+ <td><code>{f.get("resource_arn", f.get("resource_id", ""))}</code></td>
373
+ <td>{f.get("source_tool", "")}</td>
374
+ <td>{f.get("remediation", "")[:100]}</td>
375
+ </tr>"""
376
+
377
+ return f"""<!DOCTYPE html>
378
+ <html lang="en">
379
+ <head>
380
+ <meta charset="UTF-8">
381
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
382
+ <title>CloudG Security Report</title>
383
+ <style>
384
+ * {{ margin: 0; padding: 0; box-sizing: border-box; }}
385
+ body {{ font-family: 'Inter', -apple-system, sans-serif; background: #0F172A; color: #E2E8F0; }}
386
+ .container {{ max-width: 1400px; margin: 0 auto; padding: 20px; }}
387
+ h1 {{ color: #F8FAFC; margin-bottom: 8px; font-size: 28px; }}
388
+ .subtitle {{ color: #94A3B8; margin-bottom: 30px; }}
389
+ .cards {{ display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 16px; margin-bottom: 30px; }}
390
+ .card {{
391
+ background: #1E293B; border-radius: 12px; padding: 20px;
392
+ border: 1px solid #334155;
393
+ }}
394
+ .card h3 {{ color: #94A3B8; font-size: 12px; text-transform: uppercase; letter-spacing: 1px; }}
395
+ .card .value {{ font-size: 36px; font-weight: 700; color: #F8FAFC; margin-top: 8px; }}
396
+ .card.critical .value {{ color: #EF4444; }}
397
+ .card.high .value {{ color: #F97316; }}
398
+ .card.medium .value {{ color: #EAB308; }}
399
+ table {{
400
+ width: 100%; border-collapse: collapse; background: #1E293B;
401
+ border-radius: 12px; overflow: hidden; margin-top: 20px;
402
+ }}
403
+ th {{ background: #334155; color: #94A3B8; padding: 12px 16px; text-align: left; font-size: 12px; text-transform: uppercase; letter-spacing: 1px; }}
404
+ td {{ padding: 12px 16px; border-bottom: 1px solid #334155; font-size: 14px; }}
405
+ tr:hover {{ background: #334155; }}
406
+ code {{ background: #334155; padding: 2px 6px; border-radius: 4px; font-size: 12px; }}
407
+ h2 {{ color: #F8FAFC; margin: 30px 0 10px; }}
408
+ </style>
409
+ </head>
410
+ <body>
411
+ <div class="container">
412
+ <h1>☁️ CloudG Security Report</h1>
413
+ <p class="subtitle">Scan ID: {data["scan_id"]} | Provider: {data["provider"]} | Account: {data["account_id"]}</p>
414
+
415
+ <div class="cards">
416
+ <div class="card"><h3>Total Assets</h3><div class="value">{data["total_assets"]}</div></div>
417
+ <div class="card"><h3>Total Findings</h3><div class="value">{data["total_findings"]}</div></div>
418
+ <div class="card critical"><h3>Critical</h3><div class="value">{data["severity_counts"].get("CRITICAL", 0)}</div></div>
419
+ <div class="card high"><h3>High</h3><div class="value">{data["severity_counts"].get("HIGH", 0)}</div></div>
420
+ <div class="card medium"><h3>Medium</h3><div class="value">{data["severity_counts"].get("MEDIUM", 0)}</div></div>
421
+ </div>
422
+
423
+ <h2>Security Findings</h2>
424
+ <table>
425
+ <thead><tr><th>Severity</th><th>Title</th><th>Resource</th><th>Source</th><th>Remediation</th></tr></thead>
426
+ <tbody>{findings_rows}</tbody>
427
+ </table>
428
+ </div>
429
+ </body>
430
+ </html>"""
@@ -0,0 +1,65 @@
1
+ """JSON findings export renderer."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import logging
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ from cloudg.schema.models import ScanResult
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+
15
+ class JSONExporter:
16
+ """Exports scan results to a findings.json file.
17
+
18
+ Contains: full asset inventory, all findings, graph data, compliance mappings.
19
+ """
20
+
21
+ def __init__(self, output_dir: str = ".") -> None:
22
+ self._output_dir = Path(output_dir)
23
+
24
+ def export(
25
+ self,
26
+ scan_result: ScanResult,
27
+ graph_json: dict[str, Any] | None = None,
28
+ filename: str = "findings.json",
29
+ ) -> Path:
30
+ """Export scan results to JSON.
31
+
32
+ Args:
33
+ scan_result: The normalised scan result.
34
+ graph_json: Optional D3.js graph data.
35
+ filename: Output filename.
36
+
37
+ Returns:
38
+ Path to the generated JSON file.
39
+ """
40
+ self._output_dir.mkdir(parents=True, exist_ok=True)
41
+ output_path = self._output_dir / filename
42
+
43
+ export_data = {
44
+ "metadata": {
45
+ "scan_id": scan_result.scan_id,
46
+ "provider": scan_result.provider.value if scan_result.provider else None,
47
+ "account_id": scan_result.account_id,
48
+ "region": scan_result.region,
49
+ "started_at": str(scan_result.started_at),
50
+ "completed_at": str(scan_result.completed_at),
51
+ },
52
+ "summary": scan_result.summary,
53
+ "assets": [
54
+ asset.model_dump(exclude={"raw_data"}, mode="json") for asset in scan_result.assets
55
+ ],
56
+ "findings": [finding.model_dump(mode="json") for finding in scan_result.findings],
57
+ "compliance": [result.model_dump(mode="json") for result in scan_result.compliance],
58
+ "graph": graph_json or {"nodes": [], "links": []},
59
+ }
60
+
61
+ with open(output_path, "w") as f:
62
+ json.dump(export_data, f, indent=2, default=str)
63
+
64
+ logger.info("Exported findings to %s", output_path)
65
+ return output_path