Coding Agent Security: When the Prompt Says "Don't Execute" but the Config File Says "Go Ahead"

    A public reproduction report documents a repeatable attack path against several mainstream coding agents: a webpage silently drops a file disguised as project documentation into the Downloads folder, and when a user starts an agent there, it reads the file as project guidance, rewrites its own global configuration, and installs a malicious dependency. This article argues that the issue is an execution-environment architecture problem rather than a patchable defect—model-side alignment governs whether an agent "wants to" act, while trust boundaries in the runtime govern whether it "can." It breaks the chain into five inspectable stages, explains why prompt wording cannot close the gap, and provides a config-drift detection script plus a control-mapping table for building gates across local dev machines, CI pipelines, and cloud development environments.

    1. An Uncomfortable but Necessary Premise

    A public reproduction report from a security research group documents a path that exists in several mainstream coding agents: a webpage first drops a file disguised as project documentation into the Downloads directory; when a user starts an agent in that directory, it reads the file and treats it as project guidance; the file instructs the agent to modify its own global configuration, after which it installs a malicious dependency. The numbers in the report are telling: in their tests, one chain executed the malicious package more than 90% of the time, while another succeeded roughly half the time.

    The report’s most controversial sentence is: “There is nothing here for a model provider or a tool vendor to patch.” The authors are not letting vendors off the hook; their reasoning has two parts:

    • The reproduction crossed several independent product chains, and all of them succeeded;
    • Reading documentation files in the current directory, adjusting its own configuration, and installing project dependencies are all built-in capabilities by design.

    The report uses an analogy: when a browser renders a spoofed bank login page, the browser is doing exactly what it should—the attack lives in the page, not in the browser. In the same way, an agent that obeys the documentation file in its working directory is also working as designed. You may disagree with that conclusion, but it clarifies one fact: this looks more like a security-architecture problem than a bug waiting to be fixed.

    Seen across the AI application lifecycle, the agent’s identity is shifting: it has gone from “a model that gets invoked” to “an execution principal that owns a working directory, a config file, and package-management privileges.” Model-side safety alignment governs whether it “wants to”; trust boundaries on the execution side govern whether it “can.” When the file that gets trusted comes from an uninvited webpage, “wants to” is no longer a reliable line of defense.

    So for engineering teams, this line of defense has to move from “prompt reminders” to “runtime constraints.”

    2. Dissecting the Attack Chain: Every Step Has a Checkpoint

    The chain disclosed in the report breaks into five actions. Looking at them in order matters because each one lands on a specific, observable, interceptable point in the system.

    2.1 Entry: A Webpage Silently Writes to the Downloads Directory

    The Downloads directory is one of the few user-writable locations a webpage can write to on its own: no click, no confirmation, with the filename and contents both chosen by the page.

    The operating system is not defenseless, but its protections target “automatically running executables”—things like quarantine flags and origin checks. Plain-text instruction files such as AGENTS.md fall under none of the guardrails built for executables, and a single such action looks completely harmless on its own. Its danger only materializes when it meets an agent, which is exactly the blind spot that scanning files for malware cannot cover.

    2.2 Trigger: The User Starts the Agent in the Downloads Directory

    Telemetry in the report shows that roughly half of users have run a coding agent in the Downloads directory at some point, and about a quarter of sessions open a real browser. This path works not by coincidence but by habit: the Downloads directory holds archives and sample code sent by others, and unzipping and starting work on the spot is the most natural thing in the world.

    From the attacker’s point of view, the cost of the attack is offloaded onto a tiny action that is almost imperceptible: starting a tool in the wrong working directory.

    2.3 Read: The Agent Treats the File as Project Guidance

    After it starts, an agent typically reads the project documentation file in the current directory by convention, and its contents are treated as project guidance that constrains the agent’s subsequent coding behavior. The problem is what “treated as project guidance” actually means: the instructions in the file gain authority close to that of a command the user issues on the spot—and the system does not distinguish where each one came from.

    2.4 Landing: The Global Config Is Silently Rewritten

    In the chain disclosed in the report, this file asks the agent to modify its own global configuration. Why is this step worth calling out on its own? Because global configuration takes effect across projects and across sessions. A single change can alter the default permissions, tool allowlist, network policy, or identity credentials for every project afterward. A project-level file should never have the authority to change global-level settings, but under a “file contents are instructions” model, this kind of cross-level privilege escalation is not blocked by default.

    2.5 Execution: A Malicious Dependency Enters the Runtime

    After the config is changed, the file then asks to install a malicious dependency. By this point the attack has moved past the agent itself and landed in a stage with full code-execution capability: install hooks, post-install scripts, or simply top-level module code executed when the module is imported are all enough to run arbitrary logic on the build machine and the developer’s machine. That logic can steal environment variables, call back to an external host, or plant a persistent backdoor.

    3. Prompt/Execution Layering: Why Prompts Can’t Stop It

    Connect the five actions into a line and the problem becomes clear: on this chain, the decision of “whether to execute” has been handed to the file contents themselves. The prompt says “don’t execute,” the file says “go ahead,” and the system has no way to tell which sentence came from the user and which came from the file.

    The difference in success rates between two chains in the report (one over 90%, one about half) is also worth mulling over. This kind of gap is often related to whether user confirmation is required before execution—but even the lowest of them succeeds about half the time. That tells us: rewording the prompt can at most lower the success rate; it cannot change the nature of the problem. The value of an execution confirmation does not lie in “how many times it blocks,” but in whether it is a hard boundary that file contents cannot bypass.

    Borrowing the idea of prompt/execution layering, each run of the agent can be split into two layers:

    1. Prompt layer: handles “what to read.” System instructions come from the runtime platform; project documentation files can only offer coding preferences—naming style, directory layout, test conventions. File contents are always treated as data, not instructions.
    2. Execution layer: decides “what to do.” Every proposed action must answer three questions:
      • Who triggered it? User input, a project file, or a tool return?
      • Is the target within the authorized scope?
      • Is the impact reversible?

    Only the execution layer has the authority to turn an action into a side effect; the prompt layer has no right to cross over it. The pseudocode below shows the skeleton of this layering:

    1. # Illustration: assessing the origin and impact of "project-file-driven actions" at the execution layer
    2. RISK_ACTIONS = {
    3. "write_global_config": "high", # modify the agent's global config
    4. "install_dependency": "high", # introduce a new dependency (incl. install scripts)
    5. "network_request": "medium", # open an outbound connection
    6. "write_project_file": "low", # modify a file inside the project (reversible)
    7. }
    8. def propose(action, trigger="agent", args=None):
    9. """All actions enter a proposal queue and are adjudicated centrally by the execution layer"""
    10. level = RISK_ACTIONS[action]
    11. trusted = trigger in ("user", "platform_policy")
    12. # Non-user origin + high-risk action: always block and log; never enters the "allow by default" path
    13. if not trusted and level == "high":
    14. deny(action, trigger, reason="project-file-driven high-risk action")
    15. return
    16. if action == "write_global_config":
    17. deny(action, trigger, reason="global config is read-only for agents")
    18. if action == "install_dependency" and not pinned_and_allowed(args):
    19. deny(action, trigger, reason="dependency not in allowlist / not pinned")
    20. if action == "network_request" and not egress_allowed(args):
    21. deny(action, trigger, reason="destination not in egress allowlist")
    22. execute(action, args, trigger=trigger)

    A few key design points:

    • Separation of proposal and execution. What the agent outputs is only a proposal; an outer executor (runner) adjudicates and carries it out. The model cannot “authorize itself.”
    • Origin travels with the action. Every proposal carries a trigger tag indicating whether it was set off by the user, platform policy, or untrusted content such as project files or tool returns.
    • Global config is read-only to the agent. It can only be changed by the user or an administrator through a controlled process.
    • Tool results are treated as untrusted too. A malicious webpage can also enter the context through search results or fetched content, and the layering principle applies to them just as well.

    A more thorough approach is to run the agent inside a disposable container or sandbox: the working directory is mounted read-only, the global config is injected read-only, and the runtime identity is separated from the developer’s main account. That way, even if the model “wants to” execute, the damage it can cause is confined to a disposable environment.

    4. Five Categories of Actionable Detection

    Combining the chain disclosed in the report with the layering above, the defense can be narrowed to five categories of checks. Each corresponds to a clear observation point and a disposal action.

    4.1 Entry Detection: Watch Where the File Came From

    Monitor file-creation and rename events on common download directories and temporary extraction directories. The moment a file matching an agent’s documentation convention (such as AGENTS.md) appears, generate an alert with provenance attached: which browser tab triggered the download, the file size, the creation time.

    The point of the alert is not after-the-fact accountability but reminding the user that “this directory may already be contaminated.” A more robust approach is to tag directories: any directory from an external download or temporary extraction is marked “untrusted workspace” by default. When an agent starts inside it, it automatically enters read-only or propose-only mode.

    4.2 Config Integrity: Keep Your Own Settings From Being Changed

    The storage paths for global configuration, the tool allowlist, and identity credentials should have a trusted baseline, including the config file’s hash and the expected value of each field. Verify it once before the agent starts and once at the end of every session; a change in the hash or a key field is treated as drift.

    There is one principle here: the agent has read-only access to its own global config. It can modify files inside the project, but it cannot modify the definition of “what it is allowed to do.” Config drift does not necessarily mean an attack—a developer may genuinely want to flip a switch. So the response is not an automatic rollback but freezing the session, raising an alert, and waiting for human confirmation. The script below is implemented with the Python standard library and covers download-directory checks, suspicious-field scanning of the global config, and baseline comparison; you can drop it straight into CI or make it a pre-session check:

    1. #!/usr/bin/env python3
    2. """
    3. config_drift_check.py: agent config-drift and untrusted-instruction-file check
    4. Requires: Python 3.8+ standard library; see the end of the file for usage; adjust paths and field names to your actual tooling.
    5. """
    6. import hashlib
    7. import json
    8. import os
    9. import sys
    10. from datetime import datetime, timezone
    11. from pathlib import Path
    12. HOME = Path.home()
    13. # Common download-directory names (naming varies by OS / locale)
    14. DOWNLOAD_DIRS = [HOME / "Downloads", HOME / "下载"]
    15. INSTRUCTION_NAMES = ["AGENTS.md", "AGENT.md", "agent-instructions.md"]
    16. GLOBAL_CONFIG = HOME / ".config" / "agent" / "config.json" # example path
    17. BASELINE = HOME / ".config" / "agent" / "baseline.sha256" # trusted baseline
    18. # No switch that "loosens execution" should ever appear in the global config
    19. SUSPICIOUS_KEYS = {
    20. "dangerously": "skip safety confirmation",
    21. "skipconfirm": "skip execution confirmation",
    22. "skipapproval": "skip approval",
    23. "autoapprove": "auto-approve all actions",
    24. "trustall": "trust all origins",
    25. "allowall": "allow all destinations",
    26. "bypass": "bypass policy checks",
    27. }
    28. findings = []
    29. def report(level, location, detail):
    30. """Record and print an alert uniformly: level is INFO/WARN/CRIT"""
    31. findings.append({"level": level, "location": location, "detail": detail})
    32. ts = datetime.now(timezone.utc).isoformat()
    33. print(f"[{ts}] [{level}] {location}: {detail}")
    34. def check_downloads():
    35. """Entry detection: has an agent instruction file appeared in the download directory"""
    36. for d in DOWNLOAD_DIRS:
    37. if not d.is_dir():
    38. continue
    39. for name in INSTRUCTION_NAMES:
    40. for f in d.rglob(name):
    41. if f.is_file() and f.stat().st_size < 1_000_000:
    42. report("CRIT", f, "Agent instruction file found in the download directory; this directory should be tagged as an untrusted workspace")
    43. def check_config():
    44. """Config integrity: field scan + hash baseline comparison"""
    45. if not GLOBAL_CONFIG.is_file():
    46. report("WARN", GLOBAL_CONFIG, "Global config file not found; skipping check")
    47. return
    48. raw = GLOBAL_CONFIG.read_bytes()
    49. # 1) Suspicious-field scan
    50. try:
    51. data = json.loads(raw)
    52. except json.JSONDecodeError as e:
    53. report("CRIT", GLOBAL_CONFIG, f"Global config is not valid JSON: {e}")
    54. return
    55. def walk(obj, path=""):
    56. if isinstance(obj, dict):
    57. for k, v in obj.items():
    58. p = f"{path}.{k}" if path else k
    59. low = k.lower()
    60. for kw, desc in SUSPICIOUS_KEYS.items():
    61. if kw in low:
    62. report("CRIT", f"{GLOBAL_CONFIG}:{p}", f"Suspicious switch ({desc}): {v!r}")
    63. walk(v, p)
    64. elif isinstance(obj, list):
    65. for i, v in enumerate(obj):
    66. walk(v, f"{path}[{i}]")
    67. walk(data)
    68. # 2) Hash baseline comparison
    69. digest = hashlib.sha256(raw).hexdigest()
    70. if not BASELINE.is_file():
    71. report("WARN", BASELINE, "No trusted baseline found; generate one after human confirmation first (python config_drift_check.py --init)")
    72. else:
    73. baseline = {}
    74. for line in BASELINE.read_text(encoding="utf-8").splitlines():
    75. if line.strip():
    76. h, p = line.split(maxsplit=1)
    77. baseline[p.strip()] = h
    78. expected = baseline.get(str(GLOBAL_CONFIG))
    79. if expected is None:
    80. report("WARN", BASELINE, "Baseline is missing an entry for the global config")
    81. elif expected != digest:
    82. report("CRIT", GLOBAL_CONFIG, "Hash does not match the baseline; treat as config drift: freeze the session and get human confirmation")
    83. if __name__ == "__main__":
    84. if "--init" in sys.argv:
    85. # Only use when there is a trusted baseline source (e.g., a config-management repo); do not let the script generate a "self-certifying" baseline
    86. BASELINE.parent.mkdir(parents=True, exist_ok=True)
    87. h = hashlib.sha256(GLOBAL_CONFIG.read_bytes()).hexdigest() if GLOBAL_CONFIG.is_file() else ""
    88. BASELINE.write_text(f"{h} {GLOBAL_CONFIG}\n", encoding="utf-8")
    89. print(f"Baseline written to {BASELINE}")
    90. sys.exit(0)
    91. check_downloads()
    92. check_config()
    93. levels = [f["level"] for f in findings]
    94. print("------")
    95. print(f"Check complete: {levels.count('CRIT')} CRIT, {levels.count('WARN')} WARN")
    96. # CRIT means human intervention is required; CI/gates should use this as the blocking condition
    97. sys.exit(2 if "CRIT" in levels else 0)

    Two design points in the script need emphasis:

    • A baseline can’t vouch for itself. --init is only appropriate when there is a trusted source—for example, the baseline is hosted in a permission-controlled configuration-management repo and distributed after review. If the baseline lives on the same machine the agent can read and write, an attacker can change the config and regenerate the baseline, and the drift check is worthless.
    • Drift disposal is not an automatic rollback. It may just be the developer legitimately adjusting config; the script’s job is to surface the difference, preserve evidence, and hand the judgment back to a human.

    4.3 Prompt/Execution Layering: Let “Who Said It” Decide “Whether It Can Be Done”

    The principle in this section was already laid out earlier; on the detection side it comes down to two metrics:

    • Proposal interception rate: the number of high-risk actions triggered by untrusted sources such as project files and then intercepted;
    • Post-confirmation release rate: the proportion of actions executed only after the user explicitly confirms.

    If the interception rate stays at zero over the long term, it means either the detection isn’t working or no one has ever run an agent in an untrusted directory—and the former is the more worrying case.

    4.4 Egress Allowlist: Turn “Calling Back” into a Blockable Event

    The end goal of a malicious package is usually external communication, whether exfiltrating data or pulling a follow-on payload. Default-deny with per-destination allow is the most effective way to narrow this down. Common practices include:

    • Allow only known destinations such as package-registry mirrors, internal artifact repositories, and model services;
    • For unknown destinations, alert only and don’t block, to avoid disrupting normal development;
    • Route all network requests within an agent session through a proxy, logging complete target and response metadata per workspace and per session.

    Watch out for a “Downloads-directory exemption.” If an instruction file is detected in an untrusted workspace or the Downloads directory, the allowlist should tighten temporarily, keeping only the necessary service addresses.

    4.5 Rotate on Discovery: Default to “Credentials Are Already Leaked”

    The chain in the report stops at installing the malicious package, but once a real attacker has code execution, environment variables, token files, and version-control credentials are already within reach. So the response posture should be:

    1. Rotate first, investigate second. Treat all credentials usable during the session as leaked, and prioritize rotating cloud access keys, code-repository tokens, package-repository tokens, and SSH keys, rather than first spending hours locating the malicious file.
    2. Collect forensic evidence in parallel. Preserve agent run logs, proposal and execution records, network-connection metadata, and a read-only copy of the working directory.
    3. Trace back across everything. Search by time and origin for uses of the same credential on other sessions and other hosts.

    In one sentence: “rotate on discovery” is not an optional action but the default one. And it measures not an after-the-fact metric like MTTR (mean time to repair) but MTTD (mean time to detect)—how long the attack went from happening to being discovered.

    5. Control Mapping Table

    Attack step Attacker’s prerequisite Point mitigation Recommended gate Observable metric
    Webpage writes to Downloads Downloads can be silently written by a webpage Can’t block the write, only block the read Monitor + alert; directory-level untrusted tag Instruction-file appearances, alert response time
    Agent started in Downloads User habit + agent doesn’t check workspace origin Check on startup whether the working dir is a managed repo Block: refuse to start in non-allowlisted directories Refused-start count, sessions guided to migrate
    File treated as project guidance Project files carry the same authority as user instructions Project files provide coding preferences only, not execution authorization Separate the prompt layer from the execution layer Proposal interception rate, post-confirmation release rate
    Global config rewritten Agent can write its global config Agent has read-only access to global config Block: reject on write; changes require approval Config-drift alert count, mean disposal time
    Malicious dependency installed Dependency install can run scripts + egress unrestricted Pin dependency versions and verify hashes; disable install scripts by default; egress allowlist Block: dependencies and destinations not on the allowlist Interception count, unknown-destination count
    Credentials read Developer identity credentials can be read by the session Session uses a separate, least-privilege identity Rotate: session-level credentials rotated per use Credential rotation time, anomalous-use alert count

    How to read the table: “point mitigation” lowers the probability; “recommended gate” changes the nature. For example, an egress allowlist on an open network is just noise reduction; only when combined with “default deny” does it become a hard boundary. Config-hash comparison can itself be bypassed with a tampered baseline; only when the baseline is hosted in a controlled repo and the agent has read-only access to global config does it truly hold.

    Gates should also run across the full workflow:

    • Local dev machine: pre-check scripts + a runtime-layered executor;
    • CI pipeline: the same config-drift check and dependency-allowlist validation;
    • Cloud dev environment: wire the above checks into a unified logging, monitoring, and alerting system, with unified auditing of agent behavior inside cloud dev containers.

    Taking Baidu AI Cloud as an example, you can use its log service to centrally collect runtime and audit logs, use monitoring and alerting to set threshold notifications for events such as drift, interception, and unknown destinations, and pair it with key-management capabilities for centralized credential custody and fast rotation. The technical approach is general; any cloud environment can implement it the same way.

    6. Conclusion: Write “Don’t Execute” as a System Constraint

    Back to that opening line: if this class of problem can’t be solved by a vendor patch, then it can only become a check in your own gates. The conclusion sounds pessimistic, but it actually points the way: as an agent’s behavior looks more and more like “a developer with a filesystem and a command line,” the way you govern it should look more and more like the way you treat an internal account with write access:

    • Least privilege;
    • Trusted origins;
    • Changes that leave a trail;
    • Rotate on anomaly.

    That “don’t execute” in the prompt should be translated into read-only mounts, allowlist checks, and proposal confirmation in the execution environment. The user can say “go ahead,” but the system must always retain the ability to say “no.” The value of this reproduction report is not that it demonstrates some product can be compromised, but that it reminds us: every file an agent trusts is an implicit authorization. Only by governing that layer of authorization have you truly fitted a coding agent with brakes.