detection-graph 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.
@@ -0,0 +1,263 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import networkx as nx
5
+ from networkx.readwrite import json_graph
6
+
7
+ DEFAULT_COLORS = {
8
+ "tactic": "#e74c3c",
9
+ "technique": "#e67e22",
10
+ "rule": "#3498db",
11
+ "product": "#2ecc71",
12
+ }
13
+
14
+
15
+ class SigmaRenderer:
16
+ """Render a NetworkX graph to an interactive HTML page using Sigma.js.
17
+
18
+ This implementation embeds node-link JSON and uses Graphology + Sigma
19
+ from a CDN to render the graph in the browser. Positions are assigned
20
+ randomly for initial layout; consumers can extend with server-side
21
+ layout if deterministic coordinates are required.
22
+ """
23
+
24
+ def __init__(self, height: str = "800px", width: str = "100%"):
25
+ self.height = height
26
+ self.width = width
27
+
28
+ def render(self, graph: nx.DiGraph, output_path: str, hierarchical: bool = False, seed: int = 42, bundle: str = "cdn") -> None:
29
+ # Compute deterministic positions using NetworkX's spring layout
30
+ try:
31
+ pos = nx.spring_layout(graph, seed=seed)
32
+ for n, (x, y) in pos.items():
33
+ # ensure position metadata is present in node data
34
+ if "data" not in graph.nodes[n]:
35
+ graph.nodes[n]["data"] = {}
36
+ graph.nodes[n]["data"]["x"] = float(x)
37
+ graph.nodes[n]["data"]["y"] = float(y)
38
+ except Exception:
39
+ # fallback: let the client assign positions
40
+ pass
41
+
42
+ data = json_graph.node_link_data(graph)
43
+
44
+ # enrich nodes with color and label
45
+ for n in data.get("nodes", []):
46
+ nmeta = n.get("data", {}) or {}
47
+ ntype = nmeta.get("node_type")
48
+ n["color"] = DEFAULT_COLORS.get(ntype, "#95a5a6")
49
+ # label fallback
50
+ n["label"] = nmeta.get("name") or n.get("id")
51
+
52
+ # choose script tags based on bundle option
53
+ if bundle == "cdn":
54
+ scripts = (_CDN_GRAPHOLGY_SCRIPT, _CDN_SIGMA_SCRIPT)
55
+ elif bundle == "local":
56
+ # reference local package static assets relative to the HTML file
57
+ # note: filenames match vendored assets in `src/detection_graph/static/`
58
+ scripts = ("graphology.umd.min.js", "sigma.min.js")
59
+ else:
60
+ # embed mode: attempt to read bundled files from package resources or
61
+ # fall back to reading from the filesystem (useful during development).
62
+ try:
63
+ import pkgutil
64
+ import pathlib
65
+ pkg_name = __package__
66
+ gbytes = pkgutil.get_data(pkg_name, "../static/graphology.umd.min.js")
67
+ sbytes = pkgutil.get_data(pkg_name, "../static/sigma.min.js")
68
+ # fallback to disk relative to this file when pkgutil didn't find data
69
+ if not gbytes:
70
+ p = pathlib.Path(__file__).resolve().parent.parent / "static" / "graphology.umd.min.js"
71
+ gbytes = p.read_bytes() if p.exists() else b""
72
+ if not sbytes:
73
+ p2 = pathlib.Path(__file__).resolve().parent.parent / "static" / "sigma.min.js"
74
+ sbytes = p2.read_bytes() if p2.exists() else b""
75
+ # When embedding, wrap raw JS into <script> tags so the template
76
+ # receives valid script tags. Fall back to CDN tags if files missing.
77
+ gs = ("<script>" + gbytes.decode("utf-8") + "</script>") if gbytes else _CDN_GRAPHOLGY_SCRIPT
78
+ ss = ("<script>" + sbytes.decode("utf-8") + "</script>") if sbytes else _CDN_SIGMA_SCRIPT
79
+ scripts = (gs, ss)
80
+ except Exception:
81
+ scripts = (_CDN_GRAPHOLGY_SCRIPT, _CDN_SIGMA_SCRIPT)
82
+
83
+ # Use simple replacement to avoid Python format conflicts with JS template
84
+ html = (
85
+ _SIGMA_TEMPLATE.replace("__DATA__", json.dumps(data))
86
+ .replace("__GRAPH_SCRIPT_TAG__", scripts[0])
87
+ .replace("__SIGMA_SCRIPT_TAG__", scripts[1])
88
+ )
89
+
90
+ try:
91
+ with open(output_path, "w", encoding="utf-8") as fh:
92
+ fh.write(html)
93
+ except Exception:
94
+ # fallback to writing raw JSON if file write fails
95
+ with open(output_path, "w", encoding="utf-8") as fh:
96
+ fh.write(json.dumps(data, indent=2))
97
+
98
+
99
+ _SIGMA_TEMPLATE = """
100
+ <!doctype html>
101
+ <html>
102
+ <head>
103
+ <meta charset="utf-8" />
104
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
105
+ <title>Detection Graph (Sigma.js)</title>
106
+ <style>
107
+ html,body,#sigma-container {{ height: 100%; margin: 0; padding: 0; }}
108
+ #sigma-container {{ height: 80vh; width: 100%; border: 1px solid #ddd; }}
109
+ .legend {{ font-family: sans-serif; margin: 8px; }}
110
+ .legend-item {{ display:inline-block; margin-right: 12px; }}
111
+ .swatch {{ display:inline-block; width:12px; height:12px; vertical-align:middle; margin-right:6px; }}
112
+ </style>
113
+ <!-- graphology + sigma (UMD builds) -->
114
+ __GRAPH_SCRIPT_TAG__
115
+ __SIGMA_SCRIPT_TAG__
116
+ </head>
117
+ <body>
118
+ <div class="legend">
119
+ <span class="legend-item"><span class="swatch" style="background:#e74c3c"></span> Tactic</span>
120
+ <span class="legend-item"><span class="swatch" style="background:#e67e22"></span> Technique</span>
121
+ <span class="legend-item"><span class="swatch" style="background:#3498db"></span> Rule</span>
122
+ <span class="legend-item"><span class="swatch" style="background:#2ecc71"></span> Product</span>
123
+ </div>
124
+ <div style="margin:8px; font-family:sans-serif">
125
+ <input id="node-search" placeholder="Search nodes..." style="padding:6px; margin-right:8px; width:260px" />
126
+ <button id="export-png">Export PNG</button>
127
+ <label style="margin-left:12px">Show:</label>
128
+ <label><input type="checkbox" class="node-type-checkbox" value="tactic" checked/> Tactic</label>
129
+ <label><input type="checkbox" class="node-type-checkbox" value="technique" checked/> Technique</label>
130
+ <label><input type="checkbox" class="node-type-checkbox" value="rule" checked/> Rule</label>
131
+ <label><input type="checkbox" class="node-type-checkbox" value="product" checked/> Product</label>
132
+ </div>
133
+ <div id="sigma-container"></div>
134
+ <script>
135
+ // Embedded node-link JSON
136
+ const data = __DATA__;
137
+
138
+ // Build a graphology graph
139
+ const g = new graphology.Graph();
140
+
141
+ // add nodes
142
+ data.nodes.forEach(n => {{
143
+ const attrs = n.data || {{}};
144
+ g.addNode(n.id, {{
145
+ label: n.label || n.id,
146
+ color: n.color || '#95a5a6',
147
+ ...attrs
148
+ }});
149
+ }});
150
+
151
+ // add edges
152
+ data.links.forEach((e, i) => {{
153
+ // ensure unique edge key
154
+ const key = 'e' + i;
155
+ try {{
156
+ g.addEdgeWithKey(key, e.source, e.target, {{ label: e.get && e.get('relation') || e.relation || '' }});
157
+ }} catch (err) {{
158
+ // skip duplicate or invalid edges
159
+ }}
160
+ }});
161
+
162
+ // assign simple random positions for layout
163
+ g.forEachNode((node, attrs) => {{
164
+ g.setNodeAttribute(node, 'x', Math.random());
165
+ g.setNodeAttribute(node, 'y', Math.random());
166
+ g.setNodeAttribute(node, 'size', attrs.size || 6);
167
+ }});
168
+
169
+ // create sigma renderer
170
+ const container = document.getElementById('sigma-container');
171
+ const renderer = new sigma.Sigma(g, container);
172
+
173
+ // Tooltip overlay
174
+ const tooltip = document.createElement('div');
175
+ tooltip.style.position = 'absolute';
176
+ tooltip.style.pointerEvents = 'none';
177
+ tooltip.style.background = 'rgba(0,0,0,0.75)';
178
+ tooltip.style.color = 'white';
179
+ tooltip.style.padding = '6px 8px';
180
+ tooltip.style.borderRadius = '4px';
181
+ tooltip.style.fontFamily = 'sans-serif';
182
+ tooltip.style.fontSize = '12px';
183
+ tooltip.style.display = 'none';
184
+ document.body.appendChild(tooltip);
185
+
186
+ // Show tooltip on node enter, hide on leave
187
+ try {{
188
+ renderer.on('enterNode', ({node}) => {{
189
+ const attrs = g.getNodeAttributes(node) || {{}};
190
+ const lines = [];
191
+ for (const k in attrs) {{
192
+ if (k === 'x' || k === 'y') continue;
193
+ lines.push(`<strong>${{k}}</strong>: ${{String(attrs[k])}}`);
194
+ }}
195
+ tooltip.innerHTML = lines.join('<br>');
196
+ tooltip.style.display = 'block';
197
+ }});
198
+ renderer.on('leaveNode', () => {{ tooltip.style.display = 'none'; }});
199
+ // update tooltip position with mouse
200
+ container.addEventListener('mousemove', function(e) {{
201
+ tooltip.style.left = (e.clientX + 12) + 'px';
202
+ tooltip.style.top = (e.clientY + 12) + 'px';
203
+ }});
204
+ }} catch (err) {{
205
+ // renderer event API may vary across builds; ignore failures
206
+ }}
207
+
208
+ // Filtering controls: show/hide by node_type
209
+ function setVisibilityByType(typesVisible) {{
210
+ g.forEachNode((node, attrs) => {{
211
+ const ntype = attrs.node_type || (attrs.data && attrs.data.node_type) || null;
212
+ const visible = !ntype || typesVisible.includes(ntype);
213
+ // set size to 0 to hide; restore to default otherwise
214
+ g.setNodeAttribute(node, 'hidden', !visible);
215
+ g.setNodeAttribute(node, 'size', visible ? (attrs.size || 6) : 0);
216
+ }});
217
+ try {{ renderer.refresh(); }} catch (e) {{}}
218
+ }}
219
+
220
+ // wire up checkboxes
221
+ document.querySelectorAll('.node-type-checkbox').forEach(cb => {{
222
+ cb.addEventListener('change', () => {{
223
+ const visible = Array.from(document.querySelectorAll('.node-type-checkbox'))
224
+ .filter(i => i.checked)
225
+ .map(i => i.value);
226
+ setVisibilityByType(visible);
227
+ }});
228
+ }});
229
+
230
+ // Search box: highlight matching nodes
231
+ const searchInput = document.getElementById('node-search');
232
+ searchInput.addEventListener('input', () => {{
233
+ const q = searchInput.value.trim().toLowerCase();
234
+ g.forEachNode((node, attrs) => {{
235
+ const label = (attrs.label || '').toLowerCase();
236
+ const match = q.length === 0 || label.includes(q) || (attrs.name || '').toLowerCase().includes(q);
237
+ g.setNodeAttribute(node, 'size', match ? (attrs.size || 8) : (attrs.size || 6));
238
+ }});
239
+ try {{ renderer.refresh(); }} catch (e) {{}}
240
+ }});
241
+ // PNG export button
242
+ document.getElementById('export-png').addEventListener('click', () => {{
243
+ const canvas = container.querySelector('canvas');
244
+ if (!canvas) {{
245
+ alert('No canvas found to export');
246
+ return;
247
+ }}
248
+ const url = canvas.toDataURL('image/png');
249
+ const a = document.createElement('a');
250
+ a.href = url;
251
+ a.download = 'detection-graph.png';
252
+ document.body.appendChild(a);
253
+ a.click();
254
+ a.remove();
255
+ }});
256
+ </script>
257
+ </body>
258
+ </html>
259
+ """
260
+
261
+ # CDN script tags used when bundle='cdn'
262
+ _CDN_GRAPHOLGY_SCRIPT = '<script src="https://cdnjs.cloudflare.com/ajax/libs/graphology/0.25.4/graphology.umd.min.js"></script>'
263
+ _CDN_SIGMA_SCRIPT = '<script src="https://cdnjs.cloudflare.com/ajax/libs/sigma.js/2.4.0/sigma.min.js"></script>'
@@ -0,0 +1,16 @@
1
+ Metadata-Version: 2.4
2
+ Name: detection-graph
3
+ Version: 0.1.0
4
+ Summary: Interactive MITRE ATT&CK detection coverage graph for Microsoft security products
5
+ Author: Your Name
6
+ Author-email: you@example.com
7
+ Requires-Python: >=3.12
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Programming Language :: Python :: 3.12
10
+ Classifier: Programming Language :: Python :: 3.13
11
+ Classifier: Programming Language :: Python :: 3.14
12
+ Requires-Dist: networkx (>=3.1,<4.0)
13
+ Requires-Dist: pandas (>=2.2,<3.0)
14
+ Requires-Dist: pydantic (>=2.2,<3.0)
15
+ Requires-Dist: pyvis (>=0.3,<0.4)
16
+ Requires-Dist: typer (>=0.10,<0.11)
@@ -0,0 +1,29 @@
1
+ detection_graph/__init__.py,sha256=7jYr0FYe-Y6deYt1xPD33mzwLyH79KSwViVxKIM4Z9A,271
2
+ detection_graph/analytics/__init__.py,sha256=TKu9PXR8HOUaBVgGQmOGLdikJ6wycqbGbUKzPw-D8wM,175
3
+ detection_graph/analytics/coverage.py,sha256=SIXdw-llO9NSJRyweMQe6pthy10cfEHQ435FC-av0oU,2257
4
+ detection_graph/builders/__init__.py,sha256=6dx-X68UuUp--iY4sNYCSaZpf_g6EzMnXu-MQoAku_U,68
5
+ detection_graph/builders/graph_builder.py,sha256=bc4ddl6R-V7ugOk7ytXd9zvOaa4Q0Uy6btsqYWosYRk,3007
6
+ detection_graph/cli.py,sha256=fDBwUOBycn-QCMvnvPkGPFcyJaqlraNTBHCVrEqznTw,2526
7
+ detection_graph/exporters/__init__.py,sha256=wp14eNSwNifHU7npQXvspOaJH6EH9HwtsOrapeAnJdM,156
8
+ detection_graph/exporters/graphml.py,sha256=cRkcgC3U-hleUDyiQpcM3hGNCLhuTCj41XIV-InC34U,152
9
+ detection_graph/exporters/html.py,sha256=4O-9shWuzX24x0i8Dwq0vDuTzhjViRWFDz-OFH5fs9Q,1165
10
+ detection_graph/exporters/json.py,sha256=j_iDZ0bx38t0K6TitFwZIAJHzESwrk9KWUpBjYO5QNY,301
11
+ detection_graph/graph.py,sha256=oi5fGASIvOleiAJ15Uaa-iMQwXQ7wSLfkKSz-fIbLNc,2001
12
+ detection_graph/models/__init__.py,sha256=bOkV6akYNZf_gUdfSBDemTlmgI-qKwEAUMGCInI7RqM,66
13
+ detection_graph/models/attack.py,sha256=ByZ_rr6DMdVqzwFBg1cf5AGXY0-iFMnjX2ChlrblarE,1467
14
+ detection_graph/models/detection.py,sha256=NXe0bk-5iOki5hSj743mQso0dyOO2FhJHkiG8TDCVbU,869
15
+ detection_graph/providers/__init__.py,sha256=0MIbsbCxPXl4OwL_X5qXvq2AXwHgvZMrVD72xGAW8h4,69
16
+ detection_graph/providers/base.py,sha256=mmzAQvH8P-WE5g6wcjBt46mpqgLa-hXoY2oFWosn6RM,635
17
+ detection_graph/providers/defender.py,sha256=M1iEIy_4i1PgwfcUJIZic6dxeDA946KR-wBWmojruNg,1563
18
+ detection_graph/providers/sentinel.py,sha256=aOhWks1KrOR6_9hp7TRQeY6nWmxEuIcnLkNO99ZNWys,1761
19
+ detection_graph/static/graphology.umd.min.js,sha256=ZB6gR-L0FN6tmZdp1iVnzjxvHdwzTx5yi9XtsZ0zeXc,74221
20
+ detection_graph/static/sigma.min.js,sha256=qGt-s1eOkCjuhNeSvyDxUD8DNc52nVrUVCUtwKV4dhg,97311
21
+ detection_graph/static/sigma.umd.min.js,sha256=9paFMG8_uNLtHff2NwRePG-rKDya8J9erejwes3ATZ4,214
22
+ detection_graph/static/vendor-manifest.json,sha256=hOahh_y7B1dM32pAlDQfdkbsK_x6qYGdmxW-GbDcgXQ,862
23
+ detection_graph/visualizers/__init__.py,sha256=Q1FzrCdKEEiiC5z6q2VcTsfr6qTnBX0SBWHs83hYKrs,250
24
+ detection_graph/visualizers/pyvis_renderer.py,sha256=c4QRclT7orbGYhNklijbed7Z7yAgFp9eJGGTlp9Psak,1705
25
+ detection_graph/visualizers/sigma_renderer.py,sha256=JXIb9kRWOtXqMLylcoQebxc8ZZLLlGYa2HAsOyJI8oc,10856
26
+ detection_graph-0.1.0.dist-info/METADATA,sha256=PG42cBM1Ej3CGchX1u9eqqWN83H0z14CUJr48pq98pU,602
27
+ detection_graph-0.1.0.dist-info/WHEEL,sha256=eY7nduwzv-ldUxpzbRlxwvC693Hg6PX8bWDjEHjZ_dk,88
28
+ detection_graph-0.1.0.dist-info/entry_points.txt,sha256=Eu3vuP3IWgqm_uKwi1IqkRWoYGIN5VVuLPjjcG0SE-4,60
29
+ detection_graph-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: poetry-core 2.4.1
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ detection-graph=detection_graph.cli:main
3
+