Attack pattern

RAG Prompt Injection

How indirect prompt injection travels through RAG ingestion, retrieval and context assembly, and how provenance, permission-aware retrieval and independent authorization contain its impact.

By Norbert HofmannPublished: 2026-09-20Last reviewed: 2026-09-20Level: IntermediateAudience: Security Engineers, Developers, AI Engineers
Variant
Indirect
Vector
RAG / Retrieved Content
Targets
LLM, RAG System, AI Agent, Tool
OWASP
LLM01:2026 / LLM09:2026
Table of contents

What Is RAG Prompt Injection?

RAG prompt injection is indirect prompt injection delivered through content that a Retrieval-Augmented Generation pipeline retrieves into model context. The attacker controls or influences a source before a victim asks a legitimate question. A connector ingests the source, retrieval selects part of it, and context assembly places that material beside the application's instructions and the user's task. The attacker does not need direct access to the victim application.

RAG can improve grounding and relevance, but it is not a security boundary. Parsing, chunking, embedding and retrieval do not neutralize the semantic force of instruction-like language. Microsoft's current retrieval-hygiene guidance treats prompts, documents, retrieved chunks, tool results and memory writes as untrusted input. A trusted retriever can return untrusted content, just as a trusted browser can fetch an untrusted page. Source trust, instruction authority, data confidentiality and action authorization remain separate decisions.

Model influence is not automatically a vulnerability. If retrieved text changes wording, emphasis or the model's proposed plan, influence occurred. Security impact additionally requires a data or capability path and a missing, overbroad or failed application control. A sound design assumes influence may occur and prevents retrieved content from granting itself access, authority or an external side effect. For the underlying architecture and why relevance is not trust, see RAG and Retrieval.

RAG Prompt Injection and Knowledge Poisoning

RAG prompt injection, knowledge poisoning and vector-system weaknesses can coexist, but they name different mechanisms. Using them as synonyms hides which boundary failed and which control is needed.

Related but distinct RAG attack classes
ClassPrimary mechanismSecurity question
RAG prompt injectionRetrieved content carries instruction-like signals that alter task interpretation, planning or behaviorDid externally derived language influence the model, and could that influence cross a protected boundary?
Knowledge or corpus poisoningThe knowledge base is changed so retrieval returns false, biased or attacker-selected informationWas knowledge integrity corrupted, even without instruction-like content?
Vector or embedding weaknessGeneration, storage, metadata, access or retrieval of vector data failsCould unauthorized access, leakage, cross-tenant mixing or retrieval manipulation occur?

A single artifact can combine all three. A contributor might place false claims and instruction-like text in a document whose metadata also grants it excessive reach. The incident still needs separate findings for corpus integrity, prompt influence and access control. PoisonedRAG is discussed in research as knowledge corruption: its results should not be relabelled automatically as prompt injection merely because the affected application uses RAG.

The Poisoned Knowledge Base lab isolates corpus integrity from prompt injection: a controlled simulation in which false or unverified knowledge needs no instruction-like text, and provenance, source-of-truth designation and approval state decide what an answer may rely on.

The End-to-End RAG Pipeline and Trust Boundaries

RAG prompt injection delivery chain
UntrustedSource / Contributor
SystemIngestion Connector
SystemParse / Normalize
Variable trustChunks / Metadata
SystemEmbedding / Index
Variable trustCandidate Retrieval
SystemSecurity Trimming
Variable trustRank / Assemble Context
Variable trustLLM Proposal
SystemApplication Controls / Effect

Each component may be trusted system infrastructure while the source content it carries remains untrusted. The connector can authenticate correctly, the parser can behave exactly as implemented, and the index can return mathematically relevant results without giving any retrieved sentence instruction authority. Trusted infrastructure does not transfer trust to its output.

Trust and authorization metadata must survive every transformation. Source, contributor, tenant, document version, access label and chunk lineage cannot disappear when text becomes tokens or vectors. Security trimming belongs before model-visible context is built. Ranking then orders only candidates already authorized for the initiating principal. After generation, the response remains a proposal until application policy authorizes any disclosure, retrieval, write, tool call or destination.

RAG Attack Success Chain

