stackparity 1.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.
- stackparity/__init__.py +17 -0
- stackparity/_engine/agents/investigator.py +294 -0
- stackparity/_engine/agents/memory_agent.py +37 -0
- stackparity/_engine/agents/pipeline_agent.py +152 -0
- stackparity/_engine/agents/remediation_agent.py +248 -0
- stackparity/_engine/agents/runtime.py +177 -0
- stackparity/_engine/agents/specialists.py +709 -0
- stackparity/_engine/agents/suspicious_change_agent.py +1275 -0
- stackparity/_engine/cli/__init__.py +2 -0
- stackparity/_engine/cli/main.py +1252 -0
- stackparity/_engine/cli/remediate.py +461 -0
- stackparity/_engine/cli/term.py +44 -0
- stackparity/_engine/config/__init__.py +0 -0
- stackparity/_engine/config/constants.py +88 -0
- stackparity/_engine/config/loader.py +155 -0
- stackparity/_engine/config/settings.py +108 -0
- stackparity/_engine/containers/__init__.py +12 -0
- stackparity/_engine/containers/discovery.py +143 -0
- stackparity/_engine/containers/models.py +72 -0
- stackparity/_engine/containers/trivy_image_scanner.py +165 -0
- stackparity/_engine/core/__init__.py +0 -0
- stackparity/_engine/core/capabilities.py +107 -0
- stackparity/_engine/core/finding_schema.py +305 -0
- stackparity/_engine/core/git_manager.py +206 -0
- stackparity/_engine/core/http.py +64 -0
- stackparity/_engine/core/models.py +109 -0
- stackparity/_engine/core/netpolicy.py +242 -0
- stackparity/_engine/core/plugins.py +43 -0
- stackparity/_engine/core/repository_inspector.py +243 -0
- stackparity/_engine/core/safe_env.py +48 -0
- stackparity/_engine/core/scan_orchestrator.py +289 -0
- stackparity/_engine/core/scan_state.py +58 -0
- stackparity/_engine/core/url_validator.py +135 -0
- stackparity/_engine/ecosystems/__init__.py +1 -0
- stackparity/_engine/ecosystems/registry.py +138 -0
- stackparity/_engine/evidence/__init__.py +1 -0
- stackparity/_engine/evidence/store.py +65 -0
- stackparity/_engine/explainability/__init__.py +0 -0
- stackparity/_engine/explainability/evidence_formatter.py +30 -0
- stackparity/_engine/explainability/explanation_engine.py +132 -0
- stackparity/_engine/explainability/explanation_validator.py +54 -0
- stackparity/_engine/explainability/prompt_templates.py +18 -0
- stackparity/_engine/graph/__init__.py +0 -0
- stackparity/_engine/graph/dependency_tracer.py +86 -0
- stackparity/_engine/graph/graph_builder.py +165 -0
- stackparity/_engine/graph/graph_diff.py +57 -0
- stackparity/_engine/graph/graph_exporter.py +194 -0
- stackparity/_engine/graph/graph_validator.py +46 -0
- stackparity/_engine/graph/impact_analyzer.py +23 -0
- stackparity/_engine/graph/tree_view.py +185 -0
- stackparity/_engine/intel/__init__.py +0 -0
- stackparity/_engine/intel/epss.py +53 -0
- stackparity/_engine/llm/__init__.py +1 -0
- stackparity/_engine/llm/client.py +138 -0
- stackparity/_engine/monitor/__init__.py +0 -0
- stackparity/_engine/monitor/watch.py +171 -0
- stackparity/_engine/non_cve/__init__.py +7 -0
- stackparity/_engine/non_cve/base.py +62 -0
- stackparity/_engine/non_cve/iac.py +144 -0
- stackparity/_engine/non_cve/sast.py +272 -0
- stackparity/_engine/non_cve/supply_chain.py +147 -0
- stackparity/_engine/orchestration/__init__.py +1 -0
- stackparity/_engine/orchestration/pipeline.py +279 -0
- stackparity/_engine/orchestration/supervisor.py +167 -0
- stackparity/_engine/pipeline_analysis/__init__.py +0 -0
- stackparity/_engine/pipeline_analysis/analyzer.py +90 -0
- stackparity/_engine/pipeline_analysis/ci.py +189 -0
- stackparity/_engine/pipeline_analysis/ci_adapters/__init__.py +24 -0
- stackparity/_engine/pipeline_analysis/ci_adapters/azure_pipelines.py +221 -0
- stackparity/_engine/pipeline_analysis/ci_adapters/base.py +239 -0
- stackparity/_engine/pipeline_analysis/ci_adapters/circleci.py +176 -0
- stackparity/_engine/pipeline_analysis/ci_adapters/github_actions.py +356 -0
- stackparity/_engine/pipeline_analysis/ci_adapters/gitlab_ci.py +268 -0
- stackparity/_engine/pipeline_analysis/ci_adapters/jenkins.py +180 -0
- stackparity/_engine/pipeline_analysis/ci_adapters/registry.py +80 -0
- stackparity/_engine/pipeline_analysis/ci_models.py +72 -0
- stackparity/_engine/pipeline_analysis/dockerfile.py +235 -0
- stackparity/_engine/pipeline_analysis/eol.py +62 -0
- stackparity/_engine/pipeline_analysis/models.py +37 -0
- stackparity/_engine/policy/__init__.py +0 -0
- stackparity/_engine/policy/engine.py +216 -0
- stackparity/_engine/policy/resources/default.yaml +56 -0
- stackparity/_engine/policy/resources/strict.yaml +35 -0
- stackparity/_engine/reachability/__init__.py +0 -0
- stackparity/_engine/reachability/app_reachability.py +186 -0
- stackparity/_engine/reachability/scanners.py +215 -0
- stackparity/_engine/remediation/__init__.py +0 -0
- stackparity/_engine/remediation/adapters.py +198 -0
- stackparity/_engine/remediation/apply_local.py +309 -0
- stackparity/_engine/remediation/code_fixes.py +383 -0
- stackparity/_engine/remediation/compat.py +156 -0
- stackparity/_engine/remediation/container_plan.py +127 -0
- stackparity/_engine/remediation/delivery.py +31 -0
- stackparity/_engine/remediation/export.py +44 -0
- stackparity/_engine/remediation/lifecycle.py +623 -0
- stackparity/_engine/remediation/local_trial.py +358 -0
- stackparity/_engine/remediation/patchers.py +215 -0
- stackparity/_engine/remediation/planner.py +285 -0
- stackparity/_engine/remediation/pr_template_engine.py +234 -0
- stackparity/_engine/remediation/reachability_impact.py +147 -0
- stackparity/_engine/remediation/versions.py +92 -0
- stackparity/_engine/remediation/whatif.py +64 -0
- stackparity/_engine/remediation/worktree_pr.py +434 -0
- stackparity/_engine/reporting/__init__.py +0 -0
- stackparity/_engine/reporting/counts.py +63 -0
- stackparity/_engine/reporting/fix_pdf.py +343 -0
- stackparity/_engine/reporting/fix_report.py +135 -0
- stackparity/_engine/reporting/json_exporter.py +61 -0
- stackparity/_engine/reporting/report_generator.py +200 -0
- stackparity/_engine/reporting/sarif.py +71 -0
- stackparity/_engine/reporting/vex.py +57 -0
- stackparity/_engine/reporting/view.py +166 -0
- stackparity/_engine/risk_analysis/__init__.py +0 -0
- stackparity/_engine/risk_analysis/contextual_scorer.py +253 -0
- stackparity/_engine/risk_analysis/evidence_collector.py +62 -0
- stackparity/_engine/risk_analysis/evidence_normalizer.py +37 -0
- stackparity/_engine/risk_analysis/finding_correlator.py +90 -0
- stackparity/_engine/risk_analysis/function_impact.py +184 -0
- stackparity/_engine/risk_analysis/production_context.py +252 -0
- stackparity/_engine/risk_analysis/risk_rules.py +81 -0
- stackparity/_engine/risk_analysis/risk_scorer.py +390 -0
- stackparity/_engine/sandbox/__init__.py +0 -0
- stackparity/_engine/sandbox/runner.py +142 -0
- stackparity/_engine/sbom/__init__.py +0 -0
- stackparity/_engine/sbom/adapters/__init__.py +19 -0
- stackparity/_engine/sbom/adapters/builtin.py +29 -0
- stackparity/_engine/sbom/adapters/syft.py +26 -0
- stackparity/_engine/sbom/adapters/trivy.py +76 -0
- stackparity/_engine/sbom/builtin_generator.py +227 -0
- stackparity/_engine/sbom/cyclonedx_validator.py +166 -0
- stackparity/_engine/sbom/exporters.py +153 -0
- stackparity/_engine/sbom/fusion/__init__.py +5 -0
- stackparity/_engine/sbom/fusion/engine.py +315 -0
- stackparity/_engine/sbom/fusion/hashes.py +47 -0
- stackparity/_engine/sbom/fusion/ledger.py +96 -0
- stackparity/_engine/sbom/fusion/registries.py +271 -0
- stackparity/_engine/sbom/fusion/resolver.py +143 -0
- stackparity/_engine/sbom/fusion/writer.py +114 -0
- stackparity/_engine/sbom/lockfile_analyzer.py +114 -0
- stackparity/_engine/sbom/merge.py +71 -0
- stackparity/_engine/sbom/package_extractors/common.py +104 -0
- stackparity/_engine/sbom/package_extractors/manifests.py +101 -0
- stackparity/_engine/sbom/package_extractors/npm.py +206 -0
- stackparity/_engine/sbom/package_extractors/others.py +267 -0
- stackparity/_engine/sbom/package_extractors/python.py +143 -0
- stackparity/_engine/sbom/quality_analyzer.py +191 -0
- stackparity/_engine/sbom/scanner_engine.py +98 -0
- stackparity/_engine/sbom/syft_runner.py +100 -0
- stackparity/_engine/sbom/tool_locator.py +69 -0
- stackparity/_engine/sbom/trivy_runner.py +82 -0
- stackparity/_engine/storage/__init__.py +0 -0
- stackparity/_engine/storage/cache.py +56 -0
- stackparity/_engine/storage/database.py +295 -0
- stackparity/_engine/storage/memory.py +146 -0
- stackparity/_engine/suspicious_changes/__init__.py +12 -0
- stackparity/_engine/suspicious_changes/analyzer.py +1022 -0
- stackparity/_engine/suspicious_changes/change_correlation.py +861 -0
- stackparity/_engine/suspicious_changes/lifecycle_script_detector.py +263 -0
- stackparity/_engine/suspicious_changes/lockfile_change_detector.py +316 -0
- stackparity/_engine/suspicious_changes/manifest_diff_detector.py +251 -0
- stackparity/_engine/suspicious_changes/package_risk.py +78 -0
- stackparity/_engine/suspicious_changes/popular_packages.py +94 -0
- stackparity/_engine/suspicious_changes/registry_detector.py +354 -0
- stackparity/_engine/suspicious_changes/suspicious_models.py +57 -0
- stackparity/_engine/suspicious_changes/typosquatting_detector.py +298 -0
- stackparity/_engine/tools/__init__.py +1 -0
- stackparity/_engine/tools/builtin.py +93 -0
- stackparity/_engine/tools/registry.py +66 -0
- stackparity/_engine/ui/__init__.py +0 -0
- stackparity/_engine/ui/components/__init__.py +0 -0
- stackparity/_engine/ui/components/common.py +238 -0
- stackparity/_engine/ui/components/live_progress.py +157 -0
- stackparity/_engine/ui/components/memory_panel.py +82 -0
- stackparity/_engine/ui/pages/__init__.py +0 -0
- stackparity/_engine/ui/pages/agents_page.py +76 -0
- stackparity/_engine/ui/pages/architecture_page.py +44 -0
- stackparity/_engine/ui/pages/fixes_page.py +98 -0
- stackparity/_engine/ui/pages/graph_page.py +203 -0
- stackparity/_engine/ui/pages/health_page.py +117 -0
- stackparity/_engine/ui/pages/monitor_page.py +67 -0
- stackparity/_engine/ui/pages/pipeline_page.py +219 -0
- stackparity/_engine/ui/pages/remediation_page.py +409 -0
- stackparity/_engine/ui/pages/reports_page.py +54 -0
- stackparity/_engine/ui/pages/sbom_page.py +210 -0
- stackparity/_engine/ui/pages/scan_page.py +131 -0
- stackparity/_engine/ui/pages/suspicious_page.py +551 -0
- stackparity/_engine/ui/pages/vulns_page.py +201 -0
- stackparity/_engine/ui/state.py +116 -0
- stackparity/_engine/ui/theme.py +201 -0
- stackparity/_engine/ui/visualizations/__init__.py +0 -0
- stackparity/_engine/ui/visualizations/graphs.py +373 -0
- stackparity/_engine/vulnerability/__init__.py +0 -0
- stackparity/_engine/vulnerability/cvss.py +58 -0
- stackparity/_engine/vulnerability/kev_client.py +47 -0
- stackparity/_engine/vulnerability/nvd_client.py +74 -0
- stackparity/_engine/vulnerability/osv_client.py +139 -0
- stackparity/_engine/vulnerability/remediation_engine.py +50 -0
- stackparity/_engine/vulnerability/verification.py +94 -0
- stackparity/_engine/vulnerability/version_matcher.py +299 -0
- stackparity/_engine/vulnerability/vulnerability_correlator.py +303 -0
- stackparity/_engine/vulnerability/vulnerability_models.py +64 -0
- stackparity/cli.py +30 -0
- stackparity/dashboard_app.py +95 -0
- stackparity/web_dist/assets/index-DRJYw2Du.css +1 -0
- stackparity/web_dist/assets/index-Q6LLpbEi.js +495 -0
- stackparity/web_dist/index.html +13 -0
- stackparity/web_server.py +533 -0
- stackparity-1.0.0.dist-info/METADATA +204 -0
- stackparity-1.0.0.dist-info/RECORD +212 -0
- stackparity-1.0.0.dist-info/WHEEL +4 -0
- stackparity-1.0.0.dist-info/entry_points.txt +2 -0
- stackparity-1.0.0.dist-info/licenses/LICENSE +201 -0
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
"""OSV.dev client: batch queries (with pagination), full advisory retrieval, SQLite caching, explicit failure states."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import time
|
|
5
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
6
|
+
from typing import Any, Optional
|
|
7
|
+
|
|
8
|
+
from core.http import HttpClient, NotFound, SourceUnavailable
|
|
9
|
+
from storage.cache import Cache
|
|
10
|
+
|
|
11
|
+
QUERYBATCH = "https://api.osv.dev/v1/querybatch"
|
|
12
|
+
QUERY = "https://api.osv.dev/v1/query"
|
|
13
|
+
VULN = "https://api.osv.dev/v1/vulns/{id}"
|
|
14
|
+
QUERY_TTL = 12 * 3600
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def qkey(ecosystem: str, name: str, version: str) -> str:
|
|
18
|
+
return f"{ecosystem}|{name}|{version}"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class OsvClient:
|
|
22
|
+
def __init__(self, http: HttpClient, cache: Cache | None = None, batch_size: int = 500, workers: int = 8):
|
|
23
|
+
self.http, self.cache, self.batch_size, self.workers = http, cache, batch_size, workers
|
|
24
|
+
self.status: dict[str, Any] = {"source": "OSV", "state": "ok", "queries": 0, "from_cache": 0, "stale_cache": 0,
|
|
25
|
+
"unavailable": 0, "advisories_fetched": 0, "errors": []}
|
|
26
|
+
|
|
27
|
+
# -------------------------------------------------- batch
|
|
28
|
+
def query_packages(self, packages: list[tuple[str, str, str]]) -> dict[str, dict]:
|
|
29
|
+
"""packages: [(ecosystem, name, version)] -> {qkey: {"vulns": [{id, modified}], "state": ok|cached|stale|unavailable}}"""
|
|
30
|
+
out: dict[str, dict] = {}
|
|
31
|
+
todo: list[tuple[str, str, str]] = []
|
|
32
|
+
for p in dict.fromkeys(packages):
|
|
33
|
+
k = qkey(*p)
|
|
34
|
+
hit = self.cache.get("osv_query", k, ttl=QUERY_TTL) if self.cache else None
|
|
35
|
+
if hit is not None:
|
|
36
|
+
out[k] = {"vulns": hit, "state": "cached"}
|
|
37
|
+
self.status["from_cache"] += 1
|
|
38
|
+
else:
|
|
39
|
+
todo.append(p)
|
|
40
|
+
for i in range(0, len(todo), self.batch_size):
|
|
41
|
+
chunk = todo[i:i + self.batch_size]
|
|
42
|
+
payload = {"queries": [{"package": {"name": n, "ecosystem": e}, "version": v} for e, n, v in chunk]}
|
|
43
|
+
self.status["queries"] += len(chunk)
|
|
44
|
+
try:
|
|
45
|
+
resp = self.http.post_json(QUERYBATCH, payload)
|
|
46
|
+
results = resp.get("results", [])
|
|
47
|
+
if len(results) != len(chunk):
|
|
48
|
+
raise SourceUnavailable("OSV returned a result list of unexpected length")
|
|
49
|
+
for p, res in zip(chunk, results):
|
|
50
|
+
vulns = list(res.get("vulns") or [])
|
|
51
|
+
token = res.get("next_page_token")
|
|
52
|
+
while token:
|
|
53
|
+
page = self.http.post_json(QUERY, {"package": {"name": p[1], "ecosystem": p[0]}, "version": p[2],
|
|
54
|
+
"page_token": token})
|
|
55
|
+
vulns += page.get("vulns") or []
|
|
56
|
+
token = page.get("next_page_token")
|
|
57
|
+
out[qkey(*p)] = {"vulns": [{"id": v["id"], "modified": v.get("modified")} for v in vulns], "state": "ok"}
|
|
58
|
+
if self.cache:
|
|
59
|
+
self.cache.set("osv_query", qkey(*p), out[qkey(*p)]["vulns"])
|
|
60
|
+
except (SourceUnavailable, KeyError, ValueError) as e:
|
|
61
|
+
self.status["errors"].append(str(e)[:200])
|
|
62
|
+
for p in chunk:
|
|
63
|
+
stale = self.cache.get("osv_query", qkey(*p), allow_stale=True) if self.cache else None
|
|
64
|
+
if stale is not None:
|
|
65
|
+
out[qkey(*p)] = {"vulns": stale, "state": "stale"}
|
|
66
|
+
self.status["stale_cache"] += 1
|
|
67
|
+
else:
|
|
68
|
+
out[qkey(*p)] = {"vulns": [], "state": "unavailable"}
|
|
69
|
+
self.status["unavailable"] += 1
|
|
70
|
+
if self.status["unavailable"]:
|
|
71
|
+
self.status["state"] = "partial" if len(out) > self.status["unavailable"] else "unavailable"
|
|
72
|
+
elif self.status["stale_cache"]:
|
|
73
|
+
self.status["state"] = "stale_cache"
|
|
74
|
+
return out
|
|
75
|
+
|
|
76
|
+
def query_purls(self, purls: list[str]) -> dict[str, dict]:
|
|
77
|
+
"""Independent query route: OSV resolves ecosystem/name/version itself from the PURL."""
|
|
78
|
+
out: dict[str, dict] = {}
|
|
79
|
+
todo = []
|
|
80
|
+
for p in dict.fromkeys(purls):
|
|
81
|
+
hit = self.cache.get("osv_query_purl", p, ttl=QUERY_TTL) if self.cache else None
|
|
82
|
+
if hit is not None:
|
|
83
|
+
out[p] = {"vulns": hit, "state": "cached"}
|
|
84
|
+
else:
|
|
85
|
+
todo.append(p)
|
|
86
|
+
for i in range(0, len(todo), self.batch_size):
|
|
87
|
+
chunk = todo[i:i + self.batch_size]
|
|
88
|
+
try:
|
|
89
|
+
resp = self.http.post_json(QUERYBATCH, {"queries": [{"package": {"purl": p}} for p in chunk]})
|
|
90
|
+
results = resp.get("results", [])
|
|
91
|
+
if len(results) != len(chunk):
|
|
92
|
+
raise SourceUnavailable("unexpected OSV result length")
|
|
93
|
+
for p, res in zip(chunk, results):
|
|
94
|
+
vulns = list(res.get("vulns") or [])
|
|
95
|
+
token = res.get("next_page_token")
|
|
96
|
+
while token:
|
|
97
|
+
page = self.http.post_json(QUERY, {"package": {"purl": p}, "page_token": token})
|
|
98
|
+
vulns += page.get("vulns") or []
|
|
99
|
+
token = page.get("next_page_token")
|
|
100
|
+
out[p] = {"vulns": [{"id": v["id"], "modified": v.get("modified")} for v in vulns], "state": "ok"}
|
|
101
|
+
if self.cache:
|
|
102
|
+
self.cache.set("osv_query_purl", p, out[p]["vulns"])
|
|
103
|
+
except (SourceUnavailable, KeyError, ValueError) as e:
|
|
104
|
+
self.status["errors"].append(str(e)[:200])
|
|
105
|
+
for p in chunk:
|
|
106
|
+
out[p] = {"vulns": [], "state": "unavailable"}
|
|
107
|
+
return out
|
|
108
|
+
|
|
109
|
+
# -------------------------------------------------- advisories
|
|
110
|
+
def get_advisory(self, vuln_id: str, modified: Optional[str] = None) -> Optional[dict]:
|
|
111
|
+
"""Return {"record": {...}, "retrieved_at": iso, "stale": bool} or None if unobtainable."""
|
|
112
|
+
cached = self.cache.get_with_time("osv_vuln", vuln_id) if self.cache else None
|
|
113
|
+
if cached:
|
|
114
|
+
rec, ts = cached
|
|
115
|
+
if modified is None or rec.get("modified") == modified:
|
|
116
|
+
return {"record": rec, "retrieved_at": _iso(ts), "stale": False}
|
|
117
|
+
try:
|
|
118
|
+
rec = self.http.get_json(VULN.format(id=vuln_id))
|
|
119
|
+
self.status["advisories_fetched"] += 1
|
|
120
|
+
if self.cache:
|
|
121
|
+
self.cache.set("osv_vuln", vuln_id, rec)
|
|
122
|
+
return {"record": rec, "retrieved_at": _iso(time.time()), "stale": False}
|
|
123
|
+
except NotFound:
|
|
124
|
+
return None
|
|
125
|
+
except SourceUnavailable as e:
|
|
126
|
+
self.status["errors"].append(str(e)[:200])
|
|
127
|
+
if cached:
|
|
128
|
+
return {"record": cached[0], "retrieved_at": _iso(cached[1]), "stale": True}
|
|
129
|
+
return None
|
|
130
|
+
|
|
131
|
+
def get_advisories(self, items: list[tuple[str, Optional[str]]]) -> dict[str, Optional[dict]]:
|
|
132
|
+
uniq = list(dict.fromkeys(items))
|
|
133
|
+
with ThreadPoolExecutor(max_workers=self.workers) as ex:
|
|
134
|
+
res = list(ex.map(lambda it: self.get_advisory(*it), uniq))
|
|
135
|
+
return {it[0]: r for it, r in zip(uniq, res)}
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _iso(ts: float) -> str:
|
|
139
|
+
return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(ts))
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""Remediation guidance. States only what the evidence supports; compatibility is never assumed."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from vulnerability.vulnerability_models import VulnerabilityFinding
|
|
5
|
+
|
|
6
|
+
OVERRIDE_HINTS = {
|
|
7
|
+
"npm": "npm: add an `overrides` entry (Yarn: `resolutions`, pnpm: `pnpm.overrides`) in the root package.json",
|
|
8
|
+
"PyPI": "Python: pin the package in requirements/constraints (`pip install -c constraints.txt`) or poetry/uv constraints",
|
|
9
|
+
"Maven": "Maven: pin the version in `<dependencyManagement>` (Gradle: `constraints {}` / resolutionStrategy)",
|
|
10
|
+
"Go": "Go: `go get <module>@<fixed>` (or a `replace` directive) then `go mod tidy`",
|
|
11
|
+
"crates.io": "Rust: `cargo update -p <crate> --precise <fixed>` or tighten the version requirement",
|
|
12
|
+
"Packagist": "PHP: `composer require <vendor/package>:<fixed>` (or add it to `conflict`/`require` constraints)",
|
|
13
|
+
"NuGet": "NuGet: add a direct PackageReference (or Central Package Management pin) for the fixed version",
|
|
14
|
+
"RubyGems": "Ruby: constrain the gem in the Gemfile and run `bundle update <gem>`",
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def build_remediation(f: VulnerabilityFinding) -> str:
|
|
19
|
+
fixes = f.fixed_versions
|
|
20
|
+
lines: list[str] = []
|
|
21
|
+
if f.affected_status == "unknown":
|
|
22
|
+
lines.append("Applicability could not be confirmed automatically for this version; review the advisory before acting.")
|
|
23
|
+
if f.recommended_fix:
|
|
24
|
+
others = [v for v in fixes if v != f.recommended_fix]
|
|
25
|
+
base = f"Upgrade {f.package_name} from {f.installed_version} to {f.recommended_fix} or later in the same advisory line"
|
|
26
|
+
if others:
|
|
27
|
+
base += f" (other fixed releases recorded: {', '.join(others[:5])})"
|
|
28
|
+
lines.append(base + ".")
|
|
29
|
+
else:
|
|
30
|
+
lines.append(f"No fixed version is recorded in the advisory data for {f.package_name} {f.installed_version}. "
|
|
31
|
+
"Check the advisory references for mitigations, a maintained fork, or replacement options; "
|
|
32
|
+
"absence of a fix is not by itself an indicator of severity.")
|
|
33
|
+
if f.dependency_type == "transitive" and f.exposures:
|
|
34
|
+
e = next((x for x in f.exposures if x["relationship"] == "transitive"), f.exposures[0])
|
|
35
|
+
path = e["paths"][0] if e.get("paths") else []
|
|
36
|
+
chain = " -> ".join(path) if path else "(path unavailable)"
|
|
37
|
+
parent = e["immediate_parents"][0] if e.get("immediate_parents") else "its parent"
|
|
38
|
+
lines.append(f"It is pulled in transitively ({chain}). Rather than only bumping the top-level dependency, check whether a "
|
|
39
|
+
f"newer release of {parent} (or of the direct dependency in this chain) resolves to a fixed {f.package_name}. "
|
|
40
|
+
"Compatibility with the parent's declared version constraint was not verified by this scan.")
|
|
41
|
+
if f.recommended_fix and f.ecosystem in OVERRIDE_HINTS:
|
|
42
|
+
lines.append("If no compatible parent release exists, force the patched version and test: " + OVERRIDE_HINTS[f.ecosystem] + ".")
|
|
43
|
+
elif f.dependency_type in ("direct", "direct_inferred") and f.ecosystem in OVERRIDE_HINTS and f.recommended_fix:
|
|
44
|
+
lines.append("How: " + OVERRIDE_HINTS[f.ecosystem].split(": ", 1)[1] + ".")
|
|
45
|
+
other_roots = [e for e in f.exposures if e["relationship"] != (f.exposures[0]["relationship"] if f.exposures else "")]
|
|
46
|
+
if len(f.roots) > 1:
|
|
47
|
+
lines.append(f"Affects {len(f.roots)} application roots ({', '.join(f.roots[:4])}); update each one.")
|
|
48
|
+
if f.dev_dependency:
|
|
49
|
+
lines.append("The lockfile marks this as a development-only dependency; production exposure may be lower, but build/CI environments are still affected.")
|
|
50
|
+
return " ".join(lines)
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
"""Ground-truth verification of vulnerability findings.
|
|
2
|
+
|
|
3
|
+
OSV.dev (aggregating GitHub Advisories, PyPA, RustSec, the Go vulnerability DB, NVD CVE records, ...) is the *ground
|
|
4
|
+
truth* for "which advisories exist for which package versions". The scanner's own job is therefore to
|
|
5
|
+
(1) identify each component exactly (ecosystem + name + version + PURL), (2) ask the database, and
|
|
6
|
+
(3) independently re-validate the answer. Two checks are provided:
|
|
7
|
+
|
|
8
|
+
* ``cross_check`` every component is queried a second way (by PURL instead of ecosystem/name/version).
|
|
9
|
+
A finding is ``cross_verified`` when both routes returned its advisory. Disagreements are listed.
|
|
10
|
+
* ``run_ground_truth`` a built-in known-answer test: package versions with publicly documented CVEs must be detected and
|
|
11
|
+
the patched versions of the same packages must NOT be reported (precision / recall).
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
from core.models import Component
|
|
18
|
+
from sbom.package_extractors.common import parse_purl
|
|
19
|
+
from vulnerability.osv_client import OsvClient
|
|
20
|
+
from vulnerability.vulnerability_correlator import correlate
|
|
21
|
+
|
|
22
|
+
# (purl, expected to be affected?, CVE id). Negatives are patched releases of the same packages.
|
|
23
|
+
GOLDEN: list[tuple[str, bool, str]] = [
|
|
24
|
+
("pkg:npm/lodash@4.17.15", True, "CVE-2020-8203"),
|
|
25
|
+
("pkg:npm/lodash@4.17.21", False, "CVE-2020-8203"),
|
|
26
|
+
("pkg:npm/minimist@0.0.8", True, "CVE-2020-7598"),
|
|
27
|
+
("pkg:npm/minimist@1.2.6", False, "CVE-2020-7598"),
|
|
28
|
+
("pkg:pypi/requests@2.19.1", True, "CVE-2018-18074"),
|
|
29
|
+
("pkg:pypi/requests@2.32.3", False, "CVE-2018-18074"),
|
|
30
|
+
("pkg:pypi/flask@0.12.2", True, "CVE-2018-1000656"),
|
|
31
|
+
("pkg:pypi/flask@3.0.3", False, "CVE-2018-1000656"),
|
|
32
|
+
("pkg:maven/org.apache.logging.log4j/log4j-core@2.14.1", True, "CVE-2021-44228"),
|
|
33
|
+
("pkg:maven/org.apache.logging.log4j/log4j-core@2.17.1", False, "CVE-2021-44228"),
|
|
34
|
+
("pkg:golang/golang.org/x/text@v0.3.0", True, "CVE-2020-14040"),
|
|
35
|
+
("pkg:golang/golang.org/x/text@v0.3.8", False, "CVE-2020-14040"),
|
|
36
|
+
]
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def cross_check(osv: OsvClient, name_route: dict[str, list[str]], findings: list[Any]) -> dict[str, Any]:
|
|
40
|
+
"""Query every PURL a second way and compare with the ecosystem/name/version route."""
|
|
41
|
+
purls = list(name_route)
|
|
42
|
+
res = osv.query_purls(purls)
|
|
43
|
+
agree = unavailable = 0
|
|
44
|
+
disagreements: list[dict] = []
|
|
45
|
+
purl_ids: dict[str, set[str]] = {}
|
|
46
|
+
for p in purls:
|
|
47
|
+
r = res.get(p, {"state": "unavailable", "vulns": []})
|
|
48
|
+
if r["state"] == "unavailable":
|
|
49
|
+
unavailable += 1
|
|
50
|
+
continue
|
|
51
|
+
a, b = set(name_route[p]), {v["id"] for v in r["vulns"]}
|
|
52
|
+
purl_ids[p] = b
|
|
53
|
+
if a == b:
|
|
54
|
+
agree += 1
|
|
55
|
+
else:
|
|
56
|
+
disagreements.append({"purl": p, "only_in_name_route": sorted(a - b), "only_in_purl_route": sorted(b - a)})
|
|
57
|
+
verified = 0
|
|
58
|
+
for f in findings:
|
|
59
|
+
ids = purl_ids.get(f.purl or "")
|
|
60
|
+
if ids is None:
|
|
61
|
+
f.cross_verified = None
|
|
62
|
+
continue
|
|
63
|
+
f.cross_verified = bool(ids & set(f.vulnerability_ids))
|
|
64
|
+
verified += f.cross_verified
|
|
65
|
+
checked = [f for f in findings if f.cross_verified is not None]
|
|
66
|
+
return {"components_checked": len(purls) - unavailable, "routes_agree": agree, "disagreement_count": len(disagreements),
|
|
67
|
+
"disagreements": disagreements[:50], "unavailable": unavailable, "findings_checked": len(checked),
|
|
68
|
+
"findings_cross_verified": verified, "findings_unverified": len(checked) - verified}
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def run_ground_truth(osv: OsvClient) -> dict[str, Any]:
|
|
72
|
+
"""Known-answer test through the real matching code (query, local range validation, alias grouping)."""
|
|
73
|
+
rows: list[dict] = []
|
|
74
|
+
tp = fp = tn = fn = 0
|
|
75
|
+
for purl, expected, cve in GOLDEN:
|
|
76
|
+
pp = parse_purl(purl)
|
|
77
|
+
comp = Component(bom_ref=purl, name=pp["osv_name"], version=pp["version"], ecosystem=pp["ecosystem"], purl=purl, service_dir=".")
|
|
78
|
+
out = correlate([comp], None, [], osv)
|
|
79
|
+
if out["source_status"]["OSV"]["state"] == "unavailable":
|
|
80
|
+
rows.append({"purl": purl, "expected": "affected" if expected else "not affected", "cve": cve, "result": "source unavailable", "ok": None})
|
|
81
|
+
continue
|
|
82
|
+
hit = next((f for f in out["findings"] if cve in f.cve_ids and f.affected_status == "confirmed_affected"), None)
|
|
83
|
+
found = hit is not None
|
|
84
|
+
tp += expected and found
|
|
85
|
+
fn += expected and not found
|
|
86
|
+
tn += (not expected) and (not found)
|
|
87
|
+
fp += (not expected) and found
|
|
88
|
+
rows.append({"purl": purl, "expected": "affected" if expected else "not affected", "cve": cve,
|
|
89
|
+
"result": "reported" if found else "not reported", "ok": found == expected,
|
|
90
|
+
"fixed_in": ", ".join(hit.fixed_versions[:3]) if hit else ""})
|
|
91
|
+
ev = [r for r in rows if r["ok"] is not None]
|
|
92
|
+
return {"rows": rows, "evaluated": len(ev), "passed": sum(1 for r in ev if r["ok"]),
|
|
93
|
+
"precision": round(tp / (tp + fp), 3) if (tp + fp) else None, "recall": round(tp / (tp + fn), 3) if (tp + fn) else None,
|
|
94
|
+
"tp": tp, "fp": fp, "tn": tn, "fn": fn}
|
|
@@ -0,0 +1,299 @@
|
|
|
1
|
+
"""Ecosystem-aware version comparison and OSV affected-range evaluation.
|
|
2
|
+
|
|
3
|
+
Never compares versions lexicographically and never applies one ecosystem's rules to another:
|
|
4
|
+
|
|
5
|
+
* PyPI -> PEP 440 (``packaging``)
|
|
6
|
+
* npm, Go, crates.io -> semantic versioning 2.0 (npm/Go 'v' prefix and short forms tolerated)
|
|
7
|
+
* Maven -> Maven ComparableVersion rules (qualifier ordering; flattened sublists, approximated)
|
|
8
|
+
* Packagist, NuGet, RubyGems -> loose numeric-segment ordering with pre-release qualifiers
|
|
9
|
+
* OSV range type SEMVER -> semver regardless of ecosystem; GIT ranges are not evaluable (-> unknown)
|
|
10
|
+
|
|
11
|
+
Evaluation returns True / False / None. ``None`` means "cannot decide" and is never treated as affected.
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import re
|
|
16
|
+
from functools import cmp_to_key
|
|
17
|
+
from typing import Any, Optional
|
|
18
|
+
|
|
19
|
+
from packaging.version import InvalidVersion, Version
|
|
20
|
+
|
|
21
|
+
from sbom.package_extractors.common import normalize_name
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class VersionError(ValueError):
|
|
25
|
+
pass
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
# ----------------------------------------------------------------- semver
|
|
29
|
+
_SEMVER = re.compile(r"^[vV=]?\s*(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:\.\d+)*(?:-([0-9A-Za-z.\-]+))?(?:\+[0-9A-Za-z.\-]+)?$")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _semver_parts(v: str):
|
|
33
|
+
m = _SEMVER.match(v.strip())
|
|
34
|
+
if not m:
|
|
35
|
+
raise VersionError(f"not a semver: {v!r}")
|
|
36
|
+
major, minor, patch = (int(x) if x is not None else 0 for x in m.group(1, 2, 3))
|
|
37
|
+
pre = m.group(4)
|
|
38
|
+
return (major, minor, patch), (pre.split(".") if pre else None)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _pre_cmp(a: Optional[list[str]], b: Optional[list[str]]) -> int:
|
|
42
|
+
if a is None and b is None:
|
|
43
|
+
return 0
|
|
44
|
+
if a is None:
|
|
45
|
+
return 1 # release > prerelease
|
|
46
|
+
if b is None:
|
|
47
|
+
return -1
|
|
48
|
+
for x, y in zip(a, b):
|
|
49
|
+
xd, yd = x.isdigit(), y.isdigit()
|
|
50
|
+
if xd and yd:
|
|
51
|
+
if int(x) != int(y):
|
|
52
|
+
return -1 if int(x) < int(y) else 1
|
|
53
|
+
elif xd != yd:
|
|
54
|
+
return -1 if xd else 1 # numeric identifiers sort lower than alphanumeric
|
|
55
|
+
elif x != y:
|
|
56
|
+
return -1 if x < y else 1
|
|
57
|
+
return (len(a) > len(b)) - (len(a) < len(b))
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def cmp_semver(a: str, b: str) -> int:
|
|
61
|
+
(na, pa), (nb, pb) = _semver_parts(a), _semver_parts(b)
|
|
62
|
+
if na != nb:
|
|
63
|
+
return -1 if na < nb else 1
|
|
64
|
+
return _pre_cmp(pa, pb)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
# ----------------------------------------------------------------- PEP 440
|
|
68
|
+
def cmp_pep440(a: str, b: str) -> int:
|
|
69
|
+
try:
|
|
70
|
+
va, vb = Version(a), Version(b)
|
|
71
|
+
except InvalidVersion as e:
|
|
72
|
+
raise VersionError(str(e)) from e
|
|
73
|
+
return (va > vb) - (va < vb)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
# ----------------------------------------------------------------- Maven
|
|
77
|
+
_QUAL = ["alpha", "beta", "milestone", "rc", "snapshot", "", "sp"]
|
|
78
|
+
_ALIAS = {"a": "alpha", "b": "beta", "m": "milestone", "cr": "rc", "ga": "", "final": "", "release": ""}
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _mvn_tokens(v: str) -> list:
|
|
82
|
+
v = v.strip().lower()
|
|
83
|
+
if not v:
|
|
84
|
+
raise VersionError("empty maven version")
|
|
85
|
+
raw = re.findall(r"\d+|[a-z]+", v)
|
|
86
|
+
toks: list = []
|
|
87
|
+
for i, t in enumerate(raw):
|
|
88
|
+
if t.isdigit():
|
|
89
|
+
toks.append(int(t))
|
|
90
|
+
else:
|
|
91
|
+
nxt_digit = i + 1 < len(raw) and raw[i + 1].isdigit()
|
|
92
|
+
if t in ("a", "b", "m") and not nxt_digit:
|
|
93
|
+
toks.append(t) # 'a' alone is not an alias
|
|
94
|
+
else:
|
|
95
|
+
toks.append(_ALIAS.get(t, t))
|
|
96
|
+
while toks and (toks[-1] == 0 or toks[-1] == ""):
|
|
97
|
+
toks.pop()
|
|
98
|
+
return toks
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _mvn_item_cmp(x, y) -> int:
|
|
102
|
+
def rank(s):
|
|
103
|
+
return (_QUAL.index(s), "") if s in _QUAL else (len(_QUAL), s)
|
|
104
|
+
|
|
105
|
+
if x is None:
|
|
106
|
+
x = 0 if isinstance(y, int) else ""
|
|
107
|
+
if y is None:
|
|
108
|
+
y = 0 if isinstance(x, int) else ""
|
|
109
|
+
if isinstance(x, int) and isinstance(y, int):
|
|
110
|
+
return (x > y) - (x < y)
|
|
111
|
+
if isinstance(x, int):
|
|
112
|
+
return 1
|
|
113
|
+
if isinstance(y, int):
|
|
114
|
+
return -1
|
|
115
|
+
rx, ry = rank(x), rank(y)
|
|
116
|
+
return (rx > ry) - (rx < ry)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def cmp_maven(a: str, b: str) -> int:
|
|
120
|
+
ta, tb = _mvn_tokens(a), _mvn_tokens(b)
|
|
121
|
+
for i in range(max(len(ta), len(tb))):
|
|
122
|
+
c = _mvn_item_cmp(ta[i] if i < len(ta) else None, tb[i] if i < len(tb) else None)
|
|
123
|
+
if c:
|
|
124
|
+
return c
|
|
125
|
+
return 0
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
# ----------------------------------------------------------------- loose (Packagist / NuGet / RubyGems)
|
|
129
|
+
_LOOSE_Q = {"dev": 0, "alpha": 1, "a": 1, "beta": 2, "b": 2, "rc": 3, "c": 3, "pre": 3, "": 4, "stable": 4, "p": 5, "patch": 5, "pl": 5}
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _loose_key(v: str):
|
|
133
|
+
v = v.strip().lstrip("vV")
|
|
134
|
+
v = v.split("+", 1)[0]
|
|
135
|
+
m = re.match(r"^(\d+(?:\.\d+)*)(?:[-._]?([A-Za-z]+)[-._]?(\d*))?(?:-(.+))?$", v)
|
|
136
|
+
if not m:
|
|
137
|
+
raise VersionError(f"unparseable version: {v!r}")
|
|
138
|
+
nums = [int(x) for x in m.group(1).split(".")]
|
|
139
|
+
while len(nums) > 1 and nums[-1] == 0:
|
|
140
|
+
nums.pop()
|
|
141
|
+
qual = _LOOSE_Q.get((m.group(2) or "").lower(), None)
|
|
142
|
+
if m.group(2) and qual is None:
|
|
143
|
+
raise VersionError(f"unknown qualifier in {v!r}")
|
|
144
|
+
return nums, (qual if qual is not None else 4), int(m.group(3)) if m.group(3) else 0
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def cmp_loose(a: str, b: str) -> int:
|
|
148
|
+
ka, kb = _loose_key(a), _loose_key(b)
|
|
149
|
+
return (ka > kb) - (ka < kb)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
# ----------------------------------------------------------------- dispatch
|
|
153
|
+
ECOSYSTEM_CMP = {
|
|
154
|
+
"PyPI": cmp_pep440, "npm": cmp_semver, "Go": cmp_semver, "crates.io": cmp_semver, "Maven": cmp_maven,
|
|
155
|
+
"Packagist": cmp_loose, "NuGet": cmp_loose, "RubyGems": cmp_loose,
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def compare(ecosystem: str, a: str, b: str, range_type: str = "ECOSYSTEM") -> int:
|
|
160
|
+
if range_type == "SEMVER":
|
|
161
|
+
return cmp_semver(a, b)
|
|
162
|
+
fn = ECOSYSTEM_CMP.get(ecosystem)
|
|
163
|
+
if not fn:
|
|
164
|
+
raise VersionError(f"no version semantics for ecosystem {ecosystem!r}")
|
|
165
|
+
return fn(a, b)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def evaluate_range(ecosystem: str, rng: dict, version: str) -> Optional[bool]:
|
|
169
|
+
"""Evaluate one OSV range for ``version``. Returns None if the range is not evaluable."""
|
|
170
|
+
rtype = rng.get("type")
|
|
171
|
+
if rtype not in ("SEMVER", "ECOSYSTEM"):
|
|
172
|
+
return None # GIT ranges require commit ancestry we do not have
|
|
173
|
+
events = [e for e in rng.get("events", []) if isinstance(e, dict)]
|
|
174
|
+
if not events:
|
|
175
|
+
return None
|
|
176
|
+
try:
|
|
177
|
+
def ev_version(e):
|
|
178
|
+
return e.get("introduced") or e.get("fixed") or e.get("last_affected") or e.get("limit")
|
|
179
|
+
|
|
180
|
+
def sort_cmp(e1, e2):
|
|
181
|
+
v1, v2 = ev_version(e1), ev_version(e2)
|
|
182
|
+
if v1 == "0" and v2 == "0":
|
|
183
|
+
return 0
|
|
184
|
+
if v1 == "0":
|
|
185
|
+
return -1
|
|
186
|
+
if v2 == "0":
|
|
187
|
+
return 1
|
|
188
|
+
return compare(ecosystem, v1, v2, rtype)
|
|
189
|
+
|
|
190
|
+
affected = False
|
|
191
|
+
for e in sorted(events, key=cmp_to_key(sort_cmp)):
|
|
192
|
+
if "introduced" in e:
|
|
193
|
+
if e["introduced"] == "0" or compare(ecosystem, version, e["introduced"], rtype) >= 0:
|
|
194
|
+
affected = True
|
|
195
|
+
elif "fixed" in e:
|
|
196
|
+
if compare(ecosystem, version, e["fixed"], rtype) >= 0:
|
|
197
|
+
affected = False
|
|
198
|
+
elif "last_affected" in e:
|
|
199
|
+
if compare(ecosystem, version, e["last_affected"], rtype) > 0:
|
|
200
|
+
affected = False
|
|
201
|
+
return affected
|
|
202
|
+
except VersionError:
|
|
203
|
+
return None
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def describe_range(rng: dict) -> str:
|
|
207
|
+
parts, cur = [], None
|
|
208
|
+
for e in rng.get("events", []):
|
|
209
|
+
if "introduced" in e:
|
|
210
|
+
cur = e["introduced"]
|
|
211
|
+
elif "fixed" in e:
|
|
212
|
+
parts.append(f">= {cur or '0'}, < {e['fixed']}")
|
|
213
|
+
cur = None
|
|
214
|
+
elif "last_affected" in e:
|
|
215
|
+
parts.append(f">= {cur or '0'}, <= {e['last_affected']}")
|
|
216
|
+
cur = None
|
|
217
|
+
if cur is not None:
|
|
218
|
+
parts.append(f">= {cur} (no fix recorded)")
|
|
219
|
+
return "; ".join(parts) if parts else "unspecified"
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def _entry_matches(ecosystem: str, name: str, entry: dict, purl: Optional[str]) -> bool:
|
|
223
|
+
pkg = entry.get("package") or {}
|
|
224
|
+
eco = pkg.get("ecosystem", "")
|
|
225
|
+
if eco.split(":")[0] != ecosystem:
|
|
226
|
+
return False
|
|
227
|
+
if pkg.get("purl") and purl and pkg["purl"].split("@")[0] == purl.split("@")[0]:
|
|
228
|
+
return True
|
|
229
|
+
return normalize_name(ecosystem, pkg.get("name", "")) == normalize_name(ecosystem, name)
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def assess_advisory(ecosystem: str, name: str, version: str, vuln: dict, purl: Optional[str] = None) -> dict:
|
|
233
|
+
"""Decide whether ``name@version`` is affected by the advisory record.
|
|
234
|
+
|
|
235
|
+
Returns {status: confirmed_affected|not_affected|unknown, fixed_versions[], recommended_fix, ranges[], reason}.
|
|
236
|
+
"""
|
|
237
|
+
entries = [e for e in vuln.get("affected", []) or [] if _entry_matches(ecosystem, name, e, purl)]
|
|
238
|
+
if not entries:
|
|
239
|
+
return {"status": "unknown", "fixed_versions": [], "recommended_fix": None, "ranges": [],
|
|
240
|
+
"reason": "advisory has no affected entry matching this package identity; local validation impossible"}
|
|
241
|
+
verdicts: list[Optional[bool]] = []
|
|
242
|
+
fixed: set[str] = set()
|
|
243
|
+
ranges_txt: list[str] = []
|
|
244
|
+
for e in entries:
|
|
245
|
+
v: Optional[bool] = None
|
|
246
|
+
versions = e.get("versions") or []
|
|
247
|
+
rngs = e.get("ranges") or []
|
|
248
|
+
for r in rngs:
|
|
249
|
+
ranges_txt.append(describe_range(r))
|
|
250
|
+
if version in versions:
|
|
251
|
+
v = True
|
|
252
|
+
else:
|
|
253
|
+
results = [evaluate_range(ecosystem, r, version) for r in rngs]
|
|
254
|
+
if any(x is True for x in results):
|
|
255
|
+
v = True
|
|
256
|
+
elif rngs and all(x is False for x in results):
|
|
257
|
+
v = False
|
|
258
|
+
elif versions and not rngs:
|
|
259
|
+
v = False # enumerated affected versions only; ours is not in the list
|
|
260
|
+
elif versions and all(x is False for x in results if x is not None) and results and None not in results:
|
|
261
|
+
v = False
|
|
262
|
+
else:
|
|
263
|
+
v = None
|
|
264
|
+
verdicts.append(v)
|
|
265
|
+
for r in rngs:
|
|
266
|
+
if r.get("type") in ("SEMVER", "ECOSYSTEM"):
|
|
267
|
+
for ev in r.get("events", []):
|
|
268
|
+
if "fixed" in ev:
|
|
269
|
+
fixed.add(ev["fixed"])
|
|
270
|
+
if any(v is True for v in verdicts):
|
|
271
|
+
status = "confirmed_affected"
|
|
272
|
+
elif all(v is False for v in verdicts):
|
|
273
|
+
status = "not_affected"
|
|
274
|
+
else:
|
|
275
|
+
status = "unknown"
|
|
276
|
+
fixed_sorted: list[str] = []
|
|
277
|
+
recommended: Optional[str] = None
|
|
278
|
+
if status != "not_affected":
|
|
279
|
+
later = []
|
|
280
|
+
for f in fixed:
|
|
281
|
+
try:
|
|
282
|
+
if compare(ecosystem, f, version, "ECOSYSTEM") > 0:
|
|
283
|
+
later.append(f)
|
|
284
|
+
except VersionError:
|
|
285
|
+
try:
|
|
286
|
+
if compare(ecosystem, f, version, "SEMVER") > 0:
|
|
287
|
+
later.append(f)
|
|
288
|
+
except VersionError:
|
|
289
|
+
continue
|
|
290
|
+
try:
|
|
291
|
+
fixed_sorted = sorted(later, key=cmp_to_key(lambda x, y: compare(ecosystem, x, y)))
|
|
292
|
+
except VersionError:
|
|
293
|
+
fixed_sorted = sorted(later)
|
|
294
|
+
recommended = fixed_sorted[0] if fixed_sorted else None
|
|
295
|
+
reason = {"confirmed_affected": "installed version falls inside an affected range/version list",
|
|
296
|
+
"not_affected": "installed version is outside every affected range",
|
|
297
|
+
"unknown": "affected ranges could not be evaluated for this version (unsupported range type or unparseable version)"}[status]
|
|
298
|
+
return {"status": status, "fixed_versions": fixed_sorted, "recommended_fix": recommended,
|
|
299
|
+
"ranges": sorted(set(ranges_txt)), "reason": reason}
|