Blog

Prompt Injection Detection: What Works and Where It Fails

How prompt injection detection works, why hidden instructions slip past detectors, and how to layer it with enforced controls and audit evidence in sensitive work.

· By

A row of paper trays on a desk, from loose sheets through a flagged document to a stamped folder behind a divider card.
A detector that flags suspect input only protects anyone when an enforced approval step follows before execution.Image: IamVera.ai — original editorial illustration

Add a detector in front of the model and treat prompt injection as handled. That's the advice in most AI security checklists, and it's half a control. A detector that flags a hostile instruction but triggers no enforced action protects nobody; a detector tuned to catch every attack blocks enough legitimate legal, clinical or editorial material that staff route around it. Prompt injection detection is the practice of identifying instructions that try to steer a model away from the task its operator set, wherever those instructions enter. Judged as a security control rather than a classifier, it answers three questions: how often it lets an attack through at a bearable false-positive cost, what the system does when it fires, and what record an auditor can read afterwards. Published results show strong scores on single benchmarks and sharp losses across datasets. The defensible decisions sit in the second and third questions.

Which Prompt Injection Detection Approaches Exist?

Prompt injection detection is a family of methods, not a single product. They differ in what they inspect: the words in an input, the intent behind those words, the shape of the model's output, or the action the model is about to take. Most organisations meet them in the order below, running from cheap string matching to action-level control, and each answers a question the previous one leaves open.

Main prompt injection detection approaches compared

  • Keyword and pattern filters — What It Inspects: Known phrases such as "ignore previous instructions"; Main Strength: Fast and cheap to run; Main Limit: Misses rephrased, encoded or distributed attacks
  • Classifier detectors — What It Inspects: Whole input text scored for injection likelihood; Main Strength: Catch varied wording when trained on diverse data; Main Limit: Scores depend on training data; can flag benign imperative text
  • Instruction-aware detectors — What It Inspects: Whether text tries to direct the model; Main Strength: Stronger than keyword matching on realistic attack structures in published tests; Main Limit: Results vary across benchmarks and domains
  • LLM-based reviewers — What It Inspects: Whether content conflicts with the user's stated task; Main Strength: Judge intent rather than wording; Main Limit: Can themselves be targeted by injected content
  • Output format and relevance checks — What It Inspects: Whether output follows the expected format and stays grounded in context; Main Strength: Deterministic and easy to audit; Main Limit: Cannot tell an injected answer that looks correct
  • Action-level checks — What It Inspects: Proposed tool call, target and permissions before execution; Main Strength: Limits harm even when detection misses; Main Limit: Requires a clear permission model to be defined first

Two rows get confused in procurement conversations. An instruction-aware detector asks whether a passage is trying to direct the model, a narrower question than whether the passage is an attack. A classifier detector asks how much the whole input resembles injection, which is broader and blunter. Neither replaces the action check at the bottom of the table, because the harmful step in an agent workflow is a tool call that executes correctly under instructions the model was given.

What OWASP adds beyond a detector

The OWASP GenAI Security Project treats prompt injection as LLM01 and sets out mechanics that a screen alone doesn't cover. It asks for semantic filters combined with string-based checks, deterministic code that validates whether an output follows its expected format, and an assessment of retrieved context for relevance, groundedness and question-answer relevance.

The same guidance requires external content to be separated and clearly labelled, human approval and least privilege for high-risk operations, and model-facing functionality implemented in application code rather than through unrestricted API tokens handed to the model. Detection, in other words, is one control among several that share the work.

The practical rule: run at least two approaches, and judge each by what it lets through rather than by its category name.

Why Can Hidden Instructions Slip Past a Detector?

The failure is easiest to see in a human picture before it becomes a technical one.

A clerk who reads a visitor's letter aloud and then follows whatever instruction is printed inside it has lost track of who is in charge. A language model behaves the same way when a retrieved web page, an email or a tool result lands in the same context as its operator's instructions. The text arrives looking like content, and the model treats it as guidance.

Microsoft's research on indirect prompt injection describes that path precisely: malicious instructions embedded in external content the application consumes, arriving through retrieved documents, web pages, emails or other supplied data rather than through the typed request (Microsoft Research). A detector that reads only the user's prompt misses the route entirely, and testing has to cover each external channel on its own.