Attacker-oriented chain from source influence to desired effect
UntrustedInfluence Source
Variable trustReach Corpus
SystemSurvive Transformation
Variable trustCompete for Queries
SystemCandidate Retrieval
SystemPass Authorization
Variable trustSurvive Reranking / Limits
Variable trustEnter Model Context
Variable trustInfluence Model / Plan
SystemReach Data / Capabilities
SystemCross Application Control
Variable trustAttacker-Desired Effect

From an offensive perspective, each stage is a separate problem. An assessor must identify a source they can influence, establish that its content reaches the corpus, determine whether it survives parsing, chunking and indexing, and test whether it remains competitive for realistic victim queries. Even then, the item must enter the candidate set, pass legitimate authorization, survive reranking and context limits, become model-visible, influence behavior, reach a data or capability path, cross an application control and produce the intended effect.

A complete end-to-end security impact requires every stage. The three core success conditions remain distinct: first, placement and corpus reachability; second, retrieval reachability under realistic queries; and third, model or action influence after retrieval. Success at an early gate is not evidence that a later gate is exploitable. Corpus presence does not prove retrieval, retrieval does not prove influence, influence does not prove policy bypass, and policy bypass does not by itself prove a security-relevant side effect.

Controls can break the chain at several points: restrict writers and connectors, preserve authorization during indexing, security-trim candidates, minimize context, detect suspicious influence, constrain capabilities, validate destinations and deny unauthorized effects. Model influence remains distinct from security impact. An influenced answer or proposal warrants investigation, but it becomes an end-to-end vulnerability only when the surrounding system permits a protected boundary to be crossed.

Ingestion-Time vs. Query-Time Exposure

01
StageIngestion writers

Who may add, edit, synchronize or delete sources, and whether connector identity is narrower than broad repository access.

02
StageTransformation lineage

Which parser, normalizer and chunker ran, what source version they processed, and whether trusted metadata stayed outside editable content.

03
StageIndex creation

Which embedding model, collection, namespace and index generation contain the artifact, with ownership and authorization labels attached.

04
StageQuery identity

Which principal and tenant initiated the request, including the task scope that retrieval and later actions must inherit.

05
StageRetrieval scope

Which collections, resources and fields are eligible after permission filtering, including any query rewrite or expansion.

06
StageSelection and assembly

Which candidates, top-k settings and reranker produced the exact chunks shown to the model, and in what order.

07
StageModel and action controls

What the model proposed, which additional retrieval or tool calls followed, and which independent policy allowed or denied them.

A poisoned document sitting in a corpus is not yet a successful prompt injection. It must be reachable for a request, survive authorization, be selected, enter model-visible context and influence behavior. Security teams need both ingestion-time and query-time evidence because fixing only one stage leaves the other path unexplained.

What Actually Becomes Model-Visible

01
Context materialDocument text and chunks

Selected passages, including neighboring or overlapping chunks assembled around a retrieval hit.

02
Context materialTitles and headings

Document titles, section headings and hierarchy retained by parsing or added during context assembly.

03
Context materialModel-exposed metadata

Only metadata fields deliberately rendered into context, such as author, date, repository or classification labels.

04
Context materialExtracted tables

Rows, cells, captions or normalized text reconstructed from tabular source material.

05
Context materialOCR and vision-derived material

Recognized text or other rendered representations from images and scans where the product supports those modalities.

06
Context materialCitations and source labels

Source names, identifiers, links or citation markers presented alongside retrieved passages.

07
Context materialGenerated summaries

Ingestion-time summaries, retrieval-time compression and other derived text that may combine multiple sources.

08
Context materialSearch snippets

Result titles and excerpts returned by lexical, semantic or hybrid search stages.

09
Context materialTool-derived results

Text or structured values returned by retrieval tools, connectors or follow-up lookups and rendered for the model.

10
Context materialAssembled context

Ordered combinations of selected chunks, overlaps, neighboring passages, labels and application framing.

In ordinary RAG designs, the LLM generally does not "execute an embedding." Embeddings or other vector representations influence candidate selection and ranking, while the model normally receives selected text or another reconstructed or rendered representation. Implementations differ: multimodal systems, learned retrievers and provider-specific context formats may expose different representations, so investigators must establish the exact runtime path rather than assume one universal design.

Transforming content into an embedding does not sanitize semantic instructions in material later presented to the model. If retrieval selects a source and context assembly reconstructs its text, summary, table, OCR output or neighboring passage, instruction-like meaning can remain model-visible even though vector operations helped choose it.

