Indirect Prompt Injection in AI Agents: From Risk Validation to Defense in Depth
As AI agents gain the ability to browse the web, read emails, parse documents, and call tools, they become exposed to indirect prompt injection: malicious instructions hidden inside the external content they process. This article breaks down how indirect injection works, the three key roles in an attack chain (source, sink, and canary), what large-scale security testing reveals about real-world success rates, why common defenses fall short, and how to build a production-grade, defense-in-depth architecture covering content isolation, least-privilege tooling, human confirmation, policy gateways, and audit logging.
As large language models gain the ability to browse the web, process emails, analyze documents, orchestrate tasks, and call external tools, AI agents have evolved beyond simple question-answering systems. They are now automated systems capable of reading external information and taking real-world actions.
This expanded capability brings new security risks. A user asks an agent to summarize an email, but the email body contains a hidden instruction. A user asks an agent to analyze a webpage, but the page contains text designed to make the agent leak information or invoke a tool. A user loads a task template or skill package that includes operations unrelated to the original goal. When an agent cannot distinguish between “data” and “instructions,” it may execute malicious text from external content as if it were a legitimate user command.
This class of vulnerability is known as indirect prompt injection. It doesn’t require an attacker to breach a server, compromise an account, or tamper with model weights. An attacker only needs to control a piece of content that the agent will read.
What Is Indirect Prompt Injection
Direct prompt injection occurs when an attacker interacts with a model directly, explicitly entering malicious instructions, such as asking the system to ignore its rules, leak internal information, or perform unauthorized actions.
Indirect prompt injection works differently. The attacker never interacts with the agent directly. Instead, they embed malicious instructions inside third-party data that the agent is expected to process, such as:
- Webpage content, comment sections, and search results
- Email bodies, attachments, or shared documents
- Support tickets, chat logs, and knowledge base entries
- Auto-loaded task templates, plugin descriptions, or skill configurations
- Unstructured content like images, tables, and code comments
When an agent invokes a reading tool, the external data enters its context window. If the system doesn’t clearly label the source of that data or restrict the authority of instructions found within it, the model may misjudge the situation, treating content meant to be analyzed as a command to be obeyed.
Think of it like a document processor. A user asks them to read a contract and summarize the risks, but the contract contains a sentence instructing them to send internal credentials to a specific address. If the processor can’t tell the difference between the task and an embedded instruction, they may follow the hidden command. This is the core risk of indirect injection.
Three Key Roles in the Attack Chain
To describe this problem more precisely, the attack process can be broken into three components, source, sink, and decision point, along with a canary used to verify whether an attack succeeded.
1. Source: Where External Content Enters the System
The “source” is the tool or data channel through which an agent reads external information. Common examples include web scraping, email reading, document parsing, knowledge base retrieval, and skill loading.
A source isn’t inherently a vulnerability, but it determines whether untrusted content can reach the model’s context. Many systems append tool outputs directly into the prompt, often wrapped in natural language like “here is the relevant information.” This is convenient for development, but it makes it easy for the model to overlook how trustworthy that content actually is.
2. Sink: Where Real-World Impact Occurs
The “sink” is the action an agent ultimately takes, the point where an attack’s effects can materialize. Examples include:
- Sending an email or message
- Submitting a form or creating a ticket
- Modifying or deleting data
- Executing a script or accessing an internal API
- Publishing content or triggering an automated workflow
- Initiating a payment, transfer, or permission change
If an agent only generates text, the impact of an injection is usually limited to an incorrect response. But once the agent has tool-calling capability, the risk escalates from content contamination to unauthorized action.
3. Canary: Verifying Whether Output Was Compromised
Some attack goals don’t require tool invocation at all. They only need the model to output a specific string to confirm success. Testers can plant a unique marker ahead of time and check whether the model outputs it under conditions where it shouldn’t.
A canary should never contain real passwords, real credentials, or sensitive business data. Its purpose is to provide a verifiable signal, not to simulate an actual leak. In production systems, use randomized markers with no business meaning, and keep test data fully isolated from real environments.
4. The Full Attack Chain
A typical chain looks like this:
Malicious instructions are embedded in external content
→ The agent reads that content through a tool
→ The malicious text enters the model’s context
→ The model misjudges instruction priority
→ The agent produces an abnormal decision
→ A high-risk tool is invoked, or sensitive content is output
→ Data leakage, unauthorized action, or business loss occurs
The core issue here isn’t that the model “doesn’t understand well enough.” It’s that the system never established a reliable trust boundary.
What Large-Scale Security Testing Reveals
Security evaluations of agent frameworks typically involve designing multiple categories of attack samples and running a large volume of trials to observe success rates across different tool chains, context structures, and prompt combinations. One such evaluation involved roughly fourteen thousand experiments, with certain attack types achieving a success rate of around 25.5%.
This number deserves attention, but it shouldn’t be read as “one in four tasks will always be compromised.” Success rates depend on several factors:
- The model version and context length in use
- The number of tools available and their permission scope
- The format and placement of external content
- How strictly the system prompt constrains behavior
- Whether human confirmation is required
- The complexity of the attack sample
- Whether success is measured by canary output or by an actual completed action
Even when the overall success rate is relatively low, the risk can’t be dismissed if the system is connected to sensitive tools. Attackers can retry repeatedly, or chain together multiple low-probability steps to raise their overall odds of success. For high-impact actions like payments, permission changes, or data deletion, a single successful attempt can cause serious damage.
Why Traditional Defenses Fall Short
1. Relying Solely on the System Prompt
Many applications add a line to the system prompt instructing the model not to follow instructions found in external content. This is a necessary measure, but not a complete defense.
The system prompt still depends on the model’s own judgment to draw the line between data and instructions. When context is long, instructions are disguised, or external text is formatted to mimic a system notification, the model can confuse priorities.
2. Keyword Filtering Alone
Filtering for phrases like “ignore the above” or “leak this information” can catch some simple attack samples, but it struggles against rephrasing, text splitting, encoding, text embedded in images, and subtler forms of semantic persuasion. Attackers don’t need fixed phrases. Ordinary-sounding business language can be enough to steer a model’s decisions.
3. Reviewing Only the Final Output
If a system only audits the model’s final text response without inspecting tool call parameters, it can miss critical risks. Many attacks don’t try to get the model to output sensitive information directly. Instead, they push the model to invoke a specific tool, shifting the risk to the execution stage.
4. Granting Agents Excessive Default Permissions
Even if a model occasionally misjudges a situation, strict tool permission limits can contain the damage. Conversely, if an agent has unrestricted data access, unrestricted network access, or the ability to perform irreversible actions, a single injection can escalate into a serious incident.
Building a Production-Grade Defense System
1. Clearly Separate “Data” from “Instructions”
Applications should explicitly label the source of content within the context, such as:
- User instructions
- System rules
- Tool-returned data
- Untrusted web content
- Documents awaiting analysis
- Actions requiring human confirmation
This labeling shouldn’t rely on natural language alone. Source information should be preserved as structured metadata, rather than letting everything collapse into one undifferentiated block of text.
2. Establish a Least-Privilege Model
When an agent invokes tools, it should follow the principle of least privilege:
- Deny high-risk operations by default
- Grant permissions temporarily, scoped to the specific task
- Restrict the range of accessible data
- Restrict network addresses, file paths, and resource types
- Require separate authorization for write, delete, send, and payment operations
A task that only requires summarizing an email has no need for permission to send emails, read an entire contact list, or access internal admin interfaces.
3. Require Confirmation for High-Risk Actions
Any action with external effects or irreversible consequences should include a confirmation step. The confirmation prompt should clearly display:
- The specific action about to be taken
- The tool and parameters involved
- Who the data is being sent to
- Where the data came from
- Whether sensitive information is included
- Whether the action can be undone after it’s completed
Confirmation shouldn’t be a vague “continue?” prompt. Users need enough information to actually understand what the agent is about to do.
4. Use a Tool-Calling Gateway
Insert a policy gateway between the model and the actual tools to independently validate every tool call. The gateway can check:
- Parameter format and valid ranges
- Whether the target resource falls within the authorized scope
- Whether sensitive data is being sent externally
- Whether the call frequency is abnormal
- Whether the current task actually has the required permissions
- Whether the action needs escalation to human approval
With this layer in place, even if the model is influenced by malicious external text, an abnormal tool call can be blocked before it executes.
5. Tag External Content by Risk Level
The content pipeline can classify incoming data as trusted, internal, untrusted, or pending review. Content from public webpages, unknown senders, or user-uploaded files should never be granted instruction-level authority by default.
It’s also important to avoid treating self-declared labels in external text, like “system message” or “administrator notice,” as genuine identity claims. Identity should be confirmed through program metadata, not asserted by the text itself.
6. Maintain a Complete Audit Trail
Security auditing shouldn’t just preserve the final response. It should also log:
- The user’s original request
- What content the agent read
- Where that content came from
- What tool calls the model proposed
- What the tools actually executed
- Which policies were triggered or blocked
- Whether the user provided confirmation
Only with a complete trail can teams pinpoint, after an incident, whether the root cause was data contamination, a flawed model decision, misconfigured permissions, or a gateway failure.
Designing Effective Security Tests
Organizations can build a dedicated indirect injection test suite covering the following dimensions:
- Source: web pages, emails, documents, knowledge bases, images, and tables
- Expression: direct commands, role impersonation, context confusion, segmented payloads, and multi-turn escalation
- Target: sensitive data exposure, tool invocation, permission changes, external data transmission, and data modification
- Permission level: no tools, read-only tools, restricted write access, and high-risk tools
- Detection method: canary output, abnormal parameters, unauthorized reads, and real side effects
Testing shouldn’t focus only on attack success rate. It should also track false positive rate, where interception occurs in the pipeline, how often human confirmation is triggered, the scope of potential sensitive data exposure, and recovery cost.
These tests should be part of continuous integration and release processes. Every time a model, prompt template, tool description, or permission policy changes, core test cases should be rerun to prevent security posture from degrading as features evolve.
What Developers Need to Understand
At its core, indirect prompt injection is a new trust boundary problem created by connecting natural language processing systems to automated execution systems. External content can be read, but reading it shouldn’t grant it execution authority. A model can make suggestions, but it shouldn’t have inherent final authorization. Tools can improve efficiency, but they must remain subject to independent policy enforcement.
Security design, therefore, shouldn’t focus solely on making the model “more obedient.” It should shift toward ensuring that even when the model makes a wrong judgment, the system doesn’t produce uncontrolled consequences.
A reasonably robust architecture needs four layers working together: input content isolation, model decision constraints, tool permission control, and execution audit logging. Any single measure can fail on its own. Only defense in depth can reduce the chance that an indirect injection spreads from the text layer into actual business systems.
For teams building agent applications, the most important practice isn’t adding one more prohibitive line to a prompt. It’s reexamining the entire execution chain, from data sourcing and permission models to tool gateways, human approval, and continuous testing. Only by turning “external content is untrusted” into actual code, policy, and audit mechanisms can an agent’s automation capabilities deliver value within a controlled boundary.
