File size: 7,598 Bytes
8df6aa0 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 | #!/usr/bin/env python3
"""Per-language syntax validation for AppSecBench code snippets.
Best-effort but *real* where a toolchain exists; conservative heuristics
elsewhere. We never claim a snippet is valid when the toolchain says it is not,
and we never emit false alarms for correct code (heuristics only flag clearly
broken delimiter balance).
Mapping:
Python -> CPython `compile()` (exec mode) [real]
JS -> `node --check` [real]
TS -> typescript transpileModule (syntax) [real]
Go -> `gofmt -e` (prepend package main) [real]
Rust -> delimiter-balance heuristic [heuristic]
Java -> delimiter-balance + annotation-aware [heuristic]
C/C++ -> delimiter-balance heuristic [heuristic]
C# -> delimiter-balance heuristic [heuristic]
PHP -> delimiter-balance heuristic [heuristic]
Kotlin -> delimiter-balance heuristic [heuristic]
Swift -> delimiter-balance heuristic [heuristic]
YAML -> yaml.safe_load [real]
Dockerfile -> directive heuristic [heuristic]
Bash -> `bash -n` [real]
"""
from __future__ import annotations
import os
import subprocess
import tempfile
try:
import yaml # PyYAML
except Exception: # pragma: no cover
yaml = None
_TS_AVAILABLE = False
try:
import node as _node # noqa (not how it's imported)
except Exception:
_TS_AVAILABLE = False
_NODE_TS_PATH = None
for _cand in (
"/usr/local/lib/hermes-agent/node_modules/typescript/lib/typescript.js",
"/usr/local/lib/hermes-agent/node_modules/typescript/index.js",
):
if os.path.exists(_cand):
_NODE_TS_PATH = _cand
break
def _balance_ok(code: str) -> bool:
"""Heuristic: paired delimiters balanced, accounting for strings/comments lightly."""
pairs = {")": "(", "]": "[", "}": "{"}
stack = []
in_str = None
i = 0
n = len(code)
while i < n:
c = code[i]
if in_str:
if c == "\\":
i += 2
continue
if c == in_str:
in_str = None
i += 1
continue
if c in ("'", '"', "`"):
in_str = c
i += 1
continue
if c in ("(", "[", "{"):
stack.append(c)
elif c in pairs:
if not stack or stack[-1] != pairs[c]:
return False
stack.pop()
i += 1
return not stack
def _py_check(code: str):
try:
compile(code, "<snippet>", "exec")
return True, ""
except SyntaxError as e:
return False, f"SyntaxError: {e.msg} (line {e.lineno})"
def _node_check(code: str, ts: bool):
if ts:
if _NODE_TS_PATH is None:
return None, "typescript module not found (heuristic fallback)"
# Use transpileModule to get SYNTACTIC diagnostics only.
js = (
"const ts = require(%r);"
"const fs = require('fs');"
"const src = fs.readFileSync(0,'utf8');"
"const out = ts.transpileModule(src, {compilerOptions:{target:ts.ScriptTarget.ES2020}, reportDiagnostics:true});"
"const diag = (out.diagnostics||[]).filter(d=>d.category===1);"
"process.stdout.write(diag.length ? diag.map(d=>ts.flattenDiagnosticMessageText(d.messageText,'\\n')).join('\\n') : 'OK');"
) % _NODE_TS_PATH
p = subprocess.run(["node", "-e", js], input=code,
capture_output=True, text=True, timeout=30)
if p.stdout.strip() == "OK":
return True, ""
if p.stdout.strip():
return False, p.stdout.strip()[:200]
return None, f"ts heuristic: {p.stderr.strip()[:120]}"
with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as f:
f.write(code)
path = f.name
try:
p = subprocess.run(["node", "--check", path], capture_output=True, text=True, timeout=30)
if p.returncode == 0:
return True, ""
return False, p.stderr.strip().splitlines()[-1][:200]
finally:
os.unlink(path)
def _go_check(code: str):
prelude = (
"package main\n\n"
"import (\n"
'\t"context"\n'
'\t"crypto/aes"\n'
'\t"crypto/cipher"\n'
'\t"crypto/sha256"\n'
'\t"database/sql"\n'
'\t"encoding/base64"\n'
'\t"encoding/json"\n'
'\t"fmt"\n'
'\t"net/http"\n'
'\t"os"\n'
'\t"regexp"\n'
'\t"strings"\n'
'\t"time"\n'
")\n\n"
)
with tempfile.NamedTemporaryFile("w", suffix=".go", delete=False) as f:
f.write(prelude + code)
path = f.name
try:
p = subprocess.run(["go", "build", path], capture_output=True, text=True, timeout=60)
if p.returncode == 0:
return (True, "")
errs = p.stderr.strip().splitlines()
# Keep only genuine SYNTAX errors (go build also reports undefined
# identifiers, which are expected for out-of-context snippets).
syntax_errs = [e for e in errs if "expected" in e or "syntax" in e.lower()
or "invalid" in e.lower() or "unexpected" in e.lower()
or "missing return" in e.lower()]
if syntax_errs:
return (False, syntax_errs[-1][:200])
# Only undefined-name / type / unused-import errors -> syntax is valid.
return (True, "")
finally:
os.unlink(path)
def _bash_check(code: str):
with tempfile.NamedTemporaryFile("w", suffix=".sh", delete=False) as f:
f.write(code)
path = f.name
try:
p = subprocess.run(["bash", "-n", path], capture_output=True, text=True, timeout=30)
if p.returncode == 0:
return True, ""
return False, p.stderr.strip().splitlines()[-1][:200]
finally:
os.unlink(path)
def _yaml_check(code: str):
if yaml is None:
return None, "pyyaml not installed (heuristic fallback)"
try:
list(yaml.safe_load_all(code))
return True, ""
except yaml.YAMLError as e:
return False, str(e).splitlines()[0][:200]
def _dockerfile_check(code: str):
ok = any(line.strip().upper().startswith(("FROM", "RUN", "CMD", "COPY", "ENV", "USER", "VOLUME", "EXPOSE"))
for line in code.splitlines() if line.strip())
if not ok:
return (False, "no Dockerfile directive found")
if _balance_ok(code):
return (True, "")
return (False, "unbalanced delimiters")
def check(language: str, code: str):
"""Return (ok, detail). ok True=valid, False=invalid, None=skipped/heuristic."""
lang = (language or "").lower()
if lang == "python":
return _py_check(code)
if lang == "javascript":
return _node_check(code, ts=False)
if lang == "typescript":
return _node_check(code, ts=True)
if lang == "go":
return _go_check(code)
if lang in ("yaml", "dockerfile", "bash"):
if lang == "yaml":
return _yaml_check(code)
if lang == "dockerfile":
return _dockerfile_check(code)
return _bash_check(code)
# Heuristic for the rest.
if _balance_ok(code):
return (None, "heuristic: delimiter balance ok")
return (False, "heuristic: unbalanced delimiters")
if __name__ == "__main__":
import sys
ok, d = check(sys.argv[1], sys.stdin.read())
print(ok, d)
|