How to Prevent Prompt Injection in Coding Agents: Five Detection Gates
Coding AI agents that read project-level specification files can be hijacked by prompt injection through a chain that contains no vendor-patchable bug. This article examines that threat model and lays out five detection gates you can add to your own release process: entry detection to shrink the web-writable attack surface, configuration-integrity checks that treat global config drift as an intrusion signal, prompt-versus-execution layering that keeps untrusted text from acting as high-privilege instructions, an outbound allowlist that blocks malicious dependencies from landing and calling home, and a rotate-on-discovery response that assumes compromise. It includes a runnable config-drift check script, an outbound allowlist template, a control-mapping table, and an FAQ.
1. Why Waiting for a Vendor Patch Won’t Work
A note on sourcing first: this article is built on a so-called “cross-product reproduction report from a security research organization.” Its original title, link, test scope, sample size, and telemetry definitions are not specified in the source, and we have not independently verified them. So the analysis below treats it as a plausible threat model rather than a proven, settled conclusion.
Even under that caveat, the report’s central claim is worth taking seriously: nowhere in this attack chain is there a bug a vendor could patch.
That isn’t a way of letting vendors off the hook. According to the report, the same chain worked on two independent coding tools. Two unrelated implementations failing at once suggests the problem isn’t a flaw in any single product — it’s an inherent property of what a coding AI agent fundamentally is.
A useful analogy for test engineers: when a browser renders a fake bank login page, the browser is doing exactly what it should — faithfully rendering the HTML. The attack lives in the page, not in the browser engine, so there is no engine patch to apply. In the same way, a coding agent that reads the project-level specification file in its directory and then acts on it is working entirely as designed.
You may disagree with the analogy, but it forces one conclusion: if the problem can’t be fixed upstream, it has to become a check in your own release gates.
2. Five Actions in the Attack Chain, Five Detection Points
Action 1: A web page writes a file into the download directory. One commonly overstated claim needs clarifying: browsers can often write downloaded content to the user’s download directory without extra confirmation, but the exact filename and contents depend on browser policy, page settings, and the server response together — the web page doesn’t unilaterally control all of it. This single action is harmless on its own, because operating systems already have guardrails against auto-running downloaded executables. But project-level specification files — the plaintext context-convention files an agent loads at startup — aren’t executables and naturally fall outside those guardrails.
Action 2: The user launches the agent in the download directory. Here’s a key precondition: the attack only works if an agent actually loads the specification file in the current directory and the user happens to start a session there. Read rules differ across tools — some only read from the project root, and some don’t load external specs by default. The report mentions that a significant portion of users have run a coding agent directly in the download directory and that a significant portion of sessions open a browser to perform actions, but since those figures come with no stated definitions, treat them as reference rather than fact.
Actions 3, 4, 5: Read, rewrite, persist. Once the agent has the specification file, it loads it as project context. Instructions in the spec such as “first adjust the configuration” or “install such-and-such dependency” get executed as legitimate tasks, so the global config is rewritten and a malicious dependency is pulled into the dependency tree and persisted. At this point, a session that looked like it was just “helping you get some temporary work done” has spread the contamination to the account level.
3. Five Detection Gates You Can Actually Implement
3.1 Entry Detection: Shrink the “Web-Writable” Attack Surface
- Monitor specification-type files that newly appear in the download directory and that an agent would read as context — especially files that are “of unknown origin, never opened after download, yet already sitting in some agent session directory.”
- Steer users away from starting sessions with the download directory as the project root; when temporary handling is needed, copy the file into a controlled workspace first, then start the session.
- At workspace initialization, tag and snapshot any specification file that gets auto-loaded, and forbid “takes effect with zero clicks.”
3.2 Configuration Integrity: Treat Global Config Drift as an Intrusion Signal
Before the script, two things: CONFIG_PATHS must be replaced with your actual agent global config paths (the sample values may not match your environment); and back up the config and baseline directory in a trusted state before collecting a baseline — otherwise, once drift happens, you’ll have neither a reference to compare against nor a rollback point.
Here’s a ready-to-use drift check script:
#!/usr/bin/env bash# config-drift-check.sh — Detect unexpected changes to a coding agent's global configurationset -euo pipefailBASELINE_DIR="${BASELINE_DIR:-.config-baseline}"CONFIG_PATHS=("$HOME/.config/agent/global.yaml" # Replace with your actual agent global config path"$HOME/.agent/config.toml""$HOME/.config/agent/settings.json")hash_all() {for f in "${CONFIG_PATHS[@]}"; do[[ -f "$f" ]] || continueprintf '%s %s\n' "$(sha256sum "$f" | awk '{print $1}')" "$f"done}case "${1:-check}" insave) # Build the baseline in a trusted state (back up config and baseline dir first)mkdir -p "$BASELINE_DIR"hash_all > "$BASELINE_DIR/manifest.sha256"echo "baseline saved -> $BASELINE_DIR/manifest.sha256";;check) # Verify before and after each sessionif [[ ! -f "$BASELINE_DIR/manifest.sha256" ]]; thenecho "no baseline; run '$0 save' first" >&2; exit 2fiif diff -u "$BASELINE_DIR/manifest.sha256" <(hash_all); thenecho "OK: no config drift detected"elseecho "ALERT: global config drift detected -> isolate session/pause agent, then roll back and rotate credentials" >&2; exit 1fi;;*) echo "usage: $0 {save|check}" >&2; exit 2 ;;esac
Response order when drift is detected (to avoid overwriting and losing the scene and data): isolate the session or pause the agent and preserve the scene → roll the config back to the trusted baseline from backup → then rotate credentials and hunt for persistence remnants.
3.3 Prompt/Execution Layering: Untrusted Content Can’t Act as High-Privilege Instructions
This is the most fundamental one. The attack succeeds because the agent puts “text read from a file” and “actions to be executed” on the same layer, with no trust grading.
- Build trust tiers: direct user input > trusted in-repo specs > external/downloaded content. The lower the tier, the smaller the action permissions it can trigger.
- Common project spec files like
AGENTS.md,README,CLAUDE.md,.cursorrules, and so on should be treated as “data” rather than “commands” by default, regardless of source; sensitive actions such as changing config, installing dependencies, or making network calls should be forced through explicit user confirmation. - Model “prompt injection” as an ordinary threat: any controllable text that enters the context should be assumed to possibly contain privilege-escalation intent like “ignore the previous constraints.”
3.4 Outbound Allowlist: Cut Off Malicious Dependencies from Landing and Calling Home
However stealthy a malicious package is, it usually still has to connect out to download its real payload or call back to a control server. An outbound allowlist is the most effective and most easily overlooked physical boundary.
- Default-deny network access for agent sessions, allow on demand, and only open outbound to trusted dependency registries and trusted API domains.
- Route dependency installs through a unified egress; forbid direct connections to arbitrary addresses; alert immediately on “connects to an unfamiliar domain right after install.”
- Run sessions in a container or isolated workspace so the outbound policy is decoupled from the host network, shrinking the blast radius.
A reusable outbound allowlist template:
| Domain | Port | Purpose | Approver | Valid Until |
|---|---|---|---|---|
| registry.example.com | 443 | Dependency pulls | John Doe | 2026-12-31 |
| api.example.com | 443 | Business API | Jane Smith | 2026-06-30 |
3.5 Rotate on Discovery: Assume You May Already Be Compromised
The first four gates are prevention and detection; the fifth is response, shifting the posture from “trusting that nothing happened” to “assuming it already did.” Rotation order: cut the network or pause the session → revoke the tokens, keys, and session cookies the session could reach → then hunt for persistence remnants like environment variables, locally cached credentials, and exported tokens → finally roll back the config. The agent has most likely already touched these credentials, and you need to check whether backdoors were left in dependencies, scripts, and config — not just roll back that one change.
4. Control Mapping Table
| Attack action | Risk | Detection category | Key control | Common false positives / exclusions | Response when triggered |
|---|---|---|---|---|---|
| Web page writes to download dir | External file lands | Entry detection | Download-dir monitoring + isolated workspace | Documents the user downloaded on purpose | Isolate the file, tag the source |
| Session started in download dir | User habit exploited | Entry detection | “Download dir is not a project root” | Cases that only need read-only viewing | Guide migration to a controlled dir |
| Spec file read as instructions | Data treated as command | Prompt/execution layering | Trust tiers + sensitive-action confirmation | Legitimate in-repo specs written by the user | Block and review the spec content |
| Global config rewritten | Account-level persistent contamination | Configuration integrity | Baseline hash + pre/post-session check | Config changes the user made intentionally | Isolate → roll back → rotate |
| Malicious dependency installed and calls home | Payload lands and phones out | Outbound allowlist | Default-deny + unified dependency egress | Normal updates within a trusted registry | Cut network + hunt for remnants |
5. FAQ
- How do you prevent prompt injection in coding agents? The core is treating external content as data rather than instructions, requiring a second confirmation for sensitive actions, and pairing it with an outbound allowlist to limit callbacks.
- What if a project spec file is tampered with? First isolate or pause the session to preserve the scene, roll back to the trusted baseline, rotate credentials, then hunt for persistence remnants.
- Is the download directory safe? Harmless on its own, but it is often a location web pages can write to — don’t start a session with it as the project root.
6. Conclusion
What makes this class of problem so unsettling is precisely that there is “no bug to fix” — every step performs its duty compliantly, and the vulnerability hides in the trust gap between one duty and the next. So the right defensive posture isn’t to wait for an upstream fix but to treat untrusted content as untrusted: shrink the entry points, verify the config, layer trust, restrict outbound, and rotate on discovery. Only these five gates together can put an agent that is “working as designed” back inside boundaries you can audit and control.
