polycheck 0.2.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.
- polycheck/__init__.py +19 -0
- polycheck/cli.py +791 -0
- polycheck/config.py +123 -0
- polycheck/detect.py +151 -0
- polycheck/finding.py +131 -0
- polycheck/initializer.py +333 -0
- polycheck/languages/__init__.py +10 -0
- polycheck/mcp_server.py +994 -0
- polycheck/py.typed +0 -0
- polycheck/registry.py +119 -0
- polycheck/reporters/__init__.py +33 -0
- polycheck/reporters/json_reporter.py +58 -0
- polycheck/reporters/markdown_reporter.py +141 -0
- polycheck/reporters/sarif_reporter.py +114 -0
- polycheck/runner.py +279 -0
- polycheck/session.py +134 -0
- polycheck/tools/__init__.py +10 -0
- polycheck/tools/actionlint.py +66 -0
- polycheck/tools/base.py +449 -0
- polycheck/tools/depcheck.py +96 -0
- polycheck/tools/deptry.py +83 -0
- polycheck/tools/eslint.py +89 -0
- polycheck/tools/gitleaks.py +78 -0
- polycheck/tools/hadolint.py +75 -0
- polycheck/tools/knip.py +84 -0
- polycheck/tools/mypy.py +85 -0
- polycheck/tools/npm_audit.py +74 -0
- polycheck/tools/pip_audit.py +132 -0
- polycheck/tools/ruff.py +80 -0
- polycheck/tools/semgrep.py +80 -0
- polycheck/tools/shellcheck.py +80 -0
- polycheck/tools/sonarless.py +238 -0
- polycheck/tools/tsc.py +77 -0
- polycheck/tools/vulture.py +82 -0
- polycheck/verify.py +288 -0
- polycheck/workflows/__init__.py +76 -0
- polycheck-0.2.0.dist-info/METADATA +614 -0
- polycheck-0.2.0.dist-info/RECORD +42 -0
- polycheck-0.2.0.dist-info/WHEEL +5 -0
- polycheck-0.2.0.dist-info/entry_points.txt +2 -0
- polycheck-0.2.0.dist-info/licenses/LICENSE +21 -0
- polycheck-0.2.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
"""eslint — JS/TS linter (with JSON output via --format=json).
|
|
2
|
+
|
|
3
|
+
We treat ESLint findings as LOW severity by default (style). The
|
|
4
|
+
LLM-triage step usually wants to focus on bugs and security, so we
|
|
5
|
+
keep ESLint informational. Users can bump the severity in
|
|
6
|
+
``.polycheck.yml`` if they prefer.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import shutil
|
|
12
|
+
import subprocess
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
from ..finding import Category, Finding, Severity
|
|
16
|
+
from .base import Tool
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class EslintTool(Tool):
|
|
20
|
+
name = "eslint"
|
|
21
|
+
category = Category.LINT
|
|
22
|
+
languages = ["javascript", "typescript"]
|
|
23
|
+
installer = "npm:eslint"
|
|
24
|
+
|
|
25
|
+
def is_applicable(self, repo: Path) -> bool:
|
|
26
|
+
# Any of: eslint.config.* (flat config), .eslintrc.*, or the
|
|
27
|
+
# eslint dep in package.json.
|
|
28
|
+
flat = list(repo.glob("eslint.config.*"))
|
|
29
|
+
old = list(repo.glob(".eslintrc*"))
|
|
30
|
+
pkg = repo / "package.json"
|
|
31
|
+
has_dep = False
|
|
32
|
+
if pkg.exists():
|
|
33
|
+
try:
|
|
34
|
+
import json as _j
|
|
35
|
+
data = _j.loads(pkg.read_text(encoding="utf-8"))
|
|
36
|
+
for k in ("devDependencies", "dependencies"):
|
|
37
|
+
if "eslint" in data.get(k, {}):
|
|
38
|
+
has_dep = True
|
|
39
|
+
except (OSError, ValueError):
|
|
40
|
+
pass
|
|
41
|
+
return bool(flat or old or has_dep)
|
|
42
|
+
|
|
43
|
+
def run(self, repo: Path) -> list[Finding]:
|
|
44
|
+
if shutil.which("eslint") is None and shutil.which("npx") is None:
|
|
45
|
+
return []
|
|
46
|
+
# Prefer the local binary if it exists; fall back to npx (which
|
|
47
|
+
# needs the module name as its first argument).
|
|
48
|
+
if shutil.which("eslint"):
|
|
49
|
+
cmd = ["eslint", "--format=json", "--no-warn-ignored", "."]
|
|
50
|
+
else:
|
|
51
|
+
cmd = ["npx", "eslint", "--format=json", "--no-warn-ignored", "."]
|
|
52
|
+
out = subprocess.run(
|
|
53
|
+
cmd, cwd=repo, capture_output=True, text=True, timeout=300
|
|
54
|
+
)
|
|
55
|
+
if not out.stdout.strip():
|
|
56
|
+
return []
|
|
57
|
+
try:
|
|
58
|
+
data = json.loads(out.stdout)
|
|
59
|
+
except json.JSONDecodeError:
|
|
60
|
+
return []
|
|
61
|
+
|
|
62
|
+
findings: list[Finding] = []
|
|
63
|
+
for file_result in data:
|
|
64
|
+
for msg in file_result.get("messages", []):
|
|
65
|
+
# Map ESLint severity (1=warn, 2=error) to ours.
|
|
66
|
+
severity = {
|
|
67
|
+
1: Severity.LOW,
|
|
68
|
+
2: Severity.MEDIUM,
|
|
69
|
+
}.get(msg.get("severity"), Severity.LOW)
|
|
70
|
+
rule_id = msg.get("ruleId") or "unknown"
|
|
71
|
+
findings.append(
|
|
72
|
+
Finding(
|
|
73
|
+
tool=self.name,
|
|
74
|
+
rule=rule_id,
|
|
75
|
+
severity=severity,
|
|
76
|
+
category=self.category,
|
|
77
|
+
message=msg.get("message", ""),
|
|
78
|
+
file=file_result.get("filePath"),
|
|
79
|
+
line=msg.get("line"),
|
|
80
|
+
column=msg.get("column"),
|
|
81
|
+
fixable=msg.get("fix") is not None,
|
|
82
|
+
fix_command="eslint --fix ." if any(
|
|
83
|
+
m.get("fix") for fr in data for m in fr.get("messages", [])
|
|
84
|
+
) else None,
|
|
85
|
+
doc_url=f"https://eslint.org/docs/rules/{rule_id}" if rule_id != "unknown" else None,
|
|
86
|
+
raw=msg,
|
|
87
|
+
)
|
|
88
|
+
)
|
|
89
|
+
return findings
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"""gitleaks — find secrets in the working tree.
|
|
2
|
+
|
|
3
|
+
We run ``gitleaks detect --no-git`` which scans the working tree only
|
|
4
|
+
(faster, no clone dependency), writing its JSON report to a temp file
|
|
5
|
+
via ``--report-path`` (stdout behavior differs between gitleaks
|
|
6
|
+
versions). gitleaks exits 1 when leaks are found; that's normal.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import shutil
|
|
12
|
+
import subprocess
|
|
13
|
+
import tempfile
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
from ..finding import Category, Finding, Severity
|
|
17
|
+
from .base import Tool
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class GitleaksTool(Tool):
|
|
21
|
+
name = "gitleaks"
|
|
22
|
+
category = Category.SECRETS
|
|
23
|
+
languages = [] # applies to any git repo
|
|
24
|
+
universal = True
|
|
25
|
+
installer = "github-release:gitleaks/gitleaks"
|
|
26
|
+
|
|
27
|
+
def is_applicable(self, repo: Path) -> bool:
|
|
28
|
+
return (repo / ".git").exists() or (repo / ".git").is_dir()
|
|
29
|
+
|
|
30
|
+
def run(self, repo: Path) -> list[Finding]:
|
|
31
|
+
if shutil.which("gitleaks") is None:
|
|
32
|
+
return []
|
|
33
|
+
with tempfile.TemporaryDirectory(prefix="polycheck-gitleaks-") as tmp_name:
|
|
34
|
+
report_path = Path(tmp_name) / "gitleaks-report.json"
|
|
35
|
+
cmd = [
|
|
36
|
+
"gitleaks", "detect",
|
|
37
|
+
"--report-format", "json",
|
|
38
|
+
"--report-path", str(report_path),
|
|
39
|
+
"--no-banner",
|
|
40
|
+
"--no-git",
|
|
41
|
+
"--source", str(repo),
|
|
42
|
+
]
|
|
43
|
+
out = subprocess.run(
|
|
44
|
+
cmd, cwd=repo, capture_output=True, text=True, timeout=300
|
|
45
|
+
)
|
|
46
|
+
# Exit 1 = leaks found, 0 = clean. Anything else is a real
|
|
47
|
+
# failure — surface it so the runner reports an error instead
|
|
48
|
+
# of silently reporting "no findings".
|
|
49
|
+
if out.returncode not in (0, 1):
|
|
50
|
+
detail = (out.stderr or out.stdout).strip()[:200]
|
|
51
|
+
raise RuntimeError(f"gitleaks exited {out.returncode}: {detail}")
|
|
52
|
+
if not report_path.exists():
|
|
53
|
+
return []
|
|
54
|
+
try:
|
|
55
|
+
data = json.loads(report_path.read_text(encoding="utf-8"))
|
|
56
|
+
except (json.JSONDecodeError, OSError):
|
|
57
|
+
return []
|
|
58
|
+
if not isinstance(data, list):
|
|
59
|
+
return []
|
|
60
|
+
|
|
61
|
+
findings: list[Finding] = []
|
|
62
|
+
for item in data:
|
|
63
|
+
findings.append(
|
|
64
|
+
Finding(
|
|
65
|
+
tool=self.name,
|
|
66
|
+
rule=item.get("RuleID", "secret"),
|
|
67
|
+
severity=Severity.CRITICAL, # any secret is critical
|
|
68
|
+
category=Category.SECRETS,
|
|
69
|
+
message=item.get("Description") or item.get("Match", "")[:120],
|
|
70
|
+
file=item.get("File"),
|
|
71
|
+
line=item.get("StartLine"),
|
|
72
|
+
column=item.get("StartColumn"),
|
|
73
|
+
fixable=False,
|
|
74
|
+
doc_url="https://github.com/gitleaks/gitleaks#rules",
|
|
75
|
+
raw=item,
|
|
76
|
+
)
|
|
77
|
+
)
|
|
78
|
+
return findings
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""hadolint — Dockerfile linter.
|
|
2
|
+
|
|
3
|
+
hadolint is a single binary; default output is one finding per line
|
|
4
|
+
in the same gcc-like format as shellcheck.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import re
|
|
9
|
+
import shutil
|
|
10
|
+
import subprocess
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
from ..finding import Category, Finding, Severity
|
|
14
|
+
from .base import Tool
|
|
15
|
+
|
|
16
|
+
_HADOLINT_LINE = re.compile(
|
|
17
|
+
r"^(?P<file>[^:]+):(?P<line>\d+)\s*"
|
|
18
|
+
r"(?P<severity>error|warning|info|style):\s*"
|
|
19
|
+
r"(?P<message>.*?)(?:\s*\[(?P<code>[^\]]+)\])?\s*$"
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class HadolintTool(Tool):
|
|
24
|
+
name = "hadolint"
|
|
25
|
+
category = Category.LINT
|
|
26
|
+
languages = [] # applies to Dockerfiles
|
|
27
|
+
universal = False
|
|
28
|
+
installer = "github-release:hadolint/hadolint"
|
|
29
|
+
|
|
30
|
+
def is_applicable(self, repo: Path) -> bool:
|
|
31
|
+
return any(repo.glob("**/Dockerfile*")) or (repo / "Dockerfile").exists()
|
|
32
|
+
|
|
33
|
+
def run(self, repo: Path) -> list[Finding]:
|
|
34
|
+
if shutil.which("hadolint") is None:
|
|
35
|
+
return []
|
|
36
|
+
# Collect all Dockerfiles; hadolint takes files, not dirs.
|
|
37
|
+
dockerfiles = list(repo.glob("**/Dockerfile*")) + [repo / "Dockerfile"]
|
|
38
|
+
paths = [str(p) for p in dockerfiles if p.is_file()]
|
|
39
|
+
if not paths:
|
|
40
|
+
return []
|
|
41
|
+
cmd = ["hadolint", "--no-fail", "--format", "gnu"] + paths
|
|
42
|
+
out = subprocess.run(
|
|
43
|
+
cmd, cwd=repo, capture_output=True, text=True, timeout=120
|
|
44
|
+
)
|
|
45
|
+
return self._parse(out.stdout + "\n" + out.stderr)
|
|
46
|
+
|
|
47
|
+
@staticmethod
|
|
48
|
+
def _parse(text: str) -> list[Finding]:
|
|
49
|
+
findings: list[Finding] = []
|
|
50
|
+
for raw in text.splitlines():
|
|
51
|
+
m = _HADOLINT_LINE.match(raw.strip())
|
|
52
|
+
if not m:
|
|
53
|
+
continue
|
|
54
|
+
severity = {
|
|
55
|
+
"error": Severity.HIGH,
|
|
56
|
+
"warning": Severity.MEDIUM,
|
|
57
|
+
"info": Severity.LOW,
|
|
58
|
+
"style": Severity.INFO,
|
|
59
|
+
}.get(m.group("severity"), Severity.LOW)
|
|
60
|
+
findings.append(
|
|
61
|
+
Finding(
|
|
62
|
+
tool="hadolint",
|
|
63
|
+
rule=m.group("code") or m.group("severity"),
|
|
64
|
+
severity=severity,
|
|
65
|
+
category=Category.LINT,
|
|
66
|
+
message=m.group("message").strip(),
|
|
67
|
+
file=m.group("file"),
|
|
68
|
+
line=int(m.group("line")),
|
|
69
|
+
column=0,
|
|
70
|
+
fixable=False,
|
|
71
|
+
doc_url=f"https://github.com/hadolint/hadolint/wiki/{m.group('code') or ''}",
|
|
72
|
+
raw={"line": raw},
|
|
73
|
+
)
|
|
74
|
+
)
|
|
75
|
+
return findings
|
polycheck/tools/knip.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""knip — find unused files, exports, and dependencies in JS/TS.
|
|
2
|
+
|
|
3
|
+
Knip's JSON output is the cleanest of the JS tools: a list of issue
|
|
4
|
+
objects with a type (``files``, ``exports``, ``dependencies``,
|
|
5
|
+
``devDependencies``…), file path, and a short symbol name.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import shutil
|
|
11
|
+
import subprocess
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
from ..finding import Category, Finding, Severity
|
|
15
|
+
from .base import Tool
|
|
16
|
+
|
|
17
|
+
# Knip issue type → polycheck (category, severity)
|
|
18
|
+
_TYPE_MAP = {
|
|
19
|
+
"files": (Category.DEAD_CODE, Severity.MEDIUM),
|
|
20
|
+
"exports": (Category.DEAD_CODE, Severity.LOW),
|
|
21
|
+
"types": (Category.DEAD_CODE, Severity.LOW),
|
|
22
|
+
"nsExports": (Category.DEAD_CODE, Severity.LOW),
|
|
23
|
+
"nsTypes": (Category.DEAD_CODE, Severity.LOW),
|
|
24
|
+
"dependencies": (Category.DEPS, Severity.MEDIUM),
|
|
25
|
+
"devDependencies": (Category.DEPS, Severity.LOW),
|
|
26
|
+
"optionalPeerDependencies": (Category.DEPS, Severity.LOW),
|
|
27
|
+
"unlisted": (Category.DEPS, Severity.MEDIUM),
|
|
28
|
+
"binaries": (Category.DEPS, Severity.LOW),
|
|
29
|
+
"duplicates": (Category.DEPS, Severity.LOW),
|
|
30
|
+
"enumMembers": (Category.DEAD_CODE, Severity.LOW),
|
|
31
|
+
"classMembers": (Category.DEAD_CODE, Severity.LOW),
|
|
32
|
+
"namespaceMembers": (Category.DEAD_CODE, Severity.LOW),
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class KnipTool(Tool):
|
|
37
|
+
name = "knip"
|
|
38
|
+
category = Category.DEAD_CODE
|
|
39
|
+
languages = ["javascript", "typescript"]
|
|
40
|
+
installer = "npm:knip"
|
|
41
|
+
|
|
42
|
+
def is_applicable(self, repo: Path) -> bool:
|
|
43
|
+
return (repo / "package.json").exists()
|
|
44
|
+
|
|
45
|
+
def run(self, repo: Path) -> list[Finding]:
|
|
46
|
+
if shutil.which("knip") is None and shutil.which("npx") is None:
|
|
47
|
+
return []
|
|
48
|
+
if shutil.which("knip"):
|
|
49
|
+
cmd = ["knip", "--reporter=json", "--no-progress"]
|
|
50
|
+
else:
|
|
51
|
+
cmd = ["npx", "knip", "--reporter=json", "--no-progress"]
|
|
52
|
+
out = subprocess.run(
|
|
53
|
+
cmd, cwd=repo, capture_output=True, text=True, timeout=300
|
|
54
|
+
)
|
|
55
|
+
if not out.stdout.strip():
|
|
56
|
+
return []
|
|
57
|
+
try:
|
|
58
|
+
data = json.loads(out.stdout)
|
|
59
|
+
except json.JSONDecodeError:
|
|
60
|
+
return []
|
|
61
|
+
|
|
62
|
+
findings: list[Finding] = []
|
|
63
|
+
# Knip v5 schema: {"files": [...], "exports": [...], "dependencies": [...], ...}
|
|
64
|
+
# Each entry is {"filePath": "...", "symbol": "...", "type": "..."}.
|
|
65
|
+
for issue_type, items in data.items():
|
|
66
|
+
if not isinstance(items, list):
|
|
67
|
+
continue
|
|
68
|
+
category, severity = _TYPE_MAP.get(issue_type, (Category.DEAD_CODE, Severity.LOW))
|
|
69
|
+
for item in items:
|
|
70
|
+
findings.append(
|
|
71
|
+
Finding(
|
|
72
|
+
tool=self.name,
|
|
73
|
+
rule=issue_type,
|
|
74
|
+
severity=severity,
|
|
75
|
+
category=category,
|
|
76
|
+
message=f"Unused {issue_type.rstrip('s')}: {item.get('symbol') or item.get('filePath')}",
|
|
77
|
+
file=item.get("filePath"),
|
|
78
|
+
line=item.get("line", 0),
|
|
79
|
+
column=item.get("col", 0),
|
|
80
|
+
fixable=False,
|
|
81
|
+
raw=item,
|
|
82
|
+
)
|
|
83
|
+
)
|
|
84
|
+
return findings
|
polycheck/tools/mypy.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""mypy — Python static type checker.
|
|
2
|
+
|
|
3
|
+
mypy doesn't have a stable JSON output yet (the ``--output json`` flag
|
|
4
|
+
was experimental). We use plain text and parse the well-known
|
|
5
|
+
``path:line: severity: message [code]`` format. This format has been
|
|
6
|
+
stable across mypy 0.x and 1.x.
|
|
7
|
+
|
|
8
|
+
mypy has no auto-fix; type errors are reported and the LLM triages.
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import re
|
|
13
|
+
import shutil
|
|
14
|
+
import subprocess
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
from ..finding import Category, Finding, Severity
|
|
18
|
+
from .base import Tool
|
|
19
|
+
|
|
20
|
+
# mypy's "file:line[:col]: severity: message" line. The optional error
|
|
21
|
+
# code in brackets is parsed separately. The column is optional because
|
|
22
|
+
# mypy only emits it with --show-column, which we pass.
|
|
23
|
+
_MYPY_LINE = re.compile(
|
|
24
|
+
r"^(?P<file>[^:]+):(?P<line>\d+)(?::(?P<column>\d+))?:\s*"
|
|
25
|
+
r"(?P<severity>error|warning|note):\s*"
|
|
26
|
+
r"(?P<message>.*?)(?:\s*\[(?P<code>[^\]]+)\])?\s*$"
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class MypyTool(Tool):
|
|
31
|
+
name = "mypy"
|
|
32
|
+
category = Category.TYPE
|
|
33
|
+
languages = ["python"]
|
|
34
|
+
installer = "pipx:mypy"
|
|
35
|
+
|
|
36
|
+
def is_applicable(self, repo: Path) -> bool:
|
|
37
|
+
return (repo / "pyproject.toml").exists() or any(repo.glob("**/*.py"))
|
|
38
|
+
|
|
39
|
+
def run(self, repo: Path) -> list[Finding]:
|
|
40
|
+
cmd = ["mypy", "--no-error-summary", "--show-column", "."]
|
|
41
|
+
# Allow mypy itself to be missing (linter venvs may not have it).
|
|
42
|
+
if shutil.which("mypy") is None:
|
|
43
|
+
return []
|
|
44
|
+
out = subprocess.run(
|
|
45
|
+
cmd, cwd=repo, capture_output=True, text=True, timeout=300
|
|
46
|
+
)
|
|
47
|
+
# mypy exits non-zero on findings; we ignore the exit code.
|
|
48
|
+
text = out.stdout + "\n" + out.stderr
|
|
49
|
+
return self._parse(text)
|
|
50
|
+
|
|
51
|
+
@staticmethod
|
|
52
|
+
def _parse(text: str) -> list[Finding]:
|
|
53
|
+
findings: list[Finding] = []
|
|
54
|
+
for raw in text.splitlines():
|
|
55
|
+
m = _MYPY_LINE.match(raw.strip())
|
|
56
|
+
if not m:
|
|
57
|
+
continue
|
|
58
|
+
severity = {
|
|
59
|
+
"error": Severity.HIGH,
|
|
60
|
+
"warning": Severity.MEDIUM,
|
|
61
|
+
"note": Severity.INFO,
|
|
62
|
+
}.get(m.group("severity"), Severity.MEDIUM)
|
|
63
|
+
# "import not found" / "library stubs not installed" are
|
|
64
|
+
# environment noise, not code defects. Mark them LOW so
|
|
65
|
+
# they sort below real type errors.
|
|
66
|
+
msg = m.group("message")
|
|
67
|
+
if "Cannot find implementation" in msg or "Library stubs not installed" in msg:
|
|
68
|
+
severity = Severity.LOW
|
|
69
|
+
column_text = m.group("column")
|
|
70
|
+
findings.append(
|
|
71
|
+
Finding(
|
|
72
|
+
tool="mypy",
|
|
73
|
+
rule=m.group("code") or "unknown",
|
|
74
|
+
severity=severity,
|
|
75
|
+
category=Category.TYPE,
|
|
76
|
+
message=msg,
|
|
77
|
+
file=m.group("file"),
|
|
78
|
+
line=int(m.group("line")),
|
|
79
|
+
column=int(column_text) if column_text else None,
|
|
80
|
+
fixable=False,
|
|
81
|
+
doc_url=f"https://mypy.readthedocs.io/en/stable/_refs.html#code-{m.group('code') or 'unknown'}",
|
|
82
|
+
raw={"line": raw},
|
|
83
|
+
)
|
|
84
|
+
)
|
|
85
|
+
return findings
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""npm audit — scan JS/TS dependencies for known CVEs.
|
|
2
|
+
|
|
3
|
+
Calls ``npm audit --json``. The output shape is stable across npm
|
|
4
|
+
versions 7+: a top-level object with ``vulnerabilities`` (per-package
|
|
5
|
+
details) and ``metadata`` (counts). We flatten to one Finding per
|
|
6
|
+
vuln×package combo.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import shutil
|
|
12
|
+
import subprocess
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
from ..finding import Category, Finding, Severity
|
|
16
|
+
from .base import Tool
|
|
17
|
+
|
|
18
|
+
# npm's severity string → our Severity
|
|
19
|
+
_NPM_SEV = {
|
|
20
|
+
"critical": Severity.CRITICAL,
|
|
21
|
+
"high": Severity.HIGH,
|
|
22
|
+
"moderate": Severity.MEDIUM,
|
|
23
|
+
"low": Severity.LOW,
|
|
24
|
+
"info": Severity.INFO,
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class NpmAuditTool(Tool):
|
|
29
|
+
name = "npm-audit"
|
|
30
|
+
category = Category.CVE
|
|
31
|
+
languages = ["javascript", "typescript"]
|
|
32
|
+
installer = None # npm comes with Node.js; no separate install needed
|
|
33
|
+
|
|
34
|
+
def is_applicable(self, repo: Path) -> bool:
|
|
35
|
+
return (repo / "package.json").exists()
|
|
36
|
+
|
|
37
|
+
def run(self, repo: Path) -> list[Finding]:
|
|
38
|
+
if shutil.which("npm") is None:
|
|
39
|
+
return []
|
|
40
|
+
out = subprocess.run(
|
|
41
|
+
["npm", "audit", "--json"],
|
|
42
|
+
cwd=repo, capture_output=True, text=True, timeout=300
|
|
43
|
+
)
|
|
44
|
+
# npm audit exits non-zero on findings; we ignore that.
|
|
45
|
+
if not out.stdout.strip():
|
|
46
|
+
return []
|
|
47
|
+
try:
|
|
48
|
+
data = json.loads(out.stdout)
|
|
49
|
+
except json.JSONDecodeError:
|
|
50
|
+
return []
|
|
51
|
+
|
|
52
|
+
findings: list[Finding] = []
|
|
53
|
+
for pkg_name, info in data.get("vulnerabilities", {}).items():
|
|
54
|
+
severity = _NPM_SEV.get(info.get("severity"), Severity.MEDIUM)
|
|
55
|
+
for via in info.get("via", []):
|
|
56
|
+
if not isinstance(via, dict):
|
|
57
|
+
continue
|
|
58
|
+
findings.append(
|
|
59
|
+
Finding(
|
|
60
|
+
tool=self.name,
|
|
61
|
+
rule=via.get("source") or "CVE-UNKNOWN",
|
|
62
|
+
severity=severity,
|
|
63
|
+
category=self.category,
|
|
64
|
+
message=f"{pkg_name} {info.get('range','')}: {via.get('title','')}",
|
|
65
|
+
file=pkg_name,
|
|
66
|
+
line=0,
|
|
67
|
+
column=0,
|
|
68
|
+
fixable=bool(info.get("fixAvailable")),
|
|
69
|
+
fix_command=f"npm install {pkg_name}@latest",
|
|
70
|
+
doc_url=via.get("url"),
|
|
71
|
+
raw=info,
|
|
72
|
+
)
|
|
73
|
+
)
|
|
74
|
+
return findings
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
"""pip-audit — scan Python dependencies for known CVEs.
|
|
2
|
+
|
|
3
|
+
pip-audit's ``--format json`` output is a list of dependencies with
|
|
4
|
+
their vulnerabilities. We flatten to one Finding per CVE, with the
|
|
5
|
+
package name in the file field and a synthetic line of 0. This way
|
|
6
|
+
the dedupe / grouping logic in reporters treats them like any other
|
|
7
|
+
finding.
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
import shutil
|
|
13
|
+
import subprocess
|
|
14
|
+
import sys
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
from ..finding import Category, Finding, Severity
|
|
18
|
+
from .base import Tool
|
|
19
|
+
|
|
20
|
+
# Canonical name for the requirements file used by pip-audit.
|
|
21
|
+
_REQUIREMENTS_TXT = "requirements.txt"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class PipAuditTool(Tool):
|
|
25
|
+
name = "pip-audit"
|
|
26
|
+
category = Category.CVE
|
|
27
|
+
languages = ["python"]
|
|
28
|
+
installer = "pipx:pip-audit"
|
|
29
|
+
|
|
30
|
+
def is_applicable(self, repo: Path) -> bool:
|
|
31
|
+
# pip-audit is applicable to any Python project that has a
|
|
32
|
+
# lockable dependency manifest.
|
|
33
|
+
return any(
|
|
34
|
+
(repo / name).exists()
|
|
35
|
+
for name in ("pyproject.toml", _REQUIREMENTS_TXT, "Pipfile", "poetry.lock", "uv.lock")
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
def run(self, repo: Path) -> list[Finding]:
|
|
39
|
+
if shutil.which("pip-audit") is None:
|
|
40
|
+
return []
|
|
41
|
+
|
|
42
|
+
cmd = self._build_command(repo)
|
|
43
|
+
if cmd is None:
|
|
44
|
+
return []
|
|
45
|
+
|
|
46
|
+
out = subprocess.run(
|
|
47
|
+
cmd, cwd=repo, capture_output=True, text=True, timeout=300
|
|
48
|
+
)
|
|
49
|
+
if not out.stdout.strip():
|
|
50
|
+
return []
|
|
51
|
+
|
|
52
|
+
try:
|
|
53
|
+
data = json.loads(out.stdout)
|
|
54
|
+
except json.JSONDecodeError:
|
|
55
|
+
return []
|
|
56
|
+
|
|
57
|
+
return self._parse_findings(data)
|
|
58
|
+
|
|
59
|
+
def _build_command(self, repo: Path) -> list[str] | None:
|
|
60
|
+
"""Build the pip-audit command."""
|
|
61
|
+
if (repo / _REQUIREMENTS_TXT).exists():
|
|
62
|
+
return ["pip-audit", "-r", _REQUIREMENTS_TXT, "--format", "json", "--no-deps"]
|
|
63
|
+
|
|
64
|
+
reqs = self._extract_requirements(repo)
|
|
65
|
+
if not reqs:
|
|
66
|
+
return None
|
|
67
|
+
|
|
68
|
+
tmp = repo / ".polycheck-pip-audit-reqs.txt"
|
|
69
|
+
tmp.write_text("\n".join(reqs), encoding="utf-8")
|
|
70
|
+
return ["pip-audit", "-r", str(tmp.name), "--format", "json", "--no-deps"]
|
|
71
|
+
|
|
72
|
+
def _parse_findings(self, data: dict) -> list[Finding]:
|
|
73
|
+
"""Parse pip-audit JSON output into Finding objects."""
|
|
74
|
+
findings: list[Finding] = []
|
|
75
|
+
for dep in data.get("dependencies", []):
|
|
76
|
+
seen_ids: set[str] = set()
|
|
77
|
+
for vuln in dep.get("vulns", []):
|
|
78
|
+
rule_id = vuln.get("id", "CVE-UNKNOWN")
|
|
79
|
+
if rule_id in seen_ids:
|
|
80
|
+
continue
|
|
81
|
+
seen_ids.add(rule_id)
|
|
82
|
+
findings.append(self._make_finding(dep, vuln, rule_id))
|
|
83
|
+
return findings
|
|
84
|
+
|
|
85
|
+
def _make_finding(self, dep: dict, vuln: dict, rule_id: str) -> Finding:
|
|
86
|
+
"""Create a Finding from a dependency vulnerability."""
|
|
87
|
+
fix_versions = ",".join(vuln.get("fix_versions", []))
|
|
88
|
+
return Finding(
|
|
89
|
+
tool=self.name,
|
|
90
|
+
rule=rule_id,
|
|
91
|
+
severity=Severity.CRITICAL,
|
|
92
|
+
category=self.category,
|
|
93
|
+
message=(
|
|
94
|
+
f"{dep.get('name','?')} {dep.get('version','?')}: "
|
|
95
|
+
f"{vuln.get('description','')[:200]}"
|
|
96
|
+
+ (f" (fix: {fix_versions})" if fix_versions else "")
|
|
97
|
+
),
|
|
98
|
+
file=dep.get("name"),
|
|
99
|
+
line=0,
|
|
100
|
+
column=0,
|
|
101
|
+
fixable=bool(fix_versions),
|
|
102
|
+
fix_command=None,
|
|
103
|
+
doc_url=None,
|
|
104
|
+
raw={"dep": dep, "vuln": vuln},
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
@staticmethod
|
|
108
|
+
def _extract_requirements(repo: Path) -> list[str]:
|
|
109
|
+
"""Read ``dependencies`` and ``optional-dependencies`` from
|
|
110
|
+
``pyproject.toml`` and return a list of bare package specs.
|
|
111
|
+
Returns ``[]`` if pyproject is missing or malformed.
|
|
112
|
+
"""
|
|
113
|
+
pyproject = repo / "pyproject.toml"
|
|
114
|
+
if not pyproject.exists():
|
|
115
|
+
return []
|
|
116
|
+
try:
|
|
117
|
+
if sys.version_info >= (3, 11):
|
|
118
|
+
import tomllib
|
|
119
|
+
else:
|
|
120
|
+
import tomli as tomllib
|
|
121
|
+
data = tomllib.loads(pyproject.read_text(encoding="utf-8"))
|
|
122
|
+
except (OSError, ValueError):
|
|
123
|
+
return []
|
|
124
|
+
|
|
125
|
+
project = data.get("project", {})
|
|
126
|
+
reqs: list[str] = []
|
|
127
|
+
for spec in project.get("dependencies", []):
|
|
128
|
+
reqs.append(str(spec))
|
|
129
|
+
for extras in project.get("optional-dependencies", {}).values():
|
|
130
|
+
for spec in extras:
|
|
131
|
+
reqs.append(str(spec))
|
|
132
|
+
return reqs
|