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,383 @@
|
|
|
1
|
+
"""Syntax-aware source and configuration fixes for non-CVE findings.
|
|
2
|
+
|
|
3
|
+
A rule inspects the parsed file, not the raw text: Python rules look for one specific ``ast.Call`` on the reported line
|
|
4
|
+
(respecting import aliases and shadowed names), Kubernetes rules look for a real mapping key in the YAML node tree in the
|
|
5
|
+
right context (``securityContext``, pod spec). The edit replaces exactly the node's source span on that one line (plus, where
|
|
6
|
+
a rule says so, one import), and the result must parse again. A rule that cannot establish its applicability conditions
|
|
7
|
+
produces nothing, and the finding keeps its manual recommendation: comments, strings, multi-line calls, templated YAML,
|
|
8
|
+
ambiguous lines and unparseable files are never guessed at.
|
|
9
|
+
|
|
10
|
+
Rules are registered with ``register()``; the lifecycle calls only ``propose`` and ``locate``, so adding a rule never changes
|
|
11
|
+
the central workflow. Nothing here writes to disk.
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import ast
|
|
16
|
+
import re
|
|
17
|
+
from dataclasses import dataclass, field
|
|
18
|
+
from typing import Callable, Optional
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass(frozen=True)
|
|
22
|
+
class Edit:
|
|
23
|
+
"""One replacement on one line, in character columns of that line."""
|
|
24
|
+
start: int
|
|
25
|
+
end: int
|
|
26
|
+
text: str
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass(frozen=True)
|
|
30
|
+
class Rule:
|
|
31
|
+
key: str
|
|
32
|
+
applies_to: Callable[[str], bool] # file path -> bool
|
|
33
|
+
find: Callable[["FileContext", int], list[Edit]] # edits for the qualifying node(s) on a 1-based line
|
|
34
|
+
title: str
|
|
35
|
+
rationale: str # why the finding matters
|
|
36
|
+
risk: str # potential behavioural change, stated to the reviewer
|
|
37
|
+
confidence: str
|
|
38
|
+
applicability: str # conditions the rule verified before proposing the change
|
|
39
|
+
validation: str # what to check after applying it
|
|
40
|
+
add_import: Optional[str] = None # Python import line the replacement needs
|
|
41
|
+
finding_words: tuple = () # words in a finding title that tie a line-less finding to this rule
|
|
42
|
+
language: str = "python"
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass
|
|
46
|
+
class FileContext:
|
|
47
|
+
path: str
|
|
48
|
+
text: str
|
|
49
|
+
lines: list[str] = field(default_factory=list)
|
|
50
|
+
_py: object = None
|
|
51
|
+
_yaml: object = None
|
|
52
|
+
_calls: Optional[dict] = None
|
|
53
|
+
_entries: Optional[list] = None
|
|
54
|
+
|
|
55
|
+
def __post_init__(self) -> None:
|
|
56
|
+
self.lines = self.text.splitlines(keepends=True)
|
|
57
|
+
|
|
58
|
+
def calls_by_line(self) -> dict[int, list[ast.Call]]:
|
|
59
|
+
"""Single-line calls indexed by line (built once per file)."""
|
|
60
|
+
if self._calls is None:
|
|
61
|
+
self._calls = {}
|
|
62
|
+
tree = self.python()
|
|
63
|
+
for n in ast.walk(tree) if tree else ():
|
|
64
|
+
if isinstance(n, ast.Call) and getattr(n, "end_lineno", None) == n.lineno:
|
|
65
|
+
self._calls.setdefault(n.lineno, []).append(n)
|
|
66
|
+
return self._calls
|
|
67
|
+
|
|
68
|
+
def yaml_entries(self) -> list:
|
|
69
|
+
if self._entries is None:
|
|
70
|
+
self._entries = [e for doc in self.yaml_nodes() or [] for e in _walk_yaml(doc)]
|
|
71
|
+
return self._entries
|
|
72
|
+
|
|
73
|
+
def python(self) -> Optional[ast.Module]:
|
|
74
|
+
if self._py is None:
|
|
75
|
+
try:
|
|
76
|
+
self._py = ast.parse(self.text)
|
|
77
|
+
except (SyntaxError, ValueError):
|
|
78
|
+
self._py = False
|
|
79
|
+
return self._py or None
|
|
80
|
+
|
|
81
|
+
def yaml_nodes(self) -> Optional[list]:
|
|
82
|
+
if self._yaml is None:
|
|
83
|
+
try:
|
|
84
|
+
import yaml
|
|
85
|
+
self._yaml = list(yaml.compose_all(self.text, Loader=yaml.SafeLoader))
|
|
86
|
+
except Exception: # noqa: BLE001 - templated or invalid YAML: no automatic change
|
|
87
|
+
self._yaml = False
|
|
88
|
+
return self._yaml or None
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
_REGISTRY: list[Rule] = []
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def register(rule: Rule) -> Rule:
|
|
95
|
+
if any(r.key == rule.key for r in _REGISTRY):
|
|
96
|
+
raise ValueError(f"A code-fix rule named {rule.key!r} is already registered")
|
|
97
|
+
_REGISTRY.append(rule)
|
|
98
|
+
return rule
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def rules() -> list[Rule]:
|
|
102
|
+
return list(_REGISTRY)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
# ---------------------------------------------------------------------------------------------------------------- python helpers
|
|
106
|
+
def _py(path: str) -> bool:
|
|
107
|
+
return path.endswith(".py")
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _yaml_path(path: str) -> bool:
|
|
111
|
+
return path.endswith((".yml", ".yaml"))
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _col(line: str, byte_col: int) -> int:
|
|
115
|
+
"""ast column offsets are UTF-8 byte offsets; convert to a character index of ``line``."""
|
|
116
|
+
return len(line.encode("utf-8")[:byte_col].decode("utf-8", errors="ignore"))
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _module_aliases(tree: ast.Module, module: str) -> set[str]:
|
|
120
|
+
names = set()
|
|
121
|
+
for node in ast.walk(tree):
|
|
122
|
+
if isinstance(node, ast.Import):
|
|
123
|
+
names |= {a.asname or a.name for a in node.names if a.name == module}
|
|
124
|
+
return names
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _bound_names(tree: ast.Module) -> set[str]:
|
|
128
|
+
"""Names assigned, defined or imported anywhere in the module (a shadowed builtin is not the builtin)."""
|
|
129
|
+
out = set()
|
|
130
|
+
for node in ast.walk(tree):
|
|
131
|
+
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
|
|
132
|
+
out.add(node.name)
|
|
133
|
+
elif isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store):
|
|
134
|
+
out.add(node.id)
|
|
135
|
+
elif isinstance(node, (ast.Import, ast.ImportFrom)):
|
|
136
|
+
out |= {(a.asname or a.name).split(".")[0] for a in node.names}
|
|
137
|
+
elif isinstance(node, ast.arg):
|
|
138
|
+
out.add(node.arg)
|
|
139
|
+
return out
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _calls_on(ctx: FileContext, line_no: int) -> list[ast.Call]:
|
|
143
|
+
"""Calls that start and end on ``line_no`` (multi-line calls are not rewritten line by line)."""
|
|
144
|
+
return ctx.calls_by_line().get(line_no, [])
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _span(ctx: FileContext, node: ast.AST, text: str) -> Edit:
|
|
148
|
+
line = ctx.lines[node.lineno - 1]
|
|
149
|
+
return Edit(_col(line, node.col_offset), _col(line, node.end_col_offset), text)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _kw(call: ast.Call, name: str) -> Optional[ast.keyword]:
|
|
153
|
+
return next((k for k in call.keywords if k.arg == name), None)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _find_yaml_load(ctx: FileContext, line_no: int) -> list[Edit]:
|
|
157
|
+
tree = ctx.python()
|
|
158
|
+
aliases = _module_aliases(tree, "yaml") if tree else set()
|
|
159
|
+
out = []
|
|
160
|
+
for c in _calls_on(ctx, line_no):
|
|
161
|
+
f = c.func
|
|
162
|
+
if (isinstance(f, ast.Attribute) and f.attr == "load" and isinstance(f.value, ast.Name) and f.value.id in aliases
|
|
163
|
+
and len(c.args) == 1 and not c.keywords): # a Loader (positional or keyword) means the caller chose one: leave it
|
|
164
|
+
out.append(_span(ctx, f, f"{f.value.id}.safe_load"))
|
|
165
|
+
return out
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _find_flask_debug(ctx: FileContext, line_no: int) -> list[Edit]:
|
|
169
|
+
out = []
|
|
170
|
+
for c in _calls_on(ctx, line_no):
|
|
171
|
+
k = _kw(c, "debug")
|
|
172
|
+
if (isinstance(c.func, ast.Attribute) and c.func.attr == "run" and k is not None
|
|
173
|
+
and isinstance(k.value, ast.Constant) and k.value.value is True):
|
|
174
|
+
out.append(_span(ctx, k.value, "False"))
|
|
175
|
+
return out
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
_HTTP_CALLS = {"get", "post", "put", "patch", "delete", "head", "options", "request", "send", "Client", "AsyncClient", "Session", "stream"}
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _find_verify_off(ctx: FileContext, line_no: int) -> list[Edit]:
|
|
182
|
+
out = []
|
|
183
|
+
for c in _calls_on(ctx, line_no):
|
|
184
|
+
k = _kw(c, "verify")
|
|
185
|
+
name = c.func.attr if isinstance(c.func, ast.Attribute) else c.func.id if isinstance(c.func, ast.Name) else ""
|
|
186
|
+
if k is not None and name in _HTTP_CALLS and isinstance(k.value, ast.Constant) and k.value.value is False:
|
|
187
|
+
out.append(_span(ctx, k.value, "True"))
|
|
188
|
+
return out
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
_SUBPROCESS = {"run", "call", "check_call", "check_output", "Popen"}
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _find_shell_off(ctx: FileContext, line_no: int) -> list[Edit]:
|
|
195
|
+
tree = ctx.python()
|
|
196
|
+
aliases = _module_aliases(tree, "subprocess") if tree else set()
|
|
197
|
+
out = []
|
|
198
|
+
for c in _calls_on(ctx, line_no):
|
|
199
|
+
f, k = c.func, _kw(c, "shell")
|
|
200
|
+
if (isinstance(f, ast.Attribute) and f.attr in _SUBPROCESS and isinstance(f.value, ast.Name) and f.value.id in aliases
|
|
201
|
+
and k is not None and isinstance(k.value, ast.Constant) and k.value.value is True
|
|
202
|
+
and c.args and isinstance(c.args[0], (ast.List, ast.Tuple))): # a string command would need shlex parsing: manual
|
|
203
|
+
out.append(_span(ctx, k.value, "False"))
|
|
204
|
+
return out
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def _find_eval(ctx: FileContext, line_no: int) -> list[Edit]:
|
|
208
|
+
tree = ctx.python()
|
|
209
|
+
if tree is None:
|
|
210
|
+
return []
|
|
211
|
+
bound = _bound_names(tree)
|
|
212
|
+
if "eval" in bound or ("ast" in bound and not _module_aliases(tree, "ast") >= {"ast"}):
|
|
213
|
+
return [] # eval is not the builtin here, or the name ast means something else
|
|
214
|
+
out = []
|
|
215
|
+
for c in _calls_on(ctx, line_no):
|
|
216
|
+
if isinstance(c.func, ast.Name) and c.func.id == "eval" and len(c.args) == 1 and not c.keywords:
|
|
217
|
+
out.append(_span(ctx, c.func, "ast.literal_eval"))
|
|
218
|
+
return out
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
# ---------------------------------------------------------------------------------------------------------------- yaml helpers
|
|
222
|
+
def _walk_yaml(node, ancestors: tuple = ()):
|
|
223
|
+
"""Yield (key node, value node, ancestor key names, sibling key names) for every mapping entry."""
|
|
224
|
+
import yaml
|
|
225
|
+
if isinstance(node, yaml.MappingNode):
|
|
226
|
+
siblings = {k.value for k, _ in node.value if isinstance(k, yaml.ScalarNode)}
|
|
227
|
+
for k, v in node.value:
|
|
228
|
+
name = k.value if isinstance(k, yaml.ScalarNode) else None
|
|
229
|
+
yield k, v, ancestors, siblings
|
|
230
|
+
yield from _walk_yaml(v, ancestors + ((name,) if name else ()))
|
|
231
|
+
elif isinstance(node, yaml.SequenceNode):
|
|
232
|
+
for item in node.value:
|
|
233
|
+
yield from _walk_yaml(item, ancestors)
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def _yaml_bool_true(v) -> bool:
|
|
237
|
+
import yaml
|
|
238
|
+
return isinstance(v, yaml.ScalarNode) and v.tag == "tag:yaml.org,2002:bool" and v.value.lower() == "true"
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def _yaml_finder(keys: tuple[str, ...], context: Callable[[tuple, set], bool]) -> Callable[[FileContext, int], list[Edit]]:
|
|
242
|
+
def find(ctx: FileContext, line_no: int) -> list[Edit]:
|
|
243
|
+
return [Edit(v.start_mark.column, v.end_mark.column, "false") for k, v, anc, sib in ctx.yaml_entries()
|
|
244
|
+
if getattr(k, "value", None) in keys and _yaml_bool_true(v) and v.start_mark.line == line_no - 1
|
|
245
|
+
and v.end_mark.line == line_no - 1 and context(anc, sib)]
|
|
246
|
+
return find
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
_in_security_context = lambda anc, sib: "securityContext" in anc # noqa: E731
|
|
250
|
+
_in_pod_spec = lambda anc, sib: "containers" in sib # noqa: E731
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
# ---------------------------------------------------------------------------------------------------------------- rules
|
|
254
|
+
register(Rule("py-yaml-safe-load", _py, _find_yaml_load,
|
|
255
|
+
"Use yaml.safe_load instead of yaml.load",
|
|
256
|
+
"yaml.load without a safe Loader can construct arbitrary Python objects from untrusted YAML.",
|
|
257
|
+
"safe_load only builds plain types (dict, list, str, numbers); code that relies on custom tags or Python object tags stops working.",
|
|
258
|
+
"high",
|
|
259
|
+
"A call <yaml module or alias>.load(<one argument>) with no Loader, on one line of a file that parses.",
|
|
260
|
+
"Run the code paths that load YAML; check no document uses custom or !!python tags."))
|
|
261
|
+
register(Rule("py-flask-debug-off", _py, _find_flask_debug,
|
|
262
|
+
"Disable debug mode",
|
|
263
|
+
"Debug mode exposes an interactive debugger that allows code execution when reachable.",
|
|
264
|
+
"Development-only behaviour (auto-reload, the in-browser debugger) is turned off.",
|
|
265
|
+
"high",
|
|
266
|
+
"A .run(..., debug=True) call with the literal True, on one line.",
|
|
267
|
+
"Start the application; use FLASK_DEBUG or a development-only entry point if you need the debugger locally."))
|
|
268
|
+
register(Rule("py-requests-verify-on", _py, _find_verify_off,
|
|
269
|
+
"Re-enable TLS certificate verification",
|
|
270
|
+
"verify=False disables certificate checks and allows man-in-the-middle attacks.",
|
|
271
|
+
"Requests to hosts with self-signed or invalid certificates fail until a CA bundle is configured (verify='/path/ca.pem').",
|
|
272
|
+
"high",
|
|
273
|
+
"An HTTP client call (get/post/.../request/Client/Session) with the keyword verify=False, on one line.",
|
|
274
|
+
"Exercise the calls against every environment they reach (internal hosts often use private CAs)."))
|
|
275
|
+
register(Rule("py-subprocess-shell-off", _py, _find_shell_off,
|
|
276
|
+
"Run the subprocess without a shell",
|
|
277
|
+
"shell=True passes the command through the shell, so untrusted input can inject commands.",
|
|
278
|
+
"With a list command and shell=True, POSIX shells ran only the first element; shell=False runs the full argument list. "
|
|
279
|
+
"Shell features (pipes, globbing, variables) stop working.",
|
|
280
|
+
"medium",
|
|
281
|
+
"A subprocess.<run|call|check_call|check_output|Popen>(<list or tuple>, ..., shell=True) call on one line. String commands are left for manual review.",
|
|
282
|
+
"Run the code path; check the command did not rely on shell syntax."))
|
|
283
|
+
register(Rule("py-eval-literal", _py, _find_eval,
|
|
284
|
+
"Replace eval() with ast.literal_eval()",
|
|
285
|
+
"eval() executes arbitrary expressions; ast.literal_eval only accepts Python literals.",
|
|
286
|
+
"Breaking if the code evaluates anything other than literals (names, calls, arithmetic, comprehensions).",
|
|
287
|
+
"medium",
|
|
288
|
+
"A call to the builtin eval (not shadowed in the module) with exactly one argument, on one line; the name ast is free or is the ast module.",
|
|
289
|
+
"Feed the call every input shape it receives in practice; non-literal input now raises ValueError.",
|
|
290
|
+
add_import="import ast"))
|
|
291
|
+
register(Rule("k8s-privileged-off", _yaml_path, _yaml_finder(("privileged",), _in_security_context),
|
|
292
|
+
"Run the container unprivileged",
|
|
293
|
+
"A privileged container has full access to the host's devices and kernel capabilities.",
|
|
294
|
+
"Workloads that genuinely need host devices fail; grant the individual capabilities they need instead.",
|
|
295
|
+
"high",
|
|
296
|
+
"A privileged: true mapping entry (YAML boolean) inside a securityContext, in a file that parses as YAML.",
|
|
297
|
+
"Deploy to a test cluster and check the workload starts and works.",
|
|
298
|
+
finding_words=("privileged",), language="yaml"))
|
|
299
|
+
register(Rule("k8s-no-privilege-escalation", _yaml_path, _yaml_finder(("allowPrivilegeEscalation",), _in_security_context),
|
|
300
|
+
"Forbid privilege escalation",
|
|
301
|
+
"allowPrivilegeEscalation lets a process gain more privileges than its parent (setuid binaries).",
|
|
302
|
+
"Processes that rely on setuid binaries fail.",
|
|
303
|
+
"high",
|
|
304
|
+
"An allowPrivilegeEscalation: true entry (YAML boolean) inside a securityContext.",
|
|
305
|
+
"Deploy to a test cluster and check the workload starts and works.",
|
|
306
|
+
finding_words=("privilege escalation",), language="yaml"))
|
|
307
|
+
register(Rule("k8s-host-namespaces-off", _yaml_path, _yaml_finder(("hostNetwork", "hostPID", "hostIPC"), _in_pod_spec),
|
|
308
|
+
"Stop sharing host namespaces",
|
|
309
|
+
"Sharing the host network, PID or IPC namespace breaks container isolation.",
|
|
310
|
+
"Workloads that bind host ports or inspect host processes behave differently.",
|
|
311
|
+
"medium",
|
|
312
|
+
"A hostNetwork/hostPID/hostIPC: true entry (YAML boolean) in a pod spec (a mapping that also has containers).",
|
|
313
|
+
"Deploy to a test cluster; check networking and any host-process inspection.",
|
|
314
|
+
finding_words=("host network", "hostnetwork", "host namespace", "hostpid", "hostipc"), language="yaml"))
|
|
315
|
+
|
|
316
|
+
RULES = _REGISTRY # backwards-compatible name
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
# ---------------------------------------------------------------------------------------------------------------- engine
|
|
320
|
+
def _with_import(lines: list[str], import_line: str) -> list[str]:
|
|
321
|
+
"""Insert ``import_line`` after the module docstring and leading imports unless an identical line exists."""
|
|
322
|
+
if any(l.strip() == import_line for l in lines):
|
|
323
|
+
return lines
|
|
324
|
+
at = 0
|
|
325
|
+
for i, l in enumerate(lines):
|
|
326
|
+
s = l.strip()
|
|
327
|
+
if s.startswith(("import ", "from ")) or s.startswith("#!") or s.startswith("# -*-"):
|
|
328
|
+
at = i + 1
|
|
329
|
+
elif s and at:
|
|
330
|
+
break
|
|
331
|
+
newline = "\r\n" if lines and lines[0].endswith("\r\n") else "\n"
|
|
332
|
+
return lines[:at] + [import_line + newline] + lines[at:]
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def _reparses(rule: Rule, path: str, text: str) -> bool:
|
|
336
|
+
ctx = FileContext(path, text)
|
|
337
|
+
return (ctx.python() is not None) if rule.language == "python" else (ctx.yaml_nodes() is not None)
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def propose(path: str, text: str, line_no: int, only: Optional[str] = None) -> list[tuple[Rule, str]]:
|
|
341
|
+
"""Fixes (rule, new file text) for line ``line_no`` (1-based) of ``text``. ``only`` restricts to one rule key.
|
|
342
|
+
|
|
343
|
+
A rule contributes only when exactly one qualifying node is on that line (two calls on one line are ambiguous)."""
|
|
344
|
+
ctx = FileContext(path, text)
|
|
345
|
+
if not 1 <= line_no <= len(ctx.lines):
|
|
346
|
+
return []
|
|
347
|
+
out = []
|
|
348
|
+
for rule in _REGISTRY:
|
|
349
|
+
if (only and rule.key != only) or not rule.applies_to(path):
|
|
350
|
+
continue
|
|
351
|
+
edits = rule.find(ctx, line_no)
|
|
352
|
+
if len(edits) != 1:
|
|
353
|
+
continue
|
|
354
|
+
e = edits[0]
|
|
355
|
+
line = ctx.lines[line_no - 1]
|
|
356
|
+
new_line = line[:e.start] + e.text + line[e.end:]
|
|
357
|
+
if new_line == line:
|
|
358
|
+
continue
|
|
359
|
+
new_lines = list(ctx.lines)
|
|
360
|
+
new_lines[line_no - 1] = new_line
|
|
361
|
+
if rule.add_import:
|
|
362
|
+
new_lines = _with_import(new_lines, rule.add_import)
|
|
363
|
+
new_text = "".join(new_lines)
|
|
364
|
+
if _reparses(rule, path, new_text):
|
|
365
|
+
out.append((rule, new_text))
|
|
366
|
+
return out
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def locate(path: str, text: str, finding_title: str) -> Optional[int]:
|
|
370
|
+
"""Line of a finding reported without one: the single line a rule tied to the finding's title applies to, else None."""
|
|
371
|
+
title = (finding_title or "").lower()
|
|
372
|
+
candidates = [r for r in _REGISTRY if r.applies_to(path) and r.finding_words and any(w in title for w in r.finding_words)]
|
|
373
|
+
if not candidates:
|
|
374
|
+
return None
|
|
375
|
+
ctx = FileContext(path, text)
|
|
376
|
+
lines_with_nodes = set(ctx.calls_by_line()) if any(r.language == "python" for r in candidates) else set()
|
|
377
|
+
lines_with_nodes |= {v.start_mark.line + 1 for _, v, _, _ in ctx.yaml_entries()} if any(r.language == "yaml" for r in candidates) else set()
|
|
378
|
+
hits = sorted({n for n in lines_with_nodes for r in candidates if r.find(ctx, n)})
|
|
379
|
+
return hits[0] if len(hits) == 1 else None
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
def rule(key: str) -> Optional[Rule]:
|
|
383
|
+
return next((r for r in _REGISTRY if r.key == key), None)
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
"""Static compatibility check of a proposed version change, from the package registry's own metadata for the target version.
|
|
2
|
+
|
|
3
|
+
Checks (npm): deprecated flag, ``engines.node`` against the project's declared engines, ``peerDependencies`` against the project's direct
|
|
4
|
+
dependencies, and major-version jumps. PyPI: yanked releases and ``requires_python``. Range logic uses the semver library bundled with npm
|
|
5
|
+
(``npm root -g`` / npm / node_modules / semver) so it follows npm's exact rules; when it is unavailable the range checks report "unknown".
|
|
6
|
+
This does not replace running the project's tests; it catches the declared incompatibilities cheaply, before any build.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import shutil
|
|
12
|
+
import subprocess
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Any, Optional
|
|
15
|
+
from urllib.parse import quote
|
|
16
|
+
|
|
17
|
+
from core.http import HttpClient, NotFound, SourceUnavailable
|
|
18
|
+
|
|
19
|
+
_SEMVER_JS = ("const s=require(process.argv[1]);const ops=JSON.parse(require('fs').readFileSync(0,'utf8'));"
|
|
20
|
+
"console.log(JSON.stringify(ops.map(o=>{try{return o.op==='intersects'?s.intersects(o.a,o.b):s.satisfies(o.a,o.b)}catch(e){return null}})))")
|
|
21
|
+
_semver_path: Optional[str] = None
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _find_semver() -> Optional[str]:
|
|
25
|
+
global _semver_path
|
|
26
|
+
if _semver_path is not None:
|
|
27
|
+
return _semver_path or None
|
|
28
|
+
_semver_path = ""
|
|
29
|
+
npm = shutil.which("npm")
|
|
30
|
+
if npm:
|
|
31
|
+
cands = [Path(npm).resolve().parent / "node_modules" / "npm" / "node_modules" / "semver", # Windows installer layout
|
|
32
|
+
Path(npm).resolve().parent.parent / "lib" / "node_modules" / "npm" / "node_modules" / "semver"] # unix layout
|
|
33
|
+
try:
|
|
34
|
+
root = subprocess.run([npm, "root", "-g"], capture_output=True, text=True, timeout=30, shell=False).stdout.strip()
|
|
35
|
+
cands.append(Path(root) / "npm" / "node_modules" / "semver")
|
|
36
|
+
except (OSError, subprocess.TimeoutExpired):
|
|
37
|
+
pass
|
|
38
|
+
for cand in cands:
|
|
39
|
+
if cand.exists():
|
|
40
|
+
_semver_path = str(cand)
|
|
41
|
+
break
|
|
42
|
+
return _semver_path or None
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _semver(ops: list[dict]) -> list[Optional[bool]]:
|
|
46
|
+
node, sv = shutil.which("node"), _find_semver()
|
|
47
|
+
if not node or not sv or not ops:
|
|
48
|
+
return [None] * len(ops)
|
|
49
|
+
try:
|
|
50
|
+
p = subprocess.run([node, "-e", _SEMVER_JS, sv], input=json.dumps(ops), capture_output=True, text=True, timeout=30, shell=False)
|
|
51
|
+
out = json.loads(p.stdout.strip() or "[]")
|
|
52
|
+
return out if len(out) == len(ops) else [None] * len(ops)
|
|
53
|
+
except (OSError, subprocess.TimeoutExpired, ValueError):
|
|
54
|
+
return [None] * len(ops)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _c(name: str, status: str, detail: str) -> dict[str, str]:
|
|
58
|
+
return {"name": name, "status": status, "detail": detail}
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _npm(http: HttpClient, rem: dict, root: Path, manifest_dir: Path) -> list[dict]:
|
|
62
|
+
out: list[dict] = []
|
|
63
|
+
try:
|
|
64
|
+
proj = json.loads((manifest_dir / "package.json").read_text(encoding="utf-8"))
|
|
65
|
+
except (OSError, ValueError):
|
|
66
|
+
proj = {}
|
|
67
|
+
direct = {**(proj.get("dependencies") or {}), **(proj.get("devDependencies") or {}), **(proj.get("optionalDependencies") or {})}
|
|
68
|
+
proj_engine = (proj.get("engines") or {}).get("node")
|
|
69
|
+
ops: list[dict] = []
|
|
70
|
+
todo: list[tuple[str, str]] = [] # (check name, what the result means) aligned with ops
|
|
71
|
+
for ch in (rem.get("changes") or [])[:6]:
|
|
72
|
+
name, to = ch["package"], ch["to"]
|
|
73
|
+
try:
|
|
74
|
+
meta = http.get_json(f"https://registry.npmjs.org/{quote(name, safe='')}/{quote(to, safe='')}")
|
|
75
|
+
except (NotFound, SourceUnavailable):
|
|
76
|
+
out.append(_c(f"{name}@{to} metadata", "unknown", "registry metadata unavailable"))
|
|
77
|
+
continue
|
|
78
|
+
label = f"{name}@{to}"
|
|
79
|
+
if meta.get("deprecated"):
|
|
80
|
+
out.append(_c(f"{label} deprecated", "warn", str(meta["deprecated"])[:200]))
|
|
81
|
+
else:
|
|
82
|
+
out.append(_c(f"{label} deprecated", "ok", "not deprecated"))
|
|
83
|
+
eng = (meta.get("engines") or {}).get("node")
|
|
84
|
+
if eng and proj_engine:
|
|
85
|
+
ops.append({"op": "intersects", "a": proj_engine, "b": eng})
|
|
86
|
+
todo.append((f"{label} engines.node", f"project declares node {proj_engine}; package needs {eng}"))
|
|
87
|
+
elif eng:
|
|
88
|
+
out.append(_c(f"{label} engines.node", "ok", f"requires node {eng}; the project declares no engine range, so this cannot conflict"))
|
|
89
|
+
for peer, rng in (meta.get("peerDependencies") or {}).items():
|
|
90
|
+
optional = bool(((meta.get("peerDependenciesMeta") or {}).get(peer) or {}).get("optional"))
|
|
91
|
+
have = direct.get(peer)
|
|
92
|
+
if have:
|
|
93
|
+
ops.append({"op": "intersects", "a": have, "b": rng})
|
|
94
|
+
todo.append((f"{label} peer {peer}", f"project declares {peer}@{have}; package needs {rng}"))
|
|
95
|
+
elif not optional:
|
|
96
|
+
out.append(_c(f"{label} peer {peer}", "warn", f"needs {peer}@{rng}, which the project does not declare directly"))
|
|
97
|
+
for (name, detail), res in zip(todo, _semver(ops)):
|
|
98
|
+
out.append(_c(name, "ok" if res else "unknown" if res is None else "fail" if "engines" in name else "warn", detail + ("" if res else (" - semver library unavailable" if res is None else " - ranges do not overlap"))))
|
|
99
|
+
return out
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _pypi(http: HttpClient, rem: dict) -> list[dict]:
|
|
103
|
+
out: list[dict] = []
|
|
104
|
+
for ch in (rem.get("changes") or [])[:6]:
|
|
105
|
+
name, to = ch["package"], ch["to"]
|
|
106
|
+
try:
|
|
107
|
+
d = http.get_json(f"https://pypi.org/pypi/{quote(name, safe='')}/{quote(to, safe='')}/json")
|
|
108
|
+
except (NotFound, SourceUnavailable):
|
|
109
|
+
out.append(_c(f"{name}=={to} metadata", "unknown", "PyPI metadata unavailable"))
|
|
110
|
+
continue
|
|
111
|
+
info = d.get("info") or {}
|
|
112
|
+
if info.get("yanked"):
|
|
113
|
+
out.append(_c(f"{name}=={to} yanked", "fail", str(info.get("yanked_reason") or "this release was yanked by its maintainers")[:200]))
|
|
114
|
+
else:
|
|
115
|
+
out.append(_c(f"{name}=={to} yanked", "ok", "not yanked"))
|
|
116
|
+
if info.get("requires_python"):
|
|
117
|
+
out.append(_c(f"{name}=={to} requires_python", "ok", f"requires Python {info['requires_python']} (confirm your runtime satisfies it)"))
|
|
118
|
+
return out
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def static_compat(rem: dict, root: Path | str) -> dict[str, Any]:
|
|
122
|
+
"""Return {status: ok|warn|fail|unknown, checks: [{name, status, detail}]} for the proposal's version change."""
|
|
123
|
+
from core import netpolicy
|
|
124
|
+
root = Path(root)
|
|
125
|
+
eco = rem.get("ecosystem") or (rem.get("target") or {}).get("ecosystem")
|
|
126
|
+
http = HttpClient(timeout=15, retries=2, operation="compatibility")
|
|
127
|
+
checks: list[dict] = []
|
|
128
|
+
ch = (rem.get("compatibility") or {})
|
|
129
|
+
if ch.get("semver_change") == "major":
|
|
130
|
+
checks.append(_c("major version change", "warn", f"{(rem.get('target') or {}).get('from')} -> {(rem.get('target') or {}).get('to')}: read the release notes; breaking changes are expected"))
|
|
131
|
+
patch_path = (rem.get("patch") or {}).get("path") or ""
|
|
132
|
+
mdir = (root / patch_path).parent if patch_path else root
|
|
133
|
+
pol = netpolicy.current()
|
|
134
|
+
try:
|
|
135
|
+
if eco in ("npm", "PyPI") and not pol.allows("compatibility"):
|
|
136
|
+
# never reported as passing: the registry metadata was not consulted
|
|
137
|
+
checks.append(_c("registry metadata", "unverified",
|
|
138
|
+
f"not queried: the execution policy is offline ({pol.origin}); deprecated/yanked/engine/peer checks did not run"))
|
|
139
|
+
elif eco == "npm":
|
|
140
|
+
checks += _npm(http, rem, root, mdir)
|
|
141
|
+
elif eco == "PyPI":
|
|
142
|
+
checks += _pypi(http, rem)
|
|
143
|
+
else:
|
|
144
|
+
checks.append(_c("registry metadata", "unknown", f"no automated compatibility metadata for {eco or 'this ecosystem'}"))
|
|
145
|
+
except Exception as e: # noqa: BLE001 - metadata is advisory; never break validation
|
|
146
|
+
checks.append(_c("registry metadata", "unknown", f"{type(e).__name__}: {str(e)[:120]}"))
|
|
147
|
+
imp = rem.get("reachability_impact") or {}
|
|
148
|
+
if imp.get("app_files_affected"):
|
|
149
|
+
checks.append(_c("application usage", "warn" if (imp.get("reachability_preservation_score") or 100) < 100 else "ok",
|
|
150
|
+
f"{len(imp['app_files_affected'])} application file(s) import this package; {imp.get('impact_summary', '')}".strip()))
|
|
151
|
+
statuses = {c["status"] for c in checks}
|
|
152
|
+
if "unverified" in statuses:
|
|
153
|
+
status = "fail" if "fail" in statuses else "unverified"
|
|
154
|
+
else:
|
|
155
|
+
status = "fail" if "fail" in statuses else "warn" if "warn" in statuses else "ok" if statuses == {"ok"} or ("ok" in statuses and statuses <= {"ok", "unknown"}) else "unknown"
|
|
156
|
+
return {"status": status, "checks": checks}
|