The Retrieval Barrier: Reachability Before Influence

Stored content matters to a particular request only if retrieval selects it. Reachability is therefore a distinct stage in the attack-success chain: corpus presence, query eligibility, candidate selection, ranking, context inclusion and model influence are not one event. The USENIX Security 2026 work Overcoming the Retrieval Barrier studies this end-to-end distinction in deployed-style LLM systems.

Defensive testing must not force a synthetic chunk into context and then report the result as practical RAG compromise. That experiment measures influence after retrieval. It does not measure whether ordinary queries would retrieve the artifact. Report retrieval hit rate separately, then measure influence conditional on retrieval, and finally measure the end-to-end combination.

This page intentionally does not reproduce techniques for optimizing retrieval triggers. It explains the barrier, its offensive significance, and how to measure it for both authorized assessment and defense, while implementation-level optimization details remain in the cited research.

Offensive Perspective: Winning Retrieval

For an authorized offensive assessment, placement alone is insufficient. An attacker-influenced item competes with legitimate corpus material for the queries people actually issue. Its path is shaped by embedding similarity, corpus density, chunk boundaries and other transformations, query rewriting, candidate count, metadata filters, security trimming, reranking, context-window limits and any later context selector. The assessment therefore asks not merely whether content can be stored, but whether it can traverse each independent gate under a realistic identity, task and query distribution.

Attack-oriented retrieval path
UntrustedCorpus Placement
Variable trustQuery Distribution
SystemCandidate Retrieval
SystemSecurity Trimming
SystemReranking
Variable trustSelected Context
SystemLLM
SystemCapability / Action Path

A high-relevance item can still be denied by authorization. An authorized item can fail to enter the candidate set or selected context. A retrieved item can fail to influence the model, and an influenced proposal can still be contained by application policy. These are separate exploitability gates: poisoned content exists ≠ retrieved ≠ model influenced ≠ policy bypassed ≠ security impact.

01
ConstraintOther corpus documents

Legitimate and duplicate material competes for finite candidate and context positions.

02
ConstraintChunk boundaries and transformations

Parsing, splitting, overlap, summarization and normalization may preserve, separate or omit relevant semantics.

03
ConstraintEmbedding and candidate retrieval

Retriever behavior determines whether the item enters the candidate set; it does not establish trust or permission.

04
ConstraintQuery rewriting

Expansion or reformulation changes retrieval competition but must not expand authorization scope.

05
ConstraintACL and security trimming

This is an authorization gate, not a ranking factor, and it should remove ineligible material before context assembly.

06
ConstraintReranking

Ordering can promote or demote already-authorized candidates but cannot grant authority.

07
ConstraintContext limits

Token budgets, deduplication and later selection can exclude a retrieved candidate from model-visible context.

08
ConstraintTask and policy constraints

After retrieval, task scope, data policy and action authorization can still contain model influence.

Offensive Review Questions

This Red Team framework separates evidence for each gate without prescribing an exploit sequence. Assessments should use authorized identities, synthetic protected data and bounded capabilities, then record what was possible and what was contained.

01
Assessment questionSource influence

What source, record or field can the attacker influence, and under which identity?

02
Assessment questionCorpus entry

How does it enter the corpus or retrieval path, and which transformations must it survive?

03
Assessment questionQuery relevance

Which likely user queries could make it relevant, and what legitimate documents compete with it?

04
Assessment questionPre-context authorization

Which identity, tenant, ACL and security-trimming checks occur before context assembly?

05
Assessment questionModel-visible data

Which synthetic secrets, privileged data or sensitive task state would be present if the item were selected?

06
Assessment questionDownstream reach

Which tools, actions, follow-up retrievals or external destinations become reachable after model influence?

07
Assessment questionContainment gate

Which application-side policy can still reject the proposal or prevent a side effect?

08
Assessment questionStage evidence

What telemetry proves placement, retrieval, influence, authorization outcome and effect separately?

Retrieval Relevance Is Not Trust

Independent RAG decisions
DimensionQuestionWhat does not answer it
RelevanceDoes this item help answer the query?Source reputation or access permission
Authenticity and provenanceWhere did it come from and what transformed it?A high similarity score
Integrity and write controlWho could change this source or metadata?Presence in an internal index
Instruction authorityMay this content direct the workflow?Retrieval, ranking or citation
User and tenant authorizationMay this principal receive this resource?The model's request for it
Data confidentialityWhich data may enter context or leave it?Answer quality
Action authorizationMay this exact action occur on this resource and destination?The model's confidence

