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,215 @@
|
|
|
1
|
+
"""Static reachability evidence: is a dependency actually imported by the application's own source code?
|
|
2
|
+
|
|
3
|
+
This is *package-level import evidence*, not a call graph: it tells you whether the application can load the package, not whether a specific
|
|
4
|
+
vulnerable function is called. The result is therefore worded as evidence ("imported in app code at file:line"), never as proof of exploitability,
|
|
5
|
+
and absence of an import is never "safe" (packages can be used through configuration, plugins, CLIs or reflection).
|
|
6
|
+
|
|
7
|
+
One pass over the working tree builds an index of imports per file; every package query is then a dictionary lookup. Files are only read
|
|
8
|
+
(size-capped, path-confined, vendored folders skipped); nothing is executed.
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import ast
|
|
13
|
+
import os
|
|
14
|
+
import re
|
|
15
|
+
from dataclasses import dataclass, field
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Optional
|
|
18
|
+
|
|
19
|
+
from config.constants import IGNORED_DIRS
|
|
20
|
+
from sbom.package_extractors.common import normalize_name
|
|
21
|
+
|
|
22
|
+
EXT_LANG = {".py": "py", ".js": "js", ".jsx": "js", ".mjs": "js", ".cjs": "js", ".ts": "js", ".tsx": "js", ".vue": "js", ".java": "java", ".kt": "java", ".scala": "java",
|
|
23
|
+
".go": "go", ".rs": "rs", ".php": "php", ".cs": "cs", ".rb": "rb"}
|
|
24
|
+
LANG_ECO = {"py": "PyPI", "js": "npm", "java": "Maven", "go": "Go", "rs": "crates.io", "php": "Packagist", "cs": "NuGet", "rb": "RubyGems"}
|
|
25
|
+
SKIP_DIRS = IGNORED_DIRS | {"vendor", "third_party", "third-party", "site-packages", "coverage", ".next", ".nuxt", "out", "bower_components", "external", "Pods"}
|
|
26
|
+
TEST_PARTS = ("/test/", "/tests/", "/__tests__/", "/spec/", "/specs/", "/e2e/", "/cypress/", "/fixtures/", "/mocks/", "/__mocks__/", "/testing/", "/benchmark/", "/benchmarks/")
|
|
27
|
+
TEST_NAME = re.compile(r"(^|[/\\])(test_[^/\\]*\.py|[^/\\]*_test\.(py|go)|[^/\\]*\.(test|spec)\.[jt]sx?|[^/\\]*Test\.(java|kt)|[^/\\]*Tests?\.cs|conftest\.py)$")
|
|
28
|
+
# distribution name -> import name where they differ (PyPI)
|
|
29
|
+
PY_ALIAS = {"pyyaml": "yaml", "pillow": "PIL", "beautifulsoup4": "bs4", "scikit-learn": "sklearn", "python-dateutil": "dateutil", "opencv-python": "cv2", "opencv-python-headless": "cv2",
|
|
30
|
+
"protobuf": "google", "attrs": "attr", "pyjwt": "jwt", "python-dotenv": "dotenv", "pycryptodome": "Crypto", "pymysql": "pymysql", "mysqlclient": "MySQLdb", "psycopg2-binary": "psycopg2",
|
|
31
|
+
"msgpack-python": "msgpack", "pytest-cov": "pytest_cov", "ruamel-yaml": "ruamel", "typing-extensions": "typing_extensions", "setuptools": "pkg_resources", "importlib-metadata": "importlib_metadata",
|
|
32
|
+
"google-auth": "google", "azure-storage-blob": "azure", "markdown": "markdown", "docker": "docker", "websocket-client": "websocket", "python-jose": "jose", "pyopenssl": "OpenSSL"}
|
|
33
|
+
|
|
34
|
+
_JS_IMPORT = re.compile(r"""(?:require\(\s*|\bfrom\s+|\bimport\s*\(\s*|\bimport\s+)['"]([^'"\n]+)['"]""")
|
|
35
|
+
_JAVA = re.compile(r"^\s*import\s+(?:static\s+)?([\w.]+)\s*;", re.M)
|
|
36
|
+
_GO_SINGLE = re.compile(r'^\s*import\s+(?:[\w._]+\s+)?"([^"]+)"', re.M)
|
|
37
|
+
_GO_BLOCK = re.compile(r"^\s*import\s*\((.*?)\)", re.M | re.S)
|
|
38
|
+
_GO_LINE = re.compile(r'^\s*(?:[\w._]+\s+)?"([^"]+)"', re.M)
|
|
39
|
+
_RUST = re.compile(r"^\s*(?:pub\s+)?use\s+([A-Za-z_][\w]*)(?:::|;)|^\s*extern\s+crate\s+([A-Za-z_]\w*)", re.M)
|
|
40
|
+
_PHP = re.compile(r"^\s*use\s+(?:function\s+|const\s+)?([A-Za-z_][\w\\]*)", re.M)
|
|
41
|
+
_CS = re.compile(r"^\s*using\s+(?:static\s+)?([\w.]+)\s*;", re.M)
|
|
42
|
+
_RB = re.compile(r"""^\s*require(?:_relative)?\s*\(?\s*['"]([^'"]+)['"]""", re.M)
|
|
43
|
+
_PY = re.compile(r"^\s*(?:from\s+([\w.]+)\s+import|import\s+([\w.]+(?:\s*,\s*[\w.]+)*))", re.M)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass
|
|
47
|
+
class Usage:
|
|
48
|
+
path: str
|
|
49
|
+
line: int
|
|
50
|
+
module: str
|
|
51
|
+
test: bool
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dataclass
|
|
55
|
+
class SourceIndex:
|
|
56
|
+
root: Path
|
|
57
|
+
by_lang: dict[str, list[Usage]] = field(default_factory=dict)
|
|
58
|
+
files_by_lang: dict[str, int] = field(default_factory=dict)
|
|
59
|
+
skipped: int = 0
|
|
60
|
+
truncated: bool = False
|
|
61
|
+
|
|
62
|
+
@property
|
|
63
|
+
def languages(self) -> list[str]:
|
|
64
|
+
return sorted(l for l, n in self.files_by_lang.items() if n)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _is_test(rel: str) -> bool:
|
|
68
|
+
r = "/" + rel.replace("\\", "/")
|
|
69
|
+
return any(p in r for p in TEST_PARTS) or bool(TEST_NAME.search(r))
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _line_of(text: str, pos: int) -> int:
|
|
73
|
+
return text.count("\n", 0, pos) + 1
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _extract(lang: str, text: str) -> list[tuple[str, int]]:
|
|
77
|
+
out: list[tuple[str, int]] = []
|
|
78
|
+
if lang == "py":
|
|
79
|
+
try:
|
|
80
|
+
for n in ast.walk(ast.parse(text)):
|
|
81
|
+
if isinstance(n, ast.Import):
|
|
82
|
+
out += [(a.name, n.lineno) for a in n.names]
|
|
83
|
+
elif isinstance(n, ast.ImportFrom) and n.module and n.level == 0:
|
|
84
|
+
out.append((n.module, n.lineno))
|
|
85
|
+
return out
|
|
86
|
+
except (SyntaxError, ValueError, RecursionError):
|
|
87
|
+
for m in _PY.finditer(text):
|
|
88
|
+
for mod in re.split(r"\s*,\s*", m.group(1) or m.group(2) or ""):
|
|
89
|
+
if mod:
|
|
90
|
+
out.append((mod.strip(), _line_of(text, m.start())))
|
|
91
|
+
return out
|
|
92
|
+
if lang == "js":
|
|
93
|
+
return [(m.group(1), _line_of(text, m.start())) for m in _JS_IMPORT.finditer(text) if not m.group(1).startswith((".", "/"))]
|
|
94
|
+
if lang == "java":
|
|
95
|
+
return [(m.group(1), _line_of(text, m.start())) for m in _JAVA.finditer(text)]
|
|
96
|
+
if lang == "go":
|
|
97
|
+
for m in _GO_SINGLE.finditer(text):
|
|
98
|
+
out.append((m.group(1), _line_of(text, m.start())))
|
|
99
|
+
for b in _GO_BLOCK.finditer(text):
|
|
100
|
+
base = _line_of(text, b.start())
|
|
101
|
+
for ln in _GO_LINE.finditer(b.group(1)):
|
|
102
|
+
out.append((ln.group(1), base + b.group(1).count("\n", 0, ln.start())))
|
|
103
|
+
return out
|
|
104
|
+
if lang == "rs":
|
|
105
|
+
return [(m.group(1) or m.group(2), _line_of(text, m.start())) for m in _RUST.finditer(text)]
|
|
106
|
+
if lang == "php":
|
|
107
|
+
return [(m.group(1), _line_of(text, m.start())) for m in _PHP.finditer(text)]
|
|
108
|
+
if lang == "cs":
|
|
109
|
+
return [(m.group(1), _line_of(text, m.start())) for m in _CS.finditer(text)]
|
|
110
|
+
if lang == "rb":
|
|
111
|
+
return [(m.group(1), _line_of(text, m.start())) for m in _RB.finditer(text)]
|
|
112
|
+
return out
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def build_index(root: Path, max_files: int = 6000, max_bytes: int = 1_000_000) -> SourceIndex:
|
|
116
|
+
idx = SourceIndex(root=Path(root))
|
|
117
|
+
n = 0
|
|
118
|
+
for dp, dirs, files in os.walk(root, followlinks=False):
|
|
119
|
+
dirs[:] = [d for d in dirs if d not in SKIP_DIRS and not d.startswith(".git")]
|
|
120
|
+
for f in files:
|
|
121
|
+
lang = EXT_LANG.get(os.path.splitext(f)[1].lower())
|
|
122
|
+
if not lang:
|
|
123
|
+
continue
|
|
124
|
+
p = Path(dp) / f
|
|
125
|
+
try:
|
|
126
|
+
if p.is_symlink() or p.stat().st_size > max_bytes:
|
|
127
|
+
idx.skipped += 1
|
|
128
|
+
continue
|
|
129
|
+
text = p.read_text(encoding="utf-8", errors="replace")
|
|
130
|
+
except OSError:
|
|
131
|
+
idx.skipped += 1
|
|
132
|
+
continue
|
|
133
|
+
n += 1
|
|
134
|
+
if n > max_files:
|
|
135
|
+
idx.truncated = True
|
|
136
|
+
return idx
|
|
137
|
+
rel = p.relative_to(root).as_posix()
|
|
138
|
+
idx.files_by_lang[lang] = idx.files_by_lang.get(lang, 0) + 1
|
|
139
|
+
tst = _is_test(rel)
|
|
140
|
+
idx.by_lang.setdefault(lang, []).extend(Usage(rel, ln, mod, tst) for mod, ln in _extract(lang, text))
|
|
141
|
+
return idx
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _matches(eco: str, name: str, module: str) -> bool:
|
|
145
|
+
m = module
|
|
146
|
+
if eco == "npm":
|
|
147
|
+
return m == name or m.startswith(name + "/")
|
|
148
|
+
if eco == "PyPI":
|
|
149
|
+
top = m.split(".")[0].lower()
|
|
150
|
+
n = normalize_name("PyPI", name)
|
|
151
|
+
cands = {n.replace("-", "_"), n.replace("-", "")}
|
|
152
|
+
if n in PY_ALIAS:
|
|
153
|
+
cands.add(PY_ALIAS[n].lower())
|
|
154
|
+
if n.startswith("python-"):
|
|
155
|
+
cands.add(n[7:].replace("-", "_"))
|
|
156
|
+
if n.endswith("-python"):
|
|
157
|
+
cands.add(n[:-7].replace("-", "_"))
|
|
158
|
+
return top in cands
|
|
159
|
+
if eco == "Maven":
|
|
160
|
+
g, _, a = name.partition(":")
|
|
161
|
+
return bool(g) and (m == g or m.startswith(g + "."))
|
|
162
|
+
if eco == "Go":
|
|
163
|
+
return m == name or m.startswith(name + "/")
|
|
164
|
+
if eco == "crates.io":
|
|
165
|
+
return m.split("::")[0] == name.replace("-", "_")
|
|
166
|
+
if eco == "Packagist":
|
|
167
|
+
vendor, _, pkg = name.lower().partition("/")
|
|
168
|
+
first = m.lower().split("\\")[0]
|
|
169
|
+
return first == vendor.replace("-", "") or first == vendor.replace("-", "_")
|
|
170
|
+
if eco == "NuGet":
|
|
171
|
+
return m.lower() == name.lower() or m.lower().startswith(name.lower() + ".")
|
|
172
|
+
if eco == "RubyGems":
|
|
173
|
+
return m == name or m == name.replace("-", "/") or m.startswith(name + "/")
|
|
174
|
+
return False
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def package_usage(idx: SourceIndex, eco: str, name: str, limit: int = 5) -> dict:
|
|
178
|
+
"""Evidence for one package. ``status``: used_by_app | used_in_tests_only | not_imported | unknown (no analysable source for the ecosystem)."""
|
|
179
|
+
lang = next((l for l, e in LANG_ECO.items() if e == eco), None)
|
|
180
|
+
if not lang or not idx.files_by_lang.get(lang):
|
|
181
|
+
return {"status": "unknown", "reason": f"no {eco} source files were analysed", "app_files": 0, "test_files": 0, "locations": [], "confidence": "none",
|
|
182
|
+
"import_density": "none", "import_ratio": 0.0, "influence_tier": "unknown"}
|
|
183
|
+
hits = [u for u in idx.by_lang.get(lang, []) if _matches(eco, name, u.module)]
|
|
184
|
+
app = [u for u in hits if not u.test]
|
|
185
|
+
tst = [u for u in hits if u.test]
|
|
186
|
+
conf = "medium" if eco in ("Maven", "Packagist", "NuGet") else "high"
|
|
187
|
+
locs = [{"path": u.path, "line": u.line, "module": u.module, "test": u.test} for u in (app + tst)[:limit]]
|
|
188
|
+
total_files = idx.files_by_lang.get(lang, 0)
|
|
189
|
+
app_files_count = len({u.path for u in app})
|
|
190
|
+
test_files_count = len({u.path for u in tst})
|
|
191
|
+
import_ratio = round(app_files_count / max(1, total_files), 3)
|
|
192
|
+
|
|
193
|
+
if app_files_count >= 5 or (total_files > 0 and import_ratio >= 0.15):
|
|
194
|
+
density = "heavy"
|
|
195
|
+
tier = "heavy"
|
|
196
|
+
elif app_files_count >= 2:
|
|
197
|
+
density = "moderate"
|
|
198
|
+
tier = "moderate"
|
|
199
|
+
elif app_files_count == 1:
|
|
200
|
+
density = "light"
|
|
201
|
+
tier = "light"
|
|
202
|
+
elif test_files_count > 0:
|
|
203
|
+
density = "test_only"
|
|
204
|
+
tier = "tests_only"
|
|
205
|
+
else:
|
|
206
|
+
density = "none"
|
|
207
|
+
tier = "not_imported"
|
|
208
|
+
|
|
209
|
+
base = {"app_files": app_files_count, "test_files": test_files_count, "locations": locs, "confidence": conf, "files_analysed": total_files,
|
|
210
|
+
"truncated": idx.truncated, "import_density": density, "import_ratio": import_ratio, "influence_tier": tier}
|
|
211
|
+
if app:
|
|
212
|
+
return {**base, "status": "used_by_app"}
|
|
213
|
+
if tst:
|
|
214
|
+
return {**base, "status": "used_in_tests_only"}
|
|
215
|
+
return {**base, "status": "not_imported", "reason": "no import found in analysed source; the package may still be used through configuration, plugins, a CLI or reflection"}
|
|
File without changes
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
"""Capability-based lockfile adapters used after an approved manifest change.
|
|
2
|
+
|
|
3
|
+
An adapter knows one package manager: how to detect it next to a manifest, the command that regenerates its lockfile without
|
|
4
|
+
running package code, the command that checks the lockfile is consistent with the manifest, and what to tell the user when
|
|
5
|
+
neither can be done safely. ``run_isolated`` calls them inside the temporary worktree only, with a scrubbed environment
|
|
6
|
+
(no credentials), lifecycle scripts disabled, the active execution policy's network switches, and a timeout. A failed or
|
|
7
|
+
skipped regeneration never leaves a half-written lockfile behind: the worktree is discarded, and the result says the
|
|
8
|
+
manifest and lockfile disagree so the change is not applied or published silently.
|
|
9
|
+
|
|
10
|
+
``verified`` is True only for adapters whose regenerate-and-verify workflow is exercised by the test suite
|
|
11
|
+
(``tests/test_lockfile_adapters.py``). The others are prepared but report a manual recommendation instead of running.
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import json
|
|
16
|
+
import shutil
|
|
17
|
+
import subprocess
|
|
18
|
+
from dataclasses import dataclass
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
from typing import Callable, Optional
|
|
21
|
+
|
|
22
|
+
from core import netpolicy
|
|
23
|
+
from core.safe_env import scrubbed_env
|
|
24
|
+
|
|
25
|
+
TIMEOUT = 300
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass(frozen=True)
|
|
29
|
+
class Adapter:
|
|
30
|
+
name: str
|
|
31
|
+
ecosystem: str
|
|
32
|
+
manifests: tuple[str, ...]
|
|
33
|
+
lockfiles: tuple[str, ...]
|
|
34
|
+
tool: str
|
|
35
|
+
verified: bool # regenerate + verify exercised by the test suite
|
|
36
|
+
executes_package_code: bool = False # the tool may build source distributions / run build scripts to resolve
|
|
37
|
+
regenerate: Optional[Callable[[Path, dict, bool], list[str]]] = None # (manifest_dir, change, offline) -> argv
|
|
38
|
+
verify: Optional[Callable[[Path], list[str]]] = None # argv that exits non-zero when lockfile != manifest
|
|
39
|
+
manual: str = "" # command to run by hand (shown when not automated)
|
|
40
|
+
offline_capable: bool = False # regeneration can work from the local package cache
|
|
41
|
+
detect_extra: Optional[Callable[[Path], bool]] = None
|
|
42
|
+
|
|
43
|
+
@property
|
|
44
|
+
def capabilities(self) -> dict:
|
|
45
|
+
return {"ecosystem_detection": True, "package_manager_detection": True, "manifest_editing": True,
|
|
46
|
+
"compatibility_analysis": self.ecosystem in ("npm", "PyPI"), "lockfile_regeneration": self.regenerate is not None,
|
|
47
|
+
"resolution_validation": self.verify is not None, "security_rescan": True, "rollback": True,
|
|
48
|
+
"verified": self.verified, "executes_package_code": self.executes_package_code}
|
|
49
|
+
|
|
50
|
+
def detect(self, mdir: Path) -> Optional[str]:
|
|
51
|
+
if not any((mdir / m).is_file() for m in self.manifests):
|
|
52
|
+
return None
|
|
53
|
+
lock = next((n for n in self.lockfiles if (mdir / n).is_file()), None)
|
|
54
|
+
if lock and (self.detect_extra is None or self.detect_extra(mdir)):
|
|
55
|
+
return lock
|
|
56
|
+
return None
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _pkg(change: dict) -> str:
|
|
60
|
+
return str(change.get("package") or "")
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _yarn_berry(mdir: Path) -> bool:
|
|
64
|
+
if (mdir / ".yarnrc.yml").is_file():
|
|
65
|
+
return True
|
|
66
|
+
try:
|
|
67
|
+
pm = json.loads((mdir / "package.json").read_text(encoding="utf-8")).get("packageManager") or ""
|
|
68
|
+
except (OSError, ValueError):
|
|
69
|
+
return False
|
|
70
|
+
return pm.startswith("yarn@") and not pm.startswith("yarn@1.")
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _pip_tools(mdir: Path) -> bool:
|
|
74
|
+
try:
|
|
75
|
+
head = (mdir / "requirements.txt").read_text(encoding="utf-8", errors="replace")[:600]
|
|
76
|
+
except OSError:
|
|
77
|
+
return False
|
|
78
|
+
return (mdir / "requirements.in").is_file() and "pip-compile" in head
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
ADAPTERS: tuple[Adapter, ...] = (
|
|
82
|
+
Adapter("npm", "npm", ("package.json",), ("package-lock.json", "npm-shrinkwrap.json"), "npm", verified=True, offline_capable=True,
|
|
83
|
+
regenerate=lambda d, c, off: ["npm", "install", "--package-lock-only", "--ignore-scripts", "--no-audit", "--no-fund"] + (["--offline"] if off else []),
|
|
84
|
+
verify=lambda d: ["npm", "ls", "--package-lock-only", "--all", "--depth=0"],
|
|
85
|
+
manual="npm install --package-lock-only --ignore-scripts"),
|
|
86
|
+
Adapter("pnpm", "npm", ("package.json",), ("pnpm-lock.yaml",), "pnpm", verified=True, offline_capable=True,
|
|
87
|
+
regenerate=lambda d, c, off: ["pnpm", "install", "--lockfile-only", "--ignore-scripts"] + (["--offline"] if off else []),
|
|
88
|
+
verify=lambda d: ["pnpm", "install", "--frozen-lockfile", "--lockfile-only", "--ignore-scripts", "--offline"],
|
|
89
|
+
manual="pnpm install --lockfile-only --ignore-scripts"),
|
|
90
|
+
Adapter("yarn-berry", "npm", ("package.json",), ("yarn.lock",), "yarn", verified=False, detect_extra=_yarn_berry,
|
|
91
|
+
regenerate=lambda d, c, off: ["yarn", "install", "--mode=update-lockfile"],
|
|
92
|
+
verify=lambda d: ["yarn", "install", "--immutable", "--mode=skip-build"],
|
|
93
|
+
manual="yarn install --mode=update-lockfile"),
|
|
94
|
+
Adapter("yarn-classic", "npm", ("package.json",), ("yarn.lock",), "yarn", verified=False, detect_extra=lambda d: not _yarn_berry(d),
|
|
95
|
+
manual="yarn install --ignore-scripts (Yarn 1 has no lockfile-only mode; run it in a disposable checkout)"),
|
|
96
|
+
Adapter("uv", "PyPI", ("pyproject.toml",), ("uv.lock",), "uv", verified=True, offline_capable=True,
|
|
97
|
+
regenerate=lambda d, c, off: ["uv", "lock", "--no-build", "--upgrade-package", _pkg(c)] + (["--offline"] if off else []),
|
|
98
|
+
verify=lambda d: ["uv", "lock", "--check", "--offline"],
|
|
99
|
+
manual="uv lock --upgrade-package <package>"),
|
|
100
|
+
Adapter("poetry", "PyPI", ("pyproject.toml",), ("poetry.lock",), "poetry", verified=False, executes_package_code=True,
|
|
101
|
+
regenerate=lambda d, c, off: ["poetry", "lock", "--no-interaction"],
|
|
102
|
+
verify=lambda d: ["poetry", "check", "--lock", "--no-interaction"],
|
|
103
|
+
manual="poetry lock"),
|
|
104
|
+
Adapter("pipenv", "PyPI", ("Pipfile",), ("Pipfile.lock",), "pipenv", verified=False, executes_package_code=True,
|
|
105
|
+
regenerate=lambda d, c, off: ["pipenv", "lock"],
|
|
106
|
+
verify=lambda d: ["pipenv", "verify"],
|
|
107
|
+
manual="pipenv lock"),
|
|
108
|
+
Adapter("pip-tools", "PyPI", ("requirements.in",), ("requirements.txt",), "pip-compile", verified=False, detect_extra=_pip_tools,
|
|
109
|
+
regenerate=lambda d, c, off: ["pip-compile", "--quiet", "--no-upgrade", "--upgrade-package", f"{_pkg(c)}=={c.get('to')}",
|
|
110
|
+
"--pip-args", "--only-binary=:all:", "--output-file", "requirements.txt", "requirements.in"],
|
|
111
|
+
manual="pip-compile --upgrade-package <package>==<version> requirements.in"),
|
|
112
|
+
# prepared, not automated: each would need its own isolation review and tests before StackParity runs it
|
|
113
|
+
Adapter("cargo", "crates.io", ("Cargo.toml",), ("Cargo.lock",), "cargo", verified=False, manual="cargo update -p <package> --precise <version>"),
|
|
114
|
+
Adapter("go", "Go", ("go.mod",), ("go.sum",), "go", verified=False, manual="go mod tidy"),
|
|
115
|
+
Adapter("maven", "Maven", ("pom.xml",), (), "mvn", verified=False, manual="mvn -q dependency:resolve (Maven has no lockfile; re-run your build)"),
|
|
116
|
+
Adapter("gradle", "Maven", ("build.gradle", "build.gradle.kts"), ("gradle.lockfile",), "gradle", verified=False,
|
|
117
|
+
manual="gradle dependencies --write-locks (runs the build scripts: only in a trusted checkout)"),
|
|
118
|
+
Adapter("composer", "Packagist", ("composer.json",), ("composer.lock",), "composer", verified=False,
|
|
119
|
+
manual="composer update <package> --no-scripts --no-plugins"),
|
|
120
|
+
Adapter("nuget", "NuGet", ("packages.config",), ("packages.lock.json",), "dotnet", verified=False,
|
|
121
|
+
manual="dotnet restore --force-evaluate (evaluates MSBuild: only in a trusted checkout)"),
|
|
122
|
+
Adapter("bundler", "RubyGems", ("Gemfile",), ("Gemfile.lock",), "bundle", verified=False, manual="bundle lock --update <package>"),
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def detect(mdir: Path, ecosystem: str = "") -> list[tuple[Adapter, str]]:
|
|
127
|
+
"""Adapters (with the lockfile found) for the package manager(s) used next to a manifest."""
|
|
128
|
+
found = []
|
|
129
|
+
for a in ADAPTERS:
|
|
130
|
+
if ecosystem and a.ecosystem != ecosystem:
|
|
131
|
+
continue
|
|
132
|
+
lock = a.detect(mdir)
|
|
133
|
+
if lock:
|
|
134
|
+
found.append((a, lock))
|
|
135
|
+
return found
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def matrix() -> list[dict]:
|
|
139
|
+
"""Supported-ecosystem matrix for documentation and ``stackparity doctor``."""
|
|
140
|
+
return [{"adapter": a.name, "ecosystem": a.ecosystem, "lockfiles": list(a.lockfiles), "tool": a.tool,
|
|
141
|
+
"installed": bool(shutil.which(a.tool)), **a.capabilities,
|
|
142
|
+
"automation": ("automated" if a.regenerate and a.verified and not a.executes_package_code
|
|
143
|
+
else "opt-in (may run package build code)" if a.regenerate and a.executes_package_code
|
|
144
|
+
else "automated, not yet verified" if a.regenerate else "manual recommendation")}
|
|
145
|
+
for a in ADAPTERS]
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _run(argv: list[str], cwd: Path, exe: str) -> tuple[int, str]:
|
|
149
|
+
try:
|
|
150
|
+
p = subprocess.run([exe, *argv[1:]], cwd=str(cwd), capture_output=True, text=True, encoding="utf-8", errors="replace",
|
|
151
|
+
timeout=TIMEOUT, shell=False, env=scrubbed_env({"CI": "1"}, operation="package_manager"))
|
|
152
|
+
except subprocess.TimeoutExpired:
|
|
153
|
+
return 124, f"timed out after {TIMEOUT}s"
|
|
154
|
+
except OSError as exc:
|
|
155
|
+
return 127, str(exc)
|
|
156
|
+
return p.returncode, ((p.stderr or "") + (p.stdout or "")).strip()[-600:]
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def regenerate(wt_root: Path, manifest_rel: str, ecosystem: str, change: dict, *, enabled: bool, allow_build_code: bool = False) -> list[dict]:
|
|
160
|
+
"""Regenerate and verify every lockfile that belongs to ``manifest_rel`` inside the worktree ``wt_root``.
|
|
161
|
+
|
|
162
|
+
Returns one entry per lockfile: {lockfile, adapter, status, detail, command, consistent}. ``status`` is one of
|
|
163
|
+
regenerated | failed | unavailable | skipped | manual; ``consistent`` is True only when the verify command passed.
|
|
164
|
+
"""
|
|
165
|
+
mdir = (wt_root / manifest_rel).parent
|
|
166
|
+
prefix = "" if mdir == wt_root else mdir.relative_to(wt_root).as_posix() + "/"
|
|
167
|
+
pol = netpolicy.current()
|
|
168
|
+
offline = not pol.allows("package_manager")
|
|
169
|
+
out = []
|
|
170
|
+
for a, lock in detect(mdir, ecosystem):
|
|
171
|
+
e = {"lockfile": prefix + lock, "adapter": a.name, "status": "skipped", "detail": "", "consistent": False,
|
|
172
|
+
"command": a.manual.replace("<package>", _pkg(change)).replace("<version>", str(change.get("to") or ""))}
|
|
173
|
+
exe = shutil.which(a.tool)
|
|
174
|
+
if a.executes_package_code and not allow_build_code:
|
|
175
|
+
e.update(status="manual", detail=f"{a.name} may build source distributions (running package code) while locking; it would run only with "
|
|
176
|
+
f"explicit authorization (--allow-build-code). Run `{e['command']}` yourself in a trusted environment.")
|
|
177
|
+
elif a.regenerate is None or not a.verified:
|
|
178
|
+
e.update(status="manual", detail=f"Automatic {a.name} lockfile regeneration is not supported yet. Run `{e['command']}` and review the result.")
|
|
179
|
+
elif not enabled:
|
|
180
|
+
e.update(status="skipped", detail=f"Lockfile regeneration was not requested (--lockfiles). Until `{e['command']}` runs, {lock} does not match the manifest.")
|
|
181
|
+
elif not exe:
|
|
182
|
+
e.update(status="unavailable", detail=f"{a.tool} is not installed. Run `{e['command']}`.")
|
|
183
|
+
elif offline and not a.offline_capable:
|
|
184
|
+
e.update(status="unavailable", detail=f"{a.name} needs registry access and the execution policy is offline ({pol.origin}).")
|
|
185
|
+
else:
|
|
186
|
+
code, log = _run(a.regenerate(mdir, change, offline), mdir, exe)
|
|
187
|
+
if code != 0:
|
|
188
|
+
e.update(status="failed", detail=(("offline, from the local package cache: " if offline else "") + log)[-500:])
|
|
189
|
+
else:
|
|
190
|
+
e.update(status="regenerated", detail=("from the local package cache (offline)" if offline else "regenerated") + f" with `{' '.join(a.regenerate(mdir, change, offline))}`")
|
|
191
|
+
if a.verify:
|
|
192
|
+
vcode, vlog = _run(a.verify(mdir), mdir, exe)
|
|
193
|
+
e["consistent"] = vcode == 0
|
|
194
|
+
e["detail"] += "; lockfile verified against the manifest" if vcode == 0 else f"; verification failed: {vlog[-300:]}"
|
|
195
|
+
else:
|
|
196
|
+
e["consistent"] = True
|
|
197
|
+
out.append(e)
|
|
198
|
+
return out
|