AnyLearn
All lessons
Programmingintermediate

Securing AI-Generated Code: Insecure Defaults, Phantom Packages, Poisoned Context

Generated code that works is often not code that is safe. Learn what studies show about vulnerabilities in AI-written code, how hallucinated package names become a supply-chain attack, how hidden instructions hijack agents, and the controls that catch each risk.

Updated · AI-authored, review-gated · how lessons are made

Progress1 / 10

Working is not the same as safe

A model trained on public code learns the patterns that are common, and common code is not the same as secure code. It also optimizes for the request in front of it. "Return the user's orders" says nothing about checking that the caller owns those orders, so the generated code often does not check.

StudyMethodFinding
Pearce et al., IEEE Symposium on Security and Privacy 202289 scenarios built around high-risk CWEs, 1,689 programs from GitHub CopilotAbout 40% vulnerable
Veracode GenAI Code Security Report, 2025Security-relevant tasks given to over 100 LLMs in Java, JavaScript, Python and C#OWASP Top 10 flaws in 45% of tests

The studies are years and model generations apart, and Veracode reports that larger, newer models did not improve security. Gains in general coding ability did not carry over into code that resists attack.

Key idea: Treat generated code as code from a fast, well-read contributor who was never told the threat model.

Sign in free to save your progress and earn certificates.

Full lesson text

All 10 steps on one page, for reading, reference, and search.

Show

1. Working is not the same as safe

A model trained on public code learns the patterns that are common, and common code is not the same as secure code. It also optimizes for the request in front of it. "Return the user's orders" says nothing about checking that the caller owns those orders, so the generated code often does not check.

StudyMethodFinding
Pearce et al., IEEE Symposium on Security and Privacy 202289 scenarios built around high-risk CWEs, 1,689 programs from GitHub CopilotAbout 40% vulnerable
Veracode GenAI Code Security Report, 2025Security-relevant tasks given to over 100 LLMs in Java, JavaScript, Python and C#OWASP Top 10 flaws in 45% of tests

The studies are years and model generations apart, and Veracode reports that larger, newer models did not improve security. Gains in general coding ability did not carry over into code that resists attack.

Key idea: Treat generated code as code from a fast, well-read contributor who was never told the threat model.

2. The weakness classes that keep recurring

A handful of weakness classes dominate, and each has a reason rooted in how code gets generated:

WeaknessWhy generation produces itTypical fix
SQL or command injectionString-built queries are abundant in tutorial codeParameterized queries, argument lists
Cross-site scriptingRendering raw input is the shortest working pathContext-aware output encoding, safe template defaults
Missing authorizationThe prompt names the action, not who may perform itOwnership checks on every object access
Hard-coded secretsInlining a key makes the demo runEnvironment variables or a secret manager, plus scanning
Log injectionLogging user input verbatim is idiomaticEncode or strip control characters
Weak randomness or cryptoOlder APIs are common in training dataVetted libraries, secrets instead of random

Veracode singled out cross-site scripting and log injection as classes the models most consistently failed to defend against. Missing authorization is the hardest for tools to catch, because nothing in the code is wrong on its face. It is missing a rule that only the spec knows.

3. Worked example: the injection that works

Asked to "fetch a user by name", a model can easily produce the first version below. It runs, it passes a happy-path test, and it is exploitable:

import sqlite3

# Generated: works, and is injectable
def get_user(conn: sqlite3.Connection, name: str):
    query = f"SELECT id, email FROM users WHERE name = '{name}'"
    return conn.execute(query).fetchone()

# get_user(conn, "x' OR '1'='1") returns the first user in the table

# Fixed: the driver binds the value, so it is never parsed as SQL
def get_user(conn: sqlite3.Connection, name: str):
    return conn.execute(
        "SELECT id, email FROM users WHERE name = ?", (name,)
    ).fetchone()

The fix is one line, and that is the point: these flaws are cheap to prevent and expensive to find later. Put the rule where the agent will meet it, in the project's instruction file and as an unwanted-behaviour requirement in the spec. Then back it with a static analysis rule that fails the build, because instructions are followed probabilistically and checks are not.

4. Phantom packages

Code generators also invent dependencies. Joseph Spracklen and colleagues, in a USENIX Security 2025 paper, generated 576,000 code samples in Python and JavaScript from 16 models and checked the packages they used against the real registries. The average share of hallucinated packages was at least 5.2% for commercial models and 21.7% for open-source models, and the study collected 205,474 unique package names that do not exist.

A name that does not exist is an opportunity. An attacker registers it on PyPI or npm with a malicious install script, then waits for a developer, or an agent with shell access, to run the install command the model suggested. The authors frame this as a new variant of the package confusion attack; it is now widely called slopsquatting.

Definition: Package hallucination is a model recommending or importing a package that is not in the registry. It becomes an attack when someone registers the hallucinated name first.

5. Why the attack scales

Predict first

If package hallucinations were random noise, different on every run, would registering hallucinated names be a practical attack?

The same paper tested mitigations on the model side, including retrieval-augmented generation and fine-tuning, and reports that they significantly reduce package hallucinations. That helps, but you rarely control the model, and no mitigation brought the rate to zero.

