Prompts Say "Don't" but Configs Say "Welcome": Five Security Gates for Coding Agents
Coding agents that read project instruction documents can be tricked into modifying their own global configuration and installing malicious packages. Because this behavior follows the product design, vendors cannot patch it; defenders must rely on their own controls. This article breaks down the reported attack chain and presents five actionable detection categories—entry control, configuration drift detection, prompt/execution separation, outbound allowlists, and rotate-on-discovery—along with a check script, a control mapping table, and rollout recommendations.
Introduction: No vendor can patch this here
A security research organization recently published an attack reproduction report. According to the report, a web page can silently place a “project specification” document into a user’s download directory. After the user starts a coding agent in that directory, the agent treats the document as project conventions, then rewrites its own global configuration and installs malicious packages.
The organization tested two independent coding tools: one executed the malicious package in more than 90% of samples, while the other was affected in about half of the cases.
The most striking sentence in the report is this: no vendor can patch this here.
This sentence is often read as an excuse for vendors, but it is actually a judgment. Two independent chains that do not share code were exploited in the same way. That suggests the problem is not likely a defect in one implementation. It is more likely related to “what a coding agent is.”
A coding agent must read instruction documents in a project directory to understand the project. It must also be able to call external tools so developers can work smoothly. When these two capabilities exist in the same session, a document from an untrusted source is enough to change how the agent operates.
A comparison: when a browser renders a highly realistic bank login page, the browser has not necessarily done anything wrong. The attack is in the page, so there is no patch the browser can apply. Coding agents are similar. If a document claiming to describe “local development environment configuration” asks the agent to append an external tool integration configuration to the global configuration, and the agent complies, it is, at the session level, behaving as designed.
You do not have to accept the analogy completely, but the conclusion is hard to avoid: if vendors cannot fix it, defense has only one remaining landing point—build your own gates.
1. Breaking down the attack chain: every step has an observable location
The disclosed chain has five actions. Breaking them down in order is useful because each step leaves an observable trace in the real world.
Step 1: A web page writes a file into the download directory.
According to the report, an attack page can specify a filename and content, silently writing the file to the download directory without additional clicks or confirmation. Operating systems have protections against automatically running downloaded executables, but this action alone is almost harmless because what is written is only a Markdown document. The problem is that guardrails designed for executables do not apply to documents.
Step 2: The user launches the agent in the download directory.
Telemetry cited in the report shows that about half of coding agent users have run agents in the download directory, and about one quarter of sessions open a browser. These numbers show that the attack path works not by coincidence but through habit. Download directories are often places where users casually unzip files and look at things, and document files are naturally suited to “open it first and see.”
Step 3: The agent reads the document and rewrites the global configuration.
The real sample described in the report is an approximately 13 KB “engineering work standards” document. The attack is hidden in a section named “Local Development Environment.” From context, this section asks the agent to append an external tool integration configuration to the user-level global configuration file. It is placed here because it matches the real scenario of “a new colleague sets up the environment first.” It reads like reasonable advice, not a command.
Step 4: A malicious extension is loaded, and a package is installed and executed.
Once the global configuration is written, subsequent agent sessions load the newly registered external tool. When the package declared by that tool is fetched, the package manager by default executes its installation lifecycle scripts. This step obtains real code execution under the user’s identity, not just a piece of text.
Step 5: The impact crosses project boundaries and persists.
What was changed is the user-level global configuration, not a temporary file inside a project. From then on, no matter which directory the user launches the agent from, this configuration takes effect. At the same time, because the agent can open a browser, the runtime environment often has network access. A malicious extension can use that to send local files or credentials from environment variables to an external destination.
This chain shows that the real danger is not one prompt sentence. It is that untrusted input has penetrated all the way into trusted configuration.
2. Why “do not execute” in the prompt did not stop it
Many people instinctively object: doesn’t the system prompt already say “do not execute”? Why was the agent still affected? To answer this, we need to look at the levels of instructions in a coding agent and their practical effect.
- Session system prompt: issued by the product, defining the agent’s basic behavior rules.
- User-level global configuration: maintained by the user, determining which external tools the agent can load.
- Project instruction document: placed in the project directory, defining the project’s standards, style, and common commands.
Product documentation usually recommends putting project conventions into the project instruction file and states that it will serve as an important reference when the agent works. The problem is that there is no clear boundary between “important reference” and “can be directly executed.”
When a project document contains a natural sentence such as “please add the following entry to the global configuration,” the agent faces an ambiguity: is this an instruction to execute, or content to judge?
If it follows it directly in execution mode, “do not execute” becomes a slogan that cannot constrain itself. More importantly, the project document is originally low-privilege input, but it can write to high-privilege user-level configuration. This is a typical privilege escalation.
Therefore, the focus of protection should shift from “wording” to “boundary”: do not leave a channel through which low-privilege input can touch high-privilege configuration, and verify whether configuration has been changed at the start of every session.
3. Five executable detection categories
Around this attack chain, defense can be organized into five detection categories. The first four are about “prevent” and “see.” The fifth answers “what to do after seeing it.”
3.1 Entry detection: limit where untrusted instruction files can land
This layer addresses the problem of “files entering trusted directories.” The idea is to keep untrusted content outside the workspace.
- Tighten the working directory: only allow coding agents to start in managed project directories. In runtime settings, disable traversal to parent directories and do not allow the user home directory or download directory to be used as the workspace.
- Converge browser download locations: use browser management policies to point the default download location to a dedicated directory, and require that newly added document files in that directory be checked first. If the organization uses unified endpoint device management, such policies can usually be deployed centrally.
- Control file sources and attributes in the workspace: check for documents from unexpected sources, documents that are too new, or documents with abnormal attributes, especially “new specifications” in nested directories. Verify the source and content before ingesting them.
One of the most overlooked points in this layer is that you must constrain both “where files can land” and “where the agent can read from.” If you only restrict the latter, users may still drag files from the download directory into the project. If you only restrict the former, the agent may still be started directly in the download directory. Both need to be done together.
3.2 Configuration integrity detection: make configuration drift a determinable signal
This layer answers whether the global configuration has been changed by a person or the agent, and what it has become.
- Baseline it: put the user-level global configuration under version control as the reviewed expected value, including file hashes, the external tool list, and startup commands.
- Verify per session: before each session starts, compute the current configuration hash, compare it with the baseline, and record the modification time and differences.
- Run in a controlled environment: when running in a pipeline or controlled development environment, make verification a prerequisite pipeline step. If there is a mismatch, fail.
Where the baseline is stored determines whether this gate is effective. If the baseline is placed in the same directory as the configuration, or in a workspace that the agent can write to, an attacker can change the configuration and then casually change the baseline. The check then becomes “checking itself.” The baseline should be placed where the agent cannot write, such as a centralized configuration management service or a protected branch, and maintained by an account different from the agent’s identity.
In addition, “hash matches” only proves that the configuration has not changed. It does not prove that the configuration itself is safe. During baseline review, each external tool integration should be reviewed item by item: what it connects to and where its startup command points.
3.3 Prompt and execution separation: bring documents back to “reference only”
The third layer does not detect files. It redraws the responsibility boundaries inside the agent.
- Prompt layer is read-only: project instruction documents, README files, and similar materials belong to the prompt layer. They only influence how the agent understands and plans tasks. They cannot directly trigger configuration changes or package installation.
- Execution layer requires explicit authorization: writing to the global configuration, registering external tools, and installing software packages belong to the execution layer. They require user confirmation or independent approval and must keep complete audit records.
- Mark trust levels by path: documents in managed project directories can be used directly as context. Content from the download directory, archives, or other untrusted locations should be marked as untrusted and presented only as “references,” not executed as instructions.
Given that existing tools generally treat project documents as “important references,” the most realistic implementation options are:
- Choose a usage mode that supports distinguishing instruction files by source and requires secondary confirmation for sensitive operations.
- Build your own wrapper layer: before handing a document to the agent, scan for patterns such as “request to modify configuration” or “request to install software packages.” If matched, strip it or downgrade it to a prompt.
It should be emphasized that this kind of scanning is only a supplementary measure and cannot replace permission isolation. An attacker can bypass keyword matching by changing wording, but permission boundaries do not change with wording.
3.4 Outbound allowlist: deny by default, allow as needed
The first two layers address “files cannot get in” and “configuration was not changed.” The fourth layer assumes the first two will eventually have gaps and limits where the environment around the agent can connect.
- Process-level outbound control: in the container or sandbox where the agent runs, deny all outbound traffic by default and allow only reviewed targets, such as internal artifact repositories, code hosting platforms, and necessary service endpoints.
- Package source segmentation: installation access should go only through mirrors or proxy repositories, and newly appearing packages should be scanned. Installation lifecycle scripts can be disabled when allowed.
- Adjust according to browser telemetry: the report notes that about one quarter of sessions open a browser. This traffic needs separate planning. Otherwise, a blanket outbound ban will directly interrupt normal work.
It must be acknowledged that maintaining an allowlist is not cheap. Therefore, it is better suited to cover high-risk scenarios first: sessions started in download or temporary directories, one-off script tasks, and sessions handling external code and documents.
3.5 Response detection: rotate on discovery, do not gamble on “probably nothing happened”
The last layer answers “what to do after an anomaly is found.” When configuration drift is detected, suspicious instruction files appear in the workspace, or unregistered destinations appear in outbound logs, the principle should be “rotate on discovery,” not first arguing that “the agent may not have read that file yet.”
A complete response should include at least:
- Credential rotation: code hosting credentials, artifact repository credentials, cloud access keys, and tokens in environment variables that the agent’s runtime identity can access.
- Permission reduction: check whether the agent’s runtime account has unnecessary write permissions, especially whether it can write to user-level configuration. Whether it can read environment variables also directly determines whether credentials could have been read.
- Retrospective investigation: review commits, build artifacts, and dependency changes within the event time window.
- Postmortem hardening: turn the incident into new detection rules.
A single detection can only shorten the exposure window. Only multiple gates layered together can reduce the probability of a single successful exploitation to an acceptable range.
4. Configuration drift check script
The following script uses only the Python standard library and can be placed in the pipeline step “before starting the agent.” Note that the paths, field names, and allowlists in the example are illustrative. Replace them with the actual global configuration structure of the tool you use and your team’s baseline.
#!/usr/bin/env python3"""Configuration drift check: turns "the agent changed its own configuration without approval" into a deterministic pipeline assertion.Usage:python3 config_drift_check.py --config ~/.agent/global.toml --baseline config-baseline.jsonExit codes: 0 pass; 1 drift detected; 2 baseline untrusted, judgment refused."""import argparseimport hashlibimport jsonimport sysimport tomllibfrom pathlib import PathMAX_SIZE = 256 * 1024 # Configuration size limit to prevent abnormal expansiondef main() -> int:parser = argparse.ArgumentParser()parser.add_argument("--config", type=Path, required=True, help="User-level global configuration path")parser.add_argument("--baseline", type=Path, required=True, help="Review baseline; must be in a location the agent cannot write")args = parser.parse_args()# 1) Baseline trust: same directory as configuration, or inside the current workspace, may be rewritten by the same sessionbaseline = args.baseline.resolve()if baseline.parent == args.config.resolve().parent or baseline.is_relative_to(Path.cwd().resolve()):print("[ABORT] Baseline is in the same directory as the configuration or inside the workspace; it can be rewritten by the same session. Judgment refused.")return 2if not args.config.exists():print(f"[SKIP] Configuration does not exist: {args.config}")return 0raw = args.config.read_bytes()if len(raw) > MAX_SIZE:print(f"[FAIL] Configuration size {len(raw)} bytes exceeds limit {MAX_SIZE}")return 1try:current = tomllib.loads(raw.decode("utf-8"))except (tomllib.TOMLDecodeError, UnicodeDecodeError) as exc:print(f"[FAIL] Configuration cannot be parsed: {exc}")return 1expected = json.loads(baseline.read_text(encoding="utf-8"))problems = []# 2) Overall hash comparisondigest = hashlib.sha256(raw).hexdigest()if digest != expected.get("sha256"):problems.append(f"Hash mismatch: baseline {expected.get('sha256', '')[:12]}… -> current {digest[:12]}…")# 3) External tool integration entries must all come from the reviewed allowlistallowed = expected.get("extensions", [])actual = current.get("extensions", [])for item in actual:if item.get("name") not in allowed:problems.append(f"Unregistered integration entry found: {item.get('name')} -> {item.get('command', '<no startup command>')}")for name in allowed:if name not in {item.get("name") for item in actual}:problems.append(f"Registered integration entry missing: {name}")# 4) Compare key fields one by onefor key, value in expected.get("keys", {}).items():if current.get(key) != value:problems.append(f"Field changed: {key}; expected {value!r}, actual {current.get(key)!r}")# 5) Warn about top-level sections not listed in the baselinefor section in set(current) - set(expected.get("keys", {})) - {"extensions"}:problems.append(f"Configuration section not present in baseline: [{section}]")for problem in problems:print(f"[FAIL] {problem}")if problems:return 1print("[PASS] Configuration matches the reviewed baseline")return 0if __name__ == "__main__":sys.exit(main())
This script only performs detection; it does not perform repair. Once drift is found, the correct approach is to restore the configuration from the controlled baseline, not to have the script automatically overwrite it. Overwriting destroys evidence and cannot rule out the possibility that the malicious configuration was already loaded by another session.
5. Control mapping table
| Attack stage | Exposure by default | Detection signal | Corresponding gate | Failure consequence |
|---|---|---|---|---|
| Document landing | A web page can silently write files to the download directory | New specification-like documents appear in the download directory | Converge download locations; check source and content before specification-like files enter the project | Untrusted documents enter a trusted directory |
| Launch location | Users habitually start agents in download or temporary directories | Workspace is in a download or temporary directory | Only allow managed project directories; disable upward traversal | An untrusted directory becomes trusted context |
| Prompt vs. execution | Project documents are treated as “important references” and can write to global configuration across privilege levels | Conversation contains requests such as “modify configuration” or “install software package” | Mark trust levels by path; require secondary confirmation for sensitive operations; keep audit records | Document content is treated as instructions and executed |
| Configuration integrity | Global configuration can be rewritten by the agent’s runtime identity | Global configuration hash changes or unregistered integration entries appear | Baseline snapshot; pre-session validation; pipeline assertion | Malicious extensions persist across projects and sessions |
| Outbound access | Environment can access arbitrary destinations by default | Unregistered download sources or callback addresses appear | Outbound allowlist; software packages obtained only from controlled repositories | Packages and installation scripts gain execution opportunities; credentials may be exfiltrated |
| Discovery and response | Credentials remain valid for a long time and there is no audit trail | Drift alerts and abnormal outbound records | Rotate on discovery; reduce permissions; review commits and builds | Attackers persist for a long time and move laterally |
6. Rollout recommendations
Applying the five detection categories to daily development workflows can be done in three stages.
Build visibility first; do not start with a blanket ban.
First collect global configuration snapshots, agent launch directories, and outbound records to understand how the team actually uses agents, for example how many people habitually start agents in the download directory. Without baseline data, gate thresholds can only be guessed.Then cover high-risk scenarios.
Prioritize sessions in download and temporary directories, sessions handling external documents and code, and sessions holding high-privilege credentials. In these scenarios, add outbound allowlists and “rotate on discovery.”Finally integrate into daily workflows.
Put configuration validation into the pipeline as a prerequisite step, connect drift alerts to monitoring and alerting channels, clarify owners and response time limits, and periodically run a drill on “how to rotate credentials after drift is discovered.”
A few details that are easy to overlook:
- The baseline must be reviewable: the global configuration should be maintained by a designated person, and any new external tool integration should require a review record.
- Validation must have a failure loop: a gate that only alerts and does not block is often ineffective when deadlines are tight.
- Do not overtrust keywords: scanning for phrases such as “ignore the above instructions” or “modify the configuration file” can only filter crude attacks. What really works is permission boundaries.
- Do not block the authorization channel: when a new external tool is genuinely needed, follow the normal review and change process so that “legitimate changes” and “attack behavior” are distinguished by process.
Conclusion
The value of this report is not that it demonstrates one attack chain. Its value is that it pushes the problem to the right place: the security of coding agents increasingly depends on the runtime environment around them, not on how clever the model itself is.
A prompt can say “do not execute.” But as long as configuration can be freely rewritten, software packages can be freely installed, and the environment can connect to anywhere, “do not execute” is only a wish.
Building the five gates—entry, configuration, separation, outbound, and response—one by one is the only way to turn the risk brought by “agents working as designed” into an engineering problem that can be measured, blocked, and held accountable.