Repeated retrieval may increase model salience but never increases authority. A cited statement may be traceable and still false, malicious or unauthorized. Treat these dimensions as separate fields and decisions, not as one blended trust score.

The Retrieval Relevance vs Trust lab practices separating retrieval evidence from source authority and security evidence: a controlled simulation in which rank, similarity and citations order candidates, while provenance, version state, access and purpose-specific source-of-truth rules decide what an answer may rely on.

Provenance Through Parsing, Chunking, Embeddings and Indexes

A defensible lineage record starts with stable source, document and version identifiers; source URI or repository location; ingestion principal and connector; tenant and owner; authoritative ACL or security label; and ingestion time. Derived records add parser and transformation versions, chunk identifier and source offsets, embedding model and index generation, collection or namespace, and lineage for summaries, caches, index and embedding artifacts, merged passages and synthetic chunks. Microsoft's retrieval-hygiene guidance likewise places source provenance, permission-aware indexing and validation on every read and write at the center of secure retrieval.

Keep authoritative metadata outside attacker-editable text fields. A document sentence that says it is public, approved or owned by another tenant is content, not policy. Derived chunks inherit policy metadata from an authoritative control plane, and inconsistencies are handled according to fail-closed application policy rather than resolved by the model.

Chunking creates a subtle semantic risk. A split can detach a paragraph from its heading, warning, source identity or access label. Overlap can repeat an instruction-like span and raise its salience. Summarization can rephrase externally supplied language as an apparently internal conclusion. Embeddings and reindexing transform representation, but they do not sanitize semantic instructions. Every derived artifact therefore needs a route back to the original span and the exact transformation chain.

Authorization and Security Trimming

Authorization belongs before protected content enters model context. Filtering after generation is too late for data the model should never have seen and cannot reliably undo leakage into answers, logs, caches or later planning. The control objective is to enforce initiating principal, tenant and current resource permissions during candidate eligibility and context assembly.

Principal and tenantTrusted

Established by the application session and propagated to retrieval, never inferred from query text.

Document and chunk ACLTrusted

Authoritative policy metadata attached to every derived record; field or chunk controls are used where document-level access is insufficient.

Missing or conflicting metadataUntrusted

Security trimming fails closed according to application policy rather than allowing the model or reranker to decide.

Rewritten queryVariable trust

May improve recall but cannot expand the principal's collections, tenant, resources or fields.

Reranking after authorization
Variable trustAuthorized Candidates
SystemReranker
Variable trustOrdered Candidates

The reranker is processing infrastructure, not a trusted source of content or authority. It orders candidates that should already be authorized and cannot repair unauthorized candidates admitted earlier.

Revocation must reach indexes, caches and derived chunks, not only the source system. Cross-tenant retrieval must be structurally prevented. A model-generated follow-up query creates no permission, and every retrieval round reuses current identity and policy. Products may implement this objective differently, but none can delegate the decision to semantic relevance.

Multi-Tenant and Cross-User Exposure

01
Failure classShared index namespaces

Shared collections expose candidates across tenants when logical partitioning is absent, misapplied or treated as authorization.

02
Failure classMissing or stale tenant filters

A retrieval round omits current tenant or user scope, or continues using filters that no longer match policy.

03
Failure classLost ACL and security labels

Chunking, summarization, embedding or reindexing produces derived records without authoritative access metadata.

04
Failure classIncorrectly scoped cache keys

Cached queries, candidate sets, snippets or answers are reused without binding tenant, user and authorization state.

05
Failure classMixed-authority derived artifacts

Summaries, merged passages or memories combine inputs with different permissions and later appear under one weaker label.

06
Failure classOverbroad service identity

Retrieval runs with connector or service access broader than the initiating user's effective permission.

07
Failure classStale artifacts after revocation

Chunks, indexes, caches or summaries remain reachable after source access has been removed.

The stronger design propagates user and tenant identity plus current authorization into every retrieval round, including query rewrites and model-requested follow-ups. Where practical, retrieval and service credentials are scoped, short-lived and task-bound rather than ambient. Candidate admission is evaluated against the initiating principal, not merely against what a shared service account can read.

