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,263 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Lifecycle Script Investigator (Phase 1.2)
|
|
3
|
+
Statically inspects package manifests and lockfile metadata for suspicious lifecycle scripts.
|
|
4
|
+
|
|
5
|
+
Inspects:
|
|
6
|
+
- package.json scripts (preinstall, install, postinstall, preuninstall, postuninstall, prepare, etc.)
|
|
7
|
+
- lockfile metadata (hasInstallScript)
|
|
8
|
+
|
|
9
|
+
Detects:
|
|
10
|
+
1. Shell and process spawning (exec, spawn, bash, sh, powershell, cmd).
|
|
11
|
+
2. Eval and obfuscation (eval(), Function(), hex/unicode escapes, string decoding).
|
|
12
|
+
3. Base64 payload decoding (Buffer.from(..., 'base64'), atob, base64 -d).
|
|
13
|
+
4. Remote downloads and network calls (curl, wget, http.get, fetch, Invoke-WebRequest).
|
|
14
|
+
5. Remote script piped to shell (curl | sh, wget | bash).
|
|
15
|
+
6. Environment variable access (process.env, printenv, export).
|
|
16
|
+
7. Credential access and sensitive file targeting (.ssh, .aws, .env, id_rsa, token, secret).
|
|
17
|
+
8. Suspicious file-system operations (rm -rf /, chmod +x /tmp).
|
|
18
|
+
|
|
19
|
+
Distinguishes benign native compilation (e.g. node-gyp rebuild) from high-risk patterns.
|
|
20
|
+
Never executes scripts.
|
|
21
|
+
"""
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import json
|
|
25
|
+
import re
|
|
26
|
+
from pathlib import Path
|
|
27
|
+
from typing import Any, Dict, List, Optional, Tuple
|
|
28
|
+
|
|
29
|
+
LIFECYCLE_SCRIPT_NAMES = {
|
|
30
|
+
"preinstall",
|
|
31
|
+
"install",
|
|
32
|
+
"postinstall",
|
|
33
|
+
"preuninstall",
|
|
34
|
+
"postuninstall",
|
|
35
|
+
"prepack",
|
|
36
|
+
"postpack",
|
|
37
|
+
"prepare",
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
# Regex patterns for static detection
|
|
41
|
+
PATTERNS = {
|
|
42
|
+
"pipe_to_shell": (
|
|
43
|
+
re.compile(r"(curl|wget|fetch)\s+[^\n|;]+\|\s*(sh|bash|zsh|dash|powershell|cmd)\b", re.IGNORECASE),
|
|
44
|
+
"CRITICAL",
|
|
45
|
+
"Lifecycle script pipes remote download directly into shell",
|
|
46
|
+
"Executes unverified remote code with package install permissions; classic attack vector for reverse shells and backdoors."
|
|
47
|
+
),
|
|
48
|
+
"base64_eval": (
|
|
49
|
+
re.compile(r"(eval|Function)\s*\(\s*(Buffer\.from\([^)]*['\"]base64['\"]|atob\(|[A-Za-z0-9+/=]{40,})", re.IGNORECASE),
|
|
50
|
+
"CRITICAL",
|
|
51
|
+
"Lifecycle script evaluates base64-encoded payload",
|
|
52
|
+
"Obfuscation technique commonly used to hide malicious payloads from scanners and code review."
|
|
53
|
+
),
|
|
54
|
+
"credential_access": (
|
|
55
|
+
re.compile(r"(\.ssh/|\.aws/credentials|\.npmrc|\.env\b|id_rsa|\b(AWS_SECRET_ACCESS_KEY|GITHUB_TOKEN|NPM_TOKEN)\b)", re.IGNORECASE),
|
|
56
|
+
"CRITICAL",
|
|
57
|
+
"Lifecycle script targets sensitive credential paths or secret tokens",
|
|
58
|
+
"Attempts to access host credentials, deployment keys, or sensitive configuration files during installation."
|
|
59
|
+
),
|
|
60
|
+
"suspicious_eval_obfuscation": (
|
|
61
|
+
re.compile(r"\b(eval\s*\(|new\s+Function\s*\(|unescape\s*\(|String\.fromCharCode\s*\()", re.IGNORECASE),
|
|
62
|
+
"HIGH",
|
|
63
|
+
"Lifecycle script uses dynamic code evaluation or string obfuscation",
|
|
64
|
+
"Dynamic code evaluation in install scripts obscures runtime behavior and prevents static verification."
|
|
65
|
+
),
|
|
66
|
+
"hex_escapes": (
|
|
67
|
+
re.compile(r"(\\x[0-9a-fA-F]{2}){4,}|(\\u[0-9a-fA-F]{4}){4,}", re.IGNORECASE),
|
|
68
|
+
"HIGH",
|
|
69
|
+
"Lifecycle script contains heavily escaped hex/unicode characters",
|
|
70
|
+
"High concentration of hex or unicode escapes suggests intentional payload obfuscation."
|
|
71
|
+
),
|
|
72
|
+
"remote_download": (
|
|
73
|
+
re.compile(r"\b(curl\s+|wget\s+|Invoke-WebRequest|Invoke-RestMethod|http\.get\s*\(|https\.get\s*\(|fetch\s*\()", re.IGNORECASE),
|
|
74
|
+
"MEDIUM",
|
|
75
|
+
"Lifecycle script initiates remote network download",
|
|
76
|
+
"Downloads external binaries or scripts at install time outside the package manager's integrity verification."
|
|
77
|
+
),
|
|
78
|
+
"env_exfiltration": (
|
|
79
|
+
re.compile(r"\b(process\.env|printenv|env\s*\|)", re.IGNORECASE),
|
|
80
|
+
"MEDIUM",
|
|
81
|
+
"Lifecycle script inspects process environment variables",
|
|
82
|
+
"Harvesting environment variables during build or install may leak CI/CD secrets and API keys."
|
|
83
|
+
),
|
|
84
|
+
"process_spawning": (
|
|
85
|
+
re.compile(r"\b(child_process|exec\s*\(|spawn\s*\(|execSync\s*\()", re.IGNORECASE),
|
|
86
|
+
"LOW",
|
|
87
|
+
"Lifecycle script spawns child processes",
|
|
88
|
+
"Process creation in install scripts executes secondary commands and binaries."
|
|
89
|
+
),
|
|
90
|
+
"docker_latest": (
|
|
91
|
+
re.compile(r"docker\s+run\s+.*:latest\b", re.IGNORECASE),
|
|
92
|
+
"MEDIUM",
|
|
93
|
+
"Unpinned Docker Execution in npm Script",
|
|
94
|
+
"npm script invokes 'docker run' using mutable ':latest' image tag instead of an immutable digest."
|
|
95
|
+
),
|
|
96
|
+
"destructive_fs": (
|
|
97
|
+
re.compile(r"\b(rm\s+-rf\s+[/~]|chmod\s+\+x\s+(/tmp|/var/tmp))", re.IGNORECASE),
|
|
98
|
+
"HIGH",
|
|
99
|
+
"Lifecycle script executes potentially unsafe filesystem operations",
|
|
100
|
+
"Risks modifying system files or executing unauthorized binaries in shared temporary directories."
|
|
101
|
+
),
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
BENIGN_COMPILATION_PATTERNS = [
|
|
105
|
+
re.compile(r"^node-gyp\s+(rebuild|configure|build)$"),
|
|
106
|
+
re.compile(r"^(npx\s+)?tsc\b"),
|
|
107
|
+
re.compile(r"^(npx\s+)?webpack\b"),
|
|
108
|
+
re.compile(r"^(npx\s+)?vite\s+build\b"),
|
|
109
|
+
re.compile(r"^(npx\s+)?esbuild\b"),
|
|
110
|
+
re.compile(r"^patch-package\b"),
|
|
111
|
+
re.compile(r"^make\b"),
|
|
112
|
+
re.compile(r"^cargo\s+build\b"),
|
|
113
|
+
]
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _is_benign_build_command(command: str) -> bool:
|
|
117
|
+
clean = command.strip()
|
|
118
|
+
return any(p.match(clean) for p in BENIGN_COMPILATION_PATTERNS)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def inspect_lifecycle_scripts_text(
|
|
122
|
+
content: str,
|
|
123
|
+
file_path: str = "package.json",
|
|
124
|
+
commit_reference: Optional[Dict[str, str]] = None,
|
|
125
|
+
change_origin: str = "PRE_EXISTING"
|
|
126
|
+
) -> List[Dict[str, Any]]:
|
|
127
|
+
"""Statically inspect package.json manifest content for lifecycle scripts."""
|
|
128
|
+
findings: List[Dict[str, Any]] = []
|
|
129
|
+
if not content:
|
|
130
|
+
return findings
|
|
131
|
+
|
|
132
|
+
try:
|
|
133
|
+
data = json.loads(content)
|
|
134
|
+
except Exception:
|
|
135
|
+
return findings
|
|
136
|
+
|
|
137
|
+
scripts = data.get("scripts", {})
|
|
138
|
+
if not isinstance(scripts, dict):
|
|
139
|
+
return findings
|
|
140
|
+
|
|
141
|
+
lines = content.splitlines()
|
|
142
|
+
|
|
143
|
+
for script_name, cmd in scripts.items():
|
|
144
|
+
if not isinstance(cmd, str):
|
|
145
|
+
continue
|
|
146
|
+
|
|
147
|
+
target_lifecycle = script_name.lower() in LIFECYCLE_SCRIPT_NAMES
|
|
148
|
+
# Standard lifecycle scripts (preinstall, postinstall, etc.) receive increased scrutiny,
|
|
149
|
+
# but all npm scripts are scanned for malicious/unpinned patterns.
|
|
150
|
+
|
|
151
|
+
# Find line number of script definition
|
|
152
|
+
line_no = 1
|
|
153
|
+
for idx, line in enumerate(lines, start=1):
|
|
154
|
+
if f'"{script_name}"' in line:
|
|
155
|
+
line_no = idx
|
|
156
|
+
break
|
|
157
|
+
|
|
158
|
+
# Check for benign compile scripts first
|
|
159
|
+
if _is_benign_build_command(cmd):
|
|
160
|
+
continue
|
|
161
|
+
|
|
162
|
+
# Evaluate against suspicious patterns
|
|
163
|
+
for pattern_id, (regex, sev, title, impact) in PATTERNS.items():
|
|
164
|
+
if regex.search(cmd):
|
|
165
|
+
finding_id = f"SCRIPT-{pattern_id.upper()}-{script_name.upper()}-L{line_no}"
|
|
166
|
+
confidence = "HIGH" if sev in ("CRITICAL", "HIGH") else "MEDIUM"
|
|
167
|
+
|
|
168
|
+
findings.append({
|
|
169
|
+
"id": finding_id,
|
|
170
|
+
"category": "Lifecycle Script",
|
|
171
|
+
"title": f"Suspicious '{script_name}' Script: {title}",
|
|
172
|
+
"severity": sev,
|
|
173
|
+
"confidence": confidence,
|
|
174
|
+
"status": "OBSERVED",
|
|
175
|
+
"affected_file": file_path,
|
|
176
|
+
"line_number": line_no,
|
|
177
|
+
"commit_reference": commit_reference or {},
|
|
178
|
+
"change_origin": change_origin,
|
|
179
|
+
"evidence_type": "HEURISTIC_FLAG",
|
|
180
|
+
"evidence": f'"{script_name}": "{cmd}"',
|
|
181
|
+
"technical_explanation": (
|
|
182
|
+
f"Script '{script_name}' defines command '{cmd}'. "
|
|
183
|
+
f"Pattern match for '{pattern_id}': {impact}"
|
|
184
|
+
),
|
|
185
|
+
"potential_impact": impact,
|
|
186
|
+
"recommended_action": (
|
|
187
|
+
"Audit the script behavior. If installing dependencies, run with '--ignore-scripts' "
|
|
188
|
+
"and replace inline commands with trusted build scripts."
|
|
189
|
+
),
|
|
190
|
+
"references": [
|
|
191
|
+
"https://docs.npmjs.com/cli/v9/using-npm/scripts#life-cycle-scripts",
|
|
192
|
+
"https://github.blog/2021-02-04-preventing-supply-chain-attacks-like-dependency-confusion/"
|
|
193
|
+
]
|
|
194
|
+
})
|
|
195
|
+
|
|
196
|
+
return findings
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def inspect_manifest_file(file_path: Path, repo_root: Path) -> List[Dict[str, Any]]:
|
|
200
|
+
"""Inspect local manifest file directly."""
|
|
201
|
+
if not file_path.exists():
|
|
202
|
+
return []
|
|
203
|
+
try:
|
|
204
|
+
content = file_path.read_text(encoding="utf-8", errors="replace")
|
|
205
|
+
rel_path = str(file_path.relative_to(repo_root)).replace("\\", "/")
|
|
206
|
+
return inspect_lifecycle_scripts_text(content, file_path=rel_path)
|
|
207
|
+
except Exception:
|
|
208
|
+
return []
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def inspect_lockfile_install_scripts(
|
|
212
|
+
lockfile_content: str,
|
|
213
|
+
file_path: str = "package-lock.json",
|
|
214
|
+
commit_reference: Optional[Dict[str, str]] = None,
|
|
215
|
+
change_origin: str = "PRE_EXISTING"
|
|
216
|
+
) -> List[Dict[str, Any]]:
|
|
217
|
+
"""
|
|
218
|
+
Inspect package-lock.json v2/v3 metadata for packages declaring 'hasInstallScript': true.
|
|
219
|
+
Direct install script execution in transitive dependencies is a prime supply chain vector.
|
|
220
|
+
"""
|
|
221
|
+
findings: List[Dict[str, Any]] = []
|
|
222
|
+
if not lockfile_content:
|
|
223
|
+
return findings
|
|
224
|
+
|
|
225
|
+
try:
|
|
226
|
+
data = json.loads(lockfile_content)
|
|
227
|
+
except Exception:
|
|
228
|
+
return findings
|
|
229
|
+
|
|
230
|
+
packages = data.get("packages", {})
|
|
231
|
+
if not isinstance(packages, dict):
|
|
232
|
+
return findings
|
|
233
|
+
|
|
234
|
+
for pkg_path, meta in packages.items():
|
|
235
|
+
if not isinstance(meta, dict) or not pkg_path:
|
|
236
|
+
continue
|
|
237
|
+
if meta.get("hasInstallScript") is True:
|
|
238
|
+
pkg_name = pkg_path.split("node_modules/")[-1] if "node_modules/" in pkg_path else pkg_path
|
|
239
|
+
version = meta.get("version", "unknown")
|
|
240
|
+
ev_type = "OBSERVED_CHANGE" if (commit_reference and commit_reference.get("sha") and change_origin == "INTRODUCED_IN_RANGE") else "HEURISTIC_FLAG"
|
|
241
|
+
findings.append({
|
|
242
|
+
"id": f"LOCK-INSTALL-SCRIPT-{pkg_name.upper().replace('@', '').replace('/', '_')}",
|
|
243
|
+
"category": "Lifecycle Script",
|
|
244
|
+
"title": f"Dependency '{pkg_name}@{version}' Declares Install Script in Lockfile",
|
|
245
|
+
"severity": "LOW",
|
|
246
|
+
"confidence": "HIGH" if ev_type == "OBSERVED_CHANGE" else "MEDIUM",
|
|
247
|
+
"status": "OBSERVED",
|
|
248
|
+
"affected_file": file_path,
|
|
249
|
+
"line_number": 1,
|
|
250
|
+
"commit_reference": commit_reference or {},
|
|
251
|
+
"change_origin": change_origin,
|
|
252
|
+
"evidence_type": ev_type,
|
|
253
|
+
"evidence": f'"{pkg_path}": {{ "hasInstallScript": true, "version": "{version}" }}',
|
|
254
|
+
"technical_explanation": (
|
|
255
|
+
f"Package '{pkg_name}' declares 'hasInstallScript: true' in lockfile metadata. "
|
|
256
|
+
"When installed without '--ignore-scripts', it automatically executes code on the host machine."
|
|
257
|
+
),
|
|
258
|
+
"potential_impact": "Code execution occurs during 'npm install' on developer workstations and CI runners.",
|
|
259
|
+
"recommended_action": "Verify package authenticity and run builds with '--ignore-scripts' where feasible.",
|
|
260
|
+
"references": ["https://docs.npmjs.com/cli/v9/configuring-npm/package-lock-json"]
|
|
261
|
+
})
|
|
262
|
+
|
|
263
|
+
return findings
|
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
"""Modified-lockfile detector based on real Git history.
|
|
2
|
+
|
|
3
|
+
For each analysed commit the lockfiles changed against a baseline (the commit's parent by default, or an explicit
|
|
4
|
+
baseline ref) are parsed with the ecosystem parsers on both sides and diffed per package. Every change is classified:
|
|
5
|
+
|
|
6
|
+
* ``normal_update`` version/membership change consistent with a manifest change or a dependency cascade
|
|
7
|
+
* ``unexplained_change`` lockfile change that the same commit does not explain (verify; common with `npm update`)
|
|
8
|
+
* ``potentially_suspicious`` integrity/source anomalies (hash changed for the same version, non-registry source, ...)
|
|
9
|
+
* ``insufficient_baseline`` no parent / shallow boundary / baseline not found -> nothing is invented
|
|
10
|
+
|
|
11
|
+
A lockfile change is never reported as "malicious".
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import os
|
|
16
|
+
import re
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from typing import Any, Optional
|
|
19
|
+
|
|
20
|
+
from config.constants import MANIFEST_FILES, MANIFEST_SUFFIXES
|
|
21
|
+
from core import git_manager as gm
|
|
22
|
+
from core.models import LockDependency
|
|
23
|
+
from sbom.lockfile_analyzer import SIBLINGS, parse_text, parser_for
|
|
24
|
+
from sbom.package_extractors.common import host_of, normalize_name
|
|
25
|
+
from suspicious_changes.suspicious_models import LockfileChange
|
|
26
|
+
from vulnerability.version_matcher import VersionError, compare
|
|
27
|
+
|
|
28
|
+
# files whose diffs we treat as *lockfiles* (resolved state). pom.xml / package.json are *manifests*.
|
|
29
|
+
LOCKFILE_NAMES = {n for n, (k, _) in MANIFEST_FILES.items() if k == "lockfile" and n not in ("go.mod",)}
|
|
30
|
+
MANIFEST_NAMES = {n for n, (k, _) in MANIFEST_FILES.items() if k == "manifest"}
|
|
31
|
+
MAX_CHANGES_PER_FILE = 300
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _is_lockfile(name: str) -> bool:
|
|
35
|
+
if name in LOCKFILE_NAMES or (name.startswith("requirements") and name.endswith(".txt")):
|
|
36
|
+
return True
|
|
37
|
+
return False
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _is_manifest(name: str) -> bool:
|
|
41
|
+
return name in MANIFEST_NAMES or os.path.splitext(name)[1].lower() in MANIFEST_SUFFIXES
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _index(deps: list[LockDependency]) -> dict[tuple[str, str], list[LockDependency]]:
|
|
45
|
+
idx: dict[tuple[str, str], list[LockDependency]] = {}
|
|
46
|
+
for d in deps:
|
|
47
|
+
idx.setdefault((d.ecosystem, normalize_name(d.ecosystem, d.name)), []).append(d)
|
|
48
|
+
return idx
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _snap(d: Optional[LockDependency]) -> dict[str, Any]:
|
|
52
|
+
if d is None:
|
|
53
|
+
return {}
|
|
54
|
+
return {"version": d.version, "integrity": d.integrity, "resolved": d.resolved, "source_type": d.source_type,
|
|
55
|
+
"direct": d.direct, "record": d.record}
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _sibling_texts(repo: Path, sha: str, path: str) -> dict[str, Optional[str]]:
|
|
59
|
+
name = path.rsplit("/", 1)[-1]
|
|
60
|
+
sib = {}
|
|
61
|
+
for kw, sib_name in SIBLINGS.get(name, {}).items():
|
|
62
|
+
rel = path.rsplit("/", 1)[0] + "/" + sib_name if "/" in path else sib_name
|
|
63
|
+
sib[kw] = gm.show_file(repo, sha, rel)
|
|
64
|
+
return sib
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _diff_excerpt(repo: Path, base: str, head: str, path: str, needles: list[str], limit: int = 12) -> list[str]:
|
|
68
|
+
"""Changed (+/-) lines of every diff hunk in which the package name appears (context lines count for the match)."""
|
|
69
|
+
text = gm.diff_text(repo, base, head, path, context=4)
|
|
70
|
+
needles = [n for n in needles if n]
|
|
71
|
+
out: list[str] = []
|
|
72
|
+
for hunk in re.split(r"(?m)^@@.*@@.*$", text)[1:]:
|
|
73
|
+
lines = hunk.splitlines()
|
|
74
|
+
if not any(n in ln for ln in lines for n in needles):
|
|
75
|
+
continue
|
|
76
|
+
for ln in lines:
|
|
77
|
+
if ln[:1] in ("+", "-") and not ln.startswith(("+++", "---")):
|
|
78
|
+
out.append(ln[:220])
|
|
79
|
+
if len(out) >= limit:
|
|
80
|
+
return out
|
|
81
|
+
return out
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _cmp(eco: str, a: Optional[str], b: Optional[str]) -> Optional[int]:
|
|
85
|
+
if not a or not b:
|
|
86
|
+
return None
|
|
87
|
+
try:
|
|
88
|
+
return compare(eco, a, b)
|
|
89
|
+
except VersionError:
|
|
90
|
+
return None
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def detect_lockfile_changes(repo: Path, head: str = "HEAD", baseline: str | None = None, commits: int = 1,
|
|
94
|
+
scan_timestamp: str = "") -> dict[str, Any]:
|
|
95
|
+
"""Analyse ``commits`` most recent commits ending at ``head``. ``baseline`` applies to the first commit only."""
|
|
96
|
+
repo = Path(repo)
|
|
97
|
+
result: dict[str, Any] = {"changes": [], "findings": [], "comparisons": [], "limitations": [], "head": None,
|
|
98
|
+
"shallow": False, "files_examined": 0}
|
|
99
|
+
try:
|
|
100
|
+
head_sha = gm.run_git(["rev-parse", "--verify", head + "^{commit}"], cwd=repo).stdout.strip()
|
|
101
|
+
except gm.GitError as e:
|
|
102
|
+
result["limitations"].append(f"Selected revision could not be resolved: {e}")
|
|
103
|
+
return result
|
|
104
|
+
result["head"] = head_sha
|
|
105
|
+
result["shallow"] = gm.is_shallow(repo)
|
|
106
|
+
shas = gm.recent_commits(repo, max(1, commits), head_sha)
|
|
107
|
+
all_changes: list[LockfileChange] = []
|
|
108
|
+
for i, sha in enumerate(shas):
|
|
109
|
+
explicit = baseline if (i == 0 and baseline) else None
|
|
110
|
+
if explicit:
|
|
111
|
+
try:
|
|
112
|
+
base = gm.run_git(["rev-parse", "--verify", explicit + "^{commit}"], cwd=repo).stdout.strip()
|
|
113
|
+
mode = "explicit"
|
|
114
|
+
except gm.GitError:
|
|
115
|
+
result["limitations"].append(f"Baseline '{explicit}' was not found in the available history.")
|
|
116
|
+
all_changes.append(_insufficient(sha, explicit, "explicit", repo, f"baseline '{explicit}' not found in the available (possibly shallow) history", scan_timestamp))
|
|
117
|
+
result["comparisons"].append({"commit": sha, "baseline": None, "mode": "explicit", "status": "insufficient_baseline"})
|
|
118
|
+
continue
|
|
119
|
+
else:
|
|
120
|
+
base, mode = gm.parent_sha(repo, sha), "parent"
|
|
121
|
+
if not base:
|
|
122
|
+
why = ("shallow clone boundary: the parent commit is not available locally" if result["shallow"]
|
|
123
|
+
else "root commit has no parent to compare against")
|
|
124
|
+
result["limitations"].append(f"Commit {sha[:10]}: {why}.")
|
|
125
|
+
all_changes.append(_insufficient(sha, "(none)", "parent", repo, why, scan_timestamp))
|
|
126
|
+
result["comparisons"].append({"commit": sha, "baseline": None, "mode": mode, "status": "insufficient_baseline", "reason": why})
|
|
127
|
+
continue
|
|
128
|
+
all_changes.extend(_compare_commits(repo, base, sha, mode, scan_timestamp, result))
|
|
129
|
+
result["changes"] = [c.model_dump() for c in all_changes]
|
|
130
|
+
flagged = [c for c in all_changes if c.classification != "normal_update"]
|
|
131
|
+
for n, c in enumerate(flagged, 1):
|
|
132
|
+
c.finding_id = f"LOCK-{n:03d}"
|
|
133
|
+
for n, c in enumerate(all_changes, 1):
|
|
134
|
+
if not c.finding_id:
|
|
135
|
+
c.finding_id = f"CHG-{n:03d}"
|
|
136
|
+
result["changes"] = [c.model_dump() for c in all_changes]
|
|
137
|
+
result["findings"] = [c.model_dump() for c in flagged]
|
|
138
|
+
result["summary"] = {
|
|
139
|
+
"commits_analysed": len(shas), "total_changes": len(all_changes),
|
|
140
|
+
"normal_update": sum(c.classification == "normal_update" for c in all_changes),
|
|
141
|
+
"unexplained_change": sum(c.classification == "unexplained_change" for c in all_changes),
|
|
142
|
+
"potentially_suspicious": sum(c.classification == "potentially_suspicious" for c in all_changes),
|
|
143
|
+
"insufficient_baseline": sum(c.classification == "insufficient_baseline" for c in all_changes),
|
|
144
|
+
}
|
|
145
|
+
return result
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _insufficient(sha, base, mode, repo, why, ts) -> LockfileChange:
|
|
149
|
+
return LockfileChange(commit=sha, baseline=base, baseline_mode=mode, commit_info=gm.commit_info(repo, sha), file="(n/a)",
|
|
150
|
+
ecosystem="n/a", package_name="(no comparison possible)", change_type="unparseable",
|
|
151
|
+
classification="insufficient_baseline", reasons=[f"No valid comparison baseline: {why}. No result was inferred."],
|
|
152
|
+
scan_timestamp=ts)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _compare_commits(repo: Path, base: str, sha: str, mode: str, ts: str, result: dict) -> list[LockfileChange]:
|
|
156
|
+
changed = gm.changed_files(repo, base, sha)
|
|
157
|
+
info = gm.commit_info(repo, sha)
|
|
158
|
+
lock_changes = [(st, p) for st, p in changed if _is_lockfile(p.rsplit("/", 1)[-1])]
|
|
159
|
+
manifest_changed = [p for st, p in changed if _is_manifest(p.rsplit("/", 1)[-1])]
|
|
160
|
+
result["files_examined"] += len(lock_changes)
|
|
161
|
+
result["comparisons"].append({"commit": sha, "baseline": base, "mode": mode, "status": "compared",
|
|
162
|
+
"lockfiles_changed": [p for _, p in lock_changes], "manifests_changed": manifest_changed,
|
|
163
|
+
"commit_info": info})
|
|
164
|
+
out: list[LockfileChange] = []
|
|
165
|
+
|
|
166
|
+
def mk(**kw) -> LockfileChange:
|
|
167
|
+
return LockfileChange(commit=sha, baseline=base, baseline_mode=mode, commit_info=info, scan_timestamp=ts, **kw)
|
|
168
|
+
|
|
169
|
+
for status, path in lock_changes:
|
|
170
|
+
name = path.rsplit("/", 1)[-1]
|
|
171
|
+
folder = path.rsplit("/", 1)[0] if "/" in path else "."
|
|
172
|
+
eco = (MANIFEST_FILES.get(name) or ("", "PyPI" if name.startswith("requirements") else "unknown"))[1]
|
|
173
|
+
same_dir_manifests = [m for m in manifest_changed if (m.rsplit("/", 1)[0] if "/" in m else ".") == folder]
|
|
174
|
+
if parser_for(name) is None:
|
|
175
|
+
continue
|
|
176
|
+
if status == "D":
|
|
177
|
+
out.append(mk(file=path, ecosystem=eco, package_name="(entire lockfile)", change_type="lockfile_removed",
|
|
178
|
+
classification="unexplained_change", signals=["lockfile_removed"], manifest_changed=bool(same_dir_manifests),
|
|
179
|
+
manifest_files_changed=same_dir_manifests,
|
|
180
|
+
reasons=["The lockfile was deleted. Without it, resolved versions and integrity hashes are no longer pinned; "
|
|
181
|
+
"this can be intentional (tooling change) but should be confirmed."], evidence_strength="medium"))
|
|
182
|
+
continue
|
|
183
|
+
new_txt = gm.show_file(repo, sha, path)
|
|
184
|
+
old_txt = gm.show_file(repo, base, path) if status != "A" else None
|
|
185
|
+
try:
|
|
186
|
+
new = parse_text(name, new_txt or "", path, folder, _sibling_texts(repo, sha, path)) if new_txt is not None else []
|
|
187
|
+
old = parse_text(name, old_txt, path, folder, _sibling_texts(repo, base, path)) if old_txt is not None else []
|
|
188
|
+
except Exception as e:
|
|
189
|
+
out.append(mk(file=path, ecosystem=eco, package_name="(lockfile)", change_type="unparseable",
|
|
190
|
+
classification="insufficient_baseline", reasons=[f"Lockfile could not be parsed on one side of the comparison ({type(e).__name__}); no result inferred."]))
|
|
191
|
+
continue
|
|
192
|
+
if status == "A":
|
|
193
|
+
out.append(mk(file=path, ecosystem=eco, package_name="(entire lockfile)", change_type="lockfile_added",
|
|
194
|
+
classification="normal_update", signals=["lockfile_added"], manifest_changed=bool(same_dir_manifests),
|
|
195
|
+
manifest_files_changed=same_dir_manifests,
|
|
196
|
+
reasons=[f"A new lockfile with {len(new)} entries was added; entries are checked below for non-registry sources."]))
|
|
197
|
+
oi, ni = _index(old), _index(new)
|
|
198
|
+
if status == "A": # a brand-new lockfile: only report entries with non-registry sources, not every package
|
|
199
|
+
ni = {k: v for k, v in ni.items() if any(d.source_type in ("git", "url", "path") for d in v)}
|
|
200
|
+
changed_names: set[str] = set()
|
|
201
|
+
records: list[dict] = []
|
|
202
|
+
for key in sorted(set(oi) | set(ni)):
|
|
203
|
+
o_list, n_list = oi.get(key, []), ni.get(key, [])
|
|
204
|
+
o_vers = {d.version for d in o_list}
|
|
205
|
+
n_vers = {d.version for d in n_list}
|
|
206
|
+
if o_list and n_list and o_vers == n_vers:
|
|
207
|
+
# same versions: look at integrity / source drift
|
|
208
|
+
for nd in n_list:
|
|
209
|
+
od = next((d for d in o_list if d.version == nd.version), None)
|
|
210
|
+
if not od:
|
|
211
|
+
continue
|
|
212
|
+
if od.integrity and nd.integrity and od.integrity != nd.integrity:
|
|
213
|
+
records.append({"key": key, "type": "integrity_changed", "old": od, "new": nd})
|
|
214
|
+
elif od.integrity and not nd.integrity:
|
|
215
|
+
records.append({"key": key, "type": "integrity_removed", "old": od, "new": nd})
|
|
216
|
+
elif (od.source_type, host_of(od.resolved)) != (nd.source_type, host_of(nd.resolved)) and (od.resolved or nd.resolved):
|
|
217
|
+
records.append({"key": key, "type": "source_changed", "old": od, "new": nd})
|
|
218
|
+
continue
|
|
219
|
+
if not o_list:
|
|
220
|
+
records.append({"key": key, "type": "added", "old": None, "new": n_list[0], "all_new": n_list})
|
|
221
|
+
elif not n_list:
|
|
222
|
+
records.append({"key": key, "type": "removed", "old": o_list[0], "new": None})
|
|
223
|
+
else:
|
|
224
|
+
records.append({"key": key, "type": "version_changed", "old": o_list[0], "new": n_list[0],
|
|
225
|
+
"old_versions": sorted(v or "" for v in o_vers), "new_versions": sorted(v or "" for v in n_vers)})
|
|
226
|
+
changed_names.add(key[1])
|
|
227
|
+
# packages that gained/changed entries -> candidates for "explained by cascade"
|
|
228
|
+
cascade_requires = {r for d in new if normalize_name(d.ecosystem, d.name) in changed_names for r in d.requires}
|
|
229
|
+
direct_changed = [r for r in records if r["new"] is not None and r["new"].direct and r["type"] in ("added", "version_changed")]
|
|
230
|
+
for r in records[:MAX_CHANGES_PER_FILE]:
|
|
231
|
+
eco_k, nm = r["key"]
|
|
232
|
+
od, nd = r["old"], r["new"]
|
|
233
|
+
display = (nd or od).name
|
|
234
|
+
signals: list[str] = []
|
|
235
|
+
reasons: list[str] = []
|
|
236
|
+
suspicious = False
|
|
237
|
+
unexplained = False
|
|
238
|
+
manifest_mentions = False
|
|
239
|
+
if same_dir_manifests:
|
|
240
|
+
for m in same_dir_manifests:
|
|
241
|
+
mt = gm.diff_text(repo, base, sha, m)
|
|
242
|
+
if display.lower() in mt.lower():
|
|
243
|
+
manifest_mentions = True
|
|
244
|
+
break
|
|
245
|
+
ctype = r["type"]
|
|
246
|
+
if ctype == "integrity_changed":
|
|
247
|
+
suspicious = True
|
|
248
|
+
signals.append("integrity_changed_same_version")
|
|
249
|
+
reasons.append(f"The integrity hash of {display}@{nd.version} changed although the version did not "
|
|
250
|
+
f"({_short(od.integrity)} -> {_short(nd.integrity)}). A republished or tampered artifact looks like this; "
|
|
251
|
+
"registry re-publishing and lockfile format migrations can also cause it.")
|
|
252
|
+
elif ctype == "integrity_removed":
|
|
253
|
+
suspicious = True
|
|
254
|
+
signals.append("integrity_removed")
|
|
255
|
+
reasons.append(f"{display}@{nd.version} previously had an integrity hash; the new lockfile has none, which weakens tamper detection.")
|
|
256
|
+
elif ctype == "source_changed":
|
|
257
|
+
suspicious = True
|
|
258
|
+
signals.append("source_changed")
|
|
259
|
+
reasons.append(f"The resolved source of {display}@{nd.version} changed ({od.source_type}:{host_of(od.resolved)} -> {nd.source_type}:{host_of(nd.resolved)}).")
|
|
260
|
+
if nd is not None and ctype in ("added", "version_changed") and nd.source_type in ("git", "url", "path"):
|
|
261
|
+
if not (od is not None and od.source_type == nd.source_type and host_of(od.resolved) == host_of(nd.resolved)):
|
|
262
|
+
suspicious = True
|
|
263
|
+
signals.append(f"non_registry_source_{nd.source_type}")
|
|
264
|
+
reasons.append(f"{display} is resolved from a non-registry {nd.source_type} source ({_short(nd.resolved, 80)}) instead of the package registry.")
|
|
265
|
+
if (od is not None and nd is not None and ctype == "version_changed" and od.source_type == "registry" and nd.source_type == "registry"
|
|
266
|
+
and host_of(od.resolved) and host_of(nd.resolved) and host_of(od.resolved) != host_of(nd.resolved)):
|
|
267
|
+
suspicious = True
|
|
268
|
+
signals.append("registry_host_changed")
|
|
269
|
+
reasons.append(f"The registry host changed from {host_of(od.resolved)} to {host_of(nd.resolved)}.")
|
|
270
|
+
if ctype == "version_changed":
|
|
271
|
+
c = _cmp(eco_k, nd.version, od.version)
|
|
272
|
+
if c is not None and c < 0:
|
|
273
|
+
signals.append("downgrade")
|
|
274
|
+
reasons.append(f"Version moved backwards ({od.version} -> {nd.version}).")
|
|
275
|
+
if not manifest_mentions:
|
|
276
|
+
unexplained = True
|
|
277
|
+
elif c is not None and c > 0:
|
|
278
|
+
reasons.append(f"Version upgraded ({od.version} -> {nd.version}).")
|
|
279
|
+
else:
|
|
280
|
+
reasons.append(f"Version set changed ({', '.join(r.get('old_versions', []))} -> {', '.join(r.get('new_versions', []))}).")
|
|
281
|
+
elif ctype == "added":
|
|
282
|
+
reasons.append(f"New package {display}@{nd.version} entered the lockfile.")
|
|
283
|
+
elif ctype == "removed":
|
|
284
|
+
reasons.append(f"{display}@{od.version} was removed from the lockfile.")
|
|
285
|
+
# explanation logic (only matters if nothing suspicious was found)
|
|
286
|
+
if not suspicious:
|
|
287
|
+
is_direct = bool((nd and nd.direct) or (od and od.direct))
|
|
288
|
+
if manifest_mentions:
|
|
289
|
+
reasons.append("The same commit also modifies a manifest that mentions this package, which explains the change.")
|
|
290
|
+
elif ctype in ("added", "version_changed") and is_direct and not same_dir_manifests:
|
|
291
|
+
unexplained = True
|
|
292
|
+
signals.append("direct_dependency_changed_without_manifest_change")
|
|
293
|
+
reasons.append("A direct dependency changed in the lockfile but no manifest in the same directory changed in this commit "
|
|
294
|
+
"(possible `update`/`audit fix` run; verify the update was intended).")
|
|
295
|
+
elif ctype == "added" and not is_direct and nm not in cascade_requires and not same_dir_manifests and not direct_changed:
|
|
296
|
+
unexplained = True
|
|
297
|
+
signals.append("new_package_without_dependent")
|
|
298
|
+
reasons.append("A new package appeared with no changed parent requiring it and no manifest change.")
|
|
299
|
+
elif ctype in ("added", "version_changed", "removed"):
|
|
300
|
+
reasons.append("Consistent with a normal dependency update/cascade (transitive change alongside other dependency changes).")
|
|
301
|
+
cls = "potentially_suspicious" if suspicious else "unexplained_change" if unexplained else "normal_update"
|
|
302
|
+
strength = ("high" if any(s in signals for s in ("integrity_changed_same_version", "non_registry_source_git", "non_registry_source_url")) and not manifest_mentions
|
|
303
|
+
else "medium" if suspicious else "low")
|
|
304
|
+
sev = {"potentially_suspicious": "HIGH" if strength == "high" else "MEDIUM", "unexplained_change": "LOW"}.get(cls)
|
|
305
|
+
needles = [display, (nd.version if nd else None) or "", (od.version if od else None) or ""]
|
|
306
|
+
out.append(mk(file=path, ecosystem=eco_k, package_name=display, change_type=ctype, previous=_snap(od), new=_snap(nd),
|
|
307
|
+
manifest_changed=bool(same_dir_manifests), manifest_files_changed=same_dir_manifests, classification=cls,
|
|
308
|
+
signals=signals, reasons=reasons, evidence_strength=strength,
|
|
309
|
+
diff_excerpt=_diff_excerpt(repo, base, sha, path, [display]), severity=sev))
|
|
310
|
+
if len(records) > MAX_CHANGES_PER_FILE:
|
|
311
|
+
result["limitations"].append(f"{path}: {len(records) - MAX_CHANGES_PER_FILE} further changes omitted (limit {MAX_CHANGES_PER_FILE}).")
|
|
312
|
+
return out
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def _short(s: Optional[str], n: int = 28) -> str:
|
|
316
|
+
return "none" if not s else (s if len(s) <= n else s[:n] + "...")
|