How to secure AI-generated code: a five-step process

To secure AI-generated code, stop relying on someone reading every line and put automatic checks at five points: rules for the agent, a scan inside the agent loop, a secret check before commit, a gate in CI and a test of the running application before release. Then make the agent fix what the checks find and prove each fix with a new scan.

Last reviewed: November 2026

Where the checks go

AI-generated code needs the same checks as any other code. Two things change: there is far more of it, and its author cannot explain a decision a week later. A check that depends on a person noticing something does not scale to that volume, so the checks have to be automatic and placed where the code passes anyway.

The need is measured. In an academic study of GitHub Copilot by Pearce and co-authors, approximately 40% of the programs generated for security-relevant scenarios were vulnerable. In a user study by Perry and co-authors, participants with an AI assistant wrote significantly less secure code and were more likely to believe it was secure. The OWASP Top 10 for LLM Applications recommends secure coding practices and cross-checking of model output against trusted sources.

The process below has five points. Each catches what the previous one cannot.

StepWhereWhat it catchesCan it block?
1Rules for the agentKnown mistakes, before they are writtenNo, it is guidance
2In the agent loopInjection, secrets, weak cryptography, vulnerable packages in the code just writtenThe agent fixes before it reports done
3Before commitSecrets and files that must not enter the repositoryYes, locally
4In CIEverything the earlier steps missed or skipped, on every merge requestYes, for the whole team
5Before releaseFlaws visible only in the running application, and access controlYes, release sign-off

Step 1. Give the agent your rules before it writes

The cheapest finding is the one that never appears. Put your security rules, in plain language, into the instructions your agent reads at the start of a task. Keep them short and specific to your code base. General advice such as "write secure code" changes nothing.

Security rules for the agent
- Build SQL with parameters. Never format user input into a query.
- Every query for a user-owned record filters by the owner's id.
- Read credentials from the secret manager. Never write them in source or tests.
- Do not add a dependency without stating why. Never invent a package name.
- After each change: run the security scan, fix the findings, scan again.

Limit what the agent can read as well. In Claude Code, for example, the permissions documentation describes deny rules such as Read(./.env) that keep the agent's file tools away from secret files.

Treat this step as guidance, not enforcement. Anthropic says the same about the rules file of its own security guidance plugin: the plugin documentation describes those rules as guidance for the reviewer, not deterministic guardrails, and recommends a hook or a CI check for hard enforcement.

Step 2. Scan inside the agent loop

This step is new with coding agents. The agent can call a scanner itself, so the code is checked right after it is written, while the agent still has the context to fix it.

Two kinds of check fit here, and they work differently:

  • The agent's own model-based review. Good at intent and logic. It can miss issues, and two runs can differ. See the guide to Claude Code security review for what it covers.
  • An independent scanner called through its API. Static analysis for the code, composition analysis for the dependencies. It works by rules, so the result is repeatable and does not share the author's blind spots.

To set up the second one, connect your agent to a scanner. With DerScanner you copy an API key, point the agent to docs.derscanner.com, and it reads the API description and connects by itself. It takes three minutes and needs no plugin and no change to your pipeline. Then the instruction is one sentence:

Scan this with DerScanner. Fix every finding, then scan again
and show me the difference between the first and the last scan.

The agent sends the code, reads the findings with the file and the line, fixes them and repeats the scan.

Step 3. Stop secrets before commit

A secret that reaches the repository history has to be rotated, so this check belongs before the commit, not after it. Keep the pre-commit stage fast and narrow: secrets, key files, environment files. Leave full analysis to steps 2 and 4.

.git/hooks/pre-commit
#!/bin/sh
# Refuse to commit environment files and private keys.
if git diff --cached --name-only | grep -E '(^|/)\.env$|\.pem$|id_rsa$'; then
  echo "Commit blocked: secret file staged. Remove it from the commit."
  exit 1
fi

A hook like this runs for people and for agents alike, because both commit through git. It is a convenience, not a control: a local hook can be skipped. The control is the next step.

Step 4. Gate every merge request in CI

CI is the first place where the check does not depend on the agent or on the developer's machine. Run two scans on every merge request:

  • Static application security testing (SAST) on the code: injection, hardcoded credentials, weak cryptography, unsafe configuration.
  • Software composition analysis (SCA) on the dependencies: known vulnerabilities in the packages and versions the change adds.

Fail the pipeline on new high-severity findings and report the rest. Judge the change, not the whole backlog, or the team will stop trusting the gate.

Keep this gate even if the agent already reviews itself. Anthropic's documentation draws the same picture: the security guidance plugin page lists your existing static analysis and dependency scanners in CI as a separate layer, and the Claude Security plugin documentation says model-based scanning complements the deterministic checks those tools provide.

Step 5. Test the running application before release

Some flaws do not exist in the source. They exist in the deployed system. Before a release:

  • Run a dynamic scan (DAST) against a staging build. It sees the configuration that is really in effect: debug endpoints, permissive cross-origin settings, missing headers.
  • Test access control with two accounts. Can user A read user B's record by changing an id? A missing authorization check is a missing line, and tools that match patterns find it poorly.
  • Have a person review the sensitive changes: authentication, permissions, payments, personal data.
  • Keep the report. The scan results for the release are your evidence for a team lead or an auditor.

The flaw classes these checks target, with code examples, are in the guide to vibe coding security risks.

Make the agent fix and re-verify

Finding a flaw is half of the work. An agent will fix it in seconds, and the fix is new, unreviewed code. So the rule is simple: a finding is closed when a new scan no longer reports it, not when the agent says it is fixed.

  1. Scan. The scanner returns findings with the file, the line, an explanation and a recommendation.
  2. Fix. The agent changes the code. One finding, one small change.
  3. Scan again and compare. The fixed findings are gone, and no new ones have appeared.
  4. Repeat until the list is empty, or stop and ask a person.

Three guard rails keep the loop honest:

  • The agent does not suppress findings. Marking a finding as a false positive or adding an exclusion is a human decision, recorded with a reason.
  • The loop has a limit. After a few passes without progress the agent stops and reports what is left. A flaw it cannot fix is usually a design question.
  • A person reads the fix diff for sensitive code. A fix that deletes the vulnerable feature also makes the finding disappear.

With these five steps in place, the agent keeps its speed, and every change it makes has passed at least one check that it did not write itself.

Frequently Asked Questions

Try DerScanner on your own code, free

Start with step 2: connect your coding agent to DerScanner, and it scans the code it writes, fixes the findings and scans again.

Request a free pilot. We give you access and help with the first scan. It works in the cloud and on-premise.

Want to describe your project first? Take the 2-minute PoC survey