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,298 @@
|
|
|
1
|
+
"""Typosquatting detector: ecosystem-aware name similarity (RapidFuzz) corroborated by registry metadata.
|
|
2
|
+
|
|
3
|
+
A similarity score is a *signal*. Findings are always classified ``suspicious_name_similarity`` and carry the evidence,
|
|
4
|
+
caveats and the reference set used. Well-established packages (by registry age + downloads) are suppressed.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import re
|
|
9
|
+
import time
|
|
10
|
+
from collections import defaultdict
|
|
11
|
+
from datetime import datetime, timezone
|
|
12
|
+
from typing import Any, Optional
|
|
13
|
+
|
|
14
|
+
from rapidfuzz.distance import DamerauLevenshtein
|
|
15
|
+
|
|
16
|
+
from core.http import HttpClient, NotFound, SourceUnavailable
|
|
17
|
+
from core.models import Component
|
|
18
|
+
from sbom.package_extractors.common import normalize_name
|
|
19
|
+
from storage.cache import Cache
|
|
20
|
+
from suspicious_changes.popular_packages import POPULAR, REFERENCE_VERSION, TRUSTED_NPM_SCOPES
|
|
21
|
+
from suspicious_changes.suspicious_models import TyposquatFinding
|
|
22
|
+
|
|
23
|
+
HOMOGLYPHS = [("rn", "m"), ("vv", "w"), ("0", "o"), ("1", "l"), ("l", "i"), ("5", "s")]
|
|
24
|
+
AFFIXES = ("js", "-js", ".js", "py", "-py", "python", "node", "-node", "nodejs", "-nodejs", "-official", "-lib", "-dev", "-sdk", "-api")
|
|
25
|
+
REGISTRY_TTL = 24 * 3600
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _strip_seps(s: str) -> str:
|
|
29
|
+
return re.sub(r"[-_.]+", "", s)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def candidate_matches(eco: str, name: str, refs: list[str]) -> list[dict]:
|
|
33
|
+
"""Return similarity candidates for ``name`` against reference names of the same ecosystem."""
|
|
34
|
+
n = normalize_name(eco, name)
|
|
35
|
+
out = []
|
|
36
|
+
popular_set = {normalize_name(eco, r) for r in refs}
|
|
37
|
+
|
|
38
|
+
for ref in refs:
|
|
39
|
+
r = normalize_name(eco, ref)
|
|
40
|
+
if n == r:
|
|
41
|
+
continue
|
|
42
|
+
if eco == "npm" and n.startswith("@") != r.startswith("@"):
|
|
43
|
+
continue
|
|
44
|
+
dist = DamerauLevenshtein.distance(n, r)
|
|
45
|
+
longest = max(len(n), len(r))
|
|
46
|
+
sim = round((1 - dist / longest) * 100, 1)
|
|
47
|
+
techniques: list[str] = []
|
|
48
|
+
base = 0
|
|
49
|
+
is_convention = False
|
|
50
|
+
convention_type = None
|
|
51
|
+
is_deceptive = False
|
|
52
|
+
|
|
53
|
+
# 1. Version fork convention (e.g. through vs through2, async vs async2)
|
|
54
|
+
if re.match(r"^" + re.escape(r) + r"\d+$", n) or re.match(r"^" + re.escape(n) + r"\d+$", r):
|
|
55
|
+
techniques.append("version suffix convention (numeric fork)")
|
|
56
|
+
is_convention = True
|
|
57
|
+
convention_type = "version_fork"
|
|
58
|
+
base += 0
|
|
59
|
+
|
|
60
|
+
# 2. Separator normalization (e.g. object-assign vs object.assign)
|
|
61
|
+
elif _strip_seps(n) == _strip_seps(r):
|
|
62
|
+
techniques.append("separator variant")
|
|
63
|
+
is_convention = True
|
|
64
|
+
convention_type = "separator_variant"
|
|
65
|
+
base += 1
|
|
66
|
+
|
|
67
|
+
# 3. Implementation / runtime affix convention (e.g. bcrypt-nodejs vs bcrypt, sha1-js vs sha1)
|
|
68
|
+
elif any(
|
|
69
|
+
n == r + af or n == af.strip("-.") + "-" + r or n == f"{r}-{clean_af}" or n == f"{clean_af}-{r}"
|
|
70
|
+
for af in AFFIXES for clean_af in [af.strip("-.")]
|
|
71
|
+
):
|
|
72
|
+
matched_af = next(
|
|
73
|
+
clean_af for af in AFFIXES for clean_af in [af.strip("-.")]
|
|
74
|
+
if n == r + af or n == af.strip("-.") + "-" + r or n == f"{r}-{clean_af}" or n == f"{clean_af}-{r}"
|
|
75
|
+
)
|
|
76
|
+
techniques.append(f"implementation affix ({matched_af})")
|
|
77
|
+
is_convention = True
|
|
78
|
+
convention_type = "implementation_affix"
|
|
79
|
+
base += 1
|
|
80
|
+
|
|
81
|
+
# 4. Comparative companion suffix (e.g. safe-buffer vs safer-buffer)
|
|
82
|
+
elif (n.startswith("safe") and r.startswith("safer")) or (n.startswith("safer") and r.startswith("safe")):
|
|
83
|
+
if n[5:] == r[4:] or n[4:] == r[5:]:
|
|
84
|
+
techniques.append("companion morphological variant")
|
|
85
|
+
is_convention = True
|
|
86
|
+
convention_type = "companion_variant"
|
|
87
|
+
base += 1
|
|
88
|
+
|
|
89
|
+
# 5. Deceptive techniques (homoglyphs, transpositions, omissions)
|
|
90
|
+
else:
|
|
91
|
+
for a, b in HOMOGLYPHS:
|
|
92
|
+
if len(n) >= 4 and n.replace(a, b) == r and a in n:
|
|
93
|
+
techniques.append(f"look-alike characters ({a}->{b})")
|
|
94
|
+
base += 3
|
|
95
|
+
is_deceptive = True
|
|
96
|
+
break
|
|
97
|
+
|
|
98
|
+
if dist == 1 and len(r) >= 5:
|
|
99
|
+
if DamerauLevenshtein.distance(n, r) == 1 and sorted(n) == sorted(r):
|
|
100
|
+
techniques.append("character transposition")
|
|
101
|
+
base += 3
|
|
102
|
+
is_deceptive = True
|
|
103
|
+
elif len(n) == len(r) + 1 and any(n[:i] + n[i + 1:] == r for i in range(len(n))):
|
|
104
|
+
techniques.append("extra character")
|
|
105
|
+
if any(n[i] == n[i - 1] and n[:i] + n[i + 1:] == r for i in range(1, len(n))):
|
|
106
|
+
techniques.append("repeated character")
|
|
107
|
+
base += 3
|
|
108
|
+
is_deceptive = True
|
|
109
|
+
elif len(n) == len(r) - 1:
|
|
110
|
+
techniques.append("missing character")
|
|
111
|
+
base += 3
|
|
112
|
+
is_deceptive = True
|
|
113
|
+
else:
|
|
114
|
+
techniques.append("single-edit substitution")
|
|
115
|
+
base += 2
|
|
116
|
+
is_deceptive = True
|
|
117
|
+
elif dist == 2 and len(r) >= 9 and sim >= 85:
|
|
118
|
+
techniques.append("two edits on a long name")
|
|
119
|
+
base += 2
|
|
120
|
+
is_deceptive = True
|
|
121
|
+
|
|
122
|
+
# Check if both candidate and reference are established in popular reference list
|
|
123
|
+
both_in_reference = (n in popular_set) and (r in popular_set)
|
|
124
|
+
if both_in_reference and is_convention:
|
|
125
|
+
techniques.append("established companion package in reference catalog")
|
|
126
|
+
|
|
127
|
+
if techniques:
|
|
128
|
+
out.append({
|
|
129
|
+
"ref": ref,
|
|
130
|
+
"distance": dist,
|
|
131
|
+
"similarity": sim,
|
|
132
|
+
"techniques": techniques,
|
|
133
|
+
"points": base,
|
|
134
|
+
"is_ecosystem_convention": is_convention,
|
|
135
|
+
"convention_type": convention_type,
|
|
136
|
+
"is_deceptive": is_deceptive,
|
|
137
|
+
"both_in_reference": both_in_reference,
|
|
138
|
+
})
|
|
139
|
+
out.sort(key=lambda c: (-c["points"], -c["similarity"]))
|
|
140
|
+
return out[:1] # best match only
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _age_days(iso: Optional[str]) -> Optional[int]:
|
|
144
|
+
if not iso:
|
|
145
|
+
return None
|
|
146
|
+
try:
|
|
147
|
+
dt = datetime.fromisoformat(iso.replace("Z", "+00:00"))
|
|
148
|
+
if dt.tzinfo is None:
|
|
149
|
+
dt = dt.replace(tzinfo=timezone.utc)
|
|
150
|
+
return max(0, (datetime.now(timezone.utc) - dt).days)
|
|
151
|
+
except ValueError:
|
|
152
|
+
return None
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def fetch_registry_signals(http: HttpClient, cache: Cache | None, eco: str, name: str) -> dict[str, Any]:
|
|
156
|
+
key = f"{eco}:{name}"
|
|
157
|
+
hit = cache.get("registry_signals", key, ttl=REGISTRY_TTL) if cache else None
|
|
158
|
+
if hit is not None:
|
|
159
|
+
return hit
|
|
160
|
+
sig: dict[str, Any] = {"checked": True, "exists": None, "age_days": None, "monthly_downloads": None,
|
|
161
|
+
"version_count": None, "source": None}
|
|
162
|
+
try:
|
|
163
|
+
if eco == "npm":
|
|
164
|
+
sig["source"] = f"https://registry.npmjs.org/{name}"
|
|
165
|
+
d = http.get_json(sig["source"])
|
|
166
|
+
sig["exists"] = True
|
|
167
|
+
sig["age_days"] = _age_days((d.get("time") or {}).get("created"))
|
|
168
|
+
sig["version_count"] = len(d.get("versions") or {})
|
|
169
|
+
try:
|
|
170
|
+
dl = http.get_json(f"https://api.npmjs.org/downloads/point/last-month/{name}")
|
|
171
|
+
sig["monthly_downloads"] = dl.get("downloads")
|
|
172
|
+
except (NotFound, SourceUnavailable):
|
|
173
|
+
pass
|
|
174
|
+
elif eco == "PyPI":
|
|
175
|
+
sig["source"] = f"https://pypi.org/pypi/{name}/json"
|
|
176
|
+
d = http.get_json(sig["source"])
|
|
177
|
+
sig["exists"] = True
|
|
178
|
+
times = [f["upload_time_iso_8601"] for files in (d.get("releases") or {}).values() for f in files if f.get("upload_time_iso_8601")]
|
|
179
|
+
sig["age_days"] = _age_days(min(times)) if times else None
|
|
180
|
+
sig["version_count"] = len(d.get("releases") or {})
|
|
181
|
+
else:
|
|
182
|
+
sig["checked"] = False
|
|
183
|
+
sig["note"] = f"no registry integration for {eco}"
|
|
184
|
+
except NotFound:
|
|
185
|
+
sig["exists"] = False
|
|
186
|
+
except SourceUnavailable as e:
|
|
187
|
+
sig = {"checked": False, "error": str(e)[:120], "source": sig.get("source")}
|
|
188
|
+
return sig # do not cache failures
|
|
189
|
+
if cache:
|
|
190
|
+
cache.set("registry_signals", key, sig)
|
|
191
|
+
return sig
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _score_registry(sig: dict) -> tuple[int, list[str], bool]:
|
|
195
|
+
pts, ev, established = 0, [], False
|
|
196
|
+
if not sig.get("checked"):
|
|
197
|
+
return 0, ["registry metadata unavailable; assessment is name-similarity only"], False
|
|
198
|
+
if sig.get("exists") is False:
|
|
199
|
+
ev.append("package name was not found in the public registry (could be a private/internal package or a removed one)")
|
|
200
|
+
return 1, ev, False
|
|
201
|
+
age, dl, vc = sig.get("age_days"), sig.get("monthly_downloads"), sig.get("version_count")
|
|
202
|
+
if age is not None:
|
|
203
|
+
ev.append(f"first published ~{age} days ago")
|
|
204
|
+
if age < 90:
|
|
205
|
+
pts += 2
|
|
206
|
+
elif age > 730:
|
|
207
|
+
pts -= 1
|
|
208
|
+
if dl is not None:
|
|
209
|
+
ev.append(f"{dl:,} downloads in the last month")
|
|
210
|
+
if dl < 1000:
|
|
211
|
+
pts += 2
|
|
212
|
+
elif dl >= 50_000:
|
|
213
|
+
pts -= 3
|
|
214
|
+
if vc is not None:
|
|
215
|
+
ev.append(f"{vc} published versions")
|
|
216
|
+
if age is not None and dl is not None and age > 365 and dl >= 20_000:
|
|
217
|
+
established = True
|
|
218
|
+
return pts, ev, established
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def detect_typosquatting(components: list[Component], http: HttpClient | None = None, cache: Cache | None = None,
|
|
222
|
+
dependency_info: dict[str, dict] | None = None, scan_timestamp: str = "",
|
|
223
|
+
max_registry_checks: int = 30, min_points: int = 3) -> dict[str, Any]:
|
|
224
|
+
"""Return {findings: [...], suppressed: [...], stats: {...}}.
|
|
225
|
+
|
|
226
|
+
``dependency_info`` maps component bom-ref -> {"type": direct|transitive.., "roots": [...]} for context.
|
|
227
|
+
"""
|
|
228
|
+
dependency_info = dependency_info or {}
|
|
229
|
+
groups: dict[tuple[str, str], list[Component]] = defaultdict(list)
|
|
230
|
+
for c in components:
|
|
231
|
+
if c.type != "file" and not c.is_self and c.ecosystem in POPULAR and c.name:
|
|
232
|
+
groups[(c.ecosystem, c.name)].append(c)
|
|
233
|
+
popular_sets = {e: {normalize_name(e, n) for n in names} for e, names in POPULAR.items()}
|
|
234
|
+
stats = {"unique_packages_checked": len(groups), "reference_version": REFERENCE_VERSION, "candidates": 0,
|
|
235
|
+
"registry_checks": 0, "registry_unavailable": 0, "suppressed_established": 0, "below_threshold": 0}
|
|
236
|
+
findings: list[TyposquatFinding] = []
|
|
237
|
+
suppressed: list[dict] = []
|
|
238
|
+
cands: list[tuple[tuple[str, str], dict]] = []
|
|
239
|
+
for (eco, name), comps in groups.items():
|
|
240
|
+
n = normalize_name(eco, name)
|
|
241
|
+
if n in popular_sets[eco]:
|
|
242
|
+
continue # it IS a reference package
|
|
243
|
+
if eco == "npm" and name.startswith("@") and name.split("/")[0] in TRUSTED_NPM_SCOPES:
|
|
244
|
+
continue
|
|
245
|
+
m = candidate_matches(eco, name, POPULAR[eco])
|
|
246
|
+
if m:
|
|
247
|
+
cands.append(((eco, name), m[0]))
|
|
248
|
+
stats["candidates"] = len(cands)
|
|
249
|
+
cands.sort(key=lambda x: -x[1]["points"])
|
|
250
|
+
for i, ((eco, name), m) in enumerate(cands):
|
|
251
|
+
pts = m["points"] + (1 if m["similarity"] >= 90 else 0)
|
|
252
|
+
evidence = [f"name '{name}' is {m['similarity']}% similar to well-known {eco} package '{m['ref']}' "
|
|
253
|
+
f"(edit distance {m['distance']}); techniques: {', '.join(m['techniques'])}"]
|
|
254
|
+
caveats = ["Name similarity does not prove malicious intent; many legitimate packages have similar names."]
|
|
255
|
+
sig: dict[str, Any] = {"checked": False}
|
|
256
|
+
established = False
|
|
257
|
+
if http is not None and i < max_registry_checks:
|
|
258
|
+
sig = fetch_registry_signals(http, cache, eco, name)
|
|
259
|
+
stats["registry_checks"] += 1
|
|
260
|
+
if not sig.get("checked") and sig.get("error"):
|
|
261
|
+
stats["registry_unavailable"] += 1
|
|
262
|
+
rp, rev, established = _score_registry(sig)
|
|
263
|
+
pts += rp
|
|
264
|
+
evidence += rev
|
|
265
|
+
else:
|
|
266
|
+
evidence.append("registry corroboration not performed" + (" (check limit reached)" if http is not None else " (offline mode)"))
|
|
267
|
+
if established:
|
|
268
|
+
stats["suppressed_established"] += 1
|
|
269
|
+
suppressed.append({"package": name, "ecosystem": eco, "similar_to": m["ref"], "reason": "registry shows an established package (age > 1 year, >= 20k monthly downloads)"})
|
|
270
|
+
continue
|
|
271
|
+
if pts < min_points:
|
|
272
|
+
stats["below_threshold"] += 1
|
|
273
|
+
continue
|
|
274
|
+
strength = "high" if pts >= 6 else "medium" if pts >= 4 else "low"
|
|
275
|
+
if not sig.get("checked"):
|
|
276
|
+
strength = "low" # name similarity alone is never more than low-strength evidence
|
|
277
|
+
caveats.append("Uncorroborated: no registry metadata was available, so evidence strength is capped at 'low'.")
|
|
278
|
+
comps = groups[(eco, name)]
|
|
279
|
+
deps = [dependency_info.get(c.bom_ref, {}) for c in comps]
|
|
280
|
+
types = {d.get("type") for d in deps if d.get("type")}
|
|
281
|
+
dtype = "direct" if "direct" in types else "direct_inferred" if "direct_inferred" in types else "transitive" if "transitive" in types else "unknown"
|
|
282
|
+
if dtype == "transitive":
|
|
283
|
+
caveats.append("This package is a transitive dependency; check which parent introduces it.")
|
|
284
|
+
findings.append(TyposquatFinding(
|
|
285
|
+
package_name=name, ecosystem=eco, versions=sorted({c.version for c in comps if c.version}),
|
|
286
|
+
component_refs=[c.bom_ref for c in comps], similar_to=m["ref"], similarity_score=m["similarity"],
|
|
287
|
+
edit_distance=m["distance"], techniques=m["techniques"],
|
|
288
|
+
reference_source=f"curated popular-{eco}-package list ({REFERENCE_VERSION})", evidence=evidence, registry=sig,
|
|
289
|
+
evidence_strength=strength, evidence_points=pts,
|
|
290
|
+
why_flagged=(f"'{name}' closely resembles the popular {eco} package '{m['ref']}' ({', '.join(m['techniques'])})"
|
|
291
|
+
+ (" and registry signals support suspicion." if pts - m["points"] >= 2 else ".")),
|
|
292
|
+
caveats=caveats, dependency_type=dtype,
|
|
293
|
+
roots=sorted({r for d in deps for r in d.get("roots", [])}), services=sorted({c.service_dir or "." for c in comps}),
|
|
294
|
+
scan_timestamp=scan_timestamp))
|
|
295
|
+
findings.sort(key=lambda f: (-f.evidence_points, f.package_name))
|
|
296
|
+
for n, f in enumerate(findings, 1):
|
|
297
|
+
f.finding_id = f"TYPO-{n:03d}"
|
|
298
|
+
return {"findings": findings, "suppressed": suppressed, "stats": stats}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""tools package."""
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"""Built-in read-only tools used by the Investigator (deterministic planner and optional LLM planner alike).
|
|
2
|
+
|
|
3
|
+
Every tool records what it observed as Evidence and returns a compact result containing the evidence id, so conclusions can cite it.
|
|
4
|
+
Nothing here writes to the repository, runs repository code, or reaches the network (EPSS/OSV data was gathered by earlier agents).
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from core.repository_inspector import safe_read_text
|
|
11
|
+
from llm.client import redact
|
|
12
|
+
from reachability.scanners import build_index, package_usage
|
|
13
|
+
from tools.registry import ToolContext, tool
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _finding(ctx: ToolContext, fid: str) -> dict:
|
|
17
|
+
for f in ctx.state.vulns:
|
|
18
|
+
if f["finding_id"] == fid:
|
|
19
|
+
return f
|
|
20
|
+
raise KeyError(f"unknown finding {fid}")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _index(ctx: ToolContext):
|
|
24
|
+
st = ctx.state
|
|
25
|
+
if st.source_index is None:
|
|
26
|
+
st.source_index = build_index(ctx.repo_dir)
|
|
27
|
+
return st.source_index
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@tool("advisory_facts", "Facts about the vulnerability finding: advisory ids, CVSS, KEV, affected-range validation, fixed versions, cross-verification.", {"finding_id": "finding id, e.g. VULN-007"})
|
|
31
|
+
def advisory_facts(ctx: ToolContext, finding_id: str) -> dict:
|
|
32
|
+
f = _finding(ctx, finding_id)
|
|
33
|
+
data = {"ids": f["vulnerability_ids"][:6], "cves": f["cve_ids"][:6], "severity": f["severity"], "cvss": f["cvss_score"], "affected_status": f["affected_status"], "ranges": f["affected_ranges"][:3],
|
|
34
|
+
"fixed_versions": f["fixed_versions"][:4], "kev": f["kev"], "cross_verified": f["cross_verified"]}
|
|
35
|
+
eid = ctx.evidence.add("osv", "osv-client", finding_id, f"{f['primary_id']}: {f['severity'] or 'severity n/a'}, affected={f['affected_status']}, cross_verified={f['cross_verified']}", data,
|
|
36
|
+
source=(f.get("advisory_urls") or [None])[0])
|
|
37
|
+
return {"evidence_id": eid, **data}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@tool("dependency_path", "How the vulnerable package enters the application: direct/transitive, depth, the direct (source) dependency and the path from the service root.", {"finding_id": "finding id"})
|
|
41
|
+
def dependency_path(ctx: ToolContext, finding_id: str) -> dict:
|
|
42
|
+
f = _finding(ctx, finding_id)
|
|
43
|
+
e = (f["exposures"] or [{}])[0]
|
|
44
|
+
path = (e.get("paths") or [[]])[0]
|
|
45
|
+
data = {"relationship": f["dependency_type"], "depth": e.get("depth"), "source_packages": f["source_packages"][:4], "path": path[:10], "roots": f["roots"][:3], "dev_dependency": f["dev_dependency"]}
|
|
46
|
+
eid = ctx.evidence.add("graph", "dependency-graph", finding_id, f"{f['dependency_type']} via {', '.join(f['source_packages'][:2]) or 'itself'}: {' -> '.join(path[:6])}", data)
|
|
47
|
+
return {"evidence_id": eid, **data}
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@tool("find_imports", "Static import evidence: is this package imported by the application's own source code (and where)?", {"package": "package name", "ecosystem": "OSV ecosystem, e.g. npm, PyPI, Maven, Go"})
|
|
51
|
+
def find_imports(ctx: ToolContext, package: str, ecosystem: str) -> dict:
|
|
52
|
+
res = package_usage(_index(ctx), ecosystem, package)
|
|
53
|
+
summary = (f"{package} imported by app code in {res['app_files']} file(s)" if res["status"] == "used_by_app" else f"{package} imported only in tests ({res['test_files']} file(s))" if res["status"] == "used_in_tests_only"
|
|
54
|
+
else f"no import of {package} found in analysed {ecosystem} source" if res["status"] == "not_imported" else f"{package}: reachability unknown ({res.get('reason', '')})")
|
|
55
|
+
eid = ctx.evidence.add("reachability", "import-scanner", f"{ecosystem}:{package}", summary, {k: res.get(k) for k in ("status", "app_files", "test_files", "locations", "files_analysed", "confidence", "import_density", "import_ratio", "influence_tier")},
|
|
56
|
+
source=(f"{res['locations'][0]['path']}:{res['locations'][0]['line']}" if res.get("locations") else None), verified=res["status"] != "unknown")
|
|
57
|
+
return {"evidence_id": eid, **res}
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@tool("package_meta", "Fused metadata of an installed package: licence, scope, publish date, install script, deprecation, digest verdict, attestations.", {"package": "package name", "version": "installed version"})
|
|
61
|
+
def package_meta(ctx: ToolContext, package: str, version: str) -> dict:
|
|
62
|
+
for c in ctx.state.components:
|
|
63
|
+
if c.name == package and c.version == version and not c.is_self:
|
|
64
|
+
data = {"licenses": c.licenses[:3], "scope": c.scope, "published_at": c.published_at, "install_script": c.install_script, "deprecated": c.deprecated,
|
|
65
|
+
"integrity": c.integrity.get("status"), "attestations": c.integrity.get("attestations"), "resolution": c.resolution}
|
|
66
|
+
eid = ctx.evidence.add("registry", "metadata-fusion", f"{package}@{version}", f"scope={c.scope}, published={c.published_at}, install_script={c.install_script}, integrity={c.integrity.get('status')}", data)
|
|
67
|
+
return {"evidence_id": eid, **data}
|
|
68
|
+
return {"error": f"{package}@{version} not in the inventory"}
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@tool("epss", "EPSS exploitation probability (FIRST.org) for a CVE, if it was retrieved.", {"cve": "CVE id"})
|
|
72
|
+
def epss(ctx: ToolContext, cve: str) -> dict:
|
|
73
|
+
r = ctx.state.epss.get(cve)
|
|
74
|
+
if not r:
|
|
75
|
+
return {"cve": cve, "available": False}
|
|
76
|
+
eid = ctx.evidence.add("epss", "first.org-epss", cve, f"EPSS {r['epss']:.1%} (percentile {r['percentile']:.1%}) on {r.get('date')}", r, source="https://api.first.org/data/v1/epss")
|
|
77
|
+
return {"evidence_id": eid, "available": True, **r}
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@tool("read_snippet", "Read a few lines around an import found by find_imports (only files already cited as import evidence; secrets redacted).", {"path": "repo-relative path", "line": "line number", "radius": "lines of context, max 5"})
|
|
81
|
+
def read_snippet(ctx: ToolContext, path: str, line: int, radius: int = 3) -> dict:
|
|
82
|
+
allowed = {loc["path"] for e in ctx.evidence._items.values() if e.kind == "reachability" for loc in (e.data.get("locations") or [])}
|
|
83
|
+
if path not in allowed:
|
|
84
|
+
return {"error": "path is not part of any import evidence; only files cited by find_imports can be read"}
|
|
85
|
+
text = safe_read_text(Path(ctx.repo_dir), path, max_bytes=1_000_000)
|
|
86
|
+
if text is None:
|
|
87
|
+
return {"error": "file unreadable"}
|
|
88
|
+
radius = max(0, min(int(radius), 5))
|
|
89
|
+
lines = text.splitlines()
|
|
90
|
+
a, b = max(0, int(line) - 1 - radius), min(len(lines), int(line) + radius)
|
|
91
|
+
snippet = "\n".join(f"{n + 1}: {redact(lines[n])[:160]}" for n in range(a, b))
|
|
92
|
+
eid = ctx.evidence.add("source", "snippet-reader", f"{path}:{line}", f"source lines {a + 1}-{b} of {path}", {"snippet": snippet})
|
|
93
|
+
return {"evidence_id": eid, "snippet": snippet}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""Tool registry: small, typed, READ-ONLY functions that agents (deterministic planner or LLM) may call.
|
|
2
|
+
|
|
3
|
+
A tool receives a ``ToolContext`` (working tree, scan state, evidence store, HTTP client, cache) plus validated keyword arguments, records the
|
|
4
|
+
facts it observed in the evidence store and returns a compact JSON-serialisable result containing the evidence ids. Tools never write to the
|
|
5
|
+
repository, never execute repository code, and never receive secrets (the context exposes none).
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Any, Callable, Optional
|
|
13
|
+
|
|
14
|
+
from evidence.store import EvidenceStore
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass
|
|
18
|
+
class ToolContext:
|
|
19
|
+
repo_dir: Optional[Path]
|
|
20
|
+
evidence: EvidenceStore
|
|
21
|
+
http: Any = None
|
|
22
|
+
cache: Any = None
|
|
23
|
+
state: Any = None # agents.specialists.ScanState (read-only use)
|
|
24
|
+
limits: dict = field(default_factory=lambda: {"max_snippet_lines": 40, "max_files": 4000, "max_bytes": 2_000_000})
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass
|
|
28
|
+
class Tool:
|
|
29
|
+
name: str
|
|
30
|
+
description: str
|
|
31
|
+
params: dict[str, str] # arg name -> short type/meaning
|
|
32
|
+
fn: Callable[..., dict]
|
|
33
|
+
|
|
34
|
+
def schema(self) -> dict:
|
|
35
|
+
return {"name": self.name, "description": self.description, "params": self.params}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
REGISTRY: dict[str, Tool] = {}
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def tool(name: str, description: str, params: Optional[dict[str, str]] = None):
|
|
42
|
+
def deco(fn: Callable[..., dict]):
|
|
43
|
+
REGISTRY[name] = Tool(name, description, params or {}, fn)
|
|
44
|
+
return fn
|
|
45
|
+
return deco
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def catalogue() -> list[dict]:
|
|
49
|
+
return [t.schema() for t in REGISTRY.values()]
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def call(ctx: ToolContext, name: str, args: Optional[dict] = None) -> dict:
|
|
53
|
+
"""Validated invocation: unknown tools/arguments are rejected; failures come back as {"error": ...} (a tool never raises into an agent)."""
|
|
54
|
+
t = REGISTRY.get(name)
|
|
55
|
+
if t is None:
|
|
56
|
+
return {"error": f"unknown tool '{name}'", "available": sorted(REGISTRY)}
|
|
57
|
+
args = dict(args or {})
|
|
58
|
+
extra = set(args) - set(t.params)
|
|
59
|
+
if extra:
|
|
60
|
+
return {"error": f"unexpected argument(s) {sorted(extra)} for {name}", "expected": list(t.params)}
|
|
61
|
+
try:
|
|
62
|
+
out = t.fn(ctx, **args)
|
|
63
|
+
json.dumps(out, default=str)
|
|
64
|
+
return out
|
|
65
|
+
except Exception as e: # noqa: BLE001
|
|
66
|
+
return {"error": f"{type(e).__name__}: {str(e)[:200]}"}
|
|
File without changes
|
|
File without changes
|