Security review when AI agents write the code
More code, written by a tool that sounds sure and knows nothing about your auth model: tier the paths, gate every pull request in code, keep a named human on the code that holds tenants apart, and give the agent itself no more power than an intern
A coding agent opens a pull request that changes how Larkhollow's connector service loads a customer's tickets. The build is green, the agent wrote eight new tests and an AI review bot left no comments. What should decide whether it merges?
When agents write a growing share of your code, two things change for security. The code changes: there is more of it, it looks finished, and it is written by something that does not know your authorisation model. And the author changes: the agent is a new actor in your repository and your CI, with tokens, network access and tools, that reads text written by strangers. This chapter covers both, and the review system that holds up as the share grows.
It does not repeat what other chapters own. Reading a diff like an attacker, and the SAST, DAST and SCA tools, are in secure code review and AppSec. Agents inside the product are in AI and agent security. Pinning, provenance and judging a dependency are in software supply chain security. What an individual engineer checks before asking for review is in working with AI coding agents, and team agreements on disclosure and change size are in managing a team that works with AI coding agents. Your job is the layer above: which paths need what, which checks run in code on every pull request, and what permissions the agent gets.
The model: more diffs, the same bugs, a more confident reviewer
Most of what goes wrong in agent-written code is familiar. Injection, a missing authorisation check, a secret in a file, a dependency nobody chose. What changes is the rate, and where the bugs hide.
Volume. If 120 engineers each supervise agents, the number of diffs rises faster than the number of reviewers. A process where security reads every change to a sensitive file stops scaling the month agents arrive.
Plausibility. A human’s insecure code often looks rushed. An agent’s looks tidy, with a description, comments and tests. Review habits tuned to spot sloppy code relax on code that looks careful.
Missing context. The agent knows the files it read. It does not know that every query in the connectors service must carry the tenant id, that the admin role is never granted through the public API, or that a field is personal data. The bugs that matter most in a multi-tenant SaaS are breaches of rules that live in people’s heads and a few files the agent did not open.
The consequence is a design rule. Anything you want enforced on every change must be enforced by code that runs on every change, and human attention goes where code cannot decide.
What changes when an agent writes the diff
| Change | Why it happens | What catches it |
|---|---|---|
| A query, cache key or object lookup without the tenant id | The agent copies a neighbouring pattern and has no model of tenancy | Tenant-isolation tests owned by security; a code owner on tenancy paths |
| An invented or look-alike package | Models produce plausible names, and repeat them | A new-dependency check against an allow-list and the registry’s metadata |
| An insecure pattern copied from training data or the codebase | The model reproduces common code, and common code is often old | SAST rules, tuned for your stack |
| Tests that agree with the code | One reading of the task produced both | Tests written from a separate source; mutation testing on sensitive modules |
| A secret in a commit, a fixture or a log line | Pasted into a prompt, then echoed back into a file | Secret scanning with push protection |
| Quiet edits: a loosened check, a deleted test, a CI file changed | The agent removes what was in its way | Path rules that require an owner for CI, auth and test-policy files |
The first row is the one to lose sleep over, so here it is in TypeScript. The connectors service loads tickets that a customer’s ticketing system has synced. Ticket numbers come from the customer’s system, so two tenants can have ticket 4417.
// Agent's version: reads well, passes its tests, leaks across tenants
export async function getTicket(externalId: string) {
return db.ticket.findFirst({ where: { externalId } });
}
// What the codebase's rule requires: tenant comes from the request context
export async function getTicket(ctx: RequestContext, externalId: string) {
return db.ticket.findFirst({
where: { tenantId: ctx.tenantId, externalId },
});
}
The agent’s tests create one tenant, so they pass. SAST sees no tainted sink. Only a test with two tenants, or a reviewer who knows the rule, catches it. The IDOR and tenant isolation lessons show the mechanism; auth for SaaS and public APIs covers the design. A structural fix, where the data layer refuses a query on a tenant-scoped table without a tenant id, beats both, because the agent cannot forget what the code will not let it write.
What the published evidence says
You will be asked whether AI-written code is less secure. The honest answer is that the studies point one way and each has limits you should state.
Pearce et al., “Asleep at the Keyboard?” (IEEE S&P 2022). The authors wrote 89 scenarios aimed at weaknesses from MITRE’s Top 25 CWEs and had GitHub Copilot complete them, producing 1,689 programs in Python, C and Verilog. They judged about 40% vulnerable, using CodeQL plus manual inspection. The limits: the scenarios were built to invite specific weaknesses, the tool was the 2021 Copilot, and a program counted as a completion, not a reviewed change. A targeted replication by Majdinasab et al. (2023) on newer Copilot versions, Python only, found the share of vulnerable suggestions fell from 36.54% to 27.25%. Better, and still a quarter.
Perry et al., “Do Users Write More Insecure Code with AI Assistants?” (ACM CCS 2023). A user study: 47 participants, 33 with an assistant built on OpenAI’s codex-davinci-002 model and 14 without, on five security-relevant tasks such as encryption, signing and a SQL insert. Those with the assistant wrote significantly less secure code and were more likely to believe it was secure. Those who trusted the assistant less and engaged more with their prompts produced fewer vulnerabilities. The authors name the limits: mostly university students, an artificial setting, a small sample. The finding that carries over is the confidence gap, because it describes your reviewers too.
Spracklen et al., “We Have a Package for You!” (USENIX Security 2025). 576,000 code samples from 16 models in Python and JavaScript. The average share of hallucinated packages was at least 5.2% for commercial models and 21.7% for open-source models, with 205,474 unique invented names. Re-running 500 Python prompts that had produced a hallucination ten times each, 43% of the invented names came back in all ten runs. That repetition is what makes the attack work: an attacker can find the names and register them. Seth Larson, the Python Software Foundation’s developer-in-residence, is credited with naming this slopsquatting. Neither the paper nor the industry write-ups cite a confirmed malicious campaign, so treat it as a demonstrated risk with a cheap control.
Vendor reports. Veracode’s 2025 GenAI Code Security Report ran 80 coding tasks across more than 100 models and reported security flaws in 45% of cases, with larger models doing no significantly better than smaller ones. It is a vendor’s benchmark of single completions, so use it for the direction, not the number.
What none of these measures is your situation: agents working in your repository, with your tests and your reviewers, against your auth model. The published work tells you to expect insecure code at a meaningful rate and overconfident reviewers. Your own measurements, below, tell you whether your system catches it.
The coding agent is an actor with permissions
An agent that opens pull requests holds credentials. Think of it as a new joiner who works fast, never sleeps and does what any text in front of it says. The identity chapter’s three questions apply: whose authority, what it opens, how long it lasts.
Prompt injection through the work itself. The agent reads issues, pull request comments, dependency READMEs and web pages. In May 2025 Invariant Labs showed an agent connected to the official GitHub MCP server, asked to look at a public repository’s issues, reading a planted issue that told it to pull data from the user’s private repositories and publish it in a public pull request (Invariant Labs, 2025). The MCP server code had no bug. The agent held a token that could read everything, and read text a stranger wrote. The MCP chapter and AI and agent security cover the mechanism; your part is the token.
Over-broad CI tokens. In July 2025 AWS reported that an attacker had used a GitHub token with overly broad permissions in a build configuration to commit malicious code to the open-source repository of the Amazon Q Developer extension for VS Code, and that version 1.84.0 shipped with it in an automatic release (AWS-2025-015). The code failed to run because of a syntax error. The lesson is about the token, not the model: a credential in the pipeline that could write to the release path.
Least privilege for agents in CI looks like this.
| Permission | Default for a coding agent | Why |
|---|---|---|
| Repository contents | Read; write only to its own branch | A planted instruction cannot push to main |
| Merge and approve | Never | The agent’s work needs a human who did not ask for it |
| Workflow runs on its branch | Held until a human approves | Its code cannot run with CI secrets before anyone has looked |
| CI and deploy secrets | None | A build step it writes cannot read what it was never given |
| Network egress | An allow-list: the registry proxy and the docs it needs | Data leaves by request; no request, no leak |
| Other repositories | None unless the task needs one | The Invariant demo needed cross-repository read |
| MCP servers | A pinned, reviewed list | Each server is code with your permissions |
The vendors document most of this. GitHub’s risks and mitigations page for its cloud coding agent says the agent can push to a single branch, that only users with write access can trigger it, that the person who asked for the pull request cannot approve it, and that by default workflows do not run until the agent’s code is reviewed (GitHub Docs). Claude Code’s security page describes a permission system, sandboxing with network isolation, and managed settings for organisation-wide policy, and, for its cloud sessions, a short-lived credential scoped to the session, with your branch protection rules and rulesets deciding which branches a session can push to (Claude Code docs). Read the page for every agent your engineers use, and check that the defaults you are relying on are on.
For your own workflows, GitHub’s secure use reference says to set the default GITHUB_TOKEN permission to read-only for contents and raise it per job, and to avoid pull_request_target and workflow_run with untrusted code (GitHub Docs). An agent that writes workflow files is a reason to put .github/ under a code owner.
Prompts are the other direction of leakage. Engineers paste stack traces, config and sometimes credentials into a session, and the agent may write them back into a fixture or a test. Secret scanning with push protection is the control that does not depend on anyone remembering; a written rule on what may enter a prompt is the policy, and the rotation runbook in the secrets rotation lesson is what you do when both fail.
The review system
Four parts: tiers, gates, the human read, and the second reader.
Tier the paths
Not every line deserves the same review. Name the paths where a mistake breaks tenant isolation, authentication, money or the pipeline, and treat them differently from everything else.
| Tier | Paths (Larkhollow example) | What a merge needs |
|---|---|---|
| 1 | src/auth/, src/tenancy/, src/connectors/credentials/, src/billing/, .github/, CODEOWNERS |
All gates green, approval from a named code owner who did not request the change |
| 2 | Public API handlers, data-layer models, anything handling customer data | All gates green, one reviewer from the owning pod |
| 3 | Everything else | All gates green, one reviewer |
GitHub requests code owners automatically when a pull request touches their paths, and branch protection or a ruleset can require their approval. Its documentation adds that the CODEOWNERS file needs an owner itself, or anyone can edit their way out of the rule (GitHub Docs).
# .github/CODEOWNERS
/src/auth/ @larkhollow/security @larkhollow/identity-owners
/src/tenancy/ @larkhollow/security @larkhollow/tenancy-owners
/src/connectors/credentials/ @larkhollow/security @larkhollow/connectors-leads
/src/billing/ @larkhollow/billing-owners
/.github/ @larkhollow/security
/.github/CODEOWNERS @larkhollow/security
The tier applies whoever wrote the code. Writing the policy as human versus agent invites argument about what counts as agent-written; writing it by path does not.
Gates on every pull request
Gates are code. They run on every change, agent or human, and a red gate blocks the merge.
- SAST, tuned for TypeScript and your frameworks, blocking only on rules you have checked for false positives. Secure code review and AppSec covers tuning.
- Secret scanning with push protection, so the secret never reaches the remote.
- New-dependency check. Any change to
package.jsonthat adds a direct dependency fails unless the name is on an allow-list or a person approves it. The check asks the registry how old the package is and how many maintainers it has, because an invented name an attacker registered last week looks very different from a ten-year-old library. - Authorisation and tenant-isolation tests, owned by security in a path the agent cannot change without a tier-1 review. They create two tenants and assert that every endpoint refuses the other tenant’s ids.
A sketch of the dependency check, run in CI against the base branch:
// scripts/check-new-deps.ts
import { readFileSync } from "node:fs";
const allow = new Set(JSON.parse(readFileSync("security/allowed-deps.json", "utf8")));
const base = JSON.parse(readFileSync("base/package.json", "utf8"));
const head = JSON.parse(readFileSync("package.json", "utf8"));
const added = Object.keys({ ...head.dependencies, ...head.devDependencies })
.filter((n) => !(n in { ...base.dependencies, ...base.devDependencies }));
let failed = false;
for (const name of added) {
if (allow.has(name)) continue;
const res = await fetch(`https://registry.npmjs.org/${encodeURIComponent(name)}`);
if (res.status === 404) { console.error(`${name}: not on the registry`); failed = true; continue; }
const meta = await res.json();
const ageDays = (Date.now() - Date.parse(meta.time.created)) / 86_400_000;
console.error(`${name}: ${Math.round(ageDays)} days old, ` +
`${meta.maintainers?.length ?? 0} maintainers: needs a security approval`);
failed = true;
}
process.exit(failed ? 1 : 0);
The check fails on every new name not on the allow-list, and prints the facts a reviewer needs. How to judge the dependency, and the delay before adopting new releases, belongs to software supply chain security.
And the shape of a tenant-isolation test:
it("returns only the caller's own tenant's ticket", async () => {
const a = await seedTenant(); const b = await seedTenant();
const ticket = await seedTicket(b, { externalId: "4417" });
await seedTicket(a, { externalId: "4417" });
const res = await api(a.token).get(`/v1/tickets/${ticket.externalId}`);
expect(res.body.tenantId).toBe(a.id);
});
What a human still has to read
Gates catch patterns. A human on a tier-1 change reads for the rules a gate cannot know.
- Where does identity come from? Tenant and user must come from the verified session or token, never from the body, a header the client sets, or a parameter the agent added.
- What did it change besides the task? Open the file list first. A loosened check, a deleted test, a widened catch, a touched workflow.
- Do the tests prove the rule, or the code? At least one test must come from somewhere other than the agent: the security-owned suite, the spec, a captured request.
- What does failure do? A fallback that grants access, an error path that skips the check.
- Can the author explain it? The engineer who asked the agent answers for every line, as working with AI coding agents sets out.
AI review as a second reader
AI reviewers find real bugs, and they read every line at a volume no person matches. Use them. But they are a reader, not a gate, for three reasons. They read the pull request text, which an attacker can write. They know your auth model only as well as the context you give them. And they share the blind spots of the model that wrote the code. Anthropic’s security review GitHub Action says in its own README that it is not hardened against prompt injection and should only review trusted pull requests (anthropics/claude-code-security-review). GitHub’s cloud agent now runs CodeQL, secret scanning and an advisory-database check on new dependencies before it finishes a pull request (GitHub changelog, October 2025), which is welcome and runs inside the agent’s own process. Keep your gates in your CI, where the agent cannot switch them off.
Measuring whether it works
A policy you do not measure turns into a document. Track four things monthly.
- Origin and tier. Merged pull requests by tier and by origin (agent-opened, agent-assisted, human). Without the split you cannot say anything else.
- Gate catches. What each gate blocked, and how many blocks were real. A gate that never fires is either unneeded or broken.
- Escapes. Security bugs found after merge, by pentest, the disclosure inbox, an incident or your own audit, traced back to the pull request and its origin and tier. This is the number that matters, and it is small and slow, so count it over quarters.
- Review depth on tier 1. Time between review request and approval against diff size. A 600-line approval in four minutes is a rubber stamp.
One active test is worth running quarterly, as a rule of thumb: plant a known flaw, such as a dropped tenant filter, in a tier-1 pull request with the engineering manager’s agreement, and see whether review catches it. Announce afterwards that it was a drill. It measures the human layer directly.
Where practitioners disagree
| Question | One view | The other view |
|---|---|---|
| Should agents touch tier-1 code at all | Forbid it: the paths are small and the risk is large | Forbidding pushes the same code through a laptop session with less visibility; gate it instead |
| Label agent-written pull requests | Yes, reviewers should read them differently | The risk is in the path, not the author; label for measurement, review by tier |
| AI review as a required check | It catches what tired humans miss | It is attacker-readable and fallible; required but never sufficient |
| How much to read | Every line in tier 1 | Strong, independent tests carry more weight than reading 600 lines |
Day to day
Every pull request, automatic. Gates run; tier-1 paths request their code owners. You see only what a gate escalates.
Daily, 20 minutes. Read the new-dependency approvals and any secret-scanning block. These are the two queues where a delay hurts engineers and a wrong yes hurts you.
Weekly. Read a sample of tier-1 agent pull requests after merge, five is enough to start, with the review comments beside the diff. Each miss becomes a test, a SAST rule or a line in the reviewer checklist, not a reminder email.
On every new agent or MCP server. Review its permissions against the table above before it gets a token. Engineers adopt new tools monthly; the intake is how you hear about them.
Monthly. Report the four measures to engineering leadership, with one change you propose.
Quarterly. Run the planted-flaw drill, revisit the tier-1 path list as the codebase moves, and walk through a tabletop where a coding agent’s token is stolen.
The meetings that matter are the engineering managers’ sync, where the team agreement in the managers’ chapter is set, and the platform team’s planning, because the gates live in their pipeline. AI in technical strategy is where principal engineers set the organisation-wide standard; bring your measures to it.
Nobody owns security and every engineer uses agents. Do three cheap things. Turn on secret scanning with push protection. Add the new-dependency check so every new name needs a person’s yes. Put auth and tenant-scoping code under a CODEOWNERS entry for the one or two engineers who understand it, and write a two-tenant test for every endpoint that reads customer data. Give the agent a token that cannot merge or read deploy secrets. Measure nothing formal yet; read the agent pull requests to auth yourself.
You are the security team, one or two people, and the agent share is climbing every month. Tiers and gates are how you stay off the critical path. Write the tier-1 path list with the tech leads, own the tenant-isolation suite, and make the gates required checks. Review agent permissions at intake. Start the four measures so that the next debate about agents and auth code is argued with numbers. Customers’ security questionnaires begin to ask about AI-written code; the policy is your answer.
Many repositories, several agent products, and teams that configured each differently. The problem is consistency and evidence. You need an inventory of agents with their tokens and owners, organisation-level rulesets instead of per-repository settings, gates published as a paved road, and escapes traced to origin across the estate. Auditors and customers ask who approved a change to a regulated path, and the answer must be a named human. The politics are teams who see code-owner review as a tax on their speed.
Template
# Review policy: AI-written code
Owner · Approved by: <head of engineering> · Date · Review date
## 1. Scope
Applies to every pull request to: <repositories>. Tiers apply by path, not author.
## 2. Tiers
| Tier | Paths | Merge needs | Code owners |
|---|---|---|---|
| 1 | | | |
| 2 | | | |
| 3 | | | |
## 3. Gates (required checks)
| Gate | Blocks | Override by | Override recorded in |
|---|---|---|---|
| SAST | | | |
| Secret scanning (push protection) | | | |
| New-dependency check | | | |
| Authz and tenant-isolation suite | | | |
## 4. Coding agent permissions
| Permission | Setting | Owner of the setting |
|---|---|---|
| Contents | | |
| Merge / approve | | |
| Workflow runs | | |
| Secrets | | |
| Network egress | | |
| MCP servers / tools | | |
New agent or MCP server: <intake step>
## 5. Tier-1 human review checklist
- [ ] Identity and tenant come from the verified session
- [ ] Files outside the task reviewed
- [ ] At least one test from a source other than the author
- [ ] Failure paths deny
- [ ] Requester can explain every line
## 6. AI review
Tool · Where its findings go · Not a required gate because: <reason>
## 7. Prompts and secrets
What may not enter a prompt · What happens when a secret is pasted or committed
## 8. Measures (monthly)
| Measure | Baseline | Target | Owner |
|---|---|---|---|
**Revisit when:** <new agent product, new tier-1 path, an escape> WORKED EXAMPLE
Larkhollow at 300 people, 120 engineers in eight pods, one TypeScript monorepo on GitHub. Security is two people: you, and Rahel, the security engineer. In October 2,300 pull requests merged, 690 of them (30%) opened by coding agents assigned from issues; 41 agent-opened pull requests touched the four sensitive paths. In September an agent change in the connectors pod looked up tickets by external number without the tenant id; it passed its tests and one approval and was caught in staging when two customers’ ticket numbers collided.
Tiers. Tier 1: src/auth/, src/tenancy/, src/connectors/credentials/, src/billing/, .github/, CODEOWNERS. Merge needs gates green and a code owner who did not request the change. Biniam, a tech lead in the connectors pod, and two of his engineers own src/connectors/credentials/ with security.
Gates. SAST (12 blocking rules after tuning), push protection, the new-dependency check (18 new direct dependencies in October, 7 from agent pull requests; one name was 11 days old with one maintainer and was refused), and a two-tenant suite of 140 tests in security/tests/, owned by Rahel.
Agent permissions. Contents read, write to agent/* branches; never approve or merge; workflow runs wait for approval; no deploy secrets (the staging deploy secret was removed in October); egress to the registry proxy only; two pinned MCP servers.
AI review. Comments on every pull request; never a required check.
Measures. Agent share by tier; gate blocks and false-positive rate; escapes per quarter by origin and tier (baseline: one, the September near-miss); median tier-1 review minutes per 100 lines.
Now you
You are the head of security at Larkhollow at 300 people, with Rahel as your one security engineer. Engineering leadership wants agents to work through the backlog of connector bugs, which means more agent pull requests to src/connectors/credentials/, where customers’ ticketing and ERP credentials are encrypted and read. Biniam, a tech lead in the connectors pod, says code-owner review on that path already takes two days and will take longer. Complications: the coding agent’s CI token today has contents write on the whole repository; three engineers use a second agent product locally whose permissions nobody has reviewed; the tenant-isolation suite covers the public API but not the connector sync jobs; and one engineer pasted a customer’s sandbox API key into an agent session last month, which turned up in a test fixture. Write the review policy: tiers by path, gates with overrides, the agent permissions you will change and in what order, the tier-1 checklist, where AI review sits, and four measures with baselines.
Self-check
You are the head of security at Larkhollow at 300 people, with Rahel as your only security engineer. Coding agents opened 41 pull requests to the auth, tenancy, connector-credentials and billing paths last month, and one in September dropped a tenant filter and was caught in staging. Biniam, a tech lead in the connectors pod, wants agents to keep working on connector-credentials bugs. The head of engineering asks you for a rule by Friday.
- PAPER Asleep at the Keyboard? Assessing the Security of GitHub Copilot's Code Contributions Pearce, Ahmad, Tan, Dolan-Gavitt and Karri, 2022
The first systematic measurement of how often a code assistant writes vulnerable code. Know its design before you quote its 40%. Read: The abstract and the methodology section, to see how scenarios were built to invite specific CWEs.
- PAPER Do Users Write More Insecure Code with AI Assistants? Perry, Srivastava, Kumar and Boneh, 2023
A user study showing less secure code and more confidence with an assistant. The confidence finding is the one that applies to your reviewers. Read: The abstract, the results on confidence, and the limitations.
- PAPER We Have a Package for You! A Comprehensive Analysis of Package Hallucinations by Code Generating LLMs Spracklen, Wijewickrama, Sakib, Maiti, Viswanath and Jadliwala, 2025
The evidence behind slopsquatting: how often models invent packages, and that they repeat the same names. The case for a new-dependency gate. Read: The abstract and the section on how often hallucinated names repeat.
- POST Diving Deeper into AI Package Hallucinations Bar Lanyado, Lasso Security, 2024
The huggingface-cli experiment: an empty package registered under a hallucinated name, and how many real installs it drew in three months.
- DOC LLM09:2025 Misinformation OWASP GenAI Security Project, 2025
The OWASP entry that names unsafe code generation and hallucinated packages, with an attack scenario. Cite it by name and edition in your policy.
- DOC Risks and mitigations for GitHub Copilot cloud agent GitHub
What a vendor's coding agent can and cannot do by default: one branch, no self-approval, held workflow runs, a firewall. Check your settings against it.
- DOC Claude Code security Anthropic
Permission modes, sandboxing, MCP and cloud-session credentials for another widely used agent. Read it for the settings your organisation should manage centrally.
- POST GitHub MCP Exploited: Accessing private repositories via MCP Marco Milanta and Luca Beurer-Kellner, Invariant Labs, 2025
A worked demonstration of prompt injection through a public issue reaching private repositories. The argument for narrow agent tokens.
All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.