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,135 @@
|
|
|
1
|
+
"""Strict validation of repository URLs (public GitHub over HTTPS only)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import re
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from urllib.parse import unquote, urlparse
|
|
8
|
+
|
|
9
|
+
_SEGMENT = re.compile(r"^[A-Za-z0-9_.-]{1,100}$")
|
|
10
|
+
_REF = re.compile(r"^[A-Za-z0-9._/@+-]{1,200}$")
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class InvalidRepositoryURL(ValueError):
|
|
14
|
+
pass
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
# GitHub UI sub-pages that may follow ``/<owner>/<repo>`` in a pasted address; they do not change which repository is meant.
|
|
18
|
+
_UI_SEGMENTS = {"blob", "commit", "commits", "releases", "tags", "branches", "issues", "pulls", "pull", "actions", "wiki", "security",
|
|
19
|
+
"network", "graphs", "stargazers", "forks", "watchers", "tree", "archive", "compare", "projects", "discussions", "pulse"}
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True)
|
|
23
|
+
class GitHubRepo:
|
|
24
|
+
owner: str
|
|
25
|
+
name: str
|
|
26
|
+
ref: str | None = None # branch/tag taken from a pasted ``/tree/<ref>`` address
|
|
27
|
+
|
|
28
|
+
@property
|
|
29
|
+
def clone_url(self) -> str:
|
|
30
|
+
return f"https://github.com/{self.owner}/{self.name}.git"
|
|
31
|
+
|
|
32
|
+
@property
|
|
33
|
+
def web_url(self) -> str:
|
|
34
|
+
return f"https://github.com/{self.owner}/{self.name}"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _normalize(url: str) -> str:
|
|
38
|
+
"""Accept the usual pasted forms: scheme-less, http://, git@github.com:owner/repo.git, with query/fragment."""
|
|
39
|
+
u = url.strip()
|
|
40
|
+
if u.lower().startswith("git@github.com:"):
|
|
41
|
+
u = "https://github.com/" + u[len("git@github.com:"):]
|
|
42
|
+
elif u.lower().startswith(("github.com/", "www.github.com/")):
|
|
43
|
+
u = "https://" + u
|
|
44
|
+
elif u.lower().startswith("http://"):
|
|
45
|
+
u = "https://" + u[len("http://"):]
|
|
46
|
+
return u
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def validate_github_url(url: str) -> GitHubRepo:
|
|
50
|
+
"""Return a normalized GitHubRepo or raise InvalidRepositoryURL.
|
|
51
|
+
|
|
52
|
+
Accepts ``https://github.com/<owner>/<repo>[.git][/]`` plus the common pasted variants (see ``_normalize``) and GitHub
|
|
53
|
+
UI sub-pages such as ``/tree/<branch>``. Rejects local paths, other hosts/schemes, credentials, ports, control characters.
|
|
54
|
+
The clone URL is always rebuilt from owner/repo, never taken from the input.
|
|
55
|
+
"""
|
|
56
|
+
if not isinstance(url, str):
|
|
57
|
+
raise InvalidRepositoryURL("URL must be a string")
|
|
58
|
+
url = _normalize(url)
|
|
59
|
+
if not url or len(url) > 300:
|
|
60
|
+
raise InvalidRepositoryURL("URL is empty or too long")
|
|
61
|
+
if any(ord(c) < 33 or ord(c) == 127 for c in url) or "\\" in url:
|
|
62
|
+
raise InvalidRepositoryURL("URL contains whitespace, control characters or backslashes")
|
|
63
|
+
p = urlparse(url)
|
|
64
|
+
if p.scheme != "https":
|
|
65
|
+
raise InvalidRepositoryURL("Only GitHub repository URLs are supported (https://github.com/<owner>/<repository>)")
|
|
66
|
+
if p.username or p.password or p.port:
|
|
67
|
+
raise InvalidRepositoryURL("Credentials and ports are not allowed in the URL")
|
|
68
|
+
if (p.hostname or "").lower() not in ("github.com", "www.github.com"):
|
|
69
|
+
raise InvalidRepositoryURL("Only github.com repositories are supported")
|
|
70
|
+
parts = [s for s in p.path.split("/") if s != ""] # query string and fragment are ignored
|
|
71
|
+
if len(parts) < 2:
|
|
72
|
+
raise InvalidRepositoryURL("URL must look like https://github.com/<owner>/<repository>")
|
|
73
|
+
owner, name = parts[0], parts[1]
|
|
74
|
+
if name.endswith(".git"):
|
|
75
|
+
name = name[:-4]
|
|
76
|
+
for seg in (owner, name):
|
|
77
|
+
if not _SEGMENT.match(seg) or seg in (".", "..") or seg.startswith("-"):
|
|
78
|
+
raise InvalidRepositoryURL("Invalid owner or repository name")
|
|
79
|
+
ref = None
|
|
80
|
+
if len(parts) > 2:
|
|
81
|
+
if parts[2] not in _UI_SEGMENTS:
|
|
82
|
+
raise InvalidRepositoryURL("URL must point at the repository itself, e.g. https://github.com/<owner>/<repository>")
|
|
83
|
+
if parts[2] == "tree" and len(parts) > 3:
|
|
84
|
+
ref = validate_ref("/".join(parts[3:]))
|
|
85
|
+
return GitHubRepo(owner=owner, name=name, ref=ref)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
_WIN_DRIVE = re.compile(r"^[A-Za-z]:[\\/]")
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def looks_like_local_path(text: str) -> bool:
|
|
92
|
+
"""True when the input is a filesystem path (drive letter, UNC, absolute/relative/home path, file://) rather than a URL."""
|
|
93
|
+
t = (text or "").strip().strip('"').strip("'")
|
|
94
|
+
if not t:
|
|
95
|
+
return False
|
|
96
|
+
if t.lower().startswith("file://"):
|
|
97
|
+
return True
|
|
98
|
+
if "://" in t or t.lower().startswith(("git@", "github.com/", "www.github.com/")):
|
|
99
|
+
return False
|
|
100
|
+
if bool(_WIN_DRIVE.match(t)) or t.startswith(("/", "~", "./", "../", chr(92), "." + chr(92), ".." + chr(92))):
|
|
101
|
+
return True
|
|
102
|
+
try:
|
|
103
|
+
return Path(t).is_dir()
|
|
104
|
+
except (ValueError, OSError):
|
|
105
|
+
return False
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def resolve_local_path(text: str) -> Path:
|
|
109
|
+
"""Return the resolved project directory for a local path input, or raise InvalidRepositoryURL."""
|
|
110
|
+
t = text.strip().strip('"').strip("'")
|
|
111
|
+
if t.lower().startswith("file://"):
|
|
112
|
+
t = unquote(urlparse(t).path)
|
|
113
|
+
if _WIN_DRIVE.match(t.lstrip("/")):
|
|
114
|
+
t = t.lstrip("/")
|
|
115
|
+
if "\x00" in t or any(ord(c) < 32 for c in t):
|
|
116
|
+
raise InvalidRepositoryURL("Path contains control characters")
|
|
117
|
+
try:
|
|
118
|
+
p = Path(t).expanduser().resolve()
|
|
119
|
+
except (OSError, RuntimeError, ValueError) as e:
|
|
120
|
+
raise InvalidRepositoryURL(f"Invalid path: {e}")
|
|
121
|
+
if not p.exists():
|
|
122
|
+
raise InvalidRepositoryURL(f"Folder not found: {p}")
|
|
123
|
+
if not p.is_dir():
|
|
124
|
+
raise InvalidRepositoryURL(f"Not a folder: {p} (give the project's root folder)")
|
|
125
|
+
return p
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def validate_ref(ref: str | None) -> str | None:
|
|
129
|
+
"""Validate a branch/tag name; reject anything that could be parsed as an option or path trick."""
|
|
130
|
+
if ref is None or ref.strip() == "":
|
|
131
|
+
return None
|
|
132
|
+
ref = ref.strip()
|
|
133
|
+
if not _REF.match(ref) or ref.startswith("-") or ".." in ref or ref.endswith("/") or "//" in ref:
|
|
134
|
+
raise InvalidRepositoryURL("Invalid branch or tag name")
|
|
135
|
+
return ref
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""ecosystems package."""
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
"""Ecosystem plugin registry: what the Guardian can do for each ecosystem, declared in one place.
|
|
2
|
+
|
|
3
|
+
A capability that is not declared is simply not offered for that ecosystem (and the UI says so) - nothing is silently assumed.
|
|
4
|
+
Adding an ecosystem = one ``register(Ecosystem(...))`` call plus the capability modules it points to. Existing parsers/clients are wrapped,
|
|
5
|
+
not duplicated: ``parser_files`` are resolved against ``sbom.lockfile_analyzer.PARSERS`` and ``registry`` against ``sbom.fusion.registries``.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from fnmatch import fnmatchcase
|
|
11
|
+
from typing import Callable, Optional
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass
|
|
15
|
+
class Ecosystem:
|
|
16
|
+
key: str # OSV ecosystem name (npm, PyPI, Maven, Go, crates.io, Packagist, NuGet, RubyGems) or pseudo ecosystem (Docker, GitHub Actions, ...)
|
|
17
|
+
label: str
|
|
18
|
+
kind: str # package | container | pipeline
|
|
19
|
+
purl_type: Optional[str] = None
|
|
20
|
+
manifests: tuple[str, ...] = () # file names / suffixes that declare dependencies
|
|
21
|
+
lockfiles: tuple[str, ...] = () # files that pin exact versions
|
|
22
|
+
source_globs: tuple[str, ...] = () # application source files (for reachability)
|
|
23
|
+
registry: bool = False # metadata/digest client available (sbom.fusion.registries)
|
|
24
|
+
resolver: bool = False # transitive resolution for manifest-only services (deps.dev)
|
|
25
|
+
osv: bool = True # advisories available from OSV
|
|
26
|
+
# plugin hook: (manifest_path, text, name, to_version, kind) -> new manifest text, or None when it cannot patch
|
|
27
|
+
patcher: Optional[Callable] = None
|
|
28
|
+
notes: str = ""
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
ECOSYSTEMS: dict[str, Ecosystem] = {}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def register(e: Ecosystem) -> Ecosystem:
|
|
35
|
+
ECOSYSTEMS[e.key] = e
|
|
36
|
+
return e
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def get(key: Optional[str]) -> Optional[Ecosystem]:
|
|
40
|
+
return ECOSYSTEMS.get(key or "")
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def packages() -> list[Ecosystem]:
|
|
44
|
+
return [e for e in ECOSYSTEMS.values() if e.kind == "package"]
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def classify_manifest(name: str) -> Optional[tuple[str, str]]:
|
|
48
|
+
"""Match registered lockfiles before manifests, including package project suffixes."""
|
|
49
|
+
for ecosystem in packages():
|
|
50
|
+
for kind, patterns in (("lockfile", ecosystem.lockfiles), ("manifest", ecosystem.manifests)):
|
|
51
|
+
if any((name.lower().endswith(p) if p.startswith(".") else fnmatchcase(name, p)) for p in patterns):
|
|
52
|
+
return kind, ecosystem.key
|
|
53
|
+
return None
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _parses(patterns: tuple[str, ...]) -> bool:
|
|
57
|
+
"""True when a parser really exists for at least one of the declared file patterns."""
|
|
58
|
+
from sbom.lockfile_analyzer import manifest_parser_for, parser_for
|
|
59
|
+
for p in patterns:
|
|
60
|
+
name = f"x{p}" if p.startswith(".") else p.replace("*", "")
|
|
61
|
+
if parser_for(name) or manifest_parser_for(name):
|
|
62
|
+
return True
|
|
63
|
+
return False
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def support_level(files: list[str]) -> str:
|
|
67
|
+
"""How completely the built-in engine handles the dependency files found for one ecosystem."""
|
|
68
|
+
from sbom.lockfile_analyzer import manifest_parser_for, parser_for
|
|
69
|
+
if not files:
|
|
70
|
+
return "unknown"
|
|
71
|
+
locked = [f for f in files if parser_for(f)]
|
|
72
|
+
declared = [f for f in files if not parser_for(f) and manifest_parser_for(f)]
|
|
73
|
+
if locked and len(locked) + len(declared) == len(files):
|
|
74
|
+
return "supported"
|
|
75
|
+
if locked or declared:
|
|
76
|
+
return "partial"
|
|
77
|
+
return "detected-but-unsupported"
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def technology_support(inspection) -> list[dict]:
|
|
81
|
+
"""One row per detected ecosystem, plus one per programming language no detected ecosystem accounts for."""
|
|
82
|
+
from config.constants import EXTENSION_LANGUAGES, MARKUP_LANGUAGES
|
|
83
|
+
rows, covered = [], set()
|
|
84
|
+
for key in inspection.ecosystems:
|
|
85
|
+
e = ECOSYSTEMS.get(key)
|
|
86
|
+
files = sorted({m.name for m in inspection.manifests if m.ecosystem == key})
|
|
87
|
+
covered.update(e.source_globs if e else ())
|
|
88
|
+
rows.append({"name": e.label if e else key, "type": "ecosystem", "key": key, "support": support_level(files), "evidence": files})
|
|
89
|
+
for language, stats in inspection.languages.items():
|
|
90
|
+
if language in MARKUP_LANGUAGES or language in ("Shell", "PowerShell"):
|
|
91
|
+
continue
|
|
92
|
+
if not any(ext in covered for ext, lang in EXTENSION_LANGUAGES.items() if lang == language):
|
|
93
|
+
rows.append({"name": language, "type": "language", "key": language, "support": "unknown",
|
|
94
|
+
"evidence": [f"{stats.get('files', 0)} source file(s), no recognised dependency manifest"]})
|
|
95
|
+
return rows
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def capability_matrix() -> list[dict]:
|
|
99
|
+
"""Rows for docs/UI: which capability exists for which ecosystem (computed from the implementing modules)."""
|
|
100
|
+
from reachability.scanners import LANG_ECO
|
|
101
|
+
from remediation.patchers import PATCHABLE
|
|
102
|
+
reachable = set(LANG_ECO.values())
|
|
103
|
+
rows = []
|
|
104
|
+
for e in ECOSYSTEMS.values():
|
|
105
|
+
rows.append({"ecosystem": e.label, "kind": e.kind, "lockfile parsing": _parses(e.lockfiles), "manifest parsing": _parses(e.manifests), "registry metadata": e.registry,
|
|
106
|
+
"transitive resolution": e.resolver, "OSV advisories": e.osv, "reachability": e.key in reachable, "patch generation": e.patcher is not None or e.key in PATCHABLE,
|
|
107
|
+
"pipeline rules": e.kind in ("container", "pipeline")})
|
|
108
|
+
return rows
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
register(Ecosystem("npm", "Node.js / npm", "package", "npm", ("package.json",), ("package-lock.json", "npm-shrinkwrap.json", "yarn.lock", "pnpm-lock.yaml"),
|
|
112
|
+
(".js", ".jsx", ".mjs", ".cjs", ".ts", ".tsx"), registry=True, resolver=True))
|
|
113
|
+
register(Ecosystem("PyPI", "Python / PyPI", "package", "pypi", ("pyproject.toml", "setup.py", "Pipfile", "requirements*.txt"), ("poetry.lock", "uv.lock", "Pipfile.lock", "requirements*.txt"),
|
|
114
|
+
(".py",), registry=True, resolver=True))
|
|
115
|
+
register(Ecosystem("Maven", "Java / Maven & Gradle", "package", "maven", ("pom.xml", "build.gradle", "build.gradle.kts"), ("gradle.lockfile",), (".java", ".kt", ".scala"), registry=True, resolver=True))
|
|
116
|
+
register(Ecosystem("Go", "Go modules", "package", "golang", ("go.mod",), ("go.sum",), (".go",), registry=True))
|
|
117
|
+
register(Ecosystem("crates.io", "Rust / Cargo", "package", "cargo", ("Cargo.toml",), ("Cargo.lock",), (".rs",), registry=True, resolver=True))
|
|
118
|
+
register(Ecosystem("Packagist", "PHP / Composer", "package", "composer", ("composer.json",), ("composer.lock",), (".php",), registry=True))
|
|
119
|
+
register(Ecosystem("NuGet", ".NET / NuGet", "package", "nuget", (".csproj", ".fsproj", ".vbproj"), ("packages.lock.json",), (".cs", ".fs", ".vb"), registry=True, resolver=True))
|
|
120
|
+
register(Ecosystem("RubyGems", "Ruby / Bundler", "package", "gem", ("Gemfile",), ("Gemfile.lock",), (".rb",), registry=True, notes="inventory via Syft/Trivy"))
|
|
121
|
+
register(Ecosystem("Docker", "Docker / OCI images", "container", "docker", ("Dockerfile", "*.dockerfile", "docker-compose*.yml", "compose*.yml"), (), (), registry=False, osv=False,
|
|
122
|
+
notes="base-image hygiene rules; images are SBOM components"))
|
|
123
|
+
register(Ecosystem("GitHub Actions", "GitHub Actions", "pipeline", "github", (".github/workflows/*.yml", ".github/workflows/*.yaml"), (), (), registry=False, osv=True,
|
|
124
|
+
notes="workflow rules; actions are SBOM components, advisories via OSV 'GitHub Actions'"))
|
|
125
|
+
register(Ecosystem("CI (generic)", "GitLab CI / Jenkins / CircleCI / Azure Pipelines", "pipeline", None, (".gitlab-ci.yml", "Jenkinsfile", ".circleci/config.yml", "azure-pipelines.yml"), (), (), osv=False,
|
|
126
|
+
notes="generic script-level rules"))
|
|
127
|
+
|
|
128
|
+
# Detected only: reported to the user as "detected-but-unsupported" by the built-in engine (Syft/Trivy may cover them).
|
|
129
|
+
for _key, _label, _manifests, _lockfiles, _sources in (
|
|
130
|
+
("Pub", "Dart / Pub", ("pubspec.yaml",), ("pubspec.lock",), (".dart",)),
|
|
131
|
+
("Hex", "Elixir / Hex", ("mix.exs",), ("mix.lock",), (".ex", ".exs")),
|
|
132
|
+
("SwiftURL", "Swift Package Manager", ("Package.swift",), ("Package.resolved",), (".swift",)),
|
|
133
|
+
("CocoaPods", "CocoaPods", ("Podfile",), ("Podfile.lock",), (".swift", ".m")),
|
|
134
|
+
("ConanCenter", "C and C++ (Conan / vcpkg)", ("conanfile.txt", "conanfile.py", "vcpkg.json"), ("conan.lock",), (".c", ".h", ".cpp", ".cc", ".hpp")),
|
|
135
|
+
("Conda", "Conda", ("environment.yml", "environment.yaml"), ("conda-lock.yml",), ()),
|
|
136
|
+
("Hackage", "Haskell", ("stack.yaml", ".cabal"), ("stack.yaml.lock",), (".hs",)),
|
|
137
|
+
):
|
|
138
|
+
register(Ecosystem(_key, _label, "package", None, _manifests, _lockfiles, _sources, osv=False, notes="detected only; no built-in parser"))
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""evidence package."""
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""Evidence store: every fact an agent uses is an Evidence record with a stable id; claims must cite ids.
|
|
2
|
+
|
|
3
|
+
Ids are readable and deterministic (``kind:subject``) so a report line like "reachable [reach:lodash@src/app.js:12]" can be traced back.
|
|
4
|
+
The store is per scan and is persisted inside the scan result (``result["evidence_store"]``).
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import hashlib
|
|
9
|
+
import json
|
|
10
|
+
import time
|
|
11
|
+
from dataclasses import asdict, dataclass, field
|
|
12
|
+
from typing import Any, Iterable, Optional
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass
|
|
16
|
+
class Evidence:
|
|
17
|
+
id: str
|
|
18
|
+
kind: str # osv | cross-check | reachability | epss | kev | registry | provenance | dockerfile | workflow | lockfile | policy | what-if | sandbox | git
|
|
19
|
+
tool: str
|
|
20
|
+
subject: str # package / file / finding id
|
|
21
|
+
summary: str
|
|
22
|
+
data: dict[str, Any] = field(default_factory=dict)
|
|
23
|
+
source: Optional[str] = None # URL or file:line
|
|
24
|
+
retrieved_at: str = field(default_factory=lambda: time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()))
|
|
25
|
+
verified: bool = True # False = inferred (heuristic / AI), True = directly observed from a source
|
|
26
|
+
|
|
27
|
+
def to_dict(self) -> dict:
|
|
28
|
+
return asdict(self)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class EvidenceStore:
|
|
32
|
+
def __init__(self) -> None:
|
|
33
|
+
self._items: dict[str, Evidence] = {}
|
|
34
|
+
|
|
35
|
+
def add(self, kind: str, tool: str, subject: str, summary: str, data: Optional[dict] = None, source: Optional[str] = None, verified: bool = True) -> str:
|
|
36
|
+
h = hashlib.sha1(json.dumps([kind, subject, summary, data or {}], sort_keys=True, default=str).encode()).hexdigest()[:6]
|
|
37
|
+
eid = f"{kind}:{subject}#{h}"
|
|
38
|
+
if eid not in self._items:
|
|
39
|
+
self._items[eid] = Evidence(eid, kind, tool, subject, summary[:400], data or {}, source, verified=verified)
|
|
40
|
+
return eid
|
|
41
|
+
|
|
42
|
+
def get(self, eid: str) -> Optional[Evidence]:
|
|
43
|
+
return self._items.get(eid)
|
|
44
|
+
|
|
45
|
+
def for_subject(self, subject: str) -> list[Evidence]:
|
|
46
|
+
return [e for e in self._items.values() if e.subject == subject]
|
|
47
|
+
|
|
48
|
+
def many(self, ids: Iterable[str]) -> list[Evidence]:
|
|
49
|
+
return [self._items[i] for i in ids if i in self._items]
|
|
50
|
+
|
|
51
|
+
def exists(self, eid: str) -> bool:
|
|
52
|
+
return eid in self._items
|
|
53
|
+
|
|
54
|
+
def to_list(self) -> list[dict]:
|
|
55
|
+
return [e.to_dict() for e in self._items.values()]
|
|
56
|
+
|
|
57
|
+
@classmethod
|
|
58
|
+
def from_list(cls, rows: list[dict]) -> "EvidenceStore":
|
|
59
|
+
s = cls()
|
|
60
|
+
for r in rows or []:
|
|
61
|
+
s._items[r["id"]] = Evidence(**r)
|
|
62
|
+
return s
|
|
63
|
+
|
|
64
|
+
def __len__(self) -> int:
|
|
65
|
+
return len(self._items)
|
|
File without changes
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""Human-readable formatting of evidence bundles and risk factors."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def fmt_factors(risk: dict) -> list[str]:
|
|
6
|
+
out = []
|
|
7
|
+
for f in risk.get("factors", []):
|
|
8
|
+
sign = f"+{f['points']}" if f["points"] > 0 else str(f["points"])
|
|
9
|
+
out.append(f"{f['factor']} ({sign}): {f['detail']}")
|
|
10
|
+
return out
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def fmt_path(path: list[str]) -> str:
|
|
14
|
+
return " -> ".join(path)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def fmt_exposures(exposures: list[dict]) -> list[str]:
|
|
18
|
+
lines = []
|
|
19
|
+
for e in exposures:
|
|
20
|
+
rel = {"direct": "a DIRECT dependency", "direct_inferred": "a direct dependency (inferred, no recorded parent)",
|
|
21
|
+
"transitive": "a TRANSITIVE dependency"}.get(e["relationship"], e["relationship"])
|
|
22
|
+
line = f"Relative to '{e['root']}' it is {rel}"
|
|
23
|
+
if e.get("depth"):
|
|
24
|
+
line += f" (depth {e['depth']})"
|
|
25
|
+
if e.get("immediate_parents"):
|
|
26
|
+
line += f"; immediate parent: {', '.join(e['immediate_parents'])}"
|
|
27
|
+
lines.append(line + ".")
|
|
28
|
+
for p in e.get("paths", [])[:3]:
|
|
29
|
+
lines.append(" path: " + fmt_path(p))
|
|
30
|
+
return lines
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
"""Evidence-grounded explanations. Deterministic templates are always available; an LLM may rephrase them only if every
|
|
2
|
+
claim validates against the evidence (otherwise the offending section falls back to the template)."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from typing import Callable, Optional
|
|
7
|
+
|
|
8
|
+
from explainability.evidence_formatter import fmt_exposures, fmt_factors, fmt_path
|
|
9
|
+
from explainability.explanation_validator import validate_text
|
|
10
|
+
from explainability.prompt_templates import SECTIONS, SYSTEM, build_user_prompt
|
|
11
|
+
from risk_analysis.evidence_normalizer import compact_for_llm
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _vuln_template(b: dict, risk: dict, f: dict) -> dict[str, str]:
|
|
15
|
+
adv, comp, dep = b["advisory"], b["component"], b["dependency"]
|
|
16
|
+
ids = ", ".join(adv["ids"])
|
|
17
|
+
sev = adv["severity"] or "unavailable"
|
|
18
|
+
cvss = f"CVSS {adv['cvss_score']}" + (f" ({adv['cvss_vector']})" if adv.get("cvss_vector") else "") if adv.get("cvss_score") is not None else "no CVSS score available"
|
|
19
|
+
status = {"confirmed_affected": f"The installed version {comp['version']} falls inside the affected range",
|
|
20
|
+
"unknown": f"The advisory was returned for this package but its affected range could not be validated locally for {comp['version']}",
|
|
21
|
+
}.get(adv["affected_status"], adv["affected_status"])
|
|
22
|
+
ranges = f" ({'; '.join(adv['affected_ranges'])})" if adv.get("affected_ranges") else ""
|
|
23
|
+
reach = f.get("reachability") or {}
|
|
24
|
+
rst = reach.get("status")
|
|
25
|
+
app_files = reach.get("app_files", 0)
|
|
26
|
+
density = reach.get("import_density") or reach.get("influence_tier")
|
|
27
|
+
if rst == "used_by_app":
|
|
28
|
+
reach_txt = f" Application imports {comp['name']} across {app_files} file(s)" + (", indicating heavy codebase influence and broad runtime exposure." if (density == "heavy" or app_files >= 5) else ".")
|
|
29
|
+
elif rst == "reachable_via_dependency":
|
|
30
|
+
reach_txt = f" Reached via dependency {', '.join(reach.get('via') or [reach.get('package')])}, which is imported by application source."
|
|
31
|
+
elif rst == "used_in_tests_only":
|
|
32
|
+
reach_txt = f" Imported only by test code ({reach.get('test_files', 0)} files); does not run in the production execution path."
|
|
33
|
+
elif rst == "not_imported":
|
|
34
|
+
reach_txt = " No static import found in application source; practical risk is deprioritized."
|
|
35
|
+
else:
|
|
36
|
+
reach_txt = " Whether the vulnerable code is reachable in this application has not been assessed."
|
|
37
|
+
|
|
38
|
+
s = {
|
|
39
|
+
"what": f"{adv['primary_id']} ({ids}) affects {comp['name']} {comp['version']}." + (f" Advisory summary: {adv['summary']}" if adv.get("summary") else ""),
|
|
40
|
+
"why": f"{status}{ranges}. Version matching used {comp['ecosystem']} version semantics. Source(s): {', '.join(adv['sources'])}.",
|
|
41
|
+
"package": f"{comp['name']} {comp['version']} ({comp['ecosystem']}" + (f", {comp['purl']}" if comp.get('purl') else "") + f") in service '{comp.get('service_dir')}'; SBOM component reference: {comp['bom_ref']}.",
|
|
42
|
+
"how_entered": ("\n".join("path: " + fmt_path(p) for e in dep["exposures"] for p in e["paths"][:3]) or "No dependency path from a service root is recorded in the graph."),
|
|
43
|
+
"direct_transitive": ("\n".join(fmt_exposures(dep["exposures"])) or "Direct/transitive status is unknown because the component is not reachable from any root."),
|
|
44
|
+
"impact": f"Severity: {sev}; {cvss}." + (" Listed in the CISA KEV catalog (known exploited)." if adv.get("kev") else " Not listed in the CISA KEV catalog.") + reach_txt,
|
|
45
|
+
"evidence": f"Advisory source(s): {', '.join(adv['sources'])}; retrieved {adv.get('retrieved_at')}. References: " + (", ".join(adv["urls"][:3]) or "none recorded") + ".",
|
|
46
|
+
"remediation": f["remediation"],
|
|
47
|
+
"unknown": " ".join(risk.get("unknowns", [])) or "No additional unknowns recorded.",
|
|
48
|
+
}
|
|
49
|
+
return s
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _typo_template(b: dict, risk: dict, f: dict) -> dict[str, str]:
|
|
53
|
+
d, comp = b["detection"], b["component"]
|
|
54
|
+
reg = d.get("registry") or {}
|
|
55
|
+
reg_txt = "; ".join(d["evidence"][1:]) if len(d["evidence"]) > 1 else "no registry corroboration"
|
|
56
|
+
return {
|
|
57
|
+
"what": f"The package '{d['package']}' has a name very similar to the well-known {d['ecosystem']} package '{d['similar_to']}' "
|
|
58
|
+
f"(similarity {d['similarity_score']}%, edit distance {d['edit_distance']}).",
|
|
59
|
+
"why": f"Techniques: {', '.join(d['techniques'])}. Evidence strength: {d['evidence_strength']}. Reference set: {d['reference_source']}.",
|
|
60
|
+
"package": f"{d['package']} versions {', '.join(comp['versions']) or 'unknown'} in service(s) {', '.join(comp['services']) or 'unknown'}.",
|
|
61
|
+
"how_entered": f"Dependency type: {b['dependency']['type']}." + (f" Roots: {', '.join(b['dependency']['roots'])}." if b['dependency'].get('roots') else ""),
|
|
62
|
+
"direct_transitive": f"The package is classified as {b['dependency']['type']} in the dependency graph.",
|
|
63
|
+
"impact": "If this is a typosquat, it could execute attacker-controlled code at install or run time; this has NOT been established. "
|
|
64
|
+
"Name similarity is a signal, not proof of malicious intent.",
|
|
65
|
+
"evidence": f"Registry/similarity evidence: {reg_txt}.",
|
|
66
|
+
"remediation": f"Verify that '{d['package']}' is the intended dependency (compare with '{d['similar_to']}'), check its publisher and history on the registry, "
|
|
67
|
+
"and replace it if it was added by mistake.",
|
|
68
|
+
"unknown": " ".join(risk.get("unknowns", [])),
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _lock_template(b: dict, risk: dict, f: dict) -> dict[str, str]:
|
|
73
|
+
c, g = b["change"], b["git"]
|
|
74
|
+
prev, new = c.get("previous") or {}, c.get("new") or {}
|
|
75
|
+
return {
|
|
76
|
+
"what": f"Lockfile {c['file']} changed for '{c['package']}' ({c['change_type'].replace('_', ' ')})"
|
|
77
|
+
+ (f": {prev.get('version')} -> {new.get('version')}" if prev.get("version") or new.get("version") else "") + ".",
|
|
78
|
+
"why": " ".join(c["reasons"]) or "See classification.",
|
|
79
|
+
"package": f"{c['package']} ({c['ecosystem']}) in {c['file']}.",
|
|
80
|
+
"how_entered": f"Commit {g['commit']} compared with baseline {g['baseline']} ({g['baseline_mode']})"
|
|
81
|
+
+ (f"; subject: {g['commit_info'].get('subject')}; author: {g['commit_info'].get('author')}; date: {g['commit_info'].get('date')}" if g.get("commit_info") else "") + ".",
|
|
82
|
+
"direct_transitive": f"Manifest changed in the same commit: {'yes (' + ', '.join(c['manifest_files_changed']) + ')' if c['manifest_changed'] else 'no'}.",
|
|
83
|
+
"impact": f"Classification: {c['classification']}. A lockfile change alone does not prove compromise.",
|
|
84
|
+
"evidence": ("Diff excerpt: " + " | ".join(c["diff_excerpt"][:6])) if c.get("diff_excerpt") else "No diff excerpt available.",
|
|
85
|
+
"remediation": "Review the commit and the changed entry; confirm the update was intended (e.g. via the PR), and verify integrity hashes against the registry before trusting the change.",
|
|
86
|
+
"unknown": " ".join(risk.get("unknowns", [])),
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
TEMPLATES = {"vulnerability": _vuln_template, "typosquatting": _typo_template, "lockfile_change": _lock_template}
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def explain_deterministic(bundle: dict, risk: dict, finding: dict) -> dict:
|
|
94
|
+
sections = TEMPLATES[bundle["kind"]](bundle, risk, finding)
|
|
95
|
+
return {"finding_id": bundle["finding_id"], "kind": bundle["kind"], "source": "template", "sections": sections,
|
|
96
|
+
"risk_label": risk["label"], "risk_factors": fmt_factors(risk), "validation": {"grounded": True, "removed_sections": [], "checked": "template"},
|
|
97
|
+
"headline": _headline(bundle, risk)}
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _headline(b: dict, risk: dict) -> str:
|
|
101
|
+
k = b["kind"]
|
|
102
|
+
if k == "vulnerability":
|
|
103
|
+
return f"{risk['label']} risk - {b['advisory']['primary_id']} in {b['component']['name']} {b['component']['version']}"
|
|
104
|
+
if k == "typosquatting":
|
|
105
|
+
return f"{risk['label']} risk - '{b['detection']['package']}' resembles '{b['detection']['similar_to']}'"
|
|
106
|
+
return f"{risk['label']} risk - {b['change']['classification'].replace('_', ' ')}: {b['change']['package']}"
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def explain(bundle: dict, risk: dict, finding: dict, llm: Optional[Callable[[str, str], str]] = None) -> dict:
|
|
110
|
+
"""Deterministic explanation, optionally rephrased by ``llm(system, user) -> str`` with per-section validation."""
|
|
111
|
+
base = explain_deterministic(bundle, risk, finding)
|
|
112
|
+
if llm is None:
|
|
113
|
+
return base
|
|
114
|
+
try:
|
|
115
|
+
raw = llm(SYSTEM, build_user_prompt(compact_for_llm(bundle), json.dumps({k: risk[k] for k in ("label", "score", "factors", "unknowns", "cvss_severity")}, default=str)))
|
|
116
|
+
start, end = raw.find("{"), raw.rfind("}")
|
|
117
|
+
data = json.loads(raw[start:end + 1])
|
|
118
|
+
except Exception as e:
|
|
119
|
+
base["validation"] = {"grounded": True, "removed_sections": [], "checked": "template", "llm_error": f"{type(e).__name__}: {str(e)[:120]}"}
|
|
120
|
+
return base
|
|
121
|
+
sections, removed = {}, []
|
|
122
|
+
for name in SECTIONS:
|
|
123
|
+
txt = data.get(name)
|
|
124
|
+
problems = validate_text(txt, bundle, risk) if isinstance(txt, str) and txt.strip() else ["missing or empty section"]
|
|
125
|
+
if problems:
|
|
126
|
+
sections[name] = base["sections"][name]
|
|
127
|
+
removed.append({"section": name, "problems": problems[:4]})
|
|
128
|
+
else:
|
|
129
|
+
sections[name] = txt.strip()
|
|
130
|
+
used = len(removed) < len(SECTIONS)
|
|
131
|
+
return {**base, "sections": sections, "source": "llm+template" if removed and used else "llm" if used else "template",
|
|
132
|
+
"validation": {"grounded": True, "removed_sections": removed, "checked": "llm-validated"}}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""Ground-truth checks for explanation text: every identifier, number and risk label must come from the evidence."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import re
|
|
5
|
+
|
|
6
|
+
ID_RE = re.compile(r"\b(CVE-\d{4}-\d{4,}|GHSA-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}|PYSEC-\d+-\d+|GO-\d+-\d+|RUSTSEC-\d+-\d+|OSV-\d+-\d+)\b", re.I)
|
|
7
|
+
NUM_RE = re.compile(r"(?<![\w.])(?:v)?\d+\.\d+(?:\.\d+)*(?:[-+][0-9A-Za-z.]+)?(?![\w])")
|
|
8
|
+
LABEL_RE = re.compile(r"\b(CRITICAL|HIGH|MEDIUM|LOW|INFORMATIONAL)\b")
|
|
9
|
+
CERTAINTY = [
|
|
10
|
+
(re.compile(r"\b(actively|currently)\s+exploited|exploited in the wild", re.I), "kev", "claims active exploitation without a KEV entry"),
|
|
11
|
+
(re.compile(r"\b(is|are|was|confirmed|definitely|certainly)\s+(a\s+)?(malicious|compromised|backdoored)\b", re.I), None, "asserts maliciousness/compromise as fact"),
|
|
12
|
+
(re.compile(r"\bremote code execution|\bRCE\b|arbitrary code execution", re.I), "text:remote code execution|arbitrary code execution|rce", "claims code-execution impact not present in the advisory evidence"),
|
|
13
|
+
(re.compile(r"\b(is|are) (trivially |easily )?exploitable\b|will be exploited", re.I), None, "claims exploitability without evidence"),
|
|
14
|
+
(re.compile(r"\bunreachable\b|\bnot reachable\b|\bcannot be reached\b", re.I), None, "claims unreachability (reachability is unknown)"),
|
|
15
|
+
]
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def build_allowed_text(bundle_corpus: str, risk: dict) -> str:
|
|
19
|
+
extra = [str(risk.get("score", "")), risk.get("label", ""), str(risk.get("cvss_severity") or "")]
|
|
20
|
+
for f in risk.get("factors", []):
|
|
21
|
+
extra += [f["factor"], f["detail"], str(f["points"])]
|
|
22
|
+
extra += risk.get("unknowns", []) + [str(v) for v in risk.get("thresholds", {}).values()]
|
|
23
|
+
return (bundle_corpus + "\n" + "\n".join(extra)).lower()
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def validate_text(text: str, bundle: dict, risk: dict) -> list[str]:
|
|
27
|
+
"""Return a list of problems (empty list = grounded)."""
|
|
28
|
+
problems: list[str] = []
|
|
29
|
+
allowed = build_allowed_text(bundle.get("corpus", ""), risk)
|
|
30
|
+
for m in ID_RE.findall(text):
|
|
31
|
+
if m.lower() not in allowed:
|
|
32
|
+
problems.append(f"identifier '{m}' is not in the evidence")
|
|
33
|
+
for m in NUM_RE.findall(text):
|
|
34
|
+
tok = m.lstrip("v").lower()
|
|
35
|
+
if tok not in allowed:
|
|
36
|
+
problems.append(f"number/version '{m}' is not in the evidence")
|
|
37
|
+
allowed_labels = {risk.get("label")}
|
|
38
|
+
if risk.get("cvss_severity"):
|
|
39
|
+
allowed_labels.add(risk["cvss_severity"])
|
|
40
|
+
for fct in risk.get("factors", []):
|
|
41
|
+
allowed_labels.update(LABEL_RE.findall(fct["detail"]))
|
|
42
|
+
allowed_labels |= {"INFORMATIONAL"} if risk.get("label") == "INFORMATIONAL" else set()
|
|
43
|
+
for lab in set(LABEL_RE.findall(text)):
|
|
44
|
+
if lab not in allowed_labels and lab not in bundle.get("corpus", "").upper():
|
|
45
|
+
problems.append(f"risk/severity label '{lab}' contradicts the deterministic assessment")
|
|
46
|
+
kev = "true" in str(bundle.get("advisory", {}).get("kev", "")).lower()
|
|
47
|
+
for rx, need, msg in CERTAINTY:
|
|
48
|
+
if rx.search(text):
|
|
49
|
+
if need == "kev" and kev:
|
|
50
|
+
continue
|
|
51
|
+
if need and need.startswith("text:") and re.search(need[5:], bundle.get("corpus", ""), re.I):
|
|
52
|
+
continue
|
|
53
|
+
problems.append(msg)
|
|
54
|
+
return problems
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"""Prompt for the optional LLM explanation writer. The model only rephrases supplied evidence."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
SECTIONS = ["what", "why", "package", "how_entered", "direct_transitive", "impact", "evidence", "remediation", "unknown"]
|
|
5
|
+
|
|
6
|
+
SYSTEM = """You write short, precise security explanations for a software-supply-chain scanner.
|
|
7
|
+
You are given an EVIDENCE bundle and a deterministic RISK assessment. Rules:
|
|
8
|
+
- Use ONLY facts present in the evidence. Never invent CVE/GHSA ids, CVSS numbers, versions, package names or dependency paths.
|
|
9
|
+
- Never change or contradict the risk label or the factors. Do not claim exploitability, active exploitation, malicious intent,
|
|
10
|
+
or unreachability unless the evidence explicitly says so. Reachability is unknown unless stated.
|
|
11
|
+
- Similarity or a lockfile change is a signal, not proof of malice.
|
|
12
|
+
- If something is unknown, say it is unknown.
|
|
13
|
+
Return ONLY a JSON object with string values for exactly these keys: what, why, package, how_entered, direct_transitive, impact, evidence, remediation, unknown."""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def build_user_prompt(evidence_json: str, risk_json: str) -> str:
|
|
17
|
+
return (f"EVIDENCE:\n{evidence_json}\n\nRISK (deterministic, authoritative):\n{risk_json}\n\n"
|
|
18
|
+
"Write the explanation sections now as the JSON object described.")
|
|
File without changes
|