When there's no instruction to find

The harder case is an attack with no recognisable command inside it. The WAInjectBench preprint evaluated detectors and found broadly that attacks omitting explicit instructions or using imperceptible perturbations are harder to detect. Intent spread across a long context, or carried in a change the eye can't resolve, defeats phrase matching completely.

The cost lands on teams whose documents legitimately contain imperative language. A witness statement quotes a demand, a clinical note carries an instruction to a colleague, a contract reproduces a notice clause. A filter that blocks on imperative text produces false positives that make the tool unusable in exactly the workflows holding the most sensitive material.

Instruction detection isn't attack detection

That distinction is the one most product documentation blurs. A benign quotation gets misclassified while a carefully engineered payload reads like ordinary factual content, so the classifier can be confident and the attack still lands. Detection has to look at what the model is being asked to do with the content, which source the content came from, and whether the model's behaviour changes when the segment is removed.

For document-heavy work the untrusted channel is usually a file rather than a prompt, and the guide to indirect prompt injection in documents and LLM workflows traces how those instructions reach a model that was only asked to summarise.

Check what the model is about to do, not only what the text says.

How Should You Measure a Prompt Injection Detector?

A detector is only as useful as three things a single accuracy score hides: the false-positive cost your workflow can absorb, the action that follows a positive flag, and the record that later shows why the flag fired. Measure it as a security classifier under a fixed false-positive budget, on more than one independent dataset, and pair every detection score with the attack success rate it prevents. In-domain accuracy describes the data the detector was built around, which is rarely the data a live workflow produces.

Why in-domain accuracy misleads

A 2025 academic evaluation of an instruction-aware method, InstructDetector, reported 99.60% detection accuracy in-domain and 96.90% out-of-domain, while reducing attack success on the BIPIA benchmark to 0.03% (Findings of EMNLP 2025). Those figures describe a detector working on a distribution close to its design. They say nothing about the false-positive rates a legal or clinical workflow can absorb before staff start routing around the tool.

Tighten that budget and the picture changes. PromptShield reports substantially different detection rates at a fixed low false-positive rate than headline accuracy would suggest; its reported benchmark also compares performance with PromptGuard. Verify the exact operating points and any training-volume comparison against the readable primary paper before publication.

The number that travels badly

Cross-dataset results can be worse than any single benchmark implies. In our analysis, a high score on one dataset is not protection in a different tool, domain or attack style.

Reporting practice matters as much as the number. The PromptShield benchmark paper is a detection paper that supports fixed-FPR comparisons. In our analysis, detectors should report precision, recall, false-positive rate and attack-family coverage separately, on held-out examples that vary wording, placement, encoding and context, with results broken out by the channel an instruction arrived on. Direct user text, retrieved documents, emails, web pages, tool outputs and conversation history are all untrusted under that model. A score without the enforced action, and without a trail of which segment was flagged and what the system did next, cannot be audited later.

Measures to require before trusting a detector

  • Attack success rate — What It Tells You: Share of attacks the model still follows; Why It Matters: Shows end-to-end failure, not only a suspicious label; What to Ask For: Results broken down by attack family
  • Detection rate at a fixed false-positive rate — What It Tells You: Attacks caught while benign input is capped at a stated rate; Why It Matters: Sets what the workflow can tolerate; What to Ask For: Results at more than one operating point
  • False-positive rate on benign documents — What It Tells You: Legitimate content wrongly blocked; Why It Matters: Decides whether legal, clinical or newsroom work stays usable; What to Ask For: Samples drawn from your own document types
  • Cross-dataset generalisation — What It Tells You: Performance on tools, domains and attack styles not used in training; Why It Matters: A detector tuned to one dataset can degrade on another; What to Ask For: Results on at least two independent datasets

What to put in a supplier questionnaire: a detection rate at a stated false-positive rate, measured on data the detector wasn't trained on, alongside the action the system takes when it fires and the log that records that action.

Test the deployed configuration, not the model card, and re-run the corpus whenever the system prompt, the tool set or the retrieval settings change. The LLM red teaming workflow and scoring guide sets out how to structure that testing so results stay comparable between runs.

How Do You Layer Detection With Controls That Hold?