Cache keys, index partitions, namespaces and derived-artifact labels preserve tenant and authorization scope. Shared infrastructure can be efficient and safe, but shared storage or compute must never imply shared authorization. Permission changes must invalidate or rebuild every affected derivative before it can become model-visible again.

Corpus privacy and tenant isolation answer who may retrieve which data. Prompt-injection robustness answers how the system handles instruction-like content after authorized retrieval. A private corpus can still contain attacker-influenced material, while strong injection defenses cannot compensate for cross-tenant access. Test and report these properties separately.

Chunking, Context Assembly and Derived Artifacts

Context assembly is a security-sensitive transformation, not formatting. Chunk boundaries decide which qualifiers survive. Overlap and deduplication decide what repeats. Canonicalization decides which duplicate becomes authoritative. Ordering decides salience. Citation mapping decides whether a user can trace a claim to the exact source span.

Ingestion-time summaries, cached retrieval results, stored answer summaries and agent memory are second-order artifacts. They can preserve influence after the original source is removed, often with weaker provenance because their text appears system-generated. Deleting a document does not necessarily delete its chunks, vectors, cache entries, summaries or copied memory. Each layer needs explicit invalidation and lineage-aware cleanup.

Citations improve traceability but do not establish trust. A citation can point accurately to a malicious, stale or unauthorized source. The application must retain source mapping for investigation while still making separate integrity, access and authority decisions.

High-Exposure RAG Architectures

01
ArchitectureEnterprise knowledge assistants

Large permission gradients and internal data make incorrect security trimming consequential even when the assistant only answers questions.

02
ArchitectureSupport and document copilots

Customer-controlled documents meet ticket, response and account context. Impact depends on available write and communication paths.

03
ArchitectureMulti-tenant SaaS knowledge bases

Shared infrastructure makes tenant scoping and namespace isolation primary controls against cross-customer retrieval.

04
ArchitectureShared wiki and search indexes

Many legitimate writers can influence a corpus. Internal location alone does not establish source trust or instruction authority.

05
ArchitectureCustomer-uploaded document RAG

Untrusted ingestion is an intended feature, so writer controls, quarantine and per-document provenance are central.

06
ArchitectureCode and repository RAG

Comments, issues and documentation become model-visible beside proprietary code and development tools.

07
ArchitectureEmail and archive RAG

Quoted external text and attachments persist in a searchable historical corpus and can reach users far from the original exchange.

08
ArchitectureAgentic RAG

Retrieved content can influence further retrieval, tool choice, writes and external communication, adding capability paths beyond answer text.

None of these architectures is inherently vulnerable. Exposure is the product of source control, reachability, model-visible data and available capabilities, minus the deterministic controls that separate them.

Worked Example: Shared Knowledge Assistant

01Legitimate task

An employee asks a shared knowledge assistant for the current internal procedure for handling a routine customer request.

02Retrieved source

A contributor-controlled document was previously ingested and chunked. One attacker-influenced chunk is selected beside legitimate policy sources.

03Model influence

The answer incorporates the legitimate procedure but also proposes an unrelated follow-up retrieval and an external action that were not part of the user's task.

04Retrieval boundary

Permission-aware retrieval has already excluded restricted documents, so the model never receives resources the employee may not access.

05Action boundary

Independent policy rejects the unrelated retrieval scope and destination. The model may present an answer draft, but no external action executes.

06Evidence

The task record links the proposal to retrieval event, document version, chunk, index generation, authorization decision and exact model-visible context.

Influence remains visible in the proposed answer, so the source should be investigated and contained. Security impact is nevertheless bounded: protected content outside the employee's authorization never entered context, and the unrelated action never executed. Without retrieval ACLs, restricted material could have been disclosed in the answer; without action controls, the same influence could have reached an external side effect.

Persistent and Stored RAG Injection

RAG turns a source into a family of artifacts: parsed representation, chunks, embeddings, index entries, caches, summaries and sometimes memory consumed by later sessions. Prompt-injection influence can therefore persist after the initial request and reach users who never encountered the original source.

Source removal, index rebuild, cache purge, summary cleanup and memory cleanup are different operations. Deleting only the original document may leave derived chunks in an older index generation or a model-generated summary in a cache. A clean rebuild must start from known-good sources and verified authorization metadata while preserving forensic copies and lineage.

