Core content
Part 1: The core rule: AI code is untrusted by default
One rule, once it becomes a reflex, prevents most of the damage:
All AI-generated authentication, cryptography, and input-handling code is untrusted until it passes (1) manual human review and (2) automated scanning. No exceptions, and no "it's just a small change."
The rule is not anti-AI. It is the posture you already apply to a junior contractor's first pull request or a copied forum answer, made formal and enforced because the volume is now far higher. The model produces plausible, idiomatic, average code. Average internet code is full of md5, string-concatenated SQL, disabled TLS verification, and hardcoded fallback secrets.
AI suggests code
│
▼
┌──────────────────────┐ Is it auth / crypto / input
│ Classify the diff │────► handling / secrets / deps?
└──────────────────────┘ │
│ no │ yes
▼ ▼
normal review UNTRUSTED LANE:
manual security review
+ SAST + secret scan
+ dependency check
│
pass ALL ──► merge
fail any ──► fix or reject
Do assume the AI optimized for "looks right and compiles," never for "is secure under attack." Don't let its confident tone or clean formatting stand in for verification.
The dangerous diffs are the small ones. A 400-line feature gets reviewed. A quick fix to a token comparison or a regex gets rubber-stamped, and that is where the subtle flaw lands.
Part 2: Five high-risk categories and secure review patterns
Any diff that touches one of these five categories enters the untrusted lane. For each, here is what AI tends to get wrong and what good looks like.
2.1 Authentication and authorization
AI often produces comparisons that are not constant-time, missing authorization checks (it authenticates but never checks permission), and broken session or token handling.
# ✗ AI-typical: timing-attack-vulnerable token check, no authz
def check_api_key(provided):
if provided == STORED_API_KEY: # short-circuits on first mismatch
return True
return False
# ✓ Secure: constant-time compare + explicit authorization
import hmac
def check_api_key(provided, user):
if not hmac.compare_digest(provided.encode(), STORED_API_KEY.encode()):
return False
return user.has_scope("api:read") # authn AND authz
Review questions: Does it authenticate and authorize? Are comparisons constant-time? Are tokens validated for signature, expiry, and audience, not just presence?
2.2 Cryptography
AI defaults to whatever was most common in its training data: MD5 or SHA-1 for passwords, ECB mode, static initialization vectors, Math.random() for tokens, and homegrown crypto.
// ✗ AI-typical: fast hash for passwords, predictable token
const hash = crypto.createHash('md5').update(password).digest('hex');
const token = Math.random().toString(36).slice(2);
// ✓ Secure: memory-hard password hash + CSPRNG token
const hash = await argon2.hash(password); // or bcrypt/scrypt
const token = crypto.randomBytes(32).toString('hex'); // CSPRNG
Review questions: Is this a password (needs bcrypt, scrypt, or Argon2) or a digest (SHA-256 is fine)? Does randomness come from a cryptographically secure generator? Is a vetted library in use, with no hand-rolled crypto?
2.3 Input validation and injection
Injection is the headline risk. AI concatenates SQL strings, shells out with user input, and renders unescaped HTML. The 2.7 times cross-site-scripting multiple in the CodeRabbit study sits here.
# ✗ AI-typical: SQL injection
cur.execute(f"SELECT * FROM users WHERE email = '{email}'")
# ✓ Secure: parameterized query
cur.execute("SELECT * FROM users WHERE email = %s", (email,))
Review questions: Is every external input parameterized or escaped at the boundary it crosses (SQL, shell, HTML, LDAP, file path)? Is validation an allowlist, not a blocklist? Apply the same scrutiny to any input that came from an LLM response.
2.4 Secrets
AI hardcodes API keys, embeds "example" credentials that turn out to be real, and logs tokens.
# ✗ AI-typical: hardcoded fallback secret + logging it
API_KEY = os.getenv("API_KEY", "sk-live-3f9a...") # real-looking fallback
log.info(f"calling upstream with {API_KEY}")
# ✓ Secure: fail closed, never log
API_KEY = os.environ["API_KEY"] # raises if missing — fail closed
log.info("calling upstream") # never log the secret
Review questions: Is there any literal that looks like a key, token, or password? Is any secret in logs, error messages, or test fixtures? Does the code fail closed when a secret is absent?
2.5 Dependencies and supply chain
AI invents package names that attackers can then register ("slopsquatting"), pins vulnerable versions, and pulls in abandoned packages.
Review questions: Does every imported package exist, and is it the one you intended rather than a lookalike? Is it pinned to a known-good version with a lockfile? Run a dependency check before you trust any AI-added import.
If the assistant suggests a package you've never heard of, look it up before you install it. Every invented name is a registration opportunity for an attacker, and the dependency check in Part 5 is the control that catches it.
"The linter passed, so it's fine." Linters catch style. Static analysis catches some patterns. Neither understands your authorization model. Manual review of the untrusted lane is not optional.
Part 3: Prompt injection through comments, docstrings, issues, filenames, and config
Since 2025, content the assistant reads can command it, not just mislead it. Any text the AI takes in (your repository, an issue, a dependency's README, a filename, a configuration file) is a potential instruction. This is LLM01, prompt injection, from the OWASP Top 10 for LLM Applications (2025), landing directly in the software delivery process.
Attacker plants instruction in repo content
(comment / docstring / filename / config / issue / README)
│
▼
Engineer asks assistant to "refactor this file"
│
▼
Assistant reads the hidden instruction as a command
│
▼
Assistant exfiltrates secrets, adds a backdoor,
rewrites its own config, or runs a tool action —
inside the engineer's trust context
Documented 2025 cases (teach the pattern, not just the CVE number):
| Case | Vector | Lesson |
|---|---|---|
| CVE-2025-53773: GitHub Copilot remote code execution | Prompt injection in repository content changed the assistant's settings file to allow commands to run without approval, then ran code on the developer's machine | The assistant's configuration and tool permissions are attack surface |
| CVE-2025-54135: Cursor MCP configuration rewrite | An injected prompt made the agent write a new entry into its MCP configuration file, which launched an attacker's command | An agent that can edit its own tool configuration can grant itself new powers |
| Reported pattern: agent with write access reads a public issue | Instructions in an issue body, processed by an agent with broad repository access, led it to leak or change private content | Never give an agent that reads untrusted issues broad write scope |
| Reported pattern: hidden instructions in rules or config files | Invisible characters or instructions in shared assistant rules files steered generated code toward backdoors | Review the diff on the assumption that it may be adversarial |
Defenses (apply all of them):
- Treat repository content the AI reads as untrusted input, like user input. Hidden Unicode, zero-width characters, and "ignore previous instructions" in a docstring are payloads.
- Lock the assistant's own configuration. Keep
settings.json, rules files, and MCP configuration under version control, require review for any change to them, and alert when an agent writes to them. Both 2025 CVEs worked by rewriting configuration. - Turn off auto-run. No shell or tool execution without approval in editors that read untrusted content.
- Review the diff, not the prompt. Judge what the AI produced, because content you didn't write may have hijacked the prompt.
- Scan incoming issues and pull requests from outside the organization for injection markers before an agent processes them.
Your coding assistant has your privileges, and it will obey instructions hidden in any file it opens. Would you run a shell command written by a stranger in a public issue? Your agent might.
Part 4: Coding agents: secrets and the narrowest token
Coding agents now open pull requests, run tests, and in some teams merge their own changes. Whatever the agent can reach, an injected prompt can reach too. Two rules contain most of the risk: keep secrets out of the agent's environment, and give the agent the narrowest token that does the job.
┌──────────────────────── AGENT ENVIRONMENT ───────────────────────┐
│ reads: repo, issues, PR text, dependency READMEs (UNTRUSTED) │
│ │
│ holds: ✗ cloud admin keys ✗ production DB credentials │
│ ✗ personal access tokens with org-wide write │
│ ✓ short-lived, repo-scoped token ✓ test-only fixtures │
│ │
│ egress: allowlisted package registries and the model API only │
└──────────────────────────────────────────────────────────────────┘
│ proposes change
▼
human review + CI scans ──► merge (by a person or a separate, approved step)
Rules for the agent environment:
- No long-lived secrets. Don't put production credentials, cloud admin keys, or personal access tokens into the agent's environment variables, workspace, or prompt. If a task needs a credential, issue a short-lived one for that task and revoke it after.
- A separate identity per agent. Run each coding agent as its own bot account or app installation, never as an engineer's personal token. You can then see what the agent did and revoke it alone.
- The narrowest token that works. Start CI jobs at read-only and grant write scopes one at a time, only where the job needs them.
- No secrets on untrusted triggers. Never run an agent with repository secrets on pull requests from forks or on issues from outside the organization.
- Restrict network egress to the package registries and model endpoint the job needs, so a hijacked agent can't post your code elsewhere.
- A person approves the merge. An agent that merges without per-action approval is an autonomous agent (autonomy level 4 on the assessment's scale). Before you allow that, it needs every gate 6.6 control in Module 8.
Minimal GitHub Actions wiring for an agent job that proposes changes:
name: coding-agent
on:
issues:
types: [labeled] # runs only when a maintainer applies the label
permissions:
contents: read # default: read-only for the whole workflow
jobs:
propose:
if: github.event.label.name == 'agent-ok'
runs-on: ubuntu-latest
permissions:
contents: write # only this job may push a branch
pull-requests: write # and open a PR; it cannot merge or change settings
env:
MODEL_API_KEY: ${{ secrets.AGENT_MODEL_KEY }} # model access only
# no cloud, database, or deploy secrets in this job
steps:
- uses: actions/checkout@v4
with: { persist-credentials: false }
- name: Run agent in a sandbox with egress allowlist
run: ./scripts/run-agent.sh --branch "agent/${{ github.event.issue.number }}"
The fastest way to turn a prompt injection into a breach is a coding agent that runs with an engineer's personal token. That token usually reaches every repository the engineer can reach. Replace it with a repo-scoped bot identity this week.
Part 5: Automated scanning in CI for AI-generated code
You need both layers, because neither is enough alone. Manual review catches logic and authorization flaws. Automation catches the high-volume, pattern-based flaws at machine speed, which is the scale at which AI produces them.
PR opened ─► CI pipeline
├─ Secret scanning (gitleaks / trufflehog / GH secret scanning)
├─ SAST (Semgrep / CodeQL / Snyk Code)
├─ SCA / deps (Dependabot / Snyk / OSV-scanner) ── catches lookalikes & CVEs
├─ DAST (staging) (OWASP ZAP / Burp) ── runtime, on deploy
└─ Policy gate block merge on high-severity findings
Minimal GitHub Actions wiring, with Semgrep and gitleaks as the floor:
name: secure-ai-review
on: [pull_request]
permissions:
contents: read
jobs:
scan:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: SAST (Semgrep)
uses: returntocorp/semgrep-action@v1
with: { config: "p/owasp-top-ten p/secrets" }
- name: Secret scan (gitleaks)
uses: gitleaks/gitleaks-action@v2
- name: Dependency / SCA
uses: actions/dependency-review-action@v4 # fails on vulnerable/lookalike adds
- Secret scanning: run it on every pull request and as a pre-commit hook so secrets never reach history. Rotate anything that lands in a commit, even if the commit is reverted.
- Static analysis (SAST): tune rulesets to your stack. Start with the OWASP Top Ten and secrets packs. Make high-severity findings a blocking gate, not a warning.
- Dependency review (SCA): the main defense against slopsquatting and known-vulnerable pins. Block merges that add unknown or vulnerable packages.
- Dynamic testing (DAST): runs against a deployed staging build to catch runtime issues (authorization, injection in context) that static analysis misses.
Stand up the scanning gate first, then turn up AI volume. In IIIBC's field experience, teams that reverse the order spend the following quarter cleaning up what the assistant shipped.
Part 6: Pair velocity with quality, and set nudges
A velocity number reported alone misleads. AI-written pull requests carry 1.75 times more logic errors and about 1.6 times more security findings (CodeRabbit, December 2025), so higher throughput changes the quality picture, and you won't see the change unless you measure it. Never report a velocity KPI without its paired guardrail. DORA's change failure rate is the paired metric most boards already recognize.
| Velocity KPI | Mandatory paired quality or security KPI |
|---|---|
| Pull requests per engineer per week | Change failure rate (DORA) |
| AI code share (% of lines) | Code turnover ratio (lines rewritten or reverted within 2 weeks) |
| Cycle time or time to merge | Review coverage of untrusted-lane diffs (% scanned and human-reviewed) |
| Features shipped | Escaped vulnerabilities (findings that reach production) |
| AI-suggested lines accepted | Static-analysis and secret-scan findings per 1,000 AI lines |
Digital nudges make the secure path the default. A nudge is a small, automated prompt at the moment of decision:
- A pull request template with the secure-review checklist as a required checkbox block.
- A commit hook that flags likely secrets and formatted SQL strings before push.
- CODEOWNERS routing any change to
auth/,crypto/, assistant configuration, or.github/workflows/to a security reviewer. - A bot comment on pull requests labeled
ai-generatedthat reposts the untrusted-lane checklist.
Engineers skip security review because the safe path has more friction than the fast path, not because they're careless. Nudges flip that. Make the checklist one click, make the scan automatic, and assign the security reviewer automatically.