The definition that survives contact with reality
Prompt injection is a class of attack in which untrusted text reaches a language model that also holds trusted instructions, and the model follows the untrusted text. Two conditions have to hold at the same time. First, the application assembles instructions and data into a single context window, so the model sees both as one sequence of tokens. Second, the model's output can cause an effect: a tool call, a rendered link, a database write, an email reply, a file deletion. Remove either condition and the attack loses its point. A model that only prints text to a screen can still be embarrassed, but it cannot be weaponised.
The name is an analogy to SQL injection, and the analogy is useful right up to the point where it fails. SQL injection is solved by parameterised queries because a SQL parser can be told, with certainty, where a statement ends and a value begins. A transformer has no equivalent boundary. The system prompt, the user turn, a retrieved chunk and a tool response are all tokens in one sequence, distinguished only by position and by conventions the model learned during training. There is no escaping function whose correctness can be proven, because the thing being escaped is meaning rather than syntax.
Why the model cannot tell instructions from content
Instruction following is a learned behaviour, not an enforced property of the architecture. Post-training rewards a model for complying with text that looks like a directive, and the training distribution is full of directives. Nothing in the forward pass marks a span of tokens as trusted or untrusted. Attention computes relevance, not authority. A sentence inside a PDF that says to disregard prior instructions is, mechanically, just more text with a strong learned prior for being obeyed.
Role markers such as system, user and tool are better understood as a convention implemented by the chat template and respected because the model was trained to respect it. That convention raises the cost of an attack and is worth preserving, but it is not a security boundary. The same is true of delimiters, XML wrappers and preambles that announce the following content is data. All of them shift probabilities. None of them create a channel the model is incapable of crossing, which is why hardening a system prompt is a mitigation and never a fix.
Direct injection: the user is the attacker
In direct injection the person typing is the attacker. They are trying to get the assistant to abandon its instructions: to reveal its system prompt, to honour a discount it should not honour, to endorse a refund policy the operator never agreed to, or to produce content the deployment is meant to refuse. The severity depends entirely on what the session can do. In a plain chat product with no tools, no secrets and no write access, the worst case is usually reputational, and it overlaps heavily with jailbreaking.
Direct injection is worth separating from the indirect case because the controls differ. The attacker is authenticated, attributable and rate-limitable. Abuse detection has an account to suspend, and a per-tenant anomaly signal has something to key on. It is also the case most vendors test, which creates a false sense of coverage: a model that resists a chat-box override may fold when the same sentence arrives inside a retrieved support ticket.
Indirect injection: the attacker is never in the chat
Indirect injection is the class that matters for anything connected to real data. The attacker plants text somewhere the model will later read and never speaks to the model at all. The carriers are ordinary business artefacts: a web page an agent browses, a PDF in a shared drive, an email in a monitored inbox, a comment on a pull request, a calendar invitation, a filename, alt text in an image, a row in a database, a code comment, or the description field of a tool exposed through a protocol such as MCP.
This is where the economics turn against the defender. A summarisation agent that processes five hundred emails a day gives an attacker five hundred attempts, and only one has to work. Defence has to succeed on every document; the attack has to succeed once. That asymmetry, not the cleverness of any single payload, is why prompt injection has stayed unsolved while other injection classes were engineered out of existence.
Tool output is the most underrated carrier. If the agent calls a search API, a scraper, a ticketing system or a third-party enrichment service, the response body is attacker-influenced in most real deployments. A tool result that reads as an approval from the finance system is indistinguishable from a real approval unless the application verifies it out of band. The model has no way to know that the string arrived over a channel the attacker controls, because the channel is not represented in the token stream.
What attackers actually try to achieve
- Instruction override: suppress the operator's rules and substitute the attacker's goal, usually as a precondition for everything else.
- Data exfiltration: encode secrets or conversation history into a Markdown image URL, a clicked link, or a tool call to an external endpoint the attacker watches.
- Tool misuse: chain legitimate functions into an unintended sequence, such as reading a private document and then attaching it to an outbound message.
- Persistence: write the attacker's text into long-term memory, a user profile, or a saved preference so it is re-read in every future session.
- Cross-tenant retrieval: craft text that makes the retriever surface another customer's chunk in a shared index with weak metadata filtering.
- Output handling: make the model emit HTML or Markdown that the front end renders, turning the assistant into a stored cross-site scripting vector.
- Denial of wallet: force recursive tool loops, maximum-length generations or repeated retries until the inference budget is exhausted.
- Reputational damage: get the assistant to state something actionable about pricing or legal obligations that the operator must then honour or retract.
Why filters and prompt hardening are not enough
Input classifiers are worth deploying and they do raise the cost of attack, but they cannot be the control that lets you skip privilege separation. The space of text that can be read as an instruction is unbounded. Any sentence can be paraphrased, translated, split across turns, or encoded with base64, homoglyphs, unusual whitespace or a substitution cipher without changing what the model understands. Detection benchmarks consistently degrade under paraphrase and multilingual variants, and every degradation is a bypass that costs the attacker nothing.
False positives are a real cost, not a hypothetical one. A filter tuned to block instruction-like language will block the HR policy document that legitimately discusses instructions, the security runbook that quotes an attack, and the contract that defines a procedure. Teams respond by loosening thresholds, and the loosened threshold is what ships.
A classifier is also a model: it adds latency, it can be fooled, and if it consumes the same untrusted text it has its own injection surface. Treat filtering as one signal in a stack, useful for catching known campaigns and generating alerts, never as the boundary between an attacker and a privileged action.
The mental model: an untrusted interpreter holding a credential
The closest historical analogy is the browser. Browsers execute code written by strangers on every page load, and the security model was never detection of malicious JavaScript. It is the same-origin policy, a sandboxed renderer, content security policy and permission prompts. The browser assumes the code is hostile and constrains what hostility can accomplish. Language model applications in 2026 are roughly where browsers were in 1995: executing everything with ambient authority and hoping the content is friendly.
The design rule that follows is simple to state and hard to implement. Assume the model will be fully controlled by an attacker at some point, and ask what it can do in that state. Every privilege the model holds is a privilege the attacker holds. You are not trying to drive the probability of compromise to zero, because that is not available. You are trying to make the compromise uninteresting.
Controls that reduce risk in practice
- Least privilege per tool, not per session: issue a credential for the specific action and tenant, with a short lifetime, and never let the model hold a broad key it can spend elsewhere.
- Typed tool schemas with server-side validation: the model proposes arguments, deterministic code checks types, ranges, ownership and business rules before anything executes.
- Egress allowlists on tool sandboxes: deny arbitrary outbound network access, and block link-local metadata addresses such as 169.254.169.254 so a fetch tool cannot reach cloud credentials.
- Two-phase confirmation for irreversible actions: show a summary rendered by code from the structured proposal, not by the model, and require a human or a policy engine to approve it.
- Provenance labelling: wrap retrieved content in explicit delimiters that name its origin, strip or neutralise instruction-like spans where the format allows, and keep the label attached through the whole pipeline.
- Quarantine pattern: let a low-privilege model read untrusted text and return only structured fields, so the privileged model never sees raw attacker-controlled prose.
- Policy enforcement outside the model: evaluate every proposed action against rules in a decision engine such as OPA or Cedar, so authorisation does not depend on the model's judgement.
- Secrets brokered at execution time: keep tokens out of the context window entirely, and inject them only into the tool process that needs them, after authorisation.
- Output encoding at every sink: sanitise Markdown, disallow raw HTML, apply a content security policy, and never render model output as trusted markup.
- Full trace logging with provenance: record which document or tool produced each instruction-shaped span, and alert on anomalous call sequences rather than on individual prompts.
A reference architecture for a defensible agent
A workable shape has six parts. An ingress layer authenticates the user and binds a tenant identifier. A retriever queries only within that tenant's namespace and returns chunks with provenance metadata. A prompt assembler places trusted instructions first and wraps every untrusted span in labelled delimiters. The model produces a structured proposal, not an action. A policy decision point evaluates the proposal against static rules and the caller's entitlements. A tool broker executes approved calls inside a sandbox with a narrowly scoped credential, and writes an audit record.
The property that matters is that the model never holds authority. It proposes; code disposes. Everything that changes state is authorised by a component that reads the model's output as data and cannot be persuaded by it. The broker has network access and secrets; the model process has neither. If the model is fully compromised, the attacker gains the ability to submit proposals, and the proposals are exactly as powerful as the policy allows, which is a number you chose in advance.
This costs engineering time and adds latency. It is the same trade-off as putting authorisation in a service layer instead of trusting the client, and it is worth making for the same reason: the alternative is a system whose security depends on the good behaviour of an adversary-controlled component.
Testing: how you know whether any of it works
Build a corpus rather than a payload list. It should contain benign documents of every type you actually ingest, direct attempts, indirect attempts embedded in realistic artefacts, and multi-turn escalations where a harmless first turn sets up a harmful third. Then measure two numbers, always together: attack success rate on the malicious set and task success rate on the benign set. A defence that blocks everything scores perfectly on the first metric and is worthless, which is why single-number security claims should be ignored.
Published benchmarks give a floor, not a verdict. AgentDojo covers agentic injection against tool-using assistants, InjecAgent targets indirect injection through tool outputs, and the prompt-injection suites in garak and PyRIT cover a broad pattern library. They tell you whether you are worse than a baseline, not whether your refund tool is safe, because that depends on your policy and your data model.
Run the suite in continuous integration. Every new tool, data source, model version or prompt change reruns it, and results are tracked per tool and per source so regressions have an owner. In production, plant canary strings in documents that should never appear in output, alert on any egress to a domain outside the allowlist, and monitor for tool-call sequences that no legitimate workflow produces.
Residual risk and the trade-offs worth naming
There is no patch for prompt injection, and any product claiming to be injection-proof is either defining the problem down or selling a filter. The realistic goal is bounded impact: an attacker who fully controls the model can waste tokens, produce wrong answers, and annoy users, but cannot move money, read another tenant's data, or reach the open internet. That is a security property you can test and document, and it is a far stronger claim than a detection rate.
The trade-offs should be chosen per action rather than applied uniformly. Confirmation prompts cut the value of automation. Spotlighting and provenance labels cost tokens and can hurt quality on long documents. The quarantine pattern adds latency and loses nuance. Egress allowlists break tools that need arbitrary URLs. Strict per-action scoping multiplies integration work. Sort tools by reversibility and blast radius, apply the heavy controls to irreversible actions, and accept more residual risk on read-only ones.
For governance, the major frameworks already treat this as the top LLM risk: OWASP lists prompt injection first in its LLM Top 10, MITRE ATLAS catalogues the technique against real systems, and NIST's generative AI profile calls for adversarial testing. The defensible position for an enterprise is a documented control set, a measured attack success rate, and a rehearsed incident response, not a claim of immunity.
Key points
- Prompt injection is a data-flow problem: trusted instructions and untrusted content share one channel, and the model has no architectural way to separate them.
- Indirect injection through documents, tool outputs and web content is the variant that scales, because the attacker only needs one success among thousands of documents.
- Input filters and system-prompt hardening raise cost but cannot serve as the boundary in front of a privileged action.
- Design as if the model is already compromised: propose rather than act, authorise outside the model, and scope every credential to one action.
- Measure attack success and task success together, run the suite in CI, and track results per tool and per data source.
- Aim for bounded blast radius, not immunity, and say so plainly in your security documentation.