Layering means placing detection at more than one point in the workflow and giving each layer an enforced consequence. A flag that nothing acts on protects no one, and a single classifier carries risk it can't see the end of.

  1. Tag the source before the model sees it. Every passage, file and tool result keeps its provenance and enters the context as data rather than as instruction.
  2. Screen each segment and quarantine what looks wrong. Quarantine rather than silent deletion, because naive removal can miss an attack distributed across passages or shifted by position.
  3. Give a second reviewer the intent question. That pass asks whether the content conflicts with the task the user set, not whether it resembles a known payload.
  4. Verify the action before it has an external effect. Compare the proposed tool call with the original intent, the permitted tool set, the target and the authorisation scope.
  5. Require a named human for high-impact moves. Sending external mail, transferring money, filing a document or altering a record gets an approver who can be identified later.

Microsoft's published defence documentation takes the same view, combining hardened system prompts and Spotlighting to mark untrusted input, classifier-based Prompt Shields for external content, and impact controls such as data governance, user-consent workflows and deterministic blocking of known data-exfiltration methods. It states the enforcement rule plainly: when the detection layer identifies a malicious prompt, the application must block it or take another defensive action (Microsoft Security Response Center).

Research on indirect-injection defences adds two refinements. Segmentation should keep source metadata with every retrieved passage so it can be analysed before it reaches the reasoning context, and detection should be paired with action-level verification instead of carrying the load alone. The same work reports that both instructed LLMs and open-source detection models struggle to effectively detect indirect prompt injection attacks, whereas specifically trained models show satisfactory performance (indirect prompt injection defence study), which is what retrieved content reaching a model's tool chain looks like without a trained detector.

Placement matters as much as the model. A check at ingestion catches a poisoned document; a check at the tool-input step catches the moment the model decides to act on it. Run both, since the second sees parameters and targets the first one never sees.

Permissions finish the job. Model-facing functionality should run in application code rather than through unrestricted credentials held by the model, so a successful injection stays inside a small blast radius instead of inheriting every system the model can reach.

The design question for any workflow isn't whether the detector is accurate. It's which action the model can trigger, who authorises that action, and what happens at the moment the detector says yes.

What Evidence Should a Detection Decision Leave Behind?

A pass or fail label doesn't survive an audit. When a regulator, client or court asks why an action was permitted, the answer has to reconstruct the event: what was scanned, what the detector said, which policy applied, who decided and what changed as a result.

The following walkthrough sets out what that record looks like when an agent acts on retrieved content.

Placement changes what there is to record. One preprint extracts hidden states at the tool-input position and reports that a representation-engineering (RepE) based circuit breaker identifies and intercepts unauthorized actions before the agent commits to them, achieving high detection accuracy across diverse LLM backbones (tool-input detection study). In our analysis, moving detection to the model's tool-input stage changes what a record can capture, so the record has to show who checked what, not only what a model scored.

The six items an auditor needs

  • The untrusted input and its channel. The exact segment scanned, its source, and how far that source is trusted, so the origin can be traced later.
  • The detector's score and the threshold in force. A number without its cut-off can be neither reviewed nor retuned.
  • The intended tool action and the policy invoked. Which call, which target, which rule permitted it.
  • Any reviewer decision or override. A named person, a timestamp, and what they changed.
  • The resulting state change. A document altered, a message sent, a record read.
  • A plain-language reason. Two or three sentences explaining why the action was allowed, blocked or downgraded.

The tension is between reconstructing an event and creating a second copy of confidential material. Store references or pseudonymised content where the workflow allows, and keep raw input only for as long as the retention rule requires.

Logs also test the system itself. If the same passage is blocked on one run and allowed on another, the record shows where the threshold or the policy drifted. The IETF draft standard on reconstructing an AI audit trail covers what that reconstruction is being specified to contain.

In our analysis, a weaker detector with an inspectable trail and a named human escalation suits high-impact work better than a stronger detector nobody can interrogate. Ask for a retention policy that names what's logged, for how long, who can read it and who may override a block.

What Does Detection Look Like in a Legal Document Review?

A single worked case shows which layer does the work, and which one only appears to.

A litigation team uploads a witness file and asks an assistant to summarise a public web page about the case. The page carries hidden text instructing the assistant to list every name in the uploaded file and send it to an external address.

