timecs 2.0.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 (94) hide show
  1. app.py +3014 -0
  2. ast_scanner.py +36187 -0
  3. banner.py +146 -0
  4. ci_reporter.py +570 -0
  5. cli.py +2347 -0
  6. config_loader.py +307 -0
  7. cross_file_engine.py +1781 -0
  8. delivery_models.py +145 -0
  9. delivery_repository.py +78 -0
  10. diff_scan.py +127 -0
  11. durable_delivery_sink.py +103 -0
  12. event_bus.py +155 -0
  13. event_publisher.py +345 -0
  14. event_taxonomy.py +313 -0
  15. function_summarizer.py +354 -0
  16. html_auditor.py +274 -0
  17. iac_auditor.py +400 -0
  18. in_app_adapter.py +115 -0
  19. js_scanner.py +895 -0
  20. manifest_parser.py +960 -0
  21. master_rules_bank.py +389 -0
  22. notification_models.py +346 -0
  23. notification_policy.py +309 -0
  24. notification_repository.py +118 -0
  25. notification_routes.py +394 -0
  26. notification_service.py +199 -0
  27. osv_client.py +437 -0
  28. remediation/__init__.py +39 -0
  29. remediation/base.py +102 -0
  30. remediation/contracts.py +196 -0
  31. remediation/cwe1188_binding.py +78 -0
  32. remediation/cwe1336_jinja.py +91 -0
  33. remediation/cwe22_path_traversal.py +348 -0
  34. remediation/cwe295_ssl.py +87 -0
  35. remediation/cwe327_weak_hash.py +78 -0
  36. remediation/cwe377_tempfile.py +77 -0
  37. remediation/cwe489_debug.py +80 -0
  38. remediation/cwe502_yaml.py +89 -0
  39. remediation/cwe614_cookie.py +91 -0
  40. remediation/cwe78_cmdi.py +415 -0
  41. remediation/cwe798_credentials.py +153 -0
  42. remediation/cwe89_sqli.py +425 -0
  43. remediation/cwe916_password_hash.py +131 -0
  44. remediation/cwe95_eval.py +77 -0
  45. remediation/dispatcher.py +114 -0
  46. remediation/orchestrator.py +541 -0
  47. remediation/patch_engine.py +213 -0
  48. remediation/verification.py +253 -0
  49. rule_engine.py +1535 -0
  50. sarif_adapter.py +719 -0
  51. sarif_exporter.py +88 -0
  52. sca_reachability/__init__.py +28 -0
  53. sca_reachability/ast_analyzer.py +366 -0
  54. sca_reachability/call_graph.py +203 -0
  55. sca_reachability/contracts.py +365 -0
  56. sca_reachability/dist_import_map.py +46 -0
  57. sca_reachability/engine.py +603 -0
  58. sca_reachability/resolver.py +169 -0
  59. scanners/__init__.py +70 -0
  60. scanners/container_scanner.py +323 -0
  61. scanners/cve_index.py +521 -0
  62. scanners/iac_scanner.py +328 -0
  63. scanners/sbom.py +183 -0
  64. scanners/sca_scanner.py +667 -0
  65. scanners/secret_scanner.py +345 -0
  66. scanners/yaml_lite.py +217 -0
  67. secret_filters.py +435 -0
  68. secret_scanner.py +943 -0
  69. sqlite_delivery_repository.py +277 -0
  70. sqlite_notification_repository.py +441 -0
  71. ssrf_guard.py +276 -0
  72. staged_scanner.py +492 -0
  73. suppression_resolver.py +282 -0
  74. symbol_indexer.py +424 -0
  75. tcs/__init__.py +1 -0
  76. tcs/analysis/__init__.py +1 -0
  77. tcs/analysis/def_use.py +408 -0
  78. tcs/analysis/function_contracts.py +290 -0
  79. tcs/parallel_analyzer.py +276 -0
  80. tcs/parallel_scanner.py +630 -0
  81. tcs/treesitter_packer.py +1446 -0
  82. tcs_cli.py +2086 -0
  83. tcs_config.py +218 -0
  84. tcs_gui.py +2123 -0
  85. timecs-2.0.0.dist-info/METADATA +142 -0
  86. timecs-2.0.0.dist-info/RECORD +94 -0
  87. timecs-2.0.0.dist-info/WHEEL +5 -0
  88. timecs-2.0.0.dist-info/entry_points.txt +4 -0
  89. timecs-2.0.0.dist-info/licenses/LICENSE +201 -0
  90. timecs-2.0.0.dist-info/top_level.txt +49 -0
  91. version_matcher.py +934 -0
  92. webhook_adapter.py +495 -0
  93. webhook_client.py +483 -0
  94. webhook_formatters.py +245 -0
