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.
- cloudg/__init__.py +21 -0
- cloudg/api.py +613 -0
- cloudg/cli.py +934 -0
- cloudg/collectors/__init__.py +5 -0
- cloudg/collectors/aws.py +830 -0
- cloudg/collectors/azure.py +362 -0
- cloudg/collectors/base.py +44 -0
- cloudg/collectors/gcp.py +170 -0
- cloudg/collectors/multi.py +329 -0
- cloudg/config.py +261 -0
- cloudg/coverage.py +93 -0
- cloudg/credentials.py +451 -0
- cloudg/graph/__init__.py +6 -0
- cloudg/graph/builder.py +336 -0
- cloudg/graph/ontology.py +914 -0
- cloudg/graph/rag_export.py +533 -0
- cloudg/graph/reachability.py +237 -0
- cloudg/normaliser.py +390 -0
- cloudg/policies/custodian-aws-security.yml +139 -0
- cloudg/policies/custodian-azure.yml +95 -0
- cloudg/policies/custodian-gcp.yml +87 -0
- cloudg/policies/custodian.yml +131 -0
- cloudg/region_discovery.py +330 -0
- cloudg/registry.py +142 -0
- cloudg/renderers/__init__.py +1 -0
- cloudg/renderers/html_report.py +430 -0
- cloudg/renderers/json_export.py +65 -0
- cloudg/renderers/svg.py +689 -0
- cloudg/renderers/terraform_export.py +666 -0
- cloudg/retry.py +103 -0
- cloudg/rules/cis_aws_v3.yaml +148 -0
- cloudg/rules/cis_azure_v2.yaml +142 -0
- cloudg/rules/cis_gcp_v3.yaml +133 -0
- cloudg/rules/frameworks/aws_foundational_security_best_practices_aws.yaml +1286 -0
- cloudg/rules/frameworks/cis_5.0_aws.yaml +280 -0
- cloudg/rules/frameworks/cis_5.0_azure.yaml +475 -0
- cloudg/rules/frameworks/cis_5.0_gcp.yaml +327 -0
- cloudg/rules/frameworks/gdpr_aws.yaml +95 -0
- cloudg/rules/frameworks/hipaa_aws.yaml +461 -0
- cloudg/rules/frameworks/hipaa_azure.yaml +504 -0
- cloudg/rules/frameworks/hipaa_gcp.yaml +211 -0
- cloudg/rules/frameworks/iso27001_2022_aws.yaml +789 -0
- cloudg/rules/frameworks/iso27001_2022_azure.yaml +477 -0
- cloudg/rules/frameworks/iso27001_2022_gcp.yaml +240 -0
- cloudg/rules/frameworks/mitre_attack_aws.yaml +596 -0
- cloudg/rules/frameworks/mitre_attack_azure.yaml +418 -0
- cloudg/rules/frameworks/mitre_attack_gcp.yaml +300 -0
- cloudg/rules/frameworks/nist_800_53_revision_5_aws.yaml +3234 -0
- cloudg/rules/frameworks/nist_csf_2.0_aws.yaml +828 -0
- cloudg/rules/frameworks/pci_4.0_aws.yaml +7108 -0
- cloudg/rules/frameworks/pci_4.0_azure.yaml +4696 -0
- cloudg/rules/frameworks/pci_4.0_gcp.yaml +5405 -0
- cloudg/rules/frameworks/soc2_aws.yaml +421 -0
- cloudg/rules/frameworks/soc2_azure.yaml +477 -0
- cloudg/rules/frameworks/soc2_gcp.yaml +342 -0
- cloudg/rules/gdpr.yaml +56 -0
- cloudg/rules/hipaa_security_rule.yaml +83 -0
- cloudg/rules/iso_27001_2022.yaml +88 -0
- cloudg/rules/nist_800_53.yaml +134 -0
- cloudg/rules/pci_dss_v4.yaml +108 -0
- cloudg/rules/soc2_tsc.yaml +93 -0
- cloudg/scanners/__init__.py +1 -0
- cloudg/scanners/checkov.py +174 -0
- cloudg/scanners/iam_linter.py +200 -0
- cloudg/scanners/prowler.py +237 -0
- cloudg/scanners/scoutsuite.py +163 -0
- cloudg/scanners/trivy.py +339 -0
- cloudg/schema/__init__.py +25 -0
- cloudg/schema/models.py +260 -0
- cloudg/templates/report.html.j2 +828 -0
- cloudg-0.3.0.dist-info/METADATA +330 -0
- cloudg-0.3.0.dist-info/RECORD +75 -0
- cloudg-0.3.0.dist-info/WHEEL +4 -0
- cloudg-0.3.0.dist-info/entry_points.txt +14 -0
- cloudg-0.3.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,533 @@
|
|
|
1
|
+
"""RAG-ready export — generates chunked, metadata-enriched representations
|
|
2
|
+
of the cloud infrastructure graph for retrieval-augmented generation.
|
|
3
|
+
|
|
4
|
+
Three complementary chunking strategies:
|
|
5
|
+
1. Entity-centric: one chunk per cloud asset with 1-hop neighbourhood
|
|
6
|
+
2. Community-detection: Louvain clusters with aggregate summaries
|
|
7
|
+
3. Relation-group: one chunk per semantic relation group (Network, IAM, etc.)
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import json
|
|
13
|
+
import logging
|
|
14
|
+
from collections import defaultdict
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
import networkx as nx
|
|
19
|
+
|
|
20
|
+
from cloudg.graph.ontology import (
|
|
21
|
+
RelationGroup,
|
|
22
|
+
get_relation_group,
|
|
23
|
+
infer_relations,
|
|
24
|
+
)
|
|
25
|
+
from cloudg.schema.models import (
|
|
26
|
+
CloudAsset,
|
|
27
|
+
Finding,
|
|
28
|
+
NetworkEdge,
|
|
29
|
+
Severity,
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
logger = logging.getLogger(__name__)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
# ---------------------------------------------------------------------------
|
|
36
|
+
# Chunk models
|
|
37
|
+
# ---------------------------------------------------------------------------
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class RAGChunk:
|
|
41
|
+
"""A single chunk for RAG retrieval."""
|
|
42
|
+
|
|
43
|
+
def __init__(
|
|
44
|
+
self,
|
|
45
|
+
chunk_id: str,
|
|
46
|
+
chunk_type: str,
|
|
47
|
+
content: str,
|
|
48
|
+
metadata: dict[str, Any],
|
|
49
|
+
relations: list[dict[str, str]] | None = None,
|
|
50
|
+
) -> None:
|
|
51
|
+
self.chunk_id = chunk_id
|
|
52
|
+
self.chunk_type = chunk_type
|
|
53
|
+
self.content = content
|
|
54
|
+
self.metadata = metadata
|
|
55
|
+
self.relations = relations or []
|
|
56
|
+
|
|
57
|
+
def to_dict(self) -> dict[str, Any]:
|
|
58
|
+
return {
|
|
59
|
+
"chunk_id": self.chunk_id,
|
|
60
|
+
"chunk_type": self.chunk_type,
|
|
61
|
+
"content": self.content,
|
|
62
|
+
"metadata": self.metadata,
|
|
63
|
+
"relations": self.relations,
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
# ---------------------------------------------------------------------------
|
|
68
|
+
# Community detection helper
|
|
69
|
+
# ---------------------------------------------------------------------------
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _detect_communities(graph: nx.DiGraph) -> dict[str, int]:
|
|
73
|
+
"""Run Louvain community detection on the graph.
|
|
74
|
+
|
|
75
|
+
Returns mapping of node_id → community_id.
|
|
76
|
+
"""
|
|
77
|
+
try:
|
|
78
|
+
import community as community_louvain
|
|
79
|
+
except ImportError:
|
|
80
|
+
logger.warning(
|
|
81
|
+
"python-louvain not installed. Falling back to connected components. "
|
|
82
|
+
"Install with: pip install python-louvain"
|
|
83
|
+
)
|
|
84
|
+
# Fallback: use connected components as pseudo-communities
|
|
85
|
+
undirected = graph.to_undirected()
|
|
86
|
+
mapping: dict[str, int] = {}
|
|
87
|
+
for idx, component in enumerate(nx.connected_components(undirected)):
|
|
88
|
+
for node in component:
|
|
89
|
+
mapping[node] = idx
|
|
90
|
+
return mapping
|
|
91
|
+
|
|
92
|
+
undirected = graph.to_undirected()
|
|
93
|
+
partition = community_louvain.best_partition(undirected)
|
|
94
|
+
return partition
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
# ---------------------------------------------------------------------------
|
|
98
|
+
# RAG Exporter
|
|
99
|
+
# ---------------------------------------------------------------------------
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class RAGExporter:
|
|
103
|
+
"""Generates RAG-ready chunks from cloud infrastructure data.
|
|
104
|
+
|
|
105
|
+
Three strategies, each producing different chunk types for retrieval:
|
|
106
|
+
|
|
107
|
+
1. **Entity-centric**: one chunk per asset with all direct relations,
|
|
108
|
+
findings, and compliance status. Best for "tell me about resource X".
|
|
109
|
+
|
|
110
|
+
2. **Community-detection**: Louvain-clustered groups of tightly-connected
|
|
111
|
+
resources. Best for "what's the blast radius of this subnet?".
|
|
112
|
+
|
|
113
|
+
3. **Relation-group**: all triples of a semantic group (Network, IAM, etc.).
|
|
114
|
+
Best for "show me all IAM access rules" or "list all network paths".
|
|
115
|
+
"""
|
|
116
|
+
|
|
117
|
+
def __init__(self, max_chunk_tokens: int = 2000) -> None:
|
|
118
|
+
self._max_tokens = max_chunk_tokens
|
|
119
|
+
|
|
120
|
+
# ------------------------------------------------------------------
|
|
121
|
+
# Strategy 1: Entity-centric chunks
|
|
122
|
+
# ------------------------------------------------------------------
|
|
123
|
+
|
|
124
|
+
def export_entity_chunks(
|
|
125
|
+
self,
|
|
126
|
+
assets: list[CloudAsset],
|
|
127
|
+
edges: list[NetworkEdge],
|
|
128
|
+
findings: list[Finding] | None = None,
|
|
129
|
+
) -> list[RAGChunk]:
|
|
130
|
+
"""Generate one chunk per cloud asset with 1-hop neighbourhood."""
|
|
131
|
+
chunks: list[RAGChunk] = []
|
|
132
|
+
assets_by_id = {a.id: a for a in assets}
|
|
133
|
+
findings_by_resource: dict[str, list[Finding]] = defaultdict(list)
|
|
134
|
+
|
|
135
|
+
if findings:
|
|
136
|
+
for f in findings:
|
|
137
|
+
findings_by_resource[f.resource_id].append(f)
|
|
138
|
+
|
|
139
|
+
# Build adjacency from edges
|
|
140
|
+
outgoing: dict[str, list[NetworkEdge]] = defaultdict(list)
|
|
141
|
+
incoming: dict[str, list[NetworkEdge]] = defaultdict(list)
|
|
142
|
+
for edge in edges:
|
|
143
|
+
outgoing[edge.source_id].append(edge)
|
|
144
|
+
incoming[edge.target_id].append(edge)
|
|
145
|
+
|
|
146
|
+
for asset in assets:
|
|
147
|
+
# Build content text
|
|
148
|
+
content_lines = [
|
|
149
|
+
f"Resource: {asset.name}",
|
|
150
|
+
f"Type: {asset.asset_type.value}",
|
|
151
|
+
f"Provider: {asset.provider.value}",
|
|
152
|
+
f"Region: {asset.region}",
|
|
153
|
+
]
|
|
154
|
+
if asset.arn:
|
|
155
|
+
content_lines.append(f"ARN: {asset.arn}")
|
|
156
|
+
if asset.account_id:
|
|
157
|
+
content_lines.append(f"Account: {asset.account_id}")
|
|
158
|
+
if asset.is_internet_exposed:
|
|
159
|
+
content_lines.append("⚠ INTERNET EXPOSED")
|
|
160
|
+
if asset.tags:
|
|
161
|
+
content_lines.append(f"Tags: {json.dumps(asset.tags)}")
|
|
162
|
+
|
|
163
|
+
# Relations
|
|
164
|
+
chunk_relations: list[dict[str, str]] = []
|
|
165
|
+
relation_types_set: set[str] = set()
|
|
166
|
+
|
|
167
|
+
# Outgoing edges
|
|
168
|
+
for edge in outgoing.get(asset.id, []):
|
|
169
|
+
inferred = infer_relations(edge, assets_by_id)
|
|
170
|
+
tgt_name = assets_by_id.get(edge.target_id, None)
|
|
171
|
+
tgt_label = tgt_name.name if tgt_name else edge.target_id
|
|
172
|
+
for rel in inferred:
|
|
173
|
+
evidence_parts = []
|
|
174
|
+
if edge.port_range:
|
|
175
|
+
evidence_parts.append(f"port {edge.port_range}")
|
|
176
|
+
if edge.protocol:
|
|
177
|
+
evidence_parts.append(edge.protocol)
|
|
178
|
+
if edge.cidr:
|
|
179
|
+
evidence_parts.append(f"cidr {edge.cidr}")
|
|
180
|
+
chunk_relations.append(
|
|
181
|
+
{
|
|
182
|
+
"predicate": rel.value,
|
|
183
|
+
"direction": "outgoing",
|
|
184
|
+
"object": tgt_label,
|
|
185
|
+
"object_id": edge.target_id,
|
|
186
|
+
"evidence": ", ".join(evidence_parts) if evidence_parts else "",
|
|
187
|
+
}
|
|
188
|
+
)
|
|
189
|
+
relation_types_set.add(rel.value)
|
|
190
|
+
|
|
191
|
+
# Incoming edges
|
|
192
|
+
for edge in incoming.get(asset.id, []):
|
|
193
|
+
inferred = infer_relations(edge, assets_by_id)
|
|
194
|
+
src_name = assets_by_id.get(edge.source_id, None)
|
|
195
|
+
src_label = src_name.name if src_name else edge.source_id
|
|
196
|
+
for rel in inferred:
|
|
197
|
+
chunk_relations.append(
|
|
198
|
+
{
|
|
199
|
+
"predicate": rel.value,
|
|
200
|
+
"direction": "incoming",
|
|
201
|
+
"object": src_label,
|
|
202
|
+
"object_id": edge.source_id,
|
|
203
|
+
"evidence": "",
|
|
204
|
+
}
|
|
205
|
+
)
|
|
206
|
+
relation_types_set.add(rel.value)
|
|
207
|
+
|
|
208
|
+
# Add relations to content
|
|
209
|
+
if chunk_relations:
|
|
210
|
+
content_lines.append(f"\nRelations ({len(chunk_relations)}):")
|
|
211
|
+
for rel in chunk_relations[:30]: # Cap to avoid huge chunks
|
|
212
|
+
arrow = "→" if rel["direction"] == "outgoing" else "←"
|
|
213
|
+
content_lines.append(f" {arrow} {rel['predicate']}: {rel['object']}")
|
|
214
|
+
|
|
215
|
+
# Findings
|
|
216
|
+
resource_findings = findings_by_resource.get(asset.id, [])
|
|
217
|
+
severity_max = "NONE"
|
|
218
|
+
compliance_frameworks: set[str] = set()
|
|
219
|
+
if resource_findings:
|
|
220
|
+
content_lines.append(f"\nFindings ({len(resource_findings)}):")
|
|
221
|
+
severity_order = {
|
|
222
|
+
Severity.CRITICAL: 0,
|
|
223
|
+
Severity.HIGH: 1,
|
|
224
|
+
Severity.MEDIUM: 2,
|
|
225
|
+
Severity.LOW: 3,
|
|
226
|
+
Severity.INFO: 4,
|
|
227
|
+
}
|
|
228
|
+
sorted_findings = sorted(
|
|
229
|
+
resource_findings, key=lambda f: severity_order.get(f.severity, 5)
|
|
230
|
+
)
|
|
231
|
+
severity_max = sorted_findings[0].severity.value if sorted_findings else "NONE"
|
|
232
|
+
for f in sorted_findings[:10]:
|
|
233
|
+
content_lines.append(f" [{f.severity.value}] {f.title}")
|
|
234
|
+
compliance_frameworks.update(f.compliance_frameworks)
|
|
235
|
+
|
|
236
|
+
content = "\n".join(content_lines)
|
|
237
|
+
|
|
238
|
+
# Metadata
|
|
239
|
+
metadata = {
|
|
240
|
+
"asset_type": asset.asset_type.value,
|
|
241
|
+
"provider": asset.provider.value,
|
|
242
|
+
"region": asset.region,
|
|
243
|
+
"account_id": asset.account_id or "",
|
|
244
|
+
"is_internet_exposed": asset.is_internet_exposed,
|
|
245
|
+
"relation_types": sorted(relation_types_set),
|
|
246
|
+
"severity_max": severity_max,
|
|
247
|
+
"compliance_frameworks": sorted(compliance_frameworks),
|
|
248
|
+
"neighbour_count": len(chunk_relations),
|
|
249
|
+
"finding_count": len(resource_findings),
|
|
250
|
+
"arn": asset.arn or "",
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
chunks.append(
|
|
254
|
+
RAGChunk(
|
|
255
|
+
chunk_id=f"entity::{asset.id}",
|
|
256
|
+
chunk_type="entity",
|
|
257
|
+
content=content,
|
|
258
|
+
metadata=metadata,
|
|
259
|
+
relations=chunk_relations,
|
|
260
|
+
)
|
|
261
|
+
)
|
|
262
|
+
|
|
263
|
+
logger.info("Generated %d entity chunks", len(chunks))
|
|
264
|
+
return chunks
|
|
265
|
+
|
|
266
|
+
# ------------------------------------------------------------------
|
|
267
|
+
# Strategy 2: Community-detection chunks
|
|
268
|
+
# ------------------------------------------------------------------
|
|
269
|
+
|
|
270
|
+
def export_community_chunks(
|
|
271
|
+
self,
|
|
272
|
+
graph: nx.DiGraph,
|
|
273
|
+
assets_by_id: dict[str, CloudAsset] | None = None,
|
|
274
|
+
findings: list[Finding] | None = None,
|
|
275
|
+
) -> list[RAGChunk]:
|
|
276
|
+
"""Generate one chunk per detected community of resources."""
|
|
277
|
+
if graph.number_of_nodes() == 0:
|
|
278
|
+
return []
|
|
279
|
+
|
|
280
|
+
partition = _detect_communities(graph)
|
|
281
|
+
|
|
282
|
+
# Group nodes by community
|
|
283
|
+
communities: dict[int, list[str]] = defaultdict(list)
|
|
284
|
+
for node_id, comm_id in partition.items():
|
|
285
|
+
communities[comm_id].append(node_id)
|
|
286
|
+
|
|
287
|
+
findings_by_resource: dict[str, list[Finding]] = defaultdict(list)
|
|
288
|
+
if findings:
|
|
289
|
+
for f in findings:
|
|
290
|
+
findings_by_resource[f.resource_id].append(f)
|
|
291
|
+
|
|
292
|
+
chunks: list[RAGChunk] = []
|
|
293
|
+
|
|
294
|
+
for comm_id, members in communities.items():
|
|
295
|
+
if len(members) < 2:
|
|
296
|
+
continue # Skip singleton communities
|
|
297
|
+
|
|
298
|
+
content_lines = [f"Community {comm_id} ({len(members)} resources):"]
|
|
299
|
+
|
|
300
|
+
# Member summary
|
|
301
|
+
type_counts: dict[str, int] = defaultdict(int)
|
|
302
|
+
total_findings = 0
|
|
303
|
+
max_severity = "NONE"
|
|
304
|
+
severity_order = {"CRITICAL": 0, "HIGH": 1, "MEDIUM": 2, "LOW": 3, "INFO": 4, "NONE": 5}
|
|
305
|
+
frameworks: set[str] = set()
|
|
306
|
+
exposed_count = 0
|
|
307
|
+
|
|
308
|
+
for node_id in members:
|
|
309
|
+
node_data = graph.nodes.get(node_id, {})
|
|
310
|
+
asset_type = node_data.get("asset_type", "UNKNOWN")
|
|
311
|
+
type_counts[asset_type] += 1
|
|
312
|
+
|
|
313
|
+
if node_data.get("is_internet_exposed"):
|
|
314
|
+
exposed_count += 1
|
|
315
|
+
|
|
316
|
+
name = node_data.get("name", node_id)
|
|
317
|
+
content_lines.append(f" • {name} ({asset_type})")
|
|
318
|
+
|
|
319
|
+
for f in findings_by_resource.get(node_id, []):
|
|
320
|
+
total_findings += 1
|
|
321
|
+
if severity_order.get(f.severity.value, 5) < severity_order.get(
|
|
322
|
+
max_severity, 5
|
|
323
|
+
):
|
|
324
|
+
max_severity = f.severity.value
|
|
325
|
+
frameworks.update(f.compliance_frameworks)
|
|
326
|
+
|
|
327
|
+
# Internal vs external edges
|
|
328
|
+
member_set = set(members)
|
|
329
|
+
internal_edges = 0
|
|
330
|
+
external_edges = 0
|
|
331
|
+
for u, v in graph.edges():
|
|
332
|
+
if u in member_set and v in member_set:
|
|
333
|
+
internal_edges += 1
|
|
334
|
+
elif u in member_set or v in member_set:
|
|
335
|
+
external_edges += 1
|
|
336
|
+
|
|
337
|
+
content_lines.append(f"\nAsset types: {dict(type_counts)}")
|
|
338
|
+
content_lines.append(
|
|
339
|
+
f"Internal edges: {internal_edges}, External edges: {external_edges}"
|
|
340
|
+
)
|
|
341
|
+
if exposed_count:
|
|
342
|
+
content_lines.append(f"⚠ {exposed_count} internet-exposed resources")
|
|
343
|
+
if total_findings:
|
|
344
|
+
content_lines.append(f"Findings: {total_findings} (max severity: {max_severity})")
|
|
345
|
+
|
|
346
|
+
risk_score = min(10.0, len(members) * 0.3 + total_findings * 0.5 + exposed_count * 2.0)
|
|
347
|
+
|
|
348
|
+
metadata = {
|
|
349
|
+
"community_id": comm_id,
|
|
350
|
+
"member_count": len(members),
|
|
351
|
+
"asset_types": dict(type_counts),
|
|
352
|
+
"internal_edges": internal_edges,
|
|
353
|
+
"external_edges": external_edges,
|
|
354
|
+
"internet_exposed_count": exposed_count,
|
|
355
|
+
"finding_count": total_findings,
|
|
356
|
+
"severity_max": max_severity,
|
|
357
|
+
"compliance_frameworks": sorted(frameworks),
|
|
358
|
+
"risk_score": round(risk_score, 1),
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
chunks.append(
|
|
362
|
+
RAGChunk(
|
|
363
|
+
chunk_id=f"community::{comm_id}",
|
|
364
|
+
chunk_type="community",
|
|
365
|
+
content="\n".join(content_lines),
|
|
366
|
+
metadata=metadata,
|
|
367
|
+
)
|
|
368
|
+
)
|
|
369
|
+
|
|
370
|
+
logger.info("Generated %d community chunks", len(chunks))
|
|
371
|
+
return chunks
|
|
372
|
+
|
|
373
|
+
# ------------------------------------------------------------------
|
|
374
|
+
# Strategy 3: Relation-group chunks
|
|
375
|
+
# ------------------------------------------------------------------
|
|
376
|
+
|
|
377
|
+
def export_relation_chunks(
|
|
378
|
+
self,
|
|
379
|
+
edges: list[NetworkEdge],
|
|
380
|
+
assets_by_id: dict[str, CloudAsset],
|
|
381
|
+
) -> list[RAGChunk]:
|
|
382
|
+
"""Generate one chunk per semantic relation group."""
|
|
383
|
+
# Group edges by inferred relation group
|
|
384
|
+
group_triples: dict[RelationGroup, list[dict[str, str]]] = defaultdict(list)
|
|
385
|
+
|
|
386
|
+
for edge in edges:
|
|
387
|
+
inferred = infer_relations(edge, assets_by_id)
|
|
388
|
+
src_name = assets_by_id.get(edge.source_id)
|
|
389
|
+
tgt_name = assets_by_id.get(edge.target_id)
|
|
390
|
+
src_label = src_name.name if src_name else edge.source_id
|
|
391
|
+
tgt_label = tgt_name.name if tgt_name else edge.target_id
|
|
392
|
+
|
|
393
|
+
for rel in inferred:
|
|
394
|
+
group = get_relation_group(rel)
|
|
395
|
+
group_triples[group].append(
|
|
396
|
+
{
|
|
397
|
+
"subject": src_label,
|
|
398
|
+
"subject_id": edge.source_id,
|
|
399
|
+
"predicate": rel.value,
|
|
400
|
+
"object": tgt_label,
|
|
401
|
+
"object_id": edge.target_id,
|
|
402
|
+
"port_range": edge.port_range or "",
|
|
403
|
+
"protocol": edge.protocol or "",
|
|
404
|
+
"cidr": edge.cidr or "",
|
|
405
|
+
}
|
|
406
|
+
)
|
|
407
|
+
|
|
408
|
+
chunks: list[RAGChunk] = []
|
|
409
|
+
|
|
410
|
+
for group, triples in group_triples.items():
|
|
411
|
+
content_lines = [
|
|
412
|
+
f"Relation Group: {group.value}",
|
|
413
|
+
f"Total relations: {len(triples)}",
|
|
414
|
+
"",
|
|
415
|
+
]
|
|
416
|
+
|
|
417
|
+
# Summarise relation type distribution
|
|
418
|
+
type_counts: dict[str, int] = defaultdict(int)
|
|
419
|
+
for t in triples:
|
|
420
|
+
type_counts[t["predicate"]] += 1
|
|
421
|
+
|
|
422
|
+
content_lines.append("Relation type distribution:")
|
|
423
|
+
for rt_name, count in sorted(type_counts.items(), key=lambda x: -x[1]):
|
|
424
|
+
content_lines.append(f" {rt_name}: {count}")
|
|
425
|
+
|
|
426
|
+
content_lines.append("\nTriples:")
|
|
427
|
+
for t in triples[:50]: # Cap for chunk size
|
|
428
|
+
evidence = ""
|
|
429
|
+
if t["port_range"] or t["protocol"] or t["cidr"]:
|
|
430
|
+
parts = [p for p in [t["port_range"], t["protocol"], t["cidr"]] if p]
|
|
431
|
+
evidence = f" [{', '.join(parts)}]"
|
|
432
|
+
content_lines.append(
|
|
433
|
+
f" {t['subject']} → {t['predicate']} → {t['object']}{evidence}"
|
|
434
|
+
)
|
|
435
|
+
|
|
436
|
+
if len(triples) > 50:
|
|
437
|
+
content_lines.append(f" ... and {len(triples) - 50} more")
|
|
438
|
+
|
|
439
|
+
metadata = {
|
|
440
|
+
"relation_group": group.value,
|
|
441
|
+
"total_relations": len(triples),
|
|
442
|
+
"relation_type_counts": dict(type_counts),
|
|
443
|
+
"unique_subjects": len({t["subject_id"] for t in triples}),
|
|
444
|
+
"unique_objects": len({t["object_id"] for t in triples}),
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
chunks.append(
|
|
448
|
+
RAGChunk(
|
|
449
|
+
chunk_id=f"relation_group::{group.value}",
|
|
450
|
+
chunk_type="relation_group",
|
|
451
|
+
content="\n".join(content_lines),
|
|
452
|
+
metadata=metadata,
|
|
453
|
+
relations=[
|
|
454
|
+
{
|
|
455
|
+
"predicate": t["predicate"],
|
|
456
|
+
"object": t["object"],
|
|
457
|
+
"evidence": f"{t['port_range']} {t['protocol']} {t['cidr']}".strip(),
|
|
458
|
+
}
|
|
459
|
+
for t in triples[:50]
|
|
460
|
+
],
|
|
461
|
+
)
|
|
462
|
+
)
|
|
463
|
+
|
|
464
|
+
logger.info("Generated %d relation-group chunks", len(chunks))
|
|
465
|
+
return chunks
|
|
466
|
+
|
|
467
|
+
# ------------------------------------------------------------------
|
|
468
|
+
# Combined export
|
|
469
|
+
# ------------------------------------------------------------------
|
|
470
|
+
|
|
471
|
+
def export_all(
|
|
472
|
+
self,
|
|
473
|
+
assets: list[CloudAsset],
|
|
474
|
+
edges: list[NetworkEdge],
|
|
475
|
+
graph: nx.DiGraph,
|
|
476
|
+
findings: list[Finding] | None = None,
|
|
477
|
+
output_dir: str | Path = "./reports",
|
|
478
|
+
) -> dict[str, Path]:
|
|
479
|
+
"""Export all chunk types to files.
|
|
480
|
+
|
|
481
|
+
Returns:
|
|
482
|
+
Dict mapping chunk type → output file path.
|
|
483
|
+
"""
|
|
484
|
+
out = Path(output_dir)
|
|
485
|
+
out.mkdir(parents=True, exist_ok=True)
|
|
486
|
+
|
|
487
|
+
assets_by_id = {a.id: a for a in assets}
|
|
488
|
+
all_chunks: list[RAGChunk] = []
|
|
489
|
+
|
|
490
|
+
# Strategy 1
|
|
491
|
+
entity_chunks = self.export_entity_chunks(assets, edges, findings)
|
|
492
|
+
all_chunks.extend(entity_chunks)
|
|
493
|
+
|
|
494
|
+
# Strategy 2
|
|
495
|
+
community_chunks = self.export_community_chunks(graph, assets_by_id, findings)
|
|
496
|
+
all_chunks.extend(community_chunks)
|
|
497
|
+
|
|
498
|
+
# Strategy 3
|
|
499
|
+
relation_chunks = self.export_relation_chunks(edges, assets_by_id)
|
|
500
|
+
all_chunks.extend(relation_chunks)
|
|
501
|
+
|
|
502
|
+
# Write JSONL (one JSON object per line — standard for vector DBs)
|
|
503
|
+
chunks_path = out / "rag_chunks.jsonl"
|
|
504
|
+
with open(chunks_path, "w") as f:
|
|
505
|
+
for chunk in all_chunks:
|
|
506
|
+
f.write(json.dumps(chunk.to_dict(), default=str) + "\n")
|
|
507
|
+
|
|
508
|
+
# Write metadata index
|
|
509
|
+
index = {
|
|
510
|
+
"total_chunks": len(all_chunks),
|
|
511
|
+
"entity_chunks": len(entity_chunks),
|
|
512
|
+
"community_chunks": len(community_chunks),
|
|
513
|
+
"relation_group_chunks": len(relation_chunks),
|
|
514
|
+
"chunk_ids": [c.chunk_id for c in all_chunks],
|
|
515
|
+
"chunk_types": list({c.chunk_type for c in all_chunks}),
|
|
516
|
+
}
|
|
517
|
+
index_path = out / "rag_metadata_index.json"
|
|
518
|
+
with open(index_path, "w") as f:
|
|
519
|
+
json.dump(index, f, indent=2)
|
|
520
|
+
|
|
521
|
+
logger.info(
|
|
522
|
+
"RAG export complete: %d chunks (%d entity, %d community, %d relation) -> %s",
|
|
523
|
+
len(all_chunks),
|
|
524
|
+
len(entity_chunks),
|
|
525
|
+
len(community_chunks),
|
|
526
|
+
len(relation_chunks),
|
|
527
|
+
out,
|
|
528
|
+
)
|
|
529
|
+
|
|
530
|
+
return {
|
|
531
|
+
"chunks": chunks_path,
|
|
532
|
+
"index": index_path,
|
|
533
|
+
}
|