Shared corpora enlarge blast radius, while tenant boundaries should constrain it. Investigators need to identify every user, tenant and request that received an affected artifact, including second-order summaries that carried the influence onward after the source was quarantined.

Agentic RAG and Downstream Actions

In agentic RAG, retrieved content can affect more than answer text. It can alter planning, tool choice, query expansion, follow-up retrieval, writes and external communication. That creates additional policy checkpoints, not additional authority for the model.

Risky
  1. Query
  2. Retrieve
  3. LLM Agent
  4. Tool / Action

Retrieval and model planning flow directly into capabilities, so source content can redirect execution.

Stronger
  1. Query + Principal
  2. Authorized Retrieval
  3. Provenance-Preserving Context
  4. LLM Proposal
  5. Policy / Authorization
  6. Restricted Tool or Deny

Every retrieval and action inherits current identity, scope, resource and destination policy outside the model.

Detection and Telemetry

RAG evidence across the request
  1. 01
    Task identity

    Correlation ID, initiating principal, tenant and declared task scope.

  2. 02
    Query path

    Original query and rewritten or expanded queries where policy and data-minimization rules permit logging.

  3. 03
    Source lineage

    Source, document, version and chunk IDs plus ingestion principal, connector and location.

  4. 04
    Transformation versions

    Parser, chunker, embedding model, index generation, collection and namespace used for this request.

  5. 05
    Authorization evidence

    ACL or security label, policy version and allow or deny result for each candidate admitted to context.

  6. 06
    Retrieval evidence

    Candidate set and top-k where operationally feasible, ranking and reranker scores as relevance evidence only, and the exact context presented.

  7. 07
    Response and citations

    Model proposal or answer with source mapping, without treating citation as trust.

  8. 08
    Actions and egress

    Tool proposals, policy decisions, executed actions and external destinations correlated to the same task.

  9. 09
    Derived state

    Cache hits, stored summaries and memory artifacts used or created, with lineage to their inputs.

Logs can contain sensitive queries and retrieved text, so collection needs purpose limitation, access controls, retention limits and redaction where reconstruction does not require raw content. Telemetry can correlate a source span with a changed proposal; it usually cannot prove internal model causality. Content detectors remain probabilistic signals, while authorization and execution records establish what crossed a boundary.

Prevention and Secure Architecture

  1. 01
    Control ingestion

    Authenticate writers and connectors, narrow write scopes, preserve source ownership and provide a quarantine path for suspicious material.

  2. 02
    Protect metadata

    Store provenance, tenant and ACL fields in an authoritative plane that source authors cannot rewrite through document text.

  3. 03
    Inspect without granting authority

    Use content inspection and labels as probabilistic support for routing and review, never as permission.

  4. 04
    Index with permissions

    Carry resource controls into every chunk and derived record, isolate tenants and make missing security metadata fail closed under policy.

  5. 05
    Authorize before context

    Security-trim candidates for the current principal before the model sees them, including rewritten and follow-up queries.

  6. 06
    Preserve provenance

    Keep source and transformation lineage through chunks, summaries, caches, indexes, embeddings, context assembly, citations and memory.

  7. 07
    Validate every read and write

    Apply current identity, permission and integrity checks whenever retrieval reads context or a workflow writes derived state.

  8. 08
    Minimize data and capability

    Expose only task-required context and give agents least-privileged, short-lived, task-scoped tools.

  9. 09
    Validate actions and destinations

    Authorize data, resource, action, parameters and destination outside the model; restrict egress and monitor plan drift.

  10. 10
    Design revocation and recovery

    Make permission changes, quarantine, cache invalidation and reindexing produce a known, testable state.

Human approval is appropriate for selected consequential actions, not as a universal substitute for policy. It must bind the exact operation, data, destination and side effects, and become invalid when any of them changes. The Defense Hub places these controls in a broader defense-in-depth model.

Incident Response for RAG Prompt Injection