version_matcher.py ADDED
@@ -0,0 +1,934 @@
1
+ """
2
+ TimeCodeSecurity Version Matcher & SCA Findings Engine.
3
+ Deterministically evaluates dependency records against OSV vulnerability advisories
4
+ using PEP 440 semantics and emits structured SCA findings.
5
+
6
+ Includes a sound Tri-State overlap classifier (PROVEN_OVERLAP, PROVEN_DISJOINT, UNRESOLVED).
7
+ Performs zero network I/O; operates 100% offline.
8
+ """
9
+
10
+ from __future__ import annotations
11
+ from enum import Enum
12
+ from dataclasses import dataclass
13
+ from typing import Dict, List, Optional, Tuple, Any, Sequence
14
+
15
+ from packaging.version import Version, InvalidVersion
16
+ from packaging.specifiers import SpecifierSet, InvalidSpecifier
17
+
18
+ from manifest_parser import DependencyRecord, normalize_package_name
19
+ from osv_client import OSVVulnerability, OSVAffectedRange, OSVQueryResult
20
+
21
+ # Allowed finding status values
22
+ STATUS_CONFIRMED = "CONFIRMED"
23
+ STATUS_POTENTIAL = "POTENTIAL"
24
+ STATUS_UNRESOLVED = "UNRESOLVED"
25
+
26
+ # Allowed severity values
27
+ SEVERITY_CRITICAL = "CRITICAL"
28
+ SEVERITY_HIGH = "HIGH"
29
+ SEVERITY_MEDIUM = "MEDIUM"
30
+ SEVERITY_LOW = "LOW"
31
+ SEVERITY_UNKNOWN = "UNKNOWN"
32
+
33
+
34
+ class OverlapState(Enum):
35
+ """Tri-state range intersection evaluation result."""
36
+ PROVEN_OVERLAP = "PROVEN_OVERLAP"
37
+ PROVEN_DISJOINT = "PROVEN_DISJOINT"
38
+ UNRESOLVED = "UNRESOLVED"
39
+
40
+
41
+ @dataclass(frozen=True)
42
+ class SCAFinding:
43
+ """
44
+ Typed, immutable representation of a Software Composition Analysis (SCA) finding.
45
+ """
46
+ package_name: str
47
+ installed_version: Optional[str]
48
+ requested_specifier: Optional[str]
49
+
50
+ vulnerability_id: str
51
+ aliases: List[str]
52
+
53
+ severity: str
54
+ cvss_score: Optional[float]
55
+
56
+ summary: str
57
+ fixed_version: Optional[str]
58
+ matched_range: str
59
+
60
+ confidence: float
61
+ status: str
62
+
63
+ manifest_source: str
64
+ line_number: Optional[int]
65
+
66
+ @property
67
+ def is_confirmed(self) -> bool:
68
+ return self.status == STATUS_CONFIRMED
69
+
70
+ @property
71
+ def is_potential(self) -> bool:
72
+ return self.status == STATUS_POTENTIAL
73
+
74
+ @property
75
+ def is_unresolved(self) -> bool:
76
+ return self.status == STATUS_UNRESOLVED
77
+
78
+ def to_dict(self) -> Dict[str, Any]:
79
+ """Serializes finding into a plain JSON-compatible dictionary."""
80
+ return {
81
+ "package_name": self.package_name,
82
+ "installed_version": self.installed_version,
83
+ "requested_specifier": self.requested_specifier,
84
+ "vulnerability_id": self.vulnerability_id,
85
+ "aliases": list(self.aliases),
86
+ "severity": self.severity,
87
+ "cvss_score": self.cvss_score,
88
+ "summary": self.summary,
89
+ "fixed_version": self.fixed_version,
90
+ "matched_range": self.matched_range,
91
+ "confidence": self.confidence,
92
+ "status": self.status,
93
+ "manifest_source": self.manifest_source,
94
+ "line_number": self.line_number,
95
+ }
96
+
97
+
98
+ def extract_severity_and_score(vuln: OSVVulnerability) -> Tuple[str, Optional[float]]:
99
+ """
100
+ Extracts normalized severity (CRITICAL, HIGH, MEDIUM, LOW, UNKNOWN) and
101
+ optional numeric CVSS score directly from OSV payload fields.
102
+ Does not calculate CVSS metrics from vector strings.
103
+ """
104
+ cvss_score: Optional[float] = None
105
+ severity_str: Optional[str] = None
106
+
107
+ # 1. Inspect vuln.severity array for explicit numeric score
108
+ for item in vuln.severity:
109
+ if isinstance(item, dict):
110
+ raw_score = item.get("score")
111
+ if isinstance(raw_score, (int, float)):
112
+ cvss_score = float(raw_score)
113
+ break
114
+ elif isinstance(raw_score, str):
115
+ try:
116
+ cvss_score = float(raw_score)
117
+ break
118
+ except ValueError:
119
+ # Raw vector string; preserved in payload, do not compute custom arithmetic
120
+ pass
121
+
122
+ # 2. Check database_specific for cvss score if not yet found
123
+ db_spec = vuln.database_specific or {}
124
+ if cvss_score is None:
125
+ cvss_obj = db_spec.get("cvss")
126
+ if isinstance(cvss_obj, dict):
127
+ score_val = cvss_obj.get("score")
128
+ if isinstance(score_val, (int, float)):
129
+ cvss_score = float(score_val)
130
+ elif isinstance(db_spec.get("cvss_score"), (int, float)):
131
+ cvss_score = float(db_spec["cvss_score"])
132
+
133
+ # 3. Derive severity tier: first check database_specific.severity
134
+ raw_sev = str(db_spec.get("severity", "")).upper()
135
+ if raw_sev == "CRITICAL":
136
+ severity_str = SEVERITY_CRITICAL
137
+ elif raw_sev == "HIGH":
138
+ severity_str = SEVERITY_HIGH
139
+ elif raw_sev in ("MODERATE", "MEDIUM"):
140
+ severity_str = SEVERITY_MEDIUM
141
+ elif raw_sev == "LOW":
142
+ severity_str = SEVERITY_LOW
143
+
144
+ # 4. If severity not provided directly, derive from numeric cvss_score if available
145
+ if not severity_str and cvss_score is not None:
146
+ if cvss_score >= 9.0:
147
+ severity_str = SEVERITY_CRITICAL
148
+ elif cvss_score >= 7.0:
149
+ severity_str = SEVERITY_HIGH
150
+ elif cvss_score >= 4.0:
151
+ severity_str = SEVERITY_MEDIUM
152
+ elif cvss_score > 0.0:
153
+ severity_str = SEVERITY_LOW
154
+ else:
155
+ severity_str = SEVERITY_UNKNOWN
156
+
157
+ if not severity_str:
158
+ severity_str = SEVERITY_UNKNOWN
159
+
160
+ return severity_str, cvss_score
161
+
162
+
163
+ def extract_intervals_from_events(events: Sequence[Dict[str, str]]) -> List[Dict[str, str]]:
164
+ """
165
+ Groups ordered OSV events into distinct intervals.
166
+ Handles pairs of introduced -> fixed / last_affected, as well as open bounds.
167
+ """
168
+ intervals: List[Dict[str, str]] = []
169
+ current: Dict[str, str] = {}
170
+
171
+ for ev in events:
172
+ if not isinstance(ev, dict):
173
+ continue
174
+ if "introduced" in ev:
175
+ if "introduced" in current:
176
+ intervals.append(current)
177
+ current = {}
178
+ current["introduced"] = str(ev["introduced"]).strip()
179
+ elif "fixed" in ev:
180
+ current["fixed"] = str(ev["fixed"]).strip()
181
+ intervals.append(current)
182
+ current = {}
183
+ elif "last_affected" in ev:
184
+ current["last_affected"] = str(ev["last_affected"]).strip()
185
+ intervals.append(current)
186
+ current = {}
187
+ elif "limit" in ev:
188
+ current["limit"] = str(ev["limit"]).strip()
189
+ intervals.append(current)
190
+ current = {}
191
+
192
+ if current:
193
+ intervals.append(current)
194
+
195
+ return intervals
196
+
197
+
198
+ def _format_interval_range(interval: Dict[str, str]) -> str:
199
+ """Formats an interval dict into a readable range string."""
200
+ intro = interval.get("introduced")
201
+ fixed = interval.get("fixed")
202
+ last_aff = interval.get("last_affected")
203
+
204
+ parts = []
205
+ if intro is not None:
206
+ parts.append(f">={intro}")
207
+ if fixed is not None:
208
+ parts.append(f"<{fixed}")
209
+ if last_aff is not None:
210
+ parts.append(f"<={last_aff}")
211
+
212
+ return ", ".join(parts) if parts else "any"
213
+
214
+
215
+ def _safe_parse_version(v_str: str) -> Optional[Version]:
216
+ """Safely parses a version string with PEP 440, returning None on invalid format."""
217
+ if not v_str or not isinstance(v_str, str):
218
+ return None
219
+ try:
220
+ return Version(v_str.strip())
221
+ except (InvalidVersion, TypeError):
222
+ return None
223
+
224
+
225
+ def _normalize_poetry_caret(ver_str: str) -> Optional[str]:
226
+ """
227
+ Normalizes a Poetry caret version constraint (^x.y.z) according to SemVer rules:
228
+ - major > 0: ^1.2.3 -> >=1.2.3, <2.0.0
229
+ - major == 0, minor > 0: ^0.2.3 -> >=0.2.3, <0.3.0
230
+ - major == 0, minor == 0, patch > 0: ^0.0.3 -> >=0.0.3, <0.0.4
231
+ - major == 0, minor == 0 (len <= 2): ^0.0 -> >=0.0, <0.1.0
232
+ - major == 0 (len == 1): ^0 -> >=0, <1.0.0
233
+ """
234
+ v = _safe_parse_version(ver_str)
235
+ if v is None:
236
+ return None
237
+ raw_parts = [p for p in ver_str.split(".") if p.strip()]
238
+ parts = [int(p) for p in v.base_version.split(".") if p.isdigit()]
239
+ if not parts:
240
+ return None
241
+
242
+ maj = parts[0]
243
+ mnr = parts[1] if len(parts) > 1 else 0
244
+ patch = parts[2] if len(parts) > 2 else 0
245
+
246
+ if maj > 0:
247
+ high = f"{maj + 1}.0.0"
248
+ elif len(raw_parts) == 1:
249
+ high = "1.0.0"
250
+ elif mnr > 0:
251
+ high = f"0.{mnr + 1}.0"
252
+ elif len(raw_parts) == 2:
253
+ high = "0.1.0"
254
+ else:
255
+ high = f"0.0.{patch + 1}"
256
+
257
+ return f">={ver_str},<{high}"
258
+
259
+
260
+ def _normalize_poetry_tilde(ver_str: str) -> Optional[str]:
261
+ """
262
+ Normalizes a Poetry tilde version constraint (~x.y.z) according to SemVer rules:
263
+ - ~2.25.0 (major.minor.patch): allows patch updates -> >=2.25.0, <2.26.0
264
+ - ~2.25 (major.minor): allows patch updates -> >=2.25, <2.26.0
265
+ - ~2 (major only): allows minor/patch updates -> >=2, <3.0.0
266
+ """
267
+ v = _safe_parse_version(ver_str)
268
+ if v is None:
269
+ return None
270
+ raw_parts = [p for p in ver_str.split(".") if p.strip()]
271
+ parts = [int(p) for p in v.base_version.split(".") if p.isdigit()]
272
+ if not parts:
273
+ return None
274
+
275
+ maj = parts[0]
276
+ mnr = parts[1] if len(parts) > 1 else 0
277
+
278
+ if len(raw_parts) <= 1:
279
+ high = f"{maj + 1}.0.0"
280
+ else:
281
+ high = f"{maj}.{mnr + 1}.0"
282
+
283
+ return f">={ver_str},<{high}"
284
+
285
+
286
+ def normalize_poetry_specifiers(spec_str: str) -> str:
287
+ """
288
+ Normalizes Poetry-specific version operators (^ and ~) to PEP 440 compound ranges.
289
+ Also normalizes bare wildcards (* and ==*) to >=0.
290
+ Preserves standard PEP 440 operators intact.
291
+ """
292
+ if not spec_str or not spec_str.strip():
293
+ return ""
294
+ clauses = [c.strip() for c in spec_str.split(",") if c.strip()]
295
+ normalized = []
296
+ for clause in clauses:
297
+ if clause in ("*", "==*"):
298
+ normalized.append(">=0")
299
+ elif clause.startswith("^"):
300
+ ver_part = clause[1:].strip()
301
+ norm = _normalize_poetry_caret(ver_part)
302
+ normalized.append(norm if norm else clause)
303
+ elif clause.startswith("~") and not clause.startswith("~="):
304
+ ver_part = clause[1:].strip()
305
+ norm = _normalize_poetry_tilde(ver_part)
306
+ normalized.append(norm if norm else clause)
307
+ else:
308
+ normalized.append(clause)
309
+ return ",".join(normalized)
310
+
311
+
312
+ def _is_version_in_interval(v: Version, interval: Dict[str, str]) -> bool:
313
+ """Checks if a concrete Version falls inside an OSV event interval."""
314
+ intro_str = interval.get("introduced")
315
+ if intro_str:
316
+ intro_v = _safe_parse_version(intro_str)
317
+ if intro_v is not None and v < intro_v:
318
+ return False
319
+
320
+ fixed_str = interval.get("fixed")
321
+ if fixed_str:
322
+ fixed_v = _safe_parse_version(fixed_str)
323
+ if fixed_v is not None and v >= fixed_v:
324
+ return False
325
+
326
+ last_aff_str = interval.get("last_affected")
327
+ if last_aff_str:
328
+ last_aff_v = _safe_parse_version(last_aff_str)
329
+ if last_aff_v is not None and v > last_aff_v:
330
+ return False
331
+
332
+ limit_str = interval.get("limit")
333
+ if limit_str:
334
+ limit_v = _safe_parse_version(limit_str)
335
+ if limit_v is not None and v >= limit_v:
336
+ return False
337
+
338
+ return True
339
+
340
+
341
+ def _get_specifier_outer_bounds(
342
+ spec_set: SpecifierSet
343
+ ) -> Tuple[Optional[Tuple[Version, bool]], Optional[Tuple[Version, bool]]]:
344
+ """
345
+ Computes effective outer bounds (lower_bound, upper_bound) from a SpecifierSet.
346
+ Returns:
347
+ lower: (Version, is_inclusive) or None
348
+ upper: (Version, is_inclusive) or None
349
+ """
350
+ lower: Optional[Tuple[Version, bool]] = None
351
+ upper: Optional[Tuple[Version, bool]] = None
352
+
353
+ for spec in spec_set:
354
+ op = spec.operator
355
+ ver_str = spec.version
356
+
357
+ if op == ">=":
358
+ v = _safe_parse_version(ver_str)
359
+ if v is not None:
360
+ if lower is None or v > lower[0] or (v == lower[0] and not lower[1]):
361
+ lower = (v, True)
362
+ elif op == ">":
363
+ v = _safe_parse_version(ver_str)
364
+ if v is not None:
365
+ if lower is None or v >= lower[0]:
366
+ lower = (v, False)
367
+ elif op == "<=":
368
+ v = _safe_parse_version(ver_str)
369
+ if v is not None:
370
+ if upper is None or v < upper[0] or (v == upper[0] and not upper[1]):
371
+ upper = (v, True)
372
+ elif op == "<":
373
+ v = _safe_parse_version(ver_str)
374
+ if v is not None:
375
+ if upper is None or v <= upper[0]:
376
+ upper = (v, False)
377
+ elif op == "==":
378
+ if ver_str.endswith(".*"):
379
+ prefix = ver_str[:-2].strip()
380
+ v_low = _safe_parse_version(prefix)
381
+ if v_low is not None:
382
+ if lower is None or v_low > lower[0]:
383
+ lower = (v_low, True)
384
+ parts = [int(p) for p in prefix.split(".") if p.isdigit()]
385
+ if parts:
386
+ parts[-1] += 1
387
+ v_high = _safe_parse_version(".".join(str(p) for p in parts))
388
+ if v_high is not None:
389
+ if upper is None or v_high < upper[0] or (v_high == upper[0] and upper[1]):
390
+ upper = (v_high, False)
391
+ else:
392
+ v = _safe_parse_version(ver_str)
393
+ if v is not None:
394
+ if lower is None or v > lower[0]:
395
+ lower = (v, True)
396
+ if upper is None or v < upper[0]:
397
+ upper = (v, True)
398
+ elif op == "~=":
399
+ v = _safe_parse_version(ver_str)
400
+ if v is not None:
401
+ if lower is None or v > lower[0]:
402
+ lower = (v, True)
403
+ parts = [int(p) for p in ver_str.split(".") if p.isdigit()]
404
+ if len(parts) >= 2:
405
+ prefix = parts[:-1]
406
+ prefix[-1] += 1
407
+ v_high = _safe_parse_version(".".join(str(p) for p in prefix))
408
+ if v_high is not None:
409
+ if upper is None or v_high < upper[0] or (v_high == upper[0] and upper[1]):
410
+ upper = (v_high, False)
411
+
412
+ return lower, upper
413
+
414
+
415
+ def classify_interval_overlap(
416
+ spec_set: SpecifierSet,
417
+ interval: Dict[str, str],
418
+ explicit_versions: Sequence[str]
419
+ ) -> Tuple[OverlapState, Optional[str]]:
420
+ """
421
+ Tri-State overlap classifier.
422
+ Returns (PROVEN_OVERLAP | PROVEN_DISJOINT | UNRESOLVED, matched_range_desc).
423
+ """
424
+ intro_str = interval.get("introduced")
425
+ fixed_str = interval.get("fixed")
426
+ last_aff_str = interval.get("last_affected")
427
+ limit_str = interval.get("limit")
428
+
429
+ intro_v = _safe_parse_version(intro_str) if intro_str else None
430
+ fixed_v = _safe_parse_version(fixed_str) if fixed_str else None
431
+ last_aff_v = _safe_parse_version(last_aff_str) if last_aff_str else None
432
+ limit_v = _safe_parse_version(limit_str) if limit_str else None
433
+
434
+ # If interval has specified bounds that failed to parse into PEP 440:
435
+ if (intro_str and intro_v is None) or (fixed_str and fixed_v is None) or \
436
+ (last_aff_str and last_aff_v is None) or (limit_str and limit_v is None):
437
+ return OverlapState.UNRESOLVED, None
438
+
439
+ # Check for unsupported or ambiguous specifier operators (e.g. ===)
440
+ for spec in spec_set:
441
+ if spec.operator == "===":
442
+ return OverlapState.UNRESOLVED, None
443
+ if not spec.version.endswith(".*") and _safe_parse_version(spec.version) is None:
444
+ return OverlapState.UNRESOLVED, None
445
+
446
+ # Derive outer bounds of the requested specifier set
447
+ lower_bound, upper_bound = _get_specifier_outer_bounds(spec_set)
448
+
449
+ # Check if spec_set is internally unsatisfiable (e.g. >=2.0,<1.0)
450
+ if lower_bound is not None and upper_bound is not None:
451
+ req_low, req_low_inc = lower_bound
452
+ req_up, req_up_inc = upper_bound
453
+ if req_low > req_up or (req_low == req_up and not (req_low_inc and req_up_inc)):
454
+ return OverlapState.PROVEN_DISJOINT, None
455
+
456
+ # 1. MATHEMATICAL PROVEN DISJOINTNESS CHECKS:
457
+ # A. If requested upper bound is below vulnerability lower bound
458
+ if upper_bound is not None and intro_v is not None:
459
+ req_up, req_up_inc = upper_bound
460
+ if req_up < intro_v:
461
+ return OverlapState.PROVEN_DISJOINT, None
462
+ if req_up == intro_v and not req_up_inc:
463
+ return OverlapState.PROVEN_DISJOINT, None
464
+
465
+ # B. If requested lower bound is above vulnerability upper bound
466
+ if lower_bound is not None:
467
+ req_low, req_low_inc = lower_bound
468
+ if fixed_v is not None:
469
+ if req_low > fixed_v:
470
+ return OverlapState.PROVEN_DISJOINT, None
471
+ if req_low == fixed_v and req_low_inc:
472
+ # vulnerable is strictly < fixed_v, requested is >= fixed_v
473
+ return OverlapState.PROVEN_DISJOINT, None
474
+ if last_aff_v is not None:
475
+ if req_low > last_aff_v:
476
+ return OverlapState.PROVEN_DISJOINT, None
477
+ if req_low == last_aff_v and not req_low_inc:
478
+ # vulnerable is <= last_aff_v, requested is > last_aff_v
479
+ return OverlapState.PROVEN_DISJOINT, None
480
+ if limit_v is not None:
481
+ if req_low > limit_v:
482
+ return OverlapState.PROVEN_DISJOINT, None
483
+ if req_low == limit_v and req_low_inc:
484
+ return OverlapState.PROVEN_DISJOINT, None
485
+
486
+ # C. Check degenerate single-version interval (e.g. introduced == last_affected)
487
+ if intro_v is not None and last_aff_v is not None and intro_v == last_aff_v:
488
+ # The ONLY version in this vulnerable range is intro_v
489
+ if intro_v in spec_set:
490
+ return OverlapState.PROVEN_OVERLAP, f"=={intro_str}"
491
+ return OverlapState.PROVEN_DISJOINT, None
492
+
493
+ # 2. PROVEN OVERLAP VIA WITNESS PROBING:
494
+ candidates: List[Version] = []
495
+
496
+ # Explicit versions
497
+ for ev in explicit_versions:
498
+ ev_v = _safe_parse_version(ev)
499
+ if ev_v is not None:
500
+ candidates.append(ev_v)
501
+
502
+ # Event bounds
503
+ if intro_v is not None:
504
+ candidates.append(intro_v)
505
+ if last_aff_v is not None:
506
+ candidates.append(last_aff_v)
507
+
508
+ # Specifier boundary versions
509
+ if lower_bound is not None:
510
+ candidates.append(lower_bound[0])
511
+ for spec in spec_set:
512
+ v_s = _safe_parse_version(spec.version.rstrip(".*"))
513
+ if v_s is not None:
514
+ candidates.append(v_s)
515
+
516
+ # Probing grid around overlap region
517
+ start_v = intro_v or (lower_bound[0] if lower_bound else Version("0.0.1"))
518
+ try:
519
+ parts = [p for p in start_v.base_version.split(".")]
520
+ if len(parts) >= 3:
521
+ maj, mnr, patch = int(parts[0]), int(parts[1]), int(parts[2])
522
+ candidates.extend([
523
+ Version(f"{maj}.{mnr}.0"),
524
+ Version(f"{maj}.{mnr}.{patch + 1}"),
525
+ Version(f"{maj}.{mnr}.{patch + 2}"),
526
+ Version(f"{maj}.{mnr}.{patch + 5}"),
527
+ Version(f"{maj}.{mnr + 1}.0"),
528
+ Version(f"{maj + 1}.0.0"),
529
+ ])
530
+ elif len(parts) == 2:
531
+ maj, mnr = int(parts[0]), int(parts[1])
532
+ candidates.extend([
533
+ Version(f"{maj}.{mnr}.0"),
534
+ Version(f"{maj}.{mnr}.1"),
535
+ Version(f"{maj}.{mnr}.5"),
536
+ Version(f"{maj}.{mnr + 1}.0"),
537
+ Version(f"{maj + 1}.0.0"),
538
+ ])
539
+ except Exception:
540
+ pass
541
+
542
+ # Check candidates for concrete witness
543
+ for cand in candidates:
544
+ if cand in spec_set and _is_version_in_interval(cand, interval):
545
+ return OverlapState.PROVEN_OVERLAP, _format_interval_range(interval)
546
+
547
+ # 3. SOUND FALLBACK (UNRESOLVED):
548
+ # Outer bounds touch or overlap, but candidate probing did not find a witness
549
+ # (e.g. due to complex != exclusions, pre-release boundaries, or custom specs).
550
+ # DO NOT mark safe. Emit UNRESOLVED to avoid silent false clean.
551
+ return OverlapState.UNRESOLVED, _format_interval_range(interval)
552
+
553
+
554
+ class VersionMatcher:
555
+ """
556
+ Deterministic SCA Version Matcher.
557
+ Evaluates DependencyRecords against OSV vulnerabilities.
558
+ """
559
+
560
+ def match_dependency(
561
+ self,
562
+ dep: DependencyRecord,
563
+ osv_result: Optional[OSVQueryResult]
564
+ ) -> List[SCAFinding]:
565
+ """
566
+ Matches a single DependencyRecord against OSV query result.
567
+ Returns a list of SCAFindings (empty list if provably unaffected).
568
+ """
569
+ findings: List[SCAFinding] = []
570
+
571
+ # 1. Handle missing, error, or unverified offline intelligence
572
+ if osv_result is None:
573
+ return [
574
+ SCAFinding(
575
+ package_name=dep.name,
576
+ installed_version=dep.version,
577
+ requested_specifier=dep.version_specifier,
578
+ vulnerability_id="UNKNOWN",
579
+ aliases=[],
580
+ severity=SEVERITY_UNKNOWN,
581
+ cvss_score=None,
582
+ summary="No vulnerability intelligence available for this dependency.",
583
+ fixed_version=None,
584
+ matched_range="",
585
+ confidence=0.0,
586
+ status=STATUS_UNRESOLVED,
587
+ manifest_source=dep.source,
588
+ line_number=dep.line_number,
589
+ )
590
+ ]
591
+
592
+ if osv_result.source == "error":
593
+ err_msg = osv_result.error or "OSV query failed with error"
594
+ return [
595
+ SCAFinding(
596
+ package_name=dep.name,
597
+ installed_version=dep.version,
598
+ requested_specifier=dep.version_specifier,
599
+ vulnerability_id="UNKNOWN",
600
+ aliases=[],
601
+ severity=SEVERITY_UNKNOWN,
602
+ cvss_score=None,
603
+ summary=f"Vulnerability data could not be verified: {err_msg}",
604
+ fixed_version=None,
605
+ matched_range="",
606
+ confidence=0.0,
607
+ status=STATUS_UNRESOLVED,
608
+ manifest_source=dep.source,
609
+ line_number=dep.line_number,
610
+ )
611
+ ]
612
+
613
+ if osv_result.source == "offline_fallback" and not osv_result.vulnerabilities:
614
+ err_msg = osv_result.error or "Offline mode active; dependency unverified in local cache"
615
+ return [
616
+ SCAFinding(
617
+ package_name=dep.name,
618
+ installed_version=dep.version,
619
+ requested_specifier=dep.version_specifier,
620
+ vulnerability_id="UNKNOWN",
621
+ aliases=[],
622
+ severity=SEVERITY_UNKNOWN,
623
+ cvss_score=None,
624
+ summary=f"Vulnerability data could not be verified: {err_msg}",
625
+ fixed_version=None,
626
+ matched_range="",
627
+ confidence=0.0,
628
+ status=STATUS_UNRESOLVED,
629
+ manifest_source=dep.source,
630
+ line_number=dep.line_number,
631
+ )
632
+ ]
633
+
634
+ # If OSV confirmed 0 vulnerabilities (clean package from network or cache)
635
+ if not osv_result.vulnerabilities:
636
+ return []
637
+
638
+ # 2. Evaluate each vulnerability advisory individually
639
+ for vuln in osv_result.vulnerabilities:
640
+ finding = self._evaluate_advisory(dep, vuln)
641
+ if finding is not None:
642
+ findings.append(finding)
643
+
644
+ return findings
645
+
646
+ def _evaluate_advisory(
647
+ self,
648
+ dep: DependencyRecord,
649
+ vuln: OSVVulnerability
650
+ ) -> Optional[SCAFinding]:
651
+ """Evaluates a single dependency against a single vulnerability advisory."""
652
+ severity_str, cvss_score = extract_severity_and_score(vuln)
653
+ summary = vuln.summary or (vuln.details[:200] if vuln.details else "Security vulnerability advisory")
654
+
655
+ # -------------------------------------------------------------
656
+ # BRANCH A: Pinned Dependency (exact version)
657
+ # -------------------------------------------------------------
658
+ if dep.pinned:
659
+ if not dep.version:
660
+ return SCAFinding(
661
+ package_name=dep.name,
662
+ installed_version=dep.version,
663
+ requested_specifier=dep.version_specifier,
664
+ vulnerability_id=vuln.vuln_id,
665
+ aliases=list(vuln.aliases),
666
+ severity=severity_str,
667
+ cvss_score=cvss_score,
668
+ summary=f"Pinned dependency missing version string: {summary}",
669
+ fixed_version=None,
670
+ matched_range="",
671
+ confidence=0.0,
672
+ status=STATUS_UNRESOLVED,
673
+ manifest_source=dep.source,
674
+ line_number=dep.line_number,
675
+ )
676
+
677
+ try:
678
+ pinned_v = Version(dep.version)
679
+ except InvalidVersion:
680
+ return SCAFinding(
681
+ package_name=dep.name,
682
+ installed_version=dep.version,
683
+ requested_specifier=dep.version_specifier,
684
+ vulnerability_id=vuln.vuln_id,
685
+ aliases=list(vuln.aliases),
686
+ severity=severity_str,
687
+ cvss_score=cvss_score,
688
+ summary=f"Invalid PEP 440 version '{dep.version}': {summary}",
689
+ fixed_version=None,
690
+ matched_range="",
691
+ confidence=0.0,
692
+ status=STATUS_UNRESOLVED,
693
+ manifest_source=dep.source,
694
+ line_number=dep.line_number,
695
+ )
696
+
697
+ has_unresolved = False
698
+ unresolved_desc = ""
699
+
700
+ applicable_ranges = [r for r in vuln.affected_ranges if r.type.upper() in ("ECOSYSTEM", "SEMVER")]
701
+ if not applicable_ranges:
702
+ applicable_ranges = vuln.affected_ranges
703
+
704
+ # Match against affected ranges
705
+ for aff_range in applicable_ranges:
706
+ intervals = extract_intervals_from_events(aff_range.events)
707
+ for interval in intervals:
708
+ # Check unparseable interval bounds
709
+ intro_str = interval.get("introduced")
710
+ fixed_str = interval.get("fixed")
711
+ last_aff_str = interval.get("last_affected")
712
+ if (intro_str and _safe_parse_version(intro_str) is None) or \
713
+ (fixed_str and _safe_parse_version(fixed_str) is None) or \
714
+ (last_aff_str and _safe_parse_version(last_aff_str) is None):
715
+ has_unresolved = True
716
+ unresolved_desc = _format_interval_range(interval)
717
+ continue
718
+
719
+ if _is_version_in_interval(pinned_v, interval):
720
+ fixed_ver = interval.get("fixed")
721
+ matched_rng = _format_interval_range(interval)
722
+ return SCAFinding(
723
+ package_name=dep.name,
724
+ installed_version=dep.version,
725
+ requested_specifier=dep.version_specifier,
726
+ vulnerability_id=vuln.vuln_id,
727
+ aliases=list(vuln.aliases),
728
+ severity=severity_str,
729
+ cvss_score=cvss_score,
730
+ summary=summary,
731
+ fixed_version=fixed_ver,
732
+ matched_range=matched_rng,
733
+ confidence=1.0,
734
+ status=STATUS_CONFIRMED,
735
+ manifest_source=dep.source,
736
+ line_number=dep.line_number,
737
+ )
738
+
739
+ # Fallback: check explicit versions list
740
+ if aff_range.versions:
741
+ for ev in aff_range.versions:
742
+ ev_v = _safe_parse_version(ev)
743
+ if ev_v is not None and pinned_v == ev_v:
744
+ return SCAFinding(
745
+ package_name=dep.name,
746
+ installed_version=dep.version,
747
+ requested_specifier=dep.version_specifier,
748
+ vulnerability_id=vuln.vuln_id,
749
+ aliases=list(vuln.aliases),
750
+ severity=severity_str,
751
+ cvss_score=cvss_score,
752
+ summary=summary,
753
+ fixed_version=None,
754
+ matched_range=f"=={dep.version}",
755
+ confidence=1.0,
756
+ status=STATUS_CONFIRMED,
757
+ manifest_source=dep.source,
758
+ line_number=dep.line_number,
759
+ )
760
+
761
+ if has_unresolved:
762
+ return SCAFinding(
763
+ package_name=dep.name,
764
+ installed_version=dep.version,
765
+ requested_specifier=dep.version_specifier,
766
+ vulnerability_id=vuln.vuln_id,
767
+ aliases=list(vuln.aliases),
768
+ severity=severity_str,
769
+ cvss_score=cvss_score,
770
+ summary=f"Unparseable advisory range '{unresolved_desc}': {summary}",
771
+ fixed_version=None,
772
+ matched_range=unresolved_desc,
773
+ confidence=0.0,
774
+ status=STATUS_UNRESOLVED,
775
+ manifest_source=dep.source,
776
+ line_number=dep.line_number,
777
+ )
778
+
779
+ # Clearly outside all affected ranges -> emit no finding
780
+ return None
781
+
782
+ # -------------------------------------------------------------
783
+ # BRANCH B: Unpinned / Range Dependency
784
+ # -------------------------------------------------------------
785
+ raw_spec_str = dep.version_specifier or ""
786
+ # If dependency has no specifier (e.g. bare "requests"), it accepts any version
787
+ if not raw_spec_str.strip():
788
+ spec_str = ">=0"
789
+ else:
790
+ spec_str = normalize_poetry_specifiers(raw_spec_str)
791
+
792
+ try:
793
+ spec_set = SpecifierSet(spec_str)
794
+ except (InvalidSpecifier, Exception):
795
+ return SCAFinding(
796
+ package_name=dep.name,
797
+ installed_version=dep.version,
798
+ requested_specifier=dep.version_specifier,
799
+ vulnerability_id=vuln.vuln_id,
800
+ aliases=list(vuln.aliases),
801
+ severity=severity_str,
802
+ cvss_score=cvss_score,
803
+ summary=f"Ambiguous or invalid version specifier '{raw_spec_str}': {summary}",
804
+ fixed_version=None,
805
+ matched_range="",
806
+ confidence=0.0,
807
+ status=STATUS_UNRESOLVED,
808
+ manifest_source=dep.source,
809
+ line_number=dep.line_number,
810
+ )
811
+
812
+ found_overlap: Optional[Tuple[str, Optional[str]]] = None # (desc, fixed)
813
+ has_unresolved = False
814
+ unresolved_desc = ""
815
+
816
+ applicable_ranges = [r for r in vuln.affected_ranges if r.type.upper() in ("ECOSYSTEM", "SEMVER")]
817
+ if not applicable_ranges:
818
+ applicable_ranges = vuln.affected_ranges
819
+
820
+ for aff_range in applicable_ranges:
821
+ intervals = extract_intervals_from_events(aff_range.events)
822
+
823
+ # Case B1: Events intervals exist
824
+ for interval in intervals:
825
+ state, matched_desc = classify_interval_overlap(spec_set, interval, aff_range.versions)
826
+ if state == OverlapState.PROVEN_OVERLAP:
827
+ found_overlap = (matched_desc or _format_interval_range(interval), interval.get("fixed"))
828
+ break
829
+ elif state == OverlapState.UNRESOLVED:
830
+ has_unresolved = True
831
+ unresolved_desc = matched_desc or _format_interval_range(interval)
832
+
833
+ if found_overlap:
834
+ break
835
+
836
+ # Case B2: No interval events, only explicit versions
837
+ if not intervals and aff_range.versions:
838
+ admitted = []
839
+ unparseable = False
840
+ for ev in aff_range.versions:
841
+ ev_v = _safe_parse_version(ev)
842
+ if ev_v is None:
843
+ unparseable = True
844
+ elif ev_v in spec_set:
845
+ admitted.append(ev)
846
+ if admitted:
847
+ found_overlap = (f"in ({', '.join(admitted[:3])})", None)
848
+ break
849
+ elif unparseable:
850
+ has_unresolved = True
851
+ unresolved_desc = "unparseable version in advisory"
852
+
853
+ if found_overlap:
854
+ matched_desc, fixed_ver = found_overlap
855
+ return SCAFinding(
856
+ package_name=dep.name,
857
+ installed_version=dep.version,
858
+ requested_specifier=dep.version_specifier,
859
+ vulnerability_id=vuln.vuln_id,
860
+ aliases=list(vuln.aliases),
861
+ severity=severity_str,
862
+ cvss_score=cvss_score,
863
+ summary=summary,
864
+ fixed_version=fixed_ver,
865
+ matched_range=matched_desc,
866
+ confidence=0.6,
867
+ status=STATUS_POTENTIAL,
868
+ manifest_source=dep.source,
869
+ line_number=dep.line_number,
870
+ )
871
+
872
+ if has_unresolved:
873
+ return SCAFinding(
874
+ package_name=dep.name,
875
+ installed_version=dep.version,
876
+ requested_specifier=dep.version_specifier,
877
+ vulnerability_id=vuln.vuln_id,
878
+ aliases=list(vuln.aliases),
879
+ severity=severity_str,
880
+ cvss_score=cvss_score,
881
+ summary=f"Indeterminate overlap with vulnerable range '{unresolved_desc}': {summary}",
882
+ fixed_version=None,
883
+ matched_range=unresolved_desc,
884
+ confidence=0.0,
885
+ status=STATUS_UNRESOLVED,
886
+ manifest_source=dep.source,
887
+ line_number=dep.line_number,
888
+ )
889
+
890
+ # All intervals and explicit version sets are PROVEN_DISJOINT -> emit no finding
891
+ return None
892
+
893
+ def match_dependencies(
894
+ self,
895
+ dependencies: List[DependencyRecord],
896
+ osv_results: Dict[str, OSVQueryResult]
897
+ ) -> List[SCAFinding]:
898
+ """
899
+ Matches multiple DependencyRecords against OSV query results.
900
+ Returns deterministically sorted findings list.
901
+ """
902
+ all_findings: List[SCAFinding] = []
903
+
904
+ for dep in dependencies:
905
+ norm_name = normalize_package_name(dep.name)
906
+ osv_res = osv_results.get(norm_name)
907
+ dep_findings = self.match_dependency(dep, osv_res)
908
+ all_findings.extend(dep_findings)
909
+
910
+ # Stable deterministic sort: package_name, vuln_id, source, line_number, status
911
+ all_findings.sort(key=lambda f: (
912
+ f.package_name,
913
+ f.vulnerability_id,
914
+ f.manifest_source,
915
+ f.line_number if f.line_number is not None else -1,
916
+ f.status,
917
+ f.matched_range
918
+ ))
919
+
920
+ return all_findings
921
+
922
+
923
+ # Module-level convenience functions
924
+ def match_dependency(dep: DependencyRecord, osv_result: Optional[OSVQueryResult]) -> List[SCAFinding]:
925
+ """Convenience function to match a single dependency."""
926
+ return VersionMatcher().match_dependency(dep, osv_result)
927
+
928
+
929
+ def match_dependencies(
930
+ dependencies: List[DependencyRecord],
931
+ osv_results: Dict[str, OSVQueryResult]
932
+ ) -> List[SCAFinding]:
933
+ """Convenience function to match multiple dependencies."""
934
+ return VersionMatcher().match_dependencies(dependencies, osv_results)