| |
| """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 |
| except Exception: |
| yaml = None |
|
|
| _TS_AVAILABLE = False |
| try: |
| import node as _node |
| 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)" |
| |
| 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() |
| |
| |
| 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]) |
| |
| 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) |
| |
| 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) |
|
|