ai-sec-gate
Zero-dependency security posture verifier, semantic crypto/auth analyzer, behavioral KDF test helper library, and active hook prover for repositories written with AI coding agents.
General-purpose linters (ruff --select S, Bandit, ESLint, Clippy) catch broken primitives like md5 or eval, yet miss AI-era failure modes: invisible Unicode prompt-injection tags in AGENTS.md / .cursorrules, unpinned MCP server runners (npx -y), plain sha256 on user passwords, catastrophic ReDoS regexes (CWE-1333), JWT/CORS verification bypasses, unpinned trust_remote_code=True model loads, os.path.join traversal traps, and undocumented Rust unsafe blocks. ai-sec-gate pairs semantic source and AI-surface checks across Python, JS/TS, Rust, and Go (covering OWASP Top 10 2021 + OWASP LLM Top 10 2025) with repository posture verification and isolated red-team hook probes.
Quickstart (Run Anywhere with uvx — No Install Required)
# Scan the current repository or any local directory
uvx ai-sec-gate check .
uvx ai-sec-gate check /path/to/any-repo
# Scan any public Git repository directly (safe shallow clone, hooks disabled)
uvx ai-sec-gate check https://github.com/owner/repo
uvx ai-sec-gate check github:owner/repo@main
# Scan any PyPI package directly (safe sdist/wheel extraction, no code execution)
uvx ai-sec-gate check pypi:some-package
uvx ai-sec-gate check pypi:some-package==1.2.3
# Scan a single file or verify a specific rule / posture check in milliseconds (ideal for OSS fixes)
uvx ai-sec-gate check path/to/file.rs --rule RS-UNSAFE-001
uvx ai-sec-gate check datafusion/physical-expr-common --rule RS-UNSAFE-001
uvx ai-sec-gate check . --posture POSTURE-CI-SHA,POSTURE-DEP-AUDIT
# Generate an owner-ready Markdown audit report (code snippets, crate/file hotspots, & copy-paste fixes)
uvx ai-sec-gate check https://github.com/owner/repo --report audit-report.md
# Explain any rule or posture check (CWE, OWASP mapping, real-world impact, & remediation)
uvx ai-sec-gate explain PY-CRYPTO-002
uvx ai-sec-gate explain --all
Remote targets (
https://...,github:...,pypi:...) are scanned statically in an isolated temporary directory with git hooks and symlinks disabled;--proveis refused on remote targets so untrusted repository hooks are never executed.
Caught in the Wild
Real issues surfaced by ai-sec-gate during public open-source audits (only responsibly disclosed PRs and public fixes are listed):
| Repository | Rule / CWE | Surface | Issue & Impact | Upstream PR |
|---|---|---|---|---|
| apache/datafusion | PY-DOS-001 (CWE-1333) |
docs/ (tooling · LOW) |
Overlapping \s*(.*?) under re.DOTALL in docs/rustdoc_trim.py caused $O(N^2)$ backtracking on unclosed code fences (1,733 ms → 0.16 ms on 15 KB input) and falsely matched info strings like ```rustfmt |
#28008 |
Trust-boundary aware severity: The same $O(N^2)$ regex is
LOWin a Sphinxdocs/helper (not exposed to untrusted input) yetHIGHin a FastAPI/RAG ingestion pipeline where one 500 KB untrusted Markdown payload stalls a worker for ~27 minutes.ai-sec-gateautomatically contextualizesdocs//dev//scripts/DoS & SSRF findings toLOWwhile keeping runtime APIs and supply-chain/secret/RCE risks at full severity.
The 4-Level Maturity Scale
| Level | Label | Meaning |
|---|---|---|
| 1 | LEVEL_1_BROKEN |
Invisible Unicode / Trojan Source backdoor, hardcoded MCP secret, broken crypto/JWT bypass, unpinned trust_remote_code=True / torch.load pickle RCE, unsafe eval/Math.random() token/TLS bypass, or leaked .env. |
| 2 | LEVEL_2_NAIVE |
Fast-hash password trap (sha256(password)), ReDoS regex (CWE-1333), credentialed wildcard CORS, os.path.join traversal, unpinned MCP runner, timing-unsafe ==, undocumented Rust unsafe, or missing SAST / secret scanning / SHA-pinned CI. |
| 3 | LEVEL_3_HARDENED |
Clean semantic + SAST scan, salted slow KDFs (scrypt/bcrypt/argon2), secret scanning (gitleaks), and 40-char SHA-pinned GitHub Actions. |
| 4 | LEVEL_4_VERIFIED |
All Level 3 controls plus CI dependency vulnerability auditing (pip-audit / `npm |
Note on Level 3 vs. Level 4 locally: Running
ai-sec-gate check .executes fast static checks only, which cap at Level 3 (LEVEL_3_HARDENED). Pass--prove(ai-sec-gate check . --prove) to clone the repository into a temporary workspace, verify thatgit commithooks actively block planted violations, and reach Level 4 (LEVEL_4_VERIFIED).
Install & Integration (pre-commit & uvx)
1. Commit-time gate via .pre-commit-config.yaml
Pin ai-sec-gate to an immutable 40-char commit SHA (or release tag) alongside ruff and gitleaks:
repos:
- repo: https://github.com/rctruta/ai-sec-gate
rev: v1.1.0 # or 40-char commit SHA
hooks:
- id: ai-sec-gate
# Use args: [--min-level=2] for local-only repos without .github/workflows/ yet
# (while CI enforces --prove --with-deps-audit --min-level 4).
2. GitHub Action & Code Scanning (SARIF v2.1.0)
Drop ai-sec-gate into any GitHub Actions workflow in one step, optionally uploading SARIF v2.1.0 findings directly to the GitHub Security → Code scanning tab:
- name: Run ai-sec-gate
uses: rctruta/ai-sec-gate@6c60c2005814369b1e90bd511b94e931529ea16f # v1.0.0 (or pin latest v1.1.0 SHA below)
with:
min-level: "3" # set to "4" with prove: "true" and with-deps-audit: "true"
sarif-file: ai-sec-gate.sarif
- name: Upload SARIF to GitHub Code Scanning
if: always()
uses: github/codeql-action/upload-sarif@281020e373a1378352a9be2b78a47521d23c1071 # v3
with:
sarif_file: ai-sec-gate.sarif
Resolve the latest release SHA anytime via
git ls-remote https://github.com/rctruta/ai-sec-gate refs/tags/v1.1.0.
3. CI Level-4 verification & live Shields badge via uvx
# Run directly from PyPI and emit Shields.io badge JSON + SARIF v2.1.0
uvx ai-sec-gate check . --prove --with-deps-audit --min-level 4 \
--badge /tmp/sec-posture.json --sarif /tmp/ai-sec-gate.sarif
# Or pin to an immutable git tag / 40-char commit SHA
uvx --from git+https://github.com/rctruta/ai-sec-gate@v1.1.0 ai-sec-gate check . --prove --with-deps-audit --min-level 4
4. Developing ai-sec-gate from Source
Run these commands inside a local clone of ai-sec-gate (outside this repo, use uvx ai-sec-gate ... or uv tool install ai-sec-gate):
uv sync
# Fast static evaluation (caps at Level 3; prints tip when ready for --prove)
uv run ai-sec-gate check .
uv run python3 -m ai_sec_gate check . --with-clippy
# Full Level 4 verification (runs isolated red-team hook probes + JSON or Shields output)
uv run ai-sec-gate check /path/to/repo --prove --min-level 4 --format json
uv run ai-sec-gate check /path/to/repo --prove --format shields
# Run only the isolated hook prover against a local repository
uv run ai-sec-gate prove /path/to/repo
Continuous Posture, Live Badges, & Honest Scope Boundaries
A static badge pasted once into a README creates a false sense of security if posture later degrades. Production-grade enforcement for solo and multi-agent repositories relies on three operational habits:
- Scheduled CVE Drift Checks (
schedule: cron): While branch protection prevents code and hook regressions between commits, locked third-party dependencies can drop from Level 4 to Level 2 overnight when a new CVE is disclosed. Pairingpull_requestgates with a weekly GitHub Actionsscheduletrigger re-runs--with-deps-auditautomatically against fresh advisory databases. - Truth-Backed Endpoint Badges (
--badge FILE):--badgewrites a Shields.io Endpoint JSON payload (Level 4 · verifiedgreen down toLevel 1 · brokenred) before exiting non-zero. Publishing that JSON frommainand scheduled CI runs (for example to an unprotectedbadgesbranch) ensures the README shield reflects live repository health and automatically downgrades when a scheduled audit fails. - Defense-in-Depth Boundaries:
- Covered by automated gates:
.env& secret hygiene (gitleaks), broken and context-naive crypto/auth primitives, Rust// SAFETY:invariants, lockfile & 40-char GitHub Action SHA pinning, ecosystem CVE audits, and active pre-commit hook verification. - Outside static analysis (requires explicit setup & tests): Remote GitHub branch protection (
Require PR+ required status checks +Include administrators) must be enabled via GitHub repository settings or API, and application-specific authorization logic (such as cross-tenant IDOR boundaries) requires dedicated integration tests.
- Covered by automated gates:
Behavioral KDF & Verifier Test Helpers (ai_sec_gate.testing)
Verify in pytest that password KDFs apply fresh per-call random salts (catching deterministic sha256 or static-salt bugs), CSPRNG token generators have high entropy, and constant-time verifiers safely reject mutated or mismatched-length inputs:
import hashlib
import hmac
import os
import secrets
from ai_sec_gate.testing import (
assert_constant_time_verifier,
assert_salted_kdf,
assert_token_entropy,
)
def hash_pw(pw: bytes) -> tuple[bytes, bytes]:
salt = os.urandom(16)
return salt, hashlib.scrypt(pw, salt=salt, n=2**14, r=8, p=1)
def verify_pw(pw: bytes, stored: tuple[bytes, bytes]) -> bool:
salt, expected = stored
candidate = hashlib.scrypt(pw, salt=salt, n=2**14, r=8, p=1)
return hmac.compare_digest(expected, candidate)
assert_salted_kdf(hash_pw, verify_pw)
assert_token_entropy(lambda: secrets.token_urlsafe(24))
assert_constant_time_verifier(hmac.compare_digest, expected=b"mac-tag-bytes")
Semantic Rules & Language Adapters
Declarative defaults live in src/ai_sec_gate/rules.toml and can be overridden per target repository under [tool.ai_sec_gate] in pyproject.toml or .ai-sec-gate.toml.
| Rule / Adapter | Language | What it checks |
|---|---|---|
SEC-UNICODE-001 |
AI Surface | Trojan Source bidi overrides (CVE-2021-42574), invisible Unicode tag smugglers (U+E0000..U+E007F), and zero-width characters in AGENTS.md, CLAUDE.md, .cursorrules, SKILL.md, and code. |
MCP-SUPPLY-001 / MCP-SECRET-001 |
AI Surface | Unpinned npx/bunx/uvx/pipx packages, non-HTTPS remote URLs, and hardcoded literal credentials in .mcp.json / .cursor/mcp.json / .vscode/mcp.json. |
PY-CRYPTO-001 |
Python | Broken hash (md4, md5, sha1) used without usedforsecurity=False. |
PY-CRYPTO-002 |
Python | Fast hash (sha256, sha512, blake2b, etc.) applied to password material instead of scrypt / bcrypt / argon2. |
PY-CRYPTO-003 |
Python | Toy character-shift / XOR cipher (caesar, rot13, modular ord()) on secret or cipher functions. |
PY-AUTH-004 / PY-AUTH-005 / PY-CRED-001 |
Python | Timing-unsafe == on digests/tokens, disabled JWT signature verification (verify_signature=False / algorithms=['none']), hardcoded secret fallbacks in os.getenv/os.environ.get, and positional literal credentials. |
PY-NET-001 / PY-PATH-001 / PY-SSRF-001 |
Python | Credentialed wildcard CORS, unguarded os.path.join() / Path / untrusted traversal, and unvalidated dynamic outbound URLs (OWASP A01 / A10 SSRF). |
PY-EXEC-001 / PY-SQL-001 / PY-TLS-001 / PY-DESER-001 |
Python | Native AST checks for eval()/exec()/os.system()/shell=True, dynamic SQL formatting, verify=False/unverified SSL, and unsafe yaml.load() (OWASP A03 / A05 / A08). |
PY-AI-001 / PY-AI-002 |
Python | Unpinned HuggingFace trust_remote_code=True (missing 40-char revision SHA) and torch.load() without weights_only=True. |
PY-DOS-001 |
Python | Catastrophic ReDoS regex backtracking (CWE-1333: nested or overlapping unbounded quantifiers in re.*). |
RUFF-S* / PY-DEP-* |
Python | Delegates general SAST to ruff check --select S (skipped automatically when ruff-check + S is already in pre-commit) and pip-audit (--with-deps-audit). |
JS-SUPPLY-001 / JS-DEP-* |
JS / TS | Verifies lockfile presence (package-lock.json, pnpm-lock.yaml, yarn.lock, bun.lock) and runs npm / pnpm / yarn audit. |
JS-CRYPTO-001 / JS-CRYPTO-002 |
JS / TS | Catches broken hashes (md5/sha1) and fast hashes (createHash('sha256') / subtle.digest) applied to passwords. |
JS-RAND-001 / JS-AUTH-004 / JS-AUTH-005 / JS-CRED-001 |
JS / TS | Flags Math.random() on tokens/nonces, timing-unsafe === on digests, unverified jwt.decode() / algorithms: ['none'], and hardcoded secret fallbacks on process.env.*. |
JS-EXEC-001 / JS-TLS-001 / JS-NET-001 / JS-DOS-001 |
JS / TS | Flags eval(), new Function(), shell: true, rejectUnauthorized: false, credentialed wildcard/origin: true CORS, and ReDoS (CWE-1333). |
RS-SUPPLY-001 / RS-DEP-* |
Rust | Checks workspace Cargo.toml manifests for * versions or unpinned git deps (missing rev) and integrates cargo audit. |
RS-UNSAFE-001 / RS-CLIPPY-* |
Rust | Requires preceding // SAFETY: comments on production unsafe blocks and unsafe impls and integrates cargo clippy (--with-clippy). |
RS-CRYPTO-001 / RS-CRYPTO-002 / RS-AUTH-004 / RS-DOS-001 |
Rust | Catches MD5/SHA-1 calls, fast SHA-2/BLAKE hashes on passwords, non-constant-time ==, and ReDoS in backtracking fancy_regex/pcre2 crates (exempting linear-time regex::Regex). |
GO-CRYPTO-001 / GO-TLS-001 / GO-EXEC-001 / GO-SQL-001 / GO-PATH-001 / GO-AUTH-004 / GO-CRED-001 / GO-DEP-001 |
Go | Catches crypto/md5 & crypto/sha1, InsecureSkipVerify: true, exec.Command("sh", "-c", dynamic), fmt.Sprintf/+ SQLi, unguarded filepath.Join, timing-unsafe ==, os.Getenv secret fallbacks, and integrates govulncheck (--with-deps-audit). |
Baselines, Inline Suppressions, & .ai-sec-gate.toml
Adopt ai-sec-gate incrementally on legacy codebases without drowning in pre-existing findings:
# Snapshot existing findings into a content-fingerprinted baseline (survives line shifts)
uvx ai-sec-gate check . --write-baseline .ai-sec-gate-baseline.json
# Fail CI only on NEW findings not present in the baseline
uvx ai-sec-gate check . --baseline .ai-sec-gate-baseline.json
Inline suppressions require explicit rule IDs (never blind wildcards) on the flagged line or a dedicated comment line directly above it:
PATTERN = re.compile(r"...") # ai-sec-gate: ignore[PY-DOS-001] input length bounded to 128 chars
Repository-level defaults can live in .ai-sec-gate.toml (or [tool.ai_sec_gate] in pyproject.toml):
[scan]
exclude = ["legacy/**", "generated/"]
disable_rules = []
baseline = ".ai-sec-gate-baseline.json"
min_level = 3
max_snippets = 5
Repository Scaffolding
Seeded with init-agent-project from ai-agent-utils, enforcing stdlib claim/hygiene gates (.gates/), ruff (E9, F, B, S), gitleaks, external scratch/ symlink, and SHA-pinned CI.
uv run pytest
sh .gates/tests/prove_gates.sh
License
Copyright 2026 Ramona C. Truta. Code is licensed under the Apache License 2.0. Documentation is licensed under CC BY 4.0.
Metadata
Release files for ai-sec-gate 1.2.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| ai_sec_gate-1.2.0.tar.gz | 142.9 kB | Without provenance | Details for ai_sec_gate-1.2.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| ai_sec_gate-1.2.0-py3-none-any.whl | Python 3 | none | any | Details for ai_sec_gate-1.2.0-py3-none-any.whl |
Total release size: 261.1 kB
Release files / ai_sec_gate-1.2.0.tar.gz
| Download URL | ai_sec_gate-1.2.0.tar.gz |
|---|---|
| Size | 142.9 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
166fcb50afd41a63ab2ad8df897061e104b86b338cde8855585305e6a7f689c7
|
|
BLAKE2b-256 checksum How to use checksums |
4a13a6817c004e289e82c45f2d7dec0f697930d70c0a22bef240437d23a806d8
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
uv/0.13.13 {"installer":{"name":"uv","version":"0.13.13","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Release files / ai_sec_gate-1.2.0-py3-none-any.whl
| Download URL | ai_sec_gate-1.2.0-py3-none-any.whl |
|---|---|
| Size | 118.2 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
92b799ceff4bc2d4983313c57ca240a9613ba245e9436c68e7d19033b8b10515
|
|
BLAKE2b-256 checksum How to use checksums |
a332b7ea140be9b2de8c01c8724bd289e17821da57274063121cfcaf54398674
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
uv/0.13.13 {"installer":{"name":"uv","version":"0.13.13","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Security for ai-sec-gate 1.2.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.