In practice: Do not rely on the model noticing its own mistake in the moment. A deterministic check that every new dependency exists, is established, and was approved catches the risk regardless of which model wrote the import.

6. Dependency controls that do not trust the model

These defences treat every new dependency as untrusted until checked:

# Install exactly what the lockfile pins, verified by hash
pip install --require-hashes -r requirements.txt

# npm: install from the lockfile and skip install-time scripts
npm ci --ignore-scripts

# Before adding anything new, confirm it exists and inspect it
pip index versions some-package
npm view some-package time.created maintainers
  • Gate new dependencies. A pull request that adds one needs a human decision; make that a standing rule in the agent's instructions.
  • Check age and history. A package created days ago with one maintainer, whose name matches an import an agent just wrote, deserves suspicion.
  • Proxy the registry. With an internal mirror or allowlist, a hallucinated name simply fails to resolve.
  • Scan dependencies in CI so known-malicious and vulnerable versions are flagged on every change.

7. Poisoned context: instructions hidden in the repo

An agent reads far more than your prompt: source files, READMEs, issue text, documentation it fetches, and its own rules files. Any of these can carry instructions, and a model cannot reliably separate data it was asked to read from commands it was asked to follow. OWASP ranks this, prompt injection, first in its Top 10 for LLM applications.

Pillar Security demonstrated a repository-specific form it called the Rules File Backdoor. Malicious instructions were hidden in an AI assistant's rules file using invisible Unicode, such as zero-width joiners and bidirectional text markers, so the model could read them but humans could not, including in pull request review. In the demonstration, a request for a simple HTML page led the agent to add a script tag loading from an attacker's site, without mentioning it in its reply. GitHub later added a warning for hidden Unicode text on github.com.

Gotcha: Rules files, agent configuration and prompt templates act like executable code. Review them as code, and scan them for invisible characters.

8. Secrets: the shortcut that leaks

Agents leak credentials for the same reason they hard-code test values: it is the fastest path to a working result. A key pasted into a config file makes the integration test pass; a token printed to the log helps debugging. GitGuardian's State of Secrets Sprawl 2025 report looked at about 20,000 public repositories where Copilot was active and found that 6.4% leaked at least one secret, against 4.6% across all public repositories, roughly 40% higher.

ControlWhat it stops
Pre-commit secret scanning, for example gitleaks or ggshieldKeys reaching git history at all
No production credentials in the agent's environmentAn agent cannot leak what it never had
Short-lived, narrowly scoped tokens for what the agent does needLimits the damage when a leak happens
Redaction rules for logs and error messagesTokens written to output

A secret in git history stays exposed after the line is deleted. Rotation, not removal, is the fix.

9. Security checks as sensors in the loop

Each automated gate is a sensor the agent can read and fix against before a person looks. Static analyzers such as Semgrep or CodeQL catch pattern-level flaws, and scanners catch secrets and suspicious packages. That frees the human reviewer to spend attention where tools are weakest: authorization rules and where sensitive data flows. Limiting what the agent may do while it works, through sandboxes and permissions, is a separate layer that complements these checks on its output.

flowchart LR
  A["Agent diff"] --> B["Secret scan"]
  B --> C["Dependency check"]
  C --> D["Static analysis"]
  D --> E["Tests incl. security cases"]
  E --> F["Human review: authz and data flow"]
  F --> G["Merge"]

10. Reviewing an AI-written pull request

A short, repeatable checklist turns everything above into a habit:

  1. New dependencies: each one exists, is established, and was approved, not merely imported.
  2. Queries and commands use parameters or argument lists, never strings built from input.
  3. Every data access checks that the caller may see or change that specific object.
  4. Output to HTML, logs or shells is encoded for that context.
  5. No secrets in code, config, tests, fixtures or logs.
  6. Changed rules files or agent config were diffed with invisible characters made visible.
  7. Security requirements from the spec, such as rate limits and uniform error messages, each have a test.

In practice: Apply the checklist hardest where generated code is most confident and least checked: authentication, payments, file handling, and anything that builds a query or a shell command.

Check your understanding

The lesson ends with a 5-question quiz. Take it in the player above to see your score.

  1. What did Veracode's 2025 report find about larger, newer models?
    • They eliminated OWASP Top 10 flaws
    • They were worse in Java but better elsewhere
    • They produced half as many vulnerabilities
    • They did not improve security
  2. Why is package hallucination exploitable rather than just an annoying error?
    • Hallucinated packages contain bugs
    • An attacker can register a hallucinated name, and recurring names are predictable
    • Registries automatically install similarly named packages
    • Models deliberately recommend malicious packages
  3. Which weakness is hardest for automated scanners to catch in generated code?
    • A missing authorization check
    • A hard-coded API key
    • A string-built SQL query
    • A known vulnerable package version
  4. In the Rules File Backdoor demonstration, why did reviewers miss the malicious instructions?
    • They were stored in a binary file
    • They were encrypted
    • They were written with invisible Unicode characters
    • They were added after the review
  5. An agent committed an API key, and the next commit deleted it. What is the right fix?
    • Rotate the credential, since it remains in git history
    • Nothing, because the latest commit is clean
    • Make the repository private
    • Add the file to .gitignore

Related lessons