How to Prevent Indirect Prompt Injection: A Practical Security Guide for AI Agents

    Indirect prompt injection occurs when untrusted content from web pages, documents, emails, or other tools is mistaken for an instruction by an AI agent. This guide explains how the attack path works and presents a layered defense strategy based on input sanitization, content isolation, least-privilege access, action confirmation, authorization testing, and continuous security checks.

    Authorization and Compliance

    This article is intended to help developers understand security risks and build defenses. It does not provide directly reusable attack payloads. All security testing must be conducted on systems you own or in environments where you have written authorization, using an isolated sandbox and simulated data. Testing someone else’s systems without authorization may be illegal.

    Introduction: Content Read by an Agent Can Become an Instruction

    AI agents use tools such as web browsing, document parsing, and email access to gather information. Because this content comes from external sources, developers cannot fully control the text it contains. If an agent treats external text as an instruction, an attacker may influence its behavior through third-party content without interacting with the conversation directly. This risk is known as indirect prompt injection.

    The risk is particularly serious because agents often have capabilities such as sending emails, changing settings, or calling APIs. Once a model misjudges the role of external content, the result can go beyond an incorrect answer and become an unauthorized action.

    1. Build Four Defensive Gates

    Protection should cover the entire path from input to action. All four gates should be used together.

    Gate 1: Sanitize Inputs

    Before external content is sent to the model, convert rich text to plain text and remove hidden elements, invisible characters, and comments. Sanitization can reduce risk, but it cannot eliminate it completely and must not be treated as the only defense.

    Gate 2: Isolate Content

    Add clear boundary markers around external data. The system prompt should explicitly state that content within those boundaries is reference material only and does not constitute an instruction to perform an action.

    These boundaries should be designed together with the tool-layer data structures, and their effectiveness should be validated through testing.

    Gate 3: Apply Least Privilege

    Give the agent only the tools and permissions required for the current task. Read-only and write-capable tools should have separate authorization. Permissions that are not necessary should not be granted.

    Gate 4: Confirm High-Risk Actions

    Before sending messages, making payments, deleting data, publishing content, or performing other high-risk operations, display the complete action, its parameters, and the external content that led to the action. Require confirmation from the user or an independent policy engine.

    High-risk operations may also require multifactor authorization. This ensures that even if the model is misled, it cannot complete the action on its own.

    If one defensive gate is bypassed, the others should still limit the potential damage.

    2. How Indirect Prompt Injection Happens

    Indirect prompt injection usually involves three stages.

    1. Source

    Web pages, documents, emails, chat messages, and plugin configurations read by an agent may be controlled or modified by third parties.

    2. Transfer

    Once external content enters the model context, it may appear alongside the user’s request. The model must determine which text represents the user’s intent and which text is reference material.

    3. Action

    If the model’s output triggers a tool call—such as sending a message or changing data—the attack reaches the stage where it can cause real-world impact. If the result is limited to incorrect text output, the impact is generally lower.

    Understanding these stages helps determine where defenses should be applied: restrict the trust level of sources, isolate content during transfer, and enforce controls before actions are executed.

    3. Common Risk Locations

    Developers should review the following areas:

    • External input points: Any tool that returns text, including web pages, files, API responses, and database fields.
    • High-privilege tools: Tools that can send messages, make payments, delete data, publish content, or execute commands.
    • Long-context sessions: Historical tool results may remain in the context and continue influencing decisions in later turns.
    • Multi-agent workflows: One agent’s output may become another agent’s input, allowing incorrect instructions to be amplified across multiple stages.

    During the review, assign a trust level to each type of input. Content from public web pages should be treated as untrusted. Data from controlled internal systems may present lower risk, but its format should still be validated.

    4. Why Models Are Susceptible

    Large language models do not inherently distinguish between data and instructions. System prompts, user messages, and tool results ultimately enter the model as tokens. The model mainly relies on role markers, position, and text structure to infer priority.

    As a result, if a tool returns content that is structurally similar to a formal instruction, the model may assign it too much weight. Developers should not assume that a model will automatically ignore command-like text found in external content.

    User requests are also often broad, such as “help me process today’s emails.” Broad requests leave the model more room to interpret the task, making it easier for external content to influence the agent’s understanding of the requested scope.

    For this reason, defenses should not rely solely on the model’s judgment. The system itself must impose additional constraints.

    5. Pre-Release Security Checklist

    Before releasing a new version of an agent, verify that:

    1. All external input sources have been registered and assigned a trust level.
    2. External content is sanitized before entering the model and includes clear boundary markers.
    3. All high-risk tools require human confirmation or policy-based confirmation.
    4. The agent has only the tools required for the current task, managed through an allowlist.
    5. Tool-call parameters are validated, and out-of-range parameters are rejected.
    6. Critical actions are logged, including the context and source that triggered each action.
    7. Regression testing has been completed in an isolated environment, with the results preserved.
    8. Blocking thresholds have been defined. For example, if the rate of unauthorized actions in a test category exceeds the limit set by the team, the release should be blocked. Thresholds should reflect the business risk and should not be copied from another organization’s environment.

    6. Authorized Testing and Interpreting Results

    Security testing should meet the following conditions:

    • Use an independent test environment.
    • Use simulated data and fictional accounts.
    • Direct test actions to harmless recording endpoints rather than real external addresses.
    • Record the model version, framework version, tool configuration, and evaluation criteria for every test.

    Evaluation should distinguish among three outcomes:

    1. Whether an action was triggered.
    2. Whether the output contained content that should not appear.
    3. Whether the agent requested confirmation before execution.

    Counting only “success” or “failure” can hide important differences in severity.

    When reviewing success-rate figures from research reports or vendor evaluations, verify the sample size, test environment, model version, and evaluation criteria. Figures without this context should not be used directly for security decisions.

    7. Integrate Security Reviews into Development

    The risk of indirect prompt injection changes as tools are added, models are updated, and business processes evolve. A one-time assessment can quickly become outdated.

    Add test cases to the continuous integration process. Run regression tests automatically whenever the model or tool configuration changes, and track how the relevant metrics change over time.

    The goal is not to prevent an agent from ever reading external content. The goal is to ensure that, after reading it, the agent can still distinguish what it should do from what it must not do.