Repository navigation
Expand file tree
/
Copy pathTask4.py
More file actions
514 lines (418 loc) · 16.2 KB
/
Copy pathTask4.py
File metadata and controls
514 lines (418 loc) · 16.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
import json
import requests
import time
from collections import deque
import os
import urllib.parse
import networkx as nx
import numpy as np
import pandas as pd
from dataclasses import dataclass
from datetime import datetime
import subprocess
# Setup
Dir = "api_cache"
os.makedirs(Dir, exist_ok=True)
os.makedirs("output", exist_ok=True)
def fetch_json(url):
file = urllib.parse.quote_plus(url) + ".json"
cache_path = os.path.join(Dir, file)
if os.path.exists(cache_path):
with open(cache_path, "r", encoding="utf-8") as f:
return json.load(f)
res = requests.get(url)
res.raise_for_status()
data = res.json()
with open(cache_path, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2)
return data
def get_direct_dependents(package_name, version, limit=None):
url = f"https://deps.dev/_/s/npm/p/{package_name}/v/{version}/dependents"
try:
data = fetch_json(url)
items = data.get("direct", data.get("directSample", []))
names = [item["package"]["name"] for item in items]
return names[:limit]
except Exception:
return []
def get_latest_version(package_name):
"""
Representative version for graph expansion (depth >=1):
latest published npm version. Used ONLY to build the snapshot graph.
Safe-status recursion still uses fixed/safe versions, not this.
"""
try:
url = f"https://registry.npmjs.org/{package_name}"
data = fetch_json(url)
time_map = data.get("time", {})
versions = [
(ver, dt) for ver, dt in time_map.items()
if ver not in ("created", "modified")
]
if not versions:
return None
versions.sort(key=lambda x: x[1])
return versions[-1][0]
except Exception:
return None
@dataclass
class Edge:
src: str
dst: str
rng: str
# Load advisories and fix dates
with open("advisories_corrected.json", "r", encoding="utf-8") as f:
advisories = json.load(f)
well_known_packages = {
"lodash", "minimist", "ansi-regex", "node-fetch", "ws",
"debug", "chalk", "express", "axios", "qs",
"yargs-parser", "glob", "semver", "tar", "braces",
"minimatch", "commander", "moment", "uuid", "request",
}
def get_fixed_releasedate(package_name, version):
"""
Real fix date: when the patched version was actually published on npm,
not the advisory date.
"""
if not version:
return None
try:
url = f"https://registry.npmjs.org/{package_name}"
data = fetch_json(url)
return data.get("time", {}).get(version)
except Exception:
return None
npm_advisories = []
for advisory in advisories:
for vul in advisory.get("vulnerabilities", []):
package = vul.get("package", {})
name = package.get("name")
fixed_ver = vul.get("first_patched_version")
if (
package.get("ecosystem") == "npm"
and fixed_ver
and name in well_known_packages
):
real_pub_date = get_fixed_releasedate(name, fixed_ver)
if not real_pub_date:
continue
npm_advisories.append({
"ghsa_id": advisory["ghsa_id"],
"package_name": name,
"fixed_version": fixed_ver,
"published": real_pub_date, # REAL FIX DATE
})
break
print(f"Npm advisories with real patched-version date: {len(npm_advisories)}")
selected = npm_advisories[:20]
source_packages = [adv["package_name"] for adv in selected]
# Build dependency graph up to depth 5
all_nodes = set(source_packages)
all_edges = []
queue = deque()
visited = set()
for pkg in source_packages:
queue.append((pkg, 0))
visited.add(pkg)
max_graph_depth = 5
while queue:
current_pkg, depth = queue.popleft()
if depth >= max_graph_depth:
continue
matching_advisory = next((a for a in selected if a["package_name"] == current_pkg), None)
if matching_advisory and depth == 0:
version = matching_advisory["fixed_version"]
else:
version = get_latest_version(current_pkg)
if not version:
continue
dependents = get_direct_dependents(current_pkg, version, limit=15)
print(f"Depth {depth}: {current_pkg} -> {len(dependents)} dependents found")
time.sleep(0.1)
for dep in dependents:
all_nodes.add(dep)
all_edges.append(Edge(src=dep, dst=current_pkg, rng=""))
if dep not in visited:
visited.add(dep)
queue.append((dep, depth + 1))
print(f"\nFinal graph: {len(all_nodes)} nodes, {len(all_edges)} edges")
G = nx.DiGraph()
G.add_nodes_from(all_nodes)
G.add_edges_from((e.src, e.dst) for e in all_edges)
sccs = [list(scc) for scc in nx.strongly_connected_components(G)]
nontrivial = [s for s in sccs if len(s) > 1]
print(f"Found {len(sccs)} total components. Nontrivial loops: {len(nontrivial)}")
condensed_G = nx.condensation(G, scc=[set(s) for s in sccs])
print(
f"Condensed graph: {condensed_G.number_of_nodes()} super-nodes, "
f"{condensed_G.number_of_edges()} edges (reduced from {G.number_of_nodes()} original nodes)"
)
node_to_supernode = condensed_G.graph["mapping"]
def shortest_depths_from_sources(graph_instance, source_nodes, k_max=5):
"""
Compute d(u) as the shortest path length from any vulnerability source
in the condensed DAG, up to depth k_max.
"""
depths = {}
q = deque([(src, 0) for src in source_nodes])
while q:
u, d = q.popleft()
if u not in depths:
depths[u] = d
if d < k_max:
for v in graph_instance.predecessors(u):
q.append((v, d + 1))
return depths
source_supernodes = [node_to_supernode[s] for s in source_packages if s in node_to_supernode]
supernode_depth_map = shortest_depths_from_sources(condensed_G, source_supernodes, k_max=5)
depth_map = {}
for original_node, supernode_id in node_to_supernode.items():
if supernode_id in supernode_depth_map:
depth_map[original_node] = supernode_depth_map[supernode_id]
# Semver helpers
def classify_edges_batch(fixed_version, pairs):
input_data = json.dumps({
"fixed_version": fixed_version,
"pairs": [{"name": name, "range": rng} for name, rng in pairs]
})
script = """
const semver = require('semver');
const data = JSON.parse(require('fs').readFileSync(0, 'utf-8'));
const results = data.pairs.map(p => {
if (!p.range) return { name: p.name, category: 'missing_range' };
try {
if (semver.satisfies(data.fixed_version, p.range)) {
return { name: p.name, category: 'auto_fix' };
}
const major = semver.major(data.fixed_version);
const majorRange = '>=' + major + '.0.0 <' + (major + 1) + '.0.0';
if (!semver.intersects(p.range, majorRange)) {
return { name: p.name, category: 'major_locked' };
}
return { name: p.name, category: 'narrow_range' };
} catch (err) {
return { name: p.name, category: 'missing_range' };
}
});
console.log(JSON.stringify(results));
"""
result = subprocess.run(["node", "-e", script], input=input_data, capture_output=True, text=True)
if result.returncode != 0:
print(f"Node subprocess error: {result.stderr}")
return []
try:
return json.loads(result.stdout)
except json.JSONDecodeError:
print(f"Failed to parse JSON from node output: {result.stdout}")
return []
def get_declared_range(dependent_name, dependency_name, patch_date_iso):
url = f"https://registry.npmjs.org/{dependent_name}"
data = fetch_json(url)
versions = data.get("versions", {})
time_map = data.get("time", {})
patch_time = datetime.fromisoformat(patch_date_iso.replace("Z", "+00:00"))
best_time, best_version = None, None
for ver, published_at in time_map.items():
if ver in ("created", "modified"):
continue
try:
v_time = datetime.fromisoformat(published_at.replace("Z", "+00:00"))
except Exception:
continue
if v_time < patch_time and (best_time is None or v_time > best_time):
best_time, best_version = v_time, ver
if not best_version or best_version not in versions:
return None
manifest = versions[best_version]
return manifest.get("dependencies", {}).get(dependency_name) or manifest.get("devDependencies", {}).get(dependency_name)
def get_time_to_satisfying_release(dependent_name, dependency_name, target_version, baseline_date_iso):
try:
url = f"https://registry.npmjs.org/{dependent_name}"
data = fetch_json(url)
except Exception:
return None
versions = data.get("versions", {})
time_map = data.get("time", {})
try:
baseline_time = datetime.fromisoformat(baseline_date_iso.replace("Z", "+00:00"))
except Exception:
return None
candidates = []
for ver, published_at in time_map.items():
if ver in ("created", "modified"):
continue
try:
v_time = datetime.fromisoformat(published_at.replace("Z", "+00:00"))
except Exception:
continue
if v_time > baseline_time:
candidates.append((v_time, ver))
candidates.sort()
for v_time, ver in candidates:
manifest = versions.get(ver, {})
declared = manifest.get("dependencies", {}).get(dependency_name) or manifest.get("devDependencies", {}).get(dependency_name)
if not declared:
continue
script = f"""
const semver = require('semver');
try {{
console.log(semver.satisfies('{target_version}', '{declared}') ? 'true' : 'false');
}} catch (e) {{
console.log('false');
}}
"""
result = subprocess.run(["node", "-e", script], capture_output=True, text=True)
if result.stdout.strip() == "true":
delta = v_time - baseline_time
return max(0.0, delta.total_seconds() / 86400.0)
return None
def compute_safe_status(dependent_name, dependency_name, target_version, baseline_date_iso):
declared = get_declared_range(dependent_name, dependency_name, baseline_date_iso)
check = classify_edges_batch(target_version, [(dependent_name, declared)])
category = check[0]["category"] if check else "missing_range"
if category == "auto_fix":
return category, baseline_date_iso, 0.0
if category == "missing_range":
return category, None, None
t_days = get_time_to_satisfying_release(dependent_name, dependency_name, target_version, baseline_date_iso)
if t_days is None:
return category, None, None
baseline_dt = datetime.fromisoformat(baseline_date_iso.replace("Z", "+00:00"))
safe_dt = baseline_dt + pd.Timedelta(days=t_days)
return category, safe_dt.isoformat(), t_days
# Task 3: auto-fix share for direct dependents
print("\nClassifying real edges at depth 1 (direct CVE dependents)")
results_by_depth = {}
for adv in selected:
src = adv["package_name"]
fixed = adv["fixed_version"]
published = adv["published"]
if not published:
continue
dependent_edges = [e for e in all_edges if e.dst == src]
pairs = []
for e in dependent_edges:
if not e.src or '>' in e.src or '%' in e.src or ' ' in e.src:
continue
rng = get_declared_range(e.src, src, published)
pairs.append((e.src, rng))
if not pairs:
continue
classified = classify_edges_batch(fixed, pairs)
for r in classified:
node = r["name"]
d = depth_map.get(node)
if d is None:
continue
results_by_depth.setdefault(d, {
"auto_fix": 0,
"major_locked": 0,
"narrow_range": 0,
"missing_range": 0
})
results_by_depth[d][r["category"]] += 1
print(f"\n{'Depth':<6} | {'Auto-fix':<9} | {'Major-locked':<13} | {'Narrow-range':<13} | {'Missing':<8}")
for d in sorted(results_by_depth.keys()):
c = results_by_depth[d]
print(f"{d:<6} | {c['auto_fix']:<9} | {c['major_locked']:<13} | {c['narrow_range']:<13} | {c['missing_range']:<8}")
with open("output/results_by_depth.json", "w") as f:
json.dump(results_by_depth, f, indent=2)
print("\nSaved depth-1 classification results to output/results_by_depth.json")
total_all_edges = sum(sum(cats.values()) for cats in results_by_depth.values())
total_auto_fix = sum(cats.get("auto_fix", 0) for cats in results_by_depth.values())
if total_all_edges > 0:
auto_fix_share = (total_auto_fix / total_all_edges) * 100
print("\nDELIVERABLE (a): SHARE OF AUTO-FIX EDGES (depth 1 only)")
print(f"Total Edges Analyzed: {total_all_edges}")
print(f"Auto-Fix Edges (T ~= 0): {total_auto_fix}")
print(f"Auto-Fix Share: {auto_fix_share:.2f}%")
else:
print("\nNo edges analyzed yet.")
print("\nComputing recursive level-by-level safe status across all depths")
node_safe_info = {}
edge_records = [] # per-edge records for Task 5
# Depth 0 (roots)
for adv in selected:
root_pkg = adv["package_name"]
fixed_ver = adv["fixed_version"]
published = adv["published"]
if not published:
continue
node_safe_info[root_pkg] = {
"depth": depth_map.get(root_pkg, 0),
"safe_version": fixed_ver,
"safe_date": published,
}
# Depth 1
for adv in selected:
root_pkg = adv["package_name"]
root_info = node_safe_info.get(root_pkg)
if not root_info or not root_info["safe_date"]:
continue
baseline_date = root_info["safe_date"]
target_version = root_info["safe_version"]
depth1_edges = [e for e in all_edges if e.dst == root_pkg]
for e in depth1_edges:
child = e.src
if not child or '>' in child or '%' in child or ' ' in child:
continue
child_depth = depth_map.get(child, 1)
category, safe_date, t_edge = compute_safe_status(child, root_pkg, target_version, baseline_date)
edge_records.append({
"node": child,
"depth": child_depth,
"parent": root_pkg,
"category": category,
"t_days": t_edge,
})
if child in node_safe_info and node_safe_info[child]["depth"] <= child_depth:
continue
node_safe_info[child] = {
"depth": child_depth,
"safe_version": target_version if safe_date else None,
"safe_date": safe_date,
}
print(f" Level 1 done: {len(node_safe_info)} nodes with safe-status computed so far")
# Depth 2+
max_depth = 5
for current_depth in range(1, max_depth):
print(f"Propagating from depth {current_depth} to {current_depth + 1}")
parents_at_depth = [
pkg for pkg, info in node_safe_info.items()
if info["depth"] == current_depth
and info["safe_version"] is not None
and info["safe_date"] is not None
]
for parent_pkg in parents_at_depth:
p_info = node_safe_info[parent_pkg]
baseline_date = p_info["safe_date"]
target_version = p_info["safe_version"]
next_edges = [e for e in all_edges if e.dst == parent_pkg]
for e in next_edges:
child = e.src
if not child or '>' in child or '%' in child or ' ' in child:
continue
child_depth = depth_map.get(child)
if child_depth is None or child_depth != current_depth + 1:
continue
category, safe_date, t_edge = compute_safe_status(child, parent_pkg, target_version, baseline_date)
edge_records.append({
"node": child,
"depth": child_depth,
"parent": parent_pkg,
"category": category,
"t_days": t_edge,
})
if child in node_safe_info and node_safe_info[child]["depth"] <= child_depth:
continue
node_safe_info[child] = {
"depth": child_depth,
"safe_version": target_version if safe_date else None,
"safe_date": safe_date,
}
print(f" Level {current_depth + 1} done: {len(node_safe_info)} nodes with safe-status computed so far")
print(f"\nComputed safe status for {len(node_safe_info)} nodes across all depths")
df_nodes = pd.DataFrame(edge_records)
df_nodes.to_csv("output/nodes.csv", index=False)
depths_present = sorted(df_nodes["depth"].dropna().unique()) if len(df_nodes) else []
print(f"Saved {len(edge_records)} edge-level records across depths {depths_present} to output/nodes.csv")