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,64 @@
|
|
|
1
|
+
"""HTTP client with timeouts, retry/backoff and explicit failure types (errors are never silently swallowed)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import time
|
|
5
|
+
from typing import Any, Optional
|
|
6
|
+
|
|
7
|
+
import requests
|
|
8
|
+
|
|
9
|
+
from stackparity import __version__
|
|
10
|
+
|
|
11
|
+
UA = f"stackparity/{__version__}"
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class SourceUnavailable(RuntimeError):
|
|
15
|
+
"""The remote source could not be reached or kept failing after retries."""
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class NotFound(RuntimeError):
|
|
19
|
+
pass
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class HttpClient:
|
|
23
|
+
def __init__(self, timeout: int = 25, retries: int = 3, backoff: float = 1.0, session: requests.Session | None = None, *, offline: bool = False,
|
|
24
|
+
operation: str = "advisory"):
|
|
25
|
+
self.offline = offline
|
|
26
|
+
self.operation = operation # network-policy category of the requests this client makes
|
|
27
|
+
self.timeout, self.retries, self.backoff = timeout, retries, backoff
|
|
28
|
+
self.session = session or requests.Session()
|
|
29
|
+
self.session.headers.update({"User-Agent": UA})
|
|
30
|
+
|
|
31
|
+
def request(self, method: str, url: str, headers: dict | None = None, **kw) -> requests.Response:
|
|
32
|
+
from core import netpolicy
|
|
33
|
+
if self.offline:
|
|
34
|
+
raise SourceUnavailable("Network access disabled for offline scan")
|
|
35
|
+
if not netpolicy.current().allows(self.operation):
|
|
36
|
+
raise SourceUnavailable(str(netpolicy.NetworkDenied(self.operation, url.split("?")[0])))
|
|
37
|
+
last: Optional[Exception] = None
|
|
38
|
+
for attempt in range(self.retries + 1):
|
|
39
|
+
try:
|
|
40
|
+
r = self.session.request(method, url, headers=headers, timeout=self.timeout, **kw)
|
|
41
|
+
except (requests.ConnectionError, requests.Timeout) as e:
|
|
42
|
+
last = e
|
|
43
|
+
else:
|
|
44
|
+
if r.status_code == 404:
|
|
45
|
+
raise NotFound(url)
|
|
46
|
+
if r.status_code == 429 or r.status_code >= 500:
|
|
47
|
+
last = SourceUnavailable(f"HTTP {r.status_code} from {url}")
|
|
48
|
+
ra = r.headers.get("Retry-After")
|
|
49
|
+
if ra and ra.isdigit() and attempt < self.retries:
|
|
50
|
+
time.sleep(min(int(ra), 30))
|
|
51
|
+
continue
|
|
52
|
+
elif r.status_code >= 400:
|
|
53
|
+
raise SourceUnavailable(f"HTTP {r.status_code} from {url}: {r.text[:200]}")
|
|
54
|
+
else:
|
|
55
|
+
return r
|
|
56
|
+
if attempt < self.retries:
|
|
57
|
+
time.sleep(self.backoff * (2 ** attempt))
|
|
58
|
+
raise SourceUnavailable(f"{url} unreachable after {self.retries + 1} attempts: {last}")
|
|
59
|
+
|
|
60
|
+
def get_json(self, url: str, **kw) -> Any:
|
|
61
|
+
return self.request("GET", url, **kw).json()
|
|
62
|
+
|
|
63
|
+
def post_json(self, url: str, payload: Any, **kw) -> Any:
|
|
64
|
+
return self.request("POST", url, json=payload, **kw).json()
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"""Shared normalized data models."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from typing import Any, Optional
|
|
5
|
+
|
|
6
|
+
from pydantic import BaseModel, Field
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class RepoInfo(BaseModel):
|
|
10
|
+
scan_id: str
|
|
11
|
+
url: str
|
|
12
|
+
name: str
|
|
13
|
+
owner: str = ""
|
|
14
|
+
ref: Optional[str] = None # requested branch/tag
|
|
15
|
+
branch: Optional[str] = None # resolved branch name
|
|
16
|
+
commit_sha: str
|
|
17
|
+
scan_timestamp: str
|
|
18
|
+
local_path: str = ""
|
|
19
|
+
shallow: bool = False
|
|
20
|
+
source: str = "github" # github | local
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class ManifestFile(BaseModel):
|
|
24
|
+
path: str # repo-relative, posix
|
|
25
|
+
name: str
|
|
26
|
+
kind: str # manifest | lockfile
|
|
27
|
+
ecosystem: str
|
|
28
|
+
service_dir: str # repo-relative dir ("." for root)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class FrameworkHit(BaseModel):
|
|
32
|
+
name: str
|
|
33
|
+
ecosystem: str
|
|
34
|
+
service_dir: str
|
|
35
|
+
evidence: str
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class InspectionResult(BaseModel):
|
|
39
|
+
languages: dict[str, dict[str, int]] = Field(default_factory=dict) # lang -> {files, bytes}
|
|
40
|
+
frameworks: list[FrameworkHit] = Field(default_factory=list)
|
|
41
|
+
ecosystems: list[str] = Field(default_factory=list)
|
|
42
|
+
manifests: list[ManifestFile] = Field(default_factory=list)
|
|
43
|
+
services: list[dict[str, Any]] = Field(default_factory=list) # {dir, ecosystems, manifests, frameworks}
|
|
44
|
+
dockerfiles: list[str] = Field(default_factory=list)
|
|
45
|
+
container_files: list[str] = Field(default_factory=list)
|
|
46
|
+
ci_files: list[str] = Field(default_factory=list)
|
|
47
|
+
unsupported: list[str] = Field(default_factory=list) # evidence of ecosystems without parser support
|
|
48
|
+
total_files: int = 0
|
|
49
|
+
truncated: bool = False
|
|
50
|
+
limitations: list[str] = Field(default_factory=list)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class LockDependency(BaseModel):
|
|
54
|
+
"""A dependency record extracted from a manifest/lockfile (independent of Syft)."""
|
|
55
|
+
|
|
56
|
+
name: str
|
|
57
|
+
version: Optional[str] = None
|
|
58
|
+
ecosystem: str
|
|
59
|
+
purl: Optional[str] = None
|
|
60
|
+
direct: Optional[bool] = None # None = not determinable from this file
|
|
61
|
+
dev: Optional[bool] = None
|
|
62
|
+
requires: list[str] = Field(default_factory=list) # names of dependencies (when the file records edges)
|
|
63
|
+
lockfile: str # repo-relative path
|
|
64
|
+
service_dir: str = "."
|
|
65
|
+
record: Optional[str] = None # location in file (e.g. "packages[node_modules/x]")
|
|
66
|
+
integrity: Optional[str] = None
|
|
67
|
+
resolved: Optional[str] = None # source URL / registry
|
|
68
|
+
source_type: Optional[str] = None # registry | git | url | path | unknown
|
|
69
|
+
# native metadata the lockfile itself records (never guessed): license, scope flags, install scripts, deprecation, homepage, authors, time ...
|
|
70
|
+
license: Optional[str] = None
|
|
71
|
+
meta: dict[str, Any] = Field(default_factory=dict)
|
|
72
|
+
derived: bool = False # True: not read from a file of the repository but resolved by the registry resolver (see sbom/fusion/resolver.py)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class Component(BaseModel):
|
|
76
|
+
"""Normalized CycloneDX component."""
|
|
77
|
+
|
|
78
|
+
bom_ref: str
|
|
79
|
+
name: str
|
|
80
|
+
version: Optional[str] = None
|
|
81
|
+
group: Optional[str] = None
|
|
82
|
+
type: str = "library"
|
|
83
|
+
purl: Optional[str] = None
|
|
84
|
+
ecosystem: Optional[str] = None # OSV-style ecosystem; None for unsupported
|
|
85
|
+
purl_type: Optional[str] = None
|
|
86
|
+
licenses: list[str] = Field(default_factory=list)
|
|
87
|
+
supplier: Optional[str] = None
|
|
88
|
+
cpe: Optional[str] = None
|
|
89
|
+
hashes: list[dict[str, str]] = Field(default_factory=list)
|
|
90
|
+
locations: list[str] = Field(default_factory=list) # repo-relative paths
|
|
91
|
+
service_dir: Optional[str] = None
|
|
92
|
+
found_by: Optional[str] = None
|
|
93
|
+
sources: list[str] = Field(default_factory=list) # which inventories saw it: syft | trivy | builtin | lockfile
|
|
94
|
+
# ---- fused metadata (sbom/fusion): every value knows where it came from
|
|
95
|
+
scope: Optional[str] = None # required | optional | dev
|
|
96
|
+
description: Optional[str] = None
|
|
97
|
+
external_refs: list[dict[str, str]] = Field(default_factory=list) # {type, url, source}
|
|
98
|
+
published_at: Optional[str] = None
|
|
99
|
+
deprecated: Optional[bool] = None
|
|
100
|
+
install_script: Optional[bool] = None # package runs code at install time (npm hasInstallScript)
|
|
101
|
+
direct_declared: Optional[bool] = None
|
|
102
|
+
source_type: Optional[str] = None # registry | git | url | path
|
|
103
|
+
resolved_url: Optional[str] = None
|
|
104
|
+
provenance: dict[str, dict[str, Any]] = Field(default_factory=dict) # field -> {source, confidence, evidence, conflicts[]}
|
|
105
|
+
integrity: dict[str, Any] = Field(default_factory=dict) # {status: verified|mismatch|unverifiable|absent, algorithm, lockfile, registry}
|
|
106
|
+
resolution: str = "scanner" # scanner | lockfile | registry-resolved
|
|
107
|
+
completeness: Optional[float] = None # 0..1 weighted share of key metadata fields that are known
|
|
108
|
+
is_self: bool = False # the application's own package (declared by its manifest), not a dependency
|
|
109
|
+
enriched: dict[str, dict[str, str]] = Field(default_factory=dict) # field -> {value, source}
|
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
"""Centralized execution and network policy shared by scanning, remediation, validation and publication.
|
|
2
|
+
|
|
3
|
+
A scan records the policy it ran under (``execution_policy`` in the stored result). Remediation and validation of that scan
|
|
4
|
+
inherit it: an offline scan is validated offline unless the user explicitly authorizes network access for that step
|
|
5
|
+
(``--online`` in the CLI, ``allow_network`` in the dashboard API). Every operation that could leave the machine names its
|
|
6
|
+
category and asks the active policy first:
|
|
7
|
+
|
|
8
|
+
advisory OSV / NVD / CISA KEV / EPSS queries
|
|
9
|
+
registry package-registry metadata (digests, typosquatting corroboration)
|
|
10
|
+
resolution dependency resolution against a registry (remediation planning)
|
|
11
|
+
compatibility registry metadata for a proposed version (deprecated, yanked, engines, peers)
|
|
12
|
+
scanner external scanners that may contact a service (Semgrep remote rules)
|
|
13
|
+
scanner_update scanner database or application updates (Trivy DB, Syft update check)
|
|
14
|
+
ai LLM providers
|
|
15
|
+
telemetry never allowed: StackParity sends no telemetry
|
|
16
|
+
git_remote git fetch / push / ls-remote against a remote
|
|
17
|
+
pr_publish GitHub CLI calls (authentication check, pull request creation)
|
|
18
|
+
package_manager package-manager subprocesses (lockfile regeneration, container dependency install)
|
|
19
|
+
|
|
20
|
+
Offline mode is enforced twice: callers check ``allows()`` before acting, and while an offline policy is active the process
|
|
21
|
+
refuses any socket connection that is not to a loopback address (``guard()``), so a missed check fails closed instead of
|
|
22
|
+
leaking a request. Subprocesses cannot be intercepted that way; they receive ``subprocess_env()``, which turns on each
|
|
23
|
+
package manager's offline switch, and are only started when the policy allows their category.
|
|
24
|
+
"""
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import contextvars
|
|
28
|
+
import ipaddress
|
|
29
|
+
import os
|
|
30
|
+
import socket
|
|
31
|
+
import threading
|
|
32
|
+
from contextlib import contextmanager
|
|
33
|
+
from dataclasses import asdict, dataclass, field, replace
|
|
34
|
+
from datetime import datetime, timezone
|
|
35
|
+
from typing import Iterator, Optional
|
|
36
|
+
|
|
37
|
+
OPERATIONS = ("advisory", "registry", "resolution", "compatibility", "scanner", "scanner_update", "ai", "telemetry",
|
|
38
|
+
"git_remote", "pr_publish", "package_manager")
|
|
39
|
+
NEVER = frozenset({"telemetry"})
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class NetworkDenied(PermissionError):
|
|
43
|
+
"""An operation needed network access that the active execution policy does not allow."""
|
|
44
|
+
|
|
45
|
+
def __init__(self, operation: str, what: str = "", policy: Optional["ExecutionPolicy"] = None):
|
|
46
|
+
self.operation = operation
|
|
47
|
+
why = "StackParity never sends telemetry" if operation in NEVER else f"the execution policy is {(policy or current()).mode}"
|
|
48
|
+
super().__init__(f"Network access for {operation}{f' ({what})' if what else ''} is not allowed: {why}.")
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass(frozen=True)
|
|
52
|
+
class ExecutionPolicy:
|
|
53
|
+
mode: str = "online" # online | offline
|
|
54
|
+
origin: str = "default" # why: default | scan --offline | inherited from scan <id> | authorized by <actor>
|
|
55
|
+
authorized: tuple[str, ...] = field(default_factory=tuple) # categories explicitly authorized after an offline scan
|
|
56
|
+
|
|
57
|
+
@property
|
|
58
|
+
def offline(self) -> bool:
|
|
59
|
+
return self.mode == "offline"
|
|
60
|
+
|
|
61
|
+
def allows(self, operation: str) -> bool:
|
|
62
|
+
if operation not in OPERATIONS:
|
|
63
|
+
raise ValueError(f"Unknown network operation category: {operation}")
|
|
64
|
+
if operation in NEVER:
|
|
65
|
+
return False
|
|
66
|
+
return not self.offline or operation in self.authorized
|
|
67
|
+
|
|
68
|
+
def require(self, operation: str, what: str = "") -> None:
|
|
69
|
+
if not self.allows(operation):
|
|
70
|
+
raise NetworkDenied(operation, what, self)
|
|
71
|
+
|
|
72
|
+
def authorize(self, operations: tuple[str, ...] | list[str], actor: str) -> "ExecutionPolicy":
|
|
73
|
+
"""A copy that additionally allows ``operations``: the explicit transition from offline to online for one step."""
|
|
74
|
+
ops = tuple(sorted(set(self.authorized) | {o for o in operations if o not in NEVER}))
|
|
75
|
+
for o in ops:
|
|
76
|
+
if o not in OPERATIONS:
|
|
77
|
+
raise ValueError(f"Unknown network operation category: {o}")
|
|
78
|
+
return replace(self, authorized=ops, origin=f"{self.origin}; network authorized by {actor} for {', '.join(ops)}")
|
|
79
|
+
|
|
80
|
+
def to_dict(self) -> dict:
|
|
81
|
+
return {**asdict(self), "authorized": list(self.authorized),
|
|
82
|
+
"denied": [o for o in OPERATIONS if not self.allows(o)], "recorded_at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")}
|
|
83
|
+
|
|
84
|
+
@classmethod
|
|
85
|
+
def from_dict(cls, data: Optional[dict]) -> Optional["ExecutionPolicy"]:
|
|
86
|
+
if not isinstance(data, dict) or data.get("mode") not in ("online", "offline"):
|
|
87
|
+
return None
|
|
88
|
+
return cls(mode=data["mode"], origin=str(data.get("origin") or "stored"), authorized=tuple(data.get("authorized") or ()))
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
ONLINE = ExecutionPolicy()
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def for_scan(scan: dict) -> ExecutionPolicy:
|
|
95
|
+
"""The policy a stored scan ran under. Scans stored before policies were recorded are classified from their sources."""
|
|
96
|
+
stored = ExecutionPolicy.from_dict(scan.get("execution_policy"))
|
|
97
|
+
sid = (scan.get("repo") or {}).get("scan_id") or "?"
|
|
98
|
+
if stored:
|
|
99
|
+
return ExecutionPolicy(mode=stored.mode, origin=f"inherited from scan {sid} ({stored.origin})")
|
|
100
|
+
osv = ((scan.get("source_status") or {}).get("OSV") or {}).get("state")
|
|
101
|
+
if osv in ("offline", None):
|
|
102
|
+
return ExecutionPolicy(mode="offline", origin=f"inherited from scan {sid} (advisories were not queried)")
|
|
103
|
+
return ExecutionPolicy(mode="online", origin=f"inherited from scan {sid}")
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
# ---------------------------------------------------------------------------------------------------------------- active policy
|
|
107
|
+
_process_default = ONLINE
|
|
108
|
+
_active: contextvars.ContextVar[Optional[ExecutionPolicy]] = contextvars.ContextVar("stackparity_execution_policy", default=None)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
_offline_active = 0 # number of offline policies currently in force anywhere in the process
|
|
112
|
+
_count_lock = threading.Lock()
|
|
113
|
+
_FAIL_CLOSED = ExecutionPolicy(mode="offline", origin="an offline operation is running in this process")
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def current() -> ExecutionPolicy:
|
|
117
|
+
"""The policy of this context. A worker thread that did not inherit one is treated as offline while any offline policy
|
|
118
|
+
is in force, so a thread pool that drops context variables fails closed instead of reaching the network."""
|
|
119
|
+
pol = _active.get()
|
|
120
|
+
if pol is not None:
|
|
121
|
+
return pol
|
|
122
|
+
return _FAIL_CLOSED if _offline_active else _process_default
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def set_process_default(policy: ExecutionPolicy) -> None:
|
|
126
|
+
global _process_default
|
|
127
|
+
_process_default = policy
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
@contextmanager
|
|
131
|
+
def use(policy: ExecutionPolicy) -> Iterator[ExecutionPolicy]:
|
|
132
|
+
"""Make ``policy`` active for this context; while it is offline, non-loopback sockets are refused."""
|
|
133
|
+
global _offline_active
|
|
134
|
+
token = _active.set(policy)
|
|
135
|
+
guard()
|
|
136
|
+
if policy.offline:
|
|
137
|
+
with _count_lock:
|
|
138
|
+
_offline_active += 1
|
|
139
|
+
try:
|
|
140
|
+
yield policy
|
|
141
|
+
finally:
|
|
142
|
+
if policy.offline:
|
|
143
|
+
with _count_lock:
|
|
144
|
+
_offline_active -= 1
|
|
145
|
+
_active.reset(token)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
# ---------------------------------------------------------------------------------------------------------------- socket guard
|
|
149
|
+
_guard_lock = threading.Lock()
|
|
150
|
+
_guard_installed = False
|
|
151
|
+
_LOOPBACK_NAMES = {"localhost", "localhost.localdomain", "ip6-localhost", ""}
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _is_loopback(host) -> bool:
|
|
155
|
+
if host is None:
|
|
156
|
+
return True
|
|
157
|
+
if isinstance(host, bytes):
|
|
158
|
+
host = host.decode("ascii", "ignore")
|
|
159
|
+
host = str(host).strip("[]").lower()
|
|
160
|
+
if host in _LOOPBACK_NAMES:
|
|
161
|
+
return True
|
|
162
|
+
try:
|
|
163
|
+
return ipaddress.ip_address(host.split("%")[0]).is_loopback
|
|
164
|
+
except ValueError:
|
|
165
|
+
return False
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _check(host, what: str) -> None:
|
|
169
|
+
pol = current()
|
|
170
|
+
if pol.offline and not _is_loopback(host):
|
|
171
|
+
raise NetworkDenied("network", f"{what} {host}", pol)
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _installed() -> bool:
|
|
175
|
+
return all(getattr(f, "_stackparity_guard", False)
|
|
176
|
+
for f in (socket.socket.connect, socket.socket.connect_ex, socket.getaddrinfo, socket.create_connection))
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def guard() -> None:
|
|
180
|
+
"""Install the process-wide socket checks consulted by every connection attempt (idempotent; re-installs itself if
|
|
181
|
+
something replaced the socket functions since)."""
|
|
182
|
+
global _guard_installed
|
|
183
|
+
with _guard_lock:
|
|
184
|
+
if _installed():
|
|
185
|
+
return
|
|
186
|
+
orig_connect, orig_connect_ex = socket.socket.connect, socket.socket.connect_ex
|
|
187
|
+
orig_getaddrinfo, orig_create = socket.getaddrinfo, socket.create_connection
|
|
188
|
+
|
|
189
|
+
def _addr_host(addr):
|
|
190
|
+
return addr[0] if isinstance(addr, tuple) and addr else None if not isinstance(addr, (str, bytes)) else "localhost"
|
|
191
|
+
|
|
192
|
+
def connect(self, address):
|
|
193
|
+
if self.family in (socket.AF_INET, socket.AF_INET6):
|
|
194
|
+
_check(_addr_host(address), "connection to")
|
|
195
|
+
return orig_connect(self, address)
|
|
196
|
+
|
|
197
|
+
def connect_ex(self, address):
|
|
198
|
+
if self.family in (socket.AF_INET, socket.AF_INET6):
|
|
199
|
+
_check(_addr_host(address), "connection to")
|
|
200
|
+
return orig_connect_ex(self, address)
|
|
201
|
+
|
|
202
|
+
def getaddrinfo(host, *a, **kw):
|
|
203
|
+
_check(host, "name resolution of")
|
|
204
|
+
return orig_getaddrinfo(host, *a, **kw)
|
|
205
|
+
|
|
206
|
+
def create_connection(address, *a, **kw):
|
|
207
|
+
_check(_addr_host(address), "connection to")
|
|
208
|
+
return orig_create(address, *a, **kw)
|
|
209
|
+
|
|
210
|
+
for f in (connect, connect_ex, getaddrinfo, create_connection):
|
|
211
|
+
f._stackparity_guard = True
|
|
212
|
+
socket.socket.connect, socket.socket.connect_ex = connect, connect_ex
|
|
213
|
+
socket.getaddrinfo, socket.create_connection = getaddrinfo, create_connection
|
|
214
|
+
_guard_installed = True
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
# ---------------------------------------------------------------------------------------------------------------- subprocesses
|
|
218
|
+
_OFFLINE_ENV = {
|
|
219
|
+
"npm_config_offline": "true", "npm_config_prefer_offline": "true", "npm_config_audit": "false", "npm_config_fund": "false",
|
|
220
|
+
"npm_config_update_notifier": "false",
|
|
221
|
+
"PNPM_OFFLINE": "true", "pnpm_config_offline": "true",
|
|
222
|
+
"YARN_ENABLE_NETWORK": "0", "YARN_ENABLE_OFFLINE_MODE": "1",
|
|
223
|
+
"UV_OFFLINE": "1", "PIP_NO_INDEX": "1", "PIPENV_OFFLINE": "1", "POETRY_OFFLINE": "1",
|
|
224
|
+
"GOPROXY": "off",
|
|
225
|
+
"CARGO_NET_OFFLINE": "true", "COMPOSER_DISABLE_NETWORK": "1", "BUNDLE_FROZEN": "true",
|
|
226
|
+
}
|
|
227
|
+
_ALWAYS_ENV = {
|
|
228
|
+
"SYFT_CHECK_FOR_APP_UPDATE": "false", "GRYPE_CHECK_FOR_APP_UPDATE": "false", "TRIVY_SKIP_DB_UPDATE": "true",
|
|
229
|
+
"TRIVY_SKIP_JAVA_DB_UPDATE": "true", "TRIVY_SKIP_CHECK_UPDATE": "true", "SEMGREP_SEND_METRICS": "off",
|
|
230
|
+
"DO_NOT_TRACK": "1", "NEXT_TELEMETRY_DISABLED": "1", "DOTNET_CLI_TELEMETRY_OPTOUT": "1", "HOMEBREW_NO_ANALYTICS": "1",
|
|
231
|
+
"npm_config_ignore_scripts": "true",
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def subprocess_env(base: Optional[dict] = None, policy: Optional[ExecutionPolicy] = None, operation: str = "package_manager") -> dict:
|
|
236
|
+
"""Environment for a child process: telemetry and self-update checks off; each tool's offline switch on when not allowed."""
|
|
237
|
+
pol = policy or current()
|
|
238
|
+
env = dict(os.environ if base is None else base)
|
|
239
|
+
env.update(_ALWAYS_ENV)
|
|
240
|
+
if not pol.allows(operation):
|
|
241
|
+
env.update(_OFFLINE_ENV)
|
|
242
|
+
return env
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""Plugin discovery through the ``stackparity.plugins`` entry-point group.
|
|
2
|
+
|
|
3
|
+
A plugin is an installed Python package exposing a zero-argument callable that registers its extensions:
|
|
4
|
+
|
|
5
|
+
[project.entry-points."stackparity.plugins"]
|
|
6
|
+
my_plugin = "my_package:register"
|
|
7
|
+
|
|
8
|
+
``register()`` may call ``ecosystems.registry.register``, ``sbom.lockfile_analyzer.register_parser``,
|
|
9
|
+
``non_cve.register_scanner`` and ``core.capabilities.register_tool``. Plugins come from the user's own Python
|
|
10
|
+
environment, never from the scanned repository. Set ``STACKPARITY_DISABLE_PLUGINS=1`` to load none.
|
|
11
|
+
"""
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import os
|
|
15
|
+
import threading
|
|
16
|
+
from importlib import metadata
|
|
17
|
+
from typing import Any, Optional
|
|
18
|
+
|
|
19
|
+
GROUP = "stackparity.plugins"
|
|
20
|
+
_lock = threading.Lock()
|
|
21
|
+
_loaded: Optional[list[dict[str, Any]]] = None
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _entry_points():
|
|
25
|
+
return metadata.entry_points(group=GROUP)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def load_plugins(reload: bool = False) -> list[dict[str, Any]]:
|
|
29
|
+
"""Load each plugin once per process; a broken plugin is reported, never raised."""
|
|
30
|
+
global _loaded
|
|
31
|
+
with _lock:
|
|
32
|
+
if _loaded is not None and not reload:
|
|
33
|
+
return list(_loaded)
|
|
34
|
+
out: list[dict[str, Any]] = []
|
|
35
|
+
if os.environ.get("STACKPARITY_DISABLE_PLUGINS", "").lower() not in ("1", "true", "yes"):
|
|
36
|
+
for ep in _entry_points():
|
|
37
|
+
try:
|
|
38
|
+
ep.load()()
|
|
39
|
+
out.append({"name": ep.name, "status": "loaded"})
|
|
40
|
+
except Exception as exc: # noqa: BLE001 - third-party code must not stop a scan
|
|
41
|
+
out.append({"name": ep.name, "status": "error", "error": f"{type(exc).__name__}: {str(exc)[:200]}"})
|
|
42
|
+
_loaded = out
|
|
43
|
+
return list(out)
|