RAG Security: Prompt Injection, Data Poisoning and Guardrails
How RAG systems get attacked through indirect prompt injection, poisoned documents and leaky vector stores, and the layered guardrails that defend them.
RAG security is the work of protecting retrieval-augmented generation systems from attacks that arrive through the content they retrieve. Because RAG pastes outside documents into a model's prompt, anyone who can get text into your knowledge base, a web page your system reads or an email it summarizes can try to steer the model. That's indirect prompt injection, one form of the prompt injection risk that tops the OWASP Top 10 for LLM Applications 2026 [3]. No single filter stops it; the reliable defences are layered: control what gets indexed, enforce access rights at retrieval time, separate data from instructions, limit what the model can do, and check what comes out.
New to the underlying pattern? Read our explainer on retrieval-augmented generation (RAG) first.
Why RAG creates a new attack surface
A RAG system does three things: it stores documents (often as embeddings in a vector database), retrieves the passages most relevant to a question, and asks a language model to answer using them. Each step can be attacked.
The root problem is that language models process instructions and data in the same stream of text. A 2023 paper that helped define the field put it this way: integrating LLMs into applications "blurs the line between data and instructions" [5]. The authors showed attackers could plant prompts in data likely to be retrieved and compromise applications remotely, without direct access to the interface, demonstrating attacks on Bing's GPT-4-powered chat and code-completion tools [5]. NIST's Generative AI Profile describes the same mechanism and notes researchers have demonstrated indirect injections that steal proprietary data or run malicious code remotely [4].
The main RAG threats
Direct vs indirect prompt injection
OWASP distinguishes two forms [1]:
- Direct injection: a user types input meant to override the system's instructions. Jailbreaking is a specific form, aimed at getting the model to ignore its safety rules [1].
- Indirect injection: the model ingests outside content, such as a web page, file or email, containing hidden instructions. The content may even be invisible to humans, as long as the model parses it [1].
RAG makes indirect injection the bigger worry, because the system is built to pull in outside text. OWASP notes that RAG and fine-tuning, though they improve accuracy, "do not fully mitigate prompt injection vulnerabilities" [1].
Knowledge-base poisoning
An attacker who can add documents to your corpus doesn't need instructions at all; false content can be enough. The PoisonedRAG study, accepted to USENIX Security 2025, found that injecting five crafted texts per target question into a knowledge database of millions of texts produced about a 90% attack success rate in pushing the model toward a chosen wrong answer [6]. The authors tested several existing defences and found them insufficient [6].
Poisoned data can come from insiders, user-submitted content, scraped sources or unverified data providers [2].
Data leakage through retrieval
The quieter risk is a system that works exactly as built but retrieves things the user shouldn't see. OWASP's 2025 guidance on vector and embedding weaknesses (LLM08 in 2025; LLM09 in the 2026 list) lists unauthorized access when access controls are inadequate or misaligned, and context leakage between users in multi-tenant systems that share a vector database [2].
Embeddings are not anonymous
Teams sometimes assume embeddings are safe to store or share because they're just numbers. Research says otherwise: a 2023 study recovered 92% of 32-token inputs exactly from their embeddings and showed it could recover personal details such as full names from clinical notes [7]. Treat embeddings with the same sensitivity as the text they came from.
Harmful output handling
If model output is rendered in a browser, passed to another system or used to build a query, injected content can travel downstream. The 2026 OWASP list includes Improper Output Handling as LLM10 [3].
When RAG becomes agentic, the stakes rise
In a plain question-answering system, a successful injection produces a bad answer. In agentic RAG, where the model can also call tools, the same injection can trigger actions. NIST's AI safety researchers call this agent hijacking [14]. The AI agent security and governance guide covers that broader picture.
Threats and defences at a glance
Threat | Where it enters | Primary defences |
|---|---|---|
Indirect prompt injection | Retrieved documents, web pages, emails, tool outputs | Separate and mark untrusted content; least privilege; human approval for actions; output checks |
Knowledge-base poisoning | Ingestion pipeline, user uploads, third-party feeds | Trusted sources only; ingestion review; provenance tracking; monitoring for anomalous content |
Unauthorized retrieval | Vector store queries | Permission-aware retrieval enforcing the end user's rights; tenant partitioning |
Embedding inversion | Stored or shared vectors | Protect embeddings like source text; encryption and access control |
Unsafe output | Model response passed to browsers or systems | Treat output as untrusted; encode, validate and constrain formats |
Jailbreaks (direct injection) | User prompts | Instruction-hierarchy-trained models; input classifiers; refusal policies |
Defence layer 1: control what gets indexed
Your knowledge base is part of your attack surface. OWASP recommends accepting data only from trusted and verified sources, checking knowledge sources for poisoning and hidden content, and reviewing combined datasets with classification tags so access levels stay enforced [2].
In practice:
- Restrict who can add or edit indexed content, and log every change.
- Track provenance: store source, author and ingestion date with every chunk so answers can be traced.
- Scan incoming documents for hidden text and unusual formatting before indexing.
- Re-review high-impact collections, such as policy documents, on a schedule.
Defence layer 2: enforce permissions at retrieval time
Retrieval must respect the end user's access rights, not the application's. OWASP recommends "permission-aware vector and embedding stores," fine-grained access controls and logical partitioning of data between groups [2]. Filter by the user's entitlements in the query itself, before results reach the model, rather than asking the model to withhold restricted content. This is the same principle as zero trust security architecture: never let a component grant access it can't verify.
OWASP also recommends detailed, immutable logs of retrieval activity so suspicious behaviour can be spotted and investigated [2].
Defence layer 3: separate instructions from data
These techniques help the model tell trusted instructions from retrieved text. None is complete on its own.
- Mark untrusted content. OWASP advises segregating and clearly identifying external content [1]. Spotlighting techniques transform input so it carries a reliable signal of its source; with GPT-family models, they cut attack success from over 50% to below 2% in the paper's experiments, with minimal impact on task performance [8].
- Structured queries. StruQ places the prompt and the data in separate channels and fine-tunes the model to follow instructions only from the prompt channel, substantially improving resistance with little loss of utility [9].
- Instruction hierarchy. Researchers trained models (GPT-3.5 in the paper) to "selectively ignore lower-privileged instructions," treating developer instructions as higher priority than user or third-party text; robustness improved substantially, including against attack types not seen in training [10].
Defence layer 4: limit what injected text can do
Assume some injections will get through, and design so they can't cause serious harm. OWASP's prompt injection guidance lists constraining model behaviour, enforcing least-privilege access and requiring human approval for high-risk actions [1].
Architectural defences take this further:
- CaMeL separates control flow from data flow. A privileged model plans using only the trusted user request; a quarantined model with no tool access processes untrusted data; and an interpreter checks security policies before each tool call [11]. On the AgentDojo benchmark it completed 77% of tasks with provable security, compared with 84% for an undefended system, though its authors stress it doesn't solve prompt injection entirely [11].
- Design patterns for agents. A June 2025 paper proposed six patterns, including plan-then-execute (fix the sequence of actions before reading untrusted data) and dual LLM (a tool-less model handles untrusted content) [12]. The shared rule: once untrusted input is in play, the system must be constrained so that input cannot "trigger any consequential actions" [12].
For RAG specifically, that often means keeping the answering model read-only and moving any actions behind a separate, gated step. See human-in-the-loop AI systems for approval design.
Defence layer 5: guardrails on inputs and outputs
"Guardrails" usually refers to checks wrapped around the model at runtime:
- Safety classifiers. Llama Guard is an LLM-based classifier, built on Llama 2 (7B), that labels both prompts and responses against a customizable risk taxonomy; its authors reported performance matching or exceeding available content moderation tools on the OpenAI Moderation Evaluation dataset and ToxicChat, and released the weights [15].
- Programmable rails. The open-source NeMo Guardrails toolkit lets developers define rules that keep conversations on approved topics, follow set dialogue paths or block harmful content, independent of the underlying model [16].
- Output validation. OWASP recommends defining and validating expected output formats and filtering inputs and outputs [1]. Require citations that point to retrieved sources, and check that they do.
Classifiers catch known patterns; they're one layer, not a perimeter. Attackers adapt, as the next section shows.
Defence layer 6: test like an attacker
OWASP recommends regular adversarial testing and attack simulations [1]. Two findings should shape how you test:
- Benchmarks exist. AgentDojo provides 97 realistic tasks and 629 security test cases for evaluating injection attacks and defences on tool-using agents [13].
- Static tests overstate safety. NIST's CAISI found a model that resisted known attacks saw success rates rise from 11% to 81% under new, tailored attacks, and that repeating attacks 25 times raised average success from 57% to 80% [14]. Test with adaptive attacks, many attempts, and per-task analysis.
Limitations: what guardrails can't do
- No complete fix exists. OWASP says "it is unclear if there are fool-proof methods of prevention" [1], and the strongest architectural defences give up some usefulness [11].
- Classifiers create false positives and negatives, blocking legitimate questions or missing novel attacks.
- Permission systems are only as good as the source data. If document permissions are wrong in SharePoint, they'll be wrong in the vector store.
- Defences add latency and cost, especially extra model calls for checking.
A practical checklist
- Inventory every source that feeds your index, and who can write to it.
- Enforce the end user's permissions in the retrieval query.
- Partition tenants; never share an unfiltered index across customers.
- Protect embeddings as sensitive data.
- Mark retrieved content as untrusted in the prompt, and prefer models trained to respect instruction priority.
- Keep the answering model read-only; gate any actions behind approval.
- Treat model output as untrusted input to every downstream system.
- Add input and output classifiers for your risk categories.
- Log retrievals, prompts and outputs for investigation.
- Red-team with adaptive, repeated attacks before launch and after major changes.
For the retrieval side of quality, see our guides to embedding models and how RAG reduces, but doesn't end, hallucinations.
Frequently asked questions
What is indirect prompt injection?
It's an attack where instructions are hidden in content an AI system reads, such as a web page, document or email, rather than typed by the user [1]. When the system retrieves that content into the model's context, the model may follow the hidden instructions. It's the main prompt injection risk for RAG systems [4][5].
Can prompt injection be fully prevented?
Not today. OWASP says it is unclear whether any fool-proof prevention method exists, and even architectural defences such as CaMeL don't solve every case [1][11]. The practical goal is to make injections hard to land and limit what they can do when they succeed.
Are vector databases a security risk?
They can be. OWASP's 2025 list names unauthorized access, cross-tenant leakage, embedding inversion and data poisoning as vector and embedding weaknesses [2]. Use permission-aware retrieval, partition data and protect embeddings like the text they represent [2][7].
What are LLM guardrails?
Runtime controls that check what goes into and comes out of a model, such as safety classifiers like Llama Guard, rule-based rails like NeMo Guardrails, and output format validation [15][16][1]. They are one defensive layer and work best combined with access control and least privilege.
Does fine-tuning or RAG protect against prompt injection?
No. OWASP notes that research shows neither fully mitigates prompt injection [1]. Training models to respect an instruction hierarchy helps [10], but you still need architectural limits on what the model can do.
Sources
- OWASP GenAI Security Project. "LLM01:2025 Prompt Injection." https://genai.owasp.org/llmrisk/llm01-prompt-injection/
- OWASP GenAI Security Project. "LLM08:2025 Vector and Embedding Weaknesses." https://genai.owasp.org/llmrisk/llm082025-vector-and-embedding-weaknesses/
- OWASP GenAI Security Project. "OWASP Top 10 for LLM Applications 2026." Published August 4, 2026. https://raw.githubusercontent.com/GenAI-Security-Project/GenAI-LLM-Top10/main/README.md
- NIST. "Artificial Intelligence Risk Management Framework: Generative Artificial Intelligence Profile" (NIST AI 600-1). July 2024. https://nvlpubs.nist.gov/nistpubs/ai/NIST.AI.600-1.pdf
- Greshake, K. et al. "Not what you've signed up for: Compromising Real-World LLM-Integrated Applications with Indirect Prompt Injection." arXiv:2302.12173, February 2023. https://arxiv.org/abs/2302.12173
- Zou, W. et al. "PoisonedRAG: Knowledge Corruption Attacks to Retrieval-Augmented Generation of Large Language Models." USENIX Security 2025. arXiv:2402.07867. https://arxiv.org/abs/2402.07867
- Morris, J. X. et al. "Text Embeddings Reveal (Almost) As Much As Text." EMNLP 2023. arXiv:2310.06816. https://arxiv.org/abs/2310.06816
- Hines, K. et al. "Defending Against Indirect Prompt Injection Attacks With Spotlighting." arXiv:2403.14720, March 2024. https://arxiv.org/abs/2403.14720
- Chen, S. et al. "StruQ: Defending Against Prompt Injection with Structured Queries." USENIX Security 2025. arXiv:2402.06363. https://arxiv.org/abs/2402.06363
- Wallace, E. et al. "The Instruction Hierarchy: Training LLMs to Prioritize Privileged Instructions." arXiv:2404.13208, April 2024. https://arxiv.org/abs/2404.13208
- Debenedetti, E. et al. "Defeating Prompt Injections by Design." arXiv:2503.18813, March 2025. https://arxiv.org/abs/2503.18813
- Beurer-Kellner, L. et al. "Design Patterns for Securing LLM Agents against Prompt Injections." arXiv:2506.08837, June 2025. https://arxiv.org/abs/2506.08837
- Debenedetti, E. et al. "AgentDojo: A Dynamic Environment to Evaluate Prompt Injection Attacks and Defenses for LLM Agents." arXiv:2406.13352, June 2024. https://arxiv.org/abs/2406.13352
- NIST CAISI. "Technical Blog: Strengthening AI Agent Hijacking Evaluations." January 17, 2025 (updated December 19, 2025). https://www.nist.gov/news-events/news/2025/01/technical-blog-strengthening-ai-agent-hijacking-evaluations
- Inan, H. et al. "Llama Guard: LLM-based Input-Output Safeguard for Human-AI Conversations." arXiv:2312.06674, December 2023. https://arxiv.org/abs/2312.06674
- Rebedea, T. et al. "NeMo Guardrails: A Toolkit for Controllable and Safe LLM Applications with Programmable Rails." EMNLP 2023 (Demo). arXiv:2310.10501. https://arxiv.org/abs/2310.10501