RAG incident checklist

  • Preserve the original source and authoritative ownership, tenant, ACL and ingestion metadata.
  • Identify every document version, chunk, embedding and index generation derived from the source.
  • Locate summaries, caches, answer stores and memory that may carry second-order influence.
  • Determine when and through which connector and principal the artifact entered or changed in the corpus.
  • Query retrieval logs for affected requests, users and tenants, including rewritten and follow-up queries.
  • Correlate exact model-visible context with answers, proposals, tool calls, policy decisions and executed effects.
  • Quarantine source and derived artifacts without destroying evidence or lineage.
  • Rebuild or reindex from known-clean sources where appropriate, then invalidate stale caches and summaries.
  • Verify ACL propagation and tenant isolation after recovery before restoring automation.
  • Rotate credentials only where evidence shows exposure or misuse, and classify whether impact stopped at influence, retrieval, policy or an external side effect.

Controlled Defensive Testing

Use a synthetic, isolated corpus, index and test identities. Define expected retrieval, denial and action outcomes before each run. Vary source type and writer trust, ingestion route, chunk strategy and position, index version, semantic versus hybrid retrieval where supported, top-k and reranking, ACL and tenant boundaries, query rewriting, cache state and available tools. Do not optimize or publish retrieval-trigger strings. The RAG Prompt Injection lab is a controlled simulation of the RAG trust and authorization path - authorized retrieval, security trimming, chunk lineage, task scope and action policy - not an exploit tutorial.

Separate RAG security metrics
MetricQuestion answered
Retrieval Reachability / Hit RateHow often is the synthetic artifact selected under the defined natural test queries?
Injection Influence Rate after retrievalWhen retrieved, how often does it change answer, plan or proposal?
End-to-End Injection Success RateHow often is the artifact both retrieved and influential under the test definition?
Policy Bypass RateHow often does a prohibited influenced path pass the relevant policy?
Unauthorized Retrieval RateHow often does a principal receive a resource outside current permission?
Cross-Tenant Retrieval RateHow often does content cross the intended tenant boundary?
Unauthorized Action RateHow often does an impermissible side effect execute?
Synthetic Data Disclosure / Exfiltration Success RateHow often does synthetic protected data reach a forbidden output or destination?
Detection RecallHow many known synthetic cases are detected?
False-Positive RateHow many benign cases are incorrectly flagged?
Containment RateHow often is influence prevented from becoming an unauthorized disclosure or action?

Forcing a test chunk into context measures influence, not end-to-end RAG exposure. High influence with low unauthorized action means authorization is containing impact, but model-integrity exposure still needs reduction. Keep every metric separate so retrieval quality cannot hide access failures and strong detection cannot hide weak authorization.

Common Implementation Mistakes

Frequent RAG security errors

  • Treating an internal knowledge base as trusted by location alone.
  • Assuming chunking, embeddings or indexing sanitize instruction-like content.
  • Using similarity or reranker score as a trust decision.
  • Authorizing after the model has already seen unauthorized content.
  • Storing ACLs only in attacker-editable text or metadata.
  • Losing permissions and provenance during chunking, summarization or reindexing.
  • Leaving stale ACLs, indexes or caches after permission changes.
  • Allowing query rewriting to expand scope without reauthorization.
  • Mixing tenants through shared namespaces, filters or cache keys.
  • Granting broad ingestion access to writers or connectors.
  • Letting model-generated retrievals or tool calls create their own authority.
  • Deleting only the original source during incident response.
  • Shipping no correlation from retrieval and context to proposal, policy and action.

Standards and Research Context

Reviewed classifications

OWASP GenAI Security Project
LLM01:2026 Prompt Injection, LLM09:2026 Vector and Embedding Weaknesses
NIST
NIST AI 100-2e2025 terminology, NIST Glossary: indirect prompt injection
Research
Greshake et al. 2023, PoisonedRAG - USENIX Security 2025, Overcoming the Retrieval Barrier - USENIX Security 2026

OWASP LLM01:2026 treats retrieved documents, tool output and memory as a single untrusted token stream with no enforced trust boundary, and describes RAG corpus poisoning as a propagation path rather than a mitigation. OWASP LLM09:2026 addresses the broader class of vector and embedding weaknesses, including unauthorized access, leakage and retrieval manipulation; it is related to, but not identical with, prompt injection. NIST AI 100-2e2025 and the NIST glossary define indirect prompt injection through attacker control of a resource rather than the primary user input.

