07 - Security in Vibe Coding: Risks and Mitigations
You have accepted a diff written by an assistant and now you wonder what it might be hiding. The three studies I read to write this article give an answer with declared samples and years, and none of them is a rate that holds for your code: in 2021 Pearce and colleagues had GitHub Copilot complete 89 scenarios tied to known weaknesses, obtaining 1,689 programs, of which about 40% were vulnerable.
In 2022 Perry and colleagues observed in a user study that people with an assistant wrote less secure code and more often believed they had written it securely. In 2024 Spracklen and colleagues generated 576,000 code samples with 16 models and found non-existent packages in at least 5.2% of cases for commercial models and 21.7% for open ones.
These are models and tools from years ago, but the categories of error are the usual ones: injection, file paths, secrets in the source. Two things are new: dependencies that do not exist and instructions hidden in the files the assistant reads. In this article you see what happens when you run three checks (a SQL injection, a path check that looks correct and is not, a comparison of dependencies), and what the official documentation says about permissions and sandboxes. It picks up the criterion of the first article: whoever reads the diff decides how much code gets in without being checked.
What the studies say, and what they do not say
Pearce's study measures the 2021 Copilot on scenarios built to touch weaknesses from the MITRE list: it says the assistant often proposes
code with known defects when the context does not guide it, not that 40% of your code is. Perry's study concerns
participants with an assistant based on codex-davinci-002, and its most useful result sits in a tail of the abstract: those who trusted
the assistant less and worked more on their own prompts produced fewer vulnerabilities. Trust, in other words, is a security variable.
Spracklen's study measures something else, the package names that models invent, and counts 205,474 distinct ones: an attacker can register one of those names.
I have not reported the percentages from a commercial report on generated code that circulate widely: I read only its presentation page, not the report, and a figure with no sample or method does not hold up a decision.
The same goes for the numbers on "design flaws" and on the "vulnerability multiplier" found around: I have no primary source, so they do not appear. What remains is enough to work with: the risk exists, it is measured on scenarios, and its forms are the following.
SQL injection: the classic payload does not work, the one that matters does
CWE-89 describes the defect: a SQL command built with an external input that is not neutralised. The listing below creates in memory a table with three users,
including their password hashes, and compares two functions: search_vulnerable interpolates the text into the query with an f-string,
search_with_parameters uses a ? placeholder and passes the value separately. Four inputs: one normal and three hostile. The code is written by me, in
a style an assistant produces easily, and it runs as it is with the standard library alone.
import sqlite3
def create():
con = sqlite3.connect(":memory:")
con.executescript("""
CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, email TEXT, password_hash TEXT);
INSERT INTO users VALUES (1, 'anna', 'anna@example.org', 'h-anna-111');
INSERT INTO users VALUES (2, 'bruno', 'bruno@example.org', 'h-bruno-222');
INSERT INTO users VALUES (3, 'carla', 'carla@example.org', 'h-carla-333');
""")
return con
def search_vulnerable(con, name):
query = f"SELECT id, name, email FROM users WHERE name LIKE '%{name}%'"
return con.execute(query).fetchall()
def search_with_parameters(con, name):
query = "SELECT id, name, email FROM users WHERE name LIKE ?"
return con.execute(query, (f"%{name}%",)).fetchall()
INPUTS = {
"normal": "bru",
"tautology": "zzz' OR 1=1 --",
"union": "zzz' UNION SELECT id, password_hash, email FROM users --",
"drop": "'; DROP TABLE users; --",
}
if __name__ == "__main__":
con = create()
for label, value in INPUTS.items():
for function in (search_vulnerable, search_with_parameters):
try:
outcome = function(con, value)
except sqlite3.Error as error:
outcome = f"{type(error).__name__}: {error}"
print(f"{label:11} {function.__name__:22} {outcome}")
rows = con.execute("SELECT COUNT(*) FROM users").fetchone()[0]
print(f"rows in the table at the end: {rows}")
# normal search_vulnerable [(2, 'bruno', 'bruno@example.org')]
# normal search_with_parameters [(2, 'bruno', 'bruno@example.org')]
# tautology search_vulnerable [(1, 'anna', 'anna@example.org'), (2, 'bruno', 'bruno@example.org'), (3, 'carla', 'carla@example.org')]
# tautology search_with_parameters []
# union search_vulnerable [(1, 'h-anna-111', 'anna@example.org'), (2, 'h-bruno-222', 'bruno@example.org'), (3, 'h-carla-333', 'carla@example.org')]
# union search_with_parameters []
# drop search_vulnerable ProgrammingError: You can only execute one statement at a time.
# drop search_with_parameters []
# rows in the table at the end: 3
Surprise: the attack that appears in almost every example, '; DROP TABLE users; --, does nothing here. The Python documentation states that
execute accepts a single SQL statement, and indeed the drop row ends with a ProgrammingError and the table still has its three rows. Anyone who
concludes that "with sqlite3 it is fine" is wrong: the union row shows that the same input, completed with a SELECT, returns the password hashes
in the name column, and the tautology row returns all the users. The typical damage is not deleting, it is reading what you should not. The version with parameters
returns an empty list in all three hostile cases, because the text stays a value and never becomes part of the command.
A detail I found by running it: my first payload, zzz' OR '1'='1, returned nothing. The code appends %' after the input, and the comparison
'1'='1%' is false.
An attack has to be adapted to the query that contains it, and a test showing that it "does not work" does not prove the code is safe: it proves that this payload does not work.
The sqlite3 documentation says it plainly: always use placeholders instead of string formatting.
File paths: the check that looks right
CWE-22 is the case in which a path built from an external input escapes the folder that is supposed to contain it. The defence an assistant often writes is right in idea:
resolve the path and check that it stays inside the base folder. The problem is in the way. The listing compares two implementations: the first checks with
str(target).startswith(str(base)), the second with Path.is_relative_to. In a temporary folder it builds a files folder, a neighbour
files-private whose name starts the same way, and a symbolic link inside files that points to the neighbour.
import tempfile
from pathlib import Path
def naive_allowed(base: Path, requested: str) -> bool:
target = (base / requested).resolve()
return str(target).startswith(str(base))
def allowed(base: Path, requested: str) -> bool:
target = (base / requested).resolve()
return target.is_relative_to(base)
if __name__ == "__main__":
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp).resolve()
base = root / "files"
neighbour = root / "files-private" # its name starts like the base one
base.mkdir()
neighbour.mkdir()
(base / "report.pdf").write_text("public")
(neighbour / "secret.txt").write_text("confidential")
(base / "shortcut").symlink_to(neighbour) # link pointing outside
for requested in ("report.pdf", "../etc/passwd",
"../files-private/secret.txt", "shortcut/secret.txt"):
print(f"{requested:32} naive={naive_allowed(base, requested)!s:5} "
f"correct={allowed(base, requested)}")
# report.pdf naive=True correct=True
# ../etc/passwd naive=False correct=False
# ../files-private/secret.txt naive=True correct=False
# shortcut/secret.txt naive=True correct=False
The string comparison fails two times out of four: /…/files-private/secret.txt starts with /…/files and passes, and the same holds for the
symbolic link, which resolve() follows all the way to the neighbouring folder. is_relative_to, described in the pathlib documentation, reasons by path
components and rejects both.
A practical rule follows: when you review a security check written by an assistant, try the cases that break it (a name that starts like the allowed one,
a symbolic link), not the happy one. The happy case, report.pdf, passes in both and tells you nothing.
Secrets in the source: a rule an instruction file does not enforce
CWE-798 covers the use of credentials written into the code. An assistant inserts them when the prompt does not say where the configuration lives, because in the examples it has seen
they live in the source. The fix is well known (environment variables, validated at startup, with a refusal to start if they are missing), and the point is who enforces it. Writing it in
AGENTS.md or CLAUDE.md, as seen in Prompt Engineering for IDEs and Code Generation, steers
the assistant but is not a control: the Claude Code documentation says those files are context, not enforced configuration. A real control is a secrets scanner in the commit or in CI,
which fails when it finds a secret. I did not run one in this article and I do not recommend one by name.
Dependencies that do not exist: the right check is not "does it exist?"
Spracklen and colleagues call a package hallucination a package name that the model proposes and that is not in the registry; for the two languages studied, Python and JavaScript, the average is at least 5.2% for commercial models and 21.7% for open ones. The risk they describe is a package confusion attack: if an attacker registers that name with malicious code, whoever installs without looking brings the malicious code into the project.
The consequence for the check is counterintuitive. A script that queries the registry and flags "NOT FOUND" stops invented names as long as nobody has registered them, and stops working precisely when the attacker has done their job: at that point the package exists.
The check that holds is another one: every new dependency in a diff must be approved by a person, who looks at name, age, maintainers and origin. The listing compares two
package.json manifests (the package names are invented for the example and I did not look them up in the registry), flags the new dependencies, those with an unpinned version and those that do not come from the registry,
and exits with code 1 if there are any. It does not query the network: that is not needed to decide that a person must look.
import sys
BEFORE = {
"dependencies": {"express": "^4.19.2", "zod": "^3.23.8"},
"devDependencies": {"typescript": "^5.4.0"},
}
AFTER = {
"dependencies": {
"express": "^4.19.2",
"zod": "^3.23.8",
"fake-validator": "^1.0.2",
"library-from-git": "git+https://example.org/library.git",
},
"devDependencies": {"typescript": "^5.6.0", "fake-helper": "*"},
}
SECTIONS = ("dependencies", "devDependencies")
def flat(manifest):
return {name: v for s in SECTIONS for name, v in manifest.get(s, {}).items()}
def notes(version):
result = []
if version in ("*", "latest", ""):
result.append("version not pinned")
if version.startswith(("git", "http", "file:")):
result.append("does not come from the registry")
return result
def compare(before, after):
b, a = flat(before), flat(after)
rows = []
for name in sorted(a.keys() - b.keys()):
rows.append(("NEW", f"{name} {a[name]}", notes(a[name])))
for name in sorted(b.keys() & a.keys()):
if b[name] != a[name]:
rows.append(("CHANGED", f"{name} {b[name]} -> {a[name]}", notes(a[name])))
for name in sorted(b.keys() - a.keys()):
rows.append(("REMOVED", name, []))
return rows
if __name__ == "__main__":
rows = compare(BEFORE, AFTER)
for kind, text, warnings in rows:
print(f"{kind:9} {text}" + (f" [{'; '.join(warnings)}]" if warnings else ""))
new = [r for r in rows if r[0] == "NEW"]
print(f"{len(new)} new dependencies to approve by hand")
sys.exit(1 if new else 0)
# NEW fake-helper * [version not pinned]
# NEW fake-validator ^1.0.2
# NEW library-from-git git+https://example.org/library.git [does not come from the registry]
# CHANGED typescript ^5.4.0 -> ^5.6.0
# 3 new dependencies to approve by hand
The output lists three new dependencies and one changed version. fake-helper * is flagged because the version is not pinned: * installs
whatever gets published tomorrow. library-from-git is flagged because it does not come from the registry, and should be read as a dependency that no registry check sees. The update of
typescript appears as changed, but does not block. The exit code 1 is there for CI.
For the known vulnerabilities of what is already installed there is npm audit: its
documentation says it exits with a non-zero code if it finds vulnerabilities and that --audit-level sets the minimum severity that makes it fail. They are two different checks: one looks at what comes in, the other at what is already inside.
Instructions hidden in files: prompt injection
OWASP ranks prompt injection as LLM01 in its 2025 list of risks for applications with language models: inputs that alter the model's behaviour in unintended ways, even if a human cannot see them, as long as the model reads them. For a coding assistant the input is any text it reads while working: a comment in a dependency, a documentation file, a commit message.
The same page warns that neither RAG nor fine-tuning fully eliminates the problem. A sentence hidden in a comment can ask the assistant to add a network call: that is why what the assistant reads must be treated as untrusted input, not as the instructions of the person working.
I cannot promise a filter that recognises those sentences, and I do not propose one. The defence that can be verified is to take away the assistant's ability to do damage, and the Claude Code permissions documentation is precise about what holds. Rules are evaluated in the order deny, ask, allow, and the first one that matches decides: an allow cannot make an exception to a deny.
But a deny such as
Bash(curl *) does not match /usr/bin/curl or sh -c 'curl …', and the documentation calls patterns that constrain a command's arguments fragile. If a network restriction must really hold,
the guide points to pairing it with a list of allowed hosts in the sandbox. A list of forbidden commands gives an impression of safety that it does not have. How to configure permissions and hooks is in
Claude Code: agentic development from the terminal.
Automatic analysis: what it sees and what it does not
Static analysis tools read the code without running it. Bandit, for Python, processes each file, builds the syntax tree and runs plugins on the nodes, then produces a report, as
its documentation says. It finds defects that have a recognisable shape (queries built with f-strings, dangerous functions) and not logic defects: the startswith check in the paths listing is
syntactically innocent code. Dynamic analysis tests the running application and sees what static analysis does not, but it needs a test environment that I did not start here, so I report no configurations or results.
The point to keep: analysers reduce the number of errors that reach review, they do not replace it, and a green signal only means that no rule recognised the defect.
Separate the environments before granting permissions
The rule with the best return concerns what the assistant can reach, not what it writes. An agent working with production credentials can damage production with a wrong command even without any attack. It pays to keep the environments separate, so that the consequences of a mistake are limited to what the agent can touch:
- A development database with fictitious data: the agent does not see production, not even read-only by mistake.
- A read-only user if it has to analyse real data: it cannot write or delete whatever it decides.
- No release credentials in the agent's environment: the deploy is launched by a person, or by a pipeline the agent does not control.
- A verified backup before every migration: if something goes wrong, there is a point to restart from.
The four items have one thing in common: they do not depend on the quality of the assistant, and they work even when it makes mistakes or is tricked. That is why they come before security prompts. When you hand the agent long tasks, the way you break them down affects what it must be able to touch: that is the subject of Agentic workflows.
Frequently asked questions
Is a security prompt enough to get secure code?
No. A prompt steers the model and reduces repetitive errors, but it enforces nothing. In Perry's study the difference was made by those who distrusted the assistant and worked on their prompts, not by the prompt itself. Verification lives outside the prompt: tests, analysis and review.
Why does the dependencies script not check existence in the registry?
Because existence proves nothing: the attack described in the research consists of registering the invented name. A name that is present may have been registered yesterday by someone who wants you to install it. You need a person who looks at name, age and maintainers.
Does static analysis find the problems in this article's listings?
I have not verified it: I did not run any analyser on the listings. By construction a tool like Bandit looks for recognisable shapes, and the startswith check is syntactically innocent: do not take for granted that it flags it.
Should I give up assistants for code that touches sensitive data?
That is not what the sources say. They say the code must be reviewed with attention to the known categories and the environment must be separated. For the most critical parts (authentication, payments) line-by-line human review remains mandatory, and security tests must be written by someone who knows what to look for.
What you can do now
You can recognise three typical defects of generated code and prove them with an input that brings them out: interpolation in a query, the path check on strings, the dependency nobody approved. You know why a check of the "does the package exist?" kind is useless against the attack the research describes, and why a list of forbidden commands is not a sandbox. The next step is to write the tests that capture these cases: How to Test AI-Generated Code. The last article in the series looks ahead: the future of agentic development.
Sources
- Pearce et al., Asleep at the Keyboard? Assessing the Security of GitHub Copilot's Code Contributions (arXiv 2108.09293) - 89 scenarios, 1,689 programs, approximately 40% vulnerable (abstract), consulted on 2026-11-13
- Perry et al., Do Users Write More Insecure Code with AI Assistants? (arXiv 2211.03622) - user study: less secure code and more confidence with the assistant; fewer vulnerabilities for those who trusted it less (abstract), consulted on 2026-11-13
- Spracklen et al., We Have a Package for You! A Comprehensive Analysis of Package Hallucinations by Code Generating LLMs (arXiv 2406.10279) - 16 models, 576,000 samples, at least 5.2% (commercial) and 21.7% (open-source), 205,474 unique names (abstract), consulted on 2026-11-13
- OWASP Gen AI Security Project, LLM01:2025 Prompt Injection - definition and warning on RAG and fine-tuning, consulted on 2026-11-13
- MITRE, CWE-89 (SQL Injection), CWE-22 (Path Traversal) and CWE-798 (hard-coded credentials) - the definitions of the three defects, consulted on 2026-11-13
- Python: sqlite3 module and pathlib module - a single statement per
execute, placeholders instead of string formatting,PurePath.is_relative_to, consulted on 2026-11-13 - Bandit, documentation - syntax tree analysis of each file with plugins, consulted on 2026-11-13
- npm Docs: npm audit - exit code and
--audit-level, consulted on 2026-11-13 - Claude Code Docs: How Claude remembers your project - CLAUDE.md as context and not as enforced configuration, consulted on 2026-11-13
- Claude Code Docs: Permissions - evaluation order deny, ask, allow; limits of Bash patterns and the sandbox, consulted on 2026-11-13
The three listings were run with Python 3.14.4, twice each, with identical output (cmp on the output files), in memory or in temporary folders, without network. They are written by hand for the article and not generated by a model. No static analyser, secrets scanner or dynamic testing tool was run. The package names in the example are invented and were not looked up in the registries. I did not read the original advisories of any single product's vulnerability, and for that reason I cite none.

Commenti
Caricamento commenti...
Sign in to comment