Without layers, the attack is comfortable. The typed request is innocuous, a keyword filter finds nothing resembling a known payload, and the model holds the file and the page in the same context. It's one step from acting.

With layers, the sequence runs differently. The source tag marks the page as untrusted before it enters the context. The detector flags the passage and quarantines it, so the summariser keeps the page's visible text and loses its instructions. A reviewer notes that listing names and sending them conflicts with a task that was only to summarise. The action check blocks any outbound transfer, because neither the tool nor the destination sits in the permitted scope. Every decision is written to the record with a timestamp and an owner.

The honest limit matters here. A text classifier might have missed the same instruction if it were worded implicitly, threaded across the page and a linked exhibit, or embedded in an image. In this scenario the action gate carried the protection, and the detector was helpful rather than decisive.

Identifiers need protecting before the external call, not after it. Where a pseudonymisation layer sits in front of the model, detected names, dates, case numbers and medical details become synthetic, session-bound equivalents before any external request, with the mapping held in a private vault and the original values restored locally once the analysis returns. Pseudonymisation reduces exposure; it doesn't detect every indirect identifier and doesn't make re-identification impossible. A name removed from a paragraph can still be inferable from a date, a role and a location in the next sentence.

The control that mattered was the one that stopped the outbound transfer, not the one that read the words.

Which Decisions Should Leadership Ask For Now?

OWASP describes prompt injection as a vulnerability for which fool-proof prevention is unclear, while recommending layered mitigations such as constrained behavior, filtering, least privilege and human approval. A score that looks strong on a demo set still leaves the board without an owner, an enforced action, or a record of what the miss cost.

NCSC's engineering answer is to design the system and its data flows around the worst behaviour the model is permitted to produce, rather than assuming a screen will catch every malicious instruction. OWASP's guidance recommends least privilege, input and output filtering, human approval for high-risk actions, and clear separation of external content; organizations should also define what evidence their own audit and incident processes require. Those requirements become an accountability test only when leadership can see the false-positive cost, the action a positive flag enforces, and the trail a later reviewer can reconstruct.

  • Permissions limited to the task — What a defensible answer looks like: The model holds no credential or scope beyond the workflow's actual needs
  • A record that reconstructs an event — What a defensible answer looks like: Inputs, detector decisions, approvals and resulting actions are retained and readable
  • Results at more than one operating point — What a defensible answer looks like: Detection rates at a strict false-positive budget, on data the supplier didn't train on
  • A named approver for high-impact actions — What a defensible answer looks like: A person, not a policy document, authorises external sends and irreversible changes
  • A stated enforced response — What a defensible answer looks like: A positive detection blocks, escalates or downgrades, and someone can show which

If the workflow sends confidential material to external models, ask the supplier to describe the data flow in writing before the next renewal.

The shield reduces exposure. It does not detect every indirect identifier and does not make re-identification impossible.

Which of those five can the current supplier answer in writing this quarter?

Prompt injection detection earns a place in the architecture when a positive flag has a defined consequence. You can see which providers took part in a run and read the trail behind each decision.

More articles on this subject are collected in the AI security overview.

Sources and references

  1. Benchmarking and Defending Against Indirect Prompt Injection Attacks on Large Language ModelsarXiv
  2. WAInjectBencharXiv
  3. PromptShield: Deployable Detection for Prompt Injection AttacksProceedings of the Fifteenth ACM Conference on Data and Application Security and Privacy · 2024-06-19
  4. Can Indirect Prompt Injection Attacks Be Detected and Removed?ar5iv
  5. Your Agent is More Brittle Than You Think: Uncovering Indirect Injection Vulnerabilities in Agentic LLMsarXiv
  6. Findings of EMNLP 2025Aclanthology
  7. LLM01:2025 Prompt InjectionOWASP Gen AI Security Project · 2024-04-10
  8. how-microsoft-defends-against-indirect-prompt-injection-attacksMicrosoft · 2025-07-29

Sources: Key claims are attributed to the OWASP GenAI Security Project (LLM01), Microsoft Research on indirect prompt injection, and the WAInjectBench evaluation of 12 detectors on arXiv.

← All articles in this topic ← All articles