Microsoft's guidance on indirect prompt injection and least privilege supports layered defenses, limited agent authority and validation of consequential operations outside the model. Its Input, Context, and Retrieval Hygiene guidance specifically treats prompts, documents, retrieved chunks, tool results and memory writes as untrusted input, and calls for source provenance, permission-aware indexing and validation at every read and write. Greshake et al. established the broader real-world indirect-injection problem. PoisonedRAG studies knowledge corruption and is labelled accordingly here. Chang et al. show in Overcoming the Retrieval Barrier why realistic offensive analysis must treat retrieval under victim queries as a separate, measurable end-to-end stage. This article reports their study findings with configuration-specific limits and does not reproduce attack construction, token optimization, trigger generation, code or payload strings.

CaMeL and AttriGuard are relevant to the downstream boundary: they explore architectural control/data-flow separation and attribution of tool calls to trusted intent. They do not make retrieval itself an authorization system, and no research result here is presented as a universal prevention guarantee.

Frequently Asked Questions

Does RAG prevent prompt injection?

No. Retrieval can ground an answer, but retrieved content can still contain instruction-like language. Provenance, permission-aware retrieval and independent action controls remain necessary.

Is every poisoned RAG document a prompt injection?

No. Knowledge poisoning can make information false or biased without using instructions. It becomes RAG prompt injection when retrieved instruction-like content influences model behavior.

Are embeddings safe because they are vectors rather than text?

No. Embeddings change representation for retrieval; they do not sanitize semantic meaning. The retrieved text or derived representation can still influence the model.

Does a high similarity score mean a source is trusted?

No. Similarity measures relevance under a retrieval method. Trust, integrity, access permission and instruction authority require separate evidence and controls.

Should access control happen before or after retrieval?

Protected content must be excluded before model-visible context is assembled. Implementations differ, but unauthorized candidates must not become visible to the model.

Does deleting the source document remove the problem?

Not necessarily. Chunks, vectors, older index generations, caches, summaries and memory may persist. Cleanup needs lineage-aware invalidation and verified rebuilds.

Can RAG prompt injection affect other users or tenants?

Yes, if a shared corpus or derived artifact is reachable across users, or if tenant isolation fails. Correct security trimming and namespace isolation should prevent cross-tenant retrieval.

Is a citation proof that content is trustworthy?

No. It improves traceability. The cited source may still be malicious, stale, false or unauthorized.

Does reranking solve the retrieval problem?

No. Reranking can improve ordering among candidates. It cannot grant trust, repair an unauthorized candidate set or authorize actions.

References

  1. LLM01:2026 Prompt InjectionOWASP GenAI Security Project · GuidanceReviewed 2026-09-20
  2. LLM09:2026 Vector and Embedding WeaknessesOWASP GenAI Security Project · GuidanceReviewed 2026-09-20
  3. Adversarial Machine Learning: A Taxonomy and Terminology of Attacks and Mitigations, NIST AI 100-2e2025NIST · Standard · 2025-03Reviewed 2026-09-20
  4. indirect prompt injectionNIST Glossary · Technical documentationReviewed 2026-09-20
  5. Defend against indirect prompt injection attacksMicrosoft Learn · GuidanceReviewed 2026-09-20
  6. Input, Context, and Retrieval HygieneMicrosoft Learn · GuidanceReviewed 2026-09-20
  7. Least privilege for AI agents with Microsoft Entra Agent IDMicrosoft Learn · GuidanceReviewed 2026-09-20
  8. Not what you've signed up for: Compromising Real-World LLM-Integrated Applications with Indirect Prompt InjectionKai Greshake et al. · Research publication · 2023Reviewed 2026-09-20
  9. PoisonedRAG: Knowledge Corruption Attacks to Retrieval-Augmented Generation of Large Language ModelsUSENIX Association · Research publication · USENIX Security 2025Reviewed 2026-09-20
  10. Overcoming the Retrieval Barrier: Indirect Prompt Injection in the Wild for LLM SystemsHongyan Chang et al. · Research publication · USENIX Security 2026Reviewed 2026-09-20
  11. Defeating Prompt Injections by DesignEdoardo Debenedetti et al. · Research publication · 2025 preprint / IEEE SaTML 2026Reviewed 2026-09-20
  12. AttriGuard: Defeating Indirect Prompt Injection in LLM Agents via Causal Attribution of Tool InvocationsYu He et al. · Research publication · USENIX Security 2026Reviewed 2026-09-20