ai-sec-gate 0.2.2__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.
@@ -0,0 +1,22 @@
1
+ """ai-sec-gate: security posture verifier, semantic AST scanner, and hook prover."""
2
+ from __future__ import annotations
3
+
4
+ from importlib.metadata import PackageNotFoundError, version
5
+
6
+ from ai_sec_gate.testing import (
7
+ assert_constant_time_verifier,
8
+ assert_salted_kdf,
9
+ assert_token_entropy,
10
+ )
11
+
12
+ try:
13
+ __version__ = version("ai-sec-gate")
14
+ except PackageNotFoundError:
15
+ __version__ = "0.0.0-dev"
16
+
17
+ __all__ = [
18
+ "__version__",
19
+ "assert_constant_time_verifier",
20
+ "assert_salted_kdf",
21
+ "assert_token_entropy",
22
+ ]
@@ -0,0 +1,3 @@
1
+ from ai_sec_gate.cli import main
2
+
3
+ raise SystemExit(main())
@@ -0,0 +1,25 @@
1
+ """Registry of language security adapters."""
2
+ from __future__ import annotations
3
+
4
+ from ai_sec_gate.adapters.base import LanguageAdapter
5
+ from ai_sec_gate.adapters.js_adapter import JavaScriptAdapter
6
+ from ai_sec_gate.adapters.python_adapter import PythonAdapter
7
+ from ai_sec_gate.adapters.rust_adapter import RustAdapter
8
+
9
+
10
+ def get_adapters() -> list[LanguageAdapter]:
11
+ """Return all registered language adapters in deterministic order."""
12
+ return [
13
+ PythonAdapter(),
14
+ JavaScriptAdapter(),
15
+ RustAdapter(),
16
+ ]
17
+
18
+
19
+ __all__ = [
20
+ "JavaScriptAdapter",
21
+ "LanguageAdapter",
22
+ "PythonAdapter",
23
+ "RustAdapter",
24
+ "get_adapters",
25
+ ]
@@ -0,0 +1,132 @@
1
+ """Language-agnostic adapter contract and shared lexical helpers for ai-sec-gate."""
2
+ from __future__ import annotations
3
+
4
+ import abc
5
+ import pathlib
6
+ from typing import Any
7
+
8
+ from ai_sec_gate.models import AdapterResult
9
+
10
+
11
+ class LanguageAdapter(abc.ABC):
12
+ """Base interface implemented by every language security analyzer."""
13
+
14
+ language: str = "unknown"
15
+
16
+ @abc.abstractmethod
17
+ def detect(self, root: pathlib.Path) -> bool:
18
+ """Return True if the target repository contains this language ecosystem."""
19
+
20
+ @abc.abstractmethod
21
+ def scan(
22
+ self,
23
+ root: pathlib.Path,
24
+ cfg: dict[str, Any],
25
+ *,
26
+ with_deps_audit: bool = False,
27
+ with_clippy: bool = False,
28
+ no_external_sast: bool = False,
29
+ ) -> AdapterResult:
30
+ """Scan files and (optionally) dependencies/linters for this language."""
31
+
32
+
33
+ def iter_source_files(
34
+ root: pathlib.Path,
35
+ suffixes: tuple[str, ...],
36
+ ignore_dirs: set[str],
37
+ ) -> list[pathlib.Path]:
38
+ """Walk target repository skipping configured ignored directories and symlinks."""
39
+ matched: list[pathlib.Path] = []
40
+ for entry in sorted(root.rglob("*")):
41
+ if entry.is_symlink():
42
+ continue
43
+ rel_parts = entry.relative_to(root).parts
44
+ if any(part in ignore_dirs for part in rel_parts[:-1]):
45
+ continue
46
+ if entry.is_file() and entry.suffix in suffixes:
47
+ matched.append(entry)
48
+ return matched
49
+
50
+
51
+ def normalize_ident(name: str) -> str:
52
+ """Normalize snake_case and camelCase identifiers for keyword matching."""
53
+ return name.lower().replace("_", "").replace("-", "")
54
+
55
+
56
+ def matches_normalized(identifiers: set[str], keywords: list[str]) -> bool:
57
+ """Return True if any identifier contains any configured keyword (snake/camel agnostic)."""
58
+ norm_kws = [normalize_ident(k) for k in keywords]
59
+ for ident in identifiers:
60
+ norm_id = normalize_ident(ident)
61
+ if any(kw in norm_id for kw in norm_kws):
62
+ return True
63
+ return False
64
+
65
+
66
+ def strip_c_comments(
67
+ source: str,
68
+ *,
69
+ blank_strings: bool = False,
70
+ single_quote_strings: bool = True,
71
+ ) -> str:
72
+ """Strip // and /* */ comments while preserving exact line numbers.
73
+
74
+ When blank_strings is True, characters inside string/template literals are
75
+ replaced with spaces (preserving newlines) so structural keyword scans
76
+ never match inside literals. Set single_quote_strings=False for Rust so
77
+ lifetimes like `'a` and `'static` are never treated as unclosed strings.
78
+ """
79
+ out: list[str] = []
80
+ n = len(source)
81
+ i = 0
82
+ quotes = ('"', "`", "'") if single_quote_strings else ('"',)
83
+
84
+ while i < n:
85
+ ch = source[i]
86
+ nxt = source[i + 1] if i + 1 < n else ""
87
+
88
+ if ch == "/" and nxt == "/":
89
+ while i < n and source[i] != "\n":
90
+ out.append(" ")
91
+ i += 1
92
+ continue
93
+
94
+ if ch == "/" and nxt == "*":
95
+ out.append(" ")
96
+ i += 2
97
+ while i < n:
98
+ if source[i] == "*" and i + 1 < n and source[i + 1] == "/":
99
+ out.append(" ")
100
+ i += 2
101
+ break
102
+ out.append("\n" if source[i] == "\n" else " ")
103
+ i += 1
104
+ continue
105
+
106
+ if ch in quotes:
107
+ quote = ch
108
+ out.append(" " if blank_strings else ch)
109
+ i += 1
110
+ while i < n:
111
+ c = source[i]
112
+ if c == "\\" and i + 1 < n:
113
+ if blank_strings:
114
+ out.append("\n" if c == "\n" else " ")
115
+ out.append("\n" if source[i + 1] == "\n" else " ")
116
+ else:
117
+ out.append(c)
118
+ out.append(source[i + 1])
119
+ i += 2
120
+ continue
121
+ if c == quote:
122
+ out.append(" " if blank_strings else c)
123
+ i += 1
124
+ break
125
+ out.append(c if (c == "\n" or not blank_strings) else " ")
126
+ i += 1
127
+ continue
128
+
129
+ out.append(ch)
130
+ i += 1
131
+
132
+ return "".join(out)
@@ -0,0 +1,350 @@
1
+ """JavaScript / TypeScript semantic security adapter + lockfile/audit checks."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import pathlib
6
+ import re
7
+ import shutil
8
+ import subprocess
9
+ from typing import Any
10
+
11
+ from ai_sec_gate.adapters.base import (
12
+ LanguageAdapter,
13
+ iter_source_files,
14
+ matches_normalized,
15
+ normalize_ident,
16
+ strip_c_comments,
17
+ )
18
+ from ai_sec_gate.models import AdapterResult, Finding
19
+
20
+ LOCKFILES = ("package-lock.json", "pnpm-lock.yaml", "yarn.lock", "bun.lock", "bun.lockb")
21
+ IDENT_RE = re.compile(r"\b[A-Za-z_$][A-Za-z0-9_$]*\b")
22
+ HASH_CALL_RE = re.compile(
23
+ r"(?:\bcreateHash|\bsubtle\.digest)\s*\(\s*['\"`]([A-Za-z0-9_-]+)['\"`]"
24
+ )
25
+ FN_HEADER_RE = re.compile(
26
+ r"(?:\bfunction\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*\(([^)]*)\)"
27
+ r"|(?:const|let|var)\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*=\s*(?:async\s*)?\(([^)]*)\)\s*(?::[^=]+)?=>"
28
+ r"|(?:async\s+)?([A-Za-z_$][A-Za-z0-9_$]*)\s*\(([^)]*)\)\s*(?::[^{;]+)?\{)"
29
+ )
30
+ MATH_RANDOM_RE = re.compile(r"\bMath\s*\.\s*random\s*\(")
31
+ COMPARE_RE = re.compile(r"([^=!;,\n]+?)\s*(===|!==|==|!=)\s*([^=;\n]+)")
32
+ EXEC_DANGER_RE = re.compile(r"(?:\beval\s*\(|\bnew\s+Function\s*\(|\bshell\s*:\s*true\b)")
33
+ TLS_BYPASS_PROP_RE = re.compile(r"\brejectUnauthorized\s*:\s*false\b")
34
+ TLS_BYPASS_ENV_RE = re.compile(r"\bNODE_TLS_REJECT_UNAUTHORIZED\s*=\s*['\"`]?0['\"`]?")
35
+
36
+ NULLISH_TOKENS = {"null", "undefined", "true", "false", "0", "''", '""', "``"}
37
+ CONTROL_KEYWORDS = {"if", "for", "while", "switch", "catch", "return", "typeof", "export", "async", "function"}
38
+
39
+
40
+ def _is_js_test_file(rel: str, name: str) -> bool:
41
+ parts = rel.split("/")
42
+ if any(seg in ("test", "tests", "__tests__", "__mocks__") for seg in parts[:-1]):
43
+ return True
44
+ lower = name.lower()
45
+ return any(tok in lower for tok in (".test.", ".spec.", "_test."))
46
+
47
+
48
+ def _stmt_window(st_lines: list[str], idx: int) -> str:
49
+ """Extract current JS statement without crossing `;` or `}` into unrelated declarations."""
50
+ parts: list[str] = []
51
+ if idx > 0 and not st_lines[idx - 1].rstrip().endswith((";", "{", "}")) and st_lines[idx - 1].strip():
52
+ parts.append(st_lines[idx - 1])
53
+ parts.append(st_lines[idx])
54
+ cur = idx
55
+ while cur + 1 < len(st_lines) and cur < idx + 3 and ";" not in st_lines[cur] and "}" not in st_lines[cur]:
56
+ cur += 1
57
+ parts.append(st_lines[cur])
58
+ return "\n".join(parts)
59
+
60
+
61
+ def _compute_line_fn_scopes(st_lines: list[str]) -> list[set[str]]:
62
+ """Track active `{ ... }` function header identifiers per line, popping on closing `}`."""
63
+ scopes_per_line: list[set[str]] = []
64
+ stack: list[tuple[int, set[str]]] = []
65
+ brace_depth = 0
66
+ pending_fn_idents: set[str] | None = None
67
+
68
+ for line in st_lines:
69
+ m = FN_HEADER_RE.search(line)
70
+ if m and m.group(1) not in CONTROL_KEYWORDS and m.group(5) not in CONTROL_KEYWORDS:
71
+ fn_idents: set[str] = set()
72
+ for grp in m.groups():
73
+ if grp:
74
+ fn_idents.update(tok for tok in IDENT_RE.findall(grp) if tok not in CONTROL_KEYWORDS)
75
+ pending_fn_idents = fn_idents
76
+
77
+ for ch in line:
78
+ if ch == "{":
79
+ brace_depth += 1
80
+ if pending_fn_idents is not None:
81
+ stack.append((brace_depth, pending_fn_idents))
82
+ pending_fn_idents = None
83
+ elif ch == "}":
84
+ while stack and stack[-1][0] == brace_depth:
85
+ stack.pop()
86
+ brace_depth = max(0, brace_depth - 1)
87
+
88
+ if ";" in line:
89
+ pending_fn_idents = None
90
+
91
+ active: set[str] = set()
92
+ for _, ids in stack:
93
+ active.update(ids)
94
+ scopes_per_line.append(active)
95
+
96
+ return scopes_per_line
97
+
98
+
99
+ class JavaScriptAdapter(LanguageAdapter):
100
+ language = "javascript"
101
+
102
+ def detect(self, root: pathlib.Path) -> bool:
103
+ return (root / "package.json").is_file()
104
+
105
+ def scan(
106
+ self,
107
+ root: pathlib.Path,
108
+ cfg: dict[str, Any],
109
+ *,
110
+ with_deps_audit: bool = False,
111
+ with_clippy: bool = False,
112
+ no_external_sast: bool = False,
113
+ ) -> AdapterResult:
114
+ ignore_dirs = set(cfg["posture"]["ignore_dirs"])
115
+ js_files = iter_source_files(root, (".js", ".mjs", ".cjs", ".ts", ".tsx", ".jsx"), ignore_dirs)
116
+ result = AdapterResult(language=self.language, detected=True, files_scanned=len(js_files))
117
+
118
+ if not any((root / lf).is_file() for lf in LOCKFILES):
119
+ result.findings.append(
120
+ Finding(
121
+ rule_id="JS-SUPPLY-001",
122
+ severity="MEDIUM",
123
+ language=self.language,
124
+ path="package.json",
125
+ line=1,
126
+ message="No dependency lockfile committed alongside package.json.",
127
+ remediation="Commit package-lock.json (or pnpm-lock.yaml / yarn.lock) to pin transitive dependencies.",
128
+ )
129
+ )
130
+
131
+ for path in js_files:
132
+ rel = path.relative_to(root).as_posix()
133
+ if _is_js_test_file(rel, path.name):
134
+ continue
135
+ try:
136
+ raw = path.read_text(encoding="utf-8", errors="ignore")
137
+ except OSError:
138
+ continue
139
+ result.findings.extend(self._scan_js_source(rel, raw, cfg))
140
+
141
+ if with_deps_audit:
142
+ self._run_js_audit(root, result)
143
+ return result
144
+
145
+ def _scan_js_source(self, rel: str, raw: str, cfg: dict[str, Any]) -> list[Finding]:
146
+ findings: list[Finding] = []
147
+ crypto_cfg = cfg["crypto"]
148
+ broken_hashes = {normalize_ident(h) for h in crypto_cfg["broken_hashes"]}
149
+ fast_hashes = {normalize_ident(h) for h in crypto_cfg["fast_hashes"]}
150
+ approved_kdfs = list(crypto_cfg["approved_kdfs"])
151
+ pw_kws = list(crypto_cfg["password_identifiers"])
152
+ cmp_kws = list(crypto_cfg["secret_compare_identifiers"])
153
+ rand_kws = list(crypto_cfg["random_secret_identifiers"])
154
+
155
+ no_comments = strip_c_comments(raw, blank_strings=False, single_quote_strings=True)
156
+ structural = strip_c_comments(raw, blank_strings=True, single_quote_strings=True)
157
+
158
+ nc_lines = no_comments.splitlines()
159
+ st_lines = structural.splitlines()
160
+ line_scopes = _compute_line_fn_scopes(st_lines)
161
+
162
+ for idx, (nc_line, st_line) in enumerate(zip(nc_lines, st_lines, strict=False)):
163
+ lineno = idx + 1
164
+ fn_scope = line_scopes[idx] if idx < len(line_scopes) else set()
165
+
166
+ # 1. Hash primitives (JS-CRYPTO-001 broken hash, JS-CRYPTO-002 fast password hash)
167
+ for hm in HASH_CALL_RE.finditer(nc_line):
168
+ alg_raw = hm.group(1)
169
+ alg_norm = normalize_ident(alg_raw)
170
+ if alg_norm in broken_hashes:
171
+ findings.append(
172
+ Finding(
173
+ rule_id="JS-CRYPTO-001",
174
+ severity="HIGH",
175
+ language=self.language,
176
+ path=rel,
177
+ line=lineno,
178
+ message=f"Broken cryptographic hash '{alg_raw}' used in JS/TS.",
179
+ remediation="Use SHA-256 for checksums or crypto.scrypt / argon2 / bcrypt for passwords.",
180
+ )
181
+ )
182
+ continue
183
+
184
+ if alg_norm in fast_hashes and "createHmac" not in st_line:
185
+ stmt = _stmt_window(st_lines, idx)
186
+ local_idents = set(IDENT_RE.findall(stmt)) | fn_scope
187
+ if matches_normalized(local_idents, pw_kws):
188
+ kdfs = ", ".join(approved_kdfs[:4])
189
+ findings.append(
190
+ Finding(
191
+ rule_id="JS-CRYPTO-002",
192
+ severity="HIGH",
193
+ language=self.language,
194
+ path=rel,
195
+ line=lineno,
196
+ message=f"Fast hash '{alg_raw}' applied to password material (Level 2 brute-forceable hash).",
197
+ remediation=f"Use a salted slow KDF ({kdfs}, e.g. crypto.scrypt) instead of plain SHA.",
198
+ )
199
+ )
200
+
201
+ # 2. Math.random() on secrets/tokens/nonces (JS-RAND-001)
202
+ if MATH_RANDOM_RE.search(st_line):
203
+ rand_idents = set(IDENT_RE.findall(_stmt_window(st_lines, idx))) | fn_scope
204
+ if matches_normalized(rand_idents, rand_kws):
205
+ findings.append(
206
+ Finding(
207
+ rule_id="JS-RAND-001",
208
+ severity="HIGH",
209
+ language=self.language,
210
+ path=rel,
211
+ line=lineno,
212
+ message="Non-cryptographic Math.random() used to generate secret, token, or nonce material.",
213
+ remediation="Use crypto.randomBytes(), crypto.randomUUID(), or crypto.getRandomValues().",
214
+ )
215
+ )
216
+
217
+ # 3. Timing-unsafe secret comparison (JS-AUTH-004)
218
+ for cm in COMPARE_RE.finditer(st_line):
219
+ lhs, rhs = cm.group(1).strip(), cm.group(3).strip()
220
+ if lhs in NULLISH_TOKENS or rhs in NULLISH_TOKENS:
221
+ continue
222
+ if ".length" in lhs or ".length" in rhs or "typeof " in lhs or "typeof " in rhs:
223
+ continue
224
+ nc_cm = COMPARE_RE.search(nc_line)
225
+ if nc_cm and (nc_cm.group(1).strip() in NULLISH_TOKENS or nc_cm.group(3).strip() in NULLISH_TOKENS):
226
+ continue
227
+ cmp_idents = set(IDENT_RE.findall(lhs)) | set(IDENT_RE.findall(rhs))
228
+ if matches_normalized(cmp_idents, cmp_kws):
229
+ findings.append(
230
+ Finding(
231
+ rule_id="JS-AUTH-004",
232
+ severity="MEDIUM",
233
+ language=self.language,
234
+ path=rel,
235
+ line=lineno,
236
+ message="Direct equality comparison on secret/digest variable leaks timing side-channels.",
237
+ remediation="Compare digests, signatures, and tokens with crypto.timingSafeEqual(Buffer.from(a), Buffer.from(b)).",
238
+ )
239
+ )
240
+ break
241
+
242
+ # 4. Dynamic execution / shell=true (JS-EXEC-001)
243
+ if EXEC_DANGER_RE.search(st_line):
244
+ findings.append(
245
+ Finding(
246
+ rule_id="JS-EXEC-001",
247
+ severity="HIGH",
248
+ language=self.language,
249
+ path=rel,
250
+ line=lineno,
251
+ message="Unsafe dynamic code execution (eval / new Function / shell: true) detected.",
252
+ remediation="Avoid eval/Function and spawn child processes with argument arrays (shell: false).",
253
+ )
254
+ )
255
+
256
+ # 5. TLS verification bypass (JS-TLS-001)
257
+ if TLS_BYPASS_PROP_RE.search(st_line) or TLS_BYPASS_ENV_RE.search(nc_line):
258
+ findings.append(
259
+ Finding(
260
+ rule_id="JS-TLS-001",
261
+ severity="HIGH",
262
+ language=self.language,
263
+ path=rel,
264
+ line=lineno,
265
+ message="TLS certificate validation disabled (rejectUnauthorized: false / NODE_TLS_REJECT_UNAUTHORIZED=0).",
266
+ remediation="Keep TLS certificate verification enabled and configure custom CA bundles via 'ca' if needed.",
267
+ )
268
+ )
269
+
270
+ return findings
271
+
272
+ def _run_js_audit(self, root: pathlib.Path, result: AdapterResult) -> None:
273
+ if (root / "package-lock.json").is_file() and shutil.which("npm"):
274
+ self._run_npm_like_audit(
275
+ root, result, [shutil.which("npm") or "npm", "audit", "--json", "--audit-level=high"], "package-lock.json"
276
+ )
277
+ elif (root / "pnpm-lock.yaml").is_file() and shutil.which("pnpm"):
278
+ self._run_npm_like_audit(
279
+ root, result, [shutil.which("pnpm") or "pnpm", "audit", "--json", "--audit-level", "high"], "pnpm-lock.yaml"
280
+ )
281
+ elif (root / "yarn.lock").is_file() and shutil.which("yarn"):
282
+ self._run_yarn_audit(root, result)
283
+ else:
284
+ result.notes.append("JS dependency audit skipped (requires npm/pnpm/yarn and matching lockfile).")
285
+
286
+ def _run_npm_like_audit(
287
+ self,
288
+ root: pathlib.Path,
289
+ result: AdapterResult,
290
+ cmd: list[str],
291
+ lockfile_name: str,
292
+ ) -> None:
293
+ try:
294
+ proc = subprocess.run(cmd, cwd=root, capture_output=True, text=True, timeout=120)
295
+ data = json.loads(proc.stdout) if proc.stdout.strip() else {}
296
+ except (OSError, subprocess.SubprocessError, json.JSONDecodeError):
297
+ result.notes.append(f"{cmd[0]} audit execution failed.")
298
+ return
299
+
300
+ vulns = data.get("vulnerabilities", {})
301
+ if isinstance(vulns, dict):
302
+ for pkg_name, meta in vulns.items():
303
+ if not isinstance(meta, dict):
304
+ continue
305
+ sev = str(meta.get("severity", "medium")).upper()
306
+ if sev in ("HIGH", "CRITICAL"):
307
+ result.findings.append(
308
+ Finding(
309
+ rule_id="JS-DEP-AUDIT",
310
+ severity=sev,
311
+ language=self.language,
312
+ path=lockfile_name,
313
+ line=1,
314
+ message=f"Dependency audit reported {sev} vulnerability in '{pkg_name}'.",
315
+ remediation="Upgrade the affected dependency and regenerate the lockfile.",
316
+ )
317
+ )
318
+
319
+ def _run_yarn_audit(self, root: pathlib.Path, result: AdapterResult) -> None:
320
+ yarn_bin = shutil.which("yarn")
321
+ if not yarn_bin:
322
+ return
323
+ try:
324
+ proc = subprocess.run(
325
+ [yarn_bin, "npm", "audit", "--json", "--severity", "high"],
326
+ cwd=root,
327
+ capture_output=True,
328
+ text=True,
329
+ timeout=120,
330
+ )
331
+ for raw_line in proc.stdout.splitlines():
332
+ if not raw_line.strip():
333
+ continue
334
+ item = json.loads(raw_line)
335
+ if isinstance(item, dict) and str(item.get("severity", "")).upper() in ("HIGH", "CRITICAL"):
336
+ sev = str(item["severity"]).upper()
337
+ pkg = item.get("value") or item.get("module_name") or "package"
338
+ result.findings.append(
339
+ Finding(
340
+ rule_id="JS-DEP-AUDIT",
341
+ severity=sev,
342
+ language=self.language,
343
+ path="yarn.lock",
344
+ line=1,
345
+ message=f"yarn audit reported {sev} vulnerability in '{pkg}'.",
346
+ remediation="Upgrade the affected package in package.json and yarn.lock.",
347
+ )
348
+ )
349
+ except (OSError, subprocess.SubprocessError, json.JSONDecodeError):
350
+ result.notes.append("yarn audit execution failed.")