vetgate 0.1.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.
- vetgate/__init__.py +3 -0
- vetgate/__main__.py +5 -0
- vetgate/cli.py +124 -0
- vetgate/core.py +190 -0
- vetgate/hook.py +95 -0
- vetgate/languages/__init__.py +34 -0
- vetgate/languages/csharp/__init__.py +34 -0
- vetgate/languages/csharp/common.py +548 -0
- vetgate/languages/csharp/debug.py +129 -0
- vetgate/languages/csharp/practices.py +106 -0
- vetgate/languages/csharp/quality.py +68 -0
- vetgate/languages/csharp/security.py +634 -0
- vetgate/languages/csharp/security_web.py +352 -0
- vetgate-0.1.0.dist-info/METADATA +149 -0
- vetgate-0.1.0.dist-info/RECORD +19 -0
- vetgate-0.1.0.dist-info/WHEEL +5 -0
- vetgate-0.1.0.dist-info/entry_points.txt +3 -0
- vetgate-0.1.0.dist-info/licenses/LICENSE +21 -0
- vetgate-0.1.0.dist-info/top_level.txt +1 -0
vetgate/__init__.py
ADDED
vetgate/__main__.py
ADDED
vetgate/cli.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
"""vetgate: multi-language, multi-focus local code gate.
|
|
2
|
+
|
|
3
|
+
vetgate [targets...] --focus security,quality [--lang auto|csharp,...] [--diff [REF]] [--files-from PATH]
|
|
4
|
+
|
|
5
|
+
Files are routed to a language pack by extension; each pack runs only the focuses it supports.
|
|
6
|
+
Exit codes: 0 = no findings at/above threshold, 1 = findings, 2 = usage/runtime error.
|
|
7
|
+
"""
|
|
8
|
+
import argparse
|
|
9
|
+
import json
|
|
10
|
+
import sys
|
|
11
|
+
import time
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
from . import languages
|
|
15
|
+
from . import __version__
|
|
16
|
+
from .core import (
|
|
17
|
+
expand_targets, files_from_diff, files_from_list, finalize, keep_file, render_compact, render_sarif, render_text,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
ALL_FOCUSES = ("security", "debug", "quality", "practices")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _csv(value: str) -> list[str]:
|
|
24
|
+
return [v.strip() for v in value.split(",") if v.strip()]
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
28
|
+
p = argparse.ArgumentParser(prog="vetgate", description="Local multi-language security & quality gate.")
|
|
29
|
+
p.add_argument("targets", nargs="*", default=["."], help="Files or directories (default: current directory).")
|
|
30
|
+
p.add_argument("--focus", type=_csv, default=["security"],
|
|
31
|
+
help="Comma list of: security, debug, quality, practices, all (default: security).")
|
|
32
|
+
p.add_argument("--lang", type=_csv, default=["auto"],
|
|
33
|
+
help=f"Comma list of language packs or 'auto' (available: {', '.join(languages.LANGUAGE_PACKAGES)}).")
|
|
34
|
+
p.add_argument("--min-severity", choices=["low", "medium", "high"], default=None,
|
|
35
|
+
help="Default: medium for security-only runs, low when debug/quality are selected.")
|
|
36
|
+
p.add_argument("--files-from", metavar="PATH", help="Scan only the paths listed in PATH ('-' = stdin).")
|
|
37
|
+
p.add_argument("--diff", nargs="?", const="HEAD", metavar="REF",
|
|
38
|
+
help="Scan only files changed vs REF (default HEAD) plus untracked files.")
|
|
39
|
+
p.add_argument("--include-tests", action="store_true", help="Do not skip test projects/files.")
|
|
40
|
+
p.add_argument("--format", choices=["json", "text", "compact", "sarif"], default="json")
|
|
41
|
+
p.add_argument("--disable", type=_csv, default=[], metavar="RULES", help="Comma list of rule ids to skip.")
|
|
42
|
+
p.add_argument("--version", action="version", version=f"vetgate {__version__}")
|
|
43
|
+
p.add_argument("--no-fail", action="store_true", help="Always exit 0 (report-only).")
|
|
44
|
+
g = p.add_argument_group("language-specific options")
|
|
45
|
+
g.add_argument("--include-dapper", action="store_true", help="[csharp] Include dynamic Dapper SQL calls.")
|
|
46
|
+
return p
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def run(args) -> tuple[dict, int]:
|
|
50
|
+
focuses = list(ALL_FOCUSES) if "all" in args.focus else args.focus
|
|
51
|
+
bad = [f for f in focuses if f not in ALL_FOCUSES]
|
|
52
|
+
if bad:
|
|
53
|
+
raise ValueError(f"unknown focus: {', '.join(bad)}")
|
|
54
|
+
langs = languages.all_languages() if "auto" in args.lang else [languages.get(n) for n in args.lang]
|
|
55
|
+
min_sev = args.min_severity or ("medium" if focuses == ["security"] else "low")
|
|
56
|
+
options = {"include_dapper": args.include_dapper}
|
|
57
|
+
ext_map = {ext: lang for lang in langs for ext in lang.EXTENSIONS}
|
|
58
|
+
|
|
59
|
+
t0 = time.perf_counter()
|
|
60
|
+
targets = [Path(t) for t in args.targets]
|
|
61
|
+
if args.files_from or args.diff is not None:
|
|
62
|
+
base = targets[0] if targets and targets[0].is_dir() else None
|
|
63
|
+
candidates = files_from_list(args.files_from, base) if args.files_from else files_from_diff(targets[0], args.diff)
|
|
64
|
+
explicit = False
|
|
65
|
+
else:
|
|
66
|
+
candidates = expand_targets(targets, set(ext_map))
|
|
67
|
+
explicit_files = {t.resolve() for t in targets if t.is_file()}
|
|
68
|
+
explicit = None # decided per file below
|
|
69
|
+
|
|
70
|
+
results, skipped = [], {}
|
|
71
|
+
for f in sorted(set(candidates)):
|
|
72
|
+
lang = ext_map.get(f.suffix.lower())
|
|
73
|
+
if lang is None:
|
|
74
|
+
continue
|
|
75
|
+
is_explicit = explicit if explicit is not None else f.resolve() in explicit_files
|
|
76
|
+
if not keep_file(f, is_explicit, args.include_tests, lang.is_test_file):
|
|
77
|
+
continue
|
|
78
|
+
active = [x for x in focuses if x in lang.FOCUSES]
|
|
79
|
+
for x in focuses:
|
|
80
|
+
if x not in lang.FOCUSES:
|
|
81
|
+
skipped.setdefault(lang.NAME, set()).add(x)
|
|
82
|
+
source = f.read_bytes()
|
|
83
|
+
findings, syntax_errors = lang.analyze(f, source, active, options)
|
|
84
|
+
for fd in findings:
|
|
85
|
+
fd.setdefault("language", lang.NAME)
|
|
86
|
+
results.append({"file": str(f), "language": lang.NAME, "syntax_errors": syntax_errors,
|
|
87
|
+
"findings": finalize(f, findings, min_sev, source, set(args.disable))})
|
|
88
|
+
|
|
89
|
+
total = sum(len(r["findings"]) for r in results)
|
|
90
|
+
report = {
|
|
91
|
+
"focus": focuses,
|
|
92
|
+
"languages": sorted({r["language"] for r in results}),
|
|
93
|
+
"min_severity": min_sev,
|
|
94
|
+
"scanned_files": len(results),
|
|
95
|
+
"total_findings": total,
|
|
96
|
+
"elapsed_ms": round((time.perf_counter() - t0) * 1000),
|
|
97
|
+
"unsupported_focus": {k: sorted(v) for k, v in skipped.items()},
|
|
98
|
+
"results": [r for r in results if r["findings"]],
|
|
99
|
+
}
|
|
100
|
+
return report, (0 if args.no_fail or total == 0 else 1)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def main(argv=None) -> int:
|
|
104
|
+
args = build_parser().parse_args(argv)
|
|
105
|
+
try:
|
|
106
|
+
report, code = run(args)
|
|
107
|
+
except (FileNotFoundError, RuntimeError, ValueError, ModuleNotFoundError) as e:
|
|
108
|
+
print(f"Error: {e}", file=sys.stderr)
|
|
109
|
+
return 2
|
|
110
|
+
if args.format == "text":
|
|
111
|
+
print(render_text(report["results"]))
|
|
112
|
+
print(f"-- {report['scanned_files']} file(s), {report['total_findings']} finding(s), "
|
|
113
|
+
f"min-severity={report['min_severity']}, {report['elapsed_ms']} ms", file=sys.stderr)
|
|
114
|
+
elif args.format == "compact":
|
|
115
|
+
print(render_compact(report["results"]))
|
|
116
|
+
elif args.format == "sarif":
|
|
117
|
+
print(json.dumps(render_sarif(report["results"], __version__), indent=2))
|
|
118
|
+
else:
|
|
119
|
+
print(json.dumps(report, indent=2))
|
|
120
|
+
return code
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
if __name__ == "__main__":
|
|
124
|
+
sys.exit(main())
|
vetgate/core.py
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
"""Language-agnostic core: finding schema, severities, file selection, diff mode, rendering."""
|
|
2
|
+
import re
|
|
3
|
+
import subprocess
|
|
4
|
+
import sys
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
SEVERITY_RANK = {"low": 1, "medium": 2, "high": 3}
|
|
8
|
+
IGNORED_DIRS = {"bin", "obj", ".git", "node_modules", "Migrations", "TestResults", "vendor", "dist", "build",
|
|
9
|
+
".venv", "venv", "__pycache__", "fixtures"}
|
|
10
|
+
WHY_FIELDS = ("source", "guard", "sink", "reason")
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def make_finding(rule: str, line: int, *, engine: str = "deterministic", confidence: float = 1.0,
|
|
14
|
+
severity: str | None = None, source: str | None = None, guard: str | None = None,
|
|
15
|
+
sink: str | None = None, reason: str = "") -> dict:
|
|
16
|
+
"""Every finding of every language/focus uses this shape."""
|
|
17
|
+
f = {
|
|
18
|
+
"rule": rule,
|
|
19
|
+
"line": line,
|
|
20
|
+
"engine": engine,
|
|
21
|
+
"confidence": round(float(confidence), 4),
|
|
22
|
+
"source": source,
|
|
23
|
+
"guard": guard,
|
|
24
|
+
"sink": sink,
|
|
25
|
+
"reason": reason,
|
|
26
|
+
}
|
|
27
|
+
if severity:
|
|
28
|
+
f["severity"] = severity
|
|
29
|
+
return f
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def short(text: str, limit: int = 120) -> str:
|
|
33
|
+
text = " ".join(text.split())
|
|
34
|
+
return text if len(text) <= limit else text[: limit - 3] + "..."
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
SUPPRESS_RE = re.compile(r"vetgate-ignore(?:\s*:\s*([A-Z_]+(?:\s*,\s*[A-Z_]+)*))?")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def suppressions(source: bytes | None) -> dict[int, set[str] | None]:
|
|
41
|
+
"""Line -> suppressed rules (None = all). A `vetgate-ignore[: RULE, ...]` comment covers its line and the next."""
|
|
42
|
+
if not source:
|
|
43
|
+
return {}
|
|
44
|
+
out: dict[int, set[str] | None] = {}
|
|
45
|
+
for i, line in enumerate(source.decode("utf-8", errors="ignore").splitlines(), start=1):
|
|
46
|
+
m = SUPPRESS_RE.search(line)
|
|
47
|
+
if not m or ("//" not in line and "#" not in line and "/*" not in line):
|
|
48
|
+
continue
|
|
49
|
+
rules = {r.strip() for r in m.group(1).split(",")} if m.group(1) else None
|
|
50
|
+
for ln in (i, i + 1):
|
|
51
|
+
prev = out.get(ln, set())
|
|
52
|
+
out[ln] = None if rules is None or prev is None else (prev | rules)
|
|
53
|
+
return out
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def finalize(path: Path, findings: list[dict], min_severity: str, source: bytes | None = None,
|
|
57
|
+
disabled: set[str] | None = None) -> list[dict]:
|
|
58
|
+
"""Dedupe by (line, rule) keeping the most severe, apply threshold, suppressions and disabled rules."""
|
|
59
|
+
min_rank = SEVERITY_RANK[min_severity]
|
|
60
|
+
supp = suppressions(source)
|
|
61
|
+
disabled = disabled or set()
|
|
62
|
+
seen, kept = set(), []
|
|
63
|
+
for f in sorted(findings, key=lambda f: (f["line"], f["rule"], -SEVERITY_RANK[f["severity"]])):
|
|
64
|
+
key = (f["line"], f["rule"])
|
|
65
|
+
if key in seen or SEVERITY_RANK[f["severity"]] < min_rank or f["rule"] in disabled:
|
|
66
|
+
continue
|
|
67
|
+
seen.add(key)
|
|
68
|
+
if f["line"] in supp and (supp[f["line"]] is None or f["rule"] in supp[f["line"]]):
|
|
69
|
+
continue
|
|
70
|
+
kept.append({"file": str(path), **f})
|
|
71
|
+
return kept
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
# ------------------------------------------------------------------ file selection
|
|
75
|
+
|
|
76
|
+
def _git(cwd: Path, *args: str) -> str:
|
|
77
|
+
res = subprocess.run(["git", "-C", str(cwd), *args], capture_output=True, text=True)
|
|
78
|
+
if res.returncode != 0:
|
|
79
|
+
raise RuntimeError(f"git {' '.join(args)} failed: {res.stderr.strip()}")
|
|
80
|
+
return res.stdout
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def files_from_diff(target: Path, ref: str) -> list[Path]:
|
|
84
|
+
"""Files changed vs ref plus untracked files, restricted to target when it is a directory."""
|
|
85
|
+
cwd = target if target.is_dir() else target.parent
|
|
86
|
+
top = Path(_git(cwd, "rev-parse", "--show-toplevel").strip())
|
|
87
|
+
names = set(_git(cwd, "diff", "--name-only", "--diff-filter=ACMR", ref, "--").splitlines())
|
|
88
|
+
names |= set(_git(cwd, "ls-files", "--others", "--exclude-standard").splitlines())
|
|
89
|
+
files = [top / n for n in sorted(names)]
|
|
90
|
+
if target.is_dir():
|
|
91
|
+
base = target.resolve()
|
|
92
|
+
files = [f for f in files if f.resolve().is_relative_to(base)]
|
|
93
|
+
return files
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def files_from_list(spec: str, base: Path | None = None) -> list[Path]:
|
|
97
|
+
text = sys.stdin.read() if spec == "-" else Path(spec).read_text(encoding="utf-8")
|
|
98
|
+
out = []
|
|
99
|
+
for line in text.splitlines():
|
|
100
|
+
line = line.strip()
|
|
101
|
+
if not line:
|
|
102
|
+
continue
|
|
103
|
+
p = Path(line)
|
|
104
|
+
if not p.is_absolute() and base is not None and not p.exists():
|
|
105
|
+
p = base / p
|
|
106
|
+
out.append(p)
|
|
107
|
+
return out
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def expand_targets(targets: list[Path], extensions: set[str]) -> list[Path]:
|
|
111
|
+
files = []
|
|
112
|
+
for t in targets:
|
|
113
|
+
if t.is_file():
|
|
114
|
+
files.append(t)
|
|
115
|
+
elif t.is_dir():
|
|
116
|
+
files.extend(f for f in t.rglob("*") if f.suffix.lower() in extensions)
|
|
117
|
+
else:
|
|
118
|
+
raise FileNotFoundError(f"Target not found: {t}")
|
|
119
|
+
return files
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def keep_file(f: Path, explicit: bool, include_tests: bool, is_test) -> bool:
|
|
123
|
+
if not f.is_file():
|
|
124
|
+
return False
|
|
125
|
+
if not explicit and any(part in IGNORED_DIRS for part in f.parts):
|
|
126
|
+
return False
|
|
127
|
+
if not include_tests and not explicit and is_test(f):
|
|
128
|
+
return False
|
|
129
|
+
return True
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
# ------------------------------------------------------------------ rendering
|
|
133
|
+
|
|
134
|
+
def render_text(results: list[dict]) -> str:
|
|
135
|
+
lines = []
|
|
136
|
+
for r in results:
|
|
137
|
+
for f in r["findings"]:
|
|
138
|
+
lines.append(f"{f['file']}:{f['line']}: [{f['severity'].upper()}] {f['rule']} ({f['engine']}, {f['confidence']})")
|
|
139
|
+
for k in WHY_FIELDS:
|
|
140
|
+
if f.get(k):
|
|
141
|
+
lines.append(f" {k:<6}: {f[k]}")
|
|
142
|
+
return "\n".join(lines) if lines else "No findings."
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def render_compact(results: list[dict]) -> str:
|
|
146
|
+
"""One line per finding, tuned for agents: minimal tokens, still actionable."""
|
|
147
|
+
lines = []
|
|
148
|
+
for r in results:
|
|
149
|
+
for f in r["findings"]:
|
|
150
|
+
src = f" src={short(f['source'], 50)}" if f.get("source") else ""
|
|
151
|
+
lines.append(f"{f['file']}:{f['line']} {f['severity'][0].upper()} {f['rule']}{src} | {short(f.get('guard') or '', 80)}")
|
|
152
|
+
return "\n".join(lines) if lines else "OK"
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
SARIF_LEVEL = {"high": "error", "medium": "warning", "low": "note"}
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def render_sarif(results: list[dict], tool_version: str = "0.1.0") -> dict:
|
|
159
|
+
"""SARIF 2.1.0 for GitHub code scanning and IDEs."""
|
|
160
|
+
rules: dict[str, dict] = {}
|
|
161
|
+
sarif_results = []
|
|
162
|
+
for r in results:
|
|
163
|
+
for f in r["findings"]:
|
|
164
|
+
rules.setdefault(f["rule"], {
|
|
165
|
+
"id": f["rule"],
|
|
166
|
+
"name": f["rule"].title().replace("_", ""),
|
|
167
|
+
"shortDescription": {"text": f["rule"].replace("_", " ").lower()},
|
|
168
|
+
"fullDescription": {"text": f.get("reason") or f["rule"]},
|
|
169
|
+
"defaultConfiguration": {"level": SARIF_LEVEL[f["severity"]]},
|
|
170
|
+
"properties": {"tags": [t for t in (f.get("module"), f.get("language")) if t]},
|
|
171
|
+
})
|
|
172
|
+
msg = " | ".join(f"{k}: {f[k]}" for k in WHY_FIELDS if f.get(k))
|
|
173
|
+
sarif_results.append({
|
|
174
|
+
"ruleId": f["rule"],
|
|
175
|
+
"level": SARIF_LEVEL[f["severity"]],
|
|
176
|
+
"message": {"text": msg},
|
|
177
|
+
"locations": [{"physicalLocation": {
|
|
178
|
+
"artifactLocation": {"uri": Path(f["file"]).as_posix()},
|
|
179
|
+
"region": {"startLine": f["line"]},
|
|
180
|
+
}}],
|
|
181
|
+
"properties": {"confidence": f["confidence"], "engine": f["engine"]},
|
|
182
|
+
})
|
|
183
|
+
return {
|
|
184
|
+
"$schema": "https://json.schemastore.org/sarif-2.1.0.json",
|
|
185
|
+
"version": "2.1.0",
|
|
186
|
+
"runs": [{
|
|
187
|
+
"tool": {"driver": {"name": "vetgate", "version": tool_version, "rules": list(rules.values())}},
|
|
188
|
+
"results": sarif_results,
|
|
189
|
+
}],
|
|
190
|
+
}
|
vetgate/hook.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"""Claude Code PostToolUse hook (`vetgate-hook`): run the gate on the file just edited and feed findings back to the agent.
|
|
2
|
+
|
|
3
|
+
Reports:
|
|
4
|
+
- medium/high (security) findings anywhere in the file;
|
|
5
|
+
- low findings (debug, quality, practices) only on lines changed vs git HEAD (all lines if untracked / no git),
|
|
6
|
+
so editing a large legacy file does not flood the context with pre-existing noise.
|
|
7
|
+
Silent (no output) when the file is clean or not handled by any language pack. Never blocks; never fails the edit.
|
|
8
|
+
"""
|
|
9
|
+
import json
|
|
10
|
+
import re
|
|
11
|
+
import subprocess
|
|
12
|
+
import sys
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
MAX_LINES = 12
|
|
16
|
+
HUNK_RE = re.compile(r"^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@", re.M)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def changed_lines(path: Path) -> set[int] | None:
|
|
20
|
+
"""Lines added/modified vs HEAD; None means 'treat every line as changed'."""
|
|
21
|
+
try:
|
|
22
|
+
cwd = str(path.parent)
|
|
23
|
+
tracked = subprocess.run(["git", "-C", cwd, "ls-files", "--error-unmatch", path.name],
|
|
24
|
+
capture_output=True, text=True, timeout=5)
|
|
25
|
+
if tracked.returncode != 0:
|
|
26
|
+
return None
|
|
27
|
+
diff = subprocess.run(["git", "-C", cwd, "diff", "-U0", "HEAD", "--", path.name],
|
|
28
|
+
capture_output=True, text=True, timeout=5)
|
|
29
|
+
if diff.returncode != 0:
|
|
30
|
+
return None
|
|
31
|
+
except (OSError, subprocess.SubprocessError):
|
|
32
|
+
return None
|
|
33
|
+
lines: set[int] = set()
|
|
34
|
+
for m in HUNK_RE.finditer(diff.stdout):
|
|
35
|
+
start, count = int(m.group(1)), int(m.group(2) or 1)
|
|
36
|
+
lines.update(range(start, start + count))
|
|
37
|
+
return lines
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def run() -> int:
|
|
41
|
+
try:
|
|
42
|
+
payload = json.load(sys.stdin)
|
|
43
|
+
except (json.JSONDecodeError, ValueError):
|
|
44
|
+
return 0
|
|
45
|
+
tool_input = payload.get("tool_input") or {}
|
|
46
|
+
raw = tool_input.get("file_path") or (payload.get("tool_response") or {}).get("filePath")
|
|
47
|
+
if not raw:
|
|
48
|
+
return 0
|
|
49
|
+
path = Path(raw)
|
|
50
|
+
if not path.is_file():
|
|
51
|
+
return 0
|
|
52
|
+
|
|
53
|
+
from . import languages
|
|
54
|
+
from .core import IGNORED_DIRS, SEVERITY_RANK, finalize, short
|
|
55
|
+
|
|
56
|
+
lang = languages.by_extension(path.suffix)
|
|
57
|
+
if lang is None or any(part in IGNORED_DIRS for part in path.parts):
|
|
58
|
+
return 0 # unsupported language, build output, or intentionally-vulnerable fixtures
|
|
59
|
+
|
|
60
|
+
source = path.read_bytes()
|
|
61
|
+
findings, _ = lang.analyze(path, source, list(lang.FOCUSES), {})
|
|
62
|
+
findings = finalize(path, findings, "low", source)
|
|
63
|
+
changed = changed_lines(path)
|
|
64
|
+
keep = [f for f in findings
|
|
65
|
+
if SEVERITY_RANK[f["severity"]] >= SEVERITY_RANK["medium"] or changed is None or f["line"] in changed]
|
|
66
|
+
if not keep:
|
|
67
|
+
return 0
|
|
68
|
+
|
|
69
|
+
keep.sort(key=lambda f: (-SEVERITY_RANK[f["severity"]], f["line"]))
|
|
70
|
+
blocking = sum(1 for f in keep if SEVERITY_RANK[f["severity"]] >= SEVERITY_RANK["medium"])
|
|
71
|
+
head = (f"vetgate: {path.name}: {blocking} security (medium+), {len(keep) - blocking} low"
|
|
72
|
+
f"{' on changed lines' if changed is not None else ''}. Fix medium+ before finishing.")
|
|
73
|
+
lines = [head]
|
|
74
|
+
for f in keep[:MAX_LINES]:
|
|
75
|
+
why = short(f.get("guard") or "", 70)
|
|
76
|
+
src = f" [{short(f['source'], 40)}]" if f.get("source") else ""
|
|
77
|
+
lines.append(f" L{f['line']} {f['severity'][0].upper()} {f['rule']}{src} - {why}")
|
|
78
|
+
if len(keep) > MAX_LINES:
|
|
79
|
+
lines.append(f" +{len(keep) - MAX_LINES} more: vetgate \"{path}\" --focus all --format text")
|
|
80
|
+
|
|
81
|
+
print(json.dumps({"hookSpecificOutput": {"hookEventName": "PostToolUse", "additionalContext": "\n".join(lines)}}))
|
|
82
|
+
return 0
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def main() -> int:
|
|
86
|
+
"""Entry point for the `vetgate-hook` command. Never raises: a broken hook must not break the edit loop."""
|
|
87
|
+
try:
|
|
88
|
+
return run()
|
|
89
|
+
except Exception as e: # noqa: BLE001
|
|
90
|
+
print(f"vetgate hook error: {e}", file=sys.stderr)
|
|
91
|
+
return 0
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
if __name__ == "__main__":
|
|
95
|
+
sys.exit(main())
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Language registry.
|
|
2
|
+
|
|
3
|
+
Each language package exposes:
|
|
4
|
+
NAME: str language id (e.g. "csharp")
|
|
5
|
+
EXTENSIONS: set[str] file suffixes it owns (lower-case, with dot)
|
|
6
|
+
FOCUSES: dict[str, str] focus name -> module id (e.g. "security" -> "csharp-security")
|
|
7
|
+
is_test_file(path) -> bool test-file heuristic for that ecosystem
|
|
8
|
+
analyze(path, source_bytes, focuses, options) -> list[dict] findings using vetgate.core.make_finding
|
|
9
|
+
|
|
10
|
+
Add a stack by creating vetgate/languages/<name>/ and listing it in LANGUAGE_PACKAGES.
|
|
11
|
+
"""
|
|
12
|
+
import importlib
|
|
13
|
+
|
|
14
|
+
LANGUAGE_PACKAGES = ["csharp"] # next: "nodejs", "php"
|
|
15
|
+
|
|
16
|
+
_loaded: dict = {}
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def get(name: str):
|
|
20
|
+
if name not in _loaded:
|
|
21
|
+
_loaded[name] = importlib.import_module(f"{__name__}.{name}")
|
|
22
|
+
return _loaded[name]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def all_languages() -> list:
|
|
26
|
+
return [get(n) for n in LANGUAGE_PACKAGES]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def by_extension(suffix: str):
|
|
30
|
+
suffix = suffix.lower()
|
|
31
|
+
for lang in all_languages():
|
|
32
|
+
if suffix in lang.EXTENSIONS:
|
|
33
|
+
return lang
|
|
34
|
+
return None
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""C# / .NET language pack: tree-sitter AST and intra-procedural taint."""
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
|
|
4
|
+
from .common import cs_parser, is_test_file # noqa: F401
|
|
5
|
+
|
|
6
|
+
NAME = "csharp"
|
|
7
|
+
EXTENSIONS = {".cs"}
|
|
8
|
+
FOCUSES = {
|
|
9
|
+
"security": "csharp-security",
|
|
10
|
+
"debug": "csharp-debug",
|
|
11
|
+
"quality": "csharp-quality",
|
|
12
|
+
"practices": "csharp-practices",
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _focus_module(focus: str):
|
|
18
|
+
from . import debug, practices, quality, security
|
|
19
|
+
return {"security": security, "debug": debug, "quality": quality, "practices": practices}[focus]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def analyze(path: Path, source: bytes, focuses: list[str], options: dict) -> tuple[list[dict], bool]:
|
|
23
|
+
"""Return (findings, syntax_errors)."""
|
|
24
|
+
code = source.decode("utf-8", errors="ignore")
|
|
25
|
+
root = cs_parser.parse(source).root_node
|
|
26
|
+
findings: list[dict] = []
|
|
27
|
+
for focus in focuses:
|
|
28
|
+
if focus not in FOCUSES:
|
|
29
|
+
continue
|
|
30
|
+
findings.extend(_focus_module(focus).analyze(
|
|
31
|
+
root, source, code,
|
|
32
|
+
include_dapper=bool(options.get("include_dapper", False)),
|
|
33
|
+
))
|
|
34
|
+
return findings, root.has_error
|